diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..9907ee73810fab72963d8ad409e2687608680a10 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +home/wuyifan/a7_canonical_gt_rotationfix_20260930/cache/native_inventory.json filter=lfs diff=lfs merge=lfs -text +home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json filter=lfs diff=lfs merge=lfs -text +home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/arctic_t8.jsonl filter=lfs diff=lfs merge=lfs -text +home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/hot3d_t8.jsonl filter=lfs diff=lfs merge=lfs -text +home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..956155c8d4974816723acaef9777ca663cc83249 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# EgoNet training migration metadata + +This private repository preserves the code snapshot, configuration, fixed +8-frame training manifests, SQLite sampling index, normalization statistics, +and canonical-label provenance for the H2O, ARCTIC, HOT3D, and GRAB mixed run. +Paths below `home/wuyifan/` mirror their original absolute paths on g2. + +This repository is not a complete training dataset. It does not contain source +RGB/depth/VRS recordings, rendered GRAB videos, filtered GT NPZ files, +canonical label NPZ files, personalized MANO templates, licensed MANO model +files, ViTPose visual weights, or training checkpoints. Restore those through +the appropriate authorized channels before running the training code. + +The manifests and inventory contain absolute source paths and content hashes. +Preserve the original path layout on the destination, or explicitly rebuild +the associated index, inventory, and provenance checks after changing paths. diff --git a/home/wuyifan/EgoNet_train_20261008/.gitignore b/home/wuyifan/EgoNet_train_20261008/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0e2716463c55a23a0526a37ef855c5d04e0b2986 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/.gitignore @@ -0,0 +1,36 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +.venv/ +*.egg-info/ + +.env +.env.* +*.pem +*.key +id_rsa* +id_ed25519* + +data/ +datasets/ +cache/ +checkpoints/ +runs/ +artifacts/ +third_party/ +*.pt +*.pth +*.ckpt +*.safetensors +*.npy +*.npz +*.vrs +*.mp4 +*.avi +*.png +*.jpg +*.jpeg +*.lock +*.log diff --git a/home/wuyifan/EgoNet_train_20261008/README.md b/home/wuyifan/EgoNet_train_20261008/README.md new file mode 100644 index 0000000000000000000000000000000000000000..036770cde52e60d3217143ce22429f2811a0fcf3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/README.md @@ -0,0 +1,19 @@ +# EgoNet + +EgoNet is the review snapshot of the Foundation Hand bimanual reconstruction code and its current RGB training lineage. The Python package is still named `foundation_hand` so checkpoint keys and historical imports remain recognizable. + +This repository contains model and dataset code, training/evaluation scripts, configs, tests, and the experiment-specific source used for S4, A7, U0, N0, and N1. It does **not** contain datasets, fitted label caches, MANO assets, DINO weights, model checkpoints, videos, or third-party source trees. See [REVIEW_GUIDE.md](REVIEW_GUIDE.md) for the exact lineage, review entry points, and known limitations. + +The snapshot preserves the code that produced the reported experiments. In particular, the historical N0/N1 trainer still has a teacher term and the known bf16 GT-6D precision issue; do not use it for the new B0/B1 contract. The new no-teacher, MANO-pkl-mean-pose-delta model and loss path has passed two real updates per arm, but formal training and benchmark validation have not started. + +The matched RGB non-MoT/MoT smoke configuration is in `experiments/from_scratch_mean_pose/config.json`. Both arms use mean-pose delta and normalized orthogonal GT 6D. It remains smoke-only (`training_approved=false`) and is not consumed by the historical trainer. See `docs/PIONAI_NON2D_HANDOFF_20261005.md` for the PionAI transfer and readiness status. + +Primary materials: + +- `experiments/u0_normalized6d/train.py`: N0/N1 training entry point. +- `experiments/u0_normalized6d/normalized_loss.py`: normalized direct-6D and geometry supervision. +- `src/foundation_hand/`: core architecture, data readers, MANO geometry, and losses. +- `docs/HK.md`: evaluation and hard-pose diagnostics. +- `docs/FROM_SCRATCH_MEAN_POSE_REVIEW.md`: proposed next controlled experiment, not launched. + +Python 3.11 is required by `pyproject.toml`. The original environment also requires the external packages and pinned upstream repositories listed in [THIRD_PARTY.md](THIRD_PARTY.md), plus separately provided licensed MANO assets and datasets. Several historical scripts contain host-specific absolute paths; they are retained for audit, not presented as portable launch commands. diff --git a/home/wuyifan/EgoNet_train_20261008/REVIEW_GUIDE.md b/home/wuyifan/EgoNet_train_20261008/REVIEW_GUIDE.md new file mode 100644 index 0000000000000000000000000000000000000000..3228a18853be37e96d3c7b29a8c0b09918994b92 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/REVIEW_GUIDE.md @@ -0,0 +1,40 @@ +# Code review guide + +## Scope and provenance + +The root `src/foundation_hand/`, `scripts/`, and training helper files are from the frozen `foundation_hand_clean_gt_dino_20260925/code` snapshot used by the current lineage. Missing general tests and historical configs come from the `/home/jiasen/foundation_hand` working tree; where files overlapped, the frozen training snapshot takes precedence. The original project was at commit `5d59528` before local changes. No source tree or checkpoint was modified to make this review snapshot. + +The experiment chain uses these directories, in dependency order: + +| Directory | Role | +| --- | --- | +| `experiments/clean_gt_dino` | Clean-GT data filtering and from-DINO training helpers | +| `experiments/s4_modality_experts` | RGB/K/depth expert sampling and training contracts | +| `experiments/a7_mot_residual` | MoT residual expert code | +| `experiments/a7_canonical_gt_cache` | Corrected-left MANO label migration and audits | +| `experiments/a7_rotation_fix` | Frozen A7 rotation-fix data/training scripts | +| `experiments/a7_canonical_gt_train` | Canonical GT A7 trainer and geometry validation | +| `experiments/u0_depthsafe` | U0 RGB parent model, loss, and trainer | +| `experiments/u0_normalized6d` | Matched N0/N1 direct-6D continuation trainer | +| `experiments/pose_delta_diagnostics` | Frozen-panel and hard-case diagnostic scripts | + +These are source snapshots, not a single importable package. Their original configs name absolute paths under `/home/wuyifan` and data roots under `/SSD*`; the review of what ran should use those values together with the SHA256 checkpoint and code records in the experiment reports. To rerun elsewhere, map those paths, obtain the datasets/weights/assets, and revalidate each hash-bound registration. Do not treat a path substitution alone as a reproduced experiment. + +## Start here for the current training review + +1. `experiments/u0_normalized6d/config.json` fixes a 60-clip update with H2O/ARCTIC/HOT3D quotas 21/15/24, AdamW learning rates, loss coefficients, the RGB teacher weight, and checkpoint interval. +2. `experiments/u0_normalized6d/train.py` controls data coverage, source scaling, DDP, optimizer groups, clipping, checkpoints, and provenance. +3. `experiments/u0_normalized6d/normalized_loss.py` defines the direct rotation-6D and geometry terms. `src/foundation_hand/models/bimanual.py` and `src/foundation_hand/models/decoder.py` define prediction and temporal fusion. +4. `experiments/a7_canonical_gt_train/targets.py` and `common.py` apply corrected-left labels and check MANO reconstruction. `src/foundation_hand/data/{h2o,arctic,hot3d}_dataset.py` construct camera-space source targets. +5. `experiments/pose_delta_diagnostics/pose_hard_case_monitor.py` defines GT-hard buckets and paired evaluation. The reports in `reports/` use source-native GT on fixed development panels; they are not official benchmark submissions. + +## Known review findings + +- N0/N1 both continue from the same U0 RGB checkpoint and use a teacher geometry anchor of weight 0.05. They do not test from-scratch or mean-pose-delta training. +- The training loss compares Gram-Schmidt-normalized predicted 6D with the first two rows of GT rotations. GT axis-angle conversion is currently executed inside bf16 autocast, causing a small orthogonality error. This is recorded in `docs/HK.md`; it is not silently patched in this snapshot. +- Valid 3D hand geometry and root pose are camera-space. The 15 MANO finger rotations are local to the kinematic chain. The cached label is axis-angle; 6D is generated during loss computation. +- N1 improves some high-bend HOT3D hands but does not pass cross-source four-metric/no-harm gates. N0 was stopped after log step 19,247; its last complete checkpoint is 18K. See `docs/HK.md` for matched 18K numbers and the N1 20K curve point. + +## What is intentionally absent + +No raw or filtered dataset, per-frame label cache, MANO asset, DINO weight, training checkpoint, optimizer state, image/video, SSH credential, or access token is included. Runtime JSON manifests that can enumerate private data recordings are omitted; short config and aggregate reports are included. The code can be reviewed immediately but cannot reproduce training from this repository alone. diff --git a/home/wuyifan/EgoNet_train_20261008/THIRD_PARTY.md b/home/wuyifan/EgoNet_train_20261008/THIRD_PARTY.md new file mode 100644 index 0000000000000000000000000000000000000000..c81615b33f31bf138129eab51ce85ff3eacc15ff --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/THIRD_PARTY.md @@ -0,0 +1,12 @@ +# External dependencies + +`pyproject.toml` lists Python package dependencies. The original Foundation Hand repository also recorded these external repositories as Git submodules; their source is not redistributed in this review snapshot: + +| Upstream | Original revision | +| --- | --- | +| `https://github.com/taeinkwon/h2odataset.git` | `ebcb48996849f747580907dc22f8745633ae60b0` | +| `https://github.com/facebookresearch/dinov3.git` | `346f38fee679c56a6888f91c51670fae61d364e0` | +| `https://github.com/taeinkwon/h2oplayer.git` | `6f30a287f04e50bb96c6ba5e986ff72c75dd05e5` | +| `https://github.com/hassony2/manopth.git` | `4f1dcad1201ff1bfca6e065a85f0e3456e1aa32b` | + +The HOT3D Python API was present in the original runtime as a separate third-party tree, but no pinned upstream revision was registered in the project's `.gitmodules`. Reviewers should obtain a version compatible with the original dataset API before attempting to rerun its reader. MANO model files and DINO pretrained weights require their own licenses and are not included. diff --git a/home/wuyifan/EgoNet_train_20261008/configs/a_rgb_single_frame.yaml b/home/wuyifan/EgoNet_train_20261008/configs/a_rgb_single_frame.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cf961b34f90e1f9cf9291358e4266b629297fa87 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/a_rgb_single_frame.yaml @@ -0,0 +1,16 @@ +name: a_rgb_single_frame +seed: 20260716 +data: {resolution_hw: [288, 512], T: 1, stride: 1, batch_size: 2} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: false + use_depth: false + use_rays: false + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/b_rgb_video_sequential.yaml b/home/wuyifan/EgoNet_train_20261008/configs/b_rgb_video_sequential.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ba3f980a19b97d8c5eb5129d24565c9cd6dc2309 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/b_rgb_video_sequential.yaml @@ -0,0 +1,16 @@ +name: b_rgb_video_sequential +seed: 20260716 +data: {resolution_hw: [288, 512], T: 8, stride: 1, batch_size: 1} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: true + use_depth: false + use_rays: false + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/c_rgb_video_alternating.yaml b/home/wuyifan/EgoNet_train_20261008/configs/c_rgb_video_alternating.yaml new file mode 100644 index 0000000000000000000000000000000000000000..23fd865b9d3ee7dcf56e7289d3a3d5d894050987 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/c_rgb_video_alternating.yaml @@ -0,0 +1,16 @@ +name: c_rgb_video_alternating +seed: 20260716 +data: {resolution_hw: [288, 512], T: 8, stride: 1, batch_size: 1} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + use_rays: false + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/d_rgb_k_video_alternating.yaml b/home/wuyifan/EgoNet_train_20261008/configs/d_rgb_k_video_alternating.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dcb700c2f9138e5f60c9512d3a8a7f889823413b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/d_rgb_k_video_alternating.yaml @@ -0,0 +1,16 @@ +name: d_rgb_k_video_alternating +seed: 20260716 +data: {resolution_hw: [288, 512], T: 8, stride: 1, batch_size: 1} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + use_rays: true + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/e_rgb_depth_video_alternating.yaml b/home/wuyifan/EgoNet_train_20261008/configs/e_rgb_depth_video_alternating.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4d12bc95b91fa493034baf389f24438af874970 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/e_rgb_depth_video_alternating.yaml @@ -0,0 +1,18 @@ +name: e_rgb_depth_video_alternating +seed: 20260716 +data: {resolution_hw: [288, 512], T: 8, stride: 1, batch_size: 1} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_floor: 0.05 + use_rays: false + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/e_rgb_depth_video_alternating_fixed_gate.yaml b/home/wuyifan/EgoNet_train_20261008/configs/e_rgb_depth_video_alternating_fixed_gate.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3df314c0def8c152cf8d6fa1322c796c4463ec68 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/e_rgb_depth_video_alternating_fixed_gate.yaml @@ -0,0 +1,19 @@ +name: e_rgb_depth_video_alternating_fixed_gate +seed: 20260716 +data: {resolution_hw: [288, 512], T: 8, stride: 1, batch_size: 1} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/f_geometry_ablation.yaml b/home/wuyifan/EgoNet_train_20261008/configs/f_geometry_ablation.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b7563140249d901e1aef679965794afe8b080da --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/f_geometry_ablation.yaml @@ -0,0 +1,18 @@ +name: f_geometry_ablation +seed: 20260716 +data: {resolution_hw: [288, 512], T: 8, stride: 1, batch_size: 1} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_floor: 0.05 + use_rays: true + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/f_geometry_fixed_gate_ablation.yaml b/home/wuyifan/EgoNet_train_20261008/configs/f_geometry_fixed_gate_ablation.yaml new file mode 100644 index 0000000000000000000000000000000000000000..09b2d5bdb92a9702d1a390f8fcc3a7713c9dde9d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/f_geometry_fixed_gate_ablation.yaml @@ -0,0 +1,19 @@ +name: f_geometry_fixed_gate_ablation +seed: 20260716 +data: {resolution_hw: [288, 512], T: 8, stride: 1, batch_size: 1} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/f_rgb_depth_k_video_alternating.yaml b/home/wuyifan/EgoNet_train_20261008/configs/f_rgb_depth_k_video_alternating.yaml new file mode 100644 index 0000000000000000000000000000000000000000..94fab9993db9725eda58c8dd67cf88a50fba54fa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/f_rgb_depth_k_video_alternating.yaml @@ -0,0 +1,18 @@ +name: f_rgb_depth_k_video_alternating +seed: 20260716 +data: {resolution_hw: [288, 512], T: 8, stride: 1, batch_size: 1} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_floor: 0.05 + use_rays: true + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/f_rgb_depth_k_video_alternating_fixed_gate.yaml b/home/wuyifan/EgoNet_train_20261008/configs/f_rgb_depth_k_video_alternating_fixed_gate.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e6f96c67343c45befee641dd7660067f3302cac7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/f_rgb_depth_k_video_alternating_fixed_gate.yaml @@ -0,0 +1,19 @@ +name: f_rgb_depth_k_video_alternating_fixed_gate +seed: 20260716 +data: {resolution_hw: [288, 512], T: 8, stride: 1, batch_size: 1} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + require_mano: true +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t0_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t0_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a957581e24dfe61cc70473d39c9dd8db0289d35f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t0_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m0_l0_t0_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L0 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: false + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t0_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t0_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..770ff360e55a51c301ab30d5d193ee8a3f44f1d4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t0_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m0_l0_t0_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L0 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: false + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t0_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t0_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4f0943f19c4fb595ff4772efa5aa79138c5b3f7b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t0_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m0_l0_t0_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L0 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: false + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..698bad9b1201db9225710e90110001279b2b01ed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t1_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m0_l0_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L0 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ccb4860116ba4c67a69a7fa573b943bd21b08440 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t1_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m0_l0_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L0 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51dd32d3dc71ef3be2eb9703206d0c0c2706bf07 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l0_t1_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m0_l0_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L0 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t0_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t0_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ee7f127dccd24153e74582525aac78bbed3c92a0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t0_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m0_l1_t0_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L1 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: false + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t0_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t0_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d8e77b85efb767b3e8b7e71cca3111c3ad220035 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t0_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m0_l1_t0_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L1 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: false + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t0_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t0_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ba8700f49a2d0d5ff1586d43e5f87f3c42df55dc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t0_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m0_l1_t0_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L1 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: false + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..616300bece6e360f3de0b6e58d7843433797ecb1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t1_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m0_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L1 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..55709ea7a90394a49b22a8dc81e0e385a1d2df44 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t1_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m0_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L1 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b4e006372d1c459143554f45e3d12a1ad7f624c9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l1_t1_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m0_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L1 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l2_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l2_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eaebe6aa68c45b570cb7993a1c6b29f8e3bf6ee0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l2_t1_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m0_l2_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L2 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: hybrid_reread + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l2_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l2_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6132f252985e67e9a135f653e6e596bd5b0bd3ca --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l2_t1_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m0_l2_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L2 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: hybrid_reread + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l2_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l2_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b97e8cb778d5f43f15409a9d570c8f8b330691c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m0_l2_t1_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m0_l2_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M0 + layout: L2 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: hybrid_reread + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t0_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t0_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..43bd433f06b02cd2e0307e223f4e0c2ebf451ac3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t0_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m3_l0_t0_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L0 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: false + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t0_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t0_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..43e4ae53c9358362cf6e4564c0278002faad9091 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t0_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m3_l0_t0_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L0 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: false + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t0_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t0_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4debedf8a7e8acfb4cf127d5cc7cc10b496febc7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t0_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m3_l0_t0_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L0 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: false + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..811670df1bb3b7934b98d276573b5237ac80092f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t1_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m3_l0_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L0 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..12c4d0a9828cb0378889a70d726daad67bbfbdeb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t1_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m3_l0_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L0 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2f6dfb57f34ae4652c26088e9e7c04718848ad3a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l0_t1_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m3_l0_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L0 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: sequential + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t0_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t0_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd88d9e49b2b9b35fe15ab160eb3060229716af6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t0_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m3_l1_t0_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L1 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: false + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t0_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t0_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2bca87221dc6a68b7f12f8d996d3dcd4c672708a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t0_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m3_l1_t0_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L1 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: false + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t0_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t0_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f97ded87cc15f5210c4adcf67c20fea44c51fca2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t0_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m3_l1_t0_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L1 + temporal: T0 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: false + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..14f5fa50f92f82c25f7974be5c0de45cd0f91261 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t1_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m3_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L1 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..951f629f8f0c80450b25db599b30d9775883d041 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t1_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m3_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L1 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c7a737b398809c6b5b453c821ce6a1bc75a7dd7e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l1_t1_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m3_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L1 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l2_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l2_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f5773ccf13db3be486bcf47f070601b89b87441e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l2_t1_s20260716.yaml @@ -0,0 +1,63 @@ +name: core_m3_l2_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L2 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: hybrid_reread + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l2_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l2_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac9c8dc2482fc2daa10962f0bbad454f2a108760 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l2_t1_s20260717.yaml @@ -0,0 +1,63 @@ +name: core_m3_l2_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L2 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: hybrid_reread + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l2_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l2_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..69ba5a9fc2156fcf96f47ea815b30dc3cc9ab7ed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/core/core_m3_l2_t1_s20260718.yaml @@ -0,0 +1,63 @@ +name: core_m3_l2_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: decoder_temporal_core + modality: M3 + layout: L2 + temporal: T1 + registered_axes: + - layout + - temporal_attention + - modality +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: hybrid_reread + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..011fa8209556752238be299827fb26465fa14a1d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s20260716.yaml @@ -0,0 +1,65 @@ +name: depth_dropout005_geometry_m3_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: depth_modality_dropout_dose + modality: M3 + layout: L1 + temporal: T1 + variant: dropout005_geometry + registered_axes: + - modality_dropout_dose + reference: D2_dropout00_and_dropout02_endpoints +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c099360789159cb102d94a288a7922df8806b2d1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s20260717.yaml @@ -0,0 +1,65 @@ +name: depth_dropout005_geometry_m3_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: depth_modality_dropout_dose + modality: M3 + layout: L1 + temporal: T1 + variant: dropout005_geometry + registered_axes: + - modality_dropout_dose + reference: D2_dropout00_and_dropout02_endpoints +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b7050e2c075c652697c5bbd6d470d7585f40827d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s20260718.yaml @@ -0,0 +1,65 @@ +name: depth_dropout005_geometry_m3_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: depth_modality_dropout_dose + modality: M3 + layout: L1 + temporal: T1 + variant: dropout005_geometry + registered_axes: + - modality_dropout_dose + reference: D2_dropout00_and_dropout02_endpoints +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3a38c46524f77519ce1d2a506c953172bcc7f0c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s20260716.yaml @@ -0,0 +1,65 @@ +name: depth_dropout00_geometry_m3_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: depth_modality_dropout + modality: M3 + layout: L1 + temporal: T1 + variant: dropout00_geometry + registered_axes: + - modality_dropout + reference: dropout00_geometry_same_commit +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0ab96be0256fd98d70a564d21ff0196da6e2d176 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s20260717.yaml @@ -0,0 +1,65 @@ +name: depth_dropout00_geometry_m3_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: depth_modality_dropout + modality: M3 + layout: L1 + temporal: T1 + variant: dropout00_geometry + registered_axes: + - modality_dropout + reference: dropout00_geometry_same_commit +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ffe5f6c481bd3082d242b15b4f70d9e6be010085 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s20260718.yaml @@ -0,0 +1,65 @@ +name: depth_dropout00_geometry_m3_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: depth_modality_dropout + modality: M3 + layout: L1 + temporal: T1 + variant: dropout00_geometry + registered_axes: + - modality_dropout + reference: dropout00_geometry_same_commit +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout010_geometry_m3_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout010_geometry_m3_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..58ab544c11e2410a29397ebe1fa60dcc4c357f6c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout010_geometry_m3_l1_t1_s20260716.yaml @@ -0,0 +1,65 @@ +name: depth_dropout010_geometry_m3_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: depth_modality_dropout_dose + modality: M3 + layout: L1 + temporal: T1 + variant: dropout010_geometry + registered_axes: + - modality_dropout_dose + reference: D2_dropout00_and_dropout02_endpoints +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.1 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout010_geometry_m3_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout010_geometry_m3_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..162ec5cce19e7f0cfb493e841b95f76633cf8c66 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout010_geometry_m3_l1_t1_s20260717.yaml @@ -0,0 +1,65 @@ +name: depth_dropout010_geometry_m3_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: depth_modality_dropout_dose + modality: M3 + layout: L1 + temporal: T1 + variant: dropout010_geometry + registered_axes: + - modality_dropout_dose + reference: D2_dropout00_and_dropout02_endpoints +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.1 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout010_geometry_m3_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout010_geometry_m3_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48ea9d73644fdd8297abb14898313f752db33daf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout010_geometry_m3_l1_t1_s20260718.yaml @@ -0,0 +1,65 @@ +name: depth_dropout010_geometry_m3_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: depth_modality_dropout_dose + modality: M3 + layout: L1 + temporal: T1 + variant: dropout010_geometry + registered_axes: + - modality_dropout_dose + reference: D2_dropout00_and_dropout02_endpoints +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.1 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout02_geometry_m3_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout02_geometry_m3_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3406c678ce4697f6ea07479a0eb4e4cfbb2a839c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout02_geometry_m3_l1_t1_s20260716.yaml @@ -0,0 +1,65 @@ +name: depth_dropout02_geometry_m3_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: depth_modality_dropout + modality: M3 + layout: L1 + temporal: T1 + variant: dropout02_geometry + registered_axes: + - modality_dropout + reference: dropout00_geometry_same_commit +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.2 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout02_geometry_m3_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout02_geometry_m3_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c6a707e5187e706b60018580d2906d8124d11936 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout02_geometry_m3_l1_t1_s20260717.yaml @@ -0,0 +1,65 @@ +name: depth_dropout02_geometry_m3_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: depth_modality_dropout + modality: M3 + layout: L1 + temporal: T1 + variant: dropout02_geometry + registered_axes: + - modality_dropout + reference: dropout00_geometry_same_commit +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.2 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout02_geometry_m3_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout02_geometry_m3_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c004058f1d9058ddd242eec5fc2b567b918e734b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_dropout02_geometry_m3_l1_t1_s20260718.yaml @@ -0,0 +1,65 @@ +name: depth_dropout02_geometry_m3_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: depth_modality_dropout + modality: M3 + layout: L1 + temporal: T1 + variant: dropout02_geometry + registered_axes: + - modality_dropout + reference: dropout00_geometry_same_commit +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.2 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_gate025_m3_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_gate025_m3_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d490c12628edf7ebfb07f6c1631504be0f7b8b90 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_gate025_m3_l1_t1_s20260716.yaml @@ -0,0 +1,64 @@ +name: depth_gate025_m3_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: depth_fusion + modality: M3 + layout: L1 + temporal: T1 + variant: gate025 + registered_axes: + - depth_fusion_or_representation + reference: P0_M3_L1_T1_fixed_gate_0.5 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.25 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_gate025_m3_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_gate025_m3_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6d5a7c8ffcb9eedc8d215a540d125f73e7f62e36 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_gate025_m3_l1_t1_s20260717.yaml @@ -0,0 +1,64 @@ +name: depth_gate025_m3_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: depth_fusion + modality: M3 + layout: L1 + temporal: T1 + variant: gate025 + registered_axes: + - depth_fusion_or_representation + reference: P0_M3_L1_T1_fixed_gate_0.5 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.25 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_gate025_m3_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_gate025_m3_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..92180dcc97654dcea848dd89d21ea9be11196f70 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_gate025_m3_l1_t1_s20260718.yaml @@ -0,0 +1,64 @@ +name: depth_gate025_m3_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: depth_fusion + modality: M3 + layout: L1 + temporal: T1 + variant: gate025 + registered_axes: + - depth_fusion_or_representation + reference: P0_M3_L1_T1_fixed_gate_0.5 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.25 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..599923ba42bf6cb9f3760459336afc8d77670023 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s20260716.yaml @@ -0,0 +1,64 @@ +name: depth_geometry_m3_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: depth_fusion + modality: M3 + layout: L1 + temporal: T1 + variant: geometry + registered_axes: + - depth_fusion_or_representation + reference: P0_M3_L1_T1_fixed_gate_0.5 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48a296371752a40c1e924196a82e6d8b3a65359d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s20260717.yaml @@ -0,0 +1,64 @@ +name: depth_geometry_m3_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: depth_fusion + modality: M3 + layout: L1 + temporal: T1 + variant: geometry + registered_axes: + - depth_fusion_or_representation + reference: P0_M3_L1_T1_fixed_gate_0.5 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5ecd9ea27c324b2c13ba160d6712faa45fdb741 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s20260718.yaml @@ -0,0 +1,64 @@ +name: depth_geometry_m3_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: depth_fusion + modality: M3 + layout: L1 + temporal: T1 + variant: geometry + registered_axes: + - depth_fusion_or_representation + reference: P0_M3_L1_T1_fixed_gate_0.5 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_learned_gate_m3_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_learned_gate_m3_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..70fbeb6738039fae5293bce9acfedd768dc3548a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_learned_gate_m3_l1_t1_s20260716.yaml @@ -0,0 +1,64 @@ +name: depth_learned_gate_m3_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: depth_fusion + modality: M3 + layout: L1 + temporal: T1 + variant: learned_gate + registered_axes: + - depth_fusion_or_representation + reference: P0_M3_L1_T1_fixed_gate_0.5 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: learned + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_learned_gate_m3_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_learned_gate_m3_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..000bbe5ed5c9cb0f0ddc111f961872ffa8267e3d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_learned_gate_m3_l1_t1_s20260717.yaml @@ -0,0 +1,64 @@ +name: depth_learned_gate_m3_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: depth_fusion + modality: M3 + layout: L1 + temporal: T1 + variant: learned_gate + registered_axes: + - depth_fusion_or_representation + reference: P0_M3_L1_T1_fixed_gate_0.5 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: learned + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_learned_gate_m3_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_learned_gate_m3_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e0b88bdcaee5f7584c239f19e449a8defdd358c9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/depth_fusion/depth_learned_gate_m3_l1_t1_s20260718.yaml @@ -0,0 +1,64 @@ +name: depth_learned_gate_m3_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: depth_fusion + modality: M3 + layout: L1 + temporal: T1 + variant: learned_gate + registered_axes: + - depth_fusion_or_representation + reference: P0_M3_L1_T1_fixed_gate_0.5 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: learned + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/checkpoint_roles.json b/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/checkpoint_roles.json new file mode 100644 index 0000000000000000000000000000000000000000..2ea217a8efb01b7adf9c49ae6b01294db8dbe373 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/checkpoint_roles.json @@ -0,0 +1,7 @@ +{ + "tail_step_125k": "step_0125000.pt", + "tail_step_150k": "step_0150000.pt", + "tail_best_absolute": "best.pt", + "tail_best_z": "best_z.pt", + "tail_final": "step_0150000_final.pt" +} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..abc2b1b60552b5f4fdfa203d70c3091fcef35f2e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716.yaml @@ -0,0 +1,73 @@ +name: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: low_lr_tail + modality: M3 + layout: L1 + temporal: T1 + variant: photometric_on_r640x368_tail150k + registered_axes: + - training_duration + reference: photometric_on_geometry_m3_l1_t1_r640x368_s20260716 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 150000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a5fffcf8bd0a45c0d231a3f9110004e639c1d4d0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717.yaml @@ -0,0 +1,73 @@ +name: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: low_lr_tail + modality: M3 + layout: L1 + temporal: T1 + variant: photometric_on_r640x368_tail150k + registered_axes: + - training_duration + reference: photometric_on_geometry_m3_l1_t1_r640x368_s20260717 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 150000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d487ea52a00aabc0262e6bbe07491db02aa34aed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/long_tail/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718.yaml @@ -0,0 +1,73 @@ +name: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: low_lr_tail + modality: M3 + layout: L1 + temporal: T1 + variant: photometric_on_r640x368_tail150k + registered_axes: + - training_duration + reference: photometric_on_geometry_m3_l1_t1_r640x368_s20260718 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 150000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m1_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m1_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ba58f77fa67d7655d095399048fdf56902e3538b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m1_l1_t1_s20260716.yaml @@ -0,0 +1,62 @@ +name: modality_m1_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: modality_causal + modality: M1 + layout: L1 + temporal: T1 + registered_axes: + - modality + decoder_promotion_source: decoder_temporal_core_best_absolute_full_val +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m1_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m1_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9d10c5e0ce665a92bf81357d206d473840d845d1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m1_l1_t1_s20260717.yaml @@ -0,0 +1,62 @@ +name: modality_m1_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: modality_causal + modality: M1 + layout: L1 + temporal: T1 + registered_axes: + - modality + decoder_promotion_source: decoder_temporal_core_best_absolute_full_val +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m1_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m1_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..67cb84f9b08db1320617caeba91df7e11364b494 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m1_l1_t1_s20260718.yaml @@ -0,0 +1,62 @@ +name: modality_m1_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: modality_causal + modality: M1 + layout: L1 + temporal: T1 + registered_axes: + - modality + decoder_promotion_source: decoder_temporal_core_best_absolute_full_val +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m2_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m2_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b953a98f09cc89d7802a423c173d9919d28fbd63 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m2_l1_t1_s20260716.yaml @@ -0,0 +1,62 @@ +name: modality_m2_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: modality_causal + modality: M2 + layout: L1 + temporal: T1 + registered_axes: + - modality + decoder_promotion_source: decoder_temporal_core_best_absolute_full_val +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m2_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m2_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8a05a7edbec1156eef989ea789a6e753ee2d8612 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m2_l1_t1_s20260717.yaml @@ -0,0 +1,62 @@ +name: modality_m2_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: modality_causal + modality: M2 + layout: L1 + temporal: T1 + registered_axes: + - modality + decoder_promotion_source: decoder_temporal_core_best_absolute_full_val +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m2_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m2_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b76327ff697eccaebe27947eec4da6c3b95f8146 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/modality/modality_m2_l1_t1_s20260718.yaml @@ -0,0 +1,62 @@ +name: modality_m2_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: modality_causal + modality: M2 + layout: L1 + temporal: T1 + registered_axes: + - modality + decoder_promotion_source: decoder_temporal_core_best_absolute_full_val +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: false + use_bimanual_interaction: true + predict_presence: true + require_mano: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e46fc48d5ecc10a5f3b5fade3cd00ddd906360ca --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s20260716.yaml @@ -0,0 +1,72 @@ +name: photometric_off_geometry_m3_l1_t1_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: photometric_augmentation + modality: M3 + layout: L1 + temporal: T1 + variant: photometric_off_r640x368 + registered_axes: + - photometric_augmentation + reference: E1_promoted_r640x368 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: false + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..443833cd19a790b2025ec65db045bed0ce64f94f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s20260717.yaml @@ -0,0 +1,72 @@ +name: photometric_off_geometry_m3_l1_t1_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: photometric_augmentation + modality: M3 + layout: L1 + temporal: T1 + variant: photometric_off_r640x368 + registered_axes: + - photometric_augmentation + reference: E1_promoted_r640x368 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: false + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..79e65976c424bdc1b25f8722df6e1d016e383f6b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s20260718.yaml @@ -0,0 +1,72 @@ +name: photometric_off_geometry_m3_l1_t1_r640x368_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: photometric_augmentation + modality: M3 + layout: L1 + temporal: T1 + variant: photometric_off_r640x368 + registered_axes: + - photometric_augmentation + reference: E1_promoted_r640x368 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: false + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..987afe54eefd48ceb9c492c057401e882a960dbb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s20260716.yaml @@ -0,0 +1,72 @@ +name: photometric_on_geometry_m3_l1_t1_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: photometric_augmentation + modality: M3 + layout: L1 + temporal: T1 + variant: photometric_on_r640x368 + registered_axes: + - photometric_augmentation + reference: E1_promoted_r640x368 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b0300b8b919bddfe3b7982f175aeab1121c2ff0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s20260717.yaml @@ -0,0 +1,72 @@ +name: photometric_on_geometry_m3_l1_t1_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: photometric_augmentation + modality: M3 + layout: L1 + temporal: T1 + variant: photometric_on_r640x368 + registered_axes: + - photometric_augmentation + reference: E1_promoted_r640x368 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d3b7df5848880cb250298b423d13ea5ead8abd30 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s20260718.yaml @@ -0,0 +1,72 @@ +name: photometric_on_geometry_m3_l1_t1_r640x368_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: photometric_augmentation + modality: M3 + layout: L1 + temporal: T1 + variant: photometric_on_r640x368 + registered_axes: + - photometric_augmentation + reference: E1_promoted_r640x368 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a96453a5edd78a37400029a502129528aa77b7c8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s20260716.yaml @@ -0,0 +1,65 @@ +name: depth_dropout005_geometry_m3_l1_t1_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: resolution + modality: M3 + layout: L1 + temporal: T1 + variant: dropout005_geometry_r640x368 + registered_axes: + - input_resolution + reference: dropout005_geometry_r512x288_D3 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..519c6dcbc744e8d176c6e9fba0fa51f360205957 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s20260717.yaml @@ -0,0 +1,65 @@ +name: depth_dropout005_geometry_m3_l1_t1_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: resolution + modality: M3 + layout: L1 + temporal: T1 + variant: dropout005_geometry_r640x368 + registered_axes: + - input_resolution + reference: dropout005_geometry_r512x288_D3 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1dd46f84468a799cb954a5088145553fff4907c6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s20260718.yaml @@ -0,0 +1,65 @@ +name: depth_dropout005_geometry_m3_l1_t1_r640x368_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: resolution + modality: M3 + layout: L1 + temporal: T1 + variant: dropout005_geometry_r640x368 + registered_axes: + - input_resolution + reference: dropout005_geometry_r512x288_D3 +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ff083efa69aaa9876ac2ff0484895249cbb863aa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s20260716.yaml @@ -0,0 +1,65 @@ +name: temporal_p1_m3_l1_t1_s20260716 +seed: 20260716 +experiment: + phase: 3 + matrix: temporal_position + modality: M3 + layout: L1 + temporal: T1 + position: P1 + registered_axes: + - temporal_position + reference: P0_no_temporal_position_reused_core_m3_l1_t1 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + temporal_position_mode: relative_bias + temporal_relative_bias_max_distance: 15 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7eaccbc22f1eb61fd69b93e4982a8b2abad5778 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s20260717.yaml @@ -0,0 +1,65 @@ +name: temporal_p1_m3_l1_t1_s20260717 +seed: 20260717 +experiment: + phase: 3 + matrix: temporal_position + modality: M3 + layout: L1 + temporal: T1 + position: P1 + registered_axes: + - temporal_position + reference: P0_no_temporal_position_reused_core_m3_l1_t1 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + temporal_position_mode: relative_bias + temporal_relative_bias_max_distance: 15 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a6221c7cfeefe042cc99da79bc89c0b2b0ed7feb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s20260718.yaml @@ -0,0 +1,65 @@ +name: temporal_p1_m3_l1_t1_s20260718 +seed: 20260718 +experiment: + phase: 3 + matrix: temporal_position + modality: M3 + layout: L1 + temporal: T1 + position: P1 + registered_axes: + - temporal_position + reference: P0_no_temporal_position_reused_core_m3_l1_t1 +data: + resolution_hw: + - 288 + - 512 + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: log_depth + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + temporal_position_mode: relative_bias + temporal_relative_bias_max_distance: 15 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/validation_subset_256.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260716_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260716_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42116334bea6b392a8408ca3e6821e474b614cf2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260716_formal100k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_depth_k_r640x368_s20260716_formal100k +seed: 20260716 +experiment: + phase: 4 + wave: A + cell: A3 + stage: formal + oracle_crop_mode: oracle_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716/best.pt + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + coarse_checkpoint_step: 135000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 100000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260716_health25k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260716_health25k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eea54d98fdc2b724112b4a0d27a3c23571697df1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260716_health25k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_depth_k_r640x368_s20260716_health25k +seed: 20260716 +experiment: + phase: 4 + wave: A + cell: A3 + stage: health + oracle_crop_mode: oracle_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716/best.pt + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + coarse_checkpoint_step: 135000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 5000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 25000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260716_tiny2k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260716_tiny2k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dc8df2fb40ed935acca2ae3aada32a8f7664ee14 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260716_tiny2k.yaml @@ -0,0 +1,80 @@ +name: phase4_a3_depth_k_r640x368_s20260716_tiny2k +seed: 20260716 +experiment: + phase: 4 + wave: A + cell: A3 + stage: tiny + oracle_crop_mode: oracle_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716/best.pt + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + coarse_checkpoint_step: 135000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 4 + checkpoint_interval: 500 + validation_interval: 500 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 100 + early_stopping_patience: 0 + lr_schedule_steps: 2000 +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260717_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260717_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ad1b8ce721c816befc4494232fc63298a5cad74 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260717_formal100k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_depth_k_r640x368_s20260717_formal100k +seed: 20260717 +experiment: + phase: 4 + wave: A + cell: A3 + stage: formal + oracle_crop_mode: oracle_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717/best.pt + coarse_checkpoint_sha256: 957b0a033c5d54609d8f3eae9503f5f2a2b040dd5bcf1fad19960a64c92e8b6d + coarse_checkpoint_step: 130000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 100000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260718_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260718_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..344aac8a9ac2de6426128a48045afe2c6931b28d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_depth_k_r640x368_s20260718_formal100k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_depth_k_r640x368_s20260718_formal100k +seed: 20260718 +experiment: + phase: 4 + wave: A + cell: A3 + stage: formal + oracle_crop_mode: oracle_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/best.pt + coarse_checkpoint_sha256: 798fefc9147f795d7a85f351513a7835ce17017c7715e4e71815360dd4eee374 + coarse_checkpoint_step: 140000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 100000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260716_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260716_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f6e96b7f856e90966839a0cb52357e6a25a53d96 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260716_formal100k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_rgb_depth_k_r640x368_s20260716_formal100k +seed: 20260716 +experiment: + phase: 4 + wave: A + cell: A3 + stage: formal + oracle_crop_mode: oracle_rgb_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716/best.pt + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + coarse_checkpoint_step: 135000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 100000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260716_health25k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260716_health25k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4269982b7500bffcac9e9163fbf2b6492a2d0f0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260716_health25k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_rgb_depth_k_r640x368_s20260716_health25k +seed: 20260716 +experiment: + phase: 4 + wave: A + cell: A3 + stage: health + oracle_crop_mode: oracle_rgb_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716/best.pt + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + coarse_checkpoint_step: 135000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 5000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 25000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260716_tiny2k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260716_tiny2k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..175c51d2dcee40ed2c6186450be67a7ffe7499ec --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260716_tiny2k.yaml @@ -0,0 +1,80 @@ +name: phase4_a3_rgb_depth_k_r640x368_s20260716_tiny2k +seed: 20260716 +experiment: + phase: 4 + wave: A + cell: A3 + stage: tiny + oracle_crop_mode: oracle_rgb_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716/best.pt + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + coarse_checkpoint_step: 135000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 4 + checkpoint_interval: 500 + validation_interval: 500 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 100 + early_stopping_patience: 0 + lr_schedule_steps: 2000 +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260717_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260717_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..210cf7e82ed5ed512fff197d3b2a867dce14a291 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260717_formal100k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_rgb_depth_k_r640x368_s20260717_formal100k +seed: 20260717 +experiment: + phase: 4 + wave: A + cell: A3 + stage: formal + oracle_crop_mode: oracle_rgb_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717/best.pt + coarse_checkpoint_sha256: 957b0a033c5d54609d8f3eae9503f5f2a2b040dd5bcf1fad19960a64c92e8b6d + coarse_checkpoint_step: 130000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 100000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260718_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260718_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3cab351efa28b503d79b318a099795408bc3287c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_depth_k_r640x368_s20260718_formal100k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_rgb_depth_k_r640x368_s20260718_formal100k +seed: 20260718 +experiment: + phase: 4 + wave: A + cell: A3 + stage: formal + oracle_crop_mode: oracle_rgb_depth_k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/best.pt + coarse_checkpoint_sha256: 798fefc9147f795d7a85f351513a7835ce17017c7715e4e71815360dd4eee374 + coarse_checkpoint_step: 140000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb_depth_k + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 100000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260716_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260716_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2883bf5469a31bf42bb6cc00f77192dbf0e33134 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260716_formal100k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_rgb_r640x368_s20260716_formal100k +seed: 20260716 +experiment: + phase: 4 + wave: A + cell: A3 + stage: formal + oracle_crop_mode: oracle_rgb + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716/best.pt + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + coarse_checkpoint_step: 135000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 100000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260716_health25k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260716_health25k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..861459a2e8705288cb8b326a45f0a5536c77e1d4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260716_health25k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_rgb_r640x368_s20260716_health25k +seed: 20260716 +experiment: + phase: 4 + wave: A + cell: A3 + stage: health + oracle_crop_mode: oracle_rgb + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716/best.pt + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + coarse_checkpoint_step: 135000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 5000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 25000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260716_tiny2k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260716_tiny2k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb9c655630c9084c3332555e709be96af0d97f96 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260716_tiny2k.yaml @@ -0,0 +1,80 @@ +name: phase4_a3_rgb_r640x368_s20260716_tiny2k +seed: 20260716 +experiment: + phase: 4 + wave: A + cell: A3 + stage: tiny + oracle_crop_mode: oracle_rgb + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716/best.pt + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + coarse_checkpoint_step: 135000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 4 + checkpoint_interval: 500 + validation_interval: 500 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 100 + early_stopping_patience: 0 + lr_schedule_steps: 2000 +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260717_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260717_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5b5adb06a73f3874ad1f2d5cd1043d499629e63 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260717_formal100k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_rgb_r640x368_s20260717_formal100k +seed: 20260717 +experiment: + phase: 4 + wave: A + cell: A3 + stage: formal + oracle_crop_mode: oracle_rgb + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717/best.pt + coarse_checkpoint_sha256: 957b0a033c5d54609d8f3eae9503f5f2a2b040dd5bcf1fad19960a64c92e8b6d + coarse_checkpoint_step: 130000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 100000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260718_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260718_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a39851a93c3ff917f1e0c08223e2fda112c51c3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/a3_oracle_crop/phase4_a3_rgb_r640x368_s20260718_formal100k.yaml @@ -0,0 +1,81 @@ +name: phase4_a3_rgb_r640x368_s20260718_formal100k +seed: 20260718 +experiment: + phase: 4 + wave: A + cell: A3 + stage: formal + oracle_crop_mode: oracle_rgb + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718 + changed_variable: oracle_raw_high_resolution_crop_residual_only + coarse_checkpoint_path: /SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/best.pt + coarse_checkpoint_sha256: 798fefc9147f795d7a85f351513a7835ce17017c7715e4e71815360dd4eee374 + coarse_checkpoint_step: 140000 + gt_location_at_train_and_validation: true + deployable_inference: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + oracle_crop_mode: oracle_rgb + freeze_coarse_for_oracle_crop: true +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + lr_schedule_steps: 100000 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json +sampling: + mode: uniform diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dfa2d7d8fdb5a49f9b0980ddc08020ac723edc12 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_formal100k.yaml @@ -0,0 +1,78 @@ +name: phase4_b0_axis_huber_r640x368_s20260716_formal100k +seed: 20260716 +experiment: + phase: 4 + wave: B + cell: B0 + stage: formal + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: translation_loss_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_mode: axis_huber + translation_axis_weights: + - 0.5 + - 0.5 + - 2.0 + translation_huber_beta_m: 0.01 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_health25k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_health25k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b88d13dbe3fdd1ca67c94f5a883fd3f4a1401863 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_health25k.yaml @@ -0,0 +1,78 @@ +name: phase4_b0_axis_huber_r640x368_s20260716_health25k +seed: 20260716 +experiment: + phase: 4 + wave: B + cell: B0 + stage: health + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: translation_loss_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_mode: axis_huber + translation_axis_weights: + - 0.5 + - 0.5 + - 2.0 + translation_huber_beta_m: 0.01 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 5000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_smoke1.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_smoke1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1238238b9beb17e8a744e97ed155db69284b138d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_smoke1.yaml @@ -0,0 +1,77 @@ +name: phase4_b0_axis_huber_r640x368_s20260716_smoke1 +seed: 20260716 +experiment: + phase: 4 + wave: B + cell: B0 + stage: smoke + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: translation_loss_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_mode: axis_huber + translation_axis_weights: + - 0.5 + - 0.5 + - 2.0 + translation_huber_beta_m: 0.01 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 1 + num_workers: 4 + checkpoint_interval: 1 + validation_interval: 1 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 0 + early_stopping_patience: 0 + lr_schedule_steps: 1 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_tiny2k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_tiny2k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a3704dc98f87141b15f952b0f42d4b0ad1c4dd09 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260716_tiny2k.yaml @@ -0,0 +1,77 @@ +name: phase4_b0_axis_huber_r640x368_s20260716_tiny2k +seed: 20260716 +experiment: + phase: 4 + wave: B + cell: B0 + stage: tiny + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: translation_loss_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_mode: axis_huber + translation_axis_weights: + - 0.5 + - 0.5 + - 2.0 + translation_huber_beta_m: 0.01 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 4 + checkpoint_interval: 500 + validation_interval: 500 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 100 + early_stopping_patience: 0 + lr_schedule_steps: 2000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260717_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260717_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c96a47c26dec9c950755a0728537d6ced0e05c1b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260717_formal100k.yaml @@ -0,0 +1,78 @@ +name: phase4_b0_axis_huber_r640x368_s20260717_formal100k +seed: 20260717 +experiment: + phase: 4 + wave: B + cell: B0 + stage: formal + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260717 + changed_variable: translation_loss_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_mode: axis_huber + translation_axis_weights: + - 0.5 + - 0.5 + - 2.0 + translation_huber_beta_m: 0.01 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260718_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260718_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..55666e3c77cedaada196d00feb9efe10a9223c38 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b0_axis_loss/phase4_b0_axis_huber_r640x368_s20260718_formal100k.yaml @@ -0,0 +1,78 @@ +name: phase4_b0_axis_huber_r640x368_s20260718_formal100k +seed: 20260718 +experiment: + phase: 4 + wave: B + cell: B0 + stage: formal + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718 + changed_variable: translation_loss_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_mode: axis_huber + translation_axis_weights: + - 0.5 + - 0.5 + - 2.0 + translation_huber_beta_m: 0.01 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2f177f09674c925115415fcc3fc057fdb25e6f1f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_formal100k.yaml @@ -0,0 +1,75 @@ +name: phase4_b2_balanced_sampler_r640x368_s20260716_formal100k +seed: 20260716 +experiment: + phase: 4 + wave: B + cell: B2 + stage: formal + reference: photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: training_sampler_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 +sampling: + mode: balanced + manifest: /home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/train_geometry_balanced_v1.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_health25k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_health25k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0434b51ae3b3b3a70eeae34dd6ae3a088a14cb9e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_health25k.yaml @@ -0,0 +1,75 @@ +name: phase4_b2_balanced_sampler_r640x368_s20260716_health25k +seed: 20260716 +experiment: + phase: 4 + wave: B + cell: B2 + stage: health + reference: photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: training_sampler_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 5000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 +sampling: + mode: balanced + manifest: /home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/train_geometry_balanced_v1.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_smoke1.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_smoke1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dadbdc94e4488cb954744861b134e975a6c34473 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_smoke1.yaml @@ -0,0 +1,74 @@ +name: phase4_b2_balanced_sampler_r640x368_s20260716_smoke1 +seed: 20260716 +experiment: + phase: 4 + wave: B + cell: B2 + stage: smoke + reference: photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: training_sampler_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 1 + num_workers: 4 + checkpoint_interval: 1 + validation_interval: 1 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 0 + early_stopping_patience: 0 + lr_schedule_steps: 1 +sampling: + mode: balanced + manifest: /home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/train_geometry_balanced_v1.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_tiny2k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_tiny2k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..29a995c3aee3c5ac77f87fcfff60b6555c3dd281 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260716_tiny2k.yaml @@ -0,0 +1,74 @@ +name: phase4_b2_balanced_sampler_r640x368_s20260716_tiny2k +seed: 20260716 +experiment: + phase: 4 + wave: B + cell: B2 + stage: tiny + reference: photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + changed_variable: training_sampler_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 4 + checkpoint_interval: 500 + validation_interval: 500 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 100 + early_stopping_patience: 0 + lr_schedule_steps: 2000 +sampling: + mode: balanced + manifest: /home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/tiny_train_geometry_balanced_v1.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260717_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260717_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b24d891e247cab35b9d6b9dc43e2f99cde378e7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260717_formal100k.yaml @@ -0,0 +1,75 @@ +name: phase4_b2_balanced_sampler_r640x368_s20260717_formal100k +seed: 20260717 +experiment: + phase: 4 + wave: B + cell: B2 + stage: formal + reference: photometric_on_geometry_m3_l1_t1_r640x368_s20260717 + changed_variable: training_sampler_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 +sampling: + mode: balanced + manifest: /home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/train_geometry_balanced_v1.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260718_formal100k.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260718_formal100k.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c32317f19a334dc4fec3165577439a7efd71777a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase4/b2_balanced_sampling/phase4_b2_balanced_sampler_r640x368_s20260718_formal100k.yaml @@ -0,0 +1,75 @@ +name: phase4_b2_balanced_sampler_r640x368_s20260718_formal100k +seed: 20260718 +experiment: + phase: 4 + wave: B + cell: B2 + stage: formal + reference: photometric_on_geometry_m3_l1_t1_r640x368_s20260718 + changed_variable: training_sampler_only + frozen_model_recipe: true + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: /home/jiasen/foundation_hand/artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 +sampling: + mode: balanced + manifest: /home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/train_geometry_balanced_v1.json diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..72ba56c3fb8fef8d7a1f4ebc3c034aed7ea6101a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260716.yaml @@ -0,0 +1,69 @@ +name: phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 5 + stage: 1 + class: preregistered_confirmatory + matrix: p0_final_recipe + variant: p0_photometric_r640x368_tail150k + registered_axes: [modality_dropout, final_recipe] + reference: depth_dropout00_geometry_m3_l1_t1_s20260716 +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 150000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 500 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 100000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..741e86261821e81e698c05a334b0ae17d9a0ad26 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260717.yaml @@ -0,0 +1,40 @@ +name: phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 5 + stage: 1 + class: preregistered_confirmatory + matrix: p0_final_recipe + variant: p0_photometric_r640x368_tail150k + registered_axes: [modality_dropout, final_recipe] + reference: depth_dropout00_geometry_m3_l1_t1_s20260717 +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: {max_steps: 150000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 256, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json, lr_schedule_steps: 100000} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..55083ebb798fe06c73304fe6e24d16d80ffb1085 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718.yaml @@ -0,0 +1,40 @@ +name: phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718 +seed: 20260718 +experiment: + phase: 5 + stage: 1 + class: preregistered_confirmatory + matrix: p0_final_recipe + variant: p0_photometric_r640x368_tail150k + registered_axes: [modality_dropout, final_recipe] + reference: depth_dropout00_geometry_m3_l1_t1_s20260718 +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: {max_steps: 150000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 256, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json, lr_schedule_steps: 100000} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718_smoke2.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718_smoke2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1b58a22681301738a2c298c46cb9fe6b9a326977 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718_smoke2.yaml @@ -0,0 +1,40 @@ +name: phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718_smoke2 +seed: 20260718 +experiment: + phase: 5 + stage: 1 + class: engineering_smoke + matrix: p0_final_recipe + variant: p0_photometric_r640x368_smoke2 + registered_axes: [engineering_budget] + reference: phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718 +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: {max_steps: 2, num_workers: 0, checkpoint_interval: 1, validation_interval: 1, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 1, early_stopping_patience: 0, validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json, lr_schedule_steps: 2} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718_smoke2_v2.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718_smoke2_v2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d37576b6b1b9ce99043fc196bd440131709413a2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage1/phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718_smoke2_v2.yaml @@ -0,0 +1,40 @@ +name: phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718_smoke2_v2 +seed: 20260718 +experiment: + phase: 5 + stage: 1 + class: engineering_smoke + matrix: p0_final_recipe + variant: p0_photometric_r640x368_smoke2_unbound_validation + registered_axes: [engineering_budget] + reference: phase5_s1_p0_photometric_geometry_m3_l1_t1_r640x368_s20260718 +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: {max_steps: 2, num_workers: 0, checkpoint_interval: 1, validation_interval: 1, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 1, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 2} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/fixed_endpoint_checkpoint_roles.json b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/fixed_endpoint_checkpoint_roles.json new file mode 100644 index 0000000000000000000000000000000000000000..aeaef7005708f1345da8150e6e8b342061d88e97 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/fixed_endpoint_checkpoint_roles.json @@ -0,0 +1,4 @@ +{ + "fixed_step_100k": "step_0100000.pt", + "fixed_final_100k": "step_0100000_final.pt" +} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject1_p005_geometry_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject1_p005_geometry_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ee91fe2635161fc925cf8c4209a1e2790b0b04aa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject1_p005_geometry_r640x368_s20260716.yaml @@ -0,0 +1,24 @@ +name: phase5_s2_oof_subject1_p005_geometry_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 5 + stage: 2 + class: preregistered_data_construction + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_fixed100k + oof_fold: 0 + heldout_subject: subject1 + train_manifest_sha256: 0b4fe0e970ab7db45a18176834c54586a3d613dd2b1c063ea04d5d8ea6e96aac + heldout_manifest_sha256: e5f1c714e64cbd86b6b604716c44143e2cd6e16aee6445033e46ef4333949293 + checkpoint_rule: fixed_final_100k_no_heldout_selection +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 100000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 100000} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject1_p005_geometry_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject1_p005_geometry_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fc0d614ba9e8c53dbfb5747223b5f61ca3fbded3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject1_p005_geometry_r640x368_s20260717.yaml @@ -0,0 +1,25 @@ +name: phase5_s2_oof_subject1_p005_geometry_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 5 + stage: 2 + class: preregistered_data_construction + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_fixed100k + oof_fold: 0 + heldout_subject: subject1 + train_manifest_sha256: 0b4fe0e970ab7db45a18176834c54586a3d613dd2b1c063ea04d5d8ea6e96aac + heldout_manifest_sha256: e5f1c714e64cbd86b6b604716c44143e2cd6e16aee6445033e46ef4333949293 + checkpoint_rule: fixed_final_100k_no_heldout_selection +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 100000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 100000} + diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject1_p005_geometry_r640x368_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject1_p005_geometry_r640x368_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca79e021ea29d53225c6253543ea8c9ecd23c5f7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject1_p005_geometry_r640x368_s20260718.yaml @@ -0,0 +1,25 @@ +name: phase5_s2_oof_subject1_p005_geometry_r640x368_s20260718 +seed: 20260718 +experiment: + phase: 5 + stage: 2 + class: preregistered_data_construction + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_fixed100k + oof_fold: 0 + heldout_subject: subject1 + train_manifest_sha256: 0b4fe0e970ab7db45a18176834c54586a3d613dd2b1c063ea04d5d8ea6e96aac + heldout_manifest_sha256: e5f1c714e64cbd86b6b604716c44143e2cd6e16aee6445033e46ef4333949293 + checkpoint_rule: fixed_final_100k_no_heldout_selection +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 100000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 100000} + diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject2_p005_geometry_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject2_p005_geometry_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b931e2d5bcc3aca252012e26040a073e3e7e8b6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject2_p005_geometry_r640x368_s20260716.yaml @@ -0,0 +1,25 @@ +name: phase5_s2_oof_subject2_p005_geometry_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 5 + stage: 2 + class: preregistered_data_construction + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_fixed100k + oof_fold: 1 + heldout_subject: subject2 + train_manifest_sha256: 7a21c688a3f624e13df580fe485c6795945bbef4d4412864c2e508ffc990a515 + heldout_manifest_sha256: 43f38def2d0651ae655cfba36f55666bcacbba2af2221d776bbc20c9f7aaed0c + checkpoint_rule: fixed_final_100k_no_heldout_selection +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 100000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 100000} + diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject2_p005_geometry_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject2_p005_geometry_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e44d1ab410171293e64f7f9390731d2395caae5b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject2_p005_geometry_r640x368_s20260717.yaml @@ -0,0 +1,24 @@ +name: phase5_s2_oof_subject2_p005_geometry_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 5 + stage: 2 + class: preregistered_data_construction + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_fixed100k + oof_fold: 1 + heldout_subject: subject2 + train_manifest_sha256: 7a21c688a3f624e13df580fe485c6795945bbef4d4412864c2e508ffc990a515 + heldout_manifest_sha256: 43f38def2d0651ae655cfba36f55666bcacbba2af2221d776bbc20c9f7aaed0c + checkpoint_rule: fixed_final_100k_no_heldout_selection +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 100000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 100000} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject2_p005_geometry_r640x368_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject2_p005_geometry_r640x368_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c010e61b1f03dfc9a8fffd405c5373af30e3ad7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject2_p005_geometry_r640x368_s20260718.yaml @@ -0,0 +1,25 @@ +name: phase5_s2_oof_subject2_p005_geometry_r640x368_s20260718 +seed: 20260718 +experiment: + phase: 5 + stage: 2 + class: preregistered_data_construction + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_fixed100k + oof_fold: 1 + heldout_subject: subject2 + train_manifest_sha256: 7a21c688a3f624e13df580fe485c6795945bbef4d4412864c2e508ffc990a515 + heldout_manifest_sha256: 43f38def2d0651ae655cfba36f55666bcacbba2af2221d776bbc20c9f7aaed0c + checkpoint_rule: fixed_final_100k_no_heldout_selection +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 100000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 100000} + diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6aedb2f046594c139a4da605c1eddfb638c9edb2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260716.yaml @@ -0,0 +1,25 @@ +name: phase5_s2_oof_subject3_p005_geometry_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 5 + stage: 2 + class: preregistered_data_construction + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_fixed100k + oof_fold: 2 + heldout_subject: subject3 + train_manifest_sha256: 1eaf0e571899d9469c4c5f054ade2e6a7d9d15c0acba62077ab938077ab62a65 + heldout_manifest_sha256: 363e9af06a074eef0c3861f5ec2e11d0fdb2159ac857644d3285e6bc93caa670 + checkpoint_rule: fixed_final_100k_no_heldout_selection +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 100000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 100000} + diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cf83b4653bd7cd1553994acf00a5f8eb27833efd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260717.yaml @@ -0,0 +1,25 @@ +name: phase5_s2_oof_subject3_p005_geometry_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 5 + stage: 2 + class: preregistered_data_construction + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_fixed100k + oof_fold: 2 + heldout_subject: subject3 + train_manifest_sha256: 1eaf0e571899d9469c4c5f054ade2e6a7d9d15c0acba62077ab938077ab62a65 + heldout_manifest_sha256: 363e9af06a074eef0c3861f5ec2e11d0fdb2159ac857644d3285e6bc93caa670 + checkpoint_rule: fixed_final_100k_no_heldout_selection +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 100000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 100000} + diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260718.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260718.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f9985b175a86529325ac814e5571f1a0d7484dfd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260718.yaml @@ -0,0 +1,24 @@ +name: phase5_s2_oof_subject3_p005_geometry_r640x368_s20260718 +seed: 20260718 +experiment: + phase: 5 + stage: 2 + class: preregistered_data_construction + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_fixed100k + oof_fold: 2 + heldout_subject: subject3 + train_manifest_sha256: 1eaf0e571899d9469c4c5f054ade2e6a7d9d15c0acba62077ab938077ab62a65 + heldout_manifest_sha256: 363e9af06a074eef0c3861f5ec2e11d0fdb2159ac857644d3285e6bc93caa670 + checkpoint_rule: fixed_final_100k_no_heldout_selection +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 100000, num_workers: 4, checkpoint_interval: 25000, validation_interval: 5000, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 500, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 100000} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260718_smoke2.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260718_smoke2.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e80bc17076f1f7ff571fa5ee6cb1de9688c3e4fc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage2/phase5_s2_oof_subject3_p005_geometry_r640x368_s20260718_smoke2.yaml @@ -0,0 +1,24 @@ +name: phase5_s2_oof_subject3_p005_geometry_r640x368_s20260718_smoke2 +seed: 20260718 +experiment: + phase: 5 + stage: 2 + class: engineering_smoke + matrix: subject_heldout_oof_coarse + variant: p005_photometric_r640x368_smoke2 + oof_fold: 2 + heldout_subject: subject3 + train_manifest_sha256: 1eaf0e571899d9469c4c5f054ade2e6a7d9d15c0acba62077ab938077ab62a65 + heldout_manifest_sha256: 363e9af06a074eef0c3861f5ec2e11d0fdb2159ac857644d3285e6bc93caa670 + checkpoint_rule: fixed_final_engineering_only +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: {encoder: dinov3, decoder_dim: 512, decoder_layers: 3, attention_heads: 8, decoder_mode: alternating, use_temporal: true, use_depth: true, depth_mode: geometry, depth_gate_mode: fixed, depth_gate_fixed_value: 0.5, use_rays: true, use_bimanual_interaction: true, predict_presence: true, require_mano: true, depth_gate_floor: 0.0, modality_dropout_prob: 0.05} +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: {dinov3_source: third_party/dinov3, dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3, mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano} +precision: bf16 +protocol: {max_steps: 2, num_workers: 0, checkpoint_interval: 1, validation_interval: 1, validation_batches: 1, learning_rate: 5.0e-5, min_learning_rate: 5.0e-6, warmup_steps: 1, early_stopping_patience: 0, validation_subset_manifest: null, lr_schedule_steps: 2} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_matched_coarse_continue25k_p005_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_matched_coarse_continue25k_p005_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..31ea4800eeafe9f8c9ff7f98d814a2eeb6d30d80 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_matched_coarse_continue25k_p005_r640x368_s20260716.yaml @@ -0,0 +1,70 @@ +name: phase5_s5_matched_coarse_continue25k_p005_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 5 + stage: 5 + class: preregistered_matched_control + variant: matched_coarse_continuation_25k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + matched_control_initialization: true + registered_axes: [structured_hand_refinement] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-06 + min_learning_rate: 5.0e-06 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_pose_refine25k_p005_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_pose_refine25k_p005_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b6358a721d9119628ddddf115065a4e9f37badda --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_pose_refine25k_p005_r640x368_s20260716.yaml @@ -0,0 +1,73 @@ +name: phase5_s5_structured_pose_refine25k_p005_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 5 + stage: 5 + class: preregistered_mechanism_screen + variant: structured_pose_shape_2d_refinement_25k + reference: phase5_s5_structured_refine25k_p005_r640x368_s20260716 + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + registered_axes: [structured_refine_translation] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + structured_hand_refinement: true + structured_refinement_detach_locations: true + structured_deformable_samples: 4 + structured_refine_translation: false +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-06 + min_learning_rate: 5.0e-06 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_pose_tiny2k_p005_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_pose_tiny2k_p005_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3680a3885f7bc6945d92749e839c7fa542af5c1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_pose_tiny2k_p005_r640x368_s20260716.yaml @@ -0,0 +1,66 @@ +name: phase5_s5_structured_pose_tiny2k_p005_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 5 + stage: 5 + class: engineering_tiny_overfit_gate + variant: structured_pose_shape_2d_refinement_tiny2k + reference: phase5_s5_structured_pose_refine25k_p005_r640x368_s20260716 + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + registered_axes: [structured_refine_translation, tiny_overfit] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + structured_hand_refinement: true + structured_refinement_detach_locations: true + structured_deformable_samples: 4 + structured_refine_translation: false +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 0 + checkpoint_interval: 1000 + validation_interval: 2000 + validation_batches: 1 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-05 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: null + lr_schedule_steps: 2000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_refine25k_p005_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_refine25k_p005_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb69f0c3e70412980e343e9d0c266d03370f5373 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_refine25k_p005_r640x368_s20260716.yaml @@ -0,0 +1,72 @@ +name: phase5_s5_structured_refine25k_p005_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 5 + stage: 5 + class: preregistered_mechanism_screen + variant: structured_hand_refinement_25k + reference: longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260716 + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + registered_axes: [structured_hand_refinement] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + structured_hand_refinement: true + structured_refinement_detach_locations: true + structured_deformable_samples: 4 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-06 + min_learning_rate: 5.0e-06 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_tiny2k_p005_r640x368_s20260716.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_tiny2k_p005_r640x368_s20260716.yaml new file mode 100644 index 0000000000000000000000000000000000000000..37bcb9fd1ec7f41fec8241c261e825cb1a5aa1ba --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage5/phase5_s5_structured_tiny2k_p005_r640x368_s20260716.yaml @@ -0,0 +1,65 @@ +name: phase5_s5_structured_tiny2k_p005_r640x368_s20260716 +seed: 20260716 +experiment: + phase: 5 + stage: 5 + class: engineering_tiny_overfit_gate + variant: structured_hand_refinement_tiny2k + reference: phase5_s5_structured_refine25k_p005_r640x368_s20260716 + coarse_checkpoint_sha256: 85d8e39743e8ce821105c3f0e7f2d5c7d1a80b4168e327f25ec148868976ed6a + registered_axes: [tiny_overfit] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.05 + structured_hand_refinement: true + structured_refinement_detach_locations: true + structured_deformable_samples: 4 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 0 + checkpoint_interval: 1000 + validation_interval: 2000 + validation_batches: 1 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-05 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: null + lr_schedule_steps: 2000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage6/phase5_s6_dinov3_last2_lr5e7_continue25k_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage6/phase5_s6_dinov3_last2_lr5e7_continue25k_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..332c475a9e6039f0a7fff9a7c039bf2cc1b0d12e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage6/phase5_s6_dinov3_last2_lr5e7_continue25k_p0_r640x368_s20260717.yaml @@ -0,0 +1,54 @@ +name: phase5_s6_dinov3_last2_lr5e7_continue25k_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 5 + stage: 6 + class: preregistered_single_seed_mechanism_screen + matrix: dinov3_base_last2_low_lr + variant: last2_lr5e7_continue25k + matched_control_initialization: true + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + dinov3_trainable_last_blocks: 2 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + deterministic_training: true + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-6 + backbone_learning_rate: 5.0e-7 + min_learning_rate: 5.0e-6 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage6/phase5_s6_dinov3_last2_lr5e7_smoke2_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage6/phase5_s6_dinov3_last2_lr5e7_smoke2_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f11c2ad42da3a6a76baa22cb859df9113bb62bcc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage6/phase5_s6_dinov3_last2_lr5e7_smoke2_p0_r640x368_s20260717.yaml @@ -0,0 +1,53 @@ +name: phase5_s6_dinov3_last2_lr5e7_smoke2_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 5 + stage: 6 + class: engineering_real_batch_smoke + matrix: dinov3_base_last2_low_lr + variant: last2_lr5e7_smoke2 + matched_control_initialization: true + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + dinov3_trainable_last_blocks: 2 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + deterministic_training: true + max_steps: 2 + num_workers: 0 + checkpoint_interval: 1 + validation_interval: 100 + validation_batches: 1 + learning_rate: 5.0e-6 + backbone_learning_rate: 5.0e-7 + min_learning_rate: 5.0e-6 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: null + lr_schedule_steps: 2 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage6/phase5_s6_frozen_continue25k_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage6/phase5_s6_frozen_continue25k_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cbf45c1b54228084565d513d1e5382244bdb6e12 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase5/stage6/phase5_s6_frozen_continue25k_p0_r640x368_s20260717.yaml @@ -0,0 +1,53 @@ +name: phase5_s6_frozen_continue25k_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 5 + stage: 6 + class: preregistered_matched_control + matrix: dinov3_base_last2_low_lr + variant: frozen_continue25k + matched_control_initialization: true + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + dinov3_trainable_last_blocks: 0 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + deterministic_training: true + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-6 + min_learning_rate: 5.0e-6 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage0/phase6_s0_t1_eval_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage0/phase6_s0_t1_eval_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9aec32aad331a15fa136fd3dbdf3b5ff90256bb8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage0/phase6_s0_t1_eval_p0_r640x368_s20260717.yaml @@ -0,0 +1,42 @@ +name: phase6_s0_t1_eval_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 6 + stage: 0 + class: frozen_checkpoint_validation_diagnostic + variant: single_frame_t1 + selection_use: none +data: + resolution_hw: [368, 640] + T: 1 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: false} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + role: frozen_official_validation_diagnostic + checkpoint_selection: phase5_seed17_step95k_frozen + official_validation_used_for_selection: false + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage2/phase6_s2_direct_xyz_control_continue25k_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage2/phase6_s2_direct_xyz_control_continue25k_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..09472296d6b7ee121f6ae86cbab86de99bef507e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage2/phase6_s2_direct_xyz_control_continue25k_p0_r640x368_s20260717.yaml @@ -0,0 +1,68 @@ +name: phase6_s2_direct_xyz_control_continue25k_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 6 + stage: 2 + class: preregistered_matched_control + variant: direct_xyz_continue25k + matched_control_initialization: true + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc + registered_axes: [translation_parameterization] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + translation_parameterization: direct_xyz +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_teacher: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 5000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-6 + min_learning_rate: 5.0e-6 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 + deterministic_training: true + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage2/phase6_s2_mixed_projection_continue25k_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage2/phase6_s2_mixed_projection_continue25k_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6590f0116efed406d76be7470fb445f1a713dc45 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage2/phase6_s2_mixed_projection_continue25k_p0_r640x368_s20260717.yaml @@ -0,0 +1,70 @@ +name: phase6_s2_mixed_projection_continue25k_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 6 + stage: 2 + class: preregistered_single_seed_mechanism_screen + variant: differentiable_mixed_projection_continue25k + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc + registered_axes: [translation_parameterization] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + translation_parameterization: mixed_projection + mixed_projection_minimum_support: 4 + mixed_projection_huber_delta_px: 16.0 + mixed_projection_irls_iterations: 5 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_teacher: 1.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 5000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-6 + min_learning_rate: 5.0e-6 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 + deterministic_training: true + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage2/phase6_s2_mixed_projection_tiny2k_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage2/phase6_s2_mixed_projection_tiny2k_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..81f2a3ec922044fd12cb5df67da4cc622c602a5e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage2/phase6_s2_mixed_projection_tiny2k_p0_r640x368_s20260717.yaml @@ -0,0 +1,70 @@ +name: phase6_s2_mixed_projection_tiny2k_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 6 + stage: 2 + class: engineering_tiny_overfit_gate + variant: differentiable_mixed_projection_tiny2k + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc + registered_axes: [translation_parameterization] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: false} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + translation_parameterization: mixed_projection + mixed_projection_minimum_support: 4 + mixed_projection_huber_delta_px: 16.0 + mixed_projection_irls_iterations: 5 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_teacher: 1.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 0 + checkpoint_interval: 1000 + validation_interval: 2000 + validation_batches: 1 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-5 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: null + lr_schedule_steps: 2000 + deterministic_training: true + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage3b/phase6_s3b_spatial_heatmap_continue25k_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage3b/phase6_s3b_spatial_heatmap_continue25k_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..26ba777db142014613cc0d99da24d8d7d8c36736 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage3b/phase6_s3b_spatial_heatmap_continue25k_p0_r640x368_s20260717.yaml @@ -0,0 +1,69 @@ +name: phase6_s3b_spatial_heatmap_continue25k_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 6 + stage: 3b + class: preregistered_single_seed_mechanism_screen + variant: spatial_heatmap_offset_continue25k + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc + registered_axes: [joint2d_parameterization] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + joint2d_parameterization: spatial_heatmap + heatmap_offset_enabled: true + heatmap_use_depth: true +loss: + joint2d: 1.0 + joint2d_teacher: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 5000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-6 + min_learning_rate: 5.0e-6 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 + deterministic_training: true + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage3b/phase6_s3b_spatial_heatmap_tiny2k_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage3b/phase6_s3b_spatial_heatmap_tiny2k_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d1dbc5acadcbb4025a28aaa5c153c8cdef3a4ac0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage3b/phase6_s3b_spatial_heatmap_tiny2k_p0_r640x368_s20260717.yaml @@ -0,0 +1,69 @@ +name: phase6_s3b_spatial_heatmap_tiny2k_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 6 + stage: 3b + class: engineering_tiny_overfit_gate + variant: spatial_heatmap_offset_tiny2k + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc + registered_axes: [joint2d_parameterization] +data: &data + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: false} +model: &model + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + joint2d_parameterization: spatial_heatmap + heatmap_offset_enabled: true + heatmap_use_depth: true +loss: &loss + joint2d: 1.0 + joint2d_teacher: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: &assets + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 0 + checkpoint_interval: 1000 + validation_interval: 2000 + validation_batches: 1 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-5 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: null + lr_schedule_steps: 2000 + deterministic_training: true + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage4/phase6_s4_structured_pose_continue25k_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage4/phase6_s4_structured_pose_continue25k_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ce5acc809019fb5597e7de2d818b75f16051287d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage4/phase6_s4_structured_pose_continue25k_p0_r640x368_s20260717.yaml @@ -0,0 +1,73 @@ +name: phase6_s4_structured_pose_continue25k_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 6 + stage: 4 + class: preregistered_single_seed_mechanism_screen + variant: structured_pose_shape_2d_p0_continue25k + matched_control: phase6_s2_direct_xyz_control_continue25k_p0_r640x368_s20260717 + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc + registered_axes: [structured_pose_shape_2d] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + translation_parameterization: direct_xyz + structured_hand_refinement: true + structured_refinement_detach_locations: true + structured_refinement_deterministic_detached_sampling: true + structured_deformable_samples: 4 + structured_refine_translation: false +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_teacher: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 25000 + num_workers: 4 + checkpoint_interval: 5000 + validation_interval: 5000 + validation_batches: 256 + learning_rate: 5.0e-6 + min_learning_rate: 5.0e-6 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json + lr_schedule_steps: 25000 + deterministic_training: true + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage4/phase6_s4_structured_pose_tiny2k_p0_r640x368_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage4/phase6_s4_structured_pose_tiny2k_p0_r640x368_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a9ced66dd70b235dfc47f2516ccaa75344c8885e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage4/phase6_s4_structured_pose_tiny2k_p0_r640x368_s20260717.yaml @@ -0,0 +1,71 @@ +name: phase6_s4_structured_pose_tiny2k_p0_r640x368_s20260717 +seed: 20260717 +experiment: + phase: 6 + stage: 4 + class: preregistered_train_only_mechanism_gate + variant: structured_pose_shape_2d_p0_tiny2k + coarse_checkpoint_sha256: 382510062ce0c1bd5e426a4564b16655f5db58cfc514122330304a284b85e8cc + registered_axes: [structured_pose_shape_2d, tiny_overfit] +data: + resolution_hw: [368, 640] + T: 8 + stride: 1 + batch_size: 1 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + translation_parameterization: direct_xyz + structured_hand_refinement: true + structured_refinement_detach_locations: true + structured_refinement_deterministic_detached_sampling: true + structured_deformable_samples: 4 + structured_refine_translation: false +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + translation_teacher: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 0 + checkpoint_interval: 1000 + validation_interval: 2000 + validation_batches: 1 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-5 + warmup_steps: 0 + early_stopping_patience: 0 + validation_subset_manifest: null + lr_schedule_steps: 2000 + deterministic_training: true + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage5/phase6_s5_frozen_bidirectional_stream_seed17.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage5/phase6_s5_frozen_bidirectional_stream_seed17.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b596b4e29cced418d54e25e0e49484a02428424f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage5/phase6_s5_frozen_bidirectional_stream_seed17.yaml @@ -0,0 +1,45 @@ +name: phase6_s5_frozen_bidirectional_stream_seed17 +seed: 20260717 +experiment: + phase: 6 + stage: 5 + class: frozen_checkpoint_length_generalization + variant: bidirectional_offline_overlap + selection_use: none +data: + resolution_hw: [368, 640] + T: 1 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: false} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + mode: offline + windows: [8, 16] + stitching: center + stride_fraction: 0.5 + official_validation_used_for_selection: false + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage5/phase6_s5_frozen_causal_stream_seed17.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage5/phase6_s5_frozen_causal_stream_seed17.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7bd207c1d4086f771869ec65a65a5b87d2ac69cc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase6/stage5/phase6_s5_frozen_causal_stream_seed17.yaml @@ -0,0 +1,44 @@ +name: phase6_s5_frozen_causal_stream_seed17 +seed: 20260717 +experiment: + phase: 6 + stage: 5 + class: frozen_checkpoint_causal_screen + variant: causal_rolling_window + selection_use: none +data: + resolution_hw: [368, 640] + T: 1 + stride: 1 + batch_size: 1 + photometric_augmentation: {enabled: false} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: causal +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + mode: causal + windows: [4, 8, 16] + primary_window: 8 + official_validation_used_for_selection: false + official_test_used: false diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/adaptation/frozen_e40_step100k_v1/freeze.json b/home/wuyifan/EgoNet_train_20261008/configs/phase7/adaptation/frozen_e40_step100k_v1/freeze.json new file mode 100644 index 0000000000000000000000000000000000000000..065c696e374c132f30bd34ccf4eeaf5868eeec22 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/adaptation/frozen_e40_step100k_v1/freeze.json @@ -0,0 +1,27 @@ +{ + "status": "adaptation_configs_frozen", + "configs": { + "A1": { + "path": "/home/jiasen/foundation_hand/configs/phase7/adaptation/frozen_e40_step100k_v1/phase7_a1_scale100k_s20260717.yaml", + "sha256": "55dea8b9425908e23b92bff70b98d978a9389f1c6bed4905f67663cb788c6a7d" + }, + "A2": { + "path": "/home/jiasen/foundation_hand/configs/phase7/adaptation/frozen_e40_step100k_v1/phase7_a2_scale100k_s20260717.yaml", + "sha256": "517b3783c2207a7ffe7eedfd9779241f89ea738869931b54dd4a534c77d0a93d" + } + }, + "external_selection": { + "path": "/home/jiasen/foundation_hand/artifacts/phase7/selection/final_external_generalist/selection.json", + "sha256": "c37f9d685cb5cbca8f39401ffdd0422e155465d190d62c0dd2bdb8049ce7930d" + }, + "strict_zero_shot_state": { + "path": "/SSD3/jiasen/foundation_hand/phase7_artifacts/queues/h2o_strict_zero_shot_v2_state.json", + "sha256": "f910cb30b8dd6d578218535a2fb3d9abbc05160b6ae96829267d4c2aa5404b05" + }, + "h2o_train_split": { + "path": "/home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/split.json", + "sha256": "67ec7ef8af2f53c4c0d82b2d8dc0f6a705ffd9ee176ad41faa578d1811dfa14a" + }, + "h2o_official_validation_used_for_selection": false, + "official_test_used": false +} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/adaptation/frozen_e40_step100k_v1/phase7_a1_scale100k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/adaptation/frozen_e40_step100k_v1/phase7_a1_scale100k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d0bd2cc57ea485eacf2a246af8043e566df6b8a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/adaptation/frozen_e40_step100k_v1/phase7_a1_scale100k_s20260717.yaml @@ -0,0 +1,87 @@ +name: phase7_a1_scale100k_s20260717 +seed: 20260717 +experiment: + phase: 7 + branch: h2o_adaptation + stage: adaptation_scale_100k + condition: A1 + uses_h2o_training_data: true + initialization_checkpoint_sha256: a7b39702bd360d44d2ed936c8e282940b7e6adfaa5cb4ba9ce96100511b7b92d + initialization_checkpoint_step: 100000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 + sources: + - dataset: H2O + split_role: official_train + weight: 1.0 + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl + K_input_dropout: 0.0 + validation_sources: + - dataset: H2O + split_role: train_group_heldout + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/adaptation/frozen_e40_step100k_v1/phase7_a2_scale100k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/adaptation/frozen_e40_step100k_v1/phase7_a2_scale100k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6c08c2a15904c8db3741b5590bb03ba1408a73f6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/adaptation/frozen_e40_step100k_v1/phase7_a2_scale100k_s20260717.yaml @@ -0,0 +1,102 @@ +name: phase7_a2_scale100k_s20260717 +seed: 20260717 +experiment: + phase: 7 + branch: h2o_adaptation + stage: adaptation_scale_100k + condition: A2 + uses_h2o_training_data: true + initialization_checkpoint_sha256: a7b39702bd360d44d2ed936c8e282940b7e6adfaa5cb4ba9ce96100511b7b92d + initialization_checkpoint_step: 100000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: + - 368 + - 640 + T: 8 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 + sources: + - dataset: H2O + split_role: official_train + weight: 0.5 + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl + K_input_dropout: 0.0 + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl + weight: 0.2 + K_input_dropout: 0.3 + split_role: external_train + - dataset: HOI4D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl + weight: 0.2 + K_input_dropout: 0.0 + split_role: external_train + - dataset: ARCTIC + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl + weight: 0.1 + K_input_dropout: 0.0 + split_role: external_train + validation_sources: + - dataset: H2O + split_role: train_group_heldout + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_health2k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_health2k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a41d7995c8df15d3e4ba7abf9151adcf56d37fc1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_health2k_s20260717.yaml @@ -0,0 +1,56 @@ +name: phase7_e100_hot3d_health2k_s20260717 +seed: 20260717 +experiment: + phase: 7 + stage: external_health_2k + class: preregistered_health + branch: external_only + mixture: E100 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_health512_v1/cache_manifest.jsonl + weight: 1.0 + K_input_dropout: 0.3 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2000 + num_workers: 4 + checkpoint_interval: 500 + validation_interval: 500 + validation_batches: 32 + telemetry_interval: 100 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 100 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_resume4_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_resume4_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..16e0c827e5cf5b0f4f8b0aaa88d5acbe5850cb88 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_resume4_s20260717.yaml @@ -0,0 +1,55 @@ +name: phase7_e100_hot3d_resume4_s20260717 +seed: 20260717 +experiment: + phase: 7 + stage: exact_resume_audit + class: engineering_audit + branch: external_only + mixture: E100 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_smoke32_v1/cache_manifest.jsonl + weight: 1.0 + K_input_dropout: 0.3 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 4 + num_workers: 2 + checkpoint_interval: 2 + validation_interval: 4 + validation_batches: 1 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-5 + warmup_steps: 0 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_screen10k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_screen10k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..043bba801c9334e24e7353b7945b95280cd3d794 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_screen10k_s20260717.yaml @@ -0,0 +1,56 @@ +name: phase7_e100_hot3d_screen10k_s20260717 +seed: 20260717 +experiment: + phase: 7 + stage: external_matched_screen_10k + class: preregistered_external_only + branch: external_only + mixture: E100 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_health512_v1/cache_manifest.jsonl + weight: 1.0 + K_input_dropout: 0.3 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 10000 + num_workers: 4 + checkpoint_interval: 500 + validation_interval: 500 + validation_batches: 32 + telemetry_interval: 100 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 100 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_smoke2_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_smoke2_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5d13f483a7e950fdbc895e354c6dea38a0b6de4a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_hot3d_smoke2_s20260717.yaml @@ -0,0 +1,73 @@ +name: phase7_e100_hot3d_smoke2_s20260717 +seed: 20260717 +experiment: + phase: 7 + stage: external_loader_smoke + class: engineering_smoke + branch: external_only + mixture: E100 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_smoke32_v1/cache_manifest.jsonl + weight: 1.0 + K_input_dropout: 0.3 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 2 + num_workers: 2 + checkpoint_interval: 1 + validation_interval: 1 + validation_batches: 1 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-5 + warmup_steps: 0 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_scale100k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_scale100k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..87ea1c0d270f28ade68322aad5f1c0e0f9e9be0f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e100_scale100k_s20260717.yaml @@ -0,0 +1,56 @@ +name: phase7_e100_scale100k_s20260717 +seed: 20260717 +experiment: + phase: 7 + stage: external_scale_100k + class: preregistered_external_only + branch: external_only + mixture: E100 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl + weight: 1.0 + K_input_dropout: 0.3 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: false + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e40_scale100k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e40_scale100k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9a08eb63b8b166623f91ddbc8390f28f7e727637 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e40_scale100k_s20260717.yaml @@ -0,0 +1,64 @@ +name: phase7_e40_scale100k_s20260717 +seed: 20260717 +experiment: + phase: 7 + stage: external_scale_100k + class: preregistered_external_only + branch: external_only + mixture: E40 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl + weight: 0.4 + K_input_dropout: 0.3 + - dataset: HOI4D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl + weight: 0.4 + K_input_dropout: 0.0 + - dataset: ARCTIC + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl + weight: 0.2 + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e40_screen10k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e40_screen10k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..797f24b9349852f6b0fecf8478d9445038a5abc6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e40_screen10k_s20260717.yaml @@ -0,0 +1,64 @@ +name: phase7_e40_screen10k_s20260717 +seed: 20260717 +experiment: + phase: 7 + stage: external_matched_screen_10k + class: preregistered_external_only + branch: external_only + mixture: E40 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_health512_v1/cache_manifest.jsonl + weight: 0.4 + K_input_dropout: 0.3 + - dataset: HOI4D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_health512_v1/cache_manifest.jsonl + weight: 0.4 + K_input_dropout: 0.0 + - dataset: ARCTIC + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_health512_v1/cache_manifest.jsonl + weight: 0.2 + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 10000 + num_workers: 4 + checkpoint_interval: 500 + validation_interval: 500 + validation_batches: 32 + telemetry_interval: 100 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 100 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e70_scale100k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e70_scale100k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d7952beb4000692bd1967f1ae8c63c533e4c6985 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e70_scale100k_s20260717.yaml @@ -0,0 +1,64 @@ +name: phase7_e70_scale100k_s20260717 +seed: 20260717 +experiment: + phase: 7 + stage: external_scale_100k + class: preregistered_external_only + branch: external_only + mixture: E70 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl + weight: 0.7 + K_input_dropout: 0.3 + - dataset: HOI4D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl + weight: 0.2 + K_input_dropout: 0.0 + - dataset: ARCTIC + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl + weight: 0.1 + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e70_screen10k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e70_screen10k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bbc42dd351de766f7c6ef00f7c749b8d1f2f744a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/external/phase7_e70_screen10k_s20260717.yaml @@ -0,0 +1,64 @@ +name: phase7_e70_screen10k_s20260717 +seed: 20260717 +experiment: + phase: 7 + stage: external_matched_screen_10k + class: preregistered_external_only + branch: external_only + mixture: E70 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_health512_v1/cache_manifest.jsonl + weight: 0.7 + K_input_dropout: 0.3 + - dataset: HOI4D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_health512_v1/cache_manifest.jsonl + weight: 0.2 + K_input_dropout: 0.0 + - dataset: ARCTIC + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_health512_v1/cache_manifest.jsonl + weight: 0.1 + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 10000 + num_workers: 4 + checkpoint_interval: 500 + validation_interval: 500 + validation_batches: 32 + telemetry_interval: 100 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 100 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase7/inference/phase7_e40_step100k_causal_w8.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase7/inference/phase7_e40_step100k_causal_w8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d721e8ede09748b035167059ec27f530313bed7f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase7/inference/phase7_e40_step100k_causal_w8.yaml @@ -0,0 +1,82 @@ +name: phase7_e40_step100k_causal_w8_inference_only +seed: 20260717 +experiment: + phase: 7 + stage: frozen_external_causal_inference_audit + class: inference_only_causal_mask_not_finetuned + branch: external_only + mixture: E40 + uses_h2o_training_data: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: + enabled: false + probability: 0.0 + brightness: 0.0 + contrast: 0.0 + saturation: 0.0 + hue: 0.0 + sources: + - dataset: HOT3D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl + weight: 0.4 + K_input_dropout: 0.3 + - dataset: HOI4D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl + weight: 0.4 + K_input_dropout: 0.0 + - dataset: ARCTIC + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl + weight: 0.2 + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: causal +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage0/phase8_b2_neutral_h2o20k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage0/phase8_b2_neutral_h2o20k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..27751f6ddcb23946342e44b397480ebe7d0a6ed9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage0/phase8_b2_neutral_h2o20k_s20260717.yaml @@ -0,0 +1,84 @@ +name: phase8_b2_neutral_h2o20k_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_neutral_control + stage: comparable_h2o_baselines + condition: B2 + uses_h2o_training_data: true + neutral_task_heads: true + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 + sources: + - dataset: H2O + split_role: official_train + weight: 1.0 + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl + K_input_dropout: 0.0 + validation_sources: + - dataset: H2O + split_role: train_group_heldout + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 20000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-05 + min_learning_rate: 5.0e-06 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage1/phase8_s_arctic_scale100k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage1/phase8_s_arctic_scale100k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a966449a7a21888ca4ceef9953c0146a2d494883 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage1/phase8_s_arctic_scale100k_s20260717.yaml @@ -0,0 +1,57 @@ +name: phase8_s_arctic_scale100k_s20260717 +seed: 20260717 +experiment: + phase: 8 + stage: external_specialist_100k + class: preregistered_external_only + branch: external_only + mixture: S_ARCTIC + uses_h2o_training_data: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: ARCTIC + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl + weight: 1.0 + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage1/phase8_s_hoi_scale100k_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage1/phase8_s_hoi_scale100k_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..862f574478918282a15baff5b9aea1a0f43ffa58 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage1/phase8_s_hoi_scale100k_s20260717.yaml @@ -0,0 +1,57 @@ +name: phase8_s_hoi_scale100k_s20260717 +seed: 20260717 +experiment: + phase: 8 + stage: external_specialist_100k + class: preregistered_external_only + branch: external_only + mixture: S_HOI + uses_h2o_training_data: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: HOI4D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl + weight: 1.0 + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional +loss: {joint2d: 1.0, joint3d_camera: 10.0, vertices_camera: 1.0, local_pose: 1.0, global_orientation: 1.0, shape: 0.1, translation: 10.0, reprojection: 1.0, temporal_velocity: 0.1, temporal_acceleration: 0.05, bimanual_relative_wrist: 1.0, presence: 0.0} +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage5/phase8_r1_ray_rgb_base_z_e40_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage5/phase8_r1_ray_rgb_base_z_e40_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..71844fed499f94fa5f0eb91b4a49453b23571ffc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage5/phase8_r1_ray_rgb_base_z_e40_s20260717.yaml @@ -0,0 +1,80 @@ +name: phase8_r1_ray_rgb_base_z_e40_s20260717 +seed: 20260717 +experiment: + phase: 8 + stage: ray_depth_matched_screen + class: preregistered_external_only + branch: external_only + mixture: E40 + condition: R1 + uses_h2o_training_data: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: HOT3D, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl, weight: 0.4, K_input_dropout: 0.3} + - {dataset: HOI4D, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl, weight: 0.4, K_input_dropout: 0.0} + - {dataset: ARCTIC, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl, weight: 0.2, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + translation_parameterization: ray_depth_residual + ray_depth_enable_residual: false + ray_depth_residual_max_m: 0.20 + ray_depth_confidence_initial_logit: -4.0 + ray_depth_sample_radius_px: 8.0 + ray_depth_minimum_support: 3 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + wrist_ray: 1.0 + robust_log_z: 5.0 + z_tail_cvar: 0.0 + depth_confidence_calibration: 0.0 + paired_modality_no_harm: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage5/phase8_r2_ray_depth_e40_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage5/phase8_r2_ray_depth_e40_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..28acb8c74572cc976b05497fa61e8e70ff9c83fa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage5/phase8_r2_ray_depth_e40_s20260717.yaml @@ -0,0 +1,80 @@ +name: phase8_r2_ray_depth_e40_s20260717 +seed: 20260717 +experiment: + phase: 8 + stage: ray_depth_matched_screen + class: preregistered_external_only + branch: external_only + mixture: E40 + condition: R2 + uses_h2o_training_data: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: HOT3D, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl, weight: 0.4, K_input_dropout: 0.3} + - {dataset: HOI4D, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl, weight: 0.4, K_input_dropout: 0.0} + - {dataset: ARCTIC, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl, weight: 0.2, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + translation_parameterization: ray_depth_residual + ray_depth_enable_residual: true + ray_depth_residual_max_m: 0.20 + ray_depth_confidence_initial_logit: -4.0 + ray_depth_sample_radius_px: 8.0 + ray_depth_minimum_support: 3 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + wrist_ray: 1.0 + robust_log_z: 5.0 + z_tail_cvar: 0.0 + depth_confidence_calibration: 0.5 + paired_modality_no_harm: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage5/phase8_r3_ray_depth_robust_e40_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage5/phase8_r3_ray_depth_robust_e40_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fc19e86a4ef44df5995fa81f4aa1f5d02ae0803e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage5/phase8_r3_ray_depth_robust_e40_s20260717.yaml @@ -0,0 +1,85 @@ +name: phase8_r3_ray_depth_robust_e40_s20260717 +seed: 20260717 +experiment: + phase: 8 + stage: ray_depth_matched_screen + class: preregistered_external_only + branch: external_only + mixture: E40 + condition: R3 + uses_h2o_training_data: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: HOT3D, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl, weight: 0.4, K_input_dropout: 0.3} + - dataset: HOI4D + cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl + weight: 0.4 + K_input_dropout: 0.0 + depth_input_dropout: 0.25 + depth_corruption_probability: 0.3333333333333333 + - {dataset: ARCTIC, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl, weight: 0.2, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + translation_parameterization: ray_depth_residual + ray_depth_enable_residual: true + ray_depth_residual_max_m: 0.20 + ray_depth_confidence_initial_logit: -4.0 + ray_depth_sample_radius_px: 8.0 + ray_depth_minimum_support: 3 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + wrist_ray: 1.0 + robust_log_z: 5.0 + z_tail_cvar: 0.5 + depth_confidence_calibration: 0.5 + paired_modality_no_harm: 1.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h1_direct_g200_h2o_only_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h1_direct_g200_h2o_only_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7d72c4fcb3103fdfa0c25b33e3248a8a7136b52a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h1_direct_g200_h2o_only_s20260717.yaml @@ -0,0 +1,86 @@ +name: phase8_h1_direct_g200_h2o_only_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: exposure_matched_adaptation + condition: H1_direct_g200_h2o_only + uses_h2o_training_data: true + initialization_checkpoint_sha256: 6aef9457bf010cc40e1a0a1b9ae834f512333fba01b2593480742c451118aa68 + initialization_checkpoint_step: 200000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: + enabled: true + probability: 0.8 + brightness: 0.2 + contrast: 0.2 + saturation: 0.2 + hue: 0.05 + sources: + - dataset: H2O + split_role: official_train + weight: 1.0 + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl + K_input_dropout: 0.0 + validation_sources: + - dataset: H2O + split_role: train_group_heldout + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl + K_input_dropout: 0.0 +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h1_ray_r2step50_h2o_only_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h1_ray_r2step50_h2o_only_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3778190d356436a8e26deff97cbfd6fae59895a1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h1_ray_r2step50_h2o_only_s20260717.yaml @@ -0,0 +1,87 @@ +name: phase8_h1_ray_r2step50_h2o_only_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: exposure_matched_adaptation + condition: H1_ray_r2step50_h2o_only + uses_h2o_training_data: true + initialization_checkpoint_sha256: b9a6c10a01e1a076f69a015072442346b9a1d5c5368bbb854e86a94acd4dc765 + initialization_checkpoint_step: 50000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: H2O + split_role: official_train + weight: 1.0 + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl + K_input_dropout: 0.0 + validation_sources: + - {dataset: H2O, split_role: train_group_heldout, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: ray_depth_residual + ray_depth_enable_residual: true + ray_depth_residual_max_m: 0.20 + ray_depth_confidence_initial_logit: -4.0 + ray_depth_sample_radius_px: 8.0 + ray_depth_minimum_support: 3 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + wrist_ray: 1.0 + robust_log_z: 5.0 + z_tail_cvar: 0.0 + depth_confidence_calibration: 0.5 + paired_modality_no_harm: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h2_direct_g200_h2o80_replay20_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h2_direct_g200_h2o80_replay20_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5a251b137ba9a4f818ec29b14be2d0486c97a9f8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h2_direct_g200_h2o80_replay20_s20260717.yaml @@ -0,0 +1,76 @@ +name: phase8_h2_direct_g200_h2o80_replay20_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: exposure_matched_adaptation + condition: H2_direct_g200_h2o80_replay20 + uses_h2o_training_data: true + initialization_checkpoint_sha256: 6aef9457bf010cc40e1a0a1b9ae834f512333fba01b2593480742c451118aa68 + initialization_checkpoint_step: 200000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: H2O, split_role: official_train, weight: 0.80, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl, K_input_dropout: 0.0} + - {dataset: HOT3D, split_role: external_train, weight: 0.08, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl, K_input_dropout: 0.3} + - {dataset: HOI4D, split_role: external_train, weight: 0.08, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + - {dataset: ARCTIC, split_role: external_train, weight: 0.04, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + validation_sources: + - {dataset: H2O, split_role: train_group_heldout, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl, K_input_dropout: 0.0} +model: &model + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: &loss + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: &assets + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: &protocol + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h2_ray_r2step50_h2o80_replay20_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h2_ray_r2step50_h2o80_replay20_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..56019fb1f4a61e034dbe708c17d3353092b73297 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h2_ray_r2step50_h2o80_replay20_s20260717.yaml @@ -0,0 +1,86 @@ +name: phase8_h2_ray_r2step50_h2o80_replay20_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: exposure_matched_adaptation + condition: H2_ray_r2step50_h2o80_replay20 + uses_h2o_training_data: true + initialization_checkpoint_sha256: b9a6c10a01e1a076f69a015072442346b9a1d5c5368bbb854e86a94acd4dc765 + initialization_checkpoint_step: 50000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: H2O, split_role: official_train, weight: 0.80, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl, K_input_dropout: 0.0} + - {dataset: HOT3D, split_role: external_train, weight: 0.08, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl, K_input_dropout: 0.3} + - {dataset: HOI4D, split_role: external_train, weight: 0.08, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + - {dataset: ARCTIC, split_role: external_train, weight: 0.04, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + validation_sources: + - {dataset: H2O, split_role: train_group_heldout, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl, K_input_dropout: 0.0} +model: &model + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: ray_depth_residual + ray_depth_enable_residual: true + ray_depth_residual_max_m: 0.20 + ray_depth_confidence_initial_logit: -4.0 + ray_depth_sample_radius_px: 8.0 + ray_depth_minimum_support: 3 +loss: &loss + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + wrist_ray: 1.0 + robust_log_z: 5.0 + z_tail_cvar: 0.0 + depth_confidence_calibration: 0.5 + paired_modality_no_harm: 0.0 +assets: &assets + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: &protocol + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h3_direct_g200_h2o50_replay50_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h3_direct_g200_h2o50_replay50_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a545bf538f9f366635eedb36fe8830e8258f8a9b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h3_direct_g200_h2o50_replay50_s20260717.yaml @@ -0,0 +1,76 @@ +name: phase8_h3_direct_g200_h2o50_replay50_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: exposure_matched_adaptation + condition: H3_direct_g200_h2o50_replay50 + uses_h2o_training_data: true + initialization_checkpoint_sha256: 6aef9457bf010cc40e1a0a1b9ae834f512333fba01b2593480742c451118aa68 + initialization_checkpoint_step: 200000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: H2O, split_role: official_train, weight: 0.50, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl, K_input_dropout: 0.0} + - {dataset: HOT3D, split_role: external_train, weight: 0.20, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl, K_input_dropout: 0.3} + - {dataset: HOI4D, split_role: external_train, weight: 0.20, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + - {dataset: ARCTIC, split_role: external_train, weight: 0.10, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + validation_sources: + - {dataset: H2O, split_role: train_group_heldout, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h3_ray_r2step50_h2o50_replay50_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h3_ray_r2step50_h2o50_replay50_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a3e3fb405fab6ce4c155ea938079aafec8d61b4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h3_ray_r2step50_h2o50_replay50_s20260717.yaml @@ -0,0 +1,86 @@ +name: phase8_h3_ray_r2step50_h2o50_replay50_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: exposure_matched_adaptation + condition: H3_ray_r2step50_h2o50_replay50 + uses_h2o_training_data: true + initialization_checkpoint_sha256: b9a6c10a01e1a076f69a015072442346b9a1d5c5368bbb854e86a94acd4dc765 + initialization_checkpoint_step: 50000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: H2O, split_role: official_train, weight: 0.50, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl, K_input_dropout: 0.0} + - {dataset: HOT3D, split_role: external_train, weight: 0.20, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl, K_input_dropout: 0.3} + - {dataset: HOI4D, split_role: external_train, weight: 0.20, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + - {dataset: ARCTIC, split_role: external_train, weight: 0.10, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_scale10000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + validation_sources: + - {dataset: H2O, split_role: train_group_heldout, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: ray_depth_residual + ray_depth_enable_residual: true + ray_depth_residual_max_m: 0.20 + ray_depth_confidence_initial_logit: -4.0 + ray_depth_sample_radius_px: 8.0 + ray_depth_minimum_support: 3 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + wrist_ray: 1.0 + robust_log_z: 5.0 + z_tail_cvar: 0.0 + depth_confidence_calibration: 0.5 + paired_modality_no_harm: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h4_direct_g200_h2o_dropout005_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h4_direct_g200_h2o_dropout005_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d1a97c53355f4221b851932b736a397cb44ce996 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h4_direct_g200_h2o_dropout005_s20260717.yaml @@ -0,0 +1,78 @@ +name: phase8_h4_direct_g200_h2o_dropout005_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: exposure_matched_adaptation + condition: H4_direct_g200_h2o_dropout005 + uses_h2o_training_data: true + initialization_checkpoint_sha256: 6aef9457bf010cc40e1a0a1b9ae834f512333fba01b2593480742c451118aa68 + initialization_checkpoint_step: 200000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: H2O + split_role: official_train + weight: 1.0 + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl + K_input_dropout: 0.05 + depth_input_dropout: 0.05 + validation_sources: + - {dataset: H2O, split_role: train_group_heldout, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h4_ray_r2step50_h2o_dropout005_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h4_ray_r2step50_h2o_dropout005_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a1ee045352f7fd3c1eaef0535334537e2dc1ced --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h4_ray_r2step50_h2o_dropout005_s20260717.yaml @@ -0,0 +1,88 @@ +name: phase8_h4_ray_r2step50_h2o_dropout005_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: exposure_matched_adaptation + condition: H4_ray_r2step50_h2o_dropout005 + uses_h2o_training_data: true + initialization_checkpoint_sha256: b9a6c10a01e1a076f69a015072442346b9a1d5c5368bbb854e86a94acd4dc765 + initialization_checkpoint_step: 50000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - dataset: H2O + split_role: official_train + weight: 1.0 + cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl + K_input_dropout: 0.05 + depth_input_dropout: 0.05 + validation_sources: + - {dataset: H2O, split_role: train_group_heldout, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: ray_depth_residual + ray_depth_enable_residual: true + ray_depth_residual_max_m: 0.20 + ray_depth_confidence_initial_logit: -4.0 + ray_depth_sample_radius_px: 8.0 + ray_depth_minimum_support: 3 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + wrist_ray: 1.0 + robust_log_z: 5.0 + z_tail_cvar: 0.0 + depth_confidence_calibration: 0.5 + paired_modality_no_harm: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h5_direct_g200_staged_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h5_direct_g200_staged_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5c829e57d32ff5cf1be85e860e02849ae513c252 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h5_direct_g200_staged_s20260717.yaml @@ -0,0 +1,77 @@ +name: phase8_h5_direct_g200_staged_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: staged_translation_then_decoder + condition: H5_direct_g200_staged + uses_h2o_training_data: true + initialization_checkpoint_sha256: 6aef9457bf010cc40e1a0a1b9ae834f512333fba01b2593480742c451118aa68 + initialization_checkpoint_step: 200000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: H2O, split_role: official_train, weight: 1.0, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl, K_input_dropout: 0.0} + validation_sources: + - {dataset: H2O, split_role: train_group_heldout, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 + staged_adaptation: + initial_trainable_prefixes: [depth_encoder., translation_head.] + unfreeze_step: 5000 + unfrozen_learning_rate_scale: 0.1 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h5_ray_r2step50_staged_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h5_ray_r2step50_staged_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d294e001da0e32d6dc3f4e829b060f62a74be32d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage6/phase8_h5_ray_r2step50_staged_s20260717.yaml @@ -0,0 +1,92 @@ +name: phase8_h5_ray_r2step50_staged_s20260717 +seed: 20260717 +experiment: + phase: 8 + branch: h2o_adaptation + stage: staged_translation_then_decoder + condition: H5_ray_r2step50_staged + uses_h2o_training_data: true + initialization_checkpoint_sha256: b9a6c10a01e1a076f69a015072442346b9a1d5c5368bbb854e86a94acd4dc765 + initialization_checkpoint_step: 50000 + selection_split: h2o_train_group_heldout_only + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: H2O, split_role: official_train, weight: 1.0, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_fit.jsonl, K_input_dropout: 0.0} + validation_sources: + - {dataset: H2O, split_role: train_group_heldout, cache_manifest: /home/jiasen/foundation_hand/artifacts/phase7/manifests/h2o_train_group_cv_v1/train_group_heldout.jsonl, K_input_dropout: 0.0} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: ray_depth_residual + ray_depth_enable_residual: true + ray_depth_residual_max_m: 0.20 + ray_depth_confidence_initial_logit: -4.0 + ray_depth_sample_radius_px: 8.0 + ray_depth_minimum_support: 3 +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 + wrist_ray: 1.0 + robust_log_z: 5.0 + z_tail_cvar: 0.0 + depth_confidence_calibration: 0.5 + paired_modality_no_harm: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 + staged_adaptation: + initial_trainable_prefixes: + - depth_encoder. + - ray_depth_log_z_head. + - ray_depth_delta_head. + - ray_depth_confidence_head. + - translation_head. + unfreeze_step: 5000 + unfrozen_learning_rate_scale: 0.1 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage7/phase8_l0_left_sampler_control_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage7/phase8_l0_left_sampler_control_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3a2b5c7c459ad90bd0a8896c1e226bb257be2375 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage7/phase8_l0_left_sampler_control_s20260717.yaml @@ -0,0 +1,77 @@ +name: phase8_l0_left_sampler_control_s20260717 +seed: 20260717 +experiment: + phase: 8 + stage: left_geometry_screen10k + class: preregistered_external_only + branch: external_only + condition: L0_sampler_only + mixture: HOT40_HOIgeneral20_HOIleft20_ARCTIC20 + uses_h2o_training_data: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: HOT3D, source_id: HOT3D_general, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl, weight: 0.40, K_input_dropout: 0.3, joint3d_root_relative_scope: disabled} + - {dataset: HOI4D, source_id: HOI4D_general, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl, weight: 0.20, K_input_dropout: 0.0, joint3d_root_relative_scope: disabled} + - {dataset: HOI4D, source_id: HOI4D_left, cache_manifest: /SSD3/jiasen/foundation_hand/phase8_artifacts/cache/hoi4d_left2048_v2/cache_manifest.jsonl, weight: 0.20, K_input_dropout: 0.0, joint3d_root_relative_scope: disabled} + - {dataset: ARCTIC, source_id: ARCTIC_left, cache_manifest: /SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/arctic_left_root_relative_sidecars_v1/cache_manifest.jsonl, weight: 0.20, K_input_dropout: 0.0, joint3d_root_relative_scope: disabled} + validation_sources: + - {dataset: HOT3D, source_id: HOT3D_heldout, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl, K_input_dropout: 0.3, joint3d_root_relative_scope: disabled} + - {dataset: HOI4D, source_id: HOI4D_heldout_left, cache_manifest: /SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/hoi4d_heldout_left_root_relative_sidecars_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: left_only} + - {dataset: ARCTIC, source_id: ARCTIC_heldout_left, cache_manifest: /SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/arctic_p2_val_left_root_relative_sidecars_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: left_only} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + joint3d_root_relative: 0.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage7/phase8_l1_left_root_relative_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage7/phase8_l1_left_root_relative_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b3c2fc1ed5947d8fade2030f919b3e73db3b2afe --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase8/stage7/phase8_l1_left_root_relative_s20260717.yaml @@ -0,0 +1,77 @@ +name: phase8_l1_left_root_relative_s20260717 +seed: 20260717 +experiment: + phase: 8 + stage: left_geometry_screen10k + class: preregistered_external_only + branch: external_only + condition: L1_left_root_relative + mixture: HOT40_HOIgeneral20_HOIleft20_ARCTIC20 + uses_h2o_training_data: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: HOT3D, source_id: HOT3D_general, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl, weight: 0.40, K_input_dropout: 0.3, joint3d_root_relative_scope: disabled} + - {dataset: HOI4D, source_id: HOI4D_general, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_scale10000_v1/cache_manifest.jsonl, weight: 0.20, K_input_dropout: 0.0, joint3d_root_relative_scope: disabled} + - {dataset: HOI4D, source_id: HOI4D_left, cache_manifest: /SSD3/jiasen/foundation_hand/phase8_artifacts/cache/hoi4d_left2048_v2/cache_manifest.jsonl, weight: 0.20, K_input_dropout: 0.0, joint3d_root_relative_scope: left_only} + - {dataset: ARCTIC, source_id: ARCTIC_left, cache_manifest: /SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/arctic_left_root_relative_sidecars_v1/cache_manifest.jsonl, weight: 0.20, K_input_dropout: 0.0, joint3d_root_relative_scope: left_only} + validation_sources: + - {dataset: HOT3D, source_id: HOT3D_heldout, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl, K_input_dropout: 0.3, joint3d_root_relative_scope: disabled} + - {dataset: HOI4D, source_id: HOI4D_heldout_left, cache_manifest: /SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/hoi4d_heldout_left_root_relative_sidecars_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: left_only} + - {dataset: ARCTIC, source_id: ARCTIC_heldout_left, cache_manifest: /SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/arctic_p2_val_left_root_relative_sidecars_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: left_only} +model: + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: + joint2d: 1.0 + joint3d_camera: 10.0 + joint3d_root_relative: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 100000 + num_workers: 4 + checkpoint_interval: 2000 + validation_interval: 2000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase9/mixtures/phase9_j25_full_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase9/mixtures/phase9_j25_full_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e6e97b8ee28fba6840020b637f9f7498bbc0590 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase9/mixtures/phase9_j25_full_s20260717.yaml @@ -0,0 +1,76 @@ +name: phase9_j25_full_s20260717 +seed: 20260717 +experiment: + phase: 9 + branch: phase9_unified + condition: J25 + uses_h2o_training_data: true + initialization_checkpoint_sha256: 6aef9457bf010cc40e1a0a1b9ae834f512333fba01b2593480742c451118aa68 + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: H2O, source_id: H2O, split_role: official_train, weight: 0.25, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/h2o_official_train7000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + - {dataset: HOT3D, source_id: HOT3D, split_role: external_train, weight: 0.25, cache_manifest: /SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_100000_v1/cache_manifest.jsonl, K_input_dropout: 0.3} + - {dataset: HOI4D, source_id: HOI4D, split_role: external_train, weight: 0.25, cache_manifest: /SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hoi4d_full37305_left_root_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: historical_left_only} + - {dataset: ARCTIC, source_id: ARCTIC, split_role: external_train, weight: 0.25, cache_manifest: /SSD3/jiasen/foundation_hand/phase9_artifacts/cache/arctic_full23768_left_root_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: historical_left_only} +model: &model + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: &loss + joint2d: 1.0 + joint3d_camera: 10.0 + joint3d_root_relative: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: &assets + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 405000 + num_workers: 8 + checkpoint_interval: 10000 + validation_interval: 10000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 + source_exposure_milestones: + - {id: all_sources_20k, minimum_batches: {H2O: 20000, HOT3D: 20000, HOI4D: 20000, ARCTIC: 20000}} + - {id: all_sources_50k, minimum_batches: {H2O: 50000, HOT3D: 50000, HOI4D: 50000, ARCTIC: 50000}} + - {id: all_sources_100k, minimum_batches: {H2O: 100000, HOT3D: 100000, HOI4D: 100000, ARCTIC: 100000}} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase9/mixtures/phase9_j40_full_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase9/mixtures/phase9_j40_full_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb757a9c3d20b185afb8bdaac993d39e0df26c89 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase9/mixtures/phase9_j40_full_s20260717.yaml @@ -0,0 +1,77 @@ +name: phase9_j40_full_s20260717 +seed: 20260717 +experiment: + phase: 9 + branch: phase9_unified + condition: J40 + uses_h2o_training_data: true + initialization_checkpoint_sha256: 6aef9457bf010cc40e1a0a1b9ae834f512333fba01b2593480742c451118aa68 + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: H2O, source_id: H2O, split_role: official_train, weight: 0.20, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/h2o_official_train7000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + - {dataset: HOT3D, source_id: HOT3D, split_role: external_train, weight: 0.40, cache_manifest: /SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_100000_v1/cache_manifest.jsonl, K_input_dropout: 0.3} + - {dataset: HOI4D, source_id: HOI4D, split_role: external_train, weight: 0.20, cache_manifest: /SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hoi4d_full37305_left_root_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: historical_left_only} + - {dataset: ARCTIC, source_id: ARCTIC, split_role: external_train, weight: 0.20, cache_manifest: /SSD3/jiasen/foundation_hand/phase9_artifacts/cache/arctic_full23768_left_root_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: historical_left_only} +model: &model + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: &loss + joint2d: 1.0 + joint3d_camera: 10.0 + joint3d_root_relative: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: &assets + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 505000 + num_workers: 8 + checkpoint_interval: 10000 + validation_interval: 10000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 + source_exposure_milestones: + - {id: nonhot_20k, minimum_batches: {H2O: 20000, HOI4D: 20000, ARCTIC: 20000}} + - {id: hot_50k, minimum_batches: {HOT3D: 50000}} + - {id: nonhot_50k_hot_100k, minimum_batches: {H2O: 50000, HOT3D: 100000, HOI4D: 50000, ARCTIC: 50000}} + - {id: nonhot_100k_hot_200k, minimum_batches: {H2O: 100000, HOT3D: 200000, HOI4D: 100000, ARCTIC: 100000}} diff --git a/home/wuyifan/EgoNet_train_20261008/configs/phase9/mixtures/phase9_j55_full_s20260717.yaml b/home/wuyifan/EgoNet_train_20261008/configs/phase9/mixtures/phase9_j55_full_s20260717.yaml new file mode 100644 index 0000000000000000000000000000000000000000..756a9d23db7350c5d0bd35e36cfdc29119ff4b50 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/configs/phase9/mixtures/phase9_j55_full_s20260717.yaml @@ -0,0 +1,80 @@ +name: phase9_j55_full_s20260717 +seed: 20260717 +experiment: + phase: 9 + branch: phase9_unified + condition: J55 + uses_h2o_training_data: true + initialization_checkpoint_sha256: 6aef9457bf010cc40e1a0a1b9ae834f512333fba01b2593480742c451118aa68 + h2o_official_validation_used_for_selection: false + official_test_used: false +data: + resolution_hw: [368, 640] + T: 8 + batch_size: 1 + photometric_augmentation: {enabled: true, probability: 0.8, brightness: 0.2, contrast: 0.2, saturation: 0.2, hue: 0.05} + sources: + - {dataset: H2O, source_id: H2O, split_role: official_train, weight: 0.15, cache_manifest: /SSD3/jiasen/foundation_hand/phase7_artifacts/cache/h2o_official_train7000_v1/cache_manifest.jsonl, K_input_dropout: 0.0} + - {dataset: HOT3D, source_id: HOT3D, split_role: external_train, weight: 0.55, cache_manifest: /SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_100000_v1/cache_manifest.jsonl, K_input_dropout: 0.3} + - {dataset: HOI4D, source_id: HOI4D, split_role: external_train, weight: 0.15, cache_manifest: /SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hoi4d_full37305_left_root_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: historical_left_only} + - {dataset: ARCTIC, source_id: ARCTIC, split_role: external_train, weight: 0.15, cache_manifest: /SSD3/jiasen/foundation_hand/phase9_artifacts/cache/arctic_full23768_left_root_v1/cache_manifest.jsonl, K_input_dropout: 0.0, joint3d_root_relative_scope: historical_left_only} +model: &model + encoder: dinov3 + decoder_dim: 512 + decoder_layers: 3 + attention_heads: 8 + decoder_mode: alternating + use_temporal: true + use_depth: true + depth_mode: geometry + depth_gate_mode: fixed + depth_gate_fixed_value: 0.5 + use_rays: true + use_bimanual_interaction: true + predict_presence: true + require_mano: true + mano_fix_left_shapedirs: true + depth_gate_floor: 0.0 + modality_dropout_prob: 0.0 + temporal_position_mode: none + temporal_attention_mode: bidirectional + dinov3_trainable_last_blocks: 0 + translation_parameterization: direct_xyz +loss: &loss + joint2d: 1.0 + joint3d_camera: 10.0 + joint3d_root_relative: 10.0 + vertices_camera: 1.0 + local_pose: 1.0 + global_orientation: 1.0 + shape: 0.1 + translation: 10.0 + reprojection: 1.0 + temporal_velocity: 0.1 + temporal_acceleration: 0.05 + bimanual_relative_wrist: 1.0 + presence: 0.0 +assets: &assets + dinov3_source: third_party/dinov3 + dinov3_weights: /SSD3/jiasen/foundation_hand/pretrained/dinov3 + mano_root: /SSD3/jiasen/foundation_hand/pretrained/mano +precision: bf16 +protocol: + max_steps: 675000 + num_workers: 8 + checkpoint_interval: 10000 + validation_interval: 10000 + validation_batches: 32 + telemetry_interval: 500 + learning_rate: 5.0e-5 + min_learning_rate: 5.0e-6 + warmup_steps: 1000 + weight_decay: 0.05 + source_exposure_milestones: + - {id: hot_50k, minimum_batches: {HOT3D: 50000}} + - {id: nonhot_20k, minimum_batches: {H2O: 20000, HOI4D: 20000, ARCTIC: 20000}} + - {id: hot_100k, minimum_batches: {HOT3D: 100000}} + - {id: nonhot_50k, minimum_batches: {H2O: 50000, HOI4D: 50000, ARCTIC: 50000}} + - {id: hot_200k, minimum_batches: {HOT3D: 200000}} + - {id: hot_300k, minimum_batches: {HOT3D: 300000}} + - {id: nonhot_100k_hot_367k, minimum_batches: {H2O: 100000, HOT3D: 367000, HOI4D: 100000, ARCTIC: 100000}} diff --git a/home/wuyifan/EgoNet_train_20261008/docs/CLEAN_GT_FORMAL_RUN.md b/home/wuyifan/EgoNet_train_20261008/docs/CLEAN_GT_FORMAL_RUN.md new file mode 100644 index 0000000000000000000000000000000000000000..7a0864c2ad15b78a5f17fd4a2d1b0d7e9500ddcf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/CLEAN_GT_FORMAL_RUN.md @@ -0,0 +1,430 @@ +# Foundation Hand clean-GT 正式训练记录 + +日期:2026-09-25。G2 隔离 run:`/home/wuyifan/foundation_hand_clean_gt_dino_20260925/`。本文件记录**正式训练**,与预检 smoke 权重分开。训练代码 `clean_train.py` SHA256:`3f6562843cb35ae6a4e601df39b6dca5e37b18980de02865d91447449be20fb4`。六卡由用户明确授权给本任务使用。 + +## Quest3 外参根因与 formal_v3 + +2026-09-25 17:19 HKT:对两个 Quest3 尖峰帧做 RGB/GT 叠图,发现 formal_v2 的 mask-only 修法将图像中清楚可见的手判成出画,立即停止 v2 控制器和六卡训练。`formal_v2` 的 2K checkpoint 与训练账本已移到 G2 `archive/formal_v2_s1_wrong_quest3_extrinsics/`,原始旧 run 位于 `archive/checkpoints_before_hot3d_mask_fix_20260925/`;均未删除。下面 v2 的健康门通过仅代表数值稳定,**其 Quest3 监督不正确,不能作为有效 parent 或模型成绩**。 + +根因是 Quest3 官方 provider 在 LINEAR rectification 路径返回 identity `T_device_camera`,我们的 adapter 先前直接使用它;保留原生 FISHEYE624 calibration 的外参、仍用 LINEAR K 后,两个原失败 Quest3 帧在 RGB/K 完全相同的条件下恢复双手各 21 个关节,投影与官方 calibration 一致至约 `3e-5 px`。四个尖峰样本以旧权重重放,从 `1873.65/2593.77/6635.64/6655.73` 变为 `4.73/8.44/7.45/6.80`;同一均匀抽样 100 HOT3D T1 tile 的有效手从 mask-only 版 70 恢复到 183,有效 2D 关节从 977 恢复到 3481,全部在画面内。问题 Quest3 录制的真实 T8 clip 左右手 8/8 帧几何有效、336 个 2D 关节有效。修正文件 SHA256 `73ff32f3994178e0d995dc7a3ff378ac70685fce1fe6f65eb20cc88c67dce9af`,T1/T8 mask 与 Quest3 calibration 单元测试 4/4 通过。`formal_v3` 必须从官方 DINO 全新启动,不得 resume v2。 + +2026-09-25 17:20 HKT:`formal_v3` S1 2K 健康门已从官方 DINO 在 G2 六卡启动,PID 文件 `logs/formal_v3_s1_health2k.pid`,训练账本 `checkpoints/formal_v3_s1/metrics.jsonl`。控制器 `logs/formal_v3_controller.pid` 已启动,状态 `waiting_for_s1_health`;它将审计 2K endpoint,跑三源固定早期评估,通过后才 resume 完整 S1 并继续 S2–S4。第 100 步 HOT3D 的 2D/3D/MANO/translation 监督元素非零,当前只证明任务在正常前进,**尚未声称 v3 健康门通过或最终模型有效**。 + +2026-09-25 17:27 HKT 更新:`formal_v3` S1 的 2,000-step checkpoint 已落盘,`logs/formal_v3_s1_0002000_audit.json` 为 `pass`、错误列表为空。2000/2000 loss 与 grad norm 有限,最大 batch loss 5.521,首/末 100 步均值 4.470→1.154;H2O/ARCTIC/HOT3D 曝光严格为 4800/4200/3000,监督元素 1,457,394,HOT3D 2D 有效元素约 101,882。固定 32-clip/source 早期 development 评估已完成;HOT3D RGB+K 的四项均值为 177.36/60.28/175.84 mm 与 63.87 px,对应 3D/mesh 分母 466、2D 分母 446。它是冷启动健康诊断,不应与旧错误 GT 分母下的数值直接比较。控制器随后从 v3 的 2K checkpoint 精确 resume 至 S1 16,667,当前六个训练 rank 活跃;尚无任何完整阶段或最终模型结论。 + +17:29 HKT 后续核对:100 个均匀抽样 HOT3D T1 tile 按设备拆分为 Aria 27 个、Quest3 73 个;两组分别有 50/133 只有效手、926/2555 个有效 2D 关节,均无画面外有效 2D 关节。S1 约 3300 step 时,HOT3D 累计 4950 个 T1 clip,平均每 clip 有效 1.78 只手、33.5 个 2D 关节、37.4 个 3D 关节;最近 100 步 loss 均值约 1.02、裁剪率约 47%,没有发现新的数值尖峰。这些是抽样及 train-side 监督健康证据,不替代完整数据或 benchmark 审计。 + +17:38 HKT 尖峰归因复核:旧 S1 的 13,585 条 metrics 中有 20 次 batch loss >100,出现在 step 191–12,130;2 次在 1,000-step warmup 内、18 次在 warmup 后,20 次均含 HOT3D,且没有一次正好是 checkpoint 保存节点 4,167/8,334/10,000/12,500。step 5,644/5,673 分别为 1,106.92/1,110.74,前后相邻 step 回到约 1–3。旧训练的 checkpoint 在 optimizer step 与 metrics 落盘之后才触发,NCCL 日志未见 timeout/error;现有 metrics 没有逐步 DataLoader 等待时间,不能断言完全没有 I/O 抖动,但 I/O 延迟不会独立改变已读取样本的 GT 坐标。固定旧权重重放四个尖峰 HOT3D 样本,原 GT z 低至约 3e-6–2e-5 m、投影达数百万像素;修复 Quest3 原生外参后 RGB/K 不变,z 恢复约 0.3–0.5 m,单样本 loss 从 1,873.65/2,593.77/6,635.64/6,655.73 降至 4.73/8.44/7.45/6.80。故这批 loss 尖峰的可复现主因是监督几何,不是保存、warmup、DDP 通信或 I/O。新增只读阶段端点审计 `loss>100` 失败门槛(不改训练代码、loss 或 checkpoint),旧账本 20 次均可检出;formal_v3 在线至约 5.8K step 最大 batch loss 5.521、超门槛 0 次,在旧第 5,644/5,673 步的 loss 分别为 0.869/0.855。后续阶段仍需持续观察。 + +17:47 HKT:`formal_v3` S1 中途预注册恢复点 `checkpoints/formal_v3_s1/s1_update_0008334.pt` 完整落盘,独立 SHA256 `99c2edafb05dbb191a6cf05f966571f8db9715a97f3d1c712fc63759b779ca79` 与训练日志一致;反序列化得到 S1/update 8334、六 rank RNG、375 个模型 tensor、50,004 个逻辑样本曝光、grad clip 100。第 8,332–8,340 步 batch loss 为 0.59–1.32,没有与保存同步的 loss 尖峰;至约 8.6K 步最大 loss 5.521、`loss>100` 为 0、最近 100 步均值约 0.803。最近 2K 步的 20 个分源详细采样中,H2O/ARCTIC/HOT3D 均持续出现有效 2D、translation 和 MANO 监督;完整 S1 端点审计与正式评估尚未发生。 + +17:50 HKT:在 G2 以冻结 `trainable_t8_index.sqlite` 和 `audit_schedule.py` 做独立 CPU 计划覆盖校验。S2+S3 连续 800,004 个采样位置、S4 独立 400,002 个位置均 `pass`,两轮各自覆盖 H2O 6,406/6,406、ARCTIC 22,750/22,750、HOT3D 143,657/143,657 个 tile;S2+S3 三源首次完成位置分别为 16,016/65,000/574,629,S4 为 18,302/90,999/359,143。S2+S3 计划曝光 H2O/ARCTIC/HOT3D 为 320,001/280,001/200,002;S4 为 140,000/100,000/160,002。**这只是确定性采样计划的证明,不是训练已经读取这些样本**;阶段结束后还必须核对 checkpoint 的全局位置、曝光 ledger、源内实际读取及原生帧覆盖证据。 + +17:54 HKT:以 S1 第 10,586 步的冻结采样位置逐个映射 T1 HOT3D manifest,Aria/Quest3 计划曝光为 7,936/7,941;设备与输入模式拆开是 Aria RGB+K/RGB 5,557/2,379,Quest3 5,597/2,344。该步训练 metrics 中 HOT3D RGB+K/RGB 累计恰为 11,154/4,723,与排程逐项相等。它证明 Quest3 没有在采样层被漏掉,不能替代逐设备有效监督或模型四指标;S1 完整端点仍在运行。 + +18:00 HKT:`formal_v3` S1 第 12,130 步 loss 为 0.486(旧错误 run 同位置 804.91);全程至约 12.7K 步最大 loss 5.521、`loss>100` 为 0。预注册 `s1_update_0012500.pt` 的独立 SHA256 `934cf9731e85419efb21bc4cd3ea5bf15a4b602ade22fafc178a475baaa8ee04` 与训练日志一致,反序列化为 S1/update 12,500、六 rank RNG、375 个模型 tensor、75,000 个样本曝光、grad clip 100;H2O/ARCTIC/HOT3D 分别 30,000/26,250/18,750。保存前后第 12,498–12,503 步 loss 0.39–1.03,无保存尖峰。完整 S1 审计/评估仍待端点,不用这些中途数值宣称最终性能。 + +18:06 HKT:S1 已越过旧错误 run 的 13,585-step 停止位置;截至约 13.7K 步全程最大 batch loss 5.521,`loss>10` 和 `loss>100` 均为 0,最近 100 步 loss 均值 0.681、预裁剪 grad norm 中位数 80.32、裁剪 8/100。最近 2K 步的 20 个分源详细抽样里,三源的 2D/translation/MANO 有效元素均非零。阶段只读审计追加 depth/ray、2D/rotation/shape 分支非零梯度门;S2 起另要求 temporal decoder 和 `shape_score` 非零。`shape_score` 在 S1 T=1 下跨帧 softmax 长度为 1,零梯度符合结构定义。审计脚本远端 SHA256 `270a124def91742ccd9ed87ed2175dc9542bf21ff2573e5a88004db0fe2a8a6f`;训练代码、loss 与 checkpoint hash 未改。 + +18:13 HKT:`formal_v3` S1 正式 16,667-step 完整 checkpoint 已落盘,独立 SHA256 `731b77a4bd44b26e395cea85e2ac45e1521ddd471d69a2d71510042dbe9fdc8f` 与 `logs/formal_v3_s1_0016667_audit.json` 一致;扩展后的阶段审计 `pass`、`errors=[]`。16,667/16,667 loss 和 grad norm 有限,最大 batch loss 5.521、超 100 的 step 为 0;首/末 100 步均值 4.470→0.649,末 100 步 grad norm 中位数 76.45、裁剪 12/100;总裁剪 6084/16667。H2O/ARCTIC/HOT3D 曝光 40,001/35,000/25,001,七种输入模式齐全,监督元素 12,125,612。S1 完整 run 的 2K 后续训部分实测 32.93 clips/s、每卡峰值约 1.29 GiB。 + +同一 S1 checkpoint 的固定 32-clip/source development 诊断(顺序为 absolute MPJPE / root-relative MPJPE / MPVPE,mm;MANO projected 2D,px):H2O RGB+Depth+K `41.327 / 22.614 / 40.954 / 20.308`(四项分母 512);ARCTIC RGB+K `37.603 / 18.829 / 37.197 / 27.507`(3D/mesh 160、2D 321);HOT3D RGB+K `86.505 / 32.994 / 86.104 / 26.550`(3D/mesh 466、2D 446)。这些是 T1 初始化权重在固定 T8 clip 上的早期开发集检查,不是最终 benchmark 或与旧错误 GT 的可比改进。控制器随后从该完整 S1 parent 启动六卡 S2 的 2K 健康门;S2 前约 135 步 loss 有限,temporal decoder、`shape_score`、depth/ray/RGB projection 均已出现非零梯度。S2 健康门仍未完成。 + +18:35 HKT:S2 2,000-step 健康门已 `pass`、`errors=[]`,checkpoint SHA256 `de54b87045a72917b4aa4827b1b1da2cbc59c1938b95b0cc64434f5fadd736e1` 与独立磁盘校验一致。三源曝光 4,800/4,200/3,000,监督元素 11,652,251,最大 batch loss 2.068、异常 >100 为 0,首/末 100 步均值 0.722→0.683;但 1,306/2,000 次被 clip=100 裁剪,末 100 步预裁剪 grad norm 中位数 120.52。T8 temporal 和 shape pooling 梯度非零,三源固定 32-clip 评估分母与 S1 相同。控制器已从该完整 checkpoint 精确 resume 至 S2 50,000,2K 的健康通过不等于模型性能改善。 + +S1→S2 早期四指标回退的同权重 temporal 消融:用同一固定 32-clip/source development panel、相同输入模式,仅切换 `decoder.temporal_enabled`;单位依次为 absolute/root-relative/MPVPE mm 与 2D px。S1 checkpoint SHA 前缀 `731b77a4`,S2 2K SHA 前缀 `de54b870`;消融脚本 `code/diagnose_s1_s2_temporal_transition.py`,各源开/关结果的指标分母逐项完全相同。 + +| 源/输入 | S1 temporal off(正式 S1) | S1 temporal on(未训练 temporal) | S2 2K temporal off(共享权重变化) | S2 2K temporal on(正式 S2) | +|---|---|---|---|---| +| H2O / RGB+Depth+K | 41.33 / 22.61 / 40.95 / 20.31 | 35.72 / 22.63 / 34.65 / 19.58 | 44.90 / 25.45 / 45.13 / 27.31 | 38.54 / 28.79 / 37.56 / 18.48 | +| ARCTIC / RGB+K | 37.60 / 18.83 / 37.20 / 27.51 | 42.05 / 29.04 / 41.87 / 31.40 | 46.84 / 25.26 / 46.65 / 34.58 | 49.85 / 26.71 / 49.41 / 28.81 | +| HOT3D / RGB+K | 86.51 / 32.99 / 86.10 / 26.55 | 81.68 / 35.41 / 81.43 / 33.78 | 108.28 / 32.93 / 108.00 / 31.47 | 113.65 / 33.99 / 113.32 / 26.74 | + +未训练 temporal 的即时影响域相关,不能单独解释 2K 后回退;S2 2K 关闭 temporal 后三源 absolute 3D 仍比 S1 权重差,HOT3D 多 21.77 mm,表明共享权重早期也有不利变化。S2 2K 再开启 temporal,三源 2D 均改善,但 root-relative 3D 均略差。这里只是小型固定开发面板和早期训练点;不凭它更改冻结 loss/LR/源配比或宣告 S2 失败。预注册 S2 10K 完整保存点出现后,用同一面板追加只读检查恢复趋势,正式 S2 50K 端点评估仍由控制器执行。 + +小面板组成审计:`--limit 32` 是冻结 manifest 的前 32 条,**不是全量开发集的分层随机样本**。H2O 全部 96 clips/12 takes,前 32 条为 4 takes 各 8 clips;ARCTIC 全部 136 clips/17 组,前 32 条仅 s05 的 4 组各 8 clips;HOT3D 全部 248 clips/31 录制,前 32 条为 4 录制各 8 clips,其中 Quest3 24、Aria 8。故表中差值只可解释为同一前缀面板的配对变化,不可当作全开发集或官方 benchmark 的域级结论。S2 10K 前缀复评用于判断这同一切片是否恢复;之后仍需全量 development 的录制分组指标,不能由前缀结果决定最终模型推广。 + +18:39 HKT:S2 约 4.5K/50K 时仍有六卡 torchrun 和控制器进程,全部 loss/grad 有限,最大 batch loss 3.252。第 1–100 / 901–1000 / 1901–2000 / 3001–3100 / 4401–4500 步的平均 loss 约 0.722 / 0.638 / 0.683 / 0.692 / 0.678;后两窗口裁剪约 80/100、78/100。最近 1K 步预裁剪 grad norm p50/p90/p99 约 119/159/189,`clip=100` 通常是温和缩放而非非有限爆炸;第 4500 步 translation head 分组 norm 约 145.8,temporal decoder 约 2.19。早期位置退化与 translation 分支梯度需并行观察,但当前证据不足以中断已注册的 S2 训练或改动优化器。下一只读固定面板检查点为 S2 10K 完整 checkpoint。 + +18:52 HKT:按“保存/通信、warmup、数据 I/O 是否造成 loss 尖峰”复核。S2 前 6,829 条逐步账本最大 loss `3.252`,`>2` 仅 7 步、`>5` 为 0;最大的 3118/3155/5976 步分别为 `3.252/3.109/2.624`,相邻步回到约 `0.49–0.88`。S2 目前仅在 2,000 保存过完整 checkpoint,且该步及 1999/2001 步 loss 为 `0.662/0.617/0.485`;训练代码在写完该步 metrics 后才保存,后续注册保存点为 10K/12.5K 等。1000-step warmup 在 S2 确实执行:update 1/1000/1001 的 LR 为 `5e-8/5e-5/5e-5`;2K resume 的 1999/2000/2001 步 LR 连续约 `4.9954e-5`,7 次 `loss>2` 均在 warmup 后。6,829 条 loss 有限、六卡 all-reduce 后记录的 grad norm min/max 全部一致;S2 console 未见 NCCL/ProcessGroup timeout、worker 死亡、I/O error 或 traceback。DataLoader 为每 rank 2 workers、pin memory、persistent workers;当前短时 `vmstat` 的 I/O wait 为 0%,但日志没有逐步 `next(iterator)` 等待与 checkpoint wall time,因此**不能排除吞吐量的瞬时 I/O 抖动**,只不能把它作为已读 batch 的数值 loss 尖峰解释。旧错误 S1 的 20 次 `loss>100` 有 18 次在 warmup 后、保存节点无一次重合,且同权重同样本修正 Quest3 GT 外参后 loss 从千级落到个位数(见 17:38 记录)。综上,旧严重尖峰有可复现的监督几何根因;当前 S2 仅有有限的偶发 batch 波动,没有保存、warmup 或通信故障证据,继续保持冻结训练配置和监控。 + +18:57 HKT:补做冻结 development manifest 的 **录制分层**配对诊断:每源按录制 round-robin 取 32 clip,S1 16,667 与 S2 2,000 两个冻结 checkpoint 对同一输入逐帧评估,四项分母配对相等。脚本 `code/eval_stratified_probe.py` 在本地/G2 SHA256 同为 `ab47a63a1e910e84fc3dcfba21be821df14db4782f7c942547c004cc4ad776ca`;脚本不参与训练代码哈希或 optimizer。表内为 **S2 减 S1**,正值表示变差,单位为 mm/mm/mm/px: + +| 源/输入 | 覆盖录制 | 3D/2D 分母 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:|---:|---:| +| H2O / RGB+Depth+K | 12/12 | 512/512 | +5.58 | +5.70 | +5.47 | +3.60 | +| ARCTIC / RGB+K | 17/17 | 223/423 | +5.61 | +5.24 | +5.81 | -0.23 | +| HOT3D / RGB+K | 31/31 | 447/420 | +28.41 | +6.38 | +28.42 | +3.05 | + +因此前缀 32 clip 的退化不是唯一抽样解释;S2 2K 时三源大多数指标仍退化。不过这是早期冻结开发切片,不是完整 development,更不是官方 benchmark。S1→S2 继承模型权重但新建 AdamW optimizer(S2 2K 后 resume 则恢复 S2 optimizer);S2 的 1K warmup 已实证存在,之后 LR 接近 `5e-5`。新时序路径、共享权重早期更新和 optimizer 动量重建是需要看 10K 走势的候选机制,不能凭此表断言某一个是根因,也不能将连续指标漂移解释成孤立读盘/保存尖峰。保持原计划至 S2 10K 注册检查点做同分母复评。 + +19:19 HKT:S2 10K 预注册 checkpoint 已完整落盘,独立 SHA256 `e68f464abccd2b2a7c712b4a637927c1a53e5e2cb2cbc8276cf687ba21ae75f9` 与训练控制台一致;六卡仍在接续 S2 50K。以**相同录制分层 32 clip/source、相同分母**复评。下表为 S2 10K 减 S1 16,667,正值是退化;顺序 absolute/root-relative/MPVPE mm、projected 2D px: + +| 源/输入 | S2 2K - S1 | S2 10K - S1 | +|---|---|---| +| H2O / RGB+Depth+K | +5.58 / +5.70 / +5.47 / +3.60 | -0.75 / +3.21 / -0.35 / +1.08 | +| ARCTIC / RGB+K | +5.61 / +5.24 / +5.81 / -0.23 | -2.45 / +2.39 / -2.27 / -1.13 | +| HOT3D / RGB+K | +28.41 / +6.38 / +28.42 / +3.05 | +19.29 / +3.41 / +19.33 / +6.22 | + +同一个 S2 10K checkpoint 只关闭/打开 `decoder.temporal_enabled` 的配对消融(**ON 减 OFF**,负值为开启 temporal 更好):H2O `-6.46 / +0.08 / -7.51 / -7.17`,ARCTIC `-1.85 / -2.81 / -1.86 / -3.35`,HOT3D `-2.08 / -1.15 / -2.11 / -3.91`。因此 temporal 前向在 10K 已能帮助绝大多数项目;HOT3D 对 S1 的残余退化不能归结为“打开 temporal 本身”。S2 2K→10K 的三源 3D 均有恢复,支持继续冻结配置而非立刻停止。仍需特别跟踪三源 root-relative 和 HOT3D absolute/mesh/2D;32 clip 分层切片不等于全量 development 或正式 benchmark。 + +训练侧辅助诊断:S2 第 2,001–9,000 步预裁剪 grad norm p50/p90/p99 为 `120.1/160.5/199.2`,`clip=100` 对应常见缩放约 `0.83/0.62/0.50`,不是非有限爆炸。每 100 步的 71 个详细梯度样本中,translation head 平均占总梯度范数约 `99.72%`,裁剪率 `78.9%`;S1 后段详细样本约 `99.30%`、裁剪率 `19.1%`。说明全局裁剪主要由 translation 分支触发,其他分支同步被缩放;这是下一阶段受控修正的候选点,不足以在 10K 单独定为因果。保留 12.5K/20K 等注册检查点,若 HOT3D 和 root-relative 不随训练恢复,再做独立 optimizer group 或 groupwise clipping 的对照,不热改当前 run。 + +19:27 HKT:S2 12.5K 预注册 checkpoint 已完整落盘,独立 SHA256 `9213aacdd27af707cfb4eb15cb8b6371bcfa7d9476fe648c115ec405bcf63d9b` 与控制台一致。相同录制分层 32 clip/source 的配对复评,四项仍为 absolute/root-relative/MPVPE mm、projected 2D px;正值表示变差: + +| 源/输入 | S2 12.5K - S2 10K | S2 12.5K - S1 | +|---|---|---| +| H2O / RGB+Depth+K | -0.45 / -2.13 / -0.21 / +1.54 | -1.19 / +1.09 / -0.56 / +2.62 | +| ARCTIC / RGB+K | +0.58 / +3.51 / +0.92 / -2.12 | -1.87 / +5.91 / -1.35 / -3.25 | +| HOT3D / RGB+K | -12.31 / +1.43 / -12.54 / -4.30 | +6.99 / +4.84 / +6.78 / +1.91 | + +HOT3D absolute/mesh 均值持续恢复,但其 absolute p95 从 S1 的约 `221.3` mm 到 12.5K 的 `320.4` mm,root-relative p95 从 `73.4` 到 `102.5` mm;均值恢复不能掩盖困难尾部。三源 root-relative 目前仍比 S1 差,且 ARCTIC 在 10K→12.5K 又回退,故不宣称 S2 已全面超越 S1。12.5K 仅占 S2 50K 的四分之一;temporal 同权重消融大多有利,训练 loss/grad 有限且仍在收敛。保持正式六卡训练、冻结配置与控制器,下一预注册 20K 点复核三源 root-relative、HOT3D 3D/2D 和尾部;若持续退化,需在完整 development 上确认后再隔离测试 optimizer/梯度裁剪或 loss 竞争,不能直接改写当前 run。 + +19:49 HKT:为校验 32-clip 小面板的代表性,使用 `eval_stratified_probe.py` 对冻结 development manifest 的**全部** H2O 96、ARCTIC 136、HOT3D 248 个 T8 clip,配对前向 S1 16,667 与 S2 12.5K。两模型逐手帧指标分母严格相等。下表为 **S2 12.5K - S1**(正值变差;前三项 mm、2D px): + +| 源/输入 | clips | 3D/mesh 分母 | 2D 分母 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O / RGB+Depth+K | 96 | 1536 | 1536 | -2.63 | -0.54 | -1.89 | +1.55 | +| ARCTIC / RGB+K | 136 | 704 | 1349 | -0.35 | +5.93 | +0.15 | -2.68 | +| HOT3D / RGB+K | 248 | 3573 | 3289 | +9.61 | +2.54 | +9.41 | +3.86 | + +**全量修正小面板结论:**H2O root-relative 实际略好于 S1,不能再声称三源一致退化;ARCTIC 局部 3D 明显退化但 2D 改善,HOT3D 四项均退化。HOT3D absolute p95 `207.82→246.13` mm、CVaR95 `329.90→408.01` mm,root-relative p95 `72.19→80.31` mm,说明困难尾部也尚未恢复。小面板对 HOT3D 的 absolute 差值为 `+6.99` mm,全量为 `+9.61` mm;它保留了退化方向,但不能替代全量幅度与 H2O 方向判断。以上是 development,不是独立 confirmation 或最终 benchmark;不能凭 S2 12.5K 判定整个 50K 失败。20K 注册点需复核这三源的同协议四指标,并按 HOT3D 录制/headset 分层定位残余误差。 + +19:54 HKT:只读配对脚本增加可选 `--paired-groups`,逐手帧检查两 checkpoint 每项指标的有限性掩码完全一致,再输出按 headset 与物理录制分组的 paired delta;本地/G2 SHA256 同为 `3784e25cdcee6d714d252b11512351fd7ce009189bde670ac165cafae805948c`,不在训练代码 hash 内。用 HOT3D 分层 32-clip 小面板验证通过:31 个录制中 absolute/root-relative/MPVPE/2D 分别只有 `13/11/13/5` 个录制的均值变好;Aria 的 root-relative paired delta `+3.86` mm(168 个有效手帧),Quest3 为 `+5.42` mm(279 个有效手帧)。这仍是**每录制约 1 个 clip 的诊断**,不能作为全量 headset 结论;20K 时用全量 development 与相同分组脚本复核。训练当前约 18K/50K、控制器与六卡进程活跃。 + +20:59 HKT:S2 20K 预注册完整 checkpoint 独立 SHA256 `bbc6ef0bbc10f52003d62dbf5d7f4abd47112fcf0bb194f16b03d188d1c2f569` 与训练控制台一致;保存前后 loss `0.42–0.76`、LR 连续。以相同冻结 development manifest 的**全部**三源 T8 clip 配对 S1 16,667 与 S2 20K,正值为 S2 退化,顺序为 absolute/root-relative/MPVPE mm、projected 2D px: + +| 源/输入 | 有效 3D/2D 手帧 | S2 12.5K - S1 | S2 20K - S1 | +|---|---:|---|---| +| H2O / RGB+Depth+K | 1536/1536 | -2.63 / -0.54 / -1.89 / +1.55 | -5.87 / -2.36 / -6.34 / +1.45 | +| ARCTIC / RGB+K | 704/1349 | -0.35 / +5.93 / +0.15 / -2.68 | -9.38 / +2.51 / -9.06 / -4.09 | +| HOT3D / RGB+K | 3573/3289 | +9.61 / +2.54 / +9.41 / +3.86 | +12.47 / +0.22 / +12.59 / +0.45 | + +ARCTIC/H2O 的 3D 明显继续收敛;HOT3D 的局部 3D/2D 回到接近 S1,但 absolute/mesh 扩大到约 +12.5 mm。HOT3D absolute p95 `207.82→226.66` mm、CVaR95 `329.90→330.98` mm;不是仅由极端尾部拉高的均值。全量逐手帧 paired mask 一致,31 个录制中只有 5 个 absolute 均值改善;Aria 的 absolute paired delta `+19.99` mm(1191 个有效手帧),Quest3 `+8.71` mm(2382 个),说明两个 headset 均存在而非单一 Quest3 外参异常。 + +用只读 hybrid 进一步拆解:保持 S2 20K 的 MANO 局部姿态/shape、joints 与 mesh 的相对坐标,只将整体 root 平移替换为同 clip 的 S1 预测;不是新的训练模型或可直接部署的单模型。HOT3D 全量三组四指标均值(相同 3573/3289 分母)如下: + +| 输出 | absolute mm | root-relative mm | MPVPE mm | projected 2D px | +|---|---:|---:|---:|---:| +| S1 原始 | 82.62 | 34.52 | 81.97 | 25.82 | +| S2 20K 原始 | 95.10 | 34.74 | 94.56 | 26.27 | +| S2 局部 + S1 root | 82.37 | 34.74 | 81.72 | 26.40 | + +换 root 相对 S2 回收 absolute/mesh `12.73/12.84` mm,而 root-relative 数值不变(符合平移不变性);2D 仅差 `+0.13` px。hybrid absolute p95 `208.38` mm、CVaR95 `319.07` mm,接近或略优于 S1。故 HOT3D 当前 absolute/mesh 回退的**主要可分离分量是 global wrist translation**,不应把 S2 学到的 local/temporal 分支整体撤回。尚不能由此证明只复制 S1 translation head 权重就能修好:S1 root 依赖 S1 的整条特征路径,hybrid 需要两次前向。正式 S2 不热改;保存 S1/S2 权重,在 S2 50K 全量端点复查 root 是否自然恢复,若未恢复,再从冻结 checkpoint 开独立、只针对 root translation 的 optimizer-group/蒸馏或几何校正受控实验,并要求四项及 headset/录制尾部共同过门。 + +21:08 HKT:应用户要求,用 S2 逐步账本扩展复核保存/通信、warmup 与数据 I/O。前 30,958 步最大 batch loss `3.252`;`loss>2` 共 16 步、`loss>5` 为 0,所有 loss/grad norm 有限。16 步均在 1K warmup 后,最大三步 3118/3155/12890 的 loss 为 `3.252/3.109/2.842`,前后相邻 step 回落;没有一次落在 2K/10K/12.5K/20K/25K/30K 的 checkpoint 保存节点及其前后 1 步。各保存点的 loss 依次为 `0.662/0.702/0.419/0.562/0.583/0.668`,保存操作按代码在该步 optimizer step 和 metrics 写入**之后**执行。S2 的 update 1/500/1000/1001 LR 为 `5e-8/2.5e-5/5e-5/5e-5`,不是漏做 warmup;2K resume 也恢复了 optimizer state 与 stage-local LR。六卡 all-reduce 后每步记录的 grad norm min/max 一致,console 无 NCCL timeout、worker 退出或 I/O traceback。当前 DataLoader 为每 rank 2 workers、pin memory 和 persistent workers,现场 3 次 `vmstat` 采样的 I/O wait 均为 0%;但未记录逐步取 batch 等待时间,不能排除**耗时**的瞬时 I/O 抖动。I/O 等待或保存可以拖慢 step,本身不会把已读 batch 的 GT/loss 改成更大的值。16 个 `loss>2` batch 的来源组合不同,并非单一 input mode;每次都含 HOT3D,但当前账本只有每 100 步的分源 loss,不能据此判定唯一责任源。旧版千级尖峰已有同权重同样本外参修正重放证明为 Quest3 监督几何错误;formal_v3 S1 完整 16,667 步最大 loss `5.521`、`>10` 为 0,旧尖峰位置 5644/5673/12130 的新 loss 为 `0.869/0.855/0.486`。因此目前没有保存、warmup、DDP 通信造成**数值**尖峰的证据;维持原训练和只读监控。 + +21:19 HKT:S2 30K checkpoint SHA256 `98c1faf10b90fc959c10520f05beeb3cf822eb21dd31d1918b421213191f911e` 已独立核对。只读脚本对 HOT3D **全部** 248 个冻结 development clip 配对 S1 与 S2 30K,3D/mesh 与 2D 分母分别严格同为 3573/3289 手帧。S2 30K - S1 的 absolute/root-relative/MPVPE/2D 为 `-2.625/-4.764/-2.601 mm/-2.303 px`,四项均改善;对应 S2 30K 均值 `79.999/29.751/79.367 mm/23.517 px`。absolute p95 从 S1 `207.82` 降至 `168.30` mm,root-relative p95 从 `72.19` 降至 `59.61` mm。设备分层仍不均衡:Aria absolute/MPVPE 相对 S1 `+2.895/+2.761` mm(1191 手帧),Quest3 为 `-5.384/-5.282` mm(2382 手帧);两组 root-relative 和 2D 均改善。故 20K 的 HOT3D root 回退到 30K 已自然恢复并转为全量四项平均改善,不能依据 20K hybrid 诊断热改 root 或训练配置;但 Aria absolute/mesh 仍未过门。以上仅为 development 中途读数,不是正式 S2 50K 端点或独立 confirmation。 + +21:26 HKT:同一 S2 30K checkpoint 的其余两个**完整冻结 development** 源配对完成;两模型各指标的逐手帧分母相同。下面均为 S2 30K - S1 16,667,负值改善,前三项 mm、2D px: + +| 源/输入 | clips | 3D/mesh 分母 | 2D 分母 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O / RGB+Depth+K | 96 | 1536 | 1536 | -0.842 | -2.522 | -0.209 | +0.203 | +| ARCTIC / RGB+K | 136 | 704 | 1349 | -0.468 | +1.414 | -0.080 | +1.259 | +| HOT3D / RGB+K | 248 | 3573 | 3289 | -2.625 | -4.764 | -2.601 | -2.303 | + +H2O 的 2D 和 ARCTIC 的 root-relative/2D 仍未超过 S1,不可概括为三源四项全胜;但三源 absolute/mesh 均值都已到 S1 以下。与 20K 对照,HOT3D 全四项明显恢复,ARCTIC root-relative 从 `+2.51` 收窄至 `+1.41` mm,而 ARCTIC 2D 从 `-4.09` 转为 `+1.26` px。保持 S2 冻结配置与控制器,50K 阶段端点必须重新检查全量 development;独立 confirmation 留待最终 checkpoint 冻结后。目前不以中途读数选择 checkpoint。21:26 时 S2 账本至 34,089/50,000,最大 loss `3.252`、`>5` 为 0,六卡训练与控制器仍活跃。 + +21:27 HKT 控制器合同复核:`run_formal_stages.py` 在 S2 50K 自动执行完整 checkpoint/账本审计,但其阶段端点评估仍调用 `evaluate(..., full=False)`,只覆盖 H2O/ARCTIC/HOT3D 各 32 clip 的一个主输入模式;S3/S4 端点才自动跑七个条件的全量 development,S4 冻结后再跑一次独立 confirmation。因此 S2 50K 审计通过和三项 32-clip 报告**不能**替代上述三源全量配对表。S2 50K 落盘后须独立运行冻结 development 的全量 H2O/ARCTIC/HOT3D 同分母对照,并按 HOT3D 设备/录制检查;不把尚未到来的 confirmation 提前用于中途选点。控制器与正式训练代码维持冻结。 + +21:39 HKT:补查 S2 **预裁剪** grad norm,而非只看 loss。至 36,186 步,`grad>250/500/750/1000/10000` 分别为 `15/6/4/4/2` 次;四个 `>1000` step 为 14026 (`195596.9`, loss `0.342`)、16093 (`31370.6`, loss `0.561`)、17704 (`2229.9`, loss `0.603`)、28668 (`2340.2`, loss `0.509`)。四次均在 warmup 后、非 checkpoint 保存点;各自前后一步 grad 回到约 `58–159`,loss 仍有限且未同步尖峰。两个最大的 batch 只含 ARCTIC/H2O,没有 HOT3D,故不能套用旧 Quest3 GT 尖峰根因。训练代码先对六卡同步梯度做 global clip=100,再 `optimizer.step()`;这些 preclip norm 极大并不意味着对应参数更新未裁剪,但异常批次的方向可能影响该步。30K–36K 无 `grad>500`,HOT3D 30K 全量四指标较 S1 改善,不见持续失稳。 + +新增**仅诊断**的 `code/diagnose_gradient_outliers.py`(本地/G2 SHA256 `b25a20aef09efcdf9a23d5f646280f1358fcf5f3cc650cdc43dbcbfe87e63d82`),不在训练代码 hash 内。按无放回 sampler 精确找到四个 step 的各六个 tile;两个最大尖峰的 12 个 tile 用 12.5K 完整 checkpoint、28,668 的六个 tile 用 25K 完整 checkpoint 分别做单样本 BF16 forward/backward。早期 12 样本 grad norm 为 `0–263`(其中一个 ARCTIC tile 无有效监督、loss/grad 为零),25K 的六样本为 `120–260`;有监督样本的有效预测 joint z 最小约 `0.273/0.305 m`,6D rotation 两个向量的正交残量不接近零,梯度主要在 translation head。**这不是 exact step 重放**:模型权重比异常时早 1.5K–3.7K update,DDP batch 梯度和精确 rank RNG 未恢复,故只能说明这些 tile 在所测早期权重下不是必然病态,不能排除当时预测 z/旋转状态或其它反向路径瞬时异常。维持冻结训练与 clip=100;50K 全量开发集/后续阶段继续查 `grad>500/1000` 频率、loss 与四指标。若高频重现或伴随性能退化,再从保存点开独立 exact-state replay/消融,不在本 run 中途热改 loss、数值 clamp 或 optimizer。 + +22:10 HKT:更新上段的时间截面:S2 又在 step 36,687 和 36,999 分别出现预裁剪 grad norm `18,357.6`(loss `0.979`)与 `237,165.9`(loss `0.467`),两次均非保存点,前后一步恢复约 `47–91`,且两个 batch 混有三源。故“30K 后没有大梯度尖峰”只对当时截至 36,186 的账本成立,不能当作持续结论。相同冻结 sampler tile 用晚约 813/501 step 的 37.5K checkpoint 单样本重放,六个样本 grad 分别约 `115–259` 与 `134–268`,有效预测 joint z 最低约 `0.249/0.227 m`;仍非 exact-state replay,未确定尖峰的精确反向路径。37.5K checkpoint 独立 SHA256 `add9bbfad5be53a3f50599731bfb3d7781579a00dc78559039be96a6fbc958d6` 与控制台一致,回读为完整 S2/37,500、375 模型 tensor、六卡 RNG、clip=100,保存前后 loss/LR 连续。40K checkpoint 独立 SHA256 `70ff2aa6c1902903394ab90409f4ad835ec77244dcb2edc066e39406335ccd74` 也与控制台一致。训练继续有限,不能把这些受裁剪尖峰等同于 NaN 或 checkpoint 损坏。 + +以**全部冻结 development** clip 严格配对 S2 30K 与 37.5K;负值为 37.5K 改善,前三项 mm、2D px,逐项分母配对一致: + +| 源/输入 | clips | 3D/mesh 分母 | 2D 分母 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O / RGB+Depth+K | 96 | 1536 | 1536 | -3.395 | -2.205 | -3.792 | -4.324 | +| ARCTIC / RGB+K | 136 | 704 | 1349 | -7.515 | -2.357 | -7.491 | -7.037 | +| HOT3D / RGB+K | 248 | 3573 | 3289 | +7.747 | +1.751 | +8.090 | -1.553 | + +HOT3D 的 37.5K absolute/root-relative/MPVPE/2D 均值为 `87.746/31.503/87.457 mm/21.963 px`;absolute p95 从 30K `168.30` 升至 `174.46` mm,root-relative p95 `59.61→65.22` mm。Aria absolute/MPVPE 变化 `+10.401/+10.803` mm(1191 有效手帧),Quest3 为 `+6.420/+6.733` mm(2382),不是单一 headset。H2O、ARCTIC 四项却均改善,不能声称整体模型失稳,也不能由相关时间点证明这些大梯度步造成 HOT3D 回退。HOT3D S2 训练 quota 到 37.5K 尚未覆盖其全部 143,657 T8 tile;后续 S3 的高分辨率及完整覆盖仍可能改变结论。保持冻结 S2 至注册 50K,不凭中途点热改 loss、数据比例或 optimizer。 + +为避免控制器在 S2 50K 后只看每源 32 clip 就立即接 S3,已**仅向控制器 PID 2793759 发送 SIGSTOP**;`ps` 显示控制器 `T`,其子 torchrun PID 2807377 及六个训练 rank 仍在推进 S2(22:10 约 41,917/50,000)。这不是控制器故障或 goal 暂停,也没有停止训练。S2 50K 完整 checkpoint 落盘后先独立校验 SHA/回读/阶段账本,再用冻结三源全量 development 做同分母对照、检查 HOT3D 设备与尾部。如果训练健康且没有数据合同错误,基于 S3 完整 tile 覆盖的既定作用判断是否以 `kill -CONT 2793759` 恢复控制器;若存在明确可复现的数值/监督错误,先保留 checkpoint 并诊断,不静默继续。**不要遗忘恢复或明确处理这个被暂停的控制器。** + +22:12 HKT 增量:S2 第 39,750 步另有一次 preclip grad norm `1154.7`、loss `0.617`,低于 36,687/36,999 两次大异常,仍被 clip=100。账本至 42,130 步总 loss 最大仍 `3.252`;37.5K 后的 `grad>500/1000` 均各 1 次。50K 端点按完整账本重新统计,不能继续沿用“37.5K 以后没有 >500”的短时观察。 + +22:14 HKT 分源训练账本复核:HOT3D 累计 clip 曝光从 S2 30K 的 `45,000` 增至 37.5K 的 `56,250`、40K 的 `60,000`;相应有效 translation 手帧 `649,544→810,683→864,835`,有效 2D 元素 `12,131,322→15,119,295→16,133,504`,单位曝光的监督密度基本稳定,没有出现 mask 整源失效。每 100 step 的有源详细样本在 25–30K 与 35–40K 两窗:HOT3D 加权 translation 均值 `0.1635→0.1733`、camera 3D `0.2032→0.2056`、root-relative `0.1202→0.1298`;H2O 与 ARCTIC 对应项均下降。**这不是同 tile 配对 loss**:HOT3D 仍在 143,657 个 T8 tile 的无放回首轮,新窗口样本可能更难,不能据此证明共享权重遗忘或梯度尖峰导致回退。S2 50K 的 HOT3D quota 仅约 75K clips,完整首轮要靠 S3 接续;因此在确认数据/数值合同无错后,S3 仍是验证完整数据覆盖的必要阶段。 + +23:06 HKT,S2 正式 50,000/50,000 endpoint 已独立审计 `pass`、`errors=[]`,完整 checkpoint SHA256 `335b16a16f4e32d1dc307e0f1dbca657cd1b69db5bb80509a2a6b38e87d8e94b` 与训练日志、磁盘复算一致。50,000 条账本完整,最大 loss `3.252`、`loss>10` 为 0,首/末 100 步均值 `0.722→0.422`,最后 100 步 preclip grad norm 中位数 `69.23`;总裁剪 `21,178/50,000`。H2O/ARCTIC/HOT3D 曝光 `120,000/105,000/75,000`,七种 source/mode 均有读取,监督元素 `290,719,502`。 + +针对训练尖峰的系统排查:当前 `formal_v3` S2 是**有限 loss 下的 preclip 梯度尖峰**,不同于旧版已被 HOT3D GT 投影错误重放解释的 `loss>100` 尖峰。S2 全段 `grad>500/1000` 分别 10/8 次,`>1000` 出现在 14,026、16,093、17,704、28,668、36,687、36,999、39,750、44,038;1,000-step warmup 内最大仅 `211.73`,尖峰 LR 从 `4.26e-5` 到 `6.62e-6` 分散,非 warmup 边界或单一 LR 阈值。保存点 10K、12.5K、20K、25K、30K、37.5K、40K 与尖峰均不重合;`clean_train.py` 在 optimizer step 和 metrics 写入后才同步执行 checkpoint,保存点前后 loss/grad/LR 连续。36,999 的 grad `237,165.9`、loss `0.467`,前后一步 grad `46.88/74.46`;14,026 的 grad `195,596.9`、loss `0.342`,前后一步 `72.16/92.23`,均经 clip=100 后继续正常。尖峰步 DDP 各 rank 汇总 norm min=max,训练 console 无 NCCL timeout/error 或 DataLoader 异常。端点附近 `vmstat` I/O wait 0、`/proc/pressure/io` avg10/60 均 0、VRS 连续读取成功;**这些是实时快照,不能排除历史短暂读取延迟**,但单纯 I/O 等待不会改变已读 batch 的梯度数值。现有日志没有逐步数据等待时长或异常步各反传分支 norm,故只能排除上述固定时点/持续故障解释,不能确认具体数值算子;不在正式 run 中途改训练代码或 optimizer。 + +冻结的完整 development panel 上,严格配对 S2 30K→50K,负值为 50K 改善,前三项 mm、最后 2D px;原始结果见 G2 `logs/s2_30k_vs_50k_{h2o,arctic,hot3d}_full.json` 的最后一行(HOT3D stdout 含 VRS 信息行)。 + +| 源/输入 | clips | 3D/mesh 分母 | 2D 分母 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O / RGB+Depth+K | 96 | 1536 | 1536 | -7.287 | -2.153 | -7.216 | -3.821 | +| ARCTIC / RGB+K | 136 | 704 | 1349 | -6.289 | -3.453 | -6.199 | -7.692 | +| HOT3D / RGB+K | 248 | 3573 | 3289 | -14.017 | -1.891 | -13.814 | -5.288 | + +HOT3D 50K absolute/root-relative/MPVPE/2D 均值 `65.981/27.860/65.553 mm/18.229 px`,absolute p95 `168.30→154.12` mm(30K→50K);Aria absolute/MPVPE `-17.145/-16.907` mm,Quest3 `-12.454/-12.267` mm。三源四项均值均优于 30K,37.5K 的 HOT3D 中途回退没有延续到 50K;这些仍是 development 指标,不是最终 benchmark。确认端点和数据合同无错误后,已对控制器 PID 2793759 发送 `SIGCONT`,继续注册的 S3 2K 健康门与后续覆盖训练;继续保留 30K、37.5K、50K checkpoint,不以中途尖峰自动归咎于 checkpoint/I/O。 + +23:30 HKT,S3 2K 高分辨率健康门完整 checkpoint SHA256 `2bb0ae97640e50978a896922d7a6bc966a86c5462d77c55fd8c5dc125def4666`,正式审计 `pass`、`errors=[]`,H2O/ARCTIC/HOT3D 曝光 `4,800/4,200/3,000`,七种模式均有有效监督。2,000 条 loss/grad 有限,最大 batch loss `2.314`,首/末 100 步均值 `0.423→0.517`,末 100 步 preclip grad norm 中位数 `100.87`,裁剪 `727/2,000`。本阶段 `grad>500` 与 `>1000` 均仅两次:step 305 的 `435,630.06`(loss `0.463`、LR `1.525e-5`)及 step 932 的 `1,650.03`(loss `0.478`、LR `4.66e-5`);无非有限值或连续失稳。因为 305 在 S3 自身的 1,000-step warmup 内,S2“尖峰均在 warmup 后”的观察不能推广至 S3。 + +为区分固定 batch/数值条件与偶发 I/O/通信,控制器一度仅 `SIGSTOP`,子进程照常完成 S3 2K。在 G2 隔离目录 `diagnostics/s3_replay_305/` 从同一 S2 50K parent、相同六卡/数据/采样/optimizer 重新训练至 305;第 305 步 loss `0.4629574716091156`、grad norm `435630.0625`、LR `1.525e-5` 与正式账本**逐值相同**。另一个隔离回放 `diagnostics/s3_replay_304/` 的第 304 步 loss/grad/LR 亦逐值相同,并保留完整 304-step checkpoint。305 回放的 rank0 分组梯度:`rotation_head=391,593.5`、`rgb_encoder.projection=142,719.1`、`decoder.spatial=110,378.9`、`decoder.temporal=57,821.1`,`translation_head=75.4`;这将异常定位到旋转预测相关的反传链路,但**尚不能证明**具体是 6D 正交化、某个 loss 项或哪只手/哪帧。隔离诊断脚本的 S3 扩展仅在本地副本,未进入 G2 的签名训练代码;远端脚本传输受限,不声称逐 rank 算子检查已完成。异常更新均经全局 clip=100,S2 50K 的三源四指标也未显示持续损害;因此在保留所有诊断与 checkpoint 的前提下已 `SIGCONT` 控制器,放行已注册的 S3 全段。若后续尖峰频率、loss 或 HOT3D 分组指标恶化,再停阶段控制器做 304-step 精确状态的逐 rank 分支分析,不在当前正式 run 中途热改模型或 optimizer。 + +S3 2K 的控制器固定 32-clip/source development 诊断相对 S2 50K(同一 panel SHA、metric 实现、逐项分母;负值为 S3 2K 改善): + +| 源/输入 | 3D/mesh 分母 | 2D 分母 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:|---:|---:| +| H2O / RGB+Depth+K | 512 | 512 | -4.086 mm | -1.980 mm | -4.339 mm | +1.208 px | +| ARCTIC / RGB+K | 160 | 321 | +3.548 mm | +6.729 mm | +3.175 mm | +5.220 px | +| HOT3D / RGB+K | 466 | 446 | +6.907 mm | +4.248 mm | +7.117 mm | +10.723 px | + +这是切入 512x896/S3 新 optimizer 后的**早期回退风险**,不是 S3 最终表现或健康门通过即性能提升的证明。S2 早期也曾回退后于 50K 改善,但不能据此保证 S3 重复该走势;保留既定预算,注册的 S3 10K checkpoint 落盘后用相同分母重测,再看是否要做更深的分源/尾部诊断。 + +23:37 HKT 追加:S3 全段从正式 2K checkpoint resume 后,step 2024 又出现 preclip grad norm `11,517.7646`、loss `0.7618005`,邻域未见非有限值。G2 隔离 `diagnostics/s3_replay_2024/` 从**正式 S3 2K 完整 optimizer/RNG checkpoint** 续训 24 步,step 2024 loss、grad、LR 与正式账本逐值相同;rank0 分组 `rotation_head=10,691.94`、`rgb_encoder.projection=3,005.95`、`decoder.spatial=2,488.49`、`decoder.temporal=1,255.76`。这是第二个独立、可复现的旋转反传主导尖峰,进一步不支持偶发保存/通信/I/O 解释,但仍不能仅凭分组梯度断言 6D 正交化是唯一原因。正式进程约 2.9K/83,334,六卡活跃,继续监测 10K 完整 checkpoint 的尖峰频率和三源固定 development 性能;若出现持续回退或数值异常,再在隔离支路验证旋转实现的受控修正,不在正式 run 中途热改。 + +23:52 HKT 对第 305 步的更深隔离诊断:从精确重放的 S3/304 checkpoint 恢复每 rank RNG,在相同六个 tile 上单样本反传。五个样本的 grad norm 约 `142–212`;**rank 1 的 H2O/RGB tile `7db06120b58d414d6f626c05:40` 为 `2,613,779`**,其中 `rotation_head=2,349,560`。该样本有效预测 joint z 最低 `0.447 m`、原始 6D 正交残差最低 `1.322`,排除近零投影深度与 6D 向量共线两种解释。最大旋转矩阵梯度元素约 `160,942`,对应旋转 `cos(angle)=-1.0`、`sin(angle)=5.403e-7`;当前 `geometry/rotations.py` 的 `matrix_to_axis_angle` 在此使用 `angle/(2*sin_angle)`,比例因子约 **`2.907e6`**。只在诊断进程中令 `cos(angle)<-0.9999` 的 MANO 转换输出保持**相同前向值**但断开该分支反向,rank 1 总 loss 仍 `0.3581964`,grad norm 从 `2,613,779` 降至 `97.46`;这是近 180° 反传病态的强因果证据,而不是 I/O 或通信偶发。此 selective-detach 是定位用反事实,**不是已验证的训练修复**:它丢失这些旋转的 MANO 几何梯度。直接使用 G2 已装 Kornia 0.8.2 的 matrix→axis-angle,隔离样本反而出现 NaN 梯度;autograd anomaly 指向其 matrix→quaternion 未选分支的 `DivBackward0`。因此未把 Kornia 或 selective-detach 热改进签名训练代码。至约 S3 5.5K,总 `grad>1000` 仍为 3 次、最大 loss 仍 `2.314`;在 10K 同分母评估前继续保留正式训练与原始 checkpoint。 + +近 180° 转换的**未上线候选**仅在 G2 内存中测试:对 Kornia 0.8.2 matrix→quaternion 的四个开方分支先夹到正数,再用有安全小角分支的 quaternion→axis-angle;没有修改安装包或签名模型代码。在 S3/304 完整状态的六个原定 tile 上,候选的 rank 1 H2O/RGB loss `0.358196→0.293856`、单样本 grad norm `2,613,779→96.37`,另五 rank 的 loss 和梯度基本不变、无非有限值。原样 Kornia 调用以及仅修小角分支均产生 NaN,不能作为替换方案。当前证据仅是一次精确状态的局部反事实,不证明多源长期收敛/benchmark 更好,也不构成正式 run 热改依据;如 10K 性能或异常频率不满足门槛,需另起版本化受控分支验证并重新审计 checkpoint/code 身份。 + +00:20 HKT,S3 10K checkpoint `s3_update_0010000.pt` 独立 SHA256 `b2b962d167ba4c2019852bb135e45c4834da87511e01e536dcee32f375f2261f` 与训练记录一致,正式审计 `pass`、`errors=[]`。10,000 条 loss/grad 均有限,最大 batch loss `2.451`,首/末 100 步均值 `0.423→0.472`,`grad>1000` 共 4 步(305、932、2024、6929),均被 global norm 100 裁剪。两个最大尖峰已从完整 optimizer/RNG checkpoint 在相同六卡精确重放,故不是随机 checkpoint 保存、DDP 通讯等待或数据读取延迟触发;S3 step 305 发生在 1,000-step warmup 内,故不能笼统声称所有尖峰都在 warmup 后。若有未记录的历史 I/O 抖动,它仍可能影响 wall time,但不会解释逐值相同的梯度尖峰。至少 step 305 已定位到近 180 度旋转的 `matrix_to_axis_angle` 反传奇异性;针对其他尖峰不能仅凭相似的 rotation-head 分组梯度推定完全相同的精确路径。 + +S2 50K→S3 10K 冻结完整 development panel 的同分母差值(负值为 S3 改善;前三项 mm,最后 2D px): + +| 源/输入 | clips | 3D/mesh 分母 | 2D 分母 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O / RGB+Depth+K | 96 | 1536 | 1536 | +0.314 | -0.288 | +0.356 | +4.148 | +| ARCTIC / RGB+K | 136 | 704 | 1349 | -6.143 | +2.628 | -6.252 | +0.127 | +| HOT3D / RGB+K | 248 | 3573 | 3289 | +1.949 | +4.038 | +1.886 | +4.581 | + +这是 S3 的 10K/83,334 中途点,不是终点。ARCTIC 的位置/mesh 收益与 root-relative 回退并存,HOT3D 四项均退且 absolute p95 `154.12→190.25 mm`、p99 `320.08→437.96 mm`;既不能因有限尖峰断言全段训练失效,也不能把当前 checkpoint 称为改进。另用完全相同 panel 比较 S3 2K→10K 以判断高分辨率阶段内走势;正式 run 保持原代码与注册预算,修复候选只允许另起版本化对照。 + +00:52 HKT,S3 **2K→10K** 的三源完整配对完成,分母与上表逐项完全相同;负值表示 10K 改善: + +| 源/输入 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:| +| H2O / RGB+Depth+K | -1.346 mm | +0.063 mm | -0.778 mm | +1.109 px | +| ARCTIC / RGB+K | -1.600 mm | -3.369 mm | -1.503 mm | -2.764 px | +| HOT3D / RGB+K | -5.569 mm | -2.329 mm | -5.749 mm | -5.973 px | + +HOT3D 的 Aria 四项变化 `-8.478/-4.658/-8.791 mm/-4.476 px`,Quest3 `-4.114/-1.165/-4.228 mm/-6.729 px`;不是单一设备或只靠极少 clip 的恢复。原始配对输出为 G2 `logs/s3_2k_vs_10k_{h2o,arctic,hot3d}_full.json`。这支持 S3 从高分辨率/新 optimizer 切入后的阶段内恢复,但**尚未恢复至 S2 50K 的全部四指标**,尤其 HOT3D root-relative 和 2D。10K 后至约 14.3K 账本尚无新 `grad>1000`、loss/grad 均有限。继续既定 S3 到 20K 注册 checkpoint,重复冻结全量 panel 与尾部审计;若相对 S2 parent 的关键回退持续或尖峰频率上升,再从保留的完整 checkpoint 做单独版本化稳定旋转转换对照,不中途改当前 run 的代码或权重。 + +00:58 HKT,**未上线**的独立候选代码 `code/diagnose_rotation_singularity.py` 用四分支 quaternion 主元选择并保护未选分支反传。128 个覆盖 0、近 0、常规角度、近 π 和 π 的旋转,float64/float32 的最大重建矩阵元素误差分别 `6.7e-16/3.6e-7`,旧转换在近 π 样本分别达到 `1.989/1.851`;候选从 6D 输入的梯度均有限。另 10,000 个小于 3 rad 的随机旋转,候选与旧 axis-angle 最大元素差 `7.2e-7`;近 π 处 double `gradcheck` 通过。该脚本没有接入签名训练代码,也没有在完整 S3/304→305 真实样本上验证:通过 SSH stdin 流式运行被当前连接策略拒绝。已有 G2 内存中的另一安全 quaternion 候选曾通过该真实样本的局部测试,但不能把两者当成同一个已验证实现。20K 性能门前不替换正式训练。 + +01:23 HKT,S3 20K checkpoint `s3_update_0020000.pt` 的训练控制台、正式审计和独立 `sha256sum` 均为 `290e7c5951f9819d57965e93af92d0f03e40a159bf67f0c43ccfdd720642f16b`。冻结前 20,000 条账本的审计 `pass`、`errors=[]`,六卡完整状态、H2O/ARCTIC/HOT3D 曝光 `48,000/42,000/30,000`,七种输入模式都有曝光,监督元素 `116,676,453`;最大 batch loss `2.566`,无非有限或 `loss>100`,裁剪 `8,810/20,000`。完整扫描纠正了此前“10K 后没有新尖峰”的实时观察:step 17,885 的预裁剪梯度 `199,253.6`、loss `0.523`,前后步梯度约 `122/109`,非保存点。至 20K 的 `grad>1000` 共五步(305、932、2024、6929、17885);第 17,885 步尚未精确重放,不能直接断言与 305 同一反传路径。 + +S2 50K→S3 20K 的**相同冻结完整 development panel**,负值为 S3 改善;前三项 mm、最后一项 px,原始文件 G2 `logs/s2_50k_vs_s3_20k_{h2o,arctic,hot3d}_full.json`: + +| 源/输入 | clips | 3D/mesh 分母 | 2D 分母 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O / RGB+Depth+K | 96 | 1536 | 1536 | -1.169 | -1.477 | -0.265 | +2.561 | +| ARCTIC / RGB+K | 136 | 704 | 1349 | +1.899 | +4.838 | +1.595 | -0.710 | +| HOT3D / RGB+K | 248 | 3573 | 3289 | +2.267 | +2.575 | +2.296 | +5.165 | + +H2O 的 3D 从 10K 继续恢复,ARCTIC 的 3D 从 10K 明显回退;ARCTIC root-relative 在 17/17 个 recording 均退,不是单一片段尾部。HOT3D 四项仍差于 S2 parent,Aria 与 Quest3 的四项均值差都为正。纯 RGB 同面板消融:H2O 的 S2→S3 差值 `-2.679/-1.705/-1.741 mm/+2.767 px`;ARCTIC 为 `+0.159/+4.292/-0.106 mm/-0.734 px`。ARCTIC root-relative 在 RGB 和 RGB+K 都退,故不能只归咎于 K;20K 的 K 相对 RGB 还额外恶化 ARCTIC absolute/mesh 约 `1.6 mm`。所有配对模型均接收同一 512x896 GT batch,分母、panel hash 和 indices 一致。这是 development 中途点,不是 official validation;S3 20K 的 LR 约 `4.43e-5`,远高于 S2 终点约 `5e-6`,阶段切换仍可能有性能摆动。保留 parent 与 10K/20K,不把 20K 当最优点。 + +01:53 HKT,另一次 S3 step 21,802 预裁剪 grad norm `2,987.76`、loss `0.350`。从完整 20,834 checkpoint 在隔离 `diagnostics/s3_replay_21801/` 六卡重放至 21,801:前 966 条账本与正式记录**逐字节相同**,端点 loss/grad/LR/曝光逐值相同,checkpoint SHA256 `8bb7ae76f589f255eea974197938bddda9fd94b02412e55de86a55d73efd614e`。恢复各 rank RNG 后的 21,802 单样本反传定位到 rank 4 ARCTIC/RGB tile `d946707dea20f21afaa5cbbd:40`,其 grad norm `17,919.9`,`rotation_head=16,522.7`;另五 rank 为约 `130–364`。该样本有效 joint 最小深度 `0.659 m`、6D 正交残差最小 `0.806`,不是近零深度或共线 6D。只在**诊断进程**中令 `cos(angle)<-0.9999` 的 MANO matrix→axis-angle 输出保留原前向值但断开反传,loss 精确保持 `0.23497647`,rank 4 grad `17,919.9→207.2`、rotation head `16,522.7→5.3`;近 π 条目包括八个 `mano_pose_valid=true` 的 wrist/root 旋转。这是第二个被精确因果定位的近 π 转换梯度尖峰(第一个是 305),不支持保存/通信/I/O 为触发原因。selective-detach 会丢失有效监督的几何梯度,**不是生产修复**。正式训练代码和 checkpoint 链均未改变;稳健转换仍需真实样本和长期多源对照验证,下一次固定指标门在 30K。 + +02:20 HKT,冻结 development 输入上的有效 wrist/root `cos(angle)<-0.9999` 频率(S2 50K→S3 20K,分母是有效手帧;输出原始计数 G2 `logs/s2_50k_vs_s3_20k_{h2o,arctic,hot3d}_near_pi.txt`):H2O `23→31/1536`,ARCTIC `25→25/1349`,HOT3D `40→20/3573`。两版近 π 条目都只发生在全局 wrist/root,非局部关节。这说明转换 bug 对少数有效帧真实存在,但 ARCTIC 频率未升、HOT3D 反而减半,**不能把两源的普遍四指标回退归因于该 bug**。H2O 的 2D 退化可能部分受其影响,但仅凭频率不能量化贡献。 + +同一 ARCTIC 136-clip 面板上,临时关闭 temporal 的 root-relative 代价(off minus on)从 S2 50K `+5.545 mm` 变成 S3 10K `+2.142 mm`、S3 20K `+1.412 mm`;absolute 对应 `+14.302/+11.513/+8.499 mm`。S3 20K 与 S2 parent 在 temporal 关闭后的 root-relative 只差 `+0.705 mm`,正常开启却差 `+4.838 mm`,约 `4.133 mm` 的差分对应时序增益缩水。这是**推理消融的代数分解**,不等于训练因果归因。为检验 temporal block 自身的权重漂移,在只读推理中将 S3 20K 的 36 个 `decoder.temporal.*` tensor 换回 S2 50K,其余权重不变;对 S3 原模型四项反而变化 `+3.550/+0.122 mm/+3.528 mm/+0.766 px`,说明简单单块权重替换不可用,spatial/head 与 temporal 已共同适配。原始结果 G2 `logs/s{2_50k,3_10k,3_20k}_arctic_temporal_on_vs_off_full.json` 及 `logs/s3_20k_arctic_s2_temporal_swap_full.json`。 + +已在**本地隔离副本** `artifacts/clean_gt_from_dino_20260925/code_stable_rotation_v1/` 实现四分支 quaternion 稳定转换,不改原 `code/` 或 G2 签名 run;零角、近 π、随机重建与 6D 梯度检查连同既有合同共 `8/8` 测试通过。该实现仍需在 G2 完整真实样本、跨源长期训练和 benchmark 上验证;本地数学通过不构成可直接替换正式模型的证据。 + +02:24 HKT,S3 30K checkpoint `s3_update_0030000.pt` 的训练控制台、审计与独立 SHA256 均为 `a76b2f7e24c68d45535022f3e5469425fd1acbd91ac5f3c7170d03139ac02a44`。冻结 30,000 行账本审计 `pass`、`errors=[]`;H2O/ARCTIC/HOT3D 曝光 `72,000/63,000/45,000`,监督元素 `175,277,423`,最大 loss `2.566`、无非有限值,裁剪 `11,632/30,000`。20K→30K 的 `grad>1000` 有四步:21,802、27,054、27,308、27,789,最后一次约 `346,445` preclip、loss `0.698`;除 21,802 外尚未精确定位,不能自动假定同源。30K 三源固定完整 development 对照已启动,待结果判断 LR 下降后的走势。正式训练仍按原代码推进。 + +02:42 HKT,30K 三源相同冻结 development 全量配对完成。以下是 **S3 30K minus S2 50K**;负值为 S3 改善,前三项 mm、最后 2D px,分母与 10K/20K 完全相同: + +| 源/输入 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:| +| H2O / RGB+Depth+K | -1.262 | +0.356 | -1.930 | +2.048 | +| ARCTIC / RGB+K | +11.998 | +5.466 | +11.527 | +2.832 | +| HOT3D / RGB+K | -1.407 | +3.106 | -1.474 | +4.187 | + +原始结果 G2 `logs/s2_50k_vs_s3_30k_{h2o,arctic,hot3d}_full.json`。HOT3D absolute/mesh 在 20K→30K 有约 `3.7 mm` 恢复,但 root-relative/2D 仍差于 parent;Aria 与 Quest3 的 root-relative 分别退 `3.16/3.08 mm`,2D 均退。ARCTIC 则从 10K 到 30K 连续恶化,root-relative 的 17/17 个 recording 均退、absolute 多数 recording 退,非单一 outlier。ARCTIC 纯 RGB 的 parent→30K 差值仍为 `+10.004/+5.909/+9.555 mm/+2.799 px`,并非 K 独有。其源内训练详细 loss 在 S3 10K→20K 与 20K→30K 的不配对窗口未同步爆炸,不能据此证实或排除过拟合/样本难度变化。 + +ARCTIC 的内置 `hybrid-parent-root` 只读消融:保留 S3 30K 的局部姿态、mesh 形状及其它输出,把 wrist/root translation 换成 S2 50K 的预测,parent→hybrid 变成 `-1.458/+5.466/-1.317 mm/+1.568 px`。因此 S3 的全局位置预测解释了约 `13.456 mm` absolute 和 `12.844 mm` mesh 差值;root-relative 仍退 `5.466 mm`,还存在独立的局部/时序问题。原始文件 G2 `logs/s2_50k_vs_s3_30k_arctic_hybrid_root_full.json`。这不是可部署的推理拼接,只是归因实验。 + +30K 不是可选最终点。S3 当前 LR 约 `3.5e-5`,仍远高于 S2 终点;完整高分辨率/全数据覆盖尚未完成。保留 S2 50K、S3 10K/20K/30K 的完整权重,继续签名 S3 到 40K 复测同面板;若 ARCTIC 广泛回退仍持续,优先设计真正版本化的低 LR/分组 optimizer 联合训练对照,分别约束 temporal、translation head 与其余 decoder,而不是仅增加 loss 权重、硬换 temporal 权重或把 selective-detach 当修复。稳定旋转转换仍是独立数值修复,需长期训练级验证。 + +03:09 HKT,按保存、通信、warmup 与 I/O 四个候选原因复核 S3 至约 37.8K 的完整账本。`grad_norm_max>1000` 共 11 步:305、932、2024、6929、17885、21802、27054、27308、27789、32094、34673,所有 loss 均有限(约 `0.318–0.762`),均经 global-norm 100 裁剪;没有一步落在已保存的 2K、10K、20K、20,834、30K checkpoint 上。训练循环先写该步 metrics,再检查保存里程碑,所以不能把同一步 preclip 梯度归因于随后的权重序列化。305/932 确实在本阶段 1K warmup 内,剩余 9 次在 warmup 后;因此 warmup 不能解释整组尖峰,也不能否认早期两次与升 LR 同时发生。G2 S3 console 的 NCCL/ProcessGroup timeout、DataLoader worker 退出、I/O error、traceback 关键词扫描为空;六卡 all-reduce 后的 `grad_norm_min/max` 一致。现有逐步账本没有 DataLoader 等待时间或保存耗时,不能证明没有瞬时 I/O 吞吐抖动;但 step 305 和 21,802 的完整 optimizer/RNG/六卡精确重放以及单样本反事实已把**这两次数值尖峰**定位到 `matrix_to_axis_angle` 的近 π 反传病态,非随机通讯或读取等待。其余 9 次尚未逐一做同等级因果定位,不应自动归并为同一根因。 + +只读权重插值诊断:以 S2 50K 为原点,对 S3 30K 浮点模型 tensor 做 `parent + alpha*(S3-parent)`,不训练、不保存候选正式权重。相同完整 development 面板下,`alpha=0.25` 相对 S2 的差值(absolute/root-relative/MPVPE mm、projected 2D px)为 H2O `-2.057/+0.028/-1.821/+1.228`、ARCTIC `-5.774/+0.867/-5.842/+0.531`、HOT3D `-3.622/-0.719/-3.542/-0.231`;ARCTIC `alpha=0.50` 为 `-4.389/+2.157/-4.578/+1.157`,完整 S3 30K 为 `+11.998/+5.466/+11.527/+2.832`。它说明较小的权重位移在三源上更均衡,**不等于**降低 LR 后训练的因果结果。原始输出 G2 `logs/s2_s3_30k_{h2o,arctic,hot3d}_lerp_alpha025_full.json` 和 `logs/s2_s3_30k_arctic_lerp_alpha050_full.json`。 + +训练索引大小 H2O/ARCTIC/HOT3D 为 `6,406/22,750/143,657` T8 tile;累计至 S2 50K + S3 30K 的源内曝光约 `192K/168K/120K`,即约 `30/7.4/0.84` 个源内 pass。HOT3D 首个完整 pass 计划落在 S3 约 45,772;40K 门仍在此前,不能因 30K 的 HOT3D 表现直接断言高分辨率/大源训练已经收敛。ARCTIC 小源在高 LR 下多次重复,过拟合是待证假说。已建立**本地、未部署 G2** 的 `artifacts/clean_gt_from_dino_20260925/code_s3_low_lr_v1/`:仅 S3 LR `5e-5/5e-6→1e-5/1e-6`,保留数据、loss、架构、可训练组和 S2 50K parent;新增 parent checkpoint SHA、旧 `clean_train.py` SHA、variant/resume/audit 身份约束,合同测试 `6/6` 通过。它尚未进行训练/评估,也不更改正在运行的签名 S3;由于当前 SSH 文件传输被策略拒绝,不能声称该受控分支已在 G2 启动。 + +03:22 HKT,S3 40K checkpoint `s3_update_0040000.pt` 已完整落盘;正式审计 `pass`、`errors=[]`,审计与独立 `sha256sum` 均为 `8106d6b756d9d4c3730d512c58d54058d52728d030b33c5a31d2c355a7cc6507`。前 40,000 条逐步账本连续、loss/grad 均有限,最大 batch loss `2.575`,无 `loss>100`;H2O/ARCTIC/HOT3D 曝光 `96,000/84,000/60,000`,监督元素 `234,152,088`,全程裁剪 `13,419/40,000`。30K→40K 又有 3 次 preclip `grad>1000`(32,094、34,673、39,066),均非保存点;除已精确定位的 305/21,802 外,其余尖峰的相同根因尚未证明。G2 `logs/formal_v3_s3_0040000_audit.json` 和冻结前 40K 行的 `logs/s3_40k_metrics_frozen.jsonl` 是审计输入与输出。正式 S3 六卡仍继续。 + +同一冻结**完整 development** 面板比较 S3 40K 减 S2 50K,负值表示改善;前三项为 absolute/root-relative/MPVPE mm,最后为 projected 2D px。H2O 96 clips/1536 有效手帧为 RGB+Depth+K,ARCTIC 136 clips/704 3D 与 1349 2D 分母为 RGB+K,HOT3D 248 clips/3573 3D 与 3289 2D 分母为 RGB+K;每项配对分母与 10K/20K/30K 相同。 + +| 源 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:| +| H2O | -5.661 | -1.150 | -6.634 | -2.383 | +| ARCTIC | -6.767 | +6.166 | -7.027 | -3.043 | +| HOT3D | +10.514 | +2.894 | +10.292 | +4.258 | + +原始配对结果 G2 `logs/s2_50k_vs_s3_40k_{h2o,arctic,hot3d}_full.json`。H2O 四项同时改善;ARCTIC 的 global/root 位置和 2D 已从 30K 大幅恢复,但 root-relative 在 17/17 个 recording 仍退(范围 `+1.89` 至 `+15.40 mm`);HOT3D 的 Aria 与 Quest3 两组都回退,31 个 recording 中 24 个 absolute 退。ARCTIC 纯 RGB 对照也是 `-7.322/+5.531/-7.493 mm/-3.023 px`,故 root-relative 回退并非 K 输入独有。相同 ARCTIC RGB+K 面板关闭两版 temporal 后,parent→40K 变为 `-7.970/+1.396/-7.939 mm/-9.846 px`;S2 的 temporal 前向 root-relative 收益是 `5.545 mm`,S3 40K 仅 `0.775 mm`,约 `4.770 mm` 的总差值对应时序增益缩水。这是推理消融的代数分解,不是把训练因果唯一归于 temporal 权重;先前直接换回 S2 temporal tensor 也未恢复性能。相应原始输出 G2 `logs/s2_50k_vs_s3_40k_arctic_rgb_full.json`、`logs/s2_50k_vs_s3_40k_arctic_temporal_off_full.json`。 + +S2+S3 至 40K 的 HOT3D 累计约 `135K/143,657` 个源内 tile,尚未覆盖首个完整 pass;注册的第一次全覆盖约在 S3 45,772,50K 门在其后。S3 已实际越过 45,772,采样账本正常;完整唯一 tile 覆盖仍以冻结排程审计和 50K checkpoint 合同确认。故保留训练至至少 50K 同分母复测,不把 40K 的 HOT3D 波动直接当最终结论。本地低 LR 对照分支的 `6/6` 测试已用**真实 G2 S2 50K checkpoint** 的代码哈希总指纹 `49b099dae1536e1ce723cd18d4b24b85bd12362a1ad55f7429c7b0d7bcd72bdc` 锁定 parent;分支仍未部署、未训练。 + +HOT3D 40K 追加三项**同一完整 248-clip development 面板**的只读反事实(相对 S2 50K parent,负值改善): + +| 条件 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:| +| 正常 RGB+K | +10.514 | +2.894 | +10.292 | +4.258 | +| 纯 RGB | +10.318 | +2.241 | +10.076 | +3.713 | +| S3 局部输出 + S2 root translation(RGB+K) | +4.091 | +2.894 | +3.866 | +1.406 | +| 两版 temporal 都关闭(RGB+K) | +0.907 | -0.543 | +0.932 | -2.644 | + +纯 RGB 的 Aria/Quest3 absolute 各退 `+5.96/+12.50 mm`,说明高分辨率阶段 HOT3D 回退并非 K 独有。parent-root 混合令 absolute 少退 `6.423 mm`、2D 少退 `2.852 px`,但 root-relative 不变,证明平移漂移和局部误差并存。关闭两版 temporal 后,absolute 差从 `+10.514` 缩到 `+0.907 mm`,root-relative 从 `+2.894` 变为 `-0.543 mm`;S2→S3 的 temporal 增益缩水在配对平均上对应 `9.607 mm` absolute、`3.437 mm` root-relative、`6.902 px` 2D。**root 替换与 temporal 开关的救回量不可相加**,因为 temporal 也会影响 root 预测。它们是推理反事实,不证明某个单块参数独自导致退化;ARCTIC 同样有时序增益缩水,提示高 LR/high-res 联合更新可能破坏 S2 已学时序协同,但因果仍待低 LR 独立训练验证。原始输出 G2 `logs/s2_50k_vs_s3_40k_hot3d_{hybrid_root,temporal_off,rgb}_full.json`;50K 首轮覆盖后的同分母评估是下一门。 + +04:24 HKT,S3 50K checkpoint `s3_update_0050000.pt` 完整落盘,审计 `pass`、`errors=[]`,独立 SHA 与审计同为 `c16307f1a3f1b821748b1b64ce5cac2558cc55c7b8fd40e2803096d8d7777e03`。前 50,000 条账本连续且 loss/grad 有限,最大 batch loss `2.575`,无 `loss>100`;本阶段累计 H2O/ARCTIC/HOT3D 曝光 `120K/105K/75K`,与 S2 50K 合计 `240K/210K/150K`,总采样 cursor `600,000` 已越过静态覆盖审计给出的 HOT3D 首次完整位置 `574,629`。40K→50K 仅 1 次 preclip `grad>1000`(48,593,loss `0.693`),裁剪 `898/10,000`,较 30K→40K 的 `1,787/10,000` 下降。完整 checkpoint 与冻结前 50K 行的审计分别在 G2 `logs/formal_v3_s3_0050000_audit.json`、`logs/s3_50k_metrics_frozen.jsonl`。正式六卡仍向 S3 83,334 推进。 + +固定**全量 development** 面板、同输入/逐项相同分母的 S3 50K 减 S2 50K(负值改善;前三项 mm,2D px): + +| 源/输入 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:| +| H2O / RGB+Depth+K | -3.120 | -2.103 | -3.535 | -0.912 | +| ARCTIC / RGB+K | -3.704 | +6.184 | -4.003 | -3.328 | +| HOT3D / RGB+K | -3.636 | -0.018 | -3.570 | +0.104 | + +H2O 四项均值继续优于 parent,absolute/root-relative p95 分别 `57.15→53.14`、`32.91→27.34 mm`。ARCTIC 的 absolute/mesh/2D 有均值收益,但 root-relative 在 **17/17** 个 recording 都退、p95 `32.51→40.52 mm`;不是孤立样本。HOT3D 40K 的四项回退在首次源内覆盖后明显恢复:Aria/Quest3 的 absolute 分别 `-3.91/-3.50 mm`,31 个 recording 中 24 个 absolute 改善;但 root-relative、2D 仅近似持平,absolute p95 仍 `154.12→183.50 mm`,困难尾部未解决。原始文件 G2 `logs/s2_50k_vs_s3_50k_{h2o,arctic,hot3d}_full.json`。这些仍是 development,不是 official benchmark,也未达到四项在每源同时提升的选择门。 + +ARCTIC 50K 再关掉两版 temporal,root-relative 差从正常推理 `+6.184` 降到 `+0.861 mm`;S2 temporal 前向收益 `5.545 mm`,S3 50K 只剩约 `0.222 mm`。时序收益缩水从 40K 持续到 50K,且解释配对差值中的约 `5.323 mm`,但只是同权重消融的代数分解,不是单独的训练因果结论。原始输出 G2 `logs/s2_50k_vs_s3_50k_arctic_temporal_off_full.json`。 + +HOT3D 50K 的同一完整面板关闭两版 temporal 后,parent→S3 差为 `-8.597/-0.620/-8.539 mm/-7.167 px`,而正常推理为 `-3.636/-0.018/-3.570 mm/+0.104 px`。因此高分辨率的直接/非时序分支已有实质提升,但 S3 50K 的 temporal 增益相对 S2 仍缩水约 `4.961 mm` absolute、`0.602 mm` root-relative、`7.271 px` 2D;40K 的 absolute 增益缩水约 `9.607 mm`,50K 已部分恢复。不能把 temporal-off 的高分当作可部署模型,因为 S2 与 S3 绝对误差在 temporal-off 时仍高,且关闭时序改变了推理合同。ARCTIC 的时序退化更持久,HOT3D 的直接分支恢复与时序不足是两个并存事实。原始输出 G2 `logs/s2_50k_vs_s3_50k_hot3d_temporal_off_full.json`。当前不热改签名 S3:它尚有约 33K step,LR 在下降,需保留完整覆盖/收敛证据;同时保留 S2 parent 和所有注册 checkpoint,低 LR 对照分支仍仅在本地。 + +训练侧辅助检查:从 S3 `metrics.jsonl` 每 100 步记录的、当步含该源时的 `source_loss_terms.*.joint3d_root_relative` 取**逐详细行非样本加权平均**,ARCTIC 在 0–10K/10–20K/20–30K/30–40K/40–50K 五个窗口约 `0.0624/0.0575/0.0581/0.0552/0.0496`(各窗口约 97–106 行);HOT3D 约 `0.1275/0.1229/0.1042/0.1006/0.1061`(80–93 行)。ARCTIC 训练侧该 loss 总体下降,但 heldout root-relative 在 17/17 recording 回退,**符合泛化不足的候选解释,不足以证明过拟合是唯一根因**:窗口采样并非固定样本,loss 单位/监督 mask 与 development 指标也不同。直接 S2→S3 50K 的逐参数组权重位移读取命令被当前 SSH 连接策略拒绝,故没有该诊断结果;不从梯度分组大小臆测权重变化。正式训练保持运行,下一冻结门为 S3 60K。 + +对 S2+S3 50K 的实际 checkpoint cursor `600,000`,冻结 `CoverageSampler`/SQLite index 的 `audit_schedule.py --stage S1_S3 --samples 600000` 返回 `pass`:H2O `6,406/6,406`、ARCTIC `22,750/22,750`、HOT3D `143,657/143,657` 个唯一 T8 tile 全覆盖,且源码保证源内首轮完成前不重复 tile;各源首次完整的全局样本位置 `16,016/65,000/574,629`。七种 source×mode 的静态曝光分别为 HOT3D RGB+K/RGB `105,125/44,875`,ARCTIC RGB+K/RGB `105,239/104,761`,H2O RGB+Depth+K/RGB+K/RGB `168,190/23,863/47,947`;与已审计 S2 50K、S3 50K 两份 checkpoint 的模式账本逐项求和完全相等。**结论仅覆盖过滤后注册的 T8 tile 被实际采样至少一轮**,不等于每个源已经收敛或官方原始 split 的所有帧都作为独立 tile 出现。 + +后续找到仓库既有的只读、checkpoint SHA 绑定脚本 `scripts/analyze_phase8_checkpoint_drift.py`,完成此前未成功的逐组参数位移;其元数据 `step=-1` 是因为此脚本读取旧 schema 的 `step` 字段,而本 run 使用 `update`,不影响模型 tensor 的逐组 L2 统计。以下为 S3 checkpoint 相对固定 S2 50K parent 的 `||delta||_2 / ||parent||_2`,各行 checkpoint SHA 在审计报告中验证,原始 G2 `logs/s2_50k_vs_s3_{10k,20k,40k,50k}_weight_drift.json`: + +| S3 update | temporal | spatial | RGB projection | translation head | +|---:|---:|---:|---:|---:| +| 10K | 9.23% | 8.19% | 9.02% | 6.37% | +| 20K | 14.40% | 12.70% | 13.87% | 7.89% | +| 40K | 21.04% | 18.53% | 20.29% | 10.55% | +| 50K | 22.85% | 20.02% | 21.71% | 11.29% | + +S3 50K 的 DINO backbone 位移精确为零,符合 last-2 仍冻结;MANO layer 与 presence head 也未更新。ARCTIC temporal-on 相对 off 的 root-relative 收益在 S3 10K/20K/40K/50K 约 `2.142/1.412/0.775/0.222 mm`,与上表的持续权重位移同时发生。**这只是跨 checkpoint 相关性**:spatial 与 RGB projection 也等比例移动,不能断言 temporal 自身权重漂移是单独原因;此前仅换回 S2 temporal tensor 反而不改善,说明路径共同适配。受控下一候选应从相同 S2 parent、相同数据/损失重训高分辨率阶段,先测试整体更低 LR 是否保留 temporal 收益,再考虑 temporal 特别小 LR/分组 optimizer,不能只凭此表热改正式 S3。 + +### formal_v3 S3 60K 冻结审计与开发集评估 + +2026-09-26 05:27 HKT,S3 60K 注册 checkpoint `checkpoints/formal_v3_s3/s3_update_0060000.pt` 的独立 SHA256 为 `6a811e22e930f52c81b3bb6a83aad0f0f05aa9aa7afc94d67763388033b9172d`。`logs/formal_v3_s3_0060000_audit.json` 为 `pass`、`errors=[]`,审计连续 60,000 update 和六卡状态;H2O/ARCTIC/HOT3D 曝光为 `144,000/126,000/90,000`,监督元素 `350,799,373`,无非有限或 `loss>100` 更新,首/末 100 步均值 loss `0.4230→0.3610`,最大 batch loss `2.887`,总计梯度裁剪 `14,744/60,000`,末 100 步梯度中位数 `61.36`。这些证明运行和保存健康,不代表泛化性能过门。 + +固定**全量 development** 面板、同输入/逐项相同分母的 S3 60K 减 S2 50K(负值改善;前三项 mm,2D px): + +| 源/输入 | absolute | root-relative | MPVPE | projected 2D | +|---|---:|---:|---:|---:| +| H2O / RGB+Depth+K | -6.169 | -3.222 | -6.725 | -2.883 | +| ARCTIC / RGB+K | -4.847 | +4.434 | -5.155 | -4.094 | +| HOT3D / RGB+K | -4.508 | -1.083 | -4.381 | -0.054 | + +H2O 四项比 50K 继续改善。ARCTIC root-relative 回退从 50K 的 `+6.184` 收窄至 `+4.434 mm`,但仍在 **17/17** 个 recording 都退,p95 从 parent `32.51` 到 60K `35.69 mm`;不能通过整体均值掩盖该项。HOT3D 四项均值已全部低于 parent,但 2D 仅 `0.054 px`,应视作接近持平;absolute p95 从 50K 的 `183.50` 降为 `145.31 mm`,也优于 parent `154.12 mm`,31 个 recording 中 24 个 absolute 改善。原始配对输出为 G2 `logs/s2_50k_vs_s3_60k_{h2o,arctic,hot3d}_full.json`;它们是 development,不是 official validation。 + +同一 ARCTIC 面板改为纯 RGB,四项差为 `-4.527/+4.588/-4.830 mm/-4.334 px`,root-relative 与 RGB+K 的 `+4.434 mm` 接近,不能单独归因于 K。两版都关闭 temporal 后,ARCTIC 四项差变为 `-4.629/+0.019/-4.663 mm/-9.997 px`;60K 正常推理的时序 root-relative 收益约 `1.129 mm`,比 50K 的 `0.222 mm` 恢复,但仍低于 S2 parent 的 `5.545 mm`。50K→60K 的 ARCTIC root-relative 差距缩小约 `1.750 mm`,可代数分成非时序分支约 `0.842 mm` 改善与时序收益约 `0.907 mm` 恢复;这不是训练因果证明。原始输出为 G2 `logs/s2_50k_vs_s3_60k_arctic_{rgb,temporal_off}_full.json`。 + +同一 HOT3D 面板两版都关闭 temporal 后,四项差为 `-4.190/-0.742/-4.063 mm/-4.791 px`。相对 S2,60K 正常推理的 temporal 对前三个 3D 指标已多贡献约 `0.318/0.341/0.318 mm`,但 2D 时序收益仍少约 `4.737 px`;不能据此部署 temporal-off。原始输出为 G2 `logs/s2_50k_vs_s3_60k_hot3d_temporal_off_full.json`。 + +同一 S2 50K parent 到 S3 60K 的参数组相对 L2 位移为 temporal `23.927%`、spatial `20.902%`、RGB projection `22.390%`、translation head `11.756%`,DINO backbone 精确为零,见 SHA 绑定的 G2 `logs/s2_50k_vs_s3_60k_weight_drift.json`。时序参数仍在移动、ARCTIC 时序收益同时部分恢复,进一步说明不能只凭权重位移推定退化原因。05:54 HKT,签名 S3 六卡训练仍在约 64.2K/83,334 update;继续完成 S3,保留 S2 parent 和各注册 checkpoint,之后按冻结合同评估、审计再进入 S4,不热改当前 run。 + +S4 自动交接的非 GPU 预检(05:59 HKT):控制器 `run_formal_stages.py` 仅在 S3 83,334 端点训练返回并通过 checkpoint 审计后启动 S4 2K;S4 使用同一 T8/512x896 合同,主组 LR `1e-5`、最后两层 DINO LR `5e-7`。在 G2 CPU 上用真实 S3 60K checkpoint 构造 S4 模型并 `load_state_dict(strict=True)` 成功,完整 backbone 标志为 true;optimizer 分组为主组 142 个 tensor、DINO backbone 36 个 tensor,实际初始组 LR 分别为 `1e-5/5e-7`。这是**接口预检**,不能替代未来 S3 83,334 parent 的正式 2K 健康门。当前 checkpoint `.pt` 合计约 `18.99 GiB`,余盘约 `936 GiB`;训练代码另设 40 GiB checkpoint 总预算和至少 300/200 GiB 余盘门槛,后续每个保存点仍须继续核对。 + +终点评估范围核对(06:05 HKT):`clean_eval.py` 无 `--limit` 时会遍历冻结 manifest 全部 clip,并核对 manifest SHA、完整 backbone、非 smoke checkpoint、代码指纹及每项非零分母;控制器对 S3/S4 端点运行七种有效 source×input 模式,S4 冻结后再对独立 confirmation 重跑七种模式。这里的“全量”是**各自冻结 panel 的全量**:每个 role 的 H2O `96`、ARCTIC `136`、HOT3D `248` clips;development 和 confirmation 按录制不交叉。不能称作完整官方 val 或历史 HOT3D 2,048-clip heldout。历史 HOT3D 2048 缓存位于 `/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl`,实际 `2048` 行、`62` 个录制,是单独的比较集合;若用它与 A2/A3/S9L10 等历史权重比较,须在同一输入模式、GT mask 和指标分母下重跑,并把含 development 的全量结果标记为 selection-informed,不能替代 untouched confirmation 证据。 + +06:08 HKT,对 S3 62.5K 注册恢复点另做独立审计:`s3_update_0062500.pt` 的 `sha256sum` 与审计一致,为 `572b033419ca2b1e2a40bd20cb013ab3c39372f6840e40f2c898222d574e0515`;精确前缀账本 `logs/s3_62500_metrics_frozen.jsonl` 为 `62,500` 行,`logs/formal_v3_s3_0062500_audit.json` 为 `pass`、`errors=[]`,六卡完整状态、三源曝光 `150,000/131,250/93,750`、七种模式和监督账本均通过,无非有限或极端 loss,最大 batch loss `2.887`,裁剪 `14,794/62,500`。首次误将仍在追加的实时账本交给要求**恰好止于 checkpoint update** 的审计器,触发“行数/末行曝光不符”;该失败回执保存在 `logs/formal_v3_s3_0062500_audit_live_metrics_misuse.json`,不是 checkpoint 故障。签名训练未中断,06:08 已到约 66.4K。 + +06:10 HKT,按 S4 注册预算 `66,667 update × 6 clips = 400,002` 对冻结索引 `cache/trainable_t8_index.sqlite`(SHA256 `5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462`)执行只读 `audit_schedule.py --stage S4 --samples 400002`,返回 `pass`:H2O `6,406/6,406`、ARCTIC `22,750/22,750`、HOT3D `143,657/143,657` 个登记的唯一 T8 tile 均在源内重复前遍历到;对应源曝光 `140,000/100,000/160,002`,首次全覆盖的全局样本位置 `18,302/90,999/359,143`。七种 source×mode 均有预期曝光。**这是未来采样日程的静态审计,不是 S4 已经训练或各源收敛的证据**;正式 S4 checkpoint 到位后仍须核对实际曝光账本。 + +### formal_v3 S3 70K 与端点;S4 正式启动 + +2026-09-26 06:31 HKT,S3 70K 注册 checkpoint SHA256 `dabf7fac80cdc64ba6ca62836c94facf6facb1a7568e9b70a3d068d8e63ffbdc`;精确前缀 `logs/s3_70k_metrics_frozen.jsonl` 的 `70,000` 行与 `logs/formal_v3_s3_0070000_audit.json` 返回 `pass`、`errors=[]`,三源曝光 H2O/ARCTIC/HOT3D `168,000/147,000/105,000`,监督元素 `408,926,684`,裁剪 `14,897/70,000`,末 100 步 loss 均值 `0.385`、梯度中位数 `54.42`,无极端 loss。ARCTIC 固定 136-clip development RGB+K 配对(S3 70K 减 S2 50K,负值改善)为 `-5.379/+4.268/-5.683 mm/-4.240 px`;root-relative 的 704 有效手帧均值比 60K 的 `+4.434` 仅略收窄,p95 反而由 `35.69` 升至 `38.09 mm`。补跑 `--paired-groups` 后确认 17/17 个录制仍回退,逐录制差 `+1.929` 至 `+7.125 mm`。原始输出 G2 `logs/s2_50k_vs_s3_70k_arctic_full{,_paired}.json`,不把 70K 当正式选点。 + +07:54 HKT,S3 完整端点 `s3_update_0083334.pt` SHA256 `3a103e5b400992e961f43f4a5f4a7540f7d0f74fc464b41f5451ed53a699bdf7`;控制器审计 `logs/formal_v3_s3_0083334_audit.json` 为 `pass`、`errors=[]`,三源曝光 `200,001/175,001/125,002`,监督元素 `486,468,198`,裁剪 `14,964/83,334`,最大 batch loss `2.895`、末 100 步 loss 均值 `0.360`、梯度中位数 `50.35`,最终主 LR `5e-6`。控制器已完成**全部七种 source×input** 的冻结 development panel 评估,报告位于 `eval/formal_stages/formal_v3_s3_0083334_development_*.json`;均为非 smoke、checkpoint 代码与当前 evaluator 匹配。下表为 S3 端点实际均值;ARCTIC 3D/mesh 分母 `704`、2D `1349`,HOT3D 3D/mesh `3573`、2D `3289`,H2O 四项均 `1536`: + +| 源/输入 | absolute mm | root-relative mm | MPVPE mm | projected 2D px | +|---|---:|---:|---:|---:| +| H2O / RGB | 21.515 | 14.050 | 21.926 | 12.264 | +| H2O / RGB+K | 21.363 | 14.141 | 21.767 | 11.925 | +| H2O / RGB+Depth+K | 20.736 | 14.088 | 21.115 | 11.822 | +| ARCTIC / RGB | 30.769 | 21.695 | 30.408 | 17.993 | +| ARCTIC / RGB+K | 30.418 | 21.706 | 30.051 | 17.448 | +| HOT3D / RGB | 58.049 | 26.282 | 57.734 | 16.685 | +| HOT3D / RGB+K | 56.958 | 26.798 | 56.665 | 16.175 | + +以先前同 panel、同指标实现、同有效分母的 S2 50K 全量配对 reference 比较,三个主输入的 S3-S2 差值为:H2O RGB+Depth+K `-7.511/-2.961/-7.534 mm/-3.248 px`,ARCTIC RGB+K `-6.778/+3.699/-7.097 mm/-4.417 px`,HOT3D RGB+K `-9.024/-1.062/-8.889 mm/-2.053 px`。ARCTIC root-relative 虽从 70K 继续恢复,均值仍差于 S2 `3.699 mm`,p95 为 S2 `32.51`、S3 端点 `36.10 mm`;尚未计算录制级置信区间,不能写成统计显著性结论。S3 端点**不能宣称三源四项全面超过 S2**。这些是冻结 development,不是 untouched confirmation;后者只能在最终几何权重冻结后打开。 + +08:15 HKT,S4 2K 健康 checkpoint `s4_update_0002000.pt` SHA256 `f9457af84ea75e53e198a9f12c53fc95f5490b9b28b8bea5e51618bc95d887ab` 的正式审计 `pass`、`errors=[]`,六卡与七输入模式有效;H2O/ARCTIC/HOT3D 曝光 `4,200/3,000/4,800`,监督元素 `11,468,876`,裁剪 `33/2,000`,首/末 100 步 loss 均值 `0.402→0.380`,最大 loss `1.939`。控制器完成三源各 32-clip 健康评估并从该完整 checkpoint 精确 resume 到 S4 66,667;这三个前缀子集**不可**与 S3 全 development 均值直接相减。08:55 HKT,S4 实时约 8K,六卡仍训练;详细行的 DINO backbone 梯度非零,符合 last-2 解冻合同。S4 正式 full development 与 confirmation 尚未发生。 + +### formal_v3 四阶段完成与冻结评估 + +2026-09-26 15:31 HKT,正式控制器状态为 `complete`,不再有训练/评估进程。S1 `16,667`、S2 `50,000`、S3 `83,334`、S4 `66,667` 四个完整端点审计均 `pass`、`errors=[]`。最终完整 checkpoint 为 G2 `checkpoints/formal_v3_s4/s4_update_0066667.pt`,独立 `sha256sum` 与控制器/审计一致:`85a9e02274f94b69e2a634518f6f46244dbedb518b135f07be4b2c746be9bb15`。S4 账本恰好 `66,667` 行,H2O/ARCTIC/HOT3D 曝光 `140,000/100,000/160,002`(吻合预审计日程),监督元素 `385,885,152`,裁剪 `441/66,667`;首/末 100 步 loss 均值 `0.402→0.337`,最大 batch loss `3.075`,无非有限或 `loss>100` update。审计原件 G2 `logs/formal_v3_s4_0066667_audit.json`。这些证明正式训练合同完成,不单独证明四指标优于旧版。 + +S4 终点的七种输入模式各在完整冻结 development 与独立 confirmation 小面板执行一次,共 `14` 份报告;全部非 smoke、代码指纹匹配同一个最终 checkpoint、每项分母非零。下表列三个主输入的四项均值(前三项 mm,最后 2D px);H2O 每半 panel `96` clips,ARCTIC `136`,HOT3D `248`,两半按录制互斥。这不是完整官方 val 或历史 HOT3D 2048-clip benchmark。 + +| Panel / source / input | absolute | root-relative | MPVPE | 2D | +|---|---:|---:|---:|---:| +| Dev / H2O / RGB+Depth+K | 21.004 | 13.873 | 21.129 | 11.351 | +| Dev / ARCTIC / RGB+K | 30.954 | 21.661 | 30.601 | 16.902 | +| Dev / HOT3D / RGB+K | 56.625 | 23.725 | 56.398 | 14.881 | +| Confirmation / H2O / RGB+Depth+K | 20.444 | 13.244 | 20.667 | 10.999 | +| Confirmation / ARCTIC / RGB+K | 31.864 | 20.997 | 31.545 | 19.308 | +| Confirmation / HOT3D / RGB+K | 51.698 | 23.645 | 51.402 | 13.501 | + +与同一 development panel 上的 S3 端点比较,S4 对 HOT3D RGB+K 的 root-relative 降 `3.073 mm`、2D 降 `1.294 px`;H2O RGB+Depth+K root-relative 降 `0.216 mm`,但 absolute 升 `0.267 mm`;ARCTIC RGB+K root-relative 仅降 `0.045 mm`,absolute/MPVPE 各升约 `0.54/0.55 mm`。ARCTIC root-relative 仍比同 panel 的 S2 50K reference `18.007 mm` 高 `3.654 mm`,因此**S4 不是三源四项全面超过 S2 的权重**。确认集只评了 S4,没有同口径旧权重基线,不能凭两组绝对值宣称超过 A2/A3/S9L10;H2O 历史四指标与这次小面板分母不同,也不可直接横比。七模式原件 G2 `eval/formal_stages/formal_v3_s4_0066667_{development,confirmation}_*.json`。后续需完成同口径旧模型对照、分录制/手侧与困难样本分析;配方中的 RGB-only presence head 是 S4 冻结后的独立附加阶段,当前控制器未训练它,不可把旧 A2/P4 head 直接移植到新特征上。 + +### 冻结确认集的旧权重配对比较(2026-09-28) + +同一冻结 confirmation clip、相同实际输入模式、GT validity mask 和指标实现下,对 S4 与历史权重逐手帧配对。下表均为 **S4 减旧权重**;负数才是改善,前三项单位 mm,2D 单位 px。括号为按物理录制重采样 2,000 次的 95% bootstrap 区间,不是按相关帧独立重采样。 + +| Source / input / old weight | absolute | root-relative | MPVPE | 2D | +|---|---:|---:|---:|---:| +| H2O / RGB+Depth+K / A2 | +4.007 [3.032, 4.890] | +0.577 [-0.108, 1.256] | +4.875 [3.847, 5.858] | +1.784 [1.191, 2.369] | +| H2O / RGB+K / A6-K | -2.925 [-4.519, -1.312] | +0.394 [-0.037, 0.833] | -2.683 [-4.619, -0.754] | -2.874 [-4.890, -0.865] | +| H2O / RGB / A3 | -8.523 [-11.733, -5.290] | -0.263 [-0.702, 0.198] | -8.713 [-12.248, -5.166] | -9.240 [-12.879, -5.467] | +| ARCTIC / RGB+K / A2 | +2.456 [-0.480, 5.147] | +1.243 [0.305, 2.240] | +2.350 [-0.511, 4.978] | +3.765 [2.362, 5.296] | +| ARCTIC / RGB / A3 | -0.398 [-2.812, 1.913] | +1.275 [0.208, 2.471] | -0.549 [-2.951, 1.751] | +0.281 [-0.994, 1.405] | +| HOT3D / RGB+K / S9L10 | +2.271 [0.226, 4.051] | -0.979 [-1.767, -0.149] | +2.345 [0.325, 4.096] | -1.996 [-3.342, -0.789] | +| HOT3D / RGB / A3 | -306.895 [-330.107, -284.094] | -85.022 [-89.682, -80.067] | -310.012 [-333.188, -286.997] | -160.251 [-170.666, -149.330] | + +H2O 每项 1,536 有效手帧、12 个录制;ARCTIC 3D/mesh 为 712 个右手有效帧,2D 为 1,432 个左右手有效帧,17 个录制;HOT3D 3D/mesh 为 3,567、2D 为 3,350 个有效手帧,31 个录制。与 A2 的 H2O Depth+K 比较,S4 的 absolute/MPVPE/2D 在 12/12 个录制均更差;因此 **S4 不替换 A2 的主 Depth+K 权重**。ARCTIC 相对 A2 的 root-relative/2D 退化更明确,但 3D/mesh 均值差的区间跨零。HOT3D 相对 S9L10 呈清楚的权衡:root-relative/2D 改善,absolute/MPVPE 退化;absolute 左手平均 -1.10 mm、右手 +5.72 mm,提示需检查手侧和 root 误差,不能称为四项全面提升。A3 在 HOT3D 的巨大差距只是这组旧权重在该外部域表现很差,不能单靠它证明数据清洗因果收益。 + +配对 evaluator 先在一条 H2O clip 上与正式 `clean_eval` 的 S4 四指标、分母和监督覆盖逐项相等;每次旧模型完整 checkpoint 严格载入、核对 SHA256,两个预测只共享同一个解码样本,不因预测 presence 过滤 GT。原始逐录制、手侧和最大误差案例保存在 G2 `eval/legacy_comparison/paired_*_confirmation.json`,并复制至本地 `artifacts/clean_gt_from_dino_20260925/paired_*_confirmation.json`。最终 S4 **完整** checkpoint 另在本地 `artifacts/clean_gt_from_dino_20260925/s4_update_0066667_full_backup.pt` 备份,字节数 `940,990,914`,与 G2 原件的 SHA256 同为 `85a9e02274f94b69e2a634518f6f46244dbedb518b135f07be4b2c746be9bb15`;G2 原件未移动。仍待独立 RGB-only presence head 与对应可视化门槛;目前不得把 S4 作为具备已校准 visibility 的展示模型。 + +### 冻结 S4 的独立 RGB-only presence 阶段(2026-09-28) + +已在 S4 匹配的冻结 RGB encoder 空间特征及 hand token 上重训 scalar、grid2d、axis1d 三种小 head。ARCTIC 自然+裁切 T8 训练/校准/验证 `6,372/764/512` clips,录制 `239/26/34` 互斥;完整投影正/负/unknown 标签与旧审计逐项一致,7,648 条缓存无跳过,训练只更新 513 或 17,003 参数 head。最终 grid2d 在固定验证的自然/裁切召回 `99.86%/99.02%`,缺手误报 `10.31%/28.88%`;进出画 transition 正例只保留 `40/49`。因此**不晋升默认 visibility 过滤**,也不把它用于几何四指标。完整标签、loss、梯度、选点、手侧/部分出画/腕部出画与录制 bootstrap、head SHA256 均见 [独立结果](artifacts/clean_gt_from_dino_20260925/s4_rgb_presence/RESULTS_ZH.md)。完整 S4 几何权重、旧权重与所有可再生缓存未覆盖。 + +## 历史:HOT3D mask-only 修正与 formal_v2(已证伪) + +2026-09-25 16:57 HKT:旧 S1 在发现系统性 HOT3D 无效投影监督后停止,原自动阶段控制器也已停止;**旧 S1 2K 健康门和后续 checkpoint 不可作为新配方的 parent,也不可当作有效比较结果**。旧预检与中止的 S1 checkpoint、metrics 原样移入 G2 `archive/checkpoints_before_hot3d_mask_fix_20260925/`(约 19 GB);新 `checkpoints/` 为空,旧日志与投影诊断保留在 `logs/`。未删除权重。下面“当前状态”和“S1 首个健康门”两节是旧 run 的历史记录,不代表 formal_v2 已通过相同门槛。 + +根因及修正见训练 recipe 的 HOT3D amendment。固定 4,167-step 旧权重重放四个尖峰样本,loss 从 `1873.65/2593.77/6635.64/6655.73` 降为 `4.73/0/0/0`。同一批均匀抽取的 100 个 HOT3D T1 tile,原 194 只有效标注手中只有 70 只 mesh 入画;旧 2540 个有效 2D 关节中 1407 个画面外。修正后 70 只可见手保留完整几何监督,977 个 2D 有效关节均在画面内。`tests/test_hot3d_supervision_masks.py` 的部分入画、完全出画、T8 逐帧合同在 G2 为 3/3 通过。修正版 source 文件 `src/foundation_hand/data/hot3d_dataset.py` SHA256 为 `8a016f13a16e79fdcaefeabd13925410a6022194be8135fda56010b3c1bbf8e9`。 + +新正式命名空间为 `checkpoints/formal_v2_s1` 至 `formal_v2_s4`,控制器状态与日志统一带 `formal_v2` 前缀。必须从官方 DINO 新起 S1,先完成 2K 健康门和 mask/梯度审计,再接续完整 S1,之后由控制器按原 S2–S4 预算和冻结评估合同继续;不能在原 checkpoint 上热改代码并 resume。 + +2026-09-25 16:59 HKT:`formal_v2` S1 的 2,000-step 健康门已从官方 DINO 在 G2 六卡启动,运行 PID 见 `logs/formal_v2_s1_health2k.pid`,逐步账本为 `checkpoints/formal_v2_s1/metrics.jsonl`;启动后确认六个训练 rank,431/2000 时 loss 与 grad norm 有限。独立控制器 `logs/formal_v2_controller.pid` 已启动,当前状态文件 `logs/formal_v2_controller_state.json` 为 `waiting_for_s1_health`。健康门结束后它会先做 checkpoint/曝光/梯度审计与 32-clip/source development 诊断,通过后才精确 resume 至 S1 16,667 并继续 S2–S4。此处只证明训练正在运行,**尚未声称新 2K 健康门或任何完整阶段通过**。 + +2026-09-25 17:05 HKT 更新:新 S1 2K 完整 checkpoint `checkpoints/formal_v2_s1/s1_update_0002000.pt` SHA256 `70d09c19c4ba9b313810bd600a223ad48f8dcdfead9e2f285645db277582ea18`,`logs/formal_v2_s1_0002000_audit.json` 为 `pass`,错误列表为空。2000/2000 loss 与 grad norm 有限,最大 batch loss 5.487,首/末 100 步平均 loss 4.058→1.141;H2O/ARCTIC/HOT3D 曝光 4800/4200/3000,监督元素 1,304,201,裁剪 1182/2000 步。三个固定早期 development 条件均已评估;控制器已从此 checkpoint 续训 S1 16,667,账本超过 2.2K。HOT3D 的 2D 早期均值约 203 px,但新 mask 改变了评估分母,不能拿旧版约 8947 px 做同分母性能改善声明。 + +## 旧 run 历史状态(已停止) + +2026-09-25 16:15 HKT,当时 S1 从正式 2,000-step checkpoint 恢复,目标 16,667 update;`logs/formal_s1_full.pid` 和 `logs/formal_controller.pid` 对应的进程现均已停止。旧 step 账本位于 `archive/checkpoints_before_hot3d_mask_fix_20260925/formal_s1/metrics.jsonl`,旧控制器状态保留在 `logs/formal_controller_state.json`。这些历史进度不代表修正版 formal_v2 的进度;必须核对实时进程、日志及新端点。 + +## S1 首个健康门 + +S1 从官方 DINOv3-B 初始化,211 个 backbone tensor 与官方 safetensors 相等,非 DINO 模块新初始化;六卡、global batch 6、BF16、clip=100。2,000 update / 12,000 clips 用时 338.30 秒,35.47 clips/s,峰值 1.29 GiB/卡。完整 checkpoint `checkpoints/formal_s1/s1_update_0002000.pt` SHA256 `6daa21a47100a59d7b554ad79a1e7662c265aaa6e502611a2488cb0d0391cf77`,不是 smoke 权重。 + +只读审计 `logs/formal_s1_2000_audit.json` 为 `pass`:2000/2000 条有限 loss/grad,source 曝光 H2O 4,800、ARCTIC 4,200、HOT3D 3,000;七种来源/输入模式均有曝光;1,422,251 个逐手监督元素、102 个账本键与 checkpoint 一致。前/末 100 步平均 loss 5.444→2.601,末 100 步预裁剪 grad norm 中位数 118.75,2,000 步中 1,387 步裁剪。Depth、ray、spatial decoder、RGB projection 和 translation head 都有非零梯度;S1 temporal 按设计冻结。 + +同一冻结 development 前 32 clips/source 的早期配对诊断,四列依次为 absolute MPJPE、root-relative MPJPE、MPVPE(mm)与 MANO projected 2D error(px): + +| 来源/模式 | S1 1,000 smoke | 正式 S1 2,000 | +|---|---|---| +| H2O / RGB+Depth+K | 98.14 / 41.57 / 96.57 / 49.08 | 82.73 / 40.15 / 81.97 / 52.76 | +| ARCTIC / RGB+K | 172.32 / 44.41 / 170.67 / 109.05 | 89.47 / 42.95 / 88.83 / 65.96 | +| HOT3D / RGB+K | 401.36 / 127.51 / 427.69 / 9054.33 | 345.00 / 96.61 / 392.57 / 8947.12 | + +这些是冷启动早期健康诊断,不能视为最终四指标成绩。HOT3D 2D 中位数 695→365 px,但极端长尾仍使均值约 8,947 px;H2O 2D 均值也小幅反向。后续须在 S1/S2/S3/S4 的固定面板持续跟踪,不通过隐藏异常或预测 visibility 过滤改分母。 + +## 运行合同 + +正式端点依次为 S1 16,667、S2 50,000、S3 83,334、S4 66,667 update,总计 216,668 update;所有阶段固定六卡,source-local coverage 与 RGB/K/Depth 配比按训练 recipe。S1 2,000-step 健康门之后使用 `--resume` 精确接续同一输出目录。控制器代码为 `code/run_formal_stages.py`,只在上一阶段完整非 smoke checkpoint 和 `audit_formal_stage.py` 均通过时启动下一阶段。训练日志、审计和评估均写在隔离 run 目录,原始过滤 GT 与官方预训练权重只读。最终完成与否必须以 S4 端点、完整审计和正式评估文件证明;控制器状态或训练 step 不能替代这些证据。 diff --git a/home/wuyifan/EgoNet_train_20261008/docs/CLEAN_GT_FROM_DINO_TRAIN_RECIPE.md b/home/wuyifan/EgoNet_train_20261008/docs/CLEAN_GT_FROM_DINO_TRAIN_RECIPE.md new file mode 100644 index 0000000000000000000000000000000000000000..50b18de44694320e486e43fa251d83f7d85954db --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/CLEAN_GT_FROM_DINO_TRAIN_RECIPE.md @@ -0,0 +1,145 @@ +# Foundation Hand 三源过滤 GT:DINO 预训练、其余从头训练 recipe + +状态:**Quest3 原始相机外参 + HOT3D 投影监督修正后,以 formal_v3 从官方 DINO 重启;旧 S1 与 formal_v2 均不得作为 parent**。日期:2026-09-25。预检 smoke 权重与正式 checkpoint 严格分开;实时进度见 `FOUNDATION_HAND_CLEAN_GT_FORMAL_RUN_20260925.md`。 + +## 2026-09-25 Quest3 外参修正(取代 mask-only 解释) + +后续视觉抽检发现,mask-only 版把 RGB 中清楚可见的 Quest3 手错误判为出画,因此 formal_v2 已停止、不能继续训练或用于模型比较。根因是官方 HOT3D `QuestDataProvider.get_camera_calibration(camera_model=LINEAR)` 在构造去畸变用 LINEAR calibration 后,从新对象读取 `T_device_camera`;该 transform 为 identity,丢失了 Quest3 原生相机相对于设备的旋转和平移。Aria 在线 calibration 路径先保存原始外参,不受同一错误影响。我们的 adapter 现在对 Quest3 从原始 `FISHEYE624` calibration 取 `T_device_camera`,从 LINEAR calibration 取去畸变图像对应的内参;第三方 toolkit 原文件保持不变。修正文件 SHA256 `73ff32f3994178e0d995dc7a3ff378ac70685fce1fe6f65eb20cc88c67dce9af`。 + +同一 Quest3 帧仅替换外参时,RGB 与 K 逐元素不变;两个原尖峰 tile 从 0 只有效手、0 个有效 2D 关节恢复为 2 只手、42 个关节,官方 calibration 投影与 K 投影差约 `3e-5 px`,并已目视确认关键点回到 RGB 中的双手。原四个单样本尖峰 loss `1873.65/2593.77/6635.64/6655.73`,以旧权重和最终修正 adapter 重放为 `4.73/8.44/7.45/6.80`;Quest3 目标深度回到约 `0.30–0.52 m`。同一组均匀抽取的 100 个 HOT3D T1 tile,mask-only 版保留 70 只有效手、977 个有效 2D 关节;最终版恢复为 183 只手、3481 个画面内有效 2D 关节。另对问题录制的 T=8 clip 验证左右手 8/8 帧几何有效、336 个 2D 关节均在画面内。全部是数据链路诊断,不是模型最终指标。 + +formal_v2 的 2K checkpoint 及账本保存在 G2 `archive/formal_v2_s1_wrong_quest3_extrinsics/`,旧版则在 `archive/checkpoints_before_hot3d_mask_fix_20260925/`;均未删除。两者使用错误的 Quest3 目标,不能为 formal_v3 提供初始化。正式配方的采样、loss、LR、阶段步数不变;从官方 DINO 重新启动 S1,后续 checkpoint 与控制器日志仅使用 `formal_v3` 命名空间。 + +## 2026-09-25 HOT3D 监督有效性首轮修正(mask-only 结论已废弃) + +旧 S1 的 loss 尖峰来自 HOT3D 原 adapter 将 `annotation present + z>0 + finite` 视为 2D/3D 有效,却未检查该只手的 GT mesh 是否进入当前相机画面,以及关节投影是否在画面内。四个尖峰样本中有 GT 关节深度约 `3e-6`–`2e-5 m`,投影达数百万像素,仍进入 direct 2D 与 reprojection loss。固定 4,167-step 权重重放同一批样本,旧单样本 loss `1873.65/2593.77/6635.64/6655.73`;只修 mask 后为 `4.73/0/0/0`。这不是 warmup、checkpoint 保存、DDP 或瞬时 I/O 抖动。 + +对冻结 T1 训练清单均匀抽取 100 个 HOT3D tile:原 mask 有 194 只标注手、2540 个有效 2D 关节;其中只有 70 只手的 GT mesh 与画面相交,1407 个原有效 2D 关节落在画面外。修正后是 70 只几何有效手、977 个 2D 有效关节,画面外有效 2D 关节为 0。抽样只是问题规模诊断,不能当作全量分母或 HOT3D 模型指标。 + +最终监督 mask 合同:逐帧逐手以正确相机外参下的 GT mesh 投影是否与 viewport 相交决定完整 MANO/3D/translation/shape/vertices 监督;部分入画只要有 mesh 进入画面,仍监督完整手。direct 2D 与 MANO reprojection 仅使用画面内、正深度且官方 `LINEAR` calibration 与 resize 后 K 投影误差不超过 2 px 的关节。完全出画的标注手本轮几何 loss 不监督;它不能自动成为 absence 负例。过滤 manifest、原生 GT、采样覆盖分母和输入模态比例不改,监督有效元素按新 mask 重新记账。此 mask 必须建立在上节正确 Quest3 外参之上;仅做 mask 的 formal_v2 已被证伪。 + +## 1. 目标与实验边界 + +从官方预训练 DINOv3 ViT-B/16 backbone 开始,重新初始化 Foundation Hand 的所有其他可训练参数,使用本次过滤后的 ARCTIC、H2O、HOT3D 真 GT 训练一个共享模型。模型支持同一套权重在以下输入条件推理:RGB、RGB+K、RGB+真实 metric Depth+K;输出 camera-space MANO、21 joints、wrist translation 和投影 2D。主模型仍用 direct-XYZ translation、T=8 双向时序和 factorized hand-query decoder。 + +这个实验**不加载** E40、S9L10、A2、A3 或 A6 的任何 Foundation Hand 学习参数、optimizer 或 EMA。DINO 的 `rgb_encoder.backbone.*` 必须逐 tensor 与指定的官方预训练权重一致;`rgb_encoder.projection.*`、ray/depth encoder、queries、decoder、heads 均为本实验新初始化。MANO 层使用固定模板,不当作可训练权重。初始 seed 固定为 `20260925`,另记录数据队列和增强的独立 seed。完整 checkpoint 始终保存 backbone;严禁以漏载 DINO 的 slim checkpoint 做训练初始化或评估。 + +本轮先建立 RGB/K/depth 基模。外参、SAM3 mask 不输入这轮几何训练;保留相应源引用,后续以冻结本轮 checkpoint 的消融实验加入。这样可以直接判定过滤 GT 和输入模态训练对常规四指标的作用。 + +## 2. 数据合同与缓存构造 + +唯一正式训练准入清单:G2 `/SSD3/yangzijing/ego_full_training_filter_20260925/unified/filtered_manifest.jsonl`,当前 SHA256 `b4b0ac4bc4a771c9bc7626a9eec7f5f541ef96908a9a64d219192efd7b8f7f89`。清单含 22,829 个非重叠、最长约 2 秒、至少 8 原生帧的窗口;RGB/深度从源数据读取,`filtered/` 的 `native_gt.npz` 只提供原生 GT。禁止从旧 Phase 9 cache 回填被过滤排除的窗口。 + +| 源 | 过滤后窗口 | 原始保留帧条目 | 原始 T=8 tiles* | 同步后可训练 T=8 tiles | 正式训练范围 | +|---|---:|---:|---:|---:|---| +| ARCTIC | 2,939 | 170,301 | 22,750 | 22,750 | P2 train ego0 | +| H2O | 928 | 47,594 | 6,406 | 6,406 | pose_train cam4 | +| HOT3D | 18,962 | 1,079,415 | 143,930 | 143,657 | 项目 train 的 230 个录制、选定头戴视角 | +| 合计 | 22,829 | 1,297,310 | 173,086 | **172,813** | 不含 validation/test | + +\* 每窗口按 `ceil(frame_count/8)` 计数;末尾不足 8 帧时,将最后一个 T=8 clip 起点移到窗口末 8 帧,允许最多 7 帧尾部重叠,不复制或跨录制取帧。该计数是相机视角的帧条目,不等于去重后的物理时间。T=1 阶段不计入 T=8 tile 覆盖。 + +已实现独立的 SQLite 索引和原生 source adapter:严格以 filtered manifest 的窗口 ID/原生帧号为 allowlist,构造 T=8 tiles;每个 tile 有固定 ID、物理录制 ID、源窗口 ID 和帧号,索引、导出 manifest 与代码均记录 SHA256。RGB/depth 从原始源按需解码,**目前不建持久帧缓存**;先依据稳态吞吐决定是否需要上限 64 GB 的压缩缓存。不要预先将 129 万帧全部展开为未压缩的 `512x896` 图像。当前每轮重排 tile 并重抽视觉/深度增强,但未实现窗口内 temporal 起点抖动,不能把重访 tile 说成新的时序 GT。不得把用于 Qwen 去重的 8 张 JPEG 当原始训练视频。原始数据、官方 DINO 和过滤 GT 在 `/SSD3` 只读使用;新 run 的生成物全部放在独立的 `/home/wuyifan/foundation_hand_clean_gt_dino_20260925/`,不回写或覆盖源目录。 + +S0 全量审计发现 HOT3D 的 1,905 个窗口包含 3,810 帧离最近 headset pose 超过既有 20 ms 对齐门。原始过滤 GT/清单不改动;派生训练索引仅使用对齐有效的连续帧,并在受影响窗口内重新排 T=8。由此 143,930 个原始 HOT3D tiles 变为 143,657 个可训练 tiles;另有 2,706 个姿态有效帧因所处连续段不足 T=8 无法参与 T8 阶段,21 个窗口无可用 T8。三个源可用 T8 原生帧条目合计 **1,290,794**,不是原始 1,297,310。S1 的 T1 行来自可训练 T8 tile 首帧,不会绕回失同步帧。覆盖证明以 **172,813 tiles / 1,290,794 帧条目**为分母,同时报告被排除的 6,516 HOT3D 帧条目;不得宣称原始 22,829 窗口全部完整入训。 + +沿用现有 source adapter 的图像和相机标定约定,输出统一 `512x896` 或阶段指定的 `368x640` RGB/depth/K。ARCTIC 先 rectify,再把 world MANO、joints、wrist 转到 camera;HOT3D 用官方 provider/时间同步,PCA15 按源 MANO basis 转 local pose,并核验 wrist transform 与 MANO raw translation 的区别;H2O 保持原生 camera-space、米制 GT 和 cam4 真 depth。图像 resize/pad 或几何增强必须同步更新 K 与 2D 点;H2O depth 以米为单位,保留逐像素有效 mask。 + +监督继续使用逐项 `*_valid`:2D、absolute/root-relative 3D、wrist translation、pose、shape、vertices、reprojection 相互独立。ARCTIC 历史左手 MANO 不兼容时,仍保留可信的 direct 2D、pose、wrist translation 和 source root-relative joints;shape、absolute MANO 3D、vertices、MANO reprojection 维持关闭,除非按既有 `<1 mm` 兼容门逐帧通过。HOT3D 也按源 mesh 重建兼容门决定几何监督。缺失的另一只手标注是 **unknown**,不是 absence 负标签。相邻帧时间差异常、HOT3D 20 ms 对齐失败、非法 K 或投影误差超门的样本必须明确排除并计数;不静默填零为有效 GT。 + +开训前交付:每源窗口/tile/帧/录制覆盖表、左右手各 loss 有效元素数、坐标单位与外参方向核验、源/目标 MANO 顶点误差分布、K 更新后的 2D 重投影分布、100 帧固定 RGB/源 GT 投影对齐抽检、cache manifest/payload SHA256。该抽检只展示可信且与 viewport 相交的源 GT,明确标为标注诊断,不展示未校准的模型预测。任何 retained 窗口无法构建都需登记具体原因,不能仍宣称 22,829 窗口全部入训。 + +## 3. 固定采样与模态分布 + +S1–S3 的训练 clip 源曝光为 H2O 40%、ARCTIC 35%、HOT3D 25%;S4 解冻 DINO 后改为 H2O 35%、ARCTIC 25%、HOT3D 40%。这是按**采样曝光**而非原始窗口数;HOT3D 占保留窗口约 83%,直接等概率抽文件会压过另两源。每阶段用确定性 quota 控制实际曝光,而不是仅凭随机采样的期望比例。源内以物理录制交错取 coverage tile;某录制本轮队列耗尽后跳过,整个源的所有 tile 均出现一次前绝不重复任何 tile。全源队列耗尽后才进入下一轮随机次序。**S2→S3 保留同一个队列 cursor;S4 为每源重新开启一轮有独立 ledger 的无放回队列**,使所有可训练 tile 在 DINO 解冻后至少参与一次优化。重访同一 tile 时仅重抽增强,当前不改变原生帧起点。同步视角属于同一物理录制,不能被当作独立录制加权。每阶段记录实际 source、subject/recording、hand side、tile、原生帧、相机设备的曝光。 + +| 源 | S1–S3 / S4 源权重 | clip 级 K input drop | clip 级 depth input drop | RGB / RGB+K / RGB+Depth+K(源内) | +|---|---:|---:|---:|---| +| H2O | 0.40 / 0.35 | 0.20 | 0.125,独立于 K drop | 0.20 / 0.10 / 0.70 | +| ARCTIC | 0.35 / 0.25 | 0.50 | 无真 depth | 0.50 / 0.50 / 0 | +| HOT3D | 0.25 / 0.40 | 0.30 | 无真 depth | 0.30 / 0.70 / 0 | +| S1–S3 总期望 | 1.00 | — | — | **0.33 / 0.39 / 0.28** | +| S4 总期望 | 1.00 | — | — | **0.315 / 0.440 / 0.245** | + +`depth_mode=geometry` 要求 K 对模型可用;H2O 的 K drop clip 因此实际走纯 RGB,即使底层 depth tensor 仍存在。drop 只改变 `K_input_available`/`depth_input_available` 和其 legacy alias;**真实 K、`K_supervision_valid`、2D/3D/MANO GT 与 loss mask 保留**。model 内逐帧的 `modality_dropout_prob` 固定为 0。H2O depth 可用时沿用 0.30 的既有 corruption 概率,保留 corruption 类型和有效像素统计;ARCTIC/HOT3D 不输入伪深度。 + +上述比例是期望值;运行日志必须按实际 `K_input_available AND frame_valid`、`depth_input_available AND K_input_available` 统计有效模式,不能仅报告配置概率。三个源和各模式分别报告抽样数、去重 tile 数、左右手有效监督元素、loss 与固定探针 batch 的分支梯度范数。HOT3D 另按 Aria/Quest3(当前保留窗口 6,291/12,671)报告覆盖、输入模式和四指标;Quest3 灰度输入不能与 Aria 彩色结果混成一个健康信号。H2O 的高重复曝光必须每轮重采视觉增强/有效 depth corruption,但不能把不同增强视作新的 GT;若固定探针显示某源监督梯度长期为零,不能仅靠提高该源抽样比例宣称充分利用。 + +## 4. 模型、优化与阶段预算 + +结构固定为 DINOv3-B patch tokens + 512-d projection、三层交替 spatial/temporal query decoder、ray encoder、geometry depth encoder、双手 interaction、direct-XYZ MANO/2D/translation/shape heads。`T=1` 和 `T=8` 使用同一组完整模型参数;S1 必须在前向中**旁路** `decoder.temporal.*` 并冻结它,避免随机、未训练的 temporal attention 改动单帧结果。S2 起启用并解冻该分支;阶段转移逐 tensor 核对其他权重不变。固定 depth gate 0.5、双向 attention、无 temporal position bias;不引入 dataset-specific head、router 或外参 adapter。对这次从头训练,S1 的 2D/rotation/translation/shape 头 weight 以及 depth encoder 最后一层 weight 用固定种子 `normal(std=1e-3)` 初始化;保留原先的中性 bias。原框架的全零 head weight 会使刚开始的共享特征梯度为零,而仅将 head 增大到 `1e-2` 会放大零深度输出后 LayerNorm 的梯度,故不采用。 + +逻辑 global batch 为 **6 clips**,每卡 microbatch 1;6 卡时累积 1 次,2 卡时累积 3 次。仅支持整除 6 的 GPU 数,并在正式 run 开始前锁定 world size;不同卡数接续需验证 sampler、optimizer、scheduler 与累计梯度等价,否则从阶段边界恢复而不宣称 bitwise resume。保持每次 optimizer update 的 6 clips 和学习率不随卡数改变。BF16 autocast,AdamW weight decay 0.05,global grad clip 100(短程 clip 10/100 对照后的正式冻结值,见第 6 节)。各阶段采用新的 optimizer 与该阶段独立 cosine/warmup;模型权重从上阶段端点严格接续,绝不重置已训练分支。每阶段 warmup 1,000 updates;S1–S3 非 DINO 峰值 LR `5e-5`、最低 `5e-6`,S4 非 DINO 峰值 `1e-5`、最低 `1e-6`,S4 最后两层 DINO + final norm 峰值 `5e-7`,按固定 0.05 LR 比例随 cosine 衰减。这些是启动候选,需用短程健康试验核对有效 batch 改动后的优化稳定性;不因卡数线性放大 LR。以下预算均为**真实输入样本数**,不是旧实验的 405K optimizer steps。 + +| 阶段 | 输入/分辨率 | 可训练参数 | 样本曝光 | 约更新数(batch 6) | 固定目标 | +|---|---|---|---:|---:|---| +| S0 预检 | cache / CPU | 无 | — | — | 全量清单、GT/K/mask、resume 与输入模式审计通过 | +| S1 单帧初始化 | T=1,368x640,三模式混合 | projection、ray/depth encoder、spatial decoder、queries、MANO/2D/translation/shape heads;DINO backbone 与 temporal 冻结 | 100,000 帧 | 16,667 | 从随机手部参数学会单帧 camera-space MANO;三模式都有非零梯度 | +| S2 时序联合 | T=8,368x640,同样混合 | 全部非 DINO 几何参数,含 temporal;DINO backbone 冻结 | 300,000 clips | 50,000 | 建立时序与双手联合能力;所有源进入覆盖队列 | +| S3 高分辨率联合 | T=8,512x896,同样混合 | 全部非 DINO 几何参数;DINO backbone 冻结 | 500,000 clips | 83,334 | 累计 T8 800K,完成所有 172,813 个可训练 coverage tile 首次曝光 | +| S4 视觉微调 | T=8,512x896,35/25/40 源配比 | S3 参数 + DINO 最后两层和 final norm | 400,000 clips | 66,667 | 三源各完成一轮新的、DINO 解冻后的全 tile 覆盖,再依据验证曲线决定是否延长 | + +正式 T8 最低曝光 1,200,000 clips、约 200,000 updates;加 S1 后四个注册端点合计 **216,668 updates / 1,300,008 逻辑 clips**。**这比旧 Stage 9 的 405K optimizer updates 少,不能因为输入样本总数更多就声称等价或已收敛。**S2+S3 的 HOT3D quota 约 200,000 clips,完成一轮全部 143,657 可训练 tiles;S4 的 HOT3D quota 约 160,000 clips,单独完成一轮新的 DINO 解冻后覆盖。H2O/ARCTIC 全 T8 分别约 460,000/380,000 clips,约为其 tile 数的 72/17 倍;S4 单独约 140,000/100,000 clips,也足够各完成一轮。源内逐轮无放回队列和固定原生帧首轮使每源 **100% 可训练 tile ID 与 100% 可训练原生帧条目在要求的覆盖阶段被读取**;有效监督元素另按 loss/手侧计数,不能把读取等同于每帧每项 GT 均有效。这是运行时必须证明的门槛,而不是仅凭预算计算推断。每个 tile 不要求在每个输入模式都出现;逐源/逐模式的有效曝光和质量须另行报告。若准入窗口转换失败,须修复后重跑覆盖;不得悄悄减少分母。完整帧覆盖不证明其标签都正确,也不要求每个可能的重叠 T8 起点都出现。 + +## 5. 覆盖与收敛的双门槛 + +**覆盖门槛**:S3 结束前完成所有源一轮 tile;S4 另对所有三源完成一轮 fresh sweep,并保存阶段局部 coverage ledger 与分源原生帧证明。审计每个输入模式的实际占比、Aria/Quest3 和各 loss 的有效 GT 元素,尤其确认 RGB、RGB+K、RGB+Depth+K 都有持续梯度。覆盖只表示数据确实被使用,不等于训练收敛或模型更好。 + +**收敛门槛**:开训前按录制固定划分 H2O official val、ARCTIC P2 val 和 HOT3D 外部 heldout 为 development/confirmation 两个不交叉 panel;分组比例与逐源录制/hand side/device 分布在 S0 审计后冻结,避免先看模型分数再挑录制。S3 端点及 S4 每 100,000 clips 的固定快照只看 development panel 的逐源/逐输入模式四指标、train loss/grad;confirmation panel 仅在最终 checkpoint 冻结后运行一次。H2O train-side 固定诊断仍保留,但不是独立验证。开训前根据 evaluator 重复性与录制配对 bootstrap 区间锁定“最小有意义改善”阈值;连续两个间隔的改善上界均低于该阈值、区间宽度足以判别、没有来源/模态/手侧显著退化、grad norm 与裁剪稳定,且覆盖门槛已过,才称作“有收敛证据”。**仅仅不显著不等于收敛;区间过宽或小 LR 导致的停滞必须标记证据不足。**不要将总 loss 的下降或单项指标最佳点代替此判断。 + +若 1.2M T8 后仍有明确改善趋势,先报告“未收敛”,按预先注册的 100K-clip S4 延长块继续,最多另加 400K T8;保持 S4 的 35/25/40 配比、参数组和 LR floor,不因中途分数改变 loss/采样规则。延长后仍改善或出现过拟合时,保留全部快照并作为下一轮独立 recipe 决策,不在当前 run 暗调 LR。最终 checkpoint 的选择规则在开训前锁定:使用覆盖门通过、development panel 未显示过拟合的最后一个预注册端点;confirmation panel 不能用于二次选点。若 S4 达到 LR floor 后才出现平台,须结合参数更新量说明其可能是 LR 限制,不宣称数据已榨干。 + +**不能数学保证收敛**:有限预算只能保证读取覆盖。真实三源混合、所有输入模式的六卡 BF16 吞吐、数据加载、batch-6 数值和相同六卡断点恢复已测;正式 run 固定六卡。若以后需要改为 2 卡,先另做 2→6 卡累计与断点等价实验,不能沿用六卡结果。若 6 卡未实际空闲且获准使用,不能按 6 卡排期。 + +S1 的初始快照做输出尺度、有限性、2D 投影和非 DINO 梯度检查。S2/S3/S4 的两步独立 smoke 已验证阶段接口;各阶段正式前 2,000 updates 作为**阶段内健康门**,保存完整 checkpoint 后暂停检查再继续,不重复另训一份 2,000-step 预检权重。固定保存阶段 25%、50%、100% 端点以及每 10,000 updates 的可恢复完整 checkpoint。中间评估不改变已注册预算、采样或 LR。若出现 NaN/Inf、全零应有梯度、GT/K 合同错误、来源越界、resume 不等价或覆盖计数错误,停止该实验并保留失败回执;不自动换 checkpoint 或静默跳样本。 + +### 当前机器与粗略工时(2026-09-25,正式计时前重测) + +G2 有 6 张 RTX 4090 24 GB;最终预检时 6 卡无计算进程,正式开训前仍需再次确认资源归属。2026-09-25 复查的根分区余约 **962 GB**、`/SSD3` 余 **197 GB**;这是共享文件系统余量,不是已核实的用户配额。现有过滤 GT 约 1.6 GB,完整过滤产物约 51 GB(其中约 46 GB 为不能充当原始训练帧的抽样 JPEG)。若预展开全部 129 万帧为 `512x896` RGB uint8,约需 **1.62 TiB**,故禁止全量解压缓存或复制原视频包。六卡 S4 从短烟测 parent 连续运行 **834 updates / 5,004 clips**,无非有限 loss/grad 或解码失败,实测 **15.50 clips/s**、每卡最高约 **6.04 GiB**;这验证了混合流、文件句柄和解码链路,不是收敛证明。运行中 `vmstat` 的 swap-in/out 均为 0,主训练进程文件句柄数约 123→121,未见持续泄漏。 + +存储合同:本轮独占目录 `/home/wuyifan/foundation_hand_clean_gt_dino_20260925/` 已建立,下设 `code/`、`checkpoints/`、`cache/`、`logs/`、`eval/`,均在同一根分区,不能经软链落到将满的 `/SSD2`/`/SSD3`。当前索引/manifest 缓存约 **670 MB**,不缓存解码帧;预检 checkpoint 实占 **14.49 GiB**,其中预算规则计入 **3.62 GiB**。正式完整 checkpoint 及阶段端点限 **40 GB**,日志/评估预留 **10 GB**;预注册共有 34 个保存点,烟测完整 checkpoint 实测约 0.72–0.88 GiB,按较大样本估算连同已计入预检文件约 33.5 GiB,仍须在正式首个完整保存后复核。当前预算代码仅凭路径中是否包含 `smoke` 判别预检文件;未带此标记的预检 checkpoint 也会计入 40 GB。保留全部预注册 checkpoint 与端点,不清理旧权重或其他用户数据。 + +仅 rank 0 写 checkpoint:包含**完整 DINO backbone**、所有可训练模块、optimizer/scheduler、sampler/coverage cursor、每 rank RNG、阶段/输入模式/manifest/code hash;先写同目录临时文件,再原子 rename,完成后抽样做 SHA256、重新加载、断点继续等价检查,未完成的 `.tmp` 不当作有效 checkpoint。启动时须核对固定派生索引及 T1/T8 manifest 的 SHA;正式阶段只接受上一阶段完整端点、相同代码指纹和适用时相同 T8 manifest,`--smoke` 预检 checkpoint 不得接入正式阶段或正式评估。开训前根分区至少保留 300 GB;每次保存前检查剩余空间和正式 checkpoint 预算,若下探至 200 GB 或预计无法容纳完整临时 checkpoint 与最终文件,应安全停在已有有效端点并告警,不自动清理任何其他目录。源数据目录只读,无持久解码帧缓存时不虚构 cache hit-rate。G2 当前 503 GiB 内存中约 489 GiB available,但 2 GiB swap 已占约 1.9 GiB;预检需确认无持续 swap-in/out。`nofile` soft limit 为 1,024、hard limit 为 1,048,576;六卡多 worker 读取前在启动进程内将 soft limit 提至至少 8,192,并做数据加载打开文件数/句柄泄漏 smoke。 + +| 条件 | 已测短程吞吐 | 约 130 万样本若均按该速度的纯训练量级* | 当前排期口径 | +|---|---:|---:|---| +| 6 卡均空闲且获准使用 | S1 35.15、S2 17.70、S3 14.00、S4 15.50 clips/s | 四阶段约 22.6 小时 | 纯训练量级;含保存、健康门与评估按约 25–30 小时排班,不作完成承诺 | +| 仅 2 卡空闲且获准使用 | 未测 | 不给伪精度数字 | 先测跨卡累计与吞吐再排期 | + +\* S1、S2、S3 吞吐来自 1,000/100/100 update 短程,S4 来自 834 update 连续压测;模型成熟后、其他用户负载变化时可能不同。原先的 12–18 小时六卡排期已由本次测速推翻。若预算结束后仍改善,延长块需要另行注册代码/预算,目前训练入口只注册至 S4 66,667 updates,不能宣称自动延长已实现。 + +## 6. Loss 与可见性 + +几何主线沿用 Stage 9 `BimanualLoss`,起始权重冻结如下;T=1 时 temporal 项自然没有有效相邻帧。任何调权属于另一个明确注册的实验,不能在本轮看到验证结果后偷偷改。 + +| loss | 权重 | loss | 权重 | +|---|---:|---|---:| +| direct 2D joints | 1.0 | absolute camera 3D joints | 10.0 | +| root-relative 3D joints | 10.0 | camera-space MANO vertices | 1.0 | +| local pose | 1.0 | global orientation | 1.0 | +| MANO shape | 0.1 | wrist translation | 10.0 | +| MANO reprojection | 1.0 | temporal velocity / acceleration | 0.1 / 0.05 | +| bimanual relative wrist | 1.0 | presence | **0.0** | + +每个 loss 使用本源字段级 validity mask。训练入口累计所有 update 的来源 × 输入模式 × 左右手 × mask 有效元素数,随 checkpoint 精确恢复;每 100 update 抽样记录来源/模式的各加权 loss、wrist x/y/z MAE、预裁剪总/分组 grad norm 和裁剪频率。日志的参数组非零梯度是更新健康证据,不能等同于每个参数都产生非零位移。旧 A3 出现过长期高频裁剪;同队列预检后,本轮固定全局梯度裁剪阈值 **100**,写入 checkpoint 并在 resume 校验,不在正式 run 中途更改。S1 1,000-update 对照的末 100 步 loss 为 clip 10: 2.453、clip 100: 2.358;S4 834-update 对照末 100 步为 10.923、10.917,均有限且吞吐相同。这只支持初始优化配置,不证明最终四指标全面提升。相机轨迹不进入损失。 + +几何阶段不从 `native_gt.valid=False` 推导 presence 负例,也不使用尚未匹配新特征的 A2/P4 visibility head。S4 几何端点冻结后,另训一个**RGB-only、特征来源匹配本模型**的 presence head:可信完整投影与 viewport 相交为正;可信完整投影远离 viewport 为负;无完整标注、边缘过小和身份不确定为 unknown。以录制互斥数据校准阈值,分别报告自然/裁切、部分出画/腕部出画召回和缺手误报;不改变几何四指标的 GT 分母。只有新 head + 对应特征提供者 + 校准阈值都通过,正常 MANO 视频/截图才启用 visibility 过滤;记录 `presence_filter: true` 及版本。这个附加 head 不算作本轮四指标基模的改进证据。 + +## 7. 评估、比较与交付 + +三个源均以固定原生 GT panel 做 camera-space 四指标:Absolute MPJPE、Root-relative MPJPE、Absolute MPVPE(mm)、MANO projected 2D error(px)。H2O 官方 val 运行 RGB、RGB+K、RGB+Depth+K;ARCTIC P2 val 和 HOT3D 录制隔离 heldout 运行 RGB、RGB+K。三源验证数据按录制预先分成 development 与只用一次的 confirmation;模型选择只看前者。最终可另报告完整官方 val 以便和历史结果比较,但它包含选模用的 development 部分,必须标记 **selection-informed**,不能称作全量 untouched 证据。ARCTIC 历史兼容 mask 下 3D/mesh 主要是右手,2D 含双手,表格必须附分母和左右手明细。HOT3D 固定 2,048-clip heldout 的 62 个录制已核对与本批 230 个 train 录制零重叠;另按 Aria/Quest 与运动强度报告。 + +训练过程使用固定 train-side 健康集及三源 development panel 做中途诊断;confirmation panel 只在几何 checkpoint 冻结后运行,H2O official test 和各源 test 均不接触。对 A2、A3、S9L10、A6 对应输入分支重跑同一 evaluator 与 mask;availability override 同时更新 canonical 和 legacy 字段,断言实际输入模式,避免 A3 旧中途 H2O eval 的错标问题。所有四指标按录制配对汇总并给出 bootstrap 区间,不按预测 presence 筛掉难帧。 + +最终模型的推广判定单列:H2O 完整 Depth+K 对 A2、纯 RGB 对 A3、RGB+K 对现有最佳同模式分支,以及 HOT3D/ARCTIC heldout 同输入结果。一个输入改善不能抵消另一输入的大幅退化;未达成全面替代时仍保留完整训练结果和 checkpoint,标记为候选而非替换现有权重。S9L10/A2 旧数据是否损害模型,只能通过相同评估下的新模型结果分析,不能仅凭“重新初始化”直接认定。 + +交付应含:固定 recipe/config 与 Git/code hash、训练清单/hash、cache 转换与监督审计、DINO 初始化逐 tensor 回执、每阶段完整 checkpoint 与 optimizer/sampler/RNG 状态、逐源/逐模式曝光及 loss/grad 日志、100% coverage 证明、固定面板四指标与逐录制结果、失败案例及按上述 visibility 合同生成的过滤可视化。训练开始前只做只读 GPU/磁盘/路径检查,使用空闲卡,不影响其他任务。 + +## 8. 已实现的开训准备 + +1. 新建独立 clean-start 配置/入口;原 Phase 9 训练入口强制 `--init-checkpoint`,不能通过假 checkpoint 绕过。验证只加载官方 DINO backbone,其余随机初始化,特别核对 `rgb_encoder.projection` 也属于新参数。 +2. 新建 filtered-window→完整 T1/T8 索引、按需解码 adapter 与源内无放回、精确 resume 的 coverage sampler;现有 mixture sampler 有放回,不能满足 S3 及 S4 阶段内 100% tile 覆盖要求。S4 在独立阶段 ledger 中对每个源分别维护无放回第一轮;某源第一轮未覆盖完时不重访**该源**的 tile,其他已完成第一轮的源可以继续重访。落实独立 run 目录、完整 checkpoint 同目录原子写入和磁盘保护阈值;若稳态吞吐显示需要持久帧缓存,再设计不超过 64 GB 的压缩缓存,不把它当作当前实现。 +3. 四阶段在同一结构上通过 temporal 前向旁路、参数组冻结/解冻和 T/分辨率变化衔接;转换阶段核对已训练 tensor 完全一致,optimizer 按合同新建。入口支持逻辑 global batch 6 下 2/6 卡和累积,但只验证六卡相同 world size 的精确恢复;跨 world size 恢复必须单独验证。 +4. 已完成真实三模式和每源手侧监督计数、K drop 与 K supervision 独立性、source GT→camera MANO/K 投影、完整 checkpoint DINO 组合、T1/T8 与跨阶段 resume smoke;固定三源验证录制分组与 H2O selection-informed 报告合同。峰值内存、打开文件数/swap、checkpoint 原子写入与 load-back,以及约 5K-clip 三源混合吞吐均已验证。正式 run 固定 6 卡;2/6 卡累计等价仅在实际需要换卡数前再验证,不能假定已通过。 + +当前代码、派生索引、六卡四阶段短 smoke、S1 1,000-update 冷启动与裁剪对照、固定 100 帧源 GT/K 叠图、三源完整 development 面板的评估链路、5,004-clip S4 压测、相同 world-size 精确 resume 均已建立。最终代码的连续 3 步与 2+1 步恢复对照:375 个模型 tensor、94 个 optimizer state、采样位置及完整监督曝光账本逐项相等。**正式 216,668-update 训练已从官方 DINO 起步;S1 的 2,000-step 健康门通过并已精确接续。**正式端点的审计与后续阶段状态记录在独立正式训练日志中;短烟测 checkpoint 不得用作正式阶段 parent,训练入口已对此设置拒绝门。 diff --git a/home/wuyifan/EgoNet_train_20261008/docs/DINOV3_2D_VISIBLE_INFERRED_PRETRAIN_20261004.md b/home/wuyifan/EgoNet_train_20261008/docs/DINOV3_2D_VISIBLE_INFERRED_PRETRAIN_20261004.md new file mode 100644 index 0000000000000000000000000000000000000000..48e7847321efa75e1fb3ab0bc991ca6102f7ed98 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/DINOV3_2D_VISIBLE_INFERRED_PRETRAIN_20261004.md @@ -0,0 +1,75 @@ +# DINOv3 全帧 2D 预训练:看见与推断分流 + +日期:2026-10-04,2026-10-05 更新。此配方独立于现有 B0/B1 从头 MANO 合同;G1 两卡已完成真实全帧池 P0a 两步端到端 smoke,**尚无正式 2D 精度或 MANO 收益结论,也没有启动 MANO 训练**。 + +2026-10-05 P0 启动门复核:用户已用独立 MMPose 2D 预测与 3D 投影坐标对照;这支持 P0 的坐标标签质量,但不产生逐关节遮挡状态。**P0 不以人工可见性审核为启动前提;P1 才需要可信的 visible/occluded/out-of-frame 标签。** + +目标 `ego_full_training_filter_visible_20260925` manifest SHA256 为 `80490f362e670183eeb958c624531f28610c98096a354b9ee7408c7ecb00c521`,包含 22,827 个窗口、1,276,713 帧。新增 `visible_index.py` 将旧 T=1 reader 行映射到该版本,HOT3D 排除 2,745 个旧 T=1 行;产出 H2O train/dev `4939/1467`、ARCTIC `17788/4962`、HOT3D `113425/27487` 行,按 source+recording 哈希隔离。索引与原位哈希报告在 G2 `/home/wuyifan/egonet_p0_visible_20261005/index_v2/`。这只是 170,068 个旧 T=1 稀疏采样行,不等于全量逐帧训练或相同数量的不同物理帧。 + +G2 目标 reader 的 CPU/DataLoader 预检:每源 train/dev 各 12 帧,RGB/帧号/GT 对齐,最大内部 K 重投影差 `<0.0002 px`;H2O/HOT3D 无空监督抽样,ARCTIC train `2/12`、dev `1/12` 为 0 个 P0 画内有效点。检查报告与叠图在 G2 `/home/wuyifan/egonet_p0_visible_20261005/reader_preflight_v3/`。G1 空闲 GPU 0/5 上的 2-rank、2-update DDP smoke 使用该 reader 导出的真实 RGB/2D,loss 与 preclip grad 均有限;报告在 `/tmp/egonet-p0-MrWWH6/ddp_smoke.json`。这些数值只验证管线,不代表 2D 精度、收敛或 MANO 收益。 + +G1 全帧候选合同冻结在 `wuyifan/artifacts/egonet_p0_full_20261005/phase_index_v5/`,分成 8 个互斥 T=1 相位,同一 recording 不跨 train/dev。相对原 visible manifest 1,276,713 帧,HOT3D 有 19 个没有 trainable native reader 模板的 Quest3 窗口共 656 帧,ARCTIC 又有 95 帧的 RGB 文件虽存在,但 frame index 恰超出官方 camera 数组;v5 静态索引共 **1,275,962 帧**。其中 train **1,021,323 帧**(H2O 36,685 / ARCTIC 133,052 / HOT3D 851,586),dev **254,639 帧**(10,909 / 37,154 / 206,576);不能把 train+dev 总数当训练量。每个 GT NPZ 与 visible manifest 哈希核对,v5 又绑定 v4 的索引哈希并检查 ARCTIC 相机/MANO 数组边界及 RGB 文件存在性;`phase_index_v5/index_report.json` 保存逐帧排除项与相位哈希。G1 phase0/7 的真实 DataLoader 读图、2D/K 对齐及叠图抽查通过,ARCTIC 部分帧 2D 画内目标为空,训练器作同源最多 16 次重采样。G1 GPU 0/5 的两 rank、global batch 24 全模型 P0a 两步 smoke 已通过:loss `5.145 -> 5.093`,preclip grad `1.045 -> 0.878`,完整 checkpoint 383 MiB 且包含 211 个 DINO backbone tensor;这只说明管线健康,不是收敛证据。 + +术语:**GT 存在**只表示过滤后的 NPZ 有该帧且哈希匹配;**可索引**表示该帧进入相位清单并通过上述静态条件;**reader 可读**表示原生适配器实际取出 RGB 与监督、且所有同步及几何检查都通过。HOT3D 的实际 reader 对图像时间戳分别查询手部 pose 与 headset pose,二者都须找到相距不超过 20 ms 的条目;一帧不满足就不能组成训练样本。并无证据说全部 HOT3D GT 都不满足,也尚未对 v5 全池逐帧执行该动态检查。 + +长跑首先于约第 14 step 遇到 HOT3D 官方 reader 的明确 `20ms synchronization failure`(`P0002_af0d3d4a`、headset pose 缺失):全量帧池的“可索引”不等于每帧均可成功解码。训练器仅对这一特定错误在同源重采样,记录累计同步失败次数及 tile ID;其它异常仍直接终止。修复后的 G1 25-step 两卡回归完整通过并保存 383 MiB checkpoint,累计 14 次空 2D 目标与 2 次 HOT3D 同步失败重采样。之后 v4 长跑在第 50 step 的 loss 已降到 4.616,却又于下一批碰到 ARCTIC camera 数组越界,促成上述 v5 全量静态边界审计。最终实际可读帧数仍需结合 HOT3D 运行期坏帧账本,不能把索引数宣称为全部解码验证通过。 + +正式 P0a 5K 从 step 0 重新运行于 G1 tmux `egonet_p0a_g1_full_v3`,输出 `wuyifan/artifacts/egonet_p0_full_20261005/p0a_full_5k_v3/`,console 为同级 `p0a_full_5k_v3.console.log`;使用 GPU 0/5,每 25 step 记录 loss/grad/同步重采样,每 1000 step 保存完整 checkpoint。旧 v2 失败日志保留,不能用 v2/v4 checkpoint 续 v3/v5。退出后 tmux pane 保留退出码。[`eval_p0.py`](../experiments/dinov3_2d_pretrain/eval_p0.py) 已用 25-step checkpoint 在三源各 1 帧 dev 上完成 CPU 管线 smoke;其像素误差不作精度结论,1K 起需对固定三源 dev 抽样做正式评估。 + +这里的 **T=1 是单帧输入长度,不是只取 1/8 数据**。旧索引 170,068 行只是稀疏抽帧,约为完整帧数的 13.3%;新 8 相位索引合计覆盖完整 train/dev 候选帧池。P0a 仍只有 `5,000 x 24 = 120,000` 次曝光,按 21:15:24 配额约为 H2O 42,000 / ARCTIC 30,000 / HOT3D 48,000 次;尤其 HOT3D 训练池有 851,586 帧,P0a 不可能逐帧见完。全量帧池的价值是覆盖短暂遮挡、手部入画/出画和罕见姿态的候选分布;要声称每帧至少训练一次,必须另设覆盖账本与更长预算,不能靠轮转相位名称推断。 + +## 1. 标签合同与当前事实 + +现有 H2O、ARCTIC、HOT3D `joint2d` 主要来自已知 3D/MANO 与相机模型投影;`joint2d_valid` 表示投影、画内或几何监督有效,不表示视觉上可直接看见。H2O reader 甚至没有统一的画内检查。ARCTIC/HOT3D 的画内判断也不能识别物体遮挡或自遮挡。因此绝不能用 `joint2d_valid=True` 直接训练 visible 分类。 + +逐关节人工复核状态:`visible`(可直接定位)、`occluded_in_frame`(理论点在画内但视觉上被挡)、`out_of_frame`、`unknown`(证据不足);未审阅是第五个技术状态 `unreviewed`,不进入比例分母。另存可见关节的人工点击 2D 位置,用来检查投影标签偏差。几何投影只有 `in_frame/out_of_frame/unknown` 三种代理状态,**不是人工可见性标签**。 + +当前 [`audit.py`](../experiments/dinov3_2d_pretrain/audit.py) 按源从 train 索引做录制级确定性抽样,通过正式 U0 reader 导出完整 RGB 与投影点。复核页可本地打开、逐关节打状态、点人工 2D、导入和导出 JSON;`report` 汇总每源状态比例、`joint2d_valid` 当 visibility 使用时的 false-visible / missed-visible 比例和 visible 投影对人工点的误差。审计集按录制均衡,不代表逐帧总体流行率;要估总体分布,另需按录制长度/采样概率加权。 + +初始 gallery 在 `/data-hdd/jiasen_rescue_20260815/wuyifan/artifacts/dinov3_2d_visibility_audit_full_20261004/index.html`。每源 24 个 train 录制、每录制一帧,当前逐关节**人工审核覆盖率为 0%**;下表只说明几何投影与现有 2D valid 的分布,绝不是 visible/occluded 真值: + +| 源 | 抽样关节 | 几何画内 | 几何画外 | 几何未知 | 画内且 `joint2d_valid` | 人工 visible / occluded | +| --- | ---: | ---: | ---: | ---: | ---: | --- | +| H2O | 1008 | 1008 | 0 | 0 | 1008 | 未审核 | +| ARCTIC | 1008 | 751 | 152 | 105 | 751 | 未审核 | +| HOT3D | 1008 | 819 | 120 | 69 | 733 | 未审核 | + +初始 24 录制/源的复核集只是工具与分布摸底,不足以宣称数据标签可靠。正式审计目标:每源至少 200 个不同帧、覆盖至少 30 个录制;至少 20% 双人独立标注并裁决分歧;每源至少 100 个画内遮挡关节和 50 个画外关节的定向补样。若某源无法达到某类支持量,就标记该类 `unsupported`,不能报告该源的分类性能。双人可见/非可见 Cohen's kappa 初步要求 `>=0.75`;`unknown` 比例和分歧来源单列,不强行变成负样本。 + +## 2. 网络与监督 + +输入为原始视野下的 RGB `512x896` 单帧,不做 oracle 手部裁剪,不输入 K/depth/camera。官方 DINOv3 ViT-B/16 patch 特征与二维 patch 位置进入 42 个左右手/关节 query;两个 cross-attention block 后输出: + +| 输出 | shape | 监督来源 | +| --- | --- | --- | +| observed `x/y` 1D logits | `[B,2,21,224/128]` | **仅人工确认 visible** 的人工 2D,或人工确认投影偏差达标后的投影 2D | +| inferred `x/y` 1D logits | `[B,2,21,224/128]` | 画内可信几何 2D;包括 visible 与画内遮挡,审核为画外的点必须排除 | +| visibility 3-class logits | `[B,2,21,3]` | **仅人工确认** visible / occluded-in-frame / out-of-frame;unknown/unreviewed 忽略 | + +每个轴 4 px/bin,坐标分类 CE,两个轴取均值。候选 loss 系数 `inferred=1.0`、`observed=0.5`、`visibility=0.25`;先记录三个 head 和 DINO last-2 的单项梯度范数,若明显相互冲突再调整,不按标量大小直接断言。`loss.py` 已确保无人工 review 时只有 inferred 分支反传。不能用 SAM3 mask 点内/点外直接替代关节 visibility GT:它只分割可见像素,关节中心可能落在可见轮廓内但实际被手掌、物体挡住。SAM3 可在人工审计通过后作为低权重候选 pseudo-label,保持独立来源字段。 + +## 3. 分阶段训练建议 + +| 阶段 | 可立即做吗 | 权重与数据 | 建议预算和停止规则 | +| --- | --- | --- | --- | +| P0a 坐标头稳定 | G1 两卡全帧池端到端 smoke 已通过 | 冻结 DINO backbone;训练 projection、query decoder、inferred 头;三源 RGB 21:15:24,按录制隔离 development | 5K update、global batch 24;head LR `1e-4`、AdamW;每 1K 保存完整权重并离线检查三源 held-out 2D | +| P0b 2D 表征 | P0a 健康后 | 同一坐标任务;解冻 DINO 最后两层和 final norm,仍不训 observed/visibility | 先预注册 30K 最短和 80K 上限;DINO LR `1e-6`、head `5e-5`,1K warmup 后 cosine;每 2K held-out eval,连续三次无可靠提升可提前停 | +| P1 看见/推断 | 需要通过人工标签审计 | 在 P0b 权重上训练 observed 与 visibility;人工审核标签与原画内几何混合,按状态/源重采样,未知不参加分类 | 初步 20K-40K;DINO last-2 LR `5e-7`、head `5e-5`;真实审核样本与 pseudo-label 分开计数、分开报告;不得只靠小审核集重复过拟合 | + +[`train_p0.py`](../experiments/dinov3_2d_pretrain/train_p0.py) 已实现两卡 DataLoader/DDP、source-local 空监督重采样、完整模型与 optimizer checkpoint、索引哈希核验和按 step 恢复;数据顺序由 step/seed 确定。DataLoader 增强 RNG 尚未持久化,恢复并非逐 bit 复现,报告中不能声称完全确定性。`pilot.py` 只是早期两步管线,不可当作收敛证据。RGB 仍是唯一模型输入,K 仅在原始数据适配时用于构造投影 target。空间增强必须同步变换 RGB 和 2D 标签;不能在单帧头里偷用未来帧。 + +## 4. 进入 MANO 的初步门槛 + +所有验证按 **recording-disjoint** 分割,不复用同一录制的重叠 T8 tile。最重要的对照是相同 DINO 官方初始化、同等 batch/step 的 frozen-backbone 2D 头,另保留直接官方 DINO 的 MANO 基线。下列是启动下一阶段的预注册**初值**,不是已测成的结果;在人工审核和 P0 baseline 落盘后,才可根据测量方差调整一次并记录原因。 + +1. **数据门**:三源达到上面的复核覆盖与双标一致性;人工 visible 点相对现有投影的偏差每源中位数 `<=8 px`、P90 `<=20 px`(512x896)。不达标的源不能把投影坐标当 observed GT;需要修 K/同步/坐标或直接用人工点击点。 +2. **P0 -> MANO 探索消融门**:held-out 人工 visible 点的 inferred 头三源 macro 中位误差比 frozen-DINO 2D 对照低至少 `10%`,按录制 bootstrap 的 95% CI 上界仍小于 0;单源中位误差恶化不得超过 `2 px`。绝对警戒线为 visible 中位 `<=10 px`,并报告 PCK@10 / P90。若只过 P0,只能说 2D 位置表征有用,不能说学会区分看见/遮挡。 +3. **P1 -> 完整 MANO 转移门**:可见分类 macro F1 初步 `>=0.80`,visible 的 false-positive rate `<=5%`,occluded recall `>=0.70`;画内遮挡 inferred 点相对 P0 的 PCK@20 提升至少 `3` 个百分点,visible 中位误差 no-harm `<=2 px`,三个源分别报告。若类支持量不足,不能靠 macro 掩盖该源缺失。 +4. **真正效果门**:只转移 DINO backbone 与 projection 到新的 B0/B1-P 配对臂,丢弃 2D query/heads;两臂其它 MANO 参数都从头初始化,保持原 B0/B1 同一 train/val、loss、T8、步数和四指标。P0/P1 的 2D 门只授权做 MANO 实验;是否提升 Abs MPJPE、Root MPJPE、MPVPE、2D px 仍以 MANO 正式 eval 决定。 + +不要把审计 review 集用于训练后又当最终独立门;P1 应另留录制级不可训练的锁定 review/test 子集。绝对像素阈值会随输出分辨率变动,所有表都要同时写明原图 `512x896` 和模型/评估是否做了 resize。 + +## 参考 + +- Meta DINOv3 官方说明:。利用其 dense patch features,但上述任务头、阶段预算和门槛是本项目的设计,并非论文给出的配方。 +- SimCC 1D 坐标分类论文:。这里采用 x/y 轴分类形式,但保留全图输入与双手 query,不复用其裁剪 setting。 diff --git a/home/wuyifan/EgoNet_train_20261008/docs/FROM_SCRATCH_B0_B1_THREE_CHECK_AUDIT_20261004.md b/home/wuyifan/EgoNet_train_20261008/docs/FROM_SCRATCH_B0_B1_THREE_CHECK_AUDIT_20261004.md new file mode 100644 index 0000000000000000000000000000000000000000..fd9f0a4457a83da2a8db0850c3e5dbfd8d3c997b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/FROM_SCRATCH_B0_B1_THREE_CHECK_AUDIT_20261004.md @@ -0,0 +1,127 @@ +# B0/B1 从头训练:数据、表征、监督三项检查 + +> 2026-10-04 更正:当前合同使用官方 MANO pkl 的 `hands_mean`。下面先列当前 v2 验证;再往后的旧统计与 smoke 属于训练数据估计 mean 的历史合同,仅供追溯。 + +> 2026-10-06 监督变更:B0/B1 当前配置将直接 `joint2d` 权重设为 0,仅保留 MANO 关节重投影的 2D loss,且正式训练仍未批准。新合同的两臂两步 CUDA smoke 见 [`smoke_report_reprojection_only_20261006.json`](../experiments/from_scratch_mean_pose/smoke_report_reprojection_only_20261006.json):各源 `joint2d=0`、`reprojection>0`,loss/grad 有限且第二步 decoder 有梯度。本文以下旧 smoke 数值、旧配置哈希和 `joint2d=1.0` 表格均是变更前的历史记录,不能当作新合同的四指标或收敛结果。 + +## 当前 v2:MANO-pkl mean + +- 固定 anchor 分别从 `MANO_LEFT.pkl`、`MANO_RIGHT.pkl` 的 45D `hands_mean` 读取,按 15 个局部关节 axis-angle 转 SO(3)。左右 pkl SHA-256 分别为 `c4022f7083f2ca7c78b2b3d595abbab52debd32b09d372b16923a801f0ea6a30`、`45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767`。网络计算 `R_local = R_mean @ R_delta`;`flat_hand_mean=True` 的 MANO 几何层仍接收 absolute pose,不再加一次 mean。 +- [`statistics_mano_pkl_v2.json`](../experiments/from_scratch_mean_pose/statistics_mano_pkl_v2.json) 仅用 train-only 去重帧拟合相对于固定 pkl mean 的 delta 6D 与其它 GT 的归一化统计;源权重仍为 21:15:24,三源 hand-frame 仍为 H2O 95,077、ARCTIC 293,441、HOT3D 2,084,401。统计有限,`pose_scale` 范围为 `0.1` 至 `0.5559`。旧 `statistics.json` 被新 smoke 合同显式拒绝。 +- pkl mean 与旧 train-estimated mean 不相同:15 个局部关节的平均测地角差,左手约 `9.93°`、右手约 `8.98°`,最大分别约 `18.04°`、`15.80°`。因此旧 delta 统计和旧 smoke 不能复用。 +- 新 [`smoke_report_mano_pkl_v2.json`](../experiments/from_scratch_mean_pose/smoke_report_mano_pkl_v2.json) 在 GPU 5 上完成 B0/B1 各两次真实 CUDA 更新。两臂的非 decoder 初始状态相同,GT/预测最大正交误差分别不超过 `5.96e-7` / `3.58e-7`,loss 和 pre-clip grad norm 均有限。 + +| v2 smoke | B0 配额加权 loss | B1 配额加权 loss | B0 / B1 pre-clip grad norm | decoder 非零梯度 tensor | +| --- | ---: | ---: | ---: | ---: | +| 第 1 次 | 4.4953 | 4.4953 | 97.18 / 96.30 | 0 / 0 | +| 第 2 次 | 4.3371 | 4.3348 | 96.41 / 95.45 | 90 / 122 | + +变更前资产 SHA-256:`config.json` 为 `8ba60ae121a455bb3e1070f969b793f8038265c15d0b4e3f62566a392fb35bcb`,v2 statistics 为 `cc5fa3eb0e7aa27134eee3f5a547d820582e938b9fea2846139f56b7905e19ff`,v2 smoke 为 `d07c9469428fd21ed378ebe1e949fa34545f363b2b9966e388526ba7ff9e6861`。这里只通过了局部数据/表征/监督 smoke;HOT3D 训练 reader 最终 pose mask 的全量交集、完整 60-clip batch、逐 loss 梯度/DDP 和正式训练日程仍未过 gate,`training_approved=false`。本次没有正式训练,也没有四指标结果。 + +## 历史记录:训练数据估计 mean 的旧合同 + +日期:2026-10-04。以下旧数值属于当时的 **RGB-only、T=8、无 teacher** B0(非 MoT)/B1(MoT)配对 smoke;不是历史 N0/N1,也不是正式训练或 benchmark 结果。旧实测证据为 [`statistics.json`](../experiments/from_scratch_mean_pose/statistics.json) 和 [`smoke_report.json`](../experiments/from_scratch_mean_pose/smoke_report.json)。当前实现见 [`fit_targets.py`](../experiments/from_scratch_mean_pose/fit_targets.py)、[`model.py`](../experiments/from_scratch_mean_pose/model.py)、[`loss.py`](../experiments/from_scratch_mean_pose/loss.py)。 + +## 先看结论 + +| 检查 | 已证实 | 尚不能宣称 | +| --- | --- | --- | +| 1. 数据 | 三源 train-only 去重统计已生成;抽取的三条 T=8 clip 的相机坐标、有效 mask 和几何一致性通过;两臂读取同一批输入 | HOT3D 全量统计帧与训练时 `<=1 mm` pose/shape 兼容 mask 是否完全一致;全量 60-clip batch 的有效监督占比与异常率 | +| 2. 表征 | 左右手 15 个局部关节各有固定 SO(3) mean;root 直接预测,local 学右乘 delta;GT/预测经 FP32 正交化后在同一 6D 空间比较;抽样正交性通过 | 长尾关节的角度误差、预测方差、正式训练及推理链路是否持续正常 | +| 3. 监督 | 12 项 loss 都接入;无 teacher/distillation;三源两次 CUDA 更新 loss/grad 有限,第二次 decoder 有梯度;两臂非 decoder 初始状态相同 | 单项 loss 的梯度贡献、6 卡完整 batch 的 clipping/DDP 稳定性、收敛与四指标改善 | + +**当时状态:只通过局部实现和 smoke gate,未批准正式训练。** `config.json` 的 `training_approved=false`,正式 budget、warmup、分阶段 LR、DINO 解冻时间均未填。以下“通过”均不等于模型已收敛。 + +## 1. 数据检查 + +### 输入、坐标与标签 + +- 输入只含 RGB,T=8。K 用于 2D 重投影 loss,`K_input_available=false`;depth 既不输入也不训练。不能把“用了 K 算 loss”说成 RGB+K 模型。 +- 绝对 wrist translation、3D joints、vertices 为 **camera-space 米制坐标**;root-relative joints 和双手相对 wrist/时间差量也是米制差量;局部 MANO pose 是关节局部旋转,不能称为 camera-space 位置。2D joints 是像素坐标,loss 中才按图像宽高归一化。 +- H2O/ARCTIC 使用已重拟合的 canonical 参数标签;HOT3D 保留 native 几何目标。统一的 `fix_left_shapedirs=True` 模型解码约定已用于几何核验。H2O/ARCTIC 的训练目标与 source-native held-out 评估目标不可混同;后者必须单列报告。 +- HOT3D reader 只有在 corrected-MANO mesh 与 native mesh 最大顶点差 `<=1 mm` 且 pose/beta 有限时,才打开 `local_pose_valid`/`shape_valid`。不兼容的帧可能仍有 root、mesh 或 joints 等监督。各 loss 使用不同的字段 mask;2D/3D joints 与重投影在 loss 内还显式检查 `frame_valid`,其余项依赖 reader 生成的有效性字段,不能用统一的“有手”mask 替代。 +- 2D 监督沿用 source 提供的 2D 与视窗有效性 mask。这里没有证明 2D 是独立人工标注,也没有用它作为与 3D 独立的正确性证据;正式评估应继续分开看 2D 与 3D 指标。 + +### 统计资产与覆盖范围 + +[`fit_targets.py`](../experiments/from_scratch_mean_pose/fit_targets.py) 从 trainable T8 索引收集窗口、按 source/recording/frame/hand 去重;H2O/ARCTIC 读 canonical 标签,HOT3D 读 filtered/native 路径。先在每个 source 内等权,再按每步配额 H2O:ARCTIC:HOT3D = **21:15:24** 加权,而不是让 HOT3D 以原始帧数压倒其他源。held-out 不进入统计。 + +当前资产路径:训练索引 `/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite`;canonical 标签清单 `/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json`。这些是当前机器上的定位路径,跨机器复算时应以 SHA-256 确认同一内容。 + +| 源 | 扫描到的有效 hand-frame | 左 / 右 local-pose 帧 | 每步目标配额 | +| --- | ---: | ---: | ---: | +| H2O | 95,077 | 47,584 / 47,493 | 21/60 | +| ARCTIC | 293,441 | 144,564 / 148,877 | 15/60 | +| HOT3D | 2,084,401 | 1,039,059 / 1,045,342 | 24/60 | +| 合计 | 2,472,919 | 1,231,207 / 1,241,712 | 60/60 | + +**重要边界:这些是统计脚本扫描后的帧数,不是已经审计过的最终 pose 有效监督帧数。** HOT3D 统计路径使用 filtered `valid`,训练 reader 还额外施加 corrected/native mesh `<=1 mm` 兼容门。三源 smoke 样本均通过,但目前没有全量交集/差集计数,因此不能保证 HOT3D mean 与实际参与 local-pose loss 的帧集合完全一致。正式训练前应按训练 reader 的最终 mask 复算计数,并决定重拟合统计量还是明确接受该偏差。 + +Smoke 只对每源挑一条完整 T=8 clip(每源 16 个有效 hand-frame),不是加载一个完整 global batch=60。三个样本的 wrist 与 camera-space wrist joint 最大差分别为 H2O 0、ARCTIC 0.00012、HOT3D 0 mm;`validate_cached_geometry` 对这些样本通过。采样器前 60 个位置的 source 计数为 21/15/24,但完整 60-clip 数据加载、mask 分母、异常帧比例尚未测量。 + +### 版本锚点 + +| 资产 | SHA-256 | +| --- | --- | +| trainable T8 index | `5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462` | +| canonical label inventory | `0bd3135ee5cdda31e50109cefc8fc8083b0d57d9646c9eb6d2f7aeab9e904b62` | +| statistics.json | `9c3f4e5083c5aa3787f4b5f42567affe61b3a04405175a4c13fe4af57398ed73` | +| config.json | `3b141347810701f91cd7ecab2ce7919f2bda0fff3041d85c8a85a42b3a9fcf3c` | +| smoke_report.json | `e806e29419f6ffd14bce3181e45111bec9816308f192739d1979ff01f398b578` | + +## 2. 表征检查 + +模型沿用一个 `16 x 6D` rotation head,没有额外 delta head。第 0 个关节是 camera-space root orientation,直接预测;余下 15 个局部关节先预测右侧增量,再以固定训练集 mean 组合: + +```text +R_delta_gt = transpose(R_mean) @ R_local_gt +R_local_pred = R_mean @ R_delta_pred +``` + +Mean 分左/右手、分关节,通过 source 加权 SO(3) 测地均值拟合。`statistics.json` 的最后一次迭代最大切向步长为 `2.54e-7 rad`;资产本身的最大正交误差约 `6.22e-15`,最大行列式误差约 `5.11e-15`。这说明求均值的迭代和矩阵约束通过,不代表 mean 能解释全部姿态方差。 + +GT 原始 `mano_pose` 为 axis-angle;在 loss 内以 FP32 转旋转矩阵,再取**前两行**作为 6D GT。预测 raw 6D 以 FP32 Gram-Schmidt 构成矩阵,顺序同为第一行、第二行,第三行由叉乘确定。局部预测最终矩阵先左乘 mean;计算 local loss 时两侧都乘 `R_mean^T` 回到 delta,再只比较前两行六分量。**没有 3x3 矩阵 pose loss**,也没有符号等价处理。BF16 只用于模型 forward,GT 转换、正交化和 pose loss 均禁用 autocast。 + +统计归一化在同一表示空间进行:root 直接 6D 和 local delta 6D 分别用 train-only `pose_center/pose_scale`;每分量 scale 下限 `0.1`。平移/绝对 joints/vertices 用 train-only `xyz_center/xyz_scale`(整体 scale `0.154738 m`,下限 `0.1 m`);相对 3D 量只除 `xyz_scale`;beta 用 train-only center/scale(下限 `0.5`);2D 除各图像的宽/高。这些都是 **loss 目标空间的归一化**,不表示缓存中原始 GT 已被改写。 + +两次更新的三源样本中,GT 最大正交误差 `5.96e-7`,预测最大 `3.58e-7`。单元测试覆盖 6D 行顺序、mean 初始姿态、BF16 下 FP32 delta 监督与 mask。尚未记录每关节测地角误差、预测/GT 方差、极端 raw6D 范数;因此不能用这一项检查推断“平均手势”问题已解决。 + +## 3. 监督与训练动力学检查 + +B0/B1 的监督代码、系数、source 权重完全相同。下表的“第 2 次 B0 贡献”是三条选中 clip 按 21/15/24 加权后的**已乘系数标量**,仅用于看量级;不是全量均值,也不能替代逐项梯度范数。 + +| loss | 系数 | 目标/有效性 | 第 2 次 B0 贡献 | +| --- | ---: | --- | ---: | +| `joint2d` | 1.0 | 预测与 GT 的宽高归一化 2D,`joint2d_valid` | 0.1202 | +| `joint3d_camera` | 1.5 | 归一化 camera-space joints,`joint3d_valid` | 1.2037 | +| `joint3d_root_relative` | 1.5 | wrist-relative joints,专用 relative mask | 0.5861 | +| `vertices_camera` | 0.15 | 归一化 camera-space vertices,`vertices_valid` | 0.1201 | +| `local_pose` | 0.3 | mean-relative、正交 6D L1,`local_pose_valid` | 0.1897 | +| `global_orientation` | 0.3 | root 直接、正交 6D L1,`global_orientation_valid` | 0.4820 | +| `shape` | 0.1 | 序列级 beta 对有效帧 GT 均值,`shape_valid` | 0.0711 | +| `translation` | 1.5 | camera-space wrist xyz,`translation_valid` | 1.2449 | +| `reprojection` | 1.0 | 用 GT K 投影预测 3D,reprojection/K/frame mask | 0.1391 | +| `temporal_velocity` | 0.015 | 相邻有效 wrist 位移差 | 0.0002 | +| `temporal_acceleration` | 0.0075 | 连续有效 wrist 二阶差 | 0.00003 | +| `bimanual_relative_wrist` | 0.15 | 同帧双手均有效时的 wrist 差 | 0.1614 | + +除重投影外,各项使用 masked L1;重投影是 masked 像素 L1 加深度屏障。缺失监督的分母依各项自己的有效元素计算。重投影使用图像尺寸归一化的像素差,预测深度投影下限 `0.05 m`,低于下限时另加 `10/m` 的深度惩罚,不能让负深度靠 `clamp` 偷过 loss。Smoke 中三个源的非正投影关节计数均为 0。这里的 `joint2d` 与 `reprojection` 可能来自相同 2D 标注,并非两份独立证据;4 指标仍须单独评估。 + +Teacher 配置为不创建、不前向、不蒸馏且权重 0;当前 `FromScratchLoss` 只有上面 12 项,smoke 也只构建一个 student。DINO 从官方预训练权重载入,SHA-256 `9a21ac3df0c63839d62612dda6f454d816c25611cc7a52966ed5a5a94921dc8b`,冻结全部 DINO block;其余可学习模块新初始化,无 Foundation Hand parent checkpoint。B0 trainable 参数 `19,395,736`,B1 `23,071,896`,参数量并不严格匹配;两臂非 decoder 初始状态哈希相同。B1 还会更新 RGB token,因此将来有收益只能先称为架构族结果,不能归因于单一注意力算子。 + +| smoke 更新 | B0 配额加权总 loss | B1 配额加权总 loss | B0 / B1 pre-clip grad norm | decoder 非零梯度 tensor | +| --- | ---: | ---: | ---: | ---: | +| 第 1 次 | 4.4785 | 4.4785 | 97.37 / 96.48 | 0 / 0 | +| 第 2 次 | 4.3187 | 4.3162 | 96.53 / 95.55 | 90 / 122 | + +Head 初始权重为零、初始输出是 root identity 与 local mean,故第一次更新时 decoder 梯度为零;第二次 head 打开后 decoder 有梯度。这是已观察到的初始化动力学,**不是训练失败**。裁剪阈值为全局 norm `100`,上述四个 pre-clip 值都低于阈值,故本次 smoke 未触发 clipping。两次 scalar loss 下降也不能外推为收敛,更不能比较 B0/B1 性能。 + +## 正式训练前的关闭条件 + +1. 对 HOT3D 用实际 `U0Dataset + CanonicalLabels.apply` 最终 `local_pose_valid`/`shape_valid` 全量计数,与统计输入逐帧比对;若存在实质差集,以真实训练 mask 重拟合 mean/center/scale,更新资产哈希,并重跑配对 smoke。 +2. 在完整 60-clip batch 上逐源记录各 loss 的有效分母、NaN/无效深度、mask 覆盖、2D/3D 一致性与 batch 时延;检查没有一个 source 因有效 mask 稀疏而名义配额高、实际梯度低。 +3. 测量 12 项对 rotation head、translation head、decoder 的梯度范数及方向,记录多步 pre/post-clip norm;跑 6 卡 DDP 的等价性、同步和 checkpoint 恢复 smoke。现有标量贡献不能回答监督是否冲突。 +4. 给 B0/B1 注册完全相同的 budget、warmup、LR、DINO 冻结/解冻、评估与 checkpoint 规则;记录 B1/B0 FLOPs 或吞吐差异;通过后才把 `training_approved` 改为 true。 +5. 正式训练后,固定 source-native GT 和同一 RGB T=8 推理协议,列出 **Abs MPJPE、Root MPJPE、MPVPE、2D px** 四指标;另报 hard-pose、每关节角误差和预测/GT 方差。不要拿两次 smoke loss 当作四指标结果。 + +核验入口:`python -m pytest tests/test_from_scratch_mean_pose_config.py tests/test_from_scratch_mean_pose_runtime.py`。已生成的统计与报告脚本拒绝覆盖目标文件;复算时须指定新的输出路径并比较 SHA,不要覆盖当前证据。历史 N0/N1 代码没有参与这次新路径检查。 diff --git a/home/wuyifan/EgoNet_train_20261008/docs/FROM_SCRATCH_MEAN_POSE_REVIEW.md b/home/wuyifan/EgoNet_train_20261008/docs/FROM_SCRATCH_MEAN_POSE_REVIEW.md new file mode 100644 index 0000000000000000000000000000000000000000..7b3713bc6f3523482aded70573c03626c0bf6457 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/FROM_SCRATCH_MEAN_POSE_REVIEW.md @@ -0,0 +1,107 @@ +# Foundation Hand: 停训后重头训练方案(待确认,不启动) + +时间:2026-10-03 HKT。此文档供检查;不修改当前 N0/N1 配置、不启动新训练、不先删除尚可能用于诊断的唯一权重。 + +## 1. 当前实验何时停 + +- G2 N1 已自然完成 20K;按用户最新指示,G1 N0 无需等 20K,已在训练日志 `19,247` step 时主动停掉 transient systemd service(`Restart=no`)。终止信号导致服务显示 `Result: exit-code`,不是此前训练故障;主 PID 已退出。N0 最后完整 checkpoint 是 18K,未落盘的 18K 后进度不作为可评估模型。 +- 用已有且 SHA256 与当前权重一致的同一步数 **N0/N1 18K** native-GT development 报告做受控比较,另保留 N1-20K 作为时间曲线参考;不把 18K/20K 跨步数差异归因于 reweight,也不启动下一组。 +- 当前 N0/N1 均从 U0 RGB 20,004 step 继承,且 `rgb_teacher_weight=0.05`。因此它们只能回答“续训的直接 6D 与重加权”,不能证明从头训练或 mean-pose delta 的效果。 + +## 2. 训练 GT 合同审计 + +| 内容 | 当前实际表示与坐标系 | 待做/注意 | +|---|---|---| +| `joint3d_camera`、`vertices_camera`、`wrist_root_translation` | 公制米的 camera-space 3D。H2O 直接读 camera joints;ARCTIC 把 world MANO 用官方 `R,t` 转相机;HOT3D 用 `inverse(T_world_camera)` 转相机。H2O/ARCTIC 后续使用 corrected-left canonical refit 重建同一 camera-space 几何。 | 既有训练每个 batch 调 `validate_cached_geometry`,有效 mesh 与 pose/shape/wrist 重建误差必须 `<=1 mm`,否则立即抛错;抽样中各源有效 GT 深度均为正。 | +| `mano_pose` | 缓存中是每关节 axis-angle `[T,2,48]`。第 0 个 root/global orientation 表示 camera 坐标方向;后 15 个是 MANO **关节局部**旋转,不应笼统称作 camera-space pose。 | 用 GT 轴角在 FP32 转矩阵,检查 `R^T R=I`、`det R=+1`、左右手/关节顺序,以及转换前后 mesh 一致。 | +| 训练 6D target | 并非缓存里已经存好的正交 6D;loss 中现场用 axis-angle→matrix 的前两行生成,预测 raw 6D 经 Gram-Schmidt,再各自用训练集 center/scale 归一化算 L1。 | 当前 bf16 autocast 内 GT 转换虽返回 FP32,内部矩阵乘法仍降精度。三源真实 tile 上 GT 正交误差均值 `0.0015–0.0022`,对应归一化 6D 分量差 `0.0008–0.0021`;预测矩阵约 `1e-7`。下一版必须在禁用 autocast 的 FP32 区域生成 GT rotation/6D 并加单测。 | +| 其它标签 | `joint2d` 是像素,`K` 是内参,`beta` 无空间坐标;`camera_pose` 是相机与世界的变换。 | “所有 GT 都是 camera-space”仅对手的 3D 几何和 root 平移/方向成立,不能套到 2D、beta、局部 pose 或相机位姿。当前 RGB 模型不把 depth/K 当输入;K 用于重投影监督。 | + +数据入口是 `U0Dataset -> CanonicalLabels.apply -> intersect_filtered_valid`。H2O/ARCTIC 的 refit 缓存经既有审计覆盖 380/380 个登记 recording、192,148 个左手帧且 `ready_for_training=true`;HOT3D 仅对统一 MANO 重建与原生 mesh 最大偏差 `<=1 mm` 的手帧打开 pose/shape mask。仍需避免把有效 mask 外的 NaN 当作训练 target。 + +新增只读实测:从训练流每源均匀选 10 个 tile,报告见 `.tmp/pose_delta_ablation_20261002/evaluations/training_gt_contract_10_tiles_per_source.json`。只支持抽样与代码合同判断,不等于对每个训练帧做过投影逐项证明。 + +| Source | 有效 3D joints | 非正 Z | wrist/root 最大差 mm | FP32 `||R R^T-I||` 均值 | GT 3D 投影到标签 2D 均值 px | +|---|---:|---:|---:|---:|---:| +| H2O | 3,360 | 0 | 0 | 1.12e-7 | 0.345 | +| ARCTIC | 2,940 | 0 | 0.000150 | 1.22e-7 | 0.271 | +| HOT3D | 2,793 | 0 | 0 | 1.14e-7 | 0 | + +因此目前没有发现三源 hand geometry 的 camera/world 坐标混用或缓存 GT 旋转本体的非正交问题;**训练 autocast 下生成的 6D target** 仍是数值例外,应先修后训。 + +## 3. 为什么要做 mean-pose delta,但不能把它当作充分条件 + +现模型每只手一个 token 直接输出 root+15 local 的 `16x6` raw rotation,初始 head bias 为 identity;没有 mean-pose residual。N1-18K 相对同 step N0 在 HOT3D hard 的 local-pose 角误差只改善 `0.176°`(录制级 95% CI `[-0.241,-0.107]°`),H2O/ARCTIC 没有一致改善。极端弯曲仍低估,单纯 hard reweight 的增量有限。 + +HOT3D N1-18K held-out hard 的**诊断性 oracle**(只替换一个预测因子为 native GT,其余保持模型输出;不能作为部署成绩)给出: + +| 替换因子 | Abs MPJPE 变化 | Root MPJPE 变化 | MPVPE 变化 | 2D 变化 | +|---|---:|---:|---:|---:| +| 15 个 local pose | -0.643 mm | -2.711 mm | -0.533 mm | -0.998 px | +| root orientation | -0.798 mm | -12.398 mm | -0.685 mm | -0.536 px | +| root translation | -29.613 mm | -0.004 mm | -30.401 mm | -1.905 px | + +`direct` 四指标与原 N1-18K 报告逐项一致,oracle 的 20K/其它 source 尚未完成。这个分解说明局部手指 pose 有可用空间,特别是 Root MPJPE 与 2D;但 Abs/MPVPE 更受全局平移限制,root orientation 也占很大比重。**把 local pose 改写成 delta 只换坐标原点,不会凭空提供新的视觉信息,也不能单独修好四指标。** + +N1 到 20K 后在同一纯 RGB、T=8、source-native GT development panel 上完成三源评估。下表是 **N1-20K 减 U0 parent** 的配对四指标误差;负数才是改善,单位依次为 mm/mm/mm/px。模型仍是旧 U0 parent 续训、带 `0.05` teacher anchor,不是下面拟议的从头/无 teacher/delta 实验。 + +| Source / 桶(有效手数) | ΔAbs | ΔRoot | ΔMPVPE | Δ2D | Δlocal pose角误差 | +|---|---:|---:|---:|---:|---:| +| H2O all (1536) | +0.388 | +0.019 | +0.378 | +0.016 | +0.145° | +| H2O hard (488) | +0.433 | +0.020 | +0.426 | +0.174 | +0.125° | +| ARCTIC all (1568) | +0.194 | -0.243 | +0.200 | +0.378 | +0.082° | +| ARCTIC hard (533) | -0.030 | -0.317 | -0.030 | +0.371 | -0.032° | +| HOT3D all (3573) | -0.208 | +0.020 | -0.196 | -0.185 | -0.054° | +| HOT3D hard (2534) | -0.264 | +0.054 | -0.249 | -0.273 | -0.210° | + +报告:`.tmp/pose_delta_ablation_20261002/evaluations/pose_hard_{h2o,arctic,hot3d}_n1_20k.json`;其中另含 normal、指尖、弯曲偏差和按 recording bootstrap 的配对区间。H2O hard 四项都受损,ARCTIC 与 HOT3D 各有取舍,故 N1-20K **未达四指标与跨源 no-harm 门**。N0 没有 20K checkpoint,不能把 N1-20K 相对 parent 的所有变化归因于 hard reweight。 + +真正匹配的 N0/N1 比较取两者的 **18K 完整 checkpoint**。现存文件 SHA256 分别为 N0 `3d176e89...1feea`、N1 `07ffd4d5...af2b`,与三源既有 `pose_hard_*_12k18k.json` 的注册值相同。下表是 hard 手 **N1 减 N0** 的四项指标与局部 pose 角误差;负数改善,四指标单位 mm/mm/mm/px。 + +| Source hard(有效手数) | ΔAbs | ΔRoot | ΔMPVPE | Δ2D | Δlocal pose | +|---|---:|---:|---:|---:|---:| +| H2O (488) | -0.023 | -0.019 | -0.021 | -0.060 | -0.029° | +| ARCTIC (533) | -0.085 | -0.071 | -0.083 | -0.034 | +0.015° | +| HOT3D (2534) | -0.138 | -0.059 | -0.138 | -0.052 | -0.176° | + +N1 相对 N0 的 hard 收益虽多数为负,但量级很小,且 HOT3D normal 手的 local pose 角误差 **+0.276°**、指尖误差 **+0.256 mm**。更重要的是 N0 相对 U0 parent 的 H2O hard 四项分别 `+0.476/+0.017/+0.471/+0.264`,N1 并未消除这一下降;N1-20K 的 H2O hard 也仍四项受损。当前 reweight 不能解决跨源四指标或偏平均主问题。详细数值及录制级 bootstrap 区间在 `HK.md` 与上述 JSON。 + +## 4. 待批准的新模型/训练合同 + +1. **真正重头**:只加载 DINO 官方预训练视觉权重;Foundation Hand decoder、temporal blocks、MANO pose/shape/translation heads、任何 modality/MoT branch 全新初始化。不得从 S4/A7/U0/N0/N1 继承训练权重。MANO 几何资产是固定模型,不算待学习权重。 +2. **没有 teacher**:不创建 teacher 模型、不做 teacher forward,`rgb_teacher_weight=0`,不计算 distillation。保留真实 GT 的 camera/root-relative 3D、mesh、MANO 关节重投影、root translation、pose/shape 等监督。2026-10-06 两臂共同关闭独立 `joint2d` loss(权重 0),只保留权重 1.0 的重投影作为 2D 监督;该监督修订不是 B0/B1 之间的消融变量。 +3. **固定 local mean rotation(2026-10-04 修订)**:从官方 `MANO_LEFT.pkl`/`MANO_RIGHT.pkl` 各自的 `hands_mean` 读取 15 个局部关节 axis-angle,逐关节转 SO(3) 后固定为 buffer;不再从训练数据估计 local mean。训练 split 仅用于在这一固定基准下拟合 delta 6D 及其它 GT 的 center/scale。记录两份 pkl 的哈希;几何层仍以 `flat_hand_mean=True` 接收最终 absolute pose,不能把 pkl mean 再叠加一次。 +4. **预测局部 delta**:`R_delta_gt = R_mean^T @ R_gt`;head 输出 raw 6D,FP32 Gram-Schmidt 得 `R_delta_pred`;最终 `R_local_pred = R_mean @ R_delta_pred`。此处采用右乘,即 delta 在关节局部参考系;配套 round-trip 和左右手测试必须证明与 MANO 的矩阵合同一致。delta head 初始化为 identity,初始最终 pose 为固定 mean。root/global orientation 仍单独直接预测 camera-space rotation,不强套全局 mean。 +5. **监督与输出对齐**:两侧都在 FP32 正交化后,只比较 delta rotation 的前两行 6D,使用仅由训练 GT delta 拟合并固定的 center/scale;MANO/几何损失用组合后的最终矩阵。若启用现成 `structured_hand_refinement`,当前 `NormalizedLoss` 只监督 coarse `mano_rotations_6d`,会漏掉最终 residual pose,因此必须先改成监督最终姿态并单测梯度。第一轮表示消融先不启用该模块。 +6. **受控比较(2026-10-06 分辨率修订)**:mean-pose delta 与 FP32 正交 GT 6D 是两组共同的训练前提,不再作为消融变量。B0 是 RGB factorized hand-query decoder(非 MoT),B1 是 RGB/HAND unified MoT spatial decoder;二者均从官方 DINO 开始,其余可学习参数全新初始化。固定同一数据顺序及每条 clip 的分辨率、三源比例、T=8、mean/delta 统计量、损失、随机种子、temporal blocks/head 配置、冻结/解冻日程与训练预算,只改变 spatial decoder。禁止使用旧 U0 `convert_parent` 从 S4 拷贝权重。记录两组参数量与计算量;MoT 若受益,先称为架构族收益,不把参数量差异误写成单一注意力算子收益。hard/finger reweight 留作后续独立实验。 +7. **训练/选模门**:先检查 GT 合同、forward/backward、loss/grad/clipping、checkpoint 完整性;然后持续跑到四指标及 hard-pose 曲线出现可信平台,而非用 2K/6K 判收敛。按预注册 held-out H2O/ARCTIC/HOT3D 同一纯 RGB、T=8 口径比较 Abs/Root/MPVPE/2D、逐关节测地角、GT>=60° 弯曲低估、root-relative 指尖及 normal no-harm。选择权重后只做一次正式 benchmark confirmation。 + +### B0/B1 混合分辨率训练计划(2026-10-06) + +三档均为 `[H,W]`:`512x896`、`368x640`、`512x512`。保持全画幅等比例 resize + pad,不做 GT 手框裁切,也不把方形图像直接拉伸。以下为按当前源画幅提出的**起始采样比例**,尚未由全量手部框尺寸/出画分布优化,不是已运行配置: + +| 训练源/设备 | 原始画幅或当前读取画幅 | `512x896` | `368x640` | `512x512` | 依据 | +| --- | --- | ---: | ---: | ---: | --- | +| H2O cam4 | `720x1280` | 75% | 20% | 5% | 方形 pad 后有效图像约 `288x512`,仅少量用于跨画幅泛化。 | +| ARCTIC ego0 | rectified reader 输入 `600x840` | 70% | 20% | 10% | 方形有效图像约 `366x512`,不能让它替代高细节主档。 | +| HOT3D Aria | 原生 RGB `1408x1408` | 30% | 15% | 55% | 方形与宽画布的有效图像都可达 `512x512`,宽画布主要增加 padding token。 | +| HOT3D Quest3 | 原生灰度 `1024x1280` | 60% | 20% | 20% | 方形有效图像约 `410x512`,宽画布可保留约 `512x640`。 | + +原始 HOT3D 尺寸见 [官方数据说明](https://facebookresearch.github.io/hot3d/);**正式采样前仍需用项目的去畸变 provider 审计实际 `source_hw`**,不能把原生 sensor 尺寸直接当成 rectified 画幅。按当前 H2O:ARCTIC:HOT3D `21:15:24` 和 HOT3D train 保留窗口 Aria:Quest3 `6291:12671` 估算,三档总体约为 **64%/19%/17%**。这是计划值;实际曝光须从训练账本按 source、device、resolution 统计,不用理论概率冒充实测。 + +- 两臂使用同一冻结的 `(source, recording, clip, resolution)` 排程和随机增强种子。每个 T=8 clip 的 8 帧共用一个分辨率;为减少 padding/动态 shape 开销,计划一个 optimizer update 在所有 rank 上使用同一分辨率,再在固定多步周期内满足 `21:15:24` 源配比和上表条件比例。**这会把当前 `source_quota_per_update` 的逐步精确配额改为周期配额,必须先实现、测试并版本化新的 sampler;当前 smoke/配置仍只有 `512x896`,不得宣称三档已经支持。** B0/B1 必须用同一排程,不能一臂固定高分辨率、另一臂混训。 +- 三档都用同一原始帧、同一 GT 及有效性定义;RGB、K、2D 标注和画内 mask 必须经过相同的 resize/pad 变换。训练 2D loss 按当前画布宽高归一化,3D/MANO/pose GT 不因像素尺寸改变。对每源抽样核对投影误差、手部有效像素尺寸与边界手的有效性;HOT3D 另分 Aria/Quest3。三档均须分别通过 forward/backward、DDP、恢复训练和显存/吞吐 smoke,再定正式 LR/步数。 +- 主选模仍在**固定同一输入尺寸、同一 source-native held-out 面板**上比较 B0/B1 的 Abs MPJPE、Root MPJPE、MPVPE、2D px;另报三档推理鲁棒性。跨输入尺寸的 2D 误差须映射回原图或统一评估画布后才可比较,不把 `368x640` 与 `512x896` 的原始 px 直接平均。登记各档有效手/关节分母、padding 率、源/设备四指标和 hard/出画子集;若方形档损害 H2O/ARCTIC,需要调整比例并另起版本化消融,而不是中途热改配比。 + +原 N0/N1 的 20K 续训约需 26 小时/6 卡,曾粗略线性外推 400K 约 22 天/arm;**该旧值不能作为混合分辨率 B0/B1 ETA**。新模型从头训练、三档排程、microbatch/worker 数、DINO 阶段解冻与录制段 IO 都会改变吞吐;须先做包含三档和实际源比例的稳态六卡 pilot,再估算每臂时间。正式预算、冻结/解冻 step 与是否并行运行仍需在批准前明确注册,不用短训冒充收敛。对应的 B0/B1 审阅配置在 `wuyifan/EgoNet/experiments/from_scratch_mean_pose/config.json`;它尚不能由旧 N0/N1 trainer 运行。 + +## 5. 权重清理范围与记录 + +截至本次盘点:G1 N0 2K–18K 九个完整 checkpoint 约 5.4 GB,G2 N1 同样九个约 5.4 GB;本地还复制了 N1 的 2K/4K/6K/8K/12K/18K 约 3.6 GB。workspace 中另有大量历史实验权重,不能凭文件名判断“无用”。`/data-hdd` 尚有约 5.8 TB、`/SSD2` 约 1.4 TB、`/SSD3` 约 1.2 TB 可用,不存在紧急空间压力。 + +- **先保留**:DINO 官方预训练、S4/A7 及 U0 正式 parent、N0 的 18K 最后完整 checkpoint、N1 的 20K 终点、任何已证明最好或唯一的 checkpoint;6K/8K/12K/18K 也先保留到完成训练曲线和 hard-case 复核。 +- **已按用户确认范围删除**:仅删除 N0 的 2-step smoke checkpoint,以及本地 N1 2K/4K 的重复副本,共约 1.8 GB。删除前确认 smoke 元数据为 `smoke=true, update=2`;N1 2K/4K 本地与 G2 原件分别有一致 SHA256 `45d4064f...ad` / `f569060c...3cf5`。G2 原件未动,可重新复制;smoke 文件本身未备份,但不代表可用模型。 +- **后续候选暂不删**:其它中途 checkpoint 要等现有 18K/20K 评估、训练曲线和唯一性/备份检查后逐一判断,不能仅因步数较早就视为无用。 +- **不做宽泛删除**:`artifacts/` 下 255 个历史 `.pt` 的所有权、最佳权重与备份关系尚未逐个核实;当前不能主观当作废权重清掉。 + +本文件是 review 提案。**收到明确的“可以训练”前,不执行 B0/B1;当前不再扩大已确认的清理范围。** diff --git a/home/wuyifan/EgoNet_train_20261008/docs/GKDT_L_FEATURE_PROBE_20261006.md b/home/wuyifan/EgoNet_train_20261008/docs/GKDT_L_FEATURE_PROBE_20261006.md new file mode 100644 index 0000000000000000000000000000000000000000..982ae1eec82d0de39114c891eda09cb5a82982de --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/GKDT_L_FEATURE_PROBE_20261006.md @@ -0,0 +1,32 @@ +# GKDT-L frozen feature probe (2026-10-06) + +## Question and contract + +Does the 2D-keypoint-tuned GKDT-L application visual encoder improve the full-frame 42-keypoint P0 task relative to the existing frozen DINOv3-B baseline? This is an early frozen-feature probe, not a MANO benchmark or a causal test of keypoint pretraining. + +- Visual encoder: official `GKDT-L_for_App` DINOv3-L visual state, strict-loaded and frozen; 24 blocks, 1024 channels, approximately 303M parameters. Its extracted state is `wuyifan/artifacts/gkdt_feature_probe_20261006/app_visual.pt`, SHA-256 `508821fbac60701f14118f0f0df385154363f02c0d28c0f310a7fe51bc95aa7c`. +- Baseline: P0a frozen DINOv3-B, 768 channels. Both have patch size 16, 512x896 ImageNet-normalized full-frame RGB, the same 32x56 patch grid and 512-wide 42-query prediction head. Their trainable projection widths differ (1024->512 versus 768->512). +- Training: identical P0 T=1 phase index and seed, global batch 24, H2O:ARCTIC:HOT3D quota 21:15:24, AdamW 1e-4, weight decay 0.05, inferred x/y cross-entropy only. No teacher, visibility, or visible-keypoint loss. The GKDT run uses sample-mean gradient accumulation and resumes the optimizer through step 500, 1000 and 2000. +- Evaluation: same recording-disjoint dev selections of up to 256 frames per source, same selected tile hashes and valid-point counts. HOT3D has one unreadable frame in both arms. Values below are mean Euclidean 2D error in pixels against the P0 projected target; they are **not** the Foundation Hand MANO benchmark's 2D metric. + +| Source | P0a DINOv3-B 1K | GKDT-L 1K | P0a DINOv3-B 2K | GKDT-L 2K | GKDT-L minus P0a at 2K | +| --- | ---: | ---: | ---: | ---: | ---: | +| H2O | 24.875 | 37.049 | 18.358 | 26.171 | +7.813 px | +| ARCTIC | 37.429 | 59.757 | 27.592 | 44.138 | +16.546 px | +| HOT3D | 35.326 | 49.564 | 23.588 | 35.208 | +11.620 px | + +GKDT-L improves from 1K to 2K by 10.878 / 15.619 / 14.356 px on H2O / ARCTIC / HOT3D, respectively. Over the same interval P0a improves by 6.516 / 9.837 / 11.738 px. Thus the gap is narrowing, but at 2K GKDT-L is still worse on all three sources. Loss and gradient norms remained finite; this is not evidence of a failed run. + +## Interpretation and next control + +The 1024-channel, larger visual feature may require more updates for the new random projection/head to adapt; that explanation fits the faster 1K-to-2K reduction but is not established by two early checkpoints. The comparison also changes model capacity and visual pretraining together. Continuing GKDT-L to a prespecified convergence budget, and testing an **untuned DINOv3-L with the same projection/head/data/steps**, are required before attributing any gain or deficit to GKDT's keypoint training. A frozen-feature result cannot by itself predict the four MANO metrics after end-to-end tuning. + +The `ViTPose-L` weight and frozen-backbone probe interface are prepared separately, but no ViTPose-L training was launched; GKDT-L was prioritized. The ViTPose-H weights and smoke outputs were removed at the user's request. + +Artifacts: + +- GKDT-L run contract and 2K checkpoint: `wuyifan/artifacts/gkdt_feature_probe_20261006/app_head_1000to2000_b8/` +- GKDT-L 1K evaluation: `wuyifan/artifacts/gkdt_feature_probe_20261006/app_head_500to1000_b8/eval/step_001000.json` +- GKDT-L 2K evaluation: `wuyifan/artifacts/gkdt_feature_probe_20261006/app_head_1000to2000_b8/eval/step_002000.json` +- P0a matched evaluations: `wuyifan/artifacts/gkdt_feature_probe_20261006/p0a_step_001000_256.json` and `p0a_step_002000_256.json` +- Official GKDT release and training code: diff --git a/home/wuyifan/EgoNet_train_20261008/docs/HK.md b/home/wuyifan/EgoNet_train_20261008/docs/HK.md new file mode 100644 index 0000000000000000000000000000000000000000..7660d2da5bd5e10501c731805ad85c05401a1844 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/HK.md @@ -0,0 +1,263 @@ +# Foundation Hand: hard-case pose monitoring + +记录从 2026-10-03 上午开始的 N0/N1 续训评估。目标是判断直接 6D pose 监督及弯曲手势重加权,是否让局部关节、困难手势和四项 camera-space benchmark 指标持续改善,尤其解决预测偏向平均手势的问题。训练任务不因本记录或评估而停止。 + +## 固定口径 + +- N0、N1 均从同一个 U0 RGB step 20,004 权重续训,使用纯 RGB、归一化监督与正交化后的直接 6D pose loss;N1 额外对弯曲手势的 local pose 和 root-relative joint loss 加权。两者是续训消融,**不是从早期 stage 重新训练新监督范式**。 +- 当前只读监控用 `frozen_panels_sync_v2` 的 native-GT development:H2O 96 clips、ARCTIC 136 clips、HOT3D 248 clips。输入和推理设置一致,不用 refit GT,也不用预测 presence 过滤四项指标。反复看 development 只适合诊断,不等于最终官方 benchmark 或盲测。 +- 四指标依次为 Abs MPJPE、Root MPJPE、MPVPE(mm)、MANO 2D 投影误差(px),越低越好。表中差值为候选减 U0 parent,负数表示改善。分桶 hard case 另按 **GT** 的远端指骨夹角判断,不能由预测决定入桶。 +- 训练保留每 2K checkpoint。当前计划在 6K、8K、12K、20K 比较同一 panel 的四指标、局部旋转误差、root-relative 指尖误差、GT 高弯曲角下的有符号预测偏差与方差;不能凭单个 6K 节点宣称收敛或范式失败。 + +## 2026-10-03 09:00 HKT: 起始状态与 4K/6K 结果 + +G1 N0 约 8,969 step,G2 N1 约 9,016 step;两组 8K 权重都已保存,训练仍在运行。4K/6K 的 12 份 development 报告已核对:四个候选权重、同一个 parent、三源固定 panel,均为非 smoke 纯 RGB native GT。对应报告位于 `.tmp/pose_delta_ablation_20261002/evaluations/`。 + +| Source | Arm | Step | ΔAbs mm | ΔRoot mm | ΔMPVPE mm | Δ2D px | +|---|---|---:|---:|---:|---:|---:| +| H2O | N0 | 4K | +0.073 | +0.128 | +0.061 | +0.014 | +| H2O | N1 | 4K | +0.094 | +0.124 | +0.084 | +0.092 | +| H2O | N0 | 6K | +0.770 | -0.013 | +0.754 | +0.362 | +| H2O | N1 | 6K | +0.746 | +0.018 | +0.730 | +0.453 | +| ARCTIC | N0 | 4K | +1.072 | -0.219 | +1.098 | +0.448 | +| ARCTIC | N1 | 4K | +1.119 | -0.212 | +1.142 | +0.543 | +| ARCTIC | N0 | 6K | +0.557 | +0.184 | +0.557 | +1.070 | +| ARCTIC | N1 | 6K | +0.478 | +0.129 | +0.481 | +1.158 | +| HOT3D | N0 | 4K | +1.256 | +0.465 | +1.320 | +0.180 | +| HOT3D | N1 | 4K | +1.180 | +0.438 | +1.249 | +0.161 | +| HOT3D | N0 | 6K | -1.678 | +0.305 | -1.662 | -0.038 | +| HOT3D | N1 | 6K | -1.759 | +0.288 | -1.745 | -0.019 | + +HOT3D 6K 有明确的绝对关节/mesh 收益,但 root-relative 指标变差:N1 的录制级 bootstrap 95% CI,Abs 为 `[-2.381, -1.142] mm`,Root 为 `[+0.036, +0.526] mm`,MPVPE 为 `[-2.374, -1.125] mm`,2D 为 `[-0.287, +0.262] px`。N0 与 N1 在同一步数十分接近;到 6K 尚无 N1 重加权的明确增益。H2O/ARCTIC 没有四项同步改善。**这些是早期续训的 source trade-off,不是“6D loss 训练失败”或“已经解决 mean pose”的证据。** + +先前对同一 development panel 的 2K 逐关节 6D 方差诊断显示预测普遍低于 GT:手指关节平均预测/GT 方差比 H2O 约 0.79、ARCTIC 约 0.59、HOT3D 约 0.40;N0/N1 2K 没有系统性拉近。结果见 `rotation_variance_2k.json`。方差只衡量离散度,后续必须与逐帧角度误差、GT 大弯曲有符号偏差一起判断,避免把无关抖动误认作更丰富的手势。 + +## 待核实 + +1. 6K 到 8K、之后 12K/20K 的四项指标是否连续改善,还是存在 source 间抵消。 +2. 对 GT 高弯曲(至少两个远端角 >=45°,或任一 >=60°)的手,N1 是否降低角度低估、局部旋转误差和 root-relative 指尖误差;普通手是否被牺牲。 +3. 哪些 MANO 关节的预测方差低于 GT,随训练是否靠近;改善是否来自正确的逐帧姿态而非预测方差变大。 +4. 新监督是从 U0-20K 续训;如果长节点仍有优化冲突,应设计从更早 stage 出发的 matched old/new objective 训练。不能把续训结果直接外推为从头训练结论。 + +## 2026-10-03 22:17 HKT: 训练状态与 8K pose 诊断 + +G1 N0 为 18,229/20,000 step,G2 N1 为 19,123/20,000 step;两组 18K 权重已保存,训练均未停止。当前单步 loss 有限、未触发 clipping。12K/18K 权重尚未完成统一评估,因此这里不推断最终趋势。8K 的 N1 权重与 12K/18K 权重已复制到本地诊断目录,仅供只读评估。HOT3D 的 6K/8K 高弯曲评估正在运行,本节只报告已完成的 H2O 和 ARCTIC。 + +新增只读诊断器为 `.tmp/pose_delta_ablation_20261002/pose_hard_case_monitor.py`:在同一 development clip 上并排运行 U0 parent、N0/N1 6K/8K,使用 GT 的非拇指远端 8 个指骨夹角入桶。`hard` 为至少两个角 >=45° 或任一角 >=60°;仅纳入 MANO pose 有效且 21 关节几何完整的手帧。统计标准四指标、15 个 local MANO rotation 的测地角误差、root-relative 指尖误差、预测减 GT 的远端弯曲角偏差,以及左右手/关节的 6D 方差。6K 的标准四指标与前一次评估逐项一致,证明诊断器没有改变输入或这些指标的分母。报告及配对逐手记录位于同目录的 `evaluations/pose_hard_*_6k8k.json` 和对应 `.rows.json`。 + +| Source / GT 桶 | 有效手帧 | N1-8K vs U0: ΔAbs mm | ΔRoot mm | ΔMPVPE mm | Δ2D px | Δlocal pose ° | Δ指尖 root-relative mm | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O 全部 | 1,536 | +0.315 | +0.175 | +0.301 | +0.349 | +0.065 | +0.223 | +| H2O hard | 488 | +0.125 | +0.015 | +0.118 | +0.402 | +0.070 | -0.012 | +| ARCTIC 全部 | 1,568 | -1.292 | -0.629 | -1.256 | +0.935 | -0.041 | -0.778 | +| ARCTIC hard | 533 | -1.473 | -0.651 | -1.449 | +0.867 | -0.068 | -0.948 | + +ARCTIC hard 中 N1-8K 的录制级 bootstrap 95% CI:Abs `[-2.559,-0.486] mm`,Root `[-0.935,-0.434] mm`,MPVPE `[-2.532,-0.467] mm`,2D `[+0.591,+1.138] px`,指尖 `[-1.332,-0.650] mm`。local pose 平均测地角仅 `-0.068°`,CI `[-0.185,+0.068]°`,尚无可靠的旋转改善证据。 + +对 GT >=60° 的角,ARCTIC hard 的 parent 平均预测偏差为 `-31.212°`,N1-8K 为 `-29.666°`;虽然偏差减小 `1.546°`(录制级 CI `[+0.975,+2.113]°`),绝对低估仍很大。H2O 对应 parent `-14.814°`、N1-8K `-14.769°`,基本未变。故 **ARCTIC hard 的位置/指尖改善与轻微弯曲改善并存,但不能说 mean-pose 问题已解决**;尤其 2D 退化显著,H2O 未见收益。6K 到 8K 的曲线也不单调:H2O Abs/mesh 回落,但高弯曲偏差没有稳定改善。 + +## 2026-10-03 22:25 HKT: HOT3D 6K/8K 与 H2O 12K/18K + +HOT3D development 有 3,573 个完整有效手帧,按上述 GT 桶有 2,534 个 hard。这个 held-out panel 的 hard 比例不能代表全量 HOT3D 训练集分布。N1-6K 相对 U0 parent:全部手的 Abs/MPVPE 为 `-1.759/-1.745 mm`,但 Root `+0.288 mm`、root-relative 指尖 `+0.359 mm`;hard 手的 local pose 测地角 `-0.131°`(录制级 CI `[-0.226,-0.048]°`)、GT >=60° 的低估减轻 `0.772°`,但 hard 指尖 `+0.535 mm`(CI `[+0.148,+0.898] mm`)。改善了部分绝对位置和非常小的 pose 角度,却没有改善手指相对于手腕的几何。到 N1-8K,hard local pose 仅 `-0.046°`(CI 跨 0),hard 指尖变为 `+0.729 mm`,Abs/MPVPE 的改善也缩小到约 `-0.37 mm`(CI 跨 0)。因此不能把 6K 的收益解释为手指姿态持续收敛。 + +H2O 的 N1-12K 与 N1-18K 进一步检验“预测方差靠近 GT”是否意味着 pose 更准。全部手指关节的宏平均预测/GT 6D 方差比从 U0 parent `0.805` 升到 N1-12K `0.828`、N1-18K `0.833`,看似趋近 1;但 local pose 测地角从 `10.024°` 升至 `10.123°`、`10.169°`,hard 手从 `11.433°` 升至 `11.490°`、`11.578°`。N1-18K hard 的 local pose 差值为 `+0.145°`(录制级 CI `[+0.004,+0.313]°`),Abs/MPVPE 也各差约 `+0.45 mm`。**单独增大方差不能解决偏平均 pose,可能只是把预测散开而未对准 GT。** N1-12K 对 GT >=60° 的低估减轻 `0.624°`,相对仍有约 `-14.19°` 的大幅低估;到 18K 未继续稳定改善。 + +下一步正在跑 ARCTIC/HOT3D 的 12K/18K,随后在两组 20K 完成后做最终同口径评估。训练进程未人为停止;任何 checkpoint 的局部收益都应要求 hard 指尖、local pose、四指标及普通手 no-harm 同时审查。 + +## 2026-10-03 22:40 HKT: 12K/18K 三源结果与 mean-pose 机制 + +ARCTIC/HOT3D 的 12K/18K hard-case 诊断均已完成;三源各自的 parent、手帧数和 GT 入桶与 6K/8K 完全一致。下表是 N1 相对 U0 parent 的配对差值,负数为误差改善;`ΔGT>=60° bias` 为预测减 GT 的有符号偏差变化,正数在原本低估的前提下表示低估减轻。 + +| Source / GT 桶 | Step | ΔAbs mm | ΔRoot mm | ΔMPVPE mm | Δ2D px | Δlocal pose ° | Δ指尖 mm | ΔGT>=60° bias ° | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| H2O all | 12K | +0.163 | -0.002 | +0.149 | -0.106 | +0.099 | -0.006 | +0.624 | +| H2O all | 18K | +0.466 | +0.011 | +0.457 | +0.084 | +0.145 | +0.029 | +0.431 | +| H2O hard | 18K | +0.454 | -0.002 | +0.451 | +0.204 | +0.145 | -0.015 | +0.431 | +| ARCTIC all | 12K | -0.980 | -0.277 | -0.950 | +0.490 | +0.040 | -0.395 | +1.321 | +| ARCTIC all | 18K | +0.332 | -0.280 | +0.338 | +0.426 | +0.043 | -0.445 | +2.473 | +| ARCTIC hard | 18K | +0.166 | -0.348 | +0.166 | +0.434 | -0.085 | -0.651 | +2.473 | +| HOT3D all | 12K | +0.512 | +0.309 | +0.559 | -0.113 | -0.034 | +0.302 | +1.445 | +| HOT3D all | 18K | -0.415 | +0.039 | -0.392 | -0.275 | -0.028 | +0.044 | +1.573 | +| HOT3D hard | 18K | -0.569 | +0.034 | -0.543 | -0.393 | -0.212 | -0.014 | +1.573 | + +HOT3D hard 的 N1-18K local pose `-0.212°`(录制级 bootstrap 95% CI `[-0.334,-0.106]°`)、2D `-0.393 px`(CI `[-0.696,-0.146]`),但指尖 `-0.014 mm`(CI 跨 0);普通手的 local pose 却从 parent `14.037°` 升到 `14.457°`。ARCTIC 的 root/指尖及极端弯曲偏差有改善,Abs/mesh 和 2D 未稳住。H2O 到 18K 更差。**N1 确实给困难姿态一些信号,但收益小、跨源不一致,且 normal 手可能受损。** 目前不足以宣称四指标与 mean pose 问题同时解决。 + +更直接的幅度诊断:以每只手 GT 的非拇指远端平均弯曲角为自变量,对预测平均角作线性回归;理想校准斜率为 1。U0 parent 在 H2O/ARCTIC/HOT3D 的斜率分别为 `0.748/0.513/0.342`;N1-18K 为 `0.759/0.566/0.361`。源越难,预测角度随真实角度增长得越慢,符合“输出向平均手势收缩”;N1 只是部分缓解。斜率是描述性统计,不证明每个手势的逐帧准确性。 + +### Representation 与待查问题 + +- 已核对实际 `model_for("student")` 配置:`structured_hand_refinement=False`、`oracle_crop_mode=none`。每只手的一个 decoder hand token 经共享线性 head 直接输出 `16×6` raw rotation;前三数/后三数按相同行顺序 Gram-Schmidt 成为最终 MANO 使用的矩阵。GT 轴角转矩阵后取前两行,预测与 GT 用同一训练统计量归一化,再算六分量 L1。**不是预测相对 mean pose 的 delta**;head 在早期初始化为 identity,但现在继承已训练的 U0 权重。已检查的行序、正交化、最终矩阵合同没有发现硬 bug。 +- N1 只给 local pose 6D loss 和 root-relative 3D joint loss 的 GT 高弯曲手加权;对绝对 mesh、2D、translation、root orientation 没有相同加权。各 source 的有效元素再归一化,所以这不是把 hard 样本或整个梯度简单放大 2 倍。尚须实测 **经过正式 pose-valid/geometry mask 后** 的 hard 样本比例及每项对 rotation head 的梯度,才可断言该权重是否足够强。 +- 六分量 L1 监督虽实现正确,却不是直接优化远端弯曲或指尖的损失。模糊图像下它可能更倾向中心预测;提高 GT hard 样本权重不一定纠正单个样本的弯曲低估。要先测相应梯度和普通手 no-harm,再考虑有明确物理定义的弯曲角/局部几何目标,而不是盲目继续调大所有 pose 系数。 +- 单 hand token 同时回归 15 个局部关节,当前没有启用已有的 finger-level structured refinement。这是待验证的表达/注意力瓶颈假设,不是已证实的 bug。若监督梯度足够且训练标签一致,仍显著偏平均,可用配对小实验验证 finger-specific 图像特征是否改善难关节。 +- ARCTIC 的 native GT 用于评估,而训练使用 corrected-left canonical refit;直接比较参数空间的局部旋转角需核查 handedness、关节顺序及 native/refit 姿态约定。几何远端弯曲和指尖误差提供较少依赖参数基的交叉证据。ARCTIC hard 中小指多节的 native 参数角误差约 `39–49°`,不能在这一合同审计前全归因于网络。 + +## 2026-10-03 22:50 HKT: hard 权重与旋转头梯度抽查 + +只读脚本 `.tmp/pose_delta_ablation_20261002/audit_pose_gradients.py` 固定 N1-18K 完整 checkpoint,从训练 coverage 前 240 个位置各选两个有有效 pose 且 N1 hard weight >1 的 tile,逐项求 `rotation_head.weight` 的梯度。原始报告为 `evaluations/pose_gradients_n1_18k.json`。这是 **6 个经条件筛选的训练 tile**,没有跨所有 source/step 统计,也没有乘正式 DDP 每项 source-scaling 系数,故只用来检查梯度路径/量级,不用来声称全局梯度占比或冲突。 + +| Source | 每个 tile hard/有效手帧 | N1/N0 local-pose 梯度范数比 | N1 local-pose 梯度范数 | N1 root-relative joint 梯度范数 | local pose 与 root-relative 梯度 cosine | +|---|---|---|---|---|---| +| H2O | 8/16、1/16 | 1.14、1.00 | 1.56、1.53 | 2.02、2.64 | 0.12、0.09 | +| ARCTIC | 8/16、8/16 | 1.28、1.14 | 4.09、3.26 | 2.37、1.93 | 0.20、0.16 | +| HOT3D | 15/16、8/16 | 1.01、1.04 | 1.80、1.67 | 6.16、5.70 | 0.03、0.04 | + +N1 的 hard 判定和 local-pose 监督确实工作,但 loss 按带权有效元素总数归一化,权重变化在这些 tile 上并未把整个 pose-head 梯度提高 1.5–2 倍。HOT3D 的 local pose 与 root-relative 方向近乎正交;这不支持“几何项普遍反向抵消 pose”的简单解释,也不证明各项监督已经协调。global orientation 的梯度与 local pose 在单层线性 head 的不同输出行上天然正交,不能误读为任务冲突。下一步仍需最终 20K 结果和更广的 source-scaled 梯度/标签合同检查。 + +## 2026-10-03 22:54 HKT: autocast 下 6D GT 数值合同 + +原先“GT 取旋转矩阵前两行,因此训练时严格正交”的表述需要修正。`NormalizedLoss.forward` 在训练的 bf16 autocast 作用域内调用 `axis_angle_to_matrix`;函数返回 float32,但其中 `skew @ skew` 被 autocast 成 bf16,因此 GT 矩阵不是精确正交。只读脚本 `.tmp/pose_delta_ablation_20261002/audit_pose_precision.py` 用 N1-18K 和三源各一个真实训练 tile(每 tile 256 个 pose-valid joint rotations)测得: + +| Source | FP32 GT 正交误差均值 | 训练 autocast GT 正交误差均值 | autocast/FP32 GT 的归一化 6D 分量 L1 均值 | 预测矩阵正交误差均值 | +|---|---:|---:|---:|---:| +| H2O | 1.18e-7 | 0.00209 | 0.00139 | 1.46e-7 | +| ARCTIC | 1.33e-7 | 0.00216 | 0.00211 | 1.49e-7 | +| HOT3D | 1.15e-7 | 0.00155 | 0.00080 | 1.39e-7 | + +结果见 `evaluations/pose_precision_n1_18k.json`。预测端 raw 6D 的第一根向量均值范数约 0.95–1.60,正交化后第二根原始范数约 1.03–2.10;本抽查未见接近零导致 Gram-Schmidt 崩溃。预测矩阵与将 raw 6D 在 FP32 重算的矩阵逐元素相同。故这是 **GT 侧小的、真实的数值不一致**,应在下一次受控训练把 GT axis-angle→matrix 放到禁用 autocast 的 FP32 区域并加正交性测试;正在跑的 N0/N1 不应中途改代码。该偏差量级远小于 hard case 中约 15–31° 的极端弯曲低估,不能据此宣称已找到 mean-pose 主因。其余行序与 6D 语义核对仍成立。 + +同一步数 N1-18K 减 N0-18K 的 hard 手配对均值是更直接的 reweight 消融(负数表示 N1 更准): + +| Source hard | ΔAbs mm | ΔRoot mm | ΔMPVPE mm | Δ2D px | Δlocal pose ° | Δ指尖 mm | ΔGT>=60° bias ° | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O | -0.023 | -0.019 | -0.021 | -0.060 | -0.029 | -0.064 | +0.299 | +| ARCTIC | -0.085 | -0.071 | -0.083 | -0.034 | +0.015 | -0.183 | +1.060 | +| HOT3D | -0.138 | -0.059 | -0.138 | -0.052 | -0.176 | -0.128 | +1.132 | + +这些均值来自 `pose_hard_*_12k18k.json`。用对应 `.rows.json` 按物理录制 bootstrap 的 N1-vs-N0 95% CI:HOT3D hard local pose `[-0.241,-0.107]°`,GT>=60° 有符号偏差 `[+0.995,+1.277]°`;ARCTIC hard 指尖 `[-0.283,-0.089] mm`、Abs `[-0.148,-0.032] mm`;H2O hard local pose `[-0.058,+0.003]°`、Abs `[-0.078,+0.029] mm`。这表明 HOT3D 的弯曲重加权有可重复的微小局部 pose 信号、ARCTIC 有指尖/位置微小信号,但 H2O 没有明确 pose 改善,且三源四指标没有同步过门;不能宣称 reweight 已解决偏平均。继续以 20K 和正常手 no-harm 验证。 + +## 2026-10-03 23:00 HKT: 训练流 hard-case 暴露抽样 + +只读脚本 `.tmp/pose_delta_ablation_20261002/audit_hard_exposure.py` 在已注册的 1.2M clip 训练流上均匀选 30 个窗口,每窗口每源取一个 tile,按正式 `hand_tail_weights` 和 `mano_pose_valid & frame_valid` 数有效手帧。报告为 `evaluations/hard_exposure_30_tiles_per_source.json`。这是分散抽样,不是全量训练频率,也不保证 30 个 tile 的视频/subject 独立。 + +| Source | tile | pose-valid 手帧 | weight 1.5 | weight 2.0 | hard 占比 | 有效手帧平均权重 | 无 hard 的 tile | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O | 30 | 480 | 71 | 109 | 37.5% | 1.301 | 11 | +| ARCTIC | 30 | 444 | 51 | 81 | 29.7% | 1.240 | 14 | +| HOT3D | 30 | 421 | 121 | 127 | 58.9% | 1.445 | 6 | + +当前 GT 几何判据下,hard 手并非稀缺到几乎看不到;HOT3D 反而占多数。因此单纯继续增加同分布 hard tile 数量未必是主要瓶颈。N1 用带权平均损失,若 tile 中大部分手都加权,归一化后相对区分会减弱,和六 tile 梯度审计中 HOT3D local-pose 梯度只增约 1–4% 一致。更应检验单帧视觉证据、逐关节/指尖目标是否对准以及标签合同,不能把此抽样解读为完整数据已充分覆盖全部罕见手势。 + +## 2026-10-03 23:09 HKT: RGB teacher 梯度是否拖住 pose + +训练 `rgb_teacher_weight=0.05`,teacher 是较早的 RGB parent,实际蒸馏 3D joint/root-relative/vertices 等几何,不直接蒸馏 pose 参数。脚本 `.tmp/pose_delta_ablation_20261002/audit_pose_anchor.py --spread` 固定 N1-18K,在每源跨 1.2M 训练流分散的 10 个 tile 上,比较 `rotation_head.weight` 的 local-pose、GT 几何与 teacher 几何梯度;报告 `evaluations/pose_anchor_n1_18k_spread.json`。只读、单 tile 梯度,**尚未乘 DDP 每项 source scaling,也不是去 teacher 的训练消融**。 + +| Source | tile | anchor/local-pose 梯度范数比均值 | anchor/GT-geometry 范数比均值 | anchor vs local-pose cosine 均值 | anchor vs GT-geometry cosine 均值 | GT-geometry 反向 tile | +|---|---:|---:|---:|---:|---:|---:| +| H2O | 10 | 0.169 | 0.059 | -0.015 | -0.266 | 8/10 | +| ARCTIC | 10 | 0.126 | 0.057 | -0.004 | +0.130 | 4/10 | +| HOT3D | 10 | 0.258 | 0.065 | -0.016 | -0.260 | 8/10 | + +teacher 与 local-pose 梯度大致正交,不能把 mean-pose 收缩简单归咎于蒸馏。H2O/HOT3D 上 teacher 几何经常与 GT 几何反向,但量级约 GT 几何梯度的 6%;是否净伤害泛化,需要相同初始化、相同数据和步数的去 teacher 受控训练与 held-out 评估。第一次在 GPU 1 的六 tile 试验因该卡新增其它进程而 OOM,仅审计进程退出;随后改到空闲 GPU 5 成功,N0/N1 正式训练未中断。 + +## 2026-10-03 23:20 HKT: 用户确定下一阶段先暂停 + +用户要求 N0/N1 **各自到 20K 就停**,之后先诊断;新训练计划须去掉 teacher、仅保留 DINO 官方预训练并从头初始化其它权重、让局部 pose 学固定 mean rotation 的 delta,并重新核实训练 GT 的 camera-space 与旋转正交性。明确收到“可以训练”之前不运行下一阶段。G1 N0 transient systemd unit 的命令含 `--updates 20000` 且没有 `Restart`;G2 N1 是一次性的 `nohup torchrun --updates 20000`。用户还提出清理无用权重;当前 20K 尚未选点、历史 `.pt` 所有权复杂且磁盘剩余充足,所以先盘点路径/用途/备份和候选删除清单,未做不明确的不可恢复删除。方案见 `FOUNDATION_HAND_FROM_SCRATCH_MEAN_POSE_REVIEW_20261003.md`。 + +同口径 HOT3D N1-18K held-out 的 MANO 因子 oracle 已完成;`direct` 的 3,573 有效手帧、2,534 个 hard,以及四指标均与原固定 panel 报告逐项相同。oracle 只替换指定因子为 native GT、保留其余预测,结果仅为诊断上界,不能作为模型成绩: + +| HOT3D hard 因子替换 | ΔAbs mm | ΔRoot mm | ΔMPVPE mm | Δ2D px | +|---|---:|---:|---:|---:| +| 15 个 local MANO rotations | -0.643 | -2.711 | -0.533 | -0.998 | +| root/global orientation | -0.798 | -12.398 | -0.685 | -0.536 | +| root translation | -29.613 | -0.004 | -30.401 | -1.905 | +| 全部 rotations + translation,仍保留预测 shape | -48.457 | -18.848 | -48.219 | -11.001 | + +主报告在 `evaluations/oracle_pose_hot3d_n1_18k.json`。逐手原始行第一次因 NaN 严格 JSON 序列化失败,未落盘;修正了后续 evaluator 的有限值转换,但没有改动已完成主报告。局部 pose 的上界对 root-relative/2D 有意义,Abs/mesh 大部分是整体 translation 问题,root orientation 也是 root-relative 的大头;因此 mean-pose delta 值得做,但单独改变其参数化不可能负责四指标所有改进。最终 20K 仍须重测。 + +三源 train-GT 独立数值抽样已完成,见 `evaluations/training_gt_contract_10_tiles_per_source.json`。每源 10 个跨训练流 tile,共 9,093 个有效 3D joints,非正 Z 为 0;FP32 GT 轴角转矩阵的平均正交误差均约 `1.1–1.2e-7`。wrist 与 joint root 最大差 H2O/HOT3D 为 0、ARCTIC 仅 `0.000150 mm`;3D 用当前 K 投到原始 2D 标签的平均误差为 H2O `0.345 px`、ARCTIC `0.271 px`、HOT3D `0 px`。结合 H2O 直接 camera joints、ARCTIC/HOT3D 显式 world→camera 转换及逐 batch MANO 几何一致性门,目前没有发现 hand-GT 坐标混用。仍应表述准确:缓存 pose 是 axis-angle,root orientation 属 camera frame,15 个 local rotations 属关节局部;严格正交问题发生在**训练 autocast 内临时计算的 GT 6D**,不是缓存轴角本身。 + +## 2026-10-03 23:40 HKT: 20K 停训和确认范围的权重清理 + +G2 N1 已按一次性 `--updates 20000` 完成,最终 checkpoint 为 `/home/wuyifan/u0_normalized6d_20261002/runs/N1_formal/update_0020000.pt`,日志末行 `update=20000`、`consumed_clips=1,200,000`、三源暴露 H2O/ARCTIC/HOT3D=`420,000/300,000/480,000`、`grad_norm=11.42`、`clipped=false`;未发现训练进程续跑。本地只读评估副本 `.tmp/pose_delta_ablation_20261002/n1_update_0020000.pt` 与 G2 原件 SHA256 同为 `a47c1f15...394396`,checkpoint 元数据证实 `mode=N1`、`update=20000`、`complete_backbone=true` 且 parent/normalization hash 符合实验配置。G1 N0 仍按命令自然跑向 20K,没有配置自动 restart;不启动下一轮训练。 + +用户把清理范围限定为当前实验的无用副本。已逐一核对并只删除:`.tmp/u0_normalized6d_20261002/runs/N0_smoke_fixed/update_0000002.pt`(元数据 `smoke=true, update=2`)、`.tmp/pose_delta_ablation_20261002/n1_update_0002000.pt`、`.tmp/pose_delta_ablation_20261002/n1_update_0004000.pt`。后两者删除前与 G2 原件 SHA256 分别一致,G2 原件仍保留;本地不可撤销删除约释放 1.8 GB。其它 N0/N1 中途权重、唯一权重及全部历史 Foundation Hand checkpoint 均未删除。 + +N1-20K 已在三源固定 native-GT development panel 完成纯 RGB、T=8 的四项评估,报告为 `.tmp/pose_delta_ablation_20261002/evaluations/pose_hard_{h2o,arctic,hot3d}_n1_20k.json`。N1 减 U0 parent 的配对误差(负数改善): + +| Source / GT 桶 | 有效手 | ΔAbs mm | ΔRoot mm | ΔMPVPE mm | Δ2D px | Δlocal pose ° | +|---|---:|---:|---:|---:|---:|---:| +| H2O all | 1536 | +0.388 | +0.019 | +0.378 | +0.016 | +0.145 | +| H2O hard | 488 | +0.433 | +0.020 | +0.426 | +0.174 | +0.125 | +| ARCTIC all | 1568 | +0.194 | -0.243 | +0.200 | +0.378 | +0.082 | +| ARCTIC hard | 533 | -0.030 | -0.317 | -0.030 | +0.371 | -0.032 | +| HOT3D all | 3573 | -0.208 | +0.020 | -0.196 | -0.185 | -0.054 | +| HOT3D hard | 2534 | -0.264 | +0.054 | -0.249 | -0.273 | -0.210 | + +N1-20K 的改善只在部分 source/指标成立;尤其 H2O hard 四项均变差,未达到目标。用户随后决定不等 G1 N0-20K,因此 hard reweight 的同一步数增量改用已完成的 N0/N1 18K 对照(见下节)。N1 是 U0 续训且含 teacher,不能据此否定待批准的无 teacher、从 DINO 预训练视觉编码器以外重头初始化、mean-pose delta 训练。 + +## 2026-10-03 23:52 HKT: 用户决定不等 N0 20K,改用已保存 18K 同步数对照 + +用户明确说“没事,不需要到20k,直接测吧”。核对 G1 服务为 `MainPID=1572060`、`Restart=no`、`--updates 20000 --mode N0` 后主动执行 `systemctl --user stop u0-n0-normalized6d-20261002.service`。最后日志 `update=19247`、`consumed_clips=1,154,820`,主 PID 已退出;服务记录 `signal 15` / `Result: exit-code` 是人为 stop 的预期记录。**最后完整 checkpoint 是 18K**(605 MB),19,247 step 的模型状态没有保存,不能声称已评估。没有启动其它训练。 + +固定 development panel 的 `pose_hard_{h2o,arctic,hot3d}_12k18k.json` 已覆盖 N0/N1 **同为 18K** 的纯 RGB、T=8、source-native GT 评估。报告内登记的 N0/N1 18K SHA256 为 `3d176e8949c5738c0ae19690e528968071734f439b7a5efb47d27db954a1feea` / `07ffd4d5463d64e5762f9dfa268d6539bff28c4d4dcf078c85cd7d7f3b17af2b`,现存文件重新计算完全一致;因此复用这份已完成评估,无需重复跑 GPU。负数为误差改善: + +| Source / GT 桶 | N0-18K vs U0 parent:Abs / Root / MPVPE / 2D | N1-18K vs N0-18K:Abs / Root / MPVPE / 2D | N1 vs N0 local pose / 指尖 | +|---|---|---|---| +| H2O hard (488 手) | +0.476 / +0.017 / +0.471 mm / +0.264 px | -0.023 / -0.019 / -0.021 mm / -0.060 px | -0.029° / -0.064 mm | +| ARCTIC hard (533 手) | +0.251 / -0.277 / +0.250 mm / +0.468 px | -0.085 / -0.071 / -0.083 mm / -0.034 px | +0.015° / -0.183 mm | +| HOT3D hard (2534 手) | -0.431 / +0.093 / -0.405 mm / -0.341 px | -0.138 / -0.059 / -0.138 mm / -0.052 px | -0.176° / -0.128 mm | + +N1 reweight 的相对收益量级小且不跨源一致。HOT3D normal 手 N1-vs-N0 的 local pose 反而 `+0.276°`、指尖 `+0.256 mm`;极端弯曲的有符号低估在 HOT3D hard 从 parent `-16.778°` 到 N0 `-16.337°`、N1 `-15.204°`,仍显著偏平均。H2O hard 的四指标相对 parent 到 18K 全变差,N1-20K 也未扭转;目前不能说解决了目标。下一步是等待用户检查并批准或修改无 teacher、从头初始化、mean-pose delta 的受控计划,**现在不训练**。 + +## 2026-10-06 21:30 HKT: ViTPose-L + MoT 从头训练合同获批准,预检进行中 + +用户已批准新实验合同:只继承 ViTPose-L COCO 视觉主干权重(完整 SHA256 `82dea141d75805068ce80705b9a3965af9cbc62a1844c46d88238012a2c2097f`),丢弃 COCO keypoint head;512 维投影、RGB/HAND MoT、时序 decoder、MANO heads 随机初始化。纯 RGB、全画幅、双向 T=8;K 仅进入 MANO 重投影监督;无 teacher、无 S4/A7/U0 权重继承。三源训练配比 H2O/ARCTIC/HOT3D=21/15/24,保持 canonical train-only 标签、官方 MANO pkl local mean 的右乘 delta、FP32 正交化后归一化 6D L1、仅重投影 2D loss。三档源条件分辨率合同见 `experiments/vitpose_mot_from_scratch/config.json`。 + +G1 0、1 号卡空闲,2–5 号卡被现有其它任务使用,未停止或占用。新模型入口与混合分辨率读数已经写入 EgoNet;三源各一条 T8 tile 在三档分辨率上的 RGB/K/2D 同步检查通过。3D GT 通过 K 重投影到 2D GT 的均值:H2O `0.182/0.130/0.104 px`,ARCTIC `0.272/0.195/0.194 px`,HOT3D 近 `0 px`(HOT3D 2D 很可能本身是投影标签,因此不是独立 2D 精度证据)。这些是抽样 smoke,不替代全量画幅/有效手像素审计。 + +G1 GPU0 真样本最大档 512x896、T=8 前反传预检通过。视觉冻结阶段 loss `3.711`、梯度裁剪前范数 `106.3`、峰值分配 `1.82 GiB`;解冻最后两块和 final norm 后,同样样本 peak `2.17 GiB`、可训练参数 `48.38M`(其中主干 `25.19M`),loss 和梯度均有限;GT/pred rotation 正交误差分别不超过 `3.58e-7`/`2.39e-7`,非正深度关节 0。两个单样本用时约 1 秒,**不能据此声称正式 batch 60 的吞吐或 120K 完成时间**。下一步两卡实际读取/累积 pilot、断点恢复和 held-out evaluator 门;六卡正式训练等空卡且所有门通过后启动。本节覆盖此前“等待批准,现在不训练”的历史状态,但当前尚未正式开训。 + +## 2026-10-07 00:25 HKT: 六卡 pilot、完整 batch smoke 与恢复 + +G1 0/1 两卡和六卡短 pilot 均跑过混合分辨率真实数据。两卡每卡 4 clips 的 last-2 pilot 为 `1.506 clips/s`(总量),六卡同口径为 `5.629 clips/s`;六卡 batch 60 的乐观计算下界约 `10.7 秒/update`,120K 即至少约 15 天,完整 batch 的 VRS 读取可能更慢。六卡在 pilot 后再次被其它任务占用,未抢占。 + +组合测试曾发现历史数据模块修改 `sys.path`,会让 Foundation Hand 解析到旧代码;新实验入口现在显式绑定 EgoNet `src`,合同/运行时测试 9 项通过。训练入口第一次 smoke 在检查磁盘时因目标父目录未建而在 step 0 前退出,修复并重跑后 step-1 checkpoint 成功写入。两卡、**每步 global batch 60** 的 step-1 与从完整 checkpoint 恢复的 step-2 均通过:源累计暴露 `42/30/48`(精确为两倍 21/15/24),rank0 loss `4.686 -> 4.641`、裁剪前梯度范数 `97.5 -> 106.9`、直接 2D loss 始终 `0`、非正重投影深度 `0`。两个完整 smoke checkpoint 均标记 `smoke=true`、包含 backbone/optimizer/RNG,不能混作正式训练权重。H2O held-out 2-clip 评估已成功验证评估输入/输出;随机初始化后两步的四指标约 `233.08/112.86/231.47 mm/169.52 px`,**只用于接口 smoke,不作性能结论**。 + +正式 controller 已编写为六卡连续空闲门、5K/10K/20K 后每 20K 分段训练、三源 source-native held-out 四指标和 hard-pose 报告,任何阶段失败停止并保留日志;尚未启动,先补 ARCTIC/HOT3D 评估 smoke 与画幅检查。完成后将启动等待空卡的 controller;是否延长 120K 必须看真实验证曲线,不预设收敛。 + +HOT3D 官方去畸变画幅抽样与校准一致:Aria `1408x1408`,Quest3 `1024x1280`。抽样 Aria 手在 `512x896` 和 `512x512` 的 2D bbox 中位数都约 `36x49 px`,前者只是增加两侧 padding/注意力 token,不增加有效手像素;Quest3 样本在两档分别约 `85x67` 与 `68x54 px`。因此继续遵守获批的源条件初始分辨率配比,但 Aria 宽画幅的计算效率应在首批吞吐/验证结果后重新考虑。画幅审计报告为 `wuyifan/artifacts/vitpose_mot_from_scratch_20261006/hot3d_resolution_audit.json`。控制器正式训练前会用完整 smoke checkpoint 自动对三源各跑 2 clips 的评估接口 smoke,全部成功且六卡连续空闲才启动;这些少量 smoke 指标绝不作性能比较。 + +00:53 HKT 已在 G1 的 `tmux` 会话 `egonet_vitpose_mot_20261007` 启动等待控制器,状态文件为 `wuyifan/artifacts/vitpose_mot_from_scratch_20261006/formal_v1/controller_status.json`。初始状态 `waiting_for_idle_gpus/preflight_eval_H2O`,GPU0 正被别的任务使用(约 1.16 GiB、72% 利用率);控制器尚未占卡,也没有正式训练更新。正式首段 5K 的乐观用时约 15 小时,完整 120K 至少约 15 天,HOT3D IO 波动会把真实用时进一步拉长;这些都不是完成时间承诺。三源正式评估会由控制器分段完成并附加本文件,controller 失败则停在原节点保留日志,不擅自放宽门槛。 + +## 2026-10-07 00:57 HKT: ViTPose 位置编码前向修正,旧 smoke 失效 + +再次对照官方 ViTPose 实现,发现每个 patch 除空间位置向量外,还应加 `pos_embed[:, :1]` 的全局位置偏置;初版新编码器遗漏了这一项。其影响是视觉 feature 的前向口径不完全等于 COCO 预训练模型,即使 checkpoint 严格加载且 loss/梯度正常也不能接受。已在新 MoT 编码器与共用的 ViTPose probe 前向同时修复,新增单测确认该偏置确实影响每个 patch;相关 11 项测试通过。旧 `smoke2/update_000000{1,2}.pt` 原样保留用于问题追踪,但**不得用于正式初始化、评估结论或断点恢复**;之前的两步数值、吞吐仍只能代表修复前程序的机制 smoke。 + +旧控制器在等空卡、尚未占 GPU/启动正式训练时主动停止。新控制器改为先在 `smoke_posfix2/` 重新完成 1→2 步完整 batch60 训练和恢复,再做三源 2-clip 评估 smoke,全部通过且六卡连续空闲后才启动正式 run。当前仍无正式训练更新;后续 HK 时间线以修复后的 checkpoint 为准。 + +00:57 HKT 新控制器已重启于同名 `tmux` 会话;状态为 `waiting_for_idle_gpus/postfix_smoke_1`,GPU0/1 当前也被其它任务占用。它只做定时查询,不占 GPU;首个修复后 smoke 必须达到 0/1 两卡连续三次空闲采样才会启动。 + +评估报告进一步加入每个 local joint 的旋转角误差,以及预测/GT local 6D 方差比;比值显著低于 1 可提示预测分布向 mean pose 收缩。hard-pose 与 normal 分别统计,同步观察四指标、弯曲角有符号低估和 normal no-harm。该诊断只改 evaluator/controller,不改已冻结的训练输入、loss、schedule 或 checkpoint 合同;相关 12 项测试通过。控制器等待时再次短暂停止以载入新报告代码,随后重启。 + +训练 checkpoint 的 provenance 进一步锁定基础 loss `config.json` 与本仓库的 encoder/decoder/MANO/rotation/schema/三源读数器实现,共 23 项代码及资源哈希;恢复时要求完全一致,防止长跑中监督或几何实现被静默修改。合同核验通过,12 项相关测试仍通过。01:02 HKT 后台控制器重新运行,状态继续为 `waiting_for_idle_gpus/postfix_smoke_1`;修复后训练更新仍为 0。 + +## 2026-10-07 20:14 HKT: ViTPose-L + MoT 5,000 更新评估 + +训练为视觉主干预训练 + 其它部分从头,纯 RGB、T=8、三源 21/15/24;下表为固定 held-out source-native GT,未使用 teacher 或 parent checkpoint。 + +| Source / group | Abs MPJPE mm | Root MPJPE mm | MPVPE mm | 2D px | local pose deg | bend bias deg | pred/GT 6D var | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O / all | 40.813 | 24.037 | 40.362 | 24.780 | 12.934 | -2.572 | 1.068 | +| H2O / hard_pose | 57.920 | 31.673 | 56.961 | 30.794 | 15.363 | -7.721 | 1.008 | +| ARCTIC / all | 53.958 | 31.501 | 53.453 | 31.809 | 27.678 | -8.097 | 0.382 | +| ARCTIC / hard_pose | 59.365 | 34.234 | 58.712 | 34.301 | 32.553 | -13.341 | 0.335 | +| HOT3D / all | 103.671 | 39.462 | 102.728 | 40.129 | 17.424 | -5.195 | 0.367 | +| HOT3D / hard_pose | 102.304 | 38.647 | 101.405 | 37.120 | 17.813 | -7.487 | 0.344 | + +完整报告与逐手记录见本实验 `evaluations/`;单节点结果不等于收敛结论,继续看后续节点的四指标、hard pose 与 normal no-harm。 + +## 2026-10-07 23:51 HKT: ViTPose-L + MoT 10,000 更新评估 + +训练为视觉主干预训练 + 其它部分从头,纯 RGB、T=8、三源 21/15/24;下表为固定 held-out source-native GT,未使用 teacher 或 parent checkpoint。 + +| Source / group | Abs MPJPE mm | Root MPJPE mm | MPVPE mm | 2D px | local pose deg | bend bias deg | pred/GT 6D var | +|---|---:|---:|---:|---:|---:|---:|---:| +| H2O / all | 39.696 | 19.082 | 39.432 | 25.164 | 11.558 | -1.145 | 1.167 | +| H2O / hard_pose | 48.204 | 22.917 | 47.769 | 26.228 | 12.702 | -5.039 | 1.167 | +| ARCTIC / all | 55.795 | 29.609 | 55.160 | 33.375 | 26.837 | -6.383 | 0.480 | +| ARCTIC / hard_pose | 59.083 | 32.017 | 58.330 | 36.557 | 31.022 | -10.834 | 0.430 | +| HOT3D / all | 89.330 | 37.544 | 88.545 | 35.924 | 17.641 | -6.749 | 0.344 | +| HOT3D / hard_pose | 86.448 | 36.817 | 85.686 | 33.210 | 18.445 | -8.885 | 0.328 | + +完整报告与逐手记录见本实验 `evaluations/`;单节点结果不等于收敛结论,继续看后续节点的四指标、hard pose 与 normal no-harm。 diff --git a/home/wuyifan/EgoNet_train_20261008/docs/MANO_RGB_G2_THROUGHPUT_20261006.md b/home/wuyifan/EgoNet_train_20261008/docs/MANO_RGB_G2_THROUGHPUT_20261006.md new file mode 100644 index 0000000000000000000000000000000000000000..fc8a645ecc754d8688bd8c1487d200befe4117b8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/MANO_RGB_G2_THROUGHPUT_20261006.md @@ -0,0 +1,80 @@ +# G2 pure-RGB MANO throughput probe (2026-10-06) + +This is a throwaway two-GPU throughput probe, **not** an approved B0/B1 training run or a convergence test. It used G2 physical GPUs 2 and 5 while 0/1/3/4 were occupied. No checkpoint was saved. The current B0/B1 contract remains `training_approved=false`; learning-rate schedule, DINO unfreeze point, and maximum updates are not frozen. + +## Workload and measured results + +- Real canonical train-only H2O/ARCTIC/HOT3D T=8 clips; RGB input at 512x896. K is used for reprojection supervision but not supplied to the model; depth is not supplied. +- Official DINOv3 initialization, fresh decoder and heads, mean-pose delta, all 12 registered supervised terms, BF16, backward/AdamW/gradient clipping; no teacher. Each GPU processes 10 one-clip microbatches per optimizer update, matching the planned six-GPU global batch of 60 clips. +- Two warmup updates precede each timed window. GPU utilization was sampled via `nvidia-smi` at approximately 1 Hz; it is a coarse, burst-sensitive measure, not SM profiling. + +| Arm / DINO | Workers per rank | Timed updates | s/update (slower rank mean) | Two-GPU clips/s | Mean GPU utilization 2/5 | Peak PyTorch allocated/GPU | +|---|---:|---:|---:|---:|---:|---:| +| B0 / frozen | 2 | 10 | 2.568 | 7.79 | 34.5% / 29.4% | 1116 MiB | +| B1 / frozen | 2 | 10 | 2.620 | 7.63 | 30.1% / 32.1% | 1296 MiB | +| B0 / frozen | 4 | 10 | 1.788 | 11.18 | 40.1% / 44.2% | 1116 MiB | +| B1 / frozen | 4 | 10 | 1.845 | 10.84 | 55.5% / 40.8% | 1298 MiB | +| B0 / last two DINO blocks trainable | 4 | 10 | 1.932 | 10.35 | 52.2% / 42.2% | 2298 MiB | +| B0 / frozen | 4 | 50 | 2.032 | 9.84 | 38.4% / 39.0% | 1115 MiB | + +In the 50-update B0 run, mean data wait was 0.87 s/rank versus 1.17 s/rank for compute, and step-time P90 was 3.03 s. Opening additional HOT3D VRS recordings caused several roughly 3-second steps. With only two workers, data wait was about 1.47 s/rank in the short runs. Four workers helped substantially but did not fill the GPUs. G2 also had other active jobs and a load average exceeding its 64 logical CPUs during the probe. + +## Conditional six-GPU estimate for microbatch 1 + +The six-GPU step will still contain 10 clips **per GPU**, so step time does not divide by three; ideal clip throughput triples only if CPU/SSD/NCCL keep up. The two-GPU 50-step 2.03 s/update is an optimistic lower anchor. As a separate, non-comparable historical anchor, the older six-GPU U0 RGB continuation took about 26 hours for 20K updates, or 4.68 s/update; it used two workers/rank and a different teacher-containing recipe. For **microbatch 1 only**, use **2.5-5.0 s/update** as a provisional planning range, not a measured prediction. The DINO last-two phase and checkpoint/evaluation downtime can increase it. The larger-microbatch results below supersede this as the preferred implementation direction, but do not yet supply a measured six-GPU rate. + +| Per arm, six GPUs | 2.5 s/update | 5.0 s/update | +|---|---:|---:| +| 20K updates | 14 h | 28 h | +| 50K updates | 1.45 d | 2.89 d | +| 100K updates | 2.89 d | 5.79 d | +| 400K updates | 11.6 d | 23.1 d | + +Sequential matched B0 and B1 arms take roughly twice the per-arm duration, before validation/checkpoints. **None of these step counts defines convergence.** The registered three-source inventory has 6,406 H2O, 22,750 ARCTIC, and 143,657 HOT3D T8 tiles; the planned 21:15:24 source quota gives the first HOT3D pass at roughly 6K updates, but multiple passes do not establish an optimization plateau. Use held-out four-metric and hard-pose curves at fixed checkpoints to decide when to stop. A 400K-update run with global batch 60 would process 24 million clips and should not be presumed necessary. + +Raw reports are under `wuyifan/artifacts/egonet_mano_throughput_20261006/`. Probe implementation: `experiments/from_scratch_mean_pose/throughput_probe.py`. No six-GPU timing was taken because GPUs 0/1/3/4 were occupied by other jobs. + +## Microbatch follow-up + +The old S9L10 reference config also has `data.batch_size: 1`. Its >10 GB observed device memory cannot be attributed to a larger clip batch: it enables depth, rays, and presence and trains DINO last two blocks. Its eight loader workers and prebuilt cache manifests affect data throughput, not GPU allocation. The current B0/B1 reader instead opens source recordings, including HOT3D VRS files. + +The follow-up held **10 clips per GPU per optimizer update** and four workers/rank fixed. The probe batches model forwards but evaluates the loss separately per clip before summing and backward, preserving the original masked-loss denominators. Directly calling `FromScratchLoss` on a mixed-source batch would change relative weighting when valid annotation counts differ. The standard collator also rejects mixed-source optional keys such as `photometric_aug_params`; this probe filters to the verified model/loss/geometry fields. Formal training needs an audited mixed-source collator before adopting larger batches. + +| Arm / DINO | Clips per forward | Timed updates | s/update | Two-GPU clips/s | Mean GPU utilization 2/5 | Device memory 2/5 (MiB) | +|---|---:|---:|---:|---:|---:|---:| +| B0 / frozen | 1 | 10 | 1.788 | 11.18 | 40% / 44% | 2455 / 2027 | +| B0 / frozen | 2 | 10 | 1.280 | 15.62 | 83% / 59% | 3001 / 2619 | +| B0 / frozen | 5 | 10 | 1.050 | 19.04 | 58% / 71% | 4945 / 4563 | +| B0 / frozen | 10 | 10 | 0.919 | 21.76 | 78% / 83% | 8491 / 8107 | +| B0 / frozen | 1 | 50 | 2.032 | 9.84 | 38% / 39% | 2413 / 2029 | +| B0 / frozen | 10 | 50 | 1.238 | 16.16 | 59% / 66% | 8493 / 8107 | +| B1 / frozen | 10 | 10 | 0.948 | 21.09 | 73% / 79% | 8615 / 8231 | +| B0 / DINO last two | 10 | 10 | 0.933 | 21.44 | 81% / 94% | 17757 / 17375 | +| B1 / DINO last two | 10 | 10 | 0.996 | 20.08 | 91% / 97% | 18857 / 18473 | + +The matched 50-update comparison gives a **1.64x throughput gain** from microbatch 1 to 10, not the nearly 2x gain suggested by the short warm-cache window. With microbatch 10, B0's 50-update mean data wait was about 0.49 s/rank and compute about 0.85 s/rank (the rank-wise maxima are not additive); recording switches still produce multi-second I/O stalls. DINO-last-two B1 at microbatch 10 leaves about 5700 MiB of physical VRAM headroom on a 24564 MiB GPU. This is enough for the probe, not proof of a full six-GPU run with checkpointing and long-term memory stability. The old six-GPU ETA table above must **not** be used as a measured ETA for microbatch 10; a six-GPU pilot is still needed. + +## 数据侧补充对照:worker 与预取 + +保持 B0、纯 RGB、T=8、每卡每步 10 clips、microbatch 10、同一采样种子和 50 个计时步。两卡实验固定物理卡 2/5;四卡实验为 2/3/4/5,读取同一训练源但因 world size 变化,具体 clip 序列并非逐项相同。表中的等待为各 rank 平均等待的最大值,吞吐由最慢 rank 的平均步时计算。 + +| GPU | worker/卡 | OpenCV 线程/worker | 预取深度 | s/步 | 数据等待 s/步 | clips/s | 步时 P90 | +|---:|---:|---:|---:|---:|---:|---:|---:| +| 2 | 4 | 默认(该环境报告 64) | 2 | 1.238 | 0.491 | 16.16 | 2.981 | +| 2 | 4 | 1 | 2 | 1.240 | 0.440 | 16.13 | 3.259 | +| 2 | 6 | 1 | 2 | 0.905 | 0.156 | 22.10 | 1.419 | +| 2 | 6 | 1 | 4 | 0.906 | 0.164 | 22.08 | 1.593 | +| 2 | 8 | 1 | 2 | **0.761** | **0.032** | **26.28** | **0.937** | +| 4 | 1 | 1 | 2 | 4.690 | 3.495 | 8.53 | 5.642 | +| 4 | 2 | 1 | 2 | 2.567 | 1.796 | 15.58 | 5.308 | +| 4 | 4 | 1 | 2 | **1.656** | 0.774 | **24.16** | 4.966 | +| 4 | 4 (VRS LRU 8) | 1 | 2 | 1.625 | 0.814 | 24.62 | 4.875 | +| 4 | 8 | 1 | 2 | 2.031 | 0.861 | 19.69 | 5.148 | + +两卡最佳设置相对原四 worker 基线提速约 **1.63 倍**,数据等待从 0.49 秒降至 0.03 秒/步;单独限制 OpenCV 线程或加深预取没有可测收益。四卡仅 1--2 worker/卡时供数明显不足;32 个 worker 时,`vmstat` 观测到 CPU 近乎满载、极高进程排队而 I/O wait 约为零,且 GPU 0/1 还有其它任务;所以目前不能将两卡最佳配置线性推广到六卡。四卡四 worker 在已测点中最快,但仍有约 0.77 秒/步的数据等待。HOT3D 运行日志频繁出现 VRS recording 打开;这些观测指向 CPU 解码、provider 初始化及多 worker 争用,但尚未分项计时,不能将全部等待归因于 VRS 或物理磁盘。 + +HOT3D reader 已经在**每个 worker 进程内部**用 LRU 缓存 2 个已打开的 provider。2026-10-06 在 G2 统计:本次 HOT3D T8 训练 manifest 引用了 230 条 recording,其原始 `recording.vrs` 文件合计 349.0 GiB;全盘 HOT3D 目录有 424 个 `recording.vrs`,合计约 666 GiB,连同其它文件目录占用约 794 GiB。增加 provider LRU 容量不会复制这些 VRS 文件,但会按 worker 数增加内存与打开句柄。若另行建立解码后 RGB 磁盘缓存,则是不同方案,需要先按唯一帧数、编码格式和试点吞吐测算,不能把 349 GiB 当作其大小。 + +补测 provider RSS:一个只读 HOT3D reader 进程初始化后约 995 MiB;持有 2 个不同 provider 后约 1,137 MiB,8 个后约 1,433 MiB。前八条 recording 的额外 RSS 约 438 MiB,不能直接线性外推 230 条;第二次访问已在 LRU 中的八条几乎瞬时。四卡四 worker 的 LRU 2→8 吞吐仅从 24.16 到 24.62 clips/s(约 1.9%,50 步的单次短测,可能是噪声),等待未下降,因此不据此修改正式训练配置。应先统计真实重访率和分源读取耗时。 + +**当前结论:**两卡诊断可用 8 worker/卡、OpenCV 1 线程、prefetch 2;四卡共机诊断以 4 worker/卡作为已测较优点。正式六卡训练不能照抄其中任一配置,应先做六卡短测,并记录同机任务的 CPU 占用。下一项有针对性的试点是给 H2O/ARCTIC/HOT3D 分源计时,再只对主要耗时路径测试持久化、可校验的 RGB/几何缓存;纯 RGB 时读取但未用于模型/损失的 H2O depth 也值得单独消融。这些优化尚未纳入训练合同。原始 JSON 位于 `wuyifan/artifacts/egonet_mano_throughput_20261006/`;测试没有保存权重,也没有启动正式训练。 diff --git a/home/wuyifan/EgoNet_train_20261008/docs/MODEL_ARCHITECTURE.html b/home/wuyifan/EgoNet_train_20261008/docs/MODEL_ARCHITECTURE.html new file mode 100644 index 0000000000000000000000000000000000000000..02b47ce17363c3d4594a17158e58caf401fb9722 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/MODEL_ARCHITECTURE.html @@ -0,0 +1,2204 @@ + + + + + + + Foundation Hand 模型结构图 + + + +
+
+ +
+
Foundation Hand / Model Map
+
Model map · Mask interface update · 2026-09-17
+
+
+
+ +
+ + +
+ +
+
+ +
+
+
+

Accepted backbone + optional Camera / Mask Adapters

+

Foundation Hand 模型结构

+

+ 冻结 DINOv3 的 RGB-D-K 双手视频重建模型。逐帧提取 dense patch feature, + 只让左右手语义 Query 在时间维交互,最后回归 MANO 与 camera-space 几何。 + Accepted full 1e-6 主干可保持原样,也可接入 relative-camera-motion World Adapter;历史 v2 在 RGB token 前做加法, + v3 原型在 frozen decoder 后学习 reference-frame root residual。新增 + SAM3 / 统一 MaskPatchAdapter 在 RGB patch tokens 上注入空间条件; + 接口与 loss 已实现,正式数据训练待启动。Camera 实验结果与开发状态见 + World Adapter 实验进度。 +

+
+
+
+ 输入 + T=8 · 512×896 +
+
+ 主干 + DINOv3 ViT-B/16 +
+
+ Decoder + 3× Alternating +
+
+ 坐标 + Camera · meter +
+
+
+ +
+
+
+

01 / End-to-end

+

端到端数据流

+
+

+ 主图包含可选 Camera / Mask 分支。Mask M0 只训练 adapter,其余 parent 全冻结;标注的 TRAINABLE 为原主干训练配置。 +

+
+ +
+ 冻结参数 + 可训练参数 + 可选 / mask 控制 + L=2:left / right + P=32×56=1,792 patches + D=512 +
+ +
+
+
+
+ 01 + Batch 输入 +
+
+
+
+

全帧 RGB

+ INPUT +
+ [B, 8, 3, 512, 896] +

ImageNet normalization;不使用外部 detector 或 hand crop。

+
+ +
+
+

Metric Depth + Valid

+ OPTIONAL +
+ [B, 8, 1, 512, 896] +

单位为米;availability 与 pixel-valid 分开控制。

+
+ +
+
+

相机内参 K

+ OPTIONAL +
+ [B, 8, 3, 3] +

同时服务 patch ray、depth geometry 与 reprojection。

+
+ +
+
+

Camera 外参合同

+ C1 / C2 +
+ T_world_camera [B,T,4,4] + 2× mask [B,T] +

统一为 camera-to-world;C0 不消费,C1/C2 由 valid 与 input-available 双重门控。

+
+ +
+
+

语义 Query + 帧有效性

+ TRAINABLE +
+ 2×512 + frame_valid [B,8] +

固定两个 slot:0=left,1=right;另有 side embedding。

+
+ +
+
+

Hand Mask · SAM3 / GT / Manual

+ OPTIONAL +
+ hand_mask [B,T,2,Hm,Wm] +

离线 provider → 统一 soft mask;0=left,1=right;与完整输入图像对齐。

+

valid / score / input_available [B,T,2];source 为字符串。分支结构与 loss ↓

+
+
+
+ + + +
+
+ 02 + 逐帧编码 +
+
+
+
+

DINOv3 ViT-B/16

+ FROZEN +
+ RGB → 1,792×768 +

使用 normalized dense patch tokens,不保留 CLS / register token。

+
+ +
+
+

RGB Projection

+ TRAINABLE +
+ Linear 768 → 512 +
+ +
+
+

Patch Ray Condition

+ TRAINABLE +
+ [x,y,1,avail] → MLP 4→512→512 +

由 K 在每个 patch 中心生成,作为 residual 加到 RGB token。

+
+ +
+
+

World Motion Adapter

+ OPTIONAL +
+ v1 C2: 10D · v2 C2: 9D →512 +

相邻外参生成每帧 condition,broadcast 加到 1,792 个 RGB patch token;v2 去掉 valid-as-feature 并 center identity。

+
+ +
+
+

Depth Geometry Encoder

+ TRAINABLE +
+ [X,Y,Z,logZ,valid] · 5→128→512 +

3×3 Conv + GELU + 16×16 stride-16 Conv;输出 1,792 个 token。

+
+ +
+
+

MaskPatchAdapter

+ ZERO-INIT +
+ 5 features / hand → Conv → gate → RGB + ΔM +

输出 [B,T,P,512] 空间条件;最后投影零初始化,缺失输入时残差为 0。

+

probability / edge / area / score / availability;保持 DINO 三通道 RGB 输入。

+
+
+
+ + + +
+
+ 03 + Factorized Query Decoder +
+ +
+
+ RGB + K + ΔM* + ΔT* + [B,8,P,512] +
+
+ Depth + [B,8,P,512] +
+
+ L/R Query + [B,8,2,512] +
+
+ +
+
+ Alternating Stage 1 + S1 → T1 +
+
+ Spatial + L/R self-attn → RGB cross-attn → depth cross-attn × 0.5 → FFN +
+
+ Temporal + 每只手沿 T 双向 self-attn → 每帧 L/R bimanual attn +
+
+ + +
+
+ Alternating Stage 2 + S2 → T2 +
+
+ Spatial + 重新读取同帧 RGB / depth patch tokens +
+
+ Temporal + 只传递 2×T 个 hand tokens,不做全视频 patch attention +
+
+ + +
+
+ Alternating Stage 3 + S3 → T3 +
+
+ Spatial + 输出最终每帧 left / right hand query +
+
+ Temporal + frame_valid mask;bidirectional;无 temporal position encoding +
+
+ + +
+ + + +
+
+ 04 + 预测 Heads +
+
+
+
+

2D Joint Head

+ TRAINABLE +
+ Linear 512→42 · sigmoid +

[B,8,2,21,2],归一化图像坐标。

+
+ +
+
+

MANO Rotation Head

+ TRAINABLE +
+ Linear 512→96 → 16×6D +

1 个 wrist global rotation + 15 个 local joint rotations。

+
+ +
+
+

Wrist Translation

+ TRAINABLE +
+ Linear 512→3 · direct XYZ +

x/y 直接回归;z=softplus(raw)+1e-4,camera-space 米。

+
+ +
+
+

Clip-level Shape

+ TRAINABLE +
+ time softmax pool → Linear 512→10 +

每只手整段 clip 共用一组 MANO beta。

+
+ +
+
+

Presence Head

+ LOSS=0 +
+ Linear 512→1 +

接口存在,但当前正式配置没有有效监督。

+
+
+
+ + + +
+
+ 05 + MANO 与输出 +
+
+
+
+

6D → Rotation Matrix

+ GEOMETRY +
+ [B,8,2,16,3,3] +
+ +
+
+

Left / Right MANO

+ FIXED LAYER +
+ pose + beta + wrist XYZ +

官方 manopth,use_pca=False;left shapedirs convention 修正。

+
+ +
+
+

Camera-space Joints

+ OUTPUT +
+ [B,8,2,21,3] · meter +
+ +
+
+

Camera-space Vertices

+ OUTPUT +
+ [B,8,2,778,3] · meter +
+ +
+
+

其他直接输出

+ OUTPUT +
+ 2D joints · pose · shape · wrist XYZ +
+
+
+
+ +
+ OPTIONAL MASK ADAPTER +

+ Mask → spatial token residual → 原 Decoder / Heads → camera-space MANO。 + 初始化时等于 parent;adapter-only 训练后,整段无 mask 在 eval 模式下严格回退冻结 parent。 + 时序与双手 attention 可跨帧、跨手传播 mask 信息,因此不保证单帧或单手独立回退。 +

+ 2026-09-17 · 接口 / LOSS 已实现 · M0 SMOKE 通过 +
+ +
+ OPTIONAL WORLD ADAPTER +

+ v2 在 decoder 前给每个 RGB patch 加同一 motion condition;v3 prototype 在 frozen decoder 后, + 把 coarse root 对齐到首帧相机坐标并学习 bounded translation / global-orientation residual。两者均 zero-init; + 缺失、非法、静止或不可辨识的单帧外参严格回退。MANO、joints 与 wrist translation 仍输出在当前 camera-space。 +

+ V2 EVALUATED · V3 R1-A STOPPED AT 500 +
+
+
+ +
+
+
+

01B / Optional spatial mask condition · 2026-09-17

+

SAM3 / MaskPatchAdapter 结构与监督

+
+

118 项测试通过;CPU smoke 3 步有几何梯度、无 mask 精确回退。正式数据训练与 benchmark 增益尚未验证。

+
+ +
+
01 · 外部 Provider →SAM3 / SAM2 / manual / GT render
离线生成与左右手匹配;trainer 只接统一字段。
+
02 · Mask Contract →[B,T,2,Hm,Wm]
0–1 概率 + valid + score + input_available;cache / sidecar 同步几何增广。
+
03 · Patch Features →前景 / 边界下采样到 patch grid;拼 area、score、availability。每手 5 通道,shared Conv 3×3:5→64 + GELU。
+
04 · Gate + Projection →每手 pooled feature → sigmoid gate × score × available;L/R concat 128 通道 → zero-init Conv 1×1:128→512。
+
05 · Spatial Residual →RGB tokens += ΔM
投影后再用 availability 门控;整帧缺失时连 bias 一起归零。输出 [B,T,P,512]。
+
06 · Decoder → MANO原 temporal / bimanual decoder → pose、shape、translation → joints / vertices;继续使用现有主监督。
+
+ +

辅助分支:每手 pooled feature 另外输出 helpfulness logit 与 quality prediction;gate entropy 使用 gate logit。 + 质量标签只用于监督。输入 dropout 只关闭 availability,保留 mask target 和 valid;无 mask 的旧 cache 自动补零。 + 当前实现只接收概率,provider logits 需先 sigmoid。M0 冻结完整 parent;联合 decoder/head 训练属于后续阶段。

+ +
+
主监督 · M0MANO pose / shape、camera joints / vertices、translation、2D / reprojection、双手与时序监督;继承 parent 权重。
+
配对前向 · M1相同 RGB / Depth / K / Camera,分别使用正确、缺失、shuffled mask。对照分支停止梯度;no-mask student 的 parent distill 保留梯度。
+
几何误差 E每帧每手计算:Abs MPJPE / 20 mm + relative MPJPE / 15 mm + MPVPE / 20 mm + projected 2D / 10 px;仅有效标注参与。
+
弱投影监督MANO joints + K → 图像位置 → 双线性采样 hand_mask;约束投影关节落在前景内。
+
完整轮廓监督MANO mesh → 外接可微 renderer → silhouette logits → BCE / Dice / boundary / exclusion。Loss 已实现,renderer 尚需接入。
+
权重与阶段12 项默认均为 0。M0 保持关闭;M1 配置开启 parent distill 0.1、no-harm 0.1、shuffled margin 0.05。
+
+ +
+ + + + + + + + + + + + + + + + +
Loss item实现定义依赖 / 激活阶段
mask_missing_parent_distillNo-mask student 对齐冻结 parent:rotation / shape / normalized 2D L1 + translation L1 / 20 mm。M1:0.1;需要独立 frozen parent。
mask_dropout_consistencyMask-on 的 15 个局部关节旋转矩阵对齐 detached no-mask 输出。默认 0;仅有效 mask 输入。
mask_no_harmmean max(E_on − stopgrad(E_off) − margin, 0)。默认 margin=0。M1:0.1;MANO 几何 + 有效 GT。
mask_shuffled_marginmean max(E_on − stopgrad(E_shuffled) + 0.05, 0)。排除相同或不可用 shuffled mask。M1:0.05;跨 batch 打乱,保持 L/R。
mask_foreground_coveragemean(1 − M(projected joint));score 加权。排除空 mask、无效 K 与相机后的关节。默认 0;弱前景约束,需 joints + K。
mask_background_exclusion预测 silhouette 落在 mask 外的质量 / 全部预测 silhouette 质量;score 加权。默认 0;需要可微 silhouette。
mask_silhouette_bceSilhouette logits 与 soft mask 的逐像素 BCE;score 加权。默认 0;需要可微 silhouette。
mask_silhouette_diceSoft Dice loss;epsilon=1e-6,score 加权。默认 0;需要可微 silhouette。
mask_boundary_dt预测软边界到 target 边界的距离;按图像对角线和预测边界质量归一化,排除空 target 边界。默认 0;需要可微 silhouette。
mask_confidence_calibrationBCE(helpfulness logit, stopgrad(E_on < E_off))。默认 0;几何 GT 与 no-mask 对照。
mask_quality_regression预测质量与显式 quality target 的 MSE;独立 quality_valid。默认 0;不把 provider score 自动当 GT。
mask_gate_entropy(Bernoulli gate entropy / log(2) − (1 − quality target))²。默认 0;仅控制确定性,不决定开/关方向。
+
+

所有 mask loss 接入 BimanualLoss,按 source-specific valid 与 frame_valid 聚合;开启却缺少配对或渲染字段时明确报错。 + SAM3 mask 属于伪标签,第一阶段只作为输入条件。完整接口与启动命令 · + adapter-only 训练入口。

+
+ +
+
+
+

02 / Camera motion condition

+

World Adapter 数据流

+
+

+ 先保留已完成实验使用的 v2 token-bias 路径,再给出 2026-08-26 已完成 step-500 机制筛查但未晋级的 v3 reference-residual 路径。 +

+
+ +
+
+

历史 v2 · 相邻 camera-to-world pose → 当前帧 RGB token condition

+ 已评估 · centered 9D → 512D · 134,145 params +
+
+
+ 外参输入 + T_world_camera[t-1]
T_world_camera[t]
+
+
+ 相对运动 ΔT[t] + inverse(T[t-1])
@ T[t]
+
+
+ SE(3) Feature + centered rotation-6D
+ translation-3 = 9D
+
+
+ WorldMotionAdapter + Linear 9→256 → GELU
→ Linear 256→512
+
+
+ RGB Token Residual + 加到当前帧每个 patch
[B,T,1,512] → P=1,792
+
+
+ 原 Decoder + Heads + 3× alternating + MANO
仍输出 camera-space
+
+
+
+ +
+
+

v3 prototype · frozen coarse state → reference-frame refined residual

+ 已训练 500 steps / 四干预已评估 · mechanism gate failed +
+
+
+ 外参轨迹 + previous ΔT + first-reference T
centered SE(3) · 9D
+
+
+ Frozen Coarse State + hand query + wrist XYZ
+ global root rotation
+
+
+ Reference Alignment + 当前 camera → 首帧 camera
分离 ego-motion / hand motion
+
+
+ Temporal Refiner + 2 layers · D=256
query/state-gated motion
+
+
+ Bounded Residual + delta wrist ≤ 0.05 m
delta root rotation ≤ 0.25 rad
+
+
+ Back to Current Camera + 原 MANO layer
camera-space joints / vertices
+
+
+
+ +
+
+ Canonical pose + T_world_camera [B,T,4,4] + camera-to-world 齐次刚体变换;各数据源先规范化到同一方向。 +
+
+ Source validity + camera_extrinsics_valid [B,T] + 表示该帧是否确有合法、有限且正交的真实外参。 +
+
+ Input gate + camera_extrinsics_input_available [B,T] + 表示本次 forward 是否允许使用外参;与数据真实性分开控制。 +
+
+ +
+
+ v2 token bias + 134,145 parameters + 足以编码 9D pose,但 frozen decoder 很容易忽略统一 patch bias。 +
+
+ v3 residual refiner + 1,225,496 parameters + v2 的 9.13 倍;约占含 v3 整模 0.96%,负责时序状态融合与 root correction。 +
+
+ Depth-specific path + 21,514,499 parameters + v3 仅为其 5.70%;外参是低维轨迹,不需要复制 dense depth encoder。 +
+
+ +
+
+ v1 / v2 feature 版本 + Formal v1 的 C1/C2 为 7D/10D(含 valid);full-parent v2 不把 availability 当 domain token,centered C2 为 9D。v3 也使用 centered 9D motion。 +
+
+ T=1 与首帧 + 没有上一帧时 relative motion 无定义,condition 精确为 0;单帧可正常推理,但当前不会从外参获得增益。 +
+
+ 变长与安全回退 + T 可变,padding 由 frame_valid 屏蔽;任一相邻 pose 缺失、非法或被禁用时,该帧回退到原 RGB token。 +
+
+ +
+
+ Depth 与外参不重复 + Depth + K 给当前相机内的逐帧 metric geometry;外参给相机坐标系之间的时序关系。v3 在视觉融合之后使用后者,避免与 depth cross-attention 抢同一入口。 +
+
+ Camera → World 指标恒等式 + 同一刚体变换同时作用于 prediction 与 GT 时,逐帧欧氏误差不变;camera-space MPJPE 降多少,转换后的 world-space MPJPE 就降多少。 +
+
+ v3 的严格边界 + Missing / Identity 在 step 500 后 raw predictions 完全一致,375 个 frozen parent tensors 逐 bit 不变;支持变长和 causal mask。 + 但 True - Missing 为 +0.0283 mm、True - Shuffled 近零,R1-A 已停,不能写成性能提升。 +
+
+
+ +
+
+
+

03 / Decoder internals

+

一次 Spatial / Temporal 更新内部

+
+

以下结构在 alternating 模式中重复三次,顺序为 S1→T1→S2→T2→S3→T3。

+
+ +
+
+
+

SpatialUpdate · 每帧独立读取图像

+ [B×T, 2, 512] +
+
+
+ Query + Side Bias + LayerNorm
[BT,2,512]
+
+
+ L/R Self-Attention + bimanual
2 query tokens
+
+
+ RGB Cross-Attention + Q=2
K/V=1,792
+
+
+ Depth Cross-Attention + Q=2
K/V=1,792
+
+
+ Fixed Depth Gate + 0.5 × available
residual add
+
+
+ Residual FFN + LN
512→2048→512
+
+
+
+ +
+
+

TemporalUpdate · 只混合 Hand Query

+ [B, T, 2, 512] +
+
+
+ 01 +
+ 按 hand 重排 + [B,T,2,D] → [B×2,T,D] +
+
+
+ 02 +
+ 沿时间双向 Self-Attention + 8 heads;frame_valid mask;无 temporal position bias +
+
+
+ 03 +
+ 恢复逐帧排列 + [B×2,T,D] → [B,T,2,D] +
+
+
+ 04 +
+ 逐帧 Bimanual Attention + left / right 两个 query 再交换信息 +
+
+
+
+
+
+ +
+
+
+

04 / Tensor contract

+

关键张量与训练目标

+
+

B 可变;正式配置 batch size=1。T 通常为 8,collate 与推理支持变长。

+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
张量Shape产生位置语义
T_world_camera[B,T,4,4]Canonical camera contractcamera-to-world 外参;仅 C1/C2 消费
camera_extrinsics_valid[B,T]Dataset / cache adapter真实外参与刚体合法性 mask
camera_extrinsics_input_available[B,T]Input condition gate本次 forward 是否允许消费外参
world_adapter_features[B,T,10]Relative camera motionC2 的 rotation-6D + translation-3 + valid-1
world_condition[B,T,512]WorldMotionAdapter沿 P 维 broadcast 后加到 RGB patch tokens
rgb_tokens[B,T,1792,512]DINO + projection + K rays + optional ΔM / ΔT逐帧 appearance、内参射线、可选 mask 空间条件与相机运动条件
hand_mask[B,T,2,Hm,Wm]Offline provider → aligned cache全图 L/R soft probabilities;valid / score / input_available 各为 [B,T,2],source 为字符串
ΔM / mask_gate[B,T,P,512] / [B,T,2]MaskPatchAdapter空间 token residual / 每手置信门控;有无 mask 都保持原 MANO 输出接口
depth_tokens[B,T,1792,512]DepthGeometryEncodermetric XYZ / logZ patch feature
hand_tokens[B,T,2,512]Alternating decoder每帧左右手的共享语义表示
joint2d_norm[B,T,2,21,2]2D joint head归一化图像坐标 [0,1]
mano_rotation_matrices[B,T,2,16,3,3]6D rotation conversionMANO global + local joint rotations
mano_shape[B,T,2,10]time pool + shape head同一 clip 内按帧展开的共享 beta
wrist_root_translation[B,T,2,3]direct XYZ headcamera-space wrist,单位米
joints_camera[B,T,2,21,3]Left / Right MANOcamera-space hand joints,单位米
vertices_camera[B,T,2,778,3]Left / Right MANOcamera-space mesh vertices,单位米
+
+ + +
+ +
+
+ 有:K 内参条件 + patch center rays + geometry depth +
+
+ 可选:Camera 外参条件 + C0 bypass;C1 relative rotation;C2 relative SE(3) +
+
+ 输出仍为 Camera-space + 外参用于 conditioning,不把 MANO / joints 改成 world-space +
+
+ 可选:Hand Mask 空间条件 + Provider 解耦;zero-init adapter;M0 冻结 parent +
+
+
+ +
+ Foundation Hand · parent / camera snapshot 2026-08-26 · mask extension 2026-09-17 + + Evidence: + models/bimanual.py, + models/decoder.py, + models/encoders.py, + models/world_adapter.py, + geometry/camera_motion.py, + data/camera_extrinsics.py, + models/mask_adapter.py, + training/mask_losses.py, + s8a_j25_full.yaml + +
+
+ + + + diff --git a/home/wuyifan/EgoNet_train_20261008/docs/PIONAI_NON2D_HANDOFF_20261005.md b/home/wuyifan/EgoNet_train_20261008/docs/PIONAI_NON2D_HANDOFF_20261005.md new file mode 100644 index 0000000000000000000000000000000000000000..2bbd82823925c1fd7ba980d56784ac1460067f82 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/PIONAI_NON2D_HANDOFF_20261005.md @@ -0,0 +1,18 @@ +# PionAI non-2D training handoff (2026-10-05) + +## Transferred assets + +- Code and contracts: `/data/foundation_hand_wyf/code/EgoNet_20261005/`. This is a separate snapshot; the existing `/data/foundation_hand_wyf/code/` scripts and checkpoints were not changed. The source includes uncommitted October 4-5 work and is not equivalent to the GitHub HEAD alone. +- The clean-GT T8 index already on PionAI has SHA-256 `5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462`, matching the frozen B0/B1 statistics. +- Existing PionAI DINOv3 `model.safetensors` and MANO LEFT/RIGHT pkl hashes match the B0/B1 config: `9a21ac3df0c63839d62612dda6f454d816c25611cc7a52966ed5a5a94921dc8b`, `c4022f7083f2ca7c78b2b3d595abbab52debd32b09d372b16923a801f0ea6a30`, and `45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767`. +- Canonical refit labels: `/data/foundation_hand_wyf/cache/canonical_refit_20260930/`. The original inventory SHA-256 is `0bd3135ee5cdda31e50109cefc8fc8083b0d57d9646c9eb6d2f7aeab9e904b62`. `verify_transferred_labels.py` checked all 380 file hashes against that inventory: 266 ARCTIC and 114 H2O files. The inventory itself remains unchanged and still records its original G2 absolute paths. + +## Current contract and gates + +The current B0/B1 comparison is RGB T=8, H2O:ARCTIC:HOT3D 21:15:24, official DINO initialization with all other learned weights fresh, no teacher or distillation. Both arms use the official left/right MANO-pkl `hands_mean` for 15 local joints, a right-multiplied rotation delta, and FP32 orthogonalized 6D L1 pose supervision. Root orientation remains direct. The same 12 supervised terms and normalization asset are used in both arms; only the spatial decoder differs (B0 factorized hand query, B1 MoT). The geometry layer receives absolute local rotations and does not apply the mean again. + +This is **not yet a formal training release**. `experiments/from_scratch_mean_pose/config.json` has `training_approved=false`, and total updates, warmup, LR stages, and DINO freeze/unfreeze boundaries are deliberately unset. `smoke.py` performs only two updates per arm and writes no training checkpoint. The historical `experiments/u0_normalized6d/train.py` loads a parent/teacher and must not be pointed at this config. + +Local B0/B1 tests passed 6/6. On PionAI the config-only tests passed 2/2. Runtime test collection currently fails because the historical U0/A7 reader chain refers to `/home/wuyifan/...` and `/SSD3/...`; those paths have not been remapped to PionAI, and the original inventory's label paths also need a runtime resolver without changing its frozen hash. Therefore no PionAI B0/B1 CUDA smoke or formal training has run. + +Before a formal run: make the reader path mapping explicit and test it on all three sources; audit final HOT3D pose/shape masks and a full 60-clip batch; register a matched four-GPU optimizer/DINO schedule and checkpoint protocol; run per-loss gradient, DDP, and resume smoke; then evaluate the same RGB T8 source-native four metrics for both arms. Keep 2D pretraining separate from this comparison. As of this handoff, four PionAI GPUs are occupied by a root-owned vLLM service; wait for administrator release rather than stopping it. diff --git a/home/wuyifan/EgoNet_train_20261008/docs/README.md b/home/wuyifan/EgoNet_train_20261008/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9d14db5ae32278c3c54b76fbf4ab973d03eb30bb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/README.md @@ -0,0 +1,3 @@ +# Training and audit notes + +These documents describe the dataset contract, training lineage, results, and proposed next experiments. Reported numbers are not claims that the proposed retraining has been run. diff --git a/home/wuyifan/EgoNet_train_20261008/docs/TRAINING_DATA_SCHEMA.md b/home/wuyifan/EgoNet_train_20261008/docs/TRAINING_DATA_SCHEMA.md new file mode 100644 index 0000000000000000000000000000000000000000..875b9a1738d59c5e3c163494040e493babdc8331 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/TRAINING_DATA_SCHEMA.md @@ -0,0 +1,440 @@ +# Foundation Hand 训练数据 Schema 总结 + +整理日期:2026-08-20 +代码基线:`code/home/jiasen/foundation_hand`(备份生成于 2026-08-15) + +## 1. 结论先行 + +Foundation Hand 有两代相互兼容的数据入口: + +1. Phase 2-6 直接读取 H2O `cam4` 原始目录,生成 H2O clip/batch。 +2. Phase 7-9 将 H2O、HOT3D、HOI4D、ARCTIC 统一为按 clip 缓存的 `.npz`,再由同一个 reader、collate、模型和 loss 消费。 + +Phase 9 的正式主线是四源统一训练,不使用 dataset-specific head、adapter、router、crop 或 detector。统一约定是: + +- 一个样本是一段视频 clip,正式训练通常 `T=8`。 +- 手维固定为 2:`0=left`、`1=right`;缺手不删除 slot,而是用 validity mask 屏蔽。 +- 每手 21 个关节、MANO 778 个顶点。 +- 三维量统一为 camera coordinates、米;二维量为预处理后图像上的像素坐标。 +- 无效几何 target 通常写为 `NaN`,并且必须有对应的 `*_valid=False`;输入占位值和 inactive presence target 有例外,因此 mask 才是最终真值。 +- “模型输入是否可见”和“该字段能否用于监督”严格分离。 +- `camera_pose` 虽然保留在样本中,但四个 adapter 的变换方向并不统一;当前模型/loss 不消费它,不能把它当作跨数据源统一字段。 + +Phase 9 原始 J25 winner 使用 `H=368, W=640`;后续 Stage 7 已正式接受 `H=512, W=896`。除 `H/W` 外,两者 schema 相同。 + +### 正式训练数据源 + +| 数据源 | 训练输入 | 正式训练范围 | 关键限制 | +|---|---|---|---| +| H2O | RGB-D-K | official train,ego `cam4` | Phase 7-9 中 official validation 不参与训练/选择;official test 从未使用 | +| HOT3D | RGB-K | 有 GT 的 train recordings | 无 depth;K 对模型做 clip-level 0.3 dropout,但 K 仍可用于监督 | +| HOI4D | RGB-D-K | group-split external train | 历史 left-MANO 不兼容字段分别 mask;保留可信的 left root-relative 3D | +| ARCTIC | rectified RGB-K | P2 train,ego view 0 | 无 depth;历史 left-MANO 不兼容字段分别 mask;保留可信的 left root-relative 3D | + +`DEXYCB` 没进入 Phase 9 四源训练;`EgoDexter` 只用于冻结后的外部评估,不用于训练或模型选择。 + +上表的 validation 隔离是 Phase 7-9 unified 协议。早期 Phase 2/3 的 H2O-only 实验确实使用 official validation 做过 checkpoint/config 评估,不能把两段历史混为一谈。 + +## 2. 数据流 + +```text +原始数据 + -> source manifest(描述物理 recording 和 T 帧定位) + -> source adapter(解码、rectify、resize/pad、坐标/MANO 转换、数值审计) + -> clip_XXXXXXX.npz + cache_manifest.jsonl + -> CachedUnifiedClipDataset(输入 dropout / photometric / 可选几何和 depth corruption) + -> collate_h2o_clips(时间维 padding) + -> [B,T,...] batch + -> BimanualReconstructionModel + BimanualLoss +``` + +Phase 2-6 的 H2O 路径跳过 `.npz` cache:`H2OCam4Dataset` 直接从原始文件产生同类字段。 + +## 3. 维度符号 + +| 符号 | 含义 | 正式值/范围 | +|---|---|---| +| `B` | batch size | Phase 9 正式配置为 1,schema 不限定 | +| `T` | clip 帧数 | 正式通常 8;collate 支持变长 | +| `L` | left/right hand slots | 固定 2 | +| `J` | 每手关节数 | 固定 21 | +| `V` | 每手 MANO 顶点数 | 固定 778 | +| `H,W` | 网络输入分辨率 | `(368,640)` 或已接受的 `(512,896)` | + +下文先写单 clip shape `[T,...]`;collate 后除特别说明外,最前面增加 batch 维,成为 `[B,T,...]`。 + +## 4. H2O 原始磁盘 Schema + +H2O 只使用 head-mounted ego view `cam4`: + +```text +H2O/extracted/ + subject{1..4}///cam4/ + rgb/NNNNNN.png + depth/NNNNNN.png + cam_intrinsics.txt + cam_pose/NNNNNN.txt + hand_pose/NNNNNN.txt + hand_pose_mano/NNNNNN.txt + ... # object/action 等字段不进入当前 hand trainer +``` + +| 原始字段 | 原始格式 | 语义 | 是否进入训练 loader | +|---|---|---|---| +| `rgb` | `1280x720`, uint8 RGB PNG | 全帧 RGB | 是 | +| `depth` | `1280x720`, uint16 PNG | 毫米深度;除以 1000 转米 | 是 | +| `cam_intrinsics.txt` | 6 floats | `fx fy cx cy width height` | 是 | +| `cam_pose` | 16 floats | row-major `4x4 T_world_camera` | 携带但模型/loss 不使用 | +| `hand_pose` | 128 floats | 左 64 + 右 64;每手 `valid + 21*xyz` | 是 | +| `hand_pose_mano` | 124 floats | 左 62 + 右 62;每手 `valid + trans(3) + pose(48) + shape(10)` | 是 | +| `rgb256` | JPEG 缩略图 | 动作识别图像 | 否 | +| object/action/verb 字段 | txt/mesh | 手物与动作标注 | 否 | + +H2O `hand_pose` 的 21 关节顺序也是项目统一顺序: + +```text +0 wrist +1-4 thumb +5-8 index +9-12 middle +13-16 ring +17-20 pinky +``` + +H2O 的 `hand_pose_mano.trans` 是 MANO model origin 的 raw translation,不是 wrist。训练标准 target 是: + +```text +wrist_root_translation = hand_pose[..., joint_0, :] +``` + +`mano_translation_raw` 仅为兼容/审计字段,不能替代 `wrist_root_translation`。 + +### H2O 直读 manifest + +Phase 2-6 的 manifest 每行是一个 take 内连续有效帧 run: + +```json +{"take":"subject2/h1/0/cam4","frame_ids":[12,13,14],"run_index":0} +``` + +`H2OCam4Dataset` 再按配置的 `T`、stride 和 window step 从 `frame_ids` 切 clip。末尾可产生短 clip;不会循环或复制帧补齐。 + +## 5. 统一 Cache 的两层 Schema + +统一 cache 由一个 JSONL manifest 和多个 `.npz` payload 构成。JSONL 管身份、分组、路径和 hash;大数组放在 `.npz`。 + +### 5.1 `cache_manifest.jsonl` + +每行对应一个 cache clip,主要字段如下: + +| 字段 | 类型 | 含义 | +|---|---|---| +| `dataset_id` | string | `H2O/HOT3D/HOI4D/ARCTIC` | +| `subject_id` | string | 数据源内 subject/participant | +| `sequence_id` | string | 逻辑序列 ID | +| `physical_recording_id` | string | split 与 bootstrap 的物理 recording 边界 | +| `camera_id` | string | 相机 ID | +| `stream_id` | string | RGB stream ID | +| `headset_id` | string | headset/serial/subject 标识 | +| `source_clip_index` | int | 在 source manifest/dataset 中的稳定 clip 索引 | +| `source_group_key` | string | 含 dataset/subject/recording 的分组 key | +| `resolution_hw` | `[H,W]` | payload 分辨率;旧 640x368 cache 可能没有此字段 | +| `cache_path` | string | `.npz` 绝对路径 | +| `cache_sha256` | string | payload SHA256 | + +部分数据源还带 `geometry_masked_hand_frames` 或 `right_geometry_masked_frames` 等审计计数。旧 manifest 若没有 `resolution_hw`,reader 只允许把它当作 `(368,640)` legacy cache,不能冒充 896x512 cache。 + +### 5.2 `.npz` payload + +cache 中 RGB 保存为 `rgb_u8`,其余 tensor 直接保存为 NumPy array。读取时 `rgb_u8` 转为训练字段 `rgb`。 + +#### 模型输入与图像几何 + +| 字段 | 单 clip shape | dtype | 语义 | +|---|---:|---|---| +| `rgb_u8` | `[T,H,W,3]` | uint8 | cache-only RGB | +| `rgb` | `[T,3,H,W]` | float32 | reader 输出;ImageNet mean/std normalize 后的 RGB | +| `depth_m` | `[T,1,H,W]` | float32 | metric depth,单位米;无效位置通常为 0 | +| `depth_pixel_valid` | `[T,1,H,W]` | bool | depth 每像素有效性,使用 depth 必须同时检查它 | +| `K` | `[T,3,3]` | float32 | 与 resize/pad 后 `rgb/depth/joint2d` 对齐的相机内参 | +| `frame_valid` | `[T]` | bool | 真帧/时间 padding mask | +| `image_hw` | `[2]` | int64 | `[H,W]`;collate 后为 `[B,2]`,不增加 T 维 | +| `camera_pose` | `[T,4,4]` | float32 | source-specific 审计/元数据;不是统一可训练语义 | + +RGB normalize 公式: + +```text +rgb = (rgb_u8 / 255 - [0.485, 0.456, 0.406]) + / [0.229, 0.224, 0.225] +``` + +#### 几何与 MANO targets + +| 字段 | 单 clip shape | dtype | 单位/语义 | +|---|---:|---|---| +| `joint2d` | `[T,L,J,2]` | float32 | resize/pad 后像素坐标 `(u,v)` | +| `joint3d_camera` | `[T,L,J,3]` | float32 | camera-space `(x,y,z)`,米 | +| `joint3d_root_relative` | `[T,L,J,3]` | float32 | source joint 减 wrist,米;可缺省或来自 sidecar | +| `wrist_root_translation` | `[T,L,3]` | float32 | camera-space wrist,米;模型标准平移 target | +| `mano_pose` | `[T,L,48]` | float32 | 16 个 axis-angle;前 3 维为 global orientation | +| `mano_shape` | `[T,L,10]` | float32 | MANO beta | +| `mano_translation_raw` | `[T,L,3]` | float32 | source/raw 兼容字段;不是标准平移 target | +| `vertices_camera` | `[T,L,V,3]` | float32 | camera-space MANO 顶点,米 | +| `presence_target` | `[T,L]` | float32 | 当前正式训练无可靠 supervision,见 mask | + +训练循环在 forward 前调用 `attach_gt_vertices()`,用当前 MANO layer、`mano_pose`、`mano_shape`、`wrist_root_translation` 重新生成 `vertices_camera`。因此 cache 内已有的顶点不是最终 loss 的独立真值来源。 + +#### 独立监督 mask + +| mask | shape | 控制的 target/loss | +|---|---:|---| +| `joint2d_valid` | `[T,L,J]` | direct 2D joint loss | +| `joint3d_valid` | `[T,L,J]` | absolute camera 3D joint loss | +| `joint3d_root_relative_valid` | `[T,L,J]` | source root-relative joint loss | +| `translation_valid` | `[T,L]` | wrist translation、双手相对位置、时序平移 loss | +| `mano_pose_valid` | `[T,L]` | global orientation + local pose loss | +| `shape_valid` | `[T,L]` | MANO shape loss | +| `vertices_valid` | `[T,L]` | MANO vertex loss | +| `reprojection_valid` | `[T,L,J]` | 预测 3D 经 K 重投影的 loss | +| `presence_valid` | `[T,L]` | presence BCE;正式配置权重为 0 | +| `K_supervision_valid` | `[T]` | K 是否可用于几何监督/重投影 | + +这些 mask 不能相互推断。例如 HOI4D/ARCTIC 的某只手可以同时满足: + +```text +joint2d_valid = True +translation_valid = True +mano_pose_valid = True +joint3d_valid = False +shape_valid = False +vertices_valid = False +reprojection_valid = False +``` + +#### 输入 availability(不是监督 mask) + +| 字段 | shape | 含义 | +|---|---:|---| +| `depth_input_available` | `[T]` | depth 是否允许送入模型 | +| `K_input_available` | `[T]` | K/ray encoding 是否允许送入模型 | +| `depth_pixel_valid` | `[T,1,H,W]` | depth 内部哪些像素可用 | +| `K_supervision_valid` | `[T]` | 即使 K 对模型隐藏,K 是否仍可用于 loss | + +关键例子:HOT3D 做 K dropout 时,`K_input_available=False`,但数值 `K` 仍保留且 `K_supervision_valid=True`。不能因为模型看不到 K 就删除 K 或关闭 reprojection supervision。 + +#### 兼容字段 + +以下 legacy 字段仍会写入,供 Phase 2-6 batch 或 fallback 逻辑使用: + +| 字段 | shape | 新 schema 中的对应关系 | +|---|---:|---| +| `joint_annotation_valid` | `[T,L]` | 旧的整手 joint/MANO compatibility 标志 | +| `mano_annotation_valid` | `[T,L]` | 旧的整手 MANO compatibility 标志 | +| `joint_element_valid` | `[T,L,J]` | 旧 joint element mask | +| `presence_label_valid` | `[T,L]` | legacy presence mask | +| `depth_available` | `[T]` | `depth_input_available` alias | +| `K_available` | `[T]` | `K_input_available` alias | + +新代码优先使用字段级 `*_valid`。只有新字段缺失时才 fallback 到 legacy 字段。 + +#### ID、采样与增强字段 + +| 字段 | shape/type | 说明 | +|---|---|---| +| `hand_side_id` | `[T,L] int64` | 每帧固定 `[0,1]` | +| `frame_id` | `[T] int64` | 数据源内帧 ID;时间 padding 用 `-1` | +| `timestamp_ns` | `[T] int64` | source time/index;ARCTIC 实现中实际是 array index,不宜跨源比较绝对时间 | +| `photometric_aug_params` | `[T,5] float32` | `[applied, brightness, contrast, saturation, hue]`;整段 clip 参数相同 | +| `sampling_source_id` | string | mixture sampler/曝光计数使用的数据源 ID | +| `depth_input_condition_code` | `[T] int64` | 0 无源 depth,1 dropout,2 clean,3+ 对应某种 corruption | +| `geometry_aug_matrix` | `[T,3,3] float32` | 可选 shared full-frame affine;整段 clip 相同 | +| `geometry_aug_applied` | `[T] bool` | 是否应用该 affine | + +HOT3D 还可能带 `hand_pose_time_delta_ns`、`headset_time_delta_ns`、`source_hand_annotation_present` 等审计字段。这些不是模型最小输入。 + +## 6. Collate 后的 Batch Contract + +模型看到的核心 batch 可以概括为: + +```text +rgb [B,T,3,H,W] float32/bf16 autocast +depth_m [B,T,1,H,W] float32 +depth_pixel_valid [B,T,1,H,W] bool +K [B,T,3,3] float32 +frame_valid [B,T] bool +depth_input_available [B,T] bool +K_input_available [B,T] bool + +joint2d [B,T,2,21,2] float32 +joint3d_camera [B,T,2,21,3] float32 +joint3d_root_relative [B,T,2,21,3] float32, optional +wrist_root_translation [B,T,2,3] float32 +mano_pose [B,T,2,48] float32 +mano_shape [B,T,2,10] float32 +vertices_camera [B,T,2,778,3] runtime regenerated + +joint2d_valid [B,T,2,21] bool +joint3d_valid [B,T,2,21] bool +joint3d_root_relative_valid [B,T,2,21] bool, optional/fallback +translation_valid [B,T,2] bool +mano_pose_valid [B,T,2] bool +shape_valid [B,T,2] bool +vertices_valid [B,T,2] bool +reprojection_valid [B,T,2,21] bool +K_supervision_valid [B,T] bool + +image_hw [B,2] int64 +clip_length [B] int64 +dataset_id/... list[str], len B +``` + +### 时间 padding 规则 + +`collate_h2o_clips` 把 batch 内 clip pad 到最大 `T`,不会重复最后一帧: + +- `frame_valid=False` 表示 padding。 +- 几何/target 数值通常 pad 为 `NaN`。 +- bool mask pad 为 `False`。 +- `frame_id` pad 为 `-1`。 +- 其他普通数值 pad 为 0。 +- 所有 loss 还会与 `frame_valid` 相与,padding 不产生监督。 + +## 7. 四个 Source Adapter 的监督差异 + +### H2O + +- RGB、metric depth、K 都可作为输入。 +- 关节与 MANO `valid` 必须一致;无效手对应数值设为 `NaN`。 +- `joint2d` 由 camera-space joints 和更新后的 K 投影得到。 +- `translation_valid` 来自 hand annotation validity。 +- 没有可靠的 on-screen presence/visibility/occlusion label:`presence_target=NaN`、`presence_valid=False`。 +- `timestamp_ns` 是按 30 fps 从 frame ID 估算的相对时间,不是全局时钟。 + +### HOT3D + +- 只接受 official toolkit 可读取且 `have_hand_object_pose_gt=true` 的 recording。 +- 图像通过官方 rectilinear/undistorted camera API 解码;hand pose 和 headset pose 必须在 20 ms 内同步。 +- 无 metric depth,因此 depth tensor 全 0、pixel mask 和 availability 全 False。 +- source MANO mesh 与项目当前 MANO 重建误差必须 `<1 mm`,否则该 frame/hand 的 geometry supervision 被 mask。 +- 通过门的左右手可有完整 MANO/3D/2D/translation supervision。 +- 正式 cache reader 对 K 做确定性的 clip-level 0.3 input dropout。 + +### HOI4D + +- RGB 和 aligned uint16 depth 从视频精确按 frame ID 解码;K 从 `intrin.npy` 读取并随 resize/pad 更新。 +- 每帧每手 pickle 的最小源字段为 `poseCoeff[48]`、`beta[10]`、`trans[3]`、`kps2D[21,2]`。 +- 右手通过 `<1 mm` 当前 MANO compatibility gate 后可使用完整几何监督。 +- 历史 left-MANO shapedirs 与当前 corrected-left convention 不兼容:left direct 2D、pose、wrist translation 可保留;left shape、absolute MANO 3D、vertices、MANO reprojection 显式关闭。 +- Phase 9 配置 `joint3d_root_relative_scope: historical_left_only`,通过 sidecar 只启用可信的 left source root-relative joints。 + +### ARCTIC + +- 只接受 P2 train/val manifest;训练使用 P2 train,ego view 0。 +- 输入图像先从 scaled raw frame 用 ARCTIC distortion/K 做 rectify,再 resize/pad。 +- 无 metric depth。 +- 世界坐标 MANO 转到 camera coordinates 后,再用 `<1 mm` compatibility gate 判定字段。 +- 与 HOI4D 类似,历史 left convention 失败时仍保留 direct 2D、pose、wrist 和 source root-relative joints,关闭不兼容的 shape/absolute MANO 3D/vertices/reprojection。 +- Phase 9 同样把 root-relative supervision 限定为 historical left sidecar。 + +## 8. 坐标、单位与图像约束 + +### Camera coordinates + +项目训练输出使用: + +```text +x: right +y: down +z: forward +unit: meter +``` + +投影公式: + +```text +u = fx * x / z + cx +v = fy * y / z + cy +``` + +`joint2d` 是像素坐标,不是 `[0,1]`。loss 内部才除以 `[W,H]` 得到 normalized target。 + +### Resize/pad + +RGB 与 depth 必须使用同一个 aspect-preserving resize/pad contract:RGB 通常线性/area 插值,depth 用 nearest。K 同步更新 focal length 和 principal point。任何 crop/affine 也必须同步更新 RGB、depth、K 与 joint2d。 + +### Depth + +- 统一单位为米,不做 per-frame min-max normalization。 +- H2O/HOI4D 原始 uint16 depth 按毫米解释并 `/1000`。 +- `depth_pixel_valid` 是唯一可信的 per-pixel mask;无效 depth 数值本身不能充当监督依据。 +- geometry depth encoder 还要求当前帧 K 对模型可用。 + +### MANO + +- `mano_pose[...,0:3]` 是 camera-frame global axis-angle,后 45 维为 local pose。 +- `mano_shape` 为 10 维 beta。 +- MANO 输出先以 joint 0 root-center,再加 `wrist_root_translation` 放到 camera coordinates。 +- 左右手永远是两个固定 semantic slots,不能按当前帧可见手数压缩维度。 + +## 9. 哪些字段真正被模型和 Loss 消费 + +模型 forward 的最小依赖: + +- 必需:`rgb`、`frame_valid`。 +- ray/K 模式:`K`、`K_input_available`。 +- depth 模式:`depth_m`、`depth_pixel_valid`、`depth_input_available`。 +- 旧 Phase 4 oracle-crop 分支才读取 `oracle_crop_*`;Phase 9 unified 主线禁用 crop。 + +Loss 主要消费: + +- `joint2d` + `joint2d_valid`。 +- `joint3d_camera` + `joint3d_valid`。 +- `joint3d_root_relative` + `joint3d_root_relative_valid`,缺字段时从 camera joints fallback。 +- `wrist_root_translation` + `translation_valid`。 +- `mano_pose/mano_shape/vertices_camera` + 各自 validity。 +- `K` + `K_supervision_valid/reprojection_valid`。 +- `frame_valid` 始终是最外层时间 mask。 + +当前主线不消费 `camera_pose`、`mano_translation_raw`、object pose、action label 或 metadata identity。metadata 用于采样、split、审计和 grouped evaluation。 + +## 10. 最容易踩错的点 + +1. 不要把 `annotation_valid` 当作手的物理存在或可见性;项目没有可靠 presence/occlusion GT。 +2. 不要把 `mano_translation_raw` 当 wrist;训练标准平移是 `wrist_root_translation`。 +3. 不要用一个整手 mask 覆盖所有字段;2D、3D、pose、shape、translation、vertices、reprojection 必须独立 mask。 +4. 不要因 `K_input_available=False` 删除 K;K 可能仍用于 supervision。 +5. 不要用 0 代替无效几何 target 后继续计算 loss;应使用 `NaN + *_valid=False`,loss 内再安全替换。 +6. 不要把 `[H,W]` 写成 `[W,H]`;config/manifest 的 `resolution_hw` 明确是 `[height,width]`。 +7. 不要在 resize/pad 后沿用原 K 或原 joint2d。 +8. 不要跨数据源依赖 `camera_pose`;其方向/占位语义不统一。 +9. 不要通过重复帧补齐短 clip;只 pad 并设置 `frame_valid=False`。 +10. split 必须以 `physical_recording_id` 为边界,不能让同一 recording 的相邻/同步 clip 跨 train/heldout。 +11. cache manifest 与 payload 必须绑定 SHA256,且 reader 的 expected resolution 必须匹配。 +12. H2O official test、外部 official/no-GT test、ARCTIC P2 test 和 EgoDexter 均不能进入训练。 + +## 11. 可选的旧 Oracle Crop 字段 + +仅 Phase 4 A3 分支可能出现,Phase 9 主线不使用: + +```text +oracle_crop_rgb [T,2,3,224,224] +oracle_crop_depth_m [T,2,1,224,224] +oracle_crop_depth_pixel_valid [T,2,1,224,224] +oracle_crop_K [T,2,3,3] +oracle_crop_box_xyxy_raw [T,2,4] +oracle_crop_available [T,2] +oracle_crop_depth_available [T,2] +``` + +## 12. 代码真值位置 + +- H2O 原始字段解析:`src/foundation_hand/data/h2o_fields.py` +- H2O dataset 与 collate:`src/foundation_hand/data/h2o_dataset.py` +- 统一 mask/availability 定义:`src/foundation_hand/data/schema.py` +- 统一 cache reader:`src/foundation_hand/data/cached_unified_dataset.py` +- Source adapters:`src/foundation_hand/data/{hot3d,hoi4d,arctic}_dataset.py` +- 模型输入消费:`src/foundation_hand/models/bimanual.py` +- Loss 与 mask fallback:`src/foundation_hand/training/losses.py` +- H2O/统一训练入口:`scripts/train_experiment.py`、`scripts/train_phase7_external.py` +- H2O 原始格式盘点:`DATASET_REPORT.md` +- Phase 7/9 数据边界:`artifacts/phase7/PROTOCOL.md`、`artifacts/phase9/PROTOCOL.md` diff --git a/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_L_MOT_MANO_TRAIN_PLAN_20261007.md b/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_L_MOT_MANO_TRAIN_PLAN_20261007.md new file mode 100644 index 0000000000000000000000000000000000000000..523a9562ecfd0ace5a5f2d3e1ab536c888627c20 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_L_MOT_MANO_TRAIN_PLAN_20261007.md @@ -0,0 +1,75 @@ +# ViTPose-L + MoT 完整 MANO 训练计划(2026-10-07) + +## 定位与当前状态 + +这是已批准的 **纯 RGB、完整 MANO、从 ViTPose-L 视觉预训练出发** 的实验合同,不是旧 DINO B0/B1 方案,也不是从已有 Foundation Hand 权重续训。可执行配置以 G1 的 `experiments/vitpose_mot_from_scratch/config.json` 和 `experiments/from_scratch_mean_pose/config.json` 中 `shared` 部分为准;本文件用于跨机器交接,不替代配置和代码。 + +- `formal_v1` 在 update 30 因 ARCTIC 样本中 3D joints 为 NaN、但旧 `joint3d_valid` 仍为真而停止;该 run 和旧 smoke 权重不得作为正式恢复点。 +- 数据读数器现以关节有限性收紧 3D 有效 mask,不修改有限 GT 数值或 loss 定义。修正后的独立 `formal_v2` 已完成两步新 smoke 和三源预评估;截至 2026-10-07 11:05 HKT,G1 `formal_v2/controller_status.json` 显示六卡正在运行首段 5K,最近已记录 update 50,尚无 5K 正式评估结果。 +- PionAI 的 `/data/foundation_hand_wyf/code/EgoNet_20261005/` 是 10 月 5 日旧快照;新源码快照位于 `/data/foundation_hand_wyf/code/EgoNet_20261007_vitpose/`,包含本计划依赖的实验代码、reader 和测试,但**不包含训练数据、ViTPose 预训练权重或 MANO assets**。`vitpose_mot_io_v3/` 也随源码保留,它是 IO 加速实验,不能自动视为已批准的 `formal_v2` 训练配置。不能仅凭同步源码就在 PionAI 启动训练。 + +## 模型和输入合同 + +| 部件 | 合同 | +|---|---| +| 视觉编码器 | ViTPose-L COCO 预训练视觉主干,24 blocks、1024 维;严格加载视觉权重,丢弃 COCO keypoint head;权重 SHA256:`82dea141d75805068ce80705b9a3965af9cbc62a1844c46d88238012a2c2097f`。空间位置编码插值后,还要加原 `pos_embed[:, :1]` 全局位置偏置。 | +| 新参数 | 1024→512 patch 投影、RGB/HAND MoT、3 层 512 维/8-head 交替时空 decoder 和 MANO heads 全部随机初始化;不用 S4/A7/U0/teacher checkpoint。 | +| 输入 | 全画幅 RGB、双向 `T=8`;没有 depth、K、camera trajectory 作为模型输入。K 只用于 MANO 关节的训练重投影监督及评估。 | +| 输出 | 左右手 camera-space MANO root orientation、15 个 local pose、shape、XYZ translation,以及 MANO 前向得到的 21 joints/778 vertices;视觉缺失/出画由各项有效 mask 管控。 | +| 姿态参数 | 左右手分别取官方 MANO pkl 的固定 local `hands_mean`:`R_delta_gt = R_mean^T R_gt`,预测最终 `R_local = R_mean R_delta_pred`;root orientation 直接预测 camera-space rotation。GT 轴角转矩阵、预测 6D 正交化及 pose loss 都在禁用 autocast 的 FP32 路径。 | + +当前总/可训练参数量不应按 ViTPose-L 名义规模推断。G1 单样本预检报告的**解冻阶段可训练参数**为 48.38M,其中视觉最后两层及 final norm 为 25.19M;正式日志/模型实例应再次核对。其余视觉层始终冻结,MANO 几何层固定不训练;直接 2D head 冻结,`joint2d` loss 关闭。 + +## 训练数据 + +只用 H2O、ARCTIC、HOT3D 的 train-only canonical 标签。每个 optimizer update 的 global batch 固定 60 个 T8 clips,源配额严格为 H2O 21、ARCTIC 15、HOT3D 24;六卡 DDP 时每卡累计 10 clips,并在每步核对全局配额。held-out development 不参与训练统计量拟合。 + +三档目标画幅依次为 `512x896`、`368x640`、`512x512`(H×W),按来源采样: + +| 来源 | 512x896 | 368x640 | 512x512 | +|---|---:|---:|---:| +| H2O | 75% | 20% | 5% | +| ARCTIC | 70% | 20% | 10% | +| HOT3D Aria | 30% | 15% | 55% | +| HOT3D Quest3 | 60% | 20% | 20% | + +图像 resize/pad、2D 标签和 K 必须同步。HOT3D 的正式监督有效性按当前 canonical 数据合同过滤;画面外或非有限关节不能误入 2D/3D loss。HOT3D Aria 抽样显示 `512x896` 比 `512x512` 增加的多是 padding,而非有效手像素,因此后续可单独评估计算效率,但首轮不擅自修改已批准的分辨率配比。 + +## 阶段和优化器 + +| 阶段 | 更新范围 | 可训练参数 | 学习率与门槛 | +|---|---:|---|---| +| 预检 | 正式 update 前 | 两步 smoke 可训练新参数 | 修正后视觉前向、batch60 的 1→2 步完整 checkpoint 恢复、三源各 2 clips 评估接口、GT/旋转/K/有效 mask、六卡连续空闲均需通过。Smoke checkpoint 不作正式初始化。 | +| S0 | 0–4,999 | 新投影、MoT/temporal decoder、MANO heads;视觉主干冻结 | AdamW 新参数 peak LR `5e-5`,前 1,000 updates warmup;5K 后保存完整 checkpoint 并评估。 | +| S1 | 5,000–119,999 | S0 参数 + ViTPose 最后 2 blocks 和 final norm;前 22 blocks 仍冻结 | 视觉部分 peak LR `1e-6`,从 5K 起单独 1,000 updates warmup;新参数沿自身 schedule。两组 LR 均以 120K 为初始端点做 cosine 衰减,最小为 peak 的 0.1。 | + +AdamW weight decay `0.05`、全局梯度范数裁剪阈值 `100`、BF16 前向;GT/6D 几何采用 FP32。六卡 DDP,逐 clip 梯度累积而不是更改 global batch;本次正式 controller 用每卡 4 个 worker、pin-memory、OpenCV worker 单线程及 OMP/BLAS 单线程。120K 是**初始训练端点**,不是保证收敛或必须额外续训的结论。保存/评估节点:5K、10K、20K、40K、60K、80K、100K、120K。每段从完整模型、optimizer、各 rank RNG、数据位置和哈希合同恢复;不能从旧 smoke 或失败的 `formal_v1` 恢复。 + +## 监督 loss + +所有项目只在对应 GT 有效元素上求 masked mean;无效/非有限 GT 不得产生梯度。训练采用下表固定系数,不额外使用 teacher、parent distillation、hard-pose 重加权、SAM mask 或 modality loss。 + +| 项目 | 权重 | 监督对象 | +|---|---:|---| +| `joint3d_camera` | 1.5 | 绝对 camera-space 3D joints | +| `joint3d_root_relative` | 1.5 | 去腕后的 3D joints | +| `vertices_camera` | 0.15 | 绝对 camera-space MANO vertices | +| `translation` | 1.5 | 腕/root XYZ translation | +| `local_pose` | 0.3 | 15 个关节相对官方 MANO mean 的归一化 FP32 6D delta L1 | +| `global_orientation` | 0.3 | camera-space root rotation | +| `shape` | 0.1 | MANO shape 参数 | +| `reprojection` | 1.0 | 预测 MANO 3D joints 经当前 K 投影到有效 2D GT | +| `temporal_velocity` | 0.015 | 有效连续帧的 translation 速度 | +| `temporal_acceleration` | 0.0075 | 有效连续帧的 translation 加速度 | +| `bimanual_relative_wrist` | 0.15 | 双手同时有效时的相对腕位置 | +| `joint2d` | 0.0 | 直接 2D head 不参与监督;2D 只走 MANO 重投影 | + +`loss = Σ weight_i × masked_loss_i`。这些系数不能脱离各项内部归一化直接解释为梯度占比。`K` 不进入视觉/decoder 条件分支,因此此实验不能证明 K 或 depth 作为**输入**的收益。 + +## 评估与继续条件 + +- 每个节点对固定 H2O、ARCTIC、HOT3D source-native GT development 评估:Abs MPJPE、Root-relative MPJPE、MPVPE(mm)和 MANO projected 2D error(px)。这不是 official test。 +- 同步报告 per-joint local rotation 测地角、GT 高弯曲(例如 >=60°)预测偏差、root-relative 指尖误差、预测/GT local 6D 方差比,以及 normal pose no-harm。不得只凭预测方差增加断言 mean-pose 问题改善。 +- 首个 5K 节点先核对有效 GT 分母、三源暴露、各项 loss/梯度有限性与四指标;继续 10K/20K 后看跨源和 hard/normal 的配对趋势。若一段失败,controller 停止并保留日志,不自动降低过滤或改变 loss。120K 后再决定是否延长/选点,最终需独立 official benchmark 确认。 + +G1 实验路径:`wuyifan/artifacts/vitpose_mot_from_scratch_20261006/formal_v2/`。详细吞吐和 `formal_v1` NaN 诊断见 `docs/VITPOSE_MOT_RGB_THROUGHPUT_20261007.md`;历史决策与预检记录见 `docs/HK.md`。这些文档与 10 月 7 日源码均已包含在 PionAI 新快照中;运行数据和模型资产仍需单独准备与校验。 diff --git a/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_MOT_GPU_UTILIZATION_20261007.md b/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_MOT_GPU_UTILIZATION_20261007.md new file mode 100644 index 0000000000000000000000000000000000000000..c2d558b682eb6b516ef3ff72378c0e1d1c6d8c76 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_MOT_GPU_UTILIZATION_20261007.md @@ -0,0 +1,35 @@ +# ViTPose-L + MoT GPU 利用率与数据等待审计(2026-10-07) + +## 结论 + +- 当前 T=8、global batch 60、三源 21:15:24、三档分辨率、完整 MANO loss 和 AdamW 下,六卡 G1 的 `nvidia-smi` 1 Hz 平均利用率**没有达到 90%**。只增加 worker、microbatch 或预取不能宣称已达到该目标。 +- 保持训练数学合同不变,4 worker/卡、worker 内裁剪、pin memory、HOT3D hand-only provider 的预取系数从 4 提到 16,六卡 120 个稳态 update 为 **2.641 s/update、22.72 clips/s**。720 个 rank-update 中 96% 的取数等待 <10 ms,平均 24 ms;仍有最大 5.602 s 的 VRS 长尾。不能称为绝对零等待。 +- 预取 16 的六卡平均 GPU 利用率为 61–66%。即使 G2 两卡预载同一批数据、完全没有 DataLoader 等待,microbatch=10 的平均利用率仍为 85–87%。要稳定超过 90%,还需改变执行路径或有效 batch,不是数据预取一个开关能解决。 + +## 同机六卡受控测试 + +除表中变更外,均为 ViTPose-L 最后两层可训练、每 rank 10 个真实 T8 clip、完整反传与裁剪;GPU 利用率在 timed updates 期间由 `nvidia-smi` 每秒采样。20 步对照均去掉前 2 步 warmup,输入位置相同。数据等待为六个 rank-update 的平均,不能直接从最慢 rank 步时相减。 + +| G1 六卡配置 | Timed updates | 最慢 rank s/update | clips/s | 平均等数据 s/rank-update | <10 ms 比例 | 六卡平均 GPU util | +|---|---:|---:|---:|---:|---:|---:| +| 4 worker、预取 4,复测 | 20 | 3.516 | 17.06 | 0.416 | 72.5% | 69.9% | +| 6 worker、预取 4 | 20 | 5.239 | 11.45 | 0.617 | 70.0% | 53.9% | +| 4 worker、预取 8 | 20 | 2.711 | 22.13 | 0.152 | 86.7% | 61.5% | +| 4 worker、预取 16 | 20 | 2.400 | 25.00 | 0.028 | 97.5% | 67.7% | +| 4 worker、预取 16 | **120** | **2.641** | **22.72** | **0.024** | **96.0%** | **63.4%** | +| 4 worker、预取 4、同分辨率 microbatch 最大 10 | 20 | 3.348 | 17.92 | 0.476 | 66.7% | 74.7% | + +预取 16 长测按 40 步分段,最慢 rank 均值分别为 2.606 / 2.712 / 2.605 s;主存最高约 100 GiB used、约 370 GiB available,没有持续增长。最大单 rank 取数尖峰 5.602 s。预取只平滑随机 VRS/标注加载的长尾,不提高 worker 原始解码吞吐;长时间训练仍须监控。 + +G2 两卡的预载数据诊断只用于确认计算侧上限,不是正式训练吞吐:逐 clip、保留几何检查时约 78% GPU util;跳过逐 clip 几何检查约 82%;microbatch 最大 5 约 86%,最大 10 约 85–87%。延迟 loss 诊断的实验未改善步时,已撤回;`torch.compile` 编译 ViTPose encoder 的隔离试验在训练路径报错,未进入正式配置。 + +把每卡样本数从 15 提到 20、同分辨率 microbatch 最大 20 的预载数据 G2 试验仍只有 84.8% / 86.6% GPU util,14.22 clips/s;15 样本试验为 14.33 clips/s。显存约 11–14 GiB/卡。这不支持仅靠增大 batch 改到 90%,而且正式 B60 改 B120 会改变曝光量/学习率日程,未经收敛消融不能采用。 + +## 数据与训练边界 + +- HOT3D train-only manifest 有 143,657 个 T8 tile、230 段录制、约 107 万个唯一 `(recording, stream, timestamp)` 帧。随机采样不断切换 VRS 录制段,是剩余长尾的主要候选;全量离线缓存需要另行评估格式、磁盘量和逐字段等价,不应在训练中临时替换。 +- `experiments/vitpose_mot_io_v4/` 只把预取改成 16,独立实验名、哈希和 smoke 目录。源配比、采样序列、混合分辨率、loss、优化器、模型权重初始化都与 v3 一致。v4 的 smoke/小评估通过前不得启动正式训练。 +- v4 两步六卡 smoke、断点恢复及 H2O/ARCTIC/HOT3D 各两条小评估已通过;v3/v4 前两步 rank 0 的 loss 分量及裁剪前梯度范数逐项相同。冷启动时第一、二步仍各等数据约 10 秒,预取 16 的近零等待结论只适用于 steady state。`formal_io_v4/controller_status.json` 为 `preflight_complete_awaiting_performance_gate`,**未启动正式 5K**。 +- 90% 不是当前配置的已验证能力。后续若坚持该门槛,需单独验证更大的有效 batch、执行图优化或离线缓存,并重新审核训练数学、内存与收敛;不能用无关计算填满 GPU 来制造利用率。 + +原始 JSON 在 `wuyifan/artifacts/vitpose_mot_from_scratch_20261006/` 的 `g1_v3_util_6gpu_*.json`;G2 隔离诊断在 `/home/wuyifan/egonet_vitpose_throughput_20261007/g2_v3_util_*.json`。pilot 均不保存模型权重。 diff --git a/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_MOT_IO_V4_PROFILE_20261007.md b/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_MOT_IO_V4_PROFILE_20261007.md new file mode 100644 index 0000000000000000000000000000000000000000..32c20dc6c336633962a295df1e1dacd2d7ec35f6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_MOT_IO_V4_PROFILE_20261007.md @@ -0,0 +1,68 @@ +# ViTPose-L + MoT RGB v4 training profile (2026-10-07) + +## Scope and measurement + +- The G1 formal run was not edited or resumed. The profiler and ablations ran in an isolated copy of the same code on G2 GPUs 0/1, then in a checkpoint-free G1 six-GPU pilot. The isolated G2 source is `/home/wuyifan/egonet_v4_profile_20261007/`; small raw reports are copied to `wuyifan/artifacts/vitpose_mot_from_scratch_20261006/profiling_g2_20261007/`. The full Chrome traces remain on G2 because each is about 166 MB. +- All G2 throughput arms use real H2O/ARCTIC/HOT3D T=8 clips, the same source/resolution schedule, 10 clips/rank/update, two GPUs, four loader workers/rank, prefetch 16, BF16, full MANO objective, AdamW, gradient clipping, and 30 updates with three warmup updates. The frozen-visual arms use 24 updates and three warmup updates. Throughput is global clips divided by the slowest rank's mean timed update duration. GPU utilization is sampled at 1 Hz, so it is indicative rather than a kernel occupancy metric. +- A profiler-instrumented update takes about 28 seconds because recording/exporting a large trace perturbs execution. Do not use its wall duration as production step time; use the unprofiled A/B runs below. CUDA synchronization durations in a trace include waiting for already queued GPU work, not just the intrinsic cost of the line that triggered the wait. + +## What the trace shows + +The G2 last-two-unfrozen trace with formal-style logging contains 923 `cudaStreamSynchronize` calls on rank 0. Of those, 10 calls at `experiments/u0_depthsafe/model.py:111` (`bool(depth_available.any())`) account for about 574 ms of instrumented CPU wait. This is a redundant device-to-host check in the guaranteed RGB-only decoder. The formal per-clip logging causes 130 synchronizations/about 122 ms; the online canonical geometry audit causes 400 synchronizations/about 8 ms of explicit wait, plus about 92 ms of CUDA work. These phase totals overlap with queued work and must not be added as independent speedups. The source quota collective is negligible in this trace; nine NCCL all-reduce kernels total about 12 ms of GPU time. MANO-layer sync calls are numerous but account for about 1 ms of explicit CPU wait. + +The same update makes about 38,683 CUDA kernel launches (40,756 traced kernel events). By self CUDA time, `addmm` is about 39%, flash attention about 12%, copies about 9%, and `mm` about 9%. Ten serial single-clip forwards/backwards per rank create a fragmented launch pattern. There is no loop over 11 input conditions in this RGB experiment. The main-rank trace does not identify CPU MANO, gradient clipping, or DDP all-reduce as the primary bottleneck; data-worker CPU costs are separately visible through occasional loader stalls and are not ruled out by this trace. + +## Matched G2 A/B results + +The first table keeps worker-side single-clip collate. `No depth scalar check` substitutes otherwise identical RGB-only decoder logic in the isolated pilot; `no geometry audit` is a diagnostic upper bound, **not a safe training setting**. + +| Last-two-unfrozen arm | Clips/s, 2 GPUs | Mean GPU utilization | Peak PyTorch VRAM/rank | Change vs formal-style control | +|---|---:|---:|---:|---:| +| Control, formal-style source/loss logging | 12.332 | 77.5% | 2.79 GiB | baseline | +| Control repeat, simplified logging | 12.440 | 75.8% | 2.79 GiB | repeatability check | +| No depth scalar check, simplified logging | 12.915 | 80.3% | 2.79 GiB | about +4.3% vs matching simplified control | +| No online geometry audit, simplified logging | 12.909 | 78.4% | 2.79 GiB | about +4.3% vs matching simplified control | +| Both removed, formal-style logging | 13.430 | 82.4% | 2.79 GiB | +8.9% | + +The simplified control is 12.378 clips/s; its repeat is 12.440 clips/s. Adding formal-style quota/loss bookkeeping to that control gives 12.332 clips/s, so logging adds synchronizations but little net throughput cost in this particular two-GPU run. With the visual backbone frozen, the corresponding control is 14.147 clips/s, no depth scalar check 14.781, no geometry audit 14.952, and both removed 15.631 (+10.5% vs control). + +The next table groups equal-resolution clips into larger forwards while retaining the per-clip loss calculation and 10 clips/rank/update. These arms use a different, matched main-process collate path; compare only within this table. They are exploratory: a production mixed-source collator, source-quota accounting, mask/denominator equivalence, and six-GPU memory/throughput audit are still required. + +| Max clips/forward | Clips/s, 2 GPUs | Mean GPU utilization | Peak PyTorch VRAM/rank | +|---:|---:|---:|---:| +| 1 | 11.757 | 72.9% | 2.79 GiB | +| 2 | 12.849 | 80.6% | 3.57 GiB | +| 5 | 13.503 | 80.7% | 5.91 GiB | +| 10 | 13.685 | 82.6% | 8.94 GiB | +| 10 plus both diagnostic removals | 14.096 | 85.5% | 8.94 GiB | + +Early matched-path update-4 losses for microbatch 1/2/5/10 are approximately 0.351937/0.351891/0.351974/0.351954, and preclip gradient norms approximately 105.30/105.26/105.27/105.28. These are close, not a bitwise equivalence proof. Going from 1 to 10 gives +16.4% in the matched G2 pilot, with diminishing returns after 5; even the unsafe combined upper bound does not sustain 90% utilization. + +## G1 six-GPU reality and data safety + +The separate G1 frozen-visual, 24-update, six-GPU pilot with formal-style bookkeeping measured 25.433 clips/s (2.359 s/update). Its six 1-Hz utilization means were 56.0%, 59.0%, 67.1%, 56.6%, 61.8%, and 68.2% (61.5% overall); PyTorch peak allocated memory was about 2.17 GiB/rank. One rank had one 3.815-second data-wait spike among 21 timed updates; other ranks' mean data waits were about 1-2 ms. The formal G1 log likewise has a low median wait but occasional HOT3D/VRS recording-switch outliers. Therefore the G2 two-GPU gains cannot be projected linearly to G1 six GPUs. + +A matched G1 six-GPU pilot that **only** removes the redundant RGB decoder GPU-scalar check, while retaining the online geometry audit, measured 25.783 clips/s (2.327 s/update), or +1.4% end-to-end. Its six utilization means were 47.2%, 62.6%, 69.4%, 69.4%, 68.4%, and 67.7% (64.1% overall). This run had a 5.25-second and a 0.44-second data-wait spike. If each run's updates with any rank's data wait above 0.1 second are excluded, the mean slowest-rank step is 2.149 seconds (20 control updates) versus 2.012 seconds (19 ablation updates), about 6.8% less time. These short-run, differently censored numbers show the compute-path effect but are not a guaranteed six-GPU speedup. At update 4, rank-0 loss and preclip gradient norm remained approximately 0.5376 and 86.04 in both arms. + +At 15:46 HKT, the formal v4 run stopped after its last logged update 1200 and before the first scheduled checkpoint at update 5000. Rank 3 failed `validate_cached_geometry` with `canonical geometry/parameter inconsistency exceeds 1 mm`; the controller is `failed_needs_review`. This is a real label/contract failure, not an OOM or an effect of the separate G2 profiling. There is no formal model checkpoint from this run to resume. Do not remove the online geometry check to make it run: first identify and repair/quarantine the failing canonical target, then audit the complete training pool rather than only the early sampled prefix. + +## Decision + +1. Treat the bad canonical target as the blocking issue for the formal run. Preserve the failure and audit it before any retraining. +2. The RGB-only decoder scalar check is a plausible low-risk speed fix after confirming its input contract with an exact forward/backward equivalence test. Keep a host-side assertion that depth is absent without reading a GPU scalar every clip. +3. Retain online geometry validation until a complete train-pool audit passes. If moved out of the hot path later, preserve a sampled runtime guard and a versioned cache audit. +4. Pursue grouped microbatches only if the production collator preserves per-clip loss denominators, source quotas, masks, and mixed-resolution sampling. Re-benchmark on G1 six GPUs before changing the formal training recipe. Higher VRAM use alone is not evidence of higher throughput. + +## 2026-10-07 repair and six-GPU restart + +The failure was an ARCTIC right-hand root axis-angle with norm 3.141588 rad in tile `9654defbd0fb79791c03bfd8:40` at rank 3, update 1217. The cached mesh and direct MANO forward agreed within 0.000034 mm, but the old matrix-to-axis-angle round trip changed the root rotation and produced 1.797 mm mesh error. The repository rotation conversion now uses the near-pi-stable quaternion branch already present in the A7 rotation-fix source. The exact tile passes the unchanged formal 1 mm geometry guard; a replay of rank 3 updates 1201-1225 (250 clips: 85 H2O, 60 ARCTIC, 105 HOT3D) found no failures. The guard remains active during all formal training, since this replay is not a full-pool audit. The loaded rotation module path is now checked explicitly at startup. Rotation, model-contract, and grouped-collator regression tests pass 15/15. + +Matched G1 six-GPU last-two-unfrozen, real-data pilots each used 24 updates, four workers/rank, prefetch 16, 10 clips/rank, per-clip loss, BF16, full geometry validation, and three warmup updates. One-Hz GPU utilization is a coarse average, not SM occupancy. + +| Forward grouping | Decoder checkpointing | Clips/s | Mean GPU utilization | Peak PyTorch allocation/rank | +|---|---|---:|---:|---:| +| One clip | On | 22.910 | 62.1% | 2.79 GiB | +| Up to 10 equal-resolution clips | On | 25.978 | 69.4% | 9.72 GiB | +| Up to 10 equal-resolution clips | Off | 25.322 | 71.6% | 13.27 GiB | + +Grouping gave +13.4% throughput in this short pilot, without dropping geometric checks, changing the 60-clip source schedule, or changing per-clip loss denominators. Decoder checkpoint removal was slower and reduced memory headroom, so the restarted formal run keeps checkpointing. The 80% average-utilization target was **not reached** on six GPUs; use clips/s and training accuracy as the deployment criterion. The repaired, grouped run uses fresh smoke and formal output directories and cannot resume from the invalid pre-repair run. diff --git a/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_MOT_RGB_THROUGHPUT_20261007.md b/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_MOT_RGB_THROUGHPUT_20261007.md new file mode 100644 index 0000000000000000000000000000000000000000..0f25a02473f3c62b7f2a04e3e3922429941cfb42 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/docs/VITPOSE_MOT_RGB_THROUGHPUT_20261007.md @@ -0,0 +1,69 @@ +# ViTPose-L + MoT RGB 吞吐复测(2026-10-07) + +## 结论 + +- 六张 G1 GPU、global batch 60、T=8、原三源配比和混合分辨率不变。ViTPose-L 最后两层可训练时,50 个正式数据更新的最慢 rank 平均步时从 6.174 s 降到 5.270 s(约快 17% 的吞吐)。 +- 有效方案是每卡 4 个 DataLoader worker、pin-memory、OpenCV worker 线程设为 1,并以 `OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1` 启动。这里测的是整套配置的效果,未把收益归因于单个环境变量。 +- 在相同的优化数据配置下,把同分辨率 clip 合批仅从 5.270 s 降到 5.213 s(1.1%);暂不把动态合批加入正式训练,以保留原逐 clip loss 和断点口径。 +- 以 5.270 s/步机械外推 120K,纯训练约 7.32 天;此前 15 天估算偏保守。这不是包含完整三源评估、保存、长时间 IO 波动的完工承诺,也不是收敛所需步数的结论。 + +## 受控 G1 六卡测试 + +每组均为相同的前 52 个 update,去掉前 2 个 warmup 后统计 50 步;每 rank 每步 10 个真实 T8 clip,global batch 60;三档画幅及源 quota 不变。ViTPose-L 最后两层已解冻,BF16、完整 MANO loss、AdamW 反传与梯度裁剪均执行。步时取六个 rank 中均值最慢者;数据等待是 rank 0 均值,不能与最慢 rank 步时直接相减。 + +| 模式 | worker/卡 | pin-memory | 数据线程设置 | 最慢 rank s/update | clip/s | rank 0 数据等待 s | PyTorch 峰值 GiB/卡 | +|---|---:|---|---|---:|---:|---:|---:| +| 逐 clip,worker 内裁剪字段 | 2 | 否 | OpenCV 1 | 6.174 | 9.72 | 2.662 | 2.79 | +| 同尺寸合批,worker 内裁剪字段 | 2 | 否 | OpenCV 1 | 5.942 | 10.10 | 2.723 | 9.72 | +| 逐 clip,worker 内裁剪字段 | 4 | 是 | OpenCV 1、BLAS 1 | **5.270** | **11.39** | 2.003 | 2.79 | +| 同尺寸合批,worker 内裁剪字段 | 4 | 是 | OpenCV 1、BLAS 1 | 5.213 | 11.51 | 2.110 | 9.72 | + +JSON 与日志在 `wuyifan/artifacts/vitpose_mot_from_scratch_20261006/infra_g1_6gpu_20261007/`。2-worker 合批未先裁剪字段时为 6.149 s/步,说明未使用的 depth 等张量跨 worker 传输会抵消部分合批收益;正式逐 clip 路径本来就在 worker 内裁剪这些字段。 + +G2 的三卡、每卡 10 clip、4 worker、最后两层解冻的 50 步对照为 3.718 s/步、8.07 clip/s;四卡短测中 8 worker 并未优于 4 worker。G2 测试产物在 `/home/wuyifan/egonet_vitpose_throughput_20261007/`。三卡和六卡 batch 分别为 30/60,不能直接用步时比较训练总时长。 + +## 数据与稳定性 + +- 优化配置的合批 pilot 共读了 HOT3D 1,200、H2O 1,050、ARCTIC 750 个 clip;平均单 clip reader 耗时分别为 1.577、0.696、0.429 s。数据等待仍是主要可优化部分,尤其 HOT3D provider 的读取和标注生成。 +- 限制 BLAS 线程后 worker 仍可见约 67 个线程,因此不能断言这批线程由 OpenBLAS 造成;OpenCV/BLAS/worker/pin-memory 的单独因果贡献尚未逐项隔离。 +- 关闭整个 gradient checkpointing 在三卡测试中 OOM;只关 decoder 或 encoder checkpointing 的短测收益约 1%-2%,不值得当前显存与稳定性风险,正式配置保持原样。 +- 原 `formal_v1` 在 update 30 因 ARCTIC 一段 clip 的右手 3D joints 为 NaN、但 `joint3d_valid` 仍为真而失败。现在 `MixedResolutionDataset` 会以 3D joints 有限性收紧该 mask;这不改有效 GT 或 loss。5 个单元测试通过,六卡 50 步 pilot 已越过对应样本位置。旧 `formal_v1` 和旧 smoke 不复用、不删除。 + +## 正式运行 + +新 controller 目标为 `wuyifan/artifacts/vitpose_mot_from_scratch_20261006/formal_v2/`,使用独立 `smoke_nanmask_opencv_v1/`。顺序是两步新 smoke、三源各两条预评估、空闲六卡门禁、5K 正式训练,然后按原评估节点继续。实时状态以 `formal_v2/controller_status.json` 为准;本报告的 pilot 数字不是 benchmark 四指标,也不代表已达到 5K 或收敛。 + +后续若还要显著提速,应在固定训练数学口径下单独 profile HOT3D 录制段/VRS 打开与 MANO 标签生成,并验证 RGB-only H2O 是否能跳过未使用的 depth PNG 解码;两项目前都未改动。 + +## 进一步的 HOT3D IO 消融(同日) + +对真实 train-only clip 做 CPU profile 后,HOT3D 是最慢的数据源:抽样 8 个 clip 约 2.08 s/clip。官方 `Hot3dDataProvider` 初始化时还读取物体姿态和物体 2D 框,但本 RGB + MANO 训练的 `HOT3DClipDataset.__getitem__` 只使用设备影像、头显轨迹和 MANO 手轨迹。隔离测试用 hand-only provider 跳过这两类未使用的物体标注,保留同一个 VRS/相机标定/手部数据路径和原 LRU 容量。没有修改 G1 正在运行的正式训练代码。 + +- 在 Aria、Quest3、三档目标分辨率及 10 个不同录制段上,原版和 hand-only reader 的样本字典逐字段精确一致(浮点张量零容差并允许相同 NaN);40-clip 正反读取顺序测试也均一致。测试脚本和原始输出位于 `wuyifan/artifacts/vitpose_mot_from_scratch_20261006/probe_hot3d_lite_provider_20261007.py` 及同目录 `probe_hot3d_lite_provider*log`。这是抽样一致性,不等于全量形式化证明。 +- G2 的 GPU 0/1 用同一 ViTPose-L 权重(与 G1 SHA-256 完全相同)、相同三源 T8 样本、每卡 10 clip、4 worker、最后两层可训练、完整 MANO loss、AdamW 反传与裁剪跑 52 步;去掉前 2 步,报告后 50 步最慢 rank 均值。只变更 provider 或 `DataLoader.prefetch_factor`。G2 pilot 使用较早的 `single_sample` 全字段 worker 传输,而 G1 正式版已在 worker 中裁剪字段,因此数字不能直接当作 G1 六卡的承诺。 + +| G2 两卡 reader | 预取/worker | 50 步均值 s/update | clips/s | rank 0 数据等待 s/update | +|---|---:|---:|---:|---:| +| 官方 reader(A / A 重复) | 2 | 3.438 / 3.442 | 5.82 / 5.81 | 1.379(A) | +| hand-only(B / B 重复) | 2 | 2.823 / 2.803 | 7.08 / 7.14 | 0.910(B) | +| 官方 reader | 4 | 2.295 | 8.71 | 0.396 | +| hand-only(两次) | 4 | **1.939 / 1.995** | **10.32 / 10.02** | 0.209 / 0.233 | + +原版预取 2 到 hand-only 预取 4,在这组 G2 两卡短测中步时约缩短 42%-44%;其中单独提高预取和跳过未用的物体标注各有贡献。各组 PyTorch 峰值 GPU 显存均约 2.79 GiB/卡;增加预取主要占 CPU 内存及 `/dev/shm`,G1 当时可用内存约 373 GiB、`/dev/shm` 252 GiB。G2 原始 JSON 和日志位于 `/home/wuyifan/egonet_vitpose_throughput_20261007/g2_2gpu_*provider*_50.*`。 + +**正式训练边界:**`formal_v2` 仍在按原 reader、预取 2 运行。`train.py`/`data.py` 的哈希被写入 checkpoint 的 provenance,resume 和 eval 均严格校验;训练中热改会破坏这一合同。要采纳优化,需先在 G1 六卡用当前 worker 内裁剪路径做匹配 pilot,再新建版本从头重启,或在 5K 完整 checkpoint 后建立明确的 IO-only provenance amendment;不能悄悄替换当前运行中的代码。H2O RGB-only 跳过 depth 解码仍只是另一个候选,尚未验证逐字段等价与整步收益。 + +## G1 匹配测试与独立重启(同日 12:48 HKT) + +用户确认暂停 `formal_v2` 做 IO 测试。旧 controller 与六个训练 rank 已退出;最后写入的日志为 update 1,025,没有正式 checkpoint(首次保存点为 5K),旧日志和 smoke 权重均保留。上述“仍在运行”描述是测试前状态,以本节为准。 + +停训后 G1 GPU 3 被其他用户的任务占用,因此不能声称已做六卡测试。G1 同机使用 GPU 0/1/2/4 跑了 32 步匹配 pilot,前 2 步 warmup、后 30 步统计;每卡 15 clip,global batch 60,三源配比、T8、三档分辨率、完整 loss/反传/AdamW/裁剪及 worker 内裁剪均不变。ViTPose-L 最后两层可训练,与长期训练阶段相同。原始 JSON 为 `g1_4gpu_standard_p2_30_20261007.json` 和 `g1_4gpu_handonly_p4_30_20261007.json`。 + +| G1 四卡配置 | 最慢 rank s/update | clips/s | rank 0 数据等待 s/update | +|---|---:|---:|---:| +| 原版 HOT3D reader、预取 2 | 6.665 | 9.00 | 2.730 | +| hand-only reader、预取 4 | **3.670** | **16.35** | **0.390** | + +本组在同一 global batch 下步时缩短 44.9%,吞吐提高 1.82 倍。逐步 loss 的最大绝对差为 0.00060,pre-clip grad norm 最大差约 1.46;不将此 pilot 用作精度结论。另以实际 v2/v3 dataset 入口逐字段比较 10 个不同 HOT3D 录制段,Aria/Quest3 各 5 条、覆盖全部六种 headset/分辨率组合,全部零容差一致;脚本和日志为 `verify_v3_reader_equivalence_20261007.py/.log`。相关单元测试 7/7 通过,v3 provenance 与视觉权重哈希合同通过。 + +独立代码位于 `experiments/vitpose_mot_io_v3/`:只改 HOT3D provider 与预取 4,使用新的实验名和 `smoke_io_v3`,保留原版代码不变。新 controller 在 `egonet_vitpose_mot_io_v3` 会话中,对应 `formal_io_v3/`;截至本节记录时处于 `waiting_for_idle_gpus` 的 smoke 门禁,**尚未开始新训练、尚无新权重**。按用户后续确认,controller 已改为六张卡全部空闲后才做六卡 2-step smoke,再做三源预评估,并在六卡再次空闲后从 step 0 正式训练;不会停止或占用其他用户的任务。四卡加速幅度不是六卡实测承诺,待六卡可用后仍要以正式日志验证稳定吞吐。 diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/README.md b/home/wuyifan/EgoNet_train_20261008/experiments/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b391f3fd75f0983ddb63be489d0396513eaff3c3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/README.md @@ -0,0 +1,3 @@ +# Experiment source snapshots + +Each directory preserves one historical training or diagnostic stage. Imports and absolute paths reflect the run as executed; read `../REVIEW_GUIDE.md` before attempting to rerun them. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/README.md b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e559eae259615d71e8280f732e001246fc129afc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/README.md @@ -0,0 +1,48 @@ +# A7 near-pi rotation fix (2026-09-30) + +## Outcome + +The near-180-degree `matrix_to_axis_angle` failure is fixed in a **versioned code copy**. A versioned canonical-label cache on G2 has passed the full 380-recording audit. The original G2 V5 source, native cache, G1 fitted checkpoints, and controller were not overwritten. **No model training was launched.** + +The G2 artifacts are: + +- Patched model/data code: `/home/wuyifan/a7_rotation_fix_20260930_code` +- Migrated native cache, all canonical labels, and receipts: `/home/wuyifan/a7_canonical_gt_rotationfix_20260930` +- Original V5 archive remains `/home/wuyifan/a7_canonical_gt_v5_20260929` + +The new `matrix_to_axis_angle` uses the largest-magnitude quaternion component rather than dividing the antisymmetric matrix terms by a near-zero sine. The patched file is `a7_rotation_fix_20260930_code/src/foundation_hand/geometry/rotations.py`. The original file SHA-256 remains `35b98d14...`; the versioned fix is `25aae1c6...`. + +## Migration + +An official-annotation rotation scan found 176 valid left-hand frames and 96 valid right-hand frames with old root-rotation error above **0.01 degrees**, across 133 ARCTIC recordings. The worst old right-hand error was 2.887 degrees; the new conversion's error on every valid ARCTIC frame was below 0.001 degrees. Only the affected 272 `pose[..., :3]` values were replaced. The original source vertices, joints, 2D keypoints, K, masks, frame IDs, and annotation indices remained byte-identical within each migrated file. Unaffected native cache files retain their original paths and hashes. + +The G1 left-hand fit files are reused unchanged because their optimization targets (source vertices/joints, valid-frame selection, and original 2D/K) did not change. Their **original G1 receipts and old native-file hashes remain intact**; `migration.json` explicitly maps old to new native hashes. No receipt was relabeled to pretend a new fit occurred. + +## Verification + +| Gate | Result | +| --- | ---: | +| Versioned native migrations | 133/133 files, 272/272 selected valid-hand frames | +| Canonical label generation and saved-file roundtrip | 380/380 recordings | +| G2 independent left-fit geometry gates | 11/11 subjects passed, unchanged four fitting residuals | +| Full right-hand native compatibility | maximum vertex error **0.0244 mm**, below 1 mm gate | +| ARCTIC native parameter projection above 0.1 px | **0** left, **0** right | +| ARCTIC maximum native projection error | 0.0149 px left, 0.0130 px right | +| Actual canonical reader smoke | affected ARCTIC frame 524 tile and H2O tile passed; source 2D/K unchanged | +| G2 canonical unit tests | 20 passed | +| Versioned rotation/HOT3D tests | 4 passed | + +The 29,156 original training T=8 tiles were previously checked against native frame IDs, quality masks and ARCTIC annotation indices. Those fields are unchanged by this migration. `audit.json` records `ready_for_training: true` **for the completed label-cache audit only**; it is not a controller launch or an official benchmark result. + +## Remaining Training Boundary + +The original V5 `controller.py` and default `common.ExpertDataset` still point to the original V5 cache. Do **not** restart that controller to train from this new cache. Before training, register a separate versioned training root that selects the patched code and new label inventory, then run its GPU contract, training-loader smoke, and resume checks. This turn intentionally stopped before training. + +## Evidence + +- `audit.json`: 380/380 labels, 192,148 fitted left frames, no failures. +- `migration.json`: exact source and migrated hashes for 133 changed native recordings. +- `native_projection.json`: all ARCTIC native 2D projection and mesh compatibility checks. +- `reader_smoke.json`: actual ARCTIC/H2O label-reader tiles. +- `rotation_migration_scan.json`: old/new official rotation error distribution. +- `migrate_native.py`, `run_audit.py`, `verify_native_projection.py`, `smoke_reader.py`: reproducible migration and audit code. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/migrate_native.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/migrate_native.py new file mode 100644 index 0000000000000000000000000000000000000000..8b572a1025227ab7c0a93860245ac382153d7289 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/migrate_native.py @@ -0,0 +1,116 @@ +"""Version only ARCTIC native records with material root-rotation conversion error.""" + +from collections import defaultdict +import json +from pathlib import Path +import sys + +sys.path.insert(0, "/home/wuyifan/a7_canonical_gt_v5_20260929") +from runtime import (CODE, axis_angle_to_matrix, matrix_to_axis_angle, np, + dump, save_npz, sha, tensor_hash, torch) +from scipy.spatial.transform import Rotation + +ROOT = Path(__file__).resolve().parent +OLD = Path("/home/wuyifan/a7_canonical_gt_v5_20260929/cache/native_inventory.json") +SCAN = Path("/home/wuyifan/a7_canonical_gt_v5_g1_audit_20260930/rotation_migration_scan.json") +THRESHOLD_DEG = .01 + + +def same(a, b): + return np.array_equal(a, b, equal_nan=True) if a.dtype.kind in "fc" else np.array_equal(a, b) + + +def main(): + original = json.loads(OLD.read_text()) + scan = json.loads(SCAN.read_text()) + rotations = CODE / "src/foundation_hand/geometry/rotations.py" + if "a7_rotation_fix_20260930_code" not in str(CODE): + raise RuntimeError("versioned stable rotation implementation is not active") + grouped = defaultdict(list) + for row in scan["all_affected"]: + grouped[row["recording"]].append(row) + if set(grouped) != set(scan["changed_records"]): + raise RuntimeError("rotation scan recording coverage changed") + entries, modified = [], [] + for entry in original["entries"]: + if entry["recording"] not in grouped: + entries.append(entry.copy()) + continue + if entry["source"] != "ARCTIC" or sha(entry["path"]) != entry["sha256"]: + raise RuntimeError(f"changed/incorrect source cache: {entry['recording']}") + inputs = list(entry["annotation_inputs"]) + for path, expected in entry["annotation_inputs"].items(): + if sha(path) != expected: + raise RuntimeError(f"official annotation input changed: {path}") + mano = np.load(next(p for p in inputs if p.endswith(".mano.npy")), allow_pickle=True).item() + camera = np.load(next(p for p in inputs if p.endswith(".egocam.dist.npy")), allow_pickle=True).item() + with np.load(entry["path"], allow_pickle=False) as payload: + arrays = {name: payload[name].copy() for name in payload.files} + previous = arrays["pose"].copy() + chosen = set() + old_errors, new_errors = [], [] + for row in grouped[entry["recording"]]: + frame, side = row["index"], 0 if row["side"] == "left" else 1 + if (frame, side) in chosen or int(arrays["frame_ids"][frame]) != row["frame_id"] or not arrays["hand"][frame, side]: + raise RuntimeError("rotation patch frame/hand identity mismatch") + chosen.add((frame, side)) + annotation = int(arrays["annotation_indices"][frame]) + raw = torch.from_numpy(mano[row["side"]]["rot"][annotation].copy()).double() + camera_R = torch.from_numpy(camera["R_k_cam_np"][annotation].copy()).double() + official = camera_R @ axis_angle_to_matrix(raw) + repaired = matrix_to_axis_angle(official) + old_R = axis_angle_to_matrix(torch.from_numpy(previous[frame, side, :3]).double()) + old_error = float(Rotation.from_matrix((old_R @ official.T).numpy()).magnitude() * 180 / np.pi) + new_error = float(Rotation.from_matrix((axis_angle_to_matrix(repaired) @ official.T).numpy()).magnitude() * 180 / np.pi) + if abs(old_error - row["old_error_deg"]) > 1e-5 or old_error <= THRESHOLD_DEG or new_error > .001: + raise RuntimeError(f"rotation scan/reconstruction mismatch: {entry['recording']} frame {frame}") + arrays["pose"][frame, side, :3] = repaired.numpy() + old_errors.append(old_error) + new_errors.append(new_error) + pose_mask = np.ones(previous.shape, dtype=bool) + for frame, side in chosen: + pose_mask[frame, side, :3] = False + if not same(previous[pose_mask], arrays["pose"][pose_mask]): + raise RuntimeError("nonselected pose parameter changed") + path = ROOT / "cache/native" / Path(entry["path"]).name + save_npz(path, **arrays) + with np.load(path, allow_pickle=False) as saved: + if set(saved.files) != set(arrays): + raise RuntimeError("migrated cache schema changed") + for name in arrays: + if not same(saved[name], arrays[name]): + raise RuntimeError(f"migrated cache roundtrip changed: {name}") + if name != "pose": + with np.load(entry["path"], allow_pickle=False) as source: + if not same(saved[name], source[name]): + raise RuntimeError(f"source GT observation/mask changed: {name}") + updated = {**entry, "path": str(path), "sha256": sha(path), + "target_sha256": tensor_hash(arrays), "upstream_path": entry["path"], + "upstream_sha256": entry["sha256"], "rotation_fix_frames": len(chosen)} + entries.append(updated) + modified.append({"source": entry["source"], "recording": entry["recording"], + "old_sha256": entry["sha256"], "new_sha256": updated["sha256"], + "frames": len(chosen), "old_max_error_deg": max(old_errors), + "new_max_error_deg": max(new_errors)}) + if len(modified) % 10 == 0: + print(json.dumps({"phase": "native_migration", "records": len(modified), + "expected": len(grouped)}), flush=True) + if len(modified) != len(grouped) or sum(row["frames"] for row in modified) != len(scan["all_affected"]): + raise RuntimeError("rotation migration incomplete") + migrated = {**original, "entries": entries, "rotation_fix": { + "upstream_native_inventory_sha256": sha(OLD), + "rotation_implementation": str(rotations), "rotation_implementation_sha256": sha(rotations), + "scan_sha256": sha(SCAN), "threshold_deg": THRESHOLD_DEG, + "modified_records": len(modified), "modified_valid_hand_frames": len(scan["all_affected"]), + "official_gt_geometry_2d_K_masks_unchanged": True}} + dump(ROOT / "cache/native_inventory.json", migrated) + dump(ROOT / "migration.json", {"complete": True, + "new_native_inventory_sha256": sha(ROOT / "cache/native_inventory.json"), + "upstream_native_inventory_sha256": sha(OLD), "records": modified, + "code_sha256": sha(rotations), "scan_sha256": sha(SCAN)}) + print(json.dumps({"phase": "migration_complete", "records": len(modified), + "valid_hand_frames": len(scan["all_affected"])}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/run_audit.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/run_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..4d11c419deda0dbc66212ba9d14b579377ad9827 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/run_audit.py @@ -0,0 +1,239 @@ +"""Audit G1 corrected-left fits against immutable G2 V5 training inputs. + +This is deliberately separate from the G2 controller: it never starts training +or changes the original V5 cache. G1 receipt hashes remain attributable to G1. +""" + +from collections import defaultdict +import argparse +import json +from pathlib import Path +import sys + +ORIGINAL = Path("/home/wuyifan/a7_canonical_gt_v5_20260929") +STAGE = Path(__file__).resolve().parent +sys.path.insert(0, str(ORIGINAL)) + +from runtime import (CODE, CONFIG, MANO_ROOT, ManoCameraLayer, axis_angle_to_matrix, + code_hashes, dump, geometry, np, save_npz, sha, stats, torch) +from audit_cache import inspect_fit, verify_adapter_targets +from fit_cache import load_subject +from fit_quality import geometry_gate, inspect_geometry +from native_cache import inventory + + +def fail(message): + raise RuntimeError(message) + + +def preflight(): + g2_path = ORIGINAL / "cache/native_inventory.json" + g1_path = STAGE / "g1_native_inventory.json" + g2 = json.loads(g2_path.read_text()) + migrated = json.loads((STAGE / "cache/native_inventory.json").read_text()) + migration = json.loads((STAGE / "migration.json").read_text()) + g1 = json.loads(g1_path.read_text()) + fitted_audit = json.loads((STAGE / "g1_fit_only_audit.json").read_text()) + g1_config = json.loads((STAGE / "g1_config.json").read_text()) + if g2["code_sha256"] != code_hashes() or g2["pilot"] or g1["pilot"]: + fail("G2 native cache/code registration mismatch or pilot input") + if not fitted_audit["fit_only_complete"] or fitted_audit["failures"]: + fail("G1 full fit did not pass its own geometry audit") + if g1_config["fitting"] != CONFIG["fitting"] or g1_config["target_contract"] != CONFIG["target_contract"]: + fail("G1/G2 fitting or label contract differs") + for key in ("fit_cache.py", "fit_quality.py", "native_cache.py", "MANO_LEFT.pkl", "MANO_RIGHT.pkl"): + if g1["code_sha256"][key] != g2["code_sha256"][key]: + fail(f"G1/G2 fitting dependency differs: {key}") + for key in ("physical_frames", "eligible_left_frames", "training_manifests"): + if g1[key] != g2[key]: + fail(f"G1/G2 inventory metadata differs: {key}") + by_key = {(row["source"], row["recording"]): row for row in g2["entries"]} + if len(g1["entries"]) != len(g2["entries"]) or len(by_key) != len(g2["entries"]): + fail("physical recording inventory count differs") + for g1_entry in g1["entries"]: + key = g1_entry["source"], g1_entry["recording"] + original = by_key.get(key) + if original is None: + fail(f"unexpected G1 recording: {key}") + for name in ("subject", "sha256", "target_sha256", "frames", "tiles", + "left_frames", "right_frames", "quality_masks", "annotation_inputs"): + if g1_entry[name] != original[name]: + fail(f"G1/G2 physical recording mismatch: {key}:{name}") + if g1_entry["upstream_path"] != original["path"]: + fail(f"G1/G2 native path provenance mismatch: {key}") + for source, manifest in g2["training_manifests"].items(): + if sha(manifest["path"]) != manifest["sha256"]: + fail(f"G2 training manifest modified: {source}") + if len(fitted_audit["subjects"]) != 11: + fail("G1 subject fit audit incomplete") + rotation_code = CODE / "src/foundation_hand/geometry/rotations.py" + if ("a7_rotation_fix_20260930_code" not in str(CODE) + or migrated["rotation_fix"]["rotation_implementation_sha256"] != sha(rotation_code) + or migration["code_sha256"] != sha(rotation_code) + or migration["new_native_inventory_sha256"] != sha(STAGE / "cache/native_inventory.json") + or migration["upstream_native_inventory_sha256"] != sha(g2_path) + or not migration["complete"]): + fail("rotation-fix implementation or migration provenance mismatch") + old_by_key = {(row["source"], row["recording"]): row for row in g2["entries"]} + if len(migrated["entries"]) != len(g2["entries"]): + fail("migrated native cache recording count differs") + for row in migrated["entries"]: + old = old_by_key[row["source"], row["recording"]] + for name in ("source", "recording", "subject", "frames", "tiles", "left_frames", "right_frames", + "quality_masks", "annotation_inputs"): + if row[name] != old[name]: + fail(f"migrated native identity changed: {row['recording']}:{name}") + if row["sha256"] != old["sha256"]: + if row["upstream_sha256"] != old["sha256"] or row["upstream_path"] != old["path"]: + fail(f"migrated native provenance changed: {row['recording']}") + elif row["path"] != old["path"]: + fail(f"unmodified native recording unexpectedly copied: {row['recording']}") + return migrated, g1, fitted_audit, g2 + + +def exact_equal(old, new): + return np.array_equal(old, new, equal_nan=True) if old.dtype.kind in "fc" else np.array_equal(old, new) + + +def check_record_arrays(original, adapted, positions): + if set(original) != set(adapted): + fail("label array schema changed") + for name in original: + if name not in ("pose", "beta", "wrist", "vertices", "joints"): + if not exact_equal(original[name], adapted[name]): + fail(f"source observation or mask changed: {name}") + elif not exact_equal(original[name][:, 1], adapted[name][:, 1]): + fail(f"right-hand label changed: {name}") + elif name in ("pose", "beta", "wrist", "vertices", "joints"): + untouched = np.ones(len(original[name]), dtype=bool) + untouched[positions] = False + if not exact_equal(original[name][untouched, 0], adapted[name][untouched, 0]): + fail(f"unselected left-hand label changed: {name}") + + +def main(geometry_only=False): + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + g2, g1, g1_audit, original = preflight() + entries = g2["entries"] + original_by_key = {(row["source"], row["recording"]): row for row in original["entries"]} + groups = defaultdict(list) + for row in entries: + groups[(row["source"], row["subject"])].append(row) + checks = verify_adapter_targets(STAGE, entries) + layer = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=True).double().to("cuda").eval() + subject_results, label_entries, failures = {}, [], [] + right_error_max = 0.0 + for (source, subject), records in sorted(groups.items()): + fit_name = f"{source}_{subject}" + fit_path = STAGE / "fits" / (fit_name + ".npz") + receipt = json.loads(fit_path.with_suffix(".json").read_text()) + identity = {row["recording"]: original_by_key[row["source"], row["recording"]]["sha256"] for row in records} + if (not receipt["optimization_complete"] or receipt["sha256"] != sha(fit_path) + or receipt["native_sha256"] != identity or receipt["code_sha256"] != g1["code_sha256"] + or g1_audit["subjects"][fit_name]["sha256"] != receipt["sha256"]): + fail(f"G1 fit receipt mismatch: {fit_name}") + data = load_subject(records) + with np.load(fit_path, allow_pickle=False) as payload: + fit = {name: payload[name].copy() for name in payload.files} + if (fit["pose"].shape != (len(data["pose"]), 48) or fit["wrist"].shape != (len(data["pose"]), 3) + or fit["beta"].shape != (10,) or not np.isfinite(fit["pose"]).all() + or not np.isfinite(fit["wrist"]).all() or not np.isfinite(fit["beta"]).all() + or not np.array_equal(fit["record_index"], data["record_index"]) + or not np.array_equal(fit["frame_index"], data["frame_index"])): + fail(f"G1 fit physical-frame coverage mismatch: {fit_name}") + diagnostics = inspect_fit(layer.layers[0], data, fit, "cuda") + baseline, _ = inspect_geometry(layer.layers[0], data, data["pose"], data["beta"], data["wrist"], "cuda") + summary, details = inspect_geometry(layer.layers[0], data, + torch.from_numpy(fit["pose"]), torch.from_numpy(fit["beta"]), + torch.from_numpy(fit["wrist"]), "cuda") + quality = geometry_gate(summary, details, baseline, CONFIG["fitting"]) + if not quality["geometry_review_pass"]: + failures.extend(f"{fit_name}: {reason}" for reason in quality["failures"]) + if diagnostics["conditional_wrist_identity_error_mm"] > 1e-5: + failures.append(f"{fit_name}: conditional wrist placement differs") + for metric in ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", "pa_mpjpe_mm"): + delta = abs(summary[metric]["mean"] - g1_audit["subjects"][fit_name]["four_mm"][metric]["mean"]) + if delta > 1e-4: + failures.append(f"{fit_name}: G1/G2 {metric} regeneration differs by {delta:.6f} mm") + subject_results[fit_name] = {"frames": len(fit["pose"]), "four_mm": summary, + "geometry_review": quality, "diagnostics": diagnostics} + print(json.dumps({"phase": "subject_geometry", "subject": fit_name, + "frames": len(fit["pose"]), "mpvpe_mm": summary["mpvpe_mm"]["mean"], + "failures": len(failures)}), flush=True) + if geometry_only: + continue + if failures: + break + for record_index, entry in enumerate(records): + with np.load(entry["path"], allow_pickle=False) as payload: + original = {key: payload[key].copy() for key in payload.files} + arrays = {key: value.copy() for key, value in original.items()} + selected = np.flatnonzero(fit["record_index"] == record_index) + positions = fit["frame_index"][selected] + if not np.array_equal(np.sort(positions), np.flatnonzero(arrays["hand"][:, 0])): + fail(f"left valid-frame coverage failed: {entry['recording']}") + arrays["pose"][positions, 0] = fit["pose"][selected] + arrays["beta"][positions, 0] = fit["beta"][None] + arrays["wrist"][positions, 0] = fit["wrist"][selected] + for first in range(0, len(arrays["pose"]), 128): + last = min(first + 128, len(arrays["pose"])) + with torch.no_grad(): + v, j = layer(axis_angle_to_matrix(torch.from_numpy(arrays["pose"][first:last]).to("cuda").reshape(-1, 2, 16, 3)), + torch.from_numpy(arrays["beta"][first:last]).to("cuda"), + torch.from_numpy(arrays["wrist"][first:last]).to("cuda")) + right = torch.from_numpy(original["vertices"][first:last, 1]).to("cuda") + valid = torch.from_numpy(original["hand"][first:last, 1]).to("cuda") + error = torch.linalg.vector_norm(v[:, 1] - right, dim=-1).amax(-1) * 1000 + if valid.any(): + right_error_max = max(right_error_max, float(error[valid].max())) + if bool((error[valid] > 1).any()): + failures.append(f"{entry['recording']}: right-hand native compatibility >1 mm ({float(error[valid].max()):.3f} mm)") + break + active = original["hand"][first:last, 0] + arrays["vertices"][first:last, 0][active] = v[:, 0].cpu().numpy()[active] + arrays["joints"][first:last, 0][active] = j[:, 0].cpu().numpy()[active] + if failures: + break + check_record_arrays(original, arrays, positions) + label_path = STAGE / "labels" / Path(entry["path"]).name + save_npz(label_path, **arrays) + with np.load(label_path, allow_pickle=False) as saved: + for name in arrays: + if not exact_equal(arrays[name], saved[name]): + fail(f"saved label roundtrip differs: {entry['recording']}:{name}") + label_entries.append({**entry, "native_path": entry["path"], + "native_sha256": entry["sha256"], "path": str(label_path), + "sha256": sha(label_path), "fit_sha256": receipt["sha256"]}) + print(json.dumps({"phase": "subject_labels", "subject": fit_name, + "records_done": len(label_entries), "right_max_mm": right_error_max, + "failures": len(failures)}), flush=True) + if failures: + break + ready = not geometry_only and not failures and len(label_entries) == len(entries) and len(subject_results) == len(groups) + result = {"ready_for_training": ready, "source": "G1 fit on G2 original V5 native cache", + "original_g2_cache_unchanged": True, "g1_inventory_sha256": sha(STAGE / "g1_native_inventory.json"), + "g2_inventory_sha256": sha(ORIGINAL / "cache/native_inventory.json"), + "migrated_inventory_sha256": sha(STAGE / "cache/native_inventory.json"), + "g1_fit_audit_sha256": sha(STAGE / "g1_fit_only_audit.json"), + "records": len(label_entries), "expected_records": len(entries), + "fitted_left_frames": sum(value["frames"] for value in subject_results.values()), + "right_native_max_mm": right_error_max, "adapter_checks": checks, + "subjects": subject_results, "failures": failures} + dump(STAGE / ("geometry_only_audit.json" if geometry_only else "audit.json"), result) + if ready: + dump(STAGE / "label_inventory.json", { + "entries": label_entries, "target_contract": CONFIG["target_contract"], + "native_inventory_sha256": sha(STAGE / "cache/native_inventory.json"), + "g1_fit_audit_sha256": sha(STAGE / "g1_fit_only_audit.json"), + "g1_code_sha256": g1["code_sha256"], "g2_code_sha256": code_hashes(), + "rotation_fix_implementation_sha256": sha(CODE / "src/foundation_hand/geometry/rotations.py")}) + print(json.dumps({"phase": "final", "ready_for_training": ready, + "records": len(label_entries), "failures": failures}), flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--geometry-only", action="store_true") + main(parser.parse_args().geometry_only) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/smoke_reader.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/smoke_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..20bd76b07141f83d24c80d01063a2b0004641662 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/smoke_reader.py @@ -0,0 +1,75 @@ +"""Exercise the actual canonical label reader on affected ARCTIC and H2O tiles.""" + +import json +from pathlib import Path +import sys + +sys.path.insert(0, "/home/wuyifan/a7_canonical_gt_v5_20260929") +from runtime import MANO_ROOT, ManoCameraLayer, np, torch, dump +from native_cache import inventory, record_key +from targets import CanonicalLabels, native_targets +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.h2o_dataset import H2OCam4Dataset + + +def inspect(source, row, stage, source_mano): + name = source.lower() + "_reader_smoke.jsonl" + manifest = stage / name + manifest.write_text(json.dumps(row) + "\n") + if source == "ARCTIC": + native = ARCTICClipDataset(manifest, MANO_ROOT, (512, 896), hand_valid_policy="visible_mesh") + else: + native = H2OCam4Dataset("/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, + (512, 896), (8,), (1,), window_step=8, allow_partial=False) + sample = native_targets(source, native, row, native[0], source_mano) + original = {key: sample[key].clone() for key in ("joint2d", "joint2d_valid", "K", "vertices_camera")} + labels = CanonicalLabels(source, [row], cache=stage) + updated = labels.apply(sample, row, native) + for key in ("joint2d", "K"): + if not torch.allclose(updated[key], original[key], atol=0, rtol=0, equal_nan=True): + raise RuntimeError(f"reader changed original {key}") + if bool((updated["joint2d_valid"] & ~original["joint2d_valid"]).any()): + raise RuntimeError("reader expanded source 2D supervision mask") + if not bool((updated["mano_target_contract_version"] == 3).all()): + raise RuntimeError("reader target contract differs") + entry = labels.entries[record_key(source, row)] + with np.load(entry["path"], allow_pickle=False) as payload: + ids = np.asarray(row["expected_frame_ids"]) + at = np.searchsorted(payload["frame_ids"], ids) + if not np.array_equal(payload["frame_ids"][at], ids): + raise RuntimeError("reader tile-to-label identity mismatch") + expected_pose = torch.from_numpy(payload["pose"][at].copy()).float() + expected_beta = torch.from_numpy(payload["beta"][at].copy()).float() + expected_wrist = torch.from_numpy(payload["wrist"][at].copy()).float() + expected_vertices = torch.from_numpy(payload["vertices"][at].copy()).float() + for name, expected in (("mano_pose", expected_pose), ("mano_shape", expected_beta), + ("wrist_root_translation", expected_wrist)): + if not torch.allclose(updated[name], expected, atol=0, rtol=0, equal_nan=True): + raise RuntimeError(f"reader loaded wrong {name}") + valid = updated["vertices_valid"].bool() + error = torch.linalg.vector_norm(updated["vertices_camera"] - expected_vertices, dim=-1).amax(-1) * 1000 + if bool((error[valid] > 1).any()): + raise RuntimeError("reader mesh differs from saved canonical label") + right = valid[:, 1] + right_error = torch.linalg.vector_norm(updated["vertices_camera"][:, 1] - original["vertices_camera"][:, 1], dim=-1).amax(-1) * 1000 + if bool((right_error[right] > 1).any()): + raise RuntimeError("reader right hand disagrees with original source GT") + return {"source": source, "recording": record_key(source, row), + "frame_ids": row["expected_frame_ids"], "valid_hand_frames": int(valid.sum()), + "max_saved_mesh_difference_mm": float(error[valid].max()), + "max_right_source_mesh_difference_mm": float(right_error[right].max()) if right.any() else None} + + +def main(): + stage = Path(__file__).resolve().parent + groups, _ = inventory() + source_mano = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=False).eval() + arctic = next(row for row in groups["ARCTIC", "s07/phone_grab_01"] if 524 in row["expected_frame_ids"]) + h2o = next(rows[0] for (source, _), rows in groups.items() if source == "H2O") + results = [inspect("ARCTIC", arctic, stage, source_mano), inspect("H2O", h2o, stage, source_mano)] + dump(stage / "reader_smoke.json", {"pass": True, "tiles": results}) + print(json.dumps({"pass": True, "tiles": results})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/verify_native_projection.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/verify_native_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..42dcd30fefe0e743c457344b88ba0bca7743cb02 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_cache/verify_native_projection.py @@ -0,0 +1,65 @@ +"""Check migrated native parameters against unchanged source 3D/2D targets.""" + +from collections import defaultdict +import json +from pathlib import Path +import sys + +sys.path.insert(0, "/home/wuyifan/a7_canonical_gt_v5_20260929") +from runtime import MANO_ROOT, ManoCameraLayer, axis_angle_to_matrix, np, project_points, torch, dump + + +def main(): + torch.set_num_threads(2) + stage = Path(__file__).resolve().parent + inventory = json.loads((stage / "cache/native_inventory.json").read_text()) + mano = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=False).double().to("cuda").eval() + summary = defaultdict(lambda: {"valid_frames": 0, "projection_above_0_1px": 0, + "max_projection_px": 0.0, "max_vertex_mm": 0.0}) + outliers = [] + for number, entry in enumerate(inventory["entries"]): + if entry["source"] != "ARCTIC": + continue + with np.load(entry["path"], allow_pickle=False) as payload: + arrays = {key: payload[key].copy() for key in + ("pose", "beta", "wrist", "vertices", "joint2d", "joint2d_valid", "K", "hand", "frame_ids")} + for first in range(0, len(arrays["pose"]), 128): + last = min(first + 128, len(arrays["pose"])) + with torch.no_grad(): + v, j = mano(axis_angle_to_matrix(torch.from_numpy(arrays["pose"][first:last]).to("cuda").reshape(-1, 2, 16, 3)), + torch.from_numpy(arrays["beta"][first:last]).to("cuda"), + torch.from_numpy(arrays["wrist"][first:last]).to("cuda")) + uv, _ = project_points(j, torch.from_numpy(arrays["K"][first:last]).to("cuda")) + projection = torch.linalg.vector_norm(uv - torch.from_numpy(arrays["joint2d"][first:last]).to("cuda"), dim=-1).cpu().numpy() + mesh = (torch.linalg.vector_norm(v - torch.from_numpy(arrays["vertices"][first:last]).to("cuda"), dim=-1).amax(-1) * 1000).cpu().numpy() + valid_2d = arrays["joint2d_valid"][first:last] + valid_hand = arrays["hand"][first:last] + for side, name in enumerate(("left", "right")): + data = summary[name] + active = valid_hand[:, side] + if active.any(): + data["max_vertex_mm"] = max(data["max_vertex_mm"], float(mesh[active, side].max())) + count = valid_2d[:, side].sum(-1) + per_frame = (projection[:, side] * valid_2d[:, side]).sum(-1) / np.maximum(count, 1) + usable = active & (count > 0) + data["valid_frames"] += int(usable.sum()) + if usable.any(): + data["max_projection_px"] = max(data["max_projection_px"], float(per_frame[usable].max())) + flagged = np.flatnonzero(usable & (per_frame > .1)) + data["projection_above_0_1px"] += len(flagged) + for local in flagged: + outliers.append({"recording": entry["recording"], "side": name, + "frame_id": int(arrays["frame_ids"][first + local]), + "projection_px": float(per_frame[local]), + "max_vertex_mm": float(mesh[local, side])}) + if (number + 1) % 40 == 0: + print(json.dumps({"records_scanned": number + 1, "outliers": len(outliers)}), flush=True) + report = {"by_side": dict(summary), "outliers": outliers, + "source_2d_K_vertices_masks_unchanged": True} + dump(stage / "native_projection.json", report) + print(json.dumps({"phase": "native_projection_done", "by_side": report["by_side"], + "outliers": len(outliers), "worst": sorted(outliers, key=lambda x: x["projection_px"], reverse=True)[:5]}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/RESULTS.md b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/RESULTS.md new file mode 100644 index 0000000000000000000000000000000000000000..e1f7fefba3716ce798287eba4bc2ee0d25bccb31 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/RESULTS.md @@ -0,0 +1,39 @@ +# A7 Canonical Approximate GT: Matched Retraining + +Same original source-native targets and GT-defined denominators for every model. +All four primary metrics are mm; MANO 2D is auxiliary px. Previously inspected panels, not official test. +Historical A7 scores used different label/coverage contracts and are not directly comparable. + +| Source | Input | Model | Abs MPJPE | RR MPJPE | MPVPE | PA MPJPE | MANO 2D px | +|---|---|---|---:|---:|---:|---:|---:| +| H2O | rgb_depth_k | S4_RGB | 21.562 | 13.238 | 21.271 | 6.640 | 11.327 | +| H2O | rgb_depth_k | S4_same_input | 20.444 | 13.244 | 20.157 | 6.671 | 10.999 | +| H2O | rgb_depth_k | old_A7 | 20.917 | 13.171 | 20.621 | 6.639 | 11.029 | +| H2O | rgb_depth_k | new_A7 | 20.873 | 12.397 | 20.641 | 5.774 | 10.825 | +| ARCTIC | rgb_k | S4_RGB | 37.922 | 20.881 | 37.513 | 10.017 | 21.599 | +| ARCTIC | rgb_k | S4_same_input | 37.933 | 21.066 | 37.515 | 10.051 | 21.265 | +| ARCTIC | rgb_k | old_A7 | 39.431 | 20.912 | 38.996 | 10.007 | 21.510 | +| ARCTIC | rgb_k | new_A7 | 39.345 | 21.089 | 38.903 | 10.010 | 21.507 | +| H2O | rgb_k | S4_RGB | 21.562 | 13.238 | 21.271 | 6.640 | 11.327 | +| H2O | rgb_k | S4_same_input | 21.410 | 13.264 | 21.122 | 6.678 | 11.107 | +| H2O | rgb_k | old_A7 | 21.063 | 13.219 | 20.760 | 6.644 | 10.913 | +| H2O | rgb_k | new_A7 | 20.489 | 12.414 | 20.270 | 5.767 | 10.222 | +| HOT3D | rgb_k | S4_RGB | 51.661 | 23.684 | 51.343 | 8.661 | 13.972 | +| HOT3D | rgb_k | S4_same_input | 51.698 | 23.645 | 51.402 | 8.637 | 13.501 | +| HOT3D | rgb_k | old_A7 | 48.139 | 23.765 | 47.830 | 8.642 | 13.966 | +| HOT3D | rgb_k | new_A7 | 48.284 | 23.785 | 47.978 | 8.643 | 13.967 | +| ARCTIC | rgb | S4_RGB | 37.922 | 20.881 | 37.513 | 10.017 | 21.599 | +| ARCTIC | rgb | S4_same_input | 37.922 | 20.881 | 37.513 | 10.017 | 21.599 | +| ARCTIC | rgb | old_A7 | 37.922 | 20.881 | 37.513 | 10.017 | 21.599 | +| ARCTIC | rgb | new_A7 | 37.922 | 20.881 | 37.513 | 10.017 | 21.599 | +| H2O | rgb | S4_RGB | 21.562 | 13.238 | 21.271 | 6.640 | 11.327 | +| H2O | rgb | S4_same_input | 21.562 | 13.238 | 21.271 | 6.640 | 11.327 | +| H2O | rgb | old_A7 | 21.562 | 13.238 | 21.271 | 6.640 | 11.327 | +| H2O | rgb | new_A7 | 21.562 | 13.238 | 21.271 | 6.640 | 11.327 | +| HOT3D | rgb | S4_RGB | 51.661 | 23.684 | 51.343 | 8.661 | 13.972 | +| HOT3D | rgb | S4_same_input | 51.661 | 23.684 | 51.343 | 8.661 | 13.972 | +| HOT3D | rgb | old_A7 | 51.661 | 23.684 | 51.343 | 8.661 | 13.972 | +| HOT3D | rgb | new_A7 | 51.661 | 23.684 | 51.343 | 8.661 | 13.972 | + +Paired recording bootstrap intervals, side/device breakdowns and native GT hashes are retained in evaluations/. +Pure RGB remains frozen S4. Fixed budget is a controlled comparison, not a convergence claim. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/RUNNING.md b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/RUNNING.md new file mode 100644 index 0000000000000000000000000000000000000000..11414b991ed458dc939314f8aa944e8e6797988c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/RUNNING.md @@ -0,0 +1,15 @@ +# A7 rotation-fix six-GPU training + +Started on G2 at 2026-09-30 01:32 Hong Kong time. The durable controller PID is `3519533` and owns physical GPUs 0-5 through the FoundationHand GPU claim mechanism. This is a new registered run; the original V5 controller and caches were not restarted or overwritten. + +G2 root: `/home/wuyifan/a7_canonical_gt_rotationfix_train_6gpu_20260930` + +- `state.json`, `controller.log`: current stage and child process. +- `runs/K/metrics.jsonl`, `runs/D/metrics.jsonl`: per-update loss, grad norm, clipping, LR and source exposure. +- `runs/{K,D}/update_*.pt`: milestones 2,084, 4,167 and 8,334 updates. The parent S4 checkpoint remains unchanged. +- `evaluations/`: development/confirmation evaluations after the registered milestones. +- `RESULTS.md`: generated only after all seven confirmation panels complete. + +Recipe: K followed by D; six GPUs, global batch 12, two microbatches per rank, same optimizer, losses, source quotas, learning-rate schedule and 8,334-update budget as the four-GPU registered A7 recipe. The sole training-recipe change is `world_size: 4 -> 6`, so numerical updates are not expected to be bitwise identical to a four-GPU run. K source quota remains H2O:ARCTIC:HOT3D = 7:5:8. D uses H2O as registered. The model and supervised labels are the rotation-fixed versioned artifacts in `/home/wuyifan/a7_rotation_fix_20260930_code` and `/home/wuyifan/a7_canonical_gt_rotationfix_20260930`. + +Before formal training, 20 local canonical tests, the real GPU contract, K/D smoke plus H2O smoke evaluation, and the six-GPU continuous/split resume comparison passed. The resume test kept input ordering and RNG cursor exact, with model tolerance 1e-6. Formal K training began at 01:34 Hong Kong time. The controller is intentionally unattended and will fail closed into `failed_requires_diagnosis` if any later stage fails; it must not be restarted blindly over existing logs/checkpoints. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/audit_cache.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/audit_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..1306e17725b005fc3b45778f53b7fe6ba306dbf0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/audit_cache.py @@ -0,0 +1,215 @@ +"""Independent cache reconstruction, original-label checks and fail-closed gates.""" + +from collections import defaultdict +import argparse +import json +from pathlib import Path + +from runtime import (ROOT, CACHE, CONFIG, MANO_ROOT, torch, np, ManoCameraLayer, + geometry, axis_angle_to_matrix, project_points, code_hashes, + sha, dump, save_npz, stats) +from native_cache import inventory, record_key +from fit_cache import load_subject, optimal_wrist +from fit_quality import inspect_geometry, geometry_gate + + +def verify_adapter_targets(destination, entries): + from foundation_hand.data.arctic_dataset import ARCTICClipDataset + from foundation_hand.data.h2o_dataset import H2OCam4Dataset + from targets import native_targets + groups, _ = inventory() + source_mano = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=False).eval() + checks = [] + examples = {} + for entry in entries: + examples.setdefault((entry["source"], entry["subject"]), entry) + for (source, subject), entry in sorted(examples.items()): + row = groups[source, entry["recording"]][0] + manifest = destination / (source.lower() + "_" + subject + "_adapter_check.jsonl") + if not manifest.exists(): + manifest.write_text(json.dumps(row) + "\n") + if source == "ARCTIC": + native = ARCTICClipDataset(manifest, MANO_ROOT, (512, 896), hand_valid_policy="visible_mesh") + else: + native = H2OCam4Dataset("/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, + (512, 896), (8,), (1,), window_step=8, allow_partial=False) + sample = native_targets(source, native, row, native[0], source_mano) + with np.load(entry["path"], allow_pickle=False) as payload: + indices = np.searchsorted(payload["frame_ids"], row["expected_frame_ids"]) + if source == "ARCTIC" and not np.array_equal( + payload["annotation_indices"][indices], row["array_indices_0based"]): + raise RuntimeError("ARCTIC cached annotation indices disagree with image adapter") + comparisons = {} + for old, new in (("vertices", "vertices_camera"), ("joints", "joint3d_camera"), + ("wrist", "wrist_root_translation"), ("joint2d", "joint2d"), ("K", "K")): + cached = torch.from_numpy(payload[old][indices].copy()).float() + actual = sample[new] + mask = torch.isfinite(cached) & torch.isfinite(actual) + error = float((cached[mask] - actual[mask]).abs().max()) + threshold = .01 if old in ("joint2d", "K") else .00001 + if error > threshold: + raise RuntimeError(f"metadata/image adapter disagreement: {source}:{old} {error}") + comparisons[old] = error + checks.append({"source": source, "recording": entry["recording"], + "max_coordinate_difference": comparisons}) + return checks + + +def inspect_fit(layer, data, fit, device): + frames = len(fit["pose"]) + rho = frames / int(data["joint_valid"].sum()) + errors, wrist_errors, shifts, pose_shifts, projection_errors, gradients = [], [], [], [], [], [] + wrist_identity_errors = [] + shared_beta_gradient = torch.zeros(10, dtype=torch.float64) + for first in range(0, frames, 128): + last = min(first + 128, frames) + pose = torch.from_numpy(fit["pose"][first:last]).to(device).requires_grad_() + beta = torch.from_numpy(fit["beta"]).to(device).requires_grad_() + wrist = torch.from_numpy(fit["wrist"][first:last]).to(device).requires_grad_() + target_v, target_j = data["vertices"][first:last].to(device), data["joints"][first:last].to(device) + valid = data["joint_valid"][first:last].to(device) + v, j = geometry(layer, pose, beta, wrist) + with torch.no_grad(): + original_wrist = data["wrist"][first:last].to(device) + shift = wrist - original_wrist + conditional = optimal_wrist(v - shift[:, None], j - shift[:, None], + {"vertices": target_v, "joints": target_j, "joint_valid": valid, + "wrist": original_wrist}, rho) + wrist_identity_errors.append(float(torch.linalg.vector_norm(wrist - conditional, dim=-1).max()) * 1000) + loss = (((v - target_v) * 1000).square().mean() + + (((j - target_j) * 1000).square() * valid[..., None]).sum() * rho / (3 * len(v))) + pose_gradient, wrist_gradient, beta_gradient = torch.autograd.grad(loss, (pose, wrist, beta)) + shared_beta_gradient += beta_gradient.detach().cpu() * len(v) / frames + gradients.extend((pose_gradient.abs().amax(-1) * len(v)).detach().cpu().tolist()) + wrist_errors.append(float(wrist_gradient.abs().max()) * len(v)) + error = torch.linalg.vector_norm(v - target_v, dim=-1) * 1000 + for index in range(len(v)): + errors.append({"mean_vertex_mm": float(error[index].mean()), "max_vertex_mm": float(error[index].max()), + "record_index": int(fit["record_index"][first + index]), + "frame_index": int(fit["frame_index"][first + index])}) + shifts.extend((torch.linalg.vector_norm(wrist - data["wrist"][first:last].to(device), dim=-1) * 1000).detach().cpu().tolist()) + # Rotation-space adjustment avoids axis-angle wrap artifacts. + native_pose = data["pose"][first:last].to(device) + delta = axis_angle_to_matrix(pose[:, 3:].reshape(-1, 15, 3)) @ axis_angle_to_matrix(native_pose[:, 3:].reshape(-1, 15, 3)).transpose(-1, -2) + angles = torch.acos(((delta.diagonal(dim1=-2, dim2=-1).sum(-1) - 1) / 2).clamp(-1, 1)) + pose_shifts.extend(angles.square().mean(-1).sqrt().detach().cpu().tolist()) + uv, _ = project_points(j, data["K"][first:last].to(device)) + visible = data["joint2d_valid"][first:last].to(device) + projection_errors.extend(torch.linalg.vector_norm(uv - data["joint2d"][first:last].to(device), dim=-1)[visible].detach().cpu().tolist()) + return {"frames": frames, "mpvpe_mm": stats([row["mean_vertex_mm"] for row in errors]), + "max_vertex_mm": stats([row["max_vertex_mm"] for row in errors]), + "wrist_adjustment_mm": stats(shifts), "local_pose_adjustment_rms_rad": stats(pose_shifts), + "projection_disagreement_px": stats(projection_errors) if projection_errors else None, + "scaled_pose_gradient": stats(gradients), "free_wrist_gradient_max": max(wrist_errors), + "conditional_wrist_identity_error_mm": max(wrist_identity_errors), + "shared_beta_gradient_max": float(shared_beta_gradient.abs().max()), + "worst_frames": sorted(errors, key=lambda row: row["mean_vertex_mm"], reverse=True)[:10]} + + +def run(args): + destination = ROOT / "pilot/cache" if args.pilot else CACHE + native = json.loads((destination / "native_inventory.json").read_text()) + if native["code_sha256"] != code_hashes() or native["pilot"] != args.pilot: + raise RuntimeError("native cache/code registration mismatch") + entries = native["entries"] + adapter_checks = verify_adapter_targets(destination, entries) + groups = defaultdict(list) + for entry in entries: + groups[(entry["source"], entry["subject"])].append(entry) + layer = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=True).double().to("cuda").eval() + summaries, labels, failures = {}, [], [] + for (source, subject), records in sorted(groups.items()): + if not sum(record["left_frames"] for record in records): + continue + fit_path = destination / "fits" / (source + "_" + subject + ".npz") + receipt = json.loads(fit_path.with_suffix(".json").read_text()) + identities = {entry["recording"]: entry["sha256"] for entry in records} + if (not receipt["optimization_complete"] or receipt["sha256"] != sha(fit_path) + or receipt["code_sha256"] != code_hashes() or receipt["native_sha256"] != identities): + raise RuntimeError("missing/modified/incomplete subject fit") + data = load_subject(records) + with np.load(fit_path, allow_pickle=False) as payload: + fitted = {key: payload[key].copy() for key in payload.files} + if args.pilot: + for key in data: + data[key] = data[key][:32] + if (len(fitted["pose"]) != len(data["pose"]) + or fitted["beta"].shape != (10,) + or not np.array_equal(fitted["record_index"], data["record_index"]) + or not np.array_equal(fitted["frame_index"], data["frame_index"])): + raise RuntimeError("subject sharing or full physical-frame coverage failed") + result = inspect_fit(layer.layers[0], data, fitted, "cuda") + settings = CONFIG["fitting"] + baseline, _ = inspect_geometry(layer.layers[0], data, data["pose"], data["beta"], data["wrist"], "cuda") + summary, diagnostics = inspect_geometry(layer.layers[0], data, + torch.from_numpy(fitted["pose"]), torch.from_numpy(fitted["beta"]), + torch.from_numpy(fitted["wrist"]), "cuda") + quality = geometry_gate(summary, diagnostics, baseline, settings) + result.update(primary_geometry_mm=summary, unadapted_corrected_MANO=baseline, + geometry_review=quality, gradient_stationarity_is_diagnostic_only=True) + if not quality["geometry_review_pass"]: + failures.extend(f"{source}/{subject}: {reason}" for reason in quality["failures"]) + if result["conditional_wrist_identity_error_mm"] > 1e-5: + failures.append(f"{source}/{subject}: saved wrist differs from exact conditional placement") + summaries[source + "/" + subject] = result + if not args.pilot: + for record_index, entry in enumerate(records): + with np.load(entry["path"], allow_pickle=False) as payload: + arrays = {key: payload[key].copy() for key in payload.files} + selected = np.flatnonzero(fitted["record_index"] == record_index) + positions = fitted["frame_index"][selected] + if set(positions.tolist()) != set(np.flatnonzero(arrays["hand"][:, 0]).tolist()): + raise RuntimeError("a valid left hand was silently dropped") + arrays["pose"][positions, 0] = fitted["pose"][selected] + arrays["beta"][positions, 0] = fitted["beta"][None] + arrays["wrist"][positions, 0] = fitted["wrist"][selected] + for first in range(0, len(arrays["pose"]), 128): + last = first + 128 + with torch.no_grad(): + v, j = layer(axis_angle_to_matrix(torch.from_numpy(arrays["pose"][first:last]).to("cuda").reshape(-1, 2, 16, 3)), + torch.from_numpy(arrays["beta"][first:last]).to("cuda"), + torch.from_numpy(arrays["wrist"][first:last]).to("cuda")) + native_right = torch.from_numpy(arrays["vertices"][first:last, 1]).to("cuda") + right_error = torch.linalg.vector_norm(v[:, 1] - native_right, dim=-1).amax(-1) * 1000 + right_valid = torch.from_numpy(arrays["hand"][first:last, 1]).to("cuda") + if bool((right_error[right_valid] > 1).any()): + raise RuntimeError("right-hand native compatibility check failed") + arrays["vertices"][first:last, 0] = v[:, 0].cpu().numpy() + arrays["joints"][first:last, 0] = j[:, 0].cpu().numpy() + # Per-record identity/chronology diagnostic, not a smoothing loss. + consecutive = np.diff(arrays["frame_ids"]) == 1 + active_pairs = consecutive & arrays["hand"][:-1, 0] & arrays["hand"][1:, 0] + with np.load(entry["path"], allow_pickle=False) as original: + compensation = arrays["joints"][:, 0] - original["joints"][:, 0] + pair_changes = np.linalg.norm(np.diff(compensation, axis=0), axis=-1).mean(-1)[active_pairs] * 1000 + path = destination / "labels" / Path(entry["path"]).name + save_npz(path, **arrays) + labels.append({**entry, "native_path": entry["path"], "native_sha256": entry["sha256"], + "path": str(path), "sha256": sha(path), "fit_sha256": receipt["sha256"], + "adjacent_fit_compensation_change_mm": stats(pair_changes) if len(pair_changes) else None}) + print(json.dumps({"phase": "audit_subject", "subject": source + "/" + subject, + "frames": result["frames"], "mpvpe_mm": result["mpvpe_mm"], + "failures": failures}), flush=True) + if not args.pilot: + if len(labels) != len(entries): + raise RuntimeError("full record label coverage incomplete") + dump(destination / "label_inventory.json", {"entries": labels, + "target_contract": CONFIG["target_contract"], "native_inventory_sha256": sha(destination / "native_inventory.json"), + "code_sha256": code_hashes()}) + result = {"pilot": args.pilot, "ready_for_training": not args.pilot and not failures, + "code_sha256": code_hashes(), "summaries": summaries, "failures": failures, + "adapter_checks": adapter_checks, "original_GT_unchanged": True, + "complete_record_coverage": len(labels) == len(entries) if not args.pilot else False} + dump(destination / "audit.json", result) + if failures: + raise RuntimeError("canonical cache failed gates: " + "; ".join(failures)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--pilot", action="store_true") + args = parser.parse_args() + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + run(args) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/common.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/common.py new file mode 100644 index 0000000000000000000000000000000000000000..ac088a14c3f9583847b2688f72febc0e98ed15a5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/common.py @@ -0,0 +1,105 @@ +"""Runtime substitution for the read-only original A7 trainer and architecture.""" + +import importlib.util +import json +from pathlib import Path + +from runtime import ROOT, BASE_ROOT, CODE, CACHE, CONFIG, sha, dump, torch, code_hashes as local_hashes + + +def load_module(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +REFERENCE_ROOT = Path(CONFIG["reference_experts"]) +A7_ROOT = Path(CONFIG["reference_a7"]) +reference = load_module("canonical_s4_reference", REFERENCE_ROOT / "common.py") +base, PARENT = reference.base, reference.PARENT +original_model = load_module("canonical_original_a7_model", A7_ROOT / "model.py") +exact_equal, numeric_equal = reference.exact_equal, reference.numeric_equal +frozen_fingerprint, load_parent = reference.frozen_fingerprint, reference.load_parent +ExpertCoverage, mode_and_supervision = reference.ExpertCoverage, reference.mode_and_supervision + +from targets import CanonicalLabels +from foundation_hand.training.losses import BimanualLoss +from foundation_hand.geometry.rotations import axis_angle_to_matrix + + +def code_hashes(): + audit = json.loads((CACHE / "audit.json").read_text()) + labels = json.loads((CACHE / "label_inventory.json").read_text()) + native = CACHE / "cache/native_inventory.json" + native_sha = sha(native) + rotation = CODE / "src/foundation_hand/geometry/rotations.py" + if (not audit["ready_for_training"] or audit["failures"] + or audit["records"] != 380): + raise RuntimeError("training requires the complete canonical label audit") + if (len(labels["entries"]) != 380 or audit["migrated_inventory_sha256"] != native_sha + or labels["native_inventory_sha256"] != native_sha + or labels["rotation_fix_implementation_sha256"] != sha(rotation) + or audit["g1_fit_audit_sha256"] != sha(CACHE / "g1_fit_only_audit.json")): + raise RuntimeError("training cache or rotation-fix provenance changed") + return reference.code_hashes() | {"original_a7/model.py": sha(A7_ROOT / "model.py"), + **{"canonical/" + key: value for key, value in local_hashes().items()}, + "canonical/cache_audit.json": sha(CACHE / "audit.json"), + "canonical/label_inventory.json": sha(CACHE / "label_inventory.json"), + "canonical/native_inventory.json": native_sha, + "canonical/migration.json": sha(CACHE / "migration.json"), + "canonical/rotation_fix.py": sha(rotation)} + + +def model_for(expert): + parent = base.model_for("S4") + parent.load_state_dict(load_parent()["model"], strict=True) + parent.requires_grad_(False).eval() + if expert == "RGB": + return parent + with torch.random.fork_rng(devices=[]): + torch.manual_seed(CONFIG["seed"]) + return original_model.MoTResidualModel(parent, expert) + + +class ExpertDataset(reference.ExpertDataset): + def __init__(self, expert): + super().__init__(expert) + self.labels = {source: CanonicalLabels(source, dataset.rows) for source, dataset in self.sources.items()} + + def __getitem__(self, spec): + source = spec["source"] + original = self.sources[source] + sample = original[spec] + row = original.rows[original.by_tile[spec["tile_id"]]] + sample = self.labels[source].apply(sample, row, original.native) + # Restored geometric supervision still intersects the original immutable quality mask. + from filtered_dataset import intersect_filtered_valid + intersect_filtered_valid(sample, row) + quality = sample["vertices_valid"].bool() + sample["global_orientation_valid"] &= quality + sample["local_pose_valid"] &= quality + return sample + + +def validate_cached_geometry(batch, model): + version = batch.get("mano_target_contract_version") + frame = batch["frame_valid"].bool() + if version is None or not bool((version[frame] == 3).all()): + raise RuntimeError("canonical trainer received an unconverted target contract") + for key, mask in (("mano_pose", "mano_pose_valid"), ("mano_shape", "shape_valid"), + ("wrist_root_translation", "translation_valid"), ("vertices_camera", "vertices_valid")): + if not bool(torch.isfinite(batch[key][batch[mask].bool()]).all()): + raise RuntimeError(f"nonfinite active canonical label: {key}") + with torch.no_grad(): + rotations = axis_angle_to_matrix(torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3)) + v, _ = model.mano_layer(rotations, torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"])) + valid = batch["vertices_valid"].bool() + error = torch.linalg.vector_norm(v - batch["vertices_camera"], dim=-1).amax(-1) + # HOT3D/right retain native geometry; converted left is checked much tighter by the cache audit. + if not bool(torch.isfinite(error[valid]).all()) or bool((error[valid] > .001).any()): + raise RuntimeError("canonical geometry/parameter inconsistency exceeds 1 mm") + + +base.attach_gt_vertices = validate_cached_geometry diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d2f162e95e716f5b14e23bf86122ed548d250bfb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/config.json @@ -0,0 +1,62 @@ +{ + "experiment": "a7_canonical_gt_rotationfix_6gpu_20260930", + "continuation": { + "previous_root": "/home/wuyifan/a7_canonical_gt_v4_20260929", + "geometry_review_root": "/home/wuyifan/a7_canonical_gt_geometry_audit_20260929/review_cpu_v1", + "native_inventory_sha256": "02d3e09101101196fd8d939ebbc16da7a38c2c3afb203e91662e95e505467be9", + "acceptance": "geometry_first_gradients_diagnostic_only" + }, + "reference_a7": "/home/wuyifan/a7_mot_residual_20260929", + "reference_experts": "/home/wuyifan/s4_modality_experts_20260928", + "base_root": "/home/wuyifan/foundation_hand_clean_gt_dino_20260925", + "code_root": "/home/wuyifan/a7_rotation_fix_20260930_code", + "cache_root": "/home/wuyifan/a7_canonical_gt_rotationfix_20260930", + "parent_sha256": "85a9e02274f94b69e2a634518f6f46244dbedb518b135f07be4b2c746be9bb15", + "target_contract": "canonical_approximate_v3", + "seed": 20260928, + "global_batch": 12, + "world_size": 6, + "updates": 8334, + "milestones": [2084, 4167, 8334], + "warmup_clips": 1008, + "learning_rate": 0.00001, + "min_learning_rate": 0.000001, + "depth_backbone_learning_rate": null, + "grad_clip": 100.0, + "weight_decay": 0.05, + "workers_per_rank": 2, + "permitted_gpus": [0, 1, 2, 3, 4, 5], + "order": ["K", "D"], + "source_quota_K": {"H2O": 7, "ARCTIC": 5, "HOT3D": 8}, + "source_D": "H2O", + "fitting": { + "precision": "float64", + "optimizer": "streamed_joint_lbfgs", + "joint_iterations": 2048, + "joint_extension": 2048, + "joint_history_size": 50, + "preconditioner": "pose_finite_difference_and_exact_beta_diagonal", + "precondition_frames": 16, + "precondition_delta_rad": 0.0001, + "shared_beta_gradient_tolerance": 0.00001, + "initializations": ["linear_beta", "native_beta", "zero_beta", "broad_perturbation"], + "block_frames": 128, + "per_frame_pose_gradient_tolerance": 0.001, + "geometry_plateau_min_iterations": 256, + "geometry_plateau_checkpoints": 4, + "geometry_plateau_mean_range_mm": 0.001, + "geometry_plateau_p95_range_mm": 0.005, + "geometry_plateau_worst_vertex_range_mm": 0.01, + "fit_mean_mpvpe_limit_mm": 5.0, + "fit_p95_mpvpe_limit_mm": 8.0, + "fit_max_vertex_limit_mm": 30.0, + "fit_max_wrist_adjustment_limit_mm": 20.0, + "fit_max_local_pose_rms_limit_rad": 0.5 + }, + "primary_metrics_mm": ["absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", "pa_mpjpe_mm"], + "auxiliary_metrics": ["projected_mano_2d_error_px"], + "final_selection": "fixed_8334_update_endpoint_not_best_validation", + "official_test_used": false, + "dino_trainable_blocks": 0, + "minimum_free_disk_gib": 200 +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..7f55f643854612fdb77ce623f9c223ad19baead5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/controller.py @@ -0,0 +1,239 @@ +"""Durable all-label adaptation and matched A7 retraining with explicit gates.""" + +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time + +from runtime import ROOT, CACHE, CONFIG, CODE, dump, sha, code_hashes +from scripts.train_phase7_external import claim_physical_gpu, release_physical_gpu_claim, assert_physical_gpu_idle + + +def event(name, **detail): + payload = {"event": name, "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S%z"), + "controller_pid": os.getpid(), **detail} + dump(ROOT / "state.json", payload) + print(json.dumps(payload), flush=True) + + +def reserve(): + result = [] + for gpu in CONFIG["permitted_gpus"]: + if not claim_physical_gpu(gpu): + continue + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + else: + result.append(gpu) + if len(result) != CONFIG["world_size"]: + for gpu in result: + release_physical_gpu_claim(gpu) + return [] + return result + + +def start(label, arguments, gpus): + path = ROOT / "logs" / (label + ".log") + path.parent.mkdir(exist_ok=True) + if path.exists(): + raise FileExistsError("existing stage log requires diagnosis: " + str(path)) + env = dict(os.environ, CUDA_VISIBLE_DEVICES=",".join(map(str, gpus)), + OMP_NUM_THREADS="2", MKL_NUM_THREADS="2", OPENBLAS_NUM_THREADS="2", + PYTHONUNBUFFERED="1") + if "FH_A7_TEST_CODE" in env: + raise RuntimeError("test-code override cannot launch a registered experiment") + with path.open("xb") as log: + process = subprocess.Popen([sys.executable, "-u", *arguments], cwd=ROOT, env=env, + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT) + return process, {"label": label, "pid": process.pid, "gpus": gpus, "log": str(path)} + + +def execute(label, arguments, gpus=()): + process, receipt = start(label, arguments, gpus) + event("running", **receipt) + code = process.wait() + if code: + raise RuntimeError(f"{label} failed with exit code {code}; {receipt['log']}") + + +def train(expert, update, gpus, output=None, resume=None, smoke=False, label=None): + output = output or ROOT / "runs" / expert + args = ["-m", "torch.distributed.run", "--standalone", "--nproc_per_node=" + str(len(gpus)), + str(ROOT / "train_expert.py"), "--expert", expert, "--updates", str(update), "--output", str(output)] + if resume: + args += ["--resume", str(resume)] + if smoke: + args += ["--smoke"] + execute(label or f"train_{expert}_{update:07d}", args, gpus) + return output / f"update_{update:07d}.pt" + + +def evaluate(expert, source, role, gpus, checkpoint=None, smoke=False): + update = 0 if checkpoint is None else int(checkpoint.stem.split("_")[-1]) + label = f"eval_{expert}_{update:07d}_{role}_{source}" + ("_smoke" if smoke else "") + path = ROOT / "evaluations" / (label + ".json") + args = [str(ROOT / "evaluate.py"), "--expert", expert, "--source", source, + "--role", role, "--output", str(path)] + if checkpoint: + args += ["--checkpoint", str(checkpoint)] + if smoke: + args += ["--smoke", "--limit", "2"] + execute(label, args, gpus[:1]) + + +def resume_check(gpus): + from common import torch, exact_equal, numeric_equal + preflight = ROOT / "preflight" + left = train("D", 4, gpus, preflight / "continuous", smoke=True, label="resume_continuous") + middle = train("D", 2, gpus, preflight / "split", smoke=True, label="resume_split_first") + right = train("D", 4, gpus, preflight / "split", resume=middle, smoke=True, label="resume_split_second") + a, b = [torch.load(path, map_location="cpu", weights_only=False) for path in (left, right)] + for key in ("rank_rng_states", "next_global_sample_position", "source_exposure", + "supervision_exposure", "input_checksums", "frozen_fingerprint"): + if not exact_equal(a[key], b[key]): + raise RuntimeError("canonical resume changed " + key) + if not numeric_equal(a["model"], b["model"], atol=1e-6): + raise RuntimeError("canonical resumed model exceeds old A7 numerical tolerance") + names = json.loads((preflight / "continuous/provenance_from_0000000.json").read_text())["trainable_names"] + if a["optimizer"]["param_groups"] != b["optimizer"]["param_groups"]: + raise RuntimeError("resume optimizer groups changed") + errors = [] + for index, values in a["optimizer"]["state"].items(): + for key, value in values.items(): + expected = b["optimizer"]["state"][index][key] + if not torch.is_tensor(value): + if value != expected: + raise RuntimeError("resume optimizer scalar changed") + continue + sensitive = names[index].startswith(("branch.rotation_head.", "branch.translation_head.", + "branch.shape_head.", "branch.joint2d_head.")) + tolerance = .005 if sensitive and key == "exp_avg" else .002 if sensitive and key == "exp_avg_sq" else 2e-5 + difference = float((value - expected).abs().max()) + errors.append({"name": names[index], "field": key, "max_abs": difference, "atol": tolerance}) + if not torch.allclose(value, expected, atol=tolerance, rtol=1e-4): + dump(preflight / "resume_failed.json", {"errors": errors}) + raise RuntimeError("canonical optimizer continuation exceeds old A7 numerical tolerance") + dump(preflight / "resume_pass.json", {"status": "pass", "rng_inputs_gt_cursor_exact": True, + "model_atol": 1e-6, "optimizer_numeric_not_bitwise": True, "errors": errors}) + + +def report(): + records = [] + for path in sorted((ROOT / "evaluations").glob("*confirmation*.json")): + if not path.name.endswith(".rows.json"): + records.append(json.loads(path.read_text())) + if len(records) != 7: + raise RuntimeError("final report requires all seven source/input panels") + metrics = (*CONFIG["primary_metrics_mm"], *CONFIG["auxiliary_metrics"]) + lines = ["# A7 Canonical Approximate GT: Matched Retraining", "", + "Same original source-native targets and GT-defined denominators for every model.", + "All four primary metrics are mm; MANO 2D is auxiliary px. Previously inspected panels, not official test.", + "Historical A7 scores used different label/coverage contracts and are not directly comparable.", "", + "| Source | Input | Model | Abs MPJPE | RR MPJPE | MPVPE | PA MPJPE | MANO 2D px |", + "|---|---|---|---:|---:|---:|---:|---:|"] + for row in records: + for model in ("S4_RGB", "S4_same_input", "old_A7", "new_A7"): + values = " | ".join(f"{row['summary'][model][key]['mean']:.3f}" for key in metrics) + lines.append(f"| {row['source']} | {row['input_mode']} | {model} | {values} |") + lines += ["", "Paired recording bootstrap intervals, side/device breakdowns and native GT hashes are retained in evaluations/.", + "Pure RGB remains frozen S4. Fixed budget is a controlled comparison, not a convergence claim."] + (ROOT / "RESULTS.md").write_text("\n".join(lines) + "\n") + dump(ROOT / "results.json", records) + + +def main(): + lock = (ROOT / "controller.lock").open("a") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + gpus, children = [], [] + initial_hashes = code_hashes() + try: + execute("unit_tests", ["-m", "unittest", "discover", "-p", "test_*.py", "-v"]) + from common import load_parent + parent = load_parent() + del parent + original = json.loads((Path(CONFIG["reference_a7"]) / "config.json").read_text()) + for field in ("parent_sha256", "seed", "global_batch", "world_size", "updates", "milestones", + "warmup_clips", "learning_rate", "min_learning_rate", "grad_clip", "weight_decay", + "workers_per_rank", "order", "source_quota_K", "source_D", "dino_trainable_blocks"): + if CONFIG[field] != original[field]: + raise RuntimeError("controlled recipe changed original A7 field: " + field) + if shutil.disk_usage(ROOT).free < CONFIG["minimum_free_disk_gib"] * 1024**3: + raise RuntimeError("disk reserve below 200 GiB") + dump(ROOT / "registration.json", {"config": CONFIG, "code_sha256": initial_hashes, + "original_GT_unchanged": True, "old_A7_unchanged": True, + "target_contract": CONFIG["target_contract"], "continuation": CONFIG["continuation"]}) + execute("reuse_verified_V4_inputs", [str(ROOT / "import_previous.py")]) + execute("geometry_policy_cpu_preflight", [str(ROOT / "preflight_geometry.py")]) + while not gpus: + gpus = reserve() + if not gpus: + event("waiting_for_four_idle_gpus", non_preempting=True) + time.sleep(30) + if shutil.disk_usage(ROOT).free < CONFIG["minimum_free_disk_gib"] * 1024**3: + raise RuntimeError("disk reserve below 200 GiB") + dump(ROOT / "registration.json", {"config": CONFIG, "code_sha256": initial_hashes, + "gpus": gpus, "original_GT_unchanged": True, "old_A7_unchanged": True, + "target_contract": CONFIG["target_contract"]}) + execute("native_pilot", [str(ROOT / "native_cache.py"), "--pilot"], gpus[:1]) + execute("fit_pilot", [str(ROOT / "fit_cache.py"), "--pilot"], gpus[:1]) + execute("audit_pilot", [str(ROOT / "audit_cache.py"), "--pilot"], gpus[:1]) + receipts = [] + for shard, gpu in enumerate(gpus): + child, receipt = start(f"fit_full_shard_{shard}", [str(ROOT / "fit_cache.py"), "--shard", str(shard), + "--shards", str(len(gpus))], [gpu]) + children.append(child) + receipts.append(receipt) + event("fitting_all_training_left_hands", children=receipts, gpus=gpus) + pending = set(range(len(children))) + while pending: + for index in list(pending): + code = children[index].poll() + if code is not None: + pending.remove(index) + if code: + raise RuntimeError(f"full fit shard {index} failed: {receipts[index]['log']}") + if pending: + time.sleep(5) + execute("audit_full", [str(ROOT / "audit_cache.py")], gpus[:1]) + if code_hashes() != initial_hashes: + raise RuntimeError("registered implementation changed during label fitting") + execute("gpu_contract", [str(ROOT / "gpu_contract.py")], gpus[:1]) + for expert in CONFIG["order"]: + smoke = train(expert, 2, gpus, ROOT / "preflight" / expert, smoke=True, label="smoke_" + expert) + evaluate(expert, "H2O", "development", gpus, smoke, smoke=True) + resume_check(gpus) + event("preflight_pass_starting_matched_training", gpus=gpus) + for expert in CONFIG["order"]: + previous = None + for endpoint in CONFIG["milestones"]: + previous = train(expert, endpoint, gpus, resume=previous) + for source in (("H2O",) if expert == "D" else ("H2O", "ARCTIC", "HOT3D")): + evaluate(expert, source, "development", gpus, previous) + for source in (("H2O",) if expert == "D" else ("H2O", "ARCTIC", "HOT3D")): + evaluate(expert, source, "confirmation", gpus, previous) + for source in ("H2O", "ARCTIC", "HOT3D"): + evaluate("RGB", source, "confirmation", gpus) + report() + event("complete", results=str(ROOT / "RESULTS.md")) + except BaseException as error: + for child in children: + if child.poll() is None: + child.terminate() + for child in children: + if child.poll() is None: + child.wait(timeout=60) + event("failed_requires_diagnosis", error=repr(error)) + raise + finally: + for gpu in gpus: + release_physical_gpu_claim(gpu) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/evaluate.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..21c38a27ea9ab216fd4b1185756ff5f5e1a3bd60 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/evaluate.py @@ -0,0 +1,152 @@ +"""Old/new A7 and S4 on identical, untouched source-native geometry targets.""" + +from collections import defaultdict +import argparse +import json +import math +from pathlib import Path + +from common import (ROOT, BASE_ROOT, CODE, CONFIG, CACHE, A7_ROOT, base, + reference, original_model, model_for, code_hashes, sha, dump, torch) +from runtime import np, tensor_hash +from targets import NativePanel +from clean_eval import apply_mode, dataset_for +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from scripts.evaluate_phase7_external import aggregate, make_row + +METRICS = (*CONFIG["primary_metrics_mm"], *CONFIG["auxiliary_metrics"]) + + +def finite(value): + if isinstance(value, dict): + return {key: finite(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [finite(item) for item in value] + return None if isinstance(value, float) and not math.isfinite(value) else value + + +def paired(left, right): + result = {} + for metric in METRICS: + recordings = defaultdict(list) + for a, b in zip(left, right): + if any(a[key] != b[key] for key in ("physical_recording_id", "frame_id", "side")): + raise RuntimeError("evaluation row identity changed") + if math.isfinite(a[metric]) != math.isfinite(b[metric]): + raise RuntimeError("model-dependent native-GT denominator") + if math.isfinite(a[metric]): + recordings[a["physical_recording_id"]].append(b[metric] - a[metric]) + if not recordings: + raise RuntimeError("empty benchmark metric denominator: " + metric) + sums = np.array([sum(values) for values in recordings.values()]) + counts = np.array([len(values) for values in recordings.values()]) + draws = np.random.default_rng(CONFIG["seed"]).integers(0, len(sums), (2000, len(sums))) + bootstrap = sums[draws].sum(1) / counts[draws].sum(1) + result[metric] = {"delta": float(sums.sum() / counts.sum()), + "recording_bootstrap_95ci": np.quantile(bootstrap, [.025, .975]).tolist(), + "count": int(counts.sum()), "recordings": len(sums)} + return result + + +def original_a7_hashes(): + result = reference.code_hashes() + result.update({"mot/" + path.name: sha(path) for path in sorted(A7_ROOT.glob("*.py"))}) + result["mot/config.json"] = sha(A7_ROOT / "config.json") + for name in ("train_expert.py", "controller.py"): + result["reference/" + name] = sha(reference.ROOT / name) + return result + + +def run(args): + if args.output.exists() or (args.limit is not None and not args.smoke): + raise RuntimeError("existing output or unmarked subset evaluation") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + hashes = code_hashes() + parent = model_for("RGB").to("cuda").eval() + models = {"S4_RGB": parent, "S4_same_input": parent} + update = 0 + if args.expert != "RGB": + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if (checkpoint["code_sha256"] != hashes or not checkpoint["complete_backbone"] + or checkpoint["smoke"] != args.smoke or checkpoint["expert"] != args.expert + or checkpoint["parent_sha256"] != CONFIG["parent_sha256"]): + raise RuntimeError("new A7 checkpoint contract mismatch") + update = checkpoint["update"] + if args.role == "confirmation" and update != CONFIG["updates"]: + raise RuntimeError("confirmation requires fixed final endpoint") + candidate = model_for(args.expert) + candidate.load_state_dict(checkpoint["model"], strict=True) + models["new_A7"] = candidate.to("cuda").eval() + del checkpoint + old_path = A7_ROOT / "runs" / args.expert / "update_0008334.pt" + old_state = torch.load(old_path, map_location="cpu", weights_only=False) + if (not old_state["complete_backbone"] or old_state["smoke"] or old_state["update"] != 8334 + or old_state["parent_sha256"] != CONFIG["parent_sha256"] + or old_state["code_sha256"] != original_a7_hashes()): + raise RuntimeError("old A7 control checkpoint identity mismatch") + old = model_for(args.expert) + old.load_state_dict(old_state["model"], strict=True) + models["old_A7"] = old.to("cuda").eval() + del old_state + else: + models["new_A7"] = models["old_A7"] = parent + panel_root = BASE_ROOT / "eval/frozen_panels_sync_v2" + panels = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_{args.role}_t8.jsonl" + identity = panels["sources"][args.source][args.role] + if sha(manifest) != identity["manifest_sha256"] or panels["sources"][args.source]["train_overlap"]: + raise RuntimeError("evaluation panel isolation/hash mismatch") + rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), hand_valid_policy="visible_mesh") + if args.source == "ARCTIC" else dataset_for(args.source, manifest)) + dataset = NativePanel(args.source, native, rows) + mode = {"RGB": "rgb", "K": "rgb_k", "D": "rgb_depth_k"}[args.expert] + limit = min(args.limit, len(dataset)) if args.limit is not None else len(dataset) + output_rows, checksums = {key: [] for key in models}, {} + with torch.inference_mode(): + for index in range(limit): + cpu = base.collate_h2o_clips([dataset[index]]) + checksums[str(index)] = tensor_hash({key: cpu[key] for key in + ("vertices_camera", "vertices_valid", "joint3d_camera", "joint3d_valid", + "joint3d_root_relative", "joint3d_root_relative_valid", "K", "joint2d", "joint2d_valid")}) + batch = base.move_to_device(cpu, torch.device("cuda")) + apply_mode(batch, mode) + pure = original_model.rgb_inputs(batch) + # No attach_gt_vertices call: evaluation geometry remains source native. + with torch.autocast("cuda", dtype=torch.bfloat16): + predictions = {key: model(pure if key == "S4_RGB" else batch) for key, model in models.items()} + for key, prediction in predictions.items(): + if not torch.isfinite(prediction["vertices_camera"]).all() or not torch.isfinite(prediction["joints_camera"]).all(): + raise RuntimeError("nonfinite model output") + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + output_rows[key].append(make_row(prediction, batch, 0, frame, side)) + if (index + 1) % 16 == 0: + print(json.dumps({"source": args.source, "mode": mode, "done": index + 1, "total": limit}), flush=True) + if code_hashes() != hashes: + raise RuntimeError("training/evaluation code changed mid-evaluation") + summaries = {key: aggregate(values) for key, values in output_rows.items()} + report = {"source": args.source, "input_mode": mode, "expert": args.expert, "update": update, + "role": args.role, "smoke": args.smoke, "clips": limit, + "native_GT_not_refitted": True, "predicted_presence_filtered": False, + "panel_sha256": sha(manifest), "gt_checksums": checksums, "code_sha256": hashes, + "metric_units": {key: "px" if key.endswith("_px") else "mm" for key in METRICS}, + "summary": summaries, "paired_vs_old_A7": paired(output_rows["old_A7"], output_rows["new_A7"]), + "paired_vs_S4_same_input": paired(output_rows["S4_same_input"], output_rows["new_A7"])} + dump(args.output, finite(report)) + dump(args.output.with_suffix(".rows.json"), finite(output_rows)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--expert", choices=("RGB", "K", "D"), required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--checkpoint", type=Path) + parser.add_argument("--role", choices=("development", "confirmation"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--limit", type=int) + parser.add_argument("--smoke", action="store_true") + run(parser.parse_args()) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/fit_cache.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/fit_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..4b455e83a772281921ddfd53e2c4b87c7ce24ee7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/fit_cache.py @@ -0,0 +1,380 @@ +"""Memory-bounded native-to-corrected MANO fitting with all-frame shared beta.""" + +from collections import defaultdict +import argparse +import json +from pathlib import Path +import time + +from runtime import (CACHE, CONFIG, MANO_ROOT, ROOT, torch, np, ManoCameraLayer, + geometry, dump, save_npz, sha, stats, code_hashes) +from fit_quality import inspect_geometry, geometry_plateau, geometry_gate + + +def residual_objective(vertices, joints, data, rho): + v = ((vertices - data["vertices"]) * 1000).square().mean() + j = (((joints - data["joints"]) * 1000).square() + * data["joint_valid"][..., None]).sum() * rho / (3 * len(vertices)) + return v + j + + +def optimal_wrist(vertices, joints, data, rho): + valid = data["joint_valid"] + delta = ((data["vertices"] - vertices).mean(1) + + rho * ((data["joints"] - joints) * valid[..., None]).sum(1)) + return data["wrist"] + delta / (1 + rho * valid.sum(1).to(vertices.dtype))[:, None] + + +def placed_geometry(layer, pose, beta, data, rho): + v, j = geometry(layer, pose, beta, data["wrist"]) + wrist = optimal_wrist(v, j, data, rho) + delta = wrist - data["wrist"] + return v + delta[:, None], j + delta[:, None], wrist + + +def conditional_beta_system(v0, j0, av, aj, data, rho): + """Eliminate independent wrist translations before solving the common beta.""" + valid = data["joint_valid"] + bv, bj = data["vertices"] - v0, data["joints"] - j0 + denominator = (1 + rho * valid.sum(1).to(v0.dtype))[:, None, None] + mean_a = (av.mean(1) + rho * (aj * valid[..., None, None]).sum(1)) / denominator + mean_b = (bv.mean(1) + rho * (bj * valid[..., None]).sum(1)) / denominator[..., 0] + av, aj = (av - mean_a[:, None]) * 1000, (aj - mean_a[:, None]) * 1000 + bv, bj = (bv - mean_b[:, None]) * 1000, (bj - mean_b[:, None]) * 1000 + av, bv = av.reshape(-1, 10), bv.reshape(-1) + aj, bj = aj[valid].reshape(-1, 10), bj[valid].reshape(-1) + normal = av.T @ av / v0.shape[1] + rho * (aj.T @ aj) + target = av.T @ bv / v0.shape[1] + rho * (aj.T @ bj) + return normal, target + + +def load_subject(entries): + parts = defaultdict(list) + records, indices = [], [] + for record_index, entry in enumerate(entries): + if sha(entry["path"]) != entry["sha256"]: + raise RuntimeError("native cache identity changed") + with np.load(entry["path"], allow_pickle=False) as payload: + eligible = payload["hand"][:, 0] + selected = np.flatnonzero(eligible) + for target, key in (("pose", "pose"), ("beta", "beta"), ("wrist", "wrist"), + ("vertices", "vertices"), ("joints", "joints"), + ("joint_valid", "joint_valid"), ("K", "K"), + ("joint2d", "joint2d"), ("joint2d_valid", "joint2d_valid")): + value = payload[key][selected] if key == "K" else payload[key][selected, 0] + parts[target].append(value.copy()) + records.extend([record_index] * len(selected)) + indices.extend(selected.tolist()) + if not indices: + raise RuntimeError("subject without any eligible left-hand frames") + data = {key: torch.from_numpy(np.concatenate(values)) for key, values in parts.items()} + data["record_index"], data["frame_index"] = np.array(records), np.array(indices) + return data + + +def chunk(data, first, last, device): + return {key: data[key][first:last].to(device) for key in + ("vertices", "joints", "wrist", "joint_valid")} + + +def beta_solve(layer, data, pose, rho, block, device): + normal = torch.zeros(10, 10, dtype=torch.float64, device=device) + target = torch.zeros(10, dtype=torch.float64, device=device) + shapes = torch.cat((normal.new_zeros(1, 10), torch.eye(10, dtype=torch.float64, device=device))) + with torch.no_grad(): + for first in range(0, len(pose), block): + count = min(block, len(pose) - first) + values = chunk(data, first, first + count, device) + p = pose[first:first + count].to(device) + v, j = geometry(layer, p[:, None].expand(-1, 11, -1).reshape(-1, 48), + shapes[None].expand(count, -1, -1).reshape(-1, 10), + values["wrist"][:, None].expand(-1, 11, -1).reshape(-1, 3)) + v, j = v.reshape(count, 11, 778, 3), j.reshape(count, 11, 21, 3) + av = (v[:, 1:] - v[:, :1]).permute(0, 2, 3, 1) + aj = (j[:, 1:] - j[:, :1]).permute(0, 2, 3, 1) + a, b = conditional_beta_system(v[:, 0], j[:, 0], av, aj, values, rho) + normal += a + target += b + eigenvalues = torch.linalg.eigvalsh(normal) + if not bool(eigenvalues[0] > eigenvalues[-1] * 1e-12): + raise RuntimeError("shared-beta normal system is rank deficient") + beta = torch.linalg.solve(normal, target) + return beta.detach().cpu(), {"condition": float(eigenvalues[-1] / eigenvalues[0]), + "normal_residual": float((normal @ beta - target).abs().max()), + "hessian_diagonal": (2 * normal.diagonal() / (3 * len(pose))).cpu().tolist(), + "frames": len(pose)} + + +def fit_pose(layer, values, initial, beta, rho, iterations): + angles = initial.detach().clone().requires_grad_() + optimizer = torch.optim.LBFGS([angles], max_iter=iterations, history_size=30, + tolerance_grad=1e-10, tolerance_change=1e-13, + line_search_fn="strong_wolfe") + best = {"objective": float("inf")} + + def closure(): + optimizer.zero_grad() + v, j, _ = placed_geometry(layer, angles, beta, values, rho) + loss = residual_objective(v, j, values, rho) + if not bool(torch.isfinite(loss)): + raise RuntimeError("nonfinite pose fitting objective") + loss.backward() + if float(loss.detach()) < best["objective"]: + best.update(objective=float(loss.detach()), pose=angles.detach().clone()) + return loss + + optimizer.step(closure) + closure() + saved = best["pose"].requires_grad_() + v, j, wrist = placed_geometry(layer, saved, beta, values, rho) + loss = residual_objective(v, j, values, rho) + gradient, = torch.autograd.grad(loss, saved) + return {"pose": saved.detach(), "wrist": wrist.detach(), "objective": float(loss.detach()), + "per_frame_gradient": gradient.detach().abs().amax(-1) * len(saved)} + + +def sweep(layer, data, pose, beta, rho, settings, device, first_sweep=False): + block = settings["block_frames"] + updated, wrists, gradients = [], [], [] + objective = 0.0 + for first in range(0, len(pose), block): + last = min(first + block, len(pose)) + values = chunk(data, first, last, device) + p, b = pose[first:last].to(device), beta.to(device) + result = fit_pose(layer, values, p, b, rho, settings["pose_iterations"]) + if first_sweep: + generator = torch.Generator(device=device).manual_seed(20260929 + first) + perturb = torch.randn(p.shape, generator=generator, dtype=p.dtype, device=device) * .05 + other = fit_pose(layer, values, p + perturb, b, rho, settings["pose_iterations"]) + # Choose complete blocks by the unchanged fitting objective, never by a benchmark metric. + if other["objective"] < result["objective"]: + result = other + if float(result["per_frame_gradient"].max()) > settings["per_frame_pose_gradient_tolerance"]: + extended = fit_pose(layer, values, result["pose"], b, rho, settings["pose_extension"]) + if extended["objective"] <= result["objective"]: + result = extended + updated.append(result["pose"].cpu()) + wrists.append(result["wrist"].cpu()) + gradients.append(result["per_frame_gradient"].cpu()) + objective += result["objective"] * (last - first) / len(pose) + return torch.cat(updated), torch.cat(wrists), torch.cat(gradients), objective + + +def fit_subject(entries, destination, device, maximum_frames=None): + source, subject = entries[0]["source"], entries[0]["subject"] + output = destination / "fits" / (source + "_" + subject + ".npz") + receipt_path = output.with_suffix(".json") + identities = {entry["recording"]: entry["sha256"] for entry in entries} + if output.exists() and receipt_path.exists(): + receipt = json.loads(receipt_path.read_text()) + if (receipt["native_sha256"] != identities or receipt["sha256"] != sha(output) + or receipt["code_sha256"] != code_hashes() or not receipt["optimization_complete"]): + raise RuntimeError("existing fitted cache changed") + return receipt + data = load_subject(entries) + if maximum_frames is not None: + # Diagnostic only; the formal controller never limits the full fit. + for key in data: + data[key] = data[key][:maximum_frames] + settings = CONFIG["fitting"] + layer = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=True).layers[0].double().to(device).eval() + rho = len(data["pose"]) / int(data["joint_valid"].sum()) + pose = data["pose"].clone() + beta, beta_receipt = beta_solve(layer, data, pose, rho, settings["block_frames"], device) + scaling = diagonal_preconditioner(layer, data, pose, beta, rho, beta_receipt, settings, device) + baseline, _ = inspect_geometry(layer, data, data["pose"], data["beta"], data["wrist"], device) + generator = torch.Generator().manual_seed(20260929) + seeds = [("linear_beta", pose, beta), ("native_beta", pose, data["beta"].mean(0)), + ("zero_beta", pose, torch.zeros_like(beta)), + ("broad_perturbation", pose + torch.randn(pose.shape, generator=generator, dtype=pose.dtype) * .35, + beta + torch.randn(beta.shape, generator=generator, dtype=beta.dtype))] + candidates = [] + warm_path = destination / "warm_starts" / (source + "_" + subject + ".npz") + if maximum_frames is None and warm_path.exists(): + provenance = json.loads(warm_path.with_suffix(".json").read_text()) + if sha(warm_path) != provenance["sha256"] or provenance["native_sha256"] != identities: + raise RuntimeError("V4 warm-start identity changed") + with np.load(warm_path, allow_pickle=False) as payload: + if (payload["beta"].shape != (10,) or payload["pose"].shape != data["pose"].shape + or not np.array_equal(payload["record_index"], data["record_index"]) + or not np.array_equal(payload["frame_index"], data["frame_index"])): + raise RuntimeError("V4 warm-start coverage/shared-beta mismatch") + seeds.append(("v4_working_warm_start", torch.from_numpy(payload["pose"].copy()), + torch.from_numpy(payload["beta"].copy()))) + for label, initial_pose, initial_beta in seeds: + result = joint_fit(layer, data, initial_pose, initial_beta, rho, settings["joint_iterations"], + settings, device, destination, source + "_" + subject, label, scaling, baseline) + candidates.append(result) + winner = min(candidates, key=lambda result: result["objective"]) + extension = joint_fit(layer, data, winner["pose"], winner["beta"], rho, settings["joint_extension"], + settings, device, destination, source + "_" + subject, "winning_extension", scaling, baseline) + result = min((winner, extension), key=lambda value: value["objective"]) + pose, beta, wrist, gradient = [result[key] for key in ("pose", "beta", "wrist", "per_frame_gradient")] + trace = [{key: value for key, value in candidate.items() if not torch.is_tensor(value)} for candidate in candidates] + trace.append({key: value for key, value in extension.items() if not torch.is_tensor(value)}) + converged = (float(gradient.max()) <= settings["per_frame_pose_gradient_tolerance"] + and result["beta_gradient_max"] <= settings["shared_beta_gradient_tolerance"]) + quality = result["geometry_review"] + if not quality["geometry_review_pass"]: + dump(receipt_path.with_suffix(".failed.json"), {"trace": trace, "error": "geometry_quality_failed", + "geometry_review": quality}) + raise RuntimeError(f"{source}/{subject}: full shared-beta fit did not pass geometry gates") + save_npz(output, pose=pose.numpy(), beta=beta.numpy(), wrist=wrist.numpy(), + gradient=gradient.numpy(), record_index=data["record_index"], frame_index=data["frame_index"]) + receipt = {"source": source, "subject": subject, "path": str(output), "sha256": sha(output), + "native_sha256": identities, "frames": len(pose), "converged": converged, + "optimization_complete": True, "geometry_review": quality, + "gradient_stationarity_is_diagnostic_only": True, + "trace": trace, "code_sha256": code_hashes(), "pilot": maximum_frames is not None} + receipt["parameter_scaling"] = {key: value.tolist() for key, value in scaling.items()} + dump(receipt_path, receipt) + return receipt + + +def diagonal_preconditioner(layer, data, pose, beta, rho, beta_receipt, settings, device): + count = min(settings["precondition_frames"], len(pose)) + indices = torch.linspace(0, len(pose) - 1, count).round().long() + selected = {key: data[key][indices].to(device) for key in ("vertices", "joints", "wrist", "joint_valid")} + directions = torch.eye(48, dtype=pose.dtype, device=device) + step = settings["precondition_delta_rad"] + rows = pose[indices].to(device) + values = {key: value[:, None].expand(-1, 48, *value.shape[1:]).reshape(count * 48, *value.shape[1:]) + for key, value in selected.items()} + with torch.no_grad(): + plus = (rows[:, None] + step * directions[None]).reshape(-1, 48) + minus = (rows[:, None] - step * directions[None]).reshape(-1, 48) + vp, jp, _ = placed_geometry(layer, plus, beta.to(device), values, rho) + vm, jm, _ = placed_geometry(layer, minus, beta.to(device), values, rho) + dv = ((vp - vm) * (1000 / (2 * step))).reshape(count, 48, 778, 3) + dj = ((jp - jm) * (1000 / (2 * step))).reshape(count, 48, 21, 3) + diagonal = 2 * (dv.square().mean(dim=(-1, -2)) + + rho * (dj.square() * selected["joint_valid"][:, None, :, None]).sum(dim=(-1, -2)) / 3).mean(0) + pose_scale = (len(pose) / diagonal.clamp_min(1e-6)).sqrt().cpu() + beta_diagonal = torch.tensor(beta_receipt["hessian_diagonal"], dtype=pose.dtype) + beta_scale = beta_diagonal.clamp_min(1e-6).rsqrt() + return {"pose": pose_scale, "beta": beta_scale} + + +def streamed_joint_evaluation(layer, data, parameters, rho, block, device, gradient=True, scaling=None): + """Exact all-frame objective/gradient without retaining the full GPU graph.""" + frames = len(data["pose"]) + scaling = scaling or {"pose": parameters.new_full((48,), frames**.5), "beta": parameters.new_ones(10)} + pose_scale, beta_scale = scaling["pose"].to(device), scaling["beta"].to(device) + pose_cpu = parameters[:-10].reshape(frames, 48).detach() + beta_cpu = parameters[-10:].detach() + complete_gradient = torch.zeros_like(parameters) if gradient else None + wrist_rows, objective = [], 0.0 + for first in range(0, frames, block): + last = min(first + block, frames) + values = chunk(data, first, last, device) + pose = (pose_cpu[first:last].to(device) * pose_scale).requires_grad_(gradient) + beta = (beta_cpu.to(device) * beta_scale).clone().requires_grad_(gradient) + v, j, wrist = placed_geometry(layer, pose, beta, values, rho) + loss = residual_objective(v, j, values, rho) + if not bool(torch.isfinite(loss)): + raise RuntimeError("nonfinite streamed joint objective") + weight = (last - first) / frames + objective += float(loss.detach()) * weight + wrist_rows.append(wrist.detach().cpu()) + if gradient: + gp, gb = torch.autograd.grad(loss, (pose, beta)) + complete_gradient[first * 48:last * 48] = (gp.detach().cpu() * scaling["pose"][None]).reshape(-1) * weight + complete_gradient[-10:] += gb.detach().cpu() * scaling["beta"] * weight + return objective, complete_gradient, torch.cat(wrist_rows) + + +def joint_fit(layer, data, pose, beta, rho, iterations, settings, device, destination, identity, label, scaling, baseline): + frames = len(pose) + parameters = torch.cat(((pose / scaling["pose"][None]).reshape(-1), beta / scaling["beta"])).clone().requires_grad_() + optimizer = torch.optim.LBFGS([parameters], max_iter=64, history_size=settings["joint_history_size"], + tolerance_grad=1e-10, tolerance_change=1e-12, + line_search_fn="strong_wolfe") + best = {"objective": float("inf")} + calls, trace = 0, [] + clock = time.monotonic() + + def closure(): + nonlocal calls + objective, gradient, _ = streamed_joint_evaluation(layer, data, parameters, rho, + settings["block_frames"], device, scaling=scaling) + parameters.grad = gradient + calls += 1 + if objective < best["objective"]: + best.update(objective=objective, parameters=parameters.detach().clone()) + if calls == 1 or calls % 10 == 0: + progress = {"subject": identity, "start": label, "phase": "joint_closure", + "frames": frames, "calls": calls, "objective_mm2": objective, + "scaled_pose_gradient_max": float((gradient[:-10].reshape(frames, 48) / scaling["pose"][None]).abs().max()) * frames, + "beta_gradient_max": float((gradient[-10:] / scaling["beta"]).abs().max()), + "elapsed_seconds": time.monotonic() - clock} + print(json.dumps(progress), flush=True) + dump(destination / "fit_progress" / (identity + ".json"), progress) + return parameters.new_tensor(objective) + + closure() + for used in range(0, iterations, 64): + optimizer.param_groups[0]["max_iter"] = min(64, iterations - used) + optimizer.step(closure) + objective, gradient, wrist = streamed_joint_evaluation(layer, data, best["parameters"], rho, + settings["block_frames"], device, scaling=scaling) + scaled = (gradient[:-10].reshape(frames, 48) / scaling["pose"][None]).abs().amax(-1) * frames + best_pose = best["parameters"][:-10].reshape(frames, 48) * scaling["pose"][None] + best_beta = best["parameters"][-10:] * scaling["beta"] + summary, diagnostics = inspect_geometry(layer, data, best_pose, best_beta, wrist, device) + quality = geometry_gate(summary, diagnostics, baseline, settings) + receipt = {"subject": identity, "start": label, "frames": frames, + "budget_used": used + min(64, iterations - used), "objective_mm2": objective, + "scaled_pose_gradient_max": float(scaled.max()), + "beta_gradient_max": float((gradient[-10:] / scaling["beta"]).abs().max()), + "calls": calls, "elapsed_seconds": time.monotonic() - clock, + "optimizer_iterations": optimizer.state[parameters].get("n_iter", 0), + "geometry": summary, "geometry_review": quality} + trace.append(receipt) + print(json.dumps(receipt), flush=True) + dump(destination / "fit_progress" / (identity + ".json"), receipt) + save_npz(destination / "fits" / (identity + ".working.npz"), + pose=(best["parameters"][:-10].reshape(frames, 48) * scaling["pose"][None]).numpy(), + beta=(best["parameters"][-10:] * scaling["beta"]).numpy(), wrist=wrist.numpy(), gradient=scaled.numpy(), + record_index=data["record_index"], frame_index=data["frame_index"]) + if geometry_plateau(trace, settings): + receipt["stop_reason"] = "geometry_quality_pass_and_geometry_plateau" + break + receipt.setdefault("stop_reason", "registered_maximum_budget_reached") + dump(destination / "fit_progress" / (identity + ".json"), receipt) + final = best["parameters"] + return {"initialization": label, "objective": objective, + "pose": final[:-10].reshape(frames, 48) * scaling["pose"][None], "beta": final[-10:] * scaling["beta"], + "wrist": wrist, "per_frame_gradient": scaled, + "beta_gradient_max": receipt["beta_gradient_max"], "geometry_review": quality, + "geometry": summary, "trace": trace} + + +def run(args): + destination = ROOT / "pilot/cache" if args.pilot else CACHE + inventory = json.loads((destination / "native_inventory.json").read_text()) + if inventory["code_sha256"] != code_hashes() or inventory["pilot"] != args.pilot: + raise RuntimeError("fitting code/native extraction identity mismatch") + groups = defaultdict(list) + for entry in inventory["entries"]: + groups[(entry["source"], entry["subject"])].append(entry) + receipts = [] + for ordinal, key in enumerate(sorted(groups)): + if ordinal % args.shards == args.shard and sum(row["left_frames"] for row in groups[key]): + receipts.append(fit_subject(groups[key], destination, "cuda", + maximum_frames=32 if args.pilot else None)) + dump(destination / f"fit_shard_{args.shard}.json", {"receipts": receipts, "shards": args.shards, + "shard": args.shard, "pilot": args.pilot, "code_sha256": code_hashes()}) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--pilot", action="store_true") + parser.add_argument("--shard", type=int, default=0) + parser.add_argument("--shards", type=int, default=1) + args = parser.parse_args() + if not 0 <= args.shard < args.shards: + raise ValueError("invalid fitting shard") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + run(args) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/fit_quality.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/fit_quality.py new file mode 100644 index 0000000000000000000000000000000000000000..9455f10230af2de09f40fffeb8faf25571c1b47b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/fit_quality.py @@ -0,0 +1,48 @@ +"""All-frame geometry controls for fitting; gradients never determine quality.""" + +from runtime import torch, np, geometry +from geometry_metrics import PRIMARY, geometry_metrics, geometry_gate, summarize, distribution +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm + + +def inspect_geometry(layer, data, pose, beta, wrist, device, block=128): + values = {key: [] for key in (*PRIMARY, "max_vertex_mm")} + shifts = np.linalg.norm(wrist.numpy() - data["wrist"].numpy(), axis=-1) * 1000 + pose_shifts = [] + from runtime import axis_angle_to_matrix + with torch.no_grad(): + for first in range(0, len(pose), block): + last = min(first + block, len(pose)) + p = pose[first:last].to(device) + b = beta.to(device) if beta.ndim == 1 else beta[first:last].to(device) + v, j = geometry(layer, p, b, wrist[first:last].to(device)) + metrics = geometry_metrics(v.cpu().numpy(), j.cpu().numpy(), + data["vertices"][first:last].numpy(), data["joints"][first:last].numpy(), + data["joint_valid"][first:last].numpy(), aligned_mpjpe_mm) + for key in values: + values[key].append(metrics[key]) + rotations = axis_angle_to_matrix(p[:, 3:].reshape(-1, 15, 3)) + native = axis_angle_to_matrix(data["pose"][first:last, 3:].to(device).reshape(-1, 15, 3)) + relative = rotations @ native.transpose(-1, -2) + angles = torch.acos(((relative.diagonal(dim1=-2, dim2=-1).sum(-1) - 1) / 2).clamp(-1, 1)) + pose_shifts.extend(angles.square().mean(-1).sqrt().cpu().tolist()) + return summarize({key: np.concatenate(pieces) for key, pieces in values.items()}), { + "wrist_adjustment_mm": distribution(shifts), + "local_pose_adjustment_rms_rad": distribution(pose_shifts)} + + +def geometry_plateau(trace, settings): + count = settings["geometry_plateau_checkpoints"] + if len(trace) < count or trace[-1]["budget_used"] < settings["geometry_plateau_min_iterations"]: + return False + recent = trace[-count:] + if not all(row["geometry_review"]["geometry_review_pass"] for row in recent): + return False + controls = [(key, "mean", settings["geometry_plateau_mean_range_mm"]) for key in PRIMARY] + controls += [("mpvpe_mm", "p95", settings["geometry_plateau_p95_range_mm"]), + ("max_vertex_mm", "max", settings["geometry_plateau_worst_vertex_range_mm"])] + for metric, statistic, tolerance in controls: + values = [row["geometry"][metric][statistic] for row in recent] + if not np.isfinite(values).all() or max(values) - min(values) > tolerance: + return False + return True diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/geometry_metrics.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/geometry_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..959b012a45b1c37416d155dee72c6b4a72779af1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/geometry_metrics.py @@ -0,0 +1,96 @@ +"""Geometry-first diagnostics for native-to-corrected MANO fitting.""" + +import numpy as np + + +PRIMARY = ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", "pa_mpjpe_mm") +FINGERS = {name: np.arange(1 + 4 * index, 5 + 4 * index) + for index, name in enumerate(("thumb", "index", "middle", "ring", "little"))} + + +def distribution(values): + values = np.asarray(values, dtype=np.float64) + if not len(values): + return None + if not np.isfinite(values).all(): + raise ValueError("nonfinite geometry diagnostic") + return {"count": int(values.size), "mean": float(values.mean()), + "p95": float(np.quantile(values, .95)), "max": float(values.max())} + + +def masked_frame_mean(values, valid): + count = valid.sum(-1) + return np.divide(np.where(valid, values, 0).sum(-1), count, + out=np.full(len(values), np.nan), where=count > 0) + + +def geometry_metrics(vertices, joints, target_vertices, target_joints, valid, aligned): + vertices, joints, target_vertices, target_joints = [ + np.asarray(value, dtype=np.float64) + for value in (vertices, joints, target_vertices, target_joints)] + valid = np.asarray(valid, dtype=bool) + if vertices.shape != target_vertices.shape or joints.shape != target_joints.shape: + raise ValueError("prediction/target geometry shape mismatch") + if joints.shape[1:] != (21, 3) or valid.shape != joints.shape[:-1]: + raise ValueError("expected MANO 21-joint validity") + if not all(np.isfinite(value).all() for value in (vertices, joints, target_vertices, target_joints)): + raise ValueError("nonfinite geometry") + absolute = np.linalg.norm(joints - target_joints, axis=-1) * 1000 + relative = np.linalg.norm((joints - joints[:, :1]) + - (target_joints - target_joints[:, :1]), axis=-1) * 1000 + vertex = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000 + complete = valid.all(-1) + pa = np.full(len(joints), np.nan) + if complete.any(): + pa[complete] = aligned(joints[complete], target_joints[complete], estimate_scale=True) + result = {"absolute_mpjpe_mm": masked_frame_mean(absolute, valid), + "root_relative_mpjpe_mm": masked_frame_mean(relative, valid), + "mpvpe_mm": vertex.mean(-1), "pa_mpjpe_mm": pa, + "max_vertex_mm": vertex.max(-1)} + for finger, indices in FINGERS.items(): + result[f"{finger}_absolute_mpjpe_mm"] = masked_frame_mean(absolute[:, indices], valid[:, indices]) + result[f"{finger}_root_relative_mpjpe_mm"] = masked_frame_mean(relative[:, indices], valid[:, indices]) + result[f"{finger}_tip_mm"] = np.where(valid[:, indices[-1]], absolute[:, indices[-1]], np.nan) + chain = np.r_[0, indices] + pb, tb = np.diff(joints[:, chain], axis=1), np.diff(target_joints[:, chain], axis=1) + pl, tl = np.linalg.norm(pb, axis=-1), np.linalg.norm(tb, axis=-1) + pn = pb / np.maximum(pl[..., None], 1e-12) + tn = tb / np.maximum(tl[..., None], 1e-12) + pa_bend = np.arccos(np.clip((pn[:, :-1] * pn[:, 1:]).sum(-1), -1, 1)) + ta_bend = np.arccos(np.clip((tn[:, :-1] * tn[:, 1:]).sum(-1), -1, 1)) + cv = valid[:, chain] + bend_valid = (cv[:, :-2] & cv[:, 1:-1] & cv[:, 2:] + & (pl[:, :-1] > 1e-9) & (pl[:, 1:] > 1e-9) + & (tl[:, :-1] > 1e-9) & (tl[:, 1:] > 1e-9)) + result[f"{finger}_chain_bend_error_deg"] = masked_frame_mean( + np.rad2deg(np.abs(pa_bend - ta_bend)), bend_valid) + return result + + +def summarize(metrics): + return {key: distribution(value[np.isfinite(value)]) for key, value in metrics.items()} + + +def geometry_gate(summary, diagnostics, baseline, settings): + """Review quality, not gradient stationarity; never discard individual frames.""" + checks = { + "mesh_mean_mm": (summary["mpvpe_mm"]["mean"], settings["fit_mean_mpvpe_limit_mm"]), + "mesh_frame_p95_mm": (summary["mpvpe_mm"]["p95"], settings["fit_p95_mpvpe_limit_mm"]), + "worst_vertex_mm": (summary["max_vertex_mm"]["max"], settings["fit_max_vertex_limit_mm"]), + "worst_wrist_adjustment_mm": (diagnostics["wrist_adjustment_mm"]["max"], + settings["fit_max_wrist_adjustment_limit_mm"]), + "worst_local_pose_rms_rad": (diagnostics["local_pose_adjustment_rms_rad"]["max"], + settings["fit_max_local_pose_rms_limit_rad"]), + } + failures = [key for key, (value, limit) in checks.items() if value > limit] + # Counts are determined by native GT; no output-dependent metric filtering. + for metric in PRIMARY: + current, previous = summary[metric], baseline[metric] + if current is None or previous is None or current["count"] != previous["count"]: + failures.append(metric + ": missing/unpaired native-GT denominator") + elif current["mean"] > previous["mean"] + 1e-6: + failures.append(metric + ": worse than unadapted corrected-MANO baseline") + return {"geometry_review_pass": not failures, "failures": failures, + "checks": {key: {"value": value, "limit": limit} for key, (value, limit) in checks.items()}, + "gradient_stationarity_is_not_an_acceptance_gate": True, + "not_a_global_optimality_claim": True} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/gpu_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/gpu_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..c22be7a909fed11c5857b6835611ce07c4e81504 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/gpu_contract.py @@ -0,0 +1,74 @@ +"""Real converted-GT backward tests without retaining smoke optimizer updates.""" + +from common import (ROOT, CONFIG, base, model_for, ExpertDataset, + frozen_fingerprint, dump, torch, code_hashes) +from runtime import tensor_hash + + +def main(): + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + results = [] + for expert in ("K", "D"): + dataset = ExpertDataset(expert) + model = model_for(expert).to("cuda").train() + frozen = frozen_fingerprint(model) + optimizer = torch.optim.AdamW(model.branch.parameters(), lr=CONFIG["learning_rate"]) + for source, original in dataset.sources.items(): + spec = {"source": source, "tile_id": original.rows[0]["filtered_tile_id"], + "epoch": 0, "position": 0, "source_ordinal": 0, + "mode": "rgb_depth_k" if expert == "D" else "rgb_k"} + cpu = base.collate_h2o_clips([dataset[spec]]) + batch = base.move_to_device(cpu, torch.device("cuda")) + base.attach_gt_vertices(batch, model) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + parent = model.parent(batch) + rgb = dict(batch) + for key in ("K_available", "K_input_available", "depth_available", "depth_input_available"): + rgb[key] = torch.zeros_like(batch["frame_valid"]) + pure_parent = model.parent(rgb) + prediction = model(batch) + # The residual baseline is pure RGB, not the parent's legacy K path. + if any(not torch.equal(prediction[key], pure_parent[key]) for key in + ("vertices_camera", "joints_camera", "wrist_root_translation", "mano_shape")): + raise RuntimeError("zero-initialized branch differs from pure RGB parent") + for step in range(3): + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + losses = base.Objective(model)(batch) + if not bool(torch.isfinite(losses["total"])): + raise RuntimeError("nonfinite converted-GT smoke loss") + losses["total"].backward() + if any(parameter.grad is not None for parameter in model.parent.parameters()): + raise RuntimeError("canonical training gradient reached RGB parent") + norm = torch.nn.utils.clip_grad_norm_(model.branch.parameters(), CONFIG["grad_clip"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite converted-GT gradient") + optimizer.step() + if frozen_fingerprint(model) != frozen: + raise RuntimeError("converted-GT smoke changed frozen tensors") + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + fallback = model(rgb) + pure_parent = model.parent(rgb) + if any(not torch.equal(value, fallback[key]) for key, value in pure_parent.items() if torch.is_tensor(value)): + raise RuntimeError("post-update RGB fallback is not exact") + results.append({"expert": expert, "source": source, "loss": float(losses["total"]), + "grad_norm": float(norm), "frozen_parent_exact": True, + "rgb_fallback_exact": True, "target_contract": 3, + "target_hash": tensor_hash({key: cpu[key] for key in + ("vertices_camera", "mano_pose", "mano_shape", "wrist_root_translation")})}) + # Restore zero-init for the next independent source check. + del model, optimizer, batch, losses, prediction, fallback, parent, pure_parent + torch.cuda.empty_cache() + model = model_for(expert).to("cuda").train() + frozen = frozen_fingerprint(model) + optimizer = torch.optim.AdamW(model.branch.parameters(), lr=CONFIG["learning_rate"]) + del model, optimizer, dataset + torch.cuda.empty_cache() + dump(ROOT / "gpu_contract.json", {"status": "pass", "records": results, + "code_sha256": code_hashes(), "smoke_updates_discarded": True}) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/import_previous.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/import_previous.py new file mode 100644 index 0000000000000000000000000000000000000000..e3be75e2489b683b348b644d654d28d0801913a9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/import_previous.py @@ -0,0 +1,128 @@ +"""Reuse immutable V4 native inputs and explicitly distinguish completed fits.""" + +from collections import defaultdict +import json +from pathlib import Path +import shutil + +from runtime import CACHE, CONFIG, MANO_ROOT, dump, sha, code_hashes +from native_cache import inventory + + +def multistart_complete(receipt, settings): + labels = {row["initialization"] for row in receipt.get("trace", [])} + return set(settings["initializations"]).issubset(labels) and "winning_extension" in labels + + +def checked_copy(original, output): + expected = sha(original) + output.parent.mkdir(parents=True, exist_ok=True) + if output.exists(): + raise FileExistsError(output) + shutil.copyfile(original, output) + if sha(output) != expected or sha(original) != expected: + raise RuntimeError("V4 candidate changed during copy") + return expected + + +def run(): + policy = CONFIG["continuation"] + previous = Path(policy["previous_root"]) + path = previous / "cache/native_inventory.json" + if sha(path) != policy["native_inventory_sha256"]: + raise RuntimeError("registered V4 native inventory changed") + old = json.loads(path.read_text()) + if old["pilot"] or old["skipped"]: + raise RuntimeError("V4 cache is not a full no-drop inventory") + old_config = json.loads((previous / "config.json").read_text()) + for name, expected in old["code_sha256"].items(): + original = MANO_ROOT / name if name.startswith("MANO_") else previous / name + if sha(original) != expected: + raise RuntimeError("V4 registered implementation/asset changed: " + name) + for name in ("native_cache.py", "runtime.py", "targets.py"): + if code_hashes()[name] != old["code_sha256"][name]: + raise RuntimeError("native extraction/evaluation semantics changed: " + name) + # Only acceptance/stop policy changes. The objective, initialization and budget stay fixed. + for field, expected in old_config.items(): + if field not in ("experiment", "fitting") and CONFIG[field] != expected: + raise RuntimeError("controlled training recipe changed: " + field) + for field, expected in old_config["fitting"].items(): + if CONFIG["fitting"][field] != expected: + raise RuntimeError("fitting objective/budget contract changed: " + field) + _, manifests = inventory() + if manifests != old["training_manifests"]: + raise RuntimeError("training manifest identity changed") + dependencies = {} + for entry in old["entries"]: + dependencies[entry["path"]] = entry["sha256"] + for field in ("quality_masks", "annotation_inputs"): + for name, expected in entry[field].items(): + if name in dependencies and dependencies[name] != expected: + raise RuntimeError("conflicting dependency identity") + dependencies[name] = expected + for ordinal, (name, expected) in enumerate(dependencies.items(), 1): + if sha(name) != expected: + raise RuntimeError("immutable V4 annotation/cache changed: " + name) + if ordinal % 10000 == 0: + print(json.dumps({"phase": "verify_immutable_inputs", "done": ordinal, + "total": len(dependencies)}), flush=True) + review_root = Path(policy["geometry_review_root"]) + review = json.loads((review_root / "results.json").read_text()) + if (review["native_inventory_sha256"] != sha(path) + or review["original_V4_code_sha256"] != old["code_sha256"]): + raise RuntimeError("geometry review refers to different V4 inputs") + groups = defaultdict(list) + for entry in old["entries"]: + groups[(entry["source"], entry["subject"])].append(entry) + imported = [] + for (source, subject), entries in sorted(groups.items()): + identity = source + "_" + subject + complete = previous / "cache/fits" / (identity + ".npz") + working = previous / "cache/fits" / (identity + ".working.npz") + candidate = complete if complete.exists() else working + if not candidate.exists(): + continue + geometric = review["reports"][identity] + if sha(candidate) != geometric["candidate_sha256"] or not geometric["geometry_review"]["geometry_review_pass"]: + raise RuntimeError("V4 reviewed candidate changed or failed geometry: " + identity) + receipt_path = complete.with_suffix(".json") if complete.exists() else complete.with_suffix(".failed.json") + evidence = json.loads(receipt_path.read_text()) if receipt_path.exists() else {} + if complete.exists() and (evidence["code_sha256"] != old["code_sha256"] + or evidence["sha256"] != sha(candidate) + or evidence["native_sha256"] != {row["recording"]: row["sha256"] for row in entries}): + raise RuntimeError("V4 completed fit provenance mismatch") + reusable = multistart_complete(evidence, CONFIG["fitting"]) + output = CACHE / ("fits" if reusable else "warm_starts") / (identity + ".npz") + copied_sha = checked_copy(candidate, output) + receipt = {"source": source, "subject": subject, "path": str(output), "sha256": copied_sha, + "frames": geometric["frames"], "pilot": False, + "native_sha256": {row["recording"]: row["sha256"] for row in entries}, + "code_sha256": code_hashes(), "optimization_complete": reusable, + "converged": evidence.get("converged", False), + "gradient_stationarity_is_diagnostic_only": True, + "geometry_review": geometric["geometry_review"], + "trace": evidence.get("trace", []), + "upstream": {"candidate": str(candidate), "candidate_sha256": copied_sha, + "V4_code_sha256": old["code_sha256"], + "evidence_path": str(receipt_path) if evidence else None, + "evidence_sha256": sha(receipt_path) if evidence else None, + "geometry_review_sha256": sha(review_root / (identity + ".json"))}} + dump(output.with_suffix(".json"), receipt) + imported.append({"identity": identity, "optimization_complete": reusable, "sha256": copied_sha}) + rebound = {**old, "code_sha256": code_hashes(), "reuse_provenance": { + "previous_inventory": str(path), "previous_inventory_sha256": sha(path), + "previous_code_sha256": old["code_sha256"], "immutable_inputs_verified": len(dependencies), + "native_extraction_code_unchanged": True, "new_fit_policy": policy["acceptance"]}} + if (CACHE / "native_inventory.json").exists(): + raise FileExistsError(CACHE / "native_inventory.json") + dump(CACHE / "native_inventory.json", rebound) + dump(CACHE / "reuse_receipt.json", {"imported_candidates": imported, + "groups_total": len(groups), "physical_frames": old["physical_frames"], + "eligible_left_frames": old["eligible_left_frames"], + "native_payloads_read_only_at_V4_paths": True, + "does_not_release_training_labels": True, "code_sha256": code_hashes()}) + print(json.dumps({"phase": "reuse_complete", "candidates": imported, "groups": len(groups)}), flush=True) + + +if __name__ == "__main__": + run() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/launch.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..31429b07e83c8e43292f82523626739dbfa6c094 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/launch.py @@ -0,0 +1,19 @@ +"""Detach only this new registered queue; do not replace any running experiment.""" + +import json +import os +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parent + +if __name__ == "__main__": + path = ROOT / "controller.log" + with path.open("xb") as log: + process = subprocess.Popen([sys.executable, "-u", str(ROOT / "controller.py")], cwd=ROOT, + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, close_fds=True, + env=dict(os.environ, PYTHONUNBUFFERED="1")) + (ROOT / "controller.pid").write_text(str(process.pid) + "\n") + print(json.dumps({"controller_pid": process.pid, "log": str(path)}), flush=True) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/native_cache.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/native_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..34f53f1cddf2a30d028e7b117f2459650aaa7512 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/native_cache.py @@ -0,0 +1,237 @@ +"""Export source-native training annotations without decoding image sequences.""" + +from collections import defaultdict +import argparse +import json +from pathlib import Path + +from runtime import (BASE_ROOT, CACHE, CODE, CONFIG, MANO_ROOT, ROOT, torch, np, + ManoCameraLayer, geometry, axis_angle_to_matrix, + matrix_to_axis_angle, project_points, resize_and_pad_intrinsics, + dump, save_npz, sha, tensor_hash, code_hashes) +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record, load_mano_record +from foundation_hand.data.h2o_dataset import _fit_resize +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +def record_key(source, row): + return row["take"] if source == "H2O" else row["physical_recording_id"] + + +def record_id(source, recording): + import hashlib + return source + "_" + hashlib.sha256(recording.encode()).hexdigest()[:20] + + +def inventory(): + groups = defaultdict(list) + manifests = {} + for source in ("H2O", "ARCTIC"): + path = BASE_ROOT / "cache/adapter_trainable_t8" / (source.lower() + "_t8.jsonl") + manifests[source] = {"path": str(path), "sha256": sha(path)} + with path.open() as stream: + for line in stream: + row = json.loads(line) + if source == "ARCTIC" and (row["split_role"] != "arctic_p2_train" + or row["official_test_used"] is not False): + raise RuntimeError("nontraining ARCTIC row") + groups[(source, record_key(source, row))].append(row) + return groups, manifests + + +def filtered_frames(rows): + seen, inputs = {}, {} + for row in rows: + path = row["filtered_gt_path"] + if path not in inputs: + with np.load(path, allow_pickle=False) as payload: + inputs[path] = {"frame_ids": payload["frame_ids"].copy(), + "valid": payload["valid"].astype(bool).copy(), "sha256": sha(path)} + payload = inputs[path] + start = row["filtered_start_offset"] + ids = payload["frame_ids"][start:start + 8] + masks = payload["valid"][start:start + 8] + if not np.array_equal(ids, row["expected_frame_ids"]) or masks.shape != (8, 2): + raise RuntimeError("quality-mask/native frame identity mismatch") + for frame, mask in zip(ids, masks): + frame = int(frame) + seen[frame] = seen.get(frame, np.zeros(2, bool)) | mask + frames = np.array(sorted(seen), dtype=np.int64) + masks = np.stack([seen[int(frame)] for frame in frames]) + return frames, masks, {key: value["sha256"] for key, value in inputs.items()} + + +def arctic_annotation_indices(rows, frame_ids): + mapping = {} + for row in rows: + ids = row["expected_frame_ids"] + indices = row["array_indices_0based"] + if ids != row["frame_ids_1based"] or len(ids) != len(indices): + raise RuntimeError("ARCTIC manifest image/annotation identity mismatch") + for frame, index in zip(ids, indices): + frame, index = int(frame), int(index) + if index < 0 or (frame in mapping and mapping[frame] != index): + raise RuntimeError("ARCTIC duplicate frame has inconsistent annotation index") + mapping[frame] = index + if any(int(frame) not in mapping for frame in frame_ids): + raise RuntimeError("ARCTIC annotation index missing from training manifest") + return np.array([mapping[int(frame)] for frame in frame_ids], dtype=np.int64) + + +def source_annotations(source, recording, row, frame_ids, device, annotation_indices=None): + paths = {} + if source == "H2O": + take = Path("/SSD3/jiasen/foundation_hand/H2O/extracted") / recording + poses, betas, wrists, joint_rows, valid = [], [], [], [], [] + for frame in frame_ids: + stem = f"{int(frame):06d}.txt" + joint_path, mano_path = take / "hand_pose" / stem, take / "hand_pose_mano" / stem + joint, mano = load_joint_record(joint_path), load_mano_record(mano_path) + if not np.array_equal(joint.annotation_valid, mano.annotation_valid): + raise RuntimeError("H2O joint/MANO annotation validity mismatch") + poses.append(mano.pose_axis_angle) + betas.append(mano.shape) + wrists.append(joint.joints_camera_m[:, 0]) + joint_rows.append(joint.joints_camera_m) + valid.append(joint.annotation_valid) + paths[str(joint_path)], paths[str(mano_path)] = sha(joint_path), sha(mano_path) + pose, beta, wrist, joints = [torch.tensor(np.stack(value), dtype=torch.float64, device=device) + for value in (poses, betas, wrists, joint_rows)] + native = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=False).double().to(device) + vertices = [] + for first in range(0, len(pose), 256): + with torch.no_grad(): + v, _ = native(axis_angle_to_matrix(pose[first:first + 256].reshape(-1, 2, 16, 3)), + beta[first:first + 256], wrist[first:first + 256]) + vertices.append(v) + vertices = torch.cat(vertices) + K, hw = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + paths[str(take / "cam_intrinsics.txt")] = sha(take / "cam_intrinsics.txt") + resized, pad = _fit_resize(hw, (512, 896)) + K = torch.tensor(resize_and_pad_intrinsics(K, hw, resized, pad), dtype=torch.float64, device=device) + hand = torch.tensor(np.stack(valid), dtype=torch.bool, device=device) + else: + paths = {row[key]: sha(row[key]) for key in ("mano_path", "camera_path")} + mano = np.load(row["mano_path"], allow_pickle=True).item() + camera = np.load(row["camera_path"], allow_pickle=True).item() + if annotation_indices is None or len(annotation_indices) != len(frame_ids): + raise RuntimeError("ARCTIC requires explicit manifest annotation indices") + indices = annotation_indices + lengths = [len(camera[key]) for key in ("R_k_cam_np", "T_k_cam_np")] + lengths += [len(mano[side][key]) for side in ("left", "right") + for key in ("rot", "pose", "trans")] + if indices.min() < 0 or indices.max() >= min(lengths): + raise RuntimeError("ARCTIC manifest index exceeds official annotation arrays") + R = torch.tensor(camera["R_k_cam_np"][indices], dtype=torch.float64, device=device) + t = torch.tensor(camera["T_k_cam_np"][indices, :, 0], dtype=torch.float64, device=device) + pose_rows, beta_rows, vertices_rows, joint_rows = [], [], [], [] + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + for label in ("left", "right"): + values = mano[label] + raw = torch.tensor(np.concatenate((values["rot"][indices], values["pose"][indices]), -1), + dtype=torch.float64, device=device) + beta_side = torch.tensor(np.repeat(np.asarray(values["shape"])[None], len(indices), axis=0), + dtype=torch.float64, device=device) + trans = torch.tensor(values["trans"][indices], dtype=torch.float64, device=device) + layer = ManoLayer(mano_root=str(MANO_ROOT), side=label, use_pca=False, + ncomps=45, flat_hand_mean=False).double().to(device) + v_rows, j_rows = [], [] + for first in range(0, len(raw), 256): + with torch.no_grad(): + v, j = layer(raw[first:first + 256], beta_side[first:first + 256]) + v_rows.append(v) + j_rows.append(j) + v, j = torch.cat(v_rows), torch.cat(j_rows) + vertices_rows.append((v / 1000 + trans[:, None]) @ R.transpose(-1, -2) + t[:, None]) + joint_rows.append((j / 1000 + trans[:, None]) @ R.transpose(-1, -2) + t[:, None]) + pose_rows.append(torch.cat((matrix_to_axis_angle(R @ axis_angle_to_matrix(raw[:, :3])), + raw[:, 3:] + layer.th_hands_mean), -1)) + beta_rows.append(beta_side) + pose, beta = torch.stack(pose_rows, 1), torch.stack(beta_rows, 1) + vertices, joints = torch.stack(vertices_rows, 1), torch.stack(joint_rows, 1) + wrist = joints[:, :, 0].clone() + K_input = resize_and_pad_intrinsics(camera["intrinsics"], (2000, 2800), (600, 840), (0, 0)) + resized, pad = _fit_resize((600, 840), (512, 896)) + K = torch.tensor(resize_and_pad_intrinsics(K_input, (600, 840), resized, pad), + dtype=torch.float64, device=device) + uv, positive = project_points(vertices, K.expand(len(pose), -1, -1)) + hand = (positive & (uv[..., 0] >= 0) & (uv[..., 0] < 896) + & (uv[..., 1] >= 0) & (uv[..., 1] < 512)).any(-1) + K = K[None].expand(len(pose), -1, -1) + uv, positive = project_points(joints, K) + joint_valid = positive & torch.isfinite(joints).all(-1) & hand[..., None] + valid2d = joint_valid.clone() + if source == "ARCTIC": + valid2d &= (uv[..., 0] >= 0) & (uv[..., 0] < 896) & (uv[..., 1] >= 0) & (uv[..., 1] < 512) + return {"pose": pose, "beta": beta, "wrist": wrist, "joints": joints, + "vertices": vertices, "K": K, "joint2d": uv, "joint_valid": joint_valid, + "joint2d_valid": valid2d, "hand": hand}, paths + + +def prepare(device="cuda", maximum_records=None, destination=CACHE): + groups, manifests = inventory() + entries, skipped = [], [] + destination = Path(destination) + destination.mkdir(parents=True, exist_ok=True) + chosen = sorted(groups) + if maximum_records is not None: + # Balanced pilot: first recording for each source, without replacing empty frames. + chosen = [next(key for key in chosen if key[0] == source) for source in ("H2O", "ARCTIC")] + for source, recording in chosen: + rows = groups[source, recording] + path = destination / "native" / (record_id(source, recording) + ".npz") + receipt_path = path.with_suffix(".json") + frame_ids, quality, mask_hashes = filtered_frames(rows) + indices = arctic_annotation_indices(rows, frame_ids) if source == "ARCTIC" else None + if path.exists() and receipt_path.exists(): + old = json.loads(receipt_path.read_text()) + if old["sha256"] != sha(path) or old["quality_masks"] != mask_hashes: + raise RuntimeError("existing native cache changed") + for name, expected in old["annotation_inputs"].items(): + if sha(name) != expected: + raise RuntimeError("native annotation input changed") + entries.append(old) + continue + obs, annotation_inputs = source_annotations(source, recording, rows[0], frame_ids, device, indices) + hand = obs["hand"] & torch.tensor(quality, device=device) + hand &= torch.isfinite(obs["pose"]).all(-1) & torch.isfinite(obs["beta"]).all(-1) + hand &= torch.isfinite(obs["vertices"]).all(dim=(-1, -2)) & torch.isfinite(obs["joints"]).all(dim=(-1, -2)) + obs["hand"] = hand + for key in ("joint_valid", "joint2d_valid"): + obs[key] &= hand[..., None] + arrays = {key: value.detach().cpu().numpy() for key, value in obs.items()} + arrays.update(frame_ids=frame_ids, quality_valid=quality) + if indices is not None: + arrays["annotation_indices"] = indices + subject = recording.split("/")[0] if source == "H2O" else rows[0]["subject_id"] + save_npz(path, **arrays) + entry = {"source": source, "recording": recording, "subject": subject, + "path": str(path), "sha256": sha(path), "target_sha256": tensor_hash(arrays), + "frames": len(frame_ids), "tiles": len(rows), + "left_frames": int(hand[:, 0].sum()), "right_frames": int(hand[:, 1].sum()), + "quality_masks": mask_hashes, "annotation_inputs": annotation_inputs} + dump(receipt_path, entry) + entries.append(entry) + print(json.dumps({"phase": "native_cache", "source": source, "recording": recording, + "records_done": len(entries), "records_total": len(chosen), + "eligible_left_frames": entry["left_frames"]}), flush=True) + dump(destination / "native_progress.json", {"done": len(entries), "total": len(chosen)}) + result = {"entries": entries, "training_manifests": manifests, + "code_sha256": code_hashes(), "pilot": maximum_records is not None, + "physical_frames": sum(row["frames"] for row in entries), + "eligible_left_frames": sum(row["left_frames"] for row in entries), "skipped": skipped} + dump(destination / "native_inventory.json", result) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--pilot", action="store_true") + args = parser.parse_args() + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + prepare(maximum_records=2 if args.pilot else None, + destination=ROOT / "pilot/cache" if args.pilot else CACHE) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/preflight_geometry.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/preflight_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..e07c58f731302395cc634697f2b11b8c184a8d4c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/preflight_geometry.py @@ -0,0 +1,58 @@ +"""Exercise the new complete geometry review on immutable real V4 pilot fits.""" + +from collections import defaultdict +import json +from pathlib import Path + +from runtime import ROOT, CACHE, CONFIG, MANO_ROOT, torch, np, ManoCameraLayer, dump, sha, code_hashes +from fit_cache import load_subject +from fit_quality import inspect_geometry, geometry_gate +from audit_cache import inspect_fit + + +def run(): + previous = Path(CONFIG["continuation"]["previous_root"]) + pilot = previous / "pilot/cache" + native = json.loads((pilot / "native_inventory.json").read_text()) + original = json.loads((CACHE / "native_inventory.json").read_text())["reuse_provenance"]["previous_code_sha256"] + if not native["pilot"] or native["code_sha256"] != original: + raise RuntimeError("real pilot source differs from verified V4") + groups = defaultdict(list) + for entry in native["entries"]: + groups[(entry["source"], entry["subject"])].append(entry) + layer = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=True).layers[0].double().eval() + results = {} + for (source, subject), entries in sorted(groups.items()): + data = load_subject(entries) + data = {key: value[:32] for key, value in data.items()} + path = pilot / "fits" / (source + "_" + subject + ".npz") + receipt = json.loads(path.with_suffix(".json").read_text()) + if (sha(path) != receipt["sha256"] or receipt["code_sha256"] != original + or receipt["native_sha256"] != {row["recording"]: row["sha256"] for row in entries}): + raise RuntimeError("real pilot fit provenance mismatch") + with np.load(path, allow_pickle=False) as payload: + fit = {key: payload[key].copy() for key in payload.files} + if (fit["pose"].shape != data["pose"].shape or fit["beta"].shape != (10,) + or not np.array_equal(fit["record_index"], data["record_index"]) + or not np.array_equal(fit["frame_index"], data["frame_index"])): + raise RuntimeError("real pilot coverage/shared-beta mismatch") + baseline, _ = inspect_geometry(layer, data, data["pose"], data["beta"], data["wrist"], "cpu") + summary, diagnostic = inspect_geometry(layer, data, torch.from_numpy(fit["pose"]), + torch.from_numpy(fit["beta"]), torch.from_numpy(fit["wrist"]), "cpu") + review = geometry_gate(summary, diagnostic, baseline, CONFIG["fitting"]) + reconstruction = inspect_fit(layer, data, fit, "cpu") + if not review["geometry_review_pass"] or reconstruction["conditional_wrist_identity_error_mm"] > 1e-5: + raise RuntimeError("real pilot failed new geometry-first contract: " + source + "/" + subject) + results[source + "/" + subject] = {"four_mm": summary, "geometry_review": review, + "conditional_wrist_identity_error_mm": reconstruction["conditional_wrist_identity_error_mm"]} + if {key.split("/")[0] for key in results} != {"H2O", "ARCTIC"}: + raise RuntimeError("real preflight requires both source conventions") + report = {"status": "pass", "pilot_only_not_full_data_release": True, + "code_sha256": code_hashes(), "sources": results} + dump(ROOT / "preflight/real_geometry_policy_cpu.json", report) + print(json.dumps(report), flush=True) + + +if __name__ == "__main__": + torch.set_num_threads(2) + run() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/run_after_audit.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/run_after_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..894509053d8e5428dccfda31ec6f782dcd52f1f7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/run_after_audit.py @@ -0,0 +1,87 @@ +"""Resume the A7 recipe from audited rotation-fixed labels, without refitting GT.""" + +import fcntl +import json +from pathlib import Path +import shutil +import time + +from runtime import ROOT, CACHE, CODE, CONFIG, dump, sha +from common import code_hashes, load_parent +from controller import (event, reserve, execute, train, evaluate, + resume_check, report, release_physical_gpu_claim) + + +def check_registration(): + original = json.loads((Path(CONFIG["reference_a7"]) / "config.json").read_text()) + for field in ("parent_sha256", "seed", "global_batch", "updates", "milestones", + "warmup_clips", "learning_rate", "min_learning_rate", "grad_clip", + "weight_decay", "workers_per_rank", "order", "source_quota_K", + "source_D", "dino_trainable_blocks"): + if CONFIG[field] != original[field]: + raise RuntimeError(f"controlled A7 recipe field changed: {field}") + if (CONFIG["world_size"] != 6 or CONFIG["global_batch"] % 6 + or CONFIG["permitted_gpus"] != list(range(6))): + raise RuntimeError("six-GPU registered batch/device contract changed") + if CODE != Path(CONFIG["code_root"]) or CACHE != Path(CONFIG["cache_root"]): + raise RuntimeError("versioned code or cache path changed") + if shutil.disk_usage(ROOT).free < CONFIG["minimum_free_disk_gib"] * 1024**3: + raise RuntimeError("training disk reserve below registered 200 GiB") + parent = load_parent() + del parent + return code_hashes() + + +def main(): + lock = (ROOT / "controller.lock").open("a") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + gpus = [] + try: + hashes = check_registration() + dump(ROOT / "registration.json", { + "config": CONFIG, "code_sha256": hashes, + "label_audit_sha256": sha(CACHE / "audit.json"), + "migration_sha256": sha(CACHE / "migration.json"), + "rotation_fix_sha256": sha(CODE / "src/foundation_hand/geometry/rotations.py"), + "controlled_change": "world_size 4 to 6 at unchanged global batch 12", + "fitting_reused": True, "original_V5_untouched": True, + "training_not_started_at_registration": True}) + event("registered_rotationfix_six_gpu") + execute("unit_tests", ["-m", "unittest", "discover", "-p", "test_*.py", "-v"]) + while not gpus: + gpus = reserve() + if not gpus: + event("waiting_for_six_idle_gpus", non_preempting=True) + time.sleep(30) + event("preflight_running", gpus=gpus) + execute("gpu_contract", [str(ROOT / "gpu_contract.py")], gpus[:1]) + for expert in CONFIG["order"]: + smoke = train(expert, 2, gpus, ROOT / "preflight" / expert, + smoke=True, label="smoke_" + expert) + evaluate(expert, "H2O", "development", gpus, smoke, smoke=True) + resume_check(gpus) + if code_hashes() != hashes: + raise RuntimeError("registered code/cache hashes changed during preflight") + event("preflight_pass_starting_matched_training", gpus=gpus) + for expert in CONFIG["order"]: + previous = None + for endpoint in CONFIG["milestones"]: + previous = train(expert, endpoint, gpus, resume=previous) + for source in (("H2O",) if expert == "D" else ("H2O", "ARCTIC", "HOT3D")): + evaluate(expert, source, "development", gpus, previous) + for source in (("H2O",) if expert == "D" else ("H2O", "ARCTIC", "HOT3D")): + evaluate(expert, source, "confirmation", gpus, previous) + for source in ("H2O", "ARCTIC", "HOT3D"): + evaluate("RGB", source, "confirmation", gpus) + report() + event("complete", results=str(ROOT / "RESULTS.md")) + except BaseException as error: + event("failed_requires_diagnosis", error=repr(error)) + raise + finally: + for gpu in gpus: + release_physical_gpu_claim(gpu) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/runtime.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..dbbfca5c22a38818ddef16dfef48a4966620dd0f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/runtime.py @@ -0,0 +1,82 @@ +"""Shared paths and fixed MANO geometry; no parent checkpoint loaded on import.""" + +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +BASE_ROOT = Path(CONFIG["base_root"]) +CODE = Path(os.environ.get("FH_A7_TEST_CODE", CONFIG.get("code_root", str(BASE_ROOT / "code")))) +sys.path[:0] = [str(CODE), str(CODE / "src")] + +import numpy as np +import torch +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.geometry.rotations import axis_angle_to_matrix, matrix_to_axis_angle +from foundation_hand.geometry.camera import project_points, resize_and_pad_intrinsics + +MANO_ROOT = Path("/SSD3/jiasen/foundation_hand/pretrained/mano") +CACHE = Path(CONFIG.get("cache_root", str(ROOT / "cache"))) + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024**2), b""): + digest.update(block) + return digest.hexdigest() + + +def dump(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") + temporary.replace(path) + + +def save_npz(path, **values): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + with temporary.open("wb") as stream: + np.savez_compressed(stream, **values) + temporary.replace(path) + + +def code_hashes(): + return {path.name: sha(path) for path in sorted(ROOT.glob("*.py"))} | { + "config.json": sha(ROOT / "config.json"), + "MANO_LEFT.pkl": sha(MANO_ROOT / "MANO_LEFT.pkl"), + "MANO_RIGHT.pkl": sha(MANO_ROOT / "MANO_RIGHT.pkl"), + } + + +def geometry(layer, pose, beta, wrist): + if beta.ndim == 1: + beta = beta.expand(len(pose), -1) + vertices, joints = layer(pose, beta) + return ((vertices - joints[:, :1]) / 1000 + wrist[:, None], + (joints - joints[:, :1]) / 1000 + wrist[:, None]) + + +def stats(values): + values = np.asarray(values, dtype=np.float64) + if not len(values) or not np.isfinite(values).all(): + raise RuntimeError("empty/nonfinite diagnostic distribution") + return {"count": int(len(values)), "mean": float(values.mean()), + "p95": float(np.quantile(values, .95)), "max": float(values.max())} + + +def tensor_hash(values): + digest = hashlib.sha256() + for key, value in sorted(values.items()): + value = value.detach().cpu().numpy() if torch.is_tensor(value) else np.asarray(value) + digest.update(str((key, value.shape, value.dtype)).encode()) + digest.update(np.ascontiguousarray(value).tobytes()) + return digest.hexdigest() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/targets.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/targets.py new file mode 100644 index 0000000000000000000000000000000000000000..f14f29e06e54ffba5aacdd0b30f263925f8b36c6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/targets.py @@ -0,0 +1,155 @@ +"""Source-native evaluation targets and versioned canonical training labels.""" + +from functools import lru_cache +import json + +from runtime import (CACHE, CODE, MANO_ROOT, torch, np, ManoCameraLayer, + axis_angle_to_matrix, matrix_to_axis_angle, geometry, sha) +from foundation_hand.data.schema import source_root_relative_joint_target +from native_cache import record_key + + +def native_targets(source, native, row, sample, source_mano): + """Keep native mesh/joints unchanged; compatible parameter masks are separate.""" + pose, shape, wrist = [sample[key].clone() for key in + ("mano_pose", "mano_shape", "wrist_root_translation")] + time = len(sample["frame_valid"]) + if source == "H2O": + with torch.no_grad(): + vertices, _ = source_mano(axis_angle_to_matrix(torch.nan_to_num(pose).reshape(time, 2, 16, 3)), + torch.nan_to_num(shape), torch.nan_to_num(wrist)) + joints = sample["joint3d_camera"].clone() + hand = sample["joint_annotation_valid"].bool() & sample["mano_annotation_valid"].bool() + elif source == "ARCTIC": + mano, camera = native._sequence(row) + ids = row["array_indices_0based"] + R = torch.from_numpy(camera["R_k_cam_np"][ids].astype(np.float32)) + t = torch.from_numpy(camera["T_k_cam_np"][ids, :, 0].astype(np.float32)) + vertices, joints = torch.empty(time, 2, 778, 3), torch.empty(time, 2, 21, 3) + for side, label in enumerate(("left", "right")): + values = mano[label] + raw = torch.from_numpy(np.concatenate((values["rot"][ids], values["pose"][ids]), -1).astype(np.float32)) + beta = torch.from_numpy(np.repeat(np.asarray(values["shape"], np.float32)[None], time, axis=0)) + trans = torch.from_numpy(values["trans"][ids].astype(np.float32)) + with torch.no_grad(): + v, j = native._source_mano[label](raw, beta) + vertices[:, side] = (v / 1000 + trans[:, None]) @ R.transpose(-1, -2) + t[:, None] + joints[:, side] = (j / 1000 + trans[:, None]) @ R.transpose(-1, -2) + t[:, None] + pose[:, side, :3] = matrix_to_axis_angle(R @ axis_angle_to_matrix(raw[:, :3])) + pose[:, side, 3:] = raw[:, 3:] + native._source_mano[label].th_hands_mean + shape[:, side], wrist[:, side] = beta, joints[:, side, 0] + hand = sample["translation_valid"].bool() + elif source == "HOT3D": + provider, api = native._provider(str(row["recording_id"])), native._api + vertices = torch.full((time, 2, 778, 3), float("nan")) + for frame, timestamp in enumerate(row["timestamps_ns"]): + collection = provider.mano_hand_data_provider.get_pose_at_timestamp( + int(timestamp), api["TimeQueryOptions"].CLOSEST, + api["TimeDomain"].TIME_CODE, 20_000_000).pose3d_collection + w2c = np.linalg.inv(sample["camera_pose"][frame].double().numpy()) + for label, side in ((api["Handedness"].Left, 0), (api["Handedness"].Right, 1)): + if label in collection.poses: + raw = provider.mano_hand_data_provider.get_hand_mesh_vertices(collection.poses[label]) + if raw is not None: + vertices[frame, side] = torch.from_numpy( + (raw.detach().numpy() @ w2c[:3, :3].T + w2c[:3, 3]).astype(np.float32)) + joints = sample["joint3d_camera"].clone() + hand = sample["vertices_valid"].bool() + else: + raise ValueError(source) + hand &= sample["frame_valid"][:, None] & torch.isfinite(vertices).all(dim=(-1, -2)) + hand &= torch.isfinite(joints).all(dim=(-1, -2)) + sample.update(vertices_camera=vertices, joint3d_camera=joints, mano_pose=pose, + mano_shape=shape, wrist_root_translation=wrist) + sample["translation_valid"], sample["vertices_valid"] = hand.clone(), hand.clone() + joint = hand[..., None] & torch.isfinite(joints).all(-1) + if source == "H2O": + joint &= sample["joint3d_valid"] + sample["joint3d_valid"] = sample["joint_element_valid"] = joint + sample["joint_annotation_valid"] = hand.clone() + sample["joint3d_root_relative"], sample["joint3d_root_relative_valid"] = source_root_relative_joint_target(joints, hand) + sample["joint2d_valid"] &= hand[..., None] + sample["reprojection_valid"] = sample["joint2d_valid"].clone() + return sample + + +class NativePanel: + def __init__(self, source, native, rows): + self.source, self.native, self.rows = source, native, rows + self.source_mano = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=False).eval() + + def __len__(self): + return len(self.native) + + def __getitem__(self, index): + return native_targets(self.source, self.native, self.rows[index], self.native[index], self.source_mano) + + +class CanonicalLabels: + def __init__(self, source, rows, cache=CACHE): + self.source, self.rows = source, rows + self.cache = cache + self.mano = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=True).eval() + self.source_mano = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=False).eval() + self.inventory = json.loads((cache / "label_inventory.json").read_text()) + self.entries = {row["recording"]: row for row in self.inventory["entries"] if row["source"] == source} + self._recording, self._arrays = None, None + self._verified_files = {} + + def apply(self, sample, row, native): + if self.source == "HOT3D": + sample = native_targets(self.source, native, row, sample, self.source_mano) + pose, beta, wrist = sample["mano_pose"], sample["mano_shape"], sample["wrist_root_translation"] + with torch.no_grad(): + v, j = self.mano(axis_angle_to_matrix(torch.nan_to_num(pose).reshape(-1, 2, 16, 3)), + torch.nan_to_num(beta), torch.nan_to_num(wrist)) + compatible = (torch.linalg.vector_norm(v - sample["vertices_camera"], dim=-1).amax(-1) * 1000 <= 1) + compatible &= sample["vertices_valid"] & torch.isfinite(pose).all(-1) & torch.isfinite(beta).all(-1) + sample["global_orientation_valid"] = sample["vertices_valid"].clone() + sample["local_pose_valid"] = sample["shape_valid"] = sample["mano_pose_valid"] = compatible + sample["mano_annotation_valid"] = compatible.clone() + else: + recording = record_key(self.source, row) + entry = self.entries[recording] + if self._recording != recording: + from pathlib import Path + state = Path(entry["path"]).stat() + identity = (state.st_size, state.st_mtime_ns, entry["sha256"]) + if self._verified_files.get(entry["path"]) != identity: + if sha(entry["path"]) != entry["sha256"]: + raise RuntimeError("canonical training cache was modified") + self._verified_files[entry["path"]] = identity + with np.load(entry["path"], allow_pickle=False) as payload: + # Parameter arrays are small; do not decompress a full recording's mesh per tile. + self._arrays = {key: payload[key].copy() for key in + ("frame_ids", "pose", "beta", "wrist", "hand", "joint_valid", "joint2d_valid")} + self._recording = recording + arrays = self._arrays + ids = np.array(row["expected_frame_ids"], dtype=np.int64) + indices = np.searchsorted(arrays["frame_ids"], ids) + if not np.array_equal(arrays["frame_ids"][indices], ids): + raise RuntimeError("canonical cache missing a registered training frame") + values = {key: torch.from_numpy(arrays[key][indices].copy()) for key in + ("pose", "beta", "wrist", "hand", "joint_valid", "joint2d_valid")} + hand = values["hand"].bool() & sample["frame_valid"][:, None] + pose, beta, wrist = values["pose"].float(), values["beta"].float(), values["wrist"].float() + native_joints = sample["joint3d_camera"].clone() + with torch.no_grad(): + vertices, joints = self.mano(axis_angle_to_matrix(pose.reshape(-1, 2, 16, 3)), beta, wrist) + right_v, _ = geometry(self.source_mano.layers[1], pose[:, 1], beta[:, 1], wrist[:, 1]) + vertices[:, 1] = right_v + joints[:, 1] = native_joints[:, 1] + sample.update(mano_pose=values["pose"].float(), mano_shape=values["beta"].float(), + wrist_root_translation=wrist, vertices_camera=vertices, joint3d_camera=joints) + for key in ("translation_valid", "vertices_valid", "global_orientation_valid", + "local_pose_valid", "shape_valid", "mano_pose_valid", "mano_annotation_valid", + "joint_annotation_valid"): + sample[key] = hand.clone() + sample["joint3d_valid"] = sample["joint_element_valid"] = values["joint_valid"].bool() & hand[..., None] + sample["joint3d_root_relative"], sample["joint3d_root_relative_valid"] = source_root_relative_joint_target( + sample["joint3d_camera"], hand) + # Keep the actual source 2D observations and their viewport validity. + sample["joint2d_valid"] &= values["joint2d_valid"].bool() & hand[..., None] + sample["reprojection_valid"] = sample["joint2d_valid"].clone() + sample["mano_target_contract_version"] = torch.full_like(sample["frame_valid"], 3, dtype=torch.long) + return sample diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_continuation.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_continuation.py new file mode 100644 index 0000000000000000000000000000000000000000..10e7029c888a060a15ee1cbb407b97ade712838a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_continuation.py @@ -0,0 +1,74 @@ +"""Geometry plateaus do not bypass quality or multistart/coverage contracts.""" + +import copy +from pathlib import Path +import tempfile +import unittest + +from runtime import CONFIG, torch, ManoCameraLayer, MANO_ROOT, geometry +from geometry_metrics import PRIMARY +from fit_quality import geometry_plateau, inspect_geometry +from import_previous import multistart_complete +from fit_cache import joint_fit + + +class ContinuationTests(unittest.TestCase): + def trace(self): + result = [] + for budget in (64, 128, 192, 256): + result.append({"budget_used": budget, "scaled_pose_gradient_max": 100, + "geometry_review": {"geometry_review_pass": True}, + "geometry": {**{key: {"mean": 1., "p95": 1.5} for key in PRIMARY}, + "max_vertex_mm": {"max": 4.}}}) + return result + + def test_large_gradient_does_not_block_geometry_plateau(self): + self.assertTrue(geometry_plateau(self.trace(), CONFIG["fitting"])) + + def test_insufficient_checkpoint_history_does_not_stop(self): + self.assertFalse(geometry_plateau(self.trace()[:3], CONFIG["fitting"])) + + def test_bad_geometry_cannot_stop_even_when_stable(self): + rows = self.trace() + rows[-1]["geometry_review"]["geometry_review_pass"] = False + self.assertFalse(geometry_plateau(rows, CONFIG["fitting"])) + + def test_any_primary_metric_or_tail_still_changing_prevents_stop(self): + original = self.trace() + for key, statistic in [(key, "mean") for key in PRIMARY] + [ + ("mpvpe_mm", "p95"), ("max_vertex_mm", "max")]: + rows = copy.deepcopy(original) + rows[-1]["geometry"][key][statistic] += .02 + self.assertFalse(geometry_plateau(rows, CONFIG["fitting"]), (key, statistic)) + + def test_partial_v4_snapshot_cannot_claim_four_completed_initializations(self): + names = CONFIG["fitting"]["initializations"] + complete = {"trace": [{"initialization": name} for name in (*names, "winning_extension")]} + self.assertTrue(multistart_complete(complete, CONFIG["fitting"])) + self.assertFalse(multistart_complete({"trace": complete["trace"][:-1]}, CONFIG["fitting"])) + self.assertFalse(multistart_complete({"trace": [{"initialization": "winning_extension"}]}, CONFIG["fitting"])) + + def test_cpu_joint_fit_uses_geometry_plateau_and_keeps_shared_beta(self): + layer = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=True).layers[0].double() + pose = torch.zeros(2, 48, dtype=torch.float64) + beta = torch.zeros(10, dtype=torch.float64) + wrist = torch.tensor([[0., 0., .5], [.01, 0., .5]], dtype=torch.float64) + with torch.no_grad(): + v, j = geometry(layer, pose, beta, wrist) + data = {"pose": pose, "beta": beta.expand(2, -1), "wrist": wrist, + "vertices": v, "joints": j, "joint_valid": torch.ones(2, 21, dtype=torch.bool), + "record_index": [0, 0], "frame_index": [0, 1]} + scaling = {"pose": torch.ones(48, dtype=torch.float64), "beta": torch.ones(10, dtype=torch.float64)} + baseline, _ = inspect_geometry(layer, data, pose, beta, wrist, "cpu") + with tempfile.TemporaryDirectory() as temporary: + result = joint_fit(layer, data, pose, beta, 1/21, 320, CONFIG["fitting"], "cpu", + Path(temporary), "synthetic", "zero_beta", scaling, baseline) + self.assertTrue(result["geometry_review"]["geometry_review_pass"]) + self.assertEqual(result["trace"][-1]["stop_reason"], "geometry_quality_pass_and_geometry_plateau") + self.assertEqual(result["trace"][-1]["budget_used"], 256) + self.assertEqual(tuple(result["beta"].shape), (10,)) + torch.testing.assert_close(result["wrist"], wrist) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_fit.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..8c0dbb8155e49c2c5188d98ca0816232a42cba0a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_fit.py @@ -0,0 +1,89 @@ +"""Synthetic tests for exact conditional updates, sharing and metadata identity.""" + +import unittest + +from runtime import torch, ManoCameraLayer, MANO_ROOT, geometry +from fit_cache import (optimal_wrist, conditional_beta_system, residual_objective, + placed_geometry, streamed_joint_evaluation) +from native_cache import record_id + + +class FitTests(unittest.TestCase): + def setUp(self): + torch.manual_seed(19) + self.dtype = torch.float64 + + def test_conditional_wrist_stationarity_with_partial_joint_masks(self): + v = torch.randn(3, 778, 3, dtype=self.dtype) / 10 + j = torch.randn(3, 21, 3, dtype=self.dtype) / 10 + data = {"vertices": v + .01, "joints": j - .02, + "joint_valid": torch.rand(3, 21) > .25, + "wrist": torch.randn(3, 3, dtype=self.dtype)} + rho = 3 / int(data["joint_valid"].sum()) + wrist = optimal_wrist(v, j, data, rho).detach().requires_grad_() + delta = wrist - data["wrist"] + loss = residual_objective(v + delta[:, None], j + delta[:, None], data, rho) + gradient, = torch.autograd.grad(loss, wrist) + self.assertLess(float(gradient.abs().max()), 1e-8) + + def test_shared_beta_exact_recovery_with_free_translation(self): + n = 4 + av = torch.randn(n, 778, 3, 10, dtype=self.dtype) * .001 + aj = torch.randn(n, 21, 3, 10, dtype=self.dtype) * .001 + v0, j0 = torch.randn(n, 778, 3, dtype=self.dtype), torch.randn(n, 21, 3, dtype=self.dtype) + beta = torch.randn(10, dtype=self.dtype) + shift = torch.randn(n, 1, 3, dtype=self.dtype) + data = {"vertices": v0 + av @ beta + shift, "joints": j0 + aj @ beta + shift, + "joint_valid": torch.rand(n, 21) > .2} + rho = n / int(data["joint_valid"].sum()) + a, b = conditional_beta_system(v0, j0, av, aj, data, rho) + result = torch.linalg.solve(a, b) + torch.testing.assert_close(result, beta, atol=1e-10, rtol=0) + + def test_streamed_beta_same_as_full_system(self): + n = 5 + av = torch.randn(n, 778, 3, 10, dtype=self.dtype) * .001 + aj = torch.randn(n, 21, 3, 10, dtype=self.dtype) * .001 + v0, j0 = torch.randn(n, 778, 3, dtype=self.dtype), torch.randn(n, 21, 3, dtype=self.dtype) + data = {"vertices": torch.randn_like(v0), "joints": torch.randn_like(j0), + "joint_valid": torch.rand(n, 21) > .2} + rho = n / int(data["joint_valid"].sum()) + a, b = conditional_beta_system(v0, j0, av, aj, data, rho) + pieces = [] + for first, last in ((0, 2), (2, 5)): + pieces.append(conditional_beta_system(v0[first:last], j0[first:last], av[first:last], aj[first:last], + {key: value[first:last] for key, value in data.items()}, rho)) + torch.testing.assert_close(sum(value[0] for value in pieces), a) + torch.testing.assert_close(sum(value[1] for value in pieces), b) + + def test_source_and_recording_identity_are_distinct(self): + self.assertNotEqual(record_id("H2O", "s01/a"), record_id("ARCTIC", "s01/a")) + self.assertNotEqual(record_id("H2O", "s01/a"), record_id("H2O", "s01/b")) + + def test_streamed_joint_gradient_equals_full_autograd(self): + layer = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=True).layers[0].double() + frames = 3 + pose = torch.randn(frames, 48, dtype=self.dtype) * .03 + beta = torch.randn(10, dtype=self.dtype) * .2 + wrist = torch.randn(frames, 3, dtype=self.dtype) * .01 + .5 + with torch.no_grad(): + v, j = geometry(layer, pose, beta, wrist) + data = {"pose": pose, "vertices": v + .001, "joints": j - .002, + "wrist": wrist, "joint_valid": torch.rand(frames, 21) > .2} + rho = frames / int(data["joint_valid"].sum()) + scalings = [{"pose": pose.new_full((48,), frames**.5), "beta": beta.new_ones(10)}, + {"pose": torch.linspace(.1, 4, 48, dtype=self.dtype), + "beta": torch.linspace(.2, 3, 10, dtype=self.dtype)}] + for scaling in scalings: + parameters = torch.cat(((pose / scaling["pose"][None]).reshape(-1), beta / scaling["beta"])).requires_grad_() + objective, gradient, _ = streamed_joint_evaluation(layer, data, parameters, rho, 2, "cpu", scaling=scaling) + v, j, _ = placed_geometry(layer, parameters[:-10].reshape(frames, 48) * scaling["pose"][None], + parameters[-10:] * scaling["beta"], data, rho) + loss = residual_objective(v, j, data, rho) + automatic, = torch.autograd.grad(loss, parameters) + self.assertAlmostEqual(objective, float(loss.detach()), places=10) + torch.testing.assert_close(gradient, automatic, atol=1e-8, rtol=1e-8) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_geometry_metrics.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_geometry_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7f64bcdd608adf672e3ad32b79db8b04f5d106 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_geometry_metrics.py @@ -0,0 +1,63 @@ +import unittest + +import numpy as np + +from geometry_metrics import geometry_metrics, geometry_gate, summarize + + +def aligned(predicted, target, *, estimate_scale): + # Geometry tests exercise the actual repo Procrustes implementation when available. + from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm + return aligned_mpjpe_mm(predicted, target, estimate_scale=estimate_scale) + + +class GeometryTests(unittest.TestCase): + def setUp(self): + rng = np.random.default_rng(7) + self.j = rng.normal(size=(3, 21, 3)) * .04 + (0, 0, .5) + self.v = rng.normal(size=(3, 778, 3)) * .04 + (0, 0, .5) + self.valid = np.ones((3, 21), bool) + + def measure(self, v, j, valid=None): + return geometry_metrics(v, j, self.v, self.j, self.valid if valid is None else valid, aligned) + + def test_identical_geometry(self): + result = self.measure(self.v, self.j) + for metric in ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", "pa_mpjpe_mm"): + np.testing.assert_allclose(result[metric], 0, atol=1e-10) + + def test_rigid_translation(self): + result = self.measure(self.v + (.003, 0, 0), self.j + (.003, 0, 0)) + np.testing.assert_allclose(result["absolute_mpjpe_mm"], 3, atol=1e-10) + np.testing.assert_allclose(result["mpvpe_mm"], 3, atol=1e-10) + np.testing.assert_allclose(result["root_relative_mpjpe_mm"], 0, atol=1e-10) + np.testing.assert_allclose(result["pa_mpjpe_mm"], 0, atol=1e-10) + + def test_pa_requires_all_gt_joints(self): + valid = self.valid.copy() + valid[0, 20] = False + result = self.measure(self.v, self.j, valid) + self.assertTrue(np.isnan(result["pa_mpjpe_mm"][0])) + self.assertEqual(summarize(result)["pa_mpjpe_mm"]["count"], 2) + self.assertEqual(summarize(result)["absolute_mpjpe_mm"]["count"], 3) + + def test_nonfinite_prediction_cannot_reduce_denominator(self): + j = self.j.copy() + j[0, 20] = np.nan + with self.assertRaises(ValueError): + self.measure(self.v, j) + + def test_gradient_not_quality_gate(self): + summary = summarize(self.measure(self.v, self.j)) + diagnostics = {"wrist_adjustment_mm": {"max": 0}, "local_pose_adjustment_rms_rad": {"max": 0}, + "scaled_pose_gradient": {"max": 100}} + settings = {"fit_mean_mpvpe_limit_mm": 5, "fit_p95_mpvpe_limit_mm": 8, + "fit_max_vertex_limit_mm": 30, "fit_max_wrist_adjustment_limit_mm": 20, + "fit_max_local_pose_rms_limit_rad": .5} + self.assertTrue(geometry_gate(summary, diagnostics, summary, settings)["geometry_review_pass"]) + bad = {**summary, "mpvpe_mm": {"mean": 6, "p95": 6, "max": 6, "count": 3}} + self.assertFalse(geometry_gate(bad, diagnostics, summary, settings)["geometry_review_pass"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_labels.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..76915863fe2e51ae773015e5169443ce04b1629e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_labels.py @@ -0,0 +1,47 @@ +"""Canonical training targets remain consistent without replacing 2D observations.""" + +import json +from pathlib import Path +import tempfile +import unittest + +from runtime import torch, np, save_npz, dump, sha +from targets import CanonicalLabels + + +class LabelTests(unittest.TestCase): + def test_complete_parameter_replacement_and_input_preservation(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + path = root / "labels.npz" + hand = np.array([[True, True], [True, False]]) + arrays = {"frame_ids": np.array([20, 21]), "pose": np.ones((2, 2, 48)) * .1, + "beta": np.ones((2, 2, 10)) * .3, "wrist": np.ones((2, 2, 3)) * .2, + "vertices": np.ones((2, 2, 778, 3)) * .2, "joints": np.ones((2, 2, 21, 3)) * .2, + "hand": hand, "joint_valid": np.broadcast_to(hand[..., None], (2, 2, 21)), + "joint2d_valid": np.broadcast_to(hand[..., None], (2, 2, 21))} + save_npz(path, **arrays) + dump(root / "label_inventory.json", {"entries": [{"source": "H2O", "recording": "subject1/a/cam4", + "path": str(path), "sha256": sha(path)}]}) + row = {"take": "subject1/a/cam4", "expected_frame_ids": [20, 21]} + labels = CanonicalLabels("H2O", [row], cache=root) + observed2d = torch.randn(2, 2, 21, 2) + K = torch.eye(3).repeat(2, 1, 1) + sample = {"frame_valid": torch.ones(2, dtype=torch.bool), "joint2d": observed2d.clone(), + "joint3d_camera": torch.ones(2, 2, 21, 3) * .2, + "joint2d_valid": torch.ones(2, 2, 21, dtype=torch.bool), "K": K.clone(), + "K_input_available": torch.tensor([True, False]), + "depth_input_available": torch.tensor([False, False])} + result = labels.apply(sample, row, None) + torch.testing.assert_close(result["mano_pose"], torch.ones(2, 2, 48) * .1) + torch.testing.assert_close(result["wrist_root_translation"], torch.ones(2, 2, 3) * .2) + torch.testing.assert_close(result["mano_shape"], torch.ones(2, 2, 10) * .3) + self.assertTrue(torch.equal(result["joint2d"], observed2d)) + self.assertTrue(torch.equal(result["K"], K)) + self.assertTrue(torch.equal(result["K_input_available"], torch.tensor([True, False]))) + self.assertTrue(torch.equal(result["local_pose_valid"], torch.from_numpy(hand))) + self.assertTrue(bool((result["mano_target_contract_version"] == 3).all())) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_native_indices.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_native_indices.py new file mode 100644 index 0000000000000000000000000000000000000000..02624df498723f80a3ea7b0165e2a618615b5000 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/test_native_indices.py @@ -0,0 +1,32 @@ +"""Image frame numbers need not equal official annotation indices plus one.""" + +import unittest + +from runtime import np +from native_cache import arctic_annotation_indices + + +class AnnotationIndexTests(unittest.TestCase): + def row(self, frames, indices): + return {"expected_frame_ids": frames, "frame_ids_1based": frames, + "array_indices_0based": indices} + + def test_subject_offset_and_overlapping_tiles(self): + rows = [self.row([122, 123, 124], [120, 121, 122]), + self.row([123, 124, 125], [121, 122, 123])] + np.testing.assert_array_equal(arctic_annotation_indices(rows, np.array([122, 124, 125])), + [120, 122, 123]) + + def test_conflicting_overlap_is_rejected(self): + with self.assertRaisesRegex(RuntimeError, "inconsistent"): + arctic_annotation_indices([self.row([122], [120]), self.row([122], [121])], [122]) + + def test_missing_or_negative_index_is_rejected(self): + for rows, frames in (([self.row([122], [120])], [123]), + ([self.row([122], [-1])], [122])): + with self.assertRaises(RuntimeError): + arctic_annotation_indices(rows, frames) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/train_expert.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/train_expert.py new file mode 100644 index 0000000000000000000000000000000000000000..d295d42d7ce54da24b6ac8fc6feac2871aff4bec --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_canonical_gt_train/train_expert.py @@ -0,0 +1,7 @@ +"""Reuse original A7's reference training loop with a new canonical GT contract.""" + +import runpy +from common import REFERENCE_ROOT + +if __name__ == "__main__": + runpy.run_path(str(REFERENCE_ROOT / "train_expert.py"), run_name="__main__") diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/README.md b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/README.md new file mode 100644 index 0000000000000000000000000000000000000000..148c125f727cb2767e58e324bed83db5c3636d9a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/README.md @@ -0,0 +1,122 @@ +# A7 MoT-Inspired Residual Query Experiment + +Registered 2026-09-29. G2 output root: `/home/wuyifan/a7_mot_residual_20260929`. +This is a new experiment, not an automatic A7 release or an edit to the S4 model. + +## Architecture + +The original complete S4 RGB parent is immutable, including DINO, projection, +spatial/temporal decoder, heads and buffers. SHA256: +`85a9e02274f94b69e2a634518f6f46244dbedb518b135f07be4b2c746be9bb15`. + +Each independently trained K/D repair branch reads the frozen parent's full-frame +RGB patch memory and final hand queries. The parent RGB encoder executes once per +forward; a scoped read-only hook captures its output and is removed even on failure. +K rays are separate memory, not added to visual patches. Each memory has dedicated +query normalization, memory normalization, QKV/O projections. Each input-mode branch +also has its own FFNs, temporal/bimanual layers, side embeddings and MANO readout. +The K and D branches do not call or update each other. + +Read modules are copied from S4 to retain pretrained query processing. Repair heads +are zero-initialized. Rotation corrections use an SO(3) increment; XY translation is +additive in meters, Z uses a positive multiplicative/log-depth correction. Shape is +sequence-shared. Direct 2D uses an identity-preserving logit residual. Geometry is +regenerated through the unchanged MANO layer. Zero heads do not zero-initialize the +conditioning encoders, so conditioner gradients begin after the readout learns. + +This is an **asymmetric MoT-inspired cross-attention design**, not a verbatim +implementation of the original global self-attention MoT paper. It isolates +input-mode hand-query states as well as modality-specific memory projections. +The frozen RGB path cannot receive geometric updates or multimodal gradients. +No learned quality gate or restrictive small XYZ correction cap is added in M0. + +## Recipe + +- Reuse the reference trainer, native GT adapters, fixed index and source masks + read-only. The HOT3D viewport/in-frame supervision fix is retained. +- T=8, 512x896, BF16, TF32 off. Four idle G2 GPUs from IDs 1-5; never claim GPU 0. +- One clip/GPU/microstep, accumulation 3, global batch 12. +- K: original filtered H2O/ARCTIC/HOT3D exposure 35/25/40, RGB+K only. +- D: original filtered H2O measured metric depth, RGB+Depth+K only. +- Each branch: 100,008 clips / 8,334 updates. Fixed milestones 2,084/4,167/8,334. +- Same reference seed/sample order, photometric augmentation and H2O depth corruption. +- Fresh AdamW, weight decay .05, branch LR 1e-5 -> 1e-6, warmup 1,008 clips. +- One continuous cosine; no restart at evaluation boundaries. DINO remains fully + frozen, including its last two blocks and final norm. No backbone LR group exists. +- Original S4 losses and grad clip 100. No new no-harm, ray or silhouette loss. +- No ARCTIC MANO convention rewrite or supervision-denominator change is bundled. +- Original RGB/input availability is distinct from GT K used by supervision. +- Full checkpoints include parent, branch, optimizer, per-rank RNG, sampler cursor, + source/GT exposure, frozen fingerprint and code hashes. Keep a 200 GiB disk reserve. + +The frozen DINO and residual architecture differ from the prior independent D expert, +which trained the last two DINO blocks. Its endpoint is a practical performance control, +not a single-variable architecture comparison. Do not interpret gains/losses as proving +that MoT alone caused them. An unfrozen **branch-private** backbone is a later experiment. + +## Verification And Evaluation + +Before formal training: CPU routing/gradient/camera tests, real BF16 zero-init tests on +H2O/ARCTIC/HOT3D, post-update exact RGB fallback and immutable-parent checks, four-rank +K/D smoke, and continuous versus resumed DDP equivalence. All smoke updates are discarded. +Input/GT checksums, optimizer restore, RNG, sampler cursor and validity ledgers are exact. +GPU continuation permits registered numerical tolerances, not a bitwise-equivalence claim. +The stopped v1 smoke established exact RNG, input checksums and cursor but detected +BF16 optimizer moment differences in four zero-init readout heads. Model max difference +was 5.96e-8; worst translation-head AdamW `exp_avg` difference was 0.003125, +`exp_avg_sq` 0.001147. In v2, only the four readout heads have moment-specific +limits (0.005 and 0.002 respectively), with recorded per-parameter maxima; +every other optimizer tensor retains the reference 2e-5/1e-4 threshold. +Parent tensors, sample order and RNG stay exact. This does not claim bitwise replay. + +Development panels are evaluated at all three fixed milestones; confirmation is reserved +for the final checkpoint. Compare all four registered metrics against same-input S4, +S4 RGB and, at 100K, the previous independent expert. Pure RGB remains original S4. +Report paired recording-bootstrap intervals and unchanged GT-defined denominators. +The fourth metric projects MANO joints; it is not direct 2D-head error. +These are previously inspected panels, not untouched official test evidence. + +No visualization is produced by this training queue. Future displays must use the +trained/calibrated S4 RGB visibility provider with its original frozen RGB features, +not the unused legacy presence head or refined multimodal hand tokens. Geometry metrics +must not filter GT-positive hands using predicted visibility. + +The queue never preempts other tasks, stops on preflight failure and does not extend +the budget or promote a checkpoint based on validation. Final files: `RESULTS.md`, +`results.json`, paired per-row JSON, `candidate_bundle.json`. + +## EgoForce: What To Borrow, What To Keep Separate + +Sources: +- https://arxiv.org/html/2605.12498v1 (sections 3.3, 7.2, 7.3) +- https://github.com/dfki-av/EgoForce +- https://github.com/facebookresearch/Mixture-of-Transformers + +EgoForce uses calibration-derived unit bearing rays and a confidence-weighted +point-to-ray translation solve, plus crop-intrinsics conditioning and forearm context. +These are useful geometry ideas, but are not evidence of a gain in Foundation Hand. + +**M0 does not enable fisheye lifting.** Existing HOT3D decodes official LINEAR +undistorted images, with resized rectilinear K. ARCTIC ego view 0 is also undistorted +before model input. Applying the original fisheye distortion again would be incorrect. +We retain the exact current rectified-image/K/evaluator contract. + +`camera_geometry.py` implements separately tested unit-bearing and point-to-ray utilities; +neither is called by the M0 model or loss. Distorted native images explicitly require +native calibrated unprojection rays; K alone is rejected, not silently treated as pinhole. +The solver rejects insufficient, nonfinite, parallel/ill-conditioned and negative-range +correspondences, returns a validity bit and falls back to the learned translation. + +A subsequent M1 ablation can compare: +1. M0 unchanged rectified rays. +2. Normalized bearing/context tokens on the **same** rectified RGB/K inputs. +3. Learned translation versus predicted-2D/MANO point-to-ray translation, with conditioning + diagnostics and a learned blend; no GT 2D may be used as inference correspondences. + +Native fisheye requires a separate data/evaluation contract: native RGB, projection model, +distortion parameters, inverse projection, image resize/crop mapping, unit bearing rays, +and depth semantics (optical-axis Z versus ray range). Native 2D reprojection must use the +native model too. Audit calibration round trips and peripheral/wide-FOV subsets first. +Keep the current four-metric protocol as a baseline; never mix native fisheye images with +rectified K or compare differently projected pixel errors as if they were the same metric. +Forearm modeling is not included: it introduces new representations and supervision. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/RESULTS.md b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/RESULTS.md new file mode 100644 index 0000000000000000000000000000000000000000..975fa8c321f444fb875157843f82d785ddb57934 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/RESULTS.md @@ -0,0 +1,37 @@ +# A7 MoT-Inspired Residual Query Experiment + +Fixed 100,008 clips per independent K/D repair branch. Original S4 RGB remains frozen. +Previously inspected development/confirmation panels, not official test evidence. +No fisheye lifting, new loss, source convention fix, or automatic model promotion. + +| Source | Input | Model | Abs MPJPE mm | RR MPJPE mm | MPVPE mm | MANO 2D px | +|---|---|---|---:|---:|---:|---:| +| ARCTIC | rgb | S4 RGB | 32.069 | 20.865 | 31.768 | 19.758 | +| ARCTIC | rgb | S4 same input | 32.069 | 20.865 | 31.768 | 19.758 | +| ARCTIC | rgb | MoT repair | 32.069 | 20.865 | 31.768 | 19.758 | +| ARCTIC | rgb_k | S4 RGB | 32.069 | 20.865 | 31.768 | 19.758 | +| ARCTIC | rgb_k | S4 same input | 31.864 | 20.997 | 31.545 | 19.308 | +| ARCTIC | rgb_k | Prior independent expert | 33.713 | 20.722 | 33.375 | 19.334 | +| ARCTIC | rgb_k | MoT repair | 33.809 | 20.807 | 33.459 | 19.652 | +| H2O | rgb | S4 RGB | 21.562 | 13.238 | 21.812 | 11.327 | +| H2O | rgb | S4 same input | 21.562 | 13.238 | 21.812 | 11.327 | +| H2O | rgb | MoT repair | 21.562 | 13.238 | 21.812 | 11.327 | +| H2O | rgb_depth_k | S4 RGB | 21.562 | 13.238 | 21.812 | 11.327 | +| H2O | rgb_depth_k | S4 same input | 20.444 | 13.244 | 20.667 | 10.999 | +| H2O | rgb_depth_k | Prior independent expert | 19.655 | 13.186 | 19.962 | 10.784 | +| H2O | rgb_depth_k | MoT repair | 20.917 | 13.171 | 21.153 | 11.029 | +| H2O | rgb_k | S4 RGB | 21.562 | 13.238 | 21.812 | 11.327 | +| H2O | rgb_k | S4 same input | 21.410 | 13.264 | 21.624 | 11.107 | +| H2O | rgb_k | Prior independent expert | 20.829 | 13.096 | 20.999 | 10.819 | +| H2O | rgb_k | MoT repair | 21.063 | 13.219 | 21.162 | 10.913 | +| HOT3D | rgb | S4 RGB | 51.661 | 23.684 | 51.343 | 13.972 | +| HOT3D | rgb | S4 same input | 51.661 | 23.684 | 51.343 | 13.972 | +| HOT3D | rgb | MoT repair | 51.661 | 23.684 | 51.343 | 13.972 | +| HOT3D | rgb_k | S4 RGB | 51.661 | 23.684 | 51.343 | 13.972 | +| HOT3D | rgb_k | S4 same input | 51.698 | 23.645 | 51.402 | 13.501 | +| HOT3D | rgb_k | Prior independent expert | 47.683 | 23.655 | 47.333 | 13.700 | +| HOT3D | rgb_k | MoT repair | 48.139 | 23.765 | 47.830 | 13.966 | + +Paired recording-bootstrap intervals and GT-defined denominators are in evaluations/. +The prior Depth expert tuned its last two DINO blocks; this experiment freezes them. +Thus that comparison is a practical baseline, not a single-variable architecture ablation. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/camera_geometry.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/camera_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..9bb7c03b30a27ce69a49d99fa53e3f0c4b6ba830 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/camera_geometry.py @@ -0,0 +1,49 @@ +"""EgoForce-inspired ray-space utilities; disabled in the M0 training recipe.""" + +import torch +import torch.nn.functional as F + + +def unit_bearings(pixels, K=None, *, image_camera_model="pinhole_rectified", native_bearings=None): + if native_bearings is not None: + if native_bearings.shape != (*pixels.shape[:-1], 3): + raise ValueError("native unprojection rays must align with image pixels") + rays = native_bearings + else: + if image_camera_model not in ("pinhole", "pinhole_rectified"): + raise ValueError("native distorted images require their calibrated unprojection, not K alone") + if K is None or K.shape[-2:] != (3, 3): + raise ValueError("pinhole pixels require matching K") + homogeneous = torch.cat((pixels, torch.ones_like(pixels[..., :1])), dim=-1) + rays = torch.linalg.solve(K, homogeneous.transpose(-1, -2)).transpose(-1, -2) + if not bool(torch.isfinite(rays).all()) or bool((rays.norm(dim=-1) < 1e-8).any()): + raise ValueError("invalid calibrated bearing rays") + return F.normalize(rays, dim=-1) + + +def point_to_ray_translation(joints_root_relative, rays, weights, fallback, *, condition_limit=1e6): + if rays.shape != joints_root_relative.shape or weights.shape != rays.shape[:-1]: + raise ValueError("joint, ray and weight dimensions differ") + if fallback.shape != rays.shape[:-2] + (3,): + raise ValueError("fallback translation has incompatible leading dimensions") + dtype = rays.dtype + with torch.autocast(rays.device.type, enabled=False): + finite = (torch.isfinite(rays).all(-1) & torch.isfinite(joints_root_relative).all(-1) + & torch.isfinite(weights) & (weights > 0) & (torch.nan_to_num(rays).norm(dim=-1) > 1e-8)) + d = F.normalize(torch.where(finite[..., None], rays.float(), torch.zeros_like(rays).float()), dim=-1) + J = torch.where(finite[..., None], joints_root_relative.float(), torch.zeros_like(rays).float()) + w = torch.where(finite, weights.float(), torch.zeros_like(weights).float()) + eye = torch.eye(3, device=d.device, dtype=d.dtype) + projection = eye - d[..., :, None] * d[..., None, :] + A = (w[..., None, None] * projection).sum(-3) + b = -(w[..., None] * (projection @ J[..., None]).squeeze(-1)).sum(-2) + eigenvalues = torch.linalg.eigvalsh(A) + condition = eigenvalues[..., -1] / eigenvalues[..., 0].clamp_min(1e-12) + good = (finite.sum(-1) >= 3) & (eigenvalues[..., 0] > 1e-8) & (condition < condition_limit) + # A tiny ridge makes the backward solve finite even on rejected parallel-ray inputs. + ridge = 1e-7 * A.diagonal(dim1=-2, dim2=-1).sum(-1).clamp_min(1.0) + solution = torch.linalg.solve(A + ridge[..., None, None] * eye, b) + ranges = ((solution[..., None, :] + J) * d).sum(-1) + good = good & torch.isfinite(solution).all(-1) & ((ranges > 0) | ~finite).all(-1) + result = torch.where(good[..., None], solution.to(dtype), fallback.to(dtype)) + return {"translation": result, "valid": good, "condition": condition} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/common.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/common.py new file mode 100644 index 0000000000000000000000000000000000000000..aaf4aa56ce3c3089c908a534590be8c9fcd41532 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/common.py @@ -0,0 +1,56 @@ +"""Reuse hash-bound S4 data/loss contracts without editing the reference run.""" + +from __future__ import annotations + +import importlib.util +import json +from pathlib import Path + +import torch + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +BASE_ROOT = Path(CONFIG["base_root"]) +BASE_CODE = BASE_ROOT / "code" +REFERENCE_ROOT = Path(CONFIG["reference_root"]) +spec = importlib.util.spec_from_file_location("s4_expert_reference", REFERENCE_ROOT / "common.py") +reference = importlib.util.module_from_spec(spec) +spec.loader.exec_module(reference) +base = reference.base +PARENT = reference.PARENT +ExpertCoverage = reference.ExpertCoverage +ExpertDataset = reference.ExpertDataset +mode_and_supervision = reference.mode_and_supervision +exact_equal = reference.exact_equal +numeric_equal = reference.numeric_equal +dump = reference.dump +frozen_fingerprint = reference.frozen_fingerprint + +from model import MoTResidualModel + + +def load_parent(): + if (str(BASE_ROOT) != str(reference.BASE_ROOT) + or CONFIG["parent_sha256"] != reference.CONFIG["parent_sha256"]): + raise RuntimeError("reference RGB identity differs") + return reference.load_parent() + + +def model_for(expert): + parent = base.model_for("S4") + parent.load_state_dict(load_parent()["model"], strict=True) + parent.requires_grad_(False).eval() + if expert == "RGB": + return parent + with torch.random.fork_rng(devices=[]): + torch.manual_seed(CONFIG["seed"]) + return MoTResidualModel(parent, expert) + + +def code_hashes(): + records = reference.code_hashes() + records.update({f"mot/{path.name}": base.sha(path) for path in sorted(ROOT.glob("*.py"))}) + records["mot/config.json"] = base.sha(ROOT / "config.json") + records["reference/train_expert.py"] = base.sha(REFERENCE_ROOT / "train_expert.py") + records["reference/controller.py"] = base.sha(REFERENCE_ROOT / "controller.py") + return records diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0f5c10a083b25c86c8c9870d4d2955b708d4da77 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/config.json @@ -0,0 +1,36 @@ +{ + "experiment": "a7_mot_residual_20260929", + "attempt": "v2", + "reference_root": "/home/wuyifan/s4_modality_experts_20260928", + "base_root": "/home/wuyifan/foundation_hand_clean_gt_dino_20260925", + "parent": "checkpoints/formal_v3_s4/s4_update_0066667.pt", + "parent_sha256": "85a9e02274f94b69e2a634518f6f46244dbedb518b135f07be4b2c746be9bb15", + "seed": 20260928, + "global_batch": 12, + "world_size": 4, + "updates": 8334, + "milestones": [2084, 4167, 8334], + "warmup_clips": 1008, + "learning_rate": 0.00001, + "min_learning_rate": 0.000001, + "depth_backbone_learning_rate": null, + "grad_clip": 100.0, + "weight_decay": 0.05, + "workers_per_rank": 2, + "permitted_gpus": [1, 2, 3, 4, 5], + "order": ["K", "D"], + "source_quota_K": {"H2O": 7, "ARCTIC": 5, "HOT3D": 8}, + "source_D": "H2O", + "resume_model_atol": 0.000001, + "resume_optimizer_atol": 0.00002, + "resume_optimizer_rtol": 0.0001, + "resume_head_momentum_atol": 0.005, + "resume_head_second_moment_atol": 0.002, + "evaluation_role": "previously_inspected_frozen_panels", + "final_selection": "fixed_8334_update_endpoint_not_best_validation", + "official_test_used": false, + "camera_contract": "unchanged_native_adapters_rectilinear_K", + "fisheye_lifting_enabled": false, + "new_loss_enabled": false, + "dino_trainable_blocks": 0 +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..fa2fcb0cd7d89847b11e95563e2a709149fcad5f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/controller.py @@ -0,0 +1,123 @@ +"""Reuse the verified queue, adding MoT preflight and experiment-specific reporting.""" + +import importlib.util +import json + +import torch + +from common import CONFIG, PARENT, REFERENCE_ROOT, ROOT, base, dump + +spec = importlib.util.spec_from_file_location("reference_expert_controller", REFERENCE_ROOT / "controller.py") +controller = importlib.util.module_from_spec(spec) +spec.loader.exec_module(controller) +original_reserve = controller.reserve +original_run = controller.run +original_numeric_equal = controller.numeric_equal + + +def optimizer_numerical_equal(left, right, *, atol, rtol): + if left.keys() != right.keys() or left["param_groups"] != right["param_groups"]: + return False + names = json.loads((ROOT / "preflight_v2/D/provenance_from_0000000.json").read_text())["trainable_names"] + sensitive = {index for index, name in enumerate(names) + if name.startswith(("branch.rotation_head.", "branch.translation_head.", + "branch.shape_head.", "branch.joint2d_head."))} + if left["state"].keys() != right["state"].keys(): + return False + diagnostics = {"status": "pass", "head_momentum_limit": CONFIG["resume_head_momentum_atol"], + "head_second_moment_limit": CONFIG["resume_head_second_moment_atol"], + "other_atol": atol, "other_rtol": rtol, "largest": []} + for index, values in left["state"].items(): + comparison = right["state"][index] + if values.keys() != comparison.keys(): + return False + for name, value in values.items(): + expected = comparison[name] + if not torch.is_tensor(value): + if value != expected: + return False + continue + if index in sensitive and name in ("exp_avg", "exp_avg_sq"): + tolerance = CONFIG["resume_head_momentum_atol"] if name == "exp_avg" else CONFIG["resume_head_second_moment_atol"] + else: + tolerance = atol + difference = (value.float() - expected.float()).abs() + maximum = float(difference.max()) + diagnostics["largest"].append({"parameter": names[index], "field": name, + "max_abs": maximum, "atol": tolerance}) + if not torch.allclose(value.float(), expected.float(), atol=tolerance, rtol=rtol): + diagnostics["status"] = "failed" + dump(ROOT / "preflight_v2/optimizer_numerical_audit.json", diagnostics) + return False + diagnostics["largest"].sort(key=lambda item: item["max_abs"], reverse=True) + diagnostics["largest"] = diagnostics["largest"][:20] + dump(ROOT / "preflight_v2/optimizer_numerical_audit.json", diagnostics) + return True + + +def numeric_equal(left, right, *, atol, rtol=0.0): + if (isinstance(left, dict) and isinstance(right, dict) + and "param_groups" in left and "state" in left): + return optimizer_numerical_equal(left, right, atol=atol, rtol=rtol) + return original_numeric_equal(left, right, atol=atol, rtol=rtol) + + +def reserve(): + gpus = original_reserve() + if len(gpus) != CONFIG["world_size"]: + for gpu in gpus: + controller.release_physical_gpu_claim(gpu) + return [] + return gpus + + +def run(command, label, gpus): + original_run(command, label, gpus) + if label.startswith("cpu_contracts_"): + resources = json.loads((ROOT / "resources.json").read_text()) + original_run([str(ROOT / "gpu_contract.py")], f"gpu_contract_{CONFIG['attempt']}", resources["gpus"][:1]) + + +def write_table(): + records = [] + for path in sorted((ROOT / "evaluations").glob("eval_*_confirmation_*.json")): + if not path.name.endswith(".rows.json"): + records.append(json.loads(path.read_text())) + if len(records) != 7 or any(row["smoke"] for row in records): + raise RuntimeError("MoT final report requires seven complete source/input panels") + lines = ["# A7 MoT-Inspired Residual Query Experiment", "", + "Fixed 100,008 clips per independent K/D repair branch. Original S4 RGB remains frozen.", + "Previously inspected development/confirmation panels, not official test evidence.", + "No fisheye lifting, new loss, source convention fix, or automatic model promotion.", "", + "| Source | Input | Model | Abs MPJPE mm | RR MPJPE mm | MPVPE mm | MANO 2D px |", + "|---|---|---|---:|---:|---:|---:|"] + labels = (("rgb_parent", "S4 RGB"), ("parent", "S4 same input"), + ("prior_expert", "Prior independent expert"), ("routed", "MoT repair")) + for record in sorted(records, key=lambda item: (item["source"], item["input_mode"])): + for key, label in labels: + if key in record: + values = " | ".join(f"{value['mean']:.3f}" for value in record[key].values()) + lines.append(f"| {record['source']} | {record['input_mode']} | {label} | {values} |") + lines += ["", "Paired recording-bootstrap intervals and GT-defined denominators are in evaluations/.", + "The prior Depth expert tuned its last two DINO blocks; this experiment freezes them.", + "Thus that comparison is a practical baseline, not a single-variable architecture ablation."] + (ROOT / "RESULTS.md").write_text("\n".join(lines) + "\n") + dump(ROOT / "results.json", records) + dump(ROOT / "candidate_bundle.json", { + "status": "candidate_not_automatically_promoted", "architecture": "asymmetric_MoT_inspired_query_repair", + "rgb": str(PARENT), "rgb_sha256": CONFIG["parent_sha256"], + "rgb_k": str(ROOT / "runs/K/update_0008334.pt"), + "rgb_depth_k": str(ROOT / "runs/D/update_0008334.pt"), + "routing": "availability_only_complete_clip_else_K_or_RGB", + "fisheye_lifting_enabled": False, + "visualization_presence_policy": "use calibrated S4_RGB presence provider; never the frozen legacy head", + }) + + +controller.reserve = reserve +controller.run = run +controller.numeric_equal = numeric_equal +controller.write_table = write_table + +if __name__ == "__main__": + controller.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/diagnose_resume.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/diagnose_resume.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ce7101f206e411291a8e79d2ff4091fdea719d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/diagnose_resume.py @@ -0,0 +1,51 @@ +"""Read-only checkpoint comparison for a stopped preflight attempt.""" + +import argparse +import json +from pathlib import Path + +import torch + + +def summary(a, b): + records = [] + for key in a: + left, right = a[key], b[key] + if not torch.is_tensor(left): + if left != right: + records.append({"name": str(key), "non_tensor_mismatch": True}) + continue + diff = (left.float() - right.float()).abs() + bad = ~torch.isclose(left.float(), right.float(), atol=2e-5, rtol=1e-4) + records.append({"name": str(key), "max_abs": float(diff.max()), + "bad_elements": int(bad.sum()), "numel": left.numel(), + "mean_abs": float(diff.mean()), + "max_left_magnitude": float(left.float().abs().max())}) + return sorted(records, key=lambda row: row.get("max_abs", float("inf")), reverse=True) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("left", type=Path) + parser.add_argument("right", type=Path) + args = parser.parse_args() + left = torch.load(args.left, map_location="cpu", weights_only=False) + right = torch.load(args.right, map_location="cpu", weights_only=False) + model = summary(left["model"], right["model"]) + optimizer = [] + for key, values in left["optimizer"]["state"].items(): + for record in summary(values, right["optimizer"]["state"][key]): + record["name"] = f"{key}.{record['name']}" + optimizer.append(record) + optimizer.sort(key=lambda row: row.get("max_abs", float("inf")), reverse=True) + report = {"model_max": model[:15], "optimizer_max": optimizer[:20], + "optimizer_bad_tensors": sum(item.get("bad_elements", 0) > 0 for item in optimizer), + "optimizer_bad_elements": sum(item.get("bad_elements", 0) for item in optimizer), + "first_trainable_names": [name for name in left["model"] if name.startswith("branch.")][:20], + "rng_exact": str(left["rank_rng_states"]) == str(right["rank_rng_states"]), + "input_checksums_equal": left["input_checksums"] == right["input_checksums"]} + print(json.dumps(report, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/evaluate.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..8deff5c820393645cff378a2a528a5cafa51f69d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/evaluate.py @@ -0,0 +1,160 @@ +"""Registered four-metric comparisons against RGB, same-input S4, and prior experts.""" + +from collections import defaultdict +import argparse +import json +import math +from pathlib import Path + +import numpy as np +import torch + +from common import (BASE_ROOT, CONFIG, REFERENCE_ROOT, ROOT, base, code_hashes, + dump, model_for, reference) +from model import GEOMETRY_KEYS, rgb_inputs +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from scripts.evaluate_phase7_external import aggregate, make_row + + +def paired(left, right): + if len(left) != len(right): + raise RuntimeError("paired evaluation row counts differ") + result = {} + for metric in FOUR_METRICS: + recordings = defaultdict(list) + deltas = [] + for a, b in zip(left, right): + if math.isfinite(a[metric]) != math.isfinite(b[metric]): + raise RuntimeError(f"prediction changed the GT-defined denominator: {metric}") + if math.isfinite(a[metric]): + change = b[metric] - a[metric] + recordings[a["physical_recording_id"]].append(change) + deltas.append(change) + if not deltas: + raise RuntimeError(f"empty evaluation denominator: {metric}") + sums = np.array([sum(values) for values in recordings.values()]) + counts = np.array([len(values) for values in recordings.values()]) + rng = np.random.default_rng(CONFIG["seed"]) + selected = rng.integers(0, len(sums), size=(2000, len(sums))) + bootstrap = sums[selected].sum(1) / counts[selected].sum(1) + result[metric] = {"expert_minus_parent": float(np.mean(deltas)), + "recording_bootstrap_95ci": np.quantile(bootstrap, [.025, .975]).tolist(), + "count": len(deltas), "recordings": len(recordings)} + return result + + +def finite_json(value): + if isinstance(value, dict): + return {key: finite_json(item) for key, item in value.items()} + if isinstance(value, list): + return [finite_json(item) for item in value] + return None if isinstance(value, float) and not math.isfinite(value) else value + + +def run(args): + if args.output.exists(): + raise FileExistsError(args.output) + if args.source != "H2O" and args.expert == "D": + raise ValueError("only H2O supplies measured metric depth") + if args.limit is not None and not args.smoke: + raise ValueError("subset evaluation requires the smoke label") + panel_root = BASE_ROOT / "eval/frozen_panels_sync_v2" + manifest = panel_root / f"{args.source.lower()}_{args.role}_t8.jsonl" + panel_sha = json.loads((panel_root / "panels.json").read_text())["sources"][args.source][args.role]["manifest_sha256"] + if base.sha(manifest) != panel_sha: + raise RuntimeError("frozen native evaluation panel changed") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device("cuda") + parent = model_for("RGB").to(device).eval() + candidate = parent + prior = None + update = 0 + checkpoint_sha = CONFIG["parent_sha256"] + if args.expert != "RGB": + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if (state["expert"] != args.expert or state["smoke"] != args.smoke + or not state["complete_backbone"] or state["code_sha256"] != code_hashes() + or state["parent_sha256"] != CONFIG["parent_sha256"]): + raise RuntimeError("MoT checkpoint identity/implementation mismatch") + if args.role == "confirmation" and not args.smoke and state["update"] != CONFIG["updates"]: + raise RuntimeError("confirmation requires the fixed final endpoint") + candidate = model_for(args.expert) + candidate.load_state_dict(state["model"], strict=True) + candidate.to(device).eval() + update, checkpoint_sha = state["update"], base.sha(args.checkpoint) + del state + if update == CONFIG["updates"] and not args.smoke: + prior_path = REFERENCE_ROOT / "runs" / args.expert / f"update_{update:07d}.pt" + prior_state = torch.load(prior_path, map_location="cpu", weights_only=False) + if (prior_state["expert"] != args.expert or prior_state["update"] != update + or prior_state["smoke"] or not prior_state["complete_backbone"] + or prior_state["parent_sha256"] != CONFIG["parent_sha256"] + or prior_state["code_sha256"] != reference.code_hashes()): + raise RuntimeError("prior expert control differs from the registered reference") + prior = reference.model_for(args.expert) + prior.load_state_dict(prior_state["model"], strict=True) + prior.to(device).eval() + del prior_state + mode = {"RGB": "rgb", "K": "rgb_k", "D": "rgb_depth_k"}[args.expert] + dataset = dataset_for(args.source, manifest) + limit = min(args.limit, len(dataset)) if args.limit is not None else len(dataset) + rows = {"parent": [], "rgb_parent": [], "routed": []} + if prior is not None: + rows["prior_expert"] = [] + with torch.inference_mode(): + for index in range(limit): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, mode) + batch = base.move_to_device(batch, device) + base.attach_gt_vertices(batch, parent) + with torch.autocast("cuda", dtype=torch.bfloat16): + original = parent(batch) + pure = parent(rgb_inputs(batch)) + prediction = candidate(batch) + outputs = {"parent": original, "rgb_parent": pure, "routed": prediction} + if prior is not None: + outputs["prior_expert"] = prior(batch) + if args.expert == "RGB": + for key in GEOMETRY_KEYS: + if not torch.equal(original[key], prediction[key]) or not torch.equal(pure[key], prediction[key]): + raise RuntimeError(f"RGB routing changed original S4: {key}") + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + for label, output in outputs.items(): + rows[label].append(make_row(output, batch, 0, frame, side)) + summaries = {key: aggregate(value) for key, value in rows.items()} + report = {"source": args.source, "expert": args.expert, "input_mode": mode, + "role": args.role, "panel_status": CONFIG["evaluation_role"], "panel_sha256": panel_sha, + "clips": limit, "smoke": args.smoke, "expert_update": update, + "expert_checkpoint_sha256": checkpoint_sha, "parent_sha256": CONFIG["parent_sha256"], + "code_sha256": code_hashes(), "camera_model": CONFIG["camera_contract"], + "presence_filter_for_metrics": False, "fisheye_lifting_enabled": False, + "paired": paired(rows["parent"], rows["routed"]), + "paired_vs_rgb": paired(rows["rgb_parent"], rows["routed"]), + "supervision_coverage": summaries["routed"]["supervision_coverage"]} + if prior is not None: + report["paired_vs_prior_expert"] = paired(rows["prior_expert"], rows["routed"]) + report["prior_expert_checkpoint_sha256"] = base.sha(prior_path) + for key, summary in summaries.items(): + report[key] = {metric: summary[metric] for metric in FOUR_METRICS} + dump(args.output, report) + raw = [{"row": index, **{key: values[index] for key, values in rows.items()}} + for index in range(len(rows["routed"]))] + dump(args.output.with_suffix(".rows.json"), finite_json(raw)) + print(json.dumps({"source": args.source, "input_mode": mode, "update": update, + "routed": {key: report["routed"][key]["mean"] for key in FOUR_METRICS}}), flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--expert", choices=("RGB", "K", "D"), required=True) + parser.add_argument("--checkpoint", type=Path) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--role", choices=("development", "confirmation"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--limit", type=int) + run(parser.parse_args()) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/gpu_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/gpu_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..7e791cd788a08b18fbf82f0c9e3d7671e98797a5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/gpu_contract.py @@ -0,0 +1,89 @@ +"""Real S4/H2O/ARCTIC/HOT3D checks before any formal optimizer update.""" + +import json + +import torch + +from common import BASE_ROOT, ROOT, base, dump, frozen_fingerprint, model_for +from model import GEOMETRY_KEYS, rgb_inputs +from clean_eval import apply_mode, dataset_for + + +def main(): + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device("cuda") + records = [] + for expert in ("K", "D"): + model = model_for(expert).to(device).train() + frozen = frozen_fingerprint(model) + optimizer = torch.optim.AdamW(model.branch.parameters(), lr=1e-5) + smoke_batch = None + for source in (base.SOURCES if expert == "K" else ("H2O",)): + manifest = BASE_ROOT / "eval/frozen_panels_sync_v2" / f"{source.lower()}_development_t8.jsonl" + dataset = dataset_for(source, manifest) + cpu = base.collate_h2o_clips([dataset[0]]) + apply_mode(cpu, "rgb_k" if expert == "K" else "rgb_depth_k") + batch = base.move_to_device(cpu, device) + base.attach_gt_vertices(batch, model) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + original = model.parent(rgb_inputs(batch)) + prediction = model(batch) + # Each source gets a fresh zero-initialized readout until the gradient smoke below. + differences = {key: float((prediction[key].float() - original[key].float()).abs().max()) + for key in GEOMETRY_KEYS} + if any(value != 0 for value in differences.values()): + raise RuntimeError(f"zero-init changed parent geometry: {expert}:{source}:{differences}") + for key in base.MASK_FIELDS: + if key in cpu and not torch.equal(batch[key].cpu(), cpu[key]): + raise RuntimeError(f"preflight altered a GT mask: {key}") + records.append({"expert": expert, "source": source, "zero_init_max_abs": differences}) + if source == "H2O": + smoke_batch = batch + batch = smoke_batch + for step in range(3): + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = base.BimanualLoss(base.LOSS)(prediction, batch) + if not torch.isfinite(losses["total"]): + raise RuntimeError("real-data loss is nonfinite") + losses["total"].backward() + gradients = {name: sum(float(p.grad.float().abs().sum()) for p in module.parameters() + if p.grad is not None) + for name, module in (("ray", model.branch.ray_encoder), + ("spatial", model.branch.spatial), + ("temporal", model.branch.temporal))} + if expert == "D": + gradients["depth"] = sum(float(p.grad.float().abs().sum()) + for p in model.branch.depth_encoder.parameters() if p.grad is not None) + if step == 2 and any(value <= 0 for value in gradients.values()): + raise RuntimeError(f"conditioner gradient did not reach all active modules: {gradients}") + if any(p.grad is not None for p in model.parent.parameters()): + raise RuntimeError("gradient reached the RGB parent") + norm = torch.nn.utils.clip_grad_norm_(model.branch.parameters(), 100) + if not torch.isfinite(norm): + raise RuntimeError("nonfinite branch gradients") + optimizer.step() + if frozen_fingerprint(model) != frozen: + raise RuntimeError("real-data smoke changed the frozen parent") + missing = rgb_inputs(batch) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + original, prediction = model.parent(missing), model(missing) + for key, value in original.items(): + if torch.is_tensor(value) and not torch.equal(value, prediction[key]): + raise RuntimeError(f"trained branch changed missing-mask RGB fallback: {key}") + records.append({"expert": expert, "post_smoke_branch_gradients": gradients, + "frozen_parent_exact": True, "rgb_fallback_all_tensors_exact": True, + "trainable_parameters": sum(p.numel() for p in model.branch.parameters()), + "peak_allocated_gib": torch.cuda.max_memory_allocated() / 1024**3}) + del model, optimizer, prediction, original, batch, losses + torch.cuda.empty_cache() + dump(ROOT / "gpu_contract.json", {"status": "pass", "records": records, + "smoke_updates_discarded": True}) + print(json.dumps({"status": "pass", "records": records}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/launch.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad09cfb3dc265edaab4bd68975290eea55e0dfd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/launch.py @@ -0,0 +1,22 @@ +"""Detach only a new registered MoT queue; never replace a running attempt.""" + +import json +import os +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parent + +if __name__ == "__main__": + config = json.loads((ROOT / "config.json").read_text()) + path = ROOT / f"controller_{config['attempt']}.log" + if path.exists(): + raise FileExistsError("inspect the old attempt before relaunching") + with path.open("xb") as log: + process = subprocess.Popen([sys.executable, "-u", str(ROOT / "controller.py")], + cwd=ROOT, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, close_fds=True, + env=dict(os.environ, PYTHONUNBUFFERED="1")) + (ROOT / "controller.pid").write_text(f"{process.pid}\n") + print(json.dumps({"controller_pid": process.pid, "log": str(path)}), flush=True) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/model.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7bbaf532136e960cc9d8cee4aee5d2a1098dccac --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/model.py @@ -0,0 +1,222 @@ +"""Asymmetric MoT-inspired query refinement over a read-only RGB parent.""" + +from __future__ import annotations + +import copy + +import torch +from torch import nn + +from foundation_hand.geometry.camera import patch_center_rays +from foundation_hand.geometry.rotations import axis_angle_to_matrix + + +GEOMETRY_KEYS = ( + "joint2d_norm", "mano_rotation_matrices", "mano_shape_sequence", + "mano_shape", "wrist_root_translation", "vertices_camera", "joints_camera", +) + + +def availability(batch, name): + frame = batch["frame_valid"].bool() + legacy = "K_available" if name == "K" else "depth_available" + value = batch.get(f"{name}_input_available", batch.get(legacy)) + if value is None: + return torch.zeros_like(frame) + if value.shape != frame.shape: + raise ValueError("input availability must align with [B,T]") + return value.bool() & frame + + +def select_mode(batch): + frame = batch["frame_valid"].bool() + if frame.ndim != 2 or frame.shape[0] != 1 or not bool(frame.any()): + raise ValueError("routing requires one nonempty clip") + if not bool(availability(batch, "K")[frame].all()): + return "rgb" + if "K" not in batch: + raise ValueError("available K has no matrix") + depth = availability(batch, "depth")[frame].all() + if bool(depth) and ("depth_m" not in batch or "depth_pixel_valid" not in batch): + raise ValueError("available depth has no aligned values/validity") + return "rgb_depth_k" if bool(depth) else "rgb_k" + + +def rgb_inputs(batch): + result = dict(batch) + result.pop("K", None) + missing = torch.zeros_like(batch["frame_valid"], dtype=torch.bool) + result.update(K_input_available=missing, K_available=missing.clone(), + depth_input_available=missing.clone(), depth_available=missing.clone()) + return result + + +class ModalityQueryBlock(nn.Module): + def __init__(self, source, with_depth): + super().__init__() + self.hand_norm = copy.deepcopy(source.query_norm) + self.hand_attention = copy.deepcopy(source.hand_attention) + self.rgb_query_norm = copy.deepcopy(source.query_norm) + self.rgb_memory_norm = copy.deepcopy(source.rgb_norm) + self.rgb_attention = copy.deepcopy(source.rgb_attention) + self.ray_query_norm = copy.deepcopy(source.query_norm) + self.ray_memory_norm = copy.deepcopy(source.rgb_norm) + self.ray_attention = copy.deepcopy(source.rgb_attention) + self.ffn = copy.deepcopy(source.ffn) + self.with_depth = with_depth + if with_depth: + self.depth_query_norm = copy.deepcopy(source.query_norm) + self.depth_memory_norm = copy.deepcopy(source.depth_norm) + self.depth_attention = copy.deepcopy(source.depth_attention) + + def forward(self, query, rgb, rays, depth, side): + normalized = self.hand_norm(query + side) + query = query + self.hand_attention(normalized, normalized, normalized, + need_weights=False)[0] + memories = [("rgb", rgb), ("ray", rays)] + if self.with_depth: + memories.append(("depth", depth)) + for name, memory in memories: + q = getattr(self, f"{name}_query_norm")(query + side) + kv = getattr(self, f"{name}_memory_norm")(memory) + delta = getattr(self, f"{name}_attention")(q, kv, kv, need_weights=False)[0] + query = query + (0.5 * delta if name == "depth" else delta) + return query + self.ffn(query) + + +class QueryRepair(nn.Module): + def __init__(self, parent, expert): + super().__init__() + self.expert = expert + self.ray_encoder = copy.deepcopy(parent.ray_encoder) + if expert == "D": + self.depth_encoder = copy.deepcopy(parent.depth_encoder) + self.side_embedding = nn.Parameter(parent.side_embedding.detach().clone()) + self.query_bias = nn.Parameter(torch.zeros_like(parent.hand_queries)) + self.spatial = nn.ModuleList([ + ModalityQueryBlock(layer, expert == "D") for layer in parent.decoder.spatial + ]) + self.temporal = copy.deepcopy(parent.decoder.temporal) + self.shape_score = copy.deepcopy(parent.shape_score) + dim = parent.hand_queries.shape[-1] + self.rotation_head = nn.Linear(dim, 16 * 3) + self.translation_head = nn.Linear(dim, 3) + self.shape_head = nn.Linear(dim, 10) + self.joint2d_head = nn.Linear(dim, 42) + for head in (self.rotation_head, self.translation_head, self.shape_head, self.joint2d_head): + nn.init.zeros_(head.weight) + nn.init.zeros_(head.bias) + self.requires_grad_(True) + + def forward(self, batch, features, coarse): + batch_size, time, hands, dim = coarse["hand_tokens"].shape + frame = batch["frame_valid"].bool() + K = batch["K"].reshape(batch_size * time, 3, 3).to(features.tokens.dtype) + k_mask = availability(batch, "K").reshape(-1) + if (not bool(torch.isfinite(K[k_mask]).all()) + or bool((K[k_mask][:, (0, 1), (0, 1)] <= 0).any())): + raise ValueError("invalid available intrinsics") + K = torch.where(k_mask[:, None, None], K, torch.eye(3, device=K.device, dtype=K.dtype)) + raw = patch_center_rays(K, features.grid_hw, features.patch_size) + k_valid = availability(batch, "K").reshape(-1, 1, 1).to(raw.dtype) + ray_inputs = torch.cat((raw, k_valid.expand(-1, raw.shape[1], 1)), dim=-1) + rays = self.ray_encoder(ray_inputs) * k_valid + depth = None + if self.expert == "D": + d = batch["depth_m"].reshape(batch_size * time, 1, *batch["rgb"].shape[-2:]) + valid = (batch["depth_pixel_valid"].reshape_as(d).bool() + & torch.isfinite(d) & (d > 0) & frame.reshape(-1, 1, 1, 1)) + d = torch.where(valid, d, torch.zeros_like(d)) + depth_features = self.depth_encoder(d.to(features.tokens.dtype), valid, K) + if depth_features.grid_hw != features.grid_hw: + raise ValueError("RGB/depth patch grids differ") + depth = depth_features.tokens + query = coarse["hand_tokens"].detach() + self.query_bias + for index, spatial in enumerate(self.spatial): + query = spatial(query.reshape(batch_size * time, hands, dim), features.tokens, + rays, depth, self.side_embedding[None]).reshape(batch_size, time, hands, dim) + query = self.temporal[index](query, frame)[0] + scores = self.shape_score(query).squeeze(-1).masked_fill(~frame[:, :, None], -torch.inf) + weights = torch.softmax(scores, dim=1) + pooled = (query * weights[..., None]).sum(dim=1) + return { + "query": query, "rotation": self.rotation_head(query).reshape(batch_size, time, hands, 16, 3), + "translation": self.translation_head(query), "shape": self.shape_head(pooled), + "joint2d": self.joint2d_head(query).reshape(batch_size, time, hands, 21, 2), + "shape_weights": weights, + } + + +class MoTResidualModel(nn.Module): + def __init__(self, parent, expert): + super().__init__() + if expert not in ("K", "D") or parent.decoder.mode != "alternating": + raise ValueError("repair requires K/D and the registered alternating S4 decoder") + self.parent = parent.requires_grad_(False).eval() + self.expert = expert + self.branch = QueryRepair(parent, expert) + + @property + def mano_layer(self): + return self.parent.mano_layer + + def train(self, mode=True): + super().train(mode) + self.parent.eval() + return self + + def forward(self, batch): + mode = select_mode(batch) + usable = mode == "rgb_depth_k" if self.expert == "D" else mode != "rgb" + if not usable: + with torch.no_grad(): + return self.parent(rgb_inputs(batch)) + captured = [] + hook = self.parent.rgb_encoder.register_forward_hook(lambda module, args, output: captured.append(output)) + try: + with torch.no_grad(): + coarse = self.parent(rgb_inputs(batch)) + finally: + hook.remove() + if len(captured) != 1: + raise RuntimeError("RGB parent must encode exactly once") + residual = self.branch(batch, captured[0], coarse) + output = dict(coarse) + R0 = coarse["mano_rotation_matrices"] + with torch.autocast(R0.device.type, enabled=False): + delta = axis_angle_to_matrix(residual["rotation"].float()) + eye = torch.eye(3, dtype=delta.dtype, device=delta.device) + update = (delta - eye) @ R0.float() + R = R0 + update.to(R0.dtype) + t0 = coarse["wrist_root_translation"] + t_delta = residual["translation"].to(t0.dtype) + t = torch.cat((t0[..., :2] + t_delta[..., :2], + t0[..., 2:3] * t_delta[..., 2:3].clamp(-4.0, 4.0).exp()), dim=-1) + shape_sequence = coarse["mano_shape_sequence"] + residual["shape"] + shape = shape_sequence[:, None].expand_as(coarse["mano_shape"]) + p0 = coarse["joint2d_norm"] + logits = torch.logit(p0.float().clamp(1e-6, 1.0 - 1e-6)) + p_delta = torch.sigmoid(logits + residual["joint2d"].float()) - torch.sigmoid(logits) + p = (p0 + p_delta.to(p0.dtype)).clamp(0.0, 1.0) + vertices, joints = self.mano_layer(R, shape, t) + output.update(hand_tokens=residual["query"], mano_rotation_matrices=R, + mano_rotations_6d=R[..., :2, :].reshape(*R.shape[:-2], 6), + mano_shape_sequence=shape_sequence, mano_shape=shape, + wrist_root_translation=t, joint2d_norm=p, + shape_pool_weights=residual["shape_weights"], + vertices_camera=vertices, joints_camera=joints, + mot_expert=self.expert, mot_rotation_delta=residual["rotation"], + mot_translation_delta=residual["translation"]) + return output + + +class MoTRouter(nn.Module): + def __init__(self, rgb, rgb_k, rgb_depth_k): + super().__init__() + self.experts = nn.ModuleDict({"rgb": rgb, "rgb_k": rgb_k, "rgb_depth_k": rgb_depth_k}) + self.requires_grad_(False) + self.eval() + + def forward(self, batch): + mode = select_mode(batch) + return self.experts[mode](rgb_inputs(batch) if mode == "rgb" else batch) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/test_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..0da8e19d867d3a5bfcc3ec170d6f2e6506830a9c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/test_contract.py @@ -0,0 +1,203 @@ +import copy +import json +from pathlib import Path +import sys +import unittest + +import torch +from torch import nn + +ROOT = Path(__file__).resolve().parent +BASE_CODE = Path(json.loads((ROOT / "config.json").read_text())["base_root"]) / "code" +if not BASE_CODE.exists(): + BASE_CODE = ROOT.parent / "clean_gt_from_dino_20260925/code" +sys.path.insert(0, str(BASE_CODE / "src")) + +from foundation_hand.models.decoder import HandQueryDecoder +from foundation_hand.models.encoders import DepthGeometryEncoder, PatchFeatures +from model import GEOMETRY_KEYS, MoTResidualModel, MoTRouter, rgb_inputs, select_mode +from camera_geometry import point_to_ray_translation, unit_bearings + +torch.set_num_threads(1) + + +class FakeEncoder(nn.Module): + def __init__(self): + super().__init__() + self.projection = nn.Conv2d(3, 16, 4, stride=4) + + def forward(self, rgb): + value = self.projection(rgb) + return PatchFeatures(value.flatten(2).transpose(1, 2), value.shape[-2:], 4) + + +class FakeMano(nn.Module): + def forward(self, rotations, shape, translation): + offset = rotations[..., 0, 0, :] * .01 + shape[..., :3] * .005 + joints = translation[..., None, :] + offset[..., None, :].expand(*translation.shape[:-1], 21, 3) + return joints[..., :4, :], joints + + +class FakeParent(nn.Module): + def __init__(self): + super().__init__() + self.rgb_encoder = FakeEncoder() + self.ray_encoder = nn.Sequential(nn.Linear(4, 16), nn.GELU(), nn.Linear(16, 16)) + self.depth_encoder = DepthGeometryEncoder(16, 4, "geometry") + nn.init.normal_(self.depth_encoder.encoder[-1].weight, std=.001) + self.hand_queries = nn.Parameter(torch.randn(2, 16)) + self.side_embedding = nn.Parameter(torch.randn(2, 16)) + self.decoder = HandQueryDecoder(16, 3, 4, True, True, True, "alternating") + self.shape_score = nn.Linear(16, 1) + self.shape_head = nn.Linear(16, 10) + self.translation_head = nn.Linear(16, 3) + self.joint2d_head = nn.Linear(16, 42) + self.mano_layer = FakeMano() + + def forward(self, batch): + B, T = batch["rgb"].shape[:2] + features = self.rgb_encoder(batch["rgb"].reshape(B * T, 3, 16, 16)) + memory = features.tokens.reshape(B, T, 16, 16) + query = (self.hand_queries + self.side_embedding)[None, None].expand(B, T, -1, -1) + query = self.decoder(query, memory, None, batch["frame_valid"], + torch.zeros_like(batch["frame_valid"]), self.side_embedding[None])[0] + translation = self.translation_head(query) + translation = torch.cat((translation[..., :2], nn.functional.softplus(translation[..., 2:3])), -1) + shape_sequence = self.shape_head(query.mean(1)) + shape = shape_sequence[:, None].expand(B, T, 2, 10) + R = torch.eye(3)[None, None, None, None].expand(B, T, 2, 16, 3, 3).clone() + vertices, joints = self.mano_layer(R, shape, translation) + return {"hand_tokens": query, "mano_rotation_matrices": R, + "mano_shape_sequence": shape_sequence, "mano_shape": shape, + "wrist_root_translation": translation, + "joint2d_norm": self.joint2d_head(query).reshape(B, T, 2, 21, 2).sigmoid(), + "vertices_camera": vertices, "joints_camera": joints} + + +def batch_for(mode="K"): + frame = torch.tensor([[True, True, False]]) + K = torch.tensor([[12., 0., 8.], [0., 12., 8.], [0., 0., 1.]])[None, None].expand(1, 3, 3, 3).clone() + return {"rgb": torch.randn(1, 3, 3, 16, 16), "frame_valid": frame, "K": K, + "K_input_available": frame & (mode != "RGB"), "K_available": frame.clone(), + "depth_input_available": frame & (mode == "D"), + "depth_m": torch.ones(1, 3, 1, 16, 16) * .5, + "depth_pixel_valid": torch.ones(1, 3, 1, 16, 16, dtype=torch.bool)} + + +class ModelTests(unittest.TestCase): + def setUp(self): + torch.manual_seed(17) + + def test_zero_init_matches_parent_geometry(self): + for expert in ("K", "D"): + model = MoTResidualModel(FakeParent(), expert).eval() + batch = batch_for(expert) + with torch.no_grad(): + baseline, prediction = model.parent(rgb_inputs(batch)), model(batch) + for key in GEOMETRY_KEYS: + self.assertTrue(torch.equal(baseline[key], prediction[key]), (expert, key)) + self.assertEqual(len(model.parent.rgb_encoder._forward_hooks), 0) + + def test_frozen_parent_and_branch_gradient_flow(self): + for expert in ("K", "D"): + model = MoTResidualModel(FakeParent(), expert).train() + initial = {key: value.clone() for key, value in model.parent.state_dict().items()} + optimizer = torch.optim.AdamW(model.branch.parameters(), lr=.001) + batch = batch_for(expert) + self.assertFalse(model.parent.training) + self.assertTrue(model.branch.training) + for step in range(3): + optimizer.zero_grad(set_to_none=True) + output = model(batch) + loss = (output["joints_camera"] - .1).square().mean() + loss += output["mano_rotation_matrices"][..., 0, 1].mean() + loss += output["joint2d_norm"].square().mean() + loss.backward() + for parameter in model.branch.parameters(): + if parameter.grad is not None: + self.assertTrue(bool(torch.isfinite(parameter.grad).all())) + if step == 2: + for module in (model.branch.ray_encoder, model.branch.spatial, model.branch.temporal): + self.assertGreater(sum(float(p.grad.abs().sum()) for p in module.parameters() + if p.grad is not None), 0) + if expert == "D": + self.assertGreater(sum(float(p.grad.abs().sum()) for p in model.branch.depth_encoder.parameters() + if p.grad is not None), 0) + optimizer.step() + self.assertTrue(all(p.grad is None for p in model.parent.parameters())) + for key, value in model.parent.state_dict().items(): + self.assertTrue(torch.equal(initial[key], value), key) + + def test_missing_modality_is_exact_rgb_bypass(self): + for expert in ("K", "D"): + model = MoTResidualModel(FakeParent(), expert) + nn.init.normal_(model.branch.translation_head.weight) + batch = batch_for("RGB") + batch["K"].fill_(float("nan")) + original = model.parent(rgb_inputs(batch)) + actual = model(batch) + for key in original: + self.assertTrue(torch.equal(original[key], actual[key]), key) + + def test_mode_canonical_masks_padding_and_missing_payload(self): + batch = batch_for("D") + batch["K"][0, 2].fill_(float("nan")) + self.assertEqual(select_mode(batch), "rgb_depth_k") + self.assertTrue(torch.isfinite(MoTResidualModel(FakeParent(), "D")(batch)["vertices_camera"]).all()) + batch["depth_input_available"][0, 1] = False + self.assertEqual(select_mode(batch), "rgb_k") + batch["K_input_available"].zero_() + self.assertEqual(select_mode(batch), "rgb") + batch["K_input_available"] = batch["frame_valid"].clone() + batch.pop("K") + with self.assertRaises(ValueError): + select_mode(batch) + + def test_independent_parameters_and_K_depth_invariance(self): + parent = FakeParent() + K_model = MoTResidualModel(copy.deepcopy(parent), "K").eval() + D_model = MoTResidualModel(copy.deepcopy(parent), "D").eval() + left = {p.data_ptr() for p in K_model.branch.parameters()} + right = {p.data_ptr() for p in D_model.branch.parameters()} + self.assertFalse(left & right) + nn.init.normal_(K_model.branch.translation_head.weight, std=.01) + batch = batch_for("D") + first = K_model(batch)["wrist_root_translation"] + batch["depth_m"] *= 100 + self.assertTrue(torch.equal(first, K_model(batch)["wrist_root_translation"])) + + +class CameraTests(unittest.TestCase): + def test_native_fisheye_does_not_fall_back_to_pinhole(self): + pixels = torch.tensor([[4., 8.], [8., 8.]]) + K = torch.tensor([[12., 0., 8.], [0., 12., 8.], [0., 0., 1.]]) + with self.assertRaises(ValueError): + unit_bearings(pixels, K, image_camera_model="fisheye624") + native = torch.tensor([[1., 2., 1.], [0., 0., 1.]]) + actual = unit_bearings(pixels, K, image_camera_model="fisheye624", native_bearings=native) + self.assertTrue(torch.allclose(actual.norm(dim=-1), torch.ones(2))) + + def test_ray_solver_recovery_and_gradients(self): + J = torch.randn(21, 3) * .05 + translation = torch.tensor([.1, -.2, .6]) + rays = (J + translation).detach().requires_grad_(True) + output = point_to_ray_translation(J, rays, torch.ones(21), torch.zeros(3)) + self.assertTrue(bool(output["valid"])) + self.assertTrue(torch.allclose(output["translation"], translation, atol=2e-5)) + output["translation"].square().sum().backward() + self.assertTrue(bool(torch.isfinite(rays.grad).all())) + + def test_parallel_and_missing_rays_have_finite_fallback(self): + J = torch.zeros(21, 3) + rays = torch.tensor([0., 0., 1.]).expand(21, 3).clone().requires_grad_(True) + fallback = torch.tensor([.2, .1, .5]) + for weights in (torch.ones(21), torch.zeros(21)): + output = point_to_ray_translation(J, rays, weights, fallback) + self.assertFalse(bool(output["valid"])) + self.assertTrue(torch.equal(output["translation"], fallback)) + output["translation"].sum().backward() + self.assertTrue(bool(torch.isfinite(rays.grad).all())) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/train_expert.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/train_expert.py new file mode 100644 index 0000000000000000000000000000000000000000..2119dfcb0632d9f4ae52935187a89cd03e6e818c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_mot_residual/train_expert.py @@ -0,0 +1,7 @@ +"""Keep the reference trainer intact; substitute only common/model definitions.""" + +import runpy +from common import REFERENCE_ROOT + +if __name__ == "__main__": + runpy.run_path(str(REFERENCE_ROOT / "train_expert.py"), run_name="__main__") diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_formal_stage.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_formal_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..68ad0c1c90c60fc8329518db2ec8956b0a6c137e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_formal_stage.py @@ -0,0 +1,133 @@ +"""Audit a completed formal stage endpoint without modifying training state.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +import math +from pathlib import Path +import statistics + +import torch + +from clean_train import INDEX, STAGES, sha, training_code_hashes + + +EXTREME_LOSS_THRESHOLD = 100.0 + + +def run(checkpoint: Path, metrics: Path, stage: str, update: int) -> dict: + state = torch.load(checkpoint, map_location="cpu", weights_only=False) + rows = [json.loads(line) for line in metrics.open()] + errors = [] + if not rows or len(rows) != update or [row["update"] for row in rows] != list(range(1, update + 1)): + errors.append("metrics do not contain every update through the requested endpoint") + if state["stage"] != stage or state["update"] != update: + errors.append("checkpoint stage or update differs from requested endpoint") + if state.get("smoke") or not state.get("complete_backbone"): + errors.append("checkpoint is smoke or lacks the complete backbone") + if state["world_size"] != 6 or len(state["rank_rng_states"]) != 6: + errors.append("checkpoint is not a complete six-rank state") + if state["next_global_sample_position"] != STAGES[stage]["offset"] + 6 * update: + errors.append("sampler cursor differs from the registered stage schedule") + if state["index_sha256"] != sha(INDEX) or state["code_sha256"] != training_code_hashes(): + errors.append("checkpoint data index or training code identity differs from current files") + if state.get("grad_clip") != 100.0: + errors.append("gradient clipping threshold differs from the frozen recipe") + exposure = Counter(state["exposures"]) + if sum(exposure.values()) != 6 * update: + errors.append("source/mode exposure ledger does not sum to global batch times updates") + if stage in ("S1", "S2", "S3"): + expected = {"H2O": 0.40, "ARCTIC": 0.35, "HOT3D": 0.25} + else: + expected = {"H2O": 0.35, "ARCTIC": 0.25, "HOT3D": 0.40} + source_exposure = { + source: sum(count for key, count in exposure.items() if key.startswith(source + ":")) + for source in expected + } + for source, fraction in expected.items(): + if abs(source_exposure[source] - 6 * update * fraction) > 6: + errors.append(f"{source} exposure differs from the registered quota") + expected_modes = { + "H2O:rgb", "H2O:rgb_k", "H2O:rgb_depth_k", + "ARCTIC:rgb", "ARCTIC:rgb_k", "HOT3D:rgb", "HOT3D:rgb_k", + } + if set(exposure) != expected_modes: + errors.append("one or more registered source/input modes are absent") + supervision = state.get("supervision_exposures") + if (not isinstance(supervision, dict) or not supervision + or sum(supervision.values()) <= 0 or min(supervision.values()) < 0): + errors.append("supervision ledger is empty or contains invalid counts") + if rows: + last = rows[-1] + if last["exposures"] != state["exposures"] or last.get("supervision_exposures") != supervision: + errors.append("final metrics row and checkpoint exposure ledgers differ") + if not all(math.isfinite(row["loss"]) and math.isfinite(row["grad_norm_max"]) for row in rows): + errors.append("nonfinite loss or gradient norm in the training history") + extreme_loss_updates = [row["update"] for row in rows + if math.isfinite(row["loss"]) + and row["loss"] > EXTREME_LOSS_THRESHOLD] + if extreme_loss_updates: + errors.append(f"extreme finite loss at updates {extreme_loss_updates[:20]}") + detailed = [row for row in rows if "grad_parameter_groups" in row] + required_groups = { + "rgb_encoder.projection", "depth_encoder", "ray_encoder", + "decoder.spatial", "joint2d_head", "rotation_head", + "translation_head", "shape_head", + } + if stage != "S1": + required_groups.update(("decoder.temporal", "shape_score")) + if stage == "S4": + required_groups.add("rgb_encoder.backbone") + if not all(any(row["grad_parameter_groups"].get(group, 0) > 0 for row in detailed) + for group in required_groups): + errors.append("a required trainable parameter group never received a nonzero gradient") + else: + detailed = [] + extreme_loss_updates = [] + window = min(100, len(rows)) + report = { + "status": "pass" if not errors else "fail", + "errors": errors, + "checkpoint": str(checkpoint), + "checkpoint_sha256": sha(checkpoint), + "stage": stage, + "update": update, + "training_code_sha256": state["code_sha256"]["clean_train.py"], + "source_exposure": source_exposure, + "source_mode_exposure": dict(exposure), + "supervision_ledger_keys": len(supervision or {}), + "supervision_elements": sum((supervision or {}).values()), + "first_window_loss_mean": statistics.mean(row["loss"] for row in rows[:window]) if rows else None, + "last_window_loss_mean": statistics.mean(row["loss"] for row in rows[-window:]) if rows else None, + "last_window_grad_norm_median": statistics.median(row["grad_norm_max"] for row in rows[-window:]) if rows else None, + "clipped_updates": sum(bool(row["clipped"]) for row in rows), + "max_batch_loss": max((row["loss"] for row in rows), default=None), + "extreme_loss_threshold": EXTREME_LOSS_THRESHOLD, + "extreme_loss_updates": extreme_loss_updates, + "detailed_rows": len(detailed), + } + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--metrics", type=Path, required=True) + parser.add_argument("--stage", choices=tuple(STAGES), required=True) + parser.add_argument("--update", type=int, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + report = run(args.checkpoint, args.metrics, args.stage, args.update) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2)) + if report["errors"]: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_gt_projection.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_gt_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..3a92d42d3cad354945b06e3c8d86d25dae30e4d0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_gt_projection.py @@ -0,0 +1,108 @@ +"""Freeze a 100-frame RGB/GT/K alignment gallery from trainable native clips.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from clean_train import ASSETS, MANIFESTS +from filtered_dataset import FilteredClipDataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.geometry.camera import project_points + + +QUOTAS = {"H2O": 40, "ARCTIC": 30, "HOT3D": 30} +CELL_HW = (200, 356) + + +def thumbnail(sample: dict, source: str, tile_id: str) -> tuple[np.ndarray, list[float], int]: + frame = len(sample["rgb"]) // 2 + rgb = sample["rgb"][frame].permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + points = sample["joint3d_camera"][frame] + K = sample["K"][frame] + projected, positive = project_points(points, K) + target = sample["joint2d"][frame] + valid = (sample["joint2d_valid"][frame] & sample["joint3d_valid"][frame] + & positive & torch.isfinite(target).all(-1)) + errors = torch.linalg.vector_norm(projected - target, dim=-1)[valid].tolist() + height, width = image.shape[:2] + for hand in range(2): + for joint in range(21): + if not bool(valid[hand, joint]): + continue + x, y = target[hand, joint].tolist() + px, py = projected[hand, joint].tolist() + if 0 <= x < width and 0 <= y < height: + cv2.circle(image, (round(x), round(y)), 3, (0, 255, 255), -1) + if 0 <= px < width and 0 <= py < height: + cv2.circle(image, (round(px), round(py)), 2, (255, 0, 255), -1) + cell_height, cell_width = CELL_HW + image = cv2.resize(image, (cell_width, cell_height - 28), interpolation=cv2.INTER_AREA) + cell = np.zeros((cell_height, cell_width, 3), dtype=np.uint8) + cell[:cell_height - 28] = image + label = f"{source} {tile_id[-22:]} valid={int(valid.sum())}" + cv2.putText(cell, label, (5, cell_height - 9), cv2.FONT_HERSHEY_SIMPLEX, + .38, (255, 255, 255), 1, cv2.LINE_AA) + return cell, errors, int(valid.sum()) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + args.output.mkdir(parents=True) + cells = [] + report = {"schema": "clean_gt_projection_audit_v1", "selection": "linspace over frozen trainable T8 manifests", + "total_frames": sum(QUOTAS.values()), "sources": {}} + for source, count in QUOTAS.items(): + manifest = MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl" + dataset = FilteredClipDataset( + source, manifest, 8, (368, 640), ASSETS["mano_root"], + Path(__file__).parent / "third_party", {"enabled": False}, + ) + indices = np.linspace(0, len(dataset) - 1, count, dtype=int) + errors = [] + valid_counts = [] + tiles = [] + for index in indices: + row = dataset.rows[int(index)] + tile_id = str(row["filtered_tile_id"]) + sample = dataset[{"source": source, "tile_id": tile_id, "epoch": 0, + "mode": "rgb_depth_k" if source == "H2O" else "rgb_k", + "position": 0, "source_ordinal": int(index)}] + cell, joint_errors, valid_count = thumbnail(sample, source, tile_id) + cells.append(cell) + errors.extend(joint_errors) + valid_counts.append(valid_count) + tiles.append(tile_id) + values = np.asarray(errors) + report["sources"][source] = { + "frames": count, "frames_with_valid_3d_and_2d": sum(x > 0 for x in valid_counts), + "valid_joints": len(errors), "mean_reprojection_px": float(values.mean()) if len(values) else None, + "p95_reprojection_px": float(np.quantile(values, .95)) if len(values) else None, + "max_reprojection_px": float(values.max()) if len(values) else None, + "tile_ids": tiles, + } + height, width = CELL_HW + gallery = np.zeros((10 * height, 10 * width, 3), dtype=np.uint8) + for number, cell in enumerate(cells): + row, col = divmod(number, 10) + gallery[row * height:(row + 1) * height, col * width:(col + 1) * width] = cell + if not cv2.imwrite(str(args.output / "gt_projection_100.jpg"), gallery): + raise RuntimeError("gallery write failed") + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({name: {key: value for key, value in row.items() if key != "tile_ids"} + for name, row in report["sources"].items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_headset_sync.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_headset_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..679b0c33f13bd968d67a8980223428165da61a61 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_headset_sync.py @@ -0,0 +1,104 @@ +"""Audit HOT3D camera-frame GT construction against native headset pose time.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import csv +from functools import lru_cache +import json +from pathlib import Path + +import numpy as np + +from preflight_index import tile_starts + + +MAX_DELTA_NS = 20_000_000 + + +@lru_cache(maxsize=256) +def trajectory(root: str) -> np.ndarray: + path = Path(root) / "headset_trajectory.csv" + with path.open(newline="") as stream: + stamps = np.asarray( + [int(row["timestamp[ns]"]) for row in csv.DictReader(stream)], dtype=np.int64, + ) + if len(stamps) == 0 or np.any(np.diff(stamps) <= 0): + raise ValueError(f"empty or nonmonotone headset trajectory: {path}") + return stamps + + +@lru_cache(maxsize=256) +def timeline(path: str, stream: str) -> np.ndarray: + return np.asarray(json.loads(Path(path).read_text())[stream], dtype=np.int64) + + +def deltas(target: np.ndarray, reference: np.ndarray) -> np.ndarray: + upper = np.searchsorted(reference, target).clip(0, len(reference) - 1) + lower = (upper - 1).clip(0, len(reference) - 1) + return np.minimum(np.abs(reference[upper] - target), np.abs(reference[lower] - target)) + + +def audit(manifest: Path) -> tuple[dict, list[dict]]: + counts = Counter() + recording_bad = Counter() + bad: list[dict] = [] + max_deltas = [] + for line in manifest.open(): + if not line.strip(): + continue + row = json.loads(line) + if row["dataset"] != "HOT3D": + continue + source = row["source"] + stamps = timeline(source["timestamps_path"], row["stream_id"])[ + int(row["start"]):int(row["end"]) + ] + if len(stamps) != row["frame_count"]: + raise ValueError(f"timeline length mismatch: {row['id']}") + delta = deltas(stamps, trajectory(source["root"])) + bad_frames = delta > MAX_DELTA_NS + bad_tiles = [start for start in tile_starts(len(stamps)) + if bool(bad_frames[start:start + 8].any())] + counts["windows"] += 1 + counts["frames"] += len(stamps) + counts["tiles"] += len(tile_starts(len(stamps))) + counts["bad_frames"] += int(bad_frames.sum()) + counts["bad_tiles"] += len(bad_tiles) + if bad_frames.any(): + counts["bad_windows"] += 1 + recording_bad[row["recording_id"]] += 1 + max_deltas.append(float(delta.max() / 1e6)) + bad.append({"window_id": row["id"], "recording_id": row["recording_id"], + "stream_id": row["stream_id"], "bad_frame_offsets": np.flatnonzero(bad_frames).tolist(), + "bad_tile_offsets": bad_tiles, "maximum_nearest_headset_delta_ms": float(delta.max() / 1e6)}) + report = { + "threshold_ms": 20, "counts": dict(counts), + "affected_recordings": len(recording_bad), + "worst_recordings_by_window_count": recording_bad.most_common(20), + "bad_window_delta_ms_median": float(np.median(max_deltas)) if max_deltas else 0, + "bad_window_delta_ms_max": max(max_deltas, default=0), + } + return report, bad + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--report", type=Path, required=True) + parser.add_argument("--bad-windows", type=Path, required=True) + args = parser.parse_args() + for path in (args.report, args.bad_windows): + if path.exists(): + raise FileExistsError(path) + report, bad = audit(args.manifest) + args.report.write_text(json.dumps(report, indent=2) + "\n") + with args.bad_windows.open("w") as stream: + for row in bad: + stream.write(json.dumps(row) + "\n") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_input_modes.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_input_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c4c2ab8786bbffe21be79e147165f59b008111 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_input_modes.py @@ -0,0 +1,58 @@ +"""Assert modality input dropout never changes camera or GT supervision.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from clean_train import ASSETS, MANIFESTS +from filtered_dataset import FilteredClipDataset + + +SUPERVISION = ( + "K", "K_supervision_valid", "joint2d", "joint2d_valid", + "joint3d_camera", "joint3d_valid", "wrist_root_translation", + "translation_valid", "mano_pose", "mano_pose_valid", "mano_shape", + "shape_valid", "vertices_valid", "reprojection_valid", +) + + +def main() -> None: + result = {} + for source in ("H2O", "ARCTIC", "HOT3D"): + manifest = MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl" + dataset = FilteredClipDataset( + source, manifest, 8, (368, 640), ASSETS["mano_root"], + Path(__file__).parent / "third_party", {"enabled": False}, + ) + row = dataset.rows[0] + spec = {"source": source, "tile_id": row["filtered_tile_id"], + "position": 0, "source_ordinal": 0, "epoch": 0} + modes = ("rgb", "rgb_k", "rgb_depth_k") if source == "H2O" else ("rgb", "rgb_k") + samples = {mode: dataset[{**spec, "mode": mode}] for mode in modes} + reference = samples["rgb"] + frame = reference["frame_valid"].bool() + if not bool(reference["K_supervision_valid"].any()): + raise AssertionError(f"{source} selected clip lacks K supervision") + for mode, sample in samples.items(): + torch.testing.assert_close(sample["rgb"], reference["rgb"]) + for name in SUPERVISION: + torch.testing.assert_close(sample[name], reference[name], equal_nan=True) + expected_K = frame if mode != "rgb" else torch.zeros_like(frame) + expected_depth = frame if mode == "rgb_depth_k" else torch.zeros_like(frame) + for canonical, alias, expected in ( + ("K_input_available", "K_available", expected_K), + ("depth_input_available", "depth_available", expected_depth), + ): + if not torch.equal(sample[canonical], expected) or not torch.equal(sample[alias], expected): + raise AssertionError(f"{source}:{mode} availability flags diverge") + result[source] = {"tile_id": spec["tile_id"], "modes": modes, + "K_supervised_frames": int(reference["K_supervision_valid"].sum()), + "GT_and_real_K_unchanged": True} + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_schedule.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..d564389690154f78b10e1e20fca34b32a428afae --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/audit_schedule.py @@ -0,0 +1,50 @@ +"""Verify every registered T=8 tile is exposed before source-local reuse.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +from pathlib import Path + +from coverage_sampler import CoverageSampler, SOURCES + + +def audit(index: Path, stage: str, samples: int) -> dict: + sampler = CoverageSampler(index, stage) + seen = {source: set() for source in SOURCES} + exposures = Counter() + modes = Counter() + first_coverage = {} + for position in range(samples): + row = sampler.sample(position) + source = str(row["source"]) + ordinal = int(row["source_ordinal"]) + if ordinal < sampler.sizes[source] and row["tile_id"] in seen[source]: + raise AssertionError(f"tile repeated before coverage: {source} {row['tile_id']}") + seen[source].add(row["tile_id"]) + exposures[source] += 1 + modes[f"{source}:{row['mode']}"] += 1 + if source not in first_coverage and len(seen[source]) == sampler.sizes[source]: + first_coverage[source] = position + 1 + if any(len(seen[source]) != sampler.sizes[source] for source in SOURCES): + raise AssertionError("registered T=8 stage did not cover all source tiles") + return { + "stage": stage, "samples": samples, "status": "pass", + "tiles": sampler.sizes, "unique_tiles": {source: len(seen[source]) for source in SOURCES}, + "exposures": dict(exposures), "input_modes": dict(modes), + "first_complete_global_position": first_coverage, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--index", type=Path, required=True) + parser.add_argument("--stage", choices=("S1_S3", "S4"), required=True) + parser.add_argument("--samples", type=int, required=True) + args = parser.parse_args() + print(json.dumps(audit(args.index, args.stage, args.samples), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/benchmark_decode.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/benchmark_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a2146c5035daa63e01ea7574caf358c84a6363 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/benchmark_decode.py @@ -0,0 +1,56 @@ +"""Measure uncached native clip decoding across spaced recordings.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys +import time + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import numpy as np +import torch + +from filtered_dataset import FilteredClipDataset + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--count", type=int, default=8) + parser.add_argument("--grouped", action="store_true", help="Read consecutive tiles in one recording") + args = parser.parse_args() + start = time.perf_counter() + dataset = FilteredClipDataset( + args.source, args.manifests / f"{args.source.lower()}_t8.jsonl", 8, + (368, 640), "/SSD3/jiasen/foundation_hand/pretrained/mano", + Path(__file__).parent / "third_party", {"enabled": False}, + ) + init_seconds = time.perf_counter() - start + indices = list(range(args.count)) if args.grouped else np.linspace( + 0, len(dataset) - 1, args.count, dtype=int, + ).tolist() + times = [] + recordings = [] + with torch.no_grad(): + for sequence, index in enumerate(indices): + row = dataset.rows[index] + spec = {"source": args.source, "tile_id": row["filtered_tile_id"], + "epoch": 0, "source_ordinal": sequence, "position": sequence, + "mode": "rgb_depth_k" if args.source == "H2O" else "rgb_k"} + mark = time.perf_counter() + sample = dataset[spec] + times.append(time.perf_counter() - mark) + recordings.append(sample["physical_recording_id"]) + print(json.dumps({"source": args.source, "count": len(times), + "recordings": len(set(recordings)), "init_seconds": init_seconds, + "decode_seconds": times, "median_seconds": float(np.median(times)), + "p95_seconds": float(np.quantile(times, .95)), + "clips_per_second_single_worker": len(times) / sum(times)}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/build_trainable_index.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/build_trainable_index.py new file mode 100644 index 0000000000000000000000000000000000000000..03f9619e1b4a6beca9a51c0da26ab28d09d4d898 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/build_trainable_index.py @@ -0,0 +1,126 @@ +"""Apply audited HOT3D headset-pose eligibility without changing source GT.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +import os +from pathlib import Path +import sqlite3 + +from preflight_index import digest, tile_starts + + +def valid_runs(length: int, invalid: set[int]): + start = None + for position in range(length + 1): + good = position < length and position not in invalid + if good and start is None: + start = position + elif not good and start is not None: + yield start, position + start = None + + +def build(original: Path, audit: Path, bad_windows: Path, output: Path) -> dict: + if output.exists(): + raise FileExistsError(output) + report = json.loads(audit.read_text()) + if report["threshold_ms"] != 20 or report["counts"]["windows"] != 18962: + raise ValueError("headset synchronization audit is not the frozen full-data audit") + bad_rows = [json.loads(line) for line in bad_windows.open() if line.strip()] + if len(bad_rows) != report["counts"]["bad_windows"]: + raise ValueError("bad-window list differs from summary") + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_suffix(output.suffix + ".tmp") + if temporary.exists(): + raise FileExistsError(temporary) + source = sqlite3.connect(f"file:{original}?mode=ro", uri=True) + target = sqlite3.connect(temporary) + try: + source.backup(target) + target.execute("CREATE TABLE sync_exclusions (window_id TEXT PRIMARY KEY, bad_frame_offsets_json TEXT NOT NULL)") + lost_valid_frames = 0 + recovered_valid_frames = 0 + windows_without_t8 = 0 + for record in bad_rows: + window_id = record["window_id"] + row = target.execute( + "SELECT source,recording_id,frame_ids_json FROM windows WHERE window_id=?", + (window_id,), + ).fetchone() + if row is None or row[0] != "HOT3D": + raise ValueError(f"unknown HOT3D window {window_id}") + _, recording, frame_ids_json = row + frame_ids = json.loads(frame_ids_json) + invalid = set(record["bad_frame_offsets"]) + if not invalid or min(invalid) < 0 or max(invalid) >= len(frame_ids): + raise ValueError(f"bad frame offsets outside window {window_id}") + original_bad_tiles = [offset for (offset,) in target.execute( + "SELECT start_offset FROM tiles WHERE window_id=?", (window_id,), + ) if invalid.intersection(range(offset, offset + 8))] + if sorted(original_bad_tiles) != sorted(record["bad_tile_offsets"]): + raise ValueError(f"headset audit tile mapping differs: {window_id}") + target.execute("DELETE FROM tiles WHERE window_id=?", (window_id,)) + target.execute("INSERT INTO sync_exclusions VALUES (?,?)", + (window_id, json.dumps(sorted(invalid)))) + covered = set() + tile_count = 0 + for first, last in valid_runs(len(frame_ids), invalid): + if last - first < 8: + continue + for local_start in tile_starts(last - first): + offset = first + local_start + selected = frame_ids[offset:offset + 8] + if len(selected) != 8 or invalid.intersection(range(offset, offset + 8)): + raise AssertionError("trainable tile contains an invalid headset frame") + target.execute( + "INSERT INTO tiles VALUES (?,?,?,?,?,?)", + (f"{window_id}:{offset}", window_id, "HOT3D", recording, + offset, json.dumps(selected)), + ) + covered.update(range(offset, offset + 8)) + tile_count += 1 + if tile_count == 0: + windows_without_t8 += 1 + recovered_valid_frames += len(covered) + lost_valid_frames += (len(frame_ids) - len(invalid) - len(covered)) + counts = Counter(dict(target.execute("SELECT source, COUNT(*) FROM tiles GROUP BY source"))) + bad_tile_check = target.execute( + "SELECT COUNT(*) FROM tiles t JOIN sync_exclusions e ON t.window_id=e.window_id" + ).fetchone()[0] + target.commit() + except BaseException: + target.close() + source.close() + temporary.unlink(missing_ok=True) + raise + target.close() + source.close() + os.replace(temporary, output) + return { + "status": "pass", "original_index_sha256": digest(original), + "headset_sync_report_sha256": digest(audit), + "headset_bad_windows_sha256": digest(bad_windows), + "trainable_index_sha256": digest(output), "tiles_by_source": dict(counts), + "audited_windows_with_bad_headset_pose": len(bad_rows), + "windows_without_any_t8": windows_without_t8, + "valid_frames_covered_inside_affected_windows": recovered_valid_frames, + "valid_frames_not_packable_into_t8": lost_valid_frames, + "tiles_in_affected_windows": bad_tile_check, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--original", type=Path, required=True) + parser.add_argument("--audit", type=Path, required=True) + parser.add_argument("--bad-windows", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(build(args.original, args.audit, args.bad_windows, args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/clean_eval.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/clean_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..888132d52b7c6e468fab8ecb62bac9627b82caf8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/clean_eval.py @@ -0,0 +1,139 @@ +"""Evaluate a complete clean-GT checkpoint on frozen native-GT panels.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import ASSETS, INDEX, ROOT, model_for, sha, training_code_hashes +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.h2o_dataset import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +FOUR_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", +) + + +def dataset_for(source: str, manifest: Path): + hw = (512, 896) + if source == "H2O": + return H2OCam4Dataset( + "/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, hw, + clip_lengths=(8,), strides=(1,), window_step=8, + allow_partial=False, + ) + if source == "ARCTIC": + return ARCTICClipDataset(manifest, ASSETS["mano_root"], hw) + if source == "HOT3D": + return HOT3DClipDataset( + "/SSD3/jiasen/foundation_hand/HOT3D/dataset", manifest, + Path(__file__).parent / "third_party", ASSETS["mano_root"], + hw, K_input_dropout=0.0, + ) + raise ValueError(source) + + +def apply_mode(batch: dict, mode: str) -> None: + frame = batch["frame_valid"].bool() + K = frame.clone() if mode != "rgb" else torch.zeros_like(frame) + depth = frame.clone() if mode == "rgb_depth_k" else torch.zeros_like(frame) + batch["K_input_available"] = K + batch["depth_input_available"] = depth + batch["K_available"] = K.clone() + batch["depth_available"] = depth.clone() + if not (torch.equal(batch["K_input_available"], K) + and torch.equal(batch["depth_input_available"], depth)): + raise RuntimeError("input availability override failed") + + +def run(args: argparse.Namespace) -> dict: + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + if panel_report["train_manifest_sha256"] != "b4b0ac4bc4a771c9bc7626a9eec7f5f541ef96908a9a64d219192efd7b8f7f89": + raise RuntimeError("frozen training allowlist identity differs") + if args.role == "confirmation" and not args.final_checkpoint: + raise ValueError("confirmation is reserved for a frozen final checkpoint") + if args.source != "H2O" and args.mode == "rgb_depth_k": + raise ValueError("only H2O has real metric depth") + manifest = panels / f"{args.source.lower()}_{args.role}_t8.jsonl" + expected = panel_report["sources"][args.source][args.role]["manifest_sha256"] + if sha(manifest) != expected: + raise RuntimeError("validation panel SHA256 changed") + if args.output.exists(): + raise FileExistsError(args.output) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if not state.get("complete_backbone") or state["index_sha256"] != sha(INDEX): + raise RuntimeError("checkpoint lacks complete DINO or filtered-index identity") + if state.get("smoke", False) and not args.allow_smoke: + raise RuntimeError("smoke checkpoint is not valid for formal evaluation") + code_match = state["code_sha256"] == training_code_hashes() + if not code_match and not args.allow_smoke: + raise RuntimeError("evaluation code differs from checkpoint training code") + if args.role == "confirmation" and ( + state.get("smoke", False) or state["stage"] != "S4" + or state["update"] != 66667 + ): + raise RuntimeError("confirmation requires the frozen S4 endpoint") + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + dataset = dataset_for(args.source, manifest) + if args.limit is not None and not args.allow_smoke: + raise ValueError("subset evaluation must be marked as smoke") + limit = min(len(dataset), args.limit) if args.limit is not None else len(dataset) + rows = [] + with torch.inference_mode(): + for index in range(limit): + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"): + prediction = model(batch) + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows.append(make_row(prediction, batch, 0, frame, side)) + summary = aggregate(rows) + report = { + "role": args.role, "source": args.source, "input_mode": args.mode, + "checkpoint": str(args.checkpoint), "checkpoint_sha256": sha(args.checkpoint), + "checkpoint_stage": state["stage"], "checkpoint_update": state["update"], + "panel_sha256": expected, "clips": limit, "hands": len(rows), + "smoke": bool(args.allow_smoke), + "checkpoint_code_match": code_match, + "evaluator_sha256": sha(Path(__file__)), + "metric_impl_sha256": sha(Path(__file__).parent / "scripts/evaluate_phase7_external.py"), + "four_metrics": {name: summary[name] for name in FOUR_METRICS}, + "supervision_coverage": summary["supervision_coverage"], + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--role", choices=("development", "confirmation"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--final-checkpoint", action="store_true") + parser.add_argument("--allow-smoke", action="store_true") + parser.add_argument("--limit", type=int) + args = parser.parse_args() + print(json.dumps(run(args), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/clean_train.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/clean_train.py new file mode 100644 index 0000000000000000000000000000000000000000..3887eb28769f77ab87cea0c5fa960955b78dcf80 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/clean_train.py @@ -0,0 +1,558 @@ +"""Fresh-DINO staged Foundation Hand training on the frozen filtered-GT index. + +Use torchrun for DDP. This entry never loads a learned Foundation Hand parent. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from contextlib import nullcontext +from datetime import timedelta +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import sys +import time + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import numpy as np +import torch +import torch.distributed as dist +from torch import nn +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader, Dataset, Sampler +from safetensors import safe_open + +from coverage_sampler import CoverageSampler, SOURCES +from filtered_dataset import FilteredClipDataset +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.losses import BimanualLoss, LossConfig +from foundation_hand.training.optimizer import optimizer_parameter_groups, set_scheduled_learning_rate +from foundation_hand.training.schedule import warmup_cosine_learning_rate +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925") +INDEX = ROOT / "cache/trainable_t8_index.sqlite" +MANIFESTS = ROOT / "cache" +EXPECTED_INDEX_SHA256 = "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462" +EXPECTED_MANIFEST_SHA256 = { + 1: {"ARCTIC": "489315448fef1a2adcb50d7ba162d3d376810d0fa652905330d5e3db77620c62", + "H2O": "7bca84c00e66e9680704d5c54b1001af637cda620ef4f31037626407dcd8dc88", + "HOT3D": "391c837142e5985bf45c505bc9c3f3daa7f220c3a4144bad51635ca1f632e15f"}, + 8: {"ARCTIC": "35b61473010ae198b036d3c549ae1b922439e35711e5bc76f7f06c58fd82e7e6", + "H2O": "74e20172e321b363523f05497b891834d88edd0f349acb58288a4e6f37e01a8a", + "HOT3D": "8630298efbce16764a0c1d7bc108f46675c26a9fc290553b7920420b74f877b7"}, +} +ASSETS = { + "dinov3_source": "/home/jiasen/foundation_hand/third_party/dinov3", + "dinov3_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "mano_root": "/SSD3/jiasen/foundation_hand/pretrained/mano", +} +STAGES = { + "S1": {"time": 1, "hw": (368, 640), "updates": 16667, + "coverage": "S1_S3", "offset": 0, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S2": {"time": 8, "hw": (368, 640), "updates": 50000, + "coverage": "S1_S3", "offset": 0, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S3": {"time": 8, "hw": (512, 896), "updates": 83334, + "coverage": "S1_S3", "offset": 300000, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S4": {"time": 8, "hw": (512, 896), "updates": 66667, + "coverage": "S4", "offset": 0, "max_lr": 1e-5, "min_lr": 1e-6, "last2": 2}, +} +LOSS = LossConfig( + joint2d=1.0, joint3d_camera=10.0, joint3d_root_relative=10.0, + vertices_camera=1.0, local_pose=1.0, global_orientation=1.0, + shape=.1, translation=10.0, reprojection=1.0, + temporal_velocity=.1, temporal_acceleration=.05, + bimanual_relative_wrist=1.0, presence=0.0, +) +FRESH_HEAD_WEIGHT_STD = 0.001 +FRESH_DEPTH_WEIGHT_STD = 0.001 +MONITORED_LOSSES = ( + "joint2d", "joint3d_camera", "joint3d_root_relative", "vertices_camera", + "local_pose", "global_orientation", "shape", "translation", + "reprojection", "temporal_velocity", "temporal_acceleration", + "bimanual_relative_wrist", +) +TRANSLATION_DIAGNOSTICS = tuple( + f"translation_{axis}_{suffix}" + for axis in ("x", "y", "z") + for suffix in ("raw_mae_m", "effective_loss_contribution") +) +MASK_FIELDS = ( + "joint2d_valid", "joint3d_valid", "joint3d_root_relative_valid", + "translation_valid", "mano_pose_valid", "shape_valid", + "vertices_valid", "reprojection_valid", +) + + +def sha(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def training_code_hashes() -> dict[str, str]: + code_root = Path(__file__).parent + paths = [code_root / name for name in ( + "clean_train.py", "filtered_dataset.py", "coverage_sampler.py", + "export_adapter_manifests.py", "build_trainable_index.py", + )] + list((code_root / "src/foundation_hand").rglob("*.py")) + list( + (code_root / "third_party/hot3d").rglob("*.py") + ) + return {str(path.relative_to(code_root)): sha(path) for path in sorted(paths)} + + +class MixedDataset(Dataset): + def __init__(self, time: int, hw: tuple[int, int]): + manifests = MANIFESTS / f"adapter_trainable_t{time}" + self.sources = { + source: FilteredClipDataset( + source, manifests / f"{source.lower()}_t{time}.jsonl", time, + hw, ASSETS["mano_root"], Path(__file__).parent / "third_party", + {"enabled": source != "HOT3D", "probability": .8}, + ) + for source in SOURCES + } + + def __len__(self) -> int: + return sum(map(len, self.sources.values())) + + def __getitem__(self, spec: dict): + return self.sources[str(spec["source"])][spec] + + +class PositionSampler(Sampler[dict]): + def __init__(self, coverage: CoverageSampler, first: int, last: int, rank: int, world: int): + self.coverage, self.first, self.last = coverage, first, last + self.rank, self.world = rank, world + + def __iter__(self): + yield from self.coverage.shard(self.first, self.last, self.rank, self.world) + + def __len__(self): + return (self.last - self.first) // self.world + + +class Objective(nn.Module): + def __init__(self, model: BimanualReconstructionModel): + super().__init__() + self.model = model + self.criterion = BimanualLoss(LOSS) + + def forward(self, batch: dict): + prediction = self.model(batch) + losses = self.criterion(prediction, batch) + with torch.no_grad(): + losses.update(self.criterion.translation_diagnostics(prediction, batch)) + return losses + + +def model_for(stage: str) -> BimanualReconstructionModel: + options = STAGES[stage] + config = ModelConfig( + encoder="dinov3", decoder_dim=512, decoder_layers=3, attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, + depth_mode="geometry", depth_gate_mode="fixed", depth_gate_fixed_value=.5, + use_rays=True, use_bimanual_interaction=True, predict_presence=True, + require_mano=True, mano_fix_left_shapedirs=True, + modality_dropout_prob=0.0, temporal_position_mode="none", + temporal_attention_mode="bidirectional", dinov3_trainable_last_blocks=options["last2"], + translation_parameterization="direct_xyz", **ASSETS, + ) + model = BimanualReconstructionModel(config) + if stage == "S1": + with torch.no_grad(): + for head in ( + model.joint2d_head, model.rotation_head, + model.translation_head, model.shape_head, + ): + nn.init.normal_(head.weight, std=FRESH_HEAD_WEIGHT_STD) + nn.init.normal_( + model.depth_encoder.encoder[-1].weight, + std=FRESH_DEPTH_WEIGHT_STD, + ) + model.presence_head.requires_grad_(False) + if stage == "S1": + model.decoder.temporal_enabled = False + model.decoder.temporal.requires_grad_(False) + return model + + +def verify_official_dino(model: BimanualReconstructionModel) -> dict: + weight_file = Path(ASSETS["dinov3_weights"]) / "model.safetensors" + backbone = model.rgb_encoder.backbone.state_dict() + with safe_open(str(weight_file), framework="pt", device="cpu") as weights: + if set(backbone) != set(weights.keys()): + raise RuntimeError("pretrained DINO tensor names differ from model backbone") + for name, value in backbone.items(): + if not torch.equal(value.cpu(), weights.get_tensor(name)): + raise RuntimeError(f"DINO differs from official weight: {name}") + return {"tensors_equal": len(backbone), "official_safetensors_sha256": sha(weight_file), + "projection_is_new": "projection.weight" not in backbone} + + +def rng_state(device: torch.device) -> dict: + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state(device)} + + +def restore_rng(state: dict, device: torch.device) -> None: + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"].cpu()) + torch.cuda.set_rng_state(state["cuda"].cpu(), device) + + +def gradient_group_norms(model: nn.Module) -> dict[str, float]: + squared: dict[str, torch.Tensor] = {} + for name, parameter in model.named_parameters(): + if parameter.grad is None: + continue + parts = name.split(".") + group = ".".join(parts[:2]) if parts[0] in ("rgb_encoder", "decoder") else parts[0] + squared[group] = squared.get(group, parameter.grad.new_zeros(())) + parameter.grad.float().square().sum() + return {name: float(value.sqrt()) for name, value in squared.items()} + + +def storage_guard(start: bool) -> None: + devices = {path.stat().st_dev for path in (ROOT, ROOT / "cache", ROOT / "checkpoints", ROOT / "logs", ROOT / "eval")} + if len(devices) != 1: + raise RuntimeError("run directories are not on the same filesystem") + free = shutil.disk_usage(ROOT).free + threshold = (300 if start else 200) * 1024**3 + if free < threshold: + raise RuntimeError(f"root disk free {free / 1024**3:.1f} GiB below stage guard") + checkpoint_bytes = sum( + path.stat().st_size for path in (ROOT / "checkpoints").rglob("*.pt") + if not any("smoke" in component for component in path.relative_to(ROOT).parts) + ) + if not start and checkpoint_bytes + 2 * 1024**3 > 40 * 1024**3: + raise RuntimeError("checkpoint budget cannot fit another full checkpoint") + + +def checkpoint( + path: Path, stage: str, update: int, model: nn.Module, + optimizer: torch.optim.Optimizer, counts: Counter, supervision_counts: Counter, + device: torch.device, + rank: int, world: int, code_hashes: dict, data_hashes: dict, smoke: bool, + grad_clip: float, +) -> None: + local_rng = rng_state(device) + all_rng = [None] * world if rank == 0 else None + if world > 1: + dist.gather_object(local_rng, all_rng, dst=0) + else: + all_rng = [local_rng] + if rank == 0: + storage_guard(False) + if path.exists() or path.with_suffix(".tmp").exists(): + raise FileExistsError(f"checkpoint path is occupied: {path}") + state = { + "model": model.state_dict(), "optimizer": optimizer.state_dict(), + "stage": stage, "update": update, "world_size": world, + "next_global_sample_position": STAGES[stage]["offset"] + update * 6, + "index_sha256": sha(INDEX), "code_sha256": code_hashes, + "data_sha256": data_hashes, + "rank_rng_states": all_rng, "exposures": dict(counts), + "supervision_exposures": dict(supervision_counts), + "scheduler": {"stage_local_update": update, "total_updates": STAGES[stage]["updates"]}, + "complete_backbone": True, + "smoke": smoke, + "grad_clip": grad_clip, + } + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + temporary.replace(path) + loaded = torch.load(path, map_location="cpu", weights_only=False) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("checkpoint load-back failed") + print(f"checkpoint {path} sha256={sha(path)}", flush=True) + if world > 1: + dist.barrier(device_ids=[device.index]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--stage", choices=tuple(STAGES), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, required=True, help="Stage-local endpoint") + parser.add_argument("--workers", type=int, default=2) + parser.add_argument("--resume", type=Path) + parser.add_argument("--parent", type=Path) + parser.add_argument("--save", action="store_true") + parser.add_argument("--smoke", action="store_true", + help="Allow an incomplete prior-stage checkpoint for isolated preflight only") + parser.add_argument("--grad-clip", type=float, default=100.0) + args = parser.parse_args() + stage = args.stage + options = STAGES[stage] + if not 0 < args.updates <= options["updates"]: + raise ValueError("updates outside registered stage budget") + if not math.isfinite(args.grad_clip) or args.grad_clip <= 0: + raise ValueError("grad clip threshold must be finite and positive") + if not args.resume and (stage == "S1") == bool(args.parent): + raise ValueError("S1 requires no parent; S2/S3/S4 require a complete prior-stage parent") + if args.resume and args.parent: + raise ValueError("resume and stage parent are mutually exclusive") + rank = int(os.environ.get("RANK", 0)) + world = int(os.environ.get("WORLD_SIZE", 1)) + local_rank = int(os.environ.get("LOCAL_RANK", 0)) + if world not in (1, 2, 3, 6) or 6 % world: + raise ValueError("world size must divide global batch 6") + accumulation = 6 // world + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.cuda.set_device(local_rank) + device = torch.device("cuda", local_rank) + if world > 1: + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + storage_guard(True) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh run output already contains training metrics") + if world > 1: + dist.barrier(device_ids=[local_rank]) + code_hashes = training_code_hashes() + selected_manifests = MANIFESTS / f"adapter_trainable_t{options['time']}" + data_hashes = {name: sha(selected_manifests / f"{name.lower()}_t{options['time']}.jsonl") + for name in SOURCES} + if sha(INDEX) != EXPECTED_INDEX_SHA256 or data_hashes != EXPECTED_MANIFEST_SHA256[options["time"]]: + raise RuntimeError("frozen filtered index or native adapter manifest changed") + seed = 20260925 + rank + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed(seed) + model = model_for(stage) + dino_audit = verify_official_dino(model) if rank == 0 and stage == "S1" else None + model = model.to(device) + start = 0 + counts: Counter = Counter() + supervision_counts: Counter = Counter() + previous = args.resume or args.parent + state = None + if previous: + state = torch.load(previous, map_location="cpu", weights_only=False) + if not state.get("complete_backbone") or state["index_sha256"] != sha(INDEX): + raise RuntimeError("parent/resume checkpoint lacks full DINO or filtered-index identity") + if args.resume: + if (state["stage"] != stage or state["world_size"] != world + or state["code_sha256"] != code_hashes or state["data_sha256"] != data_hashes): + raise RuntimeError("exact resume contract mismatch") + if bool(state.get("smoke", False)) != args.smoke: + raise RuntimeError("smoke and formal checkpoints cannot be interchanged") + if float(state.get("grad_clip", 10.0)) != args.grad_clip: + raise RuntimeError("resume changed the gradient clipping threshold") + start = int(state["update"]) + counts.update(state["exposures"]) + supervision_counts.update(state["supervision_exposures"]) + else: + previous_stage = {"S2": "S1", "S3": "S2", "S4": "S3"}[stage] + if state["stage"] != previous_stage: + raise RuntimeError("stage parent is not the immediately preceding stage") + if not args.smoke and ( + state["update"] != STAGES[previous_stage]["updates"] + or state.get("smoke", False) + ): + raise RuntimeError("formal training requires a complete non-smoke prior stage") + if not args.smoke and state["code_sha256"] != code_hashes: + raise RuntimeError("formal stage parent was built with different training code") + if not args.smoke and STAGES[previous_stage]["time"] == options["time"]: + if state["data_sha256"] != data_hashes: + raise RuntimeError("T8 adapter manifests changed across formal stages") + model.load_state_dict(state["model"], strict=True) + model.train() + params = [parameter for parameter in model.parameters() if parameter.requires_grad] + backbone_lr = 5e-7 if stage == "S4" else None + optimizer = torch.optim.AdamW( + optimizer_parameter_groups(model, learning_rate=options["max_lr"], + backbone_learning_rate=backbone_lr), weight_decay=.05, + ) + if args.resume: + optimizer.load_state_dict(state["optimizer"]) + restore_rng(state["rank_rng_states"][rank], device) + del state + if not start < args.updates: + raise ValueError("resume checkpoint is already at or beyond requested endpoint") + dataset = MixedDataset(options["time"], options["hw"]) + coverage = CoverageSampler(INDEX, options["coverage"]) + first = options["offset"] + start * 6 + last = options["offset"] + args.updates * 6 + sampler = PositionSampler(coverage, first, last, rank, world) + loader = DataLoader(dataset, batch_size=1, sampler=sampler, + num_workers=args.workers, collate_fn=collate_h2o_clips, + pin_memory=True, persistent_workers=args.workers > 0, + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + objective = Objective(model).to(device) + if world > 1: + objective = DDP(objective, device_ids=[local_rank], output_device=local_rank, + broadcast_buffers=False, find_unused_parameters=True) + if rank == 0: + log = (args.output / "metrics.jsonl").open("a", buffering=1) + if dino_audit: + print(json.dumps({"official_dino_audit": dino_audit}), flush=True) + start_clock = time.monotonic() + torch.cuda.reset_peak_memory_stats(device) + for update in range(start, args.updates): + lr = warmup_cosine_learning_rate(update, options["updates"], + options["max_lr"], options["min_lr"], 1000) + set_scheduled_learning_rate(optimizer, lr) + optimizer.zero_grad(set_to_none=True) + losses_total = torch.zeros((), device=device) + local_modes = Counter() + local_supervision = Counter() + detailed = update < 10 or (update + 1) % 100 == 0 or update + 1 == args.updates + local_details: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + for micro in range(accumulation): + cpu = next(iterator) + source_name = cpu["sampling_source_id"][0] + local_modes[f"{source_name}:{cpu['input_mode'][0]}"] += 1 + batch = move_to_device(cpu, device) + mode_key = f"{source_name}:{cpu['input_mode'][0]}" + for name in MASK_FIELDS: + if name in cpu: + for side in range(2): + local_supervision[f"{mode_key}:{side}:{name}"] += int( + cpu[name][:, :, side].sum() + ) + attach_gt_vertices(batch, model) + sync = objective.no_sync() if world > 1 and micro + 1 < accumulation else nullcontext() + with sync, torch.autocast("cuda", dtype=torch.bfloat16): + losses = objective(batch) + if not torch.isfinite(losses["total"]): + raise RuntimeError(f"nonfinite loss at {stage} update {update}") + (losses["total"] / accumulation).backward() + losses_total += losses["total"].detach() / accumulation + if detailed: + detail = local_details[mode_key] + detail["samples"] += 1 + detail["loss_sums"].update({name: float(losses[name].detach()) + for name in MONITORED_LOSSES + TRANSLATION_DIAGNOSTICS}) + detail["valid_elements"].update({name: int(cpu[name].sum()) + for name in MASK_FIELDS if name in cpu}) + grad_groups = gradient_group_norms(model) if detailed and rank == 0 else None + grad_norm = torch.nn.utils.clip_grad_norm_(params, args.grad_clip) + if not torch.isfinite(grad_norm): + raise RuntimeError(f"nonfinite gradient norm at {stage} update {update}") + norm_min, norm_max = grad_norm.detach().clone(), grad_norm.detach().clone() + if world > 1: + dist.all_reduce(norm_min, op=dist.ReduceOp.MIN) + dist.all_reduce(norm_max, op=dist.ReduceOp.MAX) + optimizer.step() + if world > 1: + dist.all_reduce(losses_total) + gathered = [None] * world + dist.all_gather_object(gathered, { + "modes": dict(local_modes), "supervision": dict(local_supervision), + "details": dict(local_details) if detailed else {}, + }) + else: + gathered = [{"modes": dict(local_modes), + "supervision": dict(local_supervision), + "details": dict(local_details) if detailed else {}}] + for value in gathered: + counts.update(value["modes"]) + supervision_counts.update(value["supervision"]) + if rank == 0: + row = {"stage": stage, "update": update + 1, + "loss": float(losses_total / world), + "grad_norm_min": float(norm_min), "grad_norm_max": float(norm_max), + "clipped": float(norm_max) > args.grad_clip, + "grad_clip_threshold": args.grad_clip, "lr": lr, + "exposures": dict(counts)} + if detailed: + source_sums: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + mode_sums: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + for value in gathered: + for source_mode, detail in value["details"].items(): + source_name = source_mode.split(":", 1)[0] + for target in (source_sums[source_name], mode_sums[source_mode]): + target["samples"] += detail["samples"] + target["loss_sums"].update(detail["loss_sums"]) + target["valid_elements"].update(detail["valid_elements"]) + row["loss_terms"] = { + name: sum(detail["loss_sums"][name] for detail in source_sums.values()) / 6 + for name in MONITORED_LOSSES + } + row["source_loss_terms"] = { + source_name: {name: detail["loss_sums"][name] / detail["samples"] + for name in MONITORED_LOSSES} + for source_name, detail in source_sums.items() + } + row["source_valid_elements"] = { + source_name: dict(detail["valid_elements"]) + for source_name, detail in source_sums.items() + } + row["source_mode_loss_terms"] = { + source_mode: {name: detail["loss_sums"][name] / detail["samples"] + for name in MONITORED_LOSSES} + for source_mode, detail in mode_sums.items() + } + row["source_mode_translation_axes"] = { + source_mode: {name: detail["loss_sums"][name] / detail["samples"] + for name in TRANSLATION_DIAGNOSTICS} + for source_mode, detail in mode_sums.items() + } + row["source_mode_valid_elements"] = { + source_mode: dict(detail["valid_elements"]) + for source_mode, detail in mode_sums.items() + } + row["supervision_exposures"] = dict(supervision_counts) + row["grad_parameter_groups"] = grad_groups + log.write(json.dumps(row) + "\n") + if args.updates <= 10 or (update + 1) % 500 == 0 or update + 1 == args.updates: + print(json.dumps(row), flush=True) + milestone = update + 1 + registered = options["updates"] + if milestone < args.updates and ( + milestone % 10000 == 0 or milestone in { + round(registered * .25), round(registered * .50), round(registered * .75), + } + ): + checkpoint(args.output / f"{stage.lower()}_update_{milestone:07d}.pt", + stage, milestone, model, optimizer, counts, supervision_counts, + device, rank, world, code_hashes, data_hashes, + args.smoke, args.grad_clip) + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start_clock + elapsed_max = torch.tensor(elapsed, device=device) + peak_memory = torch.tensor(torch.cuda.max_memory_allocated(device) / 1024**3, device=device) + if world > 1: + dist.all_reduce(elapsed_max, op=dist.ReduceOp.MAX) + dist.all_reduce(peak_memory, op=dist.ReduceOp.MAX) + if rank == 0: + log.close() + print(json.dumps({"stage": stage, "elapsed_seconds_max": float(elapsed_max), + "clips_per_second": (args.updates - start) * 6 / float(elapsed_max), + "peak_allocated_gib_per_rank_max": float(peak_memory)}), flush=True) + if args.save: + path = args.output / f"{stage.lower()}_update_{args.updates:07d}.pt" + checkpoint(path, stage, args.updates, model, optimizer, counts, + supervision_counts, + device, rank, world, code_hashes, data_hashes, + args.smoke, args.grad_clip) + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/compare_checkpoints.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/compare_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7c8dbf5e02277d9cf98379adc69bf013f7f9ed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/compare_checkpoints.py @@ -0,0 +1,62 @@ +"""Compare continuous and resumed training checkpoints tensor by tensor.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + + +def compare(left: Path, right: Path) -> dict: + a = torch.load(left, map_location="cpu", weights_only=False) + b = torch.load(right, map_location="cpu", weights_only=False) + if (a["stage"], a["update"], a["next_global_sample_position"], a["exposures"], + a.get("supervision_exposures"), a.get("grad_clip")) != ( + b["stage"], b["update"], b["next_global_sample_position"], b["exposures"], + b.get("supervision_exposures"), b.get("grad_clip") + ): + raise AssertionError("stage/update/sampler cursor/exposures/optimizer contract differ") + model_differences = [] + if set(a["model"]) != set(b["model"]): + raise AssertionError("model tensor key sets differ") + for key in a["model"]: + if not torch.equal(a["model"][key], b["model"][key]): + model_differences.append(key) + if a["optimizer"]["param_groups"] != b["optimizer"]["param_groups"]: + raise AssertionError("optimizer parameter groups differ") + optimizer_differences = [] + left_states, right_states = a["optimizer"]["state"], b["optimizer"]["state"] + if set(left_states) != set(right_states): + raise AssertionError("optimizer state parameter IDs differ") + for parameter in left_states: + if set(left_states[parameter]) != set(right_states[parameter]): + raise AssertionError(f"optimizer state fields differ for parameter {parameter}") + for key, value in left_states[parameter].items(): + other = right_states[parameter][key] + equal = torch.equal(value, other) if torch.is_tensor(value) else value == other + if not equal: + optimizer_differences.append(f"{parameter}:{key}") + result = {"status": "pass" if not model_differences and not optimizer_differences else "fail", + "model_tensors": len(a["model"]), "model_differences": model_differences[:10], + "optimizer_states": len(left_states), + "optimizer_differences": optimizer_differences[:10], + "stage": a["stage"], "update": a["update"], + "next_global_sample_position": a["next_global_sample_position"]} + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("left", type=Path) + parser.add_argument("right", type=Path) + args = parser.parse_args() + result = compare(args.left, args.right) + print(json.dumps(result, indent=2)) + if result["status"] != "pass": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/coverage_sampler.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/coverage_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..2c00edc8e430b4c5421cb1491b0db472633be9fd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/coverage_sampler.py @@ -0,0 +1,116 @@ +"""Stateless source quotas and source-local no-replacement GT tile coverage.""" + +from __future__ import annotations + +from collections import defaultdict +import hashlib +import random +import sqlite3 +from pathlib import Path + + +SOURCES = ("H2O", "ARCTIC", "HOT3D") +QUOTAS = {"S1_S3": (8, 7, 5), "S4": (7, 5, 8)} +RECORDING_BLOCK_TILES = 64 + + +def _seed(*values: object) -> int: + encoded = "|".join(map(str, values)).encode("utf-8") + return int.from_bytes(hashlib.blake2b(encoded, digest_size=8).digest(), "little") + + +class CoverageSampler: + """A global sample position determines one immutable tile and input mode. + + S2 and S3 share S1_S3 positions 0..799999. S4 uses a new independent + position space, seed, and coverage ledger. DDP rank r reads positions + start+r, start+r+world_size, etc.; resume needs only the next global + position and the frozen index/code hashes. + """ + + def __init__(self, index: str | Path, stage: str, seed: int = 20260925): + if stage not in QUOTAS: + raise ValueError(f"unknown coverage stage {stage}") + self.stage = stage + self.seed = int(seed) + self.quota = QUOTAS[stage] + self.by_recording: dict[str, dict[str, list[str]]] = { + name: defaultdict(list) for name in SOURCES + } + with sqlite3.connect(index) as connection: + rows = connection.execute( + "SELECT source, recording_id, tile_id FROM tiles " + "ORDER BY source, recording_id, tile_id" + ) + for source, recording, tile_id in rows: + self.by_recording[source][recording].append(tile_id) + self.sizes = { + source: sum(map(len, self.by_recording[source].values())) + for source in SOURCES + } + if min(self.sizes.values()) <= 0: + raise ValueError("each source must contain at least one tile") + self._permutation_cache: dict[tuple[str, int], list[str]] = {} + self._cycle_cache: tuple[int, list[str]] | None = None + + def source_and_ordinal(self, position: int) -> tuple[str, int]: + if position < 0: + raise ValueError("negative sample position") + cycle, within = divmod(position, sum(self.quota)) + if self._cycle_cache is None or self._cycle_cache[0] != cycle: + order = [source for source, count in zip(SOURCES, self.quota) for _ in range(count)] + random.Random(_seed(self.seed, self.stage, "source", cycle)).shuffle(order) + self._cycle_cache = (cycle, order) + else: + order = self._cycle_cache[1] + source = order[within] + source_index = SOURCES.index(source) + ordinal = cycle * self.quota[source_index] + order[:within].count(source) + return source, ordinal + + def _epoch_order(self, source: str, epoch: int) -> list[str]: + key = (source, epoch) + if key in self._permutation_cache: + return self._permutation_cache[key] + randomizer = random.Random(_seed(self.seed, self.stage, source, epoch)) + recordings = list(self.by_recording[source]) + randomizer.shuffle(recordings) + groups = [] + for recording in recordings: + group = self.by_recording[source][recording].copy() + randomizer.shuffle(group) + groups.append(group) + result: list[str] = [] + depth = 0 + while len(result) < self.sizes[source]: + for group in groups: + result.extend(group[depth:depth + RECORDING_BLOCK_TILES]) + depth += RECORDING_BLOCK_TILES + if len(result) != len(set(result)): + raise AssertionError(f"duplicate tile in {source} epoch {epoch}") + for old_key in list(self._permutation_cache): + if old_key[0] == source and old_key[1] < epoch - 1: + del self._permutation_cache[old_key] + self._permutation_cache[key] = result + return result + + def sample(self, position: int) -> dict[str, object]: + source, ordinal = self.source_and_ordinal(position) + epoch, offset = divmod(ordinal, self.sizes[source]) + tile_id = self._epoch_order(source, epoch)[offset] + mode_rng = random.Random(_seed(self.seed, self.stage, "mode", position)) + K_drop = {"H2O": .20, "ARCTIC": .50, "HOT3D": .30}[source] + K_available = mode_rng.random() >= K_drop + depth_available = source == "H2O" and K_available and mode_rng.random() >= .125 + mode = "rgb_depth_k" if depth_available else "rgb_k" if K_available else "rgb" + return { + "position": position, "source": source, "source_ordinal": ordinal, + "epoch": epoch, "tile_id": tile_id, "mode": mode, + } + + def shard(self, start: int, stop: int, rank: int, world_size: int): + if not 0 <= start <= stop or not 0 <= rank < world_size: + raise ValueError("invalid range or rank") + first = start + (rank - start) % world_size + for position in range(first, stop, world_size): + yield self.sample(position) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_formal_loss_spikes.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_formal_loss_spikes.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f7417d5a9744b021aee827ed7f0b8e0e7bc4c2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_formal_loss_spikes.py @@ -0,0 +1,85 @@ +"""Replay selected S1 sample positions with a fixed checkpoint for loss diagnosis.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for +from coverage_sampler import CoverageSampler +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def run(checkpoint: Path, updates: list[int]) -> dict: + state = torch.load(checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S1" or state.get("smoke"): + raise ValueError("diagnostic requires a formal S1 checkpoint") + torch.set_num_threads(2) + device = torch.device("cuda", 0) + model = model_for("S1") + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + criterion = BimanualLoss(LOSS) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + sampler = CoverageSampler(INDEX, "S1_S3") + results = [] + with torch.inference_mode(): + for update in updates: + for position in range((update - 1) * 6, update * 6): + spec = sampler.sample(position) + cpu = collate_h2o_clips([dataset[spec]]) + batch = move_to_device(cpu, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + joint_valid = batch["joint3d_valid"].bool() + reproj_valid = batch["reprojection_valid"].bool() + gt_z = batch["joint3d_camera"][..., 2][joint_valid] + pred_z = prediction["joints_camera"][..., 2][joint_valid] + gt_2d = batch["joint2d"][reproj_valid] + item = { + "update": update, + "position": position, + "source": spec["source"], + "mode": spec["mode"], + "tile_id": spec["tile_id"], + "loss": float(losses["total"]), + "terms": {name: float(value) for name, value in losses.items() + if name != "total" and float(value) != 0}, + "valid_joint_elements": int(joint_valid.sum()), + "valid_reprojection_elements": int(reproj_valid.sum()), + "gt_z_min_max_m": [float(gt_z.min()), float(gt_z.max())] if gt_z.numel() else None, + "pred_z_min_max_m": [float(pred_z.min()), float(pred_z.max())] if pred_z.numel() else None, + "gt_2d_min_max_px": [float(gt_2d.min()), float(gt_2d.max())] + if gt_2d.numel() else None, + "focal_px": [float(batch["K"][0, 0, 0, 0]), float(batch["K"][0, 0, 1, 1])], + } + results.append(item) + return {"checkpoint": str(checkpoint), "checkpoint_update": state["update"], + "sample_count": len(results), "samples": results} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--updates", type=int, nargs="+", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + report = run(args.checkpoint, args.updates) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({"output": str(args.output), "sample_count": report["sample_count"], + "top_losses": sorted(((row["loss"], row["position"], row["source"]) + for row in report["samples"]), reverse=True)[:10]})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_gradient_outliers.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_gradient_outliers.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3f55b373393f1666b75068fe2a9f00adb5a5d0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_gradient_outliers.py @@ -0,0 +1,83 @@ +"""Read-only per-tile gradient probe for registered S2 sample positions.""" + +from __future__ import annotations + +import argparse +import json +import math + +import torch + +from clean_train import ( + INDEX, LOSS, MixedDataset, attach_gt_vertices, collate_h2o_clips, + gradient_group_norms, model_for, move_to_device, +) +from coverage_sampler import CoverageSampler +from foundation_hand.training.losses import BimanualLoss + + +def minimum(values: torch.Tensor, mask: torch.Tensor) -> float | None: + selected = values.detach()[mask] + return float(selected.min()) if selected.numel() else None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--steps", type=int, nargs="+", required=True) + args = parser.parse_args() + + torch.set_num_threads(2) + device = torch.device("cuda:0") + model = model_for("S2").to(device) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S2" or not state["complete_backbone"]: + raise ValueError("expected a full S2 checkpoint") + model.load_state_dict(state["model"], strict=True) + del state + model.train() + criterion = BimanualLoss(LOSS).to(device) + sampler = CoverageSampler(INDEX, "S1_S3") + dataset = MixedDataset(8, (368, 640)) + + for step in args.steps: + if step < 1: + raise ValueError("steps are 1-based") + for rank in range(6): + spec = sampler.sample((step - 1) * 6 + rank) + cpu = collate_h2o_clips([dataset[spec]]) + batch = move_to_device(cpu, device) + attach_gt_vertices(batch, model) + model.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + losses["total"].backward() + groups = gradient_group_norms(model) + + z = prediction["joints_camera"][..., 2].detach() + valid = batch["reprojection_valid"].bool() & (z > 0) + rotation = prediction["mano_rotations_6d"].detach().float() + first = torch.nn.functional.normalize(rotation[..., :3], dim=-1) + second = rotation[..., 3:] + residual = second - (first * second).sum(dim=-1, keepdim=True) * first + report = { + "step": step, + "rank": rank, + "source": spec["source"], + "tile_id": spec["tile_id"], + "mode": spec["mode"], + "loss": float(losses["total"].detach()), + "reprojection_loss": float(losses["reprojection"].detach()), + "grad_norm": math.sqrt(sum(value * value for value in groups.values())), + "grad_groups_top": sorted(groups.items(), key=lambda item: -item[1])[:5], + "min_positive_valid_joint_z_m": minimum(z, valid), + "positive_valid_joint_z_below_1cm": int((valid & (z < .01)).sum()), + "min_rotation_first_norm": float(rotation[..., :3].norm(dim=-1).min()), + "min_rotation_orthogonal_residual_norm": float(residual.norm(dim=-1).min()), + } + print(json.dumps(report), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_initial_gradients.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_initial_gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..4e08e92d1aae8e056f4bd01f0229a09efa660043 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_initial_gradients.py @@ -0,0 +1,90 @@ +"""Measure each weighted loss contribution to the clean-start gradient.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for, sha +from coverage_sampler import CoverageSampler, SOURCES +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def grad_norms(model) -> dict[str, float]: + sums: dict[str, torch.Tensor] = {} + for name, parameter in model.named_parameters(): + if parameter.grad is None: + continue + parts = name.split(".") + group = ".".join(parts[:2]) if parts[0] in ("rgb_encoder", "decoder") else parts[0] + sums[group] = sums.get(group, parameter.grad.new_zeros(())) + parameter.grad.float().square().sum() + return {name: float(value.sqrt()) for name, value in sums.items()} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S1" or state["index_sha256"] != sha(INDEX): + raise ValueError("expected complete S1 checkpoint on trainable index") + torch.cuda.set_device(0) + model = model_for("S1").cuda().train() + model.load_state_dict(state["model"], strict=True) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + sampler = CoverageSampler(INDEX, "S1_S3") + specs = {} + for position in range(200): + spec = sampler.sample(position) + specs.setdefault(spec["source"], spec) + if len(specs) == len(SOURCES): + break + criterion = BimanualLoss(LOSS) + report = {"checkpoint_sha256": sha(args.checkpoint), "samples": {}} + for source, spec in specs.items(): + sample = dataset[spec] + batch = move_to_device(collate_h2o_clips([sample]), torch.device("cuda", 0)) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + losses = criterion(model(batch), batch) + components = {} + for name, value in losses.items(): + if name == "total" or float(value.detach()) == 0.0: + continue + model.zero_grad(set_to_none=True) + value.backward(retain_graph=True) + groups = grad_norms(model) + components[name] = {"weighted_loss": float(value.detach()), + "global_grad_norm": sum(x * x for x in groups.values()) ** .5, + "groups": groups} + model.zero_grad(set_to_none=True) + losses["total"].backward() + groups = grad_norms(model) + report["samples"][source] = { + "tile_id": spec["tile_id"], "mode": spec["mode"], + "total_loss": float(losses["total"].detach()), + "total_grad_norm": sum(x * x for x in groups.values()) ** .5, + "total_groups": groups, "components": components, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({source: { + "total_grad_norm": row["total_grad_norm"], + "largest_components": sorted( + ((name, entry["global_grad_norm"]) for name, entry in row["components"].items()), + key=lambda pair: pair[1], reverse=True, + )[:6], + "total_groups": row["total_groups"], + } for source, row in report["samples"].items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_s1_s2_temporal_transition.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_s1_s2_temporal_transition.py new file mode 100644 index 0000000000000000000000000000000000000000..50fa8bf7a8f13085a4801d5b3286bc098be2ac1a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/diagnose_s1_s2_temporal_transition.py @@ -0,0 +1,85 @@ +"""Measure the temporal block's effect on a frozen staged model.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from clean_train import ROOT, model_for, sha +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--limit", type=int, default=32) + args = parser.parse_args() + if args.limit <= 0 or (args.source != "H2O" and args.mode == "rgb_depth_k"): + raise ValueError("invalid evaluation condition or limit") + + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + manifest = panels / f"{args.source.lower()}_development_t8.jsonl" + if sha(manifest) != panel_report["sources"][args.source]["development"]["manifest_sha256"]: + raise RuntimeError("frozen development panel changed") + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if (state["stage"] not in ("S1", "S2") or state["update"] < 2000 + or state.get("smoke") or not state.get("complete_backbone")): + raise RuntimeError("requires a complete formal S1/S2 checkpoint") + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + dataset = dataset_for(args.source, manifest) + limit = min(args.limit, len(dataset)) + rows = {False: [], True: []} + with torch.inference_mode(): + for index in range(limit): + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + for temporal_enabled in (False, True): + model.decoder.temporal_enabled = temporal_enabled + with torch.autocast(device.type, dtype=torch.bfloat16, + enabled=device.type == "cuda"): + prediction = model(batch) + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows[temporal_enabled].append( + make_row(prediction, batch, 0, frame, side) + ) + + summaries = {condition: aggregate(values) for condition, values in rows.items()} + counts_match = all( + summaries[False][metric]["count"] == summaries[True][metric]["count"] + for metric in FOUR_METRICS + ) + if not counts_match: + raise RuntimeError("temporal toggle changed metric denominators") + report = { + "checkpoint_sha256": sha(args.checkpoint), + "checkpoint_stage": state["stage"], "checkpoint_update": state["update"], + "source": args.source, "mode": args.mode, "clips": limit, + "temporal_off": {metric: summaries[False][metric] for metric in FOUR_METRICS}, + "temporal_on": {metric: summaries[True][metric] for metric in FOUR_METRICS}, + "temporal_on_minus_off": { + metric: summaries[True][metric]["mean"] - summaries[False][metric]["mean"] + for metric in FOUR_METRICS + }, + } + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/eval_stratified_probe.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/eval_stratified_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..12e100450b2927f5f87f73686250de0a6ef0a932 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/eval_stratified_probe.py @@ -0,0 +1,195 @@ +"""Evaluate fixed, recording-spread development clips without checkpoint selection.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +import math +from pathlib import Path + +import torch + +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from clean_train import INDEX, ROOT, model_for, sha, training_code_hashes +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def choose_indices(manifest: Path, limit: int) -> tuple[list[int], int]: + groups: dict[str, list[int]] = defaultdict(list) + with manifest.open() as stream: + for index, line in enumerate(stream): + row = json.loads(line) + group = row.get("take", row.get("group_key")) + if not group: + raise ValueError(f"manifest row {index} has no recording group") + groups[str(group)].append(index) + if limit < len(groups): + raise ValueError("limit must include at least one clip per recording group") + + ordered: dict[str, list[int]] = {} + for group, indices in groups.items(): + size = len(indices) + priorities = [size // 2, size // 4, 3 * size // 4, 0, size - 1] + offsets = list(dict.fromkeys(priorities + list(range(size)))) + ordered[group] = [indices[offset] for offset in offsets] + + selected: list[int] = [] + for depth in range(max(map(len, ordered.values()))): + for group in sorted(ordered): + if depth < len(ordered[group]): + selected.append(ordered[group][depth]) + if len(selected) == limit: + return selected, len(groups) + raise ValueError("limit exceeds manifest length") + + +def paired_group_deltas(reference: list[dict], candidate: list[dict], field: str) -> dict: + if len(reference) != len(candidate): + raise RuntimeError("paired evaluations have different row counts") + groups: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for first, second in zip(reference, candidate): + if first[field] != second[field]: + raise RuntimeError(f"paired {field} identities differ") + for name in FOUR_METRICS: + first_value, second_value = float(first[name]), float(second[name]) + if math.isfinite(first_value) != math.isfinite(second_value): + raise RuntimeError(f"paired {name} validity differs for {field}={first[field]}") + if math.isfinite(first_value): + groups[str(first[field])][name].append(second_value - first_value) + return { + group: { + name: {"count": len(values), "mean_delta": sum(values) / len(values)} + for name, values in metrics.items() + } + for group, metrics in sorted(groups.items()) + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--compare-checkpoint", type=Path) + parser.add_argument("--reference-temporal-off", action="store_true") + parser.add_argument("--compare-temporal-off", action="store_true") + parser.add_argument("--paired-groups", action="store_true") + parser.add_argument("--hybrid-parent-root", action="store_true") + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--limit", type=int, default=32) + args = parser.parse_args() + if args.source != "H2O" and args.mode == "rgb_depth_k": + raise ValueError("only H2O has real metric depth") + if args.compare_temporal_off and not args.compare_checkpoint: + raise ValueError("--compare-temporal-off requires --compare-checkpoint") + if args.paired_groups and not args.compare_checkpoint: + raise ValueError("--paired-groups requires --compare-checkpoint") + if args.hybrid_parent_root and not args.compare_checkpoint: + raise ValueError("--hybrid-parent-root requires --compare-checkpoint") + + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + manifest = panels / f"{args.source.lower()}_development_t8.jsonl" + expected = panel_report["sources"][args.source]["development"]["manifest_sha256"] + if sha(manifest) != expected: + raise RuntimeError("frozen development panel changed") + dataset = dataset_for(args.source, manifest) + indices, groups = choose_indices(manifest, args.limit) + if len(dataset) != sum(1 for _ in manifest.open()): + raise RuntimeError("dataset indices differ from frozen manifest rows") + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + checkpoints = [args.checkpoint] + if args.compare_checkpoint: + checkpoints.append(args.compare_checkpoint) + models = [] + identities = [] + for model_index, path in enumerate(checkpoints): + state = torch.load(path, map_location="cpu", weights_only=False) + if (state.get("smoke") or not state.get("complete_backbone") + or state["index_sha256"] != sha(INDEX) + or state["code_sha256"] != training_code_hashes()): + raise RuntimeError(f"checkpoint is not a complete matching formal state: {path}") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + if ((model_index == 0 and args.reference_temporal_off) + or (model_index == 1 and args.compare_temporal_off)): + model.decoder.temporal_enabled = False + models.append(model.to(device).eval()) + identities.append({ + "checkpoint_sha256": sha(path), "stage": state["stage"], + "update": state["update"], + "temporal_enabled": bool(model.decoder.temporal_enabled), + }) + if args.hybrid_parent_root: + identities.append({ + **identities[1], "variant": "compare_local_reference_root", + "root_checkpoint_sha256": identities[0]["checkpoint_sha256"], + }) + rows = [[] for _ in identities] + with torch.inference_mode(): + for index in indices: + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, models[0]) + predictions = [] + for model in models: + with torch.autocast(device.type, dtype=torch.bfloat16, + enabled=device.type == "cuda"): + predictions.append(model(batch)) + if args.hybrid_parent_root: + parent, candidate = predictions + delta = parent["wrist_root_translation"] - candidate["wrist_root_translation"] + hybrid = dict(candidate) + hybrid["wrist_root_translation"] = parent["wrist_root_translation"] + hybrid["joints_camera"] = candidate["joints_camera"] + delta.unsqueeze(-2) + hybrid["vertices_camera"] = candidate["vertices_camera"] + delta.unsqueeze(-2) + predictions.append(hybrid) + for model_index, prediction in enumerate(predictions): + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows[model_index].append( + make_row(prediction, batch, 0, frame, side) + ) + summaries = [aggregate(values) for values in rows] + if any(summary[name]["count"] == 0 for summary in summaries for name in FOUR_METRICS): + raise RuntimeError("stratified probe has an empty metric denominator") + if len(summaries) >= 2 and any( + summaries[0][name]["count"] != summary[name]["count"] + for summary in summaries[1:] for name in FOUR_METRICS + ): + raise RuntimeError("paired checkpoints have different metric denominators") + if args.hybrid_parent_root: + paired_group_deltas(rows[0], rows[2], "physical_recording_id") + print(json.dumps({ + "source": args.source, "mode": args.mode, + "panel_sha256": expected, "selection": "recording_round_robin_center", + "selected_indices": indices, "recording_groups": groups, + "results": [ + {**identity, "four_metrics": {name: summary[name] for name in FOUR_METRICS}} + for identity, summary in zip(identities, summaries) + ], + "compare_minus_reference": { + name: summaries[1][name]["mean"] - summaries[0][name]["mean"] + for name in FOUR_METRICS + } if len(summaries) >= 2 else None, + "hybrid_minus_reference": { + name: summaries[2][name]["mean"] - summaries[0][name]["mean"] + for name in FOUR_METRICS + } if args.hybrid_parent_root else None, + "hybrid_minus_compare": { + name: summaries[2][name]["mean"] - summaries[1][name]["mean"] + for name in FOUR_METRICS + } if args.hybrid_parent_root else None, + "paired_groups": { + "headset": paired_group_deltas(rows[0], rows[1], "headset_id"), + "recording": paired_group_deltas(rows[0], rows[1], "physical_recording_id"), + } if args.paired_groups else None, + }, separators=(",", ":"))) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/export_adapter_manifests.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/export_adapter_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..7120aeaf9b953c4f5a4a3ad64ee3c5deaaa3d5d9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/export_adapter_manifests.py @@ -0,0 +1,94 @@ +"""Translate frozen filtered tiles to the three existing native source adapters.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sqlite3 + + +def adapter_row(window: dict, tile_id: str, start: int, frames: list[int], time: int) -> dict: + dataset = window["dataset"] + source = window["source"] + selected = frames if time == 8 else [frames[0]] + shared = { + "filtered_tile_id": tile_id, + "filtered_window_id": window["id"], + "filtered_gt_path": window["filtered_gt_path"], + "filtered_start_offset": start, + "expected_frame_ids": selected, + } + if dataset == "ARCTIC": + offset = int(source["offset"]) + subject = window["recording_id"].split("/")[0] + return { + **shared, "dataset_id": "ARCTIC", "protocol": "P2", + "split_role": "arctic_p2_train", "subject_id": subject, + "physical_recording_id": window["recording_id"], + "group_key": f"ARCTIC/{subject}/{window['recording_id']}", + "camera_id": "ego_view_0_rectified", + "frame_ids_1based": selected, + "array_indices_0based": [frame - offset for frame in selected], + "image_paths": [source["rgb_template"].format(frame=frame) for frame in selected], + "mano_path": source["mano_path"], "camera_path": source["camera_path"], + "depth_input_available": False, "official_test_used": False, + } + if dataset == "H2O": + return {**shared, "take": window["recording_id"], "frame_ids": selected} + if dataset == "HOT3D": + path = Path(window["recording_id"]) + return { + **shared, "dataset": "HOT3D", "have_hand_object_pose_gt": True, + "recording_id": window["recording_id"], "participant_id": path.name.split("_")[0], + "stream_id": window["stream_id"], "headset": source["device"], + "timestamps_ns": window["_timestamps_ns"][start:start + len(selected)], + } + raise ValueError(f"foreign source {dataset}") + + +def export(index: Path, output: Path, time: int) -> dict[str, int]: + if time not in (1, 8): + raise ValueError("only T=1 and T=8 are registered") + output.mkdir(parents=True, exist_ok=False) + counts = {name: 0 for name in ("ARCTIC", "H2O", "HOT3D")} + files = {name: (output / f"{name.lower()}_t{time}.jsonl").open("w") for name in counts} + last_window = None + window = None + try: + with sqlite3.connect(index) as connection: + cursor = connection.execute( + "SELECT t.tile_id,t.window_id,t.source,t.start_offset,t.frame_ids_json," + "w.manifest_json FROM tiles t JOIN windows w ON t.window_id=w.window_id " + "ORDER BY t.source,t.window_id,t.start_offset" + ) + for tile_id, window_id, source_name, start, frames_json, manifest_json in cursor: + if window_id != last_window: + window = json.loads(manifest_json) + if source_name == "HOT3D": + timeline = json.loads(Path(window["source"]["timestamps_path"]).read_text()) + window["_timestamps_ns"] = timeline[str(window["stream_id"])][ + int(window["start"]):int(window["end"]) + ] + last_window = window_id + assert window is not None + row = adapter_row(window, tile_id, start, json.loads(frames_json), time) + files[source_name].write(json.dumps(row, separators=(",", ":")) + "\n") + counts[source_name] += 1 + finally: + for handle in files.values(): + handle.close() + return counts + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--index", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--time", type=int, choices=(1, 8), required=True) + args = parser.parse_args() + print(json.dumps(export(args.index, args.output, args.time), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/filtered_dataset.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/filtered_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..ab36aee3e3c74559a40f03ce185464476858cd67 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/filtered_dataset.py @@ -0,0 +1,138 @@ +"""Use native source decoders while enforcing the frozen filtered-GT allowlist.""" + +from __future__ import annotations + +from functools import lru_cache +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS, corrupt_metric_depth +from foundation_hand.data.h2o_dataset import H2OCam4Dataset +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + +from coverage_sampler import _seed + + +@lru_cache(maxsize=256) +def filtered_valid(gt_path: str) -> tuple[np.ndarray, np.ndarray]: + with np.load(gt_path, allow_pickle=False) as payload: + return payload["frame_ids"].copy(), payload["valid"].astype(bool).copy() + + +MASKS = ( + "joint_element_valid", "joint_annotation_valid", "mano_annotation_valid", + "joint2d_valid", "joint3d_valid", "joint3d_root_relative_valid", + "translation_valid", "mano_pose_valid", "shape_valid", "vertices_valid", + "reprojection_valid", +) + + +def intersect_filtered_valid(sample: dict[str, Any], row: dict[str, Any]) -> None: + frame_ids, valid = filtered_valid(str(row["filtered_gt_path"])) + start = int(row["filtered_start_offset"]) + time = len(row["expected_frame_ids"]) + expected = np.asarray(row["expected_frame_ids"], dtype=np.int64) + if not np.array_equal(frame_ids[start:start + time], expected): + raise ValueError(f"filtered/native frame disagreement: {row['filtered_tile_id']}") + if sample["dataset_id"] == "HOT3D": + if not torch.equal(sample["timestamp_ns"], torch.as_tensor(row["timestamps_ns"])): + raise ValueError("HOT3D image and GT timeline disagree") + elif not torch.equal(sample["frame_id"], torch.from_numpy(expected)): + raise ValueError("image and filtered GT frame IDs disagree") + hand = torch.from_numpy(valid[start:start + time]).bool() + if hand.shape != (time, 2): + raise ValueError("filtered hand validity has wrong shape") + for key in MASKS: + if key not in sample: + continue + mask = sample[key] + if mask.shape[:2] != (time, 2) or mask.dtype != torch.bool: + raise ValueError(f"invalid native loss mask {key}: {mask.shape}") + expanded = hand + while expanded.ndim < mask.ndim: + expanded = expanded.unsqueeze(-1) + sample[key] = mask & expanded + + +class FilteredClipDataset(Dataset[dict[str, Any]]): + def __init__( + self, source: str, manifest: str | Path, time: int, target_hw: tuple[int, int], + mano_root: str | Path, hot3d_toolkit: str | Path, + photometric_augmentation: dict | None = None, + ) -> None: + self.source = source + self.rows = [json.loads(line) for line in Path(manifest).open() if line.strip()] + self.by_tile = {str(row["filtered_tile_id"]): index for index, row in enumerate(self.rows)} + if len(self.by_tile) != len(self.rows): + raise ValueError("duplicate filtered tile ID") + if source == "ARCTIC": + self.native = ARCTICClipDataset( + manifest, mano_root, target_hw, photometric_augmentation, 20260925, + hand_valid_policy="visible_mesh", + ) + elif source == "H2O": + self.native = H2OCam4Dataset( + "/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, target_hw, + clip_lengths=(time,), strides=(1,), window_step=time, + allow_partial=False, photometric_augmentation=photometric_augmentation, + augmentation_seed=20260925, + ) + elif source == "HOT3D": + self.native = HOT3DClipDataset( + "/SSD3/jiasen/foundation_hand/HOT3D/dataset", manifest, + hot3d_toolkit, mano_root, target_hw, K_input_dropout=0.0, + ) + else: + raise ValueError(f"foreign source {source}") + if len(self.native) != len(self.rows): + raise ValueError("native adapter clip count differs from filtered index") + + def __len__(self) -> int: + return len(self.rows) + + def __getitem__(self, spec: dict[str, Any]) -> dict[str, Any]: + if spec["source"] != self.source: + raise ValueError("sample source differs from native adapter") + index = self.by_tile[str(spec["tile_id"])] + row = self.rows[index] + sample = self.native[(index, int(spec["epoch"]))] + intersect_filtered_valid(sample, row) + frame = sample["frame_valid"].bool() + mode = str(spec["mode"]) + if mode not in ("rgb", "rgb_k", "rgb_depth_k"): + raise ValueError(f"foreign input mode {mode}") + if mode == "rgb_depth_k" and self.source != "H2O": + raise ValueError("only H2O supplies real metric depth") + sample["K_input_available"] = frame & (mode != "rgb") + sample["depth_input_available"] = frame & (mode == "rgb_depth_k") + sample["K_available"] = sample["K_input_available"].clone() + sample["depth_available"] = sample["depth_input_available"].clone() + condition_code = 2 if mode == "rgb_depth_k" else 1 if self.source == "H2O" else 0 + if self.source == "H2O" and mode == "rgb_depth_k": + import random + position = int(spec["position"]) + rng = random.Random(_seed(20260925, "depth", position)) + if rng.random() < .30: + corruption = DEPTH_CORRUPTIONS[rng.randrange(len(DEPTH_CORRUPTIONS))] + depth, pixel_valid = corrupt_metric_depth( + sample["depth_m"].numpy(), sample["depth_pixel_valid"].numpy(), + corruption, seed=_seed(20260925, "corruption", position), + ) + sample["depth_m"] = torch.from_numpy(depth) + sample["depth_pixel_valid"] = torch.from_numpy(pixel_valid) + condition_code = 3 + DEPTH_CORRUPTIONS.index(corruption) + sample["depth_input_condition_code"] = torch.full( + frame.shape, condition_code, dtype=torch.long, + ) + sample["sampling_source_id"] = self.source + sample["filtered_tile_id"] = row["filtered_tile_id"] + sample["input_mode"] = mode + sample["source_ordinal"] = torch.full(frame.shape, int(spec["source_ordinal"]), dtype=torch.long) + sample["coverage_epoch"] = torch.full(frame.shape, int(spec["epoch"]), dtype=torch.long) + return sample diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/freeze_eval_panels.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/freeze_eval_panels.py new file mode 100644 index 0000000000000000000000000000000000000000..d84948d25345cda0de302ae204eaacf2a742d860 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/freeze_eval_panels.py @@ -0,0 +1,139 @@ +"""Freeze recording-disjoint development and confirmation GT panels.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path + +import numpy as np + +from audit_headset_sync import MAX_DELTA_NS, deltas, trajectory +from preflight_index import digest, tile_starts, EXPECTED_MANIFEST_SHA256 + + +SOURCES = { + "ARCTIC": Path("/SSD3/jiasen/foundation_hand/phase7_artifacts/manifests/arctic_p2_v2/arctic_p2_val_t8.jsonl"), + "H2O": Path("/SSD3/jiasen/foundation_hand/H2O/extracted/label_split/pose_val.txt"), + "HOT3D": Path("/SSD3/jiasen/foundation_hand/phase7_artifacts/manifests/hot3d_gt_v1_retry2/hot3d_heldout_t8.jsonl"), +} + + +def h2o_rows(path: Path) -> list[dict]: + by_take: dict[str, set[int]] = defaultdict(set) + for line in path.open(): + item = Path(line.strip()) + if not line.strip(): + continue + take = str(item.parents[1]) + if not take.endswith("cam4"): + raise ValueError(f"foreign H2O validation view {take}") + by_take[take].add(int(item.stem)) + rows = [] + for take, values in by_take.items(): + ids = sorted(values) + start = 0 + for position in range(1, len(ids) + 1): + if position < len(ids) and ids[position] == ids[position - 1] + 1: + continue + run = ids[start:position] + if len(run) >= 8: + for offset in tile_starts(len(run)): + rows.append({"take": take, "frame_ids": run[offset:offset + 8]}) + start = position + return rows + + +def load_jsonl(path: Path) -> list[dict]: + return [json.loads(line) for line in path.open() if line.strip()] + + +def recording(source: str, row: dict) -> str: + return row["take"] if source == "H2O" else row[ + "physical_recording_id" if source == "ARCTIC" else "recording_id" + ] + + +def clip_time(source: str, row: dict) -> int: + key = "frame_ids" if source == "H2O" else "frame_ids_1based" if source == "ARCTIC" else "timestamps_ns" + return int(row[key][0]) + + +def hot3d_headset_valid(row: dict) -> bool: + path = Path("/SSD3/jiasen/foundation_hand/HOT3D/dataset") / row["recording_id"] + stamps = np.asarray(row["timestamps_ns"], dtype=np.int64) + return bool(np.all(deltas(stamps, trajectory(str(path))) <= MAX_DELTA_NS)) + + +def freeze(train_manifest: Path, output: Path, per_recording: int = 8) -> dict: + if digest(train_manifest) != EXPECTED_MANIFEST_SHA256: + raise ValueError("training manifest differs from frozen allowlist") + if output.exists(): + raise FileExistsError(output) + train_recordings: dict[str, set[str]] = defaultdict(set) + for row in load_jsonl(train_manifest): + train_recordings[row["dataset"]].add(row["recording_id"]) + rows = { + "H2O": h2o_rows(SOURCES["H2O"]), + "ARCTIC": load_jsonl(SOURCES["ARCTIC"]), + "HOT3D": load_jsonl(SOURCES["HOT3D"]), + } + hot3d_total = len(rows["HOT3D"]) + rows["HOT3D"] = [row for row in rows["HOT3D"] if hot3d_headset_valid(row)] + plan: dict[str, dict] = {} + selected: dict[tuple[str, str], list[dict]] = {} + for source, values in rows.items(): + groups: dict[str, list[dict]] = defaultdict(list) + for row in values: + groups[recording(source, row)].append(row) + if train_recordings[source] & set(groups): + raise ValueError(f"{source} validation overlaps filtered train recordings") + ranked = sorted(groups, key=lambda name: hashlib.sha256( + f"clean-gt-eval-20260925|{source}|{name}".encode(), + ).digest()) + if len(ranked) < 2: + raise ValueError(f"{source} lacks disjoint validation recordings") + boundary = len(ranked) // 2 + plan[source] = {"train_recordings": len(train_recordings[source]), + "validation_recordings": len(ranked), "train_overlap": 0, + "source_sha256": digest(SOURCES[source])} + if source == "HOT3D": + plan[source]["candidate_clips"] = hot3d_total + plan[source]["clips_rejected_headset_sync"] = hot3d_total - len(values) + plan[source]["headset_sync_threshold_ms"] = MAX_DELTA_NS / 1e6 + for role, names in (("development", ranked[:boundary]), ("confirmation", ranked[boundary:])): + chosen = [] + for name in names: + candidates = sorted(groups[name], key=lambda row: clip_time(source, row)) + indices = np.linspace(0, len(candidates) - 1, + min(per_recording, len(candidates)), dtype=int) + chosen.extend(candidates[int(index)] for index in indices) + selected[source, role] = chosen + plan[source][role] = {"recordings": len(names), "clips": len(chosen), + "recording_ids": names} + output.mkdir(parents=True) + for (source, role), values in selected.items(): + path = output / f"{source.lower()}_{role}_t8.jsonl" + with path.open("w") as stream: + for row in values: + stream.write(json.dumps(row, separators=(",", ":")) + "\n") + plan[source][role]["manifest_sha256"] = digest(path) + report = {"status": "frozen", "train_manifest_sha256": EXPECTED_MANIFEST_SHA256, + "rule": "recording-disjoint, 8 spread T8 clips per recording; confirmation unopened for selection", + "sources": plan} + (output / "panels.json").write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--train-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(freeze(args.train_manifest, args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/preflight_index.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/preflight_index.py new file mode 100644 index 0000000000000000000000000000000000000000..f5153a5cd84d39d0fd4e5779d33ab123eb1f11de --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/preflight_index.py @@ -0,0 +1,195 @@ +"""Audit the filtered GT allowlist and build a complete, immutable T=8 index. + +The index contains references only. It never copies or decodes source images. +""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +import os +from pathlib import Path +import sqlite3 + +import numpy as np + + +EXPECTED_MANIFEST_SHA256 = "b4b0ac4bc4a771c9bc7626a9eec7f5f541ef96908a9a64d219192efd7b8f7f89" +EXPECTED_WINDOWS = {"ARCTIC": 2939, "H2O": 928, "HOT3D": 18962} +EXPECTED_TILES = {"ARCTIC": 22750, "H2O": 6406, "HOT3D": 143930} + + +def digest(path: Path) -> str: + value = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(4 * 1024 * 1024), b""): + value.update(block) + return value.hexdigest() + + +def tile_starts(length: int, tile_size: int = 8) -> list[int]: + if length < tile_size: + raise ValueError(f"window has only {length} frames") + starts = list(range(0, length - tile_size + 1, tile_size)) + if starts[-1] + tile_size < length: + starts.append(length - tile_size) + covered = set().union(*(range(start, start + tile_size) for start in starts)) + if covered != set(range(length)): + raise AssertionError(f"tile coverage incomplete for length={length}") + return starts + + +def source_frame_paths(row: dict, frame_ids: np.ndarray) -> list[Path]: + source = row["source"] + if row["dataset"] == "HOT3D": + return [Path(source["root"]), Path(source["timestamps_path"])] + template = str(source["rgb_template"]) + paths = [Path(template.format(frame=int(frame_id))) for frame_id in frame_ids] + if row["dataset"] == "H2O": + root = Path(source["root"]) + paths += [root / "depth" / f"{int(frame_id):06d}.png" for frame_id in frame_ids] + paths += [root / "hand_pose" / f"{int(frame_id):06d}.txt" for frame_id in frame_ids] + paths += [root / "hand_pose_mano" / f"{int(frame_id):06d}.txt" for frame_id in frame_ids] + paths.append(root / "cam_intrinsics.txt") + elif row["dataset"] == "ARCTIC": + paths += [Path(source["mano_path"]), Path(source["camera_path"])] + return paths + + +def audit_window(row: dict, check_paths: bool) -> tuple[np.ndarray, np.ndarray, list[int]]: + if row.get("retained") is not True or row.get("filter_reason") != "retained": + raise ValueError("window is not retained") + name = row["dataset"] + if name not in EXPECTED_WINDOWS: + raise ValueError(f"foreign dataset {name}") + gt = Path(row["filtered_gt_path"]) + if not gt.is_file() or digest(gt) != row["gt_sha256"]: + raise ValueError(f"GT missing or hash mismatch: {gt}") + with np.load(gt, allow_pickle=False) as payload: + if "frame_ids" not in payload or "valid" not in payload: + raise ValueError("GT lacks frame_ids or valid") + frame_ids = payload["frame_ids"].astype(np.int64) + valid = payload["valid"].astype(bool) + if valid.shape != (len(frame_ids), 2): + raise ValueError(f"invalid hand mask shape {valid.shape}") + if name == "H2O" and "joints_native_m" not in payload: + raise ValueError("H2O lacks native joints") + length = int(row["frame_count"]) + if length != len(frame_ids) or length != int(row["end"]) - int(row["start"]): + raise ValueError("manifest/GT length disagreement") + if np.any(np.diff(frame_ids) <= 0): + raise ValueError("native frame IDs are not strictly increasing") + if name == "ARCTIC": + offset = int(row["source"]["offset"]) + if offset < 1 or not np.array_equal( + frame_ids, np.arange(int(row["start"]) + offset, int(row["end"]) + offset) + ): + raise ValueError("ARCTIC frame IDs disagree with registered sequence offset") + if name == "HOT3D": + timeline_path = Path(row["source"]["timestamps_path"]) + if not timeline_path.is_file(): + raise ValueError("HOT3D timeline is missing") + timeline = json.loads(timeline_path.read_text(encoding="utf-8")) + timestamps = timeline[str(row["stream_id"])][int(row["start"]):int(row["end"])] + if len(timestamps) != length: + raise ValueError("HOT3D timeline slice length mismatch") + if check_paths: + missing = next((str(path) for path in source_frame_paths(row, frame_ids) if not path.is_file() and not path.is_dir()), None) + if missing: + raise FileNotFoundError(missing) + return frame_ids, valid, tile_starts(length) + + +def build(manifest: Path, output: Path, check_paths: bool = True) -> dict: + if digest(manifest) != EXPECTED_MANIFEST_SHA256: + raise ValueError("filtered manifest SHA256 differs from frozen recipe") + if output.exists(): + raise FileExistsError(f"refusing to overwrite index: {output}") + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_suffix(output.suffix + ".tmp") + if temporary.exists(): + raise FileExistsError(f"unfinished index already exists: {temporary}") + connection = sqlite3.connect(temporary) + try: + connection.executescript(""" + CREATE TABLE windows ( + window_id TEXT PRIMARY KEY, source TEXT NOT NULL, + recording_id TEXT NOT NULL, stream_id TEXT, + manifest_json TEXT NOT NULL, frame_ids_json TEXT NOT NULL, + valid_left INTEGER NOT NULL, valid_right INTEGER NOT NULL + ); + CREATE TABLE tiles ( + tile_id TEXT PRIMARY KEY, window_id TEXT NOT NULL, + source TEXT NOT NULL, recording_id TEXT NOT NULL, + start_offset INTEGER NOT NULL, frame_ids_json TEXT NOT NULL, + FOREIGN KEY(window_id) REFERENCES windows(window_id) + ); + CREATE INDEX tiles_source_recording ON tiles(source, recording_id); + """) + windows: Counter[str] = Counter() + tiles: Counter[str] = Counter() + frame_entries: Counter[str] = Counter() + valid_hands: Counter[str] = Counter() + recordings: dict[str, set[str]] = {name: set() for name in EXPECTED_WINDOWS} + for line_number, line in enumerate(manifest.open(encoding="utf-8"), 1): + if not line.strip(): + continue + row = json.loads(line) + try: + frame_ids, valid, starts = audit_window(row, check_paths) + name = row["dataset"] + window_id = str(row["id"]) + recording_id = str(row["recording_id"]) + connection.execute( + "INSERT INTO windows VALUES (?,?,?,?,?,?,?,?)", + (window_id, name, recording_id, row.get("stream_id"), + json.dumps(row, separators=(",", ":")), + json.dumps(frame_ids.tolist()), int(valid[:, 0].sum()), int(valid[:, 1].sum())), + ) + for start in starts: + selected = frame_ids[start:start + 8].tolist() + connection.execute( + "INSERT INTO tiles VALUES (?,?,?,?,?,?)", + (f"{window_id}:{start}", window_id, name, recording_id, + start, json.dumps(selected)), + ) + windows[name] += 1 + tiles[name] += len(starts) + frame_entries[name] += len(frame_ids) + valid_hands[f"{name}:left"] += int(valid[:, 0].sum()) + valid_hands[f"{name}:right"] += int(valid[:, 1].sum()) + recordings[name].add(recording_id) + except Exception as error: + raise ValueError(f"manifest line {line_number}, id={row.get('id')}: {error}") from error + if dict(windows) != EXPECTED_WINDOWS or dict(tiles) != EXPECTED_TILES: + raise ValueError(f"coverage counts differ: windows={windows}, tiles={tiles}") + connection.commit() + except BaseException: + connection.close() + temporary.unlink(missing_ok=True) + raise + connection.close() + os.replace(temporary, output) + return { + "status": "pass", "manifest_sha256": EXPECTED_MANIFEST_SHA256, + "index_sha256": digest(output), "windows": dict(windows), + "tiles": dict(tiles), "frame_entries": dict(frame_entries), + "valid_hands": dict(valid_hands), + "recordings": {name: len(values) for name, values in recordings.items()}, + "source_paths_checked": check_paths, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--skip-source-paths", action="store_true") + args = parser.parse_args() + print(json.dumps(build(args.manifest, args.output, not args.skip_source_paths), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/probe_cold_start.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/probe_cold_start.py new file mode 100644 index 0000000000000000000000000000000000000000..6344fe0a91a9615173f3021e4df3437da404629e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/probe_cold_start.py @@ -0,0 +1,95 @@ +"""Compare cold-start gradient flow without changing data, loss, or LR.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch +from torch import nn + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for +from coverage_sampler import CoverageSampler, SOURCES +from diagnose_initial_gradients import grad_norms +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +VARIANTS = ( + ("zero_heads_zero_depth", 0.0, 0.0), + ("head_1e-2_zero_depth", 1e-2, 0.0), + ("head_1e-2_depth_1e-4", 1e-2, 1e-4), + ("head_5e-3_depth_1e-3", 5e-3, 1e-3), + ("head_1e-3_depth_1e-3", 1e-3, 1e-3), +) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + coverage = CoverageSampler(INDEX, "S1_S3") + specs = {} + for position in range(200): + spec = coverage.sample(position) + specs.setdefault(spec["source"], spec) + if len(specs) == len(SOURCES): + break + device = torch.device("cuda", 0) + batches = { + source: move_to_device(collate_h2o_clips([dataset[spec]]), device) + for source, spec in specs.items() + } + criterion = BimanualLoss(LOSS) + results = [] + for name, head_std, depth_std in VARIANTS: + torch.manual_seed(20260925) + model = model_for("S1") + with torch.no_grad(): + for head in ( + model.joint2d_head, model.rotation_head, + model.translation_head, model.shape_head, + ): + if head_std: + nn.init.normal_(head.weight, std=head_std) + else: + nn.init.zeros_(head.weight) + final_depth = model.depth_encoder.encoder[-1] + if depth_std: + nn.init.normal_(final_depth.weight, std=depth_std) + else: + nn.init.zeros_(final_depth.weight) + model.to(device).train() + item = {"variant": name, "head_std": head_std, "depth_std": depth_std, + "samples": {}} + for source, batch in batches.items(): + model.zero_grad(set_to_none=True) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + losses = criterion(model(batch), batch) + losses["total"].backward() + groups = grad_norms(model) + item["samples"][source] = { + "mode": specs[source]["mode"], + "loss": float(losses["total"].detach()), + "grad_norm": sum(x * x for x in groups.values()) ** .5, + "decoder_grad": groups.get("decoder.spatial", 0.0), + "projection_grad": groups.get("rgb_encoder.projection", 0.0), + "depth_grad": groups.get("depth_encoder", 0.0), + "translation_head_grad": groups.get("translation_head", 0.0), + } + results.append(item) + del model + torch.cuda.empty_cache() + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(results, indent=2) + "\n") + print(json.dumps(results, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/run_formal_stages.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/run_formal_stages.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd55afacfa5d7d36a86318e62b0f4edd6bf4a47 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/run_formal_stages.py @@ -0,0 +1,186 @@ +"""Continue the registered six-GPU clean-GT stages after the S1 health gate.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import subprocess +import time + + +ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925") +CODE = ROOT / "code" +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +CHECKPOINTS = ROOT / "checkpoints" +LOGS = ROOT / "logs" +EVAL = ROOT / "eval" +RUN_TAG = "formal_v3" +S1_HEALTH_PIDFILE = LOGS / f"{RUN_TAG}_s1_health2k.pid" +S1_PIDFILE = LOGS / f"{RUN_TAG}_s1_full.pid" +ENDPOINTS = {"S1": 16667, "S2": 50000, "S3": 83334, "S4": 66667} +MODES = { + "H2O": ("rgb", "rgb_k", "rgb_depth_k"), + "ARCTIC": ("rgb", "rgb_k"), + "HOT3D": ("rgb", "rgb_k"), +} + + +def checksum(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def state(event: str, **details: object) -> None: + payload = {"event": event, "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S%z"), **details} + path = LOGS / f"{RUN_TAG}_controller_state.json" + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n") + temporary.replace(path) + print(json.dumps(payload), flush=True) + + +def endpoint(stage: str, update: int) -> Path: + return CHECKPOINTS / f"{RUN_TAG}_{stage.lower()}" / f"{stage.lower()}_update_{update:07d}.pt" + + +def process_running(pidfile: Path) -> bool: + if not pidfile.exists(): + return False + return subprocess.run( + ["start-stop-daemon", "--status", "--pidfile", str(pidfile)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, + ).returncode == 0 + + +def wait_for_s1_health() -> None: + target = endpoint("S1", 2000) + deadline = time.monotonic() + 3 * 3600 + if not process_running(S1_HEALTH_PIDFILE) and not target.is_file(): + raise RuntimeError("S1 health process is absent without a complete endpoint") + while process_running(S1_HEALTH_PIDFILE): + if time.monotonic() > deadline: + raise TimeoutError("S1 health exceeded its three-hour watchdog") + time.sleep(30) + if not target.is_file(): + raise RuntimeError("S1 health stopped without its complete formal endpoint") + + +def run_logged(command: list[str], log: Path) -> None: + if log.exists(): + raise FileExistsError(f"refusing to overwrite an existing run log: {log}") + print(json.dumps({"run": command, "log": str(log)}), flush=True) + with log.open("xb") as stream: + result = subprocess.run(command, cwd=CODE, stdout=stream, stderr=subprocess.STDOUT, + check=False) + if result.returncode != 0: + raise RuntimeError(f"command exited {result.returncode}; inspect {log}") + + +def audit(stage: str, update: int) -> dict: + target = endpoint(stage, update) + report_path = LOGS / f"{RUN_TAG}_{stage.lower()}_{update:07d}_audit.json" + if report_path.exists(): + report = json.loads(report_path.read_text()) + if report["status"] != "pass" or report["checkpoint_sha256"] != checksum(target): + raise RuntimeError(f"stale or failed endpoint audit: {report_path}") + else: + run_logged([ + PYTHON, str(CODE / "audit_formal_stage.py"), + "--checkpoint", str(target), + "--metrics", str(target.parent / "metrics.jsonl"), + "--stage", stage, "--update", str(update), + "--output", str(report_path), + ], LOGS / f"{RUN_TAG}_{stage.lower()}_{update:07d}_audit.console.log") + report = json.loads(report_path.read_text()) + if report["status"] != "pass": + raise RuntimeError(f"endpoint audit failed: {report_path}") + if update == 2000 and report["last_window_loss_mean"] > 2 * report["first_window_loss_mean"]: + raise RuntimeError(f"early-stage loss grew more than twofold: {report_path}") + state("audited", stage=stage, update=update, checkpoint_sha256=report["checkpoint_sha256"]) + return report + + +def train(stage: str, update: int, previous: Path) -> Path: + target = endpoint(stage, update) + if target.is_file(): + audit(stage, update) + return target + output = target.parent + command = [ + PYTHON, "-m", "torch.distributed.run", "--standalone", "--nproc_per_node=6", + "clean_train.py", "--stage", stage, "--output", str(output), + "--updates", str(update), "--workers", "2", "--save", + ] + if update == 2000: + if output.exists(): + raise FileExistsError(f"uncompleted formal stage requires diagnosis: {output}") + command += ["--parent", str(previous)] + else: + command += ["--resume", str(previous)] + label = "health2k" if update == 2000 else "full" + state("training", stage=stage, update=update, parent=str(previous)) + run_logged(command, LOGS / f"{RUN_TAG}_{stage.lower()}_{label}.console.log") + if not target.is_file(): + raise RuntimeError(f"training returned without endpoint: {target}") + audit(stage, update) + return target + + +def evaluate(stage: str, update: int, *, full: bool, confirmation: bool = False) -> None: + target = endpoint(stage, update) + role = "confirmation" if confirmation else "development" + conditions = [(source, mode) for source, modes in MODES.items() for mode in modes] + if not full: + conditions = [("H2O", "rgb_depth_k"), ("ARCTIC", "rgb_k"), ("HOT3D", "rgb_k")] + for source, mode in conditions: + tag = f"{RUN_TAG}_{stage.lower()}_{update:07d}_{role}_{source.lower()}_{mode}" + report_path = EVAL / "formal_stages" / f"{tag}.json" + if report_path.exists(): + report = json.loads(report_path.read_text()) + if (report["checkpoint_sha256"] != checksum(target) or report["source"] != source + or report["input_mode"] != mode or report["role"] != role): + raise RuntimeError(f"stale evaluation report: {report_path}") + continue + command = [ + PYTHON, str(CODE / "clean_eval.py"), "--checkpoint", str(target), + "--source", source, "--role", role, "--mode", mode, + "--output", str(report_path), + ] + if confirmation: + command.append("--final-checkpoint") + elif not full: + command += ["--allow-smoke", "--limit", "32"] + run_logged(command, LOGS / f"{tag}.console.log") + report = json.loads(report_path.read_text()) + if any(value["count"] == 0 for value in report["four_metrics"].values()): + raise RuntimeError(f"evaluation has an empty metric denominator: {report_path}") + state("evaluated", stage=stage, update=update, source=source, mode=mode, + role=role, report=str(report_path)) + + +def main() -> None: + try: + state("waiting_for_s1_health") + wait_for_s1_health() + audit("S1", 2000) + evaluate("S1", 2000, full=False) + parent = train("S1", ENDPOINTS["S1"], endpoint("S1", 2000)) + evaluate("S1", ENDPOINTS["S1"], full=False) + for stage in ("S2", "S3", "S4"): + short = train(stage, 2000, parent) + evaluate(stage, 2000, full=False) + parent = train(stage, ENDPOINTS[stage], short) + evaluate(stage, ENDPOINTS[stage], full=stage in ("S3", "S4")) + evaluate("S4", ENDPOINTS["S4"], full=True, confirmation=True) + state("complete", checkpoint=str(parent), checkpoint_sha256=checksum(parent)) + except Exception as error: + state("failed", error=f"{type(error).__name__}: {error}") + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/adapt_phase3_validation_subset.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/adapt_phase3_validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..3597f9540602b5d9249706b44f33431b996d1b6b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/adapt_phase3_validation_subset.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Clone a fixed validation selection under a new preprocessing contract.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--resolution-hw", type=int, nargs=2, required=True) + args = parser.parse_args() + + source = json.loads(args.source.read_text(encoding="utf-8")) + record = dict(source) + record["version"] = f"{source['version']}_resolution_contract_v1" + record["parent_selection_manifest"] = str(args.source.resolve()) + record["parent_selection_manifest_sha256"] = sha256(args.source) + record["dataset_contract"] = dict(source["dataset_contract"]) + record["dataset_contract"]["resolution_hw"] = list(args.resolution_hw) + record["adaptation"] = ( + "Clip indices and all selection metadata are copied exactly; only the " + "resize/padding resolution contract changes." + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "created", + "output": str(args.output), + "count": len(record["clip_indices"]), + "resolution_hw": record["dataset_contract"]["resolution_hw"], + "sha256": sha256(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/analyze_phase8_checkpoint_drift.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/analyze_phase8_checkpoint_drift.py new file mode 100644 index 0000000000000000000000000000000000000000..75eb62e3785a60f5e05394066d2518db310df246 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/analyze_phase8_checkpoint_drift.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Measure layerwise model-parameter drift between two hash-bound checkpoints.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import torch + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _model_state(path: Path, expected_sha256: str) -> tuple[dict[str, torch.Tensor], dict[str, Any]]: + actual = sha256(path) + if actual != expected_sha256: + raise ValueError(f"checkpoint SHA256 differs: {path}") + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + state = checkpoint.get("model") + if not isinstance(state, dict) or not state: + raise ValueError(f"checkpoint has no model state: {path}") + return state, { + "path": str(path.resolve()), "sha256": actual, + "step": int(checkpoint.get("step", -1)), + "h2o_training_data_used": checkpoint.get("extra", {}).get( + "h2o_training_data_used" + ), + "official_test_used": checkpoint.get("extra", {}).get("official_test_used"), + } + + +def _group(name: str, depth: int) -> str: + components = name.split(".") + return ".".join(components[:depth]) + + +def analyze( + reference_path: Path, + reference_sha256: str, + candidate_path: Path, + candidate_sha256: str, + *, + group_depth: int = 2, +) -> dict[str, Any]: + if group_depth <= 0: + raise ValueError("group_depth must be positive") + reference, reference_meta = _model_state(reference_path, reference_sha256) + candidate, candidate_meta = _model_state(candidate_path, candidate_sha256) + if set(reference) != set(candidate): + missing = sorted(set(reference) - set(candidate)) + extra = sorted(set(candidate) - set(reference)) + raise ValueError(f"model state keys differ; missing={missing[:5]} extra={extra[:5]}") + accumulators: dict[str, dict[str, float]] = {} + for name in sorted(reference): + before = reference[name] + after = candidate[name] + if before.shape != after.shape: + raise ValueError(f"parameter shape differs: {name}") + if not before.is_floating_point(): + continue + before64 = before.detach().to(dtype=torch.float64) + delta = after.detach().to(dtype=torch.float64) - before64 + groups = ("__overall__", _group(name, 1), _group(name, group_depth)) + for group in dict.fromkeys(groups): + values = accumulators.setdefault(group, { + "parameter_count": 0.0, "reference_sq_sum": 0.0, + "delta_sq_sum": 0.0, "delta_abs_sum": 0.0, + "delta_abs_max": 0.0, "tensor_count": 0.0, + }) + values["parameter_count"] += float(delta.numel()) + values["reference_sq_sum"] += float(before64.square().sum()) + values["delta_sq_sum"] += float(delta.square().sum()) + values["delta_abs_sum"] += float(delta.abs().sum()) + values["delta_abs_max"] = max( + values["delta_abs_max"], float(delta.abs().max()) if delta.numel() else 0.0, + ) + values["tensor_count"] += 1.0 + groups: dict[str, Any] = {} + for group, values in sorted(accumulators.items()): + count = int(values["parameter_count"]) + delta_l2 = math.sqrt(values["delta_sq_sum"]) + reference_l2 = math.sqrt(values["reference_sq_sum"]) + groups[group] = { + "parameter_count": count, + "tensor_count": int(values["tensor_count"]), + "reference_l2": reference_l2, + "delta_l2": delta_l2, + "relative_l2": delta_l2 / max(reference_l2, 1e-12), + "delta_mean_abs": values["delta_abs_sum"] / max(count, 1), + "delta_max_abs": values["delta_abs_max"], + } + return { + "schema_version": "phase8_checkpoint_drift_v1", + "status": "complete", + "reference": reference_meta, + "candidate": candidate_meta, + "group_depth": group_depth, + "groups": groups, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference", type=Path, required=True) + parser.add_argument("--reference-sha256", required=True) + parser.add_argument("--candidate", type=Path, required=True) + parser.add_argument("--candidate-sha256", required=True) + parser.add_argument("--group-depth", type=int, default=2) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = analyze( + args.reference, args.reference_sha256, + args.candidate, args.candidate_sha256, + group_depth=args.group_depth, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/analyze_phase8_paired_input_modes.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/analyze_phase8_paired_input_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..615c329bb99ebb1df93134ba095c09b527aa8fd7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/analyze_phase8_paired_input_modes.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Paired depth-contribution diagnostic for two frozen evaluation bundles.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_summary(values: np.ndarray) -> dict[str, float | int] | None: + values = np.asarray(values, dtype=np.float64) + values = values[np.isfinite(values)] + if not len(values): + return None + return { + "count": int(len(values)), "mean": float(values.mean()), + "median": float(np.median(values)), "p90": float(np.quantile(values, .9)), + "p95": float(np.quantile(values, .95)), "p99": float(np.quantile(values, .99)), + "min": float(values.min()), "max": float(values.max()), + } + + +def correlation(left: np.ndarray, right: np.ndarray) -> float | None: + finite = np.isfinite(left) & np.isfinite(right) + if finite.sum() < 2 or np.std(left[finite]) == 0 or np.std(right[finite]) == 0: + return None + return float(np.corrcoef(left[finite], right[finite])[0, 1]) + + +def optimal_slope(delta: np.ndarray, desired: np.ndarray) -> float | None: + finite = np.isfinite(delta) & np.isfinite(desired) + denominator = float(np.dot(delta[finite], delta[finite])) + if denominator <= 1e-12: + return None + return float(np.dot(delta[finite], desired[finite]) / denominator) + + +def grouped_bootstrap( + groups: np.ndarray, gains: np.ndarray, *, seed: int, resamples: int, +) -> dict[str, float | int]: + unique = np.unique(groups) + by_group = {group: gains[groups == group] for group in unique} + generator = np.random.default_rng(seed) + estimates = np.empty(resamples, dtype=np.float64) + for index in range(resamples): + sampled = generator.choice(unique, size=len(unique), replace=True) + values = np.concatenate([by_group[group] for group in sampled]) + estimates[index] = np.nanmean(values) + return { + "groups": int(len(unique)), "resamples": int(resamples), + "estimate": float(np.nanmean(gains)), + "ci95_low": float(np.quantile(estimates, .025)), + "ci95_high": float(np.quantile(estimates, .975)), + } + + +def load_bundle(directory: Path) -> tuple[dict[str, Any], dict[str, np.ndarray], list[dict[str, str]]]: + report_path = directory / "evaluation.json" + raw_path = directory / "raw_predictions.npz" + rows_path = directory / "per_hand_frame_metrics.csv" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("official_test_used") is not False + or report.get("h2o_official_validation_used_for_external_selection") is True + ): + raise ValueError("paired diagnostic refuses a bundle without official_test_used=false") + with np.load(raw_path) as archive: + raw = {key: archive[key] for key in archive.files} + with rows_path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + return report, raw, rows + + +def observation_manifest(report: dict[str, Any]) -> dict[str, Any]: + for name in ("cache_manifest", "manifest"): + value = report.get(name) + if isinstance(value, dict) and value.get("sha256"): + return value + raise ValueError("evaluation lacks a hash-bound observation manifest") + + +def validate_pair( + base_report: dict[str, Any], depth_report: dict[str, Any], + base: dict[str, np.ndarray], depth: dict[str, np.ndarray], + base_rows: list[dict[str, str]], depth_rows: list[dict[str, str]], +) -> None: + if base_report["checkpoint"]["sha256"] != depth_report["checkpoint"]["sha256"]: + raise ValueError("paired modes must use the same checkpoint") + if observation_manifest(base_report)["sha256"] != observation_manifest(depth_report)["sha256"]: + raise ValueError("paired modes must use the same cache manifest") + if base_report["input_mode"] != "rgb_k" or depth_report["input_mode"] != "rgb_d_k": + raise ValueError("expected base=rgb_k and depth=rgb_d_k") + for key in ( + "target_wrist_root_translation", "target_joints_camera", + "translation_valid", "joint3d_valid", "frame_id", + ): + if key not in base or key not in depth or not np.array_equal(base[key], depth[key], equal_nan=True): + raise ValueError(f"paired raw target alignment differs: {key}") + if len(base_rows) != len(depth_rows): + raise ValueError("paired per-hand row counts differ") + identity = ("dataset", "subject_id", "physical_recording_id", "camera_id", "frame_id", "side") + if any(any(left[key] != right[key] for key in identity) for left, right in zip(base_rows, depth_rows)): + raise ValueError("paired per-hand row identities differ") + + +def analyze( + base_dir: Path, depth_dir: Path, output_dir: Path, *, seed: int, resamples: int, +) -> dict[str, Any]: + base_report, base, base_rows = load_bundle(base_dir) + depth_report, depth, depth_rows = load_bundle(depth_dir) + validate_pair(base_report, depth_report, base, depth, base_rows, depth_rows) + if output_dir.exists() and any(output_dir.iterdir()): + raise ValueError("output directory must be new or empty") + output_dir.mkdir(parents=True, exist_ok=True) + + predicted_base = base["predicted_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + predicted_depth = depth["predicted_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + target = base["target_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + translation_valid = base["translation_valid"].reshape(-1).astype(bool) + delta = (predicted_depth - predicted_base) * 1000.0 + desired = (target - predicted_base) * 1000.0 + base_residual = (predicted_base - target) * 1000.0 + depth_residual = (predicted_depth - target) * 1000.0 + + base_joints = base["predicted_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + depth_joints = depth["predicted_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + target_joints = base["target_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + joint_valid = base["joint3d_valid"].reshape(-1, 21).astype(bool) + base_point_error = np.linalg.norm(base_joints - target_joints, axis=-1) * 1000.0 + depth_point_error = np.linalg.norm(depth_joints - target_joints, axis=-1) * 1000.0 + base_mpjpe = np.full(len(joint_valid), np.nan) + depth_mpjpe = np.full(len(joint_valid), np.nan) + for index, valid in enumerate(joint_valid): + if valid.any(): + base_mpjpe[index] = base_point_error[index, valid].mean() + depth_mpjpe[index] = depth_point_error[index, valid].mean() + + groups = np.asarray([row["physical_recording_id"] for row in base_rows], dtype=object) + if len(groups) != len(predicted_base): + raise ValueError("raw hand axis does not match per-hand metric rows") + valid = translation_valid & np.isfinite(base_residual).all(1) & np.isfinite(depth_residual).all(1) + joint_rows = np.isfinite(base_mpjpe) & np.isfinite(depth_mpjpe) + translation_gain = np.linalg.norm(base_residual, axis=1) - np.linalg.norm(depth_residual, axis=1) + mpjpe_gain = base_mpjpe - depth_mpjpe + + paired_rows: list[dict[str, Any]] = [] + for index, metadata in enumerate(base_rows): + if not (valid[index] or joint_rows[index]): + continue + record: dict[str, Any] = { + key: metadata[key] for key in + ("dataset", "subject_id", "physical_recording_id", "camera_id", "frame_id", "side") + } + for axis_index, axis in enumerate("xyz"): + record[f"depth_contribution_{axis}_mm"] = float(delta[index, axis_index]) + record[f"desired_correction_{axis}_mm"] = float(desired[index, axis_index]) + record[f"base_{axis}_error_mm"] = float(base_residual[index, axis_index]) + record[f"depth_{axis}_error_mm"] = float(depth_residual[index, axis_index]) + record["base_mpjpe_mm"] = float(base_mpjpe[index]) + record["depth_mpjpe_mm"] = float(depth_mpjpe[index]) + record["mpjpe_gain_mm"] = float(mpjpe_gain[index]) + record["translation_norm_gain_mm"] = float(translation_gain[index]) + paired_rows.append(record) + row_path = output_dir / "paired_hand_rows.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(paired_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(paired_rows) + harm_path = output_dir / "largest_harm_cases.csv" + harm_rows = sorted(paired_rows, key=lambda row: row["mpjpe_gain_mm"])[:100] + with harm_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(harm_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(harm_rows) + + axis_diagnostics = {} + for axis_index, axis in enumerate("xyz"): + selected = valid & np.isfinite(delta[:, axis_index]) & np.isfinite(desired[:, axis_index]) + axis_diagnostics[axis] = { + "base_signed_error_mm": finite_summary(base_residual[selected, axis_index]), + "depth_signed_error_mm": finite_summary(depth_residual[selected, axis_index]), + "depth_contribution_mm": finite_summary(delta[selected, axis_index]), + "desired_correction_mm": finite_summary(desired[selected, axis_index]), + "contribution_desired_correlation": correlation( + delta[selected, axis_index], desired[selected, axis_index], + ), + "optimal_depth_contribution_scale": optimal_slope( + delta[selected, axis_index], desired[selected, axis_index], + ), + "direction_agreement_fraction": float(np.mean( + np.sign(delta[selected, axis_index]) == np.sign(desired[selected, axis_index]) + )), + "absolute_error_gain_mm": finite_summary( + np.abs(base_residual[selected, axis_index]) - np.abs(depth_residual[selected, axis_index]) + ), + } + report = { + "status": "complete", + "class": "paired_input_oracle_diagnostic_only", + "deployable_claim": False, + "checkpoint": base_report["checkpoint"], + "observation_manifest": observation_manifest(base_report), + "base_input_mode": "rgb_k", "depth_input_mode": "rgb_d_k", + "hands_with_translation": int(valid.sum()), + "hands_with_joint3d": int(joint_rows.sum()), + "base_absolute_mpjpe_mm": float(np.nanmean(base_mpjpe[joint_rows])), + "depth_absolute_mpjpe_mm": float(np.nanmean(depth_mpjpe[joint_rows])), + "depth_mpjpe_gain_mm": finite_summary(mpjpe_gain[joint_rows]), + "depth_harm_fraction_mpjpe": float(np.mean(mpjpe_gain[joint_rows] < 0)), + "translation_norm_gain_mm": finite_summary(translation_gain[valid]), + "depth_harm_fraction_translation_norm": float(np.mean(translation_gain[valid] < 0)), + "axis_diagnostics": axis_diagnostics, + "grouped_bootstrap_ci": { + "mpjpe_gain_mm": grouped_bootstrap( + groups[joint_rows], mpjpe_gain[joint_rows], seed=seed, resamples=resamples, + ), + "translation_norm_gain_mm": grouped_bootstrap( + groups[valid], translation_gain[valid], seed=seed, resamples=resamples, + ), + }, + "paired_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "largest_harm_cases": {"path": str(harm_path.resolve()), "sha256": sha256(harm_path)}, + "official_test_used": False, + } + report_path = output_dir / "analysis.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-rgb-k-dir", type=Path, required=True) + parser.add_argument("--depth-rgb-d-k-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + report = analyze( + args.base_rgb_k_dir, args.depth_rgb_d_k_dir, args.output_dir, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/arm_phase9_last2_distributed_completion.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/arm_phase9_last2_distributed_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..d4159e763e607821df8bedef7283073b6dc8064b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/arm_phase9_last2_distributed_completion.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Carry one admitted last-2 candidate through both distributed handoffs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def write_state(path: Path, status: str, candidate: str, **extra: Any) -> None: + atomic_json(path, { + "schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": status, "candidate": candidate, "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "official_test_used": False, **extra, + }) + + +def wait_json(path: Path, predicate: Any, state_path: Path, candidate: str, label: str) -> dict[str, Any]: + while True: + if path.is_file(): + value = read_json(path) + if predicate(value): return value + if str(value.get("status", "")).startswith("failed"): + raise ValueError(f"last-2 dependency failed: {path}") + write_state(state_path, label, candidate, dependency=str(path.resolve())) + time.sleep(30) + + +def remote_conditions(plan: dict[str, Any], registry: dict[str, Any]) -> list[str]: + owners = condition_owners(registry, load_assignment(plan)) + result = [item["condition"] for item in registry["conditions"] + if owners[item["condition"]] == "server_new"] + if len(result) != 3: raise ValueError("last-2 remote condition count differs") + return result + + +def start_process(command: list[str], log: Path) -> int: + log.parent.mkdir(parents=True, exist_ok=True) + handle = log.open("a", encoding="utf-8") + process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=handle, + stderr=subprocess.STDOUT, text=True, start_new_session=True) + handle.close(); return process.pid + + +def start_remote(command: str) -> None: + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: raise RuntimeError("remote last-2 watcher launch failed") + + +def training_completion_plan(plan_path: Path, plan: dict[str, Any], registry_path: Path) -> dict[str, Any]: + registry = read_json(registry_path); conditions = remote_conditions(plan, registry) + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_last2_training_completion.py") + return { + "schema_version": "phase9_last2_training_completion_plan_v1", "status": "frozen", + "candidate": plan["candidate"], "source_owner": "server_new", + "destination_owner": "taku3", "conditions": conditions, "target_step": 405000, + "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/last2_v3/{plan['candidate']}/recovery/training_completion_staging", + "training_state_root": plan["training_state_root"], + "source_controller_state": plan["controller_states"]["server_new"], + "training_completion_state": plan["training_completion_state"], + "release_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_training_completion_release.json", + "receive_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_training_completion_receive.json", + "training_registry": {"path": str(registry_path.resolve()), "sha256": sha256(registry_path)}, + "controller_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "distributed_assignment": plan["distributed_assignment"], + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "results_before_terminal_states": True, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + {"path": str(registry_path.resolve()), "sha256": sha256(registry_path)}, + plan["distributed_assignment"], + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def evaluation_completion_plan(plan_path: Path, plan: dict[str, Any], dynamic: Path) -> dict[str, Any]: + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + return { + "schema_version": "phase9_resolution_evaluation_completion_release_plan_v1", + "status": "frozen", "source_owner": "server_new", "destination_owner": "taku3", + "source_host": "server_new", "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/last2_v3/{plan['candidate']}/recovery/evaluation_completion_staging", + "source_controller_state": plan["controller_states"]["server_new"], + "release_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_evaluation_completion_release.json", + "receive_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_evaluation_completion_receive.json", + "ssh_timeout_seconds": 30, + "evaluation_plan": {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "single_writer_per_output": True, "results_before_terminal_states": True, + "read_only_after_publish": True, + "scientific_contract": { + "amendment_scope": "terminal_evaluation_state_and_result_handoff_only", + "model_changed": False, "data_changed": False, "seed_changed": False, + "metric_changed": False, "selection_gate_changed": False, + }, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + plan["distributed_assignment"], + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def sync_plan_and_bridge(output: Path, value: dict[str, Any], bridge: Path) -> None: + if output.exists() and read_json(output) != value: raise ValueError(f"existing plan differs: {output}") + if not output.exists(): output.parent.mkdir(parents=True, exist_ok=True); atomic_json(output, value) + for path in (bridge, output): + installed = install_file("server_new", path) + if installed["sha256"] != sha256(path): raise ValueError(f"remote sync differs: {path}") + + +def sync_evaluation_admission(plan: dict[str, Any], dynamic: Path) -> None: + payload = read_json(dynamic) + remote_ids = {identifier for worker in payload["workers"] if worker["owner"] == "server_new" + for identifier in worker["evaluation_ids"]} + evaluations = {item["id"]: item for item in payload["evaluations"]} + for identifier in remote_ids: + item = evaluations[identifier] + for path_key, hash_key in (("config", "config_sha256"), + ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256")): + if remote_sha256("server_new", Path(item[path_key])) != item[hash_key]: + raise ValueError(f"remote last-2 evaluation input differs: {identifier}") + for path in (Path(plan["training_completion_state"]), + Path(plan["evaluation_plan_state"]), dynamic): + install_file("server_new", path) + + +def run(plan_path: Path, state_path: Path) -> dict[str, Any]: + plan = read_json(plan_path); candidate = plan["candidate"] + sync_state = Path(f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{candidate}/admission_sync_state.json") + admitted = wait_json(sync_state, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_admission_sync") + if admitted.get("admission") == "rejected": + return {"schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": "complete_formal_rejection", "candidate": candidate, + "completed_utc": utc_now(), "official_test_used": False} + registry_path = Path(plan["training_registry"]) + wait_json(registry_path, lambda value: value.get("status") == "frozen_ready", + state_path, candidate, "waiting_for_training_registry") + training_plan_path = plan_path.parent / f"last2_{candidate}_training_completion_plan_v1.json" + training_value = training_completion_plan(plan_path, plan, registry_path) + training_bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_last2_training_completion.py") + sync_plan_and_bridge(training_plan_path, training_value, training_bridge) + log_root = Path(f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{candidate}/completion_logs") + receive_pid = start_process([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_last2_training_completion", "--plan", str(training_plan_path), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], log_root / "training_receive.log") + start_remote( + "cd /home/jiasen/foundation_hand && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + f"scripts.sync_phase9_last2_training_completion --plan {training_plan_path} --role publish " + f"--wait-timeout-seconds 1209600 >> {log_root / 'training_publish.log'} 2>&1 < /dev/null" + ) + receive_state = Path(training_value["receive_state"]) + wait_json(receive_state, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_training_completion_return") + dynamic = Path(plan["evaluation_plan"]) + wait_json(dynamic, lambda value: value.get("status") == "frozen_ready", + state_path, candidate, "waiting_for_evaluation_plan") + sync_evaluation_admission(plan, dynamic) + evaluation_plan_path = plan_path.parent / f"last2_{candidate}_evaluation_completion_plan_v1.json" + evaluation_value = evaluation_completion_plan(plan_path, plan, dynamic) + evaluation_bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + sync_plan_and_bridge(evaluation_plan_path, evaluation_value, evaluation_bridge) + evaluation_receive_pid = start_process([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_resolution_evaluation_completion", "--plan", str(evaluation_plan_path), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], log_root / "evaluation_receive.log") + start_remote( + "cd /home/jiasen/foundation_hand && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + f"scripts.sync_phase9_resolution_evaluation_completion --plan {evaluation_plan_path} --role publish " + f"--wait-timeout-seconds 1209600 >> {log_root / 'evaluation_publish.log'} 2>&1 < /dev/null" + ) + central = Path(plan["controller_states"]["taku3"]) + final = wait_json(central, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_central_candidate_decision") + return { + "schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": "complete", "candidate": candidate, "completed_utc": utc_now(), + "training_receive_pid": receive_pid, "evaluation_receive_pid": evaluation_receive_pid, + "decision_report": final["decision_report"], "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser(); parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True); args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + result = run(args.plan, args.state); atomic_json(args.state, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/arm_phase9_shared_augmentation_evaluation_completion.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/arm_phase9_shared_augmentation_evaluation_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..2213de6d5ae74ec16fc626ba2609582464fcd890 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/arm_phase9_shared_augmentation_evaluation_completion.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Arm completion-only Stage 8 evaluation return after its plan freezes.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def completion_plan(static_plan_path: Path, static: dict[str, Any]) -> dict[str, Any]: + dynamic = Path(static["evaluation_plan"]) + admission = Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/" + "evaluation_admission_sync_state.json" + ) + if not dynamic.is_file() or not admission.is_file(): + raise RuntimeError("Stage 8 evaluation admission is not complete") + admitted = read_json(admission) + if admitted.get("status") != "complete" or admitted.get("evaluation_plan_sha256") != sha256(dynamic): + raise RuntimeError("Stage 8 evaluation admission is not complete") + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + assignment = Path(static["distributed_assignment"]["path"]) + return { + "schema_version": "phase9_resolution_evaluation_completion_release_plan_v1", + "status": "frozen", "source_owner": "server_new", "destination_owner": "taku3", + "source_host": "server_new", + "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts/shared_augmentation/896x512/recovery/server_evaluation_completion_staging_v1", + "source_controller_state": static["controller_states"]["server_new"], + "release_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/server_evaluation_completion_release_state_v1.json", + "receive_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/server_evaluation_completion_receive_state_v1.json", + "ssh_timeout_seconds": 30, + "evaluation_plan": {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "single_writer_per_output": True, "results_before_terminal_states": True, + "read_only_after_publish": True, + "scientific_contract": { + "amendment_scope": "terminal_evaluation_state_and_result_handoff_only", + "model_changed": False, "data_changed": False, "seed_changed": False, + "metric_changed": False, "selection_gate_changed": False, + }, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(static_plan_path.resolve()), "sha256": sha256(static_plan_path)}, + {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + {"path": str(assignment.resolve()), "sha256": sha256(assignment)}, + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def arm(static_plan_path: Path, output_plan: Path) -> dict[str, Any]: + static = read_json(static_plan_path) + plan = completion_plan(static_plan_path, static) + if output_plan.exists() and read_json(output_plan) != plan: + raise ValueError("existing Stage 8 evaluation completion plan differs") + if not output_plan.exists(): + output_plan.parent.mkdir(parents=True, exist_ok=True); atomic_json(output_plan, plan) + copied = subprocess.run(["rsync", "-a", str(output_plan), f"server_new:{output_plan}.incoming"], check=False) + if copied.returncode: + raise RuntimeError("Stage 8 evaluation completion plan sync failed") + installed = subprocess.run(["ssh", "server_new", "mv", f"{output_plan}.incoming", str(output_plan)], check=False) + if installed.returncode: + raise RuntimeError("Stage 8 evaluation completion plan install failed") + log_root = Path("/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/completion_logs") + log_root.mkdir(parents=True, exist_ok=True) + receive = subprocess.Popen([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_resolution_evaluation_completion", "--plan", str(output_plan), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], stdin=subprocess.DEVNULL, stdout=(log_root / "evaluation_receive.log").open("a"), + stderr=subprocess.STDOUT, text=True, start_new_session=True) + remote = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.sync_phase9_resolution_evaluation_completion --plan " + str(output_plan) + + " --role publish --wait-timeout-seconds 1209600 >> " + + str(log_root / "evaluation_publish.log") + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", remote], check=False) + if result.returncode: + raise RuntimeError("Stage 8 evaluation completion publisher launch failed") + return { + "schema_version": "phase9_shared_augmentation_evaluation_completion_arm_v1", + "status": "complete", "completed_utc": utc_now(), + "completion_plan": str(output_plan.resolve()), + "completion_plan_sha256": sha256(output_plan), "receiver_pid": receive.pid, + "official_test_used": False, "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--static-plan", type=Path, required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = arm(args.static_plan, args.output_plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except RuntimeError as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_evaluation_completion_arm_v1", + "status": "waiting_for_evaluation_admission", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_coordinates.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_coordinates.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca4d235ec4f8a6ed42e9e7528951c26225cab2b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_coordinates.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Create reproducible camera/depth/joint audit artifacts for H2O cam4.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record +from foundation_hand.geometry.camera import ( + depth_mm_to_m, + intrinsics_from_h2o, + project_points, + unproject_depth, +) + +HAND_COLORS = ((50, 220, 50), (50, 80, 255)) # BGR: left green, right red +HAND_EDGES = ( + (0, 1), (1, 2), (2, 3), (3, 4), + (0, 5), (5, 6), (6, 7), (7, 8), + (0, 9), (9, 10), (10, 11), (11, 12), + (0, 13), (13, 14), (14, 15), (15, 16), + (0, 17), (17, 18), (18, 19), (19, 20), +) + + +def choose_samples(frame_csv: Path, count: int) -> list[dict[str, str]]: + with frame_csv.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + buckets: dict[str, list[dict[str, str]]] = {} + for row in rows: + key = f"{row['subject']}:{row['joint_left_valid']}{row['joint_right_valid']}" + buckets.setdefault(key, []).append(row) + selected: list[dict[str, str]] = [] + keys = sorted(buckets) + cursor = {key: 0 for key in keys} + while len(selected) < count and keys: + next_keys = [] + for key in keys: + candidates = buckets[key] + index = cursor[key] + if index < len(candidates): + # Walk each bucket across time rather than taking adjacent frames. + pos = min(len(candidates) - 1, round(index * max(1, len(candidates) - 1) / max(1, count // len(keys)))) + selected.append(candidates[pos]) + cursor[key] += 1 + next_keys.append(key) + if len(selected) == count: + break + keys = next_keys + return selected + + +def draw_joints(image: np.ndarray, uv: np.ndarray, valid_z: np.ndarray, color: tuple[int, int, int]) -> None: + inside = valid_z & (uv[:, 0] >= 0) & (uv[:, 0] < image.shape[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < image.shape[0]) + for start, end in HAND_EDGES: + if inside[start] and inside[end]: + cv2.line(image, tuple(np.rint(uv[start]).astype(int)), tuple(np.rint(uv[end]).astype(int)), color, 2) + for index, point in enumerate(uv): + if inside[index]: + radius = 5 if index == 0 else 3 + cv2.circle(image, tuple(np.rint(point).astype(int)), radius, color, -1) + + +def write_colored_ply(path: Path, xyz: np.ndarray, rgb: np.ndarray, valid: np.ndarray, stride: int = 8) -> int: + points = xyz[::stride, ::stride][valid[::stride, ::stride]] + colors = rgb[::stride, ::stride][valid[::stride, ::stride]] + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="ascii") as handle: + handle.write("ply\nformat ascii 1.0\n") + handle.write(f"element vertex {len(points)}\n") + handle.write("property float x\nproperty float y\nproperty float z\n") + handle.write("property uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n") + for point, color in zip(points, colors, strict=True): + handle.write(f"{point[0]:.6f} {point[1]:.6f} {point[2]:.6f} {int(color[0])} {int(color[1])} {int(color[2])}\n") + return len(points) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=24) + args = parser.parse_args() + + root = args.root.resolve() + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + selected = choose_samples(args.frame_csv, args.samples) + result_rows = [] + roundtrip_errors = [] + + for sample_index, row in enumerate(selected): + take = root / row["subject"] / row["scene"] / row["take"] / "cam4" + frame = f"{int(row['frame_id']):06d}" + rgb_bgr = cv2.imread(str(take / "rgb" / f"{frame}.png"), cv2.IMREAD_COLOR) + depth_raw = cv2.imread(str(take / "depth" / f"{frame}.png"), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_raw is None: + raise RuntimeError(f"Could not decode sample {take}/{frame}") + K, expected_hw = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + if rgb_bgr.shape[:2] != expected_hw or depth_raw.shape != expected_hw: + raise ValueError(f"RGB/depth/K size mismatch at {take}/{frame}") + depth_m, depth_valid = depth_mm_to_m(depth_raw) + xyz, xyz_valid = unproject_depth(depth_m, K) + + # Pixel -> camera -> pixel should recover exact pixel centers for every valid depth. + sparse_xyz = xyz[::16, ::16].reshape(-1, 3) + sparse_valid = xyz_valid[::16, ::16].reshape(-1) + uv_back, positive = project_points(sparse_xyz[sparse_valid], K) + vv, uu = np.meshgrid(np.arange(0, expected_hw[0], 16), np.arange(0, expected_hw[1], 16), indexing="ij") + uv_reference = np.stack((uu, vv), axis=-1).reshape(-1, 2)[sparse_valid] + pixel_error = np.linalg.norm(uv_back[positive] - uv_reference[positive], axis=-1) + roundtrip_errors.extend(pixel_error.tolist()) + + overlay = rgb_bgr.copy() + joints = load_joint_record(take / "hand_pose" / f"{frame}.txt") + hand_stats = [] + for hand_index, color in enumerate(HAND_COLORS): + if joints.annotation_valid[hand_index]: + uv, positive_z = project_points(joints.joints_camera_m[hand_index], K) + draw_joints(overlay, uv, positive_z, color) + hand_stats.append({"side": ("left", "right")[hand_index], "annotation_valid": True, "projected_in_frame": int(((uv[:, 0] >= 0) & (uv[:, 0] < expected_hw[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < expected_hw[0]) & positive_z).sum())}) + else: + hand_stats.append({"side": ("left", "right")[hand_index], "annotation_valid": False, "projected_in_frame": None}) + + valid_depth = depth_m[depth_valid] + clipped = np.clip(depth_m, 0, np.quantile(valid_depth, 0.99) if valid_depth.size else 1.0) + depth_u8 = np.rint(255 * clipped / max(float(clipped.max()), 1e-6)).astype(np.uint8) + depth_color = cv2.applyColorMap(depth_u8, cv2.COLORMAP_TURBO) + depth_color[~depth_valid] = 0 + edges = cv2.Canny(depth_u8, 30, 90) + alignment = rgb_bgr.copy() + alignment[edges > 0] = (0, 255, 255) + + label = f"{row['subject']}/{row['scene']}/{row['take']}/{frame} L={row['joint_left_valid']} R={row['joint_right_valid']}" + for image in (overlay, depth_color, alignment): + cv2.rectangle(image, (0, 0), (image.shape[1], 34), (0, 0, 0), -1) + cv2.putText(image, label, (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) + prefix = f"{sample_index:02d}_{row['subject']}_{row['scene']}_{row['take']}_{frame}" + cv2.imwrite(str(output / f"{prefix}_joint_overlay.jpg"), overlay) + cv2.imwrite(str(output / f"{prefix}_depth.jpg"), depth_color) + cv2.imwrite(str(output / f"{prefix}_depth_edges_rgb.jpg"), alignment) + ply_count = write_colored_ply(output / f"{prefix}_pointcloud.ply", xyz, cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB), xyz_valid) + result_rows.append({ + "sample": prefix, + "subject": row["subject"], "scene": row["scene"], "take": row["take"], "frame_id": int(row["frame_id"]), + "K": K.tolist(), "depth_dtype": str(depth_raw.dtype), "depth_valid_fraction": float(depth_valid.mean()), + "depth_min_m": float(valid_depth.min()), "depth_p50_m": float(np.quantile(valid_depth, 0.5)), "depth_p95_m": float(np.quantile(valid_depth, 0.95)), "depth_max_m": float(valid_depth.max()), + "pixel_roundtrip_max": float(pixel_error.max()) if pixel_error.size else None, + "pointcloud_vertices": ply_count, "hands": hand_stats, + }) + + errors = np.asarray(roundtrip_errors) + report = { + "root": str(root), "sample_count": len(result_rows), "selection": "round-robin across subject and annotation-valid combinations, spread over time", + "camera_convention_supported_by_projection": "x-right, y-down, z-forward; u=fx*x/z+cx, v=fy*y/z+cy", + "depth_unit": "released uint16 millimeters converted by /1000 to meters", + "pixel_unprojection_projection_roundtrip": {"count": int(errors.size), "mean_px": float(errors.mean()), "p95_px": float(np.quantile(errors, 0.95)), "max_px": float(errors.max())}, + "mano_numeric_reconstruction": "BLOCKED_MISSING_LICENSED_MANO_ASSETS", + "samples": result_rows, + } + (output / "coordinate_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: report[key] for key in ("sample_count", "camera_convention_supported_by_projection", "depth_unit", "pixel_unprojection_projection_roundtrip", "mano_numeric_reconstruction")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_mano.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_mano.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ae1a83d4f165c9542c997f6cd3bd7ceeff5b46 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_mano.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Numerically reproduce H2O MANO fits before formal training is allowed.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record, load_mano_record +from foundation_hand.geometry.camera import intrinsics_from_h2o, project_points +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.mano_translation import mano_raw_to_wrist, wrist_to_mano_raw + + +def stats(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values) + return {"count": int(array.size), "mean_mm": float(array.mean()), "p50_mm": float(np.quantile(array, .5)), "p95_mm": float(np.quantile(array, .95)), "max_mm": float(array.max())} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=50) + args = parser.parse_args(); args.output_dir.mkdir(parents=True, exist_ok=True) + required = [args.mano_root / "MANO_LEFT.pkl", args.mano_root / "MANO_RIGHT.pkl"] + if not all(path.is_file() for path in required): + report = {"status": "blocked", "reason": "licensed MANO assets missing", "required": [str(path) for path in required]} + (args.output_dir / "mano_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)); raise SystemExit(2) + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + layers = [ManoLayer(mano_root=str(args.mano_root), side=side, use_pca=False, ncomps=45, flat_hand_mean=True) for side in ("left", "right")] + with args.frame_csv.open(newline="", encoding="utf-8") as handle: rows = [row for row in csv.DictReader(handle) if row["joint_left_valid"] == "1" and row["joint_right_valid"] == "1"] + rows = [rows[round(index * (len(rows)-1) / max(args.samples-1, 1))] for index in range(args.samples)] + errors = {"left": [], "right": []}; roundtrip = {"left": [], "right": []}; root_offsets = {"left": [], "right": []} + for sample_index, row in enumerate(rows): + take = args.root / row["subject"] / row["scene"] / row["take"] / "cam4"; stem = f"{int(row['frame_id']):06d}" + joints_gt = load_joint_record(take / "hand_pose" / f"{stem}.txt"); mano = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + image = cv2.imread(str(take / "rgb" / f"{stem}.png")); K, _ = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + for hand, side in enumerate(("left", "right")): + with torch.no_grad(): vertices_mm, joints_mm = layers[hand](torch.from_numpy(mano.pose_axis_angle[hand:hand+1]), torch.from_numpy(mano.shape[hand:hand+1])) + native_joints_m = joints_mm[0].numpy() / 1000.0; reconstructed = native_joints_m + mano.translation_raw_m[hand] + per_joint = np.linalg.norm(reconstructed - joints_gt.joints_camera_m[hand], axis=-1) * 1000 + errors[side].extend(per_joint.tolist()); root_offsets[side].append(native_joints_m[0].tolist()) + wrist = mano_raw_to_wrist(mano.translation_raw_m[hand], native_joints_m[0]); raw_back = wrist_to_mano_raw(wrist, native_joints_m[0]) + roundtrip[side].append(float(np.linalg.norm(raw_back - mano.translation_raw_m[hand]) * 1000)) + if sample_index < 10: + uv, positive = project_points(reconstructed, K) + for point, valid in zip(uv, positive, strict=True): + if valid: cv2.circle(image, tuple(np.rint(point).astype(int)), 3, ((50,220,50),(50,80,255))[hand], -1) + if sample_index < 10: cv2.imwrite(str(args.output_dir / f"{sample_index:02d}_{row['subject']}_{row['scene']}_{row['take']}_{stem}_mano_overlay.jpg"), image) + report = { + "status": "passed" if max(stats(errors[side])["p95_mm"] for side in errors) < 5 else "failed", + "configuration": {"use_pca": False, "ncomps": 45, "flat_hand_mean": True, "native_output_unit": "mm", "placed_output_unit": "m"}, + "joint_reconstruction": {side: stats(values) for side, values in errors.items()}, + "translation_semantics": "raw translation places the MANO model origin; wrist = raw + native MANO joint0 / 1000", + "raw_to_wrist_root_offsets_m": root_offsets, + "translation_roundtrip": {side: stats(values) for side, values in roundtrip.items()}, + } + (args.output_dir / "mano_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: report[key] for key in ("status", "joint_reconstruction", "translation_semantics", "translation_roundtrip")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase2_cam4.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase2_cam4.py new file mode 100644 index 0000000000000000000000000000000000000000..147fa879e7466f0015130321ffba9dec3915f615 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase2_cam4.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +"""Reproducible full-record audit of the extracted H2O cam4 dataset.""" + +from __future__ import annotations + +import argparse +import csv +import json +import random +from collections import Counter +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import ( + load_float_record, + parse_joint_record, + parse_mano_record, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + +CORE_FRAME_MODALITIES = ( + "rgb", + "depth", + "cam_pose", + "hand_pose", + "hand_pose_mano", + "obj_pose", + "obj_pose_rt", +) +SIDES = ("left", "right") + + +def quantiles(values: list[float] | np.ndarray) -> dict[str, float | int | None]: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if array.size == 0: + return {"count": 0, "mean": None, "p50": None, "p95": None, "max": None} + return { + "count": int(array.size), + "mean": float(array.mean()), + "p50": float(np.quantile(array, 0.50)), + "p95": float(np.quantile(array, 0.95)), + "max": float(array.max()), + } + + +def ids_in(directory: Path) -> set[int]: + return {int(path.stem) for path in directory.iterdir() if path.is_file() and path.stem.isdigit()} + + +def sample_evenly(items: list[Path], count: int) -> list[Path]: + if count <= 0 or not items: + return [] + if len(items) <= count: + return items + indices = np.linspace(0, len(items) - 1, count, dtype=int) + return [items[index] for index in indices] + + +def make_contact_sheet(rows: list[dict[str, object]], output: Path, title: str) -> None: + if not rows: + return + tile_w, tile_h = 320, 205 + columns = 4 + result_rows = (len(rows) + columns - 1) // columns + canvas = np.zeros((result_rows * tile_h + 36, columns * tile_w, 3), dtype=np.uint8) + cv2.putText(canvas, title, (8, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) + for index, row in enumerate(rows): + image = cv2.imread(str(row["rgb_path"]), cv2.IMREAD_COLOR) + if image is None: + continue + image = cv2.resize(image, (tile_w, 180), interpolation=cv2.INTER_AREA) + label = str(row["label"]) + cv2.rectangle(image, (0, 0), (tile_w, 24), (0, 0, 0), -1) + cv2.putText(image, label[:52], (4, 17), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (255, 255, 255), 1) + y = 36 + (index // columns) * tile_h + x = (index % columns) * tile_w + canvas[y : y + 180, x : x + tile_w] = image + output.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(output), canvas) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--depth-samples-per-take", type=int, default=2) + parser.add_argument("--invalid-visual-samples", type=int, default=40) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + root = args.root.resolve() + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + rng = random.Random(args.seed) + + take_dirs = sorted(root.glob("subject*/*/*/cam4")) + if not take_dirs: + raise RuntimeError(f"No cam4 takes found below {root}") + + take_rows: list[dict[str, object]] = [] + depth_candidates: list[Path] = [] + invalid_visuals: dict[str, list[dict[str, object]]] = {"left": [], "right": []} + record_lengths = {"hand_pose": Counter(), "hand_pose_mano": Counter(), "cam_pose": Counter()} + valid_combinations = Counter() + valid_agreement = Counter() + projection_counts = {side: Counter() for side in SIDES} + raw_to_wrist_offsets = {side: [] for side in SIDES} + raw_wrist_distance_mm = {side: [] for side in SIDES} + rotation_det_errors: list[float] = [] + rotation_orth_errors: list[float] = [] + pose_last_row_errors: list[float] = [] + intrinsics_rows: list[list[float]] = [] + image_shapes = Counter() + missing_by_modality = Counter() + extra_by_modality = Counter() + frame_count = 0 + nonfinite_records = Counter() + + frame_csv = output / "frame_audit.csv" + frame_fields = [ + "subject", + "scene", + "take", + "frame_id", + "joint_left_valid", + "joint_right_valid", + "mano_left_valid", + "mano_right_valid", + "left_joints_in_frame", + "right_joints_in_frame", + "left_wrist_in_frame", + "right_wrist_in_frame", + "left_raw_to_wrist_mm", + "right_raw_to_wrist_mm", + "rgb_path", + ] + + with frame_csv.open("w", newline="", encoding="utf-8") as frame_handle: + writer = csv.DictWriter(frame_handle, fieldnames=frame_fields) + writer.writeheader() + + for cam4 in take_dirs: + subject, scene, take = cam4.parts[-4:-1] + K_values = load_float_record(cam4 / "cam_intrinsics.txt") + K, expected_hw = intrinsics_from_h2o(K_values) + intrinsics_rows.append(K_values.tolist()) + + frame_sets = {name: ids_in(cam4 / name) for name in CORE_FRAME_MODALITIES} + rgb_ids = frame_sets["rgb"] + for name, ids in frame_sets.items(): + missing_by_modality[name] += len(rgb_ids - ids) + extra_by_modality[name] += len(ids - rgb_ids) + + rgb_paths = sorted((cam4 / "rgb").glob("*.png")) + depth_paths = sorted((cam4 / "depth").glob("*.png")) + depth_candidates.extend(sample_evenly(depth_paths, args.depth_samples_per_take)) + if rgb_paths: + sample_rgb = cv2.imread(str(rgb_paths[0]), cv2.IMREAD_COLOR) + if sample_rgb is None: + raise RuntimeError(f"Could not decode {rgb_paths[0]}") + image_shapes[str(tuple(sample_rgb.shape))] += 1 + if sample_rgb.shape[:2] != expected_hw: + raise ValueError( + f"K image size {expected_hw} does not match RGB {sample_rgb.shape[:2]} at {cam4}" + ) + + take_rows.append( + { + "subject": subject, + "scene": scene, + "take": take, + "frames": len(rgb_ids), + **{f"missing_{name}": len(rgb_ids - ids) for name, ids in frame_sets.items()}, + **{f"extra_{name}": len(ids - rgb_ids) for name, ids in frame_sets.items()}, + } + ) + + for frame_id in sorted(rgb_ids): + stem = f"{frame_id:06d}" + joint_values = load_float_record(cam4 / "hand_pose" / f"{stem}.txt") + mano_values = load_float_record(cam4 / "hand_pose_mano" / f"{stem}.txt") + pose_values = load_float_record(cam4 / "cam_pose" / f"{stem}.txt") + record_lengths["hand_pose"][str(joint_values.size)] += 1 + record_lengths["hand_pose_mano"][str(mano_values.size)] += 1 + record_lengths["cam_pose"][str(pose_values.size)] += 1 + if not np.isfinite(joint_values).all(): + nonfinite_records["hand_pose"] += 1 + if not np.isfinite(mano_values).all(): + nonfinite_records["hand_pose_mano"] += 1 + if not np.isfinite(pose_values).all(): + nonfinite_records["cam_pose"] += 1 + + joints = parse_joint_record(joint_values) + mano = parse_mano_record(mano_values) + joint_key = tuple(bool(value) for value in joints.annotation_valid) + mano_key = tuple(bool(value) for value in mano.annotation_valid) + valid_combinations[f"joint_{int(joint_key[0])}{int(joint_key[1])}"] += 1 + valid_combinations[f"mano_{int(mano_key[0])}{int(mano_key[1])}"] += 1 + valid_agreement[str(joint_key == mano_key)] += 1 + + camera_pose = pose_values.reshape(4, 4) + rotation = camera_pose[:3, :3] + rotation_det_errors.append(abs(float(np.linalg.det(rotation)) - 1.0)) + rotation_orth_errors.append(float(np.linalg.norm(rotation.T @ rotation - np.eye(3)))) + pose_last_row_errors.append(float(np.linalg.norm(camera_pose[3] - np.array([0, 0, 0, 1])))) + + frame_row: dict[str, object] = { + "subject": subject, + "scene": scene, + "take": take, + "frame_id": frame_id, + "joint_left_valid": int(joints.annotation_valid[0]), + "joint_right_valid": int(joints.annotation_valid[1]), + "mano_left_valid": int(mano.annotation_valid[0]), + "mano_right_valid": int(mano.annotation_valid[1]), + "rgb_path": str(cam4 / "rgb" / f"{stem}.png"), + } + + for side_index, side in enumerate(SIDES): + in_frame_count = -1 + wrist_in_frame = -1 + distance_mm = float("nan") + if joints.annotation_valid[side_index]: + uv, positive = project_points(joints.joints_camera_m[side_index], K) + inside = ( + positive + & (uv[:, 0] >= 0) + & (uv[:, 0] < expected_hw[1]) + & (uv[:, 1] >= 0) + & (uv[:, 1] < expected_hw[0]) + ) + in_frame_count = int(inside.sum()) + wrist_in_frame = int(inside[0]) + projection_counts[side]["valid"] += 1 + projection_counts[side]["any_joint_in_frame"] += int(inside.any()) + projection_counts[side]["all_joints_in_frame"] += int(inside.all()) + projection_counts[side]["wrist_in_frame"] += int(inside[0]) + projection_counts[side]["all_positive_z"] += int(positive.all()) + + if joints.annotation_valid[side_index] and mano.annotation_valid[side_index]: + offset = ( + joints.joints_camera_m[side_index, 0] + - mano.translation_raw_m[side_index] + ) + raw_to_wrist_offsets[side].append(offset.astype(np.float64)) + distance_mm = float(np.linalg.norm(offset) * 1000.0) + raw_wrist_distance_mm[side].append(distance_mm) + + frame_row[f"{side}_joints_in_frame"] = in_frame_count + frame_row[f"{side}_wrist_in_frame"] = wrist_in_frame + frame_row[f"{side}_raw_to_wrist_mm"] = distance_mm + + if not joints.annotation_valid[side_index]: + invalid_visuals[side].append( + { + "rgb_path": cam4 / "rgb" / f"{stem}.png", + "label": f"{subject}/{scene}/{take}/{stem} {side} ann=0", + } + ) + + writer.writerow(frame_row) + frame_count += 1 + + take_csv = output / "take_audit.csv" + with take_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(take_rows[0])) + writer.writeheader() + writer.writerows(take_rows) + + depth_rows: list[dict[str, object]] = [] + pooled_depth: list[np.ndarray] = [] + for path in depth_candidates: + depth_mm = cv2.imread(str(path), cv2.IMREAD_UNCHANGED) + if depth_mm is None: + raise RuntimeError(f"Could not decode depth {path}") + depth_m, valid = depth_mm_to_m(depth_mm) + positive = depth_m[valid] + sampled = positive[::64] if positive.size else positive + pooled_depth.append(sampled) + depth_rows.append( + { + "path": str(path), + "dtype": str(depth_mm.dtype), + "height": depth_mm.shape[0], + "width": depth_mm.shape[1], + "zero_fraction": float((depth_mm == 0).mean()), + "positive_min_m": float(positive.min()) if positive.size else None, + "positive_p50_m": float(np.quantile(positive, 0.50)) if positive.size else None, + "positive_p95_m": float(np.quantile(positive, 0.95)) if positive.size else None, + "positive_p99_m": float(np.quantile(positive, 0.99)) if positive.size else None, + "positive_max_m": float(positive.max()) if positive.size else None, + "fraction_gt_3_86m": float((depth_m > 3.86).mean()), + "fraction_gt_5_46m": float((depth_m > 5.46).mean()), + } + ) + + depth_csv = output / "depth_sample_stats.csv" + with depth_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(depth_rows[0])) + writer.writeheader() + writer.writerows(depth_rows) + + selected_invalid = {} + for side in SIDES: + candidates = invalid_visuals[side] + rng.shuffle(candidates) + selected_invalid[side] = candidates[: args.invalid_visual_samples] + make_contact_sheet( + selected_invalid[side], + output / f"annotation_invalid_{side}_contact_sheet.jpg", + f"H2O cam4 {side}: annotation_valid=0 (not a presence label)", + ) + + intrinsics = np.asarray(intrinsics_rows, dtype=np.float64) + combined_depth = np.concatenate(pooled_depth) if pooled_depth else np.empty(0) + summary = { + "root": str(root), + "seed": args.seed, + "take_count": len(take_dirs), + "frame_count": frame_count, + "camera": "cam4_only", + "record_length_distributions": { + name: dict(counter) for name, counter in record_lengths.items() + }, + "valid_combinations": dict(valid_combinations), + "joint_mano_valid_agreement": dict(valid_agreement), + "annotation_valid_is_presence": False, + "presence_fields_found": False, + "presence_training_recommendation": "disabled_until_reliable_labels_exist", + "projection_from_annotation_valid_joints": { + side: dict(counter) for side, counter in projection_counts.items() + }, + "raw_mano_translation_is_wrist": False, + "raw_to_wrist_offset_m": { + side: { + "x": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 0]), + "y": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 1]), + "z": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 2]), + "norm_mm": quantiles(raw_wrist_distance_mm[side]), + } + for side in SIDES + }, + "frame_alignment": { + "missing_by_modality": dict(missing_by_modality), + "extra_by_modality": dict(extra_by_modality), + }, + "nonfinite_records": dict(nonfinite_records), + "camera_pose": { + "det_rotation_abs_error": quantiles(rotation_det_errors), + "orthogonality_frobenius_error": quantiles(rotation_orth_errors), + "last_row_error": quantiles(pose_last_row_errors), + }, + "intrinsics": { + "count": int(intrinsics.shape[0]), + "fx": quantiles(intrinsics[:, 0]), + "fy": quantiles(intrinsics[:, 1]), + "cx": quantiles(intrinsics[:, 2]), + "cy": quantiles(intrinsics[:, 3]), + "width_values": sorted(set(intrinsics[:, 4].tolist())), + "height_values": sorted(set(intrinsics[:, 5].tolist())), + }, + "rgb_shapes_by_take": dict(image_shapes), + "depth_audit": { + "sampling": "uniform frames within every take; all sampled pixels decoded", + "sample_count": len(depth_rows), + "samples_per_take": args.depth_samples_per_take, + "positive_depth_m": quantiles(combined_depth), + "zero_fraction_across_sample_means": quantiles( + [float(row["zero_fraction"]) for row in depth_rows] + ), + }, + "visibility_or_occlusion_fields": [], + "outputs": { + "frame_csv": str(frame_csv), + "take_csv": str(take_csv), + "depth_csv": str(depth_csv), + "invalid_contact_sheets": { + side: str(output / f"annotation_invalid_{side}_contact_sheet.jpg") + for side in SIDES + }, + }, + } + (output / "cam4_audit_summary.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(summary, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() + diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase3_evaluations.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase3_evaluations.py new file mode 100644 index 0000000000000000000000000000000000000000..49def655a023b3142313873e6958a56e53230566 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase3_evaluations.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Audit complete Phase 3 official-validation outputs.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path + + +def json_finite(value) -> bool: + if isinstance(value, float): + return math.isfinite(value) + if isinstance(value, dict): + return all(json_finite(item) for item in value.values()) + if isinstance(value, (list, tuple)): + return all(json_finite(item) for item in value) + return True + + +def audit_csv(path: Path, expected_rows: int) -> tuple[int, bool]: + rows = 0 + finite = True + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + rows += 1 + for value in row.values(): + if value in (None, ""): + continue + try: + numeric = float(value) + except ValueError: + continue + finite = finite and math.isfinite(numeric) + return rows, finite and rows == expected_rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("evaluation_root", type=Path) + parser.add_argument("--expected-evaluations", type=int, required=True) + parser.add_argument("--expected-clips", type=int, default=1495) + parser.add_argument("--expected-frames", type=int, default=11638) + parser.add_argument("--expected-frame-rows", type=int, default=23276) + parser.add_argument("--expected-transition-rows", type=int, default=30293) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + + reports = sorted(args.evaluation_root.glob("*/*/evaluation.json")) + records = [] + for path in reports: + report = json.loads(path.read_text(encoding="utf-8")) + frame_rows, frame_csv_valid = audit_csv( + path.parent / "per_hand_frame_metrics.csv", args.expected_frame_rows, + ) + transition_rows, transition_csv_valid = audit_csv( + path.parent / "per_temporal_transition_metrics.csv", + args.expected_transition_rows, + ) + passed = ( + report.get("status") == "evaluated" + and report.get("official_test_used") is False + and report.get("split_role") == "official_validation" + and report.get("clips") == args.expected_clips + and report.get("frames") == args.expected_frames + and json_finite(report) + and frame_csv_valid + and transition_csv_valid + ) + records.append({ + "run": path.parents[1].name, + "role": path.parent.name, + "report": str(path), + "checkpoint_sha256": report.get("checkpoint", {}).get("sha256"), + "frame_rows": frame_rows, + "transition_rows": transition_rows, + "passed": passed, + }) + + passed = len(records) == args.expected_evaluations and all( + record["passed"] for record in records + ) + payload = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "evaluations": len(records), + "expected_evaluations": args.expected_evaluations, + "total_frame_rows": sum(record["frame_rows"] for record in records), + "total_transition_rows": sum(record["transition_rows"] for record in records), + "records": records, + } + output = args.output or args.evaluation_root / "evaluation_audit.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": payload["status"], "evaluations": len(records), + "output": str(output), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase3_periodic_checkpoints.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase3_periodic_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..800daf71cffb5e2c37ca0ecb20384214bdd44b88 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase3_periodic_checkpoints.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Audit periodic Phase 3 checkpoints with one isolated loader per run.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +from pathlib import Path + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def worker(checkpoint_path: Path) -> None: + import torch + + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + model_finite = all( + not torch.is_tensor(value) or torch.isfinite(value).all().item() + for value in checkpoint.get("model", {}).values() + ) + print(json.dumps({ + "step": int(checkpoint["step"]), + "model_finite": model_finite, + "bytes": checkpoint_path.stat().st_size, + "sha256": sha256(checkpoint_path), + })) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_root", type=Path, nargs="?") + parser.add_argument("--step", type=int) + parser.add_argument("--expected-runs", type=int) + parser.add_argument("--run-prefix") + parser.add_argument("--output", type=Path) + parser.add_argument("--worker", type=Path) + args = parser.parse_args() + + if args.worker is not None: + worker(args.worker) + return + if args.run_root is None or args.step is None: + parser.error("run_root and --step are required") + + checkpoint_name = f"step_{args.step:07d}.pt" + run_dirs = sorted( + path.parent for path in args.run_root.glob(f"*/{checkpoint_name}") + if path.parent.is_dir() + and (args.run_prefix is None or path.parent.name.startswith(args.run_prefix)) + ) + if args.expected_runs is not None and len(run_dirs) != args.expected_runs: + raise ValueError( + f"expected {args.expected_runs} {checkpoint_name} files, found {len(run_dirs)}" + ) + + records = [] + for run_dir in run_dirs: + checkpoint_path = run_dir / checkpoint_name + process = subprocess.run( + [sys.executable, str(Path(__file__).resolve()), "--worker", str(checkpoint_path)], + check=True, capture_output=True, text=True, + ) + checkpoint_record = json.loads(process.stdout) + validation_rows = [ + json.loads(line) for line in (run_dir / "validation.jsonl").read_text( + encoding="utf-8" + ).splitlines() if line.strip() + ] + matching_validation = [ + row for row in validation_rows if int(row["step"]) == args.step + ] + provenance_path = run_dir / "run_provenance.json" + if not provenance_path.is_file(): + candidates = sorted(run_dir.glob("resume_provenance_*.json")) + if len(candidates) != 1: + raise FileNotFoundError( + f"expected one run/resume provenance file in {run_dir}" + ) + provenance_path = candidates[0] + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + records.append({ + "run": run_dir.name, + **checkpoint_record, + "run_commit": provenance.get("git_commit"), + "validation_records": len(matching_validation), + "validation_total_loss": ( + matching_validation[0]["losses"]["total"] + if len(matching_validation) == 1 else None + ), + }) + + passed = bool(records) and all( + record["step"] == args.step + and record["model_finite"] + and record["validation_records"] == 1 + for record in records + ) + result = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "expected_step": args.step, + "run_prefix": args.run_prefix, + "runs": records, + } + suffix = f"{args.step // 1000}k" if args.step % 1000 == 0 else str(args.step) + prefix = f"{args.run_prefix.rstrip('_-')}_" if args.run_prefix else "" + output_path = ( + args.output + if args.output is not None + else args.run_root / f"checkpoint_audit_{prefix}{suffix}.json" + ) + if output_path.exists(): + raise FileExistsError(f"refusing to overwrite checkpoint audit: {output_path}") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": result["status"], "runs": len(records), "output": str(output_path) + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase3_run_checkpoints.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase3_run_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..e64c457dd74c0cd479f2c2f786f5f4e3c7ad56b5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase3_run_checkpoints.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Audit one completed Phase 3 run in an isolated process.""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +from pathlib import Path + +import torch + + +FINAL_ROLES = { + "step_100k": "step_0100000.pt", + "best_absolute": "best.pt", + "best_z": "best_z.pt", + "final": "step_0100000_final.pt", +} + + +def load_roles(path: Path | None) -> dict[str, str]: + if path is None: + return dict(FINAL_ROLES) + values = json.loads(path.read_text(encoding="utf-8")) + if ( + not isinstance(values, dict) + or not values + or any(not isinstance(role, str) or not role for role in values) + or any( + not isinstance(filename, str) or Path(filename).name != filename + for filename in values.values() + ) + ): + raise ValueError("checkpoint spec must be a non-empty role-to-filename JSON object") + return values + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_dir", type=Path) + parser.add_argument("--completed-step", type=int, default=100_000) + parser.add_argument("--checkpoint-spec", type=Path) + args = parser.parse_args() + roles = load_roles(args.checkpoint_spec) + summary = json.loads((args.run_dir / "summary.json").read_text(encoding="utf-8")) + result = { + "run": args.run_dir.name, + "summary_status": summary.get("status"), + "completed_step": summary.get("completed_step"), + "official_test_used": False, + "roles": {}, + } + for role, filename in roles.items(): + path = args.run_dir / filename + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + finite = all( + not torch.is_tensor(value) or torch.isfinite(value).all().item() + for value in checkpoint.get("model", {}).values() + ) + result["roles"][role] = { + "path": str(path), + "bytes": path.stat().st_size, + "sha256": sha256(path), + "step": int(checkpoint["step"]), + "model_finite": finite, + } + del checkpoint + gc.collect() + result["status"] = "passed" if ( + result["summary_status"] == "completed" + and result["completed_step"] == args.completed_step + and all(item["model_finite"] for item in result["roles"].values()) + ) else "failed" + output = args.run_dir / "final_checkpoint_audit.json" + output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"run": args.run_dir.name, "status": result["status"]})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase4_visualizations.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase4_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..afb6efba5a62c71bf21add06f75168566c1a33f0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase4_visualizations.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Audit raw/filtered Phase 4 videos and deterministic rerender pixels.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def fraction(value: str) -> float: + numerator, denominator = value.split("/", 1) + return float(numerator) / float(denominator) + + +def probe_video(path: Path) -> dict[str, object]: + process = subprocess.run([ + "ffprobe", "-v", "error", "-select_streams", "v:0", + "-show_entries", "stream=codec_name,pix_fmt,width,height,avg_frame_rate,nb_frames,duration", + "-of", "json", str(path), + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) + streams = json.loads(process.stdout).get("streams", []) + if len(streams) != 1: + raise ValueError(f"expected one video stream: {path}") + stream = streams[0] + return { + "codec": stream.get("codec_name"), + "pixel_format": stream.get("pix_fmt"), + "width": int(stream["width"]), "height": int(stream["height"]), + "fps": fraction(stream["avg_frame_rate"]), + "frames": int(stream["nb_frames"]), + "duration_seconds": float(stream["duration"]), + } + + +def decoded_frame_audit(path: Path, expected_frames: int) -> list[dict[str, object]]: + capture = cv2.VideoCapture(str(path)) + if not capture.isOpened(): + raise RuntimeError(f"cannot decode video: {path}") + records = [] + try: + for index in sorted({0, expected_frames // 2, expected_frames - 1}): + capture.set(cv2.CAP_PROP_POS_FRAMES, index) + ok, frame = capture.read() + if not ok or frame is None: + raise RuntimeError(f"cannot decode frame {index}: {path}") + std = float(frame.std()) + nonzero_fraction = float(np.count_nonzero(frame) / frame.size) + if std < 1.0 or nonzero_fraction < 0.05: + raise ValueError(f"blank/degenerate frame {index}: {path}") + records.append({ + "frame_index": index, "std": std, + "nonzero_fraction": nonzero_fraction, + "pixel_sha256": hashlib.sha256(frame.tobytes()).hexdigest(), + }) + finally: + capture.release() + return records + + +def audit_video( + path: Path, + *, + expected_frames: int, + expected_fps: float, + expected_sha256: str | None = None, + require_h264: bool = False, +) -> dict[str, object]: + if not path.is_file(): + raise FileNotFoundError(path) + digest = sha256(path) + if expected_sha256 is not None and digest != expected_sha256: + raise ValueError(f"video SHA256 mismatch: {path}") + probe = probe_video(path) + if probe["frames"] != expected_frames: + raise ValueError(f"video frame count mismatch: {path}") + if abs(float(probe["fps"]) - expected_fps) > 1e-3: + raise ValueError(f"video fps mismatch: {path}") + if require_h264 and ( + probe["codec"] != "h264" or probe["pixel_format"] != "yuv420p" + ): + raise ValueError(f"filtered video codec contract mismatch: {path}") + return { + "path": str(path.resolve()), "sha256": digest, **probe, + "decoded_frames": decoded_frame_audit(path, expected_frames), + "passed": True, + } + + +def deterministic_frame_hash_audit( + primary: dict[str, Any], rerun: dict[str, Any], +) -> int: + def index(manifest: dict[str, Any]) -> dict[tuple[str, str, str], list[str]]: + return { + (record["take"], record["condition"], video_name): video["frame_pixel_sha256"] + for record in manifest["cases"] + for video_name, video in record["videos"].items() + } + left, right = index(primary), index(rerun) + if left.keys() != right.keys(): + raise ValueError("deterministic video case grid mismatch") + for key in left: + if left[key] != right[key]: + raise ValueError(f"deterministic frame pixel mismatch: {key}") + return sum(len(values) for values in left.values()) + + +def audit_raw_manifest(manifest: dict[str, Any]) -> list[dict[str, object]]: + if manifest.get("status") != "complete" or manifest.get("official_test_used") is not False: + raise ValueError("invalid raw video manifest") + fps = float(manifest["visualization_fps"]) + records = [] + for case in manifest["cases"]: + frame_count = len(case["frame_ids"]) + for role, path in case["videos"].items(): + records.append({ + "set": "raw_model_primary_results", "take": case["take"], + "condition": "raw", "role": role, + **audit_video( + Path(path), expected_frames=frame_count, expected_fps=fps, + ), + }) + return records + + +def audit_filtered_manifest(manifest: dict[str, Any]) -> list[dict[str, object]]: + if ( + manifest.get("status") != "complete" + or manifest.get("official_test_used") is not False + or manifest.get("result_role") != "filtered_inference_secondary_results" + ): + raise ValueError("invalid filtered video manifest") + records = [] + expected_roles = { + "raw_vs_filtered_30fps", "raw_vs_filtered_4fps", + "failure_diagnostic_30fps", + } + for case in manifest["cases"]: + if set(case["videos"]) != expected_roles: + raise ValueError("filtered video role grid mismatch") + for role, video in case["videos"].items(): + records.append({ + "set": "filtered_inference_secondary_results", + "take": case["take"], "condition": case["condition"], + "role": role, + **audit_video( + Path(video["path"]), expected_frames=int(video["frames"]), + expected_fps=float(video["fps"]), + expected_sha256=video["sha256"], require_h264=True, + ), + }) + return records + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--raw-manifest", type=Path, required=True) + parser.add_argument("--filtered-manifest", type=Path, required=True) + parser.add_argument("--filtered-rerun-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite visualization audit: {args.output}") + raw = json.loads(args.raw_manifest.read_text(encoding="utf-8")) + filtered = json.loads(args.filtered_manifest.read_text(encoding="utf-8")) + rerun = json.loads(args.filtered_rerun_manifest.read_text(encoding="utf-8")) + records = audit_raw_manifest(raw) + records.extend(audit_filtered_manifest(filtered)) + records.extend(audit_filtered_manifest(rerun)) + compared_frames = deterministic_frame_hash_audit(filtered, rerun) + report = { + "status": "passed", + "official_test_used": False, + "videos": len(records), + "deterministic_frame_hashes_compared": compared_frames, + "raw_model_primary_results_kept_separate": True, + "filtered_inference_secondary_results_kept_separate": True, + "records": records, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "passed", "videos": len(records), + "deterministic_frame_hashes_compared": compared_frames, + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_alignment_visualizations.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_alignment_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..3ebd0b9fb31f916e3a2c0aaa08e79f95d53b848a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_alignment_visualizations.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Audit deterministic Phase 5 alignment diagnostic images.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def case_without_path(case: dict[str, Any]) -> dict[str, Any]: + return {key: value for key, value in case.items() if key not in ("image", "image_sha256")} + + +def image_audit(case: dict[str, Any]) -> dict[str, Any]: + path = Path(case["image"]) + digest = sha256(path) + if digest != case["image_sha256"]: + raise ValueError(f"manifest image hash mismatch: {path}") + image = cv2.imread(str(path), cv2.IMREAD_COLOR) + if image is None: + raise ValueError(f"cannot decode diagnostic image: {path}") + std = float(image.std()) + nonzero_fraction = float(np.count_nonzero(image) / image.size) + if min(image.shape[:2]) < 480 or std < 5.0 or nonzero_fraction < 0.2: + raise ValueError(f"blank or degenerate diagnostic image: {path}") + return { + "role": case["role"], "path": str(path.resolve()), "sha256": digest, + "width": int(image.shape[1]), "height": int(image.shape[0]), + "pixel_std": std, "nonzero_fraction": nonzero_fraction, + } + + +def audit_manifests( + primary: dict[str, Any], rerun: dict[str, Any], +) -> dict[str, Any]: + for manifest in (primary, rerun): + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_validation_secondary_failure_diagnostic" + or manifest.get("official_test_used") is not False + or manifest.get("used_for_model_or_threshold_selection") is not False + ): + raise ValueError("invalid alignment visualization manifest contract") + left = {case["role"]: case for case in primary["cases"]} + right = {case["role"]: case for case in rerun["cases"]} + if left.keys() != right.keys() or len(left) != len(primary["cases"]): + raise ValueError("visualization role grid mismatch or duplicate role") + primary_records, rerun_records = [], [] + for role in left: + if case_without_path(left[role]) != case_without_path(right[role]): + raise ValueError(f"visualization case metadata mismatch: {role}") + primary_record = image_audit(left[role]) + rerun_record = image_audit(right[role]) + if primary_record["sha256"] != rerun_record["sha256"]: + raise ValueError(f"deterministic image hash mismatch: {role}") + primary_records.append(primary_record) + rerun_records.append(rerun_record) + return { + "status": "passed", + "result_role": "deterministic_official_validation_visualization_audit", + "cases": len(left), + "deterministic_image_hashes_compared": len(left), + "primary": primary_records, + "rerun": rerun_records, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--primary-manifest", type=Path, required=True) + parser.add_argument("--rerun-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError("visualization audit refuses to overwrite output") + primary = json.loads(args.primary_manifest.read_text(encoding="utf-8")) + rerun = json.loads(args.rerun_manifest.read_text(encoding="utf-8")) + report = audit_manifests(primary, rerun) + report.update({ + "primary_manifest": str(args.primary_manifest.resolve()), + "rerun_manifest": str(args.rerun_manifest.resolve()), + }) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "cases": report["cases"], + "output": str(args.output), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_oof_bank.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..3d6814f9f1d8ebb1112e0086b5e5f95a44cd9f77 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_oof_bank.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python3 +"""Audit Phase 5 group-heldout coarse banks before refiner fitting.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + + +TAIL_ADMISSION_P95_MM = 40.0 +SEEDS = (20260716, 20260717, 20260718) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def distribution(values_m: np.ndarray) -> dict[str, float | int]: + values_mm = np.asarray(values_m, dtype=np.float64).reshape(-1) * 1000.0 + values_mm = values_mm[np.isfinite(values_mm)] + if not values_mm.size: + raise ValueError("cannot summarize an empty residual distribution") + absolute = np.abs(values_mm) + p95 = float(np.percentile(absolute, 95)) + return { + "count": int(len(values_mm)), + "signed_mean_mm": float(values_mm.mean()), + "signed_std_mm": float(values_mm.std()), + "mae_mm": float(absolute.mean()), + "p50_mm": float(np.percentile(absolute, 50)), + "p90_mm": float(np.percentile(absolute, 90)), + "p95_mm": p95, + "p99_mm": float(np.percentile(absolute, 99)), + "cvar95_mm": float(absolute[absolute >= p95].mean()), + "maximum_mm": float(absolute.max()), + } + + +def size_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 64.0, "small", np.where(values < 128.0, "medium", "large")) + + +def depth_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 0.5, "near", np.where(values < 0.8, "middle", "far")) + + +def validity_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 0.25, "low", np.where(values < 0.60, "partial", "strong")) + + +def validate_bank_manifest(path: Path) -> dict[str, Any]: + manifest = json.loads(path.read_text(encoding="utf-8")) + required = ( + manifest.get("status") == "complete", + manifest.get("bank_version") == 2, + manifest.get("scope") == "full_fold", + manifest.get("result_role") == "official_train_group_heldout_oof_predictions", + manifest.get("leakage_audit", {}).get("passed") is True, + manifest.get("official_validation_used_for_assignment") is False, + manifest.get("official_test_used") is False, + manifest.get("oracle_information_at_inference") is False, + ) + if not all(required): + raise ValueError(f"OOF audit requires a complete leakage-free full-fold bank: {path}") + return manifest + + +def load_oof_banks(bank_dirs: list[Path]) -> tuple[dict[str, np.ndarray], list[dict[str, Any]]]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + manifests = [] + observed_pairs: set[tuple[int, str]] = set() + keys_by_checkpoint: dict[str, set[str]] = defaultdict(set) + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = validate_bank_manifest(manifest_path) + manifests.append(manifest) + fold = int(manifest["fold"]) + checkpoint = str(manifest["checkpoint"]["sha256"]) + pair = (fold, checkpoint) + if pair in observed_pairs: + raise ValueError(f"duplicate fold/checkpoint bank: {pair}") + observed_pairs.add(pair) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take bank hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in ( + "frame_id", "frame_valid", "mano_annotation_valid", + "translation_residual_m", "target_wrist_translation", + "coarse_hand_scale_px", "alignment_valid_fraction", + )} + valid = arrays["frame_valid"].astype(bool)[:, None] & arrays[ + "mano_annotation_valid" + ].astype(bool) + time = len(arrays["frame_id"]) + side = np.broadcast_to(np.asarray(("left", "right"))[None], (time, 2)) + frame = np.broadcast_to(arrays["frame_id"][:, None], (time, 2)) + take = str(take_record["take"]) + subject, action_family = take.split("/")[:2] + sample_keys = np.asarray([ + f"{take}|{int(frame_id)}|{hand}" + for frame_id, hand in zip(frame[valid], side[valid], strict=True) + ]) + duplicate_keys = keys_by_checkpoint[checkpoint].intersection(sample_keys.tolist()) + if duplicate_keys: + raise ValueError(f"duplicate samples within checkpoint bank: {take}") + keys_by_checkpoint[checkpoint].update(sample_keys.tolist()) + count = int(valid.sum()) + chunks["residual_z_m"].append(arrays["translation_residual_m"][..., 2][valid]) + chunks["side"].append(side[valid]) + chunks["frame_id"].append(frame[valid]) + chunks["sample_key"].append(sample_keys) + chunks["subject"].append(np.full(count, subject)) + chunks["action_family"].append(np.full(count, action_family)) + chunks["take"].append(np.full(count, take)) + chunks["fold"].append(np.full(count, fold, dtype=np.int16)) + chunks["coarse_seed"].append(np.full(count, int(manifest.get("seed", -1)), dtype=np.int64)) + chunks["checkpoint"].append(np.full(count, checkpoint)) + chunks["hand_scale_px"].append(arrays["coarse_hand_scale_px"][valid]) + chunks["wrist_depth_m"].append(arrays["target_wrist_translation"][..., 2][valid]) + chunks["local_depth_valid_fraction"].append(arrays["alignment_valid_fraction"][valid]) + if {int(manifest["fold"]) for manifest in manifests} != {0, 1, 2}: + raise ValueError("OOF audit requires coverage of folds 0/1/2") + return {key: np.concatenate(values) for key, values in chunks.items()}, manifests + + +def validation_reference(a1_root: Path) -> tuple[list[dict[str, Any]], np.ndarray]: + rows = [] + values = [] + for seed in SEEDS: + with np.load(a1_root / f"seed_{seed}" / "validation" / "features.npz", allow_pickle=False) as archive: + residual = archive["target_residual_z_m"].astype(np.float64) + rows.append({"seed": seed, **distribution(residual)}) + values.append(residual) + return rows, np.concatenate(values) + + +def cross_checkpoint_correlations(samples: dict[str, np.ndarray]) -> dict[str, Any]: + maps: dict[str, dict[str, float]] = defaultdict(dict) + metadata: dict[str, dict[str, int]] = {} + for checkpoint, key, residual, fold, seed in zip( + samples["checkpoint"], samples["sample_key"], samples["residual_z_m"], + samples["fold"], samples["coarse_seed"], strict=True, + ): + checkpoint = str(checkpoint) + maps[checkpoint][str(key)] = float(residual) + metadata[checkpoint] = {"fold": int(fold), "seed": int(seed)} + results = {} + checkpoints = sorted(maps) + for left_index, left in enumerate(checkpoints): + for right in checkpoints[left_index + 1:]: + overlap = sorted(set(maps[left]).intersection(maps[right])) + name = f"{left[:12]}_{right[:12]}" + if len(overlap) < 2: + results[name] = { + "status": "unavailable_no_overlapping_group_heldout_samples", + "overlap": len(overlap), + "pearson": None, + "left": {"checkpoint": left, **metadata[left]}, + "right": {"checkpoint": right, **metadata[right]}, + } + else: + x = np.asarray([maps[left][key] for key in overlap]) + y = np.asarray([maps[right][key] for key in overlap]) + results[name] = { + "status": "available", + "overlap": len(overlap), + "pearson": float(np.corrcoef(x, y)[0, 1]), + "left": {"checkpoint": left, **metadata[left]}, + "right": {"checkpoint": right, **metadata[right]}, + } + return results + + +def grouped_rows(samples: dict[str, np.ndarray]) -> list[dict[str, Any]]: + residual = samples["residual_z_m"] + groups: dict[str, np.ndarray] = { + "fold": samples["fold"].astype(str), + "checkpoint": samples["checkpoint"], + "side": samples["side"], + "subject": samples["subject"], + "action_family": samples["action_family"], + "take": samples["take"], + "hand_size": size_bucket(samples["hand_scale_px"]), + "wrist_depth": depth_bucket(samples["wrist_depth_m"]), + "local_depth_validity": validity_bucket(samples["local_depth_valid_fraction"]), + } + if np.all(samples["coarse_seed"] >= 0): + groups["coarse_seed"] = samples["coarse_seed"].astype(str) + rows = [{"source": "oof", "group": "all", "value": "all", **distribution(residual)}] + for field, values in groups.items(): + for value in sorted(set(values.tolist())): + rows.append({ + "source": "oof", "group": field, "value": value, + **distribution(residual[values == value]), + }) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--validation-a1-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("OOF audit refuses to overwrite outputs") + samples, manifests = load_oof_banks(args.bank_dir) + oof = distribution(samples["residual_z_m"]) + validation_rows, validation_values = validation_reference(args.validation_a1_root) + validation = distribution(validation_values) + quantiles = np.linspace(0.0, 1.0, 101) + quantile_l1_mm = float(np.mean(np.abs( + np.quantile(np.abs(samples["residual_z_m"]), quantiles) + - np.quantile(np.abs(validation_values), quantiles) + )) * 1000.0) + rows = grouped_rows(samples) + rows.extend({ + "source": "validation", "group": "seed", "value": row["seed"], + **{key: value for key, value in row.items() if key != "seed"}, + } for row in validation_rows) + rows.append({"source": "validation", "group": "all", "value": "all", **validation}) + tail_passed = bool(oof["p95_mm"] >= TAIL_ADMISSION_P95_MM) + report = { + "status": "passed" if tail_passed else "insufficient_oof_tail", + "experiment_class": "preregistered_data_admission_audit", + "residual_definition": "GT wrist z minus group-heldout coarse predicted wrist z", + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "folds": sorted({int(manifest["fold"]) for manifest in manifests}), + "checkpoints": sorted({str(manifest["checkpoint"]["sha256"]) for manifest in manifests}), + "coarse_seeds": sorted({ + int(manifest["seed"]) for manifest in manifests if manifest.get("seed") is not None + }), + "samples": len(samples["residual_z_m"]), + "takes": len(set(samples["take"].tolist())), + "oof": oof, + "validation_reference_by_seed": validation_rows, + "validation_reference_all": validation, + "absolute_residual_quantile_l1_distance_mm": quantile_l1_mm, + "tail_admission": { + "threshold_p95_mm": TAIL_ADMISSION_P95_MM, + "passed": tail_passed, + "rule": "do not fit a formal refiner if group-heldout OOF z P95 remains below 40 mm", + }, + "cross_checkpoint_pearson": cross_checkpoint_correlations(samples), + "leakage_audit_passed": all(manifest["leakage_audit"]["passed"] for manifest in manifests), + "official_validation_used_for_training_or_thresholds": False, + "official_test_used": False, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(json.dumps({ + "status": report["status"], "samples": report["samples"], "takes": report["takes"], + "oof": oof, "validation": validation, "official_test_used": False, + }, indent=2)) + if not tail_passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_periodic_checkpoints.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_periodic_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..d039ac0e31f689bff49638990e6f519f51a0a996 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_periodic_checkpoints.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Audit Phase 5 periodic checkpoints, logs, provenance, and validation contract.""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +from pathlib import Path + +import torch + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_tree(value: object) -> bool: + if torch.is_tensor(value): + return bool(torch.isfinite(value).all()) if value.is_floating_point() else True + if isinstance(value, dict): + return all(finite_tree(item) for item in value.values()) + if isinstance(value, (list, tuple)): + return all(finite_tree(item) for item in value) + return True + + +def audit_run(run_dir: Path, step: int, expected_validation_records: int) -> dict[str, object]: + checkpoint_path = run_dir / f"step_{step:07d}.pt" + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + checkpoint_record = { + "path": str(checkpoint_path.resolve()), + "bytes": checkpoint_path.stat().st_size, + "sha256": sha256(checkpoint_path), + "step": int(checkpoint["step"]), + "model_finite": finite_tree(checkpoint.get("model", {})), + "optimizer_finite": finite_tree(checkpoint.get("optimizer", {})), + } + del checkpoint + gc.collect() + + provenance = json.loads((run_dir / "run_provenance.json").read_text(encoding="utf-8")) + train_lines = [ + line for line in (run_dir / "train_metrics.jsonl").read_text(encoding="utf-8").splitlines() + if line.strip() + ] + last_train = json.loads(train_lines[-1]) if train_lines else {} + validation_path = run_dir / "validation.jsonl" + validation_rows = ( + [json.loads(line) for line in validation_path.read_text(encoding="utf-8").splitlines() if line.strip()] + if validation_path.is_file() else [] + ) + matching_validation = [row for row in validation_rows if int(row["step"]) == step] + finite_validation = finite_tree(matching_validation) + passed = ( + checkpoint_record["step"] == step + and checkpoint_record["model_finite"] + and checkpoint_record["optimizer_finite"] + and provenance.get("git_status") in ("", None) + and int(last_train.get("step", -1)) >= step + and len(matching_validation) == expected_validation_records + and finite_validation + ) + return { + "run": run_dir.name, + "status": "passed" if passed else "failed", + "checkpoint": checkpoint_record, + "git_commit": provenance.get("git_commit"), + "git_status_clean": provenance.get("git_status") in ("", None), + "train_manifest": provenance.get("hashes", {}).get("train_manifest"), + "config": provenance.get("hashes", {}).get("config"), + "last_train_step": last_train.get("step"), + "last_gradient_norm": last_train.get("gradient_norm"), + "last_frames_per_s": last_train.get("frames_per_s"), + "validation_records_at_step": len(matching_validation), + "expected_validation_records_at_step": expected_validation_records, + "validation_finite": finite_validation, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_root", type=Path) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--expected-runs", type=int, required=True) + parser.add_argument("--expected-validation-records", type=int, choices=(0, 1), required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite audit: {args.output}") + checkpoint_name = f"step_{args.step:07d}.pt" + run_dirs = sorted(path.parent for path in args.run_root.glob(f"*/{checkpoint_name}")) + if len(run_dirs) != args.expected_runs: + raise ValueError( + f"expected {args.expected_runs} {checkpoint_name} files, found {len(run_dirs)}" + ) + records = [ + audit_run(run_dir, args.step, args.expected_validation_records) + for run_dir in run_dirs + ] + passed = bool(records) and all(record["status"] == "passed" for record in records) + report = { + "status": "passed" if passed else "failed", + "expected_step": args.step, + "expected_runs": args.expected_runs, + "expected_validation_records_at_step": args.expected_validation_records, + "runs": records, + "official_test_used": False, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "runs": len(records), "output": str(args.output), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_residual_shift.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_residual_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..62c3bfe1f2b6ba39dc8a5cfb4b4c19d0c926de49 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase5_residual_shift.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Audit in-fold train versus held-out validation coarse z residual shift.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import numpy as np + + +SEEDS = (20260716, 20260717, 20260718) + + +def distribution(values_m: np.ndarray) -> dict[str, float | int]: + values_mm = np.asarray(values_m, dtype=np.float64) * 1000.0 + absolute = np.abs(values_mm) + p95 = float(np.percentile(absolute, 95)) + return { + "count": int(len(values_mm)), + "signed_mean_mm": float(values_mm.mean()), + "mae_mm": float(absolute.mean()), + "p50_mm": float(np.percentile(absolute, 50)), + "p90_mm": float(np.percentile(absolute, 90)), + "p95_mm": p95, + "p99_mm": float(np.percentile(absolute, 99)), + "cvar95_mm": float(absolute[absolute >= p95].mean()), + } + + +def load_rows(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def size_bucket(value: str) -> str: + size = float(value) + return "small" if size < 64.0 else "medium" if size < 128.0 else "large" + + +def depth_bucket(value: str) -> str: + depth = float(value) + return "near" if depth < 0.5 else "middle" if depth < 0.8 else "far" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--a1-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("residual-shift audit refuses to overwrite outputs") + + split_values: dict[str, dict[int, np.ndarray]] = {"train": {}, "validation": {}} + split_rows: dict[str, list[dict[str, str]]] = {} + summary_rows = [] + group_rows = [] + for split in split_values: + metadata_reference: list[tuple[str, str, str]] | None = None + for seed in SEEDS: + root = args.a1_root / f"seed_{seed}" / split + with np.load(root / "features.npz", allow_pickle=False) as archive: + values = archive["target_residual_z_m"].astype(np.float64) + rows = load_rows(root / "samples.csv") + if len(rows) != len(values): + raise ValueError(f"feature/metadata length mismatch for {split}/{seed}") + metadata = [(row["take"], row["frame_id"], row["side"]) for row in rows] + if metadata_reference is None: + metadata_reference = metadata + split_rows[split] = rows + elif metadata != metadata_reference: + raise ValueError(f"sample alignment differs across seeds for {split}") + split_values[split][seed] = values + result = distribution(values) + summary_rows.append({"split": split, "seed": seed, "group": "all", "value": "all", **result}) + + groups: dict[tuple[str, str], list[int]] = {} + for index, row in enumerate(rows): + values_by_group = { + "side": row["side"], + "action_family": row["action_family"], + "hand_size": size_bucket(row["hand_size_px"]), + "wrist_depth": depth_bucket(row["wrist_depth_m"]), + "take": row["take"], + } + for field, value in values_by_group.items(): + groups.setdefault((field, value), []).append(index) + for (field, value), indices in sorted(groups.items()): + group_rows.append({ + "split": split, "seed": seed, "group": field, "value": value, + **distribution(values[np.asarray(indices, dtype=np.int64)]), + }) + + correlations = {} + for split, by_seed in split_values.items(): + matrix = np.corrcoef([by_seed[seed] for seed in SEEDS]) + correlations[split] = { + f"{left}_{right}": float(matrix[left_index, right_index]) + for left_index, left in enumerate(SEEDS) + for right_index, right in enumerate(SEEDS) + if left_index < right_index + } + gaps = {} + for seed in SEEDS: + train = distribution(split_values["train"][seed]) + validation = distribution(split_values["validation"][seed]) + gaps[str(seed)] = { + "mae_ratio_validation_over_train": validation["mae_mm"] / train["mae_mm"], + "p95_ratio_validation_over_train": validation["p95_mm"] / train["p95_mm"], + "mae_gap_mm": validation["mae_mm"] - train["mae_mm"], + "p95_gap_mm": validation["p95_mm"] - train["p95_mm"], + } + report = { + "status": "audited", + "experiment_class": "diagnostic_existing_predictions", + "source": "Phase 4 A1 frozen coarse feature banks", + "residual_definition": "GT wrist z minus coarse predicted wrist z", + "seeds": list(SEEDS), + "summary": summary_rows, + "cross_seed_pearson": correlations, + "validation_over_train_gap": gaps, + "sample_alignment_across_seeds": True, + "official_test_used": False, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + rows_to_write = summary_rows + group_rows + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows_to_write[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows_to_write) + print(json.dumps({ + "status": report["status"], + "train": [row for row in summary_rows if row["split"] == "train"], + "validation": [row for row in summary_rows if row["split"] == "validation"], + "correlations": correlations, + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase6_sequence_inference.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase6_sequence_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e78513782072066d17259a1a4014e154227187ec --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase6_sequence_inference.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Audit a frozen checkpoint through the bounded arbitrary-length API.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import time +from collections import defaultdict +from pathlib import Path + +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def clone_batch(batch: dict[str, object]) -> dict[str, object]: + return { + key: value.clone() if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, required=True) + parser.add_argument("--frames", type=int, default=257) + parser.add_argument("--take") + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output must not already exist") + if args.manifest.name != "official_val.jsonl": + parser.error("sequence audit is hard-gated to official validation") + if args.frames < 1 or args.window < 1: + parser.error("frames and window must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + configured_mode = config["model"].get( + "temporal_attention_mode", "bidirectional", + ) + expected_mode = "causal" if args.mode == "causal" else "bidirectional" + if configured_mode != expected_mode: + parser.error("config temporal mode differs from requested audit mode") + + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (1,), (1,), + ) + by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + by_take[clip.take].append(index) + take = args.take + if take is None: + take = next((name for name, indices in by_take.items() if len(indices) >= args.frames), None) + if take is None or len(by_take.get(take, ())) < args.frames: + raise ValueError("no requested take contains the audit frame count") + indices = by_take[take][: args.frames] + + loader = DataLoader( + Subset(dataset, indices), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.mode, window_size=args.window, + offline_stride=(args.window // 2 if args.mode == "offline" else None), + ), + device=device, autocast_dtype=dtype, + ) + frame_ids: list[int] = [] + + def frames(): + for batch in loader: + frame_ids.append(int(batch["frame_id"][0, 0])) + yield batch + + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + output = runner.infer(frames()) + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + output_time = int(output["wrist_root_translation"].shape[1]) + finite = all(torch.isfinite(value).all() for value in output.values()) + + invariance = None + if args.mode == "causal": + invariant_loader = DataLoader( + Subset(dataset, indices[:8]), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ) + first = list(invariant_loader) + full = runner._stack_frames(first) + perturbed = clone_batch(full) + perturbed["rgb"][:, 4:] = -perturbed["rgb"][:, 4:] + perturbed["depth_m"][:, 4:] = 0 + perturbed["depth_pixel_valid"][:, 4:] = False + perturbed["depth_available"][:, 4:] = False + prefix = { + key: value[:, :4] if torch.is_tensor(value) and value.ndim >= 2 + and value.shape[1] == 8 else value + for key, value in full.items() + } + full = runner._to_device(full) + perturbed = runner._to_device(perturbed) + prefix = runner._to_device(prefix) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + full_output = model(full) + perturbed_output = model(perturbed) + prefix_output = model(prefix) + future_delta = float(( + full_output["wrist_root_translation"][:, :4] + - perturbed_output["wrist_root_translation"][:, :4] + ).abs().max()) + monolithic_prefix_delta = float(( + full_output["wrist_root_translation"][:, :4] + - prefix_output["wrist_root_translation"] + ).abs().max()) + stream_full = runner.infer_causal(first)["wrist_root_translation"][:, :4] + stream_prefix = runner.infer_causal(first[:4])["wrist_root_translation"] + prefix_delta = float((stream_full - stream_prefix).abs().max()) + invariance = { + "future_perturbation_max_abs_m": future_delta, + "future_perturbation_bitwise_zero": future_delta == 0.0, + "streaming_prefix_max_abs_m": prefix_delta, + "prefix_tolerance_m": 1e-6, + "prefix_passed": prefix_delta <= 1e-6, + "monolithic_full_vs_short_batch_max_abs_m": monolithic_prefix_delta, + "monolithic_batch_size_numerical_invariance": monolithic_prefix_delta <= 1e-6, + } + + invariance_passed = invariance is None or ( + invariance["future_perturbation_bitwise_zero"] and invariance["prefix_passed"] + ) + order_passed = len(frame_ids) == args.frames and all( + right > left for left, right in zip(frame_ids, frame_ids[1:]) + ) + memory_passed = ( + runner.maximum_resident_frames <= args.window + and runner.maximum_input_buffer_frames <= ( + args.window if args.mode == "causal" else args.window + args.window // 2 + ) + ) + report = { + "status": "passed" if ( + finite and output_time == args.frames and order_passed + and memory_passed and invariance_passed + ) else "failed", + "experiment": "P6_S5_length_generalized_inference", + "experiment_class": "frozen_checkpoint_engineering_audit", + "official_test_used": False, + "official_validation_used_for_selection": False, + "mode": args.mode, + "causal": args.mode == "causal", + "window": args.window, + "offline_stride": args.window // 2 if args.mode == "offline" else None, + "stitching": "center" if args.mode == "offline" else None, + "take": take, + "requested_frames": args.frames, + "output_frames": output_time, + "frame_ids_strictly_increasing": order_passed, + "finite": finite, + "elapsed_s": elapsed, + "throughput_fps": args.frames / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "maximum_gpu_window_frames": runner.maximum_resident_frames, + "maximum_cpu_input_buffer_frames": runner.maximum_input_buffer_frames, + "invariance": invariance, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": int(checkpoint["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if report["status"] != "passed": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase6_variable_length.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase6_variable_length.py new file mode 100644 index 0000000000000000000000000000000000000000..85097343ce2bb9177f32360d1e752196baa31a45 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase6_variable_length.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +"""Audit the frozen Phase 5 model's variable-length and causality contract.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import statistics +import subprocess +import time +from collections import defaultdict +from pathlib import Path +from typing import Any + +import torch +import yaml + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +LENGTHS = (1, 2, 4, 8, 16, 32, 64) +OUTPUT_KEYS = ( + "hand_tokens", "joint2d_norm", "mano_rotation_matrices", "mano_shape", + "wrist_root_translation", "joints_camera", "vertices_camera", +) +MODEL_INPUT_KEYS = ( + "rgb", "depth_m", "depth_pixel_valid", "K", "K_available", + "depth_available", "frame_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_model( + config: dict[str, Any], checkpoint: Path, device: torch.device, +) -> tuple[BimanualReconstructionModel, int]: + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(checkpoint, model, optimizer=None, map_location=device) + return model, int(state["step"]) + + +def contiguous_real_sequence( + root: Path, manifest: Path, resolution_hw: tuple[int, int], length: int, +) -> tuple[dict[str, torch.Tensor], str, list[int]]: + dataset = H2OCam4Dataset( + root, manifest, resolution_hw, clip_lengths=(1,), strides=(1,), + window_step=1, allow_partial=False, + ) + by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + by_take[clip.take].append(index) + selected: list[int] | None = None + selected_take = "" + for take, indices in by_take.items(): + frame_ids = [dataset.clips[index].frame_ids[0] for index in indices] + for start in range(0, len(indices) - length + 1): + candidate = frame_ids[start : start + length] + if all(right == left + 1 for left, right in zip(candidate[:-1], candidate[1:])): + selected = indices[start : start + length] + selected_take = take + break + if selected is not None: + break + if selected is None: + raise RuntimeError(f"no contiguous {length}-frame validation prefix") + samples = [dataset[index] for index in selected] + batch_frames = collate_h2o_clips(samples) + sequence = {} + for key in MODEL_INPUT_KEYS: + value = batch_frames[key] + if value.shape[0] != length or value.shape[1] != 1: + raise ValueError(f"unexpected T=1 collate shape for {key}: {value.shape}") + sequence[key] = value[:, 0].unsqueeze(0) + frame_ids = batch_frames["frame_id"][:, 0].tolist() + return sequence, selected_take, [int(value) for value in frame_ids] + + +def prefix(batch: dict[str, torch.Tensor], length: int, device: torch.device) -> dict[str, torch.Tensor]: + return {key: value[:, :length].to(device, non_blocking=True) for key, value in batch.items()} + + +def run_once( + model: BimanualReconstructionModel, + batch: dict[str, torch.Tensor], + dtype: torch.dtype, +) -> dict[str, Any]: + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + return model(batch) + + +def output_snapshot(output: dict[str, Any]) -> dict[str, torch.Tensor]: + return {key: output[key].detach().float().cpu() for key in OUTPUT_KEYS} + + +def max_prefix_differences( + left: dict[str, torch.Tensor], right: dict[str, torch.Tensor], length: int, +) -> dict[str, float]: + return { + key: float((left[key][:, :length] - right[key][:, :length]).abs().max()) + for key in OUTPUT_KEYS + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--repeats", type=int, default=2) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("variable-length audit is hard-gated to official validation") + if args.output.exists(): + parser.error("output must not exist") + if args.repeats < 1: + parser.error("repeats must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + real, take, frame_ids = contiguous_real_sequence( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), max(LENGTHS), + ) + model, step = build_model(config, args.checkpoint, device) + results = [] + snapshots: dict[int, dict[str, torch.Tensor]] = {} + for length in LENGTHS: + current = prefix(real, length, device) + run_once(model, current, dtype) + torch.cuda.synchronize(device) + torch.cuda.reset_peak_memory_stats(device) + latencies = [] + output: dict[str, Any] | None = None + repeats = args.repeats if length <= 16 else 1 + for _ in range(repeats): + start = time.perf_counter() + output = run_once(model, current, dtype) + torch.cuda.synchronize(device) + latencies.append(1000.0 * (time.perf_counter() - start)) + assert output is not None + snapshots[length] = output_snapshot(output) + temporal_attention = output["attention"]["temporal_attention"] + finite = { + key: bool(torch.isfinite(output[key]).all().item()) for key in OUTPUT_KEYS + } + results.append({ + "T": length, + "finite": finite, + "all_finite": all(finite.values()), + "hand_token_shape": list(output["hand_tokens"].shape), + "temporal_attention_shape": list(temporal_attention.shape), + "temporal_attention_elements": temporal_attention.numel(), + "temporal_attention_bytes": temporal_attention.numel() * temporal_attention.element_size(), + "latency_ms_p50": float(statistics.median(latencies)), + "latency_ms_samples": latencies, + "peak_allocated_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + }) + del output, current + torch.cuda.empty_cache() + print(f"T={length} complete", flush=True) + + base8 = prefix(real, 8, device) + changed8 = {key: value.clone() for key, value in base8.items()} + changed8["rgb"][:, 4:] = 1.0 - changed8["rgb"][:, 4:] + changed8["depth_m"][:, 4:] = 0.0 + changed8["depth_pixel_valid"][:, 4:] = False + changed8["depth_available"][:, 4:] = False + original8 = output_snapshot(run_once(model, base8, dtype)) + perturbed8 = output_snapshot(run_once(model, changed8, dtype)) + future_differences = max_prefix_differences(original8, perturbed8, 4) + prefix_differences = max_prefix_differences(snapshots[8], snapshots[4], 4) + window_comparisons = [] + reference = snapshots[64] + for length in LENGTHS: + first_joint_delta_mm = float( + torch.linalg.vector_norm( + snapshots[length]["joints_camera"][:, 0] + - reference["joints_camera"][:, 0], dim=-1, + ).mean() * 1000.0 + ) + window_comparisons.append({ + "T": length, + "first_frame_joint_delta_vs_T64_mm": first_joint_delta_mm, + "first_frame_wrist_max_delta_vs_T64_m": float( + (snapshots[length]["wrist_root_translation"][:, 0] + - reference["wrist_root_translation"][:, 0]).abs().max() + ), + }) + report = { + "status": "completed", + "experiment": "P6_S0_variable_length_contract", + "official_validation_used": True, + "official_validation_used_for_selection": False, + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + "device": args.gpu, + "take": take, + "frame_ids": frame_ids, + "forward_results": results, + "window_comparisons": window_comparisons, + "future_perturbation": { + "changed_frames": [4, 5, 6, 7], + "compared_frames": [0, 1, 2, 3], + "maximum_absolute_differences": future_differences, + "strict_zero_passed": all(value == 0.0 for value in future_differences.values()), + }, + "prefix_invariance": { + "prefix_T": 4, "full_T": 8, + "maximum_absolute_differences": prefix_differences, + "strict_zero_passed": all(value == 0.0 for value in prefix_differences.values()), + }, + "contract": { + "tensor_shape_variable_length": all(item["all_finite"] for item in results), + "offline_bidirectional_variable_length": True, + "bounded_memory_causal_streaming": False, + "historical_causal_description": "causal z-state postprocessor over noncausal T=8 coarse predictions", + }, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], + "future_strict_zero": report["future_perturbation"]["strict_zero_passed"], + "prefix_strict_zero": report["prefix_invariance"]["strict_zero_passed"], + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_arctic.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_arctic.py new file mode 100644 index 0000000000000000000000000000000000000000..782a56fcee3691d848037cb01ef48c6c9763b4c5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_arctic.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Deterministic numeric and visual audit for ARCTIC P2 train view 0.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + "max": float(array.max()), + } + + +def select_indices(rows: list[dict], count: int) -> list[int]: + recordings: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + recordings[(row["subject_id"], row["physical_recording_id"])].append(index) + strata: dict[str, list[int]] = defaultdict(list) + for (subject, _), indices in sorted(recordings.items()): + strata[subject].append(indices[len(indices) // 2]) + selected, cursor = [], 0 + while len(selected) < count: + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected.append(strata[subject][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) != count: + raise RuntimeError(f"only {len(selected)} subject/recording strata available") + return selected + + +def denormalize(image: torch.Tensor) -> np.ndarray: + value = image.permute(1, 2, 0).numpy() + return np.rint(np.clip((value * RGB_STD + RGB_MEAN) * 255.0, 0, 255)).astype(np.uint8) + + +def render(case: dict, output: Path) -> None: + image = case["image"].copy() + for side, color in enumerate(((40, 190, 250), (250, 100, 60))): + for point in case["joint2d"][side][case["joint_valid"][side]]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, color, -1) + cv2.putText( + image, f"{case['category']} {case['recording']}", (10, 24), + cv2.FONT_HERSHEY_SIMPLEX, .55, (255, 255, 255), 2, cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=16) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + dataset = ARCTICClipDataset(args.manifest, args.mano_root) + indices = select_indices(dataset.rows, args.clips) + enabled_regen, excluded_left, enabled_reprojection = [], [], [] + wrist_depth, hand_size, cases, hand_counts = [], [], [], [] + side_frames = {"left": 0, "right": 0} + root_relative_side_frames = {"left": 0, "right": 0} + root_relative_root_norm_mm: list[float] = [] + for index in indices: + sample = dataset[index] + enabled_regen.extend(sample["source_vertex_regen_error_mm"][sample["vertices_valid"]].tolist()) + left = sample["translation_valid"][:, 0] + excluded_left.extend(sample["source_vertex_regen_error_mm"][:, 0][left].tolist()) + for side_index, side in enumerate(("left", "right")): + valid = sample["joint3d_root_relative_valid"][:, side_index] + root_relative_side_frames[side] += int(valid.any(dim=-1).sum()) + root_relative_root_norm_mm.extend( + (torch.linalg.vector_norm( + sample["joint3d_root_relative"][:, side_index, 0], dim=-1, + )[valid[:, 0]] * 1000.0).tolist() + ) + enabled_reprojection.extend( + sample["projection_roundtrip_error_px"][sample["reprojection_valid"]].tolist() + ) + for frame in range(len(sample["frame_valid"])): + valid_hands = sample["translation_valid"][frame] + hand_counts.append(int(valid_hands.sum())) + sizes = [] + for side_index, side in enumerate(("left", "right")): + if not valid_hands[side_index]: + continue + side_frames[side] += 1 + wrist_depth.append(float(sample["wrist_root_translation"][frame, side_index, 2])) + points = sample["joint2d"][frame, side_index][sample["joint2d_valid"][frame, side_index]] + if len(points): + sizes.append(float((points.max(0).values - points.min(0).values).max())) + hand_size.extend(sizes) + points = sample["joint2d"][frame][sample["joint2d_valid"][frame]] + height, width = sample["rgb"].shape[-2:] + border = ( + float(torch.stack((points[:, 0], points[:, 1], width - points[:, 0], height - points[:, 1])).amin()) + if len(points) else float("inf") + ) + z = sample["wrist_root_translation"][frame, valid_hands, 2] + cases.append({ + "recording": sample["physical_recording_id"], + "image": denormalize(sample["rgb"][frame]), + "joint2d": sample["joint2d"][frame].numpy(), + "joint_valid": sample["joint2d_valid"][frame].numpy(), + "count": int(valid_hands.sum()), + "z": float(z.mean()) if len(z) else float("nan"), + "size": max(sizes, default=0.0), "border": border, + }) + valid_cases = [row for row in cases if row["count"] > 0] + selectors = { + "near": min(valid_cases, key=lambda row: row["z"]), + "far": max(valid_cases, key=lambda row: row["z"]), + "small": min(valid_cases, key=lambda row: row["size"]), + "border": min(valid_cases, key=lambda row: row["border"]), + "bimanual": next(row for row in valid_cases if row["count"] == 2), + } + single = next((row for row in valid_cases if row["count"] == 1), None) + if single is not None: + selectors["single"] = single + visuals = {} + for category, value in selectors.items(): + path = args.output_dir / f"{category}.png" + render(dict(value, category=category), path) + visuals[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + report = { + "status": "pending", "official_test_used": False, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clips": len(indices), "frames": len(cases), "clip_indices": indices, + "side_frames": side_frames, + "no_visible_hand_frames": hand_counts.count(0), + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "source_regeneration_mm": quantiles(enabled_regen), + "enabled_reprojection_roundtrip_px": quantiles(enabled_reprojection), + "excluded_left_geometry_regeneration_mm": quantiles(excluded_left), + "wrist_depth_m": quantiles(wrist_depth), + "projected_hand_size_px": quantiles(hand_size), + "image_contract": "full 840x600 ego view (0.3x 2800x2000), cv2 undistort with scaled K/dist8, then full-frame resize/pad", + "partial_supervision_contract": { + "right": "2D/3D/translation/pose/shape/vertices/reprojection", + "left": "direct-2D/translation/pose only", + }, + "source_compatible_root_relative_joint3d": { + "side_frames": root_relative_side_frames, + "root_norm_mm": quantiles(root_relative_root_norm_mm), + "shape_vertices_enabled": False, + "claim": "source-compatible legacy MANO joint target only; not corrected-MANO regeneration", + }, + "visualizations": visuals, + } + passed = ( + len(cases) >= 100 and report["source_regeneration_mm"]["max"] < 1.0 + and report["enabled_reprojection_roundtrip_px"]["p95"] < 1.0 + and all(value > 0 for value in side_frames.values()) + and all(value > 0 for value in root_relative_side_frames.values()) + and report["source_compatible_root_relative_joint3d"]["root_norm_mm"]["max"] < 1e-4 + and report["bimanual_frames"] > 0 + ) + report["status"] = "passed" if passed else "failed" + (args.output_dir / "audit.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_egodexter.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_egodexter.py new file mode 100644 index 0000000000000000000000000000000000000000..acd74ce8142f1d6b95335fba94e4dbd155454225 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_egodexter.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Deterministic no-model EgoDexter source audit for Phase 7.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path + +import numpy as np + +from foundation_hand.data.egodexter_dataset import EgoDexterSequenceDataset, SEQUENCES + + +def finite_summary(values: np.ndarray) -> dict[str, float | int]: + values = values[np.isfinite(values)] + return { + "count": int(len(values)), + "median": float(np.median(values)), + "p95": float(np.quantile(values, .95)), + "max": float(values.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--decode-frames-per-sequence", type=int, default=25) + args = parser.parse_args() + if args.decode_frames_per_sequence < 1: + parser.error("--decode-frames-per-sequence must be positive") + report: dict[str, object] = { + "status": "numeric_adapter_passed_handedness_freeze_pending", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "dataset": "EgoDexter", + "training_or_selection_use": False, + "official_test_used": False, + "camera_frame": "depth_camera", + "depth_units_input": "millimeters", + "model_units": "meters", + "rgb_stream": "color_on_depth full frame", + "input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "sequence_handedness": "must be frozen before first model inference", + "sequences": {}, + } + total_frames = 0 + total_visible = 0 + total_annotated = 0 + for sequence in SEQUENCES: + dataset = EgoDexterSequenceDataset(args.root, sequence, hand_side="left") + xyz = dataset.fingertips_3d_m + valid = np.linalg.norm(xyz, axis=-1) > 0.0 + uv = np.full_like(xyz[..., :2], np.nan) + uv[..., 0] = ( + dataset.K_source[0, 0] * xyz[..., 0] + / np.where(valid, xyz[..., 2], np.nan) + dataset.K_source[0, 2] + ) + uv[..., 1] = ( + dataset.K_source[1, 1] * xyz[..., 1] + / np.where(valid, xyz[..., 2], np.nan) + dataset.K_source[1, 2] + ) + error = np.linalg.norm(uv - dataset.fingertips_2d, axis=-1)[valid] + sample_indices = np.linspace( + 0, len(dataset) - 1, + min(args.decode_frames_per_sequence, len(dataset)), dtype=np.int64, + ) + depth_valid_fraction = [] + for index in sample_indices: + _, depth_mm, _ = dataset._load(int(index)) + depth_valid_fraction.append(float((depth_mm > 0).mean())) + lines = (dataset.sequence_root / "annotation.txt_3D.txt").read_text( + encoding="utf-8", + ).splitlines() + sequence_report = { + "frames": len(dataset), + "visible_fingertips": int(valid.sum()), + "annotated_frames": int(np.any(valid, axis=1).sum()), + "partial_annotation_rows": sum( + len([group for group in line.split(";") if group.strip()]) < 5 + for line in lines + ), + "projection_roundtrip_px": finite_summary(error), + "decoded_frames": len(sample_indices), + "depth_valid_fraction_mean": float(np.mean(depth_valid_fraction)), + } + report["sequences"][sequence] = sequence_report + total_frames += len(dataset) + total_visible += int(valid.sum()) + total_annotated += int(np.any(valid, axis=1).sum()) + report["totals"] = { + "frames": total_frames, + "visible_fingertips": total_visible, + "annotated_frames": total_annotated, + "decoded_numeric_audit_frames": args.decode_frames_per_sequence * len(SEQUENCES), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_hoi4d.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_hoi4d.py new file mode 100644 index 0000000000000000000000000000000000000000..db2cfc39662dcb4bb7473cb83d81701c37149f39 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_hoi4d.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Deterministic numeric and visual audit of the Phase 7 HOI4D adapter.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + "max": float(array.max()), + } + + +def select_indices(rows: list[dict], count: int) -> list[int]: + strata: dict[tuple[str, str], list[int]] = {} + seen: set[str] = set() + for index, row in enumerate(rows): + side_sets = [set(value) for value in row["hand_sides"]] + hand_class = ( + "bimanual" if any(len(value) == 2 for value in side_sets) else + "left" if any("left" in value for value in side_sets) else "right" + ) + key = (row["subject_id"], hand_class) + if row["physical_recording_id"] in seen: + continue + seen.add(row["physical_recording_id"]) + strata.setdefault(key, []).append(index) + selected: list[int] = [] + keys = sorted(strata) + cursor = 0 + while len(selected) < count: + progress = False + for key in keys: + if cursor < len(strata[key]): + selected.append(strata[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) != count: + raise RuntimeError(f"only {len(selected)} stratified clips found") + return selected + + +def denormalize(image: torch.Tensor) -> np.ndarray: + value = image.permute(1, 2, 0).numpy() + return np.rint(np.clip((value * RGB_STD + RGB_MEAN) * 255.0, 0, 255)).astype(np.uint8) + + +def render(case: dict, output: Path) -> None: + image = case["image"].copy() + colors = ((40, 190, 250), (250, 100, 60)) + for side in range(2): + for point in case["joint2d"][side][case["joint_valid"][side]]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, colors[side], -1) + depth = case["depth"] + valid = depth > 0 + depth_color = np.zeros((*depth.shape, 3), dtype=np.uint8) + if valid.any(): + scale = np.quantile(depth[valid], .95) + normalized = np.clip(depth / max(scale, 1e-6), 0, 1) + depth_color = cv2.applyColorMap( + np.rint(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO, + )[..., ::-1] + depth_color[~valid] = 0 + combined = np.concatenate((image, depth_color), axis=1) + cv2.putText( + combined, f"{case['category']} {case['recording']}", (10, 24), + cv2.FONT_HERSHEY_SIMPLEX, .55, (255, 255, 255), 2, cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(combined, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=16) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + dataset = HOI4DClipDataset(args.root, args.manifest, args.mano_root) + indices = select_indices(dataset.rows, args.clips) + projection, regeneration, incompatible_left, depth_fraction, wrist_depth, hand_size = [], [], [], [], [], [] + cases: list[dict] = [] + side_frames = {"left": 0, "right": 0} + root_relative_side_frames = {"left": 0, "right": 0} + root_relative_root_norm_mm: list[float] = [] + hand_counts: list[int] = [] + for index in indices: + sample = dataset[index] + projection.extend(sample["projection_roundtrip_error_px"][sample["joint2d_valid"]].tolist()) + regeneration.extend(sample["source_vertex_regen_error_mm"][sample["vertices_valid"]].tolist()) + left_present = sample["translation_valid"][:, 0] + incompatible_left.extend(sample["source_vertex_regen_error_mm"][:, 0][left_present].tolist()) + for side_index, side in enumerate(("left", "right")): + valid = sample["joint3d_root_relative_valid"][:, side_index] + root_relative_side_frames[side] += int(valid.any(dim=-1).sum()) + root_relative_root_norm_mm.extend( + (torch.linalg.vector_norm( + sample["joint3d_root_relative"][:, side_index, 0], dim=-1, + )[valid[:, 0]] * 1000.0).tolist() + ) + for frame in range(len(sample["frame_valid"])): + valid_hands = sample["translation_valid"][frame] + hand_counts.append(int(valid_hands.sum())) + for side_index, side in enumerate(("left", "right")): + if valid_hands[side_index]: + side_frames[side] += 1 + wrist_depth.append(float(sample["wrist_root_translation"][frame, side_index, 2])) + points = sample["joint2d"][frame, side_index][sample["joint2d_valid"][frame, side_index]] + extent = points.max(0).values - points.min(0).values + hand_size.append(float(extent.max())) + depth_fraction.append(float(sample["depth_pixel_valid"][frame].float().mean())) + points = sample["joint2d"][frame][sample["joint2d_valid"][frame]] + height, width = sample["rgb"].shape[-2:] + border = min( + torch.stack((points[:, 0], points[:, 1], width - points[:, 0], height - points[:, 1])).amin().item() + if len(points) else float("inf"), + 1e9, + ) + cases.append({ + "recording": sample["physical_recording_id"], + "image": denormalize(sample["rgb"][frame]), + "depth": sample["depth_m"][frame, 0].numpy(), + "joint2d": sample["joint2d"][frame].numpy(), + "joint_valid": sample["joint2d_valid"][frame].numpy(), + "count": int(valid_hands.sum()), + "z": float(sample["wrist_root_translation"][frame, valid_hands, 2].mean()), + "size": max([ + float((sample["joint2d"][frame, side][sample["joint2d_valid"][frame, side]].max(0).values - sample["joint2d"][frame, side][sample["joint2d_valid"][frame, side]].min(0).values).max()) + for side in range(2) if sample["joint2d_valid"][frame, side].any() + ], default=0.0), + "border": border, + }) + selectors = { + "near": min(cases, key=lambda row: row["z"]), + "far": max(cases, key=lambda row: row["z"]), + "small": min(cases, key=lambda row: row["size"]), + "border": min(cases, key=lambda row: row["border"]), + "single": next(row for row in cases if row["count"] == 1), + "bimanual": next(row for row in cases if row["count"] == 2), + } + visuals = {} + for category, value in selectors.items(): + case = dict(value, category=category) + path = args.output_dir / f"{category}.png" + render(case, path) + visuals[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + report = { + "status": "pending", + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clip_indices": indices, + "clips": len(indices), "frames": len(cases), + "side_frames": side_frames, + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "projection_roundtrip_px": quantiles(projection), + "source_regeneration_mm": quantiles(regeneration), + "excluded_left_geometry_regeneration_mm": quantiles(incompatible_left), + "partial_supervision_contract": { + "right": "2D/3D/translation/pose/shape/vertices/reprojection", + "left": "direct-2D/translation/pose only", + "reason": "historical HOI4D MANO-left shapedirs cannot regenerate under corrected HOT3D/SMPL-X convention within 1 mm", + }, + "source_compatible_root_relative_joint3d": { + "side_frames": root_relative_side_frames, + "root_norm_mm": quantiles(root_relative_root_norm_mm), + "shape_vertices_enabled": False, + "claim": "source-compatible legacy MANO joint target only; not corrected-MANO regeneration", + }, + "depth_valid_fraction": quantiles(depth_fraction), + "wrist_depth_m": quantiles(wrist_depth), + "projected_hand_size_px": quantiles(hand_size), + "rgb_depth_sync": "same released aligned frame index decoded from both streams", + "depth_decode": "FFmpeg gray16le retained; millimeters converted to meters", + "visualizations": visuals, + "official_test_used": False, + } + passed = ( + len(cases) >= 100 and report["projection_roundtrip_px"]["median"] < .5 + and report["projection_roundtrip_px"]["p95"] < 1.0 + and report["source_regeneration_mm"]["max"] < 1.0 + and all(value > 0 for value in side_frames.values()) + and all(value > 0 for value in root_relative_side_frames.values()) + and report["source_compatible_root_relative_joint3d"]["root_norm_mm"]["max"] < 1e-4 + and report["single_hand_frames"] > 0 and report["bimanual_frames"] > 0 + ) + report["status"] = "passed" if passed else "failed" + (args.output_dir / "audit.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_hot3d.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_hot3d.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb6e7fdb573f9f019252e1e8a5aab2b5086a635 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase7_hot3d.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Deterministic HOT3D numeric and full-frame visualization audit.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def select_clip_indices(rows: list[dict], count: int) -> list[int]: + strata: dict[tuple[str, str], list[int]] = {} + seen_recordings: set[tuple[str, str, str]] = set() + for index, row in enumerate(rows): + hand_class = "single" if min(row.get("hand_count", [2])) == 1 else "bimanual" + key = (row["headset"], hand_class) + recording_key = (row["headset"], hand_class, row["recording_id"]) + if recording_key in seen_recordings: + continue + seen_recordings.add(recording_key) + strata.setdefault(key, []).append(index) + ordered_keys = sorted(strata) + selected: list[int] = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in ordered_keys: + values = strata[key] + if cursor < len(values): + selected.append(values[cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) < count: + raise RuntimeError(f"only {len(selected)} stratified clips available") + return selected + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), + "mean": float(array.mean()), + "median": float(np.median(array)), + "p95": float(np.quantile(array, 0.95)), + "max": float(array.max()), + } + + +def denormalize(rgb: torch.Tensor) -> np.ndarray: + image = rgb.permute(1, 2, 0).cpu().numpy() + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def render_case(case: dict, output: Path) -> None: + image = case["image"].copy() + colors = ((40, 190, 250), (250, 100, 60)) + for side in range(2): + valid = case["joint_valid"][side] + for point in case["joint2d"][side][valid]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, colors[side], -1) + cv2.putText( + image, + f"{case['category']} {case['recording']} {case['stream']}", + (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2, + cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=13) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + dataset = HOT3DClipDataset( + args.root, args.manifest, args.toolkit_root, args.mano_root, + K_input_dropout=0.3, dropout_seed=20260717, + ) + indices = select_clip_indices(dataset.rows, args.clips) + projection_errors: list[float] = [] + regeneration_errors: list[float] = [] + wrist_depths: list[float] = [] + hand_sizes: list[float] = [] + hand_counts: list[int] = [] + hand_sync_ms: list[float] = [] + headset_sync_ms: list[float] = [] + frame_cases: list[dict] = [] + headset_counts: dict[str, int] = {} + K_keep: list[bool] = [] + for index in indices: + sample = dataset[(index, 0)] + headset_counts[sample["headset_id"]] = headset_counts.get(sample["headset_id"], 0) + int(sample["frame_valid"].sum()) + projection_errors.extend(sample["projection_roundtrip_error_px"][torch.isfinite(sample["projection_roundtrip_error_px"])].tolist()) + regeneration_errors.extend(sample["source_vertex_regen_error_mm"][sample["translation_valid"]].tolist()) + hand_sync_ms.extend((sample["hand_pose_time_delta_ns"].abs() / 1e6).tolist()) + headset_sync_ms.extend((sample["headset_time_delta_ns"].abs() / 1e6).tolist()) + K_keep.append(bool(sample["K_input_available"][0])) + for frame_index in range(int(sample["frame_valid"].sum())): + valid_hands = sample["translation_valid"][frame_index] + hand_counts.append(int(valid_hands.sum())) + joint_valid = sample["joint2d_valid"][frame_index] + for side in range(2): + if not valid_hands[side]: + continue + wrist_depths.append(float(sample["wrist_root_translation"][frame_index, side, 2])) + points = sample["joint2d"][frame_index, side][joint_valid[side]] + if len(points): + extent = points.max(0).values - points.min(0).values + hand_sizes.append(float(extent.max())) + points_all = sample["joint2d"][frame_index][joint_valid] + if len(points_all): + h, w = sample["rgb"].shape[-2:] + border = torch.stack((points_all[:, 0], points_all[:, 1], w - points_all[:, 0], h - points_all[:, 1])).amin().item() + else: + border = float("inf") + valid_depth = sample["wrist_root_translation"][frame_index, :, 2][valid_hands] + frame_cases.append({ + "recording": sample["physical_recording_id"], + "stream": sample["stream_id"], + "image": denormalize(sample["rgb"][frame_index]), + "joint2d": sample["joint2d"][frame_index].cpu().numpy(), + "joint_valid": joint_valid.cpu().numpy(), + "hand_count": int(valid_hands.sum()), + "depth": float(valid_depth.mean()) if len(valid_depth) else float("nan"), + "border": float(border), + "size": float(max( + [ + (sample["joint2d"][frame_index, side][joint_valid[side]].max(0).values - sample["joint2d"][frame_index, side][joint_valid[side]].min(0).values).max().item() + for side in range(2) if joint_valid[side].any() + ], default=0.0, + )), + }) + + selectors = { + "near": lambda rows: min(rows, key=lambda row: row["depth"]), + "far": lambda rows: max(rows, key=lambda row: row["depth"]), + "border": lambda rows: min(rows, key=lambda row: row["border"]), + "small": lambda rows: min(rows, key=lambda row: row["size"]), + "single": lambda rows: next(row for row in rows if row["hand_count"] == 1), + "bimanual": lambda rows: next(row for row in rows if row["hand_count"] == 2), + } + visualizations = {} + for category, selector in selectors.items(): + case = dict(selector(frame_cases)) + case["category"] = category + path = args.output_dir / f"{category}.png" + render_case(case, path) + visualizations[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + audit = { + "status": "passed", + "official_test_used": False, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clip_indices": indices, + "clips": len(indices), + "frames": len(frame_cases), + "headset_frame_counts": headset_counts, + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "projection_roundtrip_px": quantiles(projection_errors), + "source_regeneration_mm": quantiles(regeneration_errors), + "hand_pose_sync_ms": quantiles(hand_sync_ms), + "headset_sync_ms": quantiles(headset_sync_ms), + "wrist_depth_m": quantiles(wrist_depths), + "projected_hand_size_px": quantiles(hand_sizes), + "K_input_kept_clips": int(sum(K_keep)), + "K_input_dropped_clips": int(len(K_keep) - sum(K_keep)), + "visualizations": visualizations, + } + passed = ( + audit["frames"] >= 100 + and audit["projection_roundtrip_px"]["median"] < 0.5 + and audit["projection_roundtrip_px"]["p95"] < 1.0 + and audit["source_regeneration_mm"]["max"] < 1.0 + and audit["single_hand_frames"] > 0 + and audit["bimanual_frames"] > 0 + ) + audit["status"] = "passed" if passed else "failed" + output = args.output_dir / "audit.json" + output.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") + print(json.dumps(audit, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase9_resolution_cache.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase9_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..440147147d411ed3f266dfde7363c9c87e5f944f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase9_resolution_cache.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Audit true-source Phase 9 resolution caches and train-only folds.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +EXPECTED_HW = (512, 896) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def source_index_digest(rows: list[dict[str, Any]]) -> str: + values = [int(row["source_clip_index"]) for row in rows] + payload = json.dumps(values, separators=(",", ":")).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def projection_error_px(archive: np.lib.npyio.NpzFile) -> float: + xyz = archive["joint3d_camera"] + target = archive["joint2d"] + intrinsics = archive["K"] + z = xyz[..., 2] + projected = np.empty_like(target) + projected[..., 0] = ( + intrinsics[:, None, None, 0, 0] * xyz[..., 0] / z + + intrinsics[:, None, None, 0, 2] + ) + projected[..., 1] = ( + intrinsics[:, None, None, 1, 1] * xyz[..., 1] / z + + intrinsics[:, None, None, 1, 2] + ) + valid = ( + archive["reprojection_valid"].astype(bool) + & archive["joint3d_valid"].astype(bool) + & np.isfinite(projected).all(axis=-1) + & (z > 1e-6) + ) + if not valid.any(): + return 0.0 + return float(np.linalg.norm(projected[valid] - target[valid], axis=-1).max()) + + +def audit_payload(path: Path) -> dict[str, Any]: + with np.load(path, allow_pickle=False) as archive: + if tuple(int(value) for value in archive["image_hw"].reshape(-1)) != EXPECTED_HW: + raise ValueError(f"payload resolution differs: {path}") + if archive["rgb_u8"].shape != (8, *EXPECTED_HW, 3): + raise ValueError(f"RGB shape differs: {path}") + if archive["depth_m"].shape != (8, 1, *EXPECTED_HW): + raise ValueError(f"depth shape differs: {path}") + if archive["depth_pixel_valid"].shape != (8, 1, *EXPECTED_HW): + raise ValueError(f"depth validity shape differs: {path}") + valid_depth = archive["depth_pixel_valid"].astype(bool) + depth = archive["depth_m"] + if valid_depth.any() and ( + not np.isfinite(depth[valid_depth]).all() + or not (depth[valid_depth] > 0).all() + ): + raise ValueError(f"valid depth contains nonpositive/nonfinite values: {path}") + intrinsics = archive["K"] + if ( + intrinsics.shape != (8, 3, 3) + or not np.isfinite(intrinsics).all() + or not (intrinsics[:, 0, 0] > 0).all() + or not (intrinsics[:, 1, 1] > 0).all() + or not np.allclose(intrinsics[:, 2], (0.0, 0.0, 1.0), atol=1e-6) + ): + raise ValueError(f"intrinsics contract differs: {path}") + error = projection_error_px(archive) + if error > 1.0: + raise ValueError(f"projection error exceeds 1 px ({error}): {path}") + return { + "path": str(path.resolve()), + "projection_error_max_px": error, + "depth_valid_fraction": float(valid_depth.mean()), + } + + +def audit_cache(item: dict[str, Any]) -> dict[str, Any]: + report_path = Path(item["report"]) + manifest_path = Path(item["manifest"]) + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or tuple(report.get("resolution_hw", ())) != EXPECTED_HW + or report.get("source_manifest", {}).get("sha256") + != item["source_manifest_sha256"] + or report.get("cache_manifest", {}).get("sha256") != sha256(manifest_path) + or report.get("resume_invocation") is not True + ): + raise ValueError(f"cache report contract differs: {item['id']}") + rows = read_jsonl(manifest_path) + if ( + len(rows) != int(item["clips"]) + or len({int(row["source_clip_index"]) for row in rows}) != len(rows) + or {row.get("dataset_id") for row in rows} != {item["dataset"]} + or any(tuple(row.get("resolution_hw", ())) != EXPECTED_HW for row in rows) + ): + raise ValueError(f"cache manifest contract differs: {item['id']}") + if item.get("recordings") is not None and len({ + row["physical_recording_id"] for row in rows + }) != int(item["recordings"]): + raise ValueError(f"recording count differs: {item['id']}") + control_rows = read_jsonl(Path(item["control_manifest"])) + if [row["source_clip_index"] for row in rows] != [ + row["source_clip_index"] for row in control_rows + ]: + raise ValueError(f"source clip selection differs from 640 control: {item['id']}") + payload_bytes = 0 + for row in rows: + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"payload hash differs: {path}") + payload_bytes += path.stat().st_size + samples = [audit_payload(Path(rows[index]["cache_path"])) for index in { + 0, len(rows) // 2, len(rows) - 1, + }] + return { + "id": item["id"], + "dataset": item["dataset"], + "clips": len(rows), + "recordings": len({row["physical_recording_id"] for row in rows}), + "manifest": str(manifest_path.resolve()), + "manifest_sha256": sha256(manifest_path), + "source_index_sha256": source_index_digest(rows), + "control_source_index_sha256": source_index_digest(control_rows), + "payload_bytes": payload_bytes, + "all_payload_sha256_verified": True, + "samples": samples, + } + + +def audit_sidecar(item: dict[str, Any]) -> dict[str, Any]: + report = json.loads(Path(item["report"]).read_text(encoding="utf-8")) + base_rows = read_jsonl(Path(item["base_manifest"])) + rows = read_jsonl(Path(item["manifest"])) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("base_cache_manifest", {}).get("sha256") + != sha256(item["base_manifest"]) + or report.get("augmented_cache_manifest", {}).get("sha256") + != sha256(item["manifest"]) + or report.get("right_valid_joint_count") != 0 + or float(report.get("root_norm_max_mm", math.inf)) >= 1e-4 + or report.get("shape_supervision_restored") is not False + or report.get("vertices_supervision_restored") is not False + or report.get("camera_joint3d_supervision_restored") is not False + or len(rows) != len(base_rows) + ): + raise ValueError(f"sidecar report contract differs: {item['id']}") + for base, row in zip(base_rows, rows, strict=True): + if ( + row["source_clip_index"] != base["source_clip_index"] + or row["cache_path"] != base["cache_path"] + or row["cache_sha256"] != base["cache_sha256"] + or row.get("joint3d_root_relative_scope") != "historical_left_only" + or sha256(row["joint3d_root_relative_sidecar_path"]) + != row["joint3d_root_relative_sidecar_sha256"] + ): + raise ValueError(f"sidecar row binding differs: {item['id']}") + return { + "id": item["id"], + "clips": len(rows), + "manifest_sha256": sha256(item["manifest"]), + "left_hand_frames": report["left_hand_frames"], + "all_sidecar_sha256_verified": True, + } + + +def audit_multifold(item: dict[str, Any], h2o_rows: list[dict[str, Any]]) -> dict[str, Any]: + index = json.loads(Path(item["index"]).read_text(encoding="utf-8")) + rebuild = json.loads(Path(item["rebuild_index"]).read_text(encoding="utf-8")) + if ( + index.get("status") != "complete" + or index.get("official_test_used") is not False + or index.get("h2o_official_validation_used") is not False + or index.get("source_cache_manifest", {}).get("sha256") + != sha256(item["source_manifest"]) + or len(index.get("folds", [])) != 6 + ): + raise ValueError("resolution multifold index contract differs") + if ( + rebuild.get("status") != "complete" + or rebuild.get("official_test_used") is not False + or rebuild.get("h2o_official_validation_used") is not False + or rebuild.get("source_cache_manifest", {}).get("sha256") + != index["source_cache_manifest"]["sha256"] + or [fold["id"] for fold in rebuild.get("folds", [])] + != [fold["id"] for fold in index["folds"]] + or [ + (fold["train"]["sha256"], fold["heldout"]["sha256"]) + for fold in rebuild["folds"] + ] != [ + (fold["train"]["sha256"], fold["heldout"]["sha256"]) + for fold in index["folds"] + ] + ): + raise ValueError("resolution multifold deterministic rebuild differs") + base_groups = {row["physical_recording_id"] for row in h2o_rows} + fold_audits = [] + for fold in index["folds"]: + train = read_jsonl(Path(fold["train"]["path"])) + heldout = read_jsonl(Path(fold["heldout"]["path"])) + train_groups = {row["physical_recording_id"] for row in train} + heldout_groups = {row["physical_recording_id"] for row in heldout} + if ( + train_groups & heldout_groups + or train_groups | heldout_groups != base_groups + or len(train) + len(heldout) != len(h2o_rows) + or sha256(fold["train"]["path"]) != fold["train"]["sha256"] + or sha256(fold["heldout"]["path"]) != fold["heldout"]["sha256"] + ): + raise ValueError(f"resolution multifold leakage/binding differs: {fold['id']}") + fold_audits.append({ + "id": fold["id"], "train_clips": len(train), + "heldout_clips": len(heldout), "group_overlap": 0, + }) + return { + "folds": fold_audits, + "physical_recording_isolation": True, + "deterministic_rebuild_hashes_match": True, + } + + +def audit(plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution execution plan lacks official-data isolation") + caches = [audit_cache(item) for item in plan["caches"]] + cache_by_id = {item["id"]: item for item in plan["caches"]} + h2o_rows = read_jsonl(Path(cache_by_id["h2o_train"]["manifest"])) + sidecars = [audit_sidecar(item) for item in plan["sidecars"]] + multifold = audit_multifold(plan["multifold"], h2o_rows) + return { + "schema_version": "phase9_resolution_cache_audit_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "resolution_hw": list(EXPECTED_HW), + "caches": caches, + "sidecars": sidecars, + "multifold": multifold, + "official_test_used": False, + "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("audit output must be new") + result = audit(json.loads(args.plan.read_text(encoding="utf-8"))) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase9_selection_bindings.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase9_selection_bindings.py new file mode 100644 index 0000000000000000000000000000000000000000..7a41a0a543656c690e7a0853f340aaabd6a65cac --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase9_selection_bindings.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Audit every fold report consumed by the frozen Phase 9 selection.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.summarize_phase9_unified_selection import ( + CANDIDATES, + evaluation, + validate_multifold_index, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def json_sha256(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def candidate_records() -> list[tuple[str, str, str]]: + records = [] + for mixture, candidates in CANDIDATES.items(): + for _, fold_checkpoint_id in candidates: + for fold in ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + ): + records.append((mixture, fold_checkpoint_id, fold)) + return records + + +def evaluation_path( + *, fold_final_root: Path, fold_milestone_root: Path, + condition: str, checkpoint_id: str, +) -> Path: + if checkpoint_id == "final": + return fold_final_root / condition / "rgb_d_k" / "evaluation.json" + return ( + fold_milestone_root / condition / checkpoint_id + / "rgb_d_k" / "evaluation.json" + ) + + +def file_binding(record: dict[str, Any], key: str) -> dict[str, Any]: + binding = record.get(key, {}) + path = Path(str(binding.get("path", ""))) + declared = str(binding.get("sha256", "")) + exists = path.is_file() + actual = sha256(path) if exists else None + return { + "path": str(path), + "declared_sha256": declared, + "actual_sha256": actual, + "exists": exists, + "sha256_matches": exists and declared == actual, + } + + +def artifact_binding(report: dict[str, Any], key: str) -> dict[str, Any]: + binding = report.get(key, {}) + path = Path(str(binding.get("path", ""))) + declared = str(binding.get("sha256", "")) + exists = path.is_file() + actual = sha256(path) if exists else None + return { + "path": str(path), + "declared_sha256": declared, + "actual_sha256": actual, + "exists": exists, + "sha256_matches": exists and declared == actual, + } + + +def audit_report( + *, report_path: Path, condition: str, checkpoint_id: str, + expected_manifest_path: str, expected_manifest_sha256: str, +) -> dict[str, Any]: + report = evaluation(report_path, "phase9_h2o_fold_heldout") + cache = file_binding(report, "cache_manifest") + expected_path = Path(expected_manifest_path) + expected_exists = expected_path.is_file() + expected_actual_sha = sha256(expected_path) if expected_exists else None + cache.update({ + "expected_path": expected_manifest_path, + "expected_sha256": expected_manifest_sha256, + "expected_path_exists": expected_exists, + "expected_path_actual_sha256": expected_actual_sha, + "path_matches": cache["path"] == expected_manifest_path, + "content_matches_expected": ( + cache["declared_sha256"] == expected_manifest_sha256 + and cache["actual_sha256"] == expected_manifest_sha256 + and expected_actual_sha == expected_manifest_sha256 + ), + }) + if not cache["content_matches_expected"]: + binding_status = "content_mismatch" + elif not cache["path_matches"]: + binding_status = "path_mismatch_content_identical" + else: + binding_status = "canonical" + result = { + "id": f"{condition}_{checkpoint_id}_rgb_d_k", + "condition": condition, + "checkpoint_id": checkpoint_id, + "input_mode": "rgb_d_k", + "report": { + "path": str(report_path.resolve()), + "sha256": sha256(report_path), + }, + "binding_status": binding_status, + "cache_manifest": cache, + "config": file_binding(report, "config"), + "checkpoint": file_binding(report, "checkpoint"), + "sample_counts": { + "clips": report.get("clips"), + "frames": report.get("frames"), + "hands_rows": report.get("hands_rows"), + }, + "determinism": { + "metrics_sha256": json_sha256(report.get("metrics")), + "grouped_bootstrap_ci_sha256": json_sha256( + report.get("grouped_bootstrap_ci") + ), + "raw_predictions": artifact_binding(report, "raw_predictions"), + "per_hand_rows": artifact_binding(report, "per_hand_rows"), + "take_metrics": artifact_binding(report, "take_metrics"), + }, + "evaluation_role": report.get("evaluation_role"), + "official_test_used": report.get("official_test_used"), + "h2o_official_validation_used": report.get( + "h2o_official_validation_used" + ), + } + required_bindings = [result["config"], result["checkpoint"]] + required_artifacts = [ + result["determinism"]["raw_predictions"], + result["determinism"]["per_hand_rows"], + result["determinism"]["take_metrics"], + ] + if not all(item["sha256_matches"] for item in required_bindings + required_artifacts): + result["binding_status"] = "referenced_artifact_mismatch" + return result + + +def build_audit( + *, selection_plan_path: Path, assignment_path: Path, +) -> dict[str, Any]: + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + if ( + selection_plan.get("official_test_used") is not False + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + ): + raise ValueError("selection audit must explicitly exclude official test") + index_path = Path(selection_plan["multifold_index"]) + index = json.loads(index_path.read_text(encoding="utf-8")) + folds = { + fold["id"]: fold for fold in validate_multifold_index(index) + } + records = [] + for mixture, checkpoint_id, fold in candidate_records(): + condition = f"{mixture}_{fold}" + path = evaluation_path( + fold_final_root=Path(selection_plan["fold_final_root"]), + fold_milestone_root=Path(selection_plan["fold_milestone_root"]), + condition=condition, checkpoint_id=checkpoint_id, + ) + records.append(audit_report( + report_path=path, condition=condition, + checkpoint_id=checkpoint_id, + expected_manifest_path=folds[fold]["heldout"]["path"], + expected_manifest_sha256=folds[fold]["heldout"]["sha256"], + )) + mismatches = [ + record for record in records + if record["binding_status"] != "canonical" + ] + assigned = { + item["id"] + for item in assignment["phase9_selection_recovery"]["evaluations"] + } + mismatch_ids = {item["id"] for item in mismatches} + status_counts = { + status: sum(item["binding_status"] == status for item in records) + for status in sorted({item["binding_status"] for item in records}) + } + if len(records) != 72 or len({item["id"] for item in records}) != 72: + raise ValueError("selection-critical report set is not exactly 72 unique IDs") + if mismatch_ids != assigned: + raise ValueError( + "selection mismatch IDs differ from frozen distributed assignment: " + f"missing={sorted(assigned - mismatch_ids)} " + f"unexpected={sorted(mismatch_ids - assigned)}" + ) + if any( + item["binding_status"] != "path_mismatch_content_identical" + for item in mismatches + ): + raise ValueError("selection mismatch includes a non-path-only failure") + return { + "schema_version": "phase9_selection_binding_mismatch_manifest_v1", + "status": "complete_path_only_recovery_required", + "created_utc": datetime.now(timezone.utc).isoformat(), + "selection_plan": { + "path": str(selection_plan_path.resolve()), + "sha256": sha256(selection_plan_path), + }, + "distributed_assignment": { + "path": str(assignment_path.resolve()), + "sha256": sha256(assignment_path), + }, + "multifold_index": { + "path": str(index_path.resolve()), "sha256": sha256(index_path), + }, + "selection_critical_report_count": len(records), + "canonical_report_count": len(records) - len(mismatches), + "mismatch_count": len(mismatches), + "binding_status_counts": status_counts, + "mismatch_ids": sorted(mismatch_ids), + "records": records, + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("audit output must be new") + result = build_audit( + selection_plan_path=args.selection_plan, + assignment_path=args.assignment, + ) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase9_source_coverage.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase9_source_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..db9555573bedef023846df78f2f866856869bee5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/audit_phase9_source_coverage.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Audit unique source coverage and cached geometric distributions.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def recording_id(row: dict[str, Any]) -> str: + return str(row.get("physical_recording_id", row.get("recording_id", "unknown"))) + + +def subject_id(row: dict[str, Any]) -> str: + return str(row.get("subject_id", row.get("participant_id", "unknown"))) + + +def frame_tokens(row: dict[str, Any]) -> list[str]: + values = ( + row.get("timestamps_ns") or row.get("timestamps_seconds") + or row.get("frame_ids") or row.get("frame_ids_1based") + or row.get("image_paths") or [] + ) + group = recording_id(row) + return [f"{group}:{value}" for value in values] + + +def action_family(dataset: str, recording: str) -> str: + parts = recording.split("/") + if dataset == "H2O" and len(parts) > 1: + return parts[1][:1] + if dataset == "HOI4D": + fields = [part for part in parts if part.startswith(("C", "N", "S"))] + return "/".join(fields[:3]) if fields else "unknown" + if dataset == "ARCTIC" and len(parts) > 1: + return parts[-1].rsplit("_", 1)[0] + return "unknown" + + +def quantiles(values: list[float]) -> dict[str, float | int | None]: + finite = np.asarray(values, dtype=np.float64) + finite = finite[np.isfinite(finite)] + if not len(finite): + return {"count": 0, "mean": None, "p05": None, "median": None, "p95": None} + return { + "count": int(len(finite)), "mean": float(finite.mean()), + "p05": float(np.percentile(finite, 5)), + "median": float(np.percentile(finite, 50)), + "p95": float(np.percentile(finite, 95)), + } + + +def source_summary(dataset: str, rows: list[dict[str, Any]]) -> dict[str, Any]: + tokens = [token for row in rows for token in frame_tokens(row)] + recordings = {recording_id(row) for row in rows} + return { + "clips": len(rows), + "subjects_or_participants": sorted({subject_id(row) for row in rows}), + "physical_recordings": len(recordings), + "headsets": sorted({str(row.get("headset", row.get("serial_id", "unknown"))) for row in rows}), + "cameras_or_streams": sorted({str(row.get("camera_id", row.get("stream_id", "unknown"))) for row in rows}), + "frame_references": len(tokens), + "unique_image_observations": len(set(tokens)) if tokens else None, + "clip_overlap_fraction": (1.0 - len(set(tokens)) / len(tokens)) if tokens else None, + "action_or_object_families": dict(sorted(Counter( + action_family(dataset, recording) for recording in recordings + ).items())), + } + + +def cache_numeric_summary(rows: list[dict[str, Any]]) -> dict[str, Any]: + unique_frames: set[str] = set() + side_frames = [0, 0] + single_frames = bimanual_frames = valid_frames = 0 + joint_visible = joint_total = 0 + border_hands = projected_outlier_hands = 0 + hand_sizes: list[float] = [] + wrist_depths: list[float] = [] + fx_values: list[float] = [] + fy_values: list[float] = [] + fov_x_values: list[float] = [] + depth_valid_fractions: list[float] = [] + supervision = Counter() + for row in rows: + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"cache payload is missing or differs: {path}") + with np.load(path, allow_pickle=False) as archive: + frame_valid = archive["frame_valid"].astype(bool) + translation_valid = archive["translation_valid"].astype(bool) + joint2d_valid = archive["joint2d_valid"].astype(bool) + joint2d = archive["joint2d"] + translation = archive["wrist_root_translation"] + K = archive["K"] + image_hw = archive["image_hw"] + frame_ids = archive["frame_id"] + depth_available = archive["depth_input_available"].astype(bool) + depth_pixel_valid = archive["depth_pixel_valid"].astype(bool) + for key in ( + "joint2d_valid", "joint3d_valid", "translation_valid", + "mano_pose_valid", "shape_valid", "vertices_valid", + ): + supervision[key] += int(np.count_nonzero(archive[key])) + group = row["physical_recording_id"] + for time_index in np.flatnonzero(frame_valid): + unique_frames.add(f"{group}:{int(frame_ids[time_index])}") + valid_frames += 1 + present = translation_valid[time_index] + side_frames[0] += int(present[0]) + side_frames[1] += int(present[1]) + single_frames += int(present.sum() == 1) + bimanual_frames += int(present.sum() == 2) + matrix = K[time_index] + fx_values.append(float(matrix[0, 0])) + fy_values.append(float(matrix[1, 1])) + fov_x_values.append(float(2 * np.arctan(float(image_hw[1]) / (2 * matrix[0, 0])))) + if depth_available[time_index]: + depth_valid_fractions.append(float(depth_pixel_valid[time_index].mean())) + for side in range(2): + if not present[side]: + continue + valid = joint2d_valid[time_index, side] + points_all = joint2d[time_index, side] + height, width = int(image_hw[0]), int(image_hw[1]) + finite = np.isfinite(points_all).all(axis=-1) + in_frame = ( + finite & (points_all[:, 0] >= 0) & (points_all[:, 0] < width) + & (points_all[:, 1] >= 0) & (points_all[:, 1] < height) + ) + visible = valid & in_frame + joint_visible += int(visible.sum()) + joint_total += int(len(valid)) + valid_finite = valid & finite + if valid_finite.any(): + raw_points = points_all[valid_finite] + raw_extent = raw_points.max(axis=0) - raw_points.min(axis=0) + projected_outlier_hands += int(raw_extent.max() > 4 * max(height, width)) + if visible.any(): + points = points_all[visible] + extent = points.max(axis=0) - points.min(axis=0) + hand_sizes.append(float(extent.max())) + border_hands += int( + points[:, 0].min() < 8 or points[:, 0].max() >= width - 8 + or points[:, 1].min() < 8 or points[:, 1].max() >= height - 8 + ) + wrist_depths.append(float(translation[time_index, side, 2])) + return { + "unique_cached_frames": len(unique_frames), + "valid_frame_references": valid_frames, + "left_hand_frames": side_frames[0], + "right_hand_frames": side_frames[1], + "single_hand_frames": single_frames, + "bimanual_frames": bimanual_frames, + "joint_visibility_fraction": joint_visible / joint_total if joint_total else None, + "occlusion_proxy_fraction": 1.0 - joint_visible / joint_total if joint_total else None, + "border_hand_frames": border_hands, + "projected_geometry_outlier_hand_frames": projected_outlier_hands, + "projected_hand_size_px": quantiles(hand_sizes), + "wrist_depth_m": quantiles(wrist_depths), + "fx_px": quantiles(fx_values), + "fy_px": quantiles(fy_values), + "horizontal_fov_radians": quantiles(fov_x_values), + "depth_valid_fraction": quantiles(depth_valid_fractions), + "supervision_valid_elements": dict(supervision), + } + + +def build_report( + dataset: str, source_manifest: Path, cache_manifest: Path, +) -> dict[str, Any]: + source_rows, cache_rows = read_jsonl(source_manifest), read_jsonl(cache_manifest) + cached_indices = {int(row["source_clip_index"]) for row in cache_rows} + if len(cached_indices) != len(cache_rows): + raise ValueError("cache manifest contains duplicate source clip indices") + if {row.get("dataset_id") for row in cache_rows} != {dataset}: + raise ValueError("cache manifest dataset differs from request") + return { + "schema_version": "phase9_source_coverage_v1", + "status": "complete", + "dataset": dataset, + "source_manifest": {"path": str(source_manifest.resolve()), "sha256": sha256(source_manifest)}, + "cache_manifest": {"path": str(cache_manifest.resolve()), "sha256": sha256(cache_manifest)}, + "source": source_summary(dataset, source_rows), + "cache": { + "clips": len(cache_rows), + "source_clip_coverage_fraction": len(cache_rows) / len(source_rows), + "subjects_or_participants": sorted({subject_id(row) for row in cache_rows}), + "physical_recordings": len({recording_id(row) for row in cache_rows}), + **cache_numeric_summary(cache_rows), + }, + "optimizer_exposure_is_unique_coverage": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("H2O", "HOT3D", "HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = build_report(args.dataset, args.source_manifest, args.cache_manifest) + except (OSError, ValueError, KeyError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_manifests.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..51063b592a532d6c453c612b141931ae3ac86d48 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_manifests.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Build reproducible cam4-only H2O run manifests from official pose lists.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path + + +def contiguous_runs(frame_ids: list[int]) -> list[list[int]]: + if not frame_ids: + return [] + runs = [[frame_ids[0]]] + for frame_id in frame_ids[1:]: + if frame_id == runs[-1][-1] + 1: + runs[-1].append(frame_id) + else: + runs.append([frame_id]) + return runs + + +def official_records(path: Path) -> list[dict[str, object]]: + grouped: dict[str, list[int]] = defaultdict(list) + for line in path.read_text(encoding="utf-8").splitlines(): + relative = Path(line.strip()) + if not line.strip(): + continue + if relative.parts[-3] != "cam4" or relative.parts[-2] != "rgb": + raise ValueError(f"Not a cam4 RGB record: {line}") + take = Path(*relative.parts[:-2]) + grouped[str(take)].append(int(relative.stem)) + records = [] + for take, ids in sorted(grouped.items()): + for run_index, run in enumerate(contiguous_runs(sorted(set(ids)))): + records.append({"take": take, "run_index": run_index, "frame_ids": run}) + return records + + +def write_jsonl(path: Path, records: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as handle: + for record in records: + handle.write(json.dumps(record, separators=(",", ":")) + "\n") + + +def build_debug_records(frame_csv: Path, window: int = 16, per_category: int = 4) -> list[dict[str, object]]: + categories: dict[str, list[dict[str, str]]] = defaultdict(list) + with frame_csv.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + key = row["joint_left_valid"] + row["joint_right_valid"] + categories[key].append(row) + selected = [] + for category, rows in sorted(categories.items()): + if category not in {"01", "10", "11"}: + continue + indices = [round(i * (len(rows) - 1) / max(per_category - 1, 1)) for i in range(per_category)] + for row_index in indices: + row = rows[row_index] + center = int(row["frame_id"]) + start = max(0, center - window // 2) + take_path = Path(row["rgb_path"]).parents[1] + available = sorted(int(path.stem) for path in (take_path / "rgb").glob("*.png")) + valid_ids = set(available) + frames = [frame_id for frame_id in range(start, start + window) if frame_id in valid_ids] + selected.append({ + "take": "/".join(take_path.parts[-4:]), + "run_index": len(selected), + "frame_ids": frames, + "debug_center_valid": category, + "debug_center_frame": center, + }) + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--pose-list-dir", type=Path, required=True) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + summary = {} + for split in ("train", "val", "test"): + records = official_records(args.pose_list_dir / f"pose_{split}.txt") + output = args.output_dir / f"official_{split}.jsonl" + write_jsonl(output, records) + summary[split] = { + "path": str(output.resolve()), + "runs": len(records), + "frames": sum(len(record["frame_ids"]) for record in records), + "subjects": sorted({str(record["take"]).split("/")[0] for record in records}), + } + debug = build_debug_records(args.frame_csv) + debug_path = args.output_dir / "debug_cam4.jsonl" + write_jsonl(debug_path, debug) + summary["debug"] = {"path": str(debug_path.resolve()), "runs": len(debug), "frames": sum(len(record["frame_ids"]) for record in debug)} + tiny = [] + for category in ("01", "10", "11"): + tiny.extend([record for record in debug if record["debug_center_valid"] == category][:2]) + tiny_path = args.output_dir / "tiny_overfit_cam4.jsonl" + write_jsonl(tiny_path, tiny) + summary["tiny_overfit"] = { + "path": str(tiny_path.resolve()), + "runs": len(tiny), + "frames": sum(len(record["frame_ids"]) for record in tiny), + "center_valid_combinations": {category: 2 for category in ("01", "10", "11")}, + } + summary["policy"] = "Official pose split; clips are generated inside each contiguous take/run and never cross camera, sequence, or subject." + (args.output_dir / "manifest_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase3_val_subset.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase3_val_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5c9941a59e168b9e49e961c4a41f3556b97aa9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase3_val_subset.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Build the fixed 256-clip Phase 3 validation subset from input-only strata.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.subset import balanced_stratified_indices + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def size_bucket(value: float) -> str: + if value < 64: + return "small" + if value < 128: + return "medium" + return "large" + + +def depth_bucket(value: float) -> str: + if value < 0.5: + return "near" + if value < 0.8: + return "middle" + return "far" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--per-hand-frames", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--count", type=int, default=256) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + with args.per_hand_frames.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + grouped: dict[int, list[dict[str, str]]] = defaultdict(list) + for row in rows: + grouped[int(row["clip_index"])].append(row) + + clip_records: list[dict[str, object]] = [] + for clip_index, clip_rows in sorted(grouped.items()): + sizes = [float(row["hand_size_px"]) for row in clip_rows if row["hand_size_px"]] + depths = [float(row["wrist_depth_m"]) for row in clip_rows if row["wrist_depth_m"]] + states = [row["annotation_state"] for row in clip_rows] + state_counts = Counter(states) + # Preserve rare one-hand-valid clips as a stratum instead of letting the + # dominant both-valid frames erase them. + annotation_state = "01" if state_counts["01"] else "10" if state_counts["10"] else state_counts.most_common(1)[0][0] + median_size = float(np.median(sizes)) if sizes else float("nan") + median_depth = float(np.median(depths)) if depths else float("nan") + first = clip_rows[0] + clip_records.append({ + "clip_index": clip_index, + "take": first["take"], + "subject": first["subject"], + "sequence": first["sequence"], + "first_frame_id": min(int(row["frame_id"]) for row in clip_rows), + "last_frame_id": max(int(row["frame_id"]) for row in clip_rows), + "hand_size_px_median": median_size, + "hand_size_bucket": size_bucket(median_size) if np.isfinite(median_size) else "unavailable", + "wrist_depth_m_median": median_depth, + "depth_bucket": depth_bucket(median_depth) if np.isfinite(median_depth) else "unavailable", + "annotation_state": annotation_state, + }) + + selected_indices = balanced_stratified_indices(clip_records, args.count, seed=args.seed) + selected_set = set(selected_indices) + selected_records = [record for record in clip_records if int(record["clip_index"]) in selected_set] + take_counts = Counter(str(record["take"]) for record in selected_records) + stratum_counts = Counter( + (str(record["hand_size_bucket"]), str(record["depth_bucket"]), str(record["annotation_state"])) + for record in selected_records + ) + manifest = { + "version": "phase3_stratified_256_v1", + "seed": args.seed, + "count": len(selected_indices), + "source_manifest": str(args.source_manifest.resolve()), + "source_manifest_sha256": sha256(args.source_manifest), + "source_clip_count": len(clip_records), + "dataset_contract": {"resolution_hw": [288, 512], "T": 8, "stride": 1, "allow_partial": True}, + "selection_inputs": "take, GT-projected hand extent, wrist depth, annotation validity; model errors are excluded", + "selection_policy": "balanced take quotas plus deterministic round-robin within-take size/depth/valid strata", + "clip_indices": selected_indices, + "take_counts": dict(sorted(take_counts.items())), + "stratum_counts": {"/".join(key): value for key, value in sorted(stratum_counts.items())}, + "official_test_used": False, + } + manifest_path = args.output_dir / "validation_subset_256.json" + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + + csv_path = args.output_dir / "validation_subset_256.csv" + with csv_path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(selected_records[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(selected_records) + (args.output_dir / "validation_subset_256.sha256").write_text( + f"{sha256(manifest_path)} {manifest_path.name}\n{sha256(csv_path)} {csv_path.name}\n", + encoding="utf-8", + ) + print(json.dumps({ + "status": "created", "count": len(selected_indices), "takes": len(take_counts), + "take_count_min": min(take_counts.values()), "take_count_max": max(take_counts.values()), + "manifest": str(manifest_path), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase4_balanced_sampler.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase4_balanced_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..da8852e7b9d01cedc7c28961a16d8b599e3a06a0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase4_balanced_sampler.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""Build a deterministic train-only geometry-balanced sampling manifest.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from collections import Counter +from pathlib import Path + +import numpy as np + +from foundation_hand.data import H2OCam4Dataset +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record +from foundation_hand.evaluation.phase4 import bimanual_asymmetry +from foundation_hand.geometry.camera import ( + intrinsics_from_h2o, + project_points, + resize_and_pad_intrinsics, +) + + +AXES = ( + "left_size_bucket", + "right_size_bucket", + "left_depth_bucket", + "right_depth_bucket", + "asymmetry_bucket", + "action_family", + "annotation_valid_state", +) +WEIGHT_MIN = 0.5 +WEIGHT_MAX = 3.0 +TAKE_FACTOR_MIN = 2.0 / 3.0 +TAKE_FACTOR_MAX = 1.5 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def fit_resize( + source_hw: tuple[int, int], target_hw: tuple[int, int], +) -> tuple[tuple[int, int], tuple[int, int]]: + source_h, source_w = source_hw + target_h, target_w = target_hw + scale = min(target_w / source_w, target_h / source_h) + resized = (max(1, round(source_h * scale)), max(1, round(source_w * scale))) + return resized, ((target_w - resized[1]) // 2, (target_h - resized[0]) // 2) + + +def size_bucket(value: float | None) -> str: + if value is None: + return "unavailable" + if value < 64.0: + return "small" + if value < 128.0: + return "medium" + return "large" + + +def depth_bucket(value: float | None) -> str: + if value is None: + return "unavailable" + if value < 0.5: + return "near" + if value < 0.8: + return "middle" + return "far" + + +def median_or_none(values: list[float]) -> float | None: + return float(np.median(values)) if values else None + + +def validity_state(valid_counts: list[int], frame_count: int) -> str: + frequent = [count / frame_count >= 0.5 for count in valid_counts] + if frequent == [True, True]: + return "both" + if frequent == [True, False]: + return "left_only" + if frequent == [False, True]: + return "right_only" + return "sparse" + + +def clip_geometry_record( + root: Path, + clip_index: int, + clip, + target_hw: tuple[int, int], + intrinsics_cache: dict[str, np.ndarray], +) -> dict[str, object]: + take_dir = root / clip.take + if clip.take not in intrinsics_cache: + K_raw, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + resized_hw, pad_left_top = fit_resize(source_hw, target_hw) + intrinsics_cache[clip.take] = resize_and_pad_intrinsics( + K_raw, source_hw, resized_hw, pad_left_top, + ) + K = intrinsics_cache[clip.take] + sizes: list[list[float]] = [[], []] + depths: list[list[float]] = [[], []] + valid_counts = [0, 0] + ratios: list[float] = [] + gaps: list[float] = [] + for frame_id in clip.frame_ids: + joints = load_joint_record(take_dir / "hand_pose" / f"{frame_id:06d}.txt") + joints_2d, positive = project_points(joints.joints_camera_m, K) + frame_sizes: list[float | None] = [None, None] + frame_depths: list[float | None] = [None, None] + for hand in range(2): + if not bool(joints.annotation_valid[hand]) or not bool(positive[hand].all()): + continue + extent = joints_2d[hand].max(axis=0) - joints_2d[hand].min(axis=0) + size = float(extent.max()) + depth = float(joints.joints_camera_m[hand, 0, 2]) + sizes[hand].append(size) + depths[hand].append(depth) + valid_counts[hand] += 1 + frame_sizes[hand] = size + frame_depths[hand] = depth + asymmetry = bimanual_asymmetry(frame_sizes, frame_depths) + if asymmetry["bimanual_size_ratio"] is not None: + ratios.append(float(asymmetry["bimanual_size_ratio"])) + gaps.append(float(asymmetry["bimanual_depth_gap_m"])) + median_sizes = [median_or_none(values) for values in sizes] + median_depths = [median_or_none(values) for values in depths] + aggregate_asymmetry = bimanual_asymmetry(median_sizes, median_depths) + parts = Path(clip.take).parts + return { + "clip_index": clip_index, + "take": clip.take, + "frame_count": len(clip.frame_ids), + "action_family": parts[1], + "annotation_valid_state": validity_state(valid_counts, len(clip.frame_ids)), + "left_valid_fraction": valid_counts[0] / len(clip.frame_ids), + "right_valid_fraction": valid_counts[1] / len(clip.frame_ids), + "left_hand_size_px": median_sizes[0], + "right_hand_size_px": median_sizes[1], + "left_wrist_depth_m": median_depths[0], + "right_wrist_depth_m": median_depths[1], + "median_size_ratio": median_or_none(ratios), + "median_depth_gap_m": median_or_none(gaps), + "left_size_bucket": size_bucket(median_sizes[0]), + "right_size_bucket": size_bucket(median_sizes[1]), + "left_depth_bucket": depth_bucket(median_depths[0]), + "right_depth_bucket": depth_bucket(median_depths[1]), + "asymmetry_bucket": aggregate_asymmetry["bimanual_asymmetry_bucket"] or "unavailable", + } + + +def assign_weights(records: list[dict[str, object]]) -> dict[str, object]: + if not records: + raise ValueError("cannot balance an empty clip set") + frequencies = { + axis: Counter(str(record[axis]) for record in records) for axis in AXES + } + take_counts = Counter(str(record["take"]) for record in records) + median_take_count = float(np.median(list(take_counts.values()))) + raw_weights = [] + for record in records: + marginal = [] + for axis in AXES: + counts = frequencies[axis] + count = counts[str(record[axis])] + marginal.append(math.sqrt(len(records) / (len(counts) * count))) + geometry_factor = float(np.mean(marginal)) + take_factor = math.sqrt(median_take_count / take_counts[str(record["take"])]) + take_factor = float(np.clip(take_factor, TAKE_FACTOR_MIN, TAKE_FACTOR_MAX)) + raw_weights.append(geometry_factor * take_factor) + record["geometry_rarity_factor"] = geometry_factor + record["take_frequency_factor"] = take_factor + scale = float(np.mean(raw_weights)) + weights = np.clip(np.asarray(raw_weights) / scale, WEIGHT_MIN, WEIGHT_MAX) + for record, weight in zip(records, weights, strict=True): + record["weight"] = float(weight) + return { + "axis_frequencies": { + axis: dict(sorted(counts.items())) for axis, counts in frequencies.items() + }, + "take_clip_count_min": min(take_counts.values()), + "take_clip_count_median": median_take_count, + "take_clip_count_max": max(take_counts.values()), + "weight_min": float(weights.min()), + "weight_mean": float(weights.mean()), + "weight_max": float(weights.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--expected-manifest-sha256", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--resolution-hw", type=int, nargs=2, default=(368, 640)) + parser.add_argument("--T", type=int, default=8) + parser.add_argument("--stride", type=int, default=1) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args() + if "test" in args.manifest.name.lower() or "val" in args.manifest.name.lower(): + raise ValueError("balanced sampler builder accepts official train only") + manifest_hash = sha256(args.manifest) + if manifest_hash != args.expected_manifest_sha256: + raise ValueError("official-train manifest hash mismatch") + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite {args.output}") + target_hw = tuple(args.resolution_hw) + dataset = H2OCam4Dataset( + args.root, args.manifest, target_hw, (args.T,), (args.stride,), + max_clips=args.max_clips, + ) + cache: dict[str, np.ndarray] = {} + records = [] + for clip_index, clip in enumerate(dataset.clips): + records.append(clip_geometry_record( + args.root, clip_index, clip, target_hw, cache, + )) + if (clip_index + 1) % 500 == 0: + print(f"clips={clip_index + 1}/{len(dataset)}", flush=True) + summary = assign_weights(records) + output = { + "version": "phase4_train_geometry_balanced_v1", + "phase": 4, + "wave": "B2", + "split_role": "official_train", + "official_test_used": False, + "source_manifest": str(args.manifest.resolve()), + "source_manifest_sha256": manifest_hash, + "dataset_contract": { + "resolution_hw": list(target_hw), "T": args.T, "stride": args.stride, + "allow_partial": True, + }, + "clip_count": len(records), + "policy": { + "axes": list(AXES), + "marginal_weight": "inverse square root of train-only clip frequency", + "combination": "mean marginal rarity multiplied by capped take-frequency correction", + "weight_cap": [WEIGHT_MIN, WEIGHT_MAX], + "take_factor_cap": [TAKE_FACTOR_MIN, TAKE_FACTOR_MAX], + "draws": "dataset_size draws with replacement per seed+epoch", + "validation_identity_used": False, + }, + "summary": summary, + "clips": records, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": "complete", "clips": len(records), **summary}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase4_checkpoint_index.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase4_checkpoint_index.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c866726979ff9b6154bd9fcd36293264747a33 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase4_checkpoint_index.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Build a deterministic index of Phase 4 official-validation checkpoints.""" + +from __future__ import annotations + +import argparse +import json +import os +import re +from pathlib import Path +from typing import Any + + +SHA256 = re.compile(r"[0-9a-f]{64}") +OFFICIAL_VALIDATION_CLIPS = 1495 +OFFICIAL_VALIDATION_FRAMES = 11638 + + +def evaluation_reports(root: Path) -> list[Path]: + """Find reports through SSD-backed artifact symlinks without following cycles.""" + reports = [] + visited_directories: set[Path] = set() + for directory, names, files in os.walk(root, followlinks=True): + directory_path = Path(directory) + resolved_directory = directory_path.resolve() + if resolved_directory in visited_directories: + names.clear() + continue + visited_directories.add(resolved_directory) + names[:] = sorted( + name for name in names + if (directory_path / name).resolve() not in visited_directories + ) + if "evaluation.json" in files: + reports.append(directory_path / "evaluation.json") + return sorted(reports) + + +def logical_location(root: Path, report_path: Path) -> tuple[str, str, str]: + parts = report_path.relative_to(root).parts + if "full_validation" in parts: + index = parts.index("full_validation") + if len(parts) <= index + 3: + raise ValueError(f"invalid full-validation path: {report_path}") + condition = "/".join(parts[:index]) + return condition, parts[index + 1], parts[index + 2] + if len(parts) < 2: + raise ValueError(f"invalid evaluation path: {report_path}") + return parts[0], report_path.parent.name, "reference" + + +def build_index(root: Path) -> dict[str, Any]: + root = root.resolve() + records = [] + for report_path in evaluation_reports(root): + report = json.loads(report_path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("split_role") != "official_validation": + continue + if report.get("official_test_used") is not False: + raise ValueError(f"official-validation report lacks test isolation: {report_path}") + # Real-checkpoint smokes use the validation split but are not complete + # evaluations and must not enter the formal checkpoint index. + if ( + report.get("clips") != OFFICIAL_VALIDATION_CLIPS + or report.get("frames") != OFFICIAL_VALIDATION_FRAMES + ): + continue + checkpoint = report.get("checkpoint") + if not isinstance(checkpoint, dict): + raise ValueError(f"missing checkpoint record: {report_path}") + sha256 = checkpoint.get("sha256") + if not isinstance(sha256, str) or SHA256.fullmatch(sha256) is None: + raise ValueError(f"invalid checkpoint SHA256: {report_path}") + checkpoint_path = Path(str(checkpoint.get("path", ""))) + if not checkpoint_path.is_file(): + raise FileNotFoundError(f"indexed checkpoint is missing: {checkpoint_path}") + step = checkpoint.get("step") + if not isinstance(step, int) or step < 0: + raise ValueError(f"invalid checkpoint step: {report_path}") + condition, run, role = logical_location(root, report_path) + config = report.get("config", {}) + records.append({ + "condition": condition, + "run": run, + "role": role, + "config": config.get("name"), + "seed": config.get("seed"), + "checkpoint_path": str(checkpoint_path.resolve()), + "checkpoint_sha256": sha256, + "checkpoint_step": step, + "evaluation_path": str(report_path.resolve()), + "clips": report.get("clips"), + "frames": report.get("frames"), + }) + if not records: + raise ValueError(f"no official-validation evaluations found under {root}") + unique_checkpoints = { + (record["checkpoint_path"], record["checkpoint_sha256"]) + for record in records + } + return { + "status": "indexed", + "official_test_used": False, + "evaluations": len(records), + "unique_checkpoints": len(unique_checkpoints), + "records": records, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--phase4-root", type=Path, default=Path("artifacts/phase4"), + ) + parser.add_argument( + "--output", type=Path, + default=Path("artifacts/phase4/reports/checkpoints.json"), + ) + args = parser.parse_args() + payload = build_index(args.phase4_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": payload["status"], + "evaluations": payload["evaluations"], + "unique_checkpoints": payload["unique_checkpoints"], + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase5_group_folds.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase5_group_folds.py new file mode 100644 index 0000000000000000000000000000000000000000..996077ed4feed509db4ffefe17c0a09ae4f40367 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase5_group_folds.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Build deterministic subject-held-out OOF manifests from official train only.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None: + with path.open("w", encoding="utf-8") as handle: + for record in records: + handle.write(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n") + + +def record_id(record: dict[str, Any]) -> tuple[str, int]: + return str(record["take"]), int(record["run_index"]) + + +def subject(record: dict[str, Any]) -> str: + return str(record["take"]).split("/", 1)[0] + + +def fold_summary(records: list[dict[str, Any]]) -> dict[str, Any]: + return { + "records": len(records), + "frames": sum(len(record["frame_ids"]) for record in records), + "takes": len({str(record["take"]) for record in records}), + "subjects": sorted({subject(record) for record in records}), + "action_families": sorted({str(record["take"]).split("/")[1] for record in records}), + } + + +def build_subject_folds(source_manifest: Path, output_root: Path) -> dict[str, Any]: + records = [ + json.loads(line) + for line in source_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not records: + raise ValueError("source manifest is empty") + ids = [record_id(record) for record in records] + if len(ids) != len(set(ids)): + raise ValueError("source manifest contains duplicate take/run records") + for record in records: + if not record.get("frame_ids"): + raise ValueError(f"record has no frames: {record_id(record)}") + + by_subject: dict[str, list[dict[str, Any]]] = defaultdict(list) + for record in records: + by_subject[subject(record)].append(record) + subjects = sorted(by_subject) + if len(subjects) < 2: + raise ValueError("subject-held-out OOF requires at least two subjects") + + output_root.mkdir(parents=True, exist_ok=True) + folds = [] + heldout_ids: set[tuple[str, int]] = set() + for fold_index, heldout_subject in enumerate(subjects): + fold_dir = output_root / f"fold_{fold_index}_{heldout_subject}" + fold_dir.mkdir(parents=True, exist_ok=True) + heldout = sorted(by_subject[heldout_subject], key=record_id) + train = sorted( + (record for record in records if subject(record) != heldout_subject), + key=record_id, + ) + train_path = fold_dir / "train.jsonl" + heldout_path = fold_dir / "heldout.jsonl" + write_jsonl(train_path, train) + write_jsonl(heldout_path, heldout) + + train_takes = {str(record["take"]) for record in train} + heldout_takes = {str(record["take"]) for record in heldout} + train_subjects = {subject(record) for record in train} + heldout_subjects = {subject(record) for record in heldout} + leakage_free = not (train_takes & heldout_takes) and not ( + train_subjects & heldout_subjects + ) + if not leakage_free: + raise RuntimeError(f"group leakage detected in fold {fold_index}") + current_ids = {record_id(record) for record in heldout} + if heldout_ids & current_ids: + raise RuntimeError("a source record appears in more than one heldout fold") + heldout_ids.update(current_ids) + folds.append({ + "fold": fold_index, + "heldout_subject": heldout_subject, + "train_manifest": str(train_path.relative_to(output_root)), + "train_manifest_sha256": sha256(train_path), + "heldout_manifest": str(heldout_path.relative_to(output_root)), + "heldout_manifest_sha256": sha256(heldout_path), + "train": fold_summary(train), + "heldout": fold_summary(heldout), + "leakage_audit": { + "take_overlap": [], + "subject_overlap": [], + "passed": True, + }, + }) + + if heldout_ids != set(ids): + raise RuntimeError("heldout folds do not form an exact partition of official train") + report = { + "version": "phase5_subject_oof_v1", + "status": "frozen", + "source_role": "official_train", + "source_manifest": str(source_manifest.resolve()), + "source_manifest_sha256": sha256(source_manifest), + "assignment": "one complete official-train subject per heldout fold", + "group_unit": "subject; take/recording is indivisible", + "folds": folds, + "source": fold_summary(records), + "coverage_audit": { + "heldout_records": len(heldout_ids), + "source_records": len(records), + "exact_partition": True, + }, + "official_validation_used_for_assignment": False, + "official_test_used": False, + } + (output_root / "folds.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + args = parser.parse_args() + report = build_subject_folds(args.source_manifest, args.output_root) + print(json.dumps({ + "status": report["status"], + "version": report["version"], + "folds": len(report["folds"]), + "source": report["source"], + "official_test_used": report["official_test_used"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase5_missing_alignment_package.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase5_missing_alignment_package.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9247dc5bb746e3387abd07ad37a634e36ece53 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase5_missing_alignment_package.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Build an exact zero-alignment package for true missing-input causal audits.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def validate_cache( + manifest: dict[str, Any], expected_condition: str, expected_scope: str, +) -> None: + if ( + manifest.get("status") != "complete" + or manifest.get("scope") != expected_scope + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + or manifest.get("input_condition") != expected_condition + ): + raise ValueError("invalid true missing-input cache contract") + if expected_scope == "full" and ( + manifest.get("clips") != 1495 or manifest.get("frames") != 11638 + ): + raise ValueError("invalid full-cache coverage") + + +def fallback_prediction(arrays: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + frame_id = arrays["frame_id"] + translation = arrays["pred_wrist_translation"] + if frame_id.ndim != 1 or translation.shape[:2] != (len(frame_id), 2): + raise ValueError("invalid cache take dimensions") + shape = (len(frame_id), 2) + zeros = np.zeros(shape, dtype=np.float32) + return { + "frame_id": frame_id.astype(np.int64, copy=False), + "calibrated_delta_z_m": zeros, + "alignment_applied": np.zeros(shape, dtype=bool), + "confidence": zeros.copy(), + "inlier_ratio": zeros.copy(), + "residual_scale_m": zeros.copy(), + "valid_fraction": zeros.copy(), + "quality": zeros.copy(), + } + + +def build_package( + cache_dir: Path, + output_dir: Path, + expected_condition: str, + expected_scope: str, +) -> dict[str, Any]: + if output_dir.exists() and any(output_dir.iterdir()): + raise FileExistsError("fallback alignment output must be new or empty") + manifest_path = cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + validate_cache(manifest, expected_condition, expected_scope) + output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = output_dir / "predictions" + prediction_root.mkdir() + records = [] + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"cache take hash mismatch: {take_path}") + arrays = load_npz(take_path) + stem = "__".join(Path(str(arrays["take"])).parts) + prediction_path = prediction_root / f"{stem}.npz" + np.savez_compressed(prediction_path, **fallback_prediction(arrays)) + records.append({ + "take": str(arrays["take"]), + "path": str(prediction_path.resolve()), + "sha256": sha256(prediction_path), + }) + report = { + "status": "evaluated", + "experiment_class": "preregistered_missing_input_causal_diagnostic", + "result_role": "exact_zero_alignment_max_uncertainty_input_package", + "input_condition": expected_condition, + "scope": expected_scope, + "cache_manifest": { + "path": str(manifest_path.resolve()), + "sha256": sha256(manifest_path), + }, + "coarse_checkpoint": manifest["checkpoint"], + "alignment_contract": ( + "alignment_applied=false and delta-z=0 for every hand/frame; " + "causal uncertainty evaluator maps unavailable alignment to maximum noise" + ), + "takes": records, + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + } + (output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument( + "--expected-condition", choices=("missing_depth", "missing_k"), required=True, + ) + parser.add_argument("--scope", choices=("full", "smoke"), default="full") + args = parser.parse_args() + report = build_package( + args.cache_dir, args.output_dir, args.expected_condition, args.scope, + ) + print(json.dumps({ + "status": report["status"], + "condition": report["input_condition"], + "takes": len(report["takes"]), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase5_oof_bank.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..3199c0ded583d5c1ea631b3681edadbb755d4337 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase5_oof_bank.py @@ -0,0 +1,525 @@ +#!/usr/bin/env python3 +"""Build a resume-safe group-held-out coarse prediction bank for Phase 5.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.alignment_calibration import projected_hand_scale_px +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +BANK_VERSION = 2 +SIDES = ("left", "right") +FRAME_ARRAYS = ( + "clip_index", + "frame_id", + "frame_valid", + "K_resized", + "K_raw", + "rgb_available", + "depth_available", + "K_available", + "pred_rotation_matrices", + "pred_shape", + "pred_wrist_translation", + "pred_joints_camera", + "pred_vertices_camera", + "pred_direct_2d_px", + "pred_joints_raw_px", + "pred_vertices_raw_px", + "pred_surface_depth_m", + "observed_surface_depth_m", + "observed_surface_xyz_m", + "surface_visible", + "surface_sample_valid", + "surface_local_discontinuity_m", + "silhouette_packed", + "silhouette_overlap_fraction", + "predicted_depth_order", + "alignment_delta_z_m", + "alignment_applied", + "alignment_valid_support_count", + "alignment_projected_support_count", + "alignment_inlier_ratio", + "alignment_residual_scale_m", + "alignment_valid_fraction", + "alignment_foreground_fraction", + "alignment_background_fraction", + "alignment_depth_discontinuity_m", + "alignment_conditioning_quality", + "coarse_direct_mano_consistency_px", + "coarse_hand_scale_px", + "coarse_wrist_velocity_m_per_frame", + "target_rotation_matrices", + "target_pose_axis_angle", + "target_shape", + "target_wrist_translation", + "target_joints_camera", + "target_vertices_camera", + "target_2d_px", + "translation_residual_m", + "joint_annotation_valid", + "joint_element_valid", + "mano_annotation_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def take_slug(take: str) -> str: + parts = Path(take).parts + if len(parts) != 4 or parts[-1] != "cam4": + raise ValueError(f"unexpected H2O take: {take}") + return "__".join(parts) + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def resolve_fold_contract( + folds_manifest: Path, + fold_index: int, + heldout_manifest: Path, + run_provenance: Path, +) -> dict[str, Any]: + folds = json.loads(folds_manifest.read_text(encoding="utf-8")) + if ( + folds.get("version") != "phase5_subject_oof_v1" + or folds.get("status") != "frozen" + or folds.get("source_role") != "official_train" + or folds.get("official_test_used") is not False + ): + raise ValueError("invalid or unfrozen Phase 5 OOF manifest") + matches = [record for record in folds["folds"] if int(record["fold"]) == fold_index] + if len(matches) != 1: + raise ValueError(f"fold {fold_index} is not uniquely registered") + fold = matches[0] + registered_heldout = folds_manifest.parent / fold["heldout_manifest"] + if heldout_manifest.resolve() != registered_heldout.resolve(): + raise ValueError("heldout manifest path differs from registered fold") + if sha256(heldout_manifest) != fold["heldout_manifest_sha256"]: + raise ValueError("heldout manifest hash differs from registered fold") + provenance = json.loads(run_provenance.read_text(encoding="utf-8")) + train_hash = provenance.get("hashes", {}).get("train_manifest", {}).get("sha256") + if train_hash != fold["train_manifest_sha256"]: + raise ValueError("checkpoint training manifest is not the registered fold train split") + if provenance.get("git_status") not in ("", None): + raise ValueError("OOF bank requires a checkpoint trained from a clean worktree") + return {"folds": folds, "fold": fold, "provenance": provenance} + + +def validate_checkpoint_provenance( + checkpoint: dict[str, Any], + *, + config: dict[str, Any], + config_path: Path, + run_provenance_path: Path, + provenance: dict[str, Any], +) -> None: + """Bind the extraction checkpoint to its clean training run and config.""" + + extra = checkpoint.get("extra", {}) + provenance_config_hash = provenance.get("hashes", {}).get("config", {}).get("sha256") + if provenance_config_hash != sha256(config_path): + raise ValueError("extraction config hash differs from checkpoint run provenance") + if provenance.get("config") != config or extra.get("config") != config: + raise ValueError("extraction config differs from checkpoint embedded config") + if extra.get("git_commit") != provenance.get("git_commit"): + raise ValueError("checkpoint git commit differs from run provenance") + if extra.get("run_provenance_sha256") != sha256(run_provenance_path): + raise ValueError("checkpoint run provenance hash mismatch") + protocol = config.get("protocol", {}) + if extra.get("checkpoint_role") != "final" or int(checkpoint.get("step", -1)) != int( + protocol.get("max_steps", -2) + ): + raise ValueError("OOF bank requires the preregistered fixed-final checkpoint") + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def target_geometry( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + pose_axis_angle = batch["mano_pose"].reshape(*batch["mano_pose"].shape[:-1], 16, 3) + rotations = axis_angle_to_matrix(torch.nan_to_num(pose_axis_angle)) + with torch.no_grad(): + vertices, joints = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = batch["mano_annotation_valid"].bool()[..., None, None] + vertices = torch.where(valid, vertices, torch.full_like(vertices, torch.nan)) + joints = torch.where(valid, joints, torch.full_like(joints, torch.nan)) + return pose_axis_angle, rotations, vertices, joints + + +def _observed_xyz( + pixels: np.ndarray, observed_depth_m: np.ndarray, K: np.ndarray, +) -> np.ndarray: + z = observed_depth_m.astype(np.float32) + xyz = np.full((*z.shape, 3), np.nan, dtype=np.float32) + valid = np.isfinite(z) & (z > 0.0) & np.isfinite(pixels).all(axis=-1) + xyz[..., 2][valid] = z[valid] + xyz[..., 0][valid] = (pixels[..., 0][valid] - K[0, 2]) * z[valid] / K[0, 0] + xyz[..., 1][valid] = (pixels[..., 1][valid] - K[1, 2]) * z[valid] / K[1, 1] + return xyz + + +def _velocity(translation: np.ndarray, frame_ids: np.ndarray) -> np.ndarray: + output = np.zeros_like(translation, dtype=np.float32) + contiguous = frame_ids[1:] == frame_ids[:-1] + 1 + output[1:][contiguous] = translation[1:][contiguous] - translation[:-1][contiguous] + return output + + +def infer_take( + *, + root: Path, + take: str, + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + loader = DataLoader( + Subset(dataset, clip_indices), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + take_dir = root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + silhouette_hw: tuple[int, int] | None = None + for global_clip_index, batch_cpu in zip(clip_indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + target_pose, target_rotations, target_vertices, target_joints = target_geometry(batch, model) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + valid_times = int(batch["frame_valid"][0].sum()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor( + (width, height), device=device, + ) + pred_vertices = prediction["vertices_camera"][0, :valid_times].float().cpu().numpy() + pred_joints = prediction["joints_camera"][0, :valid_times].float().cpu().numpy() + frame_ids = batch["frame_id"][0, :valid_times].cpu().numpy().astype(np.int64) + surface_fields: dict[str, list[np.ndarray]] = defaultdict(list) + for time_index, frame_id in enumerate(frame_ids): + stem = f"{int(frame_id):06d}" + raw_depth_mm = cv2.imread(str(take_dir / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED) + if raw_depth_mm is None or raw_depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{stem}") + raw_depth_m, raw_depth_valid = depth_mm_to_m(raw_depth_mm) + packed_masks = [] + medians = [] + for hand in range(2): + diagnostics, samples = align_wrist_z( + pred_vertices[time_index, hand], K_raw, raw_depth_m, raw_depth_valid, + ) + if samples is None: + raise AssertionError("full-modality OOF extraction unexpectedly lacks surface samples") + if silhouette_hw is None: + silhouette_hw = samples.silhouette_hw + elif silhouette_hw != samples.silhouette_hw: + raise AssertionError("silhouette shape changed within OOF bank") + observed_xyz = _observed_xyz( + samples.projected_vertices_px, samples.observed_depth_m, K_raw, + ) + surface_fields["pred_vertices_raw_px"].append(samples.projected_vertices_px) + surface_fields["pred_surface_depth_m"].append(samples.predicted_depth_m) + surface_fields["observed_surface_depth_m"].append(samples.observed_depth_m) + surface_fields["observed_surface_xyz_m"].append(observed_xyz) + surface_fields["surface_visible"].append(samples.visible_vertex) + surface_fields["surface_sample_valid"].append(samples.sample_valid) + surface_fields["surface_local_discontinuity_m"].append(samples.local_discontinuity_m) + surface_fields["silhouette_packed"].append(samples.silhouette_packed) + for field, value in diagnostics.as_dict().items(): + surface_fields[f"alignment_{field}"].append(np.asarray(value)) + packed_masks.append(np.unpackbits( + samples.silhouette_packed, bitorder="little", + count=samples.silhouette_hw[0] * samples.silhouette_hw[1], + ).astype(bool)) + medians.append(float(np.median(samples.predicted_depth_m[samples.visible_vertex]))) + intersection = np.logical_and(packed_masks[0], packed_masks[1]).sum() + union = np.logical_or(packed_masks[0], packed_masks[1]).sum() + surface_fields["silhouette_overlap_fraction"].append( + np.asarray(intersection / max(union, 1), dtype=np.float32) + ) + surface_fields["predicted_depth_order"].append( + np.asarray(np.sign(medians[1] - medians[0]), dtype=np.int8) + ) + + mano_2d_raw, _ = project_points(pred_joints, K_raw) + direct_np = direct_2d[0, :valid_times].cpu().numpy() + raw_to_resized = np.asarray( + (width / raw_hw[1], height / raw_hw[0]), dtype=np.float32, + ) + consistency = np.linalg.norm( + direct_np - mano_2d_raw * raw_to_resized, axis=-1, + ).mean(axis=-1) + hand_scale = projected_hand_scale_px( + mano_2d_raw, source_hw=raw_hw, target_hw=(height, width), + ) + values: dict[str, np.ndarray] = { + "clip_index": np.full(valid_times, global_clip_index, dtype=np.int64), + "frame_id": frame_ids, + "frame_valid": batch["frame_valid"][0, :valid_times].cpu().numpy(), + "K_resized": batch["K"][0, :valid_times].float().cpu().numpy(), + "K_raw": np.broadcast_to(K_raw, (valid_times, 3, 3)).copy(), + "rgb_available": batch["frame_valid"][0, :valid_times].cpu().numpy(), + "depth_available": batch["depth_available"][0, :valid_times].cpu().numpy(), + "K_available": batch["K_available"][0, :valid_times].cpu().numpy(), + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0, :valid_times].float().cpu().numpy(), + "pred_shape": prediction["mano_shape"][0, :valid_times].float().cpu().numpy(), + "pred_wrist_translation": prediction["wrist_root_translation"][0, :valid_times].float().cpu().numpy(), + "pred_joints_camera": pred_joints, + "pred_vertices_camera": pred_vertices, + "pred_direct_2d_px": direct_np, + "pred_joints_raw_px": mano_2d_raw.astype(np.float32), + "coarse_direct_mano_consistency_px": consistency.astype(np.float32), + "coarse_hand_scale_px": hand_scale.astype(np.float32), + "target_rotation_matrices": target_rotations[0, :valid_times].float().cpu().numpy(), + "target_pose_axis_angle": target_pose[0, :valid_times].float().cpu().numpy(), + "target_shape": batch["mano_shape"][0, :valid_times].float().cpu().numpy(), + "target_wrist_translation": batch["wrist_root_translation"][0, :valid_times].float().cpu().numpy(), + "target_joints_camera": target_joints[0, :valid_times].float().cpu().numpy(), + "target_vertices_camera": target_vertices[0, :valid_times].float().cpu().numpy(), + "target_2d_px": batch["joint2d"][0, :valid_times].float().cpu().numpy(), + "joint_annotation_valid": batch["joint_annotation_valid"][0, :valid_times].cpu().numpy(), + "joint_element_valid": batch["joint_element_valid"][0, :valid_times].cpu().numpy(), + "mano_annotation_valid": batch["mano_annotation_valid"][0, :valid_times].cpu().numpy(), + } + values["translation_residual_m"] = ( + values["target_wrist_translation"] - values["pred_wrist_translation"] + ) + for key, hand_values in surface_fields.items(): + stacked = np.stack(hand_values) + if key not in ("silhouette_overlap_fraction", "predicted_depth_order"): + stacked = stacked.reshape(valid_times, 2, *stacked.shape[1:]) + values[key] = stacked + for key, value in values.items(): + chunks[key].append(value) + + arrays = {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + arrays["coarse_wrist_velocity_m_per_frame"] = _velocity( + arrays["pred_wrist_translation"], arrays["frame_id"], + ) + arrays["silhouette_hw"] = np.asarray(silhouette_hw, dtype=np.int32) + return arrays + + +def validate_bank_arrays( + arrays: dict[str, np.ndarray], + *, + take: str, + expected_frame_ids: list[int], + checkpoint_sha256: str, + config_sha256: str, + heldout_manifest_sha256: str, + fold_index: int, +) -> None: + missing = sorted(set(FRAME_ARRAYS) - arrays.keys()) + if missing: + raise ValueError(f"OOF bank is missing arrays: {missing}") + scalars = { + "bank_version": BANK_VERSION, + "take": take, + "checkpoint_sha256": checkpoint_sha256, + "config_sha256": config_sha256, + "heldout_manifest_sha256": heldout_manifest_sha256, + "fold_index": fold_index, + } + for key, expected in scalars.items(): + if str(arrays[key]) != str(expected): + raise ValueError(f"OOF bank scalar mismatch: {key}") + frame_ids = arrays["frame_id"].astype(np.int64).tolist() + if frame_ids != expected_frame_ids or len(frame_ids) != len(set(frame_ids)): + raise ValueError(f"OOF bank frame sequence mismatch for {take}") + for key in FRAME_ARRAYS: + if arrays[key].shape[0] != len(frame_ids): + raise ValueError(f"OOF bank time dimension mismatch: {key}") + if np.issubdtype(arrays[key].dtype, np.floating) and key.startswith("pred_"): + if not np.isfinite(arrays[key]).all(): + raise ValueError(f"non-finite coarse prediction array: {key}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--run-provenance", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--folds-manifest", type=Path, required=True) + parser.add_argument("--fold", type=int, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args() + if "test" in str(args.manifest).lower() or "val" in args.manifest.name.lower(): + parser.error("OOF bank accepts only registered official-train heldout manifests") + contract = resolve_fold_contract( + args.folds_manifest, args.fold, args.manifest, args.run_provenance, + ) + checkpoint_hash = sha256(args.checkpoint) + if checkpoint_hash != args.expected_checkpoint_sha256: + parser.error("checkpoint hash differs from the registered extraction command") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + config_hash = sha256(args.config) + heldout_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (int(config["data"]["T"]),), (int(config["data"]["stride"]),), + max_clips=args.max_clips, + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + expected_frames = { + take: [frame for index in indices for frame in dataset.clips[index].frame_ids] + for take, indices in indices_by_take.items() + } + if any(len(frames) != len(set(frames)) for frames in expected_frames.values()): + raise ValueError("OOF bank requires non-overlapping heldout inference clips") + + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + validate_checkpoint_provenance( + checkpoint, + config=config, + config_path=args.config, + run_provenance_path=args.run_provenance, + provenance=contract["provenance"], + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + records = [] + for take_index, (take, clip_indices) in enumerate(indices_by_take.items(), start=1): + output = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "heldout_manifest_sha256": heldout_hash, + "fold_index": args.fold, + } + if output.exists(): + with np.load(output, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + validate_bank_arrays(arrays, **expected) + status = "reused" + else: + arrays = infer_take( + root=args.root, take=take, dataset=dataset, clip_indices=clip_indices, + model=model, device=device, dtype=dtype, + ) + arrays.update({ + "bank_version": np.asarray(BANK_VERSION, dtype=np.int32), + "take": np.asarray(take), + "subject": np.asarray(take.split("/")[0]), + "action_family": np.asarray(take.split("/")[1]), + "side_names": np.asarray(SIDES), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "heldout_manifest_sha256": np.asarray(heldout_hash), + "fold_index": np.asarray(args.fold, dtype=np.int32), + }) + validate_bank_arrays(arrays, **expected) + save_npz_atomic(output, arrays) + status = "written" + records.append({ + "take": take, "clips": len(clip_indices), "frames": len(expected_frames[take]), + "path": str(output.resolve()), "sha256": sha256(output), "status": status, + }) + print(f"[{take_index}/{len(indices_by_take)}] {take}: {status}", flush=True) + + total_frames = sum(record["frames"] for record in records) + full_fold = args.max_clips is None + if full_fold and total_frames != int(contract["fold"]["heldout"]["frames"]): + raise ValueError("OOF bank heldout frame coverage differs from frozen fold") + report = { + "status": "complete", + "bank_version": BANK_VERSION, + "result_role": "official_train_group_heldout_oof_predictions", + "experiment_class": "preregistered_data_construction", + "official_validation_used_for_assignment": False, + "official_test_used": False, + "oracle_information_at_inference": False, + "gt_usage": "bank targets and post-hoc residual audit only", + "fold": args.fold, + "seed": int(config["seed"]), + "heldout_subject": contract["fold"]["heldout_subject"], + "folds_manifest": {"path": str(args.folds_manifest.resolve()), "sha256": sha256(args.folds_manifest)}, + "train_manifest_sha256": contract["fold"]["train_manifest_sha256"], + "heldout_manifest": {"path": str(args.manifest.resolve()), "sha256": heldout_hash}, + "leakage_audit": contract["fold"]["leakage_audit"], + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, "step": int(checkpoint["step"])}, + "run_provenance": {"path": str(args.run_provenance.resolve()), "sha256": sha256(args.run_provenance)}, + "training_git_commit": contract["provenance"]["git_commit"], + "extractor_git_commit": subprocess.run(["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, check=False).stdout.strip(), + "scope": "full_fold" if full_fold else "smoke", + "clips": len(dataset), "frames": total_frames, "takes": records, + "surface_contract": { + "location": "coarse MANO projection only", + "depth_source": "original aligned H2O metric depth", + "surface": "frontmost projected MANO vertex per 4-pixel cell", + "silhouette": "packed quarter-resolution conservative projected vertex hull", + "solver": "bounded MAD-scaled Huber IRLS; translation-z only", + "hand_scale": "projected coarse MANO joint extent in model-resized pixels", + }, + "arrays": list(FRAME_ARRAYS), + } + (args.output_dir / "bank_manifest.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "fold": args.fold, "clips": report["clips"], + "frames": report["frames"], "takes": len(records), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_adaptation_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_adaptation_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9e5cbc986e127ee1269792135884adc311eaa1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_adaptation_configs.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Build matched A1/A2 configs after strict external zero-shot is complete.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +from pathlib import Path +from typing import Any + +import yaml + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_adaptation_inputs( + selection: dict[str, Any], zero_shot_state: dict[str, Any], split: dict[str, Any], +) -> None: + if ( + selection.get("status") != "selected_external_generalist_no_h2o" + or selection.get("h2o_training_data_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("external selection is not adaptation-eligible") + if ( + zero_shot_state.get("status") != "complete" + or set(zero_shot_state.get("completed_ids", [])) != { + "h2o_strict_zero_shot_rgb_d_k", "h2o_strict_zero_shot_rgb_k", + "h2o_strict_zero_shot_rgb_only", + } + or zero_shot_state.get("official_test_used") is not False + or zero_shot_state.get("h2o_training_data_used") is not False + ): + raise ValueError("strict three-mode H2O zero-shot must complete before adaptation") + if ( + split.get("status") != "frozen_h2o_train_group_split" + or split.get("h2o_official_validation_used") is not False + or split.get("official_test_used") is not False + or split.get("recording_overlap") != [] + ): + raise ValueError("H2O train-only group split is invalid") + + +def adaptation_config( + base: dict[str, Any], selection: dict[str, Any], split: dict[str, Any], branch: str, +) -> dict[str, Any]: + config = copy.deepcopy(base) + config["name"] = f"phase7_{branch.lower()}_scale100k_s20260717" + config["experiment"] = { + "phase": 7, "branch": "h2o_adaptation", "stage": "adaptation_scale_100k", + "condition": branch, "uses_h2o_training_data": True, + "initialization_checkpoint_sha256": selection["checkpoint"]["sha256"], + "initialization_checkpoint_step": selection["checkpoint"]["step"], + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + h2o_source = { + "dataset": "H2O", "split_role": "official_train", "weight": 1.0, + "cache_manifest": split["fit"]["path"], "K_input_dropout": 0.0, + } + if branch == "A1": + sources = [h2o_source] + elif branch == "A2": + source_lookup = { + str(source["dataset"]).upper(): copy.deepcopy(source) + for source in base["data"]["sources"] + } + if set(source_lookup) != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("winning external config is not the E40 three-source mixture") + h2o_source["weight"] = 0.5 + replay_weights = {"HOT3D": 0.2, "HOI4D": 0.2, "ARCTIC": 0.1} + sources = [h2o_source] + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + source = source_lookup[dataset] + source["weight"] = replay_weights[dataset] + source["split_role"] = "external_train" + sources.append(source) + else: + raise ValueError(f"unknown adaptation condition: {branch}") + config["data"]["sources"] = sources + config["data"]["validation_sources"] = [{ + "dataset": "H2O", "split_role": "train_group_heldout", + "cache_manifest": split["heldout"]["path"], "K_input_dropout": 0.0, + }] + config["model"]["modality_dropout_prob"] = 0.0 + config["model"]["dinov3_trainable_last_blocks"] = 0 + return config + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-selection", type=Path, required=True) + parser.add_argument("--zero-shot-state", type=Path, required=True) + parser.add_argument("--h2o-train-split", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + selection = json.loads(args.external_selection.read_text(encoding="utf-8")) + zero_shot = json.loads(args.zero_shot_state.read_text(encoding="utf-8")) + split = json.loads(args.h2o_train_split.read_text(encoding="utf-8")) + validate_adaptation_inputs(selection, zero_shot, split) + base_path = Path(selection["config"]["path"]) + if sha256(base_path) != selection["config"]["sha256"]: + parser.error("selected external config hash mismatch") + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + args.output_dir.mkdir(parents=True) + outputs = {} + for branch in ("A1", "A2"): + config = adaptation_config(base, selection, split, branch) + output = args.output_dir / f"phase7_{branch.lower()}_scale100k_s20260717.yaml" + output.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + outputs[branch] = {"path": str(output.resolve()), "sha256": sha256(output)} + record = { + "status": "adaptation_configs_frozen", "configs": outputs, + "external_selection": { + "path": str(args.external_selection.resolve()), "sha256": sha256(args.external_selection), + }, + "strict_zero_shot_state": { + "path": str(args.zero_shot_state.resolve()), "sha256": sha256(args.zero_shot_state), + }, + "h2o_train_split": { + "path": str(args.h2o_train_split.resolve()), "sha256": sha256(args.h2o_train_split), + }, + "h2o_official_validation_used_for_selection": False, "official_test_used": False, + } + (args.output_dir / "freeze.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_arctic_manifests.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_arctic_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..0dee727076139bcc1bfab8100719f0369d8ff69d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_arctic_manifests.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Build ARCTIC P2 train/val manifests without reading the P2 test list.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_p2_train_val_without_test(path: Path) -> dict[str, list[str]]: + lines: list[str] = [] + saw_test_key = False + with path.open("r", encoding="utf-8") as handle: + for line in handle: + if line.lstrip().startswith('"test"'): + saw_test_key = True + break + lines.append(line) + if not saw_test_key: + raise ValueError("protocol does not contain a test boundary") + prefix = "".join(lines).rstrip() + if prefix.endswith(","): + prefix = prefix[:-1] + record = json.loads(prefix + "\n}\n") + if set(record) != {"train", "val"}: + raise ValueError(f"expected only train/val before test boundary, got {set(record)}") + return record + + +def sequence_rows( + data_root: Path, sequence: str, split: str, clip_length: int, window_step: int, +) -> tuple[list[dict[str, Any]], list[str]]: + subject, take = sequence.split("/", 1) + mano_path = data_root / "raw_seqs" / subject / f"{take}.mano.npy" + camera_path = data_root / "raw_seqs" / subject / f"{take}.egocam.dist.npy" + image_dir = data_root / "cropped_images" / subject / take / "0" + missing = [str(path) for path in (mano_path, camera_path, image_dir) if not path.exists()] + if missing: + return [], missing + mano = np.load(mano_path, allow_pickle=True).item() + frame_count = int(len(mano["right"]["rot"])) + if frame_count != int(len(mano["left"]["rot"])): + raise ValueError(f"left/right frame count differs for {sequence}") + images = sorted(image_dir.glob("*.jpg")) + if len(images) != frame_count: + return [], [f"{sequence}: image count {len(images)} != MANO frames {frame_count}"] + rows = [] + for first in range(1, frame_count - clip_length + 2, window_step): + frame_ids = list(range(first, first + clip_length)) + rows.append({ + "dataset_id": "ARCTIC", + "protocol": "P2", + "split_role": f"arctic_p2_{split}", + "subject_id": subject, + "physical_recording_id": sequence, + "group_key": f"ARCTIC/{subject}/{sequence}", + "camera_id": "ego_view_0_rectified", + "frame_ids_1based": frame_ids, + "array_indices_0based": [value - 1 for value in frame_ids], + "image_paths": [str((image_dir / f"{value:05d}.jpg").resolve()) for value in frame_ids], + "mano_path": str(mano_path.resolve()), + "camera_path": str(camera_path.resolve()), + "depth_input_available": False, + "official_test_used": False, + }) + return rows, [] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--protocol", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--window-step", type=int, default=8) + parser.add_argument("--allow-documented-missing-sequence-exclusions", action="store_true") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + split = read_p2_train_val_without_test(args.protocol) + manifests = {} + missing: dict[str, list[str]] = {} + split_subjects: dict[str, set[str]] = {} + for role in ("train", "val"): + rows = [] + for sequence in split[role]: + sequence_values, absent = sequence_rows( + args.data_root, sequence, role, args.clip_length, args.window_step, + ) + rows.extend(sequence_values) + if absent: + missing[sequence] = absent + path = args.output_dir / f"arctic_p2_{role}_t{args.clip_length}.jsonl" + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + subjects = {row["subject_id"] for row in rows} + split_subjects[role] = subjects + manifests[role] = { + "path": str(path.resolve()), "sha256": sha256(path), + "clips": len(rows), "sequences": len({row["physical_recording_id"] for row in rows}), + "subjects": sorted(subjects), + } + overlap = sorted(split_subjects["train"] & split_subjects["val"]) + usable = not overlap and all(value["clips"] for value in manifests.values()) + status = ( + "passed" if usable and not missing else + "passed_with_documented_exclusions" + if usable and args.allow_documented_missing_sequence_exclusions else + "failed" + ) + report = { + "version": "phase7_arctic_p2_manifest_v1", + "status": status, + "protocol_path": str(args.protocol.resolve()), + "protocol_sha256": sha256(args.protocol), + "test_boundary_contract": "reader stops on the P2 test key before reading any test identity", + "clip_length": args.clip_length, "window_step": args.window_step, + "manifests": manifests, + "train_val_subject_overlap": overlap, + "missing_assets": missing, + "missing_sequence_policy": ( + "exclude entire physical recording from P2 train" + if args.allow_documented_missing_sequence_exclusions else "strict failure" + ), + "official_test_used": False, + } + (args.output_dir / "manifest_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not status.startswith("passed"): + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_continuation_manifest.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_continuation_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5feb4a5390224c6a49a11bd3846c9c91d88ea8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_continuation_manifest.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Bind frozen 50k/100k external evaluations for final checkpoint selection.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from scripts.build_phase7_scale_eval_queue import input_mode + + +DATASETS = ("HOT3D", "HOI4D", "ARCTIC") + + +def build_manifest(evaluation_root: Path, condition: str, steps: tuple[int, ...]) -> dict: + evaluations = [] + for step in steps: + for dataset in DATASETS: + mode = input_mode(condition, dataset) + path = ( + evaluation_root + / f"{condition.lower()}_scale_step{step}_{dataset.lower()}_heldout2048_{mode}" + / "evaluation.json" + ).resolve() + if not path.is_file(): + raise ValueError(f"continuation evaluation missing: {path}") + report = json.loads(path.read_text(encoding="utf-8")) + if int(report.get("checkpoint_step", -1)) != step: + raise ValueError(f"continuation evaluation step mismatch: {path}") + evaluations.append({ + "candidate": f"{condition}_step{step}", "dataset": dataset, + "path": str(path), + }) + return { + "schema_version": "phase7_external_continuation_selection_v1", + "selection_split": "external_heldout_only", "datasets": list(DATASETS), + "condition": condition, "candidate_steps": list(steps), + "h2o_training_data_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--condition", default="E40", choices=("E40", "E70", "E100")) + parser.add_argument("--steps", type=int, nargs="+", default=(50000, 100000)) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + manifest = build_manifest(args.evaluation_root, args.condition, tuple(args.steps)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + print(json.dumps(manifest, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_h2o_zero_shot_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_h2o_zero_shot_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..75fc0a82c687ff6af3ff04114659af6756484fe7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_h2o_zero_shot_queue.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Build the hash-bound three-mode strict H2O zero-shot queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_h2o_zero_shot_queue import validate_queue + + +def build_queue(freeze_path: Path, root: Path, output_root: Path) -> dict: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + status = freeze.get("status") + if status not in { + "external_generalist_frozen", "external_architecture_candidate_frozen", + }: + raise ValueError("external freeze record is incomplete") + if status == "external_architecture_candidate_frozen" and ( + freeze.get("selected_within_family") is not True + or freeze.get("overall_external_generalist_winner") is not False + ): + raise ValueError("external architecture candidate role is ambiguous") + checkpoint = freeze["checkpoint_path"] + checkpoint_sha256 = freeze["checkpoint_sha256"] + manifest = freeze["h2o_validation_manifest"]["path"] + evaluations = [{ + "id": f"h2o_strict_zero_shot_{mode}", "input_mode": mode, + "config": freeze["config_path"], "checkpoint": checkpoint, + "checkpoint_sha256": checkpoint_sha256, + "freeze_record": str(freeze_path.resolve()), "root": str(root.resolve()), + "manifest": manifest, + "output_dir": str((output_root / mode).resolve()), + "bootstrap_resamples": 2000, + } for mode in INPUT_MODES] + queue = { + "schema_version": "phase7_h2o_strict_zero_shot_queue_v1", + "purpose": "One frozen external checkpoint evaluated once in three H2O input modes", + "external_freeze_status": status, + "allowed_physical_gpus": [0, 1, 2, 3], + "official_test_used": False, "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "evaluations": evaluations, + } + validate_queue(queue) + return queue + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + queue = build_queue(args.freeze_record, args.root, args.output_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_hoi4d_manifests.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_hoi4d_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebe2622b2f7c2957b904af4295816fe440fd0c9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_hoi4d_manifests.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Build deterministic group-isolated HOI4D train/held-out clip manifests.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +SERIALS = tuple(f"ZY2021080000{index}" for index in range(1, 5)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def discover_hand_frames(root: Path) -> dict[str, dict[int, set[str]]]: + recordings: dict[str, dict[int, set[str]]] = defaultdict(lambda: defaultdict(set)) + hand_root = root / "Hand_pose" + for side in ("left", "right"): + base = hand_root / f"handpose_{side}_hand" + for directory, _, filenames in os.walk(base): + frame_names = [name for name in filenames if name.endswith(".pickle")] + if not frame_names: + continue + relative = Path(directory).relative_to(base).as_posix() + for name in frame_names: + recordings[relative][int(Path(name).stem)].add(side) + return recordings + + +def split_for_serial(serial: str, heldout_serial: str) -> str: + if serial not in SERIALS: + raise ValueError(f"unknown HOI4D serial: {serial}") + return "heldout" if serial == heldout_serial else "train" + + +def recording_assets(root: Path, recording: str) -> tuple[Path, Path, Path]: + rgb = root / "HOI4D_release" / recording / "align_rgb" / "image.mp4" + depth = ( + root / "HOI4D_release" / "HOI4D_depth_video" / recording + / "align_depth" / "depth_video.avi" + ) + serial = recording.split("/", 1)[0] + K = root / "camera" / serial / "intrin.npy" + return rgb, depth, K + + +def make_rows( + root: Path, + recordings: dict[str, dict[int, set[str]]], + heldout_serial: str, + clip_length: int, + window_step: int, +) -> tuple[dict[str, list[dict[str, Any]]], list[dict[str, str]]]: + rows: dict[str, list[dict[str, Any]]] = {"train": [], "heldout": []} + missing: list[dict[str, str]] = [] + for recording in sorted(recordings): + rgb, depth, K = recording_assets(root, recording) + absent = [str(path) for path in (rgb, depth, K) if not path.is_file()] + if absent: + missing.append({"recording": recording, "missing": ";".join(absent)}) + continue + frames = recordings[recording] + available = sorted(frames) + if not available: + continue + serial, subject = recording.split("/")[:2] + split = split_for_serial(serial, heldout_serial) + frame_set = set(available) + for start in range(available[0], available[-1] + 1, window_step): + ids = list(range(start, start + clip_length)) + if not all(frame in frame_set for frame in ids): + continue + rows[split].append({ + "dataset_id": "HOI4D", + "split_role": f"external_{split}_group_split", + "serial_id": serial, + "subject_id": subject, + "physical_recording_id": recording, + "group_key": f"HOI4D/{subject}/{recording}", + "camera_id": serial, + "fps": 15.0, + "frame_ids": ids, + "timestamps_seconds": [frame / 15.0 for frame in ids], + "hand_sides": [sorted(frames[frame]) for frame in ids], + "rgb_video": str(rgb.resolve()), + "depth_video": str(depth.resolve()), + "K_path": str(K.resolve()), + "official_test_used": False, + }) + return rows, missing + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--heldout-serial", choices=SERIALS, default=SERIALS[-1]) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--window-step", type=int, default=8) + parser.add_argument("--allow-documented-missing-asset-exclusions", action="store_true") + args = parser.parse_args() + if args.clip_length <= 0 or args.window_step <= 0: + parser.error("clip length and window step must be positive") + args.output_dir.mkdir(parents=True, exist_ok=False) + recordings = discover_hand_frames(args.root) + rows, missing = make_rows( + args.root, recordings, args.heldout_serial, + args.clip_length, args.window_step, + ) + manifests = {} + for split, values in rows.items(): + path = args.output_dir / f"hoi4d_{split}_t{args.clip_length}.jsonl" + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in values), + encoding="utf-8", + ) + manifests[split] = { + "path": str(path.resolve()), "sha256": sha256(path), + "clips": len(values), + "subjects": sorted({row["subject_id"] for row in values}), + "recordings": len({row["physical_recording_id"] for row in values}), + "hand_frames": { + side: sum(side in sides for row in values for sides in row["hand_sides"]) + for side in ("left", "right") + }, + } + usable = all(rows.values()) + exclusions_allowed = bool(args.allow_documented_missing_asset_exclusions) + report = { + "version": "phase7_hoi4d_group_split_v1", + "status": ( + "passed" if usable and not missing else + "passed_with_documented_exclusions" if usable and exclusions_allowed else + "failed" + ), + "heldout_policy": "entire device/subject serial held out", + "heldout_serial": args.heldout_serial, + "grouping": "dataset, subject, complete physical recording", + "clip_length": args.clip_length, + "window_step": args.window_step, + "manifests": manifests, + "missing_assets": missing, + "missing_asset_recordings": len(missing), + "missing_asset_policy": ( + "excluded from both training and held-out evaluation; retained in audit" + if exclusions_allowed else "strict failure" + ), + "official_test_used": False, + } + (args.output_dir / "manifest_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not report["status"].startswith("passed"): + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_hot3d_manifests.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_hot3d_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6baac33d76e1336f6bdc82c4a417627d8c123c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_hot3d_manifests.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Build GT-only HOT3D recording-group manifests through official mask APIs.""" + +from __future__ import annotations + +import argparse +import bisect +from collections import Counter +import hashlib +import json +from pathlib import Path +import subprocess +import sys +from typing import Iterable + +from foundation_hand.data.hot3d_dataset import load_hot3d_api + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def participant_split(participants: Iterable[str]) -> tuple[set[str], set[str]]: + ordered = sorted(set(participants)) + if len(ordered) < 4: + raise ValueError("HOT3D participant split requires at least four GT participants") + heldout = {participant for index, participant in enumerate(ordered) if index % 4 == 3} + return set(ordered) - heldout, heldout + + +def contiguous_clips( + timestamps_ns: Iterable[int], + length: int, + max_gap_ns: int = 100_000_000, +) -> list[list[int]]: + timestamps = sorted(set(int(value) for value in timestamps_ns)) + runs: list[list[int]] = [] + current: list[int] = [] + for timestamp in timestamps: + if current and timestamp - current[-1] > max_gap_ns: + runs.append(current) + current = [] + current.append(timestamp) + if current: + runs.append(current) + clips: list[list[int]] = [] + for run in runs: + clips.extend(run[start : start + length] for start in range(0, len(run), length) if len(run[start : start + length]) == length) + return clips + + +def nearest_timestamp( + timestamp_ns: int, + reference_ns: list[int], + maximum_delta_ns: int, +) -> int | None: + position = bisect.bisect_left(reference_ns, int(timestamp_ns)) + candidates = reference_ns[max(0, position - 1) : position + 1] + if not candidates: + return None + nearest = min(candidates, key=lambda value: abs(value - timestamp_ns)) + return nearest if abs(nearest - timestamp_ns) <= maximum_delta_ns else None + + +def write_jsonl(path: Path, rows: list[dict]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--max-recordings", type=int) + parser.add_argument("--max-clips-per-recording-stream", type=int) + args = parser.parse_args() + if args.clip_length < 1: + parser.error("--clip-length must be positive") + + api = load_hot3d_api(args.toolkit_root) + source = args.toolkit_root.resolve() / "hot3d" + if str(source) not in sys.path: + sys.path.insert(0, str(source)) + from data_loaders.loader_hand_poses import load_hand_poses + from data_loaders.loader_masks import combine_mask_data, load_mask_data + + metadata_paths = sorted(args.root.glob("P*/metadata.json")) + metadata: list[tuple[Path, dict]] = [] + no_gt_count = 0 + for path in metadata_paths: + record = json.loads(path.read_text(encoding="utf-8")) + if record.get("have_hand_object_pose_gt") is not True: + no_gt_count += 1 + continue + metadata.append((path.parent, record)) + if args.max_recordings is not None: + metadata = metadata[: args.max_recordings] + participants = [record["participant_id"] for _, record in metadata] + train_participants, heldout_participants = participant_split(participants) + rows: dict[str, list[dict]] = {"train": [], "heldout": []} + skipped: Counter[str] = Counter() + counts: Counter[str] = Counter() + required_masks = ( + "mask_hand_visible.csv", + "mask_headset_pose_available.csv", + "mask_good_exposure.csv", + "mask_qa_pass.csv", + ) + for recording_dir, record in metadata: + missing = [ + name for name in required_masks + if not (recording_dir / "masks" / name).is_file() + ] + if missing: + skipped["missing_masks"] += 1 + continue + masks = [ + load_mask_data(str(recording_dir / "masks" / name)) + for name in required_masks + ] + combined = combine_mask_data(masks, "and") + hand_poses = load_hand_poses( + str(recording_dir / "mano_hand_pose_trajectory.jsonl") + ) + hand_timestamps = sorted(hand_poses) + streams = ["214-1"] if record["headset"] == "Aria" else ["1201-1", "1201-2"] + split = "train" if record["participant_id"] in train_participants else "heldout" + for stream_id in streams: + stream_mask = combined.data.get(stream_id) + if stream_mask is None: + skipped[f"missing_stream_{stream_id}"] += 1 + continue + timestamp_to_pose = { + timestamp: nearest_timestamp(timestamp, hand_timestamps, 20_000_000) + for timestamp, valid in stream_mask.items() if valid + } + timestamp_to_pose = { + timestamp: pose_timestamp + for timestamp, pose_timestamp in timestamp_to_pose.items() + if pose_timestamp is not None + } + clips = contiguous_clips(timestamp_to_pose, args.clip_length) + if args.max_clips_per_recording_stream is not None: + clips = clips[: args.max_clips_per_recording_stream] + for clip_index, timestamps in enumerate(clips): + rows[split].append({ + "dataset": "HOT3D", + "split": split, + "participant_id": record["participant_id"], + "recording_id": record["recording_name"], + "physical_recording_id": record["recording_name"], + "headset": record["headset"], + "stream_id": stream_id, + "clip_index_in_stream": clip_index, + "timestamps_ns": timestamps, + "hand_pose_timestamp_ns": [timestamp_to_pose[value] for value in timestamps], + "hand_count": [ + len(hand_poses[timestamp_to_pose[value]].poses) + for value in timestamps + ], + "have_hand_object_pose_gt": True, + "depth_input_available": False, + "K_input_dropout": 0.3, + "group_key": f"HOT3D/{record['participant_id']}/{record['recording_name']}", + }) + counts[f"{split}/{record['headset']}/{stream_id}"] += len(clips) + + args.output_dir.mkdir(parents=True, exist_ok=True) + paths = {} + for split, split_rows in rows.items(): + path = args.output_dir / f"hot3d_{split}_t{args.clip_length}.jsonl" + write_jsonl(path, split_rows) + paths[split] = {"path": str(path.resolve()), "sha256": sha256(path), "clips": len(split_rows)} + toolkit_commit = subprocess.run( + ["git", "-C", str(args.toolkit_root), "rev-parse", "HEAD"], + text=True, stdout=subprocess.PIPE, check=True, + ).stdout.strip() + audit = { + "status": "built", + "official_test_used": False, + "gt_metadata_records": len(metadata), + "excluded_no_gt_metadata_records": no_gt_count, + "train_participants": sorted(train_participants), + "heldout_participants": sorted(heldout_participants), + "participant_overlap": sorted(train_participants & heldout_participants), + "counts": dict(sorted(counts.items())), + "skipped": dict(sorted(skipped.items())), + "clip_length": args.clip_length, + "required_masks": list(required_masks), + "pose_contract": "nearest official MANO timestamp within 20ms; one or two hands allowed", + "toolkit": {"path": str(args.toolkit_root.resolve()), "git_commit": toolkit_commit}, + "manifests": paths, + } + output = args.output_dir / "hot3d_manifest_audit.json" + output.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") + print(json.dumps(audit, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_scale_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_scale_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..104816c1155e66759d9276dae8052af0f372be82 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase7_scale_eval_queue.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Build a hash-bound formal evaluation queue for a matched scale step.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.run_phase7_heldout_cache_queue import output_complete + + +CONDITIONS = ("E40", "E70", "E100") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def stage_suffix(step: int) -> str: + suffixes = {2000: "2k", 10000: "10k", 50000: "50k", 100000: "100k"} + try: + return suffixes[step] + except KeyError as error: + raise ValueError(f"unsupported formal matched step: {step}") from error + + +def read_marker(run_root: Path, condition: str, step: int) -> dict[str, Any]: + marker_path = run_root / ".phase7_queue" / f"{condition}_scale_{stage_suffix(step)}.json" + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker["checkpoint"]) + config = Path(marker["config"]) + if ( + marker.get("status") != "complete" + or int(marker.get("completed_step", -1)) != step + or marker.get("official_test_used") is not False + or marker.get("h2o_training_data_used") is not False + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or not config.is_file() + or marker.get("config_sha256") != sha256(config) + ): + raise ValueError(f"scale marker failed frozen contract: {marker_path}") + return marker + + +def input_mode(condition: str, dataset: str) -> str: + if dataset == "HOI4D" and condition != "E100": + return "rgb_d_k" + return "rgb_k" + + +def build_queue( + plan: dict[str, Any], run_roots: dict[str, Path], step: int, + evaluation_root: Path, conditions: tuple[str, ...] = CONDITIONS, +) -> dict[str, Any]: + if plan.get("official_test_used") is not False or plan.get("h2o_used") is not False: + raise ValueError("formal cache plan is not external-only") + sources = {item["dataset"]: item for item in plan["sources"]} + if set(sources) != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("formal cache plan lacks the complete dataset grid") + for item in sources.values(): + if not output_complete(item): + raise ValueError(f"formal held-out cache is incomplete: {item['dataset']}") + markers = { + condition: read_marker(run_roots[condition], condition, step) + for condition in conditions + } + evaluations = [] + for condition in conditions: + marker = markers[condition] + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + source = sources[dataset] + mode = input_mode(condition, dataset) + evaluations.append({ + "id": f"{condition}_{dataset}_scale_step{step}_{mode}", + "config": marker["config"], + "checkpoint": marker["checkpoint"], + "checkpoint_sha256": marker["checkpoint_sha256"], + "cache_manifest": str( + (Path(source["output_dir"]) / "cache_manifest.jsonl").resolve() + ), + "input_mode": mode, + "output_dir": str(( + evaluation_root + / f"{condition.lower()}_scale_step{step}_{dataset.lower()}_heldout2048_{mode}" + ).resolve()), + "bootstrap_resamples": 2000, + }) + return { + "schema_version": "phase7_external_eval_queue_v1", + "purpose": f"Formal matched external scale evaluation at step {step}", + "matched_step": step, "selection_split": "external_heldout_only", + "official_test_used": False, "h2o_training_data_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--formal-cache-plan", type=Path, required=True) + parser.add_argument( + "--step", type=int, choices=(2000, 10000, 50000, 100000), required=True, + ) + parser.add_argument( + "--conditions", nargs="+", choices=CONDITIONS, default=list(CONDITIONS), + ) + parser.add_argument("--e40-run", type=Path, required=True) + parser.add_argument("--e70-run", type=Path, required=True) + parser.add_argument("--e100-run", type=Path, required=True) + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output queue already exists") + plan = json.loads(args.formal_cache_plan.read_text(encoding="utf-8")) + queue = build_queue( + plan, {"E40": args.e40_run, "E70": args.e70_run, "E100": args.e100_run}, + args.step, args.evaluation_root, tuple(args.conditions), + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_adaptation_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_adaptation_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..73840a2414c7276121f0302064f82599ffb40c11 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_adaptation_eval_queue.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-mode H2O train-heldout adaptation evaluation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +HELDOUT = Path( + "/home/jiasen/foundation_hand/artifacts/phase7/manifests/" + "h2o_train_group_cv_v1/train_group_heldout.jsonl" +) +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, + condition: str, + step: int, + config: Path, + config_sha256: str, + checkpoint: Path, + checkpoint_sha256: str, + output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not condition or any(character.isspace() for character in condition): + raise ValueError("condition must be a nonempty whitespace-free identifier") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap_resamples must be positive") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + if not HELDOUT.is_file(): + raise ValueError("frozen H2O train-group-heldout manifest is missing") + evaluations = [ + { + "id": f"{condition}_step{step}_{input_mode}", + "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(HELDOUT.resolve()), + "cache_manifest_sha256": sha256(HELDOUT), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str( + (output_root / f"{condition}_step{step}_{input_mode}").resolve() + ), + } + for input_mode in INPUT_MODES + ] + return { + "schema_version": "phase8_adaptation_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "Three-mode H2O train-group-heldout selection evaluation.", + "selection_split": "h2o_train_group_heldout_only", + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, + step=args.step, + config=args.config, + config_sha256=args.config_sha256, + checkpoint=args.checkpoint, + checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_adaptation_forgetting_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_adaptation_forgetting_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8f458e2c336aefbba9a75f8127f54f089f1f6f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_adaptation_forgetting_queue.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Build hash-bound external forgetting diagnostics for an H2O-adapted model.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +DOMAINS = { + "HOT3D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), + "HOI4D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_d_k", + ), + "ARCTIC": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "arctic_val2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, + condition: str, + step: int, + config: Path, + config_sha256: str, + checkpoint: Path, + checkpoint_sha256: str, + output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not condition or any(character.isspace() for character in condition): + raise ValueError("condition must be a nonempty whitespace-free identifier") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap_resamples must be positive") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + evaluations = [] + for dataset, (manifest_string, input_mode) in DOMAINS.items(): + manifest = Path(manifest_string) + if not manifest.is_file() or "h2o" in str(manifest).lower(): + raise ValueError(f"external forgetting manifest is invalid: {manifest}") + evaluations.append({ + "id": f"{condition}_step{step}_{dataset}_{input_mode}", + "dataset": dataset, + "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str( + (output_root / f"{condition}_step{step}" / f"{dataset}_{input_mode}").resolve() + ), + }) + return { + "schema_version": "phase8_adaptation_forgetting_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "External held-out forgetting diagnostic only; never used for H2O selection.", + "evaluation_split": "external_heldout_forgetting_diagnostic_only", + "selection_use": False, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, + config=args.config, config_sha256=args.config_sha256, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_egodexter_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_egodexter_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..e2873ce3d5a27694cfbb51342326605472cc5f09 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_egodexter_queue.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Build one frozen model's six-condition EgoDexter zero-shot queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_egodexter_zero_shot import sha256, validate_freeze_record + + +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") +INFERENCE_MODES = ("offline", "causal") + + +def build_queue( + freeze_path: Path, model_id: str, root: Path, output_root: Path, +) -> dict[str, Any]: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + models = {item["id"]: item for item in freeze.get("models", [])} + if model_id not in models: + raise ValueError("model is absent from the final freeze") + model = models[model_id] + checkpoint = Path(model["checkpoint"]) + if not checkpoint.is_file() or sha256(checkpoint) != model["checkpoint_sha256"]: + raise ValueError("frozen checkpoint is missing or SHA256 differs") + if not root.is_dir() or not (root / "data").is_dir(): + raise ValueError("EgoDexter root is invalid") + evaluations = [] + for inference_mode in INFERENCE_MODES: + config = Path(model["inference_configs"][inference_mode]["path"]) + validate_freeze_record( + freeze, model_id, model["checkpoint_sha256"], config, inference_mode, + ) + for input_mode in INPUT_MODES: + evaluations.append({ + "id": f"{model_id}_{inference_mode}_{input_mode}", + "model_id": model_id, + "freeze_record": str(freeze_path.resolve()), + "config": str(config.resolve()), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": model["checkpoint_sha256"], + "root": str(root.resolve()), + "input_mode": input_mode, + "inference_mode": inference_mode, + "window": 8, + "output_dir": str((output_root / inference_mode / input_mode).resolve()), + }) + return { + "schema_version": "phase8_egodexter_zero_shot_queue_v1", + "model_id": model_id, + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--model-id", required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + queue = build_queue(args.freeze_record, args.model_id, args.root, args.output_root) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_external_tail_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_external_tail_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..57d07512de8608b779e00ee27b66ee001473fca7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_external_tail_queue.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Build a hash-bound 100k-to200k minimum-LR external continuation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + +import yaml + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, condition: str, config_path: Path, config_sha256: str, + output_dir: Path, checkpoint: Path, checkpoint_sha256: str, + resume_step: int = 100000, end_step: int = 200000, +) -> dict[str, Any]: + if not config_path.is_file() or sha256(config_path) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("resume checkpoint is missing or SHA256 differs") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + if config.get("experiment", {}).get("branch") != "external_only": + raise ValueError("schedule tail is restricted to external-only configs") + max_steps = int(config["protocol"]["max_steps"]) + if max_steps != resume_step or not end_step > resume_step: + raise ValueError("tail requires resume_step=config max_steps < end_step") + expected_checkpoint = output_dir / f"step_{resume_step:07d}_final.pt" + if checkpoint.resolve() != expected_checkpoint.resolve(): + raise ValueError("checkpoint path is not the final artifact in output_dir") + required_caches = [] + for source in config["data"]["sources"]: + manifest = Path(source["cache_manifest"]) + report_path = manifest.parent / "cache_report.json" + if not manifest.is_file() or not report_path.is_file(): + raise ValueError(f"source cache is incomplete: {manifest}") + report = json.loads(report_path.read_text(encoding="utf-8")) + clips = report.get("clips", report.get("cached_clips")) + recorded = report.get("cache_manifest", {}) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or int(clips or -1) <= 0 + or recorded.get("sha256") != sha256(manifest) + ): + raise ValueError(f"source cache report is not hash-valid: {report_path}") + required_caches.append({ + "id": f"{source['dataset']}_{clips}", + "report": str(report_path.resolve()), + "manifest": str(manifest.resolve()), + "expected_clips": int(clips), + }) + return { + "schema_version": "phase8_external_schedule_tail_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": f"Exact-resume {condition} from {resume_step} to {end_step} at the registered minimum LR.", + "official_test_used": False, "h2o_training_data_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], + "required_caches": required_caches, + "stages": [{ + "id": f"{condition}_{end_step}_min_lr_tail", + "config": str(config_path.resolve()), + "config_sha256": config_sha256, + "output_dir": str(output_dir.resolve()), + "resume_from_step": resume_step, + "resume_checkpoint_sha256": checkpoint_sha256, + "stop_after_step": end_step, + "allow_schedule_tail": True, + }], + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--resume-step", type=int, default=100000) + parser.add_argument("--end-step", type=int, default=200000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, config_path=args.config, + config_sha256=args.config_sha256, output_dir=args.output_dir, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + resume_step=args.resume_step, end_step=args.end_step, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_h2o_adapted_validation_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_h2o_adapted_validation_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c9eec9bc1340e152be7824e02131c5ed03efc0b7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_h2o_adapted_validation_queue.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-mode formal H2O adaptation validation queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_external import sha256 +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_h2o_adapted_validation_queue import validate_queue + + +def build_queue(freeze_path: Path, root: Path, output_root: Path) -> dict[str, Any]: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + if ( + freeze.get("status") != "h2o_adaptation_candidate_frozen" + or freeze.get("selection_split") != "h2o_train_group_heldout_only" + or freeze.get("h2o_official_validation_used_for_selection") is not False + or freeze.get("h2o_training_data_used") is not True + or freeze.get("official_test_used") is not False + ): + raise ValueError("adaptation freeze record is incomplete") + checkpoint = freeze.get("checkpoint", {}) + config = freeze.get("config", {}) + manifest = freeze.get("h2o_validation_manifest", {}) + for record, label in ( + (checkpoint, "checkpoint"), (config, "config"), (manifest, "manifest"), + ): + path = Path(record.get("path", "")) + if not path.is_file() or sha256(path) != record.get("sha256"): + raise ValueError(f"frozen {label} is missing or SHA256 differs") + if Path(manifest["path"]).name != "official_val.jsonl": + raise ValueError("only canonical H2O official validation is allowed") + if set(freeze.get("frozen_h2o_input_modes", [])) != set(INPUT_MODES): + raise ValueError("adaptation freeze record does not bind all input modes") + if not root.is_dir() or not (root / "subject3").is_dir(): + raise ValueError("H2O root does not contain the canonical validation subject") + evaluations = [{ + "id": f"{freeze['winner']}_formal_{mode}", + "input_mode": mode, + "config": str(Path(config["path"]).resolve()), + "checkpoint": str(Path(checkpoint["path"]).resolve()), + "checkpoint_sha256": checkpoint["sha256"], + "freeze_record": str(freeze_path.resolve()), + "root": str(root.resolve()), + "manifest": str(Path(manifest["path"]).resolve()), + "output_dir": str((output_root / mode).resolve()), + "bootstrap_resamples": 2000, + } for mode in INPUT_MODES] + queue = { + "schema_version": "phase8_h2o_adapted_validation_queue_v1", + "purpose": "Formal validation of one train-heldout-frozen H2O adaptation candidate.", + "selection_split": "h2o_train_group_heldout_only", + "allowed_physical_gpus": [0, 1, 2, 3], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "evaluations": evaluations, + } + validate_queue(queue) + return queue + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + queue = build_queue(args.freeze_record, args.root, args.output_root) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_left_root_relative_sidecars.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_left_root_relative_sidecars.py new file mode 100644 index 0000000000000000000000000000000000000000..1613c74abf4e6474d9947f19ff38ba45a442d1aa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_left_root_relative_sidecars.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Attach target-only historical-left joint supervision to existing caches.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def left_only_target( + target: torch.Tensor, + source_valid: torch.Tensor, + translation_valid: torch.Tensor, + frame_valid: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + if target.shape[-2:] != (21, 3): + raise ValueError("target must end in [21,3]") + if source_valid.shape != target.shape[:-1]: + raise ValueError("source-valid shape differs from target") + if translation_valid.shape != target.shape[:-2]: + raise ValueError("translation-valid shape differs from target") + if frame_valid.shape != target.shape[:-3]: + raise ValueError("frame-valid shape differs from target") + valid = ( + source_valid.bool() + & translation_valid.bool()[..., None] + & frame_valid.bool()[..., None, None] + ) + valid[..., 1, :] = False + target = target.clone().masked_fill(~valid[..., None], float("nan")) + return target, valid + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--expected-source-manifest-sha256", required=True) + parser.add_argument("--expected-cache-manifest-sha256", required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--resume", action="store_true") + parser.add_argument("--torch-threads", type=int, default=0) + args = parser.parse_args() + if sha256(args.source_manifest) != args.expected_source_manifest_sha256: + parser.error("source manifest SHA256 differs") + if sha256(args.cache_manifest) != args.expected_cache_manifest_sha256: + parser.error("cache manifest SHA256 differs") + if args.torch_threads < 0: + parser.error("--torch-threads cannot be negative") + if args.torch_threads: + torch.set_num_threads(args.torch_threads) + torch.set_num_interop_threads(1) + if args.resume: + if not (args.output_dir / "sidecars").is_dir(): + parser.error("--resume requires an existing sidecars directory") + elif args.output_dir.exists(): + parser.error("output directory already exists") + if args.dataset == "HOI4D": + if args.root is None: + parser.error("HOI4D requires --root") + dataset = HOI4DClipDataset( + args.root, args.source_manifest, args.mano_root, + ) + else: + dataset = ARCTICClipDataset(args.source_manifest, args.mano_root) + rows = read_jsonl(args.cache_manifest) + args.output_dir.mkdir(parents=True, exist_ok=args.resume) + sidecars = args.output_dir / "sidecars" + sidecars.mkdir(exist_ok=args.resume) + augmented: list[dict[str, Any] | None] = [None] * len(rows) + left_hand_frames = 0 + right_joint_count = 0 + root_norm_max_mm = 0.0 + started = time.monotonic() + order = sorted( + range(len(rows)), + key=lambda position: ( + str(rows[position]["physical_recording_id"]), + int(rows[position]["source_clip_index"]), + ), + ) + for processed, position in enumerate(order, start=1): + row = rows[position] + source_index = int(row["source_clip_index"]) + path = sidecars / f"clip_{source_index:07d}.npz" + if path.is_file() and args.resume: + try: + with np.load(path, allow_pickle=False) as sidecar: + if set(sidecar.files) != { + "joint3d_root_relative", "joint3d_root_relative_valid", + }: + raise ValueError("unexpected sidecar keys") + target = torch.from_numpy(sidecar["joint3d_root_relative"]) + valid = torch.from_numpy( + sidecar["joint3d_root_relative_valid"] + ).bool() + except (OSError, ValueError, EOFError): + preserved = path.with_name( + f"{path.name}.invalid_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}" + ) + path.rename(preserved) + if not path.is_file(): + target, source_valid = dataset.source_root_relative_joint3d(source_index) + with np.load(row["cache_path"], allow_pickle=False) as cache: + translation_valid = torch.from_numpy(cache["translation_valid"]).bool() + frame_valid = torch.from_numpy(cache["frame_valid"]).bool() + target, valid = left_only_target( + target, source_valid, translation_valid, frame_valid, + ) + temporary = path.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed( + handle, + joint3d_root_relative=target.numpy(), + joint3d_root_relative_valid=valid.numpy(), + ) + temporary.replace(path) + output_row = dict(row) + output_row.update({ + "joint3d_root_relative_sidecar_path": str(path.resolve()), + "joint3d_root_relative_sidecar_sha256": sha256(path), + "joint3d_root_relative_scope": "historical_left_only", + }) + augmented[position] = output_row + left_hand_frames += int(valid[..., 0, :].any(-1).sum()) + right_joint_count += int(valid[..., 1, :].sum()) + finite_roots = valid[..., 0, 0] + if finite_roots.any(): + root_norm_max_mm = max( + root_norm_max_mm, + float(torch.linalg.vector_norm(target[..., 0, 0, :][finite_roots], dim=-1).max() * 1000.0), + ) + if processed % 500 == 0 or processed == len(order): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": processed, + "clips": len(order), + "clips_per_second": processed / max(elapsed, 1e-9), + "eta_seconds": (len(order) - processed) / max(processed / elapsed, 1e-9), + }), flush=True) + if any(row is None for row in augmented): + raise RuntimeError("augmented manifest contains missing rows") + manifest = args.output_dir / "cache_manifest.jsonl" + manifest.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in augmented), + encoding="utf-8", + ) + elapsed = time.monotonic() - started + report = { + "schema_version": "phase8_left_root_relative_sidecars_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "dataset": args.dataset, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "base_cache_manifest": {"path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest)}, + "augmented_cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "clips": len(rows), + "left_hand_frames": left_hand_frames, + "right_valid_joint_count": right_joint_count, + "root_norm_max_mm": root_norm_max_mm, + "shape_supervision_restored": False, + "vertices_supervision_restored": False, + "camera_joint3d_supervision_restored": False, + "wall_seconds": elapsed, + "clips_per_second": len(rows) / max(elapsed, 1e-9), + "bytes": sum(path.stat().st_size for path in sidecars.iterdir()), + "resume_invocation": bool(args.resume), + "torch_threads": args.torch_threads or torch.get_num_threads(), + "official_test_used": False, + } + report_path = args.output_dir / "sidecar_report.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if not left_hand_frames or right_joint_count or root_norm_max_mm >= 1e-4: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_specialist_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_specialist_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa0f9aa72435130c16fcd98a84a0963d098f45f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_specialist_eval_queue.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-domain evaluation queue for one external checkpoint.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +DOMAINS = { + "HOT3D": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_only"), + }, + "HOI4D": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_d_k", "rgb_only"), + }, + "ARCTIC": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_val2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_only"), + }, +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, condition: str, step: int, config: Path, config_sha256: str, + checkpoint: Path, checkpoint_sha256: str, output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap resamples must be positive") + evaluations = [] + for dataset, domain in DOMAINS.items(): + manifest = Path(domain["cache_manifest"]) + if not manifest.is_file(): + raise ValueError(f"held-out manifest is missing: {manifest}") + slug = dataset.lower() + for input_mode in domain["input_modes"]: + evaluations.append({ + "id": f"{condition}_step{step}_{dataset}_{input_mode}", + "dataset": dataset, + "matrix_role": "primary_matched_rgb_k" if input_mode == "rgb_k" else "input_diagnostic", + "config": str(config.resolve()), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str((output_root / f"{condition}_step{step}" / f"{slug}_{input_mode}").resolve()), + }) + return { + "schema_version": "phase8_specialist_cross_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "Frozen matched RGB-K cross-domain matrix plus RGB-only and HOI4D RGB-D-K diagnostics.", + "condition": condition, "checkpoint_step": step, + "h2o_training_data_used": False, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, + config=args.config, config_sha256=args.config_sha256, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_stage7_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_stage7_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5db2287015b04a005106f0656ae4231c42687dcb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase8_stage7_eval_queue.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Build a hash-bound Stage 7 external held-out evaluation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase8_specialist_eval_queue import sha256 + + +STAGE7_DOMAINS = { + "HOT3D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), + "HOI4D": ( + "/SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/" + "hoi4d_heldout_left_root_relative_sidecars_v1/cache_manifest.jsonl", + "rgb_d_k", + ), + "ARCTIC": ( + "/SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/" + "arctic_p2_val_left_root_relative_sidecars_v1/cache_manifest.jsonl", + "rgb_k", + ), +} + + +def build_queue( + *, condition: str, step: int, config: Path, config_sha256: str, + checkpoint: Path, checkpoint_sha256: str, output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if condition not in {"L0_sampler_only", "L1_left_root_relative"}: + raise ValueError("condition is not a frozen Stage 7 condition") + if step != 10000 or bootstrap_resamples <= 0: + raise ValueError("Stage 7 evaluation requires step10k and positive resamples") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + evaluations = [] + for dataset, (manifest_string, input_mode) in STAGE7_DOMAINS.items(): + manifest = Path(manifest_string) + if not manifest.is_file() or "h2o" in str(manifest).lower(): + raise ValueError(f"invalid Stage 7 held-out manifest: {manifest}") + evaluations.append({ + "id": f"{condition}_step10000_{dataset}_{input_mode}", + "dataset": dataset, "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, "bootstrap_resamples": bootstrap_resamples, + "output_dir": str((output_root / condition / f"{dataset}_{input_mode}").resolve()), + }) + return { + "schema_version": "phase8_stage7_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "condition": condition, "checkpoint_step": step, + "evaluation_split": "external_heldout_only", + "h2o_training_data_used": False, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, config=args.config, + config_sha256=args.config_sha256, checkpoint=args.checkpoint, + checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_final_deployment_plan.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_final_deployment_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..bd59e8112af6f89be4d8c8387647095fdb424bf8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_final_deployment_plan.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""Build the post-selection formal-validation and deployment-audit job plan.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +LENGTHS = [1, 2, 4, 8, 16, 32, 64] +ORDERING_LENGTHS = [31, 64, 257] + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def derive_causal_config(config: dict[str, Any]) -> dict[str, Any]: + result = deepcopy(config) + if result.get("model", {}).get("temporal_attention_mode") != "bidirectional": + raise ValueError("final checkpoint config is not the frozen bidirectional control") + result["model"]["temporal_attention_mode"] = "causal" + return result + + +def write_causal_config(source: Path, output: Path) -> str: + original = yaml.safe_load(source.read_text(encoding="utf-8")) + causal = derive_causal_config(original) + output.parent.mkdir(parents=True, exist_ok=True) + rendered = yaml.safe_dump(causal, sort_keys=False) + if output.exists(): + if yaml.safe_load(output.read_text(encoding="utf-8")) != causal: + raise ValueError("existing final causal config differs") + else: + temporary = output.with_suffix(".tmp") + temporary.write_text(rendered, encoding="utf-8") + temporary.replace(output) + return sha256(output) + + +def build_plan( + *, freeze_path: Path, freeze_state_path: Path, output_root: Path, + worker_state_root: Path, causal_config_path: Path, h2o_root: Path, +) -> dict[str, Any]: + state = read_json(freeze_state_path) + freeze = read_json(freeze_path) + if ( + state.get("status") != "complete" + or state.get("freeze_sha256") != sha256(freeze_path) + or freeze.get("status") != "phase9_final_unified_checkpoint_frozen" + or freeze.get("h2o_official_validation_used") is not False + or freeze.get("h2o_official_validation_used_for_selection") is not False + or freeze.get("official_test_used") is not False + ): + raise ValueError("final deployment freeze is incomplete or unbound") + checkpoint = freeze["checkpoint"] + config = freeze["config"] + validation = freeze["h2o_validation_manifest"] + training = freeze["h2o_training_manifest"] + for record, label in ( + (checkpoint, "checkpoint"), (config, "config"), + (validation, "validation manifest"), (training, "training manifest"), + ): + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"frozen final {label} differs") + causal_sha = write_causal_config(Path(config["path"]), causal_config_path) + if not h2o_root.is_dir(): + raise ValueError("canonical H2O root is missing") + common = { + "checkpoint": checkpoint["path"], + "checkpoint_sha256": checkpoint["sha256"], + "checkpoint_step": checkpoint["step"], + "config": config["path"], "config_sha256": config["sha256"], + "freeze_record": str(freeze_path.resolve()), + "freeze_record_sha256": sha256(freeze_path), + "root": str(h2o_root.resolve()), + } + jobs = [] + for gpu, mode in enumerate(INPUT_MODES): + jobs.append({ + **common, "id": f"formal_{mode}", "kind": "formal_validation", + "physical_gpu_id": gpu, "input_mode": mode, + "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output_dir": str((output_root / "formal_h2o" / mode).resolve()), + }) + jobs.append({ + **common, "id": "variable_length", "kind": "variable_length", + "physical_gpu_id": 0, "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output": str((output_root / "audits" / "variable_length.json").resolve()), + "lengths": LENGTHS, + }) + for index, frames in enumerate(ORDERING_LENGTHS, start=1): + for mode in ("offline", "causal"): + job_config = config if mode == "offline" else { + "path": str(causal_config_path.resolve()), "sha256": causal_sha, + } + jobs.append({ + **common, "id": f"{mode}_w8_{frames}", "kind": "sequence", + "physical_gpu_id": index, "mode": mode, "window": 8, + "frames": frames, "config": job_config["path"], + "config_sha256": job_config["sha256"], + "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output": str(( + output_root / "audits" / f"{mode}_w8_{frames}.json" + ).resolve()), + }) + jobs.append({ + **common, "id": "latency_vram", "kind": "profile", + "physical_gpu_id": 3, "manifest": training["path"], + "manifest_sha256": training["sha256"], + "resolution_hw": freeze["resolution_hw"], + "output": str((output_root / "audits" / "latency_vram.json").resolve()), + }) + ids = [job["id"] for job in jobs] + outputs = [job.get("output", job.get("output_dir")) for job in jobs] + if len(jobs) != 11 or len(set(ids)) != 11 or len(set(outputs)) != 11: + raise ValueError("final deployment jobs are not unique and complete") + workers = [] + for gpu in range(4): + workers.append({ + "id": f"gpu{gpu}", "physical_gpu_id": gpu, + "state": str((worker_state_root / f"gpu{gpu}_state.json").resolve()), + "job_ids": [job["id"] for job in jobs if job["physical_gpu_id"] == gpu], + }) + assigned = [identifier for worker in workers for identifier in worker["job_ids"]] + if sorted(assigned) != sorted(ids) or len(set(assigned)) != 11: + raise ValueError("final deployment worker assignment overlaps or omits jobs") + return { + "schema_version": "phase9_final_deployment_plan_v1", + "status": "frozen_ready_post_selection", + "created_utc": freeze["created_utc"], + "freeze": {"path": str(freeze_path.resolve()), "sha256": sha256(freeze_path)}, + "winner": freeze["winner"], + "selected_mechanism": freeze["selected_mechanism"], + "resolution_hw": freeze["resolution_hw"], + "shared_augmentation": freeze["shared_augmentation"], + "checkpoint": checkpoint, "config": config, + "causal_config": { + "path": str(causal_config_path.resolve()), "sha256": causal_sha, + "only_change": "model.temporal_attention_mode=causal", + }, + "jobs": jobs, "workers": workers, + "official_validation_checkpoint_count": 1, + "formal_validation_modes": list(INPUT_MODES), + "variable_lengths": LENGTHS, + "sequence_contract": { + "offline_window": 8, "causal_window": 8, + "ordering_lengths": ORDERING_LENGTHS, + }, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze", type=Path, required=True) + parser.add_argument("--freeze-state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--causal-config", type=Path, required=True) + parser.add_argument("--h2o-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + freeze_path=args.freeze, freeze_state_path=args.freeze_state, + output_root=args.output_root, worker_state_root=args.worker_state_root, + causal_config_path=args.causal_config, h2o_root=args.h2o_root, + ) + if args.output.exists(): + if read_json(args.output) != plan: + raise ValueError("existing final deployment plan differs") + else: + atomic_json(args.output, plan) + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_plan_state_v1", + "status": "complete", "plan": str(args.output.resolve()), + "plan_sha256": sha256(args.output), "job_count": len(plan["jobs"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_plan_state_v1", + "status": "failed_resumable", + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }) + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_fold_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_fold_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..e98a67efcafc5b55c0d5ea9199882374ee8b7a3c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_fold_configs.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Generate hash-bound six-fold Phase 9 unified training configurations.""" + +from __future__ import annotations + +import argparse +import copy +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path + +import yaml + +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--multifold-index", type=Path, required=True) + parser.add_argument("--base-config", type=Path, action="append", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--run-root", type=Path, required=True) + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--data-readiness-state", type=Path, required=True) + parser.add_argument("--data-finalize-plan-sha256", required=True) + parser.add_argument("--initialization-checkpoint", type=Path, required=True) + parser.add_argument("--initialization-checkpoint-sha256", required=True) + parser.add_argument( + "--refresh", action="store_true", + help="Replace preregistered configs only when no training checkpoint exists.", + ) + args = parser.parse_args() + if (args.output_dir.exists() or args.registry.exists()) and not args.refresh: + parser.error("fold config output and registry must be new") + if args.refresh and args.run_root.exists() and any(args.run_root.rglob("*.pt")): + parser.error("cannot refresh fold configs after a training checkpoint exists") + if sha256(args.initialization_checkpoint) != args.initialization_checkpoint_sha256: + parser.error("initialization checkpoint SHA256 differs") + index = json.loads(args.multifold_index.read_text(encoding="utf-8")) + if index.get("status") != "complete" or index.get("official_test_used") is not False: + parser.error("multifold index is incomplete or lacks test isolation") + folds = [str(fold["id"]) for fold in index["folds"]] + args.output_dir.mkdir(parents=True, exist_ok=args.refresh) + conditions = [] + for base_path in args.base_config: + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + mixture = str(base["experiment"]["condition"]) + for fold in folds: + config = copy.deepcopy(base) + condition = f"{mixture}_{fold}" + config["name"] = f"phase9_{condition.lower()}_s20260717" + config["experiment"]["condition"] = condition + config["experiment"]["h2o_selection_fold"] = fold + h2o = next( + source for source in config["data"]["sources"] + if str(source["dataset"]).upper() == "H2O" + ) + h2o["cache_manifest"] = str( + (args.multifold_index.parent / f"{fold}_train.jsonl").resolve() + ) + config["data"]["validation_sources"] = [{ + "dataset": "H2O", "source_id": f"H2O_{fold}_heldout", + "split_role": "train_fold_heldout", + "cache_manifest": str( + (args.multifold_index.parent / f"{fold}_heldout.jsonl").resolve() + ), + "K_input_dropout": 0.0, + }] + path = args.output_dir / f"{condition.lower()}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + errors = validate_phase9_unified_contract(config, path) + if errors: + raise ValueError(f"invalid generated fold config {path}: {'; '.join(errors)}") + max_steps = int(config["protocol"]["max_steps"]) + conditions.append({ + "condition": condition, + "mixture": mixture, + "h2o_selection_fold": fold, + "config": str(path.resolve()), "config_sha256": sha256(path), + "initialization_checkpoint": str(args.initialization_checkpoint.resolve()), + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "output_dir": str((args.run_root / condition.lower()).resolve()), + "log_dir": str((args.run_root.parent / "queues" / "folds" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"scale{max_steps}", "stop_after_step": max_steps}, + ], + }) + registry = { + "schema_version": "phase9_h2o_multifold_training_queue_v1", + "status": "frozen_before_fold_training", + "created_utc": datetime.now(timezone.utc).isoformat(), + "multifold_index": { + "path": str(args.multifold_index.resolve()), + "sha256": sha256(args.multifold_index), + }, + "data_readiness_state": str(args.data_readiness_state.resolve()), + "data_finalize_plan_sha256": args.data_finalize_plan_sha256, + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "allowed_physical_gpus": [0, 1, 2, 3], + "prohibited_physical_gpus": [4, 5], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "conditions": conditions, + "shards": { + str(shard): [ + condition["condition"] for index, condition in enumerate(conditions) + if index % 3 == shard + ] + for shard in range(3) + }, + } + args.registry.parent.mkdir(parents=True, exist_ok=True) + args.registry.write_text(json.dumps(registry, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "registry": str(args.registry.resolve()), "sha256": sha256(args.registry), + "conditions": len(conditions), "shards": registry["shards"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_h2o_multifold.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_h2o_multifold.py new file mode 100644 index 0000000000000000000000000000000000000000..89dc683c2a03af0cb1fa1de79ebed7e7d3cf24bb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_h2o_multifold.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Build deterministic H2O official-train-only subject and family folds.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.audit_phase9_source_coverage import quantiles + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def family(row: dict[str, Any]) -> str: + parts = str(row["physical_recording_id"]).split("/") + if len(parts) < 2 or parts[1][:1] not in {"h", "k", "o"}: + raise ValueError("H2O recording lacks h/k/o family") + return parts[1][:1] + + +def fold_definitions(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + subjects = sorted({str(row["subject_id"]) for row in rows}) + families = sorted({family(row) for row in rows}) + if subjects != ["subject1", "subject2", "subject3"] or families != ["h", "k", "o"]: + raise ValueError("unexpected H2O official-train subjects or families") + definitions = [ + {"id": f"loso_{subject}", "axis": "subject", "heldout_value": subject} + for subject in subjects + ] + definitions.extend( + {"id": f"lofamily_{value}", "axis": "family", "heldout_value": value} + for value in families + ) + return definitions + + +def split_rows( + rows: list[dict[str, Any]], definition: dict[str, Any], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + if definition["axis"] == "subject": + heldout = [row for row in rows if row["subject_id"] == definition["heldout_value"]] + else: + heldout = [row for row in rows if family(row) == definition["heldout_value"]] + heldout_groups = {row["physical_recording_id"] for row in heldout} + train = [row for row in rows if row["physical_recording_id"] not in heldout_groups] + train_groups = {row["physical_recording_id"] for row in train} + if not train or not heldout or train_groups & heldout_groups: + raise ValueError("H2O fold is empty or leaks a physical recording") + if len(train) + len(heldout) != len(rows): + raise ValueError("H2O fold does not partition the cache") + return train, heldout + + +def numeric_stats(rows: list[dict[str, Any]]) -> dict[str, Any]: + side_frames = [0, 0] + hand_sizes: list[float] = [] + depths: list[float] = [] + for row in rows: + with np.load(row["cache_path"], allow_pickle=False) as archive: + valid_frame = archive["frame_valid"].astype(bool) + translation_valid = archive["translation_valid"].astype(bool) + translation = archive["wrist_root_translation"] + joint_valid = archive["joint2d_valid"].astype(bool) + joints = archive["joint2d"] + image_hw = archive["image_hw"] + height, width = int(image_hw[0]), int(image_hw[1]) + for time_index in np.flatnonzero(valid_frame): + for side in range(2): + if not translation_valid[time_index, side]: + continue + side_frames[side] += 1 + depths.append(float(translation[time_index, side, 2])) + points = joints[time_index, side] + valid = joint_valid[time_index, side] & np.isfinite(points).all(axis=-1) + valid &= ( + (points[:, 0] >= 0) & (points[:, 0] < width) + & (points[:, 1] >= 0) & (points[:, 1] < height) + ) + if valid.any(): + extent = points[valid].max(axis=0) - points[valid].min(axis=0) + hand_sizes.append(float(extent.max())) + return { + "left_hand_frames": side_frames[0], "right_hand_frames": side_frames[1], + "wrist_depth_m": quantiles(depths), + "projected_hand_size_px": quantiles(hand_sizes), + "family_clips": dict(sorted(Counter(family(row) for row in rows).items())), + } + + +def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + temporary.replace(path) + + +def build( + cache_manifest: Path, cache_report: Path, output_dir: Path, +) -> dict[str, Any]: + report = json.loads(cache_report.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" or report.get("dataset") != "H2O" + or report.get("split_role") != "official_train" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest) + ): + raise ValueError("H2O cache report is not an isolated official-train cache") + rows = [ + json.loads(line) for line in cache_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if len(rows) != 7000 or {row.get("dataset_id") for row in rows} != {"H2O"}: + raise ValueError("H2O multifold requires the canonical 7,000-clip cache") + output_dir.mkdir(parents=True, exist_ok=False) + folds = [] + for definition in fold_definitions(rows): + train, heldout = split_rows(rows, definition) + train_path = output_dir / f"{definition['id']}_train.jsonl" + heldout_path = output_dir / f"{definition['id']}_heldout.jsonl" + write_jsonl(train_path, train) + write_jsonl(heldout_path, heldout) + folds.append({ + **definition, + "train": {"path": str(train_path.resolve()), "sha256": sha256(train_path), + "clips": len(train), "recordings": len({row['physical_recording_id'] for row in train}), + **numeric_stats(train)}, + "heldout": {"path": str(heldout_path.resolve()), "sha256": sha256(heldout_path), + "clips": len(heldout), "recordings": len({row['physical_recording_id'] for row in heldout}), + **numeric_stats(heldout)}, + }) + return { + "schema_version": "phase9_h2o_train_multifold_v1", + "status": "complete", + "source_cache_manifest": {"path": str(cache_manifest.resolve()), "sha256": sha256(cache_manifest)}, + "selection_metrics": ["fold_macro_absolute_mpjpe", "worst_fold_absolute_mpjpe"], + "folds": folds, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--cache-report", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists() or args.output_dir.exists(): + parser.error("multifold output already exists") + try: + result = build(args.cache_manifest, args.cache_report, args.output_dir) + except (OSError, ValueError, KeyError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_hot_scale_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_hot_scale_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..02461a594c28ac7532731ee53ffecf3708076071 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_hot_scale_configs.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Generate matched J40 HOT10K/HOT50K data-volume configurations.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +from pathlib import Path + +import yaml + +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--run-root", type=Path, required=True) + parser.add_argument("--data-readiness-state", type=Path, required=True) + parser.add_argument("--data-finalize-plan-sha256", required=True) + parser.add_argument("--initialization-checkpoint", type=Path, required=True) + parser.add_argument("--initialization-checkpoint-sha256", required=True) + parser.add_argument( + "--refresh", action="store_true", + help="Replace preregistered configs only when no training checkpoint exists.", + ) + args = parser.parse_args() + if (args.output_dir.exists() or args.registry.exists()) and not args.refresh: + parser.error("outputs must be new") + if args.refresh and args.run_root.exists() and any(args.run_root.rglob("*.pt")): + parser.error("cannot refresh HOT scale configs after a training checkpoint exists") + if sha256(args.initialization_checkpoint) != args.initialization_checkpoint_sha256: + parser.error("initialization checkpoint SHA256 differs") + base = yaml.safe_load(args.base_config.read_text(encoding="utf-8")) + if base["experiment"]["condition"] != "J40": + parser.error("base config must be J40") + args.output_dir.mkdir(parents=True, exist_ok=args.refresh) + hot_manifests = { + "J40_HOT10K": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl", + "J40_HOT50K": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_50000_v1/cache_manifest.jsonl", + } + conditions = [] + for condition, hot_manifest in hot_manifests.items(): + config = copy.deepcopy(base) + config["name"] = f"phase9_{condition.lower()}_s20260717" + config["experiment"]["condition"] = condition + hot = next(source for source in config["data"]["sources"] if source["dataset"] == "HOT3D") + hot["cache_manifest"] = hot_manifest + path = args.output_dir / f"{condition.lower()}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + errors = validate_phase9_unified_contract(config, path) + if errors: + raise ValueError(f"invalid generated HOT scale config: {'; '.join(errors)}") + conditions.append({ + "condition": condition, "config": str(path.resolve()), + "config_sha256": sha256(path), + "initialization_checkpoint": str(args.initialization_checkpoint.resolve()), + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "output_dir": str((args.run_root / condition.lower()).resolve()), + "log_dir": str((args.run_root.parent / "queues" / "hot_scale" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": "scale505k", "stop_after_step": 505000}, + ], + }) + registry = { + "schema_version": "phase9_hot_unique_scale_training_queue_v1", + "status": "frozen_before_hot_scale_training", + "data_readiness_state": str(args.data_readiness_state.resolve()), + "data_finalize_plan_sha256": args.data_finalize_plan_sha256, + "prerequisite_states": [ + {"condition": condition, "path": str( + (args.data_readiness_state.parent / f"{condition.lower()}_state.json").resolve() + )} for condition in ("J25", "J40", "J55") + ], + "allowed_physical_gpus": [0, 1, 2, 3], + "prohibited_physical_gpus": [4, 5], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "conditions": conditions, + } + args.registry.write_text(json.dumps(registry, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "registry": str(args.registry.resolve()), "sha256": sha256(args.registry), + "conditions": [condition["condition"] for condition in conditions], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_last2_evaluation_plan.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_last2_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe26e4c5fc7553a82ce13c2dda94c111b6b189b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_last2_evaluation_plan.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Freeze one ordered last-2 candidate's 25 matched evaluations.""" + +from __future__ import annotations + +import argparse +import fcntl +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_evaluation_plan import ( + completed_training_jobs, + evaluation_record, +) +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_control_plan(path: Path, expected_sha256: str) -> dict[str, Any]: + if not path.is_file() or sha256(path) != expected_sha256: + raise ValueError("last-2 control evaluation plan differs") + plan = read_json(path) + if ( + plan.get("status") != "frozen_ready" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or len(plan.get("evaluations", [])) != 25 + ): + raise ValueError("last-2 control evaluation contract differs") + return plan + + +def build_plan( + *, candidate: str, training_controller_plan_path: Path, + training_controller_state_path: Path, output_root: Path, + worker_state_root: Path, distributed_assignment_path: Path, + distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or controller_state.get("h2o_official_validation_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("last-2 training controller is not complete and bound") + registry = read_json(registry_path) + if registry.get("candidate") != candidate: + raise ValueError("last-2 training registry candidate differs") + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + if candidate == "5e7": + control_path = Path(registry["base_evaluation_plan"]["path"]) + control_sha256 = registry["base_evaluation_plan"]["sha256"] + elif candidate == "1e6": + five_decision_path = Path(registry["five_e7_decision"]["path"]) + if ( + not five_decision_path.is_file() + or registry["five_e7_decision"]["sha256"] != sha256(five_decision_path) + ): + raise ValueError("conditional 1e-6 decision binding differs") + five_decision = read_json(five_decision_path) + control_path = Path(five_decision["evaluation_plan"]["path"]) + control_sha256 = five_decision["evaluation_plan"]["sha256"] + else: + raise ValueError("unknown last-2 evaluation candidate") + control = validate_control_plan(control_path, control_sha256) + control_items = {item["id"]: item for item in control["evaluations"]} + evaluations = [] + for identifier, control_item in control_items.items(): + role = control_item["training_role"] + job = jobs[role] + evaluations.append(evaluation_record( + evaluation_id=identifier, + job=job, + manifest=Path(control_item["cache_manifest"]), + mode=control_item["input_mode"], + role=control_item["evaluation_role"], + output=output_root / Path(control_item["output_dir"]).relative_to( + control["output_root"] + ), + )) + ids = [item["id"] for item in evaluations] + if len(ids) != 25 or len(set(ids)) != 25 or set(ids) != set(control_items): + raise ValueError("last-2 evaluation IDs differ from control") + control_reports = { + identifier: { + "path": str((Path(item["output_dir"]) / "evaluation.json").resolve()), + "sha256": sha256(Path(item["output_dir"]) / "evaluation.json"), + "evaluation_role": item["evaluation_role"], + "input_mode": item["input_mode"], + } + for identifier, item in control_items.items() + } + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_last2_evaluation_plan_v1", + "status": "frozen_ready", "candidate": candidate, + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "control_evaluation_plan": { + "path": str(control_path.resolve()), "sha256": control_sha256, + }, + "control_reports": control_reports, + "winner": registry["winner"], + "resolution_hw": registry["resolution_hw"], + "shared_augmentation": registry["shared_augmentation"], + "backbone_learning_rate": registry["backbone_learning_rate"], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "gate": "macro_and_worst_domain_must_both_strictly_improve", + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--candidate", choices=("5e7", "1e6"), required=True) + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + candidate=args.candidate, + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing last-2 evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_last2_evaluation_plan_state_v1", + "status": "failed_resumable", "candidate": args.candidate, + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_last2_evaluation_plan_state_v1", + "status": "complete", "candidate": args.candidate, + "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_last2_training_registry.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_last2_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..2a04b4420ca861e79c5a34cb4af9de021c0a7306 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_last2_training_registry.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +"""Freeze ordered DINO Base last-2 training registries after Stage 8.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.build_phase9_resolution_training_registry import ( + FOLDS, + atomic_json, + sha256, + write_config, +) +from scripts.train_phase7_external import validate_phase9_unified_contract + + +CANDIDATES = { + "5e7": {"phase9_stage": "last2_5e7", "backbone_learning_rate": 5e-7}, + "1e6": {"phase9_stage": "last2_1e6", "backbone_learning_rate": 1e-6}, +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_stage8( + controller_plan_path: Path, controller_state_path: Path, +) -> tuple[dict[str, Any], dict[str, Any], Path]: + state = read_json(controller_state_path) + decision_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(controller_plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not decision_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(decision_path) + ): + raise ValueError("Stage 8 decision controller is not complete and bound") + decision = read_json(decision_path) + evaluation_plan_path = Path(state.get("evaluation_plan", "")) + if ( + decision.get("status") != "complete" + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + or not evaluation_plan_path.is_file() + or state.get("evaluation_plan_sha256") != sha256(evaluation_plan_path) + or decision.get("evaluation_plan", {}).get("sha256") + != sha256(evaluation_plan_path) + ): + raise ValueError("Stage 8 decision/evaluation binding differs") + return decision, read_json(evaluation_plan_path), evaluation_plan_path + + +def selected_base( + stage8_decision: dict[str, Any], stage8_plan: dict[str, Any], + stage8_plan_path: Path, +) -> tuple[dict[str, Any], Path, str, bool]: + if stage8_decision["shared_augmentation_accepted"]: + base_plan = stage8_plan + base_plan_path = stage8_plan_path + mechanism = "shared_augmentation" + shared_augmentation = True + else: + preceding = stage8_decision["stage9_preceding_mechanism_gate"] + if ( + preceding.get("source_mechanism") != "resolution" + or preceding.get("stage9_last2_admitted") is not True + or stage8_plan.get("control", {}).get("kind") + != "resolution_896x512_candidate" + ): + raise ValueError("no selected preceding mechanism admits Stage 9") + base_plan_path = Path(stage8_plan["control"]["evaluation_plan"]["path"]) + if ( + not base_plan_path.is_file() + or stage8_plan["control"]["evaluation_plan"]["sha256"] + != sha256(base_plan_path) + ): + raise ValueError("selected resolution control plan differs") + base_plan = read_json(base_plan_path) + mechanism = "resolution" + shared_augmentation = False + if set(base_plan["training_jobs"]) != {"full", *FOLDS}: + raise ValueError("selected last-2 base training roles differ") + return base_plan, base_plan_path, mechanism, shared_augmentation + + +def derive_last2_config( + base: dict[str, Any], *, condition: str, candidate: str, + resolution_hw: list[int], shared_augmentation: bool, + stage8_decision_sha256: str, +) -> dict[str, Any]: + spec = CANDIDATES[candidate] + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = spec["phase9_stage"] + experiment["last2_resolution_hw"] = list(resolution_hw) + experiment["last2_shared_augmentation"] = bool(shared_augmentation) + experiment["stage8_decision_sha256"] = stage8_decision_sha256 + model = config["model"] + if model.get("encoder") != "dinov3": + raise ValueError("last-2 base does not use DINOv3") + if model.get("dinov3_model", "dinov3_vitb16") != "dinov3_vitb16": + raise ValueError("last-2 base is not DINO Base") + model["dinov3_trainable_last_blocks"] = 2 + config["protocol"]["backbone_learning_rate"] = spec[ + "backbone_learning_rate" + ] + return config + + +def validate_matched_last2( + base: dict[str, Any], derived: dict[str, Any], candidate: str, +) -> None: + for key in ("seed", "loss", "assets", "precision"): + if derived[key] != base[key]: + raise ValueError(f"last-2 config changes matched {key}") + base_model = deepcopy(base["model"]) + derived_model = deepcopy(derived["model"]) + base_model.pop("dinov3_trainable_last_blocks", None) + if derived_model.pop("dinov3_trainable_last_blocks", None) != 2: + raise ValueError("last-2 config does not train exactly two blocks") + if base_model != derived_model: + raise ValueError("last-2 config changes non-admitted model parameters") + base_protocol = deepcopy(base["protocol"]) + derived_protocol = deepcopy(derived["protocol"]) + base_protocol.pop("backbone_learning_rate", None) + actual_lr = derived_protocol.pop("backbone_learning_rate", None) + if actual_lr != CANDIDATES[candidate]["backbone_learning_rate"]: + raise ValueError("last-2 backbone learning rate differs") + if base_protocol != derived_protocol: + raise ValueError("last-2 config changes optimizer/scheduler horizon") + if derived["data"] != base["data"]: + raise ValueError("last-2 config changes data, mixture or augmentation") + + +def validate_conditional_1e6(path: Path | None) -> dict[str, Any]: + if path is None or not path.is_file(): + raise ValueError("1e-6 requires a frozen 5e-7 decision report") + report = read_json(path) + if ( + report.get("status") != "complete" + or report.get("candidate") != "5e7" + or report.get("gate", {}).get("macro_strictly_improved") is not True + or report.get("gate", {}).get("worst_domain_strictly_improved") is not True + or report.get("gate", {}).get("accepted") is not True + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError("5e-7 did not pass strict macro and worst-domain gates") + evaluation_plan = Path(report.get("evaluation_plan", {}).get("path", "")) + if ( + not evaluation_plan.is_file() + or report["evaluation_plan"].get("sha256") != sha256(evaluation_plan) + ): + raise ValueError("5e-7 decision evaluation plan differs") + return report + + +def build_registry( + *, candidate: str, stage8_controller_plan_path: Path, + stage8_controller_state_path: Path, last2_plan_path: Path, + output_root: Path, five_e7_decision_path: Path | None, +) -> dict[str, Any]: + if candidate not in CANDIDATES: + raise ValueError("unknown last-2 candidate") + stage8_decision, stage8_plan, stage8_plan_path = validate_stage8( + stage8_controller_plan_path, stage8_controller_state_path, + ) + decision_path = stage8_decision_path(stage8_controller_state_path) + preceding = stage8_decision["stage9_preceding_mechanism_gate"] + if preceding.get("stage9_last2_admitted") is not True: + raise ValueError("Stage 9 is not admitted by the preceding mechanism") + five_e7 = ( + validate_conditional_1e6(five_e7_decision_path) + if candidate == "1e6" else None + ) + base_plan, base_plan_path, mechanism, shared_augmentation = selected_base( + stage8_decision, stage8_plan, stage8_plan_path, + ) + resolution_hw = list(stage8_decision["resolution_hw"]) + if base_plan["resolution_hw"] != resolution_hw: + raise ValueError("last-2 base resolution differs from Stage 8 decision") + base_registry_path = Path(base_plan["training_registry"]["path"]) + if ( + not base_registry_path.is_file() + or base_plan["training_registry"]["sha256"] != sha256(base_registry_path) + ): + raise ValueError("last-2 base registry differs") + base_registry = read_json(base_registry_path) + last2_plan = read_json(last2_plan_path) + expected = last2_plan[ + "candidate_5e7" if candidate == "5e7" else "conditional_candidate_1e6" + ] + if ( + last2_plan.get("official_test_used") is not False + or expected.get("dinov3_trainable_last_blocks") != 2 + or float(expected.get("backbone_learning_rate")) + != CANDIDATES[candidate]["backbone_learning_rate"] + or last2_plan.get("dino_large") != "not_admitted" + ): + raise ValueError("frozen last-2 plan differs") + + target_step = int(base_registry["target_step"]) + label = candidate + config_root = output_root / label / "phase9" / "configs" + conditions = [] + for role in ("full", *FOLDS): + job = base_plan["training_jobs"][role] + config_path = Path(job["config"]) + if not config_path.is_file() or job["config_sha256"] != sha256(config_path): + raise ValueError(f"last-2 base config differs: {role}") + base = yaml.safe_load(config_path.read_text(encoding="utf-8")) + prefix = "S9L5" if candidate == "5e7" else "S9L10" + condition = f"{prefix}_{stage8_decision['winner'].split(':', 1)[0]}_{role}" + derived = derive_last2_config( + base, condition=condition, candidate=candidate, + resolution_hw=resolution_hw, + shared_augmentation=shared_augmentation, + stage8_decision_sha256=sha256(decision_path), + ) + validate_matched_last2(base, derived, candidate) + derived_path = config_root / f"{condition.lower()}.yaml" + errors = validate_phase9_unified_contract(derived, derived_path) + if errors: + raise ValueError("; ".join(errors)) + write_config(derived_path, derived) + run_dir = output_root / label / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"last-2 run exists before freeze: {run_dir}") + conditions.append({ + "condition": condition, "role": role, + "config": str(derived_path.resolve()), + "config_sha256": sha256(derived_path), + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / label / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": base_registry[ + "matched_source_exposure_batches" + ], + "expected_source_exposure_frames": base_registry[ + "matched_source_exposure_frames" + ], + }) + return { + "schema_version": "phase9_last2_training_registry_v1", + "status": "frozen_ready", "created_utc": stage8_decision["created_utc"], + "candidate": candidate, + "backbone_learning_rate": CANDIDATES[candidate]["backbone_learning_rate"], + "winner": stage8_decision["winner"], + "resolution_hw": resolution_hw, + "shared_augmentation": shared_augmentation, + "selected_preceding_mechanism": mechanism, + "stage8_decision": { + "path": str(decision_path.resolve()), + "sha256": sha256(decision_path), + }, + "base_evaluation_plan": { + "path": str(base_plan_path.resolve()), "sha256": sha256(base_plan_path), + }, + "base_training_registry": { + "path": str(base_registry_path.resolve()), "sha256": sha256(base_registry_path), + }, + "five_e7_decision": ( + {"path": str(five_e7_decision_path.resolve()), + "sha256": sha256(five_e7_decision_path)} + if five_e7 is not None else None + ), + "last2_plan": { + "path": str(last2_plan_path.resolve()), "sha256": sha256(last2_plan_path), + }, + "target_step": target_step, + "matched_source_exposure_batches": base_registry[ + "matched_source_exposure_batches" + ], + "matched_source_exposure_frames": base_registry[ + "matched_source_exposure_frames" + ], + "data_readiness_state": base_registry["data_readiness_state"], + "data_readiness_state_sha256": base_registry["data_readiness_state_sha256"], + "data_finalize_plan_sha256": base_registry["data_finalize_plan_sha256"], + "data_artifacts": base_registry["data_artifacts"], + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def stage8_decision_path(controller_state_path: Path) -> Path: + state = read_json(controller_state_path) + return Path(state["decision_report"]["path"]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--candidate", choices=tuple(CANDIDATES), required=True) + parser.add_argument("--stage8-controller-plan", type=Path, required=True) + parser.add_argument("--stage8-controller-state", type=Path, required=True) + parser.add_argument("--last2-plan", type=Path, required=True) + parser.add_argument("--five-e7-decision", type=Path) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + registry = build_registry( + candidate=args.candidate, + stage8_controller_plan_path=args.stage8_controller_plan, + stage8_controller_state_path=args.stage8_controller_state, + last2_plan_path=args.last2_plan, + output_root=args.output_root, + five_e7_decision_path=args.five_e7_decision, + ) + if args.output_registry.exists(): + if read_json(args.output_registry) != registry: + raise ValueError("existing last-2 training registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_last2_registry_state_v1", + "status": "failed_resumable", "candidate": args.candidate, + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_last2_registry_state_v1", + "status": "complete", "candidate": args.candidate, + "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_resolution_evaluation_plan.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_resolution_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..6817a02586ce001cae349a38ad3b8510e49cff7f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_resolution_evaluation_plan.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Freeze Stage 7 evaluations from completed matched-resolution training.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +EXTERNAL_MODES = { + "HOT3D": ("rgb_k", "rgb_only"), + "HOI4D": ("rgb_d_k", "rgb_k", "rgb_only"), + "ARCTIC": ("rgb_k", "rgb_only"), +} +EXTERNAL_CACHE_IDS = { + "HOT3D": "hot3d_heldout", + "HOI4D": "hoi4d_heldout", + "ARCTIC": "arctic_heldout", +} +H2O_MODES = ("rgb_d_k", "rgb_k", "rgb_only") + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def completed_training_jobs( + registry_path: Path, registry: dict[str, Any], state_root: Path, +) -> dict[str, dict[str, Any]]: + registry_hash = sha256(registry_path) + result = {} + for job in registry["conditions"]: + condition = job["condition"] + state_path = state_root / f"{condition.lower()}.json" + if not state_path.is_file(): + raise ValueError(f"resolution training state is missing: {condition}") + state = read_json(state_path) + marker = state.get("last_completed", {}) + checkpoint = Path(marker.get("checkpoint", "")) + if ( + state.get("status") != "complete" + or state.get("queue_sha256") != registry_hash + or state.get("official_test_used") is not False + or marker.get("completed_step") != registry["target_step"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + ): + raise ValueError(f"resolution training endpoint differs: {condition}") + result[job["role"]] = { + **job, + "state": str(state_path.resolve()), + "state_sha256": sha256(state_path), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": marker["checkpoint_sha256"], + "gpu_hours": state["gpu_hours_consumed"], + } + if set(result) != { + "full", "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + }: + raise ValueError("resolution training roles differ") + return result + + +def evaluation_record( + *, evaluation_id: str, job: dict[str, Any], manifest: Path, + mode: str, role: str, output: Path, +) -> dict[str, Any]: + config = Path(job["config"]) + if not config.is_file() or sha256(config) != job["config_sha256"]: + raise ValueError(f"resolution evaluation config differs: {evaluation_id}") + if not manifest.is_file(): + raise ValueError(f"resolution evaluation manifest missing: {evaluation_id}") + return { + "id": evaluation_id, + "training_role": job["role"], + "config": str(config.resolve()), + "config_sha256": job["config_sha256"], + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": mode, + "evaluation_role": role, + "output_dir": str(output.resolve()), + } + + +def build_plan( + *, training_controller_plan_path: Path, training_controller_state_path: Path, + cache_plan_path: Path, output_root: Path, worker_state_root: Path, + distributed_assignment_path: Path, distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("resolution training controller is not complete and bound") + registry = read_json(registry_path) + if ( + registry.get("status") != "frozen_ready" + or registry.get("official_test_used") is not False + or registry.get("h2o_official_validation_used_for_selection") is not False + or registry.get("gate", {}).get("worst_domain_relative_regression_limit") + != controller_plan["worst_domain_relative_regression_limit"] + ): + raise ValueError("resolution training registry contract differs") + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + + cache_plan = read_json(cache_plan_path) + caches = {item["id"]: item for item in cache_plan["caches"]} + evaluations = [] + full = jobs["full"] + for dataset, modes in EXTERNAL_MODES.items(): + cache = caches[EXTERNAL_CACHE_IDS[dataset]] + manifest = Path(cache["manifest"]) + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=full, manifest=manifest, + mode=mode, role="phase9_external_heldout", + output=output_root / "full" / dataset.lower() / mode, + )) + for fold, job in jobs.items(): + if fold == "full": + continue + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + validation = config["data"].get("validation_sources", []) + if len(validation) != 1 or validation[0].get("dataset") != "H2O": + raise ValueError(f"resolution fold heldout differs: {fold}") + manifest = Path(validation[0]["cache_manifest"]) + for mode in H2O_MODES: + identifier = f"{fold}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=job, manifest=manifest, + mode=mode, role="phase9_h2o_fold_heldout", + output=output_root / "h2o" / fold / mode, + )) + ids = [item["id"] for item in evaluations] + outputs = [item["output_dir"] for item in evaluations] + if len(evaluations) != 25 or len(set(ids)) != 25 or len(set(outputs)) != 25: + raise ValueError("resolution evaluation IDs/outputs are not unique and complete") + + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_resolution_evaluation_plan_v1", + "status": "frozen_ready", + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "cache_execution_plan": { + "path": str(cache_plan_path.resolve()), "sha256": sha256(cache_plan_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "winner": registry["winner"], + "winner_checkpoint": registry["winner_checkpoint"], + "winner_config": registry["winner_config"], + "control_evidence": registry["control_evidence"], + "gate": registry["gate"], + "resolution_hw": [512, 896], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--cache-plan", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + cache_plan_path=args.cache_plan, output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing resolution evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_resolution_evaluation_plan_state_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_resolution_evaluation_plan_state_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_resolution_training_registry.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_resolution_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..3d10ab153ad63a19c9638d018c484bcd86b3254b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_resolution_training_registry.py @@ -0,0 +1,453 @@ +#!/usr/bin/env python3 +"""Freeze matched 896 training jobs from the selected 640 checkpoint.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +import re +from typing import Any + +import torch +import yaml + + +FOLDS = ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", +) +RESOLUTION_HW = [512, 896] +WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT = 0.01 +SOURCE_MANIFESTS = { + "H2O": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/h2o_train7000/cache_manifest.jsonl" + ), + "HOT3D": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/hot3d_train100000/cache_manifest.jsonl" + ), + "HOI4D": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/hoi4d_train37304_left_root/cache_manifest.jsonl" + ), + "ARCTIC": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/arctic_train21339_left_root/cache_manifest.jsonl" + ), +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_text(path: Path, value: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(value, encoding="utf-8") + temporary.replace(path) + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + atomic_text(path, json.dumps(value, indent=2) + "\n") + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def checkpoint_metadata( + path: Path, expected_sha256: str, expected_config_sha256: str, +) -> dict[str, Any]: + if not path.is_file() or sha256(path) != expected_sha256: + raise ValueError("selected 640 checkpoint hash differs") + payload = torch.load(path, map_location="cpu", weights_only=False) + extra = payload.get("extra", {}) + step = int(payload.get("step", -1)) + filename = re.search(r"step_(\d+)", path.name) + if ( + step <= 2000 + or filename is None + or int(filename.group(1)) != step + or extra.get("config_sha256") != expected_config_sha256 + or extra.get("official_test_used") is not False + or not extra.get("source_exposure_batches") + or not extra.get("external_initialization_checkpoint") + ): + raise ValueError("selected 640 checkpoint metadata differs") + return { + "step": step, + "source_exposure_batches": extra["source_exposure_batches"], + "source_exposure_frames": extra.get("source_exposure_frames", {}), + "completed_source_exposure_milestones": extra.get( + "completed_source_exposure_milestones", [] + ), + "initialization_checkpoint": extra["external_initialization_checkpoint"], + } + + +def derive_config( + base: dict[str, Any], *, condition: str, target_step: int, + h2o_train_manifest: str, h2o_heldout_manifest: str | None, + winner: str, winner_checkpoint_sha256: str, +) -> dict[str, Any]: + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = "resolution_896x512" + experiment["resolution_control_winner"] = winner + experiment["resolution_control_checkpoint_sha256"] = winner_checkpoint_sha256 + data = config["data"] + data["resolution_hw"] = list(RESOLUTION_HW) + for source in data["sources"]: + dataset = str(source["dataset"]).upper() + source["cache_manifest"] = ( + h2o_train_manifest if dataset == "H2O" else SOURCE_MANIFESTS[dataset] + ) + if h2o_heldout_manifest is None: + data.pop("validation_sources", None) + else: + validation = data.get("validation_sources", []) + if len(validation) != 1 or str(validation[0].get("dataset", "")).upper() != "H2O": + raise ValueError("fold base config lacks exactly one H2O heldout") + validation[0]["cache_manifest"] = h2o_heldout_manifest + return config + + +def validate_matched_config( + base: dict[str, Any], derived: dict[str, Any], target_step: int, +) -> None: + if ( + derived["seed"] != base["seed"] + or derived["model"] != base["model"] + or derived["loss"] != base["loss"] + or derived["assets"] != base["assets"] + or derived["precision"] != base["precision"] + or derived["data"]["T"] != base["data"]["T"] + or derived["data"]["batch_size"] != base["data"]["batch_size"] + or derived["data"].get("photometric_augmentation") + != base["data"].get("photometric_augmentation") + ): + raise ValueError("resolution config changes a matched model/data invariant") + base_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() if key != "cache_manifest" + } + for item in base["data"]["sources"] + } + derived_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() if key != "cache_manifest" + } + for item in derived["data"]["sources"] + } + if base_sources != derived_sources: + raise ValueError("resolution config changes source mixture or source settings") + if base["protocol"] != derived["protocol"]: + raise ValueError("resolution config changes optimizer/scheduler protocol") + + +def verify_readiness( + selection: dict[str, Any], readiness_path: Path, expected_plan_sha256: str, +) -> dict[str, Any]: + readiness = read_json(readiness_path) + audit_path = Path(readiness.get("audit", {}).get("path", "")) + if ( + readiness.get("status") != "complete" + or readiness.get("plan_sha256") != expected_plan_sha256 + or readiness.get("official_test_used") is not False + or readiness.get("h2o_official_validation_used") is not False + or readiness.get("winner") != selection.get("winner") + or readiness.get("winner_checkpoint") != selection.get("winner_checkpoint") + or readiness.get("winner_config") != selection.get("winner_config") + or not audit_path.is_file() + or readiness.get("audit", {}).get("sha256") != sha256(audit_path) + ): + raise ValueError("resolution cache readiness differs from selected winner") + audit = read_json(audit_path) + if ( + audit.get("status") != "complete" + or audit.get("plan_sha256") != expected_plan_sha256 + or audit.get("resolution_hw") != RESOLUTION_HW + or audit.get("official_test_used") is not False + or audit.get("h2o_official_validation_used") is not False + or not audit.get("multifold", {}).get("physical_recording_isolation") + or not audit.get("multifold", {}).get("deterministic_rebuild_hashes_match") + ): + raise ValueError("resolution cache audit differs") + return readiness + + +def write_config(path: Path, config: dict[str, Any]) -> None: + text = yaml.safe_dump(config, sort_keys=False, width=1000) + if path.exists(): + if path.read_text(encoding="utf-8") != text: + raise ValueError(f"existing resolution config differs: {path}") + return + atomic_text(path, text) + + +def build_registry( + *, selection_path: Path, readiness_path: Path, cache_plan_path: Path, + unified_queue_path: Path, fold_queue_path: Path, output_root: Path, +) -> dict[str, Any]: + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("unified selection is not complete and isolated") + cache_plan_sha256 = sha256(cache_plan_path) + readiness = verify_readiness(selection, readiness_path, cache_plan_sha256) + + winner = str(selection["winner"]) + mixture = winner.split(":", 1)[0] + if mixture not in {"J25", "J40", "J55"}: + raise ValueError("selected winner mixture is unknown") + winner_row = next( + (row for row in selection["candidates"] if row["id"] == winner), None + ) + if ( + winner_row is None + or winner_row.get("checkpoint") != selection["winner_checkpoint"] + or winner_row.get("config") != selection["winner_config"] + ): + raise ValueError("selected winner row is missing") + + unified_queue = read_json(unified_queue_path) + fold_queue = read_json(fold_queue_path) + full_job = next( + (item for item in unified_queue["conditions"] if item["condition"] == mixture), + None, + ) + if full_job is None: + raise ValueError("selected mixture is missing from the full-data queue") + selected_config = selection["winner_config"] + if ( + Path(selected_config["path"]).resolve() != Path(full_job["config"]).resolve() + or selected_config["sha256"] != full_job["config_sha256"] + or sha256(full_job["config"]) != full_job["config_sha256"] + ): + raise ValueError("selected config differs from the frozen full-data queue") + metadata = checkpoint_metadata( + Path(selection["winner_checkpoint"]["path"]), + selection["winner_checkpoint"]["sha256"], + selected_config["sha256"], + ) + initialization = metadata["initialization_checkpoint"] + initialization_path = Path(full_job["initialization_checkpoint"]) + if ( + Path(initialization.get("path", "")).resolve() + != initialization_path.resolve() + or initialization.get("sha256") != full_job["initialization_checkpoint_sha256"] + or not initialization_path.is_file() + or sha256(initialization_path) != full_job["initialization_checkpoint_sha256"] + ): + raise ValueError("selected checkpoint initialization differs") + + multifold = read_json( + output_root / "manifests" / "h2o_multifold_index.json" + ) + if ( + multifold.get("status") != "complete" + or multifold.get("official_test_used") is not False + or multifold.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution multifold index is not complete and isolated") + folds = {item["id"]: item for item in multifold["folds"]} + if set(folds) != set(FOLDS): + raise ValueError("resolution multifold IDs differ") + + config_root = output_root / "phase9" / "configs" + conditions = [] + base_full = yaml.safe_load(Path(full_job["config"]).read_text(encoding="utf-8")) + job_specs: list[tuple[str, dict[str, Any], str, str | None]] = [ + ("full", base_full, SOURCE_MANIFESTS["H2O"], None) + ] + fold_jobs = {item["condition"]: item for item in fold_queue["conditions"]} + for fold in FOLDS: + condition_id = f"{mixture}_{fold}" + if condition_id not in fold_jobs: + raise ValueError(f"selected mixture fold config is missing: {fold}") + base = yaml.safe_load( + Path(fold_jobs[condition_id]["config"]).read_text(encoding="utf-8") + ) + job_specs.append(( + fold, base, folds[fold]["train"]["path"], folds[fold]["heldout"]["path"] + )) + + target_step = int(metadata["step"]) + for role, base, h2o_train, h2o_heldout in job_specs: + condition = f"S7R_{mixture}_{role}" + config = derive_config( + base, condition=condition, target_step=target_step, + h2o_train_manifest=h2o_train, h2o_heldout_manifest=h2o_heldout, + winner=winner, + winner_checkpoint_sha256=selection["winner_checkpoint"]["sha256"], + ) + validate_matched_config(base, config, target_step) + config_path = config_root / f"{condition.lower()}.yaml" + write_config(config_path, config) + run_dir = output_root / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"resolution run output exists before registry freeze: {run_dir}") + conditions.append({ + "condition": condition, + "role": role, + "config": str(config_path.resolve()), + "config_sha256": sha256(config_path), + "initialization_checkpoint": full_job["initialization_checkpoint"], + "initialization_checkpoint_sha256": full_job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": metadata["source_exposure_batches"], + "expected_source_exposure_frames": metadata["source_exposure_frames"], + }) + + manifests = {} + for dataset, path in SOURCE_MANIFESTS.items(): + manifests[dataset] = {"path": path, "sha256": sha256(path)} + cache_plan = read_json(cache_plan_path) + artifact_paths = { + Path(item["manifest"]).resolve() for item in cache_plan["caches"] + } | { + Path(item["manifest"]).resolve() for item in cache_plan["sidecars"] + } | { + Path(cache_plan["multifold"]["index"]).resolve(), + } + for fold in folds.values(): + artifact_paths.add(Path(fold["train"]["path"]).resolve()) + artifact_paths.add(Path(fold["heldout"]["path"]).resolve()) + data_artifacts = [ + {"path": str(path), "sha256": sha256(path)} + for path in sorted(artifact_paths) + ] + registry = { + "schema_version": "phase9_resolution_training_registry_v1", + "status": "frozen_ready", + "created_utc": readiness["completed_utc"], + "winner": winner, + "winner_checkpoint": selection["winner_checkpoint"], + "winner_config": selection["winner_config"], + "control_evidence": winner_row, + "target_step": target_step, + "matched_source_exposure_batches": metadata["source_exposure_batches"], + "matched_source_exposure_frames": metadata["source_exposure_frames"], + "completed_source_exposure_milestones": metadata[ + "completed_source_exposure_milestones" + ], + "resolution_hw": RESOLUTION_HW, + "data_readiness_state": str(readiness_path.resolve()), + "data_readiness_state_sha256": sha256(readiness_path), + "data_finalize_plan_sha256": cache_plan_sha256, + "data_artifacts": data_artifacts, + "source_manifests": manifests, + "selection_report": { + "path": str(selection_path.resolve()), "sha256": sha256(selection_path), + }, + "cache_execution_plan": { + "path": str(cache_plan_path.resolve()), "sha256": cache_plan_sha256, + }, + "gate": { + "macro_absolute_mm_must_strictly_improve": True, + "worst_domain_relative_regression_limit": ( + WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT + ), + }, + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + return registry + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-report", type=Path, required=True) + parser.add_argument("--readiness-state", type=Path, required=True) + parser.add_argument("--cache-plan", type=Path, required=True) + parser.add_argument("--unified-queue", type=Path, required=True) + parser.add_argument("--fold-queue", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.state.is_file(): + state = read_json(args.state) + if state.get("status") == "complete": + if ( + args.output_registry.is_file() + and state.get("registry_sha256") == sha256(args.output_registry) + ): + print(json.dumps(state, indent=2)) + return + parser.error("completed resolution registry state differs") + try: + registry = build_registry( + selection_path=args.selection_report, + readiness_path=args.readiness_state, + cache_plan_path=args.cache_plan, + unified_queue_path=args.unified_queue, + fold_queue_path=args.fold_queue, + output_root=args.output_root, + ) + if args.output_registry.exists(): + existing = read_json(args.output_registry) + if existing != registry: + raise ValueError("existing resolution training registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_resolution_training_registry_state_v1", + "status": "failed_resumable", + "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_resolution_training_registry_state_v1", + "status": "complete", + "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "winner": registry["winner"], + "winner_checkpoint": registry["winner_checkpoint"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_selection_binding_recovery_plan.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_selection_binding_recovery_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..429d2680d06f834a198213ceaf1c0bf978888527 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_selection_binding_recovery_plan.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Freeze canonical re-evaluations for Phase 9 selection path mismatches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def canonical_config(condition: str) -> Path: + return Path( + "/home/jiasen/foundation_hand/artifacts/phase9/registry/fold_configs" + ) / f"{condition.lower()}.yaml" + + +def build_plan( + *, assignment_path: Path, audit_path: Path, selection_plan_path: Path, + failure_backup_root: Path, +) -> dict[str, Any]: + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + audit = json.loads(audit_path.read_text(encoding="utf-8")) + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + assignment_hash = sha256(assignment_path) + if ( + assignment.get("status") + != "frozen_before_distributed_recovery_or_stage7_work" + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + or audit.get("status") != "complete_path_only_recovery_required" + or audit.get("distributed_assignment", {}).get("sha256") + != assignment_hash + or audit.get("selection_plan", {}).get("sha256") + != sha256(selection_plan_path) + or selection_plan.get("official_test_used") is not False + ): + raise ValueError("selection recovery source contract differs") + assigned = { + item["id"]: item + for item in assignment["phase9_selection_recovery"]["evaluations"] + } + if len(assigned) != 11 or set(assigned) != set(audit["mismatch_ids"]): + raise ValueError("selection recovery assignment IDs differ") + records_by_id = {item["id"]: item for item in audit["records"]} + evaluations = [] + for identifier in sorted(assigned): + source = records_by_id[identifier] + owner_record = assigned[identifier] + if source.get("binding_status") != "path_mismatch_content_identical": + raise ValueError(f"recovery is not path-only: {identifier}") + config = canonical_config(source["condition"]) + if ( + not config.is_file() + or sha256(config) != source["config"]["declared_sha256"] + ): + raise ValueError(f"canonical config differs: {identifier}") + checkpoint = Path(source["checkpoint"]["path"]) + checkpoint_hash = source["checkpoint"]["declared_sha256"] + manifest = Path(source["cache_manifest"]["expected_path"]) + manifest_hash = source["cache_manifest"]["expected_sha256"] + if ( + not checkpoint.is_file() or sha256(checkpoint) != checkpoint_hash + or not manifest.is_file() or sha256(manifest) != manifest_hash + ): + raise ValueError(f"canonical recovery input differs: {identifier}") + owner = owner_record["owner"] + root = Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + determinism = source["determinism"] + evaluations.append({ + "id": identifier, + "owner": owner, + "physical_gpu_id": owner_record["physical_gpu_id"], + "condition": source["condition"], + "checkpoint_id": source["checkpoint_id"], + "input_mode": "rgb_d_k", + "evaluation_role": "phase9_h2o_fold_heldout", + "config": str(config.resolve()), + "config_sha256": sha256(config), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_hash, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": manifest_hash, + "output_dir": str(( + root / "evaluations" / source["condition"] + / source["checkpoint_id"] / "rgb_d_k" + ).resolve()), + "prior_report": source["report"], + "expected_sample_counts": source["sample_counts"], + "expected_determinism": { + "metrics_sha256": determinism["metrics_sha256"], + "grouped_bootstrap_ci_sha256": determinism[ + "grouped_bootstrap_ci_sha256" + ], + "raw_predictions_sha256": determinism[ + "raw_predictions" + ]["declared_sha256"], + "per_hand_rows_sha256": determinism[ + "per_hand_rows" + ]["declared_sha256"], + "take_metrics_sha256": determinism[ + "take_metrics" + ]["declared_sha256"], + }, + }) + workers = [] + for owner in ("taku3", "server_new"): + allowlist = assignment["machines"][owner]["physical_gpu_allowlist"] + for gpu in allowlist: + ids = [ + item["id"] for item in evaluations + if item["owner"] == owner and item["physical_gpu_id"] == gpu + ] + if not ids: + continue + root = Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + workers.append({ + "id": f"{owner}_gpu{gpu}", "owner": owner, + "physical_gpu_id": gpu, + "state": str((root / "states" / f"gpu{gpu}.json").resolve()), + "log": str((root / "logs" / f"gpu{gpu}.log").resolve()), + "evaluation_ids": ids, + }) + assigned_ids = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(evaluations) != 11 + or len(assigned_ids) != 11 + or len(set(assigned_ids)) != 11 + or set(assigned_ids) != set(assigned) + ): + raise ValueError("selection recovery workers are not disjoint and complete") + backup_files = {} + for name in ( + "unified_selection_state.json", "unified_selection.log", + "unified_selection_watcher.log", + ): + path = failure_backup_root / name + if not path.is_file(): + raise ValueError(f"selection failure backup missing: {path}") + backup_files[name] = sha256(path) + repository = assignment_path.resolve().parents[3] + code_paths = [ + repository / "scripts/evaluate_phase7_external.py", + repository / "scripts/summarize_phase9_unified_selection.py", + repository / "scripts/run_phase9_selection_binding_recovery.py", + repository / "scripts/finalize_phase9_selection_binding_recovery.py", + repository / "scripts/merge_phase9_selection_binding_recovery.py", + ] + code_bindings = [] + for path in code_paths: + if not path.is_file(): + raise ValueError(f"selection recovery code missing: {path}") + code_bindings.append({"path": str(path), "sha256": sha256(path)}) + return { + "schema_version": "phase9_selection_binding_recovery_plan_v2", + "status": "frozen_before_recovery_evaluation", + "reason": "migration_path_binding_differs_with_identical_manifest_sha256", + "scientific_failure": False, + "resource_scheduling_amendment_only": True, + "distributed_assignment": { + "path": str(assignment_path.resolve()), "sha256": assignment_hash, + }, + "mismatch_manifest": { + "path": str(audit_path.resolve()), "sha256": sha256(audit_path), + }, + "selection_plan": { + "path": str(selection_plan_path.resolve()), + "sha256": sha256(selection_plan_path), + }, + "failure_backup": { + "root": str(failure_backup_root.resolve()), + "files": backup_files, + }, + "code_bindings": code_bindings, + "release_manifests": { + owner: str((Path( + assignment["phase9_selection_recovery"][ + f"{owner}_recovery_root" + ] + ) / "release_manifest.json").resolve()) + for owner in ("taku3", "server_new") + }, + "canonical_fold_milestone_root": selection_plan["fold_milestone_root"], + "dry_run_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts/selection_binding_recovery_v2/dry_run", + "canonical_merge_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/selection_binding_recovery_v2/merge_state.json", + "canonical_merge_backup_root": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/recovery_backups/selection_binding_v2_20260731", + "selection_state": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/unified_selection_state.json", + "selection_log": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/unified_selection.log", + "evaluations": evaluations, + "workers": workers, + "bootstrap_resamples": 2000, + "requirements": [ + "evaluate only assigned mismatches in new recovery roots", + "bind canonical config manifest checkpoint and expected SHA256", + "validate sample counts role isolation metrics and artifact determinism", + "run temporary JSON and CSV summarizer before canonical merge", + "atomically replace each mismatched canonical output under one merge lock", + "preserve failed selection and replaced output evidence" + ], + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--audit", type=Path, required=True) + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--failure-backup-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("recovery plan output must be new") + result = build_plan( + assignment_path=args.assignment, audit_path=args.audit, + selection_plan_path=args.selection_plan, + failure_backup_root=args.failure_backup_root, + ) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_shared_augmentation_evaluation_plan.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_shared_augmentation_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..e381262202ce3e6f36fd1a7cbc71286aa7b745ca --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_shared_augmentation_evaluation_plan.py @@ -0,0 +1,282 @@ +#!/usr/bin/env python3 +"""Freeze Stage 8 evaluations after shared-augmentation training completes.""" + +from __future__ import annotations + +import argparse +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.build_phase9_resolution_evaluation_plan import ( + EXTERNAL_MODES, + H2O_MODES, + completed_training_jobs, + evaluation_record, +) +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +HELDOUT_640 = { + "HOT3D": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "HOI4D": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "ARCTIC": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/arctic_val2048_fullgroups_v2/cache_manifest.jsonl", +} +HELDOUT_896_IDS = { + "HOT3D": "hot3d_heldout", "HOI4D": "hoi4d_heldout", + "ARCTIC": "arctic_heldout", +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def control_reports_896(registry: dict[str, Any]) -> dict[str, dict[str, str]]: + path = Path(registry["control"]["evaluation_plan"]["path"]) + if ( + not path.is_file() + or registry["control"]["evaluation_plan"]["sha256"] != sha256(path) + ): + raise ValueError("Stage 8 896 control evaluation plan differs") + plan = read_json(path) + reports = {} + for item in plan["evaluations"]: + reports[item["id"]] = { + "path": str((Path(item["output_dir"]) / "evaluation.json").resolve()), + "evaluation_role": item["evaluation_role"], + "input_mode": item["input_mode"], + } + return reports + + +def control_reports_640(registry: dict[str, Any]) -> dict[str, dict[str, str]]: + control = registry["control"]["control_evidence"] + mixture = control["mixture"] + external_id = control["external_checkpoint_id"] + fold_id = control["fold_checkpoint_id"] + external_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/external_milestones" + ) + final_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold" + ) + milestone_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold_milestones" + ) + reports = {} + for dataset, modes in EXTERNAL_MODES.items(): + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + reports[identifier] = { + "path": str(( + external_root / mixture / external_id + / f"{dataset.lower()}_{mode}" / "evaluation.json" + ).resolve()), + "evaluation_role": "phase9_external_heldout", + "input_mode": mode, + } + for fold in FOLDS: + condition = f"{mixture}_{fold}" + for mode in H2O_MODES: + path = ( + final_root / condition / mode / "evaluation.json" + if fold_id == "final" + else milestone_root / condition / fold_id / mode / "evaluation.json" + ) + reports[f"{fold}_{mode}"] = { + "path": str(path.resolve()), + "evaluation_role": "phase9_h2o_fold_heldout", + "input_mode": mode, + } + return reports + + +def validate_control_reports(reports: dict[str, dict[str, str]]) -> None: + if len(reports) != 25: + raise ValueError("Stage 8 control report count differs") + for identifier, item in reports.items(): + path = Path(item["path"]) + if not path.is_file(): + raise ValueError(f"Stage 8 control report missing: {identifier}") + report = read_json(path) + if ( + report.get("status") != f"evaluated_{item['evaluation_role']}" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"Stage 8 control report differs: {identifier}") + item["sha256"] = sha256(path) + + +def build_plan( + *, training_controller_plan_path: Path, training_controller_state_path: Path, + resolution_cache_plan_path: Path, output_root: Path, worker_state_root: Path, + distributed_assignment_path: Path, distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or controller_state.get("h2o_official_validation_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("shared augmentation training is not complete and bound") + registry = read_json(registry_path) + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + resolution_hw = registry["resolution_hw"] + if resolution_hw == [512, 896]: + cache_plan = read_json(resolution_cache_plan_path) + cache_by_id = {item["id"]: item for item in cache_plan["caches"]} + heldouts = { + dataset: Path(cache_by_id[identifier]["manifest"]) + for dataset, identifier in HELDOUT_896_IDS.items() + } + control_reports = control_reports_896(registry) + elif resolution_hw == [368, 640]: + heldouts = {dataset: Path(path) for dataset, path in HELDOUT_640.items()} + control_reports = control_reports_640(registry) + else: + raise ValueError("shared augmentation resolution differs") + validate_control_reports(control_reports) + + evaluations = [] + full = jobs["full"] + for dataset, modes in EXTERNAL_MODES.items(): + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=full, manifest=heldouts[dataset], + mode=mode, role="phase9_external_heldout", + output=output_root / "full" / dataset.lower() / mode, + )) + for fold in FOLDS: + job = jobs[fold] + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + validation = config["data"].get("validation_sources", []) + if len(validation) != 1 or validation[0].get("dataset") != "H2O": + raise ValueError(f"augmentation fold heldout differs: {fold}") + manifest = Path(validation[0]["cache_manifest"]) + for mode in H2O_MODES: + evaluations.append(evaluation_record( + evaluation_id=f"{fold}_{mode}", job=job, manifest=manifest, + mode=mode, role="phase9_h2o_fold_heldout", + output=output_root / "h2o" / fold / mode, + )) + ids = [item["id"] for item in evaluations] + if len(ids) != 25 or len(set(ids)) != 25: + raise ValueError("shared augmentation evaluation IDs differ") + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_shared_augmentation_evaluation_plan_v1", + "status": "frozen_ready", + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "winner": registry["winner"], + "resolution_hw": resolution_hw, + "resolution_decision": registry["resolution_decision"], + "control": registry["control"], + "control_reports": control_reports, + "gate": registry["gate"], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--resolution-cache-plan", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + resolution_cache_plan_path=args.resolution_cache_plan, + output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing augmentation evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_eval_plan_state_v1", + "status": "failed_resumable", "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_shared_augmentation_eval_plan_state_v1", + "status": "complete", "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_shared_augmentation_training_registry.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_shared_augmentation_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..5867d7bdf6a01d537e221a7d5d1c01f6c0b2d69f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_phase9_shared_augmentation_training_registry.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Freeze Stage 8 shared-augmentation jobs after the resolution decision.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS +from scripts.build_phase9_resolution_training_registry import ( + FOLDS, + atomic_json, + checkpoint_metadata, + sha256, + write_config, +) +from scripts.train_phase7_external import validate_phase9_unified_contract + + +GEOMETRY_AUGMENTATION = { + "enabled": True, + "probability": 0.8, + "scale_min": 0.9, + "scale_max": 1.1, + "translation_fraction": 0.05, +} +DEPTH_CORRUPTION_DATASETS = {"H2O", "HOI4D"} +WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT = 0.01 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def derive_augmentation_config( + base: dict[str, Any], *, condition: str, resolution_hw: list[int], + resolution_decision_sha256: str, +) -> dict[str, Any]: + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = ( + "shared_augmentation_896x512" + if resolution_hw == [512, 896] + else "shared_augmentation_640" + ) + experiment["resolution_decision_sha256"] = resolution_decision_sha256 + data = config["data"] + if data["resolution_hw"] != resolution_hw: + raise ValueError("augmentation base config resolution differs") + data["geometry_augmentation"] = deepcopy(GEOMETRY_AUGMENTATION) + for source in data["sources"]: + dataset = str(source["dataset"]).upper() + source["depth_corruption_probability"] = ( + 0.3 if dataset in DEPTH_CORRUPTION_DATASETS else 0.0 + ) + return config + + +def validate_matched_augmentation( + base: dict[str, Any], derived: dict[str, Any], resolution_hw: list[int], +) -> None: + if ( + derived["seed"] != base["seed"] + or derived["model"] != base["model"] + or derived["loss"] != base["loss"] + or derived["assets"] != base["assets"] + or derived["precision"] != base["precision"] + or derived["protocol"] != base["protocol"] + or derived["data"]["resolution_hw"] != resolution_hw + or derived["data"]["T"] != base["data"]["T"] + or derived["data"]["batch_size"] != base["data"]["batch_size"] + or derived["data"].get("photometric_augmentation") + != base["data"].get("photometric_augmentation") + or derived["data"].get("validation_sources") + != base["data"].get("validation_sources") + ): + raise ValueError("augmentation config changes a matched invariant") + base_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() + if key != "depth_corruption_probability" + } + for item in base["data"]["sources"] + } + derived_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() + if key != "depth_corruption_probability" + } + for item in derived["data"]["sources"] + } + if base_sources != derived_sources: + raise ValueError("augmentation config changes source mixture/manifests") + if derived["data"]["geometry_augmentation"] != GEOMETRY_AUGMENTATION: + raise ValueError("augmentation affine parameters differ") + + +def data_artifacts_from_configs(configs: list[dict[str, Any]]) -> list[dict[str, str]]: + paths = set() + for config in configs: + for source in config["data"]["sources"]: + paths.add(Path(source["cache_manifest"]).resolve()) + for source in config["data"].get("validation_sources", []): + paths.add(Path(source["cache_manifest"]).resolve()) + return [ + {"path": str(path), "sha256": sha256(path)} for path in sorted(paths) + ] + + +def base_jobs_896( + resolution_state: dict[str, Any], decision: dict[str, Any], +) -> tuple[dict[str, dict[str, Any]], dict[str, Any]]: + evaluation_plan_path = Path(resolution_state["evaluation_plan"]) + if ( + not evaluation_plan_path.is_file() + or resolution_state.get("evaluation_plan_sha256") + != sha256(evaluation_plan_path) + ): + raise ValueError("accepted 896 evaluation plan differs") + evaluation_plan = read_json(evaluation_plan_path) + registry_path = Path(evaluation_plan["training_registry"]["path"]) + if evaluation_plan["training_registry"]["sha256"] != sha256(registry_path): + raise ValueError("accepted 896 training registry differs") + registry = read_json(registry_path) + jobs = { + role: { + "role": role, + "config": job["config"], + "config_sha256": job["config_sha256"], + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + } + for role, job in registry_job_map(registry).items() + } + context = { + "target_step": registry["target_step"], + "source_exposure_batches": registry["matched_source_exposure_batches"], + "source_exposure_frames": registry["matched_source_exposure_frames"], + "data_readiness_state": registry["data_readiness_state"], + "data_readiness_state_sha256": registry["data_readiness_state_sha256"], + "data_finalize_plan_sha256": registry["data_finalize_plan_sha256"], + "data_artifacts": registry["data_artifacts"], + "control": { + "kind": "resolution_896x512_candidate", + "evaluation_plan": { + "path": str(evaluation_plan_path.resolve()), + "sha256": sha256(evaluation_plan_path), + }, + "decision_report": decision, + }, + } + return jobs, context + + +def registry_job_map(registry: dict[str, Any]) -> dict[str, dict[str, Any]]: + result = {item["role"]: item for item in registry["conditions"]} + if set(result) != {"full", *FOLDS}: + raise ValueError("seven matched control roles differ") + return result + + +def base_jobs_640( + decision: dict[str, Any], unified_queue_path: Path, fold_queue_path: Path, + selection_path: Path, +) -> tuple[dict[str, dict[str, Any]], dict[str, Any]]: + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("winner") != decision.get("winner") + or selection.get("winner_checkpoint") != decision.get("control_checkpoint") + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("retained 640 selection evidence differs") + mixture = selection["winner"].split(":", 1)[0] + unified = read_json(unified_queue_path) + folds = read_json(fold_queue_path) + full = next(item for item in unified["conditions"] if item["condition"] == mixture) + if ( + Path(selection["winner_config"]["path"]).resolve() + != Path(full["config"]).resolve() + or selection["winner_config"]["sha256"] != full["config_sha256"] + ): + raise ValueError("retained 640 winner config differs from its mixture") + metadata = checkpoint_metadata( + Path(selection["winner_checkpoint"]["path"]), + selection["winner_checkpoint"]["sha256"], + selection["winner_config"]["sha256"], + ) + initialization = metadata["initialization_checkpoint"] + if ( + Path(initialization.get("path", "")).resolve() + != Path(full["initialization_checkpoint"]).resolve() + or initialization.get("sha256") != full["initialization_checkpoint_sha256"] + ): + raise ValueError("retained 640 initialization differs") + jobs = { + "full": { + "role": "full", "config": full["config"], + "config_sha256": full["config_sha256"], + "initialization_checkpoint": full["initialization_checkpoint"], + "initialization_checkpoint_sha256": full[ + "initialization_checkpoint_sha256" + ], + } + } + fold_jobs = {item["condition"]: item for item in folds["conditions"]} + for fold in FOLDS: + item = fold_jobs[f"{mixture}_{fold}"] + jobs[fold] = { + "role": fold, "config": item["config"], + "config_sha256": item["config_sha256"], + "initialization_checkpoint": full["initialization_checkpoint"], + "initialization_checkpoint_sha256": full[ + "initialization_checkpoint_sha256" + ], + } + readiness = Path(unified["data_readiness_state"]) + if not readiness.is_file(): + raise ValueError("retained 640 data readiness is missing") + configs = [ + yaml.safe_load(Path(item["config"]).read_text(encoding="utf-8")) + for item in jobs.values() + ] + context = { + "target_step": metadata["step"], + "source_exposure_batches": metadata["source_exposure_batches"], + "source_exposure_frames": metadata["source_exposure_frames"], + "data_readiness_state": str(readiness.resolve()), + "data_readiness_state_sha256": sha256(readiness), + "data_finalize_plan_sha256": unified["data_finalize_plan_sha256"], + "data_artifacts": data_artifacts_from_configs(configs), + "control": { + "kind": "frozen_640_winner", + "selection_report": { + "path": str(selection_path.resolve()), "sha256": sha256(selection_path), + }, + "control_evidence": next( + item for item in selection["candidates"] + if item["id"] == selection["winner"] + ), + "decision_report": decision, + }, + } + return jobs, context + + +def build_registry( + *, resolution_controller_plan_path: Path, + resolution_controller_state_path: Path, augmentation_plan_path: Path, + unified_queue_path: Path, fold_queue_path: Path, selection_path: Path, + output_root: Path, +) -> dict[str, Any]: + resolution_plan = read_json(resolution_controller_plan_path) + resolution_state = read_json(resolution_controller_state_path) + decision_path = Path(resolution_state.get("decision_report", {}).get("path", "")) + if ( + resolution_state.get("status") != "complete" + or resolution_state.get("plan_sha256") != sha256(resolution_controller_plan_path) + or resolution_state.get("official_test_used") is not False + or resolution_state.get("h2o_official_validation_used") is not False + or Path(resolution_plan["decision_report"]).resolve() != decision_path.resolve() + or not decision_path.is_file() + or resolution_state.get("decision_report", {}).get("sha256") + != sha256(decision_path) + ): + raise ValueError("resolution decision controller is not complete and bound") + decision = read_json(decision_path) + if ( + decision.get("status") != "complete" + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution decision report is not complete and isolated") + resolution_hw = decision["accepted_resolution_hw"] + if resolution_hw not in ([368, 640], [512, 896]): + raise ValueError("resolution decision value differs") + augmentation_plan = read_json(augmentation_plan_path) + if ( + augmentation_plan.get("official_test_used") is not False + or { + key: value for key, value in augmentation_plan.get("candidate", {}).get( + "geometry_augmentation", {} + ).items() if key in GEOMETRY_AUGMENTATION + } != GEOMETRY_AUGMENTATION + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "applicable_sources" + ) != ["H2O", "HOI4D"] + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "probability" + ) != 0.3 + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "conditions" + ) != list(DEPTH_CORRUPTIONS) + ): + raise ValueError("shared augmentation frozen plan differs") + + if resolution_hw == [512, 896]: + base_jobs, context = base_jobs_896(resolution_state, decision) + else: + base_jobs, context = base_jobs_640( + decision, unified_queue_path, fold_queue_path, selection_path, + ) + mixture = decision["winner"].split(":", 1)[0] + resolution_label = "896x512" if resolution_hw == [512, 896] else "640x368" + config_root = output_root / resolution_label / "phase9" / "configs" + conditions = [] + base_configs = [] + for role in ("full", *FOLDS): + job = base_jobs[role] + path = Path(job["config"]) + if not path.is_file() or sha256(path) != job["config_sha256"]: + raise ValueError(f"augmentation base config differs: {role}") + base = yaml.safe_load(path.read_text(encoding="utf-8")) + condition = f"S8A_{mixture}_{role}" + derived = derive_augmentation_config( + base, condition=condition, resolution_hw=resolution_hw, + resolution_decision_sha256=sha256(decision_path), + ) + validate_matched_augmentation(base, derived, resolution_hw) + config_path = config_root / f"{condition.lower()}.yaml" + errors = validate_phase9_unified_contract(derived, config_path) + if errors: + raise ValueError("; ".join(errors)) + write_config(config_path, derived) + run_dir = output_root / resolution_label / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"augmentation run exists before freeze: {run_dir}") + target_step = int(context["target_step"]) + conditions.append({ + "condition": condition, "role": role, + "config": str(config_path.resolve()), "config_sha256": sha256(config_path), + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / resolution_label / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": context[ + "source_exposure_batches" + ], + "expected_source_exposure_frames": context["source_exposure_frames"], + }) + base_configs.append(base) + data_artifacts = data_artifacts_from_configs(base_configs) + context_artifacts = { + item["path"]: item["sha256"] for item in context["data_artifacts"] + } + if any( + context_artifacts.get(item["path"]) != item["sha256"] + for item in data_artifacts + ): + raise ValueError("augmentation data artifacts differ from control") + # Preserve the stronger control set, including heldout and fold-index hashes. + data_artifacts = context["data_artifacts"] + return { + "schema_version": "phase9_shared_augmentation_training_registry_v1", + "status": "frozen_ready", + "created_utc": decision["created_utc"], + "winner": decision["winner"], + "resolution_hw": resolution_hw, + "resolution_decision": { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + }, + "shared_augmentation_plan": { + "path": str(augmentation_plan_path.resolve()), + "sha256": sha256(augmentation_plan_path), + }, + "control": context["control"], + "target_step": context["target_step"], + "matched_source_exposure_batches": context["source_exposure_batches"], + "matched_source_exposure_frames": context["source_exposure_frames"], + "data_readiness_state": context["data_readiness_state"], + "data_readiness_state_sha256": context["data_readiness_state_sha256"], + "data_finalize_plan_sha256": context["data_finalize_plan_sha256"], + "data_artifacts": data_artifacts, + "gate": { + "macro_absolute_mm_must_strictly_improve": True, + "worst_domain_relative_regression_limit": ( + WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT + ), + "stage9_preceding_mechanism_requires_worst_strict_improvement": True, + }, + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--resolution-controller-plan", type=Path, required=True) + parser.add_argument("--resolution-controller-state", type=Path, required=True) + parser.add_argument("--augmentation-plan", type=Path, required=True) + parser.add_argument("--unified-queue", type=Path, required=True) + parser.add_argument("--fold-queue", type=Path, required=True) + parser.add_argument("--selection-report", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + registry = build_registry( + resolution_controller_plan_path=args.resolution_controller_plan, + resolution_controller_state_path=args.resolution_controller_state, + augmentation_plan_path=args.augmentation_plan, + unified_queue_path=args.unified_queue, + fold_queue_path=args.fold_queue, + selection_path=args.selection_report, + output_root=args.output_root, + ) + if args.output_registry.exists(): + if read_json(args.output_registry) != registry: + raise ValueError("existing augmentation registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_registry_state_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_shared_augmentation_registry_state_v1", + "status": "complete", "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "resolution_hw": registry["resolution_hw"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_sota_ground_truth.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_sota_ground_truth.py new file mode 100644 index 0000000000000000000000000000000000000000..d859aa4924bd3147b0a16d71a3f7164a13e2f25e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/build_sota_ground_truth.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Build the immutable H2O GT bundle shared by all SOTA baseline evaluations.""" + +from __future__ import annotations + +import argparse +import hashlib +from pathlib import Path + +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import ( + load_float_record, + load_joint_record, + load_mano_record, +) +from foundation_hand.evaluation.sota import GroundTruthBundle, load_frame_index +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models.mano import ManoCameraLayer + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=256) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + keys, takes, frame_ids = load_frame_index(args.manifest) + count = len(keys) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + pose = np.zeros((count, 2, 48), dtype=np.float32) + shape = np.zeros((count, 2, 10), dtype=np.float32) + valid = np.zeros((count, 2), dtype=bool) + intrinsics = np.zeros((count, 3, 3), dtype=np.float32) + intrinsics_cache: dict[str, np.ndarray] = {} + + for index, (take_name, frame_id) in enumerate(zip(takes, frame_ids, strict=True)): + take = args.root / str(take_name) + stem = f"{int(frame_id):06d}" + joint_record = load_joint_record(take / "hand_pose" / f"{stem}.txt") + mano_record = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + if not np.array_equal(joint_record.annotation_valid, mano_record.annotation_valid): + raise ValueError(f"Joint/MANO validity mismatch: {keys[index]}") + valid[index] = joint_record.annotation_valid + joints[index] = joint_record.joints_camera_m + pose[index] = mano_record.pose_axis_angle + shape[index] = mano_record.shape + if str(take_name) not in intrinsics_cache: + values = load_float_record(take / "cam_intrinsics.txt") + intrinsics_cache[str(take_name)] = intrinsics_from_h2o(values)[0] + intrinsics[index] = intrinsics_cache[str(take_name)] + + joints[~valid] = np.nan + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + device = torch.device(args.device) + mano = ManoCameraLayer(args.mano_root).to(device).eval() + for start in range(0, count, args.batch_size): + end = min(start + args.batch_size, count) + pose_tensor = torch.from_numpy(pose[start:end]).to(device) + shape_tensor = torch.from_numpy(shape[start:end]).to(device) + wrist_tensor = torch.from_numpy(np.nan_to_num(joints[start:end, :, 0])).to(device) + with torch.no_grad(): + batch_vertices, _ = mano( + axis_angle_to_matrix(pose_tensor.reshape(end - start, 2, 16, 3)), + shape_tensor, + wrist_tensor, + ) + vertices[start:end] = batch_vertices.cpu().numpy() + vertices[~valid] = np.nan + + bundle = GroundTruthBundle( + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + annotation_valid=valid, + intrinsics=intrinsics, + metadata={ + "source": "H2O official validation cam4", + "official_test_used": False, + "manifest": str(args.manifest.resolve()), + "manifest_sha256": sha256(args.manifest), + "frames": count, + "runs": len(args.manifest.read_text(encoding="utf-8").splitlines()), + "takes": len(set(map(str, takes.tolist()))), + "joint_order": "H2O/OpenPose wrist-thumb-index-middle-ring-pinky", + "units": "meters", + }, + ) + bundle.save(args.output) + print(f"saved {count} frames to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase4_jitter_predictions.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase4_jitter_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..c638edc649e36a24ec91b04ad2594e22ffe09fcd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase4_jitter_predictions.py @@ -0,0 +1,399 @@ +#!/usr/bin/env python3 +"""Cache hash-bound raw official-validation predictions for jitter evaluation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +CACHE_VERSION = 1 +FPS = 30.0 +FRAME_ARRAYS = ( + "clip_index", + "frame_id", + "frame_valid", + "K", + "pred_rotation_matrices", + "pred_shape", + "pred_wrist_translation", + "pred_joints_camera", + "pred_vertices_camera", + "pred_direct_2d_px", + "target_rotation_matrices", + "target_shape", + "target_wrist_translation", + "target_joints_camera", + "target_vertices_camera", + "target_2d_px", + "joint_annotation_valid", + "joint_element_valid", + "mano_annotation_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def take_slug(take: str) -> str: + parts = Path(take).parts + if len(parts) != 4 or parts[-1] != "cam4": + raise ValueError(f"unexpected H2O take: {take}") + return "__".join(parts) + + +def manifest_frame_count(path: Path) -> int: + identities: set[tuple[str, int]] = set() + rows = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + record = json.loads(line) + take = str(record["take"]) + for frame_id in record["frame_ids"]: + identity = (take, int(frame_id)) + if identity in identities: + raise ValueError(f"duplicate manifest frame: {take}/{int(frame_id)}") + identities.add(identity) + rows += 1 + if rows == 0: + raise ValueError("prediction cache manifest is empty") + return rows + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def apply_input_condition( + batch: dict[str, Any], condition: str, +) -> dict[str, Any]: + if condition == "complete": + return batch + model_batch = dict(batch) + if condition == "missing_depth": + model_batch["depth_available"] = torch.zeros_like(batch["depth_available"]) + model_batch["depth_m"] = torch.zeros_like(batch["depth_m"]) + model_batch["depth_pixel_valid"] = torch.zeros_like(batch["depth_pixel_valid"]) + return model_batch + if condition == "missing_k": + model_batch["K_available"] = torch.zeros_like(batch["K_available"]) + identity = torch.eye(3, dtype=batch["K"].dtype, device=batch["K"].device) + model_batch["K"] = identity.expand_as(batch["K"]).clone() + return model_batch + raise ValueError(f"unsupported input condition: {condition}") + + +def target_geometry( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for jitter cache targets") + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, joints = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + return rotations, vertices, joints + + +def validate_cache_arrays( + arrays: dict[str, np.ndarray], + *, + take: str, + expected_frame_ids: list[int], + checkpoint_sha256: str, + config_sha256: str, + manifest_sha256: str, + input_condition: str = "complete", +) -> None: + missing = sorted(set(FRAME_ARRAYS) - arrays.keys()) + if missing: + raise ValueError(f"raw jitter cache is missing arrays: {missing}") + if int(arrays["cache_version"]) != CACHE_VERSION: + raise ValueError("raw jitter cache version mismatch") + scalar_expectations = { + "take": take, + "checkpoint_sha256": checkpoint_sha256, + "config_sha256": config_sha256, + "manifest_sha256": manifest_sha256, + } + for key, expected in scalar_expectations.items(): + if str(arrays[key]) != expected: + raise ValueError(f"raw jitter cache {key} mismatch") + if input_condition != "complete" and str(arrays.get("input_condition", "")) != input_condition: + raise ValueError("raw jitter cache input condition mismatch") + frame_ids = arrays["frame_id"].astype(np.int64).tolist() + if frame_ids != expected_frame_ids or len(frame_ids) != len(set(frame_ids)): + raise ValueError(f"raw jitter cache frame sequence mismatch for {take}") + for key in FRAME_ARRAYS: + if arrays[key].shape[0] != len(frame_ids): + raise ValueError(f"raw jitter cache time dimension mismatch: {key}") + if np.issubdtype(arrays[key].dtype, np.floating): + finite = np.isfinite(arrays[key]) + if key.startswith("target_"): + # Invalid annotations are intentionally retained as NaN. + continue + if not finite.all(): + raise ValueError(f"raw jitter cache prediction is non-finite: {key}") + + +def load_valid_cache( + path: Path, + **expected: object, +) -> dict[str, np.ndarray] | None: + if not path.is_file(): + return None + try: + with np.load(path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + validate_cache_arrays(arrays, **expected) + except (OSError, KeyError, ValueError): + return None + return arrays + + +def build_model( + config: dict[str, Any], checkpoint: Path, device: torch.device, +) -> tuple[BimanualReconstructionModel, int]: + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(checkpoint, model, optimizer=None, map_location=device) + return model, int(state["step"]) + + +def infer_take( + *, + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + input_condition: str, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + subset = Subset(dataset, clip_indices) + loader = DataLoader( + subset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + for global_clip_index, batch_cpu in zip(clip_indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + target_rotations, target_vertices, _ = target_geometry(batch, model) + model_batch = apply_input_condition(batch, input_condition) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(model_batch) + valid_times = int(batch["frame_valid"][0].sum()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor( + (width, height), device=device, + ) + values: dict[str, torch.Tensor] = { + "clip_index": torch.full( + (valid_times,), global_clip_index, device=device, dtype=torch.int64, + ), + "frame_id": batch["frame_id"][0, :valid_times], + "frame_valid": batch["frame_valid"][0, :valid_times], + "K": batch["K"][0, :valid_times], + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0, :valid_times], + "pred_shape": prediction["mano_shape"][0, :valid_times], + "pred_wrist_translation": prediction["wrist_root_translation"][0, :valid_times], + "pred_joints_camera": prediction["joints_camera"][0, :valid_times], + "pred_vertices_camera": prediction["vertices_camera"][0, :valid_times], + "pred_direct_2d_px": direct_2d[0, :valid_times], + "target_rotation_matrices": target_rotations[0, :valid_times], + "target_shape": batch["mano_shape"][0, :valid_times], + "target_wrist_translation": batch["wrist_root_translation"][0, :valid_times], + "target_joints_camera": batch["joint3d_camera"][0, :valid_times], + "target_vertices_camera": target_vertices[0, :valid_times], + "target_2d_px": batch["joint2d"][0, :valid_times], + "joint_annotation_valid": batch["joint_annotation_valid"][0, :valid_times], + "joint_element_valid": batch["joint_element_valid"][0, :valid_times], + "mano_annotation_valid": batch["mano_annotation_valid"][0, :valid_times], + } + for key, value in values.items(): + array = value.detach().float().cpu().numpy() if value.is_floating_point() else value.cpu().numpy() + chunks[key].append(array) + return {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), default=0) + parser.add_argument("--max-clips", type=int) + parser.add_argument( + "--input-condition", choices=("complete", "missing_depth", "missing_k"), + default="complete", + ) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("jitter cache is hard-gated to official validation") + if args.max_clips is not None and args.max_clips < 1: + parser.error("--max-clips must be positive") + if not torch.cuda.is_available(): + parser.error("CUDA is required") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + config_hash = sha256(args.config) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (int(config["data"]["T"]),), (int(config["data"]["stride"]),), + max_clips=args.max_clips, + oracle_crop_enabled=config["model"].get("oracle_crop_mode", "none") != "none", + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + expected_frames = { + take: [ + frame_id + for index in indices + for frame_id in dataset.clips[index].frame_ids + ] + for take, indices in indices_by_take.items() + } + if any(len(values) != len(set(values)) for values in expected_frames.values()): + raise ValueError("jitter cache requires non-overlapping inference clips") + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model: BimanualReconstructionModel | None = None + checkpoint_step: int | None = None + records = [] + for take_index, (take, clip_indices) in enumerate(indices_by_take.items(), start=1): + output = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "manifest_sha256": manifest_hash, + "input_condition": args.input_condition, + } + arrays = load_valid_cache(output, **expected) + status = "reused" + if arrays is None: + if output.exists(): + raise ValueError(f"existing jitter cache failed validation: {output}") + if model is None: + model, checkpoint_step = build_model(config, args.checkpoint, device) + arrays = infer_take( + dataset=dataset, clip_indices=clip_indices, model=model, + device=device, dtype=dtype, input_condition=args.input_condition, + ) + arrays.update({ + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + "take": np.asarray(take), + "fps": np.asarray(FPS, dtype=np.float32), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "manifest_sha256": np.asarray(manifest_hash), + "input_condition": np.asarray(args.input_condition), + }) + validate_cache_arrays(arrays, **expected) + save_npz_atomic(output, arrays) + status = "written" + records.append({ + "take": take, "clips": len(clip_indices), + "frames": len(expected_frames[take]), "path": str(output), + "sha256": sha256(output), "status": status, + }) + print( + f"[{take_index}/{len(indices_by_take)}] {take}: " + f"{records[-1]['frames']} frames ({status})", + flush=True, + ) + if checkpoint_step is None: + # Read the step only when every cache was reused. + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + checkpoint_step = int(state["step"]) + total_frames = sum(record["frames"] for record in records) + full_validation = args.max_clips is None + expected_full_frames = manifest_frame_count(args.manifest) + if full_validation and total_frames != expected_full_frames: + raise ValueError( + "official-validation cache does not cover every manifest frame exactly once" + ) + report = { + "status": "complete", + "official_test_used": False, + "split_role": "official_validation", + "scope": "full" if full_validation else "smoke", + "fps": FPS, + "temporal_length": int(config["data"]["T"]), + "clip_boundary_filter_reset_required": True, + "input_condition": args.input_condition, + "missing_rgb_status": "unsupported_no_rgb_availability_or_training_dropout", + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": checkpoint_step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, + stdout=subprocess.PIPE, check=False, + ).stdout.strip(), + "clips": len(dataset), "frames": total_frames, + "expected_manifest_frames": expected_full_frames, "takes": records, + } + (args.output_dir / "cache_manifest.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "clips": report["clips"], + "frames": report["frames"], "takes": len(records), + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase6_sequence_predictions.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase6_sequence_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..5914ff7c6988c0f4da8b47b226fbbf1b7c0337e7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase6_sequence_predictions.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Cache bounded-window Phase 6 sequence predictions in the frozen raw schema.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from scripts.cache_phase4_jitter_predictions import ( + CACHE_VERSION, + FPS, + build_model, + load_valid_cache, + manifest_frame_count, + move_to_device, + save_npz_atomic, + sha256, + take_slug, + target_geometry, + validate_cache_arrays, +) + + +def validate_sequence_config(config: dict, mode: str) -> None: + """Validate model causality; frame iteration itself always supplies T=1.""" + + attention_mode = config["model"].get("temporal_attention_mode", "bidirectional") + expected_attention = "causal" if mode == "causal" else "bidirectional" + if attention_mode != expected_attention: + raise ValueError("sequence mode differs from config temporal attention mode") + + +def offline_stride(window: int, mode: str) -> int | None: + return max(window // 2, 1) if mode == "offline" else None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--max-takes", type=int) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("sequence cache is hard-gated to official validation") + if args.window < 1: + parser.error("window must be positive") + if args.max_takes is not None and args.max_takes < 1: + parser.error("max-takes must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + try: + validate_sequence_config(config, args.mode) + except ValueError as error: + parser.error(str(error)) + + config_hash = sha256(args.config) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (1,), (1,), + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + if args.max_takes is not None: + indices_by_take = dict(list(indices_by_take.items())[: args.max_takes]) + expected_frames = { + take: [dataset.clips[index].frame_ids[0] for index in indices] + for take, indices in indices_by_take.items() + } + if any(len(ids) != len(set(ids)) for ids in expected_frames.values()): + raise ValueError("sequence cache input contains duplicate take/frame identities") + + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model = None + checkpoint_step = None + records = [] + maximum_gpu_window = 0 + maximum_cpu_buffer = 0 + for take_index, (take, indices) in enumerate(indices_by_take.items(), start=1): + output_path = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "manifest_sha256": manifest_hash, + "input_condition": "complete", + } + arrays = load_valid_cache(output_path, **expected) + status = "reused" + if arrays is None: + if output_path.exists(): + raise ValueError(f"existing sequence cache failed validation: {output_path}") + if model is None: + model, checkpoint_step = build_model(config, args.checkpoint, device) + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.mode, window_size=args.window, + offline_stride=offline_stride(args.window, args.mode), + ), + device=device, autocast_dtype=dtype, + ) + target_chunks: dict[str, list[np.ndarray]] = defaultdict(list) + loader = DataLoader( + Subset(dataset, indices), batch_size=1, shuffle=False, + num_workers=0, collate_fn=collate_h2o_clips, pin_memory=True, + ) + + def frames(): + for global_index, batch_cpu in zip(indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + rotations, vertices, _ = target_geometry(batch, model) + values = { + # One output file is one continuous take. Frame gaps and + # frame_valid, not the source dataset index, delimit segments. + "clip_index": np.asarray([0], dtype=np.int64), + "frame_id": batch_cpu["frame_id"][0].numpy(), + "frame_valid": batch_cpu["frame_valid"][0].numpy(), + "K": batch_cpu["K"][0].numpy(), + "target_rotation_matrices": rotations[0].float().cpu().numpy(), + "target_shape": batch_cpu["mano_shape"][0].numpy(), + "target_wrist_translation": batch_cpu["wrist_root_translation"][0].numpy(), + "target_joints_camera": batch_cpu["joint3d_camera"][0].numpy(), + "target_vertices_camera": vertices[0].float().cpu().numpy(), + "target_2d_px": batch_cpu["joint2d"][0].numpy(), + "joint_annotation_valid": batch_cpu["joint_annotation_valid"][0].numpy(), + "joint_element_valid": batch_cpu["joint_element_valid"][0].numpy(), + "mano_annotation_valid": batch_cpu["mano_annotation_valid"][0].numpy(), + } + for key, value in values.items(): + target_chunks[key].append(value) + yield batch_cpu + + prediction = runner.infer(frames()) + height, width = config["data"]["resolution_hw"] + predicted = { + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0].float().numpy(), + "pred_shape": prediction["mano_shape"][0].float().numpy(), + "pred_wrist_translation": prediction["wrist_root_translation"][0].float().numpy(), + "pred_joints_camera": prediction["joints_camera"][0].float().numpy(), + "pred_vertices_camera": prediction["vertices_camera"][0].float().numpy(), + "pred_direct_2d_px": ( + prediction["joint2d_norm"][0].float() + * torch.tensor((width, height)) + ).numpy(), + } + arrays = { + **{key: np.concatenate(values, axis=0) for key, values in target_chunks.items()}, + **predicted, + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + "take": np.asarray(take), + "fps": np.asarray(FPS, dtype=np.float32), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "manifest_sha256": np.asarray(manifest_hash), + "input_condition": np.asarray("complete"), + "sequence_mode": np.asarray(args.mode), + "sequence_window": np.asarray(args.window, dtype=np.int32), + } + validate_cache_arrays(arrays, **expected) + save_npz_atomic(output_path, arrays) + maximum_gpu_window = max(maximum_gpu_window, runner.maximum_resident_frames) + maximum_cpu_buffer = max(maximum_cpu_buffer, runner.maximum_input_buffer_frames) + status = "written" + records.append({ + "take": take, "clips": len(indices), "frames": len(expected_frames[take]), + "path": str(output_path), "sha256": sha256(output_path), "status": status, + }) + print(f"[{take_index}/{len(indices_by_take)}] {take} ({status})", flush=True) + + if checkpoint_step is None: + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + checkpoint_step = int(state["step"]) + total_frames = sum(record["frames"] for record in records) + expected_total = ( + manifest_frame_count(args.manifest) if args.max_takes is None + else sum(len(frame_ids) for frame_ids in expected_frames.values()) + ) + if total_frames != expected_total: + raise ValueError("sequence cache does not cover the frozen manifest exactly") + report = { + "status": "complete", + "experiment": "P6_S5_length_generalized_inference", + "official_test_used": False, + "official_validation_used_for_selection": False, + "split_role": "official_validation", + "scope": "full" if args.max_takes is None else "smoke", + "fps": FPS, + "temporal_length": 1, + "sequence_mode": args.mode, + "sequence_window": args.window, + "offline_stride": offline_stride(args.window, args.mode), + "stitching": "center" if args.mode == "offline" else None, + "maximum_gpu_window_frames": maximum_gpu_window, + "maximum_cpu_input_buffer_frames": maximum_cpu_buffer, + "input_condition": "complete", + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": checkpoint_step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + "clips": len(dataset), "frames": total_frames, + "expected_manifest_frames": expected_total, "takes": records, + } + (args.output_dir / "cache_manifest.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "mode": args.mode, "window": args.window, + "frames": total_frames, "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase7_h2o_train.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase7_h2o_train.py new file mode 100644 index 0000000000000000000000000000000000000000..14a83bba28b96456e9238ece26d398545cc921eb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase7_h2o_train.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Build a bounded canonical cache from H2O official train only.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import math +from pathlib import Path +import time + +import numpy as np + +from foundation_hand.data import H2OCam4Dataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from scripts.cache_phase7_hot3d import ( + validate_cached_resolution, + validated_target_hw, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_train_manifest_path(path: Path) -> None: + if path.name != "official_train.jsonl": + raise ValueError("H2O adaptation cache requires canonical official_train.jsonl") + + +def center_out(values: list[int]) -> list[int]: + values = sorted(values) + center = (len(values) - 1) // 2 + order = [center] + distance = 1 + while len(order) < len(values): + if center + distance < len(values): + order.append(center + distance) + if center - distance >= 0: + order.append(center - distance) + distance += 1 + return [values[index] for index in order] + + +def balanced_clip_indices( + clips: list, count: int, max_recordings: int, +) -> list[int]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, clip in enumerate(clips): + parts = Path(clip.take).parts + groups[(parts[0], "/".join(parts[:-1]))].append(index) + strata: dict[str, list[tuple[str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[0]].append(key) + selected_groups: list[tuple[str, str]] = [] + cursor = 0 + while len(selected_groups) < min(max_recordings, len(groups)): + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected_groups.append(strata[subject][cursor]) + progress = True + if len(selected_groups) == max_recordings: + break + if not progress: + break + cursor += 1 + ordered = {key: center_out(groups[key]) for key in selected_groups} + selected = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in selected_groups: + if cursor < len(ordered[key]): + selected.append(ordered[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def rgb_uint8(rgb: np.ndarray) -> np.ndarray: + image = np.transpose(rgb, (0, 2, 3, 1)) + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int, required=True) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument("--resume", action="store_true") + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + validate_train_manifest_path(args.source_manifest) + if min(args.clips, args.max_recordings) <= 0: + parser.error("clip and recording counts must be positive") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + dataset = H2OCam4Dataset( + args.root, args.source_manifest, target_hw=target_hw, + clip_lengths=(8,), strides=(1,), + ) + candidate_count = min( + len(dataset), args.clips + max(32, math.ceil(args.clips * 0.1)), + ) + selected = balanced_clip_indices(dataset.clips, candidate_count, args.max_recordings) + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced H2O train clips are available") + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", "vertices_camera", + } + cached: dict[int, dict] = {} + skipped: list[int] = [] + started = time.monotonic() + for position, source_index in enumerate(selected, 1): + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise RuntimeError(f"invalid existing cache: {output}") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + else: + sample = dataset[(source_index, 0)] + has_supervision = bool(sample["translation_valid"].any()) + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + clip = dataset.clips[source_index] + parts = Path(clip.take).parts + if has_supervision: + cached[source_index] = { + "dataset_id": "H2O", + "subject_id": parts[0], + "sequence_id": "/".join(parts[1:-1]), + "physical_recording_id": "/".join(parts[:-1]), + "camera_id": "cam4", "stream_id": "cam4-rgb", + "headset_id": "H2O-ego", "source_clip_index": source_index, + "source_group_key": f"H2O/{'/'.join(parts[:-1])}", + "resolution_hw": list(target_hw), + "cache_path": str(output.resolve()), "cache_sha256": sha256(output), + } + else: + skipped.append(source_index) + if position % 10 == 0 or position == len(selected): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": position, "requested": len(selected), + "cached": len(cached), "skipped_no_supervision": len(skipped), + "clips_per_second": position / elapsed, + }), flush=True) + ordered_valid = [index for index in selected if index in cached][:args.clips] + if len(ordered_valid) == args.clips: + break + manifest = args.output_dir / "cache_manifest.jsonl" + temporary_manifest = manifest.with_suffix(".tmp") + temporary_manifest.write_text( + "".join(json.dumps(cached[index], sort_keys=True) + "\n" for index in ordered_valid), + encoding="utf-8", + ) + temporary_manifest.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": "complete" if len(ordered_valid) == args.clips else "insufficient_valid_clips", + "dataset": "H2O", "split_role": "official_train", + "source_manifest": { + "path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest), + }, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "requested_clips": args.clips, "candidate_clips_processed": position, + "resolution_hw": list(target_hw), + "cached_clips": len(ordered_valid), "valid_candidate_files": len(cached), + "recordings": len({cached[index]["physical_recording_id"] for index in ordered_valid}), + "skipped_no_supervision": skipped, + "wall_seconds": elapsed, "clips_per_second": position / elapsed, + "bytes": sum(Path(cached[index]["cache_path"]).stat().st_size for index in ordered_valid), + "resume_invocation": bool(args.resume), + "h2o_official_validation_used": False, "official_test_used": False, + } + (args.output_dir / "cache_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase7_hot3d.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase7_hot3d.py new file mode 100644 index 0000000000000000000000000000000000000000..7f6273de04231e6edb06c4fbfdacf1fe2547e592 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase7_hot3d.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Build a bounded, source-hash-bound HOT3D clip cache.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +import time + +import numpy as np + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def validated_target_hw(values: tuple[int, int] | list[int]) -> tuple[int, int]: + """Validate the full-frame cache resolution used by every source writer.""" + + if len(values) != 2: + raise ValueError("target resolution must contain height and width") + height, width = (int(value) for value in values) + if min(height, width) <= 0: + raise ValueError("target resolution dimensions must be positive") + return height, width + + +def validate_cached_resolution( + archive: np.lib.npyio.NpzFile, target_hw: tuple[int, int], +) -> None: + if "image_hw" not in archive.files: + raise ValueError("cached payload lacks image_hw") + image_hw = tuple(int(value) for value in np.asarray(archive["image_hw"]).reshape(-1)) + if image_hw != target_hw: + raise ValueError( + f"cached payload resolution {image_hw} does not match requested {target_hw}" + ) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def sha256_json(value: object) -> str: + payload = json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + return hashlib.sha256(payload).hexdigest() + + +def decode_position_slice( + decode_order: list[int], position_range: tuple[int, int] | None, +) -> tuple[list[int], tuple[int, int] | None]: + if position_range is None: + return decode_order, None + start, stop = position_range + if start < 0 or stop <= start or stop > len(decode_order): + raise ValueError( + f"invalid prefill position range [{start}, {stop}) for {len(decode_order)} candidates" + ) + return decode_order[start:stop], (start, stop) + + +def balanced_recording_keys( + groups: dict[tuple[str, str, str], list[int]], max_recordings: int, +) -> list[tuple[str, str, str]]: + strata: dict[tuple[str, str], list[tuple[str, str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[:2]].append(key) + selected: list[tuple[str, str, str]] = [] + cursor = 0 + while len(selected) < min(max_recordings, len(groups)): + progress = False + for stratum in sorted(strata): + if cursor < len(strata[stratum]): + selected.append(strata[stratum][cursor]) + progress = True + if len(selected) == max_recordings: + break + if not progress: + break + cursor += 1 + return selected + + +def balanced_indices( + rows: list[dict], count: int, max_recordings: int | None = None, +) -> list[int]: + groups: dict[tuple[str, str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + groups[(row["headset"], row["participant_id"], row["recording_id"])].append(index) + keys = sorted(groups) + if max_recordings is not None: + if max_recordings <= 0: + raise ValueError("max_recordings must be positive") + keys = balanced_recording_keys(groups, max_recordings) + selected: list[int] = [] + cursor = 0 + while len(selected) < min(count, len(rows)): + progress = False + for key in keys: + values = groups[key] + if cursor < len(values): + selected.append(values[cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def cache_candidate_count(requested: int, available: int) -> int: + return min(available, requested + max(64, int(np.ceil(requested * 0.1)))) + + +def first_valid_indices( + selected: list[int], cached: dict[int, dict], requested: int, +) -> list[int]: + return [index for index in selected if index in cached][:requested] + + +def should_stop_decoding( + selected: list[int], cached: dict[int, dict], requested: int, + decode_all_candidates: bool, +) -> bool: + """Stop early only when full candidate decoding was not requested.""" + + return ( + not decode_all_candidates + and len(first_valid_indices(selected, cached, requested)) == requested + ) + + +def rgb_uint8(rgb: np.ndarray) -> np.ndarray: + image = np.transpose(rgb, (0, 2, 3, 1)) + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument( + "--decode-all-candidates", action="store_true", + help="Decode the complete balanced overdraw pool before freezing the valid prefix.", + ) + parser.add_argument( + "--prefill-position-range", type=int, nargs=2, metavar=("START", "STOP"), + help=( + "Decode a zero-based half-open slice of the frozen candidate order into " + "a staging cache; no deployable cache manifest is produced." + ), + ) + parser.add_argument("--resume", action="store_true") + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + if args.clips < 1: + parser.error("--clips must be positive") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing output clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + dataset = HOT3DClipDataset( + args.root, args.source_manifest, args.toolkit_root, args.mano_root, + K_input_dropout=0.0, provider_cache_size=2, target_hw=target_hw, + ) + candidate_count = cache_candidate_count(args.clips, len(dataset.rows)) + selected = balanced_indices(dataset.rows, candidate_count, args.max_recordings) + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced candidates are available") + # Decode in recording order to avoid reopening VRS files for every clip. + full_decode_order = sorted( + selected, + key=lambda index: ( + dataset.rows[index]["recording_id"], + dataset.rows[index]["stream_id"], + dataset.rows[index]["timestamps_ns"][0], + ), + ) + prefill_range = ( + tuple(args.prefill_position_range) + if args.prefill_position_range is not None else None + ) + try: + decode_order, prefill_range = decode_position_slice( + full_decode_order, prefill_range, + ) + except ValueError as error: + parser.error(str(error)) + if prefill_range is not None and not args.decode_all_candidates: + parser.error("--prefill-position-range requires --decode-all-candidates") + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", + } + cache_rows: dict[int, dict] = {} + skipped_no_supervision: list[int] = [] + started = time.monotonic() + for position, source_index in enumerate(decode_order, 1): + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + try: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise ValueError("required cache arrays missing") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + if { + "source_hand_annotation_present", "geometry_convention_compatible", + }.issubset(archive.files): + masked_geometry = int(np.count_nonzero( + archive["source_hand_annotation_present"] + & ~archive["geometry_convention_compatible"] + )) + else: + # The previous strict writer raised before saving any + # clip containing a regeneration mismatch. + masked_geometry = 0 + except Exception as error: + raise RuntimeError(f"existing resume cache is invalid: {output}: {error}") from error + else: + sample = dataset[(source_index, 0)] + has_supervision = bool(sample["translation_valid"].any()) + masked_geometry = int(( + sample["source_hand_annotation_present"] + & ~sample["geometry_convention_compatible"] + ).sum()) + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + if has_supervision: + row = dataset.rows[source_index] + cache_rows[source_index] = { + "dataset_id": "HOT3D", + "subject_id": row["participant_id"], + "sequence_id": row["recording_id"], + "physical_recording_id": row["recording_id"], + "camera_id": row["stream_id"], + "stream_id": row["stream_id"], + "headset_id": row["headset"], + "source_clip_index": source_index, + "source_group_key": row["group_key"], + "resolution_hw": list(target_hw), + "geometry_masked_hand_frames": masked_geometry, + "cache_path": str(output.resolve()), + "cache_sha256": sha256(output), + } + else: + skipped_no_supervision.append(source_index) + if position % 10 == 0 or position == len(decode_order): + elapsed = time.monotonic() - started + print(json.dumps({ + "decoded": position, "total": len(decode_order), + "cached": len(cache_rows), + "skipped_no_supervision": len(skipped_no_supervision), + "clips_per_second": position / elapsed, + "eta_seconds": (len(decode_order) - position) / (position / elapsed), + }), flush=True) + if prefill_range is None and should_stop_decoding( + selected, cache_rows, args.clips, args.decode_all_candidates, + ): + break + if prefill_range is None: + ordered_cached = first_valid_indices(selected, cache_rows, args.clips) + manifest = args.output_dir / "cache_manifest.jsonl" + status = "complete" if len(ordered_cached) == args.clips else "insufficient_valid_clips" + mode = "deployable_cache" + else: + ordered_cached = [index for index in decode_order if index in cache_rows] + manifest = args.output_dir / "prefill_manifest.jsonl" + status = ( + "complete" + if len(ordered_cached) + len(skipped_no_supervision) == len(decode_order) + else "incomplete_prefill" + ) + mode = "staged_prefill" + temporary_manifest = manifest.with_suffix(".tmp") + temporary_manifest.write_text( + "".join(json.dumps(cache_rows[index], sort_keys=True) + "\n" for index in ordered_cached), + encoding="utf-8", + ) + temporary_manifest.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": status, + "mode": mode, + "official_test_used": False, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "clips": len(ordered_cached), + "candidate_clips_processed": position, + "full_candidate_clips": len(full_decode_order), + "requested_target_clips": args.clips, + "resolution_hw": list(target_hw), + "max_recordings": args.max_recordings, + "candidate_position_range": list(prefill_range) if prefill_range else None, + "candidate_source_indices_sha256": sha256_json(full_decode_order), + "recordings": len({cache_rows[index]["source_group_key"] for index in ordered_cached}), + "skipped_no_supervision": skipped_no_supervision, + "geometry_masked_hand_frames": sum( + cache_rows[index]["geometry_masked_hand_frames"] for index in ordered_cached + ), + "geometry_masked_source_indices": [ + index for index in ordered_cached + if cache_rows[index]["geometry_masked_hand_frames"] + ], + "decode_all_candidates": bool(args.decode_all_candidates), + "resume_invocation": bool(args.resume), + "wall_seconds": elapsed, + "clips_per_second": position / elapsed, + "bytes": sum(Path(cache_rows[index]["cache_path"]).stat().st_size for index in ordered_cached), + } + report_path = args.output_dir / "cache_report.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase7_unified_source.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase7_unified_source.py new file mode 100644 index 0000000000000000000000000000000000000000..72c1f102f49f8b1c31bd065469ea43d9f629b1cf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/cache_phase7_unified_source.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Build resumable controlled caches for HOI4D or ARCTIC unified clips.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import math +from pathlib import Path +import time + +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset +from foundation_hand.data.schema import InvalidSourceSampleError +from scripts.cache_phase7_hot3d import ( + rgb_uint8, + validate_cached_resolution, + validated_target_hw, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def center_out(values: list[int]) -> list[int]: + values = sorted(values) + center = (len(values) - 1) // 2 + order = [center] + distance = 1 + while len(order) < len(values): + if center + distance < len(values): + order.append(center + distance) + if center - distance >= 0: + order.append(center - distance) + distance += 1 + return [values[index] for index in order] + + +def balanced_source_indices( + rows: list[dict], count: int, max_recordings: int, +) -> list[int]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + groups[(str(row["subject_id"]), str(row["physical_recording_id"]))].append(index) + strata: dict[str, list[tuple[str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[0]].append(key) + selected_groups: list[tuple[str, str]] = [] + cursor = 0 + while len(selected_groups) < min(max_recordings, len(groups)): + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected_groups.append(strata[subject][cursor]) + progress = True + if len(selected_groups) == max_recordings: + break + if not progress: + break + cursor += 1 + ordered = {key: center_out(groups[key]) for key in selected_groups} + selected: list[int] = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in selected_groups: + if cursor < len(ordered[key]): + selected.append(ordered[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def hand_side_source_indices(rows: list[dict], required_side: str) -> list[int]: + if required_side == "any": + return list(range(len(rows))) + if required_side not in {"left", "right"}: + raise ValueError("required hand side must be any, left or right") + return [ + index for index, row in enumerate(rows) + if any(required_side in sides for sides in row.get("hand_sides", [])) + ] + + +def cache_candidate_count(requested: int, available: int) -> int: + """Overdraw a deterministic candidate pool so invalid clips can be replaced.""" + return min(available, requested + max(32, math.ceil(requested * 0.1))) + + +def first_valid_indices( + selected: list[int], cached: dict[int, dict], requested: int, +) -> list[int]: + return [index for index in selected if index in cached][:requested] + + +def should_stop_decoding( + selected: list[int], cached: dict[int, dict], requested: int, + decode_all_candidates: bool, +) -> bool: + """Stop early only when full candidate decoding was not requested.""" + + return ( + not decode_all_candidates + and len(first_valid_indices(selected, cached, requested)) == requested + ) + + +def cache_completion_status( + requested: int, selected: list[int], cached: dict[int, dict], processed: int, + accept_all_valid: bool, +) -> str: + if accept_all_valid: + return "complete" if processed == len(selected) else "incomplete_source_scan" + return "complete" if len(first_valid_indices(selected, cached, requested)) == requested else "insufficient_valid_clips" + + +def recording_local_batches( + decode_order: list[int], rows: list[dict], batch_size: int = 2, +) -> list[list[int]]: + if batch_size < 1: + raise ValueError("prefetch batch size must be positive") + batches: list[list[int]] = [] + start = 0 + while start < len(decode_order): + recording = rows[decode_order[start]]["physical_recording_id"] + end = start + while ( + end < len(decode_order) + and rows[decode_order[end]]["physical_recording_id"] == recording + ): + end += 1 + group = decode_order[start:end] + batches.extend( + group[offset:offset + batch_size] + for offset in range(0, len(group), batch_size) + ) + start = end + return batches + + +def cache_row( + source_row: dict, source_index: int, output: Path, dataset: str, + target_hw: tuple[int, int], + right_geometry_masked_frames: int = 0, +) -> dict: + return { + "dataset_id": dataset, + "subject_id": str(source_row["subject_id"]), + "sequence_id": str(source_row["physical_recording_id"]), + "physical_recording_id": str(source_row["physical_recording_id"]), + "camera_id": str(source_row["camera_id"]), + "stream_id": str(source_row["camera_id"]), + "headset_id": str(source_row.get("serial_id", source_row["subject_id"])), + "source_clip_index": source_index, + "source_group_key": str(source_row["group_key"]), + "resolution_hw": list(target_hw), + "cache_path": str(output.resolve()), + "cache_sha256": sha256(output), + "right_geometry_masked_frames": int(right_geometry_masked_frames), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int, required=True) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument( + "--required-hand-side", choices=("any", "left", "right"), default="any", + help="Optional source-manifest hand-presence filter before balancing.", + ) + parser.add_argument( + "--prefetch-batch-size", type=int, default=0, + help="Optional exact recording-local prefetch batch; 0 keeps the original decoder.", + ) + parser.add_argument( + "--decode-all-candidates", action="store_true", + help="Decode the complete balanced overdraw pool before freezing the valid prefix.", + ) + parser.add_argument( + "--accept-all-valid", action="store_true", + help="For a full source manifest, cache every valid clip and report invalid clips explicitly.", + ) + parser.add_argument("--resume", action="store_true") + parser.add_argument("--torch-threads", type=int, default=0) + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + if min(args.clips, args.max_recordings) <= 0: + parser.error("clip and recording counts must be positive") + if args.torch_threads < 0: + parser.error("--torch-threads cannot be negative") + if args.torch_threads: + torch.set_num_threads(args.torch_threads) + torch.set_num_interop_threads(1) + if args.dataset == "HOI4D": + if args.root is None: + parser.error("HOI4D requires --root") + dataset = HOI4DClipDataset( + args.root, args.source_manifest, args.mano_root, target_hw=target_hw, + ) + else: + dataset = ARCTICClipDataset( + args.source_manifest, args.mano_root, target_hw=target_hw, + ) + eligible = hand_side_source_indices(dataset.rows, args.required_hand_side) + if args.accept_all_valid and args.clips != len(eligible): + parser.error("--accept-all-valid requires --clips to equal all eligible source clips") + eligible_rows = [dataset.rows[index] for index in eligible] + candidate_count = cache_candidate_count(args.clips, len(eligible_rows)) + selected = [ + eligible[index] + for index in balanced_source_indices( + eligible_rows, candidate_count, args.max_recordings, + ) + ] + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced candidates are available") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + # Group source reads to retain decoded sequence/provider state. + decode_order = sorted( + selected, + key=lambda index: ( + dataset.rows[index]["physical_recording_id"], + dataset.rows[index].get("frame_ids", dataset.rows[index].get("frame_ids_1based"))[0], + ), + ) + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", "geometry_convention_compatible", + } + cached: dict[int, dict] = {} + skipped_no_supervision: list[int] = [] + skipped_invalid_source: list[dict[str, str | int]] = [] + started = time.monotonic() + if args.prefetch_batch_size < 0: + parser.error("--prefetch-batch-size cannot be negative") + batches = ( + recording_local_batches(decode_order, dataset.rows, args.prefetch_batch_size) + if args.dataset == "HOI4D" and args.prefetch_batch_size + else [[index] for index in decode_order] + ) + position = 0 + for batch_indices in batches: + missing = [ + index for index in batch_indices + if not (clips_dir / f"clip_{index:07d}.npz").is_file() + ] + if args.dataset == "HOI4D" and args.prefetch_batch_size and missing: + dataset.prefetch_clip_indices(missing) + for source_index in batch_indices: + position += 1 + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise RuntimeError(f"invalid existing cache: {output}") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + right_geometry_masked_frames = int(np.count_nonzero( + archive["translation_valid"][..., 1] + & ~archive["mano_annotation_valid"][..., 1] + )) if args.dataset == "HOI4D" else 0 + else: + try: + sample = dataset[(source_index, 0)] + except InvalidSourceSampleError as error: + if not args.accept_all_valid: + raise + skipped_invalid_source.append({ + "source_clip_index": source_index, + "reason": str(error), + }) + has_supervision = False + else: + has_supervision = bool(sample["translation_valid"].any()) + right_geometry_masked_frames = int(( + sample["translation_valid"][..., 1] + & ~sample["mano_annotation_valid"][..., 1] + ).sum()) if args.dataset == "HOI4D" else 0 + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + if not has_supervision: + if not skipped_invalid_source or skipped_invalid_source[-1]["source_clip_index"] != source_index: + skipped_no_supervision.append(source_index) + else: + cached[source_index] = cache_row( + dataset.rows[source_index], source_index, output, args.dataset, + target_hw, + right_geometry_masked_frames, + ) + if position % 10 == 0 or position == len(decode_order): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": position, "requested": len(decode_order), + "cached": len(cached), "skipped_no_supervision": len(skipped_no_supervision), + "skipped_invalid_source": len(skipped_invalid_source), + "clips_per_second": position / elapsed, + "eta_seconds": (len(decode_order) - position) / (position / elapsed), + }), flush=True) + if args.dataset == "HOI4D" and args.prefetch_batch_size: + dataset.clear_prefetch() + if should_stop_decoding( + selected, cached, args.clips, + args.decode_all_candidates or args.accept_all_valid, + ): + break + ordered_cached = first_valid_indices(selected, cached, args.clips) + manifest = args.output_dir / "cache_manifest.jsonl" + manifest_temporary = manifest.with_suffix(".tmp") + manifest_temporary.write_text( + "".join(json.dumps(cached[index], sort_keys=True) + "\n" for index in ordered_cached), + encoding="utf-8", + ) + manifest_temporary.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": cache_completion_status( + args.clips, selected, cached, position, args.accept_all_valid, + ), + "dataset": args.dataset, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "requested_clips": args.clips, "candidate_clips_processed": position, + "resolution_hw": list(target_hw), + "cached_clips": len(ordered_cached), "valid_candidate_files": len(cached), + "recordings": len({cached[index]["source_group_key"] for index in ordered_cached}), + "required_hand_side": args.required_hand_side, + "eligible_source_clips": len(eligible), + "accept_all_valid": bool(args.accept_all_valid), + "all_eligible_processed": position == len(selected), + "cached_valid_clips": len(ordered_cached), + "decode_all_candidates": bool(args.decode_all_candidates), + "skipped_no_supervision": skipped_no_supervision, + "skipped_invalid_source": skipped_invalid_source, + "right_geometry_masked_frames": sum( + cached[index]["right_geometry_masked_frames"] for index in ordered_cached + ), + "right_geometry_masked_source_indices": [ + index for index in ordered_cached + if cached[index]["right_geometry_masked_frames"] + ], + "wall_seconds": elapsed, "clips_per_second": position / elapsed, + "bytes": sum(Path(cached[index]["cache_path"]).stat().st_size for index in ordered_cached), + "resume_invocation": bool(args.resume), "official_test_used": False, + "torch_threads": args.torch_threads or torch.get_num_threads(), + } + (args.output_dir / "cache_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/capture_environment.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/capture_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3d38bbd2ddfca1e23fdbc2eb2518240f885a2f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/capture_environment.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Capture phase-2 environment without exposing unrelated environment variables.""" + +from __future__ import annotations + +import json +import platform +import subprocess +from pathlib import Path + +import cv2 +import numpy as np +import torch + + +def command(args: list[str]) -> str: + return subprocess.run(args, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.strip() + + +def main() -> None: + output = Path("artifacts/phase2/environment") + output.mkdir(parents=True, exist_ok=True) + report = { + "captured_at": command(["date", "--iso-8601=seconds"]), + "platform": platform.platform(), "python": platform.python_version(), + "torch": torch.__version__, "torch_cuda": torch.version.cuda, "cuda_available": torch.cuda.is_available(), + "cuda_devices": [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())], + "bf16_supported": [torch.cuda.is_bf16_supported(index) for index in range(torch.cuda.device_count())], + "numpy": np.__version__, "opencv": cv2.__version__, + "nvidia_smi": command(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free,driver_version", "--format=csv,noheader"]), + "git_status": command(["git", "status", "--short"]), + "git_head": command(["git", "rev-parse", "HEAD"]), + "dinov3_commit": command(["git", "-C", "third_party/dinov3", "rev-parse", "HEAD"]), + "manopth_commit": command(["git", "-C", "third_party/manopth", "rev-parse", "HEAD"]), + "h2oplayer_commit": command(["git", "-C", "third_party/h2oplayer", "rev-parse", "HEAD"]), + } + (output / "environment.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/capture_phase4_provenance.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/capture_phase4_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..805db38ce73a5086e3677718bcaf2d864e418d7f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/capture_phase4_provenance.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Capture the Phase 4 entry state without reading the official test split.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import subprocess +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import cv2 +import numpy as np +import torch + + +def command(args: list[str], cwd: Path) -> str: + result = subprocess.run( + args, + cwd=cwd, + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + return result.stdout.strip() + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/freeze/entry")) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + output = (root / args.output_dir).resolve() if not args.output_dir.is_absolute() else args.output_dir + output.mkdir(parents=True, exist_ok=True) + + checkpoint_index = json.loads( + (root / "artifacts/phase3/reports/long_tail_checkpoints.json").read_text(encoding="utf-8") + ) + checkpoints = [] + for run in checkpoint_index["runs"].values(): + role = run["roles"]["tail_best_absolute"] + path = Path(role["path"]) + checkpoints.append({ + "seed": int(run["seed"]), + "step": int(role["step"]), + "path": str(path), + "registered_sha256": role["sha256"], + "observed_sha256": sha256(path), + "bytes": path.stat().st_size, + "evaluation": role["evaluation"], + }) + + protected_inputs = { + "official_train_manifest": root / "artifacts/phase2/data_audit/manifests/official_train.jsonl", + "official_val_manifest": root / "artifacts/phase2/data_audit/manifests/official_val.jsonl", + "fixed_validation_subset": root / "artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json", + } + report = { + "captured_at": datetime.now(ZoneInfo("Asia/Hong_Kong")).isoformat(), + "project_root": str(root), + "git_head": command(["git", "rev-parse", "HEAD"], root), + "git_status": command(["git", "status", "--short", "--branch"], root), + "git_diff_stat": command(["git", "diff", "--stat"], root), + "git_diff_sha256": hashlib.sha256(command(["git", "diff", "--binary"], root).encode()).hexdigest(), + "platform": platform.platform(), + "python": platform.python_version(), + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "cuda_devices": [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())], + "numpy": np.__version__, + "opencv": cv2.__version__, + "nvidia_smi": command([ + "nvidia-smi", + "--query-gpu=index,name,uuid,memory.total,memory.used,memory.free,utilization.gpu", + "--format=csv,noheader", + ], root), + "submodules": command(["git", "submodule", "status"], root), + "checkpoints": checkpoints, + "protected_inputs": { + name: {"path": str(path.resolve()), "sha256": sha256(path), "bytes": path.stat().st_size} + for name, path in protected_inputs.items() + }, + "official_test_used": False, + "official_test_note": "The official test manifest and files are intentionally not read or hashed.", + } + (output / "entry_provenance.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + (output / "git_status.txt").write_text(report["git_status"] + "\n", encoding="utf-8") + (output / "git_diff.patch").write_text(command(["git", "diff", "--binary"], root) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "captured", + "output": str(output), + "git_head": report["git_head"], + "checkpoint_hashes_match": all( + item["registered_sha256"] == item["observed_sha256"] for item in checkpoints + ), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/capture_phase5_provenance.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/capture_phase5_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..bb59cafe4facd03ad4fb3b51fc4bb96eea8d77da --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/capture_phase5_provenance.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Capture Phase 5 entry provenance without touching the official test split.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import subprocess +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import torch + + +def command(args: list[str], cwd: Path) -> str: + return subprocess.run( + args, cwd=cwd, check=False, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + ).stdout.strip() + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase5/freeze/entry")) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + output = args.output_dir if args.output_dir.is_absolute() else root / args.output_dir + output.mkdir(parents=True, exist_ok=True) + + baselines = [ + { + "name": f"p0_512_seed{seed}", + "checkpoint": root / f"artifacts/phase3/depth_dropout_runs_commit7583772/depth_dropout00_geometry_m3_l1_t1_s{seed}/best.pt", + "evaluation": root / f"artifacts/phase3/depth_dropout_full_validation/depth_dropout00_geometry_m3_l1_t1_s{seed}/best_absolute/evaluation.json", + } + for seed in (20260716, 20260717, 20260718) + ] + [{ + "name": "unified_640_tail_seed20260718", + "checkpoint": Path("/SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/best.pt"), + "evaluation": root / "artifacts/phase3/long_tail_full_validation/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/tail_best_absolute/evaluation.json", + }] + baseline_records = [] + for baseline in baselines: + evaluation = json.loads(baseline["evaluation"].read_text(encoding="utf-8")) + checkpoint = baseline["checkpoint"] + observed_hash = sha256(checkpoint) + baseline_records.append({ + "name": baseline["name"], + "checkpoint": str(checkpoint.resolve()), + "registered_sha256": evaluation["checkpoint"]["sha256"], + "observed_sha256": observed_hash, + "hash_matches": observed_hash == evaluation["checkpoint"]["sha256"], + "step": evaluation["checkpoint"]["step"], + "evaluation": str(baseline["evaluation"].resolve()), + "absolute_mpjpe_mm": evaluation["metrics"]["absolute_mpjpe_mm"]["mean"], + "official_test_used": evaluation["official_test_used"], + }) + + protected = { + "official_train": root / "artifacts/phase2/data_audit/manifests/official_train.jsonl", + "official_validation": root / "artifacts/phase2/data_audit/manifests/official_val.jsonl", + "fixed_validation_subset_640": root / "artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json", + "phase5_oof_folds": root / "artifacts/phase5/splits/subject_oof_v1/folds.json", + } + report = { + "captured_at": datetime.now(ZoneInfo("Asia/Hong_Kong")).isoformat(), + "status": "captured", + "project_root": str(root), + "git_head": command(["git", "rev-parse", "HEAD"], root), + "git_status": command(["git", "status", "--short", "--branch"], root), + "git_diff_sha256": hashlib.sha256( + command(["git", "diff", "--binary"], root).encode() + ).hexdigest(), + "platform": platform.platform(), + "python": platform.python_version(), + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "nvidia_smi": command([ + "nvidia-smi", "--query-gpu=index,name,uuid,memory.total,memory.used,memory.free,utilization.gpu", + "--format=csv,noheader", + ], root), + "disk": command(["df", "-h", str(root), "/SSD2", "/SSD3"], root), + "active_compute_processes": command([ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid,process_name,used_memory", + "--format=csv,noheader", + ], root), + "baselines": baseline_records, + "protected_inputs": { + name: {"path": str(path.resolve()), "sha256": sha256(path), "bytes": path.stat().st_size} + for name, path in protected.items() + }, + "official_test_used": False, + "official_test_note": "Official test manifests, files, predictions, and hashes were intentionally not accessed.", + } + (output / "entry_provenance.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + (output / "git_status.txt").write_text(report["git_status"] + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], + "output": str(output), + "baseline_hashes_match": all(row["hash_matches"] for row in baseline_records), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase3_resume.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase3_resume.py new file mode 100644 index 0000000000000000000000000000000000000000..82924e82bed187f735fe17acf6647623b4b1e206 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase3_resume.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Compare uninterrupted and resumed Phase 3 final states exactly.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +from pathlib import Path + + +def worker(reference_path: Path, resumed_path: Path) -> None: + import numpy as np + import torch + + reference = torch.load(reference_path, map_location="cpu", weights_only=False) + resumed = torch.load(resumed_path, map_location="cpu", weights_only=False) + + def equal(left, right) -> bool: + if torch.is_tensor(left) and torch.is_tensor(right): + return left.dtype == right.dtype and left.shape == right.shape and torch.equal(left, right) + if isinstance(left, np.ndarray) and isinstance(right, np.ndarray): + return left.dtype == right.dtype and left.shape == right.shape and np.array_equal(left, right) + if isinstance(left, dict) and isinstance(right, dict): + return left.keys() == right.keys() and all(equal(left[key], right[key]) for key in left) + if isinstance(left, (tuple, list)) and isinstance(right, type(left)): + return len(left) == len(right) and all(equal(a, b) for a, b in zip(left, right)) + return left == right + + result = { + "reference_step": int(reference["step"]), + "resumed_step": int(resumed["step"]), + "model_exact": equal(reference["model"], resumed["model"]), + "optimizer_exact": equal(reference["optimizer"], resumed["optimizer"]), + "python_rng_exact": equal(reference["python_rng"], resumed["python_rng"]), + "numpy_rng_exact": equal(reference["numpy_rng"], resumed["numpy_rng"]), + "torch_rng_exact": equal(reference["torch_rng"], resumed["torch_rng"]), + "cuda_rng_exact": equal(reference["cuda_rng"], resumed["cuda_rng"]), + } + print(json.dumps(result)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("reference_root", type=Path, nargs="?") + parser.add_argument("resumed_root", type=Path, nargs="?") + parser.add_argument("--expected-runs", type=int) + parser.add_argument("--checkpoint-name", default="step_0100000_final.pt") + parser.add_argument("--expected-step", type=int, default=100_000) + parser.add_argument("--worker", nargs=2, type=Path) + args = parser.parse_args() + if args.worker: + worker(*args.worker) + return + if args.reference_root is None or args.resumed_root is None: + parser.error("reference_root and resumed_root are required") + + # The resumed root defines the audited subset while a larger reference matrix + # may still be running. + run_names = sorted( + path.name for path in args.resumed_root.iterdir() + if path.is_dir() and not path.name.startswith("_") + ) + if args.expected_runs is not None and len(run_names) != args.expected_runs: + raise ValueError(f"expected {args.expected_runs} runs, found {len(run_names)}") + records = [] + for run_name in run_names: + reference_path = args.reference_root / run_name / args.checkpoint_name + resumed_path = args.resumed_root / run_name / args.checkpoint_name + if not reference_path.is_file() or not resumed_path.is_file(): + raise FileNotFoundError(f"missing final checkpoint for {run_name}") + process = subprocess.run( + [ + sys.executable, str(Path(__file__).resolve()), "--worker", + str(reference_path), str(resumed_path), + ], + check=True, capture_output=True, text=True, + ) + records.append({"run": run_name, **json.loads(process.stdout)}) + + passed = bool(records) and all( + row["reference_step"] == row["resumed_step"] == args.expected_step + and row["model_exact"] and row["optimizer_exact"] + and row["python_rng_exact"] and row["numpy_rng_exact"] + and row["torch_rng_exact"] and row["cuda_rng_exact"] + for row in records + ) + payload = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "reference_root": str(args.reference_root), + "resumed_root": str(args.resumed_root), + "runs": records, + } + output = args.resumed_root / "exact_resume_audit.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": payload["status"], "runs": len(records), "output": str(output)}, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase5_alignment_calibrators.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase5_alignment_calibrators.py new file mode 100644 index 0000000000000000000000000000000000000000..5921cddec59bf99669817ea5ddbe8fee1c4c6335 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase5_alignment_calibrators.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Compare shared multi-checkpoint and per-seed OOF calibrators.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + + +CONDITIONS = ( + "coarse", + "robust_alignment_unscaled", + "calibrated_always", + "calibrated_confidence", +) +METRICS = ("absolute_mpjpe_mm", "z_mae_mm", "z_p95_mm", "z_cvar95_mm") + + +def load_report(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "fitted" + or report.get("result_role") != "train_oof_cross_validated_threshold_selection" + or report.get("official_validation_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"comparison requires a train-OOF-only calibration report: {path}") + return report + + +def compare_reports( + shared: dict[str, Any], per_seed: list[dict[str, Any]], +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + if int(shared.get("expected_banks_per_fold", -1)) <= 1: + raise ValueError("shared report is not a multi-checkpoint calibration") + expected_seeds = {int(seed) for seed in shared.get("coarse_seeds", [])} + specific = {} + for report in per_seed: + seeds = [int(seed) for seed in report.get("coarse_seeds", [])] + if int(report.get("expected_banks_per_fold", -1)) != 1 or len(seeds) != 1: + raise ValueError("each per-seed report must contain one seed and one bank per fold") + if seeds[0] in specific: + raise ValueError(f"duplicate per-seed report: {seeds[0]}") + specific[seeds[0]] = report + if set(specific) != expected_seeds: + raise ValueError( + f"per-seed reports do not match shared seeds: {sorted(specific)} vs {sorted(expected_seeds)}" + ) + + rows = [] + for seed in sorted(expected_seeds): + shared_metrics = shared["metrics_by_seed"][str(seed)] + specific_metrics = specific[seed]["metrics"] + for metric in METRICS: + shared_coarse = float(shared_metrics["coarse"][metric]) + specific_coarse = float(specific_metrics["coarse"][metric]) + if abs(shared_coarse - specific_coarse) > 1e-9: + raise ValueError(f"seed {seed} coarse {metric} mismatch") + for condition in CONDITIONS: + row: dict[str, Any] = {"seed": seed, "condition": condition} + for metric in METRICS: + shared_value = float(shared_metrics[condition][metric]) + specific_value = float(specific_metrics[condition][metric]) + row[f"shared_{metric}"] = shared_value + row[f"per_seed_{metric}"] = specific_value + row[f"shared_minus_per_seed_{metric}"] = shared_value - specific_value + rows.append(row) + + calibrated = [row for row in rows if row["condition"] == "calibrated_always"] + summary = { + "status": "compared", + "experiment_class": "train_oof_shared_vs_per_seed_calibrator_ablation", + "seeds": sorted(expected_seeds), + "primary_condition": "calibrated_always", + "shared_absolute_better_seed_count": sum( + row["shared_minus_per_seed_absolute_mpjpe_mm"] < 0 for row in calibrated + ), + "mean_shared_minus_per_seed_absolute_mpjpe_mm": sum( + row["shared_minus_per_seed_absolute_mpjpe_mm"] for row in calibrated + ) / len(calibrated), + "mean_shared_minus_per_seed_z_p95_mm": sum( + row["shared_minus_per_seed_z_p95_mm"] for row in calibrated + ) / len(calibrated), + "official_validation_used": False, + "official_test_used": False, + } + return rows, summary + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--shared", type=Path, required=True) + parser.add_argument("--per-seed", type=Path, action="append", required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("comparison refuses to overwrite outputs") + shared = load_report(args.shared) + per_seed = [load_report(path) for path in args.per_seed] + rows, summary = compare_reports(shared, per_seed) + report = { + **summary, + "shared_report": str(args.shared.resolve()), + "per_seed_reports": [str(path.resolve()) for path in args.per_seed], + "rows": rows, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase6_paired_evaluations.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase6_paired_evaluations.py new file mode 100644 index 0000000000000000000000000000000000000000..6720f4f081aba86cf6a2f3152e427076a0f95dad --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase6_paired_evaluations.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Pair two frozen Phase 6 evaluation outputs by take/frame/side.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + + +METRIC_ALIASES = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm",), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm",), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm",), + "root_relative_mpvpe_mm": ("root_relative_mpvpe_mm",), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm",), + "translation_x_mae_mm": ("translation_x_mae_mm",), + "translation_y_mae_mm": ("translation_y_mae_mm",), + "translation_z_mae_mm": ("translation_z_mae_mm",), + "direct_2d_error_px": ("direct_2d_error_px",), + "projected_mano_2d_px": ("projected_mano_2d_px", "mano_projected_2d_error_px"), + "direct_mano_consistency_px": ( + "direct_mano_consistency_px", "direct_mano_2d_consistency_px", + ), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_rows(path: Path, condition: str | None) -> dict[tuple[str, int, str], dict[str, float]]: + output = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + if condition is not None and row.get("condition") != condition: + continue + if row.get("annotation_valid") not in (None, "1", "True", "true"): + continue + identity = (row["take"], int(row["frame_id"]), row["side"]) + if identity in output: + raise ValueError(f"duplicate paired identity: {identity}") + metrics = {} + for canonical, aliases in METRIC_ALIASES.items(): + source = next((alias for alias in aliases if row.get(alias, "") != ""), None) + if source is not None: + metrics[canonical] = float(row[source]) + output[identity] = metrics + if not output: + raise ValueError(f"no rows selected from {path}") + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--baseline-dir", type=Path, required=True) + parser.add_argument("--candidate-dir", type=Path, required=True) + parser.add_argument("--baseline-condition") + parser.add_argument("--candidate-condition") + parser.add_argument("--baseline-label", required=True) + parser.add_argument("--candidate-label", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + baseline_path = args.baseline_dir / "per_hand_frame_metrics.csv" + candidate_path = args.candidate_dir / "per_hand_frame_metrics.csv" + baseline = load_rows(baseline_path, args.baseline_condition) + candidate = load_rows(candidate_path, args.candidate_condition) + if set(baseline) != set(candidate): + raise ValueError("paired evaluations have different take/frame/side identities") + common_metrics = sorted( + set().union(*(set(row) for row in baseline.values())) + & set().union(*(set(row) for row in candidate.values())) + ) + if not common_metrics: + raise ValueError("paired evaluations have no common metrics") + frame_rows = [] + for identity in sorted(baseline): + take, frame_id, side = identity + row: dict[str, object] = {"take": take, "frame_id": frame_id, "side": side} + for metric in common_metrics: + if metric not in baseline[identity] or metric not in candidate[identity]: + continue + delta = candidate[identity][metric] - baseline[identity][metric] + row[f"baseline_{metric}"] = baseline[identity][metric] + row[f"candidate_{metric}"] = candidate[identity][metric] + row[f"delta_{metric}"] = delta + frame_rows.append(row) + rng = np.random.default_rng(20260717) + paired_rows = [] + for metric in common_metrics: + selected = [row for row in frame_rows if f"delta_{metric}" in row] + frame_delta = np.asarray([float(row[f"delta_{metric}"]) for row in selected]) + by_take: dict[str, list[float]] = defaultdict(list) + for row in selected: + by_take[str(row["take"])].append(float(row[f"delta_{metric}"])) + takes = sorted(by_take) + take_delta = np.asarray([ + np.mean(by_take[take]) for take in takes + ]) + indices = rng.integers(0, len(take_delta), size=(10_000, len(take_delta))) + bootstrap = take_delta[indices].mean(axis=1) + paired_rows.append({ + "candidate": args.candidate_label, "baseline": args.baseline_label, + "metric": metric, "hands": len(frame_delta), "takes": len(takes), + "frame_weighted_delta": float(frame_delta.mean()), + "take_equal_delta": float(take_delta.mean()), + "ci95_low": float(np.percentile(bootstrap, 2.5)), + "ci95_high": float(np.percentile(bootstrap, 97.5)), + "largest_sample_gain": float(frame_delta.min()), + "largest_sample_harm": float(frame_delta.max()), + "largest_take_gain": float(take_delta.min()), + "largest_take_harm": float(take_delta.max()), + }) + args.output_dir.mkdir(parents=True, exist_ok=True) + for filename, rows in ( + ("per_hand_frame_deltas.csv", frame_rows), + ("paired_take_bootstrap_ci.csv", paired_rows), + ): + with (args.output_dir / filename).open("x", newline="", encoding="utf-8") as handle: + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "paired", + "official_test_used": False, + "baseline": { + "label": args.baseline_label, "directory": str(args.baseline_dir.resolve()), + "condition": args.baseline_condition, "rows_sha256": sha256(baseline_path), + }, + "candidate": { + "label": args.candidate_label, "directory": str(args.candidate_dir.resolve()), + "condition": args.candidate_condition, "rows_sha256": sha256(candidate_path), + }, + "paired_identities": len(frame_rows), + "physical_takes": len({str(row["take"]) for row in frame_rows}), + "metrics": paired_rows, + } + (args.output_dir / "comparison.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_adaptation_forgetting.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_adaptation_forgetting.py new file mode 100644 index 0000000000000000000000000000000000000000..e1cb408e3922668217c70a3eddaf0c68cfd7748b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_adaptation_forgetting.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Paired external forgetting comparison for an H2O-adapted checkpoint.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.compare_phase8_specialist_curve import ( + MEAN_METRICS, + _load_rows, + _paired_bootstrap, +) + + +def _load_reference(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError("reference is not a strict external-heldout result") + return report + + +def _load_candidate(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_adaptation_external_heldout" + or report.get("evaluation_role") != "adaptation_external_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError("candidate is not an adaptation forgetting result") + return report + + +def compare( + reference_path: Path, + candidate_path: Path, + *, + seed: int = 20260717, + resamples: int = 2000, +) -> dict[str, Any]: + reference = _load_reference(reference_path) + candidate = _load_candidate(candidate_path) + for field in ("input_mode", "clips", "frames"): + if reference.get(field) != candidate.get(field): + raise ValueError(f"evaluation {field} differs") + if reference["cache_manifest"] != candidate["cache_manifest"]: + raise ValueError("evaluation cache manifest differs") + reference_rows = _load_rows(reference_path, reference) + candidate_rows = _load_rows(candidate_path, candidate) + if set(reference_rows) != set(candidate_rows): + raise ValueError("per-hand frame identities differ") + metrics: dict[str, Any] = {} + for metric in MEAN_METRICS: + metrics[metric] = { + "reference_global_mean": reference["metrics"][metric]["mean"], + "candidate_global_mean": candidate["metrics"][metric]["mean"], + **_paired_bootstrap( + reference_rows, candidate_rows, metric, "mean", seed, resamples, + ), + } + metrics["translation_z_recording_p95_mm"] = { + "reference_global_p95": reference["metrics"]["translation_z_mae_mm"]["p95"], + "candidate_global_p95": candidate["metrics"]["translation_z_mae_mm"]["p95"], + **_paired_bootstrap( + reference_rows, candidate_rows, "translation_z_mae_mm", "p95", + seed, resamples, + ), + } + return { + "schema_version": "phase8_adaptation_forgetting_comparison_v1", + "status": "complete", + "delta_definition": "adapted_candidate_minus_external_reference; positive is forgetting", + "reference": { + "evaluation": str(reference_path.resolve()), + "checkpoint": reference["checkpoint"], + }, + "candidate": { + "evaluation": str(candidate_path.resolve()), + "checkpoint": candidate["checkpoint"], + }, + "input_mode": reference["input_mode"], + "cache_manifest": reference["cache_manifest"], + "per_hand_identity_count": len(reference_rows), + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "metrics": metrics, + "selection_use": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-evaluation", type=Path, required=True) + parser.add_argument("--candidate-evaluation", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = compare( + args.reference_evaluation, args.candidate_evaluation, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_h2o_trainheldout.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_h2o_trainheldout.py new file mode 100644 index 0000000000000000000000000000000000000000..f823fbc57892f9bf3c1192807b564b7ad628c97a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_h2o_trainheldout.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Compare H2O train-heldout baselines separately by deployable input mode.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.select_phase7_h2o_adaptation import ( + METRIC_SPECS, + paired_recording_bootstrap, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def checked_artifact(report: dict[str, Any], name: str) -> Path: + record = report[name] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"{name} is missing or SHA256 differs: {path}") + return path + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("selection_split") != "h2o_train_group_heldout_only" + or manifest.get("h2o_official_validation_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("comparison manifest violates the train-heldout boundary") + by_mode: dict[str, list[dict[str, Any]]] = {} + cache_hashes: set[str] = set() + seen: set[tuple[str, str]] = set() + valid_status_roles = { + ("evaluated_h2o_train_group_heldout", "h2o_train_group_heldout"), + ("evaluated_h2o_train_group_heldout_control", "h2o_train_group_heldout_control"), + } + for item in manifest.get("candidates", []): + condition = str(item["condition"]) + report_path = Path(item["evaluation"]) + report = json.loads(report_path.read_text(encoding="utf-8")) + status_role = (report.get("status"), report.get("evaluation_role")) + mode = str(report.get("input_mode")) + if ( + status_role not in valid_status_roles + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or Path(report["cache_manifest"]["path"]).name != "train_group_heldout.jsonl" + ): + raise ValueError(f"invalid H2O train-heldout result: {report_path}") + if (condition, mode) in seen: + raise ValueError(f"duplicate condition/mode: {condition}/{mode}") + seen.add((condition, mode)) + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + cache = checked_artifact(report, "cache_manifest") + rows = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + cache_hashes.add(report["cache_manifest"]["sha256"]) + metrics = { + name: float(report["metrics"][row_metric][statistic]) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + by_mode.setdefault(mode, []).append({ + "condition": condition, "evaluation": str(report_path.resolve()), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config.resolve()), "cache_manifest": str(cache.resolve()), + "per_hand_rows": str(rows.resolve()), "metrics": metrics, + }) + if len(cache_hashes) != 1: + raise ValueError("candidates use different train-heldout manifests") + if not by_mode: + raise ValueError("comparison manifest has no candidates") + modes: dict[str, Any] = {} + for mode, candidates in sorted(by_mode.items()): + if len(candidates) < 2: + raise ValueError(f"input mode requires at least two candidates: {mode}") + order = sorted(candidates, key=lambda row: ( + row["metrics"]["absolute_mpjpe_mm"], + row["metrics"]["root_relative_mpjpe_mm"], + row["condition"], + )) + winner = order[0] + paired = {} + for candidate in order[1:]: + paired[candidate["condition"]] = { + name: paired_recording_bootstrap( + Path(winner["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + modes[mode] = { + "winner": winner["condition"], + "order": [candidate["condition"] for candidate in order], + "candidates": order, + "paired_recording_bootstrap_vs_winner": paired, + } + return { + "status": "compared_h2o_train_group_heldout_by_input_mode", + "selection_split": "h2o_train_group_heldout_only", + "selection_rule": "lowest Absolute MPJPE separately within each input mode", + "modes": modes, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_h2o_zero_shot.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c3efcc36b714f01f46834472c98a2b59014f8f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_h2o_zero_shot.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Compare already-frozen external checkpoints on H2O validation diagnostically.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import Any + +from scripts.compare_phase8_h2o_trainheldout import checked_artifact +from scripts.select_phase7_h2o_adaptation import METRIC_SPECS, paired_recording_bootstrap + + +BOUNDARY = "frozen_external_checkpoints_h2o_official_validation_diagnostic_only" + + +def _metrics(report: dict[str, Any]) -> dict[str, float]: + values = { + name: float(report["metrics"][row_metric][statistic]) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + if not all(math.isfinite(value) for value in values.values()): + raise ValueError("zero-shot report contains non-finite metrics") + return values + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("comparison_boundary") != BOUNDARY + or manifest.get("checkpoint_selection_frozen_before_h2o") is not True + or manifest.get("h2o_official_validation_used_for_external_selection") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("comparison manifest violates the frozen zero-shot boundary") + reference_condition = str(manifest.get("reference_condition", "")) + by_mode: dict[str, list[dict[str, Any]]] = {} + validation_hashes: set[str] = set() + seen: set[tuple[str, str]] = set() + for item in manifest.get("candidates", []): + condition = str(item["condition"]) + path = Path(item["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + mode = str(report.get("input_mode")) + if ( + report.get("status") != "evaluated_strict_h2o_zero_shot" + or report.get("evaluation_role") != "strict_external_zero_shot" + or report.get("h2o_training_data_used") is not False + or report.get("h2o_official_validation_used") is not True + or report.get("h2o_official_validation_used_for_external_selection") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid frozen H2O zero-shot result: {path}") + if (condition, mode) in seen: + raise ValueError(f"duplicate condition/mode: {condition}/{mode}") + seen.add((condition, mode)) + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + rows = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + validation = checked_artifact(report, "manifest") + validation_hashes.add(report["manifest"]["sha256"]) + by_mode.setdefault(mode, []).append({ + "condition": condition, + "evaluation": str(path.resolve()), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config), + "validation_manifest": str(validation), + "per_hand_rows": str(rows), + "metrics": _metrics(report), + }) + if len(validation_hashes) != 1 or not by_mode: + raise ValueError("zero-shot candidates must use one frozen validation manifest") + modes: dict[str, Any] = {} + for mode, candidates in sorted(by_mode.items()): + references = [row for row in candidates if row["condition"] == reference_condition] + if len(references) != 1 or len(candidates) < 2: + raise ValueError(f"mode lacks one reference and at least one candidate: {mode}") + reference = references[0] + comparisons = {} + for candidate in candidates: + if candidate is reference: + continue + comparisons[candidate["condition"]] = { + name: paired_recording_bootstrap( + Path(reference["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + modes[mode] = { + "reference": reference, + "candidates": [row for row in candidates if row is not reference], + "paired_candidate_minus_reference": comparisons, + } + return { + "status": "compared_frozen_h2o_zero_shot_diagnostic_only", + "comparison_boundary": BOUNDARY, + "selection_performed": False, + "reference_condition": reference_condition, + "modes": modes, + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_specialist_curve.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_specialist_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..92a78c396b10552bb60b3407b9e9686f7859ad84 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_specialist_curve.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Compare two frozen specialist checkpoints on identical external rows.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +MEAN_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", +) +IDENTITY_FIELDS = ( + "dataset", "physical_recording_id", "camera_id", "frame_id", "side", +) + + +def _load_report(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError(f"evaluation violates external curve contract: {path}") + return report + + +def _load_rows(report_path: Path, report: dict[str, Any]) -> dict[tuple[str, ...], dict[str, str]]: + specification = report["per_hand_rows"] + row_path = Path( + specification["path"] if isinstance(specification, dict) else specification, + ) + if not row_path.is_absolute(): + row_path = report_path.parent / row_path + if isinstance(specification, dict): + digest = hashlib.sha256(row_path.read_bytes()).hexdigest() + if digest != specification.get("sha256"): + raise ValueError(f"per-hand row SHA256 differs: {row_path}") + with row_path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + indexed: dict[tuple[str, ...], dict[str, str]] = {} + for row in rows: + identity = tuple(str(row[field]) for field in IDENTITY_FIELDS) + if identity in indexed: + raise ValueError(f"duplicate per-hand identity: {identity}") + indexed[identity] = row + if not indexed: + raise ValueError(f"evaluation has no per-hand rows: {row_path}") + return indexed + + +def _recording_statistic( + rows: dict[tuple[str, ...], dict[str, str]], metric: str, statistic: str, +) -> dict[tuple[str, str], float]: + grouped: dict[tuple[str, str], list[float]] = {} + for identity, row in rows.items(): + value = float(row[metric]) + if math.isfinite(value): + grouped.setdefault((identity[0], identity[1]), []).append(value) + if statistic == "mean": + reduce = np.mean + elif statistic == "p95": + reduce = lambda values: np.quantile(values, 0.95) + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + return {key: float(reduce(values)) for key, values in grouped.items()} + + +def _paired_bootstrap( + reference: dict[tuple[str, str], dict[str, str]], + candidate: dict[tuple[str, str], dict[str, str]], + metric: str, + statistic: str, + seed: int, + resamples: int, +) -> dict[str, Any]: + reference_values = _recording_statistic(reference, metric, statistic) + candidate_values = _recording_statistic(candidate, metric, statistic) + if set(reference_values) != set(candidate_values): + raise ValueError(f"finite recording coverage differs for {metric}/{statistic}") + keys = sorted(reference_values) + delta = np.asarray( + [candidate_values[key] - reference_values[key] for key in keys], + dtype=np.float64, + ) + rng = np.random.default_rng(seed) + sampled = delta[ + rng.integers(0, len(delta), size=(resamples, len(delta))) + ].mean(axis=1) + return { + "recording_statistic": statistic, + "recording_count": len(keys), + "mean_delta": float(delta.mean()), + "ci95_low": float(np.percentile(sampled, 2.5)), + "ci95_high": float(np.percentile(sampled, 97.5)), + } + + +def compare( + reference_path: Path, + candidate_path: Path, + *, + seed: int = 20260717, + resamples: int = 2000, +) -> dict[str, Any]: + reference_report = _load_report(reference_path) + candidate_report = _load_report(candidate_path) + for field in ("input_mode", "clips", "frames"): + if reference_report.get(field) != candidate_report.get(field): + raise ValueError(f"evaluation {field} differs") + if reference_report["cache_manifest"] != candidate_report["cache_manifest"]: + raise ValueError("evaluation cache manifest differs") + reference_rows = _load_rows(reference_path, reference_report) + candidate_rows = _load_rows(candidate_path, candidate_report) + if set(reference_rows) != set(candidate_rows): + raise ValueError("per-hand frame identities differ") + metrics: dict[str, Any] = {} + for metric in MEAN_METRICS: + reference_summary = reference_report["metrics"].get(metric) or {} + candidate_summary = candidate_report["metrics"].get(metric) or {} + metrics[metric] = { + "reference_global_mean": reference_summary.get("mean"), + "candidate_global_mean": candidate_summary.get("mean"), + **_paired_bootstrap( + reference_rows, candidate_rows, metric, "mean", seed, resamples, + ), + } + z_reference = reference_report["metrics"]["translation_z_mae_mm"] + z_candidate = candidate_report["metrics"]["translation_z_mae_mm"] + metrics["translation_z_recording_p95_mm"] = { + "reference_global_p95": z_reference.get("p95"), + "candidate_global_p95": z_candidate.get("p95"), + **_paired_bootstrap( + reference_rows, candidate_rows, "translation_z_mae_mm", "p95", + seed, resamples, + ), + } + absolute = metrics["absolute_mpjpe_mm"] + return { + "schema_version": "phase8_specialist_curve_comparison_v1", + "status": "complete", + "delta_definition": "candidate_minus_reference; negative favors candidate", + "reference": { + "evaluation": str(reference_path.resolve()), + "checkpoint_step": reference_report["checkpoint_step"], + "checkpoint": reference_report["checkpoint"], + }, + "candidate": { + "evaluation": str(candidate_path.resolve()), + "checkpoint_step": candidate_report["checkpoint_step"], + "checkpoint": candidate_report["checkpoint"], + }, + "input_mode": reference_report["input_mode"], + "cache_manifest": reference_report["cache_manifest"], + "per_hand_identity_count": len(reference_rows), + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "metrics": metrics, + "candidate_absolute_lower": ( + float(absolute["candidate_global_mean"]) + < float(absolute["reference_global_mean"]) + ), + "candidate_absolute_ci_excludes_zero": absolute["ci95_high"] < 0.0, + "h2o_training_data_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-evaluation", type=Path, required=True) + parser.add_argument("--candidate-evaluation", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + args.reference_evaluation, args.candidate_evaluation, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_stage7_left.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_stage7_left.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e522e3d109275545d58a7f4c7402d090b00fce --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/compare_phase8_stage7_left.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Compare matched Stage 7 left-supervision screens on external held-out data.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.select_phase7_h2o_adaptation import paired_recording_bootstrap + + +CONDITIONS = ("L0_sampler_only", "L1_left_root_relative") +DATASETS = ("HOT3D", "HOI4D", "ARCTIC") +METRICS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "source_root_relative_mpjpe_mm": ("source_root_relative_mpjpe_mm", "mean"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def checked(report: dict[str, Any], name: str) -> Path: + record = report[name] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"{name} is missing or SHA256 differs: {path}") + return path + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("evaluation_split") != "external_heldout_only" + or manifest.get("h2o_training_data_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("Stage 7 comparison boundary flags are invalid") + reports: dict[str, dict[str, dict[str, Any]]] = {condition: {} for condition in CONDITIONS} + for item in manifest.get("evaluations", []): + condition, dataset = str(item["condition"]), str(item["dataset"]) + if condition not in reports or dataset not in DATASETS: + raise ValueError(f"unexpected condition/dataset: {condition}/{dataset}") + if dataset in reports[condition]: + raise ValueError(f"duplicate condition/dataset: {condition}/{dataset}") + path = Path(item["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid external evaluation: {path}") + rows = checked(report, "per_hand_rows") + cache = checked(report, "cache_manifest") + checked(report, "checkpoint") + checked(report, "config") + reports[condition][dataset] = { + "path": str(path.resolve()), "report": report, + "rows": rows, "cache": cache, + } + for condition in CONDITIONS: + if set(reports[condition]) != set(DATASETS): + raise ValueError(f"{condition} does not contain all external domains") + datasets: dict[str, Any] = {} + for dataset in DATASETS: + reference = reports[CONDITIONS[0]][dataset] + candidate = reports[CONDITIONS[1]][dataset] + for key in ("sha256",): + if reference["report"]["cache_manifest"][key] != candidate["report"]["cache_manifest"][key]: + raise ValueError(f"{dataset} cache differs between L0 and L1") + if reference["report"]["input_mode"] != candidate["report"]["input_mode"]: + raise ValueError(f"{dataset} input mode differs between L0 and L1") + condition_metrics: dict[str, Any] = {} + for condition, record in ((CONDITIONS[0], reference), (CONDITIONS[1], candidate)): + report_metrics = record["report"]["metrics"] + condition_metrics[condition] = { + metric: ( + None if report_metrics.get(row_metric) is None + else float(report_metrics[row_metric][statistic]) + ) + for metric, (row_metric, statistic) in METRICS.items() + } + paired = { + metric: paired_recording_bootstrap( + reference["rows"], candidate["rows"], row_metric, statistic, + seed, resamples, + ) + for metric, (row_metric, statistic) in METRICS.items() + if condition_metrics[CONDITIONS[0]][metric] is not None + and condition_metrics[CONDITIONS[1]][metric] is not None + } + datasets[dataset] = { + "cache_manifest_sha256": reference["report"]["cache_manifest"]["sha256"], + "input_mode": reference["report"]["input_mode"], + "conditions": condition_metrics, + "paired_L1_minus_L0": paired, + } + macro: dict[str, Any] = {} + for metric in ("absolute_mpjpe_mm", "root_relative_mpjpe_mm"): + values = { + condition: [datasets[dataset]["conditions"][condition][metric] for dataset in DATASETS] + for condition in CONDITIONS + } + macro[metric] = { + **{condition: sum(rows) / len(rows) for condition, rows in values.items()}, + } + macro[metric]["L1_minus_L0"] = ( + macro[metric][CONDITIONS[1]] - macro[metric][CONDITIONS[0]] + ) + left_datasets = ("HOI4D", "ARCTIC") + source_values = { + condition: [ + datasets[dataset]["conditions"][condition]["source_root_relative_mpjpe_mm"] + for dataset in left_datasets + ] + for condition in CONDITIONS + } + if any(value is None for values in source_values.values() for value in values): + raise ValueError("left held-out source-root supervision is missing") + macro["source_root_relative_mpjpe_mm"] = { + condition: sum(values) / len(values) for condition, values in source_values.items() + } + macro["source_root_relative_mpjpe_mm"]["L1_minus_L0"] = ( + macro["source_root_relative_mpjpe_mm"][CONDITIONS[1]] + - macro["source_root_relative_mpjpe_mm"][CONDITIONS[0]] + ) + source_gain = -macro["source_root_relative_mpjpe_mm"]["L1_minus_L0"] + accepted = ( + source_gain >= 0.5 + and macro["absolute_mpjpe_mm"]["L1_minus_L0"] <= 1.0 + and macro["root_relative_mpjpe_mm"]["L1_minus_L0"] <= 1.0 + ) + return { + "schema_version": "phase8_stage7_left_comparison_v1", + "status": "complete", "datasets": datasets, "dataset_macro": macro, + "gate": { + "minimum_source_root_gain_mm": 0.5, + "maximum_absolute_regression_mm": 1.0, + "maximum_root_relative_regression_mm": 1.0, + "accepted": accepted, + }, + "h2o_training_data_used": False, "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/derive_phase9_hot_subset.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/derive_phase9_hot_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..abbd427229e098170eb3c8a45d4aef55ad057922 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/derive_phase9_hot_subset.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Derive a deterministic headset/recording-balanced HOT3D cache subset.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict, deque +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def balanced_subset(rows: list[dict[str, Any]], clips: int) -> list[dict[str, Any]]: + if clips <= 0 or clips > len(rows): + raise ValueError("subset size must be in [1, source rows]") + unique_indices = {int(row["source_clip_index"]) for row in rows} + if len(unique_indices) != len(rows): + raise ValueError("source cache contains duplicate source_clip_index values") + grouped: dict[str, dict[str, deque[dict[str, Any]]]] = defaultdict(dict) + by_recording: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for row in rows: + headset = str(row.get("headset_id", "unknown")) + recording = str(row["physical_recording_id"]) + by_recording[(headset, recording)].append(row) + for (headset, recording), recording_rows in by_recording.items(): + grouped[headset][recording] = deque(sorted( + recording_rows, key=lambda row: int(row["source_clip_index"]), + )) + + headsets = sorted(grouped) + recording_cursor = {headset: 0 for headset in headsets} + recording_ids = { + headset: sorted(grouped[headset]) for headset in headsets + } + selected: list[dict[str, Any]] = [] + while len(selected) < clips: + progress = False + for headset in headsets: + ids = recording_ids[headset] + for _ in range(len(ids)): + cursor = recording_cursor[headset] % len(ids) + recording_cursor[headset] += 1 + queue = grouped[headset][ids[cursor]] + if queue: + selected.append(queue.popleft()) + progress = True + break + if len(selected) == clips: + break + if not progress: + raise RuntimeError("balanced subset exhausted before requested size") + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--source-report", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + report = json.loads(args.source_report.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(args.source_manifest) + ): + parser.error("source cache report does not bind a complete manifest") + rows = load_jsonl(args.source_manifest) + selected = balanced_subset(rows, args.clips) + missing = [row["cache_path"] for row in selected if not Path(row["cache_path"]).is_file()] + if missing: + parser.error(f"selected cache payload is missing: {missing[0]}") + args.output_dir.mkdir(parents=True) + manifest = args.output_dir / "cache_manifest.jsonl" + temporary = manifest.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in selected), + encoding="utf-8", + ) + temporary.replace(manifest) + headset_counts = Counter(str(row.get("headset_id", "unknown")) for row in selected) + stream_counts = Counter(str(row.get("stream_id", "unknown")) for row in selected) + recording_counts = Counter(str(row["physical_recording_id"]) for row in selected) + output = { + "schema_version": "phase9_hot_balanced_subset_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "source_cache_manifest": { + "path": str(args.source_manifest.resolve()), + "sha256": sha256(args.source_manifest), + "rows": len(rows), + }, + "source_cache_report": { + "path": str(args.source_report.resolve()), + "sha256": sha256(args.source_report), + }, + "cache_manifest": { + "path": str(manifest.resolve()), + "sha256": sha256(manifest), + }, + "clips": len(selected), + "unique_source_clip_indices": len({int(row["source_clip_index"]) for row in selected}), + "recordings": len(recording_counts), + "headset_clip_counts": dict(sorted(headset_counts.items())), + "stream_clip_counts": dict(sorted(stream_counts.items())), + "recording_clip_count_min": min(recording_counts.values()), + "recording_clip_count_max": max(recording_counts.values()), + "payload_copy_bytes": 0, + "payloads_referenced_from_parent": True, + "official_test_used": False, + } + report_path = args.output_dir / "cache_report.json" + report_path.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8") + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase3.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase3.py new file mode 100644 index 0000000000000000000000000000000000000000..4acdc8f9c12791353d8d2fd3653421539f757245 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase3.py @@ -0,0 +1,1155 @@ +#!/usr/bin/env python3 +"""Audited Phase 3 validation with MANO meshes, tail metrics, and take CIs.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.phase4 import ( + action_name, + bimanual_asymmetry, + depth_validity_bucket, + find_failure_intervals, + load_action_label, + local_depth_statistics, + summarize_group_metrics, +) +from foundation_hand.evaluation.selection import select_visualization_frames +from foundation_hand.evaluation.visualization import ( + MeshLayer, + draw_skeleton, + project_mesh_layers, + render_mesh_layers, + save_attention_figure, + save_camera_views, +) +from foundation_hand.geometry.camera import project_points, unproject_depth +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +SIDES = ("left", "right") +PREDICTED_COLORS = ((32, 190, 105), (235, 112, 45)) +TARGET_COLORS = ((40, 160, 245), (215, 55, 190)) +FINGERTIP_INDICES = (4, 8, 12, 16, 20) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_clip_indices_manifest( + path: Path, + *, + source_manifest: Path, + data_config: dict[str, object], + dataset_length: int, +) -> tuple[list[int], dict[str, object]]: + record = json.loads(path.read_text(encoding="utf-8")) + contract = record.get("dataset_contract", {}) + resolution = [int(value) for value in data_config["resolution_hw"]] + if record.get("source_manifest_sha256") != sha256(source_manifest): + raise ValueError("clip subset source-manifest hash mismatch") + if int(record.get("source_clip_count", -1)) != dataset_length: + raise ValueError("clip subset source length mismatch") + if contract.get("resolution_hw") != resolution: + raise ValueError("clip subset resolution mismatch") + if int(contract.get("T", -1)) != int(data_config["T"]): + raise ValueError("clip subset temporal length mismatch") + if int(contract.get("stride", -1)) != int(data_config["stride"]): + raise ValueError("clip subset stride mismatch") + indices = [int(index) for index in record.get("clip_indices", [])] + if len(indices) != int(record.get("count", -1)) or len(indices) != len(set(indices)): + raise ValueError("clip subset count/uniqueness mismatch") + if not indices or min(indices) < 0 or max(indices) >= dataset_length: + raise ValueError("clip subset index out of bounds") + return indices, record + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def rgb_from_batch(batch: dict[str, Any], time_index: int) -> np.ndarray: + rgb = batch["rgb"][0, time_index].float().cpu().permute(1, 2, 0).numpy() + return np.clip((rgb * RGB_STD + RGB_MEAN) * 255.0, 0, 255).astype(np.uint8) + + +def hand_size_bucket(size: float | None) -> str | None: + if size is None: + return None + if size < 64: + return "small" + if size < 128: + return "medium" + return "large" + + +def wrist_depth_bucket(depth: float | None) -> str | None: + if depth is None: + return None + if depth < 0.5: + return "near" + if depth < 0.8: + return "middle" + return "far" + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + return + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def temporal_position_bias_report(model: BimanualReconstructionModel) -> dict[str, object]: + layers = [] + for layer_index, layer in enumerate(model.decoder.temporal): + bias = getattr(layer, "relative_position_bias", None) + if bias is None: + continue + values = bias.detach().float().cpu().numpy() + max_distance = int(layer.relative_bias_max_distance) + layers.append({ + "layer": layer_index, + "offsets_key_minus_query": list(range(-max_distance, max_distance + 1)), + "shape": list(values.shape), + "mean": float(values.mean()), + "std": float(values.std()), + "max_abs": float(np.abs(values).max()), + "per_head_bias": values.tolist(), + }) + return { + "mode": model.config.temporal_position_mode, + "sign_convention": "key_time_minus_query_time", + "layers": layers, + } + + +def add_label(image: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image.copy() + box_height = 8 + 18 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], box_height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (6, 17 + 18 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.38, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def attach_gt_geometry( + batch: dict[str, Any], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor]: + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + vertices, joints = model.mano_layer( + axis_angle_to_matrix(pose), + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + return vertices, joints + + +def run_model( + model: BimanualReconstructionModel, + batch: dict[str, Any], + dtype: torch.dtype, +) -> dict[str, Any]: + with torch.autocast("cuda", dtype=dtype): + return model(batch) + + +def save_depth_geometry( + output: Path, batch: dict[str, Any], time_index: int, title: str, +) -> None: + depth = batch["depth_m"][0, time_index, 0].float().cpu().numpy() + valid = batch["depth_pixel_valid"][0, time_index, 0].bool().cpu().numpy() + K = batch["K"][0, time_index].float().cpu().numpy() + xyz, xyz_valid = unproject_depth(depth, K) + fig, axes = plt.subplots(2, 3, figsize=(13, 7), constrained_layout=True) + values = ( + (depth, "depth (m)", "viridis"), + (valid, "depth validity", "gray"), + (xyz[..., 2], "Z (m)", "viridis"), + (np.where(xyz_valid, xyz[..., 0], np.nan), "X (m)", "coolwarm"), + (np.where(xyz_valid, xyz[..., 1], np.nan), "Y (m)", "coolwarm"), + (np.linalg.norm(xyz, axis=-1), "XYZ norm (m)", "viridis"), + ) + for axis, (value, name, cmap) in zip(axes.flat, values, strict=True): + artist = axis.imshow(value, cmap=cmap) + axis.set_title(name) + axis.axis("off") + fig.colorbar(artist, ax=axis, shrink=0.75) + fig.suptitle(title) + fig.savefig(output, dpi=150) + plt.close(fig) + + +def render_frame_bundle( + output_dir: Path, + image: np.ndarray, + K: np.ndarray, + predicted_vertices: np.ndarray, + target_vertices: np.ndarray, + predicted_joints: np.ndarray, + target_joints_2d: np.ndarray, + direct_joints_2d: np.ndarray, + mano_joints_2d: np.ndarray, + valid_hands: np.ndarray, + faces: tuple[np.ndarray, np.ndarray], + title_lines: tuple[str, ...], +) -> np.ndarray: + predicted_layers = [ + MeshLayer(predicted_vertices[hand], faces[hand], PREDICTED_COLORS[hand], 0.58) + for hand in range(2) + ] + target_layers = [ + MeshLayer(target_vertices[hand], faces[hand], TARGET_COLORS[hand], 0.50) + for hand in range(2) if valid_hands[hand] + ] + predicted_render = render_mesh_layers(image, project_mesh_layers(predicted_layers, K)) + target_render = render_mesh_layers(image, project_mesh_layers(target_layers, K)) + joint_render = render_mesh_layers( + image, project_mesh_layers(target_layers + predicted_layers, K), + ) + panels = [image, target_render, predicted_render, joint_render] + names = ("RGB", "GT MANO", "predicted MANO", "joint z-buffer overlay") + labeled_panels = [] + for panel, name in zip(panels, names, strict=True): + labeled_panels.append(add_label(panel, (name,))) + mosaic = np.concatenate(( + np.concatenate(labeled_panels[:2], axis=1), + np.concatenate(labeled_panels[2:], axis=1), + ), axis=0) + cv2.imwrite(str(output_dir / "mesh_rgb_overlay.png"), cv2.cvtColor(add_label(mosaic, title_lines), cv2.COLOR_RGB2BGR)) + + for hand, side in enumerate(SIDES): + layers = [predicted_layers[hand]] + if valid_hands[hand]: + layers.insert(0, MeshLayer(target_vertices[hand], faces[hand], TARGET_COLORS[hand], 0.50)) + rendered = render_mesh_layers(image, project_mesh_layers(layers, K)) + cv2.imwrite(str(output_dir / f"{side}_mesh_overlay.png"), cv2.cvtColor(add_label(rendered, title_lines), cv2.COLOR_RGB2BGR)) + + skeleton = image.copy() + for hand in range(2): + if valid_hands[hand]: + skeleton = draw_skeleton(skeleton, target_joints_2d[hand], (255, 255, 255), marker="cross") + skeleton = draw_skeleton(skeleton, direct_joints_2d[hand], PREDICTED_COLORS[hand], marker="circle", draw_edges=False) + skeleton = draw_skeleton(skeleton, mano_joints_2d[hand], TARGET_COLORS[hand], marker="ring") + skeleton = add_label(skeleton, title_lines + ("GT=white cross; direct-2D=dot; projected predicted MANO=ring",)) + cv2.imwrite(str(output_dir / "skeleton_consistency_overlay.png"), cv2.cvtColor(skeleton, cv2.COLOR_RGB2BGR)) + return add_label(joint_render, title_lines) + + +def visualize_selections( + selections: list[dict[str, object]], + dataset: H2OCam4Dataset, + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + config: dict[str, Any], + output_root: Path, +) -> None: + faces = tuple(layer.th_faces.cpu().numpy() for layer in model.mano_layer.layers) + modalities = "RGB" + ("+Depth" if config["model"].get("use_depth") else "") + ("+K" if config["model"].get("use_rays") else "") + for selection_index, selection in enumerate(selections): + clip_index = int(selection["clip_index"]) + requested_time = int(selection["time_index"]) + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(): + target_vertices, _ = attach_gt_geometry(batch, model) + prediction = run_model(model, batch, dtype) + valid_times = int(batch["frame_valid"][0].sum()) + time_index = min(requested_time, valid_times - 1) + sample_dir = output_root / f"{selection_index:02d}_{selection['subject']}_{str(selection['sequence']).replace('/', '_')}_{int(selection['frame_id']):06d}" + sample_dir.mkdir(parents=True, exist_ok=True) + valid_hands = batch["mano_annotation_valid"][0, time_index].bool().cpu().numpy() + K = batch["K"][0, time_index].float().cpu().numpy() + image = rgb_from_batch(batch, time_index) + predicted_vertices = prediction["vertices_camera"][0, time_index].float().cpu().numpy() + target_vertices_np = target_vertices[0, time_index].float().cpu().numpy() + predicted_joints = prediction["joints_camera"][0, time_index].float() + mano_2d, _ = project_points(predicted_joints, batch["K"][0, time_index].float()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"][0, time_index].float().cpu().numpy() * np.asarray((width, height)) + title_lines = ( + f"{selection['subject']}/{selection['sequence']}/{int(selection['frame_id'])} | L/R valid={int(valid_hands[0])}/{int(valid_hands[1])}", + f"config={config['name']} input={modalities} presence=unsupervised", + f"selection={','.join(str(reason) for reason in selection['reasons'])}", + ) + render_frame_bundle( + sample_dir, image, K, predicted_vertices, target_vertices_np, + predicted_joints.cpu().numpy(), batch["joint2d"][0, time_index].float().cpu().numpy(), + direct_2d, mano_2d.cpu().numpy(), valid_hands, faces, title_lines, + ) + save_camera_views( + sample_dir / "camera_3d_front_side.png", predicted_vertices, target_vertices_np, + valid_hands, " | ".join(title_lines[:2]), + ) + save_depth_geometry(sample_dir / "depth_xyz.png", batch, time_index, " | ".join(title_lines[:2])) + + attention = prediction["attention"] + grid_hw = (height // int(config["model"].get("patch_size", 16)), width // int(config["model"].get("patch_size", 16))) + rgb_attention = attention["rgb_cross_attention"][0, -1, time_index].float().cpu().numpy() + save_attention_figure( + sample_dir / "rgb_attention_raw_shared_scale.png", image, + rgb_attention[0], rgb_attention[1], grid_hw, "RGB | " + " | ".join(title_lines[:2]), + ) + if "depth_cross_attention" in attention: + depth_attention = attention["depth_cross_attention"][0, -1, time_index].float().cpu().numpy() + save_attention_figure( + sample_dir / "depth_attention_raw_shared_scale.png", image, + depth_attention[0], depth_attention[1], grid_hw, "Depth | " + " | ".join(title_lines[:2]), + ) + if "temporal_attention" in attention: + temporal = attention["temporal_attention"][0, -1].float().cpu().numpy() + shared_max = max(float(temporal.max()), 1e-8) + fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True) + artist = None + for hand, side in enumerate(SIDES): + artist = axes[hand].imshow(temporal[hand], vmin=0, vmax=shared_max, cmap="viridis") + axes[hand].set_title(side) + axes[hand].set_xlabel("key frame") + axes[hand].set_ylabel("query frame") + fig.colorbar(artist, ax=axes, label="raw head-averaged attention weight") + fig.suptitle("last-layer, head-averaged temporal attention; not calibrated probability") + fig.savefig(sample_dir / "temporal_attention_raw_shared_scale.png", dpi=160) + plt.close(fig) + + video_path = sample_dir / "clip_mesh_overlay.mp4" + writer = cv2.VideoWriter(str(video_path), cv2.VideoWriter_fourcc(*"mp4v"), 4.0, (width, height)) + for clip_time in range(valid_times): + clip_image = rgb_from_batch(batch, clip_time) + clip_K = batch["K"][0, clip_time].float().cpu().numpy() + clip_valid = batch["mano_annotation_valid"][0, clip_time].bool().cpu().numpy() + pred_layers = [ + MeshLayer(prediction["vertices_camera"][0, clip_time, hand].float().cpu().numpy(), faces[hand], PREDICTED_COLORS[hand], 0.58) + for hand in range(2) + ] + gt_layers = [ + MeshLayer(target_vertices[0, clip_time, hand].float().cpu().numpy(), faces[hand], TARGET_COLORS[hand], 0.50) + for hand in range(2) if clip_valid[hand] + ] + rendered = render_mesh_layers(clip_image, project_mesh_layers(gt_layers + pred_layers, clip_K)) + rendered = add_label(rendered, ( + f"{selection['subject']}/{selection['sequence']} frame={int(batch['frame_id'][0, clip_time])}", + f"L/R valid={int(clip_valid[0])}/{int(clip_valid[1])} config={config['name']} input={modalities}", + )) + writer.write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + writer.release() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + parser.add_argument("--clip-indices-manifest", type=Path) + parser.add_argument("--num-workers", type=int, default=0) + parser.add_argument("--seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--skip-visualizations", action="store_true") + parser.add_argument( + "--phase4-diagnostics", + action="store_true", + help=( + "Add signed translation, action, asymmetry, local-depth, group, " + "CVaR, and long-failure diagnostics without changing model inference." + ), + ) + parser.add_argument( + "--drop-depth", action="store_true", + help="Mark metric depth unavailable at inference while retaining the RGB-D-K checkpoint.", + ) + parser.add_argument( + "--drop-k", action="store_true", + help="Mark intrinsics/ray conditioning unavailable at inference while retaining the RGB-D-K checkpoint.", + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + max_clips=args.max_clips, + oracle_crop_enabled=( + config["model"].get("oracle_crop_mode", "none") != "none" + ), + ) + subset_record = None + evaluation_dataset = dataset + if args.clip_indices_manifest is not None: + if args.max_clips is not None: + parser.error("--max-clips and --clip-indices-manifest are mutually exclusive") + if not args.skip_visualizations: + parser.error("clip-index subset evaluation requires --skip-visualizations") + indices, subset_record = load_clip_indices_manifest( + args.clip_indices_manifest, + source_manifest=args.manifest, + data_config=data_config, + dataset_length=len(dataset), + ) + evaluation_dataset = Subset(dataset, indices) + loader = DataLoader( + evaluation_dataset, batch_size=1, shuffle=False, num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + values: dict[str, list[float]] = defaultdict(list) + per_joint: dict[str, list[float]] = defaultdict(list) + attention_values: dict[str, list[float]] = defaultdict(list) + temporal_by_distance: dict[int, list[float]] = defaultdict(list) + temporal_by_signed_distance: dict[int, list[float]] = defaultdict(list) + frame_rows: list[dict[str, object]] = [] + temporal_rows: list[dict[str, object]] = [] + oracle_refinement_values: dict[str, list[float]] = defaultdict(list) + selection_records: list[dict[str, object]] = [] + frame_count = 0 + + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = move_to_device(batch_cpu, device) + target_vertices, _ = attach_gt_geometry(batch, model) + if args.drop_depth: + batch["depth_input_available"] = torch.zeros_like(batch["frame_valid"], dtype=torch.bool) + batch["depth_available"] = batch["depth_input_available"] + if args.drop_k: + batch["K_input_available"] = torch.zeros_like(batch["frame_valid"], dtype=torch.bool) + batch["K_available"] = batch["K_input_available"] + prediction = run_model(model, batch, dtype) + frame_valid = batch["frame_valid"].bool() + if "mixed_projection_success" in prediction: + mixed_valid = frame_valid[..., None].expand_as( + prediction["mixed_projection_success"], + ) + mixed_diagnostics = { + "mixed_projection_success_fraction": prediction[ + "mixed_projection_success" + ].float(), + "mixed_projection_support_count": prediction[ + "mixed_projection_support_count" + ].float(), + "mixed_projection_conditioning": prediction[ + "mixed_projection_conditioning" + ].float(), + "mixed_projection_inlier_ratio": prediction[ + "mixed_projection_inlier_ratio" + ].float(), + "mixed_projection_residual_scale_px": prediction[ + "mixed_projection_residual_scale_px" + ].float(), + } + for key, diagnostic in mixed_diagnostics.items(): + values[key].extend(diagnostic[mixed_valid].cpu().tolist()) + joint_annotation = batch["joint_annotation_valid"].bool() & frame_valid[..., None] + mano_annotation = batch["mano_annotation_valid"].bool() & frame_valid[..., None] + joint_valid = batch["joint_element_valid"].bool() & joint_annotation[..., None] + frame_count += int(frame_valid.sum()) + + target_joints = torch.nan_to_num(batch["joint3d_camera"]) + predicted_joints = prediction["joints_camera"].float() + absolute_joint_error = torch.linalg.vector_norm(predicted_joints - target_joints, dim=-1) * 1000.0 + predicted_relative = predicted_joints - predicted_joints[..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + relative_joint_error = torch.linalg.vector_norm(predicted_relative - target_relative, dim=-1) * 1000.0 + translation_signed_error = ( + prediction["wrist_root_translation"].float() + - torch.nan_to_num(batch["wrist_root_translation"]) + ) * 1000.0 + translation_error = translation_signed_error.abs() + + oracle_refinement = "coarse_joints_camera" in prediction + if oracle_refinement: + coarse_joints = prediction["coarse_joints_camera"].float() + coarse_absolute_joint_error = torch.linalg.vector_norm( + coarse_joints - target_joints, dim=-1, + ) * 1000.0 + coarse_relative = coarse_joints - coarse_joints[..., :1, :] + coarse_relative_joint_error = torch.linalg.vector_norm( + coarse_relative - target_relative, dim=-1, + ) * 1000.0 + coarse_translation_error = ( + prediction["coarse_wrist_root_translation"].float() + - torch.nan_to_num(batch["wrist_root_translation"]) + ).abs() * 1000.0 + rotation_delta_degrees = torch.linalg.vector_norm( + prediction["oracle_crop_rotation_delta_axis_angle"].float(), + dim=-1, + ).mean(dim=-1) * (180.0 / np.pi) + shape_delta_l2 = torch.linalg.vector_norm( + prediction["oracle_crop_shape_delta"].float(), dim=-1, + ) + delta_z_mm = prediction["oracle_crop_delta_z"].float().squeeze(-1) * 1000.0 + + vertex_error = torch.linalg.vector_norm(prediction["vertices_camera"].float() - target_vertices, dim=-1) * 1000.0 + predicted_vertex_relative = prediction["vertices_camera"].float() - prediction["wrist_root_translation"].float()[..., None, :] + target_vertex_relative = target_vertices - torch.nan_to_num(batch["wrist_root_translation"])[..., None, :] + relative_vertex_error = torch.linalg.vector_norm(predicted_vertex_relative - target_vertex_relative, dim=-1) * 1000.0 + if oracle_refinement: + coarse_vertices = prediction["coarse_vertices_camera"].float() + coarse_vertex_error = torch.linalg.vector_norm( + coarse_vertices - target_vertices, dim=-1, + ) * 1000.0 + coarse_vertex_relative = ( + coarse_vertices + - prediction["coarse_wrist_root_translation"].float()[..., None, :] + ) + coarse_relative_vertex_error = torch.linalg.vector_norm( + coarse_vertex_relative - target_vertex_relative, dim=-1, + ) * 1000.0 + + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor((width, height), device=device) + legacy_direct_2d = prediction["joint2d_norm"] * torch.tensor((width, height), device=device) + mano_2d, mano_positive = project_points(predicted_joints, batch["K"].float()) + target_2d = torch.nan_to_num(batch["joint2d"]) + direct_2d_error = torch.linalg.vector_norm(direct_2d - target_2d, dim=-1) + legacy_direct_2d_error = torch.linalg.vector_norm(legacy_direct_2d - target_2d, dim=-1) + mano_2d_error = torch.linalg.vector_norm(mano_2d - target_2d, dim=-1) + direct_mano_consistency = torch.linalg.vector_norm(direct_2d - mano_2d, dim=-1) + + for hand, side in enumerate(SIDES): + mask = joint_valid[..., hand, :] + hand_mask = mano_annotation[..., hand] + values[f"{side}_absolute_mpjpe_mm"].extend( + absolute_joint_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_root_relative_mpjpe_mm"].extend( + relative_joint_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_direct_2d_error_px"].extend( + direct_2d_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_legacy_bf16_direct_2d_error_px"].extend( + legacy_direct_2d_error[..., hand, :][mask].float().cpu().tolist() + ) + projected_mask = mask & mano_positive[..., hand, :] + values[f"{side}_mano_projected_2d_error_px"].extend( + mano_2d_error[..., hand, :][projected_mask].cpu().tolist() + ) + values[f"{side}_direct_mano_2d_consistency_px"].extend( + direct_mano_consistency[..., hand, :][projected_mask].cpu().tolist() + ) + values[f"{side}_absolute_mpvpe_mm"].extend(vertex_error[..., hand, :].mean(-1)[hand_mask].cpu().tolist()) + values[f"{side}_root_relative_mpvpe_mm"].extend(relative_vertex_error[..., hand, :].mean(-1)[hand_mask].cpu().tolist()) + for axis_index, axis in enumerate("xyz"): + values[f"{side}_translation_{axis}_mae_mm"].extend(translation_error[..., hand, axis_index][joint_annotation[..., hand]].cpu().tolist()) + if args.phase4_diagnostics: + values[f"{side}_translation_{axis}_signed_error_mm"].extend( + translation_signed_error[..., hand, axis_index][ + joint_annotation[..., hand] + ].cpu().tolist() + ) + for joint_index in range(21): + joint_mask = mask[..., joint_index] + per_joint[f"{side}_{joint_index:02d}_absolute_mpjpe_mm"].extend( + absolute_joint_error[..., hand, joint_index][joint_mask].cpu().tolist() + ) + fingertip_mask = mask[..., list(FINGERTIP_INDICES)] + fingertip_count = fingertip_mask.sum(-1) + values[f"{side}_fingertip_mpjpe_mm"].extend( + ( + (absolute_joint_error[..., hand, list(FINGERTIP_INDICES)] * fingertip_mask).sum(-1) + / fingertip_count.clamp_min(1) + )[fingertip_count > 0].cpu().tolist() + ) + + if predicted_joints.shape[1] > 1: + pair_valid = joint_annotation[:, 1:] & joint_annotation[:, :-1] + predicted_wrist_velocity = prediction["wrist_root_translation"][:, 1:] - prediction["wrist_root_translation"][:, :-1] + target_wrist_velocity = torch.nan_to_num(batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1]) + wrist_velocity_error = torch.linalg.vector_norm(predicted_wrist_velocity - target_wrist_velocity, dim=-1) * 1000.0 + values["wrist_velocity_error_mm_per_frame"].extend(wrist_velocity_error[pair_valid].float().cpu().tolist()) + predicted_joint_velocity = predicted_joints[:, 1:] - predicted_joints[:, :-1] + target_joint_velocity = target_joints[:, 1:] - target_joints[:, :-1] + pair_joint_valid = joint_valid[:, 1:] & joint_valid[:, :-1] + joint_velocity_error = torch.linalg.vector_norm(predicted_joint_velocity - target_joint_velocity, dim=-1) * 1000.0 + values["joint_velocity_error_mm_per_frame"].extend(joint_velocity_error[pair_joint_valid].cpu().tolist()) + acceleration_valid = None + acceleration_error = None + if predicted_wrist_velocity.shape[1] > 1: + acceleration_valid = pair_valid[:, 1:] & pair_valid[:, :-1] + predicted_acceleration = predicted_wrist_velocity[:, 1:] - predicted_wrist_velocity[:, :-1] + target_acceleration = target_wrist_velocity[:, 1:] - target_wrist_velocity[:, :-1] + acceleration_error = torch.linalg.vector_norm(predicted_acceleration - target_acceleration, dim=-1) * 1000.0 + values["wrist_acceleration_error_mm_per_frame2"].extend(acceleration_error[acceleration_valid].float().cpu().tolist()) + + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + for transition_index in range(pair_valid.shape[1]): + for hand, side in enumerate(SIDES): + if not bool(pair_valid[0, transition_index, hand]): + continue + valid_joint_mask = pair_joint_valid[0, transition_index, hand] + joint_value = ( + float(joint_velocity_error[0, transition_index, hand][valid_joint_mask].mean()) + if bool(valid_joint_mask.any()) else None + ) + acceleration_value = None + if ( + transition_index > 0 + and acceleration_valid is not None + and bool(acceleration_valid[0, transition_index - 1, hand]) + ): + acceleration_value = float(acceleration_error[0, transition_index - 1, hand]) + temporal_rows.append({ + "clip_index": clip_index, + "transition_index": transition_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id_from": int(batch["frame_id"][0, transition_index]), + "frame_id_to": int(batch["frame_id"][0, transition_index + 1]), + "side": side, + "wrist_velocity_error_mm_per_frame": float(wrist_velocity_error[0, transition_index, hand]), + "joint_velocity_error_mm_per_frame": joint_value, + "wrist_acceleration_error_mm_per_frame2": acceleration_value, + "identity_switch_fraction": None, + }) + + wrong_sequence: list[bool | None] = [] + valid_length = int(frame_valid[0].sum()) + for time_index in range(valid_length): + annotation_state = "".join(str(int(value)) for value in joint_annotation[0, time_index].int().cpu().tolist()) + both_valid = bool(joint_annotation[0, time_index].all()) + wrong_side = None + if both_valid: + correct = 0.5 * ( + absolute_joint_error[0, time_index, 0].mean() + + absolute_joint_error[0, time_index, 1].mean() + ) + swapped = 0.5 * ( + torch.linalg.vector_norm(predicted_joints[0, time_index, 0] - target_joints[0, time_index, 1], dim=-1).mean() + + torch.linalg.vector_norm(predicted_joints[0, time_index, 1] - target_joints[0, time_index, 0], dim=-1).mean() + ) * 1000.0 + wrong_side = bool(swapped < correct) + values["wrong_side_preference"].append(float(wrong_side)) + wrong_sequence.append(wrong_side) + valid_hand_errors = [ + float(absolute_joint_error[0, time_index, hand].mean()) + for hand in range(2) if joint_annotation[0, time_index, hand] + ] + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + frame_id = int(batch["frame_id"][0, time_index]) + sizes: list[float | None] = [None, None] + depths: list[float | None] = [None, None] + for hand in range(2): + is_valid = bool(joint_annotation[0, time_index, hand]) + if is_valid: + extent = batch["joint2d"][0, time_index, hand].max(0).values - batch["joint2d"][0, time_index, hand].min(0).values + sizes[hand] = float(extent.max()) + depths[hand] = float(batch["wrist_root_translation"][0, time_index, hand, 2]) + valid_sizes = [value for value in sizes if value is not None] + valid_depths = [value for value in depths if value is not None] + asymmetry = bimanual_asymmetry(sizes, depths) + if args.phase4_diagnostics: + action_label = load_action_label(args.root, take, frame_id) + action = action_name(action_label) + action_family = str(batch["sequence_id"][0]).split("/", 1)[0] + depth_np = batch["depth_m"][0, time_index, 0].float().cpu().numpy() + depth_valid_np = ( + batch["depth_pixel_valid"][0, time_index, 0].bool().cpu().numpy() + ) + else: + action_label = None + action = None + action_family = None + depth_np = None + depth_valid_np = None + for hand in range(2): + is_valid = bool(joint_annotation[0, time_index, hand]) + size = sizes[hand] + depth = depths[hand] + local_depth: dict[str, float | int | None] = {} + if args.phase4_diagnostics and is_valid: + local_depth = local_depth_statistics( + depth_np, + depth_valid_np, + batch["joint2d"][0, time_index, hand].float().cpu().numpy(), + ) + local_median = local_depth.get("depth_median_m") + local_surface_minus_wrist = ( + float(local_median) - float(depth) + if local_median is not None and depth is not None + else None + ) + row = { + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "side": SIDES[hand], + "annotation_valid": int(is_valid), + "annotation_state": annotation_state, + "hand_size_px": size, + "hand_size_bucket": hand_size_bucket(size), + "wrist_depth_m": depth, + "depth_bucket": wrist_depth_bucket(depth), + "absolute_mpjpe_mm": float(absolute_joint_error[0, time_index, hand].mean()) if is_valid else None, + "root_relative_mpjpe_mm": float(relative_joint_error[0, time_index, hand].mean()) if is_valid else None, + "absolute_mpvpe_mm": float(vertex_error[0, time_index, hand].mean()) if bool(mano_annotation[0, time_index, hand]) else None, + "root_relative_mpvpe_mm": float(relative_vertex_error[0, time_index, hand].mean()) if bool(mano_annotation[0, time_index, hand]) else None, + "direct_2d_error_px": float(direct_2d_error[0, time_index, hand].mean()) if is_valid else None, + "legacy_bf16_direct_2d_error_px": float(legacy_direct_2d_error[0, time_index, hand].mean()) if is_valid else None, + "mano_projected_2d_error_px": float(mano_2d_error[0, time_index, hand].mean()) if is_valid else None, + "direct_mano_2d_consistency_px": float(direct_mano_consistency[0, time_index, hand].mean()) if is_valid else None, + "fingertip_mpjpe_mm": float(absolute_joint_error[0, time_index, hand, list(FINGERTIP_INDICES)].mean()) if is_valid else None, + "translation_x_mae_mm": float(translation_error[0, time_index, hand, 0]) if is_valid else None, + "translation_y_mae_mm": float(translation_error[0, time_index, hand, 1]) if is_valid else None, + "translation_z_mae_mm": float(translation_error[0, time_index, hand, 2]) if is_valid else None, + "wrong_side_preference": int(wrong_side) if wrong_side is not None else None, + } + if args.phase4_diagnostics: + predicted_translation = prediction["wrist_root_translation"][ + 0, time_index, hand + ].float() + target_translation = batch["wrist_root_translation"][ + 0, time_index, hand + ].float() + row.update({ + "action_family": action_family, + "action_label": action_label, + "action_name": action, + **asymmetry, + "local_depth_valid_fraction": local_depth.get("valid_fraction"), + "local_depth_validity_bucket": depth_validity_bucket( + local_depth.get("valid_fraction") + ), + "local_depth_median_m": local_median, + "local_depth_q10_m": local_depth.get("depth_q10_m"), + "local_depth_q90_m": local_depth.get("depth_q90_m"), + "local_depth_iqr_m": local_depth.get("depth_iqr_m"), + "local_depth_discontinuity_m": local_depth.get( + "depth_discontinuity_m" + ), + "local_surface_minus_wrist_z_m": local_surface_minus_wrist, + "predicted_wrist_x_m": ( + float(predicted_translation[0]) if is_valid else None + ), + "predicted_wrist_y_m": ( + float(predicted_translation[1]) if is_valid else None + ), + "predicted_wrist_z_m": ( + float(predicted_translation[2]) if is_valid else None + ), + "target_wrist_x_m": float(target_translation[0]) if is_valid else None, + "target_wrist_y_m": float(target_translation[1]) if is_valid else None, + "target_wrist_z_m": float(target_translation[2]) if is_valid else None, + "translation_x_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 0]) + if is_valid else None + ), + "translation_y_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 1]) + if is_valid else None + ), + "translation_z_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 2]) + if is_valid else None + ), + }) + if oracle_refinement: + mano_is_valid = bool(mano_annotation[0, time_index, hand]) + oracle_fields = { + "coarse_absolute_mpjpe_mm": ( + float(coarse_absolute_joint_error[0, time_index, hand].mean()) + if is_valid else None + ), + "coarse_root_relative_mpjpe_mm": ( + float(coarse_relative_joint_error[0, time_index, hand].mean()) + if is_valid else None + ), + "coarse_absolute_mpvpe_mm": ( + float(coarse_vertex_error[0, time_index, hand].mean()) + if mano_is_valid else None + ), + "coarse_root_relative_mpvpe_mm": ( + float(coarse_relative_vertex_error[0, time_index, hand].mean()) + if mano_is_valid else None + ), + "coarse_fingertip_mpjpe_mm": ( + float(coarse_absolute_joint_error[ + 0, time_index, hand, list(FINGERTIP_INDICES) + ].mean()) + if is_valid else None + ), + "coarse_translation_z_mae_mm": ( + float(coarse_translation_error[0, time_index, hand, 2]) + if is_valid else None + ), + "oracle_crop_delta_z_mm": ( + float(delta_z_mm[0, time_index, hand]) + if is_valid else None + ), + "oracle_crop_rotation_delta_geodesic_deg": ( + float(rotation_delta_degrees[0, time_index, hand]) + if is_valid else None + ), + "oracle_crop_shape_delta_l2": ( + float(shape_delta_l2[0, hand]) if is_valid else None + ), + "oracle_crop_rgb_available": int( + prediction["oracle_crop_rgb_available"][0, time_index, hand] + ), + "oracle_crop_depth_available": int( + prediction["oracle_crop_depth_available_effective"][ + 0, time_index, hand + ] + ), + } + row.update(oracle_fields) + if is_valid: + for key, value in oracle_fields.items(): + if key.startswith("oracle_crop_") and value is not None: + oracle_refinement_values[key].append(float(value)) + frame_rows.append(row) + selection_records.append({ + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "annotation_state": annotation_state, + "hand_size_bucket": hand_size_bucket(float(np.mean(valid_sizes))) if valid_sizes else None, + "depth_bucket": wrist_depth_bucket(float(np.mean(valid_depths))) if valid_depths else None, + "absolute_mpjpe_mm": float(np.mean(valid_hand_errors)) if valid_hand_errors else None, + }) + for transition_index, (previous, current) in enumerate( + zip(wrong_sequence[:-1], wrong_sequence[1:], strict=True) + ): + if previous is not None and current is not None: + identity_switch = float(previous != current) + values["identity_switch_fraction"].append(identity_switch) + temporal_rows.append({ + "clip_index": clip_index, + "transition_index": transition_index, + "take": f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4", + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id_from": int(batch["frame_id"][0, transition_index]), + "frame_id_to": int(batch["frame_id"][0, transition_index + 1]), + "side": "bimanual", + "wrist_velocity_error_mm_per_frame": None, + "joint_velocity_error_mm_per_frame": None, + "wrist_acceleration_error_mm_per_frame2": None, + "identity_switch_fraction": identity_switch, + }) + + attention = prediction["attention"] + rgb = attention["rgb_cross_attention"][:, -1] + left, right = rgb[..., 0, :], rgb[..., 1, :] + attention_values["rgb_same_peak"].extend((left.argmax(-1) == right.argmax(-1))[frame_valid].float().cpu().tolist()) + attention_values["rgb_left_right_cosine"].extend(torch.nn.functional.cosine_similarity(left, right, dim=-1)[frame_valid].float().cpu().tolist()) + attention_values["rgb_update_norm"].extend(attention["rgb_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + for key in ("depth_fusion_gate", "depth_fusion_gate_raw", "depth_update_norm", "gated_depth_update_norm"): + if key in attention: + attention_values[key].extend(attention[key][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + if "temporal_update_norm" in attention: + attention_values["temporal_update_norm"].extend( + attention["temporal_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist() + ) + if "temporal_attention" in attention: + temporal = attention["temporal_attention"][:, -1] + for hand in range(2): + valid_indices = torch.where(frame_valid[0])[0] + for query_index in valid_indices: + weights = temporal[0, hand, query_index, valid_indices].float() + normalized = weights / weights.sum().clamp_min(1e-8) + if normalized.numel() > 1: + entropy = -(normalized * normalized.clamp_min(1e-8).log()).sum() / np.log(normalized.numel()) + attention_values["temporal_normalized_entropy"].append(float(entropy)) + attention_values["temporal_diagonal"].append(float(temporal[0, hand, query_index, query_index])) + for key_index, key_frame in enumerate(valid_indices): + signed_distance = int(key_frame) - int(query_index) + temporal_by_distance[abs(signed_distance)].append(float(weights[key_index])) + temporal_by_signed_distance[signed_distance].append(float(weights[key_index])) + + selections = select_visualization_frames(selection_records, seed=args.seed) + strata_counts = { + field: { + str(value): sum(record.get(field) == value for record in selection_records) + for value in values_to_count + } + for field, values_to_count in ( + ("hand_size_bucket", ("small", "medium", "large")), + ("depth_bucket", ("near", "middle", "far")), + ("annotation_state", ("00", "01", "10", "11")), + ) + } + selection_manifest = { + "seed": args.seed, + "source_manifest": str(args.manifest.resolve()), + "clip_indices_manifest": ( + { + "path": str(args.clip_indices_manifest.resolve()), + "sha256": sha256(args.clip_indices_manifest), + "version": subset_record.get("version"), + "count": subset_record.get("count"), + } + if args.clip_indices_manifest is not None else None + ), + "checkpoint": str(args.checkpoint.resolve()), + "selection_policy": "random4 + error P50/P90/P95/worst + size/depth/valid-state medians", + "strata_counts": strata_counts, + "unavailable_requested_strata": [ + f"{field}={value}" + for field, counts in strata_counts.items() + for value, count in counts.items() if count == 0 + ], + "samples": selections, + } + (args.output_dir / "selection_manifest.json").write_text(json.dumps(selection_manifest, indent=2) + "\n", encoding="utf-8") + write_csv(args.output_dir / "per_hand_frame_metrics.csv", frame_rows) + write_csv(args.output_dir / "per_temporal_transition_metrics.csv", temporal_rows) + phase4_group_rows: list[dict[str, object]] = [] + phase4_failure_rows: list[dict[str, object]] = [] + if args.phase4_diagnostics: + phase4_metrics = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + ) + if oracle_refinement_values: + phase4_metrics += ( + "coarse_absolute_mpjpe_mm", + "coarse_root_relative_mpjpe_mm", + "coarse_absolute_mpvpe_mm", + "coarse_root_relative_mpvpe_mm", + "coarse_fingertip_mpjpe_mm", + "coarse_translation_z_mae_mm", + "oracle_crop_delta_z_mm", + "oracle_crop_rotation_delta_geodesic_deg", + "oracle_crop_shape_delta_l2", + ) + phase4_group_rows = summarize_group_metrics( + frame_rows, + phase4_metrics, + ( + "take", + "action_family", + "action_label", + "action_name", + "hand_size_bucket", + "depth_bucket", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", + ), + ) + phase4_failure_rows = find_failure_intervals( + frame_rows, + metric="translation_z_mae_mm", + threshold=40.0, + minimum_frames=3, + ) + find_failure_intervals( + frame_rows, + metric="absolute_mpjpe_mm", + threshold=50.0, + minimum_frames=3, + ) + write_csv(args.output_dir / "phase4_group_metrics.csv", phase4_group_rows) + write_csv(args.output_dir / "phase4_failure_intervals.csv", phase4_failure_rows) + + joint_rows = [] + for name, metric_values in sorted(per_joint.items()): + side, joint_index, _ = name.split("_", 2) + joint_rows.append({"side": side, "joint_index": int(joint_index), **distribution_summary(metric_values)}) + write_csv(args.output_dir / "per_joint_metrics.csv", joint_rows) + + bootstrap_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", "direct_2d_error_px", "mano_projected_2d_error_px", + "translation_z_mae_mm", "fingertip_mpjpe_mm", "wrong_side_preference", + ) + bootstrap_rows = bootstrap_take_means( + frame_rows, bootstrap_metrics, seed=args.seed, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "bootstrap_ci.csv", bootstrap_rows) + temporal_bootstrap_metrics = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", + ) + temporal_bootstrap_rows = bootstrap_take_means( + temporal_rows, temporal_bootstrap_metrics, + seed=args.seed, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "temporal_bootstrap_ci.csv", temporal_bootstrap_rows) + + distribution_metrics = {key: distribution_summary(metric_values) for key, metric_values in sorted(values.items())} + combined_keys = { + "absolute_mpjpe_mm": ("left_absolute_mpjpe_mm", "right_absolute_mpjpe_mm"), + "root_relative_mpjpe_mm": ("left_root_relative_mpjpe_mm", "right_root_relative_mpjpe_mm"), + "absolute_mpvpe_mm": ("left_absolute_mpvpe_mm", "right_absolute_mpvpe_mm"), + "root_relative_mpvpe_mm": ("left_root_relative_mpvpe_mm", "right_root_relative_mpvpe_mm"), + "direct_2d_error_px": ("left_direct_2d_error_px", "right_direct_2d_error_px"), + "legacy_bf16_direct_2d_error_px": ("left_legacy_bf16_direct_2d_error_px", "right_legacy_bf16_direct_2d_error_px"), + "mano_projected_2d_error_px": ("left_mano_projected_2d_error_px", "right_mano_projected_2d_error_px"), + "direct_mano_2d_consistency_px": ("left_direct_mano_2d_consistency_px", "right_direct_mano_2d_consistency_px"), + "fingertip_mpjpe_mm": ("left_fingertip_mpjpe_mm", "right_fingertip_mpjpe_mm"), + "translation_z_mae_mm": ("left_translation_z_mae_mm", "right_translation_z_mae_mm"), + } + for combined, components in combined_keys.items(): + distribution_metrics[combined] = distribution_summary(values[components[0]] + values[components[1]]) + + attention_report = { + key: distribution_summary(metric_values) for key, metric_values in sorted(attention_values.items()) + } + attention_report["temporal_attention_by_absolute_frame_distance"] = { + str(distance): distribution_summary(metric_values) + for distance, metric_values in sorted(temporal_by_distance.items()) + } + attention_report["temporal_attention_by_signed_frame_distance"] = { + str(distance): distribution_summary(metric_values) + for distance, metric_values in sorted(temporal_by_signed_distance.items()) + } + (args.output_dir / "attention_diagnostics.json").write_text(json.dumps(attention_report, indent=2) + "\n", encoding="utf-8") + position_bias_report = temporal_position_bias_report(model) + (args.output_dir / "temporal_position_bias.json").write_text( + json.dumps(position_bias_report, indent=2) + "\n", encoding="utf-8", + ) + + report = { + "status": "evaluated", + "split_role": "official_validation" if "val" in args.manifest.name else "non_test_evaluation", + "official_test_used": False, + "config": config, + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": sha256(args.checkpoint), + "step": int(checkpoint_state["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "inference_modality_override": { + "drop_depth": bool(args.drop_depth), + "drop_k": bool(args.drop_k), + "availability_contract": "input_and_legacy_flags_v2", + }, + "clips": len(evaluation_dataset), + "clip_indices_manifest": ( + { + "path": str(args.clip_indices_manifest.resolve()), + "sha256": sha256(args.clip_indices_manifest), + "version": subset_record.get("version"), + "count": subset_record.get("count"), + } + if args.clip_indices_manifest is not None else None + ), + "frames": frame_count, + "data_loader_workers": args.num_workers, + "metrics": distribution_metrics, + "attention": attention_report, + "temporal_position_bias": position_bias_report, + "bootstrap": bootstrap_rows, + "temporal_bootstrap": temporal_bootstrap_rows, + "phase4_diagnostics": { + "enabled": bool(args.phase4_diagnostics), + "group_rows": len(phase4_group_rows), + "failure_intervals": len(phase4_failure_rows), + "local_depth_contract": ( + "GT-joint region on aligned resized metric depth; surface statistics are " + "diagnostic and are not wrist-depth targets" + if args.phase4_diagnostics else None + ), + "failure_thresholds": ( + {"translation_z_mae_mm": 40.0, "absolute_mpjpe_mm": 50.0} + if args.phase4_diagnostics else None + ), + }, + "oracle_crop_refinement": { + "enabled": bool(oracle_refinement_values), + "gt_location_at_inference": bool(oracle_refinement_values), + "coarse_checkpoint_sha256": config.get("experiment", {}).get( + "coarse_checkpoint_sha256" + ), + "metrics": { + key: distribution_summary(metric_values) + for key, metric_values in sorted(oracle_refinement_values.items()) + }, + }, + "metric_definitions": { + "absolute_mpjpe_mm": "valid-joint-weighted Euclidean camera-space joint error", + "direct_2d_error_px": "valid-joint-weighted direct-head pixel error; frame means are used for take bootstrap", + "legacy_bf16_direct_2d_error_px": "Phase 2 compatibility metric that scales bf16 normalized coordinates before float conversion", + "absolute_mpvpe_mm": "mean Euclidean camera-space vertex error; MVE/MPVPE", + "root_relative_mpvpe_mm": "vertex error after subtracting each wrist/root", + "wrong_side_preference": "swapped L/R joint assignment has lower combined cost than semantic assignment", + "identity_switch_fraction": "adjacent both-valid frames change wrong-side assignment preference", + "translation_axis_signed_error_mm": "predicted camera-space wrist axis minus GT wrist axis", + "cvar95": "mean of observations at or above the empirical 95th percentile", + "attention": "last-layer, PyTorch head-averaged attention weights; not calibrated probability", + }, + "presence_note": "H2O annotation validity is not presence; no presence metric is reported.", + "device": torch.cuda.get_device_name(device), + "trainable_parameters": sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad), + "frozen_parameters": sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad), + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + + if not args.skip_visualizations: + visualize_selections( + selections, dataset, model, device, dtype, config, + args.output_dir / "visualization_audit", + ) + print(json.dumps({ + "status": report["status"], "clips": report["clips"], "frames": report["frames"], + "absolute_mpjpe_mm": distribution_metrics["absolute_mpjpe_mm"]["mean"], + "absolute_mpvpe_mm": distribution_metrics["absolute_mpvpe_mm"]["mean"], + "output_dir": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase4_jitter.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase4_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..01ef42bd758f0d15f63365ddcabec5115ffd2f99 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase4_jitter.py @@ -0,0 +1,767 @@ +#!/usr/bin/env python3 +"""Evaluate preregistered inference-only temporal filters from raw caches.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +import numpy as np +import torch + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.temporal_filter import ( + apply_by_segment, + butterworth_zero_phase, + derivative_norms, + ema, + ema_low_frequency_delay_frames, + filter_rotation_matrices, + high_frequency_energy_ratio, + rotation_geodesic_degrees, + valid_segments, +) +from foundation_hand.models.mano import ManoCameraLayer + + +FPS = 30.0 +FINGERTIPS = (4, 8, 12, 16, 20) + + +@dataclass(frozen=True) +class FilterCondition: + name: str + family: str + value: float | None + causal_status: str + latency_frames: float | None + + +def condition_grid() -> dict[str, FilterCondition]: + conditions = { + "F0_raw": FilterCondition("F0_raw", "F0", None, "raw", 0.0), + } + for alpha in (0.2, 0.4, 0.6): + name = f"F1_ema_alpha{alpha:g}" + conditions[name] = FilterCondition( + name, "F1", alpha, "causal", ema_low_frequency_delay_frames(alpha), + ) + for cutoff in (2.0, 4.0, 6.0): + name = f"F2_butterworth_{cutoff:g}hz" + conditions[name] = FilterCondition( + name, "F2", cutoff, "offline_zero_phase", None, + ) + return conditions + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty jitter report: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_take(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + if float(arrays["fps"]) != FPS: + raise ValueError(f"jitter cache fps mismatch: {path}") + return arrays + + +def filtered_parameters( + arrays: dict[str, np.ndarray], condition: FilterCondition, +) -> tuple[np.ndarray, np.ndarray, int]: + translation = arrays["pred_wrist_translation"].astype(np.float32) + rotations = arrays["pred_rotation_matrices"].astype(np.float32) + if condition.family == "F0": + return translation.copy(), rotations.copy(), 0 + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + if condition.family == "F1": + assert condition.value is not None + translation, fallback_translation = apply_by_segment( + translation, segments, + lambda values: ema(values, condition.value), minimum_frames=1, + ) + rotations, fallback_rotation = apply_by_segment( + rotations, segments, + lambda values: filter_rotation_matrices( + values, lambda quaternion: ema(quaternion, condition.value), + ), + minimum_frames=1, + ) + elif condition.family == "F2": + assert condition.value is not None + operation = lambda values: butterworth_zero_phase( + values, condition.value, FPS, order=2, + ) + translation, fallback_translation = apply_by_segment( + translation, segments, operation, minimum_frames=4, + ) + rotations, fallback_rotation = apply_by_segment( + rotations, segments, + lambda values: filter_rotation_matrices(values, operation), + minimum_frames=4, + ) + else: + raise ValueError(f"unsupported filter family: {condition.family}") + if fallback_translation != fallback_rotation: + raise AssertionError("translation/rotation filter fallback counts differ") + return translation, rotations, fallback_translation + + +def rebuild_geometry( + rotations: np.ndarray, + shape: np.ndarray, + translation: np.ndarray, + mano: ManoCameraLayer, + device: torch.device, + chunk_size: int = 256, +) -> tuple[np.ndarray, np.ndarray]: + vertices = [] + joints = [] + for start in range(0, len(rotations), chunk_size): + stop = min(start + chunk_size, len(rotations)) + with torch.inference_mode(): + chunk_vertices, chunk_joints = mano( + torch.from_numpy(rotations[start:stop]).to(device), + torch.from_numpy(shape[start:stop]).to(device), + torch.from_numpy(translation[start:stop]).to(device), + ) + vertices.append(chunk_vertices.cpu().numpy()) + joints.append(chunk_joints.cpu().numpy()) + return np.concatenate(vertices), np.concatenate(joints) + + +def project_points(points: np.ndarray, intrinsics: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + z = points[..., 2] + positive = np.isfinite(points).all(axis=-1) & (z > 1e-8) + safe_z = np.where(positive, z, 1.0) + x = intrinsics[:, None, None, 0, 0] * points[..., 0] / safe_z + x += intrinsics[:, None, None, 0, 2] + y = intrinsics[:, None, None, 1, 1] * points[..., 1] / safe_z + y += intrinsics[:, None, None, 1, 2] + projected = np.stack((x, y), axis=-1) + projected[~positive] = np.nan + return projected, positive + + +def append_finite(output: dict[str, list[float]], key: str, values: Iterable[float]) -> None: + output[key].extend(float(value) for value in values if np.isfinite(value)) + + +def per_frame_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + vertices: np.ndarray, + rotations: np.ndarray, + translation: np.ndarray, + frame_selected: np.ndarray, +) -> tuple[dict[str, list[float]], np.ndarray, np.ndarray]: + output: dict[str, list[float]] = defaultdict(list) + target_joints = arrays["target_joints_camera"] + target_vertices = arrays["target_vertices_camera"] + target_translation = arrays["target_wrist_translation"] + joint_valid = arrays["joint_element_valid"].astype(bool) + joint_valid &= frame_selected[:, None, None] + mano_valid = arrays["mano_annotation_valid"].astype(bool) + mano_valid &= frame_selected[:, None] + + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + joint_relative = joints - joints[..., :1, :] + target_joint_relative = target_joints - target_joints[..., :1, :] + root_joint_error = np.linalg.norm( + joint_relative - target_joint_relative, axis=-1, + ) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + vertex_relative = vertices - translation[..., None, :] + target_vertex_relative = target_vertices - target_translation[..., None, :] + root_vertex_error = np.linalg.norm( + vertex_relative - target_vertex_relative, axis=-1, + ) * 1000.0 + translation_signed = (translation - target_translation) * 1000.0 + + projected, projected_positive = project_points(joints, arrays["K"]) + projected_valid = joint_valid & projected_positive + target_2d = arrays["target_2d_px"] + projected_error = np.linalg.norm(projected - target_2d, axis=-1) + consistency = np.linalg.norm(projected - arrays["pred_direct_2d_px"], axis=-1) + direct_error = np.linalg.norm(arrays["pred_direct_2d_px"] - target_2d, axis=-1) + rotation_error = rotation_geodesic_degrees( + rotations, arrays["target_rotation_matrices"], + ).mean(axis=-1) + + for time_index in range(len(joints)): + for hand in range(2): + valid_joints = joint_valid[time_index, hand] + if valid_joints.any(): + append_finite(output, "absolute_mpjpe_mm", [ + joint_error[time_index, hand, valid_joints].mean() + ]) + append_finite(output, "root_relative_mpjpe_mm", [ + root_joint_error[time_index, hand, valid_joints].mean() + ]) + fingertip_valid = valid_joints[list(FINGERTIPS)] + if fingertip_valid.any(): + fingertip_values = joint_error[ + time_index, hand, list(FINGERTIPS) + ][fingertip_valid] + append_finite(output, "fingertip_mpjpe_mm", [fingertip_values.mean()]) + append_finite(output, "direct_2d_error_px", [ + direct_error[time_index, hand, valid_joints].mean() + ]) + valid_projected = projected_valid[time_index, hand] + if valid_projected.any(): + append_finite(output, "projected_mano_2d_error_px", [ + projected_error[time_index, hand, valid_projected].mean() + ]) + append_finite(output, "direct_mano_consistency_px", [ + consistency[time_index, hand, valid_projected].mean() + ]) + for axis, name in enumerate("xyz"): + append_finite(output, f"translation_{name}_signed_error_mm", [ + translation_signed[time_index, hand, axis] + ]) + append_finite(output, f"translation_{name}_mae_mm", [ + abs(translation_signed[time_index, hand, axis]) + ]) + if mano_valid[time_index, hand]: + append_finite(output, "absolute_mpvpe_mm", [ + vertex_error[time_index, hand].mean() + ]) + append_finite(output, "root_relative_mpvpe_mm", [ + root_vertex_error[time_index, hand].mean() + ]) + append_finite(output, "rotation_geodesic_error_deg", [ + rotation_error[time_index, hand] + ]) + return output, projected, joint_valid + + +def selected_segments( + arrays: dict[str, np.ndarray], frame_selected: np.ndarray, +) -> list[np.ndarray]: + return valid_segments( + arrays["clip_index"], arrays["frame_id"], + arrays["frame_valid"].astype(bool) & frame_selected, + ) + + +def temporal_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + projected: np.ndarray, + frame_selected: np.ndarray, +) -> dict[str, list[float]]: + output: dict[str, list[float]] = defaultdict(list) + segments = selected_segments(arrays, frame_selected) + target = arrays["target_joints_camera"] + annotation = arrays["joint_element_valid"].astype(bool) + for indices in segments: + for hand in range(2): + predicted_hand = joints[indices, hand] + target_hand = target[indices, hand] + valid_hand = annotation[indices, hand] + for order, error_name in ( + (1, "joint_velocity_error_mm_per_s"), + (2, "joint_acceleration_error_mm_per_s2"), + ): + if len(indices) <= order: + continue + predicted_derivative = np.diff(predicted_hand, n=order, axis=0) * FPS**order + target_derivative = np.diff(target_hand, n=order, axis=0) * FPS**order + derivative_valid = np.stack([ + valid_hand[start : len(valid_hand) - order + start] + for start in range(order + 1) + ]).all(axis=0) + errors = np.linalg.norm( + predicted_derivative - target_derivative, axis=-1, + ) * 1000.0 + for row, valid in zip(errors, derivative_valid, strict=True): + if valid.any(): + append_finite(output, error_name, [row[valid].mean()]) + translation_hand = joints[indices, hand, 0] + target_translation_hand = arrays["target_wrist_translation"][indices, hand] + translation_valid = arrays["joint_annotation_valid"][indices, hand].astype(bool) + for order, error_name in ( + (1, "wrist_velocity_error_mm_per_s"), + (2, "wrist_acceleration_error_mm_per_s2"), + ): + if len(indices) <= order: + continue + predicted_derivative = np.diff( + translation_hand, n=order, axis=0, + ) * FPS**order + target_derivative = np.diff( + target_translation_hand, n=order, axis=0, + ) * FPS**order + derivative_valid = np.stack([ + translation_valid[start : len(translation_valid) - order + start] + for start in range(order + 1) + ]).all(axis=0) + errors = np.linalg.norm( + predicted_derivative - target_derivative, axis=-1, + ) * 1000.0 + append_finite(output, error_name, errors[derivative_valid]) + if len(indices) >= 3: + acceleration = derivative_norms(predicted_hand, FPS, 2) * 1000.0 + append_finite( + output, "predicted_3d_joint_acceleration_mm_per_s2", + acceleration.mean(axis=-1), + ) + projected_acceleration = derivative_norms( + projected[indices, hand], FPS, 2, + ) + append_finite( + output, "predicted_2d_joint_acceleration_px_per_s2", + np.nanmean(projected_acceleration, axis=-1), + ) + if len(indices) >= 4: + jerk = derivative_norms(predicted_hand, FPS, 3) * 1000.0 + append_finite( + output, "predicted_3d_joint_jerk_mm_per_s3", + jerk.mean(axis=-1), + ) + projected_jerk = derivative_norms(projected[indices, hand], FPS, 3) + append_finite( + output, "predicted_2d_joint_jerk_px_per_s3", + np.nanmean(projected_jerk, axis=-1), + ) + append_finite(output, "high_frequency_energy_ratio", [ + high_frequency_energy_ratio(predicted_hand, FPS, 6.0) + ]) + if len(indices) >= 3: + velocity = derivative_norms(predicted_hand, FPS, 1).mean(axis=-1) + append_finite(output, "velocity_variation_m_per_s", [ + np.std(velocity) + ]) + + # Report jumps at clip boundaries without allowing the filter to cross them. + for index in range(1, len(joints)): + if ( + frame_selected[index - 1] + and frame_selected[index] + and arrays["frame_valid"][index - 1] + and arrays["frame_valid"][index] + and arrays["frame_id"][index] == arrays["frame_id"][index - 1] + 1 + and arrays["clip_index"][index] != arrays["clip_index"][index - 1] + ): + jump = np.linalg.norm(joints[index] - joints[index - 1], axis=-1) * 1000.0 + append_finite( + output, "clip_boundary_discontinuity_mm", jump.mean(axis=-1), + ) + return output + + +def identity_switch_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + frame_selected: np.ndarray, +) -> dict[str, list[float]]: + wrong: list[bool | None] = [] + target = arrays["target_joints_camera"] + annotation = arrays["joint_annotation_valid"].astype(bool) + for index in range(len(joints)): + if not frame_selected[index] or not annotation[index].all(): + wrong.append(None) + continue + semantic = ( + np.linalg.norm(joints[index, 0] - target[index, 0], axis=-1).mean() + + np.linalg.norm(joints[index, 1] - target[index, 1], axis=-1).mean() + ) + swapped = ( + np.linalg.norm(joints[index, 0] - target[index, 1], axis=-1).mean() + + np.linalg.norm(joints[index, 1] - target[index, 0], axis=-1).mean() + ) + wrong.append(bool(swapped < semantic)) + switches = [] + for indices in selected_segments(arrays, frame_selected): + for previous, current in zip(indices[:-1], indices[1:], strict=True): + if wrong[previous] is not None and wrong[current] is not None: + switches.append(float(wrong[previous] != wrong[current])) + return {"identity_switch_fraction": switches} + + +def summarize_condition( + values: dict[str, list[float]], + condition: FilterCondition, + scope: str, +) -> list[dict[str, object]]: + return [ + { + "scope": scope, "condition": condition.name, + "family": condition.family, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + "metric": metric, **distribution_summary(observations), + } + for metric, observations in sorted(values.items()) + ] + + +def metric_lookup(rows: list[dict[str, object]], condition: str, metric: str) -> dict[str, object]: + matches = [ + row for row in rows + if row["condition"] == condition and row["metric"] == metric + ] + if len(matches) != 1: + raise ValueError(f"expected one jitter metric row for {condition}/{metric}") + return matches[0] + + +def build_overview( + metric_rows: list[dict[str, object]], conditions: list[FilterCondition], + scope: str, +) -> list[dict[str, object]]: + raw_name = "F0_raw" + keys = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "z_p95_mm": ("translation_z_mae_mm", "p95"), + "velocity_error_mm_per_s": ("joint_velocity_error_mm_per_s", "mean"), + "acceleration_error_mm_per_s2": ("joint_acceleration_error_mm_per_s2", "mean"), + "jitter_3d_acceleration_mm_per_s2": ( + "predicted_3d_joint_acceleration_mm_per_s2", "mean", + ), + "jitter_3d_jerk_mm_per_s3": ("predicted_3d_joint_jerk_mm_per_s3", "mean"), + "jitter_2d_acceleration_px_per_s2": ( + "predicted_2d_joint_acceleration_px_per_s2", "mean", + ), + "jitter_2d_jerk_px_per_s3": ("predicted_2d_joint_jerk_px_per_s3", "mean"), + "high_frequency_energy_ratio": ("high_frequency_energy_ratio", "mean"), + } + raw = { + name: float(metric_lookup(metric_rows, raw_name, metric)[statistic]) + for name, (metric, statistic) in keys.items() + } + output = [] + for condition in conditions: + values = { + name: float(metric_lookup(metric_rows, condition.name, metric)[statistic]) + for name, (metric, statistic) in keys.items() + } + row: dict[str, object] = { + "scope": scope, "condition": condition.name, + "family": condition.family, "filter_value": condition.value, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + } + for name, value in values.items(): + row[name] = value + row[f"{name}_delta"] = value - raw[name] + guardrails = [ + 100.0 * (values[name] - raw[name]) / raw[name] + for name in ( + "absolute_mpjpe_mm", "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", "z_p95_mm", + ) + ] + reductions = [ + (raw[name] - values[name]) / raw[name] + for name in ( + "jitter_3d_acceleration_mm_per_s2", + "jitter_3d_jerk_mm_per_s3", + "jitter_2d_acceleration_px_per_s2", + "jitter_2d_jerk_px_per_s3", + ) + ] + row["maximum_accuracy_degradation_percent"] = max(guardrails) + row["accuracy_guardrail_passed"] = bool(max(guardrails) <= 1.0) + row["jitter_reduction_score"] = float(np.mean(reductions)) + row["accuracy_delta"] = row["absolute_mpjpe_mm_delta"] + row["jitter_delta"] = row["jitter_3d_acceleration_mm_per_s2_delta"] + row["velocity_error_delta"] = row["velocity_error_mm_per_s_delta"] + row["acceleration_error_delta"] = row[ + "acceleration_error_mm_per_s2_delta" + ] + row["selected_for_full_validation"] = False + output.append(row) + return output + + +def paired_take_bootstrap_rows( + take_rows: list[dict[str, object]], + conditions: list[FilterCondition], + *, + samples: int, + seed: int = 20260716, +) -> list[dict[str, object]]: + if samples < 1: + raise ValueError("bootstrap samples must be positive") + index = { + (str(row["take"]), str(row["condition"]), str(row["metric"])): row + for row in take_rows + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(conditions): + if condition.family == "F0": + continue + for metric_index, metric in enumerate(metrics): + for statistic_name in ("mean", "p95"): + paired = [] + raw_values = [] + filtered_values = [] + for take in takes: + raw = index.get((take, "F0_raw", metric)) + filtered = index.get((take, condition.name, metric)) + if raw is None or filtered is None: + continue + raw_value = raw.get(statistic_name) + filtered_value = filtered.get(statistic_name) + if raw_value is None or filtered_value is None: + continue + raw_float = float(raw_value) + filtered_float = float(filtered_value) + if not np.isfinite(raw_float) or not np.isfinite(filtered_float): + continue + raw_values.append(raw_float) + filtered_values.append(filtered_float) + paired.append(filtered_float - raw_float) + deltas = np.asarray(paired, dtype=np.float64) + if not len(deltas): + continue + rng = np.random.default_rng(np.random.SeedSequence([ + seed, condition_index, metric_index, + 0 if statistic_name == "mean" else 1, + ])) + indices = rng.integers(0, len(deltas), size=(samples, len(deltas))) + bootstrap = deltas[indices].mean(axis=1) + output.append({ + "scope": take_rows[0]["scope"], + "condition": condition.name, + "family": condition.family, + "metric": metric, + "take_statistic": statistic_name, + "takes": len(deltas), + "raw": float(np.mean(raw_values)), + "filtered": float(np.mean(filtered_values)), + "filtered_minus_raw": float(deltas.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def choose_filter_conditions(overview: list[dict[str, object]]) -> dict[str, str | None]: + selected: dict[str, str | None] = {"F1": None, "F2": None} + for family in selected: + candidates = [ + row for row in overview + if row["family"] == family and row["accuracy_guardrail_passed"] + ] + if not candidates: + continue + candidates.sort(key=lambda row: ( + -float(row["jitter_reduction_score"]), + float(row["acceleration_error_mm_per_s2"]), + float(row["absolute_mpjpe_mm"]), + -float(row["filter_value"]), + )) + selected[family] = str(candidates[0]["condition"]) + candidates[0]["selected_for_full_validation"] = True + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument( + "--scope", choices=("smoke", "subset", "full"), required=True, + ) + parser.add_argument("--subset-manifest", type=Path) + parser.add_argument("--selection-json", type=Path) + parser.add_argument("--conditions") + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise ValueError("jitter output directory must be new or empty") + cache_manifest = json.loads( + (args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8") + ) + expected_cache_scope = "smoke" if args.scope == "smoke" else "full" + if ( + cache_manifest.get("status") != "complete" + or cache_manifest.get("official_test_used") is not False + or float(cache_manifest.get("fps")) != FPS + or cache_manifest.get("scope") != expected_cache_scope + or ( + expected_cache_scope == "full" + and (cache_manifest.get("clips") != 1495 or cache_manifest.get("frames") != 11638) + ) + ): + raise ValueError("invalid raw jitter cache manifest") + grid = condition_grid() + if args.conditions: + requested = [value.strip() for value in args.conditions.split(",") if value.strip()] + else: + requested = list(grid) + if not requested or set(requested) - set(grid) or "F0_raw" not in requested: + raise ValueError("jitter conditions must be registered and include F0_raw") + if args.scope == "subset": + if args.subset_manifest is None or args.selection_json is not None: + raise ValueError("subset scope requires only --subset-manifest") + subset = json.loads(args.subset_manifest.read_text(encoding="utf-8")) + selected_clip_indices = {int(value) for value in subset["clip_indices"]} + if ( + len(selected_clip_indices) != 256 + or subset.get("source_manifest_sha256") + != cache_manifest["manifest"]["sha256"] + or subset.get("official_test_used", False) is not False + ): + raise ValueError("jitter tuning subset must be the frozen 256 clips") + elif args.scope == "full": + if args.selection_json is None or args.subset_manifest is not None: + raise ValueError("full scope requires only --selection-json") + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + selected_names = { + value for value in selection["selected_conditions"].values() + if value is not None + } + if set(requested) != {"F0_raw", *selected_names}: + raise ValueError("full evaluation conditions differ from frozen subset selection") + selected_clip_indices = None + else: + if args.selection_json is not None or args.subset_manifest is not None: + raise ValueError("smoke scope does not accept selection/subset inputs") + selected_clip_indices = None + + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + conditions = [grid[name] for name in requested] + global_values: dict[str, dict[str, list[float]]] = { + condition.name: defaultdict(list) for condition in conditions + } + take_rows = [] + fallback_rows = [] + for take_record in cache_manifest["takes"]: + arrays = load_take(Path(take_record["path"])) + frame_selected = ( + np.ones(len(arrays["frame_id"]), dtype=bool) + if selected_clip_indices is None else + np.isin(arrays["clip_index"], list(selected_clip_indices)) + ) + if not frame_selected.any(): + continue + take = str(arrays["take"]) + for condition in conditions: + translation, rotations, fallbacks = filtered_parameters(arrays, condition) + vertices, joints = rebuild_geometry( + rotations, arrays["pred_shape"].astype(np.float32), + translation, mano, device, + ) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, rotations, translation, frame_selected, + ) + for metric, values in temporal_metrics( + arrays, joints, projected, frame_selected, + ).items(): + metrics[metric].extend(values) + for metric, values in identity_switch_metrics( + arrays, joints, frame_selected, + ).items(): + metrics[metric].extend(values) + for metric, observations in metrics.items(): + global_values[condition.name][metric].extend(observations) + summary = distribution_summary(observations) + take_rows.append({ + "scope": args.scope, "take": take, + "condition": condition.name, "family": condition.family, + "metric": metric, **summary, + }) + fallback_rows.append({ + "scope": args.scope, "take": take, + "condition": condition.name, + "fallback_segments": fallbacks, + }) + metric_rows = [] + for condition in conditions: + metric_rows.extend(summarize_condition( + global_values[condition.name], condition, args.scope, + )) + overview = build_overview(metric_rows, conditions, args.scope) + if args.scope == "full": + for row in overview: + row["selected_for_full_validation"] = row["family"] != "F0" + paired_rows = paired_take_bootstrap_rows( + take_rows, conditions, samples=args.bootstrap_samples, + ) + selection_payload = None + if args.scope == "subset": + selected = choose_filter_conditions(overview) + selection_payload = { + "status": "selected", + "official_test_used": False, + "selection_scope": "frozen_official_validation_subset_256", + "subset_manifest": str(args.subset_manifest.resolve()), + "checkpoint": cache_manifest["checkpoint"], + "selected_conditions": selected, + "rule": ( + "<=1% maximum accuracy degradation; maximize mean relative " + "3D/2D acceleration/jerk reduction; then acceleration error, " + "absolute MPJPE, weaker smoothing" + ), + } + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "jitter_selection.json").write_text( + json.dumps(selection_payload, indent=2) + "\n", encoding="utf-8", + ) + write_csv(args.output_dir / "jitter_condition_metrics.csv", metric_rows) + write_csv(args.output_dir / "jitter_take_metrics.csv", take_rows) + write_csv(args.output_dir / "jitter_filter_fallbacks.csv", fallback_rows) + write_csv(args.output_dir / "jitter_raw_vs_filtered.csv", overview) + if paired_rows: + write_csv( + args.output_dir / "jitter_paired_take_bootstrap_ci.csv", paired_rows, + ) + report = { + "status": "evaluated", + "official_test_used": False, + "result_role": ( + "engineering_smoke" if args.scope == "smoke" + else "filtered_inference_secondary_results" + ), + "raw_model_results_remain_primary": True, + "scope": args.scope, + "fps": FPS, + "cache_manifest": str((args.cache_dir / "cache_manifest.json").resolve()), + "conditions": requested, + "selection": selection_payload, + "outputs": { + "overview": "jitter_raw_vs_filtered.csv", + "metrics": "jitter_condition_metrics.csv", + "take_metrics": "jitter_take_metrics.csv", + "fallbacks": "jitter_filter_fallbacks.csv", + "paired_take_bootstrap_ci": ( + "jitter_paired_take_bootstrap_ci.csv" if paired_rows else None + ), + }, + } + (args.output_dir / "jitter_evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "scope": args.scope, + "conditions": requested, "selection": selection_payload, + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase5_causal_state.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1f9b2876ea7a730a657e4ef9d6b15250842bed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase5_causal_state.py @@ -0,0 +1,554 @@ +#!/usr/bin/env python3 +"""Evaluate OOF-frozen causal wrist-z state estimators on official validation.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +import numpy as np + +from foundation_hand.evaluation.causal_state import ( + causal_constant_velocity_kalman, + measurement_uncertainty_multiplier, +) +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.temporal_filter import ( + apply_by_segment, + butterworth_zero_phase, + ema, + valid_segments, +) +try: + from scripts.evaluate_phase4_jitter import ( + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, + ) +except ModuleNotFoundError: # Direct `python scripts/...` execution. + from evaluate_phase4_jitter import ( # type: ignore[no-redef] + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, + ) + + +FPS = 30.0 + + +@dataclass(frozen=True) +class Condition: + name: str + family: str + causal_status: str + latency_frames: float | None + + +CONDITIONS = ( + Condition("coarse", "coarse", "causal", 0.0), + Condition("calibrated_per_frame", "calibrated", "causal", 0.0), + Condition("ema_alpha0.6", "ema", "causal_fixed_lag", (1.0 - 0.6) / 0.6), + Condition("butterworth_2hz", "butterworth", "offline_zero_phase", None), + Condition("fixed_kalman", "fixed_kalman", "causal_state", 0.0), + Condition("uncertainty_kalman", "uncertainty_kalman", "causal_state", 0.0), +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def uncertainty_base(prediction: dict[str, np.ndarray]) -> np.ndarray: + available = prediction["alignment_applied"].astype(bool) + base = measurement_uncertainty_multiplier( + prediction["confidence"], + prediction["inlier_ratio"], + prediction["residual_scale_m"], + prediction["valid_fraction"], + prediction["quality"], + 1.0, + ) + return np.where(available, base, 5.0) + + +def condition_z( + arrays: dict[str, np.ndarray], + prediction: dict[str, np.ndarray], + condition: Condition, + selection: dict[str, object], +) -> tuple[np.ndarray, np.ndarray, int]: + coarse = arrays["pred_wrist_translation"][..., 2].astype(np.float64) + available = prediction["alignment_applied"].astype(bool) + correction = np.where(available, prediction["calibrated_delta_z_m"], 0.0) + measurement = coarse + correction + variance = np.full_like(measurement, np.nan) + if condition.family == "coarse": + return coarse.copy(), variance, 0 + if condition.family == "calibrated": + return measurement, variance, 0 + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + if condition.family == "ema": + filtered, fallback = apply_by_segment( + measurement, segments, lambda values: ema(values, 0.6), minimum_frames=1, + ) + return filtered, variance, fallback + if condition.family == "butterworth": + filtered, fallback = apply_by_segment( + measurement, + segments, + lambda values: butterworth_zero_phase(values, 2.0, FPS, order=2), + minimum_frames=4, + ) + return filtered, variance, fallback + parameters = selection["selected"][condition.family] + multiplier = np.ones_like(measurement) + if condition.family == "uncertainty_kalman": + strength = float(parameters["uncertainty_strength"]) + base = uncertainty_base(prediction) + multiplier = 1.0 + strength * (base - 1.0) + measurement_available = np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), measurement.shape, + ) + filtered, variance = causal_constant_velocity_kalman( + measurement, + frame_id=arrays["frame_id"], + segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], + measurement_available=measurement_available, + process_sigma_m_per_frame2=float(parameters["process_sigma_m_per_frame2"]), + measurement_sigma_m=float(parameters["measurement_sigma_m"]), + uncertainty_multiplier=multiplier, + ) + return filtered, variance, 0 + + +def translated_geometry( + arrays: dict[str, np.ndarray], z_m: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + coarse_z = arrays["pred_wrist_translation"][..., 2] + delta = z_m - coarse_z + translation = arrays["pred_wrist_translation"].astype(np.float64).copy() + joints = arrays["pred_joints_camera"].astype(np.float64).copy() + vertices = arrays["pred_vertices_camera"].astype(np.float64).copy() + translation[..., 2] = z_m + joints[..., 2] += delta[..., None] + vertices[..., 2] += delta[..., None] + return translation, joints, vertices + + +def append_metrics( + destination: dict[str, list[float]], source: dict[str, Iterable[float]], +) -> None: + for metric, values in source.items(): + destination[metric].extend(float(value) for value in values if np.isfinite(value)) + + +def response_diagnostics( + arrays: dict[str, np.ndarray], z_m: np.ndarray, +) -> dict[str, list[float]]: + output: dict[str, list[float]] = defaultdict(list) + target = arrays["target_wrist_translation"][..., 2] + hand_valid = arrays["joint_annotation_valid"].astype(bool) + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + for indices in segments: + for hand in range(2): + selected = indices[hand_valid[indices, hand]] + if len(selected) < 3 or np.any(np.diff(selected) != 1): + continue + pred_velocity = np.diff(z_m[selected, hand]) + target_velocity = np.diff(target[selected, hand]) + step = np.abs(target_velocity) >= 0.005 + if step.any(): + output["step_same_frame_absolute_error_mm"].extend( + (np.abs(pred_velocity[step] - target_velocity[step]) * 1000.0).tolist() + ) + output["step_same_frame_gain"].extend( + (pred_velocity[step] / target_velocity[step]).tolist() + ) + correlations = [] + for lag in range(4): + pred = pred_velocity[lag:] + truth = target_velocity[: len(target_velocity) - lag or None] + if len(pred) < 3 or np.std(pred) < 1e-10 or np.std(truth) < 1e-10: + correlations.append(float("-inf")) + else: + correlations.append(float(np.corrcoef(pred, truth)[0, 1])) + if np.isfinite(correlations).any(): + output["estimated_causal_lag_frames"].append(float(np.argmax(correlations))) + if len(selected) >= 8: + error = np.abs(z_m[selected, hand] - target[selected, hand]) * 1000.0 + output["segment_endpoint_drift_delta_mm"].append(float(error[-1] - error[0])) + output["segment_length_frames"].append(float(len(selected))) + starts = np.concatenate([indices[:1] for indices in segments]) if segments else np.empty(0, dtype=int) + if len(starts): + calibrated = arrays["_calibrated_measurement_z_m"] + output["boundary_reset_difference_mm"].extend( + (np.abs(z_m[starts] - calibrated[starts]) * 1000.0).reshape(-1).tolist() + ) + return output + + +def missing_transition_diagnostics( + arrays: dict[str, np.ndarray], + prediction: dict[str, np.ndarray], + selection: dict[str, object], + family: str, +) -> dict[str, list[float]]: + parameters = selection["selected"][family] + coarse = arrays["pred_wrist_translation"][..., 2].astype(np.float64) + available = prediction["alignment_applied"].astype(bool) + full_measurement = coarse + np.where( + available, prediction["calibrated_delta_z_m"], 0.0, + ) + missing_measurement = full_measurement.copy() + multiplier = np.ones_like(full_measurement) + missing_mask = np.zeros_like(available) + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + for indices in segments: + if len(indices) >= 6: + missing_mask[indices[3:5]] = True + missing_measurement[missing_mask] = coarse[missing_mask] + if family == "uncertainty_kalman": + strength = float(parameters["uncertainty_strength"]) + base = uncertainty_base(prediction) + base[missing_mask] = 5.0 + multiplier = 1.0 + strength * (base - 1.0) + measurement_available = np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), full_measurement.shape, + ) + filtered, _ = causal_constant_velocity_kalman( + missing_measurement, + frame_id=arrays["frame_id"], segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], measurement_available=measurement_available, + process_sigma_m_per_frame2=float(parameters["process_sigma_m_per_frame2"]), + measurement_sigma_m=float(parameters["measurement_sigma_m"]), + uncertainty_multiplier=multiplier, + ) + target = arrays["target_wrist_translation"][..., 2] + hand_valid = arrays["joint_annotation_valid"].astype(bool) + output: dict[str, list[float]] = defaultdict(list) + selected = missing_mask & hand_valid + output["simulated_missing_span_z_mae_mm"].extend( + (np.abs(filtered - target)[selected] * 1000.0).tolist() + ) + for indices in segments: + if len(indices) < 6: + continue + recovery = indices[5] + valid = hand_valid[recovery] + output["first_recovery_frame_z_mae_mm"].extend( + (np.abs(filtered[recovery] - target[recovery])[valid] * 1000.0).tolist() + ) + return output + + +def paired_bootstrap( + take_rows: list[dict[str, object]], *, samples: int, seed: int = 20260716, +) -> list[dict[str, object]]: + index = { + (str(row["take"]), str(row["condition"]), str(row["metric"]), statistic): + float(row[statistic]) + for row in take_rows + for statistic in ("mean", "p95") + if row.get(statistic) is not None and np.isfinite(float(row[statistic])) + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(CONDITIONS): + if condition.name == "calibrated_per_frame": + continue + for metric_index, metric in enumerate(metrics): + for statistic_index, statistic in enumerate(("mean", "p95")): + pairs = [ + ( + index[(take, condition.name, metric, statistic)], + index[(take, "calibrated_per_frame", metric, statistic)], + ) + for take in takes + if (take, condition.name, metric, statistic) in index + and (take, "calibrated_per_frame", metric, statistic) in index + ] + if not pairs: + continue + delta = np.asarray([filtered - raw for filtered, raw in pairs]) + rng = np.random.default_rng(np.random.SeedSequence( + (seed, condition_index, metric_index, statistic_index), + )) + bootstrap = delta[ + rng.integers(0, len(delta), size=(samples, len(delta))) + ].mean(axis=1) + output.append({ + "reference": "calibrated_per_frame", "condition": condition.name, + "metric": metric, "take_statistic": statistic, "takes": len(delta), + "condition_minus_reference": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def build_overview(metric_rows: list[dict[str, object]]) -> list[dict[str, object]]: + index = { + (str(row["condition"]), str(row["metric"])): row for row in metric_rows + } + fields = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "z_mae_mm": ("translation_z_mae_mm", "mean"), + "z_p95_mm": ("translation_z_mae_mm", "p95"), + "velocity_error_mm_per_s": ("joint_velocity_error_mm_per_s", "mean"), + "acceleration_error_mm_per_s2": ("joint_acceleration_error_mm_per_s2", "mean"), + "predicted_acceleration_mm_per_s2": ( + "predicted_3d_joint_acceleration_mm_per_s2", "mean", + ), + "predicted_jerk_mm_per_s3": ("predicted_3d_joint_jerk_mm_per_s3", "mean"), + "high_frequency_energy_ratio": ("high_frequency_energy_ratio", "mean"), + "estimated_causal_lag_frames": ("estimated_causal_lag_frames", "mean"), + } + reference = { + name: float(index[("calibrated_per_frame", metric)][statistic]) + for name, (metric, statistic) in fields.items() + } + output = [] + for condition in CONDITIONS: + values = { + name: float(index[(condition.name, metric)][statistic]) + for name, (metric, statistic) in fields.items() + } + row: dict[str, object] = { + "reference": "calibrated_per_frame", "condition": condition.name, + "family": condition.family, "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + } + for name, value in values.items(): + row[name] = value + row[f"{name}_delta"] = value - reference[name] + row["accuracy_delta"] = row["absolute_mpjpe_mm_delta"] + row["jitter_delta"] = row["predicted_acceleration_mm_per_s2_delta"] + row["velocity_error_delta"] = row["velocity_error_mm_per_s_delta"] + row["acceleration_error_delta"] = row["acceleration_error_mm_per_s2_delta"] + row["static_guardrail_passed"] = bool( + float(row["absolute_mpjpe_mm_delta"]) <= 0.2 + and float(row["z_mae_mm_delta"]) <= 0.2 + and float(row["z_p95_mm_delta"]) <= 0.2 + ) + row["retained_causal_candidate"] = bool( + condition.name == "uncertainty_kalman" + and row["static_guardrail_passed"] + and float(row["jitter_delta"]) < 0.0 + and float(row["velocity_error_delta"]) < 0.0 + and float(row["acceleration_error_delta"]) < 0.0 + ) + output.append(row) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-evaluation-dir", type=Path, required=True) + parser.add_argument("--selection-json", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument( + "--continuous-take-state", + action="store_true", + help="Keep state across model inference windows until a take/frame discontinuity.", + ) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("causal-state output directory must be new or empty") + cache_manifest_path = args.cache_dir / "cache_manifest.json" + alignment_report_path = args.alignment_evaluation_dir / "evaluation.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + alignment_report = json.loads(alignment_report_path.read_text(encoding="utf-8")) + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + or cache.get("frames") != 11638 + or float(cache.get("fps")) != FPS + ): + raise ValueError("invalid complete official-validation cache contract") + if ( + alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + or alignment_report.get("coarse_checkpoint", {}).get("sha256") + != cache.get("checkpoint", {}).get("sha256") + ): + raise ValueError("alignment evaluation does not match the raw cache") + if ( + selection.get("status") != "selected" + or selection.get("official_validation_used") is not False + or selection.get("official_test_used") is not False + or "coarse z is always" not in selection.get("measurement_contract", "") + ): + raise ValueError("causal-state parameters are not valid train-OOF selections") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + global_values = {condition.name: defaultdict(list) for condition in CONDITIONS} + take_rows = [] + response_rows = [] + missing_values = { + family: defaultdict(list) for family in ("fixed_kalman", "uncertainty_kalman") + } + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw-cache take hash mismatch: {take_path}") + arrays = load_npz(take_path) + if args.continuous_take_state: + arrays["clip_index"] = np.zeros_like(arrays["clip_index"]) + stem = "__".join(Path(str(arrays["take"])).parts) + prediction_path = args.alignment_evaluation_dir / "predictions" / f"{stem}.npz" + prediction = load_npz(prediction_path) + if not np.array_equal(arrays["frame_id"], prediction["frame_id"]): + raise ValueError(f"alignment frame mismatch: {arrays['take']}") + calibrated_measurement = arrays["pred_wrist_translation"][..., 2] + np.where( + prediction["alignment_applied"], prediction["calibrated_delta_z_m"], 0.0, + ) + arrays["_calibrated_measurement_z_m"] = calibrated_measurement + saved: dict[str, np.ndarray] = {"frame_id": arrays["frame_id"]} + for condition in CONDITIONS: + z_m, variance, fallbacks = condition_z(arrays, prediction, condition, selection) + translation, joints, vertices = translated_geometry(arrays, z_m) + selected = arrays["frame_valid"].astype(bool) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, arrays["pred_rotation_matrices"], translation, selected, + ) + append_metrics(metrics, temporal_metrics(arrays, joints, projected, selected)) + append_metrics(metrics, identity_switch_metrics(arrays, joints, selected)) + response = response_diagnostics(arrays, z_m) + append_metrics(metrics, response) + for metric, observations in metrics.items(): + global_values[condition.name][metric].extend(observations) + take_rows.append({ + "take": str(arrays["take"]), "condition": condition.name, + "family": condition.family, "metric": metric, + **distribution_summary(observations), + }) + for metric, observations in response.items(): + response_rows.append({ + "take": str(arrays["take"]), "condition": condition.name, + "metric": metric, **distribution_summary(observations), + }) + saved[f"{condition.name}_z_m"] = z_m + saved[f"{condition.name}_variance_m2"] = variance + saved[f"{condition.name}_fallback_segments"] = np.asarray(fallbacks) + for family in missing_values: + append_metrics( + missing_values[family], + missing_transition_diagnostics(arrays, prediction, selection, family), + ) + np.savez_compressed(prediction_root / f"{stem}.npz", **saved) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + metric_rows = [] + for condition in CONDITIONS: + for metric, observations in sorted(global_values[condition.name].items()): + metric_rows.append({ + "condition": condition.name, "family": condition.family, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, "metric": metric, + **distribution_summary(observations), + }) + missing_rows = [ + {"condition": family, "metric": metric, **distribution_summary(observations)} + for family, values in missing_values.items() + for metric, observations in sorted(values.items()) + ] + bootstrap_rows = paired_bootstrap( + take_rows, samples=args.bootstrap_samples, + ) + overview_rows = build_overview(metric_rows) + write_csv(args.output_dir / "metrics.csv", metric_rows) + write_csv(args.output_dir / "overview.csv", overview_rows) + write_csv(args.output_dir / "take_metrics.csv", take_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap_rows) + write_csv(args.output_dir / "response_diagnostics.csv", response_rows) + write_csv(args.output_dir / "missing_modality_transition.csv", missing_rows) + report = { + "status": "evaluated", + "experiment_class": "preregistered_confirmatory_causal_state", + "result_role": "deployable_causal_translation_z_state_ablation", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "alignment_evaluation": {"path": str(alignment_report_path.resolve()), "sha256": sha256(alignment_report_path)}, + "selection": {"path": str(args.selection_json.resolve()), "sha256": sha256(args.selection_json)}, + "checkpoint": cache["checkpoint"], + "conditions": [condition.__dict__ for condition in CONDITIONS], + "state_scope": "translation z only; pose/shape and translation x/y unchanged", + "measurement_contract": selection["measurement_contract"], + "boundary_contract": ( + "reset at invalid frame, frame discontinuity, and take boundary" + if args.continuous_take_state else + "reset at invalid frame, frame discontinuity, and frozen model clip boundary; never cross take" + ), + "continuous_take_state": args.continuous_take_state, + "long_sequence_limitation": ( + None if args.continuous_take_state else + "the inherited no-cross-clip rule limits a continuous state segment to the cache clip length" + ), + "missing_modality_diagnostic": "simulated local-alignment loss uses exact coarse-z fallback with high uncertainty; the unified coarse model's missing Depth/K static fallback was audited in Stage 3", + "outputs": { + "metrics": "metrics.csv", "take_metrics": "take_metrics.csv", + "overview": "overview.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "response": "response_diagnostics.csv", + "missing_transition": "missing_modality_transition.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "evaluated", "frames": cache["frames"], + "conditions": [condition.name for condition in CONDITIONS], + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase5_metric_alignment.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase5_metric_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f686d340bef0e1a05bb1555d8d89dcd10f1938 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase5_metric_alignment.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +"""Evaluate deployable predicted-location wrist-z alignment on frozen raw caches.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import cv2 +import joblib +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.alignment_calibration import ( + FEATURE_NAMES, + features_from_take, + projected_hand_scale_px, +) +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + + +FINGERTIPS = (4, 8, 12, 16, 20) +CALIBRATED_CONDITIONS = ( + "coarse", + "robust_alignment_unscaled", + "calibrated_always", + "calibrated_confidence", + "missing_depth_fallback", + "missing_k_fallback", +) +RAW_CONDITIONS = ("coarse", "robust_alignment_unscaled") +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + first_fields = list(rows[0]) + extra_fields = sorted({key for row in rows for key in row} - set(first_fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=first_fields + extra_fields, lineterminator="\n", + ) + writer.writeheader() + writer.writerows(rows) + + +def _velocity(translation: np.ndarray, frame_ids: np.ndarray) -> np.ndarray: + output = np.zeros_like(translation, dtype=np.float32) + contiguous = frame_ids[1:] == frame_ids[:-1] + 1 + output[1:][contiguous] = translation[1:][contiguous] - translation[:-1][contiguous] + return output + + +def alignment_arrays( + arrays: dict[str, np.ndarray], data_root: Path, +) -> dict[str, np.ndarray]: + take = str(arrays["take"]) + take_dir = data_root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + time = len(arrays["frame_id"]) + diagnostics: dict[str, list[np.ndarray]] = defaultdict(list) + overlap = [] + predicted_depth_order = [] + for time_index, frame_id in enumerate(arrays["frame_id"]): + depth_mm = cv2.imread( + str(take_dir / "depth" / f"{int(frame_id):06d}.png"), cv2.IMREAD_UNCHANGED, + ) + if depth_mm is None or depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{int(frame_id):06d}") + depth_m, depth_valid = depth_mm_to_m(depth_mm) + masks = [] + predicted_surface_medians = [] + for hand in range(2): + result, samples = align_wrist_z( + arrays["pred_vertices_camera"][time_index, hand], + K_raw, depth_m, depth_valid, + ) + if samples is None: + raise AssertionError("complete-modality evaluation has no depth samples") + for field, value in result.as_dict().items(): + diagnostics[f"alignment_{field}"].append(np.asarray(value)) + masks.append(np.unpackbits( + samples.silhouette_packed, bitorder="little", + count=samples.silhouette_hw[0] * samples.silhouette_hw[1], + ).astype(bool)) + predicted_surface_medians.append(float(np.median( + samples.predicted_depth_m[samples.visible_vertex], + ))) + intersection = np.logical_and(masks[0], masks[1]).sum() + union = np.logical_or(masks[0], masks[1]).sum() + overlap.append(intersection / max(union, 1)) + predicted_depth_order.append(np.sign( + predicted_surface_medians[1] - predicted_surface_medians[0] + )) + values = { + key: np.stack(items).reshape(time, 2) + for key, items in diagnostics.items() + } + pred_joints_raw, _ = project_points(arrays["pred_joints_camera"], K_raw) + resized_hw = arrays["K"].shape # Cache K is already aligned to model image. + del resized_hw + # Recover resized dimensions from principal-point scaling used by the 640x368 cache. + width, height = 640.0, 368.0 + raw_to_resized = np.asarray((width / raw_hw[1], height / raw_hw[0]), dtype=np.float32) + mano_resized = pred_joints_raw * raw_to_resized + values.update({ + "frame_id": arrays["frame_id"], + "pred_wrist_translation": arrays["pred_wrist_translation"], + "coarse_hand_scale_px": projected_hand_scale_px( + pred_joints_raw, source_hw=raw_hw, target_hw=(int(height), int(width)), + ), + "coarse_direct_mano_consistency_px": np.linalg.norm( + arrays["pred_direct_2d_px"] - mano_resized, axis=-1, + ).mean(axis=-1), + "silhouette_overlap_fraction": np.asarray(overlap, dtype=np.float32), + "predicted_depth_order": np.asarray(predicted_depth_order, dtype=np.int8), + "coarse_wrist_velocity_m_per_frame": _velocity( + arrays["pred_wrist_translation"], arrays["frame_id"], + ), + }) + return values + + +def correction_grid( + geometry: dict[str, np.ndarray], package: dict[str, object], +) -> tuple[dict[str, np.ndarray], np.ndarray, np.ndarray]: + features = features_from_take(geometry) + flat = features.reshape(-1, features.shape[-1]) + calibrated = np.clip(package["regressor"].predict(flat), -0.12, 0.12).reshape(features.shape[:2]) + confidence = package["confidence"].predict_proba(flat)[:, 1].reshape(features.shape[:2]) + available = geometry["alignment_applied"].astype(bool) + threshold = float(package["confidence_threshold"]) + raw = np.where(available, geometry["alignment_delta_z_m"], 0.0) + calibrated_available = np.where(available, calibrated, 0.0) + gated = np.where(available & (confidence >= threshold), calibrated, 0.0) + zero = np.zeros_like(raw) + return { + "coarse": zero, + "robust_alignment_unscaled": raw, + "calibrated_always": calibrated_available, + "calibrated_confidence": gated, + "missing_depth_fallback": zero, + "missing_k_fallback": zero, + }, calibrated, confidence + + +def hand_size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def take_rows( + arrays: dict[str, np.ndarray], + geometry: dict[str, np.ndarray], + corrections: dict[str, np.ndarray], + calibrated: np.ndarray, + confidence: np.ndarray, +) -> tuple[list[dict[str, object]], list[dict[str, object]]]: + frame_rows = [] + temporal_rows = [] + take = str(arrays["take"]) + for condition, correction in corrections.items(): + joints = arrays["pred_joints_camera"].astype(np.float64).copy() + vertices = arrays["pred_vertices_camera"].astype(np.float64).copy() + translation = arrays["pred_wrist_translation"].astype(np.float64).copy() + joints[..., 2] += correction[..., None] + vertices[..., 2] += correction[..., None] + translation[..., 2] += correction + projected, _ = project_points(joints, arrays["K"]) + frame_valid = arrays["frame_valid"].astype(bool) + valid = arrays["mano_annotation_valid"].astype(bool) & frame_valid[:, None] + for time_index, hand in zip(*np.where(valid), strict=True): + target_joints = arrays["target_joints_camera"][time_index, hand] + target_vertices = arrays["target_vertices_camera"][time_index, hand] + pred_joints = joints[time_index, hand] + pred_vertices = vertices[time_index, hand] + joint_error = np.linalg.norm(pred_joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(pred_vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (pred_joints - pred_joints[:1]) - (target_joints - target_joints[:1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (pred_vertices - pred_joints[:1]) - (target_vertices - target_joints[:1]), axis=-1, + ) * 1000.0 + z_signed = 1000.0 * ( + translation[time_index, hand, 2] + - arrays["target_wrist_translation"][time_index, hand, 2] + ) + translation_signed = 1000.0 * ( + translation[time_index, hand] + - arrays["target_wrist_translation"][time_index, hand] + ) + target_2d = arrays["target_2d_px"][time_index, hand] + direct_2d = arrays["pred_direct_2d_px"][time_index, hand] + scale = float(geometry["coarse_hand_scale_px"][time_index, hand]) + target_depth = float(arrays["target_wrist_translation"][time_index, hand, 2]) + frame_rows.append({ + "condition": condition, + "take": take, + "subject": take.split("/")[0], + "action_family": take.split("/")[1], + "frame_id": int(arrays["frame_id"][time_index]), + "side": "right" if hand else "left", + "hand_size_bucket": hand_size_bucket(scale), + "depth_bucket": depth_bucket(target_depth), + "absolute_mpjpe_mm": float(joint_error.mean()), + "root_relative_mpjpe_mm": float(root_joint_error.mean()), + "absolute_mpvpe_mm": float(vertex_error.mean()), + "root_relative_mpvpe_mm": float(root_vertex_error.mean()), + "fingertip_mpjpe_mm": float(joint_error[list(FINGERTIPS)].mean()), + "translation_x_mae_mm": abs(float(translation_signed[0])), + "translation_y_mae_mm": abs(float(translation_signed[1])), + "translation_z_mae_mm": abs(float(z_signed)), + "translation_x_signed_error_mm": float(translation_signed[0]), + "translation_y_signed_error_mm": float(translation_signed[1]), + "translation_z_signed_error_mm": float(z_signed), + "direct_2d_error_px": float(np.linalg.norm(direct_2d - target_2d, axis=-1).mean()), + "mano_projected_2d_error_px": float(np.linalg.norm(projected[time_index, hand] - target_2d, axis=-1).mean()), + "direct_mano_2d_consistency_px": float( + np.linalg.norm(direct_2d - projected[time_index, hand], axis=-1).mean() + ), + "raw_alignment_delta_z_mm": 1000.0 * float(geometry["alignment_delta_z_m"][time_index, hand]), + "calibrated_delta_z_mm": 1000.0 * float(calibrated[time_index, hand]), + "applied_delta_z_mm": 1000.0 * float(correction[time_index, hand]), + "alignment_confidence": float(confidence[time_index, hand]), + "alignment_support": int(geometry["alignment_valid_support_count"][time_index, hand]), + "alignment_quality": float(geometry["alignment_conditioning_quality"][time_index, hand]), + }) + + contiguous = arrays["frame_id"][1:] == arrays["frame_id"][:-1] + 1 + for hand in range(2): + transition_valid = contiguous & valid[1:, hand] & valid[:-1, hand] + indices = np.where(transition_valid)[0] + pred_velocity = joints[1:, hand] - joints[:-1, hand] + target_velocity = arrays["target_joints_camera"][1:, hand] - arrays["target_joints_camera"][:-1, hand] + for index in indices: + temporal_rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][index + 1]), + "side": "right" if hand else "left", + "joint_velocity_error_mm_per_frame": float( + np.linalg.norm(pred_velocity[index] - target_velocity[index], axis=-1).mean() * 1000.0 + ), + }) + acceleration_valid = transition_valid[1:] & transition_valid[:-1] + acceleration_indices = np.where(acceleration_valid)[0] + pred_acceleration = pred_velocity[1:] - pred_velocity[:-1] + target_acceleration = target_velocity[1:] - target_velocity[:-1] + for index in acceleration_indices: + temporal_rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][index + 2]), + "side": "right" if hand else "left", + "joint_acceleration_error_mm_per_frame2": float( + np.linalg.norm(pred_acceleration[index] - target_acceleration[index], axis=-1).mean() * 1000.0 + ), + "predicted_joint_acceleration_mm_per_frame2": float( + np.linalg.norm(pred_acceleration[index], axis=-1).mean() * 1000.0 + ), + }) + both_valid = valid.all(axis=1) + wrong_side: list[bool | None] = [] + for time_index in range(len(valid)): + if not both_valid[time_index]: + wrong_side.append(None) + continue + correct = 0.5 * ( + np.linalg.norm( + joints[time_index, 0] - arrays["target_joints_camera"][time_index, 0], + axis=-1, + ).mean() + + np.linalg.norm( + joints[time_index, 1] - arrays["target_joints_camera"][time_index, 1], + axis=-1, + ).mean() + ) + swapped = 0.5 * ( + np.linalg.norm( + joints[time_index, 0] - arrays["target_joints_camera"][time_index, 1], + axis=-1, + ).mean() + + np.linalg.norm( + joints[time_index, 1] - arrays["target_joints_camera"][time_index, 0], + axis=-1, + ).mean() + ) + wrong_side.append(bool(swapped < correct)) + for index, (previous, current) in enumerate( + zip(wrong_side[:-1], wrong_side[1:], strict=True) + ): + if contiguous[index] and previous is not None and current is not None: + temporal_rows.append({ + "condition": condition, + "take": take, + "frame_id": int(arrays["frame_id"][index + 1]), + "side": "bimanual", + "identity_switch_fraction": float(previous != current), + }) + return frame_rows, temporal_rows + + +def aggregate_rows( + frame_rows: list[dict[str, object]], + temporal_rows: list[dict[str, object]], + conditions: tuple[str, ...] = CALIBRATED_CONDITIONS, +) -> list[dict[str, object]]: + output = [] + for condition in conditions: + selected = [row for row in frame_rows if row["condition"] == condition] + for metric in METRICS: + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row[metric] for row in selected), + }) + temporal_selected = [row for row in temporal_rows if row["condition"] == condition] + for metric in ( + "joint_velocity_error_mm_per_frame", + "joint_acceleration_error_mm_per_frame2", + "predicted_joint_acceleration_mm_per_frame2", + "identity_switch_fraction", + ): + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row.get(metric) for row in temporal_selected), + }) + for group in ("side", "hand_size_bucket", "depth_bucket", "take", "action_family"): + values = sorted({str(row[group]) for row in selected}) + for value in values: + grouped = [row for row in selected if str(row[group]) == value] + for metric in METRICS: + output.append({ + "condition": condition, "group": group, "value": value, "metric": metric, + **distribution_summary(row[metric] for row in grouped), + }) + return output + + +def paired_take_bootstrap( + frame_rows: list[dict[str, object]], + *, + conditions: tuple[str, ...] = CALIBRATED_CONDITIONS, + samples: int = 10_000, + seed: int = 20260716, +) -> list[dict[str, object]]: + take_means: dict[tuple[str, str, str], float] = {} + takes = sorted({str(row["take"]) for row in frame_rows}) + for condition in conditions: + for take in takes: + rows = [row for row in frame_rows if row["condition"] == condition and row["take"] == take] + for metric in METRICS: + take_means[(condition, take, metric)] = float(np.mean([float(row[metric]) for row in rows])) + output = [] + rng = np.random.default_rng(seed) + for condition in conditions[1:]: + for metric in METRICS: + delta = np.asarray([ + take_means[(condition, take, metric)] - take_means[("coarse", take, metric)] + for take in takes + ]) + indices = rng.integers(0, len(delta), size=(samples, len(delta))) + boot = delta[indices].mean(axis=1) + output.append({ + "condition": condition, "metric": metric, "takes": len(takes), + "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--calibrator", type=Path) + parser.add_argument("--calibration-json", type=Path) + parser.add_argument("--raw-only", action="store_true") + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("metric-alignment output directory must be new or empty") + cache = json.loads((args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + ): + raise ValueError("official-validation cache contract is invalid") + if args.raw_only: + if args.calibrator is not None or args.calibration_json is not None: + parser.error("--raw-only cannot accept calibrator inputs") + calibration = None + package = None + conditions = RAW_CONDITIONS + else: + if args.calibrator is None or args.calibration_json is None: + parser.error("calibrated evaluation requires --calibrator and --calibration-json") + calibration = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration.get("status") != "fitted" + or calibration.get("official_validation_used") is not False + or calibration.get("official_test_used") is not False + or calibration.get("model", {}).get("sha256") != sha256(args.calibrator) + ): + raise ValueError("OOF calibration contract is invalid") + package = joblib.load(args.calibrator) + if tuple(package["feature_names"]) != FEATURE_NAMES: + raise ValueError("calibrator feature schema mismatch") + conditions = CALIBRATED_CONDITIONS + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + all_frame_rows = [] + all_temporal_rows = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw-cache take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + geometry = alignment_arrays(arrays, args.data_root) + if args.raw_only: + zero = np.zeros_like(geometry["alignment_delta_z_m"]) + available = geometry["alignment_applied"].astype(bool) + corrections = { + "coarse": zero, + "robust_alignment_unscaled": np.where( + available, geometry["alignment_delta_z_m"], 0.0, + ), + } + calibrated, confidence = zero, zero + else: + corrections, calibrated, confidence = correction_grid(geometry, package) + frame_rows, temporal_rows = take_rows( + arrays, geometry, corrections, calibrated, confidence, + ) + all_frame_rows.extend(frame_rows) + all_temporal_rows.extend(temporal_rows) + np.savez_compressed( + prediction_root / f"{'__'.join(Path(str(arrays['take'])).parts)}.npz", + frame_id=arrays["frame_id"], + raw_alignment_delta_z_m=geometry["alignment_delta_z_m"], + calibrated_delta_z_m=calibrated, + confidence=confidence, + gated_delta_z_m=( + zero if args.raw_only else corrections["calibrated_confidence"] + ), + support=geometry["alignment_valid_support_count"], + projected_support=geometry["alignment_projected_support_count"], + quality=geometry["alignment_conditioning_quality"], + alignment_applied=geometry["alignment_applied"], + inlier_ratio=geometry["alignment_inlier_ratio"], + residual_scale_m=geometry["alignment_residual_scale_m"], + valid_fraction=geometry["alignment_valid_fraction"], + foreground_fraction=geometry["alignment_foreground_fraction"], + background_fraction=geometry["alignment_background_fraction"], + depth_discontinuity_m=geometry["alignment_depth_discontinuity_m"], + silhouette_overlap_fraction=geometry["silhouette_overlap_fraction"], + coarse_hand_scale_px=geometry["coarse_hand_scale_px"], + coarse_direct_mano_consistency_px=geometry[ + "coarse_direct_mano_consistency_px" + ], + coarse_wrist_velocity_m_per_frame=geometry[ + "coarse_wrist_velocity_m_per_frame" + ], + predicted_depth_order=geometry["predicted_depth_order"], + ) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + aggregate = aggregate_rows(all_frame_rows, all_temporal_rows, conditions) + paired = paired_take_bootstrap(all_frame_rows, conditions=conditions) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_frame_rows) + write_csv(args.output_dir / "per_temporal_metrics.csv", all_temporal_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + missing_fallback_exact = None if args.raw_only else all( + next(row for row in aggregate if row["condition"] == condition and row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm")["mean"] + == next(row for row in aggregate if row["condition"] == "coarse" and row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm")["mean"] + for condition in ("missing_depth_fallback", "missing_k_fallback") + ) + report = { + "status": "evaluated", + "experiment_class": "ablation" if args.raw_only else "deployable_ablation", + "result_role": ( + "fixed_raw_predicted_location_alignment_without_learned_confidence" + if args.raw_only else "deployable_predicted_location_metric_alignment" + ), + "official_validation_used": True, + "official_validation_used_for_model_or_threshold_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str((args.cache_dir / "cache_manifest.json").resolve()), "sha256": sha256(args.cache_dir / "cache_manifest.json")}, + "coarse_checkpoint": cache["checkpoint"], + "calibration": ( + None if args.raw_only else + {"path": str(args.calibration_json.resolve()), "sha256": sha256(args.calibration_json)} + ), + "calibrator": ( + None if args.raw_only else + {"path": str(args.calibrator.resolve()), "sha256": sha256(args.calibrator)} + ), + "conditions": list(conditions), + "confidence_threshold": None if args.raw_only else float(package["confidence_threshold"]), + "location": "coarse predicted MANO projection; no GT location/bbox/crop", + "correction": "translation z only; pose/shape and coarse outputs retained", + "solver": { + "loss": "MAD-scaled Huber IRLS", + "minimum_support": 20, + "maximum_raw_residual_m": 0.15, + "maximum_delta_m": 0.12, + "surface_location": "frontmost predicted MANO vertices at coarse projection", + }, + "missing_depth_k_fallback_exact": missing_fallback_exact, + "missing_rgb_status": "not_supported_by_frozen_coarse_cache; no claim", + "added_temporal_latency_frames": 0, + "outputs": { + "per_hand": "per_hand_frame_metrics.csv", + "per_temporal": "per_temporal_metrics.csv", + "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "frames": cache["frames"], + "missing_fallback_exact": missing_fallback_exact, "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase5_missing_modality.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase5_missing_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0ac6c2f8b9d554603ecc696a9392e1f97bb9bf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase5_missing_modality.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Evaluate true missing-Depth/K coarse-model caches against complete input.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import project_points +try: + from scripts.evaluate_phase4_jitter import identity_switch_metrics, temporal_metrics +except ModuleNotFoundError: # Direct `python scripts/...` execution. + from evaluate_phase4_jitter import identity_switch_metrics, temporal_metrics # type: ignore[no-redef] + + +CONDITIONS = ("complete", "missing_depth", "missing_k") +FINGERTIPS = (4, 8, 12, 16, 20) +STATIC_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "translation_x_signed_error_mm", "translation_y_signed_error_mm", + "translation_z_signed_error_mm", "direct_2d_error_px", + "mano_projected_2d_error_px", "direct_mano_2d_consistency_px", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def frame_rows(arrays: dict[str, np.ndarray], condition: str) -> list[dict[str, Any]]: + rows = [] + take = str(arrays["take"]) + projected, _ = project_points(arrays["pred_joints_camera"], arrays["K"][:, None]) + valid = arrays["frame_valid"].astype(bool)[:, None] & arrays["mano_annotation_valid"].astype(bool) + for time_index, hand in zip(*np.where(valid), strict=True): + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + vertices = arrays["pred_vertices_camera"][time_index, hand].astype(np.float64) + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_vertices = arrays["target_vertices_camera"][time_index, hand].astype(np.float64) + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (joints - joints[:1]) - (target_joints - target_joints[:1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (vertices - joints[:1]) - (target_vertices - target_joints[:1]), axis=-1, + ) * 1000.0 + translation_signed = 1000.0 * ( + arrays["pred_wrist_translation"][time_index, hand] + - arrays["target_wrist_translation"][time_index, hand] + ) + direct = arrays["pred_direct_2d_px"][time_index, hand] + target_2d = arrays["target_2d_px"][time_index, hand] + target_scale = float(np.max(np.ptp(target_2d, axis=0))) + rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][time_index]), + "side": "right" if hand else "left", + "hand_size_bucket": size_bucket(target_scale), + "wrist_depth_bucket": depth_bucket(float(arrays["target_wrist_translation"][time_index, hand, 2])), + "absolute_mpjpe_mm": float(joint_error.mean()), + "root_relative_mpjpe_mm": float(root_joint_error.mean()), + "absolute_mpvpe_mm": float(vertex_error.mean()), + "root_relative_mpvpe_mm": float(root_vertex_error.mean()), + "fingertip_mpjpe_mm": float(joint_error[list(FINGERTIPS)].mean()), + "translation_x_mae_mm": abs(float(translation_signed[0])), + "translation_y_mae_mm": abs(float(translation_signed[1])), + "translation_z_mae_mm": abs(float(translation_signed[2])), + "translation_x_signed_error_mm": float(translation_signed[0]), + "translation_y_signed_error_mm": float(translation_signed[1]), + "translation_z_signed_error_mm": float(translation_signed[2]), + "direct_2d_error_px": float(np.linalg.norm(direct - target_2d, axis=-1).mean()), + "mano_projected_2d_error_px": float( + np.linalg.norm(projected[time_index, hand] - target_2d, axis=-1).mean() + ), + "direct_mano_2d_consistency_px": float( + np.linalg.norm(direct - projected[time_index, hand], axis=-1).mean() + ), + }) + return rows + + +def matched_cache_arrays( + reference: dict[str, np.ndarray], candidate: dict[str, np.ndarray], +) -> bool: + keys = ( + "frame_id", "frame_valid", "K", "target_rotation_matrices", "target_shape", + "target_wrist_translation", "target_joints_camera", "target_vertices_camera", + "target_2d_px", "joint_annotation_valid", "joint_element_valid", + "mano_annotation_valid", + ) + return all(np.array_equal(reference[key], candidate[key], equal_nan=True) for key in keys) + + +def aggregate_static(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + output = [] + group_fields: dict[str, str | None] = { + "all": None, "side": "side", "hand_size": "hand_size_bucket", + "wrist_depth": "wrist_depth_bucket", + } + for condition in CONDITIONS: + condition_rows = [row for row in rows if row["condition"] == condition] + for group, field in group_fields.items(): + values = ["all"] if field is None else sorted({str(row[field]) for row in condition_rows}) + for value in values: + selected = condition_rows if field is None else [ + row for row in condition_rows if str(row[field]) == value + ] + for metric in STATIC_METRICS: + output.append({ + "condition": condition, "group": group, "value": value, + "metric": metric, + **distribution_summary([float(row[metric]) for row in selected]), + }) + return output + + +def take_metric_rows( + static_rows: list[dict[str, Any]], dynamic: dict[tuple[str, str], dict[str, list[float]]], +) -> list[dict[str, Any]]: + output = [] + takes = sorted({str(row["take"]) for row in static_rows}) + for condition in CONDITIONS: + for take in takes: + selected = [ + row for row in static_rows + if row["condition"] == condition and row["take"] == take + ] + for metric in STATIC_METRICS: + output.append({ + "condition": condition, "take": take, "metric": metric, + **distribution_summary([float(row[metric]) for row in selected]), + }) + for metric, observations in sorted(dynamic[(condition, take)].items()): + output.append({ + "condition": condition, "take": take, "metric": metric, + **distribution_summary(observations), + }) + return output + + +def paired_take_bootstrap( + take_rows: list[dict[str, Any]], samples: int = 10_000, seed: int = 20260716, +) -> list[dict[str, Any]]: + index = { + (row["condition"], row["take"], row["metric"]): float(row["mean"]) + for row in take_rows + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(CONDITIONS[1:]): + for metric_index, metric in enumerate(metrics): + pairs = [ + (index[(condition, take, metric)], index[("complete", take, metric)]) + for take in takes + if (condition, take, metric) in index and ("complete", take, metric) in index + ] + if not pairs: + continue + delta = np.asarray([missing - complete for missing, complete in pairs]) + rng = np.random.default_rng(np.random.SeedSequence((seed, condition_index, metric_index))) + bootstrap = delta[rng.integers(0, len(delta), size=(samples, len(delta)))].mean(axis=1) + output.append({ + "reference": "complete", "condition": condition, "metric": metric, + "takes": len(delta), "condition_minus_reference": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def load_manifest( + path: Path, expected_condition: str, expected_scope: str = "full", +) -> dict[str, Any]: + manifest = json.loads(path.read_text(encoding="utf-8")) + condition = manifest.get("input_condition", "complete") + if ( + manifest.get("status") != "complete" or manifest.get("scope") != expected_scope + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + or condition != expected_condition + ): + raise ValueError(f"invalid {expected_condition} cache manifest") + if expected_scope == "full" and ( + manifest.get("frames") != 11638 or manifest.get("clips") != 1495 + ): + raise ValueError(f"invalid {expected_condition} full-cache coverage") + return manifest + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--complete-cache", type=Path, required=True) + parser.add_argument("--missing-depth-cache", type=Path, required=True) + parser.add_argument("--missing-k-cache", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--scope", choices=("full", "smoke"), default="full") + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("missing-modality evaluation output must be new or empty") + cache_dirs = { + "complete": args.complete_cache, + "missing_depth": args.missing_depth_cache, + "missing_k": args.missing_k_cache, + } + manifests = { + condition: load_manifest(path / "cache_manifest.json", condition, args.scope) + for condition, path in cache_dirs.items() + } + coverage = {(manifest["clips"], manifest["frames"]) for manifest in manifests.values()} + if len(coverage) != 1: + raise ValueError("missing-modality cache coverage differs") + checkpoint_hashes = {manifest["checkpoint"]["sha256"] for manifest in manifests.values()} + manifest_hashes = {manifest["manifest"]["sha256"] for manifest in manifests.values()} + if len(checkpoint_hashes) != 1 or len(manifest_hashes) != 1: + raise ValueError("missing-modality caches do not share checkpoint/split") + takes_by_condition = { + condition: {record["take"]: record for record in manifest["takes"]} + for condition, manifest in manifests.items() + } + if any(set(records) != set(takes_by_condition["complete"]) for records in takes_by_condition.values()): + raise ValueError("missing-modality cache take grids differ") + static_rows: list[dict[str, Any]] = [] + dynamic: dict[tuple[str, str], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for take in sorted(takes_by_condition["complete"]): + arrays_by_condition = {} + for condition in CONDITIONS: + record = takes_by_condition[condition][take] + path = Path(record["path"]) + if sha256(path) != record["sha256"]: + raise ValueError(f"cache take hash mismatch: {path}") + arrays_by_condition[condition] = load_npz(path) + reference = arrays_by_condition["complete"] + for condition, arrays in arrays_by_condition.items(): + if condition != "complete" and not matched_cache_arrays(reference, arrays): + raise ValueError(f"cache frame/GT mismatch: {take}/{condition}") + static_rows.extend(frame_rows(arrays, condition)) + selected = arrays["frame_valid"].astype(bool) + temporal = temporal_metrics( + arrays, arrays["pred_joints_camera"], arrays["pred_direct_2d_px"], selected, + ) + identity = identity_switch_metrics(arrays, arrays["pred_joints_camera"], selected) + for metric, observations in {**temporal, **identity}.items(): + dynamic[(condition, take)][metric].extend( + float(value) for value in observations if np.isfinite(value) + ) + + group_rows = aggregate_static(static_rows) + take_rows = take_metric_rows(static_rows, dynamic) + bootstrap = paired_take_bootstrap(take_rows, samples=args.bootstrap_samples) + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", static_rows) + write_csv(args.output_dir / "group_metrics.csv", group_rows) + write_csv(args.output_dir / "take_metrics.csv", take_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap) + overview_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", "direct_2d_error_px", + "mano_projected_2d_error_px", + ) + overview = { + condition: { + metric: next( + row for row in group_rows + if row["condition"] == condition and row["group"] == "all" and row["metric"] == metric + ) + for metric in overview_metrics + } + for condition in CONDITIONS + } + report = { + "status": "evaluated", + "experiment_class": "preregistered_missing_modality_fallback_diagnostic", + "result_role": "true_coarse_model_input_ablation", + "reference": "complete", + "conditions": list(CONDITIONS), + "scope": args.scope, + "checkpoint_sha256": next(iter(checkpoint_hashes)), + "cache_manifests": { + condition: {"path": str((path / "cache_manifest.json").resolve()), "sha256": sha256(path / "cache_manifest.json")} + for condition, path in cache_dirs.items() + }, + "overview": overview, + "missing_rgb_status": "unsupported_no_rgb_availability_or_training_dropout", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "conditions": report["conditions"], + "frames": manifests["complete"]["frames"], "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_harm_risk.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..42c2af30c8069268484c386d654a282509505b07 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_harm_risk.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""Run the single frozen validation comparison for the OOF harm-risk gate.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import joblib +import numpy as np + +from foundation_hand.evaluation.harm_risk import ( + HARM_RISK_FEATURE_NAMES, + harm_risk_features, +) +from scripts.evaluate_phase6_mixed_projection import ( + METRICS, + aggregate_rows, + sha256, + take_rows, + write_csv, +) + + +ALWAYS = "coarse_wrist_ray__z_calibrated_always" +RISK = "coarse_wrist_ray__z_harm_risk" +SPECS = [ + {"id": "direct_xyz_coarse__z_coarse", "assembly": "direct_xyz_coarse", "z_mode": "coarse"}, + {"id": "direct_xyz_z_only__z_calibrated_always", "assembly": "direct_xyz_z_only", "z_mode": "calibrated_always"}, + {"id": ALWAYS, "assembly": "coarse_wrist_ray", "z_mode": "calibrated_always"}, + {"id": RISK, "assembly": "coarse_wrist_ray", "z_mode": "calibrated_confidence_0p6"}, +] + + +def paired_take_bootstrap( + rows: list[dict[str, object]], *, samples: int = 10_000, seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + output = [] + rng = np.random.default_rng(seed) + for metric in METRICS: + delta = [] + for take in takes: + candidate = [ + float(row[metric]) for row in rows + if row["condition"] == RISK and row["take"] == take + ] + reference = [ + float(row[metric]) for row in rows + if row["condition"] == ALWAYS and row["take"] == take + ] + delta.append(float(np.mean(candidate) - np.mean(reference))) + values = np.asarray(delta) + indices = rng.integers(0, len(values), size=(samples, len(values))) + boot = values[indices].mean(axis=1) + output.append({ + "condition": RISK, "reference": ALWAYS, "metric": metric, + "takes": len(takes), "delta_mean": float(values.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-dir", type=Path, required=True) + parser.add_argument("--risk-selection", type=Path, required=True) + parser.add_argument("--risk-package", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + cache_path = args.cache_dir / "cache_manifest.json" + alignment_path = args.alignment_dir / "evaluation.json" + cache = json.loads(cache_path.read_text(encoding="utf-8")) + alignment_report = json.loads(alignment_path.read_text(encoding="utf-8")) + risk_report = json.loads(args.risk_selection.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("scope") != "full" + or cache.get("official_test_used") is not False + or alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_path) + or risk_report.get("status") != "admitted_for_one_frozen_validation" + or risk_report.get("official_validation_used") is not False + or risk_report.get("official_test_used") is not False + or risk_report.get("package", {}).get("sha256") != sha256(args.risk_package) + ): + raise ValueError("cache/alignment/OOF-risk isolation contract failed") + package = joblib.load(args.risk_package) + if tuple(package["feature_names"]) != HARM_RISK_FEATURE_NAMES: + raise ValueError("risk package feature schema mismatch") + thresholds = package["selected_thresholds"] + if thresholds is None or thresholds != { + "expected_gain_threshold_mm": risk_report["selected"]["expected_gain_threshold_mm"], + "harm_probability_threshold": risk_report["selected"]["harm_probability_threshold"], + }: + raise ValueError("risk thresholds differ from frozen OOF selection") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + all_rows = [] + coverage_rows = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + raw_path = Path(take_record["path"]) + if sha256(raw_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {raw_path}") + with np.load(raw_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + diagnostic_path = args.alignment_dir / "predictions" / raw_path.name + with np.load(diagnostic_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + if not np.array_equal(arrays["frame_id"], alignment["frame_id"]): + raise ValueError(f"alignment frame mismatch: {raw_path}") + available = alignment["alignment_applied"].astype(bool) + calibrated = np.where(available, alignment["calibrated_delta_z_m"], 0.0) + raw = np.where(available, alignment["raw_alignment_delta_z_m"], 0.0) + features = harm_risk_features( + calibrated_delta_z_m=calibrated, + raw_delta_z_m=raw, + confidence=alignment["confidence"], + alignment_available=available, + raw_alignment_available=available, + valid_support_count=alignment["support"], + projected_support_count=alignment["projected_support"], + inlier_ratio=alignment["inlier_ratio"], + residual_scale_m=alignment["residual_scale_m"], + valid_fraction=alignment["valid_fraction"], + foreground_fraction=alignment["foreground_fraction"], + background_fraction=alignment["background_fraction"], + depth_discontinuity_m=alignment["depth_discontinuity_m"], + conditioning_quality=alignment["quality"], + silhouette_overlap_fraction=alignment["silhouette_overlap_fraction"], + coarse_hand_scale_px=alignment["coarse_hand_scale_px"], + coarse_direct_mano_consistency_px=alignment[ + "coarse_direct_mano_consistency_px" + ], + coarse_wrist_translation=arrays["pred_wrist_translation"], + coarse_wrist_velocity_m_per_frame=alignment[ + "coarse_wrist_velocity_m_per_frame" + ], + predicted_depth_order=alignment["predicted_depth_order"], + ) + flat = features.reshape(-1, features.shape[-1]) + expected_gain = package["regressor"].predict(flat).reshape(features.shape[:2]) + harm_probability = package["classifier"].predict_proba(flat)[:, 1].reshape( + features.shape[:2] + ) + gate = ( + available + & (expected_gain >= thresholds["expected_gain_threshold_mm"]) + & (harm_probability <= thresholds["harm_probability_threshold"]) + ) + risk_alignment = dict(alignment) + risk_alignment["gated_delta_z_m"] = np.where(gate, calibrated, 0.0) + rows, saved = take_rows(arrays, risk_alignment, SPECS) + all_rows.extend(rows) + coverage_rows.append({ + "take": str(arrays["take"]), "samples": int(gate.size), + "available": int(available.sum()), "applied": int(gate.sum()), + "coverage": float(gate.mean()), + "mean_expected_gain_mm": float(expected_gain.mean()), + "mean_harm_probability": float(harm_probability.mean()), + }) + output = prediction_root / raw_path.name + np.savez_compressed( + output, **saved, expected_gain_mm=expected_gain.astype(np.float32), + harm_probability=harm_probability.astype(np.float32), risk_gate=gate, + risk_delta_z_m=np.where(gate, calibrated, 0.0), + ) + take_records.append({ + "take": str(arrays["take"]), "frames": len(arrays["frame_id"]), + "path": str(output), "sha256": sha256(output), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + aggregate = aggregate_rows(all_rows, SPECS) + paired = paired_take_bootstrap(all_rows) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "coverage_by_take.csv", coverage_rows) + primary = { + row["condition"]: row for row in aggregate + if row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm" + } + report = { + "status": "evaluated_single_frozen_oof_risk_policy", + "experiment": "P6_S3_harm_aware_risk_gate", + "experiment_class": "exploratory_deployable_frozen_oof_policy", + "official_validation_used": True, + "official_validation_used_for_threshold_selection": False, + "official_test_used": False, + "oracle_information": False, + "conditions": SPECS, + "risk_thresholds": thresholds, + "coverage": float(sum(row["applied"] for row in coverage_rows) / sum( + row["samples"] for row in coverage_rows + )), + "always_absolute_mpjpe_mm": float(primary[ALWAYS]["mean"]), + "risk_absolute_mpjpe_mm": float(primary[RISK]["mean"]), + "absolute_delta_mm": float(primary[RISK]["mean"] - primary[ALWAYS]["mean"]), + "new_rank_one": float(primary[RISK]["mean"]) < 19.174950061401493, + "cache_manifest": {"path": str(cache_path.resolve()), "sha256": sha256(cache_path)}, + "alignment_evaluation": { + "path": str(alignment_path.resolve()), "sha256": sha256(alignment_path), + }, + "risk_selection": { + "path": str(args.risk_selection.resolve()), "sha256": sha256(args.risk_selection), + }, + "risk_package": {"path": str(args.risk_package.resolve()), "sha256": sha256(args.risk_package)}, + "checkpoint": cache["checkpoint"], "calibrator": alignment_report["calibrator"], + "takes": take_records, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..cf5426ac585026170b1b28ff18476ce0d6656dcb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_mixed_projection.py @@ -0,0 +1,471 @@ +#!/usr/bin/env python3 +"""Evaluate frozen Phase 6 mixed-projection assemblies on validation caches.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.mixed_projection import ( + coarse_wrist_ray_translation, + direct_wrist_ray_translation, + solve_mixed_projection_batch, +) + + +FINGERTIPS = (4, 8, 12, 16, 20) +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + "direct_2d_error_px", + "projected_mano_2d_px", + "direct_mano_consistency_px", +) +REFERENCE = "direct_xyz_z_only__z_calibrated_always" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def condition_specs(selection: dict[str, Any]) -> list[dict[str, object]]: + winner = selection["winner"] + support = int(winner["minimum_support"]) + delta = float(winner["huber_delta_px"]) + output: list[dict[str, object]] = [ + {"id": "direct_xyz_coarse__z_coarse", "assembly": "direct_xyz_coarse", "z_mode": "coarse"}, + {"id": REFERENCE, "assembly": "direct_xyz_z_only", "z_mode": "calibrated_always"}, + {"id": "direct_xyz_z_only__z_raw_alignment", "assembly": "direct_xyz_z_only", "z_mode": "raw_alignment"}, + {"id": "direct_xyz_z_only__z_calibrated_confidence_0p6", "assembly": "direct_xyz_z_only", "z_mode": "calibrated_confidence_0p6"}, + ] + for z_mode in ( + "coarse", "raw_alignment", "calibrated_always", "calibrated_confidence_0p6", + ): + output.extend(( + {"id": f"coarse_wrist_ray__z_{z_mode}", "assembly": "coarse_wrist_ray", "z_mode": z_mode}, + {"id": f"direct_2d_wrist_ray__z_{z_mode}", "assembly": "direct_2d_wrist_ray", "z_mode": z_mode}, + { + "id": f"mixed_wls_s{support}__z_{z_mode}", + "assembly": "mixed_projection_21j_wls", "z_mode": z_mode, + "minimum_support": support, "huber_delta_px": None, + }, + { + "id": f"mixed_huber_d{delta:g}_s{support}__z_{z_mode}", + "assembly": "robust_mixed_projection", "z_mode": z_mode, + "minimum_support": support, "huber_delta_px": delta, + }, + )) + return output + + +def correction_grid(alignment: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + available = alignment["alignment_applied"].astype(bool) + raw = np.where(available, alignment["raw_alignment_delta_z_m"], 0.0) + calibrated = np.where(available, alignment["calibrated_delta_z_m"], 0.0) + confidence = np.where(available, alignment["gated_delta_z_m"], 0.0) + return { + "coarse": np.zeros_like(raw), + "raw_alignment": raw, + "calibrated_always": calibrated, + "calibrated_confidence_0p6": confidence, + } + + +def project(points: np.ndarray, K: np.ndarray) -> np.ndarray: + z = np.maximum(points[..., 2], 1e-8) + return np.stack(( + K[:, None, 0, 0] * points[..., 0] / z + K[:, None, 0, 2], + K[:, None, 1, 1] * points[..., 1] / z + K[:, None, 1, 2], + ), axis=-1) + + +def assemble( + spec: dict[str, object], + *, + coarse: np.ndarray, + root_relative_joints: np.ndarray, + anchors: np.ndarray, + K: np.ndarray, + z: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + direct = coarse.copy() + direct[:, 2] = z + ray = coarse_wrist_ray_translation(coarse, z) + assembly = spec["assembly"] + diagnostics: dict[str, np.ndarray] = {} + if assembly in {"direct_xyz_coarse", "direct_xyz_z_only"}: + return direct, diagnostics + if assembly == "coarse_wrist_ray": + return ray, diagnostics + if assembly == "direct_2d_wrist_ray": + translation, valid = direct_wrist_ray_translation(anchors, K, z, ray) + diagnostics.update({"success": valid, "failure_reason": np.where(valid, "ok", "invalid_k_or_anchor")}) + return translation, diagnostics + result = solve_mixed_projection_batch( + root_relative_joints, anchors, K, z, ray, + image_hw=(368, 640), minimum_support=int(spec["minimum_support"]), + robust_huber_delta_px=( + None if spec["huber_delta_px"] is None else float(spec["huber_delta_px"]) + ), + ) + diagnostics.update({ + "support_count": result.support_count, + "residual_scale_px": result.residual_scale_px, + "conditioning": result.conditioning, + "inlier_ratio": result.inlier_ratio, + "uncertainty_x_m": result.uncertainty_xy_m[:, 0], + "uncertainty_y_m": result.uncertainty_xy_m[:, 1], + "success": result.failure_reason == "ok", + "failure_reason": result.failure_reason, + }) + return result.translation_m, diagnostics + + +def hand_size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def take_rows( + arrays: dict[str, np.ndarray], + alignment: dict[str, np.ndarray], + specs: list[dict[str, object]], +) -> tuple[list[dict[str, object]], dict[str, np.ndarray]]: + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + time_index, hand = np.where(valid) + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + coarse_joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + coarse_vertices = arrays["pred_vertices_camera"][time_index, hand].astype(np.float64) + root_relative = coarse_joints - coarse_joints[:, :1] + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + K = arrays["K"][time_index].astype(np.float64) + corrections = correction_grid(alignment) + coarse_projected = project(coarse_joints, K) + scale = np.ptp(coarse_projected, axis=1).max(axis=-1) + frame_rows = [] + saved: dict[str, list[np.ndarray]] = defaultdict(list) + for spec in specs: + condition = str(spec["id"]) + z_mode = str(spec["z_mode"]) + z = coarse[:, 2] + corrections[z_mode][time_index, hand] + translation, diagnostics = assemble( + spec, coarse=coarse, root_relative_joints=root_relative, + anchors=anchors, K=K, z=z, + ) + shift = translation - coarse + joints = coarse_joints + shift[:, None] + vertices = coarse_vertices + shift[:, None] + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_vertices = arrays["target_vertices_camera"][time_index, hand].astype(np.float64) + target_translation = arrays["target_wrist_translation"][time_index, hand].astype(np.float64) + target_2d = arrays["target_2d_px"][time_index, hand].astype(np.float64) + projected = project(joints, K) + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (joints - joints[:, :1]) - (target_joints - target_joints[:, :1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (vertices - joints[:, :1]) - (target_vertices - target_joints[:, :1]), axis=-1, + ) * 1000.0 + signed_translation = (translation - target_translation) * 1000.0 + success = diagnostics.get("success", np.ones(len(translation), dtype=bool)) + failure = diagnostics.get("failure_reason", np.full(len(translation), "ok")) + support = diagnostics.get("support_count", np.full(len(translation), 21)) + residual_scale = diagnostics.get("residual_scale_px", np.zeros(len(translation))) + conditioning = diagnostics.get("conditioning", np.ones(len(translation))) + inlier_ratio = diagnostics.get("inlier_ratio", np.ones(len(translation))) + uncertainty_x = diagnostics.get("uncertainty_x_m", np.zeros(len(translation))) + uncertainty_y = diagnostics.get("uncertainty_y_m", np.zeros(len(translation))) + for index in range(len(translation)): + current_time, current_hand = int(time_index[index]), int(hand[index]) + direct_error = np.linalg.norm(anchors[index] - target_2d[index], axis=-1).mean() + projected_error = np.linalg.norm(projected[index] - target_2d[index], axis=-1).mean() + consistency = np.linalg.norm(projected[index] - anchors[index], axis=-1).mean() + frame_rows.append({ + "condition": condition, + "assembly": spec["assembly"], + "z_mode": z_mode, + "take": take, + "subject": take.split("/")[0], + "action_family": take.split("/")[1], + "frame_id": int(arrays["frame_id"][current_time]), + "side": "right" if current_hand else "left", + "hand_size_bucket": hand_size_bucket(float(scale[index])), + "depth_bucket": depth_bucket(float(target_translation[index, 2])), + "absolute_mpjpe_mm": float(joint_error[index].mean()), + "root_relative_mpjpe_mm": float(root_joint_error[index].mean()), + "absolute_mpvpe_mm": float(vertex_error[index].mean()), + "root_relative_mpvpe_mm": float(root_vertex_error[index].mean()), + "fingertip_mpjpe_mm": float(joint_error[index, FINGERTIPS].mean()), + "translation_x_mae_mm": abs(float(signed_translation[index, 0])), + "translation_y_mae_mm": abs(float(signed_translation[index, 1])), + "translation_z_mae_mm": abs(float(signed_translation[index, 2])), + "translation_x_signed_error_mm": float(signed_translation[index, 0]), + "translation_y_signed_error_mm": float(signed_translation[index, 1]), + "translation_z_signed_error_mm": float(signed_translation[index, 2]), + "direct_2d_error_px": float(direct_error), + "projected_mano_2d_px": float(projected_error), + "direct_mano_consistency_px": float(consistency), + "applied_delta_z_mm": float(1000.0 * corrections[z_mode][current_time, current_hand]), + "support_count": int(support[index]), + "residual_scale_px": float(residual_scale[index]), + "conditioning": float(conditioning[index]), + "inlier_ratio": float(inlier_ratio[index]), + "uncertainty_x_mm": float(1000.0 * uncertainty_x[index]), + "uncertainty_y_mm": float(1000.0 * uncertainty_y[index]), + "solve_success": bool(success[index]), + "failure_reason": str(failure[index]), + }) + saved[f"translation__{condition}"].append(translation.astype(np.float32)) + saved[f"success__{condition}"].append(success.astype(bool)) + saved_arrays: dict[str, np.ndarray] = { + "frame_id": arrays["frame_id"], + "valid_time_index": time_index.astype(np.int64), + "valid_hand_index": hand.astype(np.int64), + } + saved_arrays.update({key: value[0] for key, value in saved.items()}) + return frame_rows, saved_arrays + + +def aggregate_rows( + rows: list[dict[str, object]], specs: list[dict[str, object]], +) -> list[dict[str, object]]: + output = [] + for spec in specs: + condition = str(spec["id"]) + selected = [row for row in rows if row["condition"] == condition] + for metric in METRICS: + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row[metric] for row in selected), + }) + for group in ("side", "hand_size_bucket", "depth_bucket", "take", "action_family"): + for value in sorted({str(row[group]) for row in selected}): + grouped = [row for row in selected if str(row[group]) == value] + for metric in METRICS: + output.append({ + "condition": condition, "group": group, "value": value, + "metric": metric, + **distribution_summary(row[metric] for row in grouped), + }) + output.append({ + "condition": condition, "group": "all", "value": "all", + "metric": "solve_success_fraction", + **distribution_summary(float(row["solve_success"]) for row in selected), + }) + return output + + +def paired_take_bootstrap( + rows: list[dict[str, object]], specs: list[dict[str, object]], + *, samples: int = 10_000, seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + take_mean: dict[tuple[str, str, str], float] = {} + for spec in specs: + condition = str(spec["id"]) + for take in takes: + selected = [row for row in rows if row["condition"] == condition and row["take"] == take] + for metric in METRICS: + take_mean[(condition, take, metric)] = float(np.mean([row[metric] for row in selected])) + output = [] + rng = np.random.default_rng(seed) + for spec in specs: + condition = str(spec["id"]) + if condition == REFERENCE: + continue + for metric in METRICS: + delta = np.asarray([ + take_mean[(condition, take, metric)] - take_mean[(REFERENCE, take, metric)] + for take in takes + ]) + indices = rng.integers(0, len(delta), size=(samples, len(delta))) + boot = delta[indices].mean(axis=1) + output.append({ + "condition": condition, "reference": REFERENCE, "metric": metric, + "takes": len(takes), "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-dir", type=Path, required=True) + parser.add_argument("--oof-selection", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + cache_manifest_path = args.cache_dir / "cache_manifest.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + alignment_report_path = args.alignment_dir / "evaluation.json" + alignment_report = json.loads(alignment_report_path.read_text(encoding="utf-8")) + selection = json.loads(args.oof_selection.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("scope") != "full" + or cache.get("official_test_used") is not False + or alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + or selection.get("status") != "selected_oof_only" + or selection.get("official_validation_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("cache/alignment/OOF isolation contract failed") + specs = condition_specs(selection) + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_dir = args.output_dir / "predictions" + prediction_dir.mkdir() + all_rows = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + alignment_path = args.alignment_dir / "predictions" / take_path.name + with np.load(alignment_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + if not np.array_equal(arrays["frame_id"], alignment["frame_id"]): + raise ValueError(f"alignment frame mismatch: {take_path}") + rows, saved = take_rows(arrays, alignment, specs) + all_rows.extend(rows) + output_path = prediction_dir / take_path.name + np.savez_compressed(output_path, **saved) + take_records.append({ + "take": str(arrays["take"]), "frames": len(arrays["frame_id"]), + "path": str(output_path), "sha256": sha256(output_path), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + aggregate = aggregate_rows(all_rows, specs) + paired = paired_take_bootstrap(all_rows, specs) + reference_rows = { + (row["take"], row["frame_id"], row["side"]): row + for row in all_rows if row["condition"] == REFERENCE + } + case_rows = [] + for spec in specs: + condition = str(spec["id"]) + if condition == REFERENCE: + continue + selected = [row for row in all_rows if row["condition"] == condition] + deltas = np.asarray([ + float(row["absolute_mpjpe_mm"]) + - float(reference_rows[(row["take"], row["frame_id"], row["side"])]["absolute_mpjpe_mm"]) + for row in selected + ]) + for role, indices in ( + ("largest_gain", np.argsort(deltas)[:10]), + ("largest_harm", np.argsort(deltas)[-10:][::-1]), + ): + for rank, index in enumerate(indices, start=1): + row = selected[int(index)] + case_rows.append({ + "condition": condition, "role": role, "rank": rank, + "take": row["take"], "frame_id": row["frame_id"], "side": row["side"], + "absolute_delta_mm": float(deltas[index]), + "candidate_absolute_mpjpe_mm": row["absolute_mpjpe_mm"], + "reference_absolute_mpjpe_mm": reference_rows[ + (row["take"], row["frame_id"], row["side"]) + ]["absolute_mpjpe_mm"], + "support_count": row["support_count"], + "residual_scale_px": row["residual_scale_px"], + "conditioning": row["conditioning"], + "inlier_ratio": row["inlier_ratio"], + "failure_reason": row["failure_reason"], + }) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "largest_gain_harm.csv", case_rows) + primary_rows = [ + row for row in aggregate + if row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm" + ] + best = min(primary_rows, key=lambda row: float(row["mean"])) + reference = next(row for row in primary_rows if row["condition"] == REFERENCE) + guardrail = min(0.2, 0.01 * float(reference["mean"])) + report = { + "status": "evaluated_frozen_oof_selection", + "experiment": "P6_S1_cache_mixed_projection", + "experiment_class": "preregistered_cache_only_deployable_ablation", + "official_validation_used": True, + "official_validation_used_for_solver_constant_selection": False, + "official_test_used": False, + "oracle_information": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "alignment_evaluation": {"path": str(alignment_report_path.resolve()), "sha256": sha256(alignment_report_path)}, + "oof_selection": {"path": str(args.oof_selection.resolve()), "sha256": sha256(args.oof_selection)}, + "checkpoint": cache["checkpoint"], + "calibrator": alignment_report["calibrator"], + "conditions": specs, + "reference_condition": REFERENCE, + "reference_absolute_mpjpe_mm": float(reference["mean"]), + "best_condition": best["condition"], + "best_absolute_mpjpe_mm": float(best["mean"]), + "best_delta_mm": float(best["mean"] - reference["mean"]), + "new_rank_one": float(best["mean"]) < 19.45484110440441, + "geometry_secondary_guardrail_passed": float(best["mean"]) <= float(reference["mean"]) + guardrail, + "takes": take_records, + "outputs": { + "per_hand": "per_hand_frame_metrics.csv", "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "largest_gain_harm": "largest_gain_harm.csv", "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "reference": report["reference_absolute_mpjpe_mm"], + "best_condition": report["best_condition"], "best": report["best_absolute_mpjpe_mm"], + "new_rank_one": report["new_rank_one"], "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_pa_mpjpe.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_pa_mpjpe.py new file mode 100644 index 0000000000000000000000000000000000000000..59e3ad31371664ffe62f535f94ff288f2eaece36 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_pa_mpjpe.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Evaluate seed17 rigid and standard Procrustes-aligned MPJPE.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def summary(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": len(array), "mean": float(array.mean()), + "p50": float(np.percentile(array, 50)), + "p95": float(np.percentile(array, 95)), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + ): + raise ValueError("raw cache isolation contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + values: dict[str, list[float]] = defaultdict(list) + rows = [] + for take_record in manifest["takes"]: + path = Path(take_record["path"]) + if sha256(path) != take_record["sha256"]: + raise ValueError(f"cache take hash mismatch: {path}") + with np.load(path, allow_pickle=False) as archive: + predicted = archive["pred_joints_camera"] + target = archive["target_joints_camera"] + valid = archive["joint_annotation_valid"].astype(bool) & archive[ + "frame_valid" + ][:, None].astype(bool) + frame_ids = archive["frame_id"] + take = str(archive["take"]) + for hand, side in enumerate(("left", "right")): + indices = np.where(valid[:, hand])[0] + rigid = aligned_mpjpe_mm( + predicted[indices, hand], target[indices, hand], estimate_scale=False, + ) + similarity = aligned_mpjpe_mm( + predicted[indices, hand], target[indices, hand], estimate_scale=True, + ) + values["rigid_aligned_mpjpe_mm"].extend(rigid.tolist()) + values["pa_mpjpe_mm"].extend(similarity.tolist()) + values[f"{side}_rigid_aligned_mpjpe_mm"].extend(rigid.tolist()) + values[f"{side}_pa_mpjpe_mm"].extend(similarity.tolist()) + rows.extend({ + "take": take, "frame_id": int(frame_ids[index]), "side": side, + "rigid_aligned_mpjpe_mm": float(rigid[position]), + "pa_mpjpe_mm": float(similarity[position]), + } for position, index in enumerate(indices)) + with (args.output_dir / "per_hand_frame_metrics.csv").open( + "x", newline="", encoding="utf-8", + ) as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "evaluated", + "experiment": "P6_pose_alignment_metric_addendum", + "official_test_used": False, + "metric_definitions": { + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation, and scale", + "rigid_aligned_mpjpe_mm": "per-hand SE(3) Kabsch; removes translation and rotation only", + }, + "translation_only_system_invariance": True, + "metrics": {key: summary(items) for key, items in values.items()}, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_state_ray.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_state_ray.py new file mode 100644 index 0000000000000000000000000000000000000000..a44aac603af5f949a790d4f714314f029344abdf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase6_state_ray.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Compose frozen causal-state z estimates with the coarse wrist camera ray.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.mixed_projection import coarse_wrist_ray_translation +from scripts.evaluate_phase4_jitter import ( + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, +) +from scripts.evaluate_phase5_causal_state import response_diagnostics +from scripts.evaluate_phase6_mixed_projection import METRICS, aggregate_rows, take_rows + + +STATE_CONDITIONS = ( + "coarse", + "calibrated_per_frame", + "ema_alpha0.6", + "butterworth_2hz", + "fixed_kalman", + "uncertainty_kalman", +) +REFERENCE = "calibrated_per_frame__coarse_wrist_ray" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def assemble_state_ray_geometry( + coarse_translation_m: np.ndarray, + coarse_joints_m: np.ndarray, + coarse_vertices_m: np.ndarray, + state_z_m: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Preserve each coarse wrist ray and rigidly translate its hand geometry.""" + + coarse_translation = np.asarray(coarse_translation_m, dtype=np.float64) + state_z = np.asarray(state_z_m, dtype=np.float64) + safe_z = np.where( + np.isfinite(state_z) & (state_z > 0.05), + state_z, + coarse_translation[..., 2], + ) + translation = coarse_wrist_ray_translation(coarse_translation, safe_z) + shift = translation - coarse_translation + joints = np.asarray(coarse_joints_m, dtype=np.float64) + shift[..., None, :] + vertices = np.asarray(coarse_vertices_m, dtype=np.float64) + shift[..., None, :] + return translation, joints, vertices + + +def paired_bootstrap( + rows: list[dict[str, object]], + conditions: list[str], + *, + samples: int, + seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + means: dict[tuple[str, str, str], float] = {} + for condition in conditions: + for take in takes: + selected = [ + row for row in rows + if row["condition"] == condition and row["take"] == take + ] + for metric in METRICS: + means[(condition, take, metric)] = float( + np.mean([float(row[metric]) for row in selected]) + ) + output = [] + for condition_index, condition in enumerate(conditions): + if condition == REFERENCE: + continue + for metric_index, metric in enumerate(METRICS): + delta = np.asarray([ + means[(condition, take, metric)] - means[(REFERENCE, take, metric)] + for take in takes + ]) + rng = np.random.default_rng( + np.random.SeedSequence((seed, condition_index, metric_index)) + ) + bootstrap = delta[ + rng.integers(0, len(delta), size=(samples, len(delta))) + ].mean(axis=1) + output.append({ + "condition": condition, + "reference": REFERENCE, + "metric": metric, + "takes": len(takes), + "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--state-evaluation-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + + cache_manifest_path = args.cache_dir / "cache_manifest.json" + state_report_path = args.state_evaluation_dir / "evaluation.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + state_report = json.loads(state_report_path.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("sequence_mode") != "causal" + or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + or state_report.get("status") != "evaluated" + or state_report.get("official_test_used") is not False + or state_report.get("official_validation_used_for_parameter_selection") is not False + or state_report.get("continuous_take_state") is not True + or state_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + ): + raise ValueError("causal cache/state isolation contract failed") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_dir = args.output_dir / "predictions" + prediction_dir.mkdir() + specs = [ + { + "id": f"{condition}__coarse_wrist_ray", + "assembly": "coarse_wrist_ray", + "z_mode": "calibrated_always", + } + for condition in STATE_CONDITIONS + ] + all_rows: list[dict[str, object]] = [] + temporal_values = { + str(spec["id"]): defaultdict(list) for spec in specs + } + temporal_take_rows: list[dict[str, object]] = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {take_path}") + arrays = load_npz(take_path) + arrays["clip_index"] = np.zeros_like(arrays["clip_index"]) + state_path = args.state_evaluation_dir / "predictions" / take_path.name + state = load_npz(state_path) + if not np.array_equal(arrays["frame_id"], state["frame_id"]): + raise ValueError(f"state frame mismatch: {take_path}") + arrays["_calibrated_measurement_z_m"] = state["calibrated_per_frame_z_m"] + saved: dict[str, np.ndarray] = {"frame_id": arrays["frame_id"]} + for spec, state_condition in zip(specs, STATE_CONDITIONS, strict=True): + condition = str(spec["id"]) + z_m = state[f"{state_condition}_z_m"].astype(np.float64) + correction = z_m - arrays["pred_wrist_translation"][..., 2] + alignment = { + "alignment_applied": np.isfinite(correction), + "raw_alignment_delta_z_m": correction, + "calibrated_delta_z_m": correction, + "gated_delta_z_m": correction, + } + rows, _ = take_rows(arrays, alignment, [spec]) + all_rows.extend(rows) + translation, joints, vertices = assemble_state_ray_geometry( + arrays["pred_wrist_translation"], + arrays["pred_joints_camera"], + arrays["pred_vertices_camera"], + z_m, + ) + selected = arrays["frame_valid"].astype(bool) + _, projected, _ = per_frame_metrics( + arrays, + joints, + vertices, + arrays["pred_rotation_matrices"], + translation, + selected, + ) + values = temporal_metrics(arrays, joints, projected, selected) + identity = identity_switch_metrics(arrays, joints, selected) + values.update(identity) + values.update(response_diagnostics(arrays, z_m)) + for metric, observations in values.items(): + finite = [float(value) for value in observations if np.isfinite(value)] + temporal_values[condition][metric].extend(finite) + temporal_take_rows.append({ + "take": str(arrays["take"]), + "condition": condition, + "metric": metric, + **distribution_summary(finite), + }) + saved[f"translation__{condition}"] = translation.astype(np.float32) + saved[f"z_variance_m2__{condition}"] = state[ + f"{state_condition}_variance_m2" + ].astype(np.float32) + output_path = prediction_dir / take_path.name + np.savez_compressed(output_path, **saved) + take_records.append({ + "take": str(arrays["take"]), + "frames": len(arrays["frame_id"]), + "path": str(output_path), + "sha256": sha256(output_path), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + aggregate = aggregate_rows(all_rows, specs) + conditions = [str(spec["id"]) for spec in specs] + paired = paired_bootstrap( + all_rows, conditions, samples=args.bootstrap_samples, + ) + temporal_rows = [ + {"condition": condition, "metric": metric, **distribution_summary(values)} + for condition in conditions + for metric, values in sorted(temporal_values[condition].items()) + ] + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "temporal_metrics.csv", temporal_rows) + write_csv(args.output_dir / "temporal_take_metrics.csv", temporal_take_rows) + + static_index = { + (str(row["condition"]), str(row["metric"])): row + for row in aggregate if row["group"] == "all" and row["value"] == "all" + } + temporal_index = { + (str(row["condition"]), str(row["metric"])): row for row in temporal_rows + } + overview = [] + for condition in conditions: + row: dict[str, object] = { + "condition": condition, + "absolute_mpjpe_mm": static_index[(condition, "absolute_mpjpe_mm")]["mean"], + "absolute_mpvpe_mm": static_index[(condition, "absolute_mpvpe_mm")]["mean"], + "fingertip_mpjpe_mm": static_index[(condition, "fingertip_mpjpe_mm")]["mean"], + "translation_x_mae_mm": static_index[(condition, "translation_x_mae_mm")]["mean"], + "translation_y_mae_mm": static_index[(condition, "translation_y_mae_mm")]["mean"], + "translation_z_mae_mm": static_index[(condition, "translation_z_mae_mm")]["mean"], + "translation_z_p95_mm": static_index[(condition, "translation_z_mae_mm")]["p95"], + "projected_mano_2d_px": static_index[(condition, "projected_mano_2d_px")]["mean"], + } + for metric in ( + "joint_velocity_error_mm_per_s", + "joint_acceleration_error_mm_per_s2", + "predicted_3d_joint_acceleration_mm_per_s2", + "predicted_3d_joint_jerk_mm_per_s3", + "high_frequency_energy_ratio", + "estimated_causal_lag_frames", + ): + if (condition, metric) in temporal_index: + row[metric] = temporal_index[(condition, metric)]["mean"] + overview.append(row) + reference = next(row for row in overview if row["condition"] == REFERENCE) + for row in overview: + row["absolute_delta_mm"] = float(row["absolute_mpjpe_mm"]) - float( + reference["absolute_mpjpe_mm"] + ) + row["static_guardrail_passed"] = bool( + float(row["absolute_delta_mm"]) <= 0.2 + and float(row["translation_z_mae_mm"]) + <= float(reference["translation_z_mae_mm"]) + 0.2 + and float(row["translation_z_p95_mm"]) + <= float(reference["translation_z_p95_mm"]) + 0.2 + ) + write_csv(args.output_dir / "overview.csv", overview) + report = { + "status": "evaluated_frozen_causal_state_coarse_ray", + "experiment_class": "preregistered_frozen_parameter_causal_state_composition", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + "oracle_information": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "state_evaluation": {"path": str(state_report_path.resolve()), "sha256": sha256(state_report_path)}, + "selection": state_report["selection"], + "assembly": "coarse wrist camera ray recomputed at each frozen state z", + "reference": REFERENCE, + "conditions": conditions, + "takes": take_records, + "outputs": { + "overview": "overview.csv", + "per_hand": "per_hand_frame_metrics.csv", + "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "temporal": "temporal_metrics.csv", + "temporal_takes": "temporal_take_metrics.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": report["status"], "overview": overview}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase7_egodexter_zero_shot.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase7_egodexter_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..d9afe80a0f18d42d100ec440bdaeeb35b14f9e7f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase7_egodexter_zero_shot.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Evaluate a fully frozen Phase 7 model on EgoDexter exactly once.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import time +from typing import Any, Iterator + +import numpy as np +import torch +import yaml + +from foundation_hand.data.egodexter_dataset import ( + EgoDexterSequenceDataset, FINGERTIP_JOINT_INDICES, SEQUENCES, +) +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.train_phase7_external import assert_physical_gpu_idle + + +FINGER_NAMES = ("thumb", "index", "middle", "ring", "little") +MODEL_INPUT_FIELDS = { + "rgb", "depth_m", "depth_pixel_valid", "K", "K_available", + "K_input_available", "depth_available", "depth_input_available", "frame_valid", +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_summary(values: list[float]) -> dict[str, float | int] | None: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if not len(array): + return None + return { + "count": int(len(array)), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + } + + +def validate_freeze_record( + record: dict[str, Any], model_id: str, checkpoint_sha: str, + config_path: Path, inference_mode: str, +) -> dict[str, Any]: + if ( + record.get("status") != "phase7_final_models_frozen" + or record.get("egodexter_used_for_training_or_selection") is not False + or record.get("official_test_used") is not False + ): + raise ValueError("Phase 7 final model set is not EgoDexter-eligible") + models = {item["id"]: item for item in record.get("models", [])} + if model_id not in models: + raise ValueError(f"model is absent from the final freeze: {model_id}") + model = models[model_id] + if model.get("checkpoint_sha256") != checkpoint_sha: + raise ValueError("checkpoint differs from final model freeze") + config_record = model.get("inference_configs", {}).get(inference_mode, {}) + if ( + Path(config_record.get("path", "")).resolve() != config_path.resolve() + or config_record.get("sha256") != sha256(config_path) + ): + raise ValueError("inference config differs from final model freeze") + mapping = record.get("egodexter_sequence_handedness", {}) + if set(mapping) != set(SEQUENCES) or any(side not in {"left", "right"} for side in mapping.values()): + raise ValueError("EgoDexter sequence handedness is not fully frozen") + return model + + +def model_frame(frame: dict[str, object]) -> dict[str, object]: + return {key: frame[key] for key in MODEL_INPUT_FIELDS} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--model-id", required=True) + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--input-mode", choices=("rgb_d_k", "rgb_k", "rgb_only"), required=True) + parser.add_argument("--inference-mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, default=8) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + checkpoint_sha = sha256(args.checkpoint) + freeze = json.loads(args.freeze_record.read_text(encoding="utf-8")) + validate_freeze_record( + freeze, args.model_id, checkpoint_sha, args.config, args.inference_mode, + ) + assert_physical_gpu_idle(args.physical_gpu_id) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + attention_mode = config["model"].get("temporal_attention_mode", "bidirectional") + required_attention = "causal" if args.inference_mode == "causal" else "bidirectional" + if attention_mode != required_attention: + parser.error("inference mode and temporal attention mode differ") + assets = config["assets"] + device = torch.device("cuda") + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + sequence_handedness = freeze["egodexter_sequence_handedness"] + rows: list[dict[str, Any]] = [] + raw_prediction, raw_target, raw_valid = [], [], [] + raw_sequence, raw_frame, raw_side = [], [], [] + maximum_gpu_window = 0 + maximum_cpu_buffer = 0 + total_frames = 0 + started = time.perf_counter() + torch.cuda.reset_peak_memory_stats() + for sequence_index, sequence in enumerate(SEQUENCES): + dataset = EgoDexterSequenceDataset( + args.root, sequence, hand_side=sequence_handedness[sequence], + target_hw=tuple(config["data"]["resolution_hw"]), + ) + targets: list[np.ndarray] = [] + target_valid: list[np.ndarray] = [] + frame_ids: list[int] = [] + + def frames() -> Iterator[dict[str, object]]: + for index in range(len(dataset)): + frame = dataset.frame(index, args.input_mode) + targets.append(frame["target_fingertips_camera_m"].numpy()) + target_valid.append(frame["target_fingertip_valid"].numpy()) + frame_ids.append(int(frame["frame_id"])) + yield model_frame(frame) + + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.inference_mode, window_size=args.window, + offline_stride=(args.window // 2 if args.inference_mode == "offline" else None), + ), + device=device, autocast_dtype=dtype, + ) + output = runner.infer(frames()) + predicted = output["joints_camera"][0, :, dataset.side_index][ + :, FINGERTIP_JOINT_INDICES + ].numpy() + target = np.stack(targets) + valid = np.stack(target_valid) & np.isfinite(predicted).all(axis=-1) + error = np.linalg.norm(predicted - target, axis=-1) * 1000.0 + for frame_index, frame_id in enumerate(frame_ids): + for finger, name in enumerate(FINGER_NAMES): + rows.append({ + "model_id": args.model_id, "sequence": sequence, + "frame_id": frame_id, "hand_side": dataset.hand_side, + "finger": name, "target_visible": bool(valid[frame_index, finger]), + "fingertip_error_mm": ( + float(error[frame_index, finger]) if valid[frame_index, finger] else math.nan + ), + }) + raw_prediction.append(predicted) + raw_target.append(target) + raw_valid.append(valid) + raw_sequence.append(np.full(len(dataset), sequence_index, dtype=np.int16)) + raw_frame.append(np.asarray(frame_ids, dtype=np.int32)) + raw_side.append(np.full(len(dataset), dataset.side_index, dtype=np.int8)) + total_frames += len(dataset) + maximum_gpu_window = max(maximum_gpu_window, runner.maximum_resident_frames) + maximum_cpu_buffer = max(maximum_cpu_buffer, runner.maximum_input_buffer_frames) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + args.output_dir.mkdir(parents=True) + row_path = args.output_dir / "per_fingertip_metrics.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed( + raw_path, predicted_fingertips_camera_m=np.concatenate(raw_prediction), + target_fingertips_camera_m=np.concatenate(raw_target), + target_visible=np.concatenate(raw_valid), sequence_index=np.concatenate(raw_sequence), + frame_id=np.concatenate(raw_frame), side_index=np.concatenate(raw_side), + ) + visible = [row["fingertip_error_mm"] for row in rows if row["target_visible"]] + report = { + "status": "evaluated_frozen_egodexter_zero_shot", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "model_id": args.model_id, "checkpoint_step": int(state["step"]), + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": checkpoint_sha}, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "freeze_record": {"path": str(args.freeze_record.resolve()), "sha256": sha256(args.freeze_record)}, + "input_mode": args.input_mode, "inference_mode": args.inference_mode, + "causal": args.inference_mode == "causal", "window": args.window, + "frames": total_frames, "visible_fingertips": len(visible), + "coverage_fraction": len(visible) / (total_frames * len(FINGER_NAMES)), + "fingertip_error_mm": finite_summary(visible), + "per_finger": { + finger: finite_summary([ + row["fingertip_error_mm"] for row in rows + if row["finger"] == finger and row["target_visible"] + ]) for finger in FINGER_NAMES + }, + "per_sequence": { + sequence: finite_summary([ + row["fingertip_error_mm"] for row in rows + if row["sequence"] == sequence and row["target_visible"] + ]) for sequence in SEQUENCES + }, + "sequence_handedness": sequence_handedness, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": total_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + "maximum_gpu_window_frames": maximum_gpu_window, + "maximum_cpu_input_buffer_frames": maximum_cpu_buffer, + }, + "per_fingertip_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "gt_passed_to_model": False, "per_frame_gt_slot_selection_used": False, + "egodexter_used_for_training_or_selection": False, "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase7_external.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..b067ba132f65bcdbd91712c730da0ff052e1e2f6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase7_external.py @@ -0,0 +1,749 @@ +#!/usr/bin/env python3 +"""Unified held-out evaluation for Phase 7 external-only checkpoints.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import CachedUnifiedClipDataset, collate_h2o_clips +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from foundation_hand.geometry.camera import project_points +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.train_experiment import attach_gt_vertices, move_to_device +from scripts.train_phase7_external import assert_physical_gpu_idle + + +TIP_INDICES = (4, 8, 12, 16, 20) + + +def checkpoint_h2o_training_data_used(checkpoint_extra: dict[str, Any]) -> bool: + """Read H2O exposure without relabelling historical H2O checkpoints.""" + + explicit = checkpoint_extra.get("h2o_training_data_used") + if isinstance(explicit, bool): + return explicit + experiment = checkpoint_extra.get("config", {}).get("experiment", {}) + phase = experiment.get("phase") + # Phase 3-6 checkpoints predate the explicit provenance flag and were + # trained on the canonical H2O train split. + if isinstance(phase, int) and 3 <= phase <= 6: + return True + raise ValueError("checkpoint lacks auditable H2O-training provenance") + + +def validate_evaluation_role( + role: str, config: dict[str, Any], dataset_ids: set[str], + checkpoint_extra: dict[str, Any], cache_manifest: Path, +) -> None: + branch = config.get("experiment", {}).get("branch") + if role == "external_heldout": + if branch != "external_only": + raise ValueError("external evaluation config is not external-only") + if "H2O" in dataset_ids or checkpoint_extra.get("h2o_training_data_used") is not False: + raise ValueError("external evaluator refuses H2O data or training exposure") + elif role == "h2o_train_group_heldout": + if branch != "h2o_adaptation": + raise ValueError("H2O train-heldout evaluation requires an adaptation config") + if dataset_ids != {"H2O"}: + raise ValueError("H2O train-heldout evaluation requires a pure H2O cache") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("adaptation checkpoint lacks H2O-training provenance") + if cache_manifest.name != "train_group_heldout.jsonl": + raise ValueError("adaptation selection requires the frozen train-group-heldout manifest") + elif role == "h2o_train_group_heldout_control": + if dataset_ids != {"H2O"}: + raise ValueError("H2O train-heldout control requires a pure H2O cache") + checkpoint_h2o_training_data_used(checkpoint_extra) + if cache_manifest.name != "train_group_heldout.jsonl": + raise ValueError("H2O control requires the frozen train-group-heldout manifest") + elif role == "adaptation_external_heldout": + if branch != "h2o_adaptation": + raise ValueError("adaptation forgetting evaluation requires an adaptation config") + if not dataset_ids or not dataset_ids.issubset({"HOT3D", "HOI4D", "ARCTIC"}): + raise ValueError("adaptation forgetting evaluation requires pure external held-out data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("adaptation forgetting checkpoint lacks H2O-training provenance") + if "h2o" in str(cache_manifest).lower(): + raise ValueError("adaptation forgetting evaluation refuses H2O cache paths") + elif role == "phase9_external_heldout": + if branch != "phase9_unified": + raise ValueError("Phase 9 external evaluation requires a unified config") + if not dataset_ids or not dataset_ids.issubset({"HOT3D", "HOI4D", "ARCTIC"}): + raise ValueError("Phase 9 external evaluation requires pure external held-out data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("Phase 9 unified checkpoint lacks H2O-training provenance") + if "h2o" in str(cache_manifest).lower(): + raise ValueError("Phase 9 external evaluation refuses H2O cache paths") + elif role == "phase9_h2o_fold_heldout": + fold = str(config.get("experiment", {}).get("h2o_selection_fold", "")) + if branch != "phase9_unified" or not fold: + raise ValueError("Phase 9 fold evaluation requires a fold-specific unified config") + if dataset_ids != {"H2O"}: + raise ValueError("Phase 9 fold evaluation requires pure H2O train-heldout data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("Phase 9 fold checkpoint lacks H2O-training provenance") + expected = f"{fold}_heldout.jsonl" + if cache_manifest.name != expected: + raise ValueError(f"Phase 9 fold cache must be {expected}") + else: + raise ValueError(f"unsupported evaluation role: {role}") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_progress_heartbeat(path: Path | None, value: dict[str, Any]) -> None: + if path is None: + return + payload = { + "schema_version": "phase9_evaluation_progress_heartbeat_v1", + "updated_utc": datetime.now(timezone.utc).isoformat(), + "evaluator_pid": os.getpid(), + "h2o_official_validation_used": False, + "official_test_used": False, + **value, + } + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def direct_child_pids(pid: int) -> list[int]: + path = Path(f"/proc/{pid}/task/{pid}/children") + try: + return sorted(int(value) for value in path.read_text().split()) + except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError): + return [] + + +def finite_summary(values: list[float]) -> dict[str, float | int] | None: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if not len(array): + return None + p95 = float(np.quantile(array, .95)) + tail = array[array >= p95] + return { + "count": int(len(array)), "mean": float(array.mean()), + "median": float(np.median(array)), "p90": float(np.quantile(array, .90)), + "p95": p95, "p99": float(np.quantile(array, .99)), + "cvar95": float(tail.mean()), "max": float(array.max()), + } + + +def tensor_to_numpy(value: torch.Tensor) -> np.ndarray: + """Move persisted floating predictions to a NumPy-supported dtype.""" + value = value.detach().cpu() + if value.is_floating_point() and value.dtype == torch.bfloat16: + value = value.float() + return value.numpy() + + +def append_valid_frame_arrays( + raw: dict[str, list[np.ndarray]], values: dict[str, torch.Tensor], + frame_valid: torch.Tensor, +) -> None: + """Persist variable-length clips on one contiguous valid-frame axis.""" + + valid = tensor_to_numpy(frame_valid.bool()).reshape(-1) + batch, time = frame_valid.shape + for key, value in values.items(): + array = tensor_to_numpy(value) + if array.shape[:2] != (batch, time): + raise ValueError(f"raw temporal field shape differs from frame_valid: {key}") + flattened = array.reshape(batch * time, *array.shape[2:]) + raw.setdefault(key, []).append(flattened[valid]) + + +def hand_size_bucket(size_px: float) -> str: + if size_px < 64.0: + return "small_lt64" + if size_px < 128.0: + return "medium_64_128" + return "large_ge128" + + +def depth_bucket(depth_m: float) -> str: + return "far_gt0.8m" if depth_m > .8 else "near_le0.8m" + + +def apply_input_mode(batch: dict[str, Any], mode: str) -> None: + frame = batch["frame_valid"].bool() + if mode == "rgb_d_k": + batch["K_input_available"] = frame.clone() + elif mode == "rgb_k": + batch["K_input_available"] = frame.clone() + batch["depth_input_available"] = torch.zeros_like(frame) + elif mode == "rgb_only": + batch["K_input_available"] = torch.zeros_like(frame) + batch["depth_input_available"] = torch.zeros_like(frame) + else: + raise ValueError(f"unsupported input mode: {mode}") + batch["K_available"] = batch["K_input_available"] + batch["depth_available"] = batch["depth_input_available"] + + +def grouped_bootstrap( + rows: list[dict[str, Any]], metric: str, seed: int, resamples: int, +) -> dict[str, float | int] | None: + groups: dict[str, list[float]] = {} + for row in rows: + value = row.get(metric) + if value is not None and math.isfinite(float(value)): + groups.setdefault(str(row["physical_recording_id"]), []).append(float(value)) + if not groups: + return None + keys = sorted(groups) + generator = np.random.default_rng(seed) + estimates = [] + for _ in range(resamples): + sampled = generator.choice(keys, size=len(keys), replace=True) + values = [value for key in sampled for value in groups[str(key)]] + estimates.append(float(np.mean(values))) + return { + "groups": len(keys), "resamples": resamples, + "estimate": float(np.mean([value for values in groups.values() for value in values])), + "ci95_low": float(np.quantile(estimates, .025)), + "ci95_high": float(np.quantile(estimates, .975)), + } + + +def metric_fields() -> tuple[str, ...]: + return ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "source_root_relative_mpjpe_mm", + "rigid_se3_mpjpe_mm", "pa_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "direct_2d_error_px", + "projected_mano_2d_error_px", "direct_mano_consistency_px", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "translation_x_signed_mm", "translation_y_signed_mm", "translation_z_signed_mm", + ) + + +def ray_depth_diagnostic_row( + prediction: dict[str, torch.Tensor], batch: dict[str, Any], + batch_index: int, frame: int, side: int, translation_valid: bool, +) -> dict[str, float | bool]: + fields: dict[str, float | bool] = { + "ray_depth_confidence": math.nan, + "ray_depth_raw_delta_z_mm": math.nan, + "ray_depth_applied_delta_z_mm": math.nan, + "ray_depth_support_count": math.nan, + "ray_depth_local_valid_fraction": math.nan, + "ray_depth_correction_valid": False, + "ray_depth_base_z_error_mm": math.nan, + "ray_depth_final_z_error_mm": math.nan, + "ray_depth_harm_mm": math.nan, + } + if "ray_depth_confidence" not in prediction: + return fields + selector = (batch_index, frame, side) + support_count = int(prediction["ray_depth_support_count"][selector]) + fields.update({ + "ray_depth_confidence": float(prediction["ray_depth_confidence"][selector]), + "ray_depth_raw_delta_z_mm": float( + prediction["ray_depth_raw_delta_z_m"][selector] * 1000.0 + ), + "ray_depth_applied_delta_z_mm": float( + prediction["ray_depth_applied_delta_z_m"][selector] * 1000.0 + ), + "ray_depth_support_count": float(support_count), + "ray_depth_local_valid_fraction": support_count / 9.0, + "ray_depth_correction_valid": bool( + prediction["ray_depth_correction_valid"][selector] + ), + }) + if translation_valid: + target_z = batch["wrist_root_translation"][selector][2] + base_error = (prediction["ray_depth_base_z_m"][selector] - target_z).abs() * 1000.0 + final_error = ( + prediction["wrist_root_translation"][selector][2] - target_z + ).abs() * 1000.0 + fields.update({ + "ray_depth_base_z_error_mm": float(base_error), + "ray_depth_final_z_error_mm": float(final_error), + "ray_depth_harm_mm": float(final_error - base_error), + }) + return fields + + +def supervision_coverage(rows: list[dict[str, Any]]) -> dict[str, float | int]: + total = len(rows) + result: dict[str, float | int] = {"hand_rows": total} + for name, field in ( + ("joint3d", "joint3d_supervision"), + ("source_root_relative", "source_root_relative_supervision"), + ("translation", "translation_supervision"), + ("vertices", "vertices_supervision"), + ): + count = sum(bool(row.get(field, False)) for row in rows) + result[f"{name}_valid_hands"] = count + result[f"{name}_valid_fraction"] = count / total if total else 0.0 + return result + + +def make_row( + prediction: dict[str, torch.Tensor], batch: dict[str, Any], + batch_index: int, frame: int, side: int, +) -> dict[str, Any]: + side_name = ("left", "right")[side] + frame_valid = bool(batch["frame_valid"][batch_index, frame]) + translation_valid = frame_valid and bool(batch["translation_valid"][batch_index, frame, side]) + joint_mask = batch["joint3d_valid"][batch_index, frame, side].bool() & frame_valid + joint2d_mask = batch["joint2d_valid"][batch_index, frame, side].bool() & frame_valid + vertices_valid = frame_valid and bool(batch["vertices_valid"][batch_index, frame, side]) + source_relative_mask = torch.zeros_like(joint_mask) + if "joint3d_root_relative_valid" in batch: + source_relative_mask = ( + batch["joint3d_root_relative_valid"][batch_index, frame, side].bool() + & frame_valid + ) + row: dict[str, Any] = { + "dataset": str(batch["dataset_id"][batch_index]), + "subject_id": str(batch["subject_id"][batch_index]), + "physical_recording_id": str(batch["physical_recording_id"][batch_index]), + "camera_id": str(batch["camera_id"][batch_index]), + "headset_id": str(batch["headset_id"][batch_index]), + "frame_id": int(batch["frame_id"][batch_index, frame]), + "side": side_name, + "joint3d_supervision": bool(joint_mask.any()), + "source_root_relative_supervision": bool(source_relative_mask.any()), + "vertices_supervision": vertices_valid, + "translation_supervision": translation_valid, + } + row.update(ray_depth_diagnostic_row( + prediction, batch, batch_index, frame, side, translation_valid, + )) + for field in metric_fields(): + row[field] = math.nan + if translation_valid: + residual_mm = ( + prediction["wrist_root_translation"][batch_index, frame, side] + - batch["wrist_root_translation"][batch_index, frame, side] + ).float().cpu().numpy() * 1000.0 + for axis_index, axis in enumerate("xyz"): + row[f"translation_{axis}_signed_mm"] = float(residual_mm[axis_index]) + row[f"translation_{axis}_mae_mm"] = float(abs(residual_mm[axis_index])) + depth = float(batch["wrist_root_translation"][batch_index, frame, side, 2]) + row["wrist_depth_m"] = depth + row["depth_bucket"] = depth_bucket(depth) + else: + row["wrist_depth_m"] = math.nan + row["depth_bucket"] = "N/A" + if joint2d_mask.any(): + visible_joint_count = int(joint2d_mask.sum()) + row["visible_joint_count"] = visible_joint_count + row["occlusion_bucket"] = ( + "severe_le7" if visible_joint_count <= 7 + else ("partial_8_15" if visible_joint_count <= 15 else "visible_ge16") + ) + target_2d = batch["joint2d"][batch_index, frame, side].float() + height, width = batch["rgb"].shape[-2:] + direct = prediction["joint2d_norm"][batch_index, frame, side].float() * target_2d.new_tensor((width, height)) + predicted_3d = prediction["joints_camera"][batch_index, frame, side].float() + projected, positive = project_points( + predicted_3d, batch["K"][batch_index, frame].float(), + ) + valid_2d = joint2d_mask & torch.isfinite(target_2d).all(-1) + projected_valid = valid_2d & positive + row["direct_2d_error_px"] = float( + torch.linalg.vector_norm(direct - target_2d, dim=-1)[valid_2d].mean() + ) + if projected_valid.any(): + row["projected_mano_2d_error_px"] = float( + torch.linalg.vector_norm(projected - target_2d, dim=-1)[projected_valid].mean() + ) + row["direct_mano_consistency_px"] = float( + torch.linalg.vector_norm(direct - projected, dim=-1)[projected_valid].mean() + ) + valid_points = target_2d[valid_2d] + extent = valid_points.max(0).values - valid_points.min(0).values + size = float(extent.max()) + row["projected_hand_size_px"] = size + row["size_bucket"] = hand_size_bucket(size) + else: + row["visible_joint_count"] = 0 + row["occlusion_bucket"] = "unlabelled" + row["projected_hand_size_px"] = math.nan + row["size_bucket"] = "N/A" + if joint_mask.any(): + predicted_joints = prediction["joints_camera"][batch_index, frame, side].float() + target_joints = batch["joint3d_camera"][batch_index, frame, side].float() + errors = torch.linalg.vector_norm(predicted_joints - target_joints, dim=-1) * 1000.0 + row["absolute_mpjpe_mm"] = float(errors[joint_mask].mean()) + relative_prediction = predicted_joints - predicted_joints[:1] + relative_target = target_joints - target_joints[:1] + relative_error = torch.linalg.vector_norm(relative_prediction - relative_target, dim=-1) * 1000.0 + row["root_relative_mpjpe_mm"] = float(relative_error[joint_mask].mean()) + tips = torch.as_tensor(TIP_INDICES, device=joint_mask.device) + tip_mask = joint_mask[tips] + if tip_mask.any(): + row["fingertip_mpjpe_mm"] = float(errors[tips][tip_mask].mean()) + if bool(joint_mask.all()): + pred_np = predicted_joints.detach().cpu().numpy()[None] + target_np = target_joints.detach().cpu().numpy()[None] + row["rigid_se3_mpjpe_mm"] = float(aligned_mpjpe_mm( + pred_np, target_np, estimate_scale=False, + )[0]) + row["pa_mpjpe_mm"] = float(aligned_mpjpe_mm( + pred_np, target_np, estimate_scale=True, + )[0]) + if source_relative_mask.any(): + predicted_joints = prediction["joints_camera"][batch_index, frame, side].float() + predicted_relative = predicted_joints - predicted_joints[:1] + target_relative = batch["joint3d_root_relative"][batch_index, frame, side].float() + source_error = torch.linalg.vector_norm( + predicted_relative - target_relative, dim=-1, + ) * 1000.0 + row["source_root_relative_mpjpe_mm"] = float( + source_error[source_relative_mask].mean() + ) + if vertices_valid: + vertex_error = torch.linalg.vector_norm( + prediction["vertices_camera"][batch_index, frame, side].float() + - batch["vertices_camera"][batch_index, frame, side].float(), dim=-1, + ) * 1000.0 + row["mpvpe_mm"] = float(vertex_error.mean()) + return row + + +def aggregate(rows: list[dict[str, Any]]) -> dict[str, Any]: + result = {field: finite_summary([row[field] for row in rows]) for field in metric_fields()} + result["supervision_coverage"] = { + "overall": supervision_coverage(rows), + "left": supervision_coverage([row for row in rows if row["side"] == "left"]), + "right": supervision_coverage([row for row in rows if row["side"] == "right"]), + } + for split_name, selector in { + "left": lambda row: row["side"] == "left", + "right": lambda row: row["side"] == "right", + "near": lambda row: row["depth_bucket"] == "near_le0.8m", + "far": lambda row: row["depth_bucket"] == "far_gt0.8m", + "small": lambda row: row["size_bucket"] == "small_lt64", + "medium": lambda row: row["size_bucket"] == "medium_64_128", + "large": lambda row: row["size_bucket"] == "large_ge128", + }.items(): + selected = [row for row in rows if selector(row)] + result[f"bucket_{split_name}"] = { + "hands": len(selected), + "supervision_coverage": supervision_coverage(selected), + "absolute_mpjpe_mm": finite_summary([row["absolute_mpjpe_mm"] for row in selected]), + "translation_z_mae_mm": finite_summary([row["translation_z_mae_mm"] for row in selected]), + "fingertip_mpjpe_mm": finite_summary([row["fingertip_mpjpe_mm"] for row in selected]), + } + for field, prefix in (("headset_id", "headset"), ("occlusion_bucket", "occlusion")): + for value in sorted({str(row[field]) for row in rows}): + selected = [row for row in rows if str(row[field]) == value] + normalized = "".join(character.lower() if character.isalnum() else "_" for character in value) + result[f"bucket_{prefix}_{normalized}"] = { + "hands": len(selected), + "supervision_coverage": supervision_coverage(selected), + "absolute_mpjpe_mm": finite_summary([ + row["absolute_mpjpe_mm"] for row in selected + ]), + "root_relative_mpjpe_mm": finite_summary([ + row["root_relative_mpjpe_mm"] for row in selected + ]), + "translation_z_mae_mm": finite_summary([ + row["translation_z_mae_mm"] for row in selected + ]), + "fingertip_mpjpe_mm": finite_summary([ + row["fingertip_mpjpe_mm"] for row in selected + ]), + } + ray_rows = [row for row in rows if math.isfinite(float(row["ray_depth_confidence"]))] + result["ray_depth_diagnostics"] = None + if ray_rows: + correction_rows = [row for row in ray_rows if row["ray_depth_correction_valid"]] + result["ray_depth_diagnostics"] = { + "hands": len(ray_rows), + "correction_valid_hands": len(correction_rows), + "correction_valid_fraction": len(correction_rows) / len(ray_rows), + "confidence": finite_summary([row["ray_depth_confidence"] for row in ray_rows]), + "raw_delta_z_mm": finite_summary([row["ray_depth_raw_delta_z_mm"] for row in ray_rows]), + "applied_delta_z_mm": finite_summary([row["ray_depth_applied_delta_z_mm"] for row in ray_rows]), + "support_count": finite_summary([row["ray_depth_support_count"] for row in ray_rows]), + "local_valid_fraction": finite_summary([ + row["ray_depth_local_valid_fraction"] for row in ray_rows + ]), + "base_z_error_mm": finite_summary([row["ray_depth_base_z_error_mm"] for row in ray_rows]), + "final_z_error_mm": finite_summary([row["ray_depth_final_z_error_mm"] for row in ray_rows]), + "harm_mm": finite_summary([row["ray_depth_harm_mm"] for row in correction_rows]), + "harm_fraction": ( + float(np.mean([row["ray_depth_harm_mm"] > 0 for row in correction_rows])) + if correction_rows else None + ), + } + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--expected-cache-manifest-sha256") + parser.add_argument("--input-mode", choices=("rgb_d_k", "rgb_k", "rgb_only"), required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument( + "--allow-physical-gpus-4-5", action="store_true", + help="Explicit resource override; default preserves the historical GPU0-3 contract.", + ) + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--evaluation-id") + parser.add_argument("--heartbeat-path", type=Path) + parser.add_argument("--heartbeat-seconds", type=float, default=30.0) + parser.add_argument( + "--evaluation-role", + choices=( + "external_heldout", "h2o_train_group_heldout", + "h2o_train_group_heldout_control", "adaptation_external_heldout", + "phase9_external_heldout", "phase9_h2o_fold_heldout", + ), + default="external_heldout", + ) + args = parser.parse_args() + if args.heartbeat_seconds < 1: + parser.error("heartbeat interval must be at least one second") + if (args.heartbeat_path is None) != (args.evaluation_id is None): + parser.error("evaluation ID and heartbeat path must be provided together") + if sha256(args.checkpoint) != args.expected_checkpoint_sha256: + parser.error("checkpoint SHA256 differs from frozen expected value") + if ( + args.expected_cache_manifest_sha256 is not None + and sha256(args.cache_manifest) != args.expected_cache_manifest_sha256 + ): + parser.error("cache manifest SHA256 differs from frozen expected value") + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + allowed_physical_gpus = {0, 1, 2, 3} + if args.allow_physical_gpus_4_5: + allowed_physical_gpus.update((4, 5)) + if args.physical_gpu_id not in allowed_physical_gpus: + parser.error("physical GPU must be one of 0-3; GPU4-5 are reserved") + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + heartbeat_path = args.heartbeat_path + if heartbeat_path is not None: + if heartbeat_path.resolve().parent != args.output_dir.resolve(): + parser.error("evaluation heartbeat must be inside the output directory") + write_progress_heartbeat(heartbeat_path, { + "status": "initializing", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "processed_clips": 0, "processed_frames": 0, + "dataloader_worker_pids": [], + }) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + dataset = CachedUnifiedClipDataset(args.cache_manifest, K_input_dropout=0.0) + write_progress_heartbeat(heartbeat_path, { + "status": "data_ready", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": 0, + "processed_frames": 0, "dataloader_worker_pids": [], + }) + loader = DataLoader( + dataset, batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).cuda().eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location="cuda") + validate_evaluation_role( + args.evaluation_role, config, + {str(row["dataset_id"]).upper() for row in dataset.rows}, + state["extra"], args.cache_manifest, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + rows: list[dict[str, Any]] = [] + raw: dict[str, list[np.ndarray]] = {} + started = time.perf_counter() + last_heartbeat = started + processed_clips = 0 + processed_frames = 0 + torch.cuda.reset_peak_memory_stats() + with torch.inference_mode(): + for batch in loader: + processed_clips += len(batch["dataset_id"]) + apply_input_mode(batch, args.input_mode) + batch = move_to_device(batch, torch.device("cuda")) + if args.evaluation_role in { + "h2o_train_group_heldout", "h2o_train_group_heldout_control", + "phase9_h2o_fold_heldout", + }: + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + processed_frames += int(batch["frame_valid"].sum()) + now = time.perf_counter() + if now - last_heartbeat >= args.heartbeat_seconds: + write_progress_heartbeat(heartbeat_path, { + "status": "running", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), + "processed_clips": processed_clips, + "processed_frames": processed_frames, + "dataloader_worker_pids": direct_child_pids(os.getpid()), + }) + last_heartbeat = now + persisted = { + "predicted_joints_camera": prediction["joints_camera"], + "predicted_vertices_camera": prediction["vertices_camera"], + "predicted_wrist_root_translation": prediction["wrist_root_translation"], + "predicted_joint2d_norm": prediction["joint2d_norm"], + "predicted_mano_rotation_matrices": prediction["mano_rotation_matrices"], + "predicted_mano_shape": prediction["mano_shape"], + "target_mano_pose": batch["mano_pose"], + "mano_pose_valid": batch["mano_pose_valid"], + "target_joints_camera": batch["joint3d_camera"], + "target_vertices_camera": batch["vertices_camera"], + "target_wrist_root_translation": batch["wrist_root_translation"], + "target_joint2d": batch["joint2d"], + "joint3d_valid": batch["joint3d_valid"], + "vertices_valid": batch["vertices_valid"], + "translation_valid": batch["translation_valid"], + "joint2d_valid": batch["joint2d_valid"], + "frame_valid": batch["frame_valid"], + "K": batch["K"], + "frame_id": batch["frame_id"], + } + if "joint3d_root_relative" in batch: + persisted.update({ + "target_joint3d_root_relative": batch["joint3d_root_relative"], + "joint3d_root_relative_valid": batch["joint3d_root_relative_valid"], + }) + for key in ( + "ray_depth_wrist2d_norm", "ray_depth_log_base_z", + "ray_depth_base_z_m", "ray_depth_raw_delta_z_m", + "ray_depth_applied_delta_z_m", "ray_depth_confidence_logit", + "ray_depth_confidence", "ray_depth_local_statistics", + "ray_depth_support_count", "ray_depth_correction_valid", + "ray_depth_K_input_available", + ): + if key in prediction: + persisted[key] = prediction[key] + append_valid_frame_arrays(raw, persisted, batch["frame_valid"]) + batch_size, time_count = batch["frame_valid"].shape + for batch_index in range(batch_size): + for frame in range(time_count): + if not bool(batch["frame_valid"][batch_index, frame]): + continue + for side in range(2): + rows.append(make_row(prediction, batch, batch_index, frame, side)) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + write_progress_heartbeat(heartbeat_path, { + "status": "finalizing", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": processed_clips, + "processed_frames": processed_frames, + "dataloader_worker_pids": direct_child_pids(os.getpid()), + }) + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed(raw_path, **{ + key: np.concatenate(values, axis=0) for key, values in raw.items() + }) + row_path = args.output_dir / "per_hand_frame_metrics.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + take_rows = [] + for take in sorted({str(row["physical_recording_id"]) for row in rows}): + selected = [row for row in rows if row["physical_recording_id"] == take] + record: dict[str, Any] = {"physical_recording_id": take, "hands": len(selected)} + for field in metric_fields(): + summary = finite_summary([row[field] for row in selected]) + record[field] = summary["mean"] if summary is not None else math.nan + take_rows.append(record) + take_path = args.output_dir / "take_metrics.csv" + with take_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(take_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(take_rows) + bootstrap = { + field: grouped_bootstrap(rows, field, int(config["seed"]), args.bootstrap_resamples) + for field in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "source_root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + report = { + "status": { + "external_heldout": "evaluated", + "h2o_train_group_heldout": "evaluated_h2o_train_group_heldout", + "h2o_train_group_heldout_control": "evaluated_h2o_train_group_heldout_control", + "adaptation_external_heldout": "evaluated_adaptation_external_heldout", + "phase9_external_heldout": "evaluated_phase9_external_heldout", + "phase9_h2o_fold_heldout": "evaluated_phase9_h2o_fold_heldout", + }[args.evaluation_role], + "evaluation_role": args.evaluation_role, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "experiment": config["name"], "checkpoint_step": int(state["step"]), + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": args.expected_checkpoint_sha256}, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "cache_manifest": {"path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest)}, + "input_mode": args.input_mode, "clips": len(dataset), "frames": processed_frames, + "hands_rows": len(rows), "metrics": aggregate(rows), "grouped_bootstrap_ci": bootstrap, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": processed_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + }, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "raw_prediction_layout": "axis0 is the ordered sequence of frame_valid=true frames", + "per_hand_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "take_metrics": {"path": str(take_path.resolve()), "sha256": sha256(take_path)}, + "official_test_used": False, + "h2o_training_data_used": checkpoint_h2o_training_data_used(state["extra"]), + "h2o_official_validation_used": False, + "oracle_information_used": False, + "metric_definitions": { + "rigid_se3_mpjpe_mm": "per-hand Kabsch; removes translation and rotation", + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation and scale", + }, + } + output = args.output_dir / "evaluation.json" + output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + write_progress_heartbeat(heartbeat_path, { + "status": "complete", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": processed_clips, + "processed_frames": processed_frames, + "evaluation_report": str(output.resolve()), + "evaluation_report_sha256": sha256(output), + "dataloader_worker_pids": [], + }) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase7_h2o_zero_shot.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase7_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..dde27a07128671619a11c73262c329644068bc26 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase7_h2o_zero_shot.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Strict one-shot H2O validation evaluation of a frozen external generalist.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.evaluate_phase7_external import ( + aggregate, + apply_input_mode, + finite_summary, + grouped_bootstrap, + make_row, + metric_fields, + sha256, + tensor_to_numpy, +) +from scripts.train_experiment import attach_gt_vertices, move_to_device +from scripts.train_phase7_external import assert_physical_gpu_idle + + +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") +EVALUATION_ROLES = ( + "strict_external_zero_shot", "h2o_adapted_formal", + "phase9_unified_formal", +) + + +def validate_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + status = record.get("status") + if status not in { + "external_generalist_frozen", "external_architecture_candidate_frozen", + }: + raise ValueError("external checkpoint is not frozen") + if status == "external_architecture_candidate_frozen" and ( + record.get("selected_within_family") is not True + or record.get("overall_external_generalist_winner") is not False + ): + raise ValueError("external architecture candidate role is ambiguous") + if record.get("checkpoint_sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen external generalist") + if record.get("official_test_used") is not False: + raise ValueError("freeze record must explicitly exclude official test") + if record.get("h2o_official_validation_used_for_external_selection") is not False: + raise ValueError("external selection must precede H2O validation access") + if not record.get("external_selection_sha256"): + raise ValueError("freeze record lacks external selection SHA256") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from freeze record") + + +def validate_adaptation_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + if record.get("status") != "h2o_adaptation_candidate_frozen": + raise ValueError("H2O adaptation candidate is not frozen") + checkpoint = record.get("checkpoint", {}) + if checkpoint.get("sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen adaptation candidate") + if record.get("h2o_official_validation_used_for_selection") is not False: + raise ValueError("adaptation selection must use H2O train-heldout only") + if record.get("official_test_used") is not False: + raise ValueError("adaptation freeze record must explicitly exclude official test") + if not record.get("adaptation_selection_sha256"): + raise ValueError("adaptation freeze record lacks selection SHA256") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from adaptation freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from adaptation freeze record") + + +def validate_phase9_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + if record.get("status") != "phase9_final_unified_checkpoint_frozen": + raise ValueError("Phase 9 final unified checkpoint is not frozen") + if record.get("checkpoint", {}).get("sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen Phase 9 final checkpoint") + if ( + record.get("selection_complete") is not True + or record.get("stage9_final_decision_complete") is not True + or record.get("h2o_official_validation_used_for_selection") is not False + or record.get("official_test_used") is not False + or not record.get("selection_chain_sha256") + ): + raise ValueError("Phase 9 final selection provenance is incomplete") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from Phase 9 freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from Phase 9 freeze record") + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"cannot write empty metric rows: {path}") + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(rows) + + +def append_valid_frame_arrays( + raw: dict[str, list[np.ndarray]], values: dict[str, torch.Tensor], + frame_valid: torch.Tensor, +) -> None: + """Persist variable-length clips as one contiguous valid-frame axis.""" + + valid = tensor_to_numpy(frame_valid.bool()).reshape(-1) + batch, time = frame_valid.shape + for key, value in values.items(): + array = tensor_to_numpy(value) + if array.shape[:2] != (batch, time): + raise ValueError(f"raw temporal field shape differs from frame_valid: {key}") + flattened = array.reshape(batch * time, *array.shape[2:]) + raw.setdefault(key, []).append(flattened[valid]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--input-mode", choices=INPUT_MODES, required=True) + parser.add_argument( + "--evaluation-role", choices=EVALUATION_ROLES, + default="strict_external_zero_shot", + ) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--frame-stride", type=int, default=1) + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.physical_gpu_id not in {0, 1, 2, 3}: + parser.error("physical GPU must be one of 0-3; GPU4-5 are reserved") + import os + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + if sha256(args.checkpoint) != args.expected_checkpoint_sha256: + parser.error("checkpoint SHA256 differs from frozen expected value") + freeze_record = json.loads(args.freeze_record.read_text(encoding="utf-8")) + if args.evaluation_role == "strict_external_zero_shot": + validate_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + elif args.evaluation_role == "h2o_adapted_formal": + validate_adaptation_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + else: + validate_phase9_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + expected_branch = { + "strict_external_zero_shot": "external_only", + "h2o_adapted_formal": "h2o_adaptation", + "phase9_unified_formal": "phase9_unified", + }[args.evaluation_role] + if config.get("experiment", {}).get("branch") != expected_branch: + raise ValueError(f"checkpoint config branch is not {expected_branch}") + dataset = H2OCam4Dataset( + args.root, args.manifest, + target_hw=tuple(config["data"]["resolution_hw"]), + clip_lengths=(args.clip_length,), strides=(args.frame_stride,), + ) + loader = DataLoader( + dataset, batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).cuda().eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location="cuda") + expected_h2o_training = args.evaluation_role != "strict_external_zero_shot" + if state["extra"].get("h2o_training_data_used") is not expected_h2o_training: + raise ValueError("checkpoint H2O-training provenance differs from evaluation role") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + rows: list[dict[str, Any]] = [] + raw: dict[str, list[np.ndarray]] = {} + processed_frames = 0 + started = time.perf_counter() + torch.cuda.reset_peak_memory_stats() + with torch.inference_mode(): + for batch in loader: + apply_input_mode(batch, args.input_mode) + batch = move_to_device(batch, torch.device("cuda")) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + processed_frames += int(batch["frame_valid"].sum()) + persisted = { + "predicted_joints_camera": prediction["joints_camera"], + "predicted_vertices_camera": prediction["vertices_camera"], + "predicted_wrist_root_translation": prediction["wrist_root_translation"], + "predicted_joint2d_norm": prediction["joint2d_norm"], + "predicted_mano_rotation_matrices": prediction["mano_rotation_matrices"], + "predicted_mano_shape": prediction["mano_shape"], + "target_joints_camera": batch["joint3d_camera"], + "target_vertices_camera": batch["vertices_camera"], + "target_wrist_root_translation": batch["wrist_root_translation"], + "target_joint2d": batch["joint2d"], + "joint3d_valid": batch["joint3d_valid"], + "vertices_valid": batch["vertices_valid"], + "translation_valid": batch["translation_valid"], + "joint2d_valid": batch["joint2d_valid"], + "frame_valid": batch["frame_valid"], + "K": batch["K"], + "frame_id": batch["frame_id"], + } + append_valid_frame_arrays(raw, persisted, batch["frame_valid"]) + batch_size, time_count = batch["frame_valid"].shape + for batch_index in range(batch_size): + for frame in range(time_count): + if not bool(batch["frame_valid"][batch_index, frame]): + continue + for side in range(2): + rows.append(make_row(prediction, batch, batch_index, frame, side)) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed(raw_path, **{ + key: np.concatenate(values, axis=0) for key, values in raw.items() + }) + row_path = args.output_dir / "per_hand_frame_metrics.csv" + write_csv(row_path, rows) + take_rows = [] + for take in sorted({str(row["physical_recording_id"]) for row in rows}): + selected = [row for row in rows if row["physical_recording_id"] == take] + record: dict[str, Any] = {"physical_recording_id": take, "hands": len(selected)} + for field in metric_fields(): + summary = finite_summary([row[field] for row in selected]) + record[field] = summary["mean"] if summary is not None else math.nan + take_rows.append(record) + take_path = args.output_dir / "take_metrics.csv" + write_csv(take_path, take_rows) + bootstrap = { + field: grouped_bootstrap( + rows, field, int(config["seed"]), args.bootstrap_resamples, + ) + for field in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + report = { + "status": { + "strict_external_zero_shot": "evaluated_strict_h2o_zero_shot", + "h2o_adapted_formal": "evaluated_h2o_adapted_formal", + "phase9_unified_formal": "evaluated_phase9_unified_formal", + }[args.evaluation_role], + "evaluation_role": args.evaluation_role, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "experiment": config["name"], "checkpoint_step": int(state["step"]), + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": args.expected_checkpoint_sha256, + }, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "freeze_record": { + "path": str(args.freeze_record.resolve()), "sha256": sha256(args.freeze_record), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "input_mode": args.input_mode, "clips": len(dataset), "frames": processed_frames, + "hands_rows": len(rows), "metrics": aggregate(rows), + "grouped_bootstrap_ci": bootstrap, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": processed_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + }, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "raw_prediction_layout": "axis0 is the ordered sequence of frame_valid=true frames", + "per_hand_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "take_metrics": {"path": str(take_path.resolve()), "sha256": sha256(take_path)}, + "h2o_training_data_used": expected_h2o_training, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + "oracle_information_used": False, + "metric_definitions": { + "rigid_se3_mpjpe_mm": "per-hand Kabsch; removes translation and rotation", + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation and scale", + }, + } + output = args.output_dir / "evaluation.json" + output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase8_translation_oracles.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase8_translation_oracles.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3f03e6d4363d51d6d533cf00426e064d9d61b4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_phase8_translation_oracles.py @@ -0,0 +1,355 @@ +#!/usr/bin/env python3 +"""Evaluation-only ray/z/root-relative decomposition from persisted predictions.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +CONDITIONS = ( + "raw", + "predicted_pose_shape_gt_translation", + "predicted_ray_gt_z", + "gt_ray_predicted_z", + "predicted_root_relative_gt_translation", + "predicted_translation_gt_root_relative", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def flatten_leading(array: np.ndarray, trailing_dimensions: int) -> np.ndarray: + trailing = array.shape[-trailing_dimensions:] + return array.reshape(-1, *trailing) + + +def axis_angle_to_matrix(axis_angle: np.ndarray) -> np.ndarray: + angle = np.linalg.norm(axis_angle, axis=-1) + safe = np.maximum(angle, 1e-12) + axis = axis_angle / safe[..., None] + x, y, z = np.moveaxis(axis, -1, 0) + zero = np.zeros_like(x) + skew = np.stack(( + zero, -z, y, z, zero, -x, -y, x, zero, + ), axis=-1).reshape(*axis.shape[:-1], 3, 3) + identity = np.broadcast_to(np.eye(3), skew.shape) + matrix = ( + identity + np.sin(angle)[..., None, None] * skew + + (1.0 - np.cos(angle))[..., None, None] * (skew @ skew) + ) + return np.where((angle < 1e-12)[..., None, None], identity, matrix) + + +def decompose(arrays: dict[str, np.ndarray]) -> dict[str, Any]: + pred_joints = flatten_leading(arrays["predicted_joints_camera"], 3) + target_joints = flatten_leading(arrays["target_joints_camera"], 3) + pred_translation = flatten_leading( + arrays["predicted_wrist_root_translation"], 2, + ) + target_translation = flatten_leading( + arrays["target_wrist_root_translation"], 2, + ) + joint_valid = flatten_leading(arrays["joint3d_valid"], 2).astype(bool) + translation_valid = flatten_leading( + arrays["translation_valid"], 1, + ).astype(bool) + if not ( + pred_joints.shape[:2] == target_joints.shape[:2] + == pred_translation.shape[:2] == target_translation.shape[:2] + == joint_valid.shape[:2] + ): + raise ValueError("raw prediction arrays do not share frame/hand axes") + pred_relative = pred_joints - pred_joints[..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + pred_z = pred_translation[..., 2] + target_z = target_translation[..., 2] + safe_pred_z = np.where(np.abs(pred_z) > 1e-6, pred_z, np.nan) + safe_target_z = np.where(np.abs(target_z) > 1e-6, target_z, np.nan) + pred_ray = pred_translation[..., :2] / safe_pred_z[..., None] + target_ray = target_translation[..., :2] / safe_target_z[..., None] + pred_ray_gt_z_translation = np.concatenate( + (pred_ray * target_z[..., None], target_z[..., None]), axis=-1, + ) + gt_ray_pred_z_translation = np.concatenate( + (target_ray * pred_z[..., None], pred_z[..., None]), axis=-1, + ) + condition_joints = { + "raw": pred_joints, + "predicted_pose_shape_gt_translation": ( + pred_relative + target_translation[..., None, :] + ), + "predicted_ray_gt_z": ( + pred_relative + pred_ray_gt_z_translation[..., None, :] + ), + "gt_ray_predicted_z": ( + pred_relative + gt_ray_pred_z_translation[..., None, :] + ), + "predicted_root_relative_gt_translation": ( + pred_relative + target_translation[..., None, :] + ), + "predicted_translation_gt_root_relative": ( + target_relative + pred_translation[..., None, :] + ), + } + condition_errors: dict[str, np.ndarray] = {} + annotation_valid = joint_valid.any(axis=-1) & translation_valid + positive_depth = ( + np.isfinite(pred_z) & np.isfinite(target_z) + & (pred_z > 0.05) & (target_z > 0.05) + ) + hand_valid = annotation_valid & positive_depth + for name, joints in condition_joints.items(): + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + numerator = np.where(joint_valid, joint_error, 0.0).sum(axis=-1) + denominator = joint_valid.sum(axis=-1) + error = numerator / np.maximum(denominator, 1) + condition_errors[name] = np.where(hand_valid, error, np.nan) + translation_residual = (pred_translation - target_translation) * 1000.0 + ray_residual = pred_ray - target_ray + result = { + "condition_errors_mm": condition_errors, + "translation_residual_mm": translation_residual, + "ray_residual": ray_residual, + "predicted_z_m": pred_z, + "target_z_m": target_z, + "valid": hand_valid, + "annotation_valid": annotation_valid, + "positive_depth": positive_depth, + } + if "K" in arrays: + K = flatten_leading(arrays["K"], 2) + if K.shape[0] != hand_valid.shape[0]: + raise ValueError("K frame axis differs from prediction frame axis") + result["K"] = np.broadcast_to(K[:, None], (*hand_valid.shape, 3, 3)) + if {"predicted_mano_rotation_matrices", "target_mano_pose", "mano_pose_valid"}.issubset(arrays): + predicted_rotation = flatten_leading( + arrays["predicted_mano_rotation_matrices"], 4, + )[..., 0, :, :] + target_pose = flatten_leading(arrays["target_mano_pose"], 2) + pose_valid = flatten_leading(arrays["mano_pose_valid"], 1).astype(bool) + target_rotation = axis_angle_to_matrix(target_pose[..., :3]) + relative = predicted_rotation @ np.swapaxes(target_rotation, -1, -2) + cosine = np.clip( + (np.trace(relative, axis1=-2, axis2=-1) - 1.0) / 2.0, + -1.0, 1.0, + ) + result["global_orientation_geodesic_deg"] = np.degrees(np.arccos(cosine)) + result["global_orientation_valid"] = pose_valid + return result + + +def finite_summary(values: np.ndarray) -> dict[str, float | int] | None: + values = np.asarray(values, dtype=np.float64) + values = values[np.isfinite(values)] + if not values.size: + return None + return { + "count": int(values.size), "mean": float(values.mean()), + "median": float(np.median(values)), + "p95": float(np.quantile(values, 0.95)), + } + + +def correlation(x: np.ndarray, y: np.ndarray, valid: np.ndarray) -> float | None: + mask = valid & np.isfinite(x) & np.isfinite(y) + if mask.sum() < 2 or np.std(x[mask]) == 0 or np.std(y[mask]) == 0: + return None + return float(np.corrcoef(x[mask], y[mask])[0, 1]) + + +def build_report(result: dict[str, Any]) -> dict[str, Any]: + errors = result["condition_errors_mm"] + raw_mean = float(np.nanmean(errors["raw"])) + conditions = {} + for name in CONDITIONS: + summary = finite_summary(errors[name]) + if summary is None: + conditions[name] = None + continue + gain = raw_mean - float(summary["mean"]) + conditions[name] = { + **summary, "gain_vs_raw_mm": gain, + "gain_vs_raw_percent": 100.0 * gain / raw_mean, + } + fix_z_gain = raw_mean - float(np.nanmean(errors["predicted_ray_gt_z"])) + fix_ray_gain = raw_mean - float(np.nanmean(errors["gt_ray_predicted_z"])) + fix_translation_gain = raw_mean - float(np.nanmean( + errors["predicted_root_relative_gt_translation"], + )) + interaction = fix_translation_gain - fix_z_gain - fix_ray_gain + residual = result["translation_residual_mm"] + valid = result["valid"] + axis = { + name: { + "signed_mm": finite_summary(residual[..., index][valid]), + "absolute_mm": finite_summary(np.abs(residual[..., index][valid])), + } + for index, name in enumerate("xyz") + } + axis["correlation"] = { + "x_y": correlation(residual[..., 0], residual[..., 1], valid), + "x_z": correlation(residual[..., 0], residual[..., 2], valid), + "y_z": correlation(residual[..., 1], residual[..., 2], valid), + } + orientation = result.get("global_orientation_geodesic_deg") + orientation_valid = result.get("global_orientation_valid") + return { + "status": "evaluated_oracle_diagnostic_only", + "deployable_claim": False, + "selection_use": False, + "official_test_used": False, + "validity_audit": { + "annotation_valid_hands": int(result["annotation_valid"].sum()), + "positive_depth_hands": int(result["valid"].sum()), + "excluded_nonpositive_or_near_depth": int( + (result["annotation_valid"] & ~result["positive_depth"]).sum() + ), + "minimum_ray_depth_m": 0.05, + }, + "conditions": conditions, + "translation_attribution": { + "fix_z_gain_mm": fix_z_gain, + "fix_ray_gain_mm": fix_ray_gain, + "fix_all_translation_gain_mm": fix_translation_gain, + "nonadditive_interaction_mm": interaction, + "note": "Counterfactual gains are not assumed additive; interaction is reported explicitly.", + }, + "translation_axis_error": axis, + "ray_residual_norm": finite_summary( + np.linalg.norm(result["ray_residual"], axis=-1)[valid], + ), + "global_orientation_geodesic_deg": ( + finite_summary(orientation[orientation_valid]) + if orientation is not None and orientation_valid is not None else None + ), + } + + +def bucket_report(result: dict[str, Any], rows: list[dict[str, Any]]) -> dict[str, Any]: + shape = result["valid"].shape + flat_rows = np.asarray(rows, dtype=object).reshape(shape) + target_z = result["target_z_m"] + selectors: dict[str, np.ndarray] = { + "side_left": np.vectorize(lambda row: row.get("side") == "left")(flat_rows), + "side_right": np.vectorize(lambda row: row.get("side") == "right")(flat_rows), + "depth_near_le0.5m": target_z <= 0.5, + "depth_mid_0.5_0.8m": (target_z > 0.5) & (target_z <= 0.8), + "depth_far_gt0.8m": target_z > 0.8, + } + for size in ("small_lt64", "medium_64_128", "large_ge128"): + selectors[f"size_{size}"] = np.vectorize( + lambda row, expected=size: row.get("size_bucket") == expected, + )(flat_rows) + K = result.get("K") + if K is not None: + focal = np.sqrt(K[..., 0, 0] * K[..., 1, 1]) + finite = focal[result["valid"] & np.isfinite(focal)] + if finite.size: + low, high = np.quantile(finite, (1.0 / 3.0, 2.0 / 3.0)) + selectors["focal_low"] = focal <= low + selectors["focal_mid"] = (focal > low) & (focal <= high) + selectors["focal_high"] = focal > high + errors = result["condition_errors_mm"] + output: dict[str, Any] = {} + for name, selector in selectors.items(): + mask = result["valid"] & selector + raw = finite_summary(errors["raw"][mask]) + if raw is None: + output[name] = None + continue + raw_mean = float(raw["mean"]) + output[name] = { + "raw_absolute_mpjpe_mm": raw, + "fix_z_gain_mm": raw_mean - float(np.nanmean(errors["predicted_ray_gt_z"][mask])), + "fix_ray_gain_mm": raw_mean - float(np.nanmean(errors["gt_ray_predicted_z"][mask])), + "fix_translation_gain_mm": raw_mean - float(np.nanmean( + errors["predicted_root_relative_gt_translation"][mask], + )), + } + output["occlusion"] = { + "status": "N/A" if not any("occlusion_bucket" in row for row in rows) else "available", + "reason": "Phase 7 per-hand rows do not persist a common occlusion bucket", + } + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--raw-predictions", type=Path, required=True) + parser.add_argument("--per-hand-rows", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + args.output_dir.mkdir(parents=True, exist_ok=True) + with np.load(args.raw_predictions) as loaded: + result = decompose({key: loaded[key] for key in loaded.files}) + rows = list(csv.DictReader(args.per_hand_rows.open(encoding="utf-8"))) + flat_count = result["valid"].size + if len(rows) != flat_count: + raise ValueError( + f"per-hand rows ({len(rows)}) differ from raw frame-hand count ({flat_count})" + ) + errors = result["condition_errors_mm"] + output_rows = [] + for index, row in enumerate(rows): + record = { + key: row.get(key, "") for key in ( + "dataset", "subject_id", "physical_recording_id", "camera_id", + "frame_id", "side", "depth_bucket", "size_bucket", + ) + } + flat_index = np.unravel_index(index, result["valid"].shape) + for condition in CONDITIONS: + record[f"{condition}_absolute_mpjpe_mm"] = float( + errors[condition][flat_index] + ) + for axis_index, axis in enumerate("xyz"): + record[f"translation_{axis}_signed_mm"] = float( + result["translation_residual_mm"][flat_index][axis_index] + ) + record["target_wrist_depth_m"] = float(result["target_z_m"][flat_index]) + record["predicted_wrist_depth_m"] = float(result["predicted_z_m"][flat_index]) + record["ray_residual_norm"] = float(np.linalg.norm(result["ray_residual"][flat_index])) + if "K" in result: + record["fx_px"] = float(result["K"][flat_index][0, 0]) + record["fy_px"] = float(result["K"][flat_index][1, 1]) + output_rows.append(record) + csv_path = args.output_dir / "per_hand_oracle_decomposition.csv" + with csv_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(output_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(output_rows) + report = build_report(result) + report["buckets"] = bucket_report(result, rows) + report.update({ + "raw_predictions": { + "path": str(args.raw_predictions.resolve()), + "sha256": sha256(args.raw_predictions), + }, + "per_hand_input": { + "path": str(args.per_hand_rows.resolve()), + "sha256": sha256(args.per_hand_rows), + }, + "per_hand_output": {"path": str(csv_path.resolve()), "sha256": sha256(csv_path)}, + }) + path = args.output_dir / "oracle_decomposition.json" + path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_sota_bundle.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_sota_bundle.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a226aebdf5591829184aa3e54525238a05d83a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_sota_bundle.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Evaluate one standardized external-model prediction bundle on H2O.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + evaluate_prediction_bundle, + write_csv_rows, +) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--prediction", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument( + "--pixel-scale", + type=float, + default=0.5, + help="Map raw H2O pixels to the Phase 3 640x368 evaluation scale.", + ) + parser.add_argument("--temporal-clip-length", type=int, default=8) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + prediction = PredictionBundle.load(args.prediction) + ground_truth = GroundTruthBundle.load(args.ground_truth) + report, frame_rows, temporal_rows = evaluate_prediction_bundle( + prediction, + ground_truth, + bootstrap_seed=args.bootstrap_seed, + bootstrap_samples=args.bootstrap_samples, + pixel_scale=args.pixel_scale, + temporal_clip_length=args.temporal_clip_length, + ) + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + write_csv_rows(args.output_dir / "per_hand_frame_metrics.csv", frame_rows) + write_csv_rows(args.output_dir / "per_temporal_transition_metrics.csv", temporal_rows) + print(json.dumps({ + "model": report["model_name"], + "coverage": report["coverage"]["hand_frame_fraction"], + "absolute_mpjpe_mm": report["metrics_success_conditioned"][ + "absolute_mpjpe_mm" + ]["mean"], + "root_relative_mpjpe_mm": report["metrics_success_conditioned"][ + "root_relative_mpjpe_mm" + ]["mean"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_tiny.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_tiny.py new file mode 100644 index 0000000000000000000000000000000000000000..d1416cb0dd5df06fc941ee11a654e30062cf3517 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/evaluate_tiny.py @@ -0,0 +1,426 @@ +#!/usr/bin/env python3 +"""Deterministic full tiny-set evaluation and visualization.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path + +import cv2 +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def draw_points(image: np.ndarray, points: np.ndarray, color: tuple[int, int, int], marker: bool) -> None: + for point in points: + if not np.isfinite(point).all(): + continue + xy = tuple(np.rint(point).astype(int)) + if marker: + cv2.drawMarker(image, xy, color, cv2.MARKER_CROSS, 8, 1) + else: + cv2.circle(image, xy, 3, color, -1) + + +def mean(values: list[float]) -> float | None: + return float(np.mean(values)) if values else None + + +def image_size_bucket(max_side_px: float) -> str: + if max_side_px < 64: + return "small_lt64px" + if max_side_px < 128: + return "medium_64_128px" + return "large_ge128px" + + +def depth_bucket(depth_m: float) -> str: + if depth_m < 0.5: + return "near_lt0.5m" + if depth_m < 0.8: + return "middle_0.5_0.8m" + return "far_ge0.8m" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--train-log", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args(); args.output_dir.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=args.max_clips, + oracle_crop_enabled=( + config["model"].get("oracle_crop_mode", "none") != "none" + ), + ) + loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_h2o_clips) + model_config = ModelConfig(**config["model"], dinov3_source=assets["dinov3_source"], dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"]) + device = torch.device(f"cuda:{args.gpu}") + model = BimanualReconstructionModel(model_config).to(device).eval() + load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + + values: dict[str, list[float]] = defaultdict(list) + loss_values: dict[str, list[float]] = defaultdict(list) + frame_rows: list[dict[str, object]] = [] + saved_overlays: list[Path] = [] + attention_same_peak = [] + attention_cosine = [] + depth_attention_same_peak = [] + temporal_attention_diagonal = [] + temporal_attention_entropy = [] + bimanual_cross_attention = [] + depth_gates = [] + raw_depth_gates = [] + rgb_update_norms = [] + depth_update_norms = [] + gated_depth_update_norms = [] + structured_diagnostics: dict[str, list[float]] = defaultdict(list) + visualization_index = 0 + saved_sequence_diagnostics = False + frame_count = 0 + bucket_values: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + + with torch.inference_mode(): + for batch in loader: + batch = {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + gt_vertices, _ = model.mano_layer( + axis_angle_to_matrix(pose), torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + mano_valid = (batch["mano_annotation_valid"].bool() & batch["frame_valid"].bool()[..., None])[..., None, None] + batch["vertices_camera"] = torch.where(mano_valid, gt_vertices, torch.full_like(gt_vertices, torch.nan)) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + for key, value in losses.items(): + loss_values[key].append(float(value)) + + frame_valid = batch["frame_valid"].bool() + frame_count += int(frame_valid.sum()) + ann = batch["joint_annotation_valid"].bool() & frame_valid[..., None] + joint_valid = batch["joint_element_valid"].bool() & ann[..., None] + target_joints = torch.nan_to_num(batch["joint3d_camera"]) + joint_error = torch.linalg.vector_norm(prediction["joints_camera"] - target_joints, dim=-1) * 1000 + pred_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + relative_error = torch.linalg.vector_norm(pred_relative - target_relative, dim=-1) * 1000 + translation_error = (prediction["wrist_root_translation"] - torch.nan_to_num(batch["wrist_root_translation"])).abs() * 1000 + height, width = map(int, batch["image_hw"][0].tolist()) + predicted_2d = prediction["joint2d_norm"] * torch.tensor((width, height), device=device) + target_2d = torch.nan_to_num(batch["joint2d"]) + error_2d = torch.linalg.vector_norm(predicted_2d - target_2d, dim=-1) + if "structured_translation_delta" in prediction: + valid_hands = frame_valid[..., None].expand(-1, -1, 2) + structured_diagnostics["translation_delta_norm_mm"].extend( + ( + torch.linalg.vector_norm( + prediction["structured_translation_delta"], dim=-1, + )[valid_hands] * 1000.0 + ).float().cpu().tolist() + ) + structured_diagnostics["rotation_delta_norm_deg"].extend( + ( + torch.linalg.vector_norm( + prediction["structured_rotation_delta_axis_angle"], dim=-1, + )[valid_hands[..., None].expand(-1, -1, -1, 16)] + * (180.0 / np.pi) + ).float().cpu().tolist() + ) + structured_diagnostics["shape_delta_abs"].extend( + prediction["structured_shape_delta"].abs().reshape(-1).float().cpu().tolist() + ) + pixel_scale = torch.tensor((width, height), device=device) + structured_diagnostics["joint2d_delta_px"].extend( + torch.linalg.vector_norm( + prediction["structured_joint2d_delta"] * pixel_scale, + dim=-1, + )[valid_hands[..., None].expand(-1, -1, -1, 21)].float().cpu().tolist() + ) + structured_diagnostics["sample_offset_norm_px"].extend( + torch.linalg.vector_norm( + prediction["structured_sample_offsets"] * pixel_scale, + dim=-1, + )[frame_valid[..., None, None, None].expand( + -1, -1, 2, 7, prediction["structured_sample_offsets"].shape[-2], + )].float().cpu().tolist() + ) + + if not saved_sequence_diagnostics: + subject = batch["subject_id"][0] + sequence = batch["sequence_id"][0] + title_prefix = f"{config['name']} | {subject}/{sequence}" + if "temporal_attention" in prediction["attention"]: + temporal_plot = prediction["attention"]["temporal_attention"][0, -1].float().cpu().numpy() + fig, axes = plt.subplots(1, 2, figsize=(9, 4)) + for hand, side in enumerate(("left", "right")): + axes[hand].imshow(temporal_plot[hand], vmin=0, vmax=max(float(temporal_plot.max()), 1e-8), cmap="viridis") + axes[hand].set_title(f"{side} temporal attention") + axes[hand].set_xlabel("key frame") + axes[hand].set_ylabel("query frame") + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_temporal_attention.png", dpi=160) + plt.close(fig) + valid_times = frame_valid[0].cpu().numpy() + time_axis = np.arange(int(valid_times.sum())) + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for hand, side in enumerate(("left", "right")): + hand_valid = ann[0, :, hand].cpu().numpy() & valid_times + pred_z = prediction["wrist_root_translation"][0, :, hand, 2].float().cpu().numpy()[valid_times] + gt_z = batch["wrist_root_translation"][0, :, hand, 2].float().cpu().numpy()[valid_times] + axes[0].plot(time_axis, pred_z, label=f"{side} pred") + axes[0].plot(time_axis[hand_valid[valid_times]], gt_z[hand_valid[valid_times]], "--", label=f"{side} GT") + per_frame = joint_error[0, :, hand].mean(-1).float().cpu().numpy()[valid_times] + axes[1].plot(time_axis[hand_valid[valid_times]], per_frame[hand_valid[valid_times]], label=side) + axes[0].set_title("Camera-space wrist z") + axes[0].set_ylabel("meters") + axes[1].set_title("Per-frame absolute MPJPE") + axes[1].set_ylabel("mm") + for axis in axes: + axis.set_xlabel("frame in clip") + axis.grid(alpha=0.25) + axis.legend() + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_translation_and_mpjpe.png", dpi=160) + plt.close(fig) + if "depth_fusion_gate" in prediction["attention"]: + gates = prediction["attention"]["depth_fusion_gate"][0, :, :, :, 0].float().cpu().numpy() + fig, axes = plt.subplots(1, 2, figsize=(10, 4)) + for hand, side in enumerate(("left", "right")): + for layer in range(gates.shape[0]): + axes[hand].plot(gates[layer, valid_times, hand], label=f"layer {layer}") + axes[hand].set_title(f"{side} depth gate") + axes[hand].set_xlabel("frame in clip") + axes[hand].set_ylim(0, 1) + axes[hand].grid(alpha=0.25) + axes[hand].legend() + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_depth_gate.png", dpi=160) + plt.close(fig) + saved_sequence_diagnostics = True + + for hand, side in enumerate(("left", "right")): + mask = joint_valid[..., hand, :] + values[f"{side}_absolute_mpjpe_mm"].extend(joint_error[..., hand, :][mask].float().cpu().tolist()) + values[f"{side}_root_relative_mpjpe_mm"].extend(relative_error[..., hand, :][mask].float().cpu().tolist()) + values[f"{side}_joint2d_error_px"].extend(error_2d[..., hand, :][mask].float().cpu().tolist()) + hand_mask = ann[..., hand] + for axis_index, axis in enumerate("xyz"): + values[f"{side}_translation_{axis}_mae_mm"].extend(translation_error[..., hand, axis_index][hand_mask].float().cpu().tolist()) + + rgb_attention = prediction["attention"]["rgb_cross_attention"][:, -1] + left_attention, right_attention = rgb_attention[..., 0, :], rgb_attention[..., 1, :] + valid_flat = frame_valid + attention_same_peak.extend((left_attention.argmax(-1) == right_attention.argmax(-1))[valid_flat].cpu().tolist()) + cosine = torch.nn.functional.cosine_similarity(left_attention, right_attention, dim=-1) + attention_cosine.extend(cosine[valid_flat].float().cpu().tolist()) + if "depth_fusion_gate" in prediction["attention"]: + depth_gates.extend(prediction["attention"]["depth_fusion_gate"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + raw_depth_gates.extend(prediction["attention"]["depth_fusion_gate_raw"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + depth_update_norms.extend(prediction["attention"]["depth_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + gated_depth_update_norms.extend(prediction["attention"]["gated_depth_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + depth_attention = prediction["attention"]["depth_cross_attention"][:, -1] + depth_attention_same_peak.extend( + (depth_attention[..., 0, :].argmax(-1) == depth_attention[..., 1, :].argmax(-1))[frame_valid].cpu().tolist() + ) + rgb_update_norms.extend(prediction["attention"]["rgb_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + + if "temporal_attention" in prediction["attention"]: + temporal = prediction["attention"]["temporal_attention"][:, -1] + for batch_index in range(temporal.shape[0]): + valid_indices = torch.where(frame_valid[batch_index])[0] + for hand_index in range(2): + for query_index in valid_indices: + weights = temporal[batch_index, hand_index, query_index, valid_indices].float() + weights = weights / weights.sum().clamp_min(1e-8) + temporal_attention_diagonal.append(float(temporal[batch_index, hand_index, query_index, query_index])) + if weights.numel() > 1: + entropy = -(weights * weights.clamp_min(1e-8).log()).sum() / np.log(weights.numel()) + temporal_attention_entropy.append(float(entropy)) + if "bimanual_attention" in prediction["attention"]: + bimanual = prediction["attention"]["bimanual_attention"][:, -1] + cross = 0.5 * (bimanual[..., 0, 1] + bimanual[..., 1, 0]) + bimanual_cross_attention.extend(cross[frame_valid].float().cpu().tolist()) + + if prediction["wrist_root_translation"].shape[1] > 1: + velocity_valid = ann[:, 1:] & ann[:, :-1] + predicted_velocity = prediction["wrist_root_translation"][:, 1:] - prediction["wrist_root_translation"][:, :-1] + target_velocity = torch.nan_to_num(batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1]) + velocity_error = torch.linalg.vector_norm(predicted_velocity - target_velocity, dim=-1) * 1000 + values["temporal_velocity_error_mm_per_frame"].extend(velocity_error[velocity_valid].float().cpu().tolist()) + if predicted_velocity.shape[1] > 1: + acceleration_valid = velocity_valid[:, 1:] & velocity_valid[:, :-1] + predicted_acceleration = predicted_velocity[:, 1:] - predicted_velocity[:, :-1] + target_acceleration = target_velocity[:, 1:] - target_velocity[:, :-1] + acceleration_error = torch.linalg.vector_norm(predicted_acceleration - target_acceleration, dim=-1) * 1000 + values["temporal_acceleration_error_mm_per_frame2"].extend( + acceleration_error[acceleration_valid].float().cpu().tolist() + ) + + for time_index in range(batch["rgb"].shape[1]): + if not frame_valid[0, time_index]: + continue + for hand, side in enumerate(("left", "right")): + is_valid = bool(ann[0, time_index, hand]) + annotation_state = "".join( + str(int(value)) for value in ann[0, time_index].int().cpu().tolist() + ) + max_side_px = None + wrist_depth_m = None + if is_valid: + points = batch["joint2d"][0, time_index, hand] + extent = points.max(dim=0).values - points.min(dim=0).values + max_side_px = float(extent.max()) + wrist_depth_m = float(batch["wrist_root_translation"][0, time_index, hand, 2]) + absolute_error = float(joint_error[0, time_index, hand].mean()) + root_error = float(relative_error[0, time_index, hand].mean()) + z_error = float(translation_error[0, time_index, hand, 2]) + for bucket in ( + f"image_size/{image_size_bucket(max_side_px)}", + f"wrist_depth/{depth_bucket(wrist_depth_m)}", + f"annotation_state/{annotation_state}", + ): + bucket_values[bucket]["absolute_mpjpe_mm"].append(absolute_error) + bucket_values[bucket]["root_relative_mpjpe_mm"].append(root_error) + bucket_values[bucket]["translation_z_mae_mm"].append(z_error) + frame_rows.append({ + "subject": batch["subject_id"][0], "sequence": batch["sequence_id"][0], + "frame_id": int(batch["frame_id"][0, time_index]), "side": side, + "annotation_valid": int(is_valid), + "annotation_state": annotation_state, + "hand_max_side_px": max_side_px, + "wrist_depth_m": wrist_depth_m, + "absolute_mpjpe_mm": float(joint_error[0, time_index, hand].mean()) if is_valid else None, + "root_relative_mpjpe_mm": float(relative_error[0, time_index, hand].mean()) if is_valid else None, + "joint2d_error_px": float(error_2d[0, time_index, hand].mean()) if is_valid else None, + **{f"pred_t_{axis}_m": float(prediction["wrist_root_translation"][0, time_index, hand, index]) for index, axis in enumerate("xyz")}, + **{f"gt_t_{axis}_m": float(batch["wrist_root_translation"][0, time_index, hand, index]) if is_valid else None for index, axis in enumerate("xyz")}, + }) + + if visualization_index < 16: + rgb = batch["rgb"][0, time_index].float().cpu().permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + for hand, color in enumerate(((50, 220, 50), (50, 80, 255))): + if ann[0, time_index, hand]: + draw_points(image, batch["joint2d"][0, time_index, hand].float().cpu().numpy(), (255, 255, 255), True) + draw_points(image, predicted_2d[0, time_index, hand].float().cpu().numpy(), color, False) + modalities = "RGB" + ("+Depth" if config["model"].get("use_depth") else "") + ("+K" if config["model"].get("use_rays") else "") + lines = ( + f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/{int(batch['frame_id'][0,time_index])} GT=x pred=dot", + f"config={config['name']} input={modalities}", + f"GT valid L={int(ann[0,time_index,0])} R={int(ann[0,time_index,1])} presence=unsupervised", + ) + cv2.rectangle(image, (0, 0), (width, 62), (0, 0, 0), -1) + for line_index, label in enumerate(lines): + cv2.putText(image, label, (6, 17 + 19 * line_index), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (255, 255, 255), 1) + overlay_path = args.output_dir / f"{visualization_index:02d}_prediction_overlay.jpg" + cv2.imwrite(str(overlay_path), image); saved_overlays.append(overlay_path) + grid_h, grid_w = height // 16, width // 16 + for hand, side in enumerate(("left", "right")): + heat = rgb_attention[0, time_index, hand].float().cpu().numpy().reshape(grid_h, grid_w) + heat = (heat - heat.min()) / max(float(heat.max() - heat.min()), 1e-8) + heat = cv2.resize(np.uint8(heat * 255), (width, height), interpolation=cv2.INTER_CUBIC) + heat = cv2.applyColorMap(heat, cv2.COLORMAP_TURBO) + cv2.imwrite(str(args.output_dir / f"{visualization_index:02d}_{side}_attention.jpg"), cv2.addWeighted(image, .55, heat, .45, 0)) + if "depth_cross_attention" in prediction["attention"]: + depth_attention = prediction["attention"]["depth_cross_attention"][:, -1] + depth_heat = depth_attention[0, time_index, hand].float().cpu().numpy().reshape(grid_h, grid_w) + depth_heat = (depth_heat - depth_heat.min()) / max(float(depth_heat.max() - depth_heat.min()), 1e-8) + depth_heat = cv2.resize(np.uint8(depth_heat * 255), (width, height), interpolation=cv2.INTER_CUBIC) + depth_heat = cv2.applyColorMap(depth_heat, cv2.COLORMAP_TURBO) + cv2.imwrite( + str(args.output_dir / f"{visualization_index:02d}_{side}_depth_attention.jpg"), + cv2.addWeighted(image, .55, depth_heat, .45, 0), + ) + visualization_index += 1 + + with (args.output_dir / "per_frame_metrics.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(frame_rows[0])); writer.writeheader(); writer.writerows(frame_rows) + + train_rows = [json.loads(line) for line in args.train_log.read_text(encoding="utf-8").splitlines() if line] + fig, axes = plt.subplots(1, 3, figsize=(15, 4)) + axes[0].plot([row["step"] for row in train_rows], [row["losses"]["total"] for row in train_rows]); axes[0].set_title("Total loss") + axes[1].plot([row["step"] for row in train_rows], [row["metrics"]["absolute_camera_mpjpe_mm"] for row in train_rows]); axes[1].set_title("Batch absolute MPJPE (mm)") + axes[2].plot([row["step"] for row in train_rows], [row["metrics"]["translation_z_mae_mm"] for row in train_rows]); axes[2].set_title("Batch z MAE (mm)") + for axis in axes: axis.set_xlabel("step"); axis.grid(alpha=.25) + fig.tight_layout(); fig.savefig(args.output_dir / "training_curves.png", dpi=160); plt.close(fig) + + metrics = {key: mean(item) for key, item in values.items()} + metrics.update({ + "all_absolute_mpjpe_mm": mean(values["left_absolute_mpjpe_mm"] + values["right_absolute_mpjpe_mm"]), + "all_root_relative_mpjpe_mm": mean(values["left_root_relative_mpjpe_mm"] + values["right_root_relative_mpjpe_mm"]), + "all_joint2d_error_px": mean(values["left_joint2d_error_px"] + values["right_joint2d_error_px"]), + "rgb_attention_same_peak_fraction": mean([float(value) for value in attention_same_peak]), + "rgb_attention_left_right_cosine": mean(attention_cosine), + "depth_attention_same_peak_fraction": mean([float(value) for value in depth_attention_same_peak]), + "temporal_attention_diagonal_mean": mean(temporal_attention_diagonal), + "temporal_attention_normalized_entropy": mean(temporal_attention_entropy), + "bimanual_cross_attention_mean": mean(bimanual_cross_attention), + "depth_gate_mean": mean(depth_gates), + "depth_gate_min": float(min(depth_gates)) if depth_gates else None, + "depth_gate_max": float(max(depth_gates)) if depth_gates else None, + "depth_gate_raw_mean": mean(raw_depth_gates), + "depth_gate_raw_min": float(min(raw_depth_gates)) if raw_depth_gates else None, + "depth_gate_raw_max": float(max(raw_depth_gates)) if raw_depth_gates else None, + "rgb_update_norm_mean": mean(rgb_update_norms), + "depth_update_norm_mean": mean(depth_update_norms), + "gated_depth_update_norm_mean": mean(gated_depth_update_norms), + }) + report = { + "status": "evaluated", "checkpoint": str(args.checkpoint.resolve()), + "split_role": "official_train_tiny_overfit" if "tiny" in args.manifest.name else "non_test_evaluation", + "official_test_used": False, + "clips": len(dataset), "frames": frame_count, + "metrics": metrics, "mean_weighted_losses": {key: mean(item) for key, item in loss_values.items()}, + "structured_residual_diagnostics": { + key: { + "mean": mean(items), + "p95": float(np.percentile(items, 95)) if items else None, + "maximum": float(max(items)) if items else None, + } + for key, items in sorted(structured_diagnostics.items()) + }, + "buckets": { + bucket: {"valid_hands": len(items["absolute_mpjpe_mm"]), **{key: mean(values) for key, values in items.items()}} + for bucket, items in sorted(bucket_values.items()) + }, + "occlusion_bucket": "UNAVAILABLE: H2O annotation_valid is not an occlusion or presence label.", + } + if "tiny" in args.manifest.name: + report["success_thresholds"] = {"absolute_mpjpe_mm": 15.0, "root_relative_mpjpe_mm": 8.0, "joint2d_error_px": 8.0} + report["tiny_overfit_passed"] = bool( + metrics["all_absolute_mpjpe_mm"] < 15 and metrics["all_root_relative_mpjpe_mm"] < 8 and metrics["all_joint2d_error_px"] < 8 + ) + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/extract_phase4_oracle_local_depth.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/extract_phase4_oracle_local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd7ff0e89f1308c39a663fd8afde461e7acc2f5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/extract_phase4_oracle_local_depth.py @@ -0,0 +1,324 @@ +#!/usr/bin/env python3 +"""Extract frozen-model A1 oracle local-depth features without test access.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import tempfile +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.local_depth import oracle_local_depth_features +from foundation_hand.evaluation.phase4 import ( + action_name, + bimanual_asymmetry, + load_action_label, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +SIDES = ("left", "right") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_save_npz(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{path.name}.", suffix=".npz", dir=path.parent, + ) + os.close(descriptor) + temporary = Path(temporary_name) + try: + np.savez_compressed(temporary, **arrays) + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError("A1 extraction produced no valid hand rows") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--split-role", choices=("official_train", "official_validation"), required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--expected-manifest-sha256", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--max-clips", type=int) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if "test" in args.manifest.name.lower() or "test" in args.split_role: + raise ValueError("Phase 4 A1 explicitly prohibits official-test access") + output_npz = args.output_dir / "features.npz" + output_csv = args.output_dir / "samples.csv" + output_json = args.output_dir / "extraction.json" + if any(path.exists() for path in (output_npz, output_csv, output_json)): + raise FileExistsError(f"refusing to overwrite existing A1 extraction in {args.output_dir}") + + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + if checkpoint_hash != args.expected_checkpoint_sha256: + raise ValueError("checkpoint hash differs from the registered Phase 3 reference") + if manifest_hash != args.expected_manifest_sha256: + raise ValueError("manifest hash differs from the registered Phase 4 protected input") + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), + (int(data_config["stride"]),), + max_clips=args.max_clips, + ) + loader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint_state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + chunks: dict[str, list[np.ndarray]] = { + "control": [], + "local": [], + "coarse_translation_m": [], + "target_translation_m": [], + "coarse_joints_m": [], + "target_joints_m": [], + "direct_joints_2d_px": [], + "target_joints_2d_px": [], + "K_resized": [], + } + rows: list[dict[str, object]] = [] + raw_intrinsics: dict[str, np.ndarray] = {} + control_names: tuple[str, ...] | None = None + local_names: tuple[str, ...] | None = None + + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = move_to_device(batch_cpu, device) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + frame_valid = batch["frame_valid"][0].bool() + annotation_valid = batch["joint_annotation_valid"][0].bool() & frame_valid[:, None] + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"][0].float().cpu().numpy() + direct_2d *= np.asarray((width, height), dtype=np.float32) + coarse_translation = prediction["wrist_root_translation"][0].float().cpu().numpy() + coarse_joints = prediction["joints_camera"][0].float().cpu().numpy() + target_translation = batch["wrist_root_translation"][0].float().cpu().numpy() + target_joints = batch["joint3d_camera"][0].float().cpu().numpy() + target_2d_resized = batch["joint2d"][0].float().cpu().numpy() + + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + take_dir = args.root / take + if take not in raw_intrinsics: + K_raw, raw_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + raw_intrinsics[take] = K_raw + else: + K_raw = raw_intrinsics[take] + raw_hw = None + + for time_index in torch.where(frame_valid)[0].cpu().tolist(): + frame_id = int(batch["frame_id"][0, time_index]) + stem = f"{frame_id:06d}" + raw_depth_mm = cv2.imread( + str(take_dir / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED, + ) + if raw_depth_mm is None: + raise RuntimeError(f"cannot read raw depth {take_dir}/depth/{stem}.png") + if raw_hw is not None and raw_depth_mm.shape != raw_hw: + raise ValueError(f"raw depth/K size mismatch at {take}/{stem}") + raw_depth_m, raw_depth_valid = depth_mm_to_m(raw_depth_mm) + target_2d_raw, positive = project_points(target_joints[time_index], K_raw) + + frame_sizes: list[float | None] = [None, None] + frame_depths: list[float | None] = [None, None] + for hand in range(2): + if bool(annotation_valid[time_index, hand]): + extent = ( + target_2d_resized[time_index, hand].max(axis=0) + - target_2d_resized[time_index, hand].min(axis=0) + ) + frame_sizes[hand] = float(extent.max()) + frame_depths[hand] = float(target_translation[time_index, hand, 2]) + asymmetry = bimanual_asymmetry(frame_sizes, frame_depths) + label = load_action_label(args.root, take, frame_id) + + clip_features: dict[str, list[np.ndarray]] = {key: [] for key in chunks} + clip_rows: list[dict[str, object]] = [] + for hand, side in enumerate(SIDES): + if not bool(annotation_valid[time_index, hand]): + continue + if not bool(positive[hand].all()): + raise ValueError(f"valid GT hand projects behind camera at {take}/{stem}/{side}") + features = oracle_local_depth_features( + raw_depth_m, + raw_depth_valid, + target_2d_raw[hand], + K_raw, + coarse_translation[time_index, hand], + hand, + ) + if control_names is None: + control_names, local_names = features.control_names, features.local_names + elif features.control_names != control_names or features.local_names != local_names: + raise AssertionError("A1 feature schema changed within one extraction") + clip_features["control"].append(features.control) + clip_features["local"].append(features.local) + clip_features["coarse_translation_m"].append(coarse_translation[time_index, hand]) + clip_features["target_translation_m"].append(target_translation[time_index, hand]) + clip_features["coarse_joints_m"].append(coarse_joints[time_index, hand]) + clip_features["target_joints_m"].append(target_joints[time_index, hand]) + clip_features["direct_joints_2d_px"].append(direct_2d[time_index, hand]) + clip_features["target_joints_2d_px"].append(target_2d_resized[time_index, hand]) + clip_features["K_resized"].append( + batch["K"][0, time_index].float().cpu().numpy() + ) + clip_rows.append({ + "sample_index": len(rows) + len(clip_rows), + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "side": side, + "side_index": hand, + "action_family": str(batch["sequence_id"][0]).split("/", 1)[0], + "action_label": label, + "action_name": action_name(label), + "hand_size_px": frame_sizes[hand], + "wrist_depth_m": frame_depths[hand], + "bimanual_size_ratio": asymmetry["bimanual_size_ratio"], + "bimanual_depth_gap_m": asymmetry["bimanual_depth_gap_m"], + "bimanual_asymmetry_bucket": asymmetry["bimanual_asymmetry_bucket"], + "local_depth_valid_fraction": features.local_valid_fraction, + "local_depth_discontinuity_m": features.local_depth_discontinuity_m, + }) + if clip_rows: + for key, values in clip_features.items(): + chunks[key].append(np.stack(values).astype(np.float32)) + rows.extend(clip_rows) + + if (clip_index + 1) % 250 == 0: + print( + f"clips={clip_index + 1}/{len(dataset)} valid_hands={len(rows)}", + flush=True, + ) + + if control_names is None or local_names is None: + raise ValueError("A1 extraction found no annotation-valid hands") + arrays = {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + sample_count = len(rows) + if any(value.shape[0] != sample_count for value in arrays.values()): + raise AssertionError("A1 array and metadata row counts differ") + arrays["target_residual_z_m"] = ( + arrays["target_translation_m"][:, 2] - arrays["coarse_translation_m"][:, 2] + ).astype(np.float32) + if not all(np.isfinite(value).all() for value in arrays.values()): + raise ValueError("A1 extraction contains non-finite values") + + args.output_dir.mkdir(parents=True, exist_ok=True) + atomic_save_npz(output_npz, arrays) + write_csv(output_csv, rows) + report = { + "status": "extracted", + "phase": 4, + "wave": "A1_oracle_local_depth", + "split_role": args.split_role, + "official_test_used": False, + "oracle_contract": ( + "GT 2D joints locate multiscale regions in original aligned metric depth only; " + "GT wrist depth is a target and is never an input feature." + ), + "control_contract": ( + "The control receives the same oracle location, K, side and coarse translation " + "but no local depth or XYZ statistics." + ), + "config": str(args.config.resolve()), + "data_root": str(args.root.resolve()), + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": checkpoint_hash, + "step": int(checkpoint_state["step"]), + }, + "dataset_clips": len(dataset), + "valid_hand_samples": sample_count, + "control_dim": len(control_names), + "local_dim": len(local_names), + "control_feature_names": list(control_names), + "local_feature_names": list(local_names), + "precision": config["precision"], + "device": torch.cuda.get_device_name(device), + "outputs": { + "features": str(output_npz.resolve()), + "samples": str(output_csv.resolve()), + }, + } + output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": "complete", "samples": sample_count, "output": str(args.output_dir)})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_fold_milestone_recovery.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_fold_milestone_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..146372c43331db29514bf7bbef1d96c7be0c0103 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_fold_milestone_recovery.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Validate recovered fold milestones and atomically complete canonical states.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.run_phase9_fold_milestone_eval import ( + atomic_json, + h2o_milestones, + milestone_checkpoint, + sha256, +) +from scripts.run_phase9_fold_shard import fold_evaluation_complete +from scripts.run_phase9_external_milestone_eval import stable_checkpoint_sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def expected_shard_evaluations( + registry: dict[str, Any], shard: int, output_root: Path, +) -> list[str]: + conditions = {item["condition"]: item for item in registry["conditions"]} + expected: list[str] = [] + for condition_id in registry["shards"][str(shard)]: + condition = conditions[condition_id] + config_path = Path(condition["config"]) + if sha256(config_path) != condition["config_sha256"]: + raise RuntimeError(f"fold config hash differs: {condition_id}") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + heldout = Path(config["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + run_dir = Path(condition["output_dir"]) + for milestone_id in h2o_milestones(config): + checkpoint = milestone_checkpoint(run_dir, milestone_id) + if checkpoint is None: + raise RuntimeError(f"missing checkpoint: {condition_id}:{milestone_id}") + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + evaluation_id = f"{condition_id}_{milestone_id}_{mode}" + output = output_root / condition_id / milestone_id / mode + if not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + raise RuntimeError(f"invalid recovered output: {evaluation_id}") + expected.append(evaluation_id) + return expected + + +def finalize(plan_path: Path) -> dict[str, Any]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + plan_hash = sha256(plan_path) + if plan.get("official_test_used") is not False: + raise RuntimeError("recovery plan must explicitly exclude official test") + registry_path = Path(plan["registry"]) + if sha256(registry_path) != plan["registry_sha256"]: + raise RuntimeError("registry SHA256 differs") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + worker_states: dict[str, str] = {} + recovered_ids: set[str] = set() + for worker in plan["workers"]: + state_path = Path(worker["state"]) + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or state.get("recovery_plan_sha256") != plan_hash + or state.get("recovery_worker_id") != worker["id"] + or set(state.get("assigned_evaluation_ids", [])) + != set(worker["evaluation_ids"]) + or not set(worker["evaluation_ids"]).issubset(state.get("completed_ids", [])) + ): + raise RuntimeError(f"incomplete recovery worker: {worker['id']}") + overlap = recovered_ids.intersection(worker["evaluation_ids"]) + if overlap: + raise RuntimeError(f"overlapping recovery IDs: {sorted(overlap)}") + recovered_ids.update(worker["evaluation_ids"]) + worker_states[worker["id"]] = sha256(state_path) + + completed_states: dict[str, Any] = {} + for shard_record in plan["canonical_states"]: + shard = int(shard_record["shard"]) + state_path = Path(shard_record["path"]) + if sha256(state_path) != shard_record["failed_state_sha256"]: + raise RuntimeError(f"canonical shard{shard} state changed during recovery") + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("registry_sha256") != plan["registry_sha256"] + or state.get("official_test_used") is not False + ): + raise RuntimeError(f"canonical shard{shard} binding differs") + expected = expected_shard_evaluations( + registry, shard, Path(plan["output_root"]), + ) + if len(expected) != 54 or len(set(expected)) != 54: + raise RuntimeError(f"shard{shard} expected evaluation count differs") + if not set(state.get("completed_ids", [])).union(recovered_ids).issuperset(expected): + raise RuntimeError(f"shard{shard} recovery coverage is incomplete") + state["recovered_failure"] = state.pop("failure", None) + state["status"] = "complete" + state["completed_ids"] = expected + state["allowed_physical_gpus"] = [0, 1, 2, 3, 4, 5] + state["resource_amendment"] = "gpu_4_5_evaluator_authorization_only_20260730" + state["recovery_plan"] = str(plan_path.resolve()) + state["recovery_plan_sha256"] = plan_hash + state["recovery_worker_state_sha256"] = worker_states + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state.pop("waiting_for", None) + atomic_json(state_path, state) + completed_states[str(shard)] = { + "path": str(state_path.resolve()), + "sha256": sha256(state_path), + "completed_ids": len(expected), + } + return { + "schema_version": "phase9_fold_milestone_recovery_merge_v1", + "status": "complete", + "recovery_plan": str(plan_path.resolve()), + "recovery_plan_sha256": plan_hash, + "canonical_states": completed_states, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + result = finalize(args.plan) + args.report.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.report, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_last2.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_last2.py new file mode 100644 index 0000000000000000000000000000000000000000..a32e407fc52390193f3f562b6d9ab92d00625032 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_last2.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Freeze the ordered Stage 9 decision after both candidate controllers finish.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +import time +from typing import Any + +from scripts.phase9_distributed_assignment import detect_machine, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if detect_machine(assignment, None) != "taku3": + raise ValueError("last-2 finalizer is owned only by Taku3") + if ( + plan.get("schema_version") != "phase9_last2_finalizer_plan_v1" + or plan.get("candidate_order") != ["5e7", "1e6"] + or plan.get("selection_rule") + != "retain_preceding_then_5e7_then_1e6_only_on_each_strict_gate" + or plan.get("dino_large_admitted") is not False + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("last-2 finalizer contract differs") + for candidate in plan["candidate_order"]: + spec = plan["candidates"][candidate] + plan_path = Path(spec["plan"]) + if not plan_path.is_file() or sha256(plan_path) != spec["plan_sha256"]: + raise ValueError(f"last-2 {candidate} plan binding differs") + controller_plan = read_json(plan_path) + if ( + controller_plan.get("candidate") != candidate + or Path(controller_plan["controller_state"]).resolve() + != Path(spec["state"]).resolve() + or Path(controller_plan["decision_report"]).resolve() + != Path(spec["report"]).resolve() + ): + raise ValueError(f"last-2 {candidate} paths differ") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"last-2 finalizer binding differs: {path}") + + +def candidate_result( + candidate: str, spec: dict[str, Any], +) -> tuple[str, dict[str, Any] | None, dict[str, Any] | None]: + state_path = Path(spec["state"]) + if not state_path.is_file(): + return "waiting", None, None + state = read_json(state_path) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed"): + return "failed", state, None + return "waiting", state, None + if ( + state.get("candidate") != candidate + or state.get("plan_sha256") != spec["plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + return "failed", state, None + report_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + not report_path.is_file() + or report_path.resolve() != Path(spec["report"]).resolve() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + ): + return "failed", state, None + report = read_json(report_path) + accepted = report.get("gate", {}).get("accepted") + if ( + report.get("schema_version") != "phase9_last2_candidate_decision_v1" + or report.get("status") != "complete" + or report.get("candidate") != candidate + or accepted not in {True, False} + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + return "failed", state, report + if accepted and ( + report.get("gate", {}).get("macro_strictly_improved") is not True + or report.get("gate", {}).get("worst_domain_strictly_improved") is not True + or state.get("admitted") is not True + ): + return "failed", state, report + return "complete", state, report + + +def build_final_report( + plan: dict[str, Any], results: dict[str, tuple[dict[str, Any], dict[str, Any]]], + *, created_utc: str | None = None, +) -> dict[str, Any]: + five_state, five = results["5e7"] + one_state, one = results["1e6"] + if one["gate"]["accepted"] and not five["gate"]["accepted"]: + raise ValueError("1e-6 cannot be accepted after a rejected 5e-7 candidate") + if one["gate"]["accepted"]: + selected = "last2_1e6" + selected_report = one + elif five["gate"]["accepted"]: + selected = "last2_5e7" + selected_report = five + else: + selected = "preceding_mechanism" + selected_report = None + reports = {} + for candidate, (state, report) in results.items(): + path = Path(plan["candidates"][candidate]["report"]) + reports[candidate] = { + "path": str(path.resolve()), + "sha256": sha256(path), + "admitted": state.get("admitted") is True, + "accepted": report["gate"]["accepted"], + "decision": report["decision"], + "candidate_training_gpu_hours": float( + report.get("candidate_training_gpu_hours", 0.0) + ), + } + total_gpu_hours = sum( + item["candidate_training_gpu_hours"] for item in reports.values() + ) + return { + "schema_version": "phase9_last2_final_decision_v1", + "status": "complete", + "created_utc": created_utc or utc_now(), + "candidate_order": list(plan["candidate_order"]), + "selection_rule": plan["selection_rule"], + "selected": selected, + "last2_accepted": selected_report is not None, + "selected_candidate_report": ( + reports["1e6"] if selected == "last2_1e6" + else reports["5e7"] if selected == "last2_5e7" + else None + ), + "selected_candidate_training_jobs": ( + selected_report.get("candidate_training_jobs") + if selected_report is not None else None + ), + "candidate_reports": reports, + "total_candidate_training_gpu_hours": total_gpu_hours, + "rejection_disclosure": { + candidate: report.get("not_admitted_reason") + or report.get("gate", {}).get("rejection_reason") + for candidate, (_, report) in results.items() + if report["gate"]["accepted"] is False + }, + "dino_large_admitted": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("last-2 finalizer state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_last2_finalizer_state_v1", + "status": "waiting_for_candidate_controllers", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing last-2 finalizer state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + statuses = {} + ready = {} + failed = None + for candidate in plan["candidate_order"]: + status, candidate_state, report = candidate_result( + candidate, plan["candidates"][candidate], + ) + statuses[candidate] = status + if status == "failed": + failed = candidate + elif status == "complete": + assert candidate_state is not None and report is not None + ready[candidate] = (candidate_state, report) + state["candidate_statuses"] = statuses + state["updated_utc"] = utc_now() + if failed is not None: + state["status"] = "failed_candidate_binding" + state["failure_candidate"] = failed + atomic_json(args.state, state) + raise SystemExit(1) + if len(ready) == len(plan["candidate_order"]): + break + state["status"] = "waiting_for_candidate_controllers" + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + report_path = Path(plan["report"]) + report_path.parent.mkdir(parents=True, exist_ok=True) + state.setdefault("decision_created_utc", utc_now()) + state["status"] = "publishing_decision" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + report = build_final_report( + plan, ready, created_utc=state["decision_created_utc"], + ) + if report_path.exists(): + if read_json(report_path) != report: + state["status"] = "failed_existing_report_differs" + atomic_json(args.state, state) + raise SystemExit(1) + else: + atomic_json(report_path, report) + state["status"] = "complete" + state["decision"] = report["selected"] + state["decision_report"] = { + "path": str(report_path.resolve()), "sha256": sha256(report_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_resolution_cache.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e6d32a6109f73a7c0dc2b0fdefe9cb8fa15bc6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_resolution_cache.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Finalize Phase 9 resolution caches after every source worker completes.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +import time +from typing import Any + +from scripts.audit_phase9_resolution_cache import audit +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + sha256, + validate_plan_bindings, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_admission(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + path = Path(plan["admission_state"]) + if not path.is_file(): + raise ValueError("resolution admission state is missing") + state = json.loads(path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution admission state differs") + return state + + +def inspect_workers( + plan_path: Path, plan: dict[str, Any], admission: dict[str, Any] +) -> tuple[str, list[dict[str, Any]]]: + records = [] + overall = "complete" + for worker in plan["workers"]: + path = Path(worker["state"]) + if not path.is_file(): + overall = "waiting_for_workers" + records.append({"worker": worker["id"], "status": "missing"}) + continue + state = json.loads(path.read_text(encoding="utf-8")) + status = state.get("status") + if str(status).startswith("failed"): + overall = "failed_dependency" + elif status != "complete" and overall != "failed_dependency": + overall = "waiting_for_workers" + if ( + state.get("worker") != worker["id"] + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution worker state differs: {worker['id']}") + if status == "complete" and ( + state.get("winner") != admission.get("winner") + or state.get("winner_checkpoint") != admission.get("winner_checkpoint") + or state.get("winner_config") != admission.get("winner_config") + or state.get("admission_state_sha256") != sha256(plan["admission_state"]) + ): + raise ValueError(f"resolution worker winner binding differs: {worker['id']}") + records.append({ + "worker": worker["id"], + "status": status, + "state": str(path.resolve()), + "state_sha256": sha256(path), + }) + return overall, records + + +def validate_existing_completion( + plan_path: Path, plan: dict[str, Any], state: dict[str, Any] +) -> bool: + audit_path = Path(plan["audit_output"]) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == sha256(plan_path) + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and audit_path.is_file() + and state.get("audit", {}).get("sha256") == sha256(audit_path) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan_bindings(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["readiness_state"]).resolve(): + parser.error("readiness state path differs from plan") + + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.state.is_file(): + existing = json.loads(args.state.read_text(encoding="utf-8")) + if validate_existing_completion(args.plan, plan, existing): + print(json.dumps(existing, indent=2)) + return + if existing.get("plan_sha256") not in (None, sha256(args.plan)): + parser.error("existing readiness state belongs to another plan") + + state: dict[str, Any] = { + "schema_version": "phase9_resolution_cache_readiness_v1", + "status": "waiting_for_admission", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, + "official_test_used": False, + } + while True: + try: + admission = validate_admission(args.plan, plan) + worker_status, workers = inspect_workers(args.plan, plan, admission) + except ValueError as error: + if "admission state is missing" in str(error): + state["status"] = "waiting_for_admission" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_validation" + state["failure"] = str(error) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + state["workers"] = workers + state["status"] = worker_status + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if worker_status == "failed_dependency": + raise SystemExit(1) + if worker_status != "complete": + time.sleep(args.poll_seconds) + continue + break + + audit_path = Path(plan["audit_output"]) + if audit_path.exists(): + existing_audit = json.loads(audit_path.read_text(encoding="utf-8")) + if ( + existing_audit.get("status") != "complete" + or existing_audit.get("plan_sha256") != sha256(args.plan) + or existing_audit.get("official_test_used") is not False + or existing_audit.get("h2o_official_validation_used") is not False + ): + state["status"] = "failed_existing_audit" + atomic_json(args.state, state) + raise SystemExit(1) + else: + state["status"] = "auditing" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + try: + result = audit(plan) + except Exception as error: + state["status"] = "failed_audit" + state["failure"] = f"{type(error).__name__}: {error}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise + result.update({ + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "admission_state": str(Path(plan["admission_state"]).resolve()), + "admission_state_sha256": sha256(plan["admission_state"]), + "winner": admission["winner"], + "winner_checkpoint": admission["winner_checkpoint"], + "winner_config": admission["winner_config"], + "worker_states": workers, + }) + audit_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(audit_path, result) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["admission_state_sha256"] = sha256(plan["admission_state"]) + state["winner"] = admission["winner"] + state["winner_checkpoint"] = admission["winner_checkpoint"] + state["winner_config"] = admission["winner_config"] + state["audit"] = { + "path": str(audit_path.resolve()), + "sha256": sha256(audit_path), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_selection_binding_recovery.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d8d4a11430f20985ff8c87f96eb749783db882 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/finalize_phase9_selection_binding_recovery.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Publish one host's complete selection recovery as an immutable release.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +from typing import Any + +from scripts.run_phase9_selection_binding_recovery import ( + atomic_json, + validate_recovered_output, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def release_root(plan: dict[str, Any], owner: str) -> Path: + assignment = json.loads( + Path(plan["distributed_assignment"]["path"]).read_text(encoding="utf-8") + ) + return Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + + +def build_release( + *, plan_path: Path, owner: str, output: Path, +) -> dict[str, Any]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + plan_hash = sha256(plan_path) + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"selection recovery code binding differs: {path}") + root = release_root(plan, owner).resolve() + if output.parent.resolve() != root: + raise ValueError("selection recovery release must live at its frozen root") + owner_workers = [item for item in plan["workers"] if item["owner"] == owner] + owner_evaluations = [ + item for item in plan["evaluations"] if item["owner"] == owner + ] + expected_ids = {item["id"] for item in owner_evaluations} + completed_ids: set[str] = set() + worker_states = [] + for worker in owner_workers: + state_path = Path(worker["state"]) + if not state_path.is_file(): + raise ValueError(f"selection recovery worker state missing: {worker['id']}") + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("owner") != owner + or state.get("plan_sha256") != plan_hash + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or set(state.get("completed_ids", [])) + != set(worker["evaluation_ids"]) + ): + raise ValueError( + f"selection recovery worker state differs: {worker['id']}" + ) + completed_ids.update(state["completed_ids"]) + worker_states.append({ + "id": worker["id"], "path": str(state_path.resolve()), + "sha256": sha256(state_path), + }) + if completed_ids != expected_ids: + raise ValueError("selection recovery completed IDs differ") + evaluation_evidence = [] + files = [] + seen_relative_paths: set[str] = set() + for item in owner_evaluations: + evidence = validate_recovered_output(item) + directory = Path(item["output_dir"]).resolve() + try: + relative_output = directory.relative_to(root) + except ValueError as error: + raise ValueError("recovery output is outside owner root") from error + for path in sorted(directory.rglob("*")): + if path.is_symlink() or not path.is_file(): + if path.is_symlink(): + raise ValueError(f"recovery release refuses symlink: {path}") + continue + relative = str(path.resolve().relative_to(root)) + if relative in seen_relative_paths: + raise ValueError(f"duplicate recovery release path: {relative}") + seen_relative_paths.add(relative) + files.append({ + "path": relative, "sha256": sha256(path), + "bytes": path.stat().st_size, + }) + evaluation_evidence.append({ + "id": item["id"], "output_dir": str(relative_output), **evidence, + }) + return { + "schema_version": "phase9_selection_binding_recovery_release_v1", + "status": "complete_immutable_release", + "created_utc": datetime.now(timezone.utc).isoformat(), + "owner": owner, + "plan": {"path": str(plan_path.resolve()), "sha256": plan_hash}, + "distributed_assignment": plan["distributed_assignment"], + "root": str(root), + "worker_states": worker_states, + "evaluation_ids": sorted(expected_ids), + "evaluations": evaluation_evidence, + "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "read_only_after_publish": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--owner", choices=("taku3", "server_new"), required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = build_release(plan_path=args.plan, owner=args.owner, output=args.output) + if args.output.exists(): + existing = json.loads(args.output.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("owner") == args.owner + and existing.get("plan", {}).get("sha256") + == result["plan"]["sha256"] + and existing.get("files") == result["files"] + and existing.get("evaluations") == result["evaluations"] + ): + print(json.dumps(existing, indent=2)) + return + parser.error("existing recovery release differs") + atomic_json(args.output, result) + for item in result["files"]: + os.chmod(Path(result["root"]) / item["path"], 0o444) + os.chmod(args.output, 0o444) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase4_oracle_local_depth.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase4_oracle_local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..61cdc0efdd02dd690411a6cae7f8faf78c60a242 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase4_oracle_local_depth.py @@ -0,0 +1,605 @@ +#!/usr/bin/env python3 +"""Fit and evaluate the Phase 4 A1 bounded oracle wrist-z diagnostic.""" + +from __future__ import annotations + +import argparse +import copy +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.nn.functional as F + +from foundation_hand.evaluation.local_depth import BoundedZResidualRegressor +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import project_points + + +FINGERTIPS = (4, 8, 12, 16, 20) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV {path}") + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def stable_take_holdout(takes: list[str], modulus: int = 5) -> np.ndarray: + """Select a deterministic official-train-only holdout by complete take.""" + + if modulus < 2: + raise ValueError("holdout modulus must be at least two") + output = [] + for take in takes: + digest = hashlib.sha256(take.encode("utf-8")).digest() + output.append(int.from_bytes(digest[:8], "little") % modulus == 0) + return np.asarray(output, dtype=bool) + + +def padded_control(control: np.ndarray, local_dim: int) -> np.ndarray: + if control.ndim != 2 or control.shape[1] > local_dim: + raise ValueError("invalid control/local feature dimensions") + output = np.zeros((control.shape[0], local_dim), dtype=np.float32) + output[:, : control.shape[1]] = control + return output + + +def standardizer(features: np.ndarray, fit_mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + values = features[fit_mask].astype(np.float64) + mean = values.mean(axis=0).astype(np.float32) + std = values.std(axis=0).astype(np.float32) + std[std < 1e-6] = 1.0 + return mean, std + + +def fit_regressor( + features: np.ndarray, + target_m: np.ndarray, + train_mask: np.ndarray, + holdout_mask: np.ndarray, + *, + device: torch.device, + seed: int, + hidden_dim: int, + max_residual_m: float, + learning_rate: float, + weight_decay: float, + batch_size: int, + epochs: int, + patience: int, +) -> tuple[BoundedZResidualRegressor, np.ndarray, np.ndarray, list[dict[str, float | int]]]: + mean, std = standardizer(features, train_mask) + normalized = (features.astype(np.float32) - mean) / std + x = torch.from_numpy(normalized).to(device) + target = torch.from_numpy(target_m.astype(np.float32)).to(device) + train_indices = torch.from_numpy(np.where(train_mask)[0]).to(device) + holdout_indices = torch.from_numpy(np.where(holdout_mask)[0]).to(device) + if not train_indices.numel() or not holdout_indices.numel(): + raise ValueError("official-train fit/holdout split is empty") + + torch.manual_seed(seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(seed) + model = BoundedZResidualRegressor( + features.shape[1], hidden_dim=hidden_dim, max_residual_m=max_residual_m, + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=learning_rate, weight_decay=weight_decay, + ) + generator = torch.Generator(device=device).manual_seed(seed) + best_state = copy.deepcopy(model.state_dict()) + best_holdout = float("inf") + stale = 0 + history: list[dict[str, float | int]] = [] + for epoch in range(1, epochs + 1): + model.train() + shuffled = train_indices[torch.randperm(train_indices.numel(), generator=generator, device=device)] + losses = [] + for start in range(0, shuffled.numel(), batch_size): + indices = shuffled[start : start + batch_size] + optimizer.zero_grad(set_to_none=True) + prediction = model(x[indices]) + loss = F.smooth_l1_loss(prediction, target[indices], beta=0.01) + if not torch.isfinite(loss): + raise FloatingPointError("non-finite A1 training loss") + loss.backward() + optimizer.step() + losses.append(float(loss.detach())) + model.eval() + with torch.inference_mode(): + holdout_prediction = model(x[holdout_indices]) + holdout_mae = float((holdout_prediction - target[holdout_indices]).abs().mean()) + history.append({ + "epoch": epoch, + "train_smooth_l1": float(np.mean(losses)), + "holdout_residual_mae_m": holdout_mae, + }) + if holdout_mae < best_holdout - 1e-6: + best_holdout = holdout_mae + best_state = copy.deepcopy(model.state_dict()) + stale = 0 + else: + stale += 1 + if stale >= patience: + break + model.load_state_dict(best_state) + return model, mean, std, history + + +def infer_residual( + model: BoundedZResidualRegressor, + features: np.ndarray, + mean: np.ndarray, + std: np.ndarray, + device: torch.device, + batch_size: int = 8192, +) -> np.ndarray: + model.eval() + output = [] + with torch.inference_mode(): + for start in range(0, features.shape[0], batch_size): + values = (features[start : start + batch_size].astype(np.float32) - mean) / std + output.append(model(torch.from_numpy(values).to(device)).cpu().numpy()) + result = np.concatenate(output).astype(np.float32) + if not np.isfinite(result).all(): + raise FloatingPointError("A1 residual inference produced non-finite values") + return result + + +def variant_metrics( + arrays: dict[str, np.ndarray], residual_m: np.ndarray, +) -> dict[str, np.ndarray]: + coarse_translation = arrays["coarse_translation_m"] + target_translation = arrays["target_translation_m"] + coarse_joints = arrays["coarse_joints_m"] + target_joints = arrays["target_joints_m"] + refined_translation = coarse_translation.copy() + refined_translation[:, 2] += residual_m + refined_joints = coarse_joints.copy() + refined_joints[:, :, 2] += residual_m[:, None] + joint_error = np.linalg.norm(refined_joints - target_joints, axis=-1) * 1000.0 + relative_prediction = refined_joints - refined_joints[:, :1] + relative_target = target_joints - target_joints[:, :1] + relative_error = np.linalg.norm(relative_prediction - relative_target, axis=-1) * 1000.0 + translation_error = (refined_translation - target_translation) * 1000.0 + projected, positive = project_points(refined_joints, arrays["K_resized"]) + if not bool(positive.all()): + raise ValueError("A1 refined MANO joints project behind the camera") + target_2d = arrays["target_joints_2d_px"] + direct_2d = arrays["direct_joints_2d_px"] + return { + "absolute_mpjpe_mm": joint_error.mean(axis=1), + "root_relative_mpjpe_mm": relative_error.mean(axis=1), + "fingertip_mpjpe_mm": joint_error[:, FINGERTIPS].mean(axis=1), + "translation_z_signed_error_mm": translation_error[:, 2], + "translation_z_mae_mm": np.abs(translation_error[:, 2]), + "direct_2d_error_px": np.linalg.norm(direct_2d - target_2d, axis=-1).mean(axis=1), + "mano_projected_2d_error_px": np.linalg.norm(projected - target_2d, axis=-1).mean(axis=1), + "direct_mano_consistency_px": np.linalg.norm(direct_2d - projected, axis=-1).mean(axis=1), + "residual_magnitude_mm": np.abs(residual_m) * 1000.0, + "predicted_wrist_xyz_m": refined_translation, + "predicted_joints_m": refined_joints, + } + + +def temporal_metrics( + metadata: list[dict[str, str]], + target_translation: np.ndarray, + predictions: dict[str, dict[str, np.ndarray]], +) -> dict[str, dict[str, np.ndarray]]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(metadata): + groups[(row["take"], row["side"])].append(index) + output = { + variant: { + "wrist_velocity_error_mm_per_frame": [], + "wrist_acceleration_error_mm_per_frame2": [], + } + for variant in predictions + } + for indices in groups.values(): + ordered = sorted(indices, key=lambda index: int(metadata[index]["frame_id"])) + for position in range(1, len(ordered)): + previous, current = ordered[position - 1], ordered[position] + if int(metadata[current]["frame_id"]) != int(metadata[previous]["frame_id"]) + 1: + continue + target_velocity = target_translation[current] - target_translation[previous] + for variant, metrics in predictions.items(): + wrist = metrics["predicted_wrist_xyz_m"] + error = np.linalg.norm((wrist[current] - wrist[previous]) - target_velocity) * 1000.0 + output[variant]["wrist_velocity_error_mm_per_frame"].append(float(error)) + for position in range(2, len(ordered)): + first, second, third = ordered[position - 2 : position + 1] + frame_ids = [int(metadata[index]["frame_id"]) for index in (first, second, third)] + if frame_ids[1] != frame_ids[0] + 1 or frame_ids[2] != frame_ids[1] + 1: + continue + target_acceleration = target_translation[third] - 2 * target_translation[second] + target_translation[first] + for variant, metrics in predictions.items(): + wrist = metrics["predicted_wrist_xyz_m"] + acceleration = wrist[third] - 2 * wrist[second] + wrist[first] + error = np.linalg.norm(acceleration - target_acceleration) * 1000.0 + output[variant]["wrist_acceleration_error_mm_per_frame2"].append(float(error)) + return { + variant: {metric: np.asarray(values, dtype=np.float32) for metric, values in metrics.items()} + for variant, metrics in output.items() + } + + +def summarize_groups( + metadata: list[dict[str, str]], + variants: dict[str, dict[str, np.ndarray]], + temporal: dict[str, dict[str, np.ndarray]], + challenge: dict[str, Any], +) -> list[dict[str, object]]: + farthest = float(challenge["thresholds"]["farthest_observed_wrist_depth_p80_m"]) + challenge_clips = set(int(value) for value in challenge["clip_indices"]) + masks = { + "all": np.ones(len(metadata), dtype=bool), + "left": np.asarray([row["side"] == "left" for row in metadata]), + "right": np.asarray([row["side"] == "right" for row in metadata]), + "small": np.asarray([float(row["hand_size_px"]) < 64.0 for row in metadata]), + "farthest_observed": np.asarray([ + float(row["wrist_depth_m"]) >= farthest for row in metadata + ]), + "strong_asymmetry": np.asarray([ + row["bimanual_asymmetry_bucket"] == "strong" for row in metadata + ]), + "challenge": np.asarray([int(row["clip_index"]) in challenge_clips for row in metadata]), + } + rows: list[dict[str, object]] = [] + scalar_metrics = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", + ) + for group, mask in masks.items(): + for variant, metrics in variants.items(): + for metric in scalar_metrics: + rows.append({ + "group": group, + "variant": variant, + "metric": metric, + **distribution_summary(metrics[metric][mask]), + }) + for variant, metrics in temporal.items(): + for metric, values in metrics.items(): + rows.append({ + "group": "all_contiguous_transitions", + "variant": variant, + "metric": metric, + **distribution_summary(values), + }) + return rows + + +def paired_take_bootstrap( + metadata: list[dict[str, str]], + variants: dict[str, dict[str, np.ndarray]], + *, + seed: int, + samples: int, +) -> list[dict[str, object]]: + take_indices: dict[str, list[int]] = defaultdict(list) + for index, row in enumerate(metadata): + take_indices[row["take"]].append(index) + rng = np.random.default_rng(seed) + rows: list[dict[str, object]] = [] + comparisons = (("local", "coarse"), ("local", "control"), ("control", "coarse")) + metric_stats = ( + ("absolute_mpjpe_mm", "mean"), + ("translation_z_mae_mm", "mean"), + ("translation_z_mae_mm", "p95"), + ("fingertip_mpjpe_mm", "mean"), + ("mano_projected_2d_error_px", "mean"), + ) + take_names = sorted(take_indices) + for candidate, reference in comparisons: + for metric, statistic in metric_stats: + deltas = [] + for take in take_names: + indices = take_indices[take] + candidate_values = variants[candidate][metric][indices] + reference_values = variants[reference][metric][indices] + if statistic == "mean": + delta = float(candidate_values.mean() - reference_values.mean()) + else: + delta = float(np.percentile(candidate_values, 95) - np.percentile(reference_values, 95)) + deltas.append(delta) + deltas_array = np.asarray(deltas, dtype=np.float64) + bootstrap_indices = rng.integers(0, len(deltas_array), size=(samples, len(deltas_array))) + distribution = deltas_array[bootstrap_indices].mean(axis=1) + rows.append({ + "candidate": candidate, + "reference": reference, + "metric": metric, + "per_take_statistic": statistic, + "take_count": len(deltas_array), + "paired_delta_candidate_minus_reference": float(deltas_array.mean()), + "ci95_low": float(np.percentile(distribution, 2.5)), + "ci95_high": float(np.percentile(distribution, 97.5)), + "bootstrap_samples": samples, + "bootstrap_seed": seed, + }) + return rows + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--train-extraction", type=Path, required=True) + parser.add_argument("--validation-extraction", type=Path, required=True) + parser.add_argument("--challenge-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--fit-seed", type=int, default=4401) + parser.add_argument("--holdout-modulus", type=int, default=5) + parser.add_argument("--hidden-dim", type=int, default=128) + parser.add_argument("--max-residual-m", type=float, default=0.15) + parser.add_argument("--learning-rate", type=float, default=3e-3) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--batch-size", type=int, default=4096) + parser.add_argument("--epochs", type=int, default=80) + parser.add_argument("--patience", type=int, default=12) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + return parser.parse_args() + + +def load_extraction(path: Path) -> tuple[dict[str, np.ndarray], list[dict[str, str]], dict[str, Any]]: + report = json.loads((path / "extraction.json").read_text(encoding="utf-8")) + if report.get("official_test_used") is not False: + raise ValueError("A1 extraction does not explicitly preserve official-test isolation") + arrays = dict(np.load(path / "features.npz")) + rows = read_csv(path / "samples.csv") + if any(value.shape[0] != len(rows) for value in arrays.values()): + raise ValueError(f"array/CSV length mismatch in {path}") + return arrays, rows, report + + +def main() -> None: + args = parse_args() + output_files = ( + args.output_dir / "results.json", + args.output_dir / "group_metrics.csv", + args.output_dir / "validation_predictions.csv", + args.output_dir / "paired_take_bootstrap_ci.csv", + args.output_dir / "regressors.pt", + ) + if any(path.exists() for path in output_files): + raise FileExistsError(f"refusing to overwrite existing A1 result in {args.output_dir}") + train, train_rows, train_report = load_extraction(args.train_extraction) + validation, validation_rows, validation_report = load_extraction(args.validation_extraction) + if train_report["split_role"] != "official_train": + raise ValueError("A1 fitting requires official_train extraction") + if validation_report["split_role"] != "official_validation": + raise ValueError("A1 reporting requires official_validation extraction") + if train_report["checkpoint"]["sha256"] != validation_report["checkpoint"]["sha256"]: + raise ValueError("train/validation A1 extractions use different frozen checkpoints") + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + if challenge.get("checkpoint_selection_allowed") is not False: + raise ValueError("challenge subset is not registered as secondary-only") + + holdout_mask = stable_take_holdout( + [row["take"] for row in train_rows], modulus=args.holdout_modulus, + ) + train_mask = ~holdout_mask + local_dim = train["local"].shape[1] + train_features = { + "control": padded_control(train["control"], local_dim), + "local": train["local"], + } + validation_features = { + "control": padded_control(validation["control"], local_dim), + "local": validation["local"], + } + device = torch.device(f"cuda:{args.gpu}") + regressors: dict[str, BoundedZResidualRegressor] = {} + scalers: dict[str, tuple[np.ndarray, np.ndarray]] = {} + histories: dict[str, list[dict[str, float | int]]] = {} + for index, variant in enumerate(("control", "local")): + model, mean, std, history = fit_regressor( + train_features[variant], + train["target_residual_z_m"], + train_mask, + holdout_mask, + device=device, + seed=args.fit_seed + index, + hidden_dim=args.hidden_dim, + max_residual_m=args.max_residual_m, + learning_rate=args.learning_rate, + weight_decay=args.weight_decay, + batch_size=args.batch_size, + epochs=args.epochs, + patience=args.patience, + ) + regressors[variant] = model + scalers[variant] = (mean, std) + histories[variant] = history + + residuals = {"coarse": np.zeros(len(validation_rows), dtype=np.float32)} + for variant in ("control", "local"): + mean, std = scalers[variant] + residuals[variant] = infer_residual( + regressors[variant], validation_features[variant], mean, std, device, + ) + variants = { + variant: variant_metrics(validation, residual) + for variant, residual in residuals.items() + } + coarse_root = variants["coarse"]["root_relative_mpjpe_mm"] + coarse_direct = variants["coarse"]["direct_2d_error_px"] + for variant in ("control", "local"): + if not np.allclose(variants[variant]["root_relative_mpjpe_mm"], coarse_root, atol=1e-4): + raise AssertionError("uniform A1 z residual changed root-relative geometry") + if not np.array_equal(variants[variant]["direct_2d_error_px"], coarse_direct): + raise AssertionError("A1 residual changed the frozen direct-2D head") + + temporal = temporal_metrics( + validation_rows, validation["target_translation_m"], variants, + ) + group_rows = summarize_groups(validation_rows, variants, temporal, challenge) + bootstrap_rows = paired_take_bootstrap( + validation_rows, + variants, + seed=args.fit_seed, + samples=args.bootstrap_samples, + ) + prediction_rows: list[dict[str, object]] = [] + for index, metadata in enumerate(validation_rows): + row: dict[str, object] = dict(metadata) + for variant, metrics in variants.items(): + for metric in ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", + ): + row[f"{variant}_{metric}"] = float(metrics[metric][index]) + prediction_rows.append(row) + + def summary_value(group: str, variant: str, metric: str, statistic: str) -> float: + match = next( + row for row in group_rows + if row["group"] == group and row["variant"] == variant and row["metric"] == metric + ) + return float(match[statistic]) + + coarse_z_p95 = summary_value("all", "coarse", "translation_z_mae_mm", "p95") + local_z_p95 = summary_value("all", "local", "translation_z_mae_mm", "p95") + reductions = { + "full_validation_z_p95_percent": 100.0 * (coarse_z_p95 - local_z_p95) / coarse_z_p95, + } + for group in ("small", "farthest_observed", "right"): + coarse_value = summary_value(group, "coarse", "absolute_mpjpe_mm", "mean") + local_value = summary_value(group, "local", "absolute_mpjpe_mm", "mean") + reductions[f"{group}_absolute_mpjpe_percent"] = 100.0 * (coarse_value - local_value) / coarse_value + gate_metric = ( + reductions["full_validation_z_p95_percent"] >= 20.0 + or reductions["small_absolute_mpjpe_percent"] >= 15.0 + or reductions["farthest_observed_absolute_mpjpe_percent"] >= 15.0 + ) + gate_no_regression = True # Exact by construction and asserted above. + gate = { + "registered_condition": ( + "z P95 reduction >=20% OR small/farthest-observed absolute MPJPE reduction >=15%; " + "root-relative and direct-2D degradation <=2%" + ), + "metric_gate_pass": bool(gate_metric), + "no_regression_gate_pass": gate_no_regression, + "formal_A1_gate_pass": bool(gate_metric and gate_no_regression), + "depth_increment_condition": ( + "A2 additionally requires local-depth to retain meaningful improvement beyond the " + "same-capacity oracle-location control; reported but not silently assumed." + ), + "reductions_percent": reductions, + } + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "group_metrics.csv", group_rows) + write_csv(args.output_dir / "validation_predictions.csv", prediction_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap_rows) + torch.save({ + "wave": "A1_oracle_local_depth", + "fit_seed": args.fit_seed, + "input_dim": local_dim, + "hidden_dim": args.hidden_dim, + "max_residual_m": args.max_residual_m, + "models": { + variant: {key: value.detach().cpu() for key, value in model.state_dict().items()} + for variant, model in regressors.items() + }, + "scalers": { + variant: {"mean": mean, "std": std} + for variant, (mean, std) in scalers.items() + }, + }, args.output_dir / "regressors.pt") + report = { + "status": "evaluated", + "phase": 4, + "wave": "A1_oracle_local_depth", + "official_test_used": False, + "frozen_checkpoint": validation_report["checkpoint"], + "train_manifest": train_report["manifest"], + "validation_manifest": validation_report["manifest"], + "challenge_manifest": { + "path": str(args.challenge_manifest.resolve()), + "sha256": sha256(args.challenge_manifest), + "role": "secondary diagnostic only; never checkpoint selection", + }, + "protocol": { + "fit_data": "official_train only", + "fit_holdout": ( + f"whole-take SHA256 modulus-{args.holdout_modulus} holdout within official_train" + ), + "validation": "complete official validation, one independent report", + "control": "same input dimension and MLP parameter count; local-depth fields zeroed", + "hidden_dim": args.hidden_dim, + "max_residual_m": args.max_residual_m, + "learning_rate": args.learning_rate, + "weight_decay": args.weight_decay, + "batch_size": args.batch_size, + "maximum_epochs": args.epochs, + "early_stopping_patience": args.patience, + "fit_seed": args.fit_seed, + }, + "sample_counts": { + "official_train_fit": int(train_mask.sum()), + "official_train_holdout": int(holdout_mask.sum()), + "official_validation": len(validation_rows), + }, + "parameter_counts": { + variant: sum(parameter.numel() for parameter in model.parameters()) + for variant, model in regressors.items() + }, + "histories": histories, + "gate": gate, + "outputs": { + "group_metrics": str((args.output_dir / "group_metrics.csv").resolve()), + "validation_predictions": str((args.output_dir / "validation_predictions.csv").resolve()), + "paired_take_bootstrap_ci": str((args.output_dir / "paired_take_bootstrap_ci.csv").resolve()), + "regressors": str((args.output_dir / "regressors.pt").resolve()), + }, + } + (args.output_dir / "results.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": "complete", "gate": gate, "output": str(args.output_dir)})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase5_alignment_calibrator.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase5_alignment_calibrator.py new file mode 100644 index 0000000000000000000000000000000000000000..68eb72f652ec43cc343bed31e01e11a7f82287e7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase5_alignment_calibrator.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +"""Fit shared metric-alignment correction/confidence using OOF banks only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +import joblib +import numpy as np +from sklearn.linear_model import HuberRegressor, LogisticRegression +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler + +from foundation_hand.evaluation.alignment_calibration import FEATURE_NAMES, features_from_take + +THRESHOLD_GRID = (0.50, 0.60, 0.70, 0.80, 0.90, 0.95, 1.01) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_bank_layout( + manifests: list[dict[str, Any]], expected_banks_per_fold: int, +) -> dict[str, Any]: + if expected_banks_per_fold < 1: + raise ValueError("expected banks per fold must be positive") + observed_pairs: set[tuple[int, str]] = set() + observed_fold_seeds: set[tuple[int, int]] = set() + fold_counts: Counter[int] = Counter() + seed_folds: dict[int, set[int]] = defaultdict(set) + for manifest in manifests: + fold = int(manifest["fold"]) + checkpoint = str(manifest["checkpoint"]["sha256"]) + pair = (fold, checkpoint) + if pair in observed_pairs: + raise ValueError(f"duplicate OOF fold/checkpoint bank: {pair}") + observed_pairs.add(pair) + fold_counts[fold] += 1 + seed = manifest.get("seed") + if seed is None: + if expected_banks_per_fold > 1: + raise ValueError("expanded OOF banks require an explicit coarse seed") + continue + seed = int(seed) + fold_seed = (fold, seed) + if fold_seed in observed_fold_seeds: + raise ValueError(f"duplicate OOF fold/seed bank: {fold_seed}") + observed_fold_seeds.add(fold_seed) + seed_folds[seed].add(fold) + if set(fold_counts) != {0, 1, 2}: + raise ValueError(f"shared calibrator requires folds 0/1/2, got {set(fold_counts)}") + if any(fold_counts[fold] != expected_banks_per_fold for fold in range(3)): + raise ValueError( + "OOF bank count per fold differs from --expected-banks-per-fold: " + f"{dict(sorted(fold_counts.items()))}" + ) + if expected_banks_per_fold > 1: + if len(seed_folds) != expected_banks_per_fold: + raise ValueError( + f"expected {expected_banks_per_fold} coarse seeds, got {sorted(seed_folds)}" + ) + incomplete = {seed: sorted(folds) for seed, folds in seed_folds.items() if folds != {0, 1, 2}} + if incomplete: + raise ValueError(f"each coarse seed must cover folds 0/1/2: {incomplete}") + return { + "banks_per_fold": {str(fold): fold_counts[fold] for fold in range(3)}, + "coarse_seeds": sorted(seed_folds), + } + + +def load_bank( + bank_dirs: list[Path], expected_banks_per_fold: int = 1, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = { + key: [] for key in ( + "features", "target_residual_z_m", "raw_delta_z_m", "alignment_applied", + "pred_joints_m", "target_joints_m", "side", "hand_scale_px", + "frame_id", "subject", "take", "coarse_seed", "checkpoint", + ) + } + manifests = [] + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("bank_version") != 2 + or manifest.get("scope") != "full_fold" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("leakage_audit", {}).get("passed") is not True + or manifest.get("official_test_used") is not False + or manifest.get("official_validation_used_for_assignment") is not False + ): + raise ValueError(f"calibrator requires a complete leakage-free OOF bank: {bank_dir}") + manifests.append(manifest) + validate_bank_layout(manifests, expected_banks_per_fold) + for bank_dir, manifest in zip(bank_dirs, manifests, strict=True): + seed = int(manifest.get("seed", -1)) + checkpoint = str(manifest["checkpoint"]["sha256"]) + for take_record in manifest["takes"]: + with np.load(take_record["path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + time = len(arrays["frame_id"]) + features = features_from_take(arrays) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays[ + "frame_valid" + ][:, None].astype(bool) + hand_indices = np.broadcast_to(np.arange(2)[None], (time, 2)) + frame_ids = np.broadcast_to(arrays["frame_id"][:, None], (time, 2)) + chunks["features"].append(features[valid]) + chunks["target_residual_z_m"].append(arrays["translation_residual_m"][..., 2][valid]) + chunks["raw_delta_z_m"].append(arrays["alignment_delta_z_m"][valid]) + chunks["alignment_applied"].append(arrays["alignment_applied"][valid]) + chunks["pred_joints_m"].append(arrays["pred_joints_camera"][valid]) + chunks["target_joints_m"].append(arrays["target_joints_camera"][valid]) + chunks["side"].append(hand_indices[valid]) + chunks["hand_scale_px"].append(arrays["coarse_hand_scale_px"][valid]) + chunks["frame_id"].append(frame_ids[valid]) + chunks["subject"].append(np.full(valid.sum(), str(arrays["subject"]))) + chunks["take"].append(np.full(valid.sum(), str(arrays["take"]))) + chunks["coarse_seed"].append(np.full(valid.sum(), seed, dtype=np.int64)) + chunks["checkpoint"].append(np.full(valid.sum(), checkpoint)) + return {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + + +def correction_metrics(samples: dict[str, np.ndarray], correction_m: np.ndarray) -> dict[str, float]: + correction = np.asarray(correction_m, dtype=np.float64) + pred_joints = samples["pred_joints_m"].astype(np.float64).copy() + pred_joints[..., 2] += correction[:, None] + target_joints = samples["target_joints_m"].astype(np.float64) + joint_error_mm = np.linalg.norm(pred_joints - target_joints, axis=-1) * 1000.0 + z_error_mm = np.abs(samples["target_residual_z_m"] - correction) * 1000.0 + p95 = float(np.percentile(z_error_mm, 95)) + return { + "absolute_mpjpe_mm": float(joint_error_mm.mean()), + "z_mae_mm": float(z_error_mm.mean()), + "z_p95_mm": p95, + "z_cvar95_mm": float(z_error_mm[z_error_mm >= p95].mean()), + } + + +def fit_regressor(features: np.ndarray, target: np.ndarray): + return make_pipeline( + StandardScaler(), + HuberRegressor(epsilon=1.35, alpha=1e-4, max_iter=400, tol=1e-5), + ).fit(features, target) + + +def fit_confidence(features: np.ndarray, helpful: np.ndarray): + if np.unique(helpful).size < 2: + raise ValueError("alignment helpfulness target has only one class") + return make_pipeline( + StandardScaler(), + LogisticRegression(max_iter=1000, class_weight="balanced", C=1.0), + ).fit(features, helpful) + + +def select_confidence_threshold( + samples: dict[str, np.ndarray], + calibrated_correction_m: np.ndarray, + confidence: np.ndarray, +) -> tuple[float, list[dict[str, float | bool]]]: + coarse = correction_metrics(samples, np.zeros(len(confidence))) + guardrail_mm = min(0.2, 0.01 * coarse["absolute_mpjpe_mm"]) + available = samples["alignment_applied"].astype(bool) + rows = [] + for threshold in THRESHOLD_GRID: + applied = available & (confidence >= threshold) + correction = np.where(applied, calibrated_correction_m, 0.0) + metrics = correction_metrics(samples, correction) + rows.append({ + "threshold": threshold, + "available_fraction": float(available.mean()), + "applied_fraction": float(applied.mean()), + **metrics, + "absolute_guardrail_passed": bool( + metrics["absolute_mpjpe_mm"] <= coarse["absolute_mpjpe_mm"] + guardrail_mm + ), + }) + eligible = [row for row in rows if row["absolute_guardrail_passed"]] + if not eligible: + return 1.01, rows + eligible.sort(key=lambda row: ( + float(row["absolute_mpjpe_mm"]), + float(row["z_p95_mm"]), + float(row["applied_fraction"]), + )) + return float(eligible[0]["threshold"]), rows + + +def write_predictions( + path: Path, + samples: dict[str, np.ndarray], + calibrated: np.ndarray, + confidence: np.ndarray, + threshold: float, +) -> None: + with path.open("x", newline="", encoding="utf-8") as handle: + fields = ( + "sample_index", "coarse_seed", "checkpoint_sha256", "subject", "take", "frame_id", "side", + "target_residual_z_mm", "raw_alignment_delta_z_mm", + "calibrated_delta_z_mm", "confidence", "alignment_available", "applied", + ) + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for index in range(len(calibrated)): + writer.writerow({ + "sample_index": index, + "coarse_seed": int(samples.get("coarse_seed", np.full(len(calibrated), -1))[index]), + "checkpoint_sha256": str(samples.get("checkpoint", np.full(len(calibrated), ""))[index]), + "subject": samples["subject"][index], + "take": samples["take"][index], + "frame_id": int(samples["frame_id"][index]), + "side": "right" if int(samples["side"][index]) else "left", + "target_residual_z_mm": 1000.0 * samples["target_residual_z_m"][index], + "raw_alignment_delta_z_mm": 1000.0 * samples["raw_delta_z_m"][index], + "calibrated_delta_z_mm": 1000.0 * calibrated[index], + "confidence": confidence[index], + "alignment_available": bool(samples["alignment_applied"][index]), + "applied": bool( + samples["alignment_applied"][index] + and confidence[index] >= threshold + ), + }) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--expected-banks-per-fold", type=int, default=1) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("calibrator output directory must be new or empty") + samples = load_bank(args.bank_dir, args.expected_banks_per_fold) + features = samples["features"] + target = samples["target_residual_z_m"].astype(np.float64) + raw_delta = samples["raw_delta_z_m"].astype(np.float64) + available = samples["alignment_applied"].astype(bool) + subjects = samples["subject"] + cv_correction = np.zeros_like(target) + cv_confidence = np.zeros_like(target) + fold_records = [] + for heldout_subject in sorted(set(subjects.tolist())): + heldout = subjects == heldout_subject + train = ~heldout + regressor = fit_regressor(features[train], target[train]) + helpful = available[train] & ( + np.abs(target[train] - raw_delta[train]) < np.abs(target[train]) + ) + confidence_model = fit_confidence(features[train], helpful) + cv_correction[heldout] = np.clip(regressor.predict(features[heldout]), -0.12, 0.12) + cv_confidence[heldout] = confidence_model.predict_proba(features[heldout])[:, 1] + fold_records.append({ + "heldout_subject": heldout_subject, + "train_samples": int(train.sum()), + "heldout_samples": int(heldout.sum()), + "raw_helpful_fraction_train": float(helpful.mean()), + }) + threshold, threshold_rows = select_confidence_threshold( + samples, cv_correction, cv_confidence, + ) + raw_available = np.where(available, raw_delta, 0.0) + calibrated_available = np.where(available, cv_correction, 0.0) + selected_correction = np.where( + available & (cv_confidence >= threshold), cv_correction, 0.0, + ) + metrics = { + "coarse": correction_metrics(samples, np.zeros_like(target)), + "robust_alignment_unscaled": correction_metrics(samples, raw_available), + "calibrated_always": correction_metrics(samples, calibrated_available), + "calibrated_confidence": correction_metrics(samples, selected_correction), + } + corrections = { + "coarse": np.zeros_like(target), + "robust_alignment_unscaled": raw_available, + "calibrated_always": calibrated_available, + "calibrated_confidence": selected_correction, + } + metrics_by_seed = {} + for seed in sorted(set(samples["coarse_seed"].tolist())): + if int(seed) < 0: + continue + mask = samples["coarse_seed"] == seed + subset = { + key: value[mask] + for key, value in samples.items() + if key in ("target_residual_z_m", "pred_joints_m", "target_joints_m") + } + metrics_by_seed[str(int(seed))] = { + condition: correction_metrics(subset, correction[mask]) + for condition, correction in corrections.items() + } + + final_regressor = fit_regressor(features, target) + final_helpful = available & (np.abs(target - raw_delta) < np.abs(target)) + final_confidence = fit_confidence(features, final_helpful) + args.output_dir.mkdir(parents=True, exist_ok=True) + model_path = args.output_dir / "alignment_calibrator.joblib" + joblib.dump({ + "version": "phase5_oof_alignment_calibrator_v1", + "feature_names": FEATURE_NAMES, + "regressor": final_regressor, + "confidence": final_confidence, + "confidence_threshold": threshold, + "correction_bound_m": 0.12, + }, model_path) + predictions_path = args.output_dir / "oof_calibration_predictions.csv" + write_predictions( + predictions_path, samples, cv_correction, cv_confidence, threshold, + ) + report = { + "status": "fitted", + "experiment_class": "preregistered_oof_calibration", + "result_role": "train_oof_cross_validated_threshold_selection", + "official_validation_used": False, + "official_test_used": False, + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "expected_banks_per_fold": args.expected_banks_per_fold, + "coarse_seeds": sorted({int(seed) for seed in samples["coarse_seed"] if int(seed) >= 0}), + "samples": len(target), + "subjects": sorted(set(subjects.tolist())), + "features": list(FEATURE_NAMES), + "leave_one_subject_out": fold_records, + "confidence_target": "available raw robust delta reduces absolute wrist-z error", + "threshold_grid": list(THRESHOLD_GRID), + "selected_threshold": threshold, + "threshold_selection_rule": "minimize OOF absolute MPJPE among <=min(0.2mm,1%) guardrail candidates; tie-break z P95 then lower apply fraction", + "threshold_rows": threshold_rows, + "metrics": metrics, + "metrics_by_seed": metrics_by_seed, + "model": {"path": str(model_path.resolve()), "sha256": sha256(model_path)}, + "predictions": {"path": str(predictions_path.resolve()), "sha256": sha256(predictions_path)}, + } + (args.output_dir / "calibration.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "samples": report["samples"], + "selected_threshold": threshold, "metrics": metrics, + "official_validation_used": False, "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase5_causal_state.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bf8459c36303256261ef7ad38e7a1f322f501a9f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase5_causal_state.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Select causal translation-z state parameters using train OOF sequences only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.causal_state import ( + causal_constant_velocity_kalman, + measurement_uncertainty_multiplier, +) + + +PROCESS_SIGMAS = (0.002, 0.005, 0.01, 0.02, 0.05) +MEASUREMENT_SIGMAS = (0.0025, 0.005, 0.01, 0.02) +UNCERTAINTY_STRENGTHS = (0.5, 1.0, 2.0) +GUARDRAIL_MM = 0.2 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_calibration_predictions(path: Path) -> dict[tuple[str, int, str], dict[str, float | bool]]: + output = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + key = (row["take"], int(row["frame_id"]), row["side"]) + if key in output: + raise ValueError(f"duplicate OOF calibration prediction: {key}") + output[key] = { + "calibrated_delta_z_m": float(row["calibrated_delta_z_mm"]) / 1000.0, + "confidence": float(row["confidence"]), + "available": row["alignment_available"] == "True", + } + return output + + +def load_sequences( + bank_dirs: list[Path], prediction_csv: Path, +) -> tuple[list[dict[str, np.ndarray]], list[dict[str, Any]]]: + predictions = read_calibration_predictions(prediction_csv) + sequences = [] + manifests = [] + consumed: set[tuple[str, int, str]] = set() + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("bank_version") != 2 + or manifest.get("scope") != "full_fold" + or manifest.get("official_test_used") is not False + ): + raise ValueError(f"invalid OOF bank: {bank_dir}") + manifests.append(manifest) + for record in manifest["takes"]: + with np.load(record["path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + time = len(arrays["frame_id"]) + calibrated = np.zeros((time, 2), dtype=np.float32) + confidence = np.zeros((time, 2), dtype=np.float32) + available = np.zeros((time, 2), dtype=bool) + prediction_present = np.zeros((time, 2), dtype=bool) + for index, frame_id in enumerate(arrays["frame_id"]): + for hand, side in enumerate(("left", "right")): + key = (str(arrays["take"]), int(frame_id), side) + if key not in predictions: + continue + row = predictions[key] + calibrated[index, hand] = float(row["calibrated_delta_z_m"]) + confidence[index, hand] = float(row["confidence"]) + available[index, hand] = bool(row["available"]) + prediction_present[index, hand] = True + consumed.add(key) + expected = arrays["mano_annotation_valid"].astype(bool) & arrays[ + "frame_valid" + ][:, None].astype(bool) + if np.any(expected & ~prediction_present): + raise ValueError(f"missing OOF calibration rows for {arrays['take']}") + uncertainty_base = measurement_uncertainty_multiplier( + confidence, + arrays["alignment_inlier_ratio"], + arrays["alignment_residual_scale_m"], + arrays["alignment_valid_fraction"], + arrays["alignment_conditioning_quality"], + 1.0, + ) + uncertainty_base = np.where(available, uncertainty_base, 5.0) + sequences.append({ + "take": np.asarray(arrays["take"]), + "clip_index": arrays["clip_index"], + "frame_id": arrays["frame_id"], + "frame_valid": arrays["frame_valid"].astype(bool), + "hand_valid": expected, + "coarse_z_m": arrays["pred_wrist_translation"][..., 2], + "measurement_z_m": arrays["pred_wrist_translation"][..., 2] + np.where( + available, calibrated, 0.0, + ), + "target_z_m": arrays["target_wrist_translation"][..., 2], + "pred_joints_m": arrays["pred_joints_camera"], + "target_joints_m": arrays["target_joints_camera"], + # The deployable coarse model remains a measurement even when + # local Depth/K alignment is unavailable. In that case the + # correction falls back to zero and uncertainty is maximal. + "measurement_available": np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), (time, 2), + ).copy(), + "alignment_available": available, + "uncertainty_multiplier_base": uncertainty_base, + }) + if consumed != set(predictions): + raise ValueError("OOF calibration predictions do not exactly match bank samples") + return sequences, manifests + + +def summarize_filter( + sequences: list[dict[str, np.ndarray]], + *, + process_sigma: float | None, + measurement_sigma: float | None, + uncertainty_strength: float, +) -> dict[str, float]: + absolute = [] + z_error = [] + velocity_error = [] + acceleration_error = [] + predicted_acceleration = [] + predicted_jerk = [] + for arrays in sequences: + measurement = arrays["measurement_z_m"] + if process_sigma is None or measurement_sigma is None: + filtered = measurement + else: + base = arrays["uncertainty_multiplier_base"] + multiplier = 1.0 + uncertainty_strength * (base - 1.0) + filtered, _ = causal_constant_velocity_kalman( + measurement, + frame_id=arrays["frame_id"], + segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], + measurement_available=arrays["measurement_available"], + process_sigma_m_per_frame2=process_sigma, + measurement_sigma_m=measurement_sigma, + uncertainty_multiplier=multiplier, + ) + correction = filtered - arrays["coarse_z_m"] + joints = arrays["pred_joints_m"].astype(np.float64).copy() + joints[..., 2] += correction[..., None] + valid = arrays["hand_valid"] + joint_error = np.linalg.norm(joints - arrays["target_joints_m"], axis=-1).mean(axis=-1) + absolute.extend((joint_error[valid] * 1000.0).tolist()) + z_error.extend((np.abs(filtered - arrays["target_z_m"])[valid] * 1000.0).tolist()) + contiguous = ( + (arrays["frame_id"][1:] == arrays["frame_id"][:-1] + 1) + & (arrays["clip_index"][1:] == arrays["clip_index"][:-1]) + ) + for hand in range(2): + pair_valid = contiguous & valid[1:, hand] & valid[:-1, hand] + pred_velocity = np.diff(filtered[:, hand]) + target_velocity = np.diff(arrays["target_z_m"][:, hand]) + velocity_error.extend((np.abs(pred_velocity - target_velocity)[pair_valid] * 1000.0).tolist()) + if len(filtered) < 3: + continue + triple_valid = pair_valid[1:] & pair_valid[:-1] + pred_acceleration = np.diff(filtered[:, hand], n=2) + target_acceleration = np.diff(arrays["target_z_m"][:, hand], n=2) + acceleration_error.extend((np.abs(pred_acceleration - target_acceleration)[triple_valid] * 1000.0).tolist()) + predicted_acceleration.extend((np.abs(pred_acceleration)[triple_valid] * 1000.0).tolist()) + if len(filtered) >= 4: + quad_valid = triple_valid[1:] & triple_valid[:-1] + jerk = np.diff(filtered[:, hand], n=3) + predicted_jerk.extend((np.abs(jerk)[quad_valid] * 1000.0).tolist()) + absolute_array = np.asarray(absolute) + z_array = np.asarray(z_error) + return { + "absolute_mpjpe_mm": float(absolute_array.mean()), + "z_mae_mm": float(z_array.mean()), + "z_p95_mm": float(np.percentile(z_array, 95)), + "velocity_error_mm_per_frame": float(np.mean(velocity_error)), + "acceleration_error_mm_per_frame2": float(np.mean(acceleration_error)), + "predicted_acceleration_mm_per_frame2": float(np.mean(predicted_acceleration)), + "predicted_jerk_mm_per_frame3": float(np.mean(predicted_jerk)), + } + + +def select_candidate(rows: list[dict[str, Any]], baseline: dict[str, float]) -> dict[str, Any]: + eligible = [ + row for row in rows + if float(row["absolute_mpjpe_mm"]) <= baseline["absolute_mpjpe_mm"] + GUARDRAIL_MM + and float(row["z_mae_mm"]) <= baseline["z_mae_mm"] + GUARDRAIL_MM + and float(row["z_p95_mm"]) <= baseline["z_p95_mm"] + GUARDRAIL_MM + ] + if not eligible: + raise ValueError("no causal-state candidate passes the OOF static guardrails") + return min(eligible, key=lambda row: ( + float(row["predicted_acceleration_mm_per_frame2"]), + float(row["acceleration_error_mm_per_frame2"]), + float(row["velocity_error_mm_per_frame"]), + float(row["absolute_mpjpe_mm"]), + )) + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("causal-state output directory must be new or empty") + sequences, manifests = load_sequences(args.bank_dir, args.calibration_predictions) + baseline = summarize_filter( + sequences, process_sigma=None, measurement_sigma=None, uncertainty_strength=0.0, + ) + rows = [] + for process_sigma in PROCESS_SIGMAS: + for measurement_sigma in MEASUREMENT_SIGMAS: + for family, strengths in ( + ("fixed_kalman", (0.0,)), + ("uncertainty_kalman", UNCERTAINTY_STRENGTHS), + ): + for strength in strengths: + rows.append({ + "family": family, + "process_sigma_m_per_frame2": process_sigma, + "measurement_sigma_m": measurement_sigma, + "uncertainty_strength": strength, + **summarize_filter( + sequences, + process_sigma=process_sigma, + measurement_sigma=measurement_sigma, + uncertainty_strength=strength, + ), + }) + selected = { + family: select_candidate( + [row for row in rows if row["family"] == family], baseline, + ) + for family in ("fixed_kalman", "uncertainty_kalman") + } + args.output_dir.mkdir(parents=True, exist_ok=True) + grid_path = args.output_dir / "causal_state_oof_grid.csv" + write_csv(grid_path, rows) + report = { + "status": "selected", + "experiment_class": "train_oof_causal_state_selection", + "official_validation_used": False, + "official_test_used": False, + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "calibration_predictions": { + "path": str(args.calibration_predictions.resolve()), + "sha256": sha256(args.calibration_predictions), + }, + "sequences": len(sequences), + "baseline_calibrated_per_frame": baseline, + "guardrail_mm": GUARDRAIL_MM, + "selection_rule": "within +0.2 mm OOF Absolute/z-MAE/z-P95 guardrails, minimize predicted acceleration then acceleration error, velocity error, and Absolute MPJPE", + "measurement_contract": "coarse z is always the causal measurement on valid frames; unavailable local alignment applies zero correction with maximum uncertainty", + "selected": selected, + "grid": {"path": str(grid_path.resolve()), "sha256": sha256(grid_path), "rows": len(rows)}, + } + (args.output_dir / "causal_state_selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": report["status"], "selected": selected}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase6_harm_risk.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase6_harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..ebfa2bd15ba7b93b4781f9835dd9f649c8e8904c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/fit_phase6_harm_risk.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python3 +"""Fit the preregistered OOF-only Phase 6 harmful-correction risk model.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import joblib +import numpy as np +from sklearn.ensemble import HistGradientBoostingClassifier, HistGradientBoostingRegressor +from sklearn.metrics import brier_score_loss, roc_auc_score +from sklearn.model_selection import GroupKFold + +from foundation_hand.evaluation.mixed_projection import coarse_wrist_ray_translation + + +FEATURE_NAMES = ( + "calibrated_delta_z_m", "abs_calibrated_delta_z_m", + "raw_delta_z_m", "abs_raw_delta_z_m", "raw_calibrated_disagreement_m", + "existing_confidence", "alignment_available", "raw_alignment_available", + "valid_support_count", "projected_support_count", "inlier_ratio", + "residual_scale_m", "valid_fraction", "foreground_fraction", + "background_fraction", "depth_discontinuity_m", "conditioning_quality", + "silhouette_overlap_fraction", "coarse_hand_scale_px", + "coarse_direct_mano_consistency_px", "coarse_z_m", "coarse_ray_x", + "coarse_ray_y", "coarse_wrist_velocity_norm_m_per_frame", + "predicted_depth_order", "side_right", +) +GAIN_THRESHOLDS_MM = (-0.5, 0.0, 0.25, 0.5, 1.0, 2.0) +HARM_THRESHOLDS = (0.2, 0.3, 0.4, 0.5, 0.6) +SEED = 20260717 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_calibration_predictions( + path: Path, +) -> dict[tuple[int, str, int, int], tuple[float, float, bool]]: + lookup = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + hand = 1 if row["side"] == "right" else 0 + key = (int(row["coarse_seed"]), row["take"], int(row["frame_id"]), hand) + if key in lookup: + raise ValueError(f"duplicate calibration prediction: {key}") + lookup[key] = ( + float(row["calibrated_delta_z_mm"]) / 1000.0, + float(row["confidence"]), row["alignment_available"] == "True", + ) + if len(lookup) != 333_936: + raise ValueError(f"calibration prediction coverage changed: {len(lookup)}") + return lookup + + +def harm_cvar95( + coarse_absolute_mm: np.ndarray, + corrected_absolute_mm: np.ndarray, + applied: np.ndarray, +) -> float: + harm = np.where( + applied, np.maximum(corrected_absolute_mm - coarse_absolute_mm, 0.0), 0.0, + ) + threshold = np.percentile(harm, 95) + return float(harm[harm >= threshold].mean()) + + +def evaluate_policy( + *, + coarse_absolute_mm: np.ndarray, + corrected_absolute_mm: np.ndarray, + applied: np.ndarray, + seed_take_groups: np.ndarray, +) -> dict[str, float]: + final = np.where(applied, corrected_absolute_mm, coarse_absolute_mm) + by_group: dict[str, list[float]] = defaultdict(list) + coarse_by_group: dict[str, list[float]] = defaultdict(list) + for group, value, coarse in zip( + seed_take_groups, final, coarse_absolute_mm, strict=True, + ): + by_group[str(group)].append(float(value)) + coarse_by_group[str(group)].append(float(coarse)) + group_values = {key: float(np.mean(values)) for key, values in by_group.items()} + take_deltas = np.asarray([ + group_values[key] - float(np.mean(coarse_by_group[key])) for key in group_values + ]) + return { + "coverage": float(applied.mean()), + "absolute_frame_mean_mm": float(final.mean()), + "absolute_take_mean_mm": float(np.mean(list(group_values.values()))), + "harm_fraction_gt_0p5mm": float( + (applied & ((corrected_absolute_mm - coarse_absolute_mm) > 0.5)).mean() + ), + "harm_cvar95_mm": harm_cvar95( + coarse_absolute_mm, corrected_absolute_mm, applied, + ), + "worst_seed_take_harm_mm": float(take_deltas.max()), + } + + +def models() -> tuple[HistGradientBoostingRegressor, HistGradientBoostingClassifier]: + common = dict( + max_iter=150, learning_rate=0.05, max_depth=3, + min_samples_leaf=40, l2_regularization=1.0, + early_stopping=False, random_state=SEED, + ) + return HistGradientBoostingRegressor(**common), HistGradientBoostingClassifier(**common) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--calibration-json", type=Path, required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + calibration_report = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration_report.get("status") != "fitted" + or calibration_report.get("official_validation_used") is not False + or calibration_report.get("official_test_used") is not False + or calibration_report.get("samples") != 333_936 + or calibration_report.get("predictions", {}).get("sha256") + != sha256(args.calibration_predictions) + ): + raise ValueError("expanded OOF calibration contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + calibration = load_calibration_predictions(args.calibration_predictions) + + feature_chunks = [] + gain_chunks = [] + coarse_chunks = [] + corrected_chunks = [] + available_chunks = [] + physical_groups = [] + seed_take_groups = [] + sample_rows = [] + bank_records = [] + for bank_index, registered in enumerate(calibration_report["bank_manifests"], start=1): + manifest_path = Path(registered["path"]) + if sha256(manifest_path) != registered["sha256"]: + raise ValueError(f"bank manifest hash mismatch: {manifest_path}") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("official_test_used") is not False + or manifest.get("leakage_audit", {}).get("passed") is not True + ): + raise ValueError(f"bank isolation contract failed: {manifest_path}") + seed = int(manifest["seed"]) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + needed = ( + "frame_id", "frame_valid", "pred_wrist_translation", + "pred_joints_camera", "target_joints_camera", + "mano_annotation_valid", "alignment_delta_z_m", "alignment_applied", + "alignment_valid_support_count", "alignment_projected_support_count", + "alignment_inlier_ratio", "alignment_residual_scale_m", + "alignment_valid_fraction", "alignment_foreground_fraction", + "alignment_background_fraction", "alignment_depth_discontinuity_m", + "alignment_conditioning_quality", "silhouette_overlap_fraction", + "coarse_hand_scale_px", "coarse_direct_mano_consistency_px", + "coarse_wrist_velocity_m_per_frame", "predicted_depth_order", + ) + arrays = {key: archive[key] for key in needed} + take = str(archive["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + time_index, hand = np.where(valid) + count = len(time_index) + calibrated = np.zeros(count, dtype=np.float64) + confidence = np.zeros(count, dtype=np.float64) + available = np.zeros(count, dtype=bool) + for index, (time_value, hand_value) in enumerate( + zip(time_index, hand, strict=True), + ): + key = (seed, take, int(arrays["frame_id"][time_value]), int(hand_value)) + calibrated[index], confidence[index], available[index] = calibration[key] + raw = arrays["alignment_delta_z_m"][time_index, hand].astype(np.float64) + raw_available = arrays["alignment_applied"][time_index, hand].astype(bool) + calibrated = np.where(available, calibrated, 0.0) + raw = np.where(raw_available, raw, 0.0) + coarse_translation = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + coarse_joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + corrected_translation = coarse_wrist_ray_translation( + coarse_translation, coarse_translation[:, 2] + calibrated, + ) + corrected_joints = coarse_joints + ( + corrected_translation - coarse_translation + )[:, None] + coarse_absolute = np.linalg.norm(coarse_joints - target_joints, axis=-1).mean(axis=1) * 1000.0 + corrected_absolute = np.linalg.norm( + corrected_joints - target_joints, axis=-1, + ).mean(axis=1) * 1000.0 + gain = coarse_absolute - corrected_absolute + z = np.maximum(coarse_translation[:, 2], 1e-6) + overlap = arrays["silhouette_overlap_fraction"][time_index] + depth_order = arrays["predicted_depth_order"][time_index] + velocity = arrays["coarse_wrist_velocity_m_per_frame"][time_index, hand] + features = np.column_stack(( + calibrated, np.abs(calibrated), raw, np.abs(raw), np.abs(raw - calibrated), + confidence, available, raw_available, + arrays["alignment_valid_support_count"][time_index, hand], + arrays["alignment_projected_support_count"][time_index, hand], + arrays["alignment_inlier_ratio"][time_index, hand], + arrays["alignment_residual_scale_m"][time_index, hand], + arrays["alignment_valid_fraction"][time_index, hand], + arrays["alignment_foreground_fraction"][time_index, hand], + arrays["alignment_background_fraction"][time_index, hand], + arrays["alignment_depth_discontinuity_m"][time_index, hand], + arrays["alignment_conditioning_quality"][time_index, hand], overlap, + arrays["coarse_hand_scale_px"][time_index, hand], + arrays["coarse_direct_mano_consistency_px"][time_index, hand], + coarse_translation[:, 2], coarse_translation[:, 0] / z, + coarse_translation[:, 1] / z, np.linalg.norm(velocity, axis=1), + depth_order, hand.astype(np.float64), + )).astype(np.float32) + features = np.nan_to_num(features, nan=0.0, posinf=1e6, neginf=-1e6) + feature_chunks.append(features) + gain_chunks.append(gain.astype(np.float32)) + coarse_chunks.append(coarse_absolute.astype(np.float32)) + corrected_chunks.append(corrected_absolute.astype(np.float32)) + available_chunks.append(available) + physical_groups.extend([take] * count) + seed_take_groups.extend([f"{seed}:{take}"] * count) + sample_rows.extend({ + "coarse_seed": seed, "take": take, + "frame_id": int(arrays["frame_id"][time_value]), + "side": "right" if hand_value else "left", + } for time_value, hand_value in zip(time_index, hand, strict=True)) + bank_records.append({ + "path": str(manifest_path), "sha256": registered["sha256"], + "seed": seed, "fold": int(manifest["fold"]), + }) + print(f"[{bank_index}/9] fold{manifest['fold']} seed{seed} loaded", flush=True) + + X = np.concatenate(feature_chunks) + gain = np.concatenate(gain_chunks) + coarse_absolute = np.concatenate(coarse_chunks) + corrected_absolute = np.concatenate(corrected_chunks) + available = np.concatenate(available_chunks) + groups = np.asarray(physical_groups) + seed_take = np.asarray(seed_take_groups) + if X.shape != (333_936, len(FEATURE_NAMES)) or len(set(zip( + (row["coarse_seed"] for row in sample_rows), + (row["take"] for row in sample_rows), + (row["frame_id"] for row in sample_rows), + (row["side"] for row in sample_rows), + ))) != len(sample_rows): + raise ValueError("OOF feature coverage or uniqueness changed") + + harmful = gain < -0.5 + harm_magnitude = np.maximum(-gain, 0.0) + regression_weight = 1.0 + 4.0 * np.minimum(harm_magnitude / 10.0, 5.0) + classifier_weight = 1.0 + 8.0 * np.minimum(harm_magnitude / 10.0, 5.0) + predicted_gain = np.zeros_like(gain) + predicted_harm = np.zeros_like(gain) + fold_id = np.full(len(gain), -1, dtype=np.int8) + splitter = GroupKFold(n_splits=5) + for fold, (train, heldout) in enumerate(splitter.split(X, gain, groups), start=0): + regressor, classifier = models() + regressor.fit(X[train], gain[train], sample_weight=regression_weight[train]) + classifier.fit(X[train], harmful[train], sample_weight=classifier_weight[train]) + predicted_gain[heldout] = regressor.predict(X[heldout]) + predicted_harm[heldout] = classifier.predict_proba(X[heldout])[:, 1] + fold_id[heldout] = fold + print(f"cross-fit {fold + 1}/5: {len(heldout)} held-out samples", flush=True) + if np.any(fold_id < 0): + raise AssertionError("cross-fitting omitted samples") + + coarse_policy = evaluate_policy( + coarse_absolute_mm=coarse_absolute, corrected_absolute_mm=corrected_absolute, + applied=np.zeros_like(available), seed_take_groups=seed_take, + ) + always_policy = evaluate_policy( + coarse_absolute_mm=coarse_absolute, corrected_absolute_mm=corrected_absolute, + applied=available, seed_take_groups=seed_take, + ) + grid_rows = [] + for gain_threshold in GAIN_THRESHOLDS_MM: + for harm_threshold in HARM_THRESHOLDS: + applied = available & (predicted_gain >= gain_threshold) & ( + predicted_harm <= harm_threshold + ) + row = { + "expected_gain_threshold_mm": gain_threshold, + "harm_probability_threshold": harm_threshold, + **evaluate_policy( + coarse_absolute_mm=coarse_absolute, + corrected_absolute_mm=corrected_absolute, + applied=applied, seed_take_groups=seed_take, + ), + } + row["absolute_delta_vs_always_mm"] = ( + row["absolute_take_mean_mm"] - always_policy["absolute_take_mean_mm"] + ) + row["harm_cvar_reduction_fraction"] = 1.0 - ( + row["harm_cvar95_mm"] / max(always_policy["harm_cvar95_mm"], 1e-12) + ) + row["admission_passed"] = bool( + row["absolute_delta_vs_always_mm"] <= 0.1 + and row["coverage"] >= 0.2 + and row["harm_cvar_reduction_fraction"] >= 0.2 + ) + grid_rows.append(row) + eligible = [row for row in grid_rows if row["admission_passed"]] + eligible.sort(key=lambda row: ( + row["absolute_take_mean_mm"], row["harm_cvar95_mm"], + row["worst_seed_take_harm_mm"], row["coverage"], + )) + selected = eligible[0] if eligible else None + + final_regressor, final_classifier = models() + final_regressor.fit(X, gain, sample_weight=regression_weight) + final_classifier.fit(X, harmful, sample_weight=classifier_weight) + package_path = args.output_dir / "harm_risk_package.joblib" + joblib.dump({ + "version": "phase6_harm_risk_v1", + "feature_names": FEATURE_NAMES, + "regressor": final_regressor, + "classifier": final_classifier, + "selected_thresholds": None if selected is None else { + "expected_gain_threshold_mm": selected["expected_gain_threshold_mm"], + "harm_probability_threshold": selected["harm_probability_threshold"], + }, + "harm_definition_mm": 0.5, + "seed": SEED, + }, package_path) + + prediction_rows = [] + for index, identity in enumerate(sample_rows): + prediction_rows.append({ + "sample_index": index, **identity, "cv_fold": int(fold_id[index]), + "coarse_absolute_mpjpe_mm": float(coarse_absolute[index]), + "corrected_absolute_mpjpe_mm": float(corrected_absolute[index]), + "realized_gain_mm": float(gain[index]), + "predicted_gain_mm": float(predicted_gain[index]), + "harmful_gt_0p5mm": bool(harmful[index]), + "predicted_harm_probability": float(predicted_harm[index]), + "alignment_available": bool(available[index]), + }) + write_csv(args.output_dir / "cross_fitted_predictions.csv", prediction_rows) + write_csv(args.output_dir / "threshold_grid.csv", grid_rows) + report = { + "status": "admitted_for_one_frozen_validation" if selected is not None else "rejected_oof_gate", + "experiment": "P6_S3_harm_aware_risk_gate", + "experiment_class": "exploratory_oof_only_cross_fitted_risk_model", + "official_validation_used": False, + "official_test_used": False, + "oracle_information_at_inference": False, + "samples": len(X), "physical_takes": len(set(groups)), + "seed_take_groups": len(set(seed_take)), "features": list(FEATURE_NAMES), + "cross_validation": "5-fold GroupKFold by physical take across coarse seeds", + "cross_fitted_gain_mae_mm": float(np.mean(np.abs(predicted_gain - gain))), + "cross_fitted_harm_brier": float(brier_score_loss(harmful, predicted_harm)), + "cross_fitted_harm_roc_auc": float(roc_auc_score(harmful, predicted_harm)), + "coarse_policy": coarse_policy, "always_policy": always_policy, + "selected": selected, "eligible_conditions": len(eligible), + "package": {"path": str(package_path), "sha256": sha256(package_path)}, + "calibration": { + "json": str(args.calibration_json.resolve()), + "json_sha256": sha256(args.calibration_json), + "predictions": str(args.calibration_predictions.resolve()), + "predictions_sha256": sha256(args.calibration_predictions), + }, + "banks": bank_records, + "outputs": { + "threshold_grid": "threshold_grid.csv", + "cross_fitted_predictions": "cross_fitted_predictions.csv", + }, + } + (args.output_dir / "risk_selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "selected": selected, + "gain_mae_mm": report["cross_fitted_gain_mae_mm"], + "harm_auc": report["cross_fitted_harm_roc_auc"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/freeze_phase7_h2o_adaptation_validation.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/freeze_phase7_h2o_adaptation_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..2298467e46db7bcb7e74db4bb2211252cb82a353 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/freeze_phase7_h2o_adaptation_validation.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Freeze a train-heldout-selected adaptation candidate before H2O validation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_external import sha256 +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES + + +def build_freeze_record(selection_path: Path, validation_manifest: Path) -> dict[str, Any]: + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if ( + selection.get("status") != "selected_h2o_adaptation_train_group_heldout" + or selection.get("selection_split") != "h2o_train_group_heldout_only" + or selection.get("h2o_official_validation_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("adaptation selection is not eligible for validation freeze") + winner = selection.get("winner") + candidates = [item for item in selection.get("candidates", []) if item["candidate"] == winner] + if len(candidates) != 1: + raise ValueError("adaptation winner is missing or duplicated") + candidate = candidates[0] + checkpoint, config = Path(candidate["checkpoint"]), Path(candidate["config"]) + if sha256(checkpoint) != candidate["checkpoint_sha256"]: + raise ValueError("adaptation checkpoint SHA256 mismatch") + if sha256(config) != candidate["config_sha256"]: + raise ValueError("adaptation config SHA256 mismatch") + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only canonical H2O official validation may be frozen") + return { + "status": "h2o_adaptation_candidate_frozen", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "winner": winner, + "checkpoint": { + "path": str(checkpoint.resolve()), + "sha256": candidate["checkpoint_sha256"], + "step": candidate["checkpoint_step"], + }, + "config": { + "path": str(config.resolve()), + "sha256": candidate["config_sha256"], + }, + "adaptation_selection_path": str(selection_path.resolve()), + "adaptation_selection_sha256": sha256(selection_path), + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used_for_selection": False, + "h2o_validation_manifest": { + "path": str(validation_manifest.resolve()), + "sha256": sha256(validation_manifest), + }, + "frozen_h2o_input_modes": list(INPUT_MODES), + "h2o_training_data_used": True, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection", type=Path, required=True) + parser.add_argument("--validation-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = build_freeze_record(args.selection, args.validation_manifest) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/freeze_phase7_h2o_zero_shot.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/freeze_phase7_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..002866bbe6508fa9e5db8985698182f6eaab4657 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/freeze_phase7_h2o_zero_shot.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Freeze H2O zero-shot exposure only after external selection is immutable.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path + +from scripts.build_phase7_scale_eval_queue import sha256 + + +def build_freeze_record(selection_path: Path, manifest: Path) -> dict: + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if ( + selection.get("status") != "selected_external_generalist_no_h2o" + or selection.get("h2o_training_data_used") is not False + or selection.get("h2o_official_validation_used_for_external_selection") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("external generalist selection is not freeze-eligible") + checkpoint = Path(selection["checkpoint"]["path"]) + config = Path(selection["config"]["path"]) + if sha256(checkpoint) != selection["checkpoint"]["sha256"]: + raise ValueError("selected checkpoint hash mismatch") + if sha256(config) != selection["config"]["sha256"]: + raise ValueError("selected config hash mismatch") + if manifest.name != "official_val.jsonl": + raise ValueError("only canonical H2O official_val.jsonl can be frozen") + return { + "status": "external_generalist_frozen", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "checkpoint_path": str(checkpoint.resolve()), + "checkpoint_sha256": selection["checkpoint"]["sha256"], + "checkpoint_step": selection["checkpoint"]["step"], + "config_path": str(config.resolve()), "config_sha256": selection["config"]["sha256"], + "external_selection_path": str(selection_path.resolve()), + "external_selection_sha256": sha256(selection_path), + "frozen_h2o_input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "h2o_validation_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-selection", type=Path, required=True) + parser.add_argument("--h2o-validation-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + record = build_freeze_record(args.external_selection, args.h2o_validation_manifest) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/freeze_phase9_final_deployment.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/freeze_phase9_final_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..fab8e06ab8f566b0f721a6d89481379322349a41 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/freeze_phase9_final_deployment.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python3 +"""Freeze the unique final Phase 9 checkpoint for post-selection deployment audits.""" + +from __future__ import annotations + +import argparse +import hashlib +import fcntl +import json +from pathlib import Path +from typing import Any + +import torch +import yaml + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def complete_controller( + plan_path: Path, state_path: Path, *, decision_path: Path | None = None, +) -> tuple[dict[str, Any], Path]: + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not report_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or (decision_path is not None and report_path.resolve() != decision_path.resolve()) + ): + raise ValueError(f"controller decision is incomplete or unbound: {state_path}") + report = read_json(report_path) + if report.get("status") != "complete" or report.get("official_test_used") is not False: + raise ValueError(f"controller decision is not isolated: {report_path}") + return report, report_path + + +def normalized_job(job: dict[str, Any], source: str) -> dict[str, Any]: + checkpoint = Path(job.get("checkpoint", job.get("path", ""))) + checkpoint_sha = job.get("checkpoint_sha256", job.get("sha256")) + config = Path(job.get("config", "")) + config_sha = job.get("config_sha256") + if ( + not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha + or not config.is_file() or sha256(config) != config_sha + ): + raise ValueError(f"selected full job differs: {source}") + return { + "source": source, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha, + "config": str(config.resolve()), + "config_sha256": config_sha, + } + + +def preceding_full_job( + stage8: dict[str, Any], selection: dict[str, Any], +) -> tuple[dict[str, Any], str, bool, list[int]]: + resolution_hw = list(stage8["resolution_hw"]) + if stage8.get("shared_augmentation_accepted") is True: + job = normalized_job( + stage8["candidate_training_jobs"]["full"], + "stage8_shared_augmentation_full", + ) + return job, "shared_augmentation", True, resolution_hw + control = stage8["control"] + if control.get("kind") == "resolution_896x512_candidate": + path = Path(control["evaluation_plan"]["path"]) + if not path.is_file() or sha256(path) != control["evaluation_plan"]["sha256"]: + raise ValueError("selected resolution evaluation plan differs") + plan = read_json(path) + job = normalized_job(plan["training_jobs"]["full"], "stage7_resolution_full") + return job, "resolution", False, resolution_hw + if control.get("kind") == "frozen_640_winner": + record = control["selection_report"] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError("selected 640 selection report differs") + selected = read_json(path) + if selected.get("winner") != selection.get("winner"): + raise ValueError("selected 640 winner differs") + job = normalized_job({ + "checkpoint": selected["winner_checkpoint"]["path"], + "checkpoint_sha256": selected["winner_checkpoint"]["sha256"], + "config": selected["winner_config"]["path"], + "config_sha256": selected["winner_config"]["sha256"], + }, "phase9_frozen_640_winner") + return job, "frozen_640_winner", False, resolution_hw + raise ValueError("Stage 8 selected control kind differs") + + +def checkpoint_contract(job: dict[str, Any], resolution_hw: list[int]) -> int: + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + if ( + config.get("experiment", {}).get("branch") != "phase9_unified" + or config.get("experiment", {}).get("official_test_used") is not False + or list(config.get("data", {}).get("resolution_hw", [])) != resolution_hw + ): + raise ValueError("final deployment config contract differs") + state = torch.load(job["checkpoint"], map_location="cpu", weights_only=False) + extra = state.get("extra", {}) + if ( + extra.get("config") != config + or extra.get("h2o_training_data_used") is not True + or extra.get("official_test_used") is not False + or not isinstance(state.get("model"), dict) + ): + raise ValueError("final deployment checkpoint provenance differs") + return int(state["step"]) + + +def build_freeze( + *, selection_plan_path: Path, selection_state_path: Path, + stage8_plan_path: Path, stage8_state_path: Path, + last2_plan_path: Path, last2_state_path: Path, + validation_manifest: Path, validation_manifest_sha256: str, + training_manifest: Path, training_manifest_sha256: str, +) -> dict[str, Any]: + selection_plan = read_json(selection_plan_path) + selection_state = read_json(selection_state_path) + selection_path = Path(selection_plan["output_json"]) + if ( + selection_state.get("status") != "complete" + or selection_state.get("plan_sha256") != sha256(selection_plan_path) + or selection_state.get("official_test_used") is not False + or selection_state.get("h2o_official_validation_used") is not False + or not selection_path.is_file() + ): + raise ValueError("unified selection is incomplete or unbound") + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("winner") != selection_state.get("winner") + or selection.get("winner_checkpoint") != selection_state.get("winner_checkpoint") + or selection.get("winner_config") != selection_state.get("winner_config") + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("unified selection report differs") + required_plan = {item["id"]: item for item in selection_plan["required_states"]} + required_state = { + item["id"]: item for item in selection_state.get("required_states", []) + } + if len(required_plan) != 9 or set(required_state) != set(required_plan): + raise ValueError("unified selection required-state chain differs") + for identifier, item in required_state.items(): + path = Path(item["path"]) + expected_path = Path(required_plan[identifier]["path"]) + if ( + path.resolve() != expected_path.resolve() + or not path.is_file() or sha256(path) != item["sha256"] + ): + raise ValueError(f"unified selection required state differs: {identifier}") + payload = read_json(path) + if payload.get("status") != "complete" or payload.get("official_test_used") is not False: + raise ValueError(f"unified selection required state is incomplete: {identifier}") + + stage8_plan = read_json(stage8_plan_path) + stage8, stage8_path = complete_controller( + stage8_plan_path, stage8_state_path, + decision_path=Path(stage8_plan["decision_report"]), + ) + last2_plan = read_json(last2_plan_path) + last2, last2_path = complete_controller( + last2_plan_path, last2_state_path, + decision_path=Path(last2_plan["report"]), + ) + if stage8.get("winner") != selection.get("winner"): + raise ValueError("Stage 8 winner differs from unified selection") + + preceding, mechanism, shared_augmentation, resolution_hw = preceding_full_job( + stage8, selection, + ) + selected = str(last2["selected"]) + if selected in {"last2_5e7", "last2_1e6"}: + candidate = "5e7" if selected == "last2_5e7" else "1e6" + report_record = last2["selected_candidate_report"] + candidate_path = Path(report_record["path"]) + if not candidate_path.is_file() or sha256(candidate_path) != report_record["sha256"]: + raise ValueError("selected last-2 candidate report differs") + candidate_report = read_json(candidate_path) + if ( + candidate_report.get("candidate") != candidate + or candidate_report.get("gate", {}).get("accepted") is not True + ): + raise ValueError("selected last-2 gate differs") + job = normalized_job( + candidate_report["candidate_training_jobs"]["full"], selected, + ) + mechanism = selected + shared_augmentation = bool(candidate_report["shared_augmentation"]) + resolution_hw = list(candidate_report["resolution_hw"]) + elif selected == "preceding_mechanism": + job = preceding + else: + raise ValueError("last-2 final selection differs") + + step = checkpoint_contract(job, resolution_hw) + for path, expected, label in ( + (validation_manifest, validation_manifest_sha256, "official validation"), + (training_manifest, training_manifest_sha256, "official train"), + ): + if not path.is_file() or sha256(path) != expected: + raise ValueError(f"{label} manifest differs") + chain = { + "unified_selection_plan": sha256(selection_plan_path), + "unified_selection_state": sha256(selection_state_path), + "unified_selection": sha256(selection_path), + "stage8_controller_plan": sha256(stage8_plan_path), + "stage8_controller_state": sha256(stage8_state_path), + "stage8_decision": sha256(stage8_path), + "last2_finalizer_plan": sha256(last2_plan_path), + "last2_finalizer_state": sha256(last2_state_path), + "last2_final_decision": sha256(last2_path), + } + chain_hash = hashlib.sha256( + json.dumps(chain, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + return { + "schema_version": "phase9_final_deployment_freeze_v1", + "status": "phase9_final_unified_checkpoint_frozen", + "created_utc": last2["created_utc"], + "winner": selection["winner"], + "selected_mechanism": mechanism, + "resolution_hw": resolution_hw, + "shared_augmentation": shared_augmentation, + "checkpoint": { + "path": job["checkpoint"], "sha256": job["checkpoint_sha256"], + "step": step, + }, + "config": {"path": job["config"], "sha256": job["config_sha256"]}, + "selection_chain": chain, + "selection_chain_sha256": chain_hash, + "selection_complete": True, + "stage9_final_decision_complete": True, + "frozen_h2o_input_modes": list(INPUT_MODES), + "h2o_validation_manifest": { + "path": str(validation_manifest.resolve()), + "sha256": validation_manifest_sha256, + }, + "h2o_training_manifest": { + "path": str(training_manifest.resolve()), + "sha256": training_manifest_sha256, + }, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--selection-state", type=Path, required=True) + parser.add_argument("--stage8-plan", type=Path, required=True) + parser.add_argument("--stage8-state", type=Path, required=True) + parser.add_argument("--last2-plan", type=Path, required=True) + parser.add_argument("--last2-state", type=Path, required=True) + parser.add_argument("--validation-manifest", type=Path, required=True) + parser.add_argument("--validation-manifest-sha256", required=True) + parser.add_argument("--training-manifest", type=Path, required=True) + parser.add_argument("--training-manifest-sha256", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = build_freeze( + selection_plan_path=args.selection_plan, + selection_state_path=args.selection_state, + stage8_plan_path=args.stage8_plan, stage8_state_path=args.stage8_state, + last2_plan_path=args.last2_plan, last2_state_path=args.last2_state, + validation_manifest=args.validation_manifest, + validation_manifest_sha256=args.validation_manifest_sha256, + training_manifest=args.training_manifest, + training_manifest_sha256=args.training_manifest_sha256, + ) + if args.output.exists(): + if read_json(args.output) != result: + raise ValueError("existing final deployment freeze differs") + else: + atomic_json(args.output, result) + state = { + "schema_version": "phase9_final_deployment_freeze_state_v1", + "status": "complete", "freeze": str(args.output.resolve()), + "freeze_sha256": sha256(args.output), + "checkpoint_sha256": result["checkpoint"]["sha256"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_freeze_state_v1", + "status": "failed_resumable", + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used": False, + "official_test_used": False, + }) + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c27472cd14392687856490a5d6fd1c44ee7bc4d7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_configs.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Generate the pre-registered Phase 3 decoder/temporal core configs.""" + +from __future__ import annotations + +import argparse +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +LAYOUTS = { + "l0": "sequential", + "l1": "alternating", + "l2": "hybrid_reread", +} +MATRIX_ROWS = ( + ("l0", "t0"), + ("l0", "t1"), + ("l1", "t0"), + ("l1", "t1"), + ("l2", "t1"), +) +MODALITIES = { + "m0": {"use_depth": False, "use_rays": False}, + "m3": {"use_depth": True, "use_rays": True}, +} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + + rows = [] + for modality, modality_values in MODALITIES.items(): + for layout, temporal in MATRIX_ROWS: + for seed in SEEDS: + name = f"core_{modality}_{layout}_{temporal}_s{seed}" + config = { + "name": name, + "seed": seed, + "experiment": { + "phase": 3, + "matrix": "decoder_temporal_core", + "modality": modality.upper(), + "layout": layout.upper(), + "temporal": temporal.upper(), + "registered_axes": ["layout", "temporal_attention", "modality"], + }, + "data": { + "resolution_hw": [288, 512], + "T": 8, + "stride": 1, + "batch_size": 1, + }, + "model": { + "encoder": "dinov3", + "decoder_dim": 512, + "decoder_layers": 3, + "attention_heads": 8, + "decoder_mode": LAYOUTS[layout], + "use_temporal": temporal == "t1", + "use_depth": modality_values["use_depth"], + "depth_mode": "log_depth", + "depth_gate_mode": "fixed", + "depth_gate_fixed_value": 0.5, + "use_rays": modality_values["use_rays"], + "use_bimanual_interaction": True, + "predict_presence": True, + "require_mano": True, + }, + "loss": { + "joint2d": 1.0, + "joint3d_camera": 10.0, + "vertices_camera": 1.0, + "local_pose": 1.0, + "global_orientation": 1.0, + "shape": 0.1, + "translation": 10.0, + "reprojection": 1.0, + "temporal_velocity": 0.1, + "temporal_acceleration": 0.05, + "bimanual_relative_wrist": 1.0, + "presence": 0.0, + }, + "assets": { + "dinov3_source": "third_party/dinov3", + "dinov3_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "mano_root": "/SSD3/jiasen/foundation_hand/pretrained/mano", + }, + "precision": "bf16", + "protocol": { + "max_steps": 100000, + "num_workers": 4, + "checkpoint_interval": 25000, + "validation_interval": 5000, + "validation_batches": 256, + "learning_rate": 5e-5, + "min_learning_rate": 5e-6, + "warmup_steps": 500, + "early_stopping_patience": 0, + "validation_subset_manifest": "artifacts/phase3/validation_subset/validation_subset_256.json", + }, + } + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": modality.upper(), "layout": layout.upper(), + "decoder_mode": LAYOUTS[layout], "temporal": temporal.upper(), + "use_depth": int(modality_values["use_depth"]), + "use_rays": int(modality_values["use_rays"]), + "depth_gate": 0.5 if modality_values["use_depth"] else "not_used", + }) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} configs under {args.output_dir}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_depth_fusion_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_depth_fusion_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..a1436a0b91cc980e884999390c44c9a0fda0795f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_depth_fusion_configs.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Generate the first independent Phase 3 Depth fusion/representation controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = { + "gate025": { + "depth_mode": "log_depth", "depth_gate_mode": "fixed", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.25, + }, + "learned_gate": { + "depth_mode": "log_depth", "depth_gate_mode": "learned", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.5, + }, + "geometry": { + "depth_mode": "geometry", "depth_gate_mode": "fixed", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.5, + }, +} + + +def matrix_row(path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(path), "name": config["name"], "seed": config["seed"], + "modality": "M3", "layout": "L1", "temporal": "T1", + "variant": config["experiment"]["variant"], + "depth_mode": model["depth_mode"], + "depth_gate_mode": model["depth_gate_mode"], + "depth_gate_floor": model["depth_gate_floor"], + "depth_gate_fixed_value": model["depth_gate_fixed_value"], + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_fusion_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_fusion_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, changes in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / f"core_m3_l1_t1_s{seed}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, "matrix": "depth_fusion", "modality": "M3", + "layout": "L1", "temporal": "T1", "variant": variant, + "registered_axes": ["depth_fusion_or_representation"], + "reference": "P0_M3_L1_T1_fixed_gate_0.5", + } + config["model"].update(changes) + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append(matrix_row(path, config, "new_formal_run")) + rows.sort(key=lambda row: (str(row["variant"]), int(row["seed"]))) + write_matrix(args.runs_csv, rows) + write_matrix(args.matrix_csv, rows) + print(f"generated {len(rows)} Depth fusion configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_dropout_dose_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_dropout_dose_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..ff442de59dcd384b1d69070f92c29d57f47b2214 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_dropout_dose_configs.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Generate lower-dose Geometry modality-dropout Phase 3 controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = {"dropout005_geometry": 0.05, "dropout010_geometry": 0.10} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/dropout_dose_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/dropout_dose_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, probability in VARIANTS.items(): + for seed in SEEDS: + base_path = ( + args.base_config_dir + / f"depth_dropout00_geometry_m3_l1_t1_s{seed}.yaml" + ) + config = copy.deepcopy( + yaml.safe_load(base_path.read_text(encoding="utf-8")) + ) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "depth_modality_dropout_dose", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": variant, + "registered_axes": ["modality_dropout_dose"], + "reference": "D2_dropout00_and_dropout02_endpoints", + } + config["model"]["modality_dropout_prob"] = probability + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), + "name": name, + "seed": seed, + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "depth_mode": "geometry", + "variant": variant, + "modality_dropout_prob": probability, + "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(rows[0]), lineterminator="\n" + ) + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} dropout-dose configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_long_tail_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_long_tail_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..45500ef2d771d2f985343c04d4f262ebc1d0645a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_long_tail_configs.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Generate the preregistered E.3 low-learning-rate tail configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/photometric"), + ) + parser.add_argument( + "--checkpoint-root", type=Path, + default=Path("artifacts/phase3/photometric_runs_commit239b0bf"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/long_tail_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + source_name = f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + base_path = args.base_config_dir / f"{source_name}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "low_lr_tail", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": "photometric_on_r640x368_tail150k", + "registered_axes": ["training_duration"], + "reference": source_name, + } + config["protocol"]["max_steps"] = 150_000 + config["protocol"]["lr_schedule_steps"] = 100_000 + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + checkpoint = args.checkpoint_root / source_name / "step_0100000_final.pt" + rows.append({ + "config": str(path.resolve()), "name": name, "seed": seed, + "resume_checkpoint": str(checkpoint.resolve()), + "start_step": 100_000, "max_steps": 150_000, + "lr_schedule_steps": 100_000, "min_learning_rate": 5e-6, + "changed_variable": "training_duration_only", + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} E.3 low-LR-tail configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_modality_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_modality_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c89255f39b11007505204124621076e0d01704eb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_modality_configs.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Generate the new M1/M2 runs for the Phase 3 modality matrix.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +NEW_MODALITIES = { + "M1": {"use_depth": False, "use_rays": True}, + "M2": {"use_depth": True, "use_rays": False}, +} + + +def matrix_row(config_path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(config_path), + "name": config["name"], + "seed": config["seed"], + "modality": config["experiment"]["modality"], + "layout": config["experiment"]["layout"], + "temporal": config["experiment"]["temporal"], + "use_depth": int(model["use_depth"]), + "use_rays": int(model["use_rays"]), + "depth_gate": 0.5 if model["use_depth"] else "not_used", + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/modality")) + parser.add_argument("--new-runs-csv", type=Path, default=Path("artifacts/phase3/reports/modality_new_runs.csv")) + parser.add_argument("--full-matrix-csv", type=Path, default=Path("artifacts/phase3/reports/modality_config_matrix.csv")) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + new_rows = [] + full_rows = [] + for seed in SEEDS: + references = {} + for modality in ("M0", "M3"): + path = args.core_config_dir / f"core_{modality.lower()}_l1_t1_s{seed}.yaml" + config = yaml.safe_load(path.read_text(encoding="utf-8")) + references[modality] = config + full_rows.append(matrix_row(path, config, "reused_core_matrix")) + + for modality, flags in NEW_MODALITIES.items(): + config = copy.deepcopy(references["M3"]) + name = f"modality_{modality.lower()}_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "modality_causal", + "modality": modality, + "layout": "L1", + "temporal": "T1", + "registered_axes": ["modality"], + "decoder_promotion_source": "decoder_temporal_core_best_absolute_full_val", + } + config["model"]["use_depth"] = flags["use_depth"] + config["model"]["use_rays"] = flags["use_rays"] + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + row = matrix_row(path, config, "new_formal_run") + new_rows.append(row) + full_rows.append(row) + + new_rows.sort(key=lambda row: (str(row["modality"]), int(row["seed"]))) + full_rows.sort(key=lambda row: (str(row["modality"]), int(row["seed"]))) + write_matrix(args.new_runs_csv, new_rows) + write_matrix(args.full_matrix_csv, full_rows) + print(f"generated {len(new_rows)} new configs and {len(full_rows)} full-matrix rows") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_modality_dropout_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_modality_dropout_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c2841dce151e58be976b8e49d194d5faab3c2e69 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_modality_dropout_configs.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Generate same-commit geometry controls for M3 modality-dropout training.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +DROP_PROB = 0.2 +VARIANTS = {"dropout00_geometry": 0.0, "dropout02_geometry": DROP_PROB} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_dropout_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_dropout_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, probability in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / f"depth_geometry_m3_l1_t1_s{seed}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, "matrix": "depth_modality_dropout", "modality": "M3", + "layout": "L1", "temporal": "T1", "variant": variant, + "registered_axes": ["modality_dropout"], + "reference": "dropout00_geometry_same_commit", + } + config["model"]["modality_dropout_prob"] = probability + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "depth_mode": "geometry", "variant": variant, + "modality_dropout_prob": probability, "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} same-commit geometry modality-dropout configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_photometric_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_photometric_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..138bc89f81a2c18daf910344d7768488270af82f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_photometric_configs.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Generate same-code Phase 3 photometric augmentation off/on controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = {"off": False, "on": True} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/resolution"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/photometric"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/photometric_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/photometric_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, enabled in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"photometric_{variant}_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "photometric_augmentation", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": f"photometric_{variant}_r640x368", + "registered_axes": ["photometric_augmentation"], + "reference": "E1_promoted_r640x368", + } + config["data"]["photometric_augmentation"] = { + "enabled": enabled, + "probability": 0.8, + "brightness": 0.2, + "contrast": 0.2, + "saturation": 0.2, + "hue": 0.05, + } + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "variant": f"photometric_{variant}", + "photometric_enabled": enabled, + "resolution_h": 368, "resolution_w": 640, + "source": "new_same_commit_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} photometric off/on configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_resolution_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_resolution_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..4bc5c0e1550283a14452e8ffc4a36f9ed606302c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_resolution_configs.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Generate the 640x368 Phase 3 resolution controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VALIDATION_SUBSET = ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" +) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/resolution"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/resolution_640_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/resolution_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + base_path = ( + args.base_config_dir + / f"depth_dropout005_geometry_m3_l1_t1_s{seed}.yaml" + ) + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "resolution", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": "dropout005_geometry_r640x368", + "registered_axes": ["input_resolution"], + "reference": "dropout005_geometry_r512x288_D3", + } + config["data"]["resolution_hw"] = [368, 640] + config["protocol"]["validation_subset_manifest"] = VALIDATION_SUBSET + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "depth_mode": "geometry", "variant": "r640x368", + "resolution_h": 368, "resolution_w": 640, + "modality_dropout_prob": 0.05, "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} 640x368 resolution configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_temporal_position_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_temporal_position_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..12031161423294f686ba8f955d905e9de947f069 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase3_temporal_position_configs.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Generate the P0/P1 relative temporal-position experiment configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) + + +def matrix_row(config_path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(config_path), + "name": config["name"], + "seed": config["seed"], + "modality": config["experiment"]["modality"], + "layout": config["experiment"]["layout"], + "temporal": config["experiment"]["temporal"], + "position": config["experiment"].get("position", "P0"), + "temporal_position_mode": model.get("temporal_position_mode", "none"), + "relative_bias_max_distance": model.get("temporal_relative_bias_max_distance", "not_used"), + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/temporal_position")) + parser.add_argument( + "--new-runs-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_new_runs.csv"), + ) + parser.add_argument( + "--p0-runs-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_p0_reused_runs.csv"), + ) + parser.add_argument( + "--full-matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + new_rows = [] + p0_rows = [] + full_rows = [] + for seed in SEEDS: + p0_path = args.core_config_dir / f"core_m3_l1_t1_s{seed}.yaml" + p0 = yaml.safe_load(p0_path.read_text(encoding="utf-8")) + p0_row_config = copy.deepcopy(p0) + p0_row_config["experiment"]["position"] = "P0" + p0_row = matrix_row(p0_path, p0_row_config, "reused_core_matrix") + p0_rows.append(p0_row) + full_rows.append(p0_row) + + p1 = copy.deepcopy(p0) + name = f"temporal_p1_m3_l1_t1_s{seed}" + p1["name"] = name + p1["experiment"] = { + "phase": 3, + "matrix": "temporal_position", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "position": "P1", + "registered_axes": ["temporal_position"], + "reference": "P0_no_temporal_position_reused_core_m3_l1_t1", + } + p1["model"]["temporal_position_mode"] = "relative_bias" + p1["model"]["temporal_relative_bias_max_distance"] = 15 + p1_path = args.output_dir / f"{name}.yaml" + p1_path.write_text(yaml.safe_dump(p1, sort_keys=False), encoding="utf-8") + row = matrix_row(p1_path, p1, "new_formal_run") + new_rows.append(row) + full_rows.append(row) + + write_matrix(args.new_runs_csv, new_rows) + write_matrix(args.p0_runs_csv, p0_rows) + write_matrix(args.full_matrix_csv, full_rows) + print(f"generated {len(new_rows)} new configs and {len(full_rows)} P0/P1 rows") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase4_a3_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase4_a3_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..11d025bc0e7dd6e7f56fcad7fc54c12e8e9b509d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase4_a3_configs.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Generate hash-bound A3 oracle-crop tiny/health/formal configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +import json +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +MODES = { + "rgb": "oracle_rgb", + "depth_k": "oracle_depth_k", + "rgb_depth_k": "oracle_rgb_depth_k", +} +STAGES = { + "tiny2k": { + "stage": "tiny", "max_steps": 2_000, "checkpoint_interval": 500, + "validation_interval": 500, "warmup_steps": 100, + "validation_subset_manifest": None, + }, + "health25k": { + "stage": "health", "max_steps": 25_000, + "checkpoint_interval": 5_000, "validation_interval": 5_000, + "warmup_steps": 500, + "validation_subset_manifest": ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" + ), + }, + "formal100k": { + "stage": "formal", "max_steps": 100_000, + "checkpoint_interval": 25_000, "validation_interval": 5_000, + "warmup_steps": 500, + "validation_subset_manifest": ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" + ), + }, +} + + +def protocol(stage: dict[str, object]) -> dict[str, object]: + output = { + "max_steps": stage["max_steps"], + "num_workers": 4, + "checkpoint_interval": stage["checkpoint_interval"], + "validation_interval": stage["validation_interval"], + "validation_batches": 256, + "learning_rate": 5e-5, + "min_learning_rate": 5e-6, + "warmup_steps": stage["warmup_steps"], + "early_stopping_patience": 0, + "lr_schedule_steps": stage["max_steps"], + } + if stage["validation_subset_manifest"] is not None: + output["validation_subset_manifest"] = stage["validation_subset_manifest"] + return output + + +def build_config( + base: dict, + mode_slug: str, + stage_slug: str, + checkpoint: dict, +) -> dict: + result = copy.deepcopy(base) + mode = MODES[mode_slug] + stage = STAGES[stage_slug] + seed = int(base["seed"]) + name = f"phase4_a3_{mode_slug}_r640x368_s{seed}_{stage_slug}" + result["name"] = name + result["experiment"] = { + "phase": 4, + "wave": "A", + "cell": "A3", + "stage": stage["stage"], + "oracle_crop_mode": mode, + "reference": base["name"], + "changed_variable": "oracle_raw_high_resolution_crop_residual_only", + "coarse_checkpoint_path": checkpoint["path"], + "coarse_checkpoint_sha256": checkpoint["sha256"], + "coarse_checkpoint_step": checkpoint["step"], + "gt_location_at_train_and_validation": True, + "deployable_inference": False, + "official_test_used": False, + } + result["model"].update({ + "oracle_crop_mode": mode, + "freeze_coarse_for_oracle_crop": True, + }) + result["sampling"] = {"mode": "uniform"} + result["protocol"] = protocol(stage) + return result + + +def write_config_matrices( + rows: list[dict[str, object]], + matrix_csv: Path, + formal_matrix_csv: Path, +) -> list[dict[str, object]]: + if not rows: + raise ValueError("at least one A3 configuration row is required") + matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + if not formal_rows: + raise ValueError("A3 configuration matrix has no formal rows") + formal_matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + return formal_rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--checkpoint-index", type=Path, + default=Path("artifacts/phase3/reports/long_tail_checkpoints.json"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase4/a3_oracle_crop"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/a3_oracle_crop_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/a3_oracle_crop_formal_config_matrix.csv"), + ) + args = parser.parse_args() + checkpoint_index = json.loads(args.checkpoint_index.read_text(encoding="utf-8")) + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + "longtail_photometric_on_geometry_m3_l1_t1_" + f"r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + run = checkpoint_index["runs"][base["name"]] + checkpoint = run["roles"]["tail_best_absolute"] + if int(run["seed"]) != seed or int(checkpoint["step"]) not in range(100_000, 150_001): + raise ValueError(f"invalid frozen checkpoint record for seed {seed}") + for mode_slug, mode in MODES.items(): + for stage_slug in STAGES: + if stage_slug != "formal100k" and seed != SEEDS[0]: + continue + generated = build_config(base, mode_slug, stage_slug, checkpoint) + output_path = args.output_dir / f"{generated['name']}.yaml" + output_path.write_text( + yaml.safe_dump(generated, sort_keys=False), encoding="utf-8", + ) + rows.append({ + "config": str(output_path.resolve()), + "name": generated["name"], + "seed": seed, + "mode": mode, + "stage": STAGES[stage_slug]["stage"], + "max_steps": STAGES[stage_slug]["max_steps"], + "initialization_checkpoint": checkpoint["path"], + "initialization_checkpoint_sha256": checkpoint["sha256"], + "initialization_checkpoint_step": checkpoint["step"], + "gt_location": True, + "official_test_used": False, + }) + formal_rows = write_config_matrices( + rows, args.matrix_csv, args.formal_matrix_csv, + ) + print(json.dumps({ + "status": "generated", "configs": len(rows), + "output_dir": str(args.output_dir), "matrix_csv": str(args.matrix_csv), + "formal_configs": len(formal_rows), + "formal_matrix_csv": str(args.formal_matrix_csv), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase4_b0_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase4_b0_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..374500c074dfdc0d588ae23fef22449cd82d1893 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase4_b0_configs.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Generate preregistered Phase 4 B0 axis-aware loss configurations.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +AXIS_WEIGHTS = (0.5, 0.5, 2.0) +HUBER_BETA_M = 0.01 + + +def b0_config(base: dict, seed: int, stage: str) -> dict: + config = copy.deepcopy(base) + config["seed"] = seed + suffix = { + "smoke": "smoke1", + "tiny": "tiny2k", + "health": "health25k", + "formal": "formal100k", + }[stage] + config["name"] = f"phase4_b0_axis_huber_r640x368_s{seed}_{suffix}" + config["experiment"] = { + "phase": 4, + "wave": "B", + "cell": "B0", + "stage": stage, + "reference": f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}", + "changed_variable": "translation_loss_only", + "frozen_model_recipe": True, + "official_test_used": False, + } + config["loss"]["translation_mode"] = "axis_huber" + config["loss"]["translation_axis_weights"] = list(AXIS_WEIGHTS) + config["loss"]["translation_huber_beta_m"] = HUBER_BETA_M + protocol = config["protocol"] + if stage == "smoke": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 1, + "lr_schedule_steps": 1, + "warmup_steps": 0, + "checkpoint_interval": 1, + "validation_interval": 1, + }) + elif stage == "tiny": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 2_000, + "lr_schedule_steps": 2_000, + "warmup_steps": 100, + "checkpoint_interval": 500, + "validation_interval": 500, + }) + elif stage == "health": + protocol.update({ + "max_steps": 25_000, + "lr_schedule_steps": 25_000, + "warmup_steps": 500, + "checkpoint_interval": 5_000, + "validation_interval": 5_000, + }) + elif stage == "formal": + protocol.update({ + "max_steps": 100_000, + "lr_schedule_steps": 100_000, + "warmup_steps": 500, + "checkpoint_interval": 25_000, + "validation_interval": 5_000, + }) + return config + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, default=Path("configs/phase3/long_tail"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase4/b0_axis_loss")) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b0_axis_loss_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b0_axis_loss_formal_config_matrix.csv"), + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + stages = ("smoke", "tiny", "health", "formal") if seed == SEEDS[0] else ("formal",) + for stage in stages: + config = b0_config(base, seed, stage) + path = args.output_dir / f"{config['name']}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), + "name": config["name"], + "seed": seed, + "stage": stage, + "run_name": f"{stage}_seed{seed}", + "max_steps": config["protocol"]["max_steps"], + "changed_variable": "translation loss L1 -> axis Huber", + "translation_axis_weights": "0.5,0.5,2.0", + "translation_huber_beta_m": HUBER_BETA_M, + "official_test_used": False, + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + with args.formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + print(f"generated {len(rows)} Phase 4 B0 configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase4_b2_configs.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase4_b2_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..fa886d4b37a143c5c5e844620f87afaea3cec7f1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/generate_phase4_b2_configs.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Generate preregistered Phase 4 B2 balanced-sampling configurations.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +FULL_SAMPLER_MANIFEST = Path( + "/home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/" + "train_geometry_balanced_v1.json" +) +TINY_SAMPLER_MANIFEST = Path( + "/home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/" + "tiny_train_geometry_balanced_v1.json" +) + + +def b2_config(base: dict, seed: int, stage: str) -> dict: + config = copy.deepcopy(base) + config["seed"] = seed + suffix = { + "smoke": "smoke1", + "tiny": "tiny2k", + "health": "health25k", + "formal": "formal100k", + }[stage] + config["name"] = f"phase4_b2_balanced_sampler_r640x368_s{seed}_{suffix}" + config["experiment"] = { + "phase": 4, + "wave": "B", + "cell": "B2", + "stage": stage, + "reference": f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}", + "changed_variable": "training_sampler_only", + "frozen_model_recipe": True, + "official_test_used": False, + } + config["sampling"] = { + "mode": "balanced", + "manifest": str( + TINY_SAMPLER_MANIFEST if stage == "tiny" else FULL_SAMPLER_MANIFEST + ), + } + protocol = config["protocol"] + if stage == "smoke": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 1, + "lr_schedule_steps": 1, + "warmup_steps": 0, + "checkpoint_interval": 1, + "validation_interval": 1, + }) + elif stage == "tiny": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 2_000, + "lr_schedule_steps": 2_000, + "warmup_steps": 100, + "checkpoint_interval": 500, + "validation_interval": 500, + }) + elif stage == "health": + protocol.update({ + "max_steps": 25_000, + "lr_schedule_steps": 25_000, + "warmup_steps": 500, + "checkpoint_interval": 5_000, + "validation_interval": 5_000, + }) + elif stage == "formal": + protocol.update({ + "max_steps": 100_000, + "lr_schedule_steps": 100_000, + "warmup_steps": 500, + "checkpoint_interval": 25_000, + "validation_interval": 5_000, + }) + return config + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("configs/phase4/b2_balanced_sampling"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b2_balanced_sampling_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path( + "artifacts/phase4/reports/b2_balanced_sampling_formal_config_matrix.csv" + ), + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + stages = ("smoke", "tiny", "health", "formal") if seed == SEEDS[0] else ("formal",) + for stage in stages: + config = b2_config(base, seed, stage) + path = args.output_dir / f"{config['name']}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), + "name": config["name"], + "seed": seed, + "stage": stage, + "run_name": f"{stage}_seed{seed}", + "max_steps": config["protocol"]["max_steps"], + "changed_variable": "uniform -> train-only balanced sampling", + "sampling_manifest": config["sampling"]["manifest"], + "official_test_used": False, + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + with args.formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + print(f"generated {len(rows)} Phase 4 B2 configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/import_phase9_distributed_cache_worker_state.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/import_phase9_distributed_cache_worker_state.py new file mode 100644 index 0000000000000000000000000000000000000000..c41dc656030e78d58876c0bd9ad515c24f18ffac --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/import_phase9_distributed_cache_worker_state.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Normalize one external Stage 7 cache worker onto the central admission.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.phase9_distributed_assignment import load_assignment +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +HOST_LOCAL_ADMISSION_FIELDS = frozenset({"admitted_utc", "available_gib"}) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: Any) -> str: + payload = json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def scientific_admission(value: dict[str, Any]) -> dict[str, Any]: + return { + key: item for key, item in value.items() + if key not in HOST_LOCAL_ADMISSION_FIELDS + } + + +def validate_admission_pair( + source: dict[str, Any], central: dict[str, Any], expected_plan_sha256: str, +) -> dict[str, Any]: + for label, value in (("source", source), ("central", central)): + if ( + value.get("schema_version") != "phase9_resolution_admission_v1" + or value.get("status") != "complete" + or value.get("scientific_stage_admitted") is not True + or value.get("plan_sha256") != expected_plan_sha256 + or value.get("official_test_used") is not False + or value.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"{label} admission contract differs") + source_scientific = scientific_admission(source) + central_scientific = scientific_admission(central) + if source_scientific != central_scientific: + differing = sorted( + key for key in set(source_scientific) | set(central_scientific) + if source_scientific.get(key) != central_scientific.get(key) + ) + raise ValueError(f"distributed admission scientific binding differs: {differing}") + return { + "host_local_operational_fields": sorted(HOST_LOCAL_ADMISSION_FIELDS), + "source_operational_values": { + key: source[key] for key in sorted(HOST_LOCAL_ADMISSION_FIELDS) + }, + "central_operational_values": { + key: central[key] for key in sorted(HOST_LOCAL_ADMISSION_FIELDS) + }, + "normalized_scientific_binding_sha256": json_sha256(source_scientific), + } + + +def external_cache_worker_owner( + assignment: dict[str, Any], worker_id: str, +) -> str: + state_id = f"{worker_id}_cache_worker" + owners = { + item["id"]: item["owner"] + for item in assignment["stage7_cache_ownership"]["states"] + } + owner = owners.get(state_id) + if owner is None: + raise ValueError(f"distributed cache worker is undeclared: {worker_id}") + if owner == assignment["central_owner"]: + raise ValueError(f"cache worker is not external-owned: {worker_id}") + return owner + + +def validate_release_metadata( + release: dict[str, Any], receive: dict[str, Any], *, + source_owner: str, source_worker_sha256: str, bridge_plan_sha256: str, +) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != source_owner + or release.get("plan_sha256") != bridge_plan_sha256 + or release.get("producer_worker_state", {}).get("sha256") + != source_worker_sha256 + or release.get("live_reverse_sync_forbidden") is not True + or release.get("read_only_after_receive") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache release binding differs") + if ( + receive.get("status") != "complete" + or receive.get("plan_sha256") != bridge_plan_sha256 + or receive.get("release_file_count") != release.get("file_count") + or receive.get("release_total_bytes") != release.get("total_bytes") + or receive.get("live_reverse_sync_performed") is not False + or receive.get("official_test_used") is not False + or receive.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache receive binding differs") + released = { + item["id"]: (item["path"], item["file_count"], item["total_bytes"]) + for item in release.get("artifacts", []) + } + installed = { + item["id"]: (item["path"], item["file_count"], item["total_bytes"]) + for item in receive.get("installed", []) + } + if released != installed: + raise ValueError("external cache installed artifacts differ from release") + + +def validate_released_cache_files( + release: dict[str, Any], expected_files: list[dict[str, Any]], + resolution_hw: list[int], +) -> list[dict[str, Any]]: + root = Path(release["release_root"]) + inventory = {item["path"]: item for item in release["files"]} + results = [] + for expected in expected_files: + path = Path(expected["path"]) + relative = str(path.relative_to(root)) + record = inventory.get(relative) + if ( + record is None or record.get("sha256") != expected["sha256"] + or record.get("bytes") != path.stat().st_size + or not path.is_file() or sha256(path) != expected["sha256"] + ): + raise ValueError(f"external cache release file hash differs: {path}") + if path.name == "cache_report.json": + report = read_json(path) + if ( + report.get("status") != "complete" + or report.get("resolution_hw") != resolution_hw + or report.get("resume_invocation") is not True + or report.get("official_test_used") is not False + ): + raise ValueError(f"external cache report contract differs: {path}") + results.append({ + "path": str(path.resolve()), "sha256": expected["sha256"], + "release_relative_path": relative, "bytes": record["bytes"], + }) + return results + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("status") != "frozen" + or plan.get("central_owner") != "taku3" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("distributed admission import plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"distributed admission import binding differs: {path}") + assignment = load_assignment(plan) + if sha256(plan_path) == plan.get("superseded_plan_sha256"): + raise ValueError("distributed admission import plan identity differs") + return assignment + + +def build_imported_state(plan_path: Path, plan: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + assignment = validate_plan(plan_path, plan) + worker_id = plan["worker_id"] + source_owner = external_cache_worker_owner(assignment, worker_id) + if source_owner != plan["source_owner"]: + raise ValueError("distributed admission source owner differs") + source_admission_path = Path(plan["source_admission"]["evidence_path"]) + central_admission_path = Path(plan["central_admission"]["path"]) + source_worker_path = Path(plan["source_worker_state"]["evidence_path"]) + release_path = Path(plan["cache_release"]["evidence_path"]) + receive_path = Path(plan["cache_receive"]["path"]) + for path, expected in ( + (source_admission_path, plan["source_admission"]["sha256"]), + (central_admission_path, plan["central_admission"]["sha256"]), + (source_worker_path, plan["source_worker_state"]["sha256"]), + (release_path, plan["cache_release"]["sha256"]), + (receive_path, plan["cache_receive"]["sha256"]), + ): + if not path.is_file() or sha256(path) != expected: + raise ValueError(f"distributed admission evidence differs: {path}") + source_admission = read_json(source_admission_path) + central_admission = read_json(central_admission_path) + source_worker = read_json(source_worker_path) + release = read_json(release_path) + receive = read_json(receive_path) + admission = validate_admission_pair( + source_admission, central_admission, plan["cache_execution_plan_sha256"], + ) + if ( + source_worker.get("status") != "complete" + or source_worker.get("worker") != worker_id + or source_worker.get("plan_sha256") != plan["cache_execution_plan_sha256"] + or source_worker.get("admission_state_sha256") != plan["source_admission"]["sha256"] + or source_worker.get("winner") != central_admission["winner"] + or source_worker.get("winner_checkpoint") != central_admission["winner_checkpoint"] + or source_worker.get("winner_config") != central_admission["winner_config"] + or source_worker.get("official_test_used") is not False + or source_worker.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache worker scientific binding differs") + checkpoint = Path(source_worker["winner_checkpoint"]["path"]) + config = Path(source_worker["winner_config"]["path"]) + if ( + not checkpoint.is_file() + or sha256(checkpoint) != source_worker["winner_checkpoint"]["sha256"] + or not config.is_file() + or sha256(config) != source_worker["winner_config"]["sha256"] + ): + raise ValueError("external cache worker winner artifact differs") + validate_release_metadata( + release, receive, source_owner=source_owner, + source_worker_sha256=plan["source_worker_state"]["sha256"], + bridge_plan_sha256=plan["cache_release"]["plan_sha256"], + ) + if ( + release.get("file_count") != plan["cache_release"]["file_count"] + or release.get("total_bytes") != plan["cache_release"]["total_bytes"] + ): + raise ValueError("external cache release inventory totals differ") + if release["producer_worker_state"].get("value") != source_worker: + raise ValueError("external cache release worker value differs") + released_files = validate_released_cache_files( + release, plan["expected_cache_files"], plan["resolution_hw"], + ) + imported = deepcopy(source_worker) + imported["admission_state"] = str(central_admission_path.resolve()) + imported["admission_state_sha256"] = plan["central_admission"]["sha256"] + imported["distributed_admission_import"] = { + "schema_version": "phase9_distributed_admission_import_v1", + "status": "complete", "imported_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "worker": worker_id, "source_owner": source_owner, + "central_owner": assignment["central_owner"], + **admission, + "source_admission": { + "original_path": plan["source_admission"]["original_path"], + "evidence_path": str(source_admission_path.resolve()), + "sha256": plan["source_admission"]["sha256"], + }, + "central_admission": { + "path": str(central_admission_path.resolve()), + "sha256": plan["central_admission"]["sha256"], + }, + "source_worker_state": { + "original_path": plan["source_worker_state"]["original_path"], + "evidence_path": str(source_worker_path.resolve()), + "sha256": plan["source_worker_state"]["sha256"], + }, + "cache_release": { + "evidence_path": str(release_path.resolve()), + "sha256": plan["cache_release"]["sha256"], + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + }, + "cache_receive": { + "path": str(receive_path.resolve()), + "sha256": plan["cache_receive"]["sha256"], + }, + "released_cache_files": released_files, + "source_worker_state_preserved_unmodified": True, + "ordinary_single_host_binding_gate_changed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + audit = { + "schema_version": "phase9_distributed_admission_import_audit_v1", + "status": "complete", "created_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "worker": worker_id, "source_owner": source_owner, + "central_owner": assignment["central_owner"], + "source_admission_sha256": plan["source_admission"]["sha256"], + "central_admission_sha256": plan["central_admission"]["sha256"], + "host_local_operational_fields": admission["host_local_operational_fields"], + "normalized_scientific_binding_sha256": admission[ + "normalized_scientific_binding_sha256" + ], + "cache_release_sha256": plan["cache_release"]["sha256"], + "cache_receive_sha256": plan["cache_receive"]["sha256"], + "cache_release_file_count": release["file_count"], + "cache_release_total_bytes": release["total_bytes"], + "ordinary_single_host_binding_gate_changed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + return imported, audit + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output-state", type=Path, required=True) + parser.add_argument("--audit-output", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + if args.output_state.resolve() != Path(plan["output_state"]).resolve(): + parser.error("distributed admission output state differs") + if args.audit_output.resolve() != Path(plan["audit_output"]).resolve(): + parser.error("distributed admission audit output differs") + with Path(f"{args.output_state}.import.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + imported, audit = build_imported_state(args.plan, plan) + existing = read_json(args.output_state) if args.output_state.is_file() else None + if existing and existing.get("distributed_admission_import", {}).get( + "plan_sha256" + ) == sha256(args.plan): + if not args.audit_output.is_file(): + parser.error("imported worker exists without its audit") + print(json.dumps(existing, indent=2)) + return + atomic_json(args.output_state, imported) + audit["imported_worker_state"] = { + "path": str(args.output_state.resolve()), "sha256": sha256(args.output_state), + } + atomic_json(args.audit_output, audit) + print(json.dumps(imported, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/inspect_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/inspect_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..dad107db9c8f8406ee3a87089dcc0316a72f4fbb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/inspect_h2o.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +"""Inventory an extracted H2O egocentric dataset using only the standard library.""" + +from __future__ import annotations + +import argparse +import json +import struct +from collections import Counter, defaultdict +from pathlib import Path + + +CORE_FRAME_MODALITIES = { + "rgb", + "rgb256", + "depth", + "cam_pose", + "hand_pose", + "hand_pose_mano", + "obj_pose", + "obj_pose_rt", +} +TRAIN_LABEL_MODALITIES = {"action_label", "verb_label"} + + +def image_info(path: Path) -> dict[str, object]: + with path.open("rb") as handle: + header = handle.read(32) + if header.startswith(b"\x89PNG\r\n\x1a\n"): + width, height, bit_depth, color_type = struct.unpack(">IIBB", header[16:26]) + channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(color_type) + return { + "format": "PNG", + "width": width, + "height": height, + "bit_depth_per_channel": bit_depth, + "channels": channels, + "png_color_type": color_type, + } + + if header.startswith(b"\xff\xd8"): + handle.seek(2) + while True: + marker_start = handle.read(1) + if not marker_start: + break + if marker_start != b"\xff": + continue + marker = handle.read(1) + while marker == b"\xff": + marker = handle.read(1) + if marker in {b"\xd8", b"\xd9"}: + continue + size_raw = handle.read(2) + if len(size_raw) != 2: + break + size = struct.unpack(">H", size_raw)[0] + if marker and marker[0] in { + 0xC0, + 0xC1, + 0xC2, + 0xC3, + 0xC5, + 0xC6, + 0xC7, + 0xC9, + 0xCA, + 0xCB, + 0xCD, + 0xCE, + 0xCF, + }: + payload = handle.read(6) + bits, height, width, channels = struct.unpack(">BHHB", payload) + return { + "format": "JPEG", + "width": width, + "height": height, + "bit_depth_per_channel": bits, + "channels": channels, + } + handle.seek(size - 2, 1) + return {"format": "unknown"} + + +def numeric_frame_ids(files: list[Path]) -> set[int]: + return {int(path.stem) for path in files if path.stem.isdigit()} + + +def inspect_text(path: Path) -> dict[str, object]: + values = path.read_text(encoding="utf-8").split() + numeric = [] + for value in values[:8]: + try: + numeric.append(float(value)) + except ValueError: + numeric.append(value) + return {"value_count": len(values), "first_values": numeric} + + +def inspect_splits(root: Path) -> dict[str, object]: + result: dict[str, object] = {} + split_root = root / "label_split" + for split_path in sorted(split_root.glob("*.txt")): + lines = [line.strip() for line in split_path.read_text().splitlines() if line.strip()] + if split_path.name.startswith("pose_"): + missing = sum(not (root / line).is_file() for line in lines) + result[split_path.name] = { + "rows": len(lines), + "missing_paths": missing, + "first": lines[0] if lines else None, + "last": lines[-1] if lines else None, + } + else: + header = lines[0].split() if lines else [] + rows = [line.split() for line in lines[1:]] + path_index = header.index("path") if "path" in header else 1 + missing = sum(not (root / row[path_index]).is_dir() for row in rows) + class_counts: Counter[str] = Counter() + if "action_label" in header: + label_index = header.index("action_label") + class_counts.update(row[label_index] for row in rows) + result[split_path.name] = { + "rows": len(rows), + "columns": header, + "missing_paths": missing, + "class_counts": dict(sorted(class_counts.items(), key=lambda item: int(item[0]))), + } + return result + + +def inspect_dataset(root: Path) -> dict[str, object]: + modalities: dict[str, dict[str, object]] = defaultdict( + lambda: {"files": 0, "bytes": 0, "suffixes": set(), "sample": None} + ) + subject_take_counts: Counter[str] = Counter() + subject_rgb_frames: Counter[str] = Counter() + scene_take_counts: Counter[str] = Counter() + cameras: Counter[str] = Counter() + alignment_issue_counts: Counter[str] = Counter() + unexpected_alignment_issue_counts: Counter[str] = Counter() + alignment_examples: list[dict[str, object]] = [] + missing_modality_directory_takes: Counter[str] = Counter() + unexpected_modality_directory_takes: Counter[str] = Counter() + scalar_label_counts: dict[str, Counter[str]] = { + "action_label": Counter(), + "verb_label": Counter(), + "obj_pose": Counter(), + "obj_pose_rt": Counter(), + } + hand_presence: dict[str, Counter[str]] = { + "hand_pose": Counter(), + "hand_pose_mano": Counter(), + } + + take_dirs = sorted(root.glob("subject*/*/*/cam4")) + for cam4 in take_dirs: + subject, scene, take = cam4.parts[-4:-1] + subject_take_counts[subject] += 1 + scene_take_counts[f"{subject}/{scene}"] += 1 + for camera_dir in cam4.parent.glob("cam*"): + if camera_dir.is_dir(): + cameras[camera_dir.name] += 1 + + files_by_modality: dict[str, list[Path]] = {} + for child in sorted(cam4.iterdir()): + if child.is_dir(): + files = [entry for entry in child.iterdir() if entry.is_file()] + files_by_modality[child.name] = files + stats = modalities[child.name] + stats["files"] = int(stats["files"]) + len(files) + stats["bytes"] = int(stats["bytes"]) + sum(entry.stat().st_size for entry in files) + suffixes = stats["suffixes"] + assert isinstance(suffixes, set) + suffixes.update(entry.suffix.lower() for entry in files) + if stats["sample"] is None and files: + sample_path = sorted(files)[0] + sample: dict[str, object] = {"path": str(sample_path.relative_to(root))} + if sample_path.suffix.lower() in {".png", ".jpg", ".jpeg"}: + sample.update(image_info(sample_path)) + elif sample_path.suffix.lower() == ".txt": + sample.update(inspect_text(sample_path)) + stats["sample"] = sample + if child.name in scalar_label_counts: + for entry in files: + values = entry.read_text(encoding="utf-8").split() + if values: + scalar_label_counts[child.name][str(int(float(values[0])))] += 1 + if child.name in hand_presence: + right_flag_index = 64 if child.name == "hand_pose" else 62 + for entry in files: + values = entry.read_text(encoding="utf-8").split() + if len(values) <= right_flag_index: + hand_presence[child.name]["malformed"] += 1 + continue + left = int(float(values[0])) != 0 + right = int(float(values[right_flag_index])) != 0 + state = { + (True, True): "both", + (True, False): "left_only", + (False, True): "right_only", + (False, False): "neither", + }[(left, right)] + hand_presence[child.name][state] += 1 + elif child.is_file(): + stats = modalities[child.name] + stats["files"] = int(stats["files"]) + 1 + stats["bytes"] = int(stats["bytes"]) + child.stat().st_size + suffixes = stats["suffixes"] + assert isinstance(suffixes, set) + suffixes.add(child.suffix.lower()) + if stats["sample"] is None: + stats["sample"] = { + "path": str(child.relative_to(root)), + **inspect_text(child), + } + + expected_modalities = set(CORE_FRAME_MODALITIES) + if subject != "subject4": + expected_modalities.update(TRAIN_LABEL_MODALITIES) + actual_modalities = set(files_by_modality) + for modality in expected_modalities - actual_modalities: + missing_modality_directory_takes[modality] += 1 + for modality in actual_modalities - expected_modalities: + unexpected_modality_directory_takes[modality] += 1 + + rgb_ids = numeric_frame_ids(files_by_modality.get("rgb", [])) + subject_rgb_frames[subject] += len(rgb_ids) + for modality, files in files_by_modality.items(): + ids = numeric_frame_ids(files) + if ids and ids != rgb_ids: + missing = len(rgb_ids - ids) + extra = len(ids - rgb_ids) + if modality in expected_modalities: + alignment_issue_counts[modality] += 1 + alignment_scope = "expected" + else: + unexpected_alignment_issue_counts[modality] += 1 + alignment_scope = "unexpected" + if len(alignment_examples) < 20: + alignment_examples.append( + { + "take": f"{subject}/{scene}/{take}", + "modality": modality, + "scope": alignment_scope, + "missing_vs_rgb": missing, + "extra_vs_rgb": extra, + } + ) + + serializable_modalities = {} + for name, stats in sorted(modalities.items()): + serializable_modalities[name] = { + **stats, + "suffixes": sorted(stats["suffixes"]), + } + + object_stats = {} + for object_dir in sorted((root / "object").glob("*")): + if object_dir.is_dir(): + object_stats[object_dir.name] = sorted(path.name for path in object_dir.iterdir() if path.is_file()) + + return { + "root": str(root.resolve()), + "subjects": sorted(subject_take_counts), + "take_count": sum(subject_take_counts.values()), + "take_counts_by_subject": dict(sorted(subject_take_counts.items())), + "rgb_frames_by_subject": dict(sorted(subject_rgb_frames.items())), + "rgb_frames_total": sum(subject_rgb_frames.values()), + "take_counts_by_subject_scene": dict(sorted(scene_take_counts.items())), + "camera_directories": dict(sorted(cameras.items())), + "modalities": serializable_modalities, + "frame_alignment_issue_takes": dict(sorted(alignment_issue_counts.items())), + "unexpected_frame_alignment_issue_takes": dict(sorted(unexpected_alignment_issue_counts.items())), + "frame_alignment_examples": alignment_examples, + "missing_modality_directory_takes": dict(sorted(missing_modality_directory_takes.items())), + "unexpected_modality_directory_takes": dict(sorted(unexpected_modality_directory_takes.items())), + "per_frame_label_counts": { + name: dict(sorted(counts.items(), key=lambda item: int(item[0]))) + for name, counts in scalar_label_counts.items() + }, + "hand_presence_counts": { + name: dict(sorted(counts.items())) for name, counts in hand_presence.items() + }, + "objects": object_stats, + "splits": inspect_splits(root), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path, help="Extracted H2O root") + parser.add_argument("--output", type=Path, help="Write JSON to this path") + args = parser.parse_args() + report = inspect_dataset(args.root) + payload = json.dumps(report, indent=2, ensure_ascii=False) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(payload, encoding="utf-8") + print(payload, end="") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/merge_phase9_hot_prefill.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/merge_phase9_hot_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..a7db862b539b070f3f4174295d1c83bcbc7a2dfa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/merge_phase9_hot_prefill.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Atomically hardlink completed HOT3D prefill shards into a live cache.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path + +from scripts.cache_phase7_hot3d import sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_prefill_reports(reports: list[dict]) -> None: + if not reports: + raise ValueError("at least one prefill report is required") + for report in reports: + if ( + report.get("status") != "complete" + or report.get("mode") != "staged_prefill" + or report.get("official_test_used") is not False + ): + raise ValueError("prefill report is incomplete or lacks test isolation") + stable_keys = ( + "full_candidate_clips", "requested_target_clips", "max_recordings", + "candidate_source_indices_sha256", + ) + for key in stable_keys: + if len({json.dumps(report.get(key), sort_keys=True) for report in reports}) != 1: + raise ValueError(f"prefill reports disagree on {key}") + source_hashes = {report["source_manifest"]["sha256"] for report in reports} + if len(source_hashes) != 1: + raise ValueError("prefill reports disagree on source manifest SHA256") + ranges = sorted(tuple(report["candidate_position_range"]) for report in reports) + if any(first[1] > second[0] for first, second in zip(ranges, ranges[1:])): + raise ValueError("prefill position ranges overlap") + + +def merge_prefills( + target_output_dir: Path, prefill_output_dirs: list[Path], report_path: Path, +) -> dict: + reports = [ + json.loads((path / "cache_report.json").read_text(encoding="utf-8")) + for path in prefill_output_dirs + ] + validate_prefill_reports(reports) + target_clips = target_output_dir / "clips" + if not target_clips.is_dir(): + raise ValueError("target cache clips directory does not exist") + if (target_output_dir / "cache_manifest.jsonl").exists(): + raise ValueError("target deployable manifest is already frozen") + linked = existing_identical = 0 + shard_records = [] + for output_dir, report in zip(prefill_output_dirs, reports, strict=True): + manifest = output_dir / "prefill_manifest.jsonl" + if sha256(manifest) != report["cache_manifest"]["sha256"]: + raise ValueError(f"prefill manifest SHA256 differs: {manifest}") + rows = [ + json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if len(rows) != int(report["clips"]): + raise ValueError(f"prefill manifest row count differs: {manifest}") + for row in rows: + source = Path(row["cache_path"]) + expected_name = f"clip_{int(row['source_clip_index']):07d}.npz" + if source.name != expected_name or not source.is_file(): + raise ValueError(f"invalid staged cache path: {source}") + if sha256(source) != row["cache_sha256"]: + raise ValueError(f"staged cache SHA256 differs: {source}") + target = target_clips / expected_name + try: + os.link(source, target) + linked += 1 + except FileExistsError: + if sha256(target) != row["cache_sha256"]: + raise ValueError(f"target cache collision differs: {target}") + existing_identical += 1 + shard_records.append({ + "output_dir": str(output_dir.resolve()), + "report_sha256": sha256(output_dir / "cache_report.json"), + "manifest_sha256": sha256(manifest), + "candidate_position_range": report["candidate_position_range"], + "clips": len(rows), + }) + result = { + "schema_version": "phase9_hot_prefill_merge_v1", + "status": "complete", "created_utc": utc_now(), + "target_output_dir": str(target_output_dir.resolve()), + "linked": linked, "existing_identical": existing_identical, + "shards": shard_records, "official_test_used": False, + } + report_path.parent.mkdir(parents=True, exist_ok=True) + temporary = report_path.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(report_path) + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--target-output-dir", type=Path, required=True) + parser.add_argument("--prefill-output-dir", type=Path, action="append", required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + result = merge_prefills( + args.target_output_dir, args.prefill_output_dir, args.report, + ) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/merge_phase9_selection_binding_recovery.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/merge_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..b71938506149e999f92a5aa6039455009504e185 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/merge_phase9_selection_binding_recovery.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""Dry-run, validate, and atomically merge Phase 9 selection recovery.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any, Callable + +from scripts.run_phase9_selection_binding_recovery import ( + atomic_json, + validate_recovered_output, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_release( + *, release_path: Path, plan_path: Path, plan: dict[str, Any], owner: str, +) -> dict[str, Any]: + if not release_path.is_file(): + raise ValueError(f"selection recovery release missing: {owner}") + release = json.loads(release_path.read_text(encoding="utf-8")) + root = release_path.parent.resolve() + expected_ids = { + item["id"] for item in plan["evaluations"] if item["owner"] == owner + } + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != owner + or release.get("plan", {}).get("sha256") != sha256(plan_path) + or Path(str(release.get("root", ""))).resolve() != root + or set(release.get("evaluation_ids", [])) != expected_ids + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or release.get("read_only_after_publish") is not True + ): + raise ValueError(f"selection recovery release contract differs: {owner}") + seen = set() + total_bytes = 0 + for item in release.get("files", []): + relative = Path(item["path"]) + if relative.is_absolute() or ".." in relative.parts or str(relative) in seen: + raise ValueError(f"invalid recovery release path: {relative}") + seen.add(str(relative)) + path = root / relative + if ( + not path.is_file() + or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"selection recovery release file differs: {path}") + total_bytes += item["bytes"] + if ( + len(seen) != release.get("file_count") + or total_bytes != release.get("total_bytes") + ): + raise ValueError(f"selection recovery release inventory differs: {owner}") + evidence = {item["id"]: item for item in release["evaluations"]} + if set(evidence) != expected_ids: + raise ValueError(f"selection recovery release evidence differs: {owner}") + for item in plan["evaluations"]: + if item["owner"] != owner: + continue + relative_output = Path(evidence[item["id"]]["output_dir"]) + if (root / relative_output).resolve() != Path(item["output_dir"]).resolve(): + raise ValueError(f"selection recovery output path differs: {item['id']}") + validate_recovered_output(item) + return release + + +def symlink_copy(source: str, destination: str) -> str: + os.symlink(str(Path(source).resolve()), destination) + return destination + + +def recovered_output_map( + plan: dict[str, Any], releases: dict[str, dict[str, Any]], + release_paths: dict[str, Path], +) -> dict[str, Path]: + result = {} + for owner, release in releases.items(): + root = release_paths[owner].parent.resolve() + by_id = {item["id"]: item for item in release["evaluations"]} + for item in plan["evaluations"]: + if item["owner"] == owner: + result[item["id"]] = root / by_id[item["id"]]["output_dir"] + return result + + +def run_dry_selection( + *, plan: dict[str, Any], recovered: dict[str, Path], +) -> dict[str, Any]: + selection_plan_path = Path(plan["selection_plan"]["path"]) + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + dry_root = Path(plan["dry_run_root"]) / sha256(selection_plan_path) + milestone_root = dry_root / "h2o_multifold_milestones" + output_json = dry_root / "unified_selection.json" + output_csv = dry_root / "unified_selection.csv" + if output_json.is_file() and output_csv.is_file(): + report = json.loads(output_json.read_text(encoding="utf-8")) + if ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + ): + return { + "root": str(dry_root.resolve()), + "json": {"path": str(output_json.resolve()), "sha256": sha256(output_json)}, + "csv": {"path": str(output_csv.resolve()), "sha256": sha256(output_csv)}, + "winner": report["winner"], + } + raise ValueError("existing selection dry-run output differs") + if dry_root.exists(): + shutil.rmtree(dry_root) + dry_root.mkdir(parents=True) + shutil.copytree( + Path(selection_plan["fold_milestone_root"]), milestone_root, + copy_function=symlink_copy, + ) + for item in plan["evaluations"]: + target = ( + milestone_root / item["condition"] / item["checkpoint_id"] + / item["input_mode"] + ) + if target.is_symlink() or target.is_file(): + target.unlink() + elif target.is_dir(): + shutil.rmtree(target) + os.symlink(str(recovered[item["id"]].resolve()), target, target_is_directory=True) + command = [ + sys.executable, "-m", "scripts.summarize_phase9_unified_selection", + "--external-root", selection_plan["external_root"], + "--fold-final-root", selection_plan["fold_final_root"], + "--fold-milestone-root", str(milestone_root.resolve()), + "--multifold-index", selection_plan["multifold_index"], + "--output-json", str(output_json.resolve()), + "--output-csv", str(output_csv.resolve()), + ] + log_path = dry_root / "summarizer.log" + with log_path.open("x", encoding="utf-8") as log: + result = subprocess.run( + command, cwd=Path.cwd(), stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + if result.returncode or not output_json.is_file() or not output_csv.is_file(): + raise ValueError(f"selection dry-run summarizer failed: {result.returncode}") + report = json.loads(output_json.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError("selection dry-run report isolation differs") + return { + "root": str(dry_root.resolve()), + "json": {"path": str(output_json.resolve()), "sha256": sha256(output_json)}, + "csv": {"path": str(output_csv.resolve()), "sha256": sha256(output_csv)}, + "log": {"path": str(log_path.resolve()), "sha256": sha256(log_path)}, + "winner": report["winner"], + } + + +def canonical_output(plan: dict[str, Any], item: dict[str, Any]) -> Path: + return ( + Path(plan["canonical_fold_milestone_root"]) + / item["condition"] / item["checkpoint_id"] / item["input_mode"] + ) + + +def prepare_outputs( + *, plan: dict[str, Any], recovered: dict[str, Path], +) -> dict[str, Path]: + prepared = {} + for item in plan["evaluations"]: + canonical = canonical_output(plan, item) + destination = canonical.parent / f".{canonical.name}.selection_recovery_v2_ready" + if destination.exists(): + shutil.rmtree(destination) + shutil.copytree(recovered[item["id"]], destination, copy_function=shutil.copy2) + candidate = {**item, "output_dir": str(destination.resolve())} + validate_recovered_output(candidate) + prepared[item["id"]] = destination + return prepared + + +def merge_outputs( + *, plan_path: Path, plan: dict[str, Any], prepared: dict[str, Path], + dry_run: dict[str, Any], releases: dict[str, dict[str, Any]], + release_paths: dict[str, Path], state_path: Path, +) -> dict[str, Any]: + backup_root = Path(plan["canonical_merge_backup_root"]) + backup_root.mkdir(parents=True, exist_ok=True) + lock_path = backup_root.parent / ".selection_binding_v2_merge.lock" + plan_hash = sha256(plan_path) + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if state_path.is_file(): + existing = json.loads(state_path.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == plan_hash + ): + return existing + if existing.get("plan_sha256") not in {None, plan_hash}: + raise ValueError("existing selection merge state differs") + replacements = [] + try: + for item in plan["evaluations"]: + canonical = canonical_output(plan, item) + backup = ( + backup_root / item["condition"] / item["checkpoint_id"] + / item["input_mode"] + ) + if backup.exists(): + raise ValueError(f"selection merge backup already exists: {backup}") + if not canonical.is_dir(): + raise ValueError(f"selection canonical output missing: {canonical}") + backup.parent.mkdir(parents=True, exist_ok=True) + os.replace(canonical, backup) + try: + os.replace(prepared[item["id"]], canonical) + except Exception: + os.replace(backup, canonical) + raise + replacements.append((item, canonical, backup)) + except Exception: + for item, canonical, backup in reversed(replacements): + staging = canonical.parent / f".{canonical.name}.rollback_recovered" + if staging.exists(): + shutil.rmtree(staging) + os.replace(canonical, staging) + os.replace(backup, canonical) + raise + merged = [] + for item, canonical, backup in replacements: + candidate = {**item, "output_dir": str(canonical.resolve())} + evidence = validate_recovered_output(candidate) + merged.append({ + "id": item["id"], "canonical_output": str(canonical.resolve()), + "backup_output": str(backup.resolve()), **evidence, + }) + state = { + "schema_version": "phase9_selection_binding_recovery_merge_state_v1", + "status": "complete", "completed_utc": datetime.now(timezone.utc).isoformat(), + "plan": str(plan_path.resolve()), "plan_sha256": plan_hash, + "dry_run": dry_run, + "releases": { + owner: { + "path": str(release_paths[owner].resolve()), + "sha256": sha256(release_paths[owner]), + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + } + for owner, release in releases.items() + }, + "merged": merged, + "failure_backup": plan["failure_backup"], + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(state_path, state) + return state + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--taku3-release", type=Path, required=True) + parser.add_argument("--server-new-release", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if ( + plan.get("official_test_used") is not False + or args.state.resolve() != Path(plan["canonical_merge_state"]).resolve() + ): + parser.error("selection merge plan/state contract differs") + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + parser.error(f"selection recovery code binding differs: {path}") + release_paths = { + "taku3": args.taku3_release, "server_new": args.server_new_release, + } + releases = { + owner: validate_release( + release_path=path, plan_path=args.plan, plan=plan, owner=owner, + ) + for owner, path in release_paths.items() + } + recovered = recovered_output_map(plan, releases, release_paths) + dry_run = run_dry_selection(plan=plan, recovered=recovered) + prepared = prepare_outputs(plan=plan, recovered=recovered) + state = merge_outputs( + plan_path=args.plan, plan=plan, prepared=prepared, dry_run=dry_run, + releases=releases, release_paths=release_paths, state_path=args.state, + ) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/merge_sota_bundles.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/merge_sota_bundles.py new file mode 100644 index 0000000000000000000000000000000000000000..584ee70fdf4d271fce83b8faeacf785e8d0e4324 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/merge_sota_bundles.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Merge disjoint inference shards and restore official-manifest frame order.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("inputs", nargs="+", type=Path) + args = parser.parse_args() + bundles = [PredictionBundle.load(path) for path in args.inputs] + names = {bundle.model_name for bundle in bundles} + if len(names) != 1: + raise ValueError(f"Shard model names differ: {names}") + has_vertices = {bundle.vertices_camera_m is not None for bundle in bundles} + if len(has_vertices) != 1: + raise ValueError("Shard vertex availability differs") + keys, _, _ = load_frame_index(args.manifest) + order_lookup = {str(key): index for index, key in enumerate(keys)} + concatenated_keys = np.concatenate([bundle.frame_keys for bundle in bundles]) + if set(map(str, concatenated_keys.tolist())) != set(map(str, keys.tolist())): + raise ValueError("Merged shards do not exactly cover the manifest") + order = np.argsort([order_lookup[str(key)] for key in concatenated_keys]) + metadata = dict(bundles[0].metadata) + metadata.pop("num_shards", None) + metadata.pop("shard_index", None) + for name in ( + "refined_windows", + "missing_detection_windows", + "tail_hand_frames_falling_back_to_wilor", + "root_iterations_total", + "smooth_iterations_total", + "run_count", + "new_initializations", + "new_optimizations", + ): + if all(name in bundle.metadata for bundle in bundles): + metadata[name] = sum(int(bundle.metadata[name]) for bundle in bundles) + delta_name = "initializer_mesh_reconstruction_delta_mm" + if all(delta_name in bundle.metadata for bundle in bundles): + weights = np.asarray( + [int(bundle.metadata.get("refined_windows", 0)) for bundle in bundles], + dtype=np.float64, + ) + values = np.asarray( + [float(bundle.metadata[delta_name]) for bundle in bundles], + dtype=np.float64, + ) + if weights.sum() > 0: + metadata[delta_name] = float(np.average(values, weights=weights)) + metadata.update({ + "merged_shards": len(bundles), + "shard_inputs": [str(path.resolve()) for path in args.inputs], + }) + PredictionBundle( + model_name=bundles[0].model_name, + frame_keys=concatenated_keys[order], + takes=np.concatenate([bundle.takes for bundle in bundles])[order], + frame_ids=np.concatenate([bundle.frame_ids for bundle in bundles])[order], + joints_camera_m=np.concatenate([ + bundle.joints_camera_m for bundle in bundles + ])[order], + detected=np.concatenate([bundle.detected for bundle in bundles])[order], + confidence=np.concatenate([bundle.confidence for bundle in bundles])[order], + vertices_camera_m=( + np.concatenate([bundle.vertices_camera_m for bundle in bundles])[order] + if True in has_vertices + else None + ), + metadata=metadata, + ).save(args.output) + print(f"merged {len(bundles)} shards into {args.output}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/phase9_distributed_assignment.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/phase9_distributed_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..a244226e86486c4dc547fe55431fa31f45e015c4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/phase9_distributed_assignment.py @@ -0,0 +1,156 @@ +"""Shared ownership checks for distributed Phase 9 controllers.""" + +from __future__ import annotations + +import json +from pathlib import Path +import socket +from typing import Any + +from scripts.run_phase9_unified_train_queue import sha256 + + +MACHINES = ("taku3", "server_new") + + +def load_assignment(plan: dict[str, Any]) -> dict[str, Any]: + binding = plan.get("distributed_assignment", {}) + path = Path(str(binding.get("path", ""))) + if not path.is_file() or sha256(path) != binding.get("sha256"): + raise ValueError("distributed assignment binding differs") + assignment = json.loads(path.read_text(encoding="utf-8")) + if ( + assignment.get("schema_version") + != "foundation_phase9_distributed_assignment_v2" + or assignment.get("central_owner") != "taku3" + or assignment.get("selection_owner") != "taku3" + or assignment.get("report_owner") != "taku3" + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + or assignment.get("writer_contract", {}).get( + "single_writer_per_output" + ) is not True + or assignment.get("writer_contract", {}).get( + "live_reverse_sync_forbidden" + ) is not True + ): + raise ValueError("distributed assignment contract differs") + return assignment + + +def detect_machine(assignment: dict[str, Any], requested: str | None) -> str: + host = socket.gethostname() + matches = [ + machine for machine in MACHINES + if assignment["machines"][machine]["hostname"] == host + ] + if requested is not None: + if requested not in MACHINES or assignment["machines"][requested]["hostname"] != host: + raise ValueError("requested distributed machine differs from hostname") + return requested + if len(matches) != 1: + raise ValueError(f"hostname is not uniquely assigned: {host}") + return matches[0] + + +def gpu_allowlist(assignment: dict[str, Any], machine: str) -> list[int]: + allowed = assignment["machines"][machine]["physical_gpu_allowlist"] + if ( + not isinstance(allowed, list) + or not allowed + or len(allowed) != len(set(allowed)) + or any(not isinstance(gpu, int) for gpu in allowed) + ): + raise ValueError(f"distributed GPU allowlist differs: {machine}") + if machine == "server_new" and allowed != [0, 1, 2, 5]: + raise ValueError("server_new GPU allowlist must be exactly 0/1/2/5") + return allowed + + +def role_owners(assignment: dict[str, Any]) -> dict[str, str]: + records = assignment["stage_condition_ownership"]["roles"] + result = {item["role"]: item["owner"] for item in records} + expected = { + "full", "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + } + if set(result) != expected or len(records) != len(result): + raise ValueError("distributed role ownership differs") + if any(owner not in MACHINES for owner in result.values()): + raise ValueError("distributed role owner is unknown") + return result + + +def condition_owners( + registry: dict[str, Any], assignment: dict[str, Any], +) -> dict[str, str]: + owners = role_owners(assignment) + result = {} + for item in registry["conditions"]: + condition = item["condition"] + role = item.get("role") + if role not in owners or condition in result: + raise ValueError(f"distributed training role differs: {condition}") + result[condition] = owners[role] + if len(result) != 7: + raise ValueError("distributed training registry must contain seven jobs") + return result + + +def controller_state_path(plan: dict[str, Any], machine: str) -> Path: + states = plan.get("controller_states", {}) + if set(states) != set(MACHINES): + raise ValueError("distributed controller states differ") + paths = [str(Path(value).resolve()) for value in states.values()] + if len(paths) != len(set(paths)): + raise ValueError("distributed controller states are not unique") + return Path(states[machine]) + + +def distribute_evaluations( + *, evaluations: list[dict[str, Any]], assignment: dict[str, Any], + worker_state_root: Path, +) -> list[dict[str, Any]]: + owners = role_owners(assignment) + grouped: dict[str, list[dict[str, Any]]] = {machine: [] for machine in MACHINES} + for item in evaluations: + role = item.get("training_role") + if role not in owners: + raise ValueError(f"distributed evaluation role differs: {item.get('id')}") + owner = owners[role] + item["owner"] = owner + grouped[owner].append(item) + workers = [] + for owner in MACHINES: + gpus = gpu_allowlist(assignment, owner) + buckets: dict[int, list[str]] = {gpu: [] for gpu in gpus} + for index, item in enumerate(grouped[owner]): + buckets[gpus[index % len(gpus)]].append(item["id"]) + for gpu, identifiers in buckets.items(): + if not identifiers: + continue + workers.append({ + "id": f"{owner}_gpu{gpu}", "owner": owner, + "physical_gpu_id": gpu, + "state": str(( + worker_state_root / owner / f"gpu{gpu}_state.json" + ).resolve()), + "evaluation_ids": identifiers, + }) + ids = [item["id"] for item in evaluations] + assigned = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(ids) != len(set(ids)) + or len(assigned) != len(ids) + or len(set(assigned)) != len(ids) + or set(assigned) != set(ids) + ): + raise ValueError("distributed evaluation workers overlap or omit IDs") + return workers + + +def local_workers(workers: list[dict[str, Any]], machine: str) -> list[dict[str, Any]]: + result = [item for item in workers if item.get("owner") == machine] + if any(item.get("owner") not in MACHINES for item in workers): + raise ValueError("distributed evaluation worker owner differs") + return result diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/postprocess_video_jitter.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/postprocess_video_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..0b737af92d0fc6c2aa7713b0b03d209f6147eb86 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/postprocess_video_jitter.py @@ -0,0 +1,927 @@ +#!/usr/bin/env python3 +"""Cache raw long-sequence predictions and render jitter-smoothed MANO demos. + +This is an offline visualization postprocessor. It does not change the model, +checkpoint, evaluator, or reported metrics. Missing raw caches are reconstructed +with the exact checkpoint and non-overlapping temporal chunks recorded in the +source selection manifest. Later filter changes reuse those caches. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from scipy.signal import butter, sosfiltfilt +from scipy.spatial.transform import Rotation + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + MeshLayer, + project_mesh_layers, + render_mesh_layers, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.training.checkpoint import load_checkpoint + + +LEFT_COLOR_RGB = (40, 100, 235) +RIGHT_COLOR_RGB = (235, 55, 55) +MESH_ALPHA = 0.55 +CACHE_VERSION = 1 +RAW_CACHE_KEYS = ( + "mano_rotations_6d", + "mano_rotation_matrices", + "mano_shape", + "wrist_root_translation", + "vertices_camera", + "joints_camera", + "joint2d_norm", + "presence_logit", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_json_atomic(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + os.replace(temporary, path) + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def add_header(image_rgb: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image_rgb.copy() + height = 8 + 22 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, + line, + (8, 20 + 22 * index), + cv2.FONT_HERSHEY_SIMPLEX, + 0.55, + (255, 255, 255), + 1, + cv2.LINE_AA, + ) + return output + + +class FFmpegVideoWriter: + """Stream BGR frames to an atomic, Mac-compatible H.264 MP4.""" + + def __init__( + self, + path: Path, + fps: float, + frame_hw: tuple[int, int], + *, + crf: int, + preset: str, + ) -> None: + self.path = path + self.frame_hw = frame_hw + self.frames_written = 0 + path.parent.mkdir(parents=True, exist_ok=True) + self.temporary = path.with_name(f".{path.stem}.tmp-{os.getpid()}.mp4") + height, width = frame_hw + command = [ + "ffmpeg", + "-nostdin", + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "rawvideo", + "-pix_fmt", + "bgr24", + "-s:v", + f"{width}x{height}", + "-r", + f"{fps:.8g}", + "-i", + "pipe:0", + "-an", + "-c:v", + "libx264", + "-preset", + preset, + "-crf", + str(crf), + "-pix_fmt", + "yuv420p", + "-movflags", + "+faststart", + str(self.temporary), + ] + self.process = subprocess.Popen( + command, + stdin=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + def write(self, frame_bgr: np.ndarray) -> None: + height, width = self.frame_hw + if frame_bgr.shape != (height, width, 3) or frame_bgr.dtype != np.uint8: + raise ValueError( + f"invalid video frame {frame_bgr.shape}/{frame_bgr.dtype}; " + f"expected {(height, width, 3)}/uint8" + ) + if self.process.stdin is None: + raise RuntimeError("ffmpeg stdin is unavailable") + try: + self.process.stdin.write(np.ascontiguousarray(frame_bgr).tobytes()) + except BrokenPipeError as error: + stderr = self._read_stderr() + raise RuntimeError(f"ffmpeg stopped while writing {self.path}: {stderr}") from error + self.frames_written += 1 + + def _read_stderr(self) -> str: + if self.process.stderr is None: + return "" + return self.process.stderr.read().decode("utf-8", errors="replace").strip() + + def close(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + stderr = self._read_stderr() + return_code = self.process.wait() + if return_code != 0: + self.temporary.unlink(missing_ok=True) + raise RuntimeError(f"ffmpeg failed for {self.path}: {stderr}") + os.replace(self.temporary, self.path) + + def abort(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + if self.process.poll() is None: + self.process.terminate() + try: + self.process.wait(timeout=5) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + self.temporary.unlink(missing_ok=True) + + +def lowpass(values: np.ndarray, cutoff_hz: float, fps: float, order: int) -> np.ndarray: + if not 0.0 < cutoff_hz < fps / 2.0: + raise ValueError(f"cutoff must be in (0, {fps / 2.0}), got {cutoff_hz}") + if values.shape[0] < max(12, order * 6): + raise ValueError(f"sequence too short for zero-phase filtering: {values.shape[0]}") + sections = butter(order, cutoff_hz, btype="lowpass", fs=fps, output="sos") + return np.asarray(sosfiltfilt(sections, values, axis=0), dtype=np.float32) + + +def smooth_rotations( + matrices: np.ndarray, + cutoff_hz: float, + fps: float, + order: int, +) -> np.ndarray: + """Low-pass SO(3) trajectories through sign-continuous unit quaternions.""" + + if matrices.ndim != 5 or matrices.shape[1:] != (2, 16, 3, 3): + raise ValueError(f"unexpected rotation shape: {matrices.shape}") + frame_count = matrices.shape[0] + quaternions = Rotation.from_matrix(matrices.reshape(-1, 3, 3)).as_quat() + quaternions = quaternions.reshape(frame_count, 2, 16, 4) + for frame_index in range(1, frame_count): + dots = np.sum( + quaternions[frame_index - 1] * quaternions[frame_index], + axis=-1, + ) + quaternions[frame_index][dots < 0.0] *= -1.0 + filtered = lowpass(quaternions, cutoff_hz, fps, order) + norms = np.linalg.norm(filtered, axis=-1, keepdims=True) + if np.any(norms < 1e-6): + raise RuntimeError("quaternion low-pass produced a near-zero norm") + filtered /= norms + smoothed = Rotation.from_quat(filtered.reshape(-1, 4)).as_matrix() + return smoothed.reshape(matrices.shape).astype(np.float32) + + +def smooth_prediction( + raw: dict[str, np.ndarray], + *, + translation_cutoff_hz: float, + rotation_cutoff_hz: float, + fps: float, + order: int, +) -> dict[str, np.ndarray]: + shape = raw["mano_shape"] + stable_shape = np.median(shape, axis=0, keepdims=True).astype(np.float32) + return { + "frame_ids": raw["frame_ids"].copy(), + "mano_rotation_matrices": smooth_rotations( + raw["mano_rotation_matrices"], rotation_cutoff_hz, fps, order + ), + "mano_shape": np.repeat(stable_shape, shape.shape[0], axis=0), + "wrist_root_translation": lowpass( + raw["wrist_root_translation"], translation_cutoff_hz, fps, order + ), + } + + +def build_model( + config: dict[str, Any], + checkpoint_path: Path, + checkpoint_step: int, + device: torch.device, +) -> BimanualReconstructionModel: + assets = config["assets"] + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + state = load_checkpoint(checkpoint_path, model, optimizer=None, map_location=device) + if int(state["step"]) != checkpoint_step: + raise ValueError( + f"checkpoint step mismatch: expected {checkpoint_step}, got {state['step']}" + ) + return model + + +def infer_case( + *, + case: dict[str, Any], + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + checkpoint_sha256: str, +) -> dict[str, np.ndarray]: + values: dict[str, list[np.ndarray]] = defaultdict(list) + observed_frame_ids: list[int] = [] + for clip_number, clip_index in enumerate(clip_indices, start=1): + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + clip_frame_ids = sample["frame_id"].cpu().numpy().astype(np.int32) + observed_frame_ids.extend(int(value) for value in clip_frame_ids) + for key in RAW_CACHE_KEYS: + if key in prediction: + values[key].append(prediction[key][0].float().cpu().numpy()) + del prediction, batch + if clip_number % 25 == 0 or clip_number == len(clip_indices): + print( + f" inference {clip_number}/{len(clip_indices)} chunks " + f"({len(observed_frame_ids)}/{len(case['frame_ids'])} frames)", + flush=True, + ) + + expected_frame_ids = [int(value) for value in case["frame_ids"]] + if observed_frame_ids != expected_frame_ids: + raise RuntimeError( + f"inference frame mismatch for {case['take']}: " + f"{len(observed_frame_ids)} != {len(expected_frame_ids)}" + ) + arrays = { + key: np.concatenate(chunks, axis=0).astype(np.float32) + for key, chunks in values.items() + } + arrays.update({ + "frame_ids": np.asarray(observed_frame_ids, dtype=np.int32), + "take": np.asarray(str(case["take"])), + "checkpoint_sha256": np.asarray(checkpoint_sha256), + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + }) + required = { + "mano_rotation_matrices", + "mano_shape", + "wrist_root_translation", + "vertices_camera", + "joints_camera", + } + missing = sorted(required - arrays.keys()) + if missing: + raise RuntimeError(f"model output is missing cache fields: {missing}") + for key, value in arrays.items(): + if np.issubdtype(value.dtype, np.floating) and not np.isfinite(value).all(): + raise RuntimeError(f"non-finite values in raw output {key} for {case['take']}") + return arrays + + +def load_raw_cache( + path: Path, + *, + case: dict[str, Any], + checkpoint_sha256: str, +) -> dict[str, np.ndarray] | None: + if not path.is_file(): + return None + try: + with np.load(path, allow_pickle=False) as archive: + raw = {key: archive[key] for key in archive.files} + if int(raw["cache_version"]) != CACHE_VERSION: + return None + if str(raw["take"]) != str(case["take"]): + return None + if str(raw["checkpoint_sha256"]) != checkpoint_sha256: + return None + expected = np.asarray(case["frame_ids"], dtype=np.int32) + if not np.array_equal(raw["frame_ids"], expected): + return None + return raw + except (KeyError, OSError, ValueError): + return None + + +def rebuild_mano_geometry( + prediction: dict[str, np.ndarray], + mano_layer: ManoCameraLayer, + device: torch.device, + *, + batch_size: int = 128, +) -> None: + vertices: list[np.ndarray] = [] + joints: list[np.ndarray] = [] + frame_count = prediction["frame_ids"].shape[0] + for start in range(0, frame_count, batch_size): + stop = min(start + batch_size, frame_count) + rotations = torch.from_numpy( + prediction["mano_rotation_matrices"][start:stop] + ).to(device) + shape = torch.from_numpy(prediction["mano_shape"][start:stop]).to(device) + translation = torch.from_numpy( + prediction["wrist_root_translation"][start:stop] + ).to(device) + with torch.inference_mode(): + vertex_batch, joint_batch = mano_layer(rotations, shape, translation) + vertices.append(vertex_batch.float().cpu().numpy()) + joints.append(joint_batch.float().cpu().numpy()) + prediction["vertices_camera"] = np.concatenate(vertices, axis=0).astype(np.float32) + prediction["joints_camera"] = np.concatenate(joints, axis=0).astype(np.float32) + + +def acceleration_stats(points_m: np.ndarray) -> dict[str, float]: + acceleration_mm = np.linalg.norm(np.diff(points_m, n=2, axis=0), axis=-1) * 1000.0 + return { + "mean_mm_per_frame2": float(acceleration_mm.mean()), + "p50_mm_per_frame2": float(np.percentile(acceleration_mm, 50)), + "p95_mm_per_frame2": float(np.percentile(acceleration_mm, 95)), + } + + +def displacement_stats(raw_m: np.ndarray, smoothed_m: np.ndarray) -> dict[str, float]: + displacement_mm = np.linalg.norm(smoothed_m - raw_m, axis=-1) * 1000.0 + return { + "mean_mm": float(displacement_mm.mean()), + "p50_mm": float(np.percentile(displacement_mm, 50)), + "p95_mm": float(np.percentile(displacement_mm, 95)), + "max_mm": float(displacement_mm.max()), + } + + +def rotation_displacement_stats( + raw_matrices: np.ndarray, + smoothed_matrices: np.ndarray, +) -> dict[str, float]: + relative = np.swapaxes(raw_matrices, -1, -2) @ smoothed_matrices + radians = Rotation.from_matrix(relative.reshape(-1, 3, 3)).magnitude() + degrees = np.degrees(radians) + return { + "mean_degrees": float(degrees.mean()), + "p50_degrees": float(np.percentile(degrees, 50)), + "p95_degrees": float(np.percentile(degrees, 95)), + "max_degrees": float(degrees.max()), + } + + +def jitter_metrics( + raw: dict[str, np.ndarray], + smoothed: dict[str, np.ndarray], +) -> dict[str, Any]: + raw_wrist = acceleration_stats(raw["wrist_root_translation"]) + smooth_wrist = acceleration_stats(smoothed["wrist_root_translation"]) + raw_vertices = acceleration_stats(raw["vertices_camera"]) + smooth_vertices = acceleration_stats(smoothed["vertices_camera"]) + + def reduction(raw_value: float, smooth_value: float) -> float: + return float((1.0 - smooth_value / max(raw_value, 1e-12)) * 100.0) + + return { + "wrist_acceleration_raw": raw_wrist, + "wrist_acceleration_smoothed": smooth_wrist, + "wrist_acceleration_mean_reduction_percent": reduction( + raw_wrist["mean_mm_per_frame2"], smooth_wrist["mean_mm_per_frame2"] + ), + "vertex_acceleration_raw": raw_vertices, + "vertex_acceleration_smoothed": smooth_vertices, + "vertex_acceleration_mean_reduction_percent": reduction( + raw_vertices["mean_mm_per_frame2"], + smooth_vertices["mean_mm_per_frame2"], + ), + "wrist_filter_displacement": displacement_stats( + raw["wrist_root_translation"], smoothed["wrist_root_translation"] + ), + "vertex_filter_displacement": displacement_stats( + raw["vertices_camera"], smoothed["vertices_camera"] + ), + "rotation_filter_displacement": rotation_displacement_stats( + raw["mano_rotation_matrices"], smoothed["mano_rotation_matrices"] + ), + "raw_shape_temporal_std_mean": float(raw["mano_shape"].std(axis=0).mean()), + } + + +def probe_video(path: Path, expected_frames: int, frame_hw: tuple[int, int]) -> None: + command = [ + "ffprobe", + "-v", + "error", + "-select_streams", + "v:0", + "-count_frames", + "-show_entries", + "stream=codec_name,pix_fmt,width,height,nb_read_frames", + "-of", + "json", + str(path), + ] + report = json.loads(subprocess.check_output(command, text=True)) + streams = report.get("streams", []) + if len(streams) != 1: + raise RuntimeError(f"expected one video stream in {path}") + stream = streams[0] + height, width = frame_hw + observed = ( + stream.get("codec_name"), + stream.get("pix_fmt"), + int(stream.get("width", -1)), + int(stream.get("height", -1)), + int(stream.get("nb_read_frames", -1)), + ) + expected = ("h264", "yuv420p", width, height, expected_frames) + if observed != expected: + raise RuntimeError(f"video validation failed for {path}: {observed} != {expected}") + + +def render_case( + *, + case: dict[str, Any], + raw: dict[str, np.ndarray], + smoothed: dict[str, np.ndarray], + source_case_dir: Path, + output_case_dir: Path, + data_root: Path, + faces: tuple[np.ndarray, np.ndarray], + fps: float, + translation_cutoff_hz: float, + rotation_cutoff_hz: float, + filter_order: int, + crf: int, + preset: str, +) -> dict[str, Any]: + output_case_dir.mkdir(parents=True, exist_ok=True) + take_dir = data_root / str(case["take"]) + raw_K, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + height, width = source_hw + output_paths = { + "smoothed_overlay": output_case_dir / "predicted_mano_overlay_smoothed.mp4", + "smoothed_side_by_side": output_case_dir / "side_by_side_smoothed.mp4", + "raw_vs_smoothed": output_case_dir / "raw_vs_smoothed.mp4", + } + writers = [ + FFmpegVideoWriter(output_paths["smoothed_overlay"], fps, source_hw, crf=crf, preset=preset), + FFmpegVideoWriter( + output_paths["smoothed_side_by_side"], + fps, + (height, width * 2), + crf=crf, + preset=preset, + ), + FFmpegVideoWriter( + output_paths["raw_vs_smoothed"], + fps, + (height, width * 2), + crf=crf, + preset=preset, + ), + ] + raw_overlay_path = source_case_dir / "predicted_mano_overlay.mp4" + raw_capture = cv2.VideoCapture(str(raw_overlay_path)) + if not raw_capture.isOpened(): + for writer in writers: + writer.abort() + raise RuntimeError(f"failed to open source overlay: {raw_overlay_path}") + + frame_ids = [int(value) for value in case["frame_ids"]] + preview = None + comparison_preview = None + try: + for frame_index, frame_id in enumerate(frame_ids): + raw_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), + cv2.IMREAD_COLOR, + ) + if raw_bgr is None or raw_bgr.shape[:2] != source_hw: + raise RuntimeError(f"raw RGB decode/shape failure: {take_dir}/{frame_id}") + ok, source_overlay_bgr = raw_capture.read() + if not ok or source_overlay_bgr.shape[:2] != source_hw: + raise RuntimeError( + f"source overlay ended at frame {frame_index}: {raw_overlay_path}" + ) + raw_rgb = cv2.cvtColor(raw_bgr, cv2.COLOR_BGR2RGB) + layers = [ + MeshLayer( + smoothed["vertices_camera"][frame_index, hand], + faces[hand], + LEFT_COLOR_RGB if hand == 0 else RIGHT_COLOR_RGB, + MESH_ALPHA, + ) + for hand in range(2) + ] + rendered = render_mesh_layers(raw_rgb, project_mesh_layers(layers, raw_K)) + rendered = add_header(rendered, ( + f"Post-processed MANO | zero-phase low-pass | left=BLUE right=RED alpha={MESH_ALPHA:.2f}", + f"{case['subject']}/{case['sequence']} | frame={frame_id} " + f"({frame_index + 1}/{len(frame_ids)}) | translation={translation_cutoff_hz:g} Hz " + f"rotation={rotation_cutoff_hz:g} Hz order={filter_order}", + )) + original_panel = add_header(raw_rgb, ("Original cam4 RGB",)) + side_by_side = np.concatenate((original_panel, rendered), axis=1) + source_overlay_rgb = cv2.cvtColor(source_overlay_bgr, cv2.COLOR_BGR2RGB) + raw_vs_smoothed = np.concatenate((source_overlay_rgb, rendered), axis=1) + + writers[0].write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + writers[1].write(cv2.cvtColor(side_by_side, cv2.COLOR_RGB2BGR)) + writers[2].write(cv2.cvtColor(raw_vs_smoothed, cv2.COLOR_RGB2BGR)) + if frame_index == len(frame_ids) // 2: + preview = rendered.copy() + comparison_preview = raw_vs_smoothed.copy() + if (frame_index + 1) % 100 == 0 or frame_index + 1 == len(frame_ids): + print(f" render {frame_index + 1}/{len(frame_ids)} frames", flush=True) + + extra, _ = raw_capture.read() + if extra: + raise RuntimeError(f"source overlay has extra frames: {raw_overlay_path}") + for writer in writers: + writer.close() + except BaseException: + for writer in writers: + if writer.process.poll() is None or writer.temporary.exists(): + writer.abort() + raise + finally: + raw_capture.release() + + if preview is None or comparison_preview is None: + raise RuntimeError(f"no preview generated for {case['take']}") + preview_path = output_case_dir / "preview_smoothed.png" + comparison_preview_path = output_case_dir / "preview_raw_vs_smoothed.png" + cv2.imwrite(str(preview_path), cv2.cvtColor(preview, cv2.COLOR_RGB2BGR)) + cv2.imwrite( + str(comparison_preview_path), + cv2.cvtColor(comparison_preview, cv2.COLOR_RGB2BGR), + ) + probe_video(output_paths["smoothed_overlay"], len(frame_ids), source_hw) + probe_video( + output_paths["smoothed_side_by_side"], + len(frame_ids), + (height, width * 2), + ) + probe_video( + output_paths["raw_vs_smoothed"], + len(frame_ids), + (height, width * 2), + ) + metrics = jitter_metrics(raw, smoothed) + record = { + "take": case["take"], + "subject": case["subject"], + "sequence": case["sequence"], + "category": case["category"], + "rank": case["rank"], + "frame_count": len(frame_ids), + "source_case": str(source_case_dir.resolve()), + "raw_prediction_cache": str((output_case_dir / "raw_prediction.npz").resolve()), + "smoothed_prediction_cache": str( + (output_case_dir / "smoothed_prediction.npz").resolve() + ), + "videos": {key: str(path.resolve()) for key, path in output_paths.items()}, + "preview": str(preview_path.resolve()), + "raw_vs_smoothed_preview": str(comparison_preview_path.resolve()), + "jitter_metrics": metrics, + } + write_json_atomic(output_case_dir / "case_postprocess.json", record) + record["preview_rgb"] = preview + return record + + +def save_contact_sheet(path: Path, records: list[dict[str, Any]]) -> None: + if not records: + return + panels = [] + for record in records: + panel = cv2.resize(record["preview_rgb"], (384, 216), interpolation=cv2.INTER_AREA) + panel = add_header(panel, ( + f"{record['category']} #{record['rank']} | " + f"jitter -{record['jitter_metrics']['vertex_acceleration_mean_reduction_percent']:.1f}%", + )) + panels.append(panel) + while len(panels) % 5: + panels.append(np.zeros_like(panels[0])) + rows = [np.concatenate(panels[index : index + 5], axis=1) for index in range(0, len(panels), 5)] + sheet = np.concatenate(rows, axis=0) + cv2.imwrite(str(path), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR)) + + +def source_case_directory(source_dir: Path, case: dict[str, Any]) -> Path: + category_dir = "best_cases" if case["category"] == "best" else "failure_cases" + recorded = Path(case["videos"]["original"]).parent.name + path = source_dir / category_dir / recorded + if not path.is_dir(): + raise FileNotFoundError(f"source case directory missing: {path}") + return path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Re-infer missing raw MANO caches and render zero-phase jitter-smoothed demos." + ) + parser.add_argument( + "--source-dir", + type=Path, + default=Path("artifacts/phase3/video_cases_best_model_long_sequences"), + ) + parser.add_argument("--output-dir", type=Path) + parser.add_argument("--data-root", type=Path, default=Path("data/H2O/extracted")) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--category", choices=("all", "best", "failure"), default="all") + parser.add_argument("--max-cases", type=int) + parser.add_argument("--translation-cutoff-hz", type=float, default=3.0) + parser.add_argument("--rotation-cutoff-hz", type=float, default=4.0) + parser.add_argument("--filter-order", type=int, default=2) + parser.add_argument("--crf", type=int, default=18) + parser.add_argument( + "--ffmpeg-preset", + choices=("ultrafast", "superfast", "veryfast", "faster", "fast", "medium"), + default="fast", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + source_dir = args.source_dir.resolve() + if args.output_dir is None: + output_dir = source_dir.with_name(f"{source_dir.name}_smoothed") + else: + output_dir = args.output_dir.resolve() + data_root = args.data_root.resolve() + if source_dir == output_dir: + raise ValueError("source and output directories must differ") + if args.filter_order < 1: + raise ValueError("filter order must be positive") + if not 0 <= args.crf <= 51: + raise ValueError("CRF must be in [0, 51]") + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required to reconstruct missing raw prediction caches") + device = torch.device(f"cuda:{args.gpu}") + + selection_path = source_dir / "selection_manifest.json" + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if selection.get("status") != "complete" or selection.get("official_test_used") is not False: + raise ValueError("source selection manifest is incomplete or uses official test data") + config_path = Path(selection["config"]) + checkpoint = selection["checkpoint"] + checkpoint_path = Path(checkpoint["path"]) + expected_checkpoint_hash = str(checkpoint["sha256"]) + observed_checkpoint_hash = sha256(checkpoint_path) + if observed_checkpoint_hash != expected_checkpoint_hash: + raise ValueError("checkpoint hash differs from the source selection manifest") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + fps = float(selection["visualization_fps"]) + lowpass(np.zeros((32, 1), dtype=np.float32), args.translation_cutoff_hz, fps, args.filter_order) + lowpass(np.zeros((32, 1), dtype=np.float32), args.rotation_cutoff_hz, fps, args.filter_order) + + cases = [ + case + for case in selection["cases"] + if args.category == "all" or case["category"] == args.category + ] + if args.max_cases is not None: + if args.max_cases < 1: + raise ValueError("max cases must be positive") + cases = cases[: args.max_cases] + if not cases: + raise ValueError(f"no cases selected for category={args.category}") + output_dir.mkdir(parents=True, exist_ok=True) + + data_config = config["data"] + render_manifest_path = source_dir / "render_input_manifest.jsonl" + model_t = int(data_config["T"]) + dataset = H2OCam4Dataset( + data_root, + render_manifest_path, + tuple(data_config["resolution_hw"]), + (model_t,), + (int(data_config["stride"]),), + ) + clip_indices_by_take: dict[str, list[int]] = defaultdict(list) + for clip_index, clip in enumerate(dataset.clips): + clip_indices_by_take[clip.take].append(clip_index) + + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model: BimanualReconstructionModel | None = None + mano_layer: ManoCameraLayer | None = None + faces: tuple[np.ndarray, np.ndarray] | None = None + records: list[dict[str, Any]] = [] + for case_index, case in enumerate(cases, start=1): + source_case_dir = source_case_directory(source_dir, case) + category_dir = "best_cases" if case["category"] == "best" else "failure_cases" + output_case_dir = output_dir / category_dir / source_case_dir.name + output_case_dir.mkdir(parents=True, exist_ok=True) + raw_cache_path = output_case_dir / "raw_prediction.npz" + print( + f"[{case_index}/{len(cases)}] {case['category']} #{case['rank']} " + f"{case['take']} ({len(case['frame_ids'])} frames)", + flush=True, + ) + raw = load_raw_cache( + raw_cache_path, + case=case, + checkpoint_sha256=expected_checkpoint_hash, + ) + if raw is None: + if model is None: + print("loading frozen model checkpoint", flush=True) + model = build_model( + config, + checkpoint_path, + int(checkpoint["step"]), + device, + ) + mano_layer = model.mano_layer + if mano_layer is None: + raise RuntimeError("loaded model has no MANO layer") + faces = tuple(layer.th_faces.cpu().numpy() for layer in mano_layer.layers) + raw = infer_case( + case=case, + dataset=dataset, + clip_indices=clip_indices_by_take[str(case["take"])], + model=model, + device=device, + dtype=dtype, + checkpoint_sha256=expected_checkpoint_hash, + ) + save_npz_atomic(raw_cache_path, raw) + print(f" saved raw cache: {raw_cache_path}", flush=True) + else: + print(f" reusing raw cache: {raw_cache_path}", flush=True) + + if mano_layer is None: + mano_layer = ManoCameraLayer(config["assets"]["mano_root"]).to(device).eval() + if faces is None: + faces = tuple(layer.th_faces.cpu().numpy() for layer in mano_layer.layers) + smoothed = smooth_prediction( + raw, + translation_cutoff_hz=args.translation_cutoff_hz, + rotation_cutoff_hz=args.rotation_cutoff_hz, + fps=fps, + order=args.filter_order, + ) + rebuild_mano_geometry(smoothed, mano_layer, device) + save_npz_atomic(output_case_dir / "smoothed_prediction.npz", smoothed) + record = render_case( + case=case, + raw=raw, + smoothed=smoothed, + source_case_dir=source_case_dir, + output_case_dir=output_case_dir, + data_root=data_root, + faces=faces, + fps=fps, + translation_cutoff_hz=args.translation_cutoff_hz, + rotation_cutoff_hz=args.rotation_cutoff_hz, + filter_order=args.filter_order, + crf=args.crf, + preset=args.ffmpeg_preset, + ) + records.append(record) + print( + " mean vertex acceleration reduction: " + f"{record['jitter_metrics']['vertex_acceleration_mean_reduction_percent']:.1f}%", + flush=True, + ) + + save_contact_sheet(output_dir / "contact_sheet_smoothed.png", records) + serializable_records = [ + {key: value for key, value in record.items() if key != "preview_rgb"} + for record in records + ] + summary = { + "status": "complete", + "purpose": "offline visualization-only jitter postprocessing", + "source_dir": str(source_dir), + "source_selection_manifest": str(selection_path), + "checkpoint": checkpoint, + "model_inference_policy": ( + f"same frozen checkpoint and non-overlapping T={model_t} chunks as source render" + ), + "raw_cache_policy": ( + "render-relevant raw outputs are cached before filtering and reused on later runs" + ), + "postprocessing": { + "translation": "zero-phase Butterworth low-pass in camera XYZ", + "translation_cutoff_hz": args.translation_cutoff_hz, + "rotation": "zero-phase Butterworth low-pass on sign-continuous unit quaternions", + "rotation_cutoff_hz": args.rotation_cutoff_hz, + "filter_order": args.filter_order, + "shape": "per-take temporal median, held constant", + "fps": fps, + "phase_lag_frames": 0, + }, + "video_encoding": { + "codec": "H.264", + "pixel_format": "yuv420p", + "crf": args.crf, + "preset": args.ffmpeg_preset, + }, + "metrics_are_official_evaluation": False, + "cases": serializable_records, + } + write_json_atomic(output_dir / "postprocess_manifest.json", summary) + mean_reductions = [ + record["jitter_metrics"]["vertex_acceleration_mean_reduction_percent"] + for record in records + ] + readme = f"""# Jitter-Smoothed Long-Sequence Video Cases + +This directory is a visualization-only postprocessing of `{source_dir}`. The +model, checkpoint, official evaluation, and source artifacts are unchanged. + +Missing predictions were reconstructed with the same frozen checkpoint and +non-overlapping T={model_t} inference policy as the source demo. Each case keeps +`raw_prediction.npz` before filtering, so filter parameters can be adjusted and +videos regenerated without running the reconstruction model again. + +The offline filter is a zero-phase order-{args.filter_order} Butterworth low-pass: + +- wrist translation cutoff: {args.translation_cutoff_hz:g} Hz; +- MANO rotation cutoff: {args.rotation_cutoff_hz:g} Hz; +- MANO shape: temporal median held fixed within each take. + +Zero-phase filtering introduces no visual time shift but uses future frames, so +these videos do not represent a causal real-time system. H.264/yuv420p output is +used for macOS playback. `raw_vs_smoothed.mp4` is the clearest A/B view. + +Across the {len(records)} rendered cases, mean per-case vertex-acceleration +reduction is {float(np.mean(mean_reductions)):.1f}%. See +`postprocess_manifest.json` and each `case_postprocess.json` for details. +""" + (output_dir / "README.md").write_text(readme, encoding="utf-8") + print(json.dumps({ + "status": "complete", + "output_dir": str(output_dir), + "case_count": len(records), + "mean_vertex_acceleration_reduction_percent": float(np.mean(mean_reductions)), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/prepare_phase9_storage_overflow.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/prepare_phase9_storage_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..8e5f5a81b71ffeca38c3c4a0820da0a212058a66 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/prepare_phase9_storage_overflow.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Bind unopened Phase 9 fold outputs to a larger physical volume.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def bind_directory(logical: Path, physical: Path) -> str: + if logical.is_symlink(): + if logical.resolve() != physical.resolve(): + raise RuntimeError(f"existing symlink has wrong target: {logical}") + return "existing_identical" + if logical.exists(): + raise RuntimeError(f"logical output already exists: {logical}") + physical.mkdir(parents=True, exist_ok=True) + logical.parent.mkdir(parents=True, exist_ok=True) + os.symlink(physical, logical, target_is_directory=True) + if not logical.is_symlink() or logical.resolve() != physical.resolve(): + raise RuntimeError(f"failed to bind output: {logical}") + return "created" + + +def prepare(plan: dict[str, Any], plan_path: Path) -> dict[str, Any]: + if plan.get("official_test_used") is not False: + raise ValueError("plan must explicitly exclude official test") + registry_path = Path(plan["fold_training_registry"]) + if sha256(registry_path) != plan["fold_training_registry_sha256"]: + raise ValueError("fold registry hash mismatch") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + raise ValueError("fold registry must explicitly exclude official test") + conditions = {row["condition"]: row for row in registry["conditions"]} + logical_roots = { + key: Path(value) for key, value in plan["logical_evaluation_roots"].items() + } + physical_root = Path(plan["physical_root"]) + rows = [] + for condition_id in plan["conditions"]: + if condition_id not in conditions: + raise ValueError(f"condition is absent from registry: {condition_id}") + condition = conditions[condition_id] + bindings = { + "run": ( + Path(condition["output_dir"]), + physical_root / "runs" / "h2o_multifold" / condition_id.lower(), + ), + "final_evaluation": ( + logical_roots["final"] / condition_id, + physical_root / "evaluations" / "h2o_multifold" / condition_id, + ), + "milestone_evaluation": ( + logical_roots["milestone"] / condition_id, + physical_root / "evaluations" / "h2o_multifold_milestones" / condition_id, + ), + } + for kind, (logical, physical) in bindings.items(): + status = bind_directory(logical, physical) + rows.append({ + "condition": condition_id, "kind": kind, "status": status, + "logical": str(logical), "physical": str(physical), + }) + return { + "schema_version": "phase9_storage_overflow_report_v1", + "status": "complete", + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "bindings": rows, + "scientific_protocol_changed": False, + "official_test_used": False, + "completed_utc": utc_now(), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output report already exists") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + report = prepare(plan, args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/probe_memory.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/probe_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..c37fb1447ab5553ded97429d5473f5c2582a7123 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/probe_memory.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""4090 memory matrix using official random DINOv3 architecture (never training).""" + +from __future__ import annotations + +import argparse +import csv +import json +import platform +import time +from pathlib import Path + +import torch +from torch import nn + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.encoders import PatchFeatures + + +class ProbeDinoEncoder(nn.Module): + def __init__(self, backbone: nn.Module, output_dim: int = 512) -> None: + super().__init__() + self.backbone = backbone.requires_grad_(False).eval() + self.projection = nn.Linear(768, output_dim) + self.patch_size = 16 + + def train(self, mode: bool = True): + super().train(mode) + self.backbone.eval() + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + with torch.no_grad(): + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + return PatchFeatures(self.projection(raw), (images.shape[-2] // 16, images.shape[-1] // 16), 16) + + +def make_batch(batch_size: int, time_steps: int, height: int, width: int, device: torch.device) -> dict[str, torch.Tensor]: + K = torch.tensor([[width * 0.5, 0, width * 0.5], [0, width * 0.5, height * 0.5], [0, 0, 1]], device=device, dtype=torch.float32) + return { + "rgb": torch.randn(batch_size, time_steps, 3, height, width, device=device), + "depth_m": torch.rand(batch_size, time_steps, 1, height, width, device=device) + 0.3, + "depth_pixel_valid": torch.ones(batch_size, time_steps, 1, height, width, device=device, dtype=torch.bool), + "K": K[None, None].expand(batch_size, time_steps, -1, -1).clone(), + "K_available": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + "depth_available": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + "frame_valid": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + } + + +def run_case(backbone: nn.Module, case: dict[str, object], device: torch.device) -> dict[str, object]: + height, width = case["height"], case["width"] + dtype = torch.bfloat16 if case["precision"] == "bf16" else torch.float16 + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats(device) + config = ModelConfig( + encoder="tiny_debug", decoder_dim=512, decoder_layers=int(case["decoder_layers"]), attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, depth_mode="log_depth", use_rays=True, + use_bimanual_interaction=True, gradient_checkpointing=bool(case["gradient_checkpointing"]), + ) + model = BimanualReconstructionModel(config) + model.rgb_encoder = ProbeDinoEncoder(backbone, 512) + model.to(device).train() + batch = make_batch(int(case["batch_size"]), int(case["T"]), int(height), int(width), device) + start = time.perf_counter() + try: + with torch.autocast("cuda", dtype=dtype): + output = model(batch) + loss = ( + output["joint2d_norm"].square().mean() + + output["mano_rotations_6d"].square().mean() + + output["wrist_root_translation"].square().mean() + + output["mano_shape_sequence"].square().mean() + ) + forward_end = time.perf_counter() + loss.backward() + torch.cuda.synchronize(device) + end = time.perf_counter() + case.update({ + "status": "ok", "forward_s": forward_end - start, "forward_backward_s": end - start, + "frames_per_s": int(case["batch_size"]) * int(case["T"]) / (end - start), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30, + "loss_finite": bool(torch.isfinite(loss)), + }) + except torch.cuda.OutOfMemoryError as error: + case.update({"status": "oom", "error": str(error).splitlines()[0], "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30}) + finally: + del model, batch + torch.cuda.empty_cache() + return case + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--quick", action="store_true", help="Probe the core matrix; omit extra checkpoint/layer variants") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + torch.cuda.set_device(args.gpu) + device = torch.device("cuda") + from dinov3.hub.backbones import dinov3_vitb16 + torch.manual_seed(20260716) + backbone = dinov3_vitb16(pretrained=False).to(device) + cases = [] + for width, height in ((384, 224), (512, 288), (640, 368)): + for T in (1, 4, 8, 16): + for batch_size in (1, 2): + for precision in ("bf16", "fp16"): + cases.append({"width": width, "height": height, "T": T, "batch_size": batch_size, "precision": precision, "decoder_layers": 3, "gradient_checkpointing": False}) + if not args.quick: + for layers in (2, 3): + for checkpointing in (False, True): + for batch_size in (1, 2): + cases.append({"width": 512, "height": 288, "T": 8, "batch_size": batch_size, "precision": "bf16", "decoder_layers": layers, "gradient_checkpointing": checkpointing}) + + results = [] + for index, case in enumerate(cases): + case.update({"case": index, "gpu": torch.cuda.get_device_name(device), "random_architecture_only": True, "dinov3": "official dinov3_vitb16 pretrained=False", "seed": 20260716}) + result = run_case(backbone, case, device) + results.append(result) + print(json.dumps(result), flush=True) + fields = sorted({key for result in results for key in result}) + with (args.output_dir / "memory_probe.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader(); writer.writerows(results) + summary = { + "warning": "Architecture-only memory probe with official randomly initialized DINOv3 ViT-B/16. Not a training/quality result.", + "torch": torch.__version__, "python": platform.python_version(), "gpu": torch.cuda.get_device_name(device), + "case_count": len(results), "ok": sum(row["status"] == "ok" for row in results), "oom": sum(row["status"] == "oom" for row in results), + "results_csv": str((args.output_dir / "memory_probe.csv").resolve()), + } + (args.output_dir / "memory_probe_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/profile_phase5_alignment_solver.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/profile_phase5_alignment_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..842eb2831c09853c1731c7bd7a4e3d1276cad639 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/profile_phase5_alignment_solver.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Profile the deployable per-frame predicted-MANO/depth alignment solver.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import resource +import time +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def latency_summary(values_ms: list[float]) -> dict[str, float | int]: + values = np.asarray(values_ms, dtype=np.float64) + if not values.size or not np.isfinite(values).all(): + raise ValueError("latency samples must be non-empty and finite") + return { + "frames": int(len(values)), + "mean_ms": float(values.mean()), + "std_ms": float(values.std()), + "p50_ms": float(np.percentile(values, 50)), + "p90_ms": float(np.percentile(values, 90)), + "p95_ms": float(np.percentile(values, 95)), + "minimum_ms": float(values.min()), + "maximum_ms": float(values.max()), + "throughput_frames_per_second": float(1000.0 / values.mean()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--frames", type=int, default=128) + parser.add_argument("--warmup", type=int, default=8) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite profile: {args.output}") + if args.frames < 1 or args.warmup < 0: + parser.error("frames must be positive and warmup non-negative") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("scope") != "full" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + ): + raise ValueError("profile requires a complete official-validation raw cache") + take_record = manifest["takes"][0] + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError("profile take cache hash mismatch") + with np.load(take_path, allow_pickle=False) as archive: + frame_ids = archive["frame_id"][:args.frames].astype(np.int64) + vertices = archive["pred_vertices_camera"][:args.frames].astype(np.float32) + take = str(archive["take"]) + take_dir = args.data_root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + + depths = [] + for frame_id in frame_ids: + depth_mm = cv2.imread( + str(take_dir / "depth" / f"{int(frame_id):06d}.png"), cv2.IMREAD_UNCHANGED, + ) + if depth_mm is None or depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{int(frame_id):06d}") + depths.append(depth_mm_to_m(depth_mm)) + cv2.setNumThreads(1) + for index in range(min(args.warmup, len(frame_ids))): + for hand in range(2): + align_wrist_z(vertices[index, hand], K_raw, *depths[index]) + + elapsed_ms = [] + applied = [] + support = [] + for index in range(len(frame_ids)): + started = time.perf_counter_ns() + for hand in range(2): + diagnostics, _ = align_wrist_z( + vertices[index, hand], K_raw, *depths[index], + ) + applied.append(diagnostics.applied) + support.append(diagnostics.valid_support_count) + elapsed_ms.append((time.perf_counter_ns() - started) / 1_000_000.0) + + report = { + "status": "profiled", + "experiment_class": "engineering_profile_not_model_selection", + "official_validation_used": True, + "official_validation_used_for_model_or_threshold_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], + "take": take, + "frame_range": [int(frame_ids[0]), int(frame_ids[-1])], + "latency": { + **latency_summary(elapsed_ms), + "scope": "CPU per-frame two-hand projection/depth sampling/IRLS; raw depth predecoded; excludes coarse model and file I/O", + }, + "applied_hand_fraction": float(np.mean(applied)), + "support_count_mean": float(np.mean(support)), + "peak_process_rss_mib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0, + "cpu": platform.processor(), + "opencv_threads": cv2.getNumThreads(), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/profile_phase5_model.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/profile_phase5_model.py new file mode 100644 index 0000000000000000000000000000000000000000..08e09f54b448c025820f47f08d473f2dfbf8948b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/profile_phase5_model.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Profile a frozen candidate on one official-train clip without model selection.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader +from torch.utils.flop_counter import FlopCounterMode + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def move_to_device(batch: dict[str, object], device: torch.device) -> dict[str, object]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def parameter_counts(model: torch.nn.Module) -> dict[str, int]: + trainable = sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad) + frozen = sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad) + return {"trainable": trainable, "frozen": frozen, "total": trainable + frozen} + + +def percentile_summary(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + if not array.size or not np.isfinite(array).all(): + raise ValueError("latency measurements must be non-empty and finite") + return { + "iterations": int(len(array)), + "mean_ms": float(array.mean()), + "std_ms": float(array.std()), + "p50_ms": float(np.percentile(array, 50)), + "p90_ms": float(np.percentile(array, 90)), + "p95_ms": float(np.percentile(array, 95)), + "minimum_ms": float(array.min()), + "maximum_ms": float(array.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--warmup", type=int, default=20) + parser.add_argument("--iterations", type=int, default=100) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite profile: {args.output}") + if args.warmup < 1 or args.iterations < 1: + parser.error("warmup and iterations must be positive") + if "test" in args.manifest.name.lower() or "val" in args.manifest.name.lower(): + parser.error("profiling is restricted to official-train data") + checkpoint_hash = sha256(args.checkpoint) + if checkpoint_hash != args.expected_checkpoint_sha256: + parser.error("checkpoint hash mismatch") + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data = config["data"] + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data["resolution_hw"]), + (int(data["T"]),), + (int(data["stride"]),), + max_clips=1, + ) + loader = DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + batch = move_to_device(next(iter(loader)), device) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + if checkpoint.get("extra", {}).get("config") != config: + raise ValueError("profiling config differs from checkpoint embedded config") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + for _ in range(args.warmup): + model(batch) + torch.cuda.synchronize(device) + torch.cuda.reset_peak_memory_stats(device) + starts = [torch.cuda.Event(enable_timing=True) for _ in range(args.iterations)] + ends = [torch.cuda.Event(enable_timing=True) for _ in range(args.iterations)] + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + for start, end in zip(starts, ends, strict=True): + start.record() + model(batch) + end.record() + torch.cuda.synchronize(device) + latency = percentile_summary([start.elapsed_time(end) for start, end in zip(starts, ends, strict=True)]) + peak_vram_gib = torch.cuda.max_memory_allocated(device) / 2**30 + + flop_counter = FlopCounterMode(display=False) + # FlopCounterMode's module tracker requires an autograd graph in PyTorch 2.6. + # This single pass is excluded from the inference latency measurements above. + with torch.autocast("cuda", dtype=dtype), flop_counter: + model(batch) + supported_flops = int(flop_counter.get_total_flops()) + report = { + "status": "profiled", + "experiment_class": "engineering_profile_not_model_selection", + "official_validation_used": False, + "official_test_used": False, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], check=True, text=True, stdout=subprocess.PIPE, + ).stdout.strip(), + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": int(checkpoint["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "input": { + "batch_size": 1, + "clip_length": int(data["T"]), + "resolution_hw": list(data["resolution_hw"]), + "modalities": ["RGB", "Depth", "K"], + "precision": config["precision"], + }, + "parameters": parameter_counts(model), + "supported_operator_flops_per_clip": supported_flops, + "flops_scope": "PyTorch FlopCounterMode supported operators; forward only; unsupported custom operators are not estimated", + "latency": {**latency, "scope": "GPU model forward only; excludes data loading and host preprocessing"}, + "peak_allocated_vram_gib": peak_vram_gib, + "gpu": torch.cuda.get_device_name(device), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/rank_phase7_external.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/rank_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..0a13c2df62d7118453c90ff38151bfa4acf049f4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/rank_phase7_external.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Rank Phase 7 external checkpoints without frame-count weighting or H2O.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_p95_mm", +) + + +def dense_ranks(values: dict[str, float]) -> dict[str, int]: + ordered = sorted(set(values.values())) + return {name: ordered.index(value) + 1 for name, value in values.items()} + + +def evaluation_metrics(report: dict[str, Any]) -> dict[str, float]: + metrics = report["metrics"] + values = { + "absolute_mpjpe_mm": metrics["absolute_mpjpe_mm"]["mean"], + "root_relative_mpjpe_mm": metrics["root_relative_mpjpe_mm"]["mean"], + "fingertip_mpjpe_mm": metrics["fingertip_mpjpe_mm"]["mean"], + "translation_z_p95_mm": metrics["translation_z_mae_mm"]["p95"], + } + if any(value is None or not math.isfinite(float(value)) for value in values.values()): + raise ValueError("selection metrics must all be finite") + return {key: float(value) for key, value in values.items()} + + +def load_entries(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if manifest.get("selection_split") != "external_heldout_only": + raise ValueError("selection manifest must be external_heldout_only") + expected = set(manifest["datasets"]) + if expected != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("selection requires exactly HOT3D, HOI4D and ARCTIC") + entries: list[dict[str, Any]] = [] + pairs: set[tuple[str, str]] = set() + steps: set[int] = set() + for item in manifest["evaluations"]: + condition = str(item["condition"]) + dataset = str(item["dataset"]) + pair = (condition, dataset) + if pair in pairs: + raise ValueError(f"duplicate condition/dataset pair: {pair}") + pairs.add(pair) + if dataset not in expected: + raise ValueError(f"unexpected dataset: {dataset}") + path = Path(item["path"]).resolve() + report = json.loads(path.read_text(encoding="utf-8")) + cache_path = str(report["cache_manifest"]["path"]).lower() + if "h2o" in cache_path or report.get("h2o_training_data_used") is not False: + raise ValueError("external ranking refuses H2O data or training exposure") + if report.get("official_test_used") is not False: + raise ValueError("external ranking refuses official-test evaluation") + step = int(report["checkpoint_step"]) + steps.add(step) + entries.append({ + "condition": condition, + "dataset": dataset, + "input_mode": report["input_mode"], + "checkpoint_step": step, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "evaluation_path": str(path), + **evaluation_metrics(report), + }) + conditions = {entry["condition"] for entry in entries} + missing = {(condition, dataset) for condition in conditions for dataset in expected} - pairs + if missing: + raise ValueError(f"incomplete condition/dataset grid: {sorted(missing)}") + if len(steps) != 1: + raise ValueError(f"checkpoint steps are not matched: {sorted(steps)}") + return entries + + +def pareto_frontier(vectors: dict[str, list[float]]) -> list[str]: + frontier = [] + for condition, vector in vectors.items(): + dominated = any( + other != condition + and all(left <= right for left, right in zip(other_vector, vector)) + and any(left < right for left, right in zip(other_vector, vector)) + for other, other_vector in vectors.items() + ) + if not dominated: + frontier.append(condition) + return sorted(frontier) + + +def rank_entries(entries: list[dict[str, Any]]) -> dict[str, Any]: + steps = {int(entry["checkpoint_step"]) for entry in entries} + if len(steps) != 1: + raise ValueError(f"checkpoint steps are not matched: {sorted(steps)}") + datasets = sorted({entry["dataset"] for entry in entries}) + conditions = sorted({entry["condition"] for entry in entries}) + lookup = {(entry["condition"], entry["dataset"]): entry for entry in entries} + dataset_ranks: dict[str, dict[str, float]] = {} + vectors = {condition: [] for condition in conditions} + for dataset in datasets: + metric_ranks = { + metric: dense_ranks({ + condition: lookup[(condition, dataset)][metric] + for condition in conditions + }) + for metric in METRICS + } + dataset_ranks[dataset] = {} + for condition in conditions: + score = sum(metric_ranks[metric][condition] for metric in METRICS) / len(METRICS) + dataset_ranks[dataset][condition] = score + vectors[condition].extend( + lookup[(condition, dataset)][metric] for metric in METRICS + ) + macro = { + condition: sum(dataset_ranks[dataset][condition] for dataset in datasets) / len(datasets) + for condition in conditions + } + order = sorted(conditions, key=lambda condition: ( + macro[condition], + sum(lookup[(condition, dataset)]["absolute_mpjpe_mm"] for dataset in datasets), + sum(lookup[(condition, dataset)]["root_relative_mpjpe_mm"] for dataset in datasets), + condition, + )) + return { + "matched_checkpoint_step": entries[0]["checkpoint_step"], + "dataset_ranks": dataset_ranks, + "macro_mean_rank": macro, + "pareto_frontier": pareto_frontier(vectors), + "order": order, + "winner": order[0], + "entries": entries, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + result = { + "status": "ranked_external_only", + "selection_rule": "dataset metric ranks -> macro mean rank -> Absolute/root-relative tie-break", + "frame_count_weighted": False, + "h2o_used": False, + "official_test_used": False, + **rank_entries(load_entries(manifest)), + } + args.output_dir.mkdir(parents=True, exist_ok=False) + (args.output_dir / "ranking.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + with (args.output_dir / "ranking.csv").open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, + fieldnames=( + "condition", "macro_mean_rank", "on_pareto_frontier", + ), + lineterminator="\n", + ) + writer.writeheader() + for condition in result["order"]: + writer.writerow({ + "condition": condition, + "macro_mean_rank": result["macro_mean_rank"][condition], + "on_pareto_frontier": condition in result["pareto_frontier"], + }) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/recover_phase9_arctic_resolution_cache.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/recover_phase9_arctic_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f62598bfecb94ccf2457dade735b0bca9d13fc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/recover_phase9_arctic_resolution_cache.py @@ -0,0 +1,561 @@ +#!/usr/bin/env python3 +"""Restore the Stage 7 ARCTIC cache to the frozen 640 source-index set.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +from typing import Any + +import cv2 +import numpy as np + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + cache_step_complete, + sha256, + validate_plan_bindings, +) + + +IDENTITY_FIELDS = ( + "dataset_id", + "subject_id", + "physical_recording_id", + "source_group_key", + "camera_id", + "stream_id", + "headset_id", +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def load_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def indexed_rows( + rows: list[dict[str, Any]], label: str, +) -> tuple[list[int], dict[int, dict[str, Any]]]: + order = [int(row["source_clip_index"]) for row in rows] + if len(order) != len(set(order)): + duplicates = sorted({value for value in order if order.count(value) > 1}) + raise ValueError(f"{label} has duplicate source clip indices: {duplicates}") + return order, dict(zip(order, rows, strict=True)) + + +def compare_source_sets( + control_rows: list[dict[str, Any]], candidate_rows: list[dict[str, Any]], +) -> dict[str, Any]: + control_order, control = indexed_rows(control_rows, "control manifest") + candidate_order, candidate = indexed_rows(candidate_rows, "candidate manifest") + control_set, candidate_set = set(control), set(candidate) + missing = sorted(control_set - candidate_set) + extra = sorted(candidate_set - control_set) + drift = [] + for source_index in control_order: + if source_index not in candidate: + continue + differing = { + field: { + "control": control[source_index].get(field), + "candidate": candidate[source_index].get(field), + } + for field in IDENTITY_FIELDS + if control[source_index].get(field) != candidate[source_index].get(field) + } + if differing: + drift.append({"source_clip_index": source_index, "fields": differing}) + control_groups = {row["source_group_key"] for row in control_rows} + candidate_groups = { + candidate[index]["source_group_key"] + for index in control_order if index in candidate + } + return { + "control_count": len(control_order), + "candidate_count": len(candidate_order), + "control_unique_count": len(control_set), + "candidate_unique_count": len(candidate_set), + "missing_source_clip_indices": missing, + "extra_source_clip_indices": extra, + "identity_drift": drift, + "control_group_count": len(control_groups), + "candidate_accepted_group_count": len(candidate_groups), + "missing_groups": sorted(control_groups - candidate_groups), + "extra_groups": sorted(candidate_groups - control_groups), + } + + +def canonical_rows( + control_rows: list[dict[str, Any]], candidate_rows: list[dict[str, Any]], +) -> list[dict[str, Any]]: + comparison = compare_source_sets(control_rows, candidate_rows) + if ( + comparison["missing_source_clip_indices"] + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC source-index or group contract differs") + control_order, _ = indexed_rows(control_rows, "control manifest") + _, candidate = indexed_rows(candidate_rows, "candidate manifest") + return [candidate[index] for index in control_order] + + +def write_jsonl_atomic(path: Path, rows: list[dict[str, Any]]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + temporary.replace(path) + + +def preserve_file(source: Path, destination: Path) -> dict[str, Any]: + destination.parent.mkdir(parents=True, exist_ok=True) + source_hash = sha256(source) + if destination.exists(): + if not destination.is_file() or sha256(destination) != source_hash: + raise ValueError(f"preserved recovery evidence differs: {destination}") + else: + shutil.copy2(source, destination) + os.chmod(destination, 0o444) + return { + "path": str(destination.resolve()), + "sha256": source_hash, + "bytes": source.stat().st_size, + } + + +def quarantine_payload( + row: dict[str, Any], quarantine_root: Path, pass_id: str, +) -> dict[str, Any]: + source = Path(row["cache_path"]) + expected_hash = row["cache_sha256"] + if not source.is_file() or sha256(source) != expected_hash: + raise ValueError(f"extra ARCTIC payload differs: {source}") + destination = quarantine_root / pass_id / source.name + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + if not destination.is_file() or sha256(destination) != expected_hash: + raise ValueError(f"ARCTIC quarantine collision differs: {destination}") + source.unlink() + else: + source.replace(destination) + os.chmod(destination, 0o444) + return { + "source_clip_index": int(row["source_clip_index"]), + "path": str(destination.resolve()), + "sha256": expected_hash, + "bytes": destination.stat().st_size, + } + + +def payload_audit(rows: list[dict[str, Any]]) -> dict[str, Any]: + totals = { + "bytes": 0, + "clips_with_translation_supervision": 0, + "translation_valid_elements": 0, + "joint3d_valid_elements": 0, + "mano_annotation_valid_elements": 0, + } + probes: dict[int, dict[str, Any]] = {} + probe_positions = {0, len(rows) // 2, len(rows) - 1} + for position, row in enumerate(rows): + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"canonical ARCTIC payload differs: {path}") + with np.load(path, allow_pickle=False) as archive: + image_hw = [int(value) for value in archive["image_hw"].reshape(-1)] + if image_hw != [512, 896]: + raise ValueError(f"canonical ARCTIC resolution differs: {path}") + translation = np.asarray(archive["translation_valid"], dtype=bool) + joint3d = np.asarray(archive["joint3d_valid"], dtype=bool) + mano = np.asarray(archive["mano_annotation_valid"], dtype=bool) + if not translation.any(): + raise ValueError(f"canonical ARCTIC clip lacks supervision: {path}") + totals["bytes"] += path.stat().st_size + totals["clips_with_translation_supervision"] += 1 + totals["translation_valid_elements"] += int(translation.sum()) + totals["joint3d_valid_elements"] += int(joint3d.sum()) + totals["mano_annotation_valid_elements"] += int(mano.sum()) + if position in probe_positions: + probes[position] = { + "position": position, + "source_clip_index": int(row["source_clip_index"]), + "path": str(path.resolve()), + "sha256": row["cache_sha256"], + "image_hw": image_hw, + "frame_ids": archive["frame_id"].astype(int).tolist(), + "translation_valid_elements": int(translation.sum()), + "joint3d_valid_elements": int(joint3d.sum()), + } + return {**totals, "probes": [probes[key] for key in sorted(probes)]} + + +def source_extra_audit( + *, source_manifest: Path, control_report: dict[str, Any], + candidate_report: dict[str, Any], candidate_by_index: dict[int, dict[str, Any]], + extra_indices: list[int], mano_root: Path, +) -> list[dict[str, Any]]: + source_rows = [ + json.loads(line) + for line in source_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + control_skipped = {int(value) for value in control_report["skipped_no_supervision"]} + candidate_skipped = { + int(value) for value in candidate_report["skipped_no_supervision"] + } + low_dataset = ARCTICClipDataset( + source_manifest, mano_root, target_hw=(368, 640), + ) + high_dataset = ARCTICClipDataset( + source_manifest, mano_root, target_hw=(512, 896), + ) + results = [] + for source_index in extra_indices: + source = source_rows[source_index] + candidate = candidate_by_index[source_index] + images = [] + for value in source["image_paths"]: + path = Path(value) + image = cv2.imread(str(path), cv2.IMREAD_COLOR) + images.append({ + "path": str(path.resolve()), + "exists": path.is_file(), + "bytes": path.stat().st_size if path.is_file() else None, + "decoded_hw": list(image.shape[:2]) if image is not None else None, + }) + if any(not item["exists"] or item["decoded_hw"] != [600, 840] for item in images): + raise ValueError(f"ARCTIC extra source image differs: {source_index}") + mano_path, camera_path = Path(source["mano_path"]), Path(source["camera_path"]) + if not mano_path.is_file() or not camera_path.is_file(): + raise ValueError(f"ARCTIC extra annotation is missing: {source_index}") + mano_value = np.load(mano_path, allow_pickle=True).item() + camera_value = np.load(camera_path, allow_pickle=True).item() + if not {"left", "right"}.issubset(mano_value) or not { + "R_k_cam_np", "T_k_cam_np", "intrinsics", "dist8", + }.issubset(camera_value): + raise ValueError(f"ARCTIC extra annotation contract differs: {source_index}") + low = low_dataset[(source_index, 0)] + high = high_dataset[(source_index, 0)] + low_count = int(low["translation_valid"].sum()) + high_count = int(high["translation_valid"].sum()) + if ( + source_index not in control_skipped + or source_index in candidate_skipped + or low_count != 0 + or high_count <= 0 + or source["group_key"] != candidate["source_group_key"] + or source["physical_recording_id"] != candidate["physical_recording_id"] + ): + raise ValueError(f"ARCTIC extra acceptance reason differs: {source_index}") + results.append({ + "source_clip_index": source_index, + "classification": "resolution_dependent_supervision_boundary", + "control_640_reason": "skipped_no_supervision", + "control_640_translation_valid_elements": low_count, + "candidate_896_translation_valid_elements": high_count, + "subject_id": source["subject_id"], + "physical_recording_id": source["physical_recording_id"], + "source_group_key": source["group_key"], + "frame_ids_1based": source["frame_ids_1based"], + "images": images, + "mano_annotation": { + "path": str(mano_path.resolve()), "bytes": mano_path.stat().st_size, + "sides": sorted(mano_value), + }, + "camera_annotation": { + "path": str(camera_path.resolve()), "bytes": camera_path.stat().st_size, + "required_fields_present": True, + }, + }) + return results + + +def validate_recovery_plan(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("status") != "frozen" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("ARCTIC recovery plan isolation differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"ARCTIC recovery binding differs: {path}") + execution_path = Path(plan["execution_plan"]["path"]) + execution = json.loads(execution_path.read_text(encoding="utf-8")) + if sha256(execution_path) != plan["execution_plan"]["sha256"]: + raise ValueError("ARCTIC execution plan binding differs") + validate_plan_bindings(execution) + return execution + + +def canonicalize_pass( + *, plan_path: Path, plan: dict[str, Any], pass_id: str, +) -> dict[str, Any]: + manifest_path = Path(plan["candidate_manifest"]) + report_path = Path(plan["candidate_report"]) + control_manifest_path = Path(plan["control_manifest"]["path"]) + control_report_path = Path(plan["control_report"]["path"]) + evidence_root = Path(plan["evidence_root"]) / pass_id + raw_manifest = preserve_file(manifest_path, evidence_root / "raw_cache_manifest.jsonl") + raw_report = preserve_file(report_path, evidence_root / "raw_cache_report.json") + control_rows = load_jsonl(control_manifest_path) + candidate_rows = load_jsonl(manifest_path) + control_report = json.loads(control_report_path.read_text(encoding="utf-8")) + candidate_report = json.loads(report_path.read_text(encoding="utf-8")) + comparison = compare_source_sets(control_rows, candidate_rows) + expected_extra = plan["expected_extra_source_clip_indices"] + if ( + comparison["control_count"] != plan["expected_clips"] + or comparison["candidate_count"] != plan["raw_candidate_clips"] + or comparison["missing_source_clip_indices"] + or comparison["extra_source_clip_indices"] != expected_extra + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC cache mismatch is outside the frozen recovery scope") + _, candidate_by_index = indexed_rows(candidate_rows, "candidate manifest") + extras = source_extra_audit( + source_manifest=Path(plan["source_manifest"]["path"]), + control_report=control_report, + candidate_report=candidate_report, + candidate_by_index=candidate_by_index, + extra_indices=expected_extra, + mano_root=Path(plan["mano_root"]), + ) + quarantined = [ + quarantine_payload(candidate_by_index[index], Path(plan["quarantine_root"]), pass_id) + for index in expected_extra + ] + accepted = canonical_rows(control_rows, candidate_rows) + coverage = payload_audit(accepted) + if coverage["clips_with_translation_supervision"] != plan["expected_clips"]: + raise ValueError("ARCTIC canonical supervision coverage differs") + write_jsonl_atomic(manifest_path, accepted) + manifest_hash = sha256(manifest_path) + canonical_report = dict(candidate_report) + canonical_report.update({ + "status": "complete", + "cached_clips": plan["expected_clips"], + "cached_valid_clips": plan["expected_clips"], + "valid_candidate_files": plan["expected_clips"], + "recordings": comparison["control_group_count"], + "bytes": coverage["bytes"], + "cache_manifest": { + "path": str(manifest_path.resolve()), "sha256": manifest_hash, + }, + "canonical_filter": { + "schema_version": "phase9_arctic_resolution_canonical_filter_v1", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "control_manifest": plan["control_manifest"], + "raw_manifest": raw_manifest, + "raw_report": raw_report, + "excluded_resolution_dependent_source_indices": expected_extra, + "quarantined_payloads": quarantined, + "ordering": "frozen_640_control_source_index_order", + "logical_clip_set_changed_from_control": False, + }, + "supervision_coverage": coverage, + "h2o_official_validation_used": False, + "official_test_used": False, + }) + atomic_json(report_path, canonical_report) + return { + "pass_id": pass_id, + "raw_manifest": raw_manifest, + "raw_report": raw_report, + "comparison": comparison, + "extra_source_audit": extras, + "quarantined_payloads": quarantined, + "canonical_manifest": { + "path": str(manifest_path.resolve()), "sha256": manifest_hash, + "rows": len(accepted), + }, + "canonical_report": { + "path": str(report_path.resolve()), "sha256": sha256(report_path), + }, + "supervision_coverage": coverage, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--audit-only", action="store_true") + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + execution = validate_recovery_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + workers = {item["id"]: item for item in execution["workers"]} + worker = workers["arctic"] + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("ARCTIC recovery state path differs from execution plan") + initial_step, resume_step = worker["steps"][:2] + if args.audit_only: + control_rows = load_jsonl(Path(plan["control_manifest"]["path"])) + candidate_rows = load_jsonl(Path(plan["candidate_manifest"])) + comparison = compare_source_sets(control_rows, candidate_rows) + _, candidate_by_index = indexed_rows(candidate_rows, "candidate manifest") + control_report = json.loads( + Path(plan["control_report"]["path"]).read_text(encoding="utf-8") + ) + candidate_report = json.loads( + Path(plan["candidate_report"]).read_text(encoding="utf-8") + ) + expected_extra = plan["expected_extra_source_clip_indices"] + if ( + comparison["control_count"] != plan["expected_clips"] + or comparison["candidate_count"] != plan["raw_candidate_clips"] + or comparison["missing_source_clip_indices"] + or comparison["extra_source_clip_indices"] != expected_extra + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC preflight mismatch is outside recovery scope") + result = { + "schema_version": "phase9_arctic_resolution_mismatch_audit_v1", + "status": "complete", + "created_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "control_manifest": plan["control_manifest"], + "candidate_manifest": { + "path": str(Path(plan["candidate_manifest"]).resolve()), + "sha256": sha256(plan["candidate_manifest"]), + }, + "candidate_report": { + "path": str(Path(plan["candidate_report"]).resolve()), + "sha256": sha256(plan["candidate_report"]), + }, + "comparison": comparison, + "extra_source_audit": source_extra_audit( + source_manifest=Path(plan["source_manifest"]["path"]), + control_report=control_report, + candidate_report=candidate_report, + candidate_by_index=candidate_by_index, + extra_indices=expected_extra, + mano_root=Path(plan["mano_root"]), + ), + "mutation_performed": False, + "expected_clips_changed": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(Path(plan["preflight_audit_output"]), result) + print(json.dumps(result, indent=2)) + return + lock_path = Path(f"{args.state}.lock") + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state = json.loads(args.state.read_text(encoding="utf-8")) + if ( + state.get("worker") != "arctic" + or state.get("plan_sha256") != plan["execution_plan"]["sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + parser.error("ARCTIC failed state binding differs") + existing = state.get("canonical_set_recovery") + if existing and existing.get("status") == "complete": + if not cache_step_complete(initial_step, False) or not cache_step_complete( + resume_step, True + ): + parser.error("completed ARCTIC recovery outputs differ") + print(json.dumps(state, indent=2)) + return + if state.get("status") != "failed_resumable": + parser.error("ARCTIC recovery requires failed_resumable input state") + result: dict[str, Any] = { + "schema_version": "phase9_arctic_resolution_canonical_recovery_v1", + "status": "running", "started_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "failure_state_sha256": sha256(args.state), + "passes": [], "official_test_used": False, + "h2o_official_validation_used": False, + } + state["canonical_set_recovery"] = result + atomic_json(args.state, state) + initial = canonicalize_pass(plan_path=args.plan, plan=plan, pass_id="initial") + if not cache_step_complete(initial_step, False): + raise ValueError("initial ARCTIC canonical cache validation failed") + result["passes"].append(initial) + if initial_step["id"] not in state["completed_steps"]: + state["completed_steps"].append(initial_step["id"]) + command = list(resume_step["resume_command"]) + log_path = Path(plan["resume_log"]) + attempt = { + "step": resume_step["id"], "kind": "cache", + "recovery": "canonical_set_exact_resume_verify", + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_step"] = resume_step["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + completed = subprocess.run( + command, cwd=Path.cwd(), env=dict(os.environ, PYTHONPATH=str(Path.cwd())), + stdout=log, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = completed.returncode + if completed.returncode: + state["status"] = "failed_resumable" + result["status"] = "failed_resume_command" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(completed.returncode) + resumed = canonicalize_pass( + plan_path=args.plan, plan=plan, pass_id="resume_verify", + ) + result["passes"].append(resumed) + if not cache_step_complete(initial_step, False) or not cache_step_complete( + resume_step, True + ): + raise ValueError("resumed ARCTIC canonical cache validation failed") + if resume_step["id"] not in state["completed_steps"]: + state["completed_steps"].append(resume_step["id"]) + result["status"] = "complete" + result["completed_utc"] = utc_now() + result["canonical_manifest_sha256"] = sha256(plan["candidate_manifest"]) + result["canonical_report_sha256"] = sha256(plan["candidate_report"]) + atomic_json(Path(plan["audit_output"]), result) + result["audit_output"] = { + "path": str(Path(plan["audit_output"]).resolve()), + "sha256": sha256(plan["audit_output"]), + } + state["status"] = "waiting_for_remaining_steps" + state["updated_utc"] = utc_now() + state["failure_evidence_preserved"] = state.get("failure") + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_best_worst_video_cases.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_best_worst_video_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..04f5d1c2379da5af6f1d151193c5df89ce67d78b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_best_worst_video_cases.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +"""Render ranked full-take videos for the frozen Phase 3 candidate.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + MeshLayer, + project_mesh_layers, + render_mesh_layers, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +LEFT_COLOR_RGB = (40, 100, 235) +RIGHT_COLOR_RGB = (235, 55, 55) +MESH_ALPHA = 0.55 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def _mean(rows: list[dict[str, str]], field: str) -> float: + values = np.asarray([float(row[field]) for row in rows], dtype=np.float64) + if not np.isfinite(values).all(): + raise ValueError(f"non-finite {field} in sequence ranking rows") + return float(values.mean()) + + +def rank_video_sequences( + rows: list[dict[str, str]], *, count: int, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Rank validation takes by all annotation-valid hand-frame errors.""" + + grouped: dict[str, list[dict[str, str]]] = defaultdict(list) + for row in rows: + grouped[row["take"]].append(row) + + candidates = [] + for take, take_rows in grouped.items(): + valid_rows = [row for row in take_rows if int(row["annotation_valid"]) == 1] + if not valid_rows: + continue + observed = { + (int(row["frame_id"]), row["side"]) + for row in take_rows + } + if len(observed) != len(take_rows): + raise ValueError(f"duplicate evaluated hand-frame rows in {take}") + errors = np.asarray( + [float(row["absolute_mpjpe_mm"]) for row in valid_rows], + dtype=np.float64, + ) + if not np.isfinite(errors).all(): + raise ValueError(f"non-finite ranking errors in {take}") + first = valid_rows[0] + evaluated_frame_ids = sorted({int(row["frame_id"]) for row in take_rows}) + annotated_frame_ids = sorted({int(row["frame_id"]) for row in valid_rows}) + candidates.append({ + "take": take, + "subject": first["subject"], + "sequence": first["sequence"], + "evaluation_frame_ids": evaluated_frame_ids, + "evaluated_frame_count": len(evaluated_frame_ids), + "annotated_frame_count": len(annotated_frame_ids), + "annotated_hand_frames": len(valid_rows), + "absolute_mpjpe_mm_mean": float(errors.mean()), + "absolute_mpjpe_mm_p50": float(np.median(errors)), + "absolute_mpjpe_mm_max": float(errors.max()), + "root_relative_mpjpe_mm_mean": _mean(valid_rows, "root_relative_mpjpe_mm"), + "direct_2d_error_px_mean": _mean(valid_rows, "direct_2d_error_px"), + "translation_x_mae_mm_mean": _mean(valid_rows, "translation_x_mae_mm"), + "translation_y_mae_mm_mean": _mean(valid_rows, "translation_y_mae_mm"), + "translation_z_mae_mm_mean": _mean(valid_rows, "translation_z_mae_mm"), + }) + if len(candidates) < count * 2: + raise ValueError( + f"need at least {count * 2} validation takes, found {len(candidates)}" + ) + best = sorted( + candidates, + key=lambda row: (row["absolute_mpjpe_mm_mean"], row["take"]), + )[:count] + failure = sorted( + candidates, + key=lambda row: (-row["absolute_mpjpe_mm_mean"], row["take"]), + )[:count] + if {row["take"] for row in best} & {row["take"] for row in failure}: + raise AssertionError("best and failure sequence selections overlap") + return best, failure + + +def source_frame_ids(data_root: Path, take: str) -> list[int]: + frame_ids = sorted( + int(path.stem) for path in (data_root / take / "rgb").glob("*.png") + ) + if not frame_ids: + raise ValueError(f"no raw RGB frames in {data_root / take}") + expected = list(range(frame_ids[0], frame_ids[-1] + 1)) + if frame_ids != expected: + raise ValueError(f"raw RGB frames are not contiguous in {data_root / take}") + return frame_ids + + +def case_directory_name(rank: int, case: dict[str, Any]) -> str: + sequence = str(case["sequence"]).replace("/", "_") + first_frame, last_frame = case["frame_ids"][0], case["frame_ids"][-1] + return ( + f"{rank:02d}_{case['subject']}_{sequence}_" + f"frames_{first_frame:06d}_{last_frame:06d}" + ) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def add_header(image_rgb: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image_rgb.copy() + height = 8 + 22 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (8, 20 + 22 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.55, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def open_writer(path: Path, fps: float, frame_hw: tuple[int, int]) -> cv2.VideoWriter: + height, width = frame_hw + writer = cv2.VideoWriter( + str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height), + ) + if not writer.isOpened(): + raise RuntimeError(f"failed to open video writer: {path}") + return writer + + +def frame_error_lookup( + rows: list[dict[str, str]], take: str, +) -> dict[int, float]: + values: dict[int, list[float]] = defaultdict(list) + for row in rows: + if row["take"] != take or int(row["annotation_valid"]) != 1: + continue + values[int(row["frame_id"])].append(float(row["absolute_mpjpe_mm"])) + return {frame_id: float(np.mean(errors)) for frame_id, errors in values.items()} + + +def render_case( + *, + case: dict[str, Any], + rank: int, + category: str, + output_dir: Path, + dataset: H2OCam4Dataset, + clip_indices: list[int], + metric_rows: list[dict[str, str]], + data_root: Path, + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + faces: tuple[np.ndarray, np.ndarray], + fps: float, + model_t: int, +) -> dict[str, Any]: + output_dir.mkdir(parents=True, exist_ok=False) + take_dir = data_root / str(case["take"]) + raw_K, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + original_path = output_dir / "original_rgb.mp4" + overlay_path = output_dir / "predicted_mano_overlay.mp4" + comparison_path = output_dir / "side_by_side.mp4" + original_writer = open_writer(original_path, fps, source_hw) + overlay_writer = open_writer(overlay_path, fps, source_hw) + comparison_writer = open_writer( + comparison_path, fps, (source_hw[0], source_hw[1] * 2), + ) + errors = frame_error_lookup(metric_rows, str(case["take"])) + expected_frame_ids = list(case["frame_ids"]) + preview = None + rendered_frame_ids: list[int] = [] + try: + for clip_index in clip_indices: + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + clip_frame_ids = [int(value) for value in sample["frame_id"].tolist()] + for time_index, frame_id in enumerate(clip_frame_ids): + raw_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), + cv2.IMREAD_COLOR, + ) + if raw_bgr is None or raw_bgr.shape[:2] != source_hw: + raise RuntimeError( + f"raw RGB decode/shape failure: {take_dir}/{frame_id}" + ) + raw_rgb = cv2.cvtColor(raw_bgr, cv2.COLOR_BGR2RGB) + layers = [ + MeshLayer( + prediction["vertices_camera"][0, time_index, hand] + .float().cpu().numpy(), + faces[hand], + LEFT_COLOR_RGB if hand == 0 else RIGHT_COLOR_RGB, + MESH_ALPHA, + ) + for hand in range(2) + ] + rendered = render_mesh_layers( + raw_rgb, project_mesh_layers(layers, raw_K), + ) + frame_error = errors.get(frame_id) + error_label = ( + f"{frame_error:.2f} mm" + if frame_error is not None else "n/a (not evaluated)" + ) + global_index = len(rendered_frame_ids) + rendered = add_header(rendered, ( + f"{category} #{rank} | predicted MANO | left=BLUE right=RED alpha={MESH_ALPHA:.2f}", + f"{case['subject']}/{case['sequence']} | frame={frame_id} ({global_index + 1}/{len(expected_frame_ids)}) | take MPJPE={case['absolute_mpjpe_mm_mean']:.2f} mm | frame={error_label}", + )) + original_panel = add_header(raw_rgb, ("Original cam4 RGB",)) + comparison = np.concatenate((original_panel, rendered), axis=1) + + original_writer.write(raw_bgr) + overlay_writer.write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + comparison_writer.write(cv2.cvtColor(comparison, cv2.COLOR_RGB2BGR)) + rendered_frame_ids.append(frame_id) + if global_index == len(expected_frame_ids) // 2: + preview = comparison + del prediction, batch + finally: + original_writer.release() + overlay_writer.release() + comparison_writer.release() + + if rendered_frame_ids != expected_frame_ids: + raise RuntimeError( + f"rendered frame sequence mismatch for {case['take']}: " + f"{len(rendered_frame_ids)} != {len(expected_frame_ids)}" + ) + if preview is None: + raise RuntimeError(f"no preview generated for {case['take']}") + preview_path = output_dir / "preview.png" + cv2.imwrite(str(preview_path), cv2.cvtColor(preview, cv2.COLOR_RGB2BGR)) + record = { + **case, + "rank": rank, + "category": category, + "selection_requirement": "official-validation take with finite annotation-valid metrics", + "ranking_metric": "mean absolute MPJPE over all annotation-valid hand-frames in the take", + "inference_policy": f"contiguous full raw take, non-overlapping T={model_t} chunks with final partial chunk", + "colors_rgb": { + "left": list(LEFT_COLOR_RGB), "right": list(RIGHT_COLOR_RGB), + }, + "mesh_alpha": MESH_ALPHA, + "visualization_fps": fps, + "duration_seconds": len(expected_frame_ids) / fps, + "videos": { + "original": str(original_path.resolve()), + "predicted_mano_overlay": str(overlay_path.resolve()), + "side_by_side": str(comparison_path.resolve()), + }, + "preview": str(preview_path.resolve()), + } + (output_dir / "case.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + record["preview_rgb"] = preview + return record + + +def save_contact_sheet(output: Path, records: list[dict[str, Any]]) -> None: + panels = [] + for record in records: + preview = record["preview_rgb"] + panel = cv2.resize(preview, (384, 216), interpolation=cv2.INTER_AREA) + panel = add_header(panel, ( + f"{record['category']} #{record['rank']} | {record['absolute_mpjpe_mm_mean']:.2f} mm | {len(record['frame_ids'])} frames", + )) + panels.append(panel) + rows = [np.concatenate(panels[:5], axis=1), np.concatenate(panels[5:], axis=1)] + sheet = np.concatenate(rows, axis=0) + cv2.imwrite(str(output), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR)) + + +def save_case_summary(output: Path, records: list[dict[str, Any]]) -> None: + lines = [ + "# Ranked Long-Sequence Video Summary", + "", + "Takes are ranked by mean camera-space absolute MPJPE over every", + "annotation-valid official-validation hand-frame. Videos render each full raw", + "take continuously; frames outside the evaluated annotation runs do not affect", + "the ranking. All metric values below use only valid evaluation rows.", + "", + ] + for category, title in (("best", "Best Sequences"), ("failure", "Worst Sequences")): + lines.extend([ + f"## {title}", + "", + "| Rank | Take | Raw frames | Seconds | Evaluated frames | Abs MPJPE | Root-relative | Direct 2D | z MAE |", + "|---:|---|---:|---:|---:|---:|---:|---:|---:|", + ]) + for record in records: + if record["category"] != category: + continue + lines.append( + f"| {record['rank']} | `{record['take']}` | {len(record['frame_ids'])} | " + f"{record['duration_seconds']:.2f} | {record['evaluated_frame_count']} | " + f"{record['absolute_mpjpe_mm_mean']:.2f} mm | " + f"{record['root_relative_mpjpe_mm_mean']:.2f} mm | " + f"{record['direct_2d_error_px_mean']:.2f} px | " + f"{record['translation_z_mae_mm_mean']:.2f} mm |" + ) + lines.append("") + lines.extend([ + "Left MANO is blue, right MANO is red, and mesh alpha is 0.55. The", + "prediction-only overlay uses raw 1280x720 cam4 RGB and the original camera", + "intrinsics. GT meshes are not rendered. Official test was not used.", + "", + ]) + output.write_text("\n".join(lines), encoding="utf-8") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--evaluation-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--count", type=int, default=5) + parser.add_argument("--fps", type=float, default=30.0) + args = parser.parse_args() + if args.count != 5: + raise ValueError("the showcase requires exactly five best and five failure cases") + if args.fps <= 0: + raise ValueError("fps must be positive") + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError(f"refusing to overwrite non-empty output: {args.output_dir}") + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + metric_path = args.evaluation_dir / "per_hand_frame_metrics.csv" + report_path = args.evaluation_dir / "evaluation.json" + metric_rows = read_csv(metric_path) + report = json.loads(report_path.read_text(encoding="utf-8")) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + if ( + report.get("split_role") != "official_validation" + or report.get("official_test_used") is not False + or report.get("checkpoint", {}).get("sha256") != checkpoint_hash + or report.get("manifest", {}).get("sha256") != manifest_hash + ): + raise ValueError("evaluation/checkpoint/manifest provenance mismatch") + + best, failure = rank_video_sequences(metric_rows, count=args.count) + selected = best + failure + for case in selected: + case["frame_ids"] = source_frame_ids(args.data_root, str(case["take"])) + case["raw_frame_count"] = len(case["frame_ids"]) + + render_manifest_path = args.output_dir / "render_input_manifest.jsonl" + render_manifest_path.write_text( + "".join( + json.dumps({"take": case["take"], "frame_ids": case["frame_ids"]}) + "\n" + for case in selected + ), + encoding="utf-8", + ) + model_t = int(data_config["T"]) + dataset = H2OCam4Dataset( + args.data_root, render_manifest_path, tuple(data_config["resolution_hw"]), + (model_t,), (int(data_config["stride"]),), + ) + clip_indices_by_take: dict[str, list[int]] = defaultdict(list) + for clip_index, clip in enumerate(dataset.clips): + clip_indices_by_take[clip.take].append(clip_index) + + device = torch.device(f"cuda:{args.gpu}") + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint( + args.checkpoint, model, optimizer=None, map_location=device, + ) + if int(checkpoint_state["step"]) != int(report["checkpoint"]["step"]): + raise ValueError("checkpoint step differs from source evaluation") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + faces = tuple(layer.th_faces.cpu().numpy() for layer in model.mano_layer.layers) + + rendered_records = [] + for category, cases, parent_name in ( + ("best", best, "best_cases"), + ("failure", failure, "failure_cases"), + ): + parent = args.output_dir / parent_name + parent.mkdir(exist_ok=False) + for rank, case in enumerate(cases, start=1): + print( + f"rendering {category} #{rank}: {case['take']} " + f"({len(case['frame_ids'])} frames)", + flush=True, + ) + record = render_case( + case=case, rank=rank, category=category, + output_dir=parent / case_directory_name(rank, case), + dataset=dataset, + clip_indices=clip_indices_by_take[str(case["take"])], + metric_rows=metric_rows, data_root=args.data_root.resolve(), + model=model, device=device, dtype=dtype, faces=faces, + fps=args.fps, model_t=model_t, + ) + rendered_records.append(record) + + save_contact_sheet(args.output_dir / "contact_sheet.png", rendered_records) + save_case_summary(args.output_dir / "CASE_SUMMARY.md", rendered_records) + serializable_records = [ + {key: value for key, value in record.items() if key != "preview_rgb"} + for record in rendered_records + ] + manifest = { + "status": "complete", + "official_test_used": False, + "source_split": "official_validation", + "selection_policy": ( + "lowest/highest take mean absolute MPJPE over all annotation-valid " + "official-validation hand-frames" + ), + "render_policy": ( + "all contiguous raw frames in each selected take, including frames " + "outside evaluated annotation runs" + ), + "config": str(args.config.resolve()), + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": checkpoint_hash, + "step": int(checkpoint_state["step"]), + }, + "source_manifest": { + "path": str(args.manifest.resolve()), + "sha256": manifest_hash, + }, + "source_evaluation": str(args.evaluation_dir.resolve()), + "render_input_manifest": str(render_manifest_path.resolve()), + "model_input_resolution_hw": list(data_config["resolution_hw"]), + "model_temporal_window": model_t, + "render_space": "raw cam4 RGB resolution with original camera intrinsics", + "videos_are_prediction_only": True, + "visualization_fps": args.fps, + "cases": serializable_records, + } + (args.output_dir / "selection_manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8", + ) + readme = f"""# Best Model Long-Sequence Video Cases + +This directory uses the Phase 3 seed-20260718 step-140k tail-best checkpoint. +The five best and five worst cases are distinct official-validation takes, +ranked by mean camera-space absolute MPJPE across all annotation-valid +hand-frames in each take. + +Each case contains: + +- `original_rgb.mp4`: untouched full raw cam4 RGB sequence; +- `predicted_mano_overlay.mp4`: prediction-only MANO, left blue and right red; +- `side_by_side.mp4`: original and overlay comparison; +- `preview.png` and `case.json`. + +All raw frames from the selected take are rendered continuously, including +frames outside the evaluated annotation runs. Those frames display `n/a` for +the frame metric and do not affect ranking. Inference uses non-overlapping +T={model_t} chunks, matching the formal evaluator, with a final partial chunk. + +Playback is {args.fps:g} fps, matching the H2O capture rate. Mesh alpha is +0.55. Camera-space vertices are projected onto raw 1280x720 RGB with original +cam4 intrinsics. GT meshes are not rendered. Official test was not used. + +See `CASE_SUMMARY.md` for the ranking and metric breakdown, `contact_sheet.png` +for the visual index, and `selection_manifest.json` for full provenance. +""" + (args.output_dir / "README.md").write_text(readme, encoding="utf-8") + print(json.dumps({ + "status": "complete", + "output_dir": str(args.output_dir.resolve()), + "fps": args.fps, + "best_take_mpjpe_mm": [row["absolute_mpjpe_mm_mean"] for row in best], + "failure_take_mpjpe_mm": [ + row["absolute_mpjpe_mm_mean"] for row in failure + ], + "frame_counts": [len(row["frame_ids"]) for row in selected], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_phase4_filtered_cases.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_phase4_filtered_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea9f5f1022a50e8c55ff0fe3b30b1d019fb4375 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_phase4_filtered_cases.py @@ -0,0 +1,517 @@ +#!/usr/bin/env python3 +"""Render deterministic raw/filtered failure videos from audited jitter caches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + OPENPOSE_HAND_EDGES, + draw_skeleton, + project_camera_points, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models.mano import ManoCameraLayer +try: + from scripts.evaluate_phase4_jitter import ( + condition_grid, + filtered_parameters, + load_take, + rebuild_geometry, + ) +except ModuleNotFoundError: + from evaluate_phase4_jitter import ( # type: ignore[no-redef] + condition_grid, + filtered_parameters, + load_take, + rebuild_geometry, + ) + + +RAW_COLOR = (245, 145, 45) +FILTERED_COLOR = (35, 210, 235) +GT_COLOR = (70, 220, 105) +AXIS_COLORS = ((235, 80, 80), (70, 190, 90), (80, 130, 240)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +class FFmpegWriter: + def __init__(self, path: Path, fps: float, frame_hw: tuple[int, int]) -> None: + self.path = path + self.frame_hw = frame_hw + self.frames = 0 + path.parent.mkdir(parents=True, exist_ok=True) + self.temporary = path.with_name(f".{path.stem}.tmp-{os.getpid()}.mp4") + height, width = frame_hw + self.process = subprocess.Popen([ + "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-y", + "-f", "rawvideo", "-pix_fmt", "bgr24", "-s:v", f"{width}x{height}", + "-r", f"{fps:g}", "-i", "pipe:0", "-an", "-c:v", "libx264", + "-preset", "fast", "-crf", "18", "-pix_fmt", "yuv420p", + "-movflags", "+faststart", str(self.temporary), + ], stdin=subprocess.PIPE, stderr=subprocess.PIPE) + + def write(self, frame_bgr: np.ndarray) -> None: + if frame_bgr.shape != (*self.frame_hw, 3) or frame_bgr.dtype != np.uint8: + raise ValueError("video frame shape/dtype mismatch") + if self.process.stdin is None: + raise RuntimeError("ffmpeg stdin unavailable") + self.process.stdin.write(np.ascontiguousarray(frame_bgr).tobytes()) + self.frames += 1 + + def close(self) -> None: + assert self.process.stdin is not None + self.process.stdin.close() + stderr = self.process.stderr.read().decode("utf-8", errors="replace") if self.process.stderr else "" + return_code = self.process.wait() + if return_code: + self.temporary.unlink(missing_ok=True) + raise RuntimeError(f"ffmpeg failed: {stderr.strip()}") + os.replace(self.temporary, self.path) + + def abort(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + if self.process.poll() is None: + self.process.terminate() + self.process.wait(timeout=10) + self.temporary.unlink(missing_ok=True) + + +def add_header(image: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image.copy() + height = 8 + 24 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (9, 21 + 24 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.58, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def ranked_failure_takes( + cache_manifest: dict[str, Any], count: int, +) -> list[dict[str, object]]: + records = [] + for record in cache_manifest["takes"]: + arrays = load_take(Path(record["path"])) + error = np.linalg.norm( + arrays["pred_joints_camera"] - arrays["target_joints_camera"], axis=-1, + ) * 1000.0 + valid = arrays["joint_element_valid"].astype(bool) + values = error[valid] + if not len(values) or not np.isfinite(values).all(): + continue + records.append({ + "take": str(arrays["take"]), "path": record["path"], + "frames": len(arrays["frame_id"]), + "raw_absolute_mpjpe_mm": float(values.mean()), + }) + if len(records) < count: + raise ValueError("not enough annotated takes for filtered video cases") + return sorted( + records, key=lambda row: (-float(row["raw_absolute_mpjpe_mm"]), str(row["take"])), + )[:count] + + +def project_joints(joints: np.ndarray, K: np.ndarray) -> np.ndarray: + pixels, z = project_camera_points(joints, K) + pixels[z <= 1e-8] = np.nan + return pixels + + +def overlay_joints( + image_rgb: np.ndarray, + joints: np.ndarray, + K: np.ndarray, + color: tuple[int, int, int], + valid_hands: np.ndarray | None = None, +) -> np.ndarray: + output = image_rgb + for hand in range(2): + if valid_hands is not None and not bool(valid_hands[hand]): + continue + output = draw_skeleton( + output, project_joints(joints[hand], K), color, + marker="ring" if color == GT_COLOR else "circle", + ) + return output + + +def side_limits(*joint_sequences: np.ndarray) -> tuple[float, float, float, float]: + points = np.concatenate([values.reshape(-1, 3) for values in joint_sequences]) + finite = points[np.isfinite(points).all(axis=-1)] + if not len(finite): + return -0.4, 0.4, 0.2, 0.9 + x0, x1 = np.percentile(finite[:, 0], (1, 99)) + z0, z1 = np.percentile(finite[:, 2], (1, 99)) + x_margin = max(0.03, 0.1 * (x1 - x0)) + z_margin = max(0.03, 0.1 * (z1 - z0)) + return x0 - x_margin, x1 + x_margin, z0 - z_margin, z1 + z_margin + + +def camera_side_panel( + raw_joints: np.ndarray, + filtered_joints: np.ndarray, + target_joints: np.ndarray, + valid_hands: np.ndarray, + limits: tuple[float, float, float, float], + frame_id: int, + size: tuple[int, int] = (540, 960), +) -> np.ndarray: + height, width = size + panel = np.full((height, width, 3), 248, dtype=np.uint8) + x0, x1, z0, z1 = limits + + def point(value: np.ndarray) -> tuple[int, int]: + x = int(round(50 + (value[0] - x0) / max(x1 - x0, 1e-6) * (width - 100))) + y = int(round(height - 45 - (value[2] - z0) / max(z1 - z0, 1e-6) * (height - 100))) + return x, y + + cv2.rectangle(panel, (50, 45), (width - 50, height - 45), (50, 50, 50), 1) + for joints, color, valid_only in ( + (target_joints, GT_COLOR, True), + (raw_joints, RAW_COLOR, False), + (filtered_joints, FILTERED_COLOR, False), + ): + for hand in range(2): + if valid_only and not valid_hands[hand]: + continue + finite = np.isfinite(joints[hand]).all(axis=-1) + for start, end in OPENPOSE_HAND_EDGES: + if finite[start] and finite[end]: + cv2.line(panel, point(joints[hand, start]), point(joints[hand, end]), color, 2, cv2.LINE_AA) + for joint_index in np.flatnonzero(finite): + cv2.circle(panel, point(joints[hand, joint_index]), 2, color, -1, cv2.LINE_AA) + panel = add_header(panel, ( + f"Camera side view x/z | frame={frame_id}", + "GT=green raw=orange filtered=cyan", + )) + return panel + + +def trace_panel( + raw_error: np.ndarray, + filtered_error: np.ndarray, + valid: np.ndarray, + current: int, + side: str, + size: tuple[int, int] = (540, 1920), +) -> np.ndarray: + height, width = size + panel = np.full((height, width, 3), 250, dtype=np.uint8) + finite_values = np.concatenate((raw_error[valid], filtered_error[valid])) + limit = max(10.0, float(np.percentile(np.abs(finite_values), 99))) if finite_values.size else 10.0 + left, right = 70, width - 35 + band_height = (height - 70) // 3 + for axis, axis_name in enumerate("xyz"): + top = 48 + axis * band_height + bottom = top + band_height - 12 + middle = (top + bottom) // 2 + cv2.line(panel, (left, middle), (right, middle), (150, 150, 150), 1) + cv2.putText(panel, f"{axis_name} +/-{limit:.0f}mm", (8, top + 18), cv2.FONT_HERSHEY_SIMPLEX, 0.48, AXIS_COLORS[axis], 1, cv2.LINE_AA) + + def points(values: np.ndarray) -> list[np.ndarray]: + output = [] + segment = [] + for index, value in enumerate(values[:, axis]): + if valid[index] and np.isfinite(value): + x = int(round(left + index / max(len(values) - 1, 1) * (right - left))) + y = int(round(middle - np.clip(value / limit, -1, 1) * (bottom - top) / 2)) + segment.append((x, y)) + elif segment: + output.append(np.asarray(segment, dtype=np.int32)) + segment = [] + if segment: + output.append(np.asarray(segment, dtype=np.int32)) + return output + + for segment in points(raw_error): + if len(segment) >= 2: + cv2.polylines(panel, [segment], False, (115, 115, 115), 1, cv2.LINE_AA) + for segment in points(filtered_error): + if len(segment) >= 2: + cv2.polylines(panel, [segment], False, AXIS_COLORS[axis], 2, cv2.LINE_AA) + current_x = int(round(left + current / max(len(raw_error) - 1, 1) * (right - left))) + cv2.line(panel, (current_x, 42), (current_x, height - 20), (20, 20, 20), 1) + return add_header(panel, ( + f"Signed wrist xyz error | {side} hand | raw=gray filtered=color", + )) + + +def worst_side(arrays: dict[str, np.ndarray]) -> int: + valid = arrays["joint_annotation_valid"].astype(bool) + signed_z = ( + arrays["pred_wrist_translation"] - arrays["target_wrist_translation"] + )[..., 2] * 1000.0 + means = [ + float(np.mean(np.abs(signed_z[:, hand][valid[:, hand]]))) + if valid[:, hand].any() else -1.0 + for hand in range(2) + ] + return int(np.argmax(means)) + + +def render_case( + *, + arrays: dict[str, np.ndarray], + condition_name: str, + filtered_translation: np.ndarray, + filtered_joints: np.ndarray, + data_root: Path, + output_dir: Path, +) -> dict[str, object]: + take = str(arrays["take"]) + take_dir = data_root / take + raw_K, source_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + output_dir.mkdir(parents=True, exist_ok=False) + paths = { + "raw_vs_filtered_30fps": output_dir / "raw_vs_filtered_30fps.mp4", + "raw_vs_filtered_4fps": output_dir / "raw_vs_filtered_4fps.mp4", + "failure_diagnostic_30fps": output_dir / "failure_diagnostic_30fps.mp4", + } + writers = { + "raw_vs_filtered_30fps": FFmpegWriter( + paths["raw_vs_filtered_30fps"], 30.0, (source_hw[0], source_hw[1] * 2), + ), + "raw_vs_filtered_4fps": FFmpegWriter( + paths["raw_vs_filtered_4fps"], 4.0, (source_hw[0], source_hw[1] * 2), + ), + "failure_diagnostic_30fps": FFmpegWriter( + paths["failure_diagnostic_30fps"], 30.0, (1080, 1920), + ), + } + side = worst_side(arrays) + side_name = "left" if side == 0 else "right" + valid_side = arrays["joint_annotation_valid"][:, side].astype(bool) + raw_error = ( + arrays["pred_wrist_translation"][:, side] + - arrays["target_wrist_translation"][:, side] + ) * 1000.0 + filtered_error = ( + filtered_translation[:, side] - arrays["target_wrist_translation"][:, side] + ) * 1000.0 + limits = side_limits( + arrays["pred_joints_camera"], filtered_joints, + arrays["target_joints_camera"], + ) + frame_hashes: dict[str, list[str]] = {key: [] for key in writers} + try: + for index, frame_id in enumerate(arrays["frame_id"].astype(int)): + image_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), cv2.IMREAD_COLOR, + ) + if image_bgr is None or image_bgr.shape[:2] != source_hw: + raise RuntimeError(f"raw RGB failure for {take}/{frame_id}") + image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) + raw_panel = overlay_joints( + image_rgb, arrays["pred_joints_camera"][index], raw_K, RAW_COLOR, + ) + raw_panel = add_header(raw_panel, ( + f"RAW model | {take} | frame={frame_id}", + "MANO joints=orange | 30 fps physical time", + )) + filtered_panel = overlay_joints( + image_rgb, filtered_joints[index], raw_K, FILTERED_COLOR, + ) + filtered_panel = add_header(filtered_panel, ( + f"FILTERED {condition_name} | {take} | frame={frame_id}", + "MANO joints=cyan | inference-only secondary", + )) + comparison_rgb = np.concatenate((raw_panel, filtered_panel), axis=1) + comparison_bgr = cv2.cvtColor(comparison_rgb, cv2.COLOR_RGB2BGR) + for key in ("raw_vs_filtered_30fps", "raw_vs_filtered_4fps"): + writers[key].write(comparison_bgr) + frame_hashes[key].append(hashlib.sha256(comparison_bgr.tobytes()).hexdigest()) + + diagnostic_overlay = overlay_joints( + image_rgb, arrays["target_joints_camera"][index], raw_K, + GT_COLOR, arrays["joint_annotation_valid"][index], + ) + diagnostic_overlay = overlay_joints( + diagnostic_overlay, arrays["pred_joints_camera"][index], raw_K, + RAW_COLOR, + ) + diagnostic_overlay = overlay_joints( + diagnostic_overlay, filtered_joints[index], raw_K, FILTERED_COLOR, + ) + diagnostic_overlay = add_header(diagnostic_overlay, ( + f"GT/raw/filtered overlay | {take} | frame={frame_id}", + "GT=green raw=orange filtered=cyan", + )) + top_left = cv2.resize(diagnostic_overlay, (960, 540), interpolation=cv2.INTER_AREA) + top_right = camera_side_panel( + arrays["pred_joints_camera"][index], filtered_joints[index], + arrays["target_joints_camera"][index], + arrays["joint_annotation_valid"][index], limits, frame_id, + ) + trace = trace_panel( + raw_error, filtered_error, valid_side, index, side_name, + ) + diagnostic_rgb = np.concatenate(( + np.concatenate((top_left, top_right), axis=1), trace, + ), axis=0) + diagnostic_bgr = cv2.cvtColor(diagnostic_rgb, cv2.COLOR_RGB2BGR) + writers["failure_diagnostic_30fps"].write(diagnostic_bgr) + frame_hashes["failure_diagnostic_30fps"].append( + hashlib.sha256(diagnostic_bgr.tobytes()).hexdigest() + ) + except Exception: + for writer in writers.values(): + writer.abort() + raise + for writer in writers.values(): + writer.close() + videos = { + key: { + "path": str(path.resolve()), "sha256": sha256(path), + "frames": writers[key].frames, + "fps": 4.0 if key.endswith("4fps") else 30.0, + "frame_pixel_sha256": frame_hashes[key], + } + for key, path in paths.items() + } + record = { + "take": take, "condition": condition_name, + "frames": len(arrays["frame_id"]), "trace_side": side_name, + "official_test_used": False, "videos": videos, + } + (output_dir / "case.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + return record + + +def assert_deterministic( + records: list[dict[str, object]], reference_manifest: Path, +) -> None: + reference = json.loads(reference_manifest.read_text(encoding="utf-8")) + reference_index = { + (record["take"], record["condition"]): record for record in reference["cases"] + } + observed_keys = {(record["take"], record["condition"]) for record in records} + if observed_keys != set(reference_index): + raise ValueError("visualization audit case grid mismatch") + for record in records: + other = reference_index.get((record["take"], record["condition"])) + if other is None: + raise ValueError("visualization audit case grid mismatch") + for video_name, video in record["videos"].items(): + if video["frame_pixel_sha256"] != other["videos"][video_name]["frame_pixel_sha256"]: + raise ValueError(f"visualization pixels are non-deterministic: {video_name}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--selection-json", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--case-count", type=int, default=3) + parser.add_argument("--audit-against", type=Path) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("filtered video output must be new or empty") + cache_manifest = json.loads( + (args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8") + ) + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + if ( + cache_manifest.get("status") != "complete" + or cache_manifest.get("official_test_used") is not False + or cache_manifest.get("scope") != "full" + or cache_manifest.get("clips") != 1495 + or cache_manifest.get("frames") != 11638 + or selection.get("status") != "selected" + or selection.get("official_test_used") is not False + or selection.get("selection_scope") + != "frozen_official_validation_subset_256" + or selection.get("checkpoint", {}).get("sha256") + != cache_manifest.get("checkpoint", {}).get("sha256") + ): + raise ValueError("filtered video cache/selection provenance mismatch") + selected_conditions = [ + value for family, value in sorted(selection["selected_conditions"].items()) + if value is not None + ] + if not selected_conditions: + raise ValueError("no eligible filter condition was selected") + grid = condition_grid() + cases = ranked_failure_takes(cache_manifest, args.case_count) + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + records = [] + for condition_name in selected_conditions: + condition = grid[condition_name] + for rank, case in enumerate(cases, start=1): + arrays = load_take(Path(case["path"])) + filtered_translation, filtered_rotations, _ = filtered_parameters( + arrays, condition, + ) + _, filtered_joints = rebuild_geometry( + filtered_rotations, arrays["pred_shape"].astype(np.float32), + filtered_translation, mano, device, + ) + record = render_case( + arrays=arrays, condition_name=condition_name, + filtered_translation=filtered_translation, + filtered_joints=filtered_joints, + data_root=args.data_root, + output_dir=( + args.output_dir / condition_name + / f"{rank:02d}_{str(case['take']).replace('/', '__')}" + ), + ) + record["rank"] = rank + record["raw_absolute_mpjpe_mm"] = case["raw_absolute_mpjpe_mm"] + records.append(record) + if args.audit_against is not None: + assert_deterministic(records, args.audit_against) + manifest = { + "status": "complete", + "official_test_used": False, + "result_role": "filtered_inference_secondary_results", + "cache_checkpoint": cache_manifest["checkpoint"], + "selection_json": str(args.selection_json.resolve()), + "conditions": selected_conditions, + "case_selection": "highest raw take-level absolute MPJPE", + "deterministic_against": ( + str(args.audit_against.resolve()) if args.audit_against else None + ), + "deterministic_pixel_audit_passed": args.audit_against is not None, + "cases": records, + } + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "video_manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "conditions": selected_conditions, + "cases": len(records), "deterministic_audit": args.audit_against is not None, + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_phase5_alignment_failure_cases.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_phase5_alignment_failure_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..051fe5d245d148f74274f9d9d3dc2463f44468db --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_phase5_alignment_failure_cases.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +"""Render deterministic predicted-MANO/depth alignment failure diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import matplotlib +import numpy as np + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def select_cases( + rows: list[dict[str, str]], refined_condition: str, +) -> list[dict[str, Any]]: + keyed: dict[tuple[str, int, str], dict[str, dict[str, str]]] = {} + for row in rows: + if row["condition"] not in ("coarse", refined_condition): + continue + key = (row["take"], int(row["frame_id"]), row["side"]) + keyed.setdefault(key, {})[row["condition"]] = row + pairs = [ + (key, values["coarse"], values[refined_condition]) + for key, values in keyed.items() + if set(values) == {"coarse", refined_condition} + ] + if not pairs: + raise ValueError("no matched coarse/refined frame rows") + + def z(row: dict[str, str]) -> float: + return float(row["translation_z_mae_mm"]) + + role_candidates = { + "right_far_small_tail": sorted( + ( + item for item in pairs + if item[0][2] == "right" and ( + item[1]["depth_bucket"] == "far" + or item[1]["hand_size_bucket"] == "small" + ) + ), + key=lambda item: (-z(item[1]), item[0]), + ), + "largest_z_gain": sorted( + pairs, key=lambda item: (-(z(item[1]) - z(item[2])), item[0]), + ), + "largest_z_harm": sorted( + pairs, key=lambda item: (-(z(item[2]) - z(item[1])), item[0]), + ), + } + selected = [] + used: set[tuple[str, int, str]] = set() + for role, candidates in role_candidates.items(): + choice = next((item for item in candidates if item[0] not in used), None) + if choice is None: + raise ValueError(f"cannot select a unique case for {role}") + key, coarse, refined = choice + used.add(key) + selected.append({ + "role": role, + "take": key[0], + "frame_id": key[1], + "side": key[2], + "coarse_z_mae_mm": z(coarse), + "refined_z_mae_mm": z(refined), + "z_mae_delta_mm": z(refined) - z(coarse), + "coarse_absolute_mpjpe_mm": float(coarse["absolute_mpjpe_mm"]), + "refined_absolute_mpjpe_mm": float(refined["absolute_mpjpe_mm"]), + "applied_delta_z_mm": float(refined["applied_delta_z_mm"]), + "alignment_confidence": float(refined["alignment_confidence"]), + "alignment_support": int(refined["alignment_support"]), + "alignment_quality": float(refined["alignment_quality"]), + "depth_bucket": coarse["depth_bucket"], + "hand_size_bucket": coarse["hand_size_bucket"], + }) + return selected + + +def inlier_masks( + observed_depth_m: np.ndarray, + predicted_depth_m: np.ndarray, + sample_valid: np.ndarray, + delta_z_m: float, + residual_scale_m: float, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + residual = observed_depth_m - predicted_depth_m + eligible = sample_valid & np.isfinite(residual) & (np.abs(residual) <= 0.15) + scale = max(float(residual_scale_m), 0.003) + inlier = eligible & (np.abs(residual - float(delta_z_m)) <= 1.345 * scale) + return eligible, inlier, eligible & ~inlier + + +def crop_bounds( + points_px: np.ndarray, image_hw: tuple[int, int], minimum_size: int = 240, +) -> tuple[int, int, int, int]: + height, width = image_hw + points = np.asarray(points_px, dtype=np.float64).reshape(-1, 2) + points = points[np.isfinite(points).all(axis=1)] + if not len(points): + return 0, 0, width, height + low, high = points.min(axis=0), points.max(axis=0) + center = (low + high) / 2.0 + size = max(float(np.max(high - low) + 120.0), float(minimum_size)) + size = min(size, float(width), float(height)) + x0 = int(np.clip(round(center[0] - size / 2), 0, width - size)) + y0 = int(np.clip(round(center[1] - size / 2), 0, height - size)) + return x0, y0, int(x0 + size), int(y0 + size) + + +def draw_points( + axis: plt.Axes, points: np.ndarray, color: str, label: str, + *, marker: str = "o", size: float = 10.0, alpha: float = 0.9, +) -> None: + values = np.asarray(points) + finite = np.isfinite(values).all(axis=-1) + axis.scatter( + values[finite, 0], values[finite, 1], s=size, c=color, + marker=marker, alpha=alpha, label=label, linewidths=0.4, + ) + + +def render_case( + case: dict[str, Any], + *, + cache_arrays: dict[str, np.ndarray], + alignment_arrays: dict[str, np.ndarray], + data_root: Path, + output: Path, +) -> dict[str, Any]: + frame_ids = cache_arrays["frame_id"].astype(np.int64) + matches = np.where(frame_ids == int(case["frame_id"]))[0] + if len(matches) != 1: + raise ValueError(f"frame is not unique in raw cache: {case}") + index = int(matches[0]) + hand = 1 if case["side"] == "right" else 0 + take_dir = data_root / case["take"] + frame_name = f"{int(case['frame_id']):06d}.png" + rgb_bgr = cv2.imread(str(take_dir / "rgb" / frame_name), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(take_dir / "depth" / frame_name), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise FileNotFoundError(f"missing RGB/depth for {case['take']}/{frame_name}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + if tuple(rgb.shape[:2]) != raw_hw or tuple(depth_mm.shape) != raw_hw: + raise ValueError("raw RGB/depth/intrinsics dimensions disagree") + depth_m, depth_valid = depth_mm_to_m(depth_mm) + coarse_vertices = cache_arrays["pred_vertices_camera"][index, hand] + diagnostics, surface = align_wrist_z(coarse_vertices, K_raw, depth_m, depth_valid) + if surface is None: + raise AssertionError("complete-modality case has no surface samples") + stored_delta = float(alignment_arrays["raw_alignment_delta_z_m"][index, hand]) + if abs(diagnostics.delta_z_m - stored_delta) > 1e-8: + raise ValueError("rerender alignment delta differs from evaluated prediction") + correction = float(alignment_arrays["calibrated_delta_z_m"][index, hand]) + eligible, inlier, outlier = inlier_masks( + surface.observed_depth_m, surface.predicted_depth_m, + surface.sample_valid, diagnostics.delta_z_m, diagnostics.residual_scale_m, + ) + + coarse_joints = cache_arrays["pred_joints_camera"][index, hand].astype(np.float64) + target_joints = cache_arrays["target_joints_camera"][index, hand].astype(np.float64) + refined_joints = coarse_joints.copy() + refined_joints[:, 2] += correction + coarse_px, _ = project_points(coarse_joints, K_raw) + refined_px, _ = project_points(refined_joints, K_raw) + target_px, _ = project_points(target_joints, K_raw) + bounds = crop_bounds( + np.concatenate((coarse_px, target_px, surface.projected_vertices_px[surface.visible_vertex])), + raw_hw, + ) + x0, y0, x1, y1 = bounds + offset = np.asarray((x0, y0)) + + figure, axes = plt.subplots(2, 3, figsize=(16, 9), dpi=120) + rgb_axis = axes[0, 0] + rgb_axis.imshow(rgb[y0:y1, x0:x1]) + draw_points(rgb_axis, target_px - offset, "#2ca02c", "GT", marker="x", size=24) + draw_points(rgb_axis, coarse_px - offset, "#d6278b", "coarse", size=16) + draw_points(rgb_axis, refined_px - offset, "#00a6d6", "refined", marker="+", size=24) + rgb_axis.set_title(f"RGB projection | {case['side']}") + rgb_axis.legend(loc="upper right", fontsize=8) + rgb_axis.axis("off") + + depth_axis = axes[0, 1] + depth_display = np.where(depth_valid, depth_m, np.nan) + depth_axis.imshow(depth_display[y0:y1, x0:x1], cmap="turbo", vmin=0.25, vmax=1.25) + projected = surface.projected_vertices_px - offset + draw_points(depth_axis, projected[inlier], "#39d353", "IRLS inlier", size=13) + draw_points(depth_axis, projected[outlier], "#ff4d4f", "eligible outlier", marker="x", size=17) + invalid_visible = surface.visible_vertex & ~eligible + draw_points(depth_axis, projected[invalid_visible], "#dddddd", "invalid", size=5, alpha=0.45) + depth_axis.set_title("Observed metric depth + surface samples") + depth_axis.legend(loc="upper right", fontsize=7) + depth_axis.axis("off") + + scatter_axis = axes[0, 2] + predicted = surface.predicted_depth_m[eligible] + observed = surface.observed_depth_m[eligible] + scatter_axis.scatter(predicted[inlier[eligible]], observed[inlier[eligible]], s=9, c="#39d353", label="inlier") + scatter_axis.scatter(predicted[outlier[eligible]], observed[outlier[eligible]], s=12, c="#ff4d4f", marker="x", label="outlier") + if len(predicted): + low = float(min(predicted.min(), observed.min())) + high = float(max(predicted.max(), observed.max())) + grid = np.linspace(low, high, 100) + scatter_axis.plot(grid, grid, color="#666666", linewidth=1, label="surface identity") + scatter_axis.plot(grid, grid + diagnostics.delta_z_m, color="#d6278b", linewidth=1.3, label="raw IRLS shift") + scatter_axis.plot(grid, grid + correction, color="#00a6d6", linewidth=1.3, label="calibrated shift") + scatter_axis.set_xlabel("predicted MANO surface z (m)") + scatter_axis.set_ylabel("observed depth z (m)") + scatter_axis.set_title("Metric correspondence") + scatter_axis.grid(alpha=0.2) + scatter_axis.legend(fontsize=7) + + side_axis = axes[1, 0] + target_vertices = cache_arrays["target_vertices_camera"][index, hand] + refined_vertices = coarse_vertices.astype(np.float64).copy() + refined_vertices[:, 2] += correction + sample = np.arange(0, len(coarse_vertices), 6) + side_axis.scatter(coarse_vertices[sample, 2], coarse_vertices[sample, 0], s=3, c="#d6278b", alpha=0.35, label="coarse") + side_axis.scatter(refined_vertices[sample, 2], refined_vertices[sample, 0], s=3, c="#00a6d6", alpha=0.35, label="refined") + side_axis.scatter(target_vertices[sample, 2], target_vertices[sample, 0], s=3, c="#2ca02c", alpha=0.35, label="GT") + side_axis.set_xlabel("camera z (m)") + side_axis.set_ylabel("camera x (m)") + side_axis.set_title("Camera side view") + side_axis.grid(alpha=0.2) + side_axis.legend(fontsize=7) + side_axis.set_aspect("equal", adjustable="datalim") + + trace_axis = axes[1, 1] + start, stop = max(0, index - 20), min(len(frame_ids), index + 21) + trace_frames = frame_ids[start:stop] + coarse_signed = 1000.0 * ( + cache_arrays["pred_wrist_translation"][start:stop, hand, 2] + - cache_arrays["target_wrist_translation"][start:stop, hand, 2] + ) + refined_signed = coarse_signed + 1000.0 * alignment_arrays["calibrated_delta_z_m"][start:stop, hand] + trace_axis.plot(trace_frames, coarse_signed, color="#d6278b", label="coarse signed z") + trace_axis.plot(trace_frames, refined_signed, color="#00a6d6", label="refined signed z") + trace_axis.axhline(0.0, color="#555555", linewidth=0.8) + trace_axis.axvline(case["frame_id"], color="#111111", linestyle="--", linewidth=0.8) + trace_axis.set_xlabel("frame") + trace_axis.set_ylabel("pred - GT wrist z (mm)") + trace_axis.set_title("Local signed-z trace") + trace_axis.grid(alpha=0.2) + trace_axis.legend(fontsize=7) + + text_axis = axes[1, 2] + text_axis.axis("off") + text_axis.text(0.0, 1.0, "\n".join(( + f"role: {case['role']}", + f"take/frame: {case['take']} / {case['frame_id']}", + f"side, size, depth: {case['side']}, {case['hand_size_bucket']}, {case['depth_bucket']}", + f"coarse -> refined z MAE: {case['coarse_z_mae_mm']:.2f} -> {case['refined_z_mae_mm']:.2f} mm", + f"coarse -> refined MPJPE: {case['coarse_absolute_mpjpe_mm']:.2f} -> {case['refined_absolute_mpjpe_mm']:.2f} mm", + f"raw IRLS / calibrated delta-z: {1000.0 * diagnostics.delta_z_m:.2f} / {1000.0 * correction:.2f} mm", + f"support / inlier ratio: {diagnostics.valid_support_count} / {diagnostics.inlier_ratio:.3f}", + f"residual scale: {1000.0 * diagnostics.residual_scale_m:.2f} mm", + f"valid / foreground / background: {diagnostics.valid_fraction:.3f} / {diagnostics.foreground_fraction:.3f} / {diagnostics.background_fraction:.3f}", + f"depth discontinuity: {1000.0 * diagnostics.depth_discontinuity_m:.2f} mm", + f"conditioning / learned confidence: {diagnostics.conditioning_quality:.3f} / {case['alignment_confidence']:.3f}", + "selection: official-validation secondary diagnostic only", + )), va="top", family="monospace", fontsize=10) + figure.suptitle("Phase 5 predicted-location MANO-depth alignment diagnostic", fontsize=14) + figure.tight_layout() + output.parent.mkdir(parents=True, exist_ok=True) + figure.savefig(output) + plt.close(figure) + return { + **case, + "image": str(output.resolve()), + "image_sha256": sha256(output), + "eligible_surface_samples": int(eligible.sum()), + "inlier_surface_samples": int(inlier.sum()), + "outlier_surface_samples": int(outlier.sum()), + "rerender_raw_delta_z_mm": 1000.0 * diagnostics.delta_z_m, + "rerender_residual_scale_mm": 1000.0 * diagnostics.residual_scale_m, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-dir", type=Path, required=True) + parser.add_argument("--raw-cache-manifest", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--condition", default="calibrated_always") + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("visualization output directory must be new or empty") + evaluation = json.loads((args.evaluation_dir / "evaluation.json").read_text(encoding="utf-8")) + cache = json.loads(args.raw_cache_manifest.read_text(encoding="utf-8")) + if evaluation.get("official_test_used") is not False or cache.get("official_test_used") is not False: + raise ValueError("failure visualization requires test-free inputs") + if args.condition not in evaluation.get("conditions", []): + raise ValueError(f"condition is absent from evaluation: {args.condition}") + cases = select_cases( + load_csv(args.evaluation_dir / "per_hand_frame_metrics.csv"), args.condition, + ) + cache_by_take = {record["take"]: record for record in cache["takes"]} + records = [] + for case in cases: + cache_record = cache_by_take[case["take"]] + cache_path = Path(cache_record["path"]) + if sha256(cache_path) != cache_record["sha256"]: + raise ValueError(f"raw-cache hash mismatch: {cache_path}") + with np.load(cache_path, allow_pickle=False) as archive: + cache_arrays = {key: archive[key] for key in archive.files} + prediction_path = args.evaluation_dir / "predictions" / f"{'__'.join(Path(case['take']).parts)}.npz" + with np.load(prediction_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + filename = f"{case['role']}__{'__'.join(Path(case['take']).parts)}__f{case['frame_id']:06d}__{case['side']}.png" + records.append(render_case( + case, cache_arrays=cache_arrays, alignment_arrays=alignment, + data_root=args.data_root, output=args.output_dir / filename, + )) + report = { + "status": "complete", + "result_role": "official_validation_secondary_failure_diagnostic", + "selection_rule": ["right far/small maximum coarse z error", "largest refined z gain", "largest refined z harm"], + "condition": args.condition, + "evaluation": str(args.evaluation_dir.resolve()), + "raw_cache_manifest": str(args.raw_cache_manifest.resolve()), + "cases": records, + "used_for_model_or_threshold_selection": False, + "oracle_information_at_inference": False, + "official_test_used": False, + } + manifest_path = args.output_dir / "manifest.json" + manifest_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "cases": len(records), + "manifest": str(manifest_path), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_sota_projection_audit.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_sota_projection_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..212336420b5c6d1a025fd254f26dc10df78e55fa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/render_sota_projection_audit.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Render deterministic GT/prediction projection checks for SOTA bundles.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + align_prediction, +) + + +EDGES = tuple( + edge + for finger_start in (1, 5, 9, 13, 17) + for edge in ( + (0, finger_start), + (finger_start, finger_start + 1), + (finger_start + 1, finger_start + 2), + (finger_start + 2, finger_start + 3), + ) +) +SIDE_COLORS = ((255, 200, 0), (0, 80, 255)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def project(points: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + normalized = points[..., :2] / points[..., 2:3] + return normalized @ intrinsics[:2, :2].T + intrinsics[:2, 2] + + +def draw_hand( + image: np.ndarray, + points: np.ndarray, + color: tuple[int, int, int], + *, + thickness: int, + radius: int, +) -> None: + rounded = np.rint(points).astype(np.int32) + for start, end in EDGES: + cv2.line( + image, + tuple(rounded[start]), + tuple(rounded[end]), + color, + thickness, + cv2.LINE_AA, + ) + for point in rounded: + cv2.circle(image, tuple(point), radius, color, -1, cv2.LINE_AA) + + +def make_panel( + image: np.ndarray, + label: str, + predicted: np.ndarray, + target: np.ndarray, + intrinsics: np.ndarray, + detected: np.ndarray, +) -> tuple[np.ndarray, float | None]: + panel = image.copy() + for hand in (0, 1): + draw_hand( + panel, + project(target[hand], intrinsics), + (245, 245, 245), + thickness=4, + radius=4, + ) + if detected[hand]: + draw_hand( + panel, + project(predicted[hand], intrinsics), + SIDE_COLORS[hand], + thickness=2, + radius=3, + ) + valid_hands = np.flatnonzero(detected) + error = None + if valid_hands.size: + error = float( + np.linalg.norm( + predicted[valid_hands] - target[valid_hands], axis=-1 + ).mean() + * 1000.0 + ) + cv2.rectangle(panel, (0, 0), (panel.shape[1], 46), (10, 10, 10), -1) + text = f"{label} Abs={error:.1f} mm" if error is not None else f"{label} missed" + cv2.putText( + panel, + text, + (12, 31), + cv2.FONT_HERSHEY_SIMPLEX, + 0.8, + (255, 255, 255), + 2, + cv2.LINE_AA, + ) + return panel, error + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--prediction", action="append", required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=6) + parser.add_argument("--panel-width", type=int, default=480) + args = parser.parse_args() + if args.samples <= 0 or args.panel_width <= 0: + raise ValueError("samples and panel width must be positive") + + ground_truth = GroundTruthBundle.load(args.ground_truth) + bundles: list[tuple[str, PredictionBundle, Path]] = [] + labels = set() + for spec in args.prediction: + label, separator, raw_path = spec.partition("=") + if not separator or not label or not raw_path or label in labels: + raise ValueError(f"Invalid or duplicate prediction spec: {spec}") + labels.add(label) + path = Path(raw_path).resolve() + bundles.append((label, align_prediction(PredictionBundle.load(path), ground_truth), path)) + + eligible = ground_truth.annotation_valid.all(axis=1) + for _, bundle, _ in bundles: + eligible &= bundle.detected.all(axis=1) + candidate_indices = np.flatnonzero(eligible) + if candidate_indices.size < args.samples: + raise ValueError("Not enough jointly valid/detected frames for projection audit") + positions = np.rint( + np.linspace(0, candidate_indices.size - 1, args.samples) + ).astype(np.int64) + selected = candidate_indices[positions] + + output_rows = [] + record_rows: list[dict[str, Any]] = [] + for frame_index in selected: + take = str(ground_truth.takes[frame_index]) + frame_id = int(ground_truth.frame_ids[frame_index]) + path = args.root / take / "rgb" / f"{frame_id:06d}.png" + image = cv2.imread(str(path)) + if image is None: + raise RuntimeError(f"Image decode failure: {path}") + panels = [] + for label, bundle, _ in bundles: + panel, error = make_panel( + image, + label, + bundle.joints_camera_m[frame_index], + ground_truth.joints_camera_m[frame_index], + ground_truth.intrinsics[frame_index], + bundle.detected[frame_index], + ) + height = round(panel.shape[0] * args.panel_width / panel.shape[1]) + panels.append(cv2.resize(panel, (args.panel_width, height))) + record_rows.append({ + "frame_key": str(ground_truth.frame_keys[frame_index]), + "model": label, + "absolute_mpjpe_mm": error, + }) + output_rows.append(np.concatenate(panels, axis=1)) + + audit_models = [] + height, width = image.shape[:2] + for label, bundle, path in bundles: + detected_points = bundle.joints_camera_m[bundle.detected] + K = np.repeat(ground_truth.intrinsics[:, None], 2, axis=1)[bundle.detected] + uv = np.einsum( + "nij,nkj->nki", + K[:, :2, :2], + detected_points[..., :2] / detected_points[..., 2:3], + ) + K[:, None, :2, 2] + in_frame = ( + (uv[..., 0] >= 0) + & (uv[..., 0] < width) + & (uv[..., 1] >= 0) + & (uv[..., 1] < height) + ) + audit_models.append({ + "label": label, + "prediction": str(path), + "prediction_sha256": sha256(path), + "detected_hand_frames": int(bundle.detected.sum()), + "finite_detected_fraction": float(np.isfinite(detected_points).all(axis=-1).mean()), + "positive_depth_fraction": float((detected_points[..., 2] > 0).mean()), + "projected_joint_in_frame_fraction": float(in_frame.mean()), + "wrist_z_m_percentiles": np.percentile( + detected_points[:, 0, 2], (1, 50, 99) + ).tolist(), + }) + + args.output_dir.mkdir(parents=True, exist_ok=True) + contact_sheet = np.concatenate(output_rows, axis=0) + contact_path = args.output_dir / "projection_contact_sheet.jpg" + if not cv2.imwrite(str(contact_path), contact_sheet, [cv2.IMWRITE_JPEG_QUALITY, 92]): + raise RuntimeError(f"Failed to write {contact_path}") + payload = { + "status": "pass", + "official_test_used": False, + "selection": "evenly spaced among frames valid and detected for every model", + "legend": "GT white; prediction left cyan and right red", + "selected_frame_keys": [ + str(ground_truth.frame_keys[index]) for index in selected + ], + "per_selected_frame": record_rows, + "models": audit_models, + "contact_sheet": str(contact_path.resolve()), + "contact_sheet_sha256": sha256(contact_path), + } + (args.output_dir / "visual_audit.json").write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(payload, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_dynhamr_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_dynhamr_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..84bdce419fb36846d43852afe76b93928b2290ea --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_dynhamr_h2o.py @@ -0,0 +1,627 @@ +#!/usr/bin/env python3 +"""Run the released Dyn-HaMR TTO pipeline zero-shot on H2O validation runs.""" + +from __future__ import annotations + +import argparse +import contextlib +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from scipy.interpolate import interp1d +from scipy.spatial.transform import Rotation, Slerp + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, frame_key +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--rescale-factor", type=float, default=1.3) + parser.add_argument("--max-runs", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + parser.add_argument( + "--run-indices", + nargs="*", + type=int, + help="Explicit global manifest-run order; overrides modulo sharding.", + ) + return parser.parse_args() + + +def _load_manifest_runs(path: Path) -> list[dict[str, Any]]: + runs = [json.loads(line) for line in path.read_text().splitlines() if line.strip()] + for run_index, run in enumerate(runs): + take = str(run["take"]) + if not take.endswith("/cam4"): + raise ValueError(f"Dyn-HaMR evaluation is cam4-only: {take}") + run["global_run_index"] = run_index + run["frame_ids"] = [int(value) for value in run["frame_ids"]] + return runs + + +def _import_hamer_runner(repo: Path) -> Any: + path = repo / "third-party" / "hamer" / "run.py" + spec = importlib.util.spec_from_file_location("dynhamr_released_hamer_runner", path) + if spec is None or spec.loader is None: + raise ImportError(f"Cannot import released HaMeR runner: {path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _to_numpy(value: Any) -> np.ndarray: + if torch.is_tensor(value): + return value.detach().float().cpu().numpy() + return np.asarray(value) + + +def _interpolate_rotvec(values: np.ndarray, visible: np.ndarray) -> np.ndarray: + output = values.copy() + indices = np.flatnonzero(visible) + if len(indices) < 2: + return output + times = np.arange(indices[0], indices[-1] + 1) + rotations = Rotation.from_rotvec(values[indices].reshape(len(indices), -1, 3)) + joint_count = rotations.as_rotvec().shape[1] + for joint in range(joint_count): + slerp = Slerp(indices, Rotation.from_rotvec(values[indices, joint])) + output[times, joint] = slerp(times).as_rotvec() + return output + + +def _interpolate_linear(values: np.ndarray, visible: np.ndarray) -> np.ndarray: + output = values.copy() + indices = np.flatnonzero(visible) + if len(indices) < 2: + return output + times = np.arange(indices[0], indices[-1] + 1) + function = interp1d(indices, values[indices], axis=0, kind="linear") + output[times] = function(times) + return output + + +def _extract_initialization( + frame_paths: list[Path], + raw_data: list[dict[str, Any]], + results: dict[str, Any], +) -> dict[str, np.ndarray]: + count = len(frame_paths) + pose = np.full((2, count, 15, 3), np.nan, dtype=np.float32) + orient = np.full((2, count, 1, 3), np.nan, dtype=np.float32) + shape = np.full((2, count, 10), np.nan, dtype=np.float32) + translation = np.full((2, count, 3), np.nan, dtype=np.float32) + keypoints = np.full((2, count, 21, 3), np.nan, dtype=np.float32) + confidence = np.full((2, count), np.nan, dtype=np.float32) + + for frame_index, (path, cleaned) in enumerate(zip(frame_paths, raw_data, strict=True)): + result = results[str(path)] + sides = np.asarray(result["tid"], dtype=np.int64) + for local, side in enumerate(sides): + mano = result["mano"][local] + hand_matrix = _to_numpy(mano["hand_pose"]).reshape(15, 3, 3) + root_matrix = _to_numpy(mano["global_orient"]).reshape(3, 3) + pose[side, frame_index] = Rotation.from_matrix(hand_matrix).as_rotvec() + orient[side, frame_index, 0] = Rotation.from_matrix(root_matrix).as_rotvec() + shape[side, frame_index] = _to_numpy(mano["betas"]).reshape(10) + translation[side, frame_index] = np.asarray( + result["cam_trans"][local], dtype=np.float32 + ) + keypoints[side, frame_index] = np.asarray( + result["extra_data"][local], dtype=np.float32 + ) + confidence[side, frame_index] = float( + cleaned["left_conf" if side == 0 else "right_conf"] + ) + + active = np.isfinite(pose).all(axis=(-1, -2)) + recovered = np.zeros_like(active) + vis_mask = np.full((2, count), -1.0, dtype=np.float32) + for side in (0, 1): + indices = np.flatnonzero(active[side]) + if len(indices) < 2: + continue + interval = slice(indices[0], indices[-1] + 1) + recovered[side, interval] = True + vis_mask[side, interval] = 0.0 + vis_mask[side, active[side]] = 1.0 + pose[side] = _interpolate_rotvec(pose[side], active[side]) + orient[side] = _interpolate_rotvec(orient[side], active[side]) + shape[side] = _interpolate_linear(shape[side], active[side]) + translation[side] = _interpolate_linear(translation[side], active[side]) + keypoints[side] = _interpolate_linear(keypoints[side], active[side]) + confidence[side] = _interpolate_linear(confidence[side], active[side]) + # The released file loader represents frames outside each recovered track + # with zeros and excludes them through the ternary visibility mask. + for values in (pose, orient, shape, translation, keypoints): + np.nan_to_num(values, copy=False) + return { + "pose": pose, + "orient": orient[:, :, 0], + "shape": shape, + "translation": translation, + "keypoints": keypoints, + "confidence": confidence, + "active": active, + "recovered": recovered, + "vis_mask": vis_mask, + } + + +def _run_official_initialization( + repo: Path, + frame_paths: list[Path], + detector: Any, + hamer_model: torch.nn.Module, + hamer_config: Any, + runner: Any, + rescale_factor: float, +) -> dict[str, np.ndarray]: + raw_data = runner.extract_raw_bboxes(frame_paths, detector, vis_dir=None) + cleaned_data = runner.clean_bbox_sequences(raw_data, vis_dir=None) + results = runner.run_hamer_on_cleaned_bboxes( + cleaned_data, + hamer_model, + hamer_config, + None, + SimpleNamespace( + rescale_factor=rescale_factor, + render=False, + res_folder=str(repo / "outputs" / "unused.pkl"), + ), + ) + return _extract_initialization(frame_paths, cleaned_data, results) + + +class _InactiveBMCLoss: + """Avoid loading unavailable BMC assets when all official bio weights are zero.""" + + def __init__(self, *_: Any, **__: Any) -> None: + pass + + def compute_loss(self, *_: Any, **__: Any) -> Any: + raise RuntimeError("BMC loss called although the released bio weight is zero") + + +def _run_optimizer_exact( + optimizer: Any, + observed: dict[str, Any], + iterations: int, +) -> int: + """Run the released outer-loop and early-stop logic without file checkpoints.""" + + optimizer.cur_step = 0 + optimizer.loss.cur_step = 0 + completed = 0 + for iteration in range(iterations): + optimizer.cur_step = iteration + optimizer.loss.cur_step = iteration + optimizer.optim_step(observed, iteration, writer=None) + completed = iteration + 1 + if np.isnan(optimizer.cur_loss): + raise FloatingPointError(f"{optimizer.name} produced NaN") + if optimizer.reached_max and optimizer.reached_max_iter < 0: + optimizer.reached_max_iter = iteration - 1 + if ( + optimizer.reached_max + and iteration - optimizer.reached_max_iter >= optimizer.max_chunk_steps + ): + break + loss_change = optimizer.prev_loss - optimizer.cur_loss + if optimizer.last_updated == iteration - 1 and loss_change == 0: + break + if ( + (optimizer.cur_loss < 0 and loss_change < 100) + or (iteration - optimizer.last_updated >= optimizer.max_chunk_steps) + or (loss_change < 20 and iteration - optimizer.last_updated > 5) + ): + optimizer.add_chunk += 1 + optimizer.last_updated = iteration + optimizer.prev_loss = optimizer.cur_loss + return completed + + +def _optimize_run( + repo: Path, + initialization: dict[str, np.ndarray], + intrinsics: np.ndarray, + device: torch.device, + log_path: Path, +) -> tuple[np.ndarray, np.ndarray, dict[str, int]]: + sys.path.insert(0, str(repo / "dyn-hamr")) + from body_model import MANO + from optim import losses as loss_module + from optim.base_scene import BaseSceneModel + from optim.optimizers import RootOptimizer, SmoothOptimizer + from util.logger import Logger + + active_sides = np.flatnonzero(initialization["recovered"].any(axis=1)) + count = initialization["pose"].shape[1] + output_joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + output_vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + if len(active_sides) == 0: + return output_joints, output_vertices, {"root_iterations": 0, "smooth_iterations": 0} + + loss_module.BMCLoss = _InactiveBMCLoss + config = yaml.safe_load((repo / "dyn-hamr" / "confs" / "optim.yaml").read_text())[ + "optim" + ] + all_weights = config["loss_weights"] + stage_weights = [ + {name: values[stage] for name, values in all_weights.items()} + for stage in range(3) + ] + options = dict(config["options"]) + options["vis_every"] = -1 + options["save_meshes"] = False + + batch = len(active_sides) + mano = MANO( + batch_size=batch * count, + pose2rot=True, + model_path=str(repo / "_DATA" / "data" / "mano"), + gender="neutral", + num_hand_joints=15, + mean_params=str(repo / "_DATA" / "data" / "mano_mean_params.npz"), + create_body_pose=False, + ).to(device) + scene = BaseSceneModel( + batch, + count, + mano, + None, + use_init=True, + opt_cams=False, + opt_scale=False, + async_tracks=True, + ) + observed: dict[str, Any] = { + "joints2d": torch.from_numpy(initialization["keypoints"][active_sides]).to(device), + "init_body_pose": torch.from_numpy(initialization["pose"][active_sides]).to(device), + "init_body_shape": torch.from_numpy(initialization["shape"][active_sides]).to(device), + "init_root_orient": torch.from_numpy(initialization["orient"][active_sides]).to(device), + "init_trans": torch.from_numpy(initialization["translation"][active_sides]).to(device), + "is_right": torch.from_numpy( + np.broadcast_to(active_sides[:, None], (batch, count)).astype(np.float32).copy() + ).to(device), + "vis_mask": torch.from_numpy(initialization["vis_mask"][active_sides]).to(device), + } + cam_data = { + "cam_R": torch.eye(3, device=device)[None].repeat(count, 1, 1), + "cam_t": torch.zeros(count, 3, device=device), + "intrins": torch.from_numpy( + np.stack( + [ + intrinsics[:, 0, 0], + intrinsics[:, 1, 1], + intrinsics[:, 0, 2], + intrinsics[:, 1, 2], + ], + axis=-1, + ).astype(np.float32) + ).to(device), + "static": True, + } + scene.initialize(observed, cam_data) + scene = scene.to(device) + Logger.init(str(log_path)) + + root_optimizer = RootOptimizer(scene, stage_weights, **options) + root_iterations = _run_optimizer_exact( + root_optimizer, observed, int(config["root"]["num_iters"]) + ) + smooth_options = dict(options) + smooth_options["opt_scale"] = bool(config["smooth"]["opt_scale"]) + smooth_optimizer = SmoothOptimizer(scene, stage_weights, **smooth_options) + smooth_iterations = _run_optimizer_exact( + smooth_optimizer, observed, int(config["smooth"]["num_iters"]) + ) + + with torch.inference_mode(): + prediction = scene.pred_params_mano(observed["is_right"]) + predicted_joints = prediction["joints3d"].float().cpu().numpy() + predicted_vertices = prediction["verts3d"].float().cpu().numpy() + for local, side in enumerate(active_sides): + valid = initialization["recovered"][side] + output_joints[valid, side] = predicted_joints[local, valid] + output_vertices[valid, side] = predicted_vertices[local, valid] + del root_optimizer, smooth_optimizer, scene, mano + torch.cuda.empty_cache() + plt.close("all") + return output_joints, output_vertices, { + "root_iterations": root_iterations, + "smooth_iterations": smooth_iterations, + } + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "detector", + "root", + "manifest", + "ground_truth", + "cache_dir", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + args.cache_dir.mkdir(parents=True, exist_ok=True) + args.output.parent.mkdir(parents=True, exist_ok=True) + + enable_legacy_mano_loading() + hamer_root = args.repo / "third-party" / "hamer" + sys.path.insert(0, str(hamer_root)) + sys.path.insert(0, str(args.repo / "dyn-hamr")) + os.chdir(args.repo) + from hamer.models import load_hamer + from ultralytics import YOLO + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + hamer_model, hamer_config = load_hamer(str(args.repo)) + hamer_model = hamer_model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + hamer_runner = _import_hamer_runner(args.repo) + + all_runs = _load_manifest_runs(args.manifest) + if args.run_indices is not None: + if len(set(args.run_indices)) != len(args.run_indices): + raise ValueError("Explicit run indices contain duplicates") + if any(index < 0 or index >= len(all_runs) for index in args.run_indices): + raise ValueError("Explicit run index is outside the manifest") + selected = [all_runs[index] for index in args.run_indices] + else: + selected = [ + run + for run in all_runs + if int(run["global_run_index"]) % args.num_shards == args.shard_index + ] + if args.max_runs is not None: + selected = selected[: args.max_runs] + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + + frame_keys: list[str] = [] + takes: list[str] = [] + frame_ids: list[int] = [] + run_outputs: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]] = [] + total_root_iterations = 0 + total_smooth_iterations = 0 + initialized_runs = 0 + optimized_runs = 0 + initialization_seconds = 0.0 + optimization_seconds = 0.0 + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for selected_index, run in enumerate(selected): + run_index = int(run["global_run_index"]) + take = str(run["take"]) + ids = np.asarray(run["frame_ids"], dtype=np.int64) + keys = np.asarray([frame_key(take, int(value)) for value in ids], dtype=np.str_) + frame_paths = [ + args.root / take / "rgb" / f"{int(value):06d}.png" for value in ids + ] + if not all(path.is_file() for path in frame_paths): + raise FileNotFoundError(f"Missing H2O RGB frame in run {run_index}") + run_dir = args.cache_dir / f"run_{run_index:03d}" + run_dir.mkdir(parents=True, exist_ok=True) + init_path = run_dir / "initialization.npz" + pred_path = run_dir / "prediction.npz" + log_path = run_dir / "optimizer.log" + if init_path.is_file(): + with np.load(init_path, allow_pickle=False) as data: + initialization = {name: data[name].copy() for name in data.files} + else: + if device.type == "cuda": + torch.cuda.synchronize(device) + stage_started = time.perf_counter() + with log_path.open("a", encoding="utf-8") as log, contextlib.redirect_stdout( + log + ), contextlib.redirect_stderr(log): + initialization = _run_official_initialization( + args.repo, + frame_paths, + detector, + hamer_model, + hamer_config, + hamer_runner, + args.rescale_factor, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + initialization_seconds += time.perf_counter() - stage_started + np.savez_compressed(init_path, **initialization) + initialized_runs += 1 + confidence = initialization["confidence"] + recovered = initialization["recovered"] + if pred_path.is_file(): + with np.load(pred_path, allow_pickle=False) as data: + run_joints = data["joints"].copy() + run_vertices = data["vertices"].copy() + iteration_counts = json.loads(str(data["iteration_counts_json"].item())) + else: + indices = np.asarray([gt_index[str(key)] for key in keys], dtype=np.int64) + # The released optimizer prints full pose tensors for every LBFGS + # closure. Logger still records scalar losses in optimizer.log. + if device.type == "cuda": + torch.cuda.synchronize(device) + stage_started = time.perf_counter() + with Path(os.devnull).open("w") as sink, contextlib.redirect_stdout( + sink + ), contextlib.redirect_stderr(sink): + run_joints, run_vertices, iteration_counts = _optimize_run( + args.repo, + initialization, + ground_truth.intrinsics[indices], + device, + log_path, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + optimization_seconds += time.perf_counter() - stage_started + np.savez_compressed( + pred_path, + joints=run_joints, + vertices=run_vertices, + iteration_counts_json=np.asarray(json.dumps(iteration_counts)), + ) + optimized_runs += 1 + total_root_iterations += int(iteration_counts["root_iterations"]) + total_smooth_iterations += int(iteration_counts["smooth_iterations"]) + frame_keys.extend(keys.tolist()) + takes.extend([take] * len(ids)) + frame_ids.extend(ids.tolist()) + run_outputs.append((run_joints, run_vertices, recovered.T, confidence.T)) + print( + f"Dyn-HaMR run {selected_index + 1}/{len(selected)} " + f"global={run_index} frames={len(ids)} " + f"iters={iteration_counts['root_iterations']}/{iteration_counts['smooth_iterations']}", + flush=True, + ) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "Dyn-HaMR", + "scope": "RGB detector/HaMeR initialization + per-run Root/Smooth test-time optimization", + "frames": int(sum(len(run["frame_ids"]) for run in selected)), + "runs": len(selected), + "processing_seconds": processing_seconds, + "frames_per_second": int(sum(len(run["frame_ids"]) for run in selected)) / processing_seconds, + "initialization_seconds": initialization_seconds, + "optimization_seconds": optimization_seconds, + "cache_and_host_overhead_seconds": processing_seconds - initialization_seconds - optimization_seconds, + "root_iterations": total_root_iterations, + "smooth_iterations": total_smooth_iterations, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + joints = np.concatenate([value[0] for value in run_outputs], axis=0) + vertices = np.concatenate([value[1] for value in run_outputs], axis=0) + detected = np.concatenate([value[2] for value in run_outputs], axis=0) + confidence = np.concatenate([value[3] for value in run_outputs], axis=0) + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + hamer_commit = subprocess.check_output( + ["git", "-C", str(hamer_root), "rev-parse", "HEAD"], text=True + ).strip() + hamer_checkpoint = args.repo / "_DATA" / "hamer_ckpts" / "checkpoints" / "hamer.ckpt" + reconstruction_parameters = sum( + parameter.numel() for parameter in hamer_model.parameters() + ) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/ZhengdiYu/Dyn-HaMR", + "repository_commit": commit, + "hamer_repository_commit": hamer_commit, + "hamer_checkpoint": str(hamer_checkpoint), + "hamer_checkpoint_sha256": sha256(hamer_checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": ( + "full RGB video, released enhanced YOLO/HaMeR tracker, known static H2O cam4 K, " + "per-contiguous-run Root and Smooth test-time optimization" + ), + "training_exposure": ( + "Dyn-HaMR is test-time optimization; released HaMeR initializer training includes " + "H2O3D but not H2O; no H2O fine-tuning" + ), + "fine_tuning": "not applicable: adaptation is per-video test-time optimization", + "camera_policy": "known static H2O cam4 extrinsics/intrinsics; no SLAM or GT pose", + "optimizer_config": str(args.repo / "dyn-hamr" / "confs" / "optim.yaml"), + "optimizer_config_sha256": sha256(args.repo / "dyn-hamr" / "confs" / "optim.yaml"), + "root_iterations_total": total_root_iterations, + "smooth_iterations_total": total_smooth_iterations, + "run_count": len(selected), + "new_initializations": initialized_runs, + "new_optimizations": optimized_runs, + "rescale_factor": args.rescale_factor, + "detector_confidence_threshold": 0.5, + "temporal": True, + "temporal_protocol": "each official validation manifest run optimized independently", + "optional_hmp_prior_used": False, + "inactive_bmc_asset_policy": ( + "BMC object initialization skipped because released bio weights are zero in all stages" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + "explicit_run_indices": args.run_indices, + } + bundle = PredictionBundle( + model_name="Dyn-HaMR-zero-shot-TTO", + frame_keys=np.asarray(frame_keys, dtype=np.str_), + takes=np.asarray(takes, dtype=np.str_), + frame_ids=np.asarray(frame_ids, dtype=np.int64), + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_foundation_hand_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_foundation_hand_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..52771dd5f05a9772cec1488dad3789b731bb9065 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_foundation_hand_h2o.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Export the promoted Phase 3 model into the common SOTA prediction schema.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.evaluation.sota import PredictionBundle, frame_key, load_frame_index +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--max-clips", type=int) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + keys, takes, frame_ids = load_frame_index(args.manifest) + key_to_index = {str(key): index for index, key in enumerate(keys)} + count = len(keys) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), + (int(data_config["stride"]),), + max_clips=args.max_clips, + ) + loader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint( + args.checkpoint, model, optimizer=None, map_location=device + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + exported = 0 + processed_clips = 0 + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = { + name: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for name, value in batch_cpu.items() + } + with torch.autocast("cuda", dtype=dtype): + output = model(batch) + valid_length = int(batch["frame_valid"][0].sum()) + output_joints = output["joints_camera"][0, :valid_length].float().cpu().numpy() + output_vertices = output["vertices_camera"][0, :valid_length].float().cpu().numpy() + for time_index in range(valid_length): + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + frame_id_value = int(batch["frame_id"][0, time_index]) + index = key_to_index[frame_key(take, frame_id_value)] + joints[index] = output_joints[time_index] + vertices[index] = output_vertices[time_index] + detected[index] = True + exported += 1 + processed_clips = clip_index + 1 + if (clip_index + 1) % 100 == 0 or clip_index + 1 == len(loader): + print(f"FoundationHand clips {clip_index + 1}/{len(loader)}", flush=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + processed_frames = int(detected.all(axis=1).sum()) + if args.timing_output is not None: + timing_output = args.timing_output.resolve() + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "FoundationHand-Phase3", + "scope": "RGB+Depth+K decode/preprocessing + BF16 T=8 model forward + host result transfer", + "frames": processed_frames, + "clips": processed_clips, + "processing_seconds": processing_seconds, + "frames_per_second": processed_frames / processing_seconds, + "clips_per_second": processed_clips / processing_seconds, + "amortized_ms_per_frame": 1000.0 * processing_seconds / processed_frames, + "clip_length": int(data_config["T"]), + "resolution_hw": data_config["resolution_hw"], + "batch_size_clips": 1, + "num_workers": args.num_workers, + "precision": config["precision"], + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + if args.max_clips is not None: + processed = detected.all(axis=1) + keys, takes, frame_ids = keys[processed], takes[processed], frame_ids[processed] + joints, vertices = joints[processed], vertices[processed] + detected, confidence = detected[processed], confidence[processed] + elif exported != count: + raise RuntimeError(f"Expected {count} exported frames, observed {exported}") + + repository_commit = subprocess.check_output( + ["git", "rev-parse", "HEAD"], text=True + ).strip() + parameter_count = sum(parameter.numel() for parameter in model.parameters()) + trainable_parameter_count = sum( + parameter.numel() for parameter in model.parameters() if parameter.requires_grad + ) + bundle = PredictionBundle( + model_name="FoundationHand-Phase3", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata={ + "repository_commit_at_export": repository_commit, + "training_commit": "d4019222835132fcbcc850ba49e6e0b53ab352b3", + "checkpoint": str(args.checkpoint.resolve()), + "checkpoint_sha256": sha256(args.checkpoint), + "checkpoint_step": int(checkpoint_state["step"]), + "parameter_count": parameter_count, + "trainable_parameter_count_at_export": trainable_parameter_count, + "input": "full RGB + aligned metric Depth + H2O K, T=8", + "temporal": True, + "temporal_window": int(data_config["T"]), + "detector": False, + "fixed_semantic_slots": True, + "official_test_used": False, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_hamba_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_hamba_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..80aca96be62d8cdd4d3d9c34afa69fc86f906300 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_hamba_h2o.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Run the released Hamba checkpoint on H2O with a common hand detector.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, load_frame_index +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--preprocess-repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256") + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=8) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "preprocess_repo", + "checkpoint", + "config", + "detector", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + if args.checkpoint_sha256 is not None and ( + len(args.checkpoint_sha256) != 64 + or any(character not in "0123456789abcdef" for character in args.checkpoint_sha256) + ): + raise ValueError("--checkpoint-sha256 must be 64 lowercase hexadecimal characters") + + sys.path.insert(0, str(args.preprocess_repo)) + sys.path.insert(0, str(args.repo)) + enable_legacy_mano_loading() + os.chdir(args.repo) + + from hamba.configs import get_config + from hamba.models import HAMBA + from ultralytics import YOLO + from wilor.datasets.vitdet_dataset import ViTDetDataset + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + config = get_config(str(args.config), update_cachedir=True) + config.defrost() + config.MODEL.BBOX_SHAPE = [192, 256] + config.MODEL.BACKBONE.pop("PRETRAINED_WEIGHTS", None) + config.MODEL.pop("PRETRAINED_WEIGHTS_INIT_REGRESSION", None) + config.freeze() + if not config.MODEL.USE_INIT_REGRESSION: + raise ValueError("This adapter requires the released initial-regressor configuration") + model = HAMBA(config, init_renderer=False) + checkpoint = torch.load( + args.checkpoint, + map_location="cpu", + weights_only=False, + mmap=True, + ) + model.load_state_dict(checkpoint["state_dict"], strict=True) + del checkpoint + model = model.to(device).eval() + + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch["keypoints_2d"] = torch.zeros((batch_size, 21, 3), dtype=torch.float32) + batch["is_valid"] = torch.ones(batch_size, dtype=torch.int64) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + record_indices = np.asarray([record[0] for record in records]) + intrinsic = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (intrinsic[:, 0, 0] + intrinsic[:, 1, 1]) + principal = intrinsic[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + camera = torch.stack(( + pred_cam[:, 1] + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), dim=-1).float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + batch_joints += camera[:, None] + batch_vertices += camera[:, None] + for local, (frame_index, side, score, _) in enumerate(records): + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + dataset = ViTDetDataset( + config, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"Hamba detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + kernel_path = Path(sys.modules["selective_scan_cuda_oflex"].__file__).resolve() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/humansensinglab/Hamba", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": args.checkpoint_sha256 or sha256(args.checkpoint), + "config": str(args.config), + "config_sha256": sha256(args.config), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector hand boxes, per-hand crops", + "training_exposure": "zero-shot H2O; release config includes H2O3D but not H2O", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "camera_policy": "cam_crop_to_full algebra with known H2O focal/principal point", + "preprocessing": "official HaMeR-compatible crop geometry shared with WiLoR", + "joint_source": "released Hamba initial regressor; no GT or external 2D joints", + "test_time_augmentation": False, + "selective_scan_kernel": str(kernel_path), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="Hamba-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_handdgp_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_handdgp_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..6a22aa27e858db7aa398de80e9399957e95d783b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_handdgp_h2o.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Run the released FreiHAND HandDGP checkpoint zero-shot on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import cv2 +import kornia +import numpy as np +import torch + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + load_frame_index, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=32) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--crop-scale", type=float, default=1.3) + parser.add_argument("--input-size", type=int, default=224) + parser.add_argument("--canonical-focal", type=float, default=1000.0) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def _prepare_crop( + image_rgb: np.ndarray, + box_xyxy: np.ndarray, + intrinsic: np.ndarray, + *, + is_left: bool, + input_size: int, + crop_scale: float, + canonical_focal: float, + generate_patch_image: Any, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Apply the released square crop and canonical-intrinsics rectification.""" + + image = image_rgb + box = np.asarray(box_xyxy, dtype=np.float32).copy() + K = np.asarray(intrinsic, dtype=np.float32).copy() + if is_left: + width = image.shape[1] + image = np.ascontiguousarray(image[:, ::-1]) + box[[0, 2]] = (width - 1) - box[[2, 0]] + K[0, 2] = (width - 1) - K[0, 2] + + width = float(box[2] - box[0]) + height = float(box[3] - box[1]) + side = max(width, height) + center = np.asarray( + [(box[0] + box[2]) * 0.5, (box[1] + box[3]) * 0.5], + dtype=np.float32, + ) + square_box = ( + float(center[0] - 0.5 * side), + float(center[1] - 0.5 * side), + side, + side, + ) + crop, _, _, _, _ = generate_patch_image( + cvimg=image, + bbox=square_box, + scale=crop_scale, + rot=0.0, + shift=(0.0, 0.0), + do_flip=False, + out_shape=(input_size, input_size), + shift_wh=None, + mask=None, + ) + crop_tensor = torch.from_numpy(np.ascontiguousarray(crop)).float() + crop_tensor = crop_tensor.permute(2, 0, 1) / 255.0 + + # FreiHAND hands are centered close to the optical axis. For arbitrary + # detector crops, use the equivalent box-centered virtual camera and map + # its ray back to the raw H2O camera after inference. + focal_scaled = K[[0, 1], [0, 1]] * input_size / (side * crop_scale) + crop_intrinsic = np.asarray( + [ + [focal_scaled[0], 0.0, input_size * 0.5], + [0.0, focal_scaled[1], input_size * 0.5], + [0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + canonical_intrinsic = np.asarray( + [ + [canonical_focal, 0.0, input_size * 0.5], + [0.0, canonical_focal, input_size * 0.5], + [0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + rectification = torch.from_numpy( + canonical_intrinsic @ np.linalg.inv(crop_intrinsic) + ) + crop_tensor = kornia.geometry.transform.warp_affine( + crop_tensor.unsqueeze(0), + rectification[:2, :3].unsqueeze(0), + dsize=(input_size, input_size), + mode="bilinear", + padding_mode="zeros", + align_corners=True, + ).squeeze(0) + ray_offset = (center - K[:2, 2]) / K[[0, 1], [0, 1]] + return ( + crop_tensor, + torch.from_numpy(canonical_intrinsic), + torch.from_numpy(ray_offset.astype(np.float32)), + ) + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "checkpoint", + "detector", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from src.models.handdgp import HandDGP + from third_party.HandMesh.utils.preprocessing import generate_patch_image + from ultralytics import YOLO + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], + takes[: args.max_frames], + frame_ids[: args.max_frames], + ) + count = len(keys) + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack( + [ground_truth.intrinsics[gt_index[str(key)]] for key in keys] + ) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + model = HandDGP( + batch_size=args.reconstruction_batch_size, + imagenet_pretrain=False, + input_size=args.input_size, + ) + checkpoint = torch.load( + args.checkpoint, + map_location="cpu", + weights_only=False, + mmap=True, + ) + state_dict = { + name.removeprefix("model."): value + for name, value in checkpoint["state_dict"].items() + } + model.load_state_dict(state_dict, strict=True) + del checkpoint, state_dict + model = model.to(device).eval() + + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + queue: list[ + tuple[int, int, float, torch.Tensor, torch.Tensor, torch.Tensor] + ] = [] + + def flush_queue(force: bool = False) -> None: + while len(queue) >= args.reconstruction_batch_size or (force and queue): + batch_size = min(args.reconstruction_batch_size, len(queue)) + records = queue[:batch_size] + del queue[:batch_size] + images = torch.stack([record[3] for record in records]).to(device) + camera = torch.stack([record[4] for record in records]).to(device) + with torch.inference_mode(): + output = model(images, camera, hand_scale=0.2) + batch_joints = output["keypoints3D_cs"].float().cpu().numpy() + batch_vertices = output["mesh_vertices3D_cs"].float().cpu().numpy() + ray_offsets = torch.stack([record[5] for record in records]).numpy() + batch_joints[..., :2] += ( + ray_offsets[:, None] * batch_joints[..., 2:3] + ) + batch_vertices[..., :2] += ( + ray_offsets[:, None] * batch_vertices[..., 2:3] + ) + for local, (frame_index, side, score, _, _, _) in enumerate(records): + if side == 0: + batch_joints[local, :, 0] *= -1.0 + batch_vertices[local, :, 0] *= -1.0 + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images_bgr = [ + cv2.imread( + str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png") + ) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images_bgr): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images_bgr, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + image_rgb = cv2.cvtColor(images_bgr[local], cv2.COLOR_BGR2RGB) + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop, crop_intrinsic, ray_offset = _prepare_crop( + image_rgb, + boxes[choice], + intrinsics[frame_index], + is_left=side == 0, + input_size=args.input_size, + crop_scale=args.crop_scale, + canonical_focal=args.canonical_focal, + generate_patch_image=generate_patch_image, + ) + queue.append( + ( + frame_index, + side, + float(scores[choice]), + crop, + crop_intrinsic, + ray_offset, + ) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"HandDGP detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + handmesh_commit = subprocess.check_output( + [ + "git", + "-C", + str((args.repo / "third_party" / "HandMesh").resolve()), + "rev-parse", + "HEAD", + ], + text=True, + ).strip() + # Decoder upsampling matrices are fixed and repeated along the configured + # batch dimension. Count one copy so the reported model size is invariant + # to inference batch size. + reconstruction_parameters = sum( + parameter[0].numel() + if name.startswith("decoder3d.up_transform.") + else parameter.numel() + for name, parameter in model.named_parameters() + ) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/nianticlabs/HandDGP", + "repository_commit": commit, + "handmesh_repository_commit": handmesh_commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector boxes, per-hand crops", + "training_exposure": "released checkpoint trained only on FreiHAND; no H2O or H2O3D", + "fine_tuning": "not available: official repository contains inference/evaluation only", + "confidence_threshold": args.confidence_threshold, + "crop_scale": args.crop_scale, + "input_size": args.input_size, + "canonical_focal": args.canonical_focal, + "preprocessing": ( + "official square crop and canonical-intrinsics rectification; " + "left hands reflected before the right-hand model and mapped back in camera x" + ), + "camera_policy": ( + "official DGP in a box-centered virtual crop camera; known H2O K " + "maps the crop ray back to raw cam4" + ), + "joint_conversion": "official MPII output already matches H2O/OpenPose convention", + "hand_scale_m": 0.2, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="HandDGP-FreiHAND-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_hawor_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_hawor_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..d65afad091f550bdebc7783b6a1acebccb125a46 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_hawor_h2o.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Run HaWoR's official tracked camera-space hand stage on H2O validation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-left", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--confidence-threshold", type=float, default=0.2) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def contiguous_runs(takes: np.ndarray, frame_ids: np.ndarray) -> list[np.ndarray]: + starts = [0] + for index in range(1, len(frame_ids)): + if takes[index] != takes[index - 1] or frame_ids[index] != frame_ids[index - 1] + 1: + starts.append(index) + starts.append(len(frame_ids)) + return [np.arange(starts[i], starts[i + 1]) for i in range(len(starts) - 1)] + + +def main() -> None: + args = parse_args() + for name in ( + "repo", "checkpoint", "detector", "mano_left", "mano_right", "root", + "manifest", "ground_truth", "output", + ): + setattr(args, name, Path(getattr(args, name)).resolve()) + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + targets = ( + (args.repo / "_DATA" / "data" / "mano" / "MANO_RIGHT.pkl", args.mano_right), + (args.repo / "_DATA" / "data_left" / "mano_left" / "MANO_LEFT.pkl", args.mano_left), + ) + for target, source in targets: + if not target.exists(): + target.symlink_to(source) + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from ultralytics import YOLO + from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + from hawor.utils.process import run_mano, run_mano_left + from hawor.configs import get_config + from hawor.utils.rotation import rotation_matrix_to_angle_axis + from lib.models.hawor import HAWOR + + from foundation_hand.evaluation.sota import GroundTruthBundle + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + all_runs = contiguous_runs(takes, frame_ids) + selected_runs = [ + run for index, run in enumerate(all_runs) + if index % args.num_shards == args.shard_index + ] + selected_mask = np.zeros(count, dtype=bool) + for run in selected_runs: + selected_mask[run] = True + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + enable_legacy_mano_loading() + model_config = args.checkpoint.parent.parent / "model_config.yaml" + config = get_config(str(model_config), update_cachedir=True) + if config.MODEL.BACKBONE.TYPE == "vit" and "BBOX_SHAPE" not in config.MODEL: + config.defrost() + config.MODEL.BBOX_SHAPE = [192, 256] + config.freeze() + model = HAWOR.load_from_checkpoint( + str(args.checkpoint), + strict=False, + cfg=config, + map_location=device, + weights_only=False, + ) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + boxes = np.full((count, 2, 4), np.nan, dtype=np.float32) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for run_number, run_indices in enumerate(selected_runs, start=1): + if getattr(detector, "predictor", None) is not None: + for tracker in getattr(detector.predictor, "trackers", []): + if hasattr(tracker, "reset"): + tracker.reset() + image_paths = [ + args.root / str(takes[index]) / "rgb" / f"{int(frame_ids[index]):06d}.png" + for index in run_indices + ] + for local, image_path in enumerate(image_paths): + image = cv2.imread(str(image_path)) + if image is None: + raise RuntimeError(f"Image decode failure: {image_path}") + with torch.no_grad(): + result = detector.track( + image, + conf=args.confidence_threshold, + persist=True, + verbose=False, + )[0] + result_boxes = result.boxes.xyxy.float().cpu().numpy() + result_classes = result.boxes.cls.long().cpu().numpy() + result_scores = result.boxes.conf.float().cpu().numpy() + frame_index = int(run_indices[local]) + for side in (0, 1): + choices = np.flatnonzero(result_classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(result_scores[choices])]) + boxes[frame_index, side] = result_boxes[choice] + confidence[frame_index, side] = result_scores[choice] + + for side in (0, 1): + available = run_indices[np.isfinite(boxes[run_indices, side]).all(axis=1)] + # The released video pipeline requires two detections, then linearly + # interpolates missing boxes between the first and last detection. + if available.size < 2: + continue + segment = np.arange(int(available[0]), int(available[-1]) + 1) + for coordinate in range(4): + boxes[segment, side, coordinate] = np.interp( + frame_ids[segment], + frame_ids[available], + boxes[available, side, coordinate], + ) + segment_paths = np.asarray([ + str(args.root / str(takes[index]) / "rgb" / f"{int(frame_ids[index]):06d}.png") + for index in segment + ]) + K = intrinsics[int(segment[0])] + focal = float(0.5 * (K[0, 0] + K[1, 1])) + center = np.asarray([K[0, 2], K[1, 2]], dtype=np.float32) + results = model.inference( + segment_paths, + boxes[segment, side], + img_focal=focal, + img_center=center, + device=str(device), + do_flip=(side == 0), + ) + root_rotation = rotation_matrix_to_angle_axis( + results["pred_rotmat"][None, :, 0] + ) + hand_pose = rotation_matrix_to_angle_axis( + results["pred_rotmat"][None, :, 1:] + ) + if side == 0: + root_rotation[..., 1:] *= -1 + hand_pose[..., 1:] *= -1 + # Keep the exact official left/right MANO conversion after canonical + # left-hand input flipping. + if side == 0: + mano_output = run_mano_left( + results["pred_trans"][None, :, 0], + root_rotation, + hand_pose, + betas=results["pred_shape"][None], + ) + else: + mano_output = run_mano( + results["pred_trans"][None, :, 0], + root_rotation, + hand_pose, + betas=results["pred_shape"][None], + ) + joints[segment, side] = mano_output["joints"][0].float().cpu().numpy() + vertices[segment, side] = mano_output["vertices"][0].float().cpu().numpy() + detected[segment, side] = True + print( + f"HaWoR run {run_number}: frames through {int(run_indices[-1]) + 1}/{count}", + flush=True, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + selected_frames = int(selected_mask.sum()) + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "HaWoR", + "scope": "RGB decode + tracked detector + bbox interpolation + temporal reconstruction + MANO conversion", + "frames": selected_frames, + "detected_hand_frames": int(detected[selected_mask].sum()), + "processing_seconds": processing_seconds, + "frames_per_second": selected_frames / processing_seconds, + "temporal_window": 16, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + keys = keys[selected_mask] + takes = takes[selected_mask] + frame_ids = frame_ids[selected_mask] + joints = joints[selected_mask] + vertices = vertices[selected_mask] + detected = detected[selected_mask] + confidence = confidence[selected_mask] + bundle = PredictionBundle( + model_name="HaWoR-camera", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata={ + "official_repository": "https://github.com/ThunderVVV/HaWoR", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "tracked per-hand RGB crops in contiguous 16-frame windows", + "confidence_threshold": args.confidence_threshold, + "temporal": True, + "temporal_window": 16, + "side_assignment": "official tracked detector handedness; highest confidence per side/frame", + "bbox_gap_policy": "official linear interpolation between first/last per-run detections", + "camera_conversion": "official get_trans with H2O fx/fy mean and principal point", + "excluded_for_camera_metrics": ["DROID-SLAM", "Metric3D", "world-space infiller"], + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_pad_hand_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_pad_hand_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb890442b99e6018c5aa3ca6ca6c2cc4d695ed5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_pad_hand_h2o.py @@ -0,0 +1,501 @@ +#!/usr/bin/env python3 +"""Run the released PAD-Hand WiLoR refinement pipeline on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import types +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + load_frame_index, +) +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +MANO_TO_OPENPOSE = np.asarray( + [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20], + dtype=np.int64, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def install_torch_scatter_compat() -> None: + """Provide the single torch-scatter operation used by the released model.""" + + if "torch_scatter" in sys.modules: + return + + def scatter_add( + source: torch.Tensor, + index: torch.Tensor, + dim: int = -1, + out: torch.Tensor | None = None, + dim_size: int | None = None, + ) -> torch.Tensor: + if out is None: + output_shape = list(source.shape) + output_shape[dim] = ( + dim_size if dim_size is not None else int(index.max().item()) + 1 + ) + out = source.new_zeros(output_shape) + index_shape = [1] * source.ndim + index_shape[dim] = index.numel() + expanded_index = index.reshape(index_shape).expand_as(source) + return out.scatter_add_(dim, expanded_index, source) + + module = types.ModuleType("torch_scatter") + module.scatter_add = scatter_add + sys.modules["torch_scatter"] = module + + +def enable_legacy_checkpoint_loading() -> None: + """Restore the pre-PyTorch-2.6 default for trusted official checkpoints.""" + + original_load = torch.load + + def load(*args: Any, **kwargs: Any) -> Any: + kwargs.setdefault("weights_only", False) + return original_load(*args, **kwargs) + + torch.load = load + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--pad-repo", type=Path, required=True) + parser.add_argument("--wilor-repo", type=Path, required=True) + parser.add_argument("--pad-checkpoint", type=Path, required=True) + parser.add_argument("--wilor-checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument("--diffusion-steps", type=int, default=4) + parser.add_argument("--kappa-degrees", type=float, default=15.0) + parser.add_argument("--seed", type=int, default=20260720) + parser.add_argument("--max-takes", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def stable_window_seed(base_seed: int, take: str, side: int, frame_id: int) -> int: + payload = f"{base_seed}|{take}|{side}|{frame_id}".encode("utf-8") + return int.from_bytes(hashlib.sha256(payload).digest()[:8], "little") % (2**31) + + +def contiguous_runs(frame_ids: np.ndarray) -> list[np.ndarray]: + if frame_ids.size == 0: + return [] + boundaries = np.flatnonzero(np.diff(frame_ids) != 1) + 1 + return [part for part in np.split(np.arange(frame_ids.size), boundaries) if part.size] + + +def main() -> None: + args = parse_args() + for name in ( + "pad_repo", + "wilor_repo", + "pad_checkpoint", + "wilor_checkpoint", + "detector", + "mano_right", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + if args.diffusion_steps <= 0: + raise ValueError("--diffusion-steps must be positive") + + required_pad_assets = ( + "processed_MANO_RIGHT.pkl", + "MeshConv_template.ply", + "MeshConv_transform.pkl", + ) + for filename in required_pad_assets: + asset = args.pad_repo / "assets" / filename + if not asset.is_file(): + raise FileNotFoundError(f"Missing released PAD-Hand asset: {asset}") + wilor_mano = args.wilor_repo / "mano_data" / "MANO_RIGHT.pkl" + if not wilor_mano.exists(): + wilor_mano.symlink_to(args.mano_right) + + keys, takes, frame_ids = load_frame_index(args.manifest) + unique_takes = list(dict.fromkeys(map(str, takes.tolist()))) + if args.max_takes is not None: + unique_takes = unique_takes[: args.max_takes] + selected_takes = { + take + for index, take in enumerate(unique_takes) + if index % args.num_shards == args.shard_index + } + selected = np.asarray([str(take) in selected_takes for take in takes], dtype=bool) + keys, takes, frame_ids = keys[selected], takes[selected], frame_ids[selected] + if not len(keys): + raise ValueError("Shard contains no frames") + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + enable_legacy_mano_loading() + enable_legacy_checkpoint_loading() + sys.path.insert(0, str(args.wilor_repo)) + os.chdir(args.wilor_repo) + from ultralytics import YOLO + from wilor.datasets.vitdet_dataset import ViTDetDataset + from wilor.models import load_wilor + + wilor_model, wilor_cfg = load_wilor( + checkpoint_path=str(args.wilor_checkpoint), + cfg_path=str(args.wilor_repo / "pretrained_models" / "model_config.yaml"), + ) + wilor_model = wilor_model.to(device).eval() + detector = YOLO(str(args.detector)).to(device) + + count = len(keys) + relative_joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + relative_vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + cameras = np.full((count, 2, 3), np.nan, dtype=np.float32) + global_orient = np.full((count, 2, 1, 3, 3), np.nan, dtype=np.float32) + hand_pose = np.full((count, 2, 15, 3, 3), np.nan, dtype=np.float32) + betas = np.full((count, 2, 10), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = wilor_model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + record_indices = np.asarray([record[0] for record in records]) + K = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (K[:, 0, 0] + K[:, 1, 1]) + principal = K[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + camera = torch.stack( + ( + pred_cam[:, 1] + + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), + dim=-1, + ).float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + batch_global = ( + output["pred_mano_params"]["global_orient"].float().cpu().numpy() + ) + batch_pose = output["pred_mano_params"]["hand_pose"].float().cpu().numpy() + batch_betas = output["pred_mano_params"]["betas"].float().cpu().numpy() + for local, (frame_index, side, score, _) in enumerate(records): + relative_joints[frame_index, side] = batch_joints[local] + relative_vertices[frame_index, side] = batch_vertices[local] + cameras[frame_index, side] = camera[local] + global_orient[frame_index, side] = batch_global[local] + hand_pose[frame_index, side] = batch_pose[local] + betas[frame_index, side] = batch_betas[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop_dataset = ViTDetDataset( + wilor_cfg, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), crop_dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"PAD-Hand WiLoR initialization {end}/{count}", flush=True) + flush_queue(force=True) + + install_torch_scatter_compat() + sys.path.insert(0, str(args.pad_repo)) + os.chdir(args.pad_repo) + from models.MANO import MANO + from models.difussionsampler import DiffusionSampler + from models.pad_hand import PAD_Hand + from models.utils import batch_euler2matzxy, rotmat2eulerzxy + + pad_model = PAD_Hand( + device=device, + seqlen=16, + decoder=True, + d_model=512, + nhead=8, + d_hid=512, + nlayers=4, + dropout=0.1, + ).to(device) + checkpoint = torch.load(args.pad_checkpoint, map_location=device, weights_only=False) + pad_model.load_state_dict(checkpoint["model"]) + pad_model.eval() + pad_model.mode = "test" + mano = MANO("RIGHT", device) + sampler = DiffusionSampler( + args.diffusion_steps, np.deg2rad(args.kappa_degrees), device + ) + + refined_joints = relative_joints.copy() + refined_vertices = relative_vertices.copy() + refined_windows = 0 + missing_detection_windows = 0 + tail_frames = 0 + initializer_mesh_delta_sum = 0.0 + initializer_mesh_delta_count = 0 + + for take in dict.fromkeys(map(str, takes.tolist())): + take_indices = np.flatnonzero(takes == take) + order = np.argsort(frame_ids[take_indices]) + take_indices = take_indices[order] + take_frame_ids = frame_ids[take_indices] + for run_positions in contiguous_runs(take_frame_ids): + run_indices = take_indices[run_positions] + tail_frames += len(run_indices) % 16 * 2 + for side in (0, 1): + for window_start in range(0, len(run_indices) - 15, 16): + window = run_indices[window_start : window_start + 16] + if not detected[window, side].all(): + missing_detection_windows += 1 + continue + rotmats = np.concatenate( + (global_orient[window, side], hand_pose[window, side]), axis=1 + ) + rotmats_t = torch.from_numpy(rotmats).to(device) + betas_t = torch.from_numpy(betas[window, side]).to(device) + y0_pose = rotmat2eulerzxy(rotmats_t.reshape(-1, 3, 3)).reshape( + 1, 16, 48 + ) + y0_shape = betas_t.unsqueeze(0) + y0_shape_t = y0_shape.reshape(-1, 10) + y0_rotmat = batch_euler2matzxy(y0_pose.reshape(-1, 3))[0].reshape( + -1, 16, 3, 3 + ) + y0_mano = mano.forward(betas=y0_shape_t, thetas_rotmat=y0_rotmat) + y0_vertices = y0_mano.vertices + comparison_vertices = y0_vertices.detach().cpu().numpy().copy() + if side == 0: + comparison_vertices[..., 0] *= -1 + initializer_mesh_delta_sum += float( + np.linalg.norm( + comparison_vertices - relative_vertices[window, side], axis=-1 + ).sum() + ) + initializer_mesh_delta_count += comparison_vertices.shape[0] * 778 + + src_mask = torch.ones((1, 16), dtype=torch.bool, device=device) + x0_pose_pred = y0_pose.clone() + window_seed = stable_window_seed( + args.seed, take, side, int(frame_ids[window[0]]) + ) + torch.manual_seed(window_seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(window_seed) + with torch.no_grad(): + for step in range(args.diffusion_steps, 0, -1): + if step == args.diffusion_steps: + step_batch = torch.full( + (1,), float(args.diffusion_steps), device=device + ) + noisy_pose = y0_pose + np.deg2rad( + args.kappa_degrees + ) * torch.randn_like(y0_pose) + else: + step_batch = torch.full( + (1,), step, device=device, dtype=torch.long + ) + noisy_pose = sampler.q_sample( + x0_pose_pred, y0_pose - x0_pose_pred, step_batch + ) + noisy_rotmat = batch_euler2matzxy( + noisy_pose.reshape(-1, 3) + )[0].reshape(-1, 16, 3, 3) + noisy_mano = mano.forward( + betas=y0_shape_t, thetas_rotmat=noisy_rotmat + ) + _, decoder_prediction = pad_model.forward( + y0_vertices.reshape(1, 16, 778, 3), + noisy_mano.vertices.reshape(1, 16, 778, 3), + step_batch.float(), + src_mask, + mano, + y0_shape_t, + ) + refined_rotmat = decoder_prediction[-2] + refined_mano = decoder_prediction[-1] + x0_pose_pred = rotmat2eulerzxy( + refined_rotmat.reshape(-1, 3, 3) + ).reshape(1, 16, 48) + vertices_out = refined_mano.vertices.detach().cpu().numpy() + joints_out = refined_mano.joints.detach().cpu().numpy()[ + :, MANO_TO_OPENPOSE + ] + if side == 0: + vertices_out[..., 0] *= -1 + joints_out[..., 0] *= -1 + refined_vertices[window, side] = vertices_out + refined_joints[window, side] = joints_out + refined_windows += 1 + + joints_camera = refined_joints + cameras[:, :, None] + vertices_camera = refined_vertices + cameras[:, :, None] + pad_commit = subprocess.check_output( + ["git", "-C", str(args.pad_repo), "rev-parse", "HEAD"], text=True + ).strip() + wilor_commit = subprocess.check_output( + ["git", "-C", str(args.wilor_repo), "rev-parse", "HEAD"], text=True + ).strip() + wilor_parameters = sum(parameter.numel() for parameter in wilor_model.parameters()) + detector_parameters = sum( + parameter.numel() for parameter in detector.model.parameters() + ) + pad_parameters = sum(parameter.numel() for parameter in pad_model.parameters()) + metadata = { + "official_repository": "https://github.com/DominoAI-Lab/PAD-Hand-CVPR-2026", + "repository_commit": pad_commit, + "base_wilor_repository_commit": wilor_commit, + "checkpoint": str(args.pad_checkpoint), + "checkpoint_sha256": sha256(args.pad_checkpoint), + "base_wilor_checkpoint": str(args.wilor_checkpoint), + "base_wilor_checkpoint_sha256": sha256(args.wilor_checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "pad_parameter_count": pad_parameters, + "reconstruction_parameter_count": wilor_parameters + pad_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": ( + wilor_parameters + pad_parameters + detector_parameters + ), + "input": ( + "full RGB detector, per-detection RGB crop WiLoR initialization, " + "per-side non-overlapping 16-frame PAD-Hand diffusion refinement" + ), + "temporal": True, + "temporal_window": 16, + "diffusion_steps": args.diffusion_steps, + "kappa_degrees": args.kappa_degrees, + "sampling_seed": args.seed, + "sampling_seed_policy": "SHA256(base seed, take, side, first frame)", + "refined_windows": refined_windows, + "missing_detection_windows": missing_detection_windows, + "tail_hand_frames_falling_back_to_wilor": tail_frames, + "initializer_mesh_reconstruction_delta_mm": ( + 1000.0 * initializer_mesh_delta_sum / initializer_mesh_delta_count + if initializer_mesh_delta_count + else None + ), + "camera_policy": "h2o_intrinsics", + "camera_conversion": ( + "WiLoR cam_crop_to_full algebra with known H2O focal/principal point; " + "PAD-Hand does not update camera translation" + ), + "side_assignment": "official WiLoR detector handedness; independent PAD-Hand refinement", + "training_exposure": ( + "paper trains on DexYCB/HO3D; released checkpoint does not label its " + "training split; no H2O fine-tuning" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="PAD-Hand-WiLoR-H2O-K", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints_camera, + vertices_camera_m=vertices_camera, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase3_full_validation.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase3_full_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..fd398945a306fb8176703ee7bb83eb8f92f6d408 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase3_full_validation.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python3 +"""Evaluate every registered Phase 3 core checkpoint on official validation.""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import queue +import shlex +import subprocess +import threading +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +VAL_MANIFEST = Path("artifacts/phase2/data_audit/manifests/official_val.jsonl") + + +@dataclass(frozen=True) +class EvaluationJob: + name: str + run_name: str + role: str + config: Path + checkpoint: Path + output: Path + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + output = {} + for line in result.stdout.splitlines(): + index, uuid = (part.strip() for part in line.split(",", 1)) + output[int(index)] = uuid + return output + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if not line.strip(): + continue + uuid, pid = (part.strip() for part in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +DEFAULT_CHECKPOINT_FILES = { + "step_025k": "step_0025000.pt", + "step_050k": "step_0050000.pt", + "step_075k": "step_0075000.pt", + "step_100k": "step_0100000.pt", + "best_absolute": "best.pt", + "best_z": "best_z.pt", + "final": "step_0100000_final.pt", +} + + +def checkpoint_roles( + run_dir: Path, checkpoint_files: dict[str, str] | None = None, +) -> tuple[tuple[str, Path], ...]: + definitions = DEFAULT_CHECKPOINT_FILES if checkpoint_files is None else checkpoint_files + return tuple((role, run_dir / filename) for role, filename in definitions.items()) + + +def load_checkpoint_files(path: Path | None) -> dict[str, str]: + if path is None: + return dict(DEFAULT_CHECKPOINT_FILES) + values = json.loads(path.read_text(encoding="utf-8")) + if ( + not isinstance(values, dict) + or not values + or any(not isinstance(role, str) or not role for role in values) + or any( + not isinstance(filename, str) or Path(filename).name != filename + for filename in values.values() + ) + ): + raise ValueError("checkpoint spec must be a non-empty role-to-filename JSON object") + return values + + +def validation_state_path(output_root: Path, filename: str) -> Path: + if Path(filename).name != filename or not filename.endswith(".json"): + raise ValueError("state filename must be a JSON basename") + return output_root / filename + + +def build_jobs( + matrix_csv: Path, + run_root: Path, + output_root: Path, + roles: tuple[str, ...] | None = None, + checkpoint_files: dict[str, str] | None = None, +) -> list[EvaluationJob]: + available_roles = checkpoint_roles(Path("unused"), checkpoint_files) + selected_roles = set(roles or (role for role, _ in available_roles)) + with matrix_csv.open(newline="", encoding="utf-8") as handle: + matrix_rows = list(csv.DictReader(handle)) + jobs = [] + for row in matrix_rows: + config = Path(row["config"]) + run_name = row.get("run_name") or config.stem + for role, checkpoint in checkpoint_roles(run_root / run_name, checkpoint_files): + if role not in selected_roles: + continue + jobs.append(EvaluationJob( + name=f"{run_name}__{role}", run_name=run_name, role=role, + config=config, checkpoint=checkpoint, + output=output_root / run_name / role, + )) + return jobs + + +def validate_job_grid(jobs: list[EvaluationJob], roles: tuple[str, ...]) -> int: + """Validate one evaluation per run and selected checkpoint role.""" + if not jobs: + raise ValueError("evaluation matrix produced no jobs") + selected_roles = set(roles) + run_names = {job.run_name for job in jobs} + job_keys = {(job.run_name, job.role) for job in jobs} + expected_jobs = len(run_names) * len(selected_roles) + if len(job_keys) != len(jobs): + raise ValueError("evaluation matrix contains duplicate run/checkpoint-role jobs") + if len(jobs) != expected_jobs: + raise ValueError( + f"expected {len(run_names)} runs x {len(selected_roles)} checkpoint roles " + f"= {expected_jobs} jobs, got {len(jobs)}" + ) + return len(run_names) + + +def command_for( + job: EvaluationJob, gpu: int, num_workers: int, + drop_depth: bool = False, drop_k: bool = False, + phase4_diagnostics: bool = False, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/evaluate_phase3.py", + "--config", str(job.config), + "--root", DATA_ROOT, + "--manifest", str(VAL_MANIFEST), + "--checkpoint", str(job.checkpoint), + "--output-dir", str(job.output), + "--gpu", "0", + "--num-workers", str(num_workers), + "--bootstrap-samples", "10000", + "--skip-visualizations", + ] + if drop_depth: + command.append("--drop-depth") + if drop_k: + command.append("--drop-k") + if phase4_diagnostics: + command.append("--phase4-diagnostics") + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def completed_evaluation(path: Path, job: EvaluationJob) -> bool: + report_path = path / "evaluation.json" + if not report_path.is_file(): + return False + try: + report = json.loads(report_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return False + return ( + report.get("status") == "evaluated" + and report.get("official_test_used") is False + and Path(report.get("checkpoint", {}).get("path", "")).resolve() == job.checkpoint.resolve() + and report.get("clips") == 1495 + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + parser.add_argument("--run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--output-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--gpus", default="0,1,2,3,5") + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument("--roles") + parser.add_argument("--checkpoint-spec", type=Path) + parser.add_argument("--drop-depth", action="store_true") + parser.add_argument("--drop-k", action="store_true") + parser.add_argument("--phase4-diagnostics", action="store_true") + parser.add_argument("--state-filename", default="validation_state.json") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + if VAL_MANIFEST.name != "official_val.jsonl": + parser.error("full validation launcher is hard-gated to official_val.jsonl") + if args.num_workers < 0: + parser.error("--num-workers must be non-negative") + try: + state_path = validation_state_path(args.output_root, args.state_filename) + except ValueError as error: + parser.error(str(error)) + + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + known_gpus = gpu_uuid_map() + unknown = sorted(set(gpus) - set(known_gpus)) + if unknown: + parser.error(f"unknown GPU indices: {unknown}") + + try: + checkpoint_files = load_checkpoint_files(args.checkpoint_spec) + except (OSError, json.JSONDecodeError, ValueError) as error: + parser.error(str(error)) + known_roles = tuple(checkpoint_files) + roles = ( + known_roles if args.roles is None + else tuple(value.strip() for value in args.roles.split(",") if value.strip()) + ) + unknown_roles = sorted(set(roles) - set(known_roles)) + if not roles or unknown_roles: + parser.error(f"invalid --roles; selected={roles}, unknown={unknown_roles}") + jobs = build_jobs( + args.matrix_csv, args.run_root, args.output_root, roles, checkpoint_files, + ) + try: + run_count = validate_job_grid(jobs, roles) + except ValueError as error: + parser.error(str(error)) + missing_configs = sorted({str(job.config) for job in jobs if not job.config.is_file()}) + missing_checkpoints = sorted({str(job.checkpoint) for job in jobs if not job.checkpoint.is_file()}) + if missing_configs or missing_checkpoints: + parser.error(json.dumps({ + "missing_configs": missing_configs, + "missing_checkpoints": missing_checkpoints, + }, indent=2)) + if args.dry_run: + print(json.dumps({ + "runs": run_count, "jobs": len(jobs), "gpus": gpus, "roles": roles, + "official_test_used": False, + "first_command": shlex.join(command_for( + jobs[0], gpus[0], args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + )[0]), + "last_command": shlex.join(command_for( + jobs[-1], gpus[-1], args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + )[0]), + "drop_depth": args.drop_depth, "drop_k": args.drop_k, + "phase4_diagnostics": args.phase4_diagnostics, + "state_file": str(state_path), + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + work: queue.Queue[EvaluationJob] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "manifest": str(VAL_MANIFEST), + "roles": roles, "official_test_used": False, "jobs": {}, + "checkpoint_spec": str(args.checkpoint_spec) if args.checkpoint_spec else None, + "drop_depth": args.drop_depth, "drop_k": args.drop_k, + "phase4_diagnostics": args.phase4_diagnostics, + "state_file": str(state_path), + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for job in jobs: + if completed_evaluation(job.output, job): + state["jobs"][job.name] = { + "status": "skipped_completed", "output": str(job.output), + "checkpoint": str(job.checkpoint), "role": job.role, + } + continue + if job.output.exists() and any(job.output.iterdir()): + state["jobs"][job.name] = { + "status": "blocked_existing_incomplete", "output": str(job.output), + "checkpoint": str(job.checkpoint), "role": job.role, + } + stop_launching.set() + continue + work.put(job) + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + job = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for( + job, gpu, args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + ) + log_path = log_root / f"{job.name}.log" + with state_lock: + state["jobs"][job.name] = { + "status": "running", "run": job.run_name, "role": job.role, + "config": str(job.config), "checkpoint": str(job.checkpoint), + "gpu": gpu, "gpu_uuid": gpu_uuid, "started_utc": utc_now(), + "output": str(job.output), "log": str(log_path), + "command": shlex.join(command), + } + persist() + job.output.mkdir(parents=True, exist_ok=False) + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][job.name]["pid"] = process.pid + persist() + return_code = process.wait() + valid_output = completed_evaluation(job.output, job) + with state_lock: + state["jobs"][job.name].update({ + "status": "completed" if return_code == 0 and valid_output else "failed", + "return_code": return_code, "output_validated": valid_output, + "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0 or not valid_output: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,), name=f"gpu-{gpu}") for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [ + name for name, record in state["jobs"].items() + if record["status"] in {"failed", "blocked_existing_incomplete"} + ] + state["status"] = "failed" if failed else "completed" + state["finished_utc"] = utc_now() + state["failed_jobs"] = failed + state["remaining_queue"] = work.qsize() + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase3_matrix.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase3_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..9e84d3da6831ce5604a00315099bb13709db6c57 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase3_matrix.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Run a pre-registered Phase 3 config queue on explicitly allowed idle GPUs.""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import queue +import shlex +import subprocess +import threading +import time +from datetime import datetime, timezone +from pathlib import Path + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +TRAIN_MANIFEST = "artifacts/phase2/data_audit/manifests/official_train.jsonl" +VAL_MANIFEST = "artifacts/phase2/data_audit/manifests/official_val.jsonl" +VAL_SUBSET = "artifacts/phase3/validation_subset/validation_subset_256.json" + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + output = {} + for line in result.stdout.splitlines(): + index, uuid = (part.strip() for part in line.split(",", 1)) + output[int(index)] = uuid + return output + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if not line.strip(): + continue + uuid, pid = (part.strip() for part in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +def command_for( + config: Path, + output_dir: Path, + gpu: int, + resume: Path | None = None, + validation_subset: Path | str = VAL_SUBSET, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/train_experiment.py", + "--config", str(config), + "--root", DATA_ROOT, + "--manifest", TRAIN_MANIFEST, + "--val-manifest", VAL_MANIFEST, + "--validation-subset-manifest", str(validation_subset), + "--output-dir", str(output_dir), + "--max-steps", "100000", + "--num-workers", "4", + "--checkpoint-interval", "25000", + "--validation-interval", "5000", + "--validation-batches", "256", + "--learning-rate", "5e-5", + "--min-learning-rate", "5e-6", + "--warmup-steps", "500", + "--early-stopping-patience", "0", + ] + if resume is not None: + command.extend(("--resume", str(resume))) + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + parser.add_argument("--output-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--gpus", default="0,1,2,3,5") + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--resume-root", type=Path) + parser.add_argument("--resume-step", type=int, default=75_000) + parser.add_argument( + "--validation-subset-manifest", type=Path, default=Path(VAL_SUBSET), + ) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + known_gpus = gpu_uuid_map() + unknown = sorted(set(gpus) - set(known_gpus)) + if unknown: + parser.error(f"unknown GPU indices: {unknown}") + + with args.matrix_csv.open(newline="", encoding="utf-8") as handle: + configs = [Path(row["config"]) for row in csv.DictReader(handle)] + missing = [str(path) for path in configs if not path.is_file()] + if missing: + parser.error(f"missing configs: {missing}") + jobs = [ + ( + config, + args.output_root / config.stem, + ( + args.resume_root / config.stem / f"step_{args.resume_step:07d}.pt" + if args.resume_root is not None else None + ), + ) + for config in configs + ] + missing_resume = [str(resume) for _, _, resume in jobs if resume and not resume.is_file()] + if missing_resume: + parser.error(f"missing resume checkpoints: {missing_resume}") + if args.dry_run: + print(json.dumps({ + "jobs": len(jobs), "gpus": gpus, + "commands": [ + shlex.join(command_for( + config, output, gpus[index % len(gpus)], resume, + args.validation_subset_manifest, + )[0]) + for index, (config, output, resume) in enumerate(jobs) + ], + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + state_path = args.output_root / "matrix_state.json" + work: queue.Queue[tuple[Path, Path, Path | None]] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "jobs": {}, + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for config, output, resume in jobs: + summary = output / "summary.json" + if summary.is_file() and json.loads(summary.read_text(encoding="utf-8")).get("status") == "completed": + state["jobs"][config.stem] = {"status": "skipped_completed", "output": str(output)} + continue + if output.exists() and any(output.iterdir()): + state["jobs"][config.stem] = { + "status": "blocked_existing_incomplete", "output": str(output), + } + stop_launching.set() + continue + work.put((config, output, resume)) + + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + config, output, resume = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for( + config, output, gpu, resume, args.validation_subset_manifest, + ) + log_path = log_root / f"{config.stem}.log" + with state_lock: + state["jobs"][config.stem] = { + "status": "running", "gpu": gpu, "gpu_uuid": gpu_uuid, + "started_utc": utc_now(), "output": str(output), + "log": str(log_path), "command": shlex.join(command), + "resume_checkpoint": str(resume) if resume is not None else None, + } + persist() + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][config.stem]["pid"] = process.pid + persist() + return_code = process.wait() + with state_lock: + state["jobs"][config.stem].update({ + "status": "completed" if return_code == 0 else "failed", + "return_code": return_code, "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,), name=f"gpu-{gpu}") for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [name for name, record in state["jobs"].items() if record["status"] in {"failed", "blocked_existing_incomplete"}] + state["status"] = "failed" if failed else "completed" + state["finished_utc"] = utc_now() + state["failed_jobs"] = failed + state["remaining_queue"] = work.qsize() + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase4_a3_matrix.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase4_a3_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..277b30257fd62aa997b6837b566ef7af2b34fe65 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase4_a3_matrix.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Run the preregistered Phase 4 A3 formal matrix on explicitly allowed GPUs.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import queue +import shlex +import subprocess +import threading +from datetime import datetime, timezone +from pathlib import Path + +import yaml + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +TRAIN_MANIFEST = "artifacts/phase2/data_audit/manifests/official_train.jsonl" +VAL_MANIFEST = "artifacts/phase2/data_audit/manifests/official_val.jsonl" +VAL_SUBSET = ( + "artifacts/phase3/validation_subset/resolution_640x368/" + "validation_subset_256.json" +) +EXPECTED_SEEDS = {20260716, 20260717, 20260718} +MODE_SLUGS = { + "oracle_rgb": "rgb", + "oracle_depth_k": "depth_k", + "oracle_rgb_depth_k": "rgb_depth_k", +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + return { + int(index.strip()): uuid.strip() + for line in result.stdout.splitlines() + for index, uuid in [line.split(",", 1)] + } + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + [ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid", + "--format=csv,noheader,nounits", + ], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if line.strip(): + uuid, pid = (value.strip() for value in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +def load_jobs( + matrix_csv: Path, + config_root: Path, + output_root: Path, +) -> list[dict[str, object]]: + with matrix_csv.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + observed = {(int(row["seed"]), row["mode"]) for row in rows} + expected = {(seed, mode) for seed in EXPECTED_SEEDS for mode in MODE_SLUGS} + if len(rows) != 9 or observed != expected: + raise ValueError("A3 formal matrix must contain exactly three modes x three seeds") + + jobs = [] + for row in rows: + seed = int(row["seed"]) + mode = row["mode"] + if row["stage"] != "formal" or int(row["max_steps"]) != 100_000: + raise ValueError("A3 matrix contains a non-formal or non-100k row") + if row["gt_location"] != "True" or row["official_test_used"] != "False": + raise ValueError("A3 formal matrix violates oracle/test-isolation contract") + config = config_root / Path(row["config"]).name + checkpoint = Path(row["initialization_checkpoint"]) + if not config.is_file() or not checkpoint.is_file(): + raise FileNotFoundError(f"missing A3 config/checkpoint: {config}, {checkpoint}") + if file_sha256(checkpoint) != row["initialization_checkpoint_sha256"]: + raise ValueError(f"initialization checkpoint hash mismatch for seed {seed}") + config_record = yaml.safe_load(config.read_text(encoding="utf-8")) + experiment = config_record.get("experiment", {}) + if ( + int(config_record["seed"]) != seed + or config_record["name"] != row["name"] + or experiment.get("oracle_crop_mode") != mode + or experiment.get("coarse_checkpoint_sha256") + != row["initialization_checkpoint_sha256"] + ): + raise ValueError(f"matrix/config mismatch for {config}") + jobs.append({ + "name": row["name"], + "seed": seed, + "mode": mode, + "config": config, + "checkpoint": checkpoint, + "output": output_root / row["name"], + }) + return jobs + + +def command_for( + job: dict[str, object], gpu: int, validation_subset: Path, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/train_experiment.py", + "--config", str(job["config"]), + "--root", DATA_ROOT, + "--manifest", TRAIN_MANIFEST, + "--val-manifest", VAL_MANIFEST, + "--validation-subset-manifest", str(validation_subset), + "--output-dir", str(job["output"]), + "--max-steps", "100000", + "--num-workers", "4", + "--checkpoint-interval", "25000", + "--validation-interval", "5000", + "--validation-batches", "256", + "--learning-rate", "5e-5", + "--min-learning-rate", "5e-6", + "--lr-schedule-steps", "100000", + "--warmup-steps", "500", + "--early-stopping-patience", "0", + "--init-checkpoint", str(job["checkpoint"]), + ] + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, required=True) + parser.add_argument( + "--config-root", type=Path, default=Path("configs/phase4/a3_oracle_crop"), + ) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--gpus", default="0,1,2,3,4,5") + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--validation-subset-manifest", type=Path, default=Path(VAL_SUBSET), + ) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + if not gpus or len(gpus) != len(set(gpus)): + parser.error("--gpus must contain unique GPU indices") + known_gpus = gpu_uuid_map() + if set(gpus) - set(known_gpus): + parser.error("--gpus contains an unknown GPU index") + if not args.validation_subset_manifest.is_file(): + parser.error("fixed validation subset is missing") + jobs = load_jobs(args.matrix_csv, args.config_root, args.output_root) + if args.dry_run: + print(json.dumps({ + "status": "dry_run", "jobs": len(jobs), "gpus": gpus, + "commands": [ + shlex.join(command_for(job, gpus[index % len(gpus)], args.validation_subset_manifest)[0]) + for index, job in enumerate(jobs) + ], + "official_test_used": False, + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + state_path = args.output_root / "matrix_state.json" + work: queue.Queue[dict[str, object]] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "official_test_used": False, "jobs": {}, + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for job in jobs: + output = job["output"] + summary = output / "summary.json" + if summary.is_file() and json.loads(summary.read_text(encoding="utf-8")).get("status") == "completed": + state["jobs"][job["name"]] = { + "status": "skipped_completed", "output": str(output), + } + elif output.exists() and any(output.iterdir()): + state["jobs"][job["name"]] = { + "status": "blocked_existing_incomplete", "output": str(output), + } + stop_launching.set() + else: + work.put(job) + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + job = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for(job, gpu, args.validation_subset_manifest) + log_path = log_root / f"{job['name']}.log" + with state_lock: + state["jobs"][job["name"]] = { + "status": "running", "gpu": gpu, "gpu_uuid": gpu_uuid, + "started_utc": utc_now(), "output": str(job["output"]), + "log": str(log_path), "command": shlex.join(command), + } + persist() + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][job["name"]]["pid"] = process.pid + persist() + return_code = process.wait() + with state_lock: + state["jobs"][job["name"]].update({ + "status": "completed" if return_code == 0 else "failed", + "return_code": return_code, "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,)) for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [ + name for name, record in state["jobs"].items() + if record["status"] in {"failed", "blocked_existing_incomplete"} + ] + state.update({ + "status": "failed" if failed else "completed", + "finished_utc": utc_now(), "failed_jobs": failed, + "remaining_queue": work.qsize(), + }) + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_adaptation_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_adaptation_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c94ba7f43f0ea64e794d451c852510a306db20e6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_adaptation_eval_queue.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Evaluate H2O adaptation checkpoints on frozen train-heldout groups.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_split") != "h2o_train_group_heldout_only" + ): + raise ValueError("adaptation evaluation queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("adaptation evaluation queue is empty") + for item in queue["evaluations"]: + if Path(item["cache_manifest"]).name != "train_group_heldout.jsonl": + raise ValueError("adaptation evaluation must use train_group_heldout.jsonl") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_train_group_heldout" + and report.get("evaluation_role") == "h2o_train_group_heldout" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("h2o_training_data_used") is True + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item.get("input_mode", "rgb_d_k"), + "--evaluation-role", "h2o_train_group_heldout", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty adaptation evaluation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_adaptation_forgetting_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_adaptation_forgetting_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa5b7a46bc6f95f83b75eb328abef01a86875a1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_adaptation_forgetting_queue.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Evaluate H2O-adapted checkpoints on frozen external held-out caches.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_use") is not False + or queue.get("evaluation_split") != "external_heldout_forgetting_diagnostic_only" + ): + raise ValueError("adaptation forgetting queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("adaptation forgetting queue is empty") + for item in queue["evaluations"]: + if "h2o" in str(item["cache_manifest"]).lower(): + raise ValueError("adaptation forgetting queue refuses H2O cache paths") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_adaptation_external_heldout" + and report.get("evaluation_role") == "adaptation_external_heldout" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("h2o_training_data_used") is True + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--evaluation-role", "adaptation_external_heldout", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "selection_use": False, "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty forgetting evaluation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_adaptation_train_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_adaptation_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff2769a01a27e87301e9a37028692b23f43a562 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_adaptation_train_queue.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 7 H2O adaptation stages on idle GPUs 0-3.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_train_queue import ( + atomic_json, + cache_report_ready, + idle_gpu, + sha256, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def stage_marker(item: dict[str, Any]) -> Path: + return Path(item["output_dir"]) / ".phase7_queue" / f"{item['id']}.json" + + +def completed_matches(item: dict[str, Any]) -> bool: + marker_path = stage_marker(item) + if not marker_path.is_file(): + return False + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and int(marker.get("completed_step", -1)) == int(item["stop_after_step"]) + and marker.get("config_sha256") == item["config_sha256"] + and marker.get("h2o_training_data_used") is True + and marker.get("h2o_official_validation_used") is False + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", item["config"], "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(item["stop_after_step"]), + ] + if item.get("resume_checkpoint") is not None: + command.extend(("--resume", item["resume_checkpoint"])) + elif item.get("resume_from_step") is not None: + resume = Path(item["output_dir"]) / f"step_{int(item['resume_from_step']):07d}_final.pt" + command.extend(("--resume", str(resume))) + elif not item.get("neutral_start", False): + command.extend(("--init-checkpoint", item["init_checkpoint"])) + return command + + +def validate_stage_inputs(item: dict[str, Any]) -> None: + config = Path(item["config"]) + if not config.is_file() or sha256(config) != item["config_sha256"]: + raise RuntimeError(f"frozen config missing or SHA mismatch: {config}") + output = Path(item["output_dir"]) + resume_checkpoint = item.get("resume_checkpoint") + resume_step = item.get("resume_from_step") + if resume_checkpoint is not None: + resume = Path(resume_checkpoint) + if ( + not resume.is_file() + or sha256(resume) != item.get("resume_checkpoint_sha256") + ): + raise RuntimeError(f"explicit resume checkpoint is missing or has a SHA mismatch: {resume}") + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"explicit-resume adaptation output is not empty: {output}") + elif resume_step is None and item.get("neutral_start", False): + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new neutral-control output is not empty: {output}") + elif resume_step is None: + initialization = Path(item["init_checkpoint"]) + if ( + not initialization.is_file() + or sha256(initialization) != item["init_checkpoint_sha256"] + ): + raise RuntimeError(f"frozen initialization missing or SHA mismatch: {initialization}") + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new adaptation output is not empty: {output}") + else: + resume = output / f"step_{int(resume_step):07d}_final.pt" + if not resume.is_file(): + raise RuntimeError(f"resume checkpoint is missing: {resume}") + + +def write_stage_marker(item: dict[str, Any], gpu: int) -> dict[str, Any]: + output = Path(item["output_dir"]) + summary = json.loads((output / "summary.json").read_text(encoding="utf-8")) + step = int(item["stop_after_step"]) + checkpoint = output / f"step_{step:07d}_final.pt" + if ( + int(summary.get("completed_step", -1)) != step + or summary.get("h2o_training_data_used") is not True + or summary.get("official_test_used") is not False + or not checkpoint.is_file() + ): + raise RuntimeError(f"adaptation summary failed stage contract: {item['id']}") + marker = { + "status": "complete", "id": item["id"], "completed_utc": utc_now(), + "completed_step": step, "physical_gpu_id": gpu, + "config": str(Path(item["config"]).resolve()), + "config_sha256": item["config_sha256"], + "checkpoint": str(checkpoint.resolve()), "checkpoint_sha256": sha256(checkpoint), + "wall_seconds": summary.get("wall_seconds"), + "gpu_hours": summary.get("gpu_hours"), + "frames_per_second": summary.get("frames_per_second"), + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + marker_path = stage_marker(item) + marker_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(marker_path, marker) + return marker + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + ): + parser.error("adaptation queue exposure flags are not explicit and valid") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_caches", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": [0, 1, 2, 3], + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + while not all(cache_report_ready(item) for item in queue["required_caches"]): + state["status"] = "waiting_for_caches" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + for index, item in enumerate(queue["stages"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + validate_stage_inputs(item) + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + command = training_command(item, gpu) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0: + marker = write_stage_marker(item, gpu) + state["completed_ids"].append(item["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + break + state["status"] = "failed_non_resource" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["stages"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_external_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_external_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..a41353ff9900a376e42d6fd5e72a03b55d48a27c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_external_eval_queue.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Wait for idle GPU0-3 slots and run a frozen Phase 7 evaluation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def completed_matches(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("official_test_used") is False + and report.get("h2o_training_data_used") is False + and ( + item.get("cache_manifest_sha256") is None + or report.get("cache_manifest", {}).get("sha256") == item["cache_manifest_sha256"] + ) + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], + "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 1000)), + ] + if item.get("cache_manifest_sha256") is not None: + command.extend(( + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + )) + return command + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + # A second observation narrows the race with non-FoundationHand users. + time.sleep(1.0) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if queue.get("official_test_used") is not False: + parser.error("queue must explicitly set official_test_used=false") + items = queue["evaluations"] + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + state["status"] = "running" + for index, item in enumerate(items): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["updated_utc"] = utc_now() + state["waiting_for_idle_gpu"] = True + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + state["waiting_for_idle_gpu"] = False + output_dir = Path(item["output_dir"]) + if output_dir.exists() and any(output_dir.iterdir()): + state["status"] = "failed_existing_output" + state["failure"] = { + "id": item["id"], "reason": f"nonempty output: {output_dir}", + } + atomic_json(args.state, state) + raise SystemExit(1) + command = evaluator_command(item, gpu) + attempt = { + "id": item["id"], "gpu": gpu, "start_utc": utc_now(), + "command": command, + } + state["attempts"].append(attempt) + atomic_json(args.state, state) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + attempt["log"] = str(log_path.resolve()) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + break + tail = log_path.read_text(encoding="utf-8", errors="replace")[-4096:] + if ( + "is not idle" in tail + and (not output_dir.exists() or not any(output_dir.iterdir())) + ): + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_non_resource" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(items) + state["updated_utc"] = utc_now() + state["waiting_for_idle_gpu"] = False + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_external_train_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_external_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..7d97cea3b8039b51ace8f9e31f76e944c5001e83 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_external_train_queue.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 7 external scale stages when caches and GPUs are ready.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def cache_report_ready(item: dict[str, Any]) -> bool: + report_path = Path(item["report"]) + manifest_path = Path(item["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + clip_count = report.get("clips", report.get("cached_clips")) + recorded_manifest = report.get("cache_manifest", {}) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(clip_count or -1) == int(item["expected_clips"]) + and Path(recorded_manifest.get("path", "")).resolve() == manifest_path.resolve() + and recorded_manifest.get("sha256") == sha256(manifest_path) + ) + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1.0) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def stage_marker(item: dict[str, Any]) -> Path: + return Path(item["output_dir"]) / ".phase7_queue" / f"{item['id']}.json" + + +def completed_matches(item: dict[str, Any]) -> bool: + marker_path = stage_marker(item) + if not marker_path.is_file(): + return False + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and int(marker.get("completed_step", -1)) == int(item["stop_after_step"]) + and marker.get("config_sha256") == item["config_sha256"] + and marker.get("h2o_training_data_used") is False + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", item["config"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(item["stop_after_step"]), + ] + resume_step = item.get("resume_from_step") + if resume_step is not None: + resume = Path(item["output_dir"]) / f"step_{int(resume_step):07d}_final.pt" + command.extend(("--resume", str(resume))) + if item.get("allow_schedule_tail") is True: + command.append("--allow-schedule-tail") + return command + + +def validate_stage_inputs(item: dict[str, Any]) -> None: + config = Path(item["config"]) + if not config.is_file() or sha256(config) != item["config_sha256"]: + raise RuntimeError(f"frozen config missing or SHA mismatch: {config}") + resume_step = item.get("resume_from_step") + output = Path(item["output_dir"]) + if resume_step is None: + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new-stage output is not empty: {output}") + else: + resume = output / f"step_{int(resume_step):07d}_final.pt" + if not resume.is_file(): + raise RuntimeError(f"resume checkpoint is missing: {resume}") + expected_resume_sha = item.get("resume_checkpoint_sha256") + if expected_resume_sha is not None and sha256(resume) != expected_resume_sha: + raise RuntimeError(f"resume checkpoint SHA256 mismatch: {resume}") + + +def write_stage_marker(item: dict[str, Any], gpu: int) -> dict[str, Any]: + output = Path(item["output_dir"]) + summary = json.loads((output / "summary.json").read_text(encoding="utf-8")) + step = int(item["stop_after_step"]) + checkpoint = output / f"step_{step:07d}_final.pt" + if ( + int(summary.get("completed_step", -1)) != step + or summary.get("h2o_training_data_used") is not False + or summary.get("official_test_used") is not False + or not checkpoint.is_file() + ): + raise RuntimeError(f"training summary did not satisfy stage contract: {item['id']}") + marker = { + "status": "complete", "id": item["id"], "completed_utc": utc_now(), + "completed_step": step, "physical_gpu_id": gpu, + "config": str(Path(item["config"]).resolve()), + "config_sha256": item["config_sha256"], + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": sha256(checkpoint), + "wall_seconds": summary.get("wall_seconds"), + "gpu_hours": summary.get("gpu_hours"), + "frames_per_second": summary.get("frames_per_second"), + "schedule_tail_enabled": summary.get("schedule_tail_enabled", False), + "schedule_tail_learning_rate": summary.get("schedule_tail_learning_rate"), + "h2o_training_data_used": False, "official_test_used": False, + } + marker_path = stage_marker(item) + marker_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(marker_path, marker) + return marker + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if queue.get("official_test_used") is not False: + parser.error("queue must explicitly set official_test_used=false") + if queue.get("h2o_training_data_used") is not False: + parser.error("queue must explicitly set h2o_training_data_used=false") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_caches", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), + "h2o_training_data_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + + while not all(cache_report_ready(item) for item in queue["required_caches"]): + state["status"] = "waiting_for_caches" + state["updated_utc"] = utc_now() + state["ready_caches"] = [ + item["id"] for item in queue["required_caches"] if cache_report_ready(item) + ] + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + for index, item in enumerate(queue["stages"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + try: + validate_stage_inputs(item) + except RuntimeError as error: + state["status"] = "failed_input_contract" + state["failure"] = {"id": item["id"], "reason": str(error)} + atomic_json(args.state, state) + raise SystemExit(str(error)) + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + command = training_command(item, gpu) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0: + marker = write_stage_marker(item, gpu) + state["completed_ids"].append(item["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + break + tail = log_path.read_text(encoding="utf-8", errors="replace")[-4096:] + output = Path(item["output_dir"]) + if "is not idle" in tail and (not output.exists() or not any(output.iterdir())): + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_non_resource_or_partial_output" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + + state["status"] = "complete" + state["current_index"] = len(queue["stages"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_h2o_adapted_validation_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_h2o_adapted_validation_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a3d4e4f667ade06aec102d29481ffdde764ac9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_h2o_adapted_validation_queue.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Run a frozen three-mode H2O validation package for an adapted checkpoint.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_split") != "h2o_train_group_heldout_only" + or queue.get("h2o_official_validation_used_for_selection") is not False + ): + raise ValueError("adapted validation exposure flags are invalid") + items = queue.get("evaluations", []) + if {item.get("input_mode") for item in items} != set(INPUT_MODES) or len(items) != 3: + raise ValueError("adapted validation queue requires exactly three unique input modes") + if len({item.get("checkpoint_sha256") for item in items}) != 1: + raise ValueError("adapted validation modes must use one frozen checkpoint") + if len({item.get("freeze_record") for item in items}) != 1: + raise ValueError("adapted validation modes must use one freeze record") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_adapted_formal" + and report.get("evaluation_role") == "h2o_adapted_formal" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is True + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--freeze-record", item["freeze_record"], "--root", item["root"], + "--manifest", item["manifest"], "--input-mode", item["input_mode"], + "--evaluation-role", "h2o_adapted_formal", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty adapted validation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_h2o_zero_shot_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_h2o_zero_shot_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9916057aef5704cf28f9a5084d7b3e2bc821cdc0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_h2o_zero_shot_queue.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Run the frozen three-mode strict H2O zero-shot evaluation package.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_training_data_used") is not False + or queue.get("h2o_official_validation_used_for_external_selection") is not False + ): + raise ValueError("strict zero-shot exposure flags are invalid") + items = queue.get("evaluations", []) + if {item.get("input_mode") for item in items} != set(INPUT_MODES) or len(items) != 3: + raise ValueError("strict zero-shot queue requires exactly three unique input modes") + if len({item.get("checkpoint_sha256") for item in items}) != 1: + raise ValueError("strict zero-shot modes must use one frozen checkpoint") + if len({item.get("manifest") for item in items}) != 1: + raise ValueError("strict zero-shot modes must use one frozen validation manifest") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_strict_h2o_zero_shot" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is False + and report.get("h2o_official_validation_used_for_external_selection") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--freeze-record", item["freeze_record"], "--root", item["root"], + "--manifest", item["manifest"], "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "official_test_used": False, "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty zero-shot output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_heldout_cache_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_heldout_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..2163297840a13304a2b53d0503dc025a689c1d1e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase7_heldout_cache_queue.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Launch formal external held-out caches as their train caches complete.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import shlex +import subprocess +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def dependency_ready(item: dict[str, Any]) -> bool: + report_path = Path(item["dependency"]) + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + count = report.get("clips", report.get("cached_clips", 0)) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(count) >= 10000 + ) + + +def output_complete(item: dict[str, Any]) -> bool: + output = Path(item["output_dir"]) + report_path = output / "cache_report.json" + manifest_path = output / "cache_manifest.jsonl" + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + cache_manifest = report.get("cache_manifest", {}) + expected_recordings = item.get("physical_recordings") + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(report.get("clips", report.get("cached_clips", 0))) == 2048 + and report.get("source_manifest", {}).get("sha256") == item["source_manifest_sha256"] + and Path(cache_manifest.get("path", "")).resolve() == manifest_path.resolve() + and cache_manifest.get("sha256") == sha256(manifest_path) + and ( + expected_recordings is None + or int(report.get("recordings", -1)) == int(expected_recordings) + ) + ) + + +def command_tokens(command: str) -> tuple[list[str], dict[str, str]]: + tokens = shlex.split(command) + environment = dict(os.environ) + while tokens and "=" in tokens[0] and not tokens[0].startswith("-"): + key, value = tokens.pop(0).split("=", 1) + if key != "PYTHONPATH": + raise ValueError(f"unexpected command environment assignment: {key}") + environment[key] = str((Path.cwd() / value).resolve()) + if not tokens: + raise ValueError("cache command is empty") + return tokens, environment + + +def process_alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except (ProcessLookupError, PermissionError): + return False + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False or plan.get("h2o_used") is not False: + parser.error("held-out cache plan must be external-only and non-test") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_train_caches", "plan": str(args.plan.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), "completed_ids": [], + "active": {}, "attempts": [], "official_test_used": False, "h2o_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan") != str(args.plan.resolve()): + parser.error("existing state belongs to a different plan") + state = previous + pending = {item["dataset"]: item for item in plan["sources"]} + processes: dict[str, subprocess.Popen[str]] = {} + while len(state["completed_ids"]) < len(pending): + for dataset, item in pending.items(): + if dataset in state["completed_ids"]: + continue + if output_complete(item): + state["completed_ids"].append(dataset) + state["active"].pop(dataset, None) + atomic_json(args.state, state) + continue + active = state["active"].get(dataset) + if active and process_alive(int(active["pid"])): + continue + if not dependency_ready(item): + continue + output = Path(item["output_dir"]) + command_key = "resume_command" if output.exists() else "start_command" + command, environment = command_tokens(item[command_key]) + log_path = args.state.parent / f"heldout_cache_{dataset.lower()}.log" + attempt = { + "dataset": dataset, "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), "mode": command_key, + } + state["attempts"].append(attempt) + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, + ) + processes[dataset] = process + state["active"][dataset] = {"pid": process.pid, "log": str(log_path.resolve())} + state["status"] = "running" + atomic_json(args.state, state) + finished = [] + for dataset, active in list(state["active"].items()): + process = processes.get(dataset) + if process is not None: + returncode = process.poll() + if returncode is None: + continue + state["active"][dataset]["returncode"] = returncode + processes.pop(dataset) + elif process_alive(int(active["pid"])): + continue + # A completed report is validated on the next loop. A dead process + # without one is retained as a failure rather than silently retried. + item = pending[dataset] + if output_complete(item): + finished.append(dataset) + else: + state["status"] = "failed_incomplete_output" + state["failure"] = {"dataset": dataset, "log": active["log"]} + atomic_json(args.state, state) + raise SystemExit(1) + for dataset in finished: + if dataset not in state["completed_ids"]: + state["completed_ids"].append(dataset) + state["active"].pop(dataset, None) + state["updated_utc"] = utc_now() + state["ready_dependencies"] = [ + dataset for dataset, item in pending.items() if dependency_ready(item) + ] + atomic_json(args.state, state) + if len(state["completed_ids"]) < len(pending): + time.sleep(args.poll_seconds) + state["status"] = "complete" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase8_egodexter_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase8_egodexter_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9d96eeb623ad017721160ed288970aa05e10ae3a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase8_egodexter_queue.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Run a frozen EgoDexter queue on atomically claimed physical GPU0-3.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("egodexter_used_for_training_or_selection") is not False + or not queue.get("evaluations") + ): + raise ValueError("EgoDexter queue boundary flags are invalid") + expected = { + (mode, input_mode) + for mode in ("offline", "causal") + for input_mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + actual = { + (item.get("inference_mode"), item.get("input_mode")) + for item in queue["evaluations"] + } + if actual != expected or len(queue["evaluations"]) != len(expected): + raise ValueError("EgoDexter queue must contain the exact six-condition grid") + if {item.get("model_id") for item in queue["evaluations"]} != {queue.get("model_id")}: + raise ValueError("EgoDexter queue mixes model IDs") + + +def completed_matches(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_frozen_egodexter_zero_shot" + and report.get("model_id") == item["model_id"] + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("inference_mode") == item["inference_mode"] + and report.get("egodexter_used_for_training_or_selection") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_egodexter_zero_shot", + "--model-id", item["model_id"], + "--freeze-record", item["freeze_record"], + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--root", item["root"], "--input-mode", item["input_mode"], + "--inference-mode", item["inference_mode"], + "--window", str(item.get("window", 8)), + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists(): + raise RuntimeError(f"EgoDexter output already exists: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase8_h2o_control_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase8_h2o_control_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..6106550a604d35b15aecabb34d29f911e7f8d1c9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase8_h2o_control_eval_queue.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Run hash-bound H2O train-heldout controls without changing their provenance.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("selection_split") != "h2o_train_group_heldout_only" + ): + raise ValueError("H2O control queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("H2O control queue is empty") + for item in queue["evaluations"]: + if Path(item["cache_manifest"]).name != "train_group_heldout.jsonl": + raise ValueError("H2O control must use train_group_heldout.jsonl") + if not isinstance(item.get("expected_h2o_training_data_used"), bool): + raise ValueError("control item must freeze expected H2O provenance") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_train_group_heldout_control" + and report.get("evaluation_role") == "h2o_train_group_heldout_control" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is item["expected_h2o_training_data_used"] + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--evaluation-role", "h2o_train_group_heldout_control", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty H2O control output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode != 0 or not completed_matches(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(item["id"]) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_data_finalize_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_data_finalize_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..8d1a4cd4bc05e33467e6e5aa5cf12294d155a053 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_data_finalize_queue.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Wait for Phase 9 base caches, then freeze subsets and left sidecars.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def base_cache_ready(item: dict[str, Any]) -> bool: + manifest = Path(item["manifest"]) + report_path = Path(item["report"]) + if not manifest.is_file() or not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(manifest) + ): + return False + if item["dataset"] == "HOT3D": + return int(report.get("clips", -1)) == int(item["expected_clips"]) + return ( + report.get("accept_all_valid") is True + and report.get("all_eligible_processed") is True + and int(report.get("cached_valid_clips", 0)) > 0 + ) + + +def artifact_complete(item: dict[str, Any]) -> bool: + report_path = Path(item["report"]) + manifest = Path(item["manifest"]) + if not report_path.is_file() or not manifest.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + key = "augmented_cache_manifest" if item["kind"] == "left_sidecar" else "cache_manifest" + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get(key, {}).get("sha256") == sha256(manifest) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("finalize plan must explicitly exclude official test") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_data_finalize_state_v1", + "status": "waiting_for_base_caches", + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "started_utc": utc_now(), + "updated_utc": utc_now(), + "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != sha256(args.plan): + parser.error("existing state is bound to a different plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + base_caches = {item["dataset"]: item for item in plan["base_caches"]} + for item in plan["artifacts"]: + if artifact_complete(item): + continue + prerequisite = base_caches[item["requires_base_cache"]] + while not base_cache_ready(prerequisite): + state["status"] = "waiting_for_base_cache" + state["current_artifact"] = item["id"] + state["waiting_for_dataset"] = item["requires_base_cache"] + state["ready_base_caches"] = [ + dataset for dataset, base in base_caches.items() + if base_cache_ready(base) + ] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = [str(value) for value in item["command"]] + if item["kind"] == "left_sidecar": + base_manifest = Path(item["base_cache_manifest"]) + command = [ + value.replace("{BASE_CACHE_SHA256}", sha256(base_manifest)) + for value in command + ] + if (Path(item["output_dir"]) / "sidecars").is_dir(): + command.append("--resume") + log_path = Path(item["log"]) + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "id": item["id"], "start_utc": utc_now(), + "command": command, "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_artifact"] = item["id"] + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode or not artifact_complete(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "returncode": result.returncode} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["artifacts"] = [{ + "id": item["id"], "manifest": item["manifest"], + "manifest_sha256": sha256(item["manifest"]), + "report": item["report"], "report_sha256": sha256(item["report"]), + } for item in plan["artifacts"]] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_distributed_resolution_cache_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_distributed_resolution_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9e349530aae1d53571708b4637ace42ed029b9e5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_distributed_resolution_cache_queue.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Enforce distributed cache ownership before entering the existing queue.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import sys + +from scripts.phase9_distributed_assignment import detect_machine, load_assignment + + +CACHE_OWNERS = { + "h2o": "taku3", + "hot3d": "server_new", + "hoi4d": "taku3", + "arctic": "taku3", +} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--assignment-sha256", required=True) + parser.add_argument("--worker", choices=tuple(CACHE_OWNERS), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + assignment = load_assignment({"distributed_assignment": { + "path": str(args.assignment.resolve()), + "sha256": args.assignment_sha256, + }}) + machine = detect_machine(assignment, None) + if CACHE_OWNERS[args.worker] != machine: + parser.error(f"cache worker {args.worker} is owned by {CACHE_OWNERS[args.worker]}") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + matches = [item for item in plan["workers"] if item["id"] == args.worker] + if ( + len(matches) != 1 + or Path(matches[0]["state"]).resolve() != args.state.resolve() + or plan.get("official_test_used") is not False + ): + parser.error("distributed cache worker plan/state differs") + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_cache_queue", + "--plan", str(args.plan.resolve()), "--worker", args.worker, + "--state", str(args.state.resolve()), + "--poll-seconds", str(args.poll_seconds), + ] + os.execv(sys.executable, command) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_expanded_coverage_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_expanded_coverage_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c69ac4d00155e8221d06fc56dc05c3fd3890b3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_expanded_coverage_queue.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Run frozen source-coverage audits after Phase 9 data finalization.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import readiness_complete + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def audit_complete(item: dict[str, Any]) -> bool: + output = Path(item["output"]) + if not output.is_file(): + return False + report = json.loads(output.read_text(encoding="utf-8")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("cache_manifest", {}).get("sha256") == sha256(item["cache_manifest"]) + and report.get("source_manifest", {}).get("sha256") == sha256(item["source_manifest"]) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("coverage plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_expanded_coverage_state_v1", + "status": "waiting_for_data", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "updated_utc": utc_now(), "completed_ids": [], "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing coverage state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not readiness_complete(plan): + state["status"] = "waiting_for_data" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + for item in plan["audits"]: + if audit_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + continue + output = Path(item["output"]) + if output.exists(): + raise RuntimeError(f"incomplete coverage output already exists: {output}") + command = [ + sys.executable, "-m", "scripts.audit_phase9_source_coverage", + "--dataset", item["dataset"], + "--source-manifest", item["source_manifest"], + "--cache-manifest", item["cache_manifest"], + "--output", item["output"], + ] + log_path = args.state.parent / f"expanded_coverage_{item['dataset'].lower()}.log" + attempt = { + "id": item["id"], "start_utc": utc_now(), + "command": command, "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not audit_complete(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_external_milestone_eval.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_external_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..6b01ab8a3b01110cdfecc246e0022914527b06f1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_external_milestone_eval.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Evaluate Phase 9 unified milestone checkpoints on native external held-outs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3, 4, 5) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def stable_checkpoint_sha256( + path: str | Path, + *, + stable_seconds: float = 2.0, + poll_seconds: float = 0.25, + timeout_seconds: float = 300.0, +) -> str: + """Hash a checkpoint only after a non-atomic torch.save has quiesced.""" + checkpoint = Path(path) + started = time.monotonic() + previous = (checkpoint.stat().st_size, checkpoint.stat().st_mtime_ns) + stable_since = time.monotonic() + while True: + if time.monotonic() - started > timeout_seconds: + raise TimeoutError(f"checkpoint did not stabilize: {checkpoint}") + time.sleep(poll_seconds) + before = checkpoint.stat() + signature = (before.st_size, before.st_mtime_ns) + if signature != previous: + previous = signature + stable_since = time.monotonic() + continue + if time.monotonic() - stable_since < stable_seconds: + continue + digest = sha256(checkpoint) + after = checkpoint.stat() + if (after.st_size, after.st_mtime_ns) == signature: + return digest + previous = (after.st_size, after.st_mtime_ns) + stable_since = time.monotonic() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def checkpoint_path(condition: dict[str, Any], checkpoint: dict[str, Any]) -> Path | None: + run = Path(condition["run_dir"]) + if checkpoint["kind"] == "final": + path = run / f"step_{int(checkpoint['step']):07d}_final.pt" + return path if path.is_file() else None + matches = sorted(run.glob(f"milestone_{checkpoint['milestone_id']}_step_*.pt")) + if len(matches) > 1: + raise RuntimeError(f"multiple checkpoint files for milestone {checkpoint['milestone_id']}") + return matches[0] if matches else None + + +def evaluation_complete( + output_dir: Path, checkpoint_hash: str, manifest_hash: str, input_mode: str, +) -> bool: + path = output_dir / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_phase9_external_heldout" + and report.get("evaluation_role") == "phase9_external_heldout" + and report.get("checkpoint", {}).get("sha256") == checkpoint_hash + and report.get("cache_manifest", {}).get("sha256") == manifest_hash + and report.get("input_mode") == input_mode + and report.get("h2o_training_data_used") is True + and report.get("official_test_used") is False + ) + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def evaluator_command( + condition: dict[str, Any], checkpoint: Path, checkpoint_hash: str, + source: dict[str, Any], gpu: int, output: Path, +) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", condition["config"], + "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", source["cache_manifest"], + "--expected-cache-manifest-sha256", source["cache_manifest_sha256"], + "--input-mode", source["input_mode"], + "--output-dir", str(output), + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(source.get("bootstrap_resamples", 2000)), + "--evaluation-role", "phase9_external_heldout", + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--condition", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + registry = json.loads(args.registry.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + parser.error("registry must explicitly exclude official test") + conditions = {item["condition"]: item for item in registry["conditions"]} + if args.condition not in conditions: + parser.error("unknown condition") + condition = conditions[args.condition] + config = Path(condition["config"]) + if not config.is_file() or sha256(config) != condition["config_sha256"]: + parser.error("frozen config is missing or changed") + for source in registry["sources"]: + manifest = Path(source["cache_manifest"]) + if not manifest.is_file() or sha256(manifest) != source["cache_manifest_sha256"]: + parser.error(f"held-out manifest is missing or changed: {source['id']}") + registry_hash = sha256(args.registry) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_external_milestone_eval_state_v1", + "status": "waiting_for_checkpoint", "condition": args.condition, + "registry": str(args.registry.resolve()), "registry_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("registry_sha256") != registry_hash: + parser.error("existing state is bound to another registry version") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for checkpoint_spec in condition["checkpoints"]: + while True: + checkpoint = checkpoint_path(condition, checkpoint_spec) + if checkpoint is not None: + break + state["status"] = "waiting_for_checkpoint" + state["waiting_for"] = checkpoint_spec["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for source in registry["sources"]: + evaluation_id = f"{args.condition}_{checkpoint_spec['id']}_{source['id']}" + output = Path(registry["evaluation_root"]) / args.condition / checkpoint_spec["id"] / source["id"] + if evaluation_complete( + output, checkpoint_hash, source["cache_manifest_sha256"], source["input_mode"], + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + continue + while True: + gpu = idle_gpu() + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + if output.exists() and any(output.iterdir()): + release_physical_gpu_claim(gpu) + state["status"] = "failed_existing_output" + state["failure"] = {"id": evaluation_id, "output": str(output)} + atomic_json(args.state, state) + raise SystemExit(1) + command = evaluator_command( + condition, checkpoint, checkpoint_hash, source, gpu, output, + ) + log_path = args.state.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not evaluation_complete( + output, checkpoint_hash, source["cache_manifest_sha256"], source["input_mode"], + ): + state["status"] = "failed" + state["failure"] = {"id": evaluation_id, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_final_deployment_controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_final_deployment_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..a64e86ece28d0bcd9b90218507b54ae5ab7ae529 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_final_deployment_controller.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +"""Wait for final selection, then supervise formal validation and deployment audits.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + if ( + plan.get("schema_version") != "phase9_final_deployment_controller_plan_v1" + or plan.get("job_count") != 11 or plan.get("worker_count") != 4 + or plan.get("allowed_physical_gpus") != [0, 1, 2, 3] + or plan.get("official_validation_checkpoint_count") != 1 + or plan.get("h2o_official_validation_used_for_selection") is not False + or plan.get("official_test_used") is not False + ): + raise ValueError("final deployment controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"final deployment binding differs: {path}") + + +def final_decision_ready(plan: dict[str, Any]) -> bool: + state_path = Path(plan["last2_finalizer_state"]) + if not state_path.is_file(): + return False + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["last2_finalizer_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and report_path.is_file() + and state.get("decision_report", {}).get("sha256") == sha256(report_path) + and report_path.resolve() == Path(plan["last2_final_decision"]).resolve() + ) + + +def worker_status(path: Path, plan_hash: str) -> str: + if not path.is_file(): + return "missing" + state = read_json(path) + if state.get("plan_sha256") != plan_hash: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def pid_matches(pid: int, worker: str, dynamic_plan: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_final_deployment_worker" in command + and f"--worker {worker}" in command + and str(dynamic_plan.resolve()) in command + ) + + +def launch_worker(dynamic_plan: Path, worker: dict[str, Any], log_path: Path) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_final_deployment_worker", + "--plan", str(dynamic_plan.resolve()), "--worker", worker["id"], + "--state", worker["state"], + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def run_command(command: list[str], state: dict[str, Any], state_path: Path, label: str) -> None: + state["status"] = label + state[f"{label}_command"] = command + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = f"failed_{label}" + state[f"{label}_returncode"] = result.returncode + atomic_json(state_path, state) + raise SystemExit(result.returncode) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["controller_state"]).resolve(): + parser.error("final deployment controller state differs") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_final_deployment_controller_state_v1", + "status": "waiting_for_final_selection", "started_utc": utc_now(), + "updated_utc": utc_now(), "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "workers": {}, + "h2o_official_validation_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing final deployment controller state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not final_decision_ready(plan): + state["status"] = "waiting_for_final_selection" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + freeze = Path(plan["freeze"]) + freeze_command = [ + sys.executable, "-m", "scripts.freeze_phase9_final_deployment", + "--selection-plan", plan["selection_plan"], + "--selection-state", plan["selection_state"], + "--stage8-plan", plan["stage8_plan"], + "--stage8-state", plan["stage8_state"], + "--last2-plan", plan["last2_finalizer_plan"], + "--last2-state", plan["last2_finalizer_state"], + "--validation-manifest", plan["validation_manifest"], + "--validation-manifest-sha256", plan["validation_manifest_sha256"], + "--training-manifest", plan["training_manifest"], + "--training-manifest-sha256", plan["training_manifest_sha256"], + "--output", str(freeze), "--state", plan["freeze_state"], + ] + run_command(freeze_command, state, args.state, "freezing_final_checkpoint") + freeze_state = read_json(plan["freeze_state"]) + if ( + freeze_state.get("status") != "complete" or not freeze.is_file() + or freeze_state.get("freeze_sha256") != sha256(freeze) + ): + state["status"] = "failed_freeze_binding" + atomic_json(args.state, state) + raise SystemExit(1) + + dynamic_plan = Path(plan["dynamic_plan"]) + dynamic_command = [ + sys.executable, "-m", "scripts.build_phase9_final_deployment_plan", + "--freeze", str(freeze), "--freeze-state", plan["freeze_state"], + "--output-root", plan["output_root"], + "--worker-state-root", plan["worker_state_root"], + "--causal-config", plan["causal_config"], + "--h2o-root", plan["h2o_root"], + "--output", str(dynamic_plan), "--state", plan["dynamic_plan_state"], + ] + run_command(dynamic_command, state, args.state, "building_deployment_plan") + dynamic_state = read_json(plan["dynamic_plan_state"]) + if ( + dynamic_state.get("status") != "complete" or not dynamic_plan.is_file() + or dynamic_state.get("plan_sha256") != sha256(dynamic_plan) + ): + state["status"] = "failed_dynamic_plan_binding" + atomic_json(args.state, state) + raise SystemExit(1) + dynamic_hash = sha256(dynamic_plan) + dynamic = read_json(dynamic_plan) + state["dynamic_plan_sha256"] = dynamic_hash + state.setdefault("workers", {}) + while True: + statuses = {} + for worker in dynamic["workers"]: + path = Path(worker["state"]) + status = worker_status(path, dynamic_hash) + statuses[worker["id"]] = status + if status == "complete" or status.startswith("failed"): + continue + previous_pid = int(state["workers"].get(worker["id"], {}).get("pid", -1)) + if not pid_matches(previous_pid, worker["id"], dynamic_plan): + pid = launch_worker( + dynamic_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(status.startswith("failed") for status in statuses.values()): + state["status"] = "failed_deployment_worker" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = "running_post_selection_audits" + state["h2o_official_validation_used"] = True + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + report = Path(plan["summary_report"]) + if not report.is_file(): + run_command([ + sys.executable, "-m", "scripts.summarize_phase9_final_deployment", + "--plan", str(dynamic_plan), "--output", str(report), + ], state, args.state, "summarizing_deployment") + summary = read_json(report) + if ( + summary.get("status") != "complete" + or summary.get("deployment_contract", {}).get("passed") is not True + or summary.get("h2o_official_validation_used_for_selection") is not False + or summary.get("official_test_used") is not False + ): + state["status"] = "failed_deployment_summary" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["summary_report"] = {"path": str(report.resolve()), "sha256": sha256(report)} + state["checkpoint"] = summary["checkpoint"] + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["h2o_official_validation_used"] = True + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_final_deployment_worker.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_final_deployment_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ad40a896ea1c75803d879094f935440c2aae9c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_final_deployment_worker.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Run one disjoint final deployment worker with resumable output validation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_artifact(record: dict[str, Any]) -> bool: + path = Path(record.get("path", "")) + return path.is_file() and record.get("sha256") == sha256(path) + + +def completed_matches(job: dict[str, Any]) -> bool: + kind = job["kind"] + path = ( + Path(job["output_dir"]) / "evaluation.json" + if kind == "formal_validation" else Path(job["output"]) + ) + if not path.is_file(): + return False + try: + report = read_json(path) + except (OSError, json.JSONDecodeError): + return False + common = ( + report.get("checkpoint", {}).get("sha256") == job["checkpoint_sha256"] + and report.get("config", {}).get("sha256") == job["config_sha256"] + and report.get("manifest", {}).get("sha256") == job["manifest_sha256"] + and report.get("official_test_used") is False + ) + if not common: + return False + report_step = report.get("checkpoint", {}).get( + "step", report.get("checkpoint_step") + ) + if int(report_step if report_step is not None else -1) != job["checkpoint_step"]: + return False + if kind == "formal_validation": + return ( + report.get("status") == "evaluated_phase9_unified_formal" + and report.get("evaluation_role") == "phase9_unified_formal" + and report.get("input_mode") == job["input_mode"] + and report.get("freeze_record", {}).get("sha256") + == job["freeze_record_sha256"] + and report.get("h2o_official_validation_used") is True + and report.get("h2o_official_validation_used_for_selection") is False + and report.get("h2o_training_data_used") is True + and all(validate_artifact(report[key]) for key in ( + "raw_predictions", "per_hand_rows", "take_metrics", + )) + ) + if kind == "variable_length": + results = report.get("forward_results", []) + return ( + report.get("status") == "completed" + and report.get("official_validation_used") is True + and [item.get("T") for item in results] == job["lengths"] + and all(item.get("all_finite") is True for item in results) + ) + if kind == "sequence": + bounded = ( + int(report.get("maximum_gpu_window_frames", 10**9)) <= job["window"] + and int(report.get("maximum_cpu_input_buffer_frames", 10**9)) + <= (job["window"] if job["mode"] == "causal" else 12) + ) + causal = report.get("invariance") + causal_ok = job["mode"] != "causal" or ( + isinstance(causal, dict) + and causal.get("future_perturbation_bitwise_zero") is True + and causal.get("prefix_passed") is True + ) + mode_ok = ( + report.get("causal") is (job["mode"] == "causal") + and report.get("offline_stride") + == (None if job["mode"] == "causal" else 4) + and report.get("stitching") + == (None if job["mode"] == "causal" else "center") + ) + return ( + report.get("status") == "passed" + and report.get("mode") == job["mode"] + and report.get("window") == job["window"] + and report.get("requested_frames") == job["frames"] + and report.get("output_frames") == job["frames"] + and report.get("frame_ids_strictly_increasing") is True + and report.get("finite") is True + and report.get("official_validation_used_for_selection") is False + and bounded and causal_ok and mode_ok + ) + if kind == "profile": + latency = report.get("latency", {}) + return ( + report.get("status") == "profiled" + and report.get("official_validation_used") is False + and report.get("input", {}).get("resolution_hw") == job["resolution_hw"] + and float(latency.get("p50_ms", 0)) > 0 + and float(latency.get("p95_ms", 0)) > 0 + and float(report.get("peak_allocated_vram_gib", 0)) > 0 + ) + return False + + +def command(job: dict[str, Any]) -> list[str]: + common = ["--config", job["config"], "--checkpoint", job["checkpoint"]] + if job["kind"] == "formal_validation": + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + *common, "--expected-checkpoint-sha256", job["checkpoint_sha256"], + "--freeze-record", job["freeze_record"], "--root", job["root"], + "--manifest", job["manifest"], "--input-mode", job["input_mode"], + "--evaluation-role", "phase9_unified_formal", + "--output-dir", job["output_dir"], "--physical-gpu-id", + str(job["physical_gpu_id"]), "--bootstrap-resamples", "2000", + ] + if job["kind"] == "variable_length": + return [ + sys.executable, "-m", "scripts.audit_phase6_variable_length", + *common, "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--gpu", str(job["physical_gpu_id"]), + "--repeats", "2", + ] + if job["kind"] == "sequence": + return [ + sys.executable, "-m", "scripts.audit_phase6_sequence_inference", + *common, "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--mode", job["mode"], + "--window", str(job["window"]), "--frames", str(job["frames"]), + "--gpu", str(job["physical_gpu_id"]), + ] + if job["kind"] == "profile": + return [ + sys.executable, "-m", "scripts.profile_phase5_model", + *common, "--expected-checkpoint-sha256", job["checkpoint_sha256"], + "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--gpu", str(job["physical_gpu_id"]), + "--warmup", "20", "--iterations", "100", + ] + raise ValueError(f"unknown final deployment job kind: {job['kind']}") + + +def output_target(job: dict[str, Any]) -> Path: + return Path(job.get("output", job.get("output_dir", ""))) + + +def archive_incomplete(job: dict[str, Any]) -> str | None: + target = output_target(job) + if not target.exists(): + return None + recovery = target.parent / "recovery" + recovery.mkdir(parents=True, exist_ok=True) + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + destination = recovery / f"{target.name}.{stamp}.incomplete" + suffix = 0 + while destination.exists(): + suffix += 1 + destination = recovery / f"{target.name}.{stamp}.{suffix}.incomplete" + shutil.move(str(target), str(destination)) + return str(destination.resolve()) + + +def validate_plan(plan: dict[str, Any], worker: dict[str, Any]) -> dict[str, dict[str, Any]]: + if ( + plan.get("status") != "frozen_ready_post_selection" + or plan.get("official_validation_checkpoint_count") != 1 + or plan.get("h2o_official_validation_used_for_selection") is not False + or plan.get("official_test_used") is not False + or worker.get("physical_gpu_id") not in {0, 1, 2, 3} + ): + raise ValueError("final deployment worker contract differs") + jobs = {job["id"]: job for job in plan["jobs"]} + if len(jobs) != 11 or any(identifier not in jobs for identifier in worker["job_ids"]): + raise ValueError("final deployment worker jobs differ") + if any(jobs[identifier]["physical_gpu_id"] != worker["physical_gpu_id"] for identifier in worker["job_ids"]): + raise ValueError("final deployment worker GPU assignment differs") + return jobs + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + worker = next((item for item in plan["workers"] if item["id"] == args.worker), None) + if worker is None: + parser.error("unknown final deployment worker") + try: + jobs = validate_plan(plan, worker) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("final deployment worker state differs") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_final_deployment_worker_state_v1", + "status": "running", "worker": args.worker, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing final deployment worker state differs") + if state.get("status") == "complete": + invalid = [ + identifier for identifier in worker["job_ids"] + if not completed_matches(jobs[identifier]) + ] + if invalid: + state["status"] = "failed_completed_output_binding" + state["failure"] = {"invalid_completed_ids": invalid} + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + print(json.dumps(state, indent=2)) + return + for identifier in worker["job_ids"]: + job = jobs[identifier] + target = output_target(job) + lock_path = Path(f"{target}.lock") + lock_path.parent.mkdir(parents=True, exist_ok=True) + with lock_path.open("a+", encoding="utf-8") as output_lock: + fcntl.flock(output_lock.fileno(), fcntl.LOCK_EX) + if completed_matches(job): + if identifier not in state["completed_ids"]: + state["completed_ids"].append(identifier) + atomic_json(args.state, state) + continue + archived = archive_incomplete(job) + attempt = { + "id": identifier, "kind": job["kind"], + "physical_gpu_id": job["physical_gpu_id"], + "start_utc": utc_now(), "command": command(job), + } + log_path = args.state.parent / f"{identifier}.log" + attempt["log"] = str(log_path.resolve()) + if archived: + attempt["archived_incomplete_output"] = archived + state["current_id"] = identifier + state["status"] = "running" + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ) + if job["kind"] == "formal_validation": + environment["CUDA_VISIBLE_DEVICES"] = str(job["physical_gpu_id"]) + else: + environment.pop("CUDA_VISIBLE_DEVICES", None) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + attempt["command"], cwd=Path.cwd(), env=environment, + stdout=log, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not completed_matches(job): + state["status"] = "failed_job" + state["failure"] = {"id": identifier, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(identifier) + atomic_json(args.state, state) + state["status"] = "complete" + state["current_id"] = None + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_fold_milestone_eval.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_fold_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..bae92c4c4151e059eb56207d37420d72fa6d3dbe --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_fold_milestone_eval.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +"""Evaluate H2O-bearing milestones for Phase 9 group-CV replicas.""" + +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any, Iterator + +import yaml + +from scripts.run_phase9_fold_shard import fold_evaluation_complete +from scripts.run_phase9_external_milestone_eval import stable_checkpoint_sha256 +from scripts.run_phase9_unified_train_queue import parse_physical_gpu_ids +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3, 4, 5) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def h2o_milestones(config: dict[str, Any]) -> list[str]: + return [ + str(milestone["id"]) + for milestone in config["protocol"].get("source_exposure_milestones", []) + if "H2O" in milestone.get("minimum_batches", {}) + ] + + +def milestone_checkpoint(run_dir: Path, milestone_id: str) -> Path | None: + matches = sorted(run_dir.glob(f"milestone_{milestone_id}_step_*.pt")) + if len(matches) > 1: + raise RuntimeError(f"multiple checkpoints found for milestone {milestone_id}") + return matches[0] if matches else None + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +@contextmanager +def exclusive_evaluation_output(output: Path) -> Iterator[None]: + output.parent.mkdir(parents=True, exist_ok=True) + lock_path = output.parent / f".{output.name}.phase9-evaluation.lock" + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(lock.fileno(), fcntl.LOCK_UN) + + +def recovery_assignment( + plan_path: Path, worker_id: str, registry_hash: str, +) -> tuple[dict[str, Any], str]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + raise ValueError("recovery plan must explicitly exclude official test") + if plan.get("registry_sha256") != registry_hash: + raise ValueError("recovery plan registry SHA256 differs") + matches = [item for item in plan["workers"] if item["id"] == worker_id] + if len(matches) != 1: + raise ValueError(f"recovery worker must be unique: {worker_id}") + return matches[0], sha256(plan_path) + + +def evaluation_command( + config_path: Path, checkpoint: Path, checkpoint_hash: str, + heldout: Path, heldout_hash: str, mode: str, output: Path, gpu: int, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", str(config_path), "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", str(heldout), + "--expected-cache-manifest-sha256", heldout_hash, + "--input-mode", mode, "--output-dir", str(output), + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", "phase9_h2o_fold_heldout", + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--shard", type=int, choices=(0, 1, 2), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--recovery-plan", type=Path) + parser.add_argument("--worker-id") + args = parser.parse_args() + registry = json.loads(args.registry.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + parser.error("fold registry must explicitly exclude official test") + conditions = {item["condition"]: item for item in registry["conditions"]} + assigned = registry["shards"][str(args.shard)] + registry_hash = sha256(args.registry) + selected_ids: set[str] | None = None + recovery_plan_hash: str | None = None + if (args.recovery_plan is None) != (args.worker_id is None): + parser.error("--recovery-plan and --worker-id must be provided together") + if args.recovery_plan is not None: + try: + worker, recovery_plan_hash = recovery_assignment( + args.recovery_plan, args.worker_id, registry_hash, + ) + except (KeyError, TypeError, ValueError) as error: + parser.error(str(error)) + if int(worker["shard"]) != args.shard: + parser.error("recovery worker shard differs") + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("recovery worker state path differs") + if tuple(worker["allowed_physical_gpus"]) != args.allowed_physical_gpus: + parser.error("recovery worker GPU assignment differs") + selected_ids = set(worker["evaluation_ids"]) + if len(selected_ids) != len(worker["evaluation_ids"]): + parser.error("recovery worker contains duplicate evaluation IDs") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_fold_milestone_eval_state_v1", + "status": "waiting_for_checkpoint", "shard": args.shard, + "registry": str(args.registry.resolve()), "registry_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(args.allowed_physical_gpus), + "official_test_used": False, + } + if recovery_plan_hash is not None: + state.update({ + "recovery_plan": str(args.recovery_plan.resolve()), + "recovery_plan_sha256": recovery_plan_hash, + "recovery_worker_id": args.worker_id, + "assigned_evaluation_ids": sorted(selected_ids), + "resource_amendment": "gpu_4_5_evaluator_authorization_only_20260730", + }) + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("registry_sha256") != registry_hash: + parser.error("existing state belongs to another registry") + if recovery_plan_hash is not None and ( + previous.get("recovery_plan_sha256") != recovery_plan_hash + or previous.get("recovery_worker_id") != args.worker_id + or set(previous.get("assigned_evaluation_ids", [])) != selected_ids + or tuple(previous.get("allowed_physical_gpus", ())) + != args.allowed_physical_gpus + ): + parser.error("existing recovery state belongs to another assignment") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for condition_id in assigned: + condition = conditions[condition_id] + config_path = Path(condition["config"]) + if sha256(config_path) != condition["config_sha256"]: + parser.error(f"fold config hash differs: {condition_id}") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + heldout = Path(config["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + run_dir = Path(condition["output_dir"]) + for milestone_id in h2o_milestones(config): + milestone_ids = { + f"{condition_id}_{milestone_id}_{mode}" + for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + if selected_ids is not None and not (milestone_ids & selected_ids): + continue + while True: + checkpoint = milestone_checkpoint(run_dir, milestone_id) + if checkpoint is not None: + break + state["status"] = "waiting_for_checkpoint" + state["waiting_for"] = f"{condition_id}:{milestone_id}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + evaluation_id = f"{condition_id}_{milestone_id}_{mode}" + if selected_ids is not None and evaluation_id not in selected_ids: + continue + output = args.output_root / condition_id / milestone_id / mode + if fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + continue + with exclusive_evaluation_output(output): + if fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + continue + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty incomplete output: {output}") + while True: + gpu = idle_gpu(args.allowed_physical_gpus) + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = evaluation_command( + config_path, checkpoint, checkpoint_hash, + heldout, heldout_hash, mode, output, gpu, + ) + log_path = args.state.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + state["status"] = "failed" + state["failure"] = { + "id": evaluation_id, "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + if selected_ids is not None and not selected_ids.issubset(state["completed_ids"]): + missing = sorted(selected_ids - set(state["completed_ids"])) + parser.error(f"recovery assignment contains unknown IDs: {missing}") + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_fold_overflow.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_fold_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..348d8b3162e8c54d6a313eb7961b75b243c63ab6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_fold_overflow.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 9 fold conditions early on otherwise idle capacity.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def prerequisite_states_complete(plan: dict[str, Any]) -> bool: + for item in plan["prerequisite_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("overflow plan must explicitly exclude official test") + registry = Path(plan["fold_training_registry"]) + if sha256(registry) != plan["fold_training_registry_sha256"]: + parser.error("fold training registry SHA256 differs") + registry_payload = json.loads(registry.read_text(encoding="utf-8")) + registered = {item["condition"] for item in registry_payload["conditions"]} + if not plan["conditions"] or any(item not in registered for item in plan["conditions"]): + parser.error("overflow condition is not in the frozen fold registry") + + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + state: dict[str, Any] = { + "schema_version": "phase9_fold_overflow_state_v1", + "status": "waiting_for_prerequisites", + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "started_utc": utc_now(), + "updated_utc": utc_now(), + "completed_conditions": [], + "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing overflow state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + + while not prerequisite_states_complete(plan): + state["status"] = "waiting_for_prerequisites" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + child_root = Path(plan["child_state_root"]) + child_root.mkdir(parents=True, exist_ok=True) + for condition in plan["conditions"]: + if condition in state["completed_conditions"]: + continue + child_state = child_root / f"{condition.lower()}.json" + command = [ + sys.executable, + "-m", + "scripts.run_phase9_unified_train_queue", + "--queue", + str(registry), + "--condition", + condition, + "--state", + str(child_state), + "--poll-seconds", + str(args.poll_seconds), + "--allowed-physical-gpus", + str(plan["physical_gpu_id"]), + ] + log_path = args.state.parent / f"overflow_{condition.lower()}.log" + attempt = { + "condition": condition, + "start_utc": utc_now(), + "command": command, + "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "running_condition" + state["current_condition"] = condition + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, + stdout=log, + stderr=subprocess.STDOUT, + text=True, + check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode: + state["status"] = "failed_resumable" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_conditions"].append(condition) + atomic_json(args.state, state) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_fold_shard.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_fold_shard.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6b518537959a2149496efd6fae0f33badb5dc7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_fold_shard.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Run a shard of Phase 9 H2O group-CV replicas and formal fold evaluations.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) +from scripts.run_phase9_unified_train_queue import parse_physical_gpu_ids + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def main_training_complete(plan: dict[str, Any]) -> bool: + for item in plan["main_training_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def main_training_gate_satisfied( + plan: dict[str, Any], start_before_main_complete: bool, +) -> bool: + return start_before_main_complete or main_training_complete(plan) + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def fold_evaluation_complete( + output: Path, checkpoint_hash: str, manifest_hash: str, mode: str, +) -> bool: + report_path = output / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_phase9_h2o_fold_heldout" + and report.get("evaluation_role") == "phase9_h2o_fold_heldout" + and report.get("checkpoint", {}).get("sha256") == checkpoint_hash + and report.get("cache_manifest", {}).get("sha256") == manifest_hash + and report.get("input_mode") == mode + and report.get("official_test_used") is False + ) + + +def run_fold_evaluations( + condition: dict[str, Any], state: dict[str, Any], state_path: Path, + evaluation_root: Path, poll_seconds: float, + allowed_gpus: tuple[int, ...] = ALLOWED_GPUS, +) -> None: + step = int(condition["stages"][-1]["stop_after_step"]) + checkpoint = Path(condition["output_dir"]) / f"step_{step:07d}_final.pt" + checkpoint_hash = sha256(checkpoint) + config = Path(condition["config"]) + config_payload = __import__("yaml").safe_load(config.read_text(encoding="utf-8")) + heldout = Path(config_payload["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + output = evaluation_root / condition["condition"] / mode + evaluation_id = f"{condition['condition']}_{mode}" + if fold_evaluation_complete(output, checkpoint_hash, heldout_hash, mode): + if evaluation_id not in state["completed_evaluations"]: + state["completed_evaluations"].append(evaluation_id) + continue + while True: + gpu = idle_gpu(allowed_gpus) + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu_evaluation" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + time.sleep(poll_seconds) + if output.exists() and any(output.iterdir()): + release_physical_gpu_claim(gpu) + raise RuntimeError(f"nonempty incomplete fold evaluation output: {output}") + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", str(config), "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", str(heldout), + "--expected-cache-manifest-sha256", heldout_hash, + "--input-mode", mode, "--output-dir", str(output), + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", "phase9_h2o_fold_heldout", + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + log_path = state_path.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "type": "fold_evaluation", + "start_utc": utc_now(), "physical_gpu_id": gpu, + "command": command, "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "evaluating_fold" + atomic_json(state_path, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + raise RuntimeError(f"fold evaluation failed: {evaluation_id}") + state["completed_evaluations"].append(evaluation_id) + atomic_json(state_path, state) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--shard", type=int, choices=(0, 1, 2), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--start-before-main-complete", action="store_true") + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("fold shard plan must explicitly exclude official test") + registry_path = Path(plan["fold_training_registry"]) + if sha256(registry_path) != plan["fold_training_registry_sha256"]: + parser.error("fold training registry SHA256 differs") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + conditions = {item["condition"]: item for item in registry["conditions"]} + assigned = registry["shards"][str(args.shard)] + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_fold_shard_state_v1", + "status": "waiting_for_main_training", "shard": args.shard, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_conditions": [], "completed_evaluations": [], "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing shard state belongs to another plan") + state = previous + previous_gpus = tuple(state.get("allowed_physical_gpus", ALLOWED_GPUS)) + if state.get("attempts") and previous_gpus != args.allowed_physical_gpus: + parser.error("cannot change allowed GPUs after this shard has attempted work") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + state["allowed_physical_gpus"] = list(args.allowed_physical_gpus) + state["start_before_main_complete"] = bool(args.start_before_main_complete) + if args.start_before_main_complete: + state["resource_amendment"] = "user_authorized_all_idle_gpus_20260727" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + while not main_training_gate_satisfied(plan, args.start_before_main_complete): + state["status"] = "waiting_for_main_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_root = Path(plan["fold_evaluation_root"]) + for condition_id in assigned: + condition = conditions[condition_id] + if condition_id not in state["completed_conditions"]: + child_state = args.state.parent / "fold_jobs" / f"{condition_id.lower()}.json" + child_state.parent.mkdir(parents=True, exist_ok=True) + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry_path), "--condition", condition_id, + "--state", str(child_state), "--poll-seconds", str(args.poll_seconds), + "--allowed-physical-gpus", + ",".join(str(gpu) for gpu in args.allowed_physical_gpus), + ] + log_path = args.state.parent / f"{condition_id.lower()}_training.log" + attempt = { + "id": condition_id, "type": "fold_training", + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "training_fold" + state["current_condition"] = condition_id + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode: + state["status"] = "failed_fold_training" + state["failure"] = {"condition": condition_id, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_conditions"].append(condition_id) + atomic_json(args.state, state) + try: + run_fold_evaluations( + condition, state, args.state, evaluation_root, args.poll_seconds, + args.allowed_physical_gpus, + ) + except RuntimeError as error: + state["status"] = "failed_fold_evaluation" + state["failure"] = {"condition": condition_id, "reason": str(error)} + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_hot_cache_release_bridge.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_hot_cache_release_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f786874c313bcb438d540641b84f917de27431 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_hot_cache_release_bridge.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Publish and receive the immutable server_new Stage 7 HOT3D cache release.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + cache_step_complete, + sha256, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any] | None: + candidate = Path(path) + if not candidate.is_file(): + return None + return json.loads(candidate.read_text(encoding="utf-8")) + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("publisher_owner") != "server_new" + or plan.get("receiver_owner") != "taku3" + ): + raise ValueError("HOT cache release bridge plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"HOT cache bridge binding differs: {path}") + root = Path(plan["release_root"]) + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("HOT cache release root is not /SSD2") + for item in plan["artifacts"]: + path = Path(item["path"]) + if root not in path.parents or path == root: + raise ValueError("HOT cache release artifact is outside release root") + if Path(plan["staging_root"]).parts[:2] != ("/", "SSD2"): + raise ValueError("HOT cache staging root is not /SSD2") + + +def inventory_tree(root: Path, directory: Path) -> list[dict[str, Any]]: + if not directory.is_dir() or directory.is_symlink(): + raise ValueError(f"HOT release artifact directory differs: {directory}") + records = [] + for path in sorted(directory.rglob("*")): + if path.is_symlink(): + raise ValueError(f"HOT release refuses symlink: {path}") + if not path.is_file(): + continue + records.append({ + "path": str(path.relative_to(root)), "bytes": path.stat().st_size, + "sha256": sha256(path), + }) + return records + + +def validate_primary(plan: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]] | None: + queue_path = Path(plan["producer_queue_state"]["path"]) + primary_path = Path(plan["producer_worker_state"]) + queue = read_json(queue_path) + primary = read_json(primary_path) + if queue is None or primary is None: + return None + if queue.get("status") != "complete": + return None + if ( + queue.get("plan_sha256") != plan["producer_queue_state"]["plan_sha256"] + or queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + ): + raise ValueError("HOT producer queue completion binding differs") + execution_path = Path(plan["cache_execution_plan"]["path"]) + execution = json.loads(execution_path.read_text(encoding="utf-8")) + worker = next(item for item in execution["workers"] if item["id"] == "hot3d") + expected_steps = [item["id"] for item in worker["steps"]] + if ( + primary.get("status") != "complete" + or primary.get("worker") != "hot3d" + or primary.get("plan_sha256") != plan["cache_execution_plan"]["sha256"] + or primary.get("completed_steps") != expected_steps + or primary.get("official_test_used") is not False + or primary.get("h2o_official_validation_used") is not False + ): + raise ValueError("HOT primary worker completion differs") + for step in worker["steps"]: + if step["id"].endswith("resume_verify") and not cache_step_complete(step, True): + raise ValueError(f"HOT deployable resume output differs: {step['id']}") + return queue, primary + + +def publish(plan_path: Path, plan: dict[str, Any]) -> bool: + completion = validate_primary(plan) + if completion is None: + return False + queue, primary = completion + release_path = Path(plan["release_state"]) + if release_path.is_file(): + existing = json.loads(release_path.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return True + raise ValueError("existing HOT cache release differs") + root = Path(plan["release_root"]) + files: list[dict[str, Any]] = [] + artifact_records = [] + for item in plan["artifacts"]: + records = inventory_tree(root, Path(item["path"])) + files.extend(records) + artifact_records.append({ + "id": item["id"], "path": item["path"], + "relative_path": str(Path(item["path"]).relative_to(root)), + "file_count": len(records), + "total_bytes": sum(record["bytes"] for record in records), + }) + relative_paths = [item["path"] for item in files] + if len(relative_paths) != len(set(relative_paths)): + raise ValueError("HOT release inventory contains duplicate paths") + release = { + "schema_version": "phase9_hot_cache_immutable_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), "release_root": str(root.resolve()), + "producer_queue_state": { + "path": str(Path(plan["producer_queue_state"]["path"]).resolve()), + "sha256": sha256(plan["producer_queue_state"]["path"]), + "completed_utc": queue.get("completed_utc"), + }, + "producer_worker_state": { + "path": str(Path(plan["producer_worker_state"]).resolve()), + "sha256": sha256(plan["producer_worker_state"]), + "value": primary, + }, + "artifacts": artifact_records, "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "single_deployable_manifest_writer": "original_resolution_cache_runner", + "live_reverse_sync_forbidden": True, + "read_only_after_receive": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(release_path, release) + os.chmod(release_path, 0o444) + return True + + +def fetch_remote_json(host: str, path: str, timeout: float) -> dict[str, Any] | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if completed.returncode: + return None + try: + value = json.loads(completed.stdout) + except json.JSONDecodeError: + return None + return value if isinstance(value, dict) else None + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or release.get("live_reverse_sync_forbidden") is not True + or release.get("read_only_after_receive") is not True + ): + raise ValueError("HOT immutable release contract differs") + paths = [item["path"] for item in release.get("files", [])] + if ( + len(paths) != len(set(paths)) + or len(paths) != release.get("file_count") + or sum(item["bytes"] for item in release["files"]) != release.get("total_bytes") + ): + raise ValueError("HOT immutable release inventory differs") + for value in paths: + relative = Path(value) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError(f"HOT immutable release path is unsafe: {relative}") + + +def write_external_proxy(plan: dict[str, Any], queue: dict[str, Any] | None) -> None: + state_path = Path(plan["local_worker_state"]) + state = read_json(state_path) + if state is None or state.get("status") == "complete": + return + backup = Path(plan["local_state_backup"]) + if not backup.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(state_path, backup) + os.chmod(backup, 0o444) + if state.get("plan_sha256") != plan["cache_execution_plan"]["sha256"]: + raise ValueError("local HOT proxy state binding differs") + state.update({ + "status": "waiting_for_server_new_immutable_release", + "updated_utc": utc_now(), "external_owner": "server_new", + "external_queue_status": (queue or {}).get("status", "unavailable"), + "external_queue_updated_utc": (queue or {}).get("updated_utc"), + "live_reverse_sync_forbidden": True, + "h2o_official_validation_used": False, "official_test_used": False, + }) + atomic_json(state_path, state) + + +def verify_staging(staging: Path, release: dict[str, Any]) -> None: + for item in release["files"]: + path = staging / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] or sha256(path) != item["sha256"] + ): + raise ValueError(f"received HOT cache file differs: {path}") + + +def install_artifacts(plan: dict[str, Any], release: dict[str, Any], staging: Path) -> list[dict[str, Any]]: + installed = [] + backup_root = Path(plan["receive_backup_root"]) + for item in release["artifacts"]: + destination = Path(item["path"]) + source = staging / item["relative_path"] + backup = backup_root / item["relative_path"] + if destination.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + if backup.exists(): + raise ValueError(f"HOT receive backup already exists: {backup}") + os.replace(destination, backup) + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination) + for path in destination.rglob("*"): + os.chmod(path, 0o555 if path.is_dir() else 0o444) + os.chmod(destination, 0o555) + installed.append({ + "id": item["id"], "path": str(destination.resolve()), + "backup": str(backup.resolve()) if backup.exists() else None, + "file_count": item["file_count"], "total_bytes": item["total_bytes"], + }) + return installed + + +def receive(plan_path: Path, plan: dict[str, Any], state_path: Path) -> bool: + timeout = float(plan["ssh_timeout_seconds"]) + queue = fetch_remote_json( + plan["remote_host"], plan["producer_queue_state"]["path"], timeout, + ) + release = fetch_remote_json(plan["remote_host"], plan["release_state"], timeout) + if release is None: + write_external_proxy(plan, queue) + atomic_json(state_path, { + "schema_version": "phase9_hot_cache_receive_state_v1", + "status": "waiting_for_server_new_immutable_release", + "updated_utc": utc_now(), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "remote_queue_status": (queue or {}).get("status", "unavailable"), + "h2o_official_validation_used": False, "official_test_used": False, + }) + return False + validate_release(plan_path, plan, release) + if (read_json(state_path) or {}).get("status") == "complete": + return True + staging = Path(plan["staging_root"]) + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".release_files.txt" + file_list.write_text("".join(item["path"] + "\n" for item in release["files"]), encoding="utf-8") + command = [ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['remote_host']}:{Path(plan['release_root']).resolve()}/", + f"{staging.resolve()}/", + ] + completed = subprocess.run(command, check=False) + if completed.returncode: + raise RuntimeError(f"HOT immutable rsync failed: {completed.returncode}") + verify_staging(staging, release) + installed = install_artifacts(plan, release, staging) + remote_state = release["producer_worker_state"]["value"] + state_temporary = Path(plan["local_worker_state"]).with_suffix(".remote.tmp") + state_temporary.write_text(json.dumps(remote_state, indent=2) + "\n", encoding="utf-8") + if sha256(state_temporary) != release["producer_worker_state"]["sha256"]: + state_temporary.unlink() + raise ValueError("HOT received worker state differs") + os.replace(state_temporary, plan["local_worker_state"]) + result = { + "schema_version": "phase9_hot_cache_receive_state_v1", + "status": "complete", "completed_utc": utc_now(), + "updated_utc": utc_now(), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), "release_state": plan["release_state"], + "release_file_count": release["file_count"], + "release_total_bytes": release["total_bytes"], "installed": installed, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, result) + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--state", type=Path) + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1 and not args.once: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + state_path = Path(plan["release_state"] if args.role == "publish" else plan["receive_state"]) + if args.state and args.state.resolve() != state_path.resolve(): + parser.error("HOT cache bridge state path differs") + state_path.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{state_path}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + complete = publish(args.plan, plan) if args.role == "publish" else receive( + args.plan, plan, state_path, + ) + if complete or args.once: + print(json.dumps(read_json(state_path) or {"status": "waiting"}, indent=2)) + return + time.sleep(args.poll_seconds) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_hot_prefill_merge_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_hot_prefill_merge_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..0044df9b517929b1658514cfee1e03e7f397a52a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_hot_prefill_merge_queue.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Wait for frozen HOT prefill shards and merge them into the primary cache.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +import time + +from scripts.cache_phase7_hot3d import sha256 +from scripts.merge_phase9_hot_prefill import merge_prefills + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def prefill_complete(path: Path) -> bool: + report = path / "cache_report.json" + if not report.is_file(): + return False + value = json.loads(report.read_text(encoding="utf-8")) + return value.get("status") == "complete" and value.get("mode") == "staged_prefill" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("prefill plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + prefill_dirs = [Path(item["output_dir"]) for item in plan["shards"]] + state = { + "schema_version": "phase9_hot_prefill_merge_queue_v1", + "status": "waiting_for_prefill", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing state belongs to another prefill plan") + if previous.get("status") == "complete": + print(json.dumps(previous, indent=2)) + return + state = previous + while not all(prefill_complete(path) for path in prefill_dirs): + state["status"] = "waiting_for_prefill" + state["ready_shards"] = [str(path) for path in prefill_dirs if prefill_complete(path)] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "merging" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + result = merge_prefills( + Path(plan["target_output_dir"]), prefill_dirs, Path(plan["merge_report"]), + ) + state.update({ + "status": "complete", "updated_utc": utc_now(), + "merge_report": str(Path(plan["merge_report"]).resolve()), + "merge_report_sha256": sha256(Path(plan["merge_report"])), + "linked": result["linked"], + "existing_identical": result["existing_identical"], + }) + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_hot_prefill_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_hot_prefill_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..404aa2ad2ed1207d4650a0580a92722f4073d778 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_hot_prefill_queue.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +"""Run disjoint HOT3D cache prefills, merge them, and resume the canonical writer.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.cache_phase7_hot3d import sha256 +from scripts.merge_phase9_hot_prefill import merge_prefills + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def command_value(command: list[str], option: str) -> str: + try: + return command[command.index(option) + 1] + except (ValueError, IndexError) as error: + raise ValueError(f"prefill command lacks {option}") from error + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("resolution_hw") != [512, 896] + ): + raise ValueError("HOT prefill plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"HOT prefill binding differs: {path}") + source = Path(plan["source_manifest"]["path"]) + if not source.is_file() or sha256(source) != plan["source_manifest"]["sha256"]: + raise ValueError("HOT prefill source manifest differs") + target = Path(plan["target_output_dir"]) + if target.parts[:2] != ("/", "SSD2"): + raise ValueError("HOT prefill target is not on /SSD2") + shards = plan["shards"] + ranges = [tuple(item["candidate_position_range"]) for item in shards] + expected_start = 0 + outputs: set[Path] = set() + for shard, (start, stop) in zip(shards, ranges, strict=True): + if start != expected_start or stop <= start: + raise ValueError("HOT prefill ranges are not a contiguous partition") + expected_start = stop + output = Path(shard["output_dir"]) + if output.parts[:2] != ("/", "SSD2") or output == target or output in outputs: + raise ValueError("HOT prefill output ownership differs") + outputs.add(output) + command = shard["command"] + if ( + command_value(command, "--output-dir") != str(output) + or command_value(command, "--source-manifest") != str(source) + or command_value(command, "--prefill-position-range") != str(start) + or command[command.index("--prefill-position-range") + 2] != str(stop) + or command[command.index("--target-hw") + 1:command.index("--target-hw") + 3] + != ["512", "896"] + or "--decode-all-candidates" not in command + ): + raise ValueError(f"HOT prefill command differs: {shard['id']}") + if expected_start != int(plan["full_candidate_clips"]): + raise ValueError("HOT prefill ranges do not cover the candidate order") + if len({item["id"] for item in shards}) != len(shards): + raise ValueError("HOT prefill shard IDs are not unique") + if Path(plan["state"]).resolve() == plan_path.resolve(): + raise ValueError("HOT prefill state collides with its plan") + + +def prefill_complete(shard: dict[str, Any], plan: dict[str, Any]) -> bool: + output = Path(shard["output_dir"]) + report_path = output / "cache_report.json" + manifest_path = output / "prefill_manifest.jsonl" + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + start, stop = shard["candidate_position_range"] + processed = int(report.get("clips", -1)) + len( + report.get("skipped_no_supervision", []) + ) + return ( + report.get("status") == "complete" + and report.get("mode") == "staged_prefill" + and report.get("official_test_used") is False + and report.get("resolution_hw") == plan["resolution_hw"] + and report.get("candidate_position_range") == [start, stop] + and report.get("full_candidate_clips") == plan["full_candidate_clips"] + and report.get("requested_target_clips") == plan["requested_target_clips"] + and report.get("candidate_source_indices_sha256") + == plan["candidate_source_indices_sha256"] + and report.get("source_manifest", {}).get("sha256") + == plan["source_manifest"]["sha256"] + and report.get("cache_manifest", {}).get("sha256") == sha256(manifest_path) + and processed == stop - start + ) + + +def shard_pid_matches(pid: int, shard: dict[str, Any]) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + start, stop = shard["candidate_position_range"] + return ( + "scripts.cache_phase7_hot3d" in command + and f"--prefill-position-range {start} {stop}" in command + and f"--output-dir {Path(shard['output_dir']).resolve()}" in command + ) + + +def primary_pid_matches(pid: int, plan: dict[str, Any]) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_resolution_cache_queue" in command + and "--worker hot3d" in command + and f"--state {Path(plan['primary_state']).resolve()}" in command + ) + + +def launch(command: list[str], log_path: Path) -> int: + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def runtime_command(shard: dict[str, Any]) -> list[str]: + command = list(shard["command"]) + if Path(shard["output_dir"]).exists() and "--resume" not in command: + command.append("--resume") + return command + + +def primary_status(plan: dict[str, Any]) -> str: + path = Path(plan["primary_state"]) + if not path.is_file(): + return "missing" + state = json.loads(path.read_text(encoding="utf-8")) + if ( + state.get("plan_sha256") != plan["cache_execution_plan"]["sha256"] + or state.get("worker") != "hot3d" + or state.get("official_test_used") is not False + ): + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("HOT prefill state path differs from plan") + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_hot_prefill_queue_v1", + "status": "prefilling", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "shards": {}, "primary": {}, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing HOT prefill state belongs to another plan") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + statuses: dict[str, str] = {} + for shard in plan["shards"]: + identifier = shard["id"] + complete = prefill_complete(shard, plan) + statuses[identifier] = "complete" if complete else "running" + if complete: + continue + previous = state.setdefault("shards", {}).get(identifier, {}) + pid = int(previous.get("pid", -1)) + if not shard_pid_matches(pid, shard): + attempts = int(previous.get("attempts", 0)) + 1 + command = runtime_command(shard) + pid = launch(command, Path(shard["log"])) + state["shards"][identifier] = { + "pid": pid, "attempts": attempts, + "launched_utc": utc_now(), "command": command, + } + state["shard_statuses"] = statuses + state["updated_utc"] = utc_now() + if all(status == "complete" for status in statuses.values()): + break + state["status"] = "prefilling" + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + merge_path = Path(plan["merge_report"]) + if merge_path.is_file(): + merge = json.loads(merge_path.read_text(encoding="utf-8")) + if merge.get("status") != "complete": + parser.error("existing HOT prefill merge report differs") + else: + state["status"] = "merging" + atomic_json(args.state, state) + merge = merge_prefills( + Path(plan["target_output_dir"]), + [Path(item["output_dir"]) for item in plan["shards"]], + merge_path, + ) + state["merge_report"] = { + "path": str(merge_path.resolve()), "sha256": sha256(merge_path), + "linked": merge["linked"], + "existing_identical": merge["existing_identical"], + } + while True: + status = primary_status(plan) + state["primary_status"] = status + if status == "complete": + break + if status.startswith("failed") and status != "failed_resumable": + state["status"] = "failed_primary_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + pid = int(state.setdefault("primary", {}).get("pid", -1)) + if not primary_pid_matches(pid, plan): + command = list(plan["primary_resume_command"]) + pid = launch(command, Path(plan["primary_log"])) + state["primary"] = { + "pid": pid, "launched_utc": utc_now(), "command": command, + } + state["status"] = "merged_waiting_for_canonical_writer" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_last2_candidate_controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_last2_candidate_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8a1689c26bf3c9735e969e1bf77208b7844390 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_last2_candidate_controller.py @@ -0,0 +1,510 @@ +#!/usr/bin/env python3 +"""Run or formally reject one ordered DINO Base last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_resolution_evaluation_controller import ( + hard_failure as evaluation_hard_failure, + launch_worker as launch_evaluation_worker, + pid_matches as evaluation_pid_matches, + should_launch as should_launch_evaluation, + worker_status, +) +from scripts.run_phase9_resolution_training_controller import ( + condition_status, + hard_failure as training_hard_failure, + pid_matches as training_pid_matches, +) +from scripts.run_phase9_shared_augmentation_training_controller import ( + launch_worker as launch_training_worker, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("candidate") not in {"5e7", "1e6"} + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("training_job_count") != 7 + or plan.get("evaluation_count") != 25 + or plan.get("evaluation_worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + ): + raise ValueError("last-2 candidate controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"last-2 candidate binding differs: {path}") + + +def admission(plan: dict[str, Any]) -> tuple[str, str, dict[str, Any] | None]: + state_path = Path(plan["admission_controller_state"]) + if not state_path.is_file(): + return "waiting", "upstream_state_missing", None + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed"): + return "failed", "upstream_controller_failed", None + return "waiting", "upstream_controller_incomplete", None + if ( + state.get("plan_sha256") != plan["admission_controller_plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not report_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or report_path.resolve() + != Path(plan["admission_decision_report"]).resolve() + ): + return "failed", "upstream_decision_binding_differs", None + report = read_json(report_path) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + return "failed", "upstream_decision_isolation_differs", None + if plan["candidate"] == "5e7": + admitted = report.get("stage9_preceding_mechanism_gate", {}).get( + "stage9_last2_admitted" + ) is True + reason = ( + "preceding_mechanism_macro_and_worst_improved" + if admitted else "preceding_mechanism_gate_failed" + ) + else: + admitted = ( + report.get("candidate") == "5e7" + and report.get("gate", {}).get("macro_strictly_improved") is True + and report.get("gate", {}).get("worst_domain_strictly_improved") is True + and report.get("gate", {}).get("accepted") is True + ) + reason = "five_e7_strict_gate_passed" if admitted else "five_e7_gate_failed" + return ("admitted" if admitted else "rejected"), reason, report + + +def formal_rejection( + plan: dict[str, Any], reason: str, upstream: dict[str, Any], output: Path, +) -> dict[str, Any]: + return { + "schema_version": "phase9_last2_candidate_decision_v1", + "status": "complete", "candidate": plan["candidate"], + "created_utc": utc_now(), + "decision": f"not_admitted_last2_{plan['candidate']}", + "not_admitted_reason": reason, + "gate": { + "macro_strictly_improved": False, + "worst_domain_strictly_improved": False, + "accepted": False, + }, + "upstream_decision": { + "path": str(Path(plan["admission_decision_report"]).resolve()), + "sha256": sha256(plan["admission_decision_report"]), + }, + "training_started": False, + "evaluation_started": False, + "dino_large_admitted": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("last-2 controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + static_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_last2_candidate_controller_state_v1", + "status": "waiting_for_admission", "candidate": plan["candidate"], + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "machine": machine, + "controller_pid": os.getpid(), + "training_workers": {}, "evaluation_workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != static_hash: + parser.error("existing last-2 controller state differs") + if state.get("machine") != machine: + parser.error("existing last-2 state belongs to another machine") + if state.get("status") in {"complete", "complete_local"}: + print(json.dumps(state, indent=2)) + return + while True: + admission_status, reason, upstream = admission(plan) + if admission_status == "waiting": + state["status"] = "waiting_for_admission" + state["waiting_reason"] = reason + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + if admission_status == "failed": + state["status"] = "failed_admission_binding" + state["failure"] = reason + atomic_json(args.state, state) + raise SystemExit(1) + break + + decision_path = Path(plan["decision_report"]) + if admission_status == "rejected": + assert upstream is not None + if machine != "taku3": + while not decision_path.is_file(): + state["status"] = "waiting_for_central_rejection_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "complete_local" + state["admitted"] = False + state["decision_report"] = { + "path": str(decision_path.resolve()), + "sha256": sha256(decision_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + if not decision_path.exists(): + decision_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json( + decision_path, + formal_rejection(plan, reason, upstream, decision_path), + ) + report = read_json(decision_path) + if ( + report.get("status") != "complete" + or report.get("candidate") != plan["candidate"] + or report.get("decision") + != f"not_admitted_last2_{plan['candidate']}" + or report.get("not_admitted_reason") != reason + or report.get("training_started") is not False + or report.get("evaluation_started") is not False + or report.get("upstream_decision", {}).get("sha256") + != sha256(plan["admission_decision_report"]) + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + state["status"] = "failed_rejection_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["admitted"] = False + state["decision"] = report["decision"] + state["decision_report"] = { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + registry = Path(plan["training_registry"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_last2_training_registry", + "--candidate", plan["candidate"], + "--stage8-controller-plan", plan["stage8_controller_plan"], + "--stage8-controller-state", plan["stage8_controller_state"], + "--last2-plan", plan["last2_plan"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), + "--state", plan["training_registry_state"], + ] + if plan["candidate"] == "1e6": + builder_command.extend(("--five-e7-decision", plan["admission_decision_report"])) + if machine == "taku3": + state["status"] = "building_training_registry" + state["training_builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_training_registry_builder" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + registry_hash = sha256(registry) + registry_payload = read_json(registry) + conditions = [item["condition"] for item in registry_payload["conditions"]] + owners = condition_owners(registry_payload, assignment) + if ( + registry_payload.get("candidate") != plan["candidate"] + or len(conditions) != plan["training_job_count"] + or len(set(conditions)) != len(conditions) + or registry_payload.get("official_test_used") is not False + ): + state["status"] = "failed_training_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_hash + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("training_workers", {}) + training_state_root = Path(plan["training_state_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = training_state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_hash) + statuses[condition] = status + if training_hard_failure(status) or status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["training_workers"].get(condition, {}).get("pid", -1) + ) + if not training_pid_matches(previous_pid, condition, registry): + pid = launch_training_worker( + condition, registry, condition_state, + Path(plan["training_log_root"]) / f"{condition.lower()}.log", + allowed_gpus, + ) + state["training_workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["training_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(training_hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + training_completion = { + "schema_version": "phase9_last2_training_completion_state_v1", + "status": "complete", "candidate": plan["candidate"], + "completed_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "training_registry": str(registry.resolve()), + "training_registry_sha256": registry_hash, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if machine == "taku3": + atomic_json(Path(plan["training_completion_state"]), training_completion) + else: + while not Path(plan["training_completion_state"]).is_file(): + state["status"] = "waiting_for_central_training_aggregate_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + eval_builder = [ + sys.executable, "-m", "scripts.build_phase9_last2_evaluation_plan", + "--candidate", plan["candidate"], + "--training-controller-plan", str(args.plan), + "--training-controller-state", plan["training_completion_state"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["evaluation_worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["evaluation_builder_command"] = eval_builder + atomic_json(args.state, state) + result = subprocess.run(eval_builder, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_hash = sha256(evaluation_plan) + dynamic = read_json(evaluation_plan) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["evaluation_worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = evaluation_hash + state["owned_evaluation_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("evaluation_workers", {}) + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + worker_state = Path(worker["state"]) + status = worker_status(worker_state, evaluation_hash) + statuses[worker["id"]] = status + if not should_launch_evaluation(worker, machine, status): + continue + previous_pid = int( + state["evaluation_workers"].get(worker["id"], {}).get("pid", -1) + ) + if not evaluation_pid_matches( + previous_pid, worker["id"], evaluation_plan, + ): + pid = launch_evaluation_worker( + evaluation_plan, worker, + Path(plan["evaluation_worker_log_root"]) / f"{worker['id']}.log", + ) + state["evaluation_workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["evaluation_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "training_workers": state["training_workers"], + "evaluation_workers": state["evaluation_workers"], + } + if any(evaluation_hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["admitted"] = True + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + if not decision_path.exists(): + command = [ + sys.executable, "-m", "scripts.summarize_phase9_last2_decision", + "--plan", str(evaluation_plan), "--output", str(decision_path), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = read_json(decision_path) + if ( + report.get("status") != "complete" + or report.get("candidate") != plan["candidate"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != evaluation_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["admitted"] = True + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["decision_report"] = { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_last2_resume_training.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_last2_resume_training.py new file mode 100644 index 0000000000000000000000000000000000000000..b169e799e229b526fefbaa79729dba29e9466d86 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_last2_resume_training.py @@ -0,0 +1,859 @@ +#!/usr/bin/env python3 +"""Freeze and supervise the resource-only Stage 9 1e-6 training resume.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import getpass +import hashlib +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import time +from typing import Any + + +SCHEMA = "phase9_last2_1e6_resume_training_amendment_v1" +STATE_SCHEMA = "phase9_last2_1e6_resume_training_supervisor_v1" +CONTROL_SCHEMA = "phase9_last2_1e6_resume_control_v1" +EXTERNAL_ROLES = {"loso_subject2", "loso_subject3", "lofamily_k"} +EXPECTED_ROLES = { + "full", + "loso_subject1", + "loso_subject2", + "loso_subject3", + "lofamily_h", + "lofamily_k", + "lofamily_o", +} +RESUMABLE_STATUSES = { + "missing", + "waiting_for_data", + "waiting_for_prerequisites", + "waiting_for_idle_gpu", + "running", + "failed_resumable", +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: str | Path, value: dict[str, Any]) -> None: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name( + f".{destination.name}.tmp.{os.getpid()}.{time.time_ns()}" + ) + with temporary.open("w", encoding="utf-8") as handle: + json.dump(value, handle, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, destination) + + +def binding(path: str | Path) -> dict[str, str]: + resolved = Path(path).resolve() + if not resolved.is_file(): + raise ValueError(f"binding is missing: {resolved}") + return {"path": str(resolved), "sha256": sha256(resolved)} + + +def validate_binding(value: dict[str, Any], label: str) -> Path: + path = Path(str(value.get("path", ""))) + digest = value.get("sha256") + if not path.is_file() or not isinstance(digest, str) or sha256(path) != digest: + raise ValueError(f"{label} binding differs: {path}") + return path + + +def process_command(pid: int) -> str | None: + try: + return Path(f"/proc/{pid}/cmdline").read_bytes().replace( + b"\0", b" " + ).decode("utf-8", errors="replace") + except (FileNotFoundError, PermissionError, ProcessLookupError): + return None + + +def matching_pids(*needles: str) -> list[int]: + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + command = process_command(int(entry.name)) + if command and all(needle in command for needle in needles): + matches.append(int(entry.name)) + return sorted(matches) + + +def world_adapter_active_pids(formal_root: str) -> list[int]: + runners = ( + "scripts.run_world_adapter_formal_training_v1", + "scripts.control_world_adapter_formal_evaluation_v1", + "scripts.train_phase7_external", + "scripts.evaluate_phase7_external", + ) + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + command = process_command(int(entry.name)) + if command and formal_root in command and any(item in command for item in runners): + matches.append(int(entry.name)) + return sorted(matches) + + +def validate_world_adapter_terminal( + amendment: dict[str, Any], *, require_inactive: bool = True +) -> None: + evidence = amendment["world_adapter_isolation"] + training_path = validate_binding(evidence["training_controller"], "WA training") + evaluation_path = validate_binding( + evidence["evaluation_controller"], "WA evaluation" + ) + report_path = validate_binding(evidence["comparison_report"], "WA comparison") + training = read_json(training_path) + evaluation = read_json(evaluation_path) + report = read_json(report_path) + if ( + training.get("status") != "training_complete_evaluation_locked" + or training.get("training_job_count") != 42 + or training.get("current_stage_complete") != 42 + or training.get("workers") != {} + or training.get("official_test_used") is not False + or evaluation.get("status") != "complete_report_only_no_promotion" + or evaluation.get("evaluation_job_count") != 150 + or evaluation.get("completed_evaluation_jobs") != 150 + or evaluation.get("workers") != {} + or evaluation.get("official_test_used") is not False + or report.get("status") != "complete_report_only_no_promotion" + ): + raise ValueError("World Adapter formal run is not terminal and isolated") + active = world_adapter_active_pids(evidence["formal_root"]) + if require_inactive and active: + raise RuntimeError(f"World Adapter workers are active: {active}") + + +def validate_original_plan_bindings(plan: dict[str, Any]) -> None: + for item in plan.get("bindings", []): + validate_binding(item, "original plan") + + +def role_owners(assignment: dict[str, Any]) -> dict[str, str]: + records = assignment["stage_condition_ownership"]["roles"] + owners = {item["role"]: item["owner"] for item in records} + if set(owners) != EXPECTED_ROLES or len(records) != len(owners): + raise ValueError("original distributed role ownership differs") + return owners + + +def freeze(args: argparse.Namespace) -> None: + output = args.output.resolve() + if output.exists(): + raise ValueError(f"amendment output already exists: {output}") + original_plan_path = args.original_plan.resolve() + original_state_path = args.original_state.resolve() + registry_path = args.training_registry.resolve() + assignment_path = args.distributed_assignment.resolve() + original_plan = read_json(original_plan_path) + original_state = read_json(original_state_path) + registry = read_json(registry_path) + assignment = read_json(assignment_path) + validate_original_plan_bindings(original_plan) + owners = role_owners(assignment) + plan_hash = sha256(original_plan_path) + registry_hash = sha256(registry_path) + if ( + original_plan.get("candidate") != "1e6" + or original_plan.get("training_registry") != str(registry_path) + or original_plan.get("distributed_assignment", {}).get("path") + != str(assignment_path) + or original_plan.get("distributed_assignment", {}).get("sha256") + != sha256(assignment_path) + or original_state.get("plan_sha256") != plan_hash + or original_state.get("training_registry_sha256") != registry_hash + or original_state.get("official_test_used") is not False + or registry.get("status") != "frozen_ready" + or registry.get("candidate") != "1e6" + or registry.get("backbone_learning_rate") != 1e-6 + or registry.get("target_step") != 405000 + or registry.get("official_test_used") is not False + or len(registry.get("conditions", [])) != 7 + ): + raise ValueError("original 1e-6 plan, state, or registry differs") + state_root = Path(original_plan["training_state_root"]).resolve() + mappings = [] + observed_roles = set() + for item in registry["conditions"]: + condition = item["condition"] + role = item["role"] + observed_roles.add(role) + logical_owner = owners[role] + if (role in EXTERNAL_ROLES) != (logical_owner == "server_new"): + raise ValueError(f"unexpected original owner for {role}") + config_path = validate_binding( + {"path": item["config"], "sha256": item["config_sha256"]}, + f"config {condition}", + ) + initialization = validate_binding( + { + "path": item["initialization_checkpoint"], + "sha256": item["initialization_checkpoint_sha256"], + }, + f"initialization {condition}", + ) + mappings.append( + { + "condition": condition, + "role": role, + "logical_owner": logical_owner, + "execution_owner": "taku3", + "priority": 0 if logical_owner == "taku3" else 1, + "config": str(config_path), + "config_sha256": item["config_sha256"], + "initialization_checkpoint": str(initialization), + "initialization_checkpoint_sha256": item[ + "initialization_checkpoint_sha256" + ], + "output_dir": item["output_dir"], + "state": str(state_root / f"{condition.lower()}.json"), + } + ) + if observed_roles != EXPECTED_ROLES: + raise ValueError("1e-6 registry roles differ") + created = utc_now() + value = { + "schema_version": SCHEMA, + "status": "frozen_training_approved", + "created_utc": created, + "candidate": "1e6", + "authorization": { + "status": "approved", + "authorized_by": args.authorized_by, + "authorized_utc": created, + "request": args.authorization_note, + }, + "repository": str(args.repository.resolve()), + "python": str(args.python.resolve()), + "orchestrator": binding(Path(__file__).resolve()), + "original_controller_plan": binding(original_plan_path), + "original_controller_state_after_fail_closed_restart": binding( + original_state_path + ), + "training_registry": binding(registry_path), + "distributed_assignment": binding(assignment_path), + "training_runner": binding(args.training_runner.resolve()), + "model_training_runner": binding(args.model_training_runner.resolve()), + "training_mappings": mappings, + "supervisor_state": str(args.supervisor_state.resolve()), + "training_completion_report": str(args.completion_report.resolve()), + "control_file": str(args.control_file.resolve()), + "scheduling": { + "physical_gpu_allowlist": [0, 1, 2, 3, 4, 5], + "max_concurrent_training_workers": 4, + "minimum_gpu_slots_reserved_for_world_adapter": 2, + "cpu_nice": 10, + "io_class": "best-effort", + "io_priority": 7, + "existing_taku3_conditions_first": True, + }, + "world_adapter_isolation": { + "formal_root": args.world_adapter_formal_root, + "training_controller": binding(args.world_adapter_training_state), + "evaluation_controller": binding(args.world_adapter_evaluation_state), + "comparison_report": binding(args.world_adapter_comparison_report), + "training_jobs_complete": 42, + "evaluation_jobs_complete": 150, + "automatic_model_promotion": False, + }, + "external_owner_preflight": { + "host": "taku-g2", + "checked_utc": args.external_owner_checked_utc, + "matching_1e6_process_count": args.external_owner_process_count, + "canonical_training_states_present": sum( + Path(item["state"]).is_file() + for item in mappings + if item["logical_owner"] == "server_new" + ), + }, + "original_controller_restart_result": { + "status": original_state.get("status"), + "gpu_training_started": False, + "reason": "registry builder rejected existing runs before worker launch", + }, + "resource_schedule_amendment_only": True, + "external_process_preemption_forbidden": True, + "external_processes_preempted": False, + "scientific_fields_changed": [], + "model_changed": False, + "data_changed": False, + "seed_changed": False, + "optimizer_changed": False, + "learning_rate_changed": False, + "horizon_changed": False, + "metric_changed": False, + "selection_gate_changed": False, + "evaluation_started": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + validate_world_adapter_terminal(value) + atomic_json(output, value) + os.chmod(output, 0o444) + print(json.dumps({"path": str(output), "sha256": sha256(output)}, indent=2)) + + +def validate_amendment(path: Path) -> tuple[dict[str, Any], dict[str, Any]]: + amendment = read_json(path) + false_fields = ( + "external_processes_preempted", + "model_changed", + "data_changed", + "seed_changed", + "optimizer_changed", + "learning_rate_changed", + "horizon_changed", + "metric_changed", + "selection_gate_changed", + "evaluation_started", + "h2o_official_validation_used", + "official_test_used", + ) + if ( + amendment.get("schema_version") != SCHEMA + or amendment.get("status") != "frozen_training_approved" + or amendment.get("candidate") != "1e6" + or amendment.get("authorization", {}).get("status") != "approved" + or amendment.get("resource_schedule_amendment_only") is not True + or amendment.get("external_process_preemption_forbidden") is not True + or amendment.get("scientific_fields_changed") != [] + or any(amendment.get(key) is not False for key in false_fields) + ): + raise ValueError("1e-6 resume amendment contract differs") + orchestrator = validate_binding(amendment["orchestrator"], "orchestrator") + if orchestrator.resolve() != Path(__file__).resolve(): + raise ValueError("running orchestrator path differs from amendment") + original_plan_path = validate_binding( + amendment["original_controller_plan"], "original controller plan" + ) + original_state_path = validate_binding( + amendment["original_controller_state_after_fail_closed_restart"], + "original controller state", + ) + registry_path = validate_binding(amendment["training_registry"], "registry") + assignment_path = validate_binding( + amendment["distributed_assignment"], "distributed assignment" + ) + validate_binding(amendment["training_runner"], "training runner") + validate_binding(amendment["model_training_runner"], "model training runner") + original_plan = read_json(original_plan_path) + original_state = read_json(original_state_path) + registry = read_json(registry_path) + assignment = read_json(assignment_path) + validate_original_plan_bindings(original_plan) + owners = role_owners(assignment) + if ( + original_plan.get("candidate") != "1e6" + or original_plan.get("training_registry") != str(registry_path) + or original_state.get("plan_sha256") != sha256(original_plan_path) + or original_state.get("training_registry_sha256") != sha256(registry_path) + or registry.get("status") != "frozen_ready" + or registry.get("candidate") != "1e6" + or registry.get("backbone_learning_rate") != 1e-6 + or registry.get("target_step") != 405000 + or len(registry.get("conditions", [])) != 7 + ): + raise ValueError("bound original 1e-6 artifacts differ") + schedule = amendment.get("scheduling", {}) + if ( + schedule.get("physical_gpu_allowlist") != [0, 1, 2, 3, 4, 5] + or schedule.get("max_concurrent_training_workers") != 4 + or schedule.get("minimum_gpu_slots_reserved_for_world_adapter") != 2 + or schedule.get("cpu_nice") != 10 + or schedule.get("io_priority") != 7 + ): + raise ValueError("1e-6/World Adapter scheduling isolation differs") + preflight = amendment.get("external_owner_preflight", {}) + if ( + preflight.get("host") != "taku-g2" + or preflight.get("matching_1e6_process_count") != 0 + or preflight.get("canonical_training_states_present") != 0 + ): + raise ValueError("external owner preflight does not permit G3 execution") + jobs = {item["condition"]: item for item in registry["conditions"]} + mappings = amendment.get("training_mappings", []) + if len(mappings) != 7 or len({item.get("condition") for item in mappings}) != 7: + raise ValueError("resume mappings must contain seven unique conditions") + state_root = Path(original_plan["training_state_root"]).resolve() + for mapping in mappings: + condition = mapping.get("condition") + job = jobs.get(condition) + role = mapping.get("role") + if ( + job is None + or role != job.get("role") + or mapping.get("logical_owner") != owners.get(role) + or mapping.get("execution_owner") != "taku3" + or mapping.get("config") != job.get("config") + or mapping.get("config_sha256") != job.get("config_sha256") + or mapping.get("initialization_checkpoint") + != job.get("initialization_checkpoint") + or mapping.get("output_dir") != job.get("output_dir") + or Path(mapping.get("state", "")).resolve() + != state_root / f"{condition.lower()}.json" + ): + raise ValueError(f"resume mapping differs: {condition}") + validate_binding( + {"path": mapping["config"], "sha256": mapping["config_sha256"]}, + f"mapped config {condition}", + ) + validate_world_adapter_terminal(amendment, require_inactive=False) + return amendment, registry + + +def queue_pids(mapping: dict[str, Any], registry: Path) -> list[int]: + return matching_pids( + "scripts.run_phase9_unified_train_queue", + f"--condition {mapping['condition']}", + str(registry.resolve()), + str(Path(mapping["state"]).resolve()), + ) + + +def training_child_pids(mapping: dict[str, Any]) -> list[int]: + return matching_pids( + "scripts.train_phase7_external", + f"--output-dir {mapping['output_dir']}", + f"--config {mapping['config']}", + ) + + +def state_status(mapping: dict[str, Any], registry_hash: str) -> str: + path = Path(mapping["state"]) + if not path.is_file(): + return "missing" + try: + value = read_json(path) + except (OSError, json.JSONDecodeError): + return "unreadable" + if ( + value.get("queue_sha256") != registry_hash + or value.get("condition") != mapping["condition"] + or value.get("official_test_used") is not False + ): + return "failed_state_binding" + return str(value.get("status", "missing")) + + +def control_requested(amendment_path: Path, amendment: dict[str, Any]) -> bool: + path = Path(amendment["control_file"]) + if not path.is_file(): + return False + value = read_json(path) + return ( + value.get("schema_version") == CONTROL_SCHEMA + and value.get("amendment_sha256") == sha256(amendment_path) + and value.get("status") == "pause_requested" + ) + + +def terminate_queues( + amendment: dict[str, Any], registry: Path, grace_seconds: float = 30.0 +) -> dict[str, Any]: + matched = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + signals = [] + for condition, pids in matched.items(): + for pid in pids: + try: + os.killpg(pid, signal.SIGTERM) + signals.append({"condition": condition, "pid": pid, "signal": "SIGTERM"}) + except ProcessLookupError: + pass + deadline = time.monotonic() + grace_seconds + while time.monotonic() < deadline: + remaining = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + if not any(remaining.values()): + return {"matched": matched, "signals": signals, "remaining": remaining} + time.sleep(0.5) + remaining = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + return {"matched": matched, "signals": signals, "remaining": remaining} + + +def launch_worker(amendment: dict[str, Any], mapping: dict[str, Any]) -> tuple[int, list[str]]: + schedule = amendment["scheduling"] + command = [ + "ionice", + "-c", + "2", + "-n", + str(schedule["io_priority"]), + "nice", + "-n", + str(schedule["cpu_nice"]), + amendment["python"], + "-m", + "scripts.run_phase9_unified_train_queue", + "--queue", + amendment["training_registry"]["path"], + "--condition", + mapping["condition"], + "--state", + mapping["state"], + "--poll-seconds", + "30", + "--allowed-physical-gpus", + ",".join(str(item) for item in schedule["physical_gpu_allowlist"]), + ] + log_path = Path(amendment["supervisor_state"]).parent / "training_logs" / ( + f"{mapping['condition'].lower()}.log" + ) + log_path.parent.mkdir(parents=True, exist_ok=True) + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, + cwd=amendment["repository"], + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + text=True, + start_new_session=True, + ) + return process.pid, command + + +def ensure_workers( + amendment: dict[str, Any], registry: dict[str, Any], state: dict[str, Any] +) -> dict[str, str]: + registry_path = Path(amendment["training_registry"]["path"]) + registry_hash = amendment["training_registry"]["sha256"] + mappings = sorted( + amendment["training_mappings"], key=lambda item: (item["priority"], item["condition"]) + ) + statuses = { + mapping["condition"]: state_status(mapping, registry_hash) + for mapping in mappings + } + terminal = { + condition: status + for condition, status in statuses.items() + if status not in RESUMABLE_STATUSES and status != "complete" + } + if terminal: + raise RuntimeError(f"terminal training state: {terminal}") + active = [] + for mapping in mappings: + pids = queue_pids(mapping, registry_path) + if len(pids) > 1: + raise RuntimeError(f"multiple queue writers: {mapping['condition']}={pids}") + if pids: + active.append(mapping["condition"]) + record = state.setdefault("workers", {}).setdefault(mapping["condition"], {}) + record["pid"] = pids[0] + record["adopted_utc"] = utc_now() + maximum = amendment["scheduling"]["max_concurrent_training_workers"] + slots = maximum - len(active) + if slots < 0: + raise RuntimeError(f"1e-6 worker cap exceeded: {len(active)} > {maximum}") + jobs = {item["condition"]: item for item in registry["conditions"]} + for mapping in mappings: + if slots <= 0 or statuses[mapping["condition"]] == "complete": + continue + if mapping["condition"] in active: + continue + children = training_child_pids(mapping) + if children: + raise RuntimeError( + f"orphan training child blocks relaunch: {mapping['condition']}={children}" + ) + job = jobs[mapping["condition"]] + if mapping["config_sha256"] != job["config_sha256"]: + raise ValueError(f"config changed before launch: {mapping['condition']}") + record = state.setdefault("workers", {}).setdefault( + mapping["condition"], {"launches": 0} + ) + launches = int(record.get("launches", 0)) + if launches >= 3: + raise RuntimeError(f"relaunch limit reached: {mapping['condition']}") + pid, command = launch_worker(amendment, mapping) + record.update( + { + "pid": pid, + "launches": launches + 1, + "launched_utc": utc_now(), + "command": command, + } + ) + active.append(mapping["condition"]) + slots -= 1 + print(f"launched {mapping['condition']} pid={pid}", flush=True) + state["active_conditions"] = active + state["reserved_gpu_slots"] = 6 - len(active) + if state["reserved_gpu_slots"] < amendment["scheduling"][ + "minimum_gpu_slots_reserved_for_world_adapter" + ]: + raise RuntimeError("World Adapter GPU reservation was violated") + return statuses + + +def validate_completion( + amendment_path: Path, amendment: dict[str, Any], registry: dict[str, Any] +) -> dict[str, Any]: + registry_hash = amendment["training_registry"]["sha256"] + jobs = {item["condition"]: item for item in registry["conditions"]} + completed = [] + for mapping in amendment["training_mappings"]: + state_path = Path(mapping["state"]) + value = read_json(state_path) + job = jobs[mapping["condition"]] + marker = value.get("last_completed", {}) + checkpoint = Path(str(marker.get("checkpoint", ""))) + if ( + value.get("status") != "complete" + or value.get("queue_sha256") != registry_hash + or value.get("condition") != mapping["condition"] + or value.get("official_test_used") is not False + or marker.get("completed_step") != 405000 + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or queue_pids(mapping, Path(amendment["training_registry"]["path"])) + or training_child_pids(mapping) + ): + raise ValueError(f"terminal training output differs: {mapping['condition']}") + completed.append( + { + "condition": mapping["condition"], + "role": mapping["role"], + "logical_owner": mapping["logical_owner"], + "execution_owner": "taku3", + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": marker["checkpoint_sha256"], + "state": str(state_path.resolve()), + "state_sha256": sha256(state_path), + } + ) + return { + "schema_version": "phase9_last2_1e6_resume_training_completion_v1", + "status": "training_complete_evaluation_not_started", + "completed_utc": utc_now(), + "amendment": {"path": str(amendment_path), "sha256": sha256(amendment_path)}, + "training_registry": amendment["training_registry"], + "conditions": completed, + "condition_count": 7, + "evaluation_started": False, + "scientific_fields_changed": [], + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def run(args: argparse.Namespace) -> None: + amendment_path = args.amendment.resolve() + amendment, registry = validate_amendment(amendment_path) + state_path = args.state.resolve() + if state_path != Path(amendment["supervisor_state"]).resolve(): + raise ValueError("supervisor state path differs from amendment") + state_path.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{state_path}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state = { + "schema_version": STATE_SCHEMA, + "status": "starting", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "amendment": str(amendment_path), + "amendment_sha256": sha256(amendment_path), + "supervisor_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if state_path.is_file(): + previous = read_json(state_path) + if previous.get("amendment_sha256") != sha256(amendment_path): + raise ValueError("existing supervisor state belongs to another amendment") + if previous.get("status") == "complete": + print(json.dumps(previous, indent=2)) + return + state = previous + state["supervisor_pid"] = os.getpid() + state["resumed_utc"] = utc_now() + while True: + validate_world_adapter_terminal(amendment, require_inactive=False) + world_adapter_pids = world_adapter_active_pids( + amendment["world_adapter_isolation"]["formal_root"] + ) + if world_adapter_pids: + termination = terminate_queues( + amendment, Path(amendment["training_registry"]["path"]) + ) + state["status"] = "paused_for_world_adapter" + state["world_adapter_active_pids"] = world_adapter_pids + state["world_adapter_pause"] = termination + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if any(termination["remaining"].values()): + raise RuntimeError( + "some queue workers survived the World Adapter priority pause" + ) + return + if control_requested(amendment_path, amendment): + termination = terminate_queues( + amendment, Path(amendment["training_registry"]["path"]) + ) + state["status"] = "paused_by_manual_request" + state["pause"] = termination + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if any(termination["remaining"].values()): + raise RuntimeError("some queue workers survived the pause request") + return + statuses = ensure_workers(amendment, registry, state) + state["training_statuses"] = statuses + state["status"] = "training" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if all(status == "complete" for status in statuses.values()): + report = validate_completion(amendment_path, amendment, registry) + report_path = Path(amendment["training_completion_report"]) + if report_path.is_file(): + raise ValueError(f"completion report already exists: {report_path}") + atomic_json(report_path, report) + os.chmod(report_path, 0o444) + state["status"] = "complete" + state["training_completion_report"] = binding(report_path) + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + print(json.dumps(state, indent=2)) + return + time.sleep(args.poll_seconds) + + +def control(args: argparse.Namespace) -> None: + amendment_path = args.amendment.resolve() + amendment, _ = validate_amendment(amendment_path) + path = Path(amendment["control_file"]) + value = { + "schema_version": CONTROL_SCHEMA, + "status": "pause_requested" if args.action == "pause" else "cleared", + "created_utc": utc_now(), + "requested_by": f"{getpass.getuser()}@{socket.gethostname()}", + "amendment": str(amendment_path), + "amendment_sha256": sha256(amendment_path), + "note": args.note, + } + atomic_json(path, value) + print(json.dumps({"path": str(path), "sha256": sha256(path)}, indent=2)) + + +def status(args: argparse.Namespace) -> None: + amendment, registry = validate_amendment(args.amendment.resolve()) + registry_hash = amendment["training_registry"]["sha256"] + statuses = { + item["condition"]: state_status(item, registry_hash) + for item in amendment["training_mappings"] + } + active = { + item["condition"]: queue_pids( + item, Path(amendment["training_registry"]["path"]) + ) + for item in amendment["training_mappings"] + } + print( + json.dumps( + { + "amendment_sha256": sha256(args.amendment), + "training_statuses": statuses, + "active_queue_pids": active, + "world_adapter_active_pids": world_adapter_active_pids( + amendment["world_adapter_isolation"]["formal_root"] + ), + "target_step": registry["target_step"], + }, + indent=2, + ) + ) + + +def parser() -> argparse.ArgumentParser: + result = argparse.ArgumentParser() + subparsers = result.add_subparsers(dest="command", required=True) + freeze_parser = subparsers.add_parser("freeze") + freeze_parser.add_argument("--original-plan", type=Path, required=True) + freeze_parser.add_argument("--original-state", type=Path, required=True) + freeze_parser.add_argument("--training-registry", type=Path, required=True) + freeze_parser.add_argument("--distributed-assignment", type=Path, required=True) + freeze_parser.add_argument("--repository", type=Path, required=True) + freeze_parser.add_argument("--python", type=Path, required=True) + freeze_parser.add_argument("--training-runner", type=Path, required=True) + freeze_parser.add_argument("--model-training-runner", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-formal-root", required=True) + freeze_parser.add_argument("--world-adapter-training-state", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-evaluation-state", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-comparison-report", type=Path, required=True) + freeze_parser.add_argument("--external-owner-checked-utc", required=True) + freeze_parser.add_argument("--external-owner-process-count", type=int, required=True) + freeze_parser.add_argument("--authorized-by", required=True) + freeze_parser.add_argument("--authorization-note", required=True) + freeze_parser.add_argument("--supervisor-state", type=Path, required=True) + freeze_parser.add_argument("--completion-report", type=Path, required=True) + freeze_parser.add_argument("--control-file", type=Path, required=True) + freeze_parser.add_argument("--output", type=Path, required=True) + freeze_parser.set_defaults(function=freeze) + run_parser = subparsers.add_parser("run") + run_parser.add_argument("--amendment", type=Path, required=True) + run_parser.add_argument("--state", type=Path, required=True) + run_parser.add_argument("--poll-seconds", type=float, default=30.0) + run_parser.set_defaults(function=run) + status_parser = subparsers.add_parser("status") + status_parser.add_argument("--amendment", type=Path, required=True) + status_parser.set_defaults(function=status) + control_parser = subparsers.add_parser("control") + control_parser.add_argument("action", choices=("pause", "resume")) + control_parser.add_argument("--amendment", type=Path, required=True) + control_parser.add_argument("--note") + control_parser.set_defaults(function=control) + return result + + +def main() -> None: + args = parser().parse_args() + if getattr(args, "poll_seconds", 30.0) < 1: + raise ValueError("poll interval must be at least one second") + args.function(args) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_cache_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..880a58c8892f00aa6bfa02fb81d2bf8683a0808c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_cache_queue.py @@ -0,0 +1,372 @@ +#!/usr/bin/env python3 +"""Run one winner-gated, resumable Phase 9 resolution cache worker.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def validate_plan_bindings(plan: dict[str, Any]) -> None: + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution execution plan lacks official-data isolation") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution plan binding differs: {path}") + validate_execution_contract(plan) + + +def validate_execution_contract(plan: dict[str, Any]) -> None: + root = Path(plan["physical_root"]) + output_directories = [Path(path) for path in plan["output_directories"]] + if len(output_directories) != len(set(output_directories)): + raise ValueError("resolution output directories are not unique") + if any(path != root and root not in path.parents for path in output_directories): + raise ValueError("resolution output directory is outside the physical root") + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("resolution physical root is not on /SSD2") + + worker_ids: set[str] = set() + owned_outputs: dict[Path, str] = {} + cache_steps: list[dict[str, Any]] = [] + for worker in plan["workers"]: + worker_id = worker["id"] + if worker_id in worker_ids: + raise ValueError(f"duplicate resolution worker: {worker_id}") + worker_ids.add(worker_id) + if Path(worker["state"]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution worker state is not on /SSD2: {worker_id}") + step_ids: set[str] = set() + for step in worker["steps"]: + if step["id"] in step_ids: + raise ValueError(f"duplicate step in resolution worker: {worker_id}") + step_ids.add(step["id"]) + if step["kind"] in {"cache", "sidecar"}: + output = Path(step["output_dir"]) + owner = owned_outputs.setdefault(output, worker_id) + if owner != worker_id: + raise ValueError(f"resolution output has multiple writers: {output}") + if step["kind"] == "cache": + cache_steps.append(step) + for command_name in ("start_command", "resume_command"): + command = step[command_name] + if command and not any( + command[index:index + 3] == ["--target-hw", "512", "896"] + for index in range(len(command) - 2) + ): + raise ValueError( + f"resolution cache command lacks 512x896 target: " + f"{worker_id}/{step['id']}/{command_name}" + ) + + cache_contracts = { + (item["manifest"], item["report"], int(item["clips"])) + for item in plan["caches"] + } + step_contracts = { + (step["manifest"], step["report"], int(step["expected_clips"])) + for step in cache_steps + } + if not cache_contracts <= step_contracts: + raise ValueError("resolution audit cache lacks a matching writer step") + + +def selection_winner(plan: dict[str, Any]) -> dict[str, Any] | None: + state_path = Path(plan["selection_state"]) + report_path = Path(plan["selection_report"]) + if not state_path.is_file() or not report_path.is_file(): + return None + state = json.loads(state_path.read_text(encoding="utf-8")) + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or state.get("winner") != report.get("winner") + or state.get("winner_checkpoint") != report.get("winner_checkpoint") + ): + return None + checkpoint = Path(report["winner_checkpoint"]["path"]) + config = Path(report["winner_config"]["path"]) + if ( + not checkpoint.is_file() + or sha256(checkpoint) != report["winner_checkpoint"]["sha256"] + or not config.is_file() + or sha256(config) != report["winner_config"]["sha256"] + ): + return None + return { + "winner": report["winner"], + "winner_checkpoint": report["winner_checkpoint"], + "winner_config": report["winner_config"], + } + + +def ensure_admission(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any] | None: + admission_path = Path(plan["admission_state"]) + admission_path.parent.mkdir(parents=True, exist_ok=True) + lock_path = Path(f"{admission_path}.lock") + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if admission_path.is_file(): + admission = json.loads(admission_path.read_text(encoding="utf-8")) + if ( + admission.get("status") != "complete" + or admission.get("plan_sha256") != sha256(plan_path) + or admission.get("official_test_used") is not False + ): + raise ValueError("resolution admission state differs") + return admission + winner = selection_winner(plan) + if winner is None: + return None + root = Path(plan["physical_root"]) + if root.exists() or any(Path(path).exists() for path in plan["output_directories"]): + raise ValueError("resolution output exists before admission") + available_gib = shutil.disk_usage(root.parent).free / (1024 ** 3) + if available_gib < float(plan["minimum_available_gib"]): + raise ValueError("SSD2 free space is below the frozen admission minimum") + admission = { + "schema_version": "phase9_resolution_admission_v1", + "status": "complete", + "admitted_utc": utc_now(), + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "scientific_stage_admitted": True, + "trigger": "frozen_full_data_640_winner_complete", + "available_gib": available_gib, + **winner, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(admission_path, admission) + return admission + + +def cache_step_complete(step: dict[str, Any], require_resume: bool) -> bool: + report_path = Path(step["report"]) + manifest_path = Path(step["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + count = report.get("cached_clips", report.get("clips")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and tuple(report.get("resolution_hw", ())) == (512, 896) + and report.get("source_manifest", {}).get("sha256") + == step["source_manifest_sha256"] + and report.get("cache_manifest", {}).get("sha256") == sha256(manifest_path) + and int(count) == int(step["expected_clips"]) + and (not require_resume or report.get("resume_invocation") is True) + ) + + +def sidecar_step_complete(step: dict[str, Any]) -> bool: + report_path = Path(step["report"]) + manifest_path = Path(step["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("base_cache_manifest", {}).get("sha256") + == sha256(step["base_manifest"]) + and report.get("augmented_cache_manifest", {}).get("sha256") + == sha256(manifest_path) + and int(report.get("clips", -1)) == int(step["expected_clips"]) + and report.get("right_valid_joint_count") == 0 + and float(report.get("root_norm_max_mm", 1.0)) < 1e-4 + and ( + not step.get("require_resume") + or report.get("resume_invocation") is True + ) + ) + + +def multifold_step_complete(step: dict[str, Any]) -> bool: + path = Path(step["index"]) + if not path.is_file(): + return False + index = json.loads(path.read_text(encoding="utf-8")) + return ( + index.get("status") == "complete" + and index.get("official_test_used") is False + and index.get("h2o_official_validation_used") is False + and index.get("source_cache_manifest", {}).get("sha256") + == sha256(step["source_manifest"]) + and len(index.get("folds", [])) == 6 + ) + + +def step_complete(step: dict[str, Any]) -> bool: + if step["kind"] == "cache": + return cache_step_complete(step, bool(step.get("require_resume"))) + if step["kind"] == "sidecar": + return sidecar_step_complete(step) + if step["kind"] == "multifold": + return multifold_step_complete(step) + raise ValueError(f"unsupported resolution step kind: {step['kind']}") + + +def runtime_command(step: dict[str, Any]) -> list[str]: + if step["kind"] == "cache": + output = Path(step["output_dir"]) + command = step["resume_command"] if output.exists() else step["start_command"] + elif step["kind"] == "sidecar": + output = Path(step["output_dir"]) + command = step["resume_command"] if output.exists() else step["start_command"] + else: + command = step["command"] + base_hash = sha256(step["base_manifest"]) if step.get("base_manifest") else None + return [base_hash if token == "{BASE_CACHE_SHA256}" else token for token in command] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan_bindings(plan) + except ValueError as error: + parser.error(str(error)) + workers = {worker["id"]: worker for worker in plan["workers"]} + if args.worker not in workers: + parser.error(f"unknown resolution worker: {args.worker}") + worker = workers[args.worker] + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("worker state path differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + state_lock = Path(f"{args.state}.lock").open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + plan_hash = sha256(args.plan) + state = { + "schema_version": "phase9_resolution_cache_worker_state_v1", + "status": "waiting_for_640_winner", + "worker": args.worker, + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "started_utc": utc_now(), + "updated_utc": utc_now(), + "completed_steps": [], + "attempts": [], + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash or previous.get("worker") != args.worker: + parser.error("existing resolution state belongs to another plan/worker") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + try: + admission = ensure_admission(args.plan, plan) + except ValueError as error: + state["status"] = "failed_admission" + state["failure"] = str(error) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + if admission is not None: + break + state["status"] = "waiting_for_640_winner" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["admission_state"] = plan["admission_state"] + state["admission_state_sha256"] = sha256(plan["admission_state"]) + state["winner"] = admission["winner"] + state["winner_checkpoint"] = admission["winner_checkpoint"] + state["winner_config"] = admission["winner_config"] + atomic_json(args.state, state) + for step in worker["steps"]: + if step["id"] in state["completed_steps"] and step_complete(step): + continue + if step.get("always_run") is not True and step_complete(step): + state["completed_steps"].append(step["id"]) + atomic_json(args.state, state) + continue + command = runtime_command(step) + log_path = args.state.parent / f"{args.worker}_{step['id']}.log" + attempt = { + "step": step["id"], "kind": step["kind"], + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_step"] = step["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ, PYTHONPATH=str(Path.cwd())) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not step_complete(step): + state["status"] = "failed_resumable" + state["failure"] = { + "step": step["id"], "returncode": result.returncode, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + if step["id"] not in state["completed_steps"]: + state["completed_steps"].append(step["id"]) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_cache_supervisor.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_cache_supervisor.py new file mode 100644 index 0000000000000000000000000000000000000000..8eddded62d805d7d1f45f69aa0d13b3d7ad675e9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_cache_supervisor.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Supervise owner-bound Stage 7 cache workers and the readiness finalizer.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def process_matches(tokens: list[str]) -> list[int]: + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (OSError, UnicodeDecodeError): + continue + if all(token in command for token in tokens): + matches.append(int(entry.name)) + return sorted(matches) + + +def read_json(path: str | Path) -> dict[str, Any] | None: + candidate = Path(path) + if not candidate.is_file(): + return None + return json.loads(candidate.read_text(encoding="utf-8")) + + +def latest_progress(path: Path) -> dict[str, Any] | None: + if not path.is_file(): + return None + with path.open("rb") as handle: + handle.seek(0, os.SEEK_END) + size = handle.tell() + handle.seek(max(0, size - 256 * 1024)) + lines = handle.read().decode("utf-8", errors="replace").splitlines() + for line in reversed(lines): + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and any( + key in value for key in ("processed", "decoded", "cached", "clips") + ): + return value + return None + + +def classify_failure(state: dict[str, Any], transient_returncodes: set[int]) -> str: + status = str(state.get("status", "missing")) + if not status.startswith("failed"): + return "not_failed" + if status != "failed_resumable": + return "terminal_failure" + returncode = state.get("failure", {}).get("returncode") + if returncode == 0: + return "terminal_contract_mismatch" + if returncode in transient_returncodes: + return "known_transient_resumable" + return "terminal_unregistered_resumable" + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("owner") != "taku3" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution supervisor plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution supervisor binding differs: {path}") + execution = plan["cache_execution_plan"] + path = Path(execution["path"]) + if not path.is_file() or sha256(path) != execution["sha256"]: + raise ValueError("resolution supervisor cache execution plan differs") + ids = [worker["id"] for worker in plan["local_workers"]] + if len(ids) != len(set(ids)) or "hot3d" in ids: + raise ValueError("resolution supervisor local ownership differs") + if Path(plan["disk"]["path"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution supervisor disk is not /SSD2") + if Path(plan["state"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution supervisor state is not /SSD2") + + +def launch(command: list[str], log_path: Path) -> int: + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ, PYTHONPATH=str(Path.cwd())), + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def local_worker_snapshot( + worker: dict[str, Any], *, plan_hash: str, now: float, + transient_returncodes: set[int], +) -> dict[str, Any]: + state_path = Path(worker["state"]) + state = read_json(state_path) + controllers = process_matches(worker["process_tokens"]) + result: dict[str, Any] = { + "id": worker["id"], "owner": "taku3", + "state": str(state_path.resolve()), "controller_pids": controllers, + } + if state is None: + result.update(status="missing", classification="missing_state") + return result + if ( + state.get("worker") != worker["id"] + or state.get("plan_sha256") != plan_hash + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + result.update(status=state.get("status"), classification="terminal_binding_mismatch") + return result + attempt = state.get("attempts", [])[-1] if state.get("attempts") else {} + log_path = Path(attempt["log"]) if attempt.get("log") else None + state_mtime = state_path.stat().st_mtime + result.update({ + "status": state.get("status"), "current_step": state.get("current_step"), + "completed_steps": state.get("completed_steps", []), + "state_sha256": sha256(state_path), + "state_heartbeat_age_seconds": round(max(0.0, now - state_mtime), 3), + "classification": classify_failure(state, transient_returncodes), + "log": str(log_path.resolve()) if log_path else None, + "log_mtime_age_seconds": ( + round(max(0.0, now - log_path.stat().st_mtime), 3) + if log_path and log_path.is_file() else None + ), + "progress": latest_progress(log_path) if log_path else None, + }) + return result + + +def remote_json(host: str, path: str, timeout: float) -> dict[str, Any] | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if completed.returncode: + return None + try: + value = json.loads(completed.stdout) + except json.JSONDecodeError: + return None + return value if isinstance(value, dict) else None + + +def external_snapshot(external: dict[str, Any]) -> dict[str, Any]: + queue = remote_json( + external["host"], external["queue_state"], external["ssh_timeout_seconds"], + ) + release = remote_json( + external["host"], external["release_state"], external["ssh_timeout_seconds"], + ) + if queue is None: + return { + "id": external["id"], "owner": external["owner"], + "status": "remote_unreachable_or_state_missing", + "classification": "external_monitor_alert", + } + status = str(queue.get("status", "missing")) + if release and release.get("status") == "complete_immutable_release": + display_status = "immutable_release_ready" + elif status == "complete": + display_status = "waiting_for_immutable_release" + else: + display_status = "waiting_for_server_new_immutable_release" + return { + "id": external["id"], "owner": external["owner"], + "status": display_status, "queue_status": status, + "queue_updated_utc": queue.get("updated_utc"), + "shard_statuses": queue.get("shard_statuses", {}), + "release_status": release.get("status") if release else "missing", + "classification": "external_owned_monitor_only", + } + + +def alarms_for( + workers: list[dict[str, Any]], *, log_stale_seconds: float, +) -> list[dict[str, Any]]: + alarms = [] + for worker in workers: + classification = worker.get("classification") + if classification and classification.startswith("terminal"): + alarms.append({"worker": worker["id"], "reason": classification}) + if ( + worker.get("status") == "running" + and not worker.get("controller_pids") + ): + alarms.append({"worker": worker["id"], "reason": "running_state_without_controller"}) + age = worker.get("log_mtime_age_seconds") + if ( + worker.get("status") == "running" and age is not None + and age > log_stale_seconds + ): + alarms.append({"worker": worker["id"], "reason": "stale_progress_log", "age_seconds": age}) + return alarms + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1 and not args.once: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("resolution supervisor state path differs") + execution_hash = plan["cache_execution_plan"]["sha256"] + transient = {int(value) for value in plan["known_transient_returncodes"]} + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + existing = read_json(args.state) or {} + recovery_attempts = dict(existing.get("recovery_attempts", {})) + while True: + now = time.time() + local = [ + local_worker_snapshot( + worker, plan_hash=execution_hash, now=now, + transient_returncodes=transient, + ) + for worker in plan["local_workers"] + ] + recoveries = [] + for worker, snapshot in zip(plan["local_workers"], local, strict=True): + restartable = ( + snapshot["classification"] == "known_transient_resumable" + or snapshot["status"] in worker.get("restartable_statuses", []) + ) + attempts = int(recovery_attempts.get(worker["id"], 0)) + if ( + restartable and not snapshot["controller_pids"] + and attempts < int(plan["max_exact_resume_attempts"]) + ): + pid = launch(worker["resume_command"], Path(worker["supervisor_log"])) + attempts += 1 + recovery_attempts[worker["id"]] = attempts + recoveries.append({ + "worker": worker["id"], "pid": pid, "attempt": attempts, + "kind": "exact_frozen_queue_resume", "launched_utc": utc_now(), + }) + external = [external_snapshot(item) for item in plan["external_workers"]] + finalizer = plan["finalizer"] + finalizer_pids = process_matches(finalizer["process_tokens"]) + readiness = read_json(finalizer["state"]) + blocking_failure = any( + str(worker.get("status", "")).startswith("failed") for worker in local + ) + finalizer_recovery = None + if ( + not finalizer_pids + and (readiness or {}).get("status") != "complete" + and not blocking_failure + ): + pid = launch(finalizer["command"], Path(finalizer["log"])) + finalizer_pids = [pid] + finalizer_recovery = { + "pid": pid, "kind": "readiness_finalizer_restart", + "launched_utc": utc_now(), + } + disk = shutil.disk_usage(plan["disk"]["path"]) + disk_record = { + "path": plan["disk"]["path"], + "free_gib": round(disk.free / (1024 ** 3), 3), + "total_gib": round(disk.total / (1024 ** 3), 3), + } + alarms = alarms_for( + local, log_stale_seconds=float(plan["log_stale_seconds"]), + ) + if disk_record["free_gib"] < float(plan["disk"]["minimum_free_gib"]): + alarms.append({"worker": "disk", "reason": "minimum_free_space_breached"}) + state = { + "schema_version": "phase9_resolution_cache_supervisor_state_v1", + "status": "alert" if alarms else "monitoring", + "updated_utc": utc_now(), "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), "local_workers": local, + "external_workers": external, + "readiness": { + "status": (readiness or {}).get("status", "missing"), + "updated_utc": (readiness or {}).get("updated_utc"), + "finalizer_pids": finalizer_pids, + "recovery": finalizer_recovery, + }, + "disk": disk_record, "alarms": alarms, + "recoveries_this_poll": recoveries, + "recovery_attempts": recovery_attempts, + "max_exact_resume_attempts": plan["max_exact_resume_attempts"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + if args.once: + print(json.dumps(state, indent=2)) + return + time.sleep(args.poll_seconds) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_evaluation_controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..64ea48925512f43aa2084947f82545ea83ac8f44 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_evaluation_controller.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""Supervise Stage 7 evaluation workers and freeze the resolution decision.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or plan.get("evaluation_count") != 25 + or plan.get("worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + ): + raise ValueError("resolution evaluation controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution evaluation binding differs: {path}") + + +def training_complete(plan: dict[str, Any]) -> bool: + path = Path( + plan.get("training_controller_states", {}).get( + "taku3", plan["training_controller_state"] + ) + ) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + registry = Path(state.get("training_registry", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["training_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and registry.is_file() + and state.get("training_registry_sha256") == sha256(registry) + ) + + +def pid_matches(pid: int, worker: str, evaluation_plan: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_resolution_evaluation_worker" in command + and f"--worker {worker}" in command + and str(evaluation_plan.resolve()) in command + ) + + +def worker_status(path: Path, plan_sha256: str) -> str: + if not path.is_file(): + return "missing" + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_sha256: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def hard_failure(status: str) -> bool: + return status.startswith("failed") and status != "failed_resumable" + + +def should_launch(worker: dict[str, Any], machine: str, status: str) -> bool: + return ( + worker.get("owner") == machine + and status != "complete" + and not hard_failure(status) + ) + + +def launch_worker( + evaluation_plan: Path, worker: dict[str, Any], log_path: Path, +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_evaluation_worker", + "--plan", str(evaluation_plan.resolve()), "--worker", worker["id"], + "--state", worker["state"], "--poll-seconds", "30", + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("resolution evaluation controller state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + static_plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_evaluation_controller_state_v1", + "status": "waiting_for_resolution_training", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_plan_hash, + "machine": machine, + "controller_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != static_plan_hash: + parser.error("existing evaluation controller state differs") + if state.get("machine") != machine: + parser.error("existing evaluation state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not training_complete(plan): + state["status"] = "waiting_for_resolution_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_resolution_evaluation_plan", + "--training-controller-plan", plan["training_controller_plan"], + "--training-controller-state", plan["training_controller_state"], + "--cache-plan", plan["cache_execution_plan"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_plan_hash = sha256(evaluation_plan) + dynamic = json.loads(evaluation_plan.read_text(encoding="utf-8")) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = evaluation_plan_hash + state["owned_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("workers", {}) + + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + worker_state = Path(worker["state"]) + status = worker_status(worker_state, evaluation_plan_hash) + statuses[worker["id"]] = status + if not should_launch(worker, machine, status): + continue + previous_pid = int( + state["workers"].get(worker["id"], {}).get("pid", -1) + ) + if not pid_matches(previous_pid, worker["id"], evaluation_plan): + pid = launch_worker( + evaluation_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "worker_processes": state["workers"], + } + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + decision = Path(plan["decision_report"]) + if not decision.exists(): + command = [ + sys.executable, "-m", "scripts.summarize_phase9_resolution_decision", + "--plan", str(evaluation_plan), + "--control-external-root", plan["control_external_root"], + "--control-fold-final-root", plan["control_fold_final_root"], + "--control-fold-milestone-root", plan["control_fold_milestone_root"], + "--output", str(decision), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = json.loads(decision.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != evaluation_plan_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["accepted_resolution_hw"] = report["accepted_resolution_hw"] + state["decision_report"] = { + "path": str(decision.resolve()), "sha256": sha256(decision), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_evaluation_resource_recovery.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_evaluation_resource_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..2edf205a25ace56f727b1148bf1478dc02fbc5fa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_evaluation_resource_recovery.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Rebind one unstarted logical evaluation worker to an idle allowed GPU.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.train_phase7_external import assert_physical_gpu_idle + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_amendment(path: Path, value: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + plan_path = Path(value.get("evaluation_plan", {}).get("path", "")) + controller_plan = Path(value.get("controller_plan", "")) + if ( + value.get("schema_version") != "phase9_resolution_evaluation_resource_amendment_v1" + or value.get("status") != "frozen" + or value.get("worker") != "server_new_gpu5" + or value.get("owner") != "server_new" + or value.get("planned_physical_gpu_id") != 5 + or value.get("replacement_physical_gpu_id") not in {0, 1, 2} + or value.get("evaluation_ids") + != ["loso_subject3_rgb_d_k", "lofamily_k_rgb_k"] + or value.get("requires_dynamic_idle_check") is not True + or value.get("external_process_preemption_forbidden") is not True + or value.get("scientific_fields_changed") != [] + or any(value.get(key) is not False for key in ( + "model_changed", "data_changed", "seed_changed", "metric_changed", + "selection_gate_changed", "official_test_used", + "h2o_official_validation_used", + )) + or not plan_path.is_file() + or sha256(plan_path) != value.get("evaluation_plan", {}).get("sha256") + or not controller_plan.is_file() + or sha256(controller_plan) != value.get("controller_plan_sha256") + ): + raise ValueError("resolution evaluation resource amendment differs") + plan = read_json(plan_path) + worker = next(item for item in plan["workers"] if item["id"] == value["worker"]) + if ( + worker.get("owner") != value["owner"] + or worker.get("physical_gpu_id") != value["planned_physical_gpu_id"] + or worker.get("evaluation_ids") != value["evaluation_ids"] + or worker.get("state") != value["original_state"] + or value["replacement_physical_gpu_id"] not in {0, 1, 2, 5} + or plan.get("official_test_used") is not False + ): + raise ValueError("resolution evaluation recovery worker binding differs") + if not path.is_file(): + raise ValueError("resolution evaluation resource amendment is unreadable") + return plan, worker + + +def imported_state( + recovery: dict[str, Any], amendment_path: Path, amendment: dict[str, Any], + original_plan_path: Path, +) -> dict[str, Any]: + if ( + recovery.get("status") != "complete" + or recovery.get("worker") != amendment["worker"] + or recovery.get("owner") != amendment["owner"] + or recovery.get("assigned_evaluation_ids") != amendment["evaluation_ids"] + or recovery.get("completed_ids") != amendment["evaluation_ids"] + or recovery.get("official_test_used") is not False + or recovery.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution evaluation recovery state differs") + return { + **recovery, + "schema_version": "phase9_resolution_evaluation_worker_state_v1", + "plan": str(original_plan_path.resolve()), + "plan_sha256": amendment["evaluation_plan"]["sha256"], + "physical_gpu_id": amendment["replacement_physical_gpu_id"], + "planned_physical_gpu_id": amendment["planned_physical_gpu_id"], + "resource_amendment": { + "path": str(amendment_path.resolve()), "sha256": sha256(amendment_path), + "reason": amendment["reason"], + }, + "source_recovery_state": { + "path": str(Path(amendment["recovery_state"]).resolve()), + "sha256": sha256(amendment["recovery_state"]), + }, + "imported_utc": utc_now(), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--amendment", type=Path, required=True) + args = parser.parse_args() + amendment = read_json(args.amendment) + try: + plan, worker = validate_amendment(args.amendment, amendment) + assert_physical_gpu_idle(amendment["replacement_physical_gpu_id"]) + except (ValueError, RuntimeError) as error: + parser.error(str(error)) + + original_state = Path(amendment["original_state"]) + backup = Path(amendment["original_state_backup"]) + if original_state.is_file(): + old = read_json(original_state) + if old.get("status") != "waiting_for_idle_gpu" or old.get("attempts") != []: + parser.error("logical GPU5 worker is not an unstarted waiter") + backup.parent.mkdir(parents=True, exist_ok=True) + if backup.exists() and sha256(backup) != sha256(original_state): + parser.error("logical GPU5 waiter backup differs") + if not backup.exists(): + shutil.copy2(original_state, backup) + os.chmod(backup, 0o444) + original_state.unlink() + + amended = deepcopy(plan) + amended_worker = next(item for item in amended["workers"] if item["id"] == amendment["worker"]) + amended_worker["physical_gpu_id"] = amendment["replacement_physical_gpu_id"] + amended_worker["state"] = amendment["recovery_state"] + amended["resource_schedule_amendment"] = { + "path": str(args.amendment.resolve()), "sha256": sha256(args.amendment), + } + recovery_plan = Path(amendment["recovery_plan"]) + if recovery_plan.exists() and read_json(recovery_plan) != amended: + parser.error("existing resolution evaluation recovery plan differs") + if not recovery_plan.exists(): + atomic_json(recovery_plan, amended) + os.chmod(recovery_plan, 0o444) + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_evaluation_worker", + "--plan", str(recovery_plan.resolve()), "--worker", amendment["worker"], + "--state", amendment["recovery_state"], "--poll-seconds", "30", + ] + result = subprocess.run(command, check=False) + if result.returncode: + raise SystemExit(result.returncode) + recovery = read_json(amendment["recovery_state"]) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if any(not evaluation_complete(evaluations[identifier]) for identifier in amendment["evaluation_ids"]): + raise ValueError("resolution evaluation recovery output differs") + imported = imported_state( + recovery, args.amendment, amendment, + Path(amendment["evaluation_plan"]["path"]), + ) + temporary = original_state.with_suffix(".importing") + atomic_json(temporary, imported) + os.replace(temporary, original_state) + controller_command = [ + sys.executable, "-u", "-m", "scripts.run_phase9_resolution_evaluation_controller", + "--plan", amendment["controller_plan"], "--state", amendment["controller_state"], + "--machine", "server_new", "--poll-seconds", "30", + ] + with Path(amendment["controller_log"]).open("a", encoding="utf-8") as log: + process = subprocess.Popen( + controller_command, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + print(json.dumps({ + "status": "complete", "imported_state": str(original_state.resolve()), + "imported_state_sha256": sha256(original_state), + "controller_pid": process.pid, "completed_utc": utc_now(), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_evaluation_worker.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_evaluation_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..71abe7979fd0b9d390223e80008f859de2a7200b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_evaluation_worker.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +"""Run one fixed-GPU shard of Stage 7 resolution evaluations.""" + +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time +from typing import Any, Iterator + +from scripts.phase9_distributed_assignment import ( + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +@contextmanager +def output_lock(output: Path) -> Iterator[None]: + output.parent.mkdir(parents=True, exist_ok=True) + path = output.parent / f".{output.name}.resolution-evaluation.lock" + with path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + yield + + +def evaluation_complete(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + bindings_match = ( + report.get("status") == f"evaluated_{item['evaluation_role']}" + and report.get("evaluation_role") == item["evaluation_role"] + and report.get("input_mode") == item["input_mode"] + and report.get("checkpoint", {}).get("path") == item["checkpoint"] + and report.get("checkpoint", {}).get("sha256") + == item["checkpoint_sha256"] + and report.get("config", {}).get("path") == item["config"] + and report.get("config", {}).get("sha256") == item["config_sha256"] + and report.get("cache_manifest", {}).get("path") + == item["cache_manifest"] + and report.get("cache_manifest", {}).get("sha256") + == item["cache_manifest_sha256"] + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + ) + if not bindings_match: + return False + for key in ("raw_predictions", "per_hand_rows", "take_metrics"): + artifact = report.get(key, {}) + path = Path(str(artifact.get("path", ""))) + if not path.is_file() or artifact.get("sha256") != sha256(path): + return False + return ( + isinstance(report.get("clips"), int) and report["clips"] > 0 + and isinstance(report.get("frames"), int) and report["frames"] > 0 + ) + + +def validate_inputs(items: list[dict[str, Any]]) -> None: + expected: dict[Path, str] = {} + for item in items: + for path_key, hash_key in ( + ("config", "config_sha256"), + ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256"), + ): + path = Path(item[path_key]) + digest = item[hash_key] + if path in expected and expected[path] != digest: + raise ValueError(f"evaluation input has conflicting hashes: {path}") + expected[path] = digest + for path, digest in expected.items(): + if not path.is_file() or sha256(path) != digest: + raise ValueError(f"resolution evaluation input differs: {path}") + + +def evaluation_command( + item: dict[str, Any], gpu: int, heartbeat_path: Path | None = None, + heartbeat_seconds: float = 30.0, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", item["evaluation_role"], + ] + if heartbeat_path is not None: + command.extend(( + "--evaluation-id", item["id"], + "--heartbeat-path", str(heartbeat_path.resolve()), + "--heartbeat-seconds", str(heartbeat_seconds), + )) + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def process_command(pid: int) -> str | None: + path = Path(f"/proc/{pid}/cmdline") + try: + return path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (FileNotFoundError, PermissionError, ProcessLookupError, UnicodeDecodeError): + return None + + +def evaluator_pid_matches(pid: int, item: dict[str, Any]) -> bool: + command = process_command(pid) + return bool( + command + and "scripts.evaluate_phase7_external" in command + and f"--evaluation-id {item['id']}" in command + and f"--output-dir {item['output_dir']}" in command + and f"--checkpoint {item['checkpoint']}" in command + ) + + +def process_descendants(pid: int) -> list[int]: + observed: set[int] = set() + pending = [pid] + while pending: + parent = pending.pop() + path = Path(f"/proc/{parent}/task/{parent}/children") + try: + children = [int(value) for value in path.read_text().split()] + except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError): + children = [] + for child in children: + if child not in observed: + observed.add(child) + pending.append(child) + return sorted(observed) + + +def validate_progress_heartbeat( + path: Path, item: dict[str, Any], evaluator_pid: int, +) -> dict[str, Any]: + value = json.loads(path.read_text(encoding="utf-8")) + if ( + value.get("schema_version") != "phase9_evaluation_progress_heartbeat_v1" + or value.get("evaluation_id") != item["id"] + or value.get("evaluator_pid") != evaluator_pid + or value.get("output_dir") != str(Path(item["output_dir"]).resolve()) + or value.get("official_test_used") is not False + or value.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution evaluator heartbeat differs: {item['id']}") + return value + + +def terminate_owned_process(process: subprocess.Popen[str]) -> None: + if process.poll() is not None: + return + try: + os.killpg(process.pid, 15) + except ProcessLookupError: + return + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, 9) + except ProcessLookupError: + pass + process.wait(timeout=15) + + +def run_evaluation_child( + *, command: list[str], environment: dict[str, str], log_path: Path, + heartbeat_path: Path, item: dict[str, Any], state: dict[str, Any], + state_path: Path, worker_heartbeat_seconds: float, + stall_timeout_seconds: float, +) -> tuple[int, str | None]: + started = time.monotonic() + last_progress = started + last_heartbeat_write = 0.0 + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + state["child"] = { + "pid": process.pid, "evaluation_id": item["id"], + "command": command, "started_utc": utc_now(), + } + atomic_json(state_path, state) + failure: str | None = None + try: + while process.poll() is None: + now = time.monotonic() + if not evaluator_pid_matches(process.pid, item): + failure = "evaluator_pid_or_cmdline_differs" + terminate_owned_process(process) + break + progress = None + if heartbeat_path.is_file(): + progress = validate_progress_heartbeat( + heartbeat_path, item, process.pid, + ) + age = time.time() - heartbeat_path.stat().st_mtime + last_progress = now - max(0.0, age) + if now - last_progress > stall_timeout_seconds: + failure = "evaluator_progress_stalled" + terminate_owned_process(process) + break + if now - last_heartbeat_write >= worker_heartbeat_seconds: + state["heartbeat"] = { + "updated_utc": utc_now(), "worker_pid": os.getpid(), + "evaluator_pid": process.pid, + "evaluator_cmdline_verified": True, + "descendant_pids": process_descendants(process.pid), + "log_mtime": log_path.stat().st_mtime, + "progress": progress, + "stall_timeout_seconds": stall_timeout_seconds, + } + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + last_heartbeat_write = now + time.sleep(min(5.0, worker_heartbeat_seconds)) + except Exception: + terminate_owned_process(process) + raise + returncode = process.wait() + return returncode, failure + + +def claim_when_idle(gpu: int, state: dict[str, Any], state_path: Path, poll: float) -> None: + while True: + try: + idle = assert_physical_gpu_idle(gpu) is None + except RuntimeError: + idle = False + if idle and claim_physical_gpu(gpu): + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + else: + return + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + time.sleep(poll) + + +def archive_incomplete_output( + item: dict[str, Any], state: dict[str, Any], state_path: Path, +) -> None: + output = Path(item["output_dir"]) + if not output.exists() or not any(output.iterdir()): + return + root = state_path.parent / "failed_outputs" / item["id"] + root.mkdir(parents=True, exist_ok=True) + destination = root / f"attempt_{len(state['attempts']):03d}" + if destination.exists(): + raise ValueError(f"incomplete evaluation archive already exists: {destination}") + shutil.move(str(output), str(destination)) + state.setdefault("archived_incomplete_outputs", []).append({ + "id": item["id"], "source": str(output.resolve()), + "archive": str(destination.resolve()), "archived_utc": utc_now(), + }) + atomic_json(state_path, state) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if ( + plan.get("status") != "frozen_ready" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + ): + parser.error("resolution evaluation plan is not frozen and isolated") + workers = {item["id"]: item for item in plan["workers"]} + if args.worker not in workers: + parser.error("unknown resolution evaluation worker") + worker = workers[args.worker] + try: + assignment = load_assignment(plan) + machine = detect_machine(assignment, None) + except ValueError as error: + parser.error(str(error)) + if worker.get("owner") != machine: + parser.error("evaluation worker is externally owned on this host") + if worker.get("physical_gpu_id") not in gpu_allowlist(assignment, machine): + parser.error("evaluation worker GPU is not allowed on this host") + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("resolution evaluation worker state differs from plan") + evaluations = {item["id"]: item for item in plan["evaluations"]} + items = [evaluations[identifier] for identifier in worker["evaluation_ids"]] + try: + validate_inputs(items) + except ValueError as error: + parser.error(str(error)) + + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_evaluation_worker_state_v1", + "status": "running", "worker": args.worker, + "physical_gpu_id": worker["physical_gpu_id"], + "owner": machine, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "assigned_evaluation_ids": worker["evaluation_ids"], + "completed_ids": [], "attempts": [], + "worker_pid": os.getpid(), + "started_utc": utc_now(), "updated_utc": utc_now(), + "resource_amendment": "user_authorized_idle_gpus_0_5_20260730", + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if ( + state.get("plan_sha256") != plan_hash + or state.get("worker") != args.worker + or state.get("owner") != machine + or state.get("assigned_evaluation_ids") != worker["evaluation_ids"] + ): + parser.error("existing evaluation worker state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + gpu = int(worker["physical_gpu_id"]) + for item in items: + if evaluation_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + with output_lock(Path(item["output_dir"])): + if evaluation_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + prior_attempts = sum( + attempt.get("id") == item["id"] + for attempt in state["attempts"] + ) + if prior_attempts >= plan["max_attempts_per_evaluation"]: + state["status"] = "failed_terminal_attempt_limit" + state["failure"] = { + "id": item["id"], "attempts": prior_attempts, + "reason": "maximum exact-resume attempts exhausted", + } + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + archive_incomplete_output(item, state, args.state) + claim_when_idle(gpu, state, args.state, args.poll_seconds) + heartbeat_path = Path(item["output_dir"]) / "evaluation_heartbeat.json" + command = evaluation_command( + item, gpu, heartbeat_path, + plan["evaluator_progress_heartbeat_seconds"], + ) + log_path = args.state.parent / "logs" / f"{item['id']}.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "id": item["id"], "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_evaluation"] = item["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + returncode, failure = run_evaluation_child( + command=command, environment=environment, + log_path=log_path, heartbeat_path=heartbeat_path, + item=item, state=state, state_path=args.state, + worker_heartbeat_seconds=plan["worker_heartbeat_seconds"], + stall_timeout_seconds=plan["stall_timeout_seconds"], + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = returncode + attempt["supervisor_failure"] = failure + state["updated_utc"] = utc_now() + if returncode or failure or not evaluation_complete(item): + attempt_count = sum( + value.get("id") == item["id"] + for value in state["attempts"] + ) + state["status"] = ( + "failed_terminal_attempt_limit" + if attempt_count >= plan["max_attempts_per_evaluation"] + else "failed_resumable" + ) + state["failure"] = { + "id": item["id"], "returncode": returncode, + "supervisor_failure": failure, + "attempts": attempt_count, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(returncode or 1) + state["completed_ids"].append(item["id"]) + state.pop("child", None) + state.pop("failure", None) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_training_controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..d6998ea02b27bfb0fc1d9a1c08cff8d426138ced --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_resolution_training_controller.py @@ -0,0 +1,268 @@ +#!/usr/bin/env python3 +"""Admit and supervise matched Phase 9 resolution training jobs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or float(plan.get("worst_domain_relative_regression_limit", -1)) != 0.01 + ): + raise ValueError("resolution training controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution training binding differs: {path}") + + +def readiness_complete(plan: dict[str, Any]) -> bool: + path = Path(plan["readiness_state"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + audit = Path(state.get("audit", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["cache_execution_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and audit.is_file() + and state.get("audit", {}).get("sha256") == sha256(audit) + ) + + +def pid_matches(pid: int, condition: str, registry: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_unified_train_queue" in command + and f"--condition {condition}" in command + and str(registry.resolve()) in command + ) + + +def condition_status(state_path: Path, registry_sha256: str) -> str: + if not state_path.is_file(): + return "missing" + state = json.loads(state_path.read_text(encoding="utf-8")) + if state.get("queue_sha256") != registry_sha256: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def hard_failure(status: str) -> bool: + return status.startswith("failed") and status != "failed_resumable" + + +def launch_worker( + condition: str, registry: Path, state_path: Path, log_path: Path, + allowed_gpus: list[int], +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry.resolve()), "--condition", condition, + "--state", str(state_path.resolve()), "--poll-seconds", "30", + "--allowed-physical-gpus", ",".join(str(gpu) for gpu in allowed_gpus), + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("resolution training controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_training_controller_state_v1", + "status": "waiting_for_cache_readiness", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "machine": machine, + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing controller state belongs to another plan") + if state.get("machine") != machine: + parser.error("existing controller state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not readiness_complete(plan): + state["status"] = "waiting_for_cache_readiness" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry = Path(plan["training_registry"]) + builder_state = Path(plan["registry_builder_state"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_resolution_training_registry", + "--selection-report", plan["selection_report"], + "--readiness-state", plan["readiness_state"], + "--cache-plan", plan["cache_execution_plan"], + "--unified-queue", plan["unified_training_queue"], + "--fold-queue", plan["fold_training_queue"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), "--state", str(builder_state), + ] + if machine == "taku3": + state["status"] = "building_registry" + state["builder_command"] = builder_command + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_registry_builder" + state["builder_returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry_sha256 = sha256(registry) + registry_payload = json.loads(registry.read_text(encoding="utf-8")) + conditions = [item["condition"] for item in registry_payload["conditions"]] + owners = condition_owners(registry_payload, assignment) + if ( + len(conditions) != 7 + or len(set(conditions)) != 7 + or registry_payload.get("gate", {}).get( + "worst_domain_relative_regression_limit" + ) != plan["worst_domain_relative_regression_limit"] + or registry_payload.get("official_test_used") is not False + ): + state["status"] = "failed_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_sha256 + state["conditions"] = conditions + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("workers", {}) + + state_root = Path(plan["training_state_root"]) + log_root = Path(plan["training_log_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_sha256) + statuses[condition] = status + if hard_failure(status): + continue + if status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["workers"].get(condition, {}).get("pid", -1) + ) + if not pid_matches(previous_pid, condition, registry): + pid = launch_worker( + condition, registry, condition_state, + log_root / f"{condition.lower()}.log", + allowed_gpus, + ) + state["workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["condition_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + state["status"] = "complete" if machine == "taku3" else "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_selection_binding_recovery.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..1de788859399ebc11c495022e81815866e615f7d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_selection_binding_recovery.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python3 +"""Run one disjoint Phase 9 selection-binding recovery worker.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import socket +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def json_sha256(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def validate_input(path: str, expected_sha256: str, label: str) -> None: + candidate = Path(path) + if not candidate.is_file() or sha256(candidate) != expected_sha256: + raise ValueError(f"selection recovery {label} differs: {candidate}") + + +def validate_recovered_output(item: dict[str, Any]) -> dict[str, Any]: + output = Path(item["output_dir"]) + report_path = output / "evaluation.json" + if not report_path.is_file(): + raise ValueError(f"selection recovery report missing: {item['id']}") + report = json.loads(report_path.read_text(encoding="utf-8")) + expected_bindings = { + "config": (item["config"], item["config_sha256"]), + "checkpoint": (item["checkpoint"], item["checkpoint_sha256"]), + "cache_manifest": ( + item["cache_manifest"], item["cache_manifest_sha256"], + ), + } + for key, (path, digest) in expected_bindings.items(): + binding = report.get(key, {}) + if ( + Path(str(binding.get("path", ""))).resolve() != Path(path).resolve() + or binding.get("sha256") != digest + ): + raise ValueError( + f"selection recovery {key} binding differs: {item['id']}" + ) + if ( + report.get("status") != "evaluated_phase9_h2o_fold_heldout" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or { + key: report.get(key) + for key in ("clips", "frames", "hands_rows") + } != item["expected_sample_counts"] + ): + raise ValueError(f"selection recovery role/sample contract differs: {item['id']}") + expected = item["expected_determinism"] + artifacts = { + "raw_predictions": expected["raw_predictions_sha256"], + "per_hand_rows": expected["per_hand_rows_sha256"], + "take_metrics": expected["take_metrics_sha256"], + } + for key, expected_hash in artifacts.items(): + binding = report.get(key, {}) + path = Path(str(binding.get("path", ""))) + if ( + binding.get("sha256") != expected_hash + or not path.is_file() + or sha256(path) != expected_hash + ): + raise ValueError( + f"selection recovery deterministic artifact differs: " + f"{item['id']}:{key}" + ) + if ( + json_sha256(report.get("metrics")) != expected["metrics_sha256"] + or json_sha256(report.get("grouped_bootstrap_ci")) + != expected["grouped_bootstrap_ci_sha256"] + ): + raise ValueError(f"selection recovery deterministic metrics differ: {item['id']}") + return { + "report": str(report_path.resolve()), + "report_sha256": sha256(report_path), + "sample_counts": item["expected_sample_counts"], + "metrics_sha256": expected["metrics_sha256"], + "raw_predictions_sha256": expected["raw_predictions_sha256"], + } + + +def archive_incomplete_output(item: dict[str, Any]) -> str | None: + output = Path(item["output_dir"]) + if not output.exists() or not any(output.iterdir()): + return None + root = output.parents[3] / "incomplete_outputs" + root.mkdir(parents=True, exist_ok=True) + suffix = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") + destination = root / f"{item['id']}.{suffix}" + shutil.move(str(output), str(destination)) + return str(destination.resolve()) + + +def evaluation_command(item: dict[str, Any], gpu: int, bootstrap: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], + "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(bootstrap), + "--evaluation-role", item["evaluation_role"], + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--owner", choices=("taku3", "server_new"), required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + assignment_path = Path(plan["distributed_assignment"]["path"]) + if ( + plan.get("official_test_used") is not False + or not assignment_path.is_file() + or sha256(assignment_path) != plan["distributed_assignment"]["sha256"] + ): + parser.error("selection recovery plan/assignment binding differs") + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + parser.error(f"selection recovery code binding differs: {path}") + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + if socket.gethostname() != assignment["machines"][args.owner]["hostname"]: + parser.error("selection recovery owner does not match this host") + matches = [item for item in plan["workers"] if item["id"] == args.worker] + if len(matches) != 1 or matches[0]["owner"] != args.owner: + parser.error("selection recovery worker owner differs") + worker = matches[0] + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("selection recovery worker state differs") + gpu = int(worker["physical_gpu_id"]) + if gpu not in assignment["machines"][args.owner]["physical_gpu_allowlist"]: + parser.error("selection recovery GPU is not allowed on this host") + evaluations = {item["id"]: item for item in plan["evaluations"]} + assigned = [evaluations[identifier] for identifier in worker["evaluation_ids"]] + if any( + item["owner"] != args.owner or item["physical_gpu_id"] != gpu + for item in assigned + ): + parser.error("selection recovery evaluation assignment differs") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_selection_binding_recovery_worker_state_v1", + "status": "waiting_for_gpu", "owner": args.owner, + "worker": args.worker, "physical_gpu_id": gpu, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "assigned_evaluation_ids": worker["evaluation_ids"], + "completed_ids": [], "attempts": [], + "started_utc": utc_now(), "updated_utc": utc_now(), + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if ( + previous.get("plan_sha256") != plan_hash + or previous.get("owner") != args.owner + or previous.get("worker") != args.worker + or previous.get("assigned_evaluation_ids") + != worker["evaluation_ids"] + ): + parser.error("existing selection recovery state differs") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for item in assigned: + for key in ("config", "checkpoint", "cache_manifest"): + validate_input(item[key], item[f"{key}_sha256"], key) + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError): + evidence = None + if evidence is not None: + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + continue + output = Path(item["output_dir"]) + lock_path = output.parent / f".{output.name}.selection-recovery.lock" + output.parent.mkdir(parents=True, exist_ok=True) + with lock_path.open("a+", encoding="utf-8") as output_lock: + fcntl.flock(output_lock.fileno(), fcntl.LOCK_EX) + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError): + evidence = None + if evidence is not None: + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + atomic_json(args.state, state) + continue + archived = archive_incomplete_output(item) + while True: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + state["status"] = "waiting_for_gpu" + state["waiting_for"] = item["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + if claim_physical_gpu(gpu): + break + state["status"] = "waiting_for_gpu_claim" + state["waiting_for"] = item["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = evaluation_command( + item, gpu, int(plan["bootstrap_resamples"]) + ) + attempt = { + "evaluation_id": item["id"], "start_utc": utc_now(), + "command": command, + } + if archived is not None: + attempt["archived_incomplete_output"] = archived + state["status"] = "running" + state["current_evaluation"] = item["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + env = dict(os.environ) + env["CUDA_VISIBLE_DEVICES"] = str(gpu) + env["PYTHONUNBUFFERED"] = "1" + try: + result = subprocess.run( + command, cwd=Path.cwd(), env=env, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError) as error: + state["status"] = "failed_resumable" + state["failure"] = f"{type(error).__name__}: {error}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + if result.returncode: + state["status"] = "failed_resumable" + state["failure"] = f"evaluator exited {result.returncode}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + state.pop("failure", None) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if set(state["completed_ids"]) != set(worker["evaluation_ids"]): + state["status"] = "failed_state_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state.pop("waiting_for", None) + state.pop("current_evaluation", None) + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_selection_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_selection_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6bcd0a5ebe87d4b4d325dff8080e1954ad4aaa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_selection_queue.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Wait for complete Phase 9 evidence and freeze unified candidate selection.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def evidence_complete(plan: dict[str, Any]) -> bool: + for item in plan["required_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def selection_complete(plan: dict[str, Any]) -> bool: + output = Path(plan["output_json"]) + if not output.is_file(): + return False + report = json.loads(output.read_text(encoding="utf-8")) + checkpoint = Path(report.get("winner_checkpoint", {}).get("path", "")) + config = Path(report.get("winner_config", {}).get("path", "")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + and checkpoint.is_file() + and report.get("winner_checkpoint", {}).get("sha256") == sha256(checkpoint) + and config.is_file() + and report.get("winner_config", {}).get("sha256") == sha256(config) + and Path(plan["output_csv"]).is_file() + ) + + +def archive_incomplete_outputs(plan: dict[str, Any], state_path: Path) -> list[str]: + outputs = [Path(plan["output_json"]), Path(plan["output_csv"])] + temporary_outputs = [ + path.with_suffix(path.suffix + ".tmp") for path in outputs + ] + existing = [path for path in outputs + temporary_outputs if path.exists()] + if not existing: + return [] + root = state_path.parent / "selection_incomplete_outputs" + root.mkdir(parents=True, exist_ok=True) + archived = [] + for path in existing: + destination = root / f"{path.name}.{len(list(root.iterdir())):03d}" + shutil.move(str(path), str(destination)) + archived.append(str(destination.resolve())) + return archived + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("selection plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state_lock = Path(f"{args.state}.lock").open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state = { + "schema_version": "phase9_selection_state_v1", + "status": "waiting_for_evidence", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "updated_utc": utc_now(), "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing selection state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not evidence_complete(plan): + state["status"] = "waiting_for_evidence" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + if not selection_complete(plan): + archived = archive_incomplete_outputs(plan, args.state) + if archived: + state.setdefault("archived_incomplete_outputs", []).extend(archived) + atomic_json(args.state, state) + command = [ + sys.executable, "-m", "scripts.summarize_phase9_unified_selection", + "--external-root", plan["external_root"], + "--fold-final-root", plan["fold_final_root"], + "--fold-milestone-root", plan["fold_milestone_root"], + "--multifold-index", plan["multifold_index"], + "--output-json", plan["output_json"], + "--output-csv", plan["output_csv"], + ] + log_path = args.state.parent / "unified_selection.log" + state["status"] = "running" + state["attempt"] = { + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + state["attempt"]["end_utc"] = utc_now() + state["attempt"]["returncode"] = result.returncode + if result.returncode or not selection_complete(plan): + state["status"] = "failed" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + report = json.loads(Path(plan["output_json"]).read_text(encoding="utf-8")) + state["status"] = "complete" + state["winner"] = report["winner"] + state["winner_checkpoint"] = report["winner_checkpoint"] + state["winner_config"] = report["winner_config"] + state["required_states"] = [ + { + "id": item["id"], "path": str(Path(item["path"]).resolve()), + "sha256": sha256(item["path"]), + } + for item in plan["required_states"] + ] + state["h2o_official_validation_used"] = False + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_shared_augmentation_evaluation_controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_shared_augmentation_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..1f0c887433e7319788e98fec0e732a102fc70c38 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_shared_augmentation_evaluation_controller.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""Supervise Stage 8 evaluations and freeze augmentation/Stage 9 gates.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_resolution_evaluation_controller import ( + hard_failure, + launch_worker, + pid_matches, + should_launch, + worker_status, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("evaluation_count") != 25 + or plan.get("worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + ): + raise ValueError("shared augmentation evaluation plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"shared augmentation evaluation binding differs: {path}") + + +def training_complete(plan: dict[str, Any]) -> bool: + path = Path( + plan.get("training_controller_states", {}).get( + "taku3", plan["training_controller_state"] + ) + ) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + registry = Path(state.get("training_registry", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["training_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and registry.is_file() + and state.get("training_registry_sha256") == sha256(registry) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("shared augmentation evaluation state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + static_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_shared_augmentation_evaluation_controller_state_v1", + "status": "waiting_for_augmentation_training", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "machine": machine, + "controller_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != static_hash: + parser.error("existing augmentation evaluation state differs") + if state.get("machine") != machine: + parser.error("existing augmentation evaluation machine differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not training_complete(plan): + state["status"] = "waiting_for_augmentation_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + builder_command = [ + sys.executable, "-m", + "scripts.build_phase9_shared_augmentation_evaluation_plan", + "--training-controller-plan", plan["training_controller_plan"], + "--training-controller-state", plan["training_controller_state"], + "--resolution-cache-plan", plan["resolution_cache_plan"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + dynamic_hash = sha256(evaluation_plan) + dynamic = json.loads(evaluation_plan.read_text(encoding="utf-8")) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = dynamic_hash + state["owned_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("workers", {}) + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + path = Path(worker["state"]) + status = worker_status(path, dynamic_hash) + statuses[worker["id"]] = status + if not should_launch(worker, machine, status): + continue + previous_pid = int( + state["workers"].get(worker["id"], {}).get("pid", -1) + ) + if not pid_matches(previous_pid, worker["id"], evaluation_plan): + pid = launch_worker( + evaluation_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "worker_processes": state["workers"], + } + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + decision = Path(plan["decision_report"]) + if not decision.exists(): + command = [ + sys.executable, "-m", + "scripts.summarize_phase9_shared_augmentation_decision", + "--plan", str(evaluation_plan), "--output", str(decision), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = json.loads(decision.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != dynamic_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["stage9_last2_admitted"] = report[ + "stage9_preceding_mechanism_gate" + ]["stage9_last2_admitted"] + state["decision_report"] = { + "path": str(decision.resolve()), "sha256": sha256(decision), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_shared_augmentation_training_controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_shared_augmentation_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..191670dce11e49ef1c417651529cdb49bca1cec2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_shared_augmentation_training_controller.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Supervise Stage 8 shared-augmentation training after resolution freeze.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_resolution_training_controller import ( + condition_status, + hard_failure, + pid_matches, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or plan.get("job_count") != 7 + or float(plan.get("worst_domain_relative_regression_limit", -1)) != 0.01 + ): + raise ValueError("shared augmentation training plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"shared augmentation binding differs: {path}") + + +def resolution_decision_complete(plan: dict[str, Any]) -> bool: + state_path = Path(plan["resolution_controller_state"]) + if not state_path.is_file(): + return False + state = json.loads(state_path.read_text(encoding="utf-8")) + report = Path(state.get("decision_report", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["resolution_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and report.is_file() + and state.get("decision_report", {}).get("sha256") == sha256(report) + ) + + +def launch_worker( + condition: str, registry: Path, state_path: Path, log_path: Path, + allowed_gpus: list[int], +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry.resolve()), "--condition", condition, + "--state", str(state_path.resolve()), "--poll-seconds", "30", + "--allowed-physical-gpus", ",".join(str(gpu) for gpu in allowed_gpus), + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("shared augmentation controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_shared_augmentation_training_controller_state_v1", + "status": "waiting_for_resolution_decision", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "machine": machine, + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing shared augmentation controller state differs") + if state.get("machine") != machine: + parser.error("existing shared augmentation state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not resolution_decision_complete(plan): + state["status"] = "waiting_for_resolution_decision" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry = Path(plan["training_registry"]) + builder_command = [ + sys.executable, "-m", + "scripts.build_phase9_shared_augmentation_training_registry", + "--resolution-controller-plan", plan["resolution_controller_plan"], + "--resolution-controller-state", plan["resolution_controller_state"], + "--augmentation-plan", plan["shared_augmentation_plan"], + "--unified-queue", plan["unified_training_queue"], + "--fold-queue", plan["fold_training_queue"], + "--selection-report", plan["selection_report"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), + "--state", plan["registry_builder_state"], + ] + if machine == "taku3": + state["status"] = "building_registry" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_registry_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + registry_hash = sha256(registry) + payload = json.loads(registry.read_text(encoding="utf-8")) + conditions = [item["condition"] for item in payload["conditions"]] + owners = condition_owners(payload, assignment) + if ( + len(conditions) != plan["job_count"] + or len(set(conditions)) != plan["job_count"] + or payload.get("shared_augmentation_plan", {}).get("sha256") + != plan["shared_augmentation_plan_sha256"] + or payload.get("gate", {}).get("worst_domain_relative_regression_limit") + != plan["worst_domain_relative_regression_limit"] + or payload.get("official_test_used") is not False + ): + state["status"] = "failed_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_hash + state["resolution_hw"] = payload["resolution_hw"] + state["conditions"] = conditions + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("workers", {}) + + state_root = Path(plan["training_state_root"]) + log_root = Path(plan["training_log_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_hash) + statuses[condition] = status + if hard_failure(status) or status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["workers"].get(condition, {}).get("pid", -1) + ) + if not pid_matches(previous_pid, condition, registry): + pid = launch_worker( + condition, registry, condition_state, + log_root / f"{condition.lower()}.log", + allowed_gpus, + ) + state["workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["condition_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + state["status"] = "complete" if machine == "taku3" else "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_unified_train_queue.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_unified_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f904f748a1ecc505a0efe794951a67ddb4acb67b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_phase9_unified_train_queue.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python3 +"""Run one hash-bound Phase 9 unified mixture through smoke, health, and scale.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any +import re + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def parse_physical_gpu_ids(value: str) -> tuple[int, ...]: + try: + gpu_ids = tuple(int(item.strip()) for item in value.split(",") if item.strip()) + except ValueError as error: + raise argparse.ArgumentTypeError("GPU IDs must be comma-separated integers") from error + if not gpu_ids or len(set(gpu_ids)) != len(gpu_ids): + raise argparse.ArgumentTypeError("GPU IDs must be nonempty and unique") + if any(gpu < 0 or gpu > 5 for gpu in gpu_ids): + raise argparse.ArgumentTypeError("physical GPU IDs must be between 0 and 5") + return gpu_ids + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def attempt_gpu_hours(attempts: list[dict[str, Any]]) -> float: + seconds = 0.0 + for attempt in attempts: + if not attempt.get("start_utc") or not attempt.get("end_utc"): + continue + start = datetime.fromisoformat(attempt["start_utc"]) + end = datetime.fromisoformat(attempt["end_utc"]) + seconds += max(0.0, (end - start).total_seconds()) + return seconds / 3600.0 + + +def state_lock_path(state_path: Path) -> Path: + return Path(f"{state_path}.lock") + + +def readiness_complete(queue: dict[str, Any]) -> bool: + state_path = Path(queue["data_readiness_state"]) + if not state_path.is_file(): + return False + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or state.get("plan_sha256") != queue["data_finalize_plan_sha256"] + or ( + queue.get("data_readiness_state_sha256") is not None + and queue["data_readiness_state_sha256"] != sha256(state_path) + ) + ): + return False + for artifact in state.get("artifacts", []): + manifest = Path(artifact["manifest"]) + if not manifest.is_file() or sha256(manifest) != artifact["manifest_sha256"]: + return False + for artifact in queue.get("data_artifacts", []): + path = Path(artifact["path"]) + if not path.is_file() or sha256(path) != artifact["sha256"]: + return False + return True + + +def prerequisite_states_complete(registry: dict[str, Any]) -> bool: + for item in registry.get("prerequisite_states", []): + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def prerequisite_gate_satisfied( + registry: dict[str, Any], start_before_prerequisites: bool, +) -> bool: + return start_before_prerequisites or prerequisite_states_complete(registry) + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def marker_path(queue: dict[str, Any], stage: dict[str, Any]) -> Path: + return Path(queue["output_dir"]) / ".phase9_queue" / f"{stage['id']}.json" + + +def stage_complete(queue: dict[str, Any], stage: dict[str, Any]) -> bool: + path = marker_path(queue, stage) + if not path.is_file(): + return False + marker = json.loads(path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and marker.get("config_sha256") == queue["config_sha256"] + and int(marker.get("completed_step", -1)) == int(stage["stop_after_step"]) + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command( + queue: dict[str, Any], stage: dict[str, Any], gpu: int, + previous_checkpoint: Path | None, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", queue["config"], + "--output-dir", queue["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(stage["stop_after_step"]), + ] + if previous_checkpoint is None: + command.extend(("--init-checkpoint", queue["initialization_checkpoint"])) + else: + command.extend(("--resume", str(previous_checkpoint))) + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def latest_resumable_checkpoint( + queue: dict[str, Any], stage: dict[str, Any], previous_checkpoint: Path | None, +) -> Path | None: + target = int(stage["stop_after_step"]) + previous_step = -1 + if previous_checkpoint is not None: + match = re.search(r"step_(\d+)", previous_checkpoint.name) + previous_step = int(match.group(1)) if match else -1 + candidates = [] + for path in Path(queue["output_dir"]).glob("step_*.pt"): + match = re.fullmatch(r"step_(\d+)(?:_final)?\.pt", path.name) + if match is None: + continue + step = int(match.group(1)) + if previous_step < step < target and path.is_file(): + candidates.append((step, path)) + return max(candidates, default=(previous_step, previous_checkpoint))[1] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--condition", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--start-before-prerequisites", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + registry = json.loads(args.queue.read_text(encoding="utf-8")) + conditions = {item["condition"]: item for item in registry["conditions"]} + if args.condition not in conditions: + parser.error(f"condition not registered: {args.condition}") + queue = conditions[args.condition] + if registry.get("official_test_used") is not False: + parser.error("queue must explicitly exclude official test") + config = Path(queue["config"]) + initialization = Path(queue["initialization_checkpoint"]) + if not config.is_file() or sha256(config) != queue["config_sha256"]: + parser.error("frozen config is missing or has changed") + if not initialization.is_file() or sha256(initialization) != queue["initialization_checkpoint_sha256"]: + parser.error("frozen initialization checkpoint is missing or has changed") + args.state.parent.mkdir(parents=True, exist_ok=True) + lock_path = state_lock_path(args.state) + state_lock = lock_path.open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + registry_hash = sha256(args.queue) + state = { + "schema_version": "phase9_unified_train_state_v1", + "status": "waiting_for_data", + "condition": args.condition, + "queue": str(args.queue.resolve()), "queue_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "attempts": [], "completed_stages": [], + "allowed_physical_gpus": list(args.allowed_physical_gpus), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue_sha256") != registry_hash: + parser.error("existing state is bound to another queue version") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for attempt in state.get("attempts", []): + if attempt.get("start_utc") and not attempt.get("end_utc"): + attempt["end_utc"] = utc_now() + attempt["returncode"] = None + attempt["interrupted_before_queue_restart"] = True + previous_gpus = tuple(state.get("allowed_physical_gpus", ALLOWED_GPUS)) + if state.get("attempts") and previous_gpus != args.allowed_physical_gpus: + parser.error("cannot change allowed GPUs after this queue has attempted work") + previous_early_start = bool(state.get("start_before_prerequisites", False)) + if state.get("attempts") and previous_early_start != args.start_before_prerequisites: + parser.error("cannot change prerequisite scheduling after attempted work") + state["allowed_physical_gpus"] = list(args.allowed_physical_gpus) + state["start_before_prerequisites"] = bool(args.start_before_prerequisites) + if args.start_before_prerequisites: + state["resource_amendment"] = "user_authorized_all_idle_gpus_20260727" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + while not readiness_complete({**registry, **queue}): + state["status"] = "waiting_for_data" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + while not prerequisite_gate_satisfied(registry, args.start_before_prerequisites): + state["status"] = "waiting_for_prerequisites" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + previous_checkpoint: Path | None = None + for stage in queue["stages"]: + if stage_complete(queue, stage): + previous_checkpoint = Path( + json.loads(marker_path(queue, stage).read_text(encoding="utf-8"))["checkpoint"] + ) + if stage["id"] not in state["completed_stages"]: + state["completed_stages"].append(stage["id"]) + continue + previous_checkpoint = latest_resumable_checkpoint( + queue, stage, previous_checkpoint, + ) + while True: + gpu = idle_gpu(args.allowed_physical_gpus) + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + break + command = training_command(queue, stage, gpu, previous_checkpoint) + log_path = Path(queue["log_dir"]) / f"{stage['id']}.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "stage": stage["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_stage"] = stage["id"] + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode: + periodic = sorted(Path(queue["output_dir"]).glob("step_*.pt")) + latest = periodic[-1] if periodic else None + state["status"] = "failed_resumable" if periodic else "failed" + state["failure"] = { + "stage": stage["id"], "returncode": result.returncode, + "latest_checkpoint": str(latest.resolve()) if latest else None, + "latest_checkpoint_sha256": sha256(latest) if latest else None, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode) + checkpoint = Path(queue["output_dir"]) / f"step_{int(stage['stop_after_step']):07d}_final.pt" + summary = json.loads((Path(queue["output_dir"]) / "summary.json").read_text(encoding="utf-8")) + marker = { + "status": "complete", "condition": args.condition, + "stage": stage["id"], "completed_utc": utc_now(), + "completed_step": int(stage["stop_after_step"]), + "physical_gpu_id": gpu, "config": str(config.resolve()), + "config_sha256": queue["config_sha256"], + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": sha256(checkpoint), + "source_manifest_sha256": summary["source_manifest_sha256"], + "source_exposure_batches": summary["source_exposure_batches"], + "wall_seconds": summary["wall_seconds"], + "gpu_hours": summary["gpu_hours"], + "frames_per_second": summary["frames_per_second"], + "peak_vram_gib": summary["peak_vram_gib"], + "official_test_used": False, + } + path = marker_path(queue, stage) + path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(path, marker) + previous_checkpoint = checkpoint + state["completed_stages"].append(stage["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + + state["status"] = "complete" + state["gpu_hours_consumed"] = attempt_gpu_hours(state["attempts"]) + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_qort_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_qort_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..9c50b6afa211f8c32cd790f2fc21f36ea2055aa0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_qort_h2o.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Run the official QORT-Former H2O checkpoint on the common cam4 validation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +import torch +import torchvision.transforms as transforms +from PIL import Image + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + repo = args.repo.resolve() + sys.path.insert(0, str(repo)) + from lib.qort_former import QORT_Former + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys = keys[: args.max_frames] + takes = takes[: args.max_frames] + frame_ids = frame_ids[: args.max_frames] + count = len(keys) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = QORT_Former(num_classes=11).to(device).eval() + model.load_state_dict(checkpoint, strict=True) + transform = transforms.Compose([ + transforms.Resize((540, 960)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + + # QORT's released inference denormalizes u/v by the raw image size and z by + # 1000 mm. H2O K then deterministically maps released (u,v,z) to camera XYZ. + from foundation_hand.evaluation.sota import GroundTruthBundle + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + detected = np.ones((count, 2), dtype=bool) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for start in range(0, count, args.batch_size): + end = min(start + args.batch_size, count) + images = [] + image_sizes = [] + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True): + path = args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png" + with Image.open(path) as image: + rgb = image.convert("RGB") + image_sizes.append(rgb.size) + images.append(transform(rgb)) + batch = torch.stack(images).to(device) + with torch.no_grad(): + outputs = model(batch) + logits = outputs["pred_logits"] + predictions = outputs["pred_keypoints"] + batch_indices = torch.arange(end - start, device=device) + left_index = logits[:, :, 9].argmax(dim=1) + right_index = logits[:, :, 10].argmax(dim=1) + left = predictions[0, batch_indices, left_index].reshape(-1, 21, 3) + right = predictions[1, batch_indices, right_index].reshape(-1, 21, 3) + uvz = torch.stack((left, right), dim=1).float().cpu().numpy() + scores = torch.stack(( + logits[batch_indices, left_index, 9].sigmoid(), + logits[batch_indices, right_index, 10].sigmoid(), + ), dim=1).float().cpu().numpy() + confidence[start:end] = scores + for local_index, (width, height) in enumerate(image_sizes): + uvz[local_index, ..., 0] *= width + uvz[local_index, ..., 1] *= height + z = uvz[local_index, ..., 2] + K = intrinsics[start + local_index] + joints[start + local_index, ..., 0] = (uvz[local_index, ..., 0] - K[0, 2]) / K[0, 0] * z + joints[start + local_index, ..., 1] = (uvz[local_index, ..., 1] - K[1, 2]) / K[1, 1] * z + joints[start + local_index, ..., 2] = z + if end % 100 == 0 or end == count: + print(f"QORT-Former {end}/{count}", flush=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output.resolve() + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "QORT-Former", + "scope": "RGB decode + resize/normalize + model forward + camera conversion", + "frames": count, + "processing_seconds": processing_seconds, + "frames_per_second": count / processing_seconds, + "batch_size": args.batch_size, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(repo), "rev-parse", "HEAD"], text=True + ).strip() + parameter_count = sum(parameter.numel() for parameter in model.parameters()) + bundle = PredictionBundle( + model_name="QORT-Former", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + detected=detected, + confidence=confidence, + vertices_camera_m=None, + metadata={ + "official_repository": "https://github.com/kcsayem/QORT-Former", + "repository_commit": commit, + "checkpoint": str(args.checkpoint.resolve()), + "checkpoint_sha256": sha256(args.checkpoint), + "parameter_count": parameter_count, + "input": "full RGB, resized to 960x540", + "temporal": False, + "detector": False, + "output_conversion": "official normalized u,v,z; raw H2O K unprojection", + "original_paper_metric": "mean endpoint error over 21 joints", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_wildhands_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_wildhands_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e77900e883aa37cc0b9aee3c5e030263be10f9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_wildhands_h2o.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Run the released WildHands checkpoint on H2O with a common hand detector.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import types +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, load_frame_index +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix + + +MANO_TO_OPENPOSE = np.asarray( + [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20], + dtype=np.int64, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-dir", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=1.75) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def install_pytorch3d_rotation_compatibility() -> None: + """Provide the three pure-PyTorch transforms used by the official model.""" + + rotation_conversions = types.ModuleType("pytorch3d.transforms.rotation_conversions") + rotation_conversions.axis_angle_to_matrix = axis_angle_to_matrix + rotation_conversions.rotation_6d_to_matrix = rotation_6d_to_matrix + rotation_conversions.matrix_to_rotation_6d = ( + lambda matrix: matrix[..., :2, :].clone().reshape(matrix.shape[:-2] + (6,)) + ) + transforms = types.ModuleType("pytorch3d.transforms") + transforms.rotation_conversions = rotation_conversions + pytorch3d = types.ModuleType("pytorch3d") + pytorch3d.transforms = transforms + sys.modules.update({ + "pytorch3d": pytorch3d, + "pytorch3d.transforms": transforms, + "pytorch3d.transforms.rotation_conversions": rotation_conversions, + }) + + +def recursive_to(value: Any, device: torch.device) -> Any: + if torch.is_tensor(value): + return value.to(device) + if isinstance(value, dict): + return {name: recursive_to(item, device) for name, item in value.items()} + if isinstance(value, tuple): + return tuple(recursive_to(item, device) for item in value) + if isinstance(value, list): + return [recursive_to(item, device) for item in value] + return value + + +def main() -> None: + args = parse_args() + for name in ("repo", "checkpoint", "detector", "mano_dir", "root", "manifest", "ground_truth", "output"): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + + os.environ["WILDHANDS_MANO_DIR"] = str(args.mano_dir) + sys.path.insert(0, str(args.repo)) + enable_legacy_mano_loading() + install_pytorch3d_rotation_compatibility() + os.chdir(args.repo) + + from ultralytics import YOLO + from wildhands.configs.parser import construct_args + from wildhands.datasets.dataset import WildHandsDataset + from wildhands.models.wrapper import WildHandsWrapper + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + config = construct_args() + model = WildHandsWrapper(config) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + ignored = ("head_o", "arti_head", "grasp_classifier") + state = { + name: value + for name, value in checkpoint["state_dict"].items() + if not any(token in name for token in ignored) + } + model.load_state_dict(state) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, Any]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = recursive_to(default_collate([record[3] for record in records]), device) + with torch.no_grad(): + output = model(batch) + right_joints = output["pred.j3d.cam.r"].float().cpu().numpy() + left_joints = output["pred.j3d.cam.l"].float().cpu().numpy() + right_vertices = output["pred.v3d.cam.r"].float().cpu().numpy() + left_vertices = output["pred.v3d.cam.l"].float().cpu().numpy() + for local, (frame_index, side, score, _) in enumerate(records): + batch_joints = right_joints[local] if side else left_joints[local] + batch_vertices = right_vertices[local] if side else left_vertices[local] + joints[frame_index, side] = batch_joints[MANO_TO_OPENPOSE] + vertices[frame_index, side] = batch_vertices + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images_bgr = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images_bgr): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images_bgr, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + rgb = cv2.cvtColor(images_bgr[local], cv2.COLOR_BGR2RGB) + intrinsic = intrinsics[frame_index] + focal = float(0.5 * (intrinsic[0, 0] + intrinsic[1, 1])) + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + dataset = WildHandsDataset( + config, + rgb, + boxes[[choice]], + np.asarray([side], dtype=np.float32), + focal_length=focal, + rescale_factor=args.rescale_factor, + intrx=intrinsic, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"WildHands detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/ap229997/hands", + "repository_branch": "demo", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector hand boxes, per-hand crops", + "training_exposure": "zero-shot H2O; released model trained on ARCTIC, AssemblyHands, and EPIC", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "camera_policy": "official WildHands weak-perspective conversion with known H2O intrinsics", + "joint_conversion": "official MANO output reordered to H2O/OpenPose convention", + "pytorch3d_compatibility": "three official pure-torch rotation formulas supplied without renderer", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="WildHands-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_wilor_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_wilor_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..cabd7ffbda3772dd8a1d4c3d23a13f7eba864eb0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/run_wilor_h2o.py @@ -0,0 +1,346 @@ +#!/usr/bin/env python3 +"""Run the complete official WiLoR detector + reconstruction pipeline on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--official-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument( + "--camera-policy", + choices=("official", "h2o_intrinsics", "both"), + default="official", + ) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.repo = args.repo.resolve() + args.checkpoint = args.checkpoint.resolve() + args.detector = args.detector.resolve() + args.mano_right = args.mano_right.resolve() + args.root = args.root.resolve() + args.manifest = args.manifest.resolve() + if args.ground_truth is not None: + args.ground_truth = args.ground_truth.resolve() + args.output = args.output.resolve() + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + if args.official_output is not None: + args.official_output = args.official_output.resolve() + mano_target = args.repo / "mano_data" / "MANO_RIGHT.pkl" + if not mano_target.exists(): + mano_target.symlink_to(args.mano_right) + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from ultralytics import YOLO + from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + from wilor.datasets.vitdet_dataset import ViTDetDataset + from wilor.models import load_wilor + from wilor.utils.renderer import cam_crop_to_full + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + intrinsics = None + if args.camera_policy in ("h2o_intrinsics", "both"): + if args.ground_truth is None: + raise ValueError("--camera-policy h2o_intrinsics requires --ground-truth") + from foundation_hand.evaluation.sota import GroundTruthBundle + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ + ground_truth.intrinsics[gt_index[str(key)]] for key in keys + ]) + if args.camera_policy == "both" and args.official_output is None: + raise ValueError("--camera-policy both requires --official-output") + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + + enable_legacy_mano_loading() + model, model_cfg = load_wilor( + checkpoint_path=str(args.checkpoint), + cfg_path=str(args.repo / "pretrained_models" / "model_config.yaml"), + ) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + official_joints = ( + np.full_like(joints, np.nan) if args.camera_policy == "both" else None + ) + official_vertices = ( + np.full_like(vertices, np.nan) if args.camera_policy == "both" else None + ) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + img_size = batch["img_size"].float() + official_focal = ( + model_cfg.EXTRA.FOCAL_LENGTH + / model_cfg.MODEL.IMAGE_SIZE + * img_size.max() + ) + official_camera_tensor = cam_crop_to_full( + pred_cam, box_center, box_size, img_size, official_focal + ) + calibrated_camera_tensor = None + if args.camera_policy in ("h2o_intrinsics", "both"): + record_indices = np.asarray([record[0] for record in records]) + K = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (K[:, 0, 0] + K[:, 1, 1]) + principal = K[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + calibrated_camera_tensor = torch.stack(( + pred_cam[:, 1] + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), dim=-1) + camera_tensor = ( + calibrated_camera_tensor + if calibrated_camera_tensor is not None + else official_camera_tensor + ) + camera = camera_tensor.float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + relative_joints = batch_joints.copy() + relative_vertices = batch_vertices.copy() + batch_joints += camera[:, None] + batch_vertices += camera[:, None] + if args.camera_policy == "both": + official_camera = official_camera_tensor.float().cpu().numpy() + batch_official_joints = relative_joints + official_camera[:, None] + batch_official_vertices = relative_vertices + official_camera[:, None] + for local, (frame_index, side, score, _) in enumerate(records): + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + if args.camera_policy == "both": + official_joints[frame_index, side] = batch_official_joints[local] + official_vertices[frame_index, side] = batch_official_vertices[local] + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop_dataset = ViTDetDataset( + model_cfg, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append(( + frame_index, side, float(scores[choice]), crop_dataset[0] + )) + flush_queue() + if end % 100 == 0 or end == count: + print(f"WiLoR detector {end}/{count}", flush=True) + flush_queue(force=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "WiLoR", + "scope": "RGB decode + detector + crop preprocessing + reconstruction + camera conversion", + "frames": count, + "detected_hand_frames": int(detected.sum()), + "processing_seconds": processing_seconds, + "frames_per_second": count / processing_seconds, + "detector_batch_size": args.detector_batch_size, + "reconstruction_batch_size": args.reconstruction_batch_size, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + effective_policy = ( + "h2o_intrinsics" if args.camera_policy == "both" else args.camera_policy + ) + metadata = { + "official_repository": "https://github.com/rolpotamias/WiLoR", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB detector, per-detection RGB crop reconstruction", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "official detector handedness; highest-confidence detection per side", + "camera_policy": effective_policy, + "camera_conversion": ( + "official cam_crop_to_full with released assumed focal" + if effective_policy == "official" + else "cam_crop_to_full algebra with known H2O focal/principal point" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name=( + "WiLoR-official-camera" + if effective_policy == "official" + else "WiLoR-H2O-K-calibrated" + ), + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + if args.camera_policy == "both": + official_metadata = dict(metadata) + official_metadata.update({ + "camera_policy": "official", + "camera_conversion": "official cam_crop_to_full with released assumed focal", + }) + PredictionBundle( + model_name="WiLoR-official-camera", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=official_joints, + vertices_camera_m=official_vertices, + detected=detected, + confidence=confidence, + metadata=official_metadata, + ).save(args.official_output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/screen_phase6_mixed_projection_oof.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/screen_phase6_mixed_projection_oof.py new file mode 100644 index 0000000000000000000000000000000000000000..71c0f7f48655721114a3fab67f4c9847cfdf1a0e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/screen_phase6_mixed_projection_oof.py @@ -0,0 +1,484 @@ +#!/usr/bin/env python3 +"""Select Phase 6 mixed-projection constants on train OOF predictions only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.mixed_projection import ( + coarse_wrist_ray_translation, + direct_wrist_ray_translation, + solve_mixed_projection_batch, +) + + +FINGERTIPS = (4, 8, 12, 16, 20) +Z_MODES = ( + "coarse", + "raw_alignment", + "calibrated_always", + "calibrated_confidence_0p6", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_cross_validated_calibration( + path: Path, +) -> dict[tuple[int, str, int, int], tuple[float, float, bool]]: + lookup: dict[tuple[int, str, int, int], tuple[float, float, bool]] = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + hand = 1 if row["side"] == "right" else 0 + key = ( + int(row["coarse_seed"]), row["take"], int(row["frame_id"]), hand, + ) + if key in lookup: + raise ValueError(f"duplicate calibration row: {key}") + lookup[key] = ( + float(row["calibrated_delta_z_mm"]) / 1000.0, + float(row["confidence"]), + row["alignment_available"] == "True", + ) + if len(lookup) != 333_936: + raise ValueError(f"expanded calibration row count changed: {len(lookup)}") + return lookup + + +def candidate_specs() -> list[dict[str, object]]: + output: list[dict[str, object]] = [] + for z_mode in Z_MODES: + output.extend(( + {"id": f"direct_xyz__z_{z_mode}", "assembly": "direct_xyz", "z_mode": z_mode}, + {"id": f"coarse_wrist_ray__z_{z_mode}", "assembly": "coarse_wrist_ray", "z_mode": z_mode}, + {"id": f"direct_2d_wrist_ray__z_{z_mode}", "assembly": "direct_2d_wrist_ray", "z_mode": z_mode}, + )) + for support in (4, 8, 12): + output.append({ + "id": f"mixed_wls_s{support}__z_{z_mode}", + "assembly": "mixed_projection_21j_wls", + "z_mode": z_mode, + "minimum_support": support, + "huber_delta_px": None, + }) + for delta in (2.0, 4.0, 8.0, 16.0): + output.append({ + "id": f"mixed_huber_d{delta:g}_s{support}__z_{z_mode}", + "assembly": "robust_mixed_projection", + "z_mode": z_mode, + "minimum_support": support, + "huber_delta_px": delta, + }) + return output + + +def corrections_for_take( + arrays: dict[str, np.ndarray], + *, + seed: int, + calibration: dict[tuple[int, str, int, int], tuple[float, float, bool]], +) -> tuple[dict[str, np.ndarray], np.ndarray, np.ndarray]: + time = len(arrays["frame_id"]) + calibrated = np.zeros((time, 2), dtype=np.float64) + confidence = np.zeros((time, 2), dtype=np.float64) + available = np.zeros((time, 2), dtype=bool) + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + for time_index, hand in zip(*np.where(valid), strict=True): + key = (seed, take, int(arrays["frame_id"][time_index]), int(hand)) + try: + calibrated[time_index, hand], confidence[time_index, hand], available[time_index, hand] = calibration[key] + except KeyError as error: + raise ValueError(f"missing cross-validated calibration row: {key}") from error + raw_available = arrays["alignment_applied"].astype(bool) + raw = np.where(raw_available, arrays["alignment_delta_z_m"], 0.0) + always = np.where(available, calibrated, 0.0) + gated = np.where(available & (confidence >= 0.6), calibrated, 0.0) + return { + "coarse": np.zeros((time, 2), dtype=np.float64), + "raw_alignment": raw, + "calibrated_always": always, + "calibrated_confidence_0p6": gated, + }, calibrated, confidence + + +def assemble( + spec: dict[str, object], + *, + coarse: np.ndarray, + root_relative_joints: np.ndarray, + anchors: np.ndarray, + K: np.ndarray, + z: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + direct = coarse.copy() + direct[:, 2] = z + ray = coarse_wrist_ray_translation(coarse, z) + assembly = spec["assembly"] + diagnostics: dict[str, np.ndarray] = {} + if assembly == "direct_xyz": + return direct, diagnostics + if assembly == "coarse_wrist_ray": + return ray, diagnostics + if assembly == "direct_2d_wrist_ray": + translation, valid = direct_wrist_ray_translation(anchors, K, z, ray) + diagnostics["success"] = valid + return translation, diagnostics + result = solve_mixed_projection_batch( + root_relative_joints, anchors, K, z, ray, + image_hw=(368, 640), + minimum_support=int(spec["minimum_support"]), + robust_huber_delta_px=( + None if spec["huber_delta_px"] is None else float(spec["huber_delta_px"]) + ), + ) + diagnostics.update({ + "support_count": result.support_count, + "residual_scale_px": result.residual_scale_px, + "conditioning": result.conditioning, + "inlier_ratio": result.inlier_ratio, + "uncertainty_x_m": result.uncertainty_xy_m[:, 0], + "uncertainty_y_m": result.uncertainty_xy_m[:, 1], + "success": result.failure_reason == "ok", + "failure_reason": result.failure_reason, + }) + return result.translation_m, diagnostics + + +def project(points: np.ndarray, K: np.ndarray) -> np.ndarray: + z = np.maximum(points[..., 2], 1e-8) + return np.stack(( + K[:, None, 0, 0] * points[..., 0] / z + K[:, None, 0, 2], + K[:, None, 1, 1] * points[..., 1] / z + K[:, None, 1, 2], + ), axis=-1) + + +def evaluate_translation( + arrays: dict[str, np.ndarray], + indices: tuple[np.ndarray, np.ndarray], + translation: np.ndarray, +) -> dict[str, np.ndarray]: + time_index, hand = indices + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + shift = translation - coarse + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + shift[:, None] + target = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_translation = arrays["target_wrist_translation"][time_index, hand].astype(np.float64) + joint_error = np.linalg.norm(joints - target, axis=-1) * 1000.0 + signed_translation = (translation - target_translation) * 1000.0 + K = arrays["K_resized"][time_index].astype(np.float64) + projected = project(joints, K) + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + target_2d = arrays["target_2d_px"][time_index, hand].astype(np.float64) + return { + "absolute_mpjpe_mm": joint_error.mean(axis=1), + "fingertip_mpjpe_mm": joint_error[:, FINGERTIPS].mean(axis=1), + "translation_x_mae_mm": np.abs(signed_translation[:, 0]), + "translation_y_mae_mm": np.abs(signed_translation[:, 1]), + "translation_z_mae_mm": np.abs(signed_translation[:, 2]), + "projected_mano_2d_px": np.linalg.norm(projected - target_2d, axis=-1).mean(axis=1), + "direct_mano_consistency_px": np.linalg.norm(projected - anchors, axis=-1).mean(axis=1), + } + + +def distribution(values: np.ndarray) -> dict[str, float]: + values = np.asarray(values, dtype=np.float64) + threshold = float(np.percentile(values, 95)) + return { + "mean": float(values.mean()), + "p95": threshold, + "cvar95": float(values[values >= threshold].mean()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--calibration-json", type=Path, required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + calibration_report = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration_report.get("status") != "fitted" + or calibration_report.get("official_validation_used") is not False + or calibration_report.get("official_test_used") is not False + or calibration_report.get("samples") != 333_936 + or calibration_report.get("predictions", {}).get("sha256") + != sha256(args.calibration_predictions) + ): + raise ValueError("expanded OOF calibration contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + calibration = load_cross_validated_calibration(args.calibration_predictions) + specs = candidate_specs() + spec_by_id = {str(spec["id"]): spec for spec in specs} + per_take: dict[tuple[str, int, str], dict[str, float]] = {} + values: dict[str, dict[str, list[np.ndarray]]] = { + str(spec["id"]): defaultdict(list) for spec in specs + } + bank_records = [] + sample_order: list[tuple[int, str, int, int]] = [] + + for bank_index, registered in enumerate(calibration_report["bank_manifests"], start=1): + manifest_path = Path(registered["path"]) + if sha256(manifest_path) != registered["sha256"]: + raise ValueError(f"bank manifest hash mismatch: {manifest_path}") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("official_test_used") is not False + or manifest.get("leakage_audit", {}).get("passed") is not True + ): + raise ValueError(f"bank isolation contract failed: {manifest_path}") + seed = int(manifest["seed"]) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + needed = ( + "frame_id", "frame_valid", "K_resized", "pred_wrist_translation", + "pred_joints_camera", "pred_direct_2d_px", "target_wrist_translation", + "target_joints_camera", "target_2d_px", "mano_annotation_valid", + "alignment_delta_z_m", "alignment_applied", + ) + arrays = {key: archive[key] for key in needed} + arrays["take"] = archive["take"] + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + indices = np.where(valid) + time_index, hand = indices + corrections, _, _ = corrections_for_take( + arrays, seed=seed, calibration=calibration, + ) + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + root_relative = joints - joints[:, :1] + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + K = arrays["K_resized"][time_index].astype(np.float64) + take_sample_keys = [ + (seed, take, int(arrays["frame_id"][t]), int(h)) + for t, h in zip(time_index, hand, strict=True) + ] + sample_order.extend(take_sample_keys) + for spec in specs: + candidate_id = str(spec["id"]) + z_mode = str(spec["z_mode"]) + refined_z = coarse[:, 2] + corrections[z_mode][time_index, hand] + translation, diagnostics = assemble( + spec, coarse=coarse, root_relative_joints=root_relative, + anchors=anchors, K=K, z=refined_z, + ) + metrics = evaluate_translation(arrays, indices, translation) + for metric, metric_values in metrics.items(): + values[candidate_id][metric].append(metric_values.astype(np.float32)) + success = diagnostics.get("success", np.ones(len(translation), dtype=bool)) + per_take[(candidate_id, seed, take)] = { + "absolute_mpjpe_mm": float(metrics["absolute_mpjpe_mm"].mean()), + "fingertip_mpjpe_mm": float(metrics["fingertip_mpjpe_mm"].mean()), + "translation_x_mae_mm": float(metrics["translation_x_mae_mm"].mean()), + "translation_y_mae_mm": float(metrics["translation_y_mae_mm"].mean()), + "translation_z_mae_mm": float(metrics["translation_z_mae_mm"].mean()), + "projected_mano_2d_px": float(metrics["projected_mano_2d_px"].mean()), + "success_fraction": float(success.mean()), + } + bank_records.append({ + "manifest": str(manifest_path), "sha256": registered["sha256"], + "seed": seed, "fold": int(manifest["fold"]), + "heldout_subject": manifest["heldout_subject"], + "takes": len(manifest["takes"]), "frames": int(manifest["frames"]), + }) + print(f"[{bank_index}/9] fold{manifest['fold']} seed{seed} complete", flush=True) + + if len(sample_order) != 333_936 or len(set(sample_order)) != len(sample_order): + raise ValueError("OOF sample coverage or uniqueness changed") + summary_rows = [] + concatenated: dict[str, dict[str, np.ndarray]] = {} + for spec in specs: + candidate_id = str(spec["id"]) + candidate_values = { + metric: np.concatenate(chunks) + for metric, chunks in values[candidate_id].items() + } + concatenated[candidate_id] = candidate_values + take_rows = [value for (name, _, _), value in per_take.items() if name == candidate_id] + z_mode = str(spec["z_mode"]) + baseline_id = f"direct_xyz__z_{z_mode}" + row: dict[str, object] = { + **spec, + "samples": len(candidate_values["absolute_mpjpe_mm"]), + "seed_take_groups": len(take_rows), + "absolute_frame_mean_mm": float(candidate_values["absolute_mpjpe_mm"].mean()), + "absolute_take_mean_mm": float(np.mean([item["absolute_mpjpe_mm"] for item in take_rows])), + "fingertip_frame_mean_mm": float(candidate_values["fingertip_mpjpe_mm"].mean()), + "translation_x_mae_mm": float(candidate_values["translation_x_mae_mm"].mean()), + "translation_x_p95_mm": float(np.percentile(candidate_values["translation_x_mae_mm"], 95)), + "translation_y_mae_mm": float(candidate_values["translation_y_mae_mm"].mean()), + "translation_y_p95_mm": float(np.percentile(candidate_values["translation_y_mae_mm"], 95)), + "translation_z_mae_mm": float(candidate_values["translation_z_mae_mm"].mean()), + "projected_mano_2d_px": float(candidate_values["projected_mano_2d_px"].mean()), + "direct_mano_consistency_px": float(candidate_values["direct_mano_consistency_px"].mean()), + "success_fraction": float(np.mean([item["success_fraction"] for item in take_rows])), + } + if candidate_id == baseline_id: + row.update({ + "absolute_frame_delta_vs_same_z_direct_mm": 0.0, + "absolute_take_delta_vs_same_z_direct_mm": 0.0, + "largest_take_harm_mm": 0.0, + "largest_sample_harm_mm": 0.0, + "absolute_guardrail_passed": True, + }) + summary_rows.append(row) + + row_by_id = {str(row["id"]): row for row in summary_rows} + for row in summary_rows: + candidate_id = str(row["id"]) + baseline_id = f"direct_xyz__z_{row['z_mode']}" + if candidate_id == baseline_id: + continue + baseline = row_by_id[baseline_id] + take_deltas = [] + for (name, seed, take), item in per_take.items(): + if name != candidate_id: + continue + take_deltas.append( + item["absolute_mpjpe_mm"] + - per_take[(baseline_id, seed, take)]["absolute_mpjpe_mm"] + ) + sample_delta = ( + concatenated[candidate_id]["absolute_mpjpe_mm"] + - concatenated[baseline_id]["absolute_mpjpe_mm"] + ) + frame_delta = float(row["absolute_frame_mean_mm"] - baseline["absolute_frame_mean_mm"]) + take_delta = float(row["absolute_take_mean_mm"] - baseline["absolute_take_mean_mm"]) + guardrail = min(0.2, 0.01 * float(baseline["absolute_frame_mean_mm"])) + row.update({ + "absolute_frame_delta_vs_same_z_direct_mm": frame_delta, + "absolute_take_delta_vs_same_z_direct_mm": take_delta, + "largest_take_harm_mm": float(np.max(take_deltas)), + "largest_sample_harm_mm": float(np.max(sample_delta)), + "absolute_guardrail_passed": frame_delta <= guardrail, + }) + + eligible = [ + row for row in summary_rows + if row["assembly"] != "direct_xyz" and row["absolute_guardrail_passed"] + ] + eligible.sort(key=lambda row: ( + float(row["absolute_take_mean_mm"]), + float(row["largest_take_harm_mm"]), + max(float(row["translation_x_p95_mm"]), float(row["translation_y_p95_mm"])), + float(row["projected_mano_2d_px"]), + distribution(concatenated[str(row["id"])]["absolute_mpjpe_mm"])["cvar95"], + 0 if row["assembly"] == "mixed_projection_21j_wls" else 1, + )) + if not eligible: + raise RuntimeError("no mixed-projection setting passes the preregistered guardrail") + best_take = float(eligible[0]["absolute_take_mean_mm"]) + tied = [row for row in eligible if float(row["absolute_take_mean_mm"]) <= best_take + 0.02] + tied.sort(key=lambda row: ( + float(row["largest_take_harm_mm"]), + max(float(row["translation_x_p95_mm"]), float(row["translation_y_p95_mm"])), + float(row["projected_mano_2d_px"]), + distribution(concatenated[str(row["id"])]["absolute_mpjpe_mm"])["cvar95"], + 0 if row["assembly"] == "mixed_projection_21j_wls" else 1, + )) + winner = tied[0] + winner_id = str(winner["id"]) + baseline_id = f"direct_xyz__z_{winner['z_mode']}" + winner_delta = ( + concatenated[winner_id]["absolute_mpjpe_mm"] + - concatenated[baseline_id]["absolute_mpjpe_mm"] + ) + order_gain = np.argsort(winner_delta)[:20] + order_harm = np.argsort(winner_delta)[-20:][::-1] + case_rows = [] + for role, order in (("largest_gain", order_gain), ("largest_harm", order_harm)): + for rank, index in enumerate(order, start=1): + seed, take, frame_id, hand = sample_order[int(index)] + case_rows.append({ + "role": role, "rank": rank, "sample_index": int(index), + "seed": seed, "take": take, "frame_id": frame_id, + "side": "right" if hand else "left", + "winner": winner_id, "baseline": baseline_id, + "absolute_delta_mm": float(winner_delta[index]), + "winner_absolute_mpjpe_mm": float(concatenated[winner_id]["absolute_mpjpe_mm"][index]), + "baseline_absolute_mpjpe_mm": float(concatenated[baseline_id]["absolute_mpjpe_mm"][index]), + }) + + write_csv(args.output_dir / "oof_grid.csv", summary_rows) + write_csv(args.output_dir / "largest_gain_harm.csv", case_rows) + report = { + "status": "selected_oof_only", + "experiment": "P6_S1_cache_mixed_projection", + "official_validation_used": False, + "official_test_used": False, + "oracle_information": False, + "samples": len(sample_order), + "seed_take_groups": len({(seed, take) for seed, take, _, _ in sample_order}), + "physical_takes": len({take for _, take, _, _ in sample_order}), + "seeds": sorted({seed for seed, _, _, _ in sample_order}), + "banks": bank_records, + "calibration": { + "json": str(args.calibration_json.resolve()), + "json_sha256": sha256(args.calibration_json), + "cross_validated_predictions": str(args.calibration_predictions.resolve()), + "predictions_sha256": sha256(args.calibration_predictions), + "confidence_threshold": 0.6, + }, + "grid": { + "conditions": len(specs), "minimum_support": [4, 8, 12], + "huber_delta_px": [2.0, 4.0, 8.0, 16.0], + "irls_iterations": 5, + "mask": "predicted finite + positive z>0.05m + in-frame anchor", + "fallback": "coarse wrist ray at same selected z; direct xyz if K invalid", + }, + "selection_rule": ( + "minimize seed-take-equal Absolute within same-z direct guardrail; " + "0.02mm tie band then largest-take harm, xy P95, projected 2D, CVaR95, WLS simplicity" + ), + "winner": winner, + "same_z_direct_baseline": row_by_id[baseline_id], + "outputs": {"grid": "oof_grid.csv", "largest_gain_harm": "largest_gain_harm.csv"}, + } + (args.output_dir / "selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "winner": winner_id, + "absolute_take_mean_mm": winner["absolute_take_mean_mm"], + "absolute_delta_mm": winner["absolute_take_delta_vs_same_z_direct_mm"], + "projected_mano_2d_px": winner["projected_mano_2d_px"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/seed_phase9_cache_hardlinks.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/seed_phase9_cache_hardlinks.py new file mode 100644 index 0000000000000000000000000000000000000000..24c63f0ecef2de0911cd4cb725ab7bafc274d7f5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/seed_phase9_cache_hardlinks.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Seed an expanded cache with hash-verified hardlinks from an older cache.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def seed_hardlinks( + manifest: Path, output_dir: Path, expected_dataset: str, +) -> dict[str, Any]: + rows = [ + json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not rows or {row.get("dataset_id") for row in rows} != {expected_dataset}: + raise ValueError("source cache manifest dataset differs from expectation") + clips_dir = output_dir / "clips" + clips_dir.mkdir(parents=True, exist_ok=True) + logical_bytes = 0 + reused = 0 + for row in rows: + source = Path(row["cache_path"]) + if not source.is_file() or sha256(source) != row["cache_sha256"]: + raise ValueError(f"source payload is missing or differs: {source}") + target = clips_dir / source.name + if target.exists(): + if not target.is_file() or sha256(target) != row["cache_sha256"]: + raise ValueError(f"existing target payload differs: {target}") + else: + os.link(source, target) + logical_bytes += source.stat().st_size + reused += 1 + return { + "schema_version": "phase9_cache_hardlink_seed_v1", + "status": "complete", + "dataset": expected_dataset, + "source_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "output_dir": str(output_dir.resolve()), + "hardlinked_clips": reused, + "logical_bytes": logical_bytes, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-cache-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--dataset", choices=("HOT3D", "HOI4D", "ARCTIC"), required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + if args.report.exists(): + parser.error("report already exists") + try: + result = seed_hardlinks(args.source_cache_manifest, args.output_dir, args.dataset) + except (OSError, ValueError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.report.parent.mkdir(parents=True, exist_ok=True) + temporary = args.report.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.report) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/select_phase7_external_continuation.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/select_phase7_external_continuation.py new file mode 100644 index 0000000000000000000000000000000000000000..b9332b63326456953ca11d008b1a0f69c2b42c24 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/select_phase7_external_continuation.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Select the final external checkpoint across frozen continuation steps.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.rank_phase7_external import METRICS, dense_ranks, evaluation_metrics, pareto_frontier +from scripts.build_phase7_scale_eval_queue import sha256 + + +DATASETS = ("ARCTIC", "HOI4D", "HOT3D") + + +def load_candidates(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if manifest.get("selection_split") != "external_heldout_only": + raise ValueError("continuation selection must be external-heldout only") + if set(manifest.get("datasets", [])) != set(DATASETS): + raise ValueError("continuation selection requires all three external datasets") + entries: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + for item in manifest.get("evaluations", []): + candidate, dataset = str(item["candidate"]), str(item["dataset"]) + if dataset not in DATASETS or (candidate, dataset) in seen: + raise ValueError(f"invalid or duplicate candidate/dataset pair: {(candidate, dataset)}") + seen.add((candidate, dataset)) + path = Path(item["path"]).resolve() + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or "h2o" in str(report["cache_manifest"]["path"]).lower() + ): + raise ValueError(f"non-external evaluation in continuation selection: {path}") + checkpoint = Path(report["checkpoint"]["path"]) + config = Path(report["config"]["path"]) + if sha256(checkpoint) != report["checkpoint"]["sha256"]: + raise ValueError(f"checkpoint hash mismatch: {checkpoint}") + if sha256(config) != report["config"]["sha256"]: + raise ValueError(f"config hash mismatch: {config}") + take_path = Path(report["take_metrics"]["path"]) + if sha256(take_path) != report["take_metrics"]["sha256"]: + raise ValueError(f"take metrics hash mismatch: {take_path}") + per_hand_path = Path(report["per_hand_rows"]["path"]) + if sha256(per_hand_path) != report["per_hand_rows"]["sha256"]: + raise ValueError(f"per-hand metrics hash mismatch: {per_hand_path}") + entries.append({ + "candidate": candidate, "dataset": dataset, + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint_path": str(checkpoint.resolve()), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config_path": str(config.resolve()), + "config_sha256": report["config"]["sha256"], + "evaluation_path": str(path), "take_metrics_path": str(take_path.resolve()), + "per_hand_metrics_path": str(per_hand_path.resolve()), + **evaluation_metrics(report), + }) + candidates = {entry["candidate"] for entry in entries} + missing = {(candidate, dataset) for candidate in candidates for dataset in DATASETS} - seen + if missing or len(candidates) < 2: + raise ValueError(f"incomplete continuation candidate grid: {sorted(missing)}") + for candidate in candidates: + selected = [entry for entry in entries if entry["candidate"] == candidate] + for field in ("checkpoint_step", "checkpoint_path", "checkpoint_sha256", "config_path", "config_sha256"): + if len({entry[field] for entry in selected}) != 1: + raise ValueError(f"candidate {candidate} has inconsistent {field}") + return entries + + +def rank_candidates(entries: list[dict[str, Any]]) -> dict[str, Any]: + candidates = sorted({entry["candidate"] for entry in entries}) + lookup = {(entry["candidate"], entry["dataset"]): entry for entry in entries} + dataset_ranks: dict[str, dict[str, float]] = {} + vectors = {candidate: [] for candidate in candidates} + for dataset in DATASETS: + ranks = { + metric: dense_ranks({candidate: lookup[(candidate, dataset)][metric] for candidate in candidates}) + for metric in METRICS + } + dataset_ranks[dataset] = {} + for candidate in candidates: + dataset_ranks[dataset][candidate] = sum(ranks[metric][candidate] for metric in METRICS) / len(METRICS) + vectors[candidate].extend(lookup[(candidate, dataset)][metric] for metric in METRICS) + macro = { + candidate: sum(dataset_ranks[dataset][candidate] for dataset in DATASETS) / len(DATASETS) + for candidate in candidates + } + order = sorted(candidates, key=lambda candidate: ( + macro[candidate], + sum(lookup[(candidate, dataset)]["absolute_mpjpe_mm"] for dataset in DATASETS), + sum(lookup[(candidate, dataset)]["root_relative_mpjpe_mm"] for dataset in DATASETS), + candidate, + )) + return { + "dataset_ranks": dataset_ranks, "macro_mean_rank": macro, + "pareto_frontier": pareto_frontier(vectors), "order": order, "winner": order[0], + } + + +def read_take_values( + path: Path, metric: str, statistic: str = "mean", +) -> dict[str, float]: + with path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + grouped: dict[str, list[float]] = {} + for row in rows: + value = float(row[metric]) + if math.isfinite(value): + grouped.setdefault(row["physical_recording_id"], []).append(value) + if statistic == "mean": + values = {key: float(np.mean(group)) for key, group in grouped.items()} + elif statistic == "p95": + values = {key: float(np.quantile(group, .95)) for key, group in grouped.items()} + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + if not values: + raise ValueError(f"no finite {metric} take values: {path}") + return values + + +def paired_take_bootstrap( + reference_path: Path, candidate_path: Path, metric: str, seed: int, resamples: int, + statistic: str = "mean", +) -> dict[str, Any]: + reference = read_take_values(reference_path, metric, statistic) + candidate = read_take_values(candidate_path, metric, statistic) + if set(reference) != set(candidate): + raise ValueError(f"paired take IDs differ for {metric}") + keys = sorted(reference) + delta = np.asarray([candidate[key] - reference[key] for key in keys], dtype=np.float64) + rng = np.random.default_rng(seed) + samples = delta[rng.integers(0, len(delta), size=(resamples, len(delta)))].mean(axis=1) + return { + "unit": "physical_recording", "recording_statistic": statistic, + "take_count": len(delta), + "delta_definition": "candidate_minus_reference; negative favors candidate", + "mean_delta": float(delta.mean()), + "ci95_low": float(np.percentile(samples, 2.5)), + "ci95_high": float(np.percentile(samples, 97.5)), + "resamples": resamples, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--funnel-selection", type=Path, required=True) + parser.add_argument("--expected-funnel-winner", required=True) + parser.add_argument("--reference-candidate", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--seed", type=int, default=20260717) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + funnel = json.loads(args.funnel_selection.read_text(encoding="utf-8")) + if ( + funnel.get("status") != "ranked_external_only" + or funnel.get("winner") != args.expected_funnel_winner + or funnel.get("h2o_used") is not False + or funnel.get("official_test_used") is not False + ): + parser.error("funnel selection does not match the frozen external-only decision") + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + entries = load_candidates(manifest) + ranking = rank_candidates(entries) + if args.reference_candidate not in ranking["order"]: + parser.error("reference candidate is absent") + lookup = {(entry["candidate"], entry["dataset"]): entry for entry in entries} + paired: dict[str, Any] = {} + paired_specs = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), + } + for candidate in ranking["order"]: + if candidate == args.reference_candidate: + continue + paired[candidate] = { + dataset: { + metric_name: paired_take_bootstrap( + Path(lookup[(args.reference_candidate, dataset)]["per_hand_metrics_path"]), + Path(lookup[(candidate, dataset)]["per_hand_metrics_path"]), + row_metric, args.seed, args.bootstrap_resamples, statistic, + ) + for metric_name, (row_metric, statistic) in paired_specs.items() + } + for dataset in DATASETS + } + winner = ranking["winner"] + winner_entries = [entry for entry in entries if entry["candidate"] == winner] + first = winner_entries[0] + result = { + "status": "selected_external_generalist_no_h2o", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "selection_rule": "dataset metric ranks -> macro mean rank -> Absolute/root-relative tie-break", + "selection_split": "external_heldout_only", "frame_count_weighted": False, + "funnel_selection": { + "path": str(args.funnel_selection.resolve()), "sha256": sha256(args.funnel_selection), + "winner": args.expected_funnel_winner, + }, + "candidate_manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "reference_candidate": args.reference_candidate, + **ranking, "entries": entries, "paired_take_bootstrap": paired, + "checkpoint": { + "path": first["checkpoint_path"], "sha256": first["checkpoint_sha256"], + "step": first["checkpoint_step"], + }, + "config": {"path": first["config_path"], "sha256": first["config_sha256"]}, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/select_phase7_h2o_adaptation.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/select_phase7_h2o_adaptation.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8d06a6082f25489ca5816a83149e0eba2424aa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/select_phase7_h2o_adaptation.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Select a Phase 7 adaptation branch using H2O train-group-heldout only.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.build_phase7_scale_eval_queue import sha256 + + +PRIMARY_METRIC = "absolute_mpjpe_mm" +METRIC_SPECS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} +IDENTITY_FIELDS = ("physical_recording_id", "camera_id", "frame_id", "side") + + +def checked_artifact(record: dict[str, Any], name: str) -> Path: + artifact = record[name] + path = Path(artifact["path"]).resolve() + if not path.is_file() or sha256(path) != artifact["sha256"]: + raise ValueError(f"{name} is missing or has a SHA256 mismatch: {path}") + return path + + +def load_candidates(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if ( + manifest.get("selection_split") != "h2o_train_group_heldout_only" + or manifest.get("h2o_official_validation_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("selection manifest violates the H2O train-heldout boundary") + candidates: list[dict[str, Any]] = [] + names: set[str] = set() + cache_sha256: set[str] = set() + for item in manifest.get("candidates", []): + name = str(item["candidate"]) + if name in names: + raise ValueError(f"duplicate candidate: {name}") + names.add(name) + report_path = Path(item["evaluation"]).resolve() + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_h2o_train_group_heldout" + or report.get("evaluation_role") != "h2o_train_group_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or Path(report["cache_manifest"]["path"]).name != "train_group_heldout.jsonl" + ): + raise ValueError(f"candidate is not a valid train-heldout evaluation: {report_path}") + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + per_hand = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + cache = checked_artifact(report, "cache_manifest") + cache_sha256.add(report["cache_manifest"]["sha256"]) + metrics = { + metric: float(report["metrics"][row_metric]["mean"]) + for metric, (row_metric, statistic) in METRIC_SPECS.items() + if statistic == "mean" + } + metrics["translation_z_p95_mm"] = float( + report["metrics"]["translation_z_mae_mm"]["p95"] + ) + if not all(math.isfinite(value) for value in metrics.values()): + raise ValueError(f"candidate contains non-finite metrics: {name}") + candidates.append({ + "candidate": name, + "evaluation": str(report_path), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config), + "config_sha256": report["config"]["sha256"], + "cache_manifest": str(cache), + "cache_manifest_sha256": report["cache_manifest"]["sha256"], + "per_hand_rows": str(per_hand), + "metrics": metrics, + }) + if len(candidates) < 2: + raise ValueError("adaptation selection requires at least two candidates") + if len(cache_sha256) != 1: + raise ValueError("adaptation candidates use different train-heldout manifests") + return candidates + + +def read_paired_rows(path: Path, metric: str) -> dict[tuple[str, ...], float]: + result: dict[tuple[str, ...], float] = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + identity = tuple(str(row[field]) for field in IDENTITY_FIELDS) + if identity in result: + raise ValueError(f"duplicate per-hand identity: {identity}") + result[identity] = float(row[metric]) + return result + + +def paired_recording_bootstrap( + reference: Path, + candidate: Path, + metric: str, + statistic: str, + seed: int, + resamples: int, +) -> dict[str, Any]: + reference_rows = read_paired_rows(reference, metric) + candidate_rows = read_paired_rows(candidate, metric) + if set(reference_rows) != set(candidate_rows): + raise ValueError(f"paired per-hand identities differ for {metric}") + grouped: dict[str, list[tuple[float, float]]] = {} + for identity in sorted(reference_rows): + reference_value, candidate_value = reference_rows[identity], candidate_rows[identity] + if math.isfinite(reference_value) and math.isfinite(candidate_value): + grouped.setdefault(identity[0], []).append((reference_value, candidate_value)) + if not grouped: + raise ValueError(f"no finite paired values for {metric}") + deltas = [] + for recording in sorted(grouped): + values = np.asarray(grouped[recording], dtype=np.float64) + if statistic == "mean": + delta = values[:, 1].mean() - values[:, 0].mean() + elif statistic == "p95": + delta = np.quantile(values[:, 1], .95) - np.quantile(values[:, 0], .95) + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + deltas.append(float(delta)) + array = np.asarray(deltas, dtype=np.float64) + rng = np.random.default_rng(seed) + samples = array[rng.integers(0, len(array), size=(resamples, len(array)))].mean(1) + return { + "unit": "physical_recording", + "recording_statistic": statistic, + "recordings": len(array), + "delta_definition": "candidate_minus_reference; negative favors candidate", + "mean_delta": float(array.mean()), + "ci95_low": float(np.quantile(samples, .025)), + "ci95_high": float(np.quantile(samples, .975)), + "resamples": resamples, + } + + +def select( + manifest: dict[str, Any], seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + candidates = load_candidates(manifest) + order = sorted(candidates, key=lambda item: ( + item["metrics"][PRIMARY_METRIC], + item["metrics"]["root_relative_mpjpe_mm"], + item["metrics"]["fingertip_mpjpe_mm"], + item["candidate"], + )) + reference = order[0] + paired = {} + for candidate in order[1:]: + paired[candidate["candidate"]] = { + metric_name: paired_recording_bootstrap( + Path(reference["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for metric_name, (row_metric, statistic) in METRIC_SPECS.items() + } + return { + "status": "selected_h2o_adaptation_train_group_heldout", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "selection_rule": "lowest train-group-heldout Absolute MPJPE; root-relative then fingertip tie-break; no multi-seed or one-percent gate", + "selection_split": "h2o_train_group_heldout_only", + "primary_metric": PRIMARY_METRIC, + "winner": reference["candidate"], + "order": [item["candidate"] for item in order], + "candidates": candidates, + "paired_recording_bootstrap_vs_winner": paired, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + result = select( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, + resamples=args.bootstrap_resamples, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase4_a3.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase4_a3.py new file mode 100644 index 0000000000000000000000000000000000000000..d8de0510886c2ea270a8dc11eb799add21226b64 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase4_a3.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +"""Real-batch equality/backward smoke for the A3 oracle crop refiner.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def attach_gt_vertices( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> None: + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + with torch.no_grad(): + vertices, _ = model.mano_layer( + axis_angle_to_matrix(pose), + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = ( + batch["mano_annotation_valid"].bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where( + valid, vertices, torch.full_like(vertices, torch.nan), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--mode", choices=( + "oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k", + ), required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + actual_hash = file_sha256(args.checkpoint) + if actual_hash != args.expected_checkpoint_sha256: + parser.error( + f"checkpoint hash mismatch: {actual_hash} != {args.expected_checkpoint_sha256}" + ) + args.output_dir.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load(args.base_config.read_text(encoding="utf-8")) + seed = int(config["seed"]) + torch.manual_seed(seed) + data, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + photometric_augmentation=data.get("photometric_augmentation"), + augmentation_seed=seed, oracle_crop_enabled=True, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + device = torch.device(f"cuda:{args.gpu}") + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + common_model = { + **config["model"], + "dinov3_source": assets["dinov3_source"], + "dinov3_weights": assets["dinov3_weights"], + "mano_root": assets["mano_root"], + } + base = BimanualReconstructionModel(ModelConfig(**common_model)).to(device).eval() + load_checkpoint(args.checkpoint, base, optimizer=None, map_location=device) + refined_config = ModelConfig( + **common_model, oracle_crop_mode=args.mode, + freeze_coarse_for_oracle_crop=True, + ) + refined = BimanualReconstructionModel(refined_config).to(device).eval() + initialization = load_model_initialization( + args.checkpoint, refined, + allowed_missing_prefixes=("oracle_crop_",), map_location=device, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + base_output = base(batch) + refined_output = refined(batch) + comparisons = { + "joint2d": torch.equal( + base_output["joint2d_norm"], refined_output["joint2d_norm"], + ), + "rotations": torch.equal( + base_output["mano_rotation_matrices"], + refined_output["coarse_mano_rotation_matrices"], + ) and torch.equal( + refined_output["mano_rotation_matrices"], + refined_output["coarse_mano_rotation_matrices"], + ), + "shape": torch.equal( + base_output["mano_shape"], refined_output["coarse_mano_shape"], + ) and torch.equal( + refined_output["mano_shape"], refined_output["coarse_mano_shape"], + ), + "translation": torch.equal( + base_output["wrist_root_translation"], + refined_output["coarse_wrist_root_translation"], + ) and torch.equal( + refined_output["wrist_root_translation"], + refined_output["coarse_wrist_root_translation"], + ), + "joints": torch.equal( + base_output["joints_camera"], refined_output["coarse_joints_camera"], + ) and torch.equal( + refined_output["joints_camera"], refined_output["coarse_joints_camera"], + ), + "vertices": torch.equal( + base_output["vertices_camera"], refined_output["coarse_vertices_camera"], + ) and torch.equal( + refined_output["vertices_camera"], refined_output["coarse_vertices_camera"], + ), + } + if not all(comparisons.values()): + raise RuntimeError(f"zero-init coarse/refined equality failed: {comparisons}") + del base, base_output, refined_output + torch.cuda.empty_cache() + + refined.train() + attach_gt_vertices(batch, refined) + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + trainable = { + name: value for name, value in refined.named_parameters() + if value.requires_grad + } + if not trainable or any(not name.startswith("oracle_crop_") for name in trainable): + raise RuntimeError("A3 smoke found trainable non-oracle parameters") + optimizer = torch.optim.AdamW(trainable.values(), lr=5e-5, weight_decay=0.05) + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=dtype): + prediction = refined(batch) + losses = criterion(prediction, batch) + losses["total"].backward() + gradients_finite = all( + parameter.grad is None or bool(torch.isfinite(parameter.grad).all()) + for parameter in trainable.values() + ) + heads_with_gradient = sorted( + name for name, parameter in trainable.items() + if parameter.grad is not None and bool(torch.count_nonzero(parameter.grad)) + ) + if not gradients_finite or not heads_with_gradient: + raise RuntimeError("A3 smoke backward did not produce finite head gradients") + optimizer.step() + smoke_checkpoint = args.output_dir / "smoke_checkpoint.pt" + save_checkpoint( + smoke_checkpoint, refined, optimizer, 1, + extra={ + "phase": 4, "wave": "A3", "mode": args.mode, + "coarse_checkpoint_sha256": actual_hash, + "official_test_used": False, + }, + exclude_prefixes=("rgb_encoder.backbone.",), + ) + reloaded = BimanualReconstructionModel(refined_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + [value for value in reloaded.parameters() if value.requires_grad], + lr=5e-5, weight_decay=0.05, + ) + resume = load_checkpoint( + smoke_checkpoint, reloaded, reloaded_optimizer, map_location=device, + ) + reload_exact = all( + key.startswith("rgb_encoder.backbone.") + or torch.equal(value, reloaded.state_dict()[key]) + for key, value in refined.state_dict().items() + ) + payload = { + "status": "passed", + "official_test_used": False, + "mode": args.mode, + "seed": seed, + "coarse_checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": actual_hash, + "step": initialization["step"], + }, + "initialization_residual_missing_keys": initialization["residual_missing_keys"], + "checkpoint_excluded_prefixes": initialization[ + "checkpoint_excluded_prefixes" + ], + "zero_init_exact": comparisons, + "trainable_parameters": sum(value.numel() for value in trainable.values()), + "trainable_names_oracle_only": True, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "gradients_finite": gradients_finite, + "heads_with_gradient": heads_with_gradient, + "checkpoint_reload_exact": bool(reload_exact and resume["step"] == 1), + "oracle_crop_available_fraction": float( + batch["oracle_crop_available"].float().mean() + ), + "oracle_crop_depth_available_fraction": float( + batch["oracle_crop_depth_available"].float().mean() + ), + } + if not payload["checkpoint_reload_exact"]: + raise RuntimeError("A3 smoke checkpoint reload was not exact") + (args.output_dir / "smoke.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(payload, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase5_structured.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase5_structured.py new file mode 100644 index 0000000000000000000000000000000000000000..32656058c47b6e540b61932cf600b3a86860e640 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase5_structured.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Real-checkpoint forward/backward smoke for Phase 5 structured refinement.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("structured smoke output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if not config.get("model", {}).get("structured_hand_refinement", False): + raise ValueError("smoke requires a structured-hand config") + expected_hash = config.get("experiment", {}).get("coarse_checkpoint_sha256") + if sha256(args.checkpoint) != expected_hash: + raise ValueError("coarse checkpoint hash does not match the registered config") + seed = int(config["seed"]) + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("structured_",), + map_location=device, + ) + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-6, weight_decay=0.05) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + exact_zero_init = { + "joint2d": torch.equal(prediction["joint2d_norm"], prediction["coarse_joint2d_norm"]), + "rotation": torch.equal( + prediction["mano_rotation_matrices"], + prediction["coarse_mano_rotation_matrices"], + ), + "shape_sequence": torch.equal( + prediction["mano_shape_sequence"], + prediction["coarse_mano_shape_sequence"], + ), + "shape": torch.equal(prediction["mano_shape"], prediction["coarse_mano_shape"]), + "translation": torch.equal( + prediction["wrist_root_translation"], + prediction["coarse_wrist_root_translation"], + ), + } + losses["total"].backward() + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + residual_head_gradients = { + name: bool( + parameter.grad is not None and torch.isfinite(parameter.grad).all() + ) + for name, parameter in model.named_parameters() + if name.startswith("structured_") and name.endswith("weight") + } + required_head_gradients = { + name: finite for name, finite in residual_head_gradients.items() + if model_config.structured_refine_translation + or not name.startswith("structured_translation_head.") + } + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + args.output_dir.mkdir(parents=True, exist_ok=True) + checkpoint = args.output_dir / "structured_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, step=1, + extra={"kind": "phase5_structured_real_checkpoint_smoke"}, + exclude_prefixes=("rgb_encoder.backbone.",), + ) + expected_state = { + key: value.detach().cpu().clone() + for key, value in model.state_dict().items() + if not key.startswith("rgb_encoder.backbone.") + } + del prediction, losses, model, optimizer, criterion + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW(reloaded.parameters(), lr=5e-6, weight_decay=0.05) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected_state.items() + ) + shared_initialization_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("structured_", "rgb_encoder.backbone.")) + ] + passed = bool( + all(exact_zero_init.values()) + and all(required_head_gradients.values()) + and all(np.isfinite(value) for value in loss_values.values()) + and not shared_initialization_missing + and resume_exact + and resumed["step"] == 1 + ) + result = { + "status": "passed" if passed else "failed", + "experiment_class": "engineering_real_checkpoint_smoke", + "formal_training": False, + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "seed": seed, + "resolution_hw": data["resolution_hw"], + "T": data["T"], + "precision": config["precision"], + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_initialization_missing, + "exact_zero_initialization": exact_zero_init, + "losses": loss_values, + "losses_finite": all(np.isfinite(value) for value in loss_values.values()), + "gradient_norm": gradient_norm, + "residual_head_gradients_finite": residual_head_gradients, + "required_residual_head_gradients_finite": required_head_gradients, + "elapsed_s": elapsed, + "frames_per_s": int(data["T"]) / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "smoke_checkpoint": { + "path": str(checkpoint.resolve()), "sha256": sha256(checkpoint), + }, + "trainable_parameters": sum( + parameter.numel() for parameter in reloaded.parameters() + if parameter.requires_grad + ), + "frozen_parameters": sum( + parameter.numel() for parameter in reloaded.parameters() + if not parameter.requires_grad + ), + } + (args.output_dir / "smoke.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": result["status"], "exact_zero_initialization": exact_zero_init, + "resume_exact": resume_exact, "checkpoint": result["smoke_checkpoint"], + }, indent=2)) + if result["status"] != "passed": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase6_mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase6_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..e77188fd1466a88d3953ae576c22e44590e495bc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase6_mixed_projection.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Real-checkpoint smoke for differentiable Phase 6 mixed projection.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def prefix(batch: dict[str, object], length: int) -> dict[str, object]: + output = {} + for key, value in batch.items(): + output[key] = ( + value[:, :length] if torch.is_tensor(value) and value.ndim >= 2 + and value.shape[1] == batch["frame_valid"].shape[1] + else value + ) + return output + + +def attach_gt_vertices( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> None: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for the real-batch smoke") + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, _ = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = ( + batch["mano_annotation_valid"].bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where( + valid, vertices, torch.full_like(vertices, torch.nan), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if config["model"].get("translation_parameterization") != "mixed_projection": + parser.error("smoke requires mixed_projection") + if sha256(args.checkpoint) != config["experiment"]["coarse_checkpoint_sha256"]: + parser.error("checkpoint hash differs from preregistration") + seed = int(config["seed"]) + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("mixed_log_tz_head",), + map_location=device, + ) + model.initialize_mixed_log_tz_from_direct_head() + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + learning_rate = float(config["protocol"]["learning_rate"]) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + attach_gt_vertices(batch, model) + args.output_dir.mkdir(parents=True, exist_ok=True) + excluded = checkpoint_excluded_prefixes(model) + initialized_checkpoint = args.output_dir / "mixed_projection_initialized_step0.pt" + save_checkpoint( + initialized_checkpoint, model, optimizer, 0, + extra={"kind": "phase6_mixed_projection_initialized_step0"}, + exclude_prefixes=excluded, + ) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + success_fraction = float(prediction["mixed_projection_success"].float().mean()) + teacher_z_difference_mm = float( + 1000.0 * ( + prediction["wrist_root_translation"][..., 2] + - prediction["mixed_projection_direct_teacher_translation"][..., 2] + ).abs().mean() + ) + losses["total"].backward() + gradient_groups = { + "log_tz": ["mixed_log_tz_head."], + "joint2d": ["joint2d_head."], + "pose": ["rotation_head."], + "shape": ["shape_head."], + "decoder": ["decoder."], + } + gradients = {} + for group, prefixes in gradient_groups.items(): + selected = [ + parameter.grad for name, parameter in model.named_parameters() + if parameter.requires_grad and name.startswith(tuple(prefixes)) + ] + gradients[group] = bool( + selected + and all(value is None or torch.isfinite(value).all() for value in selected) + and any(value.abs().sum() > 0 for value in selected if value is not None) + ) + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + model.eval() + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + t1 = model(prefix(batch, 1)) + t1_finite = bool( + torch.isfinite(t1["wrist_root_translation"]).all() + and torch.isfinite(t1["joints_camera"]).all() + ) + checkpoint = args.output_dir / "mixed_projection_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, 1, + extra={"kind": "phase6_mixed_projection_real_checkpoint_smoke"}, + exclude_prefixes=excluded, + ) + expected = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + if not key.startswith(excluded) + } + del model, optimizer, criterion, prediction, losses, t1 + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + reloaded, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected.items() + ) + shared_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("mixed_log_tz_head", "rgb_encoder.backbone.")) + ] + passed = bool( + all(np.isfinite(value) for value in loss_values.values()) + and success_fraction >= 0.99 + and all(gradients.values()) + and t1_finite + and resume_exact + and resumed["step"] == 1 + and not shared_missing + ) + report = { + "status": "passed" if passed else "failed", + "experiment": "P6_S2_differentiable_mixed_projection", + "experiment_class": "engineering_real_checkpoint_smoke", + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_missing, + "mixed_log_tz_initialization": "first-order log-softplus linearization", + "losses": loss_values, + "success_fraction": success_fraction, + "teacher_z_difference_mm": teacher_z_difference_mm, + "gradient_groups_finite_nonzero": gradients, + "gradient_norm": gradient_norm, + "T1_finite": t1_finite, + "T8_finite": all(np.isfinite(value) for value in loss_values.values()), + "elapsed_s": elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "initialized_checkpoint": { + "path": str(initialized_checkpoint.resolve()), + "sha256": sha256(initialized_checkpoint), + "step": 0, + }, + "checkpoint": {"path": str(checkpoint.resolve()), "sha256": sha256(checkpoint)}, + "trainable_parameters": sum(p.numel() for p in reloaded.parameters() if p.requires_grad), + "frozen_parameters": sum(p.numel() for p in reloaded.parameters() if not p.requires_grad), + } + (args.output_dir / "smoke.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "success_fraction": success_fraction, + "gradients": gradients, "resume_exact": resume_exact, + "output": str(args.output_dir), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase6_spatial_joint2d.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase6_spatial_joint2d.py new file mode 100644 index 0000000000000000000000000000000000000000..9c44a3f4073745881c46c5bdcea4843985a927ff --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_phase6_spatial_joint2d.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Real-checkpoint smoke for the Phase 6 spatial joint localizer.""" + +from __future__ import annotations + +import argparse +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, +) +from scripts.smoke_phase6_mixed_projection import attach_gt_vertices, prefix, sha256 + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if config["model"].get("joint2d_parameterization") != "spatial_heatmap": + parser.error("spatial smoke requires joint2d_parameterization=spatial_heatmap") + if sha256(args.checkpoint) != config["experiment"]["coarse_checkpoint_sha256"]: + parser.error("checkpoint hash differs from preregistration") + seed = int(config["seed"]) + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("joint_localization_",), + map_location=device, + ) + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + learning_rate = float(config["protocol"]["learning_rate"]) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + attach_gt_vertices(batch, model) + args.output_dir.mkdir(parents=True, exist_ok=True) + excluded = checkpoint_excluded_prefixes(model) + initialized_checkpoint = args.output_dir / "spatial_joint2d_initialized_step0.pt" + save_checkpoint( + initialized_checkpoint, model, optimizer, 0, + extra={"kind": "phase6_spatial_joint2d_initialized_step0"}, + exclude_prefixes=excluded, + ) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + height, width = map(int, batch["image_hw"][0].tolist()) + teacher_difference_px = float(( + (prediction["joint2d_norm"] - prediction["joint2d_linear_teacher_norm"]) + * prediction["joint2d_norm"].new_tensor((width, height)) + ).abs().mean()) + entropy = prediction["joint2d_heatmap_entropy"] + entropy_finite_bounded = bool( + torch.isfinite(entropy).all() and (entropy >= 0).all() and (entropy <= 1.0 + 1e-6).all() + ) + losses["total"].backward() + groups = { + "embedding": ("joint_localization_embedding",), + "query": ("joint_localization_query.",), + "feature": ("joint_localization_feature.",), + "offset": ("joint_localization_offset.",), + "decoder": ("decoder.",), + } + gradients = {} + for group, prefixes in groups.items(): + selected = [ + parameter.grad for name, parameter in model.named_parameters() + if parameter.requires_grad and name.startswith(prefixes) + ] + gradients[group] = bool( + selected + and all(value is None or torch.isfinite(value).all() for value in selected) + and any(value is not None and value.abs().sum() > 0 for value in selected) + ) + teacher_frozen = all(not parameter.requires_grad for parameter in model.joint2d_head.parameters()) + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + model.eval() + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + t1 = model(prefix(batch, 1)) + t1_finite = bool( + torch.isfinite(t1["joint2d_norm"]).all() + and torch.isfinite(t1["wrist_root_translation"]).all() + ) + checkpoint = args.output_dir / "spatial_joint2d_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, 1, + extra={"kind": "phase6_spatial_joint2d_real_checkpoint_smoke"}, + exclude_prefixes=excluded, + ) + expected = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + if not key.startswith(excluded) + } + del model, optimizer, criterion, prediction, losses, t1 + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + reloaded, learning_rate=learning_rate, backbone_learning_rate=None, + ), lr=learning_rate, weight_decay=0.05, + ) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected.items() + ) + shared_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("joint_localization_", "rgb_encoder.backbone.")) + ] + passed = bool( + all(np.isfinite(value) for value in loss_values.values()) + and all(gradients.values()) and teacher_frozen and entropy_finite_bounded + and t1_finite and resume_exact and resumed["step"] == 1 and not shared_missing + ) + report = { + "status": "passed" if passed else "failed", + "experiment": "P6_S3B_spatial_2d_anchors", + "experiment_class": "engineering_real_checkpoint_smoke", + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_missing, + "losses": loss_values, + "teacher_difference_px": teacher_difference_px, + "teacher_frozen": teacher_frozen, + "entropy_finite_bounded": entropy_finite_bounded, + "gradient_groups_finite_nonzero": gradients, + "gradient_norm": gradient_norm, + "T1_finite": t1_finite, + "T8_finite": all(np.isfinite(value) for value in loss_values.values()), + "elapsed_s": elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "initialized_checkpoint": { + "path": str(initialized_checkpoint.resolve()), + "sha256": sha256(initialized_checkpoint), "step": 0, + }, + "checkpoint": {"path": str(checkpoint.resolve()), "sha256": sha256(checkpoint)}, + } + (args.output_dir / "smoke.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "gradients": gradients, + "resume_exact": resume_exact, "output": str(args.output_dir), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_real_batch.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_real_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..7581b85b5a1e7d58affbf1c719ca10b12c981c1f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/smoke_real_batch.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Real H2O batch structural smoke test; uses debug RGB encoder when weights are absent.""" + +from __future__ import annotations + +import argparse +import json +import time +from pathlib import Path + +import cv2 +import numpy as np +import torch +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint, save_checkpoint + + +def parameter_counts(model: torch.nn.Module) -> tuple[int, int]: + trainable = sum(value.numel() for value in model.parameters() if value.requires_grad) + frozen = sum(value.numel() for value in model.parameters() if not value.requires_grad) + return trainable, frozen + + +def draw_overlay(batch: dict[str, torch.Tensor], output: dict[str, torch.Tensor], path: Path) -> None: + rgb = batch["rgb"][0, 0].detach().cpu().permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + height, width = image.shape[:2] + predicted = output["joint2d_norm"][0, 0].detach().float().cpu().numpy() * np.array((width, height)) + target = batch["joint2d"][0, 0].detach().float().cpu().numpy() + annotation_valid = batch["joint_annotation_valid"][0, 0].cpu().numpy() + for hand, color in enumerate(((50, 220, 50), (50, 80, 255))): + for point in predicted[hand]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, color, -1) + if annotation_valid[hand]: + for point in target[hand]: + cv2.drawMarker(image, tuple(np.rint(point).astype(int)), (255, 255, 255), cv2.MARKER_CROSS, 7, 1) + label = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/{int(batch['frame_id'][0,0])} debug_encoder RGB-D-K" + cv2.rectangle(image, (0, 0), (width, 32), (0, 0, 0), -1) + cv2.putText(image, label, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (255, 255, 255), 1) + cv2.imwrite(str(path), image) + + attention = output["attention"]["rgb_cross_attention"][0, -1, 0].detach().float().cpu().numpy() + grid_h, grid_w = height // 16, width // 16 + for hand, side in enumerate(("left", "right")): + heat = attention[hand].reshape(grid_h, grid_w) + heat = (heat - heat.min()) / max(float(heat.max() - heat.min()), 1e-8) + heat = cv2.resize(np.rint(heat * 255).astype(np.uint8), (width, height), interpolation=cv2.INTER_CUBIC) + heat = cv2.applyColorMap(heat, cv2.COLORMAP_TURBO) + mixed = cv2.addWeighted(image, 0.55, heat, 0.45, 0) + cv2.imwrite(str(path.with_name(path.stem + f"_{side}_rgb_attention.jpg")), mixed) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + torch.manual_seed(20260716); np.random.seed(20260716) + device = torch.device(f"cuda:{args.gpu}") + dataset = H2OCam4Dataset(args.root, args.manifest, (288, 512), (8,), (1,), max_clips=2) + loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_h2o_clips) + batch = next(iter(loader)) + batch = {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + config = ModelConfig( + encoder="tiny_debug", decoder_dim=256, decoder_layers=3, attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, depth_mode="log_depth", + use_rays=True, use_bimanual_interaction=True, require_mano=False, + ) + model = BimanualReconstructionModel(config).to(device).train() + loss_function = BimanualLoss(LossConfig()).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) + torch.cuda.reset_peak_memory_stats(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = loss_function(prediction, batch) + losses["total"].backward() + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000)) + optimizer.step(); torch.cuda.synchronize(device) + elapsed = time.perf_counter() - start + checkpoint = args.output_dir / "real_batch_smoke.pt" + save_checkpoint(checkpoint, model, optimizer, 1, {"kind": "structural_smoke_debug_encoder"}) + reloaded = BimanualReconstructionModel(config).to(device) + reloaded_optimizer = torch.optim.AdamW(reloaded.parameters(), lr=1e-4) + resume = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all(torch.equal(model.state_dict()[key], value) for key, value in reloaded.state_dict().items()) + trainable, frozen = parameter_counts(model) + result = { + "status": "passed_structural_smoke_only", "formal_training": False, + "limitation": "tiny_debug RGB encoder and no MANO assets; joint/vertex/reprojection losses are zero", + "seed": 20260716, "resolution_hw": [288, 512], "T": 8, "stride": 1, "batch_size": 1, "precision": "bf16", + "decoder": "alternating", "depth": "log_depth", "rays": True, + "trainable_parameters": trainable, "frozen_parameters": frozen, + "elapsed_s": elapsed, "frames_per_s": 8 / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30, + "gradient_norm": gradient_norm, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "losses_finite": all(bool(torch.isfinite(value)) for value in losses.values()), + "resume_success": bool(resume_exact and resume["step"] == 1), "checkpoint": str(checkpoint.resolve()), + "input_shapes": {key: list(value.shape) for key, value in batch.items() if torch.is_tensor(value)}, + "output_shapes": {key: list(value.shape) for key, value in prediction.items() if torch.is_tensor(value)}, + "attention_shapes": {key: list(value.shape) for key, value in prediction["attention"].items()}, + } + (args.output_dir / "real_batch_smoke.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + draw_overlay(batch, prediction, args.output_dir / "real_batch_prediction_overlay.jpg") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/split_phase7_h2o_train_cache.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/split_phase7_h2o_train_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..add4ccef194d122b76ef5d116d75a15fe37c347a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/split_phase7_h2o_train_cache.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Create deterministic recording-group H2O train-fit/heldout cache manifests.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def assign_group_folds(rows: list[dict[str, Any]], folds: int, seed: int) -> dict[str, int]: + if folds < 2: + raise ValueError("at least two folds are required") + subjects: dict[str, set[str]] = defaultdict(set) + group_subject: dict[str, str] = {} + for row in rows: + if str(row.get("dataset_id", "")).upper() != "H2O": + raise ValueError("H2O train cache split refuses non-H2O rows") + group = str(row["physical_recording_id"]) + subject = str(row["subject_id"]) + if group in group_subject and group_subject[group] != subject: + raise ValueError(f"physical recording spans subjects: {group}") + group_subject[group] = subject + subjects[subject].add(group) + assignments: dict[str, int] = {} + for subject, groups in sorted(subjects.items()): + ordered = sorted(groups, key=lambda group: hashlib.sha256( + f"{seed}|{subject}|{group}".encode("utf-8") + ).hexdigest()) + for index, group in enumerate(ordered): + assignments[group] = index % folds + return assignments + + +def split_rows( + rows: list[dict[str, Any]], assignments: dict[str, int], heldout_fold: int, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + fit, heldout = [], [] + for row in rows: + target = heldout if assignments[str(row["physical_recording_id"])] == heldout_fold else fit + target.append(row) + if not fit or not heldout: + raise ValueError("fit and heldout manifests must both be nonempty") + fit_groups = {row["physical_recording_id"] for row in fit} + heldout_groups = {row["physical_recording_id"] for row in heldout} + if fit_groups & heldout_groups: + raise AssertionError("physical recording leakage across H2O train split") + return fit, heldout + + +def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), encoding="utf-8", + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--cache-report", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--folds", type=int, default=5) + parser.add_argument("--heldout-fold", type=int, default=0) + parser.add_argument("--seed", type=int, default=20260717) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + if not 0 <= args.heldout_fold < args.folds: + parser.error("heldout fold is outside the fold range") + cache_report = json.loads(args.cache_report.read_text(encoding="utf-8")) + if ( + cache_report.get("status") != "complete" + or cache_report.get("dataset") != "H2O" + or cache_report.get("split_role") != "official_train" + or cache_report.get("h2o_official_validation_used") is not False + or cache_report.get("official_test_used") is not False + or cache_report["cache_manifest"]["sha256"] != sha256(args.cache_manifest) + ): + parser.error("cache report does not prove a complete official-train-only cache") + rows = [ + json.loads(line) for line in args.cache_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + assignments = assign_group_folds(rows, args.folds, args.seed) + fit, heldout = split_rows(rows, assignments, args.heldout_fold) + args.output_dir.mkdir(parents=True) + fit_path = args.output_dir / "train_fit.jsonl" + heldout_path = args.output_dir / "train_group_heldout.jsonl" + write_jsonl(fit_path, fit) + write_jsonl(heldout_path, heldout) + record = { + "status": "frozen_h2o_train_group_split", "schema_version": "phase7_h2o_train_group_cv_v1", + "source_cache_manifest": { + "path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest), + }, + "folds": args.folds, "heldout_fold": args.heldout_fold, "seed": args.seed, + "group_key": "(dataset_id, subject_id, physical_recording_id)", + "fit": { + "path": str(fit_path.resolve()), "sha256": sha256(fit_path), "clips": len(fit), + "recordings": len({row["physical_recording_id"] for row in fit}), + }, + "heldout": { + "path": str(heldout_path.resolve()), "sha256": sha256(heldout_path), + "clips": len(heldout), + "recordings": len({row["physical_recording_id"] for row in heldout}), + }, + "assignments": assignments, "recording_overlap": [], + "h2o_official_validation_used": False, "official_test_used": False, + } + (args.output_dir / "split.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_core.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_core.py new file mode 100644 index 0000000000000000000000000000000000000000..5e82cefcfac1b2f5833989ea3e5058a087bbd01f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_core.py @@ -0,0 +1,405 @@ +#!/usr/bin/env python3 +"""Summarize the pre-registered Phase 3 decoder/temporal core matrix.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import Iterable + +import numpy as np + + +CHECKPOINT_ROLES = ( + "step_025k", "step_050k", "step_075k", "step_100k", + "best_absolute", "best_z", "final", +) +FRAME_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "wrong_side_preference", +) +REPORT_METRICS = FRAME_METRICS + ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "identity_switch_fraction", +) +PAIR_DEFINITIONS = ( + ("l0_temporal", "L0", "T1", "L0", "T0"), + ("l1_temporal", "L1", "T1", "L1", "T0"), + ("alternating_without_temporal", "L1", "T0", "L0", "T0"), + ("alternating_with_temporal", "L1", "T1", "L0", "T1"), + ("hybrid_reread_vs_sequential", "L2", "T1", "L0", "T1"), + ("hybrid_reread_vs_alternating", "L2", "T1", "L1", "T1"), +) +OBSERVATION_KEY = ( + "clip_index", "time_index", "take", "subject", "sequence", + "frame_id", "side", "annotation_valid", "annotation_state", +) +TEMPORAL_OBSERVATION_KEY = ( + "clip_index", "transition_index", "take", "subject", "sequence", + "frame_id_from", "frame_id_to", "side", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: Iterable[dict[str, object]]) -> None: + rows = list(rows) + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fieldnames = list(rows[0]) + if any(list(row) != fieldnames for row in rows): + raise ValueError(f"inconsistent CSV fields for {path}") + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: str | None) -> float | None: + if value is None or value == "": + return None + result = float(value) + return result if math.isfinite(result) else None + + +def paired_take_differences( + candidate_rows: list[dict[str, str]], + reference_rows: list[dict[str, str]], + metric: str, + observation_key: tuple[str, ...] = OBSERVATION_KEY, +) -> dict[str, float]: + if len(candidate_rows) != len(reference_rows): + raise ValueError("paired evaluations have different observation counts") + take_values: dict[str, list[float]] = defaultdict(list) + frame_values = [] + for candidate, reference in zip(candidate_rows, reference_rows, strict=True): + if any(candidate[key] != reference[key] for key in observation_key): + raise ValueError("paired evaluations do not have identical observation order") + candidate_value = optional_float(candidate.get(metric)) + reference_value = optional_float(reference.get(metric)) + if candidate_value is None or reference_value is None: + continue + difference = candidate_value - reference_value + take_values[candidate["take"]].append(difference) + frame_values.append(difference) + if not take_values: + raise ValueError(f"no paired values for {metric}") + take_means = np.asarray([ + np.mean(values, dtype=np.float64) for _, values in sorted(take_values.items()) + ], dtype=np.float64) + return { + "take_equal_mean_delta": float(take_means.mean()), + "frame_weighted_mean_delta": float(np.mean(frame_values, dtype=np.float64)), + "take_count": int(take_means.size), + "observation_count": int(len(frame_values)), + "take_means": take_means, + } + + +def bootstrap_take_values( + take_values: np.ndarray, + seed: int = 20260716, + samples: int = 10_000, +) -> tuple[float, float]: + if take_values.ndim != 1 or take_values.size == 0: + raise ValueError("take_values must be a non-empty vector") + rng = np.random.default_rng(seed) + indices = rng.integers(0, take_values.size, size=(samples, take_values.size)) + means = take_values[indices].mean(axis=1) + return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5)) + + +def metric_mean(report: dict, name: str) -> float | None: + entry = report["metrics"].get(name) + if entry is not None: + return entry.get("mean") + if name in {"translation_x_mae_mm", "translation_y_mae_mm"}: + components = [ + report["metrics"][f"{side}_{name}"] for side in ("left", "right") + ] + count = sum(int(component["count"]) for component in components) + if count: + return sum( + float(component["mean"]) * int(component["count"]) + for component in components + ) / count + return None + + +def attention_mean(report: dict, name: str) -> float | None: + entry = report["attention"].get(name) + return None if entry is None else entry.get("mean") + + +def load_report(path: Path) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("official_test_used") is not False: + raise ValueError(f"invalid formal evaluation: {path}") + if report.get("split_role") != "official_validation" or report.get("clips") != 1495: + raise ValueError(f"incomplete or non-validation evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--temporal-evaluation-root", type=Path) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + report_paths = sorted(args.evaluation_root.glob("core_*/*/evaluation.json")) + if len(report_paths) != 210: + raise ValueError(f"expected 210 checkpoint evaluations, found {len(report_paths)}") + + all_rows = [] + best_rows = [] + reports_by_key: dict[tuple[str, str, str, int, str], tuple[Path, dict]] = {} + checkpoints: dict[str, dict[str, object]] = {} + collected_bootstrap = [] + for path in report_paths: + report = load_report(path) + config = report["config"] + experiment = config["experiment"] + run_name = path.parent.parent.name + role = path.parent.name + if role not in CHECKPOINT_ROLES: + raise ValueError(f"unregistered checkpoint role: {role}") + seed = int(config["seed"]) + training_summary = json.loads((args.run_root / run_name / "summary.json").read_text(encoding="utf-8")) + row: dict[str, object] = { + "run": run_name, + "modality": experiment["modality"], + "layout": experiment["layout"], + "temporal": experiment["temporal"], + "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "rgb_same_peak": attention_mean(report, "rgb_same_peak"), + "rgb_left_right_cosine": attention_mean(report, "rgb_left_right_cosine"), + "temporal_normalized_entropy": attention_mean(report, "temporal_normalized_entropy"), + "temporal_diagonal": attention_mean(report, "temporal_diagonal"), + "depth_fusion_gate": attention_mean(report, "depth_fusion_gate"), + "depth_fusion_gate_raw": attention_mean(report, "depth_fusion_gate_raw"), + "rgb_update_norm": attention_mean(report, "rgb_update_norm"), + "depth_update_norm": attention_mean(report, "depth_update_norm"), + "gated_depth_update_norm": attention_mean(report, "gated_depth_update_norm"), + "trainable_parameters": training_summary["trainable_parameters"], + "frozen_parameters": training_summary["frozen_parameters"], + "peak_vram_gib": training_summary["peak_vram_gib"], + "training_frames_per_s": training_summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + reports_by_key[(experiment["modality"], experiment["layout"], experiment["temporal"], seed, role)] = (path, report) + for bootstrap in report["bootstrap"]: + collected_bootstrap.append({ + "run": run_name, "modality": experiment["modality"], + "layout": experiment["layout"], "temporal": experiment["temporal"], + "seed": seed, "checkpoint_role": role, **bootstrap, + }) + checkpoint_record = checkpoints.setdefault(run_name, { + "config": config["name"], "modality": experiment["modality"], + "layout": experiment["layout"], "temporal": experiment["temporal"], + "seed": seed, "roles": {}, + }) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + write_csv(args.output_dir / "checkpoint_comparison.csv", all_rows) + write_csv(args.output_dir / "comparison.csv", best_rows) + write_csv(args.output_dir / "bootstrap_ci.csv", collected_bootstrap) + (args.output_dir / "checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for group_key in sorted({ + (row["modality"], row["layout"], row["temporal"]) for row in best_rows + }): + group = [row for row in best_rows if (row["modality"], row["layout"], row["temporal"]) == group_key] + if len(group) != 3: + raise ValueError(f"expected three seeds for {group_key}, got {len(group)}") + record: dict[str, object] = { + "modality": group_key[0], "layout": group_key[1], "temporal": group_key[2], + "seeds": [row["seed"] for row in group], + } + for metric in REPORT_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), + "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = {"mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1))} + aggregate.append(record) + + paired_rows = [] + for modality in ("M0", "M3"): + for comparison, candidate_layout, candidate_temporal, reference_layout, reference_temporal in PAIR_DEFINITIONS: + per_metric_by_seed: dict[str, list[dict[str, float]]] = defaultdict(list) + for seed in (20260716, 20260717, 20260718): + candidate_path, _ = reports_by_key[(modality, candidate_layout, candidate_temporal, seed, "best_absolute")] + reference_path, _ = reports_by_key[(modality, reference_layout, reference_temporal, seed, "best_absolute")] + candidate_rows = read_csv(candidate_path.parent / "per_hand_frame_metrics.csv") + reference_rows = read_csv(reference_path.parent / "per_hand_frame_metrics.csv") + for metric in FRAME_METRICS: + result = paired_take_differences(candidate_rows, reference_rows, metric) + per_metric_by_seed[metric].append({"seed": seed, **result}) + for metric in FRAME_METRICS: + results = per_metric_by_seed[metric] + stacked = np.stack([result["take_means"] for result in results], axis=0) + take_values = stacked.mean(axis=0) + ci_low, ci_high = bootstrap_take_values(take_values, args.seed, args.bootstrap_samples) + seed_deltas = [float(result["take_equal_mean_delta"]) for result in results] + paired_rows.append({ + "modality": modality, + "comparison": comparison, + "candidate": f"{candidate_layout}-{candidate_temporal}", + "reference": f"{reference_layout}-{reference_temporal}", + "metric": metric, + "delta_definition": "candidate_minus_reference_lower_is_better", + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "take_count": int(results[0]["take_count"]), + "observations_per_seed": int(results[0]["observation_count"]), + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + write_csv(args.output_dir / "paired_bootstrap_ci.csv", paired_rows) + + paired_temporal_rows = [] + if args.temporal_evaluation_root is not None: + temporal_metrics = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", + ) + for modality in ("M0", "M3"): + for comparison, candidate_layout, candidate_temporal, reference_layout, reference_temporal in PAIR_DEFINITIONS: + per_metric_by_seed: dict[str, list[dict[str, float]]] = defaultdict(list) + for seed in (20260716, 20260717, 20260718): + candidate_source, _ = reports_by_key[(modality, candidate_layout, candidate_temporal, seed, "best_absolute")] + reference_source, _ = reports_by_key[(modality, reference_layout, reference_temporal, seed, "best_absolute")] + candidate_path = ( + args.temporal_evaluation_root / candidate_source.parent.parent.name + / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + reference_path = ( + args.temporal_evaluation_root / reference_source.parent.parent.name + / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + candidate_rows = read_csv(candidate_path) + reference_rows = read_csv(reference_path) + for metric in temporal_metrics: + result = paired_take_differences( + candidate_rows, reference_rows, metric, + observation_key=TEMPORAL_OBSERVATION_KEY, + ) + per_metric_by_seed[metric].append({"seed": seed, **result}) + for metric in temporal_metrics: + results = per_metric_by_seed[metric] + stacked = np.stack([result["take_means"] for result in results], axis=0) + take_values = stacked.mean(axis=0) + ci_low, ci_high = bootstrap_take_values(take_values, args.seed, args.bootstrap_samples) + seed_deltas = [float(result["take_equal_mean_delta"]) for result in results] + paired_temporal_rows.append({ + "modality": modality, + "comparison": comparison, + "candidate": f"{candidate_layout}-{candidate_temporal}", + "reference": f"{reference_layout}-{reference_temporal}", + "metric": metric, + "delta_definition": "candidate_minus_reference_lower_is_better", + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "take_count": int(results[0]["take_count"]), + "observations_per_seed": int(results[0]["observation_count"]), + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + write_csv(args.output_dir / "paired_temporal_bootstrap_ci.csv", paired_temporal_rows) + + payload = { + "status": "complete", + "official_test_used": False, + "checkpoint_selection": "best_absolute selected only by the registered fixed 256-clip validation subset", + "evaluations": len(report_paths), + "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_bootstrap": { + "path": str((args.output_dir / "paired_bootstrap_ci.csv").resolve()), + "definition": "For each seed and take, compute paired per-observation candidate-reference deltas; average seeds within take; bootstrap the 24 take means.", + "temporal_path": ( + str((args.output_dir / "paired_temporal_bootstrap_ci.csv").resolve()) + if paired_temporal_rows else None + ), + "temporal_metric_limitation": ( + None if paired_temporal_rows + else "Provide --temporal-evaluation-root with transition exports to compute paired temporal take CIs." + ), + }, + "source_hashes": { + "full_validation_launcher_provenance": sha256(args.evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(report_paths), + "best_absolute_runs": len(best_rows), "paired_rows": len(paired_rows), + "paired_temporal_rows": len(paired_temporal_rows), + "output_dir": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_depth_fusion.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_depth_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2a737a31f0909731dfc210277fff9c0a27cda9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_depth_fusion.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +"""Summarize the registered Phase 3 Depth fusion/representation controls.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + write_csv, + ) + + +VARIANTS = ("P0_fixed05", "gate025", "learned_gate", "geometry") +NEW_VARIANTS = ("gate025", "learned_gate", "geometry") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def run_name(variant: str, seed: int) -> str: + if variant == "P0_fixed05": + return f"core_m3_l1_t1_s{seed}" + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_variant = None if variant == "P0_fixed05" else variant + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or (expected_variant is not None and experiment.get("variant") != expected_variant) + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal depth-fusion evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--new-run-root", type=Path, default=Path("artifacts/phase3/depth_fusion_runs")) + parser.add_argument("--core-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--new-evaluation-root", type=Path, default=Path("artifacts/phase3/depth_fusion_full_validation")) + parser.add_argument("--core-temporal-root", type=Path, default=Path("artifacts/phase3/temporal_position_p0_diagnostics")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + rows = [] + best_rows = [] + checkpoints: dict[str, dict] = {} + bootstrap_rows = [] + for variant in VARIANTS: + evaluation_root = args.core_evaluation_root if variant == "P0_fixed05" else args.new_evaluation_root + run_root = args.core_run_root if variant == "P0_fixed05" else args.new_run_root + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal run: {name}") + checkpoint_record = {"variant": variant, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + report_path = evaluation_root / name / role / "evaluation.json" + report = load_report(report_path, variant, seed) + reports[(variant, seed, role)] = (report_path, report) + row = { + "run": name, "variant": variant, "modality": "M3", + "layout": "L1", "temporal": "T1", "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in ( + "temporal_normalized_entropy", "temporal_diagonal", + "temporal_update_norm", "depth_fusion_gate", + "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ): + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, **item, + } for item in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(report_path.resolve()), + } + + expected_rows = len(VARIANTS) * len(SEEDS) * len(CHECKPOINT_ROLES) + if len(rows) != expected_rows or len(best_rows) != len(VARIANTS) * len(SEEDS): + raise ValueError(f"expected {expected_rows} rows, got {len(rows)}") + write_csv(args.output_dir / "depth_fusion_checkpoint_comparison.csv", rows) + write_csv(args.output_dir / "depth_fusion_comparison.csv", best_rows) + write_csv(args.output_dir / "depth_fusion_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "depth_fusion_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant, "modality": "M3", "layout": "L1", "temporal": "T1"} + for metric in FRAME_METRICS + TEMPORAL_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), + "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", "peak_vram_gib", + "training_frames_per_s", + ): + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + report_path, _ = reports[(variant, seed, "best_absolute")] + frame_cache[(variant, seed)] = read_csv(report_path.parent / "per_hand_frame_metrics.csv") + temporal_root = args.core_temporal_root if variant == "P0_fixed05" else args.new_evaluation_root + temporal_cache[(variant, seed)] = read_csv( + temporal_root / run_name(variant, seed) / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for variant in NEW_VARIANTS: + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {"candidate": frame_cache[(variant, seed)], "P0": frame_cache[("P0_fixed05", seed)]}, + metric, {"candidate": 1.0, "P0": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": f"{variant}-P0_fixed05", + "contrast": "+1*candidate -1*P0", + "metric": metric, + "delta_definition": "candidate minus fixed-gate-0.5 P0; lower is better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_fusion_bootstrap_ci.csv", paired_rows) + + temporal_rows = [] + for variant in NEW_VARIANTS: + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {"candidate": temporal_cache[(variant, seed)], "P0": temporal_cache[("P0_fixed05", seed)]}, + metric, {"candidate": 1.0, "P0": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": f"{variant}-P0_fixed05", + "contrast": "+1*candidate -1*P0", + "metric": metric, + "delta_definition": "candidate minus fixed-gate-0.5 P0; lower is better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_fusion_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", + "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "formal_validation_clips_per_run": 1495, + "evaluations": len(rows), + "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_depth_fusion_bootstrap_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_depth_fusion_temporal_ci.csv").resolve()), + "source_hashes": { + "new_validation_launcher": sha256(args.new_evaluation_root / "launcher_provenance.json"), + "core_validation_launcher": sha256(args.core_evaluation_root / "launcher_provenance.json"), + "matrix": sha256(Path("artifacts/phase3/reports/depth_fusion_new_runs.csv")), + }, + } + (args.output_dir / "depth_fusion_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "best_absolute_runs": len(best_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_dropout.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..f35a51389b1ce94b0b81b50bdffe572d73543924 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_dropout.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Summarize the same-commit Phase 3 geometry modality-dropout matrix.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) + + +VARIANTS = ("dropout00_geometry", "dropout02_geometry") + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown dropout variant: {variant}") + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "depth_modality_dropout" + or experiment.get("variant") != variant + or experiment.get("modality") != "M3" + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid complete-modality dropout evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row[metric] is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--run-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_runs_commit7583772"), + ) + parser.add_argument( + "--evaluation-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports = {} + checkpoint_rows = [] + best_rows = [] + checkpoints = {} + bootstrap_rows = [] + diagnostics = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((args.run_root / name / "summary.json").read_text(encoding="utf-8")) + provenance = json.loads( + (args.run_root / name / "run_provenance.json").read_text(encoding="utf-8") + ) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != "75837726f7eb8232b747932cbf536a834821e24d" + ): + raise ValueError(f"invalid formal dropout training run: {name}") + checkpoint_record = {"variant": variant, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = args.evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("dropout matrix is incomplete") + write_csv(args.output_dir / "depth_dropout_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "depth_dropout_comparison.csv", best_rows) + write_csv(args.output_dir / "depth_dropout_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "depth_dropout_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + diagnostics + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "dropout02": frame_cache[("dropout02_geometry", seed)], + "dropout00": frame_cache[("dropout00_geometry", seed)], + }, + metric, {"dropout02": 1.0, "dropout00": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": "dropout02_geometry-dropout00_geometry", + "metric": metric, "delta_definition": "dropout02 minus dropout00; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_bootstrap_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "dropout02": temporal_cache[("dropout02_geometry", seed)], + "dropout00": temporal_cache[("dropout00_geometry", seed)], + }, + metric, {"dropout02": 1.0, "dropout00": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": "dropout02_geometry-dropout00_geometry", + "metric": metric, "delta_definition": "dropout02 minus dropout00; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": "75837726f7eb8232b747932cbf536a834821e24d", + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str( + (args.output_dir / "paired_depth_dropout_bootstrap_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_depth_dropout_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "depth_dropout_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_dropout_dose.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_dropout_dose.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cbe8b0c7d099c4541ed67e9338ec4ffe15eac6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_dropout_dose.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +"""Summarize D.2 endpoints together with the D.3 dropout-dose sweep.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) + + +TRAINING_COMMIT = "75837726f7eb8232b747932cbf536a834821e24d" +VARIANTS = ( + "dropout00_geometry", "dropout005_geometry", + "dropout010_geometry", "dropout02_geometry", +) +ENDPOINT_VARIANTS = {"dropout00_geometry", "dropout02_geometry"} +COMPARISONS = ( + ("dropout005_geometry", "dropout00_geometry"), + ("dropout010_geometry", "dropout00_geometry"), + ("dropout02_geometry", "dropout00_geometry"), + ("dropout010_geometry", "dropout005_geometry"), + ("dropout02_geometry", "dropout010_geometry"), + ("dropout02_geometry", "dropout005_geometry"), +) + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown dropout-dose variant: {variant}") + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def matrix_for(variant: str) -> str: + return ( + "depth_modality_dropout" + if variant in ENDPOINT_VARIANTS else "depth_modality_dropout_dose" + ) + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row[metric] is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != matrix_for(variant) + or experiment.get("variant") != variant + or experiment.get("modality") != "M3" + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid complete dropout-dose evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--endpoint-run-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_runs_commit7583772"), + ) + parser.add_argument( + "--dose-run-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_runs_commit7583772"), + ) + parser.add_argument( + "--endpoint-evaluation-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--dose-evaluation-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + diagnostics = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + reports = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + for variant in VARIANTS: + run_root = ( + args.endpoint_run_root if variant in ENDPOINT_VARIANTS else args.dose_run_root + ) + evaluation_root = ( + args.endpoint_evaluation_root + if variant in ENDPOINT_VARIANTS else args.dose_evaluation_root + ) + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text()) + provenance = json.loads((run_root / name / "run_provenance.json").read_text()) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid dropout-dose training run: {name}") + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 84 or len(best_rows) != 12: + raise ValueError("dropout-dose matrix is incomplete") + write_csv(args.output_dir / "dropout_dose_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "dropout_dose_comparison.csv", best_rows) + write_csv(args.output_dir / "dropout_dose_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "dropout_dose_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n" + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + diagnostics + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + temporal_rows = [] + for candidate, reference in COMPARISONS: + comparison = f"{candidate}-{reference}" + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(candidate, seed)], + "reference": frame_cache[(reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(candidate, seed)], + "reference": temporal_cache[(reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_dropout_dose_ci.csv", paired_rows) + write_csv(args.output_dir / "paired_dropout_dose_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_dropout_dose_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_dropout_dose_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "dropout_dose_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_dropout_dose_fallback.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_dropout_dose_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..2daef68597394f8412587333dcbf489ce2f188f0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_dropout_dose_fallback.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""Summarize complete and missing-modality behavior across four dropout doses.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_dropout_dose import ( + COMPARISONS as DOSE_COMPARISONS, ENDPOINT_VARIANTS, VARIANTS, + matrix_for, run_name, + ) + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_dropout_dose import ( + COMPARISONS as DOSE_COMPARISONS, ENDPOINT_VARIANTS, VARIANTS, + matrix_for, run_name, + ) + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_depth, expected_k = CONDITIONS[condition] + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != matrix_for(variant) + or experiment.get("variant") != variant + or int(report["config"]["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid dropout-dose fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--endpoint-complete-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--dose-complete-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument( + "--endpoint-fallback-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_fallback"), + ) + parser.add_argument( + "--dose-fallback-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_fallback"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + diagnostics = ( + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + for variant in VARIANTS: + if variant in ENDPOINT_VARIANTS: + root = ( + args.endpoint_complete_root if condition == "complete" + else args.endpoint_fallback_root / condition + ) + else: + root = ( + args.dose_complete_root if condition == "complete" + else args.dose_fallback_root / condition + ) + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 48: + raise ValueError(f"expected 48 dropout-dose fallback rows, got {len(rows)}") + write_csv(args.output_dir / "dropout_dose_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + diagnostics: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": ( + float(np.std(values, ddof=1)) if len(values) > 1 else None + ), + } + aggregate.append(record) + + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + for candidate, reference in DOSE_COMPARISONS: + contrasts.append(( + f"{condition}:{candidate}-{reference}", + (condition, candidate), (condition, reference), + )) + + paired_rows = [] + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_dropout_dose_fallback_ci.csv", paired_rows) + write_csv( + args.output_dir / "paired_dropout_dose_fallback_temporal_ci.csv", temporal_rows + ) + + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + equality.append({ + "variant": variant, + "seed": seed, + "frame_metrics_identical": ( + frame_cache[("drop_k", variant, seed)] + == frame_cache[("drop_both", variant, seed)] + ), + }) + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "paired_frame": str( + (args.output_dir / "paired_dropout_dose_fallback_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_dropout_dose_fallback_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "dropout_dose_fallback_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + all_equal = all(row["frame_metrics_identical"] for row in equality) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all_equal, + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + if not all_equal: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_fallback.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..5e26939c7294190d782e80c1a8713655ecf32cb7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_fallback.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""Summarize missing Depth/K inference behavior for the geometry dropout matrix.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from scripts.summarize_phase3_dropout import VARIANTS, run_name +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from summarize_phase3_dropout import VARIANTS, run_name + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_depth, expected_k = CONDITIONS[condition] + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("variant") != variant + or int(report["config"]["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--complete-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--fallback-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_fallback"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + diagnostics = ( + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + reports = {} + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + root = args.complete_root if condition == "complete" else args.fallback_root / condition + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + reports[(condition, variant, seed)] = path + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 24: + raise ValueError(f"expected 24 fallback rows, got {len(rows)}") + write_csv(args.output_dir / "depth_dropout_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + diagnostics: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + } + aggregate.append(record) + + paired_rows = [] + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + contrasts.append(( + f"{condition}:dropout02-dropout00", + (condition, "dropout02_geometry"), + (condition, "dropout00_geometry"), + )) + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_fallback_ci.csv", paired_rows) + + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_fallback_temporal_ci.csv", temporal_rows) + + # Geometry needs K for XYZ construction, so drop-K and drop-both should be identical. + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + k_rows = frame_cache[("drop_k", variant, seed)] + both_rows = frame_cache[("drop_both", variant, seed)] + equality.append({ + "variant": variant, "seed": seed, + "frame_metrics_identical": k_rows == both_rows, + }) + payload = { + "status": "complete", "official_test_used": False, + "geometry_k_dependency": ( + "When K is unavailable, XYZ/logZ geometry tokens and ray conditioning are both " + "disabled. Therefore drop_k and drop_both are expected to be identical." + ), + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "paired_frame": str( + (args.output_dir / "paired_depth_dropout_fallback_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_depth_dropout_fallback_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "depth_dropout_fallback_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all( + row["frame_metrics_identical"] for row in equality + ), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_long_tail.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_long_tail.py new file mode 100644 index 0000000000000000000000000000000000000000..d113631c873a7e249781efb84b821f65e074cebd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_long_tail.py @@ -0,0 +1,337 @@ +#!/usr/bin/env python3 +"""Summarize the preregistered Phase 3 100k-to-150k low-LR tail.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, sha256, write_csv, + ) + from scripts.summarize_phase3_photometric import DIAGNOSTICS +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, sha256, write_csv, + ) + from summarize_phase3_photometric import DIAGNOSTICS + + +TRAINING_COMMIT = "d4019222835132fcbcc850ba49e6e0b53ab352b3" +REFERENCE_ROLE = "reference_best_absolute" +TAIL_ROLES = ( + "tail_step_125k", "tail_step_150k", "tail_best_absolute", + "tail_best_z", "tail_final", +) +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", "translation_z_mae_mm", +) + + +def reference_name(seed: int) -> str: + return f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + + +def tail_name(seed: int) -> str: + return f"longtail_{reference_name(seed)}" + + +def load_report(path: Path, seed: int, tail: bool) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + override = report.get("inference_modality_override", {}) + expected_matrix = "low_lr_tail" if tail else "photometric_augmentation" + expected_variant = ( + "photometric_on_r640x368_tail150k" if tail + else "photometric_on_r640x368" + ) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != expected_matrix + or experiment.get("variant") != expected_variant + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or int(config["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid long-tail evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def load_resume_audit(path: Path) -> dict: + audit = json.loads(path.read_text(encoding="utf-8")) + expected = {tail_name(seed) for seed in SEEDS} + rows = audit.get("runs", []) + if ( + audit.get("status") != "passed" + or audit.get("official_test_used") is not False + or {row.get("run") for row in rows} != expected + or any( + row.get("reference_step") != 150_000 + or row.get("resumed_step") != 150_000 + or not all(row.get(key) is True for key in ( + "model_exact", "optimizer_exact", "python_rng_exact", + "numpy_rng_exact", "torch_rng_exact", "cuda_rng_exact", + )) + for row in rows + ) + ): + raise ValueError(f"invalid long-tail exact-resume audit: {path}") + return {"status": "passed", "runs": len(rows), "path": str(path.resolve()), "sha256": sha256(path)} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--reference-evaluation-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--tail-run-root", type=Path, + default=Path("artifacts/phase3/long_tail_runs_commitd401922"), + ) + parser.add_argument( + "--tail-evaluation-root", type=Path, + default=Path("artifacts/phase3/long_tail_full_validation"), + ) + parser.add_argument( + "--resume-root", type=Path, + default=Path("artifacts/phase3/long_tail_resume_from125k"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports = {} + checkpoint_rows = [] + checkpoints = {} + training_audit = {} + for seed in SEEDS: + name = tail_name(seed) + run_dir = args.tail_run_root / name + summary = json.loads((run_dir / "summary.json").read_text(encoding="utf-8")) + provenance_path = Path(summary["run_provenance"]) + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + expected_resume = ( + Path("/SSD3/jiasen/foundation_hand/phase3_artifacts/photometric_runs_commit239b0bf") + / reference_name(seed) / "step_0100000_final.pt" + ) + schedule = summary.get("learning_rate_schedule", {}) + if ( + summary.get("status") != "completed" + or summary.get("start_step") != 100_000 + or summary.get("completed_step") != 150_000 + or schedule.get("total_steps") != 100_000 + or schedule.get("training_max_steps") != 150_000 + or schedule.get("min_lr") != 5e-6 + or provenance.get("git_commit") != TRAINING_COMMIT + or provenance.get("git_status") != "" + or Path(provenance.get("resume_checkpoint", "")).resolve() != expected_resume.resolve() + ): + raise ValueError(f"invalid long-tail training run: {name}") + training_audit[name] = { + "seed": seed, "start_step": 100_000, "completed_step": 150_000, + "lr_schedule_steps": 100_000, "min_lr": 5e-6, + "provenance": str(provenance_path), "provenance_sha256": sha256(provenance_path), + } + checkpoints[name] = {"seed": seed, "roles": {}} + paths = { + REFERENCE_ROLE: ( + args.reference_evaluation_root / reference_name(seed) + / "best_absolute" / "evaluation.json" + ), + **{ + role: args.tail_evaluation_root / name / role / "evaluation.json" + for role in TAIL_ROLES + }, + } + for role, path in paths.items(): + tail = role != REFERENCE_ROLE + report = load_report(path, seed, tail) + reports[(role, seed)] = path + row = { + "run": name, "seed": seed, "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "tail_training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + if len(checkpoint_rows) != 18: + raise ValueError(f"expected 18 reference/tail rows, got {len(checkpoint_rows)}") + write_csv(args.output_dir / "long_tail_checkpoint_comparison.csv", checkpoint_rows) + (args.output_dir / "long_tail_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + primary_roles = (REFERENCE_ROLE, "tail_best_absolute") + aggregate = [] + for role in primary_roles: + group = [row for row in checkpoint_rows if row["checkpoint_role"] == role] + record = {"role": role} + for metric in FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS: + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + joint_cache = {} + for role in primary_roles: + for seed in SEEDS: + parent = reports[(role, seed)].parent + frame_cache[(role, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(role, seed)] = read_csv(parent / "per_temporal_transition_metrics.csv") + joint_cache[(role, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in read_csv(parent / "per_joint_metrics.csv") + } + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + return contrast_take_differences( + { + "reference": cache[(REFERENCE_ROLE, seed)], + "tail": cache[("tail_best_absolute", seed)], + }, + metric, {"reference": -1.0, "tail": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in FRAME_METRICS: + paired_rows.append({ + "comparison": "tail_best-reference_best", "metric": metric, + "delta_definition": "tail minus reference; lower is better", + **aggregate_seed_contrasts( + [paired(metric, seed) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ), + }) + write_csv(args.output_dir / "paired_long_tail_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + temporal_rows.append({ + "comparison": "tail_best-reference_best", "metric": metric, + "delta_definition": "tail minus reference; lower is better", + **aggregate_seed_contrasts( + [paired(metric, seed, temporal=True) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ), + }) + write_csv(args.output_dir / "paired_long_tail_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": "tail_best-reference_best", + "subgroup_axis": subgroup[0], "subgroup_value": subgroup[1], + "metric": metric, + "delta_definition": "tail minus reference; lower is better", + } + try: + result = aggregate_seed_contrasts( + [paired(metric, seed, subgroup=subgroup) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ) + except ValueError as error: + if "no paired values" not in str(error): + raise + result = { + "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, + "seed_20260717_delta": None, + "seed_20260718_delta": None, + "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + } + available = False + else: + available = True + subgroup_rows.append({**prefix, "available": available, **result}) + write_csv(args.output_dir / "paired_long_tail_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + for side in ("left", "right"): + for joint_index in range(21): + reference = np.asarray([ + joint_cache[(REFERENCE_ROLE, seed)][(side, joint_index)] for seed in SEEDS + ]) + tail = np.asarray([ + joint_cache[("tail_best_absolute", seed)][(side, joint_index)] for seed in SEEDS + ]) + joint_rows.append({ + "side": side, "joint_index": joint_index, + "reference_seed_mean_mm": float(reference.mean()), + "tail_seed_mean_mm": float(tail.mean()), + "tail_minus_reference_seed_mean_mm": float((tail - reference).mean()), + "tail_minus_reference_seed_sample_std_mm": float((tail - reference).std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "long_tail_per_joint_comparison.csv", joint_rows) + + resume_audit = load_resume_audit(args.resume_root / "exact_resume_audit.json") + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(checkpoint_rows), "aggregate": aggregate, + "training_audit": training_audit, "exact_resume": resume_audit, + } + output = args.output_dir / "long_tail_comparison.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "output": str(output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_modality.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..086229a9170bafceb69ba11354aba9b9c2f33897 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_modality.py @@ -0,0 +1,445 @@ +#!/usr/bin/env python3 +"""Summarize the Phase 3 four-modality causal matrix.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import Iterable + +import numpy as np + + +SEEDS = (20260716, 20260717, 20260718) +MODALITIES = ("M0", "M1", "M2", "M3") +CHECKPOINT_ROLES = ( + "step_025k", "step_050k", "step_075k", "step_100k", + "best_absolute", "best_z", "final", +) +FRAME_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "wrong_side_preference", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", +) +REPORT_METRICS = FRAME_METRICS + TEMPORAL_METRICS +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", +) +FRAME_KEY = ( + "clip_index", "time_index", "take", "subject", "sequence", + "frame_id", "side", "annotation_valid", "annotation_state", +) +TEMPORAL_KEY = ( + "clip_index", "transition_index", "take", "subject", "sequence", + "frame_id_from", "frame_id_to", "side", +) +CONTRASTS = ( + ("K_without_depth", {"M1": 1.0, "M0": -1.0}), + ("K_with_depth", {"M3": 1.0, "M2": -1.0}), + ("Depth_without_K", {"M2": 1.0, "M0": -1.0}), + ("Depth_with_K", {"M3": 1.0, "M1": -1.0}), + ("Depth_K_interaction", {"M3": 1.0, "M2": -1.0, "M1": -1.0, "M0": 1.0}), +) +SUBGROUPS = ( + ("side", "left"), ("side", "right"), + ("hand_size_bucket", "small"), ("hand_size_bucket", "medium"), + ("hand_size_bucket", "large"), + ("depth_bucket", "near"), ("depth_bucket", "middle"), + ("depth_bucket", "far"), +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: Iterable[dict[str, object]]) -> None: + rows = list(rows) + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fieldnames = list(rows[0]) + if any(list(row) != fieldnames for row in rows): + raise ValueError(f"inconsistent CSV fields for {path}") + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: str | None) -> float | None: + if value is None or value == "": + return None + result = float(value) + return result if math.isfinite(result) else None + + +def run_name(modality: str, seed: int) -> str: + prefix = "core" if modality in {"M0", "M3"} else "modality" + return f"{prefix}_{modality.lower()}_l1_t1_s{seed}" + + +def load_report(path: Path, modality: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != modality + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal modality evaluation: {path}") + return report + + +def metric_mean(report: dict, name: str) -> float | None: + entry = report["metrics"].get(name) + if entry is not None: + return entry.get("mean") + if name in {"translation_x_mae_mm", "translation_y_mae_mm"}: + components = [report["metrics"][f"{side}_{name}"] for side in ("left", "right")] + count = sum(int(component["count"]) for component in components) + if count: + return sum( + float(component["mean"]) * int(component["count"]) + for component in components + ) / count + return None + + +def attention_mean(report: dict, name: str) -> float | None: + entry = report["attention"].get(name) + return None if entry is None else entry.get("mean") + + +def bootstrap(values: np.ndarray, seed: int, samples: int) -> tuple[float, float]: + if values.ndim != 1 or values.size == 0: + raise ValueError("bootstrap values must be a non-empty vector") + rng = np.random.default_rng(seed) + indices = rng.integers(0, values.size, size=(samples, values.size)) + means = values[indices].mean(axis=1) + return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5)) + + +def contrast_take_differences( + rows_by_modality: dict[str, list[dict[str, str]]], + metric: str, + coefficients: dict[str, float], + observation_key: tuple[str, ...], + subgroup: tuple[str, str] | None = None, +) -> dict[str, object]: + modalities = tuple(coefficients) + reference_rows = rows_by_modality[modalities[0]] + if any(len(rows_by_modality[modality]) != len(reference_rows) for modality in modalities[1:]): + raise ValueError("contrast evaluations have different observation counts") + take_values: dict[str, list[float]] = defaultdict(list) + observation_values = [] + for index, reference in enumerate(reference_rows): + aligned = [rows_by_modality[modality][index] for modality in modalities] + if any( + any(row[key] != reference[key] for key in observation_key) + for row in aligned[1:] + ): + raise ValueError("contrast evaluations do not have identical observation order") + if subgroup is not None and reference.get(subgroup[0]) != subgroup[1]: + continue + values = [optional_float(row.get(metric)) for row in aligned] + if any(value is None for value in values): + continue + difference = sum( + coefficients[modality] * float(value) + for modality, value in zip(modalities, values, strict=True) + ) + take_values[reference["take"]].append(difference) + observation_values.append(difference) + if not take_values: + raise ValueError(f"no paired values for metric={metric}, subgroup={subgroup}") + return { + "take_means": { + take: float(np.mean(values, dtype=np.float64)) + for take, values in sorted(take_values.items()) + }, + "observation_mean": float(np.mean(observation_values, dtype=np.float64)), + "observation_count": len(observation_values), + } + + +def aggregate_seed_contrasts( + seed_results: list[dict[str, object]], seed: int, samples: int, +) -> dict[str, object]: + common_takes = set(seed_results[0]["take_means"]) + for result in seed_results[1:]: + common_takes &= set(result["take_means"]) + if not common_takes: + raise ValueError("seed contrasts have no common takes") + take_values = np.asarray([ + np.mean([result["take_means"][take] for result in seed_results]) + for take in sorted(common_takes) + ], dtype=np.float64) + ci_low, ci_high = bootstrap(take_values, seed, samples) + seed_deltas = [float(np.mean(list(result["take_means"].values()))) for result in seed_results] + return { + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "frame_weighted_delta_mean": float(np.mean([ + result["observation_mean"] for result in seed_results + ])), + "take_count": len(common_takes), + "observations_per_seed": int(seed_results[0]["observation_count"]), + "bootstrap_samples": samples, + "bootstrap_seed": seed, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--modality-run-root", type=Path, default=Path("artifacts/phase3/modality_runs")) + parser.add_argument("--core-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--modality-evaluation-root", type=Path, default=Path("artifacts/phase3/modality_full_validation")) + parser.add_argument("--core-temporal-root", type=Path, default=Path("artifacts/phase3/core_temporal_validation_v2")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + all_rows = [] + best_rows = [] + checkpoints: dict[str, dict[str, object]] = {} + collected_bootstrap = [] + for modality in MODALITIES: + evaluation_root = args.core_evaluation_root if modality in {"M0", "M3"} else args.modality_evaluation_root + run_root = args.core_run_root if modality in {"M0", "M3"} else args.modality_run_root + for seed in SEEDS: + name = run_name(modality, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal training run: {name}") + checkpoint_record = { + "modality": modality, "layout": "L1", "temporal": "T1", + "seed": seed, "roles": {}, + } + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, modality, seed) + reports[(modality, seed, role)] = (path, report) + row: dict[str, object] = { + "run": name, "modality": modality, "layout": "L1", "temporal": "T1", + "seed": seed, "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "temporal_normalized_entropy": attention_mean(report, "temporal_normalized_entropy"), + "temporal_diagonal": attention_mean(report, "temporal_diagonal"), + "depth_fusion_gate": attention_mean(report, "depth_fusion_gate"), + "depth_fusion_gate_raw": attention_mean(report, "depth_fusion_gate_raw"), + "rgb_update_norm": attention_mean(report, "rgb_update_norm"), + "depth_update_norm": attention_mean(report, "depth_update_norm"), + "gated_depth_update_norm": attention_mean(report, "gated_depth_update_norm"), + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + collected_bootstrap.extend({ + "run": name, "modality": modality, "seed": seed, + "checkpoint_role": role, **bootstrap_row, + } for bootstrap_row in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(all_rows) != 84 or len(best_rows) != 12: + raise ValueError(f"expected 84 checkpoint rows and 12 best rows, got {len(all_rows)}, {len(best_rows)}") + write_csv(args.output_dir / "modality_checkpoint_comparison.csv", all_rows) + write_csv(args.output_dir / "modality_comparison.csv", best_rows) + write_csv(args.output_dir / "modality_bootstrap_ci.csv", collected_bootstrap) + (args.output_dir / "modality_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for modality in MODALITIES: + group = [row for row in best_rows if row["modality"] == modality] + if len(group) != 3: + raise ValueError(f"expected three seeds for {modality}, got {len(group)}") + record: dict[str, object] = {"modality": modality, "layout": "L1", "temporal": "T1"} + for metric in REPORT_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + } + aggregate.append(record) + + frame_cache: dict[tuple[str, int], list[dict[str, str]]] = {} + temporal_cache: dict[tuple[str, int], list[dict[str, str]]] = {} + for modality in MODALITIES: + for seed in SEEDS: + report_path, _ = reports[(modality, seed, "best_absolute")] + frame_cache[(modality, seed)] = read_csv(report_path.parent / "per_hand_frame_metrics.csv") + temporal_root = args.core_temporal_root if modality in {"M0", "M3"} else args.modality_evaluation_root + temporal_cache[(modality, seed)] = read_csv( + temporal_root / run_name(modality, seed) / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for contrast, coefficients in CONTRASTS: + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {modality: frame_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "metric": metric, + "delta_definition": "contrast_delta_lower_is_better_except_interaction_is_additivity_residual", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_bootstrap_ci.csv", paired_rows) + + subgroup_rows = [] + unavailable_subgroups: set[tuple[str, str]] = set() + for contrast, coefficients in CONTRASTS[:4]: + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "subgroup_axis": subgroup[0], "subgroup": subgroup[1], "metric": metric, + "delta_definition": "contrast_delta_lower_is_better", + } + try: + seed_results = [ + contrast_take_differences( + {modality: frame_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, FRAME_KEY, subgroup, + ) + for seed in SEEDS + ] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable_subgroups.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, + "take_equal_mean_delta": None, "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, "seed_20260717_delta": None, + "seed_20260718_delta": None, "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_subgroup_ci.csv", subgroup_rows) + + temporal_rows = [] + for contrast, coefficients in CONTRASTS: + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {modality: temporal_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "metric": metric, + "delta_definition": "contrast_delta_lower_is_better_except_interaction_is_additivity_residual", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "formal_validation_clips_per_run": 1495, + "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "causal_contrasts": { + "paired_frame": str((args.output_dir / "paired_modality_bootstrap_ci.csv").resolve()), + "paired_subgroups": str((args.output_dir / "paired_modality_subgroup_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_modality_temporal_ci.csv").resolve()), + "definition": "Within each seed and observation, apply the registered modality contrast; average within take, average seeds within take, then bootstrap equal-weight take means.", + "unavailable_subgroups": [ + {"axis": axis, "value": value} + for axis, value in sorted(unavailable_subgroups) + ], + }, + "source_hashes": { + "core_validation_launcher": sha256(args.core_evaluation_root / "launcher_provenance.json"), + "modality_validation_launcher": sha256(args.modality_evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "modality_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(all_rows), + "best_absolute_runs": len(best_rows), "paired_rows": len(paired_rows), + "subgroup_rows": len(subgroup_rows), "temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_photometric.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_photometric.py new file mode 100644 index 0000000000000000000000000000000000000000..a6cef761d482c983cc6ad19adc664c7f0754d534 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_photometric.py @@ -0,0 +1,467 @@ +#!/usr/bin/env python3 +"""Summarize the paired Phase 3 photometric augmentation experiment.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) + + +TRAINING_COMMIT = "239b0bf8850dd5533d3b3f4236cf856b4e826af6" +VARIANTS = ("off", "on") +DIAGNOSTICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", +) +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", "translation_z_mae_mm", +) +SCIENTIFIC_LOG_EXCLUSIONS = { + "timestamp", "frames_per_s", "peak_vram_gib", "photometric_augmentation", +} + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown photometric variant: {variant}") + return f"photometric_{variant}_geometry_m3_l1_t1_r640x368_s{seed}" + + +def reference_run_name(seed: int) -> str: + return f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + augmentation = config.get("data", {}).get("photometric_augmentation", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "photometric_augmentation" + or experiment.get("variant") != f"photometric_{variant}_r640x368" + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or bool(augmentation.get("enabled")) != (variant == "on") + or int(config["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid formal photometric evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def canonical_scientific_record(record: dict) -> bytes: + filtered = { + key: value for key, value in record.items() + if key not in SCIENTIFIC_LOG_EXCLUSIONS + } + return json.dumps( + filtered, sort_keys=True, separators=(",", ":"), allow_nan=False, + ).encode("utf-8") + + +def audit_off_reference(off_path: Path, reference_path: Path) -> dict: + digest = hashlib.sha256() + compared = 0 + with off_path.open(encoding="utf-8") as off_handle, reference_path.open( + encoding="utf-8" + ) as reference_handle: + for compared, (off_line, reference_line) in enumerate( + zip(off_handle, reference_handle, strict=True), start=1, + ): + off_record = canonical_scientific_record(json.loads(off_line)) + reference_record = canonical_scientific_record(json.loads(reference_line)) + if off_record != reference_record: + raise ValueError( + f"off/reference scientific trajectory differs at record {compared}" + ) + digest.update(off_record) + digest.update(b"\n") + if compared != 100_000: + raise ValueError(f"expected 100000 compared records, got {compared}") + return { + "records": compared, "scientific_fields_exact": True, + "canonical_sha256": digest.hexdigest(), + } + + +def augmentation_statistics(path: Path, variant: str) -> dict: + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + if len(rows) != 100_000: + raise ValueError(f"expected 100000 augmentation records: {path}") + diagnostics = [row.get("photometric_augmentation") for row in rows] + if any(item is None for item in diagnostics): + raise ValueError(f"missing photometric diagnostics: {path}") + applied = np.asarray([float(item["applied_fraction"]) for item in diagnostics]) + if np.any((applied < 0.0) | (applied > 1.0)): + raise ValueError(f"invalid applied fraction: {path}") + expected_identity = variant == "off" + factor_limits = { + "brightness_mean": (0.8, 1.2), + "contrast_mean": (0.8, 1.2), + "saturation_mean": (0.8, 1.2), + "hue_mean": (-0.05, 0.05), + } + factor_stats = {} + for key, (low, high) in factor_limits.items(): + values = np.asarray([float(item[key]) for item in diagnostics]) + if expected_identity: + identity = 0.0 if key == "hue_mean" else 1.0 + if not np.all(values == identity): + raise ValueError(f"off run has non-identity {key}: {path}") + if np.any((values < low - 1e-7) | (values > high + 1e-7)): + raise ValueError(f"{key} outside registered range: {path}") + factor_stats[key] = { + "mean": float(values.mean()), "min": float(values.min()), + "max": float(values.max()), + } + if expected_identity and np.any(applied != 0.0): + raise ValueError(f"off run reports applied augmentation: {path}") + return { + "records": len(rows), "applied_fraction_mean": float(applied.mean()), + "factors": factor_stats, + } + + +def load_resume_audit(path: Path, variant: str) -> dict: + audit = json.loads(path.read_text(encoding="utf-8")) + expected_names = {run_name(variant, seed) for seed in SEEDS} + records = audit.get("runs", []) + if ( + audit.get("status") != "passed" + or audit.get("official_test_used") is not False + or {record.get("run") for record in records} != expected_names + or any( + record.get("reference_step") != 100_000 + or record.get("resumed_step") != 100_000 + or not all( + record.get(key) is True for key in ( + "model_exact", "optimizer_exact", "python_rng_exact", + "numpy_rng_exact", "torch_rng_exact", "cuda_rng_exact", + ) + ) + for record in records + ) + ): + raise ValueError(f"invalid {variant} exact-resume audit: {path}") + return { + "status": "passed", "variant": variant, "runs": len(records), + "path": str(path.resolve()), "sha256": sha256(path), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--run-root", type=Path, + default=Path("artifacts/phase3/photometric_runs_commit239b0bf"), + ) + parser.add_argument( + "--evaluation-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--off-reference-root", type=Path, + default=Path("artifacts/phase3/resolution_640_runs_attempt2_commit7583772"), + ) + parser.add_argument( + "--off-resume-root", type=Path, + default=Path("artifacts/phase3/photometric_resume_from75k"), + ) + parser.add_argument( + "--on-resume-root", type=Path, + default=Path("artifacts/phase3/photometric_on_resume_from75k"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("artifacts/phase3/reports"), + ) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + resume_audits = { + variant: load_resume_audit( + ( + args.off_resume_root if variant == "off" + else args.on_resume_root + ) / "exact_resume_audit.json", + variant, + ) + for variant in VARIANTS + } + + reports: dict[tuple[str, int, str], Path] = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + training_audit = {} + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + run_dir = args.run_root / name + summary = json.loads((run_dir / "summary.json").read_text(encoding="utf-8")) + provenance = json.loads( + (run_dir / "run_provenance.json").read_text(encoding="utf-8") + ) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid photometric training run: {name}") + training_audit[name] = { + "variant": variant, "seed": seed, + "augmentation": augmentation_statistics( + run_dir / "train_metrics.jsonl", variant, + ), + } + if variant == "off": + training_audit[name]["e1_reference"] = audit_off_reference( + run_dir / "train_metrics.jsonl", + args.off_reference_root / reference_run_name(seed) / "train_metrics.jsonl", + ) + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = args.evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("photometric matrix is incomplete") + write_csv(args.output_dir / "photometric_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "photometric_comparison.csv", best_rows) + write_csv(args.output_dir / "photometric_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "photometric_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + (args.output_dir / "photometric_training_audit.json").write_text( + json.dumps({"status": "passed", "runs": training_audit}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + joint_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv( + parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + joint_cache[(variant, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in read_csv(parent / "per_joint_metrics.csv") + } + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + return contrast_take_differences( + {"off": cache[("off", seed)], "on": cache[("on", seed)]}, + metric, {"off": -1.0, "on": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in FRAME_METRICS: + results = [paired(metric, seed) for seed in SEEDS] + paired_rows.append({ + "comparison": "on-off", "metric": metric, + "delta_definition": "augmentation on minus off; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [paired(metric, seed, temporal=True) for seed in SEEDS] + temporal_rows.append({ + "comparison": "on-off", "metric": metric, + "delta_definition": "augmentation on minus off; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + unavailable = set() + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": "on-off", "subgroup_axis": subgroup[0], + "subgroup_value": subgroup[1], "metric": metric, + "bucket_source": "aligned augmentation-off reference rows", + "delta_definition": "augmentation on minus off; lower is better", + } + try: + results = [paired(metric, seed, subgroup=subgroup) for seed in SEEDS] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, "seed_delta_mean": None, + "seed_delta_sample_std": None, "seed_20260716_delta": None, + "seed_20260717_delta": None, "seed_20260718_delta": None, + "frame_weighted_delta_mean": None, "take_count": 0, + "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + for side in ("left", "right"): + for joint_index in range(21): + off = np.asarray([ + joint_cache[("off", seed)][(side, joint_index)] for seed in SEEDS + ]) + on = np.asarray([ + joint_cache[("on", seed)][(side, joint_index)] for seed in SEEDS + ]) + delta = on - off + joint_rows.append({ + "side": side, "joint_index": joint_index, + "off_seed_mean_mm": float(off.mean()), + "off_seed_sample_std_mm": float(off.std(ddof=1)), + "on_seed_mean_mm": float(on.mean()), + "on_seed_sample_std_mm": float(on.std(ddof=1)), + "on_minus_off_seed_mean_mm": float(delta.mean()), + "on_minus_off_seed_sample_std_mm": float(delta.std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "photometric_per_joint_comparison.csv", joint_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_photometric_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_photometric_temporal_ci.csv").resolve() + ), + "paired_subgroups": str( + (args.output_dir / "paired_photometric_subgroup_ci.csv").resolve() + ), + "per_joint": str( + (args.output_dir / "photometric_per_joint_comparison.csv").resolve() + ), + "training_audit": str( + (args.output_dir / "photometric_training_audit.json").resolve() + ), + "exact_resume": { + "status": "passed", "runs": sum( + audit["runs"] for audit in resume_audits.values() + ), + "variants": resume_audits, + }, + "unavailable_subgroups": [ + {"axis": axis, "value": value} for axis, value in sorted(unavailable) + ], + "source_hashes": { + "training_launcher": sha256(args.run_root / "launcher_provenance.json"), + "validation_launcher": sha256( + args.evaluation_root / "launcher_provenance.json" + ), + }, + } + (args.output_dir / "photometric_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "per_joint_rows": len(joint_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_photometric_fallback.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_photometric_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..e865911f92e2e957592fba42b7916a5421d6348b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_photometric_fallback.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Summarize missing-modality behavior for the final photometric candidate.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from scripts.summarize_phase3_photometric import DIAGNOSTICS, VARIANTS, run_name +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from summarize_phase3_photometric import DIAGNOSTICS, VARIANTS, run_name + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + augmentation = config.get("data", {}).get("photometric_augmentation", {}) + override = report.get("inference_modality_override", {}) + expected_depth, expected_k = CONDITIONS[condition] + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "photometric_augmentation" + or experiment.get("variant") != f"photometric_{variant}_r640x368" + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or bool(augmentation.get("enabled")) != (variant == "on") + or int(config["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid photometric fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--complete-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--fallback-root", type=Path, + default=Path("artifacts/phase3/photometric_fallback_validation"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("artifacts/phase3/reports"), + ) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + root = args.complete_root if condition == "complete" else args.fallback_root / condition + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 24: + raise ValueError(f"expected 24 complete/fallback rows, got {len(rows)}") + write_csv(args.output_dir / "photometric_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + } + aggregate.append(record) + + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + contrasts.append(( + f"{condition}:on-off", (condition, "on"), (condition, "off"), + )) + + paired_rows = [] + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_fallback_ci.csv", paired_rows) + write_csv( + args.output_dir / "paired_photometric_fallback_temporal_ci.csv", temporal_rows, + ) + + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + equality.append({ + "variant": variant, "seed": seed, + "frame_rows_identical": ( + frame_cache[("drop_k", variant, seed)] + == frame_cache[("drop_both", variant, seed)] + ), + "temporal_rows_identical": ( + temporal_cache[("drop_k", variant, seed)] + == temporal_cache[("drop_both", variant, seed)] + ), + }) + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "geometry_k_dependency": ( + "When K is unavailable, ray conditioning and XYZ/logZ geometry are disabled; " + "drop_k and drop_both are therefore expected to be identical." + ), + } + output = args.output_dir / "photometric_fallback_comparison.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all( + row["frame_rows_identical"] and row["temporal_rows_identical"] + for row in equality + ), + "output": str(output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_resolution.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..669c9bad9451479da904b1d35b1873d764686a56 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_resolution.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Summarize the paired Phase 3 512x288 versus 640x368 resolution study.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) + + +TRAINING_COMMIT = "75837726f7eb8232b747932cbf536a834821e24d" +VARIANTS = ("r512x288", "r640x368") +RESOLUTIONS = {"r512x288": (288, 512), "r640x368": (368, 640)} +NORMALIZED_2D_METRICS = ( + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", +) +PAIRED_FRAME_METRICS = FRAME_METRICS + tuple( + f"{metric}_at_512_width" for metric in NORMALIZED_2D_METRICS +) +DIAGNOSTICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", +) + + +def run_name(variant: str, seed: int) -> str: + if variant == "r512x288": + return f"depth_dropout005_geometry_m3_l1_t1_s{seed}" + if variant == "r640x368": + return f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + raise ValueError(f"unknown resolution variant: {variant}") + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + expected_matrix = ( + "depth_modality_dropout_dose" if variant == "r512x288" else "resolution" + ) + expected_variant = ( + "dropout005_geometry" + if variant == "r512x288" else "dropout005_geometry_r640x368" + ) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != expected_matrix + or experiment.get("variant") != expected_variant + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(report["config"]["data"]["resolution_hw"]) != RESOLUTIONS[variant] + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid formal resolution evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def add_normalized_2d_columns( + rows: list[dict[str, str]], variant: str, +) -> list[dict[str, str]]: + scale = 512.0 / RESOLUTIONS[variant][1] + output = [] + for row in rows: + adapted = dict(row) + for metric in NORMALIZED_2D_METRICS: + value = adapted.get(metric) + adapted[f"{metric}_at_512_width"] = ( + "" if value in {None, ""} else str(float(value) * scale) + ) + output.append(adapted) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--reference-run-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_runs_commit7583772"), + ) + parser.add_argument( + "--candidate-run-root", type=Path, + default=Path("artifacts/phase3/resolution_640_runs_attempt2_commit7583772"), + ) + parser.add_argument( + "--reference-evaluation-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument( + "--candidate-evaluation-root", type=Path, + default=Path("artifacts/phase3/resolution_640_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], Path] = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + for variant in VARIANTS: + run_root = ( + args.reference_run_root if variant == "r512x288" + else args.candidate_run_root + ) + evaluation_root = ( + args.reference_evaluation_root if variant == "r512x288" + else args.candidate_evaluation_root + ) + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text()) + provenance = json.loads((run_root / name / "run_provenance.json").read_text()) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid resolution training run: {name}") + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "resolution_h": RESOLUTIONS[variant][0], + "resolution_w": RESOLUTIONS[variant][1], + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in NORMALIZED_2D_METRICS: + value = row[metric] + row[f"{metric}_at_512_width"] = ( + None if value is None else value * 512.0 / RESOLUTIONS[variant][1] + ) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("resolution matrix is incomplete") + write_csv(args.output_dir / "resolution_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "resolution_comparison.csv", best_rows) + write_csv(args.output_dir / "resolution_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "resolution_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n" + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + PAIRED_FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = add_normalized_2d_columns( + read_csv(parent / "per_hand_frame_metrics.csv"), variant, + ) + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + # Reference is inserted first so subgroup membership always comes from + # the fixed 512x288 evaluation rather than changing with resolution. + return contrast_take_differences( + { + "reference": cache[("r512x288", seed)], + "candidate": cache[("r640x368", seed)], + }, + metric, {"reference": -1.0, "candidate": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in PAIRED_FRAME_METRICS: + results = [paired(metric, seed) for seed in SEEDS] + paired_rows.append({ + "comparison": "r640x368-r512x288", "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [paired(metric, seed, temporal=True) for seed in SEEDS] + temporal_rows.append({ + "comparison": "r640x368-r512x288", "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + unavailable = set() + subgroup_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px_at_512_width", "fingertip_mpjpe_mm", + "translation_z_mae_mm", + ) + for subgroup in SUBGROUPS: + for metric in subgroup_metrics: + prefix = { + "comparison": "r640x368-r512x288", + "subgroup_axis": subgroup[0], "subgroup_value": subgroup[1], + "metric": metric, + "bucket_source": "r512x288 reference rows", + "delta_definition": "candidate minus reference; lower is better", + } + try: + results = [paired(metric, seed, subgroup=subgroup) for seed in SEEDS] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, "seed_20260717_delta": None, + "seed_20260718_delta": None, "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + joint_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + rows = read_csv(parent / "per_joint_metrics.csv") + joint_cache[(variant, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in rows + } + for side in ("left", "right"): + for joint_index in range(21): + reference = np.array([ + joint_cache[("r512x288", seed)][(side, joint_index)] for seed in SEEDS + ]) + candidate = np.array([ + joint_cache[("r640x368", seed)][(side, joint_index)] for seed in SEEDS + ]) + delta = candidate - reference + joint_rows.append({ + "side": side, "joint_index": joint_index, + "r512x288_seed_mean_mm": float(reference.mean()), + "r512x288_seed_sample_std_mm": float(reference.std(ddof=1)), + "r640x368_seed_mean_mm": float(candidate.mean()), + "r640x368_seed_sample_std_mm": float(candidate.std(ddof=1)), + "candidate_minus_reference_seed_mean_mm": float(delta.mean()), + "candidate_minus_reference_seed_sample_std_mm": float(delta.std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "resolution_per_joint_comparison.csv", joint_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "evaluation_contract": { + "raw_2d": "processed-input pixels, retained for audit", + "normalized_2d": "640 metrics multiplied by 512/640; 512 unchanged", + "subgroup_membership": "always inherited from aligned r512x288 reference rows", + }, + "paired_frame": str((args.output_dir / "paired_resolution_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_resolution_temporal_ci.csv").resolve() + ), + "paired_subgroups": str( + (args.output_dir / "paired_resolution_subgroup_ci.csv").resolve() + ), + "per_joint": str( + (args.output_dir / "resolution_per_joint_comparison.csv").resolve() + ), + "unavailable_subgroups": [ + {"axis": axis, "value": value} for axis, value in sorted(unavailable) + ], + "source_hashes": { + "reference_validation_launcher": sha256( + args.reference_evaluation_root / "launcher_provenance_sixth.json" + ), + "candidate_training_launcher": sha256( + args.candidate_run_root / "launcher_provenance.json" + ), + }, + } + (args.output_dir / "resolution_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "per_joint_rows": len(joint_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_temporal_position.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_temporal_position.py new file mode 100644 index 0000000000000000000000000000000000000000..a85351446385b326384584b1928ed219e889d36c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase3_temporal_position.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python3 +"""Summarize the Phase 3 P0/P1 temporal-position experiment.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + REPORT_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + sha256, + write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + REPORT_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + sha256, + write_csv, + ) + + +POSITIONS = ("P0", "P1") +ATTENTION_METRICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", +) + + +def position_run_name(position: str, seed: int) -> str: + if position == "P0": + return f"core_m3_l1_t1_s{seed}" + if position == "P1": + return f"temporal_p1_m3_l1_t1_s{seed}" + raise ValueError(f"unknown temporal position: {position}") + + +def load_report(path: Path, position: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + observed_position = experiment.get("position", "P0") + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or observed_position != position + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal temporal-position evaluation: {path}") + return report + + +def flatten_bias_report(position: str, seed: int, report: dict) -> list[dict[str, object]]: + rows = [] + bias_report = report["temporal_position_bias"] + for layer in bias_report["layers"]: + offsets = layer["offsets_key_minus_query"] + for head, values in enumerate(layer["per_head_bias"]): + for offset, value in zip(offsets, values, strict=True): + rows.append({ + "position": position, "seed": seed, "layer": int(layer["layer"]), + "head": head, "offset_key_minus_query": int(offset), "bias": float(value), + }) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--p0-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--p1-run-root", type=Path, default=Path("artifacts/phase3/temporal_position_runs")) + parser.add_argument("--p0-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--p1-evaluation-root", type=Path, default=Path("artifacts/phase3/temporal_position_full_validation")) + parser.add_argument("--p0-diagnostic-root", type=Path, default=Path("artifacts/phase3/temporal_position_p0_diagnostics")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + diagnostics: dict[tuple[str, int], tuple[Path, dict]] = {} + all_rows = [] + best_rows = [] + checkpoints = {} + for position in POSITIONS: + run_root = args.p0_run_root if position == "P0" else args.p1_run_root + evaluation_root = args.p0_evaluation_root if position == "P0" else args.p1_evaluation_root + for seed in SEEDS: + name = position_run_name(position, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal training run: {name}") + checkpoint_record = {"position": position, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, position, seed) + reports[(position, seed, role)] = (path, report) + row: dict[str, object] = { + "run": name, "position": position, "seed": seed, + "checkpoint_role": role, "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), "evaluation": str(path.resolve()), + } + + diagnostic_path = ( + args.p0_diagnostic_root / name / "best_absolute" / "evaluation.json" + if position == "P0" + else args.p1_evaluation_root / name / "best_absolute" / "evaluation.json" + ) + diagnostic = load_report(diagnostic_path, position, seed) + formal_best = reports[(position, seed, "best_absolute")][1] + for metric in REPORT_METRICS: + if metric_mean(diagnostic, metric) != metric_mean(formal_best, metric): + raise ValueError(f"diagnostic metric drift for {name}: {metric}") + diagnostics[(position, seed)] = (diagnostic_path, diagnostic) + + if len(all_rows) != 42 or len(best_rows) != 6: + raise ValueError(f"expected 42 checkpoint rows and 6 best rows, got {len(all_rows)}, {len(best_rows)}") + write_csv(args.output_dir / "temporal_position_checkpoint_comparison.csv", all_rows) + + for row in best_rows: + diagnostic = diagnostics[(str(row["position"]), int(row["seed"]))][1] + for metric in ATTENTION_METRICS: + row[metric] = attention_mean(diagnostic, metric) + write_csv(args.output_dir / "temporal_position_comparison.csv", best_rows) + (args.output_dir / "temporal_position_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for position in POSITIONS: + group = [row for row in best_rows if row["position"] == position] + record: dict[str, object] = {"position": position, "seeds": list(SEEDS)} + for metric in REPORT_METRICS + ATTENTION_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("trainable_parameters", "peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + } + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + attention_distance_rows = [] + bias_rows = [] + for position in POSITIONS: + for seed in SEEDS: + path, report = diagnostics[(position, seed)] + frame_cache[(position, seed)] = read_csv(path.parent / "per_hand_frame_metrics.csv") + temporal_cache[(position, seed)] = read_csv(path.parent / "per_temporal_transition_metrics.csv") + for distance_mode, report_key in ( + ("absolute", "temporal_attention_by_absolute_frame_distance"), + ("signed_key_minus_query", "temporal_attention_by_signed_frame_distance"), + ): + for distance, distribution in report["attention"][report_key].items(): + attention_distance_rows.append({ + "position": position, "seed": seed, "distance_mode": distance_mode, + "distance": int(distance), **distribution, + }) + bias_rows.extend(flatten_bias_report(position, seed, report)) + write_csv(args.output_dir / "temporal_position_attention_by_distance.csv", attention_distance_rows) + if not bias_rows: + raise ValueError("P1 diagnostic evaluations did not export relative-position bias") + write_csv(args.output_dir / "temporal_position_bias.csv", bias_rows) + + grouped_bias: dict[tuple[int, int, int], list[float]] = {} + for row in bias_rows: + key = (int(row["layer"]), int(row["head"]), int(row["offset_key_minus_query"])) + grouped_bias.setdefault(key, []).append(float(row["bias"])) + bias_aggregate_rows = [{ + "position": "P1", "layer": layer, "head": head, "offset_key_minus_query": offset, + "seed_mean_bias": float(np.mean(values)), + "seed_sample_std_bias": float(np.std(values, ddof=1)), + "seed_20260716_bias": values[0], "seed_20260717_bias": values[1], + "seed_20260718_bias": values[2], + } for (layer, head, offset), values in sorted(grouped_bias.items())] + write_csv(args.output_dir / "temporal_position_bias_aggregate.csv", bias_aggregate_rows) + + paired_rows = [] + coefficients = {"P1": 1.0, "P0": -1.0} + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {position: frame_cache[(position, seed)] for position in POSITIONS}, + metric, coefficients, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": "P1_minus_P0", "metric": metric, + "delta_definition": "P1_minus_P0_lower_is_better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_temporal_position_bootstrap_ci.csv", paired_rows) + + paired_temporal_rows = [] + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {position: temporal_cache[(position, seed)] for position in POSITIONS}, + metric, coefficients, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + paired_temporal_rows.append({ + "comparison": "P1_minus_P0", "metric": metric, + "delta_definition": "P1_minus_P0_lower_is_better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_temporal_position_temporal_ci.csv", paired_temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_temporal_position_bootstrap_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_temporal_position_temporal_ci.csv").resolve()), + "attention_distance": str((args.output_dir / "temporal_position_attention_by_distance.csv").resolve()), + "bias_aggregate": str((args.output_dir / "temporal_position_bias_aggregate.csv").resolve()), + "source_hashes": { + "p0_diagnostic_launcher": sha256(args.p0_diagnostic_root / "launcher_provenance.json"), + "p1_validation_launcher": sha256(args.p1_evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "temporal_position_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "paired_rows": len(paired_rows), "paired_temporal_rows": len(paired_temporal_rows), + "bias_rows": len(bias_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_a1.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_a1.py new file mode 100644 index 0000000000000000000000000000000000000000..72611727f8c8853380b2b3d4d31e8389d70b79e3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_a1.py @@ -0,0 +1,359 @@ +#!/usr/bin/env python3 +"""Aggregate the three frozen-checkpoint Phase 4 A1 oracle diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary + +if __package__: + from scripts.fit_phase4_oracle_local_depth import paired_take_bootstrap +else: + from fit_phase4_oracle_local_depth import paired_take_bootstrap + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = ("coarse", "control", "local") +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", +) +STABLE_FIELDS = ( + "sample_index", + "clip_index", + "time_index", + "take", + "subject", + "sequence", + "frame_id", + "side", + "side_index", + "action_family", + "action_label", + "action_name", + "hand_size_px", + "wrist_depth_m", + "bimanual_size_ratio", + "bimanual_depth_gap_m", + "bimanual_asymmetry_bucket", + "local_depth_valid_fraction", + "local_depth_discontinuity_m", +) + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV {path}") + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_seed_results(root: Path) -> tuple[ + dict[int, list[dict[str, str]]], dict[int, dict[str, Any]], list[dict[str, str]] +]: + rows_by_seed: dict[int, list[dict[str, str]]] = {} + reports: dict[int, dict[str, Any]] = {} + reference: list[dict[str, str]] | None = None + for seed in SEEDS: + fit = root / f"seed_{seed}" / "fit" + rows = read_csv(fit / "validation_predictions.csv") + report = json.loads((fit / "results.json").read_text(encoding="utf-8")) + if report.get("official_test_used") is not False: + raise ValueError(f"seed {seed} did not preserve official-test isolation") + if reference is None: + reference = rows + else: + if len(rows) != len(reference): + raise ValueError("A1 seed validation row counts differ") + for index, (candidate, expected) in enumerate(zip(rows, reference, strict=True)): + for field in STABLE_FIELDS: + if candidate[field] != expected[field]: + raise ValueError( + f"A1 seed metadata mismatch at row {index}, field {field}" + ) + rows_by_seed[seed] = rows + reports[seed] = report + if reference is None: + raise ValueError("no A1 seed results found") + return rows_by_seed, reports, reference + + +def aggregate_predictions( + rows_by_seed: dict[int, list[dict[str, str]]], +) -> dict[str, dict[str, np.ndarray]]: + output: dict[str, dict[str, np.ndarray]] = {} + for variant in VARIANTS: + output[variant] = {} + for metric in METRICS: + per_seed = np.asarray([ + [float(row[f"{variant}_{metric}"]) for row in rows_by_seed[seed]] + for seed in SEEDS + ], dtype=np.float64) + output[variant][metric] = per_seed.mean(axis=0) + return output + + +def group_masks( + rows: list[dict[str, str]], challenge: dict[str, Any], +) -> dict[str, np.ndarray]: + farthest = float(challenge["thresholds"]["farthest_observed_wrist_depth_p80_m"]) + challenge_clips = {int(value) for value in challenge["clip_indices"]} + return { + "all": np.ones(len(rows), dtype=bool), + "left": np.asarray([row["side"] == "left" for row in rows]), + "right": np.asarray([row["side"] == "right" for row in rows]), + "small": np.asarray([float(row["hand_size_px"]) < 64.0 for row in rows]), + "farthest_observed": np.asarray([ + float(row["wrist_depth_m"]) >= farthest for row in rows + ]), + "strong_asymmetry": np.asarray([ + row["bimanual_asymmetry_bucket"] == "strong" for row in rows + ]), + "challenge": np.asarray([ + int(row["clip_index"]) in challenge_clips for row in rows + ]), + } + + +def aggregate_group_rows( + predictions: dict[str, dict[str, np.ndarray]], masks: dict[str, np.ndarray], +) -> list[dict[str, object]]: + rows: list[dict[str, object]] = [] + for group, mask in masks.items(): + for variant in VARIANTS: + for metric in METRICS: + rows.append({ + "group": group, + "variant": variant, + "metric": metric, + "seed_scope": "per-frame mean over seeds 20260716/17/18", + **distribution_summary(predictions[variant][metric][mask]), + }) + return rows + + +def find_value( + rows: list[dict[str, object]], group: str, variant: str, metric: str, statistic: str, +) -> float: + record = next( + row for row in rows + if row["group"] == group and row["variant"] == variant and row["metric"] == metric + ) + return float(record[statistic]) + + +def seed_summary_rows(reports: dict[int, dict[str, Any]]) -> list[dict[str, object]]: + rows = [] + for seed in SEEDS: + report = reports[seed] + reductions = report["gate"]["reductions_percent"] + rows.append({ + "seed": seed, + "checkpoint_step": report["frozen_checkpoint"]["step"], + "checkpoint_sha256": report["frozen_checkpoint"]["sha256"], + "formal_A1_gate_pass": report["gate"]["formal_A1_gate_pass"], + **reductions, + "control_best_epoch": min( + report["histories"]["control"], + key=lambda row: row["holdout_residual_mae_m"], + )["epoch"], + "local_best_epoch": min( + report["histories"]["local"], + key=lambda row: row["holdout_residual_mae_m"], + )["epoch"], + }) + return rows + + +def markdown_report( + report: dict[str, Any], group_rows: list[dict[str, object]], seed_rows: list[dict[str, object]], +) -> str: + gate = report["gate"] + lines = [ + "# Phase 4 A1 Oracle Local-Depth Diagnostic", + "", + "## Decision", + "", + f"- Formal gate: **{'PASS' if gate['formal_A1_gate_pass'] else 'FAIL'}**.", + f"- Action: **{gate['decision']}**.", + "- Official test used: no.", + "- A2 predicted-location diagnostic is not admitted when A1 fails the preregistered gate.", + "", + "## Three-Seed Aggregate", + "", + "| Metric / group | Coarse | Oracle-location control | Oracle local depth | Reduction vs coarse |", + "|---|---:|---:|---:|---:|", + ] + table_specs = ( + ("z P95 / all", "all", "translation_z_mae_mm", "p95"), + ("absolute MPJPE / all", "all", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / small", "small", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / farthest-observed", "farthest_observed", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / right", "right", "absolute_mpjpe_mm", "mean"), + ("projected MANO 2D / all", "all", "mano_projected_2d_error_px", "mean"), + ) + for label, group, metric, statistic in table_specs: + values = { + variant: find_value(group_rows, group, variant, metric, statistic) + for variant in VARIANTS + } + reduction = 100.0 * (values["coarse"] - values["local"]) / values["coarse"] + lines.append( + f"| {label} | {values['coarse']:.2f} | {values['control']:.2f} | " + f"{values['local']:.2f} | {reduction:.2f}% |" + ) + lines.extend(( + "", + "The aggregate uses the per-frame mean error over the three frozen Phase 3 checkpoints, matching the Phase 4 Wave 0 aggregation convention. The local-depth regressor improves the tail beyond the same-capacity oracle-location control, but the registered full-validation/far-small thresholds are not reached.", + "", + "## Seed Stability", + "", + "| Seed | z P95 reduction | Small absolute reduction | Farthest-observed absolute reduction | Gate | Local best epoch |", + "|---:|---:|---:|---:|---|---:|", + )) + for row in seed_rows: + lines.append( + f"| {row['seed']} | {row['full_validation_z_p95_percent']:.2f}% | " + f"{row['small_absolute_mpjpe_percent']:.2f}% | " + f"{row['farthest_observed_absolute_mpjpe_percent']:.2f}% | " + f"{'pass' if row['formal_A1_gate_pass'] else 'fail'} | {row['local_best_epoch']} |" + ) + lines.extend(( + "", + "Seed 20260718 is the limiting case: its train-only holdout selected epoch 1 and its local-depth gain over the frozen coarse output is small. This prevents a robust three-seed claim even though seeds 20260716 and 20260717 individually pass.", + "", + "## Interpretation", + "", + "- Engineering correctness is established: data/hash isolation, raw depth/K alignment, feature schema, bounded residual, and exact root-relative/direct-2D invariance all passed.", + "- Local depth contains useful information beyond oracle location alone, but the gain is checkpoint-dependent and narrowly misses the preregistered aggregate threshold.", + "- Per the Phase 4 stop rule, do not implement the deployable local-depth branch or A2 at this point. Shift the next metric-z effort to matched axis-aware loss and train-only balanced-sampling controls; A3 remains an independent appearance upper-bound diagnostic.", + "", + "## Sources", + "", + f"- Input root: `{report['input_root']}`", + f"- Aggregate table: `{report['outputs']['comparison_csv']}`", + f"- Take bootstrap: `{report['outputs']['paired_take_bootstrap_ci']}`", + )) + return "\n".join(lines) + "\n" + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--input-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument( + "--challenge-manifest", type=Path, + default=Path("artifacts/phase4/challenge_subset/official_val_challenge_128.json"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + rows_by_seed, reports, metadata = load_seed_results(args.input_root) + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + predictions = aggregate_predictions(rows_by_seed) + group_rows = aggregate_group_rows(predictions, group_masks(metadata, challenge)) + bootstrap_rows = paired_take_bootstrap( + metadata, + predictions, + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + seed_rows = seed_summary_rows(reports) + + coarse_z_p95 = find_value(group_rows, "all", "coarse", "translation_z_mae_mm", "p95") + local_z_p95 = find_value(group_rows, "all", "local", "translation_z_mae_mm", "p95") + reductions = { + "full_validation_z_p95_percent": 100.0 * (coarse_z_p95 - local_z_p95) / coarse_z_p95, + } + for group in ("small", "farthest_observed", "right"): + coarse = find_value(group_rows, group, "coarse", "absolute_mpjpe_mm", "mean") + local = find_value(group_rows, group, "local", "absolute_mpjpe_mm", "mean") + reductions[f"{group}_absolute_mpjpe_percent"] = 100.0 * (coarse - local) / coarse + metric_pass = ( + reductions["full_validation_z_p95_percent"] >= 20.0 + or reductions["small_absolute_mpjpe_percent"] >= 15.0 + or reductions["farthest_observed_absolute_mpjpe_percent"] >= 15.0 + ) + invariance_pass = all( + abs(find_value(group_rows, "all", "local", metric, "mean") + - find_value(group_rows, "all", "coarse", metric, "mean")) <= 1e-4 + for metric in ("root_relative_mpjpe_mm", "direct_2d_error_px") + ) + formal_pass = bool(metric_pass and invariance_pass) + output_csv = args.output_dir / "a1_oracle_local_depth_comparison.csv" + output_bootstrap = args.output_dir / "paired_take_bootstrap_ci.csv" + output_seed = args.output_dir / "a1_oracle_local_depth_seed_stability.csv" + output_json = args.output_dir / "A1_ORACLE_LOCAL_DEPTH.json" + output_md = args.output_dir / "A1_ORACLE_LOCAL_DEPTH.md" + report = { + "status": "complete", + "phase": 4, + "wave": "A1_oracle_local_depth", + "official_test_used": False, + "input_root": str(args.input_root.resolve()), + "seed_scope": list(SEEDS), + "aggregation": "per-frame mean error over three seeds, then distribution summary", + "checkpoint_rule": "Phase 3 fixed-subset tail-best-absolute per seed", + "gate": { + "formal_A1_gate_pass": formal_pass, + "metric_gate_pass": bool(metric_pass), + "invariance_gate_pass": bool(invariance_pass), + "decision": ( + "ADMIT_A2" if formal_pass + else "STOP_LOCAL_DEPTH_BRANCH_AND_SHIFT_TO_LOSS_SAMPLING_OR_BACKBONE_CONTROLS" + ), + "thresholds": { + "full_validation_z_p95_reduction_percent": 20.0, + "small_or_farthest_absolute_mpjpe_reduction_percent": 15.0, + "root_relative_and_direct_2d_max_degradation_percent": 2.0, + }, + "observed_reductions_percent": reductions, + }, + "seed_results": seed_rows, + "outputs": { + "comparison_csv": str(output_csv.resolve()), + "paired_take_bootstrap_ci": str(output_bootstrap.resolve()), + "seed_stability_csv": str(output_seed.resolve()), + "markdown": str(output_md.resolve()), + }, + } + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(output_csv, group_rows) + write_csv(output_bootstrap, bootstrap_rows) + write_csv(output_seed, seed_rows) + output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + output_md.write_text(markdown_report(report, group_rows, seed_rows), encoding="utf-8") + print(json.dumps({"status": "complete", "gate": report["gate"]}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_a3.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_a3.py new file mode 100644 index 0000000000000000000000000000000000000000..d41d5683a4d4ffc98d31e2e3e2bd85c042d499e2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_a3.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +"""Summarize A3 refined predictions against their exact frozen coarse outputs.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Mapping + +try: + from scripts.summarize_phase4_control import ( + RECONSTRUCTION_KEY, + RECONSTRUCTION_METADATA, + SEEDS, + aggregate_seed_rows, + assert_pair_alignment, + distribution_rows, + groups, + paired_take_bootstrap, + read_csv, + statistic, + write_csv, + ) +except ModuleNotFoundError: + from summarize_phase4_control import ( # type: ignore[no-redef] + RECONSTRUCTION_KEY, + RECONSTRUCTION_METADATA, + SEEDS, + aggregate_seed_rows, + assert_pair_alignment, + distribution_rows, + groups, + paired_take_bootstrap, + read_csv, + statistic, + write_csv, + ) + + +MODES = ("oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k") +METRIC_PAIRS = { + "absolute_mpjpe_mm": "coarse_absolute_mpjpe_mm", + "root_relative_mpjpe_mm": "coarse_root_relative_mpjpe_mm", + "absolute_mpvpe_mm": "coarse_absolute_mpvpe_mm", + "root_relative_mpvpe_mm": "coarse_root_relative_mpvpe_mm", + "fingertip_mpjpe_mm": "coarse_fingertip_mpjpe_mm", + "translation_z_mae_mm": "coarse_translation_z_mae_mm", +} +METRICS = tuple(METRIC_PAIRS) + + +def discover_evaluations(root: Path, role: str) -> dict[str, dict[int, Path]]: + output: dict[str, dict[int, Path]] = {mode: {} for mode in MODES} + for report_path in sorted(root.glob(f"*/{role}/evaluation.json")): + report = json.loads(report_path.read_text(encoding="utf-8")) + oracle = report.get("oracle_crop_refinement", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("clips") != 1495 + or report.get("phase4_diagnostics", {}).get("enabled") is not True + or oracle.get("enabled") is not True + or oracle.get("gt_location_at_inference") is not True + ): + raise ValueError(f"invalid complete A3 evaluation: {report_path}") + config = report["config"] + mode = config["experiment"]["oracle_crop_mode"] + seed = int(config["seed"]) + if mode not in output or seed in output[mode]: + raise ValueError(f"unexpected or duplicate A3 mode/seed: {mode}/{seed}") + if ( + oracle.get("coarse_checkpoint_sha256") + != config["experiment"]["coarse_checkpoint_sha256"] + ): + raise ValueError(f"coarse checkpoint identity missing: {report_path}") + output[mode][seed] = report_path.parent + for mode, records in output.items(): + if tuple(sorted(records)) != SEEDS: + raise ValueError( + f"expected seeds {SEEDS} for {mode}, found {tuple(sorted(records))}" + ) + return output + + +def coarse_rows(rows: list[dict[str, str]]) -> list[dict[str, object]]: + output = [] + for source in rows: + row: dict[str, object] = dict(source) + for metric, coarse_metric in METRIC_PAIRS.items(): + if coarse_metric not in source: + raise ValueError(f"missing A3 coarse metric {coarse_metric}") + row[metric] = source[coarse_metric] + output.append(row) + return output + + +def compute_gate( + coarse_absolute: float, + refined_absolute: float, + coarse_fingertip: float, + refined_fingertip: float, + coarse_root_mpvpe: float, + refined_root_mpvpe: float, +) -> dict[str, float | bool]: + fingertip_gain = 100.0 * (coarse_fingertip - refined_fingertip) / coarse_fingertip + root_mpvpe_gain = 100.0 * ( + coarse_root_mpvpe - refined_root_mpvpe + ) / coarse_root_mpvpe + absolute_degradation = 100.0 * ( + refined_absolute - coarse_absolute + ) / coarse_absolute + return { + "fingertip_improvement_percent": fingertip_gain, + "root_relative_mpvpe_improvement_percent": root_mpvpe_gain, + "absolute_mpjpe_degradation_percent": absolute_degradation, + "accuracy_gain_passed": bool( + fingertip_gain >= 10.0 or root_mpvpe_gain >= 10.0 + ), + "absolute_guardrail_passed": bool(absolute_degradation <= 2.0), + "promotion_gate_passed": bool( + (fingertip_gain >= 10.0 or root_mpvpe_gain >= 10.0) + and absolute_degradation <= 2.0 + ), + } + + +def rename_distribution_conditions( + rows: list[dict[str, object]], mode: str, scope: str, +) -> None: + for row in rows: + row["mode"] = mode + row["scope"] = scope + row["condition"] = { + "reference": "coarse", + "candidate": "refined", + "candidate_minus_reference": "refined_minus_coarse", + }[row["condition"]] + + +def gate_from_distributions( + rows: list[dict[str, object]], mode: str, +) -> dict[str, float | bool]: + def overall(metric: str, condition: str) -> float: + matches = [ + row for row in rows + if row["group_field"] == "all" and row["group_value"] == "all" + and row["metric"] == metric and row["condition"] == condition + ] + if len(matches) != 1: + raise ValueError(f"missing overall {mode}/{metric}/{condition}") + return float(matches[0]["mean"]) + + return compute_gate( + overall("absolute_mpjpe_mm", "coarse"), + overall("absolute_mpjpe_mm", "refined"), + overall("fingertip_mpjpe_mm", "coarse"), + overall("fingertip_mpjpe_mm", "refined"), + overall("root_relative_mpvpe_mm", "coarse"), + overall("root_relative_mpvpe_mm", "refined"), + ) + + +def assert_coarse_identical_across_modes( + raw_by_mode: Mapping[str, Mapping[int, list[dict[str, str]]]], +) -> None: + reference_mode = MODES[0] + for seed in SEEDS: + reference = { + tuple(row[field] for field in RECONSTRUCTION_KEY): tuple( + row[coarse_metric] for coarse_metric in METRIC_PAIRS.values() + ) + for row in raw_by_mode[reference_mode][seed] + } + for mode in MODES[1:]: + candidate = { + tuple(row[field] for field in RECONSTRUCTION_KEY): tuple( + row[coarse_metric] for coarse_metric in METRIC_PAIRS.values() + ) + for row in raw_by_mode[mode][seed] + } + if candidate != reference: + raise ValueError( + f"frozen coarse outputs differ across A3 modes for seed {seed}" + ) + + +def seed_deltas( + raw_by_seed: Mapping[int, list[dict[str, str]]], mode: str, +) -> list[dict[str, object]]: + output = [] + for seed in SEEDS: + rows = [ + row for row in raw_by_seed[seed] + if int(row["annotation_valid"]) == 1 + ] + for metric, coarse_metric in METRIC_PAIRS.items(): + coarse = statistic((row.get(coarse_metric) for row in rows), "mean") + refined = statistic((row.get(metric) for row in rows), "mean") + if coarse is None or refined is None: + continue + output.append({ + "mode": mode, "seed": seed, "metric": metric, + "coarse": coarse, "refined": refined, + "refined_minus_coarse": refined - coarse, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--role", default="best_absolute") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--challenge-manifest", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + evaluations = discover_evaluations(args.evaluation_root, args.role) + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + challenge_indices = {int(value) for value in challenge["clip_indices"]} + if ( + len(challenge_indices) != int(challenge["count"]) + or challenge.get("source_clip_count") != 1495 + or challenge.get("checkpoint_selection_allowed") is not False + or challenge.get("training_sampler_use_allowed") is not False + or challenge.get("official_test_used") is not False + ): + raise ValueError("invalid frozen official-validation challenge subset") + raw_by_mode = { + mode: { + seed: read_csv(evaluations[mode][seed] / "per_hand_frame_metrics.csv") + for seed in SEEDS + } + for mode in MODES + } + assert_coarse_identical_across_modes(raw_by_mode) + + comparison_output = [] + paired_output = [] + seed_output = [] + gates = {} + challenge_diagnostics = {} + for mode_index, mode in enumerate(MODES): + refined = aggregate_seed_rows( + raw_by_mode[mode], RECONSTRUCTION_KEY, METRICS, + ) + coarse = aggregate_seed_rows( + {seed: coarse_rows(raw_by_mode[mode][seed]) for seed in SEEDS}, + RECONSTRUCTION_KEY, METRICS, + ) + assert_pair_alignment( + coarse, refined, RECONSTRUCTION_KEY, RECONSTRUCTION_METADATA, + ) + distributions = distribution_rows( + coarse, refined, METRICS, require_annotation_valid=True, + ) + rename_distribution_conditions(distributions, mode, "full_validation") + comparison_output.extend(distributions) + + valid_coarse = [row for row in coarse if int(row["annotation_valid"]) == 1] + valid_refined = [row for row in refined if int(row["annotation_valid"]) == 1] + paired = paired_take_bootstrap( + valid_coarse, valid_refined, METRICS, groups(valid_coarse), + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + mode_index, + ) + paired.extend(paired_take_bootstrap( + valid_coarse, valid_refined, ("translation_z_mae_mm",), + groups(valid_coarse), statistics=("p95", "cvar95"), + bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 100 + mode_index, + )) + for row in paired: + row["mode"] = mode + row["scope"] = "full_validation" + row["coarse"] = row.pop("reference") + row["refined"] = row.pop("candidate") + row["refined_minus_coarse"] = row.pop("candidate_minus_reference") + paired_output.extend(paired) + seed_output.extend(seed_deltas(raw_by_mode[mode], mode)) + + gates[mode] = gate_from_distributions(distributions, mode) + + challenge_coarse = [ + row for row in coarse if int(row["clip_index"]) in challenge_indices + ] + challenge_refined = [ + row for row in refined if int(row["clip_index"]) in challenge_indices + ] + challenge_distributions = distribution_rows( + challenge_coarse, challenge_refined, METRICS, + require_annotation_valid=True, + ) + rename_distribution_conditions( + challenge_distributions, mode, "challenge_secondary", + ) + comparison_output.extend(challenge_distributions) + challenge_diagnostics[mode] = gate_from_distributions( + challenge_distributions, mode, + ) + challenge_paired = paired_take_bootstrap( + [row for row in challenge_coarse if int(row["annotation_valid"]) == 1], + [row for row in challenge_refined if int(row["annotation_valid"]) == 1], + METRICS, [("all", "all"), ("side", "left"), ("side", "right")], + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 200 + mode_index, + ) + for row in challenge_paired: + row["mode"] = mode + row["scope"] = "challenge_secondary" + row["coarse"] = row.pop("reference") + row["refined"] = row.pop("candidate") + row["refined_minus_coarse"] = row.pop("candidate_minus_reference") + paired_output.extend(challenge_paired) + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "a3_oracle_crop_comparison.csv", comparison_output) + write_csv( + args.output_dir / "a3_oracle_crop_paired_take_bootstrap_ci.csv", + paired_output, + ) + write_csv(args.output_dir / "a3_oracle_crop_seed_stability.csv", seed_output) + report = { + "status": "summarized", + "official_test_used": False, + "role": args.role, + "seeds": list(SEEDS), + "modes": list(MODES), + "aggregation": "aligned per-frame error averaged over three seeds", + "confidence_interval_unit": "paired official-validation take", + "coarse_consistency_across_modes": True, + "challenge_subset": { + "manifest": str(args.challenge_manifest.resolve()), + "clips": len(challenge_indices), + "role": "secondary_diagnostic_only", + "checkpoint_selection_allowed": False, + "diagnostics": challenge_diagnostics, + }, + "promotion_rule": ( + "fingertip MPJPE or root-relative MPVPE improves >=10%, and " + "absolute MPJPE degrades <=2%" + ), + "gates": gates, + } + (args.output_dir / "A3_ORACLE_CROP.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_control.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_control.py new file mode 100644 index 0000000000000000000000000000000000000000..786bf74861d7bf81eeee203f188c84966ad92b02 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_control.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +"""Compare a three-seed Phase 4 control with the matched 100k B-ref.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path +from typing import Iterable, Mapping + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary + + +SEEDS = (20260716, 20260717, 20260718) +RECONSTRUCTION_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "identity_switch_fraction", +) +RECONSTRUCTION_KEY = ("clip_index", "time_index", "side") +TEMPORAL_KEY = ("clip_index", "transition_index", "side") +RECONSTRUCTION_METADATA = ( + "take", + "frame_id", + "side", + "annotation_valid", + "hand_size_bucket", + "depth_bucket", + "action_family", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", +) +GROUP_FIELDS = ( + "side", + "hand_size_bucket", + "depth_bucket", + "action_family", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", +) + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report {path}") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: object) -> float | None: + if value in (None, ""): + return None + result = float(value) + return result if np.isfinite(result) else None + + +def discover_evaluations(root: Path, role: str) -> dict[int, Path]: + output = {} + for report_path in sorted(root.glob(f"*/{role}/evaluation.json")): + report = json.loads(report_path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("official_test_used") is not False: + raise ValueError(f"invalid evaluation report: {report_path}") + if report.get("phase4_diagnostics", {}).get("enabled") is not True: + raise ValueError(f"Phase 4 diagnostics missing: {report_path}") + seed = int(report["config"]["seed"]) + if seed in output: + raise ValueError(f"duplicate seed {seed} under {root}") + output[seed] = report_path.parent + if tuple(sorted(output)) != SEEDS: + raise ValueError(f"expected seeds {SEEDS}, found {tuple(sorted(output))} under {root}") + return output + + +def row_key(row: Mapping[str, object], fields: tuple[str, ...]) -> tuple[str, ...]: + return tuple(str(row[field]) for field in fields) + + +def aggregate_seed_rows( + rows_by_seed: Mapping[int, list[dict[str, str]]], + key_fields: tuple[str, ...], + metric_fields: tuple[str, ...], +) -> list[dict[str, object]]: + maps = { + seed: {row_key(row, key_fields): row for row in rows} + for seed, rows in rows_by_seed.items() + } + keys = set(maps[SEEDS[0]]) + if any(set(maps[seed]) != keys for seed in SEEDS[1:]): + raise ValueError("three-seed exported row keys do not align") + output = [] + for key in sorted(keys): + first = maps[SEEDS[0]][key] + row: dict[str, object] = dict(first) + for metric in metric_fields: + values = [ + optional_float(maps[seed][key].get(metric)) for seed in SEEDS + ] + finite = [value for value in values if value is not None] + row[metric] = float(np.mean(finite)) if finite else None + output.append(row) + return output + + +def assert_pair_alignment( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + key_fields: tuple[str, ...], + metadata_fields: tuple[str, ...], +) -> None: + reference_map = {row_key(row, key_fields): row for row in reference} + candidate_map = {row_key(row, key_fields): row for row in candidate} + if reference_map.keys() != candidate_map.keys(): + raise ValueError("candidate/reference exported row keys do not align") + for key, reference_row in reference_map.items(): + candidate_row = candidate_map[key] + for field in metadata_fields: + if str(reference_row.get(field, "")) != str(candidate_row.get(field, "")): + raise ValueError(f"candidate/reference metadata mismatch at {key}/{field}") + + +def groups(rows: list[dict[str, object]]) -> list[tuple[str, str]]: + output = [("all", "all")] + for field in GROUP_FIELDS: + values = sorted({str(row.get(field)) for row in rows if row.get(field) not in (None, "")}) + output.extend((field, value) for value in values) + return output + + +def selected_rows( + rows: list[dict[str, object]], group_field: str, group_value: str, +) -> list[dict[str, object]]: + if group_field == "all": + return rows + return [row for row in rows if str(row.get(group_field)) == group_value] + + +def distribution_rows( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + metrics: tuple[str, ...], + *, + require_annotation_valid: bool, +) -> list[dict[str, object]]: + if require_annotation_valid: + reference = [row for row in reference if int(row["annotation_valid"]) == 1] + candidate = [row for row in candidate if int(row["annotation_valid"]) == 1] + output = [] + for group_field, group_value in groups(reference): + reference_group = selected_rows(reference, group_field, group_value) + candidate_group = selected_rows(candidate, group_field, group_value) + for metric in metrics: + summaries = { + "reference": distribution_summary(row.get(metric) for row in reference_group), + "candidate": distribution_summary(row.get(metric) for row in candidate_group), + } + for condition, summary in summaries.items(): + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "condition": condition, + **summary, + "mean_relative_percent": None, + }) + delta = { + statistic: ( + summaries["candidate"][statistic] - summaries["reference"][statistic] + if summaries["candidate"][statistic] is not None + and summaries["reference"][statistic] is not None else None + ) + for statistic in ("mean", "p50", "p90", "p95", "p99", "cvar95") + } + reference_mean = summaries["reference"]["mean"] + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "condition": "candidate_minus_reference", + "count": summaries["candidate"]["count"], + "std": None, + **delta, + "mean_relative_percent": ( + 100.0 * delta["mean"] / reference_mean + if delta["mean"] is not None and reference_mean not in (None, 0) else None + ), + }) + return output + + +def statistic(values: Iterable[object], name: str) -> float | None: + array = np.asarray( + [value for item in values if (value := optional_float(item)) is not None], + dtype=np.float64, + ) + if not array.size: + return None + if name == "mean": + return float(array.mean()) + threshold = float(np.percentile(array, 95)) + if name == "p95": + return threshold + if name == "cvar95": + return float(array[array >= threshold].mean()) + raise ValueError(f"unknown statistic {name}") + + +def paired_take_bootstrap( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + metrics: tuple[str, ...], + group_specs: list[tuple[str, str]], + *, + statistics: tuple[str, ...], + bootstrap_samples: int, + seed: int, +) -> list[dict[str, object]]: + output = [] + for group_index, (group_field, group_value) in enumerate(group_specs): + reference_group = selected_rows(reference, group_field, group_value) + candidate_group = selected_rows(candidate, group_field, group_value) + reference_by_take: dict[str, list[dict[str, object]]] = defaultdict(list) + candidate_by_take: dict[str, list[dict[str, object]]] = defaultdict(list) + for row in reference_group: + reference_by_take[str(row["take"])].append(row) + for row in candidate_group: + candidate_by_take[str(row["take"])].append(row) + takes = sorted(set(reference_by_take) & set(candidate_by_take)) + for metric_index, metric in enumerate(metrics): + for statistic_index, statistic_name in enumerate(statistics): + paired = [] + reference_values = [] + candidate_values = [] + for take in takes: + reference_value = statistic( + (row.get(metric) for row in reference_by_take[take]), statistic_name, + ) + candidate_value = statistic( + (row.get(metric) for row in candidate_by_take[take]), statistic_name, + ) + if reference_value is None or candidate_value is None: + continue + reference_values.append(reference_value) + candidate_values.append(candidate_value) + paired.append(candidate_value - reference_value) + deltas = np.asarray(paired, dtype=np.float64) + if not deltas.size: + continue + rng = np.random.default_rng( + np.random.SeedSequence([seed, group_index, metric_index, statistic_index]) + ) + indices = rng.integers( + 0, deltas.size, size=(bootstrap_samples, deltas.size), + ) + distribution = deltas[indices].mean(axis=1) + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "statistic": f"take_{statistic_name}", + "takes": int(deltas.size), + "reference": float(np.mean(reference_values)), + "candidate": float(np.mean(candidate_values)), + "candidate_minus_reference": float(deltas.mean()), + "ci_low": float(np.percentile(distribution, 2.5)), + "ci_high": float(np.percentile(distribution, 97.5)), + "bootstrap_samples": bootstrap_samples, + }) + return output + + +def per_seed_deltas( + reference_dirs: Mapping[int, Path], + candidate_dirs: Mapping[int, Path], +) -> list[dict[str, object]]: + output = [] + for seed in SEEDS: + reference = [ + row for row in read_csv(reference_dirs[seed] / "per_hand_frame_metrics.csv") + if int(row["annotation_valid"]) == 1 + ] + candidate = [ + row for row in read_csv(candidate_dirs[seed] / "per_hand_frame_metrics.csv") + if int(row["annotation_valid"]) == 1 + ] + for metric in RECONSTRUCTION_METRICS: + reference_mean = statistic((row.get(metric) for row in reference), "mean") + candidate_mean = statistic((row.get(metric) for row in candidate), "mean") + if reference_mean is None or candidate_mean is None: + continue + output.append({ + "seed": seed, + "metric": metric, + "reference": reference_mean, + "candidate": candidate_mean, + "candidate_minus_reference": candidate_mean - reference_mean, + }) + return output + + +def lookup_distribution( + rows: list[dict[str, object]], group_field: str, group_value: str, + metric: str, condition: str, +) -> dict[str, object]: + matches = [ + row for row in rows + if row["group_field"] == group_field and row["group_value"] == group_value + and row["metric"] == metric and row["condition"] == condition + ] + if len(matches) != 1: + raise ValueError(f"expected one distribution row, found {len(matches)}") + return matches[0] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-root", type=Path, required=True) + parser.add_argument("--candidate-root", type=Path, required=True) + parser.add_argument("--role", default="best_absolute") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--prefix", required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + reference_dirs = discover_evaluations(args.reference_root, args.role) + candidate_dirs = discover_evaluations(args.candidate_root, args.role) + reconstruction = {} + temporal = {} + for name, directories in (("reference", reference_dirs), ("candidate", candidate_dirs)): + reconstruction[name] = aggregate_seed_rows({ + seed: read_csv(directory / "per_hand_frame_metrics.csv") + for seed, directory in directories.items() + }, RECONSTRUCTION_KEY, RECONSTRUCTION_METRICS) + temporal[name] = aggregate_seed_rows({ + seed: read_csv(directory / "per_temporal_transition_metrics.csv") + for seed, directory in directories.items() + }, TEMPORAL_KEY, TEMPORAL_METRICS) + assert_pair_alignment( + reconstruction["reference"], reconstruction["candidate"], + RECONSTRUCTION_KEY, RECONSTRUCTION_METADATA, + ) + assert_pair_alignment( + temporal["reference"], temporal["candidate"], + TEMPORAL_KEY, ("take", "frame_id_from", "frame_id_to", "side"), + ) + reconstruction_rows = distribution_rows( + reconstruction["reference"], reconstruction["candidate"], + RECONSTRUCTION_METRICS, require_annotation_valid=True, + ) + temporal_rows = distribution_rows( + temporal["reference"], temporal["candidate"], + TEMPORAL_METRICS, require_annotation_valid=False, + ) + valid_reference = [ + row for row in reconstruction["reference"] if int(row["annotation_valid"]) == 1 + ] + valid_candidate = [ + row for row in reconstruction["candidate"] if int(row["annotation_valid"]) == 1 + ] + group_specs = groups(valid_reference) + paired_rows = paired_take_bootstrap( + valid_reference, valid_candidate, RECONSTRUCTION_METRICS, + group_specs, statistics=("mean",), + bootstrap_samples=args.bootstrap_samples, seed=args.seed, + ) + paired_rows.extend(paired_take_bootstrap( + valid_reference, valid_candidate, ("translation_z_mae_mm",), + group_specs, statistics=("p95", "cvar95"), + bootstrap_samples=args.bootstrap_samples, seed=args.seed + 1, + )) + paired_rows.extend(paired_take_bootstrap( + temporal["reference"], temporal["candidate"], TEMPORAL_METRICS, + [("all", "all"), ("side", "left"), ("side", "right")], + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 2, + )) + seed_rows = per_seed_deltas(reference_dirs, candidate_dirs) + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / f"{args.prefix}_comparison.csv", reconstruction_rows + temporal_rows) + write_csv(args.output_dir / f"{args.prefix}_paired_take_bootstrap_ci.csv", paired_rows) + write_csv(args.output_dir / f"{args.prefix}_seed_stability.csv", seed_rows) + + def reduction(group_field: str, group_value: str, metric: str, statistic_name: str) -> float: + reference = lookup_distribution( + reconstruction_rows, group_field, group_value, metric, "reference", + )[statistic_name] + candidate = lookup_distribution( + reconstruction_rows, group_field, group_value, metric, "candidate", + )[statistic_name] + return 100.0 * (float(reference) - float(candidate)) / float(reference) + + gate = { + "z_p95_reduction_percent": reduction( + "all", "all", "translation_z_mae_mm", "p95", + ), + "small_absolute_reduction_percent": reduction( + "hand_size_bucket", "small", "absolute_mpjpe_mm", "mean", + ), + } + report = { + "status": "summarized", + "official_test_used": False, + "reference_root": str(args.reference_root.resolve()), + "candidate_root": str(args.candidate_root.resolve()), + "role": args.role, + "seeds": list(SEEDS), + "aggregation": "mean each aligned per-frame error over three seeds before distributions", + "confidence_interval_unit": "paired official-validation take", + "gate_diagnostics": gate, + "outputs": { + "comparison": f"{args.prefix}_comparison.csv", + "paired_take_bootstrap_ci": f"{args.prefix}_paired_take_bootstrap_ci.csv", + "seed_stability": f"{args.prefix}_seed_stability.csv", + }, + } + (args.output_dir / f"{args.prefix}.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_wave0.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_wave0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3340a99b19f9ae02a56d0a239a6f936d60ab8a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase4_wave0.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +"""Aggregate three frozen Phase 3 references into Phase 4 Wave 0 diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.phase4 import find_failure_intervals + + +SEEDS = (20260716, 20260717, 20260718) +MEAN_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", +) +STABLE_FIELDS = ( + "clip_index", + "time_index", + "take", + "subject", + "sequence", + "frame_id", + "side", + "annotation_valid", + "annotation_state", + "hand_size_px", + "hand_size_bucket", + "wrist_depth_m", + "depth_bucket", + "action_family", + "action_label", + "action_name", + "bimanual_size_ratio", + "bimanual_depth_gap_m", + "right_minus_left_depth_m", + "bimanual_asymmetry_bucket", + "local_depth_valid_fraction", + "local_depth_validity_bucket", + "local_depth_median_m", + "local_depth_q10_m", + "local_depth_q90_m", + "local_depth_iqr_m", + "local_depth_discontinuity_m", + "local_surface_minus_wrist_z_m", + "target_wrist_x_m", + "target_wrist_y_m", + "target_wrist_z_m", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + return + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: object) -> float | None: + if value in (None, ""): + return None + number = float(value) + return number if np.isfinite(number) else None + + +def classify_failure(row: dict[str, Any]) -> str: + if not int(row["annotation_valid"]): + return "annotation_invalid" + wrong_side = optional_float(row.get("wrong_side_preference_mean")) + z_error = float(row["translation_z_mae_mm_mean"]) + root_error = float(row["root_relative_mpjpe_mm_mean"]) + direct_2d = float(row["direct_2d_error_px_mean"]) + conditions = { + "identity": wrong_side is not None and wrong_side >= 0.5, + "z": z_error >= 40.0, + "articulation": root_error >= 30.0, + "localization_2d": direct_2d >= 20.0, + } + active = [name for name, enabled in conditions.items() if enabled] + if not active: + return "nominal" + if active == ["z"]: + return "z_translation_dominant" + if active == ["articulation"]: + return "articulation_dominant" + if active == ["localization_2d"]: + return "localization_2d_dominant" + if active == ["identity"]: + return "identity_assignment" + return "mixed_failure" + + +def aggregate_seed_rows(rows_by_seed: dict[int, list[dict[str, str]]]) -> list[dict[str, Any]]: + reference = rows_by_seed[SEEDS[0]] + for seed in SEEDS[1:]: + rows = rows_by_seed[seed] + if len(rows) != len(reference): + raise ValueError(f"seed {seed} row count differs: {len(rows)} != {len(reference)}") + output: list[dict[str, Any]] = [] + for index, reference_row in enumerate(reference): + row: dict[str, Any] = {field: reference_row.get(field, "") for field in STABLE_FIELDS} + for seed in SEEDS[1:]: + candidate = rows_by_seed[seed][index] + for field in STABLE_FIELDS: + if candidate.get(field, "") != reference_row.get(field, ""): + raise ValueError(f"target field mismatch at row {index}, seed {seed}, {field}") + row["annotation_valid"] = int(reference_row["annotation_valid"]) + row["clip_index"] = int(reference_row["clip_index"]) + row["time_index"] = int(reference_row["time_index"]) + row["frame_id"] = int(reference_row["frame_id"]) + for metric in MEAN_METRICS + ("wrong_side_preference",): + values = [optional_float(rows_by_seed[seed][index].get(metric)) for seed in SEEDS] + finite = np.asarray([value for value in values if value is not None], dtype=np.float64) + row[f"{metric}_mean"] = float(finite.mean()) if finite.size else None + row[f"{metric}_std"] = float(finite.std(ddof=1)) if finite.size > 1 else 0.0 if finite.size else None + row["failure_type"] = classify_failure(row) + output.append(row) + return output + + +def take_side_metrics(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for row in rows: + if int(row["annotation_valid"]): + grouped[(str(row["take"]), str(row["side"]))].append(row) + output = [] + for (take, side), items in sorted(grouped.items()): + record: dict[str, Any] = { + "take": take, + "side": side, + "valid_hand_frames": len(items), + "action_family": items[0]["action_family"], + "hand_size_px_mean": np.mean([float(row["hand_size_px"]) for row in items]), + "wrist_depth_m_mean": np.mean([float(row["wrist_depth_m"]) for row in items]), + "local_depth_valid_fraction_mean": np.mean([ + float(row["local_depth_valid_fraction"]) for row in items + if row["local_depth_valid_fraction"] not in (None, "") + ]), + "strong_asymmetry_fraction": np.mean([ + row["bimanual_asymmetry_bucket"] == "strong" for row in items + if row["bimanual_asymmetry_bucket"] not in (None, "") + ]), + } + for metric in ( + "absolute_mpjpe_mm_mean", + "root_relative_mpjpe_mm_mean", + "absolute_mpvpe_mm_mean", + "fingertip_mpjpe_mm_mean", + "direct_2d_error_px_mean", + "mano_projected_2d_error_px_mean", + "translation_x_mae_mm_mean", + "translation_y_mae_mm_mean", + "translation_z_mae_mm_mean", + "translation_z_signed_error_mm_mean", + ): + summary = distribution_summary(row[metric] for row in items) + base = metric.removesuffix("_mean") + record[f"{base}_mean"] = summary["mean"] + record[f"{base}_p95"] = summary["p95"] + record[f"{base}_cvar95"] = summary["cvar95"] + output.append(record) + return output + + +def select_challenge_subset( + rows: list[dict[str, Any]], + *, + seed: int, + target_clips: int = 128, +) -> tuple[list[int], list[dict[str, Any]], dict[str, float]]: + if target_clips < 112: + raise ValueError("challenge subset needs at least 112 clips for failure/control coverage") + valid = [row for row in rows if int(row["annotation_valid"])] + depths = np.asarray([float(row["wrist_depth_m"]) for row in valid], dtype=np.float64) + farthest_observed_threshold = float(np.percentile(depths, 80)) + z_median = float(np.median([row["translation_z_mae_mm_mean"] for row in valid])) + selected: dict[int, dict[str, Any]] = {} + failure_clips: set[int] = set() + + def sample_record(row: dict[str, Any], reason: str) -> dict[str, Any]: + return { + "clip_index": int(row["clip_index"]), + "time_index": int(row["time_index"]), + "take": row["take"], + "frame_id": int(row["frame_id"]), + "side": row["side"], + "action_label": int(row["action_label"]), + "action_name": row["action_name"], + "hand_size_px": float(row["hand_size_px"]), + "wrist_depth_m": float(row["wrist_depth_m"]), + "absolute_mpjpe_mm_mean": float(row["absolute_mpjpe_mm_mean"]), + "translation_z_mae_mm_mean": float(row["translation_z_mae_mm_mean"]), + "reasons": [reason], + } + + def add_failure( + candidates: list[dict[str, Any]], + count: int, + reason: str, + metric: str, + ) -> None: + if count <= 0: + return + ordered = sorted( + candidates, + key=lambda row: (-float(row[metric]), str(row["take"]), int(row["frame_id"]), str(row["side"])), + ) + added = 0 + for row in ordered: + clip_index = int(row["clip_index"]) + if clip_index in selected: + if reason not in selected[clip_index]["reasons"]: + selected[clip_index]["reasons"].append(reason) + continue + selected[clip_index] = sample_record(row, reason) + failure_clips.add(clip_index) + added += 1 + if added >= count: + break + + for side, right_count, left_count in (("right", 12, 0), ("left", 0, 8)): + add_failure( + [row for row in valid if row["side"] == side], + right_count + left_count, + "high_z_error", + "translation_z_mae_mm_mean", + ) + for side in ("left", "right"): + add_failure( + [row for row in valid if row["side"] == side], + 8, + "high_absolute_error", + "absolute_mpjpe_mm_mean", + ) + add_failure([ + row for row in valid + if row["side"] == side + and row["hand_size_bucket"] == "small" + and float(row["wrist_depth_m"]) >= farthest_observed_threshold + ], 6, "farthest_observed_small_hand", "translation_z_mae_mm_mean") + add_failure([ + row for row in valid + if row["side"] == side and row["bimanual_asymmetry_bucket"] == "strong" + ], 6, "strong_bimanual_asymmetry", "translation_z_mae_mm_mean") + add_failure([ + row for row in valid + if row["side"] == side and int(row["action_label"]) != 0 + ], 2, "object_interaction", "absolute_mpjpe_mm_mean") + + for side in ("left", "right"): + side_count = sum(selected[index]["side"] == side for index in failure_clips) + add_failure( + [row for row in valid if row["side"] == side], + max(0, 32 - side_count), + "failure_balance_fill", + "translation_z_mae_mm_mean", + ) + + # Add one ordinary low-z control for every take and side. These 48 clips + # prevent the diagnostic from collapsing onto a few known failure takes. + controls = [row for row in valid if float(row["translation_z_mae_mm_mean"]) <= z_median] + for take in sorted({str(row["take"]) for row in valid}): + for side in ("left", "right"): + candidates = [ + row for row in controls + if row["take"] == take + and row["side"] == side + and int(row["clip_index"]) not in selected + ] + candidates.sort(key=lambda row: ( + abs(float(row["translation_z_mae_mm_mean"]) - z_median), + int(row["frame_id"]), + )) + if candidates: + record = sample_record(candidates[0], "take_side_low_z_control") + selected[int(record["clip_index"])] = record + + challenge_samples = [selected[index] for index in sorted(failure_clips)] + rng = np.random.default_rng(seed) + challenge_order = rng.permutation(len(challenge_samples)) + for challenge_index in challenge_order: + if len(selected) >= target_clips: + break + challenge = challenge_samples[int(challenge_index)] + matches = [ + row for row in controls + if int(row["action_label"]) == int(challenge["action_label"]) + and row["side"] == challenge["side"] + and int(row["clip_index"]) not in selected + ] + if not matches: + continue + matches.sort(key=lambda row: ( + abs(float(row["hand_size_px"]) - float(challenge["hand_size_px"])) + / max(float(challenge["hand_size_px"]), 1.0) + + abs(float(row["wrist_depth_m"]) - float(challenge["wrist_depth_m"])) / 0.1, + str(row["take"]), + int(row["frame_id"]), + )) + match = matches[0] + record = sample_record(match, "same_action_low_z_matched_control") + record["matched_to_clip_index"] = int(challenge["clip_index"]) + selected[int(record["clip_index"])] = record + + if len(selected) < target_clips: + ordinary = sorted( + controls, + key=lambda row: ( + abs(float(row["translation_z_mae_mm_mean"]) - z_median), + int(row["action_label"]), + str(row["side"]), + int(row["clip_index"]), + ), + ) + for row in ordinary: + if len(selected) >= target_clips: + break + clip_index = int(row["clip_index"]) + if clip_index in selected: + continue + selected[clip_index] = sample_record(row, "ordinary_action_matched_fill") + samples = sorted(selected.values(), key=lambda row: int(row["clip_index"])) + return [int(row["clip_index"]) for row in samples], samples, { + "farthest_observed_wrist_depth_p80_m": farthest_observed_threshold, + "reference_z_error_median_mm": z_median, + } + + +def compare_legacy_outputs( + evaluation_root: Path, + checkpoint_index: dict[str, Any], +) -> list[dict[str, Any]]: + records = [] + for run in checkpoint_index["runs"].values(): + seed = int(run["seed"]) + original = Path(run["roles"]["tail_best_absolute"]["evaluation"]).parent + current = evaluation_root / f"seed_{seed}" + original_report = json.loads((original / "evaluation.json").read_text(encoding="utf-8")) + current_report = json.loads((current / "evaluation.json").read_text(encoding="utf-8")) + exact = True + for metric, summary in original_report["metrics"].items(): + for statistic, value in summary.items(): + exact &= current_report["metrics"][metric][statistic] == value + for filename in ("per_hand_frame_metrics.csv", "per_temporal_transition_metrics.csv"): + old_rows = read_csv(original / filename) + new_rows = read_csv(current / filename) + exact &= len(old_rows) == len(new_rows) + if exact: + for old_row, new_row in zip(old_rows, new_rows, strict=True): + exact &= all(new_row[key] == value for key, value in old_row.items()) + records.append({ + "seed": seed, + "checkpoint_sha256": current_report["checkpoint"]["sha256"], + "manifest_sha256": current_report["manifest"]["sha256"], + "clips": current_report["clips"], + "frames": current_report["frames"], + "legacy_outputs_exact": bool(exact), + "source_phase3_evaluation": str(original), + "phase4_evaluation": str(current.resolve()), + }) + if not all(record["legacy_outputs_exact"] for record in records): + raise ValueError("Phase 4 evaluator does not reproduce Phase 3 outputs exactly") + return sorted(records, key=lambda row: int(row["seed"])) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--evaluation-root", + type=Path, + default=Path("artifacts/phase4/wave0/reference_evaluations"), + ) + parser.add_argument( + "--checkpoint-index", + type=Path, + default=Path("artifacts/phase3/reports/long_tail_checkpoints.json"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/reports")) + parser.add_argument( + "--challenge-output", + type=Path, + default=Path("artifacts/phase4/challenge_subset/official_val_challenge_128.json"), + ) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + args.challenge_output.parent.mkdir(parents=True, exist_ok=True) + + checkpoint_index = json.loads(args.checkpoint_index.read_text(encoding="utf-8")) + consistency = compare_legacy_outputs(args.evaluation_root, checkpoint_index) + rows_by_seed = { + seed: read_csv(args.evaluation_root / f"seed_{seed}" / "per_hand_frame_metrics.csv") + for seed in SEEDS + } + aggregated = aggregate_seed_rows(rows_by_seed) + valid = [row for row in aggregated if int(row["annotation_valid"])] + take_rows = take_side_metrics(aggregated) + write_csv(args.output_dir / "take_side_metrics.csv", take_rows) + write_csv(args.output_dir / "failure_taxonomy.csv", aggregated) + + failure_intervals = find_failure_intervals( + [ + {**row, "translation_z_mae_mm": row["translation_z_mae_mm_mean"]} + for row in aggregated + ], + metric="translation_z_mae_mm", + threshold=40.0, + minimum_frames=3, + ) + find_failure_intervals( + [ + {**row, "absolute_mpjpe_mm": row["absolute_mpjpe_mm_mean"]} + for row in aggregated + ], + metric="absolute_mpjpe_mm", + threshold=50.0, + minimum_frames=3, + ) + write_csv(args.output_dir / "wave0_failure_intervals.csv", failure_intervals) + + bootstrap_metrics = tuple(f"{metric}_mean" for metric in MEAN_METRICS[:10]) + bootstrap_rows = bootstrap_take_means( + valid, + bootstrap_metrics, + seed=args.seed, + samples=10_000, + ) + write_csv(args.output_dir / "wave0_reference_take_bootstrap_ci.csv", bootstrap_rows) + + clip_indices, challenge_samples, thresholds = select_challenge_subset( + aggregated, + seed=args.seed, + target_clips=128, + ) + validation_manifest = Path( + json.loads( + (args.evaluation_root / f"seed_{SEEDS[0]}" / "evaluation.json").read_text( + encoding="utf-8" + ) + )["manifest"]["path"] + ) + challenge_manifest = { + "version": "phase4_official_val_challenge_v1", + "seed": args.seed, + "count": len(clip_indices), + "source_manifest": str(validation_manifest), + "source_manifest_sha256": sha256(validation_manifest), + "source_clip_count": 1495, + "dataset_contract": {"resolution_hw": [368, 640], "T": 8, "stride": 1}, + "source_checkpoints": [ + {"seed": record["seed"], "sha256": record["checkpoint_sha256"]} + for record in consistency + ], + "selection_policy": ( + "secondary diagnostic only: high z/absolute error, farthest-observed small hands, " + "strong bimanual asymmetry, object interaction, same-action low-z controls, and " + "ordinary matched fill" + ), + "thresholds": thresholds, + "far_note": ( + "Official validation has no valid wrist z >= 0.8 m. The challenge therefore uses " + "the observed validation wrist-depth P80 and labels it farthest-observed, not far." + ), + "checkpoint_selection_allowed": False, + "training_sampler_use_allowed": False, + "official_test_used": False, + "clip_indices": sorted(clip_indices), + "reason_counts": dict(Counter( + reason for sample in challenge_samples for reason in sample["reasons"] + )), + "samples": challenge_samples, + } + args.challenge_output.write_text( + json.dumps(challenge_manifest, indent=2) + "\n", encoding="utf-8" + ) + write_csv(args.challenge_output.with_suffix(".csv"), challenge_samples) + + taxonomy_counts = Counter(str(row["failure_type"]) for row in aggregated) + report = { + "status": "passed", + "official_test_used": False, + "evaluator_commit": "222b247cbf574faa9c9051832d0d51077df4573c", + "consistency": consistency, + "valid_hand_frames": len(valid), + "failure_taxonomy_counts": dict(taxonomy_counts), + "long_failure_intervals": len(failure_intervals), + "challenge_manifest": str(args.challenge_output.resolve()), + "challenge_manifest_sha256": sha256(args.challenge_output), + "challenge_clips": len(clip_indices), + } + (args.output_dir / "WAVE0_AUDIT.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase7_sequence_cache.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase7_sequence_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee2c43bea6622923c9cf4735cfd8610f5aeae19 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase7_sequence_cache.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Summarize frozen offline/causal sequence caches with static and dynamic metrics.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from foundation_hand.models.mano import ManoCameraLayer +from scripts.evaluate_phase4_jitter import ( + condition_grid, filtered_parameters, identity_switch_metrics, load_take, + per_frame_metrics, rebuild_geometry, temporal_metrics, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_manifest(manifest: dict[str, Any], path: Path) -> None: + if ( + manifest.get("status") != "complete" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_validation_used_for_selection") is not False + or manifest.get("official_test_used") is not False + or manifest.get("sequence_mode") not in {"offline", "causal"} + or int(manifest.get("sequence_window", -1)) < 1 + ): + raise ValueError(f"invalid frozen sequence cache manifest: {path}") + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"cannot write empty sequence summary: {path}") + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + + +def aligned_metrics(arrays: dict[str, np.ndarray], joints: np.ndarray) -> dict[str, list[float]]: + values: dict[str, list[float]] = defaultdict(list) + valid = arrays["joint_annotation_valid"].astype(bool) + valid &= arrays["frame_valid"][:, None].astype(bool) + for side in range(2): + indices = np.where(valid[:, side])[0] + if not len(indices): + continue + target = arrays["target_joints_camera"][indices, side] + predicted = joints[indices, side] + values["rigid_se3_mpjpe_mm"].extend(aligned_mpjpe_mm( + predicted, target, estimate_scale=False, + ).tolist()) + values["pa_mpjpe_mm"].extend(aligned_mpjpe_mm( + predicted, target, estimate_scale=True, + ).tolist()) + return values + + +def continuous_take_arrays(arrays: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + """Normalize legacy frame-iterator indices to one continuous take stream.""" + + if str(arrays.get("sequence_mode", "")) not in {"offline", "causal"}: + raise ValueError("take cache is not a bounded sequence-inference cache") + normalized = dict(arrays) + normalized["clip_index"] = np.zeros_like(arrays["frame_id"], dtype=np.int64) + return normalized + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--bootstrap-samples", type=int, default=2000) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + validate_manifest(manifest, manifest_path) + args.output_dir.mkdir(parents=True) + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + condition = condition_grid()["F0_raw"] + global_values: dict[str, list[float]] = defaultdict(list) + take_rows: list[dict[str, Any]] = [] + for take_record in manifest["takes"]: + path = Path(take_record["path"]) + if sha256(path) != take_record["sha256"]: + raise ValueError(f"take cache hash mismatch: {path}") + arrays = continuous_take_arrays(load_take(path)) + translation, rotations, _ = filtered_parameters(arrays, condition) + vertices, joints = rebuild_geometry( + rotations, arrays["pred_shape"].astype(np.float32), translation, + mano, device, + ) + selected = arrays["frame_valid"].astype(bool) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, rotations, translation, selected, + ) + for metric, observations in temporal_metrics( + arrays, joints, projected, selected, + ).items(): + metrics[metric].extend(observations) + for metric, observations in identity_switch_metrics( + arrays, joints, selected, + ).items(): + metrics[metric].extend(observations) + for metric, observations in aligned_metrics(arrays, joints).items(): + metrics[metric].extend(observations) + row: dict[str, Any] = {"take": str(arrays["take"]), "frames": len(joints)} + for metric, observations in metrics.items(): + global_values[metric].extend(observations) + summary = distribution_summary(observations) + row[metric] = summary["mean"] + row[f"{metric}_p95"] = summary["p95"] + take_rows.append(row) + all_fields = sorted({key for row in take_rows for key in row}) + normalized_rows = [{key: row.get(key) for key in all_fields} for row in take_rows] + write_csv(args.output_dir / "take_metrics.csv", normalized_rows) + metric_rows = [ + {"metric": metric, **distribution_summary(observations)} + for metric, observations in sorted(global_values.items()) + ] + write_csv(args.output_dir / "metrics.csv", metric_rows) + metric_names = sorted(global_values) + bootstrap = bootstrap_take_means( + take_rows, metric_names, seed=20260717, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "take_bootstrap_ci.csv", bootstrap) + report = { + "status": "evaluated_frozen_sequence_cache", + "sequence_mode": manifest["sequence_mode"], + "causal": manifest["sequence_mode"] == "causal", + "window": manifest["sequence_window"], + "offline_stride": manifest.get("offline_stride"), + "frames": manifest["frames"], "takes": len(manifest["takes"]), + "metrics": {row["metric"]: { + key: value for key, value in row.items() if key != "metric" + } for row in metric_rows}, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], "config": manifest["config"], + "bounded_memory": { + "maximum_gpu_window_frames": manifest["maximum_gpu_window_frames"], + "maximum_cpu_input_buffer_frames": manifest["maximum_cpu_input_buffer_frames"], + }, + "take_metrics": "take_metrics.csv", "take_bootstrap_ci": "take_bootstrap_ci.csv", + "official_validation_used_for_selection": False, "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "mode": report["sequence_mode"], + "absolute_mpjpe_mm": report["metrics"]["absolute_mpjpe_mm"]["mean"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase8_cross_domain_matrix.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase8_cross_domain_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec718b00fb86cb246600b0fafc8acaeb0e86941 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase8_cross_domain_matrix.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Summarize a frozen external cross-domain matrix without frame weighting.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "rigid_se3_mpjpe_mm", + "pa_mpjpe_mm", "mpvpe_mm", "fingertip_mpjpe_mm", + "projected_mano_2d_error_px", "translation_x_mae_mm", + "translation_y_mae_mm", "translation_z_mae_mm", +) + + +def metric_mean(report: dict[str, Any], metric: str) -> float: + value = report.get("metrics", {}).get(metric) + if not isinstance(value, dict) or value.get("mean") is None: + return math.nan + return float(value["mean"]) + + +def summarize(manifest: Path, output_dir: Path) -> dict[str, Any]: + specification = json.loads(manifest.read_text(encoding="utf-8")) + if specification.get("official_test_used") is not False: + raise ValueError("matrix manifest must set official_test_used=false") + entries = specification.get("entries", []) + if not entries: + raise ValueError("matrix manifest is empty") + if output_dir.exists() and any(output_dir.iterdir()): + raise ValueError("output directory must be new or empty") + output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, Any]] = [] + checkpoint_by_condition: dict[str, str] = {} + seen: set[tuple[str, str]] = set() + for entry in entries: + condition, dataset = str(entry["condition"]), str(entry["dataset"]) + key = (condition, dataset) + if key in seen: + raise ValueError(f"duplicate matrix cell: {condition}/{dataset}") + seen.add(key) + path = Path(entry["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"non-external or non-frozen matrix result: {path}") + checkpoint_sha = str(report["checkpoint"]["sha256"]) + prior = checkpoint_by_condition.setdefault(condition, checkpoint_sha) + if prior != checkpoint_sha: + raise ValueError(f"condition uses multiple checkpoints: {condition}") + row: dict[str, Any] = { + "condition": condition, "dataset": dataset, + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint_sha256": checkpoint_sha, + "input_mode": report["input_mode"], + "clips": int(report["clips"]), "frames": int(report["frames"]), + "evaluation": str(path.resolve()), + } + coverage = report.get("metrics", {}).get("supervision_coverage") + if not isinstance(coverage, dict): + raise ValueError(f"matrix result lacks supervision coverage: {path}") + for scope in ("overall", "left", "right"): + scoped = coverage.get(scope) + if not isinstance(scoped, dict): + raise ValueError(f"matrix result lacks {scope} supervision coverage: {path}") + for supervision in ("joint3d", "translation", "vertices"): + key = f"{supervision}_valid_fraction" + if scoped.get(key) is None: + raise ValueError(f"matrix result lacks {scope}/{key}: {path}") + row[f"{scope}_{key}"] = float(scoped[key]) + row.update({metric: metric_mean(report, metric) for metric in METRICS}) + z_summary = report.get("metrics", {}).get("translation_z_mae_mm") or {} + row["translation_z_p95_mm"] = float(z_summary.get("p95", math.nan)) + rows.append(row) + conditions = sorted({row["condition"] for row in rows}) + datasets = sorted({row["dataset"] for row in rows}) + expected = {(condition, dataset) for condition in conditions for dataset in datasets} + if seen != expected: + missing = sorted(expected - seen) + raise ValueError(f"cross-domain matrix is incomplete: {missing}") + + ranks: dict[str, dict[str, float]] = {condition: {} for condition in conditions} + for dataset in datasets: + selected = sorted( + (row for row in rows if row["dataset"] == dataset), + key=lambda row: row["absolute_mpjpe_mm"], + ) + for rank, row in enumerate(selected, 1): + ranks[row["condition"]][dataset] = float(rank) + mean_rank = { + condition: sum(ranks[condition].values()) / len(datasets) + for condition in conditions + } + absolute = { + condition: { + row["dataset"]: row["absolute_mpjpe_mm"] + for row in rows if row["condition"] == condition + } + for condition in conditions + } + pareto = [] + for condition in conditions: + dominated = any( + other != condition + and all(absolute[other][dataset] <= absolute[condition][dataset] for dataset in datasets) + and any(absolute[other][dataset] < absolute[condition][dataset] for dataset in datasets) + for other in conditions + ) + if not dominated: + pareto.append(condition) + + csv_path = output_dir / "cross_domain_matrix.csv" + with csv_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "complete", "selection": "dataset_macro_mean_rank", + "conditions": conditions, "datasets": datasets, + "dataset_ranks": ranks, "mean_rank": mean_rank, + "pareto_frontier": pareto, "rows": rows, + "official_test_used": False, + } + (output_dir / "summary.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + try: + result = summarize(args.manifest, args.output_dir) + except ValueError as error: + parser.error(str(error)) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase8_egodexter.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase8_egodexter.py new file mode 100644 index 0000000000000000000000000000000000000000..20bc81db0816cfd08d32c419fc3c157447dbb500 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase8_egodexter.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Summarize the complete frozen Phase 8 EgoDexter zero-shot grid.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_egodexter_zero_shot import sha256 + + +def summarize(queue_paths: list[Path]) -> dict[str, Any]: + rows = [] + model_ids: set[str] = set() + for queue_path in queue_paths: + queue = json.loads(queue_path.read_text(encoding="utf-8")) + if ( + queue.get("egodexter_used_for_training_or_selection") is not False + or queue.get("official_test_used") is not False + ): + raise ValueError("EgoDexter queue boundary flags are invalid") + model_ids.add(queue["model_id"]) + for item in queue["evaluations"]: + report_path = Path(item["output_dir"]) / "evaluation.json" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_frozen_egodexter_zero_shot" + or report.get("model_id") != item["model_id"] + or report.get("input_mode") != item["input_mode"] + or report.get("inference_mode") != item["inference_mode"] + or report.get("checkpoint", {}).get("sha256") != item["checkpoint_sha256"] + or report.get("egodexter_used_for_training_or_selection") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid EgoDexter report: {report_path}") + for artifact in ("per_fingertip_rows", "raw_predictions"): + record = report[artifact] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"EgoDexter {artifact} is missing or differs") + metric = report["fingertip_error_mm"] + rows.append({ + "model_id": item["model_id"], + "inference_mode": item["inference_mode"], + "input_mode": item["input_mode"], + "mean_fingertip_mm": metric["mean"], + "median_fingertip_mm": metric["median"], + "p95_fingertip_mm": metric["p95"], + "visible_fingertips": report["visible_fingertips"], + "coverage_fraction": report["coverage_fraction"], + "frames": report["frames"], + "fps": report["runtime"]["frames_per_second"], + "peak_vram_gib": report["runtime"]["peak_vram_gib"], + "maximum_gpu_window_frames": report["runtime"]["maximum_gpu_window_frames"], + "maximum_cpu_input_buffer_frames": report["runtime"]["maximum_cpu_input_buffer_frames"], + "per_finger": report["per_finger"], + "per_sequence": report["per_sequence"], + "evaluation": str(report_path.resolve()), + "evaluation_sha256": sha256(report_path), + }) + expected = len(model_ids) * 6 + identities = { + (row["model_id"], row["inference_mode"], row["input_mode"]) + for row in rows + } + if len(rows) != expected or len(identities) != expected: + raise ValueError("EgoDexter summary is not a complete unique grid") + return { + "schema_version": "phase8_egodexter_summary_v1", + "status": "complete_frozen_zero_shot", + "models": sorted(model_ids), + "conditions": rows, + "selection_use": False, + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", action="append", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("summary outputs must not exist") + try: + result = summarize(args.queue) + except (KeyError, OSError, ValueError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + csv_fields = [ + "model_id", "inference_mode", "input_mode", "mean_fingertip_mm", + "median_fingertip_mm", "p95_fingertip_mm", "visible_fingertips", + "coverage_fraction", "frames", "fps", "peak_vram_gib", + "maximum_gpu_window_frames", "maximum_cpu_input_buffer_frames", + "evaluation", "evaluation_sha256", + ] + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=csv_fields, lineterminator="\n") + writer.writeheader() + writer.writerows({key: row[key] for key in csv_fields} for row in result["conditions"]) + print(json.dumps({"status": result["status"], "conditions": len(result["conditions"])}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_final_deployment.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_final_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..8a16fb5023edce3600880e38c45f2309e30f30c8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_final_deployment.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Summarize formal H2O disclosure and the final deployment contract.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.run_phase9_final_deployment_worker import completed_matches +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def mean_metric(report: dict[str, Any], name: str) -> float: + value = report["metrics"][name] + return float(value["mean"] if isinstance(value, dict) else value) + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + jobs = {job["id"]: job for job in plan["jobs"]} + if len(jobs) != 11 or any(not completed_matches(job) for job in jobs.values()): + raise ValueError("final deployment jobs are not complete and bound") + formal = {} + formal_gpu_hours = 0.0 + for mode in plan["formal_validation_modes"]: + job = jobs[f"formal_{mode}"] + path = Path(job["output_dir"]) / "evaluation.json" + report = read_json(path) + formal_gpu_hours += float(report["runtime"]["wall_seconds"]) / 3600.0 + formal[mode] = { + "report": {"path": str(path.resolve()), "sha256": sha256(path)}, + "absolute_mpjpe_mm": mean_metric(report, "absolute_mpjpe_mm"), + "root_relative_mpjpe_mm": mean_metric(report, "root_relative_mpjpe_mm"), + "fingertip_mpjpe_mm": mean_metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": float( + report["metrics"]["translation_z_mae_mm"]["p95"] + ), + "frames": int(report["frames"]), + "peak_vram_gib": float(report["runtime"]["peak_vram_gib"]), + } + variable_job = jobs["variable_length"] + variable_path = Path(variable_job["output"]) + variable = read_json(variable_path) + sequence = {} + for mode in ("offline", "causal"): + sequence[mode] = {} + for frames in plan["sequence_contract"]["ordering_lengths"]: + job = jobs[f"{mode}_w8_{frames}"] + path = Path(job["output"]) + report = read_json(path) + sequence[mode][str(frames)] = { + "report": {"path": str(path.resolve()), "sha256": sha256(path)}, + "throughput_fps": float(report["throughput_fps"]), + "peak_allocated_gib": float(report["peak_allocated_gib"]), + "maximum_gpu_window_frames": int(report["maximum_gpu_window_frames"]), + "maximum_cpu_input_buffer_frames": int( + report["maximum_cpu_input_buffer_frames"] + ), + "invariance": report.get("invariance"), + } + profile_path = Path(jobs["latency_vram"]["output"]) + profile = read_json(profile_path) + attempts = [] + total_gpu_seconds = 0.0 + for worker in plan["workers"]: + state_path = Path(worker["state"]) + state = read_json(state_path) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + ): + raise ValueError(f"final deployment worker state differs: {worker['id']}") + for attempt in state.get("attempts", []): + start = datetime.fromisoformat(attempt["start_utc"]) + end = datetime.fromisoformat(attempt["end_utc"]) + seconds = (end - start).total_seconds() + if seconds < 0: + raise ValueError("final deployment attempt duration is negative") + total_gpu_seconds += seconds + attempts.append({ + "worker": worker["id"], "id": attempt["id"], + "kind": attempt["kind"], "physical_gpu_id": attempt["physical_gpu_id"], + "start_utc": attempt["start_utc"], "end_utc": attempt["end_utc"], + "returncode": attempt["returncode"], + "gpu_hours": seconds / 3600.0, + "archived_incomplete_output": attempt.get("archived_incomplete_output"), + }) + return { + "schema_version": "phase9_final_deployment_summary_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "final_checkpoint_deployment_contract_passed", + "winner": plan["winner"], + "selected_mechanism": plan["selected_mechanism"], + "resolution_hw": plan["resolution_hw"], + "shared_augmentation": plan["shared_augmentation"], + "checkpoint": plan["checkpoint"], "config": plan["config"], + "formal_h2o_validation": formal, + "formal_h2o_validation_checkpoint_count": 1, + "formal_h2o_validation_gpu_hours": formal_gpu_hours, + "formal_h2o_validation_used_for_selection": False, + "variable_length": { + "report": {"path": str(variable_path.resolve()), "sha256": sha256(variable_path)}, + "lengths": [item["T"] for item in variable["forward_results"]], + "all_finite": all(item["all_finite"] for item in variable["forward_results"]), + }, + "sequence_inference": sequence, + "latency_vram": { + "report": {"path": str(profile_path.resolve()), "sha256": sha256(profile_path)}, + "latency": profile["latency"], + "peak_allocated_vram_gib": profile["peak_allocated_vram_gib"], + "supported_operator_flops_per_clip": profile[ + "supported_operator_flops_per_clip" + ], + }, + "deployment_attempts": attempts, + "deployment_total_gpu_hours": total_gpu_seconds / 3600.0, + "recovery_disclosure": [ + attempt for attempt in attempts + if attempt["returncode"] != 0 + or attempt["archived_incomplete_output"] is not None + ], + "deployment_contract": { + "t_1_2_4_8_16_32_64": True, + "offline_overlap_w8_31_64_257": True, + "causal_rolling_w8_31_64_257": True, + "future_prefix_invariance": True, + "bounded_memory": True, + "fresh_resolution_latency_vram": True, + "passed": True, + }, + "selection_mutated_after_formal_validation": False, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = summarize(args.plan) + if args.output.exists(): + existing = read_json(args.output) + for key in ("created_utc",): + existing.pop(key, None) + result.pop(key, None) + if existing != result: + raise ValueError("existing final deployment summary differs") + else: + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(read_json(args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_hot_scale.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_hot_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..ed40258b5b96d9a269aa993872a60e029faed81f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_hot_scale.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Summarize the matched Phase 9 HOT unique-coverage experiment.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + +from scripts.select_phase7_external_continuation import paired_take_bootstrap + + +METRICS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "pa_mpjpe_mm": ("pa_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_x_mae_mm": ("translation_x_mae_mm", "mean"), + "translation_y_mae_mm": ("translation_y_mae_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} + + +def load_evaluation(path: Path) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(path) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_phase9_external_heldout" + or report.get("evaluation_role") != "phase9_external_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("official_test_used") is not False + ): + raise ValueError(f"evaluation role/isolation mismatch: {path}") + return report + + +def scalar(report: dict[str, Any], metric: str, statistic: str) -> float: + value = float(report["metrics"][metric][statistic]) + if not math.isfinite(value): + raise ValueError(f"non-finite {metric}.{statistic}") + return value + + +def result_row( + condition: str, unique_clips: int, source_id: str, report: dict[str, Any], +) -> dict[str, Any]: + metrics = { + output: scalar(report, metric, statistic) + for output, (metric, statistic) in METRICS.items() + } + for name in ("aria", "quest3"): + bucket = report["metrics"].get(f"bucket_headset_{name}") + metrics[f"{name}_absolute_mpjpe_mm"] = ( + None if not bucket else float(bucket["absolute_mpjpe_mm"]["mean"]) + ) + return { + "condition": condition, + "hot_unique_clips": unique_clips, + "source_id": source_id, + "checkpoint": report["checkpoint"], + "metrics": metrics, + } + + +def summarize( + registry: dict[str, Any], evaluation_root: Path, control_root: Path, +) -> dict[str, Any]: + if registry.get("official_test_used") is not False: + raise ValueError("registry must explicitly exclude official test") + clip_counts = {"J40_HOT10K": 10_000, "J40_HOT50K": 50_000} + rows: list[dict[str, Any]] = [] + checkpoint_hashes: dict[str, str] = {} + for condition in registry["conditions"]: + condition_id = str(condition["condition"]) + if condition_id not in clip_counts: + continue + hashes = set() + for source in registry["sources"]: + source_id = str(source["id"]) + report = load_evaluation( + evaluation_root / condition_id / "final505k" / source_id + / "evaluation.json" + ) + if report["cache_manifest"]["sha256"] != source["cache_manifest_sha256"]: + raise ValueError(f"manifest hash mismatch: {condition_id}/{source_id}") + hashes.add(str(report["checkpoint"]["sha256"])) + rows.append(result_row( + condition_id, clip_counts[condition_id], source_id, report, + )) + if len(hashes) != 1: + raise ValueError(f"condition uses multiple checkpoints: {condition_id}") + checkpoint_hashes[condition_id] = hashes.pop() + + control_id = "J40_HOT100K" + hashes = set() + for source in registry["sources"]: + source_id = str(source["id"]) + report = load_evaluation(control_root / source_id / "evaluation.json") + if report["cache_manifest"]["sha256"] != source["cache_manifest_sha256"]: + raise ValueError(f"control manifest hash mismatch: {source_id}") + hashes.add(str(report["checkpoint"]["sha256"])) + rows.append(result_row(control_id, 100_000, source_id, report)) + if len(hashes) != 1: + raise ValueError("HOT100K control uses multiple checkpoints") + checkpoint_hashes[control_id] = hashes.pop() + + controls = { + row["source_id"]: row for row in rows if row["condition"] == control_id + } + for row in rows: + control = controls[row["source_id"]] + row["delta_vs_hot100k"] = { + metric: ( + None if value is None or control["metrics"][metric] is None + else value - control["metrics"][metric] + ) + for metric, value in row["metrics"].items() + } + paired: dict[str, dict[str, dict[str, Any]]] = {} + for condition_id in clip_counts: + paired[condition_id] = {} + for source in registry["sources"]: + source_id = str(source["id"]) + candidate_dir = evaluation_root / condition_id / "final505k" / source_id + reference_dir = control_root / source_id + paired[condition_id][source_id] = { + metric: paired_take_bootstrap( + reference_dir / "take_metrics.csv", + candidate_dir / "take_metrics.csv", + metric, seed=20260717, resamples=2000, + ) + for metric in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + paired[condition_id][source_id]["translation_z_p95_mm"] = ( + paired_take_bootstrap( + reference_dir / "per_hand_frame_metrics.csv", + candidate_dir / "per_hand_frame_metrics.csv", + "translation_z_mae_mm", seed=20260717, resamples=2000, + statistic="p95", + ) + ) + return { + "schema_version": "phase9_hot_unique_scale_summary_v1", + "status": "complete", + "comparison": "matched_J40_final505k_source_exposure", + "checkpoint_sha256": checkpoint_hashes, + "rows": rows, + "paired_recording_bootstrap_vs_hot100k": paired, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--control-root", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("summary outputs must be new") + result = summarize( + json.loads(args.registry.read_text(encoding="utf-8")), + args.evaluation_root, args.control_root, + ) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + fields = [ + "condition", "hot_unique_clips", "source_id", "checkpoint_sha256", + *METRICS, "aria_absolute_mpjpe_mm", "quest3_absolute_mpjpe_mm", + *[f"delta_{metric}" for metric in METRICS], + ] + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for row in result["rows"]: + writer.writerow({ + "condition": row["condition"], + "hot_unique_clips": row["hot_unique_clips"], + "source_id": row["source_id"], + "checkpoint_sha256": row["checkpoint"]["sha256"], + **row["metrics"], + **{ + f"delta_{metric}": row["delta_vs_hot100k"][metric] + for metric in METRICS + }, + }) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_last2_decision.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_last2_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..0c773ab0e98bd5e250e22c0e2fbd1ae392be8b95 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_last2_decision.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Apply the strict macro-and-worst gate to one last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.summarize_phase9_resolution_decision import ( + NATIVE_EXTERNAL, + checked_report, + h2o_guardrails, + metric, +) + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def strict_gate( + control_domains: dict[str, float], candidate_domains: dict[str, float], +) -> dict[str, Any]: + if set(control_domains) != {"h2o", "hot3d", "hoi4d", "arctic"}: + raise ValueError("last-2 control domains differ") + if set(candidate_domains) != set(control_domains): + raise ValueError("last-2 candidate domains differ") + control_macro = sum(control_domains.values()) / 4 + candidate_macro = sum(candidate_domains.values()) / 4 + control_worst = max(control_domains.values()) + candidate_worst = max(candidate_domains.values()) + macro = candidate_macro < control_macro + worst = candidate_worst < control_worst + return { + "control_macro_absolute_mm": control_macro, + "candidate_macro_absolute_mm": candidate_macro, + "macro_delta_mm": candidate_macro - control_macro, + "macro_strictly_improved": macro, + "control_worst_domain_absolute_mm": control_worst, + "candidate_worst_domain_absolute_mm": candidate_worst, + "worst_domain_delta_mm": candidate_worst - control_worst, + "worst_domain_strictly_improved": worst, + "accepted": macro and worst, + } + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if len(evaluations) != 25: + raise ValueError("last-2 evaluation count differs") + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"last-2 evaluation incomplete: {item['id']}") + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + control_reports = {} + for identifier, item in plan["control_reports"].items(): + path = Path(item["path"]) + if not path.is_file() or item["sha256"] != sha256(path): + raise ValueError(f"last-2 control report hash differs: {identifier}") + control_reports[identifier] = checked_report( + path, item["evaluation_role"], item["input_mode"], + ) + control_external = { + dataset: control_reports[f"full_{dataset}_{mode}"] + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = { + (fold, mode): control_reports[f"{fold}_{mode}"] + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + gate = strict_gate(control_domains, candidate_domains) + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + candidate = plan["candidate"] + return { + "schema_version": "phase9_last2_candidate_decision_v1", + "status": "complete", "candidate": candidate, + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": ( + f"accept_last2_{candidate}" if gate["accepted"] + else f"reject_last2_{candidate}" + ), + "backbone_learning_rate": plan["backbone_learning_rate"], + "resolution_hw": plan["resolution_hw"], + "shared_augmentation": plan["shared_augmentation"], + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "control_evaluation_plan": plan["control_evaluation_plan"], + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "dino_large_admitted": False, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("last-2 candidate decision output must be new") + result = summarize(args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_resolution_decision.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_resolution_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..0341ee8e004ae8b5d4fc699ded58fb19dfec1eab --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_resolution_decision.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Apply the frozen Stage 7 resolution gate and report all guardrails.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +FOLDS = ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", +) +NATIVE_EXTERNAL = { + "hot3d": "rgb_k", "hoi4d": "rgb_d_k", "arctic": "rgb_k", +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def checked_report(path: Path, role: str, mode: str) -> dict[str, Any]: + report = read_json(path) + if ( + report.get("status") != f"evaluated_{role}" + or report.get("evaluation_role") != role + or report.get("input_mode") != mode + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution decision input differs: {path}") + return report + + +def metric(report: dict[str, Any], name: str, statistic: str = "mean") -> float: + value = report.get("metrics", {}).get(name, {}).get(statistic) + if value is None or not math.isfinite(float(value)): + raise ValueError(f"missing finite metric {name}.{statistic}") + return float(value) + + +def h2o_guardrails(reports: dict[tuple[str, str], dict[str, Any]]) -> dict[str, Any]: + result = {} + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + selected = [reports[(fold, mode)] for fold in FOLDS] + absolute = [metric(report, "absolute_mpjpe_mm") for report in selected] + root = [metric(report, "root_relative_mpjpe_mm") for report in selected] + fingertip = [metric(report, "fingertip_mpjpe_mm") for report in selected] + z_tail = [ + metric(report, "translation_z_mae_mm", "p95") for report in selected + ] + result[mode] = { + "absolute_macro_mm": sum(absolute) / len(absolute), + "absolute_worst_fold_mm": max(absolute), + "root_relative_macro_mm": sum(root) / len(root), + "fingertip_macro_mm": sum(fingertip) / len(fingertip), + "translation_z_p95_macro_mm": sum(z_tail) / len(z_tail), + "translation_z_p95_worst_fold_mm": max(z_tail), + "fold_absolute_mm": dict(zip(FOLDS, absolute, strict=True)), + } + return result + + +def gate_decision( + control_domains: dict[str, float], candidate_domains: dict[str, float], + relative_limit: float, +) -> dict[str, Any]: + if set(control_domains) != {"h2o", "hot3d", "hoi4d", "arctic"}: + raise ValueError("resolution control domains differ") + if set(candidate_domains) != set(control_domains): + raise ValueError("resolution candidate domains differ") + control_macro = sum(control_domains.values()) / 4 + candidate_macro = sum(candidate_domains.values()) / 4 + control_worst = max(control_domains.values()) + candidate_worst = max(candidate_domains.values()) + worst_relative_regression = (candidate_worst - control_worst) / control_worst + macro_improved = candidate_macro < control_macro + worst_passed = worst_relative_regression <= relative_limit + return { + "control_macro_absolute_mm": control_macro, + "candidate_macro_absolute_mm": candidate_macro, + "macro_delta_mm": candidate_macro - control_macro, + "macro_strictly_improved": macro_improved, + "control_worst_domain_absolute_mm": control_worst, + "candidate_worst_domain_absolute_mm": candidate_worst, + "worst_domain_relative_regression": worst_relative_regression, + "worst_domain_relative_regression_limit": relative_limit, + "worst_domain_gate_passed": worst_passed, + "accepted": macro_improved and worst_passed, + } + + +def summarize( + plan_path: Path, control_external_root: Path, + control_fold_final_root: Path, control_fold_milestone_root: Path, +) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"resolution evaluation is incomplete: {item['id']}") + + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + + control = plan["control_evidence"] + mixture = control["mixture"] + external_id = control["external_checkpoint_id"] + fold_id = control["fold_checkpoint_id"] + control_external = { + dataset: checked_report( + control_external_root / mixture / external_id + / f"{dataset}_{mode}" / "evaluation.json", + "phase9_external_heldout", mode, + ) + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = {} + for fold in FOLDS: + condition = f"{mixture}_{fold}" + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + path = ( + control_fold_final_root / condition / mode / "evaluation.json" + if fold_id == "final" + else control_fold_milestone_root / condition / fold_id + / mode / "evaluation.json" + ) + control_h2o_reports[(fold, mode)] = checked_report( + path, "phase9_h2o_fold_heldout", mode, + ) + + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + for dataset, expected in control["absolute_mm"].items(): + if not math.isclose(control_domains[dataset], float(expected), abs_tol=1e-8): + raise ValueError(f"resolution control evidence differs: {dataset}") + gate = gate_decision( + control_domains, candidate_domains, + float(plan["gate"]["worst_domain_relative_regression_limit"]), + ) + + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + return { + "schema_version": "phase9_resolution_decision_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "accept_896x512" if gate["accepted"] else "retain_640x368", + "accepted_resolution_hw": [512, 896] if gate["accepted"] else [368, 640], + "control_resolution_hw": [368, 640], + "candidate_resolution_hw": [512, 896], + "winner": plan["winner"], + "control_checkpoint": plan["winner_checkpoint"], + "candidate_full_checkpoint": { + "path": plan["training_jobs"]["full"]["checkpoint"], + "sha256": plan["training_jobs"]["full"]["checkpoint_sha256"], + }, + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--control-external-root", type=Path, required=True) + parser.add_argument("--control-fold-final-root", type=Path, required=True) + parser.add_argument("--control-fold-milestone-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("resolution decision output must be new") + result = summarize( + args.plan, args.control_external_root, args.control_fold_final_root, + args.control_fold_milestone_root, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_resolution_evaluation_metrics.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_resolution_evaluation_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc33c1d7f19286e4dc4a9a36f79f012afae244c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_resolution_evaluation_metrics.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +"""Write the complete paired 640/896 Stage 7 metric inventory.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +FIELDS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "pa_mpjpe_mm": ("pa_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_x_mae_mm": ("translation_x_mae_mm", "mean"), + "translation_y_mae_mm": ("translation_y_mae_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def metric_values(report: dict[str, Any]) -> dict[str, float]: + result = {} + for label, (metric, statistic) in FIELDS.items(): + value = report.get("metrics", {}).get(metric, {}).get(statistic) + if not isinstance(value, (int, float)) or not math.isfinite(float(value)): + raise ValueError(f"resolution metric is missing or nonfinite: {label}") + result[label] = float(value) + return result + + +def control_path(plan: dict[str, Any], item: dict[str, Any], identifier: str) -> Path: + control = plan["control_evidence"] + mixture = control["mixture"] + if identifier.startswith("full_"): + name = identifier.removeprefix("full_") + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/external_milestones") + / mixture / control["external_checkpoint_id"] / name / "evaluation.json" + ) + fold = item["training_role"] + mode = item["input_mode"] + condition = f"{mixture}_{fold}" + if control["fold_checkpoint_id"] == "final": + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold") + / condition / mode / "evaluation.json" + ) + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold_milestones") + / condition / control["fold_checkpoint_id"] / mode / "evaluation.json" + ) + + +def checked_report(path: Path, item: dict[str, Any]) -> dict[str, Any]: + report = read_json(path) + if ( + report.get("status") != f"evaluated_{item['evaluation_role']}" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution paired report binding differs: {path}") + return report + + +def hot_headsets(report: dict[str, Any]) -> dict[str, Any]: + result = {} + for headset in ("aria", "quest3"): + metrics = report.get("metrics", {}).get(f"bucket_headset_{headset}", {}) + result[headset] = { + key: float(metrics[source][statistic]) + for key, (source, statistic) in FIELDS.items() + if source in metrics and statistic in metrics[source] + } + return result + + +def summarize(plan_path: Path, decision_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + decision = read_json(decision_path) + if ( + decision.get("status") != "complete" + or decision.get("evaluation_plan", {}).get("sha256") != sha256(plan_path) + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution decision binding differs") + owners = { + identifier: worker["owner"] + for worker in plan["workers"] for identifier in worker["evaluation_ids"] + } + rows = [] + for item in plan["evaluations"]: + if not evaluation_complete(item): + raise ValueError(f"resolution evaluation is incomplete: {item['id']}") + candidate_path = Path(item["output_dir"]) / "evaluation.json" + candidate = checked_report(candidate_path, item) + baseline_path = control_path(plan, item, item["id"]) + baseline = checked_report(baseline_path, item) + candidate_metrics = metric_values(candidate) + baseline_metrics = metric_values(baseline) + row = { + "evaluation_id": item["id"], "owner": owners[item["id"]], + "training_role": item["training_role"], "input_mode": item["input_mode"], + "evaluation_role": item["evaluation_role"], + "checkpoint_sha256": item["checkpoint_sha256"], + "config_sha256": item["config_sha256"], + "cache_manifest_sha256": item["cache_manifest_sha256"], + "clips": candidate["clips"], "frames": candidate["frames"], + "wall_seconds": candidate["runtime"]["wall_seconds"], + "gpu_hours": candidate["runtime"]["wall_seconds"] / 3600.0, + "candidate_report_sha256": sha256(candidate_path), + "control_report_sha256": sha256(baseline_path), + "candidate": candidate_metrics, "control": baseline_metrics, + "delta": { + key: candidate_metrics[key] - baseline_metrics[key] + for key in FIELDS + }, + "candidate_grouped_recording_ci": candidate["grouped_bootstrap_ci"], + "control_grouped_recording_ci": baseline["grouped_bootstrap_ci"], + } + if item["id"].startswith("full_hot3d_"): + row["hot3d_headset"] = { + "candidate": hot_headsets(candidate), "control": hot_headsets(baseline), + } + rows.append(row) + return { + "schema_version": "phase9_resolution_evaluation_metrics_v1", + "status": "complete", "created_utc": datetime.now(timezone.utc).isoformat(), + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "decision_report": {"path": str(decision_path.resolve()), "sha256": sha256(decision_path)}, + "evaluation_count": len(rows), "paired_control_count": len(rows), + "paired_by_evaluation_id_and_identical_heldout_contract": True, + "candidate_evaluation_gpu_hours": sum(row["gpu_hours"] for row in rows), + "candidate_training_gpu_hours": decision["candidate_training_gpu_hours"], + "control_domain_absolute_mm": decision["control_domain_absolute_mm"], + "candidate_domain_absolute_mm": decision["candidate_domain_absolute_mm"], + "gate": decision["gate"], "h2o_guardrails": decision["h2o_guardrails"], + "rows": rows, + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def write_csv(path: Path, report: dict[str, Any]) -> None: + fieldnames = [ + "evaluation_id", "owner", "training_role", "input_mode", "clips", "frames", + "wall_seconds", "gpu_hours", "checkpoint_sha256", "config_sha256", + "cache_manifest_sha256", "candidate_report_sha256", "control_report_sha256", + ] + [f"{prefix}_{field}" for prefix in ("candidate", "control", "delta") for field in FIELDS] + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + for source in report["rows"]: + row = {key: source[key] for key in fieldnames if key in source} + for prefix in ("candidate", "control", "delta"): + for field in FIELDS: + row[f"{prefix}_{field}"] = source[prefix][field] + writer.writerow(row) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--decision", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("resolution metric outputs must be new") + result = summarize(args.plan, args.decision) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output_json, result) + write_csv(args.output_csv, result) + print(json.dumps({ + "status": "complete", "json_sha256": sha256(args.output_json), + "csv_sha256": sha256(args.output_csv), "evaluation_count": 25, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_shared_augmentation_decision.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_shared_augmentation_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..161b1cb515462f41add17769350833b0a3a9cc3c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_shared_augmentation_decision.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Apply Stage 8 gate and freeze whether Stage 9 has a valid predecessor.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.summarize_phase9_resolution_decision import ( + NATIVE_EXTERNAL, + checked_report, + gate_decision, + h2o_guardrails, + metric, +) + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def stage9_preceding_gate( + augmentation_accepted: bool, augmentation_gate: dict[str, Any], + resolution_decision: dict[str, Any], +) -> dict[str, Any]: + augmentation_worst_improved = ( + augmentation_gate["candidate_worst_domain_absolute_mm"] + < augmentation_gate["control_worst_domain_absolute_mm"] + ) + if augmentation_accepted: + source = "shared_augmentation" + passed = ( + augmentation_gate["macro_strictly_improved"] + and augmentation_worst_improved + ) + else: + source = "resolution" + resolution_gate = resolution_decision["gate"] + passed = ( + resolution_decision["decision"] == "accept_896x512" + and resolution_gate["macro_strictly_improved"] + and resolution_gate["candidate_worst_domain_absolute_mm"] + < resolution_gate["control_worst_domain_absolute_mm"] + ) + return { + "source_mechanism": source, + "macro_and_worst_domain_strictly_improved": passed, + "stage9_last2_admitted": passed, + } + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if len(evaluations) != 25: + raise ValueError("shared augmentation evaluation count differs") + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"augmentation evaluation incomplete: {item['id']}") + + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + control_reports = {} + for identifier, item in plan["control_reports"].items(): + path = Path(item["path"]) + if not path.is_file() or item["sha256"] != sha256(path): + raise ValueError(f"augmentation control report hash differs: {identifier}") + control_reports[identifier] = checked_report( + path, item["evaluation_role"], item["input_mode"], + ) + control_external = { + dataset: control_reports[f"full_{dataset}_{mode}"] + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = { + (fold, mode): control_reports[f"{fold}_{mode}"] + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + resolution_path = Path(plan["resolution_decision"]["path"]) + if ( + not resolution_path.is_file() + or plan["resolution_decision"]["sha256"] != sha256(resolution_path) + ): + raise ValueError("augmentation resolution decision binding differs") + resolution = read_json(resolution_path) + expected_control_domains = ( + resolution["candidate_domain_absolute_mm"] + if resolution["decision"] == "accept_896x512" + else resolution["control_domain_absolute_mm"] + ) + for dataset, expected in expected_control_domains.items(): + if not math.isclose(control_domains[dataset], float(expected), abs_tol=1e-8): + raise ValueError(f"augmentation selected control differs: {dataset}") + gate = gate_decision( + control_domains, candidate_domains, + float(plan["gate"]["worst_domain_relative_regression_limit"]), + ) + preceding = stage9_preceding_gate(gate["accepted"], gate, resolution) + + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + accepted = bool(gate["accepted"]) + return { + "schema_version": "phase9_shared_augmentation_decision_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "accept_shared_augmentation" if accepted else "reject_shared_augmentation", + "shared_augmentation_accepted": accepted, + "selected_mechanism": "shared_augmentation" if accepted else "control", + "resolution_hw": plan["resolution_hw"], + "winner": plan["winner"], + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "stage9_preceding_mechanism_gate": preceding, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "control": plan["control"], + "resolution_decision": plan["resolution_decision"], + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("shared augmentation decision output must be new") + result = summarize(args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_unified_selection.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_unified_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..829747f7fdc5bbde018e1e0026d893dd7ea8fc8c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_phase9_unified_selection.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Select a Phase 9 unified candidate with dataset-equal group-CV evidence.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +CANDIDATES = { + "J25": [ + ("all20", "all_sources_20k"), + ("all50", "all_sources_50k"), + ("all100", "all_sources_100k"), + ("final405k", "final"), + ], + "J40": [ + ("nonhot20", "nonhot_20k"), + ("nonhot50_hot100", "nonhot_50k_hot_100k"), + ("nonhot100_hot200", "nonhot_100k_hot_200k"), + ("final505k", "final"), + ], + "J55": [ + ("nonhot20", "nonhot_20k"), + ("nonhot50", "nonhot_50k"), + ("nonhot100_hot367", "nonhot_100k_hot_367k"), + ("final675k", "final"), + ], +} +NATIVE_EXTERNAL = { + "hot3d": "hot3d_rgb_k", + "hoi4d": "hoi4d_rgb_d_k", + "arctic": "arctic_rgb_k", +} +METRICS = { + "absolute": "absolute_mpjpe_mm", + "root_relative": "root_relative_mpjpe_mm", + "fingertip": "fingertip_mpjpe_mm", +} + + +def evaluation(path: Path, expected_role: str) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(path) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("evaluation_role") != expected_role + or report.get("status") != f"evaluated_{expected_role}" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"evaluation role/isolation mismatch: {path}") + return report + + +def validate_multifold_index(index: dict[str, Any]) -> list[dict[str, Any]]: + expected_folds = { + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + } + folds = index.get("folds", []) + ids = [fold.get("id") for fold in folds] + if ( + index.get("status") != "complete" + or index.get("h2o_official_validation_used") is not False + or index.get("official_test_used") is not False + or index.get("selection_metrics") + != ["fold_macro_absolute_mpjpe", "worst_fold_absolute_mpjpe"] + or len(ids) != 6 + or set(ids) != expected_folds + or any( + not fold.get("heldout", {}).get("sha256") + or not fold.get("heldout", {}).get("path") + for fold in folds + ) + ): + raise ValueError("multifold index selection/isolation contract differs") + return folds + + +def mean_metric(report: dict[str, Any], metric: str) -> float: + value = report["metrics"][metric] + if value is None or not math.isfinite(float(value["mean"])): + raise ValueError(f"missing finite metric: {metric}") + return float(value["mean"]) + + +def rank_values(values: dict[str, float]) -> dict[str, float]: + ordered = sorted(values.items(), key=lambda item: (item[1], item[0])) + ranks: dict[str, float] = {} + position = 0 + while position < len(ordered): + end = position + 1 + while end < len(ordered) and ordered[end][1] == ordered[position][1]: + end += 1 + rank = (position + 1 + end) / 2.0 + for key, _ in ordered[position:end]: + ranks[key] = rank + position = end + return ranks + + +def pareto_frontier(rows: list[dict[str, Any]], datasets: tuple[str, ...]) -> set[str]: + frontier = set() + for row in rows: + dominated = any( + other["id"] != row["id"] + and all(other["absolute_mm"][dataset] <= row["absolute_mm"][dataset] for dataset in datasets) + and any(other["absolute_mm"][dataset] < row["absolute_mm"][dataset] for dataset in datasets) + for other in rows + ) + if not dominated: + frontier.add(row["id"]) + return frontier + + +def summarize( + external_root: Path, fold_final_root: Path, fold_milestone_root: Path, + folds: list[dict[str, Any]], +) -> dict[str, Any]: + rows: list[dict[str, Any]] = [] + for mixture, candidates in CANDIDATES.items(): + for external_id, fold_id in candidates: + candidate_id = f"{mixture}:{external_id}" + external_reports = { + dataset: evaluation( + external_root / mixture / external_id / source_id / "evaluation.json", + "phase9_external_heldout", + ) + for dataset, source_id in NATIVE_EXTERNAL.items() + } + if ( + len({json.dumps(report["checkpoint"], sort_keys=True) for report in external_reports.values()}) != 1 + or len({json.dumps(report["config"], sort_keys=True) for report in external_reports.values()}) != 1 + ): + raise ValueError(f"external checkpoint/config binding differs: {candidate_id}") + fold_reports = [] + for fold_record in folds: + fold = fold_record["id"] + condition = f"{mixture}_{fold}" + root = fold_final_root if fold_id == "final" else fold_milestone_root / condition / fold_id + path = ( + root / condition / "rgb_d_k" / "evaluation.json" + if fold_id == "final" + else root / "rgb_d_k" / "evaluation.json" + ) + report = evaluation(path, "phase9_h2o_fold_heldout") + if ( + report.get("input_mode") != "rgb_d_k" + or report.get("cache_manifest", {}).get("path") + != fold_record["heldout"]["path"] + or report.get("cache_manifest", {}).get("sha256") + != fold_record["heldout"]["sha256"] + ): + raise ValueError(f"fold heldout binding differs: {condition}") + fold_reports.append(report) + h2o_absolute = [mean_metric(report, METRICS["absolute"]) for report in fold_reports] + row = { + "id": candidate_id, "mixture": mixture, + "external_checkpoint_id": external_id, + "fold_checkpoint_id": fold_id, + "checkpoint": external_reports["hot3d"]["checkpoint"], + "config": external_reports["hot3d"]["config"], + "absolute_mm": { + "h2o": sum(h2o_absolute) / len(h2o_absolute), + **{ + dataset: mean_metric(report, METRICS["absolute"]) + for dataset, report in external_reports.items() + }, + }, + "h2o_worst_fold_absolute_mm": max(h2o_absolute), + "h2o_fold_absolute_mm": dict(zip( + [fold["id"] for fold in folds], h2o_absolute, strict=True, + )), + "h2o_fold_macro_root_relative_mm": sum( + mean_metric(report, METRICS["root_relative"]) for report in fold_reports + ) / len(fold_reports), + "h2o_fold_macro_fingertip_mm": sum( + mean_metric(report, METRICS["fingertip"]) for report in fold_reports + ) / len(fold_reports), + } + rows.append(row) + datasets = ("h2o", "hot3d", "hoi4d", "arctic") + for dataset in datasets: + ranks = rank_values({row["id"]: row["absolute_mm"][dataset] for row in rows}) + best = min(row["absolute_mm"][dataset] for row in rows) + for row in rows: + row.setdefault("dataset_rank", {})[dataset] = ranks[row["id"]] + row.setdefault("normalized_regression_from_best", {})[dataset] = ( + row["absolute_mm"][dataset] - best + ) / best + frontier = pareto_frontier(rows, datasets) + for row in rows: + row["dataset_equal_mean_rank"] = sum(row["dataset_rank"].values()) / len(datasets) + row["worst_dataset_normalized_regression"] = max( + row["normalized_regression_from_best"].values() + ) + row["pareto_frontier"] = row["id"] in frontier + ordered = sorted(rows, key=lambda row: ( + row["dataset_equal_mean_rank"], + row["worst_dataset_normalized_regression"], + sum(row["absolute_mm"].values()), + row["id"], + )) + return { + "schema_version": "phase9_unified_selection_v1", + "status": "complete", + "selection_rule": "dataset_equal_mean_rank_then_worst_normalized_regression_then_sum", + "normalization": "candidate_minus_per_dataset_best divided by per_dataset_best", + "winner": ordered[0]["id"], + "winner_checkpoint": ordered[0]["checkpoint"], + "winner_config": ordered[0]["config"], + "pareto_frontier": sorted(frontier), + "candidates": ordered, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-root", type=Path, required=True) + parser.add_argument("--fold-final-root", type=Path, required=True) + parser.add_argument("--fold-milestone-root", type=Path, required=True) + parser.add_argument("--multifold-index", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("selection outputs must be new") + index = json.loads(args.multifold_index.read_text(encoding="utf-8")) + result = summarize( + args.external_root, args.fold_final_root, args.fold_milestone_root, + validate_multifold_index(index), + ) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + csv_temporary = args.output_csv.with_suffix(args.output_csv.suffix + ".tmp") + json_temporary = args.output_json.with_suffix(args.output_json.suffix + ".tmp") + with csv_temporary.open("x", newline="", encoding="utf-8") as handle: + fields = [ + "id", "mixture", "external_checkpoint_id", "fold_checkpoint_id", + "h2o_absolute_mm", "hot3d_absolute_mm", "hoi4d_absolute_mm", + "arctic_absolute_mm", "h2o_worst_fold_absolute_mm", + "dataset_equal_mean_rank", "worst_dataset_normalized_regression", + "pareto_frontier", + ] + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for row in result["candidates"]: + writer.writerow({ + **{key: row[key] for key in fields if key in row}, + **{f"{dataset}_absolute_mm": row["absolute_mm"][dataset] for dataset in ("h2o", "hot3d", "hoi4d", "arctic")}, + }) + json_temporary.write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + csv_temporary.replace(args.output_csv) + json_temporary.replace(args.output_json) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_pilots.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_pilots.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3328105d986f49810eb62ccfe40cd8a9d5dd0e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_pilots.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Create reproducible comparison tables and curves from completed pilots.""" + +from __future__ import annotations + +import argparse +import csv +import json +from datetime import datetime +from pathlib import Path + +import matplotlib.pyplot as plt + + +EXPERIMENTS_30MIN = { + "B Sequential RGB": "b_sequential_v1", + "C Alternating RGB": "c_alternating_v1", + "D Alternating RGB+K": "d_rgb_k_v1", + "E Alternating RGB+Depth": "e_rgb_depth_fixed_v1", + "F Alternating RGB+Depth+K": "f_rgb_depth_k_fixed_v1", +} + +EXPERIMENTS_2H = { + "C Alternating RGB": { + "result": "c_alternating_v3_resume_step50", + "segments": ["c_alternating_v1", "c_alternating_v2_resume_step25", "c_alternating_v3_resume_step50"], + }, + "D Alternating RGB+K": {"result": "d_rgb_k_v1", "segments": ["d_rgb_k_v1"]}, + "F Alternating RGB+Depth+K": {"result": "f_rgb_depth_k_fixed_v1", "segments": ["f_rgb_depth_k_fixed_v1"]}, +} + + +def load_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--pilot-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--suite", choices=("30min", "2h"), default="30min") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + rows = [] + bucket_rows = [] + curves = {} + if args.suite == "30min": + experiments = { + label: {"result": directory, "segments": [directory]} + for label, directory in EXPERIMENTS_30MIN.items() + } + else: + experiments = EXPERIMENTS_2H + for label, experiment in experiments.items(): + directory = experiment["result"] + root = args.pilot_root / directory + summary = load_json(root / "summary.json") + evaluation = load_json(root / "full_validation_best" / "evaluation.json") + validation = [] + training_records = [] + for segment in experiment["segments"]: + segment_root = args.pilot_root / segment + if (segment_root / "validation.jsonl").is_file(): + validation.extend(json.loads(line) for line in (segment_root / "validation.jsonl").read_text().splitlines()) + if (segment_root / "metrics.jsonl").is_file(): + training_records.extend(json.loads(line) for line in (segment_root / "metrics.jsonl").read_text().splitlines()) + validation.sort(key=lambda item: item["step"]) + training_records.sort(key=lambda item: item["step"]) + best_record = min(validation, key=lambda item: item["metrics"]["absolute_camera_mpjpe_mm"]) + metrics = evaluation["metrics"] + first_timestamp = datetime.fromisoformat(training_records[0]["timestamp"]) + last_timestamp = datetime.fromisoformat(training_records[-1]["timestamp"]) + wall_minutes = (last_timestamp - first_timestamp).total_seconds() / 60 + rows.append({ + "experiment": label, + "best_step": best_record["step"], + "trained_steps": summary["completed_step"], + "elapsed_minutes": wall_minutes, + "peak_vram_gib": summary["peak_vram_gib"], + "frames_per_s": summary["frames_per_s"], + "subset_best_absolute_mpjpe_mm": best_record["metrics"]["absolute_camera_mpjpe_mm"], + "full_absolute_mpjpe_mm": metrics["all_absolute_mpjpe_mm"], + "full_root_relative_mpjpe_mm": metrics["all_root_relative_mpjpe_mm"], + "full_joint2d_error_px": metrics["all_joint2d_error_px"], + "z_mae_mm": (metrics["left_translation_z_mae_mm"] + metrics["right_translation_z_mae_mm"]) / 2, + "velocity_error_mm_per_frame": metrics["temporal_velocity_error_mm_per_frame"], + "acceleration_error_mm_per_frame2": metrics["temporal_acceleration_error_mm_per_frame2"], + "rgb_attention_same_peak_fraction": metrics["rgb_attention_same_peak_fraction"], + "temporal_attention_entropy": metrics["temporal_attention_normalized_entropy"], + "depth_gate_mean": metrics["depth_gate_mean"], + "best_checkpoint": summary["best_checkpoint"], + }) + for bucket, values in evaluation["buckets"].items(): + bucket_rows.append({"experiment": label, "bucket": bucket, **values}) + curves[label] = validation + + with (args.output_dir / "comparison.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + with (args.output_dir / "bucket_comparison.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(bucket_rows[0])) + writer.writeheader() + writer.writerows(bucket_rows) + (args.output_dir / "comparison.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8") + + fig, axes = plt.subplots(1, 3, figsize=(16, 4.5)) + metric_names = ( + ("absolute_camera_mpjpe_mm", "Absolute MPJPE (mm)"), + ("root_relative_mpjpe_mm", "Root-relative MPJPE (mm)"), + ("translation_z_mae_mm", "Translation z MAE (mm)"), + ) + for label, records in curves.items(): + steps = [record["step"] for record in records] + for axis, (metric, title) in zip(axes, metric_names, strict=True): + axis.plot(steps, [record["metrics"][metric] for record in records], label=label) + axis.set_title(title) + axis.set_xlabel("step") + axis.grid(alpha=0.25) + axes[0].legend(fontsize=7) + fig.tight_layout() + fig.savefig(args.output_dir / "validation_curves.png", dpi=180) + plt.close(fig) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_sota_evaluation.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_sota_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..b46e9cca845bda5ca51a6087e12136c3f45da2b0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_sota_evaluation.py @@ -0,0 +1,813 @@ +#!/usr/bin/env python3 +"""Build the reproducible FoundationHand external-baseline comparison report.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +from foundation_hand.evaluation.sota import paired_take_bootstrap, write_csv_rows + + +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "joint_acceleration_error_mm_per_frame2", +) + +PROTOCOLS = { + "FoundationHand-Phase3": ( + "h2o_trained", + "H2O train;validation 子集选模", + ), + "QORT-Former": ("h2o_trained", "H2O train"), + "WiLoR-H2O-K": ("zero_shot", "无 H2O 微调;训练含 H2O3D"), + "HaWoR-camera": ("zero_shot", "发布权重无 H2O 微调"), + "WildHands-zero-shot": ( + "zero_shot", + "无 H2O;训练用 ARCTIC/AssemblyHands/EPIC", + ), + "Hamba-zero-shot": ( + "zero_shot", + "无 H2O;训练含 H2O3D", + ), + "PAD-Hand-WiLoR": ( + "zero_shot", + "无 H2O;论文训练用 DexYCB/HO3D,release checkpoint 未标具体版本", + ), + "HandDGP-zero-shot": ( + "zero_shot", + "无 H2O/H2O3D;发布权重仅用 FreiHAND 训练", + ), + "Dyn-HaMR-TTO": ( + "test_time_optimization", + "无 H2O;HaMeR initializer 含 H2O3D;每段视频独立 TTO", + ), + "WiLoR-native-camera": ("diagnostic", "同一 WiLoR 权重;原生 demo camera"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_rows(path: Path) -> list[dict[str, Any]]: + with path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + for row in rows: + for key, value in tuple(row.items()): + if value == "": + row[key] = None + return rows + + +def parameters(metadata: dict[str, Any]) -> tuple[int, int]: + if "end_to_end_parameter_count" in metadata: + return ( + int(metadata["reconstruction_parameter_count"]), + int(metadata["end_to_end_parameter_count"]), + ) + count = int(metadata["parameter_count"]) + return count, count + + +def metric_mean(report: dict[str, Any], metric: str) -> float | None: + summary = report["metrics_success_conditioned"].get(metric) + return None if summary is None else summary["mean"] + + +def temporal_mean(report: dict[str, Any], metric: str) -> float | None: + summary = report["temporal_metrics_success_conditioned"].get(metric) + return None if summary is None else summary["mean"] + + +def fmt(value: float | int | None, digits: int = 3) -> str: + if value is None: + return "N/A" + return f"{float(value):.{digits}f}" + + +def fmt_params(value: int) -> str: + return f"{value / 1_000_000:.1f}M" + + +def load_evaluation(label: str, directory: Path) -> dict[str, Any]: + report_path = directory / "evaluation.json" + frame_path = directory / "per_hand_frame_metrics.csv" + temporal_path = directory / "per_temporal_transition_metrics.csv" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("split_role") != "official_validation" + or report.get("official_test_used") is not False + ): + raise ValueError(f"Not a complete official-validation evaluation: {directory}") + model_parameters, end_to_end_parameters = parameters(report["prediction_metadata"]) + track, h2o_exposure = PROTOCOLS.get( + label, + ("uncategorized", report["prediction_metadata"].get("training_exposure", "Unknown")), + ) + row: dict[str, Any] = { + "label": label, + "model_name": report["model_name"], + "evaluation_track": track, + "h2o_exposure": h2o_exposure, + "input": report["prediction_metadata"].get("input"), + "temporal": report["prediction_metadata"].get("temporal"), + "model_parameter_count": model_parameters, + "end_to_end_parameter_count": end_to_end_parameters, + "frames": report["frames"], + "takes": report["takes"], + "annotation_valid_hand_frames": report["coverage"]["annotation_valid_hand_frames"], + "successful_hand_frames": report["coverage"]["successful_hand_frames"], + "coverage": report["coverage"]["hand_frame_fraction"], + "temporal_pair_coverage": report["coverage"]["temporal_pair_fraction"], + **{metric: metric_mean(report, metric) for metric in METRICS}, + **{metric: temporal_mean(report, metric) for metric in TEMPORAL_METRICS}, + **report["failure_aware"], + "evaluation_json": str(report_path.resolve()), + "evaluation_json_sha256": sha256(report_path), + "frame_metrics_csv": str(frame_path.resolve()), + "frame_metrics_csv_sha256": sha256(frame_path), + "temporal_metrics_csv": str(temporal_path.resolve()), + "temporal_metrics_csv_sha256": sha256(temporal_path), + } + for side in ("left", "right"): + row[f"{side}_coverage"] = report["per_side"][side]["coverage"] + row[f"{side}_absolute_mpjpe_mm"] = report["per_side"][side][ + "absolute_mpjpe_mm" + ]["mean"] + row[f"{side}_root_relative_mpjpe_mm"] = report["per_side"][side][ + "root_relative_mpjpe_mm" + ]["mean"] + return { + "label": label, + "directory": directory, + "report": report, + "frame_rows": read_rows(frame_path), + "summary": row, + } + + +def markdown_report( + evaluations: list[dict[str, Any]], + paired_rows: list[dict[str, Any]], + refinement_rows: list[dict[str, Any]], + dynhamr_hawor_rows: list[dict[str, Any]], + speed_report: dict[str, Any] | None, + *, + manifest: Path, + manifest_hash: str, + ground_truth: Path, + ground_truth_hash: str, + bootstrap_seed: int, + bootstrap_samples: int, +) -> str: + rows = [evaluation["summary"] for evaluation in evaluations] + foundation_evaluation = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "FoundationHand-Phase3" + ) + foundation_trainable = foundation_evaluation["report"]["prediction_metadata"].get( + "trainable_parameter_count_at_export" + ) + foundation_row = foundation_evaluation["summary"] + rows_by_label = {row["label"]: row for row in rows} + + comparative_note = "" + if "HaWoR-camera" in rows_by_label: + hawor_row = rows_by_label["HaWoR-camera"] + hawor_root = next( + row for row in paired_rows + if row["candidate"] == "HaWoR-camera" + and row["metric"] == "root_relative_mpjpe_mm" + ) + comparative_note = ( + "作为跨赛道描述性配对,FoundationHand 在 absolute joints/mesh、fingertip、z 和时间误差上更低;" + f"HaWoR 的逐帧 root-relative 均值虽低 " + f"{foundation_row['root_relative_mpjpe_mm'] - hawor_row['root_relative_mpjpe_mm']:.3f} mm," + f"但 take-equal paired delta 为 {hawor_root['candidate_minus_baseline']:+.3f} mm、" + f"95% CI [{hawor_root['ci95_low']:.3f}, {hawor_root['ci95_high']:.3f}]," + "只能判为等价,不能声称 HaWoR 显著更好。HaWoR 的 2D 优势有 paired CI 支持。" + ) + + qort_note = "" + if "QORT-Former" in rows_by_label: + qort_row = rows_by_label["QORT-Former"] + qort_note = ( + "具体到 QORT-Former:公开 checkpoint 在本 validation 上为 left/right " + f"{qort_row['left_absolute_mpjpe_mm']:.3f}/" + f"{qort_row['right_absolute_mpjpe_mm']:.3f} mm,没有达到论文 test 的 " + "20.1/19.9 mm 水平。它说明“公开权重在当前开发集未重现论文量级”," + "但 split 不同,所以不是论文数字错误的充分证据。" + ) + wildhands_note = "" + if "WildHands-zero-shot" in rows_by_label: + wildhands_row = rows_by_label["WildHands-zero-shot"] + wildhands_note = ( + "WildHands 发布权重在本协议的 root-relative MPJPE 为 " + f"{wildhands_row['root_relative_mpjpe_mm']:.3f} mm,与论文 H2O validation " + f"GT-box 结果 31.08 mm 相差 " + f"{wildhands_row['root_relative_mpjpe_mm'] - 31.08:.3f} mm," + "支持当前模型与关节适配的正确性。" + f"但 absolute MPJPE/z MAE 达 {wildhands_row['absolute_mpjpe_mm']:.3f}/" + f"{wildhands_row['translation_z_mae_mm']:.3f} mm,说明相对姿态接近论文量级不代表" + "绝对 camera-space 深度准确。" + ) + pad_note = "" + if "PAD-Hand-WiLoR" in rows_by_label and "WiLoR-H2O-K" in rows_by_label: + pad_row = rows_by_label["PAD-Hand-WiLoR"] + wilor_row = rows_by_label["WiLoR-H2O-K"] + pad_root = next( + row for row in refinement_rows + if row["metric"] == "root_relative_mpjpe_mm" + ) + pad_note = ( + "PAD-Hand 与 WiLoR 使用相同检测、初始化和 camera translation;其 16 帧扩散 refinement " + f"使 root-relative MPJPE 增加 " + f"{pad_row['root_relative_mpjpe_mm'] - wilor_row['root_relative_mpjpe_mm']:.3f} mm " + f"(take-equal paired delta {pad_root['candidate_minus_baseline']:+.3f} mm," + f"95% CI [{pad_root['ci95_low']:.3f}, {pad_root['ci95_high']:.3f}])," + f"但 joint velocity/acceleration error 从 " + f"{wilor_row['joint_velocity_error_mm_per_frame']:.3f}/" + f"{wilor_row['joint_acceleration_error_mm_per_frame2']:.3f} 降至 " + f"{pad_row['joint_velocity_error_mm_per_frame']:.3f}/" + f"{pad_row['joint_acceleration_error_mm_per_frame2']:.3f}。" + "因此它在 H2O 上是平滑性收益而非空间精度 SOTA。" + ) + dynhamr_note = "" + if "Dyn-HaMR-TTO" in rows_by_label: + dynhamr_row = rows_by_label["Dyn-HaMR-TTO"] + dynhamr_evaluation = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "Dyn-HaMR-TTO" + ) + dynhamr_metadata = dynhamr_evaluation["report"]["prediction_metadata"] + dynhamr_note = ( + "Dyn-HaMR 不是一次前向的重建网络:本表按每个 official-validation 连续 run " + "独立执行发布的 Root/Smooth test-time optimization,并使用已知静态 cam4 K。" + f"其 Coverage/absolute/root-relative MPJPE 为 {100 * dynhamr_row['coverage']:.2f}%/" + f"{dynhamr_row['absolute_mpjpe_mm']:.3f}/{dynhamr_row['root_relative_mpjpe_mm']:.3f} mm。" + f"94 个 run 共执行 {int(dynhamr_metadata['root_iterations_total']):,}/" + f"{int(dynhamr_metadata['smooth_iterations_total']):,} 次 Root/Smooth 外循环。" + "因此它属于高计算量 TTO 系统赛道,不能当作与 HaWoR/WiLoR 同成本的 feed-forward 模型。" + ) + if dynhamr_hawor_rows: + root_contrast = next( + row for row in dynhamr_hawor_rows + if row["metric"] == "root_relative_mpjpe_mm" + ) + dynhamr_note += ( + " 与 HaWoR 直接配对时,Dyn-HaMR 的 root-relative take-equal delta 为 " + f"{root_contrast['candidate_minus_baseline']:+.3f} mm,95% CI " + f"[{root_contrast['ci95_low']:.3f}, {root_contrast['ci95_high']:.3f}]," + "不能宣称任一方法显著更好。" + ) + h2o_trained = [row for row in rows if row["evaluation_track"] == "h2o_trained"] + zero_shot = [row for row in rows if row["evaluation_track"] == "zero_shot"] + test_time_optimization = [ + row for row in rows if row["evaluation_track"] == "test_time_optimization" + ] + diagnostics = [row for row in rows if row["evaluation_track"] == "diagnostic"] + uncategorized = [row for row in rows if row["evaluation_track"] == "uncategorized"] + h2o_absolute_winner = min( + (row for row in h2o_trained if row["absolute_mpjpe_mm"] is not None), + key=lambda row: row["absolute_mpjpe_mm"], + ) + h2o_root_winner = min( + (row for row in h2o_trained if row["root_relative_mpjpe_mm"] is not None), + key=lambda row: row["root_relative_mpjpe_mm"], + ) + zero_absolute_winner = min( + (row for row in zero_shot if row["absolute_mpjpe_mm"] is not None), + key=lambda row: row["absolute_mpjpe_mm"], + ) + zero_root_winner = min( + (row for row in zero_shot if row["root_relative_mpjpe_mm"] is not None), + key=lambda row: row["root_relative_mpjpe_mm"], + ) + zero_mesh_winner = min( + (row for row in zero_shot if row["absolute_mpvpe_mm"] is not None), + key=lambda row: row["absolute_mpvpe_mm"], + ) + zero_projected_winner = min( + (row for row in zero_shot if row["projected_2d_error_px"] is not None), + key=lambda row: row["projected_2d_error_px"], + ) + table_header = ( + "| 模型 | H2O 暴露 | 输入 | Params (模型/E2E) | Coverage | Abs MPJPE | " + "Root MPJPE | MPVPE | Root MPVPE | 2D | Fingertip | z MAE | PCK20 | AUC0-50 |" + ) + table_divider = ( + "|---|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|" + ) + speed_section: list[str] = [] + if speed_report is not None: + speed_by_label = { + row["setting_id"]: row for row in speed_report["rows"] + } + speed_section = [ + "", + "## 推理速度", + "", + ( + "同一 94 帧 H2O 连续片段、RTX 4090、包含 RGB 解码/预处理/所需 detector/" + "重建与 camera conversion 的本机实测中,批处理/时序摊销吞吐为:" + f"FoundationHand T8 {speed_by_label['FoundationHand-T8']['median_fps']:.2f} FPS," + f"QORT batch16 {speed_by_label['QORT-b16']['median_fps']:.2f} FPS," + f"WiLoR batch16 {speed_by_label['WiLoR-b16']['median_fps']:.2f} FPS," + f"HaWoR T16 {speed_by_label['HaWoR-T16']['median_fps']:.2f} FPS," + f"Dyn-HaMR TTO {speed_by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS。" + ), + "", + ( + "QORT/WiLoR 的 batch1 在线吞吐分别为 " + f"{speed_by_label['QORT-b1']['median_fps']:.2f}/" + f"{speed_by_label['WiLoR-b1']['median_fps']:.2f} FPS。" + "FoundationHand 的独立纯模型 profile 为 " + f"{speed_report['foundation_model_only_profile']['p50_ms_per_t8_clip']:.2f} ms/T8 clip," + f"即 {speed_report['foundation_model_only_profile']['amortized_frames_per_second']:.1f} frame/s;" + "完整数据路径为 T=8 RGB+Depth+K,因此二者不是同一计时口径。" + "HaWoR 与 Dyn-HaMR 是离线时序/TTO 方法,摊销 ms/frame 不是因果单帧延迟。" + "完整口径、重复范围与 Dyn-HaMR 开销拆分见 `INFERENCE_SPEED_REPORT.md`。" + ), + ] + + def result_line(row: dict[str, Any]) -> str: + return ( + f"| {row['label']} | {row['h2o_exposure']} | {row['input']} | " + f"{fmt_params(row['model_parameter_count'])}/{fmt_params(row['end_to_end_parameter_count'])} | " + f"{100 * row['coverage']:.2f}% | {fmt(row['absolute_mpjpe_mm'])} | " + f"{fmt(row['root_relative_mpjpe_mm'])} | {fmt(row['absolute_mpvpe_mm'])} | " + f"{fmt(row['root_relative_mpvpe_mm'])} | {fmt(row['projected_2d_error_px'])} | " + f"{fmt(row['fingertip_mpjpe_mm'])} | {fmt(row['translation_z_mae_mm'])} | " + f"{100 * row['absolute_pck_20mm']:.2f}% | {row['absolute_auc_0_50mm']:.4f} |" + ) + + lines = [ + "# FoundationHand 外部 SOTA 统一复评报告", + "", + "## 公平性结论", + "", + ( + "把 FoundationHand/QORT 与外部发布权重排成一个训练条件等价的 SOTA 总榜是不公平的。" + "前两者使用 H2O 训练,其余方法没有在 H2O 上微调;因此本报告改为域内训练与" + "零样本泛化两条前向赛道,并把逐视频优化方法单列为 TTO 赛道。" + "所有模型仍共享同一 validation、GT、坐标系和 evaluator。" + ), + "", + ( + f"H2O 域内训练赛道中,absolute/root-relative MPJPE 最低的分别是 " + f"**{h2o_absolute_winner['label']} ({fmt(h2o_absolute_winner['absolute_mpjpe_mm'])} mm)** " + f"和 **{h2o_root_winner['label']} ({fmt(h2o_root_winner['root_relative_mpjpe_mm'])} mm)**。" + "这仍是系统级比较:FoundationHand 使用 RGB+metric Depth+K、T=8,QORT 使用单帧 RGB。" + ), + "", + ( + f"H2O 零样本 RGB 赛道中,absolute/root-relative MPJPE 最低的分别是 " + f"**{zero_absolute_winner['label']} ({fmt(zero_absolute_winner['absolute_mpjpe_mm'])} mm)** " + f"和 **{zero_root_winner['label']} ({fmt(zero_root_winner['root_relative_mpjpe_mm'])} mm)**;" + f"absolute MPVPE 最低的是 **{zero_mesh_winner['label']} " + f"({fmt(zero_mesh_winner['absolute_mpvpe_mm'])} mm)**,投影 2D 最低的是 " + f"**{zero_projected_winner['label']} ({fmt(zero_projected_winner['projected_2d_error_px'])} px)**。" + ), + "", + comparative_note, + "", + ( + "这是一份同数据、同 GT、同坐标系、同评估器的开发集复评,不是可直接发表的官方-test " + "SOTA 声明。FoundationHand 的模型选择使用过该 validation split 的固定子集;各方法的输入模态和训练数据也不同。" + ), + "", + "## H2O 域内训练赛道", + "", + ( + "误差均为越低越好;Coverage、PCK、AUC 越高越好。MPJPE/MPVPE 是检测成功样本上的均值;" + "失败不会被静默删除,而是通过 Coverage 和 failure-aware PCK/AUC 计入。2D 误差按 Phase3 " + "约定缩放到 640x368 评估像素。" + ), + "", + table_header, + table_divider, + ] + lines.extend(result_line(row) for row in h2o_trained) + lines.extend([ + "", + "## H2O 零样本 RGB 赛道", + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in zero_shot) + if test_time_optimization: + lines.extend([ + "", + "## H2O 零样本 Test-Time Optimization 赛道", + "", + ( + "该表使用同一 H2O validation 和 evaluator,但方法在每段测试视频上优化模型变量," + "计算预算显著高于一次前向方法,因此不参与上方 zero-shot feed-forward winner 判定。" + ), + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in test_time_optimization) + if diagnostics or uncategorized: + lines.extend([ + "", + "## 诊断与未分类结果", + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in diagnostics + uncategorized) + lines.extend([ + "", + "### 左右手拆分", + "", + "| 模型 | Left coverage | Left Abs | Left Root | Right coverage | Right Abs | Right Root |", + "|---|---:|---:|---:|---:|---:|---:|", + ]) + for row in rows: + lines.append( + f"| {row['label']} | {100 * row['left_coverage']:.2f}% | " + f"{fmt(row['left_absolute_mpjpe_mm'])} | " + f"{fmt(row['left_root_relative_mpjpe_mm'])} | " + f"{100 * row['right_coverage']:.2f}% | " + f"{fmt(row['right_absolute_mpjpe_mm'])} | " + f"{fmt(row['right_root_relative_mpjpe_mm'])} |" + ) + lines.extend([ + "", + "WiLoR-H2O-K 使用已知 H2O 内参代入官方 `cam_crop_to_full` 代数,没有使用 GT pose 或拟合参数。" + "`WiLoR-native-camera` 保留发布 demo 的假设焦距,仅用于展示原样 camera translation 在 H2O 上的行为,不参与主结论。", + "", + ( + f"参数量由实际加载模块逐参数计数。FoundationHand 总参数 126.8M 中,export 时可训练参数为 " + f"{fmt_params(int(foundation_trainable)) if foundation_trainable is not None else 'N/A'}(DINO 冻结);" + "外部 RGB 方法的 E2E 数量包含实际使用的公开 detector。HaWoR 的 camera-space 表不加载与该任务无关的 " + "DROID-SLAM、Metric3D 和 world-space infiller。Dyn-HaMR 的参数数目是实际使用的 HaMeR initializer " + "与 detector;逐 run 优化变量随帧数变化,不计作网络参数。" + ), + "", + "QORT-Former 不输出 MANO mesh,因此 MPVPE 为 N/A。其 normalized `(u,v,z)` 反归一化和 K 反投影逐式复现了它所基于的官方 [H2OTR `pixel2cam`](https://github.com/chohoseong/H2OTR/blob/master/util/ops.py),不是用 GT pose 拟合得到的坐标。", + *speed_section, + "", + "## 时间指标", + "", + "| 模型 | Pair coverage | Wrist velocity | Joint velocity | Wrist acceleration | Joint acceleration |", + "|---|---:|---:|---:|---:|---:|", + ]) + for row in rows: + lines.append( + f"| {row['label']} | {100 * row['temporal_pair_coverage']:.2f}% | " + f"{fmt(row['wrist_velocity_error_mm_per_frame'])} | " + f"{fmt(row['joint_velocity_error_mm_per_frame'])} | " + f"{fmt(row['wrist_acceleration_error_mm_per_frame2'])} | " + f"{fmt(row['joint_acceleration_error_mm_per_frame2'])} |" + ) + lines.extend([ + "", + "时间差分只在同一连续 run、同一 Phase3 T=8 clip 内计算;检测失败的 pair 由 pair coverage 单独报告。", + "", + "### PAD-Hand refinement 诊断", + "", + pad_note, + "", + "### Dyn-HaMR TTO 诊断", + "", + dynhamr_note, + "", + "## 配对统计", + "", + ( + f"下表为候选模型减 FoundationHand 的 take-equal paired bootstrap;负值表示候选误差更低。" + f"每项只使用两模型都成功的精确交集,{bootstrap_samples:,} 次重采样,seed={bootstrap_seed}。" + ), + "", + "| 候选 | Metric | Paired hands | Takes | Delta | 95% CI |", + "|---|---|---:|---:|---:|---:|", + ]) + for row in paired_rows: + if row["metric"] not in ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", + ): + continue + lines.append( + f"| {row['candidate']} | {row['metric']} | {row['paired_hand_frames']} | " + f"{row['take_count']} | {fmt(row['candidate_minus_baseline'])} | " + f"[{fmt(row['ci95_low'])}, {fmt(row['ci95_high'])}] |" + ) + lines.extend([ + "", + "## 与论文原表的关系", + "", + "| 工作 | 论文报告 | 为什么不能与本表直接混排 |", + "|---|---|---|", + "| QORT-Former | H2O official test mean end-point error: left 20.1 mm, right 19.9 mm | 本报告是 official validation;论文未报告本 split 数字。指标形式接近,但 split 不同。 |", + "| WiLoR | FreiHAND PA-MPJPE/PA-MPVPE 5.5/5.1 mm;HO3D 7.5/7.7 mm | 数据集不同,且经过 Procrustes alignment;本表是 H2O 绝对 camera-space。 |", + "| HaWoR | DexYCB PA-MPJPE 4.76 mm、AUC 90.5 | 数据集不同,且 PA 对齐;本表只评 camera-space hand stage,不含 SLAM、Metric3D、world-space infiller。 |", + "| WildHands | H2O validation zero-shot root-relative MPJPE 31.08 mm、MRRPE 49.49 mm | 论文主要 ablation 使用 GT hand boxes;本表使用公开 detector,并额外报告 absolute camera-space、mesh、coverage。 |", + "| Hamba | FreiHAND PA-MPJPE/PA-MPVPE 5.8/5.5 mm(无 TTA) | 论文不报告 H2O;数据集不同且经 Procrustes alignment。本表发布配置含 H2O3D,但未含 H2O。 |", + "| PAD-Hand | DexYCB WiLoR→PAD-Hand: PA-MPJPE 4.88→4.63 mm、MPJPE 12.75→10.56 mm、ACCEL 6.70→3.34 | 本表是 H2O zero-shot,且保留 WiLoR camera translation;release checkpoint 未在 README 标明对应 DexYCB/HO3D 版本。 |", + "| HandDGP | FreiHAND camera-space MJE/MVE 46.3/46.3 mm | 发布权重仅用 FreiHAND;本表使用 H2O detector crop、已知 K 和同一 camera-space evaluator。 |", + "| Dyn-HaMR | 论文在动态相机视频上报告 global 4D hand-motion 指标 | 论文目标含相机运动与 world-space trajectory;本表因 H2O cam4 静止且 K 已知,只评每段 TTO 后的 camera-space hand 输出。 |", + "", + "因此,本复评能够检查公开 checkpoint 在同一 H2O validation 上的实际行为,但不能单独证实或否定论文 official-test 数字。", + "", + qort_note, + "", + wildhands_note, + "", + "原始来源:QORT-Former [paper](https://arxiv.org/abs/2502.19769) / [official repo](https://github.com/kcsayem/QORT-Former);WiLoR [paper](https://arxiv.org/abs/2409.12259) / [official repo](https://github.com/rolpotamias/WiLoR);HaWoR [paper](https://arxiv.org/abs/2501.02973) / [official repo](https://github.com/ThunderVVV/HaWoR);WildHands [ECCV page](https://eccv.ecva.net/virtual/2024/poster/2450) / [official repo](https://github.com/ap229997/hands);Hamba [NeurIPS paper](https://proceedings.neurips.cc/paper_files/paper/2024/hash/03e9a69e5b686c316a07d73f0cf5e225-Abstract-Conference.html) / [official repo](https://github.com/humansensinglab/Hamba);PAD-Hand [CVPR paper](https://openaccess.thecvf.com/content/CVPR2026/html/Ismayilzada_PAD-Hand_Physics-Aware_Diffusion_for_Hand_Motion_Recovery_CVPR_2026_paper.html) / [official repo](https://github.com/DominoAI-Lab/PAD-Hand-CVPR-2026);HandDGP [project](https://nianticlabs.github.io/handdgp/) / [official repo](https://github.com/nianticlabs/HandDGP);Dyn-HaMR [CVPR paper](https://openaccess.thecvf.com/content/CVPR2025/html/Yu_Dyn-HaMR_Recovering_4D_Interacting_Hand_Motion_from_a_Dynamic_Camera_CVPR_2025_paper.html) / [official repo](https://github.com/ZhengdiYu/Dyn-HaMR)。", + "", + "## 协议与公平性边界", + "", + f"- Manifest: `{manifest}`,SHA256 `{manifest_hash}`。", + f"- Ground truth bundle: `{ground_truth}`,SHA256 `{ground_truth_hash}`。", + f"- 样本:{rows[0]['frames']:,} 帧、{rows[0]['takes']} takes、{rows[0]['annotation_valid_hand_frames']:,} 个 annotation-valid hand-frames。", + "- Split:H2O official validation(subject3 held-out runs);official test(subject4)未使用。", + "- Camera:全部输出统一成 raw cam4 的 x-right/y-down/z-forward metric XYZ,再由同一 K 投影。", + "- 关节:H2O 左/右各 21 joints;mesh 统一为对应 MANO 778 vertices。", + "- FoundationHand 输入 RGB+metric Depth+K、T=8;QORT 输入单帧 RGB;WiLoR/WildHands/Hamba/HandDGP 输入 RGB detector/crop;HaWoR 与 PAD-Hand 输入 T=16 RGB track;Dyn-HaMR 对每个完整连续 run 做 TTO。协议一致不等于输入模态或计算预算一致。", + "- FoundationHand checkpoint 在 validation 固定子集上被选择;因此本报告用于开发期横向复评,最终无偏结论必须在冻结后一次性跑 official test。", + "- 直接运行 WiLoR/HaWoR/WildHands/Hamba/PAD-Hand/HandDGP 是有效的 H2O out-of-box 泛化测试,但不能解释为这些模型在 H2O 充分微调后的上限。Dyn-HaMR 已通过官方定义的 per-video TTO 适配测试序列。", + "- HandDGP 官方仓库只有 inference/evaluation;WiLoR/Hamba 只保留训练模块而缺少完整 runner/config;HaWoR 官方 README 仍写明训练代码将后续发布;PAD-Hand 仅发布 demo。自行编写微调器会形成新的派生训练配方,不能标成官方 fine-tuned baseline。", + "- 真正的 H2O fine-tuning 对照需要统一 H2O train、冻结 validation/test、同 detector/K、相同输入预算和选模规则,并同时报告 pretrained 与 fine-tuned;当前公开资产不足以严格完成这一实验。", + "- WiLoR/HaWoR 声明 CC BY-NC-ND 4.0,Hamba 声明 CC BY-NC 4.0;WildHands、QORT 与 PAD-Hand 在审计 commit 未见明确 LICENSE。MANO/Ultralytics 等依赖另有许可。当前下载与运行仅用于本地研究复评,不代表可重分发模型资产。", + "", + "## 已录用开源候选审计", + "", + "| 工作 | 状态 | 本报告处理 |", + "|---|---|---|", + "| PAD-Hand | CVPR 2026 Highlight;官方 demo 与 checkpoint | 纳入 zero-shot temporal 表;与相同 WiLoR initializer 成对报告。 |", + "| WildHands | ECCV 2024;官方代码与 checkpoint;论文明确 H2O zero-shot | 纳入零样本量化表。 |", + "| Hamba | NeurIPS 2024;官方推理代码与 checkpoint | 纳入零样本量化表;使用共同 detector 与官方 crop/initial-regressor。 |", + "| ViDiHand | 2026-06 arXiv;1.3B video diffusion + 37M decoder;metric two-hand camera-space 输出 | 方法与 H2O 高度匹配,但官方仓库仅 README,明确写明 code will be released soon;当前无 checkpoint/推理/训练代码。 |", + "| Dyn-HaMR | CVPR 2025 Highlight;官方代码、HaMeR 权重与 TTO 配置 | 已按每个连续 run、静态已知 H2O K 完整运行,单列 TTO 赛道;不是可微调 feed-forward baseline。 |", + "| HandDGP | ECCV 2024;官方 FreiHAND checkpoint 与 camera-space 推理 | 已用发布权重、官方 rectification/DGP 和共同 detector 纳入 zero-shot 表;仓库无训练入口。 |", + "| EgoHandICL | ICLR 2026;官方仓库 commit `16e5690` 含名义训练/推理文件 | 推理脚本引用未发布的 `handicl` 核心 package;Hugging Face 仅有数据/标注压缩包而无 checkpoint,README 还含 `` 与空权重路径,不能形成可审计推理或微调。 |", + "| MaskHand | ICCV 2025 | 项目页只有论文与演示;截至 2026-07-20,论文所指官方 GitHub 返回 404,无 checkpoint,无法同权重复评。 |", + "| Pose-Guided Temporal Enhancement | CVPR 2025 | 未找到作者公开的推理仓库或 checkpoint。 |", + "| OmniHands | ACM TOG 2026;官方代码与 image/video/multiview checkpoints | 任务核心是双手交互及 temporal/multiview,发布 demo 的相机输出/评估协议与本表单手 camera-space 协议不同,暂不混排。 |", + "| Enhancing Monocular 3D Hand Reconstruction with Learned Texture Priors | WACV 2026;公开 texture-supervised HaMeR 权重 | 仓库仍将完整 code release 标为未完成;待稳定发布后可按 HaMeR camera adapter 加入。 |", + "| HandOS | CVPR 2025 | 官方项目当前未提供可下载 checkpoint,无法做同权重复评。 |", + "| PS-HPME / Pseudo-Stereo-Hand | Knowledge-Based Systems 2026;目标为单目 camera-space mesh | 论文给出的官方 GitHub 地址在本次审计返回 404,无法下载代码或 checkpoint。 |", + "| SesaHand | ICLR 2026;生成数据增强重建 | 不是独立重建推理模型,官方仓库的 pretrained model 与 samples 仍标为 TBD。 |", + "| POEM-v2 | TPAMI 2025;代码/权重公开 | 多视图方法;当前冻结 H2O 产物只有 cam4,不能伪装成公平单目基线。 |", + "", + "## 公开实现与资产溯源", + "", + ]) + for evaluation in evaluations: + metadata = evaluation["report"]["prediction_metadata"] + lines.append(f"### {evaluation['label']}") + lines.append("") + if metadata.get("official_repository"): + lines.append(f"- Official repository: {metadata['official_repository']}") + lines.append(f"- Repository commit: `{metadata['repository_commit']}`") + elif metadata.get("training_commit"): + lines.append(f"- Training commit: `{metadata['training_commit']}`") + lines.append( + f"- Repository commit at export: `{metadata['repository_commit_at_export']}`" + ) + checkpoint = metadata.get("checkpoint", metadata.get("hamer_checkpoint")) + checkpoint_hash = metadata.get( + "checkpoint_sha256", metadata.get("hamer_checkpoint_sha256") + ) + lines.append(f"- Checkpoint: `{checkpoint}`") + lines.append(f"- Checkpoint SHA256: `{checkpoint_hash}`") + if metadata.get("detector_checkpoint"): + lines.append(f"- Detector: `{metadata['detector_checkpoint']}`") + lines.append( + f"- Detector SHA256: `{metadata['detector_checkpoint_sha256']}`" + ) + if metadata.get("base_wilor_checkpoint"): + lines.append( + f"- Base WiLoR commit: `{metadata['base_wilor_repository_commit']}`" + ) + lines.append(f"- Base WiLoR: `{metadata['base_wilor_checkpoint']}`") + lines.append( + f"- Base WiLoR SHA256: `{metadata['base_wilor_checkpoint_sha256']}`" + ) + lines.append(f"- Evaluation JSON SHA256: `{evaluation['summary']['evaluation_json_sha256']}`") + lines.append("") + lines.extend([ + "## 可复现产物", + "", + "- `comparison.csv`: 完整主表机器可读版本。", + "- `paired_take_bootstrap.csv`: 全指标配对差值与 CI。", + "- `pad_hand_vs_wilor_paired_take_bootstrap.csv`: PAD-Hand refinement 相对同一 WiLoR initializer 的配对差值。", + "- `dynhamr_vs_hawor_paired_take_bootstrap.csv`: Dyn-HaMR TTO 相对最强 zero-shot 前向 HaWoR 的直接配对差值。", + "- `INFERENCE_SPEED_REPORT.md`、`speed_comparison.csv` 与 `speed_report.json`: 同机统一推理速度、原始 timing 哈希和 Dyn-HaMR TTO 开销拆分。", + "- `report.json`: 汇总、论文协议旁注和所有输入文件 hash。", + "- `visual_audit/projection_contact_sheet.jpg` 与 `visual_audit/visual_audit.json`: 固定样本投影和全量正深度/画内统计。", + "- 各 evaluation 目录保留逐 hand-frame 与逐 temporal-transition CSV,可重算全部统计。", + "", + ]) + return "\n".join(lines) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--evaluation", + action="append", + required=True, + help="LABEL=directory containing evaluation.json and metric CSV files", + ) + parser.add_argument("--foundation-label", default="FoundationHand-Phase3") + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + + evaluations = [] + labels = set() + for spec in args.evaluation: + label, separator, raw_directory = spec.partition("=") + if not separator or not label or not raw_directory: + raise ValueError(f"Invalid --evaluation value: {spec}") + if label in labels: + raise ValueError(f"Duplicate evaluation label: {label}") + labels.add(label) + evaluations.append(load_evaluation(label, Path(raw_directory).resolve())) + if args.foundation_label not in labels: + raise ValueError(f"Missing foundation label: {args.foundation_label}") + baseline = next( + evaluation for evaluation in evaluations + if evaluation["label"] == args.foundation_label + ) + paired_rows: list[dict[str, Any]] = [] + for evaluation in evaluations: + if evaluation is baseline or evaluation["label"] == "WiLoR-native-camera": + continue + contrasts = paired_take_bootstrap( + baseline["frame_rows"], + evaluation["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + paired_rows.extend({ + "baseline": args.foundation_label, + "candidate": evaluation["label"], + **contrast, + } for contrast in contrasts) + + refinement_rows: list[dict[str, Any]] = [] + if "WiLoR-H2O-K" in labels and "PAD-Hand-WiLoR" in labels: + wilor = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "WiLoR-H2O-K" + ) + pad_hand = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "PAD-Hand-WiLoR" + ) + refinement_rows = [ + { + "baseline": "WiLoR-H2O-K", + "candidate": "PAD-Hand-WiLoR", + **contrast, + } + for contrast in paired_take_bootstrap( + wilor["frame_rows"], + pad_hand["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + ] + + dynhamr_hawor_rows: list[dict[str, Any]] = [] + if "HaWoR-camera" in labels and "Dyn-HaMR-TTO" in labels: + hawor = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "HaWoR-camera" + ) + dynhamr = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "Dyn-HaMR-TTO" + ) + dynhamr_hawor_rows = [ + { + "baseline": "HaWoR-camera", + "candidate": "Dyn-HaMR-TTO", + **contrast, + } + for contrast in paired_take_bootstrap( + hawor["frame_rows"], + dynhamr["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + ] + + args.output_dir.mkdir(parents=True, exist_ok=True) + comparison_rows = [evaluation["summary"] for evaluation in evaluations] + write_csv_rows(args.output_dir / "comparison.csv", comparison_rows) + write_csv_rows(args.output_dir / "paired_take_bootstrap.csv", paired_rows) + if refinement_rows: + write_csv_rows( + args.output_dir / "pad_hand_vs_wilor_paired_take_bootstrap.csv", + refinement_rows, + ) + if dynhamr_hawor_rows: + write_csv_rows( + args.output_dir / "dynhamr_vs_hawor_paired_take_bootstrap.csv", + dynhamr_hawor_rows, + ) + manifest = args.manifest.resolve() + ground_truth = args.ground_truth.resolve() + speed_report_path = args.output_dir / "speed_report.json" + speed_report = ( + json.loads(speed_report_path.read_text(encoding="utf-8")) + if speed_report_path.is_file() + else None + ) + payload = { + "status": "complete", + "official_test_used": False, + "split_role": "official_validation", + "manifest": str(manifest), + "manifest_sha256": sha256(manifest), + "ground_truth": str(ground_truth), + "ground_truth_sha256": sha256(ground_truth), + "bootstrap_seed": args.bootstrap_seed, + "bootstrap_samples": args.bootstrap_samples, + "comparison": comparison_rows, + "paired_take_bootstrap": paired_rows, + "pad_hand_vs_wilor_paired_take_bootstrap": refinement_rows, + "dynhamr_vs_hawor_paired_take_bootstrap": dynhamr_hawor_rows, + "paper_reported_context": { + "QORT-Former": "H2O test MEE left/right 20.1/19.9 mm", + "WiLoR": "FreiHAND PA-MPJPE/PA-MPVPE 5.5/5.1 mm; HO3D 7.5/7.7 mm", + "HaWoR": "DexYCB PA-MPJPE 4.76 mm, AUC 90.5", + "WildHands": "H2O validation zero-shot MPJPE/MRRPE 31.08/49.49 mm", + "Hamba": "FreiHAND no-TTA PA-MPJPE/PA-MPVPE 5.8/5.5 mm", + "PAD-Hand": ( + "DexYCB WiLoR->PAD-Hand PA-MPJPE 4.88->4.63 mm, " + "MPJPE 12.75->10.56 mm, ACCEL 6.70->3.34" + ), + "HandDGP": "FreiHAND camera-space MJE/MVE 46.3/46.3 mm", + "Dyn-HaMR": "global 4D hand-motion reconstruction on dynamic-camera videos", + }, + } + if speed_report is not None: + payload["speed_benchmark"] = { + "path": str(speed_report_path.resolve()), + "sha256": sha256(speed_report_path), + "status": speed_report.get("status"), + } + (args.output_dir / "report.json").write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + report_text = markdown_report( + evaluations, + paired_rows, + refinement_rows, + dynhamr_hawor_rows, + speed_report, + manifest=manifest, + manifest_hash=payload["manifest_sha256"], + ground_truth=ground_truth, + ground_truth_hash=payload["ground_truth_sha256"], + bootstrap_seed=args.bootstrap_seed, + bootstrap_samples=args.bootstrap_samples, + ) + (args.output_dir / "SOTA_EVALUATION_REPORT.md").write_text( + report_text, encoding="utf-8" + ) + print(json.dumps({ + "models": [evaluation["label"] for evaluation in evaluations], + "output_dir": str(args.output_dir.resolve()), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_sota_speed.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_sota_speed.py new file mode 100644 index 0000000000000000000000000000000000000000..11ebd0914d721320b8787f1e806411a282dab0cc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/summarize_sota_speed.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Summarize synchronized external-baseline speed measurements.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +SETTINGS = { + "FoundationHand-T8": ("FoundationHand", "temporal_clip", "RGB+Depth+K, T=8, clip batch=1"), + "QORT-b1": ("QORT-Former", "framewise", "batch=1"), + "QORT-b16": ("QORT-Former", "batched", "batch=16"), + "WiLoR-b1": ("WiLoR", "framewise", "detector/reconstruction batch=1"), + "WiLoR-b16": ("WiLoR", "batched", "detector/reconstruction batch=16"), + "HaWoR-T16": ("HaWoR", "offline_temporal", "tracked temporal window=16"), + "Dyn-HaMR-TTO": ("Dyn-HaMR", "test_time_optimization", "one 94-frame run"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--timing", action="append", required=True, help="SETTING=timing.json") + parser.add_argument("--foundation-profile", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + + grouped: dict[str, list[tuple[Path, dict[str, Any]]]] = {} + for spec in args.timing: + label, separator, raw_path = spec.partition("=") + if not separator or label not in SETTINGS or not raw_path: + raise ValueError(f"Invalid timing specification: {spec}") + path = Path(raw_path).resolve() + payload = json.loads(path.read_text(encoding="utf-8")) + if payload.get("schema_version") != "foundation_hand_external_speed_v1": + raise ValueError(f"Unexpected timing schema: {path}") + if int(payload.get("frames", 0)) != 94: + raise ValueError(f"Benchmark must contain exactly 94 frames: {path}") + grouped.setdefault(label, []).append((path, payload)) + + missing = set(SETTINGS) - set(grouped) + if missing: + raise ValueError(f"Missing benchmark settings: {sorted(missing)}") + + rows: list[dict[str, Any]] = [] + raw_measurements: dict[str, list[dict[str, Any]]] = {} + for label, (model, mode, setting) in SETTINGS.items(): + measurements = grouped[label] + fps = np.asarray([item[1]["frames_per_second"] for item in measurements]) + seconds = np.asarray([item[1]["processing_seconds"] for item in measurements]) + row = { + "setting_id": label, + "model": model, + "mode": mode, + "setting": setting, + "repeats": len(measurements), + "frames_per_repeat": 94, + "median_processing_seconds": float(np.median(seconds)), + "median_fps": float(np.median(fps)), + "min_fps": float(fps.min()), + "max_fps": float(fps.max()), + "amortized_ms_per_frame": float(1000.0 / np.median(fps)), + } + rows.append(row) + raw_measurements[label] = [ + { + "path": str(path), + "sha256": sha256(path), + **payload, + } + for path, payload in measurements + ] + + by_label = {row["setting_id"]: row for row in rows} + dyn = raw_measurements["Dyn-HaMR-TTO"][0] + foundation_profile_path = args.foundation_profile.resolve() + foundation_profile = json.loads( + foundation_profile_path.read_text(encoding="utf-8") + ) + foundation_forward_ms = float(foundation_profile["latency"]["p50_ms"]) + foundation_model_fps = 8_000.0 / foundation_forward_ms + dyn_initializer_fps = dyn["frames"] / dyn["initialization_seconds"] + dyn_optimizer_fraction = dyn["optimization_seconds"] / dyn["processing_seconds"] + throughput_order = [ + "FoundationHand-T8", "QORT-b16", "WiLoR-b16", "HaWoR-T16", "Dyn-HaMR-TTO" + ] + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "speed_comparison.csv", rows) + report_payload = { + "status": "complete", + "schema_version": "foundation_hand_external_speed_report_v1", + "date": "2026-07-21", + "hardware": "NVIDIA GeForce RTX 4090", + "physical_gpu_policy": ( + "QORT/WiLoR/HaWoR repeats used idle physical GPU0; " + "Dyn-HaMR used idle physical GPU1; all GPUs are identical RTX 4090 cards" + ), + "workload": "first official H2O validation contiguous run (94 RGB frames)", + "timed_scope": ( + "RGB decode/preprocessing through final camera-space conversion; " + "model loading and prediction serialization excluded" + ), + "cuda_synchronized": True, + "rows": rows, + "raw_measurements": raw_measurements, + "foundation_model_only_profile": { + "path": str(foundation_profile_path), + "sha256": sha256(foundation_profile_path), + "p50_ms_per_t8_clip": foundation_forward_ms, + "amortized_frames_per_second": foundation_model_fps, + "scope": foundation_profile["latency"]["scope"], + }, + "dynhamr_diagnostics": { + "initializer_fps": dyn_initializer_fps, + "initializer_seconds": dyn["initialization_seconds"], + "optimization_seconds": dyn["optimization_seconds"], + "optimizer_fraction": dyn_optimizer_fraction, + "root_iterations": dyn["root_iterations"], + "smooth_iterations": dyn["smooth_iterations"], + }, + } + (args.output_dir / "speed_report.json").write_text( + json.dumps(report_payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + lines = [ + "# FoundationHand 外部方法推理速度复评", + "", + "## 结论", + "", + ( + f"在相同 94 帧 H2O RGB 连续片段和 RTX 4090 上,批处理吞吐排序为 " + f"**FoundationHand ({by_label['FoundationHand-T8']['median_fps']:.2f} FPS) > " + f"QORT-Former ({by_label['QORT-b16']['median_fps']:.2f} FPS) > " + f"WiLoR ({by_label['WiLoR-b16']['median_fps']:.2f} FPS) > " + f"HaWoR ({by_label['HaWoR-T16']['median_fps']:.2f} FPS) > " + f"Dyn-HaMR ({by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS)**。" + ), + "", + ( + "QORT/WiLoR 是逐帧前向方法;FoundationHand 使用 T=8 RGB+Depth+K clip;" + "HaWoR 必须看到时序窗口/连续 track;" + "Dyn-HaMR 对整段测试视频优化。因此 FPS 可比较系统计算成本,但 HaWoR/Dyn-HaMR 的" + "摊销 ms/frame 不是因果单帧响应延迟。" + ), + "", + "## 端到端摊销吞吐", + "", + "计时包含 RGB 解码、官方预处理、需要的 detector、重建和 camera-space 转换;不包含权重加载与 NPZ 写盘。", + "", + "| 方法 | 模式 | 设置 | 重复 | Median FPS | 范围 | 摊销 ms/frame |", + "|---|---|---|---:|---:|---:|---:|", + ] + for label in throughput_order: + row = by_label[label] + lines.append( + f"| {row['model']} | {row['mode']} | {row['setting']} | {row['repeats']} | " + f"{row['median_fps']:.3f} | {row['min_fps']:.3f}-{row['max_fps']:.3f} | " + f"{row['amortized_ms_per_frame']:.2f} |" + ) + lines.extend([ + "", + "## Batch-1 在线前向", + "", + "| 方法 | Median FPS | 范围 | ms/frame |", + "|---|---:|---:|---:|", + ]) + for label in ("QORT-b1", "WiLoR-b1"): + row = by_label[label] + lines.append( + f"| {row['model']} | {row['median_fps']:.3f} | " + f"{row['min_fps']:.3f}-{row['max_fps']:.3f} | " + f"{row['amortized_ms_per_frame']:.2f} |" + ) + lines.extend([ + "", + "HaWoR 和 Dyn-HaMR 不列入 batch-1 在线表:前者是非因果 tracked temporal inference,后者是整段 TTO。", + "", + "## FoundationHand 开销拆分", + "", + ( + f"FoundationHand 完整 RGB+Depth+K 数据路径的中位吞吐为 " + f"{by_label['FoundationHand-T8']['median_fps']:.2f} FPS(" + f"{by_label['FoundationHand-T8']['amortized_ms_per_frame']:.2f} ms/frame 摊销)。" + f"独立的 100 次 GPU forward 计时 P50 为 {foundation_forward_ms:.2f} ms/T=8 clip," + f"等价于 {foundation_model_fps:.1f} frame/s 的纯模型吞吐;两者差额主要来自 RGB/Depth 解码、" + "640x368 预处理、worker 启动和 host-device/host result transfer。" + ), + "", + ( + "FoundationHand 的 T=8 需要先获得一个 8 帧窗口,因此上述 14.2 ms/frame 是系统吞吐," + "不是零缓冲的单帧响应延迟。" + ), + "", + "## Dyn-HaMR 开销拆分", + "", + ( + f"Dyn-HaMR 的 detector+HaMeR 初始化耗时 {dyn['initialization_seconds']:.2f} s," + f"相当于 {dyn_initializer_fps:.2f} FPS;32 次 Root + 300 次 Smooth TTO 耗时 " + f"{dyn['optimization_seconds']:.2f} s,占完整推理时间 {100 * dyn_optimizer_fraction:.2f}%。" + f"完整 94 帧用时 {dyn['processing_seconds']:.2f} s,即 " + f"{by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS。" + ), + "", + "## 公平性边界", + "", + "- FoundationHand/QORT/WiLoR/HaWoR 各重复 3 次并报告中位数和范围;Dyn-HaMR 因完整 TTO 昂贵,报告一次无缓存的完整官方优化。", + "- QORT/WiLoR 的 batch=16 数字是吞吐,不是单请求延迟。", + "- HaWoR 速度只覆盖本 SOTA 报告使用的 camera-space hand stage,不包含 DROID-SLAM、Metric3D 或 world-space infiller。", + "- FoundationHand 使用 RGB+metric Depth+K 且不需要 detector;外部方法为 RGB,因此这是已部署系统吞吐比较,不是输入模态等价的 backbone benchmark。", + "- Dyn-HaMR 使用已知静态 H2O K,因此不包含 VIPE/DROID-SLAM;包含与量化结果完全相同的 Root/Smooth TTO。", + "- FoundationHand/QORT/WiLoR/HaWoR 重复测量使用空闲物理 GPU0;Dyn-HaMR 使用空闲物理 GPU1。六张卡均为 RTX 4090。", + "- 这些是本机 release-code 系统测速,不应与论文在其他 GPU、分辨率或只计 model-forward 的 FPS 直接混排。", + "", + "## 可复现产物", + "", + "- `speed_comparison.csv`: 汇总速度表。", + "- `speed_report.json`: 原始 timing 路径、SHA256、计时范围与 Dyn-HaMR 分段耗时。", + "- 原始同步 timing JSON 位于 `artifacts/sota/speed_benchmark_20260721/`。", + "", + ]) + (args.output_dir / "INFERENCE_SPEED_REPORT.md").write_text( + "\n".join(lines), encoding="utf-8" + ) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_last2_candidate_admission.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_last2_candidate_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..ab89a845500fc88174c957806b8b2318ca3e8e0a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_last2_candidate_admission.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Forward-sync one frozen last-2 admission to its remote owner controller.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def upstream_files(plan: dict[str, Any]) -> list[Path]: + state_path = Path(plan["admission_controller_state"]) + report_path = Path(plan["admission_decision_report"]) + if not state_path.is_file() or not report_path.is_file(): + raise NotReady("last-2 upstream decision is not complete") + state = read_json(state_path) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != plan["admission_controller_plan_sha256"] + or state.get("decision_report", {}).get("path") != str(report_path.resolve()) + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or state.get("official_test_used") is not False + ): + raise NotReady("last-2 upstream decision is not complete") + files = [report_path, state_path] + stage8_state = Path(plan["stage8_controller_state"]) + if stage8_state not in files: + stage8 = read_json(stage8_state) + stage8_report = Path(stage8["decision_report"]["path"]) + files.extend((stage8_report, stage8_state)) + return files + + +def admission_payload(plan: dict[str, Any]) -> tuple[str, list[Path], list[dict[str, str]]]: + files = upstream_files(plan) + central_path = Path(plan["controller_states"]["taku3"]) + if not central_path.is_file(): + raise NotReady("central last-2 candidate has not consumed admission") + central = read_json(central_path) + decision_path = Path(plan["decision_report"]) + if central.get("status") == "complete" and central.get("admitted") is False: + if not decision_path.is_file() or central.get("decision_report", {}).get("sha256") != sha256(decision_path): + raise ValueError("central last-2 rejection binding differs") + return "rejected", files + [decision_path, central_path], [] + registry_path = Path(plan["training_registry"]) + if not registry_path.is_file() or not central.get("training_registry_sha256"): + raise NotReady("central last-2 training registry is not frozen") + if ( + central.get("plan_sha256") != sha256(Path(central["plan"])) + or central.get("training_registry") != str(registry_path.resolve()) + or central.get("training_registry_sha256") != sha256(registry_path) + or central.get("official_test_used") is not False + ): + raise ValueError("central last-2 controller binding differs") + registry = read_json(registry_path) + owners = condition_owners(registry, load_assignment(plan)) + conditions = registry.get("conditions", []) + if ( + registry.get("status") != "frozen_ready" + or registry.get("candidate") != plan["candidate"] + or len(conditions) != 7 + or sum(owner == "server_new" for owner in owners.values()) != 3 + or registry.get("official_test_used") is not False + ): + raise ValueError("last-2 registry contract differs") + files.extend((Path(plan["training_registry_state"]), + *[Path(item["config"]) for item in conditions], registry_path)) + prerequisites, seen = [], set() + for item in conditions: + pair = (item["initialization_checkpoint"], item["initialization_checkpoint_sha256"]) + if pair not in seen: prerequisites.append({"path": pair[0], "sha256": pair[1]}); seen.add(pair) + for item in registry["data_artifacts"]: + pair = (item["path"], item["sha256"]) + if pair not in seen: prerequisites.append({"path": pair[0], "sha256": pair[1]}); seen.add(pair) + return "admitted", files, prerequisites + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = Path(state).parent.parent / "server_new.log" + command = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_last2_candidate_controller --plan " + str(plan_path.resolve()) + + " --state " + state + " --machine server_new --poll-seconds 30 >> " + + str(log) + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: raise RuntimeError("remote last-2 controller launch failed") + time.sleep(2) + probe = subprocess.run([ + "ssh", "server_new", "pgrep", "-fo", + f"scripts.run_phase9_last2_candidate_controller.*last2_v3/{plan['candidate']}.*server_new.json", + ], stdout=subprocess.PIPE, text=True, check=False) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote last-2 controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + admission, files, prerequisites = admission_payload(plan) + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"central last-2 prerequisite differs: {path}") + if remote_sha256("server_new", path) != item["sha256"]: + raise ValueError(f"remote last-2 prerequisite differs: {path}") + registry = Path(plan["training_registry"]) + ordered = [path for path in files if path != registry] + ([registry] if registry in files else []) + installed = [install_file("server_new", path) for path in ordered] + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_last2_candidate_admission_sync_v1", + "status": "complete", "candidate": plan["candidate"], "admission": admission, + "completed_utc": utc_now(), "plan_sha256": sha256(plan_path), + "installed": installed, "immutable_prerequisites": prerequisites, + "registry_installed_last": registry in files, "remote_controller_pid": pid, + "official_test_used": False, "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_last2_candidate_admission_sync_v1", + "status": "waiting_for_candidate_admission", "candidate": plan["candidate"], + "watcher_pid": os.getpid(), "updated_utc": utc_now(), "detail": str(error), + "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_last2_training_completion.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_last2_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..6c9fa4facf8e3fbbde000e22bcab8de5e9a983fc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_last2_training_completion.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Completion-only remote training handoff for an admitted last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_resolution_training_completion import active_writer_pids +from scripts.sync_phase9_shared_augmentation_training_completion import ( + file_record, install, json_sha256, validate_terminal, +) + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(path: Path, plan: dict[str, Any]) -> None: + conditions = plan.get("conditions", []) + if ( + plan.get("schema_version") != "phase9_last2_training_completion_plan_v1" + or plan.get("status") != "frozen" + or plan.get("candidate") not in {"5e7", "1e6"} + or len(conditions) != 3 or len(set(conditions)) != 3 + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("target_step") != 405000 + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + ): + raise ValueError("last-2 training completion plan differs") + for binding in plan["bindings"]: + candidate = Path(binding["path"]) + if not candidate.is_file() or sha256(candidate) != binding["sha256"]: + raise ValueError(f"last-2 completion binding differs: {candidate}") + if not path.is_file(): raise ValueError("last-2 completion plan is unreadable") + + +def registry_jobs(plan: dict[str, Any]) -> tuple[Path, dict[str, Any], dict[str, Any]]: + path = Path(plan["training_registry"]["path"]) + if not path.is_file() or sha256(path) != plan["training_registry"]["sha256"]: + raise ValueError("last-2 training registry hash differs") + registry = read_json(path); jobs = {item["condition"]: item for item in registry["conditions"]} + owners = condition_owners(registry, load_assignment(plan)) + remote = [condition for condition in jobs if owners[condition] == "server_new"] + if ( + registry.get("status") != "frozen_ready" + or registry.get("candidate") != plan["candidate"] + or remote != plan["conditions"] + or registry.get("target_step") != 405000 + or registry.get("official_test_used") is not False + ): + raise ValueError("last-2 training registry contract differs") + return path, registry, jobs + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + registry_path, _, jobs = registry_jobs(plan) + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): raise NotReady("remote last-2 controller is missing") + controller = read_json(controller_path) + statuses = controller.get("training_statuses", {}) + if any(statuses.get(condition) != "complete" for condition in plan["conditions"]): + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("remote last-2 controller failed") + raise NotReady("remote last-2 training is still running") + if ( + controller.get("plan_sha256") != plan["controller_plan"]["sha256"] + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("official_test_used") is not False + ): + raise ValueError("remote last-2 controller binding differs") + root, state_root = Path(plan["release_root"]), Path(plan["training_state_root"]) + records, files = [], [] + for condition in plan["conditions"]: + job = jobs[condition]; state_path = state_root / f"{condition.lower()}.json" + state = read_json(state_path) + if state.get("queue_sha256") != sha256(registry_path): + raise ValueError(f"last-2 state registry binding differs: {condition}") + if active_writer_pids(job["output_dir"]): raise NotReady(f"last-2 writer exists: {condition}") + checkpoint, evidence = validate_terminal(job, state) + pair = [file_record(root, "checkpoint", checkpoint), + file_record(root, "training_state", state_path)] + files.extend(pair); records.append({ + "condition": condition, "role": job["role"], + "checkpoint_sha256": sha256(checkpoint), + "final_total_loss": float(evidence["metric"]["losses"]["total"]), + "metrics_sha256": evidence["metrics_sha256"], + "summary_sha256": evidence["summary_sha256"], "files": pair, + }) + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): return read_json(output) + records, files = source_records(plan) + value = { + "schema_version": "phase9_last2_training_completion_release_v1", + "status": "complete_immutable_release", "candidate": plan["candidate"], + "created_utc": utc_now(), "plan_sha256": sha256(plan_path), + "training_registry": plan["training_registry"], "release_root": plan["release_root"], + "conditions": records, "files": files, "file_count": 6, + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, "live_reverse_sync_performed": False, + "results_before_terminal_states": True, "official_test_used": False, + } + atomic_json(output, value); os.chmod(output, 0o444) + for item in files: os.chmod(item["absolute_path"], 0o444) + return value + + +def fetch(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run(["ssh", "server_new", "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, check=False) + if result.returncode: raise NotReady("remote last-2 release is unavailable") + return json.loads(result.stdout) + + +def validate_release(plan_path: Path, plan: dict[str, Any], value: dict[str, Any]) -> None: + files = value.get("files", []) + if ( + value.get("schema_version") != "phase9_last2_training_completion_release_v1" + or value.get("status") != "complete_immutable_release" + or value.get("candidate") != plan["candidate"] + or value.get("plan_sha256") != sha256(plan_path) + or value.get("training_registry") != plan["training_registry"] + or [item.get("condition") for item in value.get("conditions", [])] != plan["conditions"] + or len(files) != 6 or len({item.get("path") for item in files}) != 6 + or value.get("results_before_terminal_states") is not True + or value.get("official_test_used") is not False + ): + raise ValueError("last-2 immutable release differs") + + +def central_ready(plan: dict[str, Any]) -> bool: + path = Path(plan["training_completion_state"]) + if not path.is_file(): return False + value = read_json(path) + return (value.get("status") == "complete" and value.get("candidate") == plan["candidate"] + and value.get("training_registry_sha256") == plan["training_registry"]["sha256"] + and value.get("official_test_used") is False) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): return read_json(output) + release = fetch(plan); validate_release(plan_path, plan, release) + installed = install(plan, release) + deadline = time.monotonic() + 120 + while time.monotonic() < deadline and not central_ready(plan): time.sleep(2) + if not central_ready(plan): raise TimeoutError("central last-2 training did not converge") + value = { + "schema_version": "phase9_last2_training_completion_receive_v1", + "status": "complete", "candidate": plan["candidate"], "completed_utc": utc_now(), + "plan_sha256": sha256(plan_path), "release_sha256": json_sha256(release), + "installed": installed, "file_count": 6, "total_bytes": release["total_bytes"], + "results_before_terminal_states": True, "official_test_used": False, + } + atomic_json(output, value); return value + + +def main() -> None: + parser = argparse.ArgumentParser(); parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + try: validate_plan(args.plan, plan) + except ValueError as error: parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True); deadline = time.monotonic() + args.wait_timeout_seconds + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + value = publish(args.plan, plan) if args.role == "publish" else receive(args.plan, plan) + print(json.dumps(value, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(Path(f"{target}.watcher.json"), { + "schema_version": "phase9_last2_training_completion_watcher_v1", + "status": "waiting_for_terminal_source", "candidate": plan["candidate"], + "role": args.role, "watcher_pid": os.getpid(), "updated_utc": utc_now(), + "detail": str(error), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_resolution_evaluation_completion.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_resolution_evaluation_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..7213c888087d9e7daec2af464ac979afd0e504fa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_resolution_evaluation_completion.py @@ -0,0 +1,450 @@ +#!/usr/bin/env python3 +"""Publish and import terminal server_new Stage 7 evaluation evidence.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +class NotReady(RuntimeError): + """A healthy source dependency has not reached its terminal state.""" + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: dict[str, Any]) -> str: + payload = (json.dumps(value, indent=2) + "\n").encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + if ( + plan.get("schema_version") + != "phase9_resolution_evaluation_completion_release_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or scientific.get("amendment_scope") + != "terminal_evaluation_state_and_result_handoff_only" + or any( + scientific.get(key) is not False + for key in ( + "model_changed", "data_changed", "seed_changed", + "metric_changed", "selection_gate_changed", + ) + ) + ): + raise ValueError("resolution evaluation completion plan contract differs") + for key in ( + "release_root", "staging_root", "release_state", "receive_state", + ): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution evaluation completion {key} is not /SSD2") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution evaluation completion binding differs: {path}") + if not plan_path.is_file(): + raise ValueError("resolution evaluation completion plan is unreadable") + + +def remote_inventory(plan: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]: + path = Path(plan["evaluation_plan"]["path"]) + if not path.is_file() or sha256(path) != plan["evaluation_plan"]["sha256"]: + raise ValueError("resolution evaluation plan hash differs") + dynamic = read_json(path) + workers = [item for item in dynamic["workers"] if item["owner"] == "server_new"] + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + assigned = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(dynamic["evaluations"]) != 25 + or len(dynamic["workers"]) != 10 + or len(workers) != 4 + or len(assigned) != 9 + or len(set(assigned)) != 9 + or any(evaluations[identifier]["training_role"] not in { + "loso_subject2", "loso_subject3", "lofamily_k", + } for identifier in assigned) + or dynamic.get("official_test_used") is not False + or dynamic.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new resolution evaluation ownership differs") + return dynamic, workers + + +def active_evaluator_pids(evaluation_id: str, proc_root: Path = Path("/proc")) -> list[int]: + result = [] + token = f"--evaluation-id {evaluation_id}" + for entry in proc_root.iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (FileNotFoundError, PermissionError, ProcessLookupError, UnicodeDecodeError): + continue + if "scripts.evaluate_phase7_external" in command and token in command: + result.append(int(entry.name)) + return sorted(result) + + +def release_file(root: Path, kind: str, path: Path) -> dict[str, Any]: + if not path.is_file() or path.is_symlink() or root not in path.resolve().parents: + raise ValueError(f"resolution evaluation release artifact differs: {path}") + return { + "kind": kind, + "path": str(path.resolve().relative_to(root.resolve())), + "absolute_path": str(path.resolve()), + "bytes": path.stat().st_size, + "sha256": sha256(path), + } + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + dynamic, workers = remote_inventory(plan) + dynamic_hash = plan["evaluation_plan"]["sha256"] + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): + raise NotReady("server_new evaluation controller state is missing") + controller = read_json(controller_path) + if controller.get("status") not in {"complete_local", "complete"}: + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("server_new evaluation controller failed") + raise NotReady("server_new evaluation controller is still running") + if ( + controller.get("machine") != "server_new" + or controller.get("evaluation_plan_sha256") != dynamic_hash + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new evaluation controller binding differs") + + root = Path(plan["release_root"]) + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + records = [] + files = [] + for worker in workers: + state_path = Path(worker["state"]) + if not state_path.is_file(): + raise NotReady(f"server_new evaluation worker is missing: {worker['id']}") + state = read_json(state_path) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed_terminal"): + raise ValueError(f"server_new evaluation worker failed: {worker['id']}") + raise NotReady(f"server_new evaluation worker is still running: {worker['id']}") + if ( + state.get("worker") != worker["id"] + or state.get("owner") != "server_new" + or state.get("plan_sha256") != dynamic_hash + or state.get("assigned_evaluation_ids") != worker["evaluation_ids"] + or state.get("completed_ids") != worker["evaluation_ids"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"server_new evaluation worker binding differs: {worker['id']}") + files.append(release_file(root, "worker_state", state_path)) + for identifier in worker["evaluation_ids"]: + if active_evaluator_pids(identifier): + raise NotReady(f"server_new evaluator still exists: {identifier}") + item = evaluations[identifier] + if not evaluation_complete(item): + raise ValueError(f"server_new evaluation result differs: {identifier}") + report_path = Path(item["output_dir"]) / "evaluation.json" + report = read_json(report_path) + result_files = [release_file(root, "evaluation_report", report_path)] + for key in ("raw_predictions", "per_hand_rows", "take_metrics"): + artifact = report[key] + path = Path(artifact["path"]) + record = release_file(root, key, path) + if record["sha256"] != artifact["sha256"]: + raise ValueError(f"server_new result artifact hash differs: {identifier}") + result_files.append(record) + files.extend(result_files) + records.append({ + "evaluation_id": identifier, + "worker": worker["id"], + "checkpoint_sha256": item["checkpoint_sha256"], + "config_sha256": item["config_sha256"], + "cache_manifest_sha256": item["cache_manifest_sha256"], + "clips": report["clips"], "frames": report["frames"], + "wall_seconds": report["runtime"]["wall_seconds"], + "gpu_hours": report["runtime"]["wall_seconds"] / 3600.0, + "evaluation_report_sha256": sha256(report_path), + "files": result_files, + }) + files.append(release_file(root, "controller_state", controller_path)) + paths = [item["path"] for item in files] + if len(records) != 9 or len(files) != 41 or len(paths) != len(set(paths)): + raise ValueError("server_new evaluation release inventory differs") + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + existing = read_json(output) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution evaluation release differs") + records, files = source_records(plan) + result = { + "schema_version": "phase9_resolution_evaluation_completion_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "destination_owner": "taku3", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_root": str(Path(plan["release_root"]).resolve()), + "evaluation_plan": plan["evaluation_plan"], + "evaluations": records, "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "results_before_terminal_states": True, + "single_writer_per_output": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, result) + os.chmod(output, 0o444) + for item in files: + os.chmod(item["absolute_path"], 0o444) + return result + + +def fetch_release(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", plan["source_host"], + "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + timeout=float(plan["ssh_timeout_seconds"]), + ) + if result.returncode: + raise NotReady("server_new evaluation completion release is unavailable") + try: + value = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise ValueError("server_new evaluation completion release is unreadable") from error + return value + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + files = release.get("files", []) + paths = [item.get("path") for item in files] + _, workers = remote_inventory(plan) + expected_ids = { + identifier for worker in workers for identifier in worker["evaluation_ids"] + } + records = release.get("evaluations", []) + record_ids = [item.get("evaluation_id") for item in records] + kind_counts = Counter(item.get("kind") for item in files) + if ( + release.get("schema_version") + != "phase9_resolution_evaluation_completion_release_v1" + or release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("destination_owner") != "taku3" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("evaluation_plan") != plan["evaluation_plan"] + or len(records) != 9 + or len(record_ids) != len(set(record_ids)) + or set(record_ids) != expected_ids + or len(files) != 41 or len(paths) != len(set(paths)) + or kind_counts != { + "evaluation_report": 9, "raw_predictions": 9, + "per_hand_rows": 9, "take_metrics": 9, + "worker_state": 4, "controller_state": 1, + } + or release.get("file_count") != 41 + or sum(item.get("bytes", -1) for item in files) != release.get("total_bytes") + or release.get("completion_only_reverse_release") is not True + or release.get("live_reverse_sync_performed") is not False + or release.get("results_before_terminal_states") is not True + or release.get("single_writer_per_output") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution evaluation immutable release differs") + for value in paths: + path = Path(str(value)) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"unsafe resolution evaluation release path: {path}") + file_hashes = {(item["path"], item["sha256"]) for item in files} + for record in records: + result_files = record.get("files", []) + if ( + len(result_files) != 4 + or record.get("evaluation_report_sha256") + != next( + (item["sha256"] for item in result_files + if item.get("kind") == "evaluation_report"), None, + ) + or any((item.get("path"), item.get("sha256")) not in file_hashes + for item in result_files) + ): + raise ValueError("resolution evaluation release result binding differs") + + +def verify_file(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"resolution evaluation completion file differs: {path}") + return path + + +def install_release(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root = Path(plan["release_root"]) + staging = Path(plan["staging_root"]) + pending = [] + installed = [] + for item in release["files"]: + destination = root / item["path"] + if destination.exists(): + verify_file(root, item) + installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".pending_evaluation_release_files.txt" + file_list.write_text( + "".join(item["path"] + "\n" for item in pending), encoding="utf-8", + ) + result = subprocess.run([ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['source_host']}:{root.resolve()}/", f"{staging.resolve()}/", + ], check=False) + if result.returncode: + raise RuntimeError(f"resolution evaluation rsync failed: {result.returncode}") + for item in pending: + verify_file(staging, item) + order = {"evaluation_report": 0, "raw_predictions": 0, "per_hand_rows": 0, + "take_metrics": 0, "controller_state": 1, "worker_state": 2} + for item in sorted(pending, key=lambda value: (order[value["kind"]], value["path"])): + source = staging / item["path"] + destination = root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + raise ValueError(f"resolution evaluation destination appeared: {destination}") + os.replace(source, destination) + os.chmod(destination, 0o444) + verify_file(root, item) + installed.append({**item, "resumed_existing": False}) + return sorted(installed, key=lambda item: item["path"]) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): + existing = read_json(output) + if existing.get("status") == "complete" and existing.get("plan_sha256") == sha256(plan_path): + return existing + raise ValueError("existing resolution evaluation receive state differs") + release = fetch_release(plan) + validate_release(plan_path, plan, release) + installed = install_release(plan, release) + result = { + "schema_version": "phase9_resolution_evaluation_completion_receive_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state": plan["release_state"], + "release_sha256": json_sha256(release), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "installed": installed, + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "results_before_terminal_states": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, result) + return result + + +def wait_for_result( + role: str, plan_path: Path, plan: dict[str, Any], timeout_seconds: float, +) -> dict[str, Any]: + deadline = time.monotonic() + timeout_seconds + watcher_path = Path( + f"{plan['release_state' if role == 'publish' else 'receive_state']}.watcher.json" + ) + while True: + try: + return publish(plan_path, plan) if role == "publish" else receive(plan_path, plan) + except NotReady as error: + if timeout_seconds <= 0 or time.monotonic() >= deadline: + raise + atomic_json(watcher_path, { + "schema_version": "phase9_resolution_evaluation_completion_watcher_v1", + "status": "waiting_for_terminal_source", "role": role, + "watcher_pid": os.getpid(), "updated_utc": utc_now(), + "detail": str(error), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "h2o_official_validation_used": False, "official_test_used": False, + }) + time.sleep(min(30.0, max(1.0, deadline - time.monotonic()))) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = wait_for_result( + args.role, args.plan, plan, args.wait_timeout_seconds, + ) + except Exception as error: + atomic_json(Path(f"{target}.failure.json"), { + "schema_version": "phase9_resolution_evaluation_completion_failure_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "role": args.role, "failure": f"{type(error).__name__}: {error}", + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, "official_test_used": False, + }) + raise + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_resolution_training_completion.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_resolution_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..34c74406bf5162cc0d980d780e5ef77133e4776c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_resolution_training_completion.py @@ -0,0 +1,569 @@ +#!/usr/bin/env python3 +"""Publish and import terminal server_new Stage 7 training evidence.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any +import zipfile + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +EXPECTED_CONDITIONS = ( + "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", + "S7R_J25_lofamily_k", +) +EXPECTED_STAGES = ("smoke2", "health2k", "matched_405000") + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + if ( + plan.get("schema_version") + != "phase9_resolution_training_completion_release_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("read_only_after_publish") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or scientific.get("amendment_scope") + != "terminal_state_and_final_checkpoint_handoff_only" + or any( + scientific.get(key) is not False + for key in ( + "model_changed", "data_changed", "seed_changed", + "optimizer_changed", "horizon_changed", + "selection_gate_changed", + ) + ) + ): + raise ValueError("resolution training completion plan contract differs") + if tuple(item["condition"] for item in plan.get("conditions", [])) != EXPECTED_CONDITIONS: + raise ValueError("resolution training completion conditions differ") + for key in ("release_root", "staging_root"): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution training completion {key} is not /SSD2") + if Path(plan["release_state"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution training completion release state is not /SSD2") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution completion binding differs: {path}") + if sha256(plan_path) == "": + raise ValueError("resolution completion plan is unreadable") + + +def last_json_record(path: Path, tail_bytes: int = 1 << 20) -> dict[str, Any]: + with path.open("rb") as handle: + handle.seek(0, os.SEEK_END) + size = handle.tell() + handle.seek(max(0, size - tail_bytes)) + lines = handle.read().splitlines() + for line in reversed(lines): + if line.strip(): + value = json.loads(line) + if not isinstance(value, dict): + break + return value + raise ValueError(f"terminal metric record is unavailable: {path}") + + +def validate_condition_payload( + expected: dict[str, Any], job: dict[str, Any], state: dict[str, Any], + metric: dict[str, Any], summary: dict[str, Any], +) -> None: + marker = state.get("last_completed", {}) + attempts = state.get("attempts", []) + losses = metric.get("losses", {}) + if ( + state.get("status") != "complete" + or state.get("condition") != expected["condition"] + or state.get("queue_sha256") != expected["training_registry_sha256"] + or state.get("official_test_used") is not False + or tuple(state.get("completed_stages", [])) != EXPECTED_STAGES + or tuple(item.get("stage") for item in attempts) != EXPECTED_STAGES + or any(item.get("returncode") != 0 for item in attempts) + or marker.get("status") != "complete" + or marker.get("stage") != "matched_405000" + or marker.get("completed_step") != 405000 + or marker.get("checkpoint") != expected["checkpoint"] + or marker.get("checkpoint_sha256") != expected["checkpoint_sha256"] + or marker.get("config") != job["config"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or metric.get("step") != 405000 + or not isinstance(losses, dict) + or not losses + or any( + not isinstance(value, (int, float)) or not math.isfinite(float(value)) + for value in losses.values() + ) + or summary.get("status") != "completed" + or summary.get("completed_step") != 405000 + or summary.get("protocol_max_steps") != 405000 + or summary.get("registered_run_end_step") != 405000 + or summary.get("final_checkpoint") != expected["checkpoint"] + or summary.get("final_checkpoint_sha256") != expected["checkpoint_sha256"] + or summary.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or summary.get("official_test_used") is not False + ): + raise ValueError( + f"resolution terminal training evidence differs: {expected['condition']}" + ) + + +def writer_matches(command: str, output_dir: str) -> bool: + return ( + "scripts.train_phase7_external" in command + and f"--output-dir {output_dir}" in command + ) + + +def active_writer_pids(output_dir: str, proc_root: Path = Path("/proc")) -> list[int]: + result = [] + for entry in proc_root.iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (FileNotFoundError, PermissionError, UnicodeDecodeError, ProcessLookupError): + continue + if writer_matches(command, output_dir): + result.append(int(entry.name)) + return sorted(result) + + +def verify_checkpoint_archive(path: Path) -> None: + if not zipfile.is_zipfile(path): + raise ValueError(f"resolution final checkpoint archive differs: {path}") + with zipfile.ZipFile(path) as archive: + if not archive.namelist() or archive.testzip() is not None: + raise ValueError(f"resolution final checkpoint is truncated: {path}") + + +def validate_source_completion(plan: dict[str, Any]) -> list[dict[str, Any]]: + assignment = load_assignment(plan) + registry_path = Path(plan["training_registry"]["path"]) + registry = read_json(registry_path) + if sha256(registry_path) != plan["training_registry"]["sha256"]: + raise ValueError("resolution completion registry hash differs") + jobs = {item["condition"]: item for item in registry["conditions"]} + owners = condition_owners(registry, assignment) + controller_path = Path(plan["source_controller_state"]["path"]) + controller = read_json(controller_path) + if ( + sha256(controller_path) != plan["source_controller_state"]["sha256"] + or controller.get("status") != "complete_local" + or controller.get("machine") != "server_new" + or controller.get("plan_sha256") + != plan["training_controller_plan"]["sha256"] + or controller.get("training_registry_sha256") + != plan["training_registry"]["sha256"] + or controller.get("condition_statuses") + != {condition: "complete" for condition in EXPECTED_CONDITIONS} + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new resolution controller completion differs") + + records = [] + root = Path(plan["release_root"]) + for expected in plan["conditions"]: + condition = expected["condition"] + if condition not in jobs or owners.get(condition) != "server_new": + raise ValueError(f"resolution completion ownership differs: {condition}") + job = jobs[condition] + config = Path(job["config"]) + state_path = Path(expected["state"]) + checkpoint = Path(expected["checkpoint"]) + metrics = Path(expected["metrics"]) + summary_path = Path(expected["summary"]) + for path in (state_path, checkpoint, metrics, summary_path, config): + if not path.is_file() or path.is_symlink(): + raise ValueError(f"resolution terminal artifact differs: {path}") + if ( + sha256(config) != job["config_sha256"] + or sha256(state_path) != expected["state_sha256"] + or checkpoint.stat().st_size != expected["checkpoint_bytes"] + or sha256(checkpoint) != expected["checkpoint_sha256"] + or sha256(metrics) != expected["metrics_sha256"] + or sha256(summary_path) != expected["summary_sha256"] + ): + raise ValueError(f"resolution terminal artifact hash differs: {condition}") + if active_writer_pids(job["output_dir"]): + raise ValueError(f"resolution output still has a writer: {condition}") + state = read_json(state_path) + metric = last_json_record(metrics) + summary = read_json(summary_path) + validate_condition_payload(expected, job, state, metric, summary) + verify_checkpoint_archive(checkpoint) + condition_files = [] + for kind, path in (("checkpoint", checkpoint), ("training_state", state_path)): + if root not in path.parents: + raise ValueError(f"resolution release file is outside root: {path}") + condition_files.append({ + "kind": kind, + "path": str(path.relative_to(root)), + "absolute_path": str(path.resolve()), + "bytes": path.stat().st_size, + "sha256": sha256(path), + }) + records.append({ + "condition": condition, + "role": job["role"], + "completed_utc": state["completed_utc"], + "gpu_hours": state["gpu_hours_consumed"], + "wall_seconds": marker_wall_seconds(state), + "final_total_loss": float(metric["losses"]["total"]), + "metrics_sha256": expected["metrics_sha256"], + "summary_sha256": expected["summary_sha256"], + "checkpoint_archive_crc_verified": True, + "active_writer_pids": [], + "files": condition_files, + }) + return records + + +def marker_wall_seconds(state: dict[str, Any]) -> float: + marker = state.get("last_completed", {}) + value = marker.get("wall_seconds") + if not isinstance(value, (int, float)) or not math.isfinite(float(value)): + raise ValueError("resolution terminal wall time differs") + return float(value) + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + existing = read_json(output) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution completion release differs") + conditions = validate_source_completion(plan) + files = [item for condition in conditions for item in condition["files"]] + paths = [item["path"] for item in files] + if len(paths) != 6 or len(set(paths)) != 6: + raise ValueError("resolution completion release inventory differs") + release = { + "schema_version": "phase9_resolution_training_completion_release_v1", + "status": "complete_immutable_release", + "created_utc": utc_now(), + "owner": "server_new", + "destination_owner": "taku3", + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "release_root": str(Path(plan["release_root"]).resolve()), + "source_controller_state": plan["source_controller_state"], + "conditions": conditions, + "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "read_only_after_publish": True, + "single_writer_per_output": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(output, release) + os.chmod(output, 0o444) + for item in files: + os.chmod(Path(item["absolute_path"]), 0o444) + return release + + +def fetch_remote_json(host: str, path: str, timeout: float) -> dict[str, Any]: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if result.returncode: + raise ValueError("resolution completion release is unavailable") + try: + value = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise ValueError("resolution completion release is unreadable") from error + if not isinstance(value, dict): + raise ValueError("resolution completion release is not an object") + return value + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + files = release.get("files", []) + paths = [item.get("path") for item in files] + if ( + release.get("schema_version") + != "phase9_resolution_training_completion_release_v1" + or release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("destination_owner") != "taku3" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("completion_only_reverse_release") is not True + or release.get("live_reverse_sync_performed") is not False + or release.get("read_only_after_publish") is not True + or release.get("single_writer_per_output") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or len(files) != 6 + or len(paths) != len(set(paths)) + or release.get("file_count") != 6 + or sum(item.get("bytes", -1) for item in files) != release.get("total_bytes") + ): + raise ValueError("resolution completion immutable release differs") + expected = { + (item["state_sha256"], item["checkpoint_sha256"]) + for item in plan["conditions"] + } + observed = { + ( + next(file["sha256"] for file in item["files"] if file["kind"] == "training_state"), + next(file["sha256"] for file in item["files"] if file["kind"] == "checkpoint"), + ) + for item in release.get("conditions", []) + } + if expected != observed: + raise ValueError("resolution completion condition hashes differ") + for value in paths: + path = Path(str(value)) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"unsafe resolution completion release path: {path}") + + +def verify_record(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"resolution completion file differs: {path}") + return path + + +def validate_global_completion_payload( + controller: dict[str, Any], registry_sha256: str, + conditions: dict[str, dict[str, Any]], +) -> None: + expected = { + "S7R_J25_full", "S7R_J25_loso_subject1", "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", "S7R_J25_lofamily_h", + "S7R_J25_lofamily_k", "S7R_J25_lofamily_o", + } + if ( + controller.get("status") != "complete" + or controller.get("machine") != "taku3" + or controller.get("training_registry_sha256") != registry_sha256 + or controller.get("condition_statuses") + != {condition: "complete" for condition in sorted(expected)} + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + or set(conditions) != expected + or any( + state.get("status") != "complete" + or state.get("queue_sha256") != registry_sha256 + or state.get("last_completed", {}).get("completed_step") != 405000 + or state.get("official_test_used") is not False + for state in conditions.values() + ) + ): + raise ValueError("global resolution training completion differs") + + +def install_release(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root = Path(plan["release_root"]) + staging = Path(plan["staging_root"]) + pending = [] + installed = [] + for item in release["files"]: + destination = root / item["path"] + if destination.exists(): + verify_record(root, item) + installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".pending_release_files.txt" + file_list.write_text( + "".join(item["path"] + "\n" for item in pending), encoding="utf-8", + ) + result = subprocess.run([ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['source_host']}:{root.resolve()}/", f"{staging.resolve()}/", + ], check=False) + if result.returncode: + raise RuntimeError(f"resolution completion rsync failed: {result.returncode}") + for item in pending: + verify_record(staging, item) + for kind in ("checkpoint", "training_state"): + for item in pending: + if item["kind"] != kind: + continue + source = staging / item["path"] + destination = root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + raise ValueError(f"resolution completion destination appeared: {destination}") + os.replace(source, destination) + os.chmod(destination, 0o444) + verify_record(root, item) + installed.append({**item, "resumed_existing": False}) + return sorted(installed, key=lambda item: item["path"]) + + +def backup_central_controller(plan: dict[str, Any]) -> dict[str, str]: + source = Path(plan["central_controller_state"]) + destination = Path(plan["central_controller_backup"]) + if destination.exists(): + return {"path": str(destination.resolve()), "sha256": sha256(destination)} + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + os.chmod(destination, 0o444) + return {"path": str(destination.resolve()), "sha256": sha256(destination)} + + +def wait_for_global_completion(plan: dict[str, Any]) -> dict[str, Any]: + deadline = time.monotonic() + float(plan["central_completion_timeout_seconds"]) + registry_hash = plan["training_registry"]["sha256"] + state_root = Path(plan["training_state_root"]) + while time.monotonic() < deadline: + controller = read_json(plan["central_controller_state"]) + registry = read_json(plan["training_registry"]["path"]) + states = { + item["condition"]: read_json( + state_root / f"{item['condition'].lower()}.json" + ) + for item in registry["conditions"] + } + try: + validate_global_completion_payload(controller, registry_hash, states) + except ValueError: + time.sleep(2) + continue + return controller + raise TimeoutError("central resolution training controller did not converge") + + +def receive(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + if state_path.is_file(): + existing = read_json(state_path) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution completion receive state differs") + release = fetch_remote_json( + plan["source_host"], plan["release_state"], + float(plan["ssh_timeout_seconds"]), + ) + validate_release(plan_path, plan, release) + backup = backup_central_controller(plan) + installed = install_release(plan, release) + controller = wait_for_global_completion(plan) + result = { + "schema_version": "phase9_resolution_training_completion_receive_v1", + "status": "complete", + "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "release_state": plan["release_state"], + "release_sha256": sha256_bytes(release), + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + "installed": installed, + "central_controller_backup": backup, + "central_controller_state": { + "path": str(Path(plan["central_controller_state"]).resolve()), + "sha256": sha256(plan["central_controller_state"]), + "status": controller["status"], + }, + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(state_path, result) + return result + + +def sha256_bytes(value: dict[str, Any]) -> str: + import hashlib + payload = (json.dumps(value, indent=2) + "\n").encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--state", type=Path) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + expected = Path( + plan["release_state"] if args.role == "publish" else plan["receive_state"] + ) + if args.state and args.state.resolve() != expected.resolve(): + parser.error("resolution completion state path differs") + expected.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{expected}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = publish(args.plan, plan) if args.role == "publish" else receive( + args.plan, plan, expected, + ) + except Exception as error: + failure = Path(f"{expected}.failure.json") + atomic_json(failure, { + "schema_version": "phase9_resolution_training_completion_failure_v1", + "status": "failed_resumable", + "updated_utc": utc_now(), + "role": args.role, + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used": False, + "official_test_used": False, + }) + raise + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_resolution_training_handoff.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_resolution_training_handoff.py new file mode 100644 index 0000000000000000000000000000000000000000..e55e92fce4239842ceb0765c72f32f3d506032e7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_resolution_training_handoff.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Publish central Stage 7 readiness and registry to server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +import subprocess +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + unchanged_fields = ( + "model_changed", + "data_changed", + "seed_changed", + "optimizer_changed", + "horizon_changed", + "selection_gate_changed", + ) + if ( + plan.get("schema_version") + != "phase9_resolution_distributed_training_handoff_amendment_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "taku3" + or plan.get("destination_owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("readiness_published_last") is not True + or plan.get("immutable_sync") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("server_new_physical_gpu_allowlist") != [0, 1, 2, 5] + or plan.get("external_owned_conditions") != [ + "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", + "S7R_J25_lofamily_k", + ] + or scientific.get("amendment_scope") + != "resource_scheduling_and_immutable_handoff_only" + or any(scientific.get(field) is not False for field in unchanged_fields) + ): + raise ValueError("resolution training handoff plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution training handoff binding differs: {path}") + + +def ordered_handoff_files(plan: dict[str, Any]) -> list[dict[str, Any]]: + records = list(plan["files"]) + if ( + not records or records[-1].get("role") != "readiness" + or any(item.get("role") == "readiness" for item in records[:-1]) + or len({item["path"] for item in records}) != len(records) + ): + raise ValueError("resolution readiness must be published uniquely and last") + return records + + +def remote_sha256(host: str, path: str) -> str | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "sha256sum", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode or not completed.stdout.strip(): + return None + return completed.stdout.split()[0] + + +def prepare_remote_parent(host: str, path: str) -> None: + parent = str(Path(path).parent) + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "mkdir", "-p", parent], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode: + detail = completed.stderr.strip() or f"returncode={completed.returncode}" + raise ValueError(f"cannot prepare resolution handoff parent {parent}: {detail}") + + +def validate_remote_cache_receive(plan: dict[str, Any]) -> None: + item = plan["remote_cache_receive_state"] + if remote_sha256(plan["destination_host"], item["path"]) != item["sha256"]: + raise ValueError("server_new cache receive state hash differs") + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", plan["destination_host"], "cat", item["path"]], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode: + raise ValueError("server_new cache receive state is unreadable") + try: + state = json.loads(completed.stdout) + except json.JSONDecodeError as error: + raise ValueError("server_new cache receive state is unreadable") from error + if ( + state.get("status") != "complete" + or state.get("file_count") != item["file_count"] + or state.get("total_bytes") != item["total_bytes"] + or state.get("read_only") is not True + or state.get("live_reverse_sync_performed") is not False + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new cache receive state contract differs") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(plan) + records = ordered_handoff_files(plan) + validate_remote_cache_receive(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("resolution training handoff state differs") + if args.state.is_file(): + existing = read_json(args.state) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == sha256(args.plan) + ): + print(json.dumps(existing, indent=2)) + return + parser.error("existing resolution training handoff state differs") + published = [] + for item in records: + source = Path(item["path"]) + if not source.is_file() or sha256(source) != item["sha256"]: + parser.error(f"resolution handoff source differs: {source}") + try: + prepare_remote_parent(plan["destination_host"], str(source.resolve())) + except ValueError as error: + parser.error(str(error)) + completed = subprocess.run([ + "rsync", "-a", "--chmod=F444", str(source.resolve()), + f"{plan['destination_host']}:{source.resolve()}", + ], check=False) + if completed.returncode: + raise SystemExit(completed.returncode) + if remote_sha256(plan["destination_host"], str(source.resolve())) != item["sha256"]: + parser.error(f"resolution handoff remote hash differs: {source}") + published.append(item) + state = { + "schema_version": "phase9_resolution_training_handoff_state_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "destination": plan["destination_host"], "published": published, + "readiness_published_last": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_shared_augmentation_admission.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_shared_augmentation_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c3d14120047c2df37a4932378ce275eb8da7e8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_shared_augmentation_admission.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Forward-sync frozen Stage 8 admission and start the remote owner controller.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def admission_files(plan: dict[str, Any]) -> tuple[list[Path], list[dict[str, str]]]: + controller_path = Path(plan["controller_states"]["taku3"]) + if not controller_path.is_file(): + raise NotReady("central Stage 8 controller state is missing") + controller = read_json(controller_path) + registry_path = Path(plan["training_registry"]) + if not registry_path.is_file() or not controller.get("training_registry_sha256"): + raise NotReady("central Stage 8 registry is not frozen yet") + if ( + controller.get("plan_sha256") != sha256(plan_path_from_state(controller)) + or controller.get("training_registry") != str(registry_path.resolve()) + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("central Stage 8 controller binding differs") + registry = read_json(registry_path) + assignment = load_assignment(plan) + owners = condition_owners(registry, assignment) + conditions = registry.get("conditions", []) + if ( + registry.get("status") != "frozen_ready" + or len(conditions) != 7 + or len({item["condition"] for item in conditions}) != 7 + or sum(owner == "server_new" for owner in owners.values()) != 3 + or registry.get("official_test_used") is not False + or registry.get("h2o_official_validation_used_for_selection") is not False + ): + raise ValueError("Stage 8 training registry contract differs") + resolution_state = Path(plan["resolution_controller_state"]) + state = read_json(resolution_state) + decision = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != plan["resolution_controller_plan_sha256"] + or not decision.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(decision) + or state.get("official_test_used") is not False + ): + raise ValueError("Stage 8 resolution admission binding differs") + files = [ + decision, resolution_state, Path(plan["registry_builder_state"]), + *[Path(item["config"]) for item in conditions], registry_path, + ] + for path in files: + if not path.is_file(): + raise ValueError(f"Stage 8 admission file is missing: {path}") + prerequisites = [] + seen = set() + for item in conditions: + pair = (item["initialization_checkpoint"], item["initialization_checkpoint_sha256"]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + for item in registry["data_artifacts"]: + pair = (item["path"], item["sha256"]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + return files, prerequisites + + +def plan_path_from_state(state: dict[str, Any]) -> Path: + path = Path(state.get("plan", "")) + if not path.is_file(): + raise ValueError("Stage 8 controller plan is missing") + return path + + +def remote_sha256(host: str, path: Path) -> str | None: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "sha256sum", str(path)], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, check=False, + ) + return result.stdout.split()[0] if result.returncode == 0 else None + + +def install_file(host: str, path: Path) -> dict[str, Any]: + digest = sha256(path) + observed = remote_sha256(host, path) + if observed is not None: + if observed != digest: + raise ValueError(f"remote Stage 8 admission destination differs: {path}") + return {"path": str(path.resolve()), "sha256": digest, "resumed_existing": True} + temporary = Path(f"{path}.incoming-stage8-v3") + mkdir = subprocess.run( + ["ssh", host, "mkdir", "-p", str(path.parent)], check=False, + ) + if mkdir.returncode: + raise RuntimeError(f"remote Stage 8 admission mkdir failed: {path.parent}") + copied = subprocess.run( + ["rsync", "-a", str(path), f"{host}:{temporary}"], check=False, + ) + if copied.returncode or remote_sha256(host, temporary) != digest: + raise RuntimeError(f"remote Stage 8 admission staging differs: {path}") + installed = subprocess.run( + ["ssh", host, "mv", str(temporary), str(path)], check=False, + ) + if installed.returncode or remote_sha256(host, path) != digest: + raise RuntimeError(f"remote Stage 8 admission install differs: {path}") + return {"path": str(path.resolve()), "sha256": digest, "resumed_existing": False} + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/controller_logs/server_new_training.log" + command = ( + "cd /home/jiasen/foundation_hand && mkdir -p " + str(Path(log).parent) + + " && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_shared_augmentation_training_controller --plan " + + str(plan_path.resolve()) + " --state " + state + + " --machine server_new --poll-seconds 30 >> " + log + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", plan["source_host"], command], check=False) + if result.returncode: + raise RuntimeError("remote Stage 8 controller launch failed") + time.sleep(2) + probe = subprocess.run( + ["ssh", plan["source_host"], "pgrep", "-fo", + "scripts.run_phase9_shared_augmentation_training_controller.*shared_augmentation_v3.*server_new.json"], + stdout=subprocess.PIPE, text=True, check=False, + ) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote Stage 8 controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + files, prerequisites = admission_files(plan) + host = plan["source_host"] + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"local Stage 8 prerequisite differs: {path}") + if remote_sha256(host, path) != item["sha256"]: + raise ValueError(f"remote Stage 8 immutable prerequisite differs: {path}") + registry = Path(plan["training_registry"]) + installed = [] + for path in [item for item in files if item != registry] + [registry]: + installed.append(install_file(host, path)) + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_shared_augmentation_admission_sync_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "installed": installed, "immutable_prerequisites": prerequisites, + "remote_controller_pid": pid, + "registry_installed_last": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args() + plan = read_json(args.plan) + plan["source_host"] = "server_new" + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan) + atomic_json(args.state, result) + print(json.dumps(result, indent=2)) + return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: + raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_admission_sync_v1", + "status": "waiting_for_frozen_registry", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, "official_test_used": False, + }) + time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_shared_augmentation_evaluation_admission.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_shared_augmentation_evaluation_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..77f49003f8c121544b93407abc20a771830f37e0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_shared_augmentation_evaluation_admission.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Forward-sync the frozen Stage 8 evaluation plan to server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def frozen_payload(plan: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, str]]]: + dynamic_path = Path(plan["evaluation_plan"]) + central_state = Path(plan["controller_states"]["taku3"]) + if not dynamic_path.is_file() or not central_state.is_file(): + raise NotReady("central Stage 8 evaluation plan is not frozen yet") + state = read_json(central_state) + dynamic = read_json(dynamic_path) + if not state.get("evaluation_plan_sha256"): + raise NotReady("central Stage 8 evaluation controller has not admitted the plan") + if ( + state.get("plan_sha256") != sha256(Path(state["plan"])) + or state.get("evaluation_plan") != str(dynamic_path.resolve()) + or state.get("evaluation_plan_sha256") != sha256(dynamic_path) + or len(dynamic.get("evaluations", [])) != 25 + or len(dynamic.get("workers", [])) != 10 + or dynamic.get("worker_heartbeat_seconds") != 30 + or dynamic.get("stall_timeout_seconds") != 900 + or dynamic.get("official_test_used") is not False + ): + raise ValueError("Stage 8 evaluation admission binding differs") + remote_ids = { + identifier for worker in dynamic["workers"] if worker["owner"] == "server_new" + for identifier in worker["evaluation_ids"] + } + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + if len(remote_ids) != 9: + raise ValueError("Stage 8 remote evaluation ownership differs") + prerequisites = [] + seen = set() + for identifier in sorted(remote_ids): + item = evaluations[identifier] + for path_key, hash_key in ( + ("config", "config_sha256"), ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256"), + ): + pair = (item[path_key], item[hash_key]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + return dynamic, prerequisites + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/controller_logs/server_new_evaluation.log" + command = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_shared_augmentation_evaluation_controller --plan " + + str(plan_path.resolve()) + " --state " + state + + " --machine server_new --poll-seconds 30 >> " + log + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: + raise RuntimeError("remote Stage 8 evaluation controller launch failed") + time.sleep(2) + probe = subprocess.run([ + "ssh", "server_new", "pgrep", "-fo", + "scripts.run_phase9_shared_augmentation_evaluation_controller.*shared_augmentation_v3.*server_new.json", + ], stdout=subprocess.PIPE, text=True, check=False) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote Stage 8 evaluation controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + _, prerequisites = frozen_payload(plan) + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"central Stage 8 evaluation prerequisite differs: {path}") + if remote_sha256("server_new", path) != item["sha256"]: + raise ValueError(f"remote Stage 8 evaluation prerequisite differs: {path}") + dynamic = Path(plan["evaluation_plan"]) + files = [ + Path(plan["training_controller_state"]), Path(plan["evaluation_plan_state"]), + dynamic, + ] + installed = [install_file("server_new", path) for path in files[:-1]] + installed.append(install_file("server_new", dynamic)) + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_shared_augmentation_evaluation_admission_sync_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "evaluation_plan_sha256": sha256(dynamic), "installed": installed, + "immutable_prerequisites": prerequisites, "evaluation_plan_installed_last": True, + "remote_controller_pid": pid, "official_test_used": False, + "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_evaluation_admission_sync_v1", + "status": "waiting_for_frozen_evaluation_plan", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "plan_sha256": sha256(args.plan), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_shared_augmentation_training_completion.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_shared_augmentation_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..8c94bcfcd6549c3e5607171cb2a612bd1d6b3b3e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_shared_augmentation_training_completion.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Completion-only server_new to taku3 handoff for Stage 8 training.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_resolution_training_completion import ( + active_writer_pids, + last_json_record, + verify_checkpoint_archive, +) + + +EXPECTED = ( + "S8A_J25_loso_subject2", "S8A_J25_loso_subject3", "S8A_J25_lofamily_k", +) + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: dict[str, Any]) -> str: + return hashlib.sha256((json.dumps(value, indent=2) + "\n").encode()).hexdigest() + + +def validate_plan(path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("schema_version") + != "phase9_shared_augmentation_training_completion_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or tuple(plan.get("conditions", [])) != EXPECTED + or plan.get("target_step") != 405000 + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("Stage 8 training completion plan contract differs") + for key in ("release_root", "staging_root", "release_state", "receive_state"): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"Stage 8 completion {key} is not /SSD2") + for binding in plan["bindings"]: + candidate = Path(binding["path"]) + if not candidate.is_file() or sha256(candidate) != binding["sha256"]: + raise ValueError(f"Stage 8 completion binding differs: {candidate}") + if not path.is_file(): + raise ValueError("Stage 8 completion plan is unreadable") + + +def registry_payload(plan: dict[str, Any]) -> tuple[Path, dict[str, Any], dict[str, Any]]: + path = Path(plan["training_registry"]["path"]) + if not path.is_file() or sha256(path) != plan["training_registry"]["sha256"]: + raise ValueError("Stage 8 training registry hash differs") + registry = read_json(path) + owners = condition_owners(registry, load_assignment(plan)) + jobs = {item["condition"]: item for item in registry["conditions"]} + if ( + registry.get("status") != "frozen_ready" + or registry.get("target_step") != 405000 + or tuple(condition for condition in jobs if owners[condition] == "server_new") + != EXPECTED + or registry.get("official_test_used") is not False + ): + raise ValueError("Stage 8 training registry contract differs") + return path, registry, jobs + + +def validate_terminal(job: dict[str, Any], state: dict[str, Any]) -> tuple[Path, dict[str, Any]]: + marker = state.get("last_completed", {}) + checkpoint = Path(marker.get("checkpoint", "")) + metrics = Path(job["output_dir"]) / "metrics.jsonl" + summary_path = Path(job["output_dir"]) / "summary.json" + if not checkpoint.is_file() or not metrics.is_file() or not summary_path.is_file(): + raise ValueError(f"Stage 8 terminal artifact is missing: {job['condition']}") + metric = last_json_record(metrics) + summary = read_json(summary_path) + losses = metric.get("losses", {}) + if ( + state.get("status") != "complete" + or state.get("condition") != job["condition"] + or marker.get("completed_step") != 405000 + or marker.get("config") != job["config"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") != job["expected_source_exposure_batches"] + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or metric.get("step") != 405000 + or not losses + or any(not isinstance(value, (int, float)) or not math.isfinite(float(value)) + for value in losses.values()) + or summary.get("status") != "completed" + or summary.get("completed_step") != 405000 + or summary.get("final_checkpoint_sha256") != marker["checkpoint_sha256"] + or summary.get("official_test_used") is not False + or state.get("official_test_used") is not False + ): + raise ValueError(f"Stage 8 terminal evidence differs: {job['condition']}") + verify_checkpoint_archive(checkpoint) + return checkpoint, {"metric": metric, "summary": summary, + "metrics_sha256": sha256(metrics), + "summary_sha256": sha256(summary_path)} + + +def file_record(root: Path, kind: str, path: Path) -> dict[str, Any]: + if not path.is_file() or path.is_symlink() or root not in path.resolve().parents: + raise ValueError(f"Stage 8 release file differs: {path}") + return {"kind": kind, "path": str(path.resolve().relative_to(root.resolve())), + "absolute_path": str(path.resolve()), "bytes": path.stat().st_size, + "sha256": sha256(path)} + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + registry_path, _, jobs = registry_payload(plan) + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): + raise NotReady("server_new Stage 8 controller state is missing") + controller = read_json(controller_path) + if controller.get("status") != "complete_local": + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("server_new Stage 8 controller failed") + raise NotReady("server_new Stage 8 training is still running") + if ( + controller.get("plan_sha256") != plan["training_controller_plan"]["sha256"] + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("condition_statuses") != {condition: "complete" for condition in EXPECTED} + or controller.get("official_test_used") is not False + ): + raise ValueError("server_new Stage 8 controller binding differs") + root = Path(plan["release_root"]) + state_root = Path(plan["training_state_root"]) + records, files = [], [] + for condition in EXPECTED: + job = jobs[condition] + state_path = state_root / f"{condition.lower()}.json" + state = read_json(state_path) + if state.get("queue_sha256") != sha256(registry_path): + raise ValueError(f"Stage 8 state registry binding differs: {condition}") + if active_writer_pids(job["output_dir"]): + raise NotReady(f"Stage 8 writer still exists: {condition}") + checkpoint, evidence = validate_terminal(job, state) + condition_files = [file_record(root, "checkpoint", checkpoint), + file_record(root, "training_state", state_path)] + files.extend(condition_files) + records.append({ + "condition": condition, "role": job["role"], + "checkpoint_sha256": sha256(checkpoint), + "final_total_loss": float(evidence["metric"]["losses"]["total"]), + "metrics_sha256": evidence["metrics_sha256"], + "summary_sha256": evidence["summary_sha256"], + "gpu_hours": state["gpu_hours_consumed"], "files": condition_files, + }) + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + value = read_json(output) + if value.get("status") == "complete_immutable_release" and value.get("plan_sha256") == sha256(plan_path): + return value + raise ValueError("existing Stage 8 release differs") + records, files = source_records(plan) + value = { + "schema_version": "phase9_shared_augmentation_training_completion_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "destination_owner": "taku3", + "plan_sha256": sha256(plan_path), "release_root": plan["release_root"], + "training_registry": plan["training_registry"], + "conditions": records, "files": files, "file_count": 6, + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, "live_reverse_sync_performed": False, + "results_before_terminal_states": True, "single_writer_per_output": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, value) + os.chmod(output, 0o444) + for item in files: + os.chmod(item["absolute_path"], 0o444) + return value + + +def fetch(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run(["ssh", plan["source_host"], "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, check=False) + if result.returncode: + raise NotReady("server_new Stage 8 release is unavailable") + return json.loads(result.stdout) + + +def validate_release(plan_path: Path, plan: dict[str, Any], value: dict[str, Any]) -> None: + files = value.get("files", []) + if ( + value.get("schema_version") != "phase9_shared_augmentation_training_completion_release_v1" + or value.get("status") != "complete_immutable_release" + or value.get("plan_sha256") != sha256(plan_path) + or value.get("training_registry") != plan["training_registry"] + or tuple(item.get("condition") for item in value.get("conditions", [])) != EXPECTED + or len(files) != 6 or len({item.get("path") for item in files}) != 6 + or sum(item.get("bytes", -1) for item in files) != value.get("total_bytes") + or value.get("results_before_terminal_states") is not True + or value.get("official_test_used") is not False + ): + raise ValueError("Stage 8 immutable release differs") + + +def verify(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if (not path.is_file() or path.is_symlink() or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"]): + raise ValueError(f"Stage 8 completion file differs: {path}") + return path + + +def install(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root, staging = Path(plan["release_root"]), Path(plan["staging_root"]) + pending, installed = [], [] + for item in release["files"]: + if (root / item["path"]).exists(): + verify(root, item); installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + listing = staging / ".pending_stage8_files.txt" + listing.write_text("".join(item["path"] + "\n" for item in pending), encoding="utf-8") + result = subprocess.run(["rsync", "-a", "--partial", f"--files-from={listing}", + f"{plan['source_host']}:{root}/", f"{staging}/"], check=False) + if result.returncode: + raise RuntimeError("Stage 8 completion rsync failed") + for item in pending: verify(staging, item) + for kind in ("checkpoint", "training_state"): + for item in pending: + if item["kind"] != kind: continue + source, destination = staging / item["path"], root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination); os.chmod(destination, 0o444) + verify(root, item); installed.append({**item, "resumed_existing": False}) + return installed + + +def central_complete(plan: dict[str, Any]) -> bool: + path = Path(plan["central_controller_state"]) + if not path.is_file(): return False + value = read_json(path) + return (value.get("status") == "complete" + and value.get("training_registry_sha256") == plan["training_registry"]["sha256"] + and value.get("official_test_used") is False) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): return read_json(output) + release = fetch(plan); validate_release(plan_path, plan, release) + backup = Path(plan["central_controller_backup"]) + if not backup.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(plan["central_controller_state"], backup); os.chmod(backup, 0o444) + installed = install(plan, release) + deadline = time.monotonic() + plan["central_completion_timeout_seconds"] + while time.monotonic() < deadline and not central_complete(plan): time.sleep(2) + if not central_complete(plan): raise TimeoutError("central Stage 8 controller did not converge") + value = { + "schema_version": "phase9_shared_augmentation_training_completion_receive_v1", + "status": "complete", "completed_utc": utc_now(), + "plan_sha256": sha256(plan_path), "release_sha256": json_sha256(release), + "file_count": 6, "total_bytes": release["total_bytes"], "installed": installed, + "results_before_terminal_states": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, value); return value + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + try: validate_plan(args.plan, plan) + except ValueError as error: parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True) + deadline = time.monotonic() + args.wait_timeout_seconds + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + value = publish(args.plan, plan) if args.role == "publish" else receive(args.plan, plan) + print(json.dumps(value, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(Path(f"{target}.watcher.json"), { + "schema_version": "phase9_shared_augmentation_training_completion_watcher_v1", + "status": "waiting_for_terminal_source", "role": args.role, + "watcher_pid": os.getpid(), "updated_utc": utc_now(), "detail": str(error), + "plan_sha256": sha256(args.plan), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_taku_resolution_caches.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_taku_resolution_caches.py new file mode 100644 index 0000000000000000000000000000000000000000..84cb358bfea905f09ef6978f46deff950973aab4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/sync_phase9_taku_resolution_caches.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python3 +"""Publish and install Taku3-owned Stage 7 caches on server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("source_owner") != "taku3" + or plan.get("destination_owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("live_reverse_sync_forbidden") is not True + ): + raise ValueError("Taku3 cache sync plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"Taku3 cache sync binding differs: {path}") + root = Path(plan["release_root"]) + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("Taku3 cache sync root is not /SSD2") + for item in plan["artifacts"]: + path = Path(item["path"]) + if root not in path.parents: + raise ValueError(f"Taku3 cache artifact is outside release root: {path}") + + +def known_payload_hashes(manifests: list[str]) -> dict[Path, str]: + known: dict[Path, str] = {} + hash_fields = ( + ("cache_path", "cache_sha256"), + ("joint3d_root_relative_sidecar_path", "joint3d_root_relative_sidecar_sha256"), + ) + for value in manifests: + for line in Path(value).read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + row = json.loads(line) + for path_field, hash_field in hash_fields: + if row.get(path_field) and row.get(hash_field): + path = Path(row[path_field]).resolve() + digest = row[hash_field] + previous = known.setdefault(path, digest) + if previous != digest: + raise ValueError(f"conflicting manifest payload hash: {path}") + return known + + +def inventory_artifacts( + root: Path, artifacts: list[dict[str, Any]], known: dict[Path, str], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + files: list[dict[str, Any]] = [] + artifact_records = [] + seen: set[str] = set() + for item in artifacts: + artifact = Path(item["path"]) + if not artifact.exists() or artifact.is_symlink(): + raise ValueError(f"Taku3 cache artifact differs: {artifact}") + candidates = [artifact] if artifact.is_file() else sorted(artifact.rglob("*")) + start = len(files) + for path in candidates: + if path.is_symlink(): + raise ValueError(f"Taku3 cache release refuses symlink: {path}") + if not path.is_file(): + continue + relative = str(path.relative_to(root)) + if relative in seen: + raise ValueError(f"duplicate Taku3 cache release path: {relative}") + seen.add(relative) + digest = known.get(path.resolve()) + if digest is None: + digest = sha256(path) + files.append({ + "path": relative, "sha256": digest, "bytes": path.stat().st_size, + }) + selected = files[start:] + artifact_records.append({ + "id": item["id"], "path": str(artifact.resolve()), + "relative_path": str(artifact.relative_to(root)), + "kind": "file" if artifact.is_file() else "directory", + "file_count": len(selected), + "total_bytes": sum(record["bytes"] for record in selected), + }) + return files, artifact_records + + +def validate_readiness(plan: dict[str, Any]) -> dict[str, Any]: + path = Path(plan["readiness_state"]["path"]) + state = read_json(path) + audit = Path(state.get("audit", {}).get("path", "")) + if ( + state.get("status") != "complete" + or sha256(path) != plan["readiness_state"]["sha256"] + or state.get("plan_sha256") != plan["cache_execution_plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not audit.is_file() + or state.get("audit", {}).get("sha256") != sha256(audit) + ): + raise ValueError("Taku3 cache release readiness differs") + return state + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + readiness = validate_readiness(plan) + output = Path(plan["release_state"]) + if output.is_file(): + release = read_json(output) + if ( + release.get("status") == "complete_immutable_release" + and release.get("plan_sha256") == sha256(plan_path) + ): + return release + raise ValueError("existing Taku3 cache release differs") + root = Path(plan["release_root"]) + known = known_payload_hashes(plan["payload_manifests"]) + files, artifacts = inventory_artifacts(root, plan["artifacts"], known) + release = { + "schema_version": "phase9_taku_cache_immutable_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "taku3", "destination_owner": "server_new", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_root": str(root.resolve()), + "readiness_state": { + "path": str(Path(plan["readiness_state"]["path"]).resolve()), + "sha256": plan["readiness_state"]["sha256"], + "audit": readiness["audit"], + }, + "artifacts": artifacts, "files": files, "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "payload_hash_source": "globally_audited_cache_and_sidecar_manifests", + "read_only_after_publish": True, "live_reverse_sync_forbidden": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, release) + os.chmod(output, 0o444) + for item in plan["artifacts"]: + path = Path(item["path"]) + if path.is_file(): + os.chmod(path, 0o444) + continue + for candidate in path.rglob("*"): + os.chmod(candidate, 0o555 if candidate.is_dir() else 0o444) + os.chmod(path, 0o555) + return release + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != "taku3" + or release.get("destination_owner") != "server_new" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("read_only_after_publish") is not True + or release.get("live_reverse_sync_forbidden") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or len(release.get("files", [])) != release.get("file_count") + or sum(item["bytes"] for item in release["files"]) != release.get("total_bytes") + ): + raise ValueError("Taku3 cache immutable release differs") + paths = [item["path"] for item in release["files"]] + if len(paths) != len(set(paths)) or any( + Path(path).is_absolute() or ".." in Path(path).parts for path in paths + ): + raise ValueError("Taku3 cache release paths differ") + + +def push(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + release = read_json(plan["release_state"]) + validate_release(plan_path, plan, release) + file_list = Path(plan["push_file_list"]) + file_list.parent.mkdir(parents=True, exist_ok=True) + file_list.write_text( + "".join(item["path"] + "\n" for item in release["files"]), + encoding="utf-8", + ) + state = { + "schema_version": "phase9_taku_cache_push_state_v1", + "status": "syncing", "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state_sha256": sha256(plan["release_state"]), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "destination": plan["destination_host"], + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, state) + staging = Path(plan["destination_staging_root"]) + command = [ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{Path(plan['release_root']).resolve()}/", + f"{plan['destination_host']}:{staging.resolve()}/", + ] + completed = subprocess.run(command, check=False) + state["returncode"] = completed.returncode + state["updated_utc"] = utc_now() + state["status"] = "synced_waiting_for_remote_install" if not completed.returncode else "failed_resumable" + atomic_json(state_path, state) + if completed.returncode: + raise SystemExit(completed.returncode) + return state + + +def verify_files(root: Path, release: dict[str, Any]) -> None: + for item in release["files"]: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] or sha256(path) != item["sha256"] + ): + raise ValueError(f"received Taku3 cache file differs: {path}") + + +def install(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + release = read_json(plan["release_state"]) + validate_release(plan_path, plan, release) + staging = Path(plan["destination_staging_root"]) + verify_files(staging, release) + root = Path(plan["release_root"]) + installed = [] + for item in release["artifacts"]: + source = staging / item["relative_path"] + destination = root / item["relative_path"] + if destination.exists(): + raise ValueError(f"Taku3 cache destination already exists: {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination) + if destination.is_file(): + os.chmod(destination, 0o444) + else: + for path in destination.rglob("*"): + os.chmod(path, 0o555 if path.is_dir() else 0o444) + os.chmod(destination, 0o555) + installed.append(item) + state = { + "schema_version": "phase9_taku_cache_receive_state_v1", + "status": "complete", "completed_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state_sha256": sha256(plan["release_state"]), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "installed": installed, "read_only": True, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, state) + return state + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "push", "install"), required=True) + parser.add_argument("--state", type=Path) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + expected_state = { + "publish": Path(plan["release_state"]), + "push": Path(plan["push_state"]), + "install": Path(plan["destination_receive_state"]), + }[args.role] + if args.state and args.state.resolve() != expected_state.resolve(): + parser.error("Taku3 cache sync state differs") + expected_state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{expected_state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.role == "publish": + result = publish(args.plan, plan) + elif args.role == "push": + result = push(args.plan, plan, expected_state) + else: + result = install(args.plan, plan, expected_state) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/train_experiment.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/train_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..0773e54df5b6b201d2dd25e039341ea338b675c6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/train_experiment.py @@ -0,0 +1,776 @@ +#!/usr/bin/env python3 +"""Formal H2O camera-space training entry point with hard asset/geometry gates.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import random +import shlex +import socket +import subprocess +import sys +import time +from dataclasses import asdict +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import ( + H2OCam4Dataset, + ResumableRandomBatchSampler, + ResumableWeightedBatchSampler, + collate_h2o_clips, + load_balanced_sampling_weights, +) +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.metrics import camera_metrics +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, + set_scheduled_learning_rate, +) +from foundation_hand.training.schedule import warmup_cosine_learning_rate + + +def git_state() -> str: + return subprocess.run(["git", "status", "--short"], text=True, stdout=subprocess.PIPE, check=False).stdout + + +def git_commit() -> str | None: + result = subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=False, + ) + return result.stdout.strip() or None + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def resolved_weight_path(value: str) -> Path: + path = Path(value) + return path / "model.safetensors" if path.is_dir() else path + + +def capture_run_provenance( + args: argparse.Namespace, + config: dict, + output_path: Path, +) -> Path: + assets = config["assets"] + tracked_files = { + "config": args.config, + "train_manifest": args.manifest, + "validation_manifest": args.val_manifest, + "validation_subset": args.validation_subset_manifest, + "sampling_manifest": Path(config.get("sampling", {}).get("manifest", "")), + "initialization_checkpoint": args.init_checkpoint, + "dinov3_weights": resolved_weight_path(assets["dinov3_weights"]), + "mano_left": Path(assets["mano_root"]) / "MANO_LEFT.pkl", + "mano_right": Path(assets["mano_root"]) / "MANO_RIGHT.pkl", + } + hashes = { + name: {"path": str(path.resolve()), "sha256": file_sha256(path)} + for name, path in tracked_files.items() if path is not None and path.is_file() + } + gpu_inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid,name,memory.total", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, + ).stdout.strip().splitlines() + provenance = { + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "hostname": socket.gethostname(), + "git_commit": git_commit(), + "git_status": git_state(), + "command_argv": [sys.executable, *sys.argv], + "command_shell": shlex.join([sys.executable, *sys.argv]), + "working_directory": str(Path.cwd()), + "config": config, + "seed": int(config["seed"]), + "cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "gpu_inventory": gpu_inventory, + "python": sys.version, + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "hashes": hashes, + "resume_checkpoint": str(args.resume.resolve()) if args.resume else None, + "initialization_checkpoint": ( + str(args.init_checkpoint.resolve()) if args.init_checkpoint else None + ), + } + output_path.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8") + return output_path + + +def load_validation_subset( + path: Path, + validation_manifest: Path, + data_config: dict, + dataset_size: int, +) -> tuple[list[int], dict]: + record = json.loads(path.read_text(encoding="utf-8")) + if record.get("source_manifest_sha256") != file_sha256(validation_manifest): + raise ValueError("validation subset source-manifest hash does not match --val-manifest") + contract = record.get("dataset_contract", {}) + expected = { + "resolution_hw": list(data_config["resolution_hw"]), + "T": int(data_config["T"]), + "stride": int(data_config["stride"]), + } + for key, value in expected.items(): + if contract.get(key) != value: + raise ValueError(f"validation subset contract mismatch for {key}: {contract.get(key)} != {value}") + indices = [int(index) for index in record["clip_indices"]] + if len(indices) != len(set(indices)) or not indices: + raise ValueError("validation subset indices must be non-empty and unique") + if min(indices) < 0 or max(indices) >= dataset_size: + raise ValueError("validation subset index is outside the validation dataset") + return indices, record + + +def preflight(config: dict, root: Path, manifest: Path) -> list[str]: + blockers = [] + if not root.is_dir(): blockers.append(f"dataset root missing: {root}") + if not manifest.is_file(): blockers.append(f"manifest missing: {manifest}") + assets = config.get("assets", {}) + source = Path(assets.get("dinov3_source") or "") + weights = Path(assets.get("dinov3_weights") or "") + mano_root = Path(assets.get("mano_root") or "") + if not (source / "hubconf.py").is_file(): blockers.append(f"official DINOv3 source missing: {source}") + valid_weight = weights.is_file() or (weights.is_dir() and (weights / "model.safetensors").is_file()) + if not valid_weight: blockers.append("DINOv3 pretrained weight missing; formal training forbids random DINO") + for side in ("LEFT", "RIGHT"): + if not (mano_root / f"MANO_{side}.pkl").is_file(): blockers.append(f"licensed MANO_{side}.pkl missing") + coordinate_report = Path("artifacts/phase2/coordinate_audit/mano_audit.json") + if not coordinate_report.is_file(): blockers.append("numerical MANO reconstruction/translation audit has not passed") + else: + audit = json.loads(coordinate_report.read_text(encoding="utf-8")) + if audit.get("status") != "passed": blockers.append("MANO coordinate audit exists but did not pass") + return blockers + + +def protocol_mismatches(config: dict, args: argparse.Namespace) -> list[str]: + """Reject formal runs whose CLI silently diverges from the registered config.""" + + protocol = config.get("protocol") + if protocol is None: + return [] + actual = { + "max_steps": args.max_steps, + "num_workers": args.num_workers, + "checkpoint_interval": args.checkpoint_interval, + "validation_interval": args.validation_interval, + "validation_batches": args.validation_batches, + "learning_rate": args.learning_rate, + "min_learning_rate": args.min_learning_rate, + "warmup_steps": args.warmup_steps, + "early_stopping_patience": args.early_stopping_patience, + } + mismatches = [ + f"protocol {key}={protocol.get(key)} but CLI resolved {value}" + for key, value in actual.items() if protocol.get(key) != value + ] + if "lr_schedule_steps" in protocol: + resolved_schedule_steps = ( + args.max_steps if args.lr_schedule_steps is None else args.lr_schedule_steps + ) + if protocol["lr_schedule_steps"] != resolved_schedule_steps: + mismatches.append( + "protocol lr_schedule_steps=" + f"{protocol['lr_schedule_steps']} but CLI resolved {resolved_schedule_steps}" + ) + registered_subset = protocol.get("validation_subset_manifest") + actual_subset = str(args.validation_subset_manifest) if args.validation_subset_manifest else None + if registered_subset != actual_subset: + mismatches.append( + f"protocol validation_subset_manifest={registered_subset} but CLI resolved {actual_subset}" + ) + return mismatches + + +def attach_gt_vertices(batch: dict[str, torch.Tensor], model: BimanualReconstructionModel) -> None: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for formal geometry supervision") + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, _ = model.mano_layer(rotations, torch.nan_to_num(batch["mano_shape"]), torch.nan_to_num(batch["wrist_root_translation"])) + valid = ( + batch.get("vertices_valid", batch["mano_annotation_valid"]).bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where(valid, vertices, torch.full_like(vertices, torch.nan)) + + +def move_to_device(batch: dict, device: torch.device) -> dict: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def photometric_diagnostics(batch: dict[str, torch.Tensor]) -> dict[str, float]: + parameters = batch.get("photometric_aug_params") + if parameters is None: + return {} + values = parameters[batch["frame_valid"].bool()] + if values.numel() == 0: + return {} + return { + "applied_fraction": float(values[:, 0].mean()), + "brightness_mean": float(values[:, 1].mean()), + "contrast_mean": float(values[:, 2].mean()), + "saturation_mean": float(values[:, 3].mean()), + "hue_mean": float(values[:, 4].mean()), + } + + +def run_validation( + model: BimanualReconstructionModel, + criterion: BimanualLoss, + loader: DataLoader, + device: torch.device, + dtype: torch.dtype, + max_batches: int, +) -> dict[str, dict[str, float]]: + """Run a bounded deterministic validation pass without changing train RNG.""" + + was_training = model.training + model.eval() + loss_values: dict[str, list[float]] = {} + metric_values: dict[str, list[float]] = {} + with torch.inference_mode(): + for batch_index, batch in enumerate(loader): + if batch_index >= max_batches: + break + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + for key, value in losses.items(): + scalar = float(value) + if math.isfinite(scalar): + loss_values.setdefault(key, []).append(scalar) + for key, value in camera_metrics(prediction, batch).items(): + if math.isfinite(value): + metric_values.setdefault(key, []).append(value) + model.train(was_training) + return { + "losses": {key: sum(values) / len(values) for key, values in loss_values.items()}, + "metrics": {key: sum(values) / len(values) for key, values in metric_values.items()}, + } + + +def validation_state_from_log(path: Path, metric: str) -> tuple[float, int]: + if not path.is_file(): + return float("inf"), 0 + best = float("inf") + no_improvement = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + record = json.loads(line) + value = record.get("metrics", {}).get(metric) + if value is not None and math.isfinite(value): + if float(value) < best: + best = float(value) + no_improvement = 0 + else: + no_improvement += 1 + return best, no_improvement + + +def attention_diagnostics(prediction: dict, batch: dict) -> dict[str, float | None]: + attention = prediction.get("attention", {}) + frame_valid = batch["frame_valid"].bool() + result: dict[str, float | None] = {} + if "rgb_cross_attention" in attention: + weights = attention["rgb_cross_attention"][:, -1] + left, right = weights[..., 0, :], weights[..., 1, :] + result["rgb_attention_same_peak_fraction"] = float( + (left.argmax(-1) == right.argmax(-1))[frame_valid].float().mean() + ) + result["rgb_attention_left_right_cosine"] = float( + torch.nn.functional.cosine_similarity(left, right, dim=-1)[frame_valid].mean() + ) + if "depth_fusion_gate" in attention: + result["depth_gate_mean"] = float(attention["depth_fusion_gate"][:, -1][frame_valid].float().mean()) + result["depth_gate_raw_mean"] = float(attention["depth_fusion_gate_raw"][:, -1][frame_valid].float().mean()) + result["gated_depth_update_norm_mean"] = float( + attention["gated_depth_update_norm"][:, -1][frame_valid].float().mean() + ) + if "temporal_attention" in attention: + weights = attention["temporal_attention"][:, -1] + entropy_values = [] + for batch_index in range(weights.shape[0]): + valid_indices = torch.where(frame_valid[batch_index])[0] + if valid_indices.numel() <= 1: + continue + selected = weights[batch_index, :, valid_indices][:, :, valid_indices].float() + selected = selected / selected.sum(dim=-1, keepdim=True).clamp_min(1e-8) + entropy = -(selected * selected.clamp_min(1e-8).log()).sum(dim=-1) / math.log(valid_indices.numel()) + entropy_values.append(entropy.mean()) + result["temporal_attention_normalized_entropy"] = ( + float(torch.stack(entropy_values).mean()) if entropy_values else None + ) + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--val-manifest", type=Path) + parser.add_argument("--validation-subset-manifest", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--max-steps", type=int, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--checkpoint-interval", type=int, default=100) + parser.add_argument("--learning-rate", type=float, default=1e-4) + parser.add_argument("--min-learning-rate", type=float) + parser.add_argument("--lr-schedule-steps", type=int) + parser.add_argument("--warmup-steps", type=int, default=0) + parser.add_argument("--depth-gate-warmup-steps", type=int, default=0) + parser.add_argument("--validation-interval", type=int, default=500) + parser.add_argument("--validation-batches", type=int, default=32) + parser.add_argument("--max-minutes", type=float) + parser.add_argument("--early-stopping-patience", type=int, default=0) + args = parser.parse_args() + if args.checkpoint_interval <= 0: + parser.error("--checkpoint-interval must be positive") + if args.validation_interval <= 0: + parser.error("--validation-interval must be positive") + if args.validation_batches <= 0: + parser.error("--validation-batches must be positive") + if args.max_minutes is not None and args.max_minutes <= 0: + parser.error("--max-minutes must be positive") + if args.early_stopping_patience < 0: + parser.error("--early-stopping-patience must be non-negative") + if args.resume is not None and args.init_checkpoint is not None: + parser.error("--resume and --init-checkpoint are mutually exclusive") + lr_schedule_steps = ( + args.max_steps if args.lr_schedule_steps is None else args.lr_schedule_steps + ) + if not 0 < lr_schedule_steps <= args.max_steps: + parser.error("--lr-schedule-steps must be in (0, max-steps]") + if not 0 <= args.warmup_steps < lr_schedule_steps: + parser.error("--warmup-steps must be in [0, lr-schedule-steps)") + min_learning_rate = args.learning_rate if args.min_learning_rate is None else args.min_learning_rate + if not 0 <= min_learning_rate <= args.learning_rate: + parser.error("--min-learning-rate must be in [0, learning-rate]") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + deterministic_training = bool( + config.get("protocol", {}).get("deterministic_training", False) + ) + if deterministic_training: + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.use_deterministic_algorithms(True) + torch.backends.cudnn.benchmark = False + oracle_crop_mode = config.get("model", {}).get("oracle_crop_mode", "none") + structured_refinement = bool( + config.get("model", {}).get("structured_hand_refinement", False) + ) + mixed_projection = ( + config.get("model", {}).get( + "translation_parameterization", "direct_xyz", + ) == "mixed_projection" + ) + spatial_joint2d = ( + config.get("model", {}).get( + "joint2d_parameterization", "hand_token_linear", + ) == "spatial_heatmap" + ) + matched_control_initialization = bool( + config.get("experiment", {}).get("matched_control_initialization", False) + ) + residual_initialization = ( + oracle_crop_mode != "none" or structured_refinement + or mixed_projection or spatial_joint2d + ) + if residual_initialization and args.resume is None and args.init_checkpoint is None: + parser.error("registered residual training requires --init-checkpoint on a new run") + if ( + not residual_initialization + and not matched_control_initialization + and args.init_checkpoint is not None + ): + parser.error( + "--init-checkpoint is restricted to registered residual or matched-control runs" + ) + if args.init_checkpoint is not None: + if not args.init_checkpoint.is_file(): + parser.error(f"initialization checkpoint missing: {args.init_checkpoint}") + expected_init_hash = config.get("experiment", {}).get("coarse_checkpoint_sha256") + actual_init_hash = file_sha256(args.init_checkpoint) + if expected_init_hash != actual_init_hash: + parser.error( + "initialization checkpoint hash mismatch: " + f"{actual_init_hash} != {expected_init_hash}" + ) + protocol_errors = protocol_mismatches(config, args) + if protocol_errors: + parser.error("; ".join(protocol_errors)) + if args.validation_subset_manifest is not None and args.val_manifest is None: + parser.error("--validation-subset-manifest requires --val-manifest") + if args.output_dir.exists() and any(args.output_dir.iterdir()) and args.resume is None: + parser.error("--output-dir must be new or empty unless --resume is provided") + args.output_dir.mkdir(parents=True, exist_ok=True) + blockers = preflight(config, args.root, args.manifest) + if args.val_manifest is not None and not args.val_manifest.is_file(): + blockers.append(f"validation manifest missing: {args.val_manifest}") + if args.validation_subset_manifest is not None and not args.validation_subset_manifest.is_file(): + blockers.append(f"validation subset manifest missing: {args.validation_subset_manifest}") + if blockers: + result = {"status": "blocked_preflight", "config": str(args.config), "blockers": blockers, "timestamp": datetime.now(timezone.utc).isoformat()} + (args.output_dir / "BLOCKED.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + raise SystemExit(2) + + provenance_name = "run_provenance.json" if args.resume is None else f"resume_provenance_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json" + provenance_path = capture_run_provenance(args, config, args.output_dir / provenance_name) + sampling_config = config.get("sampling", {"mode": "uniform"}) + sampling_mode = str(sampling_config.get("mode", "uniform")) + if sampling_mode not in {"uniform", "balanced"}: + parser.error(f"unsupported sampling mode: {sampling_mode}") + checkpoint_context = { + "config": config, + "external_frozen_backbone": config["assets"]["dinov3_weights"], + "sampler": ( + "global_step_weighted_v1" if sampling_mode == "balanced" + else "global_step_seeded_v1" + ), + "git_commit": git_commit(), + "run_provenance": str(provenance_path), + "run_provenance_sha256": file_sha256(provenance_path), + "initialization_checkpoint": ( + { + "path": str(args.init_checkpoint.resolve()), + "sha256": file_sha256(args.init_checkpoint), + } + if args.init_checkpoint is not None else None + ), + } + + seed = int(config["seed"]); random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + data_config, model_values, assets = config["data"], config["model"], config["assets"] + photometric_config = data_config.get("photometric_augmentation") + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + photometric_augmentation=photometric_config, + augmentation_seed=seed, + oracle_crop_enabled=oracle_crop_mode != "none", + ) + model_config = ModelConfig(**model_values, dinov3_source=assets["dinov3_source"], dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"]) + device = torch.device("cuda") + model = BimanualReconstructionModel(model_config).to(device) + initialization_record = None + if args.init_checkpoint is not None: + allowed_missing_prefixes = ( + (("oracle_crop_",) if oracle_crop_mode != "none" else ()) + + (("structured_",) if structured_refinement else ()) + + (("mixed_log_tz_head",) if mixed_projection else ()) + + (("joint_localization_",) if spatial_joint2d else ()) + ) + initialization_record = load_model_initialization( + args.init_checkpoint, model, + allowed_missing_prefixes=allowed_missing_prefixes, map_location=device, + require_residual=residual_initialization, + ) + checkpoint_context["initialization_checkpoint"].update({ + "source_step": initialization_record["step"], + "residual_missing_keys": initialization_record["residual_missing_keys"], + "checkpoint_excluded_prefixes": initialization_record[ + "checkpoint_excluded_prefixes" + ], + }) + if mixed_projection: + model.initialize_mixed_log_tz_from_direct_head() + checkpoint_context["initialization_checkpoint"].update({ + "mixed_log_tz_initialization": ( + "first-order log-softplus linearization of frozen direct-z head" + ), + "direct_xyz_teacher_frozen": True, + }) + loss_config = LossConfig(**config.get("loss", {})) + criterion = BimanualLoss(loss_config).to(device) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, + learning_rate=args.learning_rate, + backbone_learning_rate=config.get("protocol", {}).get( + "backbone_learning_rate" + ), + ), + lr=args.learning_rate, + weight_decay=0.05, + ) + excluded_checkpoint_prefixes = checkpoint_excluded_prefixes(model) + start_step = 0 + if args.resume: + start_step = int(load_checkpoint(args.resume, model, optimizer, device)["step"]) + set_scheduled_learning_rate(optimizer, args.learning_rate) + sampling_manifest_record = None + if sampling_mode == "balanced": + sampling_manifest = sampling_config.get("manifest") + if not sampling_manifest: + raise ValueError("balanced sampling requires sampling.manifest") + weights, sampling_manifest_record = load_balanced_sampling_weights( + sampling_manifest, args.manifest, data_config, len(dataset), + ) + batch_sampler = ResumableWeightedBatchSampler( + weights, int(data_config["batch_size"]), seed, start_step, args.max_steps, + include_epoch=photometric_config is not None, + ) + else: + batch_sampler = ResumableRandomBatchSampler( + len(dataset), int(data_config["batch_size"]), seed, start_step, args.max_steps, + include_epoch=photometric_config is not None, + ) + loader_generator = torch.Generator().manual_seed(seed + 10_000_000) + loader = DataLoader( + dataset, batch_sampler=batch_sampler, generator=loader_generator, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + val_loader = None + val_dataset_size = 0 + val_evaluated_samples = 0 + validation_subset_record = None + if args.val_manifest is not None: + val_dataset = H2OCam4Dataset( + args.root, args.val_manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + oracle_crop_enabled=oracle_crop_mode != "none", + ) + val_dataset_size = len(val_dataset) + if args.validation_subset_manifest is not None: + validation_indices, validation_subset_record = load_validation_subset( + args.validation_subset_manifest, args.val_manifest, data_config, len(val_dataset), + ) + expected_batches = math.ceil(len(validation_indices) / int(data_config["batch_size"])) + if args.validation_batches != expected_batches: + raise ValueError( + f"--validation-batches must be {expected_batches} to evaluate the complete fixed subset" + ) + val_evaluated_samples = len(validation_indices) + else: + val_evaluated_samples = min( + len(val_dataset), args.validation_batches * int(data_config["batch_size"]), + ) + validation_generator = torch.Generator().manual_seed(seed + 20_000_000) + validation_indices = torch.randperm( + len(val_dataset), generator=validation_generator, + )[:val_evaluated_samples].tolist() + validation_subset = Subset(val_dataset, validation_indices) + val_loader = DataLoader( + validation_subset, batch_size=int(data_config["batch_size"]), shuffle=False, + generator=torch.Generator().manual_seed(seed + 30_000_000), + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + log_path = args.output_dir / "train_metrics.jsonl" + validation_log_path = args.output_dir / "validation.jsonl" + best_metric_name = "absolute_camera_mpjpe_mm" + best_metric, no_improvement_validations = validation_state_from_log(validation_log_path, best_metric_name) + best_z_metric_name = "translation_z_mae_mm" + best_z_metric, _ = validation_state_from_log(validation_log_path, best_z_metric_name) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + completed_step = start_step + processed_frames = 0 + last_validation_step = -1 + stopped_for_time = False + stopped_for_early_stopping = False + for step, batch in zip(range(start_step, args.max_steps), loader, strict=True): + if args.max_minutes is not None and time.perf_counter() - started >= args.max_minutes * 60: + stopped_for_time = True + break + batch = move_to_device(batch, device) + processed_frames += int(batch["frame_valid"].sum()) + learning_rate = warmup_cosine_learning_rate( + step, lr_schedule_steps, args.learning_rate, min_learning_rate, + args.warmup_steps, + ) + set_scheduled_learning_rate(optimizer, learning_rate) + optimizer.zero_grad(set_to_none=True) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_diagnostics = criterion.translation_diagnostics(prediction, batch) + if not torch.isfinite(losses["total"]): + raise FloatingPointError(f"NaN/Inf loss at step {step}") + losses["total"].backward() + depth_gate_warmup_active = step < args.depth_gate_warmup_steps + if depth_gate_warmup_active: + for name, parameter in model.named_parameters(): + if ".depth_gate." in name: + parameter.grad = None + grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) + if not torch.isfinite(grad_norm): + raise FloatingPointError(f"NaN/Inf gradient at step {step}") + optimizer.step() + completed_step = step + 1 + record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": step + 1, "seed": seed, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "loss_diagnostics": { + key: float(value.detach()) for key, value in loss_diagnostics.items() + }, + "metrics": camera_metrics(prediction, batch), "gradient_norm": float(grad_norm), + "diagnostics": attention_diagnostics(prediction, batch), + "photometric_augmentation": photometric_diagnostics(batch), + "learning_rate": learning_rate, + "depth_gate_warmup_active": depth_gate_warmup_active, + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "frames_per_s": processed_frames / (time.perf_counter() - started), + } + with log_path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(record) + "\n") + if completed_step % args.checkpoint_interval == 0: + save_checkpoint( + args.output_dir / f"step_{completed_step:07d}.pt", model, optimizer, completed_step, + checkpoint_context, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if val_loader is not None and completed_step % args.validation_interval == 0: + validation = run_validation(model, criterion, val_loader, device, dtype, args.validation_batches) + validation_record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": completed_step, + "batches": args.validation_batches, **validation, + } + with validation_log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(validation_record) + "\n") + last_validation_step = completed_step + current_metric = validation["metrics"].get(best_metric_name, float("inf")) + current_z_metric = validation["metrics"].get(best_z_metric_name, float("inf")) + if current_metric < best_metric: + best_metric = current_metric + no_improvement_validations = 0 + save_checkpoint( + args.output_dir / "best.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_metric_name: best_metric}, "checkpoint_role": "best_absolute"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + else: + no_improvement_validations += 1 + if current_z_metric < best_z_metric: + best_z_metric = current_z_metric + save_checkpoint( + args.output_dir / "best_z.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_z_metric_name: best_z_metric}, "checkpoint_role": "best_z"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if args.early_stopping_patience and no_improvement_validations >= args.early_stopping_patience: + stopped_for_early_stopping = True + break + if val_loader is not None and completed_step > 0 and last_validation_step != completed_step: + validation = run_validation(model, criterion, val_loader, device, dtype, args.validation_batches) + validation_record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": completed_step, + "batches": args.validation_batches, **validation, + } + with validation_log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(validation_record) + "\n") + current_metric = validation["metrics"].get(best_metric_name, float("inf")) + current_z_metric = validation["metrics"].get(best_z_metric_name, float("inf")) + if current_metric < best_metric: + best_metric = current_metric + save_checkpoint( + args.output_dir / "best.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_metric_name: best_metric}, "checkpoint_role": "best_absolute"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if current_z_metric < best_z_metric: + best_z_metric = current_z_metric + save_checkpoint( + args.output_dir / "best_z.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_z_metric_name: best_z_metric}, "checkpoint_role": "best_z"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + final_checkpoint = args.output_dir / f"step_{completed_step:07d}_final.pt" + save_checkpoint( + final_checkpoint, model, optimizer, completed_step, + {**checkpoint_context, "checkpoint_role": "final"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + summary = { + "status": ( + "stopped_early_validation" if stopped_for_early_stopping else + "stopped_time_budget" if stopped_for_time else "completed" + ), + "config": config, "model_config": asdict(model_config), "loss_config": asdict(loss_config), + "seed": seed, "dataset_clips": len(dataset), "validation_manifest": str(args.val_manifest) if args.val_manifest else None, + "validation_dataset_clips": val_dataset_size, "validation_evaluated_samples": val_evaluated_samples, + "validation_sampling": ( + validation_subset_record.get("version") if validation_subset_record is not None else + "fixed_seed_uniform_random_subset_v1" if val_loader is not None else None + ), + "validation_subset_manifest": str(args.validation_subset_manifest.resolve()) if args.validation_subset_manifest else None, + "run_provenance": str(provenance_path), + "initialization": checkpoint_context["initialization_checkpoint"], + "start_step": start_step, "completed_step": completed_step, "requested_max_steps": args.max_steps, + "elapsed_minutes": (time.perf_counter() - started) / 60, + "sampler": checkpoint_context["sampler"], + "sampling_manifest": ( + str(Path(sampling_config["manifest"]).resolve()) + if sampling_manifest_record is not None else None + ), + "learning_rate_schedule": { + "name": "warmup_cosine_clamped", "base_lr": args.learning_rate, + "min_lr": min_learning_rate, "warmup_steps": args.warmup_steps, + "total_steps": lr_schedule_steps, + "training_max_steps": args.max_steps, + "backbone_lr_scale": next( + ( + float(group["lr_scale"]) + for group in optimizer.param_groups + if group.get("group_name") == "dinov3_backbone" + ), + None, + ), + "deterministic_training": deterministic_training, + }, + "best_validation": {best_metric_name: best_metric if math.isfinite(best_metric) else None}, + "best_z_validation": {best_z_metric_name: best_z_metric if math.isfinite(best_z_metric) else None}, + "best_z_checkpoint": str(args.output_dir / "best_z.pt") if (args.output_dir / "best_z.pt").is_file() else None, + "early_stopping_patience": args.early_stopping_patience, + "validation_checks_without_improvement": no_improvement_validations, + "best_checkpoint": str(args.output_dir / "best.pt") if (args.output_dir / "best.pt").is_file() else None, + "final_checkpoint": str(final_checkpoint), "git_status": git_state(), + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "frames_per_s": processed_frames / max(time.perf_counter() - started, 1e-6), + "precision": config["precision"], "gpu": torch.cuda.get_device_name(device), + "trainable_parameters": sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad), + "frozen_parameters": sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad), + } + (args.output_dir / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/train_phase7_external.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/train_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..fba61b4edae8c4636a2bb46343fa410e3885120a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/scripts/train_phase7_external.py @@ -0,0 +1,1316 @@ +#!/usr/bin/env python3 +"""External-only Phase 7 training over hash-bound unified clip caches.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import copy +from dataclasses import asdict +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import random +import shlex +import socket +import subprocess +import sys +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import ( + CachedUnifiedClipDataset, + ResumableMixtureBatchSampler, + UnifiedConcatDataset, + collate_h2o_clips, +) +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint, save_checkpoint +from foundation_hand.training.metrics import camera_metrics +from foundation_hand.training.optimizer import ( + clear_staged_later_gradients, + checkpoint_excluded_prefixes, + optimizer_parameter_groups, + set_scheduled_learning_rate, + set_staged_parameter_group_phase, + staged_optimizer_parameter_groups, +) +from foundation_hand.training.schedule import warmup_cosine_learning_rate +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +PHASE9_H2O_TRAIN_MANIFESTS = { + "full_data_640": Path( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "h2o_official_train7000_v1/cache_manifest.jsonl" + ), + "resolution_896x512": Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/h2o_train7000/cache_manifest.jsonl" + ), +} +PHASE9_H2O_TRAIN_MANIFESTS.update({ + "shared_augmentation_640": PHASE9_H2O_TRAIN_MANIFESTS["full_data_640"], + "shared_augmentation_896x512": PHASE9_H2O_TRAIN_MANIFESTS[ + "resolution_896x512" + ], +}) +PHASE9_H2O_FOLD_ROOTS = { + "full_data_640": Path("artifacts/phase9/manifests/h2o_multifold_v1"), + "resolution_896x512": Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "manifests/h2o_multifold_v1" + ), +} +PHASE9_H2O_FOLD_ROOTS.update({ + "shared_augmentation_640": PHASE9_H2O_FOLD_ROOTS["full_data_640"], + "shared_augmentation_896x512": PHASE9_H2O_FOLD_ROOTS[ + "resolution_896x512" + ], +}) +PHASE9_DATASETS = ("H2O", "HOT3D", "HOI4D", "ARCTIC") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def git_output(*arguments: str) -> str: + return subprocess.run( + ["git", *arguments], text=True, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=False, + ).stdout.strip() + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def assert_physical_gpu_idle(physical_gpu_id: int) -> None: + """Fail before CUDA allocation if another compute process owns the GPU.""" + + inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ).stdout.splitlines() + mapping = { + int(line.split(",", 1)[0].strip()): line.split(",", 1)[1].strip() + for line in inventory if line.strip() + } + if physical_gpu_id not in mapping: + raise RuntimeError(f"physical GPU {physical_gpu_id} is not present") + compute = subprocess.run( + [ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid,process_name", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ).stdout.splitlines() + owners = [line for line in compute if line.split(",", 1)[0].strip() == mapping[physical_gpu_id]] + if owners: + raise RuntimeError( + f"physical GPU {physical_gpu_id} is not idle: " + "; ".join(owners) + ) + + +def claim_physical_gpu(physical_gpu_id: int) -> bool: + """Atomically reserve an idle GPU across FoundationHand queue processes.""" + + path = Path(f"/tmp/foundation_hand_{os.getuid()}_gpu{physical_gpu_id}.claim") + owner = os.getpid() + while True: + try: + descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + try: + recorded = int(path.read_text(encoding="ascii").strip()) + except (OSError, ValueError): + recorded = -1 + if recorded == owner: + return True + try: + os.kill(recorded, 0) + except (OSError, ValueError): + try: + path.unlink() + except FileNotFoundError: + pass + continue + return False + else: + with os.fdopen(descriptor, "w", encoding="ascii") as handle: + handle.write(f"{owner}\n") + return True + + +def release_physical_gpu_claim(physical_gpu_id: int) -> None: + """Release a claim owned by this process after a failed stability check.""" + + path = Path(f"/tmp/foundation_hand_{os.getuid()}_gpu{physical_gpu_id}.claim") + try: + if int(path.read_text(encoding="ascii").strip()) == os.getpid(): + path.unlink() + except (FileNotFoundError, OSError, ValueError): + return + + +def contains_h2o(value: str) -> bool: + return any(part.lower() == "h2o" for part in Path(value).parts) + + +def load_cache_rows(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def validate_external_contract(config: dict[str, Any], config_path: Path) -> list[str]: + errors: list[str] = [] + experiment = config.get("experiment", {}) + if int(experiment.get("phase", -1)) not in {7, 8}: + errors.append("external-only experiment.phase must be 7 or 8") + if experiment.get("branch") != "external_only": + errors.append("experiment.branch must be external_only") + if experiment.get("uses_h2o_training_data") is not False: + errors.append("uses_h2o_training_data must be explicitly false") + if config.get("model", {}).get("dinov3_trainable_last_blocks", 0) != 0: + errors.append("Phase 7 external screen requires frozen DINO") + if float(config.get("model", {}).get("modality_dropout_prob", 0.0)) != 0.0: + errors.append("model modality dropout is frame-wise; use source clip dropout instead") + sources = config.get("data", {}).get("sources", []) + if not sources: + errors.append("at least one external source is required") + source_ids: set[str] = set() + for source in sources: + name = str(source.get("dataset", "")) + source_id = str(source.get("source_id", name)) + if source_id in source_ids: + errors.append(f"duplicate external source_id: {source_id}") + source_ids.add(source_id) + manifest = str(source.get("cache_manifest", "")) + if name.upper() not in {"HOT3D", "HOI4D", "ARCTIC"}: + errors.append(f"unsupported external source: {name}") + if contains_h2o(manifest) or name.upper() == "H2O": + errors.append(f"H2O source forbidden in external-only training: {manifest}") + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"source weight must be positive: {name}") + if name.upper() == "HOT3D" and float(source.get("K_input_dropout", -1)) != 0.3: + errors.append("HOT3D K_input_dropout must equal frozen clip-level 0.3") + if contains_h2o(str(config_path)): + errors.append("external-only config path must not be under an H2O directory") + if "initialization_checkpoint" in experiment: + errors.append("external-only configs may not define initialization_checkpoint") + return errors + + +def validate_adaptation_contract(config: dict[str, Any]) -> list[str]: + errors: list[str] = [] + experiment = config.get("experiment", {}) + if int(experiment.get("phase", -1)) not in {7, 8}: + errors.append("adaptation experiment.phase must be 7 or 8") + if experiment.get("branch") != "h2o_adaptation": + errors.append("experiment.branch must be h2o_adaptation") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("H2O adaptation must explicitly use H2O training data") + expected_init = str(experiment.get("initialization_checkpoint_sha256", "")) + if len(expected_init) != 64: + errors.append("adaptation requires a frozen initialization checkpoint SHA256") + if config.get("model", {}).get("dinov3_trainable_last_blocks", 0) != 0: + errors.append("adaptation requires frozen DINO") + if float(config.get("model", {}).get("modality_dropout_prob", 0.0)) != 0.0: + errors.append("use source clip dropout instead of frame-wise model dropout") + sources = config.get("data", {}).get("sources", []) + if not sources or not any(str(source.get("dataset", "")).upper() == "H2O" for source in sources): + errors.append("adaptation requires an H2O official-train source") + allowed = {"H2O", "HOT3D", "HOI4D", "ARCTIC"} + source_ids: set[str] = set() + for source in sources: + name = str(source.get("dataset", "")).upper() + source_id = str(source.get("source_id", name)) + if source_id in source_ids: + errors.append(f"duplicate adaptation source_id: {source_id}") + source_ids.add(source_id) + role = str(source.get("split_role", "")) + if name not in allowed: + errors.append(f"unsupported adaptation source: {name}") + if name == "H2O" and role != "official_train": + errors.append("H2O adaptation source must be official_train") + if name == "H2O" and Path(str(source.get("cache_manifest", ""))).name != "train_fit.jsonl": + errors.append("H2O adaptation training requires frozen train_fit.jsonl") + if name != "H2O" and role != "external_train": + errors.append(f"external replay source must be external_train: {name}") + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"source weight must be positive: {name}") + if name == "HOT3D" and float(source.get("K_input_dropout", -1)) != 0.3: + errors.append("HOT3D replay K_input_dropout must equal 0.3") + if sources and not math.isclose( + sum(float(source.get("weight", 0.0)) for source in sources), 1.0, + rel_tol=0.0, abs_tol=1e-8, + ): + errors.append("adaptation source weights must sum to one") + validation_sources = config.get("data", {}).get("validation_sources", []) + if len(validation_sources) != 1: + errors.append("adaptation requires exactly one H2O train-group-heldout source") + else: + validation = validation_sources[0] + if ( + str(validation.get("dataset", "")).upper() != "H2O" + or validation.get("split_role") != "train_group_heldout" + or Path(str(validation.get("cache_manifest", ""))).name + != "train_group_heldout.jsonl" + ): + errors.append("adaptation validation must be frozen H2O train_group_heldout.jsonl") + staged = config.get("protocol", {}).get("staged_adaptation") + if staged is not None: + prefixes = staged.get("initial_trainable_prefixes", []) + unfreeze_step = int(staged.get("unfreeze_step", -1)) + scale = float(staged.get("unfrozen_learning_rate_scale", -1.0)) + if not isinstance(prefixes, list) or not prefixes or not all( + isinstance(prefix, str) and prefix for prefix in prefixes + ): + errors.append("staged adaptation requires nonempty trainable prefixes") + if not 0 < unfreeze_step < int(config.get("protocol", {}).get("max_steps", 0)): + errors.append("staged adaptation unfreeze_step must be within training horizon") + if not 0.0 < scale <= 1.0: + errors.append("staged adaptation LR scale must be in (0, 1]") + return errors + + +def validate_h2o_neutral_control_contract(config: dict[str, Any]) -> list[str]: + """Validate the random-task-head H2O control without faking an init checkpoint.""" + + experiment = config.get("experiment", {}) + errors: list[str] = [] + if int(experiment.get("phase", -1)) != 8: + errors.append("neutral H2O control must be registered in Phase 8") + if experiment.get("branch") != "h2o_neutral_control": + errors.append("neutral H2O control branch is invalid") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("neutral H2O control must explicitly use H2O training data") + if experiment.get("neutral_task_heads") is not True: + errors.append("neutral H2O control must explicitly declare neutral_task_heads=true") + if any(key.startswith("initialization_checkpoint") for key in experiment): + errors.append("neutral H2O control forbids initialization checkpoint fields") + adaptation_view = copy.deepcopy(config) + adaptation_view["experiment"].update({ + "phase": 7, + "branch": "h2o_adaptation", + "initialization_checkpoint_sha256": "0" * 64, + }) + errors.extend(validate_adaptation_contract(adaptation_view)) + sources = config.get("data", {}).get("sources", []) + if len(sources) != 1 or str(sources[0].get("dataset", "")).upper() != "H2O": + errors.append("neutral H2O control must use only H2O official train") + return errors + + +def validate_phase9_unified_contract( + config: dict[str, Any], config_path: Path, +) -> list[str]: + """Validate the shared four-source Phase 9 direct-XYZ training contract.""" + + errors: list[str] = [] + experiment = config.get("experiment", {}) + specialization = experiment.get("data_only_amendment") == "arctic_h2o_s9_v2_20260917" + data = config.get("data", {}) + model = config.get("model", {}) + loss = config.get("loss", {}) + if int(experiment.get("phase", -1)) != 9: + errors.append("Phase 9 unified training requires experiment.phase=9") + if experiment.get("branch") != "phase9_unified": + errors.append("Phase 9 unified training requires branch=phase9_unified") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("Phase 9 unified training must declare H2O training use") + if experiment.get("h2o_official_validation_used_for_selection") is not False: + errors.append("H2O official validation must be excluded from selection") + if experiment.get("official_test_used") is not False: + errors.append("official test must be explicitly unused") + if len(str(experiment.get("initialization_checkpoint_sha256", ""))) != 64: + errors.append("Phase 9 requires a hash-bound external initialization") + if "phase9" not in {part.lower() for part in config_path.parts}: + errors.append("Phase 9 unified config must live under configs/phase9") + + phase9_stage = str(experiment.get("phase9_stage", "full_data_640")) + last2_stage = phase9_stage in {"last2_5e7", "last2_1e6"} + expected_model = { + "decoder_mode": "alternating", + "use_temporal": True, + "translation_parameterization": "direct_xyz", + "dinov3_trainable_last_blocks": 2 if last2_stage else 0, + "temporal_attention_mode": "bidirectional", + } + for key, expected in expected_model.items(): + if model.get(key) != expected: + errors.append(f"Phase 9 frozen model contract requires {key}={expected}") + if not math.isclose( + float(loss.get("joint3d_root_relative", 0.0)), + 10.0, + rel_tol=0.0, + abs_tol=1e-8, + ): + errors.append( + "Phase 9 frozen loss contract requires joint3d_root_relative=10.0" + ) + resolution = list(data.get("resolution_hw", [])) + if last2_stage: + expected_resolution = list(experiment.get("last2_resolution_hw", [])) + if expected_resolution not in ([368, 640], [512, 896]): + errors.append("Phase 9 last-2 requires a frozen 640 or 896 resolution") + h2o_contract_stage = ( + "resolution_896x512" + if expected_resolution == [512, 896] + else "full_data_640" + ) + else: + expected_resolution = { + "full_data_640": [368, 640], + "resolution_896x512": [512, 896], + "shared_augmentation_640": [368, 640], + "shared_augmentation_896x512": [512, 896], + }.get(phase9_stage) + h2o_contract_stage = phase9_stage + if expected_resolution is None: + errors.append(f"unsupported Phase 9 stage contract: {phase9_stage}") + elif resolution != expected_resolution or int(data.get("T", -1)) != 8: + errors.append( + f"Phase 9 {phase9_stage} contract requires " + f"{expected_resolution[1]}x{expected_resolution[0]} and T=8" + ) + shared_augmentation_stage = phase9_stage in { + "shared_augmentation_640", "shared_augmentation_896x512", + } or (last2_stage and experiment.get("last2_shared_augmentation") is True) + geometry = data.get("geometry_augmentation", {}) + expected_geometry = { + "enabled": True, "probability": 0.8, + "scale_min": 0.9, "scale_max": 1.1, + "translation_fraction": 0.05, + } + if shared_augmentation_stage: + if geometry != expected_geometry: + errors.append("Phase 9 shared geometry augmentation parameters differ") + elif bool(geometry.get("enabled", False)): + errors.append("Phase 9 shared geometry augmentation is not yet admitted") + if last2_stage: + if model.get("encoder") != "dinov3": + errors.append("Phase 9 last-2 requires the shared DINOv3 encoder") + if model.get("dinov3_model", "dinov3_vitb16") != "dinov3_vitb16": + errors.append("Phase 9 last-2 admits DINO Base only") + expected_backbone_lr = 5e-7 if phase9_stage == "last2_5e7" else 1e-6 + actual_backbone_lr = config.get("protocol", {}).get( + "backbone_learning_rate" + ) + if actual_backbone_lr is None or not math.isclose( + float(actual_backbone_lr), expected_backbone_lr, + rel_tol=0.0, abs_tol=1e-15, + ): + errors.append( + f"Phase 9 {phase9_stage} requires backbone learning rate " + f"{expected_backbone_lr}" + ) + elif config.get("protocol", {}).get("backbone_learning_rate") is not None: + errors.append("Phase 9 frozen-DINO stages forbid backbone learning rate") + if int(config.get("seed", -1)) != 20260717: + errors.append("Phase 9 primary seed must be 20260717") + + sources = data.get("sources", []) + names = [str(source.get("dataset", "")).upper() for source in sources] + if specialization: + if len(sources) != 2 or set(names) != {"H2O", "ARCTIC"}: + errors.append("Specialization requires exactly H2O and ARCTIC") + weights = {source["dataset"]: float(source["weight"]) for source in sources} + if not any(all(math.isclose(weights.get(k, -1), v, abs_tol=1e-10) + for k, v in pair.items()) + for pair in ({"H2O": 0.5, "ARCTIC": 0.5}, + {"H2O": 1 / 3, "ARCTIC": 2 / 3})): + errors.append("Unregistered specialization ratio") + if phase9_stage != "last2_1e6": + errors.append("Specialization must retain last2_1e6") + parent_config = Path(experiment["parent_config"]) + if sha256(parent_config) != experiment["parent_config_sha256"]: + errors.append("Parent configuration hash differs") + parent = yaml.safe_load(parent_config.read_text()) + for section in ("model", "loss", "precision"): + if config[section] != parent[section]: + errors.append(f"Specialization changed parent {section}") + expected_protocol = copy.deepcopy(parent["protocol"]) + for milestone in expected_protocol.get("source_exposure_milestones", []): + milestone["minimum_batches"] = { + k: v for k, v in milestone["minimum_batches"].items() + if k in {"H2O", "ARCTIC"} + } + if config["protocol"] != expected_protocol: + errors.append("Data-only experiment must preserve the complete Stage 9 protocol") + if {k: v for k, v in data.items() if k != "sources"} != { + k: v for k, v in parent["data"].items() if k != "sources" + }: + errors.append("Data-only experiment changed augmentation, batch size, or sequence settings") + if experiment["initialization_checkpoint_sha256"] != parent["experiment"]["initialization_checkpoint_sha256"]: + errors.append("Data-only experiment must use the same E40 initialization as Stage 9") + if config["seed"] != parent["seed"]: + errors.append("Data-only experiment changed the Stage 9 seed") + for source in sources: + original = next((s for s in parent["data"]["sources"] + if s["dataset"] == source["dataset"]), None) + if original is None: + errors.append("Unknown source in data-only experiment") + continue + if {k: v for k, v in source.items() if k != "weight"} != { + k: v for k, v in original.items() if k != "weight" + }: + errors.append(f"Specialization changed source contract: {source['dataset']}") + elif len(sources) != 4 or set(names) != set(PHASE9_DATASETS): + errors.append("Phase 9 unified training requires exactly H2O/HOT3D/HOI4D/ARCTIC") + source_ids = [str(source.get("source_id", source.get("dataset", ""))) for source in sources] + if len(set(source_ids)) != len(source_ids): + errors.append("Phase 9 sampling source IDs must be unique") + if sources and not math.isclose( + sum(float(source.get("weight", 0.0)) for source in sources), + 1.0, rel_tol=0.0, abs_tol=1e-8, + ): + errors.append("Phase 9 source weights must sum to one") + for source, name in zip(sources, names): + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"Phase 9 source weight must be positive: {name}") + expected_role = "official_train" if name == "H2O" else "external_train" + if source.get("split_role") != expected_role: + errors.append(f"Phase 9 {name} split role must be {expected_role}") + expected_k_dropout = 0.3 if name == "HOT3D" else 0.0 + if float(source.get("K_input_dropout", -1.0)) != expected_k_dropout: + errors.append(f"Phase 9 {name} K_input_dropout must equal {expected_k_dropout}") + corruption_probability = float( + source.get("depth_corruption_probability", 0.0) + ) + expected_corruption_probability = ( + 0.3 if shared_augmentation_stage and name in {"H2O", "HOI4D"} + else 0.0 + ) + if not math.isclose( + corruption_probability, expected_corruption_probability, + rel_tol=0.0, abs_tol=1e-12, + ): + errors.append( + f"Phase 9 {name} depth corruption probability must equal " + f"{expected_corruption_probability}" + ) + + selection_fold = experiment.get("h2o_selection_fold") + h2o_sources = [source for source, name in zip(sources, names) if name == "H2O"] + validation_sources = data.get("validation_sources", []) + if h2o_sources: + h2o_manifest = Path(str(h2o_sources[0].get("cache_manifest", ""))).resolve() + expected_h2o_manifest = PHASE9_H2O_TRAIN_MANIFESTS.get( + h2o_contract_stage + ) + fold_root = PHASE9_H2O_FOLD_ROOTS.get(h2o_contract_stage) + if selection_fold is None: + if ( + expected_h2o_manifest is None + or h2o_manifest != expected_h2o_manifest.resolve() + ): + errors.append( + "Phase 9 full run must use its stage-matched frozen H2O train cache" + ) + if validation_sources: + errors.append("Phase 9 full run cannot validate on leaked train subsets") + else: + if fold_root is None: + errors.append("Phase 9 fold stage has no admitted manifest root") + fold_root = Path("/__invalid_phase9_fold_root__") + expected_train = (fold_root.resolve() / f"{selection_fold}_train.jsonl") + expected_heldout = ( + fold_root.resolve() / f"{selection_fold}_heldout.jsonl" + ) + if h2o_manifest != expected_train: + errors.append("Phase 9 fold run H2O train manifest does not match its fold") + if len(validation_sources) != 1: + errors.append("Phase 9 fold run requires exactly its H2O heldout source") + elif ( + str(validation_sources[0].get("dataset", "")).upper() != "H2O" + or Path(str(validation_sources[0].get("cache_manifest", ""))).resolve() + != expected_heldout + ): + errors.append("Phase 9 fold validation manifest does not match its fold") + + valid_source_ids = set(source_ids) + milestone_ids: set[str] = set() + for milestone in config.get("protocol", {}).get("source_exposure_milestones", []): + milestone_id = str(milestone.get("id", "")) + minimum = milestone.get("minimum_batches", {}) + if not milestone_id or milestone_id in milestone_ids: + errors.append("Phase 9 exposure milestone IDs must be nonempty and unique") + milestone_ids.add(milestone_id) + if not minimum or not set(minimum).issubset(valid_source_ids): + errors.append(f"invalid source keys in exposure milestone: {milestone_id}") + if any(int(value) <= 0 for value in minimum.values()): + errors.append(f"exposure milestone counts must be positive: {milestone_id}") + return errors + + +def reached_source_exposure_milestones( + milestones: list[dict[str, Any]], + counts: Counter[str], + completed: set[str], +) -> list[str]: + reached = [] + for milestone in milestones: + milestone_id = str(milestone["id"]) + if milestone_id in completed: + continue + minimum = milestone["minimum_batches"] + if all(counts[source_id] >= int(target) for source_id, target in minimum.items()): + reached.append(milestone_id) + return reached + + +def checkpoint_context_with_exposure( + context: dict[str, Any], + source_batches: Counter[str], + source_frames: Counter[str], + depth_conditions: Counter[str], + completed_milestones: set[str], +) -> dict[str, Any]: + return { + **context, + "source_exposure_batches": dict(source_batches), + "source_exposure_frames": dict(source_frames), + "depth_input_condition_frames": dict(depth_conditions), + "completed_source_exposure_milestones": sorted(completed_milestones), + } + + +def validate_cache_manifest( + path: Path, expected_dataset: str, allow_h2o: bool = False, +) -> tuple[list[dict], list[str]]: + errors: list[str] = [] + if not path.is_file(): + return [], [f"cache manifest missing: {path}"] + rows = load_cache_rows(path) + if not rows: + errors.append(f"cache manifest is empty: {path}") + for index, row in enumerate(rows): + dataset = str(row.get("dataset_id", "")) + cache_path = Path(str(row.get("cache_path", ""))) + if dataset.upper() != expected_dataset.upper(): + errors.append(f"row {index} dataset mismatch: {dataset} != {expected_dataset}") + if not allow_h2o and ( + dataset.upper() == "H2O" or contains_h2o(str(cache_path)) + ): + errors.append(f"row {index} contains forbidden H2O data") + if not cache_path.is_file(): + errors.append(f"row {index} cache missing: {cache_path}") + if not row.get("cache_sha256"): + errors.append(f"row {index} lacks cache_sha256") + if len(errors) >= 20: + errors.append("additional cache errors omitted") + break + return rows, errors + + +def write_provenance( + output: Path, + config_path: Path, + config: dict[str, Any], + source_hashes: dict[str, str], + resume: Path | None, + initialization_checkpoint: Path | None = None, +) -> dict[str, Any]: + inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid,name,memory.total,memory.used", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, + ).stdout.strip().splitlines() + record = { + "timestamp_utc": utc_now(), + "hostname": socket.gethostname(), + "git_commit": git_output("rev-parse", "HEAD"), + "git_status": git_output("status", "--short"), + "command_argv": [sys.executable, *sys.argv], + "command_shell": shlex.join([sys.executable, *sys.argv]), + "working_directory": str(Path.cwd()), + "config_path": str(config_path.resolve()), + "config_sha256": sha256(config_path), + "config": config, + "source_manifest_sha256": source_hashes, + "resume_checkpoint": str(resume.resolve()) if resume else None, + "cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "gpu_inventory": inventory, + "python": sys.version, + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "external_only_neutral_heads": ( + config.get("experiment", {}).get("branch") == "external_only" + ), + "neutral_task_heads": ( + config.get("experiment", {}).get("branch") + in {"external_only", "h2o_neutral_control"} + ), + "initialization_checkpoint": ( + { + "path": str(initialization_checkpoint.resolve()), + "sha256": sha256(initialization_checkpoint), + } + if initialization_checkpoint is not None else None + ), + "h2o_initialization_used": False, + "h2o_training_data_used": bool( + config.get("experiment", {}).get("uses_h2o_training_data", False) + ), + "official_test_used": False, + } + name = "run_provenance.json" if resume is None else f"resume_provenance_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json" + (output / name).write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + return record + + +def source_batch_counts(batch: dict[str, Any]) -> dict[str, int]: + values = batch.get("sampling_source_id", batch.get("dataset_id", [])) + if isinstance(values, str): + values = [values] + return dict(Counter(str(value) for value in values)) + + +def source_frame_counts(batch: dict[str, Any]) -> dict[str, int]: + datasets = batch.get("sampling_source_id", batch.get("dataset_id", [])) + if isinstance(datasets, str): + datasets = [datasets] + valid = batch["frame_valid"].detach().cpu() + counts: Counter[str] = Counter() + for index, dataset in enumerate(datasets): + counts[str(dataset)] += int(valid[index].sum()) + return dict(counts) + + +def depth_input_condition_counts(batch: dict[str, Any]) -> dict[str, int]: + codes = batch.get("depth_input_condition_code") + if codes is None: + return {} + names = {0: "source_unavailable", 1: "rgb_k", 2: "clean_rgb_d_k"} + names.update({3 + index: f"corrupted_{name}" for index, name in enumerate(DEPTH_CORRUPTIONS)}) + values = codes.detach().cpu().reshape(-1).tolist() + return dict(Counter(names.get(int(value), f"unknown_{int(value)}") for value in values)) + + +def gpu_telemetry(physical_gpu_id: int) -> dict[str, float] | None: + result = subprocess.run( + [ + "nvidia-smi", f"--id={physical_gpu_id}", + "--query-gpu=utilization.gpu,memory.used", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + if result.returncode != 0 or not result.stdout.strip(): + return None + utilization, memory = result.stdout.strip().split(",")[:2] + return { + "gpu_utilization_percent": float(utilization.strip()), + "gpu_memory_used_mib": float(memory.strip()), + } + + +def run_validation( + model: BimanualReconstructionModel, + criterion: BimanualLoss, + loaders: dict[str, DataLoader], + device: torch.device, + dtype: torch.dtype, + max_batches: int, +) -> dict[str, Any]: + was_training = model.training + model.eval() + sources: dict[str, Any] = {} + with torch.inference_mode(): + for name, loader in loaders.items(): + metric_rows: list[dict[str, float]] = [] + loss_rows: list[dict[str, float]] = [] + for batch_index, batch in enumerate(loader): + if batch_index >= max_batches: + break + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + metric_rows.append(camera_metrics(prediction, batch)) + loss_rows.append({key: float(value) for key, value in losses.items()}) + sources[name] = { + "batches": len(metric_rows), + "metrics": { + key: float(np.mean([row[key] for row in metric_rows if math.isfinite(row.get(key, math.nan))])) + for key in sorted({key for row in metric_rows for key in row}) + if any(math.isfinite(row.get(key, math.nan)) for row in metric_rows) + }, + "losses": { + key: float(np.mean([row[key] for row in loss_rows if math.isfinite(row.get(key, math.nan))])) + for key in sorted({key for row in loss_rows for key in row}) + if any(math.isfinite(row.get(key, math.nan)) for row in loss_rows) + }, + } + model.train(was_training) + absolute = [ + record["metrics"]["absolute_camera_mpjpe_mm"] + for record in sources.values() + if "absolute_camera_mpjpe_mm" in record["metrics"] + ] + return { + "sources": sources, + "macro_absolute_camera_mpjpe_mm": float(np.mean(absolute)) if absolute else None, + } + + +def build_datasets( + config: dict[str, Any], seed: int, allow_h2o: bool = False, +) -> tuple[UnifiedConcatDataset, list[int], list[float], dict[str, str]]: + data = config["data"] + expected_resolution_hw = tuple(int(value) for value in data["resolution_hw"]) + datasets = [] + sizes: list[int] = [] + weights: list[float] = [] + hashes: dict[str, str] = {} + for source in data["sources"]: + manifest = Path(source["cache_manifest"]).resolve() + _, errors = validate_cache_manifest( + manifest, str(source["dataset"]), allow_h2o=allow_h2o, + ) + if errors: + raise ValueError("; ".join(errors)) + source_id = str(source.get("source_id", source["dataset"])) + if source_id in hashes: + raise ValueError(f"duplicate training source_id: {source_id}") + dataset = CachedUnifiedClipDataset( + manifest, + K_input_dropout=float(source.get("K_input_dropout", 0.0)), + dropout_seed=seed, + photometric_augmentation=data.get("photometric_augmentation"), + depth_input_dropout=float(source.get("depth_input_dropout", 0.0)), + depth_corruption_probability=float( + source.get("depth_corruption_probability", 0.0) + ), + joint3d_root_relative_scope=str( + source.get("joint3d_root_relative_scope", "auto") + ), + source_id=source_id, + expected_resolution_hw=expected_resolution_hw, + geometry_augmentation=data.get("geometry_augmentation"), + ) + datasets.append(dataset) + sizes.append(len(dataset)) + weights.append(float(source["weight"])) + hashes[source_id] = sha256(manifest) + return UnifiedConcatDataset(datasets), sizes, weights, hashes + + +def build_validation_loaders( + config: dict[str, Any], seed: int, batch_size: int, workers: int, + allow_h2o: bool = False, +) -> dict[str, DataLoader]: + loaders: dict[str, DataLoader] = {} + expected_resolution_hw = tuple( + int(value) for value in config["data"]["resolution_hw"] + ) + for source in config.get("data", {}).get("validation_sources", []): + name = str(source.get("source_id", source["dataset"])) + manifest = Path(source["cache_manifest"]).resolve() + _, errors = validate_cache_manifest( + manifest, str(source["dataset"]), allow_h2o=allow_h2o, + ) + if errors: + raise ValueError("; ".join(errors)) + dataset = CachedUnifiedClipDataset( + manifest, + K_input_dropout=float(source.get("K_input_dropout", 0.0)), + dropout_seed=seed, + joint3d_root_relative_scope=str( + source.get("joint3d_root_relative_scope", "auto") + ), + source_id=str(source.get("source_id", source["dataset"])), + expected_resolution_hw=expected_resolution_hw, + ) + loaders[name] = DataLoader( + dataset, batch_size=batch_size, shuffle=False, num_workers=workers, + persistent_workers=workers > 0, collate_fn=collate_h2o_clips, + pin_memory=True, + ) + return loaders + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument( + "--allow-physical-gpus-4-5", action="store_true", + help="Explicit resource override; default preserves the historical GPU0-3 contract.", + ) + parser.add_argument("--stop-after-step", type=int) + parser.add_argument( + "--allow-schedule-tail", action="store_true", + help="Allow external-only exact resume beyond max_steps at the clamped minimum LR.", + ) + args = parser.parse_args() + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + branch = str(config.get("experiment", {}).get("branch", "")) + if branch == "external_only": + errors = validate_external_contract(config, args.config) + if args.init_checkpoint is not None: + errors.append("external-only training forbids checkpoint initialization") + elif branch == "h2o_adaptation": + errors = validate_adaptation_contract(config) + if args.resume is None and args.init_checkpoint is None: + errors.append("new H2O adaptation requires --init-checkpoint") + if args.resume is not None and args.init_checkpoint is not None: + errors.append("--resume and --init-checkpoint are mutually exclusive") + elif branch == "h2o_neutral_control": + errors = validate_h2o_neutral_control_contract(config) + if args.init_checkpoint is not None: + errors.append("neutral H2O control forbids --init-checkpoint") + elif branch == "phase9_unified": + errors = validate_phase9_unified_contract(config, args.config) + if args.resume is None and args.init_checkpoint is None: + errors.append("new Phase 9 unified training requires --init-checkpoint") + if args.resume is not None and args.init_checkpoint is not None: + errors.append("--resume and --init-checkpoint are mutually exclusive") + else: + errors = [f"unsupported Phase 7 training branch: {branch}"] + if errors: + parser.error("; ".join(errors)) + if args.init_checkpoint is not None: + if not args.init_checkpoint.is_file(): + parser.error(f"initialization checkpoint missing: {args.init_checkpoint}") + expected = config["experiment"]["initialization_checkpoint_sha256"] + actual = sha256(args.init_checkpoint) + if actual != expected: + parser.error(f"initialization checkpoint SHA256 mismatch: {actual} != {expected}") + if args.output_dir.exists() and any(args.output_dir.iterdir()) and args.resume is None: + parser.error("--output-dir must be new or empty unless --resume is supplied") + visible = os.environ.get("CUDA_VISIBLE_DEVICES") + if visible != str(args.physical_gpu_id): + parser.error( + "CUDA_VISIBLE_DEVICES must name exactly --physical-gpu-id for auditable launch" + ) + allowed_physical_gpus = {0, 1, 2, 3} + if args.allow_physical_gpus_4_5: + allowed_physical_gpus.update((4, 5)) + if args.physical_gpu_id not in allowed_physical_gpus: + parser.error("Phase 7 may use only physical GPUs 0-3; GPU4-5 are reserved") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + protocol = config["protocol"] + max_steps = int(protocol["max_steps"]) + run_end_step = max_steps if args.stop_after_step is None else int(args.stop_after_step) + checkpoint_interval = int(protocol["checkpoint_interval"]) + validation_interval = int(protocol["validation_interval"]) + validation_batches = int(protocol["validation_batches"]) + telemetry_interval = int(protocol.get("telemetry_interval", 100)) + workers = int(protocol["num_workers"]) + batch_size = int(config["data"]["batch_size"]) + seed = int(config["seed"]) + if min(max_steps, checkpoint_interval, validation_interval, validation_batches, telemetry_interval) <= 0: + parser.error("step, checkpoint, and validation values must be positive") + if run_end_step <= 0: + parser.error("--stop-after-step must be positive") + if run_end_step > max_steps and not args.allow_schedule_tail: + parser.error("--stop-after-step exceeds protocol.max_steps without --allow-schedule-tail") + if args.allow_schedule_tail and branch != "external_only": + parser.error("--allow-schedule-tail is restricted to external-only training") + + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + allow_h2o = branch in { + "h2o_adaptation", "h2o_neutral_control", "phase9_unified", + } + train_dataset, source_sizes, source_weights, source_hashes = build_datasets( + config, seed, allow_h2o=allow_h2o, + ) + validation_loaders = build_validation_loaders( + config, seed, batch_size, workers, allow_h2o=allow_h2o, + ) + assets = config["assets"] + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + device = torch.device("cuda") + assert_physical_gpu_idle(args.physical_gpu_id) + provenance = write_provenance( + args.output_dir, args.config, config, source_hashes, args.resume, + args.init_checkpoint, + ) + model = BimanualReconstructionModel(model_config).to(device) + initialization_state = None + if args.init_checkpoint is not None: + specialization = config["experiment"].get("data_only_amendment") == "arctic_h2o_s9_v2_20260917" + if specialization: + payload = torch.load(args.init_checkpoint, map_location="cpu", weights_only=False) + if tuple(payload.get("excluded_model_prefixes", ())) != ("rgb_encoder.backbone.",): + raise RuntimeError("E40 exclusion contract differs from historical Stage 9") + missing = set(model.state_dict()) - set(payload["model"]) + if set(payload["model"]) - set(model.state_dict()): + raise RuntimeError("Unexpected E40 tensors") + if missing != {k for k in model.state_dict() if k.startswith("rgb_encoder.backbone.")}: + raise RuntimeError("E40 must supply every non-backbone tensor") + pretrained_backbone = {k: v.detach().cpu().clone() for k, v in model.state_dict().items() if k in missing} + initialization_state = load_checkpoint( + args.init_checkpoint, model, optimizer=None, map_location=device, + ) + if specialization: + if initialization_state["step"] != 200000: + raise RuntimeError("Data-only experiment must initialize from exact E40 200K") + if initialization_state["extra"].get("h2o_training_data_used") is not False: + raise RuntimeError("E40 initialization must retain no-H2O provenance") + if initialization_state["extra"].get("official_test_used") is not False: + raise RuntimeError("Parent official-test isolation is missing") + current = model.state_dict() + assert all(torch.equal(current[k].detach().cpu(), v) for k, v in payload["model"].items()) + assert all(torch.equal(current[k].detach().cpu(), v) for k, v in pretrained_backbone.items()) + composition = { + "initialization_checkpoint": str(args.init_checkpoint.resolve()), + "initialization_checkpoint_sha256": sha256(args.init_checkpoint), + "source_step": 200000, "new_stage_start_step": 0, + "loaded_non_backbone_tensors": len(payload["model"]), + "pretrained_backbone_tensors_preserved": len(pretrained_backbone), + "all_non_backbone_tensors_equal_E40": True, + "depth_and_K_reinitialized": False, + "matches_historical_stage9_initialization": True, + } + (args.output_dir / "initialization_composition.json").write_text(json.dumps(composition, indent=2) + "\n") + del payload, pretrained_backbone, current + elif initialization_state.get("extra", {}).get("h2o_training_data_used") is not False: + raise RuntimeError("adaptation initialization lacks strict no-H2O provenance") + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + learning_rate = float(protocol["learning_rate"]) + minimum_lr = float(protocol["min_learning_rate"]) + warmup_steps = int(protocol["warmup_steps"]) + staged_adaptation = protocol.get("staged_adaptation") + staged_prefixes: tuple[str, ...] = () + if staged_adaptation is not None: + staged_prefixes = tuple(staged_adaptation["initial_trainable_prefixes"]) + parameter_groups = staged_optimizer_parameter_groups( + model, + learning_rate=learning_rate, + initial_trainable_prefixes=staged_prefixes, + unfrozen_learning_rate_scale=float( + staged_adaptation["unfrozen_learning_rate_scale"] + ), + ) + else: + backbone_learning_rate = protocol.get("backbone_learning_rate") + parameter_groups = optimizer_parameter_groups( + model, + learning_rate=learning_rate, + backbone_learning_rate=( + float(backbone_learning_rate) + if backbone_learning_rate is not None else None + ), + ) + optimizer = torch.optim.AdamW( + parameter_groups, + lr=learning_rate, weight_decay=float(protocol.get("weight_decay", 0.05)), + ) + start_step = 0 + resume_extra: dict[str, Any] | None = None + if args.resume is not None: + if not args.resume.is_file(): + parser.error(f"resume checkpoint missing: {args.resume}") + state = load_checkpoint(args.resume, model, optimizer, device) + start_step = int(state["step"]) + resume_extra = state.get("extra", {}) + if resume_extra.get("config_sha256") != provenance["config_sha256"]: + raise RuntimeError("resume config hash differs from checkpoint") + if resume_extra.get("source_manifest_sha256") != source_hashes: + raise RuntimeError("resume source manifests differ from checkpoint") + set_scheduled_learning_rate(optimizer, learning_rate) + if start_step >= max_steps and not args.allow_schedule_tail: + parser.error(f"checkpoint step {start_step} is not below max_steps {max_steps}") + if start_step >= run_end_step: + parser.error( + f"checkpoint step {start_step} is not below this invocation's end step {run_end_step}" + ) + + batch_sampler = ResumableMixtureBatchSampler( + source_sizes, source_weights, batch_size, seed, start_step, run_end_step, + include_epoch=bool(config["data"].get("photometric_augmentation")), + ) + loader = DataLoader( + train_dataset, batch_sampler=batch_sampler, + generator=torch.Generator().manual_seed(seed + 10_000_000), + num_workers=workers, persistent_workers=workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + context = { + "phase": int(config.get("experiment", {}).get("phase", 7)), + "branch": branch, + "config": config, + "config_sha256": provenance["config_sha256"], + "source_manifest_sha256": source_hashes, + "h2o_training_data_used": allow_h2o, + "h2o_checkpoint_initialization_used": False, + "external_initialization_checkpoint": ( + { + "path": str(args.init_checkpoint.resolve()), + "sha256": sha256(args.init_checkpoint), + "source_step": int(initialization_state["step"]), + } + if args.init_checkpoint is not None + else ( + resume_extra.get("external_initialization_checkpoint") + if resume_extra is not None else None + ) + ), + "official_test_used": False, + "checkpoint_role": "periodic", + "schedule_tail": { + "enabled": bool(args.allow_schedule_tail), + "registered_max_steps": max_steps, + "run_end_step": run_end_step, + "learning_rate_after_horizon": minimum_lr, + }, + } + excluded = () if config["experiment"].get("data_only_amendment") else checkpoint_excluded_prefixes(model) + log_path = args.output_dir / "train_metrics.jsonl" + val_path = args.output_dir / "validation.jsonl" + started = time.perf_counter() + processed_frames = 0 + completed_step = start_step + iterator = iter(loader) + telemetry_samples: list[dict[str, float]] = [] + cumulative_source_batches: Counter[str] = Counter( + (resume_extra or {}).get("source_exposure_batches", {}) + ) + cumulative_source_frames: Counter[str] = Counter( + (resume_extra or {}).get("source_exposure_frames", {}) + ) + cumulative_depth_conditions: Counter[str] = Counter( + (resume_extra or {}).get("depth_input_condition_frames", {}) + ) + exposure_milestones = list(protocol.get("source_exposure_milestones", [])) + completed_exposure_milestones = set( + (resume_extra or {}).get("completed_source_exposure_milestones", []) + ) + torch.cuda.reset_peak_memory_stats(device) + for step in range(start_step, run_end_step): + fetch_started = time.perf_counter() + batch = next(iterator) + data_seconds = time.perf_counter() - fetch_started + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + step_source_batches = source_batch_counts(batch) + step_source_frames = source_frame_counts(batch) + step_depth_conditions = depth_input_condition_counts(batch) + cumulative_source_batches.update(step_source_batches) + cumulative_source_frames.update(step_source_frames) + cumulative_depth_conditions.update(step_depth_conditions) + processed_frames += int(batch["frame_valid"].sum()) + scheduled_lr = warmup_cosine_learning_rate( + step, max_steps, learning_rate, minimum_lr, warmup_steps, + ) + staged_later_active = bool( + staged_adaptation is not None + and step >= int(staged_adaptation["unfreeze_step"]) + ) + if staged_adaptation is not None: + set_staged_parameter_group_phase( + optimizer, active=staged_later_active, + ) + set_scheduled_learning_rate(optimizer, scheduled_lr) + optimizer.zero_grad(set_to_none=True) + forward_start = torch.cuda.Event(enable_timing=True) + forward_end = torch.cuda.Event(enable_timing=True) + backward_end = torch.cuda.Event(enable_timing=True) + forward_start.record() + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + forward_end.record() + if not torch.isfinite(losses["total"]): + raise FloatingPointError(f"non-finite loss at step {step + 1}") + losses["total"].backward() + if staged_adaptation is not None and not staged_later_active: + clear_staged_later_gradients(model, staged_prefixes) + group_norms = { + group["group_name"]: float(torch.linalg.vector_norm(torch.stack([ + p.grad.detach().float().norm() for p in group["params"] if p.grad is not None + ]))) for group in optimizer.param_groups + } + gradient_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) + if not torch.isfinite(gradient_norm): + raise FloatingPointError(f"non-finite gradient at step {step + 1}") + optimizer.step() + backward_end.record() + torch.cuda.synchronize(device) + completed_step = step + 1 + elapsed = time.perf_counter() - started + record = { + "timestamp_utc": utc_now(), + "step": completed_step, + "seed": seed, + "source_counts": step_source_batches, + "source_frame_counts": step_source_frames, + "depth_input_condition_counts": step_depth_conditions, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "metrics": camera_metrics(prediction, batch), + "gradient_norm": float(gradient_norm), + "gradient_group_norms_preclip": group_norms, + "clip_scale": min(1.0, 10.0 / (float(gradient_norm) + 1e-6)), + "optimizer_group_lrs": {g["group_name"]: g["lr"] for g in optimizer.param_groups}, + "learning_rate": scheduled_lr, + "staged_adaptation": ( + { + "later_group_active": staged_later_active, + "unfreeze_step": int(staged_adaptation["unfreeze_step"]), + "unfrozen_learning_rate_scale": float( + staged_adaptation["unfrozen_learning_rate_scale"] + ), + } + if staged_adaptation is not None else None + ), + "timing": { + "data_loading_seconds": data_seconds, + "forward_seconds": forward_start.elapsed_time(forward_end) / 1000.0, + "backward_optimizer_seconds": forward_end.elapsed_time(backward_end) / 1000.0, + "steps_per_second": (completed_step - start_step) / elapsed, + "frames_per_second": processed_frames / elapsed, + }, + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + } + if completed_step == start_step + 1 or completed_step % telemetry_interval == 0: + telemetry = gpu_telemetry(args.physical_gpu_id) + if telemetry is not None: + telemetry_samples.append(telemetry) + record["gpu_telemetry"] = telemetry + with log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + if completed_step % checkpoint_interval == 0: + save_checkpoint( + args.output_dir / f"step_{completed_step:07d}.pt", + model, optimizer, completed_step, + checkpoint_context_with_exposure( + context, cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + newly_reached = reached_source_exposure_milestones( + exposure_milestones, cumulative_source_batches, + completed_exposure_milestones, + ) + for milestone_id in newly_reached: + completed_exposure_milestones.add(milestone_id) + save_checkpoint( + args.output_dir + / f"milestone_{milestone_id}_step_{completed_step:07d}.pt", + model, optimizer, completed_step, + checkpoint_context_with_exposure( + context, cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + if validation_loaders and completed_step % validation_interval == 0: + result = run_validation( + model, criterion, validation_loaders, device, dtype, validation_batches, + ) + with val_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"timestamp_utc": utc_now(), "step": completed_step, **result}) + "\n") + + final_path = args.output_dir / f"step_{completed_step:07d}_final.pt" + save_checkpoint( + final_path, model, optimizer, completed_step, + checkpoint_context_with_exposure( + {**context, "checkpoint_role": "final"}, + cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + elapsed = time.perf_counter() - started + schedule_tail_argument = " --allow-schedule-tail" if args.allow_schedule_tail else "" + resource_override_argument = ( + " --allow-physical-gpus-4-5" if args.allow_physical_gpus_4_5 else "" + ) + resume_command = ( + f"CUDA_VISIBLE_DEVICES= {shlex.quote(sys.executable)} " + f"-m scripts.train_phase7_external --config {shlex.quote(str(args.config.resolve()))} " + f"--output-dir {shlex.quote(str(args.output_dir.resolve()))} " + f"--resume {shlex.quote(str(final_path.resolve()))} " + f"--physical-gpu-id {args.physical_gpu_id}{schedule_tail_argument}" + f"{resource_override_argument}" + ) + (args.output_dir / "resume_command.txt").write_text(resume_command + "\n", encoding="utf-8") + summary = { + "status": ( + "completed_schedule_tail" + if args.allow_schedule_tail and completed_step == run_end_step and completed_step > max_steps + else ("completed" if completed_step == max_steps else "paused_requested") + ), + "start_timestamp_utc": datetime.fromtimestamp( + time.time() - elapsed, timezone.utc, + ).isoformat(), + "end_timestamp_utc": utc_now(), + "start_step": start_step, + "completed_step": completed_step, + "protocol_max_steps": max_steps, + "registered_run_end_step": run_end_step, + "schedule_tail_enabled": bool(args.allow_schedule_tail), + "schedule_tail_learning_rate": minimum_lr if args.allow_schedule_tail else None, + "wall_seconds": elapsed, + "gpu_ids_visible": os.environ.get("CUDA_VISIBLE_DEVICES"), + "physical_gpu_id": args.physical_gpu_id, + "gpu_hours": elapsed / 3600.0, + "train_samples_per_second": ( + (completed_step - start_step) * batch_size / max(elapsed, 1e-9) + ), + "optimizer_steps_per_second": (completed_step - start_step) / max(elapsed, 1e-9), + "frames_per_second": processed_frames / max(elapsed, 1e-9), + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "gpu_utilization_percent_mean": ( + float(np.mean([value["gpu_utilization_percent"] for value in telemetry_samples])) + if telemetry_samples else None + ), + "gpu_telemetry_samples": len(telemetry_samples), + "final_checkpoint": str(final_path.resolve()), + "final_checkpoint_sha256": sha256(final_path), + "resume_command": resume_command, + "source_manifest_sha256": source_hashes, + "official_test_used": False, + "h2o_training_data_used": allow_h2o, + "model_config": asdict(model_config), + "source_exposure_batches": dict(cumulative_source_batches), + "source_exposure_frames": dict(cumulative_source_frames), + "depth_input_condition_frames": dict(cumulative_depth_conditions), + "completed_source_exposure_milestones": sorted( + completed_exposure_milestones + ), + "staged_adaptation": staged_adaptation, + } + (args.output_dir / "summary.json").write_text( + json.dumps(summary, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/smoke_adapters.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/smoke_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..187e1e4a8016617c0eb87fb67f5d443d23898476 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/smoke_adapters.py @@ -0,0 +1,57 @@ +"""Decode one frozen filtered tile from each source without starting training.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import torch + +from filtered_dataset import FilteredClipDataset + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", type=Path, required=True) + parser.add_argument("--time", type=int, choices=(1, 8), required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--tile-id", help="Inspect a specific frozen tile") + args = parser.parse_args() + source = args.source + with torch.no_grad(): + dataset = FilteredClipDataset( + source, args.manifests / f"{source.lower()}_t{args.time}.jsonl", + args.time, (368, 640), + "/SSD3/jiasen/foundation_hand/pretrained/mano", + Path(__file__).parent / "third_party", + photometric_augmentation={"enabled": False}, + ) + mode = "rgb_depth_k" if source == "H2O" else "rgb_k" + spec = {"source": source, "tile_id": args.tile_id or dataset.rows[0]["filtered_tile_id"], + "epoch": 0, "source_ordinal": 0, "position": 0, "mode": mode} + sample = dataset[spec] + out = { + "source": source, "tile_id": spec["tile_id"], "frames": sample["frame_id"].tolist(), + "rgb_shape": list(sample["rgb"].shape), + "K_shape": list(sample["K"].shape), + "K_input": sample["K_input_available"].tolist(), + "K_supervision": sample["K_supervision_valid"].tolist(), + "depth_input": sample["depth_input_available"].tolist(), + "valid": {key: int(sample[key].sum()) for key in ( + "joint2d_valid", "joint3d_valid", "translation_valid", + "mano_pose_valid", "shape_valid", "vertices_valid", "reprojection_valid", + )}, + "finite_K": bool(torch.isfinite(sample["K"]).all()), + "valid_depth_pixels": int(sample["depth_pixel_valid"].sum()), + } + if "joint3d_root_relative_valid" in sample: + out["valid"]["joint3d_root_relative_valid"] = int(sample["joint3d_root_relative_valid"].sum()) + print(json.dumps(out, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/test_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..68b938b2aa050e510e544ed06105a08bb428ef15 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/test_contract.py @@ -0,0 +1,61 @@ +from collections import Counter +from pathlib import Path +import sqlite3 +import tempfile +import unittest + +from coverage_sampler import CoverageSampler, SOURCES +from preflight_index import tile_starts + + +class IndexTests(unittest.TestCase): + def test_tail_covers_every_frame_without_duplicates_at_start(self): + for length in range(8, 100): + starts = tile_starts(length) + self.assertEqual(starts[0], 0) + self.assertEqual(len(starts), (length + 7) // 8) + self.assertEqual(set().union(*(set(range(s, s + 8)) for s in starts)), set(range(length))) + + +class SamplerTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.index = Path(self.temp.name) / "index.sqlite" + with sqlite3.connect(self.index) as connection: + connection.execute("CREATE TABLE tiles(source TEXT, recording_id TEXT, tile_id TEXT)") + for source in SOURCES: + for recording in range(2): + for tile in range(5): + connection.execute( + "INSERT INTO tiles VALUES (?,?,?)", + (source, f"{source}-{recording}", f"{source}-{recording}-{tile}"), + ) + + def test_quota_resume_ddp_and_no_replacement(self): + sampler = CoverageSampler(self.index, "S1_S3") + first = [sampler.sample(pos) for pos in range(200)] + self.assertEqual(Counter(row["source"] for row in first), + Counter({"H2O": 80, "ARCTIC": 70, "HOT3D": 50})) + for source in SOURCES: + source_rows = [row for row in first if row["source"] == source] + self.assertEqual(len({row["tile_id"] for row in source_rows[:10]}), 10) + resumed = CoverageSampler(self.index, "S1_S3") + self.assertEqual(first[43:], [resumed.sample(pos) for pos in range(43, 200)]) + shards = [CoverageSampler(self.index, "S1_S3") for _ in range(6)] + merged = sorted((row for rank, item in enumerate(shards) + for row in item.shard(0, 200, rank, 6)), + key=lambda row: row["position"]) + self.assertEqual(first, merged) + + def test_s4_has_separate_ledger_and_modes(self): + sampler = CoverageSampler(self.index, "S4") + first = [sampler.sample(pos) for pos in range(200)] + self.assertEqual(Counter(row["source"] for row in first), + Counter({"H2O": 70, "ARCTIC": 50, "HOT3D": 80})) + self.assertTrue(all(row["mode"] != "rgb_depth_k" for row in first + if row["source"] != "H2O")) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/test_hot3d_rotation.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/test_hot3d_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..70352220213018fe79a2540793fd9bfd46df2014 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/test_hot3d_rotation.py @@ -0,0 +1,24 @@ +import unittest + +import numpy as np +from scipy.spatial.transform import Rotation +import torch + +from third_party.hot3d.data_loaders.rotation_compat import matrix_to_axis_angle + + +class Hot3dRotationTests(unittest.TestCase): + def test_roundtrip_including_singular_angles(self): + values = np.array([ + [0.0, 0.0, 0.0], [1e-8, 0.0, 0.0], [0.4, -1.2, 2.1], + [np.pi - 1e-8, 0.0, 0.0], [0.0, np.pi, 0.0], + ]) + for value in values: + matrix = Rotation.from_rotvec(value).as_matrix() + recovered = matrix_to_axis_angle(torch.tensor(matrix, dtype=torch.float64)).numpy() + error = (Rotation.from_rotvec(recovered).inv() * Rotation.from_matrix(matrix)).magnitude() + self.assertLess(error, 1e-8) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/test_rotation_pi.py b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/test_rotation_pi.py new file mode 100644 index 0000000000000000000000000000000000000000..32247982bb73ce1509133204f3474feff7bd9b88 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/a7_rotation_fix/test_rotation_pi.py @@ -0,0 +1,38 @@ +"""Regression checks for near-pi matrix-to-axis-angle conversion.""" + +import math + +import torch + +from foundation_hand.geometry.rotations import axis_angle_to_matrix, matrix_to_axis_angle + + +def test_matrix_axis_angle_roundtrip_random_and_near_pi(): + torch.manual_seed(20260930) + for dtype, tolerance in ((torch.float64, 1e-10), (torch.float32, 3e-6)): + axes = torch.nn.functional.normalize(torch.randn(10000, 3, dtype=dtype), dim=-1) + angles = torch.rand(10000, 1, dtype=dtype) * math.pi + angles[:100] = math.pi - 1e-6 + angles[100:200] = math.pi - 1e-4 + angles[200:300] = 0 + matrices = axis_angle_to_matrix(axes * angles) + restored = axis_angle_to_matrix(matrix_to_axis_angle(matrices)) + assert torch.isfinite(restored).all() + assert float((restored - matrices).abs().max()) < tolerance + + +def test_matrix_axis_angle_gradients_identity_and_near_pi(): + axes = torch.nn.functional.normalize(torch.tensor([[0.3, -0.7, 0.2]], dtype=torch.float64), dim=-1) + values = torch.cat((torch.zeros(1, 3, dtype=torch.float64), axes * (math.pi - 1e-5)), dim=0) + matrices = axis_angle_to_matrix(values).detach().requires_grad_() + vector = matrix_to_axis_angle(matrices) + vector.square().sum().backward() + assert torch.isfinite(vector).all() + assert torch.isfinite(matrices.grad).all() + + +def test_near_pi_arbitrary_axis(): + axis = torch.nn.functional.normalize(torch.tensor([0.37, 0.48, -0.79], dtype=torch.float64), dim=-1) + matrix = axis_angle_to_matrix(axis * (math.pi - 1e-5)) + recovered = matrix_to_axis_angle(matrix) + assert float((axis_angle_to_matrix(recovered) - matrix).abs().max()) < 1e-10 diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_formal_stage.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_formal_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..68ad0c1c90c60fc8329518db2ec8956b0a6c137e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_formal_stage.py @@ -0,0 +1,133 @@ +"""Audit a completed formal stage endpoint without modifying training state.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +import math +from pathlib import Path +import statistics + +import torch + +from clean_train import INDEX, STAGES, sha, training_code_hashes + + +EXTREME_LOSS_THRESHOLD = 100.0 + + +def run(checkpoint: Path, metrics: Path, stage: str, update: int) -> dict: + state = torch.load(checkpoint, map_location="cpu", weights_only=False) + rows = [json.loads(line) for line in metrics.open()] + errors = [] + if not rows or len(rows) != update or [row["update"] for row in rows] != list(range(1, update + 1)): + errors.append("metrics do not contain every update through the requested endpoint") + if state["stage"] != stage or state["update"] != update: + errors.append("checkpoint stage or update differs from requested endpoint") + if state.get("smoke") or not state.get("complete_backbone"): + errors.append("checkpoint is smoke or lacks the complete backbone") + if state["world_size"] != 6 or len(state["rank_rng_states"]) != 6: + errors.append("checkpoint is not a complete six-rank state") + if state["next_global_sample_position"] != STAGES[stage]["offset"] + 6 * update: + errors.append("sampler cursor differs from the registered stage schedule") + if state["index_sha256"] != sha(INDEX) or state["code_sha256"] != training_code_hashes(): + errors.append("checkpoint data index or training code identity differs from current files") + if state.get("grad_clip") != 100.0: + errors.append("gradient clipping threshold differs from the frozen recipe") + exposure = Counter(state["exposures"]) + if sum(exposure.values()) != 6 * update: + errors.append("source/mode exposure ledger does not sum to global batch times updates") + if stage in ("S1", "S2", "S3"): + expected = {"H2O": 0.40, "ARCTIC": 0.35, "HOT3D": 0.25} + else: + expected = {"H2O": 0.35, "ARCTIC": 0.25, "HOT3D": 0.40} + source_exposure = { + source: sum(count for key, count in exposure.items() if key.startswith(source + ":")) + for source in expected + } + for source, fraction in expected.items(): + if abs(source_exposure[source] - 6 * update * fraction) > 6: + errors.append(f"{source} exposure differs from the registered quota") + expected_modes = { + "H2O:rgb", "H2O:rgb_k", "H2O:rgb_depth_k", + "ARCTIC:rgb", "ARCTIC:rgb_k", "HOT3D:rgb", "HOT3D:rgb_k", + } + if set(exposure) != expected_modes: + errors.append("one or more registered source/input modes are absent") + supervision = state.get("supervision_exposures") + if (not isinstance(supervision, dict) or not supervision + or sum(supervision.values()) <= 0 or min(supervision.values()) < 0): + errors.append("supervision ledger is empty or contains invalid counts") + if rows: + last = rows[-1] + if last["exposures"] != state["exposures"] or last.get("supervision_exposures") != supervision: + errors.append("final metrics row and checkpoint exposure ledgers differ") + if not all(math.isfinite(row["loss"]) and math.isfinite(row["grad_norm_max"]) for row in rows): + errors.append("nonfinite loss or gradient norm in the training history") + extreme_loss_updates = [row["update"] for row in rows + if math.isfinite(row["loss"]) + and row["loss"] > EXTREME_LOSS_THRESHOLD] + if extreme_loss_updates: + errors.append(f"extreme finite loss at updates {extreme_loss_updates[:20]}") + detailed = [row for row in rows if "grad_parameter_groups" in row] + required_groups = { + "rgb_encoder.projection", "depth_encoder", "ray_encoder", + "decoder.spatial", "joint2d_head", "rotation_head", + "translation_head", "shape_head", + } + if stage != "S1": + required_groups.update(("decoder.temporal", "shape_score")) + if stage == "S4": + required_groups.add("rgb_encoder.backbone") + if not all(any(row["grad_parameter_groups"].get(group, 0) > 0 for row in detailed) + for group in required_groups): + errors.append("a required trainable parameter group never received a nonzero gradient") + else: + detailed = [] + extreme_loss_updates = [] + window = min(100, len(rows)) + report = { + "status": "pass" if not errors else "fail", + "errors": errors, + "checkpoint": str(checkpoint), + "checkpoint_sha256": sha(checkpoint), + "stage": stage, + "update": update, + "training_code_sha256": state["code_sha256"]["clean_train.py"], + "source_exposure": source_exposure, + "source_mode_exposure": dict(exposure), + "supervision_ledger_keys": len(supervision or {}), + "supervision_elements": sum((supervision or {}).values()), + "first_window_loss_mean": statistics.mean(row["loss"] for row in rows[:window]) if rows else None, + "last_window_loss_mean": statistics.mean(row["loss"] for row in rows[-window:]) if rows else None, + "last_window_grad_norm_median": statistics.median(row["grad_norm_max"] for row in rows[-window:]) if rows else None, + "clipped_updates": sum(bool(row["clipped"]) for row in rows), + "max_batch_loss": max((row["loss"] for row in rows), default=None), + "extreme_loss_threshold": EXTREME_LOSS_THRESHOLD, + "extreme_loss_updates": extreme_loss_updates, + "detailed_rows": len(detailed), + } + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--metrics", type=Path, required=True) + parser.add_argument("--stage", choices=tuple(STAGES), required=True) + parser.add_argument("--update", type=int, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + report = run(args.checkpoint, args.metrics, args.stage, args.update) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2)) + if report["errors"]: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_gt_projection.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_gt_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..3a92d42d3cad354945b06e3c8d86d25dae30e4d0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_gt_projection.py @@ -0,0 +1,108 @@ +"""Freeze a 100-frame RGB/GT/K alignment gallery from trainable native clips.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from clean_train import ASSETS, MANIFESTS +from filtered_dataset import FilteredClipDataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.geometry.camera import project_points + + +QUOTAS = {"H2O": 40, "ARCTIC": 30, "HOT3D": 30} +CELL_HW = (200, 356) + + +def thumbnail(sample: dict, source: str, tile_id: str) -> tuple[np.ndarray, list[float], int]: + frame = len(sample["rgb"]) // 2 + rgb = sample["rgb"][frame].permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + points = sample["joint3d_camera"][frame] + K = sample["K"][frame] + projected, positive = project_points(points, K) + target = sample["joint2d"][frame] + valid = (sample["joint2d_valid"][frame] & sample["joint3d_valid"][frame] + & positive & torch.isfinite(target).all(-1)) + errors = torch.linalg.vector_norm(projected - target, dim=-1)[valid].tolist() + height, width = image.shape[:2] + for hand in range(2): + for joint in range(21): + if not bool(valid[hand, joint]): + continue + x, y = target[hand, joint].tolist() + px, py = projected[hand, joint].tolist() + if 0 <= x < width and 0 <= y < height: + cv2.circle(image, (round(x), round(y)), 3, (0, 255, 255), -1) + if 0 <= px < width and 0 <= py < height: + cv2.circle(image, (round(px), round(py)), 2, (255, 0, 255), -1) + cell_height, cell_width = CELL_HW + image = cv2.resize(image, (cell_width, cell_height - 28), interpolation=cv2.INTER_AREA) + cell = np.zeros((cell_height, cell_width, 3), dtype=np.uint8) + cell[:cell_height - 28] = image + label = f"{source} {tile_id[-22:]} valid={int(valid.sum())}" + cv2.putText(cell, label, (5, cell_height - 9), cv2.FONT_HERSHEY_SIMPLEX, + .38, (255, 255, 255), 1, cv2.LINE_AA) + return cell, errors, int(valid.sum()) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + args.output.mkdir(parents=True) + cells = [] + report = {"schema": "clean_gt_projection_audit_v1", "selection": "linspace over frozen trainable T8 manifests", + "total_frames": sum(QUOTAS.values()), "sources": {}} + for source, count in QUOTAS.items(): + manifest = MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl" + dataset = FilteredClipDataset( + source, manifest, 8, (368, 640), ASSETS["mano_root"], + Path(__file__).parent / "third_party", {"enabled": False}, + ) + indices = np.linspace(0, len(dataset) - 1, count, dtype=int) + errors = [] + valid_counts = [] + tiles = [] + for index in indices: + row = dataset.rows[int(index)] + tile_id = str(row["filtered_tile_id"]) + sample = dataset[{"source": source, "tile_id": tile_id, "epoch": 0, + "mode": "rgb_depth_k" if source == "H2O" else "rgb_k", + "position": 0, "source_ordinal": int(index)}] + cell, joint_errors, valid_count = thumbnail(sample, source, tile_id) + cells.append(cell) + errors.extend(joint_errors) + valid_counts.append(valid_count) + tiles.append(tile_id) + values = np.asarray(errors) + report["sources"][source] = { + "frames": count, "frames_with_valid_3d_and_2d": sum(x > 0 for x in valid_counts), + "valid_joints": len(errors), "mean_reprojection_px": float(values.mean()) if len(values) else None, + "p95_reprojection_px": float(np.quantile(values, .95)) if len(values) else None, + "max_reprojection_px": float(values.max()) if len(values) else None, + "tile_ids": tiles, + } + height, width = CELL_HW + gallery = np.zeros((10 * height, 10 * width, 3), dtype=np.uint8) + for number, cell in enumerate(cells): + row, col = divmod(number, 10) + gallery[row * height:(row + 1) * height, col * width:(col + 1) * width] = cell + if not cv2.imwrite(str(args.output / "gt_projection_100.jpg"), gallery): + raise RuntimeError("gallery write failed") + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({name: {key: value for key, value in row.items() if key != "tile_ids"} + for name, row in report["sources"].items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_headset_sync.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_headset_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..679b0c33f13bd968d67a8980223428165da61a61 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_headset_sync.py @@ -0,0 +1,104 @@ +"""Audit HOT3D camera-frame GT construction against native headset pose time.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import csv +from functools import lru_cache +import json +from pathlib import Path + +import numpy as np + +from preflight_index import tile_starts + + +MAX_DELTA_NS = 20_000_000 + + +@lru_cache(maxsize=256) +def trajectory(root: str) -> np.ndarray: + path = Path(root) / "headset_trajectory.csv" + with path.open(newline="") as stream: + stamps = np.asarray( + [int(row["timestamp[ns]"]) for row in csv.DictReader(stream)], dtype=np.int64, + ) + if len(stamps) == 0 or np.any(np.diff(stamps) <= 0): + raise ValueError(f"empty or nonmonotone headset trajectory: {path}") + return stamps + + +@lru_cache(maxsize=256) +def timeline(path: str, stream: str) -> np.ndarray: + return np.asarray(json.loads(Path(path).read_text())[stream], dtype=np.int64) + + +def deltas(target: np.ndarray, reference: np.ndarray) -> np.ndarray: + upper = np.searchsorted(reference, target).clip(0, len(reference) - 1) + lower = (upper - 1).clip(0, len(reference) - 1) + return np.minimum(np.abs(reference[upper] - target), np.abs(reference[lower] - target)) + + +def audit(manifest: Path) -> tuple[dict, list[dict]]: + counts = Counter() + recording_bad = Counter() + bad: list[dict] = [] + max_deltas = [] + for line in manifest.open(): + if not line.strip(): + continue + row = json.loads(line) + if row["dataset"] != "HOT3D": + continue + source = row["source"] + stamps = timeline(source["timestamps_path"], row["stream_id"])[ + int(row["start"]):int(row["end"]) + ] + if len(stamps) != row["frame_count"]: + raise ValueError(f"timeline length mismatch: {row['id']}") + delta = deltas(stamps, trajectory(source["root"])) + bad_frames = delta > MAX_DELTA_NS + bad_tiles = [start for start in tile_starts(len(stamps)) + if bool(bad_frames[start:start + 8].any())] + counts["windows"] += 1 + counts["frames"] += len(stamps) + counts["tiles"] += len(tile_starts(len(stamps))) + counts["bad_frames"] += int(bad_frames.sum()) + counts["bad_tiles"] += len(bad_tiles) + if bad_frames.any(): + counts["bad_windows"] += 1 + recording_bad[row["recording_id"]] += 1 + max_deltas.append(float(delta.max() / 1e6)) + bad.append({"window_id": row["id"], "recording_id": row["recording_id"], + "stream_id": row["stream_id"], "bad_frame_offsets": np.flatnonzero(bad_frames).tolist(), + "bad_tile_offsets": bad_tiles, "maximum_nearest_headset_delta_ms": float(delta.max() / 1e6)}) + report = { + "threshold_ms": 20, "counts": dict(counts), + "affected_recordings": len(recording_bad), + "worst_recordings_by_window_count": recording_bad.most_common(20), + "bad_window_delta_ms_median": float(np.median(max_deltas)) if max_deltas else 0, + "bad_window_delta_ms_max": max(max_deltas, default=0), + } + return report, bad + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--report", type=Path, required=True) + parser.add_argument("--bad-windows", type=Path, required=True) + args = parser.parse_args() + for path in (args.report, args.bad_windows): + if path.exists(): + raise FileExistsError(path) + report, bad = audit(args.manifest) + args.report.write_text(json.dumps(report, indent=2) + "\n") + with args.bad_windows.open("w") as stream: + for row in bad: + stream.write(json.dumps(row) + "\n") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_input_modes.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_input_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c4c2ab8786bbffe21be79e147165f59b008111 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_input_modes.py @@ -0,0 +1,58 @@ +"""Assert modality input dropout never changes camera or GT supervision.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from clean_train import ASSETS, MANIFESTS +from filtered_dataset import FilteredClipDataset + + +SUPERVISION = ( + "K", "K_supervision_valid", "joint2d", "joint2d_valid", + "joint3d_camera", "joint3d_valid", "wrist_root_translation", + "translation_valid", "mano_pose", "mano_pose_valid", "mano_shape", + "shape_valid", "vertices_valid", "reprojection_valid", +) + + +def main() -> None: + result = {} + for source in ("H2O", "ARCTIC", "HOT3D"): + manifest = MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl" + dataset = FilteredClipDataset( + source, manifest, 8, (368, 640), ASSETS["mano_root"], + Path(__file__).parent / "third_party", {"enabled": False}, + ) + row = dataset.rows[0] + spec = {"source": source, "tile_id": row["filtered_tile_id"], + "position": 0, "source_ordinal": 0, "epoch": 0} + modes = ("rgb", "rgb_k", "rgb_depth_k") if source == "H2O" else ("rgb", "rgb_k") + samples = {mode: dataset[{**spec, "mode": mode}] for mode in modes} + reference = samples["rgb"] + frame = reference["frame_valid"].bool() + if not bool(reference["K_supervision_valid"].any()): + raise AssertionError(f"{source} selected clip lacks K supervision") + for mode, sample in samples.items(): + torch.testing.assert_close(sample["rgb"], reference["rgb"]) + for name in SUPERVISION: + torch.testing.assert_close(sample[name], reference[name], equal_nan=True) + expected_K = frame if mode != "rgb" else torch.zeros_like(frame) + expected_depth = frame if mode == "rgb_depth_k" else torch.zeros_like(frame) + for canonical, alias, expected in ( + ("K_input_available", "K_available", expected_K), + ("depth_input_available", "depth_available", expected_depth), + ): + if not torch.equal(sample[canonical], expected) or not torch.equal(sample[alias], expected): + raise AssertionError(f"{source}:{mode} availability flags diverge") + result[source] = {"tile_id": spec["tile_id"], "modes": modes, + "K_supervised_frames": int(reference["K_supervision_valid"].sum()), + "GT_and_real_K_unchanged": True} + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_schedule.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..d564389690154f78b10e1e20fca34b32a428afae --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/audit_schedule.py @@ -0,0 +1,50 @@ +"""Verify every registered T=8 tile is exposed before source-local reuse.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +from pathlib import Path + +from coverage_sampler import CoverageSampler, SOURCES + + +def audit(index: Path, stage: str, samples: int) -> dict: + sampler = CoverageSampler(index, stage) + seen = {source: set() for source in SOURCES} + exposures = Counter() + modes = Counter() + first_coverage = {} + for position in range(samples): + row = sampler.sample(position) + source = str(row["source"]) + ordinal = int(row["source_ordinal"]) + if ordinal < sampler.sizes[source] and row["tile_id"] in seen[source]: + raise AssertionError(f"tile repeated before coverage: {source} {row['tile_id']}") + seen[source].add(row["tile_id"]) + exposures[source] += 1 + modes[f"{source}:{row['mode']}"] += 1 + if source not in first_coverage and len(seen[source]) == sampler.sizes[source]: + first_coverage[source] = position + 1 + if any(len(seen[source]) != sampler.sizes[source] for source in SOURCES): + raise AssertionError("registered T=8 stage did not cover all source tiles") + return { + "stage": stage, "samples": samples, "status": "pass", + "tiles": sampler.sizes, "unique_tiles": {source: len(seen[source]) for source in SOURCES}, + "exposures": dict(exposures), "input_modes": dict(modes), + "first_complete_global_position": first_coverage, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--index", type=Path, required=True) + parser.add_argument("--stage", choices=("S1_S3", "S4"), required=True) + parser.add_argument("--samples", type=int, required=True) + args = parser.parse_args() + print(json.dumps(audit(args.index, args.stage, args.samples), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/benchmark_decode.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/benchmark_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a2146c5035daa63e01ea7574caf358c84a6363 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/benchmark_decode.py @@ -0,0 +1,56 @@ +"""Measure uncached native clip decoding across spaced recordings.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys +import time + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import numpy as np +import torch + +from filtered_dataset import FilteredClipDataset + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--count", type=int, default=8) + parser.add_argument("--grouped", action="store_true", help="Read consecutive tiles in one recording") + args = parser.parse_args() + start = time.perf_counter() + dataset = FilteredClipDataset( + args.source, args.manifests / f"{args.source.lower()}_t8.jsonl", 8, + (368, 640), "/SSD3/jiasen/foundation_hand/pretrained/mano", + Path(__file__).parent / "third_party", {"enabled": False}, + ) + init_seconds = time.perf_counter() - start + indices = list(range(args.count)) if args.grouped else np.linspace( + 0, len(dataset) - 1, args.count, dtype=int, + ).tolist() + times = [] + recordings = [] + with torch.no_grad(): + for sequence, index in enumerate(indices): + row = dataset.rows[index] + spec = {"source": args.source, "tile_id": row["filtered_tile_id"], + "epoch": 0, "source_ordinal": sequence, "position": sequence, + "mode": "rgb_depth_k" if args.source == "H2O" else "rgb_k"} + mark = time.perf_counter() + sample = dataset[spec] + times.append(time.perf_counter() - mark) + recordings.append(sample["physical_recording_id"]) + print(json.dumps({"source": args.source, "count": len(times), + "recordings": len(set(recordings)), "init_seconds": init_seconds, + "decode_seconds": times, "median_seconds": float(np.median(times)), + "p95_seconds": float(np.quantile(times, .95)), + "clips_per_second_single_worker": len(times) / sum(times)}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/build_trainable_index.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/build_trainable_index.py new file mode 100644 index 0000000000000000000000000000000000000000..03f9619e1b4a6beca9a51c0da26ab28d09d4d898 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/build_trainable_index.py @@ -0,0 +1,126 @@ +"""Apply audited HOT3D headset-pose eligibility without changing source GT.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +import os +from pathlib import Path +import sqlite3 + +from preflight_index import digest, tile_starts + + +def valid_runs(length: int, invalid: set[int]): + start = None + for position in range(length + 1): + good = position < length and position not in invalid + if good and start is None: + start = position + elif not good and start is not None: + yield start, position + start = None + + +def build(original: Path, audit: Path, bad_windows: Path, output: Path) -> dict: + if output.exists(): + raise FileExistsError(output) + report = json.loads(audit.read_text()) + if report["threshold_ms"] != 20 or report["counts"]["windows"] != 18962: + raise ValueError("headset synchronization audit is not the frozen full-data audit") + bad_rows = [json.loads(line) for line in bad_windows.open() if line.strip()] + if len(bad_rows) != report["counts"]["bad_windows"]: + raise ValueError("bad-window list differs from summary") + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_suffix(output.suffix + ".tmp") + if temporary.exists(): + raise FileExistsError(temporary) + source = sqlite3.connect(f"file:{original}?mode=ro", uri=True) + target = sqlite3.connect(temporary) + try: + source.backup(target) + target.execute("CREATE TABLE sync_exclusions (window_id TEXT PRIMARY KEY, bad_frame_offsets_json TEXT NOT NULL)") + lost_valid_frames = 0 + recovered_valid_frames = 0 + windows_without_t8 = 0 + for record in bad_rows: + window_id = record["window_id"] + row = target.execute( + "SELECT source,recording_id,frame_ids_json FROM windows WHERE window_id=?", + (window_id,), + ).fetchone() + if row is None or row[0] != "HOT3D": + raise ValueError(f"unknown HOT3D window {window_id}") + _, recording, frame_ids_json = row + frame_ids = json.loads(frame_ids_json) + invalid = set(record["bad_frame_offsets"]) + if not invalid or min(invalid) < 0 or max(invalid) >= len(frame_ids): + raise ValueError(f"bad frame offsets outside window {window_id}") + original_bad_tiles = [offset for (offset,) in target.execute( + "SELECT start_offset FROM tiles WHERE window_id=?", (window_id,), + ) if invalid.intersection(range(offset, offset + 8))] + if sorted(original_bad_tiles) != sorted(record["bad_tile_offsets"]): + raise ValueError(f"headset audit tile mapping differs: {window_id}") + target.execute("DELETE FROM tiles WHERE window_id=?", (window_id,)) + target.execute("INSERT INTO sync_exclusions VALUES (?,?)", + (window_id, json.dumps(sorted(invalid)))) + covered = set() + tile_count = 0 + for first, last in valid_runs(len(frame_ids), invalid): + if last - first < 8: + continue + for local_start in tile_starts(last - first): + offset = first + local_start + selected = frame_ids[offset:offset + 8] + if len(selected) != 8 or invalid.intersection(range(offset, offset + 8)): + raise AssertionError("trainable tile contains an invalid headset frame") + target.execute( + "INSERT INTO tiles VALUES (?,?,?,?,?,?)", + (f"{window_id}:{offset}", window_id, "HOT3D", recording, + offset, json.dumps(selected)), + ) + covered.update(range(offset, offset + 8)) + tile_count += 1 + if tile_count == 0: + windows_without_t8 += 1 + recovered_valid_frames += len(covered) + lost_valid_frames += (len(frame_ids) - len(invalid) - len(covered)) + counts = Counter(dict(target.execute("SELECT source, COUNT(*) FROM tiles GROUP BY source"))) + bad_tile_check = target.execute( + "SELECT COUNT(*) FROM tiles t JOIN sync_exclusions e ON t.window_id=e.window_id" + ).fetchone()[0] + target.commit() + except BaseException: + target.close() + source.close() + temporary.unlink(missing_ok=True) + raise + target.close() + source.close() + os.replace(temporary, output) + return { + "status": "pass", "original_index_sha256": digest(original), + "headset_sync_report_sha256": digest(audit), + "headset_bad_windows_sha256": digest(bad_windows), + "trainable_index_sha256": digest(output), "tiles_by_source": dict(counts), + "audited_windows_with_bad_headset_pose": len(bad_rows), + "windows_without_any_t8": windows_without_t8, + "valid_frames_covered_inside_affected_windows": recovered_valid_frames, + "valid_frames_not_packable_into_t8": lost_valid_frames, + "tiles_in_affected_windows": bad_tile_check, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--original", type=Path, required=True) + parser.add_argument("--audit", type=Path, required=True) + parser.add_argument("--bad-windows", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(build(args.original, args.audit, args.bad_windows, args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/clean_eval.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/clean_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..888132d52b7c6e468fab8ecb62bac9627b82caf8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/clean_eval.py @@ -0,0 +1,139 @@ +"""Evaluate a complete clean-GT checkpoint on frozen native-GT panels.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import ASSETS, INDEX, ROOT, model_for, sha, training_code_hashes +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.h2o_dataset import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +FOUR_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", +) + + +def dataset_for(source: str, manifest: Path): + hw = (512, 896) + if source == "H2O": + return H2OCam4Dataset( + "/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, hw, + clip_lengths=(8,), strides=(1,), window_step=8, + allow_partial=False, + ) + if source == "ARCTIC": + return ARCTICClipDataset(manifest, ASSETS["mano_root"], hw) + if source == "HOT3D": + return HOT3DClipDataset( + "/SSD3/jiasen/foundation_hand/HOT3D/dataset", manifest, + Path(__file__).parent / "third_party", ASSETS["mano_root"], + hw, K_input_dropout=0.0, + ) + raise ValueError(source) + + +def apply_mode(batch: dict, mode: str) -> None: + frame = batch["frame_valid"].bool() + K = frame.clone() if mode != "rgb" else torch.zeros_like(frame) + depth = frame.clone() if mode == "rgb_depth_k" else torch.zeros_like(frame) + batch["K_input_available"] = K + batch["depth_input_available"] = depth + batch["K_available"] = K.clone() + batch["depth_available"] = depth.clone() + if not (torch.equal(batch["K_input_available"], K) + and torch.equal(batch["depth_input_available"], depth)): + raise RuntimeError("input availability override failed") + + +def run(args: argparse.Namespace) -> dict: + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + if panel_report["train_manifest_sha256"] != "b4b0ac4bc4a771c9bc7626a9eec7f5f541ef96908a9a64d219192efd7b8f7f89": + raise RuntimeError("frozen training allowlist identity differs") + if args.role == "confirmation" and not args.final_checkpoint: + raise ValueError("confirmation is reserved for a frozen final checkpoint") + if args.source != "H2O" and args.mode == "rgb_depth_k": + raise ValueError("only H2O has real metric depth") + manifest = panels / f"{args.source.lower()}_{args.role}_t8.jsonl" + expected = panel_report["sources"][args.source][args.role]["manifest_sha256"] + if sha(manifest) != expected: + raise RuntimeError("validation panel SHA256 changed") + if args.output.exists(): + raise FileExistsError(args.output) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if not state.get("complete_backbone") or state["index_sha256"] != sha(INDEX): + raise RuntimeError("checkpoint lacks complete DINO or filtered-index identity") + if state.get("smoke", False) and not args.allow_smoke: + raise RuntimeError("smoke checkpoint is not valid for formal evaluation") + code_match = state["code_sha256"] == training_code_hashes() + if not code_match and not args.allow_smoke: + raise RuntimeError("evaluation code differs from checkpoint training code") + if args.role == "confirmation" and ( + state.get("smoke", False) or state["stage"] != "S4" + or state["update"] != 66667 + ): + raise RuntimeError("confirmation requires the frozen S4 endpoint") + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + dataset = dataset_for(args.source, manifest) + if args.limit is not None and not args.allow_smoke: + raise ValueError("subset evaluation must be marked as smoke") + limit = min(len(dataset), args.limit) if args.limit is not None else len(dataset) + rows = [] + with torch.inference_mode(): + for index in range(limit): + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"): + prediction = model(batch) + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows.append(make_row(prediction, batch, 0, frame, side)) + summary = aggregate(rows) + report = { + "role": args.role, "source": args.source, "input_mode": args.mode, + "checkpoint": str(args.checkpoint), "checkpoint_sha256": sha(args.checkpoint), + "checkpoint_stage": state["stage"], "checkpoint_update": state["update"], + "panel_sha256": expected, "clips": limit, "hands": len(rows), + "smoke": bool(args.allow_smoke), + "checkpoint_code_match": code_match, + "evaluator_sha256": sha(Path(__file__)), + "metric_impl_sha256": sha(Path(__file__).parent / "scripts/evaluate_phase7_external.py"), + "four_metrics": {name: summary[name] for name in FOUR_METRICS}, + "supervision_coverage": summary["supervision_coverage"], + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--role", choices=("development", "confirmation"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--final-checkpoint", action="store_true") + parser.add_argument("--allow-smoke", action="store_true") + parser.add_argument("--limit", type=int) + args = parser.parse_args() + print(json.dumps(run(args), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/clean_train.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/clean_train.py new file mode 100644 index 0000000000000000000000000000000000000000..3887eb28769f77ab87cea0c5fa960955b78dcf80 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/clean_train.py @@ -0,0 +1,558 @@ +"""Fresh-DINO staged Foundation Hand training on the frozen filtered-GT index. + +Use torchrun for DDP. This entry never loads a learned Foundation Hand parent. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from contextlib import nullcontext +from datetime import timedelta +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import sys +import time + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import numpy as np +import torch +import torch.distributed as dist +from torch import nn +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader, Dataset, Sampler +from safetensors import safe_open + +from coverage_sampler import CoverageSampler, SOURCES +from filtered_dataset import FilteredClipDataset +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.losses import BimanualLoss, LossConfig +from foundation_hand.training.optimizer import optimizer_parameter_groups, set_scheduled_learning_rate +from foundation_hand.training.schedule import warmup_cosine_learning_rate +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925") +INDEX = ROOT / "cache/trainable_t8_index.sqlite" +MANIFESTS = ROOT / "cache" +EXPECTED_INDEX_SHA256 = "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462" +EXPECTED_MANIFEST_SHA256 = { + 1: {"ARCTIC": "489315448fef1a2adcb50d7ba162d3d376810d0fa652905330d5e3db77620c62", + "H2O": "7bca84c00e66e9680704d5c54b1001af637cda620ef4f31037626407dcd8dc88", + "HOT3D": "391c837142e5985bf45c505bc9c3f3daa7f220c3a4144bad51635ca1f632e15f"}, + 8: {"ARCTIC": "35b61473010ae198b036d3c549ae1b922439e35711e5bc76f7f06c58fd82e7e6", + "H2O": "74e20172e321b363523f05497b891834d88edd0f349acb58288a4e6f37e01a8a", + "HOT3D": "8630298efbce16764a0c1d7bc108f46675c26a9fc290553b7920420b74f877b7"}, +} +ASSETS = { + "dinov3_source": "/home/jiasen/foundation_hand/third_party/dinov3", + "dinov3_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "mano_root": "/SSD3/jiasen/foundation_hand/pretrained/mano", +} +STAGES = { + "S1": {"time": 1, "hw": (368, 640), "updates": 16667, + "coverage": "S1_S3", "offset": 0, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S2": {"time": 8, "hw": (368, 640), "updates": 50000, + "coverage": "S1_S3", "offset": 0, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S3": {"time": 8, "hw": (512, 896), "updates": 83334, + "coverage": "S1_S3", "offset": 300000, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S4": {"time": 8, "hw": (512, 896), "updates": 66667, + "coverage": "S4", "offset": 0, "max_lr": 1e-5, "min_lr": 1e-6, "last2": 2}, +} +LOSS = LossConfig( + joint2d=1.0, joint3d_camera=10.0, joint3d_root_relative=10.0, + vertices_camera=1.0, local_pose=1.0, global_orientation=1.0, + shape=.1, translation=10.0, reprojection=1.0, + temporal_velocity=.1, temporal_acceleration=.05, + bimanual_relative_wrist=1.0, presence=0.0, +) +FRESH_HEAD_WEIGHT_STD = 0.001 +FRESH_DEPTH_WEIGHT_STD = 0.001 +MONITORED_LOSSES = ( + "joint2d", "joint3d_camera", "joint3d_root_relative", "vertices_camera", + "local_pose", "global_orientation", "shape", "translation", + "reprojection", "temporal_velocity", "temporal_acceleration", + "bimanual_relative_wrist", +) +TRANSLATION_DIAGNOSTICS = tuple( + f"translation_{axis}_{suffix}" + for axis in ("x", "y", "z") + for suffix in ("raw_mae_m", "effective_loss_contribution") +) +MASK_FIELDS = ( + "joint2d_valid", "joint3d_valid", "joint3d_root_relative_valid", + "translation_valid", "mano_pose_valid", "shape_valid", + "vertices_valid", "reprojection_valid", +) + + +def sha(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def training_code_hashes() -> dict[str, str]: + code_root = Path(__file__).parent + paths = [code_root / name for name in ( + "clean_train.py", "filtered_dataset.py", "coverage_sampler.py", + "export_adapter_manifests.py", "build_trainable_index.py", + )] + list((code_root / "src/foundation_hand").rglob("*.py")) + list( + (code_root / "third_party/hot3d").rglob("*.py") + ) + return {str(path.relative_to(code_root)): sha(path) for path in sorted(paths)} + + +class MixedDataset(Dataset): + def __init__(self, time: int, hw: tuple[int, int]): + manifests = MANIFESTS / f"adapter_trainable_t{time}" + self.sources = { + source: FilteredClipDataset( + source, manifests / f"{source.lower()}_t{time}.jsonl", time, + hw, ASSETS["mano_root"], Path(__file__).parent / "third_party", + {"enabled": source != "HOT3D", "probability": .8}, + ) + for source in SOURCES + } + + def __len__(self) -> int: + return sum(map(len, self.sources.values())) + + def __getitem__(self, spec: dict): + return self.sources[str(spec["source"])][spec] + + +class PositionSampler(Sampler[dict]): + def __init__(self, coverage: CoverageSampler, first: int, last: int, rank: int, world: int): + self.coverage, self.first, self.last = coverage, first, last + self.rank, self.world = rank, world + + def __iter__(self): + yield from self.coverage.shard(self.first, self.last, self.rank, self.world) + + def __len__(self): + return (self.last - self.first) // self.world + + +class Objective(nn.Module): + def __init__(self, model: BimanualReconstructionModel): + super().__init__() + self.model = model + self.criterion = BimanualLoss(LOSS) + + def forward(self, batch: dict): + prediction = self.model(batch) + losses = self.criterion(prediction, batch) + with torch.no_grad(): + losses.update(self.criterion.translation_diagnostics(prediction, batch)) + return losses + + +def model_for(stage: str) -> BimanualReconstructionModel: + options = STAGES[stage] + config = ModelConfig( + encoder="dinov3", decoder_dim=512, decoder_layers=3, attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, + depth_mode="geometry", depth_gate_mode="fixed", depth_gate_fixed_value=.5, + use_rays=True, use_bimanual_interaction=True, predict_presence=True, + require_mano=True, mano_fix_left_shapedirs=True, + modality_dropout_prob=0.0, temporal_position_mode="none", + temporal_attention_mode="bidirectional", dinov3_trainable_last_blocks=options["last2"], + translation_parameterization="direct_xyz", **ASSETS, + ) + model = BimanualReconstructionModel(config) + if stage == "S1": + with torch.no_grad(): + for head in ( + model.joint2d_head, model.rotation_head, + model.translation_head, model.shape_head, + ): + nn.init.normal_(head.weight, std=FRESH_HEAD_WEIGHT_STD) + nn.init.normal_( + model.depth_encoder.encoder[-1].weight, + std=FRESH_DEPTH_WEIGHT_STD, + ) + model.presence_head.requires_grad_(False) + if stage == "S1": + model.decoder.temporal_enabled = False + model.decoder.temporal.requires_grad_(False) + return model + + +def verify_official_dino(model: BimanualReconstructionModel) -> dict: + weight_file = Path(ASSETS["dinov3_weights"]) / "model.safetensors" + backbone = model.rgb_encoder.backbone.state_dict() + with safe_open(str(weight_file), framework="pt", device="cpu") as weights: + if set(backbone) != set(weights.keys()): + raise RuntimeError("pretrained DINO tensor names differ from model backbone") + for name, value in backbone.items(): + if not torch.equal(value.cpu(), weights.get_tensor(name)): + raise RuntimeError(f"DINO differs from official weight: {name}") + return {"tensors_equal": len(backbone), "official_safetensors_sha256": sha(weight_file), + "projection_is_new": "projection.weight" not in backbone} + + +def rng_state(device: torch.device) -> dict: + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state(device)} + + +def restore_rng(state: dict, device: torch.device) -> None: + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"].cpu()) + torch.cuda.set_rng_state(state["cuda"].cpu(), device) + + +def gradient_group_norms(model: nn.Module) -> dict[str, float]: + squared: dict[str, torch.Tensor] = {} + for name, parameter in model.named_parameters(): + if parameter.grad is None: + continue + parts = name.split(".") + group = ".".join(parts[:2]) if parts[0] in ("rgb_encoder", "decoder") else parts[0] + squared[group] = squared.get(group, parameter.grad.new_zeros(())) + parameter.grad.float().square().sum() + return {name: float(value.sqrt()) for name, value in squared.items()} + + +def storage_guard(start: bool) -> None: + devices = {path.stat().st_dev for path in (ROOT, ROOT / "cache", ROOT / "checkpoints", ROOT / "logs", ROOT / "eval")} + if len(devices) != 1: + raise RuntimeError("run directories are not on the same filesystem") + free = shutil.disk_usage(ROOT).free + threshold = (300 if start else 200) * 1024**3 + if free < threshold: + raise RuntimeError(f"root disk free {free / 1024**3:.1f} GiB below stage guard") + checkpoint_bytes = sum( + path.stat().st_size for path in (ROOT / "checkpoints").rglob("*.pt") + if not any("smoke" in component for component in path.relative_to(ROOT).parts) + ) + if not start and checkpoint_bytes + 2 * 1024**3 > 40 * 1024**3: + raise RuntimeError("checkpoint budget cannot fit another full checkpoint") + + +def checkpoint( + path: Path, stage: str, update: int, model: nn.Module, + optimizer: torch.optim.Optimizer, counts: Counter, supervision_counts: Counter, + device: torch.device, + rank: int, world: int, code_hashes: dict, data_hashes: dict, smoke: bool, + grad_clip: float, +) -> None: + local_rng = rng_state(device) + all_rng = [None] * world if rank == 0 else None + if world > 1: + dist.gather_object(local_rng, all_rng, dst=0) + else: + all_rng = [local_rng] + if rank == 0: + storage_guard(False) + if path.exists() or path.with_suffix(".tmp").exists(): + raise FileExistsError(f"checkpoint path is occupied: {path}") + state = { + "model": model.state_dict(), "optimizer": optimizer.state_dict(), + "stage": stage, "update": update, "world_size": world, + "next_global_sample_position": STAGES[stage]["offset"] + update * 6, + "index_sha256": sha(INDEX), "code_sha256": code_hashes, + "data_sha256": data_hashes, + "rank_rng_states": all_rng, "exposures": dict(counts), + "supervision_exposures": dict(supervision_counts), + "scheduler": {"stage_local_update": update, "total_updates": STAGES[stage]["updates"]}, + "complete_backbone": True, + "smoke": smoke, + "grad_clip": grad_clip, + } + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + temporary.replace(path) + loaded = torch.load(path, map_location="cpu", weights_only=False) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("checkpoint load-back failed") + print(f"checkpoint {path} sha256={sha(path)}", flush=True) + if world > 1: + dist.barrier(device_ids=[device.index]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--stage", choices=tuple(STAGES), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, required=True, help="Stage-local endpoint") + parser.add_argument("--workers", type=int, default=2) + parser.add_argument("--resume", type=Path) + parser.add_argument("--parent", type=Path) + parser.add_argument("--save", action="store_true") + parser.add_argument("--smoke", action="store_true", + help="Allow an incomplete prior-stage checkpoint for isolated preflight only") + parser.add_argument("--grad-clip", type=float, default=100.0) + args = parser.parse_args() + stage = args.stage + options = STAGES[stage] + if not 0 < args.updates <= options["updates"]: + raise ValueError("updates outside registered stage budget") + if not math.isfinite(args.grad_clip) or args.grad_clip <= 0: + raise ValueError("grad clip threshold must be finite and positive") + if not args.resume and (stage == "S1") == bool(args.parent): + raise ValueError("S1 requires no parent; S2/S3/S4 require a complete prior-stage parent") + if args.resume and args.parent: + raise ValueError("resume and stage parent are mutually exclusive") + rank = int(os.environ.get("RANK", 0)) + world = int(os.environ.get("WORLD_SIZE", 1)) + local_rank = int(os.environ.get("LOCAL_RANK", 0)) + if world not in (1, 2, 3, 6) or 6 % world: + raise ValueError("world size must divide global batch 6") + accumulation = 6 // world + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.cuda.set_device(local_rank) + device = torch.device("cuda", local_rank) + if world > 1: + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + storage_guard(True) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh run output already contains training metrics") + if world > 1: + dist.barrier(device_ids=[local_rank]) + code_hashes = training_code_hashes() + selected_manifests = MANIFESTS / f"adapter_trainable_t{options['time']}" + data_hashes = {name: sha(selected_manifests / f"{name.lower()}_t{options['time']}.jsonl") + for name in SOURCES} + if sha(INDEX) != EXPECTED_INDEX_SHA256 or data_hashes != EXPECTED_MANIFEST_SHA256[options["time"]]: + raise RuntimeError("frozen filtered index or native adapter manifest changed") + seed = 20260925 + rank + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed(seed) + model = model_for(stage) + dino_audit = verify_official_dino(model) if rank == 0 and stage == "S1" else None + model = model.to(device) + start = 0 + counts: Counter = Counter() + supervision_counts: Counter = Counter() + previous = args.resume or args.parent + state = None + if previous: + state = torch.load(previous, map_location="cpu", weights_only=False) + if not state.get("complete_backbone") or state["index_sha256"] != sha(INDEX): + raise RuntimeError("parent/resume checkpoint lacks full DINO or filtered-index identity") + if args.resume: + if (state["stage"] != stage or state["world_size"] != world + or state["code_sha256"] != code_hashes or state["data_sha256"] != data_hashes): + raise RuntimeError("exact resume contract mismatch") + if bool(state.get("smoke", False)) != args.smoke: + raise RuntimeError("smoke and formal checkpoints cannot be interchanged") + if float(state.get("grad_clip", 10.0)) != args.grad_clip: + raise RuntimeError("resume changed the gradient clipping threshold") + start = int(state["update"]) + counts.update(state["exposures"]) + supervision_counts.update(state["supervision_exposures"]) + else: + previous_stage = {"S2": "S1", "S3": "S2", "S4": "S3"}[stage] + if state["stage"] != previous_stage: + raise RuntimeError("stage parent is not the immediately preceding stage") + if not args.smoke and ( + state["update"] != STAGES[previous_stage]["updates"] + or state.get("smoke", False) + ): + raise RuntimeError("formal training requires a complete non-smoke prior stage") + if not args.smoke and state["code_sha256"] != code_hashes: + raise RuntimeError("formal stage parent was built with different training code") + if not args.smoke and STAGES[previous_stage]["time"] == options["time"]: + if state["data_sha256"] != data_hashes: + raise RuntimeError("T8 adapter manifests changed across formal stages") + model.load_state_dict(state["model"], strict=True) + model.train() + params = [parameter for parameter in model.parameters() if parameter.requires_grad] + backbone_lr = 5e-7 if stage == "S4" else None + optimizer = torch.optim.AdamW( + optimizer_parameter_groups(model, learning_rate=options["max_lr"], + backbone_learning_rate=backbone_lr), weight_decay=.05, + ) + if args.resume: + optimizer.load_state_dict(state["optimizer"]) + restore_rng(state["rank_rng_states"][rank], device) + del state + if not start < args.updates: + raise ValueError("resume checkpoint is already at or beyond requested endpoint") + dataset = MixedDataset(options["time"], options["hw"]) + coverage = CoverageSampler(INDEX, options["coverage"]) + first = options["offset"] + start * 6 + last = options["offset"] + args.updates * 6 + sampler = PositionSampler(coverage, first, last, rank, world) + loader = DataLoader(dataset, batch_size=1, sampler=sampler, + num_workers=args.workers, collate_fn=collate_h2o_clips, + pin_memory=True, persistent_workers=args.workers > 0, + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + objective = Objective(model).to(device) + if world > 1: + objective = DDP(objective, device_ids=[local_rank], output_device=local_rank, + broadcast_buffers=False, find_unused_parameters=True) + if rank == 0: + log = (args.output / "metrics.jsonl").open("a", buffering=1) + if dino_audit: + print(json.dumps({"official_dino_audit": dino_audit}), flush=True) + start_clock = time.monotonic() + torch.cuda.reset_peak_memory_stats(device) + for update in range(start, args.updates): + lr = warmup_cosine_learning_rate(update, options["updates"], + options["max_lr"], options["min_lr"], 1000) + set_scheduled_learning_rate(optimizer, lr) + optimizer.zero_grad(set_to_none=True) + losses_total = torch.zeros((), device=device) + local_modes = Counter() + local_supervision = Counter() + detailed = update < 10 or (update + 1) % 100 == 0 or update + 1 == args.updates + local_details: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + for micro in range(accumulation): + cpu = next(iterator) + source_name = cpu["sampling_source_id"][0] + local_modes[f"{source_name}:{cpu['input_mode'][0]}"] += 1 + batch = move_to_device(cpu, device) + mode_key = f"{source_name}:{cpu['input_mode'][0]}" + for name in MASK_FIELDS: + if name in cpu: + for side in range(2): + local_supervision[f"{mode_key}:{side}:{name}"] += int( + cpu[name][:, :, side].sum() + ) + attach_gt_vertices(batch, model) + sync = objective.no_sync() if world > 1 and micro + 1 < accumulation else nullcontext() + with sync, torch.autocast("cuda", dtype=torch.bfloat16): + losses = objective(batch) + if not torch.isfinite(losses["total"]): + raise RuntimeError(f"nonfinite loss at {stage} update {update}") + (losses["total"] / accumulation).backward() + losses_total += losses["total"].detach() / accumulation + if detailed: + detail = local_details[mode_key] + detail["samples"] += 1 + detail["loss_sums"].update({name: float(losses[name].detach()) + for name in MONITORED_LOSSES + TRANSLATION_DIAGNOSTICS}) + detail["valid_elements"].update({name: int(cpu[name].sum()) + for name in MASK_FIELDS if name in cpu}) + grad_groups = gradient_group_norms(model) if detailed and rank == 0 else None + grad_norm = torch.nn.utils.clip_grad_norm_(params, args.grad_clip) + if not torch.isfinite(grad_norm): + raise RuntimeError(f"nonfinite gradient norm at {stage} update {update}") + norm_min, norm_max = grad_norm.detach().clone(), grad_norm.detach().clone() + if world > 1: + dist.all_reduce(norm_min, op=dist.ReduceOp.MIN) + dist.all_reduce(norm_max, op=dist.ReduceOp.MAX) + optimizer.step() + if world > 1: + dist.all_reduce(losses_total) + gathered = [None] * world + dist.all_gather_object(gathered, { + "modes": dict(local_modes), "supervision": dict(local_supervision), + "details": dict(local_details) if detailed else {}, + }) + else: + gathered = [{"modes": dict(local_modes), + "supervision": dict(local_supervision), + "details": dict(local_details) if detailed else {}}] + for value in gathered: + counts.update(value["modes"]) + supervision_counts.update(value["supervision"]) + if rank == 0: + row = {"stage": stage, "update": update + 1, + "loss": float(losses_total / world), + "grad_norm_min": float(norm_min), "grad_norm_max": float(norm_max), + "clipped": float(norm_max) > args.grad_clip, + "grad_clip_threshold": args.grad_clip, "lr": lr, + "exposures": dict(counts)} + if detailed: + source_sums: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + mode_sums: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + for value in gathered: + for source_mode, detail in value["details"].items(): + source_name = source_mode.split(":", 1)[0] + for target in (source_sums[source_name], mode_sums[source_mode]): + target["samples"] += detail["samples"] + target["loss_sums"].update(detail["loss_sums"]) + target["valid_elements"].update(detail["valid_elements"]) + row["loss_terms"] = { + name: sum(detail["loss_sums"][name] for detail in source_sums.values()) / 6 + for name in MONITORED_LOSSES + } + row["source_loss_terms"] = { + source_name: {name: detail["loss_sums"][name] / detail["samples"] + for name in MONITORED_LOSSES} + for source_name, detail in source_sums.items() + } + row["source_valid_elements"] = { + source_name: dict(detail["valid_elements"]) + for source_name, detail in source_sums.items() + } + row["source_mode_loss_terms"] = { + source_mode: {name: detail["loss_sums"][name] / detail["samples"] + for name in MONITORED_LOSSES} + for source_mode, detail in mode_sums.items() + } + row["source_mode_translation_axes"] = { + source_mode: {name: detail["loss_sums"][name] / detail["samples"] + for name in TRANSLATION_DIAGNOSTICS} + for source_mode, detail in mode_sums.items() + } + row["source_mode_valid_elements"] = { + source_mode: dict(detail["valid_elements"]) + for source_mode, detail in mode_sums.items() + } + row["supervision_exposures"] = dict(supervision_counts) + row["grad_parameter_groups"] = grad_groups + log.write(json.dumps(row) + "\n") + if args.updates <= 10 or (update + 1) % 500 == 0 or update + 1 == args.updates: + print(json.dumps(row), flush=True) + milestone = update + 1 + registered = options["updates"] + if milestone < args.updates and ( + milestone % 10000 == 0 or milestone in { + round(registered * .25), round(registered * .50), round(registered * .75), + } + ): + checkpoint(args.output / f"{stage.lower()}_update_{milestone:07d}.pt", + stage, milestone, model, optimizer, counts, supervision_counts, + device, rank, world, code_hashes, data_hashes, + args.smoke, args.grad_clip) + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start_clock + elapsed_max = torch.tensor(elapsed, device=device) + peak_memory = torch.tensor(torch.cuda.max_memory_allocated(device) / 1024**3, device=device) + if world > 1: + dist.all_reduce(elapsed_max, op=dist.ReduceOp.MAX) + dist.all_reduce(peak_memory, op=dist.ReduceOp.MAX) + if rank == 0: + log.close() + print(json.dumps({"stage": stage, "elapsed_seconds_max": float(elapsed_max), + "clips_per_second": (args.updates - start) * 6 / float(elapsed_max), + "peak_allocated_gib_per_rank_max": float(peak_memory)}), flush=True) + if args.save: + path = args.output / f"{stage.lower()}_update_{args.updates:07d}.pt" + checkpoint(path, stage, args.updates, model, optimizer, counts, + supervision_counts, + device, rank, world, code_hashes, data_hashes, + args.smoke, args.grad_clip) + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/compare_checkpoints.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/compare_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7c8dbf5e02277d9cf98379adc69bf013f7f9ed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/compare_checkpoints.py @@ -0,0 +1,62 @@ +"""Compare continuous and resumed training checkpoints tensor by tensor.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + + +def compare(left: Path, right: Path) -> dict: + a = torch.load(left, map_location="cpu", weights_only=False) + b = torch.load(right, map_location="cpu", weights_only=False) + if (a["stage"], a["update"], a["next_global_sample_position"], a["exposures"], + a.get("supervision_exposures"), a.get("grad_clip")) != ( + b["stage"], b["update"], b["next_global_sample_position"], b["exposures"], + b.get("supervision_exposures"), b.get("grad_clip") + ): + raise AssertionError("stage/update/sampler cursor/exposures/optimizer contract differ") + model_differences = [] + if set(a["model"]) != set(b["model"]): + raise AssertionError("model tensor key sets differ") + for key in a["model"]: + if not torch.equal(a["model"][key], b["model"][key]): + model_differences.append(key) + if a["optimizer"]["param_groups"] != b["optimizer"]["param_groups"]: + raise AssertionError("optimizer parameter groups differ") + optimizer_differences = [] + left_states, right_states = a["optimizer"]["state"], b["optimizer"]["state"] + if set(left_states) != set(right_states): + raise AssertionError("optimizer state parameter IDs differ") + for parameter in left_states: + if set(left_states[parameter]) != set(right_states[parameter]): + raise AssertionError(f"optimizer state fields differ for parameter {parameter}") + for key, value in left_states[parameter].items(): + other = right_states[parameter][key] + equal = torch.equal(value, other) if torch.is_tensor(value) else value == other + if not equal: + optimizer_differences.append(f"{parameter}:{key}") + result = {"status": "pass" if not model_differences and not optimizer_differences else "fail", + "model_tensors": len(a["model"]), "model_differences": model_differences[:10], + "optimizer_states": len(left_states), + "optimizer_differences": optimizer_differences[:10], + "stage": a["stage"], "update": a["update"], + "next_global_sample_position": a["next_global_sample_position"]} + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("left", type=Path) + parser.add_argument("right", type=Path) + args = parser.parse_args() + result = compare(args.left, args.right) + print(json.dumps(result, indent=2)) + if result["status"] != "pass": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/coverage_sampler.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/coverage_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..2c00edc8e430b4c5421cb1491b0db472633be9fd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/coverage_sampler.py @@ -0,0 +1,116 @@ +"""Stateless source quotas and source-local no-replacement GT tile coverage.""" + +from __future__ import annotations + +from collections import defaultdict +import hashlib +import random +import sqlite3 +from pathlib import Path + + +SOURCES = ("H2O", "ARCTIC", "HOT3D") +QUOTAS = {"S1_S3": (8, 7, 5), "S4": (7, 5, 8)} +RECORDING_BLOCK_TILES = 64 + + +def _seed(*values: object) -> int: + encoded = "|".join(map(str, values)).encode("utf-8") + return int.from_bytes(hashlib.blake2b(encoded, digest_size=8).digest(), "little") + + +class CoverageSampler: + """A global sample position determines one immutable tile and input mode. + + S2 and S3 share S1_S3 positions 0..799999. S4 uses a new independent + position space, seed, and coverage ledger. DDP rank r reads positions + start+r, start+r+world_size, etc.; resume needs only the next global + position and the frozen index/code hashes. + """ + + def __init__(self, index: str | Path, stage: str, seed: int = 20260925): + if stage not in QUOTAS: + raise ValueError(f"unknown coverage stage {stage}") + self.stage = stage + self.seed = int(seed) + self.quota = QUOTAS[stage] + self.by_recording: dict[str, dict[str, list[str]]] = { + name: defaultdict(list) for name in SOURCES + } + with sqlite3.connect(index) as connection: + rows = connection.execute( + "SELECT source, recording_id, tile_id FROM tiles " + "ORDER BY source, recording_id, tile_id" + ) + for source, recording, tile_id in rows: + self.by_recording[source][recording].append(tile_id) + self.sizes = { + source: sum(map(len, self.by_recording[source].values())) + for source in SOURCES + } + if min(self.sizes.values()) <= 0: + raise ValueError("each source must contain at least one tile") + self._permutation_cache: dict[tuple[str, int], list[str]] = {} + self._cycle_cache: tuple[int, list[str]] | None = None + + def source_and_ordinal(self, position: int) -> tuple[str, int]: + if position < 0: + raise ValueError("negative sample position") + cycle, within = divmod(position, sum(self.quota)) + if self._cycle_cache is None or self._cycle_cache[0] != cycle: + order = [source for source, count in zip(SOURCES, self.quota) for _ in range(count)] + random.Random(_seed(self.seed, self.stage, "source", cycle)).shuffle(order) + self._cycle_cache = (cycle, order) + else: + order = self._cycle_cache[1] + source = order[within] + source_index = SOURCES.index(source) + ordinal = cycle * self.quota[source_index] + order[:within].count(source) + return source, ordinal + + def _epoch_order(self, source: str, epoch: int) -> list[str]: + key = (source, epoch) + if key in self._permutation_cache: + return self._permutation_cache[key] + randomizer = random.Random(_seed(self.seed, self.stage, source, epoch)) + recordings = list(self.by_recording[source]) + randomizer.shuffle(recordings) + groups = [] + for recording in recordings: + group = self.by_recording[source][recording].copy() + randomizer.shuffle(group) + groups.append(group) + result: list[str] = [] + depth = 0 + while len(result) < self.sizes[source]: + for group in groups: + result.extend(group[depth:depth + RECORDING_BLOCK_TILES]) + depth += RECORDING_BLOCK_TILES + if len(result) != len(set(result)): + raise AssertionError(f"duplicate tile in {source} epoch {epoch}") + for old_key in list(self._permutation_cache): + if old_key[0] == source and old_key[1] < epoch - 1: + del self._permutation_cache[old_key] + self._permutation_cache[key] = result + return result + + def sample(self, position: int) -> dict[str, object]: + source, ordinal = self.source_and_ordinal(position) + epoch, offset = divmod(ordinal, self.sizes[source]) + tile_id = self._epoch_order(source, epoch)[offset] + mode_rng = random.Random(_seed(self.seed, self.stage, "mode", position)) + K_drop = {"H2O": .20, "ARCTIC": .50, "HOT3D": .30}[source] + K_available = mode_rng.random() >= K_drop + depth_available = source == "H2O" and K_available and mode_rng.random() >= .125 + mode = "rgb_depth_k" if depth_available else "rgb_k" if K_available else "rgb" + return { + "position": position, "source": source, "source_ordinal": ordinal, + "epoch": epoch, "tile_id": tile_id, "mode": mode, + } + + def shard(self, start: int, stop: int, rank: int, world_size: int): + if not 0 <= start <= stop or not 0 <= rank < world_size: + raise ValueError("invalid range or rank") + first = start + (rank - start) % world_size + for position in range(first, stop, world_size): + yield self.sample(position) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_formal_loss_spikes.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_formal_loss_spikes.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f7417d5a9744b021aee827ed7f0b8e0e7bc4c2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_formal_loss_spikes.py @@ -0,0 +1,85 @@ +"""Replay selected S1 sample positions with a fixed checkpoint for loss diagnosis.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for +from coverage_sampler import CoverageSampler +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def run(checkpoint: Path, updates: list[int]) -> dict: + state = torch.load(checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S1" or state.get("smoke"): + raise ValueError("diagnostic requires a formal S1 checkpoint") + torch.set_num_threads(2) + device = torch.device("cuda", 0) + model = model_for("S1") + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + criterion = BimanualLoss(LOSS) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + sampler = CoverageSampler(INDEX, "S1_S3") + results = [] + with torch.inference_mode(): + for update in updates: + for position in range((update - 1) * 6, update * 6): + spec = sampler.sample(position) + cpu = collate_h2o_clips([dataset[spec]]) + batch = move_to_device(cpu, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + joint_valid = batch["joint3d_valid"].bool() + reproj_valid = batch["reprojection_valid"].bool() + gt_z = batch["joint3d_camera"][..., 2][joint_valid] + pred_z = prediction["joints_camera"][..., 2][joint_valid] + gt_2d = batch["joint2d"][reproj_valid] + item = { + "update": update, + "position": position, + "source": spec["source"], + "mode": spec["mode"], + "tile_id": spec["tile_id"], + "loss": float(losses["total"]), + "terms": {name: float(value) for name, value in losses.items() + if name != "total" and float(value) != 0}, + "valid_joint_elements": int(joint_valid.sum()), + "valid_reprojection_elements": int(reproj_valid.sum()), + "gt_z_min_max_m": [float(gt_z.min()), float(gt_z.max())] if gt_z.numel() else None, + "pred_z_min_max_m": [float(pred_z.min()), float(pred_z.max())] if pred_z.numel() else None, + "gt_2d_min_max_px": [float(gt_2d.min()), float(gt_2d.max())] + if gt_2d.numel() else None, + "focal_px": [float(batch["K"][0, 0, 0, 0]), float(batch["K"][0, 0, 1, 1])], + } + results.append(item) + return {"checkpoint": str(checkpoint), "checkpoint_update": state["update"], + "sample_count": len(results), "samples": results} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--updates", type=int, nargs="+", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + report = run(args.checkpoint, args.updates) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({"output": str(args.output), "sample_count": report["sample_count"], + "top_losses": sorted(((row["loss"], row["position"], row["source"]) + for row in report["samples"]), reverse=True)[:10]})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_gradient_outliers.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_gradient_outliers.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3f55b373393f1666b75068fe2a9f00adb5a5d0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_gradient_outliers.py @@ -0,0 +1,83 @@ +"""Read-only per-tile gradient probe for registered S2 sample positions.""" + +from __future__ import annotations + +import argparse +import json +import math + +import torch + +from clean_train import ( + INDEX, LOSS, MixedDataset, attach_gt_vertices, collate_h2o_clips, + gradient_group_norms, model_for, move_to_device, +) +from coverage_sampler import CoverageSampler +from foundation_hand.training.losses import BimanualLoss + + +def minimum(values: torch.Tensor, mask: torch.Tensor) -> float | None: + selected = values.detach()[mask] + return float(selected.min()) if selected.numel() else None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--steps", type=int, nargs="+", required=True) + args = parser.parse_args() + + torch.set_num_threads(2) + device = torch.device("cuda:0") + model = model_for("S2").to(device) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S2" or not state["complete_backbone"]: + raise ValueError("expected a full S2 checkpoint") + model.load_state_dict(state["model"], strict=True) + del state + model.train() + criterion = BimanualLoss(LOSS).to(device) + sampler = CoverageSampler(INDEX, "S1_S3") + dataset = MixedDataset(8, (368, 640)) + + for step in args.steps: + if step < 1: + raise ValueError("steps are 1-based") + for rank in range(6): + spec = sampler.sample((step - 1) * 6 + rank) + cpu = collate_h2o_clips([dataset[spec]]) + batch = move_to_device(cpu, device) + attach_gt_vertices(batch, model) + model.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + losses["total"].backward() + groups = gradient_group_norms(model) + + z = prediction["joints_camera"][..., 2].detach() + valid = batch["reprojection_valid"].bool() & (z > 0) + rotation = prediction["mano_rotations_6d"].detach().float() + first = torch.nn.functional.normalize(rotation[..., :3], dim=-1) + second = rotation[..., 3:] + residual = second - (first * second).sum(dim=-1, keepdim=True) * first + report = { + "step": step, + "rank": rank, + "source": spec["source"], + "tile_id": spec["tile_id"], + "mode": spec["mode"], + "loss": float(losses["total"].detach()), + "reprojection_loss": float(losses["reprojection"].detach()), + "grad_norm": math.sqrt(sum(value * value for value in groups.values())), + "grad_groups_top": sorted(groups.items(), key=lambda item: -item[1])[:5], + "min_positive_valid_joint_z_m": minimum(z, valid), + "positive_valid_joint_z_below_1cm": int((valid & (z < .01)).sum()), + "min_rotation_first_norm": float(rotation[..., :3].norm(dim=-1).min()), + "min_rotation_orthogonal_residual_norm": float(residual.norm(dim=-1).min()), + } + print(json.dumps(report), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_initial_gradients.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_initial_gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..4e08e92d1aae8e056f4bd01f0229a09efa660043 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_initial_gradients.py @@ -0,0 +1,90 @@ +"""Measure each weighted loss contribution to the clean-start gradient.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for, sha +from coverage_sampler import CoverageSampler, SOURCES +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def grad_norms(model) -> dict[str, float]: + sums: dict[str, torch.Tensor] = {} + for name, parameter in model.named_parameters(): + if parameter.grad is None: + continue + parts = name.split(".") + group = ".".join(parts[:2]) if parts[0] in ("rgb_encoder", "decoder") else parts[0] + sums[group] = sums.get(group, parameter.grad.new_zeros(())) + parameter.grad.float().square().sum() + return {name: float(value.sqrt()) for name, value in sums.items()} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S1" or state["index_sha256"] != sha(INDEX): + raise ValueError("expected complete S1 checkpoint on trainable index") + torch.cuda.set_device(0) + model = model_for("S1").cuda().train() + model.load_state_dict(state["model"], strict=True) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + sampler = CoverageSampler(INDEX, "S1_S3") + specs = {} + for position in range(200): + spec = sampler.sample(position) + specs.setdefault(spec["source"], spec) + if len(specs) == len(SOURCES): + break + criterion = BimanualLoss(LOSS) + report = {"checkpoint_sha256": sha(args.checkpoint), "samples": {}} + for source, spec in specs.items(): + sample = dataset[spec] + batch = move_to_device(collate_h2o_clips([sample]), torch.device("cuda", 0)) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + losses = criterion(model(batch), batch) + components = {} + for name, value in losses.items(): + if name == "total" or float(value.detach()) == 0.0: + continue + model.zero_grad(set_to_none=True) + value.backward(retain_graph=True) + groups = grad_norms(model) + components[name] = {"weighted_loss": float(value.detach()), + "global_grad_norm": sum(x * x for x in groups.values()) ** .5, + "groups": groups} + model.zero_grad(set_to_none=True) + losses["total"].backward() + groups = grad_norms(model) + report["samples"][source] = { + "tile_id": spec["tile_id"], "mode": spec["mode"], + "total_loss": float(losses["total"].detach()), + "total_grad_norm": sum(x * x for x in groups.values()) ** .5, + "total_groups": groups, "components": components, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({source: { + "total_grad_norm": row["total_grad_norm"], + "largest_components": sorted( + ((name, entry["global_grad_norm"]) for name, entry in row["components"].items()), + key=lambda pair: pair[1], reverse=True, + )[:6], + "total_groups": row["total_groups"], + } for source, row in report["samples"].items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_s1_s2_temporal_transition.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_s1_s2_temporal_transition.py new file mode 100644 index 0000000000000000000000000000000000000000..50fa8bf7a8f13085a4801d5b3286bc098be2ac1a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/diagnose_s1_s2_temporal_transition.py @@ -0,0 +1,85 @@ +"""Measure the temporal block's effect on a frozen staged model.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from clean_train import ROOT, model_for, sha +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--limit", type=int, default=32) + args = parser.parse_args() + if args.limit <= 0 or (args.source != "H2O" and args.mode == "rgb_depth_k"): + raise ValueError("invalid evaluation condition or limit") + + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + manifest = panels / f"{args.source.lower()}_development_t8.jsonl" + if sha(manifest) != panel_report["sources"][args.source]["development"]["manifest_sha256"]: + raise RuntimeError("frozen development panel changed") + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if (state["stage"] not in ("S1", "S2") or state["update"] < 2000 + or state.get("smoke") or not state.get("complete_backbone")): + raise RuntimeError("requires a complete formal S1/S2 checkpoint") + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + dataset = dataset_for(args.source, manifest) + limit = min(args.limit, len(dataset)) + rows = {False: [], True: []} + with torch.inference_mode(): + for index in range(limit): + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + for temporal_enabled in (False, True): + model.decoder.temporal_enabled = temporal_enabled + with torch.autocast(device.type, dtype=torch.bfloat16, + enabled=device.type == "cuda"): + prediction = model(batch) + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows[temporal_enabled].append( + make_row(prediction, batch, 0, frame, side) + ) + + summaries = {condition: aggregate(values) for condition, values in rows.items()} + counts_match = all( + summaries[False][metric]["count"] == summaries[True][metric]["count"] + for metric in FOUR_METRICS + ) + if not counts_match: + raise RuntimeError("temporal toggle changed metric denominators") + report = { + "checkpoint_sha256": sha(args.checkpoint), + "checkpoint_stage": state["stage"], "checkpoint_update": state["update"], + "source": args.source, "mode": args.mode, "clips": limit, + "temporal_off": {metric: summaries[False][metric] for metric in FOUR_METRICS}, + "temporal_on": {metric: summaries[True][metric] for metric in FOUR_METRICS}, + "temporal_on_minus_off": { + metric: summaries[True][metric]["mean"] - summaries[False][metric]["mean"] + for metric in FOUR_METRICS + }, + } + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/eval_stratified_probe.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/eval_stratified_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..12e100450b2927f5f87f73686250de0a6ef0a932 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/eval_stratified_probe.py @@ -0,0 +1,195 @@ +"""Evaluate fixed, recording-spread development clips without checkpoint selection.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +import math +from pathlib import Path + +import torch + +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from clean_train import INDEX, ROOT, model_for, sha, training_code_hashes +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def choose_indices(manifest: Path, limit: int) -> tuple[list[int], int]: + groups: dict[str, list[int]] = defaultdict(list) + with manifest.open() as stream: + for index, line in enumerate(stream): + row = json.loads(line) + group = row.get("take", row.get("group_key")) + if not group: + raise ValueError(f"manifest row {index} has no recording group") + groups[str(group)].append(index) + if limit < len(groups): + raise ValueError("limit must include at least one clip per recording group") + + ordered: dict[str, list[int]] = {} + for group, indices in groups.items(): + size = len(indices) + priorities = [size // 2, size // 4, 3 * size // 4, 0, size - 1] + offsets = list(dict.fromkeys(priorities + list(range(size)))) + ordered[group] = [indices[offset] for offset in offsets] + + selected: list[int] = [] + for depth in range(max(map(len, ordered.values()))): + for group in sorted(ordered): + if depth < len(ordered[group]): + selected.append(ordered[group][depth]) + if len(selected) == limit: + return selected, len(groups) + raise ValueError("limit exceeds manifest length") + + +def paired_group_deltas(reference: list[dict], candidate: list[dict], field: str) -> dict: + if len(reference) != len(candidate): + raise RuntimeError("paired evaluations have different row counts") + groups: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for first, second in zip(reference, candidate): + if first[field] != second[field]: + raise RuntimeError(f"paired {field} identities differ") + for name in FOUR_METRICS: + first_value, second_value = float(first[name]), float(second[name]) + if math.isfinite(first_value) != math.isfinite(second_value): + raise RuntimeError(f"paired {name} validity differs for {field}={first[field]}") + if math.isfinite(first_value): + groups[str(first[field])][name].append(second_value - first_value) + return { + group: { + name: {"count": len(values), "mean_delta": sum(values) / len(values)} + for name, values in metrics.items() + } + for group, metrics in sorted(groups.items()) + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--compare-checkpoint", type=Path) + parser.add_argument("--reference-temporal-off", action="store_true") + parser.add_argument("--compare-temporal-off", action="store_true") + parser.add_argument("--paired-groups", action="store_true") + parser.add_argument("--hybrid-parent-root", action="store_true") + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--limit", type=int, default=32) + args = parser.parse_args() + if args.source != "H2O" and args.mode == "rgb_depth_k": + raise ValueError("only H2O has real metric depth") + if args.compare_temporal_off and not args.compare_checkpoint: + raise ValueError("--compare-temporal-off requires --compare-checkpoint") + if args.paired_groups and not args.compare_checkpoint: + raise ValueError("--paired-groups requires --compare-checkpoint") + if args.hybrid_parent_root and not args.compare_checkpoint: + raise ValueError("--hybrid-parent-root requires --compare-checkpoint") + + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + manifest = panels / f"{args.source.lower()}_development_t8.jsonl" + expected = panel_report["sources"][args.source]["development"]["manifest_sha256"] + if sha(manifest) != expected: + raise RuntimeError("frozen development panel changed") + dataset = dataset_for(args.source, manifest) + indices, groups = choose_indices(manifest, args.limit) + if len(dataset) != sum(1 for _ in manifest.open()): + raise RuntimeError("dataset indices differ from frozen manifest rows") + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + checkpoints = [args.checkpoint] + if args.compare_checkpoint: + checkpoints.append(args.compare_checkpoint) + models = [] + identities = [] + for model_index, path in enumerate(checkpoints): + state = torch.load(path, map_location="cpu", weights_only=False) + if (state.get("smoke") or not state.get("complete_backbone") + or state["index_sha256"] != sha(INDEX) + or state["code_sha256"] != training_code_hashes()): + raise RuntimeError(f"checkpoint is not a complete matching formal state: {path}") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + if ((model_index == 0 and args.reference_temporal_off) + or (model_index == 1 and args.compare_temporal_off)): + model.decoder.temporal_enabled = False + models.append(model.to(device).eval()) + identities.append({ + "checkpoint_sha256": sha(path), "stage": state["stage"], + "update": state["update"], + "temporal_enabled": bool(model.decoder.temporal_enabled), + }) + if args.hybrid_parent_root: + identities.append({ + **identities[1], "variant": "compare_local_reference_root", + "root_checkpoint_sha256": identities[0]["checkpoint_sha256"], + }) + rows = [[] for _ in identities] + with torch.inference_mode(): + for index in indices: + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, models[0]) + predictions = [] + for model in models: + with torch.autocast(device.type, dtype=torch.bfloat16, + enabled=device.type == "cuda"): + predictions.append(model(batch)) + if args.hybrid_parent_root: + parent, candidate = predictions + delta = parent["wrist_root_translation"] - candidate["wrist_root_translation"] + hybrid = dict(candidate) + hybrid["wrist_root_translation"] = parent["wrist_root_translation"] + hybrid["joints_camera"] = candidate["joints_camera"] + delta.unsqueeze(-2) + hybrid["vertices_camera"] = candidate["vertices_camera"] + delta.unsqueeze(-2) + predictions.append(hybrid) + for model_index, prediction in enumerate(predictions): + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows[model_index].append( + make_row(prediction, batch, 0, frame, side) + ) + summaries = [aggregate(values) for values in rows] + if any(summary[name]["count"] == 0 for summary in summaries for name in FOUR_METRICS): + raise RuntimeError("stratified probe has an empty metric denominator") + if len(summaries) >= 2 and any( + summaries[0][name]["count"] != summary[name]["count"] + for summary in summaries[1:] for name in FOUR_METRICS + ): + raise RuntimeError("paired checkpoints have different metric denominators") + if args.hybrid_parent_root: + paired_group_deltas(rows[0], rows[2], "physical_recording_id") + print(json.dumps({ + "source": args.source, "mode": args.mode, + "panel_sha256": expected, "selection": "recording_round_robin_center", + "selected_indices": indices, "recording_groups": groups, + "results": [ + {**identity, "four_metrics": {name: summary[name] for name in FOUR_METRICS}} + for identity, summary in zip(identities, summaries) + ], + "compare_minus_reference": { + name: summaries[1][name]["mean"] - summaries[0][name]["mean"] + for name in FOUR_METRICS + } if len(summaries) >= 2 else None, + "hybrid_minus_reference": { + name: summaries[2][name]["mean"] - summaries[0][name]["mean"] + for name in FOUR_METRICS + } if args.hybrid_parent_root else None, + "hybrid_minus_compare": { + name: summaries[2][name]["mean"] - summaries[1][name]["mean"] + for name in FOUR_METRICS + } if args.hybrid_parent_root else None, + "paired_groups": { + "headset": paired_group_deltas(rows[0], rows[1], "headset_id"), + "recording": paired_group_deltas(rows[0], rows[1], "physical_recording_id"), + } if args.paired_groups else None, + }, separators=(",", ":"))) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/export_adapter_manifests.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/export_adapter_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..7120aeaf9b953c4f5a4a3ad64ee3c5deaaa3d5d9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/export_adapter_manifests.py @@ -0,0 +1,94 @@ +"""Translate frozen filtered tiles to the three existing native source adapters.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sqlite3 + + +def adapter_row(window: dict, tile_id: str, start: int, frames: list[int], time: int) -> dict: + dataset = window["dataset"] + source = window["source"] + selected = frames if time == 8 else [frames[0]] + shared = { + "filtered_tile_id": tile_id, + "filtered_window_id": window["id"], + "filtered_gt_path": window["filtered_gt_path"], + "filtered_start_offset": start, + "expected_frame_ids": selected, + } + if dataset == "ARCTIC": + offset = int(source["offset"]) + subject = window["recording_id"].split("/")[0] + return { + **shared, "dataset_id": "ARCTIC", "protocol": "P2", + "split_role": "arctic_p2_train", "subject_id": subject, + "physical_recording_id": window["recording_id"], + "group_key": f"ARCTIC/{subject}/{window['recording_id']}", + "camera_id": "ego_view_0_rectified", + "frame_ids_1based": selected, + "array_indices_0based": [frame - offset for frame in selected], + "image_paths": [source["rgb_template"].format(frame=frame) for frame in selected], + "mano_path": source["mano_path"], "camera_path": source["camera_path"], + "depth_input_available": False, "official_test_used": False, + } + if dataset == "H2O": + return {**shared, "take": window["recording_id"], "frame_ids": selected} + if dataset == "HOT3D": + path = Path(window["recording_id"]) + return { + **shared, "dataset": "HOT3D", "have_hand_object_pose_gt": True, + "recording_id": window["recording_id"], "participant_id": path.name.split("_")[0], + "stream_id": window["stream_id"], "headset": source["device"], + "timestamps_ns": window["_timestamps_ns"][start:start + len(selected)], + } + raise ValueError(f"foreign source {dataset}") + + +def export(index: Path, output: Path, time: int) -> dict[str, int]: + if time not in (1, 8): + raise ValueError("only T=1 and T=8 are registered") + output.mkdir(parents=True, exist_ok=False) + counts = {name: 0 for name in ("ARCTIC", "H2O", "HOT3D")} + files = {name: (output / f"{name.lower()}_t{time}.jsonl").open("w") for name in counts} + last_window = None + window = None + try: + with sqlite3.connect(index) as connection: + cursor = connection.execute( + "SELECT t.tile_id,t.window_id,t.source,t.start_offset,t.frame_ids_json," + "w.manifest_json FROM tiles t JOIN windows w ON t.window_id=w.window_id " + "ORDER BY t.source,t.window_id,t.start_offset" + ) + for tile_id, window_id, source_name, start, frames_json, manifest_json in cursor: + if window_id != last_window: + window = json.loads(manifest_json) + if source_name == "HOT3D": + timeline = json.loads(Path(window["source"]["timestamps_path"]).read_text()) + window["_timestamps_ns"] = timeline[str(window["stream_id"])][ + int(window["start"]):int(window["end"]) + ] + last_window = window_id + assert window is not None + row = adapter_row(window, tile_id, start, json.loads(frames_json), time) + files[source_name].write(json.dumps(row, separators=(",", ":")) + "\n") + counts[source_name] += 1 + finally: + for handle in files.values(): + handle.close() + return counts + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--index", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--time", type=int, choices=(1, 8), required=True) + args = parser.parse_args() + print(json.dumps(export(args.index, args.output, args.time), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/filtered_dataset.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/filtered_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..ab36aee3e3c74559a40f03ce185464476858cd67 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/filtered_dataset.py @@ -0,0 +1,138 @@ +"""Use native source decoders while enforcing the frozen filtered-GT allowlist.""" + +from __future__ import annotations + +from functools import lru_cache +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS, corrupt_metric_depth +from foundation_hand.data.h2o_dataset import H2OCam4Dataset +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + +from coverage_sampler import _seed + + +@lru_cache(maxsize=256) +def filtered_valid(gt_path: str) -> tuple[np.ndarray, np.ndarray]: + with np.load(gt_path, allow_pickle=False) as payload: + return payload["frame_ids"].copy(), payload["valid"].astype(bool).copy() + + +MASKS = ( + "joint_element_valid", "joint_annotation_valid", "mano_annotation_valid", + "joint2d_valid", "joint3d_valid", "joint3d_root_relative_valid", + "translation_valid", "mano_pose_valid", "shape_valid", "vertices_valid", + "reprojection_valid", +) + + +def intersect_filtered_valid(sample: dict[str, Any], row: dict[str, Any]) -> None: + frame_ids, valid = filtered_valid(str(row["filtered_gt_path"])) + start = int(row["filtered_start_offset"]) + time = len(row["expected_frame_ids"]) + expected = np.asarray(row["expected_frame_ids"], dtype=np.int64) + if not np.array_equal(frame_ids[start:start + time], expected): + raise ValueError(f"filtered/native frame disagreement: {row['filtered_tile_id']}") + if sample["dataset_id"] == "HOT3D": + if not torch.equal(sample["timestamp_ns"], torch.as_tensor(row["timestamps_ns"])): + raise ValueError("HOT3D image and GT timeline disagree") + elif not torch.equal(sample["frame_id"], torch.from_numpy(expected)): + raise ValueError("image and filtered GT frame IDs disagree") + hand = torch.from_numpy(valid[start:start + time]).bool() + if hand.shape != (time, 2): + raise ValueError("filtered hand validity has wrong shape") + for key in MASKS: + if key not in sample: + continue + mask = sample[key] + if mask.shape[:2] != (time, 2) or mask.dtype != torch.bool: + raise ValueError(f"invalid native loss mask {key}: {mask.shape}") + expanded = hand + while expanded.ndim < mask.ndim: + expanded = expanded.unsqueeze(-1) + sample[key] = mask & expanded + + +class FilteredClipDataset(Dataset[dict[str, Any]]): + def __init__( + self, source: str, manifest: str | Path, time: int, target_hw: tuple[int, int], + mano_root: str | Path, hot3d_toolkit: str | Path, + photometric_augmentation: dict | None = None, + ) -> None: + self.source = source + self.rows = [json.loads(line) for line in Path(manifest).open() if line.strip()] + self.by_tile = {str(row["filtered_tile_id"]): index for index, row in enumerate(self.rows)} + if len(self.by_tile) != len(self.rows): + raise ValueError("duplicate filtered tile ID") + if source == "ARCTIC": + self.native = ARCTICClipDataset( + manifest, mano_root, target_hw, photometric_augmentation, 20260925, + hand_valid_policy="visible_mesh", + ) + elif source == "H2O": + self.native = H2OCam4Dataset( + "/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, target_hw, + clip_lengths=(time,), strides=(1,), window_step=time, + allow_partial=False, photometric_augmentation=photometric_augmentation, + augmentation_seed=20260925, + ) + elif source == "HOT3D": + self.native = HOT3DClipDataset( + "/SSD3/jiasen/foundation_hand/HOT3D/dataset", manifest, + hot3d_toolkit, mano_root, target_hw, K_input_dropout=0.0, + ) + else: + raise ValueError(f"foreign source {source}") + if len(self.native) != len(self.rows): + raise ValueError("native adapter clip count differs from filtered index") + + def __len__(self) -> int: + return len(self.rows) + + def __getitem__(self, spec: dict[str, Any]) -> dict[str, Any]: + if spec["source"] != self.source: + raise ValueError("sample source differs from native adapter") + index = self.by_tile[str(spec["tile_id"])] + row = self.rows[index] + sample = self.native[(index, int(spec["epoch"]))] + intersect_filtered_valid(sample, row) + frame = sample["frame_valid"].bool() + mode = str(spec["mode"]) + if mode not in ("rgb", "rgb_k", "rgb_depth_k"): + raise ValueError(f"foreign input mode {mode}") + if mode == "rgb_depth_k" and self.source != "H2O": + raise ValueError("only H2O supplies real metric depth") + sample["K_input_available"] = frame & (mode != "rgb") + sample["depth_input_available"] = frame & (mode == "rgb_depth_k") + sample["K_available"] = sample["K_input_available"].clone() + sample["depth_available"] = sample["depth_input_available"].clone() + condition_code = 2 if mode == "rgb_depth_k" else 1 if self.source == "H2O" else 0 + if self.source == "H2O" and mode == "rgb_depth_k": + import random + position = int(spec["position"]) + rng = random.Random(_seed(20260925, "depth", position)) + if rng.random() < .30: + corruption = DEPTH_CORRUPTIONS[rng.randrange(len(DEPTH_CORRUPTIONS))] + depth, pixel_valid = corrupt_metric_depth( + sample["depth_m"].numpy(), sample["depth_pixel_valid"].numpy(), + corruption, seed=_seed(20260925, "corruption", position), + ) + sample["depth_m"] = torch.from_numpy(depth) + sample["depth_pixel_valid"] = torch.from_numpy(pixel_valid) + condition_code = 3 + DEPTH_CORRUPTIONS.index(corruption) + sample["depth_input_condition_code"] = torch.full( + frame.shape, condition_code, dtype=torch.long, + ) + sample["sampling_source_id"] = self.source + sample["filtered_tile_id"] = row["filtered_tile_id"] + sample["input_mode"] = mode + sample["source_ordinal"] = torch.full(frame.shape, int(spec["source_ordinal"]), dtype=torch.long) + sample["coverage_epoch"] = torch.full(frame.shape, int(spec["epoch"]), dtype=torch.long) + return sample diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/freeze_eval_panels.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/freeze_eval_panels.py new file mode 100644 index 0000000000000000000000000000000000000000..d84948d25345cda0de302ae204eaacf2a742d860 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/freeze_eval_panels.py @@ -0,0 +1,139 @@ +"""Freeze recording-disjoint development and confirmation GT panels.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path + +import numpy as np + +from audit_headset_sync import MAX_DELTA_NS, deltas, trajectory +from preflight_index import digest, tile_starts, EXPECTED_MANIFEST_SHA256 + + +SOURCES = { + "ARCTIC": Path("/SSD3/jiasen/foundation_hand/phase7_artifacts/manifests/arctic_p2_v2/arctic_p2_val_t8.jsonl"), + "H2O": Path("/SSD3/jiasen/foundation_hand/H2O/extracted/label_split/pose_val.txt"), + "HOT3D": Path("/SSD3/jiasen/foundation_hand/phase7_artifacts/manifests/hot3d_gt_v1_retry2/hot3d_heldout_t8.jsonl"), +} + + +def h2o_rows(path: Path) -> list[dict]: + by_take: dict[str, set[int]] = defaultdict(set) + for line in path.open(): + item = Path(line.strip()) + if not line.strip(): + continue + take = str(item.parents[1]) + if not take.endswith("cam4"): + raise ValueError(f"foreign H2O validation view {take}") + by_take[take].add(int(item.stem)) + rows = [] + for take, values in by_take.items(): + ids = sorted(values) + start = 0 + for position in range(1, len(ids) + 1): + if position < len(ids) and ids[position] == ids[position - 1] + 1: + continue + run = ids[start:position] + if len(run) >= 8: + for offset in tile_starts(len(run)): + rows.append({"take": take, "frame_ids": run[offset:offset + 8]}) + start = position + return rows + + +def load_jsonl(path: Path) -> list[dict]: + return [json.loads(line) for line in path.open() if line.strip()] + + +def recording(source: str, row: dict) -> str: + return row["take"] if source == "H2O" else row[ + "physical_recording_id" if source == "ARCTIC" else "recording_id" + ] + + +def clip_time(source: str, row: dict) -> int: + key = "frame_ids" if source == "H2O" else "frame_ids_1based" if source == "ARCTIC" else "timestamps_ns" + return int(row[key][0]) + + +def hot3d_headset_valid(row: dict) -> bool: + path = Path("/SSD3/jiasen/foundation_hand/HOT3D/dataset") / row["recording_id"] + stamps = np.asarray(row["timestamps_ns"], dtype=np.int64) + return bool(np.all(deltas(stamps, trajectory(str(path))) <= MAX_DELTA_NS)) + + +def freeze(train_manifest: Path, output: Path, per_recording: int = 8) -> dict: + if digest(train_manifest) != EXPECTED_MANIFEST_SHA256: + raise ValueError("training manifest differs from frozen allowlist") + if output.exists(): + raise FileExistsError(output) + train_recordings: dict[str, set[str]] = defaultdict(set) + for row in load_jsonl(train_manifest): + train_recordings[row["dataset"]].add(row["recording_id"]) + rows = { + "H2O": h2o_rows(SOURCES["H2O"]), + "ARCTIC": load_jsonl(SOURCES["ARCTIC"]), + "HOT3D": load_jsonl(SOURCES["HOT3D"]), + } + hot3d_total = len(rows["HOT3D"]) + rows["HOT3D"] = [row for row in rows["HOT3D"] if hot3d_headset_valid(row)] + plan: dict[str, dict] = {} + selected: dict[tuple[str, str], list[dict]] = {} + for source, values in rows.items(): + groups: dict[str, list[dict]] = defaultdict(list) + for row in values: + groups[recording(source, row)].append(row) + if train_recordings[source] & set(groups): + raise ValueError(f"{source} validation overlaps filtered train recordings") + ranked = sorted(groups, key=lambda name: hashlib.sha256( + f"clean-gt-eval-20260925|{source}|{name}".encode(), + ).digest()) + if len(ranked) < 2: + raise ValueError(f"{source} lacks disjoint validation recordings") + boundary = len(ranked) // 2 + plan[source] = {"train_recordings": len(train_recordings[source]), + "validation_recordings": len(ranked), "train_overlap": 0, + "source_sha256": digest(SOURCES[source])} + if source == "HOT3D": + plan[source]["candidate_clips"] = hot3d_total + plan[source]["clips_rejected_headset_sync"] = hot3d_total - len(values) + plan[source]["headset_sync_threshold_ms"] = MAX_DELTA_NS / 1e6 + for role, names in (("development", ranked[:boundary]), ("confirmation", ranked[boundary:])): + chosen = [] + for name in names: + candidates = sorted(groups[name], key=lambda row: clip_time(source, row)) + indices = np.linspace(0, len(candidates) - 1, + min(per_recording, len(candidates)), dtype=int) + chosen.extend(candidates[int(index)] for index in indices) + selected[source, role] = chosen + plan[source][role] = {"recordings": len(names), "clips": len(chosen), + "recording_ids": names} + output.mkdir(parents=True) + for (source, role), values in selected.items(): + path = output / f"{source.lower()}_{role}_t8.jsonl" + with path.open("w") as stream: + for row in values: + stream.write(json.dumps(row, separators=(",", ":")) + "\n") + plan[source][role]["manifest_sha256"] = digest(path) + report = {"status": "frozen", "train_manifest_sha256": EXPECTED_MANIFEST_SHA256, + "rule": "recording-disjoint, 8 spread T8 clips per recording; confirmation unopened for selection", + "sources": plan} + (output / "panels.json").write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--train-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(freeze(args.train_manifest, args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/preflight_index.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/preflight_index.py new file mode 100644 index 0000000000000000000000000000000000000000..f5153a5cd84d39d0fd4e5779d33ab123eb1f11de --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/preflight_index.py @@ -0,0 +1,195 @@ +"""Audit the filtered GT allowlist and build a complete, immutable T=8 index. + +The index contains references only. It never copies or decodes source images. +""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +import os +from pathlib import Path +import sqlite3 + +import numpy as np + + +EXPECTED_MANIFEST_SHA256 = "b4b0ac4bc4a771c9bc7626a9eec7f5f541ef96908a9a64d219192efd7b8f7f89" +EXPECTED_WINDOWS = {"ARCTIC": 2939, "H2O": 928, "HOT3D": 18962} +EXPECTED_TILES = {"ARCTIC": 22750, "H2O": 6406, "HOT3D": 143930} + + +def digest(path: Path) -> str: + value = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(4 * 1024 * 1024), b""): + value.update(block) + return value.hexdigest() + + +def tile_starts(length: int, tile_size: int = 8) -> list[int]: + if length < tile_size: + raise ValueError(f"window has only {length} frames") + starts = list(range(0, length - tile_size + 1, tile_size)) + if starts[-1] + tile_size < length: + starts.append(length - tile_size) + covered = set().union(*(range(start, start + tile_size) for start in starts)) + if covered != set(range(length)): + raise AssertionError(f"tile coverage incomplete for length={length}") + return starts + + +def source_frame_paths(row: dict, frame_ids: np.ndarray) -> list[Path]: + source = row["source"] + if row["dataset"] == "HOT3D": + return [Path(source["root"]), Path(source["timestamps_path"])] + template = str(source["rgb_template"]) + paths = [Path(template.format(frame=int(frame_id))) for frame_id in frame_ids] + if row["dataset"] == "H2O": + root = Path(source["root"]) + paths += [root / "depth" / f"{int(frame_id):06d}.png" for frame_id in frame_ids] + paths += [root / "hand_pose" / f"{int(frame_id):06d}.txt" for frame_id in frame_ids] + paths += [root / "hand_pose_mano" / f"{int(frame_id):06d}.txt" for frame_id in frame_ids] + paths.append(root / "cam_intrinsics.txt") + elif row["dataset"] == "ARCTIC": + paths += [Path(source["mano_path"]), Path(source["camera_path"])] + return paths + + +def audit_window(row: dict, check_paths: bool) -> tuple[np.ndarray, np.ndarray, list[int]]: + if row.get("retained") is not True or row.get("filter_reason") != "retained": + raise ValueError("window is not retained") + name = row["dataset"] + if name not in EXPECTED_WINDOWS: + raise ValueError(f"foreign dataset {name}") + gt = Path(row["filtered_gt_path"]) + if not gt.is_file() or digest(gt) != row["gt_sha256"]: + raise ValueError(f"GT missing or hash mismatch: {gt}") + with np.load(gt, allow_pickle=False) as payload: + if "frame_ids" not in payload or "valid" not in payload: + raise ValueError("GT lacks frame_ids or valid") + frame_ids = payload["frame_ids"].astype(np.int64) + valid = payload["valid"].astype(bool) + if valid.shape != (len(frame_ids), 2): + raise ValueError(f"invalid hand mask shape {valid.shape}") + if name == "H2O" and "joints_native_m" not in payload: + raise ValueError("H2O lacks native joints") + length = int(row["frame_count"]) + if length != len(frame_ids) or length != int(row["end"]) - int(row["start"]): + raise ValueError("manifest/GT length disagreement") + if np.any(np.diff(frame_ids) <= 0): + raise ValueError("native frame IDs are not strictly increasing") + if name == "ARCTIC": + offset = int(row["source"]["offset"]) + if offset < 1 or not np.array_equal( + frame_ids, np.arange(int(row["start"]) + offset, int(row["end"]) + offset) + ): + raise ValueError("ARCTIC frame IDs disagree with registered sequence offset") + if name == "HOT3D": + timeline_path = Path(row["source"]["timestamps_path"]) + if not timeline_path.is_file(): + raise ValueError("HOT3D timeline is missing") + timeline = json.loads(timeline_path.read_text(encoding="utf-8")) + timestamps = timeline[str(row["stream_id"])][int(row["start"]):int(row["end"])] + if len(timestamps) != length: + raise ValueError("HOT3D timeline slice length mismatch") + if check_paths: + missing = next((str(path) for path in source_frame_paths(row, frame_ids) if not path.is_file() and not path.is_dir()), None) + if missing: + raise FileNotFoundError(missing) + return frame_ids, valid, tile_starts(length) + + +def build(manifest: Path, output: Path, check_paths: bool = True) -> dict: + if digest(manifest) != EXPECTED_MANIFEST_SHA256: + raise ValueError("filtered manifest SHA256 differs from frozen recipe") + if output.exists(): + raise FileExistsError(f"refusing to overwrite index: {output}") + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_suffix(output.suffix + ".tmp") + if temporary.exists(): + raise FileExistsError(f"unfinished index already exists: {temporary}") + connection = sqlite3.connect(temporary) + try: + connection.executescript(""" + CREATE TABLE windows ( + window_id TEXT PRIMARY KEY, source TEXT NOT NULL, + recording_id TEXT NOT NULL, stream_id TEXT, + manifest_json TEXT NOT NULL, frame_ids_json TEXT NOT NULL, + valid_left INTEGER NOT NULL, valid_right INTEGER NOT NULL + ); + CREATE TABLE tiles ( + tile_id TEXT PRIMARY KEY, window_id TEXT NOT NULL, + source TEXT NOT NULL, recording_id TEXT NOT NULL, + start_offset INTEGER NOT NULL, frame_ids_json TEXT NOT NULL, + FOREIGN KEY(window_id) REFERENCES windows(window_id) + ); + CREATE INDEX tiles_source_recording ON tiles(source, recording_id); + """) + windows: Counter[str] = Counter() + tiles: Counter[str] = Counter() + frame_entries: Counter[str] = Counter() + valid_hands: Counter[str] = Counter() + recordings: dict[str, set[str]] = {name: set() for name in EXPECTED_WINDOWS} + for line_number, line in enumerate(manifest.open(encoding="utf-8"), 1): + if not line.strip(): + continue + row = json.loads(line) + try: + frame_ids, valid, starts = audit_window(row, check_paths) + name = row["dataset"] + window_id = str(row["id"]) + recording_id = str(row["recording_id"]) + connection.execute( + "INSERT INTO windows VALUES (?,?,?,?,?,?,?,?)", + (window_id, name, recording_id, row.get("stream_id"), + json.dumps(row, separators=(",", ":")), + json.dumps(frame_ids.tolist()), int(valid[:, 0].sum()), int(valid[:, 1].sum())), + ) + for start in starts: + selected = frame_ids[start:start + 8].tolist() + connection.execute( + "INSERT INTO tiles VALUES (?,?,?,?,?,?)", + (f"{window_id}:{start}", window_id, name, recording_id, + start, json.dumps(selected)), + ) + windows[name] += 1 + tiles[name] += len(starts) + frame_entries[name] += len(frame_ids) + valid_hands[f"{name}:left"] += int(valid[:, 0].sum()) + valid_hands[f"{name}:right"] += int(valid[:, 1].sum()) + recordings[name].add(recording_id) + except Exception as error: + raise ValueError(f"manifest line {line_number}, id={row.get('id')}: {error}") from error + if dict(windows) != EXPECTED_WINDOWS or dict(tiles) != EXPECTED_TILES: + raise ValueError(f"coverage counts differ: windows={windows}, tiles={tiles}") + connection.commit() + except BaseException: + connection.close() + temporary.unlink(missing_ok=True) + raise + connection.close() + os.replace(temporary, output) + return { + "status": "pass", "manifest_sha256": EXPECTED_MANIFEST_SHA256, + "index_sha256": digest(output), "windows": dict(windows), + "tiles": dict(tiles), "frame_entries": dict(frame_entries), + "valid_hands": dict(valid_hands), + "recordings": {name: len(values) for name, values in recordings.items()}, + "source_paths_checked": check_paths, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--skip-source-paths", action="store_true") + args = parser.parse_args() + print(json.dumps(build(args.manifest, args.output, not args.skip_source_paths), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/probe_cold_start.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/probe_cold_start.py new file mode 100644 index 0000000000000000000000000000000000000000..6344fe0a91a9615173f3021e4df3437da404629e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/probe_cold_start.py @@ -0,0 +1,95 @@ +"""Compare cold-start gradient flow without changing data, loss, or LR.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch +from torch import nn + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for +from coverage_sampler import CoverageSampler, SOURCES +from diagnose_initial_gradients import grad_norms +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +VARIANTS = ( + ("zero_heads_zero_depth", 0.0, 0.0), + ("head_1e-2_zero_depth", 1e-2, 0.0), + ("head_1e-2_depth_1e-4", 1e-2, 1e-4), + ("head_5e-3_depth_1e-3", 5e-3, 1e-3), + ("head_1e-3_depth_1e-3", 1e-3, 1e-3), +) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + coverage = CoverageSampler(INDEX, "S1_S3") + specs = {} + for position in range(200): + spec = coverage.sample(position) + specs.setdefault(spec["source"], spec) + if len(specs) == len(SOURCES): + break + device = torch.device("cuda", 0) + batches = { + source: move_to_device(collate_h2o_clips([dataset[spec]]), device) + for source, spec in specs.items() + } + criterion = BimanualLoss(LOSS) + results = [] + for name, head_std, depth_std in VARIANTS: + torch.manual_seed(20260925) + model = model_for("S1") + with torch.no_grad(): + for head in ( + model.joint2d_head, model.rotation_head, + model.translation_head, model.shape_head, + ): + if head_std: + nn.init.normal_(head.weight, std=head_std) + else: + nn.init.zeros_(head.weight) + final_depth = model.depth_encoder.encoder[-1] + if depth_std: + nn.init.normal_(final_depth.weight, std=depth_std) + else: + nn.init.zeros_(final_depth.weight) + model.to(device).train() + item = {"variant": name, "head_std": head_std, "depth_std": depth_std, + "samples": {}} + for source, batch in batches.items(): + model.zero_grad(set_to_none=True) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + losses = criterion(model(batch), batch) + losses["total"].backward() + groups = grad_norms(model) + item["samples"][source] = { + "mode": specs[source]["mode"], + "loss": float(losses["total"].detach()), + "grad_norm": sum(x * x for x in groups.values()) ** .5, + "decoder_grad": groups.get("decoder.spatial", 0.0), + "projection_grad": groups.get("rgb_encoder.projection", 0.0), + "depth_grad": groups.get("depth_encoder", 0.0), + "translation_head_grad": groups.get("translation_head", 0.0), + } + results.append(item) + del model + torch.cuda.empty_cache() + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(results, indent=2) + "\n") + print(json.dumps(results, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/run_formal_stages.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/run_formal_stages.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd55afacfa5d7d36a86318e62b0f4edd6bf4a47 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/run_formal_stages.py @@ -0,0 +1,186 @@ +"""Continue the registered six-GPU clean-GT stages after the S1 health gate.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import subprocess +import time + + +ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925") +CODE = ROOT / "code" +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +CHECKPOINTS = ROOT / "checkpoints" +LOGS = ROOT / "logs" +EVAL = ROOT / "eval" +RUN_TAG = "formal_v3" +S1_HEALTH_PIDFILE = LOGS / f"{RUN_TAG}_s1_health2k.pid" +S1_PIDFILE = LOGS / f"{RUN_TAG}_s1_full.pid" +ENDPOINTS = {"S1": 16667, "S2": 50000, "S3": 83334, "S4": 66667} +MODES = { + "H2O": ("rgb", "rgb_k", "rgb_depth_k"), + "ARCTIC": ("rgb", "rgb_k"), + "HOT3D": ("rgb", "rgb_k"), +} + + +def checksum(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def state(event: str, **details: object) -> None: + payload = {"event": event, "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S%z"), **details} + path = LOGS / f"{RUN_TAG}_controller_state.json" + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n") + temporary.replace(path) + print(json.dumps(payload), flush=True) + + +def endpoint(stage: str, update: int) -> Path: + return CHECKPOINTS / f"{RUN_TAG}_{stage.lower()}" / f"{stage.lower()}_update_{update:07d}.pt" + + +def process_running(pidfile: Path) -> bool: + if not pidfile.exists(): + return False + return subprocess.run( + ["start-stop-daemon", "--status", "--pidfile", str(pidfile)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, + ).returncode == 0 + + +def wait_for_s1_health() -> None: + target = endpoint("S1", 2000) + deadline = time.monotonic() + 3 * 3600 + if not process_running(S1_HEALTH_PIDFILE) and not target.is_file(): + raise RuntimeError("S1 health process is absent without a complete endpoint") + while process_running(S1_HEALTH_PIDFILE): + if time.monotonic() > deadline: + raise TimeoutError("S1 health exceeded its three-hour watchdog") + time.sleep(30) + if not target.is_file(): + raise RuntimeError("S1 health stopped without its complete formal endpoint") + + +def run_logged(command: list[str], log: Path) -> None: + if log.exists(): + raise FileExistsError(f"refusing to overwrite an existing run log: {log}") + print(json.dumps({"run": command, "log": str(log)}), flush=True) + with log.open("xb") as stream: + result = subprocess.run(command, cwd=CODE, stdout=stream, stderr=subprocess.STDOUT, + check=False) + if result.returncode != 0: + raise RuntimeError(f"command exited {result.returncode}; inspect {log}") + + +def audit(stage: str, update: int) -> dict: + target = endpoint(stage, update) + report_path = LOGS / f"{RUN_TAG}_{stage.lower()}_{update:07d}_audit.json" + if report_path.exists(): + report = json.loads(report_path.read_text()) + if report["status"] != "pass" or report["checkpoint_sha256"] != checksum(target): + raise RuntimeError(f"stale or failed endpoint audit: {report_path}") + else: + run_logged([ + PYTHON, str(CODE / "audit_formal_stage.py"), + "--checkpoint", str(target), + "--metrics", str(target.parent / "metrics.jsonl"), + "--stage", stage, "--update", str(update), + "--output", str(report_path), + ], LOGS / f"{RUN_TAG}_{stage.lower()}_{update:07d}_audit.console.log") + report = json.loads(report_path.read_text()) + if report["status"] != "pass": + raise RuntimeError(f"endpoint audit failed: {report_path}") + if update == 2000 and report["last_window_loss_mean"] > 2 * report["first_window_loss_mean"]: + raise RuntimeError(f"early-stage loss grew more than twofold: {report_path}") + state("audited", stage=stage, update=update, checkpoint_sha256=report["checkpoint_sha256"]) + return report + + +def train(stage: str, update: int, previous: Path) -> Path: + target = endpoint(stage, update) + if target.is_file(): + audit(stage, update) + return target + output = target.parent + command = [ + PYTHON, "-m", "torch.distributed.run", "--standalone", "--nproc_per_node=6", + "clean_train.py", "--stage", stage, "--output", str(output), + "--updates", str(update), "--workers", "2", "--save", + ] + if update == 2000: + if output.exists(): + raise FileExistsError(f"uncompleted formal stage requires diagnosis: {output}") + command += ["--parent", str(previous)] + else: + command += ["--resume", str(previous)] + label = "health2k" if update == 2000 else "full" + state("training", stage=stage, update=update, parent=str(previous)) + run_logged(command, LOGS / f"{RUN_TAG}_{stage.lower()}_{label}.console.log") + if not target.is_file(): + raise RuntimeError(f"training returned without endpoint: {target}") + audit(stage, update) + return target + + +def evaluate(stage: str, update: int, *, full: bool, confirmation: bool = False) -> None: + target = endpoint(stage, update) + role = "confirmation" if confirmation else "development" + conditions = [(source, mode) for source, modes in MODES.items() for mode in modes] + if not full: + conditions = [("H2O", "rgb_depth_k"), ("ARCTIC", "rgb_k"), ("HOT3D", "rgb_k")] + for source, mode in conditions: + tag = f"{RUN_TAG}_{stage.lower()}_{update:07d}_{role}_{source.lower()}_{mode}" + report_path = EVAL / "formal_stages" / f"{tag}.json" + if report_path.exists(): + report = json.loads(report_path.read_text()) + if (report["checkpoint_sha256"] != checksum(target) or report["source"] != source + or report["input_mode"] != mode or report["role"] != role): + raise RuntimeError(f"stale evaluation report: {report_path}") + continue + command = [ + PYTHON, str(CODE / "clean_eval.py"), "--checkpoint", str(target), + "--source", source, "--role", role, "--mode", mode, + "--output", str(report_path), + ] + if confirmation: + command.append("--final-checkpoint") + elif not full: + command += ["--allow-smoke", "--limit", "32"] + run_logged(command, LOGS / f"{tag}.console.log") + report = json.loads(report_path.read_text()) + if any(value["count"] == 0 for value in report["four_metrics"].values()): + raise RuntimeError(f"evaluation has an empty metric denominator: {report_path}") + state("evaluated", stage=stage, update=update, source=source, mode=mode, + role=role, report=str(report_path)) + + +def main() -> None: + try: + state("waiting_for_s1_health") + wait_for_s1_health() + audit("S1", 2000) + evaluate("S1", 2000, full=False) + parent = train("S1", ENDPOINTS["S1"], endpoint("S1", 2000)) + evaluate("S1", ENDPOINTS["S1"], full=False) + for stage in ("S2", "S3", "S4"): + short = train(stage, 2000, parent) + evaluate(stage, 2000, full=False) + parent = train(stage, ENDPOINTS[stage], short) + evaluate(stage, ENDPOINTS[stage], full=stage in ("S3", "S4")) + evaluate("S4", ENDPOINTS["S4"], full=True, confirmation=True) + state("complete", checkpoint=str(parent), checkpoint_sha256=checksum(parent)) + except Exception as error: + state("failed", error=f"{type(error).__name__}: {error}") + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/smoke_adapters.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/smoke_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..187e1e4a8016617c0eb87fb67f5d443d23898476 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/smoke_adapters.py @@ -0,0 +1,57 @@ +"""Decode one frozen filtered tile from each source without starting training.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import torch + +from filtered_dataset import FilteredClipDataset + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", type=Path, required=True) + parser.add_argument("--time", type=int, choices=(1, 8), required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--tile-id", help="Inspect a specific frozen tile") + args = parser.parse_args() + source = args.source + with torch.no_grad(): + dataset = FilteredClipDataset( + source, args.manifests / f"{source.lower()}_t{args.time}.jsonl", + args.time, (368, 640), + "/SSD3/jiasen/foundation_hand/pretrained/mano", + Path(__file__).parent / "third_party", + photometric_augmentation={"enabled": False}, + ) + mode = "rgb_depth_k" if source == "H2O" else "rgb_k" + spec = {"source": source, "tile_id": args.tile_id or dataset.rows[0]["filtered_tile_id"], + "epoch": 0, "source_ordinal": 0, "position": 0, "mode": mode} + sample = dataset[spec] + out = { + "source": source, "tile_id": spec["tile_id"], "frames": sample["frame_id"].tolist(), + "rgb_shape": list(sample["rgb"].shape), + "K_shape": list(sample["K"].shape), + "K_input": sample["K_input_available"].tolist(), + "K_supervision": sample["K_supervision_valid"].tolist(), + "depth_input": sample["depth_input_available"].tolist(), + "valid": {key: int(sample[key].sum()) for key in ( + "joint2d_valid", "joint3d_valid", "translation_valid", + "mano_pose_valid", "shape_valid", "vertices_valid", "reprojection_valid", + )}, + "finite_K": bool(torch.isfinite(sample["K"]).all()), + "valid_depth_pixels": int(sample["depth_pixel_valid"].sum()), + } + if "joint3d_root_relative_valid" in sample: + out["valid"]["joint3d_root_relative_valid"] = int(sample["joint3d_root_relative_valid"].sum()) + print(json.dumps(out, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/test_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..68b938b2aa050e510e544ed06105a08bb428ef15 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/test_contract.py @@ -0,0 +1,61 @@ +from collections import Counter +from pathlib import Path +import sqlite3 +import tempfile +import unittest + +from coverage_sampler import CoverageSampler, SOURCES +from preflight_index import tile_starts + + +class IndexTests(unittest.TestCase): + def test_tail_covers_every_frame_without_duplicates_at_start(self): + for length in range(8, 100): + starts = tile_starts(length) + self.assertEqual(starts[0], 0) + self.assertEqual(len(starts), (length + 7) // 8) + self.assertEqual(set().union(*(set(range(s, s + 8)) for s in starts)), set(range(length))) + + +class SamplerTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.index = Path(self.temp.name) / "index.sqlite" + with sqlite3.connect(self.index) as connection: + connection.execute("CREATE TABLE tiles(source TEXT, recording_id TEXT, tile_id TEXT)") + for source in SOURCES: + for recording in range(2): + for tile in range(5): + connection.execute( + "INSERT INTO tiles VALUES (?,?,?)", + (source, f"{source}-{recording}", f"{source}-{recording}-{tile}"), + ) + + def test_quota_resume_ddp_and_no_replacement(self): + sampler = CoverageSampler(self.index, "S1_S3") + first = [sampler.sample(pos) for pos in range(200)] + self.assertEqual(Counter(row["source"] for row in first), + Counter({"H2O": 80, "ARCTIC": 70, "HOT3D": 50})) + for source in SOURCES: + source_rows = [row for row in first if row["source"] == source] + self.assertEqual(len({row["tile_id"] for row in source_rows[:10]}), 10) + resumed = CoverageSampler(self.index, "S1_S3") + self.assertEqual(first[43:], [resumed.sample(pos) for pos in range(43, 200)]) + shards = [CoverageSampler(self.index, "S1_S3") for _ in range(6)] + merged = sorted((row for rank, item in enumerate(shards) + for row in item.shard(0, 200, rank, 6)), + key=lambda row: row["position"]) + self.assertEqual(first, merged) + + def test_s4_has_separate_ledger_and_modes(self): + sampler = CoverageSampler(self.index, "S4") + first = [sampler.sample(pos) for pos in range(200)] + self.assertEqual(Counter(row["source"] for row in first), + Counter({"H2O": 70, "ARCTIC": 50, "HOT3D": 80})) + self.assertTrue(all(row["mode"] != "rgb_depth_k" for row in first + if row["source"] != "H2O")) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/test_hot3d_rotation.py b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/test_hot3d_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..70352220213018fe79a2540793fd9bfd46df2014 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/clean_gt_dino/test_hot3d_rotation.py @@ -0,0 +1,24 @@ +import unittest + +import numpy as np +from scipy.spatial.transform import Rotation +import torch + +from third_party.hot3d.data_loaders.rotation_compat import matrix_to_axis_angle + + +class Hot3dRotationTests(unittest.TestCase): + def test_roundtrip_including_singular_angles(self): + values = np.array([ + [0.0, 0.0, 0.0], [1e-8, 0.0, 0.0], [0.4, -1.2, 2.1], + [np.pi - 1e-8, 0.0, 0.0], [0.0, np.pi, 0.0], + ]) + for value in values: + matrix = Rotation.from_rotvec(value).as_matrix() + recovered = matrix_to_axis_angle(torch.tensor(matrix, dtype=torch.float64)).numpy() + error = (Rotation.from_rotvec(recovered).inv() * Rotation.from_matrix(matrix)).magnitude() + self.assertLess(error, 1e-8) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/README.md b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f3156b4ea4b21c7fda72e4431a66070555c8beb3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/README.md @@ -0,0 +1,29 @@ +# DINOv3 2D observed/inferred pretraining + +Design and gates: [`docs/DINOV3_2D_VISIBLE_INFERRED_PRETRAIN_20261004.md`](../../docs/DINOV3_2D_VISIBLE_INFERRED_PRETRAIN_20261004.md). + +The source 2D valid mask is geometric supervision, **not** a visibility label. +`audit.py export` creates a recording-balanced review gallery; open its +`index.html` directly, label joints, and export `visibility_review.json`. +`audit.py report` aggregates reviewed states and checks the old valid mask's +errors. No reviewed labels have been fabricated by this package. + +```bash +PYTHONPATH=src /SSD2/jiasen/envs/foundation_hand/bin/python -m experiments.dinov3_2d_pretrain.audit report \ + --manifest /path/to/audit/manifest.json --reviews /path/to/visibility_review.json \ + --output /path/to/audit/report_reviewed.json +``` + +`pilot.py` is the original two-update P0 smoke on the older U0/A7 index. +`visible_index.py` maps its T=1 rows to the frozen visible-filter data without +changing the source GT. It writes recording-disjoint train/dev manifests. +`preflight_reader.py` checks decoded RGB/2D/masks on those manifests and exports +small GPU-smoke tensors. `smoke_ddp.py` checks two distributed updates on those +decoded tensors. None of these scripts is a formal pretraining runner or saves +pretrained weights. P0 coordinate pretraining does not require manual +visible/occluded labels; only P1's observed/visibility tasks do. + +The current index reuses the old T=1 sampling grid (170,068 surviving rows), +not every one of the visible-filter dataset's 1,276,713 frames. Formal P0 must +freeze the intended coverage policy and deterministically resample source-local +frames with no valid in-frame 2D joints. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/__init__.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92c5a510e8ec5e3d796c4267a56d2c5681565337 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/__init__.py @@ -0,0 +1 @@ +"""Full-frame DINOv3 keypoint pretraining and visibility-label audit.""" diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/audit.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/audit.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ac14c1d2d9ebc63ebe15e04240e76491a121e4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/audit.py @@ -0,0 +1,289 @@ +"""Export a recording-balanced visibility review set and summarize reviewed labels.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +import hashlib +import json +from pathlib import Path +import sys + +import numpy as np +from PIL import Image, ImageDraw + + +ROOT = Path(__file__).resolve().parent +REPO = ROOT.parents[1] +SOURCES = ("H2O", "ARCTIC", "HOT3D") +STATES = ("visible", "occluded_in_frame", "out_of_frame", "unknown") +RGB_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32) +RGB_STD = np.array([0.229, 0.224, 0.225], dtype=np.float32) + + +def project_geometry(joints: np.ndarray, K: np.ndarray, height: int, width: int) -> tuple[np.ndarray, np.ndarray]: + """Projection gives in-frame geometry, never image visibility.""" + if joints.shape != (2, 21, 3) or K.shape != (3, 3): + raise ValueError("expected [2,21,3] joints and [3,3] K") + finite = np.isfinite(joints).all(-1) & np.isfinite(K).all() + positive = finite & (joints[..., 2] > 1e-6) + uv = np.full((2, 21, 2), np.nan, dtype=np.float32) + if positive.any(): + projected = joints[positive] @ K.T + uv[positive] = (projected[:, :2] / projected[:, 2:3]).astype(np.float32) + in_frame = (positive & np.isfinite(uv).all(-1) + & (uv[..., 0] >= 0) & (uv[..., 0] < width) + & (uv[..., 1] >= 0) & (uv[..., 1] < height)) + bucket = np.full((2, 21), "unknown", dtype=" str: + return f"{sample_id}:{side}:{joint}" + + +def recording_id(source: str, row: dict) -> str: + key = {"H2O": "take", "ARCTIC": "physical_recording_id", "HOT3D": "recording_id"}[source] + return str(row[key]) + + +def select_specs(dataset, per_source: int) -> list[tuple[dict, dict]]: + selected = [] + for source in SOURCES: + by_recording = defaultdict(list) + for row in dataset.sources[source].rows: + by_recording[recording_id(source, row)].append(row) + if not by_recording: + raise RuntimeError(f"{source} has no train recordings") + recordings = sorted( + by_recording, + key=lambda recording: hashlib.sha256(f"20261004/{source}/{recording}".encode()).digest(), + )[:per_source] + candidates = {} + for recording in recordings: + ordered = sorted( + by_recording[recording], + key=lambda value: hashlib.sha256(value["filtered_tile_id"].encode()).digest(), + ) + by_frame = {} + for row in ordered: + ids = row["expected_frame_ids"] + by_frame.setdefault(str(ids[len(ids) // 2]), row) + candidates[recording] = list(by_frame.values()) + count, round_index = 0, 0 + while count < per_source: + added = False + for recording in recordings: + rows = candidates[recording] + if round_index >= len(rows): + continue + row = rows[round_index] + spec = {"position": count, "source": source, "source_ordinal": count, + "epoch": 0, "tile_id": row["filtered_tile_id"], "mode": "rgb"} + selected.append((spec, row)) + count += 1 + added = True + if count == per_source: + break + if not added: + raise RuntimeError(f"{source} has only {count} distinct center-frame candidates") + round_index += 1 + return selected + + +def image_from_rgb(rgb) -> Image.Image: + array = rgb.detach().cpu().numpy().transpose(1, 2, 0) + array = np.clip((array * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + return Image.fromarray(array, "RGB") + + +def overlay(image: Image.Image, joints: list[dict]) -> Image.Image: + result = image.copy() + draw = ImageDraw.Draw(result) + for row in joints: + if row["geometry_bucket"] != "in_frame": + continue + x, y = row["uv"] + color = "#ff7f37" if row["side"] == 0 else "#36c6aa" + draw.ellipse((x - 3, y - 3, x + 3, y + 3), outline="black", fill=color, width=1) + draw.text((x + 4, y - 7), f'{"L" if row["side"] == 0 else "R"}{row["joint"]}', fill=color, stroke_width=1, stroke_fill="black") + return result + + +def export_review_set(output: Path, per_source: int) -> dict: + if output.exists() and any(output.iterdir()): + raise FileExistsError(f"review directory is not empty: {output}") + sys.path.insert(0, str(REPO / "experiments/u0_depthsafe")) + from common import U0Dataset + + dataset = U0Dataset() + specs = select_specs(dataset, per_source) + output.mkdir(parents=True, exist_ok=True) + (output / "images").mkdir(exist_ok=True) + samples = [] + for ordinal, (spec, row) in enumerate(specs): + sample = dataset[spec] + valid_frames = np.flatnonzero(sample["frame_valid"].cpu().numpy()) + if not len(valid_frames): + raise RuntimeError(f"no real frame in {spec['tile_id']}") + frame = int(valid_frames[len(valid_frames) // 2]) + image = image_from_rgb(sample["rgb"][frame]) + width, height = image.size + uv, bucket = project_geometry( + sample["joint3d_camera"][frame].cpu().numpy(), + sample["K"][frame].cpu().numpy(), height, width, + ) + existing = sample["joint2d_valid"][frame].cpu().numpy().astype(bool) + recording = recording_id(spec["source"], row) + sample_id = hashlib.sha256( + f'{spec["source"]}/{recording}/{int(sample["frame_id"][frame])}'.encode() + ).hexdigest()[:16] + joints = [ + {"side": side, "joint": joint, "uv": uv[side, joint].tolist() if np.isfinite(uv[side, joint]).all() else None, + "geometry_bucket": str(bucket[side, joint]), "joint2d_valid": bool(existing[side, joint])} + for side in range(2) for joint in range(21) + ] + filename = f"{ordinal:03d}_{spec['source'].lower()}_{sample_id}.jpg" + image.save(output / "images" / filename, quality=92) + overlay(image, joints).save(output / "images" / filename.replace(".jpg", "_points.jpg"), quality=92) + samples.append({ + "sample_id": sample_id, "source": spec["source"], + "recording": recording, "tile_id": spec["tile_id"], + "frame_index": frame, "frame_id": int(sample["frame_id"][frame]), + "image": "images/" + filename, "overlay": "images/" + filename.replace(".jpg", "_points.jpg"), + "height": height, "width": width, "joints": joints, + }) + if (ordinal + 1) % 12 == 0: + print(json.dumps({"exported": ordinal + 1, "total": len(specs)}), flush=True) + manifest = {"version": 1, "selection": "hash_sampled_recordings_then_distinct_center_frames_round_robin", + "review_states": STATES, "samples": samples} + (output / "manifest.json").write_text(json.dumps(manifest, indent=2, allow_nan=False) + "\n") + template = (ROOT / "review_template.html").read_text() + embedded = json.dumps(manifest, ensure_ascii=True).replace("<", "\\u003c") + (output / "index.html").write_text(template.replace("__MANIFEST_JSON__", embedded)) + return summarize(manifest, {}) + + +def summarize(manifest: dict, reviews: dict[str, str], manual_uv: dict[str, list[float]] | None = None, + second_reviews: dict[str, str] | None = None) -> dict: + manual_uv = manual_uv or {} + known = {review_key(sample["sample_id"], joint["side"], joint["joint"]) + for sample in manifest["samples"] for joint in sample["joints"]} + if (set(reviews) | set(manual_uv) | set(second_reviews or {})) - known: + raise ValueError("review contains unknown joint keys") + if (set(reviews.values()) | set((second_reviews or {}).values())) - set(STATES): + raise ValueError("review contains an invalid state") + report = {} + for source in SOURCES: + counts = Counter() + proxy = Counter() + confusion = Counter() + valid_by_proxy = Counter() + recordings = set() + projection_errors = [] + pairs = [] + for sample in manifest["samples"]: + if sample["source"] != source: + continue + recordings.add(sample["recording"]) + for joint in sample["joints"]: + proxy[joint["geometry_bucket"]] += 1 + if joint["joint2d_valid"]: + valid_by_proxy[joint["geometry_bucket"]] += 1 + key = review_key(sample["sample_id"], joint["side"], joint["joint"]) + state = reviews.get(key, "unreviewed") + counts[state] += 1 + if second_reviews is not None: + second = second_reviews.get(key) + if state in STATES[:3] and second in STATES[:3]: + pairs.append((state == "visible", second == "visible")) + if state == "visible" and key in manual_uv and joint.get("uv") is not None: + marked = np.asarray(manual_uv[key], dtype=np.float64) + if marked.shape != (2,) or not np.isfinite(marked).all(): + raise ValueError(f"invalid manual 2D point for {key}") + projection_errors.append(float(np.linalg.norm(marked - joint["uv"]))) + if state in {"visible", "occluded_in_frame", "out_of_frame"}: + confusion["reviewed_binary"] += 1 + predicted_visible = joint["joint2d_valid"] + actually_visible = state == "visible" + confusion["false_visible"] += int(predicted_visible and not actually_visible) + confusion["missed_visible"] += int(actually_visible and not predicted_visible) + confusion["predicted_visible"] += int(predicted_visible) + confusion["actually_visible"] += int(actually_visible) + reviewed = sum(counts[state] for state in STATES) + denominator = sum(counts.values()) + agreement = None + if second_reviews is not None: + pairs_array = np.asarray(pairs, dtype=np.bool_).reshape(-1, 2) + observed = float(np.mean(pairs_array[:, 0] == pairs_array[:, 1])) if len(pairs) else None + if len(pairs): + a, b = pairs_array.mean(axis=0) + expected = float(a * b + (1 - a) * (1 - b)) + kappa = (observed - expected) / (1 - expected) if expected < 1 else None + else: + kappa = None + agreement = {"double_reviewed_binary_joints": len(pairs), "agreement": observed, + "cohen_kappa_visible_vs_other": kappa} + report[source] = { + "recordings": len(recordings), "joints": denominator, + "geometry_proxy_not_visibility": dict(proxy), + "joint2d_valid_by_geometry_proxy": dict(valid_by_proxy), + "review_coverage": reviewed / denominator if denominator else None, + "review_state_count": {state: counts[state] for state in (*STATES, "unreviewed")}, + "review_state_fraction_of_reviewed": { + state: counts[state] / reviewed if reviewed else None for state in STATES + }, + "joint2d_valid_as_visibility_errors": { + **dict(confusion), + "false_visible_rate_among_predicted_visible": ( + confusion["false_visible"] / confusion["predicted_visible"] + if confusion["predicted_visible"] else None + ), + "missed_visible_rate_among_visible": ( + confusion["missed_visible"] / confusion["actually_visible"] + if confusion["actually_visible"] else None + ), + }, + "visible_projection_vs_manual_px": { + "count": len(projection_errors), + "median": float(np.median(projection_errors)) if projection_errors else None, + "p90": float(np.percentile(projection_errors, 90)) if projection_errors else None, + }, + "reviewer_agreement": agreement, + } + return {"status": "manual_review_pending" if not reviews else "partially_or_fully_reviewed", + "source": report} + + +def main(): + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest="command", required=True) + export = sub.add_parser("export") + export.add_argument("--output", type=Path, required=True) + export.add_argument("--per-source", type=int, default=24) + report = sub.add_parser("report") + report.add_argument("--manifest", type=Path, required=True) + report.add_argument("--reviews", type=Path) + report.add_argument("--reviews-b", type=Path) + report.add_argument("--output", type=Path) + args = parser.parse_args() + if args.command == "export": + result = export_review_set(args.output, args.per_source) + destination = args.output / "report_unreviewed.json" + else: + manifest = json.loads(args.manifest.read_text()) + review_data = json.loads(args.reviews.read_text()) if args.reviews else {} + second = json.loads(args.reviews_b.read_text()) if args.reviews_b else None + result = summarize(manifest, review_data.get("labels", review_data), + review_data.get("manual_uv", {}), + second.get("labels", second) if second is not None else None) + destination = args.output + if destination: + destination.write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bf4735de2f36c85499957025520ff7cdacb5b309 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/config.json @@ -0,0 +1,14 @@ +{ + "contract": "DINOV3_FULL_FRAME_2D_OBSERVED_INFERRED_V1", + "status": "p0a_full_frame_g1_running", + "seed": 20261004, + "dino_source": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "dino_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "image_hw": [512, 896], + "model_width": 512, + "bin_pixels": 4, + "source_quota_per_60": {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}, + "review_codes": {"visible": 0, "occluded_in_frame": 1, "out_of_frame": 2, "unknown": 3, "unreviewed": -1}, + "pilot": {"updates": 2, "learning_rate": 0.0001, "weight_decay": 0.05, "grad_clip_norm": 1.0}, + "formal_pretraining_approved": true +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/eval_p0.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/eval_p0.py new file mode 100644 index 0000000000000000000000000000000000000000..f36da9a33eecd50a960cd0001be3150cfb9f638e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/eval_p0.py @@ -0,0 +1,173 @@ +"""Recording-disjoint P0 inferred-keypoint evaluation at 512x896 pixels.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +import random +import sys + +import numpy as np +import torch +from torch.utils.data import DataLoader, Dataset + +from .full_index import PHASES +from .model import DinoKeypointPretrainer +from .train_p0 import CONFIG, is_expected_hot3d_sync_error +from .visible_index import SOURCES, sha256 + + +RECORDING_KEYS = {"H2O": "take", "ARCTIC": "physical_recording_id", + "HOT3D": "recording_id"} + + +def decode_coordinates(prediction: dict[str, torch.Tensor], bin_pixels: int) -> torch.Tensor: + x = prediction["infer_x"].argmax(-1).float() + y = prediction["infer_y"].argmax(-1).float() + return (torch.stack((x, y), dim=-1) + 0.5) * bin_pixels + + +def pixel_summary(errors: list[float]) -> dict: + if not errors: + return {"count": 0, "mean_px": None, "median_px": None, + "p90_px": None, "pck10": None, "pck20": None} + values = np.asarray(errors, dtype=np.float64) + return {"count": len(values), "mean_px": float(values.mean()), + "median_px": float(np.median(values)), "p90_px": float(np.percentile(values, 90)), + "pck10": float(np.mean(values <= 10)), "pck20": float(np.mean(values <= 20))} + + +def list_collate(samples): + return samples + + +class SelectedDevFrames(Dataset): + def __init__(self, dataset, source: str, phase: int, count: int): + self.dataset, self.source = dataset, source + seed = CONFIG["seed"] + phase * 100 + SOURCES.index(source) + self.indices = sorted(random.Random(seed).sample(range(len(dataset)), + min(count, len(dataset)))) + + def __len__(self): + return len(self.indices) + + def __getitem__(self, item): + index = self.indices[item] + row = self.dataset.rows[index] + spec = {"position": index, "source": self.source, "source_ordinal": index, + "epoch": 0, "tile_id": row["filtered_tile_id"], "mode": "rgb"} + try: + sample = self.dataset[spec] + except RuntimeError as error: + if not is_expected_hot3d_sync_error(self.source, error): + raise + return {"unreadable_tile_id": row["filtered_tile_id"]} + return {"rgb": sample["rgb"][0], "uv": sample["joint2d"][0], + "valid": sample["joint2d_valid"][0].bool(), + "recording": str(row[RECORDING_KEYS[self.source]]), + "tile_id": row["filtered_tile_id"]} + + +def evaluate(args): + sys.path.insert(0, str(args.code_root)) + sys.path.insert(0, str(args.code_root / "src")) + from filtered_dataset import FilteredClipDataset + + report_path = args.index_root / "index_report.json" + report_hash = sha256(report_path) + index_report = json.loads(report_path.read_text()) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if state["index_report_sha256"] != report_hash: + raise ValueError("checkpoint and dev index differ") + device = torch.device(args.device) + model = DinoKeypointPretrainer( + CONFIG["dino_source"], CONFIG["dino_weights"], tuple(CONFIG["image_hw"]), + width=CONFIG["model_width"], bin_pixels=CONFIG["bin_pixels"], + ).to(device) + model.load_state_dict(state["model"], strict=True) + model.eval() + output = {"step": state["step"], "checkpoint": str(args.checkpoint), + "index_report_sha256": report_hash, "image_hw": CONFIG["image_hw"], + "max_frames_per_source": args.limit_per_source, "sources": {}} + height, width = CONFIG["image_hw"] + for source in SOURCES: + errors, per_recording = [], defaultdict(list) + selected_count, sampled, empty = 0, 0, 0 + selected_tiles, unreadable_tiles = [], [] + for phase in range(PHASES): + manifest = args.index_root / f"{source.lower()}_dev_phase{phase}_t1.jsonl" + expected = index_report["manifests"][f"{source}/dev/phase{phase}"]["sha256"] + if sha256(manifest) != expected: + raise ValueError(f"changed dev manifest: {manifest}") + dataset = FilteredClipDataset( + source, manifest, 1, tuple(CONFIG["image_hw"]), + "/SSD3/jiasen/foundation_hand/pretrained/mano", + args.code_root / "third_party", photometric_augmentation=None, + ) + count = args.limit_per_source // PHASES + int(phase < args.limit_per_source % PHASES) + selected = SelectedDevFrames(dataset, source, phase, count) + selected_tiles.extend(dataset.rows[index]["filtered_tile_id"] for index in selected.indices) + loader = DataLoader(selected, batch_size=args.batch_size, + num_workers=args.workers, collate_fn=list_collate) + for samples in loader: + selected_count += len(samples) + unreadable_tiles.extend(sample["unreadable_tile_id"] for sample in samples + if "unreadable_tile_id" in sample) + samples = [sample for sample in samples if "unreadable_tile_id" not in sample] + if not samples: + continue + sampled += len(samples) + rgb = torch.stack([sample["rgb"] for sample in samples]).to(device) + with torch.inference_mode(), torch.autocast(device.type, dtype=torch.bfloat16, + enabled=device.type == "cuda"): + prediction = model(rgb) + xy = decode_coordinates(prediction, CONFIG["bin_pixels"]).cpu() + for position, sample in enumerate(samples): + uv = sample["uv"] + mask = (sample["valid"] & torch.isfinite(uv).all(-1) + & (uv[..., 0] >= 0) & (uv[..., 0] < width) + & (uv[..., 1] >= 0) & (uv[..., 1] < height)) + if not bool(mask.any()): + empty += 1 + continue + values = torch.linalg.vector_norm(xy[position][mask] - uv[mask], dim=-1).tolist() + errors.extend(values) + per_recording[sample["recording"]].extend(values) + del loader, selected, dataset + recording_medians = [float(np.median(values)) for values in per_recording.values()] + output["sources"][source] = {"selected_frames": selected_count, + "selected_tile_ids_sha256": hashlib.sha256( + "\n".join(selected_tiles).encode()).hexdigest(), + "sampled_frames": sampled, + "unreadable_frames": len(unreadable_tiles), + "unreadable_tile_ids": unreadable_tiles, + "empty_target_frames": empty, + "recordings": len(per_recording), + "recording_macro_median_px": + float(np.mean(recording_medians)) if recording_medians else None, + **pixel_summary(errors)} + args.output.parent.mkdir(parents=True, exist_ok=True) + if args.output.exists(): + raise FileExistsError(args.output) + args.output.write_text(json.dumps(output, indent=2) + "\n") + print(json.dumps(output)) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--index-root", type=Path, required=True) + parser.add_argument("--code-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--limit-per-source", type=int, default=512) + parser.add_argument("--batch-size", type=int, default=2) + parser.add_argument("--workers", type=int, default=1) + parser.add_argument("--device", default="cuda:0") + evaluate(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/filter_unreadable_index.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/filter_unreadable_index.py new file mode 100644 index 0000000000000000000000000000000000000000..70962999d76d75b4653f37eeec17c8b49766c077 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/filter_unreadable_index.py @@ -0,0 +1,78 @@ +"""Hash-bound ARCTIC source-readability gate for an existing full P0 index.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from .full_index import PHASES, arctic_unreadable_reason +from .visible_index import SOURCES, sha256 + + +def filter_index(parent: Path, output: Path) -> dict: + if output.exists(): + raise FileExistsError(output) + parent_report = parent / "index_report.json" + original = json.loads(parent_report.read_text()) + report = json.loads(json.dumps(original)) + report["parent_index_report_sha256"] = sha256(parent_report) + report["arctic_readability_gate"] = "camera/mano array bounds and nonempty RGB file" + bounds_cache, excluded = {}, [] + output.mkdir(parents=True) + arctic_recordings = {"train": set(), "dev": set()} + for source in SOURCES: + for role in ("train", "dev"): + for phase in range(PHASES): + key = f"{source}/{role}/phase{phase}" + name = f"{source.lower()}_{role}_phase{phase}_t1.jsonl" + source_path, destination = parent / name, output / name + if sha256(source_path) != original["manifests"][key]["sha256"]: + raise ValueError(f"changed parent phase: {source_path}") + count = 0 + with source_path.open() as input_stream, destination.open("w") as output_stream: + for line in input_stream: + row = json.loads(line) + reason = (arctic_unreadable_reason(row, bounds_cache) + if source == "ARCTIC" else None) + if reason: + excluded.append({"tile_id": row["filtered_tile_id"], + "recording_id": row["physical_recording_id"], + "frame_id": row["expected_frame_ids"][0], + "role": role, "reason": reason}) + continue + output_stream.write(line) + count += 1 + if source == "ARCTIC": + arctic_recordings[role].add(row["physical_recording_id"]) + report["sources"][source]["per_phase_rows"][f"{role}_phase{phase}"] = count + report["manifests"][key] = {"path": str(destination), "sha256": sha256(destination)} + if arctic_recordings["train"] & arctic_recordings["dev"]: + raise ValueError("ARCTIC recording leaked across roles") + arctic = report["sources"]["ARCTIC"] + arctic["excluded_unusable_frames"] = excluded + arctic["trainable_frames"] -= len(excluded) + arctic["indexed_frames"] -= len(excluded) + arctic["recordings"] = {key: len(value) for key, value in arctic_recordings.items()} + for source in SOURCES: + details = report["sources"][source] + if sum(details["per_phase_rows"].values()) != details["indexed_frames"]: + raise ValueError(f"{source}: filtered frame coverage mismatch") + (output / "index_report.json").write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--parent", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + report = filter_index(args.parent, args.output) + excluded = report["sources"]["ARCTIC"]["excluded_unusable_frames"] + print(json.dumps({"excluded_arctic_frames": len(excluded), + "reasons": sorted(set(item["reason"] for item in excluded)), + "arctic_trainable": report["sources"]["ARCTIC"]["trainable_frames"]})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/full_index.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/full_index.py new file mode 100644 index 0000000000000000000000000000000000000000..e5cc37988cd7bd2056441b5c11ab0a4581c7c74c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/full_index.py @@ -0,0 +1,216 @@ +"""Eight disjoint T=1 phases covering every visible-filter training frame.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +import hashlib +import json +from pathlib import Path + +import numpy as np + +from .visible_index import RECORDING_KEY, SOURCES, heldout_recording, read_jsonl, sha256 + + +PHASES = 8 + + +def load_children(visible_manifest: Path, local_gt: Path) -> tuple[dict, dict]: + parents = defaultdict(list) + children = {} + for row in read_jsonl(visible_manifest): + source = row["dataset"] + if source not in SOURCES or not row["retained"]: + raise ValueError("foreign or removed visible row") + path = local_gt / source / row["id"] / "native_gt.npz" + if not path.is_file() or sha256(path) != row["gt_sha256"]: + raise ValueError(f"missing or changed visible GT: {path}") + with np.load(path, allow_pickle=False) as archive: + frame_ids = archive["frame_ids"].astype(np.int64).copy() + start, end = map(int, row["parent_frame_slice"]) + if start < 0 or end - start != len(frame_ids) or end - start != int(row["frame_count"]): + raise ValueError(f"GT length/parent slice mismatch: {path}") + child = {"row": row, "path": path, "start": start, "end": end, + "frame_ids": frame_ids, "coverage": np.zeros(len(frame_ids), dtype=np.uint8)} + parents[source, row["parent_id"]].append(child) + children[source, row["id"]] = child + for key, group in parents.items(): + group.sort(key=lambda child: child["start"]) + if any(left["end"] > right["start"] for left, right in zip(group, group[1:])): + raise ValueError(f"overlapping visible children: {key}") + return parents, children + + +def find_child(group: list[dict], parent_offset: int) -> tuple[dict, int] | None: + for child in group: + if child["start"] <= parent_offset < child["end"]: + return child, parent_offset - child["start"] + return None + + +def transformed_row(template: dict, source: str, child: dict, offset: int, + timeline_root: Path, timeline_cache: dict) -> dict: + row = child["row"] + frame_id = int(child["frame_ids"][offset]) + result = dict(template) + result.update(filtered_tile_id=f"{row['id']}:{offset}", filtered_window_id=row["id"], + filtered_gt_path=str(child["path"]), filtered_start_offset=offset, + expected_frame_ids=[frame_id]) + if source == "H2O": + result["frame_ids"] = [frame_id] + elif source == "ARCTIC": + result["frame_ids_1based"] = [frame_id] + result["array_indices_0based"] = [frame_id - 1] + result["image_paths"] = [row["source"]["rgb_template"].format(frame=frame_id)] + else: + recording = row["recording_id"] + if recording not in timeline_cache: + path = timeline_root / f"hot_timeline_{recording}.json" + timeline_cache[recording] = json.loads(path.read_text()) + stream = row["stream_id"] + result["timestamps_ns"] = [int(timeline_cache[recording][stream][frame_id])] + return result + + +def arctic_unreadable_reason(row: dict, bounds_cache: dict) -> str | None: + key = row["camera_path"], row["mano_path"] + if key not in bounds_cache: + camera = np.load(key[0], allow_pickle=True).item() + mano = np.load(key[1], allow_pickle=True).item() + bounds_cache[key] = { + "camera_R": len(camera["R_k_cam_np"]), + "camera_T": len(camera["T_k_cam_np"]), + **{f"mano_{side}_{field}": len(mano[side][field]) + for side in ("left", "right") for field in ("rot", "pose", "trans")}, + } + index = int(row["array_indices_0based"][0]) + for name, count in bounds_cache[key].items(): + if index < 0 or index >= count: + return f"{name}_index_{index}_outside_{count}" + image = Path(row["image_paths"][0]) + if not image.is_file() or image.stat().st_size == 0: + return "missing_or_empty_rgb" + return None + + +def build(visible_manifest: Path, parent_t1_dir: Path, local_gt: Path, + timeline_root: Path, output_dir: Path, expected_sha256: str) -> dict: + if output_dir.exists(): + raise FileExistsError(output_dir) + manifest_sha = sha256(visible_manifest) + if manifest_sha != expected_sha256: + raise ValueError("visible manifest hash changed") + parents, children = load_children(visible_manifest, local_gt) + output_dir.mkdir(parents=True) + paths = {(source, role, phase): output_dir / f"{source.lower()}_{role}_phase{phase}_t1.jsonl" + for source in SOURCES for role in ("train", "dev") for phase in range(PHASES)} + streams = {key: path.open("w", encoding="utf-8") for key, path in paths.items()} + report = {"visible_manifest_sha256": manifest_sha, "phase_count": PHASES, + "sources": {}, "manifests": {}} + timeline_cache, arctic_bounds_cache = {}, {} + try: + for source in SOURCES: + counts = Counter() + recordings = {"train": set(), "dev": set()} + parent_path = parent_t1_dir / f"{source.lower()}_t1.jsonl" + templates = {} + for template in read_jsonl(parent_path): + base = int(template["filtered_start_offset"]) + group = parents.get((source, template["filtered_window_id"]), []) + found = find_child(group, base) + if found is not None: + child, offset = found + if int(child["frame_ids"][offset]) != int(template["expected_frame_ids"][0]): + raise ValueError("old/new frame identity mismatch") + templates.setdefault(template["filtered_window_id"], template) + source_children = [child for (name, _), child in children.items() if name == source] + excluded = [] + excluded_frames = [] + excluded_frame_keys = set() + for child in source_children: + parent_id = child["row"]["parent_id"] + template = templates.get(parent_id) + if template is None: + if source != "HOT3D" or child["row"]["source"]["device"] != "Quest3": + raise ValueError(f"{source}: no native reader template for {parent_id}") + excluded.append({"window_id": child["row"]["id"], + "frames": len(child["frame_ids"]), + "reason": "absent_from_frozen_trainable_T1; headset_sync_failure_spot_checked"}) + continue + recording = str(template[RECORDING_KEY[source]]) + if recording != child["row"]["recording_id"]: + raise ValueError("recording identity changed") + role = "dev" if heldout_recording(source, recording) else "train" + recordings[role].add(recording) + for offset in range(len(child["frame_ids"])): + phase = (child["start"] + offset) % PHASES + mapped = transformed_row(template, source, child, offset, + timeline_root, timeline_cache) + reason = (arctic_unreadable_reason(mapped, arctic_bounds_cache) + if source == "ARCTIC" else None) + if reason: + key = child["row"]["id"], offset + excluded_frame_keys.add(key) + excluded_frames.append({"tile_id": mapped["filtered_tile_id"], + "recording_id": recording, + "frame_id": mapped["expected_frame_ids"][0], + "reason": reason}) + continue + child["coverage"][offset] += 1 + if child["coverage"][offset] != 1: + raise ValueError(f"duplicate visible frame: {child['row']['id']}:{offset}") + streams[source, role, phase].write(json.dumps(mapped, separators=(",", ":")) + "\n") + counts[f"{role}_phase{phase}"] += 1 + if recordings["train"] & recordings["dev"]: + raise AssertionError("recording leaked across splits") + excluded_ids = {item["window_id"] for item in excluded} + trainable = [child for child in source_children + if child["row"]["id"] not in excluded_ids] + if any(any(int(value) != int((child["row"]["id"], offset) + not in excluded_frame_keys) + for offset, value in enumerate(child["coverage"])) for child in trainable): + missing = sum(sum(int(value) != int((child["row"]["id"], offset) + not in excluded_frame_keys) + for offset, value in enumerate(child["coverage"])) + for child in trainable) + raise ValueError(f"{source}: {missing} visible frames not covered once") + indexed = sum(value for key, value in counts.items() if "_phase" in key) + trainable_frames = sum(len(child["frame_ids"]) for child in trainable) - len(excluded_frames) + if indexed != trainable_frames: + raise ValueError(f"{source}: indexed count differs from trainable frame count") + report["sources"][source] = { + "visible_frames": sum(len(child["frame_ids"]) for child in source_children), + "trainable_frames": trainable_frames, "indexed_frames": indexed, + "per_phase_rows": {key: value for key, value in counts.items() if "_phase" in key}, + "excluded_unusable_windows": excluded, + "excluded_unusable_frames": excluded_frames, + "recordings": {role: len(values) for role, values in recordings.items()}, + "parent_t1_sha256": sha256(parent_path), + } + finally: + for stream in streams.values(): + stream.close() + for (source, role, phase), path in paths.items(): + report["manifests"][f"{source}/{role}/phase{phase}"] = { + "path": str(path), "sha256": sha256(path)} + (output_dir / "index_report.json").write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--visible-manifest", type=Path, required=True) + parser.add_argument("--parent-t1-dir", type=Path, required=True) + parser.add_argument("--local-gt", type=Path, required=True) + parser.add_argument("--timeline-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--expected-sha256", required=True) + args = parser.parse_args() + report = build(args.visible_manifest, args.parent_t1_dir, args.local_gt, + args.timeline_root, args.output_dir, args.expected_sha256) + print(json.dumps(report["sources"], indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/gkdt_probe.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/gkdt_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..3e5d4db52f8435e234512e1f1fb69223cba0e886 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/gkdt_probe.py @@ -0,0 +1,341 @@ +"""Frozen GKDT-L visual features with the existing P0 inferred-2D head.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +import hashlib +import json +import os +from pathlib import Path +import sys +import time + +import numpy as np +import torch +from torch import nn +from torch.utils.data import DataLoader + +from foundation_hand.models.encoders import PatchFeatures +from .eval_p0 import SelectedDevFrames, decode_coordinates, list_collate, pixel_summary +from .full_index import PHASES +from .loss import KeypointPretrainLoss, UNREVIEWED +from .model import DinoKeypointPretrainer +from .train_p0 import CONFIG, P0Frames, PositionRange, checked_index +from .visible_index import SOURCES, sha256 + + +VISUAL_PREFIX = "dinov3_visual_encoder." + + +class FrozenGKDTEncoder(nn.Module): + trainable_last_blocks = 0 + + def __init__(self, source_repo: Path, weights: Path, output_dim: int): + super().__init__() + self.backbone = torch.hub.load(str(source_repo), "dinov3_vitl16", + source="local", pretrained=False) + self.backbone.load_state_dict(torch.load(weights, map_location="cpu", + weights_only=True), strict=True) + self.backbone.requires_grad_(False) + self.backbone.eval() + self.projection = nn.Linear(1024, output_dim) + + def train(self, mode: bool = True): + super().train(mode) + self.backbone.eval() + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + height, width = images.shape[-2:] + if height % 16 or width % 16: + raise ValueError("GKDT ViT-L input must be divisible by 16") + with torch.no_grad(): + tokens = self.backbone.forward_features(images)["x_norm_patchtokens"] + return PatchFeatures(self.projection(tokens), (height // 16, width // 16), 16) + + +def export_visual(checkpoint: Path, output: Path) -> None: + if output.exists(): + raise FileExistsError(output) + state = torch.load(checkpoint, map_location="cpu", weights_only=True) + model_state = state["model"] + visual = {key[len(VISUAL_PREFIX):]: value for key, value in model_state.items() + if key.startswith(VISUAL_PREFIX)} + if not visual or visual["patch_embed.proj.weight"].shape != (1024, 3, 16, 16): + raise ValueError("checkpoint does not contain the expected GKDT-L DINOv3 visual encoder") + blocks = {int(key.split(".")[1]) for key in visual if key.startswith("blocks.")} + if blocks != set(range(24)): + raise ValueError(f"expected all 24 GKDT-L blocks, found {sorted(blocks)}") + temporary = output.with_suffix(output.suffix + ".tmp") + torch.save(visual, temporary) + os.replace(temporary, output) + print(json.dumps({"visual_tensors": len(visual), "backbone": str(output), + "sha256": sha256(output), "bytes": output.stat().st_size})) + + +def make_model(args: argparse.Namespace) -> DinoKeypointPretrainer: + encoder = FrozenGKDTEncoder(args.dino_source, args.visual_weights, + CONFIG["model_width"]) + model = DinoKeypointPretrainer( + args.dino_source, args.visual_weights, tuple(CONFIG["image_hw"]), + width=CONFIG["model_width"], bin_pixels=CONFIG["bin_pixels"], encoder=encoder, + ) + model.set_auxiliary_tuning(False) + if any(parameter.requires_grad for parameter in model.encoder.backbone.parameters()): + raise AssertionError("GKDT visual backbone must remain frozen") + return model + + +def head_state(model: DinoKeypointPretrainer) -> dict[str, torch.Tensor]: + return {key: value for key, value in model.state_dict().items() + if not key.startswith("encoder.backbone.")} + + +def load_head(model: DinoKeypointPretrainer, saved: dict[str, torch.Tensor]) -> None: + result = model.load_state_dict(saved, strict=False) + expected = {key for key in model.state_dict() if key.startswith("encoder.backbone.")} + if set(result.missing_keys) != expected or result.unexpected_keys: + raise ValueError("head-only checkpoint composition is incomplete") + + +def sample_mean_loss(criterion: KeypointPretrainLoss, + prediction: dict[str, torch.Tensor], uv: torch.Tensor, + valid: torch.Tensor, states: torch.Tensor) -> torch.Tensor: + losses = [] + for index in range(uv.shape[0]): + one = {key: value[index:index + 1] for key, value in prediction.items()} + loss, details = criterion(one, uv[index:index + 1], valid[index:index + 1], + states[index:index + 1]) + if not bool(torch.isfinite(loss)) or details["infer_count"] == 0: + raise RuntimeError("empty or nonfinite inferred-2D sample loss") + losses.append(loss) + return torch.stack(losses).mean() + + +def compatible_resume_contract(previous: dict, current: dict) -> bool: + previous = dict(previous) + current = dict(current) + previous.pop("micro_batch", None) + current.pop("micro_batch", None) + return previous == current + + +def evaluate(model: DinoKeypointPretrainer, args: argparse.Namespace, + index_report: dict, step: int, report_sha: str) -> dict: + sys.path.insert(0, str(args.code_root)) + sys.path.insert(0, str(args.code_root / "src")) + from filtered_dataset import FilteredClipDataset + + height, width = CONFIG["image_hw"] + output = {"step": step, "backbone_sha256": sha256(args.visual_weights), + "index_report_sha256": report_sha, "image_hw": CONFIG["image_hw"], + "max_frames_per_source": args.eval_limit_per_source, "sources": {}} + model.eval() + for source in SOURCES: + errors, by_recording = [], defaultdict(list) + selected_count = sampled = empty = 0 + selected_tiles, unreadable = [], [] + for phase in range(PHASES): + manifest = args.index_root / f"{source.lower()}_dev_phase{phase}_t1.jsonl" + if sha256(manifest) != index_report["manifests"][f"{source}/dev/phase{phase}"]["sha256"]: + raise ValueError(f"changed dev manifest: {manifest}") + dataset = FilteredClipDataset( + source, manifest, 1, tuple(CONFIG["image_hw"]), + "/SSD3/jiasen/foundation_hand/pretrained/mano", + args.code_root / "third_party", photometric_augmentation=None, + ) + count = args.eval_limit_per_source // PHASES + int( + phase < args.eval_limit_per_source % PHASES) + selected = SelectedDevFrames(dataset, source, phase, count) + selected_tiles.extend(dataset.rows[index]["filtered_tile_id"] + for index in selected.indices) + loader = DataLoader(selected, batch_size=2, num_workers=0, + collate_fn=list_collate) + for samples in loader: + selected_count += len(samples) + unreadable.extend(sample["unreadable_tile_id"] for sample in samples + if "unreadable_tile_id" in sample) + samples = [sample for sample in samples if "unreadable_tile_id" not in sample] + if not samples: + continue + sampled += len(samples) + rgb = torch.stack([sample["rgb"] for sample in samples]).to(args.device) + with torch.inference_mode(), torch.autocast( + "cuda", dtype=torch.bfloat16, enabled=args.device.startswith("cuda") + ): + prediction = model(rgb) + xy = decode_coordinates(prediction, CONFIG["bin_pixels"]).cpu() + for position, sample in enumerate(samples): + uv = sample["uv"] + mask = sample["valid"] & torch.isfinite(uv).all(-1) + mask &= (uv[..., 0] >= 0) & (uv[..., 0] < width) + mask &= (uv[..., 1] >= 0) & (uv[..., 1] < height) + if not bool(mask.any()): + empty += 1 + continue + values = torch.linalg.vector_norm( + xy[position][mask] - uv[mask], dim=-1).tolist() + errors.extend(values) + by_recording[sample["recording"]].extend(values) + del loader, selected, dataset + medians = [float(np.median(values)) for values in by_recording.values()] + output["sources"][source] = { + "selected_frames": selected_count, + "selected_tile_ids_sha256": hashlib.sha256( + "\n".join(selected_tiles).encode()).hexdigest(), + "sampled_frames": sampled, "unreadable_frames": len(unreadable), + "unreadable_tile_ids": unreadable, "empty_target_frames": empty, + "recordings": len(by_recording), + "recording_macro_median_px": float(np.mean(medians)) if medians else None, + **pixel_summary(errors), + } + model.train() + model.encoder.backbone.eval() + return output + + +def train(args: argparse.Namespace, model_factory=make_model, + stage_name: str = "GKDT-L frozen-feature P0 head probe") -> None: + if args.output.exists() and args.resume is None: + raise FileExistsError(args.output) + if (args.global_batch <= 0 or args.phase_steps <= 0 or args.updates <= 0 + or args.micro_batch <= 0 or args.global_batch % args.micro_batch): + raise ValueError("training budget must be positive") + torch.manual_seed(CONFIG["seed"]) + torch.set_num_threads(2) + index_path = args.index_root / "index_report.json" + report_sha = sha256(index_path) + report = json.loads(index_path.read_text()) + if report["visible_manifest_sha256"] != args.expected_visible_sha256: + raise ValueError("GKDT probe is bound to the wrong visible data") + backbone_sha = sha256(args.visual_weights) + model = model_factory(args).to(args.device).train() + trainable = [parameter for parameter in model.parameters() if parameter.requires_grad] + optimizer = torch.optim.AdamW(trainable, lr=1e-4, weight_decay=0.05) + contract = {"stage": stage_name, + "gkdt_checkpoint": str(args.gkdt_checkpoint), + "gkdt_checkpoint_sha256": sha256(args.gkdt_checkpoint), + "backbone": str(args.visual_weights), "backbone_sha256": backbone_sha, + "index_report_sha256": report_sha, + "visible_manifest_sha256": args.expected_visible_sha256, + "seed": CONFIG["seed"], "global_batch": args.global_batch, + "micro_batch": args.micro_batch, + "phase_steps": args.phase_steps, "image_hw": CONFIG["image_hw"], + "head_lr": 1e-4, "source_quota_per_60": CONFIG["source_quota_per_60"], + "loss": "P0 inferred x/y cross-entropy only", "teacher_loss": False, + "visible_loss": False, "visibility_loss": False, + "trainable_head_parameters": sum(p.numel() for p in trainable), + "trainable_backbone_parameters": 0} + start = 0 + if args.resume is not None: + saved = torch.load(args.resume, map_location="cpu", weights_only=True) + if not compatible_resume_contract(saved["contract"], contract): + raise ValueError("GKDT probe resume contract mismatch") + load_head(model, saved["head"]) + optimizer.load_state_dict(saved["optimizer"]) + start = int(saved["step"]) + if not 0 <= start < args.updates: + raise ValueError("GKDT probe resume step outside requested budget") + args.output.mkdir(parents=True, exist_ok=True) + contract_path = args.output / "run_contract.json" + if not contract_path.exists(): + contract_path.write_text(json.dumps({**contract, + "resumed_from": str(args.resume) if args.resume else None}, + indent=2) + "\n") + criterion = KeypointPretrainLoss(tuple(CONFIG["image_hw"]), + visible_weight=0, visibility_weight=0) + while start < args.updates: + end = min(args.updates, (start // args.phase_steps + 1) * args.phase_steps) + phase = (start // args.phase_steps) % PHASES + checked_index(report, args.index_root, phase) + dataset = P0Frames(phase, args.index_root, args.code_root, CONFIG["seed"]) + sampler = PositionRange(start, end, 0, 1, args.global_batch) + loader = DataLoader(dataset, batch_size=args.micro_batch, sampler=sampler, + num_workers=args.workers, pin_memory=True, + prefetch_factor=2 if args.workers else None) + iterator = iter(loader) + for step in range(start, end): + started = time.monotonic() + optimizer.zero_grad(set_to_none=True) + loss_sum, sources = 0.0, Counter() + for _ in range(args.global_batch // args.micro_batch): + batch = next(iterator) + rgb = batch["rgb"].to(args.device, non_blocking=True) + uv = batch["uv"].to(args.device, non_blocking=True) + valid = batch["valid"].to(args.device, non_blocking=True) + states = torch.full(valid.shape, UNREVIEWED, device=args.device, + dtype=torch.long) + with torch.autocast("cuda", dtype=torch.bfloat16, + enabled=args.device.startswith("cuda")): + prediction = model(rgb) + loss = sample_mean_loss(criterion, prediction, uv, valid, states) + (loss * args.micro_batch / args.global_batch).backward() + loss_sum += float(loss.detach()) * args.micro_batch / args.global_batch + sources.update(batch["source"]) + norm = torch.nn.utils.clip_grad_norm_(trainable, 1.0) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"step {step + 1}: nonfinite head gradient") + optimizer.step() + if (step + 1) % args.log_every == 0 or step == start: + entry = {"step": step + 1, "phase": phase, "loss": loss_sum, + "head_preclip_grad_norm": float(norm), + "seconds_per_step": time.monotonic() - started, + "sources": dict(sources)} + with (args.output / "train.jsonl").open("a") as stream: + stream.write(json.dumps(entry) + "\n") + print(json.dumps(entry), flush=True) + if (step + 1) % args.save_every == 0 or step + 1 == args.updates: + checkpoint = args.output / f"step_{step + 1:06d}.pt" + if checkpoint.exists(): + raise FileExistsError(checkpoint) + torch.save({"step": step + 1, "head": head_state(model), + "optimizer": optimizer.state_dict(), "contract": contract}, + checkpoint) + if (step + 1) % args.eval_every == 0 or step + 1 == args.updates: + report_out = evaluate(model, args, report, step + 1, report_sha) + evaluation = args.output / "eval" / f"step_{step + 1:06d}.json" + evaluation.parent.mkdir(exist_ok=True) + if evaluation.exists(): + raise FileExistsError(evaluation) + evaluation.write_text(json.dumps(report_out, indent=2) + "\n") + print(json.dumps({"eval_step": step + 1, + "sources": report_out["sources"]}), flush=True) + del iterator, loader, dataset + start = end + + +def main() -> None: + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest="action", required=True) + export = sub.add_parser("export") + export.add_argument("--checkpoint", type=Path, required=True) + export.add_argument("--output", type=Path, required=True) + run = sub.add_parser("train") + run.add_argument("--gkdt-checkpoint", type=Path, required=True) + run.add_argument("--visual-weights", type=Path, required=True) + run.add_argument("--dino-source", type=Path, required=True) + run.add_argument("--index-root", type=Path, required=True) + run.add_argument("--code-root", type=Path, required=True) + run.add_argument("--output", type=Path, required=True) + run.add_argument("--expected-visible-sha256", required=True) + run.add_argument("--updates", type=int, default=1000) + run.add_argument("--global-batch", type=int, default=24) + run.add_argument("--micro-batch", type=int, default=1) + run.add_argument("--phase-steps", type=int, default=625) + run.add_argument("--workers", type=int, default=2) + run.add_argument("--log-every", type=int, default=25) + run.add_argument("--save-every", type=int, default=500) + run.add_argument("--eval-every", type=int, default=500) + run.add_argument("--eval-limit-per-source", type=int, default=256) + run.add_argument("--device", default="cuda:0") + run.add_argument("--resume", type=Path) + args = parser.parse_args() + if args.action == "export": + export_visual(args.checkpoint, args.output) + else: + train(args) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/loss.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..4a25a20b984557588e673b477ea05e64026117dc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/loss.py @@ -0,0 +1,79 @@ +"""Strict masks for visible evidence versus amodal 2D inference.""" + +from __future__ import annotations + +import torch +from torch import nn +from torch.nn import functional as F + + +VISIBLE = 0 +OCCLUDED_IN_FRAME = 1 +OUT_OF_FRAME = 2 +UNKNOWN = 3 +UNREVIEWED = -1 + + +def coordinate_bins(uv: torch.Tensor, image_hw: tuple[int, int], x_bins: int, y_bins: int): + height, width = image_hw + x = (uv[..., 0] / width * x_bins).floor().long().clamp(0, x_bins - 1) + y = (uv[..., 1] / height * y_bins).floor().long().clamp(0, y_bins - 1) + return x, y + + +def masked_cross_entropy(logits: torch.Tensor, target: torch.Tensor, mask: torch.Tensor): + if not bool(mask.any()): + return logits.sum() * 0 + return F.cross_entropy(logits[mask].float(), target[mask], reduction="mean") + + +class KeypointPretrainLoss(nn.Module): + def __init__(self, image_hw=(512, 896), infer_weight=1.0, + visible_weight=0.5, visibility_weight=0.25, + allow_projected_observed=False): + super().__init__() + self.image_hw = tuple(image_hw) + self.infer_weight = infer_weight + self.visible_weight = visible_weight + self.visibility_weight = visibility_weight + self.allow_projected_observed = allow_projected_observed + + def forward(self, prediction: dict[str, torch.Tensor], uv: torch.Tensor, + geometric_valid: torch.Tensor, reviewed_state: torch.Tensor, + observed_uv: torch.Tensor | None = None): + if uv.shape[-3:] != (2, 21, 2) or geometric_valid.shape != uv.shape[:-1]: + raise ValueError("expected [B,2,21,2] uv and [B,2,21] masks") + if reviewed_state.shape != geometric_valid.shape: + raise ValueError("review state must have [B,2,21] layout") + if bool(((reviewed_state < UNREVIEWED) | (reviewed_state > UNKNOWN)).any()): + raise ValueError("invalid visibility review code") + height, width = self.image_hw + finite = torch.isfinite(uv).all(-1) + in_frame = (finite & (uv[..., 0] >= 0) & (uv[..., 0] < width) + & (uv[..., 1] >= 0) & (uv[..., 1] < height)) + if observed_uv is None: + observed_uv = uv if self.allow_projected_observed else torch.full_like(uv, float("nan")) + if observed_uv.shape != uv.shape: + raise ValueError("observed 2D coordinates must match source 2D shape") + observed_in_frame = (torch.isfinite(observed_uv).all(-1) + & (observed_uv[..., 0] >= 0) & (observed_uv[..., 0] < width) + & (observed_uv[..., 1] >= 0) & (observed_uv[..., 1] < height)) + reviewed_outside = reviewed_state == OUT_OF_FRAME + visible_mask = observed_in_frame & (reviewed_state == VISIBLE) + infer_mask = ((geometric_valid.bool() & in_frame) | visible_mask) & ~reviewed_outside + status_mask = (reviewed_state >= VISIBLE) & (reviewed_state <= OUT_OF_FRAME) + inferred_uv = torch.where(visible_mask[..., None], observed_uv, uv) + infer_x, infer_y = coordinate_bins(torch.nan_to_num(inferred_uv.float()), self.image_hw, + prediction["infer_x"].shape[-1], prediction["infer_y"].shape[-1]) + visible_x, visible_y = coordinate_bins(torch.nan_to_num(observed_uv.float()), self.image_hw, + prediction["visible_x"].shape[-1], prediction["visible_y"].shape[-1]) + infer = (masked_cross_entropy(prediction["infer_x"], infer_x, infer_mask) + + masked_cross_entropy(prediction["infer_y"], infer_y, infer_mask)) / 2 + visible = (masked_cross_entropy(prediction["visible_x"], visible_x, visible_mask) + + masked_cross_entropy(prediction["visible_y"], visible_y, visible_mask)) / 2 + status = masked_cross_entropy(prediction["visibility"], reviewed_state.clamp(0, 2), status_mask) + total = (self.infer_weight * infer + self.visible_weight * visible + + self.visibility_weight * status) + return total, {"infer": infer.detach(), "visible": visible.detach(), + "visibility": status.detach(), "infer_count": int(infer_mask.sum()), + "visible_count": int(visible_mask.sum()), "status_count": int(status_mask.sum())} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/model.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f24a147280c54f3b0beede993a80c61d4a5e0e97 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/model.py @@ -0,0 +1,86 @@ +"""Full-frame DINOv3 with separate observed and amodal 2D keypoint heads.""" + +from __future__ import annotations + +import torch +from torch import nn + +from foundation_hand.models.encoders import DinoV3Encoder + + +class KeypointDecoderLayer(nn.Module): + def __init__(self, width: int, heads: int): + super().__init__() + self.query_norm = nn.LayerNorm(width) + self.cross = nn.MultiheadAttention(width, heads, batch_first=True) + self.feed_norm = nn.LayerNorm(width) + self.feed = nn.Sequential(nn.Linear(width, width * 2), nn.GELU(), nn.Linear(width * 2, width)) + + def forward(self, queries: torch.Tensor, patches: torch.Tensor) -> torch.Tensor: + attended, _ = self.cross(self.query_norm(queries), patches, patches, need_weights=False) + queries = queries + attended + return queries + self.feed(self.feed_norm(queries)) + + +class DinoKeypointPretrainer(nn.Module): + """Coordinates are 1D distributions; unknown visibility never gets a class target.""" + + def __init__(self, dino_source: str, dino_weights: str, image_hw=(512, 896), + width: int = 512, bin_pixels: int = 4, layers: int = 2, + trainable_last_blocks: int = 2, encoder: nn.Module | None = None): + super().__init__() + height, image_width = image_hw + if height % 16 or image_width % 16 or height % bin_pixels or image_width % bin_pixels: + raise ValueError("image dimensions must align with DINO patches and coordinate bins") + self.image_hw = tuple(image_hw) + self.x_bins, self.y_bins = image_width // bin_pixels, height // bin_pixels + self.encoder = encoder if encoder is not None else DinoV3Encoder( + dino_source, dino_weights, output_dim=width, + frozen=True, trainable_last_blocks=trainable_last_blocks, + ) + self.patch_position = nn.Linear(2, width, bias=False) + self.query = nn.Parameter(torch.randn(2, 21, width) * 0.02) + self.decoder = nn.ModuleList(KeypointDecoderLayer(width, 8) for _ in range(layers)) + self.visible_x = nn.Linear(width, self.x_bins) + self.visible_y = nn.Linear(width, self.y_bins) + self.infer_x = nn.Linear(width, self.x_bins) + self.infer_y = nn.Linear(width, self.y_bins) + self.visibility = nn.Linear(width, 3) + self.set_dino_tuning(False) + + def set_dino_tuning(self, enabled: bool) -> None: + if self.encoder.trainable_last_blocks == 0: + if enabled: + raise ValueError("this encoder has no trainable DINO blocks") + self.encoder.backbone.eval() + return + for block in self.encoder._backbone_blocks()[-self.encoder.trainable_last_blocks:]: + block.requires_grad_(enabled) + self.encoder._backbone_final_norm().requires_grad_(enabled) + if not enabled: + self.encoder.backbone.eval() + + def set_auxiliary_tuning(self, enabled: bool) -> None: + for head in (self.visible_x, self.visible_y, self.visibility): + head.requires_grad_(enabled) + + def forward(self, rgb: torch.Tensor) -> dict[str, torch.Tensor]: + if rgb.ndim != 4 or tuple(rgb.shape[-2:]) != self.image_hw: + raise ValueError(f"expected [B,3,{self.image_hw[0]},{self.image_hw[1]}] RGB") + features = self.encoder(rgb) + rows, cols = features.grid_hw + y, x = torch.meshgrid( + torch.linspace(-1, 1, rows, device=rgb.device), + torch.linspace(-1, 1, cols, device=rgb.device), indexing="ij", + ) + patches = features.tokens + self.patch_position(torch.stack((x, y), dim=-1).reshape(1, -1, 2)) + batch = rgb.shape[0] + queries = self.query.reshape(1, 42, -1).expand(batch, -1, -1) + for layer in self.decoder: + queries = layer(queries, patches) + queries = queries.reshape(batch, 2, 21, -1) + return { + "visible_x": self.visible_x(queries), "visible_y": self.visible_y(queries), + "infer_x": self.infer_x(queries), "infer_y": self.infer_y(queries), + "visibility": self.visibility(queries), + } diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/pilot.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/pilot.py new file mode 100644 index 0000000000000000000000000000000000000000..f76e5065031d6a257e3c9bd4fb6a44f596f7455a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/pilot.py @@ -0,0 +1,125 @@ +"""Two-update real-data P0 smoke; not a pretraining checkpoint or performance result.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +import sys + +import torch + +from .audit import REPO, SOURCES, recording_id +from .loss import KeypointPretrainLoss, UNREVIEWED +from .model import DinoKeypointPretrainer + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) + + +def heldout_recording(source: str, recording: str) -> bool: + digest = hashlib.sha256(f"{source}/{recording}".encode()).digest() + return int.from_bytes(digest[:4], "big") % 5 == 0 + + +def source_frames(): + sys.path.insert(0, str(REPO / "experiments/u0_depthsafe")) + from common import U0Coverage, U0Dataset + + coverage, dataset = U0Coverage(), U0Dataset() + coverage.seed = CONFIG["seed"] + selected = {} + for position in range(2000): + spec = coverage.sample(position) + source = spec["source"] + if source in selected: + continue + original = dataset.sources[source] + row = original.rows[original.by_tile[spec["tile_id"]]] + if heldout_recording(source, recording_id(source, row)): + continue + sample = dataset[spec] + valid = torch.nonzero(sample["frame_valid"], as_tuple=False).flatten() + if not len(valid): + continue + frame = int(valid[len(valid) // 2]) + uv = sample["joint2d"][frame] + geometric = sample["joint2d_valid"][frame] + height, width = sample["rgb"].shape[-2:] + in_frame = (torch.isfinite(uv).all(-1) & (uv[..., 0] >= 0) & (uv[..., 0] < width) + & (uv[..., 1] >= 0) & (uv[..., 1] < height)) + geometric = geometric & in_frame + if geometric.sum() < 4: + continue + selected[source] = { + "rgb": sample["rgb"][frame].unsqueeze(0), + "uv": uv.unsqueeze(0), "geometric": geometric.unsqueeze(0), + "states": torch.full((1, 2, 21), UNREVIEWED, dtype=torch.long), + "recording": recording_id(source, row), "frame_id": int(sample["frame_id"][frame]), + } + if len(selected) == len(SOURCES): + break + if set(selected) != set(SOURCES): + raise RuntimeError(f"missing training-side sample for {set(SOURCES) - set(selected)}") + return selected + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + if not torch.cuda.is_available() or not args.device.startswith("cuda"): + raise RuntimeError("real-data DINOv3 pilot requires CUDA") + torch.manual_seed(CONFIG["seed"]) + torch.set_num_threads(2) + data = source_frames() + device = torch.device(args.device) + model = DinoKeypointPretrainer( + CONFIG["dino_source"], CONFIG["dino_weights"], tuple(CONFIG["image_hw"]), + width=CONFIG["model_width"], bin_pixels=CONFIG["bin_pixels"], + ).to(device).train() + model.set_dino_tuning(False) + model.set_auxiliary_tuning(False) + criterion = KeypointPretrainLoss(tuple(CONFIG["image_hw"]), + visible_weight=0, visibility_weight=0) + optimizer = torch.optim.AdamW( + [parameter for parameter in model.parameters() if parameter.requires_grad], + lr=CONFIG["pilot"]["learning_rate"], weight_decay=CONFIG["pilot"]["weight_decay"], + ) + report = {"kind": "P0_two_update_pipeline_smoke_not_pretraining_performance", + "dino_backbone_trainable": sum(p.numel() for p in model.encoder.backbone.parameters() if p.requires_grad), + "samples": {source: {key: value for key, value in sample.items() if key in {"recording", "frame_id"}} + for source, sample in data.items()}, "updates": []} + weights = CONFIG["source_quota_per_60"] + for update in range(2): + optimizer.zero_grad(set_to_none=True) + source_loss, supervised = {}, {} + for source in SOURCES: + sample = data[source] + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(sample["rgb"].to(device)) + loss, details = criterion(prediction, sample["uv"].to(device), + sample["geometric"].to(device), sample["states"].to(device)) + if not bool(torch.isfinite(loss)) or details["infer_count"] == 0: + raise RuntimeError(f"{source} P0 coordinate supervision is empty or nonfinite") + (loss * weights[source] / 60).backward() + source_loss[source] = float(loss.detach()) + supervised[source] = details["infer_count"] + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), CONFIG["pilot"]["grad_clip_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite P0 gradient") + optimizer.step() + report["updates"].append({"update": update + 1, "source_loss": source_loss, + "infer_joint_count": supervised, "preclip_grad_norm": float(norm)}) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/preflight_reader.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/preflight_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..9b9da4b80471faf94917bda946a859f3284ade20 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/preflight_reader.py @@ -0,0 +1,147 @@ +"""Exercise the frozen P0 train/dev readers without using a GPU.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +from pathlib import Path +import sys + +import numpy as np +from PIL import Image, ImageDraw +import torch +from torch.utils.data import DataLoader, Dataset + + +SOURCES = ("H2O", "ARCTIC", "HOT3D") + + +class SelectedFrames(Dataset): + def __init__(self, source_dataset, source: str): + self.dataset = source_dataset + self.source = source + length = len(source_dataset) + self.indices = sorted(set(np.linspace(0, length - 1, 12, dtype=int).tolist())) + + def __len__(self): + return len(self.indices) + + def __getitem__(self, index): + row = self.dataset.rows[self.indices[index]] + spec = {"position": self.indices[index], "source": self.source, + "source_ordinal": self.indices[index], "epoch": 0, + "tile_id": row["filtered_tile_id"], "mode": "rgb"} + return self.dataset[spec] + + +def list_collate(batch): + return batch + + +def save_overlay(sample: dict, path: Path) -> None: + from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD + + rgb = sample["rgb"][0].numpy().transpose(1, 2, 0) + image = Image.fromarray(np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype("uint8")) + draw = ImageDraw.Draw(image) + uv = sample["joint2d"][0].numpy() + mask = sample["joint2d_valid"][0].numpy().astype(bool) + for side, color in enumerate(("#eb6b36", "#26a881")): + for point, valid in zip(uv[side], mask[side]): + if not valid or not np.isfinite(point).all(): + continue + x, y = map(float, point) + if 0 <= x < image.width and 0 <= y < image.height: + draw.ellipse((x - 3, y - 3, x + 3, y + 3), fill=color, outline="black") + image.save(path) + + +def inspect_sample(sample: dict, source: str) -> dict: + rgb = sample["rgb"] + uv = sample["joint2d"] + valid = sample["joint2d_valid"].bool() + if rgb.shape != (1, 3, 512, 896) or uv.shape != (1, 2, 21, 2) or valid.shape != (1, 2, 21): + raise ValueError(f"{source}: incorrect RGB/2D/mask shape") + if not torch.isfinite(rgb).all() or not bool(sample["frame_valid"].all()): + raise ValueError(f"{source}: nonfinite RGB or invalid frame") + height, width = rgb.shape[-2:] + in_frame = (torch.isfinite(uv).all(-1) & (uv[..., 0] >= 0) & (uv[..., 0] < width) + & (uv[..., 1] >= 0) & (uv[..., 1] < height)) + supervised = valid & in_frame + xyz = sample["joint3d_camera"] + K = sample["K"] + projected = xyz @ K.transpose(-1, -2).unsqueeze(1) + reprojected = projected[..., :2] / projected[..., 2:].clamp_min(1e-8) + comparable = supervised & torch.isfinite(reprojected).all(-1) & (xyz[..., 2] > 0) + difference = torch.linalg.vector_norm(uv - reprojected, dim=-1) + return {"joint2d_valid": int(valid.sum()), "p0_in_frame": int(supervised.sum()), + "out_of_frame_valid_excluded": int((valid & ~in_frame).sum()), + "reprojection_count": int(comparable.sum()), + "reprojection_max_px": float(difference[comparable].max()) if comparable.any() else None, + "frame_id": int(sample["frame_id"][0]), + "tile_id": sample["filtered_tile_id"]} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", type=Path, required=True) + parser.add_argument("--code-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--phase", type=int, choices=range(8)) + parser.add_argument("--num-workers", type=int, default=1) + args = parser.parse_args() + sys.path.insert(0, str(args.code_root)) + sys.path.insert(0, str(args.code_root / "src")) + from filtered_dataset import FilteredClipDataset + + if args.output.exists(): + raise FileExistsError(args.output) + args.output.mkdir(parents=True) + report = {"kind": "visible_P0_target_reader_cpu_preflight", + "phase": args.phase, "sources": {}} + smoke_samples = {} + for source in SOURCES: + report["sources"][source] = {} + for role in ("train", "dev"): + suffix = f"_phase{args.phase}" if args.phase is not None else "" + manifest = args.manifests / f"{source.lower()}_{role}{suffix}_t1.jsonl" + dataset = FilteredClipDataset( + source, manifest, 1, (512, 896), + "/SSD3/jiasen/foundation_hand/pretrained/mano", + args.code_root / "third_party", photometric_augmentation=None, + ) + loader = DataLoader(SelectedFrames(dataset, source), batch_size=2, + num_workers=args.num_workers, collate_fn=list_collate) + rows = [] + for batch in loader: + for sample in batch: + rows.append(inspect_sample(sample, source)) + if rows[-1]["p0_in_frame"] and not (args.output / f"{source.lower()}_{role}.jpg").exists(): + save_overlay(sample, args.output / f"{source.lower()}_{role}.jpg") + smoke_samples[f"{source}_{role}"] = { + "rgb": sample["rgb"][0].clone(), + "uv": sample["joint2d"][0].clone(), + "valid": sample["joint2d_valid"][0].clone(), + "tile_id": sample["filtered_tile_id"], + } + report["sources"][source][role] = { + "total_t1_rows": len(dataset), "checked": len(rows), + "empty_target_frames": sum(row["p0_in_frame"] == 0 for row in rows), + "counts": dict(sum((Counter({"valid": row["joint2d_valid"], + "p0": row["p0_in_frame"], + "excluded": row["out_of_frame_valid_excluded"]}) + for row in rows), Counter())), + "max_reprojection_px": max((row["reprojection_max_px"] or 0) for row in rows), + "samples": rows, + } + torch.save(smoke_samples, args.output / "smoke_samples.pt") + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({source: {role: {key: value[key] for key in + ("checked", "empty_target_frames", "max_reprojection_px")} + for role, value in roles.items()} + for source, roles in report["sources"].items()})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/review_template.html b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/review_template.html new file mode 100644 index 0000000000000000000000000000000000000000..8481e79922960baf15b5a035dde1ae7b258a1086 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/review_template.html @@ -0,0 +1,149 @@ + + + + + + Keypoint Visibility Review + + + +
+

Visibility Review

+ + + + + + + +
+
+
+ + Full-frame hand image with optional projected joints +
+ +
+ + + diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/smoke_ddp.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/smoke_ddp.py new file mode 100644 index 0000000000000000000000000000000000000000..54be8886ea468a3b22bc93140e4ee800747a52e8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/smoke_ddp.py @@ -0,0 +1,102 @@ +"""Two-update DDP health check on decoded visible-filter RGB/2D samples.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path + +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader, Dataset, DistributedSampler + +from .loss import KeypointPretrainLoss, UNREVIEWED +from .model import DinoKeypointPretrainer + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) + + +class SmokeFrames(Dataset): + def __init__(self, path: Path): + saved = torch.load(path, map_location="cpu", weights_only=True) + self.rows = [(source, saved[f"{source}_train"]) for source in ("H2O", "ARCTIC", "HOT3D")] + if any(int(row["valid"].sum()) == 0 for _, row in self.rows): + raise ValueError("smoke cache contains an empty 2D target") + + def __len__(self): + return len(self.rows) + + def __getitem__(self, index): + source, row = self.rows[index] + return source, row["rgb"], row["uv"], row["valid"] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--samples", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + rank = int(os.environ["RANK"]) + local_rank = int(os.environ["LOCAL_RANK"]) + torch.cuda.set_device(local_rank) + dist.init_process_group("nccl") + torch.manual_seed(CONFIG["seed"]) + torch.set_num_threads(2) + dataset = SmokeFrames(args.samples) + sampler = DistributedSampler(dataset, shuffle=True, seed=CONFIG["seed"], drop_last=False) + loader = DataLoader(dataset, batch_size=1, sampler=sampler, num_workers=0) + model = DinoKeypointPretrainer( + CONFIG["dino_source"], CONFIG["dino_weights"], tuple(CONFIG["image_hw"]), + width=CONFIG["model_width"], bin_pixels=CONFIG["bin_pixels"], + ).cuda(local_rank).train() + model.set_dino_tuning(False) + model.set_auxiliary_tuning(False) + model = DistributedDataParallel(model, device_ids=[local_rank]) + criterion = KeypointPretrainLoss(tuple(CONFIG["image_hw"]), + visible_weight=0, visibility_weight=0) + optimizer = torch.optim.AdamW( + [parameter for parameter in model.parameters() if parameter.requires_grad], + lr=CONFIG["pilot"]["learning_rate"], + weight_decay=CONFIG["pilot"]["weight_decay"], + ) + iterator = iter(loader) + updates = [] + for step in range(2): + try: + source, rgb, uv, valid = next(iterator) + except StopIteration: + iterator = iter(loader) + source, rgb, uv, valid = next(iterator) + device = torch.device("cuda", local_rank) + rgb, uv, valid = rgb.to(device), uv.to(device), valid.to(device) + states = torch.full(valid.shape, UNREVIEWED, device=device, dtype=torch.long) + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(rgb) + loss, detail = criterion(prediction, uv, valid, states) + if not bool(torch.isfinite(loss)) or detail["infer_count"] == 0: + raise RuntimeError(f"rank {rank}: empty or nonfinite P0 loss") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), CONFIG["pilot"]["grad_clip_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"rank {rank}: nonfinite gradient") + optimizer.step() + updates.append({"step": step + 1, "rank": rank, "source": source[0], + "loss": float(loss.detach()), "valid_joints": detail["infer_count"], + "preclip_grad_norm": float(norm)}) + gathered = [None] * dist.get_world_size() + dist.all_gather_object(gathered, updates) + if rank == 0: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps({"kind": "P0_visible_target_DDP_smoke_not_pretraining", + "world_size": dist.get_world_size(), + "updates": gathered}, indent=2) + "\n") + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/train_p0.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/train_p0.py new file mode 100644 index 0000000000000000000000000000000000000000..646e5837eff9c8a1c085696f75949a1228e0961f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/train_p0.py @@ -0,0 +1,296 @@ +"""Full-frame-pool P0a training; no MANO, teacher, or visibility loss.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +import hashlib +import json +import os +from pathlib import Path +import random +import sys +import time + +import numpy as np +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader, Dataset, Sampler + +from .full_index import PHASES +from .loss import KeypointPretrainLoss, UNREVIEWED +from .model import DinoKeypointPretrainer +from .visible_index import SOURCES, sha256 + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +QUOTAS = CONFIG["source_quota_per_60"] +SOURCE_CYCLE = sum(QUOTAS.values()) + + +def source_and_ordinal(position: int, seed: int = CONFIG["seed"]) -> tuple[str, int]: + cycle, slot = divmod(position, SOURCE_CYCLE) + order = [source for source in SOURCES for _ in range(QUOTAS[source])] + random.Random(int.from_bytes(hashlib.blake2b(f"{seed}/{cycle}".encode(), + digest_size=8).digest(), "little")).shuffle(order) + source = order[slot] + return source, cycle * QUOTAS[source] + order[:slot].count(source) + + +def is_expected_hot3d_sync_error(source: str, error: RuntimeError) -> bool: + return source == "HOT3D" and str(error).startswith("HOT3D 20ms synchronization failure ") + + +class P0Frames(Dataset): + def __init__(self, phase: int, index_root: Path, code_root: Path, seed: int): + sys.path.insert(0, str(code_root)) + sys.path.insert(0, str(code_root / "src")) + from filtered_dataset import FilteredClipDataset + + self.phase, self.seed = phase, seed + self.sources = { + source: FilteredClipDataset( + source, index_root / f"{source.lower()}_train_phase{phase}_t1.jsonl", + 1, tuple(CONFIG["image_hw"]), + "/SSD3/jiasen/foundation_hand/pretrained/mano", code_root / "third_party", + {"enabled": source != "HOT3D", "probability": 0.8}, + ) for source in SOURCES + } + self.orders = {} + + def __len__(self): + return sum(len(dataset) for dataset in self.sources.values()) + + def order(self, source: str, epoch: int): + key = source, epoch + if key not in self.orders: + digest = hashlib.blake2b(f"{self.seed}/{self.phase}/{source}/{epoch}".encode(), + digest_size=8).digest() + self.orders[key] = np.random.default_rng(int.from_bytes(digest, "little")).permutation( + len(self.sources[source])) + return self.orders[key] + + def __getitem__(self, position: int): + source, ordinal = source_and_ordinal(int(position), self.seed) + dataset = self.sources[source] + size = len(dataset) + epoch, offset = divmod(ordinal, size) + order = self.order(source, epoch) + height, width = CONFIG["image_hw"] + empty_retries, sync_retries, sync_bad_tiles = 0, 0, [] + for retry in range(16): + index = int(order[(offset + retry) % size]) + row = dataset.rows[index] + spec = {"position": int(position), "source": source, + "source_ordinal": ordinal, "epoch": epoch, + "tile_id": row["filtered_tile_id"], "mode": "rgb"} + try: + sample = dataset[spec] + except RuntimeError as error: + if not is_expected_hot3d_sync_error(source, error): + raise + sync_retries += 1 + sync_bad_tiles.append(row["filtered_tile_id"]) + continue + uv = sample["joint2d"][0] + valid = sample["joint2d_valid"][0].bool() + in_frame = (torch.isfinite(uv).all(-1) & (uv[..., 0] >= 0) & (uv[..., 0] < width) + & (uv[..., 1] >= 0) & (uv[..., 1] < height)) + valid &= in_frame + if bool(valid.any()): + return {"rgb": sample["rgb"][0], "uv": uv, "valid": valid, + "source": source, "tile_id": row["filtered_tile_id"], + "empty_retry": empty_retries, "sync_retry": sync_retries, + "sync_bad_tiles": json.dumps(sync_bad_tiles)} + empty_retries += 1 + raise RuntimeError(f"{source} position {position}: 16 unusable 2D/sync targets; " + f"empty={empty_retries}, sync={sync_retries}") + + +class PositionRange(Sampler[int]): + def __init__(self, start_step: int, end_step: int, rank: int, world_size: int, + global_batch: int): + self.first = start_step * global_batch + rank + self.stop = end_step * global_batch + self.world_size = world_size + + def __iter__(self): + return iter(range(self.first, self.stop, self.world_size)) + + def __len__(self): + return len(range(self.first, self.stop, self.world_size)) + + +def checked_index(report: dict, index_root: Path, phase: int) -> None: + for source in SOURCES: + path = index_root / f"{source.lower()}_train_phase{phase}_t1.jsonl" + expected = report["manifests"][f"{source}/train/phase{phase}"]["sha256"] + if sha256(path) != expected: + raise ValueError(f"changed P0 phase manifest: {path}") + + +def save_checkpoint(path: Path, model, optimizer, step: int, report_sha: str) -> None: + state = {"step": step, "model": model.module.state_dict(), + "optimizer": optimizer.state_dict(), "index_report_sha256": report_sha, + "config": {"stage": "P0a", "seed": CONFIG["seed"], + "source_quota_per_60": QUOTAS, "image_hw": CONFIG["image_hw"], + "full_model_state": True}} + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + + +def train(args): + rank = int(os.environ["RANK"]) + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + if world_size != 2 or args.global_batch % world_size: + raise ValueError("G1 P0a contract requires two ranks and divisible global batch") + torch.cuda.set_device(local_rank) + dist.init_process_group("nccl") + torch.manual_seed(CONFIG["seed"]) + torch.set_num_threads(2) + index_report = args.index_root / "index_report.json" + report_sha = sha256(index_report) + report = json.loads(index_report.read_text()) + if report["visible_manifest_sha256"] != args.expected_visible_sha256: + raise ValueError("P0 index is bound to the wrong visible data") + model = DinoKeypointPretrainer( + CONFIG["dino_source"], CONFIG["dino_weights"], tuple(CONFIG["image_hw"]), + width=CONFIG["model_width"], bin_pixels=CONFIG["bin_pixels"], + ).cuda(local_rank).train() + model.set_dino_tuning(False) + model.set_auxiliary_tuning(False) + optimizer = torch.optim.AdamW( + [parameter for parameter in model.parameters() if parameter.requires_grad], + lr=1e-4, weight_decay=0.05, + ) + start_step = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False) + if state["index_report_sha256"] != report_sha or not state["config"]["full_model_state"]: + raise ValueError("resume checkpoint/index composition mismatch") + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + start_step = int(state["step"]) + model = DistributedDataParallel(model, device_ids=[local_rank]) + criterion = KeypointPretrainLoss(tuple(CONFIG["image_hw"]), + visible_weight=0, visibility_weight=0) + if rank == 0: + if args.output.exists() and not args.resume: + raise FileExistsError(args.output) + args.output.mkdir(parents=True, exist_ok=True) + (args.output / "run_contract.json").write_text(json.dumps({ + "stage": "P0a", "visible_manifest_sha256": args.expected_visible_sha256, + "index_report_sha256": report_sha, "global_batch": args.global_batch, + "world_size": world_size, "updates": args.updates, + "phase_steps": args.phase_steps, "source_quota_per_60": QUOTAS, + "teacher_loss": False, "visible_loss": False, "visibility_loss": False, + "dino_backbone_trainable": 0, "full_model_checkpoint": True, + }, indent=2) + "\n") + dist.barrier() + accumulation = args.global_batch // world_size + device = torch.device("cuda", local_rank) + boundaries = [] + current = start_step + while current < args.updates: + end = min(args.updates, (current // args.phase_steps + 1) * args.phase_steps) + boundaries.append((current, end)) + current = end + empty_total, sync_total = 0, 0 + bad_tiles_since_log = set() + for start, end in boundaries: + phase = (start // args.phase_steps) % PHASES + checked_index(report, args.index_root, phase) + dataset = P0Frames(phase, args.index_root, args.code_root, CONFIG["seed"]) + sampler = PositionRange(start, end, rank, world_size, args.global_batch) + kwargs = {"batch_size": 1, "sampler": sampler, "num_workers": args.workers, + "pin_memory": True} + if args.workers: + kwargs["prefetch_factor"] = 2 + loader = DataLoader(dataset, **kwargs) + iterator = iter(loader) + for step in range(start, end): + started = time.monotonic() + optimizer.zero_grad(set_to_none=True) + loss_sum, empty_retry_sum, sync_retry_sum, by_source = 0.0, 0, 0, Counter() + bad_tiles = set() + for micro in range(accumulation): + batch = next(iterator) + rgb = batch["rgb"].to(device, non_blocking=True) + uv = batch["uv"].to(device, non_blocking=True) + valid = batch["valid"].to(device, non_blocking=True) + states = torch.full(valid.shape, UNREVIEWED, device=device, dtype=torch.long) + context = model.no_sync() if micro < accumulation - 1 else nullcontext() + with context: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(rgb) + loss, details = criterion(prediction, uv, valid, states) + if not bool(torch.isfinite(loss)) or details["infer_count"] == 0: + raise RuntimeError(f"step {step + 1}: empty or nonfinite P0 coordinate loss") + (loss / accumulation).backward() + loss_sum += float(loss.detach()) / accumulation + empty_retry_sum += int(batch["empty_retry"][0]) + sync_retry_sum += int(batch["sync_retry"][0]) + bad_tiles.update(json.loads(batch["sync_bad_tiles"][0])) + by_source[batch["source"][0]] += 1 + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"step {step + 1}: nonfinite P0 gradient") + optimizer.step() + empty_total += empty_retry_sum + sync_total += sync_retry_sum + bad_tiles_since_log.update(bad_tiles) + if (step + 1) % args.log_every == 0 or step == start or step + 1 == args.updates: + values = torch.tensor([loss_sum, empty_retry_sum, sync_retry_sum, + empty_total, sync_total], device=device) + dist.all_reduce(values) + gathered_bad_tiles = [None] * world_size + dist.all_gather_object(gathered_bad_tiles, sorted(bad_tiles_since_log)) + if rank == 0: + all_bad_tiles = sorted(set().union(*gathered_bad_tiles)) + entry = {"step": step + 1, "phase": phase, + "loss": float(values[0] / world_size), + "empty_target_retries": int(values[1]), + "hot3d_sync_retries": int(values[2]), + "empty_target_retries_total": int(values[3]), + "hot3d_sync_retries_total": int(values[4]), + "hot3d_sync_bad_tiles": all_bad_tiles, + "preclip_grad_norm": float(norm), + "seconds_per_step": time.monotonic() - started, + "rank0_sources": dict(by_source)} + with (args.output / "train.jsonl").open("a") as stream: + stream.write(json.dumps(entry) + "\n") + print(json.dumps(entry), flush=True) + bad_tiles_since_log.clear() + if (step + 1) % args.save_every == 0 or step + 1 == args.updates: + dist.barrier() + if rank == 0: + save_checkpoint(args.output / f"step_{step + 1:06d}.pt", + model, optimizer, step + 1, report_sha) + dist.barrier() + del iterator, loader, dataset + dist.destroy_process_group() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--index-root", type=Path, required=True) + parser.add_argument("--code-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--expected-visible-sha256", required=True) + parser.add_argument("--updates", type=int, default=5000) + parser.add_argument("--global-batch", type=int, default=24) + parser.add_argument("--phase-steps", type=int, default=625) + parser.add_argument("--workers", type=int, default=1) + parser.add_argument("--log-every", type=int, default=50) + parser.add_argument("--save-every", type=int, default=1000) + parser.add_argument("--resume", type=Path) + train(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/train_p0b.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/train_p0b.py new file mode 100644 index 0000000000000000000000000000000000000000..5de6a443f25cb1c68e864fe04e23272bece32533 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/train_p0b.py @@ -0,0 +1,288 @@ +"""Matched P0b last-two-block and frozen-backbone 2D continuation.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +import inspect +import json +import math +import os +from pathlib import Path +import subprocess +import sys +import time + +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from .full_index import PHASES +from .loss import KeypointPretrainLoss, UNREVIEWED +from .model import DinoKeypointPretrainer +from .train_p0 import CONFIG, QUOTAS, P0Frames, PositionRange, checked_index +from .visible_index import SOURCES, sha256 + + +def lr_multiplier(step: int, warmup: int, schedule_total: int) -> float: + """One-based linear warmup followed by cosine decay to zero.""" + if not 0 <= step < schedule_total or not 0 < warmup < schedule_total: + raise ValueError("invalid P0b schedule step or bounds") + if step < warmup: + return (step + 1) / warmup + progress = (step + 1 - warmup) / (schedule_total - warmup) + return 0.5 * (1.0 + math.cos(math.pi * progress)) + + +def trainable_groups(model: DinoKeypointPretrainer, arm: str): + if arm not in {"tuned", "frozen"}: + raise ValueError(f"unknown P0b arm: {arm}") + model.set_dino_tuning(arm == "tuned") + model.set_auxiliary_tuning(False) + backbone_ids = {id(parameter) for parameter in model.encoder.backbone.parameters()} + dino = [parameter for parameter in model.encoder.backbone.parameters() + if parameter.requires_grad] + head = [parameter for parameter in model.parameters() + if parameter.requires_grad and id(parameter) not in backbone_ids] + expected_dino = (list(model.encoder._backbone_blocks()[-2:].parameters()) + + list(model.encoder._backbone_final_norm().parameters())) + if arm == "tuned" and {id(parameter) for parameter in dino} != { + id(parameter) for parameter in expected_dino}: + raise AssertionError("P0b DINO trainable set is not exactly last-2 plus final norm") + if arm == "frozen" and dino: + raise AssertionError("frozen control unexpectedly trains DINO") + if not head or any(parameter.requires_grad for module in + (model.visible_x, model.visible_y, model.visibility) + for parameter in module.parameters()): + raise AssertionError("P0b head partition or auxiliary freeze is invalid") + return head, dino + + +def save_checkpoint(path: Path, model: DistributedDataParallel, optimizer, + step: int, contract: dict, counters: dict) -> None: + state = {"step": step, "model": model.module.state_dict(), + "optimizer": optimizer.state_dict(), + "index_report_sha256": contract["index_report_sha256"], + "config": {**contract, "full_model_state": True}, + "retry_counters": counters} + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + + +def run_eval(args, checkpoint: Path, step: int) -> int: + destination = args.output / "eval" + destination.mkdir(parents=True, exist_ok=True) + command = [sys.executable, "-m", "experiments.dinov3_2d_pretrain.eval_p0", + "--checkpoint", str(checkpoint), "--index-root", str(args.index_root), + "--code-root", str(args.code_root), "--output", + str(destination / f"step_{step:06d}.json"), "--limit-per-source", + str(args.eval_limit_per_source), "--batch-size", "2", "--workers", "0", + "--device", "cuda:0"] + with (destination / f"step_{step:06d}.log").open("w") as stream: + return subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, + check=False).returncode + + +def train(args) -> None: + rank = int(os.environ["RANK"]) + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + if world_size != 2 or args.global_batch % world_size: + raise ValueError("P0b requires two ranks and a divisible global batch") + if not 0 < args.updates <= args.schedule_total or not 0 < args.warmup < args.schedule_total: + raise ValueError("invalid P0b update budget or schedule") + if args.eval_every and args.eval_every % args.save_every: + raise ValueError("checkpoint interval must divide the evaluation interval") + encoder_path = Path(inspect.getfile(DinoKeypointPretrainer.__init__.__globals__["DinoV3Encoder"])).resolve() + if not encoder_path.is_relative_to((args.code_root / "src").resolve()): + raise RuntimeError(f"wrong foundation_hand encoder import: {encoder_path}") + torch.cuda.set_device(local_rank) + dist.init_process_group("nccl", timeout=timedelta(minutes=30)) + torch.manual_seed(CONFIG["seed"]) + torch.set_num_threads(2) + + index_path = args.index_root / "index_report.json" + report_sha = sha256(index_path) + report = json.loads(index_path.read_text()) + if report["visible_manifest_sha256"] != args.expected_visible_sha256: + raise ValueError("P0b index is bound to the wrong visible data") + parent_sha = sha256(args.parent_checkpoint) + parent = torch.load(args.parent_checkpoint, map_location="cpu", weights_only=False) + if (parent["index_report_sha256"] != report_sha + or parent["step"] != 5000 or parent["config"]["stage"] != "P0a" + or not parent["config"]["full_model_state"]): + raise ValueError("P0b parent is not the complete P0a 5K checkpoint on this index") + model = DinoKeypointPretrainer( + CONFIG["dino_source"], CONFIG["dino_weights"], tuple(CONFIG["image_hw"]), + width=CONFIG["model_width"], bin_pixels=CONFIG["bin_pixels"], + ).cuda(local_rank).train() + model.load_state_dict(parent["model"], strict=True) + head, dino = trainable_groups(model, args.arm) + groups = [{"params": head, "lr": args.head_lr, "base_lr": args.head_lr, + "name": "head"}] + if dino: + groups.append({"params": dino, "lr": args.dino_lr, "base_lr": args.dino_lr, + "name": "dino_last2_norm"}) + optimizer = torch.optim.AdamW(groups, weight_decay=0.05) + contract = {"stage": "P0b", "arm": args.arm, + "parent_checkpoint": str(args.parent_checkpoint), + "parent_sha256": parent_sha, "parent_step": 5000, + "visible_manifest_sha256": args.expected_visible_sha256, + "index_report_sha256": report_sha, + "global_batch": args.global_batch, "world_size": world_size, + "source_quota_per_60": QUOTAS, "image_hw": CONFIG["image_hw"], + "head_lr": args.head_lr, "dino_lr": args.dino_lr if dino else 0.0, + "warmup": args.warmup, "schedule_total": args.schedule_total, + "save_every": args.save_every, "eval_every": args.eval_every, + "eval_limit_per_source": args.eval_limit_per_source, + "teacher_loss": False, "visible_loss": False, + "visibility_loss": False, "trainable_head_parameters": sum(p.numel() for p in head), + "trainable_dino_parameters": sum(p.numel() for p in dino)} + start_step = 0 + empty_total = sync_total = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False) + if any(state["config"].get(key) != value for key, value in contract.items()): + raise ValueError("P0b resume contract mismatch") + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + start_step = int(state["step"]) + empty_total = int(state["retry_counters"]["empty_target"][rank]) + sync_total = int(state["retry_counters"]["hot3d_sync"][rank]) + if not 0 <= start_step < args.updates: + raise ValueError("P0b resume step is outside requested update range") + if rank == 0: + if args.output.exists() and not args.resume: + raise FileExistsError(args.output) + args.output.mkdir(parents=True, exist_ok=True) + (args.output / "run_contract.json").write_text(json.dumps(contract, indent=2) + "\n") + dist.barrier() + del parent + model = DistributedDataParallel(model, device_ids=[local_rank]) + criterion = KeypointPretrainLoss(tuple(CONFIG["image_hw"]), + visible_weight=0, visibility_weight=0) + accumulation = args.global_batch // world_size + device = torch.device("cuda", local_rank) + start = start_step + while start < args.updates: + end = min(args.updates, ((start // args.phase_steps) + 1) * args.phase_steps) + phase = (start // args.phase_steps) % PHASES + checked_index(report, args.index_root, phase) + dataset = P0Frames(phase, args.index_root, args.code_root, CONFIG["seed"]) + sampler = PositionRange(start, end, rank, world_size, args.global_batch) + loader_args = {"batch_size": 1, "sampler": sampler, + "num_workers": args.workers, "pin_memory": True} + if args.workers: + loader_args["prefetch_factor"] = 2 + loader = DataLoader(dataset, **loader_args) + iterator = iter(loader) + for step in range(start, end): + started = time.monotonic() + factor = lr_multiplier(step, args.warmup, args.schedule_total) + for group in optimizer.param_groups: + group["lr"] = group["base_lr"] * factor + optimizer.zero_grad(set_to_none=True) + loss_sum, empty_retries, sync_retries = 0.0, 0, 0 + by_source = Counter() + for micro in range(accumulation): + batch = next(iterator) + rgb = batch["rgb"].to(device, non_blocking=True) + uv = batch["uv"].to(device, non_blocking=True) + valid = batch["valid"].to(device, non_blocking=True) + states = torch.full(valid.shape, UNREVIEWED, device=device, dtype=torch.long) + context = model.no_sync() if micro < accumulation - 1 else nullcontext() + with context: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(rgb) + loss, details = criterion(prediction, uv, valid, states) + if not bool(torch.isfinite(loss)) or details["infer_count"] == 0: + raise RuntimeError(f"step {step + 1}: empty or nonfinite P0b loss") + (loss / accumulation).backward() + loss_sum += float(loss.detach()) / accumulation + empty_retries += int(batch["empty_retry"][0]) + sync_retries += int(batch["sync_retry"][0]) + by_source[batch["source"][0]] += 1 + head_norm = torch.nn.utils.clip_grad_norm_(head, 1.0) + dino_norm = torch.nn.utils.clip_grad_norm_(dino, 1.0) if dino else torch.zeros((), device=device) + if not bool(torch.isfinite(head_norm)) or not bool(torch.isfinite(dino_norm)): + raise RuntimeError(f"step {step + 1}: nonfinite P0b gradient") + if dino and step == 0 and not bool(dino_norm > 0): + raise RuntimeError("P0b DINO last-2 received no gradient") + optimizer.step() + empty_total += empty_retries + sync_total += sync_retries + if (step + 1) % args.log_every == 0 or step == start or step + 1 == args.updates: + values = torch.tensor([loss_sum, empty_retries, sync_retries, + empty_total, sync_total], device=device) + dist.all_reduce(values) + if rank == 0: + entry = {"step": step + 1, "phase": phase, + "loss": float(values[0] / world_size), + "head_lr": optimizer.param_groups[0]["lr"], + "dino_lr": optimizer.param_groups[1]["lr"] if dino else 0.0, + "head_preclip_grad_norm": float(head_norm), + "dino_preclip_grad_norm": float(dino_norm), + "empty_target_retries": int(values[1]), + "hot3d_sync_retries": int(values[2]), + "empty_target_retries_total": int(values[3]), + "hot3d_sync_retries_total": int(values[4]), + "seconds_per_step": time.monotonic() - started, + "rank0_sources": dict(by_source)} + with (args.output / "train.jsonl").open("a") as stream: + stream.write(json.dumps(entry) + "\n") + print(json.dumps(entry), flush=True) + save = (step + 1) % args.save_every == 0 or step + 1 == args.updates + if save: + dist.barrier() + checkpoint = args.output / f"step_{step + 1:06d}.pt" + local_counters = torch.tensor([empty_total, sync_total], device=device) + gathered_counters = [torch.empty_like(local_counters) for _ in range(world_size)] + dist.all_gather(gathered_counters, local_counters) + if rank == 0: + save_checkpoint(checkpoint, model, optimizer, step + 1, contract, + {"empty_target": [int(row[0]) for row in gathered_counters], + "hot3d_sync": [int(row[1]) for row in gathered_counters]}) + dist.barrier() + if args.eval_every and (step + 1) % args.eval_every == 0: + status = torch.zeros((), dtype=torch.int32, device=device) + if rank == 0: + torch.cuda.empty_cache() + status.fill_(run_eval(args, checkpoint, step + 1)) + dist.broadcast(status, src=0) + if int(status) != 0: + raise RuntimeError(f"P0b evaluation failed at step {step + 1}") + del iterator, loader, dataset + start = end + dist.destroy_process_group() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--arm", choices=("tuned", "frozen"), required=True) + parser.add_argument("--parent-checkpoint", type=Path, required=True) + parser.add_argument("--index-root", type=Path, required=True) + parser.add_argument("--code-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--expected-visible-sha256", required=True) + parser.add_argument("--updates", type=int, default=30000) + parser.add_argument("--global-batch", type=int, default=24) + parser.add_argument("--phase-steps", type=int, default=625) + parser.add_argument("--warmup", type=int, default=1000) + parser.add_argument("--schedule-total", type=int, default=80000) + parser.add_argument("--head-lr", type=float, default=5e-5) + parser.add_argument("--dino-lr", type=float, default=1e-6) + parser.add_argument("--save-every", type=int, default=2000) + parser.add_argument("--eval-every", type=int, default=2000) + parser.add_argument("--eval-limit-per-source", type=int, default=256) + parser.add_argument("--log-every", type=int, default=25) + parser.add_argument("--workers", type=int, default=1) + parser.add_argument("--resume", type=Path) + train(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/visible_index.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/visible_index.py new file mode 100644 index 0000000000000000000000000000000000000000..3e862cf8672cd078fe60972048c70593a476e54c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/visible_index.py @@ -0,0 +1,133 @@ +"""Bind the existing T=1 source readers to the frozen visible-filter GT.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +import hashlib +import json +from pathlib import Path + + +SOURCES = ("H2O", "ARCTIC", "HOT3D") +RECORDING_KEY = {"H2O": "take", "ARCTIC": "physical_recording_id", "HOT3D": "recording_id"} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_jsonl(path: Path): + with path.open(encoding="utf-8") as stream: + for line in stream: + if line.strip(): + yield json.loads(line) + + +def heldout_recording(source: str, recording: str) -> bool: + digest = hashlib.sha256(f"{source}/{recording}".encode()).digest() + return int.from_bytes(digest[:4], "big") % 5 == 0 + + +def visible_children(path: Path) -> dict[tuple[str, str], list[dict]]: + parents = defaultdict(list) + for child in read_jsonl(path): + source = child["dataset"] + if source not in SOURCES or not child["retained"]: + raise ValueError("visible manifest includes a foreign or removed window") + start, end = map(int, child["parent_frame_slice"]) + if start < 0 or end - start != int(child["frame_count"]): + raise ValueError(f"invalid parent slice for {child['id']}") + parents[source, child["parent_id"]].append(child) + for key, children in parents.items(): + children.sort(key=lambda row: row["parent_frame_slice"][0]) + previous_end = 0 + for child in children: + start, end = child["parent_frame_slice"] + if start < previous_end: + raise ValueError(f"overlapping visible children for {key}") + previous_end = end + return parents + + +def remap_row(row: dict, source: str, children: list[dict]) -> dict | None: + if len(row["expected_frame_ids"]) != 1: + raise ValueError("P0 index requires single-frame native reader rows") + offset = int(row["filtered_start_offset"]) + for child in children: + start, end = map(int, child["parent_frame_slice"]) + if start <= offset < end: + recording = row[RECORDING_KEY[source]] + if (child["dataset"] != source or child["recording_id"] != recording + or row["filtered_gt_path"] != child["parent_filtered_gt_path"]): + raise ValueError(f"source/recording/parent mismatch for {row['filtered_tile_id']}") + result = dict(row) + result["filtered_window_id"] = child["id"] + result["filtered_start_offset"] = offset - start + result["filtered_gt_path"] = child["filtered_gt_path"] + result["filtered_tile_id"] = f"{child['id']}:{offset - start}" + return result + return None + + +def build(visible_manifest: Path, parent_t1_dir: Path, output_dir: Path) -> dict: + if output_dir.exists(): + raise FileExistsError(output_dir) + parents = visible_children(visible_manifest) + output_dir.mkdir(parents=True) + report = {"visible_manifest": str(visible_manifest.resolve()), + "visible_manifest_sha256": sha256(visible_manifest), "sources": {}} + for source in SOURCES: + parent_path = parent_t1_dir / f"{source.lower()}_t1.jsonl" + counts = Counter() + recording_sets = {"train": set(), "dev": set()} + seen_tiles = set() + paths = {role: output_dir / f"{source.lower()}_{role}_t1.jsonl" + for role in ("train", "dev")} + with paths["train"].open("w", encoding="utf-8") as train, \ + paths["dev"].open("w", encoding="utf-8") as dev: + streams = {"train": train, "dev": dev} + for row in read_jsonl(parent_path): + counts["parent_t1_rows"] += 1 + child_rows = parents.get((source, row["filtered_window_id"]), []) + mapped = remap_row(row, source, child_rows) + if mapped is None: + counts["removed_t1_rows"] += 1 + continue + if mapped["filtered_tile_id"] in seen_tiles: + raise ValueError(f"duplicate mapped tile {mapped['filtered_tile_id']}") + seen_tiles.add(mapped["filtered_tile_id"]) + recording = str(row[RECORDING_KEY[source]]) + role = "dev" if heldout_recording(source, recording) else "train" + recording_sets[role].add(recording) + streams[role].write(json.dumps(mapped, separators=(",", ":")) + "\n") + counts[f"{role}_t1_rows"] += 1 + if recording_sets["train"] & recording_sets["dev"]: + raise AssertionError(f"{source} recording leak") + if not recording_sets["train"] or not recording_sets["dev"]: + raise ValueError(f"{source} train/dev split is empty") + report["sources"][source] = { + "parent_t1_sha256": sha256(parent_path), "counts": dict(counts), + "recordings": {role: len(value) for role, value in recording_sets.items()}, + "manifests": {role: {"path": str(path), "sha256": sha256(path)} + for role, path in paths.items()}, + } + (output_dir / "index_report.json").write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--visible-manifest", type=Path, required=True) + parser.add_argument("--parent-t1-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(build(args.visible_manifest, args.parent_t1_dir, args.output_dir), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/vitpose_probe.py b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/vitpose_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..19dbe68e5ed05e2c48c52daa2e25b7b65313477e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/dinov3_2d_pretrain/vitpose_probe.py @@ -0,0 +1,170 @@ +"""Frozen ViTPose-L COCO features with the same P0 full-frame 2D head.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path + +import numpy as np +import torch +from torch import nn +from torch.nn import functional as F + +from foundation_hand.models.encoders import PatchFeatures +from . import gkdt_probe +from .model import DinoKeypointPretrainer +from .train_p0 import CONFIG +from .visible_index import sha256 + + +class ViTPoseBlock(nn.Module): + def __init__(self, width: int, heads: int) -> None: + super().__init__() + self.width, self.heads = width, heads + self.ln1 = nn.LayerNorm(width, eps=1e-6) + self.attn = nn.Module() + self.attn.qkv = nn.Linear(width, width * 3) + self.attn.proj = nn.Linear(width, width) + self.ln2 = nn.LayerNorm(width, eps=1e-6) + self.ffn = nn.Module() + self.ffn.layers = nn.ModuleList([ + nn.Sequential(nn.Linear(width, width * 4), nn.GELU()), + nn.Linear(width * 4, width), + ]) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + batch, tokens, channels = x.shape + qkv = self.attn.qkv(self.ln1(x)).reshape( + batch, tokens, 3, self.heads, channels // self.heads) + q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0) + attended = F.scaled_dot_product_attention(q, k, v) + x = x + self.attn.proj(attended.transpose(1, 2).reshape(batch, tokens, channels)) + return x + self.ffn.layers[1](self.ffn.layers[0](self.ln2(x))) + + +class ViTPoseBackbone(nn.Module): + def __init__(self, width: int, depth: int, heads: int) -> None: + super().__init__() + self.cls_token = nn.Parameter(torch.zeros(1, 1, width)) + self.pos_embed = nn.Parameter(torch.zeros(1, 193, width)) + self.patch_embed = nn.Module() + self.patch_embed.projection = nn.Conv2d(3, width, 16, stride=16, padding=2) + self.layers = nn.ModuleList(ViTPoseBlock(width, heads) for _ in range(depth)) + self.ln1 = nn.LayerNorm(width, eps=1e-6) + + def forward(self, images: torch.Tensor) -> tuple[torch.Tensor, tuple[int, int]]: + patches = self.patch_embed.projection(images) + rows, cols = patches.shape[-2:] + x = patches.flatten(2).transpose(1, 2) + position = F.interpolate( + self.pos_embed[:, 1:].reshape(1, 16, 12, -1).permute(0, 3, 1, 2), + size=(rows, cols), mode="bicubic", align_corners=False, + ).flatten(2).transpose(1, 2) + x = x + position + self.pos_embed[:, :1] + for layer in self.layers: + x = layer(x) + return self.ln1(x), (rows, cols) + + +class FrozenViTPoseEncoder(nn.Module): + trainable_last_blocks = 0 + + def __init__(self, weights: Path, output_dim: int) -> None: + super().__init__() + state = torch.load(weights, map_location="cpu", weights_only=True) + width = state["pos_embed"].shape[-1] + depth = len({int(key.split(".")[1]) for key in state + if key.startswith("layers.")}) + if (width, depth) != (1024, 24): + raise ValueError("expected complete ViTPose-L backbone") + self.backbone = ViTPoseBackbone(width, depth, heads=16) + self.backbone.load_state_dict(state, strict=True) + self.backbone.requires_grad_(False) + self.backbone.eval() + self.projection = nn.Linear(width, output_dim) + + def train(self, mode: bool = True): + super().train(mode) + self.backbone.eval() + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + with torch.no_grad(): + tokens, grid = self.backbone(images) + return PatchFeatures(self.projection(tokens), grid, 16) + + +def export_backbone(checkpoint: Path, output: Path) -> None: + if output.exists(): + raise FileExistsError(output) + from numpy.core.multiarray import _reconstruct + + allowed = [(_reconstruct, "numpy.core.multiarray._reconstruct"), + np.ndarray, np.dtype] + allowed += [type(np.dtype(name)) for name in + ("float32", "float64", "int32", "int64", "uint8", "bool")] + with torch.serialization.safe_globals(allowed): + checkpoint_state = torch.load(checkpoint, map_location="cpu", weights_only=True) + state = {key[len("backbone."):]: value + for key, value in checkpoint_state["state_dict"].items() + if key.startswith("backbone.")} + if state["pos_embed"].shape != (1, 193, 1024): + raise ValueError("not the expected ViTPose-L COCO checkpoint") + if {int(key.split(".")[1]) for key in state if key.startswith("layers.")} != set(range(24)): + raise ValueError("ViTPose-L backbone is incomplete") + temporary = output.with_suffix(output.suffix + ".tmp") + torch.save(state, temporary) + os.replace(temporary, output) + print(json.dumps({"backbone": str(output), "tensors": len(state), + "sha256": sha256(output), "bytes": output.stat().st_size})) + + +def make_model(args: argparse.Namespace) -> DinoKeypointPretrainer: + encoder = FrozenViTPoseEncoder(args.visual_weights, CONFIG["model_width"]) + model = DinoKeypointPretrainer( + args.dino_source, args.visual_weights, tuple(CONFIG["image_hw"]), + width=CONFIG["model_width"], bin_pixels=CONFIG["bin_pixels"], encoder=encoder, + ) + model.set_auxiliary_tuning(False) + if any(parameter.requires_grad for parameter in model.encoder.backbone.parameters()): + raise AssertionError("ViTPose-L backbone must remain frozen") + return model + + +def main() -> None: + parser = argparse.ArgumentParser() + sub = parser.add_subparsers(dest="action", required=True) + export = sub.add_parser("export") + export.add_argument("--checkpoint", type=Path, required=True) + export.add_argument("--output", type=Path, required=True) + run = sub.add_parser("train") + run.add_argument("--gkdt-checkpoint", type=Path, required=True) + run.add_argument("--visual-weights", type=Path, required=True) + run.add_argument("--dino-source", type=Path, required=True) + run.add_argument("--index-root", type=Path, required=True) + run.add_argument("--code-root", type=Path, required=True) + run.add_argument("--output", type=Path, required=True) + run.add_argument("--expected-visible-sha256", required=True) + run.add_argument("--updates", type=int, default=1000) + run.add_argument("--global-batch", type=int, default=24) + run.add_argument("--micro-batch", type=int, default=1) + run.add_argument("--phase-steps", type=int, default=625) + run.add_argument("--workers", type=int, default=2) + run.add_argument("--log-every", type=int, default=25) + run.add_argument("--save-every", type=int, default=500) + run.add_argument("--eval-every", type=int, default=500) + run.add_argument("--eval-limit-per-source", type=int, default=256) + run.add_argument("--device", default="cuda:0") + run.add_argument("--resume", type=Path) + args = parser.parse_args() + if args.action == "export": + export_backbone(args.checkpoint, args.output) + else: + gkdt_probe.train(args, model_factory=make_model, + stage_name="ViTPose-L COCO frozen-feature P0 head probe") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/README.md b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/README.md new file mode 100644 index 0000000000000000000000000000000000000000..033dd505a446044cde290945744064c10a992478 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/README.md @@ -0,0 +1,72 @@ +# From-scratch mean-pose configuration + +`config.json` records the corrected matched B0/B1 experiment specified by +[`docs/FROM_SCRATCH_MEAN_POSE_REVIEW.md`](../../docs/FROM_SCRATCH_MEAN_POSE_REVIEW.md). Only a two-update +smoke per arm is authorized. It is not accepted by the historical N0/N1 trainer. +`fit_targets.py` loads the local-pose anchor from both official MANO pkl files and +fits train-only delta-6D normalization into `statistics_mano_pkl_v2.json`; +`smoke.py` tests two real CUDA updates for each arm and writes a diagnostic report, +not a training checkpoint. +The post-implementation data, representation, and loss audit is in +[`docs/FROM_SCRATCH_B0_B1_THREE_CHECK_AUDIT_20261004.md`](../../docs/FROM_SCRATCH_B0_B1_THREE_CHECK_AUDIT_20261004.md). +Prediction heads start with zero weights, so the first update cannot propagate +into the decoder. The second update must produce nonzero decoder gradients. +The experiment imports `foundation_hand` from this checkout's `src`; it raises +if another checkout was imported first. This avoids an older editable install +silently supplying a mismatched ARCTIC reader. + +Both arms use only official pretrained DINO weights; all Foundation Hand +learned modules start fresh. Both use RGB T=8, the same 21:15:24 source quota, +the same supervised losses, no teacher, and no hard-pose reweighting. Both use +MANO-joint reprojection as their only 2D loss (`joint2d=0`, `reprojection=1`); +the unused direct 2D head remains in both model definitions for matched +architecture, but its output is not a trained keypoint prediction. Both use +the same fixed side/joint SO(3) means from MANO pkl `hands_mean` and +predict right-side deltas with `R_final = R_mean @ R_delta`. Root orientation +remains direct in both arms. B0 uses the factorized hand-query spatial decoder; +B1 uses fresh RGB/HAND MoT spatial blocks. Their temporal blocks and heads have +the same configuration and shared initialization. The MoT arm must not copy any +S4/U0 weights through the historical `convert_parent` helper. + +The planned formal B0/B1 comparison uses the same three-resolution schedule in +both arms: `512x896`, `368x640`, and `512x512` `[H,W]`. Source/device-conditional +starting ratios, full-frame resize/pad rules, and fixed-resolution evaluation +gates are registered in the review document's mixed-resolution section. The +current `config.json` and two-update smoke remain fixed at `512x896`; the +multi-resolution sampler and three-size runtime checks have **not** been +implemented or approved for formal training. + +The MoT design updates RGB tokens and has different spatial parameters and +compute. Record both parameter counts and FLOPs/throughput; any B1 gain is an +architecture-family result, not proof that a single attention operator helped. + +The `optimizer` null fields are deliberate open decisions, not defaults. Total +budget, warmup, learning rates, and DINO freeze/unfreeze boundaries must be +registered identically for both arms before formal training is enabled. Only +normalization statistics use unique train-only labels and 21:15:24 source +weighting; the local mean never depends on the training-data distribution. +The MANO geometry layer still takes absolute local rotations +(`flat_hand_mean=True`), so the pkl mean is composed once in the network and +never added a second time. Old N0/N1 direct-pose statistics are not reused. +The reprojection-only contract passed a new two-update CUDA smoke for both arms; +the report is `smoke_report_reprojection_only_20261006.json`. The earlier +`smoke_report_mano_pkl_v2.json` belongs to the direct-2D-plus-reprojection +contract and must not be used to validate this loss change. +The same `16x6D` head predicts the direct root and a right mean-relative delta +for each local joint. There is no extra delta head or teacher network. + +Run the new-path checks from the repo root with the Foundation Hand environment: + +```bash +/SSD2/jiasen/envs/foundation_hand/bin/python -m pytest tests/test_from_scratch_mean_pose_config.py tests/test_from_scratch_mean_pose_runtime.py +``` + +The old `statistics.json` and `smoke_report.json` used a train-estimated mean; +they are retained only as historical evidence and the new smoke rejects them. +Generators refuse to overwrite an existing file; repeat audits must provide +fresh `--output` paths and compare hashes with the registered assets. The +three-check audit marks its old results as superseded by this mean correction. + +The historical N0/N1 files are left unchanged to preserve their recorded code +and configuration hashes. Do not point their `train.py` at this config: it loads +U0 20K and runs a teacher regardless of these fields. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/__init__.py b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27532eeb64c1addc6e3374c5a5227a93412343a7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/__init__.py @@ -0,0 +1,16 @@ +"""Bind this experiment to the checked-out EgoNet source, not an older install.""" + +from pathlib import Path +import sys + + +_SRC = Path(__file__).resolve().parents[2] / "src" +_loaded = sys.modules.get("foundation_hand") +if _loaded is not None: + _paths = [Path(path).resolve() for path in getattr(_loaded, "__path__", ())] + if _SRC / "foundation_hand" not in _paths: + raise RuntimeError( + "Foundation Hand was imported from another checkout before EgoNet; " + "start a fresh process with the EgoNet repository on PYTHONPATH" + ) +sys.path.insert(0, str(_SRC)) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/config.json new file mode 100644 index 0000000000000000000000000000000000000000..e5fa6201f4df22d85b287c4c0effe73fbdfc211e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/config.json @@ -0,0 +1,167 @@ +{ + "contract": "FOUNDATION_HAND_FROM_SCRATCH_MANO_PKL_MEAN_REPROJECTION_ONLY_20261006", + "status": "smoke_only_formal_training_unapproved", + "training_approved": false, + "shared": { + "seed": 20261003, + "input": { + "mode": "rgb", + "frames": 8, + "depth_as_input": false, + "intrinsics_as_input": false, + "intrinsics_for_reprojection_loss": true + }, + "data": { + "split": "train_only", + "target_contract": "canonical_approximate_v3", + "canonical_labels": true, + "source_quota_per_update": { + "H2O": 21, + "ARCTIC": 15, + "HOT3D": 24 + }, + "global_batch": 60, + "hot3d_pose_shape_requires_native_mesh_compatibility_mm": 1.0, + "heldout_excluded_from_training_statistics": true + }, + "initialization": { + "rgb_backbone": "official_dinov3_pretrained_only", + "dinov3_source": "/home/jiasen/foundation_hand/third_party/dinov3", + "dinov3_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "dinov3_model_sha256": "9a21ac3df0c63839d62612dda6f454d816c25611cc7a52966ed5a5a94921dc8b", + "mano_root": "/SSD3/jiasen/foundation_hand/pretrained/mano", + "mano_pkl_sha256": { + "left": "c4022f7083f2ca7c78b2b3d595abbab52debd32b09d372b16923a801f0ea6a30", + "right": "45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767" + }, + "verify_official_weights_sha256": true, + "foundation_hand_parent_checkpoint": null, + "decoder_temporal_projection_and_heads": "fresh_random_initialization", + "mano_geometry_assets": "fixed_nontrainable" + }, + "model": { + "decoder_dim": 512, + "decoder_layers": 3, + "attention_heads": 8, + "spatial_temporal_order": "alternating", + "temporal_attention": "bidirectional", + "structured_hand_refinement": false, + "depth_branch": false, + "ray_branch": false, + "presence_head": false + }, + "pose": { + "local_pose_parameterization": "right_mean_pose_delta_rotation_6d", + "root_orientation_parameterization": "direct_camera_rotation_6d", + "mean_rotation": { + "source": "official_mano_left_and_right_pkl_hands_mean", + "representation": "axis_angle_per_local_joint_to_so3", + "separate_side_and_joint": true, + "joints_per_side": 15, + "fixed_buffer": true, + "mano_geometry_layer_remains_flat_hand_mean": true + }, + "delta_gt": "transpose(R_mean) @ R_gt", + "local_pose_target": "delta_gt_first_two_rows", + "local_pose_loss": "normalized_fp32_delta_6d_l1", + "final_local_rotation": "R_mean @ R_delta_pred", + "head_initial_delta_rotation": "identity" + }, + "teacher": { + "create_model": false, + "forward": false, + "distillation": false, + "rgb_teacher_weight": 0.0 + }, + "precision": { + "model_autocast": "bf16", + "gt_axis_angle_to_matrix": "fp32_autocast_disabled", + "predicted_6d_gram_schmidt": "fp32_autocast_disabled", + "pose_loss": "fp32" + }, + "normalization": { + "statistics_asset": "statistics_mano_pkl_v2.json", + "fit_split": "train_only", + "source_weighting": "source_quota_per_update", + "deduplicate_overlapping_clips_by_source_recording_frame_side": true, + "fit_new_statistics_for_mano_pkl_delta": true, + "reuse_n0_n1_pose_statistics": false + }, + "loss": { + "hard_pose_reweight": false, + "joint2d": 0.0, + "joint3d_camera": 1.5, + "joint3d_root_relative": 1.5, + "vertices_camera": 0.15, + "local_pose": 0.3, + "global_orientation": 0.3, + "shape": 0.1, + "translation": 1.5, + "reprojection": 1.0, + "temporal_velocity": 0.015, + "temporal_acceleration": 0.0075, + "bimanual_relative_wrist": 0.15 + }, + "optimizer": { + "name": "AdamW", + "world_size": 6, + "weight_decay": 0.05, + "global_grad_clip_norm": 100.0, + "maximum_updates": null, + "warmup_updates": null, + "learning_rates_by_stage": null, + "dino_freeze_unfreeze_updates": null + }, + "smoke": { + "updates": 2, + "learning_rate": 0.00005, + "samples_per_source": 1, + "target_hw": [512, 896], + "reprojection_depth_floor_m": 0.05, + "reprojection_depth_penalty_per_m": 10.0 + }, + "evaluation": { + "input_mode": "rgb", + "frames": 8, + "development_sources": ["H2O", "ARCTIC", "HOT3D"], + "development_targets": "source_native_gt", + "four_metrics": [ + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "mpvpe_mm", + "projected_mano_2d_error_px" + ], + "hard_case_diagnostics": [ + "per_joint_geodesic_angle", + "gt_bend_at_least_60_degrees_underprediction", + "root_relative_fingertip_error", + "normal_pose_no_harm" + ], + "official_benchmark_confirmation_after_selection": true + }, + "required_preflight": [ + "gt_camera_space_and_mask_audit", + "fp32_rotation_round_trip_left_and_right", + "mano_pkl_mean_and_train_only_normalization_hashes", + "identical_paired_sample_order_and_shared_initial_tensors", + "report_parameter_counts_and_compute_by_architecture", + "forward_backward_loss_gradient_and_clipping", + "checkpoint_full_backbone_optimizer_rng_and_data_hashes" + ] + }, + "arms": { + "B0": { + "architecture": "non_mot", + "spatial_decoder": "fresh_factorized_hand_query_rgb_only", + "spatial_attention": "hand_self_then_hand_to_rgb_cross_attention", + "rgb_patch_tokens_updated_by_decoder": false + }, + "B1": { + "architecture": "mot", + "spatial_decoder": "fresh_unified_rgb_hand_mot", + "spatial_attention": "joint_rgb_hand_attention_with_type_specific_projections_and_ffn", + "rgb_patch_tokens_updated_by_decoder": true, + "terminal_unused_rgb_output_path": "freeze_or_omit" + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/fit_targets.py b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/fit_targets.py new file mode 100644 index 0000000000000000000000000000000000000000..1d2c353f26e084db343470d8074faab5c1254d4e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/fit_targets.py @@ -0,0 +1,159 @@ +"""Load the MANO-pkl local mean and fit train-only normalized GT statistics.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np +from scipy.spatial.transform import Rotation + +from experiments.u0_normalized6d.fit_normalization import ( + BASE_ROOT, LABEL_ROOT, Moments, U0Dataset, canonical_source, hot3d_source, + selected_frames, sha, +) + +SOURCES = ("H2O", "ARCTIC", "HOT3D") +QUOTA = {"H2O": 21, "ARCTIC": 15, "HOT3D": 24} +CHUNK = 16384 +ROOT = Path(__file__).resolve().parent + + +class TargetMoments(Moments): + def __init__(self): + super().__init__() + self.local = [[], []] + + def add(self, pose, beta, wrist, valid): + super().add(pose, beta, wrist, valid) + finite = np.isfinite(pose).all(-1) & np.isfinite(beta).all(-1) & np.isfinite(wrist).all(-1) + valid = valid.astype(bool) & finite + for side in range(2): + selected = pose[:, side, 3:][valid[:, side]].reshape(-1, 15, 3) + if len(selected): + self.local[side].append(selected.astype(np.float32, copy=False)) + + +def chunks(values): + for start in range(0, len(values), CHUNK): + yield values[start:start + CHUNK] + + +def weighted_local_matrices(local): + for source in SOURCES: + for side in range(2): + count = len(local[source][side]) + if not count: + raise RuntimeError(f"empty train-only local-pose set: {source}/{side}") + weight = QUOTA[source] / sum(QUOTA.values()) / count + for block in chunks(local[source][side]): + matrices = Rotation.from_rotvec(block.reshape(-1, 3)).as_matrix().reshape(-1, 15, 3, 3) + yield source, side, weight, matrices + + +def mano_pkl_mean(mano_root: Path) -> tuple[np.ndarray, dict[str, str]]: + from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + + means, hashes = [], {} + for side in ("left", "right"): + path = mano_root / f"MANO_{side.upper()}.pkl" + hashes[side] = sha(path) + layer = ManoLayer(mano_root=str(mano_root), side=side, use_pca=False, + ncomps=45, flat_hand_mean=False) + axis_angle = layer.th_hands_mean.detach().cpu().numpy().reshape(15, 3).astype(np.float64) + means.append(Rotation.from_rotvec(axis_angle).as_matrix()) + mean = np.stack(means) + if mean.shape != (2, 15, 3, 3) or not np.isfinite(mean).all(): + raise RuntimeError("MANO-pkl hands_mean is not a finite [side,joint,3,3] rotation asset") + return mean, hashes + + +def weighted_moments(moment, key_sum, key_sq, count): + center = sum(QUOTA[s] / 60 * getattr(moment[s], key_sum) / count(moment[s]) for s in SOURCES) + second = sum(QUOTA[s] / 60 * getattr(moment[s], key_sq) / count(moment[s]) for s in SOURCES) + return center, second + + +def fit(local, moments, mean, mano_hashes): + xyz_center, xyz_second = weighted_moments(moments, "xyz_sum", "xyz_sq", lambda m: m.count) + beta_center, beta_second = weighted_moments(moments, "beta_sum", "beta_sq", lambda m: m.count) + xyz_scale = max(0.1, float(np.sqrt(np.maximum((xyz_second - xyz_center**2).mean(), 0)))) + beta_scale = np.maximum(np.sqrt(np.maximum(beta_second - beta_center**2, 0)), 0.5) + root_sum = np.zeros((2, 6), np.float64) + root_sq = np.zeros((2, 6), np.float64) + delta_sum = np.zeros((2, 15, 6), np.float64) + delta_sq = np.zeros((2, 15, 6), np.float64) + for source in SOURCES: + m = moments[source] + root_sum += QUOTA[source] / 60 * m.pose_sum[:, 0] / m.pose_count[:, 0] + root_sq += QUOTA[source] / 60 * m.pose_sq[:, 0] / m.pose_count[:, 0] + for source, side, weight, matrices in weighted_local_matrices(local): + relative = mean[side].transpose(0, 2, 1)[None] @ matrices + six = relative[..., :2, :].reshape(-1, 15, 6) + delta_sum[side] += weight * six.sum(axis=0) + delta_sq[side] += weight * np.square(six).sum(axis=0) + pose_center = np.concatenate((root_sum[:, None], delta_sum), axis=1) + pose_second = np.concatenate((root_sq[:, None], delta_sq), axis=1) + pose_scale = np.maximum(np.sqrt(np.maximum(pose_second - pose_center**2, 0)), 0.1) + if not all(np.isfinite(x).all() for x in (mean, xyz_center, beta_center, pose_center, pose_scale)): + raise RuntimeError("nonfinite fitted GT statistics") + return { + "version": "b0_b1_mano_pkl_mean_delta_v2", + "training_index_sha256": sha(BASE_ROOT / "cache/trainable_t8_index.sqlite"), + "label_inventory_sha256": sha(LABEL_ROOT / "label_inventory.json"), + "mean_source": "official_mano_pkl_hands_mean_axis_angle", + "mano_pkl_sha256": mano_hashes, + "source_quota": QUOTA, + "source_hand_frames": {source: moments[source].count for source in SOURCES}, + "source_local_pose_frames_by_side": { + source: [len(local[source][side]) for side in range(2)] for source in SOURCES + }, + "mean_local": mean.tolist(), + "xyz_center": xyz_center.tolist(), "xyz_scale": xyz_scale, + "beta_center": beta_center.tolist(), "beta_scale": beta_scale.tolist(), + "pose_center": pose_center.tolist(), "pose_scale": pose_scale.tolist(), + "variance_floors": {"xyz_m": 0.1, "beta": 0.5, "pose_component": 0.1}, + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + groups, _ = selected_frames() + inventory = json.loads((LABEL_ROOT / "label_inventory.json").read_text()) + labels = {(row["source"], row["recording"]): row["path"] for row in inventory["entries"]} + native = U0Dataset().sources["HOT3D"].native + moments = {source: TargetMoments() for source in SOURCES} + for ordinal, ((source, recording), windows) in enumerate(sorted(groups.items()), 1): + if source == "HOT3D": + hot3d_source(recording, windows, native, moments[source]) + else: + canonical_source(source, recording, windows, labels, moments[source]) + if ordinal % 25 == 0: + print(json.dumps({"recordings_done": ordinal, "hand_frames": { + key: value.count for key, value in moments.items()}}), flush=True) + local = { + source: [np.concatenate(moments[source].local[side], axis=0) for side in range(2)] + for source in SOURCES + } + config = json.loads((ROOT / "config.json").read_text()) + mean, mano_hashes = mano_pkl_mean(Path(config["shared"]["initialization"]["mano_root"])) + result = fit(local, moments, mean, mano_hashes) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(args.output.suffix + ".tmp") + temporary.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") + temporary.replace(args.output) + print(json.dumps({"asset": str(args.output), "sha256": sha(args.output), + "hand_frames": result["source_hand_frames"], + "mean_source": result["mean_source"]}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/loss.py b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..1e5c79e5c64c799dde3067d9ad5931b9c4b24b75 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/loss.py @@ -0,0 +1,149 @@ +"""Teacher-free, quota-weighted B0/B1 supervision in normalized GT space.""" + +from __future__ import annotations + +import torch +from torch import nn + +from foundation_hand.data.schema import supervision_mask +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix +from experiments.u0_normalized6d.normalized_loss import masked_weighted_l1 +from experiments.u0_depthsafe.reprojection import fixed_mask_reprojection + +from .model import no_autocast + + +TERMS = ( + "joint2d", "joint3d_camera", "joint3d_root_relative", "vertices_camera", + "local_pose", "global_orientation", "shape", "translation", "reprojection", + "temporal_velocity", "temporal_acceleration", "bimanual_relative_wrist", +) + + +class FromScratchLoss(nn.Module): + def __init__(self, statistics: dict, coefficients: dict[str, float], smoke: dict): + super().__init__() + if set(coefficients) != set(TERMS): + raise ValueError("B0/B1 supervision terms differ from the registered contract") + for key in ("xyz_center", "xyz_scale", "beta_center", "beta_scale", "pose_center", "pose_scale", "mean_local"): + self.register_buffer(key, torch.as_tensor(statistics[key], dtype=torch.float32)) + self.coefficients = coefficients + self.depth_floor = smoke["reprojection_depth_floor_m"] + self.depth_penalty = smoke["reprojection_depth_penalty_per_m"] + + def absolute_xyz(self, value): + return (value.float() - self.xyz_center) / self.xyz_scale + + def relative_xyz(self, value): + return value.float() / self.xyz_scale + + def beta(self, value): + return (value.float() - self.beta_center) / self.beta_scale + + def pose_6d(self, prediction, batch, root_valid, local_valid): + with no_autocast(prediction["mano_rotations_6d"].device): + target_axis = torch.nan_to_num(batch["mano_pose"].float()).reshape(*root_valid.shape, 16, 3) + target_rotations = axis_angle_to_matrix(target_axis) + raw_pred = prediction["mano_rotations_6d"].float() + predicted_rotations = rotation_6d_to_matrix(raw_pred) + predicted_root = predicted_rotations[..., :1, :2, :].reshape(*root_valid.shape, 1, 6) + target_root = target_rotations[..., :1, :2, :].reshape(*root_valid.shape, 1, 6) + predicted_delta = self.mean_local.transpose(-1, -2) @ predicted_rotations[..., 1:, :, :] + target_delta = self.mean_local.transpose(-1, -2) @ target_rotations[..., 1:, :, :] + predicted_delta = predicted_delta[..., :2, :].reshape(*root_valid.shape, 15, 6) + target_delta = target_delta[..., :2, :].reshape(*root_valid.shape, 15, 6) + root_center, root_scale = self.pose_center[:, :1], self.pose_scale[:, :1] + local_center, local_scale = self.pose_center[:, 1:], self.pose_scale[:, 1:] + root = masked_weighted_l1( + (predicted_root - root_center) / root_scale, + (target_root - root_center) / root_scale, root_valid[..., None, None], + ) + local = masked_weighted_l1( + (predicted_delta - local_center) / local_scale, + (target_delta - local_center) / local_scale, local_valid[..., None, None], + ) + return root, local, target_rotations, predicted_rotations + + def forward(self, prediction: dict, batch: dict) -> tuple[torch.Tensor, dict[str, torch.Tensor], dict]: + frame = batch["frame_valid"].bool() + legacy_joint = batch["joint_annotation_valid"].bool() + legacy_mano = batch["mano_annotation_valid"].bool() + elements = batch["joint_element_valid"].bool() & legacy_joint[..., None] + joint3d_valid = supervision_mask(batch, "joint3d_valid", elements) & frame[..., None, None] + relative_valid = supervision_mask(batch, "joint3d_root_relative_valid", joint3d_valid) & frame[..., None, None] + translation_valid = supervision_mask(batch, "translation_valid", legacy_joint) & frame[..., None] + root_valid = supervision_mask(batch, "global_orientation_valid", legacy_mano) & frame[..., None] + local_valid = supervision_mask(batch, "local_pose_valid", legacy_mano) & frame[..., None] + shape_valid = supervision_mask(batch, "shape_valid", legacy_mano) & frame[..., None] + vertices_valid = supervision_mask(batch, "vertices_valid", legacy_mano) & frame[..., None] + losses = {"joint2d": prediction["joints_camera"].new_zeros(())} + if self.coefficients["joint2d"] != 0: + joint2d_valid = supervision_mask(batch, "joint2d_valid", elements) & frame[..., None, None] + wh = batch["image_hw"].float()[:, None, None, None, [1, 0]] + losses["joint2d"] = masked_weighted_l1( + prediction["joint2d_norm"].float(), batch["joint2d"].float() / wh, + joint2d_valid[..., None], + ) + root, local, target_rotation, predicted_rotation = self.pose_6d( + prediction, batch, root_valid, local_valid, + ) + losses["global_orientation"], losses["local_pose"] = root, local + losses["translation"] = masked_weighted_l1( + self.absolute_xyz(prediction["wrist_root_translation"]), + self.absolute_xyz(batch["wrist_root_translation"]), translation_valid[..., None], + ) + safe_shape = torch.where(shape_valid[..., None], batch["mano_shape"], torch.zeros_like(batch["mano_shape"])) + target_shape = safe_shape.sum(dim=1) / shape_valid.sum(dim=1).clamp_min(1)[..., None] + losses["shape"] = masked_weighted_l1( + self.beta(prediction["mano_shape_sequence"]), self.beta(target_shape), + shape_valid.any(dim=1)[..., None], + ) + losses["joint3d_camera"] = masked_weighted_l1( + self.absolute_xyz(prediction["joints_camera"]), self.absolute_xyz(batch["joint3d_camera"]), + joint3d_valid[..., None], + ) + predicted_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + target_relative = batch.get("joint3d_root_relative") + if target_relative is None: + target_relative = batch["joint3d_camera"] - batch["joint3d_camera"][..., :1, :] + losses["joint3d_root_relative"] = masked_weighted_l1( + self.relative_xyz(predicted_relative), self.relative_xyz(target_relative), + relative_valid[..., None], + ) + losses["vertices_camera"] = masked_weighted_l1( + self.absolute_xyz(prediction["vertices_camera"]), + self.absolute_xyz(batch["vertices_camera"]), vertices_valid[..., None, None], + ) + wrists, target_wrists = prediction["wrist_root_translation"], batch["wrist_root_translation"] + losses["bimanual_relative_wrist"] = masked_weighted_l1( + self.relative_xyz(wrists[:, :, 1] - wrists[:, :, 0]), + self.relative_xyz(target_wrists[:, :, 1] - target_wrists[:, :, 0]), + translation_valid.all(dim=-1)[..., None], + ) + velocity_valid = translation_valid[:, 1:] & translation_valid[:, :-1] + velocity = wrists[:, 1:] - wrists[:, :-1] + target_velocity = target_wrists[:, 1:] - target_wrists[:, :-1] + losses["temporal_velocity"] = masked_weighted_l1( + self.relative_xyz(velocity), self.relative_xyz(target_velocity), velocity_valid[..., None], + ) + acceleration_valid = velocity_valid[:, 1:] & velocity_valid[:, :-1] + losses["temporal_acceleration"] = masked_weighted_l1( + self.relative_xyz(velocity[:, 1:] - velocity[:, :-1]), + self.relative_xyz(target_velocity[:, 1:] - target_velocity[:, :-1]), + acceleration_valid[..., None], + ) + reprojection, nonpositive, min_z = fixed_mask_reprojection( + prediction, batch, self.depth_floor, self.depth_penalty, + ) + losses["reprojection"] = reprojection + weighted = {key: value * self.coefficients[key] for key, value in losses.items()} + total = sum(weighted.values()) + diagnostics = { + "gt_rotation_orthogonality_max": float((target_rotation.transpose(-1, -2) @ target_rotation - torch.eye(3, device=total.device)).abs().max()), + "pred_rotation_orthogonality_max": float((predicted_rotation.transpose(-1, -2) @ predicted_rotation - torch.eye(3, device=total.device)).abs().max()), + "nonpositive_reprojection_joints": int(nonpositive), + "minimum_supervised_joint_z_m": float(min_z), + "valid_root_frames": int(root_valid.sum()), + "valid_local_frames": int(local_valid.sum()), + } + return total, weighted, diagnostics diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/model.py b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4a5ce8ecd15148fdf90ca194c5548b72a5a09d46 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/model.py @@ -0,0 +1,80 @@ +"""Fresh RGB B0/B1 models with a shared fixed-mean local rotation target.""" + +from __future__ import annotations + +from contextlib import nullcontext + +import torch +from torch import nn + +from foundation_hand.geometry.rotations import rotation_6d_to_matrix +from foundation_hand.models.bimanual import BimanualReconstructionModel, ModelConfig +from experiments.u0_depthsafe.model import UnifiedRGBDecoder + + +IDENTITY_6D = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0) + + +def no_autocast(device: torch.device): + return torch.autocast(device.type, enabled=False) if device.type in {"cuda", "cpu"} else nullcontext() + + +class MeanDeltaRotationHead(nn.Module): + """One 16x6D head: direct root, right-multiplied mean-relative local joints.""" + + def __init__(self, linear: nn.Linear, mean_local: torch.Tensor): + super().__init__() + if mean_local.shape != (2, 15, 3, 3): + raise ValueError(f"expected [side,local joint,3,3] mean, got {mean_local.shape}") + self.linear = linear + self.register_buffer("mean_local", mean_local.detach().float().clone()) + + def forward(self, hand_tokens: torch.Tensor) -> torch.Tensor: + raw = self.linear(hand_tokens).reshape(*hand_tokens.shape[:-1], 16, 6) + with no_autocast(raw.device): + raw = raw.float() + local_delta = rotation_6d_to_matrix(raw[..., 1:, :]) + final_local = self.mean_local @ local_delta + final_local_6d = final_local[..., :2, :].reshape(*raw.shape[:-2], 15, 6) + return torch.cat((raw[..., :1, :], final_local_6d), dim=-2) + + +def build_model(arm: str, shared: dict, mean_local: torch.Tensor) -> BimanualReconstructionModel: + if arm not in {"B0", "B1"}: + raise ValueError(f"unknown matched arm {arm}") + model_cfg = shared["model"] + init = shared["initialization"] + if init["foundation_hand_parent_checkpoint"] is not None: + raise RuntimeError("from-scratch B0/B1 must not have a parent checkpoint") + if init["decoder_temporal_projection_and_heads"] != "fresh_random_initialization": + raise RuntimeError("B0/B1 requires fresh non-DINO learned parameters") + config = ModelConfig( + encoder="dinov3", + dinov3_source=init["dinov3_source"], + dinov3_weights=init["dinov3_weights"], + dinov3_trainable_last_blocks=0, + decoder_dim=model_cfg["decoder_dim"], + decoder_layers=model_cfg["decoder_layers"], + attention_heads=model_cfg["attention_heads"], + decoder_mode=model_cfg["spatial_temporal_order"], + temporal_attention_mode=model_cfg["temporal_attention"], + use_depth=False, use_rays=False, predict_presence=False, + structured_hand_refinement=False, + translation_parameterization="direct_xyz", + joint2d_parameterization="hand_token_linear", + mano_root=init["mano_root"], require_mano=True, + mano_fix_left_shapedirs=True, + gradient_checkpointing=True, + ) + model = BimanualReconstructionModel(config) + if arm == "B1": + # The source decoder above is random in both arms. No S4/U0 model or + # checkpoint is constructed; only the fresh spatial topology changes. + model.decoder = UnifiedRGBDecoder(model.decoder, config.attention_heads) + model.rotation_head = MeanDeltaRotationHead(model.rotation_head, mean_local) + model.mano_layer.requires_grad_(False) + return model + + +def trainable_parameter_count(model: nn.Module) -> int: + return sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/probe_hot3d_provider_cache.py b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/probe_hot3d_provider_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..3c2600cf662dfc42b2a7308fb6d128e385a94d26 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/probe_hot3d_provider_cache.py @@ -0,0 +1,46 @@ +"""Read-only HOT3D provider RSS and open-time probe.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import time + +from .smoke import U0Dataset + + +def rss_kib() -> int: + for line in Path("/proc/self/status").read_text().splitlines(): + if line.startswith("VmRSS:"): + return int(line.split()[1]) + raise RuntimeError("VmRSS unavailable") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--providers", type=int, default=8) + args = parser.parse_args() + native = U0Dataset().sources["HOT3D"].native + native.provider_cache_size = args.providers + ids = list(dict.fromkeys(row["recording_id"] for row in native.rows)) + print(json.dumps({"stage": "reader_initialized", "recordings": len(ids), + "rss_mib": rss_kib() / 1024, + "open_fds": len(list(Path("/proc/self/fd").iterdir()))}), flush=True) + for recording in ids[:args.providers]: + started = time.perf_counter() + native._provider(recording) + print(json.dumps({"stage": "opened", "recording": recording, + "open_seconds": time.perf_counter() - started, + "rss_mib": rss_kib() / 1024, + "open_fds": len(list(Path("/proc/self/fd").iterdir()))}), flush=True) + started = time.perf_counter() + for recording in ids[:args.providers]: + native._provider(recording) + print(json.dumps({"stage": "cache_hits", "count": args.providers, + "seconds": time.perf_counter() - started, + "rss_mib": rss_kib() / 1024}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke.py b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..f2b497bcc5839f8b87dcd36d7016363e4fc0d7ef --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke.py @@ -0,0 +1,260 @@ +"""Two matched train-side updates per fresh RGB arm; never a formal run.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +import random +import sys +import time + +import numpy as np +import torch + +from .fit_targets import mano_pkl_mean +from .loss import FromScratchLoss, TERMS +from .model import build_model, trainable_parameter_count + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +U0_ROOT = ROOT.parent / "u0_depthsafe" +sys.path.insert(0, str(U0_ROOT)) +from common import U0Coverage, U0Dataset, a7, base # data reader only; model_for is never called + + +def sha(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024**2), b""): + digest.update(block) + return digest.hexdigest() + + +def check_contract(statistics: dict) -> dict: + shared = CONFIG["shared"] + if CONFIG["training_approved"] or CONFIG["status"] != "smoke_only_formal_training_unapproved": + raise RuntimeError("smoke may not implicitly authorize formal training") + if any(shared["optimizer"][key] is not None for key in ( + "maximum_updates", "warmup_updates", "learning_rates_by_stage", "dino_freeze_unfreeze_updates", + )): + raise RuntimeError("formal schedule unexpectedly changed") + if shared["teacher"] != {"create_model": False, "forward": False, + "distillation": False, "rgb_teacher_weight": 0.0}: + raise RuntimeError("teacher-free contract changed") + weights = Path(shared["initialization"]["dinov3_weights"]) / "model.safetensors" + if not weights.is_file() or sha(weights) != shared["initialization"]["dinov3_model_sha256"]: + raise RuntimeError("official DINOv3 model checksum differs") + index = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite") + inventory = Path("/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json") + if sha(index) != statistics["training_index_sha256"] or sha(inventory) != statistics["label_inventory_sha256"]: + raise RuntimeError("fitted GT statistics do not match this train-only data") + if statistics["source_quota"] != shared["data"]["source_quota_per_update"]: + raise RuntimeError("normalization source weighting differs from smoke data quota") + if statistics.get("version") != "b0_b1_mano_pkl_mean_delta_v2": + raise RuntimeError("the old train-estimated mean asset cannot initialize this contract") + if statistics.get("mean_source") != "official_mano_pkl_hands_mean_axis_angle": + raise RuntimeError("mean-pose asset does not come from MANO pkl hands_mean") + mano_root = Path(shared["initialization"]["mano_root"]) + expected_hashes = shared["initialization"]["mano_pkl_sha256"] + if statistics.get("mano_pkl_sha256") != expected_hashes: + raise RuntimeError("fitted statistics use different MANO pkl assets") + pkl_mean, current_hashes = mano_pkl_mean(mano_root) + if current_hashes != expected_hashes: + raise RuntimeError("MANO pkl asset checksum differs") + mean = torch.as_tensor(statistics["mean_local"], dtype=torch.float64) + if mean.shape != (2, 15, 3, 3): + raise RuntimeError("mean-pose asset has the wrong side/joint layout") + orthogonality = (mean.transpose(-1, -2) @ mean - torch.eye(3)).abs().max() + determinant = (torch.linalg.det(mean) - 1).abs().max() + if float(max(orthogonality, determinant)) > 1e-5: + raise RuntimeError("fitted mean-pose asset is not on SO(3)") + if not torch.allclose(mean, torch.as_tensor(pkl_mean), atol=1e-7, rtol=0): + raise RuntimeError("fitted local mean differs from official MANO-pkl hands_mean") + return {"dinov3": sha(weights), "index": sha(index), "labels": sha(inventory), + "mano_pkl": current_hashes} + + +def input_digest(sample: dict) -> str: + digest = hashlib.sha256() + for key in ("rgb", "K", "frame_valid", "joint2d", "joint3d_camera", "mano_pose", + "mano_shape", "wrist_root_translation"): + value = sample[key].contiguous().reshape(-1).view(torch.uint8) + digest.update(key.encode()) + digest.update(value.numpy().tobytes()) + return digest.hexdigest() + + +def sample_batches(): + coverage = U0Coverage() + coverage.seed = CONFIG["shared"]["seed"] + dataset = U0Dataset() + source_counts = Counter() + for position in range(60): + item = coverage.sample(position) + source_counts[item["source"]] += 1 + if dict(source_counts) != CONFIG["shared"]["data"]["source_quota_per_update"]: + raise RuntimeError("coverage sampler does not match the registered 21/15/24 mixture") + batches, descriptors = {}, {} + for position in range(600): + item = coverage.sample(position) + source = item["source"] + if source in batches: + continue + batch = base.collate_h2o_clips([dataset[item]]) + if batch["input_mode"] != ["rgb"]: + raise RuntimeError("non-RGB smoke sample") + if bool(batch["K_input_available"].any()) or bool(batch["depth_input_available"].any()): + raise RuntimeError("K or depth leaked into RGB-only model input") + if not bool(batch["frame_valid"].all()): + continue + if not bool(batch["global_orientation_valid"].any()) or not bool(batch["local_pose_valid"].any()): + continue + batches[source] = batch + descriptors[source] = {"position": item["position"], "tile_id": item["tile_id"], + "input_sha256": input_digest(batch)} + if len(batches) == 3: + break + if set(batches) != {"H2O", "ARCTIC", "HOT3D"}: + raise RuntimeError("no fully supervised smoke tile for every training source") + return batches, descriptors + + +def shared_init_digest(model) -> str: + digest = hashlib.sha256() + for key, value in sorted(model.state_dict().items()): + if key.startswith("decoder."): + continue + digest.update(key.encode()) + digest.update(value.detach().cpu().contiguous().reshape(-1).view(torch.uint8).numpy().tobytes()) + return digest.hexdigest() + + +def smoke_arm(arm: str, statistics: dict, batches: dict, device: torch.device) -> dict: + seed = CONFIG["shared"]["seed"] + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + mean = torch.as_tensor(statistics["mean_local"], dtype=torch.float32) + start = time.monotonic() + model = build_model(arm, CONFIG["shared"], mean).to(device).train() + criterion = FromScratchLoss(statistics, { + key: value for key, value in CONFIG["shared"]["loss"].items() if key in TERMS + }, CONFIG["shared"]["smoke"]).to(device) + initial_digest = shared_init_digest(model) + optimizer = torch.optim.AdamW( + [parameter for parameter in model.parameters() if parameter.requires_grad], + lr=CONFIG["shared"]["smoke"]["learning_rate"], + weight_decay=CONFIG["shared"]["optimizer"]["weight_decay"], + ) + before = model.rotation_head.linear.bias.detach().clone() + trainable = [parameter for parameter in model.parameters() if parameter.requires_grad] + updates = [] + for update in range(CONFIG["shared"]["smoke"]["updates"]): + optimizer.zero_grad(set_to_none=True) + source_losses, source_terms, diagnostics = {}, {}, {} + for source in ("H2O", "ARCTIC", "HOT3D"): + batch = base.move_to_device(batches[source], device) + if update == 0: + a7.validate_cached_geometry(batch, model) + wrist_valid = batch["translation_valid"].bool() & batch["joint3d_valid"][..., 0].bool() + wrist_gap = torch.linalg.vector_norm( + batch["wrist_root_translation"] - batch["joint3d_camera"][..., 0, :], dim=-1, + ) + if bool((wrist_gap[wrist_valid] > 0.001).any()): + raise RuntimeError(f"{source} canonical wrist is not in camera-space meters") + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + total, terms, diag = criterion(prediction, batch) + if not bool(torch.isfinite(total)) or not bool(torch.isfinite(prediction["joints_camera"]).all()): + raise RuntimeError(f"{arm}/{source} nonfinite loss or prediction") + if diag["gt_rotation_orthogonality_max"] > 1e-5 or diag["pred_rotation_orthogonality_max"] > 1e-5: + raise RuntimeError(f"{arm}/{source} rotation matrix is not FP32-orthogonal: {diag}") + if not diag["valid_root_frames"] or not diag["valid_local_frames"]: + raise RuntimeError(f"{arm}/{source} missing active root/local 6D supervision") + weighted = CONFIG["shared"]["data"]["source_quota_per_update"][source] / 60 + (total * weighted).backward() + source_losses[source] = float(total.detach()) + source_terms[source] = {key: float(value.detach()) for key, value in terms.items()} + diagnostics[source] = diag + diagnostics[source]["gt_wrist_joint_max_gap_mm"] = ( + float(wrist_gap[wrist_valid].max() * 1000) if bool(wrist_valid.any()) else None + ) + nonzero = sum(int(parameter.grad is not None and bool(parameter.grad.detach().abs().max() > 0)) + for parameter in trainable) + decoder_grads = sum(int(parameter.grad is not None and bool(parameter.grad.detach().abs().max() > 0)) + for name, parameter in model.named_parameters() if name.startswith("decoder.")) + grad_norm = torch.nn.utils.clip_grad_norm_( + trainable, CONFIG["shared"]["optimizer"]["global_grad_clip_norm"], + ) + if not bool(torch.isfinite(grad_norm)) or not nonzero: + raise RuntimeError(f"{arm} update {update + 1} has nonfinite or absent gradients") + if update > 0 and not decoder_grads: + raise RuntimeError(f"{arm} decoder still has no gradient after prediction heads opened") + optimizer.step() + updates.append({ + "update": update + 1, "source_loss": source_losses, "source_terms": source_terms, + "diagnostics": diagnostics, "preclip_grad_norm": float(grad_norm), + "nonzero_gradient_tensors": nonzero, "decoder_gradient_tensors": decoder_grads, + }) + head_change = float((model.rotation_head.linear.bias.detach() - before).abs().max()) + if head_change <= 0: + raise RuntimeError(f"{arm} did not update the rotation head") + report = { + "arm": arm, "architecture": CONFIG["arms"][arm]["architecture"], + "trainable_parameters": trainable_parameter_count(model), + "all_parameters": sum(p.numel() for p in model.parameters()), + "shared_initial_state_sha256": initial_digest, + "updates": updates, + "rotation_head_max_update": head_change, + "elapsed_seconds": time.monotonic() - start, + } + del model, criterion, optimizer + torch.cuda.empty_cache() + return report + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--statistics", type=Path, default=ROOT / CONFIG["shared"]["normalization"]["statistics_asset"]) + parser.add_argument("--output", type=Path, default=ROOT / "smoke_report_mano_pkl_v2.json") + parser.add_argument("--device", default="cuda:0") + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + if not torch.cuda.is_available() or not args.device.startswith("cuda"): + raise RuntimeError("new-path smoke requires a real CUDA forward/backward") + statistics = json.loads(args.statistics.read_text()) + hashes = check_contract(statistics) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device(args.device) + torch.cuda.set_device(device) + batches, descriptors = sample_batches() + arms = {arm: smoke_arm(arm, statistics, batches, device) for arm in ("B0", "B1")} + if arms["B0"]["shared_initial_state_sha256"] != arms["B1"]["shared_initial_state_sha256"]: + raise RuntimeError("matched arms do not share identical non-decoder initialization") + result = { + "kind": "two_update_new_path_smoke_not_performance_or_training_result", + "formal_training_approved": False, "statistics_sha256": sha(args.statistics), + "config_sha256": sha(ROOT / "config.json"), "input_assets_sha256": hashes, + "samples": descriptors, "arms": arms, + } + temporary = args.output.with_suffix(args.output.suffix + ".tmp") + temporary.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") + temporary.replace(args.output) + print(json.dumps({"result": str(args.output), "arms": {key: { + "source_loss": value["updates"][-1]["source_loss"], + "preclip_grad_norm": value["updates"][-1]["preclip_grad_norm"], + "decoder_gradient_tensors": value["updates"][-1]["decoder_gradient_tensors"], + "rotation_head_max_update": value["rotation_head_max_update"] + } for key, value in arms.items()}}, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke_report.json b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke_report.json new file mode 100644 index 0000000000000000000000000000000000000000..2e425cde7d16b0d4c47376c35aca0a0e168a33c3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke_report.json @@ -0,0 +1,388 @@ +{ + "kind": "two_update_new_path_smoke_not_performance_or_training_result", + "formal_training_approved": false, + "statistics_sha256": "9c3f4e5083c5aa3787f4b5f42567affe61b3a04405175a4c13fe4af57398ed73", + "config_sha256": "3b141347810701f91cd7ecab2ce7919f2bda0fff3041d85c8a85a42b3a9fcf3c", + "input_assets_sha256": { + "dinov3": "9a21ac3df0c63839d62612dda6f454d816c25611cc7a52966ed5a5a94921dc8b", + "index": "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462", + "labels": "0bd3135ee5cdda31e50109cefc8fc8083b0d57d9646c9eb6d2f7aeab9e904b62" + }, + "samples": { + "H2O": { + "position": 0, + "tile_id": "21e4a88169875fa885addf4a:8", + "input_sha256": "eaef0787a8a0cb7f14b8c4b00f99044b5496956cadac3e4529644ca7aa297f39" + }, + "HOT3D": { + "position": 3, + "tile_id": "abfcc9e0f258ce65bb8c7e19:16", + "input_sha256": "558a9b7b037525937268c86ec72e19da9cc79c0182a3c46113e15c9ee78f5ded" + }, + "ARCTIC": { + "position": 7, + "tile_id": "f828239868b093de6fd05e00:52", + "input_sha256": "3899ce6ab5876f94498a1e693efb717135cf11ff2d4f8cc6d369afa87acd6738" + } + }, + "arms": { + "B0": { + "arm": "B0", + "architecture": "non_mot", + "trainable_parameters": 19395736, + "all_parameters": 105056152, + "shared_initial_state_sha256": "9e240103dea54aec6640fff3f47a18550d3a781cd8c093062dbd134462584ed1", + "updates": [ + { + "update": 1, + "source_loss": { + "H2O": 3.7985472679138184, + "ARCTIC": 4.058504581451416, + "HOT3D": 5.335982322692871 + }, + "source_terms": { + "H2O": { + "joint2d": 0.12329580634832382, + "global_orientation": 0.4755599796772003, + "local_pose": 0.15525883436203003, + "translation": 0.934148907661438, + "shape": 0.09566089510917664, + "joint3d_camera": 1.1198508739471436, + "joint3d_root_relative": 0.5037301182746887, + "vertices_camera": 0.10910995304584503, + "bimanual_relative_wrist": 0.13746987283229828, + "temporal_velocity": 0.00024711768492124975, + "temporal_acceleration": 5.1653292757691815e-05, + "reprojection": 0.144163578748703 + }, + "ARCTIC": { + "joint2d": 0.12679609656333923, + "global_orientation": 0.4721835255622864, + "local_pose": 0.2373819649219513, + "translation": 1.0138256549835205, + "shape": 0.05416140705347061, + "joint3d_camera": 1.130501627922058, + "joint3d_root_relative": 0.5547618269920349, + "vertices_camera": 0.11182468384504318, + "bimanual_relative_wrist": 0.17232197523117065, + "temporal_velocity": 0.00021346223365981132, + "temporal_acceleration": 1.7508531527710147e-05, + "reprojection": 0.18451504409313202 + }, + "HOT3D": { + "joint2d": 0.12042418122291565, + "global_orientation": 0.4976328909397125, + "local_pose": 0.20022286474704742, + "translation": 1.8163654804229736, + "shape": 0.06149355694651604, + "joint3d_camera": 1.5089590549468994, + "joint3d_root_relative": 0.6809073686599731, + "vertices_camera": 0.1533815860748291, + "bimanual_relative_wrist": 0.176408052444458, + "temporal_velocity": 0.00012852385407313704, + "temporal_acceleration": 1.5283134416677058e-05, + "reprojection": 0.12004367262125015 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5515102744102478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5515102744102478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.384185791015625e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5515102744102478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 97.3693618774414, + "nonzero_gradient_tensors": 8, + "decoder_gradient_tensors": 0 + }, + { + "update": 2, + "source_loss": { + "H2O": 3.6857731342315674, + "ARCTIC": 4.013528347015381, + "HOT3D": 5.063238143920898 + }, + "source_terms": { + "H2O": { + "joint2d": 0.12002970278263092, + "global_orientation": 0.47228509187698364, + "local_pose": 0.15262815356254578, + "translation": 0.8976303935050964, + "shape": 0.09547501057386398, + "joint3d_camera": 1.068666934967041, + "joint3d_root_relative": 0.4986898899078369, + "vertices_camera": 0.10417477786540985, + "bimanual_relative_wrist": 0.13695462048053741, + "temporal_velocity": 0.000247681193286553, + "temporal_acceleration": 5.09958881593775e-05, + "reprojection": 0.13893990218639374 + }, + "ARCTIC": { + "joint2d": 0.12598827481269836, + "global_orientation": 0.4714352786540985, + "local_pose": 0.2331799417734146, + "translation": 1.0025748014450073, + "shape": 0.053891170769929886, + "joint3d_camera": 1.112546443939209, + "joint3d_root_relative": 0.5508322715759277, + "vertices_camera": 0.11001140624284744, + "bimanual_relative_wrist": 0.1717999428510666, + "temporal_velocity": 0.00021351984469220042, + "temporal_acceleration": 1.9096161850029603e-05, + "reprojection": 0.18103604018688202 + }, + "HOT3D": { + "joint2d": 0.11670394241809845, + "global_orientation": 0.49706459045410156, + "local_pose": 0.19506408274173737, + "translation": 1.7003257274627686, + "shape": 0.060626279562711716, + "joint3d_camera": 1.3787906169891357, + "joint3d_root_relative": 0.6845939755439758, + "vertices_camera": 0.14042548835277557, + "bimanual_relative_wrist": 0.17636269330978394, + "temporal_velocity": 0.00012880559370387346, + "temporal_acceleration": 1.613441781955771e-05, + "reprojection": 0.11313585937023163 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5402734875679016, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5404338240623474, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.384185791015625e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5395641326904297, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 96.53389739990234, + "nonzero_gradient_tensors": 104, + "decoder_gradient_tensors": 90 + } + ], + "rotation_head_max_update": 0.00010006769298342988, + "elapsed_seconds": 3.149312816094607 + }, + "B1": { + "arm": "B1", + "architecture": "mot", + "trainable_parameters": 23071896, + "all_parameters": 111358360, + "shared_initial_state_sha256": "9e240103dea54aec6640fff3f47a18550d3a781cd8c093062dbd134462584ed1", + "updates": [ + { + "update": 1, + "source_loss": { + "H2O": 3.7985472679138184, + "ARCTIC": 4.058504581451416, + "HOT3D": 5.335982322692871 + }, + "source_terms": { + "H2O": { + "joint2d": 0.12329580634832382, + "global_orientation": 0.4755599796772003, + "local_pose": 0.15525883436203003, + "translation": 0.934148907661438, + "shape": 0.09566089510917664, + "joint3d_camera": 1.1198508739471436, + "joint3d_root_relative": 0.5037301182746887, + "vertices_camera": 0.10910995304584503, + "bimanual_relative_wrist": 0.13746987283229828, + "temporal_velocity": 0.00024711768492124975, + "temporal_acceleration": 5.1653292757691815e-05, + "reprojection": 0.144163578748703 + }, + "ARCTIC": { + "joint2d": 0.12679609656333923, + "global_orientation": 0.4721835255622864, + "local_pose": 0.2373819649219513, + "translation": 1.0138256549835205, + "shape": 0.05416140705347061, + "joint3d_camera": 1.130501627922058, + "joint3d_root_relative": 0.5547618269920349, + "vertices_camera": 0.11182468384504318, + "bimanual_relative_wrist": 0.17232197523117065, + "temporal_velocity": 0.00021346223365981132, + "temporal_acceleration": 1.7508531527710147e-05, + "reprojection": 0.18451504409313202 + }, + "HOT3D": { + "joint2d": 0.12042418122291565, + "global_orientation": 0.4976328909397125, + "local_pose": 0.20022286474704742, + "translation": 1.8163654804229736, + "shape": 0.06149355694651604, + "joint3d_camera": 1.5089590549468994, + "joint3d_root_relative": 0.6809073686599731, + "vertices_camera": 0.1533815860748291, + "bimanual_relative_wrist": 0.176408052444458, + "temporal_velocity": 0.00012852385407313704, + "temporal_acceleration": 1.5283134416677058e-05, + "reprojection": 0.12004367262125015 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5515102744102478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5515102744102478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.384185791015625e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5515102744102478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 96.48371887207031, + "nonzero_gradient_tensors": 8, + "decoder_gradient_tensors": 0 + }, + { + "update": 2, + "source_loss": { + "H2O": 3.6838605403900146, + "ARCTIC": 4.003681182861328, + "HOT3D": 5.064878940582275 + }, + "source_terms": { + "H2O": { + "joint2d": 0.11981838941574097, + "global_orientation": 0.4722316265106201, + "local_pose": 0.15226618945598602, + "translation": 0.8959423899650574, + "shape": 0.09545345604419708, + "joint3d_camera": 1.06890070438385, + "joint3d_root_relative": 0.49868184328079224, + "vertices_camera": 0.10417591035366058, + "bimanual_relative_wrist": 0.13689792156219482, + "temporal_velocity": 0.000247540301643312, + "temporal_acceleration": 5.1554648962337524e-05, + "reprojection": 0.13919329643249512 + }, + "ARCTIC": { + "joint2d": 0.12600281834602356, + "global_orientation": 0.4714508354663849, + "local_pose": 0.23290503025054932, + "translation": 0.9967656135559082, + "shape": 0.05384225398302078, + "joint3d_camera": 1.1099562644958496, + "joint3d_root_relative": 0.550831139087677, + "vertices_camera": 0.10973823070526123, + "bimanual_relative_wrist": 0.17146888375282288, + "temporal_velocity": 0.00021318050858099014, + "temporal_acceleration": 1.7637650671531446e-05, + "reprojection": 0.18048922717571259 + }, + "HOT3D": { + "joint2d": 0.11677369475364685, + "global_orientation": 0.49709686636924744, + "local_pose": 0.19505727291107178, + "translation": 1.7012100219726562, + "shape": 0.060652147978544235, + "joint3d_camera": 1.379798173904419, + "joint3d_root_relative": 0.6844714879989624, + "vertices_camera": 0.14052079617977142, + "bimanual_relative_wrist": 0.1760120689868927, + "temporal_velocity": 0.0001284886384382844, + "temporal_acceleration": 1.58047132572392e-05, + "reprojection": 0.11314260214567184 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5398387908935547, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5404338240623474, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.384185791015625e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5397546887397766, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 95.55139923095703, + "nonzero_gradient_tensors": 136, + "decoder_gradient_tensors": 122 + } + ], + "rotation_head_max_update": 0.00010006738011725247, + "elapsed_seconds": 1.0320865879766643 + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke_report_mano_pkl_v2.json b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke_report_mano_pkl_v2.json new file mode 100644 index 0000000000000000000000000000000000000000..295a90d665216eee07e62456ffdc57cc48cbb307 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke_report_mano_pkl_v2.json @@ -0,0 +1,392 @@ +{ + "kind": "two_update_new_path_smoke_not_performance_or_training_result", + "formal_training_approved": false, + "statistics_sha256": "cc5fa3eb0e7aa27134eee3f5a547d820582e938b9fea2846139f56b7905e19ff", + "config_sha256": "8ba60ae121a455bb3e1070f969b793f8038265c15d0b4e3f62566a392fb35bcb", + "input_assets_sha256": { + "dinov3": "9a21ac3df0c63839d62612dda6f454d816c25611cc7a52966ed5a5a94921dc8b", + "index": "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462", + "labels": "0bd3135ee5cdda31e50109cefc8fc8083b0d57d9646c9eb6d2f7aeab9e904b62", + "mano_pkl": { + "left": "c4022f7083f2ca7c78b2b3d595abbab52debd32b09d372b16923a801f0ea6a30", + "right": "45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767" + } + }, + "samples": { + "H2O": { + "position": 0, + "tile_id": "21e4a88169875fa885addf4a:8", + "input_sha256": "1b637e9937138868cbfd234814621eea181e8632285deca38c3e40e2d3cd02fb" + }, + "HOT3D": { + "position": 3, + "tile_id": "abfcc9e0f258ce65bb8c7e19:16", + "input_sha256": "a14e7bfdc09c68cf1d1a5c86681fd3885d7e8d84e731504e5a8869e4b2dcd98a" + }, + "ARCTIC": { + "position": 7, + "tile_id": "f828239868b093de6fd05e00:52", + "input_sha256": "f8908983073841c0ab343799a9794d8dc81687534324f3bbed214131ae1beff3" + } + }, + "arms": { + "B0": { + "arm": "B0", + "architecture": "non_mot", + "trainable_parameters": 19395736, + "all_parameters": 105056152, + "shared_initial_state_sha256": "2f586ab81ef37be2083ae9cdbcc9f4ccf4ba7156e46986f28eb296e976967129", + "updates": [ + { + "update": 1, + "source_loss": { + "H2O": 3.834120750427246, + "ARCTIC": 4.064811706542969, + "HOT3D": 5.342980861663818 + }, + "source_terms": { + "H2O": { + "joint2d": 0.12329580634832382, + "global_orientation": 0.4755599796772003, + "local_pose": 0.19416601955890656, + "translation": 0.934148907661438, + "shape": 0.09566089510917664, + "joint3d_camera": 1.1191259622573853, + "joint3d_root_relative": 0.5010771155357361, + "vertices_camera": 0.10899747163057327, + "bimanual_relative_wrist": 0.13746987283229828, + "temporal_velocity": 0.00024711768492124975, + "temporal_acceleration": 5.1653292757691815e-05, + "reprojection": 0.14432001113891602 + }, + "ARCTIC": { + "joint2d": 0.12679609656333923, + "global_orientation": 0.4721835255622864, + "local_pose": 0.2473057359457016, + "translation": 1.0138256549835205, + "shape": 0.05416140705347061, + "joint3d_camera": 1.1291896104812622, + "joint3d_root_relative": 0.5527065992355347, + "vertices_camera": 0.11163412779569626, + "bimanual_relative_wrist": 0.17232197523117065, + "temporal_velocity": 0.00021346223365981132, + "temporal_acceleration": 1.7508531527710147e-05, + "reprojection": 0.1844564974308014 + }, + "HOT3D": { + "joint2d": 0.12042418122291565, + "global_orientation": 0.4976328909397125, + "local_pose": 0.20780202746391296, + "translation": 1.8163654804229736, + "shape": 0.06149355694651604, + "joint3d_camera": 1.514883279800415, + "joint3d_root_relative": 0.6733893752098083, + "vertices_camera": 0.15395233035087585, + "bimanual_relative_wrist": 0.176408052444458, + "temporal_velocity": 0.00012852385407313704, + "temporal_acceleration": 1.5283134416677058e-05, + "reprojection": 0.12048578262329102 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.980232238769531e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 97.18485260009766, + "nonzero_gradient_tensors": 8, + "decoder_gradient_tensors": 0 + }, + { + "update": 2, + "source_loss": { + "H2O": 3.7253921031951904, + "ARCTIC": 4.016021728515625, + "HOT3D": 5.073129653930664 + }, + "source_terms": { + "H2O": { + "joint2d": 0.12002970278263092, + "global_orientation": 0.47229626774787903, + "local_pose": 0.18950222432613373, + "translation": 0.8976181745529175, + "shape": 0.09547727555036545, + "joint3d_camera": 1.0721731185913086, + "joint3d_root_relative": 0.49678611755371094, + "vertices_camera": 0.10441675782203674, + "bimanual_relative_wrist": 0.13695216178894043, + "temporal_velocity": 0.000247681193286553, + "temporal_acceleration": 5.124241579324007e-05, + "reprojection": 0.1398410052061081 + }, + "ARCTIC": { + "joint2d": 0.12598827481269836, + "global_orientation": 0.4714369773864746, + "local_pose": 0.24264366924762726, + "translation": 0.9993391036987305, + "shape": 0.053892988711595535, + "joint3d_camera": 1.110687255859375, + "joint3d_root_relative": 0.5494017601013184, + "vertices_camera": 0.10975614190101624, + "bimanual_relative_wrist": 0.17179007828235626, + "temporal_velocity": 0.00021348461450543255, + "temporal_acceleration": 1.9137249182676896e-05, + "reprojection": 0.1808527708053589 + }, + "HOT3D": { + "joint2d": 0.11670394241809845, + "global_orientation": 0.49706515669822693, + "local_pose": 0.20519554615020752, + "translation": 1.7002618312835693, + "shape": 0.06062830612063408, + "joint3d_camera": 1.3849955797195435, + "joint3d_root_relative": 0.6771657466888428, + "vertices_camera": 0.14102575182914734, + "bimanual_relative_wrist": 0.17634990811347961, + "temporal_velocity": 0.00012878798588644713, + "temporal_acceleration": 1.616362715139985e-05, + "reprojection": 0.11359262466430664 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5390527844429016, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5394572615623474, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.980232238769531e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5385875701904297, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 96.41411590576172, + "nonzero_gradient_tensors": 104, + "decoder_gradient_tensors": 90 + } + ], + "rotation_head_max_update": 0.00010006720549426973, + "elapsed_seconds": 5.598529469687492 + }, + "B1": { + "arm": "B1", + "architecture": "mot", + "trainable_parameters": 23071896, + "all_parameters": 111358360, + "shared_initial_state_sha256": "2f586ab81ef37be2083ae9cdbcc9f4ccf4ba7156e46986f28eb296e976967129", + "updates": [ + { + "update": 1, + "source_loss": { + "H2O": 3.834120750427246, + "ARCTIC": 4.064811706542969, + "HOT3D": 5.342980861663818 + }, + "source_terms": { + "H2O": { + "joint2d": 0.12329580634832382, + "global_orientation": 0.4755599796772003, + "local_pose": 0.19416601955890656, + "translation": 0.934148907661438, + "shape": 0.09566089510917664, + "joint3d_camera": 1.1191259622573853, + "joint3d_root_relative": 0.5010771155357361, + "vertices_camera": 0.10899747163057327, + "bimanual_relative_wrist": 0.13746987283229828, + "temporal_velocity": 0.00024711768492124975, + "temporal_acceleration": 5.1653292757691815e-05, + "reprojection": 0.14432001113891602 + }, + "ARCTIC": { + "joint2d": 0.12679609656333923, + "global_orientation": 0.4721835255622864, + "local_pose": 0.2473057359457016, + "translation": 1.0138256549835205, + "shape": 0.05416140705347061, + "joint3d_camera": 1.1291896104812622, + "joint3d_root_relative": 0.5527065992355347, + "vertices_camera": 0.11163412779569626, + "bimanual_relative_wrist": 0.17232197523117065, + "temporal_velocity": 0.00021346223365981132, + "temporal_acceleration": 1.7508531527710147e-05, + "reprojection": 0.1844564974308014 + }, + "HOT3D": { + "joint2d": 0.12042418122291565, + "global_orientation": 0.4976328909397125, + "local_pose": 0.20780202746391296, + "translation": 1.8163654804229736, + "shape": 0.06149355694651604, + "joint3d_camera": 1.514883279800415, + "joint3d_root_relative": 0.6733893752098083, + "vertices_camera": 0.15395233035087585, + "bimanual_relative_wrist": 0.176408052444458, + "temporal_velocity": 0.00012852385407313704, + "temporal_acceleration": 1.5283134416677058e-05, + "reprojection": 0.12048578262329102 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.980232238769531e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 96.2962875366211, + "nonzero_gradient_tensors": 8, + "decoder_gradient_tensors": 0 + }, + { + "update": 2, + "source_loss": { + "H2O": 3.723310708999634, + "ARCTIC": 4.006514072418213, + "HOT3D": 5.074931621551514 + }, + "source_terms": { + "H2O": { + "joint2d": 0.11981838941574097, + "global_orientation": 0.4722391664981842, + "local_pose": 0.1890067160129547, + "translation": 0.8958560228347778, + "shape": 0.09545501321554184, + "joint3d_camera": 1.0725897550582886, + "joint3d_root_relative": 0.49659985303878784, + "vertices_camera": 0.10443532466888428, + "bimanual_relative_wrist": 0.13688066601753235, + "temporal_velocity": 0.000247540301643312, + "temporal_acceleration": 5.143138696439564e-05, + "reprojection": 0.14013102650642395 + }, + "ARCTIC": { + "joint2d": 0.12600281834602356, + "global_orientation": 0.4714444875717163, + "local_pose": 0.2424372136592865, + "translation": 0.9935175776481628, + "shape": 0.05384264513850212, + "joint3d_camera": 1.1082983016967773, + "joint3d_root_relative": 0.5494860410690308, + "vertices_camera": 0.10949629545211792, + "bimanual_relative_wrist": 0.17143315076828003, + "temporal_velocity": 0.00021318050858099014, + "temporal_acceleration": 1.7678739823168144e-05, + "reprojection": 0.1803247630596161 + }, + "HOT3D": { + "joint2d": 0.11677369475364685, + "global_orientation": 0.4970947206020355, + "local_pose": 0.205274298787117, + "translation": 1.7010712623596191, + "shape": 0.060649435967206955, + "joint3d_camera": 1.3859223127365112, + "joint3d_root_relative": 0.6773160099983215, + "vertices_camera": 0.14111365377902985, + "bimanual_relative_wrist": 0.17598433792591095, + "temporal_velocity": 0.00012854146189056337, + "temporal_acceleration": 1.58047132572392e-05, + "reprojection": 0.11358698457479477 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5386180877685547, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5394572615623474, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.980232238769531e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5390222668647766, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 95.45271301269531, + "nonzero_gradient_tensors": 136, + "decoder_gradient_tensors": 122 + } + ], + "rotation_head_max_update": 0.00010006764205172658, + "elapsed_seconds": 1.0458772676065564 + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke_report_reprojection_only_20261006.json b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke_report_reprojection_only_20261006.json new file mode 100644 index 0000000000000000000000000000000000000000..e22ff37c14793ab8bc1ccc256831a9e77c4fc6ba --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/smoke_report_reprojection_only_20261006.json @@ -0,0 +1,392 @@ +{ + "kind": "two_update_new_path_smoke_not_performance_or_training_result", + "formal_training_approved": false, + "statistics_sha256": "cc5fa3eb0e7aa27134eee3f5a547d820582e938b9fea2846139f56b7905e19ff", + "config_sha256": "9485d9faa6d978b5d269df95552e4846d4b384becd67412ed5cab192800ac2b6", + "input_assets_sha256": { + "dinov3": "9a21ac3df0c63839d62612dda6f454d816c25611cc7a52966ed5a5a94921dc8b", + "index": "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462", + "labels": "0bd3135ee5cdda31e50109cefc8fc8083b0d57d9646c9eb6d2f7aeab9e904b62", + "mano_pkl": { + "left": "c4022f7083f2ca7c78b2b3d595abbab52debd32b09d372b16923a801f0ea6a30", + "right": "45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767" + } + }, + "samples": { + "H2O": { + "position": 0, + "tile_id": "21e4a88169875fa885addf4a:8", + "input_sha256": "1b637e9937138868cbfd234814621eea181e8632285deca38c3e40e2d3cd02fb" + }, + "HOT3D": { + "position": 3, + "tile_id": "abfcc9e0f258ce65bb8c7e19:16", + "input_sha256": "a14e7bfdc09c68cf1d1a5c86681fd3885d7e8d84e731504e5a8869e4b2dcd98a" + }, + "ARCTIC": { + "position": 7, + "tile_id": "f828239868b093de6fd05e00:52", + "input_sha256": "f8908983073841c0ab343799a9794d8dc81687534324f3bbed214131ae1beff3" + } + }, + "arms": { + "B0": { + "arm": "B0", + "architecture": "non_mot", + "trainable_parameters": 19395736, + "all_parameters": 105056152, + "shared_initial_state_sha256": "2f586ab81ef37be2083ae9cdbcc9f4ccf4ba7156e46986f28eb296e976967129", + "updates": [ + { + "update": 1, + "source_loss": { + "H2O": 3.710824966430664, + "ARCTIC": 3.938016176223755, + "HOT3D": 5.2225565910339355 + }, + "source_terms": { + "H2O": { + "joint2d": 0.0, + "global_orientation": 0.4755599796772003, + "local_pose": 0.19416601955890656, + "translation": 0.934148907661438, + "shape": 0.09566089510917664, + "joint3d_camera": 1.1191259622573853, + "joint3d_root_relative": 0.5010771155357361, + "vertices_camera": 0.10899747163057327, + "bimanual_relative_wrist": 0.13746987283229828, + "temporal_velocity": 0.00024711768492124975, + "temporal_acceleration": 5.1653292757691815e-05, + "reprojection": 0.14432001113891602 + }, + "ARCTIC": { + "joint2d": 0.0, + "global_orientation": 0.4721835255622864, + "local_pose": 0.2473057359457016, + "translation": 1.0138256549835205, + "shape": 0.05416140705347061, + "joint3d_camera": 1.1291896104812622, + "joint3d_root_relative": 0.5527065992355347, + "vertices_camera": 0.11163412779569626, + "bimanual_relative_wrist": 0.17232197523117065, + "temporal_velocity": 0.00021346223365981132, + "temporal_acceleration": 1.7508531527710147e-05, + "reprojection": 0.1844564974308014 + }, + "HOT3D": { + "joint2d": 0.0, + "global_orientation": 0.4976328909397125, + "local_pose": 0.20780202746391296, + "translation": 1.8163654804229736, + "shape": 0.06149355694651604, + "joint3d_camera": 1.514883279800415, + "joint3d_root_relative": 0.6733893752098083, + "vertices_camera": 0.15395233035087585, + "bimanual_relative_wrist": 0.176408052444458, + "temporal_velocity": 0.00012852385407313704, + "temporal_acceleration": 1.5283134416677058e-05, + "reprojection": 0.12048578262329102 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.980232238769531e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 97.18363952636719, + "nonzero_gradient_tensors": 6, + "decoder_gradient_tensors": 0 + }, + { + "update": 2, + "source_loss": { + "H2O": 3.6053621768951416, + "ARCTIC": 3.89003324508667, + "HOT3D": 4.956425666809082 + }, + "source_terms": { + "H2O": { + "joint2d": 0.0, + "global_orientation": 0.47229626774787903, + "local_pose": 0.18950222432613373, + "translation": 0.8976181745529175, + "shape": 0.09547727555036545, + "joint3d_camera": 1.0721731185913086, + "joint3d_root_relative": 0.49678611755371094, + "vertices_camera": 0.10441675782203674, + "bimanual_relative_wrist": 0.13695216178894043, + "temporal_velocity": 0.000247681193286553, + "temporal_acceleration": 5.124241579324007e-05, + "reprojection": 0.1398410052061081 + }, + "ARCTIC": { + "joint2d": 0.0, + "global_orientation": 0.4714369773864746, + "local_pose": 0.24264366924762726, + "translation": 0.9993391036987305, + "shape": 0.053892988711595535, + "joint3d_camera": 1.110687255859375, + "joint3d_root_relative": 0.5494017601013184, + "vertices_camera": 0.10975614190101624, + "bimanual_relative_wrist": 0.17179007828235626, + "temporal_velocity": 0.00021348461450543255, + "temporal_acceleration": 1.9137249182676896e-05, + "reprojection": 0.1808527708053589 + }, + "HOT3D": { + "joint2d": 0.0, + "global_orientation": 0.49706515669822693, + "local_pose": 0.20519554615020752, + "translation": 1.7002618312835693, + "shape": 0.06062830612063408, + "joint3d_camera": 1.3849955797195435, + "joint3d_root_relative": 0.6771657466888428, + "vertices_camera": 0.14102575182914734, + "bimanual_relative_wrist": 0.17634990811347961, + "temporal_velocity": 0.00012878798588644713, + "temporal_acceleration": 1.616362715139985e-05, + "reprojection": 0.11359262466430664 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5390527844429016, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5394572615623474, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.980232238769531e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5385875701904297, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 96.412841796875, + "nonzero_gradient_tensors": 102, + "decoder_gradient_tensors": 90 + } + ], + "rotation_head_max_update": 0.00010006720549426973, + "elapsed_seconds": 3.234531878028065 + }, + "B1": { + "arm": "B1", + "architecture": "mot", + "trainable_parameters": 23071896, + "all_parameters": 111358360, + "shared_initial_state_sha256": "2f586ab81ef37be2083ae9cdbcc9f4ccf4ba7156e46986f28eb296e976967129", + "updates": [ + { + "update": 1, + "source_loss": { + "H2O": 3.710824966430664, + "ARCTIC": 3.938016176223755, + "HOT3D": 5.2225565910339355 + }, + "source_terms": { + "H2O": { + "joint2d": 0.0, + "global_orientation": 0.4755599796772003, + "local_pose": 0.19416601955890656, + "translation": 0.934148907661438, + "shape": 0.09566089510917664, + "joint3d_camera": 1.1191259622573853, + "joint3d_root_relative": 0.5010771155357361, + "vertices_camera": 0.10899747163057327, + "bimanual_relative_wrist": 0.13746987283229828, + "temporal_velocity": 0.00024711768492124975, + "temporal_acceleration": 5.1653292757691815e-05, + "reprojection": 0.14432001113891602 + }, + "ARCTIC": { + "joint2d": 0.0, + "global_orientation": 0.4721835255622864, + "local_pose": 0.2473057359457016, + "translation": 1.0138256549835205, + "shape": 0.05416140705347061, + "joint3d_camera": 1.1291896104812622, + "joint3d_root_relative": 0.5527065992355347, + "vertices_camera": 0.11163412779569626, + "bimanual_relative_wrist": 0.17232197523117065, + "temporal_velocity": 0.00021346223365981132, + "temporal_acceleration": 1.7508531527710147e-05, + "reprojection": 0.1844564974308014 + }, + "HOT3D": { + "joint2d": 0.0, + "global_orientation": 0.4976328909397125, + "local_pose": 0.20780202746391296, + "translation": 1.8163654804229736, + "shape": 0.06149355694651604, + "joint3d_camera": 1.514883279800415, + "joint3d_root_relative": 0.6733893752098083, + "vertices_camera": 0.15395233035087585, + "bimanual_relative_wrist": 0.176408052444458, + "temporal_velocity": 0.00012852385407313704, + "temporal_acceleration": 1.5283134416677058e-05, + "reprojection": 0.12048578262329102 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.980232238769531e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5510219931602478, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 96.29508209228516, + "nonzero_gradient_tensors": 6, + "decoder_gradient_tensors": 0 + }, + { + "update": 2, + "source_loss": { + "H2O": 3.603492498397827, + "ARCTIC": 3.880511522293091, + "HOT3D": 4.958157539367676 + }, + "source_terms": { + "H2O": { + "joint2d": 0.0, + "global_orientation": 0.4722391664981842, + "local_pose": 0.1890067160129547, + "translation": 0.8958560228347778, + "shape": 0.09545501321554184, + "joint3d_camera": 1.0725897550582886, + "joint3d_root_relative": 0.49659985303878784, + "vertices_camera": 0.10443532466888428, + "bimanual_relative_wrist": 0.13688066601753235, + "temporal_velocity": 0.000247540301643312, + "temporal_acceleration": 5.143138696439564e-05, + "reprojection": 0.14013102650642395 + }, + "ARCTIC": { + "joint2d": 0.0, + "global_orientation": 0.4714444875717163, + "local_pose": 0.2424372136592865, + "translation": 0.9935175776481628, + "shape": 0.05384264513850212, + "joint3d_camera": 1.1082983016967773, + "joint3d_root_relative": 0.5494860410690308, + "vertices_camera": 0.10949629545211792, + "bimanual_relative_wrist": 0.17143315076828003, + "temporal_velocity": 0.00021318050858099014, + "temporal_acceleration": 1.7678739823168144e-05, + "reprojection": 0.1803247630596161 + }, + "HOT3D": { + "joint2d": 0.0, + "global_orientation": 0.4970947206020355, + "local_pose": 0.205274298787117, + "translation": 1.7010712623596191, + "shape": 0.060649435967206955, + "joint3d_camera": 1.3859223127365112, + "joint3d_root_relative": 0.6773160099983215, + "vertices_camera": 0.14111365377902985, + "bimanual_relative_wrist": 0.17598433792591095, + "temporal_velocity": 0.00012854146189056337, + "temporal_acceleration": 1.58047132572392e-05, + "reprojection": 0.11358698457479477 + } + }, + "diagnostics": { + "H2O": { + "gt_rotation_orthogonality_max": 3.5762786865234375e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5386180877685547, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + }, + "ARCTIC": { + "gt_rotation_orthogonality_max": 5.960464477539062e-07, + "pred_rotation_orthogonality_max": 3.5762786865234375e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5394572615623474, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.00012036781845381483 + }, + "HOT3D": { + "gt_rotation_orthogonality_max": 2.980232238769531e-07, + "pred_rotation_orthogonality_max": 2.384185791015625e-07, + "nonpositive_reprojection_joints": 0, + "minimum_supervised_joint_z_m": 0.5390222668647766, + "valid_root_frames": 16, + "valid_local_frames": 16, + "gt_wrist_joint_max_gap_mm": 0.0 + } + }, + "preclip_grad_norm": 95.4515151977539, + "nonzero_gradient_tensors": 134, + "decoder_gradient_tensors": 122 + } + ], + "rotation_head_max_update": 0.00010006764205172658, + "elapsed_seconds": 1.0147253321483731 + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/statistics.json b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/statistics.json new file mode 100644 index 0000000000000000000000000000000000000000..0ab5841b65067ae0f1212e0d3b8408b38b654e3a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/statistics.json @@ -0,0 +1,1111 @@ +{ + "version": "b0_b1_train_unique_quota_weighted_so3_delta_v1", + "training_index_sha256": "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462", + "label_inventory_sha256": "0bd3135ee5cdda31e50109cefc8fc8083b0d57d9646c9eb6d2f7aeab9e904b62", + "source_quota": { + "H2O": 21, + "ARCTIC": 15, + "HOT3D": 24 + }, + "source_hand_frames": { + "H2O": 95077, + "ARCTIC": 293441, + "HOT3D": 2084401 + }, + "source_local_pose_frames_by_side": { + "H2O": [ + 47584, + 47493 + ], + "ARCTIC": [ + 144564, + 148877 + ], + "HOT3D": [ + 1039059, + 1045342 + ] + }, + "mean_local": [ + [ + [ + [ + 0.8945355329421333, + 0.42565216331444267, + 0.1364786289851653 + ], + [ + -0.4211222701908895, + 0.9048845593569514, + -0.061967473618406724 + ], + [ + -0.1498739932516877, + -0.002042083032453926, + 0.9887029968821183 + ] + ], + [ + [ + 0.8555227364510554, + 0.5135595933462287, + -0.0658588756156196 + ], + [ + -0.5175425893190506, + 0.8519385862996353, + -0.0796888537670791 + ], + [ + 0.015182742052406186, + 0.10226039925520888, + 0.9946417923493538 + ] + ], + [ + [ + 0.9873413424242529, + 0.157201009527429, + -0.02109303542477176 + ], + [ + -0.1576836857660489, + 0.9872079132535782, + -0.023587947192349294 + ], + [ + 0.017115162374555567, + 0.026615383015698206, + 0.9994992209120626 + ] + ], + [ + [ + 0.774581796787653, + 0.6307693167808898, + 0.04640160657760684 + ], + [ + -0.6323468213499338, + 0.7708696545962478, + 0.07679500733313775 + ], + [ + 0.01267034387251533, + -0.08882592318930342, + 0.9959665746177023 + ] + ], + [ + [ + 0.9034686079360641, + 0.4223922212837144, + 0.07300195800852113 + ], + [ + -0.4286349430862587, + 0.8918468576192248, + 0.14450352286415194 + ], + [ + -0.004069402844038903, + -0.1618455867601005, + 0.9868077046754201 + ] + ], + [ + [ + 0.9555619415443343, + 0.29093517323136225, + -0.04751947862571008 + ], + [ + -0.28713782482046774, + 0.9550746909706467, + 0.07337713693443543 + ], + [ + 0.06673264140877762, + -0.056471759704844464, + 0.9961715188291854 + ] + ], + [ + [ + 0.78079029986713, + 0.587336550045882, + -0.21307811857063325 + ], + [ + -0.4790080595650874, + 0.7816809547250944, + 0.39940726569725343 + ], + [ + 0.4011455926532016, + -0.20978718264057036, + 0.8916678481893613 + ] + ], + [ + [ + 0.9434724888723766, + 0.325861229798318, + 0.06061453336693302 + ], + [ + -0.33033367389951557, + 0.9094330367073205, + 0.2526088193894814 + ], + [ + 0.027190561395670446, + -0.25835249303931, + 0.9656679878257127 + ] + ], + [ + [ + 0.9969716802400802, + 0.06387523620694657, + -0.044355642242899285 + ], + [ + -0.053355580365764675, + 0.9768001889739082, + 0.20739954885287387 + ], + [ + 0.056574294897114186, + -0.20440485566651825, + 0.9772502259589642 + ] + ], + [ + [ + 0.7471076278856317, + 0.6559799673771656, + -0.10733347453128847 + ], + [ + -0.6462945175697002, + 0.7546229356763807, + 0.1133473489346403 + ], + [ + 0.15534989190358026, + -0.01531363284840474, + 0.9877408079726844 + ] + ], + [ + [ + 0.9485540503959157, + 0.3159796182843005, + -0.02005228930600261 + ], + [ + -0.29377054054653073, + 0.9019670853729655, + 0.31647155703285124 + ], + [ + 0.11808506672946927, + -0.29429960538999267, + 0.94839003541939 + ] + ], + [ + [ + 0.9406627760766598, + 0.33613318602227765, + -0.046562033442120426 + ], + [ + -0.3278898607572366, + 0.9356651660875739, + 0.13045664484002067 + ], + [ + 0.08741728042184974, + -0.10744849103095037, + 0.990360056170896 + ] + ], + [ + [ + 0.9852759738591581, + 0.053622123900670685, + 0.16234507434556888 + ], + [ + 0.07462951895835261, + 0.7194226736039098, + -0.6905515560800999 + ], + [ + -0.1538235685320428, + 0.6924995917204455, + 0.7048280820392192 + ] + ], + [ + [ + 0.9787519251449366, + 0.14010099601805734, + 0.14972100700913188 + ], + [ + -0.19050107074277697, + 0.8914187960083716, + 0.41119566166101756 + ], + [ + -0.07585519804822895, + -0.43098055760989257, + 0.8991672524571444 + ] + ], + [ + [ + 0.9829934172828619, + 0.18019848852918952, + -0.03538991820220658 + ], + [ + -0.1775705462264917, + 0.8835447633423482, + -0.4333789938185061 + ], + [ + -0.046825662743723254, + 0.43229290521833885, + 0.9005166302775873 + ] + ] + ], + [ + [ + [ + 0.8785299694974963, + -0.4596850658639803, + -0.12990278255817383 + ], + [ + 0.45247248101178833, + 0.8879800711820408, + -0.08221950565756514 + ], + [ + 0.15314616097625405, + 0.013454865483008133, + 0.9881119470854853 + ] + ], + [ + [ + 0.8696202937710517, + -0.49215269236944864, + 0.0393226659199555 + ], + [ + 0.4936467927461569, + 0.8653452713765141, + -0.08654712772668612 + ], + [ + 0.008566718915779306, + 0.09467464655233591, + 0.9954714072373995 + ] + ], + [ + [ + 0.9895111988491456, + -0.13986547868265792, + 0.03612803931847358 + ], + [ + 0.13874449362319444, + 0.9898149880227243, + 0.031878754285834886 + ], + [ + -0.040218812033294256, + -0.02653181785035348, + 0.9988385804524103 + ] + ], + [ + [ + 0.7355314133835722, + -0.6723942350930872, + -0.08294294749735566 + ], + [ + 0.6774310493383989, + 0.7315577072951768, + 0.07687973913392923 + ], + [ + 0.008984059118355535, + -0.11273559114409273, + 0.993584406666666 + ] + ], + [ + [ + 0.8987940459229151, + -0.42962611208892376, + -0.08712443299598885 + ], + [ + 0.4382933986029288, + 0.8844508391070997, + 0.16014246764628906 + ], + [ + 0.008255892114831178, + -0.18212116025905287, + 0.9832414368970038 + ] + ], + [ + [ + 0.9577097712913094, + -0.28456288819076764, + 0.042614042728597964 + ], + [ + 0.2830398602861741, + 0.9583381376072057, + 0.038424620970608336 + ], + [ + -0.051772883465470064, + -0.024738162261584803, + 0.9983524387036824 + ] + ], + [ + [ + 0.7500114773987119, + -0.6384841500865619, + 0.1726869243991641 + ], + [ + 0.5187889175285973, + 0.7298230473742087, + 0.4452149801735445 + ], + [ + -0.4102936056285889, + -0.24432828245961316, + 0.8786141630833344 + ] + ], + [ + [ + 0.9323268974078356, + -0.35763003342347893, + -0.05354732078639211 + ], + [ + 0.3603504421635131, + 0.9064396781986895, + 0.22026045632300315 + ], + [ + -0.030234338134646998, + -0.2246505485873074, + 0.9739702335374433 + ] + ], + [ + [ + 0.9912435972109862, + -0.11976925898721096, + 0.05560085961456499 + ], + [ + 0.10398248662323802, + 0.9675321386679195, + 0.23036753920709152 + ], + [ + -0.08138656808019555, + -0.22256883260316815, + 0.9715139429209398 + ] + ], + [ + [ + 0.698503029725416, + -0.7121327134650447, + 0.07043092983432253 + ], + [ + 0.70120813363948, + 0.7007694116474494, + 0.131260752005787 + ], + [ + -0.14283091675912446, + -0.04229929210045998, + 0.9888428080870832 + ] + ], + [ + [ + 0.9345828005183774, + -0.35497979634626453, + 0.02333094857033724 + ], + [ + 0.32903062428881447, + 0.8874732439768834, + 0.32269194211392843 + ], + [ + -0.13525471250695792, + -0.2939057423922014, + 0.9462164537427726 + ] + ], + [ + [ + 0.9307546810985912, + -0.3633799190767711, + 0.04062952159230579 + ], + [ + 0.3555492029975167, + 0.9253828485743419, + 0.13134438629902773 + ], + [ + -0.0853257748918294, + -0.10780360836352693, + 0.9905038587319652 + ] + ], + [ + [ + 0.9813199606954645, + -0.11424132482716139, + -0.15479035642567715 + ], + [ + -0.04827248214690466, + 0.6326370594526551, + -0.7729425065776073 + ], + [ + 0.18622809188742143, + 0.7659760248916625, + 0.6153046620034162 + ] + ], + [ + [ + 0.9916457110414127, + -0.08524544348933331, + -0.09680908086269181 + ], + [ + 0.1207394174299816, + 0.8775414559570164, + 0.4640506288709336 + ], + [ + 0.045395780110500224, + -0.4718624878512243, + 0.8805027062462739 + ] + ], + [ + [ + 0.9755092642689023, + -0.21966977611404548, + 0.011263426989597229 + ], + [ + 0.20218647884043148, + 0.8753506206261017, + -0.4391832405085677 + ], + [ + 0.08661583630983725, + 0.430704632470448, + 0.8983268984444603 + ] + ] + ] + ], + "geodesic_mean_final_step_rad": 2.543164213194468e-07, + "geodesic_mean_step_history_rad": [ + 0.024878624641237624, + 0.0003492454111411091, + 6.689468948864454e-06, + 2.543164213194468e-07 + ], + "xyz_center": [ + 0.07174891128025795, + 0.05202783260666617, + 0.43106404328731673 + ], + "xyz_scale": 0.1547383683812374, + "beta_center": [ + -0.25382584935872243, + 0.14956684931528838, + -0.8570264034974872, + -1.1353964653658775, + -0.07119626380984889, + -1.2349882691555876, + -1.2360446930577347, + -0.4641101084588954, + -0.19527318261163287, + -0.19995166035789763 + ], + "beta_scale": [ + 1.1192564692255698, + 0.6480333931568955, + 2.1003177673150426, + 1.4693180011509825, + 0.8364393107111716, + 1.2700435915590453, + 1.621992553671842, + 1.1360204912339191, + 1.471618858604333, + 1.1451121686648695 + ], + "pose_center": [ + [ + [ + -0.10134831676194242, + -0.48570835201225804, + -0.03751156287852858, + -0.4765796658856649, + 0.1792883456679293, + -0.18347779537819744 + ], + [ + 0.9325218494847017, + -0.00118593864614488, + -0.0008824116925430663, + -0.0028193760535052573, + 0.9410244234144364, + 0.00044385621896402656 + ], + [ + 0.9405316648177208, + 0.000661356089155952, + -0.011093614004733464, + 0.0035285099205622345, + 0.932625169115509, + 0.0009692887586505971 + ], + [ + 0.965952888040726, + 0.006689850364846525, + -0.010104098374250078, + 0.005420945360777798, + 0.9580604177732686, + -0.003617642712073147 + ], + [ + 0.9135766269719997, + 0.001945865404110932, + 0.016813562790405818, + -0.003287274609449715, + 0.9115634236874226, + 0.007781652283738717 + ], + [ + 0.9375867643263512, + -0.0006993954916766412, + 0.005353617836410605, + 0.0030717780114206403, + 0.9375941493268349, + -0.0011986332335559495 + ], + [ + 0.9729986719361443, + -0.0005627703335383501, + -0.00014607045250876867, + 0.00112815001549325, + 0.9695828396863718, + -0.0012083804201566454 + ], + [ + 0.9233791218072048, + 0.015187422580005168, + 0.05423795232949343, + 0.019510598620070405, + 0.8314453576513103, + 0.010921904816531384 + ], + [ + 0.9441067684450727, + 0.02254892533269053, + 0.008576682426072317, + 0.02651460949221043, + 0.861839052513253, + 0.015403584018826487 + ], + [ + 0.9202650241729149, + 0.006248799031732884, + -0.033859456019060444, + -0.01753851539897324, + 0.8853488014121519, + -0.003110838057456785 + ], + [ + 0.9223389933640527, + 0.0033351925610771668, + 0.01655556531904007, + 0.002845504995417004, + 0.9181266113360415, + 0.013560763488074109 + ], + [ + 0.9324432044133549, + -0.0014351621592797114, + 0.013096207343436849, + 0.0036364677985214963, + 0.9314912704928753, + -0.005038165636011558 + ], + [ + 0.969886645255366, + -0.000363931899944605, + -0.00018732896491088918, + 0.0013166251241203725, + 0.9678048764992833, + 0.0005246436952300407 + ], + [ + 0.9509882085318838, + 0.007140355083183842, + -0.02206913506062648, + -0.002336646233380289, + 0.9187528568679999, + -0.008098936985028695 + ], + [ + 0.8970210660398709, + -0.026531715858028555, + 0.021108670892630074, + 0.004532298985925092, + 0.8961865154521732, + -0.03214712507717305 + ], + [ + 0.8605701750337832, + 0.03607010122829191, + 0.031444319413430365, + -0.0016315151700048013, + 0.8513317681543102, + 0.003669907104093883 + ] + ], + [ + [ + 0.38716473568210996, + 0.3194330803604645, + -0.37463444185671907, + 0.5041452585143826, + -0.31857260029141427, + 0.17742283643711815 + ], + [ + 0.9324827970245765, + 0.0008894041476119031, + 0.0009654412818896401, + 0.0006917615085654363, + 0.9413147317189612, + -6.989459840663398e-05 + ], + [ + 0.9378236502672588, + 0.0011015167989827553, + 0.011323816949102745, + -0.003942848666390629, + 0.9295873520940378, + 0.0036247912162194586 + ], + [ + 0.9681613201234877, + -0.004000004242126248, + 0.008081393416409722, + -0.004357638894371322, + 0.9644569210778275, + -0.0026269891587121985 + ], + [ + 0.9083542510393591, + -0.00015330102525569175, + -0.015077608579588514, + 0.0014225449482859836, + 0.9061360723842206, + 0.008979754572077687 + ], + [ + 0.9347638821536726, + 0.00189433341362822, + -0.0039845386439797586, + -0.0031184341683739908, + 0.9344814322305031, + -0.002315012738830613 + ], + [ + 0.9674334383776222, + 0.002977854142169387, + -0.0006611831993859959, + -0.003168397518619274, + 0.9665266742549468, + -0.0003747654799687386 + ], + [ + 0.9095108139334298, + -0.022615053549349954, + -0.06992119327461789, + -0.02307051862668943, + 0.8014067550494387, + 0.017857513872597233 + ], + [ + 0.9407932657547776, + -0.025850333113428627, + -0.023110521573433934, + -0.028706251198703292, + 0.8700736605114718, + 0.016466772408877672 + ], + [ + 0.9221660232390151, + -0.0001857948374408914, + 0.019729832042997622, + 0.0038108896551754578, + 0.8989999719811791, + -0.0018551441981830966 + ], + [ + 0.9085638004984115, + -0.003037389201702245, + -0.02149299872838175, + -0.004634863274713653, + 0.9029345467079862, + 0.015844326318092714 + ], + [ + 0.9253976807724061, + 0.0010074313542434436, + -0.01335434308404845, + -0.005202158780210773, + 0.9248869909468956, + -0.006406842431946269 + ], + [ + 0.9598220135667584, + 0.002902670313934363, + -0.0015692043320834955, + -0.004555585405131042, + 0.9581171741685165, + -4.7697845488743715e-05 + ], + [ + 0.9540331532581329, + -0.01122423161654762, + 0.026226174067039237, + -0.0024920087388355244, + 0.9146663953565535, + -0.012736029944385668 + ], + [ + 0.9132996219204812, + 0.01582349559313636, + -0.006103314305897702, + -0.004128117127962649, + 0.9296522744030395, + -0.027508589047525903 + ], + [ + 0.903101715509796, + -0.027536448192722728, + -0.006779631584838264, + -0.012660380882153172, + 0.8950565384728162, + 0.0034662257798459485 + ] + ] + ], + "pose_scale": [ + [ + [ + 0.49632420752937534, + 0.44393436379220946, + 0.5558717116297703, + 0.5312270308371142, + 0.4569302537734121, + 0.46483975160228075 + ], + [ + 0.1, + 0.31669995817728425, + 0.14948483201804896, + 0.3166423605510876, + 0.1, + 0.1 + ], + [ + 0.1, + 0.3181159407682578, + 0.1, + 0.3197234831049904, + 0.1, + 0.14033362630289029 + ], + [ + 0.1, + 0.23226201091115298, + 0.1023593101427444, + 0.23525330636281822, + 0.1, + 0.15368872630228522 + ], + [ + 0.12399233764920145, + 0.36443369106212575, + 0.1300201883851503, + 0.36380671586336233, + 0.12428781073090413, + 0.14552655395176362 + ], + [ + 0.1, + 0.32411097386152676, + 0.1, + 0.3239661359363273, + 0.1, + 0.1 + ], + [ + 0.1, + 0.2219898922433293, + 0.1, + 0.2223930085136279, + 0.1, + 0.1 + ], + [ + 0.1, + 0.28843512720650355, + 0.22653609302160455, + 0.28842177684275266, + 0.18960500099690103, + 0.4348120145724881 + ], + [ + 0.1, + 0.2813435805085701, + 0.1504595751928957, + 0.27576388813004704, + 0.1692288519141617, + 0.3893700377906849 + ], + [ + 0.11166894050456151, + 0.3559172902947154, + 0.11304735834435495, + 0.3353436615779794, + 0.16013043476107117, + 0.2788244887110111 + ], + [ + 0.11000695158261994, + 0.34415605790077447, + 0.13586997269975395, + 0.34302058858052636, + 0.10972394749889122, + 0.1647697348018462 + ], + [ + 0.1, + 0.33525534522604544, + 0.1, + 0.3357563040105839, + 0.1, + 0.1 + ], + [ + 0.1, + 0.22850594226725277, + 0.1, + 0.2273459390604369, + 0.1, + 0.1 + ], + [ + 0.1, + 0.22644543671107897, + 0.20023369432827082, + 0.22953350952289753, + 0.11299744165264788, + 0.30061284318378545 + ], + [ + 0.1365215517631591, + 0.3216349311607935, + 0.26854522172036294, + 0.3587564464395325, + 0.13276163852730383, + 0.2224048327048934 + ], + [ + 0.16633278632060736, + 0.39584329301796, + 0.2697603899460667, + 0.38678347973563254, + 0.15968304823581234, + 0.31641421330444397 + ] + ], + [ + [ + 0.3828301178411518, + 0.5208857543439791, + 0.43569959993734836, + 0.49772056644741863, + 0.3971282754031018, + 0.45544875055516304 + ], + [ + 0.1, + 0.31694568643123905, + 0.15300563759639954, + 0.3181236898151702, + 0.1, + 0.1 + ], + [ + 0.1, + 0.32630643142731464, + 0.1, + 0.32741912766184733, + 0.1, + 0.14151449894951806 + ], + [ + 0.1, + 0.22516818970688246, + 0.1, + 0.22686000294281924, + 0.1, + 0.12311898439912514 + ], + [ + 0.11619889730467055, + 0.37810792089923867, + 0.13489778817859194, + 0.3818124684163582, + 0.11552671262595628, + 0.14038367543785885 + ], + [ + 0.1, + 0.33271962580271924, + 0.1, + 0.3319161858307051, + 0.1, + 0.1 + ], + [ + 0.1, + 0.24075642966707572, + 0.1, + 0.24066413778729367, + 0.1, + 0.1 + ], + [ + 0.10717237725335449, + 0.31494036145812493, + 0.23815187528267606, + 0.3232590559361437, + 0.2125718737435964, + 0.4552063867940824 + ], + [ + 0.1, + 0.28443117297000875, + 0.15854038243188773, + 0.28059339602681327, + 0.17316069451655478, + 0.36491004619413225 + ], + [ + 0.10941527863119861, + 0.3540705721896772, + 0.10900849280081433, + 0.3455736124692597, + 0.1361280390121303, + 0.2320110370166424 + ], + [ + 0.11281647005294641, + 0.37379196222488476, + 0.1469444070294796, + 0.3722144381220239, + 0.11288478871959655, + 0.1820717338205816 + ], + [ + 0.1, + 0.3506305006304199, + 0.10274059789357093, + 0.3516054515223675, + 0.10339096403433233, + 0.10099435086715439 + ], + [ + 0.1, + 0.26396214597670753, + 0.1, + 0.26338872075147657, + 0.1, + 0.1 + ], + [ + 0.1, + 0.21209660033091327, + 0.2009491616108178, + 0.21967911275650198, + 0.11457796501504795, + 0.31910804751788546 + ], + [ + 0.12945106204095952, + 0.259789300558564, + 0.2852158989140777, + 0.2911857069245024, + 0.10139472834080258, + 0.1997570474912481 + ], + [ + 0.12530260685278607, + 0.30735660384186003, + 0.270987540028062, + 0.29726163280802415, + 0.11133764716607737, + 0.3129551772309444 + ] + ] + ], + "variance_floors": { + "xyz_m": 0.1, + "beta": 0.5, + "pose_component": 0.1 + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/statistics_mano_pkl_v2.json b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/statistics_mano_pkl_v2.json new file mode 100644 index 0000000000000000000000000000000000000000..24bd0611317efc29119d478742e076773cf76589 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/statistics_mano_pkl_v2.json @@ -0,0 +1,1109 @@ +{ + "version": "b0_b1_mano_pkl_mean_delta_v2", + "training_index_sha256": "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462", + "label_inventory_sha256": "0bd3135ee5cdda31e50109cefc8fc8083b0d57d9646c9eb6d2f7aeab9e904b62", + "mean_source": "official_mano_pkl_hands_mean_axis_angle", + "mano_pkl_sha256": { + "left": "c4022f7083f2ca7c78b2b3d595abbab52debd32b09d372b16923a801f0ea6a30", + "right": "45d60aa3b27ef9107a7afd4e00808f307fd91111e1cfa35afd5c4a62de264767" + }, + "source_quota": { + "H2O": 21, + "ARCTIC": 15, + "HOT3D": 24 + }, + "source_hand_frames": { + "H2O": 95077, + "ARCTIC": 293441, + "HOT3D": 2084401 + }, + "source_local_pose_frames_by_side": { + "H2O": [ + 47584, + 47493 + ], + "ARCTIC": [ + 144564, + 148877 + ], + "HOT3D": [ + 1039059, + 1045342 + ] + }, + "mean_local": [ + [ + [ + [ + 0.9137306492963517, + 0.40589126499527917, + 0.01867033842756021 + ], + [ + -0.40117559461245567, + 0.9084971026147197, + -0.11700921685064884 + ], + [ + -0.06445496740989151, + 0.09942482356630873, + 0.992955317038485 + ] + ], + [ + [ + 0.7257337026238132, + 0.6808340665183311, + -0.09887146577270467 + ], + [ + -0.6876690240337854, + 0.7221706688016633, + -0.07470500991887637 + ], + [ + 0.020540356870114025, + 0.1222067878256805, + 0.9922920914473607 + ] + ], + [ + [ + 0.9782053698821243, + 0.1911591261991394, + -0.08107060382504636 + ], + [ + -0.18243418792426105, + 0.9776946610477144, + 0.10407169084438836 + ], + [ + 0.0991565500115425, + -0.08701343706334119, + 0.9912601274944091 + ] + ], + [ + [ + 0.861940805289614, + 0.5008221182916844, + 0.07896362457816725 + ], + [ + -0.5066908987351973, + 0.8564043120340201, + 0.09917654696779159 + ], + [ + -0.01795498024531385, + -0.12549446266416178, + 0.9919318315917801 + ] + ], + [ + [ + 0.7607175844614655, + 0.6414799231637544, + 0.09905687693914514 + ], + [ + -0.6490796536875868, + 0.7522938953579781, + 0.1129136757701307 + ], + [ + -0.0020880277573848416, + -0.15019122206355315, + 0.988654761256497 + ] + ], + [ + [ + 0.9392709101003734, + 0.3319009333466876, + -0.08724636314949584 + ], + [ + -0.33014773637760597, + 0.9433082986303295, + 0.03423340327656275 + ], + [ + 0.09366231688335953, + -0.0033502505504255705, + 0.9955983860057681 + ] + ], + [ + [ + 0.7963314216142106, + 0.6034985260360358, + -0.040568411630510504 + ], + [ + -0.5184638153633422, + 0.7155929505741847, + 0.46810469047790865 + ], + [ + 0.31153096011275777, + -0.35173322015536795, + 0.8827413000026444 + ] + ], + [ + [ + 0.872663626525002, + 0.4882265523386931, + -0.009645129947560206 + ], + [ + -0.47441903765647647, + 0.8523325633099863, + 0.22012673220336276 + ], + [ + 0.11569257387289247, + -0.18752075915189131, + 0.9754235968223055 + ] + ], + [ + [ + 0.9950804814487978, + 0.08858123956425734, + -0.04436439379602033 + ], + [ + -0.06654170114287347, + 0.929362255782766, + 0.3631225681989224 + ], + [ + 0.07339644029952153, + -0.35838409775494806, + 0.9306845872946057 + ] + ], + [ + [ + 0.8016535042181872, + 0.5966841101119545, + -0.03632811465801428 + ], + [ + -0.5849358363142091, + 0.7955013562411537, + 0.1582013262077209 + ], + [ + 0.12329528202691947, + -0.10557303139717993, + 0.9867383688047772 + ] + ], + [ + [ + 0.8071385304598477, + 0.58909531339352, + 0.0386536464632753 + ], + [ + -0.5722486270280283, + 0.7646008899170049, + 0.2965079897787929 + ], + [ + 0.14511685467806304, + -0.2614425192578945, + 0.954247822953991 + ] + ], + [ + [ + 0.9227989131107248, + 0.3732253241789047, + -0.09562961546098692 + ], + [ + -0.35032290640707514, + 0.9161194752236443, + 0.19493324078374585 + ], + [ + 0.1603621751167163, + -0.146382937897508, + 0.9761434363270235 + ] + ], + [ + [ + 0.9602583282059144, + 0.18978269203784154, + 0.20466185016766583 + ], + [ + 0.030400261431124412, + 0.657781090617366, + -0.7525954164962392 + ], + [ + -0.277452279169052, + 0.7289077902101873, + 0.6258703269486421 + ] + ], + [ + [ + 0.9982858354861774, + -0.05717421775093005, + 0.012509975708765206 + ], + [ + 0.04417812738982766, + 0.8763264555819064, + 0.47968764452253854 + ], + [ + -0.0383885885126403, + -0.47831271368407335, + 0.8773501377444383 + ] + ], + [ + [ + 0.9616703643436919, + 0.27268893551218554, + -0.02882455190114301 + ], + [ + -0.24881545859668378, + 0.823602397148304, + -0.5096763276579452 + ], + [ + -0.11524312520229786, + 0.497312613816298, + 0.8598832398836536 + ] + ] + ], + [ + [ + [ + 0.9137306492963517, + -0.40589126499527917, + -0.01867033842756021 + ], + [ + 0.40117559461245567, + 0.9084971026147197, + -0.11700921685064884 + ], + [ + 0.06445496740989151, + 0.09942482356630873, + 0.992955317038485 + ] + ], + [ + [ + 0.7257337026238132, + -0.6808340665183311, + 0.09887146577270467 + ], + [ + 0.6876690240337854, + 0.7221706688016633, + -0.07470500991887637 + ], + [ + -0.020540356870114025, + 0.1222067878256805, + 0.9922920914473607 + ] + ], + [ + [ + 0.9782053698821243, + -0.1911591261991394, + 0.08107060382504636 + ], + [ + 0.18243418792426105, + 0.9776946610477144, + 0.10407169084438836 + ], + [ + -0.0991565500115425, + -0.08701343706334119, + 0.9912601274944091 + ] + ], + [ + [ + 0.861940805289614, + -0.5008221182916844, + -0.07896362457816725 + ], + [ + 0.5066908987351973, + 0.8564043120340201, + 0.09917654696779159 + ], + [ + 0.01795498024531385, + -0.12549446266416178, + 0.9919318315917801 + ] + ], + [ + [ + 0.7607175844614655, + -0.6414799231637544, + -0.09905687693914514 + ], + [ + 0.6490796536875868, + 0.7522938953579781, + 0.1129136757701307 + ], + [ + 0.0020880277573848416, + -0.15019122206355315, + 0.988654761256497 + ] + ], + [ + [ + 0.9392709101003734, + -0.3319009333466876, + 0.08724636314949584 + ], + [ + 0.33014773637760597, + 0.9433082986303295, + 0.03423340327656275 + ], + [ + -0.09366231688335953, + -0.0033502505504255705, + 0.9955983860057681 + ] + ], + [ + [ + 0.7963314216142106, + -0.6034985260360358, + 0.040568411630510504 + ], + [ + 0.5184638153633422, + 0.7155929505741847, + 0.46810469047790865 + ], + [ + -0.31153096011275777, + -0.35173322015536795, + 0.8827413000026444 + ] + ], + [ + [ + 0.872663626525002, + -0.4882265523386931, + 0.009645129947560206 + ], + [ + 0.47441903765647647, + 0.8523325633099863, + 0.22012673220336276 + ], + [ + -0.11569257387289247, + -0.18752075915189131, + 0.9754235968223055 + ] + ], + [ + [ + 0.9950804814487978, + -0.08858123956425734, + 0.04436439379602033 + ], + [ + 0.06654170114287347, + 0.929362255782766, + 0.3631225681989224 + ], + [ + -0.07339644029952153, + -0.35838409775494806, + 0.9306845872946057 + ] + ], + [ + [ + 0.8016535042181872, + -0.5966841101119545, + 0.03632811465801428 + ], + [ + 0.5849358363142091, + 0.7955013562411537, + 0.1582013262077209 + ], + [ + -0.12329528202691947, + -0.10557303139717993, + 0.9867383688047772 + ] + ], + [ + [ + 0.8071385304598477, + -0.58909531339352, + -0.0386536464632753 + ], + [ + 0.5722486270280283, + 0.7646008899170049, + 0.2965079897787929 + ], + [ + -0.14511685467806304, + -0.2614425192578945, + 0.954247822953991 + ] + ], + [ + [ + 0.9227989131107248, + -0.3732253241789047, + 0.09562961546098692 + ], + [ + 0.35032290640707514, + 0.9161194752236443, + 0.19493324078374585 + ], + [ + -0.1603621751167163, + -0.146382937897508, + 0.9761434363270235 + ] + ], + [ + [ + 0.9602583282059144, + -0.18978269203784154, + -0.20466185016766583 + ], + [ + -0.030400261431124412, + 0.657781090617366, + -0.7525954164962392 + ], + [ + 0.277452279169052, + 0.7289077902101873, + 0.6258703269486421 + ] + ], + [ + [ + 0.9982858354861774, + 0.05717421775093005, + -0.012509975708765206 + ], + [ + -0.04417812738982766, + 0.8763264555819064, + 0.47968764452253854 + ], + [ + 0.0383885885126403, + -0.47831271368407335, + 0.8773501377444383 + ] + ], + [ + [ + 0.9616703643436919, + -0.27268893551218554, + 0.02882455190114301 + ], + [ + 0.24881545859668378, + 0.823602397148304, + -0.5096763276579452 + ], + [ + 0.11524312520229786, + 0.497312613816298, + 0.8598832398836536 + ] + ] + ] + ], + "xyz_center": [ + 0.07174891128025795, + 0.05202783260666617, + 0.43106404328731673 + ], + "xyz_scale": 0.1547383683812374, + "beta_center": [ + -0.25382584935872243, + 0.14956684931528838, + -0.8570264034974872, + -1.1353964653658775, + -0.07119626380984889, + -1.2349882691555876, + -1.2360446930577347, + -0.4641101084588954, + -0.19527318261163287, + -0.19995166035789763 + ], + "beta_scale": [ + 1.1192564692255698, + 0.6480333931568955, + 2.1003177673150426, + 1.4693180011509825, + 0.8364393107111716, + 1.2700435915590453, + 1.621992553671842, + 1.1360204912339191, + 1.471618858604333, + 1.1451121686648695 + ], + "pose_center": [ + [ + [ + -0.10134831676194242, + -0.48570835201225804, + -0.03751156287852858, + -0.4765796658856649, + 0.1792883456679293, + -0.18347779537819744 + ], + [ + 0.928627487491059, + 0.023296298709176044, + 0.08363841090135787, + -0.03495796909117262, + 0.9359949296461965, + 0.09636023609291902 + ], + [ + 0.917902311728918, + -0.19611533499608946, + 0.01601707449258522, + 0.20126034054975034, + 0.9117227253124706, + 0.017515071242397453 + ], + [ + 0.9613759970232413, + -0.016267400977460062, + 0.07134448981053013, + 0.038526856018065575, + 0.9518307365631806, + -0.11599007391675405 + ], + [ + 0.9016536476206457, + 0.1428252808135437, + 0.0013481219960347404, + -0.14565473452096536, + 0.89939296300645, + -0.030193536828994005 + ], + [ + 0.9042139983216847, + -0.24180967098471293, + -0.03453894929313031, + 0.24463699252015353, + 0.9057122196677527, + 0.007494739483135748 + ], + [ + 0.9715579456492962, + -0.04647912516433085, + 0.02422367727722266, + 0.04593929656506919, + 0.9672693139334714, + 0.048624299880672364 + ], + [ + 0.9131183384187048, + 0.011297286937980426, + -0.03082460946032171, + -0.0013795599533321405, + 0.8187515940996524, + -0.12384919810044526 + ], + [ + 0.9241166737130957, + -0.1304488995960524, + 0.0457550539238151, + 0.19111437652648172, + 0.8506990428014548, + 0.07371078820935105 + ], + [ + 0.9199452147391642, + -0.00801305905469899, + -0.02070803289011336, + 0.004313130672103556, + 0.8702569343919974, + -0.15695691345489096 + ], + [ + 0.9184735992337035, + 0.07869476910435382, + -0.012222920164044075, + -0.07665911873996707, + 0.9105942389035065, + -0.06422730037477808 + ], + [ + 0.8847275627409081, + -0.28414545600677854, + -0.04510289749567819, + 0.2860378897939681, + 0.8870902873004195, + -0.018445218678765665 + ], + [ + 0.9668455177359342, + -0.03402815715524966, + 0.06942859755597176, + 0.0380795990768312, + 0.9661791213562775, + -0.042005919423632 + ], + [ + 0.9442023171232893, + -0.10206063172250869, + -0.0772149464842508, + 0.11343836873275194, + 0.9087867447484136, + 0.07311469882896646 + ], + [ + 0.8769739761528444, + 0.14733874095866387, + 0.13851521791609858, + -0.1656486507139384, + 0.8839727940568609, + -0.10853941016026392 + ], + [ + 0.8552745073404626, + -0.04567143227709013, + 0.003837769497681065, + 0.08603290738889442, + 0.8466064731013961, + 0.08016604501241856 + ] + ], + [ + [ + 0.38716473568210996, + 0.3194330803604645, + -0.37463444185671907, + 0.5041452585143826, + -0.31857260029141427, + 0.17742283643711815 + ], + [ + 0.927061916941444, + -0.05827787982347204, + -0.08562634641412441, + 0.06560822590055296, + 0.9362771255160361, + 0.07505612331974718 + ], + [ + 0.908521098173265, + 0.22018423934421097, + -0.03889220043343456, + -0.2233847928844115, + 0.9030437234891624, + 0.03281146446056914 + ], + [ + 0.964789077111788, + 0.04089346050274799, + -0.04921845194312521, + -0.05330036551895203, + 0.9617065313138368, + -0.06488423917623583 + ], + [ + 0.88778802207333, + -0.1913909017911522, + -0.031037476456151767, + 0.1930573069575672, + 0.8854854727575021, + -0.011366035408585747 + ], + [ + 0.9041134068900302, + 0.23248660720932848, + 0.03499649665536766, + -0.2350434880392787, + 0.9043696809756382, + 0.027222134029204335 + ], + [ + 0.9652166952465053, + 0.052691096105117394, + -0.04134581290371059, + -0.052225312763748415, + 0.9649567418139913, + 0.018357749095515387 + ], + [ + 0.8979011072510426, + -0.06429401636450832, + 0.008892261188613545, + 0.04175508390317821, + 0.7933729479955095, + -0.06604640360311806 + ], + [ + 0.9269967507810933, + 0.09941507124125874, + -0.06998736891417753, + -0.1632392976414775, + 0.8646172743298919, + 0.04775313586170886 + ], + [ + 0.9213256769655395, + -0.03477186340985943, + 0.019160316808497373, + 0.0364169520079342, + 0.8879141380710589, + -0.13516294170804333 + ], + [ + 0.8978745133697075, + -0.14345365098835733, + -0.012701567593629254, + 0.13823267775897236, + 0.8898773400568271, + -0.028515471893040704 + ], + [ + 0.8882300771709771, + 0.24487723496040675, + 0.050933071632123156, + -0.24878308257069554, + 0.8918603812630563, + -0.016900587488339173 + ], + [ + 0.9571929747929397, + 0.008787492039515971, + -0.0764150646163354, + -0.013272533623074656, + 0.9572935068523281, + -0.039607339588063666 + ], + [ + 0.950803966209944, + 0.06517425532258289, + 0.06703142677168109, + -0.08182885383648278, + 0.9121345659538843, + -0.04298921522266366 + ], + [ + 0.9030227858061078, + -0.11515434909080693, + -0.07984992858227265, + 0.12488201789230471, + 0.9227278100167265, + -0.046771444507141394 + ], + [ + 0.9008722983777608, + 0.02274770622009805, + -0.001969018799517516, + -0.06483148973332604, + 0.8913634639327056, + 0.07810282291231004 + ] + ] + ], + "pose_scale": [ + [ + [ + 0.49632420752937534, + 0.44393436379220946, + 0.5558717116297703, + 0.5312270308371142, + 0.4569302537734121, + 0.46483975160228075 + ], + [ + 0.1, + 0.31587414009481746, + 0.1498288879449111, + 0.3157013678070106, + 0.1, + 0.1 + ], + [ + 0.10184311442573904, + 0.3151613624359036, + 0.1, + 0.31495952883805783, + 0.1069910220588168, + 0.13153929505243359 + ], + [ + 0.1, + 0.23858755695351, + 0.10482482913583221, + 0.23163226120792996, + 0.1, + 0.1494286969669494 + ], + [ + 0.129667947204638, + 0.3636714231047747, + 0.13247317065988334, + 0.36281756801250026, + 0.12986443391151556, + 0.14305239559755126 + ], + [ + 0.11364647799235214, + 0.3183846831896193, + 0.1, + 0.3170251581069474, + 0.11305546573320553, + 0.1 + ], + [ + 0.1, + 0.22220635638193492, + 0.1, + 0.22287301370912538, + 0.1, + 0.1 + ], + [ + 0.10388928789971104, + 0.31726051982217257, + 0.231710796521827, + 0.29773906321438015, + 0.19910987200410485, + 0.4312910956769481 + ], + [ + 0.1, + 0.2833532442920388, + 0.19303754962892294, + 0.26678794065974754, + 0.1576871440553528, + 0.37190336470827445 + ], + [ + 0.11476796351602123, + 0.35631683759046096, + 0.11434332484600057, + 0.34430403402882687, + 0.14038045379568692, + 0.2823948524827526 + ], + [ + 0.11429332311144515, + 0.34527063271818326, + 0.13337618799279802, + 0.3466546107575484, + 0.11344509739818665, + 0.16666480190241634 + ], + [ + 0.1266621852865704, + 0.3296178453044056, + 0.1, + 0.3256319684126024, + 0.12665664874696927, + 0.1 + ], + [ + 0.1, + 0.22835304955631636, + 0.1, + 0.22754949409505543, + 0.1, + 0.1 + ], + [ + 0.1, + 0.21051385985091503, + 0.20367286927577752, + 0.2239306184467718, + 0.13792044041766677, + 0.29449220723310654 + ], + [ + 0.20102029684538875, + 0.27643850282039195, + 0.2705440248529881, + 0.32748850007128316, + 0.16388920687314856, + 0.21275203998451195 + ], + [ + 0.19215500981471384, + 0.3889062731318345, + 0.27970211263839756, + 0.3772035274099051, + 0.1763627845390682, + 0.3099078748842078 + ] + ], + [ + [ + 0.3828301178411518, + 0.5208857543439791, + 0.43569959993734836, + 0.49772056644741863, + 0.3971282754031018, + 0.45544875055516304 + ], + [ + 0.1, + 0.314778625581276, + 0.15205841002807224, + 0.3168664206127719, + 0.1, + 0.1 + ], + [ + 0.10570917378038704, + 0.3245026268210061, + 0.1, + 0.32203352866336216, + 0.10926290537714863, + 0.133756119485942 + ], + [ + 0.1, + 0.22899997047090953, + 0.10050617715218257, + 0.22531954776184623, + 0.1, + 0.11920985525450926 + ], + [ + 0.13775370850117924, + 0.36920944769741537, + 0.13764783018656643, + 0.37511591702324976, + 0.13755034664133148, + 0.13741585767101447 + ], + [ + 0.10958492347177651, + 0.32836251860611754, + 0.1, + 0.3267311764043475, + 0.11021902796321302, + 0.1 + ], + [ + 0.1, + 0.24170696537948866, + 0.1, + 0.24210704031062713, + 0.1, + 0.1 + ], + [ + 0.11174554073701363, + 0.3456737449639643, + 0.23996542441778396, + 0.32964431922653736, + 0.21800040778904548, + 0.4563597220764898 + ], + [ + 0.1, + 0.2829306212068661, + 0.19140152361144566, + 0.2758002044816588, + 0.16276134555137636, + 0.3477823029618103 + ], + [ + 0.11178510094535128, + 0.3543961539324164, + 0.10719260246558034, + 0.34883935169073704, + 0.12203697066349704, + 0.2354386389530635 + ], + [ + 0.1288064953346301, + 0.3693824440472659, + 0.14158592878236068, + 0.37007937501439403, + 0.1285639281259898, + 0.18630482250725203 + ], + [ + 0.12216111914056152, + 0.3487354833469266, + 0.10930926605834801, + 0.34497417724227386, + 0.12123458660617191, + 0.1 + ], + [ + 0.1, + 0.26239857243987513, + 0.1, + 0.2634818487388751, + 0.1, + 0.1 + ], + [ + 0.1, + 0.19844774757007672, + 0.20628587428878373, + 0.21507694202360708, + 0.1174622226113142, + 0.3152951552362483 + ], + [ + 0.16431560044462107, + 0.24178976762758275, + 0.28187125576578226, + 0.27612851963597596, + 0.12179742433865606, + 0.1992704952463128 + ], + [ + 0.1336350702103144, + 0.30435629016780946, + 0.27823853702791435, + 0.29534988587408934, + 0.11462303564615751, + 0.3078928494970238 + ] + ] + ], + "variance_floors": { + "xyz_m": 0.1, + "beta": 0.5, + "pose_component": 0.1 + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/throughput_probe.py b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/throughput_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..70c8e302925c3ae8156fc4e96e8902dfed03545b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/throughput_probe.py @@ -0,0 +1,286 @@ +"""Multi-rank, real-data RGB MANO throughput probe; never a training run.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from collections import defaultdict +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import json +import os +from pathlib import Path +import statistics +import subprocess +import threading +import time + +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from .loss import FromScratchLoss, TERMS +from .model import build_model, trainable_parameter_count +from .smoke import CONFIG, ROOT, U0Coverage, U0Dataset, a7, base, check_contract + + +PROBE_FIELDS = frozenset({ + "rgb", "K", "frame_valid", "K_input_available", "depth_input_available", + "joint_annotation_valid", "mano_annotation_valid", "joint_element_valid", + "joint2d_valid", "joint3d_valid", "joint3d_root_relative_valid", + "translation_valid", "global_orientation_valid", "local_pose_valid", + "shape_valid", "vertices_valid", "reprojection_valid", "K_supervision_valid", + "image_hw", "joint2d", "joint3d_camera", "joint3d_root_relative", + "mano_pose", "mano_pose_valid", "mano_shape", "wrist_root_translation", + "vertices_camera", "mano_target_contract_version", "sampling_source_id", "input_mode", +}) + + +def initialize_worker(_worker_id: int, opencv_threads: int) -> None: + if opencv_threads: + import cv2 + + cv2.setNumThreads(opencv_threads) + + +def collate_probe_samples(samples: list[dict]) -> dict: + for sample in samples: + missing = PROBE_FIELDS - sample.keys() + if missing: + raise RuntimeError(f"probe sample is missing required fields: {sorted(missing)}") + return base.collate_h2o_clips([ + {key: sample[key] for key in PROBE_FIELDS} for sample in samples + ]) + + +def collate_matching_resolutions(samples: list[dict], maximum: int) -> list[dict]: + if maximum < 1: + raise ValueError("maximum clips per microbatch must be positive") + grouped = defaultdict(list) + for sample in samples: + grouped[tuple(sample["rgb"].shape[-2:])].append(sample) + return [collate_probe_samples(group[offset:offset + maximum]) + for group in grouped.values() for offset in range(0, len(group), maximum)] + + +def monitor_gpus(stop: threading.Event, physical_gpus: tuple[int, ...], samples: list[dict]) -> None: + while not stop.is_set(): + try: + output = subprocess.check_output( + ["nvidia-smi", "--query-gpu=index,utilization.gpu,memory.used", + "--format=csv,noheader,nounits"], text=True, timeout=5, + ) + for line in output.splitlines(): + index, utilization, memory = (int(part.strip()) for part in line.split(",")) + if index in physical_gpus: + samples.append({"gpu": index, "utilization_pct": utilization, + "memory_mib": memory}) + except (OSError, subprocess.SubprocessError, ValueError): + pass + stop.wait(1) + + +def unfreeze_last_two(model) -> None: + encoder = model.rgb_encoder + encoder.backbone.requires_grad_(False) + for block in encoder._backbone_blocks()[-2:]: + block.requires_grad_(True) + encoder._backbone_final_norm().requires_grad_(True) + encoder.trainable_last_blocks = 2 + encoder.frozen = False + model.config.dinov3_trainable_last_blocks = 2 + + +def summarize(values: list[float]) -> dict[str, float]: + ordered = sorted(values) + return {"mean": statistics.mean(values), "median": statistics.median(values), + "p90": ordered[min(len(ordered) - 1, int(0.9 * len(ordered)))]} + + +def select_clip(values: dict, index: int, count: int) -> dict: + return { + key: value[index:index + 1] + if isinstance(value, torch.Tensor) and value.ndim and value.shape[0] == count else value + for key, value in values.items() + } + + +def run(args) -> None: + rank = int(os.environ["RANK"]) + local_rank = int(os.environ["LOCAL_RANK"]) + world = int(os.environ["WORLD_SIZE"]) + if world not in (2, 4) or len(args.physical_gpus) != world or args.clips_per_gpu != 10 or args.clips_per_gpu % args.microbatch_size: + raise ValueError("probe requires two/four ranks and the planned ten clips per GPU") + if args.warmup < 1 or args.timed < 3 or args.output.exists(): + raise ValueError("invalid probe duration or existing output") + torch.cuda.set_device(local_rank) + device = torch.device("cuda", local_rank) + free_bytes, _ = torch.cuda.mem_get_info(device) + if free_bytes < 18 * 1024**3: + raise RuntimeError(f"rank {rank}: less than 18 GiB free before probe") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=20), device_id=device) + + config = CONFIG["shared"] + fitted = json.loads((ROOT / config["normalization"]["statistics_asset"]).read_text()) + hashes = check_contract(fitted) + torch.manual_seed(config["seed"]) + model = build_model(args.arm, config, torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if args.dino_last2: + unfreeze_last_two(model) + model = model.to(device).train() + trainable = [parameter for parameter in model.parameters() if parameter.requires_grad] + parameters = trainable_parameter_count(model) + objective = FromScratchLoss( + fitted, {name: config["loss"][name] for name in TERMS}, config["smoke"], + ).to(device) + optimizer = torch.optim.AdamW(trainable, lr=config["smoke"]["learning_rate"], + weight_decay=config["optimizer"]["weight_decay"]) + model = DistributedDataParallel(model, device_ids=[local_rank], broadcast_buffers=False, + find_unused_parameters=False) + + total_updates = args.warmup + args.timed + coverage = U0Coverage() + coverage.seed = config["seed"] + dataset = U0Dataset() + dataset.sources["HOT3D"].native.provider_cache_size = args.hot3d_provider_cache_size + sampler = base.PositionSampler(coverage, 0, + total_updates * args.clips_per_gpu * world, rank, world) + loader = DataLoader(dataset, batch_size=args.microbatch_size, sampler=sampler, num_workers=args.workers, + persistent_workers=True, collate_fn=collate_probe_samples, + pin_memory=True, prefetch_factor=args.prefetch_factor, + worker_init_fn=partial(initialize_worker, opencv_threads=args.opencv_threads), + generator=torch.Generator().manual_seed(config["seed"] + rank)) + iterator = iter(loader) + rows: list[dict] = [] + source_counts: Counter[str] = Counter() + gpu_samples: list[dict] = [] + stop = threading.Event() + monitor = None + for update in range(total_updates): + if update == args.warmup: + dist.barrier(device_ids=[local_rank]) + torch.cuda.reset_peak_memory_stats(device) + if rank == 0: + monitor = threading.Thread(target=monitor_gpus, + args=(stop, args.physical_gpus, gpu_samples), + daemon=True) + monitor.start() + torch.cuda.synchronize(device) + started = time.perf_counter() + microsteps = args.clips_per_gpu // args.microbatch_size + batches = [next(iterator) for _ in range(microsteps)] + data_ready = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + total_loss = 0.0 + for micro, cpu in enumerate(batches): + if cpu["input_mode"] != ["rgb"] * args.microbatch_size or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("probe received non-RGB model input") + if cpu["rgb"].shape[:2] != (args.microbatch_size, 8): + raise RuntimeError("probe did not receive T=8") + source_counts.update(cpu["sampling_source_id"]) + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, model.module) + sync = model.no_sync() if micro + 1 < microsteps else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + # Keep the original per-clip masked-loss normalization when batching forwards. + losses = [objective(select_clip(prediction, index, args.microbatch_size), + select_clip(batch, index, args.microbatch_size))[0] + for index in range(args.microbatch_size)] + loss = torch.stack(losses).sum() / args.clips_per_gpu + if not bool(torch.isfinite(loss)): + raise RuntimeError(f"{args.arm} nonfinite loss at update {update + 1}") + loss.backward() + total_loss += float(loss.detach()) + norm = torch.nn.utils.clip_grad_norm_(trainable, config["optimizer"]["global_grad_clip_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"{args.arm} nonfinite gradient at update {update + 1}") + optimizer.step() + torch.cuda.synchronize(device) + ended = time.perf_counter() + row = {"update": update + 1, "warmup": update < args.warmup, + "seconds": ended - started, "data_wait_seconds": data_ready - started, + "compute_seconds": ended - data_ready, "loss": total_loss, + "preclip_grad_norm": float(norm)} + rows.append(row) + if rank == 0: + print(json.dumps({"arm": args.arm, "dino_last2": args.dino_last2, **row}), flush=True) + + stop.set() + if monitor is not None: + monitor.join(timeout=6) + timed = [row for row in rows if not row["warmup"]] + local = {"rank": rank, "timing_seconds": summarize([row["seconds"] for row in timed]), + "data_wait_seconds": summarize([row["data_wait_seconds"] for row in timed]), + "compute_seconds": summarize([row["compute_seconds"] for row in timed]), + "peak_allocated_mib": torch.cuda.max_memory_allocated(device) / 1024**2, + "peak_reserved_mib": torch.cuda.max_memory_reserved(device) / 1024**2, + "source_clips": dict(source_counts), "updates": rows} + gathered: list[dict | None] = [None] * world + dist.all_gather_object(gathered, local) + if rank == 0: + per_gpu = {} + for gpu in args.physical_gpus: + matching = [row for row in gpu_samples if row["gpu"] == gpu] + if matching: + per_gpu[str(gpu)] = { + "samples": len(matching), + "utilization_pct": summarize([row["utilization_pct"] for row in matching]), + "fraction_at_least_90pct": sum(row["utilization_pct"] >= 90 for row in matching) / len(matching), + "memory_mib": summarize([row["memory_mib"] for row in matching]), + } + slowest_mean = max(row["timing_seconds"]["mean"] for row in gathered) + measured_throughput = args.clips_per_gpu * world / slowest_mean + result = {"kind": "short_rgb_mano_throughput_not_convergence_or_formal_training", + "arm": args.arm, "dino_last2": args.dino_last2, + "world_size": world, "clips_per_gpu_per_update": args.clips_per_gpu, + "microbatch_size": args.microbatch_size, + "global_clips_per_update": args.clips_per_gpu * world, + "planned_six_gpu_global_batch": config["data"]["global_batch"], + "warmup_updates": args.warmup, "timed_updates": args.timed, + "workers_per_rank": args.workers, + "opencv_threads_per_worker": args.opencv_threads, + "prefetch_factor": args.prefetch_factor, + "hot3d_provider_cache_size": args.hot3d_provider_cache_size, + "trainable_parameters": parameters, "assets_sha256": hashes, + "rank_results": gathered, "gpu_samples": per_gpu, + "measured_clips_per_second": measured_throughput} + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") + temporary.replace(args.output) + print(json.dumps({"result": str(args.output), "arm": args.arm, + "dino_last2": args.dino_last2, + "microbatch_size": args.microbatch_size, + "seconds_per_update": slowest_mean, + "measured_clips_per_second": measured_throughput, + "gpu_samples": per_gpu}), flush=True) + dist.destroy_process_group() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--arm", choices=("B0", "B1"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--warmup", type=int, default=2) + parser.add_argument("--timed", type=int, default=10) + parser.add_argument("--clips-per-gpu", type=int, default=10) + parser.add_argument("--microbatch-size", type=int, choices=(1, 2, 5, 10), default=1) + parser.add_argument("--workers", type=int, choices=(1, 2, 4, 6, 8), default=2) + parser.add_argument("--opencv-threads", type=int, choices=(0, 1, 2, 4), default=0) + parser.add_argument("--prefetch-factor", type=int, choices=(2, 4), default=2) + parser.add_argument("--hot3d-provider-cache-size", type=int, choices=(2, 4, 8), default=2) + parser.add_argument("--physical-gpus", type=lambda value: tuple(map(int, value.split(","))), + default=(2, 5)) + parser.add_argument("--dino-last2", action="store_true") + run(parser.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/verify_transferred_labels.py b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/verify_transferred_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..2118f494875bb71f49b16c32f522da821cc22095 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/from_scratch_mean_pose/verify_transferred_labels.py @@ -0,0 +1,60 @@ +"""Verify a relocated canonical-label cache against the frozen training asset.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path + + +ROOT = Path(__file__).resolve().parent + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def verify(cache_root: Path) -> dict: + statistics = json.loads((ROOT / "statistics_mano_pkl_v2.json").read_text()) + inventory_path = cache_root / "label_inventory.json" + inventory_sha = sha256(inventory_path) + if inventory_sha != statistics["label_inventory_sha256"]: + raise RuntimeError("canonical label inventory differs from fitted statistics") + + entries = json.loads(inventory_path.read_text())["entries"] + names: set[str] = set() + counts: Counter[str] = Counter() + for entry in entries: + original = Path(entry["path"]) + if original.parent.name != "labels" or original.suffix != ".npz": + raise RuntimeError(f"unexpected canonical label path: {original}") + if original.name in names: + raise RuntimeError(f"duplicate canonical label file: {original.name}") + names.add(original.name) + relocated = cache_root / "labels" / original.name + if sha256(relocated) != entry["sha256"]: + raise RuntimeError(f"canonical label checksum differs: {relocated}") + counts[entry["source"]] += 1 + + actual = {path.name for path in (cache_root / "labels").glob("*.npz")} + if actual != names: + raise RuntimeError(f"label set differs: missing={len(names - actual)}, extra={len(actual - names)}") + return {"inventory_sha256": inventory_sha, "verified_files": len(entries), + "files_by_source": dict(sorted(counts.items())), "cache_root": str(cache_root)} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-root", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(verify(args.cache_root.resolve()), sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/__init__.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b0093c2742b267b09222ef93ea4b01b48b0f2626 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/__init__.py @@ -0,0 +1 @@ +"""GRAB original-personalized RGB pilot.""" diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/check_pose_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/check_pose_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c8ab9c99428c9bb1147dc623fc1b79f349894d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/check_pose_contract.py @@ -0,0 +1,54 @@ +"""Check camera-space pose conversion against the standard MANO output.""" + +import json + +import torch + +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + +from .data import MANIFEST, MANO_ROOT, PersonalGrabDataset + + +def main() -> None: + torch.set_num_threads(1) + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + + layers = {side: ManoLayer(mano_root=MANO_ROOT, side=side, + use_pca=False, ncomps=45, flat_hand_mean=True) + for side in ("left", "right")} + dataset = PersonalGrabDataset() + rows = [] + for subject in MANIFEST["summary"]["subjects"]: + index = next(i for i, row in enumerate(MANIFEST["clips"]) if row["subject"] == subject) + clip = MANIFEST["clips"][index] + sample = dataset[{"clip_index": index, "start": clip["frames"] // 2 - 4}] + for side_index, side in enumerate(("left", "right")): + pose = sample["mano_pose"][:, side_index] + layer = layers[side] + with torch.no_grad(): + v, j = layer(pose, torch.zeros(8, 10)) + standard = layer.th_v_template[0].clone() + layer.th_v_template[0].copy_(torch.from_numpy( + dataset._templates[subject][side_index])) + pv, pj = layer(pose, torch.zeros(8, 10)) + layer.th_v_template[0].copy_(standard) + v = (v - j[:, :1]) / 1000 + sample["wrist_root_translation"][:, side_index, None] + j = (j - j[:, :1]) / 1000 + sample["wrist_root_translation"][:, side_index, None] + pv = (pv - pj[:, :1]) / 1000 + sample["wrist_root_translation"][:, side_index, None] + pj = (pj - pj[:, :1]) / 1000 + sample["wrist_root_translation"][:, side_index, None] + valid = sample["vertices_valid"][:, side_index] + if not valid.any(): + continue + gt_v = sample["vertices_camera"][:, side_index] + gt_j = sample["joint3d_camera"][:, side_index] + rows.append({"subject": subject, "side": side, "valid_frames": int(valid.sum()), + "personal_joint_mean_mm": float(torch.linalg.vector_norm(pj[valid] - gt_j[valid], dim=-1).mean() * 1000), + "personal_vertex_mean_mm": float(torch.linalg.vector_norm(pv[valid] - gt_v[valid], dim=-1).mean() * 1000), + "joint_mean_mm": float(torch.linalg.vector_norm(j[valid] - gt_j[valid], dim=-1).mean() * 1000), + "vertex_mean_mm": float(torch.linalg.vector_norm(v[valid] - gt_v[valid], dim=-1).mean() * 1000)}) + print(json.dumps(rows, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/compare_cached_external_h2o.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/compare_cached_external_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..67d5196471819a6a9d769242ba68b534b405fc90 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/compare_cached_external_h2o.py @@ -0,0 +1,170 @@ +"""Re-score cached H2O baselines on the frozen RGB MoT development panel.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +from experiments.from_scratch_mean_pose import smoke # noqa: F401 - installs frozen eval imports +from clean_eval import dataset_for +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from targets import NativePanel + + +PANEL_ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925/eval/frozen_panels_sync_v2") +BASELINES = Path("/SSD3/jiasen/foundation_hand/external_baselines/artifacts") +PREDICTIONS = { + "FoundationHand-Phase3": "foundation_hand/phase3_best.npz", + "QORT-Former": "qort/qort.npz", + "WiLoR-H2O-K": "wilor/wilor_h2o_k.npz", + "HaWoR-camera": "hawor/hawor.npz", + "WildHands-zero-shot": "wildhands/wildhands.npz", + "Hamba-zero-shot": "hamba/hamba.npz", + "PAD-Hand-WiLoR": "pad_hand/pad_hand_h2o_k.npz", + "HandDGP-zero-shot": "handdgp/handdgp_h2o.npz", + "Dyn-HaMR-TTO": "dynhamr/dynhamr_h2o.npz", +} +METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", "pa_mpjpe_mm", +) + + +def load_panel(): + manifest = PANEL_ROOT / "h2o_development_t8.jsonl" + rows = [json.loads(line) for line in manifest.read_text().splitlines()] + dataset = NativePanel("H2O", dataset_for("H2O", manifest), rows) + frames = [] + for clip in range(len(dataset)): + sample = dataset[clip] + for frame in range(8): + frame_id = int(sample["frame_id"][frame]) + key = f'{sample["physical_recording_id"]}/cam4/{frame_id:06d}' + frames.append({ + "key": key, + "joints": sample["joint3d_camera"][frame].numpy().copy(), + "vertices": sample["vertices_camera"][frame].numpy().copy(), + "joint_valid": sample["joint3d_valid"][frame].numpy().copy(), + "vertices_valid": sample["vertices_valid"][frame].numpy().copy(), + "joint2d": sample["joint2d"][frame].numpy().copy(), + "joint2d_valid": sample["joint2d_valid"][frame].numpy().copy(), + "K": sample["K"][frame].numpy().copy(), + }) + if (clip + 1) % 24 == 0: + print(json.dumps({"panel_clips_loaded": clip + 1}), flush=True) + if len(frames) != 768 or len({row["key"] for row in frames}) != 768: + raise RuntimeError("unexpected or duplicate H2O panel frames") + return frames + + +def score(name, path, frames): + with np.load(path, allow_pickle=False) as payload: + lookup = {key: index for index, key in enumerate(payload["frame_keys"].tolist())} + if len(lookup) != len(payload["frame_keys"]): + raise RuntimeError(f"duplicate prediction frame: {name}") + joints = payload["joints_camera_m"] + vertices = payload["vertices_camera_m"] if "vertices_camera_m" in payload else None + detected = payload["detected"] if "detected" in payload else np.ones(joints.shape[:2], bool) + values = {metric: [] for metric in METRICS} + pa_predicted, pa_target = [], [] + valid_hands = 0 + detected_hands = 0 + for frame in frames: + index = lookup.get(frame["key"]) + if index is None: + raise RuntimeError(f"missing frame in {name}: {frame['key']}") + for side in range(2): + mask = frame["joint_valid"][side].astype(bool) + if not mask.any(): + continue + valid_hands += 1 + if not detected[index, side] or not np.isfinite(joints[index, side]).all(): + continue + detected_hands += 1 + pred = joints[index, side] + gt = frame["joints"][side] + values["absolute_mpjpe_mm"].append(float(np.linalg.norm(pred - gt, axis=-1)[mask].mean() * 1000)) + relative = (pred - pred[:1]) - (gt - gt[:1]) + values["root_relative_mpjpe_mm"].append(float(np.linalg.norm(relative, axis=-1)[mask].mean() * 1000)) + if mask.all(): + pa_predicted.append(pred) + pa_target.append(gt) + if (vertices is not None and frame["vertices_valid"][side] + and np.isfinite(vertices[index, side]).all()): + pred_vertices = vertices[index, side] + gt_vertices = frame["vertices"][side] + values["mpvpe_mm"].append(float(np.linalg.norm(pred_vertices - gt_vertices, axis=-1).mean() * 1000)) + z = pred[:, 2] + uv = pred[:, :2] / np.maximum(z[:, None], 1e-8) + uv = uv @ frame["K"][:2, :2].T + frame["K"][:2, 2] + valid2d = frame["joint2d_valid"][side].astype(bool) & (z > 1e-8) + valid2d &= np.isfinite(uv).all(-1) & np.isfinite(frame["joint2d"][side]).all(-1) + if valid2d.any(): + delta = uv - frame["joint2d"][side] + values["projected_mano_2d_error_px"].append(float(np.linalg.norm(delta, axis=-1)[valid2d].mean())) + if pa_predicted: + values["pa_mpjpe_mm"] = aligned_mpjpe_mm( + np.stack(pa_predicted), np.stack(pa_target), estimate_scale=True, + ).tolist() + return { + "model": name, "checkpoint": str(path), "valid_hands": valid_hands, + "detected_hands": detected_hands, + "metrics": {key: {"mean": float(np.mean(items)) if items else None, "hands": len(items)} + for key, items in values.items()}, + } + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + frames = load_panel() + with np.load(BASELINES / "ground_truth/official_val_cam4.npz", allow_pickle=False) as gt: + frame_keys = gt["frame_keys"] + joints = gt["joints_camera_m"] + vertices = gt["vertices_camera_m"] + frame_lookup = {key: index for index, key in enumerate(frame_keys.tolist())} + gt_lookup = {} + for frame in frames: + index = frame_lookup[frame["key"]] + gt_lookup[frame["key"]] = { + "joints": joints[index], + "vertices": vertices[index], + } + gt_audit = {"joint_max_mm": 0.0, "vertex_max_mm": 0.0, + "joint_hands_gt1mm": 0, "vertex_hands_gt1mm": 0} + for frame in frames: + cached = gt_lookup[frame["key"]] + for side in range(2): + if not frame["joint_valid"][side].any(): + continue + joint_diff = float(np.linalg.norm(frame["joints"][side] - cached["joints"][side], axis=-1).max() * 1000) + vertex_diff = float(np.linalg.norm(frame["vertices"][side] - cached["vertices"][side], axis=-1).max() * 1000) + gt_audit["joint_max_mm"] = max(gt_audit["joint_max_mm"], joint_diff) + gt_audit["vertex_max_mm"] = max(gt_audit["vertex_max_mm"], vertex_diff) + gt_audit["joint_hands_gt1mm"] += joint_diff > 1 + gt_audit["vertex_hands_gt1mm"] += vertex_diff > 1 + print(json.dumps({"cached_vs_current_gt": gt_audit}), flush=True) + results = [] + for name, relative in PREDICTIONS.items(): + result = score(name, BASELINES / "predictions" / relative, frames) + results.append(result) + print(json.dumps(result), flush=True) + report = { + "role": "cached_external_predictions_recomputed_on_h2o_development_t8", + "panel": str(PANEL_ROOT / "h2o_development_t8.jsonl"), + "clips": 96, "frames": 768, "image_hw": [512, 896], + "cached_vs_current_gt": gt_audit, + "metrics": results, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/compare_mirohand_a7.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/compare_mirohand_a7.py new file mode 100644 index 0000000000000000000000000000000000000000..b04d5b861df0ae7034508a218644ad6902091c68 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/compare_mirohand_a7.py @@ -0,0 +1,175 @@ +"""Compare RGB GRAB checkpoints and refit A7 on one MiroHand hand-frame mask.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np +import torch + +from experiments.vitpose_mot_io_v4.model import build_model + +from .evaluate_mirohand_multisource import ( + BENCH, + CONFIG, + METRICS, + PARENT, + STATS, + TOP, + canonical, + infer, + load_benchmark_code, + sha, +) + + +A7 = Path("/SSD3/yangzijing/MiroHand_A7_refit_rotationfix_public_benchmark_20261002") +NATIVE = TOP / "rgb_native_hawor/predictions/HaWoR" +GRAB = Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_5k_to_20k") +METHODS = { + "A6": BENCH / "predictions/A6", + "A6 + P3R4": BENCH / "predictions/P3R4", + "WiLoR + GeoCalib": BENCH / "predictions/WiLoR", + "HaWoR + GeoCalib": BENCH / "predictions/HaWoR", + "HaWoR native 600px": NATIVE, + "MINT": BENCH / "predictions/MINT", + "ACE-Ego-Hand": BENCH / "predictions/ACE-Ego-Hand", + "refit A7 only": A7 / "rgb/predictions/A7", + "refit A7 + pipeline": A7 / "rgb/predictions/Old_A7_Current", +} + + +def read_prediction(path: Path) -> dict[str, np.ndarray]: + with np.load(path) as array: + return {key: array[key] for key in + ("joints_camera_m", "vertices_camera_m", "valid")} + + +def score(metric_values, gt, prediction, clip, receipt, common) -> dict: + values, _ = metric_values(canonical(gt, clip["dataset"]), + canonical(prediction, clip["dataset"]), + gt["K"], receipt["image_size_hw"], + gt["timestamps_s"], common) + return {key: {"sum": float(np.nansum(values[key])), + "n": int(np.isfinite(values[key]).sum())} for key in METRICS} + + +def inputs(clip): + receipt = json.loads((BENCH / "inputs" / clip["id"] / "complete.json").read_text()) + with np.load(receipt["reference"]) as array: + gt = {key: array[key] for key in array.files} + predictions = {name: read_prediction(root / clip["id"] / "prediction.npz") + for name, root in METHODS.items()} + common = gt["valid"] & np.isfinite(gt["joints_camera_m"]).all(axis=(2, 3)) + for prediction in predictions.values(): + common &= prediction["valid"] & np.isfinite(prediction["joints_camera_m"]).all(axis=(2, 3)) + common &= np.isfinite(prediction["vertices_camera_m"]).all(axis=(2, 3)) + return receipt, gt, predictions, common + + +def aggregate(output: Path, selection: list[dict], updates: list[int]): + groups = [] + for partition in sorted({clip["partition"] for clip in selection}): + clips = [clip for clip in selection if clip["partition"] == partition] + rows = [json.loads((output / "baseline" / f"{clip['id']}.json").read_text()) + for clip in clips] + methods = list(METHODS) + [f"FoundationHand + GRAB {update // 1000}K" if update != 40000 + else "FoundationHand 40K parent" for update in updates] + for update in updates: + rows_for_update = [json.loads((output / f"update_{update:07d}" / f"{clip['id']}.json").read_text()) + for clip in clips] + for row, update_row in zip(rows, rows_for_update): + name = "FoundationHand 40K parent" if update == 40000 else f"FoundationHand + GRAB {update // 1000}K" + row["scores"][name] = update_row["scores"] + groups.append({ + "partition": partition, + "dataset": clips[0]["dataset"], + "recordings": len(clips), + "common_hand_frames": sum(row["common_hand_frames"] for row in rows), + "scores": { + name: {key: (sum(row["scores"][name][key]["sum"] for row in rows) / + sum(row["scores"][name][key]["n"] for row in rows) + if sum(row["scores"][name][key]["n"] for row in rows) else None) + for key in METRICS} + for name in methods + }, + }) + (output / "summary.json").write_text(json.dumps({ + "benchmark": str(TOP), + "a7_release": str(A7), + "input_mode": "rgb", + "mask": "intersection of benchmark RGB methods, HaWoR native, refit A7 only and pipeline", + "selection_sha256": sha(BENCH / "selection.json"), + "metric_code_sha256": sha(TOP / "code/metrics.py"), + "groups": groups, + }, indent=2) + "\n") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--updates", nargs="+", type=int, default=[40000, 10000, 15000, 20000]) + parser.add_argument("--limit", type=int) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + torch.set_num_threads(2) + metric_values, runner_class, config_class = load_benchmark_code() + selection = json.loads((BENCH / "selection.json").read_text()) + if args.limit is not None: + selection = selection[:args.limit] + args.output.mkdir(parents=True, exist_ok=True) + + for index, clip in enumerate(selection): + path = args.output / "baseline" / f"{clip['id']}.json" + if path.exists(): + continue + receipt, gt, predictions, common = inputs(clip) + row = {"id": clip["id"], "partition": clip["partition"], + "common_hand_frames": int(common.sum()), + "scores": {name: score(metric_values, gt, prediction, clip, receipt, common) + for name, prediction in predictions.items()}} + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(row) + "\n") + print(f"baseline {index + 1}/{len(selection)} {clip['partition']}", flush=True) + + statistics = json.loads(STATS.read_text()) + for update in args.updates: + checkpoint = PARENT if update == 40000 else GRAB / f"update_{update:07d}.pt" + state = torch.load(checkpoint, map_location="cpu", weights_only=False, mmap=True) + if (state["update"] != update or state["teacher_used"] + or not state["complete_backbone"] + or (update == 40000 and state["experiment"] != + "vitpose_l_mot_rgb_from_scratch_io_v4_rotationfix_grouped_20261007") + or (update != 40000 and + (state["variant"] != "mixed" or state["parent_checkpoint"] != str(PARENT) + or state["config"] != CONFIG))): + raise RuntimeError(f"checkpoint composition invalid: {checkpoint}") + model = build_model(torch.tensor(statistics["mean_local"], dtype=torch.float32)) + model.load_state_dict(state["model"], strict=True) + model.cuda().eval().requires_grad_(False) + del state + checkpoint_sha = sha(checkpoint) + for index, clip in enumerate(selection): + path = args.output / f"update_{update:07d}" / f"{clip['id']}.json" + if path.exists(): + row = json.loads(path.read_text()) + if row["checkpoint_sha256"] != checkpoint_sha: + raise RuntimeError(f"stale score: {path}") + continue + receipt, gt, _, common = inputs(clip) + prediction = infer(model, runner_class, config_class, receipt) + if (common & ~prediction["valid"]).any(): + raise RuntimeError(f"model has invalid geometry: {clip['id']}") + row = {"id": clip["id"], "checkpoint_sha256": checkpoint_sha, + "scores": score(metric_values, gt, prediction, clip, receipt, common)} + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(row) + "\n") + print(f"update {update}: {index + 1}/{len(selection)} {clip['partition']}", flush=True) + del model + torch.cuda.empty_cache() + aggregate(args.output, selection, args.updates) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/config.json new file mode 100644 index 0000000000000000000000000000000000000000..75ef61561093d7264a527688860b19f15fb85b34 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/config.json @@ -0,0 +1,17 @@ +{ + "experiment": "vitpose_mot_40k_grab_original_personal_rgb_pilot_20261011", + "parent_checkpoint": "/home/wuyifan/artifacts/vitpose_mot_g2_continuous_20261008/formal_run/update_0040000.pt", + "variants": { + "mixed": {"H2O": 20, "ARCTIC": 14, "HOT3D": 23, "GRAB": 3}, + "control": {"H2O": 21, "ARCTIC": 15, "HOT3D": 24} + }, + "global_batch": 60, + "frames": 8, + "optimizer": { + "name": "AdamW", "lr_peak": 0.00001, "weight_decay": 0.05, + "clip_grad_norm": 100, "warmup_updates": 100, + "minimum_lr_ratio": 0.1, "endpoint_updates": 2000 + }, + "evaluation_updates": [100, 500, 1000, 2000], + "io": {"prefetch_factor": 4, "group_max_clips": 10} +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/continue_from_20k.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/continue_from_20k.py new file mode 100644 index 0000000000000000000000000000000000000000..ffb8becc19e3f8095083d261dee03e59fb040b13 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/continue_from_20k.py @@ -0,0 +1,349 @@ +"""Continue the audited GRAB RGB pilot from 20K to 40K.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +import foundation_hand.geometry.rotations as rotations +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.fit_targets import mano_pkl_mean +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base, sha +from experiments.from_scratch_mean_pose.throughput_probe import ( + PROBE_FIELDS, collate_matching_resolutions, initialize_worker, select_clip, +) +from .data import MANIFEST, PilotCoverage, PilotDataset +from experiments.vitpose_mot_io_v4.model import MANO_ROOT, VISUAL_SHA256, VISUAL_WEIGHTS, build_model, verify_visual_weights + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +STATS = BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"] +INDEX = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite") +LABELS = Path("/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json") +PARENT = Path(CONFIG["parent_checkpoint"]) +BASE_STEP = 20000 +FINAL_STEP = 40000 +BASE_CHECKPOINT = Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_5k_to_20k/update_0020000.pt") + + +def code_hashes(): + files = [ROOT / "train.py", ROOT / "data.py", ROOT / "config.json", ROOT / "manifest.json", + ROOT.parent / "vitpose_mot_io_v4/train.py", ROOT.parent / "vitpose_mot_io_v4/model.py", + ROOT.parent / "vitpose_mot_io_v4/data.py", ROOT.parent / "vitpose_mot_io_v4/hot3d_hand_only.py", + BASE_ROOT / "config.json", BASE_ROOT / "loss.py", BASE_ROOT / "model.py", BASE_ROOT / "fit_targets.py", + BASE_ROOT / "throughput_probe.py", + BASE_ROOT / "statistics_mano_pkl_v2.json", + ROOT.parent / "dinov3_2d_pretrain/vitpose_probe.py", + ROOT.parent / "u0_depthsafe/model.py", + ROOT.parent / "u0_depthsafe/reprojection.py", + ROOT.parent / "u0_normalized6d/normalized_loss.py", + ROOT.parent / "a7_rotation_fix/filtered_dataset.py", + ROOT.parent.parent / "src/foundation_hand/models/bimanual.py", + ROOT.parent.parent / "src/foundation_hand/models/decoder.py", + ROOT.parent.parent / "src/foundation_hand/models/encoders.py", + ROOT.parent.parent / "src/foundation_hand/models/mano.py", + ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py", + ROOT.parent.parent / "src/foundation_hand/data/schema.py", + ROOT.parent.parent / "src/foundation_hand/data/h2o_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/arctic_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/hot3d_dataset.py"] + return {str(path.relative_to(ROOT.parent.parent)): sha(path) for path in files} + + +def verify_contract(fitted): + expected_rotations = ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py" + if Path(rotations.__file__).resolve() != expected_rotations.resolve(): + raise RuntimeError(f"wrong rotation implementation loaded: {rotations.__file__}") + verify_visual_weights() + if BASE_CONFIG["shared"]["teacher"] != { + "create_model": False, "forward": False, "distillation": False, "rgb_teacher_weight": 0.0, + }: + raise RuntimeError("teacher-free base loss contract changed") + if BASE_CONFIG["shared"]["loss"]["joint2d"] != 0 or BASE_CONFIG["shared"]["loss"]["reprojection"] != 1: + raise RuntimeError("2D supervision must be MANO reprojection only") + if fitted["training_index_sha256"] != sha(INDEX) or fitted["label_inventory_sha256"] != sha(LABELS): + raise RuntimeError("train-only fitted statistics do not match current data") + if fitted["source_quota"] != {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}: + raise RuntimeError("parent statistics source mixture differs") + if fitted["version"] != "b0_b1_mano_pkl_mean_delta_v2": + raise RuntimeError("expected official MANO-pkl mean and normalized delta statistics") + mean, hashes = mano_pkl_mean(Path(MANO_ROOT)) + if hashes != fitted["mano_pkl_sha256"] or not torch.allclose( + torch.as_tensor(mean, dtype=torch.float64), + torch.as_tensor(fitted["mean_local"], dtype=torch.float64), atol=1e-7, rtol=0, + ): + raise RuntimeError("official MANO mean/asset mismatch") + if sha(VISUAL_WEIGHTS) != VISUAL_SHA256: + raise RuntimeError("ViTPose visual asset changed") + if any(sum(quota.values()) != CONFIG["global_batch"] for quota in CONFIG["variants"].values()): + raise RuntimeError("source quotas do not fill global batch") + if MANIFEST["summary"]["clips"] != 153 or MANIFEST["summary"]["frames"] != 42508: + raise RuntimeError("audited GRAB pilot manifest changed") + return {"code_sha256": code_hashes(), "index_sha256": sha(INDEX), + "labels_sha256": sha(LABELS), "statistics_sha256": sha(STATS), + "visual_sha256": VISUAL_SHA256, "mano_pkl_sha256": hashes, + "parent_sha256": sha(PARENT), + "template_sha256": MANIFEST["template_sha256"]} + + +def rng_state(): + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state()} + + +def restore_rng(state): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"]) + torch.cuda.set_rng_state(state["cuda"]) + + +def single_training_sample(samples): + if len(samples) != 1: + raise RuntimeError("loader must return one clip at a time") + sample = samples[0] + missing = PROBE_FIELDS - sample.keys() + if missing: + raise RuntimeError(f"training clip is missing fields: {sorted(missing)}") + return {key: sample[key] for key in PROBE_FIELDS} + + +def schedule(update): + settings = CONFIG["optimizer"] + endpoint = settings["endpoint_updates"] + warmup = settings["warmup_updates"] + floor = settings["minimum_lr_ratio"] + fraction = min(1.0, max(0.0, (update - warmup) / (endpoint - warmup))) + factor = max(1 / warmup, (update + 1) / warmup) if update < warmup else ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * fraction))) + return settings["lr_peak"] * factor + + +def save_checkpoint(path, model, optimizer, update, provenance, rng_states, exposure, smoke, world, variant): + if path.exists(): + raise FileExistsError(path) + state = {"experiment": CONFIG["experiment"], "variant": variant, "model": model.state_dict(), + "optimizer": optimizer.state_dict(), "update": update, + "next_sample_position": update * CONFIG["global_batch"], + "world_size": world, "global_batch": CONFIG["global_batch"], + "source_exposure": dict(exposure), "rank_rng_states": rng_states, + "provenance": provenance, "config": CONFIG, "complete_backbone": True, + "teacher_used": False, "parent_checkpoint": str(PARENT), "smoke": smoke} + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + loaded = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("full checkpoint load-back failed") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, default=120000) + parser.add_argument("--resume", type=Path) + parser.add_argument("--variant", choices=tuple(CONFIG["variants"]), default="mixed") + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--log-every", type=int, default=25) + args = parser.parse_args() + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if (world != 4 or args.smoke or args.variant != "mixed" or args.updates != FINAL_STEP + or args.resume is None or args.resume.resolve() != BASE_CHECKPOINT.resolve()): + raise RuntimeError("continuation requires four GPUs and the audited mixed 20K checkpoint") + if args.output.resolve() == BASE_CHECKPOINT.parent.resolve(): + raise RuntimeError("continuation must write to a separate output directory") + if args.workers < 1 or args.log_every < 1: + raise ValueError("workers/log interval must be positive") + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError(f"rank {rank}: less than 18 GiB free") + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=20), device_id=device) + try: + if rank == 0: + args.output.parent.mkdir(parents=True, exist_ok=True) + dist.barrier(device_ids=[local]) + if shutil.disk_usage(args.output.parent).free < 100 * 1024**3: + raise RuntimeError("less than 100 GiB free for complete checkpoints") + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + quota = CONFIG["variants"][args.variant] + sources = tuple(quota) + seed = BASE_CONFIG["shared"]["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + state = None + start = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["variant"] != args.variant + or state["world_size"] != 4 + or state["global_batch"] != CONFIG["global_batch"] + or state["config"] != CONFIG or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] != str(PARENT) or state["smoke"] != args.smoke): + raise RuntimeError("resume checkpoint contract mismatch") + start = state["update"] + if (start != BASE_STEP or state["next_sample_position"] != start * CONFIG["global_batch"] + or start >= args.updates or len(state["rank_rng_states"]) != world + or state["source_exposure"] != { + source: count * start for source, count in quota.items() + }): + raise RuntimeError("resume cursor or endpoint mismatch") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if state is None: + parent = torch.load(PARENT, map_location="cpu", weights_only=False, mmap=True) + model.load_state_dict(parent["model"], strict=True) + del parent + model.to(device).train() + new = [p for name, p in model.named_parameters() + if not name.startswith("rgb_encoder.backbone.") and p.requires_grad] + if not new or any(p.requires_grad for p in model.rgb_encoder.backbone.parameters()): + raise RuntimeError("optimizer parameter partition invalid") + optimizer = torch.optim.AdamW([{"params": new, "name": "non_visual", "lr": schedule(start)}], + weight_decay=CONFIG["optimizer"]["weight_decay"]) + exposure = Counter() + if state: + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + exposure.update(state["source_exposure"]) + restore_rng(state["rank_rng_states"][rank]) + del state + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists(): + raise FileExistsError("continuation would append to existing metrics") + (args.output / "provenance.json").write_text(json.dumps({ + "experiment": CONFIG["experiment"], "contract": provenance, + "loss_coefficients": BASE_CONFIG["shared"]["loss"], + "optimizer": CONFIG["optimizer"], "io": CONFIG["io"], + "workers_per_rank": args.workers, + "resume": str(args.resume) if args.resume else None, "smoke": args.smoke, + "variant": args.variant, "source_quota": quota, "parent_checkpoint": str(PARENT), + "continuation_script_sha256": sha(Path(__file__)), + "continuation_learning_rate": "fixed 1e-6 from update 20001 through 40000", + "resume_world_size": 4, "continuation_world_size": world, + }, indent=2) + "\n") + dist.barrier(device_ids=[local]) + sampler = base.PositionSampler(PilotCoverage(args.variant == "mixed"), + start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(PilotDataset(args.variant == "mixed"), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=True, + collate_fn=single_training_sample, pin_memory=True, + prefetch_factor=CONFIG["io"]["prefetch_factor"], + worker_init_fn=partial(initialize_worker, opencv_threads=1), + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + clips_per_rank = CONFIG["global_batch"] // world + for update in range(start, args.updates): + lr_new = schedule(update) + optimizer.param_groups[0]["lr"] = lr_new + started = time.monotonic() + cpu_batches = collate_matching_resolutions( + [next(iterator) for _ in range(clips_per_rank)], CONFIG["io"]["group_max_clips"]) + data_ready = time.monotonic() + if sum(len(cpu["input_mode"]) for cpu in cpu_batches) != clips_per_rank: + raise RuntimeError("grouping changed the per-rank clip count") + counts = Counter(source for cpu in cpu_batches for source in cpu["sampling_source_id"]) + local_counts = torch.tensor([counts[source] for source in sources], device=device) + dist.all_reduce(local_counts) + if local_counts.tolist() != [quota[source] for source in sources]: + raise RuntimeError("source quota per update changed") + optimizer.zero_grad(set_to_none=True) + total_loss = 0.0 + term_totals = {key: 0.0 for key in TERMS} + nonpositive = 0 + valid_pose = 0 + for micro, cpu in enumerate(cpu_batches): + count = len(cpu["input_mode"]) + if cpu["input_mode"] != ["rgb"] * count or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("non-RGB input reached ViTPose-L") + batch = base.move_to_device(cpu, device) + if "GRAB" not in cpu["sampling_source_id"]: + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < len(cpu_batches) else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + results = [objective(select_clip(prediction, index, count), + select_clip(batch, index, count)) + for index in range(count)] + loss = torch.stack([result[0] for result in results]).sum() + if not bool(torch.isfinite(loss)) or any( + result[2]["gt_rotation_orthogonality_max"] > 1e-5 for result in results + ): + raise RuntimeError(f"nonfinite loss or invalid GT at update {update + 1}") + (loss / clips_per_rank).backward() + for clip_loss, terms, diagnostics in results: + total_loss += float(clip_loss.detach()) / clips_per_rank + for name, value in terms.items(): + term_totals[name] += float(value.detach()) / clips_per_rank + nonpositive += diagnostics["nonpositive_reprojection_joints"] + valid_pose += diagnostics["valid_local_frames"] + trainable = [p for p in model.parameters() if p.requires_grad] + norm = torch.nn.utils.clip_grad_norm_(trainable, CONFIG["optimizer"]["clip_grad_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"nonfinite gradient at update {update + 1}") + optimizer.step() + elapsed = time.monotonic() - started + for source, count in zip(sources, local_counts.tolist()): + exposure[source] += count + if rank == 0 and ((update + 1) % args.log_every == 0 or update < 10): + row = {"update": update + 1, "consumed_clips": (update + 1) * CONFIG["global_batch"], + "seconds": elapsed, "data_wait_seconds": data_ready - started, + "loss_rank0": total_loss, "terms_rank0": term_totals, + "preclip_grad_norm_rank0": float(norm), "nonpositive_rank0": nonpositive, + "valid_local_pose_frames_rank0": valid_pose, + "learning_rate_new": lr_new, "learning_rate_visual": 0.0, + "exposure": dict(exposure)} + log.write(json.dumps(row, allow_nan=False) + "\n") + print(json.dumps(row, allow_nan=False), flush=True) + if (update + 1) % 5000 == 0: + gathered = [None] * world + dist.all_gather_object(gathered, rng_state()) + if rank == 0: + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", model, + optimizer, update + 1, provenance, gathered, exposure, + args.smoke, world, args.variant) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/continue_from_5k.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/continue_from_5k.py new file mode 100644 index 0000000000000000000000000000000000000000..612f621d69c2a88e2736798c194a598288ff7a56 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/continue_from_5k.py @@ -0,0 +1,346 @@ +"""Continue the audited GRAB pilot from 5K with five-thousand-step saves.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +import foundation_hand.geometry.rotations as rotations +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.fit_targets import mano_pkl_mean +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base, sha +from experiments.from_scratch_mean_pose.throughput_probe import ( + PROBE_FIELDS, collate_matching_resolutions, initialize_worker, select_clip, +) +from .data import MANIFEST, PilotCoverage, PilotDataset +from experiments.vitpose_mot_io_v4.model import MANO_ROOT, VISUAL_SHA256, VISUAL_WEIGHTS, build_model, verify_visual_weights + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +STATS = BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"] +INDEX = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite") +LABELS = Path("/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json") +PARENT = Path(CONFIG["parent_checkpoint"]) +BASE_STEP = 5000 +FINAL_STEP = 20000 +BASE_CHECKPOINT = Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k_to_5k/update_0005000.pt") + + +def code_hashes(): + files = [ROOT / "train.py", ROOT / "data.py", ROOT / "config.json", ROOT / "manifest.json", + ROOT.parent / "vitpose_mot_io_v4/train.py", ROOT.parent / "vitpose_mot_io_v4/model.py", + ROOT.parent / "vitpose_mot_io_v4/data.py", ROOT.parent / "vitpose_mot_io_v4/hot3d_hand_only.py", + BASE_ROOT / "config.json", BASE_ROOT / "loss.py", BASE_ROOT / "model.py", BASE_ROOT / "fit_targets.py", + BASE_ROOT / "throughput_probe.py", + BASE_ROOT / "statistics_mano_pkl_v2.json", + ROOT.parent / "dinov3_2d_pretrain/vitpose_probe.py", + ROOT.parent / "u0_depthsafe/model.py", + ROOT.parent / "u0_depthsafe/reprojection.py", + ROOT.parent / "u0_normalized6d/normalized_loss.py", + ROOT.parent / "a7_rotation_fix/filtered_dataset.py", + ROOT.parent.parent / "src/foundation_hand/models/bimanual.py", + ROOT.parent.parent / "src/foundation_hand/models/decoder.py", + ROOT.parent.parent / "src/foundation_hand/models/encoders.py", + ROOT.parent.parent / "src/foundation_hand/models/mano.py", + ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py", + ROOT.parent.parent / "src/foundation_hand/data/schema.py", + ROOT.parent.parent / "src/foundation_hand/data/h2o_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/arctic_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/hot3d_dataset.py"] + return {str(path.relative_to(ROOT.parent.parent)): sha(path) for path in files} + + +def verify_contract(fitted): + expected_rotations = ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py" + if Path(rotations.__file__).resolve() != expected_rotations.resolve(): + raise RuntimeError(f"wrong rotation implementation loaded: {rotations.__file__}") + verify_visual_weights() + if BASE_CONFIG["shared"]["teacher"] != { + "create_model": False, "forward": False, "distillation": False, "rgb_teacher_weight": 0.0, + }: + raise RuntimeError("teacher-free base loss contract changed") + if BASE_CONFIG["shared"]["loss"]["joint2d"] != 0 or BASE_CONFIG["shared"]["loss"]["reprojection"] != 1: + raise RuntimeError("2D supervision must be MANO reprojection only") + if fitted["training_index_sha256"] != sha(INDEX) or fitted["label_inventory_sha256"] != sha(LABELS): + raise RuntimeError("train-only fitted statistics do not match current data") + if fitted["source_quota"] != {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}: + raise RuntimeError("parent statistics source mixture differs") + if fitted["version"] != "b0_b1_mano_pkl_mean_delta_v2": + raise RuntimeError("expected official MANO-pkl mean and normalized delta statistics") + mean, hashes = mano_pkl_mean(Path(MANO_ROOT)) + if hashes != fitted["mano_pkl_sha256"] or not torch.allclose( + torch.as_tensor(mean, dtype=torch.float64), + torch.as_tensor(fitted["mean_local"], dtype=torch.float64), atol=1e-7, rtol=0, + ): + raise RuntimeError("official MANO mean/asset mismatch") + if sha(VISUAL_WEIGHTS) != VISUAL_SHA256: + raise RuntimeError("ViTPose visual asset changed") + if any(sum(quota.values()) != CONFIG["global_batch"] for quota in CONFIG["variants"].values()): + raise RuntimeError("source quotas do not fill global batch") + if MANIFEST["summary"]["clips"] != 153 or MANIFEST["summary"]["frames"] != 42508: + raise RuntimeError("audited GRAB pilot manifest changed") + return {"code_sha256": code_hashes(), "index_sha256": sha(INDEX), + "labels_sha256": sha(LABELS), "statistics_sha256": sha(STATS), + "visual_sha256": VISUAL_SHA256, "mano_pkl_sha256": hashes, + "parent_sha256": sha(PARENT), + "template_sha256": MANIFEST["template_sha256"]} + + +def rng_state(): + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state()} + + +def restore_rng(state): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"]) + torch.cuda.set_rng_state(state["cuda"]) + + +def single_training_sample(samples): + if len(samples) != 1: + raise RuntimeError("loader must return one clip at a time") + sample = samples[0] + missing = PROBE_FIELDS - sample.keys() + if missing: + raise RuntimeError(f"training clip is missing fields: {sorted(missing)}") + return {key: sample[key] for key in PROBE_FIELDS} + + +def schedule(update): + settings = CONFIG["optimizer"] + endpoint = settings["endpoint_updates"] + warmup = settings["warmup_updates"] + floor = settings["minimum_lr_ratio"] + fraction = min(1.0, max(0.0, (update - warmup) / (endpoint - warmup))) + factor = max(1 / warmup, (update + 1) / warmup) if update < warmup else ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * fraction))) + return settings["lr_peak"] * factor + + +def save_checkpoint(path, model, optimizer, update, provenance, rng_states, exposure, smoke, world, variant): + if path.exists(): + raise FileExistsError(path) + state = {"experiment": CONFIG["experiment"], "variant": variant, "model": model.state_dict(), + "optimizer": optimizer.state_dict(), "update": update, + "next_sample_position": update * CONFIG["global_batch"], + "world_size": world, "global_batch": CONFIG["global_batch"], + "source_exposure": dict(exposure), "rank_rng_states": rng_states, + "provenance": provenance, "config": CONFIG, "complete_backbone": True, + "teacher_used": False, "parent_checkpoint": str(PARENT), "smoke": smoke} + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + loaded = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("full checkpoint load-back failed") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, default=120000) + parser.add_argument("--resume", type=Path) + parser.add_argument("--variant", choices=tuple(CONFIG["variants"]), default="mixed") + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--log-every", type=int, default=25) + args = parser.parse_args() + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if (world not in (3, 4, 5, 6) or args.smoke or args.variant != "mixed" or args.updates != FINAL_STEP + or args.resume is None or args.resume.resolve() != BASE_CHECKPOINT.resolve()): + raise RuntimeError("continuation requires three to six GPUs and the audited mixed 5K checkpoint") + if args.output.resolve() == BASE_CHECKPOINT.parent.resolve(): + raise RuntimeError("continuation must write to a separate output directory") + if args.workers < 1 or args.log_every < 1: + raise ValueError("workers/log interval must be positive") + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError(f"rank {rank}: less than 18 GiB free") + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=20), device_id=device) + try: + if rank == 0: + args.output.parent.mkdir(parents=True, exist_ok=True) + dist.barrier(device_ids=[local]) + if shutil.disk_usage(args.output.parent).free < 100 * 1024**3: + raise RuntimeError("less than 100 GiB free for complete checkpoints") + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + quota = CONFIG["variants"][args.variant] + sources = tuple(quota) + seed = BASE_CONFIG["shared"]["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + state = None + start = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["variant"] != args.variant + or state["world_size"] != 5 + or state["global_batch"] != CONFIG["global_batch"] + or state["config"] != CONFIG or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] != str(PARENT) or state["smoke"] != args.smoke): + raise RuntimeError("resume checkpoint contract mismatch") + start = state["update"] + if (start != BASE_STEP or state["next_sample_position"] != start * CONFIG["global_batch"] + or start >= args.updates): + raise RuntimeError("resume cursor or endpoint mismatch") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if state is None: + parent = torch.load(PARENT, map_location="cpu", weights_only=False, mmap=True) + model.load_state_dict(parent["model"], strict=True) + del parent + model.to(device).train() + new = [p for name, p in model.named_parameters() + if not name.startswith("rgb_encoder.backbone.") and p.requires_grad] + if not new or any(p.requires_grad for p in model.rgb_encoder.backbone.parameters()): + raise RuntimeError("optimizer parameter partition invalid") + optimizer = torch.optim.AdamW([{"params": new, "name": "non_visual", "lr": schedule(start)}], + weight_decay=CONFIG["optimizer"]["weight_decay"]) + exposure = Counter() + if state: + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + exposure.update(state["source_exposure"]) + restore_rng(state["rank_rng_states"][rank]) + del state + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh training would overwrite old metrics") + (args.output / "provenance.json").write_text(json.dumps({ + "experiment": CONFIG["experiment"], "contract": provenance, + "loss_coefficients": BASE_CONFIG["shared"]["loss"], + "optimizer": CONFIG["optimizer"], "io": CONFIG["io"], + "workers_per_rank": args.workers, + "resume": str(args.resume) if args.resume else None, "smoke": args.smoke, + "variant": args.variant, "source_quota": quota, "parent_checkpoint": str(PARENT), + "continuation_script_sha256": sha(Path(__file__)), + "continuation_learning_rate": "fixed 1e-6 from update 5001 through 20000", + "resume_world_size": 5, "continuation_world_size": world, + }, indent=2) + "\n") + dist.barrier(device_ids=[local]) + sampler = base.PositionSampler(PilotCoverage(args.variant == "mixed"), + start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(PilotDataset(args.variant == "mixed"), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=True, + collate_fn=single_training_sample, pin_memory=True, + prefetch_factor=CONFIG["io"]["prefetch_factor"], + worker_init_fn=partial(initialize_worker, opencv_threads=1), + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + clips_per_rank = CONFIG["global_batch"] // world + for update in range(start, args.updates): + lr_new = schedule(update) + optimizer.param_groups[0]["lr"] = lr_new + started = time.monotonic() + cpu_batches = collate_matching_resolutions( + [next(iterator) for _ in range(clips_per_rank)], CONFIG["io"]["group_max_clips"]) + data_ready = time.monotonic() + if sum(len(cpu["input_mode"]) for cpu in cpu_batches) != clips_per_rank: + raise RuntimeError("grouping changed the per-rank clip count") + counts = Counter(source for cpu in cpu_batches for source in cpu["sampling_source_id"]) + local_counts = torch.tensor([counts[source] for source in sources], device=device) + dist.all_reduce(local_counts) + if local_counts.tolist() != [quota[source] for source in sources]: + raise RuntimeError("source quota per update changed") + optimizer.zero_grad(set_to_none=True) + total_loss = 0.0 + term_totals = {key: 0.0 for key in TERMS} + nonpositive = 0 + valid_pose = 0 + for micro, cpu in enumerate(cpu_batches): + count = len(cpu["input_mode"]) + if cpu["input_mode"] != ["rgb"] * count or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("non-RGB input reached ViTPose-L") + batch = base.move_to_device(cpu, device) + if "GRAB" not in cpu["sampling_source_id"]: + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < len(cpu_batches) else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + results = [objective(select_clip(prediction, index, count), + select_clip(batch, index, count)) + for index in range(count)] + loss = torch.stack([result[0] for result in results]).sum() + if not bool(torch.isfinite(loss)) or any( + result[2]["gt_rotation_orthogonality_max"] > 1e-5 for result in results + ): + raise RuntimeError(f"nonfinite loss or invalid GT at update {update + 1}") + (loss / clips_per_rank).backward() + for clip_loss, terms, diagnostics in results: + total_loss += float(clip_loss.detach()) / clips_per_rank + for name, value in terms.items(): + term_totals[name] += float(value.detach()) / clips_per_rank + nonpositive += diagnostics["nonpositive_reprojection_joints"] + valid_pose += diagnostics["valid_local_frames"] + trainable = [p for p in model.parameters() if p.requires_grad] + norm = torch.nn.utils.clip_grad_norm_(trainable, CONFIG["optimizer"]["clip_grad_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"nonfinite gradient at update {update + 1}") + optimizer.step() + elapsed = time.monotonic() - started + for source, count in zip(sources, local_counts.tolist()): + exposure[source] += count + if rank == 0 and ((update + 1) % args.log_every == 0 or update < 10): + row = {"update": update + 1, "consumed_clips": (update + 1) * CONFIG["global_batch"], + "seconds": elapsed, "data_wait_seconds": data_ready - started, + "loss_rank0": total_loss, "terms_rank0": term_totals, + "preclip_grad_norm_rank0": float(norm), "nonpositive_rank0": nonpositive, + "valid_local_pose_frames_rank0": valid_pose, + "learning_rate_new": lr_new, "learning_rate_visual": 0.0, + "exposure": dict(exposure)} + log.write(json.dumps(row, allow_nan=False) + "\n") + print(json.dumps(row, allow_nan=False), flush=True) + if update + 1 in (10000, 15000, FINAL_STEP): + gathered = [None] * world + dist.all_gather_object(gathered, rng_state()) + if rank == 0: + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", model, + optimizer, update + 1, provenance, gathered, exposure, + args.smoke, world, args.variant) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/continue_to_5k.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/continue_to_5k.py new file mode 100644 index 0000000000000000000000000000000000000000..3a8fa8a83a0522269d2fdf690fc7339de175fccc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/continue_to_5k.py @@ -0,0 +1,346 @@ +"""Continue the audited 2K GRAB pilot to 5K without an LR discontinuity.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +import foundation_hand.geometry.rotations as rotations +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.fit_targets import mano_pkl_mean +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base, sha +from experiments.from_scratch_mean_pose.throughput_probe import ( + PROBE_FIELDS, collate_matching_resolutions, initialize_worker, select_clip, +) +from .data import MANIFEST, PilotCoverage, PilotDataset +from experiments.vitpose_mot_io_v4.model import MANO_ROOT, VISUAL_SHA256, VISUAL_WEIGHTS, build_model, verify_visual_weights + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +STATS = BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"] +INDEX = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite") +LABELS = Path("/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json") +PARENT = Path(CONFIG["parent_checkpoint"]) +BASE_STEP = 2000 +FINAL_STEP = 5000 +BASE_CHECKPOINT = Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k/update_0002000.pt") + + +def code_hashes(): + files = [ROOT / "train.py", ROOT / "data.py", ROOT / "config.json", ROOT / "manifest.json", + ROOT.parent / "vitpose_mot_io_v4/train.py", ROOT.parent / "vitpose_mot_io_v4/model.py", + ROOT.parent / "vitpose_mot_io_v4/data.py", ROOT.parent / "vitpose_mot_io_v4/hot3d_hand_only.py", + BASE_ROOT / "config.json", BASE_ROOT / "loss.py", BASE_ROOT / "model.py", BASE_ROOT / "fit_targets.py", + BASE_ROOT / "throughput_probe.py", + BASE_ROOT / "statistics_mano_pkl_v2.json", + ROOT.parent / "dinov3_2d_pretrain/vitpose_probe.py", + ROOT.parent / "u0_depthsafe/model.py", + ROOT.parent / "u0_depthsafe/reprojection.py", + ROOT.parent / "u0_normalized6d/normalized_loss.py", + ROOT.parent / "a7_rotation_fix/filtered_dataset.py", + ROOT.parent.parent / "src/foundation_hand/models/bimanual.py", + ROOT.parent.parent / "src/foundation_hand/models/decoder.py", + ROOT.parent.parent / "src/foundation_hand/models/encoders.py", + ROOT.parent.parent / "src/foundation_hand/models/mano.py", + ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py", + ROOT.parent.parent / "src/foundation_hand/data/schema.py", + ROOT.parent.parent / "src/foundation_hand/data/h2o_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/arctic_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/hot3d_dataset.py"] + return {str(path.relative_to(ROOT.parent.parent)): sha(path) for path in files} + + +def verify_contract(fitted): + expected_rotations = ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py" + if Path(rotations.__file__).resolve() != expected_rotations.resolve(): + raise RuntimeError(f"wrong rotation implementation loaded: {rotations.__file__}") + verify_visual_weights() + if BASE_CONFIG["shared"]["teacher"] != { + "create_model": False, "forward": False, "distillation": False, "rgb_teacher_weight": 0.0, + }: + raise RuntimeError("teacher-free base loss contract changed") + if BASE_CONFIG["shared"]["loss"]["joint2d"] != 0 or BASE_CONFIG["shared"]["loss"]["reprojection"] != 1: + raise RuntimeError("2D supervision must be MANO reprojection only") + if fitted["training_index_sha256"] != sha(INDEX) or fitted["label_inventory_sha256"] != sha(LABELS): + raise RuntimeError("train-only fitted statistics do not match current data") + if fitted["source_quota"] != {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}: + raise RuntimeError("parent statistics source mixture differs") + if fitted["version"] != "b0_b1_mano_pkl_mean_delta_v2": + raise RuntimeError("expected official MANO-pkl mean and normalized delta statistics") + mean, hashes = mano_pkl_mean(Path(MANO_ROOT)) + if hashes != fitted["mano_pkl_sha256"] or not torch.allclose( + torch.as_tensor(mean, dtype=torch.float64), + torch.as_tensor(fitted["mean_local"], dtype=torch.float64), atol=1e-7, rtol=0, + ): + raise RuntimeError("official MANO mean/asset mismatch") + if sha(VISUAL_WEIGHTS) != VISUAL_SHA256: + raise RuntimeError("ViTPose visual asset changed") + if any(sum(quota.values()) != CONFIG["global_batch"] for quota in CONFIG["variants"].values()): + raise RuntimeError("source quotas do not fill global batch") + if MANIFEST["summary"]["clips"] != 153 or MANIFEST["summary"]["frames"] != 42508: + raise RuntimeError("audited GRAB pilot manifest changed") + return {"code_sha256": code_hashes(), "index_sha256": sha(INDEX), + "labels_sha256": sha(LABELS), "statistics_sha256": sha(STATS), + "visual_sha256": VISUAL_SHA256, "mano_pkl_sha256": hashes, + "parent_sha256": sha(PARENT), + "template_sha256": MANIFEST["template_sha256"]} + + +def rng_state(): + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state()} + + +def restore_rng(state): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"]) + torch.cuda.set_rng_state(state["cuda"]) + + +def single_training_sample(samples): + if len(samples) != 1: + raise RuntimeError("loader must return one clip at a time") + sample = samples[0] + missing = PROBE_FIELDS - sample.keys() + if missing: + raise RuntimeError(f"training clip is missing fields: {sorted(missing)}") + return {key: sample[key] for key in PROBE_FIELDS} + + +def schedule(update): + settings = CONFIG["optimizer"] + endpoint = settings["endpoint_updates"] + warmup = settings["warmup_updates"] + floor = settings["minimum_lr_ratio"] + fraction = min(1.0, max(0.0, (update - warmup) / (endpoint - warmup))) + factor = max(1 / warmup, (update + 1) / warmup) if update < warmup else ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * fraction))) + return settings["lr_peak"] * factor + + +def save_checkpoint(path, model, optimizer, update, provenance, rng_states, exposure, smoke, world, variant): + if path.exists(): + raise FileExistsError(path) + state = {"experiment": CONFIG["experiment"], "variant": variant, "model": model.state_dict(), + "optimizer": optimizer.state_dict(), "update": update, + "next_sample_position": update * CONFIG["global_batch"], + "world_size": world, "global_batch": CONFIG["global_batch"], + "source_exposure": dict(exposure), "rank_rng_states": rng_states, + "provenance": provenance, "config": CONFIG, "complete_backbone": True, + "teacher_used": False, "parent_checkpoint": str(PARENT), "smoke": smoke} + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + loaded = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("full checkpoint load-back failed") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, default=120000) + parser.add_argument("--resume", type=Path) + parser.add_argument("--variant", choices=tuple(CONFIG["variants"]), default="mixed") + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--log-every", type=int, default=25) + args = parser.parse_args() + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if (world not in (5, 6) or args.smoke or args.variant != "mixed" or args.updates != FINAL_STEP + or args.resume is None or args.resume.resolve() != BASE_CHECKPOINT.resolve()): + raise RuntimeError("5K continuation requires five/six GPUs and the audited mixed 2K checkpoint") + if args.output.resolve() == BASE_CHECKPOINT.parent.resolve(): + raise RuntimeError("continuation must write to a separate output directory") + if args.workers < 1 or args.log_every < 1: + raise ValueError("workers/log interval must be positive") + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError(f"rank {rank}: less than 18 GiB free") + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=20), device_id=device) + try: + if rank == 0: + args.output.parent.mkdir(parents=True, exist_ok=True) + dist.barrier(device_ids=[local]) + if shutil.disk_usage(args.output.parent).free < 100 * 1024**3: + raise RuntimeError("less than 100 GiB free for complete checkpoints") + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + quota = CONFIG["variants"][args.variant] + sources = tuple(quota) + seed = BASE_CONFIG["shared"]["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + state = None + start = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["variant"] != args.variant + or state["world_size"] != 6 + or state["global_batch"] != CONFIG["global_batch"] + or state["config"] != CONFIG or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] != str(PARENT) or state["smoke"] != args.smoke): + raise RuntimeError("resume checkpoint contract mismatch") + start = state["update"] + if (start != BASE_STEP or state["next_sample_position"] != start * CONFIG["global_batch"] + or start >= args.updates): + raise RuntimeError("resume cursor or endpoint mismatch") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if state is None: + parent = torch.load(PARENT, map_location="cpu", weights_only=False, mmap=True) + model.load_state_dict(parent["model"], strict=True) + del parent + model.to(device).train() + new = [p for name, p in model.named_parameters() + if not name.startswith("rgb_encoder.backbone.") and p.requires_grad] + if not new or any(p.requires_grad for p in model.rgb_encoder.backbone.parameters()): + raise RuntimeError("optimizer parameter partition invalid") + optimizer = torch.optim.AdamW([{"params": new, "name": "non_visual", "lr": schedule(start)}], + weight_decay=CONFIG["optimizer"]["weight_decay"]) + exposure = Counter() + if state: + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + exposure.update(state["source_exposure"]) + restore_rng(state["rank_rng_states"][rank]) + del state + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh training would overwrite old metrics") + (args.output / "provenance.json").write_text(json.dumps({ + "experiment": CONFIG["experiment"], "contract": provenance, + "loss_coefficients": BASE_CONFIG["shared"]["loss"], + "optimizer": CONFIG["optimizer"], "io": CONFIG["io"], + "workers_per_rank": args.workers, + "resume": str(args.resume) if args.resume else None, "smoke": args.smoke, + "variant": args.variant, "source_quota": quota, "parent_checkpoint": str(PARENT), + "continuation_script_sha256": sha(Path(__file__)), + "continuation_learning_rate": "fixed 1e-6 from update 2001 through 5000", + "resume_world_size": 6, "continuation_world_size": world, + }, indent=2) + "\n") + dist.barrier(device_ids=[local]) + sampler = base.PositionSampler(PilotCoverage(args.variant == "mixed"), + start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(PilotDataset(args.variant == "mixed"), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=True, + collate_fn=single_training_sample, pin_memory=True, + prefetch_factor=CONFIG["io"]["prefetch_factor"], + worker_init_fn=partial(initialize_worker, opencv_threads=1), + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + clips_per_rank = CONFIG["global_batch"] // world + for update in range(start, args.updates): + lr_new = schedule(update) + optimizer.param_groups[0]["lr"] = lr_new + started = time.monotonic() + cpu_batches = collate_matching_resolutions( + [next(iterator) for _ in range(clips_per_rank)], CONFIG["io"]["group_max_clips"]) + data_ready = time.monotonic() + if sum(len(cpu["input_mode"]) for cpu in cpu_batches) != clips_per_rank: + raise RuntimeError("grouping changed the per-rank clip count") + counts = Counter(source for cpu in cpu_batches for source in cpu["sampling_source_id"]) + local_counts = torch.tensor([counts[source] for source in sources], device=device) + dist.all_reduce(local_counts) + if local_counts.tolist() != [quota[source] for source in sources]: + raise RuntimeError("source quota per update changed") + optimizer.zero_grad(set_to_none=True) + total_loss = 0.0 + term_totals = {key: 0.0 for key in TERMS} + nonpositive = 0 + valid_pose = 0 + for micro, cpu in enumerate(cpu_batches): + count = len(cpu["input_mode"]) + if cpu["input_mode"] != ["rgb"] * count or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("non-RGB input reached ViTPose-L") + batch = base.move_to_device(cpu, device) + if "GRAB" not in cpu["sampling_source_id"]: + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < len(cpu_batches) else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + results = [objective(select_clip(prediction, index, count), + select_clip(batch, index, count)) + for index in range(count)] + loss = torch.stack([result[0] for result in results]).sum() + if not bool(torch.isfinite(loss)) or any( + result[2]["gt_rotation_orthogonality_max"] > 1e-5 for result in results + ): + raise RuntimeError(f"nonfinite loss or invalid GT at update {update + 1}") + (loss / clips_per_rank).backward() + for clip_loss, terms, diagnostics in results: + total_loss += float(clip_loss.detach()) / clips_per_rank + for name, value in terms.items(): + term_totals[name] += float(value.detach()) / clips_per_rank + nonpositive += diagnostics["nonpositive_reprojection_joints"] + valid_pose += diagnostics["valid_local_frames"] + trainable = [p for p in model.parameters() if p.requires_grad] + norm = torch.nn.utils.clip_grad_norm_(trainable, CONFIG["optimizer"]["clip_grad_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"nonfinite gradient at update {update + 1}") + optimizer.step() + elapsed = time.monotonic() - started + for source, count in zip(sources, local_counts.tolist()): + exposure[source] += count + if rank == 0 and ((update + 1) % args.log_every == 0 or update < 10): + row = {"update": update + 1, "consumed_clips": (update + 1) * CONFIG["global_batch"], + "seconds": elapsed, "data_wait_seconds": data_ready - started, + "loss_rank0": total_loss, "terms_rank0": term_totals, + "preclip_grad_norm_rank0": float(norm), "nonpositive_rank0": nonpositive, + "valid_local_pose_frames_rank0": valid_pose, + "learning_rate_new": lr_new, "learning_rate_visual": 0.0, + "exposure": dict(exposure)} + log.write(json.dumps(row, allow_nan=False) + "\n") + print(json.dumps(row, allow_nan=False), flush=True) + if update + 1 in (3500, FINAL_STEP): + gathered = [None] * world + dist.all_gather_object(gathered, rng_state()) + if rank == 0: + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", model, + optimizer, update + 1, provenance, gathered, exposure, + args.smoke, world, args.variant) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/data.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/data.py new file mode 100644 index 0000000000000000000000000000000000000000..b644c8f43a27e01988b88f2dda36f7b0c93b7650 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/data.py @@ -0,0 +1,197 @@ +"""Original-personalized GRAB targets for the RGB-only MoT pilot.""" + +from __future__ import annotations + +from functools import lru_cache +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from experiments.vitpose_mot_io_v4.data import MixedResolutionCoverage, MixedResolutionDataset +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +ROOT = Path(__file__).resolve().parent +MANIFEST = json.loads((ROOT / "manifest.json").read_text()) +HW = (512, 896) +MEAN = np.asarray([0.485, 0.456, 0.406], dtype=np.float32)[:, None, None] +STD = np.asarray([0.229, 0.224, 0.225], dtype=np.float32)[:, None, None] +MANO_ROOT = "/SSD3/jiasen/foundation_hand/pretrained/mano" + + +def draw(key: str, modulus: int) -> int: + return int.from_bytes(hashlib.blake2b(key.encode(), digest_size=8).digest(), "big") % modulus + + +class PilotCoverage: + def __init__(self, include_grab: bool): + self.base = MixedResolutionCoverage() + self.include_grab = include_grab + + @lru_cache(maxsize=16) + def replaced_positions(self, update: int) -> frozenset[int]: + first = {} + for position in range(update * 60, (update + 1) * 60): + source = self.base.sample(position)["source"] + first.setdefault(source, position) + if set(first) != {"H2O", "ARCTIC", "HOT3D"}: + raise RuntimeError(f"base coverage changed at update {update}: {first}") + return frozenset(first.values()) + + def sample(self, position: int) -> dict: + spec = self.base.sample(position) + if not self.include_grab or position not in self.replaced_positions(position // 60): + return spec + index = draw(f"grab-clip:{position}", len(MANIFEST["clips"])) + frames = MANIFEST["clips"][index]["frames"] + start = draw(f"grab-start:{position}", frames - 7) + return {"source": "GRAB", "position": position, "clip_index": index, "start": start} + + def shard(self, first: int, last: int, rank: int, world: int): + for position in range(first + rank, last, world): + yield self.sample(position) + + +class PersonalGrabDataset(Dataset): + def __init__(self): + self._layers = None + self._templates = None + + def __len__(self): + return len(MANIFEST["clips"]) + + def _load_mano(self) -> None: + if self._layers is not None: + return + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + self._layers = {side: ManoLayer(mano_root=MANO_ROOT, side=side, + use_pca=False, ncomps=45, flat_hand_mean=True) + for side in ("left", "right")} + self._templates = { + subject: np.load(path)["mano_personalized_v_template"].copy() + for subject, path in MANIFEST["template_sources"].items() + } + + @staticmethod + def video_frames(path: Path, start: int) -> torch.Tensor: + video = cv2.VideoCapture(str(path)) + if not video.isOpened() or not video.set(cv2.CAP_PROP_POS_FRAMES, start): + raise RuntimeError(f"cannot seek RGB video {path} at {start}") + frames = [] + for _ in range(8): + ok, bgr = video.read() + if not ok: + raise RuntimeError(f"cannot decode 8 frames from {path} at {start}") + rgb = cv2.cvtColor(cv2.resize(bgr, HW[::-1], interpolation=cv2.INTER_AREA), + cv2.COLOR_BGR2RGB).astype(np.float32) / 255 + frames.append(torch.from_numpy(((rgb.transpose(2, 0, 1) - MEAN) / STD).copy())) + video.release() + return torch.stack(frames) + + def __getitem__(self, spec: dict) -> dict: + self._load_mano() + row = MANIFEST["clips"][spec["clip_index"]] + path = Path(row["clip"]) + indices = np.arange(spec["start"], spec["start"] + 8) + rgb = self.video_frames(path / "rgb.mp4", spec["start"]) + with np.load(path / "mano_parameters.npz") as mano, np.load(path / "camera_parameters.npz") as camera: + width, height = map(int, camera["image_size"]) + scale = np.asarray([HW[1] / width, HW[0] / height], dtype=np.float32) + K = camera["K"][indices].copy() + K[:, 0, :] *= scale[0] + K[:, 1, :] *= scale[1] + world_to_camera = camera["world_to_camera"][indices] + source_to_world = mano["source_to_world_rotation"] + offset = mano["source_to_world_translation"] + mano["floor_contact_common_translation_blender"] + vertices, joints, poses, hand_valid, joint2d_valid = [], [], [], [], [] + for side_index, side in enumerate(("left", "right")): + layer = self._layers[side] + with torch.no_grad(): + layer.th_v_template[0].copy_(torch.from_numpy( + self._templates[row["subject"]][side_index])) + source_pose = np.concatenate((mano[f"{side}_global_orient_source"][indices], + mano[f"{side}_fullpose_source"][indices]), axis=-1) + v, j = layer(torch.from_numpy(source_pose.copy()), torch.zeros(8, 10)) + translation = mano[f"{side}_transl_source"][indices] + source_v = v.numpy() / 1000 + translation[:, None] + source_j = j.numpy() / 1000 + translation[:, None] + world_v = source_v @ source_to_world.T + offset + world_j = source_j @ source_to_world.T + offset + R, t = world_to_camera[:, :3, :3], world_to_camera[:, :3, 3] + camera_v = np.einsum("fij,fvj->fvi", R, world_v) + t[:, None] + camera_j = np.einsum("fij,fvj->fvi", R, world_j) + t[:, None] + camera_pose = source_pose.copy() + for frame in range(8): + root_rotation = cv2.Rodrigues(source_pose[frame, :3])[0] + camera_root = R[frame] @ source_to_world @ root_rotation + camera_pose[frame, :3] = cv2.Rodrigues(camera_root)[0][:, 0] + mesh_z = camera_v[..., 2] + mesh_uv = camera_v[..., :2] / np.maximum(mesh_z[..., None], 1e-6) + mesh_uv = np.einsum("fij,fvj->fvi", K[:, :2, :2], mesh_uv) + K[:, None, :2, 2] + in_view = (mesh_z > .05) & (mesh_uv[..., 0] >= 0) & (mesh_uv[..., 0] < HW[1]) & ( + mesh_uv[..., 1] >= 0) & (mesh_uv[..., 1] < HW[0]) + valid = in_view.any(axis=1) & np.isfinite(camera_v).all(axis=(1, 2)) & ( + mesh_z.min(axis=1) > .05) + z = camera_j[..., 2] + uv = camera_j[..., :2] / np.maximum(z[..., None], 1e-6) + uv = np.einsum("fij,fvj->fvi", K[:, :2, :2], uv) + K[:, None, :2, 2] + valid2d = valid[:, None] & (z > .05) & (uv[..., 0] >= 0) & (uv[..., 0] < HW[1]) & ( + uv[..., 1] >= 0) & (uv[..., 1] < HW[0]) & np.isfinite(uv).all(axis=-1) + vertices.append(camera_v.astype(np.float32)) + joints.append(camera_j.astype(np.float32)) + poses.append(camera_pose.astype(np.float32)) + hand_valid.append(valid) + joint2d_valid.append(valid2d) + vertices = np.stack(vertices, axis=1) + joints = np.stack(joints, axis=1) + poses = np.stack(poses, axis=1) + hand_valid = np.stack(hand_valid, axis=1) + joint2d_valid = np.stack(joint2d_valid, axis=1) + z = joints[..., 2] + uv = joints[..., :2] / np.maximum(z[..., None], 1e-6) + uv = np.einsum("fij,fhvj->fhvi", K[:, :2, :2], uv) + K[:, None, None, :2, 2] + hand = torch.from_numpy(hand_valid) + element = hand[..., None].expand(-1, -1, 21).clone() + projected = torch.from_numpy(joint2d_valid) + joint3d = torch.from_numpy(joints) + return { + "rgb": rgb, "K": torch.from_numpy(K.copy()), "image_hw": torch.tensor(HW), + "frame_valid": torch.ones(8, dtype=torch.bool), + "K_input_available": torch.zeros(8, dtype=torch.bool), + "depth_input_available": torch.zeros(8, dtype=torch.bool), + "joint_annotation_valid": hand.clone(), "mano_annotation_valid": hand.clone(), + "joint_element_valid": element, "joint2d_valid": projected, + "joint3d_valid": element.clone(), "joint3d_root_relative_valid": element.clone(), + "translation_valid": hand.clone(), "global_orientation_valid": hand.clone(), + "local_pose_valid": hand.clone(), "shape_valid": torch.zeros_like(hand), + "vertices_valid": hand.clone(), "reprojection_valid": projected.clone(), + "K_supervision_valid": torch.ones(8, dtype=torch.bool), + "joint2d": torch.from_numpy(uv.astype(np.float32)), + "joint3d_camera": joint3d, + "joint3d_root_relative": joint3d - joint3d[..., :1, :], + "mano_pose": torch.from_numpy(poses), + "mano_pose_valid": hand.clone(), + "mano_shape": torch.zeros((8, 2, 10), dtype=torch.float32), + "wrist_root_translation": joint3d[..., 0, :].clone(), + "vertices_camera": torch.from_numpy(vertices), + "mano_target_contract_version": torch.full((8,), 3, dtype=torch.int64), + "sampling_source_id": "GRAB", "input_mode": "rgb", + } + + +class PilotDataset(Dataset): + def __init__(self, include_grab: bool): + self.base = MixedResolutionDataset() + self.grab = PersonalGrabDataset() if include_grab else None + + def __getitem__(self, spec: dict) -> dict: + return self.grab[spec] if spec["source"] == "GRAB" else self.base[spec] + + def __len__(self) -> int: + return len(self.base) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/evaluate.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..a848e7e2861578d04a495a0e00eb16106206d5df --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/evaluate.py @@ -0,0 +1,181 @@ +"""Frozen source-native development benchmark and hard-pose diagnostics.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + +import numpy as np +import torch + +from experiments.vitpose_mot_io_v4.model import build_model +from experiments.from_scratch_mean_pose.smoke import a7, base, sha + +from clean_eval import apply_mode, dataset_for +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from scripts.evaluate_phase7_external import make_row +from targets import NativePanel + +from .train import CONFIG, PARENT, STATS, verify_contract + + +FOUR = ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px") + + +def finite(value): + if isinstance(value, dict): + return {key: finite(item) for key, item in value.items()} + if isinstance(value, list): + return [finite(item) for item in value] + return None if isinstance(value, float) and not math.isfinite(value) else value + + +def finger_angles(joints): + fingers = joints[..., 1:, :].reshape(*joints.shape[:-2], 5, 4, 3) + bones = fingers[..., 1:, :] - fingers[..., :-1, :] + lengths = torch.linalg.vector_norm(bones, dim=-1) + unit = bones / lengths.clamp_min(1e-8)[..., None] + angles = torch.rad2deg(torch.acos((unit[..., :-1, :] * unit[..., 1:, :]).sum(-1).clamp(-1, 1))) + complete = (lengths > 1e-6).all(dim=(-1, -2)) & torch.isfinite(angles).all(dim=(-1, -2)) + return angles, complete + + +def summarize(rows): + result = {} + for key in (*FOUR, "local_pose_angle_deg", "fingertip_root_relative_mm", + "bend_bias_deg", "gt60_bend_bias_deg"): + values = [row[key] for row in rows if row.get(key) is not None and math.isfinite(row[key])] + result[key] = {"mean": float(np.mean(values)) if values else None, "count": len(values)} + complete = [row for row in rows if "gt_local_6d" in row] + if len(complete) > 1: + gt = np.asarray([row["gt_local_6d"] for row in complete], dtype=np.float64) + pred = np.asarray([row["pred_local_6d"] for row in complete], dtype=np.float64) + gt_variance = gt.var(axis=0) + pred_variance = pred.var(axis=0) + eligible = gt_variance > 1e-8 + ratio = pred_variance[eligible] / gt_variance[eligible] + variance_ratio = float(ratio.mean()) if ratio.size else None + per_joint = np.asarray([row["local_pose_per_joint_deg"] for row in complete], dtype=np.float64).mean(axis=0).tolist() + else: + variance_ratio, per_joint = None, None + return {"hands": len(rows), "metrics": result, + "pred_gt_local_6d_variance_ratio_macro": variance_ratio, + "local_pose_per_joint_mean_deg": per_joint} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--expected-update", type=int, default=5000) + parser.add_argument("--limit", type=int) + parser.add_argument("--smoke", action="store_true") + args = parser.parse_args() + if args.output.exists() or args.output.with_suffix(".rows.json").exists(): + raise FileExistsError(args.output) + if args.limit is not None and args.limit < 1: + raise ValueError("positive limit required") + if (args.limit is not None or "smoke" in str(args.checkpoint)) and not args.smoke: + raise RuntimeError("subset or smoke checkpoint requires explicit --smoke") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["provenance"] != provenance + or state["config"] != CONFIG or state["variant"] != "mixed" + or state["update"] != args.expected_update or not state["complete_backbone"] + or state["teacher_used"] or state["parent_checkpoint"] != str(PARENT) + or state["smoke"] != args.smoke): + raise RuntimeError("evaluation checkpoint composition invalid") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + model.load_state_dict(state["model"], strict=True) + model.to("cuda").eval() + panel_root = a7.BASE_ROOT / "eval/frozen_panels_sync_v2" + registry = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_development_t8.jsonl" + registered = registry["sources"][args.source]["development"] + if sha(manifest) != registered["manifest_sha256"] or registry["sources"][args.source]["train_overlap"]: + raise RuntimeError("development panel overlaps training or hash changed") + manifest_rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), + hand_valid_policy="visible_mesh") if args.source == "ARCTIC" + else dataset_for(args.source, manifest)) + dataset = NativePanel(args.source, native, manifest_rows) + limit = min(args.limit, len(dataset)) if args.limit else len(dataset) + rows = [] + with torch.inference_mode(): + for index in range(limit): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, "rgb") + batch = base.move_to_device(batch, torch.device("cuda")) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + if not bool(torch.isfinite(prediction["joints_camera"]).all()): + raise RuntimeError(f"nonfinite development prediction at clip {index}") + pose_valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + joint_valid = batch["joint3d_root_relative_valid"].bool().all(dim=-1) + gt_angles, complete_geometry = finger_angles(batch["joint3d_camera"].float()) + pred_angles, _ = finger_angles(prediction["joints_camera"].float()) + complete = pose_valid & joint_valid & complete_geometry + gt_hard = ((gt_angles >= 45).sum(dim=(-1, -2)) >= 2) | (gt_angles >= 60).any(dim=(-1, -2)) + target_rotation = axis_angle_to_matrix(torch.nan_to_num(batch["mano_pose"].float()).reshape( + *pose_valid.shape, 16, 3)) + relative = prediction["mano_rotation_matrices"].float() @ target_rotation.transpose(-1, -2) + trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1) + angle_error = torch.rad2deg(torch.acos(((trace - 1) / 2).clamp(-1, 1))) + predicted_rel = prediction["joints_camera"].float() - prediction["joints_camera"].float()[..., :1, :] + target_rel = batch["joint3d_camera"].float() - batch["joint3d_camera"].float()[..., :1, :] + tip_error = torch.linalg.vector_norm(predicted_rel[..., [4, 8, 12, 16, 20], :] + - target_rel[..., [4, 8, 12, 16, 20], :], dim=-1).mean(-1) * 1000 + for frame in range(batch["frame_valid"].shape[1]): + if not bool(batch["frame_valid"][0, frame]): + continue + for side in range(2): + row = make_row(prediction, batch, 0, frame, side) + if bool(complete[0, frame, side]): + gt = gt_angles[0, frame, side] + difference = pred_angles[0, frame, side] - gt + high = gt >= 60 + row.update({ + "gt_hard": bool(gt_hard[0, frame, side]), + "local_pose_angle_deg": float(angle_error[0, frame, side, 1:].mean()), + "fingertip_root_relative_mm": float(tip_error[0, frame, side]), + "bend_bias_deg": float(difference.mean()), + "gt60_bend_bias_deg": float(difference[high].mean()) if bool(high.any()) else None, + "local_pose_per_joint_deg": angle_error[0, frame, side, 1:].tolist(), + "gt_local_6d": target_rotation[0, frame, side, 1:, :2, :].reshape(15, 6).tolist(), + "pred_local_6d": prediction["mano_rotation_matrices"][0, frame, side, 1:, :2, :].float().reshape(15, 6).tolist(), + }) + else: + row.update({"gt_hard": None, "local_pose_angle_deg": None, + "fingertip_root_relative_mm": None, + "bend_bias_deg": None, "gt60_bend_bias_deg": None}) + rows.append(row) + if (index + 1) % 32 == 0: + print(json.dumps({"source": args.source, "done": index + 1, "total": limit}), flush=True) + complete_rows = [row for row in rows if row["gt_hard"] is not None] + report = {"experiment": CONFIG["experiment"], "source": args.source, + "role": "development_subset_smoke" if args.limit else "development_full", + "input_mode": "rgb", "frames": 8, "source_native_gt": True, + "training_update": state["update"], "checkpoint_sha256": sha(args.checkpoint), + "panel_sha256": sha(manifest), "clips": limit, + "hard_definition": "GT >=2 distal angles >=45deg or >=1 >=60deg, complete joints and MANO pose", + "all": summarize(rows), "pose_complete": summarize(complete_rows), + "normal_pose": summarize([row for row in complete_rows if not row["gt_hard"]]), + "hard_pose": summarize([row for row in complete_rows if row["gt_hard"]])} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + args.output.with_suffix(".rows.json").write_text(json.dumps(finite(rows), allow_nan=False) + "\n") + print(json.dumps({"source": args.source, "update": state["update"], + "all": report["all"], "hard_pose": report["hard_pose"]}, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/evaluate_grab_v6.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/evaluate_grab_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..357354f5d8314ec258819cbd5892663faee19103 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/evaluate_grab_v6.py @@ -0,0 +1,201 @@ +"""Paired RGB evaluation on sequence-disjoint GRAB v6 render clips.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np +import torch + +from experiments.vitpose_mot_io_v4.model import build_model +from experiments.from_scratch_mean_pose.smoke import base +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from foundation_hand.geometry.camera import project_points + +from . import data +from .train import PARENT, STATS + + +V6 = Path("/SSD3/wbr/bedlam2_remote_render/production/grab_training_minimal_v1/channels_v2/grab_seeded_remaining_production_v6") +RUN = Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/evaluations_5k/grab_v6") +MIXED = Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k_to_5k/update_0005000.pt") +METRICS = ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", "pa_mpjpe_mm") + + +def freeze_panel(selection: str) -> list[dict]: + manifest = RUN / "panel.json" + if manifest.exists(): + panel = json.loads(manifest.read_text()) + if (not panel or (selection == "pilot64" and len(panel) != 64) + or any(not Path(row["clip"]).is_dir() for row in panel)): + raise RuntimeError("frozen GRAB panel is incomplete") + return panel + train_sequences = {row["sequence_index"] for row in data.MANIFEST["clips"]} + eligible = set(data.MANIFEST["template_sources"]) + candidates: dict[str, list[Path]] = {subject: [] for subject in eligible} + inventory = {"params": 0, "unsupported_subject": 0, "training_sequence": 0, + "missing_inputs": 0, "short_clip": 0} + for params in sorted(V6.rglob("mano_params_30fps.npz")): + inventory["params"] += 1 + clip = params.parent + relative = clip.relative_to(V6).parts + if len(relative) != 3: + continue + subject, sequence, _ = relative + if subject not in eligible: + inventory["unsupported_subject"] += 1 + continue + if f"{subject}/{sequence}" in train_sequences: + inventory["training_sequence"] += 1 + continue + if not (clip / "rgb.mp4").is_file() or not (clip / "camera/camera_parameters.npz").is_file(): + inventory["missing_inputs"] += 1 + continue + candidates[subject].append(clip) + + panel = [] + for subject in sorted(eligible): + if selection == "pilot64": + first_by_sequence = {} + for clip in candidates[subject]: + first_by_sequence.setdefault(clip.parent.name, clip) + sequences = sorted(first_by_sequence, key=lambda seq: hashlib.sha256( + f"grab-v6-panel:{subject}/{seq}".encode()).hexdigest()) + if len(sequences) < 8: + raise RuntimeError(f"only {len(sequences)} held-out sequences for {subject}") + selected = [first_by_sequence[sequence] for sequence in sequences[:8]] + else: + selected = candidates[subject] + for original in selected: + sequence = original.parent.name + with np.load(original / "mano_params_30fps.npz") as mano: + frames = len(mano["source_frame_indices"]) + if frames < 8: + inventory["short_clip"] += 1 + if selection == "pilot64": + raise RuntimeError(f"short clip: {original}") + continue + staged = RUN / "staging" / subject / sequence + if selection == "all_disjoint": + staged = staged / original.name + staged.mkdir(parents=True, exist_ok=True) + for name, target in (("rgb.mp4", original / "rgb.mp4"), + ("mano_parameters.npz", original / "mano_params_30fps.npz"), + ("camera_parameters.npz", original / "camera/camera_parameters.npz")): + link = staged / name + if link.is_symlink(): + if link.resolve() != target.resolve(): + raise RuntimeError(f"staging path changed: {link}") + elif link.exists(): + raise RuntimeError(f"staging path occupied: {link}") + else: + link.symlink_to(target) + panel.append({"clip": str(staged), "original_clip": str(original), + "subject": subject, "sequence_index": f"{subject}/{sequence}", + "frames": frames, "start": (frames - 8) // 2}) + if selection == "pilot64" and len(panel) != 64: + raise RuntimeError(f"expected 64 clips, got {len(panel)}") + payload = json.dumps(panel, indent=2) + "\n" + manifest.write_text(payload) + print(json.dumps({"selection": selection, "clips": len(panel), "inventory": inventory}), flush=True) + return panel + + +def evaluate(checkpoint: Path, name: str, panel: list[dict], selection: str) -> None: + output = RUN / f"{name}.json" + if output.exists(): + raise FileExistsError(output) + state = torch.load(checkpoint, map_location="cpu", mmap=True, weights_only=False) + if name == "mixed_5k" and (state["update"] != 5000 or state["teacher_used"]): + raise RuntimeError("unexpected mixed checkpoint") + fitted = json.loads(STATS.read_text()) + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + model.load_state_dict(state["model"], strict=True) + model.cuda().eval() + rows = [] + dataset = data.PersonalGrabDataset() + with torch.inference_mode(): + for index, item in enumerate(panel): + sample = dataset[{"clip_index": index, "start": item["start"]}] + batch = base.collate_h2o_clips([sample]) + batch = base.move_to_device(batch, torch.device("cuda")) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + if not bool(torch.isfinite(prediction["joints_camera"]).all()): + raise RuntimeError(f"nonfinite prediction at {item['original_clip']}") + for frame in range(8): + for side in range(2): + joint_mask = batch["joint3d_valid"][0, frame, side].bool() + valid_2d = batch["joint2d_valid"][0, frame, side].bool() + row = {"subject": item["subject"], "sequence_index": item["sequence_index"], + "frame": item["start"] + frame, "side": ("left", "right")[side]} + pred_j = prediction["joints_camera"][0, frame, side].float() + gt_j = batch["joint3d_camera"][0, frame, side].float() + if joint_mask.any(): + row["absolute_mpjpe_mm"] = float(torch.linalg.vector_norm( + pred_j - gt_j, dim=-1)[joint_mask].mean() * 1000) + row["root_relative_mpjpe_mm"] = float(torch.linalg.vector_norm( + (pred_j - pred_j[:1]) - (gt_j - gt_j[:1]), dim=-1)[joint_mask].mean() * 1000) + if bool(joint_mask.all()): + row["pa_mpjpe_mm"] = float(aligned_mpjpe_mm( + pred_j.cpu().numpy()[None], gt_j.cpu().numpy()[None], + estimate_scale=True)[0]) + if bool(batch["vertices_valid"][0, frame, side]): + row["mpvpe_mm"] = float(torch.linalg.vector_norm( + prediction["vertices_camera"][0, frame, side].float() + - batch["vertices_camera"][0, frame, side].float(), dim=-1).mean() * 1000) + projected, positive = project_points(pred_j, batch["K"][0, frame].float()) + valid_2d &= positive + if valid_2d.any(): + row["projected_mano_2d_error_px"] = float(torch.linalg.vector_norm( + projected - batch["joint2d"][0, frame, side].float(), dim=-1)[valid_2d].mean()) + rows.append(row) + if (index + 1) % 8 == 0: + print(json.dumps({"checkpoint": name, "done": index + 1, "clips": len(panel)}), flush=True) + summary = {key: {"mean": float(np.mean(values)), "hands": len(values)} for key in METRICS + if (values := [row[key] for row in rows if key in row and math.isfinite(row[key])])} + report = {"role": f"GRAB v6 {selection} sequence-disjoint development evaluation", + "input_mode": "rgb", "frames_per_clip": 8, + "checkpoint": str(checkpoint), "clips": len(panel), + "panel_sha256": hashlib.sha256((RUN / "panel.json").read_bytes()).hexdigest(), + "subject_shape_independent": False, "metrics": summary} + output.write_text(json.dumps(report, indent=2) + "\n") + (RUN / f"{name}.rows.json").write_text(json.dumps(rows) + "\n") + print(json.dumps(report), flush=True) + del model + torch.cuda.empty_cache() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path) + parser.add_argument("--name") + parser.add_argument("--run-dir", type=Path) + parser.add_argument("--selection", choices=("pilot64", "all_disjoint"), default="pilot64") + parser.add_argument("--prepare-only", action="store_true") + args = parser.parse_args() + if (args.checkpoint is None) != (args.name is None): + parser.error("--checkpoint and --name must be provided together") + global RUN + if args.run_dir is not None: + RUN = args.run_dir + torch.set_num_threads(2) + RUN.mkdir(parents=True, exist_ok=True) + panel = freeze_panel(args.selection) + if args.prepare_only: + return + data.MANIFEST = {"clips": panel, "template_sources": data.MANIFEST["template_sources"]} + if args.checkpoint is not None: + evaluate(args.checkpoint, args.name, panel, args.selection) + else: + evaluate(PARENT, "parent_40k_pa", panel, args.selection) + evaluate(MIXED, "mixed_5k_pa", panel, args.selection) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/evaluate_mirohand_multisource.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/evaluate_mirohand_multisource.py new file mode 100644 index 0000000000000000000000000000000000000000..3cede5e51205987fe888aa8300c6d7f8fb22cd27 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/evaluate_mirohand_multisource.py @@ -0,0 +1,217 @@ +"""Score GRAB-RGB checkpoints on the frozen MiroHand three-source benchmark.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import importlib.util +import json +import sys +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from experiments.vitpose_mot_io_v4.model import build_model +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD, _resize_pad + +from .train import CONFIG, PARENT, STATS + + +TOP = Path("/SSD3/yangzijing/MiroHand_multisource_benchmark_20260928") +BENCH = TOP / "rgb" +RELEASE_SEQUENCE = Path( + "/SSD2/jiasen/foundation_hand/releases/FoundationHand_A6_20260924/inference/sequence.py" +) +METRICS = ("abs_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", "epe_px", "pa_mpjpe_mm") + + +def sha(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_benchmark_code(): + sys.path.insert(0, str(TOP / "code")) + from metrics import metric_values + + spec = importlib.util.spec_from_file_location("mirohand_a6_sequence", RELEASE_SEQUENCE) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return metric_values, module.LengthGeneralizedInference, module.SequenceInferenceConfig + + +def canonical(array: dict[str, np.ndarray], source: str) -> dict[str, np.ndarray]: + output = dict(array) + joints = array["joints_camera_m"].copy() + for side in range(2): + tips = ([745, 317, 445 if side == 0 else 444, 556, 673] + if source == "H2O" else [744, 320, 443, 554, 671]) + joints[:, side, [4, 8, 12, 16, 20]] = array["vertices_camera_m"][:, side, tips] + output["joints_camera_m"] = joints + return output + + +def model_frames(receipt: dict): + identity = torch.eye(3, dtype=torch.float32)[None, None] + for frame in range(receipt["frames"]): + image = cv2.imread(str(Path(receipt["rgb_dir"]) / f"{frame:06d}.png"), cv2.IMREAD_COLOR) + if image is None: + raise FileNotFoundError(f"RGB frame {frame} missing from {receipt['rgb_dir']}") + image, _, _ = _resize_pad(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), + (512, 896), interpolation=cv2.INTER_AREA, fill=0) + rgb = ((image.astype(np.float32) / 255.0 - RGB_MEAN) / RGB_STD).transpose(2, 0, 1) + yield { + "rgb": torch.from_numpy(np.ascontiguousarray(rgb))[None, None], + "frame_valid": torch.ones((1, 1), dtype=torch.bool), + "K": identity, + "K_input_available": torch.zeros((1, 1), dtype=torch.bool), + "depth_input_available": torch.zeros((1, 1), dtype=torch.bool), + } + + +def infer(model, runner_class, config_class, receipt: dict) -> dict[str, np.ndarray]: + runner = runner_class( + model, config_class(mode="offline", window_size=8, offline_stride=6, + stitching="linear_mano"), + device="cuda:0", autocast_dtype=torch.bfloat16, + ) + output = runner.infer(model_frames(receipt)) + joints = output["joints_camera"][0].float().numpy() + vertices = output["vertices_camera"][0].float().numpy() + valid = np.isfinite(joints).all(axis=(2, 3)) & np.isfinite(vertices).all(axis=(2, 3)) + if joints.shape != (receipt["frames"], 2, 21, 3) or not valid.all(): + raise RuntimeError(f"invalid inference output for {receipt['id']}") + return {"joints_camera_m": joints, "vertices_camera_m": vertices, "valid": valid} + + +def existing_common_valid(clip: dict, gt: dict) -> np.ndarray: + common = gt["valid"] & np.isfinite(gt["joints_camera_m"]).all(axis=(2, 3)) + for method in json.loads((TOP / "audit/protocol.json").read_text())["models"]["rgb"]: + prediction = BENCH / "predictions" / method / clip["id"] / "prediction.npz" + with np.load(prediction) as array: + common &= array["valid"] & np.isfinite(array["joints_camera_m"]).all(axis=(2, 3)) + return common + + +def aggregate(rows: list[dict], output: Path) -> None: + with (BENCH / "metrics/summary.csv").open(newline="") as stream: + baseline = list(csv.DictReader(stream)) + report = [] + for update in sorted({row["update"] for row in rows}): + for partition in sorted({row["partition"] for row in rows}): + subset = [row for row in rows if row["update"] == update and row["partition"] == partition] + if not subset: + continue + reference = [row for row in baseline if row["partition"] == partition + and row["scope"] == "common_within_modality"] + if not reference: + raise RuntimeError(f"benchmark summary missing {partition}") + own = {key: sum(row["metrics"][key]["sum"] for row in subset) / + sum(row["metrics"][key]["n"] for row in subset) + if sum(row["metrics"][key]["n"] for row in subset) else None + for key in METRICS} + common_count = sum(row["common_hand_frames"] for row in subset) + expected = int(next(row["common_hand_frames"] for row in reference)) + if len(subset) == int(reference[0]["recordings"]) and common_count != expected: + raise RuntimeError(f"common mask changed for {partition}: {common_count} != {expected}") + report.append({"update": update, "dataset": subset[0]["dataset"], + "partition": partition, "recordings": len(subset), + "common_hand_frames": common_count, "metrics": own, + "published": [{"method": row["method"], + "metrics": {key: float(row[key]) if row[key] else None + for key in METRICS}} + for row in reference]}) + output.write_text(json.dumps({"benchmark": str(TOP), "input_mode": "rgb", + "sequence_policy": "T8 stride6 linear_mano", + "scope": "common_within_modality", + "selection_sha256": sha(BENCH / "selection.json"), + "metric_code_sha256": sha(TOP / "code/metrics.py"), + "groups": report}, indent=2) + "\n") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--updates", nargs="+", type=int, default=[10000, 15000]) + parser.add_argument("--limit", type=int) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + torch.set_num_threads(2) + cv2.setNumThreads(0) + args.output.mkdir(parents=True, exist_ok=True) + metric_values, runner_class, config_class = load_benchmark_code() + selection = json.loads((BENCH / "selection.json").read_text()) + if args.limit is not None: + selection = selection[:args.limit] + statistics = json.loads(STATS.read_text()) + rows = [] + for update in args.updates: + checkpoint = (PARENT if update == 40000 else + Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/") + / "pilot_mixed_5k_to_20k" / f"update_{update:07d}.pt") + state = torch.load(checkpoint, map_location="cpu", weights_only=False, mmap=True) + is_parent = update == 40000 + if (state["update"] != update or state["teacher_used"] + or not state["complete_backbone"] + or (is_parent and state["experiment"] != + "vitpose_l_mot_rgb_from_scratch_io_v4_rotationfix_grouped_20261007") + or (not is_parent and + (state["variant"] != "mixed" or state["parent_checkpoint"] != str(PARENT) + or state["config"] != CONFIG))): + raise RuntimeError(f"checkpoint composition invalid: {checkpoint}") + model = build_model(torch.tensor(statistics["mean_local"], dtype=torch.float32)) + model.load_state_dict(state["model"], strict=True) + model.cuda().eval().requires_grad_(False) + del state + checkpoint_sha = sha(checkpoint) + for index, clip in enumerate(selection): + path = args.output / f"update_{update:07d}" / f"{clip['id']}.json" + if path.exists(): + row = json.loads(path.read_text()) + if row["checkpoint_sha256"] != checkpoint_sha: + raise RuntimeError(f"stale result: {path}") + rows.append(row) + continue + receipt = json.loads((BENCH / "inputs" / clip["id"] / "complete.json").read_text()) + with np.load(receipt["reference"]) as array: + gt = {key: array[key] for key in array.files} + if len(gt["joints_camera_m"]) != receipt["frames"]: + raise RuntimeError(f"reference length differs: {clip['id']}") + prediction = infer(model, runner_class, config_class, receipt) + common = existing_common_valid(clip, gt) & prediction["valid"] + values, _ = metric_values(canonical(gt, clip["dataset"]), + canonical(prediction, clip["dataset"]), + gt["K"], receipt["image_size_hw"], + gt["timestamps_s"], common) + row = {"update": update, "checkpoint_sha256": checkpoint_sha, + "id": clip["id"], "dataset": clip["dataset"], + "partition": clip["partition"], "recording_id": clip["recording_id"], + "reference_sha256": receipt["reference_sha256"], + "input_manifest_sha256": sha(BENCH / "inputs" / clip["id"] / "complete.json"), + "common_hand_frames": int(common.sum()), + "metrics": {key: {"sum": float(np.nansum(values[key])), + "n": int(np.isfinite(values[key]).sum())} + for key in METRICS}} + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(row) + "\n") + rows.append(row) + print(json.dumps({"update": update, "done": index + 1, "total": len(selection), + "dataset": clip["dataset"], "recording_id": clip["recording_id"], + "metrics": {key: row["metrics"][key]["sum"] / + row["metrics"][key]["n"] + if row["metrics"][key]["n"] else None for key in METRICS}}), + flush=True) + del model + torch.cuda.empty_cache() + all_rows = [json.loads(path.read_text()) for path in sorted(args.output.glob("update_*/*.json"))] + aggregate(all_rows, args.output / "summary.json") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/gradient_probe_5k.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/gradient_probe_5k.py new file mode 100644 index 0000000000000000000000000000000000000000..1090edb53d56dc6a62d8edd14b2c58cff7bcd9d3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/gradient_probe_5k.py @@ -0,0 +1,146 @@ +"""Read-only per-loss gradient probe for the saved GRAB-mixed 5K checkpoint.""" + +from __future__ import annotations + +import json +import math +from pathlib import Path + +import torch + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.throughput_probe import collate_matching_resolutions +from experiments.vitpose_mot_io_v4.model import build_model + +from .data import PilotCoverage, PilotDataset +from .train import BASE_CONFIG, CONFIG, STATS, base + + +CHECKPOINT = Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k_to_5k/update_0005000.pt") +OUTPUT = Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/gradient_probe_5k_split.json") +SOURCES = ("H2O", "ARCTIC", "HOT3D", "GRAB") + + +def squared_norm(grads): + return sum(float(torch.sum(grad.detach().float().square())) + for grad in grads if grad is not None) + + +def dot_product(a, b): + return sum(float(torch.sum(left.detach().float() * right.detach().float())) + for left, right in zip(a, b) if left is not None and right is not None) + + +def parameter_group(name): + return "rgb_projection" if name.startswith("rgb_encoder.projection.") else name.split(".")[0] + + +def group_statistics(grads, total_grads, names): + squares, dots = {}, {} + + def add(group, gradient, total): + squares[group] = squares.get(group, 0.0) + float(torch.sum(gradient.detach().float().square())) + if total is not None: + dots[group] = dots.get(group, 0.0) + float(torch.sum( + gradient.detach().float() * total.detach().float())) + + for name, grad, total in zip(names, grads, total_grads): + if grad is None: + continue + add(parameter_group(name), grad, total) + if name in ("rotation_head.linear.weight", "rotation_head.linear.bias"): + add("rotation_head_root", grad[:6], total[:6] if total is not None else None) + add("rotation_head_local", grad[6:], total[6:] if total is not None else None) + return squares, dots + + +def main() -> None: + if OUTPUT.exists(): + raise FileExistsError(OUTPUT) + torch.set_num_threads(2) + torch.manual_seed(5012) + fitted = json.loads(STATS.read_text()) + state = torch.load(CHECKPOINT, map_location="cpu", mmap=True, weights_only=False) + if state["update"] != 5000 or state["variant"] != "mixed" or state["teacher_used"]: + raise RuntimeError("unexpected gradient-probe checkpoint") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + model.load_state_dict(state["model"], strict=True) + model.cuda().train() + named = [(name, param) for name, param in model.named_parameters() if param.requires_grad] + names = [name for name, _ in named] + params = [param for _, param in named] + criterion = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] + for name in TERMS}, BASE_CONFIG["shared"]["smoke"]).cuda() + coverage = PilotCoverage(True) + dataset = PilotDataset(True) + specs = {source: [] for source in SOURCES} + for position in range(5000 * CONFIG["global_batch"], 5002 * CONFIG["global_batch"]): + spec = coverage.sample(position) + specs[spec["source"]].append(spec) + if any(not candidates for candidates in specs.values()): + raise RuntimeError("missing probe source") + + records = [] + for source in SOURCES: + for spec in specs[source]: + sample = dataset[spec] + batch = collate_matching_resolutions([sample], CONFIG["io"]["group_max_clips"])[0] + batch = base.move_to_device(batch, torch.device("cuda")) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + total, terms, diagnostics = criterion(prediction, batch) + if not bool(torch.isfinite(total)): + raise RuntimeError(f"nonfinite probe loss for {source}") + total_grads = torch.autograd.grad(total, params, retain_graph=True, allow_unused=True) + total_sq = squared_norm(total_grads) + if not math.isfinite(total_sq): + raise RuntimeError(f"nonfinite probe gradient for {source}") + if total_sq > 0: + break + del total_grads, total, terms, prediction, batch, sample + else: + raise RuntimeError(f"no supervised probe clip for {source}") + entries = {} + total_group_sq, _ = group_statistics(total_grads, total_grads, names) + for term in TERMS: + value = terms[term] + if not value.requires_grad: + norm_sq, projection = 0.0, 0.0 + term_group_sq, term_group_dot = {}, {} + else: + grads = torch.autograd.grad(value, params, retain_graph=True, allow_unused=True) + norm_sq = squared_norm(grads) + projection = dot_product(grads, total_grads) / total_sq + term_group_sq, term_group_dot = group_statistics(grads, total_grads, names) + del grads + entries[term] = {"weighted_loss": float(value.detach()), + "grad_norm": math.sqrt(norm_sq), + "signed_total_gradient_projection": projection, + "groups": {group: {"grad_norm": math.sqrt(term_group_sq.get(group, 0.0)), + "signed_group_projection": term_group_dot.get(group, 0.0) / square} + for group, square in total_group_sq.items() if square > 0}} + record = {"source": source, "sample_position": spec["position"], + "total_weighted_loss": float(total.detach()), + "total_grad_norm": math.sqrt(total_sq), + "total_group_grad_norms": {group: math.sqrt(square) + for group, square in total_group_sq.items()}, + "projection_sum": sum(item["signed_total_gradient_projection"] + for item in entries.values()), + "nonpositive_reprojection_joints": diagnostics["nonpositive_reprojection_joints"], + "terms": entries} + records.append(record) + print(json.dumps({"source": source, "total_grad_norm": record["total_grad_norm"], + "projection_sum": record["projection_sum"]}), flush=True) + del total_grads, total, terms, prediction, batch, sample + torch.cuda.empty_cache() + + report = {"checkpoint": str(CHECKPOINT), "update": 5000, "input_mode": "rgb", + "split": "train", "optimizer_steps": 0, "source_clips": 1, + "gradient_scope": "all trainable model parameters, ViTPose-L backbone frozen", + "precision": "BF16 forward, FP32 loss", "records": records, + "note": "One clip per source is a diagnostic, not a training-run gradient average."} + OUTPUT.write_text(json.dumps(report, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_continuation_3gpu.sh b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_continuation_3gpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..93d711b72bd2b1ebd1c79d2bac6676e1665b64b1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_continuation_3gpu.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/wuyifan/EgoNet_train_20261008 +export CUDA_VISIBLE_DEVICES=1,2,3 +export PYTHONPATH=src:. +exec /SSD2/jiasen/envs/foundation_hand/bin/torchrun --standalone --nproc_per_node=3 \ + -m experiments.grab_personal_rgb_pilot.continue_from_5k \ + --output /home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_5k_to_20k \ + --updates 20000 --variant mixed \ + --resume /home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k_to_5k/update_0005000.pt \ + --workers 4 --log-every 25 diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_continuation_4gpu.sh b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_continuation_4gpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..118cb05e7d96719147d298e3375f913c55c622b9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_continuation_4gpu.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/wuyifan/EgoNet_train_20261008 +export CUDA_VISIBLE_DEVICES=1,2,3,4 +export PYTHONPATH=src:. +exec /SSD2/jiasen/envs/foundation_hand/bin/torchrun --standalone --nproc_per_node=4 \ + -m experiments.grab_personal_rgb_pilot.continue_from_5k \ + --output /home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_5k_to_20k \ + --updates 20000 --variant mixed \ + --resume /home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k_to_5k/update_0005000.pt \ + --workers 4 --log-every 25 diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_continuation_5gpu.sh b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_continuation_5gpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..1530294c5fb70240fa5f977de42e427e9b2b599b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_continuation_5gpu.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/wuyifan/EgoNet_train_20261008 +export CUDA_VISIBLE_DEVICES=0,1,2,3,4 +export PYTHONPATH=src:. +exec /SSD2/jiasen/envs/foundation_hand/bin/torchrun --standalone --nproc_per_node=5 \ + -m experiments.grab_personal_rgb_pilot.continue_to_5k \ + --output /home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k_to_5k \ + --updates 5000 --variant mixed \ + --resume /home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k/update_0002000.pt \ + --workers 4 --log-every 25 diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_eval_5k.sh b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_eval_5k.sh new file mode 100644 index 0000000000000000000000000000000000000000..af2962f95a062405e196fbdef783262754f88676 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_eval_5k.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/wuyifan/EgoNet_train_20261008 +export CUDA_VISIBLE_DEVICES=0 +export PYTHONPATH=src:. +checkpoint=/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k_to_5k/update_0005000.pt +output=/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/evaluations_5k +mkdir -p "$output" +for source in ARCTIC H2O HOT3D; do + /SSD2/jiasen/envs/foundation_hand/bin/python -m experiments.grab_personal_rgb_pilot.evaluate \ + --checkpoint "$checkpoint" --source "$source" \ + --output "$output/${source,,}.json" +done diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_pilot.sh b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_pilot.sh new file mode 100644 index 0000000000000000000000000000000000000000..a0f1fd1a6e07ff146876d27986366d4aaf6e7a93 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_pilot.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/wuyifan/EgoNet_train_20261008 +export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5 +export PYTHONPATH=src:. +exec /SSD2/jiasen/envs/foundation_hand/bin/torchrun --standalone --nproc_per_node=6 \ + -m experiments.grab_personal_rgb_pilot.train \ + --output /home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/pilot_mixed_2k \ + --updates 2000 --variant mixed --workers 4 --log-every 25 diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_smoke.sh b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_smoke.sh new file mode 100644 index 0000000000000000000000000000000000000000..55d16f783a60ac63baf8c72415a9682fe43b3eae --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/launch_smoke.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /home/wuyifan/EgoNet_train_20261008 +export CUDA_VISIBLE_DEVICES=0 +export PYTHONPATH=src:. +exec /SSD2/jiasen/envs/foundation_hand/bin/torchrun --standalone --nproc_per_node=1 \ + -m experiments.grab_personal_rgb_pilot.train \ + --output /home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011/smoke_mixed \ + --updates 1 --variant mixed --smoke --workers 2 --log-every 1 diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/manifest.json b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..ed72cf1f9e1b101a377f4f549a4bb040dc4d263f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/manifest.json @@ -0,0 +1,1979 @@ +{ + "schema": "foundation_hand.grab_personal_rgb_pilot_manifest.v1", + "input": "RGB only; original personalized MANO; no fitted beta label", + "template_sources": { + "s1": "/SSD3/wbr/bedlam2_remote_render/production/grab_training_minimal_v1/grab_seeded_remaining_production_v6/s1/apple_offhand_1/shared/original_personalized_mano.npz", + "s10": "/SSD3/wbr/bedlam2_remote_render/production/grab_training_minimal_v1/grab_seeded_remaining_production_v6/s10/airplane_fly_1/shared/original_personalized_mano.npz", + "s2": "/SSD3/wbr/bedlam2_remote_render/production/grab_training_minimal_v1/grab_seeded_remaining_production_v6/s2/airplane_fly_1/shared/original_personalized_mano.npz", + "s4": "/SSD3/wbr/bedlam2_remote_render/production/grab_training_minimal_v1/grab_seeded_remaining_production_v6/s4/airplane_fly_1/shared/original_personalized_mano.npz", + "s5": "/SSD3/wbr/bedlam2_remote_render/production/grab_training_minimal_v1/grab_seeded_remaining_production_v6/s5/airplane_lift/shared/original_personalized_mano.npz", + "s7": "/SSD3/wbr/bedlam2_remote_render/production/grab_training_minimal_v1/grab_seeded_remaining_production_v6/s7/airplane_lift_Retake/shared/original_personalized_mano.npz", + "s8": "/SSD3/wbr/bedlam2_remote_render/production/grab_training_minimal_v1/grab_seeded_remaining_production_v6/s8/airplane_fly_1/shared/original_personalized_mano.npz", + "s9": "/SSD3/wbr/bedlam2_remote_render/production/grab_training_minimal_v1/grab_seeded_remaining_production_v6/s9/airplane_fly_1/shared/original_personalized_mano.npz" + }, + "template_sha256": { + "s1": "8ea54a2592738adc71e206c945090a6679412475927c35c1c8d16f7c29873720", + "s10": "42d1d2e664df531d15515a0fea2e16bc2d913c3288c41a88b1b32f7db51ec3f9", + "s2": "463fd43af8d0f13724ebd7c1ba84e600ba9d355568dac82b73965f35592c6cf6", + "s4": "a4f8176248aaa77b6b7259b5d37ea0511acdba8f28582c2bd9549542b19ce84d", + "s5": "955abcef11f2b4cf7cec5bb240de177f4e2b22de22000ab4665e67b11c217349", + "s7": "89cc7f04087ca95211cc67bb9d89b34d1bb41adc9b4ba721077123d9db2f1392", + "s8": "451e0bb9d30122dc67b61bfd1b29ed6ff278fabc0391a638bf0cbac6ee4b8a13", + "s9": "58e141b67e39c32064edf76f4590d748dfaf19934641e3e714394bf6d3c602ac" + }, + "clips": [ + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v2/GRAB/93e4ef6ba1e58c7ee3a82ead8164e9ea581742c0896a6c102f813231e235d2e6/s1/airplane_fly_1/i03_warm_evening", + "campaign": "grab_oakink_latest_production_v2", + "sequence_index": "s1/airplane_fly_1", + "subject": "s1", + "frames": 279, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v2/GRAB/93e4ef6ba1e58c7ee3a82ead8164e9ea581742c0896a6c102f813231e235d2e6/s1/airplane_lift/o02_cool_patio", + "campaign": "grab_oakink_latest_production_v2", + "sequence_index": "s1/airplane_lift", + "subject": "s1", + "frames": 432, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v2/GRAB/93e4ef6ba1e58c7ee3a82ead8164e9ea581742c0896a6c102f813231e235d2e6/s1/airplane_offhand_1/o01_bright_patio", + "campaign": "grab_oakink_latest_production_v2", + "sequence_index": "s1/airplane_offhand_1", + "subject": "s1", + "frames": 294, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v2/GRAB/93e4ef6ba1e58c7ee3a82ead8164e9ea581742c0896a6c102f813231e235d2e6/s1/airplane_pass_1/i01_sage_morning", + "campaign": "grab_oakink_latest_production_v2", + "sequence_index": "s1/airplane_pass_1", + "subject": "s1", + "frames": 219, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v2/GRAB/93e4ef6ba1e58c7ee3a82ead8164e9ea581742c0896a6c102f813231e235d2e6/s1/alarmclock_offhand_1/o01_bright_patio", + "campaign": "grab_oakink_latest_production_v2", + "sequence_index": "s1/alarmclock_offhand_1", + "subject": "s1", + "frames": 271, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v2/GRAB/93e4ef6ba1e58c7ee3a82ead8164e9ea581742c0896a6c102f813231e235d2e6/s1/alarmclock_pass_1/i03_warm_evening", + "campaign": "grab_oakink_latest_production_v2", + "sequence_index": "s1/alarmclock_pass_1", + "subject": "s1", + "frames": 226, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v2/GRAB/93e4ef6ba1e58c7ee3a82ead8164e9ea581742c0896a6c102f813231e235d2e6/s1/alarmclock_see_1/i03_warm_evening", + "campaign": "grab_oakink_latest_production_v2", + "sequence_index": "s1/alarmclock_see_1", + "subject": "s1", + "frames": 254, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s1/apple_lift/i02_cool_overcast", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s1/apple_lift", + "subject": "s1", + "frames": 651, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s1/camera_browse_1/o00_patio_anchor", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s1/camera_browse_1", + "subject": "s1", + "frames": 323, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s10/banana_pass_1/i01_sage_morning", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s10/banana_pass_1", + "subject": "s10", + "frames": 167, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s2/cup_pass_1/o04_soft_patio", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s2/cup_pass_1", + "subject": "s2", + "frames": 207, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s5/binoculars_see_1/o00_patio_anchor", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s5/binoculars_see_1", + "subject": "s5", + "frames": 302, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s5/bowl_drink_2/o02_cool_patio", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s5/bowl_drink_2", + "subject": "s5", + "frames": 204, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s5/camera_takepicture_3/o02_cool_patio", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s5/camera_takepicture_3", + "subject": "s5", + "frames": 233, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s5/cubesmall_inspect_1/o00_patio_anchor", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s5/cubesmall_inspect_1", + "subject": "s5", + "frames": 247, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s5/cubesmall_lift/o04_soft_patio", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s5/cubesmall_lift", + "subject": "s5", + "frames": 584, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s5/cubesmall_pass_1/o03_sunny_patio", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s5/cubesmall_pass_1", + "subject": "s5", + "frames": 183, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s8/cubesmall_pass_1/o04_soft_patio", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s8/cubesmall_pass_1", + "subject": "s8", + "frames": 223, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s9/cubelarge_pass_1/o01_bright_patio", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s9/cubelarge_pass_1", + "subject": "s9", + "frames": 123, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s9/cubesmall_pass_1/i00_daylight_anchor", + "campaign": "grab_oakink_latest_production_v3", + "sequence_index": "s9/cubesmall_pass_1", + "subject": "s9", + "frames": 156, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/alarmclock_lift/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/alarmclock_lift", + "subject": "s1", + "frames": 510, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/apple_eat_1/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/apple_eat_1", + "subject": "s1", + "frames": 345, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/cylindersmall_inspect_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/cylindersmall_inspect_1", + "subject": "s1", + "frames": 224, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/doorknob_use_1/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/doorknob_use_1", + "subject": "s1", + "frames": 261, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/doorknob_use_2/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/doorknob_use_2", + "subject": "s1", + "frames": 256, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/doorknob_use_fun_1/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/doorknob_use_fun_1", + "subject": "s1", + "frames": 374, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/hammer_use_3/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/hammer_use_3", + "subject": "s1", + "frames": 450, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/headphones_use_1/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/headphones_use_1", + "subject": "s1", + "frames": 269, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/mug_drink_2/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/mug_drink_2", + "subject": "s1", + "frames": 377, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/mug_drink_3/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/mug_drink_3", + "subject": "s1", + "frames": 309, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/pyramidsmall_inspect_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/pyramidsmall_inspect_1", + "subject": "s1", + "frames": 254, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/pyramidsmall_pass_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/pyramidsmall_pass_1", + "subject": "s1", + "frames": 243, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/scissors_use_2/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/scissors_use_2", + "subject": "s1", + "frames": 350, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/spherelarge_pass_1/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/spherelarge_pass_1", + "subject": "s1", + "frames": 245, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/spheresmall_inspect_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/spheresmall_inspect_1", + "subject": "s1", + "frames": 272, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/spheresmall_lift/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/spheresmall_lift", + "subject": "s1", + "frames": 301, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/spheresmall_offhand_1/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/spheresmall_offhand_1", + "subject": "s1", + "frames": 296, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/spheresmall_pass_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/spheresmall_pass_1", + "subject": "s1", + "frames": 264, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/torussmall_inspect_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/torussmall_inspect_1", + "subject": "s1", + "frames": 301, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/torussmall_lift/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/torussmall_lift", + "subject": "s1", + "frames": 489, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/torussmall_offhand_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/torussmall_offhand_1", + "subject": "s1", + "frames": 288, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/torussmall_pass_1/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s1/torussmall_pass_1", + "subject": "s1", + "frames": 287, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/bowl_drink_1_Retake/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/bowl_drink_1_Retake", + "subject": "s10", + "frames": 316, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/camera_takepicture_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/camera_takepicture_1", + "subject": "s10", + "frames": 228, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/camera_takepicture_2/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/camera_takepicture_2", + "subject": "s10", + "frames": 204, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/cubelarge_inspect_1/i00_daylight_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/cubelarge_inspect_1", + "subject": "s10", + "frames": 254, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/cubesmall_pass_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/cubesmall_pass_1", + "subject": "s10", + "frames": 191, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/cup_drink_2/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/cup_drink_2", + "subject": "s10", + "frames": 275, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/cup_pass_1/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/cup_pass_1", + "subject": "s10", + "frames": 195, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/cylindermedium_inspect_1/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/cylindermedium_inspect_1", + "subject": "s10", + "frames": 192, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/cylindersmall_pass_1/i00_daylight_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/cylindersmall_pass_1", + "subject": "s10", + "frames": 168, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/doorknob_lift/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/doorknob_lift", + "subject": "s10", + "frames": 290, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/doorknob_use_1/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/doorknob_use_1", + "subject": "s10", + "frames": 295, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/doorknob_use_2/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/doorknob_use_2", + "subject": "s10", + "frames": 239, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/flashlight_on_2/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/flashlight_on_2", + "subject": "s10", + "frames": 270, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/hammer_use_2/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/hammer_use_2", + "subject": "s10", + "frames": 238, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/lightbulb_screw_1/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/lightbulb_screw_1", + "subject": "s10", + "frames": 262, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/pyramidmedium_lift/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/pyramidmedium_lift", + "subject": "s10", + "frames": 259, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/pyramidsmall_inspect_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/pyramidsmall_inspect_1", + "subject": "s10", + "frames": 125, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/spheresmall_inspect_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/spheresmall_inspect_1", + "subject": "s10", + "frames": 150, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/spheresmall_pass_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/spheresmall_pass_1", + "subject": "s10", + "frames": 166, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/torussmall_inspect_1/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/torussmall_inspect_1", + "subject": "s10", + "frames": 148, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/torussmall_pass_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/torussmall_pass_1", + "subject": "s10", + "frames": 158, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/waterbottle_pour_1/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s10/waterbottle_pour_1", + "subject": "s10", + "frames": 174, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s2/banana_pass_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s2/banana_pass_1", + "subject": "s2", + "frames": 275, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s2/cylindersmall_pass_1/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s2/cylindersmall_pass_1", + "subject": "s2", + "frames": 269, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s2/doorknob_use_2/i00_daylight_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s2/doorknob_use_2", + "subject": "s2", + "frames": 282, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s2/flashlight_on_2/i00_daylight_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s2/flashlight_on_2", + "subject": "s2", + "frames": 287, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s2/headphones_use_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s2/headphones_use_1", + "subject": "s2", + "frames": 191, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s2/mug_drink_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s2/mug_drink_1", + "subject": "s2", + "frames": 249, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s2/spheresmall_inspect_1/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s2/spheresmall_inspect_1", + "subject": "s2", + "frames": 211, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s2/stamp_stamp_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s2/stamp_stamp_1", + "subject": "s2", + "frames": 267, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s2/torussmall_lift/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s2/torussmall_lift", + "subject": "s2", + "frames": 444, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/doorknob_lift/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/doorknob_lift", + "subject": "s4", + "frames": 533, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/doorknob_use_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/doorknob_use_1", + "subject": "s4", + "frames": 320, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/gamecontroller_pass_1/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/gamecontroller_pass_1", + "subject": "s4", + "frames": 190, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/hammer_use_2/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/hammer_use_2", + "subject": "s4", + "frames": 193, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/mouse_pass_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/mouse_pass_1", + "subject": "s4", + "frames": 141, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/mouse_use_2/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/mouse_use_2", + "subject": "s4", + "frames": 247, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/spherelarge_inspect_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/spherelarge_inspect_1", + "subject": "s4", + "frames": 227, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/toruslarge_pass_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/toruslarge_pass_1", + "subject": "s4", + "frames": 177, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/torussmall_lift/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/torussmall_lift", + "subject": "s4", + "frames": 440, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/torussmall_pass_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s4/torussmall_pass_1", + "subject": "s4", + "frames": 158, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/alarmclock_pass_1/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/alarmclock_pass_1", + "subject": "s5", + "frames": 194, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/cup_pass_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/cup_pass_1", + "subject": "s5", + "frames": 206, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/cylinderlarge_lift/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/cylinderlarge_lift", + "subject": "s5", + "frames": 689, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/cylindermedium_pass_1/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/cylindermedium_pass_1", + "subject": "s5", + "frames": 179, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/doorknob_lift/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/doorknob_lift", + "subject": "s5", + "frames": 507, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/flashlight_on_2/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/flashlight_on_2", + "subject": "s5", + "frames": 262, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/mouse_lift/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/mouse_lift", + "subject": "s5", + "frames": 431, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/piggybank_lift/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/piggybank_lift", + "subject": "s5", + "frames": 553, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/piggybank_use_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/piggybank_use_1", + "subject": "s5", + "frames": 221, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/spheremedium_pass_1/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/spheremedium_pass_1", + "subject": "s5", + "frames": 192, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/spheresmall_inspect_1/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/spheresmall_inspect_1", + "subject": "s5", + "frames": 187, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/teapot_pass_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/teapot_pass_1", + "subject": "s5", + "frames": 241, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/torussmall_inspect_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s5/torussmall_inspect_1", + "subject": "s5", + "frames": 261, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/cubelarge_pass_1/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/cubelarge_pass_1", + "subject": "s7", + "frames": 351, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/cubesmall_pass_1/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/cubesmall_pass_1", + "subject": "s7", + "frames": 188, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/cup_pass_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/cup_pass_1", + "subject": "s7", + "frames": 230, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/doorknob_lift/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/doorknob_lift", + "subject": "s7", + "frames": 625, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/doorknob_use_1/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/doorknob_use_1", + "subject": "s7", + "frames": 294, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/doorknob_use_2/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/doorknob_use_2", + "subject": "s7", + "frames": 345, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/gamecontroller_lift/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/gamecontroller_lift", + "subject": "s7", + "frames": 614, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/hammer_use_2/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/hammer_use_2", + "subject": "s7", + "frames": 244, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/knife_chop_1/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/knife_chop_1", + "subject": "s7", + "frames": 252, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/lightbulb_pass_1/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/lightbulb_pass_1", + "subject": "s7", + "frames": 128, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/mouse_pass_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/mouse_pass_1", + "subject": "s7", + "frames": 153, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/mouse_use_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/mouse_use_1", + "subject": "s7", + "frames": 274, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/mug_drink_1/o04_soft_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/mug_drink_1", + "subject": "s7", + "frames": 228, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/mug_drink_2/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/mug_drink_2", + "subject": "s7", + "frames": 268, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/piggybank_pass_1/i00_daylight_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/piggybank_pass_1", + "subject": "s7", + "frames": 243, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/pyramidlarge_inspect_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/pyramidlarge_inspect_1", + "subject": "s7", + "frames": 243, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/pyramidlarge_pass_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/pyramidlarge_pass_1", + "subject": "s7", + "frames": 129, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/pyramidmedium_inspect_1/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/pyramidmedium_inspect_1", + "subject": "s7", + "frames": 170, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/pyramidmedium_pass_1/i00_daylight_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/pyramidmedium_pass_1", + "subject": "s7", + "frames": 142, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/pyramidsmall_inspect_1/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/pyramidsmall_inspect_1", + "subject": "s7", + "frames": 228, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/pyramidsmall_pass_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/pyramidsmall_pass_1", + "subject": "s7", + "frames": 138, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/spherelarge_inspect_1/i00_daylight_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/spherelarge_inspect_1", + "subject": "s7", + "frames": 266, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/spherelarge_lift/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/spherelarge_lift", + "subject": "s7", + "frames": 464, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/spheresmall_pass_1/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/spheresmall_pass_1", + "subject": "s7", + "frames": 195, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/toothbrush_pass_1/i00_daylight_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/toothbrush_pass_1", + "subject": "s7", + "frames": 188, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/torussmall_inspect_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/torussmall_inspect_1", + "subject": "s7", + "frames": 217, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/torussmall_pass_1/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/torussmall_pass_1", + "subject": "s7", + "frames": 210, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/train_lift/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s7/train_lift", + "subject": "s7", + "frames": 642, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/bowl_offhand_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/bowl_offhand_1", + "subject": "s8", + "frames": 253, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/cylindersmall_inspect_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/cylindersmall_inspect_1", + "subject": "s8", + "frames": 292, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/cylindersmall_lift/o00_patio_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/cylindersmall_lift", + "subject": "s8", + "frames": 475, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/doorknob_lift/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/doorknob_lift", + "subject": "s8", + "frames": 473, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/doorknob_use_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/doorknob_use_1", + "subject": "s8", + "frames": 363, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/doorknob_use_2/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/doorknob_use_2", + "subject": "s8", + "frames": 302, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/eyeglasses_pass_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/eyeglasses_pass_1", + "subject": "s8", + "frames": 267, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/flashlight_on_2/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/flashlight_on_2", + "subject": "s8", + "frames": 346, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/phone_lift/i01_sage_morning", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/phone_lift", + "subject": "s8", + "frames": 532, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/spheresmall_inspect_1/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/spheresmall_inspect_1", + "subject": "s8", + "frames": 286, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/spheresmall_lift/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/spheresmall_lift", + "subject": "s8", + "frames": 460, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/spheresmall_pass_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/spheresmall_pass_1", + "subject": "s8", + "frames": 257, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/torussmall_inspect_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/torussmall_inspect_1", + "subject": "s8", + "frames": 269, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/torussmall_pass_1/o03_sunny_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/torussmall_pass_1", + "subject": "s8", + "frames": 258, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/waterbottle_drink_1/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s8/waterbottle_drink_1", + "subject": "s8", + "frames": 290, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/cup_pass_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/cup_pass_1", + "subject": "s9", + "frames": 123, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/doorknob_lift/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/doorknob_lift", + "subject": "s9", + "frames": 269, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/doorknob_use_2/i00_daylight_anchor", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/doorknob_use_2", + "subject": "s9", + "frames": 163, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/eyeglasses_wear_1/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/eyeglasses_wear_1", + "subject": "s9", + "frames": 295, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/flute_play_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/flute_play_1", + "subject": "s9", + "frames": 237, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/lightbulb_screw_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/lightbulb_screw_1", + "subject": "s9", + "frames": 194, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/mug_pass_1/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/mug_pass_1", + "subject": "s9", + "frames": 228, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/spheresmall_inspect_1/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/spheresmall_inspect_1", + "subject": "s9", + "frames": 170, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/spheresmall_pass_1/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/spheresmall_pass_1", + "subject": "s9", + "frames": 190, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/teapot_pass_1/i03_warm_evening", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/teapot_pass_1", + "subject": "s9", + "frames": 201, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/torussmall_inspect_1/i04_mixed_daylight", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/torussmall_inspect_1", + "subject": "s9", + "frames": 151, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/torussmall_lift/i02_cool_overcast", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/torussmall_lift", + "subject": "s9", + "frames": 628, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/torussmall_pass_1/o01_bright_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/torussmall_pass_1", + "subject": "s9", + "frames": 139, + "resolution": [ + 1536, + 864 + ] + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s9/waterbottle_pass_1/o02_cool_patio", + "campaign": "grab_recipe_production_v4", + "sequence_index": "s9/waterbottle_pass_1", + "subject": "s9", + "frames": 164, + "resolution": [ + 1536, + 864 + ] + } + ], + "summary": { + "clips": 153, + "frames": 42508, + "subjects": [ + "s1", + "s10", + "s2", + "s4", + "s5", + "s7", + "s8", + "s9" + ], + "rejected_clips": 50, + "mask_review_clips": 12 + }, + "rejected": [ + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v2/GRAB/93e4ef6ba1e58c7ee3a82ead8164e9ea581742c0896a6c102f813231e235d2e6/s3/airplane_offhand_1/o00_patio_anchor", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v2/GRAB/93e4ef6ba1e58c7ee3a82ead8164e9ea581742c0896a6c102f813231e235d2e6/s3/alarmclock_pass_1/i02_cool_overcast", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s3/camera_offhand_1/o04_soft_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s3/camera_takepicture_1/i03_warm_evening", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s3/camera_takepicture_2/i04_mixed_daylight", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s6/camera_takepicture_3/o03_sunny_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s6/cubesmall_offhand_1/o01_bright_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/airplane_fly_1/i01_sage_morning", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/cylindersmall_pass_1/o03_sunny_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/doorknob_use_1/i00_daylight_anchor", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/doorknob_use_2/i02_cool_overcast", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/eyeglasses_offhand_1/i01_sage_morning", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/eyeglasses_pass_1/o04_soft_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/eyeglasses_wear_1/i03_warm_evening", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/flashlight_pass_1/o02_cool_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/gamecontroller_lift/o04_soft_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/hammer_use_2/i02_cool_overcast", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/knife_lift/i04_mixed_daylight", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/lightbulb_screw_1/o01_bright_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/mouse_use_1/i01_sage_morning", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/piggybank_pass_1/o04_soft_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/pyramidsmall_pass_1/o03_sunny_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/scissors_use_2/o02_cool_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/spheresmall_pass_1/o00_patio_anchor", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/stanfordbunny_lift/o02_cool_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/stanfordbunny_pass_1/i01_sage_morning", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/stapler_lift/o02_cool_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/toothbrush_brush_1/i01_sage_morning", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/toothbrush_pass_1/o04_soft_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s3/toothpaste_lift/o00_patio_anchor", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/airplane_fly_1/o02_cool_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/cylinderlarge_pass_1/o02_cool_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/cylindersmall_inspect_1/o01_bright_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/cylindersmall_pass_1/i03_warm_evening", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/doorknob_lift/i03_warm_evening_capture_context_v1", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/doorknob_use_1/i01_sage_morning_capture_context_v1", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/doorknob_use_2/i01_sage_morning", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/eyeglasses_pass_1/o00_patio_anchor", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/eyeglasses_wear_1/o01_bright_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/flashlight_on_2/i04_mixed_daylight", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/flashlight_pass_1/o04_soft_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/flute_lift/o00_patio_anchor", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/hand_pass_1/i04_mixed_daylight", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/phone_pass_1/i02_cool_overcast", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/pyramidsmall_inspect_2/i01_sage_morning", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/spheremedium_pass_1/o03_sunny_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/spheresmall_pass_1/o02_cool_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/stanfordbunny_pass_1/o04_soft_patio", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/torussmall_pass_1/i02_cool_overcast", + "reason": "missing_personal_template_or_audit_failure" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s6/train_pass_1/i01_sage_morning", + "reason": "missing_personal_template_or_audit_failure" + } + ], + "mask_review": [ + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_oakink_latest_production_v3/GRAB/407ce37711e678cc602880fa7614dde24e9450fb22e34bdddf9298ed42d64680/s5/bowl_drink_2/o02_cool_patio", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/doorknob_use_1/o00_patio_anchor", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s1/doorknob_use_fun_1/o00_patio_anchor", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/camera_takepicture_1/o03_sunny_patio", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/doorknob_lift/o02_cool_patio", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s10/doorknob_use_2/o00_patio_anchor", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/doorknob_lift/o01_bright_patio", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s4/doorknob_use_1/o01_bright_patio", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s5/doorknob_lift/i02_cool_overcast", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/knife_chop_1/i04_mixed_daylight", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s7/pyramidlarge_inspect_1/i03_warm_evening", + "reason": "visible_human_mask_distance_only" + }, + { + "clip": "/SSD3/wbr/bedlam2_remote_render/production/synthetic_training_minimal_v1/grab_recipe_production_v4/GRAB/0c165bc3c9472cf16a2b580c4bc24ba932a46731bddd87a96972dc238b3b7975/s8/waterbottle_drink_1/i02_cool_overcast", + "reason": "visible_human_mask_distance_only" + } + ], + "mask_review_note": "A visible segmentation miss or object occlusion is not proof of GT projection error.", + "caveat": "Templates are stored with v6 eval sidecars, so v6 is not subject-shape-independent evaluation." +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/smoke.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..76589a1399735215c1caaae85c7f13c22ce17eb5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/smoke.py @@ -0,0 +1,47 @@ +"""One GRAB target through the frozen-visual parent and the production loss.""" + +import json + +import torch + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, base +from experiments.from_scratch_mean_pose.throughput_probe import collate_matching_resolutions +from experiments.vitpose_mot_io_v4.model import build_model + +from .data import PilotCoverage, PilotDataset +from .train import CONFIG, STATS + + +def main(): + fitted = json.loads(STATS.read_text()) + coverage = PilotCoverage(True) + dataset = PilotDataset(True) + position = next(i for i in range(60) if coverage.sample(i)["source"] == "GRAB") + sample = dataset[coverage.sample(position)] + assert not sample["shape_valid"].any() + assert not sample["K_input_available"].any() + assert not sample["depth_input_available"].any() + assert sample["reprojection_valid"].sum() > 0 + cpu = collate_matching_resolutions([sample], 10)[0] + device = torch.device("cuda:0") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + parent = torch.load(CONFIG["parent_checkpoint"], map_location="cpu", weights_only=False, mmap=True) + model.load_state_dict(parent["model"], strict=True) + del parent + model.to(device).eval() + batch = base.move_to_device(cpu, device) + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + with torch.no_grad(): + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + loss, terms, diagnostics = objective(prediction, batch) + assert torch.isfinite(loss) + print(json.dumps({"position": position, "loss": float(loss), + "weighted_terms": {key: float(value) for key, value in terms.items()}, + "diagnostics": diagnostics}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/train.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/train.py new file mode 100644 index 0000000000000000000000000000000000000000..2eef27d1cc7ce733863bc23d4c0e2a2be50b15b4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/train.py @@ -0,0 +1,340 @@ +"""Isolated RGB MoT continuation with original-personalized GRAB targets.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +import foundation_hand.geometry.rotations as rotations +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.fit_targets import mano_pkl_mean +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base, sha +from experiments.from_scratch_mean_pose.throughput_probe import ( + PROBE_FIELDS, collate_matching_resolutions, initialize_worker, select_clip, +) +from .data import MANIFEST, PilotCoverage, PilotDataset +from experiments.vitpose_mot_io_v4.model import MANO_ROOT, VISUAL_SHA256, VISUAL_WEIGHTS, build_model, verify_visual_weights + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +STATS = BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"] +INDEX = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite") +LABELS = Path("/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json") +PARENT = Path(CONFIG["parent_checkpoint"]) + + +def code_hashes(): + files = [ROOT / "train.py", ROOT / "data.py", ROOT / "config.json", ROOT / "manifest.json", + ROOT.parent / "vitpose_mot_io_v4/train.py", ROOT.parent / "vitpose_mot_io_v4/model.py", + ROOT.parent / "vitpose_mot_io_v4/data.py", ROOT.parent / "vitpose_mot_io_v4/hot3d_hand_only.py", + BASE_ROOT / "config.json", BASE_ROOT / "loss.py", BASE_ROOT / "model.py", BASE_ROOT / "fit_targets.py", + BASE_ROOT / "throughput_probe.py", + BASE_ROOT / "statistics_mano_pkl_v2.json", + ROOT.parent / "dinov3_2d_pretrain/vitpose_probe.py", + ROOT.parent / "u0_depthsafe/model.py", + ROOT.parent / "u0_depthsafe/reprojection.py", + ROOT.parent / "u0_normalized6d/normalized_loss.py", + ROOT.parent / "a7_rotation_fix/filtered_dataset.py", + ROOT.parent.parent / "src/foundation_hand/models/bimanual.py", + ROOT.parent.parent / "src/foundation_hand/models/decoder.py", + ROOT.parent.parent / "src/foundation_hand/models/encoders.py", + ROOT.parent.parent / "src/foundation_hand/models/mano.py", + ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py", + ROOT.parent.parent / "src/foundation_hand/data/schema.py", + ROOT.parent.parent / "src/foundation_hand/data/h2o_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/arctic_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/hot3d_dataset.py"] + return {str(path.relative_to(ROOT.parent.parent)): sha(path) for path in files} + + +def verify_contract(fitted): + expected_rotations = ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py" + if Path(rotations.__file__).resolve() != expected_rotations.resolve(): + raise RuntimeError(f"wrong rotation implementation loaded: {rotations.__file__}") + verify_visual_weights() + if BASE_CONFIG["shared"]["teacher"] != { + "create_model": False, "forward": False, "distillation": False, "rgb_teacher_weight": 0.0, + }: + raise RuntimeError("teacher-free base loss contract changed") + if BASE_CONFIG["shared"]["loss"]["joint2d"] != 0 or BASE_CONFIG["shared"]["loss"]["reprojection"] != 1: + raise RuntimeError("2D supervision must be MANO reprojection only") + if fitted["training_index_sha256"] != sha(INDEX) or fitted["label_inventory_sha256"] != sha(LABELS): + raise RuntimeError("train-only fitted statistics do not match current data") + if fitted["source_quota"] != {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}: + raise RuntimeError("parent statistics source mixture differs") + if fitted["version"] != "b0_b1_mano_pkl_mean_delta_v2": + raise RuntimeError("expected official MANO-pkl mean and normalized delta statistics") + mean, hashes = mano_pkl_mean(Path(MANO_ROOT)) + if hashes != fitted["mano_pkl_sha256"] or not torch.allclose( + torch.as_tensor(mean, dtype=torch.float64), + torch.as_tensor(fitted["mean_local"], dtype=torch.float64), atol=1e-7, rtol=0, + ): + raise RuntimeError("official MANO mean/asset mismatch") + if sha(VISUAL_WEIGHTS) != VISUAL_SHA256: + raise RuntimeError("ViTPose visual asset changed") + if any(sum(quota.values()) != CONFIG["global_batch"] for quota in CONFIG["variants"].values()): + raise RuntimeError("source quotas do not fill global batch") + if MANIFEST["summary"]["clips"] != 153 or MANIFEST["summary"]["frames"] != 42508: + raise RuntimeError("audited GRAB pilot manifest changed") + return {"code_sha256": code_hashes(), "index_sha256": sha(INDEX), + "labels_sha256": sha(LABELS), "statistics_sha256": sha(STATS), + "visual_sha256": VISUAL_SHA256, "mano_pkl_sha256": hashes, + "parent_sha256": sha(PARENT), + "template_sha256": MANIFEST["template_sha256"]} + + +def rng_state(): + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state()} + + +def restore_rng(state): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"]) + torch.cuda.set_rng_state(state["cuda"]) + + +def single_training_sample(samples): + if len(samples) != 1: + raise RuntimeError("loader must return one clip at a time") + sample = samples[0] + missing = PROBE_FIELDS - sample.keys() + if missing: + raise RuntimeError(f"training clip is missing fields: {sorted(missing)}") + return {key: sample[key] for key in PROBE_FIELDS} + + +def schedule(update): + settings = CONFIG["optimizer"] + endpoint = settings["endpoint_updates"] + warmup = settings["warmup_updates"] + floor = settings["minimum_lr_ratio"] + fraction = min(1.0, max(0.0, (update - warmup) / (endpoint - warmup))) + factor = max(1 / warmup, (update + 1) / warmup) if update < warmup else ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * fraction))) + return settings["lr_peak"] * factor + + +def save_checkpoint(path, model, optimizer, update, provenance, rng_states, exposure, smoke, world, variant): + if path.exists(): + raise FileExistsError(path) + state = {"experiment": CONFIG["experiment"], "variant": variant, "model": model.state_dict(), + "optimizer": optimizer.state_dict(), "update": update, + "next_sample_position": update * CONFIG["global_batch"], + "world_size": world, "global_batch": CONFIG["global_batch"], + "source_exposure": dict(exposure), "rank_rng_states": rng_states, + "provenance": provenance, "config": CONFIG, "complete_backbone": True, + "teacher_used": False, "parent_checkpoint": str(PARENT), "smoke": smoke} + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + loaded = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("full checkpoint load-back failed") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, default=120000) + parser.add_argument("--resume", type=Path) + parser.add_argument("--variant", choices=tuple(CONFIG["variants"]), default="mixed") + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--log-every", type=int, default=25) + args = parser.parse_args() + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if (not args.smoke and world not in (5, 6)) or (args.smoke and world not in (1, 2)): + raise RuntimeError("pilot requires five/six GPUs; smoke requires one/two") + if args.updates < 1 or args.updates > CONFIG["optimizer"]["endpoint_updates"]: + raise RuntimeError("updates outside pilot schedule") + if args.smoke and args.updates > 2: + raise RuntimeError("smoke is at most two updates") + if args.workers < 1 or args.log_every < 1: + raise ValueError("workers/log interval must be positive") + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError(f"rank {rank}: less than 18 GiB free") + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=20), device_id=device) + try: + if rank == 0: + args.output.parent.mkdir(parents=True, exist_ok=True) + dist.barrier(device_ids=[local]) + if shutil.disk_usage(args.output.parent).free < 100 * 1024**3: + raise RuntimeError("less than 100 GiB free for complete checkpoints") + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + quota = CONFIG["variants"][args.variant] + sources = tuple(quota) + seed = BASE_CONFIG["shared"]["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + state = None + start = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["variant"] != args.variant + or state["world_size"] != world + or state["global_batch"] != CONFIG["global_batch"] + or state["config"] != CONFIG or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] != str(PARENT) or state["smoke"] != args.smoke): + raise RuntimeError("resume checkpoint contract mismatch") + start = state["update"] + if state["next_sample_position"] != start * CONFIG["global_batch"] or start >= args.updates: + raise RuntimeError("resume cursor or endpoint mismatch") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if state is None: + parent = torch.load(PARENT, map_location="cpu", weights_only=False, mmap=True) + model.load_state_dict(parent["model"], strict=True) + del parent + model.to(device).train() + new = [p for name, p in model.named_parameters() + if not name.startswith("rgb_encoder.backbone.") and p.requires_grad] + if not new or any(p.requires_grad for p in model.rgb_encoder.backbone.parameters()): + raise RuntimeError("optimizer parameter partition invalid") + optimizer = torch.optim.AdamW([{"params": new, "name": "non_visual", "lr": schedule(start)}], + weight_decay=CONFIG["optimizer"]["weight_decay"]) + exposure = Counter() + if state: + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + exposure.update(state["source_exposure"]) + restore_rng(state["rank_rng_states"][rank]) + del state + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh training would overwrite old metrics") + (args.output / "provenance.json").write_text(json.dumps({ + "experiment": CONFIG["experiment"], "contract": provenance, + "loss_coefficients": BASE_CONFIG["shared"]["loss"], + "optimizer": CONFIG["optimizer"], "io": CONFIG["io"], + "workers_per_rank": args.workers, + "resume": str(args.resume) if args.resume else None, "smoke": args.smoke, + "variant": args.variant, "source_quota": quota, "parent_checkpoint": str(PARENT), + }, indent=2) + "\n") + dist.barrier(device_ids=[local]) + sampler = base.PositionSampler(PilotCoverage(args.variant == "mixed"), + start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(PilotDataset(args.variant == "mixed"), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=True, + collate_fn=single_training_sample, pin_memory=True, + prefetch_factor=CONFIG["io"]["prefetch_factor"], + worker_init_fn=partial(initialize_worker, opencv_threads=1), + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + clips_per_rank = CONFIG["global_batch"] // world + for update in range(start, args.updates): + lr_new = schedule(update) + optimizer.param_groups[0]["lr"] = lr_new + started = time.monotonic() + cpu_batches = collate_matching_resolutions( + [next(iterator) for _ in range(clips_per_rank)], CONFIG["io"]["group_max_clips"]) + data_ready = time.monotonic() + if sum(len(cpu["input_mode"]) for cpu in cpu_batches) != clips_per_rank: + raise RuntimeError("grouping changed the per-rank clip count") + counts = Counter(source for cpu in cpu_batches for source in cpu["sampling_source_id"]) + local_counts = torch.tensor([counts[source] for source in sources], device=device) + dist.all_reduce(local_counts) + if local_counts.tolist() != [quota[source] for source in sources]: + raise RuntimeError("source quota per update changed") + optimizer.zero_grad(set_to_none=True) + total_loss = 0.0 + term_totals = {key: 0.0 for key in TERMS} + nonpositive = 0 + valid_pose = 0 + for micro, cpu in enumerate(cpu_batches): + count = len(cpu["input_mode"]) + if cpu["input_mode"] != ["rgb"] * count or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("non-RGB input reached ViTPose-L") + batch = base.move_to_device(cpu, device) + if "GRAB" not in cpu["sampling_source_id"]: + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < len(cpu_batches) else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + results = [objective(select_clip(prediction, index, count), + select_clip(batch, index, count)) + for index in range(count)] + loss = torch.stack([result[0] for result in results]).sum() + if not bool(torch.isfinite(loss)) or any( + result[2]["gt_rotation_orthogonality_max"] > 1e-5 for result in results + ): + raise RuntimeError(f"nonfinite loss or invalid GT at update {update + 1}") + (loss / clips_per_rank).backward() + for clip_loss, terms, diagnostics in results: + total_loss += float(clip_loss.detach()) / clips_per_rank + for name, value in terms.items(): + term_totals[name] += float(value.detach()) / clips_per_rank + nonpositive += diagnostics["nonpositive_reprojection_joints"] + valid_pose += diagnostics["valid_local_frames"] + trainable = [p for p in model.parameters() if p.requires_grad] + norm = torch.nn.utils.clip_grad_norm_(trainable, CONFIG["optimizer"]["clip_grad_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"nonfinite gradient at update {update + 1}") + optimizer.step() + elapsed = time.monotonic() - started + for source, count in zip(sources, local_counts.tolist()): + exposure[source] += count + if rank == 0 and ((update + 1) % args.log_every == 0 or update < 10): + row = {"update": update + 1, "consumed_clips": (update + 1) * CONFIG["global_batch"], + "seconds": elapsed, "data_wait_seconds": data_ready - started, + "loss_rank0": total_loss, "terms_rank0": term_totals, + "preclip_grad_norm_rank0": float(norm), "nonpositive_rank0": nonpositive, + "valid_local_pose_frames_rank0": valid_pose, + "learning_rate_new": lr_new, "learning_rate_visual": 0.0, + "exposure": dict(exposure)} + log.write(json.dumps(row, allow_nan=False) + "\n") + print(json.dumps(row, allow_nan=False), flush=True) + if update + 1 in CONFIG["evaluation_updates"] or update + 1 == args.updates: + gathered = [None] * world + dist.all_gather_object(gathered, rng_state()) + if rank == 0: + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", model, + optimizer, update + 1, provenance, gathered, exposure, + args.smoke, world, args.variant) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/watch_and_launch_5k.py b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/watch_and_launch_5k.py new file mode 100644 index 0000000000000000000000000000000000000000..99c9724902c43d56f3c528d8c1f49e34bca1b6c1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/grab_personal_rgb_pilot/watch_and_launch_5k.py @@ -0,0 +1,57 @@ +"""Start 2K->5K continuation only after the six-GPU pilot exits cleanly.""" + +import json +import os +from pathlib import Path +import subprocess +import time + +import torch + + +ROOT = Path("/home/wuyifan/artifacts/grab_personal_rgb_pilot_20261011") +BASE = ROOT / "pilot_mixed_2k" +CHECKPOINT = BASE / "update_0002000.pt" +NEXT = ROOT / "pilot_mixed_2k_to_5k" +SESSION = "grab_personal_pilot_1011" +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/torchrun" + + +def main() -> None: + while subprocess.run(["tmux", "has-session", "-t", SESSION], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0: + time.sleep(30) + if not CHECKPOINT.is_file(): + raise RuntimeError("2K job ended without its final checkpoint; 5K continuation not launched") + last = json.loads((BASE / "metrics.jsonl").read_text().splitlines()[-1]) + if last["update"] != 2000: + raise RuntimeError(f"2K job ended at logged step {last['update']}; 5K continuation not launched") + state = torch.load(CHECKPOINT, map_location="cpu", weights_only=False, mmap=True) + if (state["update"] != 2000 or state["world_size"] != 6 or + state["source_exposure"].get("GRAB") != 6000): + raise RuntimeError("2K checkpoint contract failed") + del state + print("Verified 2K checkpoint; waiting for six free GPUs", flush=True) + while True: + result = subprocess.run(["nvidia-smi", "--query-gpu=memory.free", + "--format=csv,noheader,nounits"], + capture_output=True, text=True, check=True) + free_mb = [int(value.strip()) for value in result.stdout.splitlines()] + if len(free_mb) == 6 and all(value >= 18 * 1024 for value in free_mb): + break + time.sleep(30) + if NEXT.exists(): + raise FileExistsError(f"continuation output already exists: {NEXT}") + os.chdir("/home/wuyifan/EgoNet_train_20261008") + os.environ["PYTHONPATH"] = "src:." + os.environ["CUDA_VISIBLE_DEVICES"] = "0,1,2,3,4,5" + command = [PYTHON, "--standalone", "--nproc_per_node=6", "-m", + "experiments.grab_personal_rgb_pilot.continue_to_5k", + "--output", str(NEXT), "--updates", "5000", "--variant", "mixed", + "--resume", str(CHECKPOINT), "--workers", "4", "--log-every", "25"] + print("Launching: " + " ".join(command), flush=True) + os.execv(PYTHON, command) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_distribution.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..b741003226602027d11b85ad6ffc734433c7f763 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_distribution.py @@ -0,0 +1,181 @@ +"""Read-only pose-distribution audit over the frozen T8 training index.""" + +import collections +import json +import random +import sqlite3 + +import numpy as np +from scipy.spatial.transform import Rotation + + +INDEX = "/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite" +INVENTORY = "/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json" +GRAB = "/SSD3/yangzijing/MiroHand_GRAB_channels_v2_benchmark_20260930" +GRAB_A7 = "/SSD3/yangzijing/MiroHand_A7_refit_rotationfix_GRAB_20260930" +GRAB_U0 = "/home/wuyifan/unified_mot_u0_grab_ood_20261001/full100/predictions" +SOURCES = ("H2O", "ARCTIC", "HOT3D") +SAMPLE_TILES = 2000 + + +def finger_angles(joints): + fingers = joints[..., 1:, :].reshape(*joints.shape[:-2], 5, 4, 3) + bones = np.diff(fingers, axis=-2) + lengths = np.linalg.norm(bones, axis=-1) + unit = bones / np.maximum(lengths[..., None], 1e-8) + cosine = (unit[..., :-1, :] * unit[..., 1:, :]).sum(-1) + angles = np.rad2deg(np.arccos(np.clip(cosine, -1, 1))) + angles = np.where((lengths[..., :-1] > 1e-6) & (lengths[..., 1:] > 1e-6), angles, np.nan) + return angles[..., 1:, :] + + +def main(): + inventory = json.load(open(INVENTORY))["entries"] + labels = {(row["source"], row["recording"]): row["path"] for row in inventory} + connection = sqlite3.connect(INDEX) + rng = random.Random(20261002) + output = {} + for source in SOURCES: + tile_ids = [row[0] for row in connection.execute( + "SELECT tile_id FROM tiles WHERE source=? ORDER BY tile_id", (source,) + )] + chosen = rng.sample(tile_ids, min(SAMPLE_TILES, len(tile_ids))) + angle_chunks = [] + hand_chunks = [] + pose_chunks_by_side = [[], []] + recording_counts = collections.Counter() + hand_count = 0 + filtered_count = 0 + for tile_id in chosen: + recording, start, frame_ids_json, manifest_json = connection.execute( + "SELECT t.recording_id, t.start_offset, t.frame_ids_json, w.manifest_json " + "FROM tiles t JOIN windows w USING(window_id) WHERE t.tile_id=?", (tile_id,) + ).fetchone() + row = json.loads(manifest_json) + ids = np.asarray(json.loads(frame_ids_json), dtype=np.int64) + with np.load(row["filtered_gt_path"], allow_pickle=False) as data: + filtered_ids = data["frame_ids"][start:start + len(ids)] + valid = data["valid"][start:start + len(ids)].astype(bool) + if not np.array_equal(filtered_ids, ids): + raise ValueError((source, tile_id, "frame mismatch")) + if source == "HOT3D": + joints = data["joints_native_m"][start:start + len(ids)] + pose = data["local_pose_aa_rad"][start:start + len(ids)] + # The filtered SMPL-X cache stores 16 MANO joints followed by + # five fingertips; the model's manopth output is finger-major. + joints = joints[..., [0, 13, 14, 15, 16, 1, 2, 3, 17, + 4, 5, 6, 18, 10, 11, 12, 19, + 7, 8, 9, 20], :] + if source != "HOT3D": + with np.load(labels[(source, recording)], allow_pickle=False) as data: + label_ids = data["frame_ids"] + positions = np.searchsorted(label_ids, ids) + if not np.array_equal(label_ids[positions], ids): + raise ValueError((source, tile_id, "label mismatch")) + joints = data["joints"][positions] + pose = data["pose"][positions, :, 3:] + valid &= data["hand"][positions].astype(bool) + hand_count += int(valid.sum()) + filtered_count += len(ids) * 2 + recording_counts[recording] += 1 + angles = finger_angles(joints) + complete = valid & np.isfinite(angles).all(axis=(-1, -2)) + hand_angles = angles[complete] + if len(hand_angles): + angle_chunks.append(hand_angles.reshape(-1)) + hand_chunks.append(hand_angles) + for side in range(2): + if complete[:, side].any(): + pose_chunks_by_side[side].append( + pose[:, side][complete[:, side]].reshape(-1, 15, 3) + ) + angle_values = np.concatenate(angle_chunks) + hands = np.concatenate(hand_chunks) + pose_stats = [] + for chunks in pose_chunks_by_side: + poses = np.concatenate(chunks) + mean_angles = [] + flat_errors = [] + mean_errors = [] + for joint in range(15): + rotations = Rotation.from_rotvec(poses[:, joint]) + center = rotations.mean() + mean_angles.append(np.rad2deg(center.magnitude())) + flat_errors.append(np.rad2deg(rotations.magnitude()).mean()) + mean_errors.append(np.rad2deg((center.inv() * rotations).magnitude()).mean()) + pose_stats.append({ + "hand_frames": len(poses), + "mean_distance_from_flat_deg": round(float(np.mean(mean_angles)), 2), + "gt_distance_from_flat_deg": round(float(np.mean(flat_errors)), 2), + "gt_distance_from_source_side_mean_deg": round(float(np.mean(mean_errors)), 2), + }) + bins = np.histogram(angle_values, bins=[0, 20, 45, 60, 181])[0] + output[source] = { + "all_train_tiles": len(tile_ids), + "sampled_tiles": len(chosen), + "sampled_recordings": len(recording_counts), + "valid_hand_frames": hand_count, + "complete_angle_hand_frames": len(hands), + "valid_hand_fraction": round(hand_count / filtered_count, 4), + "angle_counts_0_20_45_60_plus": bins.tolist(), + "angle_pct_0_20_45_60_plus": (100 * bins / bins.sum()).round(2).tolist(), + "angle_mean_deg": round(float(angle_values.mean()), 2), + "angle_p50_p90_p99_deg": np.percentile(angle_values, [50, 90, 99]).round(2).tolist(), + "hand_pct_two_or_more_angles_ge45": round(float(100 * ((hands >= 45).sum((1, 2)) >= 2).mean()), 2), + "hand_pct_any_angle_ge60": round(float(100 * (hands >= 60).any((1, 2)).mean()), 2), + "local_joint_pose_by_side_left_right": pose_stats, + } + grab_angles = [] + grab_hands = [] + prediction_bins = {model: [[] for _ in range(4)] for model in ("A7_RGB", "U0_RGB_16K")} + bin_edges = [0, 20, 45, 60, 181] + for selected in json.load(open(f"{GRAB}/selection.json")): + meta = json.load(open(f"{GRAB}/rgb/inputs/{selected['id']}/complete.json")) + with np.load(meta["reference"], allow_pickle=False) as data: + valid = data["valid"] & data["hand_any_joint_in_frame"] + joints = data["joints_camera_m"].copy() + joints[:, :, [4, 8, 12, 16, 20]] = data["vertices_camera_m"][:, :, [744, 320, 443, 554, 671]] + angles = finger_angles(joints) + complete = valid & np.isfinite(angles).all(axis=(-1, -2)) + hand_angles = angles[complete] + if len(hand_angles): + grab_angles.append(hand_angles.reshape(-1)) + grab_hands.append(hand_angles) + for name, path in ( + ("A7_RGB", f"{GRAB_A7}/rgb/predictions/A7/{selected['id']}/prediction.npz"), + ("U0_RGB_16K", f"{GRAB_U0}/{selected['id']}.npz"), + ): + with np.load(path, allow_pickle=False) as prediction: + pred_joints = prediction["joints_camera_m"].copy() + pred_joints[:, :, [4, 8, 12, 16, 20]] = prediction["vertices_camera_m"][:, :, [744, 320, 443, 554, 671]] + pred_angles = finger_angles(pred_joints) + selected_angles = angles[complete] + signed = (pred_angles - angles)[complete] + for index in range(4): + mask = (selected_angles >= bin_edges[index]) & (selected_angles < bin_edges[index + 1]) + prediction_bins[name][index].append(signed[mask]) + angle_values = np.concatenate(grab_angles) + hands = np.concatenate(grab_hands) + bins = np.histogram(angle_values, bins=[0, 20, 45, 60, 181])[0] + output["GRAB_OOD_GT"] = { + "recordings": 100, + "complete_angle_hand_frames": len(hands), + "angle_counts_0_20_45_60_plus": bins.tolist(), + "angle_pct_0_20_45_60_plus": (100 * bins / bins.sum()).round(2).tolist(), + "angle_mean_deg": round(float(angle_values.mean()), 2), + "angle_p50_p90_p99_deg": np.percentile(angle_values, [50, 90, 99]).round(2).tolist(), + "hand_pct_two_or_more_angles_ge45": round(float(100 * ((hands >= 45).sum((1, 2)) >= 2).mean()), 2), + "hand_pct_any_angle_ge60": round(float(100 * (hands >= 60).any((1, 2)).mean()), 2), + } + output["GRAB_OOD_MODEL_ERROR_BY_GT_ANGLE"] = { + name: [ + {"count": len(values), "signed_bias_deg": round(float(values.mean()), 2), + "mae_deg": round(float(np.abs(values).mean()), 2)} + for values in (np.concatenate(chunks) for chunks in buckets) + ] for name, buckets in prediction_bins.items() + } + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_hard_exposure.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_hard_exposure.py new file mode 100644 index 0000000000000000000000000000000000000000..14843dc9b58222a95d61e44cbb23c3cde94a5df6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_hard_exposure.py @@ -0,0 +1,79 @@ +"""Sample the registered training stream to estimate N1 hard-case exposure.""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys + +import torch + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, "/home/wuyifan/u0_normalized6d_20261002") + +from train import CONFIG, U0Coverage, U0Dataset, base # noqa: E402 +from normalized_loss import hand_tail_weights # noqa: E402 + +OUTPUT = ROOT / "evaluations/hard_exposure_30_tiles_per_source.json" +SOURCES = ("H2O", "ARCTIC", "HOT3D") +PER_SOURCE = 30 + + +def main() -> None: + if OUTPUT.exists(): + raise FileExistsError(OUTPUT) + coverage, dataset = U0Coverage(), U0Dataset() + rows = {source: [] for source in SOURCES} + total = CONFIG["full_stage_clips"] + for index in range(PER_SOURCE): + base_position = (index * 2 + 1) * total // (2 * PER_SOURCE) + pending = set(SOURCES) + for offset in range(120): + position = base_position + offset + spec = coverage.sample(position) + source = spec["source"] + if source not in pending: + continue + batch = base.collate_h2o_clips([dataset[spec]]) + pose = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + weight = hand_tail_weights(batch, True) + active = weight[pose] + row = { + "position": position, + "tile_id": batch["filtered_tile_id"][0], + "pose_valid_hands": int(pose.sum()), + "weighted_15": int((active == 1.5).sum()), + "weighted_20": int((active == 2).sum()), + "weight_mass": float(active.sum()), + } + rows[source].append(row) + pending.remove(source) + if not pending: + break + if pending: + raise RuntimeError(f"missing sources near {base_position}: {sorted(pending)}") + if index % 5 == 4: + print(json.dumps({"windows_completed": index + 1}), flush=True) + summary = {} + for source, source_rows in rows.items(): + valid = sum(row["pose_valid_hands"] for row in source_rows) + weighted_15 = sum(row["weighted_15"] for row in source_rows) + weighted_20 = sum(row["weighted_20"] for row in source_rows) + mass = sum(row["weight_mass"] for row in source_rows) + summary[source] = { + "sampled_tiles": len(source_rows), + "pose_valid_hands": valid, + "weighted_15": weighted_15, + "weighted_20": weighted_20, + "weighted_hand_fraction": (weighted_15 + weighted_20) / valid if valid else None, + "mean_weight_per_valid_hand": mass / valid if valid else None, + "tiles_without_hard": sum(row["weighted_15"] + row["weighted_20"] == 0 for row in source_rows), + } + report = {"sampling": "one source tile per 30 evenly spaced windows across the 1.2M-clip training stream", + "summary": summary, "rows": rows} + OUTPUT.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(summary), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_pose_anchor.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_pose_anchor.py new file mode 100644 index 0000000000000000000000000000000000000000..402ccee4915531b3b56de2ca51a6d0484af08ade --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_pose_anchor.py @@ -0,0 +1,122 @@ +"""Check whether the RGB teacher anchor opposes local-pose gradients.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +import torch + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, "/home/wuyifan/u0_normalized6d_20261002") + +from train import CONFIG, STATISTICS, U0Coverage, U0Dataset, base, model_for # noqa: E402 +from normalized_loss import NormalizedLoss, hand_tail_weights, masked_weighted_l1 # noqa: E402 + +OUTPUT = ROOT / "evaluations/pose_anchor_n1_18k.json" +SPREAD_OUTPUT = ROOT / "evaluations/pose_anchor_n1_18k_spread.json" +CHECKPOINT = ROOT / "n1_update_0018000.pt" +POSITIONS = ROOT / "evaluations/pose_gradients_n1_18k.json" +SPREAD_POSITIONS = ROOT / "evaluations/hard_exposure_30_tiles_per_source.json" +GEOMETRY = ("joint3d_camera", "joint3d_root_relative", "vertices_camera") + + +def gradient(value: torch.Tensor, parameter: torch.Tensor) -> torch.Tensor: + result = torch.autograd.grad(value.float(), parameter, retain_graph=True, allow_unused=True)[0] + return torch.zeros_like(parameter).flatten() if result is None else result.float().flatten() + + +def cosine(left: torch.Tensor, right: torch.Tensor) -> float | None: + denominator = torch.linalg.vector_norm(left) * torch.linalg.vector_norm(right) + return float(torch.dot(left, right) / denominator) if bool(denominator > 0) else None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--spread", action="store_true") + args = parser.parse_args() + output = SPREAD_OUTPUT if args.spread else OUTPUT + if output.exists(): + raise FileExistsError(output) + torch.set_num_threads(2) + device = torch.device("cuda") + sample = json.loads((SPREAD_POSITIONS if args.spread else POSITIONS).read_text()) + selected = ({source: [row["position"] for row in source_rows[::3]] + for source, source_rows in sample["rows"].items()} + if args.spread else + {source: [row["sample_position"] for row in source_rows] + for source, source_rows in sample["sources"].items()}) + coverage, dataset = U0Coverage(), U0Dataset() + state = torch.load(CHECKPOINT, map_location="cpu", weights_only=False) + if state["mode"] != "N1" or state["update"] != 18000 or not state["complete_backbone"]: + raise RuntimeError("N1 checkpoint mismatch") + student = model_for("student") + student.load_state_dict(state["model"], strict=True) + student.to(device).eval() + teacher = model_for("teacher").to(device).eval() + criterion = NormalizedLoss(STATISTICS, CONFIG["loss_coefficients"], True).to(device) + parameter = student.rotation_head.weight + rows = {} + for source, positions in selected.items(): + rows[source] = [] + for position in positions: + cpu = base.collate_h2o_clips([dataset[coverage.sample(position)]]) + cpu["tail_weight"] = hand_tail_weights(cpu, True) + batch = base.move_to_device(cpu, device) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + reference = teacher(batch) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = student(batch) + supervised = criterion(prediction, batch, batch["tail_weight"]) + student_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + teacher_relative = reference["joints_camera"] - reference["joints_camera"][..., :1, :] + valid = {key: batch[key].bool() for key in ( + "joint3d_valid", "joint3d_root_relative_valid", "vertices_valid", + )} + norm = criterion + anchored = { + "joint3d_camera": CONFIG["loss_coefficients"]["joint3d_camera"] * masked_weighted_l1( + norm.absolute_xyz(prediction["joints_camera"]), + norm.absolute_xyz(reference["joints_camera"]), + valid["joint3d_valid"][..., None]), + "joint3d_root_relative": CONFIG["loss_coefficients"]["joint3d_root_relative"] * masked_weighted_l1( + norm.relative_xyz(student_relative), norm.relative_xyz(teacher_relative), + valid["joint3d_root_relative_valid"][..., None]), + "vertices_camera": CONFIG["loss_coefficients"]["vertices_camera"] * masked_weighted_l1( + norm.absolute_xyz(prediction["vertices_camera"]), + norm.absolute_xyz(reference["vertices_camera"]), + valid["vertices_valid"][..., None, None]), + } + anchor = CONFIG["rgb_teacher_weight"] * sum(anchored.values()) + geometry = sum(supervised[key] for key in GEOMETRY) + pose = supervised["local_pose"] + g_pose = gradient(pose, parameter) + g_geometry = gradient(geometry, parameter) + g_anchor = gradient(anchor, parameter) + row = { + "position": position, + "tile_id": cpu["filtered_tile_id"][0], + "local_pose_loss": float(pose), + "geometry_loss": float(geometry), + "anchor_loss": float(anchor), + "local_grad_norm": float(torch.linalg.vector_norm(g_pose)), + "geometry_grad_norm": float(torch.linalg.vector_norm(g_geometry)), + "anchor_grad_norm": float(torch.linalg.vector_norm(g_anchor)), + "anchor_to_local_grad_ratio": float(torch.linalg.vector_norm(g_anchor) / + torch.linalg.vector_norm(g_pose).clamp_min(1e-12)), + "anchor_vs_local_cosine": cosine(g_anchor, g_pose), + "anchor_vs_geometry_cosine": cosine(g_anchor, g_geometry), + } + rows[source].append(row) + print(json.dumps({"source": source, **row}), flush=True) + output.write_text(json.dumps({"checkpoint": str(CHECKPOINT), + "sample": ("ten training tiles per source spread across 1.2M stream" + if args.spread else + "same six selected hard tiles as pose_gradients_n1_18k"), + "source_scaling": "not applied", "rows": rows}, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_pose_gradients.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_pose_gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..24a7762b18a4f38bd2e61887dc7ad59ab1a3a0c2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_pose_gradients.py @@ -0,0 +1,132 @@ +"""Read-only fixed-tile audit of N1 hard weights and pose-head gradients.""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +import sys + +import torch + +ROOT = Path(__file__).resolve().parent +EXPERIMENT = Path("/home/wuyifan/u0_normalized6d_20261002") +sys.path.insert(0, str(EXPERIMENT)) + +from train import CONFIG, STATISTICS, U0Coverage, U0Dataset, base, model_for, sha # noqa: E402 +from normalized_loss import NormalizedLoss, hand_tail_weights # noqa: E402 +from reprojection import fixed_mask_reprojection # noqa: E402 + +TERMS = ( + "local_pose", "global_orientation", "joint3d_root_relative", + "joint3d_camera", "vertices_camera", "reprojection", +) +OUTPUT = ROOT / "evaluations/pose_gradients_n1_18k.json" +CHECKPOINT = ROOT / "n1_update_0018000.pt" + + +def grad(term: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + value = torch.autograd.grad(term.float(), weight, retain_graph=True, allow_unused=True)[0] + return torch.zeros_like(weight, dtype=torch.float32).flatten() if value is None else value.float().flatten() + + +def cosine(left: torch.Tensor, right: torch.Tensor) -> float | None: + denom = torch.linalg.vector_norm(left) * torch.linalg.vector_norm(right) + return float(torch.dot(left, right) / denom) if bool(denom > 0) else None + + +def main() -> None: + if OUTPUT.exists(): + raise FileExistsError(OUTPUT) + torch.set_num_threads(2) + device = torch.device("cuda") + coverage, dataset = U0Coverage(), U0Dataset() + selected = {source: [] for source in ("H2O", "ARCTIC", "HOT3D")} + for position in range(240): + spec = coverage.sample(position) + source = spec["source"] + if len(selected[source]) >= 2: + continue + cpu = base.collate_h2o_clips([dataset[spec]]) + pose_valid = cpu["mano_pose_valid"].bool() & cpu["frame_valid"].bool()[..., None] + weights = hand_tail_weights(cpu, True) + if bool(((weights > 1) & pose_valid).any()): + selected[source].append((position, cpu, weights)) + if all(len(chunks) >= 2 for chunks in selected.values()): + break + if any(len(chunks) < 2 for chunks in selected.values()): + raise RuntimeError("could not find two hard, pose-valid tiles per source") + + state = torch.load(CHECKPOINT, map_location="cpu", weights_only=False) + if (state["experiment"] != CONFIG["experiment"] or state["mode"] != "N1" + or state["update"] != 18000 or state["smoke"] + or state["parent_sha256"] != CONFIG["start_checkpoint_sha256"] + or not state["complete_backbone"]): + raise RuntimeError("N1 checkpoint lineage mismatch") + model = model_for("student") + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + n0 = NormalizedLoss(STATISTICS, CONFIG["loss_coefficients"], False).to(device) + n1 = NormalizedLoss(STATISTICS, CONFIG["loss_coefficients"], True).to(device) + parameter = model.rotation_head.weight + report = { + "checkpoint": str(CHECKPOINT), "sha256": sha(CHECKPOINT), "update": 18000, + "role": "diagnostic_two_selected_hard_train_tiles_per_source_not_global_gradient", + "selection": "first two pose-valid tiles per source with N1 weight >1 among positions 0..239", + "sources": {}, + } + for source, chunks in selected.items(): + report["sources"][source] = [] + for position, cpu, cpu_weight in chunks: + batch = base.move_to_device(cpu, device) + weight = cpu_weight.to(device) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + old = n0(prediction, batch, weight) + new = n1(prediction, batch, weight) + reprojection, _, _ = fixed_mask_reprojection( + prediction, batch, CONFIG["reprojection_depth_floor_m"], + CONFIG["reprojection_depth_penalty_per_m"], + ) + new["reprojection"] = reprojection * CONFIG["loss_coefficients"]["reprojection"] + gradients = {term: grad(new[term], parameter) for term in TERMS} + old_local = grad(old["local_pose"], parameter) + old_relative = grad(old["joint3d_root_relative"], parameter) + pose_valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + active = weight[pose_valid] + local = gradients["local_pose"] + row = { + "sample_position": position, + "tile_id": cpu["filtered_tile_id"][0], + "valid_pose_hands": int(pose_valid.sum()), + "hard_weighted_hands": int((active > 1).sum()), + "maximum_weight": float(active.max()) if active.numel() else None, + "mean_weight_valid": float(active.mean()) if active.numel() else None, + "loss_value": {term: float(new[term]) for term in TERMS}, + "rotation_head_grad_norm": { + term: float(torch.linalg.vector_norm(value)) for term, value in gradients.items() + }, + "cosine_with_local_pose": {term: cosine(local, value) + for term, value in gradients.items() if term != "local_pose"}, + "n1_vs_n0_local_grad_norm_ratio": float( + torch.linalg.vector_norm(local) / torch.linalg.vector_norm(old_local).clamp_min(1e-12) + ), + "n1_vs_n0_local_grad_cosine": cosine(local, old_local), + "n1_vs_n0_relative_grad_norm_ratio": float( + torch.linalg.vector_norm(gradients["joint3d_root_relative"]) + / torch.linalg.vector_norm(old_relative).clamp_min(1e-12) + ), + "n1_vs_n0_relative_grad_cosine": cosine(gradients["joint3d_root_relative"], old_relative), + } + if not all(math.isfinite(v) for v in row["rotation_head_grad_norm"].values()): + raise RuntimeError("nonfinite gradient norm") + report["sources"][source].append(row) + print(json.dumps({"source": source, "position": position, + "hard_hands": row["hard_weighted_hands"], + "local_grad": row["rotation_head_grad_norm"]["local_pose"]}), flush=True) + OUTPUT.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps({"output": str(OUTPUT)}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_pose_precision.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_pose_precision.py new file mode 100644 index 0000000000000000000000000000000000000000..facce8db9c8c42721d04dc48dd78a10c70b1e80c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_pose_precision.py @@ -0,0 +1,92 @@ +"""Read-only BF16 rotation contract check on three real train tiles.""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys + +import torch + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, "/home/wuyifan/u0_normalized6d_20261002") + +from train import STATISTICS, U0Coverage, U0Dataset, base, model_for # noqa: E402 +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix # noqa: E402 + +OUTPUT = ROOT / "evaluations/pose_precision_n1_18k.json" +CHECKPOINT = ROOT / "n1_update_0018000.pt" + + +def summary(value: torch.Tensor) -> dict[str, float]: + finite = value.detach().float().flatten() + finite = finite[torch.isfinite(finite)] + return { + "count": int(finite.numel()), + "mean": float(finite.mean()), + "p50": float(torch.quantile(finite, 0.50)), + "p95": float(torch.quantile(finite, 0.95)), + "max": float(finite.max()), + } + + +def main() -> None: + if OUTPUT.exists(): + raise FileExistsError(OUTPUT) + torch.set_num_threads(2) + device = torch.device("cuda") + coverage, dataset = U0Coverage(), U0Dataset() + positions: dict[str, int] = {} + for position in range(50): + source = coverage.sample(position)["source"] + positions.setdefault(source, position) + if len(positions) == 3: + break + state = torch.load(CHECKPOINT, map_location="cpu", weights_only=False) + if state["update"] != 18000 or state["mode"] != "N1" or not state["complete_backbone"]: + raise RuntimeError("unexpected checkpoint") + model = model_for("student") + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + eye = torch.eye(3, device=device) + scale = torch.tensor(STATISTICS["pose_scale"], device=device) + rows = {} + for source, position in positions.items(): + cpu = base.collate_h2o_clips([dataset[coverage.sample(position)]]) + batch = base.move_to_device(cpu, device) + valid = (batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None]) + axis = torch.nan_to_num(batch["mano_pose"].float()).reshape(*valid.shape, 16, 3) + with torch.no_grad(): + exact = axis_angle_to_matrix(axis) + with torch.autocast("cuda", dtype=torch.bfloat16): + autocast_gt = axis_angle_to_matrix(axis) + prediction = model(batch) + raw = prediction["mano_rotations_6d"].float() + predicted = prediction["mano_rotation_matrices"].float() + precise_predicted = rotation_6d_to_matrix(raw) + raw_first = torch.linalg.vector_norm(raw[..., :3], dim=-1) + raw_second_orthogonal = raw[..., 3:] - ( + raw[..., 3:] * raw[..., :3] / raw_first.clamp_min(1e-8)[..., None] + ).sum(dim=-1, keepdim=True) * raw[..., :3] / raw_first.clamp_min(1e-8)[..., None] + raw_second = torch.linalg.vector_norm(raw_second_orthogonal, dim=-1) + v = valid[..., None].expand_as(raw_first) + component_difference = ((autocast_gt[..., :2, :] - exact[..., :2, :]) + .reshape(*valid.shape, 16, 6).abs() + / scale[None, None]).mean(dim=-1) + rows[source] = { + "position": position, + "valid_pose_rotations": int(v.sum()), + "gt_orthogonality_fp32": summary(torch.linalg.matrix_norm(exact @ exact.transpose(-1, -2) - eye)[v]), + "gt_orthogonality_autocast": summary(torch.linalg.matrix_norm(autocast_gt @ autocast_gt.transpose(-1, -2) - eye)[v]), + "gt_autocast_vs_fp32_normalized_6d_l1": summary(component_difference[v]), + "pred_raw_first_norm": summary(raw_first[v]), + "pred_raw_orthogonal_second_norm": summary(raw_second[v]), + "pred_matrix_autocast_orthogonality": summary(torch.linalg.matrix_norm(predicted @ predicted.transpose(-1, -2) - eye)[v]), + "pred_matrix_autocast_vs_fp32": summary(torch.linalg.matrix_norm(predicted - precise_predicted)[v]), + } + print(json.dumps({"source": source, **rows[source]}), flush=True) + OUTPUT.write_text(json.dumps({"checkpoint": str(CHECKPOINT), "rows": rows}, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_training_gt_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_training_gt_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..cce8d7e841ad40d49b5303360133b8f7e4c591e6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/audit_training_gt_contract.py @@ -0,0 +1,91 @@ +"""Read-only camera-space and rotation checks on registered training tiles.""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys + +import torch + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, "/home/wuyifan/u0_normalized6d_20261002") + +from train import U0Coverage, U0Dataset, base # noqa: E402 +from foundation_hand.geometry.camera import project_points # noqa: E402 +from foundation_hand.geometry.rotations import axis_angle_to_matrix # noqa: E402 + +POSITIONS = ROOT / "evaluations/hard_exposure_30_tiles_per_source.json" +OUTPUT = ROOT / "evaluations/training_gt_contract_10_tiles_per_source.json" + + +def distribution(values: list[torch.Tensor]) -> dict: + data = torch.cat([item.flatten() for item in values]).float() + return {"count": int(data.numel()), "mean": float(data.mean()), + "p05": float(torch.quantile(data, 0.05)), + "p95": float(torch.quantile(data, 0.95)), + "min": float(data.min()), "max": float(data.max())} + + +def main() -> None: + if OUTPUT.exists(): + raise FileExistsError(OUTPUT) + torch.set_num_threads(2) + positions = json.loads(POSITIONS.read_text())["rows"] + coverage, dataset = U0Coverage(), U0Dataset() + report = {"sample": "ten evenly spread registered training tiles per source", + "sources": {}} + eye = torch.eye(3) + for source, source_rows in positions.items(): + items = {"z_m": [], "wrist_vs_root_mm": [], "rotation_orthogonality": [], + "rotation_det_error": [], "projected_2d_error_px": []} + active = {"hands_pose": 0, "joints_3d": 0, "joints_2d": 0, "nonpositive_gt_z": 0} + tile_ids = [] + for row in source_rows[::3]: + spec = coverage.sample(row["position"]) + if spec["source"] != source: + raise RuntimeError("coverage source changed") + batch = base.collate_h2o_clips([dataset[spec]]) + tile_ids.append(batch["filtered_tile_id"][0]) + frame = batch["frame_valid"].bool() + pose_valid = batch["mano_pose_valid"].bool() & frame[..., None] + joint_valid = batch["joint3d_valid"].bool() & frame[..., None, None] + translation_valid = batch["translation_valid"].bool() & frame[..., None] + joint2d_valid = batch["joint2d_valid"].bool() & joint_valid + xyz = batch["joint3d_camera"].float() + z = xyz[..., 2][joint_valid] + items["z_m"].append(z) + active["joints_3d"] += int(joint_valid.sum()) + active["nonpositive_gt_z"] += int((z <= 0).sum()) + wrist = torch.linalg.vector_norm( + xyz[..., 0, :] - batch["wrist_root_translation"].float(), dim=-1, + )[translation_valid] * 1000 + items["wrist_vs_root_mm"].append(wrist) + rotation = axis_angle_to_matrix(torch.nan_to_num(batch["mano_pose"].float()) + .reshape(*pose_valid.shape, 16, 3)) + active["hands_pose"] += int(pose_valid.sum()) + items["rotation_orthogonality"].append( + torch.linalg.matrix_norm(rotation @ rotation.transpose(-1, -2) - eye)[pose_valid[..., None].expand_as(rotation[..., 0, 0])] + ) + items["rotation_det_error"].append( + (torch.linalg.det(rotation) - 1).abs()[pose_valid[..., None].expand_as(rotation[..., 0, 0])] + ) + projected, positive = project_points(xyz, batch["K"].float()[:, :, None, None]) + mask = joint2d_valid & positive & torch.isfinite(batch["joint2d"]).all(-1) + residual = torch.linalg.vector_norm(projected - batch["joint2d"].float(), dim=-1)[mask] + if residual.numel(): + items["projected_2d_error_px"].append(residual) + active["joints_2d"] += int(mask.sum()) + report["sources"][source] = { + "tile_count": len(tile_ids), "tile_ids": tile_ids, + "valid_counts": active, + "statistics": {key: distribution(values) if values else None + for key, values in items.items()}, + } + print(json.dumps({"source": source, "valid_counts": active, + "statistics": report["sources"][source]["statistics"]}), flush=True) + OUTPUT.write_text(json.dumps(report, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/evaluate_4k_6k.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/evaluate_4k_6k.py new file mode 100644 index 0000000000000000000000000000000000000000..acc87134d9fdbab817270723cfccd5a38aac59ab --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/evaluate_4k_6k.py @@ -0,0 +1,39 @@ +"""Run matched N0/N1 4K and 6K development evaluations.""" + +from __future__ import annotations + +from pathlib import Path +import subprocess +import sys + + +ROOT = Path(__file__).resolve().parent +CHECKPOINTS = { + "N0": ROOT.parent / "u0_normalized6d_20261002/runs/N0_formal", + "N1": ROOT, +} + + +def main() -> None: + for mode in ("N0", "N1"): + for update in (4000, 6000): + checkpoint = (CHECKPOINTS[mode] / f"update_{update:07d}.pt" if mode == "N0" + else CHECKPOINTS[mode] / f"n1_update_{update:07d}.pt") + if not checkpoint.is_file(): + raise FileNotFoundError(checkpoint) + for source in ("H2O", "ARCTIC", "HOT3D"): + output = ROOT / "evaluations" / f"{mode.lower()}_{update:06d}_{source.lower()}_development.json" + if output.exists(): + print(f"Existing: {output}", flush=True) + continue + print(f"Evaluating {mode} {update} {source}", flush=True) + subprocess.run([ + sys.executable, str(ROOT / "evaluate_n0.py"), + "--checkpoint", str(checkpoint), + "--source", source, + "--output", str(output), + ], check=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/evaluate_n0.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/evaluate_n0.py new file mode 100644 index 0000000000000000000000000000000000000000..01c79ebd2e723952791975cdb097dbbcbe5aab1c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/evaluate_n0.py @@ -0,0 +1,150 @@ +"""Evaluate an N0/N1 checkpoint against its U0 parent on frozen native-GT panels.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +import torch + +EXPERIMENT = Path("/home/wuyifan/u0_normalized6d_20261002") +sys.path.insert(0, str(EXPERIMENT)) + +from train import CONFIG, STATISTICS, a7, base, experiment_hashes, model_for, sha # noqa: E402 +from clean_eval import FOUR_METRICS, apply_mode, dataset_for # noqa: E402 +from evaluate import finite, paired # noqa: E402 +from foundation_hand.data.arctic_dataset import ARCTICClipDataset # noqa: E402 +from foundation_hand.geometry.rotations import axis_angle_to_matrix # noqa: E402 +from normalized_loss import canonical_rotation_6d # noqa: E402 +from scripts.evaluate_phase7_external import aggregate, make_row # noqa: E402 +from targets import NativePanel # noqa: E402 + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--limit", type=int) + args = parser.parse_args() + if (args.output.exists() or tuple(CONFIG["metric_keys"]) != tuple(FOUR_METRICS) + or (args.limit is not None and not args.smoke)): + raise RuntimeError("existing result or metric contract mismatch") + + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if (state["experiment"] != CONFIG["experiment"] + or state["code_sha256"] != experiment_hashes() + or state["parent_sha256"] != CONFIG["start_checkpoint_sha256"] + or state["metric_keys"] != CONFIG["metric_keys"] + or state["mode"] not in ("N0", "N1") or state["smoke"] != args.smoke + or not state["complete_backbone"]): + raise RuntimeError("N0/N1 checkpoint composition mismatch") + candidate_label = f'{state["mode"]}_RGB' + parent_path = Path(CONFIG["start_checkpoint"]) + if sha(parent_path) != CONFIG["start_checkpoint_sha256"]: + raise RuntimeError("U0 parent checkpoint changed") + parent_state = torch.load(parent_path, map_location="cpu", weights_only=False) + if not parent_state["complete_backbone"] or parent_state["update"] != 20004: + raise RuntimeError("U0 parent checkpoint lineage mismatch") + + candidate = model_for("student") + candidate.load_state_dict(state["model"], strict=True) + candidate.to("cuda").eval() + parent = model_for("student") + parent.load_state_dict(parent_state["model"], strict=True) + parent.to("cuda").eval() + + panel_root = a7.BASE_ROOT / "eval/frozen_panels_sync_v2" + panels = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_development_t8.jsonl" + registered = panels["sources"][args.source]["development"] + if sha(manifest) != registered["manifest_sha256"] or panels["sources"][args.source]["train_overlap"]: + raise RuntimeError("development panel isolation/hash mismatch") + rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), hand_valid_policy="visible_mesh") + if args.source == "ARCTIC" else dataset_for(args.source, manifest)) + dataset = NativePanel(args.source, native, rows) + limit = len(dataset) if args.limit is None else min(args.limit, len(dataset)) + output_rows = {"U0_parent_RGB": [], candidate_label: []} + rotation_values = {key: {name: [] for name in ("root_angle_deg", "local_angle_deg", + "raw_first_norm", "raw_second_orth_norm", + "normalized_6d_l1")} + for key in output_rows} + pose_scale = torch.tensor(STATISTICS["pose_scale"], device="cuda")[None, None] + with torch.inference_mode(): + for index in range(limit): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, "rgb") + batch = base.move_to_device(batch, torch.device("cuda")) + with torch.autocast("cuda", dtype=torch.bfloat16): + predictions = {"U0_parent_RGB": parent(batch), candidate_label: candidate(batch)} + pose_valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + target_rotation = axis_angle_to_matrix( + torch.nan_to_num(batch["mano_pose"].float()).reshape(*pose_valid.shape, 16, 3) + ) + target_6d = target_rotation[..., :2, :].reshape(*pose_valid.shape, 16, 6) + for label, prediction in predictions.items(): + if not bool(torch.isfinite(prediction["joints_camera"]).all()): + raise RuntimeError("nonfinite benchmark prediction") + raw = prediction["mano_rotations_6d"].float() + first = torch.nn.functional.normalize(raw[..., :3], dim=-1) + second_orth = raw[..., 3:] - (first * raw[..., 3:]).sum(-1, keepdim=True) * first + relative_rotation = prediction["mano_rotation_matrices"].float() @ target_rotation.transpose(-1, -2) + trace = relative_rotation.diagonal(dim1=-2, dim2=-1).sum(-1) + angle = torch.rad2deg(torch.acos(((trace - 1) / 2).clamp(-1, 1))) + normalized_l1 = ((canonical_rotation_6d(raw) - target_6d) / pose_scale).abs().mean(-1) + values = rotation_values[label] + for name, selected in ( + ("root_angle_deg", angle[..., 0][pose_valid]), + ("local_angle_deg", angle[..., 1:][pose_valid[..., None].expand_as(angle[..., 1:])]), + ("raw_first_norm", torch.linalg.vector_norm(raw[..., :3], dim=-1)[pose_valid[..., None].expand_as(angle)]), + ("raw_second_orth_norm", torch.linalg.vector_norm(second_orth, dim=-1)[pose_valid[..., None].expand_as(angle)]), + ("normalized_6d_l1", normalized_l1[pose_valid[..., None].expand_as(angle)]), + ): + values[name].append(selected.cpu()) + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + output_rows[label].append(make_row(prediction, batch, 0, frame, side)) + if (index + 1) % 32 == 0: + print(json.dumps({"source": args.source, "done": index + 1, "total": limit}), flush=True) + + summaries = {key: aggregate(value) for key, value in output_rows.items()} + rotation_report = {} + for label, values in rotation_values.items(): + merged = {name: torch.cat(items) for name, items in values.items()} + rotation_report[label] = { + "root_angle_deg_mean": float(merged["root_angle_deg"].mean()), + "local_angle_deg_mean": float(merged["local_angle_deg"].mean()), + "normalized_6d_l1_mean": float(merged["normalized_6d_l1"].mean()), + "raw_first_norm_p01": float(torch.quantile(merged["raw_first_norm"], .01)), + "raw_second_orth_norm_p01": float(torch.quantile(merged["raw_second_orth_norm"], .01)), + "near_singular_fraction": float(((merged["raw_first_norm"] < 1e-4) + | (merged["raw_second_orth_norm"] < 1e-4)).float().mean()), + } + report = {"source": args.source, "role": "development", "input_mode": "rgb", "clips": limit, + "smoke": args.smoke, + "update": state["update"], "checkpoint_sha256": sha(args.checkpoint), + "parent_checkpoint_sha256": sha(parent_path), "native_GT_not_refitted": True, + "presence_filter_for_metrics": False, "metric_keys": CONFIG["metric_keys"], + "metric_units": ["mm", "mm", "mm", "px"], "panel_sha256": sha(manifest), + "rotation_diagnostic": rotation_report, + "paired": paired(output_rows["U0_parent_RGB"], output_rows[candidate_label]), + "summary": {key: {metric: value[metric] for metric in (*CONFIG["metric_keys"], "pa_mpjpe_mm")} + for key, value in summaries.items()}} + a7.dump(args.output, finite(report)) + a7.dump(args.output.with_suffix(".rows.json"), finite(output_rows)) + print(json.dumps({"source": args.source, "update": state["update"], + **{label: {metric: report["summary"][label][metric]["mean"] + for metric in CONFIG["metric_keys"]} + for label in output_rows}}, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/oracle_pose_decomposition.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/oracle_pose_decomposition.py new file mode 100644 index 0000000000000000000000000000000000000000..caa2623c83838d6e627eff589533539d72a120d6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/oracle_pose_decomposition.py @@ -0,0 +1,127 @@ +"""Diagnostic MANO-factor oracles on a frozen native-GT RGB panel.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + +import torch + +from pose_hard_case_monitor import ( # noqa: E402 + CONFIG, EXPERIMENT, FOUR, NativePanel, a7, apply_mode, axis_angle_to_matrix, + base, dataset_for, finger_angles, finite, load_model, make_row, paired, sha, + ARCTICClipDataset, +) + +ROOT = Path(__file__).resolve().parent +VARIANTS = ("direct", "gt_local", "gt_root", "gt_translation", "gt_all_rot_translation") + + +def summarize(rows: list[dict], key: str) -> dict: + values = [row[key] for row in rows if row.get(key) is not None and math.isfinite(row[key])] + return {"mean": sum(values) / len(values) if values else None, "count": len(values)} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source", required=True, choices=("H2O", "ARCTIC", "HOT3D")) + parser.add_argument("--mode", default="N1", choices=("N0", "N1")) + parser.add_argument("--step", default=18000, type=int) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + if args.output.exists() or args.output.with_suffix(".rows.json").exists(): + raise FileExistsError(args.output) + if args.step < 2000 or args.step % 2000: + raise ValueError("checkpoint must be a completed 2K step") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device("cuda") + checkpoint = (EXPERIMENT / f"runs/N0_formal/update_{args.step:07d}.pt" + if args.mode == "N0" else ROOT / f"n1_update_{args.step:07d}.pt") + model = load_model(checkpoint, args.mode, args.step, device) + panel_root = a7.BASE_ROOT / "eval/frozen_panels_sync_v2" + panels = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_development_t8.jsonl" + if (sha(manifest) != panels["sources"][args.source]["development"]["manifest_sha256"] + or panels["sources"][args.source]["train_overlap"]): + raise RuntimeError("development panel isolation/hash mismatch") + manifest_rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), + hand_valid_policy="visible_mesh") + if args.source == "ARCTIC" else dataset_for(args.source, manifest)) + dataset = NativePanel(args.source, native, manifest_rows) + rows = {variant: [] for variant in VARIANTS} + with torch.inference_mode(): + for index in range(len(dataset)): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, "rgb") + batch = base.move_to_device(batch, device) + pose_valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + joint_valid = batch["joint3d_root_relative_valid"].bool().all(dim=-1) + gt_angles, gt_geometry_valid = finger_angles(batch["joint3d_camera"].float()) + complete = pose_valid & joint_valid & gt_geometry_valid + gt_hard = ((gt_angles >= 45).sum(dim=(-1, -2)) >= 2) | (gt_angles >= 60).any(dim=(-1, -2)) + gt_rot = axis_angle_to_matrix(torch.nan_to_num(batch["mano_pose"].float()) + .reshape(*pose_valid.shape, 16, 3)) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + pred_rot = prediction["mano_rotation_matrices"].float() + pred_trans = prediction["wrist_root_translation"].float() + predicted = {"direct": prediction} + for variant in VARIANTS[1:]: + rotation = pred_rot.clone() + translation = pred_trans.clone() + if variant in ("gt_local", "gt_all_rot_translation"): + rotation[..., 1:, :, :] = gt_rot[..., 1:, :, :] + if variant in ("gt_root", "gt_all_rot_translation"): + rotation[..., :1, :, :] = gt_rot[..., :1, :, :] + if variant in ("gt_translation", "gt_all_rot_translation"): + translation = torch.where(pose_valid[..., None], + batch["wrist_root_translation"].float(), translation) + vertices, joints = model.mano_layer(rotation, prediction["mano_shape"].float(), translation) + predicted[variant] = {**prediction, "mano_rotation_matrices": rotation, + "wrist_root_translation": translation, + "vertices_camera": vertices, "joints_camera": joints} + for frame in range(batch["frame_valid"].shape[1]): + if not bool(batch["frame_valid"][0, frame]): + continue + for side in range(2): + if not bool(complete[0, frame, side]): + continue + hard = bool(gt_hard[0, frame, side]) + for variant in VARIANTS: + row = make_row(predicted[variant], batch, 0, frame, side) + row["gt_hard"] = hard + rows[variant].append(row) + if (index + 1) % 32 == 0: + print(json.dumps({"source": args.source, "done": index + 1, + "total": len(dataset)}), flush=True) + report = {"source": args.source, "role": "development_oracle_diagnostic", + "checkpoint": str(checkpoint), "checkpoint_sha256": sha(checkpoint), + "panel_sha256": sha(manifest), "gt": "source_native_not_refitted", + "oracle_contract": "replace selected MANO factors by native GT, retaining predicted shape; not a deployable score", + "clips": len(dataset), "groups": {}} + for group in ("all", "normal", "hard"): + selected = {variant: [row for row in values if group == "all" or row["gt_hard"] == (group == "hard")] + for variant, values in rows.items()} + report["groups"][group] = { + "hands": len(selected["direct"]), + "variants": {variant: { + "means": {key: summarize(values, key) for key in FOUR}, + "paired_to_direct": ({key: paired(selected["direct"], values, key) + for key in FOUR} if variant != "direct" else None), + } for variant, values in selected.items()}, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + a7.dump(args.output, finite(report)) + a7.dump(args.output.with_suffix(".rows.json"), finite(rows)) + print(json.dumps({"source": args.source, + "hands": {group: values["hands"] for group, values in report["groups"].items()}, + "output": str(args.output)}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/pose_hard_case_monitor.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/pose_hard_case_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..fde96762c25b0c03774fec26de8ab7d732d6a87b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/pose_hard_case_monitor.py @@ -0,0 +1,276 @@ +"""Paired RGB pose diagnostics on a frozen native-GT development source.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +import math +from pathlib import Path +import sys + +import numpy as np +import torch + +EXPERIMENT = Path("/home/wuyifan/u0_normalized6d_20261002") +sys.path.insert(0, str(EXPERIMENT)) + +from train import CONFIG, a7, base, experiment_hashes, model_for, sha # noqa: E402 +from clean_eval import apply_mode, dataset_for # noqa: E402 +from evaluate import finite # noqa: E402 +from foundation_hand.data.arctic_dataset import ARCTICClipDataset # noqa: E402 +from foundation_hand.geometry.rotations import axis_angle_to_matrix # noqa: E402 +from normalized_loss import canonical_rotation_6d # noqa: E402 +from rotation_variance import JOINTS, Moments # noqa: E402 +from scripts.evaluate_phase7_external import make_row # noqa: E402 +from targets import NativePanel # noqa: E402 + +FOUR = tuple(CONFIG["metric_keys"]) +DIAGNOSTICS = ( + "local_pose_angle_deg", "root_relative_fingertip_mm", + "distal_angle_bias_deg", "distal_angle_mae_deg", "gt60_angle_bias_deg", +) +ALL_METRICS = FOUR + DIAGNOSTICS + + +def finger_angles(joints: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + fingers = joints[..., 1:, :].reshape(*joints.shape[:-2], 5, 4, 3) + bones = fingers[..., 1:, :] - fingers[..., :-1, :] + lengths = torch.linalg.vector_norm(bones, dim=-1) + unit = bones / lengths.clamp_min(1e-8)[..., None] + cosine = (unit[..., :-1, :] * unit[..., 1:, :]).sum(-1).clamp(-1, 1) + angles = torch.rad2deg(torch.acos(cosine))[..., 1:, :] + complete = (lengths[..., 1:, :] > 1e-6).all(dim=(-1, -2)) + complete &= torch.isfinite(angles).all(dim=(-1, -2)) + return angles, complete + + +def load_model(path: Path, mode: str | None, step: int | None, device: torch.device): + state = torch.load(path, map_location="cpu", weights_only=False) + if not state["complete_backbone"]: + raise RuntimeError(f"incomplete backbone: {path}") + if mode is None: + if state["update"] != 20004 or sha(path) != CONFIG["start_checkpoint_sha256"]: + raise RuntimeError("U0 parent checkpoint mismatch") + elif (state["experiment"] != CONFIG["experiment"] or state["mode"] != mode + or state["update"] != step or state["smoke"] + or state["parent_sha256"] != CONFIG["start_checkpoint_sha256"] + or state["code_sha256"] != experiment_hashes()): + raise RuntimeError(f"candidate checkpoint mismatch: {path}") + model = model_for("student") + model.load_state_dict(state["model"], strict=True) + return model.to(device).eval() + + +def mean(rows: list[dict], key: str) -> dict: + values = [row[key] for row in rows if row.get(key) is not None and math.isfinite(row[key])] + return {"mean": float(np.mean(values)) if values else None, "count": len(values)} + + +def paired(parent: list[dict], child: list[dict], key: str) -> dict: + if len(parent) != len(child): + raise RuntimeError("different GT-defined hand counts") + by_recording = defaultdict(list) + for left, right in zip(parent, child): + if any(left[k] != right[k] for k in ("physical_recording_id", "frame_id", "side")): + raise RuntimeError("paired hand identity changed") + old, new = left.get(key), right.get(key) + if old is None or new is None or not math.isfinite(old) or not math.isfinite(new): + continue + by_recording[left["physical_recording_id"]].append(new - old) + if not by_recording: + return {"delta": None, "recording_bootstrap_95ci": None, "count": 0, "recordings": 0} + sums = np.asarray([sum(values) for values in by_recording.values()]) + counts = np.asarray([len(values) for values in by_recording.values()]) + rng = np.random.default_rng(CONFIG["seed"]) + draws = rng.integers(0, len(sums), size=(2000, len(sums))) + boot = sums[draws].sum(axis=1) / counts[draws].sum(axis=1) + return {"delta": float(sums.sum() / counts.sum()), + "recording_bootstrap_95ci": np.quantile(boot, [0.025, 0.975]).tolist(), + "count": int(counts.sum()), "recordings": len(by_recording)} + + +def variance_report(moments: dict[str, Moments]) -> dict: + gt = moments["GT"].variance() + result = {} + for name, value in moments.items(): + if name == "GT": + continue + pred = value.variance() + eligible = (moments["GT"].count > 1) & (gt > 1e-8) + ratio = pred[eligible] / gt[eligible] + result[name] = { + "pred_gt_variance_ratio_macro": float(ratio.mean()) if ratio.numel() else None, + "mean_abs_log_variance_ratio": float(ratio.clamp_min(1e-8).log().abs().mean()) + if ratio.numel() else None, + "per_joint_side": [ + {"joint": joint, "name": JOINTS[joint], "side": side_name, + "count": int(moments["GT"].count[side, joint]), + "gt_variance_6d": float(gt[side, joint]), + "pred_variance_6d": float(pred[side, joint]), + "pred_gt_ratio": float(pred[side, joint] / gt[side, joint]) + if bool(eligible[side, joint]) else None} + for side, side_name in enumerate(("left", "right")) + for joint in range(16) + ], + } + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source", required=True, choices=("H2O", "ARCTIC", "HOT3D")) + parser.add_argument("--steps", type=int, nargs="+", required=True) + parser.add_argument("--modes", nargs="+", choices=("N0", "N1"), default=("N0", "N1")) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists() or args.output.with_suffix(".rows.json").exists(): + raise FileExistsError(args.output) + steps = sorted(set(args.steps)) + if any(step < 2000 or step % 2000 for step in steps): + raise ValueError("only completed 2K checkpoint steps are supported") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device("cuda") + paths = {"U0_parent": Path(CONFIG["start_checkpoint"])} + for mode in dict.fromkeys(args.modes): + for step in steps: + paths[f"{mode}_{step // 1000}K"] = ( + EXPERIMENT / f"runs/N0_formal/update_{step:07d}.pt" if mode == "N0" + else Path(__file__).resolve().parent / f"n1_update_{step:07d}.pt" + ) + models = {} + for name, path in paths.items(): + if not path.is_file(): + raise FileNotFoundError(path) + mode = None if name == "U0_parent" else name[:2] + step = None if mode is None else int(name[3:-1]) * 1000 + models[name] = load_model(path, mode, step, device) + + panel_root = a7.BASE_ROOT / "eval/frozen_panels_sync_v2" + panels = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_development_t8.jsonl" + registered = panels["sources"][args.source]["development"] + if sha(manifest) != registered["manifest_sha256"] or panels["sources"][args.source]["train_overlap"]: + raise RuntimeError("development panel isolation/hash mismatch") + manifest_rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), + hand_valid_policy="visible_mesh") + if args.source == "ARCTIC" else dataset_for(args.source, manifest)) + dataset = NativePanel(args.source, native, manifest_rows) + rows = {name: [] for name in models} + moments = {group: {"GT": Moments(), **{name: Moments() for name in models}} + for group in ("all", "normal", "hard")} + + with torch.inference_mode(): + for index in range(len(dataset)): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, "rgb") + batch = base.move_to_device(batch, device) + pose_valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + joint_valid = batch["joint3d_root_relative_valid"].bool().all(dim=-1) + gt_angles, gt_geometry_valid = finger_angles(batch["joint3d_camera"].float()) + complete = pose_valid & joint_valid & gt_geometry_valid + gt_hard = ((gt_angles >= 45).sum(dim=(-1, -2)) >= 2) | (gt_angles >= 60).any(dim=(-1, -2)) + target = axis_angle_to_matrix(torch.nan_to_num(batch["mano_pose"].float()) + .reshape(*pose_valid.shape, 16, 3)) + target6 = target[..., :2, :].reshape(*pose_valid.shape, 16, 6) + for group, selected in (("all", complete), ("normal", complete & ~gt_hard), + ("hard", complete & gt_hard)): + moments[group]["GT"].add(target6, selected) + + for name, model in models.items(): + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + if not torch.isfinite(prediction["joints_camera"]).all(): + raise RuntimeError(f"nonfinite joints: {name}, clip {index}") + pred6 = canonical_rotation_6d(prediction["mano_rotations_6d"]) + for group, selected in (("all", complete), ("normal", complete & ~gt_hard), + ("hard", complete & gt_hard)): + moments[group][name].add(pred6, selected) + pred_angles, _ = finger_angles(prediction["joints_camera"].float()) + relative = prediction["mano_rotation_matrices"].float() @ target.transpose(-1, -2) + trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1) + pose_error = torch.rad2deg(torch.acos(((trace - 1) / 2).clamp(-1, 1))) + pred_relative = prediction["joints_camera"].float() - prediction["joints_camera"].float()[..., :1, :] + gt_relative = batch["joint3d_camera"].float() - batch["joint3d_camera"].float()[..., :1, :] + tip_error = torch.linalg.vector_norm( + pred_relative[..., [4, 8, 12, 16, 20], :] + - gt_relative[..., [4, 8, 12, 16, 20], :], dim=-1, + ).mean(-1) * 1000 + for frame in range(batch["frame_valid"].shape[1]): + if not bool(batch["frame_valid"][0, frame]): + continue + for side in range(2): + if not bool(complete[0, frame, side]): + continue + row = make_row(prediction, batch, 0, frame, side) + gt = gt_angles[0, frame, side] + pred = pred_angles[0, frame, side] + difference = pred - gt + high = gt >= 60 + local = pose_error[0, frame, side, 1:] + row.update({ + "gt_hard": bool(gt_hard[0, frame, side]), + "gt_any60": bool(high.any()), + "gt_two45": bool((gt >= 45).sum() >= 2), + "gt_max_distal_angle_deg": float(gt.max()), + "gt_mean_distal_angle_deg": float(gt.mean()), + "pred_mean_distal_angle_deg": float(pred.mean()), + "distal_angle_bias_deg": float(difference.mean()), + "distal_angle_mae_deg": float(difference.abs().mean()), + "gt60_angle_bias_deg": float(difference[high].mean()) if bool(high.any()) else None, + "local_pose_angle_deg": float(local.mean()), + "local_pose_per_joint_deg": local.tolist(), + "root_relative_fingertip_mm": float(tip_error[0, frame, side]), + }) + rows[name].append(row) + if (index + 1) % 32 == 0: + print(json.dumps({"source": args.source, "done": index + 1, + "total": len(dataset)}), flush=True) + + report = { + "source": args.source, "role": "development", "input_mode": "rgb", + "gt": "source_native_not_refitted", "clips": len(dataset), + "panel_sha256": sha(manifest), "parent_checkpoint_sha256": CONFIG["start_checkpoint_sha256"], + "checkpoints": {name: {"path": str(path), "sha256": sha(path)} for name, path in paths.items()}, + "hard_definition": "GT >=2 non-thumb distal angles >=45deg OR >=1 >=60deg; complete 21-joint geometry and MANO pose only", + "groups": {}, + } + for group in ("all", "normal", "hard"): + selected = {name: [row for row in value if group == "all" or row["gt_hard"] == (group == "hard")] + for name, value in rows.items()} + parent = selected["U0_parent"] + report["groups"][group] = { + "hands": len(parent), + "gt_variance_6d": [ + {"joint": joint, "name": JOINTS[joint], "side": side_name, + "count": int(moments[group]["GT"].count[side, joint]), + "variance": float(moments[group]["GT"].variance()[side, joint])} + for side, side_name in enumerate(("left", "right")) for joint in range(16) + ], + "models": { + name: { + "means": {key: mean(model_rows, key) for key in ALL_METRICS}, + "local_pose_per_joint_mean_deg": [ + float(np.mean([row["local_pose_per_joint_deg"][joint] for row in model_rows])) + if model_rows else None for joint in range(15) + ], + "paired_to_parent": ({key: paired(parent, model_rows, key) + for key in ALL_METRICS} if name != "U0_parent" else None), + "rotation_variance": variance_report(moments[group])[name], + } for name, model_rows in selected.items() + }, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + a7.dump(args.output, finite(report)) + a7.dump(args.output.with_suffix(".rows.json"), finite(rows)) + print(json.dumps({"source": args.source, "clips": len(dataset), + "hands": {group: report["groups"][group]["hands"] + for group in ("all", "normal", "hard")}, + "output": str(args.output)}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/rotation_variance.py b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/rotation_variance.py new file mode 100644 index 0000000000000000000000000000000000000000..6aa30a6315d55d0536979810ac4aaa102920ed46 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/pose_delta_diagnostics/rotation_variance.py @@ -0,0 +1,151 @@ +"""Compare per-joint rotation dispersion on fixed native-GT development panels.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +import torch + +EXPERIMENT = Path("/home/wuyifan/u0_normalized6d_20261002") +sys.path.insert(0, str(EXPERIMENT)) + +from train import CONFIG, a7, base, model_for, sha # noqa: E402 +from clean_eval import apply_mode, dataset_for # noqa: E402 +from foundation_hand.data.arctic_dataset import ARCTICClipDataset # noqa: E402 +from foundation_hand.geometry.rotations import axis_angle_to_matrix # noqa: E402 +from normalized_loss import canonical_rotation_6d # noqa: E402 +from targets import NativePanel # noqa: E402 + +JOINTS = ( + "wrist", "index_1", "index_2", "index_3", "middle_1", "middle_2", + "middle_3", "little_1", "little_2", "little_3", "ring_1", "ring_2", + "ring_3", "thumb_1", "thumb_2", "thumb_3", +) + + +class Moments: + def __init__(self): + self.count = torch.zeros((2, 16), dtype=torch.float64) + self.total = torch.zeros((2, 16, 6), dtype=torch.float64) + self.squares = torch.zeros((2, 16, 6), dtype=torch.float64) + + def add(self, values, valid): + values = values.detach().double().cpu()[0] + valid = valid.detach().cpu()[0] + for side in range(2): + selected = values[:, side][valid[:, side]] + self.count[side] += selected.shape[0] + self.total[side] += selected.sum(dim=0) + self.squares[side] += selected.square().sum(dim=0) + + def variance(self): + mean = self.total / self.count.clamp_min(1)[..., None] + return (self.squares / self.count.clamp_min(1)[..., None] - mean.square()).clamp_min(0).sum(-1) + + +def load_model(path: Path, expected_mode: str | None, device): + state = torch.load(path, map_location="cpu", weights_only=False) + if not state["complete_backbone"]: + raise RuntimeError(f"incomplete backbone: {path}") + if expected_mode is not None: + if (state["experiment"] != CONFIG["experiment"] or state["mode"] != expected_mode + or state["parent_sha256"] != CONFIG["start_checkpoint_sha256"] + or state["update"] != 2000 or state["smoke"]): + raise RuntimeError(f"checkpoint lineage mismatch: {path}") + elif state["update"] != 20004 or sha(path) != CONFIG["start_checkpoint_sha256"]: + raise RuntimeError("parent checkpoint mismatch") + model = model_for("student") + model.load_state_dict(state["model"], strict=True) + return model.to(device).eval() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--n1", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device("cuda") + paths = { + "GT": None, + "U0_parent": Path(CONFIG["start_checkpoint"]), + "N0_2K": EXPERIMENT / "runs/N0_formal/update_0002000.pt", + "N1_2K": args.n1, + } + models = {name: load_model(path, None if name == "U0_parent" else name[:2], device) + for name, path in paths.items() if path is not None} + panel_root = a7.BASE_ROOT / "eval/frozen_panels_sync_v2" + panels = json.loads((panel_root / "panels.json").read_text()) + report = {"definition": "sum of six component population variances of orthonormal rotation-6D; " + "each source and hand side centered separately", + "weights": {name: {"path": str(path), "sha256": sha(path)} + for name, path in paths.items() if path is not None}, + "sources": {}} + for source in ("H2O", "ARCTIC", "HOT3D"): + manifest = panel_root / f"{source.lower()}_development_t8.jsonl" + registered = panels["sources"][source]["development"] + if sha(manifest) != registered["manifest_sha256"] or panels["sources"][source]["train_overlap"]: + raise RuntimeError(f"panel mismatch: {source}") + rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), + hand_valid_policy="visible_mesh") + if source == "ARCTIC" else dataset_for(source, manifest)) + dataset = NativePanel(source, native, rows) + moments = {name: Moments() for name in paths} + angle_sum = {name: torch.zeros((2, 16), dtype=torch.float64) for name in models} + angle_count = {name: torch.zeros((2, 16), dtype=torch.float64) for name in models} + with torch.inference_mode(): + for index in range(len(dataset)): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, "rgb") + batch = base.move_to_device(batch, device) + valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + target = axis_angle_to_matrix(torch.nan_to_num(batch["mano_pose"].float()) + .reshape(*valid.shape, 16, 3)) + gt6 = target[..., :2, :].reshape(*valid.shape, 16, 6) + moments["GT"].add(gt6, valid) + for name, model in models.items(): + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + pred6 = canonical_rotation_6d(prediction["mano_rotations_6d"]) + moments[name].add(pred6, valid) + if not torch.isfinite(pred6).all(): + raise RuntimeError(f"nonfinite prediction: {name}, {source}, {index}") + relative = prediction["mano_rotation_matrices"].float() @ target.transpose(-1, -2) + trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1) + angle = torch.rad2deg(torch.acos(((trace - 1) / 2).clamp(-1, 1)))[0].double().cpu() + valid_cpu = valid[0].cpu() + angle_sum[name] += (angle * valid_cpu[..., None]).sum(dim=0) + angle_count[name] += valid_cpu.sum(dim=0)[:, None] + if (index + 1) % 32 == 0: + print(json.dumps({"source": source, "done": index + 1, + "total": len(dataset)}), flush=True) + source_report = {"clips": len(dataset), "manifest_sha256": sha(manifest), "joints": []} + variances = {name: value.variance() for name, value in moments.items()} + for joint, label in enumerate(JOINTS): + for side, side_label in enumerate(("left", "right")): + source_report["joints"].append({ + "joint": joint, "name": label, "side": side_label, + "n": int(moments["GT"].count[side, joint]), + "variance_6d": {name: float(value[side, joint]) + for name, value in variances.items()}, + "angle_error_deg": { + name: float(angle_sum[name][side, joint] / angle_count[name][side, joint].clamp_min(1)) + for name in models}, + }) + report["sources"][source] = source_report + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({"output": str(args.output), "sources": list(report["sources"])})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/README.md b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e2f1d1f680ed342a8ba510bbbc668cc79e01887f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/README.md @@ -0,0 +1,72 @@ +# S4 Independent Modality Experts + +Registered 2026-09-28. Both trained experts start from the **same complete S4** +checkpoint (`85a9e02274f94b69e2a634518f6f46244dbedb518b135f07be4b2c746be9bb15`). +RGB continues to use that unchanged checkpoint; no A2/A3 weight substitution. + +| Route | Training data | DINO | Other trainable parameters | +|---|---|---|---| +| RGB | No new training | Frozen | None | +| RGB+K | Same filtered H2O/ARCTIC/HOT3D, 35/25/40 exposure | Frozen | RGB projection, ray encoder, spatial/temporal/bimanual decoder, queries, MANO/2D/shape/translation heads | +| RGB+K+Depth | Same filtered H2O, measured metric depth | Last two blocks and final norm | Same geometry readout plus depth encoder and depth attention | + +This tests independent specialization from S4, not an architectural camera experiment +or a one-variable replication of A6. The K source mixture includes HOT3D to retain +the current S4 training domains. All source-native supervision masks and S4 loss +weights remain unchanged. Earlier DINO blocks, legacy presence, fixed-gate MLPs +and unused depth modules on the K route stay frozen. Each expert has its own full +checkpoint and optimizer; no trainable trunk is shared with RGB or the other expert. + +## Fixed Recipe + +- T=8, 512x896, BF16, TF32 disabled; one clip per GPU microbatch. +- Global batch 12, accumulation 12 / claimed idle GPUs. Same GPU count within resume. +- Per expert: 100,008 clips = 8,334 optimizer updates. Milestones 25,008/50,004/100,008 clips. +- Fresh AdamW, weight decay 0.05, main peak/min LR 1e-5/1e-6. +- DINO on D: peak LR 2e-7, fixed 0.02 ratio. K keeps its S4 backbone unchanged. +- One continuous cosine, warmup 1,008 clips; no scheduler restart after evaluations. +- Preserve S4 grad clip 100, fixed depth gate 0.5, existing visual augmentation + and measured-depth corruption probability 0.30. No input-modality dropout inside experts. +- Source-local no-replacement queues reuse the original filtered index. The parent + already completed coverage; this 100K fine-tune is not claimed to cover all HOT3D tiles. +- Entire checkpoints include all DINO tensors, optimizer, per-rank RNG, sample + cursor and source/GT ledgers. Recovery checkpoint every 417 updates and milestones. +- Original S4 code/data are read-only and checked against the parent fingerprint. + No raw RGB/depth cache copy or deletion. New outputs live under G2 + `/home/wuyifan/s4_modality_experts_20260928`, with a 200 GiB free-space reserve. + +## Evaluation And Routing + +Reuse the frozen native S4 development and confirmation panels: H2O three modes, +ARCTIC/HOT3D RGB and RGB+K. These panels have already been inspected; report them +as validation-informed diagnostics, not untouched test evidence. Earlier milestones +use development only. The final table uses the **fixed 8,334-update endpoints**, +not a validation-selected best checkpoint. The original S4 is rerun on exactly the +same clips, masks, input mode, precision and camera convention for paired deltas. + +Four metrics: absolute MPJPE, root-relative MPJPE, absolute MPVPE (mm), projected +MANO 2D joint error (px). Do not substitute direct 2D-head error. GT validity sets +denominators; no predicted visibility filter is used. Report source/hand-side +coverage and paired recording-bootstrap intervals. Reject a model that changes +the finite metric denominator. No official test, camera adapter, mask interface, +new loss, or automatic promotion is part of this experiment. + +Routing reads canonical input availability (legacy aliases only as fallback), +not source identity or supervision masks. Single-clip routing is conservative: +incomplete K -> original S4 RGB; complete K but incomplete depth -> K expert; +complete K and depth -> D expert. Invalid/padded frames do not block routing. +Pure-RGB outputs must be tensor-identical to standalone S4 on real clips. + +Preflight includes CPU routing/sampler tests, real-data DDP smoke for both experts, +full-parent composition, frozen-tensor identity, and same-world-size resume. +Decoded inputs/GT checksums, sampler cursor, RNG and restored optimizer buffers +must be exact. Independent GPU continuation is numerical, not bitwise: model +absolute tolerance 1e-7; optimizer absolute/relative tolerance 2e-5/1e-4. Report +actual differences. The first preflight stopped on a strict bitwise comparison +(DINO-only model max difference 7.45e-9, optimizer max 1.22e-5); losses and RNG +were identical. Its artifacts remain under `preflight/` and the original logs. +Attempt v2 adds decoded-input checksums and exact optimizer/RNG restore checks, +and runs a new preflight under `preflight_v2/` before any formal training. +Controller releases only its own GPU claims and never preempts existing jobs. +Final artifacts: `RESULTS.md`, paired evaluation JSON/rows, `results.json`, and +`candidate_bundle.json`; no HTML update is performed. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/RESULTS.md b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/RESULTS.md new file mode 100644 index 0000000000000000000000000000000000000000..5c4d04dbc9acec462151907421ac834ef7e6c26a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/RESULTS.md @@ -0,0 +1,33 @@ +# S4 Independent Modality Experts: Fixed Endpoint + +Same frozen confirmation panels and original GT masks. Previously inspected panels; not untouched test evidence. +RGB is the immutable original S4. K/D are independent S4-initialized full checkpoints at 100,008 clips. + +Lower is better. First three metrics in mm; projected MANO 2D error in px. Delta = expert minus same-input S4. + +| Source | Input | Model | Abs MPJPE | RR MPJPE | MPVPE | MANO projected 2D | +|---|---|---|---:|---:|---:|---:| +| ARCTIC | rgb | S4 parent | 32.069 | 20.865 | 31.768 | 19.758 | +| ARCTIC | rgb | Routed experts | 32.069 | 20.865 | 31.768 | 19.758 | +| ARCTIC | rgb | Delta | +0.000 | +0.000 | +0.000 | +0.000 | +| ARCTIC | rgb_k | S4 parent | 31.864 | 20.997 | 31.545 | 19.308 | +| ARCTIC | rgb_k | Routed experts | 33.713 | 20.722 | 33.375 | 19.334 | +| ARCTIC | rgb_k | Delta | +1.849 | -0.275 | +1.830 | +0.026 | +| H2O | rgb | S4 parent | 21.562 | 13.238 | 21.812 | 11.327 | +| H2O | rgb | Routed experts | 21.562 | 13.238 | 21.812 | 11.327 | +| H2O | rgb | Delta | +0.000 | +0.000 | +0.000 | +0.000 | +| H2O | rgb_depth_k | S4 parent | 20.444 | 13.244 | 20.667 | 10.999 | +| H2O | rgb_depth_k | Routed experts | 19.655 | 13.186 | 19.962 | 10.784 | +| H2O | rgb_depth_k | Delta | -0.789 | -0.059 | -0.705 | -0.215 | +| H2O | rgb_k | S4 parent | 21.410 | 13.264 | 21.624 | 11.107 | +| H2O | rgb_k | Routed experts | 20.829 | 13.096 | 20.999 | 10.819 | +| H2O | rgb_k | Delta | -0.581 | -0.168 | -0.625 | -0.288 | +| HOT3D | rgb | S4 parent | 51.661 | 23.684 | 51.343 | 13.972 | +| HOT3D | rgb | Routed experts | 51.661 | 23.684 | 51.343 | 13.972 | +| HOT3D | rgb | Delta | +0.000 | +0.000 | +0.000 | +0.000 | +| HOT3D | rgb_k | S4 parent | 51.698 | 23.645 | 51.402 | 13.501 | +| HOT3D | rgb_k | Routed experts | 47.683 | 23.655 | 47.333 | 13.700 | +| HOT3D | rgb_k | Delta | -4.015 | +0.010 | -4.068 | +0.199 | + +Per-recording paired 95% bootstrap intervals, effective denominators and hand-side metadata are in evaluations/*.json and their .rows.json files. +No predicted-presence filtering, new camera adapter, loss-weight change, or automatic promotion was applied. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/common.py b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/common.py new file mode 100644 index 0000000000000000000000000000000000000000..85492be4ec06671d488c456e3aaaf4c1929ce5d4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/common.py @@ -0,0 +1,159 @@ +"""Use the original S4 implementation and filtered-GT contracts read-only.""" + +from __future__ import annotations + +from collections import Counter +import hashlib +import json +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parent +CONFIG_PATH = ROOT / "config.json" +CONFIG = json.loads(CONFIG_PATH.read_text()) +BASE_ROOT = Path(CONFIG["base_root"]) +BASE_CODE = BASE_ROOT / "code" +sys.path[:0] = [str(BASE_CODE), str(BASE_CODE / "src")] + +import torch +import numpy as np +import clean_train as base +from coverage_sampler import CoverageSampler + +PARENT = BASE_ROOT / CONFIG["parent"] + + +def exact_equal(left, right) -> bool: + if torch.is_tensor(left): + return torch.is_tensor(right) and torch.equal(left.detach().cpu(), right.detach().cpu()) + if isinstance(left, np.ndarray): + return isinstance(right, np.ndarray) and np.array_equal(left, right) + if isinstance(left, dict): + return isinstance(right, dict) and left.keys() == right.keys() and all( + exact_equal(value, right[key]) for key, value in left.items()) + if isinstance(left, (list, tuple)): + return type(left) is type(right) and len(left) == len(right) and all( + exact_equal(a, b) for a, b in zip(left, right)) + return left == right + + +def numeric_equal(left, right, *, atol, rtol=0.0) -> bool: + if torch.is_tensor(left): + return torch.is_tensor(right) and torch.allclose(left.detach().cpu(), right.detach().cpu(), + atol=atol, rtol=rtol) + if isinstance(left, dict): + return isinstance(right, dict) and left.keys() == right.keys() and all( + numeric_equal(value, right[key], atol=atol, rtol=rtol) for key, value in left.items()) + if isinstance(left, (list, tuple)): + return type(left) is type(right) and len(left) == len(right) and all( + numeric_equal(a, b, atol=atol, rtol=rtol) for a, b in zip(left, right)) + return exact_equal(left, right) + + +def dump(path: Path, value: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") + temporary.replace(path) + + +def code_hashes() -> dict[str, str]: + return {**{f"base/{key}": value for key, value in base.training_code_hashes().items()}, + **{f"experiment/{path.name}": base.sha(path) + for path in sorted(ROOT.glob("*.py"))}, + "experiment/config.json": base.sha(CONFIG_PATH)} + + +def load_parent() -> dict: + if base.sha(PARENT) != CONFIG["parent_sha256"]: + raise RuntimeError("S4 parent checksum changed") + state = torch.load(PARENT, map_location="cpu", weights_only=False) + if (not state.get("complete_backbone") or state.get("smoke") + or state["stage"] != "S4" or state["update"] != 66667 + or state["index_sha256"] != base.sha(base.INDEX) + or state["code_sha256"] != base.training_code_hashes()): + raise RuntimeError("S4 parent, index or native implementation contract mismatch") + if state["data_sha256"] != base.EXPECTED_MANIFEST_SHA256[8]: + raise RuntimeError("S4 parent training manifests differ") + for source, expected in state["data_sha256"].items(): + manifest = base.MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl" + if base.sha(manifest) != expected: + raise RuntimeError(f"filtered training manifest changed: {source}") + return state + + +def model_for(expert: str): + if expert not in ("RGB", "K", "D"): + raise ValueError(expert) + model = base.model_for("S4") + model.load_state_dict(load_parent()["model"], strict=True) + if expert == "RGB": + model.requires_grad_(False) + elif expert == "K": + model.rgb_encoder.backbone.requires_grad_(False) + for name, parameter in model.named_parameters(): + if (name.startswith("presence_head.") or ".depth_gate." in name + or (expert == "K" and (name.startswith("depth_encoder.") + or ".depth_" in name))): + parameter.requires_grad_(False) + return model + + +def frozen_fingerprint(model) -> str: + trainable = {name for name, parameter in model.named_parameters() if parameter.requires_grad} + digest = hashlib.sha256() + for name, value in sorted(model.state_dict().items()): + if name not in trainable: + digest.update(name.encode()) + digest.update(value.detach().cpu().contiguous().reshape(-1).view(torch.uint8).numpy().tobytes()) + return digest.hexdigest() + + +class ExpertCoverage(CoverageSampler): + def __init__(self, index, expert: str): + super().__init__(index, "S4", seed=CONFIG["seed"]) + self.expert = expert + if expert not in ("K", "D"): + raise ValueError(expert) + if self.quota != tuple(CONFIG["source_quota_K"][source] for source in base.SOURCES): + raise RuntimeError("K source quotas do not match the registered S4 mixture") + + def source_and_ordinal(self, position): + if self.expert == "D": + if position < 0: + raise ValueError("negative sample position") + return "H2O", position + return super().source_and_ordinal(position) + + def sample(self, position): + row = super().sample(position) + row["mode"] = "rgb_depth_k" if self.expert == "D" else "rgb_k" + return row + + +class ExpertDataset(base.MixedDataset): + def __init__(self, expert): + self.sources = {} + for source in (("H2O",) if expert == "D" else base.SOURCES): + self.sources[source] = base.FilteredClipDataset( + source, base.MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl", + 8, (512, 896), base.ASSETS["mano_root"], BASE_CODE / "third_party", + {"enabled": source != "HOT3D", "probability": .8}, + ) + + +def mode_and_supervision(batch, expert): + frame = batch["frame_valid"].bool() + wanted_depth = frame if expert == "D" else torch.zeros_like(frame) + if (not torch.equal(batch["K_input_available"], frame) + or not torch.equal(batch["depth_input_available"], wanted_depth) + or not torch.equal(batch["K_available"], frame) + or not torch.equal(batch["depth_available"], wanted_depth)): + raise RuntimeError("expert input availability contract failed") + counts = Counter() + source = batch["sampling_source_id"][0] + for key in base.MASK_FIELDS: + if key in batch: + for side in range(2): + counts[f"{source}:{side}:{key}"] += int(batch[key][:, :, side].sum()) + return source, counts diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/config.json new file mode 100644 index 0000000000000000000000000000000000000000..247207987ba7a671c0406a0add88e1987fff7989 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/config.json @@ -0,0 +1,28 @@ +{ + "experiment": "s4_modality_experts_20260928", + "attempt": "v2", + "resume_model_atol": 0.0000001, + "resume_optimizer_atol": 0.00002, + "resume_optimizer_rtol": 0.0001, + "base_root": "/home/wuyifan/foundation_hand_clean_gt_dino_20260925", + "parent": "checkpoints/formal_v3_s4/s4_update_0066667.pt", + "parent_sha256": "85a9e02274f94b69e2a634518f6f46244dbedb518b135f07be4b2c746be9bb15", + "seed": 20260928, + "global_batch": 12, + "updates": 8334, + "milestones": [2084, 4167, 8334], + "warmup_clips": 1008, + "learning_rate": 0.00001, + "min_learning_rate": 0.000001, + "depth_backbone_learning_rate": 0.0000002, + "grad_clip": 100.0, + "weight_decay": 0.05, + "workers_per_rank": 2, + "permitted_gpus": [0, 1, 2, 3, 4, 5], + "order": ["D", "K"], + "source_quota_K": {"H2O": 7, "ARCTIC": 5, "HOT3D": 8}, + "source_D": "H2O", + "evaluation_role": "previously_inspected_frozen_panels", + "final_selection": "fixed_8334_update_endpoint_not_best_validation", + "official_test_used": false +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..b72fa75b796c13d647a832af37d0c10ca7ee25b5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/controller.py @@ -0,0 +1,213 @@ +"""Durable train/evaluate queue; GPU claims are held for a complete expert run.""" + +from __future__ import annotations + +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +from common import CONFIG, PARENT, ROOT, base, dump, exact_equal, load_parent, numeric_equal +from scripts.train_phase7_external import (assert_physical_gpu_idle, claim_physical_gpu, + release_physical_gpu_claim) + + +def status(event, **details): + payload = {"event": event, "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S%z"), **details} + dump(ROOT / "state.json", payload) + print(json.dumps(payload), flush=True) + + +def reserve(): + claimed = [] + for gpu in CONFIG["permitted_gpus"]: + if not claim_physical_gpu(gpu): + continue + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + else: + claimed.append(gpu) + world = max((n for n in range(1, len(claimed) + 1) if CONFIG["global_batch"] % n == 0), default=0) + for gpu in claimed[world:]: + release_physical_gpu_claim(gpu) + return claimed[:world] + + +def run(command, label, gpus): + path = ROOT / "logs" / f"{label}.log" + path.parent.mkdir(exist_ok=True) + if path.exists(): + raise FileExistsError(f"unfinished queue needs manual diagnosis: {path}") + env = dict(os.environ, CUDA_VISIBLE_DEVICES=",".join(map(str, gpus)), + OMP_NUM_THREADS="2", MKL_NUM_THREADS="2", PYTHONUNBUFFERED="1") + with path.open("xb") as stream: + process = subprocess.Popen([sys.executable, *command], cwd=ROOT, env=env, + stdin=subprocess.DEVNULL, stdout=stream, stderr=subprocess.STDOUT) + status("running", label=label, command=command, child_pid=process.pid, gpus=gpus) + result = process.wait() + if result: + raise RuntimeError(f"{label} failed with exit code {result}") + + +def train(expert, update, gpus, *, smoke=False, resume=None, label=None, output=None): + output = output or ROOT / "runs" / expert + target = output / f"update_{update:07d}.pt" + if target.exists(): + raise FileExistsError(f"queue endpoint already exists: {target}") + command = ["-m", "torch.distributed.run", "--standalone", f"--nproc_per_node={len(gpus)}", + str(ROOT / "train_expert.py"), "--expert", expert, "--output", str(output), + "--updates", str(update)] + if resume: + command += ["--resume", str(resume)] + if smoke: + command += ["--smoke"] + run(command, label or f"train_{expert}_{update:07d}", gpus) + record = json.loads(target.with_suffix(".json").read_text()) + if (record["sha256"] != base.sha(target) or not record["complete_backbone"] + or not record["frozen_state_unchanged"] or sum(record["source_exposure"].values()) + != update * CONFIG["global_batch"]): + raise RuntimeError("expert endpoint checkpoint or sample ledger failed") + return target + + +def evaluate(expert, source, role, gpus, checkpoint=None, *, smoke=False, limit=None, label=None): + update = 0 if expert == "RGB" else int(checkpoint.stem.split("_")[-1]) + label = label or f"eval_{expert}_{update:07d}_{role}_{source}" + path = ROOT / "evaluations" / f"{label}.json" + command = [str(ROOT / "evaluate.py"), "--expert", expert, "--source", source, + "--role", role, "--output", str(path)] + if checkpoint: + command += ["--checkpoint", str(checkpoint)] + if smoke: + command += ["--smoke"] + if limit is not None: + command += ["--limit", str(limit)] + run(command, label, gpus[:1]) + return path + + +def write_table(): + records = [] + for path in sorted((ROOT / "evaluations").glob("eval_*_confirmation_*.json")): + if path.name.endswith(".rows.json"): + continue + report = json.loads(path.read_text()) + if report["smoke"]: + continue + records.append(report) + if len(records) != 7: + raise RuntimeError(f"final table requires seven source/input reports, got {len(records)}") + lines = ["# S4 Independent Modality Experts: Fixed Endpoint", "", + "Same frozen confirmation panels and original GT masks. Previously inspected panels; not untouched test evidence.", + "RGB is the immutable original S4. K/D are independent S4-initialized full checkpoints at 100,008 clips.", "", + "Lower is better. First three metrics in mm; projected MANO 2D error in px. Delta = expert minus same-input S4.", "", + "| Source | Input | Model | Abs MPJPE | RR MPJPE | MPVPE | MANO projected 2D |", + "|---|---|---|---:|---:|---:|---:|"] + for report in sorted(records, key=lambda x: (x["source"], x["input_mode"])): + for key, label in (("parent", "S4 parent"), ("routed", "Routed experts")): + values = " | ".join(f"{value['mean']:.3f}" for value in report[key].values()) + lines.append(f"| {report['source']} | {report['input_mode']} | {label} | {values} |") + deltas = " | ".join(f"{value['expert_minus_parent']:+.3f}" for value in report["paired"].values()) + lines.append(f"| {report['source']} | {report['input_mode']} | Delta | {deltas} |") + lines += ["", "Per-recording paired 95% bootstrap intervals, effective denominators and hand-side metadata are in evaluations/*.json and their .rows.json files.", + "No predicted-presence filtering, new camera adapter, loss-weight change, or automatic promotion was applied."] + (ROOT / "RESULTS.md").write_text("\n".join(lines) + "\n") + dump(ROOT / "results.json", records) + dump(ROOT / "candidate_bundle.json", { + "status": "candidate_not_automatically_promoted", "rgb": str(PARENT), + "rgb_sha256": CONFIG["parent_sha256"], + "rgb_k": str(ROOT / "runs/K/update_0008334.pt"), + "rgb_depth_k": str(ROOT / "runs/D/update_0008334.pt"), + "routing": "availability only; conservative whole-clip fallback; batch size one", + }) + + +def main(): + lock = (ROOT / "controller.lock").open("a") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + gpus = [] + try: + load_parent() + while not gpus: + gpus = reserve() + if not gpus: + status("waiting_for_idle_gpus") + time.sleep(30) + dump(ROOT / "resources.json", {"gpus": gpus, "global_batch": CONFIG["global_batch"], + "accumulation": CONFIG["global_batch"] // len(gpus)}) + attempt = CONFIG["attempt"] + preflight_root = ROOT / f"preflight_{attempt}" + run(["-m", "unittest", "-v", "test_contract"], f"cpu_contracts_{attempt}", []) + for expert in CONFIG["order"]: + smoke = train(expert, 2, gpus, smoke=True, + output=preflight_root / expert, label=f"smoke_{expert}_{attempt}") + evaluate(expert, "H2O", "development", gpus, smoke, smoke=True, + limit=2, label=f"smoke_eval_{expert}_{attempt}") + # Exact same-world-size continuation is checked before using formal outputs. + continuous = train("D", 4, gpus, smoke=True, output=preflight_root / "continuous_D", + label=f"resume_continuous_D_{attempt}") + resumed = train("D", 4, gpus, smoke=True, output=preflight_root / "D", + resume=preflight_root / "D/update_0000002.pt", label=f"resume_split_D_{attempt}") + left = base.torch.load(continuous, map_location="cpu", weights_only=False) + right = base.torch.load(resumed, map_location="cpu", weights_only=False) + for key in ("rank_rng_states", "next_global_sample_position", "source_exposure", + "supervision_exposure", "input_checksums", "frozen_fingerprint"): + if not exact_equal(left[key], right[key]): + raise RuntimeError(f"same-world-size continuation changed {key}") + if not numeric_equal(left["model"], right["model"], atol=CONFIG["resume_model_atol"]): + raise RuntimeError("resumed model exceeds registered numerical tolerance") + if not numeric_equal(left["optimizer"], right["optimizer"], + atol=CONFIG["resume_optimizer_atol"], rtol=CONFIG["resume_optimizer_rtol"]): + raise RuntimeError("resumed optimizer exceeds registered numerical tolerance") + max_model_difference = max(float((value.float() - right["model"][key].float()).abs().max()) + for key, value in left["model"].items()) + max_optimizer_difference = max(float((value - right["optimizer"]["state"][key][name]).abs().max()) + for key, values in left["optimizer"]["state"].items() for name, value in values.items() + if base.torch.is_tensor(value)) + dump(preflight_root / "resume_audit.json", {"status": "pass", + "input_checksums_rng_cursor_gt_ledgers_exact": True, + "optimizer_restore_is_exact": True, "frozen_state_exact": True, + "model_max_abs_difference": max_model_difference, + "optimizer_max_abs_difference": max_optimizer_difference, + "model_atol": CONFIG["resume_model_atol"], + "optimizer_atol": CONFIG["resume_optimizer_atol"], + "optimizer_rtol": CONFIG["resume_optimizer_rtol"], + "post_continuation_equivalence": "numerical_not_bitwise"}) + del left, right + for source in base.SOURCES: + evaluate("RGB", source, "development", gpus, smoke=True, limit=2, + label=f"rgb_identity_{source}_{attempt}") + dump(ROOT / "preflight.json", {"status": "pass", "complete_parent_verified": True, + "real_clip_expert_inputs_and_metrics": True, "rgb_routing_tensor_identical": True, + "same_world_resume_numerical_equivalence": True, + "input_checksums_rng_cursor_gt_ledgers_exact": True, "gpus": gpus}) + status("preflight_pass", gpus=gpus) + for expert in CONFIG["order"]: + previous = None + for update in CONFIG["milestones"]: + previous = train(expert, update, gpus, resume=previous) + for source in (("H2O",) if expert == "D" else base.SOURCES): + evaluate(expert, source, "development", gpus, previous) + for source in (("H2O",) if expert == "D" else base.SOURCES): + evaluate(expert, source, "confirmation", gpus, previous) + for source in base.SOURCES: + evaluate("RGB", source, "confirmation", gpus) + if base.sha(PARENT) != CONFIG["parent_sha256"]: + raise RuntimeError("immutable RGB checkpoint changed") + write_table() + status("complete", results=str(ROOT / "RESULTS.md"), gpus=gpus) + except Exception as error: + status("failed_requires_diagnosis", error=repr(error)) + raise + finally: + for gpu in gpus: + release_physical_gpu_claim(gpu) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/evaluate.py b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..5d6a07ba03bea67e67a2f1a1996c4e5d468280c5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/evaluate.py @@ -0,0 +1,138 @@ +"""Paired four-metric evaluation with the exact S4 native GT and camera convention.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +import math +from pathlib import Path + +import numpy as np +import torch + +from common import CONFIG, BASE_ROOT, ROOT, base, code_hashes, dump, model_for +from router import ExpertRouter +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from scripts.evaluate_phase7_external import aggregate, make_row + + +def paired_summary(parent_rows, expert_rows): + result = {} + for metric in FOUR_METRICS: + recording = defaultdict(list) + deltas = [] + for left, right in zip(parent_rows, expert_rows): + a, b = left[metric], right[metric] + if math.isfinite(a) != math.isfinite(b): + raise RuntimeError(f"prediction changed the metric denominator: {metric}") + if math.isfinite(a): + recording[left["physical_recording_id"]].append(b - a) + deltas.append(b - a) + if not deltas: + raise RuntimeError(f"empty four-metric denominator: {metric}") + sums = np.array([sum(values) for values in recording.values()]) + counts = np.array([len(values) for values in recording.values()]) + rng = np.random.default_rng(CONFIG["seed"]) + selections = rng.integers(0, len(sums), size=(2000, len(sums))) + bootstrap = sums[selections].sum(1) / counts[selections].sum(1) + result[metric] = {"expert_minus_parent": float(np.mean(deltas)), + "recording_bootstrap_95ci": np.quantile(bootstrap, [.025, .975]).tolist(), + "count": len(deltas), "recordings": len(recording)} + return result + + +def run(args): + if args.output.exists(): + raise FileExistsError(args.output) + if args.source != "H2O" and args.expert == "D": + raise ValueError("real metric depth is only available on H2O") + if args.limit is not None and not args.smoke: + raise ValueError("subset evaluation must be marked smoke") + mode = {"RGB": "rgb", "K": "rgb_k", "D": "rgb_depth_k"}[args.expert] + panel_root = BASE_ROOT / "eval/frozen_panels_sync_v2" + panels = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_{args.role}_t8.jsonl" + panel_sha = panels["sources"][args.source][args.role]["manifest_sha256"] + if base.sha(manifest) != panel_sha: + raise RuntimeError("frozen native evaluation panel changed") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device("cuda") + parent = model_for("RGB").to(device).eval() + candidate = parent + checkpoint_sha = CONFIG["parent_sha256"] + update = 0 + if args.expert != "RGB": + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if (state["expert"] != args.expert or state["smoke"] != args.smoke + or not state["complete_backbone"] or state["code_sha256"] != code_hashes() + or state["parent_sha256"] != CONFIG["parent_sha256"]): + raise RuntimeError("expert checkpoint identity or implementation mismatch") + if args.role == "confirmation" and not args.smoke and state["update"] != CONFIG["updates"]: + raise RuntimeError("confirmation table requires the registered final expert endpoint") + candidate = model_for(args.expert) + candidate.load_state_dict(state["model"], strict=True) + candidate.to(device).eval() + update, checkpoint_sha = state["update"], base.sha(args.checkpoint) + del state + experts = {"rgb": parent, "rgb_k": candidate, "rgb_depth_k": candidate} + router = ExpertRouter(experts["rgb"], experts["rgb_k"], experts["rgb_depth_k"]) + dataset = dataset_for(args.source, manifest) + limit = min(args.limit, len(dataset)) if args.limit is not None else len(dataset) + parent_rows, expert_rows = [], [] + with torch.inference_mode(): + for index in range(limit): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, mode) + batch = base.move_to_device(batch, device) + base.attach_gt_vertices(batch, parent) + if router.select_mode(batch) != mode: + raise RuntimeError("routed input differs from the registered evaluation mode") + with torch.autocast("cuda", dtype=torch.bfloat16): + original = parent(batch) + prediction = router(batch) + if args.expert == "RGB": + for key, value in original.items(): + if torch.is_tensor(value) and not torch.equal(value, prediction[key]): + raise RuntimeError(f"pure RGB routing changed S4 output: {key}") + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + parent_rows.append(make_row(original, batch, 0, frame, side)) + expert_rows.append(make_row(prediction, batch, 0, frame, side)) + original, updated = aggregate(parent_rows), aggregate(expert_rows) + report = {"source": args.source, "expert": args.expert, "input_mode": mode, "role": args.role, + "panel_status": CONFIG["evaluation_role"], "panel_sha256": panel_sha, + "clips": limit, "hands": len(expert_rows), "smoke": args.smoke, + "expert_checkpoint_sha256": checkpoint_sha, "expert_update": update, + "parent_sha256": CONFIG["parent_sha256"], "code_sha256": code_hashes(), + "camera_model": "unchanged native S4 adapter and K pinhole metric convention", + "presence_filter_for_metrics": False, + "parent": {key: original[key] for key in FOUR_METRICS}, + "routed": {key: updated[key] for key in FOUR_METRICS}, + "paired": paired_summary(parent_rows, expert_rows), + "supervision_coverage": updated["supervision_coverage"]} + dump(args.output, report) + rows = [{"clip_row": index, "parent": a, "expert": b} + for index, (a, b) in enumerate(zip(parent_rows, expert_rows))] + def finite(value): + if isinstance(value, dict): + return {key: finite(item) for key, item in value.items()} + return None if isinstance(value, float) and not math.isfinite(value) else value + dump(args.output.with_suffix(".rows.json"), [finite(row) for row in rows]) + print(json.dumps({"source": args.source, "input_mode": mode, "update": update, + "routed": {key: updated[key]["mean"] for key in FOUR_METRICS}}), flush=True) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--expert", choices=("RGB", "K", "D"), required=True) + parser.add_argument("--checkpoint", type=Path) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--role", choices=("development", "confirmation"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--limit", type=int) + parser.add_argument("--smoke", action="store_true") + run(parser.parse_args()) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/launch.py b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..2174c023af8e75b68b2724675a5e0cf15e5cefcc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/launch.py @@ -0,0 +1,30 @@ +"""Detach the registered controller without replacing any existing run.""" + +import os +import json +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parent + + +def main(): + config = json.loads((ROOT / "config.json").read_text()) + log_path = ROOT / f"controller_{config['attempt']}.log" + state_path = ROOT / "state.json" + if log_path.exists() or (state_path.exists() and json.loads(state_path.read_text())["event"] + != "failed_requires_diagnosis"): + raise FileExistsError("existing controller requires inspection before any relaunch") + with log_path.open("xb") as log: + process = subprocess.Popen([sys.executable, "-u", str(ROOT / "controller.py")], + cwd=ROOT, stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, close_fds=True, + env=dict(os.environ, PYTHONUNBUFFERED="1")) + (ROOT / "controller.pid").write_text(f"{process.pid}\n") + print(f"controller pid={process.pid}, log={log_path}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/router.py b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/router.py new file mode 100644 index 0000000000000000000000000000000000000000..9e23a15fa1e49c165af45366ff2157209aa7b42c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/router.py @@ -0,0 +1,35 @@ +"""Choose an independent expert from input availability, never dataset or GT.""" + +import torch +from torch import nn + + +class ExpertRouter(nn.Module): + def __init__(self, rgb, rgb_k, rgb_depth_k): + super().__init__() + self.experts = nn.ModuleDict({"rgb": rgb, "rgb_k": rgb_k, "rgb_depth_k": rgb_depth_k}) + self.requires_grad_(False) + self.eval() + + @staticmethod + def select_mode(batch): + frame = batch["frame_valid"].bool() + if frame.ndim != 2 or frame.shape[0] != 1 or not bool(frame.any()): + raise ValueError("router requires one nonempty clip") + k = batch.get("K_input_available", batch.get("K_available", torch.zeros_like(frame))) + depth = batch.get("depth_input_available", batch.get("depth_available", torch.zeros_like(frame))) + if k.shape != frame.shape or depth.shape != frame.shape: + raise ValueError("availability shape differs from frame_valid") + if not bool(k.bool()[frame].all()): + return "rgb" + return "rgb_depth_k" if bool(depth.bool()[frame].all()) else "rgb_k" + + def forward(self, batch): + mode = self.select_mode(batch) + inputs = dict(batch) + frame = batch["frame_valid"].bool() + k = frame.clone() if mode != "rgb" else torch.zeros_like(frame) + depth = frame.clone() if mode == "rgb_depth_k" else torch.zeros_like(frame) + inputs.update(K_input_available=k, K_available=k.clone(), + depth_input_available=depth, depth_available=depth.clone()) + return self.experts[mode](inputs) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/test_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..85634448cd0868b27e876d3482cefe703162202d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/test_contract.py @@ -0,0 +1,104 @@ +import sqlite3 +import tempfile +from pathlib import Path +from collections import Counter +import unittest + +import torch +from torch import nn + +from router import ExpertRouter +from common import ExpertCoverage, exact_equal, numeric_equal + + +class Echo(nn.Module): + def __init__(self, value): + super().__init__() + self.value = value + + def forward(self, batch): + return {"route": self.value, "K": batch["K_input_available"], + "depth": batch["depth_input_available"]} + + +class RouterTests(unittest.TestCase): + def setUp(self): + self.router = ExpertRouter(Echo("RGB"), Echo("K"), Echo("D")) + self.frame = torch.tensor([[True, True, False]]) + + def test_three_routes_and_padding(self): + for k, d, expected in ((False, False, "RGB"), (True, False, "K"), (True, True, "D"), + (False, True, "RGB")): + batch = {"frame_valid": self.frame, + "K_input_available": self.frame & k, + "depth_input_available": self.frame & d} + result = self.router(batch) + self.assertEqual(result["route"], expected) + self.assertFalse(bool(result["K"][0, 2])) + self.assertFalse(bool(result["depth"][0, 2])) + self.assertEqual(bool(result["depth"].any()), expected == "D") + + def test_canonical_overrides_legacy_and_gt_is_not_used(self): + batch = {"frame_valid": self.frame, "K_input_available": torch.zeros_like(self.frame), + "K_available": self.frame, "depth_available": self.frame, + "K_supervision_valid": self.frame, "dataset_id": ["H2O"]} + self.assertEqual(self.router.select_mode(batch), "rgb") + self.assertTrue(torch.equal(batch["K_available"], self.frame)) + + def test_partial_clip_falls_back(self): + batch = {"frame_valid": self.frame, "K_available": self.frame, + "depth_available": torch.tensor([[True, False, False]])} + self.assertEqual(self.router.select_mode(batch), "rgb_k") + batch["K_available"] = torch.tensor([[True, False, False]]) + self.assertEqual(self.router.select_mode(batch), "rgb") + + def test_empty_clip_rejected(self): + with self.assertRaises(ValueError): + self.router.select_mode({"frame_valid": torch.zeros_like(self.frame)}) + + +class SamplerTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.index = Path(self.temp.name) / "index.sqlite" + with sqlite3.connect(self.index) as db: + db.execute("CREATE TABLE tiles(source TEXT, recording_id TEXT, tile_id TEXT)") + for source in ("H2O", "ARCTIC", "HOT3D"): + for index in range(10): + db.execute("INSERT INTO tiles VALUES(?,?,?)", (source, f"{source}-rec", + f"{source}-{index}")) + + def test_specialization_no_replacement_and_resume(self): + for expert in ("K", "D"): + sampler = ExpertCoverage(self.index, expert) + rows = [sampler.sample(p) for p in range(200)] + expected = {"H2O": 200} if expert == "D" else {"H2O": 70, "ARCTIC": 50, "HOT3D": 80} + self.assertEqual(Counter(row["source"] for row in rows), expected) + self.assertEqual({row["mode"] for row in rows}, + {"rgb_depth_k" if expert == "D" else "rgb_k"}) + for source in expected: + first = [row["tile_id"] for row in rows if row["source"] == source][:10] + self.assertEqual(len(set(first)), 10) + resumed = ExpertCoverage(self.index, expert) + self.assertEqual(rows[43:], [resumed.sample(p) for p in range(43, 200)]) + shards = [ExpertCoverage(self.index, expert) for _ in range(4)] + merged = sorted((row for rank, item in enumerate(shards) + for row in item.shard(0, 200, rank, 4)), key=lambda row: row["position"]) + self.assertEqual(rows, merged) + + +class ResumeComparisonTests(unittest.TestCase): + def test_exact_metadata_and_bounded_tensor_comparison(self): + left = {"weights": torch.tensor([1.0, .1]), "cursor": 48} + close = {"weights": torch.tensor([1.0, .1 + 1e-8]), "cursor": 48} + wrong = {"weights": torch.tensor([1.0, .101]), "cursor": 48} + self.assertFalse(exact_equal(left, close)) + self.assertTrue(numeric_equal(left, close, atol=1e-7)) + self.assertFalse(numeric_equal(left, wrong, atol=1e-7)) + close["cursor"] = 49 + self.assertFalse(numeric_equal(left, close, atol=1e-7)) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/train_expert.py b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/train_expert.py new file mode 100644 index 0000000000000000000000000000000000000000..656e925d2bcc5c602e3abd8cfd3ca2ecb1b4e6b4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/s4_modality_experts/train_expert.py @@ -0,0 +1,265 @@ +"""Full, independent S4-initialized experts on the unchanged filtered native GT.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from contextlib import nullcontext +from datetime import timedelta +import json +import hashlib +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader + +from common import (CONFIG, PARENT, ROOT, ExpertCoverage, ExpertDataset, base, + code_hashes, dump, exact_equal, frozen_fingerprint, mode_and_supervision, model_for) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--expert", choices=("K", "D"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--smoke", action="store_true") + args = parser.parse_args() + if not 0 < args.updates <= CONFIG["updates"]: + raise ValueError("endpoint exceeds registered budget") + rank, world = int(os.environ.get("RANK", 0)), int(os.environ.get("WORLD_SIZE", 1)) + local = int(os.environ.get("LOCAL_RANK", 0)) + if CONFIG["global_batch"] % world: + raise ValueError("world size must divide the registered global batch") + accumulation = CONFIG["global_batch"] // world + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.cuda.set_device(local) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device("cuda", local) + if world > 1: + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + if shutil.disk_usage(ROOT).free < 200 * 1024**3: + raise RuntimeError("experiment disk reserve below 200 GiB") + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh run would overwrite existing metrics") + if world > 1: + dist.barrier(device_ids=[local]) + seed = CONFIG["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + hashes = code_hashes() + model = model_for(args.expert).to(device) + model.train() + frozen = frozen_fingerprint(model) + parameters = [p for p in model.parameters() if p.requires_grad] + backbone_lr = CONFIG["depth_backbone_learning_rate"] if args.expert == "D" else None + optimizer = torch.optim.AdamW(base.optimizer_parameter_groups( + model, learning_rate=CONFIG["learning_rate"], backbone_learning_rate=backbone_lr, + ), weight_decay=CONFIG["weight_decay"]) + sources, supervision = Counter(), Counter() + input_checksums = [] + start = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False) + if (state["expert"] != args.expert or state["world_size"] != world + or state["code_sha256"] != hashes or state["smoke"] != args.smoke + or state["parent_sha256"] != CONFIG["parent_sha256"] + or state["global_batch"] != CONFIG["global_batch"]): + raise RuntimeError("exact expert resume contract mismatch") + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + if not exact_equal(optimizer.state_dict(), state["optimizer"]): + raise RuntimeError("optimizer restoration changed checkpoint buffers") + start = state["update"] + if state["next_global_sample_position"] != start * CONFIG["global_batch"]: + raise RuntimeError("resume sample cursor mismatch") + if state["frozen_fingerprint"] != frozen or frozen_fingerprint(model) != frozen: + raise RuntimeError("frozen tensors changed in resumed expert") + sources.update(state["source_exposure"]) + supervision.update(state["supervision_exposure"]) + base.restore_rng(state["rank_rng_states"][rank], device) + if not exact_equal(base.rng_state(device), state["rank_rng_states"][rank]): + raise RuntimeError("RNG restoration differs from the checkpoint") + input_checksums = state.get("input_checksums", []) + del state + if not start < args.updates: + raise ValueError("resume is already at the requested endpoint") + dataset = ExpertDataset(args.expert) + coverage = ExpertCoverage(base.INDEX, args.expert) + sampler = base.PositionSampler(coverage, start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(dataset, batch_size=1, sampler=sampler, + num_workers=CONFIG["workers_per_rank"], + persistent_workers=CONFIG["workers_per_rank"] > 0, + collate_fn=base.collate_h2o_clips, pin_memory=True, + generator=torch.Generator().manual_seed(seed + 1000000)) + objective = base.Objective(model).to(device) + if world > 1: + objective = DDP(objective, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=True) + if rank == 0: + provenance = { + "expert": args.expert, "parent": str(PARENT), + "parent_sha256": CONFIG["parent_sha256"], "complete_backbone": True, + "code_sha256": hashes, "world_size": world, "global_batch": CONFIG["global_batch"], + "accumulation": accumulation, "precision": "bf16", "tf32": False, + "devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "trainable_parameters": sum(p.numel() for p in parameters), + "trainable_names": [n for n, p in model.named_parameters() if p.requires_grad], + "frozen_fingerprint": frozen, "loss": vars(base.LOSS), "smoke": args.smoke, + } + dump(args.output / f"provenance_from_{start:07d}.json", provenance) + log = (args.output / "metrics.jsonl").open("a", buffering=1) + iterator = iter(loader) + torch.cuda.reset_peak_memory_stats(device) + clock = time.monotonic() + + def save(update): + local_rng = base.rng_state(device) + states = [None] * world if rank == 0 else None + if world > 1: + dist.gather_object(local_rng, states, dst=0) + else: + states = [local_rng] + if frozen_fingerprint(model) != frozen: + raise RuntimeError("an expert changed frozen tensors") + if rank == 0: + if shutil.disk_usage(ROOT).free < 200 * 1024**3: + raise RuntimeError("checkpoint would violate the 200 GiB disk reserve") + if base.sha(PARENT) != CONFIG["parent_sha256"]: + raise RuntimeError("RGB parent file changed during training") + path = args.output / f"update_{update:07d}.pt" + if path.exists(): + raise FileExistsError(path) + state = { + "model": model.state_dict(), "optimizer": optimizer.state_dict(), + "expert": args.expert, "update": update, "world_size": world, + "global_batch": CONFIG["global_batch"], "precision": "bf16", + "next_global_sample_position": update * CONFIG["global_batch"], + "parent_sha256": CONFIG["parent_sha256"], "complete_backbone": True, + "code_sha256": hashes, "source_exposure": dict(sources), + "supervision_exposure": dict(supervision), "rank_rng_states": states, + "frozen_fingerprint": frozen, "smoke": args.smoke, "config": CONFIG, + "input_checksums": input_checksums, + } + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + temporary.replace(path) + loaded = torch.load(path, map_location="cpu", weights_only=False) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("complete checkpoint load-back failed") + dump(path.with_suffix(".json"), {"checkpoint": str(path), "sha256": base.sha(path), + "expert": args.expert, "update": update, + "consumed_clips": update * CONFIG["global_batch"], + "source_exposure": dict(sources), "supervision_exposure": dict(supervision), + "complete_backbone": True, "frozen_state_unchanged": True}) + if world > 1: + dist.barrier(device_ids=[local]) + + for update in range(start, args.updates): + lr = base.warmup_cosine_learning_rate(update * CONFIG["global_batch"], + CONFIG["updates"] * CONFIG["global_batch"], CONFIG["learning_rate"], + CONFIG["min_learning_rate"], CONFIG["warmup_clips"]) + base.set_scheduled_learning_rate(optimizer, lr) + optimizer.zero_grad(set_to_none=True) + total = torch.zeros((), device=device) + local_sources, local_supervision = Counter(), Counter() + local_checksums = [] + details = defaultdict(Counter) + detailed = update < 5 or (update + 1) % 100 == 0 or update + 1 == args.updates + for micro in range(accumulation): + cpu = next(iterator) + source, masks = mode_and_supervision(cpu, args.expert) + if args.smoke: + digest = hashlib.sha256() + for key in ("rgb", "depth_m", "K", "frame_valid", "depth_pixel_valid", + "joint2d", "joint3d_camera", "wrist_root_translation", + *base.MASK_FIELDS): + if key in cpu and torch.is_tensor(cpu[key]): + digest.update(key.encode()) + digest.update(cpu[key].contiguous().reshape(-1).view(torch.uint8).numpy().tobytes()) + local_checksums.append({"position": update * CONFIG["global_batch"] + micro * world + rank, + "source": source, "sha256": digest.hexdigest()}) + local_sources[source] += 1 + local_supervision.update(masks) + batch = base.move_to_device(cpu, device) + base.attach_gt_vertices(batch, model) + sync = objective.no_sync() if world > 1 and micro + 1 < accumulation else nullcontext() + with sync, torch.autocast("cuda", dtype=torch.bfloat16): + losses = objective(batch) + if not torch.isfinite(losses["total"]): + raise RuntimeError(f"nonfinite loss at update {update + 1}") + (losses["total"] / accumulation).backward() + total += losses["total"].detach() / accumulation + if detailed: + details[source].update({name: float(losses[name].detach()) + for name in base.MONITORED_LOSSES + base.TRANSLATION_DIAGNOSTICS}) + details[source]["samples"] += 1 + groups = base.gradient_group_norms(model) if detailed and rank == 0 else None + norm = torch.nn.utils.clip_grad_norm_(parameters, CONFIG["grad_clip"]) + if not torch.isfinite(norm): + raise RuntimeError(f"nonfinite gradients at update {update + 1}") + optimizer.step() + values = [{"sources": dict(local_sources), "supervision": dict(local_supervision), + "details": dict(details), "input_checksums": local_checksums}] + if world > 1: + dist.all_reduce(total) + values = [None] * world + dist.all_gather_object(values, {"sources": dict(local_sources), + "supervision": dict(local_supervision), "details": dict(details), + "input_checksums": local_checksums}) + for item in values: + sources.update(item["sources"]) + supervision.update(item["supervision"]) + input_checksums.extend(sorted((row for item in values for row in item["input_checksums"]), + key=lambda row: row["position"])) + if rank == 0: + row = {"expert": args.expert, "update": update + 1, + "consumed_clips": (update + 1) * CONFIG["global_batch"], + "loss": float(total / world), "grad_norm": float(norm), + "clipped": float(norm) > CONFIG["grad_clip"], "lr": lr, + "source_exposure": dict(sources), "grad_groups": groups, + "elapsed_seconds": time.monotonic() - clock} + if detailed: + combined = defaultdict(Counter) + for item in values: + for source, terms in item["details"].items(): + combined[source].update(terms) + row["weighted_source_loss_terms"] = { + source: {key: value / terms["samples"] for key, value in terms.items() + if key != "samples"} for source, terms in combined.items()} + log.write(json.dumps(row, allow_nan=False) + "\n") + if detailed or (update + 1) % 500 == 0: + print(json.dumps(row, allow_nan=False), flush=True) + if update + 1 == args.updates or (update + 1) % 417 == 0: + save(update + 1) + if rank == 0: + log.close() + dump(args.output / "summary.json", {"expert": args.expert, "updates": args.updates, + "consumed_clips": args.updates * CONFIG["global_batch"], + "source_exposure": dict(sources), "elapsed_seconds": time.monotonic() - clock, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 1024**3, + "all_losses_and_gradients_finite": True, "frozen_state_unchanged": True}) + finally: + if world > 1 and dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/DEPTHSAFE_CONTRACT_20261001.md b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/DEPTHSAFE_CONTRACT_20261001.md new file mode 100644 index 0000000000000000000000000000000000000000..e6cc24b76bb0035150af5609014a21a9ee554ec2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/DEPTHSAFE_CONTRACT_20261001.md @@ -0,0 +1,9 @@ +# U0 RGB Depth-Safe Reprojection Continuation + +2026-10-01. The previous convergence run stopped after update 1975 because a supervised predicted MANO joint had nonpositive camera Z. The most recent complete checkpoint is update 1900, SHA256 `79068a50e45df40537208d3e607416cb27b0f6c975f441f242ab8fb7bead1c9d`. This version resumes its complete model, AdamW moments, six-rank RNG and source-coverage cursor. Old artifacts are preserved read-only. + +The only intended optimization change is the reprojection loss for predicted joints nearer than 5 cm to the camera. For all GT-valid reprojection joints, use the original L1 normalized-pixel error with `z_safe = max(z_pred, 0.05 m)` and add `10 * max(0, 0.05 m - z_pred)` per joint. Normal predictions with `z_pred >= 0.05 m` must match the previous loss to floating-point tolerance. GT validity still determines the denominator, so a joint cannot escape 2D supervision by crossing behind the camera; the barrier supplies a forward-Z gradient below the floor. Any nonfinite supervised prediction or target remains a hard error. + +No change to RGB MoT, frozen DINO/MANO, V3 refit GT, original 2D targets, source quotas 21/15/24, optimizer groups/moments, full 1,200,240-clip schedule, or source-native benchmark metrics. This is a versioned loss amendment, not an equivalent continuation of the previous loss past update 1900. New checkpoints include the new code/config hashes; the old update-1900 SHA and unrelated functional file hashes are checked before GPU work. + +Preflight: pure positive-Z parity and negative-Z finite-gradient unit tests; one real H2O/ARCTIC/HOT3D BF16 forward/backward; six-rank replay through update 1977, crossing the prior failure at update 1976. Log every nonpositive reprojection occurrence with source, tile, rank, update, count and minimum predicted joint Z. Then continue the registered development milestones 2400, 3200, 4800, 6400, 8000, 10000, 12000, 16000, 20004. Do not start U1 automatically. Use the original and continued source-native development records together for selection; only a passing checkpoint receives one frozen confirmation pass. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/EXTENDED_RGB_CONTRACT.md b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/EXTENDED_RGB_CONTRACT.md new file mode 100644 index 0000000000000000000000000000000000000000..e64955809deaebdca9fd08c176f99b068c27856a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/EXTENDED_RGB_CONTRACT.md @@ -0,0 +1,20 @@ +# U0 RGB Convergence Extension + +2026-09-30. This extends the hash-bound 400-update U0 RGB pilot from its exact checkpoint. It does not change model, data, targets, loss, optimizer groups, source quotas, or the 1,200,240-clip cosine schedule. The only training-code changes are the registered endpoint limit and a one-time checkpoint lineage check. The parent 400-update checkpoint SHA256 is frozen in `config.json` before launch. + +## Metric and label contract + +The Foundation Hand primary table is camera-space Abs MPJPE (mm), root-relative MPJPE (mm), MPVPE (mm), and projected-MANO 2D keypoint error (px), in that order. Evaluate S4 and U0 on the same source-native GT, recording-disjoint panels, source masks and denominators. PA-MPJPE and the direct 2D head are auxiliary. Do not filter geometry metrics by predicted presence. + +Training retains the rotation-fixed corrected-left V3 refit for H2O/ARCTIC left, source-original right/HOT3D, native 2D reprojection targets, and the H2O independent native-joint diagnostic. No K/Depth input token, camera trajectory, visibility training or loss change enters this RGB stage. + +## Training and convergence + +- Continue from update 400 with all AdamW moments, rank RNG and coverage cursor; six G2 GPUs, global batch 60, source quota H2O/ARCTIC/HOT3D = 21/15/24. One full stage is capped at 20,004 updates = 1,200,240 clip exposures. +- Development checkpoints: updates 600, 1,000, 1,600, 2,400, 3,200, 4,800, 6,400, 8,000, 10,000, 12,000, 16,000 and 20,004. All three source-native panels and all four metrics are evaluated at each checkpoint. +- HOT3D has 143,657 indexed T8 tiles and receives 24 clips/update, so its first nominal full coverage takes approximately 5,986 updates. No plateau stop is allowed before the 6,400-update checkpoint. This is a coverage lower bound, not proof that the model has converged. +- Convergence diagnostic: after update 6,400, stop if three consecutive milestones fail to improve the best equal-source/equal-metric U0-to-S4 ratio by at least 1% relative. Keep per-source trends and paired recording-bootstrap intervals; a declining training loss alone is not convergence evidence. Otherwise continue to the full cap. +- Select the best development checkpoint, not the last. A formal RGB acceptance requires every source and every primary metric to be no more than 1% worse than matched S4 and its paired recording-bootstrap 95% upper delta to be within the same 1% tolerance. Record whether any metrics genuinely beat S4; the goal is improvement, not merely approximate recovery. +- Do not start U1 automatically. If RGB plateaus below the acceptance gate, diagnose MoT mapping/attention and optimization before adding K/Depth. Run the already frozen confirmation panel once only if a selected development checkpoint passes the gate. + +All intermediate checkpoints and evaluations are diagnostic; they are not official validation or held-out test results. This extension is not evidence of MoT benefit until the above paired comparison supports it. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/common.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/common.py new file mode 100644 index 0000000000000000000000000000000000000000..aae8eeffcd7d952d1973e568b346d432f79a664f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/common.py @@ -0,0 +1,114 @@ +"""Hash-bound S4/V3 inputs for the unified RGB MoT pilot.""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +A7_ROOT = Path(CONFIG["a7_root"]) +sys.path.insert(1, str(A7_ROOT)) + +spec = importlib.util.spec_from_file_location("u0_a7_common", A7_ROOT / "common.py") +a7 = importlib.util.module_from_spec(spec) +spec.loader.exec_module(a7) +base = a7.base + +from filtered_dataset import intersect_filtered_valid +from model import MAPPING, convert_parent + + +def sha(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024**2), b""): + digest.update(block) + return digest.hexdigest() + + +def code_hashes() -> dict[str, str]: + return a7.code_hashes() | { + "unified_mot/" + path.name: sha(path) + for path in sorted(ROOT.glob("*.py")) + } | { + "unified_mot/config.json": sha(ROOT / "config.json"), + "unified_mot/U0_FROZEN_CONTRACT_20260930.md": sha( + ROOT.parent / "a7_mot_unified_design_20260929/U0_FROZEN_CONTRACT_20260930.md" + ), + } + + +def model_for(role: str): + if role not in ("student", "teacher"): + raise ValueError(role) + parent = a7.model_for("RGB") + if role == "teacher": + return parent.eval() + model = convert_parent(parent) + final_rgb = f"decoder.spatial.{len(model.decoder.spatial) - 1}.rgb." + final_unidentifiable = ("q.", "o.", "ffn_norm.", "ffn_in.", "ffn_out.") + for name, parameter in model.named_parameters(): + parameter.requires_grad_( + not name.startswith("rgb_encoder.backbone.") + and not name.startswith("mano_layer.") + and not (name.startswith(final_rgb) and name[len(final_rgb):].startswith(final_unidentifiable)) + ) + return model + + +class U0Coverage(a7.ExpertCoverage): + def __init__(self): + super().__init__(base.INDEX, "K") + + def sample(self, position): + spec = super().sample(position) + spec["mode"] = "rgb" + return spec + + +class U0Dataset(a7.reference.ExpertDataset): + def __init__(self): + super().__init__("K") + self.labels = { + source: a7.CanonicalLabels(source, dataset.rows) + for source, dataset in self.sources.items() + } + + def __getitem__(self, spec): + source = spec["source"] + original = self.sources[source] + sample = original[spec] + if sample["input_mode"] != "rgb": + raise RuntimeError("U0 data reader received a non-RGB mode") + native_joints = sample["joint3d_camera"].clone() + native_valid = sample["joint3d_valid"].clone() + row = original.rows[original.by_tile[spec["tile_id"]]] + sample = self.labels[source].apply(sample, row, original.native) + intersect_filtered_valid(sample, row) + quality = sample["vertices_valid"].bool() + sample["global_orientation_valid"] &= quality + sample["local_pose_valid"] &= quality + sample["source_native_joint3d_camera"] = native_joints + sample["source_native_joint3d_valid"] = native_valid + return sample + + +def validate_run_contract(): + if CONFIG["parent_sha256"] != a7.CONFIG["parent_sha256"]: + raise RuntimeError("U0 parent differs from audited A7 parent") + if CONFIG["target_contract"] != a7.CONFIG["target_contract"]: + raise RuntimeError("U0 target contract differs from audited V3 labels") + if CONFIG["metric_keys"] != [ + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", + ]: + raise RuntimeError("U0 primary benchmark metric order changed") + if CONFIG["global_batch"] != sum(CONFIG["source_quota_per_update"].values()): + raise RuntimeError("source quotas do not fill one update") + a7.code_hashes() + a7.load_parent() + return {"code_sha256": code_hashes(), "mapping": MAPPING} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/config.json new file mode 100644 index 0000000000000000000000000000000000000000..cf5d6350ee6e4d4a4590e056396569669a904433 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/config.json @@ -0,0 +1,39 @@ +{ + "experiment": "unified_mot_u0_20260930", + "a7_root": "/home/wuyifan/a7_canonical_gt_rotationfix_train_6gpu_20260930", + "parent_sha256": "85a9e02274f94b69e2a634518f6f46244dbedb518b135f07be4b2c746be9bb15", + "target_contract": "canonical_approximate_v3", + "metric_keys": [ + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "mpvpe_mm", + "projected_mano_2d_error_px" + ], + "auxiliary_metric_keys": ["pa_mpjpe_mm"], + "seed": 20260930, + "world_size": 6, + "global_batch": 60, + "pilot_clips": 24000, + "pilot_updates": 400, + "maximum_updates": 20004, + "continuation_update": 1900, + "continuation_checkpoint": "/home/wuyifan/unified_mot_u0_extended_20260930/runs/U0/update_0001900.pt", + "continuation_checkpoint_sha256": "79068a50e45df40537208d3e607416cb27b0f6c975f441f242ab8fb7bead1c9d", + "reprojection_depth_floor_m": 0.05, + "reprojection_depth_penalty_per_m": 10.0, + "full_stage_clips": 1200240, + "source_quota_per_update": {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}, + "learning_rate_new_mot": 0.00005, + "learning_rate_inherited": 0.00001, + "minimum_learning_rate_ratio": 0.1, + "warmup_clips": 1008, + "weight_decay": 0.05, + "grad_clip": 100.0, + "rgb_teacher_weight": 0.05, + "workers_per_rank": 2, + "minimum_free_disk_gib": 200, + "resume_model_atol": 0.00002, + "resume_head_exp_avg_atol": 0.025, + "resume_other_exp_avg_atol": 0.01, + "resume_exp_avg_sq_atol": 0.002 +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/continuation_controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/continuation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..a38a50a4b569f179ed5bd931d2949600355e131d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/continuation_controller.py @@ -0,0 +1,190 @@ +"""Non-preempting U0 RGB continuation after the depth-safe loss correction.""" + +from __future__ import annotations + +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time + +from common import CONFIG, ROOT, a7, sha, validate_run_contract +from lineage_check import check_parent +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, claim_physical_gpu, release_physical_gpu_claim, +) + + +MILESTONES = (2400, 3200, 4800, 6400, 8000, + 10000, 12000, 16000, 20004) +SOURCES = ("H2O", "ARCTIC", "HOT3D") + + +def event(name, **fields): + record = {"event": name, "time": time.strftime("%Y-%m-%dT%H:%M:%S%z"), + "controller_pid": os.getpid(), **fields} + a7.dump(ROOT / "state.json", record) + print(json.dumps(record, allow_nan=False), flush=True) + + +def reserve(): + claimed = [] + for gpu in range(CONFIG["world_size"]): + if not claim_physical_gpu(gpu): + break + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + break + claimed.append(gpu) + if len(claimed) != CONFIG["world_size"]: + for gpu in claimed: + release_physical_gpu_claim(gpu) + return [] + return claimed + + +def execute(label, argv, gpus): + logfile = ROOT / "logs" / (label + ".log") + logfile.parent.mkdir(exist_ok=True) + if logfile.exists(): + raise FileExistsError("existing continuation log: " + str(logfile)) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=",".join(map(str, gpus)), + OMP_NUM_THREADS="2", MKL_NUM_THREADS="2", OPENBLAS_NUM_THREADS="2", + PYTHONUNBUFFERED="1") + if "FH_A7_TEST_CODE" in environment: + raise RuntimeError("test-code override cannot launch U0") + with logfile.open("xb") as output: + child = subprocess.Popen([sys.executable, "-u", *argv], cwd=ROOT, env=environment, + stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT) + event("running", stage=label, child_pid=child.pid, gpus=gpus, log=str(logfile)) + result = child.wait() + if result: + raise RuntimeError(f"U0 {label} failed with exit {result}; inspect {logfile}") + + +def train(endpoint, previous, gpus): + output = ROOT / "runs/U0" + execute(f"train_{endpoint:05d}", ["-m", "torch.distributed.run", "--standalone", + "--nproc_per_node=6", str(ROOT / "train.py"), "--output", str(output), + "--updates", str(endpoint), "--resume", str(previous)], gpus) + checkpoint = output / f"update_{endpoint:07d}.pt" + if not checkpoint.is_file(): + raise FileNotFoundError(checkpoint) + return checkpoint + + +def evaluate(endpoint, checkpoint, source, role, gpu): + path = ROOT / "evaluations" / f"u0_{endpoint:07d}_{role}_{source}.json" + path.parent.mkdir(exist_ok=True) + evaluator = checkpoint.parents[2] / "evaluate.py" + execute(f"eval_{role}_{endpoint:05d}_{source}", [str(evaluator), + "--checkpoint", str(checkpoint), "--source", source, "--role", role, + "--output", str(path)], [gpu]) + record = json.loads(path.read_text()) + if record["source"] != source or record["update"] != endpoint: + raise RuntimeError("evaluation source/update differs from selected checkpoint") + return record + + +def gate(records): + scores, details = [], {} + for record in records: + checks = {} + for metric in CONFIG["metric_keys"]: + parent = record["summary"]["S4_RGB"][metric]["mean"] + student = record["summary"]["U0_RGB"][metric]["mean"] + upper_delta = record["paired"][metric]["recording_bootstrap_95ci"][1] + ratio = student / parent + checks[metric] = {"S4": parent, "U0": student, "ratio": ratio, + "paired_95ci_upper_delta": upper_delta, + "pass": ratio <= 1.01 and upper_delta <= 0.01 * parent, + "better_than_s4": ratio < 1.0 and upper_delta < 0.0} + scores.append(ratio) + details[record["source"]] = checks + return {"pass": len(details) == len(SOURCES) + and all(item["pass"] for row in details.values() for item in row.values()), + "equal_source_metric_ratio": sum(scores) / len(scores), "sources": details} + + +def main(): + lock = (ROOT / "continuation.lock").open("a") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + gpus = [] + try: + registered = validate_run_contract() + lineage = check_parent() + parent = Path(CONFIG["continuation_checkpoint"]) + if not parent.is_file() or sha(parent) != CONFIG["continuation_checkpoint_sha256"]: + raise RuntimeError("update-1900 checkpoint is absent or has wrong SHA256") + if shutil.disk_usage(ROOT).free < CONFIG["minimum_free_disk_gib"] * 1024**3: + raise RuntimeError("insufficient U0 continuation disk reserve") + contract = ROOT / "DEPTHSAFE_CONTRACT_20261001.md" + a7.dump(ROOT / "registration.json", {"config": CONFIG, + "code_sha256": registered["code_sha256"], "mapping": registered["mapping"], + "contract_sha256": sha(contract), "continuation_checkpoint_sha256": sha(parent), + "lineage_audit": lineage, + "parent_unchanged": True, "A7_unchanged": True}) + execute("unit_tests", ["-m", "unittest", "discover", "-p", "test_*.py", "-v"], []) + while not gpus: + gpus = reserve() + if not gpus: + event("waiting_for_six_idle_gpus", non_preempting=True) + time.sleep(30) + execute("real_source_gpu_smoke", [str(ROOT / "gpu_smoke.py")], gpus[:1]) + previous = train(1977, parent, gpus) + event("failed_batch_replayed_with_depth_safe_loss", checkpoint=str(previous)) + old_root = parent.parents[2] + candidates = json.loads((old_root / "development_gates.json").read_text()) + if [item["update"] for item in candidates] != [400, 600, 1000, 1600]: + raise RuntimeError("prior U0 development milestones changed") + a7.dump(ROOT / "development_gates.json", candidates) + best_meaningful = min(item["gate"]["equal_source_metric_ratio"] for item in candidates) + stale = 0 + for endpoint in MILESTONES: + previous = train(endpoint, previous, gpus) + records = [evaluate(endpoint, previous, source, "development", gpus[0]) + for source in SOURCES] + result = gate(records) + score = result["equal_source_metric_ratio"] + if score <= best_meaningful * 0.99: + best_meaningful, stale = score, 0 + elif endpoint >= 6400: + stale += 1 + candidate = {"update": endpoint, "checkpoint": str(previous), + "gate": result, "stale_milestones": stale} + candidates.append(candidate) + a7.dump(ROOT / "development_gates.json", candidates) + event("milestone_evaluated", update=endpoint, gate_pass=result["pass"], + equal_source_metric_ratio=score, stale_milestones=stale) + if endpoint >= 6400 and stale >= 3: + break + selected = min(candidates, key=lambda item: item["gate"]["equal_source_metric_ratio"]) + a7.dump(ROOT / "selection.json", {"selected": selected, + "last_update": candidates[-1]["update"], "plateau": stale >= 3, + "development_only": True}) + if not selected["gate"]["pass"]: + event("rgb_convergence_gate_failed_no_u1", selected_update=selected["update"], + last_update=candidates[-1]["update"], plateau=stale >= 3) + return + confirmation = [evaluate(selected["update"], Path(selected["checkpoint"]), source, + "confirmation", gpus[0]) for source in SOURCES] + confirmed = gate(confirmation) + a7.dump(ROOT / "confirmation.json", {"selected": selected, + "sources": confirmation, "gate": confirmed}) + event("rgb_convergence_complete_no_automatic_u1", selected_update=selected["update"], + last_update=candidates[-1]["update"], confirmation_gate=confirmed["pass"]) + except BaseException as error: + event("failed_requires_diagnosis", error=repr(error)) + raise + finally: + for gpu in gpus: + release_physical_gpu_claim(gpu) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8c69825c2d51bad1ca535c1c2f86e10302fe47 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/controller.py @@ -0,0 +1,209 @@ +"""Non-preempting six-GPU U0 pilot with fail-closed RGB benchmark gate.""" + +from __future__ import annotations + +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time + +import torch + +from common import CONFIG, ROOT, a7, code_hashes, sha, validate_run_contract +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, claim_physical_gpu, release_physical_gpu_claim, +) + + +def event(name, **fields): + record = {"event": name, "time": time.strftime("%Y-%m-%dT%H:%M:%S%z"), + "controller_pid": os.getpid(), **fields} + a7.dump(ROOT / "state.json", record) + print(json.dumps(record, allow_nan=False), flush=True) + + +def reserve(): + claimed = [] + for gpu in range(CONFIG["world_size"]): + if not claim_physical_gpu(gpu): + break + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + break + claimed.append(gpu) + if len(claimed) != CONFIG["world_size"]: + for gpu in claimed: + release_physical_gpu_claim(gpu) + return [] + return claimed + + +def execute(label, argv, gpus): + logfile = ROOT / "logs" / (label + ".log") + logfile.parent.mkdir(exist_ok=True) + if logfile.exists(): + raise FileExistsError("existing U0 stage log: " + str(logfile)) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=",".join(map(str, gpus)), + OMP_NUM_THREADS="2", MKL_NUM_THREADS="2", OPENBLAS_NUM_THREADS="2", + PYTHONUNBUFFERED="1") + if "FH_A7_TEST_CODE" in environment: + raise RuntimeError("test-code override cannot launch U0") + with logfile.open("xb") as output: + child = subprocess.Popen([sys.executable, "-u", *argv], cwd=ROOT, env=environment, + stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.STDOUT) + event("running", stage=label, child_pid=child.pid, gpus=gpus, log=str(logfile)) + result = child.wait() + if result: + raise RuntimeError(f"U0 {label} failed with exit {result}; inspect {logfile}") + + +def train(label, updates, gpus, output, *, resume=None, smoke=False): + argv = ["-m", "torch.distributed.run", "--standalone", "--nproc_per_node=6", + str(ROOT / "train.py"), "--output", str(output), "--updates", str(updates)] + if resume: + argv.extend(("--resume", str(resume))) + if smoke: + argv.append("--smoke") + execute(label, argv, gpus) + return output / f"update_{updates:07d}.pt" + + +def compare_resume(continuous, resumed): + left, right = (torch.load(path, map_location="cpu", weights_only=False) + for path in (continuous, resumed)) + for key in ("update", "next_global_sample_position", "source_exposure", "code_sha256", + "parent_sha256", "target_contract", "metric_keys", "frozen_fingerprint", + "input_checksums", "optimizer_parameter_names"): + if not a7.reference.exact_equal(left[key], right[key]): + raise RuntimeError("U0 resumed state changed " + key) + if not a7.reference.exact_equal(left["rank_rng_states"], right["rank_rng_states"]): + raise RuntimeError("U0 resumed rank RNG states changed") + maxima = {} + for key, value in left["model"].items(): + difference = float((value.float() - right["model"][key].float()).abs().max()) + maxima[key] = difference + if difference > CONFIG["resume_model_atol"]: + raise RuntimeError(f"U0 resume model tensor {key} differs by {difference}") + optimizer_maxima = {} + names = left["optimizer_parameter_names"] + for index, values in left["optimizer"]["state"].items(): + for key, value in values.items(): + expected = right["optimizer"]["state"][index][key] + if not torch.is_tensor(value): + if value != expected: + raise RuntimeError("U0 resume optimizer scalar changed") + continue + difference = float((value.float() - expected.float()).abs().max()) + optimizer_maxima[f"{names[index]}:{key}"] = difference + if key == "exp_avg": + limit = (CONFIG["resume_head_exp_avg_atol"] if names[index].startswith( + ("rotation_head.", "translation_head.", "shape_head.", "joint2d_head.")) + else CONFIG["resume_other_exp_avg_atol"]) + elif key == "exp_avg_sq": + limit = CONFIG["resume_exp_avg_sq_atol"] + else: + limit = 0.0 + if difference > limit: + raise RuntimeError(f"U0 resume optimizer {names[index]}:{key} differs by {difference}") + a7.dump(ROOT / "preflight/resume.json", { + "status": "pass", "model_max_abs": max(maxima.values()), + "optimizer_max_abs": max(optimizer_maxima.values()), + "rng_cursor_inputs_exact": True, "not_bitwise_equivalent": True, + "limits": {key: CONFIG[key] for key in CONFIG if key.startswith("resume_")}, + }) + + +def evaluate(label, checkpoint, source, role, gpu): + update = int(checkpoint.stem.split("_")[-1]) + path = ROOT / "evaluations" / f"u0_{update:07d}_{role}_{source}.json" + path.parent.mkdir(exist_ok=True) + execute(label, [str(ROOT / "evaluate.py"), "--checkpoint", str(checkpoint), + "--source", source, "--role", role, "--output", str(path)], [gpu]) + return json.loads(path.read_text()) + + +def development_gate(records): + scores, gates = [], {} + for record in records: + ratios = [] + checks = {} + for metric in CONFIG["metric_keys"]: + parent = record["summary"]["S4_RGB"][metric]["mean"] + child = record["summary"]["U0_RGB"][metric]["mean"] + upper = record["paired"][metric]["recording_bootstrap_95ci"][1] + ratio = child / parent + checks[metric] = {"S4": parent, "U0": child, "ratio": ratio, + "paired_95ci_upper_delta": upper, + "pass": ratio <= 1.01 and upper <= 0.01 * parent} + ratios.append(ratio) + gates[record["source"]] = checks + scores.extend(ratios) + return {"pass": len(gates) == 3 and all(item["pass"] for row in gates.values() for item in row.values()), + "equal_source_metric_ratio": sum(scores) / len(scores), "sources": gates} + + +def main(): + lock = (ROOT / "controller.lock").open("a") + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + gpus = [] + try: + registered = validate_run_contract() + if shutil.disk_usage(ROOT).free < CONFIG["minimum_free_disk_gib"] * 1024**3: + raise RuntimeError("insufficient U0 disk reserve") + a7.dump(ROOT / "registration.json", {"config": CONFIG, "code_sha256": registered["code_sha256"], + "mapping": registered["mapping"], + "parent_unchanged": True, "A7_unchanged": True}) + execute("unit_tests", ["-m", "unittest", "discover", "-p", "test_*.py", "-v"], []) + while not gpus: + gpus = reserve() + if not gpus: + event("waiting_for_six_idle_gpus", non_preempting=True) + time.sleep(30) + execute("real_source_gpu_smoke", [str(ROOT / "gpu_smoke.py")], gpus[:1]) + continuous = train("resume_continuous_4", 4, gpus, ROOT / "preflight/continuous", smoke=True) + split = train("resume_split_2", 2, gpus, ROOT / "preflight/split", smoke=True) + resumed = train("resume_split_4", 4, gpus, ROOT / "preflight/split", resume=split, smoke=True) + compare_resume(continuous, resumed) + if code_hashes() != registered["code_sha256"]: + raise RuntimeError("U0 implementation changed after preflight") + event("preflight_pass_starting_24k_pilot", gpus=gpus) + previous = None + candidates = [] + for endpoint in (100, 200, CONFIG["pilot_updates"]): + previous = train(f"pilot_train_{endpoint:04d}", endpoint, gpus, ROOT / "runs/U0", resume=previous) + records = [evaluate(f"eval_{endpoint:04d}_{source}", previous, source, "development", gpus[0]) + for source in ("H2O", "ARCTIC", "HOT3D")] + gate = development_gate(records) + candidates.append({"update": endpoint, "checkpoint": str(previous), "gate": gate}) + a7.dump(ROOT / "development_gates.json", candidates) + event("pilot_milestone_evaluated", update=endpoint, gate_pass=gate["pass"], + equal_source_metric_ratio=gate["equal_source_metric_ratio"]) + eligible = [candidate for candidate in candidates if candidate["gate"]["pass"]] + if not eligible: + event("u0_gate_failed_no_u1", results=str(ROOT / "development_gates.json")) + return + selected = min(eligible, key=lambda row: row["gate"]["equal_source_metric_ratio"]) + frozen = Path(selected["checkpoint"]) + confirmation = [evaluate(f"confirmation_{source}", frozen, source, "confirmation", gpus[0]) + for source in ("H2O", "ARCTIC", "HOT3D")] + a7.dump(ROOT / "confirmation.json", {"selected": selected, "sources": confirmation, + "gate": development_gate(confirmation)}) + event("u0_pilot_complete", selected_update=selected["update"], + confirmation_gate=development_gate(confirmation)["pass"], + results=str(ROOT / "confirmation.json")) + except BaseException as error: + event("failed_requires_diagnosis", error=repr(error)) + raise + finally: + for gpu in gpus: + release_physical_gpu_claim(gpu) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/evaluate.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..35b8f364c185878bf23a1c51ef70d1f953f7a027 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/evaluate.py @@ -0,0 +1,129 @@ +"""Matched native-GT four-metric development evaluation for unified MoT U0.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +import math +from pathlib import Path + +import numpy as np +import torch + +from common import CONFIG, ROOT, a7, base, code_hashes, model_for, sha +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from scripts.evaluate_phase7_external import aggregate, make_row +from targets import NativePanel + + +def paired(parent: list[dict], child: list[dict]) -> dict: + if len(parent) != len(child): + raise RuntimeError("U0 and S4 evaluation row counts differ") + result = {} + for metric in CONFIG["metric_keys"]: + recordings = defaultdict(list) + for left, right in zip(parent, child): + if any(left[key] != right[key] for key in ("physical_recording_id", "frame_id", "side")): + raise RuntimeError("U0/S4 row alignment changed") + if math.isfinite(left[metric]) != math.isfinite(right[metric]): + raise RuntimeError("U0/S4 GT-defined denominator changed: " + metric) + if math.isfinite(left[metric]): + recordings[left["physical_recording_id"]].append(right[metric] - left[metric]) + if not recordings: + raise RuntimeError("empty U0 development metric: " + metric) + sums = np.asarray([sum(values) for values in recordings.values()]) + counts = np.asarray([len(values) for values in recordings.values()]) + rng = np.random.default_rng(CONFIG["seed"]) + draws = rng.integers(0, len(sums), size=(2000, len(sums))) + bootstrap = sums[draws].sum(axis=1) / counts[draws].sum(axis=1) + result[metric] = {"delta": float(sums.sum() / counts.sum()), + "recording_bootstrap_95ci": np.quantile(bootstrap, [0.025, 0.975]).tolist(), + "count": int(counts.sum()), "recordings": len(recordings)} + return result + + +def finite(value): + if isinstance(value, dict): + return {key: finite(item) for key, item in value.items()} + if isinstance(value, list): + return [finite(item) for item in value] + return None if isinstance(value, float) and not math.isfinite(value) else value + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--role", choices=("development", "confirmation"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--limit", type=int) + args = parser.parse_args() + if args.output.exists() or (args.limit is not None and not args.smoke): + raise RuntimeError("existing evaluation output or unmarked subset") + if tuple(CONFIG["metric_keys"]) != tuple(FOUR_METRICS): + raise RuntimeError("U0 metrics differ from Foundation Hand four-metric benchmark") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if (state["experiment"] != CONFIG["experiment"] or state["code_sha256"] != code_hashes() + or state["parent_sha256"] != CONFIG["parent_sha256"] + or state["metric_keys"] != CONFIG["metric_keys"] or state["smoke"] != args.smoke + or not state["complete_backbone"]): + raise RuntimeError("U0 checkpoint composition/metric contract mismatch") + if args.role == "confirmation" and state["update"] > CONFIG["pilot_updates"]: + raise RuntimeError("confirmation candidate exceeds registered pilot") + student = model_for("student") + student.load_state_dict(state["model"], strict=True) + student.to("cuda").eval() + parent = model_for("teacher").to("cuda").eval() + panel_root = a7.BASE_ROOT / "eval/frozen_panels_sync_v2" + panels = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_{args.role}_t8.jsonl" + registered = panels["sources"][args.source][args.role] + if sha(manifest) != registered["manifest_sha256"] or panels["sources"][args.source]["train_overlap"]: + raise RuntimeError("evaluation panel isolation/hash mismatch") + rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), hand_valid_policy="visible_mesh") + if args.source == "ARCTIC" else dataset_for(args.source, manifest)) + dataset = NativePanel(args.source, native, rows) + limit = min(args.limit, len(dataset)) if args.limit is not None else len(dataset) + output_rows = {"S4_RGB": [], "U0_RGB": []} + with torch.inference_mode(): + for index in range(limit): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, "rgb") + batch = base.move_to_device(batch, torch.device("cuda")) + with torch.autocast("cuda", dtype=torch.bfloat16): + predictions = {"S4_RGB": parent(batch), "U0_RGB": student(batch)} + for label, prediction in predictions.items(): + if not bool(torch.isfinite(prediction["joints_camera"]).all()): + raise RuntimeError("nonfinite U0/S4 evaluation prediction") + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + output_rows[label].append(make_row(prediction, batch, 0, frame, side)) + if (index + 1) % 32 == 0: + print(json.dumps({"source": args.source, "role": args.role, + "done": index + 1, "total": limit}), flush=True) + summaries = {key: aggregate(value) for key, value in output_rows.items()} + report = {"source": args.source, "role": args.role, "input_mode": "rgb", "clips": limit, + "update": state["update"], "checkpoint_sha256": sha(args.checkpoint), + "native_GT_not_refitted": True, "presence_filter_for_metrics": False, + "metric_keys": CONFIG["metric_keys"], "metric_units": ["mm", "mm", "mm", "px"], + "panel_sha256": sha(manifest), "paired": paired(output_rows["S4_RGB"], output_rows["U0_RGB"]), + "summary": {key: {metric: value[metric] for metric in (*CONFIG["metric_keys"], "pa_mpjpe_mm")} + for key, value in summaries.items()}} + a7.dump(args.output, finite(report)) + a7.dump(args.output.with_suffix(".rows.json"), finite(output_rows)) + print(json.dumps({"source": args.source, "role": args.role, "update": state["update"], + "S4_RGB": {key: report["summary"]["S4_RGB"][key]["mean"] for key in CONFIG["metric_keys"]}, + "U0_RGB": {key: report["summary"]["U0_RGB"][key]["mean"] for key in CONFIG["metric_keys"]}}, + allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/gpu_smoke.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/gpu_smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..f5b4c99a43eccacb6710688fd32acf784cb247f3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/gpu_smoke.py @@ -0,0 +1,49 @@ +"""One real V3 T8 clip through U0 and the frozen S4 teacher.""" + +import json + +import torch + +from common import U0Coverage, U0Dataset, a7, base, model_for, validate_run_contract +from loss_scaling import TERMS, element_counts +from train import Objective + + +def main(): + validate_run_contract() + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + student = model_for("student").to("cuda").train() + teacher = model_for("teacher").to("cuda").eval() + dataset = U0Dataset() + results = [] + for source in ("H2O", "ARCTIC", "HOT3D"): + coverage = U0Coverage() + position = next(position for position in range(60) if coverage.sample(position)["source"] == source) + cpu = base.collate_h2o_clips([dataset[coverage.sample(position)]]) + counts = element_counts(cpu) + batch = base.move_to_device(cpu, torch.device("cuda")) + a7.validate_cached_geometry(batch, student) + student.zero_grad(set_to_none=True) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + coarse = teacher(batch) + with torch.autocast("cuda", dtype=torch.bfloat16): + output = Objective(student)(batch, coarse, {name: 1.0 for name in TERMS}) + loss = output[0] + if not bool(torch.isfinite(loss)): + raise RuntimeError("nonfinite real-source U0 smoke loss") + loss.backward() + grad = student.decoder.spatial[0].rgb.k.weight.grad + if grad is None or not bool(torch.isfinite(grad).all()) or float(grad.abs().sum()) == 0: + raise RuntimeError("real-source U0 MoT has no finite RGB-key gradient") + results.append({"source": source, "loss": float(loss.detach()), + "native_joint_gap": float(output[4]), "valid_counts": counts, + "rgb_key_grad_norm": float(torch.linalg.vector_norm(grad)), + "peak_gib": torch.cuda.max_memory_allocated() / 1024**3}) + del cpu, batch, coarse, output, loss + print(json.dumps(results, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/lineage_check.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/lineage_check.py new file mode 100644 index 0000000000000000000000000000000000000000..70f00eee4b0373b930da92b085c2f86975b5d3ca --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/lineage_check.py @@ -0,0 +1,65 @@ +"""CPU-only integrity check for the U0 depth-safe loss continuation.""" + +from __future__ import annotations + +from pathlib import Path + +import torch + +from common import CONFIG, a7, code_hashes, model_for, sha + + +def check_parent() -> dict: + parent = Path(CONFIG["continuation_checkpoint"]) + if not parent.is_file() or sha(parent) != CONFIG["continuation_checkpoint_sha256"]: + raise RuntimeError("U0 continuation checkpoint path or SHA256 mismatch") + state = torch.load(parent, map_location="cpu", weights_only=False) + if not state["complete_backbone"] or state["smoke"]: + raise RuntimeError("U0 continuation parent is slim or smoke-only") + if state["update"] != CONFIG["continuation_update"] or state["global_batch"] != CONFIG["global_batch"]: + raise RuntimeError("U0 continuation cursor/batch mismatch") + if state["next_global_sample_position"] != state["update"] * state["global_batch"]: + raise RuntimeError("U0 pilot sample cursor mismatch") + expected_exposure = {source: count * state["update"] + for source, count in CONFIG["source_quota_per_update"].items()} + if state["source_exposure"] != expected_exposure: + raise RuntimeError("U0 pilot source coverage mismatch") + if state["parent_sha256"] != CONFIG["parent_sha256"] or state["target_contract"] != CONFIG["target_contract"]: + raise RuntimeError("U0 pilot S4/label lineage mismatch") + if state["metric_keys"] != CONFIG["metric_keys"]: + raise RuntimeError("U0 pilot benchmark contract mismatch") + for key, value in state["config"].items(): + if key not in ("continuation_checkpoint", "continuation_checkpoint_sha256") and CONFIG.get(key) != value: + raise RuntimeError("U0 continuation changed an unrelated training setting: " + key) + hashes = code_hashes() + allowed_changes = {"unified_mot/train.py", "unified_mot/config.json", + "unified_mot/lineage_check.py", "unified_mot/continuation_controller.py"} + for key, value in state["code_sha256"].items(): + if key not in allowed_changes and hashes.get(key) != value: + raise RuntimeError("U0 continuation changed an unrelated file: " + key) + student = model_for("student") + if set(state["model"]) != set(student.state_dict()): + raise RuntimeError("U0 pilot model state is not complete") + student.load_state_dict(state["model"], strict=True) + if a7.reference.frozen_fingerprint(student) != state["frozen_fingerprint"]: + raise RuntimeError("U0 pilot frozen backbone/MANO composition changed") + expected_names = ([name for name, parameter in student.named_parameters() + if parameter.requires_grad and name.startswith("decoder.spatial.")] + + [name for name, parameter in student.named_parameters() + if parameter.requires_grad and not name.startswith("decoder.spatial.")]) + if state["optimizer_parameter_names"] != expected_names: + raise RuntimeError("U0 pilot optimizer parameter order changed") + if len(state["rank_rng_states"]) != CONFIG["world_size"]: + raise RuntimeError("U0 pilot rank RNG count changed") + return {"checkpoint_sha256": sha(parent), "update": state["update"], + "complete_backbone": True, "model_tensors": len(state["model"]), + "dino_tensors": len([name for name in state["model"] + if name.startswith("rgb_encoder.backbone.")]), + "optimizer_parameters": len(expected_names), + "source_exposure": expected_exposure, + "model_and_optimizer_order_exact": True} + + +if __name__ == "__main__": + import json + print(json.dumps(check_parent(), allow_nan=False)) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/loss_scaling.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/loss_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..6122423258149c6547012cf83c1407975608f4d6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/loss_scaling.py @@ -0,0 +1,64 @@ +"""Exact source/item denominators for BimanualLoss with distributed accumulation.""" + +from __future__ import annotations + +import torch + + +SOURCES = ("H2O", "ARCTIC", "HOT3D") +TERMS = ( + "joint2d", "joint3d_camera", "joint3d_root_relative", "vertices_camera", + "local_pose", "global_orientation", "shape", "translation", "reprojection", + "temporal_velocity", "temporal_acceleration", "bimanual_relative_wrist", +) + + +def element_counts(batch: dict) -> dict[str, int]: + frame = batch["frame_valid"].bool() + joint2d = batch["joint2d_valid"].bool() & frame[..., None, None] + joint3d = batch["joint3d_valid"].bool() & frame[..., None, None] + relative = batch["joint3d_root_relative_valid"].bool() & frame[..., None, None] + hands = batch["translation_valid"].bool() & frame[..., None] + pose = batch["mano_pose_valid"].bool() & frame[..., None] + shape = batch["shape_valid"].bool() & frame[..., None] + vertices = batch["vertices_valid"].bool() & frame[..., None] + k_valid = batch["K_supervision_valid"].bool() & frame + reprojection = batch["reprojection_valid"].bool() & k_valid[..., None, None] + velocity = hands[:, 1:] & hands[:, :-1] + acceleration = velocity[:, 1:] & velocity[:, :-1] + counts = { + "joint2d": joint2d.sum() * 2, + "joint3d_camera": joint3d.sum() * 3, + "joint3d_root_relative": relative.sum() * 3, + "vertices_camera": vertices.sum() * 778 * 3, + "local_pose": pose.sum() * 15 * 9, + "global_orientation": pose.sum() * 9, + "shape": shape.any(dim=1).sum() * 10, + "translation": hands.sum() * 3, + "reprojection": reprojection.sum() * 2, + "temporal_velocity": velocity.sum() * 3, + "temporal_acceleration": acceleration.sum() * 3, + "bimanual_relative_wrist": hands.all(dim=-1).sum() * 3, + } + return {key: int(value) for key, value in counts.items()} + + +def scaling(source: str, counts: dict[str, int], global_counts: torch.Tensor, world: int) -> dict[str, float]: + index = SOURCES.index(source) + result = {} + for term_index, term in enumerate(TERMS): + denominator = int(global_counts[index, term_index]) + numerator = counts[term] + if numerator and not denominator: + raise RuntimeError("nonzero local mask with zero global denominator") + result[term] = world * numerator / (len(SOURCES) * denominator) if denominator else 0.0 + return result + + +def count_table(samples: list[tuple[str, dict[str, int]]], device: torch.device) -> torch.Tensor: + table = torch.zeros(len(SOURCES), len(TERMS), dtype=torch.long, device=device) + for source, counts in samples: + row = SOURCES.index(source) + for column, term in enumerate(TERMS): + table[row, column] += counts[term] + return table diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/model.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/model.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6c78ddc3e05d354fa30cf091c7ec0718996891 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/model.py @@ -0,0 +1,159 @@ +"""RGB/HAND unified MoT spatial decoder for the registered U0 pilot.""" + +from __future__ import annotations + +import copy + +import torch +from torch import nn +from torch.nn import functional as F +from torch.utils.checkpoint import checkpoint + + +class TypeExpert(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.attn_norm = nn.LayerNorm(dim) + self.q = nn.Linear(dim, dim) + self.k = nn.Linear(dim, dim) + self.v = nn.Linear(dim, dim) + self.o = nn.Linear(dim, dim) + self.ffn_norm = nn.LayerNorm(dim) + self.ffn_in = nn.Linear(dim, 4 * dim) + self.ffn_out = nn.Linear(4 * dim, dim) + + def finish(self, tokens: torch.Tensor, attention: torch.Tensor) -> torch.Tensor: + tokens = tokens + self.o(attention) + return tokens + self.ffn_out(F.gelu(self.ffn_in(self.ffn_norm(tokens)))) + + +def copy_projection(target: nn.Linear, source: nn.MultiheadAttention, part: int) -> None: + dim = target.out_features + with torch.no_grad(): + target.weight.copy_(source.in_proj_weight[part * dim:(part + 1) * dim]) + target.bias.copy_(source.in_proj_bias[part * dim:(part + 1) * dim]) + + +def initialize_expert(expert: TypeExpert, old, kind: str) -> None: + if kind == "RGB": + expert.attn_norm.load_state_dict(old.rgb_norm.state_dict()) + # Old RGB memory supplied K/V; its K projection is the closest available + # initialization for a newly active RGB query. + copy_projection(expert.q, old.rgb_attention, 1) + copy_projection(expert.k, old.rgb_attention, 1) + copy_projection(expert.v, old.rgb_attention, 2) + elif kind == "HAND": + expert.attn_norm.load_state_dict(old.query_norm.state_dict()) + copy_projection(expert.q, old.rgb_attention, 0) + copy_projection(expert.k, old.hand_attention, 1) + copy_projection(expert.v, old.hand_attention, 2) + else: + raise ValueError(kind) + expert.o.load_state_dict(old.rgb_attention.out_proj.state_dict()) + expert.ffn_norm.load_state_dict(old.ffn[0].state_dict()) + expert.ffn_in.load_state_dict(old.ffn[1].state_dict()) + expert.ffn_out.load_state_dict(old.ffn[3].state_dict()) + + +class MoTSpatialBlock(nn.Module): + def __init__(self, old, heads: int): + super().__init__() + dim = old.query_norm.normalized_shape[0] + if dim % heads: + raise ValueError("hidden dimension must divide attention heads") + self.heads = heads + self.rgb = TypeExpert(dim) + self.hand = TypeExpert(dim) + initialize_expert(self.rgb, old, "RGB") + initialize_expert(self.hand, old, "HAND") + + def forward(self, rgb: torch.Tensor, hand: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + if rgb.ndim != 3 or hand.ndim != 3 or rgb.shape[0] != hand.shape[0]: + raise ValueError("MoT expects aligned [frame,tokens,dim] RGB/HAND tensors") + normalized_rgb = self.rgb.attn_norm(rgb) + normalized_hand = self.hand.attn_norm(hand) + hand_count = hand.shape[1] + query = torch.cat((self.hand.q(normalized_hand), self.rgb.q(normalized_rgb)), dim=1) + key = torch.cat((self.hand.k(normalized_hand), self.rgb.k(normalized_rgb)), dim=1) + value = torch.cat((self.hand.v(normalized_hand), self.rgb.v(normalized_rgb)), dim=1) + batch, tokens, dim = query.shape + head_dim = dim // self.heads + + def split(x: torch.Tensor) -> torch.Tensor: + return x.reshape(batch, tokens, self.heads, head_dim).transpose(1, 2) + + attention = F.scaled_dot_product_attention(split(query), split(key), split(value)) + attention = attention.transpose(1, 2).reshape(batch, tokens, dim) + hand = self.hand.finish(hand, attention[:, :hand_count]) + rgb = self.rgb.finish(rgb, attention[:, hand_count:]) + return rgb, hand + + +class UnifiedRGBDecoder(nn.Module): + """Drop-in U0 decoder; K and depth are prohibited, not zero-token substitutes.""" + + def __init__(self, old, heads: int, gradient_checkpointing: bool = True): + super().__init__() + if old.mode != "alternating" or len(old.spatial) != len(old.temporal): + raise ValueError("U0 expects alternating S4 decoder") + self.spatial = nn.ModuleList(MoTSpatialBlock(layer, heads) for layer in old.spatial) + self.temporal = copy.deepcopy(old.temporal) + self.gradient_checkpointing = gradient_checkpointing + self.mode = "alternating" + # U0 reads only HAND tokens after the terminal block. Its final RGB + # query/output/FFN path has no supervised consumer and is not trainable. + terminal_rgb = self.spatial[-1].rgb + for module in (terminal_rgb.q, terminal_rgb.o, terminal_rgb.ffn_norm, + terminal_rgb.ffn_in, terminal_rgb.ffn_out): + module.requires_grad_(False) + + def forward(self, queries, rgb, depth, frame_valid, depth_available, side_bias): + if bool(depth_available.any()): + raise ValueError("U0 cannot receive depth input") + batch, time, hands, dim = queries.shape + if frame_valid.shape != (batch, time): + raise ValueError("frame validity does not match query sequence") + flat_rgb = rgb.reshape(batch * time, rgb.shape[2], dim) + hand = queries.reshape(batch * time, hands, dim) + for spatial, temporal in zip(self.spatial, self.temporal): + if self.training and self.gradient_checkpointing: + flat_rgb, hand = checkpoint(spatial, flat_rgb, hand, use_reentrant=False) + else: + flat_rgb, hand = spatial(flat_rgb, hand) + hand = hand.reshape(batch, time, hands, dim) + hand = hand * frame_valid[:, :, None, None].to(hand.dtype) + hand, _ = temporal(hand, frame_valid) + hand = hand.reshape(batch * time, hands, dim) + return hand.reshape(batch, time, hands, dim), {} + + +def convert_parent(parent, *, gradient_checkpointing: bool = True): + """Replace only the spatial topology; preserve compatible S4 state.""" + old = parent.decoder + parent.decoder = UnifiedRGBDecoder(old, parent.config.attention_heads, gradient_checkpointing) + parent.config.use_depth = False + parent.config.use_rays = False + parent.config.predict_presence = False + del parent.depth_encoder + del parent.ray_encoder + parent.presence_head = None + parent.rgb_encoder.backbone.requires_grad_(False) + parent.rgb_encoder.trainable_last_blocks = 0 + parent.rgb_encoder.frozen = True + parent.config.dinov3_trainable_last_blocks = 0 + parent.rgb_encoder.backbone.eval() + parent.mano_layer.requires_grad_(False) + return parent + + +MAPPING = { + "RGB Q": "S4 rgb_attention.K (proxy; newly active RGB query)", + "RGB K/V/O": "S4 rgb_attention.K/V/O", + "HAND Q/O": "S4 rgb_attention.Q/O", + "HAND K/V": "S4 hand_attention.K/V", + "RGB/HAND FFN": "S4 shared spatial FFN copied into each type", + "temporal and heads": "S4 exact tensor copy", + "DINO projection and backbone": "S4 exact tensor copy; backbone frozen", + "not functionally mapped": "old sequential hand-self then RGB-cross attention softmax", + "terminal RGB post-attention": "frozen in U0: no downstream RGB consumer or supervised gradient", +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/reprojection.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/reprojection.py new file mode 100644 index 0000000000000000000000000000000000000000..a8ff80d50a6b6ded53f8efb3cfccfee64a4836e0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/reprojection.py @@ -0,0 +1,42 @@ +"""GT-mask-stable reprojection with a finite near-camera depth barrier.""" + +from __future__ import annotations + +import torch +from torch.nn import functional as F + + +def fixed_mask_reprojection(prediction, batch, depth_floor_m: float, depth_penalty_per_m: float): + if depth_floor_m <= 0 or depth_penalty_per_m <= 0: + raise ValueError("reprojection depth floor and penalty must be positive") + points = prediction["joints_camera"] + valid = (batch["reprojection_valid"].bool() + & batch["K_supervision_valid"].bool()[..., None, None] + & batch["frame_valid"].bool()[..., None, None]) + if not bool(torch.isfinite(points[valid]).all()): + raise RuntimeError("nonfinite supervised camera-space joint prediction") + if not bool(torch.isfinite(batch["joint2d"][valid]).all()): + raise RuntimeError("nonfinite supervised 2D target") + + safe_points = torch.where(valid[..., None], points, torch.zeros_like(points)) + z = safe_points[..., 2] + safe_z = z.clamp_min(depth_floor_m) + k_valid = batch["K_supervision_valid"].bool() & batch["frame_valid"].bool() + identity = torch.eye(3, dtype=batch["K"].dtype, device=batch["K"].device) + K = torch.where(k_valid[..., None, None], batch["K"], identity) + fx, fy = K[..., 0, 0][..., None, None], K[..., 1, 1][..., None, None] + cx, cy = K[..., 0, 2][..., None, None], K[..., 1, 2][..., None, None] + pixel = torch.stack((fx * safe_points[..., 0] / safe_z + cx, + fy * safe_points[..., 1] / safe_z + cy), dim=-1) + wh = batch["image_hw"].to(pixel.dtype)[:, None, None, None, [1, 0]] + target = torch.where(valid[..., None], batch["joint2d"].to(pixel.dtype), + torch.zeros_like(pixel)) + error = (pixel - target).abs() / wh + depth_barrier = depth_penalty_per_m * F.relu(depth_floor_m - z) + elementwise = torch.where(valid[..., None], error + depth_barrier[..., None], + torch.zeros_like(error)) + loss = elementwise.sum() / (valid.sum() * 2).clamp_min(1) + nonpositive = (valid & (points[..., 2] <= 0)).sum() + minimum_z = torch.where(valid, points[..., 2], torch.inf).amin() + minimum_z = torch.where(valid.any(), minimum_z, torch.zeros_like(minimum_z)) + return loss, nonpositive.detach(), minimum_z.detach() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/test_loss_scaling.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/test_loss_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..6c2c3711c256e2c937869ca8acc39c8d7833f567 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/test_loss_scaling.py @@ -0,0 +1,24 @@ +import unittest + +import torch + +from loss_scaling import SOURCES, TERMS, count_table, scaling + + +class ScalingTests(unittest.TestCase): + def test_exact_source_balance_after_ddp_mean(self): + samples = [] + for source, total in zip(SOURCES, (21, 15, 24)): + for _ in range(total): + samples.append((source, {term: 2 for term in TERMS})) + table = count_table(samples, torch.device("cpu")) + total = sum(scaling(source, counts, table, 6)["joint2d"] / 6 for source, counts in samples) + self.assertAlmostEqual(total, 1.0) + for source in SOURCES: + contribution = sum(scaling(name, counts, table, 6)["joint2d"] / 6 + for name, counts in samples if name == source) + self.assertAlmostEqual(contribution, 1 / 3) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/test_model.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/test_model.py new file mode 100644 index 0000000000000000000000000000000000000000..9263e5ed7e0195a049c37c877de7050e15e9c537 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/test_model.py @@ -0,0 +1,58 @@ +import unittest + +import torch +from torch import nn + +from model import MoTSpatialBlock, UnifiedRGBDecoder + + +class OldLayer(nn.Module): + def __init__(self, dim=16): + super().__init__() + self.query_norm = nn.LayerNorm(dim) + self.rgb_norm = nn.LayerNorm(dim) + self.rgb_attention = nn.MultiheadAttention(dim, 4, batch_first=True) + self.hand_attention = nn.MultiheadAttention(dim, 4, batch_first=True) + self.ffn = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, 4 * dim), nn.GELU(), nn.Linear(4 * dim, dim)) + + +class OldDecoder: + mode = "alternating" + + def __init__(self): + self.spatial = [OldLayer()] + self.temporal = [Temporal()] + + +class Temporal(nn.Module): + def forward(self, hand, valid): + return hand * valid[:, :, None, None], {} + + +class MoTTests(unittest.TestCase): + def test_joint_softmax_and_rgb_update(self): + block = MoTSpatialBlock(OldLayer(), 4) + rgb = torch.randn(2, 7, 16, requires_grad=True) + hand = torch.randn(2, 2, 16, requires_grad=True) + rgb_out, hand_out = block(rgb, hand) + self.assertEqual(rgb_out.shape, rgb.shape) + self.assertEqual(hand_out.shape, hand.shape) + self.assertFalse(torch.equal(rgb_out, rgb)) + hand_out.square().mean().backward() + self.assertGreater(rgb.grad.abs().sum().item(), 0) + self.assertGreater(block.rgb.k.weight.grad.abs().sum().item(), 0) + self.assertGreater(block.hand.q.weight.grad.abs().sum().item(), 0) + + def test_depth_is_rejected(self): + decoder = UnifiedRGBDecoder(OldDecoder(), 4) + query = torch.randn(1, 2, 2, 16) + rgb = torch.randn(1, 2, 7, 16) + valid = torch.ones(1, 2, dtype=torch.bool) + with self.assertRaises(ValueError): + decoder(query, rgb, None, valid, valid, None) + output, _ = decoder(query, rgb, None, valid, torch.zeros_like(valid), None) + self.assertEqual(output.shape, query.shape) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/test_reprojection.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/test_reprojection.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c7fa140bd354903edbf261cb2bbfed149e0408 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/test_reprojection.py @@ -0,0 +1,65 @@ +"""Regression tests for GT-mask-stable, depth-safe reprojection.""" + +import unittest + +import torch + +from reprojection import fixed_mask_reprojection + + +class ReprojectionTests(unittest.TestCase): + def batch(self, points): + K = torch.tensor([[[[800.0, 0.0, 448.0], + [0.0, 800.0, 256.0], + [0.0, 0.0, 1.0]]]]) + return {"K": K, "image_hw": torch.tensor([[512, 896]]), + "frame_valid": torch.tensor([[True]]), + "K_supervision_valid": torch.tensor([[True]]), + "reprojection_valid": torch.ones(points.shape[:-1], dtype=torch.bool), + "joint2d": torch.zeros((*points.shape[:-1], 2))} + + def test_positive_depth_matches_original_normalized_l1(self): + points = torch.tensor([[[[[0.02, -0.01, 0.5], [0.03, 0.01, 0.6]], + [[-0.02, 0.01, 0.7], [0.0, -0.01, 0.8]]]]]) + batch = self.batch(points) + batch["joint2d"] = torch.tensor([[[[[460.0, 244.0], [490.0, 280.0]], + [[420.0, 260.0], [448.0, 240.0]]]]]) + loss, nonpositive, _ = fixed_mask_reprojection( + {"joints_camera": points}, batch, 0.05, 10.0, + ) + z = points[..., 2] + u = 800 * points[..., 0] / z + 448 + v = 800 * points[..., 1] / z + 256 + expected = ((torch.stack((u, v), -1) - batch["joint2d"]).abs() + / torch.tensor([896.0, 512.0])).mean() + self.assertTrue(torch.allclose(loss, expected, atol=1e-7)) + self.assertEqual(int(nonpositive), 0) + + def test_nonpositive_joint_keeps_loss_and_forward_depth_gradient(self): + points = torch.tensor([[[[[0.0, 0.0, -0.01]]]]], requires_grad=True) + batch = self.batch(points) + batch["joint2d"][..., 0] = 448 + batch["joint2d"][..., 1] = 256 + loss, nonpositive, minimum_z = fixed_mask_reprojection( + {"joints_camera": points}, batch, 0.05, 10.0, + ) + self.assertTrue(bool(torch.isfinite(loss))) + self.assertEqual(int(nonpositive), 1) + self.assertAlmostEqual(float(minimum_z), -0.01, places=5) + self.assertAlmostEqual(float(loss), 0.6, places=5) + loss.backward() + self.assertLess(float(points.grad[..., 2].item()), 0.0) + + def test_invalid_nan_is_masked_but_supervised_nan_fails(self): + points = torch.tensor([[[[[0.0, 0.0, 0.5], [float("nan"), 0.0, 0.5]]]]]) + batch = self.batch(points) + batch["reprojection_valid"][..., 1] = False + loss, _, _ = fixed_mask_reprojection({"joints_camera": points}, batch, 0.05, 10.0) + self.assertTrue(bool(torch.isfinite(loss))) + batch["reprojection_valid"][..., 1] = True + with self.assertRaisesRegex(RuntimeError, "nonfinite supervised"): + fixed_mask_reprojection({"joints_camera": points}, batch, 0.05, 10.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/train.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/train.py new file mode 100644 index 0000000000000000000000000000000000000000..0df649165f4af4d064715accb583454baf6cd20e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_depthsafe/train.py @@ -0,0 +1,314 @@ +"""Source-balanced U0 RGB training with a hash-bound pilot continuation.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +import hashlib +import json +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +from torch import nn +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader + +from common import CONFIG, ROOT, U0Coverage, U0Dataset, a7, base, code_hashes, model_for, sha, validate_run_contract +from loss_scaling import SOURCES, TERMS, count_table, element_counts, scaling +from reprojection import fixed_mask_reprojection +from foundation_hand.training.losses import BimanualLoss, masked_l1 + + +class Objective(nn.Module): + def __init__(self, model): + super().__init__() + self.model = model + self.criterion = BimanualLoss(base.LOSS) + + def forward(self, batch, teacher, weights): + prediction = self.model(batch) + # The shared criterion masks predicted negative-Z joints, while U0's + # source-balanced denominator is fixed by GT validity. + criterion_batch = dict(batch) + criterion_batch.pop("K") + losses = self.criterion(prediction, criterion_batch) + reprojection, nonpositive, minimum_z = fixed_mask_reprojection( + prediction, batch, CONFIG["reprojection_depth_floor_m"], + CONFIG["reprojection_depth_penalty_per_m"], + ) + losses["reprojection"] = reprojection + valid = {key: batch[key].bool() for key in ( + "joint3d_valid", "joint3d_root_relative_valid", "vertices_valid", + "translation_valid", "joint2d_valid", + )} + student_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + teacher_relative = teacher["joints_camera"] - teacher["joints_camera"][..., :1, :] + distill = { + "joint3d_camera": 10 * masked_l1(prediction["joints_camera"], teacher["joints_camera"], valid["joint3d_valid"][..., None]), + "joint3d_root_relative": 10 * masked_l1(student_relative, teacher_relative, valid["joint3d_root_relative_valid"][..., None]), + "vertices_camera": masked_l1(prediction["vertices_camera"], teacher["vertices_camera"], valid["vertices_valid"][..., None, None]), + "translation": 10 * masked_l1(prediction["wrist_root_translation"], teacher["wrist_root_translation"], valid["translation_valid"][..., None]), + "joint2d": masked_l1(prediction["joint2d_norm"], teacher["joint2d_norm"], valid["joint2d_valid"][..., None]), + } + supervised = sum(losses[name] * weights[name] for name in TERMS) + anchored = CONFIG["rgb_teacher_weight"] * sum(value * weights[name] for name, value in distill.items()) + total = supervised + anchored + with torch.no_grad(): + native_valid = batch["source_native_joint3d_valid"].bool() & valid["joint3d_valid"] + native_error = masked_l1(prediction["joints_camera"], batch["source_native_joint3d_camera"], native_valid[..., None]) + label_gap = (masked_l1(batch["joint3d_camera"], batch["source_native_joint3d_camera"], native_valid[..., None]) + if batch["sampling_source_id"][0] == "H2O" else native_error.new_zeros(())) + return (total, supervised.detach(), anchored.detach(), native_error.detach(), + label_gap.detach(), nonpositive, minimum_z) + + +def save_checkpoint(path, model, optimizer, update, hashes, rng_states, exposure, + frozen_hash, smoke, input_checksums, optimizer_names): + if path.exists(): + raise FileExistsError(path) + state = { + "experiment": CONFIG["experiment"], "model": model.state_dict(), + "optimizer": optimizer.state_dict(), "update": update, + "next_global_sample_position": update * CONFIG["global_batch"], + "world_size": CONFIG["world_size"], "global_batch": CONFIG["global_batch"], + "source_exposure": dict(exposure), "parent_sha256": CONFIG["parent_sha256"], + "code_sha256": hashes, "target_contract": CONFIG["target_contract"], + "metric_keys": CONFIG["metric_keys"], "rank_rng_states": rng_states, + "frozen_fingerprint": frozen_hash, "complete_backbone": True, + "smoke": smoke, "config": CONFIG, "input_checksums": input_checksums, + "optimizer_parameter_names": optimizer_names, + } + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + temporary.replace(path) + loaded = torch.load(path, map_location="cpu", weights_only=False) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("U0 full checkpoint load-back failed") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--smoke", action="store_true") + args = parser.parse_args() + if not 0 < args.updates <= CONFIG["maximum_updates"]: + raise ValueError("U0 endpoint exceeds registered full-stage budget") + rank, world = int(os.environ.get("RANK", 0)), int(os.environ.get("WORLD_SIZE", 1)) + local = int(os.environ.get("LOCAL_RANK", 0)) + if world != CONFIG["world_size"] or CONFIG["global_batch"] % world: + raise RuntimeError("U0 requires registered six-rank/global-batch contract") + accumulation = CONFIG["global_batch"] // world + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.cuda.set_device(local) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device("cuda", local) + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + if shutil.disk_usage(ROOT).free < CONFIG["minimum_free_disk_gib"] * 1024**3: + raise RuntimeError("U0 disk reserve below registered minimum") + registration = validate_run_contract() + hashes = registration["code_sha256"] + seed = CONFIG["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + student = model_for("student").to(device).train() + teacher = model_for("teacher").to(device).eval() + frozen_hash = a7.reference.frozen_fingerprint(student) + trainable = [(name, parameter) for name, parameter in student.named_parameters() if parameter.requires_grad] + new = [parameter for name, parameter in trainable if name.startswith("decoder.spatial.")] + inherited = [parameter for name, parameter in trainable if not name.startswith("decoder.spatial.")] + optimizer_names = ([name for name, _ in trainable if name.startswith("decoder.spatial.")] + + [name for name, _ in trainable if not name.startswith("decoder.spatial.")]) + if not new or not inherited: + raise RuntimeError("U0 optimizer lost new or inherited trainable parameters") + optimizer = torch.optim.AdamW([ + {"params": new, "lr_scale": 1.0}, + {"params": inherited, "lr_scale": CONFIG["learning_rate_inherited"] / CONFIG["learning_rate_new_mot"]}, + ], lr=CONFIG["learning_rate_new_mot"], weight_decay=CONFIG["weight_decay"]) + start, exposure, input_checksums = 0, Counter(), [] + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False) + for key, value in (("experiment", CONFIG["experiment"]), ("world_size", world), + ("global_batch", CONFIG["global_batch"]), + ("target_contract", CONFIG["target_contract"]), ("smoke", args.smoke)): + if state[key] != value: + raise RuntimeError("U0 resume contract differs: " + key) + if state["code_sha256"] != hashes: + parent = Path(CONFIG["continuation_checkpoint"]) + if (args.resume.resolve() != parent.resolve() + or sha(parent) != CONFIG["continuation_checkpoint_sha256"] + or state["update"] != CONFIG["continuation_update"]): + raise RuntimeError("unregistered U0 depth-safe checkpoint continuation") + for key, value in state["config"].items(): + if key not in ("continuation_checkpoint", "continuation_checkpoint_sha256") and CONFIG.get(key) != value: + raise RuntimeError("depth-safe U0 changed unrelated training setting: " + key) + allowed_changes = {"unified_mot/train.py", "unified_mot/config.json", + "unified_mot/lineage_check.py", "unified_mot/continuation_controller.py"} + for key, value in state["code_sha256"].items(): + if key not in allowed_changes and hashes.get(key) != value: + raise RuntimeError("depth-safe U0 changed unrelated file: " + key) + student.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + start = state["update"] + if state["next_global_sample_position"] != start * CONFIG["global_batch"]: + raise RuntimeError("U0 resume coverage cursor mismatch") + exposure.update(state["source_exposure"]) + input_checksums = state["input_checksums"] + if state["optimizer_parameter_names"] != optimizer_names: + raise RuntimeError("U0 resume optimizer parameter order changed") + base.restore_rng(state["rank_rng_states"][rank], device) + if a7.reference.frozen_fingerprint(student) != frozen_hash: + raise RuntimeError("U0 resumed frozen parameters changed") + if start >= args.updates: + raise ValueError("resume already reached requested endpoint") + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("U0 fresh run would overwrite metrics") + a7.dump(args.output / "provenance.json", { + "code_sha256": hashes, "mapping": registration["mapping"], + "parent_sha256": CONFIG["parent_sha256"], "target_contract": CONFIG["target_contract"], + "metric_keys": CONFIG["metric_keys"], "trainable_parameters": sum(p.numel() for _, p in trainable), + "new_mot_parameters": sum(p.numel() for p in new), "inherited_parameters": sum(p.numel() for p in inherited), + "frozen_fingerprint": frozen_hash, "loss": vars(base.LOSS), + "source_quota": CONFIG["source_quota_per_update"], "smoke": args.smoke, + "continuation_checkpoint_sha256": CONFIG["continuation_checkpoint_sha256"], + }) + dist.barrier(device_ids=[local]) + coverage = U0Coverage() + dataset = U0Dataset() + sampler = base.PositionSampler(coverage, start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(dataset, batch_size=1, sampler=sampler, + num_workers=CONFIG["workers_per_rank"], + persistent_workers=CONFIG["workers_per_rank"] > 0, + collate_fn=base.collate_h2o_clips, pin_memory=True, + generator=torch.Generator().manual_seed(seed + 1000000)) + objective = DDP(Objective(student), device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + iterator = iter(loader) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + clock = time.monotonic() + for update in range(start, args.updates): + lr = base.warmup_cosine_learning_rate( + update * CONFIG["global_batch"], CONFIG["full_stage_clips"], + CONFIG["learning_rate_new_mot"], + CONFIG["learning_rate_new_mot"] * CONFIG["minimum_learning_rate_ratio"], + CONFIG["warmup_clips"], + ) + base.set_scheduled_learning_rate(optimizer, lr) + optimizer.zero_grad(set_to_none=True) + cpu_batches = [next(iterator) for _ in range(accumulation)] + descriptors = [(batch["sampling_source_id"][0], element_counts(batch)) for batch in cpu_batches] + local_input_checksums = [] + if args.smoke: + for micro, cpu in enumerate(cpu_batches): + digest = hashlib.sha256() + for key in ("rgb", "K", "frame_valid", "joint3d_camera", "joint2d", + "mano_pose", "mano_shape", "wrist_root_translation", + "photometric_aug_params"): + if key in cpu and torch.is_tensor(cpu[key]): + value = cpu[key].contiguous().reshape(-1).view(torch.uint8) + digest.update(key.encode()) + digest.update(value.numpy().tobytes()) + local_input_checksums.append({ + "position": update * CONFIG["global_batch"] + micro * world + rank, + "source": cpu["sampling_source_id"][0], "sha256": digest.hexdigest(), + }) + global_counts = count_table(descriptors, device) + dist.all_reduce(global_counts) + local_sources = Counter(source for source, _ in descriptors) + source_count = torch.tensor([local_sources[source] for source in SOURCES], device=device) + dist.all_reduce(source_count) + if source_count.tolist() != [CONFIG["source_quota_per_update"][source] for source in SOURCES]: + raise RuntimeError("coverage source quota differs from registered 21/15/24") + totals = torch.zeros(5, device=device) + nonpositive_by_source = torch.zeros(len(SOURCES), dtype=torch.long, device=device) + for micro, (cpu, (source, counts)) in enumerate(zip(cpu_batches, descriptors)): + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, student) + weights = scaling(source, counts, global_counts, world) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + teacher_prediction = teacher(batch) + sync = objective.no_sync() if micro + 1 < accumulation else nullcontext() + with sync, torch.autocast("cuda", dtype=torch.bfloat16): + total, supervised, anchored, native_error, label_gap, nonpositive, minimum_z = objective( + batch, teacher_prediction, weights, + ) + if not bool(torch.isfinite(total)): + raise RuntimeError("nonfinite U0 loss") + total.backward() + totals += torch.stack((total.detach(), supervised, anchored, native_error, label_gap)) + nonpositive_by_source[SOURCES.index(source)] += nonpositive + if int(nonpositive) > 0: + print(json.dumps({"event": "nonpositive_reprojection_depth", + "update": update + 1, "rank": rank, "micro": micro, + "source": source, "tile": cpu["filtered_tile_id"][0], + "joint_count": int(nonpositive), "minimum_z_m": float(minimum_z)}, + allow_nan=False), flush=True) + norm = torch.nn.utils.clip_grad_norm_([p for _, p in trainable], CONFIG["grad_clip"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite U0 gradients") + optimizer.step() + dist.all_reduce(totals) + dist.all_reduce(nonpositive_by_source) + if args.smoke: + gathered = [None] * world + dist.all_gather_object(gathered, local_input_checksums) + input_checksums.extend(sorted((item for group in gathered for item in group), + key=lambda item: item["position"])) + for source, count in zip(SOURCES, source_count.tolist()): + exposure[source] += count + if rank == 0: + row = { + "update": update + 1, "consumed_clips": (update + 1) * CONFIG["global_batch"], + "loss": float(totals[0] / world), "supervised": float(totals[1] / world), + "rgb_anchor": float(totals[2] / world), + "native_joint_error_diagnostic": float(totals[3] / CONFIG["global_batch"]), + "h2o_native_vs_refit_joint_gap_m": float(totals[4] / source_count[0]), + "grad_norm": float(norm), "clipped": float(norm) > CONFIG["grad_clip"], + "lr_new_mot": lr, "lr_inherited": lr * optimizer.param_groups[1]["lr_scale"], + "source_exposure": dict(exposure), "elapsed_seconds": time.monotonic() - clock, + "nonpositive_reprojection_joints_by_source": dict(zip(SOURCES, nonpositive_by_source.tolist())), + } + log.write(json.dumps(row, allow_nan=False) + "\n") + if update < 5 or (update + 1) % 20 == 0: + print(json.dumps(row, allow_nan=False), flush=True) + if update + 1 == args.updates or (update + 1) % 100 == 0: + rng = base.rng_state(device) + states = [None] * world if rank == 0 else None + dist.gather_object(rng, states, dst=0) + if a7.reference.frozen_fingerprint(student) != frozen_hash: + raise RuntimeError("U0 updated frozen DINO/MANO tensors") + if rank == 0: + if shutil.disk_usage(ROOT).free < CONFIG["minimum_free_disk_gib"] * 1024**3: + raise RuntimeError("U0 checkpoint violates disk reserve") + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", student, optimizer, + update + 1, hashes, states, exposure, frozen_hash, args.smoke, + input_checksums, optimizer_names) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/audit_loss.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/audit_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..226737b69f6acb4e828eaf1dae17e9e4e491a274 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/audit_loss.py @@ -0,0 +1,71 @@ +"""Fixed-batch comparison of inherited and normalized objective magnitudes/gradients.""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys + +import torch + +ROOT = Path(__file__).resolve().parent +U0_ROOT = Path("/home/wuyifan/unified_mot_u0_depthsafe_20261001") +sys.path.insert(0, str(U0_ROOT)) +from common import U0Coverage, U0Dataset, base, model_for +from reprojection import fixed_mask_reprojection +from foundation_hand.training.losses import BimanualLoss +from normalized_loss import NormalizedLoss, hand_tail_weights + +CONFIG = json.loads((ROOT / "config.json").read_text()) +STATS = json.loads((ROOT / "normalization.json").read_text()) +TERMS = tuple(CONFIG["loss_coefficients"]) + + +def main(): + torch.set_num_threads(2) + model = model_for("student").cuda().train() + state = torch.load(CONFIG["start_checkpoint"], map_location="cpu", weights_only=False) + model.load_state_dict(state["model"], strict=True) + legacy = BimanualLoss(base.LOSS) + revised = NormalizedLoss(STATS, CONFIG["loss_coefficients"], False).cuda() + coverage, dataset = U0Coverage(), U0Dataset() + selected = {} + for position in range(120): + spec = coverage.sample(position) + selected.setdefault(spec["source"], spec) + output = {} + for source, spec in sorted(selected.items()): + batch = base.collate_h2o_clips([dataset[spec]]) + batch = base.move_to_device(batch, torch.device("cuda:0")) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + old_batch = dict(batch) + old_batch.pop("K") + old_losses = legacy(prediction, old_batch) + reprojection, _, _ = fixed_mask_reprojection( + prediction, batch, CONFIG["reprojection_depth_floor_m"], + CONFIG["reprojection_depth_penalty_per_m"], + ) + old_losses["reprojection"] = reprojection + new_losses = revised(prediction, batch, hand_tail_weights(batch, False)) + new_losses["reprojection"] = reprojection + old_total = sum(old_losses[name] for name in TERMS) + new_total = sum(new_losses[name] for name in TERMS) + parameters = [model.rotation_head.weight, model.translation_head.weight] + old_gradient = torch.autograd.grad(old_total, parameters, retain_graph=True) + new_gradient = torch.autograd.grad(new_total, parameters) + output[source] = { + "old": {name: float(old_losses[name]) for name in TERMS}, + "new": {name: float(new_losses[name]) for name in TERMS}, + "total_old": float(old_total), "total_new": float(new_total), + "rotation_head_grad_old": float(torch.linalg.vector_norm(old_gradient[0])), + "rotation_head_grad_new": float(torch.linalg.vector_norm(new_gradient[0])), + "translation_head_grad_old": float(torch.linalg.vector_norm(old_gradient[1])), + "translation_head_grad_new": float(torch.linalg.vector_norm(new_gradient[1])), + } + print(json.dumps({"source": source, **output[source]}, allow_nan=False), flush=True) + (ROOT / "loss_audit.json").write_text(json.dumps(output, indent=2, allow_nan=False) + "\n") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/check_6d_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/check_6d_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..aad82492f30df537d6c6f722cf26a09e9086c4dd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/check_6d_contract.py @@ -0,0 +1,85 @@ +"""Read-only GT/raw-head rotation contract check on the U0 20K checkpoint.""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys + +import torch +from torch.nn import functional as F + +U0_ROOT = Path("/home/wuyifan/unified_mot_u0_depthsafe_20261001") +sys.path.insert(0, str(U0_ROOT)) + +from common import U0Coverage, U0Dataset, base, model_for +from foundation_hand.geometry.rotations import axis_angle_to_matrix + + +def stats(values): + values = values.float().flatten() + return { + "count": int(values.numel()), + "mean": float(values.mean()), + "p50": float(torch.quantile(values, 0.5)), + "p95": float(torch.quantile(values, 0.95)), + "max": float(values.max()), + } + + +def main(): + state = torch.load(U0_ROOT / "runs/U0/update_0020004.pt", map_location="cpu", weights_only=False) + model = model_for("student").cuda().eval() + model.load_state_dict(state["model"], strict=True) + coverage, dataset = U0Coverage(), U0Dataset() + result = {} + positions_by_source = {source: [] for source in ("H2O", "ARCTIC", "HOT3D")} + for position in range(120): + spec = coverage.sample(position) + if len(positions_by_source[spec["source"]]) < 3: + positions_by_source[spec["source"]].append(position) + for source, positions in positions_by_source.items(): + clips = [] + for position in positions: + spec = coverage.sample(position) + if spec["source"] != source: + raise RuntimeError((source, position, spec["source"])) + clips.append(dataset[spec]) + batch = base.collate_h2o_clips(clips) + batch = base.move_to_device(batch, torch.device("cuda:0")) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + mask = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + raw = prediction["mano_rotations_6d"].float() + first_raw, second_raw = raw[..., :3], raw[..., 3:] + first = F.normalize(first_raw, dim=-1) + second = F.normalize(second_raw - (first * second_raw).sum(-1, keepdim=True) * first, dim=-1) + canonical = torch.cat((first, second), dim=-1) + matrix_from_raw = torch.stack((first, second, torch.cross(first, second, dim=-1)), dim=-2) + target_matrix = axis_angle_to_matrix( + torch.nan_to_num(batch["mano_pose"].float()).reshape(*mask.shape, 16, 3) + ) + target = target_matrix[..., :2, :].reshape(*mask.shape, 16, 6) + valid = mask[..., None].expand(*mask.shape, 16) + gt_first, gt_second = target[..., :3], target[..., 3:] + result[source] = { + "valid_rotations": int(valid.sum()), + "gt_first_norm_error": stats((torch.linalg.vector_norm(gt_first, dim=-1) - 1).abs()[valid]), + "gt_second_norm_error": stats((torch.linalg.vector_norm(gt_second, dim=-1) - 1).abs()[valid]), + "gt_abs_axis_dot": stats((gt_first * gt_second).sum(-1).abs()[valid]), + "gt_det_error": stats((torch.linalg.det(target_matrix) - 1).abs()[valid]), + "raw_first_norm": stats(torch.linalg.vector_norm(first_raw, dim=-1)[valid]), + "raw_second_norm": stats(torch.linalg.vector_norm(second_raw, dim=-1)[valid]), + "raw_axis_abs_cosine": stats(F.cosine_similarity(first_raw, second_raw, dim=-1).abs()[valid]), + "raw_6d_l1": float((raw - target).abs()[valid].mean()), + "canonical_6d_l1": float((canonical - target).abs()[valid].mean()), + "raw_canonical_l1": float((raw - canonical).abs()[valid].mean()), + "raw_matrix_vs_final_matrix_max": float( + (matrix_from_raw - prediction["mano_rotation_matrices"].float()).abs()[valid].max() + ), + } + print(json.dumps(result, indent=2, allow_nan=False)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/check_hot3d_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/check_hot3d_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e85ff3d9aee533fae8f8bff71733ca2ba4054f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/check_hot3d_contract.py @@ -0,0 +1,47 @@ +"""Read-only check of filtered HOT3D pose coordinates versus U0 supervision.""" + +from pathlib import Path +import sys + +import numpy as np +import torch + +sys.path.insert(0, "/home/wuyifan/unified_mot_u0_depthsafe_20261001") +from common import U0Coverage, U0Dataset +from foundation_hand.geometry.rotations import axis_angle_to_matrix + + +coverage, dataset = U0Coverage(), U0Dataset() +position = next(i for i in range(120) if coverage.sample(i)["source"] == "HOT3D") +spec = coverage.sample(position) +sample = dataset[spec] +row = dataset.sources["HOT3D"].rows[dataset.sources["HOT3D"].by_tile[spec["tile_id"]]] +start = row["filtered_start_offset"] +with np.load(row["filtered_gt_path"], allow_pickle=False) as data: + raw_rotation = axis_angle_to_matrix(torch.from_numpy(data["native_global_orient_aa_rad"][start:start + 8]).float()) + raw_translation = torch.from_numpy(data["native_translation_m"][start:start + 8]).float() + filtered_wrist = torch.from_numpy(data["joints_native_m"][start:start + 8, :, 0]).float() +target_rotation = axis_angle_to_matrix(sample["mano_pose"][..., :3]) +target_translation = sample["wrist_root_translation"] +valid = sample["mano_pose_valid"].bool() +camera = sample["camera_pose"].float() +world_to_camera_rotation = camera[:, :3, :3].transpose(-1, -2) +camera_rotation = world_to_camera_rotation[:, None] @ raw_rotation +camera_translation = ( + world_to_camera_rotation[:, None] @ + (raw_translation - camera[:, None, :3, 3])[..., None] +)[..., 0] +for label, rotation, translation in ( + ("raw", raw_rotation, raw_translation), + ("world_to_camera", camera_rotation, camera_translation), +): + print(label, "rotation_matrix_abs_max", float((rotation - target_rotation).abs()[valid].max())) + print(label, "translation_m_abs_max", float((translation - target_translation).abs()[valid].max())) +print("valid_hands", int(valid.sum())) +print("filtered_wrist_vs_target_m_abs_max", float((filtered_wrist - target_translation).abs()[valid].max())) +filtered_wrist_camera = ( + world_to_camera_rotation[:, None] @ + (filtered_wrist - camera[:, None, :3, 3])[..., None] +)[..., 0] +print("filtered_wrist_world_to_camera_vs_target_m_abs_max", float((filtered_wrist_camera - target_translation).abs()[valid].max())) +print("sample_joint_wrist_vs_target_m_abs_max", float((sample["joint3d_camera"][..., 0, :] - target_translation).abs()[valid].max())) diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/config.json new file mode 100644 index 0000000000000000000000000000000000000000..764ba47e4f25da6400d16b595519d1bc9987dd86 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/config.json @@ -0,0 +1,45 @@ +{ + "experiment": "u0_normalized6d_tail_pair_20261002", + "start_checkpoint": "/home/wuyifan/unified_mot_u0_depthsafe_20261001/runs/U0/update_0020004.pt", + "start_checkpoint_sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a", + "target_contract": "canonical_approximate_v3", + "metric_keys": [ + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "mpvpe_mm", + "projected_mano_2d_error_px" + ], + "seed": 20260930, + "world_size": 6, + "global_batch": 60, + "maximum_updates": 20000, + "full_stage_clips": 1200000, + "source_quota_per_update": {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}, + "learning_rate_new_mot": 0.00001, + "learning_rate_inherited": 0.000002, + "minimum_learning_rate_ratio": 0.1, + "warmup_clips": 1008, + "weight_decay": 0.05, + "grad_clip": 100.0, + "rgb_teacher_weight": 0.05, + "workers_per_rank": 2, + "minimum_free_disk_gib": 200, + "checkpoint_interval": 2000, + "evaluation_updates": [2000, 6000, 12000, 20000], + "reprojection_depth_floor_m": 0.05, + "reprojection_depth_penalty_per_m": 10.0, + "loss_coefficients": { + "joint2d": 1.0, + "joint3d_camera": 1.5, + "joint3d_root_relative": 1.5, + "vertices_camera": 0.15, + "local_pose": 0.3, + "global_orientation": 0.3, + "shape": 0.1, + "translation": 1.5, + "reprojection": 1.0, + "temporal_velocity": 0.015, + "temporal_acceleration": 0.0075, + "bimanual_relative_wrist": 0.15 + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/fit_normalization.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/fit_normalization.py new file mode 100644 index 0000000000000000000000000000000000000000..39c11c581c715f35a0b05d15e99f46d825f7db6e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/fit_normalization.py @@ -0,0 +1,233 @@ +"""Fit train-only, equal-source normalization from unique labeled hand frames.""" + +from __future__ import annotations + +from collections import defaultdict +import hashlib +import json +from pathlib import Path +import sqlite3 +import sys + +import numpy as np +from scipy.spatial.transform import Rotation + +U0_ROOT = Path("/home/wuyifan/unified_mot_u0_depthsafe_20261001") +BASE_ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925") +LABEL_ROOT = Path("/home/wuyifan/a7_canonical_gt_rotationfix_20260930") +sys.path.insert(0, str(U0_ROOT)) + +from common import U0Dataset +from foundation_hand.data.hot3d_dataset import quest_linear_camera_calibration + + +def sha(path): + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024**2), b""): + digest.update(block) + return digest.hexdigest() + + +class Moments: + def __init__(self): + self.count = 0 + self.xyz_sum = np.zeros(3, np.float64) + self.xyz_sq = np.zeros(3, np.float64) + self.beta_sum = np.zeros(10, np.float64) + self.beta_sq = np.zeros(10, np.float64) + self.pose_count = np.zeros((2, 16, 1), np.int64) + self.pose_sum = np.zeros((2, 16, 6), np.float64) + self.pose_sq = np.zeros((2, 16, 6), np.float64) + + def add(self, pose, beta, wrist, valid): + valid = valid.astype(bool) + valid &= np.isfinite(pose).all(-1) & np.isfinite(beta).all(-1) & np.isfinite(wrist).all(-1) + self.count += int(valid.sum()) + selected_xyz = wrist[valid].astype(np.float64) + selected_beta = beta[valid].astype(np.float64) + self.xyz_sum += selected_xyz.sum(axis=0) + self.xyz_sq += np.square(selected_xyz).sum(axis=0) + self.beta_sum += selected_beta.sum(axis=0) + self.beta_sq += np.square(selected_beta).sum(axis=0) + for side in range(2): + selected_pose = pose[:, side][valid[:, side]].reshape(-1, 16, 3) + if not len(selected_pose): + continue + six = Rotation.from_rotvec(selected_pose.reshape(-1, 3)).as_matrix() + six = six[..., :2, :].reshape(-1, 16, 6) + self.pose_count[side] += len(six) + self.pose_sum[side] += six.sum(axis=0) + self.pose_sq[side] += np.square(six).sum(axis=0) + + +def selected_frames(): + index = BASE_ROOT / "cache/trainable_t8_index.sqlite" + connection = sqlite3.connect(index) + grouped = defaultdict(lambda: defaultdict(dict)) + query = ( + "SELECT t.source,t.recording_id,t.start_offset,t.frame_ids_json,w.manifest_json " + "FROM tiles t JOIN windows w USING(window_id) ORDER BY t.source,t.recording_id,w.window_id,t.start_offset" + ) + for source, recording, start, ids_json, row_json in connection.execute(query): + row = json.loads(row_json) + ids = json.loads(ids_json) + selection = grouped[(source, recording)][row["filtered_gt_path"]] + for offset, frame_id in enumerate(ids): + position = start + offset + previous = selection.get(position) + if previous is not None and previous != frame_id: + raise RuntimeError("overlapping tile metadata disagree") + selection[position] = frame_id + if source == "HOT3D": + selection["headset"] = row["source"]["device"] + selection["stream_id"] = row["stream_id"] + connection.close() + return grouped, index + + +def canonical_source(source, recording, windows, labels, moments): + chosen = {} + for path, selection in windows.items(): + positions = [key for key in selection if isinstance(key, int)] + with np.load(path, allow_pickle=False) as filtered: + ids = filtered["frame_ids"] + valid = filtered["valid"] + for index in positions: + frame_id = selection[index] + if ids[index] != frame_id: + raise RuntimeError("filtered GT frame mismatch") + if frame_id in chosen: + chosen[frame_id] |= valid[index] + else: + chosen[frame_id] = valid[index].copy() + if not chosen: + return + label_path = labels[(source, recording)] + with np.load(label_path, allow_pickle=False) as label: + ids = label["frame_ids"] + selected_ids = np.fromiter(sorted(chosen), dtype=np.int64) + indices = np.searchsorted(ids, selected_ids) + if (indices >= len(ids)).any() or not np.array_equal(ids[indices], selected_ids): + raise RuntimeError("canonical label frame mismatch") + valid = np.stack([chosen[int(key)] for key in selected_ids]) & label["hand"][indices] + moments.add(label["pose"][indices], label["beta"][indices], label["wrist"][indices], valid) + + +def hot3d_source(recording, windows, native, moments): + provider = native._provider(recording) + api = native._api + device = provider.device_data_provider + pose_provider = provider.device_pose_data_provider + seen = set() + quest_cameras = {} + for path, selection in windows.items(): + headset, stream_id = selection["headset"], selection["stream_id"] + stream = api["StreamId"](str(stream_id)) + if headset != "Aria" and stream_id not in quest_cameras: + quest_cameras[stream_id], _ = quest_linear_camera_calibration( + device, stream, api["LINEAR"], api["FISHEYE624"], + ) + positions = sorted(key for key in selection if isinstance(key, int)) + with np.load(path, allow_pickle=False) as filtered: + frame_ids = filtered["frame_ids"] + world_root = filtered["native_global_orient_aa_rad"][positions] + local = filtered["local_pose_aa_rad"][positions] + world_wrist = filtered["joints_native_m"][positions, :, 0] + beta = filtered["betas"][positions] + valid = filtered["valid"][positions].copy() + timestamps = filtered["matched_annotation_ns"][positions] + camera_pose = np.empty((len(positions), 4, 4), np.float64) + for ordinal, position in enumerate(positions): + frame_id = selection[position] + timestamp = int(timestamps[ordinal]) + if frame_ids[position] != frame_id: + raise RuntimeError("HOT3D frame mismatch") + for side in range(2): + key = (stream_id, frame_id, side) + if key in seen: + valid[ordinal, side] = False + elif valid[ordinal, side]: + seen.add(key) + if not valid[ordinal].any(): + camera_pose[ordinal] = np.eye(4) + continue + if timestamp <= 0: + raise RuntimeError("HOT3D supervised frame has no camera timestamp") + headset_pose = pose_provider.get_pose_at_timestamp( + timestamp, api["TimeQueryOptions"].CLOSEST, + api["TimeDomain"].TIME_CODE, 20_000_000, + ) + if headset_pose is None: + raise RuntimeError("HOT3D camera pose missing for supervised frame") + if headset == "Aria": + device_camera, _ = device.get_online_camera_calibration( + stream, timestamp, camera_model=api["LINEAR"], + ) + else: + device_camera = quest_cameras[stream_id] + camera_pose[ordinal] = np.asarray( + (headset_pose.pose3d.T_world_device @ device_camera).inverse().to_matrix() + ) + camera_rotation = camera_pose[:, None, :3, :3] + world_rotation = Rotation.from_rotvec(np.nan_to_num(world_root).reshape(-1, 3)).as_matrix() + world_rotation = world_rotation.reshape(len(positions), 2, 3, 3) + camera_root = Rotation.from_matrix( + (camera_rotation @ world_rotation).reshape(-1, 3, 3) + ).as_rotvec().reshape(len(positions), 2, 3) + camera_wrist = (camera_rotation @ world_wrist[..., None])[..., 0] + camera_pose[:, None, :3, 3] + pose = np.concatenate((camera_root, local), axis=-1) + moments.add(pose, beta, camera_wrist, valid) + + +def main(): + groups, index = selected_frames() + inventory = LABEL_ROOT / "label_inventory.json" + labels = { + (entry["source"], entry["recording"]): entry["path"] + for entry in json.loads(inventory.read_text())["entries"] + } + native = U0Dataset().sources["HOT3D"].native + moments = {source: Moments() for source in ("H2O", "ARCTIC", "HOT3D")} + for ordinal, ((source, recording), windows) in enumerate(sorted(groups.items())): + if source == "HOT3D": + hot3d_source(recording, windows, native, moments[source]) + else: + canonical_source(source, recording, windows, labels, moments[source]) + if (ordinal + 1) % 25 == 0: + print(json.dumps({"recordings_done": ordinal + 1, + "hand_frames": {key: value.count for key, value in moments.items()}}), flush=True) + + xyz_mean = np.mean([item.xyz_sum / item.count for item in moments.values()], axis=0) + xyz_second = np.mean([item.xyz_sq / item.count for item in moments.values()], axis=0) + xyz_scale = max(0.1, float(np.sqrt(np.maximum((xyz_second - xyz_mean**2).mean(), 0)))) + beta_mean = np.mean([item.beta_sum / item.count for item in moments.values()], axis=0) + beta_second = np.mean([item.beta_sq / item.count for item in moments.values()], axis=0) + beta_scale = np.sqrt(np.maximum(beta_second - beta_mean**2, 0)) + beta_scale = np.maximum(beta_scale, 0.5) + pose_mean = np.mean([item.pose_sum / item.pose_count for item in moments.values()], axis=0) + pose_second = np.mean([item.pose_sq / item.pose_count for item in moments.values()], axis=0) + pose_scale = np.sqrt(np.maximum(pose_second - pose_mean**2, 0)) + pose_scale = np.maximum(pose_scale, 0.1) + result = { + "version": "train_unique_frames_equal_source_v1", + "training_index_sha256": sha(index), + "label_inventory_sha256": sha(inventory), + "source_hand_frames": {key: value.count for key, value in moments.items()}, + "xyz_center": xyz_mean.tolist(), "xyz_scale": xyz_scale, + "beta_center": beta_mean.tolist(), "beta_scale": beta_scale.tolist(), + "pose_center": pose_mean.tolist(), "pose_scale": pose_scale.tolist(), + "variance_floors": {"xyz_m": 0.1, "beta": 0.5, "pose_component": 0.1}, + } + if not np.isfinite(xyz_mean).all() or not np.isfinite(pose_scale).all(): + raise RuntimeError("nonfinite normalization statistics") + destination = Path(__file__).resolve().parent / "normalization.json" + destination.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") + print(json.dumps({"complete": str(destination), "counts": result["source_hand_frames"], + "xyz_scale": xyz_scale, "beta_scale": beta_scale.tolist(), + "pose_scale_min": float(pose_scale.min()), + "pose_scale_max": float(pose_scale.max())}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/normalization.json b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/normalization.json new file mode 100644 index 0000000000000000000000000000000000000000..3fd1e47ce2cd590dbacfd9a7ed0b1f707d3b4f1d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/normalization.json @@ -0,0 +1,569 @@ +{ + "version": "train_unique_frames_equal_source_v1", + "training_index_sha256": "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462", + "label_inventory_sha256": "0bd3135ee5cdda31e50109cefc8fc8083b0d57d9646c9eb6d2f7aeab9e904b62", + "source_hand_frames": { + "H2O": 95077, + "ARCTIC": 293441, + "HOT3D": 2084401 + }, + "xyz_center": [ + 0.05994407596646214, + 0.06014296839083632, + 0.44514722423466796 + ], + "xyz_scale": 0.15008881049400505, + "beta_center": [ + -0.19718160544415178, + 0.16037801501501522, + -0.5826519209868676, + -1.0090437326976502, + -0.1578454475569871, + -1.1671961104797894, + -1.193845219992087, + -0.3502025259588859, + -0.1503531398285081, + -0.044570832148330165 + ], + "beta_scale": [ + 1.1330261603220695, + 0.6256970731795106, + 2.0676881691397293, + 1.4334167768470645, + 0.839381168944676, + 1.2530977338264941, + 1.5587187643040932, + 1.1399629559799613, + 1.4579210614888947, + 1.165130545324764 + ], + "pose_center": [ + [ + [ + -0.05570128803155681, + -0.5240701394294555, + 0.0006167109567432419, + -0.539360629110705, + 0.13509294461340368, + -0.1745414484084421 + ], + [ + 0.8299274479860292, + 0.39010389773609355, + 0.13417910854451007, + -0.3847211018567653, + 0.8510627809342969, + -0.06156842835468942 + ], + [ + 0.8120552045077248, + 0.4656255965391544, + -0.07498990182918645, + -0.46833559252415186, + 0.7983747255614636, + -0.062422988425390534 + ], + [ + 0.9544958750399036, + 0.1581479414196779, + -0.023146342995144554, + -0.14722876042759367, + 0.9432643089782956, + -0.038486986102980916 + ], + [ + 0.7049132662800881, + 0.5627002849550747, + 0.05492689640300297, + -0.563419188441618, + 0.7018282804664522, + 0.0675268848949206 + ], + [ + 0.847163038552664, + 0.38913816041897725, + 0.08085572319941069, + -0.39249760201714684, + 0.8348549617754407, + 0.14168206659159074 + ], + [ + 0.9323622854457795, + 0.2736037770226561, + -0.046750740902424204, + -0.2694766128926644, + 0.9266468269901011, + 0.08505934868812663 + ], + [ + 0.7082145213423493, + 0.5057879155976068, + -0.1292843866213168, + -0.40439176583942865, + 0.6347085663309945, + 0.33555332738217153 + ], + [ + 0.8982427990165499, + 0.2950524592490826, + 0.0627503373488979, + -0.2763715429420064, + 0.778069062525765, + 0.19379353592068935 + ], + [ + 0.9105744617016933, + 0.016369360481235357, + -0.07569584887948634, + -0.033486553285137534, + 0.8496173234320246, + 0.21904230533531255 + ], + [ + 0.6882767080584764, + 0.5955511200737581, + -0.08124848723001239, + -0.5834207830010164, + 0.6914804470740726, + 0.11382167761563527 + ], + [ + 0.8882486555093166, + 0.27538427869824084, + -0.01228974191901915, + -0.24859239414202747, + 0.8435953343905628, + 0.3008491969860692 + ], + [ + 0.9148076746509485, + 0.31405574340150516, + -0.04722084395994536, + -0.3059965010249088, + 0.9080646151069015, + 0.13019039604544788 + ], + [ + 0.9285892919045312, + 0.030866037195797818, + 0.12647947907729162, + 0.10487086302016164, + 0.6510263985564818, + -0.6485633553979323 + ], + [ + 0.8577813564481768, + 0.13088492176981908, + 0.19172568936972256, + -0.20324086241543313, + 0.7593929943703458, + 0.3610968754681001 + ], + [ + 0.8329444879711122, + 0.13096501948727143, + -0.006701812920528353, + -0.12768589168015806, + 0.7332011680830467, + -0.410332419882313 + ] + ], + [ + [ + 0.35342410333044666, + 0.37778343992340613, + -0.3656882844458515, + 0.5625694421525144, + -0.28073891723115924, + 0.1447993111161881 + ], + [ + 0.8129690354229172, + -0.43106056245075036, + -0.13539594330381308, + 0.419332921866443, + 0.8331867855086651, + -0.08693748387959388 + ], + [ + 0.8263403819498939, + -0.4400181570893105, + 0.04225492132327721, + 0.4413644651876994, + 0.8127482638185244, + -0.06632223105418898 + ], + [ + 0.9575861225255687, + -0.14674404793803839, + 0.039330909880121716, + 0.1379680407640473, + 0.9518113997174975, + 0.017715038562390754 + ], + [ + 0.6664087367217555, + -0.6016252117610432, + -0.09959170411839775, + 0.6059191569360979, + 0.6631111887388893, + 0.06244683912061308 + ], + [ + 0.840034899724324, + -0.393179890703165, + -0.09573445677608361, + 0.4012158203660788, + 0.824435627992569, + 0.16278221485925684 + ], + [ + 0.929610011956829, + -0.2681550287722944, + 0.04091476418418483, + 0.26642651670698386, + 0.9287596213298391, + 0.04314575922682642 + ], + [ + 0.6737960315163251, + -0.534043723919567, + 0.07336329458088058, + 0.4251033603581685, + 0.5686835142482649, + 0.3558898685766221 + ], + [ + 0.8884827719437007, + -0.32570751240857254, + -0.0750030088546745, + 0.29383277284157155, + 0.7822331961322626, + 0.17519168324855686 + ], + [ + 0.9128400671282751, + -0.0766530651767237, + 0.07469703109809132, + 0.07586774440877259, + 0.862447786336261, + 0.2385924757659387 + ], + [ + 0.634693729446199, + -0.6402447616892943, + 0.03431002596031283, + 0.6280822164340597, + 0.6312682078758788, + 0.1173921886105486 + ], + [ + 0.8713183984170721, + -0.30888339052378894, + 0.02026011412634268, + 0.27513245847676465, + 0.8244595363949739, + 0.3118606905675347 + ], + [ + 0.8974279448858026, + -0.33824867319698804, + 0.038706288286308, + 0.3297628153188289, + 0.8905638873576844, + 0.12830656641260185 + ], + [ + 0.9300790575734593, + -0.09656450864063543, + -0.10932420951752735, + -0.08059528413367155, + 0.5699085586749423, + -0.7243876708258533 + ], + [ + 0.8892216015278477, + -0.08082393010546611, + -0.12575582096709223, + 0.13242002431681074, + 0.7833770352633671, + 0.4179501915836627 + ], + [ + 0.8806920298755895, + -0.18759006136631048, + 0.009795459014521056, + 0.15494225264331288, + 0.7695245980193821, + -0.40911509119637185 + ] + ] + ], + "pose_scale": [ + [ + [ + 0.47738003039756033, + 0.42834040201735923, + 0.5575663922035142, + 0.5081505013113163, + 0.44453750863233177, + 0.4522662515648109 + ], + [ + 0.1568778413335337, + 0.2992685924694171, + 0.16389935735264335, + 0.30438038501249454, + 0.1541547676126371, + 0.1 + ], + [ + 0.19040406078002098, + 0.27454770728362404, + 0.1, + 0.27948583710635877, + 0.19477396992208734, + 0.15268827189243755 + ], + [ + 0.1, + 0.22969152691555766, + 0.1, + 0.23249553114921845, + 0.1, + 0.16948918919983283 + ], + [ + 0.24536530943138324, + 0.3153879358173039, + 0.15419152782786466, + 0.31663998549392125, + 0.2546395633317025, + 0.14259668657556596 + ], + [ + 0.17598119266247458, + 0.29483944748928087, + 0.1, + 0.2940200789832226, + 0.18191712654084463, + 0.1 + ], + [ + 0.1, + 0.21041215756158285, + 0.1, + 0.2112978731852781, + 0.1, + 0.1 + ], + [ + 0.21598663924321712, + 0.3041743949575655, + 0.29448944410932926, + 0.22789490678740104, + 0.3398816515777311, + 0.39186818499494386 + ], + [ + 0.11082065694969491, + 0.2656279218275899, + 0.13902123797239435, + 0.2566430053258549, + 0.20386663627049187, + 0.4162260588436956 + ], + [ + 0.10901905280259265, + 0.37465214843586725, + 0.11228065726088234, + 0.3289275075045016, + 0.2010392956193674, + 0.2836184397573961 + ], + [ + 0.25289106425003804, + 0.28524219702045783, + 0.1402701625697324, + 0.2725873725134259, + 0.25446019072525144, + 0.17165588444262328 + ], + [ + 0.14968949296585826, + 0.3216000807929892, + 0.1, + 0.3145750381993087, + 0.1633591583040299, + 0.10195501352140551 + ], + [ + 0.1, + 0.2175293467599986, + 0.1, + 0.21483488618507662, + 0.1, + 0.1 + ], + [ + 0.1, + 0.27081561266502, + 0.20643970309530202, + 0.22346998782509378, + 0.19704447463075717, + 0.2361502573911389 + ], + [ + 0.20650425086522295, + 0.296603968144892, + 0.2823182995737905, + 0.37072606031062993, + 0.2741955974677639, + 0.1974928885020977 + ], + [ + 0.1379682726668655, + 0.44332687021570794, + 0.27098481731433444, + 0.393441902020028, + 0.200140739288171, + 0.28790071134520123 + ] + ], + [ + [ + 0.3779172594053059, + 0.5082676284016726, + 0.44439365126684693, + 0.4759173593366418, + 0.39069702300520043, + 0.45231951749319177 + ], + [ + 0.17143697157622953, + 0.2848505681003613, + 0.15622290520188792, + 0.29227841195974835, + 0.16422795969057727, + 0.1000203086754605 + ], + [ + 0.18868836775907122, + 0.28125824835524194, + 0.1, + 0.28466383920997446, + 0.19317727839886484, + 0.14794616572993355 + ], + [ + 0.1, + 0.22084847879968034, + 0.1, + 0.22512715095302702, + 0.1, + 0.13967337243947728 + ], + [ + 0.27153410423587054, + 0.29447174582339525, + 0.15356957320293912, + 0.30235348597838707, + 0.27985481869673084, + 0.1396766583217309 + ], + [ + 0.183242530691006, + 0.30030609021746646, + 0.1, + 0.2969555356904351, + 0.19016938302594588, + 0.1 + ], + [ + 0.10989076093149508, + 0.2188464024839813, + 0.1, + 0.21872169277212625, + 0.10940052875803818, + 0.1 + ], + [ + 0.23805366570139752, + 0.3158021070548811, + 0.3146641341002102, + 0.23791694941862251, + 0.38819606379258276, + 0.4024027041586969 + ], + [ + 0.12646084581748063, + 0.25834897386536426, + 0.1270865498801677, + 0.2583068809012353, + 0.2292971083831374, + 0.3895918299447286 + ], + [ + 0.11925654300714918, + 0.360065754145536, + 0.10676236523690993, + 0.33139121367242125, + 0.17026676288391257, + 0.2338602673983779 + ], + [ + 0.2897860273664923, + 0.2798254152187358, + 0.1542567093857019, + 0.26601810629208217, + 0.297189601227268, + 0.18478355236554964 + ], + [ + 0.16652817423472846, + 0.3281717669767464, + 0.1, + 0.3216515004822605, + 0.18113505403945018, + 0.10508052747437102 + ], + [ + 0.13794546504801605, + 0.23442621950215597, + 0.1, + 0.23214541146508882, + 0.13838603073512032, + 0.1 + ], + [ + 0.1, + 0.2633183373481753, + 0.2010529504876328, + 0.1923730278839243, + 0.23137558868980398, + 0.23114733911766272 + ], + [ + 0.17129145919110877, + 0.25693479672160474, + 0.3026246114136396, + 0.3385712189270865, + 0.21714992169620637, + 0.17977329156092683 + ], + [ + 0.10859328916092682, + 0.33415009628879855, + 0.2562162701162618, + 0.3157150484821488, + 0.17991744349231412, + 0.29052255546413885 + ] + ] + ], + "variance_floors": { + "xyz_m": 0.1, + "beta": 0.5, + "pose_component": 0.1 + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/normalized_loss.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/normalized_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..2d40a1cac85bb09954e56951e9ee9e82ab61262a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/normalized_loss.py @@ -0,0 +1,171 @@ +"""Normalized U0 supervision with a direct six-component rotation loss.""" + +from __future__ import annotations + +import math + +import torch +from torch import nn +from torch.nn import functional as F + +from foundation_hand.data.schema import supervision_mask +from foundation_hand.geometry.rotations import axis_angle_to_matrix + + +def canonical_rotation_6d(raw: torch.Tensor) -> torch.Tensor: + first = F.normalize(raw[..., :3].float(), dim=-1) + second_raw = raw[..., 3:].float() + second = F.normalize( + second_raw - (first * second_raw).sum(dim=-1, keepdim=True) * first, + dim=-1, + ) + return torch.cat((first, second), dim=-1) + + +def hand_tail_weights(batch: dict[str, torch.Tensor], enabled: bool) -> torch.Tensor: + valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + weight = torch.ones_like(valid, dtype=torch.float32) + if not enabled: + return weight + joints = torch.nan_to_num(batch["joint3d_camera"].float()) + fingers = joints[..., 1:, :].reshape(*joints.shape[:-2], 5, 4, 3) + bones = fingers[..., 1:, :] - fingers[..., :-1, :] + lengths = torch.linalg.vector_norm(bones, dim=-1) + unit = bones / lengths.clamp_min(1e-8)[..., None] + cosine = (unit[..., :-1, :] * unit[..., 1:, :]).sum(dim=-1).clamp(-1, 1) + distal = cosine[..., 1:, :] + joint_valid = batch["joint3d_root_relative_valid"].bool() + fingers_valid = joint_valid[..., 1:].reshape(*joint_valid.shape[:-1], 5, 4) + complete = fingers_valid[..., 1:, :].all(dim=(-1, -2)) & valid + complete &= (lengths[..., 1:, :] > 1e-6).all(dim=(-1, -2)) + two_45 = (distal <= math.cos(math.pi / 4)).sum(dim=(-1, -2)) >= 2 + any_60 = (distal <= 0.5).any(dim=(-1, -2)) + return weight + 0.5 * (complete & two_45).float() + 0.5 * (complete & any_60).float() + + +def masked_weighted_l1( + prediction: torch.Tensor, + target: torch.Tensor, + mask: torch.Tensor, + weight: torch.Tensor | None = None, +) -> torch.Tensor: + mask = torch.broadcast_to(mask.bool(), prediction.shape) + target = torch.where(mask, target, torch.zeros_like(target)) + error = torch.where(mask, (prediction - target).abs(), torch.zeros_like(prediction)) + mass = mask.to(error.dtype) + if weight is not None: + weight = torch.broadcast_to(weight.to(error.dtype), error.shape) + error = error * weight + mass = mass * weight + return error.sum() / mass.sum().clamp_min(1) + + +class NormalizedLoss(nn.Module): + def __init__(self, statistics: dict, coefficients: dict[str, float], tail_enabled: bool): + super().__init__() + self.register_buffer("xyz_center", torch.tensor(statistics["xyz_center"], dtype=torch.float32)) + self.register_buffer("xyz_scale", torch.tensor(statistics["xyz_scale"], dtype=torch.float32)) + self.register_buffer("beta_center", torch.tensor(statistics["beta_center"], dtype=torch.float32)) + self.register_buffer("beta_scale", torch.tensor(statistics["beta_scale"], dtype=torch.float32)) + self.register_buffer("pose_center", torch.tensor(statistics["pose_center"], dtype=torch.float32)) + self.register_buffer("pose_scale", torch.tensor(statistics["pose_scale"], dtype=torch.float32)) + self.coefficients = coefficients + self.tail_enabled = tail_enabled + + def absolute_xyz(self, value: torch.Tensor) -> torch.Tensor: + return (value.float() - self.xyz_center) / self.xyz_scale + + def relative_xyz(self, value: torch.Tensor) -> torch.Tensor: + return value.float() / self.xyz_scale + + def beta(self, value: torch.Tensor) -> torch.Tensor: + return (value.float() - self.beta_center) / self.beta_scale + + def forward( + self, + prediction: dict[str, torch.Tensor], + batch: dict[str, torch.Tensor], + tail_weight: torch.Tensor, + ) -> dict[str, torch.Tensor]: + frame = batch["frame_valid"].bool() + legacy_joint = batch["joint_annotation_valid"].bool() + legacy_mano = batch["mano_annotation_valid"].bool() + legacy_elements = batch["joint_element_valid"].bool() & legacy_joint[..., None] + joint2d_valid = supervision_mask(batch, "joint2d_valid", legacy_elements) & frame[..., None, None] + joint3d_valid = supervision_mask(batch, "joint3d_valid", legacy_elements) & frame[..., None, None] + relative_valid = supervision_mask(batch, "joint3d_root_relative_valid", joint3d_valid) & frame[..., None, None] + translation_valid = supervision_mask(batch, "translation_valid", legacy_joint) & frame[..., None] + pose_valid = supervision_mask(batch, "mano_pose_valid", legacy_mano) & frame[..., None] + shape_valid = supervision_mask(batch, "shape_valid", legacy_mano) & frame[..., None] + vertices_valid = supervision_mask(batch, "vertices_valid", legacy_mano) & frame[..., None] + + wh = batch["image_hw"].to(torch.float32)[:, None, None, None, [1, 0]] + target_2d = batch["joint2d"].float() / wh + losses = {"joint2d": masked_weighted_l1( + prediction["joint2d_norm"].float(), target_2d, joint2d_valid[..., None], + )} + + target_axis = torch.nan_to_num(batch["mano_pose"].float()).reshape(*pose_valid.shape, 16, 3) + target_6d = axis_angle_to_matrix(target_axis)[..., :2, :].reshape(*pose_valid.shape, 16, 6) + predicted_6d = canonical_rotation_6d(prediction["mano_rotations_6d"]) + center = self.pose_center[None, None] + scale = self.pose_scale[None, None] + predicted_6d = (predicted_6d - center) / scale + target_6d = (target_6d - center) / scale + losses["global_orientation"] = masked_weighted_l1( + predicted_6d[..., :1, :], target_6d[..., :1, :], pose_valid[..., None, None], + ) + losses["local_pose"] = masked_weighted_l1( + predicted_6d[..., 1:, :], target_6d[..., 1:, :], pose_valid[..., None, None], + tail_weight[..., None, None] if self.tail_enabled else None, + ) + + losses["translation"] = masked_weighted_l1( + self.absolute_xyz(prediction["wrist_root_translation"]), + self.absolute_xyz(batch["wrist_root_translation"]), translation_valid[..., None], + ) + safe_shape = torch.where(shape_valid[..., None], batch["mano_shape"], + torch.zeros_like(batch["mano_shape"])) + target_shape = safe_shape.sum(dim=1) / shape_valid.sum(dim=1).clamp_min(1)[..., None] + losses["shape"] = masked_weighted_l1( + self.beta(prediction["mano_shape_sequence"]), self.beta(target_shape), + shape_valid.any(dim=1)[..., None], + ) + losses["joint3d_camera"] = masked_weighted_l1( + self.absolute_xyz(prediction["joints_camera"]), + self.absolute_xyz(batch["joint3d_camera"]), joint3d_valid[..., None], + ) + predicted_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + target_relative = batch.get("joint3d_root_relative") + if target_relative is None: + target_relative = batch["joint3d_camera"] - batch["joint3d_camera"][..., :1, :] + losses["joint3d_root_relative"] = masked_weighted_l1( + self.relative_xyz(predicted_relative), self.relative_xyz(target_relative), + relative_valid[..., None], tail_weight[..., None, None] if self.tail_enabled else None, + ) + losses["vertices_camera"] = masked_weighted_l1( + self.absolute_xyz(prediction["vertices_camera"]), + self.absolute_xyz(batch["vertices_camera"]), vertices_valid[..., None, None], + ) + + wrists = prediction["wrist_root_translation"] + target_wrists = batch["wrist_root_translation"] + pair_valid = translation_valid.all(dim=-1) + losses["bimanual_relative_wrist"] = masked_weighted_l1( + self.relative_xyz(wrists[:, :, 1] - wrists[:, :, 0]), + self.relative_xyz(target_wrists[:, :, 1] - target_wrists[:, :, 0]), + pair_valid[..., None], + ) + velocity_valid = translation_valid[:, 1:] & translation_valid[:, :-1] + pred_velocity = wrists[:, 1:] - wrists[:, :-1] + target_velocity = target_wrists[:, 1:] - target_wrists[:, :-1] + losses["temporal_velocity"] = masked_weighted_l1( + self.relative_xyz(pred_velocity), self.relative_xyz(target_velocity), velocity_valid[..., None], + ) + acceleration_valid = velocity_valid[:, 1:] & velocity_valid[:, :-1] + losses["temporal_acceleration"] = masked_weighted_l1( + self.relative_xyz(pred_velocity[:, 1:] - pred_velocity[:, :-1]), + self.relative_xyz(target_velocity[:, 1:] - target_velocity[:, :-1]), + acceleration_valid[..., None], + ) + return {name: value * self.coefficients[name] for name, value in losses.items()} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/source_scaling.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/source_scaling.py new file mode 100644 index 0000000000000000000000000000000000000000..ea41b6cc6937d905bbc13f4f9b4bb448733ea725 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/source_scaling.py @@ -0,0 +1,64 @@ +"""Equal-source loss denominators, including optional weighted hand mass.""" + +from __future__ import annotations + +import torch + + +SOURCES = ("H2O", "ARCTIC", "HOT3D") +TERMS = ( + "joint2d", "joint3d_camera", "joint3d_root_relative", "vertices_camera", + "local_pose", "global_orientation", "shape", "translation", "reprojection", + "temporal_velocity", "temporal_acceleration", "bimanual_relative_wrist", +) + + +def element_counts(batch: dict, tail_weight: torch.Tensor) -> dict[str, float]: + frame = batch["frame_valid"].bool() + joint2d = batch["joint2d_valid"].bool() & frame[..., None, None] + joint3d = batch["joint3d_valid"].bool() & frame[..., None, None] + relative = batch["joint3d_root_relative_valid"].bool() & frame[..., None, None] + hands = batch["translation_valid"].bool() & frame[..., None] + pose = batch["mano_pose_valid"].bool() & frame[..., None] + shape = batch["shape_valid"].bool() & frame[..., None] + vertices = batch["vertices_valid"].bool() & frame[..., None] + k_valid = batch["K_supervision_valid"].bool() & frame + reprojection = batch["reprojection_valid"].bool() & k_valid[..., None, None] + velocity = hands[:, 1:] & hands[:, :-1] + acceleration = velocity[:, 1:] & velocity[:, :-1] + counts = { + "joint2d": joint2d.sum() * 2, + "joint3d_camera": joint3d.sum() * 3, + "joint3d_root_relative": (relative.float() * tail_weight[..., None]).sum() * 3, + "vertices_camera": vertices.sum() * 778 * 3, + "local_pose": (pose.float() * tail_weight).sum() * 15 * 6, + "global_orientation": pose.sum() * 6, + "shape": shape.any(dim=1).sum() * 10, + "translation": hands.sum() * 3, + "reprojection": reprojection.sum() * 2, + "temporal_velocity": velocity.sum() * 3, + "temporal_acceleration": acceleration.sum() * 3, + "bimanual_relative_wrist": hands.all(dim=-1).sum() * 3, + } + return {key: float(value) for key, value in counts.items()} + + +def count_table(samples: list[tuple[str, dict[str, float]]], device: torch.device) -> torch.Tensor: + table = torch.zeros(len(SOURCES), len(TERMS), dtype=torch.float64, device=device) + for source, counts in samples: + row = SOURCES.index(source) + for column, term in enumerate(TERMS): + table[row, column] += counts[term] + return table + + +def scaling(source: str, counts: dict[str, float], global_counts: torch.Tensor, world: int) -> dict[str, float]: + index = SOURCES.index(source) + result = {} + for column, term in enumerate(TERMS): + denominator = float(global_counts[index, column]) + numerator = counts[term] + if numerator and not denominator: + raise RuntimeError("nonzero local mask with zero global denominator") + result[term] = world * numerator / (len(SOURCES) * denominator) if denominator else 0.0 + return result diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/train.py b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/train.py new file mode 100644 index 0000000000000000000000000000000000000000..c0014717d26b5a99d106d5341da5847edb3aaf91 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/u0_normalized6d/train.py @@ -0,0 +1,346 @@ +"""Matched N0/N1 RGB continuation with normalized GT and direct 6D loss.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +import hashlib +import json +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +from torch import nn +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader + +U0_ROOT = Path("/home/wuyifan/unified_mot_u0_depthsafe_20261001") +os.sys.path.insert(0, str(U0_ROOT)) +from common import U0Coverage, U0Dataset, a7, base, code_hashes, model_for, sha, validate_run_contract +from reprojection import fixed_mask_reprojection +from normalized_loss import NormalizedLoss, hand_tail_weights, masked_weighted_l1 +from source_scaling import SOURCES, TERMS, count_table, element_counts, scaling + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +STATISTICS = json.loads((ROOT / "normalization.json").read_text()) + + +def experiment_hashes() -> dict[str, str]: + return code_hashes() | { + "normalized6d/" + path.name: sha(path) + for path in sorted(ROOT.glob("*.py")) + } | {"normalized6d/config.json": sha(ROOT / "config.json"), + "normalized6d/normalization.json": sha(ROOT / "normalization.json")} + + +class Objective(nn.Module): + def __init__(self, model, mode: str): + super().__init__() + self.model = model + self.criterion = NormalizedLoss(STATISTICS, CONFIG["loss_coefficients"], mode == "N1") + + def forward(self, batch, teacher, weights): + prediction = self.model(batch) + losses = self.criterion(prediction, batch, batch["tail_weight"]) + reprojection, nonpositive, minimum_z = fixed_mask_reprojection( + prediction, batch, CONFIG["reprojection_depth_floor_m"], + CONFIG["reprojection_depth_penalty_per_m"], + ) + losses["reprojection"] = reprojection * CONFIG["loss_coefficients"]["reprojection"] + valid = {key: batch[key].bool() for key in ( + "joint3d_valid", "joint3d_root_relative_valid", "vertices_valid", + "translation_valid", "joint2d_valid", + )} + norm = self.criterion + student_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + teacher_relative = teacher["joints_camera"] - teacher["joints_camera"][..., :1, :] + distill = { + "joint3d_camera": CONFIG["loss_coefficients"]["joint3d_camera"] * masked_weighted_l1( + norm.absolute_xyz(prediction["joints_camera"]), norm.absolute_xyz(teacher["joints_camera"]), + valid["joint3d_valid"][..., None]), + "joint3d_root_relative": CONFIG["loss_coefficients"]["joint3d_root_relative"] * masked_weighted_l1( + norm.relative_xyz(student_relative), norm.relative_xyz(teacher_relative), + valid["joint3d_root_relative_valid"][..., None]), + "vertices_camera": CONFIG["loss_coefficients"]["vertices_camera"] * masked_weighted_l1( + norm.absolute_xyz(prediction["vertices_camera"]), norm.absolute_xyz(teacher["vertices_camera"]), + valid["vertices_valid"][..., None, None]), + "translation": CONFIG["loss_coefficients"]["translation"] * masked_weighted_l1( + norm.absolute_xyz(prediction["wrist_root_translation"]), + norm.absolute_xyz(teacher["wrist_root_translation"]), valid["translation_valid"][..., None]), + "joint2d": CONFIG["loss_coefficients"]["joint2d"] * masked_weighted_l1( + prediction["joint2d_norm"].float(), teacher["joint2d_norm"].float(), + valid["joint2d_valid"][..., None]), + } + supervised = sum(losses[name] * weights[name] for name in TERMS) + anchored = CONFIG["rgb_teacher_weight"] * sum(value * weights[name] for name, value in distill.items()) + total = supervised + anchored + with torch.no_grad(): + native_valid = batch["source_native_joint3d_valid"].bool() & valid["joint3d_valid"] + native_error = masked_weighted_l1(prediction["joints_camera"], batch["source_native_joint3d_camera"], native_valid[..., None]) + label_gap = (masked_weighted_l1(batch["joint3d_camera"], batch["source_native_joint3d_camera"], native_valid[..., None]) + if batch["sampling_source_id"][0] == "H2O" else native_error.new_zeros(())) + return (total, supervised.detach(), anchored.detach(), native_error.detach(), + label_gap.detach(), nonpositive, minimum_z) + + +def save_checkpoint(path, model, optimizer, update, hashes, rng_states, exposure, + frozen_hash, smoke, input_checksums, optimizer_names, mode): + if path.exists(): + raise FileExistsError(path) + state = { + "experiment": CONFIG["experiment"], "model": model.state_dict(), + "optimizer": optimizer.state_dict(), "update": update, + "next_global_sample_position": update * CONFIG["global_batch"], + "world_size": CONFIG["world_size"], "global_batch": CONFIG["global_batch"], + "source_exposure": dict(exposure), "parent_sha256": CONFIG["start_checkpoint_sha256"], + "code_sha256": hashes, "target_contract": CONFIG["target_contract"], + "metric_keys": CONFIG["metric_keys"], "rank_rng_states": rng_states, + "frozen_fingerprint": frozen_hash, "complete_backbone": True, + "smoke": smoke, "config": CONFIG, "input_checksums": input_checksums, + "optimizer_parameter_names": optimizer_names, "mode": mode, + "normalization_sha256": sha(ROOT / "normalization.json"), + } + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + temporary.replace(path) + loaded = torch.load(path, map_location="cpu", weights_only=False) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("U0 full checkpoint load-back failed") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--mode", choices=("N0", "N1"), required=True) + args = parser.parse_args() + if not 0 < args.updates <= CONFIG["maximum_updates"]: + raise ValueError("U0 endpoint exceeds registered full-stage budget") + rank, world = int(os.environ.get("RANK", 0)), int(os.environ.get("WORLD_SIZE", 1)) + local = int(os.environ.get("LOCAL_RANK", 0)) + if world != CONFIG["world_size"] or CONFIG["global_batch"] % world: + raise RuntimeError("U0 requires registered six-rank/global-batch contract") + accumulation = CONFIG["global_batch"] // world + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.cuda.set_device(local) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + device = torch.device("cuda", local) + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + if shutil.disk_usage(ROOT).free < CONFIG["minimum_free_disk_gib"] * 1024**3: + raise RuntimeError("U0 disk reserve below registered minimum") + registration = validate_run_contract() + hashes = experiment_hashes() + seed = CONFIG["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + student = model_for("student").to(device).train() + teacher = model_for("teacher").to(device).eval() + frozen_hash = a7.reference.frozen_fingerprint(student) + trainable = [(name, parameter) for name, parameter in student.named_parameters() if parameter.requires_grad] + new = [parameter for name, parameter in trainable if name.startswith("decoder.spatial.")] + inherited = [parameter for name, parameter in trainable if not name.startswith("decoder.spatial.")] + optimizer_names = ([name for name, _ in trainable if name.startswith("decoder.spatial.")] + + [name for name, _ in trainable if not name.startswith("decoder.spatial.")]) + if not new or not inherited: + raise RuntimeError("U0 optimizer lost new or inherited trainable parameters") + optimizer = torch.optim.AdamW([ + {"params": new, "lr_scale": 1.0}, + {"params": inherited, "lr_scale": CONFIG["learning_rate_inherited"] / CONFIG["learning_rate_new_mot"]}, + ], lr=CONFIG["learning_rate_new_mot"], weight_decay=CONFIG["weight_decay"]) + start, exposure, input_checksums = 0, Counter(), [] + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False) + for key, value in (("experiment", CONFIG["experiment"]), ("world_size", world), + ("global_batch", CONFIG["global_batch"]), + ("target_contract", CONFIG["target_contract"]), + ("smoke", args.smoke), ("mode", args.mode), + ("normalization_sha256", sha(ROOT / "normalization.json"))): + if state[key] != value: + raise RuntimeError("N0/N1 resume contract differs: " + key) + if state["code_sha256"] != hashes: + raise RuntimeError("N0/N1 resume code or data changed") + student.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + start = state["update"] + if state["next_global_sample_position"] != start * CONFIG["global_batch"]: + raise RuntimeError("U0 resume coverage cursor mismatch") + exposure.update(state["source_exposure"]) + input_checksums = state["input_checksums"] + if state["optimizer_parameter_names"] != optimizer_names: + raise RuntimeError("U0 resume optimizer parameter order changed") + base.restore_rng(state["rank_rng_states"][rank], device) + if a7.reference.frozen_fingerprint(student) != frozen_hash: + raise RuntimeError("N0/N1 resumed frozen parameters changed") + else: + parent = Path(CONFIG["start_checkpoint"]) + if sha(parent) != CONFIG["start_checkpoint_sha256"]: + raise RuntimeError("U0 20K start checkpoint checksum changed") + state = torch.load(parent, map_location="cpu", weights_only=False) + if (state["update"] != 20004 or not state["complete_backbone"] + or state["target_contract"] != CONFIG["target_contract"]): + raise RuntimeError("N0/N1 start checkpoint has incorrect lineage") + student.load_state_dict(state["model"], strict=True) + if a7.reference.frozen_fingerprint(student) != frozen_hash: + raise RuntimeError("N0/N1 start checkpoint changed frozen tensors") + if start >= args.updates: + raise ValueError("resume already reached requested endpoint") + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("U0 fresh run would overwrite metrics") + a7.dump(args.output / "provenance.json", { + "code_sha256": hashes, "mapping": registration["mapping"], + "parent_sha256": CONFIG["start_checkpoint_sha256"], "target_contract": CONFIG["target_contract"], + "metric_keys": CONFIG["metric_keys"], "trainable_parameters": sum(p.numel() for _, p in trainable), + "new_mot_parameters": sum(p.numel() for p in new), "inherited_parameters": sum(p.numel() for p in inherited), + "frozen_fingerprint": frozen_hash, "loss": CONFIG["loss_coefficients"], "mode": args.mode, + "source_quota": CONFIG["source_quota_per_update"], "smoke": args.smoke, + "start_checkpoint_sha256": CONFIG["start_checkpoint_sha256"], + "normalization_sha256": sha(ROOT / "normalization.json"), + }) + dist.barrier(device_ids=[local]) + coverage = U0Coverage() + dataset = U0Dataset() + sampler = base.PositionSampler(coverage, start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(dataset, batch_size=1, sampler=sampler, + num_workers=CONFIG["workers_per_rank"], + persistent_workers=CONFIG["workers_per_rank"] > 0, + collate_fn=base.collate_h2o_clips, pin_memory=True, + generator=torch.Generator().manual_seed(seed + 1000000)) + objective = DDP(Objective(student, args.mode).to(device), device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + iterator = iter(loader) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + clock = time.monotonic() + for update in range(start, args.updates): + lr = base.warmup_cosine_learning_rate( + update * CONFIG["global_batch"], CONFIG["full_stage_clips"], + CONFIG["learning_rate_new_mot"], + CONFIG["learning_rate_new_mot"] * CONFIG["minimum_learning_rate_ratio"], + CONFIG["warmup_clips"], + ) + base.set_scheduled_learning_rate(optimizer, lr) + optimizer.zero_grad(set_to_none=True) + cpu_batches = [next(iterator) for _ in range(accumulation)] + for cpu in cpu_batches: + cpu["tail_weight"] = hand_tail_weights(cpu, args.mode == "N1") + descriptors = [ + (batch["sampling_source_id"][0], element_counts(batch, batch["tail_weight"])) + for batch in cpu_batches + ] + local_input_checksums = [] + if args.smoke: + for micro, cpu in enumerate(cpu_batches): + digest = hashlib.sha256() + for key in ("rgb", "K", "frame_valid", "joint3d_camera", "joint2d", + "mano_pose", "mano_shape", "wrist_root_translation", + "photometric_aug_params"): + if key in cpu and torch.is_tensor(cpu[key]): + value = cpu[key].contiguous().reshape(-1).view(torch.uint8) + digest.update(key.encode()) + digest.update(value.numpy().tobytes()) + local_input_checksums.append({ + "position": update * CONFIG["global_batch"] + micro * world + rank, + "source": cpu["sampling_source_id"][0], "sha256": digest.hexdigest(), + }) + global_counts = count_table(descriptors, device) + dist.all_reduce(global_counts) + local_sources = Counter(source for source, _ in descriptors) + source_count = torch.tensor([local_sources[source] for source in SOURCES], device=device) + dist.all_reduce(source_count) + if source_count.tolist() != [CONFIG["source_quota_per_update"][source] for source in SOURCES]: + raise RuntimeError("coverage source quota differs from registered 21/15/24") + totals = torch.zeros(5, device=device) + nonpositive_by_source = torch.zeros(len(SOURCES), dtype=torch.long, device=device) + for micro, (cpu, (source, counts)) in enumerate(zip(cpu_batches, descriptors)): + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, student) + weights = scaling(source, counts, global_counts, world) + with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): + teacher_prediction = teacher(batch) + sync = objective.no_sync() if micro + 1 < accumulation else nullcontext() + with sync, torch.autocast("cuda", dtype=torch.bfloat16): + total, supervised, anchored, native_error, label_gap, nonpositive, minimum_z = objective( + batch, teacher_prediction, weights, + ) + if not bool(torch.isfinite(total)): + raise RuntimeError("nonfinite U0 loss") + total.backward() + totals += torch.stack((total.detach(), supervised, anchored, native_error, label_gap)) + nonpositive_by_source[SOURCES.index(source)] += nonpositive + if int(nonpositive) > 0: + print(json.dumps({"event": "nonpositive_reprojection_depth", + "update": update + 1, "rank": rank, "micro": micro, + "source": source, "tile": cpu["filtered_tile_id"][0], + "joint_count": int(nonpositive), "minimum_z_m": float(minimum_z)}, + allow_nan=False), flush=True) + norm = torch.nn.utils.clip_grad_norm_([p for _, p in trainable], CONFIG["grad_clip"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite U0 gradients") + optimizer.step() + dist.all_reduce(totals) + dist.all_reduce(nonpositive_by_source) + if args.smoke: + gathered = [None] * world + dist.all_gather_object(gathered, local_input_checksums) + input_checksums.extend(sorted((item for group in gathered for item in group), + key=lambda item: item["position"])) + for source, count in zip(SOURCES, source_count.tolist()): + exposure[source] += count + if rank == 0: + row = { + "update": update + 1, "consumed_clips": (update + 1) * CONFIG["global_batch"], + "loss": float(totals[0] / world), "supervised": float(totals[1] / world), + "rgb_anchor": float(totals[2] / world), + "native_joint_error_diagnostic": float(totals[3] / CONFIG["global_batch"]), + "h2o_native_vs_refit_joint_gap_m": float(totals[4] / source_count[0]), + "grad_norm": float(norm), "clipped": float(norm) > CONFIG["grad_clip"], + "lr_new_mot": lr, "lr_inherited": lr * optimizer.param_groups[1]["lr_scale"], + "mode": args.mode, + "source_exposure": dict(exposure), "elapsed_seconds": time.monotonic() - clock, + "nonpositive_reprojection_joints_by_source": dict(zip(SOURCES, nonpositive_by_source.tolist())), + } + log.write(json.dumps(row, allow_nan=False) + "\n") + if update < 5 or (update + 1) % 20 == 0: + print(json.dumps(row, allow_nan=False), flush=True) + if (update + 1 == args.updates or (update + 1) % CONFIG["checkpoint_interval"] == 0 + or update + 1 in CONFIG["evaluation_updates"]): + rng = base.rng_state(device) + states = [None] * world if rank == 0 else None + dist.gather_object(rng, states, dst=0) + if a7.reference.frozen_fingerprint(student) != frozen_hash: + raise RuntimeError("U0 updated frozen DINO/MANO tensors") + if rank == 0: + if shutil.disk_usage(ROOT).free < CONFIG["minimum_free_disk_gib"] * 1024**3: + raise RuntimeError("U0 checkpoint violates disk reserve") + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", student, optimizer, + update + 1, hashes, states, exposure, frozen_hash, args.smoke, + input_checksums, optimizer_names, args.mode) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/__init__.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22d8dd8b2b6b1322e408c586055c7249add4e539 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/__init__.py @@ -0,0 +1,11 @@ +"""Teacher-free ViTPose-L RGB MoT training using this EgoNet source tree.""" + +from pathlib import Path +import sys + +_SOURCE = Path(__file__).resolve().parents[2] / "src" +sys.path.insert(0, str(_SOURCE)) +import foundation_hand # noqa: E402 + +if not Path(foundation_hand.__file__).resolve().is_relative_to(_SOURCE): + raise RuntimeError("ViTPose-L training must use this EgoNet foundation_hand source") diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/audit_resolution.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/audit_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c940207a8da5d66ff485acc51485859017483c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/audit_resolution.py @@ -0,0 +1,85 @@ +"""Check official HOT3D rectified image size and hand size under each target canvas.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from foundation_hand.data.hot3d_dataset import quest_linear_camera_calibration +from .data import MixedResolutionCoverage, MixedResolutionDataset, RESOLUTIONS + + +def hand_extents(sample): + coordinates = sample["joint2d"].float() + valid = sample["joint2d_valid"].bool() & torch.isfinite(coordinates).all(-1) + extents = [] + for frame in range(coordinates.shape[0]): + for side in range(2): + points = coordinates[frame, side][valid[frame, side]] + if len(points) < 5: + continue + size = points.max(dim=0).values - points.min(dim=0).values + extents.append((float(size[0]), float(size[1]))) + return {"valid_hand_frames": len(extents), + "median_bbox_width_px": float(torch.tensor([value[0] for value in extents]).median()) if extents else None, + "median_bbox_height_px": float(torch.tensor([value[1] for value in extents]).median()) if extents else None} + + +def source_image_size(native, row): + provider = native._provider(str(row["recording_id"])) + stream_id = native._api["StreamId"](str(row["stream_id"])) + timestamp = int(row["timestamps_ns"][0]) + device = provider.device_data_provider + if row["headset"] == "Aria": + _, calibration = device.get_online_camera_calibration( + stream_id, timestamp, camera_model=native._api["LINEAR"]) + else: + _, calibration = quest_linear_camera_calibration( + device, stream_id, native._api["LINEAR"], native._api["FISHEYE624"]) + image = device.get_undistorted_image(timestamp, stream_id) + return {"calibration_hw": list(map(int, calibration.get_image_size()[::-1])), + "undistorted_image_hw": list(map(int, image.shape[:2]))} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + coverage, dataset = MixedResolutionCoverage(), MixedResolutionDataset() + found = {} + for position in range(3000): + spec = coverage.sample(position) + if spec["source"] != "HOT3D": + continue + row = dataset.sources["HOT3D"].rows[dataset.sources["HOT3D"].by_tile[spec["tile_id"]]] + headset = row["headset"] + if headset not in found: + found[headset] = (spec, row) + if set(found) == {"Aria", "Quest3"}: + break + if set(found) != {"Aria", "Quest3"}: + raise RuntimeError("coverage audit did not sample both HOT3D headset types") + report = {} + for headset, (spec, row) in found.items(): + entries = [] + for hw in RESOLUTIONS: + sample = dataset[dict(spec, target_hw=hw)] + native = dataset._reader("HOT3D", hw).native + source = source_image_size(native, row) + if source["calibration_hw"] != source["undistorted_image_hw"]: + raise RuntimeError(f"{headset} calibration/image dimensions differ") + entries.append({"target_hw": hw, **source, **hand_extents(sample)}) + report[headset] = {"recording": row["recording_id"], "stream_id": row["stream_id"], + "tile": spec["tile_id"], "resolutions": entries} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps(report, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a8eef379af3d12676bb37549a2df4fa9196e788e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/config.json @@ -0,0 +1,23 @@ +{ + "experiment": "vitpose_l_mot_rgb_from_scratch_20261006", + "status": "approved_protocol_v1", + "visual_sha256": "82dea141d75805068ce80705b9a3965af9cbc62a1844c46d88238012a2c2097f", + "initialization": "ViTPose-L visual-only; all other weights random; no teacher or old MANO checkpoint", + "source_quota_per_update": {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}, + "global_batch": 60, + "frames": 8, + "resolutions_hw": [[512, 896], [368, 640], [512, 512]], + "resolution_pct_by_source": { + "H2O": [75, 20, 5], "ARCTIC": [70, 20, 10], + "HOT3D_Aria": [30, 15, 55], "HOT3D_Quest3": [60, 20, 20] + }, + "optimizer": {"name": "AdamW", "new_lr_peak": 0.00005, "visual_last2_lr_peak": 0.000001, + "weight_decay": 0.05, "clip_grad_norm": 100, "freeze_visual_updates": 5000, + "warmup_updates": 1000, "visual_warmup_updates": 1000, + "minimum_lr_ratio": 0.1, "initial_endpoint_updates": 120000}, + "evaluation_updates": [5000, 10000, 20000, 40000, 60000, 80000, 100000, 120000], + "loss_source": "experiments/from_scratch_mean_pose/config.json shared.loss", + "statistics_source": "experiments/from_scratch_mean_pose/statistics_mano_pkl_v2.json", + "prohibit_teacher": true, + "prohibit_old_model_checkpoint": true +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c1ca8402e9e2f8e4bba357079926ea2fc1157e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/controller.py @@ -0,0 +1,195 @@ +"""Wait for six idle G1 GPUs, then run staged training and native-GT evaluation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +from .train import CONFIG + + +ROOT = Path(__file__).resolve().parents[2] +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +TORCHRUN = "/SSD2/jiasen/envs/foundation_hand/bin/torchrun" +SOURCES = ("H2O", "ARCTIC", "HOT3D") +HK = ROOT / "docs/HK.md" + + +def gpu_idle(indices, max_memory_mib=200, max_utilization_pct=5): + result = subprocess.run(["nvidia-smi", "--query-gpu=index,memory.used,utilization.gpu", + "--format=csv,noheader,nounits"], text=True, capture_output=True, check=True) + usage = {} + for line in result.stdout.splitlines(): + gpu, memory, utilization = (int(value.strip()) for value in line.split(",")) + usage[gpu] = {"memory_mib": memory, "utilization_pct": utilization} + return all(index in usage and usage[index]["memory_mib"] <= max_memory_mib + and usage[index]["utilization_pct"] <= max_utilization_pct for index in indices), usage + + +def write_status(path, **fields): + value = {"time_hkt": datetime.now().astimezone().isoformat(), **fields} + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") + os.replace(temporary, path) + + +def wait_for_idle(indices, status, stage, samples=3, interval=30): + streak = 0 + while streak < samples: + try: + free, usage = gpu_idle(indices) + except (OSError, subprocess.SubprocessError, ValueError) as error: + free, usage = False, {"error": str(error)} + streak = streak + 1 if free else 0 + write_status(status, state="waiting_for_idle_gpus", stage=stage, + idle_streak=streak, required_streak=samples, usage=usage) + if streak < samples: + time.sleep(interval) + + +def run_logged(command, log_path, env, status, state, stage): + write_status(status, state=state, stage=stage, command=command, log=str(log_path)) + with log_path.open("a", buffering=1) as log: + log.write(json.dumps({"event": "start", "time_hkt": datetime.now().astimezone().isoformat(), + "command": command}) + "\n") + result = subprocess.run(command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT) + log.write(json.dumps({"event": "exit", "time_hkt": datetime.now().astimezone().isoformat(), + "returncode": result.returncode}) + "\n") + if result.returncode: + write_status(status, state="failed_needs_review", stage=stage, + returncode=result.returncode, log=str(log_path)) + raise RuntimeError(f"{stage} failed with code {result.returncode}: {log_path}") + + +def record_evaluation(update, output): + reports = {source: json.loads((output / "evaluations" / + f"update_{update:07d}_{source.lower()}.json").read_text()) + for source in SOURCES} + lines = [f"\n## {datetime.now().astimezone():%Y-%m-%d %H:%M} HKT: ViTPose-L + MoT {update:,} 更新评估\n", + "\n训练为视觉主干预训练 + 其它部分从头,纯 RGB、T=8、三源 21/15/24;下表为固定 held-out source-native GT,未使用 teacher 或 parent checkpoint。\n", + "\n| Source / group | Abs MPJPE mm | Root MPJPE mm | MPVPE mm | 2D px | local pose deg | bend bias deg | pred/GT 6D var |\n", + "|---|---:|---:|---:|---:|---:|---:|---:|\n"] + names = ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", "local_pose_angle_deg", "bend_bias_deg") + for source in SOURCES: + report = reports[source] + for group in ("all", "hard_pose"): + values = [report[group]["metrics"][name]["mean"] for name in names] + cells = [f"{value:.3f}" if value is not None else "n/a" for value in values] + ratio = report[group]["pred_gt_local_6d_variance_ratio_macro"] + cells.append(f"{ratio:.3f}" if ratio is not None else "n/a") + lines.append(f"| {source} / {group} | " + " | ".join(cells) + " |\n") + lines.append("\n完整报告与逐手记录见本实验 `evaluations/`;单节点结果不等于收敛结论,继续看后续节点的四指标、hard pose 与 normal no-harm。\n") + with HK.open("a") as document: + document.writelines(lines) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--idle-samples", type=int, default=3) + parser.add_argument("--idle-interval", type=int, default=30) + parser.add_argument("--workers", type=int, default=2) + args = parser.parse_args() + if args.idle_samples < 2 or args.idle_interval < 10 or args.workers < 1: + raise ValueError("idle gate must cover multiple samples and at least 10-second intervals") + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + (output / "evaluations").mkdir(exist_ok=True) + status = output / "controller_status.json" + smoke_output = output.parent / "smoke_nanmask_opencv_v1" + smoke_checkpoint = smoke_output / "update_0000002.pt" + resolution_audit = output.parent / "hot3d_resolution_audit.json" + if not resolution_audit.is_file(): + raise RuntimeError("HOT3D resolution audit is missing") + endpoints = CONFIG["evaluation_updates"] + if endpoints != [5000, 10000, 20000, 40000, 60000, 80000, 100000, 120000]: + raise RuntimeError("evaluation cadence changed") + env = os.environ.copy() + env["CUDA_VISIBLE_DEVICES"] = "0,1,2,3,4,5" + env["OMP_NUM_THREADS"] = "1" + env["OPENBLAS_NUM_THREADS"] = "1" + env["MKL_NUM_THREADS"] = "1" + for endpoint in (1, 2): + checkpoint = smoke_output / f"update_{endpoint:07d}.pt" + if checkpoint.is_file(): + continue + previous = smoke_output / "update_0000001.pt" if endpoint == 2 else None + if previous is not None and not previous.is_file(): + raise RuntimeError("post-fix smoke step-1 checkpoint missing") + wait_for_idle((0, 1), status, f"postfix_smoke_{endpoint}", + samples=args.idle_samples, interval=args.idle_interval) + smoke_env = env.copy() + smoke_env["CUDA_VISIBLE_DEVICES"] = "0,1" + command = [TORCHRUN, "--standalone", "--nnodes=1", "--nproc_per_node=2", + "-m", "experiments.vitpose_mot_from_scratch.train", "--output", str(smoke_output), + "--updates", str(endpoint), "--smoke", "--workers", str(args.workers), "--log-every", "1"] + if previous: + command += ["--resume", str(previous)] + run_logged(command, output / f"postfix_smoke_{endpoint}.log", smoke_env, + status, "preflight_training", endpoint) + if not checkpoint.is_file(): + raise RuntimeError(f"post-fix smoke returned without checkpoint {checkpoint}") + for source in SOURCES: + report = output / "evaluations" / f"preflight_smoke_{source.lower()}.json" + if report.is_file(): + continue + wait_for_idle((0,), status, f"preflight_eval_{source}", samples=2, interval=15) + smoke_env = env.copy() + smoke_env["CUDA_VISIBLE_DEVICES"] = "0" + run_logged([PYTHON, "-m", "experiments.vitpose_mot_from_scratch.evaluate", + "--checkpoint", str(smoke_checkpoint), "--source", source, + "--output", str(report), "--limit", "2", "--smoke"], + output / f"preflight_eval_{source.lower()}.log", smoke_env, + status, "preflight_evaluation", source) + for endpoint in endpoints: + checkpoint = output / f"update_{endpoint:07d}.pt" + previous = output / f"update_{endpoints[endpoints.index(endpoint) - 1]:07d}.pt" if endpoint != endpoints[0] else None + if not checkpoint.is_file(): + if previous is not None and not previous.is_file(): + raise RuntimeError(f"missing previous full checkpoint: {previous}") + wait_for_idle(range(6), status, f"train_to_{endpoint}", + samples=args.idle_samples, interval=args.idle_interval) + command = [TORCHRUN, "--standalone", "--nnodes=1", "--nproc_per_node=6", + "-m", "experiments.vitpose_mot_from_scratch.train", "--output", str(output), + "--updates", str(endpoint), "--workers", str(args.workers), "--log-every", "25"] + if previous: + command += ["--resume", str(previous)] + run_logged(command, output / f"train_to_{endpoint:07d}.log", env, status, + "training", endpoint) + if not checkpoint.is_file(): + raise RuntimeError(f"training returned without checkpoint {checkpoint}") + for source in SOURCES: + report = output / "evaluations" / f"update_{endpoint:07d}_{source.lower()}.json" + if report.is_file(): + continue + wait_for_idle((0,), status, f"eval_{endpoint}_{source}", samples=2, interval=15) + eval_env = env.copy() + eval_env["CUDA_VISIBLE_DEVICES"] = "0" + run_logged([PYTHON, "-m", "experiments.vitpose_mot_from_scratch.evaluate", + "--checkpoint", str(checkpoint), "--source", source, + "--output", str(report)], + output / f"eval_{endpoint:07d}_{source.lower()}.log", eval_env, + status, "evaluating", f"{endpoint}_{source}") + marker = output / "evaluations" / f"update_{endpoint:07d}_hk_recorded.json" + if not marker.exists(): + record_evaluation(endpoint, output) + marker.write_text(json.dumps({"update": endpoint, + "recorded_at": datetime.now().astimezone().isoformat()}) + "\n") + write_status(status, state="evaluated", stage=endpoint, + checkpoint=str(checkpoint), next_endpoint=next((value for value in endpoints if value > endpoint), None)) + write_status(status, state="complete_120k_waiting_for_curve_review", stage=120000) + + +if __name__ == "__main__": + try: + main() + except Exception as error: + print(f"controller failed: {error}", file=sys.stderr, flush=True) + raise diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/data.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/data.py new file mode 100644 index 0000000000000000000000000000000000000000..f3d981a771119db3a1d1d71cdd820eaa166f68ec --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/data.py @@ -0,0 +1,92 @@ +"""Canonical train-only RGB clips with deterministic source-specific resolutions.""" + +from __future__ import annotations + +import hashlib + +import torch + +from experiments.from_scratch_mean_pose.smoke import U0Coverage, U0Dataset, a7, base +from experiments.a7_rotation_fix.filtered_dataset import intersect_filtered_valid + + +RESOLUTIONS = ((512, 896), (368, 640), (512, 512)) +RESOLUTION_PCT = { + "H2O": (75, 20, 5), + "ARCTIC": (70, 20, 10), + "HOT3D_Aria": (30, 15, 55), + "HOT3D_Quest3": (60, 20, 20), +} + + +def mask_invalid_joint3d(sample: dict) -> None: + sample["joint3d_valid"] &= torch.isfinite(sample["joint3d_camera"]).all(dim=-1) + + +def resolution_for(source: str, headset: str | None, position: int) -> tuple[int, int]: + name = f"{source}_{headset}" if source == "HOT3D" else source + weights = RESOLUTION_PCT[name] + digest = hashlib.blake2b(f"20261006:{position}:{name}".encode(), digest_size=8).digest() + draw = int.from_bytes(digest, "big") % 100 + return RESOLUTIONS[0 if draw < weights[0] else 1 if draw < weights[0] + weights[1] else 2] + + +class MixedResolutionCoverage(U0Coverage): + def __init__(self): + super().__init__() + self.seed = 20261003 + + def sample(self, position): + spec = super().sample(position) + if spec["source"] == "HOT3D": + # The immutable filtered manifest resolves headset by tile ID. + spec["target_hw"] = None + else: + spec["target_hw"] = resolution_for(spec["source"], None, position) + return spec + + +class MixedResolutionDataset(U0Dataset): + def __init__(self): + super().__init__() + self.alternates = {} + + def _reader(self, source, target_hw): + if target_hw == (512, 896): + return self.sources[source] + key = (source, target_hw) + if key not in self.alternates: + self.alternates[key] = base.FilteredClipDataset( + source, + base.MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl", + 8, target_hw, base.ASSETS["mano_root"], + a7.reference.BASE_CODE / "third_party", + {"enabled": source != "HOT3D", "probability": .8}, + ) + return self.alternates[key] + + def __getitem__(self, spec): + source = spec["source"] + anchor = self.sources[source] + row = anchor.rows[anchor.by_tile[spec["tile_id"]]] + target_hw = spec["target_hw"] + if target_hw is None: + target_hw = resolution_for(source, row["headset"], spec["position"]) + original = self._reader(source, target_hw) + sample = original[spec] + if sample["input_mode"] != "rgb": + raise RuntimeError("ViTPose-L experiment requires RGB-only input") + native_joints = sample["joint3d_camera"].clone() + native_valid = sample["joint3d_valid"].clone() + row = original.rows[original.by_tile[spec["tile_id"]]] + sample = self.labels[source].apply(sample, row, original.native) + intersect_filtered_valid(sample, row) + mask_invalid_joint3d(sample) + quality = sample["vertices_valid"].bool() + sample["global_orientation_valid"] &= quality + sample["local_pose_valid"] &= quality + sample["source_native_joint3d_camera"] = native_joints + sample["source_native_joint3d_valid"] = native_valid + if tuple(sample["rgb"].shape[-2:]) != target_hw: + raise RuntimeError(f"source reader returned wrong target shape for {source}") + return sample diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/evaluate.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..d31e5a33273ea1d897b0b64e864ae7040957d00f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/evaluate.py @@ -0,0 +1,178 @@ +"""Frozen source-native development benchmark and hard-pose diagnostics.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + +import numpy as np +import torch + +from experiments.from_scratch_mean_pose.smoke import a7, base, sha + +from clean_eval import apply_mode, dataset_for +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from scripts.evaluate_phase7_external import make_row +from targets import NativePanel + +from .model import build_model +from .train import CONFIG, STATS, verify_contract + + +FOUR = ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px") + + +def finite(value): + if isinstance(value, dict): + return {key: finite(item) for key, item in value.items()} + if isinstance(value, list): + return [finite(item) for item in value] + return None if isinstance(value, float) and not math.isfinite(value) else value + + +def finger_angles(joints): + fingers = joints[..., 1:, :].reshape(*joints.shape[:-2], 5, 4, 3) + bones = fingers[..., 1:, :] - fingers[..., :-1, :] + lengths = torch.linalg.vector_norm(bones, dim=-1) + unit = bones / lengths.clamp_min(1e-8)[..., None] + angles = torch.rad2deg(torch.acos((unit[..., :-1, :] * unit[..., 1:, :]).sum(-1).clamp(-1, 1))) + complete = (lengths > 1e-6).all(dim=(-1, -2)) & torch.isfinite(angles).all(dim=(-1, -2)) + return angles, complete + + +def summarize(rows): + result = {} + for key in (*FOUR, "local_pose_angle_deg", "fingertip_root_relative_mm", + "bend_bias_deg", "gt60_bend_bias_deg"): + values = [row[key] for row in rows if row.get(key) is not None and math.isfinite(row[key])] + result[key] = {"mean": float(np.mean(values)) if values else None, "count": len(values)} + complete = [row for row in rows if "gt_local_6d" in row] + if len(complete) > 1: + gt = np.asarray([row["gt_local_6d"] for row in complete], dtype=np.float64) + pred = np.asarray([row["pred_local_6d"] for row in complete], dtype=np.float64) + gt_variance = gt.var(axis=0) + pred_variance = pred.var(axis=0) + eligible = gt_variance > 1e-8 + ratio = pred_variance[eligible] / gt_variance[eligible] + variance_ratio = float(ratio.mean()) if ratio.size else None + per_joint = np.asarray([row["local_pose_per_joint_deg"] for row in complete], dtype=np.float64).mean(axis=0).tolist() + else: + variance_ratio, per_joint = None, None + return {"hands": len(rows), "metrics": result, + "pred_gt_local_6d_variance_ratio_macro": variance_ratio, + "local_pose_per_joint_mean_deg": per_joint} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--limit", type=int) + parser.add_argument("--smoke", action="store_true") + args = parser.parse_args() + if args.output.exists() or args.output.with_suffix(".rows.json").exists(): + raise FileExistsError(args.output) + if args.limit is not None and args.limit < 1: + raise ValueError("positive limit required") + if (args.limit is not None or "smoke" in str(args.checkpoint)) and not args.smoke: + raise RuntimeError("subset or smoke checkpoint requires explicit --smoke") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] is not None or state["smoke"] != args.smoke): + raise RuntimeError("evaluation checkpoint composition invalid") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + model.load_state_dict(state["model"], strict=True) + model.to("cuda").eval() + panel_root = a7.BASE_ROOT / "eval/frozen_panels_sync_v2" + registry = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_development_t8.jsonl" + registered = registry["sources"][args.source]["development"] + if sha(manifest) != registered["manifest_sha256"] or registry["sources"][args.source]["train_overlap"]: + raise RuntimeError("development panel overlaps training or hash changed") + manifest_rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), + hand_valid_policy="visible_mesh") if args.source == "ARCTIC" + else dataset_for(args.source, manifest)) + dataset = NativePanel(args.source, native, manifest_rows) + limit = min(args.limit, len(dataset)) if args.limit else len(dataset) + rows = [] + with torch.inference_mode(): + for index in range(limit): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, "rgb") + batch = base.move_to_device(batch, torch.device("cuda")) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + if not bool(torch.isfinite(prediction["joints_camera"]).all()): + raise RuntimeError(f"nonfinite development prediction at clip {index}") + pose_valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + joint_valid = batch["joint3d_root_relative_valid"].bool().all(dim=-1) + gt_angles, complete_geometry = finger_angles(batch["joint3d_camera"].float()) + pred_angles, _ = finger_angles(prediction["joints_camera"].float()) + complete = pose_valid & joint_valid & complete_geometry + gt_hard = ((gt_angles >= 45).sum(dim=(-1, -2)) >= 2) | (gt_angles >= 60).any(dim=(-1, -2)) + target_rotation = axis_angle_to_matrix(torch.nan_to_num(batch["mano_pose"].float()).reshape( + *pose_valid.shape, 16, 3)) + relative = prediction["mano_rotation_matrices"].float() @ target_rotation.transpose(-1, -2) + trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1) + angle_error = torch.rad2deg(torch.acos(((trace - 1) / 2).clamp(-1, 1))) + predicted_rel = prediction["joints_camera"].float() - prediction["joints_camera"].float()[..., :1, :] + target_rel = batch["joint3d_camera"].float() - batch["joint3d_camera"].float()[..., :1, :] + tip_error = torch.linalg.vector_norm(predicted_rel[..., [4, 8, 12, 16, 20], :] + - target_rel[..., [4, 8, 12, 16, 20], :], dim=-1).mean(-1) * 1000 + for frame in range(batch["frame_valid"].shape[1]): + if not bool(batch["frame_valid"][0, frame]): + continue + for side in range(2): + row = make_row(prediction, batch, 0, frame, side) + if bool(complete[0, frame, side]): + gt = gt_angles[0, frame, side] + difference = pred_angles[0, frame, side] - gt + high = gt >= 60 + row.update({ + "gt_hard": bool(gt_hard[0, frame, side]), + "local_pose_angle_deg": float(angle_error[0, frame, side, 1:].mean()), + "fingertip_root_relative_mm": float(tip_error[0, frame, side]), + "bend_bias_deg": float(difference.mean()), + "gt60_bend_bias_deg": float(difference[high].mean()) if bool(high.any()) else None, + "local_pose_per_joint_deg": angle_error[0, frame, side, 1:].tolist(), + "gt_local_6d": target_rotation[0, frame, side, 1:, :2, :].reshape(15, 6).tolist(), + "pred_local_6d": prediction["mano_rotation_matrices"][0, frame, side, 1:, :2, :].float().reshape(15, 6).tolist(), + }) + else: + row.update({"gt_hard": None, "local_pose_angle_deg": None, + "fingertip_root_relative_mm": None, + "bend_bias_deg": None, "gt60_bend_bias_deg": None}) + rows.append(row) + if (index + 1) % 32 == 0: + print(json.dumps({"source": args.source, "done": index + 1, "total": limit}), flush=True) + complete_rows = [row for row in rows if row["gt_hard"] is not None] + report = {"experiment": CONFIG["experiment"], "source": args.source, + "role": "development_subset_smoke" if args.limit else "development_full", + "input_mode": "rgb", "frames": 8, "source_native_gt": True, + "training_update": state["update"], "checkpoint_sha256": sha(args.checkpoint), + "panel_sha256": sha(manifest), "clips": limit, + "hard_definition": "GT >=2 distal angles >=45deg or >=1 >=60deg, complete joints and MANO pose", + "all": summarize(rows), "pose_complete": summarize(complete_rows), + "normal_pose": summarize([row for row in complete_rows if not row["gt_hard"]]), + "hard_pose": summarize([row for row in complete_rows if row["gt_hard"]])} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + args.output.with_suffix(".rows.json").write_text(json.dumps(finite(rows), allow_nan=False) + "\n") + print(json.dumps({"source": args.source, "update": state["update"], + "all": report["all"], "hard_pose": report["hard_pose"]}, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/model.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/model.py new file mode 100644 index 0000000000000000000000000000000000000000..8abac2d5f44683a895b752727fe8ebdac9ae617e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/model.py @@ -0,0 +1,96 @@ +"""Full-frame ViTPose-L backbone and freshly initialized MANO MoT.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +import torch +from torch import nn +from torch.utils.checkpoint import checkpoint + +from foundation_hand.models.bimanual import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.encoders import PatchFeatures +from experiments.dinov3_2d_pretrain.vitpose_probe import ViTPoseBackbone +from experiments.from_scratch_mean_pose.model import MeanDeltaRotationHead +from experiments.u0_depthsafe.model import UnifiedRGBDecoder + + +VISUAL_WEIGHTS = Path("/data-hdd/jiasen_rescue_20260815/wuyifan/artifacts/gkdt_feature_probe_20261006/vitpose_large_visual.pt") +VISUAL_SHA256 = "82dea141d75805068ce80705b9a3965af9cbc62a1844c46d88238012a2c2097f" +MANO_ROOT = "/SSD3/jiasen/foundation_hand/pretrained/mano" + + +def verify_visual_weights(path: Path = VISUAL_WEIGHTS) -> None: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + if digest.hexdigest() != VISUAL_SHA256: + raise RuntimeError("ViTPose-L visual checkpoint SHA-256 mismatch") + + +class TrainableViTPoseEncoder(nn.Module): + def __init__(self, weights: Path = VISUAL_WEIGHTS, output_dim: int = 512) -> None: + super().__init__() + verify_visual_weights(weights) + state = torch.load(weights, map_location="cpu", weights_only=True) + if state["pos_embed"].shape != (1, 193, 1024): + raise RuntimeError("unexpected ViTPose-L positional embedding") + if {int(key.split(".")[1]) for key in state if key.startswith("layers.")} != set(range(24)): + raise RuntimeError("ViTPose-L checkpoint is missing transformer blocks") + self.backbone = ViTPoseBackbone(1024, 24, 16) + self.backbone.load_state_dict(state, strict=True) + self.backbone.requires_grad_(False) + self.projection = nn.Linear(1024, output_dim) + self.trainable_last_blocks = 0 + + def unfreeze_last_two(self) -> None: + self.backbone.requires_grad_(False) + for layer in self.backbone.layers[-2:]: + layer.requires_grad_(True) + self.backbone.ln1.requires_grad_(True) + self.trainable_last_blocks = 2 + + def train(self, mode: bool = True): + super().train(mode) + if not self.trainable_last_blocks: + self.backbone.eval() + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + backbone = self.backbone + patches = backbone.patch_embed.projection(images) + rows, cols = patches.shape[-2:] + x = patches.flatten(2).transpose(1, 2) + position = torch.nn.functional.interpolate( + backbone.pos_embed[:, 1:].reshape(1, 16, 12, -1).permute(0, 3, 1, 2), + size=(rows, cols), mode="bicubic", align_corners=False, + ).flatten(2).transpose(1, 2) + with torch.no_grad(): + x = x + position + backbone.pos_embed[:, :1] + for layer in backbone.layers[:-self.trainable_last_blocks or None]: + x = layer(x) + if self.trainable_last_blocks: + for layer in backbone.layers[-self.trainable_last_blocks:]: + x = checkpoint(layer, x, use_reentrant=False) if self.training else layer(x) + x = backbone.ln1(x) + return PatchFeatures(self.projection(x), (rows, cols), 16) + + +def build_model(mean_local: torch.Tensor, *, weights: Path = VISUAL_WEIGHTS) -> BimanualReconstructionModel: + config = ModelConfig( + encoder="vitpose_l", decoder_dim=512, decoder_layers=3, + attention_heads=8, decoder_mode="alternating", + temporal_attention_mode="bidirectional", use_depth=False, use_rays=False, + predict_presence=False, structured_hand_refinement=False, + translation_parameterization="direct_xyz", + joint2d_parameterization="hand_token_linear", mano_root=MANO_ROOT, + require_mano=True, mano_fix_left_shapedirs=True, gradient_checkpointing=True, + ) + model = BimanualReconstructionModel(config, rgb_encoder=TrainableViTPoseEncoder(weights)) + model.decoder = UnifiedRGBDecoder(model.decoder, config.attention_heads) + model.rotation_head = MeanDeltaRotationHead(model.rotation_head, mean_local) + model.mano_layer.requires_grad_(False) + model.joint2d_head.requires_grad_(False) + return model diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/pilot.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/pilot.py new file mode 100644 index 0000000000000000000000000000000000000000..3e80e9f2cc3f55ae569510362367abfa4ce8b701 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/pilot.py @@ -0,0 +1,194 @@ +"""Real-data DDP throughput pilot; output is not a trained checkpoint.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import json +import os +from pathlib import Path +import statistics +import time + +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base +from experiments.from_scratch_mean_pose.throughput_probe import ( + PROBE_FIELDS, collate_probe_samples, initialize_worker, select_clip, +) +from .data import MixedResolutionCoverage, MixedResolutionDataset +from .model import VISUAL_WEIGHTS, build_model + + +class TimedDataset(MixedResolutionDataset): + def __getitem__(self, spec): + started = time.monotonic() + sample = super().__getitem__(spec) + sample["_pilot_load_seconds"] = time.monotonic() - started + sample["_pilot_worker_threads"] = len(os.listdir("/proc/self/task")) + return sample + + +def single_sample(samples): + sample = samples[0] + return {key: value for key, value in sample.items() + if key in PROBE_FIELDS or key.startswith("_pilot_")} + + +def resolution_batches(samples, maximum): + grouped = defaultdict(list) + for sample in samples: + grouped[tuple(sample["rgb"].shape[-2:])].append(sample) + return [collate_probe_samples(group[offset:offset + maximum]) + for group in grouped.values() for offset in range(0, len(group), maximum)] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--last-two", action="store_true") + parser.add_argument("--no-checkpointing", action="store_true") + parser.add_argument("--no-decoder-checkpointing", action="store_true") + parser.add_argument("--no-encoder-checkpointing", action="store_true") + parser.add_argument("--interop-threads", type=int, default=0) + parser.add_argument("--weights", type=Path, default=VISUAL_WEIGHTS) + parser.add_argument("--workers", type=int, default=2) + parser.add_argument("--prefetch-factor", type=int, default=2) + parser.add_argument("--opencv-threads", type=int, default=1) + parser.add_argument("--pin-memory", action="store_true") + parser.add_argument("--clips-per-rank", type=int, default=10) + parser.add_argument("--microbatch-size", type=int, default=1) + parser.add_argument("--collate-in-worker", action="store_true") + parser.add_argument("--warmup", type=int, default=2) + parser.add_argument("--updates", type=int, default=12) + args = parser.parse_args() + if (args.output.exists() or args.workers < 0 or args.prefetch_factor < 1 or args.clips_per_rank < 1 + or args.microbatch_size < 1 or args.warmup < 1 or args.updates <= args.warmup): + raise ValueError("invalid pilot settings or output exists") + if args.collate_in_worker and args.microbatch_size != 1: + raise ValueError("worker-side collate is only available for single-clip microbatches") + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if world not in (2, 3, 4, 6): + raise RuntimeError("pilot requires two, three, four or six GPUs") + if args.interop_threads: + torch.set_num_interop_threads(args.interop_threads) + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError("pilot requires 18 GiB free per GPU") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + fitted = json.loads((BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"]).read_text()) + torch.manual_seed(20261003) + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32), weights=args.weights) + if args.last_two: + model.rgb_encoder.unfreeze_last_two() + model.to(device).train() + if args.no_checkpointing or args.no_decoder_checkpointing: + model.decoder.gradient_checkpointing = False + if args.no_checkpointing or args.no_encoder_checkpointing: + model.rgb_encoder.eval() + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + trainable = [p for p in model.parameters() if p.requires_grad] + optimizer = torch.optim.AdamW(trainable, lr=5e-5, weight_decay=0.05) + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + sampler = base.PositionSampler(MixedResolutionCoverage(), 0, + args.updates * args.clips_per_rank * world, rank, world) + loader = DataLoader(TimedDataset(), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=args.workers > 0, + collate_fn=collate_probe_samples if args.collate_in_worker else single_sample, + pin_memory=args.pin_memory, + prefetch_factor=args.prefetch_factor if args.workers else None, + worker_init_fn=partial(initialize_worker, opencv_threads=args.opencv_threads)) + iterator = iter(loader) + rows = [] + for update in range(args.updates): + torch.cuda.synchronize(device) + start = time.monotonic() + samples = [next(iterator) for _ in range(args.clips_per_rank)] + data_ready = time.monotonic() + source_load = {} + if args.collate_in_worker: + cpu_batches = samples + else: + cpu_batches = resolution_batches(samples, args.microbatch_size) + for sample in samples: + source = sample["sampling_source_id"] + bucket = source_load.setdefault(source, {"clips": 0, "load_seconds": 0.0}) + bucket["clips"] += 1 + bucket["load_seconds"] += sample["_pilot_load_seconds"] + bucket["max_worker_threads"] = max(bucket.get("max_worker_threads", 0), + sample["_pilot_worker_threads"]) + optimizer.zero_grad(set_to_none=True) + for micro, cpu in enumerate(cpu_batches): + count = len(cpu["input_mode"]) + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < len(cpu_batches) else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + losses = [objective(select_clip(prediction, index, count), + select_clip(batch, index, count))[0] + for index in range(count)] + loss = torch.stack(losses).sum() / args.clips_per_rank + if not bool(torch.isfinite(loss)): + raise RuntimeError("nonfinite pilot loss") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(trainable, 100) + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite pilot gradient") + optimizer.step() + torch.cuda.synchronize(device) + rows.append({"update": update + 1, "seconds": time.monotonic() - start, + "data_wait_seconds": data_ready - start, + "source_load": source_load, + "microbatch_sizes": [len(cpu["input_mode"]) for cpu in cpu_batches], + "loss": float(loss.detach()), "preclip_grad_norm": float(norm), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 1024**3}) + if rank == 0: + print(json.dumps({"last_two": args.last_two, + "no_decoder_checkpointing": not model.decoder.gradient_checkpointing, + "no_encoder_checkpointing": not model.rgb_encoder.training, + **rows[-1]}), flush=True) + gathered = [None] * world + dist.all_gather_object(gathered, {"rank": rank, "rows": rows}) + if rank == 0: + slowest = max(statistics.mean(row["seconds"] for row in part["rows"][args.warmup:]) + for part in gathered) + report = {"kind": "gpu_pilot_not_formal_training", "last_two": args.last_two, + "no_decoder_checkpointing": not model.decoder.gradient_checkpointing, + "no_encoder_checkpointing": not model.rgb_encoder.training, + "interop_threads": args.interop_threads, + "world_size": world, "clips_per_rank": args.clips_per_rank, + "microbatch_size_max": args.microbatch_size, + "collate_in_worker": args.collate_in_worker, + "pin_memory": args.pin_memory, + "opencv_threads": args.opencv_threads, + "workers_per_rank": args.workers, "updates": args.updates, + "prefetch_factor": args.prefetch_factor, + "warmup": args.warmup, + "seconds_per_update_slowest_rank": slowest, + "clips_per_second": args.clips_per_rank * world / slowest, + "ranks": gathered} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps({"result": str(args.output), "clips_per_second": report["clips_per_second"]}), flush=True) + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/preflight.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..be32263ca0d0150e09b5ef068a20c954997822a1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/preflight.py @@ -0,0 +1,106 @@ +"""Real-data three-resolution and one-update ViTPose-L/MoT checks.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import time + +import torch + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base +from .data import MixedResolutionCoverage, MixedResolutionDataset, RESOLUTIONS +from .model import build_model, verify_visual_weights + + +def reprojection_error(batch): + joints = batch["joint3d_camera"].float() + k = batch["K"].float() + xy = joints[..., :2] / joints[..., 2:].clamp_min(0.05) + projected = torch.einsum("btij,bthkj->bthki", k[..., :2, :2], xy) + k[..., :2, 2][:, :, None, None] + valid = batch["joint2d_valid"].bool() & batch["joint3d_valid"].bool() & (joints[..., 2] > 0.05) + error = torch.linalg.vector_norm(projected - batch["joint2d"].float(), dim=-1) + return {"valid_joints": int(valid.sum()), + "mean_px": float(error[valid].mean()) if bool(valid.any()) else None, + "p95_px": float(torch.quantile(error[valid], 0.95)) if bool(valid.any()) else None} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), default="H2O") + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--last-two", action="store_true") + parser.add_argument("--geometry-only", action="store_true") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + verify_visual_weights() + fitted = json.loads((BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"]).read_text()) + coverage, dataset = MixedResolutionCoverage(), MixedResolutionDataset() + spec = next(coverage.sample(position) for position in range(600) + if coverage.sample(position)["source"] == args.source) + rows = [] + for hw in RESOLUTIONS: + item = dict(spec, target_hw=hw) + cpu = base.collate_h2o_clips([dataset[item]]) + if cpu["input_mode"] != ["rgb"] or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("RGB-only model input violated") + if tuple(cpu["rgb"].shape) != (1, 8, 3, *hw): + raise RuntimeError("mixed-resolution sample shape violated") + rows.append({"target_hw": hw, "image_hw": cpu["image_hw"].tolist(), + "K": cpu["K"][0, 0].tolist(), "reprojection": reprojection_error(cpu), + "valid_pose_frames": int(cpu["local_pose_valid"].sum()), + "valid_geometry_frames": int(cpu["vertices_valid"].sum())}) + report = {"source": args.source, "tile_id": spec["tile_id"], "three_resolutions": rows, + "visual_weights_verified": True, "last_two": args.last_two} + if not args.geometry_only: + device = torch.device(args.device) + torch.cuda.set_device(device) + free, _ = torch.cuda.mem_get_info(device) + if free < 18 * 1024**3: + raise RuntimeError("pilot GPU has less than 18 GiB free") + torch.manual_seed(20261003) + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if args.last_two: + model.rgb_encoder.unfreeze_last_two() + model.to(device).train() + criterion = FromScratchLoss(fitted, {key: BASE_CONFIG["shared"]["loss"][key] for key in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + trainable = [p for p in model.parameters() if p.requires_grad] + cpu = base.collate_h2o_clips([dataset[dict(spec, target_hw=RESOLUTIONS[0])]]) + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, model) + torch.cuda.reset_peak_memory_stats(device) + start = time.monotonic() + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + forward_seconds = time.monotonic() - start + loss, terms, diagnostics = criterion(prediction, batch) + if not bool(torch.isfinite(loss)) or diagnostics["gt_rotation_orthogonality_max"] > 1e-5: + raise RuntimeError("nonfinite or nonorthogonal 6D target") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(trainable, 100) + torch.cuda.synchronize(device) + report["forward_backward"] = { + "seconds": time.monotonic() - start, "forward_seconds": forward_seconds, + "loss": float(loss.detach()), "weighted_terms": {k: float(v.detach()) for k, v in terms.items()}, + "diagnostics": diagnostics, "preclip_grad_norm": float(norm), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 1024**3, + "trainable_parameters": sum(p.numel() for p in trainable), + "backbone_trainable_parameters": sum(p.numel() for p in model.rgb_encoder.backbone.parameters() if p.requires_grad), + } + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite ViTPose-L pilot gradient") + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps(report, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/train.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fcfb096065bbe94686637d8c2b4e53fabe946793 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_from_scratch/train.py @@ -0,0 +1,316 @@ +"""Six-rank, teacher-free RGB ViTPose-L/MoT training with full resume state.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.fit_targets import mano_pkl_mean +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base, sha +from experiments.from_scratch_mean_pose.throughput_probe import collate_probe_samples, initialize_worker +from .data import MixedResolutionCoverage, MixedResolutionDataset, RESOLUTION_PCT +from .model import MANO_ROOT, VISUAL_SHA256, VISUAL_WEIGHTS, build_model, verify_visual_weights + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +SOURCES = ("H2O", "ARCTIC", "HOT3D") +STATS = BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"] +INDEX = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite") +LABELS = Path("/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json") + + +def code_hashes(): + files = [ROOT / "train.py", ROOT / "model.py", ROOT / "data.py", ROOT / "config.json", + BASE_ROOT / "config.json", BASE_ROOT / "loss.py", BASE_ROOT / "model.py", BASE_ROOT / "fit_targets.py", + BASE_ROOT / "throughput_probe.py", + BASE_ROOT / "statistics_mano_pkl_v2.json", + ROOT.parent / "dinov3_2d_pretrain/vitpose_probe.py", + ROOT.parent / "u0_depthsafe/model.py", + ROOT.parent / "u0_depthsafe/reprojection.py", + ROOT.parent / "u0_normalized6d/normalized_loss.py", + ROOT.parent / "a7_rotation_fix/filtered_dataset.py", + ROOT.parent.parent / "src/foundation_hand/models/bimanual.py", + ROOT.parent.parent / "src/foundation_hand/models/decoder.py", + ROOT.parent.parent / "src/foundation_hand/models/encoders.py", + ROOT.parent.parent / "src/foundation_hand/models/mano.py", + ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py", + ROOT.parent.parent / "src/foundation_hand/data/schema.py", + ROOT.parent.parent / "src/foundation_hand/data/h2o_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/arctic_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/hot3d_dataset.py"] + return {str(path.relative_to(ROOT.parent.parent)): sha(path) for path in files} + + +def verify_contract(fitted): + verify_visual_weights() + if BASE_CONFIG["shared"]["teacher"] != { + "create_model": False, "forward": False, "distillation": False, "rgb_teacher_weight": 0.0, + } or not CONFIG["prohibit_teacher"] or not CONFIG["prohibit_old_model_checkpoint"]: + raise RuntimeError("teacher/parent checkpoint prohibited") + if BASE_CONFIG["shared"]["loss"]["joint2d"] != 0 or BASE_CONFIG["shared"]["loss"]["reprojection"] != 1: + raise RuntimeError("2D supervision must be MANO reprojection only") + if fitted["training_index_sha256"] != sha(INDEX) or fitted["label_inventory_sha256"] != sha(LABELS): + raise RuntimeError("train-only fitted statistics do not match current data") + if fitted["source_quota"] != CONFIG["source_quota_per_update"]: + raise RuntimeError("fitted statistic source mixture differs") + if fitted["version"] != "b0_b1_mano_pkl_mean_delta_v2": + raise RuntimeError("expected official MANO-pkl mean and normalized delta statistics") + mean, hashes = mano_pkl_mean(Path(MANO_ROOT)) + if hashes != fitted["mano_pkl_sha256"] or not torch.allclose( + torch.as_tensor(mean, dtype=torch.float64), + torch.as_tensor(fitted["mean_local"], dtype=torch.float64), atol=1e-7, rtol=0, + ): + raise RuntimeError("official MANO mean/asset mismatch") + if sha(VISUAL_WEIGHTS) != VISUAL_SHA256 or RESOLUTION_PCT != { + key: tuple(value) for key, value in CONFIG["resolution_pct_by_source"].items() + }: + raise RuntimeError("visual asset or mixed resolution contract changed") + if sum(CONFIG["source_quota_per_update"].values()) != CONFIG["global_batch"]: + raise RuntimeError("source quotas do not fill global batch") + return {"code_sha256": code_hashes(), "index_sha256": sha(INDEX), + "labels_sha256": sha(LABELS), "statistics_sha256": sha(STATS), + "visual_sha256": VISUAL_SHA256, "mano_pkl_sha256": hashes} + + +def rng_state(): + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state()} + + +def restore_rng(state): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"]) + torch.cuda.set_rng_state(state["cuda"]) + + +def schedule(update): + settings = CONFIG["optimizer"] + endpoint = settings["initial_endpoint_updates"] + warmup = settings["warmup_updates"] + floor = settings["minimum_lr_ratio"] + fraction = min(1.0, max(0.0, (update - warmup) / (endpoint - warmup))) + factor = max(1 / warmup, (update + 1) / warmup) if update < warmup else ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * fraction))) + visual_stage = update - settings["freeze_visual_updates"] + visual = 0.0 if visual_stage < 0 else settings["visual_last2_lr_peak"] * min( + 1.0, (visual_stage + 1) / settings["visual_warmup_updates"]) * ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * max(0.0, min( + 1.0, (visual_stage - settings["visual_warmup_updates"]) / + (endpoint - settings["freeze_visual_updates"] - settings["visual_warmup_updates"])))))) + return settings["new_lr_peak"] * factor, visual + + +def save_checkpoint(path, model, optimizer, update, provenance, rng_states, exposure, smoke, world): + if path.exists(): + raise FileExistsError(path) + state = {"experiment": CONFIG["experiment"], "model": model.state_dict(), + "optimizer": optimizer.state_dict(), "update": update, + "next_sample_position": update * CONFIG["global_batch"], + "world_size": world, "global_batch": CONFIG["global_batch"], + "source_exposure": dict(exposure), "rank_rng_states": rng_states, + "provenance": provenance, "config": CONFIG, "complete_backbone": True, + "teacher_used": False, "parent_checkpoint": None, "smoke": smoke} + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + loaded = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("full checkpoint load-back failed") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, default=120000) + parser.add_argument("--resume", type=Path) + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--workers", type=int, default=2) + parser.add_argument("--log-every", type=int, default=25) + args = parser.parse_args() + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if (world != 6 and not (args.smoke and world == 2)) or args.updates < 1 or args.updates > CONFIG["optimizer"]["initial_endpoint_updates"]: + raise RuntimeError("formal contract requires six GPUs; two are permitted only for smoke") + if (args.smoke and args.updates > 2) or (not args.smoke and args.updates < 5000): + raise RuntimeError("smoke is at most two updates; formal stage must reach first 5K gate") + if args.workers < 1 or args.log_every < 1: + raise ValueError("workers/log interval must be positive") + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError(f"rank {rank}: less than 18 GiB free") + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=20), device_id=device) + try: + if rank == 0: + args.output.parent.mkdir(parents=True, exist_ok=True) + dist.barrier(device_ids=[local]) + if shutil.disk_usage(args.output.parent).free < 100 * 1024**3: + raise RuntimeError("less than 100 GiB free for complete checkpoints") + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + seed = BASE_CONFIG["shared"]["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + state = None + start = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["world_size"] != world + or state["global_batch"] != CONFIG["global_batch"] + or state["config"] != CONFIG or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] is not None or state["smoke"] != args.smoke): + raise RuntimeError("resume checkpoint contract mismatch") + start = state["update"] + if state["next_sample_position"] != start * CONFIG["global_batch"] or start >= args.updates: + raise RuntimeError("resume cursor or endpoint mismatch") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if start >= CONFIG["optimizer"]["freeze_visual_updates"]: + model.rgb_encoder.unfreeze_last_two() + model.to(device).train() + new = [p for name, p in model.named_parameters() + if not name.startswith("rgb_encoder.backbone.") and p.requires_grad] + visual = [p for name, p in model.named_parameters() + if name.startswith("rgb_encoder.backbone.layers.22.") + or name.startswith("rgb_encoder.backbone.layers.23.") + or name.startswith("rgb_encoder.backbone.ln1.")] + if not new or not visual or any(p.requires_grad for p in model.rgb_encoder.backbone.layers[:22].parameters()): + raise RuntimeError("optimizer parameter partition invalid") + optimizer = torch.optim.AdamW([ + {"params": new, "name": "new", "lr": schedule(start)[0]}, + {"params": visual, "name": "visual_last_two", "lr": schedule(start)[1]}, + ], weight_decay=CONFIG["optimizer"]["weight_decay"]) + exposure = Counter() + if state: + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + exposure.update(state["source_exposure"]) + restore_rng(state["rank_rng_states"][rank]) + del state + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh training would overwrite old metrics") + (args.output / "provenance.json").write_text(json.dumps({ + "experiment": CONFIG["experiment"], "contract": provenance, + "loss_coefficients": BASE_CONFIG["shared"]["loss"], + "optimizer": CONFIG["optimizer"], "workers_per_rank": args.workers, + "resume": str(args.resume) if args.resume else None, "smoke": args.smoke, + }, indent=2) + "\n") + dist.barrier(device_ids=[local]) + sampler = base.PositionSampler(MixedResolutionCoverage(), + start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(MixedResolutionDataset(), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=True, + collate_fn=collate_probe_samples, pin_memory=True, prefetch_factor=2, + worker_init_fn=partial(initialize_worker, opencv_threads=1), + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + clips_per_rank = CONFIG["global_batch"] // world + for update in range(start, args.updates): + if update == CONFIG["optimizer"]["freeze_visual_updates"]: + dist.barrier(device_ids=[local]) + del ddp + model.rgb_encoder.unfreeze_last_two() + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + lr_new, lr_visual = schedule(update) + optimizer.param_groups[0]["lr"] = lr_new + optimizer.param_groups[1]["lr"] = lr_visual + started = time.monotonic() + cpu_batches = [next(iterator) for _ in range(clips_per_rank)] + data_ready = time.monotonic() + counts = Counter(cpu["sampling_source_id"][0] for cpu in cpu_batches) + local_counts = torch.tensor([counts[source] for source in SOURCES], device=device) + dist.all_reduce(local_counts) + if local_counts.tolist() != [CONFIG["source_quota_per_update"][source] for source in SOURCES]: + raise RuntimeError("source quota per update changed") + optimizer.zero_grad(set_to_none=True) + total_loss = 0.0 + term_totals = {key: 0.0 for key in TERMS} + nonpositive = 0 + valid_pose = 0 + for micro, cpu in enumerate(cpu_batches): + if cpu["input_mode"] != ["rgb"] or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("non-RGB input reached ViTPose-L") + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < clips_per_rank else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + loss, terms, diagnostics = objective(prediction, batch) + if not bool(torch.isfinite(loss)) or diagnostics["gt_rotation_orthogonality_max"] > 1e-5: + raise RuntimeError(f"nonfinite loss or invalid GT at update {update + 1}") + (loss / clips_per_rank).backward() + total_loss += float(loss.detach()) / clips_per_rank + for name, value in terms.items(): + term_totals[name] += float(value.detach()) / clips_per_rank + nonpositive += diagnostics["nonpositive_reprojection_joints"] + valid_pose += diagnostics["valid_local_frames"] + trainable = [p for p in model.parameters() if p.requires_grad] + norm = torch.nn.utils.clip_grad_norm_(trainable, CONFIG["optimizer"]["clip_grad_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"nonfinite gradient at update {update + 1}") + optimizer.step() + elapsed = time.monotonic() - started + for source, count in zip(SOURCES, local_counts.tolist()): + exposure[source] += count + if rank == 0 and ((update + 1) % args.log_every == 0 or update < 10): + row = {"update": update + 1, "consumed_clips": (update + 1) * CONFIG["global_batch"], + "seconds": elapsed, "data_wait_seconds": data_ready - started, + "loss_rank0": total_loss, "terms_rank0": term_totals, + "preclip_grad_norm_rank0": float(norm), "nonpositive_rank0": nonpositive, + "valid_local_pose_frames_rank0": valid_pose, + "learning_rate_new": lr_new, "learning_rate_visual": lr_visual, + "exposure": dict(exposure)} + log.write(json.dumps(row, allow_nan=False) + "\n") + print(json.dumps(row, allow_nan=False), flush=True) + if update + 1 in CONFIG["evaluation_updates"] or update + 1 == args.updates: + gathered = [None] * world + dist.all_gather_object(gathered, rng_state()) + if rank == 0: + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", model, + optimizer, update + 1, provenance, gathered, exposure, args.smoke, world) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_geometry_incremental/__init__.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_geometry_incremental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7115811157cc2fa5d5a41c7f0fcca3ee5df324 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_geometry_incremental/__init__.py @@ -0,0 +1 @@ +"""Incremental K and metric-depth experts for the 40K RGB MoT.""" diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_geometry_incremental/data.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_geometry_incremental/data.py new file mode 100644 index 0000000000000000000000000000000000000000..37af15ae13580758d4b6b8cc183796c89235daad --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_geometry_incremental/data.py @@ -0,0 +1,80 @@ +"""The existing canonical GT reader with explicit geometry input modes.""" + +from __future__ import annotations + +import torch + +from experiments.a7_rotation_fix.filtered_dataset import intersect_filtered_valid +from experiments.vitpose_mot_io_v4.data import ( + MixedResolutionCoverage, MixedResolutionDataset, mask_invalid_joint3d, resolution_for, +) + + +class GeometryCoverage(MixedResolutionCoverage): + def __init__(self, stage: str): + super().__init__() + if stage not in ("k", "depth"): + raise ValueError(stage) + self.stage = stage + + def sample(self, position: int): + spec = super().sample(position) + spec["mode"] = "rgb_k" if self.stage == "k" else "rgb_depth_k" + return spec + + +class GeometryDataset(MixedResolutionDataset): + def __getitem__(self, spec): + source = spec["source"] + if spec["mode"] == "rgb_depth_k" and source != "H2O": + raise ValueError("only H2O supplies metric depth") + anchor = self.sources[source] + row = anchor.rows[anchor.by_tile[spec["tile_id"]]] + target_hw = spec["target_hw"] + if target_hw is None: + target_hw = resolution_for(source, row["headset"], spec["position"]) + original = self._reader(source, target_hw) + sample = original[spec] + native_joints = sample["joint3d_camera"].clone() + native_valid = sample["joint3d_valid"].clone() + row = original.rows[original.by_tile[spec["tile_id"]]] + sample = self.labels[source].apply(sample, row, original.native) + intersect_filtered_valid(sample, row) + mask_invalid_joint3d(sample) + quality = sample["vertices_valid"].bool() + sample["global_orientation_valid"] &= quality + sample["local_pose_valid"] &= quality + sample["source_native_joint3d_camera"] = native_joints + sample["source_native_joint3d_valid"] = native_valid + if tuple(sample["rgb"].shape[-2:]) != target_hw: + raise RuntimeError("source reader returned wrong target resolution") + if not torch.equal(sample["K_input_available"], sample["frame_valid"]): + raise RuntimeError("geometry stage requires calibrated frames") + if spec["mode"] == "rgb_depth_k" and not torch.equal( + sample["depth_input_available"], sample["frame_valid"] + ): + raise RuntimeError("depth stage requires metric depth on each valid frame") + return sample + + +class StageSampler: + def __init__(self, stage: str, start_sample: int, end_sample: int): + self.stage = stage + self.start_sample = start_sample + self.end_sample = end_sample + + def __iter__(self): + coverage = GeometryCoverage(self.stage) + position = 0 + accepted = 0 + while accepted < self.end_sample: + spec = coverage.sample(position) + position += 1 + if self.stage == "depth" and spec["source"] != "H2O": + continue + if accepted >= self.start_sample: + yield spec + accepted += 1 + + def __len__(self): + return self.end_sample - self.start_sample diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_geometry_incremental/model.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_geometry_incremental/model.py new file mode 100644 index 0000000000000000000000000000000000000000..2b602f6fc35bc99005bb4593112a425aa6a38c7d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_geometry_incremental/model.py @@ -0,0 +1,284 @@ +"""Type-specific geometry experts on a frozen RGB/HAND MoT.""" + +from __future__ import annotations + +import copy +import math + +import torch +from torch import nn +from torch.nn import functional as F + +from foundation_hand.data.schema import input_availability +from foundation_hand.geometry.camera import patch_center_rays +from foundation_hand.models.bimanual import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.encoders import PatchFeatures +from experiments.from_scratch_mean_pose.model import MeanDeltaRotationHead +from experiments.u0_depthsafe.model import MoTSpatialBlock, UnifiedRGBDecoder +from experiments.vitpose_mot_io_v4.model import MANO_ROOT, TrainableViTPoseEncoder + + +class BearingEncoder(nn.Module): + def __init__(self, dim: int, reduction: int = 4): + super().__init__() + self.reduction = reduction + self.projection = nn.Sequential( + nn.Linear(7, dim // 2), nn.GELU(), nn.Linear(dim // 2, dim), nn.LayerNorm(dim), + ) + + def forward(self, K: torch.Tensor, grid_hw: tuple[int, int], patch_size: int) -> torch.Tensor: + coarse = tuple(math.ceil(size / self.reduction) for size in grid_hw) + rays = patch_center_rays(K, coarse, patch_size * self.reduction) + unit = F.normalize(rays, dim=-1) + angular_pixel = torch.stack(( + patch_size * self.reduction / K[:, 0, 0], + patch_size * self.reduction / K[:, 1, 1], + ), dim=-1)[:, None].expand(-1, rays.shape[1], -1) + features = torch.cat((unit, rays[..., :2], angular_pixel), dim=-1) + return self.projection(features) + + +class CompactMetricDepthEncoder(nn.Module): + """Patch-level camera XYZ and support, without a full-resolution CNN.""" + + def __init__(self, dim: int, patch_size: int): + super().__init__() + self.patch_size = patch_size + self.dim = dim + self.input_context = None + self.projection = nn.Sequential( + nn.Linear(6, dim // 2), nn.GELU(), nn.Linear(dim // 2, dim), nn.LayerNorm(dim), + ) + + def forward(self, depth_m: torch.Tensor, valid: torch.Tensor, K: torch.Tensor) -> PatchFeatures: + if self.input_context is not None: + context = self.input_context + if not bool(context["available"].any()): + _, _, height, width = depth_m.shape + grid_hw = (height // self.patch_size, width // self.patch_size) + zeros = K.new_zeros((K.shape[0], grid_hw[0] * grid_hw[1], self.dim)) + return PatchFeatures(zeros, grid_hw, self.patch_size) + depth_m, valid, K = context["depth"], context["valid"], context["K"] + if depth_m.ndim != 4 or valid.shape != depth_m.shape or depth_m.shape[1] != 1: + raise ValueError("depth and validity must be aligned [BT,1,H,W]") + _, _, height, width = depth_m.shape + if height % self.patch_size or width % self.patch_size: + raise ValueError("depth dimensions must be divisible by patch size") + valid = valid & torch.isfinite(depth_m) & (depth_m > 0) + depth = torch.where(valid, depth_m, torch.zeros_like(depth_m)) + support = F.avg_pool2d(valid.to(depth.dtype), self.patch_size) + z = F.avg_pool2d(depth, self.patch_size) / support.clamp_min(1e-6) + z2 = F.avg_pool2d(depth.square(), self.patch_size) / support.clamp_min(1e-6) + z_std = (z2 - z.square()).clamp_min(0).sqrt() + grid_hw = (height // self.patch_size, width // self.patch_size) + ray = patch_center_rays(K, grid_hw, self.patch_size) + z = z.flatten(2).transpose(1, 2) + inputs = torch.cat((ray[..., :2] * z, z, z.clamp_min(1e-4).log(), + support.flatten(2).transpose(1, 2), + z_std.flatten(2).transpose(1, 2)), dim=-1) + tokens = self.projection(inputs) * (support.flatten(2).transpose(1, 2) > 0).to(inputs.dtype) + return PatchFeatures(tokens, grid_hw, self.patch_size) + + +class ConditionedBimanual(BimanualReconstructionModel): + def forward(self, batch): + if not isinstance(self.decoder, GeometryMoTDecoder): + return super().forward(batch) + rgb = batch["rgb"] + batch_size, time, _, height, width = rgb.shape + frame_valid = batch["frame_valid"].bool() + if "K" in batch: + K = batch["K"].reshape(batch_size * time, 3, 3).float() + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ) & frame_valid + else: + K = torch.eye(3, device=rgb.device)[None].expand(batch_size * time, -1, -1) + K_available = torch.zeros_like(frame_valid) + depth_available = input_availability( + batch, "depth_input_available", "depth_available", torch.zeros_like(frame_valid), + ) & frame_valid + depth = batch.get("depth_m") + valid = batch.get("depth_pixel_valid") + if depth is None or valid is None: + depth = torch.zeros((batch_size, time, 1, height, width), device=rgb.device) + valid = torch.zeros_like(depth, dtype=torch.bool) + depth_available = torch.zeros_like(frame_valid) + self.decoder.camera_context = { + "K": K.reshape(batch_size, time, 3, 3), + "available": K_available, + "grid_hw": (height // self.config.patch_size, width // self.config.patch_size), + "patch_size": self.config.patch_size, + } + self.depth_encoder.input_context = { + "depth": depth.reshape(batch_size * time, 1, height, width).float(), + "valid": valid.reshape(batch_size * time, 1, height, width), + "K": K, + "available": depth_available, + } + try: + return super().forward(batch) + finally: + self.decoder.camera_context = None + self.depth_encoder.input_context = None + + +class GeometryMoTBlock(nn.Module): + def __init__(self, old: MoTSpatialBlock): + super().__init__() + self.heads = old.heads + self.rgb = old.rgb + self.hand = old.hand + self.k = copy.deepcopy(old.rgb) + self.depth = copy.deepcopy(old.rgb) + self.k_gate_logit = nn.Parameter(torch.tensor(-2.0)) + self.depth_gate_logit = nn.Parameter(torch.tensor(-2.0)) + + def forward(self, rgb: torch.Tensor, hand: torch.Tensor, + bearing: torch.Tensor | None, depth: torch.Tensor | None): + if bearing is None and depth is None: + rgb, hand = MoTSpatialBlock.forward(self, rgb, hand) + return rgb, hand, bearing, depth + parts = [("hand", hand, self.hand), ("rgb", rgb, self.rgb)] + if bearing is not None: + parts.append(("bearing", bearing, self.k)) + if depth is not None: + parts.append(("depth", depth, self.depth)) + batch, _, dim = hand.shape + lengths = [tokens.shape[1] for _, tokens, _ in parts] + normalized = [expert.attn_norm(tokens) for _, tokens, expert in parts] + query = torch.cat([expert.q(tokens) for tokens, (_, _, expert) in zip(normalized, parts)], dim=1) + key = torch.cat([expert.k(tokens) for tokens, (_, _, expert) in zip(normalized, parts)], dim=1) + value = torch.cat([expert.v(tokens) for tokens, (_, _, expert) in zip(normalized, parts)], dim=1) + head_dim = dim // self.heads + + def split(tokens: torch.Tensor) -> torch.Tensor: + return tokens.reshape(batch, -1, self.heads, head_dim).transpose(1, 2) + + bias = [query.new_zeros(lengths[0] + lengths[1])] + if bearing is not None: + bias.append(F.logsigmoid(self.k_gate_logit).to(query.dtype).expand(bearing.shape[1])) + if depth is not None: + bias.append(F.logsigmoid(self.depth_gate_logit).to(query.dtype).expand(depth.shape[1])) + key_bias = torch.cat(bias)[None, None, None, :] + attended = F.scaled_dot_product_attention(split(query), split(key), split(value), attn_mask=key_bias) + attended = attended.transpose(1, 2).reshape(batch, -1, dim) + outputs = [expert.finish(tokens, delta) for (_, tokens, expert), delta in + zip(parts, attended.split(lengths, dim=1))] + return outputs[1], outputs[0], (outputs[2] if bearing is not None else None), (outputs[-1] if depth is not None else None) + + +class GeometryMoTDecoder(nn.Module): + def __init__(self, old): + super().__init__() + self.spatial = nn.ModuleList(GeometryMoTBlock(layer) for layer in old.spatial) + self.temporal = old.temporal + self.bearing_encoder = BearingEncoder(old.spatial[0].rgb.q.out_features) + self.gradient_checkpointing = old.gradient_checkpointing + self.camera_context = None + + def forward(self, queries, rgb, depth, frame_valid, depth_available, side_bias): + if self.camera_context is None: + raise RuntimeError("geometry decoder requires the current camera context") + camera_K = self.camera_context["K"] + camera_available = self.camera_context["available"] + camera_grid_hw = self.camera_context["grid_hw"] + camera_patch_size = self.camera_context["patch_size"] + batch, time, hands, dim = queries.shape + flat_rgb = rgb.reshape(batch * time, rgb.shape[2], dim) + hand = queries.reshape(batch * time, hands, dim) + k_available = (camera_available & frame_valid).reshape(-1) + d_available = (depth_available & camera_available & frame_valid).reshape(-1) + if bool((depth_available & ~camera_available).any()): + raise ValueError("metric depth requires aligned camera calibration") + if not bool(k_available.any()): + for spatial, temporal in zip(self.spatial, self.temporal): + flat_rgb, hand = MoTSpatialBlock.forward(spatial, flat_rgb, hand) + hand = hand.reshape(batch, time, hands, dim) + hand = hand * frame_valid[:, :, None, None].to(hand.dtype) + hand, _ = temporal(hand, frame_valid) + hand = hand.reshape(batch * time, hands, dim) + return hand.reshape(batch, time, hands, dim), {} + bearing = (self.bearing_encoder(camera_K.reshape(-1, 3, 3), camera_grid_hw, + camera_patch_size)) + depth_flat = None + if bool(d_available.any()): + if depth is None: + raise ValueError("available depth has no encoded tokens") + rows, cols = camera_grid_hw + grid = depth.reshape(batch * time, rows, cols, dim).permute(0, 3, 1, 2) + pooled = F.avg_pool2d(grid, 2, ceil_mode=True) + depth_flat = pooled.flatten(2).transpose(1, 2) + modes = k_available.to(torch.long) + 2 * d_available.to(torch.long) + for spatial, temporal in zip(self.spatial, self.temporal): + next_rgb, next_hand = flat_rgb.clone(), hand.clone() + next_bearing = None if bearing is None else bearing.clone() + next_depth = None if depth_flat is None else depth_flat.clone() + for mode in (0, 1, 3): + indices = torch.nonzero(modes == mode, as_tuple=True)[0] + if indices.numel() == 0: + continue + rgb_part, hand_part, k_part, depth_part = spatial( + flat_rgb.index_select(0, indices), hand.index_select(0, indices), + bearing.index_select(0, indices) if mode & 1 else None, + depth_flat.index_select(0, indices) if mode & 2 else None, + ) + next_rgb.index_copy_(0, indices, rgb_part) + next_hand.index_copy_(0, indices, hand_part) + if k_part is not None: + next_bearing.index_copy_(0, indices, k_part) + if depth_part is not None: + next_depth.index_copy_(0, indices, depth_part) + flat_rgb, hand, bearing, depth_flat = next_rgb, next_hand, next_bearing, next_depth + hand = hand.reshape(batch, time, hands, dim) + hand = hand * frame_valid[:, :, None, None].to(hand.dtype) + hand, _ = temporal(hand, frame_valid) + hand = hand.reshape(batch * time, hands, dim) + return hand.reshape(batch, time, hands, dim), {} + + +def extend_rgb_model(model): + for parameter in model.parameters(): + parameter.requires_grad_(False) + model.decoder = GeometryMoTDecoder(model.decoder) + model.depth_encoder = CompactMetricDepthEncoder(model.config.decoder_dim, model.config.patch_size) + model.config.use_depth = True + model.config.depth_mode = "geometry" + return model + + +def build_model(mean_local, rgb_state: dict): + config = ModelConfig( + encoder="vitpose_l", decoder_dim=512, decoder_layers=3, + attention_heads=8, decoder_mode="alternating", + temporal_attention_mode="bidirectional", use_depth=False, use_rays=False, + predict_presence=False, structured_hand_refinement=False, + translation_parameterization="direct_xyz", + joint2d_parameterization="hand_token_linear", mano_root=MANO_ROOT, + require_mano=True, mano_fix_left_shapedirs=True, gradient_checkpointing=True, + ) + model = ConditionedBimanual(config, rgb_encoder=TrainableViTPoseEncoder()) + model.decoder = UnifiedRGBDecoder(model.decoder, config.attention_heads) + model.rotation_head = MeanDeltaRotationHead(model.rotation_head, mean_local) + model.mano_layer.requires_grad_(False) + model.joint2d_head.requires_grad_(False) + model.load_state_dict(rgb_state, strict=True) + return extend_rgb_model(model) + + +def set_train_stage(model, stage: str): + if stage not in ("k", "depth"): + raise ValueError(stage) + for parameter in model.parameters(): + parameter.requires_grad_(False) + for block in model.decoder.spatial: + expert = block.k if stage == "k" else block.depth + expert.requires_grad_(True) + (block.k_gate_logit if stage == "k" else block.depth_gate_logit).requires_grad_(True) + terminal = model.decoder.spatial[-1].k if stage == "k" else model.decoder.spatial[-1].depth + for module in (terminal.q, terminal.o, terminal.ffn_norm, + terminal.ffn_in, terminal.ffn_out): + module.requires_grad_(False) + encoder = model.decoder.bearing_encoder if stage == "k" else model.depth_encoder + encoder.requires_grad_(True) + return [parameter for parameter in model.parameters() if parameter.requires_grad] diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/__init__.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22d8dd8b2b6b1322e408c586055c7249add4e539 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/__init__.py @@ -0,0 +1,11 @@ +"""Teacher-free ViTPose-L RGB MoT training using this EgoNet source tree.""" + +from pathlib import Path +import sys + +_SOURCE = Path(__file__).resolve().parents[2] / "src" +sys.path.insert(0, str(_SOURCE)) +import foundation_hand # noqa: E402 + +if not Path(foundation_hand.__file__).resolve().is_relative_to(_SOURCE): + raise RuntimeError("ViTPose-L training must use this EgoNet foundation_hand source") diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/audit_resolution.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/audit_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c940207a8da5d66ff485acc51485859017483c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/audit_resolution.py @@ -0,0 +1,85 @@ +"""Check official HOT3D rectified image size and hand size under each target canvas.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from foundation_hand.data.hot3d_dataset import quest_linear_camera_calibration +from .data import MixedResolutionCoverage, MixedResolutionDataset, RESOLUTIONS + + +def hand_extents(sample): + coordinates = sample["joint2d"].float() + valid = sample["joint2d_valid"].bool() & torch.isfinite(coordinates).all(-1) + extents = [] + for frame in range(coordinates.shape[0]): + for side in range(2): + points = coordinates[frame, side][valid[frame, side]] + if len(points) < 5: + continue + size = points.max(dim=0).values - points.min(dim=0).values + extents.append((float(size[0]), float(size[1]))) + return {"valid_hand_frames": len(extents), + "median_bbox_width_px": float(torch.tensor([value[0] for value in extents]).median()) if extents else None, + "median_bbox_height_px": float(torch.tensor([value[1] for value in extents]).median()) if extents else None} + + +def source_image_size(native, row): + provider = native._provider(str(row["recording_id"])) + stream_id = native._api["StreamId"](str(row["stream_id"])) + timestamp = int(row["timestamps_ns"][0]) + device = provider.device_data_provider + if row["headset"] == "Aria": + _, calibration = device.get_online_camera_calibration( + stream_id, timestamp, camera_model=native._api["LINEAR"]) + else: + _, calibration = quest_linear_camera_calibration( + device, stream_id, native._api["LINEAR"], native._api["FISHEYE624"]) + image = device.get_undistorted_image(timestamp, stream_id) + return {"calibration_hw": list(map(int, calibration.get_image_size()[::-1])), + "undistorted_image_hw": list(map(int, image.shape[:2]))} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + coverage, dataset = MixedResolutionCoverage(), MixedResolutionDataset() + found = {} + for position in range(3000): + spec = coverage.sample(position) + if spec["source"] != "HOT3D": + continue + row = dataset.sources["HOT3D"].rows[dataset.sources["HOT3D"].by_tile[spec["tile_id"]]] + headset = row["headset"] + if headset not in found: + found[headset] = (spec, row) + if set(found) == {"Aria", "Quest3"}: + break + if set(found) != {"Aria", "Quest3"}: + raise RuntimeError("coverage audit did not sample both HOT3D headset types") + report = {} + for headset, (spec, row) in found.items(): + entries = [] + for hw in RESOLUTIONS: + sample = dataset[dict(spec, target_hw=hw)] + native = dataset._reader("HOT3D", hw).native + source = source_image_size(native, row) + if source["calibration_hw"] != source["undistorted_image_hw"]: + raise RuntimeError(f"{headset} calibration/image dimensions differ") + entries.append({"target_hw": hw, **source, **hand_extents(sample)}) + report[headset] = {"recording": row["recording_id"], "stream_id": row["stream_id"], + "tile": spec["tile_id"], "resolutions": entries} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps(report, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7da9063474dbdab3c917b80edbdb40b16b3d4227 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/config.json @@ -0,0 +1,24 @@ +{ + "experiment": "vitpose_l_mot_rgb_from_scratch_io_v3_20261007", + "status": "io_only_speed_protocol_v1", + "visual_sha256": "82dea141d75805068ce80705b9a3965af9cbc62a1844c46d88238012a2c2097f", + "initialization": "ViTPose-L visual-only; all other weights random; no teacher or old MANO checkpoint", + "source_quota_per_update": {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}, + "global_batch": 60, + "io": {"hot3d_provider": "hand_only", "prefetch_factor": 4}, + "frames": 8, + "resolutions_hw": [[512, 896], [368, 640], [512, 512]], + "resolution_pct_by_source": { + "H2O": [75, 20, 5], "ARCTIC": [70, 20, 10], + "HOT3D_Aria": [30, 15, 55], "HOT3D_Quest3": [60, 20, 20] + }, + "optimizer": {"name": "AdamW", "new_lr_peak": 0.00005, "visual_last2_lr_peak": 0.000001, + "weight_decay": 0.05, "clip_grad_norm": 100, "freeze_visual_updates": 5000, + "warmup_updates": 1000, "visual_warmup_updates": 1000, + "minimum_lr_ratio": 0.1, "initial_endpoint_updates": 120000}, + "evaluation_updates": [5000, 10000, 20000, 40000, 60000, 80000, 100000, 120000], + "loss_source": "experiments/from_scratch_mean_pose/config.json shared.loss", + "statistics_source": "experiments/from_scratch_mean_pose/statistics_mano_pkl_v2.json", + "prohibit_teacher": true, + "prohibit_old_model_checkpoint": true +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..c3abd343265950d4754e221cbedfb6cd6752c66b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/controller.py @@ -0,0 +1,195 @@ +"""Wait for six idle G1 GPUs, then run staged training and native-GT evaluation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +from .train import CONFIG + + +ROOT = Path(__file__).resolve().parents[2] +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +TORCHRUN = "/SSD2/jiasen/envs/foundation_hand/bin/torchrun" +SOURCES = ("H2O", "ARCTIC", "HOT3D") +HK = ROOT / "docs/HK.md" + + +def gpu_idle(indices, max_memory_mib=200, max_utilization_pct=5): + result = subprocess.run(["nvidia-smi", "--query-gpu=index,memory.used,utilization.gpu", + "--format=csv,noheader,nounits"], text=True, capture_output=True, check=True) + usage = {} + for line in result.stdout.splitlines(): + gpu, memory, utilization = (int(value.strip()) for value in line.split(",")) + usage[gpu] = {"memory_mib": memory, "utilization_pct": utilization} + return all(index in usage and usage[index]["memory_mib"] <= max_memory_mib + and usage[index]["utilization_pct"] <= max_utilization_pct for index in indices), usage + + +def write_status(path, **fields): + value = {"time_hkt": datetime.now().astimezone().isoformat(), **fields} + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") + os.replace(temporary, path) + + +def wait_for_idle(indices, status, stage, samples=3, interval=30): + streak = 0 + while streak < samples: + try: + free, usage = gpu_idle(indices) + except (OSError, subprocess.SubprocessError, ValueError) as error: + free, usage = False, {"error": str(error)} + streak = streak + 1 if free else 0 + write_status(status, state="waiting_for_idle_gpus", stage=stage, + idle_streak=streak, required_streak=samples, usage=usage) + if streak < samples: + time.sleep(interval) + + +def run_logged(command, log_path, env, status, state, stage): + write_status(status, state=state, stage=stage, command=command, log=str(log_path)) + with log_path.open("a", buffering=1) as log: + log.write(json.dumps({"event": "start", "time_hkt": datetime.now().astimezone().isoformat(), + "command": command}) + "\n") + result = subprocess.run(command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT) + log.write(json.dumps({"event": "exit", "time_hkt": datetime.now().astimezone().isoformat(), + "returncode": result.returncode}) + "\n") + if result.returncode: + write_status(status, state="failed_needs_review", stage=stage, + returncode=result.returncode, log=str(log_path)) + raise RuntimeError(f"{stage} failed with code {result.returncode}: {log_path}") + + +def record_evaluation(update, output): + reports = {source: json.loads((output / "evaluations" / + f"update_{update:07d}_{source.lower()}.json").read_text()) + for source in SOURCES} + lines = [f"\n## {datetime.now().astimezone():%Y-%m-%d %H:%M} HKT: ViTPose-L + MoT {update:,} 更新评估\n", + "\n训练为视觉主干预训练 + 其它部分从头,纯 RGB、T=8、三源 21/15/24;下表为固定 held-out source-native GT,未使用 teacher 或 parent checkpoint。\n", + "\n| Source / group | Abs MPJPE mm | Root MPJPE mm | MPVPE mm | 2D px | local pose deg | bend bias deg | pred/GT 6D var |\n", + "|---|---:|---:|---:|---:|---:|---:|---:|\n"] + names = ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", "local_pose_angle_deg", "bend_bias_deg") + for source in SOURCES: + report = reports[source] + for group in ("all", "hard_pose"): + values = [report[group]["metrics"][name]["mean"] for name in names] + cells = [f"{value:.3f}" if value is not None else "n/a" for value in values] + ratio = report[group]["pred_gt_local_6d_variance_ratio_macro"] + cells.append(f"{ratio:.3f}" if ratio is not None else "n/a") + lines.append(f"| {source} / {group} | " + " | ".join(cells) + " |\n") + lines.append("\n完整报告与逐手记录见本实验 `evaluations/`;单节点结果不等于收敛结论,继续看后续节点的四指标、hard pose 与 normal no-harm。\n") + with HK.open("a") as document: + document.writelines(lines) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--idle-samples", type=int, default=3) + parser.add_argument("--idle-interval", type=int, default=30) + parser.add_argument("--workers", type=int, default=2) + args = parser.parse_args() + if args.idle_samples < 2 or args.idle_interval < 10 or args.workers < 1: + raise ValueError("idle gate must cover multiple samples and at least 10-second intervals") + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + (output / "evaluations").mkdir(exist_ok=True) + status = output / "controller_status.json" + smoke_output = output.parent / "smoke_io_v3" + smoke_checkpoint = smoke_output / "update_0000002.pt" + resolution_audit = output.parent / "hot3d_resolution_audit.json" + if not resolution_audit.is_file(): + raise RuntimeError("HOT3D resolution audit is missing") + endpoints = CONFIG["evaluation_updates"] + if endpoints != [5000, 10000, 20000, 40000, 60000, 80000, 100000, 120000]: + raise RuntimeError("evaluation cadence changed") + env = os.environ.copy() + env["CUDA_VISIBLE_DEVICES"] = "0,1,2,3,4,5" + env["OMP_NUM_THREADS"] = "1" + env["OPENBLAS_NUM_THREADS"] = "1" + env["MKL_NUM_THREADS"] = "1" + for endpoint in (1, 2): + checkpoint = smoke_output / f"update_{endpoint:07d}.pt" + if checkpoint.is_file(): + continue + previous = smoke_output / "update_0000001.pt" if endpoint == 2 else None + if previous is not None and not previous.is_file(): + raise RuntimeError("post-fix smoke step-1 checkpoint missing") + wait_for_idle(range(6), status, f"postfix_smoke_{endpoint}", + samples=args.idle_samples, interval=args.idle_interval) + smoke_env = env.copy() + smoke_env["CUDA_VISIBLE_DEVICES"] = "0,1,2,3,4,5" + command = [TORCHRUN, "--standalone", "--nnodes=1", "--nproc_per_node=6", + "-m", "experiments.vitpose_mot_io_v3.train", "--output", str(smoke_output), + "--updates", str(endpoint), "--smoke", "--workers", str(args.workers), "--log-every", "1"] + if previous: + command += ["--resume", str(previous)] + run_logged(command, output / f"postfix_smoke_{endpoint}.log", smoke_env, + status, "preflight_training", endpoint) + if not checkpoint.is_file(): + raise RuntimeError(f"post-fix smoke returned without checkpoint {checkpoint}") + for source in SOURCES: + report = output / "evaluations" / f"preflight_smoke_{source.lower()}.json" + if report.is_file(): + continue + wait_for_idle((0,), status, f"preflight_eval_{source}", samples=2, interval=15) + smoke_env = env.copy() + smoke_env["CUDA_VISIBLE_DEVICES"] = "0" + run_logged([PYTHON, "-m", "experiments.vitpose_mot_io_v3.evaluate", + "--checkpoint", str(smoke_checkpoint), "--source", source, + "--output", str(report), "--limit", "2", "--smoke"], + output / f"preflight_eval_{source.lower()}.log", smoke_env, + status, "preflight_evaluation", source) + for endpoint in endpoints: + checkpoint = output / f"update_{endpoint:07d}.pt" + previous = output / f"update_{endpoints[endpoints.index(endpoint) - 1]:07d}.pt" if endpoint != endpoints[0] else None + if not checkpoint.is_file(): + if previous is not None and not previous.is_file(): + raise RuntimeError(f"missing previous full checkpoint: {previous}") + wait_for_idle(range(6), status, f"train_to_{endpoint}", + samples=args.idle_samples, interval=args.idle_interval) + command = [TORCHRUN, "--standalone", "--nnodes=1", "--nproc_per_node=6", + "-m", "experiments.vitpose_mot_io_v3.train", "--output", str(output), + "--updates", str(endpoint), "--workers", str(args.workers), "--log-every", "25"] + if previous: + command += ["--resume", str(previous)] + run_logged(command, output / f"train_to_{endpoint:07d}.log", env, status, + "training", endpoint) + if not checkpoint.is_file(): + raise RuntimeError(f"training returned without checkpoint {checkpoint}") + for source in SOURCES: + report = output / "evaluations" / f"update_{endpoint:07d}_{source.lower()}.json" + if report.is_file(): + continue + wait_for_idle((0,), status, f"eval_{endpoint}_{source}", samples=2, interval=15) + eval_env = env.copy() + eval_env["CUDA_VISIBLE_DEVICES"] = "0" + run_logged([PYTHON, "-m", "experiments.vitpose_mot_io_v3.evaluate", + "--checkpoint", str(checkpoint), "--source", source, + "--output", str(report)], + output / f"eval_{endpoint:07d}_{source.lower()}.log", eval_env, + status, "evaluating", f"{endpoint}_{source}") + marker = output / "evaluations" / f"update_{endpoint:07d}_hk_recorded.json" + if not marker.exists(): + record_evaluation(endpoint, output) + marker.write_text(json.dumps({"update": endpoint, + "recorded_at": datetime.now().astimezone().isoformat()}) + "\n") + write_status(status, state="evaluated", stage=endpoint, + checkpoint=str(checkpoint), next_endpoint=next((value for value in endpoints if value > endpoint), None)) + write_status(status, state="complete_120k_waiting_for_curve_review", stage=120000) + + +if __name__ == "__main__": + try: + main() + except Exception as error: + print(f"controller failed: {error}", file=sys.stderr, flush=True) + raise diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/data.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/data.py new file mode 100644 index 0000000000000000000000000000000000000000..6b4905464192926ce378fc5f5a86883d8c846d52 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/data.py @@ -0,0 +1,99 @@ +"""Canonical train-only RGB clips with deterministic source-specific resolutions.""" + +from __future__ import annotations + +import hashlib +from types import MethodType + +import torch + +from experiments.from_scratch_mean_pose.smoke import U0Coverage, U0Dataset, a7, base +from experiments.a7_rotation_fix.filtered_dataset import intersect_filtered_valid +from .hot3d_hand_only import hand_only_provider + + +RESOLUTIONS = ((512, 896), (368, 640), (512, 512)) +RESOLUTION_PCT = { + "H2O": (75, 20, 5), + "ARCTIC": (70, 20, 10), + "HOT3D_Aria": (30, 15, 55), + "HOT3D_Quest3": (60, 20, 20), +} + + +def mask_invalid_joint3d(sample: dict) -> None: + sample["joint3d_valid"] &= torch.isfinite(sample["joint3d_camera"]).all(dim=-1) + + +def resolution_for(source: str, headset: str | None, position: int) -> tuple[int, int]: + name = f"{source}_{headset}" if source == "HOT3D" else source + weights = RESOLUTION_PCT[name] + digest = hashlib.blake2b(f"20261006:{position}:{name}".encode(), digest_size=8).digest() + draw = int.from_bytes(digest, "big") % 100 + return RESOLUTIONS[0 if draw < weights[0] else 1 if draw < weights[0] + weights[1] else 2] + + +class MixedResolutionCoverage(U0Coverage): + def __init__(self): + super().__init__() + self.seed = 20261003 + + def sample(self, position): + spec = super().sample(position) + if spec["source"] == "HOT3D": + # The immutable filtered manifest resolves headset by tile ID. + spec["target_hw"] = None + else: + spec["target_hw"] = resolution_for(spec["source"], None, position) + return spec + + +class MixedResolutionDataset(U0Dataset): + def __init__(self): + super().__init__() + self.alternates = {} + native = self.sources["HOT3D"].native + native._provider = MethodType(hand_only_provider, native) + + def _reader(self, source, target_hw): + if target_hw == (512, 896): + return self.sources[source] + key = (source, target_hw) + if key not in self.alternates: + self.alternates[key] = base.FilteredClipDataset( + source, + base.MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl", + 8, target_hw, base.ASSETS["mano_root"], + a7.reference.BASE_CODE / "third_party", + {"enabled": source != "HOT3D", "probability": .8}, + ) + if source == "HOT3D": + native = self.alternates[key].native + native._provider = MethodType(hand_only_provider, native) + return self.alternates[key] + + def __getitem__(self, spec): + source = spec["source"] + anchor = self.sources[source] + row = anchor.rows[anchor.by_tile[spec["tile_id"]]] + target_hw = spec["target_hw"] + if target_hw is None: + target_hw = resolution_for(source, row["headset"], spec["position"]) + original = self._reader(source, target_hw) + sample = original[spec] + if sample["input_mode"] != "rgb": + raise RuntimeError("ViTPose-L experiment requires RGB-only input") + native_joints = sample["joint3d_camera"].clone() + native_valid = sample["joint3d_valid"].clone() + row = original.rows[original.by_tile[spec["tile_id"]]] + sample = self.labels[source].apply(sample, row, original.native) + intersect_filtered_valid(sample, row) + mask_invalid_joint3d(sample) + quality = sample["vertices_valid"].bool() + sample["global_orientation_valid"] &= quality + sample["local_pose_valid"] &= quality + sample["source_native_joint3d_camera"] = native_joints + sample["source_native_joint3d_valid"] = native_valid + if tuple(sample["rgb"].shape[-2:]) != target_hw: + raise RuntimeError(f"source reader returned wrong target shape for {source}") + return sample diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/evaluate.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..d31e5a33273ea1d897b0b64e864ae7040957d00f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/evaluate.py @@ -0,0 +1,178 @@ +"""Frozen source-native development benchmark and hard-pose diagnostics.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + +import numpy as np +import torch + +from experiments.from_scratch_mean_pose.smoke import a7, base, sha + +from clean_eval import apply_mode, dataset_for +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from scripts.evaluate_phase7_external import make_row +from targets import NativePanel + +from .model import build_model +from .train import CONFIG, STATS, verify_contract + + +FOUR = ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px") + + +def finite(value): + if isinstance(value, dict): + return {key: finite(item) for key, item in value.items()} + if isinstance(value, list): + return [finite(item) for item in value] + return None if isinstance(value, float) and not math.isfinite(value) else value + + +def finger_angles(joints): + fingers = joints[..., 1:, :].reshape(*joints.shape[:-2], 5, 4, 3) + bones = fingers[..., 1:, :] - fingers[..., :-1, :] + lengths = torch.linalg.vector_norm(bones, dim=-1) + unit = bones / lengths.clamp_min(1e-8)[..., None] + angles = torch.rad2deg(torch.acos((unit[..., :-1, :] * unit[..., 1:, :]).sum(-1).clamp(-1, 1))) + complete = (lengths > 1e-6).all(dim=(-1, -2)) & torch.isfinite(angles).all(dim=(-1, -2)) + return angles, complete + + +def summarize(rows): + result = {} + for key in (*FOUR, "local_pose_angle_deg", "fingertip_root_relative_mm", + "bend_bias_deg", "gt60_bend_bias_deg"): + values = [row[key] for row in rows if row.get(key) is not None and math.isfinite(row[key])] + result[key] = {"mean": float(np.mean(values)) if values else None, "count": len(values)} + complete = [row for row in rows if "gt_local_6d" in row] + if len(complete) > 1: + gt = np.asarray([row["gt_local_6d"] for row in complete], dtype=np.float64) + pred = np.asarray([row["pred_local_6d"] for row in complete], dtype=np.float64) + gt_variance = gt.var(axis=0) + pred_variance = pred.var(axis=0) + eligible = gt_variance > 1e-8 + ratio = pred_variance[eligible] / gt_variance[eligible] + variance_ratio = float(ratio.mean()) if ratio.size else None + per_joint = np.asarray([row["local_pose_per_joint_deg"] for row in complete], dtype=np.float64).mean(axis=0).tolist() + else: + variance_ratio, per_joint = None, None + return {"hands": len(rows), "metrics": result, + "pred_gt_local_6d_variance_ratio_macro": variance_ratio, + "local_pose_per_joint_mean_deg": per_joint} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--limit", type=int) + parser.add_argument("--smoke", action="store_true") + args = parser.parse_args() + if args.output.exists() or args.output.with_suffix(".rows.json").exists(): + raise FileExistsError(args.output) + if args.limit is not None and args.limit < 1: + raise ValueError("positive limit required") + if (args.limit is not None or "smoke" in str(args.checkpoint)) and not args.smoke: + raise RuntimeError("subset or smoke checkpoint requires explicit --smoke") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] is not None or state["smoke"] != args.smoke): + raise RuntimeError("evaluation checkpoint composition invalid") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + model.load_state_dict(state["model"], strict=True) + model.to("cuda").eval() + panel_root = a7.BASE_ROOT / "eval/frozen_panels_sync_v2" + registry = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_development_t8.jsonl" + registered = registry["sources"][args.source]["development"] + if sha(manifest) != registered["manifest_sha256"] or registry["sources"][args.source]["train_overlap"]: + raise RuntimeError("development panel overlaps training or hash changed") + manifest_rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), + hand_valid_policy="visible_mesh") if args.source == "ARCTIC" + else dataset_for(args.source, manifest)) + dataset = NativePanel(args.source, native, manifest_rows) + limit = min(args.limit, len(dataset)) if args.limit else len(dataset) + rows = [] + with torch.inference_mode(): + for index in range(limit): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, "rgb") + batch = base.move_to_device(batch, torch.device("cuda")) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + if not bool(torch.isfinite(prediction["joints_camera"]).all()): + raise RuntimeError(f"nonfinite development prediction at clip {index}") + pose_valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + joint_valid = batch["joint3d_root_relative_valid"].bool().all(dim=-1) + gt_angles, complete_geometry = finger_angles(batch["joint3d_camera"].float()) + pred_angles, _ = finger_angles(prediction["joints_camera"].float()) + complete = pose_valid & joint_valid & complete_geometry + gt_hard = ((gt_angles >= 45).sum(dim=(-1, -2)) >= 2) | (gt_angles >= 60).any(dim=(-1, -2)) + target_rotation = axis_angle_to_matrix(torch.nan_to_num(batch["mano_pose"].float()).reshape( + *pose_valid.shape, 16, 3)) + relative = prediction["mano_rotation_matrices"].float() @ target_rotation.transpose(-1, -2) + trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1) + angle_error = torch.rad2deg(torch.acos(((trace - 1) / 2).clamp(-1, 1))) + predicted_rel = prediction["joints_camera"].float() - prediction["joints_camera"].float()[..., :1, :] + target_rel = batch["joint3d_camera"].float() - batch["joint3d_camera"].float()[..., :1, :] + tip_error = torch.linalg.vector_norm(predicted_rel[..., [4, 8, 12, 16, 20], :] + - target_rel[..., [4, 8, 12, 16, 20], :], dim=-1).mean(-1) * 1000 + for frame in range(batch["frame_valid"].shape[1]): + if not bool(batch["frame_valid"][0, frame]): + continue + for side in range(2): + row = make_row(prediction, batch, 0, frame, side) + if bool(complete[0, frame, side]): + gt = gt_angles[0, frame, side] + difference = pred_angles[0, frame, side] - gt + high = gt >= 60 + row.update({ + "gt_hard": bool(gt_hard[0, frame, side]), + "local_pose_angle_deg": float(angle_error[0, frame, side, 1:].mean()), + "fingertip_root_relative_mm": float(tip_error[0, frame, side]), + "bend_bias_deg": float(difference.mean()), + "gt60_bend_bias_deg": float(difference[high].mean()) if bool(high.any()) else None, + "local_pose_per_joint_deg": angle_error[0, frame, side, 1:].tolist(), + "gt_local_6d": target_rotation[0, frame, side, 1:, :2, :].reshape(15, 6).tolist(), + "pred_local_6d": prediction["mano_rotation_matrices"][0, frame, side, 1:, :2, :].float().reshape(15, 6).tolist(), + }) + else: + row.update({"gt_hard": None, "local_pose_angle_deg": None, + "fingertip_root_relative_mm": None, + "bend_bias_deg": None, "gt60_bend_bias_deg": None}) + rows.append(row) + if (index + 1) % 32 == 0: + print(json.dumps({"source": args.source, "done": index + 1, "total": limit}), flush=True) + complete_rows = [row for row in rows if row["gt_hard"] is not None] + report = {"experiment": CONFIG["experiment"], "source": args.source, + "role": "development_subset_smoke" if args.limit else "development_full", + "input_mode": "rgb", "frames": 8, "source_native_gt": True, + "training_update": state["update"], "checkpoint_sha256": sha(args.checkpoint), + "panel_sha256": sha(manifest), "clips": limit, + "hard_definition": "GT >=2 distal angles >=45deg or >=1 >=60deg, complete joints and MANO pose", + "all": summarize(rows), "pose_complete": summarize(complete_rows), + "normal_pose": summarize([row for row in complete_rows if not row["gt_hard"]]), + "hard_pose": summarize([row for row in complete_rows if row["gt_hard"]])} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + args.output.with_suffix(".rows.json").write_text(json.dumps(finite(rows), allow_nan=False) + "\n") + print(json.dumps({"source": args.source, "update": state["update"], + "all": report["all"], "hard_pose": report["hard_pose"]}, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/hot3d_hand_only.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/hot3d_hand_only.py new file mode 100644 index 0000000000000000000000000000000000000000..251fba2cbbab425ccd728d062f9ef36d48dbb4f6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/hot3d_hand_only.py @@ -0,0 +1,47 @@ +"""Load only the official HOT3D streams used by RGB hand training.""" + +from __future__ import annotations + +import json +from pathlib import Path +from types import SimpleNamespace + +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def hand_only_provider(self: HOT3DClipDataset, recording: str): + self._initialize_runtime() + if recording in self._providers: + provider = self._providers.pop(recording) + self._providers[recording] = provider + return provider + + from data_loaders.AriaDataProvider import AriaDataProvider + from data_loaders.HeadsetPose3dProvider import load_headset_pose_provider_from_csv + from data_loaders.ManoHandDataProvider import MANOHandDataProvider + from data_loaders.PathProvider import Hot3dDataPathProvider + from data_loaders.QuestDataProvider import QuestDataProvider + + paths = Hot3dDataPathProvider.fromRecordingFolder( + recording_instance_folderpath=str(self.root / recording) + ) + if not paths.is_valid(): + raise RuntimeError(f"invalid official HOT3D recording {recording}") + headset = json.loads(Path(paths.scene_metadata_filepath).read_text())["headset"] + if headset == "Aria": + device = AriaDataProvider(paths.vrs_filepath, paths.mps_folderpath) + elif headset == "Quest3": + device = QuestDataProvider(paths.vrs_filepath, paths.camera_models_filepath) + else: + raise RuntimeError(f"unsupported headset {headset}") + provider = SimpleNamespace( + device_data_provider=device, + device_pose_data_provider=load_headset_pose_provider_from_csv(paths.headset_trajectory_filepath), + mano_hand_data_provider=MANOHandDataProvider( + paths.mano_hand_pose_trajectory_filepath, self._source_mano + ), + ) + self._providers[recording] = provider + while len(self._providers) > self.provider_cache_size: + self._providers.popitem(last=False) + return provider diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/model.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/model.py new file mode 100644 index 0000000000000000000000000000000000000000..8abac2d5f44683a895b752727fe8ebdac9ae617e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/model.py @@ -0,0 +1,96 @@ +"""Full-frame ViTPose-L backbone and freshly initialized MANO MoT.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +import torch +from torch import nn +from torch.utils.checkpoint import checkpoint + +from foundation_hand.models.bimanual import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.encoders import PatchFeatures +from experiments.dinov3_2d_pretrain.vitpose_probe import ViTPoseBackbone +from experiments.from_scratch_mean_pose.model import MeanDeltaRotationHead +from experiments.u0_depthsafe.model import UnifiedRGBDecoder + + +VISUAL_WEIGHTS = Path("/data-hdd/jiasen_rescue_20260815/wuyifan/artifacts/gkdt_feature_probe_20261006/vitpose_large_visual.pt") +VISUAL_SHA256 = "82dea141d75805068ce80705b9a3965af9cbc62a1844c46d88238012a2c2097f" +MANO_ROOT = "/SSD3/jiasen/foundation_hand/pretrained/mano" + + +def verify_visual_weights(path: Path = VISUAL_WEIGHTS) -> None: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + if digest.hexdigest() != VISUAL_SHA256: + raise RuntimeError("ViTPose-L visual checkpoint SHA-256 mismatch") + + +class TrainableViTPoseEncoder(nn.Module): + def __init__(self, weights: Path = VISUAL_WEIGHTS, output_dim: int = 512) -> None: + super().__init__() + verify_visual_weights(weights) + state = torch.load(weights, map_location="cpu", weights_only=True) + if state["pos_embed"].shape != (1, 193, 1024): + raise RuntimeError("unexpected ViTPose-L positional embedding") + if {int(key.split(".")[1]) for key in state if key.startswith("layers.")} != set(range(24)): + raise RuntimeError("ViTPose-L checkpoint is missing transformer blocks") + self.backbone = ViTPoseBackbone(1024, 24, 16) + self.backbone.load_state_dict(state, strict=True) + self.backbone.requires_grad_(False) + self.projection = nn.Linear(1024, output_dim) + self.trainable_last_blocks = 0 + + def unfreeze_last_two(self) -> None: + self.backbone.requires_grad_(False) + for layer in self.backbone.layers[-2:]: + layer.requires_grad_(True) + self.backbone.ln1.requires_grad_(True) + self.trainable_last_blocks = 2 + + def train(self, mode: bool = True): + super().train(mode) + if not self.trainable_last_blocks: + self.backbone.eval() + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + backbone = self.backbone + patches = backbone.patch_embed.projection(images) + rows, cols = patches.shape[-2:] + x = patches.flatten(2).transpose(1, 2) + position = torch.nn.functional.interpolate( + backbone.pos_embed[:, 1:].reshape(1, 16, 12, -1).permute(0, 3, 1, 2), + size=(rows, cols), mode="bicubic", align_corners=False, + ).flatten(2).transpose(1, 2) + with torch.no_grad(): + x = x + position + backbone.pos_embed[:, :1] + for layer in backbone.layers[:-self.trainable_last_blocks or None]: + x = layer(x) + if self.trainable_last_blocks: + for layer in backbone.layers[-self.trainable_last_blocks:]: + x = checkpoint(layer, x, use_reentrant=False) if self.training else layer(x) + x = backbone.ln1(x) + return PatchFeatures(self.projection(x), (rows, cols), 16) + + +def build_model(mean_local: torch.Tensor, *, weights: Path = VISUAL_WEIGHTS) -> BimanualReconstructionModel: + config = ModelConfig( + encoder="vitpose_l", decoder_dim=512, decoder_layers=3, + attention_heads=8, decoder_mode="alternating", + temporal_attention_mode="bidirectional", use_depth=False, use_rays=False, + predict_presence=False, structured_hand_refinement=False, + translation_parameterization="direct_xyz", + joint2d_parameterization="hand_token_linear", mano_root=MANO_ROOT, + require_mano=True, mano_fix_left_shapedirs=True, gradient_checkpointing=True, + ) + model = BimanualReconstructionModel(config, rgb_encoder=TrainableViTPoseEncoder(weights)) + model.decoder = UnifiedRGBDecoder(model.decoder, config.attention_heads) + model.rotation_head = MeanDeltaRotationHead(model.rotation_head, mean_local) + model.mano_layer.requires_grad_(False) + model.joint2d_head.requires_grad_(False) + return model diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/pilot.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/pilot.py new file mode 100644 index 0000000000000000000000000000000000000000..a757e1323b46e6fe175ed549d84b9f723f7dbe19 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/pilot.py @@ -0,0 +1,231 @@ +"""Real-data DDP throughput pilot; output is not a trained checkpoint.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import json +import os +from pathlib import Path +import statistics +import threading +import time + +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base +from experiments.from_scratch_mean_pose.throughput_probe import ( + PROBE_FIELDS, collate_probe_samples, initialize_worker, monitor_gpus, select_clip, +) +from .data import MixedResolutionCoverage, MixedResolutionDataset +from .model import VISUAL_WEIGHTS, build_model + + +class TimedDataset(MixedResolutionDataset): + def __getitem__(self, spec): + started = time.monotonic() + sample = super().__getitem__(spec) + sample["_pilot_load_seconds"] = time.monotonic() - started + sample["_pilot_worker_threads"] = len(os.listdir("/proc/self/task")) + return sample + + +def single_sample(samples): + sample = samples[0] + return {key: value for key, value in sample.items() + if key in PROBE_FIELDS or key.startswith("_pilot_")} + + +def resolution_batches(samples, maximum): + grouped = defaultdict(list) + for sample in samples: + grouped[tuple(sample["rgb"].shape[-2:])].append(sample) + return [collate_probe_samples(group[offset:offset + maximum]) + for group in grouped.values() for offset in range(0, len(group), maximum)] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--last-two", action="store_true") + parser.add_argument("--no-checkpointing", action="store_true") + parser.add_argument("--no-decoder-checkpointing", action="store_true") + parser.add_argument("--no-encoder-checkpointing", action="store_true") + parser.add_argument("--interop-threads", type=int, default=0) + parser.add_argument("--weights", type=Path, default=VISUAL_WEIGHTS) + parser.add_argument("--workers", type=int, default=2) + parser.add_argument("--prefetch-factor", type=int, default=2) + parser.add_argument("--opencv-threads", type=int, default=1) + parser.add_argument("--pin-memory", action="store_true") + parser.add_argument("--clips-per-rank", type=int, default=10) + parser.add_argument("--microbatch-size", type=int, default=1) + parser.add_argument("--collate-in-worker", action="store_true") + parser.add_argument("--warmup", type=int, default=2) + parser.add_argument("--updates", type=int, default=12) + parser.add_argument("--physical-gpus", type=int, nargs="+", default=None) + parser.add_argument("--reuse-first-batch", action="store_true") + parser.add_argument("--skip-geometry-check", action="store_true") + args = parser.parse_args() + if (args.output.exists() or args.workers < 0 or args.prefetch_factor < 1 or args.clips_per_rank < 1 + or args.microbatch_size < 1 or args.warmup < 1 or args.updates <= args.warmup): + raise ValueError("invalid pilot settings or output exists") + if args.collate_in_worker and args.microbatch_size != 1: + raise ValueError("worker-side collate is only available for single-clip microbatches") + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if world not in (2, 3, 4, 6): + raise RuntimeError("pilot requires two, three, four or six GPUs") + if args.physical_gpus is not None and len(args.physical_gpus) != world: + raise ValueError("physical GPU list must match the DDP world size") + if args.interop_threads: + torch.set_num_interop_threads(args.interop_threads) + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError("pilot requires 18 GiB free per GPU") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + fitted = json.loads((BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"]).read_text()) + torch.manual_seed(20261003) + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32), weights=args.weights) + if args.last_two: + model.rgb_encoder.unfreeze_last_two() + model.to(device).train() + if args.no_checkpointing or args.no_decoder_checkpointing: + model.decoder.gradient_checkpointing = False + if args.no_checkpointing or args.no_encoder_checkpointing: + model.rgb_encoder.eval() + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + trainable = [p for p in model.parameters() if p.requires_grad] + optimizer = torch.optim.AdamW(trainable, lr=5e-5, weight_decay=0.05) + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + sampler = base.PositionSampler(MixedResolutionCoverage(), 0, + args.updates * args.clips_per_rank * world, rank, world) + loader = DataLoader(TimedDataset(), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=args.workers > 0, + collate_fn=collate_probe_samples if args.collate_in_worker else single_sample, + pin_memory=args.pin_memory, + prefetch_factor=args.prefetch_factor if args.workers else None, + worker_init_fn=partial(initialize_worker, opencv_threads=args.opencv_threads)) + iterator = iter(loader) + cached_samples = ([next(iterator) for _ in range(args.clips_per_rank)] + if args.reuse_first_batch else None) + rows = [] + gpu_samples = [] + monitor_stop = threading.Event() + monitor = None + for update in range(args.updates): + if update == args.warmup and rank == 0 and args.physical_gpus is not None: + monitor = threading.Thread( + target=monitor_gpus, + args=(monitor_stop, tuple(args.physical_gpus), gpu_samples), + daemon=True, + ) + monitor.start() + torch.cuda.synchronize(device) + start = time.monotonic() + samples = (cached_samples if cached_samples is not None else + [next(iterator) for _ in range(args.clips_per_rank)]) + data_ready = time.monotonic() + source_load = {} + if args.collate_in_worker: + cpu_batches = samples + else: + cpu_batches = resolution_batches(samples, args.microbatch_size) + for sample in samples: + source = sample["sampling_source_id"] + bucket = source_load.setdefault(source, {"clips": 0, "load_seconds": 0.0}) + bucket["clips"] += 1 + bucket["load_seconds"] += sample["_pilot_load_seconds"] + bucket["max_worker_threads"] = max(bucket.get("max_worker_threads", 0), + sample["_pilot_worker_threads"]) + optimizer.zero_grad(set_to_none=True) + for micro, cpu in enumerate(cpu_batches): + count = len(cpu["input_mode"]) + batch = base.move_to_device(cpu, device) + if not args.skip_geometry_check: + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < len(cpu_batches) else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + losses = [objective(select_clip(prediction, index, count), + select_clip(batch, index, count))[0] + for index in range(count)] + loss = torch.stack(losses).sum() / args.clips_per_rank + if not bool(torch.isfinite(loss)): + raise RuntimeError("nonfinite pilot loss") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(trainable, 100) + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite pilot gradient") + optimizer.step() + torch.cuda.synchronize(device) + rows.append({"update": update + 1, "seconds": time.monotonic() - start, + "data_wait_seconds": data_ready - start, + "source_load": source_load, + "microbatch_sizes": [len(cpu["input_mode"]) for cpu in cpu_batches], + "loss": float(loss.detach()), "preclip_grad_norm": float(norm), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 1024**3}) + if rank == 0: + print(json.dumps({"last_two": args.last_two, + "no_decoder_checkpointing": not model.decoder.gradient_checkpointing, + "no_encoder_checkpointing": not model.rgb_encoder.training, + **rows[-1]}), flush=True) + monitor_stop.set() + if monitor is not None: + monitor.join(timeout=6) + gathered = [None] * world + dist.all_gather_object(gathered, {"rank": rank, "rows": rows}) + if rank == 0: + slowest = max(statistics.mean(row["seconds"] for row in part["rows"][args.warmup:]) + for part in gathered) + report = {"kind": "gpu_pilot_not_formal_training", "last_two": args.last_two, + "reuse_first_batch": args.reuse_first_batch, + "skip_geometry_check": args.skip_geometry_check, + "no_decoder_checkpointing": not model.decoder.gradient_checkpointing, + "no_encoder_checkpointing": not model.rgb_encoder.training, + "interop_threads": args.interop_threads, + "world_size": world, "clips_per_rank": args.clips_per_rank, + "microbatch_size_max": args.microbatch_size, + "collate_in_worker": args.collate_in_worker, + "pin_memory": args.pin_memory, + "opencv_threads": args.opencv_threads, + "workers_per_rank": args.workers, "updates": args.updates, + "prefetch_factor": args.prefetch_factor, + "warmup": args.warmup, + "seconds_per_update_slowest_rank": slowest, + "clips_per_second": args.clips_per_rank * world / slowest, + "ranks": gathered} + if args.physical_gpus is not None: + report["gpu_utilization"] = { + str(gpu): { + "samples": len(values), + "mean_pct": statistics.mean(values) if values else None, + "fraction_at_least_90pct": ( + sum(value >= 90 for value in values) / len(values) if values else None + ), + } + for gpu in args.physical_gpus + for values in [[sample["utilization_pct"] for sample in gpu_samples if sample["gpu"] == gpu]] + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps({"result": str(args.output), "clips_per_second": report["clips_per_second"]}), flush=True) + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/preflight.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..be32263ca0d0150e09b5ef068a20c954997822a1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/preflight.py @@ -0,0 +1,106 @@ +"""Real-data three-resolution and one-update ViTPose-L/MoT checks.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import time + +import torch + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base +from .data import MixedResolutionCoverage, MixedResolutionDataset, RESOLUTIONS +from .model import build_model, verify_visual_weights + + +def reprojection_error(batch): + joints = batch["joint3d_camera"].float() + k = batch["K"].float() + xy = joints[..., :2] / joints[..., 2:].clamp_min(0.05) + projected = torch.einsum("btij,bthkj->bthki", k[..., :2, :2], xy) + k[..., :2, 2][:, :, None, None] + valid = batch["joint2d_valid"].bool() & batch["joint3d_valid"].bool() & (joints[..., 2] > 0.05) + error = torch.linalg.vector_norm(projected - batch["joint2d"].float(), dim=-1) + return {"valid_joints": int(valid.sum()), + "mean_px": float(error[valid].mean()) if bool(valid.any()) else None, + "p95_px": float(torch.quantile(error[valid], 0.95)) if bool(valid.any()) else None} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), default="H2O") + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--last-two", action="store_true") + parser.add_argument("--geometry-only", action="store_true") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + verify_visual_weights() + fitted = json.loads((BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"]).read_text()) + coverage, dataset = MixedResolutionCoverage(), MixedResolutionDataset() + spec = next(coverage.sample(position) for position in range(600) + if coverage.sample(position)["source"] == args.source) + rows = [] + for hw in RESOLUTIONS: + item = dict(spec, target_hw=hw) + cpu = base.collate_h2o_clips([dataset[item]]) + if cpu["input_mode"] != ["rgb"] or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("RGB-only model input violated") + if tuple(cpu["rgb"].shape) != (1, 8, 3, *hw): + raise RuntimeError("mixed-resolution sample shape violated") + rows.append({"target_hw": hw, "image_hw": cpu["image_hw"].tolist(), + "K": cpu["K"][0, 0].tolist(), "reprojection": reprojection_error(cpu), + "valid_pose_frames": int(cpu["local_pose_valid"].sum()), + "valid_geometry_frames": int(cpu["vertices_valid"].sum())}) + report = {"source": args.source, "tile_id": spec["tile_id"], "three_resolutions": rows, + "visual_weights_verified": True, "last_two": args.last_two} + if not args.geometry_only: + device = torch.device(args.device) + torch.cuda.set_device(device) + free, _ = torch.cuda.mem_get_info(device) + if free < 18 * 1024**3: + raise RuntimeError("pilot GPU has less than 18 GiB free") + torch.manual_seed(20261003) + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if args.last_two: + model.rgb_encoder.unfreeze_last_two() + model.to(device).train() + criterion = FromScratchLoss(fitted, {key: BASE_CONFIG["shared"]["loss"][key] for key in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + trainable = [p for p in model.parameters() if p.requires_grad] + cpu = base.collate_h2o_clips([dataset[dict(spec, target_hw=RESOLUTIONS[0])]]) + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, model) + torch.cuda.reset_peak_memory_stats(device) + start = time.monotonic() + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + forward_seconds = time.monotonic() - start + loss, terms, diagnostics = criterion(prediction, batch) + if not bool(torch.isfinite(loss)) or diagnostics["gt_rotation_orthogonality_max"] > 1e-5: + raise RuntimeError("nonfinite or nonorthogonal 6D target") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(trainable, 100) + torch.cuda.synchronize(device) + report["forward_backward"] = { + "seconds": time.monotonic() - start, "forward_seconds": forward_seconds, + "loss": float(loss.detach()), "weighted_terms": {k: float(v.detach()) for k, v in terms.items()}, + "diagnostics": diagnostics, "preclip_grad_norm": float(norm), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 1024**3, + "trainable_parameters": sum(p.numel() for p in trainable), + "backbone_trainable_parameters": sum(p.numel() for p in model.rgb_encoder.backbone.parameters() if p.requires_grad), + } + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite ViTPose-L pilot gradient") + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps(report, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/train.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/train.py new file mode 100644 index 0000000000000000000000000000000000000000..24f0eca0940aa70e60367ec3d9c9ef1a852fc316 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v3/train.py @@ -0,0 +1,320 @@ +"""Six-rank, teacher-free RGB ViTPose-L/MoT training with full resume state.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.fit_targets import mano_pkl_mean +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base, sha +from experiments.from_scratch_mean_pose.throughput_probe import collate_probe_samples, initialize_worker +from .data import MixedResolutionCoverage, MixedResolutionDataset, RESOLUTION_PCT +from .model import MANO_ROOT, VISUAL_SHA256, VISUAL_WEIGHTS, build_model, verify_visual_weights + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +SOURCES = ("H2O", "ARCTIC", "HOT3D") +STATS = BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"] +INDEX = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite") +LABELS = Path("/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json") + + +def code_hashes(): + files = [ROOT / "train.py", ROOT / "model.py", ROOT / "data.py", + ROOT / "hot3d_hand_only.py", ROOT / "config.json", + BASE_ROOT / "config.json", BASE_ROOT / "loss.py", BASE_ROOT / "model.py", BASE_ROOT / "fit_targets.py", + BASE_ROOT / "throughput_probe.py", + BASE_ROOT / "statistics_mano_pkl_v2.json", + ROOT.parent / "dinov3_2d_pretrain/vitpose_probe.py", + ROOT.parent / "u0_depthsafe/model.py", + ROOT.parent / "u0_depthsafe/reprojection.py", + ROOT.parent / "u0_normalized6d/normalized_loss.py", + ROOT.parent / "a7_rotation_fix/filtered_dataset.py", + ROOT.parent.parent / "src/foundation_hand/models/bimanual.py", + ROOT.parent.parent / "src/foundation_hand/models/decoder.py", + ROOT.parent.parent / "src/foundation_hand/models/encoders.py", + ROOT.parent.parent / "src/foundation_hand/models/mano.py", + ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py", + ROOT.parent.parent / "src/foundation_hand/data/schema.py", + ROOT.parent.parent / "src/foundation_hand/data/h2o_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/arctic_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/hot3d_dataset.py"] + return {str(path.relative_to(ROOT.parent.parent)): sha(path) for path in files} + + +def verify_contract(fitted): + verify_visual_weights() + if BASE_CONFIG["shared"]["teacher"] != { + "create_model": False, "forward": False, "distillation": False, "rgb_teacher_weight": 0.0, + } or not CONFIG["prohibit_teacher"] or not CONFIG["prohibit_old_model_checkpoint"]: + raise RuntimeError("teacher/parent checkpoint prohibited") + if BASE_CONFIG["shared"]["loss"]["joint2d"] != 0 or BASE_CONFIG["shared"]["loss"]["reprojection"] != 1: + raise RuntimeError("2D supervision must be MANO reprojection only") + if fitted["training_index_sha256"] != sha(INDEX) or fitted["label_inventory_sha256"] != sha(LABELS): + raise RuntimeError("train-only fitted statistics do not match current data") + if fitted["source_quota"] != CONFIG["source_quota_per_update"]: + raise RuntimeError("fitted statistic source mixture differs") + if fitted["version"] != "b0_b1_mano_pkl_mean_delta_v2": + raise RuntimeError("expected official MANO-pkl mean and normalized delta statistics") + mean, hashes = mano_pkl_mean(Path(MANO_ROOT)) + if hashes != fitted["mano_pkl_sha256"] or not torch.allclose( + torch.as_tensor(mean, dtype=torch.float64), + torch.as_tensor(fitted["mean_local"], dtype=torch.float64), atol=1e-7, rtol=0, + ): + raise RuntimeError("official MANO mean/asset mismatch") + if sha(VISUAL_WEIGHTS) != VISUAL_SHA256 or RESOLUTION_PCT != { + key: tuple(value) for key, value in CONFIG["resolution_pct_by_source"].items() + }: + raise RuntimeError("visual asset or mixed resolution contract changed") + if sum(CONFIG["source_quota_per_update"].values()) != CONFIG["global_batch"]: + raise RuntimeError("source quotas do not fill global batch") + if CONFIG["io"] != {"hot3d_provider": "hand_only", "prefetch_factor": 4}: + raise RuntimeError("IO-only protocol changed") + return {"code_sha256": code_hashes(), "index_sha256": sha(INDEX), + "labels_sha256": sha(LABELS), "statistics_sha256": sha(STATS), + "visual_sha256": VISUAL_SHA256, "mano_pkl_sha256": hashes} + + +def rng_state(): + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state()} + + +def restore_rng(state): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"]) + torch.cuda.set_rng_state(state["cuda"]) + + +def schedule(update): + settings = CONFIG["optimizer"] + endpoint = settings["initial_endpoint_updates"] + warmup = settings["warmup_updates"] + floor = settings["minimum_lr_ratio"] + fraction = min(1.0, max(0.0, (update - warmup) / (endpoint - warmup))) + factor = max(1 / warmup, (update + 1) / warmup) if update < warmup else ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * fraction))) + visual_stage = update - settings["freeze_visual_updates"] + visual = 0.0 if visual_stage < 0 else settings["visual_last2_lr_peak"] * min( + 1.0, (visual_stage + 1) / settings["visual_warmup_updates"]) * ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * max(0.0, min( + 1.0, (visual_stage - settings["visual_warmup_updates"]) / + (endpoint - settings["freeze_visual_updates"] - settings["visual_warmup_updates"])))))) + return settings["new_lr_peak"] * factor, visual + + +def save_checkpoint(path, model, optimizer, update, provenance, rng_states, exposure, smoke, world): + if path.exists(): + raise FileExistsError(path) + state = {"experiment": CONFIG["experiment"], "model": model.state_dict(), + "optimizer": optimizer.state_dict(), "update": update, + "next_sample_position": update * CONFIG["global_batch"], + "world_size": world, "global_batch": CONFIG["global_batch"], + "source_exposure": dict(exposure), "rank_rng_states": rng_states, + "provenance": provenance, "config": CONFIG, "complete_backbone": True, + "teacher_used": False, "parent_checkpoint": None, "smoke": smoke} + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + loaded = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("full checkpoint load-back failed") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, default=120000) + parser.add_argument("--resume", type=Path) + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--workers", type=int, default=2) + parser.add_argument("--log-every", type=int, default=25) + args = parser.parse_args() + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if (world != 6 and not (args.smoke and world == 2)) or args.updates < 1 or args.updates > CONFIG["optimizer"]["initial_endpoint_updates"]: + raise RuntimeError("formal contract requires six GPUs; two are permitted only for smoke") + if (args.smoke and args.updates > 2) or (not args.smoke and args.updates < 5000): + raise RuntimeError("smoke is at most two updates; formal stage must reach first 5K gate") + if args.workers < 1 or args.log_every < 1: + raise ValueError("workers/log interval must be positive") + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError(f"rank {rank}: less than 18 GiB free") + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=20), device_id=device) + try: + if rank == 0: + args.output.parent.mkdir(parents=True, exist_ok=True) + dist.barrier(device_ids=[local]) + if shutil.disk_usage(args.output.parent).free < 100 * 1024**3: + raise RuntimeError("less than 100 GiB free for complete checkpoints") + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + seed = BASE_CONFIG["shared"]["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + state = None + start = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["world_size"] != world + or state["global_batch"] != CONFIG["global_batch"] + or state["config"] != CONFIG or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] is not None or state["smoke"] != args.smoke): + raise RuntimeError("resume checkpoint contract mismatch") + start = state["update"] + if state["next_sample_position"] != start * CONFIG["global_batch"] or start >= args.updates: + raise RuntimeError("resume cursor or endpoint mismatch") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if start >= CONFIG["optimizer"]["freeze_visual_updates"]: + model.rgb_encoder.unfreeze_last_two() + model.to(device).train() + new = [p for name, p in model.named_parameters() + if not name.startswith("rgb_encoder.backbone.") and p.requires_grad] + visual = [p for name, p in model.named_parameters() + if name.startswith("rgb_encoder.backbone.layers.22.") + or name.startswith("rgb_encoder.backbone.layers.23.") + or name.startswith("rgb_encoder.backbone.ln1.")] + if not new or not visual or any(p.requires_grad for p in model.rgb_encoder.backbone.layers[:22].parameters()): + raise RuntimeError("optimizer parameter partition invalid") + optimizer = torch.optim.AdamW([ + {"params": new, "name": "new", "lr": schedule(start)[0]}, + {"params": visual, "name": "visual_last_two", "lr": schedule(start)[1]}, + ], weight_decay=CONFIG["optimizer"]["weight_decay"]) + exposure = Counter() + if state: + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + exposure.update(state["source_exposure"]) + restore_rng(state["rank_rng_states"][rank]) + del state + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh training would overwrite old metrics") + (args.output / "provenance.json").write_text(json.dumps({ + "experiment": CONFIG["experiment"], "contract": provenance, + "loss_coefficients": BASE_CONFIG["shared"]["loss"], + "optimizer": CONFIG["optimizer"], "io": CONFIG["io"], + "workers_per_rank": args.workers, + "resume": str(args.resume) if args.resume else None, "smoke": args.smoke, + }, indent=2) + "\n") + dist.barrier(device_ids=[local]) + sampler = base.PositionSampler(MixedResolutionCoverage(), + start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(MixedResolutionDataset(), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=True, + collate_fn=collate_probe_samples, pin_memory=True, prefetch_factor=4, + worker_init_fn=partial(initialize_worker, opencv_threads=1), + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + clips_per_rank = CONFIG["global_batch"] // world + for update in range(start, args.updates): + if update == CONFIG["optimizer"]["freeze_visual_updates"]: + dist.barrier(device_ids=[local]) + del ddp + model.rgb_encoder.unfreeze_last_two() + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + lr_new, lr_visual = schedule(update) + optimizer.param_groups[0]["lr"] = lr_new + optimizer.param_groups[1]["lr"] = lr_visual + started = time.monotonic() + cpu_batches = [next(iterator) for _ in range(clips_per_rank)] + data_ready = time.monotonic() + counts = Counter(cpu["sampling_source_id"][0] for cpu in cpu_batches) + local_counts = torch.tensor([counts[source] for source in SOURCES], device=device) + dist.all_reduce(local_counts) + if local_counts.tolist() != [CONFIG["source_quota_per_update"][source] for source in SOURCES]: + raise RuntimeError("source quota per update changed") + optimizer.zero_grad(set_to_none=True) + total_loss = 0.0 + term_totals = {key: 0.0 for key in TERMS} + nonpositive = 0 + valid_pose = 0 + for micro, cpu in enumerate(cpu_batches): + if cpu["input_mode"] != ["rgb"] or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("non-RGB input reached ViTPose-L") + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < clips_per_rank else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + loss, terms, diagnostics = objective(prediction, batch) + if not bool(torch.isfinite(loss)) or diagnostics["gt_rotation_orthogonality_max"] > 1e-5: + raise RuntimeError(f"nonfinite loss or invalid GT at update {update + 1}") + (loss / clips_per_rank).backward() + total_loss += float(loss.detach()) / clips_per_rank + for name, value in terms.items(): + term_totals[name] += float(value.detach()) / clips_per_rank + nonpositive += diagnostics["nonpositive_reprojection_joints"] + valid_pose += diagnostics["valid_local_frames"] + trainable = [p for p in model.parameters() if p.requires_grad] + norm = torch.nn.utils.clip_grad_norm_(trainable, CONFIG["optimizer"]["clip_grad_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"nonfinite gradient at update {update + 1}") + optimizer.step() + elapsed = time.monotonic() - started + for source, count in zip(SOURCES, local_counts.tolist()): + exposure[source] += count + if rank == 0 and ((update + 1) % args.log_every == 0 or update < 10): + row = {"update": update + 1, "consumed_clips": (update + 1) * CONFIG["global_batch"], + "seconds": elapsed, "data_wait_seconds": data_ready - started, + "loss_rank0": total_loss, "terms_rank0": term_totals, + "preclip_grad_norm_rank0": float(norm), "nonpositive_rank0": nonpositive, + "valid_local_pose_frames_rank0": valid_pose, + "learning_rate_new": lr_new, "learning_rate_visual": lr_visual, + "exposure": dict(exposure)} + log.write(json.dumps(row, allow_nan=False) + "\n") + print(json.dumps(row, allow_nan=False), flush=True) + if update + 1 in CONFIG["evaluation_updates"] or update + 1 == args.updates: + gathered = [None] * world + dist.all_gather_object(gathered, rng_state()) + if rank == 0: + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", model, + optimizer, update + 1, provenance, gathered, exposure, args.smoke, world) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/__init__.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..22d8dd8b2b6b1322e408c586055c7249add4e539 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/__init__.py @@ -0,0 +1,11 @@ +"""Teacher-free ViTPose-L RGB MoT training using this EgoNet source tree.""" + +from pathlib import Path +import sys + +_SOURCE = Path(__file__).resolve().parents[2] / "src" +sys.path.insert(0, str(_SOURCE)) +import foundation_hand # noqa: E402 + +if not Path(foundation_hand.__file__).resolve().is_relative_to(_SOURCE): + raise RuntimeError("ViTPose-L training must use this EgoNet foundation_hand source") diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/analyze_trace.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/analyze_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..02a77bcf1ea46fa5ee7296f0b6b8b30c5e568fcb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/analyze_trace.py @@ -0,0 +1,83 @@ +"""Summarize phase-local CPU synchronizations in a PyTorch Chrome trace.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +import json +from pathlib import Path + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("trace", type=Path) + args = parser.parse_args() + events = json.loads(args.trace.read_text())["traceEvents"] + markers = defaultdict(list) + for event in events: + if event.get("ph") == "X" and event.get("name", "").startswith("profile/"): + markers[(event.get("pid"), event.get("tid"))].append(event) + + sync = defaultdict(lambda: [0, 0.0]) + sync_names = Counter() + sync_ops = defaultdict(lambda: [0, 0.0]) + sync_python = defaultdict(lambda: [0, 0.0]) + thread_events = defaultdict(list) + for event in events: + if event.get("ph") == "X" and (event.get("cat") in ("cpu_op", "python_function", "user_annotation") or event.get("name") in ( + "cudaStreamSynchronize", "cudaDeviceSynchronize", "cudaEventSynchronize" + )): + thread_events[(event.get("pid"), event.get("tid"))].append(event) + if event.get("ph") != "X" or event.get("name") not in ( + "cudaStreamSynchronize", "cudaDeviceSynchronize", "cudaEventSynchronize" + ): + continue + sync_names[event["name"]] += 1 + enclosing = [marker for marker in markers[(event.get("pid"), event.get("tid"))] + if marker["ts"] <= event["ts"] + and event["ts"] + event["dur"] <= marker["ts"] + marker["dur"]] + phase = min(enclosing, key=lambda marker: marker["dur"])["name"] if enclosing else "other" + sync[phase][0] += 1 + sync[phase][1] += event["dur"] / 1000.0 + + for thread, spans in thread_events.items(): + spans.sort(key=lambda event: (event["ts"], -event["dur"])) + active = [] + for event in spans: + while active and active[-1]["ts"] + active[-1]["dur"] <= event["ts"]: + active.pop() + if event["name"] in sync_names: + nearest = next((parent["name"] for parent in reversed(active) + if parent["name"].startswith("aten::")), "other") + sync_ops[nearest][0] += 1 + sync_ops[nearest][1] += event["dur"] / 1000.0 + python_stack = [parent["name"] for parent in reversed(active) + if parent.get("cat") == "python_function"] + caller = python_stack[0] if python_stack else "other" + sync_python[caller][0] += 1 + sync_python[caller][1] += event["dur"] / 1000.0 + active.append(event) + + cuda_events = Counter(event.get("cat", "") for event in events + if event.get("ph") == "X" and event.get("cat", "").startswith("kernel")) + scalar_example = next((event for event in events if event.get("name") == "aten::_local_scalar_dense"), {}) + categories = Counter(event.get("cat", "") for event in events if event.get("ph") == "X") + output = { + "trace": str(args.trace), + "events": len(events), + "sync_names": sync_names, + "sync_by_phase": {key: {"calls": value[0], "cpu_ms": round(value[1], 3)} + for key, value in sorted(sync.items(), key=lambda row: -row[1][1])}, + "sync_by_parent_op": {key: {"calls": value[0], "cpu_ms": round(value[1], 3)} + for key, value in sorted(sync_ops.items(), key=lambda row: -row[1][1])}, + "sync_by_python_caller": {key: {"calls": value[0], "cpu_ms": round(value[1], 3)} + for key, value in sorted(sync_python.items(), key=lambda row: -row[1][1])[:20]}, + "kernel_event_categories": cuda_events, + "event_categories": categories.most_common(10), + "scalar_example": scalar_example, + } + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/audit_geometry_failure.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/audit_geometry_failure.py new file mode 100644 index 0000000000000000000000000000000000000000..e562243faca201d3b6a28385cdb73a7b809b3ee1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/audit_geometry_failure.py @@ -0,0 +1,110 @@ +"""Read-only replay of the canonical geometry guard on sampled training tiles.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +from types import SimpleNamespace + +import torch + +from foundation_hand.geometry.rotations import axis_angle_to_matrix, matrix_to_axis_angle +from foundation_hand.models.mano import ManoCameraLayer +from experiments.from_scratch_mean_pose.smoke import a7 +from experiments.from_scratch_mean_pose.throughput_probe import collate_probe_samples +from .data import MixedResolutionCoverage, MixedResolutionDataset +from .model import MANO_ROOT + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--first-update", type=int, required=True) + parser.add_argument("--last-update", type=int, required=True) + parser.add_argument("--rank", type=int, default=3) + parser.add_argument("--world", type=int, default=6) + parser.add_argument("--stop-first", action="store_true") + parser.add_argument("--position", type=int) + parser.add_argument("--formal-guard", action="store_true") + args = parser.parse_args() + if args.first_update < 0 or args.last_update <= args.first_update: + raise ValueError("invalid update range") + + torch.set_num_threads(2) + coverage = MixedResolutionCoverage() + dataset = MixedResolutionDataset() + mano = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=True).eval() + counts = Counter() + failures = [] + positions = ([args.position] if args.position is not None else + range(args.first_update * 60 + args.rank, + args.last_update * 60, args.world)) + for position in positions: + spec = coverage.sample(position) + sample = dataset[spec] + counts[spec["source"]] += 1 + if args.formal_guard: + a7.validate_cached_geometry( + collate_probe_samples([sample]), SimpleNamespace(mano_layer=mano)) + with torch.no_grad(): + rotation = axis_angle_to_matrix( + torch.nan_to_num(sample["mano_pose"]).reshape(-1, 2, 16, 3)) + vertices, _ = mano(rotation, torch.nan_to_num(sample["mano_shape"]), + torch.nan_to_num(sample["wrist_root_translation"])) + error = torch.linalg.vector_norm( + vertices - sample["vertices_camera"], dim=-1).amax(-1) + valid = sample["vertices_valid"].bool() + bad = valid & (~torch.isfinite(error) | (error > .001)) + if bad.any(): + row = dataset.sources[spec["source"]].rows[ + dataset.sources[spec["source"]].by_tile[spec["tile_id"]]] + record = { + "position": position, "update": position // 60 + 1, + "microbatch": (position // args.world) % 10 + 1, + "source": spec["source"], "tile_id": str(spec["tile_id"]), + "recording": str(row.get("recording_id", row.get("recording"))), + "target_hw": tuple(sample["rgb"].shape[-2:]), + "bad_frame_side": bad.nonzero().tolist(), + "error_mm": (error * 1000).tolist(), + "vertices_valid": valid.tolist(), + "mano_pose_valid": sample["mano_pose_valid"].bool().tolist(), + "global_orientation_valid": sample["global_orientation_valid"].bool().tolist(), + } + details = [] + for frame, side in bad.nonzero().tolist(): + pose = sample["mano_pose"][frame, side].reshape(16, 3) + matrix = axis_angle_to_matrix(pose) + recovered = matrix_to_axis_angle(matrix) + matrix_error = (axis_angle_to_matrix(recovered) - matrix).abs().amax((-1, -2)) + layer = dataset.labels[spec["source"]].source_mano.layers[side] + beta = sample["mano_shape"][frame, side].reshape(1, 10) + wrist = sample["wrist_root_translation"][frame, side].reshape(1, 1, 3) + with torch.no_grad(): + raw_vertices, raw_joints = layer(pose.reshape(1, 48), beta) + direct = (raw_vertices - raw_joints[:, :1]) / 1000 + wrist + recovered_vertices, recovered_joints = layer(recovered.reshape(1, 48), beta) + recovered_mesh = (recovered_vertices - recovered_joints[:, :1]) / 1000 + wrist + target = sample["vertices_camera"][frame, side] + details.append({ + "frame": frame, "side": side, + "root_pose": pose[0].tolist(), + "root_recovered": recovered[0].tolist(), + "root_matrix": matrix[0].tolist(), + "root_matrix_det": float(torch.linalg.det(matrix[0])), + "pose_norm_rad": pose.norm(dim=-1).tolist(), + "roundtrip_matrix_error": matrix_error.tolist(), + "direct_vs_target_max_mm": float((direct[0] - target).norm(dim=-1).max() * 1000), + "recovered_vs_target_max_mm": float((recovered_mesh[0] - target).norm(dim=-1).max() * 1000), + }) + record["details"] = details + failures.append(record) + print(json.dumps({"failure": record}), flush=True) + if args.stop_first: + break + print(json.dumps({"range": [args.first_update, args.last_update], + "rank": args.rank, "counts": counts, + "failure_count": len(failures)}), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/audit_resolution.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/audit_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c940207a8da5d66ff485acc51485859017483c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/audit_resolution.py @@ -0,0 +1,85 @@ +"""Check official HOT3D rectified image size and hand size under each target canvas.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from foundation_hand.data.hot3d_dataset import quest_linear_camera_calibration +from .data import MixedResolutionCoverage, MixedResolutionDataset, RESOLUTIONS + + +def hand_extents(sample): + coordinates = sample["joint2d"].float() + valid = sample["joint2d_valid"].bool() & torch.isfinite(coordinates).all(-1) + extents = [] + for frame in range(coordinates.shape[0]): + for side in range(2): + points = coordinates[frame, side][valid[frame, side]] + if len(points) < 5: + continue + size = points.max(dim=0).values - points.min(dim=0).values + extents.append((float(size[0]), float(size[1]))) + return {"valid_hand_frames": len(extents), + "median_bbox_width_px": float(torch.tensor([value[0] for value in extents]).median()) if extents else None, + "median_bbox_height_px": float(torch.tensor([value[1] for value in extents]).median()) if extents else None} + + +def source_image_size(native, row): + provider = native._provider(str(row["recording_id"])) + stream_id = native._api["StreamId"](str(row["stream_id"])) + timestamp = int(row["timestamps_ns"][0]) + device = provider.device_data_provider + if row["headset"] == "Aria": + _, calibration = device.get_online_camera_calibration( + stream_id, timestamp, camera_model=native._api["LINEAR"]) + else: + _, calibration = quest_linear_camera_calibration( + device, stream_id, native._api["LINEAR"], native._api["FISHEYE624"]) + image = device.get_undistorted_image(timestamp, stream_id) + return {"calibration_hw": list(map(int, calibration.get_image_size()[::-1])), + "undistorted_image_hw": list(map(int, image.shape[:2]))} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + coverage, dataset = MixedResolutionCoverage(), MixedResolutionDataset() + found = {} + for position in range(3000): + spec = coverage.sample(position) + if spec["source"] != "HOT3D": + continue + row = dataset.sources["HOT3D"].rows[dataset.sources["HOT3D"].by_tile[spec["tile_id"]]] + headset = row["headset"] + if headset not in found: + found[headset] = (spec, row) + if set(found) == {"Aria", "Quest3"}: + break + if set(found) != {"Aria", "Quest3"}: + raise RuntimeError("coverage audit did not sample both HOT3D headset types") + report = {} + for headset, (spec, row) in found.items(): + entries = [] + for hw in RESOLUTIONS: + sample = dataset[dict(spec, target_hw=hw)] + native = dataset._reader("HOT3D", hw).native + source = source_image_size(native, row) + if source["calibration_hw"] != source["undistorted_image_hw"]: + raise RuntimeError(f"{headset} calibration/image dimensions differ") + entries.append({"target_hw": hw, **source, **hand_extents(sample)}) + report[headset] = {"recording": row["recording_id"], "stream_id": row["stream_id"], + "tile": spec["tile_id"], "resolutions": entries} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps(report, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ce3f12cf7b0fa114261c19e07101d237f29dafb7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/config.json @@ -0,0 +1,24 @@ +{ + "experiment": "vitpose_l_mot_rgb_from_scratch_io_v4_rotationfix_grouped_20261007", + "status": "rotationfix_grouped_resolution_protocol_v1", + "visual_sha256": "82dea141d75805068ce80705b9a3965af9cbc62a1844c46d88238012a2c2097f", + "initialization": "ViTPose-L visual-only; all other weights random; no teacher or old MANO checkpoint", + "source_quota_per_update": {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}, + "global_batch": 60, + "io": {"hot3d_provider": "hand_only", "prefetch_factor": 16, "group_max_clips": 10}, + "frames": 8, + "resolutions_hw": [[512, 896], [368, 640], [512, 512]], + "resolution_pct_by_source": { + "H2O": [75, 20, 5], "ARCTIC": [70, 20, 10], + "HOT3D_Aria": [30, 15, 55], "HOT3D_Quest3": [60, 20, 20] + }, + "optimizer": {"name": "AdamW", "new_lr_peak": 0.00005, "visual_last2_lr_peak": 0.000001, + "weight_decay": 0.05, "clip_grad_norm": 100, "freeze_visual_updates": 5000, + "warmup_updates": 1000, "visual_warmup_updates": 1000, + "minimum_lr_ratio": 0.1, "initial_endpoint_updates": 120000}, + "evaluation_updates": [5000, 10000, 20000, 40000, 60000, 80000, 100000, 120000], + "loss_source": "experiments/from_scratch_mean_pose/config.json shared.loss", + "statistics_source": "experiments/from_scratch_mean_pose/statistics_mano_pkl_v2.json", + "prohibit_teacher": true, + "prohibit_old_model_checkpoint": true +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/controller.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..d423b71abdd4e3d7fd66b7e105e15211e56c8500 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/controller.py @@ -0,0 +1,203 @@ +"""Wait for six idle G1 GPUs, then run staged training and native-GT evaluation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime +import json +import os +from pathlib import Path +import subprocess +import sys +import time + +from .train import CONFIG + + +ROOT = Path(__file__).resolve().parents[2] +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +TORCHRUN = "/SSD2/jiasen/envs/foundation_hand/bin/torchrun" +SOURCES = ("H2O", "ARCTIC", "HOT3D") +HK = ROOT / "docs/HK.md" + + +def gpu_idle(indices, max_memory_mib=200, max_utilization_pct=5): + result = subprocess.run(["nvidia-smi", "--query-gpu=index,memory.used,utilization.gpu", + "--format=csv,noheader,nounits"], text=True, capture_output=True, check=True) + usage = {} + for line in result.stdout.splitlines(): + gpu, memory, utilization = (int(value.strip()) for value in line.split(",")) + usage[gpu] = {"memory_mib": memory, "utilization_pct": utilization} + return all(index in usage and usage[index]["memory_mib"] <= max_memory_mib + and usage[index]["utilization_pct"] <= max_utilization_pct for index in indices), usage + + +def write_status(path, **fields): + value = {"time_hkt": datetime.now().astimezone().isoformat(), **fields} + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n") + os.replace(temporary, path) + + +def wait_for_idle(indices, status, stage, samples=3, interval=30): + streak = 0 + while streak < samples: + try: + free, usage = gpu_idle(indices) + except (OSError, subprocess.SubprocessError, ValueError) as error: + free, usage = False, {"error": str(error)} + streak = streak + 1 if free else 0 + write_status(status, state="waiting_for_idle_gpus", stage=stage, + idle_streak=streak, required_streak=samples, usage=usage) + if streak < samples: + time.sleep(interval) + + +def run_logged(command, log_path, env, status, state, stage): + write_status(status, state=state, stage=stage, command=command, log=str(log_path)) + with log_path.open("a", buffering=1) as log: + log.write(json.dumps({"event": "start", "time_hkt": datetime.now().astimezone().isoformat(), + "command": command}) + "\n") + result = subprocess.run(command, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT) + log.write(json.dumps({"event": "exit", "time_hkt": datetime.now().astimezone().isoformat(), + "returncode": result.returncode}) + "\n") + if result.returncode: + write_status(status, state="failed_needs_review", stage=stage, + returncode=result.returncode, log=str(log_path)) + raise RuntimeError(f"{stage} failed with code {result.returncode}: {log_path}") + + +def record_evaluation(update, output): + reports = {source: json.loads((output / "evaluations" / + f"update_{update:07d}_{source.lower()}.json").read_text()) + for source in SOURCES} + lines = [f"\n## {datetime.now().astimezone():%Y-%m-%d %H:%M} HKT: ViTPose-L + MoT {update:,} 更新评估\n", + "\n训练为视觉主干预训练 + 其它部分从头,纯 RGB、T=8、三源 21/15/24;下表为固定 held-out source-native GT,未使用 teacher 或 parent checkpoint。\n", + "\n| Source / group | Abs MPJPE mm | Root MPJPE mm | MPVPE mm | 2D px | local pose deg | bend bias deg | pred/GT 6D var |\n", + "|---|---:|---:|---:|---:|---:|---:|---:|\n"] + names = ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", "local_pose_angle_deg", "bend_bias_deg") + for source in SOURCES: + report = reports[source] + for group in ("all", "hard_pose"): + values = [report[group]["metrics"][name]["mean"] for name in names] + cells = [f"{value:.3f}" if value is not None else "n/a" for value in values] + ratio = report[group]["pred_gt_local_6d_variance_ratio_macro"] + cells.append(f"{ratio:.3f}" if ratio is not None else "n/a") + lines.append(f"| {source} / {group} | " + " | ".join(cells) + " |\n") + lines.append("\n完整报告与逐手记录见本实验 `evaluations/`;单节点结果不等于收敛结论,继续看后续节点的四指标、hard pose 与 normal no-harm。\n") + with HK.open("a") as document: + document.writelines(lines) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--idle-samples", type=int, default=3) + parser.add_argument("--idle-interval", type=int, default=30) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--smoke-output", type=Path) + parser.add_argument("--preflight-only", action="store_true") + args = parser.parse_args() + if args.idle_samples < 2 or args.idle_interval < 10 or args.workers < 1: + raise ValueError("idle gate must cover multiple samples and at least 10-second intervals") + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + (output / "evaluations").mkdir(exist_ok=True) + status = output / "controller_status.json" + smoke_output = (args.smoke_output or output.parent / "smoke_io_v4").resolve() + if smoke_output == output: + raise ValueError("smoke and formal outputs must be separate") + smoke_checkpoint = smoke_output / "update_0000002.pt" + resolution_audit = output.parent / "hot3d_resolution_audit.json" + if not resolution_audit.is_file(): + raise RuntimeError("HOT3D resolution audit is missing") + endpoints = CONFIG["evaluation_updates"] + if endpoints != [5000, 10000, 20000, 40000, 60000, 80000, 100000, 120000]: + raise RuntimeError("evaluation cadence changed") + env = os.environ.copy() + env["CUDA_VISIBLE_DEVICES"] = "0,1,2,3,4,5" + env["OMP_NUM_THREADS"] = "1" + env["OPENBLAS_NUM_THREADS"] = "1" + env["MKL_NUM_THREADS"] = "1" + env["PYTHONPATH"] = f"{ROOT / 'src'}:{ROOT}" + for endpoint in (1, 2): + checkpoint = smoke_output / f"update_{endpoint:07d}.pt" + if checkpoint.is_file(): + continue + previous = smoke_output / "update_0000001.pt" if endpoint == 2 else None + if previous is not None and not previous.is_file(): + raise RuntimeError("post-fix smoke step-1 checkpoint missing") + wait_for_idle(range(6), status, f"postfix_smoke_{endpoint}", + samples=args.idle_samples, interval=args.idle_interval) + smoke_env = env.copy() + smoke_env["CUDA_VISIBLE_DEVICES"] = "0,1,2,3,4,5" + command = [TORCHRUN, "--standalone", "--nnodes=1", "--nproc_per_node=6", + "-m", "experiments.vitpose_mot_io_v4.train", "--output", str(smoke_output), + "--updates", str(endpoint), "--smoke", "--workers", str(args.workers), "--log-every", "1"] + if previous: + command += ["--resume", str(previous)] + run_logged(command, output / f"postfix_smoke_{endpoint}.log", smoke_env, + status, "preflight_training", endpoint) + if not checkpoint.is_file(): + raise RuntimeError(f"post-fix smoke returned without checkpoint {checkpoint}") + for source in SOURCES: + report = output / "evaluations" / f"preflight_smoke_{source.lower()}.json" + if report.is_file(): + continue + wait_for_idle((0,), status, f"preflight_eval_{source}", samples=2, interval=15) + smoke_env = env.copy() + smoke_env["CUDA_VISIBLE_DEVICES"] = "0" + run_logged([PYTHON, "-m", "experiments.vitpose_mot_io_v4.evaluate", + "--checkpoint", str(smoke_checkpoint), "--source", source, + "--output", str(report), "--limit", "2", "--smoke"], + output / f"preflight_eval_{source.lower()}.log", smoke_env, + status, "preflight_evaluation", source) + if args.preflight_only: + write_status(status, state="preflight_complete_awaiting_performance_gate", stage="preflight") + return + for endpoint in endpoints: + checkpoint = output / f"update_{endpoint:07d}.pt" + previous = output / f"update_{endpoints[endpoints.index(endpoint) - 1]:07d}.pt" if endpoint != endpoints[0] else None + if not checkpoint.is_file(): + if previous is not None and not previous.is_file(): + raise RuntimeError(f"missing previous full checkpoint: {previous}") + wait_for_idle(range(6), status, f"train_to_{endpoint}", + samples=args.idle_samples, interval=args.idle_interval) + command = [TORCHRUN, "--standalone", "--nnodes=1", "--nproc_per_node=6", + "-m", "experiments.vitpose_mot_io_v4.train", "--output", str(output), + "--updates", str(endpoint), "--workers", str(args.workers), "--log-every", "25"] + if previous: + command += ["--resume", str(previous)] + run_logged(command, output / f"train_to_{endpoint:07d}.log", env, status, + "training", endpoint) + if not checkpoint.is_file(): + raise RuntimeError(f"training returned without checkpoint {checkpoint}") + for source in SOURCES: + report = output / "evaluations" / f"update_{endpoint:07d}_{source.lower()}.json" + if report.is_file(): + continue + wait_for_idle((0,), status, f"eval_{endpoint}_{source}", samples=2, interval=15) + eval_env = env.copy() + eval_env["CUDA_VISIBLE_DEVICES"] = "0" + run_logged([PYTHON, "-m", "experiments.vitpose_mot_io_v4.evaluate", + "--checkpoint", str(checkpoint), "--source", source, + "--output", str(report)], + output / f"eval_{endpoint:07d}_{source.lower()}.log", eval_env, + status, "evaluating", f"{endpoint}_{source}") + marker = output / "evaluations" / f"update_{endpoint:07d}_hk_recorded.json" + if not marker.exists(): + record_evaluation(endpoint, output) + marker.write_text(json.dumps({"update": endpoint, + "recorded_at": datetime.now().astimezone().isoformat()}) + "\n") + write_status(status, state="evaluated", stage=endpoint, + checkpoint=str(checkpoint), next_endpoint=next((value for value in endpoints if value > endpoint), None)) + write_status(status, state="complete_120k_waiting_for_curve_review", stage=120000) + + +if __name__ == "__main__": + try: + main() + except Exception as error: + print(f"controller failed: {error}", file=sys.stderr, flush=True) + raise diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/data.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/data.py new file mode 100644 index 0000000000000000000000000000000000000000..6b4905464192926ce378fc5f5a86883d8c846d52 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/data.py @@ -0,0 +1,99 @@ +"""Canonical train-only RGB clips with deterministic source-specific resolutions.""" + +from __future__ import annotations + +import hashlib +from types import MethodType + +import torch + +from experiments.from_scratch_mean_pose.smoke import U0Coverage, U0Dataset, a7, base +from experiments.a7_rotation_fix.filtered_dataset import intersect_filtered_valid +from .hot3d_hand_only import hand_only_provider + + +RESOLUTIONS = ((512, 896), (368, 640), (512, 512)) +RESOLUTION_PCT = { + "H2O": (75, 20, 5), + "ARCTIC": (70, 20, 10), + "HOT3D_Aria": (30, 15, 55), + "HOT3D_Quest3": (60, 20, 20), +} + + +def mask_invalid_joint3d(sample: dict) -> None: + sample["joint3d_valid"] &= torch.isfinite(sample["joint3d_camera"]).all(dim=-1) + + +def resolution_for(source: str, headset: str | None, position: int) -> tuple[int, int]: + name = f"{source}_{headset}" if source == "HOT3D" else source + weights = RESOLUTION_PCT[name] + digest = hashlib.blake2b(f"20261006:{position}:{name}".encode(), digest_size=8).digest() + draw = int.from_bytes(digest, "big") % 100 + return RESOLUTIONS[0 if draw < weights[0] else 1 if draw < weights[0] + weights[1] else 2] + + +class MixedResolutionCoverage(U0Coverage): + def __init__(self): + super().__init__() + self.seed = 20261003 + + def sample(self, position): + spec = super().sample(position) + if spec["source"] == "HOT3D": + # The immutable filtered manifest resolves headset by tile ID. + spec["target_hw"] = None + else: + spec["target_hw"] = resolution_for(spec["source"], None, position) + return spec + + +class MixedResolutionDataset(U0Dataset): + def __init__(self): + super().__init__() + self.alternates = {} + native = self.sources["HOT3D"].native + native._provider = MethodType(hand_only_provider, native) + + def _reader(self, source, target_hw): + if target_hw == (512, 896): + return self.sources[source] + key = (source, target_hw) + if key not in self.alternates: + self.alternates[key] = base.FilteredClipDataset( + source, + base.MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl", + 8, target_hw, base.ASSETS["mano_root"], + a7.reference.BASE_CODE / "third_party", + {"enabled": source != "HOT3D", "probability": .8}, + ) + if source == "HOT3D": + native = self.alternates[key].native + native._provider = MethodType(hand_only_provider, native) + return self.alternates[key] + + def __getitem__(self, spec): + source = spec["source"] + anchor = self.sources[source] + row = anchor.rows[anchor.by_tile[spec["tile_id"]]] + target_hw = spec["target_hw"] + if target_hw is None: + target_hw = resolution_for(source, row["headset"], spec["position"]) + original = self._reader(source, target_hw) + sample = original[spec] + if sample["input_mode"] != "rgb": + raise RuntimeError("ViTPose-L experiment requires RGB-only input") + native_joints = sample["joint3d_camera"].clone() + native_valid = sample["joint3d_valid"].clone() + row = original.rows[original.by_tile[spec["tile_id"]]] + sample = self.labels[source].apply(sample, row, original.native) + intersect_filtered_valid(sample, row) + mask_invalid_joint3d(sample) + quality = sample["vertices_valid"].bool() + sample["global_orientation_valid"] &= quality + sample["local_pose_valid"] &= quality + sample["source_native_joint3d_camera"] = native_joints + sample["source_native_joint3d_valid"] = native_valid + if tuple(sample["rgb"].shape[-2:]) != target_hw: + raise RuntimeError(f"source reader returned wrong target shape for {source}") + return sample diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/evaluate.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..d31e5a33273ea1d897b0b64e864ae7040957d00f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/evaluate.py @@ -0,0 +1,178 @@ +"""Frozen source-native development benchmark and hard-pose diagnostics.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + +import numpy as np +import torch + +from experiments.from_scratch_mean_pose.smoke import a7, base, sha + +from clean_eval import apply_mode, dataset_for +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from scripts.evaluate_phase7_external import make_row +from targets import NativePanel + +from .model import build_model +from .train import CONFIG, STATS, verify_contract + + +FOUR = ("absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px") + + +def finite(value): + if isinstance(value, dict): + return {key: finite(item) for key, item in value.items()} + if isinstance(value, list): + return [finite(item) for item in value] + return None if isinstance(value, float) and not math.isfinite(value) else value + + +def finger_angles(joints): + fingers = joints[..., 1:, :].reshape(*joints.shape[:-2], 5, 4, 3) + bones = fingers[..., 1:, :] - fingers[..., :-1, :] + lengths = torch.linalg.vector_norm(bones, dim=-1) + unit = bones / lengths.clamp_min(1e-8)[..., None] + angles = torch.rad2deg(torch.acos((unit[..., :-1, :] * unit[..., 1:, :]).sum(-1).clamp(-1, 1))) + complete = (lengths > 1e-6).all(dim=(-1, -2)) & torch.isfinite(angles).all(dim=(-1, -2)) + return angles, complete + + +def summarize(rows): + result = {} + for key in (*FOUR, "local_pose_angle_deg", "fingertip_root_relative_mm", + "bend_bias_deg", "gt60_bend_bias_deg"): + values = [row[key] for row in rows if row.get(key) is not None and math.isfinite(row[key])] + result[key] = {"mean": float(np.mean(values)) if values else None, "count": len(values)} + complete = [row for row in rows if "gt_local_6d" in row] + if len(complete) > 1: + gt = np.asarray([row["gt_local_6d"] for row in complete], dtype=np.float64) + pred = np.asarray([row["pred_local_6d"] for row in complete], dtype=np.float64) + gt_variance = gt.var(axis=0) + pred_variance = pred.var(axis=0) + eligible = gt_variance > 1e-8 + ratio = pred_variance[eligible] / gt_variance[eligible] + variance_ratio = float(ratio.mean()) if ratio.size else None + per_joint = np.asarray([row["local_pose_per_joint_deg"] for row in complete], dtype=np.float64).mean(axis=0).tolist() + else: + variance_ratio, per_joint = None, None + return {"hands": len(rows), "metrics": result, + "pred_gt_local_6d_variance_ratio_macro": variance_ratio, + "local_pose_per_joint_mean_deg": per_joint} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--limit", type=int) + parser.add_argument("--smoke", action="store_true") + args = parser.parse_args() + if args.output.exists() or args.output.with_suffix(".rows.json").exists(): + raise FileExistsError(args.output) + if args.limit is not None and args.limit < 1: + raise ValueError("positive limit required") + if (args.limit is not None or "smoke" in str(args.checkpoint)) and not args.smoke: + raise RuntimeError("subset or smoke checkpoint requires explicit --smoke") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] is not None or state["smoke"] != args.smoke): + raise RuntimeError("evaluation checkpoint composition invalid") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + model.load_state_dict(state["model"], strict=True) + model.to("cuda").eval() + panel_root = a7.BASE_ROOT / "eval/frozen_panels_sync_v2" + registry = json.loads((panel_root / "panels.json").read_text()) + manifest = panel_root / f"{args.source.lower()}_development_t8.jsonl" + registered = registry["sources"][args.source]["development"] + if sha(manifest) != registered["manifest_sha256"] or registry["sources"][args.source]["train_overlap"]: + raise RuntimeError("development panel overlaps training or hash changed") + manifest_rows = [json.loads(line) for line in manifest.read_text().splitlines() if line.strip()] + native = (ARCTICClipDataset(manifest, base.ASSETS["mano_root"], (512, 896), + hand_valid_policy="visible_mesh") if args.source == "ARCTIC" + else dataset_for(args.source, manifest)) + dataset = NativePanel(args.source, native, manifest_rows) + limit = min(args.limit, len(dataset)) if args.limit else len(dataset) + rows = [] + with torch.inference_mode(): + for index in range(limit): + batch = base.collate_h2o_clips([dataset[index]]) + apply_mode(batch, "rgb") + batch = base.move_to_device(batch, torch.device("cuda")) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + if not bool(torch.isfinite(prediction["joints_camera"]).all()): + raise RuntimeError(f"nonfinite development prediction at clip {index}") + pose_valid = batch["mano_pose_valid"].bool() & batch["frame_valid"].bool()[..., None] + joint_valid = batch["joint3d_root_relative_valid"].bool().all(dim=-1) + gt_angles, complete_geometry = finger_angles(batch["joint3d_camera"].float()) + pred_angles, _ = finger_angles(prediction["joints_camera"].float()) + complete = pose_valid & joint_valid & complete_geometry + gt_hard = ((gt_angles >= 45).sum(dim=(-1, -2)) >= 2) | (gt_angles >= 60).any(dim=(-1, -2)) + target_rotation = axis_angle_to_matrix(torch.nan_to_num(batch["mano_pose"].float()).reshape( + *pose_valid.shape, 16, 3)) + relative = prediction["mano_rotation_matrices"].float() @ target_rotation.transpose(-1, -2) + trace = relative.diagonal(dim1=-2, dim2=-1).sum(-1) + angle_error = torch.rad2deg(torch.acos(((trace - 1) / 2).clamp(-1, 1))) + predicted_rel = prediction["joints_camera"].float() - prediction["joints_camera"].float()[..., :1, :] + target_rel = batch["joint3d_camera"].float() - batch["joint3d_camera"].float()[..., :1, :] + tip_error = torch.linalg.vector_norm(predicted_rel[..., [4, 8, 12, 16, 20], :] + - target_rel[..., [4, 8, 12, 16, 20], :], dim=-1).mean(-1) * 1000 + for frame in range(batch["frame_valid"].shape[1]): + if not bool(batch["frame_valid"][0, frame]): + continue + for side in range(2): + row = make_row(prediction, batch, 0, frame, side) + if bool(complete[0, frame, side]): + gt = gt_angles[0, frame, side] + difference = pred_angles[0, frame, side] - gt + high = gt >= 60 + row.update({ + "gt_hard": bool(gt_hard[0, frame, side]), + "local_pose_angle_deg": float(angle_error[0, frame, side, 1:].mean()), + "fingertip_root_relative_mm": float(tip_error[0, frame, side]), + "bend_bias_deg": float(difference.mean()), + "gt60_bend_bias_deg": float(difference[high].mean()) if bool(high.any()) else None, + "local_pose_per_joint_deg": angle_error[0, frame, side, 1:].tolist(), + "gt_local_6d": target_rotation[0, frame, side, 1:, :2, :].reshape(15, 6).tolist(), + "pred_local_6d": prediction["mano_rotation_matrices"][0, frame, side, 1:, :2, :].float().reshape(15, 6).tolist(), + }) + else: + row.update({"gt_hard": None, "local_pose_angle_deg": None, + "fingertip_root_relative_mm": None, + "bend_bias_deg": None, "gt60_bend_bias_deg": None}) + rows.append(row) + if (index + 1) % 32 == 0: + print(json.dumps({"source": args.source, "done": index + 1, "total": limit}), flush=True) + complete_rows = [row for row in rows if row["gt_hard"] is not None] + report = {"experiment": CONFIG["experiment"], "source": args.source, + "role": "development_subset_smoke" if args.limit else "development_full", + "input_mode": "rgb", "frames": 8, "source_native_gt": True, + "training_update": state["update"], "checkpoint_sha256": sha(args.checkpoint), + "panel_sha256": sha(manifest), "clips": limit, + "hard_definition": "GT >=2 distal angles >=45deg or >=1 >=60deg, complete joints and MANO pose", + "all": summarize(rows), "pose_complete": summarize(complete_rows), + "normal_pose": summarize([row for row in complete_rows if not row["gt_hard"]]), + "hard_pose": summarize([row for row in complete_rows if row["gt_hard"]])} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + args.output.with_suffix(".rows.json").write_text(json.dumps(finite(rows), allow_nan=False) + "\n") + print(json.dumps({"source": args.source, "update": state["update"], + "all": report["all"], "hard_pose": report["hard_pose"]}, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/hot3d_hand_only.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/hot3d_hand_only.py new file mode 100644 index 0000000000000000000000000000000000000000..251fba2cbbab425ccd728d062f9ef36d48dbb4f6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/hot3d_hand_only.py @@ -0,0 +1,47 @@ +"""Load only the official HOT3D streams used by RGB hand training.""" + +from __future__ import annotations + +import json +from pathlib import Path +from types import SimpleNamespace + +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def hand_only_provider(self: HOT3DClipDataset, recording: str): + self._initialize_runtime() + if recording in self._providers: + provider = self._providers.pop(recording) + self._providers[recording] = provider + return provider + + from data_loaders.AriaDataProvider import AriaDataProvider + from data_loaders.HeadsetPose3dProvider import load_headset_pose_provider_from_csv + from data_loaders.ManoHandDataProvider import MANOHandDataProvider + from data_loaders.PathProvider import Hot3dDataPathProvider + from data_loaders.QuestDataProvider import QuestDataProvider + + paths = Hot3dDataPathProvider.fromRecordingFolder( + recording_instance_folderpath=str(self.root / recording) + ) + if not paths.is_valid(): + raise RuntimeError(f"invalid official HOT3D recording {recording}") + headset = json.loads(Path(paths.scene_metadata_filepath).read_text())["headset"] + if headset == "Aria": + device = AriaDataProvider(paths.vrs_filepath, paths.mps_folderpath) + elif headset == "Quest3": + device = QuestDataProvider(paths.vrs_filepath, paths.camera_models_filepath) + else: + raise RuntimeError(f"unsupported headset {headset}") + provider = SimpleNamespace( + device_data_provider=device, + device_pose_data_provider=load_headset_pose_provider_from_csv(paths.headset_trajectory_filepath), + mano_hand_data_provider=MANOHandDataProvider( + paths.mano_hand_pose_trajectory_filepath, self._source_mano + ), + ) + self._providers[recording] = provider + while len(self._providers) > self.provider_cache_size: + self._providers.popitem(last=False) + return provider diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/migrate_checkpoint.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/migrate_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..fe3191e40e36111777d53d2551666dea7f1767c3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/migrate_checkpoint.py @@ -0,0 +1,75 @@ +"""Apply the audited G1-to-G2 visual asset path relocation to a checkpoint.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path + +import torch + +from experiments.from_scratch_mean_pose.smoke import sha +from .train import CONFIG, STATS, verify_contract + + +EXPECTED_ORIGINAL_SHA = "8e25a2a50f64406528fd84af01526961fe030af49126b85f587a679e7bd32bb1" +ALLOWED_CODE_CHANGE = "experiments/vitpose_mot_io_v4/model.py" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists() or args.output.with_suffix(".tmp").exists(): + raise FileExistsError(args.output) + if sha(args.source) != EXPECTED_ORIGINAL_SHA: + raise RuntimeError("source is not the verified G1 10K checkpoint") + expected = verify_contract(json.loads(STATS.read_text())) + state = torch.load(args.source, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["update"] != 10000 + or state["next_sample_position"] != 600000 or state["world_size"] != 6 + or state["global_batch"] != 60 or state["config"] != CONFIG + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] is not None or state["smoke"]): + raise RuntimeError("G1 checkpoint training contract differs") + original = state["provenance"] + if set(original) != set(expected): + raise RuntimeError("provenance fields differ") + for key in set(expected) - {"code_sha256"}: + if original[key] != expected[key]: + raise RuntimeError(f"non-code provenance differs: {key}") + before, after = original["code_sha256"], expected["code_sha256"] + if set(before) != set(after): + raise RuntimeError("code inventory differs") + changed = {key for key in before if before[key] != after[key]} + if changed != {ALLOWED_CODE_CHANGE}: + raise RuntimeError(f"unexpected code changes: {sorted(changed)}") + state["provenance"] = expected + state["resource_relocation"] = { + "reason": "same SHA-256 ViTPose-L visual weights at G2-local path", + "source_checkpoint_sha256": EXPECTED_ORIGINAL_SHA, + "changed_code_file": ALLOWED_CODE_CHANGE, + "old_code_sha256": before[ALLOWED_CODE_CHANGE], + "new_code_sha256": after[ALLOWED_CODE_CHANGE], + "visual_sha256": expected["visual_sha256"], + } + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, args.output) + loaded = torch.load(args.output, map_location="cpu", weights_only=False, mmap=True) + if (loaded["update"] != 10000 or loaded["provenance"] != expected + or set(loaded["model"]) != set(state["model"]) + or set(loaded["optimizer"]) != set(state["optimizer"])): + raise RuntimeError("relocated checkpoint load-back failed") + args.output.with_suffix(".migration.json").write_text(json.dumps( + state["resource_relocation"] | {"output_checkpoint_sha256": sha(args.output)}, + indent=2) + "\n") + print(json.dumps({"checkpoint": str(args.output), + "migration": str(args.output.with_suffix('.migration.json'))})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/model.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/model.py new file mode 100644 index 0000000000000000000000000000000000000000..de2a17fbcacd6c6a7d0f6a894e48adf91aa05783 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/model.py @@ -0,0 +1,96 @@ +"""Full-frame ViTPose-L backbone and freshly initialized MANO MoT.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path + +import torch +from torch import nn +from torch.utils.checkpoint import checkpoint + +from foundation_hand.models.bimanual import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.encoders import PatchFeatures +from experiments.dinov3_2d_pretrain.vitpose_probe import ViTPoseBackbone +from experiments.from_scratch_mean_pose.model import MeanDeltaRotationHead +from experiments.u0_depthsafe.model import UnifiedRGBDecoder + + +VISUAL_WEIGHTS = Path("/home/wuyifan/artifacts/gkdt_feature_probe_20261006/vitpose_large_visual.pt") +VISUAL_SHA256 = "82dea141d75805068ce80705b9a3965af9cbc62a1844c46d88238012a2c2097f" +MANO_ROOT = "/SSD3/jiasen/foundation_hand/pretrained/mano" + + +def verify_visual_weights(path: Path = VISUAL_WEIGHTS) -> None: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + if digest.hexdigest() != VISUAL_SHA256: + raise RuntimeError("ViTPose-L visual checkpoint SHA-256 mismatch") + + +class TrainableViTPoseEncoder(nn.Module): + def __init__(self, weights: Path = VISUAL_WEIGHTS, output_dim: int = 512) -> None: + super().__init__() + verify_visual_weights(weights) + state = torch.load(weights, map_location="cpu", weights_only=True) + if state["pos_embed"].shape != (1, 193, 1024): + raise RuntimeError("unexpected ViTPose-L positional embedding") + if {int(key.split(".")[1]) for key in state if key.startswith("layers.")} != set(range(24)): + raise RuntimeError("ViTPose-L checkpoint is missing transformer blocks") + self.backbone = ViTPoseBackbone(1024, 24, 16) + self.backbone.load_state_dict(state, strict=True) + self.backbone.requires_grad_(False) + self.projection = nn.Linear(1024, output_dim) + self.trainable_last_blocks = 0 + + def unfreeze_last_two(self) -> None: + self.backbone.requires_grad_(False) + for layer in self.backbone.layers[-2:]: + layer.requires_grad_(True) + self.backbone.ln1.requires_grad_(True) + self.trainable_last_blocks = 2 + + def train(self, mode: bool = True): + super().train(mode) + if not self.trainable_last_blocks: + self.backbone.eval() + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + backbone = self.backbone + patches = backbone.patch_embed.projection(images) + rows, cols = patches.shape[-2:] + x = patches.flatten(2).transpose(1, 2) + position = torch.nn.functional.interpolate( + backbone.pos_embed[:, 1:].reshape(1, 16, 12, -1).permute(0, 3, 1, 2), + size=(rows, cols), mode="bicubic", align_corners=False, + ).flatten(2).transpose(1, 2) + with torch.no_grad(): + x = x + position + backbone.pos_embed[:, :1] + for layer in backbone.layers[:-self.trainable_last_blocks or None]: + x = layer(x) + if self.trainable_last_blocks: + for layer in backbone.layers[-self.trainable_last_blocks:]: + x = checkpoint(layer, x, use_reentrant=False) if self.training else layer(x) + x = backbone.ln1(x) + return PatchFeatures(self.projection(x), (rows, cols), 16) + + +def build_model(mean_local: torch.Tensor, *, weights: Path = VISUAL_WEIGHTS) -> BimanualReconstructionModel: + config = ModelConfig( + encoder="vitpose_l", decoder_dim=512, decoder_layers=3, + attention_heads=8, decoder_mode="alternating", + temporal_attention_mode="bidirectional", use_depth=False, use_rays=False, + predict_presence=False, structured_hand_refinement=False, + translation_parameterization="direct_xyz", + joint2d_parameterization="hand_token_linear", mano_root=MANO_ROOT, + require_mano=True, mano_fix_left_shapedirs=True, gradient_checkpointing=True, + ) + model = BimanualReconstructionModel(config, rgb_encoder=TrainableViTPoseEncoder(weights)) + model.decoder = UnifiedRGBDecoder(model.decoder, config.attention_heads) + model.rotation_head = MeanDeltaRotationHead(model.rotation_head, mean_local) + model.mano_layer.requires_grad_(False) + model.joint2d_head.requires_grad_(False) + return model diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/pilot.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/pilot.py new file mode 100644 index 0000000000000000000000000000000000000000..5041244e95fa8604f56bb4b558d11014e77e1a6c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/pilot.py @@ -0,0 +1,303 @@ +"""Real-data DDP throughput pilot; output is not a trained checkpoint.""" + +from __future__ import annotations + +import argparse +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import json +import os +from pathlib import Path +import statistics +import threading +import time +from types import MethodType + +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel +from torch.profiler import ProfilerActivity, profile, record_function +from torch.utils.data import DataLoader +from torch.utils.checkpoint import checkpoint + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base +from experiments.from_scratch_mean_pose.throughput_probe import ( + PROBE_FIELDS, collate_matching_resolutions, collate_probe_samples, + initialize_worker, monitor_gpus, select_clip, +) +from .data import MixedResolutionCoverage, MixedResolutionDataset +from .model import VISUAL_WEIGHTS, build_model +from .train import SOURCES + + +class TimedDataset(MixedResolutionDataset): + def __getitem__(self, spec): + started = time.monotonic() + sample = super().__getitem__(spec) + sample["_pilot_load_seconds"] = time.monotonic() - started + sample["_pilot_worker_threads"] = len(os.listdir("/proc/self/task")) + return sample + + +def single_sample(samples): + sample = samples[0] + return {key: value for key, value in sample.items() + if key in PROBE_FIELDS or key.startswith("_pilot_")} + + +def rgb_only_decoder_forward(self, queries, rgb, depth, frame_valid, depth_available, side_bias): + if depth is not None: + raise ValueError("RGB-only profile cannot receive depth tokens") + batch, time, hands, dim = queries.shape + if frame_valid.shape != (batch, time): + raise ValueError("frame validity does not match query sequence") + flat_rgb = rgb.reshape(batch * time, rgb.shape[2], dim) + hand = queries.reshape(batch * time, hands, dim) + for spatial, temporal in zip(self.spatial, self.temporal): + if self.training and self.gradient_checkpointing: + flat_rgb, hand = checkpoint(spatial, flat_rgb, hand, use_reentrant=False) + else: + flat_rgb, hand = spatial(flat_rgb, hand) + hand = hand.reshape(batch, time, hands, dim) + hand = hand * frame_valid[:, :, None, None].to(hand.dtype) + hand, _ = temporal(hand, frame_valid) + hand = hand.reshape(batch * time, hands, dim) + return hand.reshape(batch, time, hands, dim), {} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--last-two", action="store_true") + parser.add_argument("--no-checkpointing", action="store_true") + parser.add_argument("--no-decoder-checkpointing", action="store_true") + parser.add_argument("--no-encoder-checkpointing", action="store_true") + parser.add_argument("--interop-threads", type=int, default=0) + parser.add_argument("--weights", type=Path, default=VISUAL_WEIGHTS) + parser.add_argument("--workers", type=int, default=2) + parser.add_argument("--prefetch-factor", type=int, default=2) + parser.add_argument("--opencv-threads", type=int, default=1) + parser.add_argument("--pin-memory", action="store_true") + parser.add_argument("--clips-per-rank", type=int, default=10) + parser.add_argument("--microbatch-size", type=int, default=1) + parser.add_argument("--collate-in-worker", action="store_true") + parser.add_argument("--warmup", type=int, default=2) + parser.add_argument("--updates", type=int, default=12) + parser.add_argument("--physical-gpus", type=int, nargs="+", default=None) + parser.add_argument("--reuse-first-batch", action="store_true") + parser.add_argument("--skip-geometry-check", action="store_true") + parser.add_argument("--skip-depth-any-check", action="store_true") + parser.add_argument("--formal-bookkeeping", action="store_true") + parser.add_argument("--profile-output", type=Path) + parser.add_argument("--profile-update", type=int, default=3) + args = parser.parse_args() + if (args.output.exists() or args.workers < 0 or args.prefetch_factor < 1 or args.clips_per_rank < 1 + or args.microbatch_size < 1 or args.warmup < 1 or args.updates <= args.warmup): + raise ValueError("invalid pilot settings or output exists") + if args.collate_in_worker and args.microbatch_size != 1: + raise ValueError("worker-side collate is only available for single-clip microbatches") + if args.profile_output is not None and (args.profile_output.exists() or + args.profile_update <= args.warmup or + args.profile_update > args.updates): + raise ValueError("profile output must be new and profile update must follow warmup") + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if world not in (2, 3, 4, 6): + raise RuntimeError("pilot requires two, three, four or six GPUs") + if args.physical_gpus is not None and len(args.physical_gpus) != world: + raise ValueError("physical GPU list must match the DDP world size") + if args.interop_threads: + torch.set_num_interop_threads(args.interop_threads) + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError("pilot requires 18 GiB free per GPU") + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + fitted = json.loads((BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"]).read_text()) + torch.manual_seed(20261003) + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32), weights=args.weights) + if args.last_two: + model.rgb_encoder.unfreeze_last_two() + if args.skip_depth_any_check: + model.decoder.forward = MethodType(rgb_only_decoder_forward, model.decoder) + model.to(device).train() + if args.no_checkpointing or args.no_decoder_checkpointing: + model.decoder.gradient_checkpointing = False + if args.no_checkpointing or args.no_encoder_checkpointing: + model.rgb_encoder.eval() + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + trainable = [p for p in model.parameters() if p.requires_grad] + optimizer = torch.optim.AdamW(trainable, lr=5e-5, weight_decay=0.05) + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + sampler = base.PositionSampler(MixedResolutionCoverage(), 0, + args.updates * args.clips_per_rank * world, rank, world) + loader = DataLoader(TimedDataset(), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=args.workers > 0, + collate_fn=collate_probe_samples if args.collate_in_worker else single_sample, + pin_memory=args.pin_memory, + prefetch_factor=args.prefetch_factor if args.workers else None, + worker_init_fn=partial(initialize_worker, opencv_threads=args.opencv_threads)) + iterator = iter(loader) + cached_samples = ([next(iterator) for _ in range(args.clips_per_rank)] + if args.reuse_first_batch else None) + rows = [] + gpu_samples = [] + monitor_stop = threading.Event() + monitor = None + for update in range(args.updates): + profiling = rank == 0 and args.profile_output is not None and update + 1 == args.profile_update + profiler = (profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], + record_shapes=False, profile_memory=False, with_stack=True) + if profiling else None) + mark = record_function if profiling else nullcontext + if profiler is not None: + profiler.start() + if update == args.warmup and rank == 0 and args.physical_gpus is not None: + monitor = threading.Thread( + target=monitor_gpus, + args=(monitor_stop, tuple(args.physical_gpus), gpu_samples), + daemon=True, + ) + monitor.start() + torch.cuda.synchronize(device) + start = time.monotonic() + with mark("profile/data_wait"): + samples = (cached_samples if cached_samples is not None else + [next(iterator) for _ in range(args.clips_per_rank)]) + data_ready = time.monotonic() + source_load = {} + with mark("profile/collate"): + if args.collate_in_worker: + cpu_batches = samples + else: + cpu_batches = collate_matching_resolutions(samples, args.microbatch_size) + for sample in samples: + source = sample["sampling_source_id"] + bucket = source_load.setdefault(source, {"clips": 0, "load_seconds": 0.0}) + bucket["clips"] += 1 + bucket["load_seconds"] += sample["_pilot_load_seconds"] + bucket["max_worker_threads"] = max(bucket.get("max_worker_threads", 0), + sample["_pilot_worker_threads"]) + if args.formal_bookkeeping: + with mark("profile/source_quota"): + counts = {source: 0 for source in SOURCES} + for cpu in cpu_batches: + for source in cpu["sampling_source_id"]: + counts[source] += 1 + local_counts = torch.tensor([counts[source] for source in SOURCES], device=device) + dist.all_reduce(local_counts) + local_counts.tolist() + with mark("profile/zero_grad"): + optimizer.zero_grad(set_to_none=True) + term_totals = {name: 0.0 for name in TERMS} if args.formal_bookkeeping else None + for micro, cpu in enumerate(cpu_batches): + count = len(cpu["input_mode"]) + with mark("profile/host_to_device"): + batch = base.move_to_device(cpu, device) + with mark("profile/geometry_check"): + if not args.skip_geometry_check: + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < len(cpu_batches) else nullcontext() + with sync: + with mark("profile/model_forward"): + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + with mark("profile/loss_and_diagnostics"): + results = [objective(select_clip(prediction, index, count), + select_clip(batch, index, count)) + for index in range(count)] + losses = [result[0] for result in results] + loss = torch.stack(losses).sum() / args.clips_per_rank + if not bool(torch.isfinite(loss)): + raise RuntimeError("nonfinite pilot loss") + with mark("profile/backward"): + loss.backward() + if term_totals is not None: + with mark("profile/formal_diagnostics"): + float(loss.detach()) + for _, terms, _ in results: + for name, value in terms.items(): + term_totals[name] += float(value.detach()) / args.clips_per_rank + with mark("profile/grad_clip"): + norm = torch.nn.utils.clip_grad_norm_(trainable, 100) + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite pilot gradient") + with mark("profile/optimizer"): + optimizer.step() + with mark("profile/end_sync"): + torch.cuda.synchronize(device) + if profiler is not None: + profiler.stop() + args.profile_output.parent.mkdir(parents=True, exist_ok=True) + profiler.export_chrome_trace(str(args.profile_output)) + args.profile_output.with_suffix(".txt").write_text( + profiler.key_averages().table(sort_by="self_cpu_time_total", row_limit=40) + + "\nCUDA total:\n" + + profiler.key_averages().table(sort_by="self_cuda_time_total", row_limit=40) + ) + rows.append({"update": update + 1, "seconds": time.monotonic() - start, + "data_wait_seconds": data_ready - start, + "source_load": source_load, + "microbatch_sizes": [len(cpu["input_mode"]) for cpu in cpu_batches], + "loss": float(loss.detach()), "preclip_grad_norm": float(norm), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 1024**3}) + if rank == 0: + print(json.dumps({"last_two": args.last_two, + "no_decoder_checkpointing": not model.decoder.gradient_checkpointing, + "no_encoder_checkpointing": not model.rgb_encoder.training, + **rows[-1]}), flush=True) + monitor_stop.set() + if monitor is not None: + monitor.join(timeout=6) + gathered = [None] * world + dist.all_gather_object(gathered, {"rank": rank, "rows": rows}) + if rank == 0: + slowest = max(statistics.mean(row["seconds"] for row in part["rows"][args.warmup:]) + for part in gathered) + report = {"kind": "gpu_pilot_not_formal_training", "last_two": args.last_two, + "skip_depth_any_check": args.skip_depth_any_check, + "formal_bookkeeping": args.formal_bookkeeping, + "reuse_first_batch": args.reuse_first_batch, + "skip_geometry_check": args.skip_geometry_check, + "no_decoder_checkpointing": not model.decoder.gradient_checkpointing, + "no_encoder_checkpointing": not model.rgb_encoder.training, + "interop_threads": args.interop_threads, + "world_size": world, "clips_per_rank": args.clips_per_rank, + "microbatch_size_max": args.microbatch_size, + "collate_in_worker": args.collate_in_worker, + "pin_memory": args.pin_memory, + "opencv_threads": args.opencv_threads, + "workers_per_rank": args.workers, "updates": args.updates, + "prefetch_factor": args.prefetch_factor, + "warmup": args.warmup, + "seconds_per_update_slowest_rank": slowest, + "clips_per_second": args.clips_per_rank * world / slowest, + "ranks": gathered} + if args.physical_gpus is not None: + report["gpu_utilization"] = { + str(gpu): { + "samples": len(values), + "mean_pct": statistics.mean(values) if values else None, + "fraction_at_least_90pct": ( + sum(value >= 90 for value in values) / len(values) if values else None + ), + } + for gpu in args.physical_gpus + for values in [[sample["utilization_pct"] for sample in gpu_samples if sample["gpu"] == gpu]] + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps({"result": str(args.output), "clips_per_second": report["clips_per_second"]}), flush=True) + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/preflight.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/preflight.py new file mode 100644 index 0000000000000000000000000000000000000000..be32263ca0d0150e09b5ef068a20c954997822a1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/preflight.py @@ -0,0 +1,106 @@ +"""Real-data three-resolution and one-update ViTPose-L/MoT checks.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import time + +import torch + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base +from .data import MixedResolutionCoverage, MixedResolutionDataset, RESOLUTIONS +from .model import build_model, verify_visual_weights + + +def reprojection_error(batch): + joints = batch["joint3d_camera"].float() + k = batch["K"].float() + xy = joints[..., :2] / joints[..., 2:].clamp_min(0.05) + projected = torch.einsum("btij,bthkj->bthki", k[..., :2, :2], xy) + k[..., :2, 2][:, :, None, None] + valid = batch["joint2d_valid"].bool() & batch["joint3d_valid"].bool() & (joints[..., 2] > 0.05) + error = torch.linalg.vector_norm(projected - batch["joint2d"].float(), dim=-1) + return {"valid_joints": int(valid.sum()), + "mean_px": float(error[valid].mean()) if bool(valid.any()) else None, + "p95_px": float(torch.quantile(error[valid], 0.95)) if bool(valid.any()) else None} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), default="H2O") + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--last-two", action="store_true") + parser.add_argument("--geometry-only", action="store_true") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + verify_visual_weights() + fitted = json.loads((BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"]).read_text()) + coverage, dataset = MixedResolutionCoverage(), MixedResolutionDataset() + spec = next(coverage.sample(position) for position in range(600) + if coverage.sample(position)["source"] == args.source) + rows = [] + for hw in RESOLUTIONS: + item = dict(spec, target_hw=hw) + cpu = base.collate_h2o_clips([dataset[item]]) + if cpu["input_mode"] != ["rgb"] or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("RGB-only model input violated") + if tuple(cpu["rgb"].shape) != (1, 8, 3, *hw): + raise RuntimeError("mixed-resolution sample shape violated") + rows.append({"target_hw": hw, "image_hw": cpu["image_hw"].tolist(), + "K": cpu["K"][0, 0].tolist(), "reprojection": reprojection_error(cpu), + "valid_pose_frames": int(cpu["local_pose_valid"].sum()), + "valid_geometry_frames": int(cpu["vertices_valid"].sum())}) + report = {"source": args.source, "tile_id": spec["tile_id"], "three_resolutions": rows, + "visual_weights_verified": True, "last_two": args.last_two} + if not args.geometry_only: + device = torch.device(args.device) + torch.cuda.set_device(device) + free, _ = torch.cuda.mem_get_info(device) + if free < 18 * 1024**3: + raise RuntimeError("pilot GPU has less than 18 GiB free") + torch.manual_seed(20261003) + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if args.last_two: + model.rgb_encoder.unfreeze_last_two() + model.to(device).train() + criterion = FromScratchLoss(fitted, {key: BASE_CONFIG["shared"]["loss"][key] for key in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + trainable = [p for p in model.parameters() if p.requires_grad] + cpu = base.collate_h2o_clips([dataset[dict(spec, target_hw=RESOLUTIONS[0])]]) + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, model) + torch.cuda.reset_peak_memory_stats(device) + start = time.monotonic() + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + forward_seconds = time.monotonic() - start + loss, terms, diagnostics = criterion(prediction, batch) + if not bool(torch.isfinite(loss)) or diagnostics["gt_rotation_orthogonality_max"] > 1e-5: + raise RuntimeError("nonfinite or nonorthogonal 6D target") + loss.backward() + norm = torch.nn.utils.clip_grad_norm_(trainable, 100) + torch.cuda.synchronize(device) + report["forward_backward"] = { + "seconds": time.monotonic() - start, "forward_seconds": forward_seconds, + "loss": float(loss.detach()), "weighted_terms": {k: float(v.detach()) for k, v in terms.items()}, + "diagnostics": diagnostics, "preclip_grad_norm": float(norm), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 1024**3, + "trainable_parameters": sum(p.numel() for p in trainable), + "backbone_trainable_parameters": sum(p.numel() for p in model.rgb_encoder.backbone.parameters() if p.requires_grad), + } + if not bool(torch.isfinite(norm)): + raise RuntimeError("nonfinite ViTPose-L pilot gradient") + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") + print(json.dumps(report, allow_nan=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/train.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/train.py new file mode 100644 index 0000000000000000000000000000000000000000..149984fcf52f579c690ec27d626e176b50c3593f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_io_v4/train.py @@ -0,0 +1,347 @@ +"""Six-rank, teacher-free RGB ViTPose-L/MoT training with full resume state.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from contextlib import nullcontext +from datetime import timedelta +from functools import partial +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +import foundation_hand.geometry.rotations as rotations +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.fit_targets import mano_pkl_mean +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import CONFIG as BASE_CONFIG, ROOT as BASE_ROOT, a7, base, sha +from experiments.from_scratch_mean_pose.throughput_probe import ( + PROBE_FIELDS, collate_matching_resolutions, initialize_worker, select_clip, +) +from .data import MixedResolutionCoverage, MixedResolutionDataset, RESOLUTION_PCT +from .model import MANO_ROOT, VISUAL_SHA256, VISUAL_WEIGHTS, build_model, verify_visual_weights + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +SOURCES = ("H2O", "ARCTIC", "HOT3D") +STATS = BASE_ROOT / BASE_CONFIG["shared"]["normalization"]["statistics_asset"] +INDEX = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite") +LABELS = Path("/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json") + + +def code_hashes(): + files = [ROOT / "train.py", ROOT / "model.py", ROOT / "data.py", + ROOT / "hot3d_hand_only.py", ROOT / "config.json", + BASE_ROOT / "config.json", BASE_ROOT / "loss.py", BASE_ROOT / "model.py", BASE_ROOT / "fit_targets.py", + BASE_ROOT / "throughput_probe.py", + BASE_ROOT / "statistics_mano_pkl_v2.json", + ROOT.parent / "dinov3_2d_pretrain/vitpose_probe.py", + ROOT.parent / "u0_depthsafe/model.py", + ROOT.parent / "u0_depthsafe/reprojection.py", + ROOT.parent / "u0_normalized6d/normalized_loss.py", + ROOT.parent / "a7_rotation_fix/filtered_dataset.py", + ROOT.parent.parent / "src/foundation_hand/models/bimanual.py", + ROOT.parent.parent / "src/foundation_hand/models/decoder.py", + ROOT.parent.parent / "src/foundation_hand/models/encoders.py", + ROOT.parent.parent / "src/foundation_hand/models/mano.py", + ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py", + ROOT.parent.parent / "src/foundation_hand/data/schema.py", + ROOT.parent.parent / "src/foundation_hand/data/h2o_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/arctic_dataset.py", + ROOT.parent.parent / "src/foundation_hand/data/hot3d_dataset.py"] + return {str(path.relative_to(ROOT.parent.parent)): sha(path) for path in files} + + +def verify_contract(fitted): + expected_rotations = ROOT.parent.parent / "src/foundation_hand/geometry/rotations.py" + if Path(rotations.__file__).resolve() != expected_rotations.resolve(): + raise RuntimeError(f"wrong rotation implementation loaded: {rotations.__file__}") + verify_visual_weights() + if BASE_CONFIG["shared"]["teacher"] != { + "create_model": False, "forward": False, "distillation": False, "rgb_teacher_weight": 0.0, + } or not CONFIG["prohibit_teacher"] or not CONFIG["prohibit_old_model_checkpoint"]: + raise RuntimeError("teacher/parent checkpoint prohibited") + if BASE_CONFIG["shared"]["loss"]["joint2d"] != 0 or BASE_CONFIG["shared"]["loss"]["reprojection"] != 1: + raise RuntimeError("2D supervision must be MANO reprojection only") + if fitted["training_index_sha256"] != sha(INDEX) or fitted["label_inventory_sha256"] != sha(LABELS): + raise RuntimeError("train-only fitted statistics do not match current data") + if fitted["source_quota"] != CONFIG["source_quota_per_update"]: + raise RuntimeError("fitted statistic source mixture differs") + if fitted["version"] != "b0_b1_mano_pkl_mean_delta_v2": + raise RuntimeError("expected official MANO-pkl mean and normalized delta statistics") + mean, hashes = mano_pkl_mean(Path(MANO_ROOT)) + if hashes != fitted["mano_pkl_sha256"] or not torch.allclose( + torch.as_tensor(mean, dtype=torch.float64), + torch.as_tensor(fitted["mean_local"], dtype=torch.float64), atol=1e-7, rtol=0, + ): + raise RuntimeError("official MANO mean/asset mismatch") + if sha(VISUAL_WEIGHTS) != VISUAL_SHA256 or RESOLUTION_PCT != { + key: tuple(value) for key, value in CONFIG["resolution_pct_by_source"].items() + }: + raise RuntimeError("visual asset or mixed resolution contract changed") + if sum(CONFIG["source_quota_per_update"].values()) != CONFIG["global_batch"]: + raise RuntimeError("source quotas do not fill global batch") + if CONFIG["io"] != {"hot3d_provider": "hand_only", "prefetch_factor": 16, + "group_max_clips": 10}: + raise RuntimeError("grouped IO protocol changed") + return {"code_sha256": code_hashes(), "index_sha256": sha(INDEX), + "labels_sha256": sha(LABELS), "statistics_sha256": sha(STATS), + "visual_sha256": VISUAL_SHA256, "mano_pkl_sha256": hashes} + + +def rng_state(): + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state()} + + +def restore_rng(state): + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"]) + torch.cuda.set_rng_state(state["cuda"]) + + +def single_training_sample(samples): + if len(samples) != 1: + raise RuntimeError("loader must return one clip at a time") + sample = samples[0] + missing = PROBE_FIELDS - sample.keys() + if missing: + raise RuntimeError(f"training clip is missing fields: {sorted(missing)}") + return {key: sample[key] for key in PROBE_FIELDS} + + +def schedule(update): + settings = CONFIG["optimizer"] + endpoint = settings["initial_endpoint_updates"] + warmup = settings["warmup_updates"] + floor = settings["minimum_lr_ratio"] + fraction = min(1.0, max(0.0, (update - warmup) / (endpoint - warmup))) + factor = max(1 / warmup, (update + 1) / warmup) if update < warmup else ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * fraction))) + visual_stage = update - settings["freeze_visual_updates"] + visual = 0.0 if visual_stage < 0 else settings["visual_last2_lr_peak"] * min( + 1.0, (visual_stage + 1) / settings["visual_warmup_updates"]) * ( + floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * max(0.0, min( + 1.0, (visual_stage - settings["visual_warmup_updates"]) / + (endpoint - settings["freeze_visual_updates"] - settings["visual_warmup_updates"])))))) + return settings["new_lr_peak"] * factor, visual + + +def save_checkpoint(path, model, optimizer, update, provenance, rng_states, exposure, smoke, world): + if path.exists(): + raise FileExistsError(path) + state = {"experiment": CONFIG["experiment"], "model": model.state_dict(), + "optimizer": optimizer.state_dict(), "update": update, + "next_sample_position": update * CONFIG["global_batch"], + "world_size": world, "global_batch": CONFIG["global_batch"], + "source_exposure": dict(exposure), "rank_rng_states": rng_states, + "provenance": provenance, "config": CONFIG, "complete_backbone": True, + "teacher_used": False, "parent_checkpoint": None, "smoke": smoke} + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + loaded = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("full checkpoint load-back failed") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, default=120000) + parser.add_argument("--resume", type=Path) + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--log-every", type=int, default=25) + args = parser.parse_args() + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if (world != 6 and not (args.smoke and world == 2)) or args.updates < 1 or args.updates > CONFIG["optimizer"]["initial_endpoint_updates"]: + raise RuntimeError("formal contract requires six GPUs; two are permitted only for smoke") + if (args.smoke and args.updates > 2) or (not args.smoke and args.updates < 5000): + raise RuntimeError("smoke is at most two updates; formal stage must reach first 5K gate") + if args.workers < 1 or args.log_every < 1: + raise ValueError("workers/log interval must be positive") + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError(f"rank {rank}: less than 18 GiB free") + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=20), device_id=device) + try: + if rank == 0: + args.output.parent.mkdir(parents=True, exist_ok=True) + dist.barrier(device_ids=[local]) + if shutil.disk_usage(args.output.parent).free < 100 * 1024**3: + raise RuntimeError("less than 100 GiB free for complete checkpoints") + fitted = json.loads(STATS.read_text()) + provenance = verify_contract(fitted) + seed = BASE_CONFIG["shared"]["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + state = None + start = 0 + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["world_size"] != world + or state["global_batch"] != CONFIG["global_batch"] + or state["config"] != CONFIG or state["provenance"] != provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] is not None or state["smoke"] != args.smoke): + raise RuntimeError("resume checkpoint contract mismatch") + start = state["update"] + if state["next_sample_position"] != start * CONFIG["global_batch"] or start >= args.updates: + raise RuntimeError("resume cursor or endpoint mismatch") + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32)) + if start >= CONFIG["optimizer"]["freeze_visual_updates"]: + model.rgb_encoder.unfreeze_last_two() + model.to(device).train() + new = [p for name, p in model.named_parameters() + if not name.startswith("rgb_encoder.backbone.") and p.requires_grad] + visual = [p for name, p in model.named_parameters() + if name.startswith("rgb_encoder.backbone.layers.22.") + or name.startswith("rgb_encoder.backbone.layers.23.") + or name.startswith("rgb_encoder.backbone.ln1.")] + if not new or not visual or any(p.requires_grad for p in model.rgb_encoder.backbone.layers[:22].parameters()): + raise RuntimeError("optimizer parameter partition invalid") + optimizer = torch.optim.AdamW([ + {"params": new, "name": "new", "lr": schedule(start)[0]}, + {"params": visual, "name": "visual_last_two", "lr": schedule(start)[1]}, + ], weight_decay=CONFIG["optimizer"]["weight_decay"]) + exposure = Counter() + if state: + model.load_state_dict(state["model"], strict=True) + optimizer.load_state_dict(state["optimizer"]) + exposure.update(state["source_exposure"]) + restore_rng(state["rank_rng_states"][rank]) + del state + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh training would overwrite old metrics") + (args.output / "provenance.json").write_text(json.dumps({ + "experiment": CONFIG["experiment"], "contract": provenance, + "loss_coefficients": BASE_CONFIG["shared"]["loss"], + "optimizer": CONFIG["optimizer"], "io": CONFIG["io"], + "workers_per_rank": args.workers, + "resume": str(args.resume) if args.resume else None, "smoke": args.smoke, + }, indent=2) + "\n") + dist.barrier(device_ids=[local]) + sampler = base.PositionSampler(MixedResolutionCoverage(), + start * CONFIG["global_batch"], + args.updates * CONFIG["global_batch"], rank, world) + loader = DataLoader(MixedResolutionDataset(), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=True, + collate_fn=single_training_sample, pin_memory=True, prefetch_factor=16, + worker_init_fn=partial(initialize_worker, opencv_threads=1), + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] for name in TERMS}, + BASE_CONFIG["shared"]["smoke"]).to(device) + clips_per_rank = CONFIG["global_batch"] // world + for update in range(start, args.updates): + if update == CONFIG["optimizer"]["freeze_visual_updates"]: + dist.barrier(device_ids=[local]) + del ddp + model.rgb_encoder.unfreeze_last_two() + ddp = DistributedDataParallel(model, device_ids=[local], broadcast_buffers=False, + find_unused_parameters=False) + lr_new, lr_visual = schedule(update) + optimizer.param_groups[0]["lr"] = lr_new + optimizer.param_groups[1]["lr"] = lr_visual + started = time.monotonic() + cpu_batches = collate_matching_resolutions( + [next(iterator) for _ in range(clips_per_rank)], CONFIG["io"]["group_max_clips"]) + data_ready = time.monotonic() + if sum(len(cpu["input_mode"]) for cpu in cpu_batches) != clips_per_rank: + raise RuntimeError("grouping changed the per-rank clip count") + counts = Counter(source for cpu in cpu_batches for source in cpu["sampling_source_id"]) + local_counts = torch.tensor([counts[source] for source in SOURCES], device=device) + dist.all_reduce(local_counts) + if local_counts.tolist() != [CONFIG["source_quota_per_update"][source] for source in SOURCES]: + raise RuntimeError("source quota per update changed") + optimizer.zero_grad(set_to_none=True) + total_loss = 0.0 + term_totals = {key: 0.0 for key in TERMS} + nonpositive = 0 + valid_pose = 0 + for micro, cpu in enumerate(cpu_batches): + count = len(cpu["input_mode"]) + if cpu["input_mode"] != ["rgb"] * count or bool(cpu["K_input_available"].any()) or bool(cpu["depth_input_available"].any()): + raise RuntimeError("non-RGB input reached ViTPose-L") + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, model) + sync = ddp.no_sync() if micro + 1 < len(cpu_batches) else nullcontext() + with sync: + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = ddp(batch) + results = [objective(select_clip(prediction, index, count), + select_clip(batch, index, count)) + for index in range(count)] + loss = torch.stack([result[0] for result in results]).sum() + if not bool(torch.isfinite(loss)) or any( + result[2]["gt_rotation_orthogonality_max"] > 1e-5 for result in results + ): + raise RuntimeError(f"nonfinite loss or invalid GT at update {update + 1}") + (loss / clips_per_rank).backward() + for clip_loss, terms, diagnostics in results: + total_loss += float(clip_loss.detach()) / clips_per_rank + for name, value in terms.items(): + term_totals[name] += float(value.detach()) / clips_per_rank + nonpositive += diagnostics["nonpositive_reprojection_joints"] + valid_pose += diagnostics["valid_local_frames"] + trainable = [p for p in model.parameters() if p.requires_grad] + norm = torch.nn.utils.clip_grad_norm_(trainable, CONFIG["optimizer"]["clip_grad_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"nonfinite gradient at update {update + 1}") + optimizer.step() + elapsed = time.monotonic() - started + for source, count in zip(SOURCES, local_counts.tolist()): + exposure[source] += count + if rank == 0 and ((update + 1) % args.log_every == 0 or update < 10): + row = {"update": update + 1, "consumed_clips": (update + 1) * CONFIG["global_batch"], + "seconds": elapsed, "data_wait_seconds": data_ready - started, + "loss_rank0": total_loss, "terms_rank0": term_totals, + "preclip_grad_norm_rank0": float(norm), "nonpositive_rank0": nonpositive, + "valid_local_pose_frames_rank0": valid_pose, + "learning_rate_new": lr_new, "learning_rate_visual": lr_visual, + "exposure": dict(exposure)} + log.write(json.dumps(row, allow_nan=False) + "\n") + print(json.dumps(row, allow_nan=False), flush=True) + if update + 1 in CONFIG["evaluation_updates"] or update + 1 == args.updates: + gathered = [None] * world + dist.all_gather_object(gathered, rng_state()) + if rank == 0: + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", model, + optimizer, update + 1, provenance, gathered, exposure, args.smoke, world) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/README.md b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c9b527f84bd8ecba7e4cf66e55d531e9758a03f5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/README.md @@ -0,0 +1,52 @@ +# RGB 40K -> joint K/depth MoT continuation + +The G2 RGB-only run was stopped at approximately 62.5K updates on 2026-10-09. +This is a **new** six-GPU run initialized from its untouched original 40K +checkpoint. The new update numbers count additional optimizer steps after RGB +40K, not cumulative steps. The RGB 40K and 60K checkpoints remain preserved. + +## Data and inputs + +- Same train-only canonical GT, T=8 tiles, source quota 21 H2O / 15 ARCTIC / + 24 HOT3D and source-specific mixed resolutions as RGB v4. +- Reuse the registered S4 source-local K/drop mode sampler. RGB-only and RGB+K + appear on all three sources; RGB+K+metric depth appears only on H2O. +- K and depth are model inputs only when their input-availability flags are true. + K may still be present as projection supervision when omitted from input. +- Same normalized camera-space GT, official MANO-pkl local mean-pose deltas, + FP32-orthogonalized 6D pose supervision, and unchanged loss coefficients. + Direct joint-2D loss remains off; MANO reprojection remains on. No teacher. + +## Model and optimizer + +The three RGB/HAND MoT spatial blocks and full ViTPose-L RGB 40K weights are +loaded exactly. New K-bearing and metric-depth type experts are initialized +from corresponding RGB experts. No-input RGB uses the original RGB/HAND path. +The geometric tokens use the rectified image's aligned pinhole K; this run does +not establish raw fisheye support. + +| Additional updates | Trainable parameters | Peak LR | +| --- | --- | --- | +| 0-5K | K/depth encoders, experts, gates | 1e-4 / 5e-5 / 1e-3 | +| 5K-10K | above + RGB/HAND spatial, temporal, shared heads | shared 1e-5 | +| 10K-40K | above + ViTPose-L last two blocks/final norm | visual 2e-7 | + +Each newly opened group ramps for 1K updates; all groups cosine-decay to 10% +of peak by 40K. AdamW weight decay is 0.05; global gradient norm clips at +100. The model trains with BF16 forward and FP32 geometric supervision. Grouped +microbatches retain all 60 clips per update across six ranks; the batch mixes +input modes and logs source/mode exposure. This is joint multimodal training, +not the earlier single-GPU frozen-parent 2K pilot. + +## Checkpoints and interpretation + +Complete checkpoints with model, optimizer, per-rank RNG, provenance, source +exposure, and mode exposure are written at additional updates 5K, 10K, 15K, +20K, 25K, 30K, 35K, and 40K. The run has no automatic evaluation pause; +future evaluations must compare RGB, RGB+K, and RGB+K+depth with matched +source-native held-out panels and preserve the exact parent comparison. + +The pre-existing 2K frozen-parent geometry pilot improved H2O slightly but +regressed ARCTIC with K and gave mixed HOT3D results. Longer joint training is +an experiment, not a guaranteed improvement. In particular, H2O is the only +source with metric depth here, so depth-domain transfer remains untested. diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/__init__.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..45eaf7c781e0e0159afa598806636bd64bd35d08 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/__init__.py @@ -0,0 +1,5 @@ +"""Joint RGB/K/depth MoT continuation from the audited RGB 40K checkpoint.""" + +# The RGB package pins the canonical EgoNet foundation_hand source before +# legacy data helpers can import a different installed copy. +from experiments import vitpose_mot_io_v4 as _rgb_source_contract # noqa: F401 diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/config.json b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7966859d514ff0aa12164c001fda7e30e0034684 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/config.json @@ -0,0 +1,32 @@ +{ + "experiment": "vitpose_l_mot_rgb40k_joint_k_depth_20261009", + "rgb_parent_update": 40000, + "rgb_parent_sha256": "ee3c4e9b9f4a10005684ea8544ba2e89fa5edd32d27fef1c76d01f580a7b9a11", + "updates": 40000, + "checkpoint_updates": [5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000], + "world_size": 6, + "global_batch": 60, + "source_quota_per_update": {"H2O": 21, "ARCTIC": 15, "HOT3D": 24}, + "input_modes": ["rgb", "rgb_k", "rgb_depth_k"], + "sampling": "registered S4 source-local K/drop mode sampler; depth only on H2O", + "resolution_protocol": "vitpose_mot_io_v4 source-specific mixed resolution", + "joint_start_update": 5000, + "visual_start_update": 10000, + "warmup_updates": 1000, + "stage_warmup_updates": 1000, + "minimum_lr_ratio": 0.1, + "learning_rates_peak": { + "bearing_encoder": 0.0001, + "depth_encoder": 0.0001, + "geometry_experts": 0.00005, + "geometry_gates": 0.001, + "shared": 0.00001, + "visual_last_two": 0.0000002 + }, + "weight_decay": 0.05, + "clip_grad_norm": 100, + "group_max_clips": 2, + "prefetch_factor": 8, + "teacher": false, + "loss": "unchanged from from_scratch_mean_pose/config.json; MANO 2D reprojection only" +} diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/data.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/data.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ad797b49ef109264b7b799565135df10139264 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/data.py @@ -0,0 +1,62 @@ +"""Registered three-source coverage with RGB, K, and H2O metric-depth modes.""" + +from __future__ import annotations + +from collections import defaultdict + +from experiments.a7_rotation_fix.coverage_sampler import CoverageSampler +from experiments.from_scratch_mean_pose.smoke import base +from experiments.from_scratch_mean_pose.throughput_probe import PROBE_FIELDS +from experiments.vitpose_mot_geometry_incremental.data import GeometryDataset +from experiments.vitpose_mot_io_v4.data import MixedResolutionCoverage, MixedResolutionDataset, resolution_for + + +FIELDS = PROBE_FIELDS | {"depth_m", "depth_pixel_valid"} + + +class MultimodalCoverage(MixedResolutionCoverage): + def sample(self, position: int) -> dict: + # CoverageSampler retains the established K-drop and H2O depth-drop rates. + spec = CoverageSampler.sample(self, position) + spec["target_hw"] = (None if spec["source"] == "HOT3D" else + resolution_for(spec["source"], None, position)) + return spec + + +class MultimodalDataset(GeometryDataset): + def __getitem__(self, spec: dict) -> dict: + if spec["mode"] == "rgb": + sample = MixedResolutionDataset.__getitem__(self, spec) + else: + sample = super().__getitem__(spec) + if set(FIELDS) - sample.keys(): + raise RuntimeError(f"missing multimodal sample fields: {sorted(set(FIELDS) - sample.keys())}") + frame = sample["frame_valid"].bool() + expected_k = frame if spec["mode"] != "rgb" else frame & False + expected_depth = frame if spec["mode"] == "rgb_depth_k" else frame & False + if (sample["input_mode"] != spec["mode"] + or not sample["K_input_available"].equal(expected_k) + or not sample["depth_input_available"].equal(expected_depth) + or (spec["mode"] == "rgb_depth_k" and spec["source"] != "H2O")): + raise RuntimeError("sample modality contract differs from registered coverage") + return sample + + +def one_sample(samples: list[dict]) -> dict: + if len(samples) != 1: + raise RuntimeError("reader must return exactly one clip") + sample = samples[0] + missing = FIELDS - sample.keys() + if missing: + raise RuntimeError(f"missing multimodal fields: {sorted(missing)}") + return {key: sample[key] for key in FIELDS} + + +def collate_grouped(samples: list[dict], maximum: int) -> list[dict]: + if maximum < 1: + raise ValueError("maximum must be positive") + groups = defaultdict(list) + for sample in samples: + groups[tuple(sample["rgb"].shape[-2:])].append(sample) + return [base.collate_h2o_clips(group[start:start + maximum]) + for group in groups.values() for start in range(0, len(group), maximum)] diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/test_contract.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..a6bf1fa52062e47353826852e76339beb70e2675 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/test_contract.py @@ -0,0 +1,33 @@ +"""Cheap checks for source/input quotas, trainability, and checkpoint schedule.""" + +from collections import Counter +import unittest + +from .data import MultimodalCoverage +from .train import CONFIG, group_name + + +class MultimodalContractTest(unittest.TestCase): + def test_source_quota_and_depth_origin(self): + coverage = MultimodalCoverage() + for start in (0, 60, 600): + rows = [coverage.sample(position) for position in range(start, start + 60)] + self.assertEqual(dict(Counter(row["source"] for row in rows)), + CONFIG["source_quota_per_update"]) + self.assertEqual({row["mode"] for row in rows}, set(CONFIG["input_modes"])) + self.assertTrue(all(row["source"] == "H2O" for row in rows + if row["mode"] == "rgb_depth_k")) + + def test_no_unidentifiable_terminal_paths(self): + self.assertEqual(group_name("decoder.spatial.0.k.q.weight"), "geometry_experts") + self.assertIsNone(group_name("decoder.spatial.2.k.q.weight")) + self.assertIsNone(group_name("decoder.spatial.2.depth.ffn_out.bias")) + self.assertIsNone(group_name("decoder.spatial.2.rgb.o.weight")) + self.assertEqual(group_name("decoder.temporal.0.attn.in_proj_weight"), "shared") + + def test_checkpoint_schedule(self): + self.assertEqual(CONFIG["checkpoint_updates"], list(range(5000, 40001, 5000))) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/train.py b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/train.py new file mode 100644 index 0000000000000000000000000000000000000000..c80bb881b911b461d3a79ba7f7ddade56b63975e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/experiments/vitpose_mot_multimodal_40k/train.py @@ -0,0 +1,384 @@ +"""Six-GPU mixed RGB/K/depth MoT continuation from the audited RGB 40K.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from datetime import timedelta +from functools import partial +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import time + +import numpy as np +import torch +import torch.distributed as dist +from torch.utils.data import DataLoader + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.smoke import a7, base +from experiments.from_scratch_mean_pose.throughput_probe import initialize_worker, select_clip +from experiments.vitpose_mot_geometry_incremental.model import build_model +from experiments.vitpose_mot_io_v4.train import ( + BASE_CONFIG, CONFIG as RGB_CONFIG, STATS, restore_rng, rng_state, sha, + verify_contract, +) +from .data import MultimodalCoverage, MultimodalDataset, collate_grouped, one_sample + + +ROOT = Path(__file__).resolve().parent +CONFIG = json.loads((ROOT / "config.json").read_text()) +PARENT = Path( + "/home/wuyifan/artifacts/vitpose_mot_g2_continuous_20261008/" + "formal_run/update_0040000.pt" +) +SOURCES = ("H2O", "ARCTIC", "HOT3D") +MODES = ("rgb", "rgb_k", "rgb_depth_k") +DEAD_TERMINAL = ("q.", "o.", "ffn_norm.", "ffn_in.", "ffn_out.") + + +def own_code_hashes() -> dict[str, str]: + paths = [ROOT / name for name in ("__init__.py", "config.json", "data.py", "train.py")] + paths += [ROOT.parent / "vitpose_mot_geometry_incremental" / name + for name in ("data.py", "model.py")] + return {str(path.relative_to(ROOT.parent.parent)): sha(path) for path in paths} + + +def verify_parent(path: Path, expected_provenance: dict, rank: int) -> dict: + if rank == 0 and sha(path) != CONFIG["rgb_parent_sha256"]: + raise RuntimeError("RGB 40K checkpoint SHA-256 mismatch") + state = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != RGB_CONFIG["experiment"] + or state["update"] != CONFIG["rgb_parent_update"] + or state["provenance"] != expected_provenance + or not state["complete_backbone"] or state["teacher_used"] + or state["parent_checkpoint"] is not None or state["smoke"]): + raise RuntimeError("RGB parent is not the audited complete teacher-free 40K") + return state + + +def group_name(name: str) -> str | None: + if name.startswith("mano_layer.") or name.startswith("joint2d_head."): + return None + if name.startswith("rgb_encoder.backbone."): + if name.startswith(("rgb_encoder.backbone.layers.22.", + "rgb_encoder.backbone.layers.23.", + "rgb_encoder.backbone.ln1.")): + return "visual_last_two" + return None + if name.startswith("decoder.bearing_encoder."): + return "bearing_encoder" + if name.startswith("depth_encoder."): + return "depth_encoder" + if name.endswith(("k_gate_logit", "depth_gate_logit")): + return "geometry_gates" + parts = name.split(".") + if len(parts) >= 4 and parts[:2] == ["decoder", "spatial"]: + if parts[3] in ("k", "depth"): + if parts[2] == "2" and any(".".join(parts[4:]).startswith(prefix) + for prefix in DEAD_TERMINAL): + return None + return "geometry_experts" + if parts[2] == "2" and parts[3] == "rgb" and any( + ".".join(parts[4:]).startswith(prefix) for prefix in DEAD_TERMINAL): + return None + return "shared" + + +def configure_stage(model, update: int) -> str: + joint = update >= CONFIG["joint_start_update"] + visual = update >= CONFIG["visual_start_update"] + if visual: + model.rgb_encoder.unfreeze_last_two() + for name, parameter in model.named_parameters(): + group = group_name(name) + parameter.requires_grad_(group in { + "bearing_encoder", "depth_encoder", "geometry_experts", "geometry_gates" + } or (joint and group == "shared") or (visual and group == "visual_last_two")) + return "visual_joint" if visual else "joint" if joint else "geometry_only" + + +def optimizer_for(model): + groups = {name: [] for name in CONFIG["learning_rates_peak"]} + for name, parameter in model.named_parameters(): + group = group_name(name) + if group is not None: + groups[group].append(parameter) + if not all(groups.values()) or len({id(p) for values in groups.values() for p in values}) != sum( + map(len, groups.values())): + raise RuntimeError("optimizer group partition invalid") + optimizer = torch.optim.AdamW([ + {"name": name, "params": parameters, "lr": 0.0, + "peak_lr": CONFIG["learning_rates_peak"][name]} + for name, parameters in groups.items() + ], weight_decay=CONFIG["weight_decay"]) + return optimizer + + +def learning_rates(optimizer, update: int) -> dict[str, float]: + endpoint = CONFIG["updates"] + floor = CONFIG["minimum_lr_ratio"] + rates = {} + for group in optimizer.param_groups: + name = group["name"] + start = (CONFIG["visual_start_update"] if name == "visual_last_two" else + CONFIG["joint_start_update"] if name == "shared" else 0) + if update < start: + factor = 0.0 + else: + warm = CONFIG["stage_warmup_updates"] if start else CONFIG["warmup_updates"] + ramp = min(1.0, (update - start + 1) / warm) + fraction = max(0.0, min(1.0, (update - start - warm) / (endpoint - start - warm))) + factor = ramp * (floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * fraction))) + group["lr"] = group["peak_lr"] * factor + rates[name] = group["lr"] + return rates + + +def synchronize_gradients(model, world: int) -> list[torch.nn.Parameter]: + """Average conditional-branch gradients, including ranks without that branch.""" + parameters = [parameter for parameter in model.parameters() if parameter.requires_grad] + device = parameters[0].device + present = torch.tensor([parameter.grad is not None for parameter in parameters], + dtype=torch.uint8, device=device) + dist.all_reduce(present, op=dist.ReduceOp.MAX) + flattened = torch.cat([ + (parameter.grad if parameter.grad is not None else torch.zeros_like(parameter)) + .reshape(-1) for parameter in parameters + ]) + dist.all_reduce(flattened, op=dist.ReduceOp.SUM) + flattened.div_(world) + offset = 0 + for active, parameter in zip(present.tolist(), parameters): + length = parameter.numel() + parameter.grad = (flattened[offset:offset + length].view_as(parameter).clone() + if active else None) + offset += length + return parameters + + +def save_checkpoint(path: Path, model, optimizer, update: int, batch_size: int, + provenance: dict, rng_states: list, source_exposure: Counter, + mode_exposure: Counter, smoke: bool) -> None: + if path.exists(): + raise FileExistsError(path) + state = { + "experiment": CONFIG["experiment"], "update": update, + "parent_rgb_update": CONFIG["rgb_parent_update"], + "parent_rgb_sha256": CONFIG["rgb_parent_sha256"], + "complete_backbone": True, "teacher_used": False, + "model": model.state_dict(), "optimizer": optimizer.state_dict(), + "rank_rng_states": rng_states, "next_sample_position": update * batch_size, + "global_batch": batch_size, "world_size": dist.get_world_size(), + "source_exposure": dict(source_exposure), "mode_exposure": dict(mode_exposure), + "provenance": provenance, "config": CONFIG, "smoke": smoke, + } + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + os.replace(temporary, path) + loaded = torch.load(path, map_location="cpu", weights_only=False, mmap=True) + if (loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()) + or loaded["next_sample_position"] != update * batch_size): + raise RuntimeError("checkpoint load-back failed") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--updates", type=int, default=CONFIG["updates"]) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--log-every", type=int, default=25) + parser.add_argument("--smoke", action="store_true") + parser.add_argument("--smoke-stage", choices=("geometry_only", "joint", "visual_joint"), + default="geometry_only") + args = parser.parse_args() + rank, world, local = (int(os.environ[key]) for key in ("RANK", "WORLD_SIZE", "LOCAL_RANK")) + if (world != (2 if args.smoke else CONFIG["world_size"]) + or args.updates < 1 or args.updates > (2 if args.smoke else CONFIG["updates"]) + or args.workers < 1 or args.log_every < 1 + or (not args.smoke and args.smoke_stage != "geometry_only")): + raise ValueError("invalid distributed training contract") + batch_size = 12 if args.smoke else CONFIG["global_batch"] + if batch_size % world: + raise RuntimeError("global batch must divide world size") + torch.cuda.set_device(local) + device = torch.device("cuda", local) + if torch.cuda.mem_get_info(device)[0] < 18 * 1024**3: + raise RuntimeError(f"rank {rank}: less than 18 GiB free") + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + dist.init_process_group("nccl", timeout=timedelta(minutes=20), device_id=device) + try: + fitted = json.loads(STATS.read_text()) + base_provenance = verify_contract(fitted) + if (CONFIG["source_quota_per_update"] != RGB_CONFIG["source_quota_per_update"] + or BASE_CONFIG["shared"]["loss"]["joint2d"] != 0 + or BASE_CONFIG["shared"]["loss"]["reprojection"] != 1): + raise RuntimeError("source mix or loss changed from RGB parent") + parent = verify_parent(PARENT, base_provenance, rank) + provenance = {"rgb_provenance": base_provenance, "own_code_sha256": own_code_hashes(), + "statistics_sha256": sha(STATS), "parent_sha256": CONFIG["rgb_parent_sha256"]} + seed = BASE_CONFIG["shared"]["seed"] + rank + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + model = build_model(torch.tensor(fitted["mean_local"], dtype=torch.float32), parent["model"]) + del parent + start = 0 + state = None + if args.resume: + state = torch.load(args.resume, map_location="cpu", weights_only=False, mmap=True) + if (state["experiment"] != CONFIG["experiment"] or state["config"] != CONFIG + or state["provenance"] != provenance or state["smoke"] != args.smoke + or state["world_size"] != world or state["global_batch"] != batch_size + or not state["complete_backbone"] or state["teacher_used"]): + raise RuntimeError("resume checkpoint contract mismatch") + start = state["update"] + if start >= args.updates or state["next_sample_position"] != start * batch_size: + raise RuntimeError("resume cursor or endpoint mismatch") + model.load_state_dict(state["model"], strict=True) + smoke_start = {"geometry_only": 0, "joint": CONFIG["joint_start_update"], + "visual_joint": CONFIG["visual_start_update"]}[args.smoke_stage] + stage = configure_stage(model, smoke_start if args.smoke else start) + model.to(device).train() + optimizer = optimizer_for(model) + source_exposure, mode_exposure = Counter(), Counter() + if state: + optimizer.load_state_dict(state["optimizer"]) + source_exposure.update(state["source_exposure"]) + mode_exposure.update(state["mode_exposure"]) + restore_rng(state["rank_rng_states"][rank]) + del state + for parameter in model.parameters(): + dist.broadcast(parameter.data, src=0) + for buffer in model.buffers(): + contiguous = buffer.data.contiguous() + dist.broadcast(contiguous, src=0) + if contiguous.data_ptr() != buffer.data.data_ptr(): + buffer.data.copy_(contiguous) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh run would overwrite existing metrics") + if shutil.disk_usage(args.output).free < 80 * 1024**3: + raise RuntimeError("less than 80 GiB free for eight full checkpoints") + (args.output / "provenance.json").write_text(json.dumps({ + "experiment": CONFIG["experiment"], "provenance": provenance, + "source_quota": CONFIG["source_quota_per_update"], + "loss": BASE_CONFIG["shared"]["loss"], "rgb_parent": str(PARENT), + "world_size": world, "global_batch": batch_size, + "workers_per_rank": args.workers, "resume": str(args.resume) if args.resume else None, + "smoke": args.smoke, "smoke_stage": args.smoke_stage, + }, indent=2) + "\n") + dist.barrier(device_ids=[local]) + sampler = base.PositionSampler(MultimodalCoverage(), start * batch_size, + args.updates * batch_size, rank, world) + loader = DataLoader(MultimodalDataset(), batch_size=1, sampler=sampler, + num_workers=args.workers, persistent_workers=True, + collate_fn=one_sample, pin_memory=True, + prefetch_factor=CONFIG["prefetch_factor"], + worker_init_fn=partial(initialize_worker, opencv_threads=1), + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + objective = FromScratchLoss(fitted, {name: BASE_CONFIG["shared"]["loss"][name] + for name in TERMS}, BASE_CONFIG["shared"]["smoke"]).to(device) + log = (args.output / "metrics.jsonl").open("a", buffering=1) if rank == 0 else None + clips_per_rank = batch_size // world + for update in range(start, args.updates): + next_stage = (args.smoke_stage if args.smoke else + "visual_joint" if update >= CONFIG["visual_start_update"] else + "joint" if update >= CONFIG["joint_start_update"] else "geometry_only") + if next_stage != stage: + dist.barrier(device_ids=[local]) + stage = configure_stage(model, update) + model.train() + rates = learning_rates(optimizer, update) + started = time.monotonic() + cpu_batches = collate_grouped([next(iterator) for _ in range(clips_per_rank)], + CONFIG["group_max_clips"]) + data_ready = time.monotonic() + if sum(len(cpu["input_mode"]) for cpu in cpu_batches) != clips_per_rank: + raise RuntimeError("microbatch grouping changed clip count") + local_sources = Counter(s for cpu in cpu_batches for s in cpu["sampling_source_id"]) + local_modes = Counter(m for cpu in cpu_batches for m in cpu["input_mode"]) + local_counts = torch.tensor([local_sources[s] for s in SOURCES] + + [local_modes[m] for m in MODES], device=device) + dist.all_reduce(local_counts) + if not args.smoke and local_counts[:3].tolist() != [ + CONFIG["source_quota_per_update"][source] for source in SOURCES]: + raise RuntimeError("source quota per update changed") + if local_counts[3:].sum().item() != batch_size: + raise RuntimeError("modality accounting changed") + optimizer.zero_grad(set_to_none=True) + loss_total = 0.0 + term_totals = Counter() + nonpositive = 0 + valid_pose = 0 + for cpu in cpu_batches: + count = len(cpu["input_mode"]) + batch = base.move_to_device(cpu, device) + a7.validate_cached_geometry(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + results = [objective(select_clip(prediction, index, count), + select_clip(batch, index, count)) for index in range(count)] + loss = torch.stack([result[0] for result in results]).sum() + if not bool(torch.isfinite(loss)) or any( + result[2]["gt_rotation_orthogonality_max"] > 1e-5 + for result in results): + raise RuntimeError(f"nonfinite loss or invalid GT at update {update + 1}") + if loss.requires_grad: + (loss / clips_per_rank).backward() + for clip_loss, terms, diagnostics in results: + loss_total += float(clip_loss.detach()) / clips_per_rank + for name, value in terms.items(): + term_totals[name] += float(value.detach()) / clips_per_rank + nonpositive += diagnostics["nonpositive_reprojection_joints"] + valid_pose += diagnostics["valid_local_frames"] + trainable = synchronize_gradients(model, world) + norm = torch.nn.utils.clip_grad_norm_(trainable, CONFIG["clip_grad_norm"]) + if not bool(torch.isfinite(norm)): + raise RuntimeError(f"nonfinite gradient at update {update + 1}") + optimizer.step() + for source, count in zip(SOURCES, local_counts[:3].tolist()): + source_exposure[source] += count + for mode, count in zip(MODES, local_counts[3:].tolist()): + mode_exposure[mode] += count + if rank == 0 and ((update + 1) % args.log_every == 0 or update < 10): + row = {"update": update + 1, "rgb_parent_update": CONFIG["rgb_parent_update"], + "stage": stage, "seconds": time.monotonic() - started, + "data_wait_seconds": data_ready - started, + "loss_rank0": loss_total, "terms_rank0": dict(term_totals), + "preclip_grad_norm_rank0": float(norm), "nonpositive_rank0": nonpositive, + "valid_local_pose_frames_rank0": valid_pose, + "learning_rates": rates, "source_exposure": dict(source_exposure), + "mode_exposure": dict(mode_exposure)} + log.write(json.dumps(row, allow_nan=False) + "\n") + print(json.dumps(row, allow_nan=False), flush=True) + if (update + 1 in CONFIG["checkpoint_updates"] or update + 1 == args.updates): + gathered = [None] * world + dist.all_gather_object(gathered, rng_state()) + if rank == 0: + save_checkpoint(args.output / f"update_{update + 1:07d}.pt", model, + optimizer, update + 1, batch_size, provenance, + gathered, source_exposure, mode_exposure, args.smoke) + dist.barrier(device_ids=[local]) + if log: + log.close() + finally: + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/pyproject.toml b/home/wuyifan/EgoNet_train_20261008/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d274759219556334f63cca86e5aefac56269cf7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/pyproject.toml @@ -0,0 +1,37 @@ +[build-system] +requires = ["setuptools>=68", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "foundation-hand" +version = "0.1.0" +description = "Full-frame token-based bimanual reconstruction research code" +requires-python = ">=3.11,<3.12" +dependencies = [ + "einops>=0.8", + "numpy>=2.0", + "opencv-python-headless>=4.10", + "Pillow>=10", + "PyYAML>=6", + "scipy>=1.13", + "torch>=2.6", + "torchvision>=0.21", + "transformers>=4.56,<5", + "safetensors>=0.5", + "chumpy>=0.70", + "tqdm>=4.66", +] + +[project.optional-dependencies] +dev = ["pytest>=8"] + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-ra" + +[tool.ruff] +line-length = 100 +target-version = "py311" diff --git a/home/wuyifan/EgoNet_train_20261008/reports/README.md b/home/wuyifan/EgoNet_train_20261008/reports/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2bdfc75a551ec27a82a9e942624070dcac0cd119 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/README.md @@ -0,0 +1,3 @@ +# Aggregate evaluation reports + +Only aggregate JSON reports from frozen development panels are included. Per-frame rows, input media, GT caches, and model weights are omitted. diff --git a/home/wuyifan/EgoNet_train_20261008/reports/hard_exposure_30_tiles_per_source.json b/home/wuyifan/EgoNet_train_20261008/reports/hard_exposure_30_tiles_per_source.json new file mode 100644 index 0000000000000000000000000000000000000000..89cbfdf43735deff890d99a704549f240f4fa599 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/hard_exposure_30_tiles_per_source.json @@ -0,0 +1,760 @@ +{ + "sampling": "one source tile per 30 evenly spaced windows across the 1.2M-clip training stream", + "summary": { + "H2O": { + "sampled_tiles": 30, + "pose_valid_hands": 480, + "weighted_15": 71, + "weighted_20": 109, + "weighted_hand_fraction": 0.375, + "mean_weight_per_valid_hand": 1.3010416666666667, + "tiles_without_hard": 11 + }, + "ARCTIC": { + "sampled_tiles": 30, + "pose_valid_hands": 444, + "weighted_15": 51, + "weighted_20": 81, + "weighted_hand_fraction": 0.2972972972972973, + "mean_weight_per_valid_hand": 1.239864864864865, + "tiles_without_hard": 14 + }, + "HOT3D": { + "sampled_tiles": 30, + "pose_valid_hands": 421, + "weighted_15": 121, + "weighted_20": 127, + "weighted_hand_fraction": 0.5890736342042755, + "mean_weight_per_valid_hand": 1.4453681710213777, + "tiles_without_hard": 6 + } + }, + "rows": { + "H2O": [ + { + "position": 20001, + "tile_id": "1a0411b79c50842e39d45b42:52", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 60000, + "tile_id": "aa11dc9d7b07b603d290114e:0", + "pose_valid_hands": 16, + "weighted_15": 6, + "weighted_20": 2, + "weight_mass": 21.0 + }, + { + "position": 100000, + "tile_id": "2165ae07dec3fec7d917d255:40", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 140002, + "tile_id": "190fd760cb4cb156d76ce231:48", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 180004, + "tile_id": "9ace43868b51405a8a39b0b4:48", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 220000, + "tile_id": "342e60f49ebbe86431722341:8", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 260000, + "tile_id": "2ab7272c90c73bb59a775564:51", + "pose_valid_hands": 16, + "weighted_15": 2, + "weighted_20": 2, + "weight_mass": 19.0 + }, + { + "position": 300003, + "tile_id": "a2754e4b2ae22fb33f8f0a5a:24", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 340003, + "tile_id": "6538d84f721b276557020fb5:24", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 380000, + "tile_id": "c30308beaaa8b32b52c21203:8", + "pose_valid_hands": 16, + "weighted_15": 3, + "weighted_20": 5, + "weight_mass": 22.5 + }, + { + "position": 420001, + "tile_id": "9f13c55015a34cf86264767f:32", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 460000, + "tile_id": "4e88f98d4c8cecc1d1ba4725:24", + "pose_valid_hands": 16, + "weighted_15": 1, + "weighted_20": 7, + "weight_mass": 23.5 + }, + { + "position": 500003, + "tile_id": "241ec367e677298677fa8c09:32", + "pose_valid_hands": 16, + "weighted_15": 8, + "weighted_20": 0, + "weight_mass": 20.0 + }, + { + "position": 540000, + "tile_id": "aed3bc9abc808be128ef025d:40", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 580000, + "tile_id": "87802b1df370f0f1484452fb:33", + "pose_valid_hands": 16, + "weighted_15": 5, + "weighted_20": 11, + "weight_mass": 29.5 + }, + { + "position": 620000, + "tile_id": "d8268fca7bb675318198fd73:8", + "pose_valid_hands": 16, + "weighted_15": 7, + "weighted_20": 9, + "weight_mass": 28.5 + }, + { + "position": 660000, + "tile_id": "5be40b2e1da79fa454731380:52", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 700002, + "tile_id": "ba5145b72ddaab13a7e05a5b:8", + "pose_valid_hands": 16, + "weighted_15": 4, + "weighted_20": 0, + "weight_mass": 18.0 + }, + { + "position": 740003, + "tile_id": "2a70eb568925204312daf44c:0", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 780000, + "tile_id": "dc9b8d24db5f307c8fd158a0:32", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 820002, + "tile_id": "0d1cd97b8f79f940c16db83f:8", + "pose_valid_hands": 16, + "weighted_15": 4, + "weighted_20": 3, + "weight_mass": 21.0 + }, + { + "position": 860000, + "tile_id": "9978933e1bc58b64c7f8ac4e:8", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 900000, + "tile_id": "1eec23b9e8be7fefbcf2261a:32", + "pose_valid_hands": 16, + "weighted_15": 1, + "weighted_20": 7, + "weight_mass": 23.5 + }, + { + "position": 940003, + "tile_id": "c3040d6462594e73a3405007:52", + "pose_valid_hands": 16, + "weighted_15": 13, + "weighted_20": 0, + "weight_mass": 22.5 + }, + { + "position": 980007, + "tile_id": "c998c7d9e0ea7723aa22d2c7:24", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 1020001, + "tile_id": "138dfc66313c782aa8adc392:40", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 1060001, + "tile_id": "63020ea45618f6fab8f8c705:0", + "pose_valid_hands": 16, + "weighted_15": 14, + "weighted_20": 2, + "weight_mass": 25.0 + }, + { + "position": 1100003, + "tile_id": "2571a3ec1fffcb68addeb374:24", + "pose_valid_hands": 16, + "weighted_15": 3, + "weighted_20": 13, + "weight_mass": 30.5 + }, + { + "position": 1140002, + "tile_id": "d44a0e856751103bfae05c42:48", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 1180000, + "tile_id": "4d03335d48ae750cc2d0cd5c:24", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + } + ], + "ARCTIC": [ + { + "position": 20002, + "tile_id": "17a3d720e547aa30e3460058:24", + "pose_valid_hands": 16, + "weighted_15": 10, + "weighted_20": 2, + "weight_mass": 23.0 + }, + { + "position": 60001, + "tile_id": "a6ceef87445c0271265aad0c:40", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 100006, + "tile_id": "a28e90c5810e174b7f56aec9:24", + "pose_valid_hands": 16, + "weighted_15": 5, + "weighted_20": 0, + "weight_mass": 18.5 + }, + { + "position": 140000, + "tile_id": "0fc8dd69a28adc0ecf611115:40", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 180000, + "tile_id": "fbf9245cbcacade7e5be5be1:0", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 220002, + "tile_id": "fd51b599cd968be49634c509:52", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 260003, + "tile_id": "b3690d65b7b0a6c85266b669:16", + "pose_valid_hands": 4, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 4.0 + }, + { + "position": 300000, + "tile_id": "d722428c2d72cba55dcb315f:16", + "pose_valid_hands": 16, + "weighted_15": 2, + "weighted_20": 0, + "weight_mass": 17.0 + }, + { + "position": 340002, + "tile_id": "d499eafea9c5f402f940e2c8:8", + "pose_valid_hands": 16, + "weighted_15": 4, + "weighted_20": 4, + "weight_mass": 22.0 + }, + { + "position": 380003, + "tile_id": "2c60e4eb6ec976e4760bcf0f:32", + "pose_valid_hands": 16, + "weighted_15": 6, + "weighted_20": 1, + "weight_mass": 20.0 + }, + { + "position": 420000, + "tile_id": "992dcce495e6cff1dfdcd885:40", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 460001, + "tile_id": "1d87b33cbb239c87b497c0bb:40", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 500001, + "tile_id": "516923930866cb4d79385817:24", + "pose_valid_hands": 16, + "weighted_15": 1, + "weighted_20": 0, + "weight_mass": 16.5 + }, + { + "position": 540001, + "tile_id": "7cdb84e70e27d303622e43c7:24", + "pose_valid_hands": 16, + "weighted_15": 7, + "weighted_20": 0, + "weight_mass": 19.5 + }, + { + "position": 580002, + "tile_id": "1e61b47265b66bbd7ac42bd0:0", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 620002, + "tile_id": "6b0eff9c53c057f42c0eacb9:8", + "pose_valid_hands": 16, + "weighted_15": 2, + "weighted_20": 14, + "weight_mass": 31.0 + }, + { + "position": 660008, + "tile_id": "31646546e7995303d21a819b:16", + "pose_valid_hands": 16, + "weighted_15": 2, + "weighted_20": 3, + "weight_mass": 20.0 + }, + { + "position": 700004, + "tile_id": "789f2a8822a0f3384aa3d1a4:16", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 16, + "weight_mass": 32.0 + }, + { + "position": 740000, + "tile_id": "f9eea8372047c9da0c1c7048:48", + "pose_valid_hands": 16, + "weighted_15": 2, + "weighted_20": 8, + "weight_mass": 25.0 + }, + { + "position": 780001, + "tile_id": "1fdd2eb7dd484acd0765e00e:0", + "pose_valid_hands": 16, + "weighted_15": 5, + "weighted_20": 1, + "weight_mass": 19.5 + }, + { + "position": 820000, + "tile_id": "f55596412f83a4704c72b444:32", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 860007, + "tile_id": "567ce6607f1e809cd6e9c779:16", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 900002, + "tile_id": "cb5d2040fda3ab53c9c88dde:0", + "pose_valid_hands": 0, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 0.0 + }, + { + "position": 940001, + "tile_id": "2c122d7fa9a23f0ae2a3b628:48", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 980001, + "tile_id": "c68e7d52bb5de3e4a2ae800d:16", + "pose_valid_hands": 8, + "weighted_15": 5, + "weighted_20": 0, + "weight_mass": 10.5 + }, + { + "position": 1020002, + "tile_id": "67a1293eb8fd4c57c743d958:8", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 1060000, + "tile_id": "429697e48f9cc7372dfcf781:8", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 1100000, + "tile_id": "6f9b27e20e458fd91b99233a:48", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 1140003, + "tile_id": "a8ce5bdfe854bece36ed1ba8:0", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 16, + "weight_mass": 32.0 + }, + { + "position": 1180005, + "tile_id": "db198fa8b46c9ad19b5bc2fe:8", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + } + ], + "HOT3D": [ + { + "position": 20000, + "tile_id": "a431aedbaf7ba47abeb1138c:8", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 60002, + "tile_id": "f3fd55e1b60c3bc7f36b9504:40", + "pose_valid_hands": 16, + "weighted_15": 4, + "weighted_20": 12, + "weight_mass": 30.0 + }, + { + "position": 100001, + "tile_id": "6d1660e18a3c735b67fe91f1:8", + "pose_valid_hands": 16, + "weighted_15": 8, + "weighted_20": 8, + "weight_mass": 28.0 + }, + { + "position": 140001, + "tile_id": "6c757dada2fd37d1b8bf406d:0", + "pose_valid_hands": 3, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 3.0 + }, + { + "position": 180002, + "tile_id": "82fee09fb47dca32b3c8b31f:7", + "pose_valid_hands": 16, + "weighted_15": 7, + "weighted_20": 1, + "weight_mass": 20.5 + }, + { + "position": 220001, + "tile_id": "0e9ae572659ee5da8dbb7967:0", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 16, + "weight_mass": 32.0 + }, + { + "position": 260001, + "tile_id": "711e74dcb13d975659cd0a38:24", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 300001, + "tile_id": "82c435fd93e8a2614db9bd9b:48", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 340000, + "tile_id": "9c7ebe87bc1424289f7a41c6:24", + "pose_valid_hands": 16, + "weighted_15": 8, + "weighted_20": 2, + "weight_mass": 22.0 + }, + { + "position": 380001, + "tile_id": "0cd6b0032f64b42a4aed2215:8", + "pose_valid_hands": 15, + "weighted_15": 7, + "weighted_20": 8, + "weight_mass": 26.5 + }, + { + "position": 420003, + "tile_id": "437b336cc230c100a77a38cc:40", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 8, + "weight_mass": 24.0 + }, + { + "position": 460002, + "tile_id": "82377fca5bb1fcd32d64a246:0", + "pose_valid_hands": 8, + "weighted_15": 2, + "weighted_20": 0, + "weight_mass": 9.0 + }, + { + "position": 500000, + "tile_id": "9b5f2ea1ebc3946bbf0b75f2:16", + "pose_valid_hands": 11, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 11.0 + }, + { + "position": 540003, + "tile_id": "6ae705ea7260e501f360da11:24", + "pose_valid_hands": 16, + "weighted_15": 11, + "weighted_20": 5, + "weight_mass": 26.5 + }, + { + "position": 580001, + "tile_id": "a0366ee5a1144e6415bee2bf:48", + "pose_valid_hands": 16, + "weighted_15": 5, + "weighted_20": 0, + "weight_mass": 18.5 + }, + { + "position": 620001, + "tile_id": "63dc0ace8fc425136887e3c1:24", + "pose_valid_hands": 16, + "weighted_15": 8, + "weighted_20": 0, + "weight_mass": 20.0 + }, + { + "position": 660001, + "tile_id": "5a1dae83af85b17744c8c4b8:0", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 16.0 + }, + { + "position": 700000, + "tile_id": "8e36f65132190bc76e1f956b:32", + "pose_valid_hands": 8, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 8.0 + }, + { + "position": 740001, + "tile_id": "c118b176bfec6916e158668d:8", + "pose_valid_hands": 16, + "weighted_15": 8, + "weighted_20": 8, + "weight_mass": 28.0 + }, + { + "position": 780005, + "tile_id": "bf69dae06f8ad0490bc5466e:8", + "pose_valid_hands": 16, + "weighted_15": 8, + "weighted_20": 8, + "weight_mass": 28.0 + }, + { + "position": 820001, + "tile_id": "3cbca6e5a9f32e1891bdf86b:40", + "pose_valid_hands": 16, + "weighted_15": 7, + "weighted_20": 1, + "weight_mass": 20.5 + }, + { + "position": 860001, + "tile_id": "e4795a6c7764239fda34799c:32", + "pose_valid_hands": 16, + "weighted_15": 9, + "weighted_20": 0, + "weight_mass": 20.5 + }, + { + "position": 900001, + "tile_id": "2867e037207ea071d1393990:52", + "pose_valid_hands": 16, + "weighted_15": 3, + "weighted_20": 5, + "weight_mass": 22.5 + }, + { + "position": 940000, + "tile_id": "fab592ed922d9f06af47980f:16", + "pose_valid_hands": 16, + "weighted_15": 8, + "weighted_20": 0, + "weight_mass": 20.0 + }, + { + "position": 980000, + "tile_id": "0c420a9ede59514482f2488f:0", + "pose_valid_hands": 8, + "weighted_15": 1, + "weighted_20": 0, + "weight_mass": 8.5 + }, + { + "position": 1020000, + "tile_id": "c2207f0ce9c10cce3624ecd4:52", + "pose_valid_hands": 8, + "weighted_15": 8, + "weighted_20": 0, + "weight_mass": 12.0 + }, + { + "position": 1060002, + "tile_id": "42aad86fe5e827c7788e3269:48", + "pose_valid_hands": 16, + "weighted_15": 0, + "weighted_20": 16, + "weight_mass": 32.0 + }, + { + "position": 1100001, + "tile_id": "61637533eb709b4da8d63349:0", + "pose_valid_hands": 16, + "weighted_15": 5, + "weighted_20": 5, + "weight_mass": 23.5 + }, + { + "position": 1140000, + "tile_id": "f3c1103335b4a5c77561f58a:40", + "pose_valid_hands": 16, + "weighted_15": 4, + "weighted_20": 8, + "weight_mass": 26.0 + }, + { + "position": 1180002, + "tile_id": "8155bb599bca91451fe5cb60:24", + "pose_valid_hands": 8, + "weighted_15": 0, + "weighted_20": 0, + "weight_mass": 8.0 + } + ] + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/oracle_pose_hot3d_n1_18k.json b/home/wuyifan/EgoNet_train_20261008/reports/oracle_pose_hot3d_n1_18k.json new file mode 100644 index 0000000000000000000000000000000000000000..3190542806b5b22d1355283dcf7f02851321c609 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/oracle_pose_hot3d_n1_18k.json @@ -0,0 +1,786 @@ +{ + "source": "HOT3D", + "role": "development_oracle_diagnostic", + "checkpoint": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0018000.pt", + "checkpoint_sha256": "07ffd4d5463d64e5762f9dfa268d6539bff28c4d4dcf078c85cd7d7f3b17af2b", + "panel_sha256": "8ae334a8bc87bc6670a31f2edb8b78989c883547d26c86815498d5f89ccb7060", + "gt": "source_native_not_refitted", + "oracle_contract": "replace selected MANO factors by native GT, retaining predicted shape; not a deployable score", + "clips": 248, + "groups": { + "all": { + "hands": 3573, + "variants": { + "direct": { + "means": { + "absolute_mpjpe_mm": { + "mean": 52.66985028042968, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 23.959289349263166, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 52.42802933247991, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 14.482651678179854, + "count": 3289 + } + }, + "paired_to_direct": null + }, + "gt_local": { + "means": { + "absolute_mpjpe_mm": { + "mean": 51.96233118437866, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 21.725695134810696, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 51.80633194680779, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 13.641196136816761, + "count": 3289 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -0.7075190960510152, + "recording_bootstrap_95ci": [ + -1.349076399520032, + 0.03011834500136148 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": -2.2335942144524705, + "recording_bootstrap_95ci": [ + -2.7032235176802972, + -1.7648572843784502 + ], + "count": 3573, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -0.6216973856721243, + "recording_bootstrap_95ci": [ + -1.2501623895679153, + 0.10063506078275793 + ], + "count": 3573, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.841455541363093, + "recording_bootstrap_95ci": [ + -1.2847894125386705, + -0.3821845817597187 + ], + "count": 3289, + "recordings": 31 + } + } + }, + "gt_root": { + "means": { + "absolute_mpjpe_mm": { + "mean": 52.61875343242681, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 12.262771792682718, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 52.43403378621957, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 14.15296659718969, + "count": 3289 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -0.05109684800287605, + "recording_bootstrap_95ci": [ + -1.5763737106450528, + 1.385032205826605 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": -11.696517556580448, + "recording_bootstrap_95ci": [ + -12.9996873022903, + -10.428819752234437 + ], + "count": 3573, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": 0.00600445373966485, + "recording_bootstrap_95ci": [ + -1.413700592694106, + 1.356699241740362 + ], + "count": 3573, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.3296850809901636, + "recording_bootstrap_95ci": [ + -0.8454208371914239, + 0.2274799287310547 + ], + "count": 3289, + "recordings": 31 + } + } + }, + "gt_translation": { + "means": { + "absolute_mpjpe_mm": { + "mean": 23.951915971978586, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 23.951915974781155, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 22.938368736179545, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 12.361923307406935, + "count": 3289 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -28.717934308451095, + "recording_bootstrap_95ci": [ + -33.89870705084039, + -24.005716651563247 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": -0.007373374482012582, + "recording_bootstrap_95ci": [ + -0.01413000945474816, + -0.0007261062189237717 + ], + "count": 3573, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -29.489660596300364, + "recording_bootstrap_95ci": [ + -34.71629092620621, + -24.772539042345578 + ], + "count": 3573, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -2.1207283707729188, + "recording_bootstrap_95ci": [ + -3.8897252716385973, + -0.7541070520533979 + ], + "count": 3289, + "recordings": 31 + } + } + }, + "gt_all_rot_translation": { + "means": { + "absolute_mpjpe_mm": { + "mean": 5.54437631223504, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 5.544376312201677, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 5.483129237400795, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 3.3338727477420314, + "count": 3289 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -47.12547396819464, + "recording_bootstrap_95ci": [ + -53.683819799714456, + -41.29366082881366 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": -18.414913037061492, + "recording_bootstrap_95ci": [ + -20.21010852610224, + -16.687693321667716 + ], + "count": 3573, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -46.94490009507911, + "recording_bootstrap_95ci": [ + -53.409399186200375, + -41.15742246988259 + ], + "count": 3573, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -11.148778930437823, + "recording_bootstrap_95ci": [ + -14.579390466527396, + -8.412972979807424 + ], + "count": 3289, + "recordings": 31 + } + } + } + } + }, + "normal": { + "hands": 1039, + "variants": { + "direct": { + "means": { + "absolute_mpjpe_mm": { + "mean": 49.327910123591934, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 22.809003156693194, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 49.25970123316716, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.630683421605506, + "count": 987 + } + }, + "paired_to_direct": null + }, + "gt_local": { + "means": { + "absolute_mpjpe_mm": { + "mean": 48.46395742904692, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 21.739262656137505, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 48.42263242438852, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.154277868425472, + "count": 987 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -0.8639526945450079, + "recording_bootstrap_95ci": [ + -1.9333041998230178, + 0.29515360293878473 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_mpjpe_mm": { + "delta": -1.0697405005556901, + "recording_bootstrap_95ci": [ + -1.8610761407100622, + -0.2503188298107022 + ], + "count": 1039, + "recordings": 30 + }, + "mpvpe_mm": { + "delta": -0.8370688087786472, + "recording_bootstrap_95ci": [ + -1.8752225588616713, + 0.2764010859559628 + ], + "count": 1039, + "recordings": 30 + }, + "projected_mano_2d_error_px": { + "delta": -0.4764055531800337, + "recording_bootstrap_95ci": [ + -1.1974342536334557, + 0.22970843299339727 + ], + "count": 987, + "recordings": 30 + } + } + }, + "gt_root": { + "means": { + "absolute_mpjpe_mm": { + "mean": 51.098171171715215, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 12.823761131352708, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 50.95041345655058, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.783132238107854, + "count": 987 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": 1.7702610481232834, + "recording_bootstrap_95ci": [ + 0.13146900304643386, + 3.4837063472880088 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_mpjpe_mm": { + "delta": -9.985242025340487, + "recording_bootstrap_95ci": [ + -12.070256749846717, + -8.174298904648074 + ], + "count": 1039, + "recordings": 30 + }, + "mpvpe_mm": { + "delta": 1.6907122233834142, + "recording_bootstrap_95ci": [ + 0.1578015968127287, + 3.2977152523889974 + ], + "count": 1039, + "recordings": 30 + }, + "projected_mano_2d_error_px": { + "delta": 0.1524488165023479, + "recording_bootstrap_95ci": [ + -0.8150981052414727, + 1.1955719008991552 + ], + "count": 987, + "recordings": 30 + } + } + }, + "gt_translation": { + "means": { + "absolute_mpjpe_mm": { + "mean": 22.792855616597972, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 22.792855631284006, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 21.993811587167542, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 12.007859006599572, + "count": 987 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -26.53505450699396, + "recording_bootstrap_95ci": [ + -32.728865694467665, + -21.68273618556741 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_mpjpe_mm": { + "delta": -0.016147525409188148, + "recording_bootstrap_95ci": [ + -0.028836629906327273, + -0.003972137854097153 + ], + "count": 1039, + "recordings": 30 + }, + "mpvpe_mm": { + "delta": -27.265889645999618, + "recording_bootstrap_95ci": [ + -33.455995318162884, + -22.278762868630107 + ], + "count": 1039, + "recordings": 30 + }, + "projected_mano_2d_error_px": { + "delta": -2.6228244150059323, + "recording_bootstrap_95ci": [ + -5.480844824625255, + -0.2891097854533042 + ], + "count": 987, + "recordings": 30 + } + } + }, + "gt_all_rot_translation": { + "means": { + "absolute_mpjpe_mm": { + "mean": 5.450205388266497, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 5.450205388954904, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 5.4226238449911754, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 3.138350357853533, + "count": 987 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -43.87770473532544, + "recording_bootstrap_95ci": [ + -51.48971671055026, + -37.71930365327289 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_mpjpe_mm": { + "delta": -17.35879776773829, + "recording_bootstrap_95ci": [ + -19.61997019197761, + -15.17463147689855 + ], + "count": 1039, + "recordings": 30 + }, + "mpvpe_mm": { + "delta": -43.837077388175985, + "recording_bootstrap_95ci": [ + -51.425044158463336, + -37.61573943526064 + ], + "count": 1039, + "recordings": 30 + }, + "projected_mano_2d_error_px": { + "delta": -11.492333063751973, + "recording_bootstrap_95ci": [ + -15.31681475437677, + -8.191773063195216 + ], + "count": 987, + "recordings": 30 + } + } + } + } + }, + "hard": { + "hands": 2534, + "variants": { + "direct": { + "means": { + "absolute_mpjpe_mm": { + "mean": 54.04012487512361, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 24.43093392466972, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 53.72711887280585, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 14.419181942836188, + "count": 2302 + } + }, + "paired_to_direct": null + }, + "gt_local": { + "means": { + "absolute_mpjpe_mm": { + "mean": 53.39674725848667, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 21.720132129815212, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 53.19372887016754, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 13.421208443898516, + "count": 2302 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -0.6433776166369432, + "recording_bootstrap_95ci": [ + -1.2726525262057515, + 0.0740608007632148 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": -2.710801794854505, + "recording_bootstrap_95ci": [ + -3.256151120789692, + -2.166993008588073 + ], + "count": 2534, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -0.5333900026383133, + "recording_bootstrap_95ci": [ + -1.1569546103638613, + 0.18294804122329542 + ], + "count": 2534, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.9979734989376714, + "recording_bootstrap_95ci": [ + -1.49371547103474, + -0.5440232932029866 + ], + "count": 2302, + "recordings": 31 + } + } + }, + "gt_root": { + "means": { + "absolute_mpjpe_mm": { + "mean": 53.242228163634124, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 12.032752880733975, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 53.04235325051558, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 13.88277828807317, + "count": 2302 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -0.79789671148949, + "recording_bootstrap_95ci": [ + -2.812192067420669, + 1.0354843826206226 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": -12.398181043935745, + "recording_bootstrap_95ci": [ + -14.094312825494129, + -10.832845338454042 + ], + "count": 2534, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -0.6847656222902703, + "recording_bootstrap_95ci": [ + -2.579056148199218, + 1.0470563498417103 + ], + "count": 2534, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.5364036547630171, + "recording_bootstrap_95ci": [ + -1.3612901694789012, + 0.21359763011124508 + ], + "count": 2302, + "recordings": 31 + } + } + }, + "gt_translation": { + "means": { + "absolute_mpjpe_mm": { + "mean": 24.427158161891946, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 24.427158159822014, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 23.325659532479253, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 12.513731068005052, + "count": 2302 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -29.612966713231664, + "recording_bootstrap_95ci": [ + -36.24559955539097, + -23.658501449695628 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": -0.003775764847705001, + "recording_bootstrap_95ci": [ + -0.01154244784233733, + 0.0041004664091831644 + ], + "count": 2534, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -30.4014593403266, + "recording_bootstrap_95ci": [ + -36.99493099402651, + -24.502977308829223 + ], + "count": 2534, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -1.9054508748311358, + "recording_bootstrap_95ci": [ + -3.6263105090600094, + -0.5738620178773252 + ], + "count": 2302, + "recordings": 31 + } + } + }, + "gt_all_rot_translation": { + "means": { + "absolute_mpjpe_mm": { + "mean": 5.582988620839348, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 5.582988620510041, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 5.507937880934179, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 3.4177044587845806, + "count": 2302 + } + }, + "paired_to_direct": { + "absolute_mpjpe_mm": { + "delta": -48.457136254284265, + "recording_bootstrap_95ci": [ + -56.654124486140965, + -41.185375945768506 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": -18.847945304159676, + "recording_bootstrap_95ci": [ + -21.016809466418216, + -16.816361031165798 + ], + "count": 2534, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -48.219180991871674, + "recording_bootstrap_95ci": [ + -56.28389322134659, + -41.04983833440105 + ], + "count": 2534, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -11.001477484051607, + "recording_bootstrap_95ci": [ + -14.65576363650049, + -7.989854373807958 + ], + "count": 2302, + "recordings": 31 + } + } + } + } + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/pose_anchor_n1_18k_spread.json b/home/wuyifan/EgoNet_train_20261008/reports/pose_anchor_n1_18k_spread.json new file mode 100644 index 0000000000000000000000000000000000000000..19208299ce56b900e1d3441311edc26b5af956f2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/pose_anchor_n1_18k_spread.json @@ -0,0 +1,403 @@ +{ + "checkpoint": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0018000.pt", + "sample": "ten training tiles per source spread across 1.2M stream", + "source_scaling": "not applied", + "rows": { + "H2O": [ + { + "position": 20001, + "tile_id": "1a0411b79c50842e39d45b42:52", + "local_pose_loss": 0.023688022047281265, + "geometry_loss": 0.03354087844491005, + "anchor_loss": 0.002211472950875759, + "local_grad_norm": 0.8848132491111755, + "geometry_grad_norm": 3.220552444458008, + "anchor_grad_norm": 0.11007654666900635, + "anchor_to_local_grad_ratio": 0.12440653145313263, + "anchor_vs_local_cosine": -0.02735075354576111, + "anchor_vs_geometry_cosine": -0.060645606368780136 + }, + { + "position": 140002, + "tile_id": "190fd760cb4cb156d76ce231:48", + "local_pose_loss": 0.037373606115579605, + "geometry_loss": 0.03467855975031853, + "anchor_loss": 0.0017476361244916916, + "local_grad_norm": 1.2078559398651123, + "geometry_grad_norm": 3.61857533454895, + "anchor_grad_norm": 0.12788480520248413, + "anchor_to_local_grad_ratio": 0.10587753355503082, + "anchor_vs_local_cosine": 0.0069961040280759335, + "anchor_vs_geometry_cosine": -0.5156996250152588 + }, + { + "position": 260000, + "tile_id": "2ab7272c90c73bb59a775564:51", + "local_pose_loss": 0.07916273921728134, + "geometry_loss": 0.10443219542503357, + "anchor_loss": 0.003581854747608304, + "local_grad_norm": 1.5917892456054688, + "geometry_grad_norm": 5.538802146911621, + "anchor_grad_norm": 0.3673267364501953, + "anchor_to_local_grad_ratio": 0.23076342046260834, + "anchor_vs_local_cosine": -0.0198027603328228, + "anchor_vs_geometry_cosine": -0.3817479908466339 + }, + { + "position": 380000, + "tile_id": "c30308beaaa8b32b52c21203:8", + "local_pose_loss": 0.0656156837940216, + "geometry_loss": 0.051863428205251694, + "anchor_loss": 0.0021613433491438627, + "local_grad_norm": 1.7793700695037842, + "geometry_grad_norm": 3.414473056793213, + "anchor_grad_norm": 0.18155965209007263, + "anchor_to_local_grad_ratio": 0.10203591734170914, + "anchor_vs_local_cosine": -0.005969224032014608, + "anchor_vs_geometry_cosine": -0.4082987904548645 + }, + { + "position": 500003, + "tile_id": "241ec367e677298677fa8c09:32", + "local_pose_loss": 0.040377214550971985, + "geometry_loss": 0.054145924746990204, + "anchor_loss": 0.002529481193050742, + "local_grad_norm": 1.0233601331710815, + "geometry_grad_norm": 3.0067310333251953, + "anchor_grad_norm": 0.28403621912002563, + "anchor_to_local_grad_ratio": 0.2775525450706482, + "anchor_vs_local_cosine": 0.006678903475403786, + "anchor_vs_geometry_cosine": -0.37318146228790283 + }, + { + "position": 620000, + "tile_id": "d8268fca7bb675318198fd73:8", + "local_pose_loss": 0.06813924014568329, + "geometry_loss": 0.06070810928940773, + "anchor_loss": 0.002701870631426573, + "local_grad_norm": 1.3794342279434204, + "geometry_grad_norm": 3.10933518409729, + "anchor_grad_norm": 0.1560305655002594, + "anchor_to_local_grad_ratio": 0.11311200261116028, + "anchor_vs_local_cosine": -0.035392552614212036, + "anchor_vs_geometry_cosine": -0.6881108283996582 + }, + { + "position": 740003, + "tile_id": "2a70eb568925204312daf44c:0", + "local_pose_loss": 0.04037594795227051, + "geometry_loss": 0.04637809097766876, + "anchor_loss": 0.002411690540611744, + "local_grad_norm": 1.0741028785705566, + "geometry_grad_norm": 3.2814605236053467, + "anchor_grad_norm": 0.24110278487205505, + "anchor_to_local_grad_ratio": 0.22446899116039276, + "anchor_vs_local_cosine": -0.019371457397937775, + "anchor_vs_geometry_cosine": 0.3845185935497284 + }, + { + "position": 860000, + "tile_id": "9978933e1bc58b64c7f8ac4e:8", + "local_pose_loss": 0.039895497262477875, + "geometry_loss": 0.038034871220588684, + "anchor_loss": 0.002966754836961627, + "local_grad_norm": 1.3009620904922485, + "geometry_grad_norm": 4.089384078979492, + "anchor_grad_norm": 0.13837313652038574, + "anchor_to_local_grad_ratio": 0.10636215656995773, + "anchor_vs_local_cosine": -0.008251109160482883, + "anchor_vs_geometry_cosine": -0.5387224555015564 + }, + { + "position": 980007, + "tile_id": "c998c7d9e0ea7723aa22d2c7:24", + "local_pose_loss": 0.06068216636776924, + "geometry_loss": 0.06588686257600784, + "anchor_loss": 0.0032390833366662264, + "local_grad_norm": 1.1162657737731934, + "geometry_grad_norm": 2.7208714485168457, + "anchor_grad_norm": 0.2809445261955261, + "anchor_to_local_grad_ratio": 0.25168246030807495, + "anchor_vs_local_cosine": -0.05841808766126633, + "anchor_vs_geometry_cosine": -0.2614987790584564 + }, + { + "position": 1100003, + "tile_id": "2571a3ec1fffcb68addeb374:24", + "local_pose_loss": 0.058262307196855545, + "geometry_loss": 0.04741440340876579, + "anchor_loss": 0.0013621256221085787, + "local_grad_norm": 1.2068355083465576, + "geometry_grad_norm": 3.809140682220459, + "anchor_grad_norm": 0.18210667371749878, + "anchor_to_local_grad_ratio": 0.15089601278305054, + "anchor_vs_local_cosine": 0.011233226396143436, + "anchor_vs_geometry_cosine": 0.18625693023204803 + } + ], + "ARCTIC": [ + { + "position": 20002, + "tile_id": "17a3d720e547aa30e3460058:24", + "local_pose_loss": 0.11123808473348618, + "geometry_loss": 0.0870455801486969, + "anchor_loss": 0.0022795165423303843, + "local_grad_norm": 2.324538469314575, + "geometry_grad_norm": 5.55442476272583, + "anchor_grad_norm": 0.2669930160045624, + "anchor_to_local_grad_ratio": 0.11485850811004639, + "anchor_vs_local_cosine": -0.03525698930025101, + "anchor_vs_geometry_cosine": 0.26041311025619507 + }, + { + "position": 140000, + "tile_id": "0fc8dd69a28adc0ecf611115:40", + "local_pose_loss": 0.1280401647090912, + "geometry_loss": 0.08518994599580765, + "anchor_loss": 0.0018489487702026963, + "local_grad_norm": 2.314788341522217, + "geometry_grad_norm": 5.023162364959717, + "anchor_grad_norm": 0.20067887008190155, + "anchor_to_local_grad_ratio": 0.08669426292181015, + "anchor_vs_local_cosine": -0.002708759857341647, + "anchor_vs_geometry_cosine": -0.033686134964227676 + }, + { + "position": 260003, + "tile_id": "b3690d65b7b0a6c85266b669:16", + "local_pose_loss": 0.11527406424283981, + "geometry_loss": 0.22785678505897522, + "anchor_loss": 0.004235369153320789, + "local_grad_norm": 2.7540621757507324, + "geometry_grad_norm": 11.127191543579102, + "anchor_grad_norm": 0.4201873540878296, + "anchor_to_local_grad_ratio": 0.15257003903388977, + "anchor_vs_local_cosine": 0.007738504093140364, + "anchor_vs_geometry_cosine": -0.25853946805000305 + }, + { + "position": 380003, + "tile_id": "2c60e4eb6ec976e4760bcf0f:32", + "local_pose_loss": 0.2077367603778839, + "geometry_loss": 0.1100437268614769, + "anchor_loss": 0.003012642962858081, + "local_grad_norm": 2.066330909729004, + "geometry_grad_norm": 2.3785831928253174, + "anchor_grad_norm": 0.2975267469882965, + "anchor_to_local_grad_ratio": 0.14398795366287231, + "anchor_vs_local_cosine": -0.02048889733850956, + "anchor_vs_geometry_cosine": -0.3506568670272827 + }, + { + "position": 500001, + "tile_id": "516923930866cb4d79385817:24", + "local_pose_loss": 0.07646913081407547, + "geometry_loss": 0.05976361036300659, + "anchor_loss": 0.002593292621895671, + "local_grad_norm": 1.5928821563720703, + "geometry_grad_norm": 3.929567575454712, + "anchor_grad_norm": 0.2625916302204132, + "anchor_to_local_grad_ratio": 0.16485314071178436, + "anchor_vs_local_cosine": 0.07171683758497238, + "anchor_vs_geometry_cosine": 0.41755396127700806 + }, + { + "position": 620002, + "tile_id": "6b0eff9c53c057f42c0eacb9:8", + "local_pose_loss": 0.13466359674930573, + "geometry_loss": 0.05086787790060043, + "anchor_loss": 0.0016332619125023484, + "local_grad_norm": 3.1583783626556396, + "geometry_grad_norm": 2.9673972129821777, + "anchor_grad_norm": 0.17037348449230194, + "anchor_to_local_grad_ratio": 0.053943343460559845, + "anchor_vs_local_cosine": -0.08305875211954117, + "anchor_vs_geometry_cosine": -0.5871760249137878 + }, + { + "position": 740000, + "tile_id": "f9eea8372047c9da0c1c7048:48", + "local_pose_loss": 0.17994073033332825, + "geometry_loss": 0.13903097808361053, + "anchor_loss": 0.0027670443523675203, + "local_grad_norm": 2.5619072914123535, + "geometry_grad_norm": 4.867450714111328, + "anchor_grad_norm": 0.18061214685440063, + "anchor_to_local_grad_ratio": 0.07049909234046936, + "anchor_vs_local_cosine": 0.02764376811683178, + "anchor_vs_geometry_cosine": 0.330891877412796 + }, + { + "position": 860007, + "tile_id": "567ce6607f1e809cd6e9c779:16", + "local_pose_loss": 0.08423900604248047, + "geometry_loss": 0.09191573411226273, + "anchor_loss": 0.002547336043789983, + "local_grad_norm": 2.0567026138305664, + "geometry_grad_norm": 5.614840030670166, + "anchor_grad_norm": 0.2569223642349243, + "anchor_to_local_grad_ratio": 0.12491954863071442, + "anchor_vs_local_cosine": 0.044207002967596054, + "anchor_vs_geometry_cosine": 0.15532976388931274 + }, + { + "position": 980001, + "tile_id": "c68e7d52bb5de3e4a2ae800d:16", + "local_pose_loss": 0.1466636210680008, + "geometry_loss": 0.08550217747688293, + "anchor_loss": 0.002249818993732333, + "local_grad_norm": 2.356119155883789, + "geometry_grad_norm": 7.0630364418029785, + "anchor_grad_norm": 0.3738804757595062, + "anchor_to_local_grad_ratio": 0.1586848795413971, + "anchor_vs_local_cosine": -0.0022364880423992872, + "anchor_vs_geometry_cosine": 0.8943203687667847 + }, + { + "position": 1100000, + "tile_id": "6f9b27e20e458fd91b99233a:48", + "local_pose_loss": 0.0735212042927742, + "geometry_loss": 0.07065758109092712, + "anchor_loss": 0.0018041033763438463, + "local_grad_norm": 1.6920182704925537, + "geometry_grad_norm": 5.193323612213135, + "anchor_grad_norm": 0.312919944524765, + "anchor_to_local_grad_ratio": 0.18493886291980743, + "anchor_vs_local_cosine": -0.043973758816719055, + "anchor_vs_geometry_cosine": 0.4725719392299652 + } + ], + "HOT3D": [ + { + "position": 20000, + "tile_id": "a431aedbaf7ba47abeb1138c:8", + "local_pose_loss": 0.0681307464838028, + "geometry_loss": 0.10136997699737549, + "anchor_loss": 0.003533046692609787, + "local_grad_norm": 2.0539636611938477, + "geometry_grad_norm": 9.084513664245605, + "anchor_grad_norm": 0.5756996870040894, + "anchor_to_local_grad_ratio": 0.2802871763706207, + "anchor_vs_local_cosine": -0.004463410936295986, + "anchor_vs_geometry_cosine": -0.44957777857780457 + }, + { + "position": 140001, + "tile_id": "6c757dada2fd37d1b8bf406d:0", + "local_pose_loss": 0.2878716289997101, + "geometry_loss": 1.4502663612365723, + "anchor_loss": 0.014260485768318176, + "local_grad_norm": 3.0126571655273438, + "geometry_grad_norm": 27.70813751220703, + "anchor_grad_norm": 0.5387464761734009, + "anchor_to_local_grad_ratio": 0.1788276731967926, + "anchor_vs_local_cosine": -0.04362852871417999, + "anchor_vs_geometry_cosine": -0.7896417379379272 + }, + { + "position": 260001, + "tile_id": "711e74dcb13d975659cd0a38:24", + "local_pose_loss": 0.12813399732112885, + "geometry_loss": 0.4180832505226135, + "anchor_loss": 0.010376217775046825, + "local_grad_norm": 1.8972419500350952, + "geometry_grad_norm": 11.819589614868164, + "anchor_grad_norm": 0.8191126585006714, + "anchor_to_local_grad_ratio": 0.43173864483833313, + "anchor_vs_local_cosine": -0.020804453641176224, + "anchor_vs_geometry_cosine": 0.8312544226646423 + }, + { + "position": 380001, + "tile_id": "0cd6b0032f64b42a4aed2215:8", + "local_pose_loss": 0.08627372235059738, + "geometry_loss": 0.46400195360183716, + "anchor_loss": 0.009702288545668125, + "local_grad_norm": 1.715224266052246, + "geometry_grad_norm": 12.492506980895996, + "anchor_grad_norm": 0.3872760236263275, + "anchor_to_local_grad_ratio": 0.22578740119934082, + "anchor_vs_local_cosine": -0.06527992337942123, + "anchor_vs_geometry_cosine": -0.3612949550151825 + }, + { + "position": 500000, + "tile_id": "9b5f2ea1ebc3946bbf0b75f2:16", + "local_pose_loss": 0.1109699085354805, + "geometry_loss": 0.38719186186790466, + "anchor_loss": 0.006356194149702787, + "local_grad_norm": 1.8318748474121094, + "geometry_grad_norm": 9.16281509399414, + "anchor_grad_norm": 0.42660999298095703, + "anchor_to_local_grad_ratio": 0.23288162052631378, + "anchor_vs_local_cosine": 0.010484008118510246, + "anchor_vs_geometry_cosine": 0.5247796773910522 + }, + { + "position": 620001, + "tile_id": "63dc0ace8fc425136887e3c1:24", + "local_pose_loss": 0.09437291324138641, + "geometry_loss": 0.10628461837768555, + "anchor_loss": 0.0037402042653411627, + "local_grad_norm": 1.8746986389160156, + "geometry_grad_norm": 6.168127059936523, + "anchor_grad_norm": 0.42599180340766907, + "anchor_to_local_grad_ratio": 0.22723214328289032, + "anchor_vs_local_cosine": -0.00433605769649148, + "anchor_vs_geometry_cosine": -0.41736215353012085 + }, + { + "position": 740001, + "tile_id": "c118b176bfec6916e158668d:8", + "local_pose_loss": 0.16657119989395142, + "geometry_loss": 0.13447938859462738, + "anchor_loss": 0.003906408790498972, + "local_grad_norm": 2.051363229751587, + "geometry_grad_norm": 6.934160232543945, + "anchor_grad_norm": 0.5514570474624634, + "anchor_to_local_grad_ratio": 0.26882466673851013, + "anchor_vs_local_cosine": 0.0008814058965072036, + "anchor_vs_geometry_cosine": -0.6860961318016052 + }, + { + "position": 860001, + "tile_id": "e4795a6c7764239fda34799c:32", + "local_pose_loss": 0.13614976406097412, + "geometry_loss": 0.15011896193027496, + "anchor_loss": 0.004984715487807989, + "local_grad_norm": 2.1711580753326416, + "geometry_grad_norm": 7.562813758850098, + "anchor_grad_norm": 0.5798943042755127, + "anchor_to_local_grad_ratio": 0.2670898735523224, + "anchor_vs_local_cosine": 0.0013118019560351968, + "anchor_vs_geometry_cosine": -0.22174981236457825 + }, + { + "position": 980000, + "tile_id": "0c420a9ede59514482f2488f:0", + "local_pose_loss": 0.14076675474643707, + "geometry_loss": 0.11299929767847061, + "anchor_loss": 0.0021188377868384123, + "local_grad_norm": 2.363576650619507, + "geometry_grad_norm": 4.158533096313477, + "anchor_grad_norm": 0.49521175026893616, + "anchor_to_local_grad_ratio": 0.2095179557800293, + "anchor_vs_local_cosine": 0.01103132776916027, + "anchor_vs_geometry_cosine": -0.3598203957080841 + }, + { + "position": 1100001, + "tile_id": "61637533eb709b4da8d63349:0", + "local_pose_loss": 0.09626153856515884, + "geometry_loss": 0.11011707782745361, + "anchor_loss": 0.00240068300627172, + "local_grad_norm": 1.8233362436294556, + "geometry_grad_norm": 6.464844703674316, + "anchor_grad_norm": 0.46792078018188477, + "anchor_to_local_grad_ratio": 0.2566289007663727, + "anchor_vs_local_cosine": -0.04961206018924713, + "anchor_vs_geometry_cosine": -0.6684687733650208 + } + ] + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/pose_gradients_n1_18k.json b/home/wuyifan/EgoNet_train_20261008/reports/pose_gradients_n1_18k.json new file mode 100644 index 0000000000000000000000000000000000000000..2f434c4f05bf7fa40110413fa3164180921f94a0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/pose_gradients_n1_18k.json @@ -0,0 +1,225 @@ +{ + "checkpoint": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0018000.pt", + "sha256": "07ffd4d5463d64e5762f9dfa268d6539bff28c4d4dcf078c85cd7d7f3b17af2b", + "update": 18000, + "role": "diagnostic_two_selected_hard_train_tiles_per_source_not_global_gradient", + "selection": "first two pose-valid tiles per source with N1 weight >1 among positions 0..239", + "sources": { + "H2O": [ + { + "sample_position": 1, + "tile_id": "ba01377a570eb2fef9642454:8", + "valid_pose_hands": 16, + "hard_weighted_hands": 8, + "maximum_weight": 2.0, + "mean_weight_valid": 1.5, + "loss_value": { + "local_pose": 0.056353915482759476, + "global_orientation": 0.008729033172130585, + "joint3d_root_relative": 0.02294144034385681, + "joint3d_camera": 0.025822892785072327, + "vertices_camera": 0.002495340071618557, + "reprojection": 0.0034758271649479866 + }, + "rotation_head_grad_norm": { + "local_pose": 1.5569015741348267, + "global_orientation": 1.863870620727539, + "joint3d_root_relative": 2.019885778427124, + "joint3d_camera": 2.2138993740081787, + "vertices_camera": 0.2042778879404068, + "reprojection": 0.2095838189125061 + }, + "cosine_with_local_pose": { + "global_orientation": 0.0, + "joint3d_root_relative": 0.11852435022592545, + "joint3d_camera": 0.08746501803398132, + "vertices_camera": 0.0824953094124794, + "reprojection": 0.06261003017425537 + }, + "n1_vs_n0_local_grad_norm_ratio": 1.1411255598068237, + "n1_vs_n0_local_grad_cosine": 0.959539532661438, + "n1_vs_n0_relative_grad_norm_ratio": 0.9397865533828735, + "n1_vs_n0_relative_grad_cosine": 0.9487369060516357 + }, + { + "sample_position": 3, + "tile_id": "fb77fbe2ddf439a073b02adb:32", + "valid_pose_hands": 16, + "hard_weighted_hands": 1, + "maximum_weight": 1.5, + "mean_weight_valid": 1.03125, + "loss_value": { + "local_pose": 0.0654071792960167, + "global_orientation": 0.01442898903042078, + "joint3d_root_relative": 0.0298750139772892, + "joint3d_camera": 0.030117101967334747, + "vertices_camera": 0.002958703553304076, + "reprojection": 0.0034149785060435534 + }, + "rotation_head_grad_norm": { + "local_pose": 1.5267282724380493, + "global_orientation": 2.027574300765991, + "joint3d_root_relative": 2.636686086654663, + "joint3d_camera": 2.0899319648742676, + "vertices_camera": 0.1969984918832779, + "reprojection": 0.2037210315465927 + }, + "cosine_with_local_pose": { + "global_orientation": 0.0, + "joint3d_root_relative": 0.08530503511428833, + "joint3d_camera": 0.1071624606847763, + "vertices_camera": 0.10325750708580017, + "reprojection": 0.12333694845438004 + }, + "n1_vs_n0_local_grad_norm_ratio": 1.0049601793289185, + "n1_vs_n0_local_grad_cosine": 0.9988285899162292, + "n1_vs_n0_relative_grad_norm_ratio": 0.9978987574577332, + "n1_vs_n0_relative_grad_cosine": 0.9983657002449036 + } + ], + "ARCTIC": [ + { + "sample_position": 0, + "tile_id": "dbf169215645e68fd79234a3:48", + "valid_pose_hands": 16, + "hard_weighted_hands": 8, + "maximum_weight": 2.0, + "mean_weight_valid": 1.5, + "loss_value": { + "local_pose": 0.16849157214164734, + "global_orientation": 0.01397999282926321, + "joint3d_root_relative": 0.041667308658361435, + "joint3d_camera": 0.04582028090953827, + "vertices_camera": 0.004467303398996592, + "reprojection": 0.004849448800086975 + }, + "rotation_head_grad_norm": { + "local_pose": 4.090594291687012, + "global_orientation": 2.0374794006347656, + "joint3d_root_relative": 2.3682656288146973, + "joint3d_camera": 4.328090667724609, + "vertices_camera": 0.4130864143371582, + "reprojection": 0.4290303885936737 + }, + "cosine_with_local_pose": { + "global_orientation": 0.0, + "joint3d_root_relative": 0.198123037815094, + "joint3d_camera": 0.08690277487039566, + "vertices_camera": 0.08503503352403641, + "reprojection": 0.10300387442111969 + }, + "n1_vs_n0_local_grad_norm_ratio": 1.2761329412460327, + "n1_vs_n0_local_grad_cosine": 0.9873416423797607, + "n1_vs_n0_relative_grad_norm_ratio": 0.753205418586731, + "n1_vs_n0_relative_grad_cosine": 0.9668904542922974 + }, + { + "sample_position": 8, + "tile_id": "116d532640d6e8172a332364:24", + "valid_pose_hands": 16, + "hard_weighted_hands": 8, + "maximum_weight": 1.5, + "mean_weight_valid": 1.25, + "loss_value": { + "local_pose": 0.10673493891954422, + "global_orientation": 0.017218006774783134, + "joint3d_root_relative": 0.02974129468202591, + "joint3d_camera": 0.040708284825086594, + "vertices_camera": 0.004026524722576141, + "reprojection": 0.0046590459533035755 + }, + "rotation_head_grad_norm": { + "local_pose": 3.264371871948242, + "global_orientation": 3.0783658027648926, + "joint3d_root_relative": 1.9306813478469849, + "joint3d_camera": 1.8808555603027344, + "vertices_camera": 0.18027877807617188, + "reprojection": 0.32736214995384216 + }, + "cosine_with_local_pose": { + "global_orientation": 0.0, + "joint3d_root_relative": 0.1585056185722351, + "joint3d_camera": 0.09423824399709702, + "vertices_camera": 0.0909535214304924, + "reprojection": 0.14429883658885956 + }, + "n1_vs_n0_local_grad_norm_ratio": 1.1408706903457642, + "n1_vs_n0_local_grad_cosine": 0.9913141131401062, + "n1_vs_n0_relative_grad_norm_ratio": 1.1399976015090942, + "n1_vs_n0_relative_grad_cosine": 0.9911050796508789 + } + ], + "HOT3D": [ + { + "sample_position": 2, + "tile_id": "29056989df652e4096f8e73f:48", + "valid_pose_hands": 16, + "hard_weighted_hands": 15, + "maximum_weight": 2.0, + "mean_weight_valid": 1.53125, + "loss_value": { + "local_pose": 0.06791022419929504, + "global_orientation": 0.03178030624985695, + "joint3d_root_relative": 0.05743971839547157, + "joint3d_camera": 0.0540565624833107, + "vertices_camera": 0.005340352654457092, + "reprojection": 0.004041692707687616 + }, + "rotation_head_grad_norm": { + "local_pose": 1.7977545261383057, + "global_orientation": 3.731436252593994, + "joint3d_root_relative": 6.164747714996338, + "joint3d_camera": 4.195086479187012, + "vertices_camera": 0.38109996914863586, + "reprojection": 0.6575700044631958 + }, + "cosine_with_local_pose": { + "global_orientation": 0.0, + "joint3d_root_relative": 0.030829060822725296, + "joint3d_camera": 0.028610138222575188, + "vertices_camera": 0.030715838074684143, + "reprojection": 0.022088993340730667 + }, + "n1_vs_n0_local_grad_norm_ratio": 1.0066823959350586, + "n1_vs_n0_local_grad_cosine": 0.9981759786605835, + "n1_vs_n0_relative_grad_norm_ratio": 1.0271309614181519, + "n1_vs_n0_relative_grad_cosine": 0.9982463717460632 + }, + { + "sample_position": 4, + "tile_id": "fa7c6e6c888e0a036aaa76b4:16", + "valid_pose_hands": 16, + "hard_weighted_hands": 8, + "maximum_weight": 2.0, + "mean_weight_valid": 1.28125, + "loss_value": { + "local_pose": 0.08485407382249832, + "global_orientation": 0.0367593914270401, + "joint3d_root_relative": 0.07618457078933716, + "joint3d_camera": 0.08391427993774414, + "vertices_camera": 0.008254489861428738, + "reprojection": 0.012388057075440884 + }, + "rotation_head_grad_norm": { + "local_pose": 1.6658612489700317, + "global_orientation": 3.316358804702759, + "joint3d_root_relative": 5.702782154083252, + "joint3d_camera": 3.853961706161499, + "vertices_camera": 0.3676556646823883, + "reprojection": 0.5701465606689453 + }, + "cosine_with_local_pose": { + "global_orientation": 0.0, + "joint3d_root_relative": 0.04316824674606323, + "joint3d_camera": 0.04122979938983917, + "vertices_camera": 0.039649683982133865, + "reprojection": 0.03825988620519638 + }, + "n1_vs_n0_local_grad_norm_ratio": 1.0390146970748901, + "n1_vs_n0_local_grad_cosine": 0.9748757481575012, + "n1_vs_n0_relative_grad_norm_ratio": 0.8908782005310059, + "n1_vs_n0_relative_grad_cosine": 0.9887104034423828 + } + ] + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_arctic_12k18k.json b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_arctic_12k18k.json new file mode 100644 index 0000000000000000000000000000000000000000..7b9d284d8cb4ed4b6ac6091237951f130b7b55b2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_arctic_12k18k.json @@ -0,0 +1,6979 @@ +{ + "source": "ARCTIC", + "role": "development", + "input_mode": "rgb", + "gt": "source_native_not_refitted", + "clips": 136, + "panel_sha256": "780737bf04f0b31796976dc7e7a01971eef2f96cf44f9b2d2641d61708c49683", + "parent_checkpoint_sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a", + "checkpoints": { + "U0_parent": { + "path": "/home/wuyifan/unified_mot_u0_depthsafe_20261001/runs/U0/update_0020004.pt", + "sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a" + }, + "N0_12K": { + "path": "/home/wuyifan/u0_normalized6d_20261002/runs/N0_formal/update_0012000.pt", + "sha256": "f6cf83fc77f577153bfaa71c16717fa36b04bf1639f924a27f137925e73a9a00" + }, + "N0_18K": { + "path": "/home/wuyifan/u0_normalized6d_20261002/runs/N0_formal/update_0018000.pt", + "sha256": "3d176e8949c5738c0ae19690e528968071734f439b7a5efb47d27db954a1feea" + }, + "N1_12K": { + "path": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0012000.pt", + "sha256": "ebe561dbf78d6488180c5f5ee0381432bf739e7a0f68961752d28986210d4958" + }, + "N1_18K": { + "path": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0018000.pt", + "sha256": "07ffd4d5463d64e5762f9dfa268d6539bff28c4d4dcf078c85cd7d7f3b17af2b" + } + }, + "hard_definition": "GT >=2 non-thumb distal angles >=45deg OR >=1 >=60deg; complete 21-joint geometry and MANO pose only", + "groups": { + "all": { + "hands": 1568, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 767, + "variance": 0.6041206514557352 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 767, + "variance": 0.42622491017607517 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 767, + "variance": 0.36013793956825124 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 767, + "variance": 0.16537945493992876 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 767, + "variance": 0.6986380897862388 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 767, + "variance": 0.32717479619499984 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 767, + "variance": 0.11479048415862723 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 767, + "variance": 1.167599519374319 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 767, + "variance": 0.8466303804649719 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 767, + "variance": 0.52456643352366 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 767, + "variance": 0.6685087062162507 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 767, + "variance": 0.7064156976466149 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 767, + "variance": 0.23052468668921106 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 767, + "variance": 0.24381033322493656 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 767, + "variance": 0.32886345901547964 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 767, + "variance": 0.44479070634385803 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 801, + "variance": 0.7087786381727638 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 801, + "variance": 0.3959572086166194 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 801, + "variance": 0.3554500392924433 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 801, + "variance": 0.18899980206505118 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 801, + "variance": 0.7016650020022339 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 801, + "variance": 0.3615881996184217 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 801, + "variance": 0.07292192902480385 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 801, + "variance": 1.0068298690770092 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 801, + "variance": 0.6310660433105342 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 801, + "variance": 0.47947190051608823 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 801, + "variance": 0.6657770069032021 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 801, + "variance": 0.4545595117883542 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 801, + "variance": 0.13893213807109603 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 801, + "variance": 0.2726204271078565 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 801, + "variance": 0.3773495194787544 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 801, + "variance": 0.47425826504130897 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.62759631294377, + "count": 1568 + }, + "root_relative_mpjpe_mm": { + "mean": 20.916816820599596, + "count": 1568 + }, + "mpvpe_mm": { + "mean": 34.19091033296926, + "count": 1568 + }, + "projected_mano_2d_error_px": { + "mean": 17.01909283338449, + "count": 1560 + }, + "local_pose_angle_deg": { + "mean": 24.339378317399902, + "count": 1568 + }, + "root_relative_fingertip_mm": { + "mean": 31.318568994804306, + "count": 1568 + }, + "distal_angle_bias_deg": { + "mean": -4.111982597152189, + "count": 1568 + }, + "distal_angle_mae_deg": { + "mean": 11.895296396193455, + "count": 1568 + }, + "gt60_angle_bias_deg": { + "mean": -31.212367823693604, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 21.097496747210318, + 18.24508785540048, + 13.8429469072393, + 25.46307769927139, + 19.707462538717962, + 11.717333851572203, + 42.689524243984906, + 42.541036103909114, + 36.21159382483789, + 26.673233333594943, + 25.219032170517103, + 15.216072100955916, + 17.53362161692764, + 22.536071663912463, + 26.397065003003394 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6127992698358318, + "mean_abs_log_variance_ratio": 0.5727506075921863, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6041206514557352, + "pred_variance_6d": 0.5511921482978331, + "pred_gt_ratio": 0.9123875288315976 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.42622491017607517, + "pred_variance_6d": 0.343832062740217, + "pred_gt_ratio": 0.806691618746963 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.36013793956825124, + "pred_variance_6d": 0.2278303826675563, + "pred_gt_ratio": 0.6326197760244009 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.16537945493992876, + "pred_variance_6d": 0.09246536513402062, + "pred_gt_ratio": 0.5591103512078153 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6986380897862388, + "pred_variance_6d": 0.5655322393141939, + "pred_gt_ratio": 0.809478108311027 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32717479619499984, + "pred_variance_6d": 0.1747461663296579, + "pred_gt_ratio": 0.5341064420668492 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.11479048415862723, + "pred_variance_6d": 0.02814959863873967, + "pred_gt_ratio": 0.24522588997743197 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 767, + "gt_variance_6d": 1.167599519374319, + "pred_variance_6d": 0.6249371483547054, + "pred_gt_ratio": 0.5352324474144955 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.8466303804649719, + "pred_variance_6d": 0.31838304417774876, + "pred_gt_ratio": 0.37605908259858556 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.52456643352366, + "pred_variance_6d": 0.22408176886037884, + "pred_gt_ratio": 0.42717519562805173 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6685087062162507, + "pred_variance_6d": 0.4820572704361744, + "pred_gt_ratio": 0.721093481586218 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.7064156976466149, + "pred_variance_6d": 0.1446451660138487, + "pred_gt_ratio": 0.204759274879828 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.23052468668921106, + "pred_variance_6d": 0.04911983045416895, + "pred_gt_ratio": 0.2130783958960168 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.24381033322493656, + "pred_variance_6d": 0.19683342044901647, + "pred_gt_ratio": 0.807321895858369 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32886345901547964, + "pred_variance_6d": 0.19762559162455529, + "pred_gt_ratio": 0.6009350878209093 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.44479070634385803, + "pred_variance_6d": 0.24884508283076612, + "pred_gt_ratio": 0.5594655627502914 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7087786381727638, + "pred_variance_6d": 0.6379052134292298, + "pred_gt_ratio": 0.9000062629903094 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3959572086166194, + "pred_variance_6d": 0.28504180565638526, + "pred_gt_ratio": 0.7198803291200423 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3554500392924433, + "pred_variance_6d": 0.21509276427469928, + "pred_gt_ratio": 0.6051279800189687 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.18899980206505118, + "pred_variance_6d": 0.11812940136558889, + "pred_gt_ratio": 0.625023942220481 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7016650020022339, + "pred_variance_6d": 0.45061457661413523, + "pred_gt_ratio": 0.642207571032167 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3615881996184217, + "pred_variance_6d": 0.2728452644411343, + "pred_gt_ratio": 0.7545745816070978 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.07292192902480385, + "pred_variance_6d": 0.04613344806403579, + "pred_gt_ratio": 0.6326416303159484 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 801, + "gt_variance_6d": 1.0068298690770092, + "pred_variance_6d": 0.5024081879929398, + "pred_gt_ratio": 0.499000082758284 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6310660433105342, + "pred_variance_6d": 0.23676330303813614, + "pred_gt_ratio": 0.37517991270151413 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47947190051608823, + "pred_variance_6d": 0.22678861157004102, + "pred_gt_ratio": 0.4729966684719855 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6657770069032021, + "pred_variance_6d": 0.40387497423120194, + "pred_gt_ratio": 0.6066219921138275 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.4545595117883542, + "pred_variance_6d": 0.14379636279023578, + "pred_gt_ratio": 0.3163422149599375 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.13893213807109603, + "pred_variance_6d": 0.09100196407306194, + "pred_gt_ratio": 0.6550101750143176 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.2726204271078565, + "pred_variance_6d": 0.27561943585259463, + "pred_gt_ratio": 1.011000675101839 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3773495194787544, + "pred_variance_6d": 0.4217514916829631, + "pred_gt_ratio": 1.1176680237079477 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47425826504130897, + "pred_variance_6d": 0.3469457456692362, + "pred_gt_ratio": 0.7315544530130992 + } + ] + } + }, + "N0_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 33.568893415283185, + "count": 1568 + }, + "root_relative_mpjpe_mm": { + "mean": 20.647442600252678, + "count": 1568 + }, + "mpvpe_mm": { + "mean": 33.16526616896902, + "count": 1568 + }, + "projected_mano_2d_error_px": { + "mean": 17.580274297946538, + "count": 1560 + }, + "local_pose_angle_deg": { + "mean": 24.28364493834729, + "count": 1568 + }, + "root_relative_fingertip_mm": { + "mean": 30.95043098804902, + "count": 1568 + }, + "distal_angle_bias_deg": { + "mean": -3.9135305570932677, + "count": 1568 + }, + "distal_angle_mae_deg": { + "mean": 11.865123873158376, + "count": 1568 + }, + "gt60_angle_bias_deg": { + "mean": -30.747976674442796, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 20.934439233523243, + 18.2665588883493, + 13.836838042268491, + 25.356161308607884, + 19.495651778822044, + 11.784756258415172, + 42.52906485799016, + 42.44900956217732, + 36.83102095856958, + 26.325580478170696, + 25.006124623652017, + 15.21121488652211, + 17.283944991322198, + 22.443100939979967, + 26.50118849715408 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -1.0587028976605863, + "recording_bootstrap_95ci": [ + -1.5523894885868341, + -0.5304283514586438 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.26937422034691794, + "recording_bootstrap_95ci": [ + -0.3703376258482506, + -0.17327326926513884 + ], + "count": 1568, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": -1.0256441640002387, + "recording_bootstrap_95ci": [ + -1.5193612970591184, + -0.5005717145076426 + ], + "count": 1568, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.5611814645620493, + "recording_bootstrap_95ci": [ + 0.3387387128210024, + 0.7647997781998137 + ], + "count": 1560, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": -0.05573337905260981, + "recording_bootstrap_95ci": [ + -0.13414466865689384, + 0.016319737663971903 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.3681380067552839, + "recording_bootstrap_95ci": [ + -0.5311420946639611, + -0.21250630139387203 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.1984520400589218, + "recording_bootstrap_95ci": [ + 0.051483650595239905, + 0.34920417959746886 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": -0.030172523035078634, + "recording_bootstrap_95ci": [ + -0.09358866240521002, + 0.03504264251388507 + ], + "count": 1568, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 0.46439114925080693, + "recording_bootstrap_95ci": [ + -0.0018613742554888992, + 1.021192589018249 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6300432794771313, + "mean_abs_log_variance_ratio": 0.5349491040769238, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6041206514557352, + "pred_variance_6d": 0.5533082210334855, + "pred_gt_ratio": 0.9158902608281836 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.42622491017607517, + "pred_variance_6d": 0.3446497358275106, + "pred_gt_ratio": 0.8086100263007491 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.36013793956825124, + "pred_variance_6d": 0.23209869939095445, + "pred_gt_ratio": 0.6444716701306291 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.16537945493992876, + "pred_variance_6d": 0.10188241288549005, + "pred_gt_ratio": 0.6160524166831792 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6986380897862388, + "pred_variance_6d": 0.5708244735778922, + "pred_gt_ratio": 0.8170531809288362 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32717479619499984, + "pred_variance_6d": 0.1877411014245793, + "pred_gt_ratio": 0.5738250733491205 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.11479048415862723, + "pred_variance_6d": 0.031823799365043426, + "pred_gt_ratio": 0.2772337759379654 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 767, + "gt_variance_6d": 1.167599519374319, + "pred_variance_6d": 0.6348506125059178, + "pred_gt_ratio": 0.5437229135261334 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.8466303804649719, + "pred_variance_6d": 0.3418143266504382, + "pred_gt_ratio": 0.4037350118037493 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.52456643352366, + "pred_variance_6d": 0.2294226951807355, + "pred_gt_ratio": 0.43735679700212393 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6685087062162507, + "pred_variance_6d": 0.4876087087495672, + "pred_gt_ratio": 0.7293976940246975 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.7064156976466149, + "pred_variance_6d": 0.16170533038869617, + "pred_gt_ratio": 0.2289095937808412 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.23052468668921106, + "pred_variance_6d": 0.05506531014857395, + "pred_gt_ratio": 0.23886947180981072 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.24381033322493656, + "pred_variance_6d": 0.19932492282882697, + "pred_gt_ratio": 0.817540914662268 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32886345901547964, + "pred_variance_6d": 0.19536567145587136, + "pred_gt_ratio": 0.5940631775896862 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.44479070634385803, + "pred_variance_6d": 0.25858850329907523, + "pred_gt_ratio": 0.5813711923629225 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7087786381727638, + "pred_variance_6d": 0.6389805936931782, + "pred_gt_ratio": 0.9015234930619165 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3959572086166194, + "pred_variance_6d": 0.29549239288406043, + "pred_gt_ratio": 0.7462735529337646 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3554500392924433, + "pred_variance_6d": 0.2215828197356833, + "pred_gt_ratio": 0.6233866795366368 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.18899980206505118, + "pred_variance_6d": 0.1217809876341753, + "pred_gt_ratio": 0.6443445247220944 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7016650020022339, + "pred_variance_6d": 0.4693491605328686, + "pred_gt_ratio": 0.668907753975984 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3615881996184217, + "pred_variance_6d": 0.27693472176993744, + "pred_gt_ratio": 0.7658842906438381 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.07292192902480385, + "pred_variance_6d": 0.04684583601616353, + "pred_gt_ratio": 0.6424108171936767 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 801, + "gt_variance_6d": 1.0068298690770092, + "pred_variance_6d": 0.5235854622965401, + "pred_gt_ratio": 0.5200337002084835 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6310660433105342, + "pred_variance_6d": 0.24581851618810172, + "pred_gt_ratio": 0.38952898637764233 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47947190051608823, + "pred_variance_6d": 0.2424813498961034, + "pred_gt_ratio": 0.5057258822364861 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6657770069032021, + "pred_variance_6d": 0.42222496266291776, + "pred_gt_ratio": 0.6341837556494428 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.4545595117883542, + "pred_variance_6d": 0.15933727050356, + "pred_gt_ratio": 0.35053115460434686 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.13893213807109603, + "pred_variance_6d": 0.0971409886786747, + "pred_gt_ratio": 0.6991973925353725 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.2726204271078565, + "pred_variance_6d": 0.2725446326641188, + "pred_gt_ratio": 0.9997219781197552 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3773495194787544, + "pred_variance_6d": 0.42669458209062106, + "pred_gt_ratio": 1.1307675247076734 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47425826504130897, + "pred_variance_6d": 0.337131365944191, + "pred_gt_ratio": 0.710860286040194 + } + ] + } + }, + "N0_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.9985530130109, + "count": 1568 + }, + "root_relative_mpjpe_mm": { + "mean": 20.67019370654408, + "count": 1568 + }, + "mpvpe_mm": { + "mean": 34.57041943985589, + "count": 1568 + }, + "projected_mano_2d_error_px": { + "mean": 17.433100311572733, + "count": 1560 + }, + "local_pose_angle_deg": { + "mean": 24.285094640692886, + "count": 1568 + }, + "root_relative_fingertip_mm": { + "mean": 30.944099720643493, + "count": 1568 + }, + "distal_angle_bias_deg": { + "mean": -3.7099482228561325, + "count": 1568 + }, + "distal_angle_mae_deg": { + "mean": 11.893110788750406, + "count": 1568 + }, + "gt60_angle_bias_deg": { + "mean": -29.79891960599781, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 20.82966265188796, + 18.437988722373788, + 13.956369825182673, + 25.17310384501304, + 19.56501116231084, + 11.790683284097788, + 42.39888086626116, + 42.42193102441272, + 36.64586655217774, + 26.236035650405956, + 25.017038013405944, + 15.166358125681171, + 17.387783327425012, + 22.617380752627337, + 26.632307241461714 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.3709567000671309, + "recording_bootstrap_95ci": [ + 0.060606385605416827, + 0.6799666429431821 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.24662311405551676, + "recording_bootstrap_95ci": [ + -0.34668556709221393, + -0.14049258141209206 + ], + "count": 1568, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": 0.37950910688663014, + "recording_bootstrap_95ci": [ + 0.07299648264088743, + 0.6846737468728102 + ], + "count": 1568, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.41400747818824574, + "recording_bootstrap_95ci": [ + 0.16771965499458133, + 0.67093999202556 + ], + "count": 1560, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": -0.05428367670701475, + "recording_bootstrap_95ci": [ + -0.14949804363881722, + 0.038868131803375144 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.3744692741608133, + "recording_bootstrap_95ci": [ + -0.5238675002367109, + -0.2009983598031158 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.402034374296057, + "recording_bootstrap_95ci": [ + 0.2522250749371169, + 0.5736965967654276 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": -0.002185607443050462, + "recording_bootstrap_95ci": [ + -0.11036062123771856, + 0.09312263930308291 + ], + "count": 1568, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 1.4134482176957932, + "recording_bootstrap_95ci": [ + 0.7464650688351213, + 1.9848519907482343 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6393407976652585, + "mean_abs_log_variance_ratio": 0.5243960130274068, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6041206514557352, + "pred_variance_6d": 0.5526527362414613, + "pred_gt_ratio": 0.9148052378440417 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.42622491017607517, + "pred_variance_6d": 0.35162028417208113, + "pred_gt_ratio": 0.8249641815322935 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.36013793956825124, + "pred_variance_6d": 0.24732470274976356, + "pred_gt_ratio": 0.6867499243380661 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.16537945493992876, + "pred_variance_6d": 0.1085390561233759, + "pred_gt_ratio": 0.6563031433547828 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6986380897862388, + "pred_variance_6d": 0.566407106047621, + "pred_gt_ratio": 0.8107303542824636 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32717479619499984, + "pred_variance_6d": 0.1876788683989059, + "pred_gt_ratio": 0.5736348599635016 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.11479048415862723, + "pred_variance_6d": 0.031906451026654487, + "pred_gt_ratio": 0.2779537978301707 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 767, + "gt_variance_6d": 1.167599519374319, + "pred_variance_6d": 0.6434741187268481, + "pred_gt_ratio": 0.5511085847925549 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.8466303804649719, + "pred_variance_6d": 0.34986574546779353, + "pred_gt_ratio": 0.4132449691631031 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.52456643352366, + "pred_variance_6d": 0.2353076288452013, + "pred_gt_ratio": 0.4485754592884907 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6685087062162507, + "pred_variance_6d": 0.48224328632810576, + "pred_gt_ratio": 0.721371736589035 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.7064156976466149, + "pred_variance_6d": 0.16445223863024952, + "pred_gt_ratio": 0.23279810907106555 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.23052468668921106, + "pred_variance_6d": 0.05501994324315366, + "pred_gt_ratio": 0.23867267334075368 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.24381033322493656, + "pred_variance_6d": 0.20382178277284796, + "pred_gt_ratio": 0.8359850055444712 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32886345901547964, + "pred_variance_6d": 0.2023201773499122, + "pred_gt_ratio": 0.61521026980498 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.44479070634385803, + "pred_variance_6d": 0.26377576329191804, + "pred_gt_ratio": 0.5930334414136763 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7087786381727638, + "pred_variance_6d": 0.6448223531471164, + "pred_gt_ratio": 0.9097655014116579 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3959572086166194, + "pred_variance_6d": 0.30268814655262116, + "pred_gt_ratio": 0.7644466118198523 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3554500392924433, + "pred_variance_6d": 0.23047061148254144, + "pred_gt_ratio": 0.6483910142233065 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.18899980206505118, + "pred_variance_6d": 0.12474593348363003, + "pred_gt_ratio": 0.6600320853282913 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7016650020022339, + "pred_variance_6d": 0.47741847925992853, + "pred_gt_ratio": 0.6804079979728112 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3615881996184217, + "pred_variance_6d": 0.278033190779697, + "pred_gt_ratio": 0.7689221912471177 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.07292192902480385, + "pred_variance_6d": 0.04638186679789316, + "pred_gt_ratio": 0.6360482699534281 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 801, + "gt_variance_6d": 1.0068298690770092, + "pred_variance_6d": 0.5235082422934059, + "pred_gt_ratio": 0.5199570040302056 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6310660433105342, + "pred_variance_6d": 0.2404302621307599, + "pred_gt_ratio": 0.38099065015363104 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47947190051608823, + "pred_variance_6d": 0.24014142344269493, + "pred_gt_ratio": 0.5008456662094575 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6657770069032021, + "pred_variance_6d": 0.42878612208151967, + "pred_gt_ratio": 0.6440386460265085 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.4545595117883542, + "pred_variance_6d": 0.15702938369661107, + "pred_gt_ratio": 0.34545396064602635 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.13893213807109603, + "pred_variance_6d": 0.09541631160837494, + "pred_gt_ratio": 0.6867835832163423 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.2726204271078565, + "pred_variance_6d": 0.27477483920970347, + "pred_gt_ratio": 1.0079026070228942 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3773495194787544, + "pred_variance_6d": 0.4420708302859565, + "pred_gt_ratio": 1.1715155511436819 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47425826504130897, + "pred_variance_6d": 0.35012706238855534, + "pred_gt_ratio": 0.7382624367296129 + } + ] + } + }, + "N1_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 33.64776532382381, + "count": 1568 + }, + "root_relative_mpjpe_mm": { + "mean": 20.639559907876716, + "count": 1568 + }, + "mpvpe_mm": { + "mean": 33.24083111389559, + "count": 1568 + }, + "projected_mano_2d_error_px": { + "mean": 17.509042078715105, + "count": 1560 + }, + "local_pose_angle_deg": { + "mean": 24.379377404037786, + "count": 1568 + }, + "root_relative_fingertip_mm": { + "mean": 30.923910052192454, + "count": 1568 + }, + "distal_angle_bias_deg": { + "mean": -3.6260357416824114, + "count": 1568 + }, + "distal_angle_mae_deg": { + "mean": 11.912355888254789, + "count": 1568 + }, + "gt60_angle_bias_deg": { + "mean": -29.891554515973656, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 21.08659000938036, + 18.51346337553874, + 13.875377966053023, + 25.53951024613818, + 19.810556658980797, + 11.821655348893636, + 42.61198058169411, + 42.57565030440384, + 36.88893551196979, + 26.4207673662019, + 25.040530208954397, + 15.224825925706904, + 17.270395143603793, + 22.47995116105493, + 26.530451560963172 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.9798309891199579, + "recording_bootstrap_95ci": [ + -1.4358673206321884, + -0.491979057520532 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.2772569127228795, + "recording_bootstrap_95ci": [ + -0.37379201653628413, + -0.18283648883077241 + ], + "count": 1568, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": -0.9500792190736654, + "recording_bootstrap_95ci": [ + -1.409010167222469, + -0.46411561981678257 + ], + "count": 1568, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.4899492453306149, + "recording_bootstrap_95ci": [ + 0.27061229382163315, + 0.6858520772186975 + ], + "count": 1560, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": 0.039999086637886205, + "recording_bootstrap_95ci": [ + -0.05248090110427886, + 0.13290110160937715 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.39465894261185, + "recording_bootstrap_95ci": [ + -0.5461601377436881, + -0.2458652273006595 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.4859468554697779, + "recording_bootstrap_95ci": [ + 0.288451468721049, + 0.7071771374061587 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": 0.01705949206133278, + "recording_bootstrap_95ci": [ + -0.08445191850880654, + 0.11646847429336374 + ], + "count": 1568, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 1.320813307719948, + "recording_bootstrap_95ci": [ + 0.6492644162449839, + 2.1405976400832936 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6345344499335118, + "mean_abs_log_variance_ratio": 0.5250851416479446, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6041206514557352, + "pred_variance_6d": 0.5531068830694359, + "pred_gt_ratio": 0.9155569864010232 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.42622491017607517, + "pred_variance_6d": 0.3444160962266369, + "pred_gt_ratio": 0.8080618659391757 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.36013793956825124, + "pred_variance_6d": 0.24241272326448388, + "pred_gt_ratio": 0.6731107629346095 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.16537945493992876, + "pred_variance_6d": 0.10238877229018269, + "pred_gt_ratio": 0.6191142202480571 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6986380897862388, + "pred_variance_6d": 0.5715292397864109, + "pred_gt_ratio": 0.818061952449917 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32717479619499984, + "pred_variance_6d": 0.1937360626793717, + "pred_gt_ratio": 0.5921484935040744 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.11479048415862723, + "pred_variance_6d": 0.032305231437095586, + "pred_gt_ratio": 0.2814277827459415 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 767, + "gt_variance_6d": 1.167599519374319, + "pred_variance_6d": 0.6398500100232141, + "pred_gt_ratio": 0.548004687742669 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.8466303804649719, + "pred_variance_6d": 0.3433281636176363, + "pred_gt_ratio": 0.4055230848544314 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.52456643352366, + "pred_variance_6d": 0.23096978285766318, + "pred_gt_ratio": 0.44030606629969504 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6685087062162507, + "pred_variance_6d": 0.4879611926084274, + "pred_gt_ratio": 0.7299249629377013 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.7064156976466149, + "pred_variance_6d": 0.1656509300330476, + "pred_gt_ratio": 0.23449497312263098 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.23052468668921106, + "pred_variance_6d": 0.056163772398486383, + "pred_gt_ratio": 0.24363452437614763 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.24381033322493656, + "pred_variance_6d": 0.19905456948235745, + "pred_gt_ratio": 0.8164320471959325 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32886345901547964, + "pred_variance_6d": 0.1942879226425603, + "pred_gt_ratio": 0.5907859852359431 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.44479070634385803, + "pred_variance_6d": 0.25992735598820826, + "pred_gt_ratio": 0.5843812657975459 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7087786381727638, + "pred_variance_6d": 0.6397823591348967, + "pred_gt_ratio": 0.9026546860727349 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3959572086166194, + "pred_variance_6d": 0.2955140381413483, + "pred_gt_ratio": 0.7463282185815084 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3554500392924433, + "pred_variance_6d": 0.22764304314508452, + "pred_gt_ratio": 0.6404361175433526 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.18899980206505118, + "pred_variance_6d": 0.12212271708633056, + "pred_gt_ratio": 0.6461526189551118 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7016650020022339, + "pred_variance_6d": 0.4721762212302122, + "pred_gt_ratio": 0.672936828661591 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3615881996184217, + "pred_variance_6d": 0.28664746962848875, + "pred_gt_ratio": 0.7927456425043276 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.07292192902480385, + "pred_variance_6d": 0.04643606538296274, + "pred_gt_ratio": 0.6367915111950462 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 801, + "gt_variance_6d": 1.0068298690770092, + "pred_variance_6d": 0.5209606487570843, + "pred_gt_ratio": 0.5174266921924598 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6310660433105342, + "pred_variance_6d": 0.25293551488009525, + "pred_gt_ratio": 0.400806726271011 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47947190051608823, + "pred_variance_6d": 0.24769417724201287, + "pred_gt_ratio": 0.5165979006807339 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6657770069032021, + "pred_variance_6d": 0.420377642993851, + "pred_gt_ratio": 0.6314090733610602 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.4545595117883542, + "pred_variance_6d": 0.1661732019174174, + "pred_gt_ratio": 0.3655697386325703 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.13893213807109603, + "pred_variance_6d": 0.09701521355220816, + "pred_gt_ratio": 0.6982920935295933 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.2726204271078565, + "pred_variance_6d": 0.2726714560916467, + "pred_gt_ratio": 1.0001871796047406 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3773495194787544, + "pred_variance_6d": 0.422922346964256, + "pred_gt_ratio": 1.1207708639683784 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47425826504130897, + "pred_variance_6d": 0.33910739065117146, + "pred_gt_ratio": 0.7150268443326643 + } + ] + } + }, + "N1_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.959198021767094, + "count": 1568 + }, + "root_relative_mpjpe_mm": { + "mean": 20.637158096140745, + "count": 1568 + }, + "mpvpe_mm": { + "mean": 34.52933551462329, + "count": 1568 + }, + "projected_mano_2d_error_px": { + "mean": 17.445022100974352, + "count": 1560 + }, + "local_pose_angle_deg": { + "mean": 24.382051250764302, + "count": 1568 + }, + "root_relative_fingertip_mm": { + "mean": 30.87382767030171, + "count": 1568 + }, + "distal_angle_bias_deg": { + "mean": -3.40300710275009, + "count": 1568 + }, + "distal_angle_mae_deg": { + "mean": 11.934690199184175, + "count": 1568 + }, + "gt60_angle_bias_deg": { + "mean": -28.73902339217937, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 20.967253548302214, + 18.73584934757376, + 14.00986350512094, + 25.37066602212738, + 19.84382816388899, + 11.812480760662227, + 42.449832737293775, + 42.51275628364208, + 36.778752132033816, + 26.344005396703675, + 25.005171060486106, + 15.177103170516844, + 17.395373489327575, + 22.66500202300293, + 26.662812104942848 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.3316017088233208, + "recording_bootstrap_95ci": [ + 0.027786494416631485, + 0.6395671984222852 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.27965872445885015, + "recording_bootstrap_95ci": [ + -0.3767310098562598, + -0.18142756437776256 + ], + "count": 1568, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": 0.33842518165403485, + "recording_bootstrap_95ci": [ + 0.03572256801533583, + 0.6445343898982585 + ], + "count": 1568, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.42592926758986255, + "recording_bootstrap_95ci": [ + 0.19453936691271848, + 0.665120916258671 + ], + "count": 1560, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": 0.04267293336440106, + "recording_bootstrap_95ci": [ + -0.07431334506820582, + 0.14973408169722913 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.4447413245025946, + "recording_bootstrap_95ci": [ + -0.6029062579711291, + -0.279463441807765 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.7089754944020996, + "recording_bootstrap_95ci": [ + 0.5229286927364484, + 0.9240697014360171 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": 0.03939380299071876, + "recording_bootstrap_95ci": [ + -0.12023461313852357, + 0.17700829164962334 + ], + "count": 1568, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 2.4733444315142337, + "recording_bootstrap_95ci": [ + 1.6777230725446826, + 3.3333754783194447 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6463068206384341, + "mean_abs_log_variance_ratio": 0.5105327444469089, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6041206514557352, + "pred_variance_6d": 0.5526373703221251, + "pred_gt_ratio": 0.9147798026610213 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.42622491017607517, + "pred_variance_6d": 0.35422403456975204, + "pred_gt_ratio": 0.8310730464425946 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.36013793956825124, + "pred_variance_6d": 0.2616492117378721, + "pred_gt_ratio": 0.7265249866524709 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.16537945493992876, + "pred_variance_6d": 0.11002327026934207, + "pred_gt_ratio": 0.6652777414782636 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6986380897862388, + "pred_variance_6d": 0.5676901096491884, + "pred_gt_ratio": 0.8125667895131279 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32717479619499984, + "pred_variance_6d": 0.19551399082101228, + "pred_gt_ratio": 0.5975826778065256 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.11479048415862723, + "pred_variance_6d": 0.032392478242344216, + "pred_gt_ratio": 0.2821878353399184 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 767, + "gt_variance_6d": 1.167599519374319, + "pred_variance_6d": 0.6502472194869172, + "pred_gt_ratio": 0.5569094614182137 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.8466303804649719, + "pred_variance_6d": 0.3573886862301458, + "pred_gt_ratio": 0.42213071309095584 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.52456643352366, + "pred_variance_6d": 0.24142347137461834, + "pred_gt_ratio": 0.4602343115111448 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6685087062162507, + "pred_variance_6d": 0.4830099227456633, + "pred_gt_ratio": 0.7225185225776524 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.7064156976466149, + "pred_variance_6d": 0.17225572314306292, + "pred_gt_ratio": 0.24384469897388095 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.23052468668921106, + "pred_variance_6d": 0.05666148924480715, + "pred_gt_ratio": 0.24579358531434456 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.24381033322493656, + "pred_variance_6d": 0.20354702250437215, + "pred_gt_ratio": 0.8348580628721017 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32886345901547964, + "pred_variance_6d": 0.2006456276386373, + "pred_gt_ratio": 0.6101183398098141 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.44479070634385803, + "pred_variance_6d": 0.26498989835607667, + "pred_gt_ratio": 0.5957631186457811 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7087786381727638, + "pred_variance_6d": 0.6450048780379266, + "pred_gt_ratio": 0.9100230217162776 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3959572086166194, + "pred_variance_6d": 0.30391418738340725, + "pred_gt_ratio": 0.7675430091176048 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3554500392924433, + "pred_variance_6d": 0.23909585305917663, + "pred_gt_ratio": 0.6726567073536394 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.18899980206505118, + "pred_variance_6d": 0.12652880075546813, + "pred_gt_ratio": 0.6694652553758688 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7016650020022339, + "pred_variance_6d": 0.48095222401349047, + "pred_gt_ratio": 0.6854442257217772 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3615881996184217, + "pred_variance_6d": 0.289421885321159, + "pred_gt_ratio": 0.8004185026684535 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.07292192902480385, + "pred_variance_6d": 0.045689389934622904, + "pred_gt_ratio": 0.626552129731538 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 801, + "gt_variance_6d": 1.0068298690770092, + "pred_variance_6d": 0.5230888000962929, + "pred_gt_ratio": 0.5195404071353424 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6310660433105342, + "pred_variance_6d": 0.24792051357518485, + "pred_gt_ratio": 0.39285985389834777 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47947190051608823, + "pred_variance_6d": 0.24510227359605463, + "pred_gt_ratio": 0.5111921539765613 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6657770069032021, + "pred_variance_6d": 0.42764774117800153, + "pred_gt_ratio": 0.6423287928899257 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.4545595117883542, + "pred_variance_6d": 0.1629008818210823, + "pred_gt_ratio": 0.35837085705277244 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.13893213807109603, + "pred_variance_6d": 0.09536941436968807, + "pred_gt_ratio": 0.6864460282104381 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.2726204271078565, + "pred_variance_6d": 0.2759783913585185, + "pred_gt_ratio": 1.0123173611247167 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3773495194787544, + "pred_variance_6d": 0.4389406530431639, + "pred_gt_ratio": 1.163220384246116 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47425826504130897, + "pred_variance_6d": 0.35155621091744305, + "pred_gt_ratio": 0.7412758761027005 + } + ] + } + } + } + }, + "normal": { + "hands": 1035, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 477, + "variance": 0.5699010059812321 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 477, + "variance": 0.32043017497961696 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 477, + "variance": 0.17137041841495992 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 477, + "variance": 0.093209514507725 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 477, + "variance": 0.4784002229757597 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 477, + "variance": 0.14882381724806748 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 477, + "variance": 0.07720752935442478 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 477, + "variance": 1.1847942889023333 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 477, + "variance": 0.49906953323828607 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 477, + "variance": 0.33117526573572365 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 477, + "variance": 0.5965439728070058 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 477, + "variance": 0.32917522352554507 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 477, + "variance": 0.09575482889376169 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 477, + "variance": 0.26779385793285265 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 477, + "variance": 0.36864379388159163 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 477, + "variance": 0.47448711475703753 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 558, + "variance": 0.6592795114306718 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 558, + "variance": 0.3619243761243408 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 558, + "variance": 0.19477889578850316 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 558, + "variance": 0.1333605768702072 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 558, + "variance": 0.5785755301589407 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 558, + "variance": 0.16567743958066852 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 558, + "variance": 0.05076092282958291 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 558, + "variance": 0.8993044976521545 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 558, + "variance": 0.45081289440831723 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 558, + "variance": 0.39346621144539196 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 558, + "variance": 0.5518684507077155 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 558, + "variance": 0.21194670985420427 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 558, + "variance": 0.09239705921877114 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 558, + "variance": 0.2745392720629573 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 558, + "variance": 0.3572100947679524 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 558, + "variance": 0.4674054724345946 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 33.96329937027272, + "count": 1035 + }, + "root_relative_mpjpe_mm": { + "mean": 20.446218082870264, + "count": 1035 + }, + "mpvpe_mm": { + "mean": 33.55826290840112, + "count": 1035 + }, + "projected_mano_2d_error_px": { + "mean": 16.819089050998706, + "count": 1027 + }, + "local_pose_angle_deg": { + "mean": 22.833865565608665, + "count": 1035 + }, + "root_relative_fingertip_mm": { + "mean": 30.212256455536625, + "count": 1035 + }, + "distal_angle_bias_deg": { + "mean": -2.1798302536425385, + "count": 1035 + }, + "distal_angle_mae_deg": { + "mean": 9.442646320776086, + "count": 1035 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 19.676526484051763, + 16.174382352944157, + 12.314740523854315, + 23.499995102628993, + 17.91413645076291, + 10.951865373832591, + 40.371926761019054, + 39.28303707348552, + 34.61170306712533, + 25.433041658493632, + 21.361070613815013, + 12.611027684015928, + 17.8822580491863, + 23.427045040545256, + 26.995208969208353 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6787034975622026, + "mean_abs_log_variance_ratio": 0.4900953982068317, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5699010059812321, + "pred_variance_6d": 0.5388082836186078, + "pred_gt_ratio": 0.9454418889661546 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32043017497961696, + "pred_variance_6d": 0.2606392146730714, + "pred_gt_ratio": 0.8134040893297613 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.17137041841495992, + "pred_variance_6d": 0.14662891549702112, + "pred_gt_ratio": 0.8556255907712776 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.093209514507725, + "pred_variance_6d": 0.043601295686962804, + "pred_gt_ratio": 0.4677773070403583 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.4784002229757597, + "pred_variance_6d": 0.44580281199570077, + "pred_gt_ratio": 0.9318616308803213 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.14882381724806748, + "pred_variance_6d": 0.12240336160464915, + "pred_gt_ratio": 0.8224715900185566 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.07720752935442478, + "pred_variance_6d": 0.026264895276653405, + "pred_gt_ratio": 0.34018567225591656 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 477, + "gt_variance_6d": 1.1847942889023333, + "pred_variance_6d": 0.6600389409413983, + "pred_gt_ratio": 0.5570915956667036 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.49906953323828607, + "pred_variance_6d": 0.21920197003327946, + "pred_gt_ratio": 0.4392213017111168 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.33117526573572365, + "pred_variance_6d": 0.178815979749151, + "pred_gt_ratio": 0.5399436438947266 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5965439728070058, + "pred_variance_6d": 0.4516012664515722, + "pred_gt_ratio": 0.7570293004999893 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32917522352554507, + "pred_variance_6d": 0.08356980782729895, + "pred_gt_ratio": 0.25387636083981774 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.09575482889376169, + "pred_variance_6d": 0.04258926680918515, + "pred_gt_ratio": 0.44477408921525197 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.26779385793285265, + "pred_variance_6d": 0.18988665434661195, + "pred_gt_ratio": 0.7090777055619574 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.36864379388159163, + "pred_variance_6d": 0.1899559220689879, + "pred_gt_ratio": 0.515283114002461 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.47448711475703753, + "pred_variance_6d": 0.2483133212782086, + "pred_gt_ratio": 0.5233299568216054 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 558, + "gt_variance_6d": 0.6592795114306718, + "pred_variance_6d": 0.5989702047686952, + "pred_gt_ratio": 0.9085224011723008 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3619243761243408, + "pred_variance_6d": 0.2574838528118043, + "pred_gt_ratio": 0.7114299831613015 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.19477889578850316, + "pred_variance_6d": 0.17611294238465897, + "pred_gt_ratio": 0.9041685017861881 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.1333605768702072, + "pred_variance_6d": 0.11311478308442524, + "pred_gt_ratio": 0.8481875659139798 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5785755301589407, + "pred_variance_6d": 0.3983261695287371, + "pred_gt_ratio": 0.6884601037643483 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.16567743958066852, + "pred_variance_6d": 0.21223392391402757, + "pred_gt_ratio": 1.2810067831274676 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.05076092282958291, + "pred_variance_6d": 0.028959464415209624, + "pred_gt_ratio": 0.5705070515056193 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.8993044976521545, + "pred_variance_6d": 0.4654230744463438, + "pred_gt_ratio": 0.5175366915893782 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.45081289440831723, + "pred_variance_6d": 0.15960464102587324, + "pred_gt_ratio": 0.3540374354982705 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.39346621144539196, + "pred_variance_6d": 0.15577231010474457, + "pred_gt_ratio": 0.3958975525052518 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5518684507077155, + "pred_variance_6d": 0.3541407217203172, + "pred_gt_ratio": 0.6417122074403193 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.21194670985420427, + "pred_variance_6d": 0.08425549716717784, + "pred_gt_ratio": 0.3975315173570575 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.09239705921877114, + "pred_variance_6d": 0.04973937388418574, + "pred_gt_ratio": 0.5383220451466579 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.2745392720629573, + "pred_variance_6d": 0.2908505106514413, + "pred_gt_ratio": 1.05941313410616 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3572100947679524, + "pred_variance_6d": 0.43674068929659554, + "pred_gt_ratio": 1.2226437485768902 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.4674054724345946, + "pred_variance_6d": 0.35650901918165806, + "pred_gt_ratio": 0.7627403618633185 + } + ] + } + }, + "N0_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 33.11338498166218, + "count": 1035 + }, + "root_relative_mpjpe_mm": { + "mean": 20.176319149496475, + "count": 1035 + }, + "mpvpe_mm": { + "mean": 32.744663596959505, + "count": 1035 + }, + "projected_mano_2d_error_px": { + "mean": 17.414731951976357, + "count": 1027 + }, + "local_pose_angle_deg": { + "mean": 22.78073564428062, + "count": 1035 + }, + "root_relative_fingertip_mm": { + "mean": 29.857902244899584, + "count": 1035 + }, + "distal_angle_bias_deg": { + "mean": -2.118564366084942, + "count": 1035 + }, + "distal_angle_mae_deg": { + "mean": 9.425751157198551, + "count": 1035 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 19.475757982880598, + 16.09613694632111, + 12.290801653222761, + 23.508091601657405, + 17.716910652492356, + 11.010612960224567, + 40.32272415460596, + 39.00193394393737, + 35.01806986251315, + 25.155134269004858, + 21.278654855115402, + 12.625019688594744, + 17.69708316936585, + 23.41686887142163, + 27.097216614893668 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.849914388610545, + "recording_bootstrap_95ci": [ + -1.248150901867793, + -0.4370909843802603 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.26989893337378756, + "recording_bootstrap_95ci": [ + -0.3775282000641998, + -0.16014212687910626 + ], + "count": 1035, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": -0.813599311441615, + "recording_bootstrap_95ci": [ + -1.2116499982517295, + -0.4060962840123782 + ], + "count": 1035, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.59564290097765, + "recording_bootstrap_95ci": [ + 0.3225958120677594, + 0.8416866935270766 + ], + "count": 1027, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": -0.05312992132804244, + "recording_bootstrap_95ci": [ + -0.13303608567408082, + 0.027602080592881682 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.3543542106370419, + "recording_bootstrap_95ci": [ + -0.5484245809202518, + -0.172172084797561 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.0612658875575964, + "recording_bootstrap_95ci": [ + -0.07043695164582661, + 0.20025768151994544 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": -0.016895163577535878, + "recording_bootstrap_95ci": [ + -0.08530055242261418, + 0.052444066957069504 + ], + "count": 1035, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6956238157128839, + "mean_abs_log_variance_ratio": 0.46242178864864814, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5699010059812321, + "pred_variance_6d": 0.5432936231861014, + "pred_gt_ratio": 0.9533122726300173 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32043017497961696, + "pred_variance_6d": 0.264243548085778, + "pred_gt_ratio": 0.824652510028392 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.17137041841495992, + "pred_variance_6d": 0.1483588657255661, + "pred_gt_ratio": 0.8657203915224554 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.093209514507725, + "pred_variance_6d": 0.04546662826978669, + "pred_gt_ratio": 0.4877895621483847 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.4784002229757597, + "pred_variance_6d": 0.4507892022806009, + "pred_gt_ratio": 0.9422846826378719 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.14882381724806748, + "pred_variance_6d": 0.12437177005076122, + "pred_gt_ratio": 0.835698024352189 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.07720752935442478, + "pred_variance_6d": 0.02841483948932502, + "pred_gt_ratio": 0.3680319746910352 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 477, + "gt_variance_6d": 1.1847942889023333, + "pred_variance_6d": 0.6726155890594183, + "pred_gt_ratio": 0.5677066435579893 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.49906953323828607, + "pred_variance_6d": 0.23256506040429914, + "pred_gt_ratio": 0.4659973108261419 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.33117526573572365, + "pred_variance_6d": 0.18385627973926652, + "pred_gt_ratio": 0.5551630775650468 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5965439728070058, + "pred_variance_6d": 0.4602113775712131, + "pred_gt_ratio": 0.7714626222870262 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32917522352554507, + "pred_variance_6d": 0.08639669970220817, + "pred_gt_ratio": 0.2624641635445066 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.09575482889376169, + "pred_variance_6d": 0.04537508952377832, + "pred_gt_ratio": 0.47386737617296765 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.26779385793285265, + "pred_variance_6d": 0.192259105114727, + "pred_gt_ratio": 0.7179369482138555 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.36864379388159163, + "pred_variance_6d": 0.1875959508240494, + "pred_gt_ratio": 0.5088813481675083 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.47448711475703753, + "pred_variance_6d": 0.2574921591670628, + "pred_gt_ratio": 0.5426747137251817 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 558, + "gt_variance_6d": 0.6592795114306718, + "pred_variance_6d": 0.6007494487760965, + "pred_gt_ratio": 0.9112211715368465 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3619243761243408, + "pred_variance_6d": 0.26472247253082104, + "pred_gt_ratio": 0.7314303484213907 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.19477889578850316, + "pred_variance_6d": 0.1794069680617139, + "pred_gt_ratio": 0.9210801166904624 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.1333605768702072, + "pred_variance_6d": 0.11529170302643119, + "pred_gt_ratio": 0.8645111301418448 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5785755301589407, + "pred_variance_6d": 0.41333672923310183, + "pred_gt_ratio": 0.7144040971099381 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.16567743958066852, + "pred_variance_6d": 0.2161978308877791, + "pred_gt_ratio": 1.3049322311775113 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.05076092282958291, + "pred_variance_6d": 0.02956940109172031, + "pred_gt_ratio": 0.5825229220318191 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.8993044976521545, + "pred_variance_6d": 0.48857965080197185, + "pred_gt_ratio": 0.5432861195262825 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.45081289440831723, + "pred_variance_6d": 0.1671165266840854, + "pred_gt_ratio": 0.37070041420049094 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.39346621144539196, + "pred_variance_6d": 0.16755765840286296, + "pred_gt_ratio": 0.4258501836468817 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5518684507077155, + "pred_variance_6d": 0.3699467958367843, + "pred_gt_ratio": 0.6703532252339574 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.21194670985420427, + "pred_variance_6d": 0.09234004335173863, + "pred_gt_ratio": 0.4356757574357172 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.09239705921877114, + "pred_variance_6d": 0.053889047853376906, + "pred_gt_ratio": 0.583233365964411 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.2745392720629573, + "pred_variance_6d": 0.28958139252276466, + "pred_gt_ratio": 1.054790414306766 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3572100947679524, + "pred_variance_6d": 0.44859501955821557, + "pred_gt_ratio": 1.2558296255586725 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.4674054724345946, + "pred_variance_6d": 0.3489169501743921, + "pred_gt_ratio": 0.7464973577587222 + } + ] + } + }, + "N0_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.39584665759174, + "count": 1035 + }, + "root_relative_mpjpe_mm": { + "mean": 20.215242117269028, + "count": 1035 + }, + "mpvpe_mm": { + "mean": 34.004648039076066, + "count": 1035 + }, + "projected_mano_2d_error_px": { + "mean": 17.20511496217945, + "count": 1027 + }, + "local_pose_angle_deg": { + "mean": 22.803221667561555, + "count": 1035 + }, + "root_relative_fingertip_mm": { + "mean": 29.885609687584033, + "count": 1035 + }, + "distal_angle_bias_deg": { + "mean": -1.9888574202279539, + "count": 1035 + }, + "distal_angle_mae_deg": { + "mean": 9.492540275417088, + "count": 1035 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 19.373677215714384, + 16.35397583277905, + 12.389174316269187, + 23.339913551012675, + 17.751912414163783, + 10.98748792818779, + 40.217924213870134, + 39.011835346590495, + 34.92858354688266, + 25.044758413609674, + 21.3563697780388, + 12.598215705645833, + 17.799544769784678, + 23.64794696149043, + 27.246987654736653 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.4325472873190175, + "recording_bootstrap_95ci": [ + 0.03992886031496904, + 0.7678450512650296 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.23097596560123462, + "recording_bootstrap_95ci": [ + -0.33606601930829016, + -0.10885405170070876 + ], + "count": 1035, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": 0.4463851306749427, + "recording_bootstrap_95ci": [ + 0.05593723183218383, + 0.78024906116104 + ], + "count": 1035, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.3860259111807432, + "recording_bootstrap_95ci": [ + 0.09278309446692716, + 0.7083173622500797 + ], + "count": 1027, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": -0.030643898047110884, + "recording_bootstrap_95ci": [ + -0.12412936746516115, + 0.0659151559689805 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.3266467679525919, + "recording_bootstrap_95ci": [ + -0.5074454983057776, + -0.11666489173552795 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.19097283341458454, + "recording_bootstrap_95ci": [ + 0.060097465343587154, + 0.33817767178381436 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": 0.049893954641001236, + "recording_bootstrap_95ci": [ + -0.023566014899880652, + 0.11985955146449896 + ], + "count": 1035, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.7021946240035501, + "mean_abs_log_variance_ratio": 0.4589781959665129, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5699010059812321, + "pred_variance_6d": 0.542072657224676, + "pred_gt_ratio": 0.9511698550020239 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32043017497961696, + "pred_variance_6d": 0.26486261629912217, + "pred_gt_ratio": 0.8265845010257554 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.17137041841495992, + "pred_variance_6d": 0.15642668079903127, + "pred_gt_ratio": 0.9127986162714292 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.093209514507725, + "pred_variance_6d": 0.046918072016288434, + "pred_gt_ratio": 0.5033614032224143 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.4784002229757597, + "pred_variance_6d": 0.4457587924332397, + "pred_gt_ratio": 0.9317696167876286 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.14882381724806748, + "pred_variance_6d": 0.1220267187378258, + "pred_gt_ratio": 0.8199407930413797 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.07720752935442478, + "pred_variance_6d": 0.028114423081914225, + "pred_gt_ratio": 0.36414094994354307 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 477, + "gt_variance_6d": 1.1847942889023333, + "pred_variance_6d": 0.6828030043788317, + "pred_gt_ratio": 0.5763051111694864 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.49906953323828607, + "pred_variance_6d": 0.2310810504236886, + "pred_gt_ratio": 0.463023757279442 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.33117526573572365, + "pred_variance_6d": 0.1832583086457703, + "pred_gt_ratio": 0.5533574744437877 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5965439728070058, + "pred_variance_6d": 0.4581553670321594, + "pred_gt_ratio": 0.7680160858491853 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32917522352554507, + "pred_variance_6d": 0.08410971676006532, + "pred_gt_ratio": 0.25551654787146555 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.09575482889376169, + "pred_variance_6d": 0.04418717239517149, + "pred_gt_ratio": 0.46146155661973337 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.26779385793285265, + "pred_variance_6d": 0.19570610740528635, + "pred_gt_ratio": 0.7308087979163369 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.36864379388159163, + "pred_variance_6d": 0.19382340457952396, + "pred_gt_ratio": 0.5257742237803141 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.47448711475703753, + "pred_variance_6d": 0.26237511135308567, + "pred_gt_ratio": 0.5529657248699695 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 558, + "gt_variance_6d": 0.6592795114306718, + "pred_variance_6d": 0.607350297383983, + "pred_gt_ratio": 0.921233387134996 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3619243761243408, + "pred_variance_6d": 0.2714884536701001, + "pred_gt_ratio": 0.7501248094348555 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.19477889578850316, + "pred_variance_6d": 0.18514395923119553, + "pred_gt_ratio": 0.9505339810131713 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.1333605768702072, + "pred_variance_6d": 0.11778629816461911, + "pred_gt_ratio": 0.8832167716195041 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5785755301589407, + "pred_variance_6d": 0.42123289970137295, + "pred_gt_ratio": 0.7280517024037568 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.16567743958066852, + "pred_variance_6d": 0.2164497705397504, + "pred_gt_ratio": 1.3064528947790792 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.05076092282958291, + "pred_variance_6d": 0.02951934258819451, + "pred_gt_ratio": 0.5815367598279944 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.8993044976521545, + "pred_variance_6d": 0.48833868661641766, + "pred_gt_ratio": 0.5430181744796567 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.45081289440831723, + "pred_variance_6d": 0.16182617280620257, + "pred_gt_ratio": 0.3589652709880806 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.39346621144539196, + "pred_variance_6d": 0.1653469966379501, + "pred_gt_ratio": 0.42023175517549655 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5518684507077155, + "pred_variance_6d": 0.37630111309437897, + "pred_gt_ratio": 0.6818674135327193 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.21194670985420427, + "pred_variance_6d": 0.09130439479785407, + "pred_gt_ratio": 0.4307893944693047 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.09239705921877114, + "pred_variance_6d": 0.05357964508940967, + "pred_gt_ratio": 0.5798847446275062 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.2745392720629573, + "pred_variance_6d": 0.29152188518514494, + "pred_gt_ratio": 1.0618585931061009 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3572100947679524, + "pred_variance_6d": 0.46543592400861034, + "pred_gt_ratio": 1.3029752821262306 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.4674054724345946, + "pred_variance_6d": 0.3610669967660545, + "pred_gt_ratio": 0.7724920183012612 + } + ] + } + }, + "N1_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 33.20130727924587, + "count": 1035 + }, + "root_relative_mpjpe_mm": { + "mean": 20.18215535712127, + "count": 1035 + }, + "mpvpe_mm": { + "mean": 32.82767183008977, + "count": 1035 + }, + "projected_mano_2d_error_px": { + "mean": 17.364078375937993, + "count": 1027 + }, + "local_pose_angle_deg": { + "mean": 22.90913132838005, + "count": 1035 + }, + "root_relative_fingertip_mm": { + "mean": 29.879064217166626, + "count": 1035 + }, + "distal_angle_bias_deg": { + "mean": -1.8961887964015998, + "count": 1035 + }, + "distal_angle_mae_deg": { + "mean": 9.526346490924485, + "count": 1035 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 19.62456477045437, + 16.365991038429563, + 12.340270111871803, + 23.722267429840162, + 18.155114607419367, + 11.040680172535533, + 40.40244850536475, + 39.16059840474152, + 35.03471611985838, + 25.285132485081032, + 21.557462124548096, + 12.657757240965747, + 17.696749265643135, + 23.46764633782244, + 27.125552967089963 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.761992091026859, + "recording_bootstrap_95ci": [ + -1.1367079207928517, + -0.3828538567620108 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.26406272574899275, + "recording_bootstrap_95ci": [ + -0.36550364083636566, + -0.15917732942769003 + ], + "count": 1035, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": -0.7305910783113488, + "recording_bootstrap_95ci": [ + -1.100657794125419, + -0.3494215485260012 + ], + "count": 1035, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.5449893249392858, + "recording_bootstrap_95ci": [ + 0.24926415455923315, + 0.7963526182906121 + ], + "count": 1027, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": 0.0752657627713853, + "recording_bootstrap_95ci": [ + -0.01561485995832351, + 0.16915142432574626 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.3331922383700016, + "recording_bootstrap_95ci": [ + -0.516711020707068, + -0.14559181167064114 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.2836414572409386, + "recording_bootstrap_95ci": [ + 0.11350667873401445, + 0.46777711940210887 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": 0.08370017014839799, + "recording_bootstrap_95ci": [ + -0.004663594948489345, + 0.17465742911933282 + ], + "count": 1035, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.7040250160326094, + "mean_abs_log_variance_ratio": 0.4522308528231697, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5699010059812321, + "pred_variance_6d": 0.5427502031408683, + "pred_gt_ratio": 0.952358738525796 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32043017497961696, + "pred_variance_6d": 0.2641868292468529, + "pred_gt_ratio": 0.8244755016086054 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.17137041841495992, + "pred_variance_6d": 0.1573475274591844, + "pred_gt_ratio": 0.9181720445951167 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.093209514507725, + "pred_variance_6d": 0.04498813418771215, + "pred_gt_ratio": 0.4826560295406714 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.4784002229757597, + "pred_variance_6d": 0.4512542825327448, + "pred_gt_ratio": 0.9432568399024548 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.14882381724806748, + "pred_variance_6d": 0.13124231461663594, + "pred_gt_ratio": 0.8818636495385295 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.07720752935442478, + "pred_variance_6d": 0.029025141989641037, + "pred_gt_ratio": 0.3759366765435501 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 477, + "gt_variance_6d": 1.1847942889023333, + "pred_variance_6d": 0.6776800047499898, + "pred_gt_ratio": 0.5719811541105878 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.49906953323828607, + "pred_variance_6d": 0.23678692088508055, + "pred_gt_ratio": 0.47445677428684896 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.33117526573572365, + "pred_variance_6d": 0.18588989889798904, + "pred_gt_ratio": 0.5613036906153744 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5965439728070058, + "pred_variance_6d": 0.46152147433933666, + "pred_gt_ratio": 0.7736587667924496 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32917522352554507, + "pred_variance_6d": 0.08974316951418311, + "pred_gt_ratio": 0.27263038983618626 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.09575482889376169, + "pred_variance_6d": 0.04650511078218081, + "pred_gt_ratio": 0.48566856961101584 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.26779385793285265, + "pred_variance_6d": 0.1922656397135439, + "pred_gt_ratio": 0.7179613498146515 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.36864379388159163, + "pred_variance_6d": 0.1871677948928227, + "pred_gt_ratio": 0.5077199128244133 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.47448711475703753, + "pred_variance_6d": 0.2587469146030062, + "pred_gt_ratio": 0.5453191594791742 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 558, + "gt_variance_6d": 0.6592795114306718, + "pred_variance_6d": 0.6013806673051946, + "pred_gt_ratio": 0.912178608432964 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3619243761243408, + "pred_variance_6d": 0.26484790658745777, + "pred_gt_ratio": 0.7317769237418483 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.19477889578850316, + "pred_variance_6d": 0.1848193544989673, + "pred_gt_ratio": 0.948867451736916 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.1333605768702072, + "pred_variance_6d": 0.11591394593133787, + "pred_gt_ratio": 0.869176998567956 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5785755301589407, + "pred_variance_6d": 0.4165139656259408, + "pred_gt_ratio": 0.7198955778712592 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.16567743958066852, + "pred_variance_6d": 0.22529748684855755, + "pred_gt_ratio": 1.3598561603727584 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.05076092282958291, + "pred_variance_6d": 0.02928366558045744, + "pred_gt_ratio": 0.5768938771812722 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.8993044976521545, + "pred_variance_6d": 0.4871695607230437, + "pred_gt_ratio": 0.5417181410689196 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.45081289440831723, + "pred_variance_6d": 0.17150498011598633, + "pred_gt_ratio": 0.38043494816421153 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.39346621144539196, + "pred_variance_6d": 0.17129203798928247, + "pred_gt_ratio": 0.4353411627393464 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5518684507077155, + "pred_variance_6d": 0.36873640547859077, + "pred_gt_ratio": 0.6681599663936643 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.21194670985420427, + "pred_variance_6d": 0.09732758120567267, + "pred_gt_ratio": 0.45920779460376243 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.09239705921877114, + "pred_variance_6d": 0.05390578837817228, + "pred_gt_ratio": 0.5834145462415423 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.2745392720629573, + "pred_variance_6d": 0.2898261852482903, + "pred_gt_ratio": 1.0556820635185022 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3572100947679524, + "pred_variance_6d": 0.44546938186775, + "pred_gt_ratio": 1.2470794873731992 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.4674054724345946, + "pred_variance_6d": 0.3504127410042618, + "pred_gt_ratio": 0.7496975574099553 + } + ] + } + }, + "N1_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.38002280728253, + "count": 1035 + }, + "root_relative_mpjpe_mm": { + "mean": 20.201851608442222, + "count": 1035 + }, + "mpvpe_mm": { + "mean": 33.98539773692256, + "count": 1035 + }, + "projected_mano_2d_error_px": { + "mean": 17.24077521094793, + "count": 1027 + }, + "local_pose_angle_deg": { + "mean": 22.942493346578257, + "count": 1035 + }, + "root_relative_fingertip_mm": { + "mean": 29.873550251946934, + "count": 1035 + }, + "distal_angle_bias_deg": { + "mean": -1.7753990975555014, + "count": 1035 + }, + "distal_angle_mae_deg": { + "mean": 9.609355271150525, + "count": 1035 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 19.496932058057922, + 16.656316854182073, + 12.45494297981838, + 23.567048203772394, + 18.14621610917907, + 11.022410004323232, + 40.29181953835602, + 39.16735831274502, + 35.04325452518924, + 25.22471804112052, + 21.62151501547311, + 12.626207643833713, + 17.82693867959838, + 23.71172186648788, + 27.27998321160026 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.4167234370098022, + "recording_bootstrap_95ci": [ + 0.02619487177363765, + 0.7550300355536088 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.24436647442803866, + "recording_bootstrap_95ci": [ + -0.339710044972755, + -0.1340680238542009 + ], + "count": 1035, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": 0.42713482852143364, + "recording_bootstrap_95ci": [ + 0.04330004291893462, + 0.7613505616710889 + ], + "count": 1035, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.42168615994922376, + "recording_bootstrap_95ci": [ + 0.1428658515182016, + 0.7255079829943389 + ], + "count": 1027, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": 0.10862778096959211, + "recording_bootstrap_95ci": [ + -0.005937930949953514, + 0.22162400084243492 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.3387062035896928, + "recording_bootstrap_95ci": [ + -0.509247880729215, + -0.13395938647899472 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.4044311560870369, + "recording_bootstrap_95ci": [ + 0.23314372601239197, + 0.593801131536834 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": 0.16670895037443742, + "recording_bootstrap_95ci": [ + 0.07168341422753183, + 0.2549070960860009 + ], + "count": 1035, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.7133347244352313, + "mean_abs_log_variance_ratio": 0.44550537397480183, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5699010059812321, + "pred_variance_6d": 0.5415263072256604, + "pred_gt_ratio": 0.9502111797351239 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32043017497961696, + "pred_variance_6d": 0.2672178960366718, + "pred_gt_ratio": 0.8339348691291946 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.17137041841495992, + "pred_variance_6d": 0.16769380641457127, + "pred_gt_ratio": 0.978545818850217 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.093209514507725, + "pred_variance_6d": 0.04672061810135708, + "pred_gt_ratio": 0.5012430152448115 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.4784002229757597, + "pred_variance_6d": 0.4469005044607799, + "pred_gt_ratio": 0.9341561374720014 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.14882381724806748, + "pred_variance_6d": 0.12992931546735315, + "pred_gt_ratio": 0.873041142673958 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.07720752935442478, + "pred_variance_6d": 0.028812847161841647, + "pred_gt_ratio": 0.3731870117171464 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 477, + "gt_variance_6d": 1.1847942889023333, + "pred_variance_6d": 0.6904488678798195, + "pred_gt_ratio": 0.582758436926206 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.49906953323828607, + "pred_variance_6d": 0.2394687224895291, + "pred_gt_ratio": 0.47983037741394685 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.33117526573572365, + "pred_variance_6d": 0.18875348462351782, + "pred_gt_ratio": 0.5699504285266951 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5965439728070058, + "pred_variance_6d": 0.4602510819354074, + "pred_gt_ratio": 0.771529179600492 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32917522352554507, + "pred_variance_6d": 0.08847754953276271, + "pred_gt_ratio": 0.26878556832178035 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.09575482889376169, + "pred_variance_6d": 0.04551777724815246, + "pred_gt_ratio": 0.4753575122425798 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.26779385793285265, + "pred_variance_6d": 0.19577123614286057, + "pred_gt_ratio": 0.7310520026637384 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.36864379388159163, + "pred_variance_6d": 0.19327425532414577, + "pred_gt_ratio": 0.5242845764174873 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.47448711475703753, + "pred_variance_6d": 0.26365397578106936, + "pred_gt_ratio": 0.5556609812598897 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 558, + "gt_variance_6d": 0.6592795114306718, + "pred_variance_6d": 0.6077291061531856, + "pred_gt_ratio": 0.9218079670554011 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3619243761243408, + "pred_variance_6d": 0.27246631707395086, + "pred_gt_ratio": 0.752826653986809 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.19477889578850316, + "pred_variance_6d": 0.19208031843616913, + "pred_gt_ratio": 0.9861454325356468 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.1333605768702072, + "pred_variance_6d": 0.11962705611411308, + "pred_gt_ratio": 0.8970196359493838 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5785755301589407, + "pred_variance_6d": 0.42478471677559676, + "pred_gt_ratio": 0.7341906019753445 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.16567743958066852, + "pred_variance_6d": 0.22673922526409854, + "pred_gt_ratio": 1.3685582408683892 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.05076092282958291, + "pred_variance_6d": 0.029087984832244757, + "pred_gt_ratio": 0.5730389285848956 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.8993044976521545, + "pred_variance_6d": 0.4884801946703265, + "pred_gt_ratio": 0.5431755272498011 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.45081289440831723, + "pred_variance_6d": 0.16664632818383474, + "pred_gt_ratio": 0.3696574127555838 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.39346621144539196, + "pred_variance_6d": 0.16886317688918517, + "pred_gt_ratio": 0.42916817753897835 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5518684507077155, + "pred_variance_6d": 0.37541534178294894, + "pred_gt_ratio": 0.6802623728562789 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.21194670985420427, + "pred_variance_6d": 0.09576783419772433, + "pred_gt_ratio": 0.45184864753787374 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.09239705921877114, + "pred_variance_6d": 0.05353802917982173, + "pred_gt_ratio": 0.5794343416607904 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.2745392720629573, + "pred_variance_6d": 0.29280899433713575, + "pred_gt_ratio": 1.066546844598571 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3572100947679524, + "pred_variance_6d": 0.4623790974623444, + "pred_gt_ratio": 1.2944177788780324 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.4674054724345946, + "pred_variance_6d": 0.3622786806705185, + "pred_gt_ratio": 0.7750843797003536 + } + ] + } + } + } + }, + "hard": { + "hands": 533, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 290, + "variance": 0.6138053009987845 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 290, + "variance": 0.5807387522725387 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 290, + "variance": 0.4087374559798051 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 290, + "variance": 0.27216020313339495 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 290, + "variance": 0.9921459193572351 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 290, + "variance": 0.45085131937280354 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 290, + "variance": 0.1440343915553799 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 290, + "variance": 1.0927133588640738 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 290, + "variance": 0.9174771232143025 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 290, + "variance": 0.7379834224474471 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 290, + "variance": 0.7513754751856945 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 290, + "variance": 0.714811725463003 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 290, + "variance": 0.36939217839320143 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 290, + "variance": 0.18054553885693672 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 290, + "variance": 0.24785972821602548 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 290, + "variance": 0.35665097727134426 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 243, + "variance": 0.7980280331327785 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 243, + "variance": 0.45202466056999735 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 243, + "variance": 0.5573761758309335 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 243, + "variance": 0.28644333077364537 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 243, + "variance": 0.8985408974776645 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 243, + "variance": 0.5075990704457212 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 243, + "variance": 0.10794738783732755 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 243, + "variance": 1.0699376260085949 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 243, + "variance": 0.7741661980374077 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 243, + "variance": 0.5849821902534715 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 243, + "variance": 0.8490313559290219 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 243, + "variance": 0.6704939861672432 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 243, + "variance": 0.18305638522721163 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 243, + "variance": 0.25406185431104117 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 243, + "variance": 0.3864964776799549 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 243, + "variance": 0.41223091337116574 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 35.91755379073839, + "count": 533 + }, + "root_relative_mpjpe_mm": { + "mean": 21.83064363776631, + "count": 533 + }, + "mpvpe_mm": { + "mean": 35.419409553284495, + "count": 533 + }, + "projected_mano_2d_error_px": { + "mean": 17.404465975054656, + "count": 533 + }, + "local_pose_angle_deg": { + "mean": 27.26284116562491, + "count": 533 + }, + "root_relative_fingertip_mm": { + "mean": 33.46684944159989, + "count": 533 + }, + "distal_angle_bias_deg": { + "mean": -7.863910693836033, + "count": 533 + }, + "distal_angle_mae_deg": { + "mean": 16.657947105493598, + "count": 533 + }, + "gt60_angle_bias_deg": { + "mean": -31.212367823693604, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 23.856791723512575, + 22.266063831089586, + 16.810477126382754, + 29.275067356916573, + 23.18981244684831, + 13.203750126357374, + 47.18992460959401, + 48.86754454009752, + 39.31832353259117, + 29.081485460667853, + 32.7105710282782, + 20.27464803253732, + 16.85662591826401, + 20.805945125798125, + 25.235565931667306 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5672533057603333, + "mean_abs_log_variance_ratio": 0.6630044852114826, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 290, + "gt_variance_6d": 0.6138053009987845, + "pred_variance_6d": 0.5331670768358004, + "pred_gt_ratio": 0.8686257286605875 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.5807387522725387, + "pred_variance_6d": 0.47512359654399117, + "pred_gt_ratio": 0.8181365453652684 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.4087374559798051, + "pred_variance_6d": 0.2152719041957326, + "pred_gt_ratio": 0.5266752558306493 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.27216020313339495, + "pred_variance_6d": 0.16802313826440407, + "pred_gt_ratio": 0.6173685069673843 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9921459193572351, + "pred_variance_6d": 0.7177526368918237, + "pred_gt_ratio": 0.7234345501887687 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.45085131937280354, + "pred_variance_6d": 0.18177143789145783, + "pred_gt_ratio": 0.4031737960628063 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.1440343915553799, + "pred_variance_6d": 0.02874270008714776, + "pred_gt_ratio": 0.19955442430633977 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 290, + "gt_variance_6d": 1.0927133588640738, + "pred_variance_6d": 0.5114034524648663, + "pred_gt_ratio": 0.4680124465545968 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9174771232143025, + "pred_variance_6d": 0.3764370498587525, + "pred_gt_ratio": 0.4102958431703861 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7379834224474471, + "pred_variance_6d": 0.27861291686302936, + "pred_gt_ratio": 0.37753275803816555 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7513754751856945, + "pred_variance_6d": 0.4823447623497834, + "pred_gt_ratio": 0.6419490365061183 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.714811725463003, + "pred_variance_6d": 0.1820837355802205, + "pred_gt_ratio": 0.254729642917203 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.36939217839320143, + "pred_variance_6d": 0.05061809008710885, + "pred_gt_ratio": 0.13703075768222728 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.18054553885693672, + "pred_variance_6d": 0.1896830043657758, + "pred_gt_ratio": 1.0506103089928993 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.24785972821602548, + "pred_variance_6d": 0.20367322164706406, + "pred_gt_ratio": 0.8217277696260117 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.35665097727134426, + "pred_variance_6d": 0.23329010132503994, + "pred_gt_ratio": 0.6541131699957465 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7980280331327785, + "pred_variance_6d": 0.7134306667079935, + "pred_gt_ratio": 0.8939919866064286 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.45202466056999735, + "pred_variance_6d": 0.3313177009358491, + "pred_gt_ratio": 0.7329637735208112 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5573761758309335, + "pred_variance_6d": 0.23654249808959835, + "pred_gt_ratio": 0.42438573506835314 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.28644333077364537, + "pred_variance_6d": 0.11312523968327501, + "pred_gt_ratio": 0.3949306111534829 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8985408974776645, + "pred_variance_6d": 0.5232708666048927, + "pred_gt_ratio": 0.5823562044574604 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5075990704457212, + "pred_variance_6d": 0.1929200840702889, + "pred_gt_ratio": 0.38006390338911844 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.10794738783732755, + "pred_variance_6d": 0.053333256564659016, + "pred_gt_ratio": 0.4940671343064839 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 243, + "gt_variance_6d": 1.0699376260085949, + "pred_variance_6d": 0.48512772744092564, + "pred_gt_ratio": 0.45341683070881045 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7741661980374077, + "pred_variance_6d": 0.31657512287231354, + "pred_gt_ratio": 0.4089239799862931 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5849821902534715, + "pred_variance_6d": 0.29819692319228, + "pred_gt_ratio": 0.5097538491950873 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8490313559290219, + "pred_variance_6d": 0.43745282433973454, + "pred_gt_ratio": 0.5152375366173226 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.6704939861672432, + "pred_variance_6d": 0.18454466285225757, + "pred_gt_ratio": 0.2752368651465072 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.18305638522721163, + "pred_variance_6d": 0.10534866215101288, + "pred_gt_ratio": 0.5754984291875584 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.25406185431104117, + "pred_variance_6d": 0.22765505081001353, + "pred_gt_ratio": 0.8960615178825764 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.3864964776799549, + "pred_variance_6d": 0.3660450329782435, + "pred_gt_ratio": 0.947085042470564 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.41223091337116574, + "pred_variance_6d": 0.2865672017975346, + "pred_gt_ratio": 0.6951618437686509 + } + ] + } + }, + "N0_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.453417296704835, + "count": 533 + }, + "root_relative_mpjpe_mm": { + "mean": 21.562288325454684, + "count": 533 + }, + "mpvpe_mm": { + "mean": 33.98200849923139, + "count": 533 + }, + "projected_mano_2d_error_px": { + "mean": 17.89924613530372, + "count": 533 + }, + "local_pose_angle_deg": { + "mean": 27.20205229174129, + "count": 533 + }, + "root_relative_fingertip_mm": { + "mean": 33.07194552681012, + "count": 533 + }, + "distal_angle_bias_deg": { + "mean": -7.399065280721067, + "count": 533 + }, + "distal_angle_mae_deg": { + "mean": 16.60199209270513, + "count": 533 + }, + "gt60_angle_bias_deg": { + "mean": -30.747976674442796, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 23.766962862819938, + 22.481168100355266, + 16.838991255518643, + 28.944814491898214, + 22.949680044771807, + 13.288017634826573, + 46.81342250902702, + 49.142674224238014, + 40.3514794659212, + 28.598398163886724, + 32.24426948375594, + 20.233188676118402, + 16.48169730975525, + 20.552200735398127, + 25.343798062143808 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -1.4641364940335557, + "recording_bootstrap_95ci": [ + -2.610412907766323, + -0.37294843948822953 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.26835531231162696, + "recording_bootstrap_95ci": [ + -0.4933318708909843, + -0.12002933365779511 + ], + "count": 533, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": -1.4374010540531008, + "recording_bootstrap_95ci": [ + -2.5756785019107444, + -0.34753014066753357 + ], + "count": 533, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.49478016024906235, + "recording_bootstrap_95ci": [ + 0.2492909839205698, + 0.7058526519557701 + ], + "count": 533, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": -0.06078887388361775, + "recording_bootstrap_95ci": [ + -0.22458284322545302, + 0.09176945456277152 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.39490391478976883, + "recording_bootstrap_95ci": [ + -0.7349384591245933, + -0.14808041358839338 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.4648454131149664, + "recording_bootstrap_95ci": [ + 0.17912928516161272, + 0.7616296909053393 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": -0.05595501278846841, + "recording_bootstrap_95ci": [ + -0.1547616757367739, + 0.06497128016178327 + ], + "count": 533, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 0.46439114925080693, + "recording_bootstrap_95ci": [ + -0.0018613742554888992, + 1.021192589018249 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5837281596529647, + "mean_abs_log_variance_ratio": 0.6180727585846134, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 290, + "gt_variance_6d": 0.6138053009987845, + "pred_variance_6d": 0.5330131807094023, + "pred_gt_ratio": 0.86837500399896 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.5807387522725387, + "pred_variance_6d": 0.47186912314406404, + "pred_gt_ratio": 0.8125325222357772 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.4087374559798051, + "pred_variance_6d": 0.21548866721270227, + "pred_gt_ratio": 0.5272055791807568 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.27216020313339495, + "pred_variance_6d": 0.18908124642092472, + "pred_gt_ratio": 0.6947424503804092 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9921459193572351, + "pred_variance_6d": 0.7234203023304744, + "pred_gt_ratio": 0.7291470823154165 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.45085131937280354, + "pred_variance_6d": 0.2083401001857029, + "pred_gt_ratio": 0.46210378285136827 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.1440343915553799, + "pred_variance_6d": 0.03478325577145597, + "pred_gt_ratio": 0.24149271153814766 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 290, + "gt_variance_6d": 1.0927133588640738, + "pred_variance_6d": 0.513827452907443, + "pred_gt_ratio": 0.47023077803458946 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9174771232143025, + "pred_variance_6d": 0.40930833623683205, + "pred_gt_ratio": 0.44612375162320705 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7379834224474471, + "pred_variance_6d": 0.2859388029588601, + "pred_gt_ratio": 0.38745965595077064 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7513754751856945, + "pred_variance_6d": 0.48244010075853894, + "pred_gt_ratio": 0.6420759216812459 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.714811725463003, + "pred_variance_6d": 0.21545310754442437, + "pred_gt_ratio": 0.3014123857647544 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.36939217839320143, + "pred_variance_6d": 0.061101894441966585, + "pred_gt_ratio": 0.16541198762721596 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.18054553885693672, + "pred_variance_6d": 0.19055705863600908, + "pred_gt_ratio": 1.055451493525993 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.24785972821602548, + "pred_variance_6d": 0.20086865968705117, + "pred_gt_ratio": 0.8104126520786845 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.35665097727134426, + "pred_variance_6d": 0.24345336216582059, + "pred_gt_ratio": 0.6826095473743744 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7980280331327785, + "pred_variance_6d": 0.7124550368373178, + "pred_gt_ratio": 0.8927694357308088 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.45202466056999735, + "pred_variance_6d": 0.3492159133740268, + "pred_gt_ratio": 0.7725594283587758 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5573761758309335, + "pred_variance_6d": 0.24918134353427004, + "pred_gt_ratio": 0.44706134624931143 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.28644333077364537, + "pred_variance_6d": 0.11956511458524709, + "pred_gt_ratio": 0.41741280644348605 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8985408974776645, + "pred_variance_6d": 0.5469606086874785, + "pred_gt_ratio": 0.6087208831816969 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5075990704457212, + "pred_variance_6d": 0.19517884143826475, + "pred_gt_ratio": 0.38451378814953074 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.10794738783732755, + "pred_variance_6d": 0.05382343680883056, + "pred_gt_ratio": 0.49860805237770417 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 243, + "gt_variance_6d": 1.0699376260085949, + "pred_variance_6d": 0.49803566255432463, + "pred_gt_ratio": 0.4654810247324865 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7741661980374077, + "pred_variance_6d": 0.33111990347498577, + "pred_gt_ratio": 0.4277116519868852 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5849821902534715, + "pred_variance_6d": 0.3175921341451053, + "pred_gt_ratio": 0.5429090653298236 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8490313559290219, + "pred_variance_6d": 0.4597329451058104, + "pred_gt_ratio": 0.5414793480775092 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.6704939861672432, + "pred_variance_6d": 0.2083478717674876, + "pred_gt_ratio": 0.3107378679985935 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.18305638522721163, + "pred_variance_6d": 0.11256537247359694, + "pred_gt_ratio": 0.6149218577318651 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.25406185431104117, + "pred_variance_6d": 0.22089806549196517, + "pred_gt_ratio": 0.8694656901209795 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.3864964776799549, + "pred_variance_6d": 0.3563704146552902, + "pred_gt_ratio": 0.9220534603432762 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.41223091337116574, + "pred_variance_6d": 0.2745903487852205, + "pred_gt_ratio": 0.6661080959204628 + } + ] + } + }, + "N0_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 36.16891150805561, + "count": 533 + }, + "root_relative_mpjpe_mm": { + "mean": 21.55363628609319, + "count": 533 + }, + "mpvpe_mm": { + "mean": 35.66905621247712, + "count": 533 + }, + "projected_mano_2d_error_px": { + "mean": 17.872389155525653, + "count": 533 + }, + "local_pose_angle_deg": { + "mean": 27.162652853058606, + "count": 533 + }, + "root_relative_fingertip_mm": { + "mean": 32.99951657658446, + "count": 533 + }, + "distal_angle_bias_deg": { + "mean": -7.052028862105972, + "count": 533 + }, + "distal_angle_mae_deg": { + "mean": 16.554631391564634, + "count": 533 + }, + "gt60_angle_bias_deg": { + "mean": -29.79891960599781, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 23.656951444457665, + 22.48480549672755, + 16.999610635174147, + 28.732863609160088, + 23.08575638619865, + 13.35035906902621, + 46.633946786007336, + 49.0437866089268, + 39.980553063398006, + 28.54930383067641, + 32.12546507457855, + 20.1532763334421, + 16.588209044418907, + 20.616187457743102, + 25.438697058085427 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.25135771731721973, + "recording_bootstrap_95ci": [ + -0.3528793085965642, + 0.9097158684799795 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.2770073516731191, + "recording_bootstrap_95ci": [ + -0.4873410570810298, + -0.12957617245291247 + ], + "count": 533, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": 0.2496466591926274, + "recording_bootstrap_95ci": [ + -0.34630178759984925, + 0.9038441301250457 + ], + "count": 533, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.46792318047099446, + "recording_bootstrap_95ci": [ + 0.18613646701724063, + 0.7038477312521528 + ], + "count": 533, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": -0.10018831256630273, + "recording_bootstrap_95ci": [ + -0.27712742227424275, + 0.10133382172792507 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.46733286501542715, + "recording_bootstrap_95ci": [ + -0.8175503741192138, + -0.22269474624138613 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.8118818317300607, + "recording_bootstrap_95ci": [ + 0.5659889688622665, + 1.0563770456364514 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": -0.10331571392896699, + "recording_bootstrap_95ci": [ + -0.2908068983076842, + 0.12719726487167488 + ], + "count": 533, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 1.4134482176957932, + "recording_bootstrap_95ci": [ + 0.7464650688351213, + 1.9848519907482343 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5955317740555055, + "mean_abs_log_variance_ratio": 0.6006460474671053, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 290, + "gt_variance_6d": 0.6138053009987845, + "pred_variance_6d": 0.5327661345317782, + "pred_gt_ratio": 0.8679725210337231 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.5807387522725387, + "pred_variance_6d": 0.4886349088446129, + "pred_gt_ratio": 0.841402277586081 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.4087374559798051, + "pred_variance_6d": 0.23227219812890737, + "pred_gt_ratio": 0.5682674654127697 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.27216020313339495, + "pred_variance_6d": 0.20370462218235774, + "pred_gt_ratio": 0.7484732148091291 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9921459193572351, + "pred_variance_6d": 0.7228160916066126, + "pred_gt_ratio": 0.7285380885050572 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.45085131937280354, + "pred_variance_6d": 0.20791786658766018, + "pred_gt_ratio": 0.4611672577046079 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.1440343915553799, + "pred_variance_6d": 0.03544479346716409, + "pred_gt_ratio": 0.24608562638691672 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 290, + "gt_variance_6d": 1.0927133588640738, + "pred_variance_6d": 0.5220074316614942, + "pred_gt_ratio": 0.4777167108162246 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9174771232143025, + "pred_variance_6d": 0.42922154315816896, + "pred_gt_ratio": 0.4678280605563527 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7379834224474471, + "pred_variance_6d": 0.29997731975249275, + "pred_gt_ratio": 0.406482463735633 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7513754751856945, + "pred_variance_6d": 0.4748522141250865, + "pred_gt_ratio": 0.6319772601145011 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.714811725463003, + "pred_variance_6d": 0.221841471750587, + "pred_gt_ratio": 0.3103495142121434 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.36939217839320143, + "pred_variance_6d": 0.06226466086727611, + "pred_gt_ratio": 0.16855977064299985 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.18054553885693672, + "pred_variance_6d": 0.19658420775590715, + "pred_gt_ratio": 1.0888344791043516 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.24785972821602548, + "pred_variance_6d": 0.20905449074720583, + "pred_gt_ratio": 0.8434387153245064 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.35665097727134426, + "pred_variance_6d": 0.24879274481760053, + "pred_gt_ratio": 0.6975804376622136 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7980280331327785, + "pred_variance_6d": 0.7165243384209579, + "pred_gt_ratio": 0.8978686320180186 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.45202466056999735, + "pred_variance_6d": 0.3559255275588598, + "pred_gt_ratio": 0.7874028976871356 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5573761758309335, + "pred_variance_6d": 0.25978759114970384, + "pred_gt_ratio": 0.4660902320814374 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.28644333077364537, + "pred_variance_6d": 0.12307108490777151, + "pred_gt_ratio": 0.4296524711375645 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8985408974776645, + "pred_variance_6d": 0.552745750054219, + "pred_gt_ratio": 0.6151592560849005 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5075990704457212, + "pred_variance_6d": 0.20040825139843452, + "pred_gt_ratio": 0.39481603309962066 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.10794738783732755, + "pred_variance_6d": 0.0528314694149643, + "pred_gt_ratio": 0.4894186925076801 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 243, + "gt_variance_6d": 1.0699376260085949, + "pred_variance_6d": 0.49803401506250145, + "pred_gt_ratio": 0.46547948493074187 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7741661980374077, + "pred_variance_6d": 0.32845221536329905, + "pred_gt_ratio": 0.42426576644131425 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5849821902534715, + "pred_variance_6d": 0.31699533183226325, + "pred_gt_ratio": 0.5418888593769151 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8490313559290219, + "pred_variance_6d": 0.46419009987322746, + "pred_gt_ratio": 0.5467290420214271 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.6704939861672432, + "pred_variance_6d": 0.20839956688494338, + "pred_gt_ratio": 0.31081496804501046 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.18305638522721163, + "pred_variance_6d": 0.10995526607448261, + "pred_gt_ratio": 0.6006633745007305 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.25406185431104117, + "pred_variance_6d": 0.22364818284342794, + "pred_gt_ratio": 0.8802902877722896 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.3864964776799549, + "pred_variance_6d": 0.3679720658123067, + "pred_gt_ratio": 0.9520709425895787 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.41223091337116574, + "pred_variance_6d": 0.28845114740748923, + "pred_gt_ratio": 0.6997319658746036 + } + ] + } + }, + "N1_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.51471481001176, + "count": 533 + }, + "root_relative_mpjpe_mm": { + "mean": 21.52776574283335, + "count": 533 + }, + "mpvpe_mm": { + "mean": 34.04311977944723, + "count": 533 + }, + "projected_mano_2d_error_px": { + "mean": 17.788362384066126, + "count": 533 + }, + "local_pose_angle_deg": { + "mean": 27.234358057519508, + "count": 533 + }, + "root_relative_fingertip_mm": { + "mean": 32.95283207705499, + "count": 533 + }, + "distal_angle_bias_deg": { + "mean": -6.985119397152656, + "count": 533 + }, + "distal_angle_mae_deg": { + "mean": 16.545601153239524, + "count": 533 + }, + "gt60_angle_bias_deg": { + "mean": -29.891554515973656, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 23.92560712436798, + 22.683508157730103, + 16.856309727924625, + 29.068302581726275, + 23.02515801614042, + 13.338183130377006, + 46.90253536405975, + 49.20713007204081, + 40.48953039158576, + 28.62598706969177, + 31.80408643289534, + 20.20965911277463, + 16.442484231200943, + 20.562006493223095, + 25.374860650379258 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -1.4028389807266322, + "recording_bootstrap_95ci": [ + -2.47251816906761, + -0.37485959815920067 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.3028778949329598, + "recording_bootstrap_95ci": [ + -0.5462561524228046, + -0.13735260363121207 + ], + "count": 533, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": -1.376289773837263, + "recording_bootstrap_95ci": [ + -2.434373505345053, + -0.3432469522409336 + ], + "count": 533, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.38389640901146865, + "recording_bootstrap_95ci": [ + 0.15653971750391832, + 0.5786491150784492 + ], + "count": 533, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": -0.028483108105400043, + "recording_bootstrap_95ci": [ + -0.21843906501046867, + 0.14482069014688137 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.5140173645448953, + "recording_bootstrap_95ci": [ + -0.8989482441633838, + -0.2544141076451739 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.8787912966833776, + "recording_bootstrap_95ci": [ + 0.4799034452100681, + 1.302207966808622 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": -0.11234595225407527, + "recording_bootstrap_95ci": [ + -0.3001363102130247, + 0.06620961077577975 + ], + "count": 533, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 1.320813307719948, + "recording_bootstrap_95ci": [ + 0.6492644162449839, + 2.1405976400832936 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5854397625852212, + "mean_abs_log_variance_ratio": 0.6131055238598615, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 290, + "gt_variance_6d": 0.6138053009987845, + "pred_variance_6d": 0.5334335994238231, + "pred_gt_ratio": 0.8690599422256854 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.5807387522725387, + "pred_variance_6d": 0.47143133451645586, + "pred_gt_ratio": 0.811778674441231 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.4087374559798051, + "pred_variance_6d": 0.22225234581940267, + "pred_gt_ratio": 0.5437533129588782 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.27216020313339495, + "pred_variance_6d": 0.19109525727237164, + "pred_gt_ratio": 0.7021425435176846 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9921459193572351, + "pred_variance_6d": 0.7255933640445362, + "pred_gt_ratio": 0.7313373465413376 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.45085131937280354, + "pred_variance_6d": 0.20793063408577123, + "pred_gt_ratio": 0.4611955763488315 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.1440343915553799, + "pred_variance_6d": 0.0350005274192252, + "pred_gt_ratio": 0.24300118215702546 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 290, + "gt_variance_6d": 1.0927133588640738, + "pred_variance_6d": 0.5194914996197506, + "pred_gt_ratio": 0.4754142478497619 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9174771232143025, + "pred_variance_6d": 0.40669660644887046, + "pred_gt_ratio": 0.44327710866952597 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7379834224474471, + "pred_variance_6d": 0.2869977946251983, + "pred_gt_ratio": 0.3888946362418268 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7513754751856945, + "pred_variance_6d": 0.4822085701646848, + "pred_gt_ratio": 0.6417677793456222 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.714811725463003, + "pred_variance_6d": 0.2158227781142955, + "pred_gt_ratio": 0.30192954371936365 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.36939217839320143, + "pred_variance_6d": 0.062406943989978224, + "pred_gt_ratio": 0.16894495238485754 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.18054553885693672, + "pred_variance_6d": 0.18975949670086806, + "pred_gt_ratio": 1.0510339823529642 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.24785972821602548, + "pred_variance_6d": 0.1989503851166349, + "pred_gt_ratio": 0.8026732964995307 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.35665097727134426, + "pred_variance_6d": 0.24390178767114148, + "pred_gt_ratio": 0.6838668704546353 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7980280331327785, + "pred_variance_6d": 0.7137126373628245, + "pred_gt_ratio": 0.8943453208793164 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.45202466056999735, + "pred_variance_6d": 0.3496691314052911, + "pred_gt_ratio": 0.7735620684153885 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5573761758309335, + "pred_variance_6d": 0.2559439354413393, + "pred_gt_ratio": 0.45919425074058723 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.28644333077364537, + "pred_variance_6d": 0.11843546294066809, + "pred_gt_ratio": 0.41346908870522364 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8985408974776645, + "pred_variance_6d": 0.5508066877354161, + "pred_gt_ratio": 0.6130012437737791 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5075990704457212, + "pred_variance_6d": 0.19882832929365507, + "pred_gt_ratio": 0.3917034937023516 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.10794738783732755, + "pred_variance_6d": 0.05304267872516913, + "pred_gt_ratio": 0.4913752874233729 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 243, + "gt_variance_6d": 1.0699376260085949, + "pred_variance_6d": 0.49452360264066686, + "pred_gt_ratio": 0.4621985344000738 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7741661980374077, + "pred_variance_6d": 0.3398092150759364, + "pred_gt_ratio": 0.4389357426575693 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5849821902534715, + "pred_variance_6d": 0.3237944112207322, + "pred_gt_ratio": 0.5535115711478887 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8490313559290219, + "pred_variance_6d": 0.45890245773684757, + "pred_gt_ratio": 0.5405011894227512 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.6704939861672432, + "pred_variance_6d": 0.21296056862568868, + "pred_gt_ratio": 0.31761741793246945 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.18305638522721163, + "pred_variance_6d": 0.11252168392017169, + "pred_gt_ratio": 0.6146831960027427 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.25406185431104117, + "pred_variance_6d": 0.22081094531647447, + "pred_gt_ratio": 0.8691227808096744 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.3864964776799549, + "pred_variance_6d": 0.35102065754352196, + "pred_gt_ratio": 0.9082117892784284 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.41223091337116574, + "pred_variance_6d": 0.27725349891531026, + "pred_gt_ratio": 0.6725684317267004 + } + ] + } + }, + "N1_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 36.08386283788627, + "count": 533 + }, + "root_relative_mpjpe_mm": { + "mean": 21.482453058181964, + "count": 533 + }, + "mpvpe_mm": { + "mean": 35.58557491409846, + "count": 533 + }, + "projected_mano_2d_error_px": { + "mean": 17.83857098663502, + "count": 533 + }, + "local_pose_angle_deg": { + "mean": 27.177440426810374, + "count": 533 + }, + "root_relative_fingertip_mm": { + "mean": 32.816205021140725, + "count": 533 + }, + "distal_angle_bias_deg": { + "mean": -6.563559232912189, + "count": 533 + }, + "distal_angle_mae_deg": { + "mean": 16.450115434671655, + "count": 533 + }, + "gt60_angle_bias_deg": { + "mean": -28.73902339217937, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 23.82238064474281, + 22.773965915416913, + 17.02926827751897, + 28.87300081011502, + 23.140316862997373, + 13.346670690888983, + 46.64034617237928, + 49.00897936033711, + 40.14880846052188, + 28.517480843286354, + 31.575685144141737, + 20.13053069418859, + 16.557343523229488, + 20.632440976085626, + 25.46436539689327 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.16630904714788325, + "recording_bootstrap_95ci": [ + -0.447839078357215, + 0.8255816745991217 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.3481905795843471, + "recording_bootstrap_95ci": [ + -0.5684907050979565, + -0.19145381072268336 + ], + "count": 533, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": 0.16616536081396394, + "recording_bootstrap_95ci": [ + -0.44044757658647615, + 0.8233957511526933 + ], + "count": 533, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.43410501158036163, + "recording_bootstrap_95ci": [ + 0.13814239631217792, + 0.6800856631579218 + ], + "count": 533, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": -0.08540073881453465, + "recording_bootstrap_95ci": [ + -0.29049919728924994, + 0.13183560703147032 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.6506444204591676, + "recording_bootstrap_95ci": [ + -1.0260769642992984, + -0.38822551776593106 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 1.3003514609238445, + "recording_bootstrap_95ci": [ + 0.979530992868222, + 1.6379979368756878 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": -0.20783167082194315, + "recording_bootstrap_95ci": [ + -0.4694379506727913, + 0.10440519804256716 + ], + "count": 533, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 2.4733444315142337, + "recording_bootstrap_95ci": [ + 1.6777230725446826, + 3.3333754783194447 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5995855591145596, + "mean_abs_log_variance_ratio": 0.5910064343198856, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 290, + "gt_variance_6d": 0.6138053009987845, + "pred_variance_6d": 0.5337000482772094, + "pred_gt_ratio": 0.8694940356637068 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.5807387522725387, + "pred_variance_6d": 0.49172768259461286, + "pred_gt_ratio": 0.8467278628649991 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.4087374559798051, + "pred_variance_6d": 0.24173698771181956, + "pred_gt_ratio": 0.5914236245668743 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.27216020313339495, + "pred_variance_6d": 0.20783514874748693, + "pred_gt_ratio": 0.763650035363987 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9921459193572351, + "pred_variance_6d": 0.726052660582593, + "pred_gt_ratio": 0.7318002789881639 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.45085131937280354, + "pred_variance_6d": 0.2079369241723209, + "pred_gt_ratio": 0.46120952792505937 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.1440343915553799, + "pred_variance_6d": 0.03545634535905945, + "pred_gt_ratio": 0.24616582870367326 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 290, + "gt_variance_6d": 1.0927133588640738, + "pred_variance_6d": 0.5286579761253943, + "pred_gt_ratio": 0.48380297709086195 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9174771232143025, + "pred_variance_6d": 0.4333152351620442, + "pred_gt_ratio": 0.4722899614586153 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7379834224474471, + "pred_variance_6d": 0.3072147987956295, + "pred_gt_ratio": 0.41628956620296814 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7513754751856945, + "pred_variance_6d": 0.47532543898777757, + "pred_gt_ratio": 0.6326070715447638 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.714811725463003, + "pred_variance_6d": 0.2278962959839182, + "pred_gt_ratio": 0.3188200303181982 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.36939217839320143, + "pred_variance_6d": 0.06437280612630378, + "pred_gt_ratio": 0.1742668358770223 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.18054553885693672, + "pred_variance_6d": 0.1957149052868679, + "pred_gt_ratio": 1.0840196136995184 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.24785972821602548, + "pred_variance_6d": 0.2056822120745125, + "pred_gt_ratio": 0.8298331219634334 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.35665097727134426, + "pred_variance_6d": 0.24897293386060104, + "pred_gt_ratio": 0.6980856628108424 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7980280331327785, + "pred_variance_6d": 0.7164108605858917, + "pred_gt_ratio": 0.8977264342124844 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.45202466056999735, + "pred_variance_6d": 0.3582407935063659, + "pred_gt_ratio": 0.7925248880329423 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5573761758309335, + "pred_variance_6d": 0.2704057840020631, + "pred_gt_ratio": 0.48514054910751003 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.28644333077364537, + "pred_variance_6d": 0.12377431814275186, + "pred_gt_ratio": 0.4321075230079677 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8985408974776645, + "pred_variance_6d": 0.5576836017631185, + "pred_gt_ratio": 0.6206546672818318 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5075990704457212, + "pred_variance_6d": 0.20622015151490983, + "pred_gt_ratio": 0.40626581789014815 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.10794738783732755, + "pred_variance_6d": 0.05185962950361171, + "pred_gt_ratio": 0.48041578904866256 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 243, + "gt_variance_6d": 1.0699376260085949, + "pred_variance_6d": 0.49665191158797695, + "pred_gt_ratio": 0.46418772413933906 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7741661980374077, + "pred_variance_6d": 0.3388190484084328, + "pred_gt_ratio": 0.4376567321944235 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5849821902534715, + "pred_variance_6d": 0.3234347679830534, + "pred_gt_ratio": 0.5528967776658462 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8490313559290219, + "pred_variance_6d": 0.4638795962716961, + "pred_gt_ratio": 0.5463633269045908 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.6704939861672432, + "pred_variance_6d": 0.21185306943119836, + "pred_gt_ratio": 0.31596565189528075 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.18305638522721163, + "pred_variance_6d": 0.1101961189324324, + "pred_gt_ratio": 0.6019791049389277 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.25406185431104117, + "pred_variance_6d": 0.22477006050022286, + "pred_gt_ratio": 0.8847060536094602 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.3864964776799549, + "pred_variance_6d": 0.3649035707089423, + "pred_gt_ratio": 0.9441316849751656 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.41223091337116574, + "pred_variance_6d": 0.29001645655159636, + "pred_gt_ratio": 0.7035291317186357 + } + ] + } + } + } + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_arctic_n1_20k.json b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_arctic_n1_20k.json new file mode 100644 index 0000000000000000000000000000000000000000..3349b027b919a2e2382dcd72c1e7ab64dd3bf88c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_arctic_n1_20k.json @@ -0,0 +1,3070 @@ +{ + "source": "ARCTIC", + "role": "development", + "input_mode": "rgb", + "gt": "source_native_not_refitted", + "clips": 136, + "panel_sha256": "780737bf04f0b31796976dc7e7a01971eef2f96cf44f9b2d2641d61708c49683", + "parent_checkpoint_sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a", + "checkpoints": { + "U0_parent": { + "path": "/home/wuyifan/unified_mot_u0_depthsafe_20261001/runs/U0/update_0020004.pt", + "sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a" + }, + "N1_20K": { + "path": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0020000.pt", + "sha256": "a47c1f157c03b2370e785e6a6ddf0644fc87098b672e91e2e82da40c67894396" + } + }, + "hard_definition": "GT >=2 non-thumb distal angles >=45deg OR >=1 >=60deg; complete 21-joint geometry and MANO pose only", + "groups": { + "all": { + "hands": 1568, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 767, + "variance": 0.6041206514557352 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 767, + "variance": 0.42622491017607517 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 767, + "variance": 0.36013793956825124 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 767, + "variance": 0.16537945493992876 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 767, + "variance": 0.6986380897862388 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 767, + "variance": 0.32717479619499984 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 767, + "variance": 0.11479048415862723 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 767, + "variance": 1.167599519374319 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 767, + "variance": 0.8466303804649719 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 767, + "variance": 0.52456643352366 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 767, + "variance": 0.6685087062162507 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 767, + "variance": 0.7064156976466149 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 767, + "variance": 0.23052468668921106 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 767, + "variance": 0.24381033322493656 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 767, + "variance": 0.32886345901547964 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 767, + "variance": 0.44479070634385803 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 801, + "variance": 0.7087786381727638 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 801, + "variance": 0.3959572086166194 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 801, + "variance": 0.3554500392924433 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 801, + "variance": 0.18899980206505118 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 801, + "variance": 0.7016650020022339 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 801, + "variance": 0.3615881996184217 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 801, + "variance": 0.07292192902480385 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 801, + "variance": 1.0068298690770092 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 801, + "variance": 0.6310660433105342 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 801, + "variance": 0.47947190051608823 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 801, + "variance": 0.6657770069032021 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 801, + "variance": 0.4545595117883542 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 801, + "variance": 0.13893213807109603 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 801, + "variance": 0.2726204271078565 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 801, + "variance": 0.3773495194787544 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 801, + "variance": 0.47425826504130897 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.62759631294377, + "count": 1568 + }, + "root_relative_mpjpe_mm": { + "mean": 20.916816820599596, + "count": 1568 + }, + "mpvpe_mm": { + "mean": 34.19091033296926, + "count": 1568 + }, + "projected_mano_2d_error_px": { + "mean": 17.01909283338449, + "count": 1560 + }, + "local_pose_angle_deg": { + "mean": 24.339378317399902, + "count": 1568 + }, + "root_relative_fingertip_mm": { + "mean": 31.318568994804306, + "count": 1568 + }, + "distal_angle_bias_deg": { + "mean": -4.111982597152189, + "count": 1568 + }, + "distal_angle_mae_deg": { + "mean": 11.895296396193455, + "count": 1568 + }, + "gt60_angle_bias_deg": { + "mean": -31.212367823693604, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 21.097496747210318, + 18.24508785540048, + 13.8429469072393, + 25.46307769927139, + 19.707462538717962, + 11.717333851572203, + 42.689524243984906, + 42.541036103909114, + 36.21159382483789, + 26.673233333594943, + 25.219032170517103, + 15.216072100955916, + 17.53362161692764, + 22.536071663912463, + 26.397065003003394 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6127992698358318, + "mean_abs_log_variance_ratio": 0.5727506075921863, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6041206514557352, + "pred_variance_6d": 0.5511921482978331, + "pred_gt_ratio": 0.9123875288315976 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.42622491017607517, + "pred_variance_6d": 0.343832062740217, + "pred_gt_ratio": 0.806691618746963 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.36013793956825124, + "pred_variance_6d": 0.2278303826675563, + "pred_gt_ratio": 0.6326197760244009 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.16537945493992876, + "pred_variance_6d": 0.09246536513402062, + "pred_gt_ratio": 0.5591103512078153 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6986380897862388, + "pred_variance_6d": 0.5655322393141939, + "pred_gt_ratio": 0.809478108311027 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32717479619499984, + "pred_variance_6d": 0.1747461663296579, + "pred_gt_ratio": 0.5341064420668492 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.11479048415862723, + "pred_variance_6d": 0.02814959863873967, + "pred_gt_ratio": 0.24522588997743197 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 767, + "gt_variance_6d": 1.167599519374319, + "pred_variance_6d": 0.6249371483547054, + "pred_gt_ratio": 0.5352324474144955 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.8466303804649719, + "pred_variance_6d": 0.31838304417774876, + "pred_gt_ratio": 0.37605908259858556 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.52456643352366, + "pred_variance_6d": 0.22408176886037884, + "pred_gt_ratio": 0.42717519562805173 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6685087062162507, + "pred_variance_6d": 0.4820572704361744, + "pred_gt_ratio": 0.721093481586218 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.7064156976466149, + "pred_variance_6d": 0.1446451660138487, + "pred_gt_ratio": 0.204759274879828 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.23052468668921106, + "pred_variance_6d": 0.04911983045416895, + "pred_gt_ratio": 0.2130783958960168 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.24381033322493656, + "pred_variance_6d": 0.19683342044901647, + "pred_gt_ratio": 0.807321895858369 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32886345901547964, + "pred_variance_6d": 0.19762559162455529, + "pred_gt_ratio": 0.6009350878209093 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.44479070634385803, + "pred_variance_6d": 0.24884508283076612, + "pred_gt_ratio": 0.5594655627502914 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7087786381727638, + "pred_variance_6d": 0.6379052134292298, + "pred_gt_ratio": 0.9000062629903094 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3959572086166194, + "pred_variance_6d": 0.28504180565638526, + "pred_gt_ratio": 0.7198803291200423 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3554500392924433, + "pred_variance_6d": 0.21509276427469928, + "pred_gt_ratio": 0.6051279800189687 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.18899980206505118, + "pred_variance_6d": 0.11812940136558889, + "pred_gt_ratio": 0.625023942220481 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7016650020022339, + "pred_variance_6d": 0.45061457661413523, + "pred_gt_ratio": 0.642207571032167 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3615881996184217, + "pred_variance_6d": 0.2728452644411343, + "pred_gt_ratio": 0.7545745816070978 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.07292192902480385, + "pred_variance_6d": 0.04613344806403579, + "pred_gt_ratio": 0.6326416303159484 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 801, + "gt_variance_6d": 1.0068298690770092, + "pred_variance_6d": 0.5024081879929398, + "pred_gt_ratio": 0.499000082758284 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6310660433105342, + "pred_variance_6d": 0.23676330303813614, + "pred_gt_ratio": 0.37517991270151413 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47947190051608823, + "pred_variance_6d": 0.22678861157004102, + "pred_gt_ratio": 0.4729966684719855 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6657770069032021, + "pred_variance_6d": 0.40387497423120194, + "pred_gt_ratio": 0.6066219921138275 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.4545595117883542, + "pred_variance_6d": 0.14379636279023578, + "pred_gt_ratio": 0.3163422149599375 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.13893213807109603, + "pred_variance_6d": 0.09100196407306194, + "pred_gt_ratio": 0.6550101750143176 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.2726204271078565, + "pred_variance_6d": 0.27561943585259463, + "pred_gt_ratio": 1.011000675101839 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3773495194787544, + "pred_variance_6d": 0.4217514916829631, + "pred_gt_ratio": 1.1176680237079477 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47425826504130897, + "pred_variance_6d": 0.3469457456692362, + "pred_gt_ratio": 0.7315544530130992 + } + ] + } + }, + "N1_20K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.82146745798539, + "count": 1568 + }, + "root_relative_mpjpe_mm": { + "mean": 20.674054931317055, + "count": 1568 + }, + "mpvpe_mm": { + "mean": 34.39043676397022, + "count": 1568 + }, + "projected_mano_2d_error_px": { + "mean": 17.397056836653977, + "count": 1560 + }, + "local_pose_angle_deg": { + "mean": 24.421836235693522, + "count": 1568 + }, + "root_relative_fingertip_mm": { + "mean": 30.95205716515074, + "count": 1568 + }, + "distal_angle_bias_deg": { + "mean": -3.4984949091639446, + "count": 1568 + }, + "distal_angle_mae_deg": { + "mean": 11.925036530713646, + "count": 1568 + }, + "gt60_angle_bias_deg": { + "mean": -29.23281649783649, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 21.07802754458116, + 18.65948856386299, + 14.008421645632811, + 25.53133560177319, + 19.818636667515552, + 11.822736952301799, + 42.56480732560158, + 42.6488824799961, + 36.72350142470428, + 26.47589362975286, + 25.064059834243082, + 15.196187311935486, + 17.43798085165267, + 22.645001869040485, + 26.65256266067831 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.19387114504162145, + "recording_bootstrap_95ci": [ + -0.09158296379990123, + 0.46661248534858524 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.24276188928253797, + "recording_bootstrap_95ci": [ + -0.3378100431929142, + -0.15383684192948174 + ], + "count": 1568, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": 0.19952643100096254, + "recording_bootstrap_95ci": [ + -0.07972977172820896, + 0.4643923999752715 + ], + "count": 1568, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.377964003269489, + "recording_bootstrap_95ci": [ + 0.1461754063142825, + 0.6226856624979062 + ], + "count": 1560, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": 0.08245791829362208, + "recording_bootstrap_95ci": [ + -0.013955923634481098, + 0.17918125882221553 + ], + "count": 1568, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.36651182965356477, + "recording_bootstrap_95ci": [ + -0.5149021484898706, + -0.21860297646185894 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.6134876879882447, + "recording_bootstrap_95ci": [ + 0.4511202606278523, + 0.7948067424319187 + ], + "count": 1568, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": 0.029740134520190104, + "recording_bootstrap_95ci": [ + -0.11005548928325322, + 0.14905545362270506 + ], + "count": 1568, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 1.9795513258571118, + "recording_bootstrap_95ci": [ + 1.366102305324694, + 2.7296918163129775 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6402922762755061, + "mean_abs_log_variance_ratio": 0.520196939017064, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6041206514557352, + "pred_variance_6d": 0.5556342407052575, + "pred_gt_ratio": 0.9197405176703674 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.42622491017607517, + "pred_variance_6d": 0.3550596757930279, + "pred_gt_ratio": 0.8330336104624935 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.36013793956825124, + "pred_variance_6d": 0.24883909527026965, + "pred_gt_ratio": 0.6909549590042876 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.16537945493992876, + "pred_variance_6d": 0.10877975000932685, + "pred_gt_ratio": 0.657758547147463 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6986380897862388, + "pred_variance_6d": 0.5663188793648016, + "pred_gt_ratio": 0.8106040704681265 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32717479619499984, + "pred_variance_6d": 0.1889741321764994, + "pred_gt_ratio": 0.5775937950424173 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.11479048415862723, + "pred_variance_6d": 0.03240673100149338, + "pred_gt_ratio": 0.282311998586146 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 767, + "gt_variance_6d": 1.167599519374319, + "pred_variance_6d": 0.6465020041358471, + "pred_gt_ratio": 0.5537018416060053 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.8466303804649719, + "pred_variance_6d": 0.35225915504034133, + "pred_gt_ratio": 0.41607195202099834 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.52456643352366, + "pred_variance_6d": 0.24002394767364005, + "pred_gt_ratio": 0.45756634876793745 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.6685087062162507, + "pred_variance_6d": 0.47961776020309077, + "pred_gt_ratio": 0.7174442991441654 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.7064156976466149, + "pred_variance_6d": 0.1641637619881448, + "pred_gt_ratio": 0.2323897423783862 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.23052468668921106, + "pred_variance_6d": 0.05613767383432933, + "pred_gt_ratio": 0.24352131062654064 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 767, + "gt_variance_6d": 0.24381033322493656, + "pred_variance_6d": 0.2003606413352499, + "pred_gt_ratio": 0.8217889647458031 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 767, + "gt_variance_6d": 0.32886345901547964, + "pred_variance_6d": 0.19892665901744302, + "pred_gt_ratio": 0.604891341874743 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 767, + "gt_variance_6d": 0.44479070634385803, + "pred_variance_6d": 0.2649758499167183, + "pred_gt_ratio": 0.5957315342642776 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7087786381727638, + "pred_variance_6d": 0.6437510852861217, + "pred_gt_ratio": 0.9082540734378175 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3959572086166194, + "pred_variance_6d": 0.2985788959956299, + "pred_gt_ratio": 0.7540685950352912 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3554500392924433, + "pred_variance_6d": 0.23329921340384094, + "pred_gt_ratio": 0.6563488187207546 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.18899980206505118, + "pred_variance_6d": 0.1241294375782152, + "pred_gt_ratio": 0.6567701988147666 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.7016650020022339, + "pred_variance_6d": 0.4737298711257104, + "pred_gt_ratio": 0.6751510617943036 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3615881996184217, + "pred_variance_6d": 0.29089399728108656, + "pred_gt_ratio": 0.8044897416123159 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.07292192902480385, + "pred_variance_6d": 0.0457419689130366, + "pred_gt_ratio": 0.6272731608276272 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 801, + "gt_variance_6d": 1.0068298690770092, + "pred_variance_6d": 0.5164638294786376, + "pred_gt_ratio": 0.5129603772602568 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6310660433105342, + "pred_variance_6d": 0.2483637461314417, + "pred_gt_ratio": 0.39356220916045576 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47947190051608823, + "pred_variance_6d": 0.24234856734941632, + "pred_gt_ratio": 0.5054489472450003 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.6657770069032021, + "pred_variance_6d": 0.42347597244260676, + "pred_gt_ratio": 0.6360627778546524 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.4545595117883542, + "pred_variance_6d": 0.16356429020639096, + "pred_gt_ratio": 0.3598303103654941 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.13893213807109603, + "pred_variance_6d": 0.09454323351509922, + "pred_gt_ratio": 0.6804993778093188 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 801, + "gt_variance_6d": 0.2726204271078565, + "pred_variance_6d": 0.27631375291022886, + "pred_gt_ratio": 1.0135475020766187 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 801, + "gt_variance_6d": 0.3773495194787544, + "pred_variance_6d": 0.43463773962366625, + "pred_gt_ratio": 1.1518173925967787 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 801, + "gt_variance_6d": 0.47425826504130897, + "pred_variance_6d": 0.3500801229921421, + "pred_gt_ratio": 0.7381634623945864 + } + ] + } + } + } + }, + "normal": { + "hands": 1035, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 477, + "variance": 0.5699010059812321 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 477, + "variance": 0.32043017497961696 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 477, + "variance": 0.17137041841495992 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 477, + "variance": 0.093209514507725 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 477, + "variance": 0.4784002229757597 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 477, + "variance": 0.14882381724806748 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 477, + "variance": 0.07720752935442478 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 477, + "variance": 1.1847942889023333 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 477, + "variance": 0.49906953323828607 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 477, + "variance": 0.33117526573572365 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 477, + "variance": 0.5965439728070058 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 477, + "variance": 0.32917522352554507 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 477, + "variance": 0.09575482889376169 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 477, + "variance": 0.26779385793285265 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 477, + "variance": 0.36864379388159163 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 477, + "variance": 0.47448711475703753 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 558, + "variance": 0.6592795114306718 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 558, + "variance": 0.3619243761243408 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 558, + "variance": 0.19477889578850316 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 558, + "variance": 0.1333605768702072 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 558, + "variance": 0.5785755301589407 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 558, + "variance": 0.16567743958066852 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 558, + "variance": 0.05076092282958291 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 558, + "variance": 0.8993044976521545 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 558, + "variance": 0.45081289440831723 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 558, + "variance": 0.39346621144539196 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 558, + "variance": 0.5518684507077155 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 558, + "variance": 0.21194670985420427 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 558, + "variance": 0.09239705921877114 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 558, + "variance": 0.2745392720629573 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 558, + "variance": 0.3572100947679524 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 558, + "variance": 0.4674054724345946 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 33.96329937027272, + "count": 1035 + }, + "root_relative_mpjpe_mm": { + "mean": 20.446218082870264, + "count": 1035 + }, + "mpvpe_mm": { + "mean": 33.55826290840112, + "count": 1035 + }, + "projected_mano_2d_error_px": { + "mean": 16.819089050998706, + "count": 1027 + }, + "local_pose_angle_deg": { + "mean": 22.833865565608665, + "count": 1035 + }, + "root_relative_fingertip_mm": { + "mean": 30.212256455536625, + "count": 1035 + }, + "distal_angle_bias_deg": { + "mean": -2.1798302536425385, + "count": 1035 + }, + "distal_angle_mae_deg": { + "mean": 9.442646320776086, + "count": 1035 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 19.676526484051763, + 16.174382352944157, + 12.314740523854315, + 23.499995102628993, + 17.91413645076291, + 10.951865373832591, + 40.371926761019054, + 39.28303707348552, + 34.61170306712533, + 25.433041658493632, + 21.361070613815013, + 12.611027684015928, + 17.8822580491863, + 23.427045040545256, + 26.995208969208353 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.6787034975622026, + "mean_abs_log_variance_ratio": 0.4900953982068317, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5699010059812321, + "pred_variance_6d": 0.5388082836186078, + "pred_gt_ratio": 0.9454418889661546 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32043017497961696, + "pred_variance_6d": 0.2606392146730714, + "pred_gt_ratio": 0.8134040893297613 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.17137041841495992, + "pred_variance_6d": 0.14662891549702112, + "pred_gt_ratio": 0.8556255907712776 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.093209514507725, + "pred_variance_6d": 0.043601295686962804, + "pred_gt_ratio": 0.4677773070403583 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.4784002229757597, + "pred_variance_6d": 0.44580281199570077, + "pred_gt_ratio": 0.9318616308803213 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.14882381724806748, + "pred_variance_6d": 0.12240336160464915, + "pred_gt_ratio": 0.8224715900185566 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.07720752935442478, + "pred_variance_6d": 0.026264895276653405, + "pred_gt_ratio": 0.34018567225591656 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 477, + "gt_variance_6d": 1.1847942889023333, + "pred_variance_6d": 0.6600389409413983, + "pred_gt_ratio": 0.5570915956667036 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.49906953323828607, + "pred_variance_6d": 0.21920197003327946, + "pred_gt_ratio": 0.4392213017111168 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.33117526573572365, + "pred_variance_6d": 0.178815979749151, + "pred_gt_ratio": 0.5399436438947266 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5965439728070058, + "pred_variance_6d": 0.4516012664515722, + "pred_gt_ratio": 0.7570293004999893 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32917522352554507, + "pred_variance_6d": 0.08356980782729895, + "pred_gt_ratio": 0.25387636083981774 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.09575482889376169, + "pred_variance_6d": 0.04258926680918515, + "pred_gt_ratio": 0.44477408921525197 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.26779385793285265, + "pred_variance_6d": 0.18988665434661195, + "pred_gt_ratio": 0.7090777055619574 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.36864379388159163, + "pred_variance_6d": 0.1899559220689879, + "pred_gt_ratio": 0.515283114002461 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.47448711475703753, + "pred_variance_6d": 0.2483133212782086, + "pred_gt_ratio": 0.5233299568216054 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 558, + "gt_variance_6d": 0.6592795114306718, + "pred_variance_6d": 0.5989702047686952, + "pred_gt_ratio": 0.9085224011723008 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3619243761243408, + "pred_variance_6d": 0.2574838528118043, + "pred_gt_ratio": 0.7114299831613015 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.19477889578850316, + "pred_variance_6d": 0.17611294238465897, + "pred_gt_ratio": 0.9041685017861881 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.1333605768702072, + "pred_variance_6d": 0.11311478308442524, + "pred_gt_ratio": 0.8481875659139798 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5785755301589407, + "pred_variance_6d": 0.3983261695287371, + "pred_gt_ratio": 0.6884601037643483 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.16567743958066852, + "pred_variance_6d": 0.21223392391402757, + "pred_gt_ratio": 1.2810067831274676 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.05076092282958291, + "pred_variance_6d": 0.028959464415209624, + "pred_gt_ratio": 0.5705070515056193 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.8993044976521545, + "pred_variance_6d": 0.4654230744463438, + "pred_gt_ratio": 0.5175366915893782 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.45081289440831723, + "pred_variance_6d": 0.15960464102587324, + "pred_gt_ratio": 0.3540374354982705 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.39346621144539196, + "pred_variance_6d": 0.15577231010474457, + "pred_gt_ratio": 0.3958975525052518 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5518684507077155, + "pred_variance_6d": 0.3541407217203172, + "pred_gt_ratio": 0.6417122074403193 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.21194670985420427, + "pred_variance_6d": 0.08425549716717784, + "pred_gt_ratio": 0.3975315173570575 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.09239705921877114, + "pred_variance_6d": 0.04973937388418574, + "pred_gt_ratio": 0.5383220451466579 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.2745392720629573, + "pred_variance_6d": 0.2908505106514413, + "pred_gt_ratio": 1.05941313410616 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3572100947679524, + "pred_variance_6d": 0.43674068929659554, + "pred_gt_ratio": 1.2226437485768902 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.4674054724345946, + "pred_variance_6d": 0.35650901918165806, + "pred_gt_ratio": 0.7627403618633185 + } + ] + } + }, + "N1_20K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 34.27267776986827, + "count": 1035 + }, + "root_relative_mpjpe_mm": { + "mean": 20.241584310209117, + "count": 1035 + }, + "mpvpe_mm": { + "mean": 33.87595945947988, + "count": 1035 + }, + "projected_mano_2d_error_px": { + "mean": 17.20064983024337, + "count": 1027 + }, + "local_pose_angle_deg": { + "mean": 22.975320197764226, + "count": 1035 + }, + "root_relative_fingertip_mm": { + "mean": 29.936377559422294, + "count": 1035 + }, + "distal_angle_bias_deg": { + "mean": -1.8180079639245923, + "count": 1035 + }, + "distal_angle_mae_deg": { + "mean": 9.582481362854224, + "count": 1035 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 19.63185017074364, + 16.583725431575868, + 12.455338487648158, + 23.712813306661044, + 18.164386668182225, + 11.034734115450854, + 40.393250068950195, + 39.30652289690027, + 34.95022908639217, + 25.38401725464973, + 21.613990774707517, + 12.644926703321762, + 17.865418640081433, + 23.644908698630218, + 27.24367235386429 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.30937839959554625, + "recording_bootstrap_95ci": [ + -0.07915338838075893, + 0.6602953380899245 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.2046337726611446, + "recording_bootstrap_95ci": [ + -0.3021819029056598, + -0.09300610535346394 + ], + "count": 1035, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": 0.31769655107875955, + "recording_bootstrap_95ci": [ + -0.062152152263816894, + 0.6618385670629234 + ], + "count": 1035, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.3815607792446653, + "recording_bootstrap_95ci": [ + 0.09237407310629019, + 0.6961335659807371 + ], + "count": 1027, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": 0.14145463215556123, + "recording_bootstrap_95ci": [ + 0.042591852556566674, + 0.24371782533596054 + ], + "count": 1035, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.2758788961143309, + "recording_bootstrap_95ci": [ + -0.43784943739633997, + -0.10112470189316212 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 0.36182228971794606, + "recording_bootstrap_95ci": [ + 0.18872461350270214, + 0.546651014009907 + ], + "count": 1035, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": 0.13983504207813796, + "recording_bootstrap_95ci": [ + 0.04840967041289519, + 0.22416593813423275 + ], + "count": 1035, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.7056290764923558, + "mean_abs_log_variance_ratio": 0.45524748958830874, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5699010059812321, + "pred_variance_6d": 0.5440554422636009, + "pred_gt_ratio": 0.9546490294869171 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32043017497961696, + "pred_variance_6d": 0.2668455700400974, + "pred_gt_ratio": 0.8327729124046194 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.17137041841495992, + "pred_variance_6d": 0.1597964630567255, + "pred_gt_ratio": 0.9324623498892965 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.093209514507725, + "pred_variance_6d": 0.04599781931186023, + "pred_gt_ratio": 0.4934884550659046 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.4784002229757597, + "pred_variance_6d": 0.44416625136713783, + "pred_gt_ratio": 0.9284407281508386 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.14882381724806748, + "pred_variance_6d": 0.12448215807674998, + "pred_gt_ratio": 0.8364397606416484 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.07720752935442478, + "pred_variance_6d": 0.02872607135412952, + "pred_gt_ratio": 0.372063082374533 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 477, + "gt_variance_6d": 1.1847942889023333, + "pred_variance_6d": 0.6856880489666581, + "pred_gt_ratio": 0.5787401706687175 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.49906953323828607, + "pred_variance_6d": 0.23823843223545121, + "pred_gt_ratio": 0.47736520939197813 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.33117526573572365, + "pred_variance_6d": 0.19030604853998243, + "pred_gt_ratio": 0.574638471617762 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.5965439728070058, + "pred_variance_6d": 0.4552100348911576, + "pred_gt_ratio": 0.7630787597252741 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.32917522352554507, + "pred_variance_6d": 0.08557006771589942, + "pred_gt_ratio": 0.2599529417780099 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.09575482889376169, + "pred_variance_6d": 0.045259464641494454, + "pred_gt_ratio": 0.4726598664983156 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 477, + "gt_variance_6d": 0.26779385793285265, + "pred_variance_6d": 0.19313666872265722, + "pred_gt_ratio": 0.7212139599224296 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 477, + "gt_variance_6d": 0.36864379388159163, + "pred_variance_6d": 0.1913303116927089, + "pred_gt_ratio": 0.5190113460967803 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 477, + "gt_variance_6d": 0.47448711475703753, + "pred_variance_6d": 0.2636690335744647, + "pred_gt_ratio": 0.5556927161435715 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 558, + "gt_variance_6d": 0.6592795114306718, + "pred_variance_6d": 0.6062403253090459, + "pred_gt_ratio": 0.9195497733479872 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3619243761243408, + "pred_variance_6d": 0.2683889702551516, + "pred_gt_ratio": 0.7415609115064008 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.19477889578850316, + "pred_variance_6d": 0.18738542321610668, + "pred_gt_ratio": 0.9620417163652857 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.1333605768702072, + "pred_variance_6d": 0.11700472865310967, + "pred_gt_ratio": 0.8773561977538848 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5785755301589407, + "pred_variance_6d": 0.4192409798503326, + "pred_gt_ratio": 0.7246089023764326 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.16567743958066852, + "pred_variance_6d": 0.22678320084812298, + "pred_gt_ratio": 1.3688236697894043 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.05076092282958291, + "pred_variance_6d": 0.029097792185220836, + "pred_gt_ratio": 0.5732321353358644 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.8993044976521545, + "pred_variance_6d": 0.4802275330446767, + "pred_gt_ratio": 0.533998811635462 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.45081289440831723, + "pred_variance_6d": 0.16667576924976588, + "pred_gt_ratio": 0.3697227193745743 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.39346621144539196, + "pred_variance_6d": 0.16705253155940547, + "pred_gt_ratio": 0.4245663965547146 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.5518684507077155, + "pred_variance_6d": 0.37119282324165737, + "pred_gt_ratio": 0.6726110593306069 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.21194670985420427, + "pred_variance_6d": 0.09613879055317084, + "pred_gt_ratio": 0.45359888162125106 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.09239705921877114, + "pred_variance_6d": 0.0527686447338591, + "pred_gt_ratio": 0.5711074051493055 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 558, + "gt_variance_6d": 0.2745392720629573, + "pred_variance_6d": 0.29279807940470554, + "pred_gt_ratio": 1.0665070873268765 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 558, + "gt_variance_6d": 0.3572100947679524, + "pred_variance_6d": 0.45669552789539064, + "pred_gt_ratio": 1.2785067795804177 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 558, + "gt_variance_6d": 0.4674054724345946, + "pred_variance_6d": 0.35974714773254823, + "pred_gt_ratio": 0.7696682408503223 + } + ] + } + } + } + }, + "hard": { + "hands": 533, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 290, + "variance": 0.6138053009987845 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 290, + "variance": 0.5807387522725387 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 290, + "variance": 0.4087374559798051 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 290, + "variance": 0.27216020313339495 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 290, + "variance": 0.9921459193572351 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 290, + "variance": 0.45085131937280354 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 290, + "variance": 0.1440343915553799 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 290, + "variance": 1.0927133588640738 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 290, + "variance": 0.9174771232143025 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 290, + "variance": 0.7379834224474471 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 290, + "variance": 0.7513754751856945 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 290, + "variance": 0.714811725463003 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 290, + "variance": 0.36939217839320143 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 290, + "variance": 0.18054553885693672 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 290, + "variance": 0.24785972821602548 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 290, + "variance": 0.35665097727134426 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 243, + "variance": 0.7980280331327785 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 243, + "variance": 0.45202466056999735 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 243, + "variance": 0.5573761758309335 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 243, + "variance": 0.28644333077364537 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 243, + "variance": 0.8985408974776645 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 243, + "variance": 0.5075990704457212 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 243, + "variance": 0.10794738783732755 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 243, + "variance": 1.0699376260085949 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 243, + "variance": 0.7741661980374077 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 243, + "variance": 0.5849821902534715 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 243, + "variance": 0.8490313559290219 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 243, + "variance": 0.6704939861672432 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 243, + "variance": 0.18305638522721163 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 243, + "variance": 0.25406185431104117 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 243, + "variance": 0.3864964776799549 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 243, + "variance": 0.41223091337116574 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 35.91755379073839, + "count": 533 + }, + "root_relative_mpjpe_mm": { + "mean": 21.83064363776631, + "count": 533 + }, + "mpvpe_mm": { + "mean": 35.419409553284495, + "count": 533 + }, + "projected_mano_2d_error_px": { + "mean": 17.404465975054656, + "count": 533 + }, + "local_pose_angle_deg": { + "mean": 27.26284116562491, + "count": 533 + }, + "root_relative_fingertip_mm": { + "mean": 33.46684944159989, + "count": 533 + }, + "distal_angle_bias_deg": { + "mean": -7.863910693836033, + "count": 533 + }, + "distal_angle_mae_deg": { + "mean": 16.657947105493598, + "count": 533 + }, + "gt60_angle_bias_deg": { + "mean": -31.212367823693604, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 23.856791723512575, + 22.266063831089586, + 16.810477126382754, + 29.275067356916573, + 23.18981244684831, + 13.203750126357374, + 47.18992460959401, + 48.86754454009752, + 39.31832353259117, + 29.081485460667853, + 32.7105710282782, + 20.27464803253732, + 16.85662591826401, + 20.805945125798125, + 25.235565931667306 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5672533057603333, + "mean_abs_log_variance_ratio": 0.6630044852114826, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 290, + "gt_variance_6d": 0.6138053009987845, + "pred_variance_6d": 0.5331670768358004, + "pred_gt_ratio": 0.8686257286605875 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.5807387522725387, + "pred_variance_6d": 0.47512359654399117, + "pred_gt_ratio": 0.8181365453652684 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.4087374559798051, + "pred_variance_6d": 0.2152719041957326, + "pred_gt_ratio": 0.5266752558306493 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.27216020313339495, + "pred_variance_6d": 0.16802313826440407, + "pred_gt_ratio": 0.6173685069673843 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9921459193572351, + "pred_variance_6d": 0.7177526368918237, + "pred_gt_ratio": 0.7234345501887687 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.45085131937280354, + "pred_variance_6d": 0.18177143789145783, + "pred_gt_ratio": 0.4031737960628063 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.1440343915553799, + "pred_variance_6d": 0.02874270008714776, + "pred_gt_ratio": 0.19955442430633977 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 290, + "gt_variance_6d": 1.0927133588640738, + "pred_variance_6d": 0.5114034524648663, + "pred_gt_ratio": 0.4680124465545968 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9174771232143025, + "pred_variance_6d": 0.3764370498587525, + "pred_gt_ratio": 0.4102958431703861 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7379834224474471, + "pred_variance_6d": 0.27861291686302936, + "pred_gt_ratio": 0.37753275803816555 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7513754751856945, + "pred_variance_6d": 0.4823447623497834, + "pred_gt_ratio": 0.6419490365061183 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.714811725463003, + "pred_variance_6d": 0.1820837355802205, + "pred_gt_ratio": 0.254729642917203 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.36939217839320143, + "pred_variance_6d": 0.05061809008710885, + "pred_gt_ratio": 0.13703075768222728 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.18054553885693672, + "pred_variance_6d": 0.1896830043657758, + "pred_gt_ratio": 1.0506103089928993 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.24785972821602548, + "pred_variance_6d": 0.20367322164706406, + "pred_gt_ratio": 0.8217277696260117 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.35665097727134426, + "pred_variance_6d": 0.23329010132503994, + "pred_gt_ratio": 0.6541131699957465 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7980280331327785, + "pred_variance_6d": 0.7134306667079935, + "pred_gt_ratio": 0.8939919866064286 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.45202466056999735, + "pred_variance_6d": 0.3313177009358491, + "pred_gt_ratio": 0.7329637735208112 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5573761758309335, + "pred_variance_6d": 0.23654249808959835, + "pred_gt_ratio": 0.42438573506835314 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.28644333077364537, + "pred_variance_6d": 0.11312523968327501, + "pred_gt_ratio": 0.3949306111534829 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8985408974776645, + "pred_variance_6d": 0.5232708666048927, + "pred_gt_ratio": 0.5823562044574604 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5075990704457212, + "pred_variance_6d": 0.1929200840702889, + "pred_gt_ratio": 0.38006390338911844 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.10794738783732755, + "pred_variance_6d": 0.053333256564659016, + "pred_gt_ratio": 0.4940671343064839 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 243, + "gt_variance_6d": 1.0699376260085949, + "pred_variance_6d": 0.48512772744092564, + "pred_gt_ratio": 0.45341683070881045 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7741661980374077, + "pred_variance_6d": 0.31657512287231354, + "pred_gt_ratio": 0.4089239799862931 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5849821902534715, + "pred_variance_6d": 0.29819692319228, + "pred_gt_ratio": 0.5097538491950873 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8490313559290219, + "pred_variance_6d": 0.43745282433973454, + "pred_gt_ratio": 0.5152375366173226 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.6704939861672432, + "pred_variance_6d": 0.18454466285225757, + "pred_gt_ratio": 0.2752368651465072 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.18305638522721163, + "pred_variance_6d": 0.10534866215101288, + "pred_gt_ratio": 0.5754984291875584 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.25406185431104117, + "pred_variance_6d": 0.22765505081001353, + "pred_gt_ratio": 0.8960615178825764 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.3864964776799549, + "pred_variance_6d": 0.3660450329782435, + "pred_gt_ratio": 0.947085042470564 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.41223091337116574, + "pred_variance_6d": 0.2865672017975346, + "pred_gt_ratio": 0.6951618437686509 + } + ] + } + }, + "N1_20K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 35.88712848462933, + "count": 533 + }, + "root_relative_mpjpe_mm": { + "mean": 21.513843098008834, + "count": 533 + }, + "mpvpe_mm": { + "mean": 35.389468677943015, + "count": 533 + }, + "projected_mano_2d_error_px": { + "mean": 17.775499605103683, + "count": 533 + }, + "local_pose_angle_deg": { + "mean": 27.230736984768235, + "count": 533 + }, + "root_relative_fingertip_mm": { + "mean": 32.92434307871348, + "count": 533 + }, + "distal_angle_bias_deg": { + "mean": -6.761729408831354, + "count": 533 + }, + "distal_angle_mae_deg": { + "mean": 16.47390069344254, + "count": 533 + }, + "gt60_angle_bias_deg": { + "mean": -29.23281649783649, + "count": 452 + } + }, + "local_pose_per_joint_mean_deg": [ + 23.886270662633382, + 22.69028564063067, + 17.024258547160237, + 29.06261247877332, + 23.030923251586827, + 13.352911316543315, + 46.78162113542181, + 49.13920549782758, + 40.16691018671748, + 28.59614137502817, + 31.76353727630558, + 20.150323765810167, + 16.607965633972054, + 20.703344141788374, + 25.504723012559186 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.03042530610905803, + "recording_bootstrap_95ci": [ + -0.6081929430356261, + 0.5665492490783562 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_mpjpe_mm": { + "delta": -0.3168005397574763, + "recording_bootstrap_95ci": [ + -0.5248615797518883, + -0.1664722236776196 + ], + "count": 533, + "recordings": 17 + }, + "mpvpe_mm": { + "delta": -0.02994087534147624, + "recording_bootstrap_95ci": [ + -0.601598684830614, + 0.5638093706757963 + ], + "count": 533, + "recordings": 17 + }, + "projected_mano_2d_error_px": { + "delta": 0.3710336300490274, + "recording_bootstrap_95ci": [ + 0.1138270684955096, + 0.5956986095906099 + ], + "count": 533, + "recordings": 17 + }, + "local_pose_angle_deg": { + "delta": -0.03210418085667251, + "recording_bootstrap_95ci": [ + -0.21307960258200315, + 0.16685881915660075 + ], + "count": 533, + "recordings": 17 + }, + "root_relative_fingertip_mm": { + "delta": -0.542506362886411, + "recording_bootstrap_95ci": [ + -0.8918297578342659, + -0.2993112227666091 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_bias_deg": { + "delta": 1.1021812850046784, + "recording_bootstrap_95ci": [ + 0.7913193821002061, + 1.463183066276544 + ], + "count": 533, + "recordings": 17 + }, + "distal_angle_mae_deg": { + "delta": -0.1840464120510595, + "recording_bootstrap_95ci": [ + -0.41189434777741923, + 0.07344978287362605 + ], + "count": 533, + "recordings": 17 + }, + "gt60_angle_bias_deg": { + "delta": 1.9795513258571118, + "recording_bootstrap_95ci": [ + 1.366102305324694, + 2.7296918163129775 + ], + "count": 452, + "recordings": 16 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5950314046390268, + "mean_abs_log_variance_ratio": 0.5978802671568095, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 290, + "gt_variance_6d": 0.6138053009987845, + "pred_variance_6d": 0.5368910472423211, + "pred_gt_ratio": 0.8746927508913519 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.5807387522725387, + "pred_variance_6d": 0.494428428749103, + "pred_gt_ratio": 0.8513783983147545 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.4087374559798051, + "pred_variance_6d": 0.2327123849553438, + "pred_gt_ratio": 0.5693444081299015 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.27216020313339495, + "pred_variance_6d": 0.2058745502375074, + "pred_gt_ratio": 0.7564461955394753 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9921459193572351, + "pred_variance_6d": 0.7263019025559774, + "pred_gt_ratio": 0.7320514940247039 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.45085131937280354, + "pred_variance_6d": 0.20614293756653876, + "pred_gt_ratio": 0.45723041878487136 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.1440343915553799, + "pred_variance_6d": 0.0358581697252323, + "pred_gt_ratio": 0.24895560940697392 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 290, + "gt_variance_6d": 1.0927133588640738, + "pred_variance_6d": 0.5240830592563502, + "pred_gt_ratio": 0.4796162278103371 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.9174771232143025, + "pred_variance_6d": 0.42713354731527553, + "pred_gt_ratio": 0.46555225902401765 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7379834224474471, + "pred_variance_6d": 0.302814039285836, + "pred_gt_ratio": 0.4103263434855813 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.7513754751856945, + "pred_variance_6d": 0.47307093124576854, + "pred_gt_ratio": 0.6296065640535501 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.714811725463003, + "pred_variance_6d": 0.21960577415026442, + "pred_gt_ratio": 0.30722184083930604 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.36939217839320143, + "pred_variance_6d": 0.0641810547373747, + "pred_gt_ratio": 0.1737477361230341 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 290, + "gt_variance_6d": 0.18054553885693672, + "pred_variance_6d": 0.19195267445935554, + "pred_gt_ratio": 1.0631814869236829 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 290, + "gt_variance_6d": 0.24785972821602548, + "pred_variance_6d": 0.20438521442399626, + "pred_gt_ratio": 0.8246003329990808 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 290, + "gt_variance_6d": 0.35665097727134426, + "pred_variance_6d": 0.2486582927545663, + "pred_gt_ratio": 0.6972034526780061 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7980280331327785, + "pred_variance_6d": 0.715779304659913, + "pred_gt_ratio": 0.8969350385474734 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.45202466056999735, + "pred_variance_6d": 0.35125582876774686, + "pred_gt_ratio": 0.7770722692979134 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5573761758309335, + "pred_variance_6d": 0.26286912156122316, + "pred_gt_ratio": 0.47161886883546694 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.28644333077364537, + "pred_variance_6d": 0.12167526944348687, + "pred_gt_ratio": 0.42477955103670295 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8985408974776645, + "pred_variance_6d": 0.5499556012753137, + "pred_gt_ratio": 0.6120540565478092 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5075990704457212, + "pred_variance_6d": 0.2064714716749546, + "pred_gt_ratio": 0.40676093337533625 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.10794738783732755, + "pred_variance_6d": 0.05177656642653429, + "pred_gt_ratio": 0.4796463116324735 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 243, + "gt_variance_6d": 1.0699376260085949, + "pred_variance_6d": 0.49385574938364807, + "pred_gt_ratio": 0.4615743360909535 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.7741661980374077, + "pred_variance_6d": 0.3392961219264325, + "pred_gt_ratio": 0.4382729739254745 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.5849821902534715, + "pred_variance_6d": 0.3190903533206101, + "pred_gt_ratio": 0.5454702017207548 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.8490313559290219, + "pred_variance_6d": 0.4614587492484418, + "pred_gt_ratio": 0.5435120222898097 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.6704939861672432, + "pred_variance_6d": 0.21159793533370436, + "pred_gt_ratio": 0.31558513528699256 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.18305638522721163, + "pred_variance_6d": 0.10912806311680515, + "pred_gt_ratio": 0.5961445320869533 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 243, + "gt_variance_6d": 0.25406185431104117, + "pred_variance_6d": 0.22560885874543873, + "pred_gt_ratio": 0.8880076049088101 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 243, + "gt_variance_6d": 0.3864964776799549, + "pred_variance_6d": 0.36319175577818463, + "pred_gt_ratio": 0.9397026279730598 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 243, + "gt_variance_6d": 0.41223091337116574, + "pred_variance_6d": 0.2896800077559799, + "pred_gt_ratio": 0.7027129658642484 + } + ] + } + } + } + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_h2o_12k18k.json b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_h2o_12k18k.json new file mode 100644 index 0000000000000000000000000000000000000000..9b6421890910bc4c3b61384185b11195eabf4813 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_h2o_12k18k.json @@ -0,0 +1,6979 @@ +{ + "source": "H2O", + "role": "development", + "input_mode": "rgb", + "gt": "source_native_not_refitted", + "clips": 96, + "panel_sha256": "5dac67629afe705e237e410011727f2bc6f115ca86a9c5a42e9ad925822432ec", + "parent_checkpoint_sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a", + "checkpoints": { + "U0_parent": { + "path": "/home/wuyifan/unified_mot_u0_depthsafe_20261001/runs/U0/update_0020004.pt", + "sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a" + }, + "N0_12K": { + "path": "/home/wuyifan/u0_normalized6d_20261002/runs/N0_formal/update_0012000.pt", + "sha256": "f6cf83fc77f577153bfaa71c16717fa36b04bf1639f924a27f137925e73a9a00" + }, + "N0_18K": { + "path": "/home/wuyifan/u0_normalized6d_20261002/runs/N0_formal/update_0018000.pt", + "sha256": "3d176e8949c5738c0ae19690e528968071734f439b7a5efb47d27db954a1feea" + }, + "N1_12K": { + "path": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0012000.pt", + "sha256": "ebe561dbf78d6488180c5f5ee0381432bf739e7a0f68961752d28986210d4958" + }, + "N1_18K": { + "path": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0018000.pt", + "sha256": "07ffd4d5463d64e5762f9dfa268d6539bff28c4d4dcf078c85cd7d7f3b17af2b" + } + }, + "hard_definition": "GT >=2 non-thumb distal angles >=45deg OR >=1 >=60deg; complete 21-joint geometry and MANO pose only", + "groups": { + "all": { + "hands": 1536, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 768, + "variance": 0.6276556489562777 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 768, + "variance": 0.09593922255610139 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 768, + "variance": 0.12244189528720367 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 768, + "variance": 0.03214429306650994 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 768, + "variance": 0.13904494533806688 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 768, + "variance": 0.08829846748000257 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 768, + "variance": 0.042789003839059675 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 768, + "variance": 0.23990383480120056 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 768, + "variance": 0.06611468194100378 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 768, + "variance": 0.04967650231648196 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 768, + "variance": 0.1615580244429538 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 768, + "variance": 0.12077039788861064 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 768, + "variance": 0.05196939792383421 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 768, + "variance": 0.10800775482101788 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 768, + "variance": 0.02196545540494259 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 768, + "variance": 0.048189028939135216 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 768, + "variance": 0.6731547796707966 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 768, + "variance": 0.12440969118655591 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 768, + "variance": 0.10154130448647992 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 768, + "variance": 0.031123622695296803 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 768, + "variance": 0.2352408934541732 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 768, + "variance": 0.1985170871883211 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 768, + "variance": 0.14216654828818165 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 768, + "variance": 0.3842963067498238 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 768, + "variance": 0.15250539617004505 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 768, + "variance": 0.16994163048790034 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 768, + "variance": 0.2784070818638871 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 768, + "variance": 0.21526081221477664 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 768, + "variance": 0.165995085812219 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 768, + "variance": 0.12790844637157237 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 768, + "variance": 0.02238697863982246 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 768, + "variance": 0.04676594210336735 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 20.630753997092445, + "count": 1536 + }, + "root_relative_mpjpe_mm": { + "mean": 13.283040416582176, + "count": 1536 + }, + "mpvpe_mm": { + "mean": 20.46384940482676, + "count": 1536 + }, + "projected_mano_2d_error_px": { + "mean": 10.793614093214273, + "count": 1536 + }, + "local_pose_angle_deg": { + "mean": 10.023834046442062, + "count": 1536 + }, + "root_relative_fingertip_mm": { + "mean": 19.17614179197699, + "count": 1536 + }, + "distal_angle_bias_deg": { + "mean": -0.9564234532105426, + "count": 1536 + }, + "distal_angle_mae_deg": { + "mean": 6.352203568909317, + "count": 1536 + }, + "gt60_angle_bias_deg": { + "mean": -14.813732662861296, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 8.133591202863803, + 8.277025114706097, + 6.608799953750956, + 9.257692793772245, + 9.766511462745257, + 7.905319208997146, + 16.600299852201715, + 10.179078662962032, + 7.10320868868924, + 11.299065872405967, + 11.998560446586149, + 7.779385318552765, + 11.297737618151587, + 10.817307048632452, + 13.33391980852078 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8051487100534478, + "mean_abs_log_variance_ratio": 0.2533391585966686, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 768, + "gt_variance_6d": 0.6276556489562777, + "pred_variance_6d": 0.5874918649316394, + "pred_gt_ratio": 0.9360098421938428 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.09593922255610139, + "pred_variance_6d": 0.07778560258846287, + "pred_gt_ratio": 0.8107799971276293 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12244189528720367, + "pred_variance_6d": 0.1168757153498433, + "pred_gt_ratio": 0.9545402337630909 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.03214429306650994, + "pred_variance_6d": 0.024110743965079826, + "pred_gt_ratio": 0.7500785260759086 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.13904494533806688, + "pred_variance_6d": 0.1195750362697045, + "pred_gt_ratio": 0.8599739888348747 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.08829846748000257, + "pred_variance_6d": 0.07201167521845961, + "pred_gt_ratio": 0.815548415206283 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.042789003839059675, + "pred_variance_6d": 0.031225209131742638, + "pred_gt_ratio": 0.7297484477364463 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.23990383480120056, + "pred_variance_6d": 0.21911837499865977, + "pred_gt_ratio": 0.9133592015327102 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.06611468194100378, + "pred_variance_6d": 0.04235992035914568, + "pred_gt_ratio": 0.6407036851049934 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.04967650231648196, + "pred_variance_6d": 0.044097592466890975, + "pred_gt_ratio": 0.8876951961301836 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.1615580244429538, + "pred_variance_6d": 0.1477043428590606, + "pred_gt_ratio": 0.9142494987069804 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12077039788861064, + "pred_variance_6d": 0.08434409855039804, + "pred_gt_ratio": 0.6983838757258262 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.05196939792383421, + "pred_variance_6d": 0.03732461647426406, + "pred_gt_ratio": 0.7182037500023881 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.10800775482101788, + "pred_variance_6d": 0.10121903508856749, + "pred_gt_ratio": 0.937145997121224 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.02196545540494259, + "pred_variance_6d": 0.014219863191042029, + "pred_gt_ratio": 0.6473739300593934 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.048189028939135216, + "pred_variance_6d": 0.05434897701675566, + "pred_gt_ratio": 1.1278288484584473 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 768, + "gt_variance_6d": 0.6731547796707966, + "pred_variance_6d": 0.6340252315793864, + "pred_gt_ratio": 0.9418713952970127 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12440969118655591, + "pred_variance_6d": 0.10646028775191341, + "pred_gt_ratio": 0.8557234306793121 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.10154130448647992, + "pred_variance_6d": 0.11086737969909391, + "pred_gt_ratio": 1.0918451388799693 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.031123622695296803, + "pred_variance_6d": 0.014583675687340687, + "pred_gt_ratio": 0.46857256400118474 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2352408934541732, + "pred_variance_6d": 0.19332894972628667, + "pred_gt_ratio": 0.8218339374907564 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.1985170871883211, + "pred_variance_6d": 0.12324392727682683, + "pred_gt_ratio": 0.6208227665556709 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.14216654828818165, + "pred_variance_6d": 0.13941315507494761, + "pred_gt_ratio": 0.9806326224671875 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.3842963067498238, + "pred_variance_6d": 0.320407883459355, + "pred_gt_ratio": 0.8337521798457979 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.15250539617004505, + "pred_variance_6d": 0.10704969239019525, + "pred_gt_ratio": 0.7019403580371266 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.16994163048790034, + "pred_variance_6d": 0.16451919053915653, + "pred_gt_ratio": 0.9680923389214517 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2784070818638871, + "pred_variance_6d": 0.23288592064873978, + "pred_gt_ratio": 0.8364942410574077 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.21526081221477664, + "pred_variance_6d": 0.12580112282325645, + "pred_gt_ratio": 0.5844125622723113 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.165995085812219, + "pred_variance_6d": 0.15670288532292886, + "pred_gt_ratio": 0.9440212314489727 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12790844637157237, + "pred_variance_6d": 0.10389876096632726, + "pred_gt_ratio": 0.8122900708566401 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.02238697863982246, + "pred_variance_6d": 0.010189021252917766, + "pred_gt_ratio": 0.45513159309462625 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.04676594210336735, + "pred_variance_6d": 0.023649483469355196, + "pred_gt_ratio": 0.5056988570246793 + } + ] + } + }, + "N0_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 20.87767661968246, + "count": 1536 + }, + "root_relative_mpjpe_mm": { + "mean": 13.277919396292418, + "count": 1536 + }, + "mpvpe_mm": { + "mean": 20.69843883595119, + "count": 1536 + }, + "projected_mano_2d_error_px": { + "mean": 10.810128074139357, + "count": 1536 + }, + "local_pose_angle_deg": { + "mean": 10.104041242506355, + "count": 1536 + }, + "root_relative_fingertip_mm": { + "mean": 19.168040919738512, + "count": 1536 + }, + "distal_angle_bias_deg": { + "mean": -0.9271085263462737, + "count": 1536 + }, + "distal_angle_mae_deg": { + "mean": 6.397998473684614, + "count": 1536 + }, + "gt60_angle_bias_deg": { + "mean": -14.418034544683618, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 8.409391750436043, + 8.345471868757159, + 6.696537224944525, + 9.356286743888631, + 9.82862784905592, + 8.006599679143013, + 16.70240706302381, + 10.176523888173202, + 7.106651913617195, + 11.426089045979703, + 12.198029357086247, + 7.8670302065826645, + 11.440022341286143, + 10.91484893167702, + 13.086092375781542 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.24692262259001532, + "recording_bootstrap_95ci": [ + -0.12016872365881377, + 0.658635336055886 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": -0.0051210202897588415, + "recording_bootstrap_95ci": [ + -0.11403486321602638, + 0.10820972083214046 + ], + "count": 1536, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.2345894311244289, + "recording_bootstrap_95ci": [ + -0.13326149166096002, + 0.6478433752044414 + ], + "count": 1536, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.01651398092508316, + "recording_bootstrap_95ci": [ + -0.1906814277366114, + 0.20986617093052096 + ], + "count": 1536, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.08020719606429338, + "recording_bootstrap_95ci": [ + 0.036770264928539596, + 0.12282777919899672 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": -0.008100872238477072, + "recording_bootstrap_95ci": [ + -0.20953503327133755, + 0.1937817429735635 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.02931492686426888, + "recording_bootstrap_95ci": [ + -0.10471701006851315, + 0.15118095744692242 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.04579490477529665, + "recording_bootstrap_95ci": [ + 0.00040486506574476767, + 0.09010998039739204 + ], + "count": 1536, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.3956981181776781, + "recording_bootstrap_95ci": [ + -0.15981417210925783, + 0.7368247920675336 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8204481570504639, + "mean_abs_log_variance_ratio": 0.2343610670994323, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 768, + "gt_variance_6d": 0.6276556489562777, + "pred_variance_6d": 0.591127260084809, + "pred_gt_ratio": 0.9418018639166056 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.09593922255610139, + "pred_variance_6d": 0.07832130341228562, + "pred_gt_ratio": 0.816363749106748 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12244189528720367, + "pred_variance_6d": 0.1175145585462982, + "pred_gt_ratio": 0.9597577550613069 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.03214429306650994, + "pred_variance_6d": 0.025294070335014424, + "pred_gt_ratio": 0.7868914796999368 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.13904494533806688, + "pred_variance_6d": 0.12456842266936684, + "pred_gt_ratio": 0.8958860199232518 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.08829846748000257, + "pred_variance_6d": 0.0769031652768147, + "pred_gt_ratio": 0.870945640072761 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.042789003839059675, + "pred_variance_6d": 0.03114650717446143, + "pred_gt_ratio": 0.7279091444056833 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.23990383480120056, + "pred_variance_6d": 0.22094301323958143, + "pred_gt_ratio": 0.9209649083878494 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.06611468194100378, + "pred_variance_6d": 0.04291249014741744, + "pred_gt_ratio": 0.6490614321597978 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.04967650231648196, + "pred_variance_6d": 0.04552146829834948, + "pred_gt_ratio": 0.9163581608129061 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.1615580244429538, + "pred_variance_6d": 0.14951252131782938, + "pred_gt_ratio": 0.9254416289957934 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12077039788861064, + "pred_variance_6d": 0.0901885217607634, + "pred_gt_ratio": 0.7467767212619966 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.05196939792383421, + "pred_variance_6d": 0.038348404781400516, + "pred_gt_ratio": 0.7379035800569312 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.10800775482101788, + "pred_variance_6d": 0.10391244867681224, + "pred_gt_ratio": 0.9620832212372893 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.02196545540494259, + "pred_variance_6d": 0.01379591284856934, + "pred_gt_ratio": 0.6280731536968285 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.048189028939135216, + "pred_variance_6d": 0.05213414461177003, + "pred_gt_ratio": 1.0818675071792307 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 768, + "gt_variance_6d": 0.6731547796707966, + "pred_variance_6d": 0.6404219020720066, + "pred_gt_ratio": 0.9513739208465578 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12440969118655591, + "pred_variance_6d": 0.1057682175041296, + "pred_gt_ratio": 0.8501605983855961 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.10154130448647992, + "pred_variance_6d": 0.11220617392273176, + "pred_gt_ratio": 1.1050298643511305 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.031123622695296803, + "pred_variance_6d": 0.014957361724597697, + "pred_gt_ratio": 0.4805790723988553 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2352408934541732, + "pred_variance_6d": 0.2010974659180913, + "pred_gt_ratio": 0.8548576013518104 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.1985170871883211, + "pred_variance_6d": 0.12676113917013832, + "pred_gt_ratio": 0.6385401930156659 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.14216654828818165, + "pred_variance_6d": 0.14289424881931959, + "pred_gt_ratio": 1.0051186480919747 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.3842963067498238, + "pred_variance_6d": 0.32691269137557016, + "pred_gt_ratio": 0.8506787227294114 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.15250539617004505, + "pred_variance_6d": 0.10611578727774894, + "pred_gt_ratio": 0.6958166067738926 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.16994163048790034, + "pred_variance_6d": 0.17338513370954384, + "pred_gt_ratio": 1.0202628585577131 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2784070818638871, + "pred_variance_6d": 0.2401754488189908, + "pred_gt_ratio": 0.8626772250585649 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.21526081221477664, + "pred_variance_6d": 0.1288834742932494, + "pred_gt_ratio": 0.5987317104641221 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.165995085812219, + "pred_variance_6d": 0.1639623226011634, + "pred_gt_ratio": 0.9877540759649044 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12790844637157237, + "pred_variance_6d": 0.10489850275179574, + "pred_gt_ratio": 0.8201061441014377 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.02238697863982246, + "pred_variance_6d": 0.010206809174196998, + "pred_gt_ratio": 0.45592615861261854 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.04676594210336735, + "pred_variance_6d": 0.023787106373146474, + "pred_gt_ratio": 0.5086416589356745 + } + ] + } + }, + "N0_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 21.09131852723658, + "count": 1536 + }, + "root_relative_mpjpe_mm": { + "mean": 13.298584976854423, + "count": 1536 + }, + "mpvpe_mm": { + "mean": 20.914216328722734, + "count": 1536 + }, + "projected_mano_2d_error_px": { + "mean": 10.90519869963949, + "count": 1536 + }, + "local_pose_angle_deg": { + "mean": 10.146150570362806, + "count": 1536 + }, + "root_relative_fingertip_mm": { + "mean": 19.213912716135383, + "count": 1536 + }, + "distal_angle_bias_deg": { + "mean": -0.9560096606534595, + "count": 1536 + }, + "distal_angle_mae_deg": { + "mean": 6.434853078409408, + "count": 1536 + }, + "gt60_angle_bias_deg": { + "mean": -14.681723083818344, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 8.49614477949217, + 8.304315593268257, + 6.725900184498944, + 9.344020287118232, + 9.868989870951433, + 7.996514050581027, + 16.897467837436125, + 10.179407045827247, + 7.156973746061946, + 11.510036989270398, + 12.329220780035635, + 7.837781641166657, + 11.432884504785761, + 10.934806613309775, + 13.177786646372018 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.4605645301441352, + "recording_bootstrap_95ci": [ + 0.22984763350492962, + 0.7203591153801728 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.0155445602722466, + "recording_bootstrap_95ci": [ + -0.11614473769829298, + 0.15050273744078974 + ], + "count": 1536, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.45036692389597494, + "recording_bootstrap_95ci": [ + 0.22206884947760652, + 0.7089618874713776 + ], + "count": 1536, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.1115846064252158, + "recording_bootstrap_95ci": [ + -0.04231962136303385, + 0.2694252824022745 + ], + "count": 1536, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.12231652392074466, + "recording_bootstrap_95ci": [ + 0.05687903657866021, + 0.19249724921925612 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.03777092415839434, + "recording_bootstrap_95ci": [ + -0.17786108308937398, + 0.2605299712003519 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.0004137925570830703, + "recording_bootstrap_95ci": [ + -0.1591851180176794, + 0.1463866899682519 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.08264950950009127, + "recording_bootstrap_95ci": [ + 0.024990508652990684, + 0.14061656744646214 + ], + "count": 1536, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.132009579042951, + "recording_bootstrap_95ci": [ + -0.451257445329207, + 0.5596174129671856 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8254449488814183, + "mean_abs_log_variance_ratio": 0.22978590835660248, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 768, + "gt_variance_6d": 0.6276556489562777, + "pred_variance_6d": 0.5920227026820643, + "pred_gt_ratio": 0.9432285101974831 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.09593922255610139, + "pred_variance_6d": 0.0799024181670387, + "pred_gt_ratio": 0.8328441281699462 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12244189528720367, + "pred_variance_6d": 0.12428323254841046, + "pred_gt_ratio": 1.0150384576854816 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.03214429306650994, + "pred_variance_6d": 0.025718451241279385, + "pred_gt_ratio": 0.8000938514362469 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.13904494533806688, + "pred_variance_6d": 0.12369058879678588, + "pred_gt_ratio": 0.8895727097166374 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.08829846748000257, + "pred_variance_6d": 0.07827170930052708, + "pred_gt_ratio": 0.8864447088875432 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.042789003839059675, + "pred_variance_6d": 0.031018910884624194, + "pred_gt_ratio": 0.7249271565492434 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.23990383480120056, + "pred_variance_6d": 0.22681628702126438, + "pred_gt_ratio": 0.9454466920431625 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.06611468194100378, + "pred_variance_6d": 0.04250146497027482, + "pred_gt_ratio": 0.6428445803944156 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.04967650231648196, + "pred_variance_6d": 0.04601837840955603, + "pred_gt_ratio": 0.9263610814702584 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.1615580244429538, + "pred_variance_6d": 0.15041884362143393, + "pred_gt_ratio": 0.9310515162590817 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12077039788861064, + "pred_variance_6d": 0.0905945605433513, + "pred_gt_ratio": 0.750138793339977 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.05196939792383421, + "pred_variance_6d": 0.03798717913456093, + "pred_gt_ratio": 0.7309528424830807 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.10800775482101788, + "pred_variance_6d": 0.10419772796258077, + "pred_gt_ratio": 0.9647245064509415 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.02196545540494259, + "pred_variance_6d": 0.014420691494316415, + "pred_gt_ratio": 0.6565168455861616 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.048189028939135216, + "pred_variance_6d": 0.05354516749180579, + "pred_gt_ratio": 1.1111485055952384 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 768, + "gt_variance_6d": 0.6731547796707966, + "pred_variance_6d": 0.6417401991374945, + "pred_gt_ratio": 0.9533323070978337 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12440969118655591, + "pred_variance_6d": 0.1065520355107035, + "pred_gt_ratio": 0.8564608954050505 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.10154130448647992, + "pred_variance_6d": 0.11157827339421883, + "pred_gt_ratio": 1.0988461686453448 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.031123622695296803, + "pred_variance_6d": 0.014975493115684132, + "pred_gt_ratio": 0.4811616328309728 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2352408934541732, + "pred_variance_6d": 0.20150442095935492, + "pred_gt_ratio": 0.8565875515968042 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.1985170871883211, + "pred_variance_6d": 0.12560845598911535, + "pred_gt_ratio": 0.6327337246791167 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.14216654828818165, + "pred_variance_6d": 0.14175033773556187, + "pred_gt_ratio": 0.9970723735109888 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.3842963067498238, + "pred_variance_6d": 0.33106578308703005, + "pred_gt_ratio": 0.86148572669618 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.15250539617004505, + "pred_variance_6d": 0.10575585033876078, + "pred_gt_ratio": 0.6934564480645783 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.16994163048790034, + "pred_variance_6d": 0.1713928825566043, + "pred_gt_ratio": 1.0085397089844168 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2784070818638871, + "pred_variance_6d": 0.24159030686966523, + "pred_gt_ratio": 0.8677592008517171 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.21526081221477664, + "pred_variance_6d": 0.12565935613300447, + "pred_gt_ratio": 0.583753981229188 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.165995085812219, + "pred_variance_6d": 0.16217025567415222, + "pred_gt_ratio": 0.9769581724702766 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12790844637157237, + "pred_variance_6d": 0.10443887690776803, + "pred_gt_ratio": 0.8165127469719587 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.02238697863982246, + "pred_variance_6d": 0.010509027145734746, + "pred_gt_ratio": 0.4694258798746988 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.04676594210336735, + "pred_variance_6d": 0.023795304447272098, + "pred_gt_ratio": 0.5088169590313617 + } + ] + } + }, + "N1_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 20.793559247627854, + "count": 1536 + }, + "root_relative_mpjpe_mm": { + "mean": 13.280635638783375, + "count": 1536 + }, + "mpvpe_mm": { + "mean": 20.613062475807965, + "count": 1536 + }, + "projected_mano_2d_error_px": { + "mean": 10.687942453660071, + "count": 1536 + }, + "local_pose_angle_deg": { + "mean": 10.12304068201532, + "count": 1536 + }, + "root_relative_fingertip_mm": { + "mean": 19.17021036303292, + "count": 1536 + }, + "distal_angle_bias_deg": { + "mean": -0.7688221939218541, + "count": 1536 + }, + "distal_angle_mae_deg": { + "mean": 6.404557778655241, + "count": 1536 + }, + "gt60_angle_bias_deg": { + "mean": -14.18970313003595, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 8.370060952128066, + 8.388919485422472, + 6.740491958579999, + 9.37599726075617, + 9.789092894721156, + 8.088168648770079, + 16.732169903931208, + 10.232054581050761, + 7.141020768380258, + 11.454227736840645, + 12.141561981212968, + 7.915622802179617, + 11.488355900587825, + 10.884741875110194, + 13.103115976788104 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.16280525053540865, + "recording_bootstrap_95ci": [ + -0.19261527037403237, + 0.5775918047021448 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": -0.0024047777988016605, + "recording_bootstrap_95ci": [ + -0.11731633907572056, + 0.11398960954975326 + ], + "count": 1536, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.1492130709812045, + "recording_bootstrap_95ci": [ + -0.202556067549934, + 0.5649333548809709 + ], + "count": 1536, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": -0.10567163955420256, + "recording_bootstrap_95ci": [ + -0.31528669300023465, + 0.08865066893631571 + ], + "count": 1536, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.099206635573258, + "recording_bootstrap_95ci": [ + 0.050971878319978715, + 0.14381916443041215 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": -0.005931428944071134, + "recording_bootstrap_95ci": [ + -0.21270393248026567, + 0.19923331538060046 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.1876012592886885, + "recording_bootstrap_95ci": [ + 0.05225265784441339, + 0.30185194152339434 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.052354209745923676, + "recording_bootstrap_95ci": [ + -0.011264143106139575, + 0.11828744298933691 + ], + "count": 1536, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.6240295328253465, + "recording_bootstrap_95ci": [ + 0.05059309374779256, + 0.9955809614368558 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8278497452584564, + "mean_abs_log_variance_ratio": 0.22643690200443367, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 768, + "gt_variance_6d": 0.6276556489562777, + "pred_variance_6d": 0.590987293145377, + "pred_gt_ratio": 0.9415788643472323 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.09593922255610139, + "pred_variance_6d": 0.07826236861610292, + "pred_gt_ratio": 0.8157494560719234 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12244189528720367, + "pred_variance_6d": 0.12072987153919593, + "pred_gt_ratio": 0.9860176637743807 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.03214429306650994, + "pred_variance_6d": 0.026433077504199418, + "pred_gt_ratio": 0.8223256753385924 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.13904494533806688, + "pred_variance_6d": 0.12473552592096056, + "pred_gt_ratio": 0.8970878129923017 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.08829846748000257, + "pred_variance_6d": 0.0799811228820483, + "pred_gt_ratio": 0.9058042020962828 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.042789003839059675, + "pred_variance_6d": 0.032132832336920464, + "pred_gt_ratio": 0.7509600470667702 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.23990383480120056, + "pred_variance_6d": 0.22213368309138276, + "pred_gt_ratio": 0.9259280214318238 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.06611468194100378, + "pred_variance_6d": 0.04352649670546659, + "pred_gt_ratio": 0.6583484247009864 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.04967650231648196, + "pred_variance_6d": 0.046366121040073066, + "pred_gt_ratio": 0.9333612246828706 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.1615580244429538, + "pred_variance_6d": 0.15041412398794402, + "pred_gt_ratio": 0.931022303018166 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12077039788861064, + "pred_variance_6d": 0.0928299526832796, + "pred_gt_ratio": 0.7686482309091905 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.05196939792383421, + "pred_variance_6d": 0.03908190946667061, + "pred_gt_ratio": 0.7520177455961417 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.10800775482101788, + "pred_variance_6d": 0.1043994168807065, + "pred_gt_ratio": 0.966591862350154 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.02196545540494259, + "pred_variance_6d": 0.013720770553677639, + "pred_gt_ratio": 0.6246522232628164 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.048189028939135216, + "pred_variance_6d": 0.05175334846404507, + "pred_gt_ratio": 1.0739653735171077 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 768, + "gt_variance_6d": 0.6731547796707966, + "pred_variance_6d": 0.6408304092314436, + "pred_gt_ratio": 0.9519807755726535 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12440969118655591, + "pred_variance_6d": 0.104989377239006, + "pred_gt_ratio": 0.8439003122479535 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.10154130448647992, + "pred_variance_6d": 0.1134793776538493, + "pred_gt_ratio": 1.11756864093625 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.031123622695296803, + "pred_variance_6d": 0.015599306503036809, + "pred_gt_ratio": 0.501204716936569 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2352408934541732, + "pred_variance_6d": 0.20040017011471314, + "pred_gt_ratio": 0.8518934236821061 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.1985170871883211, + "pred_variance_6d": 0.12804529963083305, + "pred_gt_ratio": 0.6450089583944191 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.14216654828818165, + "pred_variance_6d": 0.14502252184096287, + "pred_gt_ratio": 1.020088928001487 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.3842963067498238, + "pred_variance_6d": 0.32534008184565516, + "pred_gt_ratio": 0.8465865430693587 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.15250539617004505, + "pred_variance_6d": 0.10644080407490936, + "pred_gt_ratio": 0.6979477890488989 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.16994163048790034, + "pred_variance_6d": 0.17385236368167822, + "pred_gt_ratio": 1.023012214149942 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2784070818638871, + "pred_variance_6d": 0.2390665870037863, + "pred_gt_ratio": 0.85869434571591 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.21526081221477664, + "pred_variance_6d": 0.13105930377414401, + "pred_gt_ratio": 0.6088395859223067 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.165995085812219, + "pred_variance_6d": 0.16481696528149847, + "pred_gt_ratio": 0.9929026782632995 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12790844637157237, + "pred_variance_6d": 0.10481481646193395, + "pred_gt_ratio": 0.8194518769890167 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.02238697863982246, + "pred_variance_6d": 0.010056840035624983, + "pred_gt_ratio": 0.44922721361495604 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.04676594210336735, + "pred_variance_6d": 0.02379566714228422, + "pred_gt_ratio": 0.5088247145687423 + } + ] + } + }, + "N1_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 21.096255202777684, + "count": 1536 + }, + "root_relative_mpjpe_mm": { + "mean": 13.293838635863116, + "count": 1536 + }, + "mpvpe_mm": { + "mean": 20.92094779495771, + "count": 1536 + }, + "projected_mano_2d_error_px": { + "mean": 10.877951713589331, + "count": 1536 + }, + "local_pose_angle_deg": { + "mean": 10.168563484524688, + "count": 1536 + }, + "root_relative_fingertip_mm": { + "mean": 19.204914193600416, + "count": 1536 + }, + "distal_angle_bias_deg": { + "mean": -0.7955980258993804, + "count": 1536 + }, + "distal_angle_mae_deg": { + "mean": 6.450680043548346, + "count": 1536 + }, + "gt60_angle_bias_deg": { + "mean": -14.38297939129013, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 8.479326773745319, + 8.339201303586984, + 6.779762525538293, + 9.350932422443293, + 9.843643373247081, + 8.053278959045807, + 16.951759615020517, + 10.232074768321278, + 7.187270575513442, + 11.53910605807323, + 12.301955323443204, + 7.877058511832729, + 11.476496114744805, + 10.934340293810237, + 13.182237721630372 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.46550120568523806, + "recording_bootstrap_95ci": [ + 0.24323621077928692, + 0.7144749702885745 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.010798219280938307, + "recording_bootstrap_95ci": [ + -0.12832604486029595, + 0.155206743600623 + ], + "count": 1536, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.45709839013094705, + "recording_bootstrap_95ci": [ + 0.23296750539448113, + 0.7088126017750861 + ], + "count": 1536, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.08433762037505706, + "recording_bootstrap_95ci": [ + -0.06585622510174288, + 0.23443423865052504 + ], + "count": 1536, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.14472943808262548, + "recording_bootstrap_95ci": [ + 0.07305682939477265, + 0.22292843082686883 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.028772401623427868, + "recording_bootstrap_95ci": [ + -0.1946720387553796, + 0.25794913212303067 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.16082542731116214, + "recording_bootstrap_95ci": [ + -0.007665497894534686, + 0.3018881986417303 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.09847647463902831, + "recording_bootstrap_95ci": [ + 0.019680454523768275, + 0.1754308967249623 + ], + "count": 1536, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.4307532715711662, + "recording_bootstrap_95ci": [ + -0.1818091494782167, + 0.8761923271176186 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8334198057109194, + "mean_abs_log_variance_ratio": 0.22283628962918933, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 768, + "gt_variance_6d": 0.6276556489562777, + "pred_variance_6d": 0.5921498031082362, + "pred_gt_ratio": 0.9434310104480318 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.09593922255610139, + "pred_variance_6d": 0.08004810705676636, + "pred_gt_ratio": 0.8343626821653413 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12244189528720367, + "pred_variance_6d": 0.12782436882258136, + "pred_gt_ratio": 1.04395941048407 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.03214429306650994, + "pred_variance_6d": 0.026914335712514167, + "pred_gt_ratio": 0.8372974840922948 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.13904494533806688, + "pred_variance_6d": 0.12335106495906147, + "pred_gt_ratio": 0.8871308817386485 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.08829846748000257, + "pred_variance_6d": 0.08138648330757915, + "pred_gt_ratio": 0.9217202249406106 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.042789003839059675, + "pred_variance_6d": 0.03188933426787933, + "pred_gt_ratio": 0.7452693778014375 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.23990383480120056, + "pred_variance_6d": 0.22817425143952008, + "pred_gt_ratio": 0.9511071451967396 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.06611468194100378, + "pred_variance_6d": 0.04313486138050196, + "pred_gt_ratio": 0.6524248489767002 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.04967650231648196, + "pred_variance_6d": 0.04683075788138477, + "pred_gt_ratio": 0.9427144766157779 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.1615580244429538, + "pred_variance_6d": 0.15116901076176412, + "pred_gt_ratio": 0.9356948457558166 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12077039788861064, + "pred_variance_6d": 0.09353392157096782, + "pred_gt_ratio": 0.7744772163227974 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.05196939792383421, + "pred_variance_6d": 0.03862839626438602, + "pred_gt_ratio": 0.7432912022763739 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.10800775482101788, + "pred_variance_6d": 0.10480209409088133, + "pred_gt_ratio": 0.9703200873358703 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.02196545540494259, + "pred_variance_6d": 0.014307585541761897, + "pred_gt_ratio": 0.6513675805029042 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.048189028939135216, + "pred_variance_6d": 0.05316499503872167, + "pred_gt_ratio": 1.1032593146019047 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 768, + "gt_variance_6d": 0.6731547796707966, + "pred_variance_6d": 0.641761104194963, + "pred_gt_ratio": 0.9533633624481036 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12440969118655591, + "pred_variance_6d": 0.10631795407034869, + "pred_gt_ratio": 0.8545793583790982 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.10154130448647992, + "pred_variance_6d": 0.11375828300740867, + "pred_gt_ratio": 1.1203153591803168 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.031123622695296803, + "pred_variance_6d": 0.01576445979494548, + "pred_gt_ratio": 0.5065110816077236 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2352408934541732, + "pred_variance_6d": 0.2011732131160904, + "pred_gt_ratio": 0.855179599780259 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.1985170871883211, + "pred_variance_6d": 0.1276830662984274, + "pred_gt_ratio": 0.6431842624071058 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.14216654828818165, + "pred_variance_6d": 0.14299432154312058, + "pred_gt_ratio": 1.0058225599826829 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.3842963067498238, + "pred_variance_6d": 0.33009647940132525, + "pred_gt_ratio": 0.858963444621958 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.15250539617004505, + "pred_variance_6d": 0.10589045808137133, + "pred_gt_ratio": 0.6943390905545559 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.16994163048790034, + "pred_variance_6d": 0.17182329043465816, + "pred_gt_ratio": 1.0110723896278717 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2784070818638871, + "pred_variance_6d": 0.24111107827258585, + "pred_gt_ratio": 0.8660378775510632 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.21526081221477664, + "pred_variance_6d": 0.12796867745087573, + "pred_gt_ratio": 0.5944819966729239 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.165995085812219, + "pred_variance_6d": 0.16297815442961056, + "pred_gt_ratio": 0.9818251765234705 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12790844637157237, + "pred_variance_6d": 0.10408798916410003, + "pred_gt_ratio": 0.8137694743138837 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.02238697863982246, + "pred_variance_6d": 0.010349795885628019, + "pred_gt_ratio": 0.46231320680395743 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.04676594210336735, + "pred_variance_6d": 0.023843510500159884, + "pred_gt_ratio": 0.5098477530391299 + } + ] + } + } + } + }, + "normal": { + "hands": 1048, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 588, + "variance": 0.5805831955619537 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 588, + "variance": 0.09545684434321916 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 588, + "variance": 0.10342149802794981 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 588, + "variance": 0.016837883903797677 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 588, + "variance": 0.1476797655526118 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 588, + "variance": 0.04955620383213525 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 588, + "variance": 0.025912651779223927 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 588, + "variance": 0.24556055089965978 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 588, + "variance": 0.04119891892668358 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 588, + "variance": 0.0164697432807629 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 588, + "variance": 0.1619348379212032 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 588, + "variance": 0.0674997817846674 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 588, + "variance": 0.026999770899868276 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 588, + "variance": 0.12062940680660475 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 588, + "variance": 0.017583452877790336 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 588, + "variance": 0.048288454118829933 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 460, + "variance": 0.461866976947212 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 460, + "variance": 0.10221362099003453 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 460, + "variance": 0.06938982404971092 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 460, + "variance": 0.02030802956821813 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 460, + "variance": 0.14881038235534289 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 460, + "variance": 0.07199332698568023 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 460, + "variance": 0.031119814694062903 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 460, + "variance": 0.2741106435761934 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 460, + "variance": 0.048844176402784004 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 460, + "variance": 0.013294943050347847 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 460, + "variance": 0.17726570739539127 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 460, + "variance": 0.06215319041469471 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 460, + "variance": 0.03698108778165434 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 460, + "variance": 0.15541348357880702 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 460, + "variance": 0.024819460131972153 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 460, + "variance": 0.052086190760765684 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 18.31905404438499, + "count": 1048 + }, + "root_relative_mpjpe_mm": { + "mean": 12.423988155053772, + "count": 1048 + }, + "mpvpe_mm": { + "mean": 18.222329692986175, + "count": 1048 + }, + "projected_mano_2d_error_px": { + "mean": 10.15403231887417, + "count": 1048 + }, + "local_pose_angle_deg": { + "mean": 9.367586661158628, + "count": 1048 + }, + "root_relative_fingertip_mm": { + "mean": 18.226285755634308, + "count": 1048 + }, + "distal_angle_bias_deg": { + "mean": 0.4399894580586266, + "count": 1048 + }, + "distal_angle_mae_deg": { + "mean": 5.175950221887982, + "count": 1048 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 7.56776231618328, + 7.1911698061660045, + 6.342933174450207, + 8.56229066655381, + 8.66854335683334, + 7.35023009543883, + 15.501919383538588, + 9.059413234753007, + 5.579491989018808, + 10.339334917887477, + 11.20080159428238, + 7.357912133668215, + 11.370845570989692, + 10.862484712011486, + 13.55865977235309 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.9243729906564595, + "mean_abs_log_variance_ratio": 0.21893051705202235, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 588, + "gt_variance_6d": 0.5805831955619537, + "pred_variance_6d": 0.5512699423350982, + "pred_gt_ratio": 0.9495106757292848 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.09545684434321916, + "pred_variance_6d": 0.07731304079166063, + "pred_gt_ratio": 0.8099266356813377 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.10342149802794981, + "pred_variance_6d": 0.10784832780134071, + "pred_gt_ratio": 1.0428037676672846 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.016837883903797677, + "pred_variance_6d": 0.018916979494777605, + "pred_gt_ratio": 1.1234772494488456 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1476797655526118, + "pred_variance_6d": 0.12707074757425568, + "pred_gt_ratio": 0.8604479232395988 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04955620383213525, + "pred_variance_6d": 0.05839068535484023, + "pred_gt_ratio": 1.1782719586962422 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.025912651779223927, + "pred_variance_6d": 0.023320244599641993, + "pred_gt_ratio": 0.8999559287999827 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.24556055089965978, + "pred_variance_6d": 0.24468979104091515, + "pred_gt_ratio": 0.9964539912638475 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04119891892668358, + "pred_variance_6d": 0.03394700889245278, + "pred_gt_ratio": 0.8239781474087684 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0164697432807629, + "pred_variance_6d": 0.03021817161655333, + "pred_gt_ratio": 1.8347688304194127 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1619348379212032, + "pred_variance_6d": 0.15939605305063304, + "pred_gt_ratio": 0.9843221822854109 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0674997817846674, + "pred_variance_6d": 0.06011637987630464, + "pred_gt_ratio": 0.890615914405224 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.026999770899868276, + "pred_variance_6d": 0.025365962643946936, + "pred_gt_ratio": 0.9394880696587944 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.12062940680660475, + "pred_variance_6d": 0.11230359076467221, + "pred_gt_ratio": 0.9309802123516976 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.017583452877790336, + "pred_variance_6d": 0.01182088538010076, + "pred_gt_ratio": 0.6722732709132302 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.048288454118829933, + "pred_variance_6d": 0.05709530414915664, + "pred_gt_ratio": 1.1823800366160924 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 460, + "gt_variance_6d": 0.461866976947212, + "pred_variance_6d": 0.42406681111879563, + "pred_gt_ratio": 0.9181578945559975 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.10221362099003453, + "pred_variance_6d": 0.08568730666209706, + "pred_gt_ratio": 0.8383159292483267 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06938982404971092, + "pred_variance_6d": 0.06459628924652744, + "pred_gt_ratio": 0.9309187641151909 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.02030802956821813, + "pred_variance_6d": 0.013560268849986575, + "pred_gt_ratio": 0.6677294222187004 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.14881038235534289, + "pred_variance_6d": 0.09701788700621647, + "pred_gt_ratio": 0.6519564392661017 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.07199332698568023, + "pred_variance_6d": 0.06947639363724212, + "pred_gt_ratio": 0.9650393522035905 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.031119814694062903, + "pred_variance_6d": 0.028565300135474612, + "pred_gt_ratio": 0.9179135678119689 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.2741106435761934, + "pred_variance_6d": 0.23287934463717705, + "pred_gt_ratio": 0.8495815470676699 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.048844176402784004, + "pred_variance_6d": 0.030022773061009957, + "pred_gt_ratio": 0.6146643320061945 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.013294943050347847, + "pred_variance_6d": 0.022370049253342253, + "pred_gt_ratio": 1.682598351014145 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.17726570739539127, + "pred_variance_6d": 0.1265019836794805, + "pred_gt_ratio": 0.7136291927987953 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06215319041469471, + "pred_variance_6d": 0.06150551874372194, + "pred_gt_ratio": 0.9895794300075118 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.03698108778165434, + "pred_variance_6d": 0.03378640057561916, + "pred_gt_ratio": 0.9136129465715713 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.15541348357880702, + "pred_variance_6d": 0.12308610361130874, + "pred_gt_ratio": 0.7919911501687321 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.024819460131972153, + "pred_variance_6d": 0.009927300194986359, + "pred_gt_ratio": 0.39998050490220455 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.052086190760765684, + "pred_variance_6d": 0.03201280217114081, + "pred_gt_ratio": 0.6146120824649495 + } + ] + } + }, + "N0_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 18.561865114301217, + "count": 1048 + }, + "root_relative_mpjpe_mm": { + "mean": 12.428600224147317, + "count": 1048 + }, + "mpvpe_mm": { + "mean": 18.443820830519872, + "count": 1048 + }, + "projected_mano_2d_error_px": { + "mean": 10.105309579208607, + "count": 1048 + }, + "local_pose_angle_deg": { + "mean": 9.445362988091608, + "count": 1048 + }, + "root_relative_fingertip_mm": { + "mean": 18.232099096738654, + "count": 1048 + }, + "distal_angle_bias_deg": { + "mean": 0.402609889118271, + "count": 1048 + }, + "distal_angle_mae_deg": { + "mean": 5.266927382531967, + "count": 1048 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 7.84533919268892, + 7.275032610895525, + 6.4400148195790425, + 8.500055098863504, + 8.857543766299504, + 7.479436164992001, + 15.506642906265405, + 8.976163359998747, + 5.52411241310414, + 10.377549879082286, + 11.553847672375104, + 7.521396711269635, + 11.463523755944868, + 11.02621712404808, + 13.333561446631455 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.24281106991622284, + "recording_bootstrap_95ci": [ + -0.19083690896454766, + 0.6907840396622589 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.004612069093544065, + "recording_bootstrap_95ci": [ + -0.1396353715898588, + 0.14597364683018615 + ], + "count": 1048, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.22149113753369745, + "recording_bootstrap_95ci": [ + -0.20589602726776918, + 0.6674092985804582 + ], + "count": 1048, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": -0.04872273966556287, + "recording_bootstrap_95ci": [ + -0.26098604536310366, + 0.1299873443592842 + ], + "count": 1048, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.07777632693297991, + "recording_bootstrap_95ci": [ + 0.027444300973563734, + 0.13025109388408823 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.005813341104347287, + "recording_bootstrap_95ci": [ + -0.19481583178045608, + 0.18775038066083619 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": -0.03737956894035558, + "recording_bootstrap_95ci": [ + -0.16091340283097583, + 0.08995231055421286 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.09097716064398526, + "recording_bootstrap_95ci": [ + 0.0276604359789202, + 0.15205041715823311 + ], + "count": 1048, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.9466869391333657, + "mean_abs_log_variance_ratio": 0.21711092671055526, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 588, + "gt_variance_6d": 0.5805831955619537, + "pred_variance_6d": 0.5537787649916301, + "pred_gt_ratio": 0.9538318870142647 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.09545684434321916, + "pred_variance_6d": 0.07781414349274406, + "pred_gt_ratio": 0.8151761565986823 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.10342149802794981, + "pred_variance_6d": 0.11126836542569069, + "pred_gt_ratio": 1.075872691339476 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.016837883903797677, + "pred_variance_6d": 0.01963374781439095, + "pred_gt_ratio": 1.166046038003783 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1476797655526118, + "pred_variance_6d": 0.1325167090223005, + "pred_gt_ratio": 0.8973247521515778 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04955620383213525, + "pred_variance_6d": 0.06248289980911204, + "pred_gt_ratio": 1.2608491970200981 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.025912651779223927, + "pred_variance_6d": 0.02322034452231498, + "pred_gt_ratio": 0.8961006661978314 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.24556055089965978, + "pred_variance_6d": 0.24682007795051913, + "pred_gt_ratio": 1.005129191338938 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04119891892668358, + "pred_variance_6d": 0.03399858939689593, + "pred_gt_ratio": 0.8252301342517955 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0164697432807629, + "pred_variance_6d": 0.031177732637416966, + "pred_gt_ratio": 1.8930308812908692 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1619348379212032, + "pred_variance_6d": 0.16251301542277546, + "pred_gt_ratio": 1.003570433076628 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0674997817846674, + "pred_variance_6d": 0.06451261869819569, + "pred_gt_ratio": 0.9557455889857374 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.026999770899868276, + "pred_variance_6d": 0.025907193197179955, + "pred_gt_ratio": 0.9595338157964277 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.12062940680660475, + "pred_variance_6d": 0.11476054831560321, + "pred_gt_ratio": 0.9513480282597212 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.017583452877790336, + "pred_variance_6d": 0.011079270654467666, + "pred_gt_ratio": 0.6300964168682646 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.048288454118829933, + "pred_variance_6d": 0.05473690806207396, + "pred_gt_ratio": 1.1335402853728853 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 460, + "gt_variance_6d": 0.461866976947212, + "pred_variance_6d": 0.4254173773058182, + "pred_gt_ratio": 0.9210820399364474 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.10221362099003453, + "pred_variance_6d": 0.08436214193351135, + "pred_gt_ratio": 0.8253512703726283 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06938982404971092, + "pred_variance_6d": 0.06320602225370497, + "pred_gt_ratio": 0.9108831607416116 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.02030802956821813, + "pred_variance_6d": 0.013623561705585745, + "pred_gt_ratio": 0.6708460641059184 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.14881038235534289, + "pred_variance_6d": 0.09876119740574363, + "pred_gt_ratio": 0.6636714175622015 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.07199332698568023, + "pred_variance_6d": 0.07074416968713937, + "pred_gt_ratio": 0.9826489849706581 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.031119814694062903, + "pred_variance_6d": 0.029307699065039737, + "pred_gt_ratio": 0.9417697165989589 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.2741106435761934, + "pred_variance_6d": 0.23639141790221374, + "pred_gt_ratio": 0.8623941588627331 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.048844176402784004, + "pred_variance_6d": 0.03025231762637999, + "pred_gt_ratio": 0.6193638598163707 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.013294943050347847, + "pred_variance_6d": 0.025342307197846026, + "pred_gt_ratio": 1.9061613954926246 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.17726570739539127, + "pred_variance_6d": 0.12962879098470717, + "pred_gt_ratio": 0.7312682914782275 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06215319041469471, + "pred_variance_6d": 0.06319584242838389, + "pred_gt_ratio": 1.0167755187904668 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.03698108778165434, + "pred_variance_6d": 0.03670198353048427, + "pred_gt_ratio": 0.9924527841685465 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.15541348357880702, + "pred_variance_6d": 0.12419769457597313, + "pred_gt_ratio": 0.7991436245812932 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.024819460131972153, + "pred_variance_6d": 0.010310656327147366, + "pred_gt_ratio": 0.4154262934134209 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.052086190760765684, + "pred_variance_6d": 0.03189327610063791, + "pred_gt_ratio": 0.6123173078086134 + } + ] + } + }, + "N0_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 18.772209272584842, + "count": 1048 + }, + "root_relative_mpjpe_mm": { + "mean": 12.43875197167615, + "count": 1048 + }, + "mpvpe_mm": { + "mean": 18.662926863168032, + "count": 1048 + }, + "projected_mano_2d_error_px": { + "mean": 10.19462269112354, + "count": 1048 + }, + "local_pose_angle_deg": { + "mean": 9.465848801245215, + "count": 1048 + }, + "root_relative_fingertip_mm": { + "mean": 18.258661533130034, + "count": 1048 + }, + "distal_angle_bias_deg": { + "mean": 0.4251490276847177, + "count": 1048 + }, + "distal_angle_mae_deg": { + "mean": 5.286631110060306, + "count": 1048 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 7.909111008958052, + 7.3061859216114495, + 6.453554850981663, + 8.43262817966574, + 8.853620043621605, + 7.419055401653279, + 15.604617629911154, + 8.946512746048793, + 5.584768363025807, + 10.412443856644721, + 11.678555410042518, + 7.456790282014217, + 11.481952646533951, + 11.034976400918405, + 13.412951800033792 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.4531552281998496, + "recording_bootstrap_95ci": [ + 0.22142408195219, + 0.6995769641360775 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.014763816622377352, + "recording_bootstrap_95ci": [ + -0.14852358750473454, + 0.17387770010354134 + ], + "count": 1048, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.4405971701818568, + "recording_bootstrap_95ci": [ + 0.2085634165138251, + 0.687904588407714 + ], + "count": 1048, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.040590372249370316, + "recording_bootstrap_95ci": [ + -0.1299085620950288, + 0.20331185551594605 + ], + "count": 1048, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.09826214008658897, + "recording_bootstrap_95ci": [ + 0.03494709090910096, + 0.17080547902857626 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.03237577749572637, + "recording_bootstrap_95ci": [ + -0.20986752015623017, + 0.2673467385275161 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": -0.014840430373908909, + "recording_bootstrap_95ci": [ + -0.1623624761691972, + 0.13012363296378968 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.11068088817232438, + "recording_bootstrap_95ci": [ + 0.02701700275213235, + 0.18876734384448005 + ], + "count": 1048, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.9549643180273817, + "mean_abs_log_variance_ratio": 0.21973600780410013, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 588, + "gt_variance_6d": 0.5805831955619537, + "pred_variance_6d": 0.5546368116684078, + "pred_gt_ratio": 0.9553097917888718 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.09545684434321916, + "pred_variance_6d": 0.07875318868715232, + "pred_gt_ratio": 0.825013536001587 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.10342149802794981, + "pred_variance_6d": 0.11799486419029631, + "pred_gt_ratio": 1.140912348401761 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.016837883903797677, + "pred_variance_6d": 0.02015326967596142, + "pred_gt_ratio": 1.1969003819664048 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1476797655526118, + "pred_variance_6d": 0.1310142211843931, + "pred_gt_ratio": 0.8871507934356687 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04955620383213525, + "pred_variance_6d": 0.06399171174312546, + "pred_gt_ratio": 1.2912956763171062 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.025912651779223927, + "pred_variance_6d": 0.02327465236483945, + "pred_gt_ratio": 0.8981964703242161 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.24556055089965978, + "pred_variance_6d": 0.2526151521928963, + "pred_gt_ratio": 1.0287285611120784 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04119891892668358, + "pred_variance_6d": 0.03375011422098455, + "pred_gt_ratio": 0.8191990251260061 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0164697432807629, + "pred_variance_6d": 0.03167446160915839, + "pred_gt_ratio": 1.923190973240913 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1619348379212032, + "pred_variance_6d": 0.16299586744712063, + "pred_gt_ratio": 1.0065522004995227 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0674997817846674, + "pred_variance_6d": 0.06505142683152135, + "pred_gt_ratio": 0.9637279575072316 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.026999770899868276, + "pred_variance_6d": 0.025733245587052346, + "pred_gt_ratio": 0.9530912570512919 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.12062940680660475, + "pred_variance_6d": 0.11513307430029474, + "pred_gt_ratio": 0.9544362137573814 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.017583452877790336, + "pred_variance_6d": 0.011451811565717042, + "pred_gt_ratio": 0.6512834336526603 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.048288454118829933, + "pred_variance_6d": 0.05593939421561887, + "pred_gt_ratio": 1.1584424317655984 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 460, + "gt_variance_6d": 0.461866976947212, + "pred_variance_6d": 0.42834104418831875, + "pred_gt_ratio": 0.9274121458509794 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.10221362099003453, + "pred_variance_6d": 0.08597746634677161, + "pred_gt_ratio": 0.841154686762874 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06938982404971092, + "pred_variance_6d": 0.06418207079977939, + "pred_gt_ratio": 0.9249493233157546 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.02030802956821813, + "pred_variance_6d": 0.013593555703649632, + "pred_gt_ratio": 0.6693685203671071 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.14881038235534289, + "pred_variance_6d": 0.09973257350722191, + "pred_gt_ratio": 0.6701990273035617 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.07199332698568023, + "pred_variance_6d": 0.0701818496033057, + "pred_gt_ratio": 0.9748382599024096 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.031119814694062903, + "pred_variance_6d": 0.029062436228783607, + "pred_gt_ratio": 0.9338884731318209 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.2741106435761934, + "pred_variance_6d": 0.23951738391875202, + "pred_gt_ratio": 0.8737981889133551 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.048844176402784004, + "pred_variance_6d": 0.029999386129908805, + "pred_gt_ratio": 0.614185525056758 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.013294943050347847, + "pred_variance_6d": 0.025464849634981933, + "pred_gt_ratio": 1.915378617158926 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.17726570739539127, + "pred_variance_6d": 0.13127108540101268, + "pred_gt_ratio": 0.7405328832621441 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06215319041469471, + "pred_variance_6d": 0.06288749325838063, + "pred_gt_ratio": 1.0118144030706475 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.03698108778165434, + "pred_variance_6d": 0.03598404457764228, + "pred_gt_ratio": 0.9730391055585261 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.15541348357880702, + "pred_variance_6d": 0.12355704006665763, + "pred_gt_ratio": 0.7950213663668658 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.024819460131972153, + "pred_variance_6d": 0.0106047310087364, + "pred_gt_ratio": 0.4272748461226803 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.052086190760765684, + "pred_variance_6d": 0.031906529170138156, + "pred_gt_ratio": 0.6125717527835034 + } + ] + } + }, + "N1_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 18.459575542966828, + "count": 1048 + }, + "root_relative_mpjpe_mm": { + "mean": 12.436863317289426, + "count": 1048 + }, + "mpvpe_mm": { + "mean": 18.340896850778858, + "count": 1048 + }, + "projected_mano_2d_error_px": { + "mean": 9.967475700469418, + "count": 1048 + }, + "local_pose_angle_deg": { + "mean": 9.48662389098233, + "count": 1048 + }, + "root_relative_fingertip_mm": { + "mean": 18.260975756263004, + "count": 1048 + }, + "distal_angle_bias_deg": { + "mean": 0.5386412544673636, + "count": 1048 + }, + "distal_angle_mae_deg": { + "mean": 5.305045134238615, + "count": 1048 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 7.823335457991325, + 7.35849564670379, + 6.511030093251322, + 8.529677663140625, + 8.877685828575196, + 7.568150079034212, + 15.526080973730743, + 9.061979074002677, + 5.596209876068675, + 10.41109709578161, + 11.5592480595899, + 7.597286329185235, + 11.526682991392285, + 10.988633918056962, + 13.363758252265344 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.14052149858183532, + "recording_bootstrap_95ci": [ + -0.2721688714722916, + 0.5672955957282408 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.012875162235653128, + "recording_bootstrap_95ci": [ + -0.12873684675735983, + 0.15409470186363383 + ], + "count": 1048, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.11856715779268105, + "recording_bootstrap_95ci": [ + -0.2931808157384196, + 0.5456308038364273 + ], + "count": 1048, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": -0.18655661840475243, + "recording_bootstrap_95ci": [ + -0.41904401029182214, + 0.012597683996830205 + ], + "count": 1048, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.11903722982370217, + "recording_bootstrap_95ci": [ + 0.07149926332236109, + 0.17253998057003736 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.03469000062869705, + "recording_bootstrap_95ci": [ + -0.16691762426889764, + 0.21736669270512884 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.09865179640873697, + "recording_bootstrap_95ci": [ + -0.01958245825055155, + 0.21302883405740383 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.12909491235063275, + "recording_bootstrap_95ci": [ + 0.05330055819181197, + 0.20712636088439726 + ], + "count": 1048, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.9649494285317919, + "mean_abs_log_variance_ratio": 0.219263106176789, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 588, + "gt_variance_6d": 0.5805831955619537, + "pred_variance_6d": 0.5536124709747826, + "pred_gt_ratio": 0.9535454611960207 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.09545684434321916, + "pred_variance_6d": 0.07761745720709196, + "pred_gt_ratio": 0.8131156832297438 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.10342149802794981, + "pred_variance_6d": 0.11470275918577288, + "pred_gt_ratio": 1.109080426922208 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.016837883903797677, + "pred_variance_6d": 0.020591571856474377, + "pred_gt_ratio": 1.2229310983567288 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1476797655526118, + "pred_variance_6d": 0.13229087948162638, + "pred_gt_ratio": 0.8957955681104934 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04955620383213525, + "pred_variance_6d": 0.06537649087242256, + "pred_gt_ratio": 1.3192392842251666 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.025912651779223927, + "pred_variance_6d": 0.024109360676874872, + "pred_gt_ratio": 0.9304088551911586 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.24556055089965978, + "pred_variance_6d": 0.24801998495774044, + "pred_gt_ratio": 1.010015591059191 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04119891892668358, + "pred_variance_6d": 0.03434016186568309, + "pred_gt_ratio": 0.8335209457023341 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0164697432807629, + "pred_variance_6d": 0.031626239195885114, + "pred_gt_ratio": 1.9202630336579323 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1619348379212032, + "pred_variance_6d": 0.16304398950734558, + "pred_gt_ratio": 1.0068493697859018 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0674997817846674, + "pred_variance_6d": 0.06689550394969365, + "pred_gt_ratio": 0.9910477068370167 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.026999770899868276, + "pred_variance_6d": 0.026566790736259435, + "pred_gt_ratio": 0.983963561571889 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.12062940680660475, + "pred_variance_6d": 0.11539878539360288, + "pred_gt_ratio": 0.9566389195514515 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.017583452877790336, + "pred_variance_6d": 0.011017073439427764, + "pred_gt_ratio": 0.6265591585452156 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.048288454118829933, + "pred_variance_6d": 0.05417231504160638, + "pred_gt_ratio": 1.121848193945021 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 460, + "gt_variance_6d": 0.461866976947212, + "pred_variance_6d": 0.4258152116503045, + "pred_gt_ratio": 0.9219434012468314 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.10221362099003453, + "pred_variance_6d": 0.08410266201612943, + "pred_gt_ratio": 0.8228126662720338 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06938982404971092, + "pred_variance_6d": 0.06456001511581619, + "pred_gt_ratio": 0.9303960054656624 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.02030802956821813, + "pred_variance_6d": 0.014098639787029542, + "pred_gt_ratio": 0.6942396720307015 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.14881038235534289, + "pred_variance_6d": 0.09816406698649395, + "pred_gt_ratio": 0.6596587242957882 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.07199332698568023, + "pred_variance_6d": 0.07300071360499397, + "pred_gt_ratio": 1.0139927776849944 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.031119814694062903, + "pred_variance_6d": 0.029979163377574558, + "pred_gt_ratio": 0.9633464618057009 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.2741106435761934, + "pred_variance_6d": 0.23415050725119352, + "pred_gt_ratio": 0.8542189540557102 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.048844176402784004, + "pred_variance_6d": 0.0316888615097161, + "pred_gt_ratio": 0.6487746102708348 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.013294943050347847, + "pred_variance_6d": 0.026859791046869044, + "pred_gt_ratio": 2.020301323980947 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.17726570739539127, + "pred_variance_6d": 0.12837954644755312, + "pred_gt_ratio": 0.7242209919440451 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06215319041469471, + "pred_variance_6d": 0.06682406780452191, + "pred_gt_ratio": 1.0751510478973396 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.03698108778165434, + "pred_variance_6d": 0.0380388638234313, + "pred_gt_ratio": 1.0286031619194744 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.15541348357880702, + "pred_variance_6d": 0.12401251626569339, + "pred_gt_ratio": 0.7979521043475559 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.024819460131972153, + "pred_variance_6d": 0.010221325949162197, + "pred_gt_ratio": 0.41182708627877035 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.052086190760765684, + "pred_variance_6d": 0.03209133685288271, + "pred_gt_ratio": 0.616119865633479 + } + ] + } + }, + "N1_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 18.790096188774545, + "count": 1048 + }, + "root_relative_mpjpe_mm": { + "mean": 12.44056996521149, + "count": 1048 + }, + "mpvpe_mm": { + "mean": 18.68236162485057, + "count": 1048 + }, + "projected_mano_2d_error_px": { + "mean": 10.182534328626312, + "count": 1048 + }, + "local_pose_angle_deg": { + "mean": 9.512364488976603, + "count": 1048 + }, + "root_relative_fingertip_mm": { + "mean": 18.275278665182245, + "count": 1048 + }, + "distal_angle_bias_deg": { + "mean": 0.5565491569519952, + "count": 1048 + }, + "distal_angle_mae_deg": { + "mean": 5.343796691252985, + "count": 1048 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 7.907704484940485, + 7.37495403520706, + 6.531978332643746, + 8.443384128558726, + 8.893560475321443, + 7.48882013212406, + 15.643880547799228, + 9.039837104957977, + 5.65850636644559, + 10.43556572411579, + 11.729987456925384, + 7.523240136565598, + 11.546102460445338, + 11.032895641216568, + 13.435042844815108 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.47104214438955294, + "recording_bootstrap_95ci": [ + 0.25526561059399294, + 0.6900522986721812 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.01658181015771764, + "recording_bootstrap_95ci": [ + -0.14704628891952043, + 0.176123783751796 + ], + "count": 1048, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.4600319318643963, + "recording_bootstrap_95ci": [ + 0.24609278444205784, + 0.6833033417920016 + ], + "count": 1048, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.02850200975214252, + "recording_bootstrap_95ci": [ + -0.13124376483606714, + 0.1806056220769093 + ], + "count": 1048, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.1447778278179751, + "recording_bootstrap_95ci": [ + 0.07301308450810355, + 0.22637349835684267 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.04899290954793682, + "recording_bootstrap_95ci": [ + -0.19024845635611012, + 0.28031527052077587 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.1165596988933687, + "recording_bootstrap_95ci": [ + -0.039536567928576224, + 0.2616306400910109 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.16784646936500344, + "recording_bootstrap_95ci": [ + 0.06404750643031668, + 0.2667443974576009 + ], + "count": 1048, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.9747625779332052, + "mean_abs_log_variance_ratio": 0.220374159778977, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 588, + "gt_variance_6d": 0.5805831955619537, + "pred_variance_6d": 0.554909413721547, + "pred_gt_ratio": 0.9557793232104199 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.09545684434321916, + "pred_variance_6d": 0.0787472398612987, + "pred_gt_ratio": 0.824951216469713 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.10342149802794981, + "pred_variance_6d": 0.1221029815666735, + "pred_gt_ratio": 1.1806344318632378 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.016837883903797677, + "pred_variance_6d": 0.02113822904436456, + "pred_gt_ratio": 1.255397006247143 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1476797655526118, + "pred_variance_6d": 0.13012920954231294, + "pred_gt_ratio": 0.8811580181981913 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04955620383213525, + "pred_variance_6d": 0.06691859751082035, + "pred_gt_ratio": 1.3503576209650319 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.025912651779223927, + "pred_variance_6d": 0.024036217442949204, + "pred_gt_ratio": 0.9275861709460705 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.24556055089965978, + "pred_variance_6d": 0.2540573365188723, + "pred_gt_ratio": 1.0346015904756805 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04119891892668358, + "pred_variance_6d": 0.034090867620322325, + "pred_gt_ratio": 0.827469955728437 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0164697432807629, + "pred_variance_6d": 0.03192784153194176, + "pred_gt_ratio": 1.938575543507975 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1619348379212032, + "pred_variance_6d": 0.16323733794836348, + "pred_gt_ratio": 1.0080433589453683 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0674997817846674, + "pred_variance_6d": 0.06747911267938857, + "pred_gt_ratio": 0.9996937900429846 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.026999770899868276, + "pred_variance_6d": 0.026266329137865047, + "pred_gt_ratio": 0.9728352597981931 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.12062940680660475, + "pred_variance_6d": 0.11595794800970469, + "pred_gt_ratio": 0.9612742952107074 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.017583452877790336, + "pred_variance_6d": 0.01138116861038467, + "pred_gt_ratio": 0.6472658521330715 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.048288454118829933, + "pred_variance_6d": 0.05528143377863178, + "pred_gt_ratio": 1.1448168053297643 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 460, + "gt_variance_6d": 0.461866976947212, + "pred_variance_6d": 0.4284956555447951, + "pred_gt_ratio": 0.9277468988517206 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.10221362099003453, + "pred_variance_6d": 0.08606349904870125, + "pred_gt_ratio": 0.8419963818432001 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06938982404971092, + "pred_variance_6d": 0.06597967215136466, + "pred_gt_ratio": 0.9508551585906426 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.02030802956821813, + "pred_variance_6d": 0.014206799974788409, + "pred_gt_ratio": 0.6995656534310898 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.14881038235534289, + "pred_variance_6d": 0.09957884501719708, + "pred_gt_ratio": 0.6691659778106994 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.07199332698568023, + "pred_variance_6d": 0.07290663767398152, + "pred_gt_ratio": 1.0126860464232046 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.031119814694062903, + "pred_variance_6d": 0.029661756507812522, + "pred_gt_ratio": 0.9531469515296133 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.2741106435761934, + "pred_variance_6d": 0.23751913294716284, + "pred_gt_ratio": 0.8665082458979402 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.048844176402784004, + "pred_variance_6d": 0.03148243893276537, + "pred_gt_ratio": 0.6445484651670972 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.013294943050347847, + "pred_variance_6d": 0.02732035816472022, + "pred_gt_ratio": 2.0549436023349803 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.17726570739539127, + "pred_variance_6d": 0.13027184752376098, + "pred_gt_ratio": 0.7348959335557753 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06215319041469471, + "pred_variance_6d": 0.066880962004493, + "pred_gt_ratio": 1.0760664345346385 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.03698108778165434, + "pred_variance_6d": 0.037548777367881106, + "pred_gt_ratio": 1.015350808217934 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.15541348357880702, + "pred_variance_6d": 0.12310387160797776, + "pred_gt_ratio": 0.7921054774218113 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.024819460131972153, + "pred_variance_6d": 0.010530859023926727, + "pred_gt_ratio": 0.4242984725667337 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.052086190760765684, + "pred_variance_6d": 0.03219352375985779, + "pred_gt_ratio": 0.6180817466134959 + } + ] + } + } + } + }, + "hard": { + "hands": 488, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 180, + "variance": 0.7216755774104807 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 180, + "variance": 0.08869835021167637 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 180, + "variance": 0.08626865914916154 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 180, + "variance": 0.03914948525409978 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 180, + "variance": 0.10062364842175701 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 180, + "variance": 0.07594666645089979 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 180, + "variance": 0.03251117276277506 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 180, + "variance": 0.19387960847459368 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 180, + "variance": 0.06605427950664242 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 180, + "variance": 0.059160565093287786 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 180, + "variance": 0.14626557141486912 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 180, + "variance": 0.08307399865880341 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 180, + "variance": 0.0407806635414321 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 180, + "variance": 0.06031602038668906 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 180, + "variance": 0.03414197666792314 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 180, + "variance": 0.03953256416902763 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 308, + "variance": 0.9011416865350345 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 308, + "variance": 0.1071358232161539 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 308, + "variance": 0.13066771667467203 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 308, + "variance": 0.04031062797161822 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 308, + "variance": 0.2612633704123083 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 308, + "variance": 0.07176775645359448 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 308, + "variance": 0.09187937080523265 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 308, + "variance": 0.3264421614740461 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 308, + "variance": 0.09882061809099224 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 308, + "variance": 0.1582634435437344 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 308, + "variance": 0.26351325961149585 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 308, + "variance": 0.0809051766964645 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 308, + "variance": 0.1240315561135563 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 308, + "variance": 0.05921969686286878 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 308, + "variance": 0.016878418295302018 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 308, + "variance": 0.0387037224391419 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 25.59522438733304, + "count": 488 + }, + "root_relative_mpjpe_mm": { + "mean": 15.127890355274326, + "count": 488 + }, + "mpvpe_mm": { + "mean": 25.277604851566377, + "count": 488 + }, + "projected_mano_2d_error_px": { + "mean": 12.167142165977447, + "count": 488 + }, + "local_pose_angle_deg": { + "mean": 11.43315220172288, + "count": 488 + }, + "root_relative_fingertip_mm": { + "mean": 21.215996558548973, + "count": 488 + }, + "distal_angle_bias_deg": { + "mean": -3.9552774101984305, + "count": 488 + }, + "distal_angle_mae_deg": { + "mean": 8.878255838742021, + "count": 488 + }, + "gt60_angle_bias_deg": { + "mean": -14.813732662861296, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 9.348731926718695, + 10.608943892062687, + 7.179759758478794, + 10.751097362061016, + 12.124442968883963, + 9.097395829917467, + 18.959116924248757, + 12.583606057968296, + 10.375452748637219, + 13.360127430470264, + 13.711780276943426, + 8.68451625658352, + 11.140735293204179, + 10.720286164982397, + 12.851281525536638 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8616982693103896, + "mean_abs_log_variance_ratio": 0.3039490382780567, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 180, + "gt_variance_6d": 0.7216755774104807, + "pred_variance_6d": 0.6602914961708598, + "pred_gt_ratio": 0.9149422771657598 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08869835021167637, + "pred_variance_6d": 0.05729236246274447, + "pred_gt_ratio": 0.6459236538900407 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08626865914916154, + "pred_variance_6d": 0.07674431349748913, + "pred_gt_ratio": 0.889596688465918 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03914948525409978, + "pred_variance_6d": 0.024057707084520343, + "pred_gt_ratio": 0.6145088991176708 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.10062364842175701, + "pred_variance_6d": 0.07487426215658266, + "pred_gt_ratio": 0.7441020409312968 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.07594666645089979, + "pred_variance_6d": 0.05943591055826371, + "pred_gt_ratio": 0.7826006503746885 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03251117276277506, + "pred_variance_6d": 0.027577101318646994, + "pred_gt_ratio": 0.8482345906088775 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.19387960847459368, + "pred_variance_6d": 0.13036676121347474, + "pred_gt_ratio": 0.6724108958088711 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06605427950664242, + "pred_variance_6d": 0.043537454409440915, + "pred_gt_ratio": 0.6591163318201478 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.059160565093287786, + "pred_variance_6d": 0.05392171919912529, + "pred_gt_ratio": 0.9114469936874068 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.14626557141486912, + "pred_variance_6d": 0.10546400706459107, + "pred_gt_ratio": 0.7210446453284068 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08307399865880341, + "pred_variance_6d": 0.06897312640749022, + "pred_gt_ratio": 0.8302613034286762 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.0407806635414321, + "pred_variance_6d": 0.03245732473746683, + "pred_gt_ratio": 0.7958998681934399 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06031602038668906, + "pred_variance_6d": 0.05963676492412365, + "pred_gt_ratio": 0.9887383905932342 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03414197666792314, + "pred_variance_6d": 0.02031252500819574, + "pred_gt_ratio": 0.5949428530680135 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03953256416902763, + "pred_variance_6d": 0.03001231795646963, + "pred_gt_ratio": 0.7591796430949252 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 308, + "gt_variance_6d": 0.9011416865350345, + "pred_variance_6d": 0.8645366687445859, + "pred_gt_ratio": 0.9593792870339869 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1071358232161539, + "pred_variance_6d": 0.07291365151684451, + "pred_gt_ratio": 0.6805720937033003 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.13066771667467203, + "pred_variance_6d": 0.14825777177701094, + "pred_gt_ratio": 1.1346166868908676 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.04031062797161822, + "pred_variance_6d": 0.015998617075844032, + "pred_gt_ratio": 0.3968833501454824 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.2612633704123083, + "pred_variance_6d": 0.19005430347044508, + "pred_gt_ratio": 0.727443357905527 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.07176775645359448, + "pred_variance_6d": 0.07556584431457758, + "pred_gt_ratio": 1.052921925508971 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09187937080523265, + "pred_variance_6d": 0.17291228807331643, + "pred_gt_ratio": 1.881948978948263 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.3264421614740461, + "pred_variance_6d": 0.3339098023819352, + "pred_gt_ratio": 1.0228758469009305 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09882061809099224, + "pred_variance_6d": 0.1123893385678086, + "pred_gt_ratio": 1.1373065736577617 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1582634435437344, + "pred_variance_6d": 0.1924653532698692, + "pred_gt_ratio": 1.2161074532457237 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.26351325961149585, + "pred_variance_6d": 0.2608497650605974, + "pred_gt_ratio": 0.9898923699140404 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0809051766964645, + "pred_variance_6d": 0.06424288512754228, + "pred_gt_ratio": 0.7940516015256369 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1240315561135563, + "pred_variance_6d": 0.1751196353401253, + "pred_gt_ratio": 1.4118958177046141 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.05921969686286878, + "pred_variance_6d": 0.058578924672926844, + "pred_gt_ratio": 0.989179745525788 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.016878418295302018, + "pred_variance_6d": 0.009689220908912263, + "pred_gt_ratio": 0.574059769072626 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0387037224391419, + "pred_variance_6d": 0.008989327915634176, + "pred_gt_ratio": 0.23226003467157663 + } + ] + } + }, + "N0_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 25.850976737796284, + "count": 488 + }, + "root_relative_mpjpe_mm": { + "mean": 15.101867126636817, + "count": 488 + }, + "mpvpe_mm": { + "mean": 25.540323404992215, + "count": 488 + }, + "projected_mano_2d_error_px": { + "mean": 12.323754678007033, + "count": 488 + }, + "local_pose_angle_deg": { + "mean": 11.518579788872453, + "count": 488 + }, + "root_relative_fingertip_mm": { + "mean": 21.178014342902138, + "count": 488 + }, + "distal_angle_bias_deg": { + "mean": -3.782733320212755, + "count": 488 + }, + "distal_angle_mae_deg": { + "mean": 8.827019997307511, + "count": 488 + }, + "gt60_angle_bias_deg": { + "mean": -14.418034544683618, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 9.620717735106094, + 10.644284045476406, + 7.247429603680235, + 11.195079293040955, + 11.914070715303303, + 9.138704930844366, + 19.270359596390215, + 12.75434731753146, + 10.50522034914523, + 13.677869879808583, + 13.581435925892142, + 8.609292303074579, + 11.3895520901338, + 10.675681174289984, + 12.55464240395632 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.25575235046324185, + "recording_bootstrap_95ci": [ + -0.1916098927049527, + 0.7650511577147394 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": -0.026023228637507705, + "recording_bootstrap_95ci": [ + -0.18363176831629383, + 0.1481155029555287 + ], + "count": 488, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.2627185534258358, + "recording_bootstrap_95ci": [ + -0.17866170909463275, + 0.7660764507958966 + ], + "count": 488, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.1566125120295853, + "recording_bootstrap_95ci": [ + -0.23761781694797368, + 0.5335920680428139 + ], + "count": 488, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.08542758714957316, + "recording_bootstrap_95ci": [ + -4.463387837472559e-05, + 0.16919449163988523 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": -0.037982215646837576, + "recording_bootstrap_95ci": [ + -0.40201920589008244, + 0.3445469662219613 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.1725440899856755, + "recording_bootstrap_95ci": [ + -0.08163994873810104, + 0.36531704198983533 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": -0.05123584143451003, + "recording_bootstrap_95ci": [ + -0.1695709028239592, + 0.07505496637135275 + ], + "count": 488, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.3956981181776781, + "recording_bootstrap_95ci": [ + -0.15981417210925783, + 0.7368247920675336 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8826835512231505, + "mean_abs_log_variance_ratio": 0.29897097644134774, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 180, + "gt_variance_6d": 0.7216755774104807, + "pred_variance_6d": 0.6673047384118013, + "pred_gt_ratio": 0.9246602757519201 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08869835021167637, + "pred_variance_6d": 0.05890046702146778, + "pred_gt_ratio": 0.664053693004473 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08626865914916154, + "pred_variance_6d": 0.0708826824683928, + "pred_gt_ratio": 0.8216504483491989 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03914948525409978, + "pred_variance_6d": 0.025586141391299624, + "pred_gt_ratio": 0.6535498800362953 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.10062364842175701, + "pred_variance_6d": 0.08001256901270692, + "pred_gt_ratio": 0.7951666458896404 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.07594666645089979, + "pred_variance_6d": 0.06359317230179333, + "pred_gt_ratio": 0.8373398764369322 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03251117276277506, + "pred_variance_6d": 0.02684995070646639, + "pred_gt_ratio": 0.8258684146026651 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.19387960847459368, + "pred_variance_6d": 0.13168619882218877, + "pred_gt_ratio": 0.6792163438861346 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06605427950664242, + "pred_variance_6d": 0.04743871769168619, + "pred_gt_ratio": 0.7181778084024936 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.059160565093287786, + "pred_variance_6d": 0.05592389970905148, + "pred_gt_ratio": 0.9452901543598756 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.14626557141486912, + "pred_variance_6d": 0.1035609874302001, + "pred_gt_ratio": 0.7080339305307788 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08307399865880341, + "pred_variance_6d": 0.07425943019024439, + "pred_gt_ratio": 0.8938949778406395 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.0407806635414321, + "pred_variance_6d": 0.033231269449161494, + "pred_gt_ratio": 0.8148780957278781 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06031602038668906, + "pred_variance_6d": 0.06321513305013055, + "pred_gt_ratio": 1.0480653837049447 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03414197666792314, + "pred_variance_6d": 0.021050247111880402, + "pred_gt_ratio": 0.6165503338199338 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03953256416902763, + "pred_variance_6d": 0.02877617467552772, + "pred_gt_ratio": 0.7279106549347698 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 308, + "gt_variance_6d": 0.9011416865350345, + "pred_variance_6d": 0.8754393097407683, + "pred_gt_ratio": 0.9714779848959225 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1071358232161539, + "pred_variance_6d": 0.07378740030573888, + "pred_gt_ratio": 0.6887276178096632 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.13066771667467203, + "pred_variance_6d": 0.15337636754318196, + "pred_gt_ratio": 1.1737892988904708 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.04031062797161822, + "pred_variance_6d": 0.016797821107238223, + "pred_gt_ratio": 0.4167094871125595 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.2612633704123083, + "pred_variance_6d": 0.20182503488699538, + "pred_gt_ratio": 0.7724964834086335 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.07176775645359448, + "pred_variance_6d": 0.07646879482234376, + "pred_gt_ratio": 1.0655034879317844 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09187937080523265, + "pred_variance_6d": 0.1765301296966046, + "pred_gt_ratio": 1.921324973707275 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.3264421614740461, + "pred_variance_6d": 0.35141149465953786, + "pred_gt_ratio": 1.0764893023399398 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09882061809099224, + "pred_variance_6d": 0.1113842889695791, + "pred_gt_ratio": 1.1271361292945816 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1582634435437344, + "pred_variance_6d": 0.2023873919927574, + "pred_gt_ratio": 1.278800634315971 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.26351325961149585, + "pred_variance_6d": 0.2757809090935305, + "pred_gt_ratio": 1.0465542018649123 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0809051766964645, + "pred_variance_6d": 0.06462551238757058, + "pred_gt_ratio": 0.798780931287363 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1240315561135563, + "pred_variance_6d": 0.18106189964796246, + "pred_gt_ratio": 1.4598051118716304 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.05921969686286878, + "pred_variance_6d": 0.05937976668954347, + "pred_gt_ratio": 1.0027029828782366 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.016878418295302018, + "pred_variance_6d": 0.009060586936556205, + "pred_gt_ratio": 0.5368149300505339 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0387037224391419, + "pred_variance_6d": 0.009074210192282262, + "pred_gt_ratio": 0.23445316420276205 + } + ] + } + }, + "N0_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 26.071700697062447, + "count": 488 + }, + "root_relative_mpjpe_mm": { + "mean": 15.145111594532358, + "count": 488 + }, + "mpvpe_mm": { + "mean": 25.748952721963164, + "count": 488 + }, + "projected_mano_2d_error_px": { + "mean": 12.431189799895051, + "count": 488 + }, + "local_pose_angle_deg": { + "mean": 11.607126500762877, + "count": 488 + }, + "root_relative_fingertip_mm": { + "mean": 21.265353781278016, + "count": 488 + }, + "distal_angle_bias_deg": { + "mean": -3.922104548723971, + "count": 488 + }, + "distal_angle_mae_deg": { + "mean": 8.900706813716498, + "count": 488 + }, + "gt60_angle_bias_deg": { + "mean": -14.681723083818344, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 9.756823860475274, + 10.447839970105006, + 7.310772949921303, + 11.301272190008007, + 12.049538188659755, + 9.236630165491436, + 19.673916643760244, + 12.827098083056388, + 10.5333492407789, + 13.867163224909149, + 13.72655132870938, + 8.655976199346487, + 11.327508659392107, + 10.719687889101076, + 12.672759840967226 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.47647630972940413, + "recording_bootstrap_95ci": [ + 0.08341949135077414, + 0.9412230400745593 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.017221239258031377, + "recording_bootstrap_95ci": [ + -0.14606591898989413, + 0.2129207745773331 + ], + "count": 488, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.47134787039678605, + "recording_bootstrap_95ci": [ + 0.08943327442791042, + 0.9264402761752131 + ], + "count": 488, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.2640476339176053, + "recording_bootstrap_95ci": [ + -0.013630871124737903, + 0.5945093537833129 + ], + "count": 488, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.17397429903999703, + "recording_bootstrap_95ci": [ + 0.04782744418722674, + 0.3270873909446677 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.04935722272904193, + "recording_bootstrap_95ci": [ + -0.30620061936585796, + 0.41064928145063556 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.03317286147445929, + "recording_bootstrap_95ci": [ + -0.23980267048006726, + 0.26905578851555484 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.022450974974475922, + "recording_bootstrap_95ci": [ + -0.13182783062564013, + 0.20536920865842898 + ], + "count": 488, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.132009579042951, + "recording_bootstrap_95ci": [ + -0.451257445329207, + 0.5596174129671856 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8940704056939068, + "mean_abs_log_variance_ratio": 0.2909375315830446, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 180, + "gt_variance_6d": 0.7216755774104807, + "pred_variance_6d": 0.6685735544973745, + "pred_gt_ratio": 0.9264184287576323 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08869835021167637, + "pred_variance_6d": 0.061009276979989785, + "pred_gt_ratio": 0.687828768341155 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08626865914916154, + "pred_variance_6d": 0.07474494539181384, + "pred_gt_ratio": 0.8664206228426155 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03914948525409978, + "pred_variance_6d": 0.02610950450626823, + "pred_gt_ratio": 0.6669182068884038 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.10062364842175701, + "pred_variance_6d": 0.08142581965016565, + "pred_gt_ratio": 0.8092115613704942 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.07594666645089979, + "pred_variance_6d": 0.06421747377233987, + "pred_gt_ratio": 0.8455601380984517 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03251117276277506, + "pred_variance_6d": 0.026750071547453572, + "pred_gt_ratio": 0.8227962658450177 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.19387960847459368, + "pred_variance_6d": 0.1378788789130174, + "pred_gt_ratio": 0.7111571969730137 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06605427950664242, + "pred_variance_6d": 0.04666240630744667, + "pred_gt_ratio": 0.7064251802603387 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.059160565093287786, + "pred_variance_6d": 0.05648992825814613, + "pred_gt_ratio": 0.9548578207302374 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.14626557141486912, + "pred_variance_6d": 0.10628079280715079, + "pred_gt_ratio": 0.7266289105431031 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08307399865880341, + "pred_variance_6d": 0.0742164367754502, + "pred_gt_ratio": 0.8933774462966149 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.0407806635414321, + "pred_variance_6d": 0.03298292771060933, + "pred_gt_ratio": 0.808788402304919 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06031602038668906, + "pred_variance_6d": 0.06320518037297733, + "pred_gt_ratio": 1.047900374855067 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03414197666792314, + "pred_variance_6d": 0.022181637831987715, + "pred_gt_ratio": 0.6496881550747374 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03953256416902763, + "pred_variance_6d": 0.030559903115241357, + "pred_gt_ratio": 0.7730311392040682 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 308, + "gt_variance_6d": 0.9011416865350345, + "pred_variance_6d": 0.8749233764645542, + "pred_gt_ratio": 0.9709054519813728 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1071358232161539, + "pred_variance_6d": 0.07393764856659034, + "pred_gt_ratio": 0.6901300269790809 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.13066771667467203, + "pred_variance_6d": 0.15053157181384724, + "pred_gt_ratio": 1.15201807795135 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.04031062797161822, + "pred_variance_6d": 0.016911315402006466, + "pred_gt_ratio": 0.41952498020902407 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.2612633704123083, + "pred_variance_6d": 0.20327057186171676, + "pred_gt_ratio": 0.77802935612799 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.07176775645359448, + "pred_variance_6d": 0.07807755719335358, + "pred_gt_ratio": 1.0879197156433202 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09187937080523265, + "pred_variance_6d": 0.17863185522473166, + "pred_gt_ratio": 1.9441998095894486 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.3264421614740461, + "pred_variance_6d": 0.3595111173899221, + "pred_gt_ratio": 1.1013011179884162 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09882061809099224, + "pred_variance_6d": 0.11347497269458019, + "pred_gt_ratio": 1.1482924807259804 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1582634435437344, + "pred_variance_6d": 0.20479759000217787, + "pred_gt_ratio": 1.2940296597652652 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.26351325961149585, + "pred_variance_6d": 0.2793118223239997, + "pred_gt_ratio": 1.0599535778040015 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0809051766964645, + "pred_variance_6d": 0.06434945661140618, + "pred_gt_ratio": 0.7953688408941847 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1240315561135563, + "pred_variance_6d": 0.18350418331160395, + "pred_gt_ratio": 1.479495936853343 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.05921969686286878, + "pred_variance_6d": 0.05933279490897958, + "pred_gt_ratio": 1.0019098045431185 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.016878418295302018, + "pred_variance_6d": 0.009379736778991213, + "pred_gt_ratio": 0.5557236830421481 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0387037224391419, + "pred_variance_6d": 0.009073772047502256, + "pred_gt_ratio": 0.2344418437211031 + } + ] + } + }, + "N1_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 25.805884908457273, + "count": 488 + }, + "root_relative_mpjpe_mm": { + "mean": 15.092671280024481, + "count": 488 + }, + "mpvpe_mm": { + "mean": 25.492631277099985, + "count": 488 + }, + "projected_mano_2d_error_px": { + "mean": 12.23517433346295, + "count": 488 + }, + "local_pose_angle_deg": { + "mean": 11.489771823414037, + "count": 488 + }, + "root_relative_fingertip_mm": { + "mean": 21.122828944784697, + "count": 488 + }, + "distal_angle_bias_deg": { + "mean": -3.576653533905256, + "count": 488 + }, + "distal_angle_mae_deg": { + "mean": 8.76580624453357, + "count": 488 + }, + "gt60_angle_bias_deg": { + "mean": -14.18970313003595, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 9.544176357569265, + 10.601796909556038, + 7.233270718548142, + 11.193503281864963, + 11.746376922018216, + 9.204929839514318, + 19.322295311410898, + 12.744839686350744, + 10.458565471541197, + 13.694393539770704, + 13.392104993223167, + 8.599263424511816, + 11.406046902302835, + 10.661629455011399, + 12.543376008140259 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.21066052112423006, + "recording_bootstrap_95ci": [ + -0.24066463405731717, + 0.7343747616463585 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": -0.03521907524984391, + "recording_bootstrap_95ci": [ + -0.19311266361205665, + 0.14473973740302967 + ], + "count": 488, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.21502642553360735, + "recording_bootstrap_95ci": [ + -0.2301402838518901, + 0.7333968231568285 + ], + "count": 488, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.0680321674855029, + "recording_bootstrap_95ci": [ + -0.3058484395491657, + 0.4223717783616222 + ], + "count": 488, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.056619621691156606, + "recording_bootstrap_95ci": [ + -0.05068159621373693, + 0.1631767027756461 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": -0.09316761376427822, + "recording_bootstrap_95ci": [ + -0.44828150290088664, + 0.2679489882288443 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.37862387629317457, + "recording_bootstrap_95ci": [ + 0.15638927966457353, + 0.5419355419779406 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": -0.11244959420845156, + "recording_bootstrap_95ci": [ + -0.24960261068509182, + 0.031947746497399 + ], + "count": 488, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.6240295328253465, + "recording_bootstrap_95ci": [ + 0.05059309374779256, + 0.9955809614368558 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8878016495798119, + "mean_abs_log_variance_ratio": 0.2924570535911066, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 180, + "gt_variance_6d": 0.7216755774104807, + "pred_variance_6d": 0.6673480389783598, + "pred_gt_ratio": 0.9247202757961421 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08869835021167637, + "pred_variance_6d": 0.059633859665572005, + "pred_gt_ratio": 0.6723220840439231 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08626865914916154, + "pred_variance_6d": 0.07199369392363625, + "pred_gt_ratio": 0.834528954474146 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03914948525409978, + "pred_variance_6d": 0.02679413597466263, + "pred_gt_ratio": 0.6844058306451607 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.10062364842175701, + "pred_variance_6d": 0.0819371812967715, + "pred_gt_ratio": 0.8142934845031409 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.07594666645089979, + "pred_variance_6d": 0.06468310420393836, + "pred_gt_ratio": 0.8516911567903586 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03251117276277506, + "pred_variance_6d": 0.02704737055476403, + "pred_gt_ratio": 0.8319407839305315 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.19387960847459368, + "pred_variance_6d": 0.13269569613624682, + "pred_gt_ratio": 0.6844231695136495 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06605427950664242, + "pred_variance_6d": 0.048141533751198215, + "pred_gt_ratio": 0.7288177860808717 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.059160565093287786, + "pred_variance_6d": 0.05664683053545901, + "pred_gt_ratio": 0.9575099637086804 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.14626557141486912, + "pred_variance_6d": 0.10571064257905555, + "pred_gt_ratio": 0.7227308624749212 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08307399865880341, + "pred_variance_6d": 0.07540375583804465, + "pred_gt_ratio": 0.9076697529360357 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.0407806635414321, + "pred_variance_6d": 0.03351587332357218, + "pred_gt_ratio": 0.821856988411209 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06031602038668906, + "pred_variance_6d": 0.06333360511468793, + "pred_gt_ratio": 1.0500295727180438 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03414197666792314, + "pred_variance_6d": 0.02092837370207811, + "pred_gt_ratio": 0.6129807276724142 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03953256416902763, + "pred_variance_6d": 0.029142114615391963, + "pred_gt_ratio": 0.7371673259237705 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 308, + "gt_variance_6d": 0.9011416865350345, + "pred_variance_6d": 0.8760750930060953, + "pred_gt_ratio": 0.9721835157517545 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1071358232161539, + "pred_variance_6d": 0.07342314750464565, + "pred_gt_ratio": 0.6853277017950326 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.13066771667467203, + "pred_variance_6d": 0.1542262782502528, + "pred_gt_ratio": 1.180293665299405 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.04031062797161822, + "pred_variance_6d": 0.017653548929715046, + "pred_gt_ratio": 0.43793782974912976 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.2612633704123083, + "pred_variance_6d": 0.20177255866419386, + "pred_gt_ratio": 0.7722956277635474 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.07176775645359448, + "pred_variance_6d": 0.0752980783354345, + "pred_gt_ratio": 1.0491909188233124 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09187937080523265, + "pred_variance_6d": 0.17961240917520102, + "pred_gt_ratio": 1.9548719979367977 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.3264421614740461, + "pred_variance_6d": 0.35075088679611066, + "pred_gt_ratio": 1.0744656425882575 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09882061809099224, + "pred_variance_6d": 0.10954804974456642, + "pred_gt_ratio": 1.1085545897283962 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1582634435437344, + "pred_variance_6d": 0.20190672863784204, + "pred_gt_ratio": 1.2757635251506916 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.26351325961149585, + "pred_variance_6d": 0.27522927938148983, + "pred_gt_ratio": 1.0444608358124643 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0809051766964645, + "pred_variance_6d": 0.06422673140684507, + "pred_gt_ratio": 0.7938519391386698 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1240315561135563, + "pred_variance_6d": 0.18166002059222133, + "pred_gt_ratio": 1.4646274406644035 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.05921969686286878, + "pred_variance_6d": 0.05953285602144703, + "pred_gt_ratio": 1.0052880912123445 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.016878418295302018, + "pred_variance_6d": 0.008852319661399023, + "pred_gt_ratio": 0.5244756651079681 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0387037224391419, + "pred_variance_6d": 0.008862187957622664, + "pred_gt_ratio": 0.22897508040880699 + } + ] + } + }, + "N1_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 26.04882620006311, + "count": 488 + }, + "root_relative_mpjpe_mm": { + "mean": 15.126268076114966, + "count": 488 + }, + "mpvpe_mm": { + "mean": 25.728403340597623, + "count": 488 + }, + "projected_mano_2d_error_px": { + "mean": 12.37138904850991, + "count": 488 + }, + "local_pose_angle_deg": { + "mean": 11.577777720865656, + "count": 488 + }, + "root_relative_fingertip_mm": { + "mean": 21.20134459069518, + "count": 488 + }, + "distal_angle_bias_deg": { + "mean": -3.6993895169408595, + "count": 488 + }, + "distal_angle_mae_deg": { + "mean": 8.827757406674447, + "count": 488 + }, + "gt60_angle_bias_deg": { + "mean": -14.38297939129013, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 9.706909066096681, + 10.409961830763542, + 7.311889234869207, + 11.299929578162608, + 11.883985334366072, + 9.26547742341874, + 19.76048351347935, + 12.792454012593286, + 10.470354368757517, + 13.909004152309699, + 13.53027975809623, + 8.636897973471978, + 11.327013634633822, + 10.722688646101561, + 12.639328358725447 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.45360181273007, + "recording_bootstrap_95ci": [ + 0.049200199033796174, + 0.9317741499841713 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": -0.0016222791593582904, + "recording_bootstrap_95ci": [ + -0.16805194482531463, + 0.2040871808729984 + ], + "count": 488, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.4507984890312445, + "recording_bootstrap_95ci": [ + 0.06004042243576205, + 0.921391006434111 + ], + "count": 488, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.2042468825324637, + "recording_bootstrap_95ci": [ + -0.06433589185446487, + 0.5214406119964582 + ], + "count": 488, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.14462551914277624, + "recording_bootstrap_95ci": [ + 0.004040498965275726, + 0.31288033504121615 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": -0.014651967853796287, + "recording_bootstrap_95ci": [ + -0.34898977335773074, + 0.3275990356063716 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.25588789325757105, + "recording_bootstrap_95ci": [ + -0.011274721834168475, + 0.48392331913737435 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": -0.050498432067574046, + "recording_bootstrap_95ci": [ + -0.20791024354519536, + 0.13701697781980302 + ], + "count": 488, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.4307532715711662, + "recording_bootstrap_95ci": [ + -0.1818091494782167, + 0.8761923271176186 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8983196769208429, + "mean_abs_log_variance_ratio": 0.2844425803899192, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 180, + "gt_variance_6d": 0.7216755774104807, + "pred_variance_6d": 0.6684718612921029, + "pred_gt_ratio": 0.9262775161253431 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08869835021167637, + "pred_variance_6d": 0.0618714263984589, + "pred_gt_ratio": 0.6975487847384343 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08626865914916154, + "pred_variance_6d": 0.07528659830590673, + "pred_gt_ratio": 0.8726992983133487 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03914948525409978, + "pred_variance_6d": 0.027451952894318704, + "pred_gt_ratio": 0.7012085271656006 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.10062364842175701, + "pred_variance_6d": 0.08364691388074923, + "pred_gt_ratio": 0.8312848439975961 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.07594666645089979, + "pred_variance_6d": 0.06528576472336153, + "pred_gt_ratio": 0.8596264691297462 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03251117276277506, + "pred_variance_6d": 0.026662357373008747, + "pred_gt_ratio": 0.820098295670738 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.19387960847459368, + "pred_variance_6d": 0.1387884832503198, + "pred_gt_ratio": 0.715848790609183 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06605427950664242, + "pred_variance_6d": 0.047360769417253167, + "pred_gt_ratio": 0.7169977444457716 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.059160565093287786, + "pred_variance_6d": 0.05705639709445151, + "pred_gt_ratio": 0.9644329293420659 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.14626557141486912, + "pred_variance_6d": 0.10874739176709108, + "pred_gt_ratio": 0.743492748943898 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08307399865880341, + "pred_variance_6d": 0.07552163343651686, + "pred_gt_ratio": 0.9090886999035019 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.0407806635414321, + "pred_variance_6d": 0.032978819478075794, + "pred_gt_ratio": 0.8086876625872005 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06031602038668906, + "pred_variance_6d": 0.06323367868738336, + "pred_gt_ratio": 1.048372858189069 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03414197666792314, + "pred_variance_6d": 0.021945011134234027, + "pred_gt_ratio": 0.6427574872913456 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03953256416902763, + "pred_variance_6d": 0.030997633262325516, + "pred_gt_ratio": 0.7841037866855869 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 308, + "gt_variance_6d": 0.9011416865350345, + "pred_variance_6d": 0.8750652835961197, + "pred_gt_ratio": 0.9710629268087899 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1071358232161539, + "pred_variance_6d": 0.07420131992039514, + "pred_gt_ratio": 0.6925911211853841 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.13066771667467203, + "pred_variance_6d": 0.15260850692729167, + "pred_gt_ratio": 1.1679128618069174 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.04031062797161822, + "pred_variance_6d": 0.0179331350145251, + "pred_gt_ratio": 0.44487362060326635 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.2612633704123083, + "pred_variance_6d": 0.203567649063678, + "pred_gt_ratio": 0.7791664355490064 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.07176775645359448, + "pred_variance_6d": 0.07718443525367531, + "pred_gt_ratio": 1.0754751028560199 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09187937080523265, + "pred_variance_6d": 0.1801029925557053, + "pred_gt_ratio": 1.960211426975164 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.3264421614740461, + "pred_variance_6d": 0.35947060894541116, + "pred_gt_ratio": 1.1011770272633457 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09882061809099224, + "pred_variance_6d": 0.11113615158224219, + "pred_gt_ratio": 1.124625141282865 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1582634435437344, + "pred_variance_6d": 0.2037190549796653, + "pred_gt_ratio": 1.2872148515040351 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.26351325961149585, + "pred_variance_6d": 0.2800072679503412, + "pred_gt_ratio": 1.0625927073391406 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0809051766964645, + "pred_variance_6d": 0.0637602342186312, + "pred_gt_ratio": 0.7880859646082136 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1240315561135563, + "pred_variance_6d": 0.1834223027955533, + "pred_gt_ratio": 1.4788357781113555 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.05921969686286878, + "pred_variance_6d": 0.05913256015681875, + "pred_gt_ratio": 0.9985285857465329 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.016878418295302018, + "pred_variance_6d": 0.009149000558648816, + "pred_gt_ratio": 0.5420531947116971 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0387037224391419, + "pred_variance_6d": 0.008874627007664978, + "pred_gt_ratio": 0.22929647197681116 + } + ] + } + } + } + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_h2o_n1_20k.json b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_h2o_n1_20k.json new file mode 100644 index 0000000000000000000000000000000000000000..2b8920cb7739b9d44a35724a8b74cd98f55428bb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_h2o_n1_20k.json @@ -0,0 +1,3070 @@ +{ + "source": "H2O", + "role": "development", + "input_mode": "rgb", + "gt": "source_native_not_refitted", + "clips": 96, + "panel_sha256": "5dac67629afe705e237e410011727f2bc6f115ca86a9c5a42e9ad925822432ec", + "parent_checkpoint_sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a", + "checkpoints": { + "U0_parent": { + "path": "/home/wuyifan/unified_mot_u0_depthsafe_20261001/runs/U0/update_0020004.pt", + "sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a" + }, + "N1_20K": { + "path": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0020000.pt", + "sha256": "a47c1f157c03b2370e785e6a6ddf0644fc87098b672e91e2e82da40c67894396" + } + }, + "hard_definition": "GT >=2 non-thumb distal angles >=45deg OR >=1 >=60deg; complete 21-joint geometry and MANO pose only", + "groups": { + "all": { + "hands": 1536, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 768, + "variance": 0.6276556489562777 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 768, + "variance": 0.09593922255610139 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 768, + "variance": 0.12244189528720367 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 768, + "variance": 0.03214429306650994 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 768, + "variance": 0.13904494533806688 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 768, + "variance": 0.08829846748000257 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 768, + "variance": 0.042789003839059675 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 768, + "variance": 0.23990383480120056 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 768, + "variance": 0.06611468194100378 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 768, + "variance": 0.04967650231648196 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 768, + "variance": 0.1615580244429538 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 768, + "variance": 0.12077039788861064 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 768, + "variance": 0.05196939792383421 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 768, + "variance": 0.10800775482101788 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 768, + "variance": 0.02196545540494259 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 768, + "variance": 0.048189028939135216 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 768, + "variance": 0.6731547796707966 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 768, + "variance": 0.12440969118655591 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 768, + "variance": 0.10154130448647992 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 768, + "variance": 0.031123622695296803 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 768, + "variance": 0.2352408934541732 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 768, + "variance": 0.1985170871883211 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 768, + "variance": 0.14216654828818165 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 768, + "variance": 0.3842963067498238 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 768, + "variance": 0.15250539617004505 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 768, + "variance": 0.16994163048790034 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 768, + "variance": 0.2784070818638871 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 768, + "variance": 0.21526081221477664 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 768, + "variance": 0.165995085812219 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 768, + "variance": 0.12790844637157237 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 768, + "variance": 0.02238697863982246 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 768, + "variance": 0.04676594210336735 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 20.630753997092445, + "count": 1536 + }, + "root_relative_mpjpe_mm": { + "mean": 13.283040416582176, + "count": 1536 + }, + "mpvpe_mm": { + "mean": 20.46384940482676, + "count": 1536 + }, + "projected_mano_2d_error_px": { + "mean": 10.793614093214273, + "count": 1536 + }, + "local_pose_angle_deg": { + "mean": 10.023834046442062, + "count": 1536 + }, + "root_relative_fingertip_mm": { + "mean": 19.17614179197699, + "count": 1536 + }, + "distal_angle_bias_deg": { + "mean": -0.9564234532105426, + "count": 1536 + }, + "distal_angle_mae_deg": { + "mean": 6.352203568909317, + "count": 1536 + }, + "gt60_angle_bias_deg": { + "mean": -14.813732662861296, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 8.133591202863803, + 8.277025114706097, + 6.608799953750956, + 9.257692793772245, + 9.766511462745257, + 7.905319208997146, + 16.600299852201715, + 10.179078662962032, + 7.10320868868924, + 11.299065872405967, + 11.998560446586149, + 7.779385318552765, + 11.297737618151587, + 10.817307048632452, + 13.33391980852078 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8051487100534478, + "mean_abs_log_variance_ratio": 0.2533391585966686, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 768, + "gt_variance_6d": 0.6276556489562777, + "pred_variance_6d": 0.5874918649316394, + "pred_gt_ratio": 0.9360098421938428 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.09593922255610139, + "pred_variance_6d": 0.07778560258846287, + "pred_gt_ratio": 0.8107799971276293 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12244189528720367, + "pred_variance_6d": 0.1168757153498433, + "pred_gt_ratio": 0.9545402337630909 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.03214429306650994, + "pred_variance_6d": 0.024110743965079826, + "pred_gt_ratio": 0.7500785260759086 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.13904494533806688, + "pred_variance_6d": 0.1195750362697045, + "pred_gt_ratio": 0.8599739888348747 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.08829846748000257, + "pred_variance_6d": 0.07201167521845961, + "pred_gt_ratio": 0.815548415206283 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.042789003839059675, + "pred_variance_6d": 0.031225209131742638, + "pred_gt_ratio": 0.7297484477364463 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.23990383480120056, + "pred_variance_6d": 0.21911837499865977, + "pred_gt_ratio": 0.9133592015327102 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.06611468194100378, + "pred_variance_6d": 0.04235992035914568, + "pred_gt_ratio": 0.6407036851049934 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.04967650231648196, + "pred_variance_6d": 0.044097592466890975, + "pred_gt_ratio": 0.8876951961301836 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.1615580244429538, + "pred_variance_6d": 0.1477043428590606, + "pred_gt_ratio": 0.9142494987069804 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12077039788861064, + "pred_variance_6d": 0.08434409855039804, + "pred_gt_ratio": 0.6983838757258262 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.05196939792383421, + "pred_variance_6d": 0.03732461647426406, + "pred_gt_ratio": 0.7182037500023881 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.10800775482101788, + "pred_variance_6d": 0.10121903508856749, + "pred_gt_ratio": 0.937145997121224 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.02196545540494259, + "pred_variance_6d": 0.014219863191042029, + "pred_gt_ratio": 0.6473739300593934 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.048189028939135216, + "pred_variance_6d": 0.05434897701675566, + "pred_gt_ratio": 1.1278288484584473 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 768, + "gt_variance_6d": 0.6731547796707966, + "pred_variance_6d": 0.6340252315793864, + "pred_gt_ratio": 0.9418713952970127 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12440969118655591, + "pred_variance_6d": 0.10646028775191341, + "pred_gt_ratio": 0.8557234306793121 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.10154130448647992, + "pred_variance_6d": 0.11086737969909391, + "pred_gt_ratio": 1.0918451388799693 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.031123622695296803, + "pred_variance_6d": 0.014583675687340687, + "pred_gt_ratio": 0.46857256400118474 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2352408934541732, + "pred_variance_6d": 0.19332894972628667, + "pred_gt_ratio": 0.8218339374907564 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.1985170871883211, + "pred_variance_6d": 0.12324392727682683, + "pred_gt_ratio": 0.6208227665556709 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.14216654828818165, + "pred_variance_6d": 0.13941315507494761, + "pred_gt_ratio": 0.9806326224671875 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.3842963067498238, + "pred_variance_6d": 0.320407883459355, + "pred_gt_ratio": 0.8337521798457979 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.15250539617004505, + "pred_variance_6d": 0.10704969239019525, + "pred_gt_ratio": 0.7019403580371266 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.16994163048790034, + "pred_variance_6d": 0.16451919053915653, + "pred_gt_ratio": 0.9680923389214517 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2784070818638871, + "pred_variance_6d": 0.23288592064873978, + "pred_gt_ratio": 0.8364942410574077 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.21526081221477664, + "pred_variance_6d": 0.12580112282325645, + "pred_gt_ratio": 0.5844125622723113 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.165995085812219, + "pred_variance_6d": 0.15670288532292886, + "pred_gt_ratio": 0.9440212314489727 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12790844637157237, + "pred_variance_6d": 0.10389876096632726, + "pred_gt_ratio": 0.8122900708566401 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.02238697863982246, + "pred_variance_6d": 0.010189021252917766, + "pred_gt_ratio": 0.45513159309462625 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.04676594210336735, + "pred_variance_6d": 0.023649483469355196, + "pred_gt_ratio": 0.5056988570246793 + } + ] + } + }, + "N1_20K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 21.018838859784108, + "count": 1536 + }, + "root_relative_mpjpe_mm": { + "mean": 13.301718684534231, + "count": 1536 + }, + "mpvpe_mm": { + "mean": 20.84231721702963, + "count": 1536 + }, + "projected_mano_2d_error_px": { + "mean": 10.809552322762707, + "count": 1536 + }, + "local_pose_angle_deg": { + "mean": 10.168568132755658, + "count": 1536 + }, + "root_relative_fingertip_mm": { + "mean": 19.21845506100605, + "count": 1536 + }, + "distal_angle_bias_deg": { + "mean": -0.7941844990515771, + "count": 1536 + }, + "distal_angle_mae_deg": { + "mean": 6.450785438530147, + "count": 1536 + }, + "gt60_angle_bias_deg": { + "mean": -14.295726392444946, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 8.411115112122692, + 8.345194046676625, + 6.7883282600572175, + 9.342293612998523, + 9.848013128551733, + 8.066669616169142, + 16.975059906913277, + 10.229080745232446, + 7.174954089665941, + 11.515347365949614, + 12.289353633260665, + 7.892041083270063, + 11.442669900716282, + 10.914824079722166, + 13.293569312081672 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.3880848626916607, + "recording_bootstrap_95ci": [ + 0.1292370478545005, + 0.6715629472707707 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.01867826795205474, + "recording_bootstrap_95ci": [ + -0.12466130241906892, + 0.16736043415342763 + ], + "count": 1536, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.37846781220287085, + "recording_bootstrap_95ci": [ + 0.12341823953514298, + 0.662990028830245 + ], + "count": 1536, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.015938229548434418, + "recording_bootstrap_95ci": [ + -0.15360577074267592, + 0.18241457189045213 + ], + "count": 1536, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.14473408631359538, + "recording_bootstrap_95ci": [ + 0.07669396338363489, + 0.21501975470067308 + ], + "count": 1536, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.042313269029061, + "recording_bootstrap_95ci": [ + -0.1797299938664461, + 0.26815155440320565 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.1622389541589655, + "recording_bootstrap_95ci": [ + 0.006993229602327726, + 0.2935978889717565 + ], + "count": 1536, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.09858186962082982, + "recording_bootstrap_95ci": [ + 0.02153201959445141, + 0.17443541473670235 + ], + "count": 1536, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.518006270416349, + "recording_bootstrap_95ci": [ + -0.04401248699438105, + 0.9113757994732907 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8276723628298591, + "mean_abs_log_variance_ratio": 0.22686028856507628, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 768, + "gt_variance_6d": 0.6276556489562777, + "pred_variance_6d": 0.5908524079317842, + "pred_gt_ratio": 0.9413639611374593 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.09593922255610139, + "pred_variance_6d": 0.07948220120226848, + "pred_gt_ratio": 0.8284640951284601 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12244189528720367, + "pred_variance_6d": 0.12536908382719314, + "pred_gt_ratio": 1.0239067562056545 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.03214429306650994, + "pred_variance_6d": 0.026894821355439073, + "pred_gt_ratio": 0.8366903978815413 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.13904494533806688, + "pred_variance_6d": 0.1222424553509073, + "pred_gt_ratio": 0.8791578511084538 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.08829846748000257, + "pred_variance_6d": 0.08098897249914522, + "pred_gt_ratio": 0.9172183256463339 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.042789003839059675, + "pred_variance_6d": 0.03184467180086119, + "pred_gt_ratio": 0.744225594048347 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.23990383480120056, + "pred_variance_6d": 0.22810218824248596, + "pred_gt_ratio": 0.950806761515529 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.06611468194100378, + "pred_variance_6d": 0.04289111223157992, + "pred_gt_ratio": 0.6487380861917026 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.04967650231648196, + "pred_variance_6d": 0.04626430022883214, + "pred_gt_ratio": 0.9313115471393061 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.1615580244429538, + "pred_variance_6d": 0.15077960642164834, + "pred_gt_ratio": 0.9332845393568715 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.12077039788861064, + "pred_variance_6d": 0.09279218508058154, + "pred_gt_ratio": 0.7683355085586945 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.05196939792383421, + "pred_variance_6d": 0.03843130337810784, + "pred_gt_ratio": 0.7394987225834777 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 768, + "gt_variance_6d": 0.10800775482101788, + "pred_variance_6d": 0.1036923820284147, + "pred_gt_ratio": 0.9600457133864667 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 768, + "gt_variance_6d": 0.02196545540494259, + "pred_variance_6d": 0.014199031287156886, + "pred_gt_ratio": 0.6464255361608332 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 768, + "gt_variance_6d": 0.048189028939135216, + "pred_variance_6d": 0.05227974976368662, + "pred_gt_ratio": 1.0848890487027276 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 768, + "gt_variance_6d": 0.6731547796707966, + "pred_variance_6d": 0.6423344728811419, + "pred_gt_ratio": 0.9542151259703938 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12440969118655591, + "pred_variance_6d": 0.1043534551383623, + "pred_gt_ratio": 0.8387887964602476 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.10154130448647992, + "pred_variance_6d": 0.1131486297467754, + "pred_gt_ratio": 1.114311366384317 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.031123622695296803, + "pred_variance_6d": 0.015621088532812298, + "pred_gt_ratio": 0.5019045721555047 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2352408934541732, + "pred_variance_6d": 0.19815801784227918, + "pred_gt_ratio": 0.8423621205166096 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.1985170871883211, + "pred_variance_6d": 0.1277756349052488, + "pred_gt_ratio": 0.6436505628557597 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.14216654828818165, + "pred_variance_6d": 0.14228288860547855, + "pred_gt_ratio": 1.0008183382004963 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.3842963067498238, + "pred_variance_6d": 0.3268373754905189, + "pred_gt_ratio": 0.8504827388395627 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.15250539617004505, + "pred_variance_6d": 0.1070085550535977, + "pred_gt_ratio": 0.7016706145550554 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.16994163048790034, + "pred_variance_6d": 0.1719966958174327, + "pred_gt_ratio": 1.0120927716394876 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.2784070818638871, + "pred_variance_6d": 0.23800352589039295, + "pred_gt_ratio": 0.8548759762036248 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.21526081221477664, + "pred_variance_6d": 0.12847704572585558, + "pred_gt_ratio": 0.5968436354205869 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.165995085812219, + "pred_variance_6d": 0.16232091671588728, + "pred_gt_ratio": 0.9778657959761043 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 768, + "gt_variance_6d": 0.12790844637157237, + "pred_variance_6d": 0.10288170460329628, + "pred_gt_ratio": 0.804338630651695 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 768, + "gt_variance_6d": 0.02238697863982246, + "pred_variance_6d": 0.010195848775506838, + "pred_gt_ratio": 0.4554365704968438 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 768, + "gt_variance_6d": 0.04676594210336735, + "pred_variance_6d": 0.023452911831953895, + "pred_gt_ratio": 0.5014955494773446 + } + ] + } + } + } + }, + "normal": { + "hands": 1048, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 588, + "variance": 0.5805831955619537 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 588, + "variance": 0.09545684434321916 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 588, + "variance": 0.10342149802794981 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 588, + "variance": 0.016837883903797677 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 588, + "variance": 0.1476797655526118 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 588, + "variance": 0.04955620383213525 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 588, + "variance": 0.025912651779223927 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 588, + "variance": 0.24556055089965978 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 588, + "variance": 0.04119891892668358 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 588, + "variance": 0.0164697432807629 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 588, + "variance": 0.1619348379212032 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 588, + "variance": 0.0674997817846674 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 588, + "variance": 0.026999770899868276 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 588, + "variance": 0.12062940680660475 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 588, + "variance": 0.017583452877790336 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 588, + "variance": 0.048288454118829933 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 460, + "variance": 0.461866976947212 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 460, + "variance": 0.10221362099003453 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 460, + "variance": 0.06938982404971092 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 460, + "variance": 0.02030802956821813 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 460, + "variance": 0.14881038235534289 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 460, + "variance": 0.07199332698568023 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 460, + "variance": 0.031119814694062903 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 460, + "variance": 0.2741106435761934 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 460, + "variance": 0.048844176402784004 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 460, + "variance": 0.013294943050347847 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 460, + "variance": 0.17726570739539127 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 460, + "variance": 0.06215319041469471 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 460, + "variance": 0.03698108778165434 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 460, + "variance": 0.15541348357880702 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 460, + "variance": 0.024819460131972153 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 460, + "variance": 0.052086190760765684 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 18.31905404438499, + "count": 1048 + }, + "root_relative_mpjpe_mm": { + "mean": 12.423988155053772, + "count": 1048 + }, + "mpvpe_mm": { + "mean": 18.222329692986175, + "count": 1048 + }, + "projected_mano_2d_error_px": { + "mean": 10.15403231887417, + "count": 1048 + }, + "local_pose_angle_deg": { + "mean": 9.367586661158628, + "count": 1048 + }, + "root_relative_fingertip_mm": { + "mean": 18.226285755634308, + "count": 1048 + }, + "distal_angle_bias_deg": { + "mean": 0.4399894580586266, + "count": 1048 + }, + "distal_angle_mae_deg": { + "mean": 5.175950221887982, + "count": 1048 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 7.56776231618328, + 7.1911698061660045, + 6.342933174450207, + 8.56229066655381, + 8.66854335683334, + 7.35023009543883, + 15.501919383538588, + 9.059413234753007, + 5.579491989018808, + 10.339334917887477, + 11.20080159428238, + 7.357912133668215, + 11.370845570989692, + 10.862484712011486, + 13.55865977235309 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.9243729906564595, + "mean_abs_log_variance_ratio": 0.21893051705202235, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 588, + "gt_variance_6d": 0.5805831955619537, + "pred_variance_6d": 0.5512699423350982, + "pred_gt_ratio": 0.9495106757292848 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.09545684434321916, + "pred_variance_6d": 0.07731304079166063, + "pred_gt_ratio": 0.8099266356813377 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.10342149802794981, + "pred_variance_6d": 0.10784832780134071, + "pred_gt_ratio": 1.0428037676672846 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.016837883903797677, + "pred_variance_6d": 0.018916979494777605, + "pred_gt_ratio": 1.1234772494488456 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1476797655526118, + "pred_variance_6d": 0.12707074757425568, + "pred_gt_ratio": 0.8604479232395988 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04955620383213525, + "pred_variance_6d": 0.05839068535484023, + "pred_gt_ratio": 1.1782719586962422 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.025912651779223927, + "pred_variance_6d": 0.023320244599641993, + "pred_gt_ratio": 0.8999559287999827 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.24556055089965978, + "pred_variance_6d": 0.24468979104091515, + "pred_gt_ratio": 0.9964539912638475 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04119891892668358, + "pred_variance_6d": 0.03394700889245278, + "pred_gt_ratio": 0.8239781474087684 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0164697432807629, + "pred_variance_6d": 0.03021817161655333, + "pred_gt_ratio": 1.8347688304194127 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1619348379212032, + "pred_variance_6d": 0.15939605305063304, + "pred_gt_ratio": 0.9843221822854109 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0674997817846674, + "pred_variance_6d": 0.06011637987630464, + "pred_gt_ratio": 0.890615914405224 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.026999770899868276, + "pred_variance_6d": 0.025365962643946936, + "pred_gt_ratio": 0.9394880696587944 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.12062940680660475, + "pred_variance_6d": 0.11230359076467221, + "pred_gt_ratio": 0.9309802123516976 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.017583452877790336, + "pred_variance_6d": 0.01182088538010076, + "pred_gt_ratio": 0.6722732709132302 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.048288454118829933, + "pred_variance_6d": 0.05709530414915664, + "pred_gt_ratio": 1.1823800366160924 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 460, + "gt_variance_6d": 0.461866976947212, + "pred_variance_6d": 0.42406681111879563, + "pred_gt_ratio": 0.9181578945559975 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.10221362099003453, + "pred_variance_6d": 0.08568730666209706, + "pred_gt_ratio": 0.8383159292483267 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06938982404971092, + "pred_variance_6d": 0.06459628924652744, + "pred_gt_ratio": 0.9309187641151909 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.02030802956821813, + "pred_variance_6d": 0.013560268849986575, + "pred_gt_ratio": 0.6677294222187004 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.14881038235534289, + "pred_variance_6d": 0.09701788700621647, + "pred_gt_ratio": 0.6519564392661017 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.07199332698568023, + "pred_variance_6d": 0.06947639363724212, + "pred_gt_ratio": 0.9650393522035905 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.031119814694062903, + "pred_variance_6d": 0.028565300135474612, + "pred_gt_ratio": 0.9179135678119689 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.2741106435761934, + "pred_variance_6d": 0.23287934463717705, + "pred_gt_ratio": 0.8495815470676699 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.048844176402784004, + "pred_variance_6d": 0.030022773061009957, + "pred_gt_ratio": 0.6146643320061945 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.013294943050347847, + "pred_variance_6d": 0.022370049253342253, + "pred_gt_ratio": 1.682598351014145 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.17726570739539127, + "pred_variance_6d": 0.1265019836794805, + "pred_gt_ratio": 0.7136291927987953 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06215319041469471, + "pred_variance_6d": 0.06150551874372194, + "pred_gt_ratio": 0.9895794300075118 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.03698108778165434, + "pred_variance_6d": 0.03378640057561916, + "pred_gt_ratio": 0.9136129465715713 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.15541348357880702, + "pred_variance_6d": 0.12308610361130874, + "pred_gt_ratio": 0.7919911501687321 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.024819460131972153, + "pred_variance_6d": 0.009927300194986359, + "pred_gt_ratio": 0.39998050490220455 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.052086190760765684, + "pred_variance_6d": 0.03201280217114081, + "pred_gt_ratio": 0.6146120824649495 + } + ] + } + }, + "N1_20K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 18.686212306259243, + "count": 1048 + }, + "root_relative_mpjpe_mm": { + "mean": 12.441924038734145, + "count": 1048 + }, + "mpvpe_mm": { + "mean": 18.57875790668808, + "count": 1048 + }, + "projected_mano_2d_error_px": { + "mean": 10.096242474918148, + "count": 1048 + }, + "local_pose_angle_deg": { + "mean": 9.521531695172987, + "count": 1048 + }, + "root_relative_fingertip_mm": { + "mean": 18.281081372999964, + "count": 1048 + }, + "distal_angle_bias_deg": { + "mean": 0.552488960240406, + "count": 1048 + }, + "distal_angle_mae_deg": { + "mean": 5.342725326427977, + "count": 1048 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 7.846336957778185, + 7.357016712427139, + 6.550785685469973, + 8.476100471339949, + 8.932245909442543, + 7.508781891515237, + 15.69416464956207, + 9.04510461422437, + 5.647115494145919, + 10.421168733928495, + 11.711450074067098, + 7.536872205388455, + 11.504383225932376, + 11.007052149936444, + 13.584388903136016 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.3671582618742499, + "recording_bootstrap_95ci": [ + 0.11716613524361569, + 0.6343523884694671 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.017935883680372747, + "recording_bootstrap_95ci": [ + -0.14605647317207548, + 0.17375131161491839 + ], + "count": 1048, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.35642821370190336, + "recording_bootstrap_95ci": [ + 0.10631916033805058, + 0.6250399686493546 + ], + "count": 1048, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": -0.057789843956022775, + "recording_bootstrap_95ci": [ + -0.23655259940231074, + 0.09997098191257202 + ], + "count": 1048, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.1539450340143597, + "recording_bootstrap_95ci": [ + 0.0884103825553762, + 0.22914825784665757 + ], + "count": 1048, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.0547956173656551, + "recording_bootstrap_95ci": [ + -0.16512103489193158, + 0.26935764502982745 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.11249950218177934, + "recording_bootstrap_95ci": [ + -0.03765858811175866, + 0.2648208183258604 + ], + "count": 1048, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": 0.16677510453999497, + "recording_bootstrap_95ci": [ + 0.06583783933917062, + 0.26185659279660883 + ], + "count": 1048, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.9644276016458992, + "mean_abs_log_variance_ratio": 0.2242396268479511, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 588, + "gt_variance_6d": 0.5805831955619537, + "pred_variance_6d": 0.5540856729929342, + "pred_gt_ratio": 0.9543605072079769 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.09545684434321916, + "pred_variance_6d": 0.0781459050718664, + "pred_gt_ratio": 0.8186516703913809 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.10342149802794981, + "pred_variance_6d": 0.11951212747098874, + "pred_gt_ratio": 1.1555830243214078 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.016837883903797677, + "pred_variance_6d": 0.02123753459531262, + "pred_gt_ratio": 1.261294751564514 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1476797655526118, + "pred_variance_6d": 0.12881748981123992, + "pred_gt_ratio": 0.8722758282369287 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04955620383213525, + "pred_variance_6d": 0.06652178001703812, + "pred_gt_ratio": 1.3423501978152201 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.025912651779223927, + "pred_variance_6d": 0.024036922495254957, + "pred_gt_ratio": 0.9276133797517058 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.24556055089965978, + "pred_variance_6d": 0.25393493339068585, + "pred_gt_ratio": 1.0341031263382692 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.04119891892668358, + "pred_variance_6d": 0.033875714392341036, + "pred_gt_ratio": 0.8222476529693726 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0164697432807629, + "pred_variance_6d": 0.031552612972891136, + "pred_gt_ratio": 1.915792640784233 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.1619348379212032, + "pred_variance_6d": 0.16265113072993248, + "pred_gt_ratio": 1.0044233397700242 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.0674997817846674, + "pred_variance_6d": 0.06691833795684439, + "pred_gt_ratio": 0.9913859895180419 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.026999770899868276, + "pred_variance_6d": 0.026190141946607334, + "pred_gt_ratio": 0.9700134880305635 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 588, + "gt_variance_6d": 0.12062940680660475, + "pred_variance_6d": 0.1144472484726664, + "pred_gt_ratio": 0.9487508187464628 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 588, + "gt_variance_6d": 0.017583452877790336, + "pred_variance_6d": 0.011290022616628672, + "pred_gt_ratio": 0.6420822289624981 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 588, + "gt_variance_6d": 0.048288454118829933, + "pred_variance_6d": 0.05433970175470272, + "pred_gt_ratio": 1.1253145859874012 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 460, + "gt_variance_6d": 0.461866976947212, + "pred_variance_6d": 0.4279731753182668, + "pred_gt_ratio": 0.9266156635553985 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.10221362099003453, + "pred_variance_6d": 0.08372207258511932, + "pred_gt_ratio": 0.8190891954926627 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06938982404971092, + "pred_variance_6d": 0.06487094610774291, + "pred_gt_ratio": 0.9348769361523286 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.02030802956821813, + "pred_variance_6d": 0.014061098537229137, + "pred_gt_ratio": 0.6923910805819694 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.14881038235534289, + "pred_variance_6d": 0.0969879555470579, + "pred_gt_ratio": 0.6517553010210086 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.07199332698568023, + "pred_variance_6d": 0.07253703799084703, + "pred_gt_ratio": 1.0075522416858849 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.031119814694062903, + "pred_variance_6d": 0.029162892316412004, + "pred_gt_ratio": 0.9371165157347725 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.2741106435761934, + "pred_variance_6d": 0.23509288124800767, + "pred_gt_ratio": 0.8576568869448511 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.048844176402784004, + "pred_variance_6d": 0.031425768673327636, + "pred_gt_ratio": 0.6433882396579101 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.013294943050347847, + "pred_variance_6d": 0.026652522275313315, + "pred_gt_ratio": 2.004711278143909 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.17726570739539127, + "pred_variance_6d": 0.1279149999042029, + "pred_gt_ratio": 0.7216003692067097 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.06215319041469471, + "pred_variance_6d": 0.0665323714074533, + "pred_gt_ratio": 1.0704578632816768 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.03698108778165434, + "pred_variance_6d": 0.03683843772827413, + "pred_gt_ratio": 0.9961426214874356 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 460, + "gt_variance_6d": 0.15541348357880702, + "pred_variance_6d": 0.1219802717299777, + "pred_gt_ratio": 0.7848757322792008 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 460, + "gt_variance_6d": 0.024819460131972153, + "pred_variance_6d": 0.010386745499280607, + "pred_gt_ratio": 0.4184919995862649 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 460, + "gt_variance_6d": 0.052086190760765684, + "pred_variance_6d": 0.031705806943872886, + "pred_gt_ratio": 0.6087180974607865 + } + ] + } + } + } + }, + "hard": { + "hands": 488, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 180, + "variance": 0.7216755774104807 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 180, + "variance": 0.08869835021167637 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 180, + "variance": 0.08626865914916154 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 180, + "variance": 0.03914948525409978 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 180, + "variance": 0.10062364842175701 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 180, + "variance": 0.07594666645089979 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 180, + "variance": 0.03251117276277506 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 180, + "variance": 0.19387960847459368 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 180, + "variance": 0.06605427950664242 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 180, + "variance": 0.059160565093287786 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 180, + "variance": 0.14626557141486912 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 180, + "variance": 0.08307399865880341 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 180, + "variance": 0.0407806635414321 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 180, + "variance": 0.06031602038668906 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 180, + "variance": 0.03414197666792314 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 180, + "variance": 0.03953256416902763 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 308, + "variance": 0.9011416865350345 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 308, + "variance": 0.1071358232161539 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 308, + "variance": 0.13066771667467203 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 308, + "variance": 0.04031062797161822 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 308, + "variance": 0.2612633704123083 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 308, + "variance": 0.07176775645359448 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 308, + "variance": 0.09187937080523265 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 308, + "variance": 0.3264421614740461 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 308, + "variance": 0.09882061809099224 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 308, + "variance": 0.1582634435437344 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 308, + "variance": 0.26351325961149585 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 308, + "variance": 0.0809051766964645 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 308, + "variance": 0.1240315561135563 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 308, + "variance": 0.05921969686286878 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 308, + "variance": 0.016878418295302018 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 308, + "variance": 0.0387037224391419 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 25.59522438733304, + "count": 488 + }, + "root_relative_mpjpe_mm": { + "mean": 15.127890355274326, + "count": 488 + }, + "mpvpe_mm": { + "mean": 25.277604851566377, + "count": 488 + }, + "projected_mano_2d_error_px": { + "mean": 12.167142165977447, + "count": 488 + }, + "local_pose_angle_deg": { + "mean": 11.43315220172288, + "count": 488 + }, + "root_relative_fingertip_mm": { + "mean": 21.215996558548973, + "count": 488 + }, + "distal_angle_bias_deg": { + "mean": -3.9552774101984305, + "count": 488 + }, + "distal_angle_mae_deg": { + "mean": 8.878255838742021, + "count": 488 + }, + "gt60_angle_bias_deg": { + "mean": -14.813732662861296, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 9.348731926718695, + 10.608943892062687, + 7.179759758478794, + 10.751097362061016, + 12.124442968883963, + 9.097395829917467, + 18.959116924248757, + 12.583606057968296, + 10.375452748637219, + 13.360127430470264, + 13.711780276943426, + 8.68451625658352, + 11.140735293204179, + 10.720286164982397, + 12.851281525536638 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8616982693103896, + "mean_abs_log_variance_ratio": 0.3039490382780567, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 180, + "gt_variance_6d": 0.7216755774104807, + "pred_variance_6d": 0.6602914961708598, + "pred_gt_ratio": 0.9149422771657598 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08869835021167637, + "pred_variance_6d": 0.05729236246274447, + "pred_gt_ratio": 0.6459236538900407 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08626865914916154, + "pred_variance_6d": 0.07674431349748913, + "pred_gt_ratio": 0.889596688465918 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03914948525409978, + "pred_variance_6d": 0.024057707084520343, + "pred_gt_ratio": 0.6145088991176708 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.10062364842175701, + "pred_variance_6d": 0.07487426215658266, + "pred_gt_ratio": 0.7441020409312968 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.07594666645089979, + "pred_variance_6d": 0.05943591055826371, + "pred_gt_ratio": 0.7826006503746885 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03251117276277506, + "pred_variance_6d": 0.027577101318646994, + "pred_gt_ratio": 0.8482345906088775 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.19387960847459368, + "pred_variance_6d": 0.13036676121347474, + "pred_gt_ratio": 0.6724108958088711 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06605427950664242, + "pred_variance_6d": 0.043537454409440915, + "pred_gt_ratio": 0.6591163318201478 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.059160565093287786, + "pred_variance_6d": 0.05392171919912529, + "pred_gt_ratio": 0.9114469936874068 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.14626557141486912, + "pred_variance_6d": 0.10546400706459107, + "pred_gt_ratio": 0.7210446453284068 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08307399865880341, + "pred_variance_6d": 0.06897312640749022, + "pred_gt_ratio": 0.8302613034286762 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.0407806635414321, + "pred_variance_6d": 0.03245732473746683, + "pred_gt_ratio": 0.7958998681934399 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06031602038668906, + "pred_variance_6d": 0.05963676492412365, + "pred_gt_ratio": 0.9887383905932342 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03414197666792314, + "pred_variance_6d": 0.02031252500819574, + "pred_gt_ratio": 0.5949428530680135 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03953256416902763, + "pred_variance_6d": 0.03001231795646963, + "pred_gt_ratio": 0.7591796430949252 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 308, + "gt_variance_6d": 0.9011416865350345, + "pred_variance_6d": 0.8645366687445859, + "pred_gt_ratio": 0.9593792870339869 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1071358232161539, + "pred_variance_6d": 0.07291365151684451, + "pred_gt_ratio": 0.6805720937033003 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.13066771667467203, + "pred_variance_6d": 0.14825777177701094, + "pred_gt_ratio": 1.1346166868908676 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.04031062797161822, + "pred_variance_6d": 0.015998617075844032, + "pred_gt_ratio": 0.3968833501454824 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.2612633704123083, + "pred_variance_6d": 0.19005430347044508, + "pred_gt_ratio": 0.727443357905527 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.07176775645359448, + "pred_variance_6d": 0.07556584431457758, + "pred_gt_ratio": 1.052921925508971 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09187937080523265, + "pred_variance_6d": 0.17291228807331643, + "pred_gt_ratio": 1.881948978948263 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.3264421614740461, + "pred_variance_6d": 0.3339098023819352, + "pred_gt_ratio": 1.0228758469009305 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09882061809099224, + "pred_variance_6d": 0.1123893385678086, + "pred_gt_ratio": 1.1373065736577617 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1582634435437344, + "pred_variance_6d": 0.1924653532698692, + "pred_gt_ratio": 1.2161074532457237 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.26351325961149585, + "pred_variance_6d": 0.2608497650605974, + "pred_gt_ratio": 0.9898923699140404 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0809051766964645, + "pred_variance_6d": 0.06424288512754228, + "pred_gt_ratio": 0.7940516015256369 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1240315561135563, + "pred_variance_6d": 0.1751196353401253, + "pred_gt_ratio": 1.4118958177046141 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.05921969686286878, + "pred_variance_6d": 0.058578924672926844, + "pred_gt_ratio": 0.989179745525788 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.016878418295302018, + "pred_variance_6d": 0.009689220908912263, + "pred_gt_ratio": 0.574059769072626 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0387037224391419, + "pred_variance_6d": 0.008989327915634176, + "pred_gt_ratio": 0.23226003467157663 + } + ] + } + }, + "N1_20K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 26.028249982927665, + "count": 488 + }, + "root_relative_mpjpe_mm": { + "mean": 15.148162923875402, + "count": 488 + }, + "mpvpe_mm": { + "mean": 25.70340360481231, + "count": 488 + }, + "projected_mano_2d_error_px": { + "mean": 12.34141445501906, + "count": 488 + }, + "local_pose_angle_deg": { + "mean": 11.558105400351227, + "count": 488 + }, + "root_relative_fingertip_mm": { + "mean": 21.231503472953545, + "count": 488 + }, + "distal_angle_bias_deg": { + "mean": -3.6862209444163274, + "count": 488 + }, + "distal_angle_mae_deg": { + "mean": 8.830389941569235, + "count": 488 + }, + "gt60_angle_bias_deg": { + "mean": -14.295726392444946, + "count": 278 + } + }, + "local_pose_per_joint_mean_deg": [ + 9.62399934522319, + 10.46734537104847, + 7.298460674334745, + 11.202478884429228, + 11.814660763032125, + 9.26475636911441, + 19.725834967782262, + 12.771718010184218, + 10.456050089881069, + 13.865140821601523, + 13.53042521120095, + 8.65478080462237, + 11.31013800558008, + 10.716760519098063, + 12.669022321456769 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.433025595594625, + "recording_bootstrap_95ci": [ + 0.014173075037660028, + 0.9181305651970648 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_mpjpe_mm": { + "delta": 0.02027256860107672, + "recording_bootstrap_95ci": [ + -0.16459600679692085, + 0.2459848600188371 + ], + "count": 488, + "recordings": 12 + }, + "mpvpe_mm": { + "delta": 0.42579875324593214, + "recording_bootstrap_95ci": [ + 0.01390870140927026, + 0.9056145324563389 + ], + "count": 488, + "recordings": 12 + }, + "projected_mano_2d_error_px": { + "delta": 0.17427228904161296, + "recording_bootstrap_95ci": [ + -0.1193802700477094, + 0.5321042892669855 + ], + "count": 488, + "recordings": 12 + }, + "local_pose_angle_deg": { + "delta": 0.12495319862834743, + "recording_bootstrap_95ci": [ + -0.016629487607185012, + 0.2808961424487917 + ], + "count": 488, + "recordings": 12 + }, + "root_relative_fingertip_mm": { + "delta": 0.015506914404572034, + "recording_bootstrap_95ci": [ + -0.34885735195687473, + 0.3890143335420776 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_bias_deg": { + "delta": 0.269056465782103, + "recording_bootstrap_95ci": [ + 0.021135653696074015, + 0.47826952882759216 + ], + "count": 488, + "recordings": 12 + }, + "distal_angle_mae_deg": { + "delta": -0.04786589717278715, + "recording_bootstrap_95ci": [ + -0.2065174705730329, + 0.12656406264247436 + ], + "count": 488, + "recordings": 12 + }, + "gt60_angle_bias_deg": { + "delta": 0.518006270416349, + "recording_bootstrap_95ci": [ + -0.04401248699438105, + 0.9113757994732907 + ], + "count": 278, + "recordings": 12 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.8954279435423965, + "mean_abs_log_variance_ratio": 0.2865702406843881, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 180, + "gt_variance_6d": 0.7216755774104807, + "pred_variance_6d": 0.666037274471622, + "pred_gt_ratio": 0.9229039963656518 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08869835021167637, + "pred_variance_6d": 0.0618648436695876, + "pred_gt_ratio": 0.6974745699547819 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08626865914916154, + "pred_variance_6d": 0.07521802528503951, + "pred_gt_ratio": 0.8719044207582374 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03914948525409978, + "pred_variance_6d": 0.027353576970833328, + "pred_gt_ratio": 0.6986956991463592 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.10062364842175701, + "pred_variance_6d": 0.08357467237363272, + "pred_gt_ratio": 0.8305669063333433 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.07594666645089979, + "pred_variance_6d": 0.06599139789668836, + "pred_gt_ratio": 0.8689176362908884 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03251117276277506, + "pred_variance_6d": 0.02699266712875141, + "pred_gt_ratio": 0.8302581800327338 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.19387960847459368, + "pred_variance_6d": 0.13877088423050582, + "pred_gt_ratio": 0.7157580176808053 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06605427950664242, + "pred_variance_6d": 0.04694895560809436, + "pred_gt_ratio": 0.7107632686141581 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.059160565093287786, + "pred_variance_6d": 0.05676806849904683, + "pred_gt_ratio": 0.9595592673858282 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.14626557141486912, + "pred_variance_6d": 0.10895365155518272, + "pred_gt_ratio": 0.7449029221384266 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.08307399865880341, + "pred_variance_6d": 0.07551845852940789, + "pred_gt_ratio": 0.9090504820837241 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.0407806635414321, + "pred_variance_6d": 0.033295362594946296, + "pred_gt_ratio": 0.8164497510227872 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 180, + "gt_variance_6d": 0.06031602038668906, + "pred_variance_6d": 0.06331043702420364, + "pred_gt_ratio": 1.0496454609955568 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03414197666792314, + "pred_variance_6d": 0.02177129754342498, + "pred_gt_ratio": 0.637669510326841 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 180, + "gt_variance_6d": 0.03953256416902763, + "pred_variance_6d": 0.030635628299758976, + "pred_gt_ratio": 0.7749466533152664 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 308, + "gt_variance_6d": 0.9011416865350345, + "pred_variance_6d": 0.8762828166313509, + "pred_gt_ratio": 0.9724140273664755 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1071358232161539, + "pred_variance_6d": 0.07300946069935312, + "pred_gt_ratio": 0.6814663714493657 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.13066771667467203, + "pred_variance_6d": 0.15238579885631162, + "pred_gt_ratio": 1.1662084770005727 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.04031062797161822, + "pred_variance_6d": 0.01777996160651582, + "pred_gt_ratio": 0.4410737937159967 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.2612633704123083, + "pred_variance_6d": 0.19992287822453988, + "pred_gt_ratio": 0.7652158735801159 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.07176775645359448, + "pred_variance_6d": 0.07719872542460224, + "pred_gt_ratio": 1.0756742197245563 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09187937080523265, + "pred_variance_6d": 0.1793641056894808, + "pred_gt_ratio": 1.9521695035297932 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.3264421614740461, + "pred_variance_6d": 0.35409063007956376, + "pred_gt_ratio": 1.0846963777003293 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.09882061809099224, + "pred_variance_6d": 0.11241479977192093, + "pred_gt_ratio": 1.1375642243849498 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1582634435437344, + "pred_variance_6d": 0.2040172233984079, + "pred_gt_ratio": 1.2890988520796967 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.26351325961149585, + "pred_variance_6d": 0.2748910780027188, + "pred_gt_ratio": 1.0431774037025594 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0809051766964645, + "pred_variance_6d": 0.06410754909974731, + "pred_gt_ratio": 0.7923788281219928 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.1240315561135563, + "pred_variance_6d": 0.18292556772738827, + "pred_gt_ratio": 1.4748308693306398 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 308, + "gt_variance_6d": 0.05921969686286878, + "pred_variance_6d": 0.05786402305798792, + "pred_gt_ratio": 0.9771077213039421 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 308, + "gt_variance_6d": 0.016878418295302018, + "pred_variance_6d": 0.00904774723993061, + "pred_gt_ratio": 0.536054213234482 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 308, + "gt_variance_6d": 0.0387037224391419, + "pred_variance_6d": 0.008712079993088666, + "pred_gt_ratio": 0.22509669468583088 + } + ] + } + } + } + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_hot3d_12k18k.json b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_hot3d_12k18k.json new file mode 100644 index 0000000000000000000000000000000000000000..6e6e40a1aa88835e3e805c74e8f4bcb64bdcec3e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_hot3d_12k18k.json @@ -0,0 +1,6979 @@ +{ + "source": "HOT3D", + "role": "development", + "input_mode": "rgb", + "gt": "source_native_not_refitted", + "clips": 248, + "panel_sha256": "8ae334a8bc87bc6670a31f2edb8b78989c883547d26c86815498d5f89ccb7060", + "parent_checkpoint_sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a", + "checkpoints": { + "U0_parent": { + "path": "/home/wuyifan/unified_mot_u0_depthsafe_20261001/runs/U0/update_0020004.pt", + "sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a" + }, + "N0_12K": { + "path": "/home/wuyifan/u0_normalized6d_20261002/runs/N0_formal/update_0012000.pt", + "sha256": "f6cf83fc77f577153bfaa71c16717fa36b04bf1639f924a27f137925e73a9a00" + }, + "N0_18K": { + "path": "/home/wuyifan/u0_normalized6d_20261002/runs/N0_formal/update_0018000.pt", + "sha256": "3d176e8949c5738c0ae19690e528968071734f439b7a5efb47d27db954a1feea" + }, + "N1_12K": { + "path": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0012000.pt", + "sha256": "ebe561dbf78d6488180c5f5ee0381432bf739e7a0f68961752d28986210d4958" + }, + "N1_18K": { + "path": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0018000.pt", + "sha256": "07ffd4d5463d64e5762f9dfa268d6539bff28c4d4dcf078c85cd7d7f3b17af2b" + } + }, + "hard_definition": "GT >=2 non-thumb distal angles >=45deg OR >=1 >=60deg; complete 21-joint geometry and MANO pose only", + "groups": { + "all": { + "hands": 3573, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1828, + "variance": 0.9078642060833665 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1828, + "variance": 0.16199262882475624 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1828, + "variance": 0.12232570281073116 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1828, + "variance": 0.09439385714932436 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1828, + "variance": 0.18498699394554094 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1828, + "variance": 0.17591510017264494 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1828, + "variance": 0.06181170335264618 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1828, + "variance": 0.48520380553723685 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1828, + "variance": 0.2749259641279063 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1828, + "variance": 0.18181540568994045 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1828, + "variance": 0.2343304679990655 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1828, + "variance": 0.24823855156388863 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1828, + "variance": 0.0652150158232389 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1828, + "variance": 0.13684319564689476 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1828, + "variance": 0.11868189348606356 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1828, + "variance": 0.1759020250807575 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1745, + "variance": 0.9101462201961528 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1745, + "variance": 0.21365722111186325 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1745, + "variance": 0.18926917560471376 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1745, + "variance": 0.14613903441426507 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1745, + "variance": 0.2583566611716799 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1745, + "variance": 0.18678808384059908 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1745, + "variance": 0.07952837254109431 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1745, + "variance": 0.4996390591174059 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1745, + "variance": 0.22379709478908846 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1745, + "variance": 0.14773829719745404 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1745, + "variance": 0.2945443603939768 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1745, + "variance": 0.25151218340149883 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1745, + "variance": 0.07535130472881144 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1745, + "variance": 0.1331221242401221 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1745, + "variance": 0.14755590450729988 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1745, + "variance": 0.19342181043223353 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 53.084679531377134, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 23.920554598005687, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 52.81978568502277, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 14.757412691832531, + "count": 3289 + }, + "local_pose_angle_deg": { + "mean": 14.682485548548428, + "count": 3573 + }, + "root_relative_fingertip_mm": { + "mean": 33.39453798030359, + "count": 3573 + }, + "distal_angle_bias_deg": { + "mean": -3.7865728957627023, + "count": 3573 + }, + "distal_angle_mae_deg": { + "mean": 9.531410505849708, + "count": 3573 + }, + "gt60_angle_bias_deg": { + "mean": -16.777784632594997, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.605053656806206, + 11.723984282673356, + 12.195507196078205, + 14.634379403483724, + 13.33239297474128, + 8.482029535016059, + 24.564950862744592, + 22.43920696165393, + 15.747543460859694, + 15.089280581360867, + 15.62697612436052, + 8.785158222007912, + 13.865488775030691, + 13.054160223282787, + 17.091159332075474 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4343958458640267, + "mean_abs_log_variance_ratio": 0.8740216377821366, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.9078642060833665, + "pred_variance_6d": 0.8042887951052126, + "pred_gt_ratio": 0.8859131021091904 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.16199262882475624, + "pred_variance_6d": 0.0747604773746268, + "pred_gt_ratio": 0.4615054272346104 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.12232570281073116, + "pred_variance_6d": 0.06038014604322044, + "pred_gt_ratio": 0.4936014644170393 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.09439385714932436, + "pred_variance_6d": 0.028883912952377615, + "pred_gt_ratio": 0.3059935659445013 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18498699394554094, + "pred_variance_6d": 0.08105219843476143, + "pred_gt_ratio": 0.4381507948533004 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.17591510017264494, + "pred_variance_6d": 0.06469243479378003, + "pred_gt_ratio": 0.367748048520509 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.06181170335264618, + "pred_variance_6d": 0.022922464507875114, + "pred_gt_ratio": 0.37084343683426085 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.48520380553723685, + "pred_variance_6d": 0.15151880484977442, + "pred_gt_ratio": 0.3122786819077126 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2749259641279063, + "pred_variance_6d": 0.06480237321837296, + "pred_gt_ratio": 0.23570845126953652 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18181540568994045, + "pred_variance_6d": 0.04934338909811801, + "pred_gt_ratio": 0.2713927838560938 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2343304679990655, + "pred_variance_6d": 0.09368009302581219, + "pred_gt_ratio": 0.39977768928531215 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.24823855156388863, + "pred_variance_6d": 0.08742200289825847, + "pred_gt_ratio": 0.3521693240131513 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.0652150158232389, + "pred_variance_6d": 0.029799894763991683, + "pred_gt_ratio": 0.4569483636216908 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.13684319564689476, + "pred_variance_6d": 0.0625655627671026, + "pred_gt_ratio": 0.45720623865394455 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.11868189348606356, + "pred_variance_6d": 0.04694346871602259, + "pred_gt_ratio": 0.39554027440196693 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.1759020250807575, + "pred_variance_6d": 0.08356069207204053, + "pred_gt_ratio": 0.47504110332827265 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.9101462201961528, + "pred_variance_6d": 0.8136453901592792, + "pred_gt_ratio": 0.8939721685422416 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.21365722111186325, + "pred_variance_6d": 0.07500075070355064, + "pred_gt_ratio": 0.35103307210142426 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18926917560471376, + "pred_variance_6d": 0.10093387514506906, + "pred_gt_ratio": 0.5332821618870902 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14613903441426507, + "pred_variance_6d": 0.04628113414184008, + "pred_gt_ratio": 0.31669248621586926 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2583566611716799, + "pred_variance_6d": 0.10523412114742274, + "pred_gt_ratio": 0.40732110668319055 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18678808384059908, + "pred_variance_6d": 0.07856990270908476, + "pred_gt_ratio": 0.42063659037337 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07952837254109431, + "pred_variance_6d": 0.031398711856016524, + "pred_gt_ratio": 0.39481144719505007 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.4996390591174059, + "pred_variance_6d": 0.2465414057407459, + "pred_gt_ratio": 0.4934390161094536 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.22379709478908846, + "pred_variance_6d": 0.07770255708800353, + "pred_gt_ratio": 0.347200919481248 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14773829719745404, + "pred_variance_6d": 0.054410020925465735, + "pred_gt_ratio": 0.3682865036189369 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2945443603939768, + "pred_variance_6d": 0.1308624652318437, + "pred_gt_ratio": 0.44428779779319016 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.25151218340149883, + "pred_variance_6d": 0.0931492261494454, + "pred_gt_ratio": 0.3703567154866117 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07535130472881144, + "pred_variance_6d": 0.035251945545125986, + "pred_gt_ratio": 0.4678345739598985 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.1331221242401221, + "pred_variance_6d": 0.07388720259227816, + "pred_gt_ratio": 0.555033229931055 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14755590450729988, + "pred_variance_6d": 0.05616968985416318, + "pred_gt_ratio": 0.3806671785972777 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.19342181043223353, + "pred_variance_6d": 0.09206749539887747, + "pred_gt_ratio": 0.4759933494218526 + } + ] + } + }, + "N0_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 53.6687995050923, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 24.242661347750886, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 53.453593921367776, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 14.673273956206621, + "count": 3289 + }, + "local_pose_angle_deg": { + "mean": 14.67510268590112, + "count": 3573 + }, + "root_relative_fingertip_mm": { + "mean": 33.6958702528073, + "count": 3573 + }, + "distal_angle_bias_deg": { + "mean": -3.130469047803022, + "count": 3573 + }, + "distal_angle_mae_deg": { + "mean": 9.449974857639805, + "count": 3573 + }, + "gt60_angle_bias_deg": { + "mean": -16.340660139886282, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.87766413055329, + 11.757132948696063, + 12.180688636862795, + 14.696145578055297, + 13.359659369272777, + 8.272452247520638, + 24.712594896346424, + 22.522483466787897, + 15.618091248995512, + 15.094675528612786, + 15.539190823970774, + 8.53502139138001, + 13.80006165013005, + 13.107228372399293, + 17.05343818988181 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.5841199737151664, + "recording_bootstrap_95ci": [ + 0.12851199841736027, + 1.0141727269238927 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.3221067497452, + "recording_bootstrap_95ci": [ + 0.022047793195198225, + 0.5853719410074225 + ], + "count": 3573, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": 0.6338082363450024, + "recording_bootstrap_95ci": [ + 0.16885769433724837, + 1.062990634585146 + ], + "count": 3573, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.08413873562590987, + "recording_bootstrap_95ci": [ + -0.2995164133064696, + 0.16077902883782788 + ], + "count": 3289, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": -0.0073828626473077434, + "recording_bootstrap_95ci": [ + -0.07916822772282085, + 0.061489467674725226 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": 0.30133227250371164, + "recording_bootstrap_95ci": [ + -0.13510180604741617, + 0.6671670899854245 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 0.6561038479596801, + "recording_bootstrap_95ci": [ + 0.4918015837787862, + 0.8170442529793809 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.08143564820990254, + "recording_bootstrap_95ci": [ + -0.16958925937007044, + 0.011341384047240576 + ], + "count": 3573, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 0.4371244927087138, + "recording_bootstrap_95ci": [ + 0.18717554678883475, + 0.7015187273606427 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4507052956099822, + "mean_abs_log_variance_ratio": 0.8348236932995892, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.9078642060833665, + "pred_variance_6d": 0.7882500889147969, + "pred_gt_ratio": 0.8682466867103407 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.16199262882475624, + "pred_variance_6d": 0.07678427916302294, + "pred_gt_ratio": 0.47399859931952976 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.12232570281073116, + "pred_variance_6d": 0.0602970300660101, + "pred_gt_ratio": 0.4929219998785119 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.09439385714932436, + "pred_variance_6d": 0.03214566186932561, + "pred_gt_ratio": 0.3405482394736075 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18498699394554094, + "pred_variance_6d": 0.08208979559165644, + "pred_gt_ratio": 0.44375982246526574 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.17591510017264494, + "pred_variance_6d": 0.06128194638656797, + "pred_gt_ratio": 0.34836092141280206 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.06181170335264618, + "pred_variance_6d": 0.023731544458901896, + "pred_gt_ratio": 0.383932866620896 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.48520380553723685, + "pred_variance_6d": 0.15507382127407487, + "pred_gt_ratio": 0.3196055338073266 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2749259641279063, + "pred_variance_6d": 0.0655273346333358, + "pred_gt_ratio": 0.23834538451541054 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18181540568994045, + "pred_variance_6d": 0.051901401139229954, + "pred_gt_ratio": 0.2854620649019159 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2343304679990655, + "pred_variance_6d": 0.09464926963219661, + "pred_gt_ratio": 0.403913628647616 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.24823855156388863, + "pred_variance_6d": 0.08786090339958591, + "pred_gt_ratio": 0.3539373834002304 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.0652150158232389, + "pred_variance_6d": 0.03142184118014181, + "pred_gt_ratio": 0.4818191145626444 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.13684319564689476, + "pred_variance_6d": 0.06373678394825295, + "pred_gt_ratio": 0.46576509447146386 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.11868189348606356, + "pred_variance_6d": 0.04967057720361933, + "pred_gt_ratio": 0.4185185772204754 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.1759020250807575, + "pred_variance_6d": 0.08927198995683677, + "pred_gt_ratio": 0.5075097339888586 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.9101462201961528, + "pred_variance_6d": 0.8366376712012707, + "pred_gt_ratio": 0.9192343522790881 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.21365722111186325, + "pred_variance_6d": 0.0728685594367592, + "pred_gt_ratio": 0.34105357664746483 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18926917560471376, + "pred_variance_6d": 0.0996697469470646, + "pred_gt_ratio": 0.5266031651938062 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14613903441426507, + "pred_variance_6d": 0.04861358452747731, + "pred_gt_ratio": 0.33265297476696615 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2583566611716799, + "pred_variance_6d": 0.10587788464925182, + "pred_gt_ratio": 0.40981286942276746 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18678808384059908, + "pred_variance_6d": 0.0838715738579741, + "pred_gt_ratio": 0.4490199381752226 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07952837254109431, + "pred_variance_6d": 0.034994089673663104, + "pred_gt_ratio": 0.4400201909775128 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.4996390591174059, + "pred_variance_6d": 0.2414956741795244, + "pred_gt_ratio": 0.48334026288120396 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.22379709478908846, + "pred_variance_6d": 0.08232601786667754, + "pred_gt_ratio": 0.3678600830107445 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14773829719745404, + "pred_variance_6d": 0.06288948853574364, + "pred_gt_ratio": 0.42568169343180573 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2945443603939768, + "pred_variance_6d": 0.13424607688951168, + "pred_gt_ratio": 0.4557754109090622 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.25151218340149883, + "pred_variance_6d": 0.10933044538124839, + "pred_gt_ratio": 0.43469244273833 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07535130472881144, + "pred_variance_6d": 0.04064322392855499, + "pred_gt_ratio": 0.5393831477083181 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.1331221242401221, + "pred_variance_6d": 0.0750277647767607, + "pred_gt_ratio": 0.5636010182757273 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14755590450729988, + "pred_variance_6d": 0.05928016267408312, + "pred_gt_ratio": 0.40174714032640024 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.19342181043223353, + "pred_variance_6d": 0.0977641916882555, + "pred_gt_ratio": 0.5054455413781155 + } + ] + } + }, + "N0_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 52.76832860983489, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 23.971199686641356, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 52.52736832839983, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 14.511260873171723, + "count": 3289 + }, + "local_pose_angle_deg": { + "mean": 14.69897778575373, + "count": 3573 + }, + "root_relative_fingertip_mm": { + "mean": 33.4543341451955, + "count": 3573 + }, + "distal_angle_bias_deg": { + "mean": -3.4037813822862115, + "count": 3573 + }, + "distal_angle_mae_deg": { + "mean": 9.480567150378874, + "count": 3573 + }, + "gt60_angle_bias_deg": { + "mean": -16.336611252262067, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.705435235127327, + 11.62349304194014, + 12.011858868492174, + 14.487847709702471, + 13.432090696594877, + 8.338318296909133, + 25.038714071498543, + 22.69188657347942, + 15.6719136701523, + 15.081043294671868, + 15.602183313170235, + 8.650654993636449, + 13.928847595686475, + 13.158277536169207, + 17.06209024349882 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.3163509215422448, + "recording_bootstrap_95ci": [ + -0.8913270478566915, + 0.18358062602141176 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.050645088635670715, + "recording_bootstrap_95ci": [ + -0.23949778244495898, + 0.2991719869291754 + ], + "count": 3573, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -0.2924173566229431, + "recording_bootstrap_95ci": [ + -0.8616300759365234, + 0.20569310502211602 + ], + "count": 3573, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.24615181866080682, + "recording_bootstrap_95ci": [ + -0.3911536696458954, + -0.09151917672500694 + ], + "count": 3289, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": 0.016492237205302518, + "recording_bootstrap_95ci": [ + -0.056225948876795814, + 0.08682973959560154 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": 0.05979616489191533, + "recording_bootstrap_95ci": [ + -0.3470283521395565, + 0.42291713003736303 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 0.38279151347649054, + "recording_bootstrap_95ci": [ + 0.24536967404541096, + 0.5208841175462293 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.050843355470834045, + "recording_bootstrap_95ci": [ + -0.12344175485400291, + 0.01931018007789796 + ], + "count": 3573, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 0.44117338033292886, + "recording_bootstrap_95ci": [ + 0.17956424138586755, + 0.6860260023735127 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.45172993828931024, + "mean_abs_log_variance_ratio": 0.8336607213947893, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.9078642060833665, + "pred_variance_6d": 0.8003205473654742, + "pred_gt_ratio": 0.8815421315244398 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.16199262882475624, + "pred_variance_6d": 0.07632986226962475, + "pred_gt_ratio": 0.471193429129411 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.12232570281073116, + "pred_variance_6d": 0.06157722243447187, + "pred_gt_ratio": 0.5033874404118277 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.09439385714932436, + "pred_variance_6d": 0.03248261975280696, + "pred_gt_ratio": 0.34411794086792924 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18498699394554094, + "pred_variance_6d": 0.08024879424451037, + "pred_gt_ratio": 0.4338077641725187 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.17591510017264494, + "pred_variance_6d": 0.06324560753802569, + "pred_gt_ratio": 0.3595234716971754 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.06181170335264618, + "pred_variance_6d": 0.02373509390029941, + "pred_gt_ratio": 0.38399029007317115 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.48520380553723685, + "pred_variance_6d": 0.14837838565684688, + "pred_gt_ratio": 0.3058063105926312 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2749259641279063, + "pred_variance_6d": 0.06484462823015184, + "pred_gt_ratio": 0.23586214723605947 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18181540568994045, + "pred_variance_6d": 0.05095542522441772, + "pred_gt_ratio": 0.2802591179281845 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2343304679990655, + "pred_variance_6d": 0.09093429143427595, + "pred_gt_ratio": 0.3880600427710433 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.24823855156388863, + "pred_variance_6d": 0.08805350888834579, + "pred_gt_ratio": 0.35471327210706693 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.0652150158232389, + "pred_variance_6d": 0.031224605389476363, + "pred_gt_ratio": 0.47879472227851094 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.13684319564689476, + "pred_variance_6d": 0.06483658112941357, + "pred_gt_ratio": 0.47380200983259363 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.11868189348606356, + "pred_variance_6d": 0.050226983769624006, + "pred_gt_ratio": 0.42320679502406156 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.1759020250807575, + "pred_variance_6d": 0.09033295954263937, + "pred_gt_ratio": 0.5135413279134624 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.9101462201961528, + "pred_variance_6d": 0.8319451350679188, + "pred_gt_ratio": 0.9140785476081192 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.21365722111186325, + "pred_variance_6d": 0.07785968570996996, + "pred_gt_ratio": 0.3644140146763653 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18926917560471376, + "pred_variance_6d": 0.10384520646762374, + "pred_gt_ratio": 0.5486641241810188 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14613903441426507, + "pred_variance_6d": 0.04991084316699492, + "pred_gt_ratio": 0.3415298545459869 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2583566611716799, + "pred_variance_6d": 0.10991624589241515, + "pred_gt_ratio": 0.42544382402966185 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18678808384059908, + "pred_variance_6d": 0.08415711890634867, + "pred_gt_ratio": 0.4505486494425765 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07952837254109431, + "pred_variance_6d": 0.03310909164090335, + "pred_gt_ratio": 0.4163179829160348 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.4996390591174059, + "pred_variance_6d": 0.24595886519103002, + "pred_gt_ratio": 0.4922730933516434 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.22379709478908846, + "pred_variance_6d": 0.07836435952879608, + "pred_gt_ratio": 0.35015807333266974 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14773829719745404, + "pred_variance_6d": 0.05995668351783951, + "pred_gt_ratio": 0.40583034091496717 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2945443603939768, + "pred_variance_6d": 0.1370250758910478, + "pred_gt_ratio": 0.4652103191103904 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.25151218340149883, + "pred_variance_6d": 0.1062774804146852, + "pred_gt_ratio": 0.4225540050480587 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07535130472881144, + "pred_variance_6d": 0.03860228619968903, + "pred_gt_ratio": 0.5122975154659665 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.1331221242401221, + "pred_variance_6d": 0.07726685223623805, + "pred_gt_ratio": 0.5804208179315573 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14755590450729988, + "pred_variance_6d": 0.061518918667567674, + "pred_gt_ratio": 0.4169193965702959 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.19342181043223353, + "pred_variance_6d": 0.10001633938762916, + "pred_gt_ratio": 0.5170892525725297 + } + ] + } + }, + "N1_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 53.596443848619266, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 24.22970881169829, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 53.37928224857735, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 14.64424303368835, + "count": 3289 + }, + "local_pose_angle_deg": { + "mean": 14.648704701433521, + "count": 3573 + }, + "root_relative_fingertip_mm": { + "mean": 33.69622544831266, + "count": 3573 + }, + "distal_angle_bias_deg": { + "mean": -2.2543093241999337, + "count": 3573 + }, + "distal_angle_mae_deg": { + "mean": 9.424847361422906, + "count": 3573 + }, + "gt60_angle_bias_deg": { + "mean": -15.333011264985888, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.934995924954384, + 11.720856873087612, + 12.043772847436237, + 14.69468190314354, + 13.159118397877124, + 8.129475131293088, + 24.836863099677938, + 22.522107106295415, + 15.5628725557043, + 15.140033406651456, + 15.561415158230952, + 8.449152564396886, + 13.781994172197546, + 13.10781989005344, + 17.085399712955386 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.511764317242131, + "recording_bootstrap_95ci": [ + 0.036741264565445936, + 0.9458145485971456 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.3091542136926061, + "recording_bootstrap_95ci": [ + 0.0019978166076115036, + 0.5775576561963969 + ], + "count": 3573, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": 0.5594965635545774, + "recording_bootstrap_95ci": [ + 0.07935964687297703, + 0.9946529116229478 + ], + "count": 3573, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.11316965814418219, + "recording_bootstrap_95ci": [ + -0.31274411761313986, + 0.10813984516331138 + ], + "count": 3289, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": -0.03378084711490677, + "recording_bootstrap_95ci": [ + -0.1312551656177622, + 0.06302134237590767 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": 0.30168746800907115, + "recording_bootstrap_95ci": [ + -0.1733948878436171, + 0.6972574090141753 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 1.5322635715627684, + "recording_bootstrap_95ci": [ + 1.3267425906871315, + 1.7283623661360172 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.10656314442680224, + "recording_bootstrap_95ci": [ + -0.25486005346883034, + 0.059159566090778645 + ], + "count": 3573, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 1.4447733676091077, + "recording_bootstrap_95ci": [ + 1.1111775147446636, + 1.8132244463954068 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4539291277136584, + "mean_abs_log_variance_ratio": 0.8271301219690258, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.9078642060833665, + "pred_variance_6d": 0.7875137606657708, + "pred_gt_ratio": 0.8674356312197815 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.16199262882475624, + "pred_variance_6d": 0.07628788093343519, + "pred_gt_ratio": 0.47093427328698695 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.12232570281073116, + "pred_variance_6d": 0.06078057825305897, + "pred_gt_ratio": 0.4968749564194364 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.09439385714932436, + "pred_variance_6d": 0.03222152260788376, + "pred_gt_ratio": 0.3413519012885723 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18498699394554094, + "pred_variance_6d": 0.08112490614813818, + "pred_gt_ratio": 0.4385438371522533 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.17591510017264494, + "pred_variance_6d": 0.06324616425062493, + "pred_gt_ratio": 0.3595266363635326 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.06181170335264618, + "pred_variance_6d": 0.024673194173297722, + "pred_gt_ratio": 0.3991670320510825 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.48520380553723685, + "pred_variance_6d": 0.15339054566344498, + "pred_gt_ratio": 0.3161363202697986 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2749259641279063, + "pred_variance_6d": 0.06554686359573927, + "pred_gt_ratio": 0.23841641804789418 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18181540568994045, + "pred_variance_6d": 0.05242665249894478, + "pred_gt_ratio": 0.28835099149051624 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2343304679990655, + "pred_variance_6d": 0.0935025582183226, + "pred_gt_ratio": 0.3990200634886944 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.24823855156388863, + "pred_variance_6d": 0.08907995707320793, + "pred_gt_ratio": 0.35884819868634144 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.0652150158232389, + "pred_variance_6d": 0.032354536861253023, + "pred_gt_ratio": 0.49612096927106347 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.13684319564689476, + "pred_variance_6d": 0.06341997045747591, + "pred_gt_ratio": 0.46344993740954804 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.11868189348606356, + "pred_variance_6d": 0.04900278709889225, + "pred_gt_ratio": 0.4128918545156721 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.1759020250807575, + "pred_variance_6d": 0.08929204877249623, + "pred_gt_ratio": 0.5076237680123455 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.9101462201961528, + "pred_variance_6d": 0.8350726521011597, + "pred_gt_ratio": 0.9175148273660759 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.21365722111186325, + "pred_variance_6d": 0.07302481602066468, + "pred_gt_ratio": 0.34178491904297265 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18926917560471376, + "pred_variance_6d": 0.10105031239108725, + "pred_gt_ratio": 0.5338973558067878 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14613903441426507, + "pred_variance_6d": 0.04917270123951209, + "pred_gt_ratio": 0.3364788978974682 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2583566611716799, + "pred_variance_6d": 0.10696713785031431, + "pred_gt_ratio": 0.4140289527090376 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18678808384059908, + "pred_variance_6d": 0.0859258775473977, + "pred_gt_ratio": 0.4600179828426581 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07952837254109431, + "pred_variance_6d": 0.03559013526051304, + "pred_gt_ratio": 0.4475149449603375 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.4996390591174059, + "pred_variance_6d": 0.24193378834016147, + "pred_gt_ratio": 0.4842171241926695 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.22379709478908846, + "pred_variance_6d": 0.08444945712765534, + "pred_gt_ratio": 0.37734831726588075 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14773829719745404, + "pred_variance_6d": 0.06408956134013499, + "pred_gt_ratio": 0.4338046569907226 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2945443603939768, + "pred_variance_6d": 0.13472283551490294, + "pred_gt_ratio": 0.4573940418845579 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.25151218340149883, + "pred_variance_6d": 0.11227661556541285, + "pred_gt_ratio": 0.4464062696564534 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07535130472881144, + "pred_variance_6d": 0.04128817762899667, + "pred_gt_ratio": 0.5479424381248924 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.1331221242401221, + "pred_variance_6d": 0.07479454922708598, + "pred_gt_ratio": 0.5618491265371757 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14755590450729988, + "pred_variance_6d": 0.059199257160366045, + "pred_gt_ratio": 0.4011988361837282 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.19342181043223353, + "pred_variance_6d": 0.09857560876008174, + "pred_gt_ratio": 0.5096406064021322 + } + ] + } + }, + "N1_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 52.66985028042968, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 23.959289349263166, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 52.42802933247991, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 14.482651678179854, + "count": 3289 + }, + "local_pose_angle_deg": { + "mean": 14.65414635887541, + "count": 3573 + }, + "root_relative_fingertip_mm": { + "mean": 33.43831804864319, + "count": 3573 + }, + "distal_angle_bias_deg": { + "mean": -2.4109858414671717, + "count": 3573 + }, + "distal_angle_mae_deg": { + "mean": 9.428915324479366, + "count": 3573 + }, + "gt60_angle_bias_deg": { + "mean": -15.204320517150304, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.753974526319857, + 11.570038223025547, + 11.872181727677342, + 14.49032537706286, + 13.163420252733427, + 8.15965464675323, + 25.18220206386997, + 22.654301250277864, + 15.59737625949162, + 15.148656885638278, + 15.566959007544375, + 8.502627221177747, + 13.915806429745802, + 13.144430076478745, + 17.090229923780846 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.4148292509474542, + "recording_bootstrap_95ci": [ + -1.16173022848628, + 0.17238395829478154 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.038734751257481374, + "recording_bootstrap_95ci": [ + -0.2677438258009024, + 0.29340175784703976 + ], + "count": 3573, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -0.39175635254286334, + "recording_bootstrap_95ci": [ + -1.1371015242016778, + 0.1964494203079158 + ], + "count": 3573, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.2747610136526774, + "recording_bootstrap_95ci": [ + -0.47973210971046826, + -0.08327191192575137 + ], + "count": 3289, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": -0.02833918967301726, + "recording_bootstrap_95ci": [ + -0.12276915355299561, + 0.06611900134238342 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": 0.043780068339602206, + "recording_bootstrap_95ci": [ + -0.3877724841182216, + 0.42279528256647037 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 1.3755870542955304, + "recording_bootstrap_95ci": [ + 1.1739723449546033, + 1.571924486318905 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.10249518137034201, + "recording_bootstrap_95ci": [ + -0.24120211704897312, + 0.042201976829466914 + ], + "count": 3573, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 1.573464115444691, + "recording_bootstrap_95ci": [ + 1.2426470795369866, + 1.9121950647213475 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4562992970625652, + "mean_abs_log_variance_ratio": 0.8226170252700622, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.9078642060833665, + "pred_variance_6d": 0.7991742392744894, + "pred_gt_ratio": 0.8802794888480311 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.16199262882475624, + "pred_variance_6d": 0.07589449860214544, + "pred_gt_ratio": 0.4685058767967039 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.12232570281073116, + "pred_variance_6d": 0.061771763729937215, + "pred_gt_ratio": 0.5049777954312168 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.09439385714932436, + "pred_variance_6d": 0.03261314965811978, + "pred_gt_ratio": 0.34550076289951903 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18498699394554094, + "pred_variance_6d": 0.07942638652545009, + "pred_gt_ratio": 0.42936200449223333 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.17591510017264494, + "pred_variance_6d": 0.06530917421070746, + "pred_gt_ratio": 0.37125394094430975 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.06181170335264618, + "pred_variance_6d": 0.024770963808142223, + "pred_gt_ratio": 0.4007487654371811 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.48520380553723685, + "pred_variance_6d": 0.14716815569391403, + "pred_gt_ratio": 0.3033120392181665 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2749259641279063, + "pred_variance_6d": 0.06525043926010127, + "pred_gt_ratio": 0.2373382210992055 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18181540568994045, + "pred_variance_6d": 0.05209673966379422, + "pred_gt_ratio": 0.2865364431913849 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2343304679990655, + "pred_variance_6d": 0.08995590286351686, + "pred_gt_ratio": 0.3838847915580299 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.24823855156388863, + "pred_variance_6d": 0.08967291394567878, + "pred_gt_ratio": 0.36123685616413953 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.0652150158232389, + "pred_variance_6d": 0.0323878179230962, + "pred_gt_ratio": 0.49663129747420903 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.13684319564689476, + "pred_variance_6d": 0.0644208669741047, + "pred_gt_ratio": 0.470764122904101 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.11868189348606356, + "pred_variance_6d": 0.049363504840732514, + "pred_gt_ratio": 0.41593122076813777 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.1759020250807575, + "pred_variance_6d": 0.08991464463393785, + "pred_gt_ratio": 0.51116321482176 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.9101462201961528, + "pred_variance_6d": 0.8313385520005913, + "pred_gt_ratio": 0.9134120798979124 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.21365722111186325, + "pred_variance_6d": 0.07791762749932288, + "pred_gt_ratio": 0.3646852050861787 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18926917560471376, + "pred_variance_6d": 0.10572164421217206, + "pred_gt_ratio": 0.5585782464280943 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14613903441426507, + "pred_variance_6d": 0.050543294628491664, + "pred_gt_ratio": 0.34585759260742716 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2583566611716799, + "pred_variance_6d": 0.11065409503826536, + "pred_gt_ratio": 0.42829975637723117 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18678808384059908, + "pred_variance_6d": 0.08721932300092264, + "pred_gt_ratio": 0.4669426507707725 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07952837254109431, + "pred_variance_6d": 0.03410169604139684, + "pred_gt_ratio": 0.4287991185004526 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.4996390591174059, + "pred_variance_6d": 0.24610233636210263, + "pred_gt_ratio": 0.4925602429818705 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.22379709478908846, + "pred_variance_6d": 0.08138273513686244, + "pred_gt_ratio": 0.3636451814245373 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14773829719745404, + "pred_variance_6d": 0.06201414027812675, + "pred_gt_ratio": 0.41975670123802833 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2945443603939768, + "pred_variance_6d": 0.13707307116245193, + "pred_gt_ratio": 0.4653732666247816 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.25151218340149883, + "pred_variance_6d": 0.11026678661032635, + "pred_gt_ratio": 0.438415289148451 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07535130472881144, + "pred_variance_6d": 0.03979833576295217, + "pred_gt_ratio": 0.5281704929488078 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.1331221242401221, + "pred_variance_6d": 0.07708403628288753, + "pred_gt_ratio": 0.5790475228884225 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14755590450729988, + "pred_variance_6d": 0.06166194688503562, + "pred_gt_ratio": 0.41788871201684163 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.19342181043223353, + "pred_variance_6d": 0.10110517892840934, + "pred_gt_ratio": 0.5227186050139476 + } + ] + } + } + } + }, + "normal": { + "hands": 1039, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 545, + "variance": 1.0827241385159592 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 545, + "variance": 0.12400796906680656 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 545, + "variance": 0.07354481761372055 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 545, + "variance": 0.09381512691794847 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 545, + "variance": 0.1267101769167171 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 545, + "variance": 0.08075673841413365 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 545, + "variance": 0.03143736772576662 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 545, + "variance": 0.4911503904937964 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 545, + "variance": 0.2142312218545364 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 545, + "variance": 0.1355850701279912 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 545, + "variance": 0.186007061146542 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 545, + "variance": 0.1014455657894766 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 545, + "variance": 0.024940999180766 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 545, + "variance": 0.14941141870907892 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 545, + "variance": 0.14445662430848943 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 545, + "variance": 0.18846841823407084 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 494, + "variance": 0.9023800950488734 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 494, + "variance": 0.24763924205574364 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 494, + "variance": 0.09071934710965093 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 494, + "variance": 0.14796302500045028 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 494, + "variance": 0.24470360564125565 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 494, + "variance": 0.07247421520685057 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 494, + "variance": 0.03884170855571756 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 494, + "variance": 0.4407256699754486 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 494, + "variance": 0.14405031509129812 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 494, + "variance": 0.089153279742193 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 494, + "variance": 0.24252463324047752 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 494, + "variance": 0.08484108365834611 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 494, + "variance": 0.03429392078633288 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 494, + "variance": 0.1723511395250014 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 494, + "variance": 0.22195927830866272 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 494, + "variance": 0.24691242579776249 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 49.36649959332904, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 22.758902805831365, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 49.282017397582244, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.629668909727984, + "count": 987 + }, + "local_pose_angle_deg": { + "mean": 14.036746979218703, + "count": 1039 + }, + "root_relative_fingertip_mm": { + "mean": 32.28058153442515, + "count": 1039 + }, + "distal_angle_bias_deg": { + "mean": 1.6770096656734605, + "count": 1039 + }, + "distal_angle_mae_deg": { + "mean": 7.367876557688855, + "count": 1039 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.30436464168913, + 9.918093604119038, + 10.809532189965822, + 14.019094580176706, + 11.310527948431377, + 6.856722158577949, + 25.780867560077333, + 20.266277028116846, + 14.579996284495419, + 14.507325454269957, + 13.45159145056685, + 6.996299121618501, + 15.646021942087271, + 14.79519435944066, + 18.309285134048388 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5455682625815981, + "mean_abs_log_variance_ratio": 0.6860176210996016, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 545, + "gt_variance_6d": 1.0827241385159592, + "pred_variance_6d": 0.8953476791165637, + "pred_gt_ratio": 0.8269397968200617 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.12400796906680656, + "pred_variance_6d": 0.061577646494260396, + "pred_gt_ratio": 0.49656201095501207 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.07354481761372055, + "pred_variance_6d": 0.044875696410129874, + "pred_gt_ratio": 0.6101816262001015 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.09381512691794847, + "pred_variance_6d": 0.03678271075736603, + "pred_gt_ratio": 0.39207654421803967 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1267101769167171, + "pred_variance_6d": 0.06505495228931318, + "pred_gt_ratio": 0.5134153694069254 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.08075673841413365, + "pred_variance_6d": 0.05093717586982474, + "pred_gt_ratio": 0.6307483049725292 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.03143736772576662, + "pred_variance_6d": 0.014867446202436711, + "pred_gt_ratio": 0.4729227437910169 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.4911503904937964, + "pred_variance_6d": 0.16122896152544175, + "pred_gt_ratio": 0.3282680104628324 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.2142312218545364, + "pred_variance_6d": 0.0490300842830636, + "pred_gt_ratio": 0.22886525996829335 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1355850701279912, + "pred_variance_6d": 0.03790609439349878, + "pred_gt_ratio": 0.2795742507468982 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.186007061146542, + "pred_variance_6d": 0.09539841454624765, + "pred_gt_ratio": 0.5128752315004315 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1014455657894766, + "pred_variance_6d": 0.047821377631822794, + "pred_gt_ratio": 0.47139938803302056 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.024940999180766, + "pred_variance_6d": 0.01779235326364683, + "pred_gt_ratio": 0.7133777253546416 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14941141870907892, + "pred_variance_6d": 0.08539608596756264, + "pred_gt_ratio": 0.571549930422912 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14445662430848943, + "pred_variance_6d": 0.06371558106962355, + "pred_gt_ratio": 0.4410706769220767 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.18846841823407084, + "pred_variance_6d": 0.12273475856113308, + "pred_gt_ratio": 0.6512218848714538 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 494, + "gt_variance_6d": 0.9023800950488734, + "pred_variance_6d": 0.7630330607333655, + "pred_gt_ratio": 0.8455783376871131 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24763924205574364, + "pred_variance_6d": 0.07885092639794655, + "pred_gt_ratio": 0.31841046573788656 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.09071934710965093, + "pred_variance_6d": 0.10553963164798777, + "pred_gt_ratio": 1.1633641004980317 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14796302500045028, + "pred_variance_6d": 0.046746211387104296, + "pred_gt_ratio": 0.3159317092020931 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24470360564125565, + "pred_variance_6d": 0.0766063775102613, + "pred_gt_ratio": 0.31305782074404337 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.07247421520685057, + "pred_variance_6d": 0.07195162016417103, + "pred_gt_ratio": 0.9927892279869746 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03884170855571756, + "pred_variance_6d": 0.021323064506233926, + "pred_gt_ratio": 0.5489733922401088 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.4407256699754486, + "pred_variance_6d": 0.21934781502513687, + "pred_gt_ratio": 0.4976969347788524 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14405031509129812, + "pred_variance_6d": 0.06678113866732549, + "pred_gt_ratio": 0.4635959221956582 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.089153279742193, + "pred_variance_6d": 0.04611902559163075, + "pred_gt_ratio": 0.5173003811524871 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24252463324047752, + "pred_variance_6d": 0.1054206529452027, + "pred_gt_ratio": 0.4346801870664902 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.08484108365834611, + "pred_variance_6d": 0.08022340295653962, + "pred_gt_ratio": 0.9455725869744683 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03429392078633288, + "pred_variance_6d": 0.01998335433565871, + "pred_gt_ratio": 0.582708359891665 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.1723511395250014, + "pred_variance_6d": 0.09556248635568798, + "pred_gt_ratio": 0.5544639079211056 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.22195927830866272, + "pred_variance_6d": 0.07726878808860468, + "pred_gt_ratio": 0.3481214602849473 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24691242579776249, + "pred_variance_6d": 0.11725645265227867, + "pred_gt_ratio": 0.47489085360296696 + } + ] + } + }, + "N0_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 49.77466279205161, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 22.883269611520188, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 49.74824411118684, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.857952440884096, + "count": 987 + }, + "local_pose_angle_deg": { + "mean": 14.185077904048622, + "count": 1039 + }, + "root_relative_fingertip_mm": { + "mean": 32.42476382911836, + "count": 1039 + }, + "distal_angle_bias_deg": { + "mean": 2.202987494264461, + "count": 1039 + }, + "distal_angle_mae_deg": { + "mean": 7.542788295130872, + "count": 1039 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.564130369534391, + 9.79067200617336, + 10.73927023900714, + 14.326593344663634, + 11.267904385336324, + 6.891293819574236, + 26.109261122429107, + 21.144814434593062, + 14.866223538690628, + 14.737113832280082, + 13.973207467673946, + 7.0182274191911915, + 15.405608608070994, + 14.678479078472291, + 18.263357433019863 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.4081631987225677, + "recording_bootstrap_95ci": [ + -0.37559731359939325, + 1.0456039020330261 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_mpjpe_mm": { + "delta": 0.12436680568882315, + "recording_bootstrap_95ci": [ + -0.2808623966930899, + 0.4983280315981489 + ], + "count": 1039, + "recordings": 30 + }, + "mpvpe_mm": { + "delta": 0.4662267136046012, + "recording_bootstrap_95ci": [ + -0.3141984765593381, + 1.0809776758069811 + ], + "count": 1039, + "recordings": 30 + }, + "projected_mano_2d_error_px": { + "delta": 0.22828353115611283, + "recording_bootstrap_95ci": [ + -0.28184263418637734, + 0.7864945822826969 + ], + "count": 987, + "recordings": 30 + }, + "local_pose_angle_deg": { + "delta": 0.1483309248299181, + "recording_bootstrap_95ci": [ + 0.025374772015720293, + 0.2872075677936762 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_fingertip_mm": { + "delta": 0.14418229469321345, + "recording_bootstrap_95ci": [ + -0.5500402393314653, + 0.72850193452829 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_bias_deg": { + "delta": 0.5259778285910007, + "recording_bootstrap_95ci": [ + 0.3477922155315267, + 0.715066352838369 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_mae_deg": { + "delta": 0.1749117374420166, + "recording_bootstrap_95ci": [ + 0.04815397561882228, + 0.3253131909780558 + ], + "count": 1039, + "recordings": 30 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5697426932867524, + "mean_abs_log_variance_ratio": 0.6437140703798784, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 545, + "gt_variance_6d": 1.0827241385159592, + "pred_variance_6d": 0.8834070843172194, + "pred_gt_ratio": 0.815911507734616 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.12400796906680656, + "pred_variance_6d": 0.06324209208561772, + "pred_gt_ratio": 0.5099840966796855 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.07354481761372055, + "pred_variance_6d": 0.04721358994148203, + "pred_gt_ratio": 0.6419703178742243 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.09381512691794847, + "pred_variance_6d": 0.041217227984433294, + "pred_gt_ratio": 0.4393452243632548 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1267101769167171, + "pred_variance_6d": 0.06600820692076974, + "pred_gt_ratio": 0.5209384796625689 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.08075673841413365, + "pred_variance_6d": 0.05318874615610418, + "pred_gt_ratio": 0.6586292017310514 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.03143736772576662, + "pred_variance_6d": 0.01700360474790075, + "pred_gt_ratio": 0.5408724068829813 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.4911503904937964, + "pred_variance_6d": 0.17093488865359222, + "pred_gt_ratio": 0.3480296299504851 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.2142312218545364, + "pred_variance_6d": 0.052908450694971125, + "pred_gt_ratio": 0.24696890694530094 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1355850701279912, + "pred_variance_6d": 0.04151530491050566, + "pred_gt_ratio": 0.30619377835122663 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.186007061146542, + "pred_variance_6d": 0.09949869795739211, + "pred_gt_ratio": 0.5349189291206747 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1014455657894766, + "pred_variance_6d": 0.052995772367355025, + "pred_gt_ratio": 0.5224060012374885 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.024940999180766, + "pred_variance_6d": 0.01966080300869809, + "pred_gt_ratio": 0.788292516518749 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14941141870907892, + "pred_variance_6d": 0.08741864328859618, + "pred_gt_ratio": 0.5850867627380625 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14445662430848943, + "pred_variance_6d": 0.06852009126137847, + "pred_gt_ratio": 0.4743298660714424 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.18846841823407084, + "pred_variance_6d": 0.12977793869208287, + "pred_gt_ratio": 0.6885924968654613 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 494, + "gt_variance_6d": 0.9023800950488734, + "pred_variance_6d": 0.7861014515162936, + "pred_gt_ratio": 0.871142277882047 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24763924205574364, + "pred_variance_6d": 0.0725325163669929, + "pred_gt_ratio": 0.2928958906709374 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.09071934710965093, + "pred_variance_6d": 0.09977593713507857, + "pred_gt_ratio": 1.0998308554236076 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14796302500045028, + "pred_variance_6d": 0.05071633253684647, + "pred_gt_ratio": 0.3427635555348516 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24470360564125565, + "pred_variance_6d": 0.07117955000203516, + "pred_gt_ratio": 0.29088067507426496 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.07247421520685057, + "pred_variance_6d": 0.07565865068680938, + "pred_gt_ratio": 1.0439388749622196 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03884170855571756, + "pred_variance_6d": 0.022845222327719104, + "pred_gt_ratio": 0.5881621374854854 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.4407256699754486, + "pred_variance_6d": 0.21275879958328275, + "pred_gt_ratio": 0.48274655659411636 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14405031509129812, + "pred_variance_6d": 0.06901707504512661, + "pred_gt_ratio": 0.47911783463565527 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.089153279742193, + "pred_variance_6d": 0.05013986497718785, + "pred_gt_ratio": 0.562400678047725 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24252463324047752, + "pred_variance_6d": 0.10629520255590533, + "pred_gt_ratio": 0.43828621091246983 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.08484108365834611, + "pred_variance_6d": 0.08863146149754797, + "pred_gt_ratio": 1.0446762072778992 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03429392078633288, + "pred_variance_6d": 0.022262900575494182, + "pred_gt_ratio": 0.6491792150043862 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.1723511395250014, + "pred_variance_6d": 0.09577465059055185, + "pred_gt_ratio": 0.5556949078172976 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.22195927830866272, + "pred_variance_6d": 0.08021804733961921, + "pred_gt_ratio": 0.3614088491856861 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24691242579776249, + "pred_variance_6d": 0.12497999242627789, + "pred_gt_ratio": 0.5061713359401552 + } + ] + } + }, + "N0_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 49.32979851393199, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 22.706149179276878, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 49.264685686788845, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.605750810532342, + "count": 987 + }, + "local_pose_angle_deg": { + "mean": 14.181246055331336, + "count": 1039 + }, + "root_relative_fingertip_mm": { + "mean": 32.208126154395686, + "count": 1039 + }, + "distal_angle_bias_deg": { + "mean": 2.0179482294574624, + "count": 1039 + }, + "distal_angle_mae_deg": { + "mean": 7.48789649955118, + "count": 1039 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.39974305435255, + 9.795112854821735, + 10.703573009678673, + 14.01696637126548, + 11.280274679760616, + 6.926464551710188, + 26.599124932197334, + 21.108590176176634, + 14.898089021415638, + 14.678274414078103, + 13.83709319883866, + 7.0617927643860385, + 15.482608008545332, + 14.69135422541386, + 18.23961820756735 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.0367010793970455, + "recording_bootstrap_95ci": [ + -0.7896657175654441, + 0.631006904116541 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_mpjpe_mm": { + "delta": -0.0527536265544873, + "recording_bootstrap_95ci": [ + -0.44024159566056353, + 0.3040865447362611 + ], + "count": 1039, + "recordings": 30 + }, + "mpvpe_mm": { + "delta": -0.017331710793400637, + "recording_bootstrap_95ci": [ + -0.7654023095905825, + 0.647957804346747 + ], + "count": 1039, + "recordings": 30 + }, + "projected_mano_2d_error_px": { + "delta": -0.02391809919564074, + "recording_bootstrap_95ci": [ + -0.42711669064256014, + 0.3207335589141778 + ], + "count": 987, + "recordings": 30 + }, + "local_pose_angle_deg": { + "delta": 0.14449907611263155, + "recording_bootstrap_95ci": [ + 0.03380648017232297, + 0.2677339849738926 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_fingertip_mm": { + "delta": -0.07245538002946723, + "recording_bootstrap_95ci": [ + -0.732799480811165, + 0.5180874425542376 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_bias_deg": { + "delta": 0.3409385637840018, + "recording_bootstrap_95ci": [ + 0.16669279034788248, + 0.5279699472344443 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_mae_deg": { + "delta": 0.12001994186232477, + "recording_bootstrap_95ci": [ + 0.03159687372835262, + 0.22352468488700974 + ], + "count": 1039, + "recordings": 30 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5752931739174655, + "mean_abs_log_variance_ratio": 0.634991455578432, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 545, + "gt_variance_6d": 1.0827241385159592, + "pred_variance_6d": 0.8932314789436501, + "pred_gt_ratio": 0.824985282186432 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.12400796906680656, + "pred_variance_6d": 0.06299620844628784, + "pred_gt_ratio": 0.5080012915327242 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.07354481761372055, + "pred_variance_6d": 0.047681187156900055, + "pred_gt_ratio": 0.648328307880726 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.09381512691794847, + "pred_variance_6d": 0.04170583487088887, + "pred_gt_ratio": 0.4445534130904621 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1267101769167171, + "pred_variance_6d": 0.06468128507995902, + "pred_gt_ratio": 0.5104663781068836 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.08075673841413365, + "pred_variance_6d": 0.05485321261464401, + "pred_gt_ratio": 0.6792400695202404 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.03143736772576662, + "pred_variance_6d": 0.01728896859068558, + "pred_gt_ratio": 0.5499496249654272 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.4911503904937964, + "pred_variance_6d": 0.16394619371005542, + "pred_gt_ratio": 0.33380039369453823 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.2142312218545364, + "pred_variance_6d": 0.052671867353959116, + "pred_gt_ratio": 0.2458645705233547 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1355850701279912, + "pred_variance_6d": 0.04149022236342496, + "pred_gt_ratio": 0.3060087834468686 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.186007061146542, + "pred_variance_6d": 0.09616536274951448, + "pred_gt_ratio": 0.516998452406882 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1014455657894766, + "pred_variance_6d": 0.05345087563651098, + "pred_gt_ratio": 0.5268921832170971 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.024940999180766, + "pred_variance_6d": 0.02001313932930393, + "pred_gt_ratio": 0.8024193090362499 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14941141870907892, + "pred_variance_6d": 0.08849953547785899, + "pred_gt_ratio": 0.5923210972929565 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14445662430848943, + "pred_variance_6d": 0.06914497220192037, + "pred_gt_ratio": 0.47865560013544395 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.18846841823407084, + "pred_variance_6d": 0.1311928039223748, + "pred_gt_ratio": 0.6960996709774375 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 494, + "gt_variance_6d": 0.9023800950488734, + "pred_variance_6d": 0.7794574217023271, + "pred_gt_ratio": 0.8637794937842809 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24763924205574364, + "pred_variance_6d": 0.07987829761127323, + "pred_gt_ratio": 0.3225591265268556 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.09071934710965093, + "pred_variance_6d": 0.10462351723893254, + "pred_gt_ratio": 1.1532657649362916 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14796302500045028, + "pred_variance_6d": 0.05242285672871482, + "pred_gt_ratio": 0.35429700581314344 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24470360564125565, + "pred_variance_6d": 0.07678260422853408, + "pred_gt_ratio": 0.3137779847065276 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.07247421520685057, + "pred_variance_6d": 0.07555765415971595, + "pred_gt_ratio": 1.0425453237963993 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03884170855571756, + "pred_variance_6d": 0.021973631684979223, + "pred_gt_ratio": 0.565722582812199 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.4407256699754486, + "pred_variance_6d": 0.21908922250646232, + "pred_gt_ratio": 0.49711019219431235 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14405031509129812, + "pred_variance_6d": 0.06798458860646764, + "pred_gt_ratio": 0.47195029433555535 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.089153279742193, + "pred_variance_6d": 0.0494313031273014, + "pred_gt_ratio": 0.554452996796565 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24252463324047752, + "pred_variance_6d": 0.10990883880595154, + "pred_gt_ratio": 0.45318629014055833 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.08484108365834611, + "pred_variance_6d": 0.08812590862562733, + "pred_gt_ratio": 1.0387173857951788 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03429392078633288, + "pred_variance_6d": 0.021777354158423027, + "pred_gt_ratio": 0.635020833403859 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.1723511395250014, + "pred_variance_6d": 0.09982176557336424, + "pred_gt_ratio": 0.5791767077866289 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.22195927830866272, + "pred_variance_6d": 0.08420728394182178, + "pred_gt_ratio": 0.37938168020496443 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24691242579776249, + "pred_variance_6d": 0.12835828240173486, + "pred_gt_ratio": 0.5198534743118547 + } + ] + } + }, + "N1_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 49.81385734611342, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 22.981300611468434, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 49.779304128982794, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.858797999983985, + "count": 987 + }, + "local_pose_angle_deg": { + "mean": 14.446404248504711, + "count": 1039 + }, + "root_relative_fingertip_mm": { + "mean": 32.669869810256735, + "count": 1039 + }, + "distal_angle_bias_deg": { + "mean": 3.03594101037511, + "count": 1039 + }, + "distal_angle_mae_deg": { + "mean": 7.918885076241039, + "count": 1039 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.638795180631671, + 10.068037145176797, + 10.772064477061859, + 14.375822072079597, + 11.748996224365518, + 7.105962404904168, + 26.390422632421178, + 21.814587987421568, + 15.196907539397507, + 14.87397623830856, + 14.940613708436432, + 7.244392475046942, + 15.427445398143442, + 14.744844535718869, + 18.353184634699513 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.4473577527843839, + "recording_bootstrap_95ci": [ + -0.3397525712419928, + 1.0988641666784624 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_mpjpe_mm": { + "delta": 0.22239780563706957, + "recording_bootstrap_95ci": [ + -0.16816912147423838, + 0.5692856782294079 + ], + "count": 1039, + "recordings": 30 + }, + "mpvpe_mm": { + "delta": 0.49728673140054946, + "recording_bootstrap_95ci": [ + -0.28513195618638343, + 1.1173356996302097 + ], + "count": 1039, + "recordings": 30 + }, + "projected_mano_2d_error_px": { + "delta": 0.22912909025600012, + "recording_bootstrap_95ci": [ + -0.2938673337301831, + 0.8062805602951865 + ], + "count": 987, + "recordings": 30 + }, + "local_pose_angle_deg": { + "delta": 0.40965726928600793, + "recording_bootstrap_95ci": [ + 0.24604700423026254, + 0.5940695582323119 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_fingertip_mm": { + "delta": 0.38928827583158787, + "recording_bootstrap_95ci": [ + -0.2854007407611562, + 0.9438138030931805 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_bias_deg": { + "delta": 1.3589313447016496, + "recording_bootstrap_95ci": [ + 1.1155654519957996, + 1.6207507320317687 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_mae_deg": { + "delta": 0.5510085185521836, + "recording_bootstrap_95ci": [ + 0.34108680962011134, + 0.8003952646606655 + ], + "count": 1039, + "recordings": 30 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5881504481289561, + "mean_abs_log_variance_ratio": 0.6311665446163006, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 545, + "gt_variance_6d": 1.0827241385159592, + "pred_variance_6d": 0.8813869316892305, + "pred_gt_ratio": 0.8140457022573706 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.12400796906680656, + "pred_variance_6d": 0.06349601564887222, + "pred_gt_ratio": 0.5120317357561525 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.07354481761372055, + "pred_variance_6d": 0.048508149871581994, + "pred_gt_ratio": 0.659572644892008 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.09381512691794847, + "pred_variance_6d": 0.041384450631668845, + "pred_gt_ratio": 0.44112769434148985 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1267101769167171, + "pred_variance_6d": 0.06567724400754398, + "pred_gt_ratio": 0.5183265117742808 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.08075673841413365, + "pred_variance_6d": 0.056765590423114555, + "pred_gt_ratio": 0.7029207907334172 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.03143736772576662, + "pred_variance_6d": 0.018187406028014184, + "pred_gt_ratio": 0.5785282720444647 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.4911503904937964, + "pred_variance_6d": 0.16968935732391147, + "pred_gt_ratio": 0.3454936830108349 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.2142312218545364, + "pred_variance_6d": 0.05497334884801314, + "pred_gt_ratio": 0.25660754941378333 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1355850701279912, + "pred_variance_6d": 0.043054905957733064, + "pred_gt_ratio": 0.31754901861310825 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.186007061146542, + "pred_variance_6d": 0.09907707837554755, + "pred_gt_ratio": 0.5326522432258183 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1014455657894766, + "pred_variance_6d": 0.057628144335870664, + "pred_gt_ratio": 0.568069623224958 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.024940999180766, + "pred_variance_6d": 0.021199153843889817, + "pred_gt_ratio": 0.8499721158019274 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14941141870907892, + "pred_variance_6d": 0.0874961364110567, + "pred_gt_ratio": 0.5856054186957536 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14445662430848943, + "pred_variance_6d": 0.06808654165063203, + "pred_gt_ratio": 0.4713286218375984 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.18846841823407084, + "pred_variance_6d": 0.1306309274289969, + "pred_gt_ratio": 0.693118394333623 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 494, + "gt_variance_6d": 0.9023800950488734, + "pred_variance_6d": 0.7847403809458322, + "pred_gt_ratio": 0.8696339660543269 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24763924205574364, + "pred_variance_6d": 0.07260603277364786, + "pred_gt_ratio": 0.29319275964067204 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.09071934710965093, + "pred_variance_6d": 0.10540980951225248, + "pred_gt_ratio": 1.1619330701845267 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14796302500045028, + "pred_variance_6d": 0.05177548544342853, + "pred_gt_ratio": 0.34992178244038313 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24470360564125565, + "pred_variance_6d": 0.07137490994336632, + "pred_gt_ratio": 0.29167902841613425 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.07247421520685057, + "pred_variance_6d": 0.08165064967425398, + "pred_gt_ratio": 1.1266165413618168 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03884170855571756, + "pred_variance_6d": 0.02407395663805211, + "pred_gt_ratio": 0.6197965417385942 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.4407256699754486, + "pred_variance_6d": 0.21236865006370104, + "pred_gt_ratio": 0.48186131312825825 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14405031509129812, + "pred_variance_6d": 0.07266701398789359, + "pred_gt_ratio": 0.5044557795089704 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.089153279742193, + "pred_variance_6d": 0.05249718806837185, + "pred_gt_ratio": 0.5888419160818247 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24252463324047752, + "pred_variance_6d": 0.10520480630150426, + "pred_gt_ratio": 0.4337901882205404 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.08484108365834611, + "pred_variance_6d": 0.0961101139437068, + "pred_gt_ratio": 1.1328251573346344 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03429392078633288, + "pred_variance_6d": 0.023804800935967544, + "pred_gt_ratio": 0.6941405470748754 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.1723511395250014, + "pred_variance_6d": 0.09554458148146833, + "pred_gt_ratio": 0.5543600218994117 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.22195927830866272, + "pred_variance_6d": 0.07988852298234113, + "pred_gt_ratio": 0.3599242329092724 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24691242579776249, + "pred_variance_6d": 0.12614545320813295, + "pred_gt_ratio": 0.5108914741757645 + } + ] + } + }, + "N1_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 49.327910123591934, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 22.809003156693194, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 49.25970123316716, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.630683421605506, + "count": 987 + }, + "local_pose_angle_deg": { + "mean": 14.457070360743622, + "count": 1039 + }, + "root_relative_fingertip_mm": { + "mean": 32.46445435073309, + "count": 1039 + }, + "distal_angle_bias_deg": { + "mean": 2.9354517949212617, + "count": 1039 + }, + "distal_angle_mae_deg": { + "mean": 7.914565981065458, + "count": 1039 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.460334855134494, + 10.110695584217325, + 10.756171635415717, + 14.078672673406224, + 11.821124229970978, + 7.158571123646588, + 26.89375303753072, + 21.765912862324278, + 15.270053832948609, + 14.845693583323246, + 14.835956823206269, + 7.281944010754522, + 15.51236154805937, + 14.738431516579416, + 18.326366970611375 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.03858946973710707, + "recording_bootstrap_95ci": [ + -0.8011423390918709, + 0.6370979842897578 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_mpjpe_mm": { + "delta": 0.05010035086182933, + "recording_bootstrap_95ci": [ + -0.3226840122785786, + 0.37948781571853846 + ], + "count": 1039, + "recordings": 30 + }, + "mpvpe_mm": { + "delta": -0.022316164415082298, + "recording_bootstrap_95ci": [ + -0.7766267393369314, + 0.6446976375689475 + ], + "count": 1039, + "recordings": 30 + }, + "projected_mano_2d_error_px": { + "delta": 0.001014511877521797, + "recording_bootstrap_95ci": [ + -0.39222545330494163, + 0.33953644405742894 + ], + "count": 987, + "recordings": 30 + }, + "local_pose_angle_deg": { + "delta": 0.42032338152491666, + "recording_bootstrap_95ci": [ + 0.26294966049805546, + 0.5958170671215531 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_fingertip_mm": { + "delta": 0.1838728163079417, + "recording_bootstrap_95ci": [ + -0.45723328319922213, + 0.7278317991217216 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_bias_deg": { + "delta": 1.2584421292478012, + "recording_bootstrap_95ci": [ + 1.0207705839835377, + 1.5166832438990956 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_mae_deg": { + "delta": 0.5466894233766029, + "recording_bootstrap_95ci": [ + 0.3641127538949419, + 0.7674618788451537 + ], + "count": 1039, + "recordings": 30 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5962327226344918, + "mean_abs_log_variance_ratio": 0.620280275642614, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 545, + "gt_variance_6d": 1.0827241385159592, + "pred_variance_6d": 0.8915661217550686, + "pred_gt_ratio": 0.8234471644615754 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.12400796906680656, + "pred_variance_6d": 0.06346103887566665, + "pred_gt_ratio": 0.5117496831310769 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.07354481761372055, + "pred_variance_6d": 0.04899444055296135, + "pred_gt_ratio": 0.6661848127803492 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.09381512691794847, + "pred_variance_6d": 0.042037895967576996, + "pred_gt_ratio": 0.44809293925854526 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1267101769167171, + "pred_variance_6d": 0.06445164453192716, + "pred_gt_ratio": 0.5086540489505381 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.08075673841413365, + "pred_variance_6d": 0.05876434080304491, + "pred_gt_ratio": 0.7276710520636908 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.03143736772576662, + "pred_variance_6d": 0.018529569509380037, + "pred_gt_ratio": 0.5894122456758005 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.4911503904937964, + "pred_variance_6d": 0.16360512035486233, + "pred_gt_ratio": 0.33310595597893305 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.2142312218545364, + "pred_variance_6d": 0.055350399841150144, + "pred_gt_ratio": 0.25836756828438956 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1355850701279912, + "pred_variance_6d": 0.04357064298040525, + "pred_gt_ratio": 0.32135280779273795 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.186007061146542, + "pred_variance_6d": 0.09584631805878169, + "pred_gt_ratio": 0.5152832234861829 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1014455657894766, + "pred_variance_6d": 0.05853693671331099, + "pred_gt_ratio": 0.5770280470887106 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.024940999180766, + "pred_variance_6d": 0.021698799189610006, + "pred_gt_ratio": 0.8700052083857044 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14941141870907892, + "pred_variance_6d": 0.0885175743124103, + "pred_gt_ratio": 0.5924418299297733 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14445662430848943, + "pred_variance_6d": 0.06858109352124878, + "pred_gt_ratio": 0.4747521538008029 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.18846841823407084, + "pred_variance_6d": 0.1313937667386506, + "pred_gt_ratio": 0.6971659653633023 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 494, + "gt_variance_6d": 0.9023800950488734, + "pred_variance_6d": 0.7794318864441205, + "pred_gt_ratio": 0.8637511961097791 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24763924205574364, + "pred_variance_6d": 0.08013584636271745, + "pred_gt_ratio": 0.32359914243591026 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.09071934710965093, + "pred_variance_6d": 0.1108916620138898, + "pred_gt_ratio": 1.2223595687902926 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14796302500045028, + "pred_variance_6d": 0.05366904580837743, + "pred_gt_ratio": 0.3627193064497979 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24470360564125565, + "pred_variance_6d": 0.07641557997491102, + "pred_gt_ratio": 0.3122781120231593 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.07247421520685057, + "pred_variance_6d": 0.08264441932739, + "pred_gt_ratio": 1.1403285857116545 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03884170855571756, + "pred_variance_6d": 0.023394380156837508, + "pred_gt_ratio": 0.6023004915779849 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.4407256699754486, + "pred_variance_6d": 0.21911312845513867, + "pred_gt_ratio": 0.49716443443683406 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14405031509129812, + "pred_variance_6d": 0.0725526917368614, + "pred_gt_ratio": 0.503662152289483 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.089153279742193, + "pred_variance_6d": 0.05224817803597838, + "pred_gt_ratio": 0.5860488608727114 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24252463324047752, + "pred_variance_6d": 0.10827005421130428, + "pred_gt_ratio": 0.4464291019211567 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.08484108365834611, + "pred_variance_6d": 0.09637598609687495, + "pred_gt_ratio": 1.1359589239215724 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03429392078633288, + "pred_variance_6d": 0.02349187352434291, + "pred_gt_ratio": 0.6850156816628882 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.1723511395250014, + "pred_variance_6d": 0.09965709375482404, + "pred_gt_ratio": 0.5782212640396712 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.22195927830866272, + "pred_variance_6d": 0.08402888678043957, + "pred_gt_ratio": 0.37857794195738315 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24691242579776249, + "pred_variance_6d": 0.12995436860817847, + "pred_gt_ratio": 0.5263176536713452 + } + ] + } + } + } + }, + "hard": { + "hands": 2534, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1283, + "variance": 0.8231272433561402 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1283, + "variance": 0.15409708922232784 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1283, + "variance": 0.08717469219770257 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1283, + "variance": 0.09250426057328964 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1283, + "variance": 0.19332078185401297 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1283, + "variance": 0.13481498840208778 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1283, + "variance": 0.05009253551874426 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1283, + "variance": 0.4768318135394507 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1283, + "variance": 0.24299048153455496 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1283, + "variance": 0.15811544472841882 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1283, + "variance": 0.24887416488884723 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1283, + "variance": 0.19186471184797532 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1283, + "variance": 0.05322111639171685 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1283, + "variance": 0.12319734347700959 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1283, + "variance": 0.09743079736570204 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1283, + "variance": 0.1606695633471843 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1251, + "variance": 0.9115786538600362 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1251, + "variance": 0.1962898913910759 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1251, + "variance": 0.16412110852660775 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1251, + "variance": 0.13664942506817684 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1251, + "variance": 0.2594089839097105 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1251, + "variance": 0.1499002076022079 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1251, + "variance": 0.0726948825070978 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1251, + "variance": 0.518760522291538 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1251, + "variance": 0.2096864259618268 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1251, + "variance": 0.13670665100539392 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1251, + "variance": 0.3108960965839195 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1251, + "variance": 0.2086624728401734 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1251, + "variance": 0.06997302916388579 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1251, + "variance": 0.10937821422775133 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1251, + "variance": 0.10469939868574002 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1251, + "variance": 0.16128650383730753 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 54.60922134496513, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 24.396859338364454, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 54.2703544500783, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 14.812183809528964, + "count": 2302 + }, + "local_pose_angle_deg": { + "mean": 14.947253651758208, + "count": 2534 + }, + "root_relative_fingertip_mm": { + "mean": 33.851286499351616, + "count": 2534 + }, + "distal_angle_bias_deg": { + "mean": -6.0267711125473005, + "count": 2534 + }, + "distal_angle_mae_deg": { + "mean": 10.418510652708084, + "count": 2534 + }, + "gt60_angle_bias_deg": { + "mean": -16.777784632594997, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.728343272712538, + 12.464442220723056, + 12.763789765672037, + 14.886660749741022, + 14.161405509206942, + 9.14844404335039, + 24.06639622638756, + 23.33015968499451, + 16.22626544832713, + 15.327895962989697, + 16.51893534932959, + 9.51863280973664, + 13.135428017109703, + 12.340295003287512, + 16.591698910508835 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4410767545268288, + "mean_abs_log_variance_ratio": 0.8629221523731494, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.8231272433561402, + "pred_variance_6d": 0.7585274242218907, + "pred_gt_ratio": 0.9215190365090379 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15409708922232784, + "pred_variance_6d": 0.0705914066267044, + "pred_gt_ratio": 0.4580969503249779 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.08717469219770257, + "pred_variance_6d": 0.05250806351717904, + "pred_gt_ratio": 0.6023315046309146 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09250426057328964, + "pred_variance_6d": 0.02470050209262366, + "pred_gt_ratio": 0.2670201560397734 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19332078185401297, + "pred_variance_6d": 0.08006759030302017, + "pred_gt_ratio": 0.4141695969525075 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.13481498840208778, + "pred_variance_6d": 0.05962038064185585, + "pred_gt_ratio": 0.4422385177532126 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05009253551874426, + "pred_variance_6d": 0.023079303079932105, + "pred_gt_ratio": 0.46073337755674193 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.4768318135394507, + "pred_variance_6d": 0.14170561220315103, + "pred_gt_ratio": 0.29718153902377364 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24299048153455496, + "pred_variance_6d": 0.06190454399766296, + "pred_gt_ratio": 0.25476118902566847 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15811544472841882, + "pred_variance_6d": 0.046063952203255626, + "pred_gt_ratio": 0.2913311364514433 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24887416488884723, + "pred_variance_6d": 0.08816876237597085, + "pred_gt_ratio": 0.35427044994947143 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19186471184797532, + "pred_variance_6d": 0.08543158470540552, + "pred_gt_ratio": 0.44526991900989865 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05322111639171685, + "pred_variance_6d": 0.030139746356839567, + "pred_gt_ratio": 0.5663118025372803 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.12319734347700959, + "pred_variance_6d": 0.0489196915000083, + "pred_gt_ratio": 0.39708398021697133 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09743079736570204, + "pred_variance_6d": 0.036779728204714694, + "pred_gt_ratio": 0.3774959170934799 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.1606695633471843, + "pred_variance_6d": 0.06222293875377527, + "pred_gt_ratio": 0.3872727195960585 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.9115786538600362, + "pred_variance_6d": 0.830237802939764, + "pred_gt_ratio": 0.910769245664279 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1962898913910759, + "pred_variance_6d": 0.062203777135776246, + "pred_gt_ratio": 0.31689750651420595 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16412110852660775, + "pred_variance_6d": 0.08120921166890019, + "pred_gt_ratio": 0.494812717254675 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13664942506817684, + "pred_variance_6d": 0.04434015799077859, + "pred_gt_ratio": 0.3244811163212468 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2594089839097105, + "pred_variance_6d": 0.10307450476863624, + "pred_gt_ratio": 0.3973436201597096 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1499002076022079, + "pred_variance_6d": 0.06333265616994943, + "pred_gt_ratio": 0.42249878891439635 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.0726948825070978, + "pred_variance_6d": 0.030360468685222058, + "pred_gt_ratio": 0.4176424479709107 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.518760522291538, + "pred_variance_6d": 0.23888357499093085, + "pred_gt_ratio": 0.4604891172822915 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2096864259618268, + "pred_variance_6d": 0.06929863469823777, + "pred_gt_ratio": 0.3304869849365143 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13670665100539392, + "pred_variance_6d": 0.05115017639741009, + "pred_gt_ratio": 0.37416011599458976 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.3108960965839195, + "pred_variance_6d": 0.12850179361118874, + "pred_gt_ratio": 0.4133271373399265 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2086624728401734, + "pred_variance_6d": 0.07755291691419672, + "pred_gt_ratio": 0.3716668160719008 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.06997302916388579, + "pred_variance_6d": 0.03378604098024014, + "pred_gt_ratio": 0.4828437668620707 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10937821422775133, + "pred_variance_6d": 0.06040094124277372, + "pred_gt_ratio": 0.5522209488354295 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10469939868574002, + "pred_variance_6d": 0.044072109593335844, + "pred_gt_ratio": 0.42093947192209075 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16128650383730753, + "pred_variance_6d": 0.07851242336060807, + "pred_gt_ratio": 0.48678855014307276 + } + ] + } + }, + "N0_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 55.26548776272816, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 24.800044147255107, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 54.972875078738724, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 14.59409165195959, + "count": 2302 + }, + "local_pose_angle_deg": { + "mean": 14.876024449257372, + "count": 2534 + }, + "root_relative_fingertip_mm": { + "mean": 34.21705398375158, + "count": 2534 + }, + "distal_angle_bias_deg": { + "mean": -5.317312515525246, + "count": 2534 + }, + "distal_angle_mae_deg": { + "mean": 10.231966506592759, + "count": 2534 + }, + "gt60_angle_bias_deg": { + "mean": -16.340660139886282, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 14.006220396416998, + 12.563428496952215, + 12.771704309858858, + 14.84767074399608, + 14.217328441218307, + 8.838759906019577, + 24.139928673418282, + 23.08736039040685, + 15.92637481292873, + 15.241284290447702, + 16.181281079374248, + 9.156942834593973, + 13.14174938126634, + 12.462978378867389, + 16.557342651752194 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.6562664177630394, + "recording_bootstrap_95ci": [ + 0.11560483501432856, + 1.2030649542936775 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.40318480889065206, + "recording_bootstrap_95ci": [ + 0.07885605094840029, + 0.6914997892556831 + ], + "count": 2534, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": 0.7025206286604233, + "recording_bootstrap_95ci": [ + 0.1538916742253074, + 1.2528727485766562 + ], + "count": 2534, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.21809215756937486, + "recording_bootstrap_95ci": [ + -0.45213800771370005, + 0.0314365447800903 + ], + "count": 2302, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": -0.07122920250083484, + "recording_bootstrap_95ci": [ + -0.15380761218677294, + 0.00200628308346276 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": 0.36576748439996565, + "recording_bootstrap_95ci": [ + -0.06560231283900791, + 0.7508415558865579 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 0.709458597022055, + "recording_bootstrap_95ci": [ + 0.5256436619629099, + 0.8930203158433743 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.18654414611532638, + "recording_bootstrap_95ci": [ + -0.3095940669611611, + -0.06775163707709225 + ], + "count": 2534, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 0.4371244927087138, + "recording_bootstrap_95ci": [ + 0.18717554678883475, + 0.7015187273606427 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4572594714688816, + "mean_abs_log_variance_ratio": 0.8244802486808439, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.8231272433561402, + "pred_variance_6d": 0.7411895527114829, + "pred_gt_ratio": 0.9004556205543964 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15409708922232784, + "pred_variance_6d": 0.07193871726476594, + "pred_gt_ratio": 0.4668402085192821 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.08717469219770257, + "pred_variance_6d": 0.050913387071447394, + "pred_gt_ratio": 0.5840386216217598 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09250426057328964, + "pred_variance_6d": 0.027320732926216076, + "pred_gt_ratio": 0.29534567118203486 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19332078185401297, + "pred_variance_6d": 0.08036046314735987, + "pred_gt_ratio": 0.4156845548454507 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.13481498840208778, + "pred_variance_6d": 0.05451949126164708, + "pred_gt_ratio": 0.40440229909037906 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05009253551874426, + "pred_variance_6d": 0.023417319030034245, + "pred_gt_ratio": 0.46748120827846007 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.4768318135394507, + "pred_variance_6d": 0.14302832947178815, + "pred_gt_ratio": 0.2999555092813762 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24299048153455496, + "pred_variance_6d": 0.06107699076455123, + "pred_gt_ratio": 0.2513554867615901 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15811544472841882, + "pred_variance_6d": 0.04783788128438528, + "pred_gt_ratio": 0.3025503382452755 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24887416488884723, + "pred_variance_6d": 0.08756013298910319, + "pred_gt_ratio": 0.35182491934512167 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19186471184797532, + "pred_variance_6d": 0.08441525225010998, + "pred_gt_ratio": 0.439972788310321 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05322111639171685, + "pred_variance_6d": 0.03153306535891351, + "pred_gt_ratio": 0.5924916179289543 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.12319734347700959, + "pred_variance_6d": 0.04966374439042932, + "pred_gt_ratio": 0.4031235007895872 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09743079736570204, + "pred_variance_6d": 0.03848206963801093, + "pred_gt_ratio": 0.39496823056441016 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.1606695633471843, + "pred_variance_6d": 0.06698619690470278, + "pred_gt_ratio": 0.41691902006327763 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.9115786538600362, + "pred_variance_6d": 0.8530117690580563, + "pred_gt_ratio": 0.9357522419442565 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1962898913910759, + "pred_variance_6d": 0.06188010492802642, + "pred_gt_ratio": 0.31524855655832174 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16412110852660775, + "pred_variance_6d": 0.08138572953335271, + "pred_gt_ratio": 0.4958882514503504 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13664942506817684, + "pred_variance_6d": 0.04615676480894608, + "pred_gt_ratio": 0.3377750384673601 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2594089839097105, + "pred_variance_6d": 0.10609605910151024, + "pred_gt_ratio": 0.4089914601355436 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1499002076022079, + "pred_variance_6d": 0.06854138819154584, + "pred_gt_ratio": 0.45724678629822185 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.0726948825070978, + "pred_variance_6d": 0.034070206781980306, + "pred_gt_ratio": 0.4686740745286128 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.518760522291538, + "pred_variance_6d": 0.2333046824680842, + "pred_gt_ratio": 0.4497348438109741 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2096864259618268, + "pred_variance_6d": 0.07459628030553596, + "pred_gt_ratio": 0.3557515941404626 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13670665100539392, + "pred_variance_6d": 0.06006373396363572, + "pred_gt_ratio": 0.43936219285531203 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.3108960965839195, + "pred_variance_6d": 0.13255143814432457, + "pred_gt_ratio": 0.42635285421972247 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2086624728401734, + "pred_variance_6d": 0.09405979215199127, + "pred_gt_ratio": 0.45077483685356823 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.06997302916388579, + "pred_variance_6d": 0.039649601331742494, + "pred_gt_ratio": 0.5666412016961286 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10937821422775133, + "pred_variance_6d": 0.06191632024342919, + "pred_gt_ratio": 0.5660754354107917 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10469939868574002, + "pred_variance_6d": 0.04739725496765887, + "pred_gt_ratio": 0.4526984449062967 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16128650383730753, + "pred_variance_6d": 0.08353442190809057, + "pred_gt_ratio": 0.5179256783466097 + } + ] + } + }, + "N0_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 54.17820736660013, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 24.489900348500747, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 53.86514546519297, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 14.47074759420781, + "count": 2302 + }, + "local_pose_angle_deg": { + "mean": 14.911260054068201, + "count": 2534 + }, + "root_relative_fingertip_mm": { + "mean": 33.96530892911066, + "count": 2534 + }, + "distal_angle_bias_deg": { + "mean": -5.626818898703606, + "count": 2534 + }, + "distal_angle_mae_deg": { + "mean": 10.297609299633008, + "count": 2534 + }, + "gt60_angle_bias_deg": { + "mean": -16.336611252262067, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.83077626741817, + 12.373172211007237, + 12.548287048171426, + 14.680920207980305, + 14.314386214152414, + 8.917211762284706, + 24.3989086712357, + 23.341075585633163, + 15.989200098738486, + 15.2461880724686, + 16.325912053813685, + 9.302126128676376, + 13.291769036507175, + 12.529679793420511, + 16.57927589674775 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.43101397836500016, + "recording_bootstrap_95ci": [ + -1.225862610170842, + 0.26460074753776275 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.09304101013629194, + "recording_bootstrap_95ci": [ + -0.21158153329367343, + 0.36735867037050346 + ], + "count": 2534, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -0.4052089848853324, + "recording_bootstrap_95ci": [ + -1.2014739717639522, + 0.2818236324644491 + ], + "count": 2534, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.34143621532115387, + "recording_bootstrap_95ci": [ + -0.5608124710932723, + -0.12856886628616973 + ], + "count": 2302, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": -0.03599359769000721, + "recording_bootstrap_95ci": [ + -0.11859204896834372, + 0.03941691943559945 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": 0.1140224297590489, + "recording_bootstrap_95ci": [ + -0.2942346112917067, + 0.47278026018007274 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 0.3999522138436949, + "recording_bootstrap_95ci": [ + 0.24582569347227554, + 0.5563741683638875 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.12090135307507714, + "recording_bootstrap_95ci": [ + -0.2121289447183349, + -0.03377115807987647 + ], + "count": 2534, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 0.44117338033292886, + "recording_bootstrap_95ci": [ + 0.17956424138586755, + 0.6860260023735127 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4577420310538044, + "mean_abs_log_variance_ratio": 0.8246963731335287, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.8231272433561402, + "pred_variance_6d": 0.75428325372391, + "pred_gt_ratio": 0.9163628829103843 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15409708922232784, + "pred_variance_6d": 0.07149326354957283, + "pred_gt_ratio": 0.4639494743889935 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.08717469219770257, + "pred_variance_6d": 0.05259273916572635, + "pred_gt_ratio": 0.6033028375534935 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09250426057328964, + "pred_variance_6d": 0.027610633836494678, + "pred_gt_ratio": 0.2984795907278153 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19332078185401297, + "pred_variance_6d": 0.07862165468738679, + "pred_gt_ratio": 0.40669013405272836 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.13481498840208778, + "pred_variance_6d": 0.056624025922099835, + "pred_gt_ratio": 0.42001283828484864 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05009253551874426, + "pred_variance_6d": 0.023315642113994124, + "pred_gt_ratio": 0.46545142649586146 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.4768318135394507, + "pred_variance_6d": 0.13660656956512177, + "pred_gt_ratio": 0.2864879516975006 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24299048153455496, + "pred_variance_6d": 0.06068839636939532, + "pred_gt_ratio": 0.24975627022972502 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15811544472841882, + "pred_variance_6d": 0.046941662849871564, + "pred_gt_ratio": 0.2968822111622251 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24887416488884723, + "pred_variance_6d": 0.08403905713426625, + "pred_gt_ratio": 0.3376769025897082 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19186471184797532, + "pred_variance_6d": 0.08483779101755248, + "pred_gt_ratio": 0.4421750628368494 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05322111639171685, + "pred_variance_6d": 0.031271619491605875, + "pred_gt_ratio": 0.5875791717979234 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.12319734347700959, + "pred_variance_6d": 0.05077765746016661, + "pred_gt_ratio": 0.4121651979422954 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09743079736570204, + "pred_variance_6d": 0.03900633482929161, + "pred_gt_ratio": 0.40034912865264893 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.1606695633471843, + "pred_variance_6d": 0.06785670838858492, + "pred_gt_ratio": 0.4223370436499919 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.9115786538600362, + "pred_variance_6d": 0.8492924633672985, + "pred_gt_ratio": 0.9316721708774225 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1962898913910759, + "pred_variance_6d": 0.06558503479177273, + "pred_gt_ratio": 0.3341233434232492 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16412110852660775, + "pred_variance_6d": 0.0845984031982873, + "pred_gt_ratio": 0.5154632695194841 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13664942506817684, + "pred_variance_6d": 0.04728253598207201, + "pred_gt_ratio": 0.34601342785366207 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2594089839097105, + "pred_variance_6d": 0.10934731213084468, + "pred_gt_ratio": 0.42152476943089967 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1499002076022079, + "pred_variance_6d": 0.06881905111319464, + "pred_gt_ratio": 0.45909910475788424 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.0726948825070978, + "pred_variance_6d": 0.03207421527699619, + "pred_gt_ratio": 0.4412169628840727 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.518760522291538, + "pred_variance_6d": 0.2380546065873104, + "pred_gt_ratio": 0.45889113831512063 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2096864259618268, + "pred_variance_6d": 0.07010030363682886, + "pred_gt_ratio": 0.3343101648820632 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13670665100539392, + "pred_variance_6d": 0.056759322873172716, + "pred_gt_ratio": 0.41519064694908814 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.3108960965839195, + "pred_variance_6d": 0.13531562053997545, + "pred_gt_ratio": 0.43524387094853734 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2086624728401734, + "pred_variance_6d": 0.09052098695666963, + "pred_gt_ratio": 0.4338153656695369 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.06997302916388579, + "pred_variance_6d": 0.037436489836365786, + "pred_gt_ratio": 0.535013136971457 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10937821422775133, + "pred_variance_6d": 0.06351267941130466, + "pred_gt_ratio": 0.5806702903290799 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10469939868574002, + "pred_variance_6d": 0.04889162583438039, + "pred_gt_ratio": 0.46697141003771014 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16128650383730753, + "pred_variance_6d": 0.08529923779277013, + "pred_gt_ratio": 0.5288677958994817 + } + ] + } + }, + "N1_12K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 55.147393878652245, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 24.74158573357628, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 54.855358517819155, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 14.552250960823974, + "count": 2302 + }, + "local_pose_angle_deg": { + "mean": 14.731652677200305, + "count": 2534 + }, + "root_relative_fingertip_mm": { + "mean": 34.117055561943324, + "count": 2534 + }, + "distal_angle_bias_deg": { + "mean": -4.423437223814563, + "count": 2534 + }, + "distal_angle_mae_deg": { + "mean": 10.042327556491557, + "count": 2534 + }, + "gt60_angle_bias_deg": { + "mean": -15.333011264985888, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 14.056445243561841, + 12.398552096962646, + 12.56520339077443, + 14.825421983836293, + 13.737301877860771, + 8.549139583825877, + 24.199866906102475, + 22.81220669765687, + 15.712926877702232, + 15.249123145368218, + 15.815958451970694, + 8.943132727315037, + 13.107320208599367, + 12.436601023894648, + 16.565577876454935 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": 0.5381725336871188, + "recording_bootstrap_95ci": [ + -0.07335079758659296, + 1.1192724298785477 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.3447263952118257, + "recording_bootstrap_95ci": [ + 0.0009048158889655792, + 0.6364268373537434 + ], + "count": 2534, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": 0.5850040677408581, + "recording_bootstrap_95ci": [ + -0.02831006121862891, + 1.1663129179674439 + ], + "count": 2534, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.25993284870499017, + "recording_bootstrap_95ci": [ + -0.5076509657045744, + 0.002311491276141405 + ], + "count": 2302, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": -0.21560097455790217, + "recording_bootstrap_95ci": [ + -0.33830331329532143, + -0.10695239113435276 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": 0.2657690625917093, + "recording_bootstrap_95ci": [ + -0.2340920698857763, + 0.685681349473805 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 1.6033338887327377, + "recording_bootstrap_95ci": [ + 1.3699862573204526, + 1.8350921975447017 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.37618309621652846, + "recording_bootstrap_95ci": [ + -0.5796130306483998, + -0.1665083428890078 + ], + "count": 2534, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 1.4447733676091077, + "recording_bootstrap_95ci": [ + 1.1111775147446636, + 1.8132244463954068 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4591547411317849, + "mean_abs_log_variance_ratio": 0.8207170291335812, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.8231272433561402, + "pred_variance_6d": 0.7409822834779782, + "pred_gt_ratio": 0.90020381351584 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15409708922232784, + "pred_variance_6d": 0.07128143470226048, + "pred_gt_ratio": 0.46257482903792696 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.08717469219770257, + "pred_variance_6d": 0.05118350997298521, + "pred_gt_ratio": 0.5871372606272777 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09250426057328964, + "pred_variance_6d": 0.02743959280766734, + "pred_gt_ratio": 0.2966305836900063 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19332078185401297, + "pred_variance_6d": 0.07940095806726882, + "pred_gt_ratio": 0.4107212753113569 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.13481498840208778, + "pred_variance_6d": 0.055872669542479936, + "pred_gt_ratio": 0.4144395975901347 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05009253551874426, + "pred_variance_6d": 0.02424305504670197, + "pred_gt_ratio": 0.4839654211081089 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.4768318135394507, + "pred_variance_6d": 0.14121876214162404, + "pred_gt_ratio": 0.2961605289994777 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24299048153455496, + "pred_variance_6d": 0.06049187048014846, + "pred_gt_ratio": 0.2489474900338682 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15811544472841882, + "pred_variance_6d": 0.0480772419628462, + "pred_gt_ratio": 0.3040641731452883 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24887416488884723, + "pred_variance_6d": 0.08627153354262941, + "pred_gt_ratio": 0.34664720454676445 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19186471184797532, + "pred_variance_6d": 0.08458360915931187, + "pred_gt_ratio": 0.44085026550547757 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05322111639171685, + "pred_variance_6d": 0.03223502586234928, + "pred_gt_ratio": 0.6056811289919921 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.12319734347700959, + "pred_variance_6d": 0.04923057030673345, + "pred_gt_ratio": 0.3996074015664193 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09743079736570204, + "pred_variance_6d": 0.037870311916416946, + "pred_gt_ratio": 0.3886893358192735 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.1606695633471843, + "pred_variance_6d": 0.06673006498555223, + "pred_gt_ratio": 0.41532486673507635 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.9115786538600362, + "pred_variance_6d": 0.8513540912244568, + "pred_gt_ratio": 0.9339337726036461 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1962898913910759, + "pred_variance_6d": 0.061966788696025336, + "pred_gt_ratio": 0.3156901675214977 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16412110852660775, + "pred_variance_6d": 0.08205234350092831, + "pred_gt_ratio": 0.4999499713202691 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13664942506817684, + "pred_variance_6d": 0.046598880922397876, + "pred_gt_ratio": 0.34101044259168206 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2594089839097105, + "pred_variance_6d": 0.10769637427332418, + "pred_gt_ratio": 0.4151605416673187 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1499002076022079, + "pred_variance_6d": 0.06917337915995905, + "pred_gt_ratio": 0.4614628643045334 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.0726948825070978, + "pred_variance_6d": 0.0343094033227245, + "pred_gt_ratio": 0.47196449240253735 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.518760522291538, + "pred_variance_6d": 0.23414011041409188, + "pred_gt_ratio": 0.45134527465547497 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2096864259618268, + "pred_variance_6d": 0.07592160427407518, + "pred_gt_ratio": 0.36207209849576355 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13670665100539392, + "pred_variance_6d": 0.06071792778380823, + "pred_gt_ratio": 0.4441475768535397 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.3108960965839195, + "pred_variance_6d": 0.13376694334664366, + "pred_gt_ratio": 0.43026253727999525 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2086624728401734, + "pred_variance_6d": 0.09469127794863406, + "pred_gt_ratio": 0.45380118743806686 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.06997302916388579, + "pred_variance_6d": 0.039896779063779676, + "pred_gt_ratio": 0.5701736732068053 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10937821422775133, + "pred_variance_6d": 0.06172885628894246, + "pred_gt_ratio": 0.5643615296224198 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10469939868574002, + "pred_variance_6d": 0.047507899158556854, + "pred_gt_ratio": 0.45375522452763994 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16128650383730753, + "pred_variance_6d": 0.08422626152031024, + "pred_gt_ratio": 0.5222151855016383 + } + ] + } + }, + "N1_18K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 54.04012487512361, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 24.43093392466972, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 53.72711887280585, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 14.419181942836188, + "count": 2302 + }, + "local_pose_angle_deg": { + "mean": 14.734952184470883, + "count": 2534 + }, + "root_relative_fingertip_mm": { + "mean": 33.83762522391099, + "count": 2534 + }, + "distal_angle_bias_deg": { + "mean": -4.60315186522707, + "count": 2534 + }, + "distal_angle_mae_deg": { + "mean": 10.049834412011746, + "count": 2534 + }, + "gt60_angle_bias_deg": { + "mean": -15.204320517150304, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.874373744299962, + 12.168403259221973, + 12.329772290368672, + 14.65911273266635, + 13.713793404923713, + 8.57012259486207, + 24.48042563860023, + 23.018561524580857, + 15.731586204707952, + 15.272879013146296, + 15.866687211777718, + 9.003136240763277, + 13.26118102803791, + 12.49085174330408, + 16.5833844653527 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.5690964698415153, + "recording_bootstrap_95ci": [ + -1.5832292054450885, + 0.22576199510061487 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.03407458630526452, + "recording_bootstrap_95ci": [ + -0.29178946107353776, + 0.3207511672346873 + ], + "count": 2534, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -0.5432355772724468, + "recording_bootstrap_95ci": [ + -1.546848772821482, + 0.24968729846562612 + ], + "count": 2534, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.39300186669277587, + "recording_bootstrap_95ci": [ + -0.696272839321111, + -0.14626548034833076 + ], + "count": 2302, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": -0.21230146728732405, + "recording_bootstrap_95ci": [ + -0.33391614169881684, + -0.10614464921579649 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": -0.013661275440628546, + "recording_bootstrap_95ci": [ + -0.46497625707723494, + 0.3837999439754688 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 1.423619247320231, + "recording_bootstrap_95ci": [ + 1.2068665793752618, + 1.6487777831252322 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.36867624069633875, + "recording_bootstrap_95ci": [ + -0.5518497981216757, + -0.18629867047924684 + ], + "count": 2534, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 1.573464115444691, + "recording_bootstrap_95ci": [ + 1.2426470795369866, + 1.9121950647213475 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4609773133178952, + "mean_abs_log_variance_ratio": 0.8178044124815294, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.8231272433561402, + "pred_variance_6d": 0.7533227965311703, + "pred_gt_ratio": 0.9151960436391876 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15409708922232784, + "pred_variance_6d": 0.07087454556699722, + "pred_gt_ratio": 0.4599343564805498 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.08717469219770257, + "pred_variance_6d": 0.05243854089693419, + "pred_gt_ratio": 0.6015339954170342 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09250426057328964, + "pred_variance_6d": 0.027750619498080456, + "pred_gt_ratio": 0.2999928795289822 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19332078185401297, + "pred_variance_6d": 0.07782708633241804, + "pred_gt_ratio": 0.4025800309000897 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.13481498840208778, + "pred_variance_6d": 0.057873252735338936, + "pred_gt_ratio": 0.429279069199124 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05009253551874426, + "pred_variance_6d": 0.02424076175045743, + "pred_gt_ratio": 0.4839196399109546 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.4768318135394507, + "pred_variance_6d": 0.13503057596806745, + "pred_gt_ratio": 0.283182816527605 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24299048153455496, + "pred_variance_6d": 0.060364227880281285, + "pred_gt_ratio": 0.24842219126882575 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15811544472841882, + "pred_variance_6d": 0.047789570312655676, + "pred_gt_ratio": 0.30224479584989106 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24887416488884723, + "pred_variance_6d": 0.0829001581878542, + "pred_gt_ratio": 0.3331006985995484 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19186471184797532, + "pred_variance_6d": 0.08537624139905142, + "pred_gt_ratio": 0.4449814693735844 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05322111639171685, + "pred_variance_6d": 0.032186287949602856, + "pred_gt_ratio": 0.6047653663013393 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.12319734347700959, + "pred_variance_6d": 0.050238615062168736, + "pred_gt_ratio": 0.40778975945649343 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09743079736570204, + "pred_variance_6d": 0.03819781346093464, + "pred_gt_ratio": 0.3920507118253472 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.1606695633471843, + "pred_variance_6d": 0.06733228948312853, + "pred_gt_ratio": 0.4190730844125899 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.9115786538600362, + "pred_variance_6d": 0.8484681903068034, + "pred_gt_ratio": 0.9307679449425516 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1962898913910759, + "pred_variance_6d": 0.06556657796532367, + "pred_gt_ratio": 0.3340293150129308 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16412110852660775, + "pred_variance_6d": 0.08566013861384368, + "pred_gt_ratio": 0.521932488653379 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13664942506817684, + "pred_variance_6d": 0.04777244159603994, + "pred_gt_ratio": 0.3495985553704702 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2594089839097105, + "pred_variance_6d": 0.11076965956687361, + "pred_gt_ratio": 0.4270078001825408 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1499002076022079, + "pred_variance_6d": 0.07020453601741453, + "pred_gt_ratio": 0.46834181980399386 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.0726948825070978, + "pred_variance_6d": 0.03276600762754593, + "pred_gt_ratio": 0.45073334597310505 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.518760522291538, + "pred_variance_6d": 0.23865329467070281, + "pred_gt_ratio": 0.46004521241611007 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2096864259618268, + "pred_variance_6d": 0.07225689685104708, + "pred_gt_ratio": 0.344595013814587 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13670665100539392, + "pred_variance_6d": 0.058269810362617615, + "pred_gt_ratio": 0.42623976181172424 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.3108960965839195, + "pred_variance_6d": 0.13632458771415693, + "pred_gt_ratio": 0.43848922264406476 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2086624728401734, + "pred_variance_6d": 0.09194792240410433, + "pred_gt_ratio": 0.44065385190049267 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.06997302916388579, + "pred_variance_6d": 0.03827681297536582, + "pred_gt_ratio": 0.5470223803762537 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10937821422775133, + "pred_variance_6d": 0.06336488185926778, + "pred_gt_ratio": 0.5793190381342952 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10469939868574002, + "pred_variance_6d": 0.04922130546289452, + "pred_gt_ratio": 0.4701202306866584 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16128650383730753, + "pred_variance_6d": 0.08618040077788079, + "pred_gt_ratio": 0.5343311357583425 + } + ] + } + } + } + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_hot3d_n1_20k.json b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_hot3d_n1_20k.json new file mode 100644 index 0000000000000000000000000000000000000000..d5f1cf0f6811f7a889e20d8940c95614c5ff8704 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/pose_hard_hot3d_n1_20k.json @@ -0,0 +1,3070 @@ +{ + "source": "HOT3D", + "role": "development", + "input_mode": "rgb", + "gt": "source_native_not_refitted", + "clips": 248, + "panel_sha256": "8ae334a8bc87bc6670a31f2edb8b78989c883547d26c86815498d5f89ccb7060", + "parent_checkpoint_sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a", + "checkpoints": { + "U0_parent": { + "path": "/home/wuyifan/unified_mot_u0_depthsafe_20261001/runs/U0/update_0020004.pt", + "sha256": "d41f461f217bdd11901d0d695d15839494593c499791a4ad390ae44dce02809a" + }, + "N1_20K": { + "path": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0020000.pt", + "sha256": "a47c1f157c03b2370e785e6a6ddf0644fc87098b672e91e2e82da40c67894396" + } + }, + "hard_definition": "GT >=2 non-thumb distal angles >=45deg OR >=1 >=60deg; complete 21-joint geometry and MANO pose only", + "groups": { + "all": { + "hands": 3573, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1828, + "variance": 0.9078642060833665 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1828, + "variance": 0.16199262882475624 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1828, + "variance": 0.12232570281073116 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1828, + "variance": 0.09439385714932436 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1828, + "variance": 0.18498699394554094 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1828, + "variance": 0.17591510017264494 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1828, + "variance": 0.06181170335264618 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1828, + "variance": 0.48520380553723685 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1828, + "variance": 0.2749259641279063 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1828, + "variance": 0.18181540568994045 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1828, + "variance": 0.2343304679990655 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1828, + "variance": 0.24823855156388863 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1828, + "variance": 0.0652150158232389 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1828, + "variance": 0.13684319564689476 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1828, + "variance": 0.11868189348606356 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1828, + "variance": 0.1759020250807575 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1745, + "variance": 0.9101462201961528 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1745, + "variance": 0.21365722111186325 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1745, + "variance": 0.18926917560471376 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1745, + "variance": 0.14613903441426507 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1745, + "variance": 0.2583566611716799 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1745, + "variance": 0.18678808384059908 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1745, + "variance": 0.07952837254109431 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1745, + "variance": 0.4996390591174059 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1745, + "variance": 0.22379709478908846 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1745, + "variance": 0.14773829719745404 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1745, + "variance": 0.2945443603939768 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1745, + "variance": 0.25151218340149883 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1745, + "variance": 0.07535130472881144 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1745, + "variance": 0.1331221242401221 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1745, + "variance": 0.14755590450729988 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1745, + "variance": 0.19342181043223353 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 53.084679531377134, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 23.920554598005687, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 52.81978568502277, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 14.757412691832531, + "count": 3289 + }, + "local_pose_angle_deg": { + "mean": 14.682485548548428, + "count": 3573 + }, + "root_relative_fingertip_mm": { + "mean": 33.39453798030359, + "count": 3573 + }, + "distal_angle_bias_deg": { + "mean": -3.7865728957627023, + "count": 3573 + }, + "distal_angle_mae_deg": { + "mean": 9.531410505849708, + "count": 3573 + }, + "gt60_angle_bias_deg": { + "mean": -16.777784632594997, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.605053656806206, + 11.723984282673356, + 12.195507196078205, + 14.634379403483724, + 13.33239297474128, + 8.482029535016059, + 24.564950862744592, + 22.43920696165393, + 15.747543460859694, + 15.089280581360867, + 15.62697612436052, + 8.785158222007912, + 13.865488775030691, + 13.054160223282787, + 17.091159332075474 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4343958458640267, + "mean_abs_log_variance_ratio": 0.8740216377821366, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.9078642060833665, + "pred_variance_6d": 0.8042887951052126, + "pred_gt_ratio": 0.8859131021091904 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.16199262882475624, + "pred_variance_6d": 0.0747604773746268, + "pred_gt_ratio": 0.4615054272346104 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.12232570281073116, + "pred_variance_6d": 0.06038014604322044, + "pred_gt_ratio": 0.4936014644170393 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.09439385714932436, + "pred_variance_6d": 0.028883912952377615, + "pred_gt_ratio": 0.3059935659445013 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18498699394554094, + "pred_variance_6d": 0.08105219843476143, + "pred_gt_ratio": 0.4381507948533004 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.17591510017264494, + "pred_variance_6d": 0.06469243479378003, + "pred_gt_ratio": 0.367748048520509 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.06181170335264618, + "pred_variance_6d": 0.022922464507875114, + "pred_gt_ratio": 0.37084343683426085 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.48520380553723685, + "pred_variance_6d": 0.15151880484977442, + "pred_gt_ratio": 0.3122786819077126 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2749259641279063, + "pred_variance_6d": 0.06480237321837296, + "pred_gt_ratio": 0.23570845126953652 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18181540568994045, + "pred_variance_6d": 0.04934338909811801, + "pred_gt_ratio": 0.2713927838560938 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2343304679990655, + "pred_variance_6d": 0.09368009302581219, + "pred_gt_ratio": 0.39977768928531215 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.24823855156388863, + "pred_variance_6d": 0.08742200289825847, + "pred_gt_ratio": 0.3521693240131513 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.0652150158232389, + "pred_variance_6d": 0.029799894763991683, + "pred_gt_ratio": 0.4569483636216908 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.13684319564689476, + "pred_variance_6d": 0.0625655627671026, + "pred_gt_ratio": 0.45720623865394455 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.11868189348606356, + "pred_variance_6d": 0.04694346871602259, + "pred_gt_ratio": 0.39554027440196693 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.1759020250807575, + "pred_variance_6d": 0.08356069207204053, + "pred_gt_ratio": 0.47504110332827265 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.9101462201961528, + "pred_variance_6d": 0.8136453901592792, + "pred_gt_ratio": 0.8939721685422416 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.21365722111186325, + "pred_variance_6d": 0.07500075070355064, + "pred_gt_ratio": 0.35103307210142426 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18926917560471376, + "pred_variance_6d": 0.10093387514506906, + "pred_gt_ratio": 0.5332821618870902 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14613903441426507, + "pred_variance_6d": 0.04628113414184008, + "pred_gt_ratio": 0.31669248621586926 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2583566611716799, + "pred_variance_6d": 0.10523412114742274, + "pred_gt_ratio": 0.40732110668319055 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18678808384059908, + "pred_variance_6d": 0.07856990270908476, + "pred_gt_ratio": 0.42063659037337 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07952837254109431, + "pred_variance_6d": 0.031398711856016524, + "pred_gt_ratio": 0.39481144719505007 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.4996390591174059, + "pred_variance_6d": 0.2465414057407459, + "pred_gt_ratio": 0.4934390161094536 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.22379709478908846, + "pred_variance_6d": 0.07770255708800353, + "pred_gt_ratio": 0.347200919481248 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14773829719745404, + "pred_variance_6d": 0.054410020925465735, + "pred_gt_ratio": 0.3682865036189369 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2945443603939768, + "pred_variance_6d": 0.1308624652318437, + "pred_gt_ratio": 0.44428779779319016 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.25151218340149883, + "pred_variance_6d": 0.0931492261494454, + "pred_gt_ratio": 0.3703567154866117 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07535130472881144, + "pred_variance_6d": 0.035251945545125986, + "pred_gt_ratio": 0.4678345739598985 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.1331221242401221, + "pred_variance_6d": 0.07388720259227816, + "pred_gt_ratio": 0.555033229931055 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14755590450729988, + "pred_variance_6d": 0.05616968985416318, + "pred_gt_ratio": 0.3806671785972777 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.19342181043223353, + "pred_variance_6d": 0.09206749539887747, + "pred_gt_ratio": 0.4759933494218526 + } + ] + } + }, + "N1_20K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 52.876747095448074, + "count": 3573 + }, + "root_relative_mpjpe_mm": { + "mean": 23.940694491201977, + "count": 3573 + }, + "mpvpe_mm": { + "mean": 52.624237953498856, + "count": 3573 + }, + "projected_mano_2d_error_px": { + "mean": 14.572545324570866, + "count": 3289 + }, + "local_pose_angle_deg": { + "mean": 14.628961387482672, + "count": 3573 + }, + "root_relative_fingertip_mm": { + "mean": 33.391941281550075, + "count": 3573 + }, + "distal_angle_bias_deg": { + "mean": -2.6707963179697884, + "count": 3573 + }, + "distal_angle_mae_deg": { + "mean": 9.443705816312962, + "count": 3573 + }, + "gt60_angle_bias_deg": { + "mean": -15.51311545105631, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.699065741540469, + 11.591536200696302, + 11.901777648238484, + 14.518020407987715, + 13.162724491105573, + 8.206297038267415, + 25.002090517342875, + 22.63002715252075, + 15.580368954178468, + 15.094128999011442, + 15.561440857691888, + 8.567392281364267, + 13.812414819949687, + 13.045538544504709, + 17.06158556941174 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.2079324359290579, + "recording_bootstrap_95ci": [ + -0.7652680520342299, + 0.2565823363883969 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.02013989319629173, + "recording_bootstrap_95ci": [ + -0.2372968585765061, + 0.24014471129337145 + ], + "count": 3573, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -0.19554773152391683, + "recording_bootstrap_95ci": [ + -0.7524278623896823, + 0.26959351531534076 + ], + "count": 3573, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.1848673672616645, + "recording_bootstrap_95ci": [ + -0.36017861194027934, + 0.012165666717075967 + ], + "count": 3289, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": -0.053524161065755825, + "recording_bootstrap_95ci": [ + -0.13177870716624657, + 0.023562859327097903 + ], + "count": 3573, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": -0.00259669875351281, + "recording_bootstrap_95ci": [ + -0.3698692745320005, + 0.3195780482224652 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 1.1157765777929136, + "recording_bootstrap_95ci": [ + 0.9341486530700903, + 1.2928222912221428 + ], + "count": 3573, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.08770468953674726, + "recording_bootstrap_95ci": [ + -0.19993239168325586, + 0.029622578879864393 + ], + "count": 3573, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 1.2646691815386857, + "recording_bootstrap_95ci": [ + 0.9570686690311805, + 1.5861683819734078 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4565105277121786, + "mean_abs_log_variance_ratio": 0.8210286078345489, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.9078642060833665, + "pred_variance_6d": 0.8066800394932765, + "pred_gt_ratio": 0.8885470250814156 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.16199262882475624, + "pred_variance_6d": 0.07664744943010664, + "pred_gt_ratio": 0.47315393290532937 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.12232570281073116, + "pred_variance_6d": 0.06276996041642147, + "pred_gt_ratio": 0.513137950358172 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.09439385714932436, + "pred_variance_6d": 0.032433357090236335, + "pred_gt_ratio": 0.3435960566684872 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18498699394554094, + "pred_variance_6d": 0.08143599348127124, + "pred_gt_ratio": 0.44022550853086195 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.17591510017264494, + "pred_variance_6d": 0.06626689273941636, + "pred_gt_ratio": 0.37669814970051646 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.06181170335264618, + "pred_variance_6d": 0.025064700145397974, + "pred_gt_ratio": 0.40550088067302786 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.48520380553723685, + "pred_variance_6d": 0.15399914089102354, + "pred_gt_ratio": 0.3173906287080943 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2749259641279063, + "pred_variance_6d": 0.0668223201363105, + "pred_gt_ratio": 0.24305569082308331 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.18181540568994045, + "pred_variance_6d": 0.05286694112587941, + "pred_gt_ratio": 0.29077261591372644 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.2343304679990655, + "pred_variance_6d": 0.09291939224316453, + "pred_gt_ratio": 0.39653141581032086 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.24823855156388863, + "pred_variance_6d": 0.09054578116725373, + "pred_gt_ratio": 0.3647530997776957 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.0652150158232389, + "pred_variance_6d": 0.032719197088855845, + "pred_gt_ratio": 0.5017126297651928 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.13684319564689476, + "pred_variance_6d": 0.06455521460985017, + "pred_gt_ratio": 0.47174588626551894 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.11868189348606356, + "pred_variance_6d": 0.048680471413291806, + "pred_gt_ratio": 0.4101760595773457 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1828, + "gt_variance_6d": 0.1759020250807575, + "pred_variance_6d": 0.08802883038054445, + "pred_gt_ratio": 0.5004423930885956 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.9101462201961528, + "pred_variance_6d": 0.8304836298001652, + "pred_gt_ratio": 0.9124727558844129 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.21365722111186325, + "pred_variance_6d": 0.0778889176102309, + "pred_gt_ratio": 0.3645508314902732 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18926917560471376, + "pred_variance_6d": 0.10507918338362601, + "pred_gt_ratio": 0.5551838171635646 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14613903441426507, + "pred_variance_6d": 0.050054703269609147, + "pred_gt_ratio": 0.34251426027434567 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2583566611716799, + "pred_variance_6d": 0.11158157821410877, + "pred_gt_ratio": 0.431889689656432 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.18678808384059908, + "pred_variance_6d": 0.08400516595218854, + "pred_gt_ratio": 0.449735144902909 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07952837254109431, + "pred_variance_6d": 0.033289278826837576, + "pred_gt_ratio": 0.41858367980101907 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.4996390591174059, + "pred_variance_6d": 0.2501145930671974, + "pred_gt_ratio": 0.5005905533266668 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.22379709478908846, + "pred_variance_6d": 0.08246288529182337, + "pred_gt_ratio": 0.368471652277427 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14773829719745404, + "pred_variance_6d": 0.06180553788925193, + "pred_gt_ratio": 0.41834472890023955 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.2945443603939768, + "pred_variance_6d": 0.13805592576133296, + "pred_gt_ratio": 0.4687101310535094 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.25151218340149883, + "pred_variance_6d": 0.10699049132094317, + "pred_gt_ratio": 0.4253889011418187 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.07535130472881144, + "pred_variance_6d": 0.038968683906107617, + "pred_gt_ratio": 0.5171600418381009 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.1331221242401221, + "pred_variance_6d": 0.07676393390327788, + "pred_gt_ratio": 0.5766429460276127 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.14755590450729988, + "pred_variance_6d": 0.06109629966624626, + "pred_gt_ratio": 0.4140552685455139 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1745, + "gt_variance_6d": 0.19342181043223353, + "pred_variance_6d": 0.09798798449085426, + "pred_gt_ratio": 0.5066025608584867 + } + ] + } + } + } + }, + "normal": { + "hands": 1039, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 545, + "variance": 1.0827241385159592 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 545, + "variance": 0.12400796906680656 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 545, + "variance": 0.07354481761372055 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 545, + "variance": 0.09381512691794847 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 545, + "variance": 0.1267101769167171 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 545, + "variance": 0.08075673841413365 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 545, + "variance": 0.03143736772576662 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 545, + "variance": 0.4911503904937964 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 545, + "variance": 0.2142312218545364 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 545, + "variance": 0.1355850701279912 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 545, + "variance": 0.186007061146542 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 545, + "variance": 0.1014455657894766 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 545, + "variance": 0.024940999180766 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 545, + "variance": 0.14941141870907892 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 545, + "variance": 0.14445662430848943 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 545, + "variance": 0.18846841823407084 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 494, + "variance": 0.9023800950488734 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 494, + "variance": 0.24763924205574364 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 494, + "variance": 0.09071934710965093 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 494, + "variance": 0.14796302500045028 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 494, + "variance": 0.24470360564125565 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 494, + "variance": 0.07247421520685057 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 494, + "variance": 0.03884170855571756 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 494, + "variance": 0.4407256699754486 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 494, + "variance": 0.14405031509129812 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 494, + "variance": 0.089153279742193 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 494, + "variance": 0.24252463324047752 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 494, + "variance": 0.08484108365834611 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 494, + "variance": 0.03429392078633288 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 494, + "variance": 0.1723511395250014 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 494, + "variance": 0.22195927830866272 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 494, + "variance": 0.24691242579776249 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 49.36649959332904, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 22.758902805831365, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 49.282017397582244, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.629668909727984, + "count": 987 + }, + "local_pose_angle_deg": { + "mean": 14.036746979218703, + "count": 1039 + }, + "root_relative_fingertip_mm": { + "mean": 32.28058153442515, + "count": 1039 + }, + "distal_angle_bias_deg": { + "mean": 1.6770096656734605, + "count": 1039 + }, + "distal_angle_mae_deg": { + "mean": 7.367876557688855, + "count": 1039 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.30436464168913, + 9.918093604119038, + 10.809532189965822, + 14.019094580176706, + 11.310527948431377, + 6.856722158577949, + 25.780867560077333, + 20.266277028116846, + 14.579996284495419, + 14.507325454269957, + 13.45159145056685, + 6.996299121618501, + 15.646021942087271, + 14.79519435944066, + 18.309285134048388 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5455682625815981, + "mean_abs_log_variance_ratio": 0.6860176210996016, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 545, + "gt_variance_6d": 1.0827241385159592, + "pred_variance_6d": 0.8953476791165637, + "pred_gt_ratio": 0.8269397968200617 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.12400796906680656, + "pred_variance_6d": 0.061577646494260396, + "pred_gt_ratio": 0.49656201095501207 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.07354481761372055, + "pred_variance_6d": 0.044875696410129874, + "pred_gt_ratio": 0.6101816262001015 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.09381512691794847, + "pred_variance_6d": 0.03678271075736603, + "pred_gt_ratio": 0.39207654421803967 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1267101769167171, + "pred_variance_6d": 0.06505495228931318, + "pred_gt_ratio": 0.5134153694069254 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.08075673841413365, + "pred_variance_6d": 0.05093717586982474, + "pred_gt_ratio": 0.6307483049725292 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.03143736772576662, + "pred_variance_6d": 0.014867446202436711, + "pred_gt_ratio": 0.4729227437910169 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.4911503904937964, + "pred_variance_6d": 0.16122896152544175, + "pred_gt_ratio": 0.3282680104628324 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.2142312218545364, + "pred_variance_6d": 0.0490300842830636, + "pred_gt_ratio": 0.22886525996829335 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1355850701279912, + "pred_variance_6d": 0.03790609439349878, + "pred_gt_ratio": 0.2795742507468982 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.186007061146542, + "pred_variance_6d": 0.09539841454624765, + "pred_gt_ratio": 0.5128752315004315 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1014455657894766, + "pred_variance_6d": 0.047821377631822794, + "pred_gt_ratio": 0.47139938803302056 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.024940999180766, + "pred_variance_6d": 0.01779235326364683, + "pred_gt_ratio": 0.7133777253546416 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14941141870907892, + "pred_variance_6d": 0.08539608596756264, + "pred_gt_ratio": 0.571549930422912 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14445662430848943, + "pred_variance_6d": 0.06371558106962355, + "pred_gt_ratio": 0.4410706769220767 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.18846841823407084, + "pred_variance_6d": 0.12273475856113308, + "pred_gt_ratio": 0.6512218848714538 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 494, + "gt_variance_6d": 0.9023800950488734, + "pred_variance_6d": 0.7630330607333655, + "pred_gt_ratio": 0.8455783376871131 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24763924205574364, + "pred_variance_6d": 0.07885092639794655, + "pred_gt_ratio": 0.31841046573788656 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.09071934710965093, + "pred_variance_6d": 0.10553963164798777, + "pred_gt_ratio": 1.1633641004980317 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14796302500045028, + "pred_variance_6d": 0.046746211387104296, + "pred_gt_ratio": 0.3159317092020931 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24470360564125565, + "pred_variance_6d": 0.0766063775102613, + "pred_gt_ratio": 0.31305782074404337 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.07247421520685057, + "pred_variance_6d": 0.07195162016417103, + "pred_gt_ratio": 0.9927892279869746 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03884170855571756, + "pred_variance_6d": 0.021323064506233926, + "pred_gt_ratio": 0.5489733922401088 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.4407256699754486, + "pred_variance_6d": 0.21934781502513687, + "pred_gt_ratio": 0.4976969347788524 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14405031509129812, + "pred_variance_6d": 0.06678113866732549, + "pred_gt_ratio": 0.4635959221956582 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.089153279742193, + "pred_variance_6d": 0.04611902559163075, + "pred_gt_ratio": 0.5173003811524871 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24252463324047752, + "pred_variance_6d": 0.1054206529452027, + "pred_gt_ratio": 0.4346801870664902 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.08484108365834611, + "pred_variance_6d": 0.08022340295653962, + "pred_gt_ratio": 0.9455725869744683 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03429392078633288, + "pred_variance_6d": 0.01998335433565871, + "pred_gt_ratio": 0.582708359891665 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.1723511395250014, + "pred_variance_6d": 0.09556248635568798, + "pred_gt_ratio": 0.5544639079211056 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.22195927830866272, + "pred_variance_6d": 0.07726878808860468, + "pred_gt_ratio": 0.3481214602849473 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24691242579776249, + "pred_variance_6d": 0.11725645265227867, + "pred_gt_ratio": 0.47489085360296696 + } + ] + } + }, + "N1_20K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 49.29615738761322, + "count": 1039 + }, + "root_relative_mpjpe_mm": { + "mean": 22.697564931416075, + "count": 1039 + }, + "mpvpe_mm": { + "mean": 49.218017840637856, + "count": 1039 + }, + "projected_mano_2d_error_px": { + "mean": 14.649897972259598, + "count": 987 + }, + "local_pose_angle_deg": { + "mean": 14.364079886611776, + "count": 1039 + }, + "root_relative_fingertip_mm": { + "mean": 32.3393541736254, + "count": 1039 + }, + "distal_angle_bias_deg": { + "mean": 2.705947001784667, + "count": 1039 + }, + "distal_angle_mae_deg": { + "mean": 7.836842174479546, + "count": 1039 + }, + "gt60_angle_bias_deg": { + "mean": null, + "count": 0 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.360513500259746, + 10.074553028337077, + 10.735440362520924, + 14.029951980873527, + 11.769702012918682, + 7.122504157355706, + 26.618655981010146, + 21.550113148478157, + 15.09055422394177, + 14.75166823395866, + 14.564714831670278, + 7.269921500884764, + 15.481451897149595, + 14.693529558480073, + 18.347912344540163 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.07034220571582196, + "recording_bootstrap_95ci": [ + -0.7823718126839329, + 0.6233052254227416 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_mpjpe_mm": { + "delta": -0.061337874415290254, + "recording_bootstrap_95ci": [ + -0.3720151605753777, + 0.20634703542421556 + ], + "count": 1039, + "recordings": 30 + }, + "mpvpe_mm": { + "delta": -0.06399955694439093, + "recording_bootstrap_95ci": [ + -0.7738089969437969, + 0.6207500996917907 + ], + "count": 1039, + "recordings": 30 + }, + "projected_mano_2d_error_px": { + "delta": 0.020229062531615223, + "recording_bootstrap_95ci": [ + -0.3650519856881911, + 0.43792743059920136 + ], + "count": 987, + "recordings": 30 + }, + "local_pose_angle_deg": { + "delta": 0.32733290739307275, + "recording_bootstrap_95ci": [ + 0.21527701008816555, + 0.4528834891318464 + ], + "count": 1039, + "recordings": 30 + }, + "root_relative_fingertip_mm": { + "delta": 0.058772639200249124, + "recording_bootstrap_95ci": [ + -0.47887679207227674, + 0.4905262341973759 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_bias_deg": { + "delta": 1.0289373361112064, + "recording_bootstrap_95ci": [ + 0.8210576229568014, + 1.2515165617289878 + ], + "count": 1039, + "recordings": 30 + }, + "distal_angle_mae_deg": { + "delta": 0.4689656167906907, + "recording_bootstrap_95ci": [ + 0.3267298327385505, + 0.6352382733722247 + ], + "count": 1039, + "recordings": 30 + }, + "gt60_angle_bias_deg": { + "delta": null, + "recording_bootstrap_95ci": null, + "count": 0, + "recordings": 0 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.5936819383608447, + "mean_abs_log_variance_ratio": 0.6146344357104483, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 545, + "gt_variance_6d": 1.0827241385159592, + "pred_variance_6d": 0.8988485883715606, + "pred_gt_ratio": 0.8301732236279239 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.12400796906680656, + "pred_variance_6d": 0.06407995179044715, + "pred_gt_ratio": 0.5167405955654792 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.07354481761372055, + "pred_variance_6d": 0.04959162840626367, + "pred_gt_ratio": 0.674304866275334 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.09381512691794847, + "pred_variance_6d": 0.04166985919075919, + "pred_gt_ratio": 0.444169938896997 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1267101769167171, + "pred_variance_6d": 0.06550944764011313, + "pred_gt_ratio": 0.5170022584939691 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.08075673841413365, + "pred_variance_6d": 0.05899130799224696, + "pred_gt_ratio": 0.7304815567182761 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.03143736772576662, + "pred_variance_6d": 0.018683376469584918, + "pred_gt_ratio": 0.594304734180136 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.4911503904937964, + "pred_variance_6d": 0.16933255027156446, + "pred_gt_ratio": 0.3447672109174537 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.2142312218545364, + "pred_variance_6d": 0.05624424011561508, + "pred_gt_ratio": 0.262539883910129 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1355850701279912, + "pred_variance_6d": 0.04405410041936146, + "pred_gt_ratio": 0.3249185207322218 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.186007061146542, + "pred_variance_6d": 0.09776372092446639, + "pred_gt_ratio": 0.5255914497108536 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.1014455657894766, + "pred_variance_6d": 0.0584446674925665, + "pred_gt_ratio": 0.5761185029403151 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.024940999180766, + "pred_variance_6d": 0.021893664563449954, + "pred_gt_ratio": 0.8778182624028114 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14941141870907892, + "pred_variance_6d": 0.08831384503765512, + "pred_gt_ratio": 0.5910782843820809 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 545, + "gt_variance_6d": 0.14445662430848943, + "pred_variance_6d": 0.06725681004413606, + "pred_gt_ratio": 0.4655848104307634 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 545, + "gt_variance_6d": 0.18846841823407084, + "pred_variance_6d": 0.12907681955362488, + "pred_gt_ratio": 0.6848724086669853 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 494, + "gt_variance_6d": 0.9023800950488734, + "pred_variance_6d": 0.7782266169031876, + "pred_gt_ratio": 0.8624155399405595 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24763924205574364, + "pred_variance_6d": 0.08195308262710331, + "pred_gt_ratio": 0.3309373827297358 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.09071934710965093, + "pred_variance_6d": 0.11038431765456697, + "pred_gt_ratio": 1.2167671083561407 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14796302500045028, + "pred_variance_6d": 0.0530850999372377, + "pred_gt_ratio": 0.35877274026450967 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24470360564125565, + "pred_variance_6d": 0.07841211900495086, + "pred_gt_ratio": 0.3204371214697419 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.07247421520685057, + "pred_variance_6d": 0.07896816566026514, + "pred_gt_ratio": 1.089603598119414 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03884170855571756, + "pred_variance_6d": 0.02278110215195617, + "pred_gt_ratio": 0.5865113301923162 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.4407256699754486, + "pred_variance_6d": 0.22398242804602336, + "pred_gt_ratio": 0.5082128028950542 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.14405031509129812, + "pred_variance_6d": 0.0728644932430121, + "pred_gt_ratio": 0.5058266842167688 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.089153279742193, + "pred_variance_6d": 0.052085893486664966, + "pred_gt_ratio": 0.5842285739490817 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24252463324047752, + "pred_variance_6d": 0.10974099156925325, + "pred_gt_ratio": 0.4524942068892382 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.08484108365834611, + "pred_variance_6d": 0.09210934351478511, + "pred_gt_ratio": 1.085669106793923 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.03429392078633288, + "pred_variance_6d": 0.023067104130817646, + "pred_gt_ratio": 0.6726295390526054 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 494, + "gt_variance_6d": 0.1723511395250014, + "pred_variance_6d": 0.09946039151180078, + "pred_gt_ratio": 0.5770799762967217 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 494, + "gt_variance_6d": 0.22195927830866272, + "pred_variance_6d": 0.0834192354117474, + "pred_gt_ratio": 0.375831260794344 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 494, + "gt_variance_6d": 0.24691242579776249, + "pred_variance_6d": 0.12591016382907338, + "pred_gt_ratio": 0.5099385477351476 + } + ] + } + } + } + }, + "hard": { + "hands": 2534, + "gt_variance_6d": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1283, + "variance": 0.8231272433561402 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1283, + "variance": 0.15409708922232784 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1283, + "variance": 0.08717469219770257 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1283, + "variance": 0.09250426057328964 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1283, + "variance": 0.19332078185401297 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1283, + "variance": 0.13481498840208778 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1283, + "variance": 0.05009253551874426 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1283, + "variance": 0.4768318135394507 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1283, + "variance": 0.24299048153455496 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1283, + "variance": 0.15811544472841882 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1283, + "variance": 0.24887416488884723 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1283, + "variance": 0.19186471184797532 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1283, + "variance": 0.05322111639171685 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1283, + "variance": 0.12319734347700959 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1283, + "variance": 0.09743079736570204 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1283, + "variance": 0.1606695633471843 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1251, + "variance": 0.9115786538600362 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1251, + "variance": 0.1962898913910759 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1251, + "variance": 0.16412110852660775 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1251, + "variance": 0.13664942506817684 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1251, + "variance": 0.2594089839097105 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1251, + "variance": 0.1499002076022079 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1251, + "variance": 0.0726948825070978 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1251, + "variance": 0.518760522291538 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1251, + "variance": 0.2096864259618268 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1251, + "variance": 0.13670665100539392 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1251, + "variance": 0.3108960965839195 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1251, + "variance": 0.2086624728401734 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1251, + "variance": 0.06997302916388579 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1251, + "variance": 0.10937821422775133 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1251, + "variance": 0.10469939868574002 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1251, + "variance": 0.16128650383730753 + } + ], + "models": { + "U0_parent": { + "means": { + "absolute_mpjpe_mm": { + "mean": 54.60922134496513, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 24.396859338364454, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 54.2703544500783, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 14.812183809528964, + "count": 2302 + }, + "local_pose_angle_deg": { + "mean": 14.947253651758208, + "count": 2534 + }, + "root_relative_fingertip_mm": { + "mean": 33.851286499351616, + "count": 2534 + }, + "distal_angle_bias_deg": { + "mean": -6.0267711125473005, + "count": 2534 + }, + "distal_angle_mae_deg": { + "mean": 10.418510652708084, + "count": 2534 + }, + "gt60_angle_bias_deg": { + "mean": -16.777784632594997, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.728343272712538, + 12.464442220723056, + 12.763789765672037, + 14.886660749741022, + 14.161405509206942, + 9.14844404335039, + 24.06639622638756, + 23.33015968499451, + 16.22626544832713, + 15.327895962989697, + 16.51893534932959, + 9.51863280973664, + 13.135428017109703, + 12.340295003287512, + 16.591698910508835 + ], + "paired_to_parent": null, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4410767545268288, + "mean_abs_log_variance_ratio": 0.8629221523731494, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.8231272433561402, + "pred_variance_6d": 0.7585274242218907, + "pred_gt_ratio": 0.9215190365090379 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15409708922232784, + "pred_variance_6d": 0.0705914066267044, + "pred_gt_ratio": 0.4580969503249779 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.08717469219770257, + "pred_variance_6d": 0.05250806351717904, + "pred_gt_ratio": 0.6023315046309146 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09250426057328964, + "pred_variance_6d": 0.02470050209262366, + "pred_gt_ratio": 0.2670201560397734 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19332078185401297, + "pred_variance_6d": 0.08006759030302017, + "pred_gt_ratio": 0.4141695969525075 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.13481498840208778, + "pred_variance_6d": 0.05962038064185585, + "pred_gt_ratio": 0.4422385177532126 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05009253551874426, + "pred_variance_6d": 0.023079303079932105, + "pred_gt_ratio": 0.46073337755674193 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.4768318135394507, + "pred_variance_6d": 0.14170561220315103, + "pred_gt_ratio": 0.29718153902377364 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24299048153455496, + "pred_variance_6d": 0.06190454399766296, + "pred_gt_ratio": 0.25476118902566847 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15811544472841882, + "pred_variance_6d": 0.046063952203255626, + "pred_gt_ratio": 0.2913311364514433 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24887416488884723, + "pred_variance_6d": 0.08816876237597085, + "pred_gt_ratio": 0.35427044994947143 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19186471184797532, + "pred_variance_6d": 0.08543158470540552, + "pred_gt_ratio": 0.44526991900989865 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05322111639171685, + "pred_variance_6d": 0.030139746356839567, + "pred_gt_ratio": 0.5663118025372803 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.12319734347700959, + "pred_variance_6d": 0.0489196915000083, + "pred_gt_ratio": 0.39708398021697133 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09743079736570204, + "pred_variance_6d": 0.036779728204714694, + "pred_gt_ratio": 0.3774959170934799 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.1606695633471843, + "pred_variance_6d": 0.06222293875377527, + "pred_gt_ratio": 0.3872727195960585 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.9115786538600362, + "pred_variance_6d": 0.830237802939764, + "pred_gt_ratio": 0.910769245664279 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1962898913910759, + "pred_variance_6d": 0.062203777135776246, + "pred_gt_ratio": 0.31689750651420595 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16412110852660775, + "pred_variance_6d": 0.08120921166890019, + "pred_gt_ratio": 0.494812717254675 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13664942506817684, + "pred_variance_6d": 0.04434015799077859, + "pred_gt_ratio": 0.3244811163212468 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2594089839097105, + "pred_variance_6d": 0.10307450476863624, + "pred_gt_ratio": 0.3973436201597096 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1499002076022079, + "pred_variance_6d": 0.06333265616994943, + "pred_gt_ratio": 0.42249878891439635 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.0726948825070978, + "pred_variance_6d": 0.030360468685222058, + "pred_gt_ratio": 0.4176424479709107 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.518760522291538, + "pred_variance_6d": 0.23888357499093085, + "pred_gt_ratio": 0.4604891172822915 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2096864259618268, + "pred_variance_6d": 0.06929863469823777, + "pred_gt_ratio": 0.3304869849365143 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13670665100539392, + "pred_variance_6d": 0.05115017639741009, + "pred_gt_ratio": 0.37416011599458976 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.3108960965839195, + "pred_variance_6d": 0.12850179361118874, + "pred_gt_ratio": 0.4133271373399265 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2086624728401734, + "pred_variance_6d": 0.07755291691419672, + "pred_gt_ratio": 0.3716668160719008 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.06997302916388579, + "pred_variance_6d": 0.03378604098024014, + "pred_gt_ratio": 0.4828437668620707 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10937821422775133, + "pred_variance_6d": 0.06040094124277372, + "pred_gt_ratio": 0.5522209488354295 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10469939868574002, + "pred_variance_6d": 0.044072109593335844, + "pred_gt_ratio": 0.42093947192209075 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16128650383730753, + "pred_variance_6d": 0.07851242336060807, + "pred_gt_ratio": 0.48678855014307276 + } + ] + } + }, + "N1_20K": { + "means": { + "absolute_mpjpe_mm": { + "mean": 54.34487365678999, + "count": 2534 + }, + "root_relative_mpjpe_mm": { + "mean": 24.450407045510403, + "count": 2534 + }, + "mpvpe_mm": { + "mean": 54.0208688521818, + "count": 2534 + }, + "projected_mano_2d_error_px": { + "mean": 14.539379788832909, + "count": 2302 + }, + "local_pose_angle_deg": { + "mean": 14.73756907469848, + "count": 2534 + }, + "root_relative_fingertip_mm": { + "mean": 33.82352691893514, + "count": 2534 + }, + "distal_angle_bias_deg": { + "mean": -4.875388389487105, + "count": 2534 + }, + "distal_angle_mae_deg": { + "mean": 10.102557956749, + "count": 2534 + }, + "gt60_angle_bias_deg": { + "mean": -15.51311545105631, + "count": 1860 + } + }, + "local_pose_per_joint_mean_deg": [ + 13.837880176698588, + 12.21353522046001, + 12.380003551893001, + 14.718140019578735, + 13.733896691119849, + 8.65067778146681, + 24.339260400235418, + 23.07281746435984, + 15.781204591398646, + 15.234546021462052, + 15.97012212881914, + 9.099386022847378, + 13.12807009887206, + 12.369823207677399, + 16.534161133990104 + ], + "paired_to_parent": { + "absolute_mpjpe_mm": { + "delta": -0.26434768817513216, + "recording_bootstrap_95ci": [ + -1.0786028777048327, + 0.38642682035420195 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_mpjpe_mm": { + "delta": 0.05354770714594985, + "recording_bootstrap_95ci": [ + -0.22038123550141955, + 0.3038212817766203 + ], + "count": 2534, + "recordings": 31 + }, + "mpvpe_mm": { + "delta": -0.24948559789650065, + "recording_bootstrap_95ci": [ + -1.0606388623457548, + 0.40038375005511656 + ], + "count": 2534, + "recordings": 31 + }, + "projected_mano_2d_error_px": { + "delta": -0.272804020696055, + "recording_bootstrap_95ci": [ + -0.5976199545130545, + 0.02815712311567767 + ], + "count": 2302, + "recordings": 31 + }, + "local_pose_angle_deg": { + "delta": -0.20968457705972698, + "recording_bootstrap_95ci": [ + -0.3122724423710833, + -0.11602948657597965 + ], + "count": 2534, + "recordings": 31 + }, + "root_relative_fingertip_mm": { + "delta": -0.027759580416479916, + "recording_bootstrap_95ci": [ + -0.42887069831471414, + 0.32393065319100106 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_bias_deg": { + "delta": 1.1513827230601963, + "recording_bootstrap_95ci": [ + 0.9372855231346078, + 1.3630395657507954 + ], + "count": 2534, + "recordings": 31 + }, + "distal_angle_mae_deg": { + "delta": -0.31595269595908665, + "recording_bootstrap_95ci": [ + -0.47760265749941816, + -0.16401047244161251 + ], + "count": 2534, + "recordings": 31 + }, + "gt60_angle_bias_deg": { + "delta": 1.2646691815386857, + "recording_bootstrap_95ci": [ + 0.9570686690311805, + 1.5861683819734078 + ], + "count": 1860, + "recordings": 31 + } + }, + "rotation_variance": { + "pred_gt_variance_ratio_macro": 0.4620474230103778, + "mean_abs_log_variance_ratio": 0.814357563450438, + "per_joint_side": [ + { + "joint": 0, + "name": "wrist", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.8231272433561402, + "pred_variance_6d": 0.7608676221475107, + "pred_gt_ratio": 0.9243620938182314 + }, + { + "joint": 1, + "name": "index_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15409708922232784, + "pred_variance_6d": 0.07163619362432322, + "pred_gt_ratio": 0.4648770069950388 + }, + { + "joint": 2, + "name": "index_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.08717469219770257, + "pred_variance_6d": 0.05358466701836533, + "pred_gt_ratio": 0.6146814593487893 + }, + { + "joint": 3, + "name": "index_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09250426057328964, + "pred_variance_6d": 0.027622901900161825, + "pred_gt_ratio": 0.29861221233455126 + }, + { + "joint": 4, + "name": "middle_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19332078185401297, + "pred_variance_6d": 0.08002406287161407, + "pred_gt_ratio": 0.41394444044843864 + }, + { + "joint": 5, + "name": "middle_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.13481498840208778, + "pred_variance_6d": 0.05935840435177123, + "pred_gt_ratio": 0.440295289532154 + }, + { + "joint": 6, + "name": "middle_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05009253551874426, + "pred_variance_6d": 0.024676177109365708, + "pred_gt_ratio": 0.4926118603066531 + }, + { + "joint": 7, + "name": "little_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.4768318135394507, + "pred_variance_6d": 0.14201014401702658, + "pred_gt_ratio": 0.2978201956847356 + }, + { + "joint": 8, + "name": "little_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24299048153455496, + "pred_variance_6d": 0.06233573256704763, + "pred_gt_ratio": 0.2565356970914231 + }, + { + "joint": 9, + "name": "little_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.15811544472841882, + "pred_variance_6d": 0.04880126776585394, + "pred_gt_ratio": 0.3086432691611856 + }, + { + "joint": 10, + "name": "ring_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.24887416488884723, + "pred_variance_6d": 0.08602337179070024, + "pred_gt_ratio": 0.34565006708960816 + }, + { + "joint": 11, + "name": "ring_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.19186471184797532, + "pred_variance_6d": 0.08695602626817966, + "pred_gt_ratio": 0.45321531734860954 + }, + { + "joint": 12, + "name": "ring_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.05322111639171685, + "pred_variance_6d": 0.03268152342165977, + "pred_gt_ratio": 0.6140706102652557 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.12319734347700959, + "pred_variance_6d": 0.05052000636744054, + "pred_gt_ratio": 0.4100738290421685 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.09743079736570204, + "pred_variance_6d": 0.03788156047867717, + "pred_gt_ratio": 0.3888047876329131 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "left", + "count": 1283, + "gt_variance_6d": 0.1606695633471843, + "pred_variance_6d": 0.06581056649560484, + "pred_gt_ratio": 0.4096019502673165 + }, + { + "joint": 0, + "name": "wrist", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.9115786538600362, + "pred_variance_6d": 0.847672401401875, + "pred_gt_ratio": 0.9298949660706147 + }, + { + "joint": 1, + "name": "index_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1962898913910759, + "pred_variance_6d": 0.0650686995541426, + "pred_gt_ratio": 0.331492870534549 + }, + { + "joint": 2, + "name": "index_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16412110852660775, + "pred_variance_6d": 0.08524800486037623, + "pred_gt_ratio": 0.5194213323666139 + }, + { + "joint": 3, + "name": "index_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13664942506817684, + "pred_variance_6d": 0.04740870517712559, + "pred_gt_ratio": 0.3469367335681986 + }, + { + "joint": 4, + "name": "middle_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2594089839097105, + "pred_variance_6d": 0.11121302063992289, + "pred_gt_ratio": 0.4287169201458016 + }, + { + "joint": 5, + "name": "middle_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.1499002076022079, + "pred_variance_6d": 0.06710646998876868, + "pred_gt_ratio": 0.44767429653499863 + }, + { + "joint": 6, + "name": "middle_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.0726948825070978, + "pred_variance_6d": 0.03196342776903423, + "pred_gt_ratio": 0.43969295590942564 + }, + { + "joint": 7, + "name": "little_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.518760522291538, + "pred_variance_6d": 0.24262964901211398, + "pred_gt_ratio": 0.46771031831862997 + }, + { + "joint": 8, + "name": "little_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2096864259618268, + "pred_variance_6d": 0.07347694509789676, + "pred_gt_ratio": 0.3504134555246469 + }, + { + "joint": 9, + "name": "little_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.13670665100539392, + "pred_variance_6d": 0.058003692932110766, + "pred_gt_ratio": 0.4242931306233386 + }, + { + "joint": 10, + "name": "ring_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.3108960965839195, + "pred_variance_6d": 0.13715808267826635, + "pred_gt_ratio": 0.4411701664489814 + }, + { + "joint": 11, + "name": "ring_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.2086624728401734, + "pred_variance_6d": 0.08923383040515963, + "pred_gt_ratio": 0.4276467598153548 + }, + { + "joint": 12, + "name": "ring_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.06997302916388579, + "pred_variance_6d": 0.037358622717225495, + "pred_gt_ratio": 0.5339003207896977 + }, + { + "joint": 13, + "name": "thumb_1", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10937821422775133, + "pred_variance_6d": 0.0631681607735196, + "pred_gt_ratio": 0.5775204982044096 + }, + { + "joint": 14, + "name": "thumb_2", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.10469939868574002, + "pred_variance_6d": 0.04887253450690894, + "pred_gt_ratio": 0.4667890658436546 + }, + { + "joint": 15, + "name": "thumb_3", + "side": "right", + "count": 1251, + "gt_variance_6d": 0.16128650383730753, + "pred_variance_6d": 0.08361796523965048, + "pred_gt_ratio": 0.5184436592661055 + } + ] + } + } + } + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/pose_precision_n1_18k.json b/home/wuyifan/EgoNet_train_20261008/reports/pose_precision_n1_18k.json new file mode 100644 index 0000000000000000000000000000000000000000..51c9a85578ee01d197116b7ff5c39ec4ee750553 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/pose_precision_n1_18k.json @@ -0,0 +1,164 @@ +{ + "checkpoint": "/data-hdd/jiasen_rescue_20260815/.tmp/pose_delta_ablation_20261002/n1_update_0018000.pt", + "rows": { + "ARCTIC": { + "position": 0, + "valid_pose_rotations": 256, + "gt_orthogonality_fp32": { + "count": 256, + "mean": 1.332149963673146e-07, + "p50": 1.2859335640769132e-07, + "p95": 2.7115359557683405e-07, + "max": 5.88548687119328e-07 + }, + "gt_orthogonality_autocast": { + "count": 256, + "mean": 0.002155477413907647, + "p50": 0.0013082749210298061, + "p95": 0.0076102688908576965, + "max": 0.015150254592299461 + }, + "gt_autocast_vs_fp32_normalized_6d_l1": { + "count": 256, + "mean": 0.002108708955347538, + "p50": 0.0010912406723946333, + "p95": 0.007140062749385834, + "max": 0.015750844031572342 + }, + "pred_raw_first_norm": { + "count": 256, + "mean": 0.9482289552688599, + "p50": 0.9745265245437622, + "p95": 1.5954136848449707, + "max": 1.8780015707015991 + }, + "pred_raw_orthogonal_second_norm": { + "count": 256, + "mean": 1.0258047580718994, + "p50": 0.9498828649520874, + "p95": 1.599087119102478, + "max": 1.6900242567062378 + }, + "pred_matrix_autocast_orthogonality": { + "count": 256, + "mean": 1.4942176562726672e-07, + "p50": 1.4150273841551098e-07, + "p95": 2.94190613203682e-07, + "max": 4.1419465901526564e-07 + }, + "pred_matrix_autocast_vs_fp32": { + "count": 256, + "mean": 0.0, + "p50": 0.0, + "p95": 0.0, + "max": 0.0 + } + }, + "H2O": { + "position": 1, + "valid_pose_rotations": 256, + "gt_orthogonality_fp32": { + "count": 256, + "mean": 1.1817007816716796e-07, + "p50": 1.1955938816754497e-07, + "p95": 2.518479220725567e-07, + "max": 4.040555836581916e-07 + }, + "gt_orthogonality_autocast": { + "count": 256, + "mean": 0.002088294131681323, + "p50": 0.001161309308372438, + "p95": 0.005454307422041893, + "max": 0.024891342967748642 + }, + "gt_autocast_vs_fp32_normalized_6d_l1": { + "count": 256, + "mean": 0.0013948887353762984, + "p50": 0.0010148461442440748, + "p95": 0.004243075381964445, + "max": 0.007635227870196104 + }, + "pred_raw_first_norm": { + "count": 256, + "mean": 1.28480863571167, + "p50": 1.2651646137237549, + "p95": 1.7897858619689941, + "max": 1.9197301864624023 + }, + "pred_raw_orthogonal_second_norm": { + "count": 256, + "mean": 1.6736400127410889, + "p50": 1.5648844242095947, + "p95": 2.6648097038269043, + "max": 3.5529520511627197 + }, + "pred_matrix_autocast_orthogonality": { + "count": 256, + "mean": 1.4624779964833579e-07, + "p50": 1.3850826974248776e-07, + "p95": 2.8556524966916186e-07, + "max": 3.8499044308082375e-07 + }, + "pred_matrix_autocast_vs_fp32": { + "count": 256, + "mean": 0.0, + "p50": 0.0, + "p95": 0.0, + "max": 0.0 + } + }, + "HOT3D": { + "position": 2, + "valid_pose_rotations": 256, + "gt_orthogonality_fp32": { + "count": 256, + "mean": 1.1516003439737688e-07, + "p50": 1.1354497075899417e-07, + "p95": 2.637886211687146e-07, + "max": 5.674193062077393e-07 + }, + "gt_orthogonality_autocast": { + "count": 256, + "mean": 0.0015457661356776953, + "p50": 0.0005560035351663828, + "p95": 0.0061336406506598, + "max": 0.028093989938497543 + }, + "gt_autocast_vs_fp32_normalized_6d_l1": { + "count": 256, + "mean": 0.0008010320598259568, + "p50": 0.0004123893741052598, + "p95": 0.0028977508191019297, + "max": 0.006935374345630407 + }, + "pred_raw_first_norm": { + "count": 256, + "mean": 1.597764492034912, + "p50": 1.560282826423645, + "p95": 2.0554583072662354, + "max": 2.2121243476867676 + }, + "pred_raw_orthogonal_second_norm": { + "count": 256, + "mean": 2.1027908325195312, + "p50": 1.998534917831421, + "p95": 3.684222936630249, + "max": 3.9354894161224365 + }, + "pred_matrix_autocast_orthogonality": { + "count": 256, + "mean": 1.3858709735359298e-07, + "p50": 1.3530859632737702e-07, + "p95": 2.7561716819946014e-07, + "max": 3.588384913655318e-07 + }, + "pred_matrix_autocast_vs_fp32": { + "count": 256, + "mean": 0.0, + "p50": 0.0, + "p95": 0.0, + "max": 0.0 + } + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/reports/training_gt_contract_10_tiles_per_source.json b/home/wuyifan/EgoNet_train_20261008/reports/training_gt_contract_10_tiles_per_source.json new file mode 100644 index 0000000000000000000000000000000000000000..0c93f42e4cd5b413aed334c44c2679592fd9eec3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/reports/training_gt_contract_10_tiles_per_source.json @@ -0,0 +1,194 @@ +{ + "sample": "ten evenly spread registered training tiles per source", + "sources": { + "H2O": { + "tile_count": 10, + "tile_ids": [ + "1a0411b79c50842e39d45b42:52", + "190fd760cb4cb156d76ce231:48", + "2ab7272c90c73bb59a775564:51", + "c30308beaaa8b32b52c21203:8", + "241ec367e677298677fa8c09:32", + "d8268fca7bb675318198fd73:8", + "2a70eb568925204312daf44c:0", + "9978933e1bc58b64c7f8ac4e:8", + "c998c7d9e0ea7723aa22d2c7:24", + "2571a3ec1fffcb68addeb374:24" + ], + "valid_counts": { + "hands_pose": 160, + "joints_3d": 3360, + "joints_2d": 3360, + "nonpositive_gt_z": 0 + }, + "statistics": { + "z_m": { + "count": 3360, + "mean": 0.48380666971206665, + "p05": 0.3113947808742523, + "p95": 0.6521764397621155, + "min": 0.20262162387371063, + "max": 0.6826578974723816 + }, + "wrist_vs_root_mm": { + "count": 160, + "mean": 0.0, + "p05": 0.0, + "p95": 0.0, + "min": 0.0, + "max": 0.0 + }, + "rotation_orthogonality": { + "count": 2560, + "mean": 1.1218960338510442e-07, + "p05": 1.790216153096935e-08, + "p95": 2.226799864502027e-07, + "min": 0.0, + "max": 6.154738798613835e-07 + }, + "rotation_det_error": { + "count": 2560, + "mean": 6.38654427120855e-08, + "p05": 0.0, + "p95": 1.7881393432617188e-07, + "min": 0.0, + "max": 4.76837158203125e-07 + }, + "projected_2d_error_px": { + "count": 3360, + "mean": 0.3454558551311493, + "p05": 0.0, + "p95": 1.5498476028442383, + "min": 0.0, + "max": 4.202671527862549 + } + } + }, + "ARCTIC": { + "tile_count": 10, + "tile_ids": [ + "17a3d720e547aa30e3460058:24", + "0fc8dd69a28adc0ecf611115:40", + "b3690d65b7b0a6c85266b669:16", + "2c60e4eb6ec976e4760bcf0f:32", + "516923930866cb4d79385817:24", + "6b0eff9c53c057f42c0eacb9:8", + "f9eea8372047c9da0c1c7048:48", + "567ce6607f1e809cd6e9c779:16", + "c68e7d52bb5de3e4a2ae800d:16", + "6f9b27e20e458fd91b99233a:48" + ], + "valid_counts": { + "hands_pose": 140, + "joints_3d": 2940, + "joints_2d": 2888, + "nonpositive_gt_z": 0 + }, + "statistics": { + "z_m": { + "count": 2940, + "mean": 0.5582757592201233, + "p05": 0.4297997057437897, + "p95": 0.7366219162940979, + "min": 0.33529093861579895, + "max": 0.8142500519752502 + }, + "wrist_vs_root_mm": { + "count": 140, + "mean": 3.0776958737988025e-05, + "p05": 0.0, + "p95": 0.00012136623990954831, + "min": 0.0, + "max": 0.0001499400386819616 + }, + "rotation_orthogonality": { + "count": 2240, + "mean": 1.2234667678967526e-07, + "p05": 2.5809567816281742e-08, + "p95": 2.603127597922139e-07, + "min": 0.0, + "max": 6.74678744871926e-07 + }, + "rotation_det_error": { + "count": 2240, + "mean": 6.652304307408485e-08, + "p05": 0.0, + "p95": 1.7881393432617188e-07, + "min": 0.0, + "max": 4.76837158203125e-07 + }, + "projected_2d_error_px": { + "count": 2888, + "mean": 0.27094727754592896, + "p05": 0.0, + "p95": 1.1124764680862427, + "min": 0.0, + "max": 2.2967588901519775 + } + } + }, + "HOT3D": { + "tile_count": 10, + "tile_ids": [ + "a431aedbaf7ba47abeb1138c:8", + "6c757dada2fd37d1b8bf406d:0", + "711e74dcb13d975659cd0a38:24", + "0cd6b0032f64b42a4aed2215:8", + "9b5f2ea1ebc3946bbf0b75f2:16", + "63dc0ace8fc425136887e3c1:24", + "c118b176bfec6916e158668d:8", + "e4795a6c7764239fda34799c:32", + "0c420a9ede59514482f2488f:0", + "61637533eb709b4da8d63349:0" + ], + "valid_counts": { + "hands_pose": 133, + "joints_3d": 2793, + "joints_2d": 2343, + "nonpositive_gt_z": 0 + }, + "statistics": { + "z_m": { + "count": 2793, + "mean": 0.34641191363334656, + "p05": 0.19880658388137817, + "p95": 0.5739707350730896, + "min": 0.11732112616300583, + "max": 0.6728987693786621 + }, + "wrist_vs_root_mm": { + "count": 133, + "mean": 0.0, + "p05": 0.0, + "p95": 0.0, + "min": 0.0, + "max": 0.0 + }, + "rotation_orthogonality": { + "count": 2128, + "mean": 1.1414603307002835e-07, + "p05": 2.356080486265455e-08, + "p95": 2.285757858544457e-07, + "min": 0.0, + "max": 5.579485105045023e-07 + }, + "rotation_det_error": { + "count": 2128, + "mean": 6.184541945231103e-08, + "p05": 0.0, + "p95": 1.7881393432617188e-07, + "min": 0.0, + "max": 4.172325134277344e-07 + }, + "projected_2d_error_px": { + "count": 2343, + "mean": 0.0, + "p05": 0.0, + "p95": 0.0, + "min": 0.0, + "max": 0.0 + } + } + } + } +} diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/adapt_phase3_validation_subset.py b/home/wuyifan/EgoNet_train_20261008/scripts/adapt_phase3_validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..3597f9540602b5d9249706b44f33431b996d1b6b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/adapt_phase3_validation_subset.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Clone a fixed validation selection under a new preprocessing contract.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--resolution-hw", type=int, nargs=2, required=True) + args = parser.parse_args() + + source = json.loads(args.source.read_text(encoding="utf-8")) + record = dict(source) + record["version"] = f"{source['version']}_resolution_contract_v1" + record["parent_selection_manifest"] = str(args.source.resolve()) + record["parent_selection_manifest_sha256"] = sha256(args.source) + record["dataset_contract"] = dict(source["dataset_contract"]) + record["dataset_contract"]["resolution_hw"] = list(args.resolution_hw) + record["adaptation"] = ( + "Clip indices and all selection metadata are copied exactly; only the " + "resize/padding resolution contract changes." + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "created", + "output": str(args.output), + "count": len(record["clip_indices"]), + "resolution_hw": record["dataset_contract"]["resolution_hw"], + "sha256": sha256(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/analyze_phase8_checkpoint_drift.py b/home/wuyifan/EgoNet_train_20261008/scripts/analyze_phase8_checkpoint_drift.py new file mode 100644 index 0000000000000000000000000000000000000000..75eb62e3785a60f5e05394066d2518db310df246 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/analyze_phase8_checkpoint_drift.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Measure layerwise model-parameter drift between two hash-bound checkpoints.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import torch + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _model_state(path: Path, expected_sha256: str) -> tuple[dict[str, torch.Tensor], dict[str, Any]]: + actual = sha256(path) + if actual != expected_sha256: + raise ValueError(f"checkpoint SHA256 differs: {path}") + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + state = checkpoint.get("model") + if not isinstance(state, dict) or not state: + raise ValueError(f"checkpoint has no model state: {path}") + return state, { + "path": str(path.resolve()), "sha256": actual, + "step": int(checkpoint.get("step", -1)), + "h2o_training_data_used": checkpoint.get("extra", {}).get( + "h2o_training_data_used" + ), + "official_test_used": checkpoint.get("extra", {}).get("official_test_used"), + } + + +def _group(name: str, depth: int) -> str: + components = name.split(".") + return ".".join(components[:depth]) + + +def analyze( + reference_path: Path, + reference_sha256: str, + candidate_path: Path, + candidate_sha256: str, + *, + group_depth: int = 2, +) -> dict[str, Any]: + if group_depth <= 0: + raise ValueError("group_depth must be positive") + reference, reference_meta = _model_state(reference_path, reference_sha256) + candidate, candidate_meta = _model_state(candidate_path, candidate_sha256) + if set(reference) != set(candidate): + missing = sorted(set(reference) - set(candidate)) + extra = sorted(set(candidate) - set(reference)) + raise ValueError(f"model state keys differ; missing={missing[:5]} extra={extra[:5]}") + accumulators: dict[str, dict[str, float]] = {} + for name in sorted(reference): + before = reference[name] + after = candidate[name] + if before.shape != after.shape: + raise ValueError(f"parameter shape differs: {name}") + if not before.is_floating_point(): + continue + before64 = before.detach().to(dtype=torch.float64) + delta = after.detach().to(dtype=torch.float64) - before64 + groups = ("__overall__", _group(name, 1), _group(name, group_depth)) + for group in dict.fromkeys(groups): + values = accumulators.setdefault(group, { + "parameter_count": 0.0, "reference_sq_sum": 0.0, + "delta_sq_sum": 0.0, "delta_abs_sum": 0.0, + "delta_abs_max": 0.0, "tensor_count": 0.0, + }) + values["parameter_count"] += float(delta.numel()) + values["reference_sq_sum"] += float(before64.square().sum()) + values["delta_sq_sum"] += float(delta.square().sum()) + values["delta_abs_sum"] += float(delta.abs().sum()) + values["delta_abs_max"] = max( + values["delta_abs_max"], float(delta.abs().max()) if delta.numel() else 0.0, + ) + values["tensor_count"] += 1.0 + groups: dict[str, Any] = {} + for group, values in sorted(accumulators.items()): + count = int(values["parameter_count"]) + delta_l2 = math.sqrt(values["delta_sq_sum"]) + reference_l2 = math.sqrt(values["reference_sq_sum"]) + groups[group] = { + "parameter_count": count, + "tensor_count": int(values["tensor_count"]), + "reference_l2": reference_l2, + "delta_l2": delta_l2, + "relative_l2": delta_l2 / max(reference_l2, 1e-12), + "delta_mean_abs": values["delta_abs_sum"] / max(count, 1), + "delta_max_abs": values["delta_abs_max"], + } + return { + "schema_version": "phase8_checkpoint_drift_v1", + "status": "complete", + "reference": reference_meta, + "candidate": candidate_meta, + "group_depth": group_depth, + "groups": groups, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference", type=Path, required=True) + parser.add_argument("--reference-sha256", required=True) + parser.add_argument("--candidate", type=Path, required=True) + parser.add_argument("--candidate-sha256", required=True) + parser.add_argument("--group-depth", type=int, default=2) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = analyze( + args.reference, args.reference_sha256, + args.candidate, args.candidate_sha256, + group_depth=args.group_depth, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/analyze_phase8_paired_input_modes.py b/home/wuyifan/EgoNet_train_20261008/scripts/analyze_phase8_paired_input_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..615c329bb99ebb1df93134ba095c09b527aa8fd7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/analyze_phase8_paired_input_modes.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Paired depth-contribution diagnostic for two frozen evaluation bundles.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_summary(values: np.ndarray) -> dict[str, float | int] | None: + values = np.asarray(values, dtype=np.float64) + values = values[np.isfinite(values)] + if not len(values): + return None + return { + "count": int(len(values)), "mean": float(values.mean()), + "median": float(np.median(values)), "p90": float(np.quantile(values, .9)), + "p95": float(np.quantile(values, .95)), "p99": float(np.quantile(values, .99)), + "min": float(values.min()), "max": float(values.max()), + } + + +def correlation(left: np.ndarray, right: np.ndarray) -> float | None: + finite = np.isfinite(left) & np.isfinite(right) + if finite.sum() < 2 or np.std(left[finite]) == 0 or np.std(right[finite]) == 0: + return None + return float(np.corrcoef(left[finite], right[finite])[0, 1]) + + +def optimal_slope(delta: np.ndarray, desired: np.ndarray) -> float | None: + finite = np.isfinite(delta) & np.isfinite(desired) + denominator = float(np.dot(delta[finite], delta[finite])) + if denominator <= 1e-12: + return None + return float(np.dot(delta[finite], desired[finite]) / denominator) + + +def grouped_bootstrap( + groups: np.ndarray, gains: np.ndarray, *, seed: int, resamples: int, +) -> dict[str, float | int]: + unique = np.unique(groups) + by_group = {group: gains[groups == group] for group in unique} + generator = np.random.default_rng(seed) + estimates = np.empty(resamples, dtype=np.float64) + for index in range(resamples): + sampled = generator.choice(unique, size=len(unique), replace=True) + values = np.concatenate([by_group[group] for group in sampled]) + estimates[index] = np.nanmean(values) + return { + "groups": int(len(unique)), "resamples": int(resamples), + "estimate": float(np.nanmean(gains)), + "ci95_low": float(np.quantile(estimates, .025)), + "ci95_high": float(np.quantile(estimates, .975)), + } + + +def load_bundle(directory: Path) -> tuple[dict[str, Any], dict[str, np.ndarray], list[dict[str, str]]]: + report_path = directory / "evaluation.json" + raw_path = directory / "raw_predictions.npz" + rows_path = directory / "per_hand_frame_metrics.csv" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("official_test_used") is not False + or report.get("h2o_official_validation_used_for_external_selection") is True + ): + raise ValueError("paired diagnostic refuses a bundle without official_test_used=false") + with np.load(raw_path) as archive: + raw = {key: archive[key] for key in archive.files} + with rows_path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + return report, raw, rows + + +def observation_manifest(report: dict[str, Any]) -> dict[str, Any]: + for name in ("cache_manifest", "manifest"): + value = report.get(name) + if isinstance(value, dict) and value.get("sha256"): + return value + raise ValueError("evaluation lacks a hash-bound observation manifest") + + +def validate_pair( + base_report: dict[str, Any], depth_report: dict[str, Any], + base: dict[str, np.ndarray], depth: dict[str, np.ndarray], + base_rows: list[dict[str, str]], depth_rows: list[dict[str, str]], +) -> None: + if base_report["checkpoint"]["sha256"] != depth_report["checkpoint"]["sha256"]: + raise ValueError("paired modes must use the same checkpoint") + if observation_manifest(base_report)["sha256"] != observation_manifest(depth_report)["sha256"]: + raise ValueError("paired modes must use the same cache manifest") + if base_report["input_mode"] != "rgb_k" or depth_report["input_mode"] != "rgb_d_k": + raise ValueError("expected base=rgb_k and depth=rgb_d_k") + for key in ( + "target_wrist_root_translation", "target_joints_camera", + "translation_valid", "joint3d_valid", "frame_id", + ): + if key not in base or key not in depth or not np.array_equal(base[key], depth[key], equal_nan=True): + raise ValueError(f"paired raw target alignment differs: {key}") + if len(base_rows) != len(depth_rows): + raise ValueError("paired per-hand row counts differ") + identity = ("dataset", "subject_id", "physical_recording_id", "camera_id", "frame_id", "side") + if any(any(left[key] != right[key] for key in identity) for left, right in zip(base_rows, depth_rows)): + raise ValueError("paired per-hand row identities differ") + + +def analyze( + base_dir: Path, depth_dir: Path, output_dir: Path, *, seed: int, resamples: int, +) -> dict[str, Any]: + base_report, base, base_rows = load_bundle(base_dir) + depth_report, depth, depth_rows = load_bundle(depth_dir) + validate_pair(base_report, depth_report, base, depth, base_rows, depth_rows) + if output_dir.exists() and any(output_dir.iterdir()): + raise ValueError("output directory must be new or empty") + output_dir.mkdir(parents=True, exist_ok=True) + + predicted_base = base["predicted_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + predicted_depth = depth["predicted_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + target = base["target_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + translation_valid = base["translation_valid"].reshape(-1).astype(bool) + delta = (predicted_depth - predicted_base) * 1000.0 + desired = (target - predicted_base) * 1000.0 + base_residual = (predicted_base - target) * 1000.0 + depth_residual = (predicted_depth - target) * 1000.0 + + base_joints = base["predicted_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + depth_joints = depth["predicted_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + target_joints = base["target_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + joint_valid = base["joint3d_valid"].reshape(-1, 21).astype(bool) + base_point_error = np.linalg.norm(base_joints - target_joints, axis=-1) * 1000.0 + depth_point_error = np.linalg.norm(depth_joints - target_joints, axis=-1) * 1000.0 + base_mpjpe = np.full(len(joint_valid), np.nan) + depth_mpjpe = np.full(len(joint_valid), np.nan) + for index, valid in enumerate(joint_valid): + if valid.any(): + base_mpjpe[index] = base_point_error[index, valid].mean() + depth_mpjpe[index] = depth_point_error[index, valid].mean() + + groups = np.asarray([row["physical_recording_id"] for row in base_rows], dtype=object) + if len(groups) != len(predicted_base): + raise ValueError("raw hand axis does not match per-hand metric rows") + valid = translation_valid & np.isfinite(base_residual).all(1) & np.isfinite(depth_residual).all(1) + joint_rows = np.isfinite(base_mpjpe) & np.isfinite(depth_mpjpe) + translation_gain = np.linalg.norm(base_residual, axis=1) - np.linalg.norm(depth_residual, axis=1) + mpjpe_gain = base_mpjpe - depth_mpjpe + + paired_rows: list[dict[str, Any]] = [] + for index, metadata in enumerate(base_rows): + if not (valid[index] or joint_rows[index]): + continue + record: dict[str, Any] = { + key: metadata[key] for key in + ("dataset", "subject_id", "physical_recording_id", "camera_id", "frame_id", "side") + } + for axis_index, axis in enumerate("xyz"): + record[f"depth_contribution_{axis}_mm"] = float(delta[index, axis_index]) + record[f"desired_correction_{axis}_mm"] = float(desired[index, axis_index]) + record[f"base_{axis}_error_mm"] = float(base_residual[index, axis_index]) + record[f"depth_{axis}_error_mm"] = float(depth_residual[index, axis_index]) + record["base_mpjpe_mm"] = float(base_mpjpe[index]) + record["depth_mpjpe_mm"] = float(depth_mpjpe[index]) + record["mpjpe_gain_mm"] = float(mpjpe_gain[index]) + record["translation_norm_gain_mm"] = float(translation_gain[index]) + paired_rows.append(record) + row_path = output_dir / "paired_hand_rows.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(paired_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(paired_rows) + harm_path = output_dir / "largest_harm_cases.csv" + harm_rows = sorted(paired_rows, key=lambda row: row["mpjpe_gain_mm"])[:100] + with harm_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(harm_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(harm_rows) + + axis_diagnostics = {} + for axis_index, axis in enumerate("xyz"): + selected = valid & np.isfinite(delta[:, axis_index]) & np.isfinite(desired[:, axis_index]) + axis_diagnostics[axis] = { + "base_signed_error_mm": finite_summary(base_residual[selected, axis_index]), + "depth_signed_error_mm": finite_summary(depth_residual[selected, axis_index]), + "depth_contribution_mm": finite_summary(delta[selected, axis_index]), + "desired_correction_mm": finite_summary(desired[selected, axis_index]), + "contribution_desired_correlation": correlation( + delta[selected, axis_index], desired[selected, axis_index], + ), + "optimal_depth_contribution_scale": optimal_slope( + delta[selected, axis_index], desired[selected, axis_index], + ), + "direction_agreement_fraction": float(np.mean( + np.sign(delta[selected, axis_index]) == np.sign(desired[selected, axis_index]) + )), + "absolute_error_gain_mm": finite_summary( + np.abs(base_residual[selected, axis_index]) - np.abs(depth_residual[selected, axis_index]) + ), + } + report = { + "status": "complete", + "class": "paired_input_oracle_diagnostic_only", + "deployable_claim": False, + "checkpoint": base_report["checkpoint"], + "observation_manifest": observation_manifest(base_report), + "base_input_mode": "rgb_k", "depth_input_mode": "rgb_d_k", + "hands_with_translation": int(valid.sum()), + "hands_with_joint3d": int(joint_rows.sum()), + "base_absolute_mpjpe_mm": float(np.nanmean(base_mpjpe[joint_rows])), + "depth_absolute_mpjpe_mm": float(np.nanmean(depth_mpjpe[joint_rows])), + "depth_mpjpe_gain_mm": finite_summary(mpjpe_gain[joint_rows]), + "depth_harm_fraction_mpjpe": float(np.mean(mpjpe_gain[joint_rows] < 0)), + "translation_norm_gain_mm": finite_summary(translation_gain[valid]), + "depth_harm_fraction_translation_norm": float(np.mean(translation_gain[valid] < 0)), + "axis_diagnostics": axis_diagnostics, + "grouped_bootstrap_ci": { + "mpjpe_gain_mm": grouped_bootstrap( + groups[joint_rows], mpjpe_gain[joint_rows], seed=seed, resamples=resamples, + ), + "translation_norm_gain_mm": grouped_bootstrap( + groups[valid], translation_gain[valid], seed=seed, resamples=resamples, + ), + }, + "paired_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "largest_harm_cases": {"path": str(harm_path.resolve()), "sha256": sha256(harm_path)}, + "official_test_used": False, + } + report_path = output_dir / "analysis.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-rgb-k-dir", type=Path, required=True) + parser.add_argument("--depth-rgb-d-k-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + report = analyze( + args.base_rgb_k_dir, args.depth_rgb_d_k_dir, args.output_dir, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/arm_phase9_last2_distributed_completion.py b/home/wuyifan/EgoNet_train_20261008/scripts/arm_phase9_last2_distributed_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..d4159e763e607821df8bedef7283073b6dc8064b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/arm_phase9_last2_distributed_completion.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Carry one admitted last-2 candidate through both distributed handoffs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def write_state(path: Path, status: str, candidate: str, **extra: Any) -> None: + atomic_json(path, { + "schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": status, "candidate": candidate, "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "official_test_used": False, **extra, + }) + + +def wait_json(path: Path, predicate: Any, state_path: Path, candidate: str, label: str) -> dict[str, Any]: + while True: + if path.is_file(): + value = read_json(path) + if predicate(value): return value + if str(value.get("status", "")).startswith("failed"): + raise ValueError(f"last-2 dependency failed: {path}") + write_state(state_path, label, candidate, dependency=str(path.resolve())) + time.sleep(30) + + +def remote_conditions(plan: dict[str, Any], registry: dict[str, Any]) -> list[str]: + owners = condition_owners(registry, load_assignment(plan)) + result = [item["condition"] for item in registry["conditions"] + if owners[item["condition"]] == "server_new"] + if len(result) != 3: raise ValueError("last-2 remote condition count differs") + return result + + +def start_process(command: list[str], log: Path) -> int: + log.parent.mkdir(parents=True, exist_ok=True) + handle = log.open("a", encoding="utf-8") + process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=handle, + stderr=subprocess.STDOUT, text=True, start_new_session=True) + handle.close(); return process.pid + + +def start_remote(command: str) -> None: + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: raise RuntimeError("remote last-2 watcher launch failed") + + +def training_completion_plan(plan_path: Path, plan: dict[str, Any], registry_path: Path) -> dict[str, Any]: + registry = read_json(registry_path); conditions = remote_conditions(plan, registry) + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_last2_training_completion.py") + return { + "schema_version": "phase9_last2_training_completion_plan_v1", "status": "frozen", + "candidate": plan["candidate"], "source_owner": "server_new", + "destination_owner": "taku3", "conditions": conditions, "target_step": 405000, + "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/last2_v3/{plan['candidate']}/recovery/training_completion_staging", + "training_state_root": plan["training_state_root"], + "source_controller_state": plan["controller_states"]["server_new"], + "training_completion_state": plan["training_completion_state"], + "release_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_training_completion_release.json", + "receive_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_training_completion_receive.json", + "training_registry": {"path": str(registry_path.resolve()), "sha256": sha256(registry_path)}, + "controller_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "distributed_assignment": plan["distributed_assignment"], + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "results_before_terminal_states": True, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + {"path": str(registry_path.resolve()), "sha256": sha256(registry_path)}, + plan["distributed_assignment"], + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def evaluation_completion_plan(plan_path: Path, plan: dict[str, Any], dynamic: Path) -> dict[str, Any]: + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + return { + "schema_version": "phase9_resolution_evaluation_completion_release_plan_v1", + "status": "frozen", "source_owner": "server_new", "destination_owner": "taku3", + "source_host": "server_new", "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/last2_v3/{plan['candidate']}/recovery/evaluation_completion_staging", + "source_controller_state": plan["controller_states"]["server_new"], + "release_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_evaluation_completion_release.json", + "receive_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_evaluation_completion_receive.json", + "ssh_timeout_seconds": 30, + "evaluation_plan": {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "single_writer_per_output": True, "results_before_terminal_states": True, + "read_only_after_publish": True, + "scientific_contract": { + "amendment_scope": "terminal_evaluation_state_and_result_handoff_only", + "model_changed": False, "data_changed": False, "seed_changed": False, + "metric_changed": False, "selection_gate_changed": False, + }, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + plan["distributed_assignment"], + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def sync_plan_and_bridge(output: Path, value: dict[str, Any], bridge: Path) -> None: + if output.exists() and read_json(output) != value: raise ValueError(f"existing plan differs: {output}") + if not output.exists(): output.parent.mkdir(parents=True, exist_ok=True); atomic_json(output, value) + for path in (bridge, output): + installed = install_file("server_new", path) + if installed["sha256"] != sha256(path): raise ValueError(f"remote sync differs: {path}") + + +def sync_evaluation_admission(plan: dict[str, Any], dynamic: Path) -> None: + payload = read_json(dynamic) + remote_ids = {identifier for worker in payload["workers"] if worker["owner"] == "server_new" + for identifier in worker["evaluation_ids"]} + evaluations = {item["id"]: item for item in payload["evaluations"]} + for identifier in remote_ids: + item = evaluations[identifier] + for path_key, hash_key in (("config", "config_sha256"), + ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256")): + if remote_sha256("server_new", Path(item[path_key])) != item[hash_key]: + raise ValueError(f"remote last-2 evaluation input differs: {identifier}") + for path in (Path(plan["training_completion_state"]), + Path(plan["evaluation_plan_state"]), dynamic): + install_file("server_new", path) + + +def run(plan_path: Path, state_path: Path) -> dict[str, Any]: + plan = read_json(plan_path); candidate = plan["candidate"] + sync_state = Path(f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{candidate}/admission_sync_state.json") + admitted = wait_json(sync_state, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_admission_sync") + if admitted.get("admission") == "rejected": + return {"schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": "complete_formal_rejection", "candidate": candidate, + "completed_utc": utc_now(), "official_test_used": False} + registry_path = Path(plan["training_registry"]) + wait_json(registry_path, lambda value: value.get("status") == "frozen_ready", + state_path, candidate, "waiting_for_training_registry") + training_plan_path = plan_path.parent / f"last2_{candidate}_training_completion_plan_v1.json" + training_value = training_completion_plan(plan_path, plan, registry_path) + training_bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_last2_training_completion.py") + sync_plan_and_bridge(training_plan_path, training_value, training_bridge) + log_root = Path(f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{candidate}/completion_logs") + receive_pid = start_process([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_last2_training_completion", "--plan", str(training_plan_path), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], log_root / "training_receive.log") + start_remote( + "cd /home/jiasen/foundation_hand && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + f"scripts.sync_phase9_last2_training_completion --plan {training_plan_path} --role publish " + f"--wait-timeout-seconds 1209600 >> {log_root / 'training_publish.log'} 2>&1 < /dev/null" + ) + receive_state = Path(training_value["receive_state"]) + wait_json(receive_state, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_training_completion_return") + dynamic = Path(plan["evaluation_plan"]) + wait_json(dynamic, lambda value: value.get("status") == "frozen_ready", + state_path, candidate, "waiting_for_evaluation_plan") + sync_evaluation_admission(plan, dynamic) + evaluation_plan_path = plan_path.parent / f"last2_{candidate}_evaluation_completion_plan_v1.json" + evaluation_value = evaluation_completion_plan(plan_path, plan, dynamic) + evaluation_bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + sync_plan_and_bridge(evaluation_plan_path, evaluation_value, evaluation_bridge) + evaluation_receive_pid = start_process([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_resolution_evaluation_completion", "--plan", str(evaluation_plan_path), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], log_root / "evaluation_receive.log") + start_remote( + "cd /home/jiasen/foundation_hand && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + f"scripts.sync_phase9_resolution_evaluation_completion --plan {evaluation_plan_path} --role publish " + f"--wait-timeout-seconds 1209600 >> {log_root / 'evaluation_publish.log'} 2>&1 < /dev/null" + ) + central = Path(plan["controller_states"]["taku3"]) + final = wait_json(central, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_central_candidate_decision") + return { + "schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": "complete", "candidate": candidate, "completed_utc": utc_now(), + "training_receive_pid": receive_pid, "evaluation_receive_pid": evaluation_receive_pid, + "decision_report": final["decision_report"], "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser(); parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True); args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + result = run(args.plan, args.state); atomic_json(args.state, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/arm_phase9_shared_augmentation_evaluation_completion.py b/home/wuyifan/EgoNet_train_20261008/scripts/arm_phase9_shared_augmentation_evaluation_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..2213de6d5ae74ec16fc626ba2609582464fcd890 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/arm_phase9_shared_augmentation_evaluation_completion.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Arm completion-only Stage 8 evaluation return after its plan freezes.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def completion_plan(static_plan_path: Path, static: dict[str, Any]) -> dict[str, Any]: + dynamic = Path(static["evaluation_plan"]) + admission = Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/" + "evaluation_admission_sync_state.json" + ) + if not dynamic.is_file() or not admission.is_file(): + raise RuntimeError("Stage 8 evaluation admission is not complete") + admitted = read_json(admission) + if admitted.get("status") != "complete" or admitted.get("evaluation_plan_sha256") != sha256(dynamic): + raise RuntimeError("Stage 8 evaluation admission is not complete") + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + assignment = Path(static["distributed_assignment"]["path"]) + return { + "schema_version": "phase9_resolution_evaluation_completion_release_plan_v1", + "status": "frozen", "source_owner": "server_new", "destination_owner": "taku3", + "source_host": "server_new", + "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts/shared_augmentation/896x512/recovery/server_evaluation_completion_staging_v1", + "source_controller_state": static["controller_states"]["server_new"], + "release_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/server_evaluation_completion_release_state_v1.json", + "receive_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/server_evaluation_completion_receive_state_v1.json", + "ssh_timeout_seconds": 30, + "evaluation_plan": {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "single_writer_per_output": True, "results_before_terminal_states": True, + "read_only_after_publish": True, + "scientific_contract": { + "amendment_scope": "terminal_evaluation_state_and_result_handoff_only", + "model_changed": False, "data_changed": False, "seed_changed": False, + "metric_changed": False, "selection_gate_changed": False, + }, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(static_plan_path.resolve()), "sha256": sha256(static_plan_path)}, + {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + {"path": str(assignment.resolve()), "sha256": sha256(assignment)}, + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def arm(static_plan_path: Path, output_plan: Path) -> dict[str, Any]: + static = read_json(static_plan_path) + plan = completion_plan(static_plan_path, static) + if output_plan.exists() and read_json(output_plan) != plan: + raise ValueError("existing Stage 8 evaluation completion plan differs") + if not output_plan.exists(): + output_plan.parent.mkdir(parents=True, exist_ok=True); atomic_json(output_plan, plan) + copied = subprocess.run(["rsync", "-a", str(output_plan), f"server_new:{output_plan}.incoming"], check=False) + if copied.returncode: + raise RuntimeError("Stage 8 evaluation completion plan sync failed") + installed = subprocess.run(["ssh", "server_new", "mv", f"{output_plan}.incoming", str(output_plan)], check=False) + if installed.returncode: + raise RuntimeError("Stage 8 evaluation completion plan install failed") + log_root = Path("/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/completion_logs") + log_root.mkdir(parents=True, exist_ok=True) + receive = subprocess.Popen([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_resolution_evaluation_completion", "--plan", str(output_plan), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], stdin=subprocess.DEVNULL, stdout=(log_root / "evaluation_receive.log").open("a"), + stderr=subprocess.STDOUT, text=True, start_new_session=True) + remote = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.sync_phase9_resolution_evaluation_completion --plan " + str(output_plan) + + " --role publish --wait-timeout-seconds 1209600 >> " + + str(log_root / "evaluation_publish.log") + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", remote], check=False) + if result.returncode: + raise RuntimeError("Stage 8 evaluation completion publisher launch failed") + return { + "schema_version": "phase9_shared_augmentation_evaluation_completion_arm_v1", + "status": "complete", "completed_utc": utc_now(), + "completion_plan": str(output_plan.resolve()), + "completion_plan_sha256": sha256(output_plan), "receiver_pid": receive.pid, + "official_test_used": False, "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--static-plan", type=Path, required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = arm(args.static_plan, args.output_plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except RuntimeError as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_evaluation_completion_arm_v1", + "status": "waiting_for_evaluation_admission", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_coordinates.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_coordinates.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca4d235ec4f8a6ed42e9e7528951c26225cab2b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_coordinates.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Create reproducible camera/depth/joint audit artifacts for H2O cam4.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record +from foundation_hand.geometry.camera import ( + depth_mm_to_m, + intrinsics_from_h2o, + project_points, + unproject_depth, +) + +HAND_COLORS = ((50, 220, 50), (50, 80, 255)) # BGR: left green, right red +HAND_EDGES = ( + (0, 1), (1, 2), (2, 3), (3, 4), + (0, 5), (5, 6), (6, 7), (7, 8), + (0, 9), (9, 10), (10, 11), (11, 12), + (0, 13), (13, 14), (14, 15), (15, 16), + (0, 17), (17, 18), (18, 19), (19, 20), +) + + +def choose_samples(frame_csv: Path, count: int) -> list[dict[str, str]]: + with frame_csv.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + buckets: dict[str, list[dict[str, str]]] = {} + for row in rows: + key = f"{row['subject']}:{row['joint_left_valid']}{row['joint_right_valid']}" + buckets.setdefault(key, []).append(row) + selected: list[dict[str, str]] = [] + keys = sorted(buckets) + cursor = {key: 0 for key in keys} + while len(selected) < count and keys: + next_keys = [] + for key in keys: + candidates = buckets[key] + index = cursor[key] + if index < len(candidates): + # Walk each bucket across time rather than taking adjacent frames. + pos = min(len(candidates) - 1, round(index * max(1, len(candidates) - 1) / max(1, count // len(keys)))) + selected.append(candidates[pos]) + cursor[key] += 1 + next_keys.append(key) + if len(selected) == count: + break + keys = next_keys + return selected + + +def draw_joints(image: np.ndarray, uv: np.ndarray, valid_z: np.ndarray, color: tuple[int, int, int]) -> None: + inside = valid_z & (uv[:, 0] >= 0) & (uv[:, 0] < image.shape[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < image.shape[0]) + for start, end in HAND_EDGES: + if inside[start] and inside[end]: + cv2.line(image, tuple(np.rint(uv[start]).astype(int)), tuple(np.rint(uv[end]).astype(int)), color, 2) + for index, point in enumerate(uv): + if inside[index]: + radius = 5 if index == 0 else 3 + cv2.circle(image, tuple(np.rint(point).astype(int)), radius, color, -1) + + +def write_colored_ply(path: Path, xyz: np.ndarray, rgb: np.ndarray, valid: np.ndarray, stride: int = 8) -> int: + points = xyz[::stride, ::stride][valid[::stride, ::stride]] + colors = rgb[::stride, ::stride][valid[::stride, ::stride]] + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="ascii") as handle: + handle.write("ply\nformat ascii 1.0\n") + handle.write(f"element vertex {len(points)}\n") + handle.write("property float x\nproperty float y\nproperty float z\n") + handle.write("property uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n") + for point, color in zip(points, colors, strict=True): + handle.write(f"{point[0]:.6f} {point[1]:.6f} {point[2]:.6f} {int(color[0])} {int(color[1])} {int(color[2])}\n") + return len(points) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=24) + args = parser.parse_args() + + root = args.root.resolve() + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + selected = choose_samples(args.frame_csv, args.samples) + result_rows = [] + roundtrip_errors = [] + + for sample_index, row in enumerate(selected): + take = root / row["subject"] / row["scene"] / row["take"] / "cam4" + frame = f"{int(row['frame_id']):06d}" + rgb_bgr = cv2.imread(str(take / "rgb" / f"{frame}.png"), cv2.IMREAD_COLOR) + depth_raw = cv2.imread(str(take / "depth" / f"{frame}.png"), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_raw is None: + raise RuntimeError(f"Could not decode sample {take}/{frame}") + K, expected_hw = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + if rgb_bgr.shape[:2] != expected_hw or depth_raw.shape != expected_hw: + raise ValueError(f"RGB/depth/K size mismatch at {take}/{frame}") + depth_m, depth_valid = depth_mm_to_m(depth_raw) + xyz, xyz_valid = unproject_depth(depth_m, K) + + # Pixel -> camera -> pixel should recover exact pixel centers for every valid depth. + sparse_xyz = xyz[::16, ::16].reshape(-1, 3) + sparse_valid = xyz_valid[::16, ::16].reshape(-1) + uv_back, positive = project_points(sparse_xyz[sparse_valid], K) + vv, uu = np.meshgrid(np.arange(0, expected_hw[0], 16), np.arange(0, expected_hw[1], 16), indexing="ij") + uv_reference = np.stack((uu, vv), axis=-1).reshape(-1, 2)[sparse_valid] + pixel_error = np.linalg.norm(uv_back[positive] - uv_reference[positive], axis=-1) + roundtrip_errors.extend(pixel_error.tolist()) + + overlay = rgb_bgr.copy() + joints = load_joint_record(take / "hand_pose" / f"{frame}.txt") + hand_stats = [] + for hand_index, color in enumerate(HAND_COLORS): + if joints.annotation_valid[hand_index]: + uv, positive_z = project_points(joints.joints_camera_m[hand_index], K) + draw_joints(overlay, uv, positive_z, color) + hand_stats.append({"side": ("left", "right")[hand_index], "annotation_valid": True, "projected_in_frame": int(((uv[:, 0] >= 0) & (uv[:, 0] < expected_hw[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < expected_hw[0]) & positive_z).sum())}) + else: + hand_stats.append({"side": ("left", "right")[hand_index], "annotation_valid": False, "projected_in_frame": None}) + + valid_depth = depth_m[depth_valid] + clipped = np.clip(depth_m, 0, np.quantile(valid_depth, 0.99) if valid_depth.size else 1.0) + depth_u8 = np.rint(255 * clipped / max(float(clipped.max()), 1e-6)).astype(np.uint8) + depth_color = cv2.applyColorMap(depth_u8, cv2.COLORMAP_TURBO) + depth_color[~depth_valid] = 0 + edges = cv2.Canny(depth_u8, 30, 90) + alignment = rgb_bgr.copy() + alignment[edges > 0] = (0, 255, 255) + + label = f"{row['subject']}/{row['scene']}/{row['take']}/{frame} L={row['joint_left_valid']} R={row['joint_right_valid']}" + for image in (overlay, depth_color, alignment): + cv2.rectangle(image, (0, 0), (image.shape[1], 34), (0, 0, 0), -1) + cv2.putText(image, label, (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) + prefix = f"{sample_index:02d}_{row['subject']}_{row['scene']}_{row['take']}_{frame}" + cv2.imwrite(str(output / f"{prefix}_joint_overlay.jpg"), overlay) + cv2.imwrite(str(output / f"{prefix}_depth.jpg"), depth_color) + cv2.imwrite(str(output / f"{prefix}_depth_edges_rgb.jpg"), alignment) + ply_count = write_colored_ply(output / f"{prefix}_pointcloud.ply", xyz, cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB), xyz_valid) + result_rows.append({ + "sample": prefix, + "subject": row["subject"], "scene": row["scene"], "take": row["take"], "frame_id": int(row["frame_id"]), + "K": K.tolist(), "depth_dtype": str(depth_raw.dtype), "depth_valid_fraction": float(depth_valid.mean()), + "depth_min_m": float(valid_depth.min()), "depth_p50_m": float(np.quantile(valid_depth, 0.5)), "depth_p95_m": float(np.quantile(valid_depth, 0.95)), "depth_max_m": float(valid_depth.max()), + "pixel_roundtrip_max": float(pixel_error.max()) if pixel_error.size else None, + "pointcloud_vertices": ply_count, "hands": hand_stats, + }) + + errors = np.asarray(roundtrip_errors) + report = { + "root": str(root), "sample_count": len(result_rows), "selection": "round-robin across subject and annotation-valid combinations, spread over time", + "camera_convention_supported_by_projection": "x-right, y-down, z-forward; u=fx*x/z+cx, v=fy*y/z+cy", + "depth_unit": "released uint16 millimeters converted by /1000 to meters", + "pixel_unprojection_projection_roundtrip": {"count": int(errors.size), "mean_px": float(errors.mean()), "p95_px": float(np.quantile(errors, 0.95)), "max_px": float(errors.max())}, + "mano_numeric_reconstruction": "BLOCKED_MISSING_LICENSED_MANO_ASSETS", + "samples": result_rows, + } + (output / "coordinate_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: report[key] for key in ("sample_count", "camera_convention_supported_by_projection", "depth_unit", "pixel_unprojection_projection_roundtrip", "mano_numeric_reconstruction")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_mano.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_mano.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ae1a83d4f165c9542c997f6cd3bd7ceeff5b46 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_mano.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Numerically reproduce H2O MANO fits before formal training is allowed.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record, load_mano_record +from foundation_hand.geometry.camera import intrinsics_from_h2o, project_points +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.mano_translation import mano_raw_to_wrist, wrist_to_mano_raw + + +def stats(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values) + return {"count": int(array.size), "mean_mm": float(array.mean()), "p50_mm": float(np.quantile(array, .5)), "p95_mm": float(np.quantile(array, .95)), "max_mm": float(array.max())} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=50) + args = parser.parse_args(); args.output_dir.mkdir(parents=True, exist_ok=True) + required = [args.mano_root / "MANO_LEFT.pkl", args.mano_root / "MANO_RIGHT.pkl"] + if not all(path.is_file() for path in required): + report = {"status": "blocked", "reason": "licensed MANO assets missing", "required": [str(path) for path in required]} + (args.output_dir / "mano_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)); raise SystemExit(2) + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + layers = [ManoLayer(mano_root=str(args.mano_root), side=side, use_pca=False, ncomps=45, flat_hand_mean=True) for side in ("left", "right")] + with args.frame_csv.open(newline="", encoding="utf-8") as handle: rows = [row for row in csv.DictReader(handle) if row["joint_left_valid"] == "1" and row["joint_right_valid"] == "1"] + rows = [rows[round(index * (len(rows)-1) / max(args.samples-1, 1))] for index in range(args.samples)] + errors = {"left": [], "right": []}; roundtrip = {"left": [], "right": []}; root_offsets = {"left": [], "right": []} + for sample_index, row in enumerate(rows): + take = args.root / row["subject"] / row["scene"] / row["take"] / "cam4"; stem = f"{int(row['frame_id']):06d}" + joints_gt = load_joint_record(take / "hand_pose" / f"{stem}.txt"); mano = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + image = cv2.imread(str(take / "rgb" / f"{stem}.png")); K, _ = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + for hand, side in enumerate(("left", "right")): + with torch.no_grad(): vertices_mm, joints_mm = layers[hand](torch.from_numpy(mano.pose_axis_angle[hand:hand+1]), torch.from_numpy(mano.shape[hand:hand+1])) + native_joints_m = joints_mm[0].numpy() / 1000.0; reconstructed = native_joints_m + mano.translation_raw_m[hand] + per_joint = np.linalg.norm(reconstructed - joints_gt.joints_camera_m[hand], axis=-1) * 1000 + errors[side].extend(per_joint.tolist()); root_offsets[side].append(native_joints_m[0].tolist()) + wrist = mano_raw_to_wrist(mano.translation_raw_m[hand], native_joints_m[0]); raw_back = wrist_to_mano_raw(wrist, native_joints_m[0]) + roundtrip[side].append(float(np.linalg.norm(raw_back - mano.translation_raw_m[hand]) * 1000)) + if sample_index < 10: + uv, positive = project_points(reconstructed, K) + for point, valid in zip(uv, positive, strict=True): + if valid: cv2.circle(image, tuple(np.rint(point).astype(int)), 3, ((50,220,50),(50,80,255))[hand], -1) + if sample_index < 10: cv2.imwrite(str(args.output_dir / f"{sample_index:02d}_{row['subject']}_{row['scene']}_{row['take']}_{stem}_mano_overlay.jpg"), image) + report = { + "status": "passed" if max(stats(errors[side])["p95_mm"] for side in errors) < 5 else "failed", + "configuration": {"use_pca": False, "ncomps": 45, "flat_hand_mean": True, "native_output_unit": "mm", "placed_output_unit": "m"}, + "joint_reconstruction": {side: stats(values) for side, values in errors.items()}, + "translation_semantics": "raw translation places the MANO model origin; wrist = raw + native MANO joint0 / 1000", + "raw_to_wrist_root_offsets_m": root_offsets, + "translation_roundtrip": {side: stats(values) for side, values in roundtrip.items()}, + } + (args.output_dir / "mano_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: report[key] for key in ("status", "joint_reconstruction", "translation_semantics", "translation_roundtrip")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase2_cam4.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase2_cam4.py new file mode 100644 index 0000000000000000000000000000000000000000..147fa879e7466f0015130321ffba9dec3915f615 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase2_cam4.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +"""Reproducible full-record audit of the extracted H2O cam4 dataset.""" + +from __future__ import annotations + +import argparse +import csv +import json +import random +from collections import Counter +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import ( + load_float_record, + parse_joint_record, + parse_mano_record, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + +CORE_FRAME_MODALITIES = ( + "rgb", + "depth", + "cam_pose", + "hand_pose", + "hand_pose_mano", + "obj_pose", + "obj_pose_rt", +) +SIDES = ("left", "right") + + +def quantiles(values: list[float] | np.ndarray) -> dict[str, float | int | None]: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if array.size == 0: + return {"count": 0, "mean": None, "p50": None, "p95": None, "max": None} + return { + "count": int(array.size), + "mean": float(array.mean()), + "p50": float(np.quantile(array, 0.50)), + "p95": float(np.quantile(array, 0.95)), + "max": float(array.max()), + } + + +def ids_in(directory: Path) -> set[int]: + return {int(path.stem) for path in directory.iterdir() if path.is_file() and path.stem.isdigit()} + + +def sample_evenly(items: list[Path], count: int) -> list[Path]: + if count <= 0 or not items: + return [] + if len(items) <= count: + return items + indices = np.linspace(0, len(items) - 1, count, dtype=int) + return [items[index] for index in indices] + + +def make_contact_sheet(rows: list[dict[str, object]], output: Path, title: str) -> None: + if not rows: + return + tile_w, tile_h = 320, 205 + columns = 4 + result_rows = (len(rows) + columns - 1) // columns + canvas = np.zeros((result_rows * tile_h + 36, columns * tile_w, 3), dtype=np.uint8) + cv2.putText(canvas, title, (8, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) + for index, row in enumerate(rows): + image = cv2.imread(str(row["rgb_path"]), cv2.IMREAD_COLOR) + if image is None: + continue + image = cv2.resize(image, (tile_w, 180), interpolation=cv2.INTER_AREA) + label = str(row["label"]) + cv2.rectangle(image, (0, 0), (tile_w, 24), (0, 0, 0), -1) + cv2.putText(image, label[:52], (4, 17), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (255, 255, 255), 1) + y = 36 + (index // columns) * tile_h + x = (index % columns) * tile_w + canvas[y : y + 180, x : x + tile_w] = image + output.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(output), canvas) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--depth-samples-per-take", type=int, default=2) + parser.add_argument("--invalid-visual-samples", type=int, default=40) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + root = args.root.resolve() + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + rng = random.Random(args.seed) + + take_dirs = sorted(root.glob("subject*/*/*/cam4")) + if not take_dirs: + raise RuntimeError(f"No cam4 takes found below {root}") + + take_rows: list[dict[str, object]] = [] + depth_candidates: list[Path] = [] + invalid_visuals: dict[str, list[dict[str, object]]] = {"left": [], "right": []} + record_lengths = {"hand_pose": Counter(), "hand_pose_mano": Counter(), "cam_pose": Counter()} + valid_combinations = Counter() + valid_agreement = Counter() + projection_counts = {side: Counter() for side in SIDES} + raw_to_wrist_offsets = {side: [] for side in SIDES} + raw_wrist_distance_mm = {side: [] for side in SIDES} + rotation_det_errors: list[float] = [] + rotation_orth_errors: list[float] = [] + pose_last_row_errors: list[float] = [] + intrinsics_rows: list[list[float]] = [] + image_shapes = Counter() + missing_by_modality = Counter() + extra_by_modality = Counter() + frame_count = 0 + nonfinite_records = Counter() + + frame_csv = output / "frame_audit.csv" + frame_fields = [ + "subject", + "scene", + "take", + "frame_id", + "joint_left_valid", + "joint_right_valid", + "mano_left_valid", + "mano_right_valid", + "left_joints_in_frame", + "right_joints_in_frame", + "left_wrist_in_frame", + "right_wrist_in_frame", + "left_raw_to_wrist_mm", + "right_raw_to_wrist_mm", + "rgb_path", + ] + + with frame_csv.open("w", newline="", encoding="utf-8") as frame_handle: + writer = csv.DictWriter(frame_handle, fieldnames=frame_fields) + writer.writeheader() + + for cam4 in take_dirs: + subject, scene, take = cam4.parts[-4:-1] + K_values = load_float_record(cam4 / "cam_intrinsics.txt") + K, expected_hw = intrinsics_from_h2o(K_values) + intrinsics_rows.append(K_values.tolist()) + + frame_sets = {name: ids_in(cam4 / name) for name in CORE_FRAME_MODALITIES} + rgb_ids = frame_sets["rgb"] + for name, ids in frame_sets.items(): + missing_by_modality[name] += len(rgb_ids - ids) + extra_by_modality[name] += len(ids - rgb_ids) + + rgb_paths = sorted((cam4 / "rgb").glob("*.png")) + depth_paths = sorted((cam4 / "depth").glob("*.png")) + depth_candidates.extend(sample_evenly(depth_paths, args.depth_samples_per_take)) + if rgb_paths: + sample_rgb = cv2.imread(str(rgb_paths[0]), cv2.IMREAD_COLOR) + if sample_rgb is None: + raise RuntimeError(f"Could not decode {rgb_paths[0]}") + image_shapes[str(tuple(sample_rgb.shape))] += 1 + if sample_rgb.shape[:2] != expected_hw: + raise ValueError( + f"K image size {expected_hw} does not match RGB {sample_rgb.shape[:2]} at {cam4}" + ) + + take_rows.append( + { + "subject": subject, + "scene": scene, + "take": take, + "frames": len(rgb_ids), + **{f"missing_{name}": len(rgb_ids - ids) for name, ids in frame_sets.items()}, + **{f"extra_{name}": len(ids - rgb_ids) for name, ids in frame_sets.items()}, + } + ) + + for frame_id in sorted(rgb_ids): + stem = f"{frame_id:06d}" + joint_values = load_float_record(cam4 / "hand_pose" / f"{stem}.txt") + mano_values = load_float_record(cam4 / "hand_pose_mano" / f"{stem}.txt") + pose_values = load_float_record(cam4 / "cam_pose" / f"{stem}.txt") + record_lengths["hand_pose"][str(joint_values.size)] += 1 + record_lengths["hand_pose_mano"][str(mano_values.size)] += 1 + record_lengths["cam_pose"][str(pose_values.size)] += 1 + if not np.isfinite(joint_values).all(): + nonfinite_records["hand_pose"] += 1 + if not np.isfinite(mano_values).all(): + nonfinite_records["hand_pose_mano"] += 1 + if not np.isfinite(pose_values).all(): + nonfinite_records["cam_pose"] += 1 + + joints = parse_joint_record(joint_values) + mano = parse_mano_record(mano_values) + joint_key = tuple(bool(value) for value in joints.annotation_valid) + mano_key = tuple(bool(value) for value in mano.annotation_valid) + valid_combinations[f"joint_{int(joint_key[0])}{int(joint_key[1])}"] += 1 + valid_combinations[f"mano_{int(mano_key[0])}{int(mano_key[1])}"] += 1 + valid_agreement[str(joint_key == mano_key)] += 1 + + camera_pose = pose_values.reshape(4, 4) + rotation = camera_pose[:3, :3] + rotation_det_errors.append(abs(float(np.linalg.det(rotation)) - 1.0)) + rotation_orth_errors.append(float(np.linalg.norm(rotation.T @ rotation - np.eye(3)))) + pose_last_row_errors.append(float(np.linalg.norm(camera_pose[3] - np.array([0, 0, 0, 1])))) + + frame_row: dict[str, object] = { + "subject": subject, + "scene": scene, + "take": take, + "frame_id": frame_id, + "joint_left_valid": int(joints.annotation_valid[0]), + "joint_right_valid": int(joints.annotation_valid[1]), + "mano_left_valid": int(mano.annotation_valid[0]), + "mano_right_valid": int(mano.annotation_valid[1]), + "rgb_path": str(cam4 / "rgb" / f"{stem}.png"), + } + + for side_index, side in enumerate(SIDES): + in_frame_count = -1 + wrist_in_frame = -1 + distance_mm = float("nan") + if joints.annotation_valid[side_index]: + uv, positive = project_points(joints.joints_camera_m[side_index], K) + inside = ( + positive + & (uv[:, 0] >= 0) + & (uv[:, 0] < expected_hw[1]) + & (uv[:, 1] >= 0) + & (uv[:, 1] < expected_hw[0]) + ) + in_frame_count = int(inside.sum()) + wrist_in_frame = int(inside[0]) + projection_counts[side]["valid"] += 1 + projection_counts[side]["any_joint_in_frame"] += int(inside.any()) + projection_counts[side]["all_joints_in_frame"] += int(inside.all()) + projection_counts[side]["wrist_in_frame"] += int(inside[0]) + projection_counts[side]["all_positive_z"] += int(positive.all()) + + if joints.annotation_valid[side_index] and mano.annotation_valid[side_index]: + offset = ( + joints.joints_camera_m[side_index, 0] + - mano.translation_raw_m[side_index] + ) + raw_to_wrist_offsets[side].append(offset.astype(np.float64)) + distance_mm = float(np.linalg.norm(offset) * 1000.0) + raw_wrist_distance_mm[side].append(distance_mm) + + frame_row[f"{side}_joints_in_frame"] = in_frame_count + frame_row[f"{side}_wrist_in_frame"] = wrist_in_frame + frame_row[f"{side}_raw_to_wrist_mm"] = distance_mm + + if not joints.annotation_valid[side_index]: + invalid_visuals[side].append( + { + "rgb_path": cam4 / "rgb" / f"{stem}.png", + "label": f"{subject}/{scene}/{take}/{stem} {side} ann=0", + } + ) + + writer.writerow(frame_row) + frame_count += 1 + + take_csv = output / "take_audit.csv" + with take_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(take_rows[0])) + writer.writeheader() + writer.writerows(take_rows) + + depth_rows: list[dict[str, object]] = [] + pooled_depth: list[np.ndarray] = [] + for path in depth_candidates: + depth_mm = cv2.imread(str(path), cv2.IMREAD_UNCHANGED) + if depth_mm is None: + raise RuntimeError(f"Could not decode depth {path}") + depth_m, valid = depth_mm_to_m(depth_mm) + positive = depth_m[valid] + sampled = positive[::64] if positive.size else positive + pooled_depth.append(sampled) + depth_rows.append( + { + "path": str(path), + "dtype": str(depth_mm.dtype), + "height": depth_mm.shape[0], + "width": depth_mm.shape[1], + "zero_fraction": float((depth_mm == 0).mean()), + "positive_min_m": float(positive.min()) if positive.size else None, + "positive_p50_m": float(np.quantile(positive, 0.50)) if positive.size else None, + "positive_p95_m": float(np.quantile(positive, 0.95)) if positive.size else None, + "positive_p99_m": float(np.quantile(positive, 0.99)) if positive.size else None, + "positive_max_m": float(positive.max()) if positive.size else None, + "fraction_gt_3_86m": float((depth_m > 3.86).mean()), + "fraction_gt_5_46m": float((depth_m > 5.46).mean()), + } + ) + + depth_csv = output / "depth_sample_stats.csv" + with depth_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(depth_rows[0])) + writer.writeheader() + writer.writerows(depth_rows) + + selected_invalid = {} + for side in SIDES: + candidates = invalid_visuals[side] + rng.shuffle(candidates) + selected_invalid[side] = candidates[: args.invalid_visual_samples] + make_contact_sheet( + selected_invalid[side], + output / f"annotation_invalid_{side}_contact_sheet.jpg", + f"H2O cam4 {side}: annotation_valid=0 (not a presence label)", + ) + + intrinsics = np.asarray(intrinsics_rows, dtype=np.float64) + combined_depth = np.concatenate(pooled_depth) if pooled_depth else np.empty(0) + summary = { + "root": str(root), + "seed": args.seed, + "take_count": len(take_dirs), + "frame_count": frame_count, + "camera": "cam4_only", + "record_length_distributions": { + name: dict(counter) for name, counter in record_lengths.items() + }, + "valid_combinations": dict(valid_combinations), + "joint_mano_valid_agreement": dict(valid_agreement), + "annotation_valid_is_presence": False, + "presence_fields_found": False, + "presence_training_recommendation": "disabled_until_reliable_labels_exist", + "projection_from_annotation_valid_joints": { + side: dict(counter) for side, counter in projection_counts.items() + }, + "raw_mano_translation_is_wrist": False, + "raw_to_wrist_offset_m": { + side: { + "x": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 0]), + "y": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 1]), + "z": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 2]), + "norm_mm": quantiles(raw_wrist_distance_mm[side]), + } + for side in SIDES + }, + "frame_alignment": { + "missing_by_modality": dict(missing_by_modality), + "extra_by_modality": dict(extra_by_modality), + }, + "nonfinite_records": dict(nonfinite_records), + "camera_pose": { + "det_rotation_abs_error": quantiles(rotation_det_errors), + "orthogonality_frobenius_error": quantiles(rotation_orth_errors), + "last_row_error": quantiles(pose_last_row_errors), + }, + "intrinsics": { + "count": int(intrinsics.shape[0]), + "fx": quantiles(intrinsics[:, 0]), + "fy": quantiles(intrinsics[:, 1]), + "cx": quantiles(intrinsics[:, 2]), + "cy": quantiles(intrinsics[:, 3]), + "width_values": sorted(set(intrinsics[:, 4].tolist())), + "height_values": sorted(set(intrinsics[:, 5].tolist())), + }, + "rgb_shapes_by_take": dict(image_shapes), + "depth_audit": { + "sampling": "uniform frames within every take; all sampled pixels decoded", + "sample_count": len(depth_rows), + "samples_per_take": args.depth_samples_per_take, + "positive_depth_m": quantiles(combined_depth), + "zero_fraction_across_sample_means": quantiles( + [float(row["zero_fraction"]) for row in depth_rows] + ), + }, + "visibility_or_occlusion_fields": [], + "outputs": { + "frame_csv": str(frame_csv), + "take_csv": str(take_csv), + "depth_csv": str(depth_csv), + "invalid_contact_sheets": { + side: str(output / f"annotation_invalid_{side}_contact_sheet.jpg") + for side in SIDES + }, + }, + } + (output / "cam4_audit_summary.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(summary, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() + diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase3_evaluations.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase3_evaluations.py new file mode 100644 index 0000000000000000000000000000000000000000..49def655a023b3142313873e6958a56e53230566 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase3_evaluations.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Audit complete Phase 3 official-validation outputs.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path + + +def json_finite(value) -> bool: + if isinstance(value, float): + return math.isfinite(value) + if isinstance(value, dict): + return all(json_finite(item) for item in value.values()) + if isinstance(value, (list, tuple)): + return all(json_finite(item) for item in value) + return True + + +def audit_csv(path: Path, expected_rows: int) -> tuple[int, bool]: + rows = 0 + finite = True + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + rows += 1 + for value in row.values(): + if value in (None, ""): + continue + try: + numeric = float(value) + except ValueError: + continue + finite = finite and math.isfinite(numeric) + return rows, finite and rows == expected_rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("evaluation_root", type=Path) + parser.add_argument("--expected-evaluations", type=int, required=True) + parser.add_argument("--expected-clips", type=int, default=1495) + parser.add_argument("--expected-frames", type=int, default=11638) + parser.add_argument("--expected-frame-rows", type=int, default=23276) + parser.add_argument("--expected-transition-rows", type=int, default=30293) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + + reports = sorted(args.evaluation_root.glob("*/*/evaluation.json")) + records = [] + for path in reports: + report = json.loads(path.read_text(encoding="utf-8")) + frame_rows, frame_csv_valid = audit_csv( + path.parent / "per_hand_frame_metrics.csv", args.expected_frame_rows, + ) + transition_rows, transition_csv_valid = audit_csv( + path.parent / "per_temporal_transition_metrics.csv", + args.expected_transition_rows, + ) + passed = ( + report.get("status") == "evaluated" + and report.get("official_test_used") is False + and report.get("split_role") == "official_validation" + and report.get("clips") == args.expected_clips + and report.get("frames") == args.expected_frames + and json_finite(report) + and frame_csv_valid + and transition_csv_valid + ) + records.append({ + "run": path.parents[1].name, + "role": path.parent.name, + "report": str(path), + "checkpoint_sha256": report.get("checkpoint", {}).get("sha256"), + "frame_rows": frame_rows, + "transition_rows": transition_rows, + "passed": passed, + }) + + passed = len(records) == args.expected_evaluations and all( + record["passed"] for record in records + ) + payload = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "evaluations": len(records), + "expected_evaluations": args.expected_evaluations, + "total_frame_rows": sum(record["frame_rows"] for record in records), + "total_transition_rows": sum(record["transition_rows"] for record in records), + "records": records, + } + output = args.output or args.evaluation_root / "evaluation_audit.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": payload["status"], "evaluations": len(records), + "output": str(output), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase3_periodic_checkpoints.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase3_periodic_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..800daf71cffb5e2c37ca0ecb20384214bdd44b88 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase3_periodic_checkpoints.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Audit periodic Phase 3 checkpoints with one isolated loader per run.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +from pathlib import Path + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def worker(checkpoint_path: Path) -> None: + import torch + + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + model_finite = all( + not torch.is_tensor(value) or torch.isfinite(value).all().item() + for value in checkpoint.get("model", {}).values() + ) + print(json.dumps({ + "step": int(checkpoint["step"]), + "model_finite": model_finite, + "bytes": checkpoint_path.stat().st_size, + "sha256": sha256(checkpoint_path), + })) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_root", type=Path, nargs="?") + parser.add_argument("--step", type=int) + parser.add_argument("--expected-runs", type=int) + parser.add_argument("--run-prefix") + parser.add_argument("--output", type=Path) + parser.add_argument("--worker", type=Path) + args = parser.parse_args() + + if args.worker is not None: + worker(args.worker) + return + if args.run_root is None or args.step is None: + parser.error("run_root and --step are required") + + checkpoint_name = f"step_{args.step:07d}.pt" + run_dirs = sorted( + path.parent for path in args.run_root.glob(f"*/{checkpoint_name}") + if path.parent.is_dir() + and (args.run_prefix is None or path.parent.name.startswith(args.run_prefix)) + ) + if args.expected_runs is not None and len(run_dirs) != args.expected_runs: + raise ValueError( + f"expected {args.expected_runs} {checkpoint_name} files, found {len(run_dirs)}" + ) + + records = [] + for run_dir in run_dirs: + checkpoint_path = run_dir / checkpoint_name + process = subprocess.run( + [sys.executable, str(Path(__file__).resolve()), "--worker", str(checkpoint_path)], + check=True, capture_output=True, text=True, + ) + checkpoint_record = json.loads(process.stdout) + validation_rows = [ + json.loads(line) for line in (run_dir / "validation.jsonl").read_text( + encoding="utf-8" + ).splitlines() if line.strip() + ] + matching_validation = [ + row for row in validation_rows if int(row["step"]) == args.step + ] + provenance_path = run_dir / "run_provenance.json" + if not provenance_path.is_file(): + candidates = sorted(run_dir.glob("resume_provenance_*.json")) + if len(candidates) != 1: + raise FileNotFoundError( + f"expected one run/resume provenance file in {run_dir}" + ) + provenance_path = candidates[0] + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + records.append({ + "run": run_dir.name, + **checkpoint_record, + "run_commit": provenance.get("git_commit"), + "validation_records": len(matching_validation), + "validation_total_loss": ( + matching_validation[0]["losses"]["total"] + if len(matching_validation) == 1 else None + ), + }) + + passed = bool(records) and all( + record["step"] == args.step + and record["model_finite"] + and record["validation_records"] == 1 + for record in records + ) + result = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "expected_step": args.step, + "run_prefix": args.run_prefix, + "runs": records, + } + suffix = f"{args.step // 1000}k" if args.step % 1000 == 0 else str(args.step) + prefix = f"{args.run_prefix.rstrip('_-')}_" if args.run_prefix else "" + output_path = ( + args.output + if args.output is not None + else args.run_root / f"checkpoint_audit_{prefix}{suffix}.json" + ) + if output_path.exists(): + raise FileExistsError(f"refusing to overwrite checkpoint audit: {output_path}") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": result["status"], "runs": len(records), "output": str(output_path) + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase3_run_checkpoints.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase3_run_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..e64c457dd74c0cd479f2c2f786f5f4e3c7ad56b5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase3_run_checkpoints.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Audit one completed Phase 3 run in an isolated process.""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +from pathlib import Path + +import torch + + +FINAL_ROLES = { + "step_100k": "step_0100000.pt", + "best_absolute": "best.pt", + "best_z": "best_z.pt", + "final": "step_0100000_final.pt", +} + + +def load_roles(path: Path | None) -> dict[str, str]: + if path is None: + return dict(FINAL_ROLES) + values = json.loads(path.read_text(encoding="utf-8")) + if ( + not isinstance(values, dict) + or not values + or any(not isinstance(role, str) or not role for role in values) + or any( + not isinstance(filename, str) or Path(filename).name != filename + for filename in values.values() + ) + ): + raise ValueError("checkpoint spec must be a non-empty role-to-filename JSON object") + return values + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_dir", type=Path) + parser.add_argument("--completed-step", type=int, default=100_000) + parser.add_argument("--checkpoint-spec", type=Path) + args = parser.parse_args() + roles = load_roles(args.checkpoint_spec) + summary = json.loads((args.run_dir / "summary.json").read_text(encoding="utf-8")) + result = { + "run": args.run_dir.name, + "summary_status": summary.get("status"), + "completed_step": summary.get("completed_step"), + "official_test_used": False, + "roles": {}, + } + for role, filename in roles.items(): + path = args.run_dir / filename + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + finite = all( + not torch.is_tensor(value) or torch.isfinite(value).all().item() + for value in checkpoint.get("model", {}).values() + ) + result["roles"][role] = { + "path": str(path), + "bytes": path.stat().st_size, + "sha256": sha256(path), + "step": int(checkpoint["step"]), + "model_finite": finite, + } + del checkpoint + gc.collect() + result["status"] = "passed" if ( + result["summary_status"] == "completed" + and result["completed_step"] == args.completed_step + and all(item["model_finite"] for item in result["roles"].values()) + ) else "failed" + output = args.run_dir / "final_checkpoint_audit.json" + output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"run": args.run_dir.name, "status": result["status"]})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase4_visualizations.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase4_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..afb6efba5a62c71bf21add06f75168566c1a33f0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase4_visualizations.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Audit raw/filtered Phase 4 videos and deterministic rerender pixels.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def fraction(value: str) -> float: + numerator, denominator = value.split("/", 1) + return float(numerator) / float(denominator) + + +def probe_video(path: Path) -> dict[str, object]: + process = subprocess.run([ + "ffprobe", "-v", "error", "-select_streams", "v:0", + "-show_entries", "stream=codec_name,pix_fmt,width,height,avg_frame_rate,nb_frames,duration", + "-of", "json", str(path), + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) + streams = json.loads(process.stdout).get("streams", []) + if len(streams) != 1: + raise ValueError(f"expected one video stream: {path}") + stream = streams[0] + return { + "codec": stream.get("codec_name"), + "pixel_format": stream.get("pix_fmt"), + "width": int(stream["width"]), "height": int(stream["height"]), + "fps": fraction(stream["avg_frame_rate"]), + "frames": int(stream["nb_frames"]), + "duration_seconds": float(stream["duration"]), + } + + +def decoded_frame_audit(path: Path, expected_frames: int) -> list[dict[str, object]]: + capture = cv2.VideoCapture(str(path)) + if not capture.isOpened(): + raise RuntimeError(f"cannot decode video: {path}") + records = [] + try: + for index in sorted({0, expected_frames // 2, expected_frames - 1}): + capture.set(cv2.CAP_PROP_POS_FRAMES, index) + ok, frame = capture.read() + if not ok or frame is None: + raise RuntimeError(f"cannot decode frame {index}: {path}") + std = float(frame.std()) + nonzero_fraction = float(np.count_nonzero(frame) / frame.size) + if std < 1.0 or nonzero_fraction < 0.05: + raise ValueError(f"blank/degenerate frame {index}: {path}") + records.append({ + "frame_index": index, "std": std, + "nonzero_fraction": nonzero_fraction, + "pixel_sha256": hashlib.sha256(frame.tobytes()).hexdigest(), + }) + finally: + capture.release() + return records + + +def audit_video( + path: Path, + *, + expected_frames: int, + expected_fps: float, + expected_sha256: str | None = None, + require_h264: bool = False, +) -> dict[str, object]: + if not path.is_file(): + raise FileNotFoundError(path) + digest = sha256(path) + if expected_sha256 is not None and digest != expected_sha256: + raise ValueError(f"video SHA256 mismatch: {path}") + probe = probe_video(path) + if probe["frames"] != expected_frames: + raise ValueError(f"video frame count mismatch: {path}") + if abs(float(probe["fps"]) - expected_fps) > 1e-3: + raise ValueError(f"video fps mismatch: {path}") + if require_h264 and ( + probe["codec"] != "h264" or probe["pixel_format"] != "yuv420p" + ): + raise ValueError(f"filtered video codec contract mismatch: {path}") + return { + "path": str(path.resolve()), "sha256": digest, **probe, + "decoded_frames": decoded_frame_audit(path, expected_frames), + "passed": True, + } + + +def deterministic_frame_hash_audit( + primary: dict[str, Any], rerun: dict[str, Any], +) -> int: + def index(manifest: dict[str, Any]) -> dict[tuple[str, str, str], list[str]]: + return { + (record["take"], record["condition"], video_name): video["frame_pixel_sha256"] + for record in manifest["cases"] + for video_name, video in record["videos"].items() + } + left, right = index(primary), index(rerun) + if left.keys() != right.keys(): + raise ValueError("deterministic video case grid mismatch") + for key in left: + if left[key] != right[key]: + raise ValueError(f"deterministic frame pixel mismatch: {key}") + return sum(len(values) for values in left.values()) + + +def audit_raw_manifest(manifest: dict[str, Any]) -> list[dict[str, object]]: + if manifest.get("status") != "complete" or manifest.get("official_test_used") is not False: + raise ValueError("invalid raw video manifest") + fps = float(manifest["visualization_fps"]) + records = [] + for case in manifest["cases"]: + frame_count = len(case["frame_ids"]) + for role, path in case["videos"].items(): + records.append({ + "set": "raw_model_primary_results", "take": case["take"], + "condition": "raw", "role": role, + **audit_video( + Path(path), expected_frames=frame_count, expected_fps=fps, + ), + }) + return records + + +def audit_filtered_manifest(manifest: dict[str, Any]) -> list[dict[str, object]]: + if ( + manifest.get("status") != "complete" + or manifest.get("official_test_used") is not False + or manifest.get("result_role") != "filtered_inference_secondary_results" + ): + raise ValueError("invalid filtered video manifest") + records = [] + expected_roles = { + "raw_vs_filtered_30fps", "raw_vs_filtered_4fps", + "failure_diagnostic_30fps", + } + for case in manifest["cases"]: + if set(case["videos"]) != expected_roles: + raise ValueError("filtered video role grid mismatch") + for role, video in case["videos"].items(): + records.append({ + "set": "filtered_inference_secondary_results", + "take": case["take"], "condition": case["condition"], + "role": role, + **audit_video( + Path(video["path"]), expected_frames=int(video["frames"]), + expected_fps=float(video["fps"]), + expected_sha256=video["sha256"], require_h264=True, + ), + }) + return records + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--raw-manifest", type=Path, required=True) + parser.add_argument("--filtered-manifest", type=Path, required=True) + parser.add_argument("--filtered-rerun-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite visualization audit: {args.output}") + raw = json.loads(args.raw_manifest.read_text(encoding="utf-8")) + filtered = json.loads(args.filtered_manifest.read_text(encoding="utf-8")) + rerun = json.loads(args.filtered_rerun_manifest.read_text(encoding="utf-8")) + records = audit_raw_manifest(raw) + records.extend(audit_filtered_manifest(filtered)) + records.extend(audit_filtered_manifest(rerun)) + compared_frames = deterministic_frame_hash_audit(filtered, rerun) + report = { + "status": "passed", + "official_test_used": False, + "videos": len(records), + "deterministic_frame_hashes_compared": compared_frames, + "raw_model_primary_results_kept_separate": True, + "filtered_inference_secondary_results_kept_separate": True, + "records": records, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "passed", "videos": len(records), + "deterministic_frame_hashes_compared": compared_frames, + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_alignment_visualizations.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_alignment_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..3ebd0b9fb31f916e3a2c0aaa08e79f95d53b848a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_alignment_visualizations.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Audit deterministic Phase 5 alignment diagnostic images.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def case_without_path(case: dict[str, Any]) -> dict[str, Any]: + return {key: value for key, value in case.items() if key not in ("image", "image_sha256")} + + +def image_audit(case: dict[str, Any]) -> dict[str, Any]: + path = Path(case["image"]) + digest = sha256(path) + if digest != case["image_sha256"]: + raise ValueError(f"manifest image hash mismatch: {path}") + image = cv2.imread(str(path), cv2.IMREAD_COLOR) + if image is None: + raise ValueError(f"cannot decode diagnostic image: {path}") + std = float(image.std()) + nonzero_fraction = float(np.count_nonzero(image) / image.size) + if min(image.shape[:2]) < 480 or std < 5.0 or nonzero_fraction < 0.2: + raise ValueError(f"blank or degenerate diagnostic image: {path}") + return { + "role": case["role"], "path": str(path.resolve()), "sha256": digest, + "width": int(image.shape[1]), "height": int(image.shape[0]), + "pixel_std": std, "nonzero_fraction": nonzero_fraction, + } + + +def audit_manifests( + primary: dict[str, Any], rerun: dict[str, Any], +) -> dict[str, Any]: + for manifest in (primary, rerun): + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_validation_secondary_failure_diagnostic" + or manifest.get("official_test_used") is not False + or manifest.get("used_for_model_or_threshold_selection") is not False + ): + raise ValueError("invalid alignment visualization manifest contract") + left = {case["role"]: case for case in primary["cases"]} + right = {case["role"]: case for case in rerun["cases"]} + if left.keys() != right.keys() or len(left) != len(primary["cases"]): + raise ValueError("visualization role grid mismatch or duplicate role") + primary_records, rerun_records = [], [] + for role in left: + if case_without_path(left[role]) != case_without_path(right[role]): + raise ValueError(f"visualization case metadata mismatch: {role}") + primary_record = image_audit(left[role]) + rerun_record = image_audit(right[role]) + if primary_record["sha256"] != rerun_record["sha256"]: + raise ValueError(f"deterministic image hash mismatch: {role}") + primary_records.append(primary_record) + rerun_records.append(rerun_record) + return { + "status": "passed", + "result_role": "deterministic_official_validation_visualization_audit", + "cases": len(left), + "deterministic_image_hashes_compared": len(left), + "primary": primary_records, + "rerun": rerun_records, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--primary-manifest", type=Path, required=True) + parser.add_argument("--rerun-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError("visualization audit refuses to overwrite output") + primary = json.loads(args.primary_manifest.read_text(encoding="utf-8")) + rerun = json.loads(args.rerun_manifest.read_text(encoding="utf-8")) + report = audit_manifests(primary, rerun) + report.update({ + "primary_manifest": str(args.primary_manifest.resolve()), + "rerun_manifest": str(args.rerun_manifest.resolve()), + }) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "cases": report["cases"], + "output": str(args.output), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_oof_bank.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..3d6814f9f1d8ebb1112e0086b5e5f95a44cd9f77 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_oof_bank.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python3 +"""Audit Phase 5 group-heldout coarse banks before refiner fitting.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + + +TAIL_ADMISSION_P95_MM = 40.0 +SEEDS = (20260716, 20260717, 20260718) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def distribution(values_m: np.ndarray) -> dict[str, float | int]: + values_mm = np.asarray(values_m, dtype=np.float64).reshape(-1) * 1000.0 + values_mm = values_mm[np.isfinite(values_mm)] + if not values_mm.size: + raise ValueError("cannot summarize an empty residual distribution") + absolute = np.abs(values_mm) + p95 = float(np.percentile(absolute, 95)) + return { + "count": int(len(values_mm)), + "signed_mean_mm": float(values_mm.mean()), + "signed_std_mm": float(values_mm.std()), + "mae_mm": float(absolute.mean()), + "p50_mm": float(np.percentile(absolute, 50)), + "p90_mm": float(np.percentile(absolute, 90)), + "p95_mm": p95, + "p99_mm": float(np.percentile(absolute, 99)), + "cvar95_mm": float(absolute[absolute >= p95].mean()), + "maximum_mm": float(absolute.max()), + } + + +def size_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 64.0, "small", np.where(values < 128.0, "medium", "large")) + + +def depth_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 0.5, "near", np.where(values < 0.8, "middle", "far")) + + +def validity_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 0.25, "low", np.where(values < 0.60, "partial", "strong")) + + +def validate_bank_manifest(path: Path) -> dict[str, Any]: + manifest = json.loads(path.read_text(encoding="utf-8")) + required = ( + manifest.get("status") == "complete", + manifest.get("bank_version") == 2, + manifest.get("scope") == "full_fold", + manifest.get("result_role") == "official_train_group_heldout_oof_predictions", + manifest.get("leakage_audit", {}).get("passed") is True, + manifest.get("official_validation_used_for_assignment") is False, + manifest.get("official_test_used") is False, + manifest.get("oracle_information_at_inference") is False, + ) + if not all(required): + raise ValueError(f"OOF audit requires a complete leakage-free full-fold bank: {path}") + return manifest + + +def load_oof_banks(bank_dirs: list[Path]) -> tuple[dict[str, np.ndarray], list[dict[str, Any]]]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + manifests = [] + observed_pairs: set[tuple[int, str]] = set() + keys_by_checkpoint: dict[str, set[str]] = defaultdict(set) + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = validate_bank_manifest(manifest_path) + manifests.append(manifest) + fold = int(manifest["fold"]) + checkpoint = str(manifest["checkpoint"]["sha256"]) + pair = (fold, checkpoint) + if pair in observed_pairs: + raise ValueError(f"duplicate fold/checkpoint bank: {pair}") + observed_pairs.add(pair) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take bank hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in ( + "frame_id", "frame_valid", "mano_annotation_valid", + "translation_residual_m", "target_wrist_translation", + "coarse_hand_scale_px", "alignment_valid_fraction", + )} + valid = arrays["frame_valid"].astype(bool)[:, None] & arrays[ + "mano_annotation_valid" + ].astype(bool) + time = len(arrays["frame_id"]) + side = np.broadcast_to(np.asarray(("left", "right"))[None], (time, 2)) + frame = np.broadcast_to(arrays["frame_id"][:, None], (time, 2)) + take = str(take_record["take"]) + subject, action_family = take.split("/")[:2] + sample_keys = np.asarray([ + f"{take}|{int(frame_id)}|{hand}" + for frame_id, hand in zip(frame[valid], side[valid], strict=True) + ]) + duplicate_keys = keys_by_checkpoint[checkpoint].intersection(sample_keys.tolist()) + if duplicate_keys: + raise ValueError(f"duplicate samples within checkpoint bank: {take}") + keys_by_checkpoint[checkpoint].update(sample_keys.tolist()) + count = int(valid.sum()) + chunks["residual_z_m"].append(arrays["translation_residual_m"][..., 2][valid]) + chunks["side"].append(side[valid]) + chunks["frame_id"].append(frame[valid]) + chunks["sample_key"].append(sample_keys) + chunks["subject"].append(np.full(count, subject)) + chunks["action_family"].append(np.full(count, action_family)) + chunks["take"].append(np.full(count, take)) + chunks["fold"].append(np.full(count, fold, dtype=np.int16)) + chunks["coarse_seed"].append(np.full(count, int(manifest.get("seed", -1)), dtype=np.int64)) + chunks["checkpoint"].append(np.full(count, checkpoint)) + chunks["hand_scale_px"].append(arrays["coarse_hand_scale_px"][valid]) + chunks["wrist_depth_m"].append(arrays["target_wrist_translation"][..., 2][valid]) + chunks["local_depth_valid_fraction"].append(arrays["alignment_valid_fraction"][valid]) + if {int(manifest["fold"]) for manifest in manifests} != {0, 1, 2}: + raise ValueError("OOF audit requires coverage of folds 0/1/2") + return {key: np.concatenate(values) for key, values in chunks.items()}, manifests + + +def validation_reference(a1_root: Path) -> tuple[list[dict[str, Any]], np.ndarray]: + rows = [] + values = [] + for seed in SEEDS: + with np.load(a1_root / f"seed_{seed}" / "validation" / "features.npz", allow_pickle=False) as archive: + residual = archive["target_residual_z_m"].astype(np.float64) + rows.append({"seed": seed, **distribution(residual)}) + values.append(residual) + return rows, np.concatenate(values) + + +def cross_checkpoint_correlations(samples: dict[str, np.ndarray]) -> dict[str, Any]: + maps: dict[str, dict[str, float]] = defaultdict(dict) + metadata: dict[str, dict[str, int]] = {} + for checkpoint, key, residual, fold, seed in zip( + samples["checkpoint"], samples["sample_key"], samples["residual_z_m"], + samples["fold"], samples["coarse_seed"], strict=True, + ): + checkpoint = str(checkpoint) + maps[checkpoint][str(key)] = float(residual) + metadata[checkpoint] = {"fold": int(fold), "seed": int(seed)} + results = {} + checkpoints = sorted(maps) + for left_index, left in enumerate(checkpoints): + for right in checkpoints[left_index + 1:]: + overlap = sorted(set(maps[left]).intersection(maps[right])) + name = f"{left[:12]}_{right[:12]}" + if len(overlap) < 2: + results[name] = { + "status": "unavailable_no_overlapping_group_heldout_samples", + "overlap": len(overlap), + "pearson": None, + "left": {"checkpoint": left, **metadata[left]}, + "right": {"checkpoint": right, **metadata[right]}, + } + else: + x = np.asarray([maps[left][key] for key in overlap]) + y = np.asarray([maps[right][key] for key in overlap]) + results[name] = { + "status": "available", + "overlap": len(overlap), + "pearson": float(np.corrcoef(x, y)[0, 1]), + "left": {"checkpoint": left, **metadata[left]}, + "right": {"checkpoint": right, **metadata[right]}, + } + return results + + +def grouped_rows(samples: dict[str, np.ndarray]) -> list[dict[str, Any]]: + residual = samples["residual_z_m"] + groups: dict[str, np.ndarray] = { + "fold": samples["fold"].astype(str), + "checkpoint": samples["checkpoint"], + "side": samples["side"], + "subject": samples["subject"], + "action_family": samples["action_family"], + "take": samples["take"], + "hand_size": size_bucket(samples["hand_scale_px"]), + "wrist_depth": depth_bucket(samples["wrist_depth_m"]), + "local_depth_validity": validity_bucket(samples["local_depth_valid_fraction"]), + } + if np.all(samples["coarse_seed"] >= 0): + groups["coarse_seed"] = samples["coarse_seed"].astype(str) + rows = [{"source": "oof", "group": "all", "value": "all", **distribution(residual)}] + for field, values in groups.items(): + for value in sorted(set(values.tolist())): + rows.append({ + "source": "oof", "group": field, "value": value, + **distribution(residual[values == value]), + }) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--validation-a1-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("OOF audit refuses to overwrite outputs") + samples, manifests = load_oof_banks(args.bank_dir) + oof = distribution(samples["residual_z_m"]) + validation_rows, validation_values = validation_reference(args.validation_a1_root) + validation = distribution(validation_values) + quantiles = np.linspace(0.0, 1.0, 101) + quantile_l1_mm = float(np.mean(np.abs( + np.quantile(np.abs(samples["residual_z_m"]), quantiles) + - np.quantile(np.abs(validation_values), quantiles) + )) * 1000.0) + rows = grouped_rows(samples) + rows.extend({ + "source": "validation", "group": "seed", "value": row["seed"], + **{key: value for key, value in row.items() if key != "seed"}, + } for row in validation_rows) + rows.append({"source": "validation", "group": "all", "value": "all", **validation}) + tail_passed = bool(oof["p95_mm"] >= TAIL_ADMISSION_P95_MM) + report = { + "status": "passed" if tail_passed else "insufficient_oof_tail", + "experiment_class": "preregistered_data_admission_audit", + "residual_definition": "GT wrist z minus group-heldout coarse predicted wrist z", + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "folds": sorted({int(manifest["fold"]) for manifest in manifests}), + "checkpoints": sorted({str(manifest["checkpoint"]["sha256"]) for manifest in manifests}), + "coarse_seeds": sorted({ + int(manifest["seed"]) for manifest in manifests if manifest.get("seed") is not None + }), + "samples": len(samples["residual_z_m"]), + "takes": len(set(samples["take"].tolist())), + "oof": oof, + "validation_reference_by_seed": validation_rows, + "validation_reference_all": validation, + "absolute_residual_quantile_l1_distance_mm": quantile_l1_mm, + "tail_admission": { + "threshold_p95_mm": TAIL_ADMISSION_P95_MM, + "passed": tail_passed, + "rule": "do not fit a formal refiner if group-heldout OOF z P95 remains below 40 mm", + }, + "cross_checkpoint_pearson": cross_checkpoint_correlations(samples), + "leakage_audit_passed": all(manifest["leakage_audit"]["passed"] for manifest in manifests), + "official_validation_used_for_training_or_thresholds": False, + "official_test_used": False, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(json.dumps({ + "status": report["status"], "samples": report["samples"], "takes": report["takes"], + "oof": oof, "validation": validation, "official_test_used": False, + }, indent=2)) + if not tail_passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_periodic_checkpoints.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_periodic_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..d039ac0e31f689bff49638990e6f519f51a0a996 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_periodic_checkpoints.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Audit Phase 5 periodic checkpoints, logs, provenance, and validation contract.""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +from pathlib import Path + +import torch + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_tree(value: object) -> bool: + if torch.is_tensor(value): + return bool(torch.isfinite(value).all()) if value.is_floating_point() else True + if isinstance(value, dict): + return all(finite_tree(item) for item in value.values()) + if isinstance(value, (list, tuple)): + return all(finite_tree(item) for item in value) + return True + + +def audit_run(run_dir: Path, step: int, expected_validation_records: int) -> dict[str, object]: + checkpoint_path = run_dir / f"step_{step:07d}.pt" + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + checkpoint_record = { + "path": str(checkpoint_path.resolve()), + "bytes": checkpoint_path.stat().st_size, + "sha256": sha256(checkpoint_path), + "step": int(checkpoint["step"]), + "model_finite": finite_tree(checkpoint.get("model", {})), + "optimizer_finite": finite_tree(checkpoint.get("optimizer", {})), + } + del checkpoint + gc.collect() + + provenance = json.loads((run_dir / "run_provenance.json").read_text(encoding="utf-8")) + train_lines = [ + line for line in (run_dir / "train_metrics.jsonl").read_text(encoding="utf-8").splitlines() + if line.strip() + ] + last_train = json.loads(train_lines[-1]) if train_lines else {} + validation_path = run_dir / "validation.jsonl" + validation_rows = ( + [json.loads(line) for line in validation_path.read_text(encoding="utf-8").splitlines() if line.strip()] + if validation_path.is_file() else [] + ) + matching_validation = [row for row in validation_rows if int(row["step"]) == step] + finite_validation = finite_tree(matching_validation) + passed = ( + checkpoint_record["step"] == step + and checkpoint_record["model_finite"] + and checkpoint_record["optimizer_finite"] + and provenance.get("git_status") in ("", None) + and int(last_train.get("step", -1)) >= step + and len(matching_validation) == expected_validation_records + and finite_validation + ) + return { + "run": run_dir.name, + "status": "passed" if passed else "failed", + "checkpoint": checkpoint_record, + "git_commit": provenance.get("git_commit"), + "git_status_clean": provenance.get("git_status") in ("", None), + "train_manifest": provenance.get("hashes", {}).get("train_manifest"), + "config": provenance.get("hashes", {}).get("config"), + "last_train_step": last_train.get("step"), + "last_gradient_norm": last_train.get("gradient_norm"), + "last_frames_per_s": last_train.get("frames_per_s"), + "validation_records_at_step": len(matching_validation), + "expected_validation_records_at_step": expected_validation_records, + "validation_finite": finite_validation, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_root", type=Path) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--expected-runs", type=int, required=True) + parser.add_argument("--expected-validation-records", type=int, choices=(0, 1), required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite audit: {args.output}") + checkpoint_name = f"step_{args.step:07d}.pt" + run_dirs = sorted(path.parent for path in args.run_root.glob(f"*/{checkpoint_name}")) + if len(run_dirs) != args.expected_runs: + raise ValueError( + f"expected {args.expected_runs} {checkpoint_name} files, found {len(run_dirs)}" + ) + records = [ + audit_run(run_dir, args.step, args.expected_validation_records) + for run_dir in run_dirs + ] + passed = bool(records) and all(record["status"] == "passed" for record in records) + report = { + "status": "passed" if passed else "failed", + "expected_step": args.step, + "expected_runs": args.expected_runs, + "expected_validation_records_at_step": args.expected_validation_records, + "runs": records, + "official_test_used": False, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "runs": len(records), "output": str(args.output), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_residual_shift.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_residual_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..62c3bfe1f2b6ba39dc8a5cfb4b4c19d0c926de49 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase5_residual_shift.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Audit in-fold train versus held-out validation coarse z residual shift.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import numpy as np + + +SEEDS = (20260716, 20260717, 20260718) + + +def distribution(values_m: np.ndarray) -> dict[str, float | int]: + values_mm = np.asarray(values_m, dtype=np.float64) * 1000.0 + absolute = np.abs(values_mm) + p95 = float(np.percentile(absolute, 95)) + return { + "count": int(len(values_mm)), + "signed_mean_mm": float(values_mm.mean()), + "mae_mm": float(absolute.mean()), + "p50_mm": float(np.percentile(absolute, 50)), + "p90_mm": float(np.percentile(absolute, 90)), + "p95_mm": p95, + "p99_mm": float(np.percentile(absolute, 99)), + "cvar95_mm": float(absolute[absolute >= p95].mean()), + } + + +def load_rows(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def size_bucket(value: str) -> str: + size = float(value) + return "small" if size < 64.0 else "medium" if size < 128.0 else "large" + + +def depth_bucket(value: str) -> str: + depth = float(value) + return "near" if depth < 0.5 else "middle" if depth < 0.8 else "far" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--a1-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("residual-shift audit refuses to overwrite outputs") + + split_values: dict[str, dict[int, np.ndarray]] = {"train": {}, "validation": {}} + split_rows: dict[str, list[dict[str, str]]] = {} + summary_rows = [] + group_rows = [] + for split in split_values: + metadata_reference: list[tuple[str, str, str]] | None = None + for seed in SEEDS: + root = args.a1_root / f"seed_{seed}" / split + with np.load(root / "features.npz", allow_pickle=False) as archive: + values = archive["target_residual_z_m"].astype(np.float64) + rows = load_rows(root / "samples.csv") + if len(rows) != len(values): + raise ValueError(f"feature/metadata length mismatch for {split}/{seed}") + metadata = [(row["take"], row["frame_id"], row["side"]) for row in rows] + if metadata_reference is None: + metadata_reference = metadata + split_rows[split] = rows + elif metadata != metadata_reference: + raise ValueError(f"sample alignment differs across seeds for {split}") + split_values[split][seed] = values + result = distribution(values) + summary_rows.append({"split": split, "seed": seed, "group": "all", "value": "all", **result}) + + groups: dict[tuple[str, str], list[int]] = {} + for index, row in enumerate(rows): + values_by_group = { + "side": row["side"], + "action_family": row["action_family"], + "hand_size": size_bucket(row["hand_size_px"]), + "wrist_depth": depth_bucket(row["wrist_depth_m"]), + "take": row["take"], + } + for field, value in values_by_group.items(): + groups.setdefault((field, value), []).append(index) + for (field, value), indices in sorted(groups.items()): + group_rows.append({ + "split": split, "seed": seed, "group": field, "value": value, + **distribution(values[np.asarray(indices, dtype=np.int64)]), + }) + + correlations = {} + for split, by_seed in split_values.items(): + matrix = np.corrcoef([by_seed[seed] for seed in SEEDS]) + correlations[split] = { + f"{left}_{right}": float(matrix[left_index, right_index]) + for left_index, left in enumerate(SEEDS) + for right_index, right in enumerate(SEEDS) + if left_index < right_index + } + gaps = {} + for seed in SEEDS: + train = distribution(split_values["train"][seed]) + validation = distribution(split_values["validation"][seed]) + gaps[str(seed)] = { + "mae_ratio_validation_over_train": validation["mae_mm"] / train["mae_mm"], + "p95_ratio_validation_over_train": validation["p95_mm"] / train["p95_mm"], + "mae_gap_mm": validation["mae_mm"] - train["mae_mm"], + "p95_gap_mm": validation["p95_mm"] - train["p95_mm"], + } + report = { + "status": "audited", + "experiment_class": "diagnostic_existing_predictions", + "source": "Phase 4 A1 frozen coarse feature banks", + "residual_definition": "GT wrist z minus coarse predicted wrist z", + "seeds": list(SEEDS), + "summary": summary_rows, + "cross_seed_pearson": correlations, + "validation_over_train_gap": gaps, + "sample_alignment_across_seeds": True, + "official_test_used": False, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + rows_to_write = summary_rows + group_rows + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows_to_write[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows_to_write) + print(json.dumps({ + "status": report["status"], + "train": [row for row in summary_rows if row["split"] == "train"], + "validation": [row for row in summary_rows if row["split"] == "validation"], + "correlations": correlations, + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase6_sequence_inference.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase6_sequence_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e78513782072066d17259a1a4014e154227187ec --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase6_sequence_inference.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Audit a frozen checkpoint through the bounded arbitrary-length API.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import time +from collections import defaultdict +from pathlib import Path + +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def clone_batch(batch: dict[str, object]) -> dict[str, object]: + return { + key: value.clone() if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, required=True) + parser.add_argument("--frames", type=int, default=257) + parser.add_argument("--take") + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output must not already exist") + if args.manifest.name != "official_val.jsonl": + parser.error("sequence audit is hard-gated to official validation") + if args.frames < 1 or args.window < 1: + parser.error("frames and window must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + configured_mode = config["model"].get( + "temporal_attention_mode", "bidirectional", + ) + expected_mode = "causal" if args.mode == "causal" else "bidirectional" + if configured_mode != expected_mode: + parser.error("config temporal mode differs from requested audit mode") + + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (1,), (1,), + ) + by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + by_take[clip.take].append(index) + take = args.take + if take is None: + take = next((name for name, indices in by_take.items() if len(indices) >= args.frames), None) + if take is None or len(by_take.get(take, ())) < args.frames: + raise ValueError("no requested take contains the audit frame count") + indices = by_take[take][: args.frames] + + loader = DataLoader( + Subset(dataset, indices), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.mode, window_size=args.window, + offline_stride=(args.window // 2 if args.mode == "offline" else None), + ), + device=device, autocast_dtype=dtype, + ) + frame_ids: list[int] = [] + + def frames(): + for batch in loader: + frame_ids.append(int(batch["frame_id"][0, 0])) + yield batch + + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + output = runner.infer(frames()) + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + output_time = int(output["wrist_root_translation"].shape[1]) + finite = all(torch.isfinite(value).all() for value in output.values()) + + invariance = None + if args.mode == "causal": + invariant_loader = DataLoader( + Subset(dataset, indices[:8]), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ) + first = list(invariant_loader) + full = runner._stack_frames(first) + perturbed = clone_batch(full) + perturbed["rgb"][:, 4:] = -perturbed["rgb"][:, 4:] + perturbed["depth_m"][:, 4:] = 0 + perturbed["depth_pixel_valid"][:, 4:] = False + perturbed["depth_available"][:, 4:] = False + prefix = { + key: value[:, :4] if torch.is_tensor(value) and value.ndim >= 2 + and value.shape[1] == 8 else value + for key, value in full.items() + } + full = runner._to_device(full) + perturbed = runner._to_device(perturbed) + prefix = runner._to_device(prefix) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + full_output = model(full) + perturbed_output = model(perturbed) + prefix_output = model(prefix) + future_delta = float(( + full_output["wrist_root_translation"][:, :4] + - perturbed_output["wrist_root_translation"][:, :4] + ).abs().max()) + monolithic_prefix_delta = float(( + full_output["wrist_root_translation"][:, :4] + - prefix_output["wrist_root_translation"] + ).abs().max()) + stream_full = runner.infer_causal(first)["wrist_root_translation"][:, :4] + stream_prefix = runner.infer_causal(first[:4])["wrist_root_translation"] + prefix_delta = float((stream_full - stream_prefix).abs().max()) + invariance = { + "future_perturbation_max_abs_m": future_delta, + "future_perturbation_bitwise_zero": future_delta == 0.0, + "streaming_prefix_max_abs_m": prefix_delta, + "prefix_tolerance_m": 1e-6, + "prefix_passed": prefix_delta <= 1e-6, + "monolithic_full_vs_short_batch_max_abs_m": monolithic_prefix_delta, + "monolithic_batch_size_numerical_invariance": monolithic_prefix_delta <= 1e-6, + } + + invariance_passed = invariance is None or ( + invariance["future_perturbation_bitwise_zero"] and invariance["prefix_passed"] + ) + order_passed = len(frame_ids) == args.frames and all( + right > left for left, right in zip(frame_ids, frame_ids[1:]) + ) + memory_passed = ( + runner.maximum_resident_frames <= args.window + and runner.maximum_input_buffer_frames <= ( + args.window if args.mode == "causal" else args.window + args.window // 2 + ) + ) + report = { + "status": "passed" if ( + finite and output_time == args.frames and order_passed + and memory_passed and invariance_passed + ) else "failed", + "experiment": "P6_S5_length_generalized_inference", + "experiment_class": "frozen_checkpoint_engineering_audit", + "official_test_used": False, + "official_validation_used_for_selection": False, + "mode": args.mode, + "causal": args.mode == "causal", + "window": args.window, + "offline_stride": args.window // 2 if args.mode == "offline" else None, + "stitching": "center" if args.mode == "offline" else None, + "take": take, + "requested_frames": args.frames, + "output_frames": output_time, + "frame_ids_strictly_increasing": order_passed, + "finite": finite, + "elapsed_s": elapsed, + "throughput_fps": args.frames / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "maximum_gpu_window_frames": runner.maximum_resident_frames, + "maximum_cpu_input_buffer_frames": runner.maximum_input_buffer_frames, + "invariance": invariance, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": int(checkpoint["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if report["status"] != "passed": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase6_variable_length.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase6_variable_length.py new file mode 100644 index 0000000000000000000000000000000000000000..85097343ce2bb9177f32360d1e752196baa31a45 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase6_variable_length.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +"""Audit the frozen Phase 5 model's variable-length and causality contract.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import statistics +import subprocess +import time +from collections import defaultdict +from pathlib import Path +from typing import Any + +import torch +import yaml + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +LENGTHS = (1, 2, 4, 8, 16, 32, 64) +OUTPUT_KEYS = ( + "hand_tokens", "joint2d_norm", "mano_rotation_matrices", "mano_shape", + "wrist_root_translation", "joints_camera", "vertices_camera", +) +MODEL_INPUT_KEYS = ( + "rgb", "depth_m", "depth_pixel_valid", "K", "K_available", + "depth_available", "frame_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_model( + config: dict[str, Any], checkpoint: Path, device: torch.device, +) -> tuple[BimanualReconstructionModel, int]: + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(checkpoint, model, optimizer=None, map_location=device) + return model, int(state["step"]) + + +def contiguous_real_sequence( + root: Path, manifest: Path, resolution_hw: tuple[int, int], length: int, +) -> tuple[dict[str, torch.Tensor], str, list[int]]: + dataset = H2OCam4Dataset( + root, manifest, resolution_hw, clip_lengths=(1,), strides=(1,), + window_step=1, allow_partial=False, + ) + by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + by_take[clip.take].append(index) + selected: list[int] | None = None + selected_take = "" + for take, indices in by_take.items(): + frame_ids = [dataset.clips[index].frame_ids[0] for index in indices] + for start in range(0, len(indices) - length + 1): + candidate = frame_ids[start : start + length] + if all(right == left + 1 for left, right in zip(candidate[:-1], candidate[1:])): + selected = indices[start : start + length] + selected_take = take + break + if selected is not None: + break + if selected is None: + raise RuntimeError(f"no contiguous {length}-frame validation prefix") + samples = [dataset[index] for index in selected] + batch_frames = collate_h2o_clips(samples) + sequence = {} + for key in MODEL_INPUT_KEYS: + value = batch_frames[key] + if value.shape[0] != length or value.shape[1] != 1: + raise ValueError(f"unexpected T=1 collate shape for {key}: {value.shape}") + sequence[key] = value[:, 0].unsqueeze(0) + frame_ids = batch_frames["frame_id"][:, 0].tolist() + return sequence, selected_take, [int(value) for value in frame_ids] + + +def prefix(batch: dict[str, torch.Tensor], length: int, device: torch.device) -> dict[str, torch.Tensor]: + return {key: value[:, :length].to(device, non_blocking=True) for key, value in batch.items()} + + +def run_once( + model: BimanualReconstructionModel, + batch: dict[str, torch.Tensor], + dtype: torch.dtype, +) -> dict[str, Any]: + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + return model(batch) + + +def output_snapshot(output: dict[str, Any]) -> dict[str, torch.Tensor]: + return {key: output[key].detach().float().cpu() for key in OUTPUT_KEYS} + + +def max_prefix_differences( + left: dict[str, torch.Tensor], right: dict[str, torch.Tensor], length: int, +) -> dict[str, float]: + return { + key: float((left[key][:, :length] - right[key][:, :length]).abs().max()) + for key in OUTPUT_KEYS + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--repeats", type=int, default=2) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("variable-length audit is hard-gated to official validation") + if args.output.exists(): + parser.error("output must not exist") + if args.repeats < 1: + parser.error("repeats must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + real, take, frame_ids = contiguous_real_sequence( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), max(LENGTHS), + ) + model, step = build_model(config, args.checkpoint, device) + results = [] + snapshots: dict[int, dict[str, torch.Tensor]] = {} + for length in LENGTHS: + current = prefix(real, length, device) + run_once(model, current, dtype) + torch.cuda.synchronize(device) + torch.cuda.reset_peak_memory_stats(device) + latencies = [] + output: dict[str, Any] | None = None + repeats = args.repeats if length <= 16 else 1 + for _ in range(repeats): + start = time.perf_counter() + output = run_once(model, current, dtype) + torch.cuda.synchronize(device) + latencies.append(1000.0 * (time.perf_counter() - start)) + assert output is not None + snapshots[length] = output_snapshot(output) + temporal_attention = output["attention"]["temporal_attention"] + finite = { + key: bool(torch.isfinite(output[key]).all().item()) for key in OUTPUT_KEYS + } + results.append({ + "T": length, + "finite": finite, + "all_finite": all(finite.values()), + "hand_token_shape": list(output["hand_tokens"].shape), + "temporal_attention_shape": list(temporal_attention.shape), + "temporal_attention_elements": temporal_attention.numel(), + "temporal_attention_bytes": temporal_attention.numel() * temporal_attention.element_size(), + "latency_ms_p50": float(statistics.median(latencies)), + "latency_ms_samples": latencies, + "peak_allocated_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + }) + del output, current + torch.cuda.empty_cache() + print(f"T={length} complete", flush=True) + + base8 = prefix(real, 8, device) + changed8 = {key: value.clone() for key, value in base8.items()} + changed8["rgb"][:, 4:] = 1.0 - changed8["rgb"][:, 4:] + changed8["depth_m"][:, 4:] = 0.0 + changed8["depth_pixel_valid"][:, 4:] = False + changed8["depth_available"][:, 4:] = False + original8 = output_snapshot(run_once(model, base8, dtype)) + perturbed8 = output_snapshot(run_once(model, changed8, dtype)) + future_differences = max_prefix_differences(original8, perturbed8, 4) + prefix_differences = max_prefix_differences(snapshots[8], snapshots[4], 4) + window_comparisons = [] + reference = snapshots[64] + for length in LENGTHS: + first_joint_delta_mm = float( + torch.linalg.vector_norm( + snapshots[length]["joints_camera"][:, 0] + - reference["joints_camera"][:, 0], dim=-1, + ).mean() * 1000.0 + ) + window_comparisons.append({ + "T": length, + "first_frame_joint_delta_vs_T64_mm": first_joint_delta_mm, + "first_frame_wrist_max_delta_vs_T64_m": float( + (snapshots[length]["wrist_root_translation"][:, 0] + - reference["wrist_root_translation"][:, 0]).abs().max() + ), + }) + report = { + "status": "completed", + "experiment": "P6_S0_variable_length_contract", + "official_validation_used": True, + "official_validation_used_for_selection": False, + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + "device": args.gpu, + "take": take, + "frame_ids": frame_ids, + "forward_results": results, + "window_comparisons": window_comparisons, + "future_perturbation": { + "changed_frames": [4, 5, 6, 7], + "compared_frames": [0, 1, 2, 3], + "maximum_absolute_differences": future_differences, + "strict_zero_passed": all(value == 0.0 for value in future_differences.values()), + }, + "prefix_invariance": { + "prefix_T": 4, "full_T": 8, + "maximum_absolute_differences": prefix_differences, + "strict_zero_passed": all(value == 0.0 for value in prefix_differences.values()), + }, + "contract": { + "tensor_shape_variable_length": all(item["all_finite"] for item in results), + "offline_bidirectional_variable_length": True, + "bounded_memory_causal_streaming": False, + "historical_causal_description": "causal z-state postprocessor over noncausal T=8 coarse predictions", + }, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], + "future_strict_zero": report["future_perturbation"]["strict_zero_passed"], + "prefix_strict_zero": report["prefix_invariance"]["strict_zero_passed"], + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_arctic.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_arctic.py new file mode 100644 index 0000000000000000000000000000000000000000..782a56fcee3691d848037cb01ef48c6c9763b4c5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_arctic.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Deterministic numeric and visual audit for ARCTIC P2 train view 0.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + "max": float(array.max()), + } + + +def select_indices(rows: list[dict], count: int) -> list[int]: + recordings: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + recordings[(row["subject_id"], row["physical_recording_id"])].append(index) + strata: dict[str, list[int]] = defaultdict(list) + for (subject, _), indices in sorted(recordings.items()): + strata[subject].append(indices[len(indices) // 2]) + selected, cursor = [], 0 + while len(selected) < count: + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected.append(strata[subject][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) != count: + raise RuntimeError(f"only {len(selected)} subject/recording strata available") + return selected + + +def denormalize(image: torch.Tensor) -> np.ndarray: + value = image.permute(1, 2, 0).numpy() + return np.rint(np.clip((value * RGB_STD + RGB_MEAN) * 255.0, 0, 255)).astype(np.uint8) + + +def render(case: dict, output: Path) -> None: + image = case["image"].copy() + for side, color in enumerate(((40, 190, 250), (250, 100, 60))): + for point in case["joint2d"][side][case["joint_valid"][side]]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, color, -1) + cv2.putText( + image, f"{case['category']} {case['recording']}", (10, 24), + cv2.FONT_HERSHEY_SIMPLEX, .55, (255, 255, 255), 2, cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=16) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + dataset = ARCTICClipDataset(args.manifest, args.mano_root) + indices = select_indices(dataset.rows, args.clips) + enabled_regen, excluded_left, enabled_reprojection = [], [], [] + wrist_depth, hand_size, cases, hand_counts = [], [], [], [] + side_frames = {"left": 0, "right": 0} + root_relative_side_frames = {"left": 0, "right": 0} + root_relative_root_norm_mm: list[float] = [] + for index in indices: + sample = dataset[index] + enabled_regen.extend(sample["source_vertex_regen_error_mm"][sample["vertices_valid"]].tolist()) + left = sample["translation_valid"][:, 0] + excluded_left.extend(sample["source_vertex_regen_error_mm"][:, 0][left].tolist()) + for side_index, side in enumerate(("left", "right")): + valid = sample["joint3d_root_relative_valid"][:, side_index] + root_relative_side_frames[side] += int(valid.any(dim=-1).sum()) + root_relative_root_norm_mm.extend( + (torch.linalg.vector_norm( + sample["joint3d_root_relative"][:, side_index, 0], dim=-1, + )[valid[:, 0]] * 1000.0).tolist() + ) + enabled_reprojection.extend( + sample["projection_roundtrip_error_px"][sample["reprojection_valid"]].tolist() + ) + for frame in range(len(sample["frame_valid"])): + valid_hands = sample["translation_valid"][frame] + hand_counts.append(int(valid_hands.sum())) + sizes = [] + for side_index, side in enumerate(("left", "right")): + if not valid_hands[side_index]: + continue + side_frames[side] += 1 + wrist_depth.append(float(sample["wrist_root_translation"][frame, side_index, 2])) + points = sample["joint2d"][frame, side_index][sample["joint2d_valid"][frame, side_index]] + if len(points): + sizes.append(float((points.max(0).values - points.min(0).values).max())) + hand_size.extend(sizes) + points = sample["joint2d"][frame][sample["joint2d_valid"][frame]] + height, width = sample["rgb"].shape[-2:] + border = ( + float(torch.stack((points[:, 0], points[:, 1], width - points[:, 0], height - points[:, 1])).amin()) + if len(points) else float("inf") + ) + z = sample["wrist_root_translation"][frame, valid_hands, 2] + cases.append({ + "recording": sample["physical_recording_id"], + "image": denormalize(sample["rgb"][frame]), + "joint2d": sample["joint2d"][frame].numpy(), + "joint_valid": sample["joint2d_valid"][frame].numpy(), + "count": int(valid_hands.sum()), + "z": float(z.mean()) if len(z) else float("nan"), + "size": max(sizes, default=0.0), "border": border, + }) + valid_cases = [row for row in cases if row["count"] > 0] + selectors = { + "near": min(valid_cases, key=lambda row: row["z"]), + "far": max(valid_cases, key=lambda row: row["z"]), + "small": min(valid_cases, key=lambda row: row["size"]), + "border": min(valid_cases, key=lambda row: row["border"]), + "bimanual": next(row for row in valid_cases if row["count"] == 2), + } + single = next((row for row in valid_cases if row["count"] == 1), None) + if single is not None: + selectors["single"] = single + visuals = {} + for category, value in selectors.items(): + path = args.output_dir / f"{category}.png" + render(dict(value, category=category), path) + visuals[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + report = { + "status": "pending", "official_test_used": False, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clips": len(indices), "frames": len(cases), "clip_indices": indices, + "side_frames": side_frames, + "no_visible_hand_frames": hand_counts.count(0), + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "source_regeneration_mm": quantiles(enabled_regen), + "enabled_reprojection_roundtrip_px": quantiles(enabled_reprojection), + "excluded_left_geometry_regeneration_mm": quantiles(excluded_left), + "wrist_depth_m": quantiles(wrist_depth), + "projected_hand_size_px": quantiles(hand_size), + "image_contract": "full 840x600 ego view (0.3x 2800x2000), cv2 undistort with scaled K/dist8, then full-frame resize/pad", + "partial_supervision_contract": { + "right": "2D/3D/translation/pose/shape/vertices/reprojection", + "left": "direct-2D/translation/pose only", + }, + "source_compatible_root_relative_joint3d": { + "side_frames": root_relative_side_frames, + "root_norm_mm": quantiles(root_relative_root_norm_mm), + "shape_vertices_enabled": False, + "claim": "source-compatible legacy MANO joint target only; not corrected-MANO regeneration", + }, + "visualizations": visuals, + } + passed = ( + len(cases) >= 100 and report["source_regeneration_mm"]["max"] < 1.0 + and report["enabled_reprojection_roundtrip_px"]["p95"] < 1.0 + and all(value > 0 for value in side_frames.values()) + and all(value > 0 for value in root_relative_side_frames.values()) + and report["source_compatible_root_relative_joint3d"]["root_norm_mm"]["max"] < 1e-4 + and report["bimanual_frames"] > 0 + ) + report["status"] = "passed" if passed else "failed" + (args.output_dir / "audit.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_egodexter.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_egodexter.py new file mode 100644 index 0000000000000000000000000000000000000000..acd74ce8142f1d6b95335fba94e4dbd155454225 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_egodexter.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Deterministic no-model EgoDexter source audit for Phase 7.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path + +import numpy as np + +from foundation_hand.data.egodexter_dataset import EgoDexterSequenceDataset, SEQUENCES + + +def finite_summary(values: np.ndarray) -> dict[str, float | int]: + values = values[np.isfinite(values)] + return { + "count": int(len(values)), + "median": float(np.median(values)), + "p95": float(np.quantile(values, .95)), + "max": float(values.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--decode-frames-per-sequence", type=int, default=25) + args = parser.parse_args() + if args.decode_frames_per_sequence < 1: + parser.error("--decode-frames-per-sequence must be positive") + report: dict[str, object] = { + "status": "numeric_adapter_passed_handedness_freeze_pending", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "dataset": "EgoDexter", + "training_or_selection_use": False, + "official_test_used": False, + "camera_frame": "depth_camera", + "depth_units_input": "millimeters", + "model_units": "meters", + "rgb_stream": "color_on_depth full frame", + "input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "sequence_handedness": "must be frozen before first model inference", + "sequences": {}, + } + total_frames = 0 + total_visible = 0 + total_annotated = 0 + for sequence in SEQUENCES: + dataset = EgoDexterSequenceDataset(args.root, sequence, hand_side="left") + xyz = dataset.fingertips_3d_m + valid = np.linalg.norm(xyz, axis=-1) > 0.0 + uv = np.full_like(xyz[..., :2], np.nan) + uv[..., 0] = ( + dataset.K_source[0, 0] * xyz[..., 0] + / np.where(valid, xyz[..., 2], np.nan) + dataset.K_source[0, 2] + ) + uv[..., 1] = ( + dataset.K_source[1, 1] * xyz[..., 1] + / np.where(valid, xyz[..., 2], np.nan) + dataset.K_source[1, 2] + ) + error = np.linalg.norm(uv - dataset.fingertips_2d, axis=-1)[valid] + sample_indices = np.linspace( + 0, len(dataset) - 1, + min(args.decode_frames_per_sequence, len(dataset)), dtype=np.int64, + ) + depth_valid_fraction = [] + for index in sample_indices: + _, depth_mm, _ = dataset._load(int(index)) + depth_valid_fraction.append(float((depth_mm > 0).mean())) + lines = (dataset.sequence_root / "annotation.txt_3D.txt").read_text( + encoding="utf-8", + ).splitlines() + sequence_report = { + "frames": len(dataset), + "visible_fingertips": int(valid.sum()), + "annotated_frames": int(np.any(valid, axis=1).sum()), + "partial_annotation_rows": sum( + len([group for group in line.split(";") if group.strip()]) < 5 + for line in lines + ), + "projection_roundtrip_px": finite_summary(error), + "decoded_frames": len(sample_indices), + "depth_valid_fraction_mean": float(np.mean(depth_valid_fraction)), + } + report["sequences"][sequence] = sequence_report + total_frames += len(dataset) + total_visible += int(valid.sum()) + total_annotated += int(np.any(valid, axis=1).sum()) + report["totals"] = { + "frames": total_frames, + "visible_fingertips": total_visible, + "annotated_frames": total_annotated, + "decoded_numeric_audit_frames": args.decode_frames_per_sequence * len(SEQUENCES), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_hoi4d.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_hoi4d.py new file mode 100644 index 0000000000000000000000000000000000000000..db2cfc39662dcb4bb7473cb83d81701c37149f39 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_hoi4d.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Deterministic numeric and visual audit of the Phase 7 HOI4D adapter.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + "max": float(array.max()), + } + + +def select_indices(rows: list[dict], count: int) -> list[int]: + strata: dict[tuple[str, str], list[int]] = {} + seen: set[str] = set() + for index, row in enumerate(rows): + side_sets = [set(value) for value in row["hand_sides"]] + hand_class = ( + "bimanual" if any(len(value) == 2 for value in side_sets) else + "left" if any("left" in value for value in side_sets) else "right" + ) + key = (row["subject_id"], hand_class) + if row["physical_recording_id"] in seen: + continue + seen.add(row["physical_recording_id"]) + strata.setdefault(key, []).append(index) + selected: list[int] = [] + keys = sorted(strata) + cursor = 0 + while len(selected) < count: + progress = False + for key in keys: + if cursor < len(strata[key]): + selected.append(strata[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) != count: + raise RuntimeError(f"only {len(selected)} stratified clips found") + return selected + + +def denormalize(image: torch.Tensor) -> np.ndarray: + value = image.permute(1, 2, 0).numpy() + return np.rint(np.clip((value * RGB_STD + RGB_MEAN) * 255.0, 0, 255)).astype(np.uint8) + + +def render(case: dict, output: Path) -> None: + image = case["image"].copy() + colors = ((40, 190, 250), (250, 100, 60)) + for side in range(2): + for point in case["joint2d"][side][case["joint_valid"][side]]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, colors[side], -1) + depth = case["depth"] + valid = depth > 0 + depth_color = np.zeros((*depth.shape, 3), dtype=np.uint8) + if valid.any(): + scale = np.quantile(depth[valid], .95) + normalized = np.clip(depth / max(scale, 1e-6), 0, 1) + depth_color = cv2.applyColorMap( + np.rint(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO, + )[..., ::-1] + depth_color[~valid] = 0 + combined = np.concatenate((image, depth_color), axis=1) + cv2.putText( + combined, f"{case['category']} {case['recording']}", (10, 24), + cv2.FONT_HERSHEY_SIMPLEX, .55, (255, 255, 255), 2, cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(combined, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=16) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + dataset = HOI4DClipDataset(args.root, args.manifest, args.mano_root) + indices = select_indices(dataset.rows, args.clips) + projection, regeneration, incompatible_left, depth_fraction, wrist_depth, hand_size = [], [], [], [], [], [] + cases: list[dict] = [] + side_frames = {"left": 0, "right": 0} + root_relative_side_frames = {"left": 0, "right": 0} + root_relative_root_norm_mm: list[float] = [] + hand_counts: list[int] = [] + for index in indices: + sample = dataset[index] + projection.extend(sample["projection_roundtrip_error_px"][sample["joint2d_valid"]].tolist()) + regeneration.extend(sample["source_vertex_regen_error_mm"][sample["vertices_valid"]].tolist()) + left_present = sample["translation_valid"][:, 0] + incompatible_left.extend(sample["source_vertex_regen_error_mm"][:, 0][left_present].tolist()) + for side_index, side in enumerate(("left", "right")): + valid = sample["joint3d_root_relative_valid"][:, side_index] + root_relative_side_frames[side] += int(valid.any(dim=-1).sum()) + root_relative_root_norm_mm.extend( + (torch.linalg.vector_norm( + sample["joint3d_root_relative"][:, side_index, 0], dim=-1, + )[valid[:, 0]] * 1000.0).tolist() + ) + for frame in range(len(sample["frame_valid"])): + valid_hands = sample["translation_valid"][frame] + hand_counts.append(int(valid_hands.sum())) + for side_index, side in enumerate(("left", "right")): + if valid_hands[side_index]: + side_frames[side] += 1 + wrist_depth.append(float(sample["wrist_root_translation"][frame, side_index, 2])) + points = sample["joint2d"][frame, side_index][sample["joint2d_valid"][frame, side_index]] + extent = points.max(0).values - points.min(0).values + hand_size.append(float(extent.max())) + depth_fraction.append(float(sample["depth_pixel_valid"][frame].float().mean())) + points = sample["joint2d"][frame][sample["joint2d_valid"][frame]] + height, width = sample["rgb"].shape[-2:] + border = min( + torch.stack((points[:, 0], points[:, 1], width - points[:, 0], height - points[:, 1])).amin().item() + if len(points) else float("inf"), + 1e9, + ) + cases.append({ + "recording": sample["physical_recording_id"], + "image": denormalize(sample["rgb"][frame]), + "depth": sample["depth_m"][frame, 0].numpy(), + "joint2d": sample["joint2d"][frame].numpy(), + "joint_valid": sample["joint2d_valid"][frame].numpy(), + "count": int(valid_hands.sum()), + "z": float(sample["wrist_root_translation"][frame, valid_hands, 2].mean()), + "size": max([ + float((sample["joint2d"][frame, side][sample["joint2d_valid"][frame, side]].max(0).values - sample["joint2d"][frame, side][sample["joint2d_valid"][frame, side]].min(0).values).max()) + for side in range(2) if sample["joint2d_valid"][frame, side].any() + ], default=0.0), + "border": border, + }) + selectors = { + "near": min(cases, key=lambda row: row["z"]), + "far": max(cases, key=lambda row: row["z"]), + "small": min(cases, key=lambda row: row["size"]), + "border": min(cases, key=lambda row: row["border"]), + "single": next(row for row in cases if row["count"] == 1), + "bimanual": next(row for row in cases if row["count"] == 2), + } + visuals = {} + for category, value in selectors.items(): + case = dict(value, category=category) + path = args.output_dir / f"{category}.png" + render(case, path) + visuals[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + report = { + "status": "pending", + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clip_indices": indices, + "clips": len(indices), "frames": len(cases), + "side_frames": side_frames, + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "projection_roundtrip_px": quantiles(projection), + "source_regeneration_mm": quantiles(regeneration), + "excluded_left_geometry_regeneration_mm": quantiles(incompatible_left), + "partial_supervision_contract": { + "right": "2D/3D/translation/pose/shape/vertices/reprojection", + "left": "direct-2D/translation/pose only", + "reason": "historical HOI4D MANO-left shapedirs cannot regenerate under corrected HOT3D/SMPL-X convention within 1 mm", + }, + "source_compatible_root_relative_joint3d": { + "side_frames": root_relative_side_frames, + "root_norm_mm": quantiles(root_relative_root_norm_mm), + "shape_vertices_enabled": False, + "claim": "source-compatible legacy MANO joint target only; not corrected-MANO regeneration", + }, + "depth_valid_fraction": quantiles(depth_fraction), + "wrist_depth_m": quantiles(wrist_depth), + "projected_hand_size_px": quantiles(hand_size), + "rgb_depth_sync": "same released aligned frame index decoded from both streams", + "depth_decode": "FFmpeg gray16le retained; millimeters converted to meters", + "visualizations": visuals, + "official_test_used": False, + } + passed = ( + len(cases) >= 100 and report["projection_roundtrip_px"]["median"] < .5 + and report["projection_roundtrip_px"]["p95"] < 1.0 + and report["source_regeneration_mm"]["max"] < 1.0 + and all(value > 0 for value in side_frames.values()) + and all(value > 0 for value in root_relative_side_frames.values()) + and report["source_compatible_root_relative_joint3d"]["root_norm_mm"]["max"] < 1e-4 + and report["single_hand_frames"] > 0 and report["bimanual_frames"] > 0 + ) + report["status"] = "passed" if passed else "failed" + (args.output_dir / "audit.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_hot3d.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_hot3d.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb6e7fdb573f9f019252e1e8a5aab2b5086a635 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase7_hot3d.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Deterministic HOT3D numeric and full-frame visualization audit.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def select_clip_indices(rows: list[dict], count: int) -> list[int]: + strata: dict[tuple[str, str], list[int]] = {} + seen_recordings: set[tuple[str, str, str]] = set() + for index, row in enumerate(rows): + hand_class = "single" if min(row.get("hand_count", [2])) == 1 else "bimanual" + key = (row["headset"], hand_class) + recording_key = (row["headset"], hand_class, row["recording_id"]) + if recording_key in seen_recordings: + continue + seen_recordings.add(recording_key) + strata.setdefault(key, []).append(index) + ordered_keys = sorted(strata) + selected: list[int] = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in ordered_keys: + values = strata[key] + if cursor < len(values): + selected.append(values[cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) < count: + raise RuntimeError(f"only {len(selected)} stratified clips available") + return selected + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), + "mean": float(array.mean()), + "median": float(np.median(array)), + "p95": float(np.quantile(array, 0.95)), + "max": float(array.max()), + } + + +def denormalize(rgb: torch.Tensor) -> np.ndarray: + image = rgb.permute(1, 2, 0).cpu().numpy() + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def render_case(case: dict, output: Path) -> None: + image = case["image"].copy() + colors = ((40, 190, 250), (250, 100, 60)) + for side in range(2): + valid = case["joint_valid"][side] + for point in case["joint2d"][side][valid]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, colors[side], -1) + cv2.putText( + image, + f"{case['category']} {case['recording']} {case['stream']}", + (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2, + cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=13) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + dataset = HOT3DClipDataset( + args.root, args.manifest, args.toolkit_root, args.mano_root, + K_input_dropout=0.3, dropout_seed=20260717, + ) + indices = select_clip_indices(dataset.rows, args.clips) + projection_errors: list[float] = [] + regeneration_errors: list[float] = [] + wrist_depths: list[float] = [] + hand_sizes: list[float] = [] + hand_counts: list[int] = [] + hand_sync_ms: list[float] = [] + headset_sync_ms: list[float] = [] + frame_cases: list[dict] = [] + headset_counts: dict[str, int] = {} + K_keep: list[bool] = [] + for index in indices: + sample = dataset[(index, 0)] + headset_counts[sample["headset_id"]] = headset_counts.get(sample["headset_id"], 0) + int(sample["frame_valid"].sum()) + projection_errors.extend(sample["projection_roundtrip_error_px"][torch.isfinite(sample["projection_roundtrip_error_px"])].tolist()) + regeneration_errors.extend(sample["source_vertex_regen_error_mm"][sample["translation_valid"]].tolist()) + hand_sync_ms.extend((sample["hand_pose_time_delta_ns"].abs() / 1e6).tolist()) + headset_sync_ms.extend((sample["headset_time_delta_ns"].abs() / 1e6).tolist()) + K_keep.append(bool(sample["K_input_available"][0])) + for frame_index in range(int(sample["frame_valid"].sum())): + valid_hands = sample["translation_valid"][frame_index] + hand_counts.append(int(valid_hands.sum())) + joint_valid = sample["joint2d_valid"][frame_index] + for side in range(2): + if not valid_hands[side]: + continue + wrist_depths.append(float(sample["wrist_root_translation"][frame_index, side, 2])) + points = sample["joint2d"][frame_index, side][joint_valid[side]] + if len(points): + extent = points.max(0).values - points.min(0).values + hand_sizes.append(float(extent.max())) + points_all = sample["joint2d"][frame_index][joint_valid] + if len(points_all): + h, w = sample["rgb"].shape[-2:] + border = torch.stack((points_all[:, 0], points_all[:, 1], w - points_all[:, 0], h - points_all[:, 1])).amin().item() + else: + border = float("inf") + valid_depth = sample["wrist_root_translation"][frame_index, :, 2][valid_hands] + frame_cases.append({ + "recording": sample["physical_recording_id"], + "stream": sample["stream_id"], + "image": denormalize(sample["rgb"][frame_index]), + "joint2d": sample["joint2d"][frame_index].cpu().numpy(), + "joint_valid": joint_valid.cpu().numpy(), + "hand_count": int(valid_hands.sum()), + "depth": float(valid_depth.mean()) if len(valid_depth) else float("nan"), + "border": float(border), + "size": float(max( + [ + (sample["joint2d"][frame_index, side][joint_valid[side]].max(0).values - sample["joint2d"][frame_index, side][joint_valid[side]].min(0).values).max().item() + for side in range(2) if joint_valid[side].any() + ], default=0.0, + )), + }) + + selectors = { + "near": lambda rows: min(rows, key=lambda row: row["depth"]), + "far": lambda rows: max(rows, key=lambda row: row["depth"]), + "border": lambda rows: min(rows, key=lambda row: row["border"]), + "small": lambda rows: min(rows, key=lambda row: row["size"]), + "single": lambda rows: next(row for row in rows if row["hand_count"] == 1), + "bimanual": lambda rows: next(row for row in rows if row["hand_count"] == 2), + } + visualizations = {} + for category, selector in selectors.items(): + case = dict(selector(frame_cases)) + case["category"] = category + path = args.output_dir / f"{category}.png" + render_case(case, path) + visualizations[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + audit = { + "status": "passed", + "official_test_used": False, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clip_indices": indices, + "clips": len(indices), + "frames": len(frame_cases), + "headset_frame_counts": headset_counts, + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "projection_roundtrip_px": quantiles(projection_errors), + "source_regeneration_mm": quantiles(regeneration_errors), + "hand_pose_sync_ms": quantiles(hand_sync_ms), + "headset_sync_ms": quantiles(headset_sync_ms), + "wrist_depth_m": quantiles(wrist_depths), + "projected_hand_size_px": quantiles(hand_sizes), + "K_input_kept_clips": int(sum(K_keep)), + "K_input_dropped_clips": int(len(K_keep) - sum(K_keep)), + "visualizations": visualizations, + } + passed = ( + audit["frames"] >= 100 + and audit["projection_roundtrip_px"]["median"] < 0.5 + and audit["projection_roundtrip_px"]["p95"] < 1.0 + and audit["source_regeneration_mm"]["max"] < 1.0 + and audit["single_hand_frames"] > 0 + and audit["bimanual_frames"] > 0 + ) + audit["status"] = "passed" if passed else "failed" + output = args.output_dir / "audit.json" + output.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") + print(json.dumps(audit, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase9_resolution_cache.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase9_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..440147147d411ed3f266dfde7363c9c87e5f944f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase9_resolution_cache.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Audit true-source Phase 9 resolution caches and train-only folds.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +EXPECTED_HW = (512, 896) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def source_index_digest(rows: list[dict[str, Any]]) -> str: + values = [int(row["source_clip_index"]) for row in rows] + payload = json.dumps(values, separators=(",", ":")).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def projection_error_px(archive: np.lib.npyio.NpzFile) -> float: + xyz = archive["joint3d_camera"] + target = archive["joint2d"] + intrinsics = archive["K"] + z = xyz[..., 2] + projected = np.empty_like(target) + projected[..., 0] = ( + intrinsics[:, None, None, 0, 0] * xyz[..., 0] / z + + intrinsics[:, None, None, 0, 2] + ) + projected[..., 1] = ( + intrinsics[:, None, None, 1, 1] * xyz[..., 1] / z + + intrinsics[:, None, None, 1, 2] + ) + valid = ( + archive["reprojection_valid"].astype(bool) + & archive["joint3d_valid"].astype(bool) + & np.isfinite(projected).all(axis=-1) + & (z > 1e-6) + ) + if not valid.any(): + return 0.0 + return float(np.linalg.norm(projected[valid] - target[valid], axis=-1).max()) + + +def audit_payload(path: Path) -> dict[str, Any]: + with np.load(path, allow_pickle=False) as archive: + if tuple(int(value) for value in archive["image_hw"].reshape(-1)) != EXPECTED_HW: + raise ValueError(f"payload resolution differs: {path}") + if archive["rgb_u8"].shape != (8, *EXPECTED_HW, 3): + raise ValueError(f"RGB shape differs: {path}") + if archive["depth_m"].shape != (8, 1, *EXPECTED_HW): + raise ValueError(f"depth shape differs: {path}") + if archive["depth_pixel_valid"].shape != (8, 1, *EXPECTED_HW): + raise ValueError(f"depth validity shape differs: {path}") + valid_depth = archive["depth_pixel_valid"].astype(bool) + depth = archive["depth_m"] + if valid_depth.any() and ( + not np.isfinite(depth[valid_depth]).all() + or not (depth[valid_depth] > 0).all() + ): + raise ValueError(f"valid depth contains nonpositive/nonfinite values: {path}") + intrinsics = archive["K"] + if ( + intrinsics.shape != (8, 3, 3) + or not np.isfinite(intrinsics).all() + or not (intrinsics[:, 0, 0] > 0).all() + or not (intrinsics[:, 1, 1] > 0).all() + or not np.allclose(intrinsics[:, 2], (0.0, 0.0, 1.0), atol=1e-6) + ): + raise ValueError(f"intrinsics contract differs: {path}") + error = projection_error_px(archive) + if error > 1.0: + raise ValueError(f"projection error exceeds 1 px ({error}): {path}") + return { + "path": str(path.resolve()), + "projection_error_max_px": error, + "depth_valid_fraction": float(valid_depth.mean()), + } + + +def audit_cache(item: dict[str, Any]) -> dict[str, Any]: + report_path = Path(item["report"]) + manifest_path = Path(item["manifest"]) + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or tuple(report.get("resolution_hw", ())) != EXPECTED_HW + or report.get("source_manifest", {}).get("sha256") + != item["source_manifest_sha256"] + or report.get("cache_manifest", {}).get("sha256") != sha256(manifest_path) + or report.get("resume_invocation") is not True + ): + raise ValueError(f"cache report contract differs: {item['id']}") + rows = read_jsonl(manifest_path) + if ( + len(rows) != int(item["clips"]) + or len({int(row["source_clip_index"]) for row in rows}) != len(rows) + or {row.get("dataset_id") for row in rows} != {item["dataset"]} + or any(tuple(row.get("resolution_hw", ())) != EXPECTED_HW for row in rows) + ): + raise ValueError(f"cache manifest contract differs: {item['id']}") + if item.get("recordings") is not None and len({ + row["physical_recording_id"] for row in rows + }) != int(item["recordings"]): + raise ValueError(f"recording count differs: {item['id']}") + control_rows = read_jsonl(Path(item["control_manifest"])) + if [row["source_clip_index"] for row in rows] != [ + row["source_clip_index"] for row in control_rows + ]: + raise ValueError(f"source clip selection differs from 640 control: {item['id']}") + payload_bytes = 0 + for row in rows: + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"payload hash differs: {path}") + payload_bytes += path.stat().st_size + samples = [audit_payload(Path(rows[index]["cache_path"])) for index in { + 0, len(rows) // 2, len(rows) - 1, + }] + return { + "id": item["id"], + "dataset": item["dataset"], + "clips": len(rows), + "recordings": len({row["physical_recording_id"] for row in rows}), + "manifest": str(manifest_path.resolve()), + "manifest_sha256": sha256(manifest_path), + "source_index_sha256": source_index_digest(rows), + "control_source_index_sha256": source_index_digest(control_rows), + "payload_bytes": payload_bytes, + "all_payload_sha256_verified": True, + "samples": samples, + } + + +def audit_sidecar(item: dict[str, Any]) -> dict[str, Any]: + report = json.loads(Path(item["report"]).read_text(encoding="utf-8")) + base_rows = read_jsonl(Path(item["base_manifest"])) + rows = read_jsonl(Path(item["manifest"])) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("base_cache_manifest", {}).get("sha256") + != sha256(item["base_manifest"]) + or report.get("augmented_cache_manifest", {}).get("sha256") + != sha256(item["manifest"]) + or report.get("right_valid_joint_count") != 0 + or float(report.get("root_norm_max_mm", math.inf)) >= 1e-4 + or report.get("shape_supervision_restored") is not False + or report.get("vertices_supervision_restored") is not False + or report.get("camera_joint3d_supervision_restored") is not False + or len(rows) != len(base_rows) + ): + raise ValueError(f"sidecar report contract differs: {item['id']}") + for base, row in zip(base_rows, rows, strict=True): + if ( + row["source_clip_index"] != base["source_clip_index"] + or row["cache_path"] != base["cache_path"] + or row["cache_sha256"] != base["cache_sha256"] + or row.get("joint3d_root_relative_scope") != "historical_left_only" + or sha256(row["joint3d_root_relative_sidecar_path"]) + != row["joint3d_root_relative_sidecar_sha256"] + ): + raise ValueError(f"sidecar row binding differs: {item['id']}") + return { + "id": item["id"], + "clips": len(rows), + "manifest_sha256": sha256(item["manifest"]), + "left_hand_frames": report["left_hand_frames"], + "all_sidecar_sha256_verified": True, + } + + +def audit_multifold(item: dict[str, Any], h2o_rows: list[dict[str, Any]]) -> dict[str, Any]: + index = json.loads(Path(item["index"]).read_text(encoding="utf-8")) + rebuild = json.loads(Path(item["rebuild_index"]).read_text(encoding="utf-8")) + if ( + index.get("status") != "complete" + or index.get("official_test_used") is not False + or index.get("h2o_official_validation_used") is not False + or index.get("source_cache_manifest", {}).get("sha256") + != sha256(item["source_manifest"]) + or len(index.get("folds", [])) != 6 + ): + raise ValueError("resolution multifold index contract differs") + if ( + rebuild.get("status") != "complete" + or rebuild.get("official_test_used") is not False + or rebuild.get("h2o_official_validation_used") is not False + or rebuild.get("source_cache_manifest", {}).get("sha256") + != index["source_cache_manifest"]["sha256"] + or [fold["id"] for fold in rebuild.get("folds", [])] + != [fold["id"] for fold in index["folds"]] + or [ + (fold["train"]["sha256"], fold["heldout"]["sha256"]) + for fold in rebuild["folds"] + ] != [ + (fold["train"]["sha256"], fold["heldout"]["sha256"]) + for fold in index["folds"] + ] + ): + raise ValueError("resolution multifold deterministic rebuild differs") + base_groups = {row["physical_recording_id"] for row in h2o_rows} + fold_audits = [] + for fold in index["folds"]: + train = read_jsonl(Path(fold["train"]["path"])) + heldout = read_jsonl(Path(fold["heldout"]["path"])) + train_groups = {row["physical_recording_id"] for row in train} + heldout_groups = {row["physical_recording_id"] for row in heldout} + if ( + train_groups & heldout_groups + or train_groups | heldout_groups != base_groups + or len(train) + len(heldout) != len(h2o_rows) + or sha256(fold["train"]["path"]) != fold["train"]["sha256"] + or sha256(fold["heldout"]["path"]) != fold["heldout"]["sha256"] + ): + raise ValueError(f"resolution multifold leakage/binding differs: {fold['id']}") + fold_audits.append({ + "id": fold["id"], "train_clips": len(train), + "heldout_clips": len(heldout), "group_overlap": 0, + }) + return { + "folds": fold_audits, + "physical_recording_isolation": True, + "deterministic_rebuild_hashes_match": True, + } + + +def audit(plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution execution plan lacks official-data isolation") + caches = [audit_cache(item) for item in plan["caches"]] + cache_by_id = {item["id"]: item for item in plan["caches"]} + h2o_rows = read_jsonl(Path(cache_by_id["h2o_train"]["manifest"])) + sidecars = [audit_sidecar(item) for item in plan["sidecars"]] + multifold = audit_multifold(plan["multifold"], h2o_rows) + return { + "schema_version": "phase9_resolution_cache_audit_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "resolution_hw": list(EXPECTED_HW), + "caches": caches, + "sidecars": sidecars, + "multifold": multifold, + "official_test_used": False, + "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("audit output must be new") + result = audit(json.loads(args.plan.read_text(encoding="utf-8"))) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase9_selection_bindings.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase9_selection_bindings.py new file mode 100644 index 0000000000000000000000000000000000000000..7a41a0a543656c690e7a0853f340aaabd6a65cac --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase9_selection_bindings.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Audit every fold report consumed by the frozen Phase 9 selection.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.summarize_phase9_unified_selection import ( + CANDIDATES, + evaluation, + validate_multifold_index, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def json_sha256(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def candidate_records() -> list[tuple[str, str, str]]: + records = [] + for mixture, candidates in CANDIDATES.items(): + for _, fold_checkpoint_id in candidates: + for fold in ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + ): + records.append((mixture, fold_checkpoint_id, fold)) + return records + + +def evaluation_path( + *, fold_final_root: Path, fold_milestone_root: Path, + condition: str, checkpoint_id: str, +) -> Path: + if checkpoint_id == "final": + return fold_final_root / condition / "rgb_d_k" / "evaluation.json" + return ( + fold_milestone_root / condition / checkpoint_id + / "rgb_d_k" / "evaluation.json" + ) + + +def file_binding(record: dict[str, Any], key: str) -> dict[str, Any]: + binding = record.get(key, {}) + path = Path(str(binding.get("path", ""))) + declared = str(binding.get("sha256", "")) + exists = path.is_file() + actual = sha256(path) if exists else None + return { + "path": str(path), + "declared_sha256": declared, + "actual_sha256": actual, + "exists": exists, + "sha256_matches": exists and declared == actual, + } + + +def artifact_binding(report: dict[str, Any], key: str) -> dict[str, Any]: + binding = report.get(key, {}) + path = Path(str(binding.get("path", ""))) + declared = str(binding.get("sha256", "")) + exists = path.is_file() + actual = sha256(path) if exists else None + return { + "path": str(path), + "declared_sha256": declared, + "actual_sha256": actual, + "exists": exists, + "sha256_matches": exists and declared == actual, + } + + +def audit_report( + *, report_path: Path, condition: str, checkpoint_id: str, + expected_manifest_path: str, expected_manifest_sha256: str, +) -> dict[str, Any]: + report = evaluation(report_path, "phase9_h2o_fold_heldout") + cache = file_binding(report, "cache_manifest") + expected_path = Path(expected_manifest_path) + expected_exists = expected_path.is_file() + expected_actual_sha = sha256(expected_path) if expected_exists else None + cache.update({ + "expected_path": expected_manifest_path, + "expected_sha256": expected_manifest_sha256, + "expected_path_exists": expected_exists, + "expected_path_actual_sha256": expected_actual_sha, + "path_matches": cache["path"] == expected_manifest_path, + "content_matches_expected": ( + cache["declared_sha256"] == expected_manifest_sha256 + and cache["actual_sha256"] == expected_manifest_sha256 + and expected_actual_sha == expected_manifest_sha256 + ), + }) + if not cache["content_matches_expected"]: + binding_status = "content_mismatch" + elif not cache["path_matches"]: + binding_status = "path_mismatch_content_identical" + else: + binding_status = "canonical" + result = { + "id": f"{condition}_{checkpoint_id}_rgb_d_k", + "condition": condition, + "checkpoint_id": checkpoint_id, + "input_mode": "rgb_d_k", + "report": { + "path": str(report_path.resolve()), + "sha256": sha256(report_path), + }, + "binding_status": binding_status, + "cache_manifest": cache, + "config": file_binding(report, "config"), + "checkpoint": file_binding(report, "checkpoint"), + "sample_counts": { + "clips": report.get("clips"), + "frames": report.get("frames"), + "hands_rows": report.get("hands_rows"), + }, + "determinism": { + "metrics_sha256": json_sha256(report.get("metrics")), + "grouped_bootstrap_ci_sha256": json_sha256( + report.get("grouped_bootstrap_ci") + ), + "raw_predictions": artifact_binding(report, "raw_predictions"), + "per_hand_rows": artifact_binding(report, "per_hand_rows"), + "take_metrics": artifact_binding(report, "take_metrics"), + }, + "evaluation_role": report.get("evaluation_role"), + "official_test_used": report.get("official_test_used"), + "h2o_official_validation_used": report.get( + "h2o_official_validation_used" + ), + } + required_bindings = [result["config"], result["checkpoint"]] + required_artifacts = [ + result["determinism"]["raw_predictions"], + result["determinism"]["per_hand_rows"], + result["determinism"]["take_metrics"], + ] + if not all(item["sha256_matches"] for item in required_bindings + required_artifacts): + result["binding_status"] = "referenced_artifact_mismatch" + return result + + +def build_audit( + *, selection_plan_path: Path, assignment_path: Path, +) -> dict[str, Any]: + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + if ( + selection_plan.get("official_test_used") is not False + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + ): + raise ValueError("selection audit must explicitly exclude official test") + index_path = Path(selection_plan["multifold_index"]) + index = json.loads(index_path.read_text(encoding="utf-8")) + folds = { + fold["id"]: fold for fold in validate_multifold_index(index) + } + records = [] + for mixture, checkpoint_id, fold in candidate_records(): + condition = f"{mixture}_{fold}" + path = evaluation_path( + fold_final_root=Path(selection_plan["fold_final_root"]), + fold_milestone_root=Path(selection_plan["fold_milestone_root"]), + condition=condition, checkpoint_id=checkpoint_id, + ) + records.append(audit_report( + report_path=path, condition=condition, + checkpoint_id=checkpoint_id, + expected_manifest_path=folds[fold]["heldout"]["path"], + expected_manifest_sha256=folds[fold]["heldout"]["sha256"], + )) + mismatches = [ + record for record in records + if record["binding_status"] != "canonical" + ] + assigned = { + item["id"] + for item in assignment["phase9_selection_recovery"]["evaluations"] + } + mismatch_ids = {item["id"] for item in mismatches} + status_counts = { + status: sum(item["binding_status"] == status for item in records) + for status in sorted({item["binding_status"] for item in records}) + } + if len(records) != 72 or len({item["id"] for item in records}) != 72: + raise ValueError("selection-critical report set is not exactly 72 unique IDs") + if mismatch_ids != assigned: + raise ValueError( + "selection mismatch IDs differ from frozen distributed assignment: " + f"missing={sorted(assigned - mismatch_ids)} " + f"unexpected={sorted(mismatch_ids - assigned)}" + ) + if any( + item["binding_status"] != "path_mismatch_content_identical" + for item in mismatches + ): + raise ValueError("selection mismatch includes a non-path-only failure") + return { + "schema_version": "phase9_selection_binding_mismatch_manifest_v1", + "status": "complete_path_only_recovery_required", + "created_utc": datetime.now(timezone.utc).isoformat(), + "selection_plan": { + "path": str(selection_plan_path.resolve()), + "sha256": sha256(selection_plan_path), + }, + "distributed_assignment": { + "path": str(assignment_path.resolve()), + "sha256": sha256(assignment_path), + }, + "multifold_index": { + "path": str(index_path.resolve()), "sha256": sha256(index_path), + }, + "selection_critical_report_count": len(records), + "canonical_report_count": len(records) - len(mismatches), + "mismatch_count": len(mismatches), + "binding_status_counts": status_counts, + "mismatch_ids": sorted(mismatch_ids), + "records": records, + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("audit output must be new") + result = build_audit( + selection_plan_path=args.selection_plan, + assignment_path=args.assignment, + ) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase9_source_coverage.py b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase9_source_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..db9555573bedef023846df78f2f866856869bee5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/audit_phase9_source_coverage.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Audit unique source coverage and cached geometric distributions.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def recording_id(row: dict[str, Any]) -> str: + return str(row.get("physical_recording_id", row.get("recording_id", "unknown"))) + + +def subject_id(row: dict[str, Any]) -> str: + return str(row.get("subject_id", row.get("participant_id", "unknown"))) + + +def frame_tokens(row: dict[str, Any]) -> list[str]: + values = ( + row.get("timestamps_ns") or row.get("timestamps_seconds") + or row.get("frame_ids") or row.get("frame_ids_1based") + or row.get("image_paths") or [] + ) + group = recording_id(row) + return [f"{group}:{value}" for value in values] + + +def action_family(dataset: str, recording: str) -> str: + parts = recording.split("/") + if dataset == "H2O" and len(parts) > 1: + return parts[1][:1] + if dataset == "HOI4D": + fields = [part for part in parts if part.startswith(("C", "N", "S"))] + return "/".join(fields[:3]) if fields else "unknown" + if dataset == "ARCTIC" and len(parts) > 1: + return parts[-1].rsplit("_", 1)[0] + return "unknown" + + +def quantiles(values: list[float]) -> dict[str, float | int | None]: + finite = np.asarray(values, dtype=np.float64) + finite = finite[np.isfinite(finite)] + if not len(finite): + return {"count": 0, "mean": None, "p05": None, "median": None, "p95": None} + return { + "count": int(len(finite)), "mean": float(finite.mean()), + "p05": float(np.percentile(finite, 5)), + "median": float(np.percentile(finite, 50)), + "p95": float(np.percentile(finite, 95)), + } + + +def source_summary(dataset: str, rows: list[dict[str, Any]]) -> dict[str, Any]: + tokens = [token for row in rows for token in frame_tokens(row)] + recordings = {recording_id(row) for row in rows} + return { + "clips": len(rows), + "subjects_or_participants": sorted({subject_id(row) for row in rows}), + "physical_recordings": len(recordings), + "headsets": sorted({str(row.get("headset", row.get("serial_id", "unknown"))) for row in rows}), + "cameras_or_streams": sorted({str(row.get("camera_id", row.get("stream_id", "unknown"))) for row in rows}), + "frame_references": len(tokens), + "unique_image_observations": len(set(tokens)) if tokens else None, + "clip_overlap_fraction": (1.0 - len(set(tokens)) / len(tokens)) if tokens else None, + "action_or_object_families": dict(sorted(Counter( + action_family(dataset, recording) for recording in recordings + ).items())), + } + + +def cache_numeric_summary(rows: list[dict[str, Any]]) -> dict[str, Any]: + unique_frames: set[str] = set() + side_frames = [0, 0] + single_frames = bimanual_frames = valid_frames = 0 + joint_visible = joint_total = 0 + border_hands = projected_outlier_hands = 0 + hand_sizes: list[float] = [] + wrist_depths: list[float] = [] + fx_values: list[float] = [] + fy_values: list[float] = [] + fov_x_values: list[float] = [] + depth_valid_fractions: list[float] = [] + supervision = Counter() + for row in rows: + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"cache payload is missing or differs: {path}") + with np.load(path, allow_pickle=False) as archive: + frame_valid = archive["frame_valid"].astype(bool) + translation_valid = archive["translation_valid"].astype(bool) + joint2d_valid = archive["joint2d_valid"].astype(bool) + joint2d = archive["joint2d"] + translation = archive["wrist_root_translation"] + K = archive["K"] + image_hw = archive["image_hw"] + frame_ids = archive["frame_id"] + depth_available = archive["depth_input_available"].astype(bool) + depth_pixel_valid = archive["depth_pixel_valid"].astype(bool) + for key in ( + "joint2d_valid", "joint3d_valid", "translation_valid", + "mano_pose_valid", "shape_valid", "vertices_valid", + ): + supervision[key] += int(np.count_nonzero(archive[key])) + group = row["physical_recording_id"] + for time_index in np.flatnonzero(frame_valid): + unique_frames.add(f"{group}:{int(frame_ids[time_index])}") + valid_frames += 1 + present = translation_valid[time_index] + side_frames[0] += int(present[0]) + side_frames[1] += int(present[1]) + single_frames += int(present.sum() == 1) + bimanual_frames += int(present.sum() == 2) + matrix = K[time_index] + fx_values.append(float(matrix[0, 0])) + fy_values.append(float(matrix[1, 1])) + fov_x_values.append(float(2 * np.arctan(float(image_hw[1]) / (2 * matrix[0, 0])))) + if depth_available[time_index]: + depth_valid_fractions.append(float(depth_pixel_valid[time_index].mean())) + for side in range(2): + if not present[side]: + continue + valid = joint2d_valid[time_index, side] + points_all = joint2d[time_index, side] + height, width = int(image_hw[0]), int(image_hw[1]) + finite = np.isfinite(points_all).all(axis=-1) + in_frame = ( + finite & (points_all[:, 0] >= 0) & (points_all[:, 0] < width) + & (points_all[:, 1] >= 0) & (points_all[:, 1] < height) + ) + visible = valid & in_frame + joint_visible += int(visible.sum()) + joint_total += int(len(valid)) + valid_finite = valid & finite + if valid_finite.any(): + raw_points = points_all[valid_finite] + raw_extent = raw_points.max(axis=0) - raw_points.min(axis=0) + projected_outlier_hands += int(raw_extent.max() > 4 * max(height, width)) + if visible.any(): + points = points_all[visible] + extent = points.max(axis=0) - points.min(axis=0) + hand_sizes.append(float(extent.max())) + border_hands += int( + points[:, 0].min() < 8 or points[:, 0].max() >= width - 8 + or points[:, 1].min() < 8 or points[:, 1].max() >= height - 8 + ) + wrist_depths.append(float(translation[time_index, side, 2])) + return { + "unique_cached_frames": len(unique_frames), + "valid_frame_references": valid_frames, + "left_hand_frames": side_frames[0], + "right_hand_frames": side_frames[1], + "single_hand_frames": single_frames, + "bimanual_frames": bimanual_frames, + "joint_visibility_fraction": joint_visible / joint_total if joint_total else None, + "occlusion_proxy_fraction": 1.0 - joint_visible / joint_total if joint_total else None, + "border_hand_frames": border_hands, + "projected_geometry_outlier_hand_frames": projected_outlier_hands, + "projected_hand_size_px": quantiles(hand_sizes), + "wrist_depth_m": quantiles(wrist_depths), + "fx_px": quantiles(fx_values), + "fy_px": quantiles(fy_values), + "horizontal_fov_radians": quantiles(fov_x_values), + "depth_valid_fraction": quantiles(depth_valid_fractions), + "supervision_valid_elements": dict(supervision), + } + + +def build_report( + dataset: str, source_manifest: Path, cache_manifest: Path, +) -> dict[str, Any]: + source_rows, cache_rows = read_jsonl(source_manifest), read_jsonl(cache_manifest) + cached_indices = {int(row["source_clip_index"]) for row in cache_rows} + if len(cached_indices) != len(cache_rows): + raise ValueError("cache manifest contains duplicate source clip indices") + if {row.get("dataset_id") for row in cache_rows} != {dataset}: + raise ValueError("cache manifest dataset differs from request") + return { + "schema_version": "phase9_source_coverage_v1", + "status": "complete", + "dataset": dataset, + "source_manifest": {"path": str(source_manifest.resolve()), "sha256": sha256(source_manifest)}, + "cache_manifest": {"path": str(cache_manifest.resolve()), "sha256": sha256(cache_manifest)}, + "source": source_summary(dataset, source_rows), + "cache": { + "clips": len(cache_rows), + "source_clip_coverage_fraction": len(cache_rows) / len(source_rows), + "subjects_or_participants": sorted({subject_id(row) for row in cache_rows}), + "physical_recordings": len({recording_id(row) for row in cache_rows}), + **cache_numeric_summary(cache_rows), + }, + "optimizer_exposure_is_unique_coverage": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("H2O", "HOT3D", "HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = build_report(args.dataset, args.source_manifest, args.cache_manifest) + except (OSError, ValueError, KeyError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_manifests.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..51063b592a532d6c453c612b141931ae3ac86d48 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_manifests.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Build reproducible cam4-only H2O run manifests from official pose lists.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path + + +def contiguous_runs(frame_ids: list[int]) -> list[list[int]]: + if not frame_ids: + return [] + runs = [[frame_ids[0]]] + for frame_id in frame_ids[1:]: + if frame_id == runs[-1][-1] + 1: + runs[-1].append(frame_id) + else: + runs.append([frame_id]) + return runs + + +def official_records(path: Path) -> list[dict[str, object]]: + grouped: dict[str, list[int]] = defaultdict(list) + for line in path.read_text(encoding="utf-8").splitlines(): + relative = Path(line.strip()) + if not line.strip(): + continue + if relative.parts[-3] != "cam4" or relative.parts[-2] != "rgb": + raise ValueError(f"Not a cam4 RGB record: {line}") + take = Path(*relative.parts[:-2]) + grouped[str(take)].append(int(relative.stem)) + records = [] + for take, ids in sorted(grouped.items()): + for run_index, run in enumerate(contiguous_runs(sorted(set(ids)))): + records.append({"take": take, "run_index": run_index, "frame_ids": run}) + return records + + +def write_jsonl(path: Path, records: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as handle: + for record in records: + handle.write(json.dumps(record, separators=(",", ":")) + "\n") + + +def build_debug_records(frame_csv: Path, window: int = 16, per_category: int = 4) -> list[dict[str, object]]: + categories: dict[str, list[dict[str, str]]] = defaultdict(list) + with frame_csv.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + key = row["joint_left_valid"] + row["joint_right_valid"] + categories[key].append(row) + selected = [] + for category, rows in sorted(categories.items()): + if category not in {"01", "10", "11"}: + continue + indices = [round(i * (len(rows) - 1) / max(per_category - 1, 1)) for i in range(per_category)] + for row_index in indices: + row = rows[row_index] + center = int(row["frame_id"]) + start = max(0, center - window // 2) + take_path = Path(row["rgb_path"]).parents[1] + available = sorted(int(path.stem) for path in (take_path / "rgb").glob("*.png")) + valid_ids = set(available) + frames = [frame_id for frame_id in range(start, start + window) if frame_id in valid_ids] + selected.append({ + "take": "/".join(take_path.parts[-4:]), + "run_index": len(selected), + "frame_ids": frames, + "debug_center_valid": category, + "debug_center_frame": center, + }) + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--pose-list-dir", type=Path, required=True) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + summary = {} + for split in ("train", "val", "test"): + records = official_records(args.pose_list_dir / f"pose_{split}.txt") + output = args.output_dir / f"official_{split}.jsonl" + write_jsonl(output, records) + summary[split] = { + "path": str(output.resolve()), + "runs": len(records), + "frames": sum(len(record["frame_ids"]) for record in records), + "subjects": sorted({str(record["take"]).split("/")[0] for record in records}), + } + debug = build_debug_records(args.frame_csv) + debug_path = args.output_dir / "debug_cam4.jsonl" + write_jsonl(debug_path, debug) + summary["debug"] = {"path": str(debug_path.resolve()), "runs": len(debug), "frames": sum(len(record["frame_ids"]) for record in debug)} + tiny = [] + for category in ("01", "10", "11"): + tiny.extend([record for record in debug if record["debug_center_valid"] == category][:2]) + tiny_path = args.output_dir / "tiny_overfit_cam4.jsonl" + write_jsonl(tiny_path, tiny) + summary["tiny_overfit"] = { + "path": str(tiny_path.resolve()), + "runs": len(tiny), + "frames": sum(len(record["frame_ids"]) for record in tiny), + "center_valid_combinations": {category: 2 for category in ("01", "10", "11")}, + } + summary["policy"] = "Official pose split; clips are generated inside each contiguous take/run and never cross camera, sequence, or subject." + (args.output_dir / "manifest_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase3_val_subset.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase3_val_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5c9941a59e168b9e49e961c4a41f3556b97aa9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase3_val_subset.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Build the fixed 256-clip Phase 3 validation subset from input-only strata.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.subset import balanced_stratified_indices + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def size_bucket(value: float) -> str: + if value < 64: + return "small" + if value < 128: + return "medium" + return "large" + + +def depth_bucket(value: float) -> str: + if value < 0.5: + return "near" + if value < 0.8: + return "middle" + return "far" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--per-hand-frames", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--count", type=int, default=256) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + with args.per_hand_frames.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + grouped: dict[int, list[dict[str, str]]] = defaultdict(list) + for row in rows: + grouped[int(row["clip_index"])].append(row) + + clip_records: list[dict[str, object]] = [] + for clip_index, clip_rows in sorted(grouped.items()): + sizes = [float(row["hand_size_px"]) for row in clip_rows if row["hand_size_px"]] + depths = [float(row["wrist_depth_m"]) for row in clip_rows if row["wrist_depth_m"]] + states = [row["annotation_state"] for row in clip_rows] + state_counts = Counter(states) + # Preserve rare one-hand-valid clips as a stratum instead of letting the + # dominant both-valid frames erase them. + annotation_state = "01" if state_counts["01"] else "10" if state_counts["10"] else state_counts.most_common(1)[0][0] + median_size = float(np.median(sizes)) if sizes else float("nan") + median_depth = float(np.median(depths)) if depths else float("nan") + first = clip_rows[0] + clip_records.append({ + "clip_index": clip_index, + "take": first["take"], + "subject": first["subject"], + "sequence": first["sequence"], + "first_frame_id": min(int(row["frame_id"]) for row in clip_rows), + "last_frame_id": max(int(row["frame_id"]) for row in clip_rows), + "hand_size_px_median": median_size, + "hand_size_bucket": size_bucket(median_size) if np.isfinite(median_size) else "unavailable", + "wrist_depth_m_median": median_depth, + "depth_bucket": depth_bucket(median_depth) if np.isfinite(median_depth) else "unavailable", + "annotation_state": annotation_state, + }) + + selected_indices = balanced_stratified_indices(clip_records, args.count, seed=args.seed) + selected_set = set(selected_indices) + selected_records = [record for record in clip_records if int(record["clip_index"]) in selected_set] + take_counts = Counter(str(record["take"]) for record in selected_records) + stratum_counts = Counter( + (str(record["hand_size_bucket"]), str(record["depth_bucket"]), str(record["annotation_state"])) + for record in selected_records + ) + manifest = { + "version": "phase3_stratified_256_v1", + "seed": args.seed, + "count": len(selected_indices), + "source_manifest": str(args.source_manifest.resolve()), + "source_manifest_sha256": sha256(args.source_manifest), + "source_clip_count": len(clip_records), + "dataset_contract": {"resolution_hw": [288, 512], "T": 8, "stride": 1, "allow_partial": True}, + "selection_inputs": "take, GT-projected hand extent, wrist depth, annotation validity; model errors are excluded", + "selection_policy": "balanced take quotas plus deterministic round-robin within-take size/depth/valid strata", + "clip_indices": selected_indices, + "take_counts": dict(sorted(take_counts.items())), + "stratum_counts": {"/".join(key): value for key, value in sorted(stratum_counts.items())}, + "official_test_used": False, + } + manifest_path = args.output_dir / "validation_subset_256.json" + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + + csv_path = args.output_dir / "validation_subset_256.csv" + with csv_path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(selected_records[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(selected_records) + (args.output_dir / "validation_subset_256.sha256").write_text( + f"{sha256(manifest_path)} {manifest_path.name}\n{sha256(csv_path)} {csv_path.name}\n", + encoding="utf-8", + ) + print(json.dumps({ + "status": "created", "count": len(selected_indices), "takes": len(take_counts), + "take_count_min": min(take_counts.values()), "take_count_max": max(take_counts.values()), + "manifest": str(manifest_path), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase4_balanced_sampler.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase4_balanced_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..da8852e7b9d01cedc7c28961a16d8b599e3a06a0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase4_balanced_sampler.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""Build a deterministic train-only geometry-balanced sampling manifest.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from collections import Counter +from pathlib import Path + +import numpy as np + +from foundation_hand.data import H2OCam4Dataset +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record +from foundation_hand.evaluation.phase4 import bimanual_asymmetry +from foundation_hand.geometry.camera import ( + intrinsics_from_h2o, + project_points, + resize_and_pad_intrinsics, +) + + +AXES = ( + "left_size_bucket", + "right_size_bucket", + "left_depth_bucket", + "right_depth_bucket", + "asymmetry_bucket", + "action_family", + "annotation_valid_state", +) +WEIGHT_MIN = 0.5 +WEIGHT_MAX = 3.0 +TAKE_FACTOR_MIN = 2.0 / 3.0 +TAKE_FACTOR_MAX = 1.5 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def fit_resize( + source_hw: tuple[int, int], target_hw: tuple[int, int], +) -> tuple[tuple[int, int], tuple[int, int]]: + source_h, source_w = source_hw + target_h, target_w = target_hw + scale = min(target_w / source_w, target_h / source_h) + resized = (max(1, round(source_h * scale)), max(1, round(source_w * scale))) + return resized, ((target_w - resized[1]) // 2, (target_h - resized[0]) // 2) + + +def size_bucket(value: float | None) -> str: + if value is None: + return "unavailable" + if value < 64.0: + return "small" + if value < 128.0: + return "medium" + return "large" + + +def depth_bucket(value: float | None) -> str: + if value is None: + return "unavailable" + if value < 0.5: + return "near" + if value < 0.8: + return "middle" + return "far" + + +def median_or_none(values: list[float]) -> float | None: + return float(np.median(values)) if values else None + + +def validity_state(valid_counts: list[int], frame_count: int) -> str: + frequent = [count / frame_count >= 0.5 for count in valid_counts] + if frequent == [True, True]: + return "both" + if frequent == [True, False]: + return "left_only" + if frequent == [False, True]: + return "right_only" + return "sparse" + + +def clip_geometry_record( + root: Path, + clip_index: int, + clip, + target_hw: tuple[int, int], + intrinsics_cache: dict[str, np.ndarray], +) -> dict[str, object]: + take_dir = root / clip.take + if clip.take not in intrinsics_cache: + K_raw, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + resized_hw, pad_left_top = fit_resize(source_hw, target_hw) + intrinsics_cache[clip.take] = resize_and_pad_intrinsics( + K_raw, source_hw, resized_hw, pad_left_top, + ) + K = intrinsics_cache[clip.take] + sizes: list[list[float]] = [[], []] + depths: list[list[float]] = [[], []] + valid_counts = [0, 0] + ratios: list[float] = [] + gaps: list[float] = [] + for frame_id in clip.frame_ids: + joints = load_joint_record(take_dir / "hand_pose" / f"{frame_id:06d}.txt") + joints_2d, positive = project_points(joints.joints_camera_m, K) + frame_sizes: list[float | None] = [None, None] + frame_depths: list[float | None] = [None, None] + for hand in range(2): + if not bool(joints.annotation_valid[hand]) or not bool(positive[hand].all()): + continue + extent = joints_2d[hand].max(axis=0) - joints_2d[hand].min(axis=0) + size = float(extent.max()) + depth = float(joints.joints_camera_m[hand, 0, 2]) + sizes[hand].append(size) + depths[hand].append(depth) + valid_counts[hand] += 1 + frame_sizes[hand] = size + frame_depths[hand] = depth + asymmetry = bimanual_asymmetry(frame_sizes, frame_depths) + if asymmetry["bimanual_size_ratio"] is not None: + ratios.append(float(asymmetry["bimanual_size_ratio"])) + gaps.append(float(asymmetry["bimanual_depth_gap_m"])) + median_sizes = [median_or_none(values) for values in sizes] + median_depths = [median_or_none(values) for values in depths] + aggregate_asymmetry = bimanual_asymmetry(median_sizes, median_depths) + parts = Path(clip.take).parts + return { + "clip_index": clip_index, + "take": clip.take, + "frame_count": len(clip.frame_ids), + "action_family": parts[1], + "annotation_valid_state": validity_state(valid_counts, len(clip.frame_ids)), + "left_valid_fraction": valid_counts[0] / len(clip.frame_ids), + "right_valid_fraction": valid_counts[1] / len(clip.frame_ids), + "left_hand_size_px": median_sizes[0], + "right_hand_size_px": median_sizes[1], + "left_wrist_depth_m": median_depths[0], + "right_wrist_depth_m": median_depths[1], + "median_size_ratio": median_or_none(ratios), + "median_depth_gap_m": median_or_none(gaps), + "left_size_bucket": size_bucket(median_sizes[0]), + "right_size_bucket": size_bucket(median_sizes[1]), + "left_depth_bucket": depth_bucket(median_depths[0]), + "right_depth_bucket": depth_bucket(median_depths[1]), + "asymmetry_bucket": aggregate_asymmetry["bimanual_asymmetry_bucket"] or "unavailable", + } + + +def assign_weights(records: list[dict[str, object]]) -> dict[str, object]: + if not records: + raise ValueError("cannot balance an empty clip set") + frequencies = { + axis: Counter(str(record[axis]) for record in records) for axis in AXES + } + take_counts = Counter(str(record["take"]) for record in records) + median_take_count = float(np.median(list(take_counts.values()))) + raw_weights = [] + for record in records: + marginal = [] + for axis in AXES: + counts = frequencies[axis] + count = counts[str(record[axis])] + marginal.append(math.sqrt(len(records) / (len(counts) * count))) + geometry_factor = float(np.mean(marginal)) + take_factor = math.sqrt(median_take_count / take_counts[str(record["take"])]) + take_factor = float(np.clip(take_factor, TAKE_FACTOR_MIN, TAKE_FACTOR_MAX)) + raw_weights.append(geometry_factor * take_factor) + record["geometry_rarity_factor"] = geometry_factor + record["take_frequency_factor"] = take_factor + scale = float(np.mean(raw_weights)) + weights = np.clip(np.asarray(raw_weights) / scale, WEIGHT_MIN, WEIGHT_MAX) + for record, weight in zip(records, weights, strict=True): + record["weight"] = float(weight) + return { + "axis_frequencies": { + axis: dict(sorted(counts.items())) for axis, counts in frequencies.items() + }, + "take_clip_count_min": min(take_counts.values()), + "take_clip_count_median": median_take_count, + "take_clip_count_max": max(take_counts.values()), + "weight_min": float(weights.min()), + "weight_mean": float(weights.mean()), + "weight_max": float(weights.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--expected-manifest-sha256", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--resolution-hw", type=int, nargs=2, default=(368, 640)) + parser.add_argument("--T", type=int, default=8) + parser.add_argument("--stride", type=int, default=1) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args() + if "test" in args.manifest.name.lower() or "val" in args.manifest.name.lower(): + raise ValueError("balanced sampler builder accepts official train only") + manifest_hash = sha256(args.manifest) + if manifest_hash != args.expected_manifest_sha256: + raise ValueError("official-train manifest hash mismatch") + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite {args.output}") + target_hw = tuple(args.resolution_hw) + dataset = H2OCam4Dataset( + args.root, args.manifest, target_hw, (args.T,), (args.stride,), + max_clips=args.max_clips, + ) + cache: dict[str, np.ndarray] = {} + records = [] + for clip_index, clip in enumerate(dataset.clips): + records.append(clip_geometry_record( + args.root, clip_index, clip, target_hw, cache, + )) + if (clip_index + 1) % 500 == 0: + print(f"clips={clip_index + 1}/{len(dataset)}", flush=True) + summary = assign_weights(records) + output = { + "version": "phase4_train_geometry_balanced_v1", + "phase": 4, + "wave": "B2", + "split_role": "official_train", + "official_test_used": False, + "source_manifest": str(args.manifest.resolve()), + "source_manifest_sha256": manifest_hash, + "dataset_contract": { + "resolution_hw": list(target_hw), "T": args.T, "stride": args.stride, + "allow_partial": True, + }, + "clip_count": len(records), + "policy": { + "axes": list(AXES), + "marginal_weight": "inverse square root of train-only clip frequency", + "combination": "mean marginal rarity multiplied by capped take-frequency correction", + "weight_cap": [WEIGHT_MIN, WEIGHT_MAX], + "take_factor_cap": [TAKE_FACTOR_MIN, TAKE_FACTOR_MAX], + "draws": "dataset_size draws with replacement per seed+epoch", + "validation_identity_used": False, + }, + "summary": summary, + "clips": records, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": "complete", "clips": len(records), **summary}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase4_checkpoint_index.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase4_checkpoint_index.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c866726979ff9b6154bd9fcd36293264747a33 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase4_checkpoint_index.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Build a deterministic index of Phase 4 official-validation checkpoints.""" + +from __future__ import annotations + +import argparse +import json +import os +import re +from pathlib import Path +from typing import Any + + +SHA256 = re.compile(r"[0-9a-f]{64}") +OFFICIAL_VALIDATION_CLIPS = 1495 +OFFICIAL_VALIDATION_FRAMES = 11638 + + +def evaluation_reports(root: Path) -> list[Path]: + """Find reports through SSD-backed artifact symlinks without following cycles.""" + reports = [] + visited_directories: set[Path] = set() + for directory, names, files in os.walk(root, followlinks=True): + directory_path = Path(directory) + resolved_directory = directory_path.resolve() + if resolved_directory in visited_directories: + names.clear() + continue + visited_directories.add(resolved_directory) + names[:] = sorted( + name for name in names + if (directory_path / name).resolve() not in visited_directories + ) + if "evaluation.json" in files: + reports.append(directory_path / "evaluation.json") + return sorted(reports) + + +def logical_location(root: Path, report_path: Path) -> tuple[str, str, str]: + parts = report_path.relative_to(root).parts + if "full_validation" in parts: + index = parts.index("full_validation") + if len(parts) <= index + 3: + raise ValueError(f"invalid full-validation path: {report_path}") + condition = "/".join(parts[:index]) + return condition, parts[index + 1], parts[index + 2] + if len(parts) < 2: + raise ValueError(f"invalid evaluation path: {report_path}") + return parts[0], report_path.parent.name, "reference" + + +def build_index(root: Path) -> dict[str, Any]: + root = root.resolve() + records = [] + for report_path in evaluation_reports(root): + report = json.loads(report_path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("split_role") != "official_validation": + continue + if report.get("official_test_used") is not False: + raise ValueError(f"official-validation report lacks test isolation: {report_path}") + # Real-checkpoint smokes use the validation split but are not complete + # evaluations and must not enter the formal checkpoint index. + if ( + report.get("clips") != OFFICIAL_VALIDATION_CLIPS + or report.get("frames") != OFFICIAL_VALIDATION_FRAMES + ): + continue + checkpoint = report.get("checkpoint") + if not isinstance(checkpoint, dict): + raise ValueError(f"missing checkpoint record: {report_path}") + sha256 = checkpoint.get("sha256") + if not isinstance(sha256, str) or SHA256.fullmatch(sha256) is None: + raise ValueError(f"invalid checkpoint SHA256: {report_path}") + checkpoint_path = Path(str(checkpoint.get("path", ""))) + if not checkpoint_path.is_file(): + raise FileNotFoundError(f"indexed checkpoint is missing: {checkpoint_path}") + step = checkpoint.get("step") + if not isinstance(step, int) or step < 0: + raise ValueError(f"invalid checkpoint step: {report_path}") + condition, run, role = logical_location(root, report_path) + config = report.get("config", {}) + records.append({ + "condition": condition, + "run": run, + "role": role, + "config": config.get("name"), + "seed": config.get("seed"), + "checkpoint_path": str(checkpoint_path.resolve()), + "checkpoint_sha256": sha256, + "checkpoint_step": step, + "evaluation_path": str(report_path.resolve()), + "clips": report.get("clips"), + "frames": report.get("frames"), + }) + if not records: + raise ValueError(f"no official-validation evaluations found under {root}") + unique_checkpoints = { + (record["checkpoint_path"], record["checkpoint_sha256"]) + for record in records + } + return { + "status": "indexed", + "official_test_used": False, + "evaluations": len(records), + "unique_checkpoints": len(unique_checkpoints), + "records": records, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--phase4-root", type=Path, default=Path("artifacts/phase4"), + ) + parser.add_argument( + "--output", type=Path, + default=Path("artifacts/phase4/reports/checkpoints.json"), + ) + args = parser.parse_args() + payload = build_index(args.phase4_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": payload["status"], + "evaluations": payload["evaluations"], + "unique_checkpoints": payload["unique_checkpoints"], + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase5_group_folds.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase5_group_folds.py new file mode 100644 index 0000000000000000000000000000000000000000..996077ed4feed509db4ffefe17c0a09ae4f40367 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase5_group_folds.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Build deterministic subject-held-out OOF manifests from official train only.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None: + with path.open("w", encoding="utf-8") as handle: + for record in records: + handle.write(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n") + + +def record_id(record: dict[str, Any]) -> tuple[str, int]: + return str(record["take"]), int(record["run_index"]) + + +def subject(record: dict[str, Any]) -> str: + return str(record["take"]).split("/", 1)[0] + + +def fold_summary(records: list[dict[str, Any]]) -> dict[str, Any]: + return { + "records": len(records), + "frames": sum(len(record["frame_ids"]) for record in records), + "takes": len({str(record["take"]) for record in records}), + "subjects": sorted({subject(record) for record in records}), + "action_families": sorted({str(record["take"]).split("/")[1] for record in records}), + } + + +def build_subject_folds(source_manifest: Path, output_root: Path) -> dict[str, Any]: + records = [ + json.loads(line) + for line in source_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not records: + raise ValueError("source manifest is empty") + ids = [record_id(record) for record in records] + if len(ids) != len(set(ids)): + raise ValueError("source manifest contains duplicate take/run records") + for record in records: + if not record.get("frame_ids"): + raise ValueError(f"record has no frames: {record_id(record)}") + + by_subject: dict[str, list[dict[str, Any]]] = defaultdict(list) + for record in records: + by_subject[subject(record)].append(record) + subjects = sorted(by_subject) + if len(subjects) < 2: + raise ValueError("subject-held-out OOF requires at least two subjects") + + output_root.mkdir(parents=True, exist_ok=True) + folds = [] + heldout_ids: set[tuple[str, int]] = set() + for fold_index, heldout_subject in enumerate(subjects): + fold_dir = output_root / f"fold_{fold_index}_{heldout_subject}" + fold_dir.mkdir(parents=True, exist_ok=True) + heldout = sorted(by_subject[heldout_subject], key=record_id) + train = sorted( + (record for record in records if subject(record) != heldout_subject), + key=record_id, + ) + train_path = fold_dir / "train.jsonl" + heldout_path = fold_dir / "heldout.jsonl" + write_jsonl(train_path, train) + write_jsonl(heldout_path, heldout) + + train_takes = {str(record["take"]) for record in train} + heldout_takes = {str(record["take"]) for record in heldout} + train_subjects = {subject(record) for record in train} + heldout_subjects = {subject(record) for record in heldout} + leakage_free = not (train_takes & heldout_takes) and not ( + train_subjects & heldout_subjects + ) + if not leakage_free: + raise RuntimeError(f"group leakage detected in fold {fold_index}") + current_ids = {record_id(record) for record in heldout} + if heldout_ids & current_ids: + raise RuntimeError("a source record appears in more than one heldout fold") + heldout_ids.update(current_ids) + folds.append({ + "fold": fold_index, + "heldout_subject": heldout_subject, + "train_manifest": str(train_path.relative_to(output_root)), + "train_manifest_sha256": sha256(train_path), + "heldout_manifest": str(heldout_path.relative_to(output_root)), + "heldout_manifest_sha256": sha256(heldout_path), + "train": fold_summary(train), + "heldout": fold_summary(heldout), + "leakage_audit": { + "take_overlap": [], + "subject_overlap": [], + "passed": True, + }, + }) + + if heldout_ids != set(ids): + raise RuntimeError("heldout folds do not form an exact partition of official train") + report = { + "version": "phase5_subject_oof_v1", + "status": "frozen", + "source_role": "official_train", + "source_manifest": str(source_manifest.resolve()), + "source_manifest_sha256": sha256(source_manifest), + "assignment": "one complete official-train subject per heldout fold", + "group_unit": "subject; take/recording is indivisible", + "folds": folds, + "source": fold_summary(records), + "coverage_audit": { + "heldout_records": len(heldout_ids), + "source_records": len(records), + "exact_partition": True, + }, + "official_validation_used_for_assignment": False, + "official_test_used": False, + } + (output_root / "folds.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + args = parser.parse_args() + report = build_subject_folds(args.source_manifest, args.output_root) + print(json.dumps({ + "status": report["status"], + "version": report["version"], + "folds": len(report["folds"]), + "source": report["source"], + "official_test_used": report["official_test_used"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase5_missing_alignment_package.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase5_missing_alignment_package.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9247dc5bb746e3387abd07ad37a634e36ece53 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase5_missing_alignment_package.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Build an exact zero-alignment package for true missing-input causal audits.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def validate_cache( + manifest: dict[str, Any], expected_condition: str, expected_scope: str, +) -> None: + if ( + manifest.get("status") != "complete" + or manifest.get("scope") != expected_scope + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + or manifest.get("input_condition") != expected_condition + ): + raise ValueError("invalid true missing-input cache contract") + if expected_scope == "full" and ( + manifest.get("clips") != 1495 or manifest.get("frames") != 11638 + ): + raise ValueError("invalid full-cache coverage") + + +def fallback_prediction(arrays: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + frame_id = arrays["frame_id"] + translation = arrays["pred_wrist_translation"] + if frame_id.ndim != 1 or translation.shape[:2] != (len(frame_id), 2): + raise ValueError("invalid cache take dimensions") + shape = (len(frame_id), 2) + zeros = np.zeros(shape, dtype=np.float32) + return { + "frame_id": frame_id.astype(np.int64, copy=False), + "calibrated_delta_z_m": zeros, + "alignment_applied": np.zeros(shape, dtype=bool), + "confidence": zeros.copy(), + "inlier_ratio": zeros.copy(), + "residual_scale_m": zeros.copy(), + "valid_fraction": zeros.copy(), + "quality": zeros.copy(), + } + + +def build_package( + cache_dir: Path, + output_dir: Path, + expected_condition: str, + expected_scope: str, +) -> dict[str, Any]: + if output_dir.exists() and any(output_dir.iterdir()): + raise FileExistsError("fallback alignment output must be new or empty") + manifest_path = cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + validate_cache(manifest, expected_condition, expected_scope) + output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = output_dir / "predictions" + prediction_root.mkdir() + records = [] + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"cache take hash mismatch: {take_path}") + arrays = load_npz(take_path) + stem = "__".join(Path(str(arrays["take"])).parts) + prediction_path = prediction_root / f"{stem}.npz" + np.savez_compressed(prediction_path, **fallback_prediction(arrays)) + records.append({ + "take": str(arrays["take"]), + "path": str(prediction_path.resolve()), + "sha256": sha256(prediction_path), + }) + report = { + "status": "evaluated", + "experiment_class": "preregistered_missing_input_causal_diagnostic", + "result_role": "exact_zero_alignment_max_uncertainty_input_package", + "input_condition": expected_condition, + "scope": expected_scope, + "cache_manifest": { + "path": str(manifest_path.resolve()), + "sha256": sha256(manifest_path), + }, + "coarse_checkpoint": manifest["checkpoint"], + "alignment_contract": ( + "alignment_applied=false and delta-z=0 for every hand/frame; " + "causal uncertainty evaluator maps unavailable alignment to maximum noise" + ), + "takes": records, + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + } + (output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument( + "--expected-condition", choices=("missing_depth", "missing_k"), required=True, + ) + parser.add_argument("--scope", choices=("full", "smoke"), default="full") + args = parser.parse_args() + report = build_package( + args.cache_dir, args.output_dir, args.expected_condition, args.scope, + ) + print(json.dumps({ + "status": report["status"], + "condition": report["input_condition"], + "takes": len(report["takes"]), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase5_oof_bank.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..3199c0ded583d5c1ea631b3681edadbb755d4337 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase5_oof_bank.py @@ -0,0 +1,525 @@ +#!/usr/bin/env python3 +"""Build a resume-safe group-held-out coarse prediction bank for Phase 5.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.alignment_calibration import projected_hand_scale_px +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +BANK_VERSION = 2 +SIDES = ("left", "right") +FRAME_ARRAYS = ( + "clip_index", + "frame_id", + "frame_valid", + "K_resized", + "K_raw", + "rgb_available", + "depth_available", + "K_available", + "pred_rotation_matrices", + "pred_shape", + "pred_wrist_translation", + "pred_joints_camera", + "pred_vertices_camera", + "pred_direct_2d_px", + "pred_joints_raw_px", + "pred_vertices_raw_px", + "pred_surface_depth_m", + "observed_surface_depth_m", + "observed_surface_xyz_m", + "surface_visible", + "surface_sample_valid", + "surface_local_discontinuity_m", + "silhouette_packed", + "silhouette_overlap_fraction", + "predicted_depth_order", + "alignment_delta_z_m", + "alignment_applied", + "alignment_valid_support_count", + "alignment_projected_support_count", + "alignment_inlier_ratio", + "alignment_residual_scale_m", + "alignment_valid_fraction", + "alignment_foreground_fraction", + "alignment_background_fraction", + "alignment_depth_discontinuity_m", + "alignment_conditioning_quality", + "coarse_direct_mano_consistency_px", + "coarse_hand_scale_px", + "coarse_wrist_velocity_m_per_frame", + "target_rotation_matrices", + "target_pose_axis_angle", + "target_shape", + "target_wrist_translation", + "target_joints_camera", + "target_vertices_camera", + "target_2d_px", + "translation_residual_m", + "joint_annotation_valid", + "joint_element_valid", + "mano_annotation_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def take_slug(take: str) -> str: + parts = Path(take).parts + if len(parts) != 4 or parts[-1] != "cam4": + raise ValueError(f"unexpected H2O take: {take}") + return "__".join(parts) + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def resolve_fold_contract( + folds_manifest: Path, + fold_index: int, + heldout_manifest: Path, + run_provenance: Path, +) -> dict[str, Any]: + folds = json.loads(folds_manifest.read_text(encoding="utf-8")) + if ( + folds.get("version") != "phase5_subject_oof_v1" + or folds.get("status") != "frozen" + or folds.get("source_role") != "official_train" + or folds.get("official_test_used") is not False + ): + raise ValueError("invalid or unfrozen Phase 5 OOF manifest") + matches = [record for record in folds["folds"] if int(record["fold"]) == fold_index] + if len(matches) != 1: + raise ValueError(f"fold {fold_index} is not uniquely registered") + fold = matches[0] + registered_heldout = folds_manifest.parent / fold["heldout_manifest"] + if heldout_manifest.resolve() != registered_heldout.resolve(): + raise ValueError("heldout manifest path differs from registered fold") + if sha256(heldout_manifest) != fold["heldout_manifest_sha256"]: + raise ValueError("heldout manifest hash differs from registered fold") + provenance = json.loads(run_provenance.read_text(encoding="utf-8")) + train_hash = provenance.get("hashes", {}).get("train_manifest", {}).get("sha256") + if train_hash != fold["train_manifest_sha256"]: + raise ValueError("checkpoint training manifest is not the registered fold train split") + if provenance.get("git_status") not in ("", None): + raise ValueError("OOF bank requires a checkpoint trained from a clean worktree") + return {"folds": folds, "fold": fold, "provenance": provenance} + + +def validate_checkpoint_provenance( + checkpoint: dict[str, Any], + *, + config: dict[str, Any], + config_path: Path, + run_provenance_path: Path, + provenance: dict[str, Any], +) -> None: + """Bind the extraction checkpoint to its clean training run and config.""" + + extra = checkpoint.get("extra", {}) + provenance_config_hash = provenance.get("hashes", {}).get("config", {}).get("sha256") + if provenance_config_hash != sha256(config_path): + raise ValueError("extraction config hash differs from checkpoint run provenance") + if provenance.get("config") != config or extra.get("config") != config: + raise ValueError("extraction config differs from checkpoint embedded config") + if extra.get("git_commit") != provenance.get("git_commit"): + raise ValueError("checkpoint git commit differs from run provenance") + if extra.get("run_provenance_sha256") != sha256(run_provenance_path): + raise ValueError("checkpoint run provenance hash mismatch") + protocol = config.get("protocol", {}) + if extra.get("checkpoint_role") != "final" or int(checkpoint.get("step", -1)) != int( + protocol.get("max_steps", -2) + ): + raise ValueError("OOF bank requires the preregistered fixed-final checkpoint") + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def target_geometry( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + pose_axis_angle = batch["mano_pose"].reshape(*batch["mano_pose"].shape[:-1], 16, 3) + rotations = axis_angle_to_matrix(torch.nan_to_num(pose_axis_angle)) + with torch.no_grad(): + vertices, joints = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = batch["mano_annotation_valid"].bool()[..., None, None] + vertices = torch.where(valid, vertices, torch.full_like(vertices, torch.nan)) + joints = torch.where(valid, joints, torch.full_like(joints, torch.nan)) + return pose_axis_angle, rotations, vertices, joints + + +def _observed_xyz( + pixels: np.ndarray, observed_depth_m: np.ndarray, K: np.ndarray, +) -> np.ndarray: + z = observed_depth_m.astype(np.float32) + xyz = np.full((*z.shape, 3), np.nan, dtype=np.float32) + valid = np.isfinite(z) & (z > 0.0) & np.isfinite(pixels).all(axis=-1) + xyz[..., 2][valid] = z[valid] + xyz[..., 0][valid] = (pixels[..., 0][valid] - K[0, 2]) * z[valid] / K[0, 0] + xyz[..., 1][valid] = (pixels[..., 1][valid] - K[1, 2]) * z[valid] / K[1, 1] + return xyz + + +def _velocity(translation: np.ndarray, frame_ids: np.ndarray) -> np.ndarray: + output = np.zeros_like(translation, dtype=np.float32) + contiguous = frame_ids[1:] == frame_ids[:-1] + 1 + output[1:][contiguous] = translation[1:][contiguous] - translation[:-1][contiguous] + return output + + +def infer_take( + *, + root: Path, + take: str, + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + loader = DataLoader( + Subset(dataset, clip_indices), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + take_dir = root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + silhouette_hw: tuple[int, int] | None = None + for global_clip_index, batch_cpu in zip(clip_indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + target_pose, target_rotations, target_vertices, target_joints = target_geometry(batch, model) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + valid_times = int(batch["frame_valid"][0].sum()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor( + (width, height), device=device, + ) + pred_vertices = prediction["vertices_camera"][0, :valid_times].float().cpu().numpy() + pred_joints = prediction["joints_camera"][0, :valid_times].float().cpu().numpy() + frame_ids = batch["frame_id"][0, :valid_times].cpu().numpy().astype(np.int64) + surface_fields: dict[str, list[np.ndarray]] = defaultdict(list) + for time_index, frame_id in enumerate(frame_ids): + stem = f"{int(frame_id):06d}" + raw_depth_mm = cv2.imread(str(take_dir / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED) + if raw_depth_mm is None or raw_depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{stem}") + raw_depth_m, raw_depth_valid = depth_mm_to_m(raw_depth_mm) + packed_masks = [] + medians = [] + for hand in range(2): + diagnostics, samples = align_wrist_z( + pred_vertices[time_index, hand], K_raw, raw_depth_m, raw_depth_valid, + ) + if samples is None: + raise AssertionError("full-modality OOF extraction unexpectedly lacks surface samples") + if silhouette_hw is None: + silhouette_hw = samples.silhouette_hw + elif silhouette_hw != samples.silhouette_hw: + raise AssertionError("silhouette shape changed within OOF bank") + observed_xyz = _observed_xyz( + samples.projected_vertices_px, samples.observed_depth_m, K_raw, + ) + surface_fields["pred_vertices_raw_px"].append(samples.projected_vertices_px) + surface_fields["pred_surface_depth_m"].append(samples.predicted_depth_m) + surface_fields["observed_surface_depth_m"].append(samples.observed_depth_m) + surface_fields["observed_surface_xyz_m"].append(observed_xyz) + surface_fields["surface_visible"].append(samples.visible_vertex) + surface_fields["surface_sample_valid"].append(samples.sample_valid) + surface_fields["surface_local_discontinuity_m"].append(samples.local_discontinuity_m) + surface_fields["silhouette_packed"].append(samples.silhouette_packed) + for field, value in diagnostics.as_dict().items(): + surface_fields[f"alignment_{field}"].append(np.asarray(value)) + packed_masks.append(np.unpackbits( + samples.silhouette_packed, bitorder="little", + count=samples.silhouette_hw[0] * samples.silhouette_hw[1], + ).astype(bool)) + medians.append(float(np.median(samples.predicted_depth_m[samples.visible_vertex]))) + intersection = np.logical_and(packed_masks[0], packed_masks[1]).sum() + union = np.logical_or(packed_masks[0], packed_masks[1]).sum() + surface_fields["silhouette_overlap_fraction"].append( + np.asarray(intersection / max(union, 1), dtype=np.float32) + ) + surface_fields["predicted_depth_order"].append( + np.asarray(np.sign(medians[1] - medians[0]), dtype=np.int8) + ) + + mano_2d_raw, _ = project_points(pred_joints, K_raw) + direct_np = direct_2d[0, :valid_times].cpu().numpy() + raw_to_resized = np.asarray( + (width / raw_hw[1], height / raw_hw[0]), dtype=np.float32, + ) + consistency = np.linalg.norm( + direct_np - mano_2d_raw * raw_to_resized, axis=-1, + ).mean(axis=-1) + hand_scale = projected_hand_scale_px( + mano_2d_raw, source_hw=raw_hw, target_hw=(height, width), + ) + values: dict[str, np.ndarray] = { + "clip_index": np.full(valid_times, global_clip_index, dtype=np.int64), + "frame_id": frame_ids, + "frame_valid": batch["frame_valid"][0, :valid_times].cpu().numpy(), + "K_resized": batch["K"][0, :valid_times].float().cpu().numpy(), + "K_raw": np.broadcast_to(K_raw, (valid_times, 3, 3)).copy(), + "rgb_available": batch["frame_valid"][0, :valid_times].cpu().numpy(), + "depth_available": batch["depth_available"][0, :valid_times].cpu().numpy(), + "K_available": batch["K_available"][0, :valid_times].cpu().numpy(), + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0, :valid_times].float().cpu().numpy(), + "pred_shape": prediction["mano_shape"][0, :valid_times].float().cpu().numpy(), + "pred_wrist_translation": prediction["wrist_root_translation"][0, :valid_times].float().cpu().numpy(), + "pred_joints_camera": pred_joints, + "pred_vertices_camera": pred_vertices, + "pred_direct_2d_px": direct_np, + "pred_joints_raw_px": mano_2d_raw.astype(np.float32), + "coarse_direct_mano_consistency_px": consistency.astype(np.float32), + "coarse_hand_scale_px": hand_scale.astype(np.float32), + "target_rotation_matrices": target_rotations[0, :valid_times].float().cpu().numpy(), + "target_pose_axis_angle": target_pose[0, :valid_times].float().cpu().numpy(), + "target_shape": batch["mano_shape"][0, :valid_times].float().cpu().numpy(), + "target_wrist_translation": batch["wrist_root_translation"][0, :valid_times].float().cpu().numpy(), + "target_joints_camera": target_joints[0, :valid_times].float().cpu().numpy(), + "target_vertices_camera": target_vertices[0, :valid_times].float().cpu().numpy(), + "target_2d_px": batch["joint2d"][0, :valid_times].float().cpu().numpy(), + "joint_annotation_valid": batch["joint_annotation_valid"][0, :valid_times].cpu().numpy(), + "joint_element_valid": batch["joint_element_valid"][0, :valid_times].cpu().numpy(), + "mano_annotation_valid": batch["mano_annotation_valid"][0, :valid_times].cpu().numpy(), + } + values["translation_residual_m"] = ( + values["target_wrist_translation"] - values["pred_wrist_translation"] + ) + for key, hand_values in surface_fields.items(): + stacked = np.stack(hand_values) + if key not in ("silhouette_overlap_fraction", "predicted_depth_order"): + stacked = stacked.reshape(valid_times, 2, *stacked.shape[1:]) + values[key] = stacked + for key, value in values.items(): + chunks[key].append(value) + + arrays = {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + arrays["coarse_wrist_velocity_m_per_frame"] = _velocity( + arrays["pred_wrist_translation"], arrays["frame_id"], + ) + arrays["silhouette_hw"] = np.asarray(silhouette_hw, dtype=np.int32) + return arrays + + +def validate_bank_arrays( + arrays: dict[str, np.ndarray], + *, + take: str, + expected_frame_ids: list[int], + checkpoint_sha256: str, + config_sha256: str, + heldout_manifest_sha256: str, + fold_index: int, +) -> None: + missing = sorted(set(FRAME_ARRAYS) - arrays.keys()) + if missing: + raise ValueError(f"OOF bank is missing arrays: {missing}") + scalars = { + "bank_version": BANK_VERSION, + "take": take, + "checkpoint_sha256": checkpoint_sha256, + "config_sha256": config_sha256, + "heldout_manifest_sha256": heldout_manifest_sha256, + "fold_index": fold_index, + } + for key, expected in scalars.items(): + if str(arrays[key]) != str(expected): + raise ValueError(f"OOF bank scalar mismatch: {key}") + frame_ids = arrays["frame_id"].astype(np.int64).tolist() + if frame_ids != expected_frame_ids or len(frame_ids) != len(set(frame_ids)): + raise ValueError(f"OOF bank frame sequence mismatch for {take}") + for key in FRAME_ARRAYS: + if arrays[key].shape[0] != len(frame_ids): + raise ValueError(f"OOF bank time dimension mismatch: {key}") + if np.issubdtype(arrays[key].dtype, np.floating) and key.startswith("pred_"): + if not np.isfinite(arrays[key]).all(): + raise ValueError(f"non-finite coarse prediction array: {key}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--run-provenance", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--folds-manifest", type=Path, required=True) + parser.add_argument("--fold", type=int, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args() + if "test" in str(args.manifest).lower() or "val" in args.manifest.name.lower(): + parser.error("OOF bank accepts only registered official-train heldout manifests") + contract = resolve_fold_contract( + args.folds_manifest, args.fold, args.manifest, args.run_provenance, + ) + checkpoint_hash = sha256(args.checkpoint) + if checkpoint_hash != args.expected_checkpoint_sha256: + parser.error("checkpoint hash differs from the registered extraction command") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + config_hash = sha256(args.config) + heldout_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (int(config["data"]["T"]),), (int(config["data"]["stride"]),), + max_clips=args.max_clips, + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + expected_frames = { + take: [frame for index in indices for frame in dataset.clips[index].frame_ids] + for take, indices in indices_by_take.items() + } + if any(len(frames) != len(set(frames)) for frames in expected_frames.values()): + raise ValueError("OOF bank requires non-overlapping heldout inference clips") + + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + validate_checkpoint_provenance( + checkpoint, + config=config, + config_path=args.config, + run_provenance_path=args.run_provenance, + provenance=contract["provenance"], + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + records = [] + for take_index, (take, clip_indices) in enumerate(indices_by_take.items(), start=1): + output = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "heldout_manifest_sha256": heldout_hash, + "fold_index": args.fold, + } + if output.exists(): + with np.load(output, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + validate_bank_arrays(arrays, **expected) + status = "reused" + else: + arrays = infer_take( + root=args.root, take=take, dataset=dataset, clip_indices=clip_indices, + model=model, device=device, dtype=dtype, + ) + arrays.update({ + "bank_version": np.asarray(BANK_VERSION, dtype=np.int32), + "take": np.asarray(take), + "subject": np.asarray(take.split("/")[0]), + "action_family": np.asarray(take.split("/")[1]), + "side_names": np.asarray(SIDES), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "heldout_manifest_sha256": np.asarray(heldout_hash), + "fold_index": np.asarray(args.fold, dtype=np.int32), + }) + validate_bank_arrays(arrays, **expected) + save_npz_atomic(output, arrays) + status = "written" + records.append({ + "take": take, "clips": len(clip_indices), "frames": len(expected_frames[take]), + "path": str(output.resolve()), "sha256": sha256(output), "status": status, + }) + print(f"[{take_index}/{len(indices_by_take)}] {take}: {status}", flush=True) + + total_frames = sum(record["frames"] for record in records) + full_fold = args.max_clips is None + if full_fold and total_frames != int(contract["fold"]["heldout"]["frames"]): + raise ValueError("OOF bank heldout frame coverage differs from frozen fold") + report = { + "status": "complete", + "bank_version": BANK_VERSION, + "result_role": "official_train_group_heldout_oof_predictions", + "experiment_class": "preregistered_data_construction", + "official_validation_used_for_assignment": False, + "official_test_used": False, + "oracle_information_at_inference": False, + "gt_usage": "bank targets and post-hoc residual audit only", + "fold": args.fold, + "seed": int(config["seed"]), + "heldout_subject": contract["fold"]["heldout_subject"], + "folds_manifest": {"path": str(args.folds_manifest.resolve()), "sha256": sha256(args.folds_manifest)}, + "train_manifest_sha256": contract["fold"]["train_manifest_sha256"], + "heldout_manifest": {"path": str(args.manifest.resolve()), "sha256": heldout_hash}, + "leakage_audit": contract["fold"]["leakage_audit"], + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, "step": int(checkpoint["step"])}, + "run_provenance": {"path": str(args.run_provenance.resolve()), "sha256": sha256(args.run_provenance)}, + "training_git_commit": contract["provenance"]["git_commit"], + "extractor_git_commit": subprocess.run(["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, check=False).stdout.strip(), + "scope": "full_fold" if full_fold else "smoke", + "clips": len(dataset), "frames": total_frames, "takes": records, + "surface_contract": { + "location": "coarse MANO projection only", + "depth_source": "original aligned H2O metric depth", + "surface": "frontmost projected MANO vertex per 4-pixel cell", + "silhouette": "packed quarter-resolution conservative projected vertex hull", + "solver": "bounded MAD-scaled Huber IRLS; translation-z only", + "hand_scale": "projected coarse MANO joint extent in model-resized pixels", + }, + "arrays": list(FRAME_ARRAYS), + } + (args.output_dir / "bank_manifest.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "fold": args.fold, "clips": report["clips"], + "frames": report["frames"], "takes": len(records), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_adaptation_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_adaptation_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9e5cbc986e127ee1269792135884adc311eaa1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_adaptation_configs.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Build matched A1/A2 configs after strict external zero-shot is complete.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +from pathlib import Path +from typing import Any + +import yaml + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_adaptation_inputs( + selection: dict[str, Any], zero_shot_state: dict[str, Any], split: dict[str, Any], +) -> None: + if ( + selection.get("status") != "selected_external_generalist_no_h2o" + or selection.get("h2o_training_data_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("external selection is not adaptation-eligible") + if ( + zero_shot_state.get("status") != "complete" + or set(zero_shot_state.get("completed_ids", [])) != { + "h2o_strict_zero_shot_rgb_d_k", "h2o_strict_zero_shot_rgb_k", + "h2o_strict_zero_shot_rgb_only", + } + or zero_shot_state.get("official_test_used") is not False + or zero_shot_state.get("h2o_training_data_used") is not False + ): + raise ValueError("strict three-mode H2O zero-shot must complete before adaptation") + if ( + split.get("status") != "frozen_h2o_train_group_split" + or split.get("h2o_official_validation_used") is not False + or split.get("official_test_used") is not False + or split.get("recording_overlap") != [] + ): + raise ValueError("H2O train-only group split is invalid") + + +def adaptation_config( + base: dict[str, Any], selection: dict[str, Any], split: dict[str, Any], branch: str, +) -> dict[str, Any]: + config = copy.deepcopy(base) + config["name"] = f"phase7_{branch.lower()}_scale100k_s20260717" + config["experiment"] = { + "phase": 7, "branch": "h2o_adaptation", "stage": "adaptation_scale_100k", + "condition": branch, "uses_h2o_training_data": True, + "initialization_checkpoint_sha256": selection["checkpoint"]["sha256"], + "initialization_checkpoint_step": selection["checkpoint"]["step"], + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + h2o_source = { + "dataset": "H2O", "split_role": "official_train", "weight": 1.0, + "cache_manifest": split["fit"]["path"], "K_input_dropout": 0.0, + } + if branch == "A1": + sources = [h2o_source] + elif branch == "A2": + source_lookup = { + str(source["dataset"]).upper(): copy.deepcopy(source) + for source in base["data"]["sources"] + } + if set(source_lookup) != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("winning external config is not the E40 three-source mixture") + h2o_source["weight"] = 0.5 + replay_weights = {"HOT3D": 0.2, "HOI4D": 0.2, "ARCTIC": 0.1} + sources = [h2o_source] + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + source = source_lookup[dataset] + source["weight"] = replay_weights[dataset] + source["split_role"] = "external_train" + sources.append(source) + else: + raise ValueError(f"unknown adaptation condition: {branch}") + config["data"]["sources"] = sources + config["data"]["validation_sources"] = [{ + "dataset": "H2O", "split_role": "train_group_heldout", + "cache_manifest": split["heldout"]["path"], "K_input_dropout": 0.0, + }] + config["model"]["modality_dropout_prob"] = 0.0 + config["model"]["dinov3_trainable_last_blocks"] = 0 + return config + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-selection", type=Path, required=True) + parser.add_argument("--zero-shot-state", type=Path, required=True) + parser.add_argument("--h2o-train-split", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + selection = json.loads(args.external_selection.read_text(encoding="utf-8")) + zero_shot = json.loads(args.zero_shot_state.read_text(encoding="utf-8")) + split = json.loads(args.h2o_train_split.read_text(encoding="utf-8")) + validate_adaptation_inputs(selection, zero_shot, split) + base_path = Path(selection["config"]["path"]) + if sha256(base_path) != selection["config"]["sha256"]: + parser.error("selected external config hash mismatch") + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + args.output_dir.mkdir(parents=True) + outputs = {} + for branch in ("A1", "A2"): + config = adaptation_config(base, selection, split, branch) + output = args.output_dir / f"phase7_{branch.lower()}_scale100k_s20260717.yaml" + output.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + outputs[branch] = {"path": str(output.resolve()), "sha256": sha256(output)} + record = { + "status": "adaptation_configs_frozen", "configs": outputs, + "external_selection": { + "path": str(args.external_selection.resolve()), "sha256": sha256(args.external_selection), + }, + "strict_zero_shot_state": { + "path": str(args.zero_shot_state.resolve()), "sha256": sha256(args.zero_shot_state), + }, + "h2o_train_split": { + "path": str(args.h2o_train_split.resolve()), "sha256": sha256(args.h2o_train_split), + }, + "h2o_official_validation_used_for_selection": False, "official_test_used": False, + } + (args.output_dir / "freeze.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_arctic_manifests.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_arctic_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..0dee727076139bcc1bfab8100719f0369d8ff69d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_arctic_manifests.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Build ARCTIC P2 train/val manifests without reading the P2 test list.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_p2_train_val_without_test(path: Path) -> dict[str, list[str]]: + lines: list[str] = [] + saw_test_key = False + with path.open("r", encoding="utf-8") as handle: + for line in handle: + if line.lstrip().startswith('"test"'): + saw_test_key = True + break + lines.append(line) + if not saw_test_key: + raise ValueError("protocol does not contain a test boundary") + prefix = "".join(lines).rstrip() + if prefix.endswith(","): + prefix = prefix[:-1] + record = json.loads(prefix + "\n}\n") + if set(record) != {"train", "val"}: + raise ValueError(f"expected only train/val before test boundary, got {set(record)}") + return record + + +def sequence_rows( + data_root: Path, sequence: str, split: str, clip_length: int, window_step: int, +) -> tuple[list[dict[str, Any]], list[str]]: + subject, take = sequence.split("/", 1) + mano_path = data_root / "raw_seqs" / subject / f"{take}.mano.npy" + camera_path = data_root / "raw_seqs" / subject / f"{take}.egocam.dist.npy" + image_dir = data_root / "cropped_images" / subject / take / "0" + missing = [str(path) for path in (mano_path, camera_path, image_dir) if not path.exists()] + if missing: + return [], missing + mano = np.load(mano_path, allow_pickle=True).item() + frame_count = int(len(mano["right"]["rot"])) + if frame_count != int(len(mano["left"]["rot"])): + raise ValueError(f"left/right frame count differs for {sequence}") + images = sorted(image_dir.glob("*.jpg")) + if len(images) != frame_count: + return [], [f"{sequence}: image count {len(images)} != MANO frames {frame_count}"] + rows = [] + for first in range(1, frame_count - clip_length + 2, window_step): + frame_ids = list(range(first, first + clip_length)) + rows.append({ + "dataset_id": "ARCTIC", + "protocol": "P2", + "split_role": f"arctic_p2_{split}", + "subject_id": subject, + "physical_recording_id": sequence, + "group_key": f"ARCTIC/{subject}/{sequence}", + "camera_id": "ego_view_0_rectified", + "frame_ids_1based": frame_ids, + "array_indices_0based": [value - 1 for value in frame_ids], + "image_paths": [str((image_dir / f"{value:05d}.jpg").resolve()) for value in frame_ids], + "mano_path": str(mano_path.resolve()), + "camera_path": str(camera_path.resolve()), + "depth_input_available": False, + "official_test_used": False, + }) + return rows, [] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--protocol", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--window-step", type=int, default=8) + parser.add_argument("--allow-documented-missing-sequence-exclusions", action="store_true") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + split = read_p2_train_val_without_test(args.protocol) + manifests = {} + missing: dict[str, list[str]] = {} + split_subjects: dict[str, set[str]] = {} + for role in ("train", "val"): + rows = [] + for sequence in split[role]: + sequence_values, absent = sequence_rows( + args.data_root, sequence, role, args.clip_length, args.window_step, + ) + rows.extend(sequence_values) + if absent: + missing[sequence] = absent + path = args.output_dir / f"arctic_p2_{role}_t{args.clip_length}.jsonl" + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + subjects = {row["subject_id"] for row in rows} + split_subjects[role] = subjects + manifests[role] = { + "path": str(path.resolve()), "sha256": sha256(path), + "clips": len(rows), "sequences": len({row["physical_recording_id"] for row in rows}), + "subjects": sorted(subjects), + } + overlap = sorted(split_subjects["train"] & split_subjects["val"]) + usable = not overlap and all(value["clips"] for value in manifests.values()) + status = ( + "passed" if usable and not missing else + "passed_with_documented_exclusions" + if usable and args.allow_documented_missing_sequence_exclusions else + "failed" + ) + report = { + "version": "phase7_arctic_p2_manifest_v1", + "status": status, + "protocol_path": str(args.protocol.resolve()), + "protocol_sha256": sha256(args.protocol), + "test_boundary_contract": "reader stops on the P2 test key before reading any test identity", + "clip_length": args.clip_length, "window_step": args.window_step, + "manifests": manifests, + "train_val_subject_overlap": overlap, + "missing_assets": missing, + "missing_sequence_policy": ( + "exclude entire physical recording from P2 train" + if args.allow_documented_missing_sequence_exclusions else "strict failure" + ), + "official_test_used": False, + } + (args.output_dir / "manifest_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not status.startswith("passed"): + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_continuation_manifest.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_continuation_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5feb4a5390224c6a49a11bd3846c9c91d88ea8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_continuation_manifest.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Bind frozen 50k/100k external evaluations for final checkpoint selection.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from scripts.build_phase7_scale_eval_queue import input_mode + + +DATASETS = ("HOT3D", "HOI4D", "ARCTIC") + + +def build_manifest(evaluation_root: Path, condition: str, steps: tuple[int, ...]) -> dict: + evaluations = [] + for step in steps: + for dataset in DATASETS: + mode = input_mode(condition, dataset) + path = ( + evaluation_root + / f"{condition.lower()}_scale_step{step}_{dataset.lower()}_heldout2048_{mode}" + / "evaluation.json" + ).resolve() + if not path.is_file(): + raise ValueError(f"continuation evaluation missing: {path}") + report = json.loads(path.read_text(encoding="utf-8")) + if int(report.get("checkpoint_step", -1)) != step: + raise ValueError(f"continuation evaluation step mismatch: {path}") + evaluations.append({ + "candidate": f"{condition}_step{step}", "dataset": dataset, + "path": str(path), + }) + return { + "schema_version": "phase7_external_continuation_selection_v1", + "selection_split": "external_heldout_only", "datasets": list(DATASETS), + "condition": condition, "candidate_steps": list(steps), + "h2o_training_data_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--condition", default="E40", choices=("E40", "E70", "E100")) + parser.add_argument("--steps", type=int, nargs="+", default=(50000, 100000)) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + manifest = build_manifest(args.evaluation_root, args.condition, tuple(args.steps)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + print(json.dumps(manifest, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_h2o_zero_shot_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_h2o_zero_shot_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..75fc0a82c687ff6af3ff04114659af6756484fe7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_h2o_zero_shot_queue.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Build the hash-bound three-mode strict H2O zero-shot queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_h2o_zero_shot_queue import validate_queue + + +def build_queue(freeze_path: Path, root: Path, output_root: Path) -> dict: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + status = freeze.get("status") + if status not in { + "external_generalist_frozen", "external_architecture_candidate_frozen", + }: + raise ValueError("external freeze record is incomplete") + if status == "external_architecture_candidate_frozen" and ( + freeze.get("selected_within_family") is not True + or freeze.get("overall_external_generalist_winner") is not False + ): + raise ValueError("external architecture candidate role is ambiguous") + checkpoint = freeze["checkpoint_path"] + checkpoint_sha256 = freeze["checkpoint_sha256"] + manifest = freeze["h2o_validation_manifest"]["path"] + evaluations = [{ + "id": f"h2o_strict_zero_shot_{mode}", "input_mode": mode, + "config": freeze["config_path"], "checkpoint": checkpoint, + "checkpoint_sha256": checkpoint_sha256, + "freeze_record": str(freeze_path.resolve()), "root": str(root.resolve()), + "manifest": manifest, + "output_dir": str((output_root / mode).resolve()), + "bootstrap_resamples": 2000, + } for mode in INPUT_MODES] + queue = { + "schema_version": "phase7_h2o_strict_zero_shot_queue_v1", + "purpose": "One frozen external checkpoint evaluated once in three H2O input modes", + "external_freeze_status": status, + "allowed_physical_gpus": [0, 1, 2, 3], + "official_test_used": False, "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "evaluations": evaluations, + } + validate_queue(queue) + return queue + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + queue = build_queue(args.freeze_record, args.root, args.output_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_hoi4d_manifests.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_hoi4d_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebe2622b2f7c2957b904af4295816fe440fd0c9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_hoi4d_manifests.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Build deterministic group-isolated HOI4D train/held-out clip manifests.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +SERIALS = tuple(f"ZY2021080000{index}" for index in range(1, 5)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def discover_hand_frames(root: Path) -> dict[str, dict[int, set[str]]]: + recordings: dict[str, dict[int, set[str]]] = defaultdict(lambda: defaultdict(set)) + hand_root = root / "Hand_pose" + for side in ("left", "right"): + base = hand_root / f"handpose_{side}_hand" + for directory, _, filenames in os.walk(base): + frame_names = [name for name in filenames if name.endswith(".pickle")] + if not frame_names: + continue + relative = Path(directory).relative_to(base).as_posix() + for name in frame_names: + recordings[relative][int(Path(name).stem)].add(side) + return recordings + + +def split_for_serial(serial: str, heldout_serial: str) -> str: + if serial not in SERIALS: + raise ValueError(f"unknown HOI4D serial: {serial}") + return "heldout" if serial == heldout_serial else "train" + + +def recording_assets(root: Path, recording: str) -> tuple[Path, Path, Path]: + rgb = root / "HOI4D_release" / recording / "align_rgb" / "image.mp4" + depth = ( + root / "HOI4D_release" / "HOI4D_depth_video" / recording + / "align_depth" / "depth_video.avi" + ) + serial = recording.split("/", 1)[0] + K = root / "camera" / serial / "intrin.npy" + return rgb, depth, K + + +def make_rows( + root: Path, + recordings: dict[str, dict[int, set[str]]], + heldout_serial: str, + clip_length: int, + window_step: int, +) -> tuple[dict[str, list[dict[str, Any]]], list[dict[str, str]]]: + rows: dict[str, list[dict[str, Any]]] = {"train": [], "heldout": []} + missing: list[dict[str, str]] = [] + for recording in sorted(recordings): + rgb, depth, K = recording_assets(root, recording) + absent = [str(path) for path in (rgb, depth, K) if not path.is_file()] + if absent: + missing.append({"recording": recording, "missing": ";".join(absent)}) + continue + frames = recordings[recording] + available = sorted(frames) + if not available: + continue + serial, subject = recording.split("/")[:2] + split = split_for_serial(serial, heldout_serial) + frame_set = set(available) + for start in range(available[0], available[-1] + 1, window_step): + ids = list(range(start, start + clip_length)) + if not all(frame in frame_set for frame in ids): + continue + rows[split].append({ + "dataset_id": "HOI4D", + "split_role": f"external_{split}_group_split", + "serial_id": serial, + "subject_id": subject, + "physical_recording_id": recording, + "group_key": f"HOI4D/{subject}/{recording}", + "camera_id": serial, + "fps": 15.0, + "frame_ids": ids, + "timestamps_seconds": [frame / 15.0 for frame in ids], + "hand_sides": [sorted(frames[frame]) for frame in ids], + "rgb_video": str(rgb.resolve()), + "depth_video": str(depth.resolve()), + "K_path": str(K.resolve()), + "official_test_used": False, + }) + return rows, missing + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--heldout-serial", choices=SERIALS, default=SERIALS[-1]) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--window-step", type=int, default=8) + parser.add_argument("--allow-documented-missing-asset-exclusions", action="store_true") + args = parser.parse_args() + if args.clip_length <= 0 or args.window_step <= 0: + parser.error("clip length and window step must be positive") + args.output_dir.mkdir(parents=True, exist_ok=False) + recordings = discover_hand_frames(args.root) + rows, missing = make_rows( + args.root, recordings, args.heldout_serial, + args.clip_length, args.window_step, + ) + manifests = {} + for split, values in rows.items(): + path = args.output_dir / f"hoi4d_{split}_t{args.clip_length}.jsonl" + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in values), + encoding="utf-8", + ) + manifests[split] = { + "path": str(path.resolve()), "sha256": sha256(path), + "clips": len(values), + "subjects": sorted({row["subject_id"] for row in values}), + "recordings": len({row["physical_recording_id"] for row in values}), + "hand_frames": { + side: sum(side in sides for row in values for sides in row["hand_sides"]) + for side in ("left", "right") + }, + } + usable = all(rows.values()) + exclusions_allowed = bool(args.allow_documented_missing_asset_exclusions) + report = { + "version": "phase7_hoi4d_group_split_v1", + "status": ( + "passed" if usable and not missing else + "passed_with_documented_exclusions" if usable and exclusions_allowed else + "failed" + ), + "heldout_policy": "entire device/subject serial held out", + "heldout_serial": args.heldout_serial, + "grouping": "dataset, subject, complete physical recording", + "clip_length": args.clip_length, + "window_step": args.window_step, + "manifests": manifests, + "missing_assets": missing, + "missing_asset_recordings": len(missing), + "missing_asset_policy": ( + "excluded from both training and held-out evaluation; retained in audit" + if exclusions_allowed else "strict failure" + ), + "official_test_used": False, + } + (args.output_dir / "manifest_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not report["status"].startswith("passed"): + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_hot3d_manifests.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_hot3d_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6baac33d76e1336f6bdc82c4a417627d8c123c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_hot3d_manifests.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Build GT-only HOT3D recording-group manifests through official mask APIs.""" + +from __future__ import annotations + +import argparse +import bisect +from collections import Counter +import hashlib +import json +from pathlib import Path +import subprocess +import sys +from typing import Iterable + +from foundation_hand.data.hot3d_dataset import load_hot3d_api + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def participant_split(participants: Iterable[str]) -> tuple[set[str], set[str]]: + ordered = sorted(set(participants)) + if len(ordered) < 4: + raise ValueError("HOT3D participant split requires at least four GT participants") + heldout = {participant for index, participant in enumerate(ordered) if index % 4 == 3} + return set(ordered) - heldout, heldout + + +def contiguous_clips( + timestamps_ns: Iterable[int], + length: int, + max_gap_ns: int = 100_000_000, +) -> list[list[int]]: + timestamps = sorted(set(int(value) for value in timestamps_ns)) + runs: list[list[int]] = [] + current: list[int] = [] + for timestamp in timestamps: + if current and timestamp - current[-1] > max_gap_ns: + runs.append(current) + current = [] + current.append(timestamp) + if current: + runs.append(current) + clips: list[list[int]] = [] + for run in runs: + clips.extend(run[start : start + length] for start in range(0, len(run), length) if len(run[start : start + length]) == length) + return clips + + +def nearest_timestamp( + timestamp_ns: int, + reference_ns: list[int], + maximum_delta_ns: int, +) -> int | None: + position = bisect.bisect_left(reference_ns, int(timestamp_ns)) + candidates = reference_ns[max(0, position - 1) : position + 1] + if not candidates: + return None + nearest = min(candidates, key=lambda value: abs(value - timestamp_ns)) + return nearest if abs(nearest - timestamp_ns) <= maximum_delta_ns else None + + +def write_jsonl(path: Path, rows: list[dict]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--max-recordings", type=int) + parser.add_argument("--max-clips-per-recording-stream", type=int) + args = parser.parse_args() + if args.clip_length < 1: + parser.error("--clip-length must be positive") + + api = load_hot3d_api(args.toolkit_root) + source = args.toolkit_root.resolve() / "hot3d" + if str(source) not in sys.path: + sys.path.insert(0, str(source)) + from data_loaders.loader_hand_poses import load_hand_poses + from data_loaders.loader_masks import combine_mask_data, load_mask_data + + metadata_paths = sorted(args.root.glob("P*/metadata.json")) + metadata: list[tuple[Path, dict]] = [] + no_gt_count = 0 + for path in metadata_paths: + record = json.loads(path.read_text(encoding="utf-8")) + if record.get("have_hand_object_pose_gt") is not True: + no_gt_count += 1 + continue + metadata.append((path.parent, record)) + if args.max_recordings is not None: + metadata = metadata[: args.max_recordings] + participants = [record["participant_id"] for _, record in metadata] + train_participants, heldout_participants = participant_split(participants) + rows: dict[str, list[dict]] = {"train": [], "heldout": []} + skipped: Counter[str] = Counter() + counts: Counter[str] = Counter() + required_masks = ( + "mask_hand_visible.csv", + "mask_headset_pose_available.csv", + "mask_good_exposure.csv", + "mask_qa_pass.csv", + ) + for recording_dir, record in metadata: + missing = [ + name for name in required_masks + if not (recording_dir / "masks" / name).is_file() + ] + if missing: + skipped["missing_masks"] += 1 + continue + masks = [ + load_mask_data(str(recording_dir / "masks" / name)) + for name in required_masks + ] + combined = combine_mask_data(masks, "and") + hand_poses = load_hand_poses( + str(recording_dir / "mano_hand_pose_trajectory.jsonl") + ) + hand_timestamps = sorted(hand_poses) + streams = ["214-1"] if record["headset"] == "Aria" else ["1201-1", "1201-2"] + split = "train" if record["participant_id"] in train_participants else "heldout" + for stream_id in streams: + stream_mask = combined.data.get(stream_id) + if stream_mask is None: + skipped[f"missing_stream_{stream_id}"] += 1 + continue + timestamp_to_pose = { + timestamp: nearest_timestamp(timestamp, hand_timestamps, 20_000_000) + for timestamp, valid in stream_mask.items() if valid + } + timestamp_to_pose = { + timestamp: pose_timestamp + for timestamp, pose_timestamp in timestamp_to_pose.items() + if pose_timestamp is not None + } + clips = contiguous_clips(timestamp_to_pose, args.clip_length) + if args.max_clips_per_recording_stream is not None: + clips = clips[: args.max_clips_per_recording_stream] + for clip_index, timestamps in enumerate(clips): + rows[split].append({ + "dataset": "HOT3D", + "split": split, + "participant_id": record["participant_id"], + "recording_id": record["recording_name"], + "physical_recording_id": record["recording_name"], + "headset": record["headset"], + "stream_id": stream_id, + "clip_index_in_stream": clip_index, + "timestamps_ns": timestamps, + "hand_pose_timestamp_ns": [timestamp_to_pose[value] for value in timestamps], + "hand_count": [ + len(hand_poses[timestamp_to_pose[value]].poses) + for value in timestamps + ], + "have_hand_object_pose_gt": True, + "depth_input_available": False, + "K_input_dropout": 0.3, + "group_key": f"HOT3D/{record['participant_id']}/{record['recording_name']}", + }) + counts[f"{split}/{record['headset']}/{stream_id}"] += len(clips) + + args.output_dir.mkdir(parents=True, exist_ok=True) + paths = {} + for split, split_rows in rows.items(): + path = args.output_dir / f"hot3d_{split}_t{args.clip_length}.jsonl" + write_jsonl(path, split_rows) + paths[split] = {"path": str(path.resolve()), "sha256": sha256(path), "clips": len(split_rows)} + toolkit_commit = subprocess.run( + ["git", "-C", str(args.toolkit_root), "rev-parse", "HEAD"], + text=True, stdout=subprocess.PIPE, check=True, + ).stdout.strip() + audit = { + "status": "built", + "official_test_used": False, + "gt_metadata_records": len(metadata), + "excluded_no_gt_metadata_records": no_gt_count, + "train_participants": sorted(train_participants), + "heldout_participants": sorted(heldout_participants), + "participant_overlap": sorted(train_participants & heldout_participants), + "counts": dict(sorted(counts.items())), + "skipped": dict(sorted(skipped.items())), + "clip_length": args.clip_length, + "required_masks": list(required_masks), + "pose_contract": "nearest official MANO timestamp within 20ms; one or two hands allowed", + "toolkit": {"path": str(args.toolkit_root.resolve()), "git_commit": toolkit_commit}, + "manifests": paths, + } + output = args.output_dir / "hot3d_manifest_audit.json" + output.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") + print(json.dumps(audit, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_scale_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_scale_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..104816c1155e66759d9276dae8052af0f372be82 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase7_scale_eval_queue.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Build a hash-bound formal evaluation queue for a matched scale step.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.run_phase7_heldout_cache_queue import output_complete + + +CONDITIONS = ("E40", "E70", "E100") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def stage_suffix(step: int) -> str: + suffixes = {2000: "2k", 10000: "10k", 50000: "50k", 100000: "100k"} + try: + return suffixes[step] + except KeyError as error: + raise ValueError(f"unsupported formal matched step: {step}") from error + + +def read_marker(run_root: Path, condition: str, step: int) -> dict[str, Any]: + marker_path = run_root / ".phase7_queue" / f"{condition}_scale_{stage_suffix(step)}.json" + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker["checkpoint"]) + config = Path(marker["config"]) + if ( + marker.get("status") != "complete" + or int(marker.get("completed_step", -1)) != step + or marker.get("official_test_used") is not False + or marker.get("h2o_training_data_used") is not False + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or not config.is_file() + or marker.get("config_sha256") != sha256(config) + ): + raise ValueError(f"scale marker failed frozen contract: {marker_path}") + return marker + + +def input_mode(condition: str, dataset: str) -> str: + if dataset == "HOI4D" and condition != "E100": + return "rgb_d_k" + return "rgb_k" + + +def build_queue( + plan: dict[str, Any], run_roots: dict[str, Path], step: int, + evaluation_root: Path, conditions: tuple[str, ...] = CONDITIONS, +) -> dict[str, Any]: + if plan.get("official_test_used") is not False or plan.get("h2o_used") is not False: + raise ValueError("formal cache plan is not external-only") + sources = {item["dataset"]: item for item in plan["sources"]} + if set(sources) != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("formal cache plan lacks the complete dataset grid") + for item in sources.values(): + if not output_complete(item): + raise ValueError(f"formal held-out cache is incomplete: {item['dataset']}") + markers = { + condition: read_marker(run_roots[condition], condition, step) + for condition in conditions + } + evaluations = [] + for condition in conditions: + marker = markers[condition] + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + source = sources[dataset] + mode = input_mode(condition, dataset) + evaluations.append({ + "id": f"{condition}_{dataset}_scale_step{step}_{mode}", + "config": marker["config"], + "checkpoint": marker["checkpoint"], + "checkpoint_sha256": marker["checkpoint_sha256"], + "cache_manifest": str( + (Path(source["output_dir"]) / "cache_manifest.jsonl").resolve() + ), + "input_mode": mode, + "output_dir": str(( + evaluation_root + / f"{condition.lower()}_scale_step{step}_{dataset.lower()}_heldout2048_{mode}" + ).resolve()), + "bootstrap_resamples": 2000, + }) + return { + "schema_version": "phase7_external_eval_queue_v1", + "purpose": f"Formal matched external scale evaluation at step {step}", + "matched_step": step, "selection_split": "external_heldout_only", + "official_test_used": False, "h2o_training_data_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--formal-cache-plan", type=Path, required=True) + parser.add_argument( + "--step", type=int, choices=(2000, 10000, 50000, 100000), required=True, + ) + parser.add_argument( + "--conditions", nargs="+", choices=CONDITIONS, default=list(CONDITIONS), + ) + parser.add_argument("--e40-run", type=Path, required=True) + parser.add_argument("--e70-run", type=Path, required=True) + parser.add_argument("--e100-run", type=Path, required=True) + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output queue already exists") + plan = json.loads(args.formal_cache_plan.read_text(encoding="utf-8")) + queue = build_queue( + plan, {"E40": args.e40_run, "E70": args.e70_run, "E100": args.e100_run}, + args.step, args.evaluation_root, tuple(args.conditions), + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_adaptation_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_adaptation_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..73840a2414c7276121f0302064f82599ffb40c11 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_adaptation_eval_queue.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-mode H2O train-heldout adaptation evaluation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +HELDOUT = Path( + "/home/jiasen/foundation_hand/artifacts/phase7/manifests/" + "h2o_train_group_cv_v1/train_group_heldout.jsonl" +) +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, + condition: str, + step: int, + config: Path, + config_sha256: str, + checkpoint: Path, + checkpoint_sha256: str, + output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not condition or any(character.isspace() for character in condition): + raise ValueError("condition must be a nonempty whitespace-free identifier") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap_resamples must be positive") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + if not HELDOUT.is_file(): + raise ValueError("frozen H2O train-group-heldout manifest is missing") + evaluations = [ + { + "id": f"{condition}_step{step}_{input_mode}", + "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(HELDOUT.resolve()), + "cache_manifest_sha256": sha256(HELDOUT), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str( + (output_root / f"{condition}_step{step}_{input_mode}").resolve() + ), + } + for input_mode in INPUT_MODES + ] + return { + "schema_version": "phase8_adaptation_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "Three-mode H2O train-group-heldout selection evaluation.", + "selection_split": "h2o_train_group_heldout_only", + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, + step=args.step, + config=args.config, + config_sha256=args.config_sha256, + checkpoint=args.checkpoint, + checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_adaptation_forgetting_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_adaptation_forgetting_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8f458e2c336aefbba9a75f8127f54f089f1f6f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_adaptation_forgetting_queue.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Build hash-bound external forgetting diagnostics for an H2O-adapted model.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +DOMAINS = { + "HOT3D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), + "HOI4D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_d_k", + ), + "ARCTIC": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "arctic_val2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, + condition: str, + step: int, + config: Path, + config_sha256: str, + checkpoint: Path, + checkpoint_sha256: str, + output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not condition or any(character.isspace() for character in condition): + raise ValueError("condition must be a nonempty whitespace-free identifier") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap_resamples must be positive") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + evaluations = [] + for dataset, (manifest_string, input_mode) in DOMAINS.items(): + manifest = Path(manifest_string) + if not manifest.is_file() or "h2o" in str(manifest).lower(): + raise ValueError(f"external forgetting manifest is invalid: {manifest}") + evaluations.append({ + "id": f"{condition}_step{step}_{dataset}_{input_mode}", + "dataset": dataset, + "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str( + (output_root / f"{condition}_step{step}" / f"{dataset}_{input_mode}").resolve() + ), + }) + return { + "schema_version": "phase8_adaptation_forgetting_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "External held-out forgetting diagnostic only; never used for H2O selection.", + "evaluation_split": "external_heldout_forgetting_diagnostic_only", + "selection_use": False, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, + config=args.config, config_sha256=args.config_sha256, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_egodexter_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_egodexter_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..e2873ce3d5a27694cfbb51342326605472cc5f09 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_egodexter_queue.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Build one frozen model's six-condition EgoDexter zero-shot queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_egodexter_zero_shot import sha256, validate_freeze_record + + +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") +INFERENCE_MODES = ("offline", "causal") + + +def build_queue( + freeze_path: Path, model_id: str, root: Path, output_root: Path, +) -> dict[str, Any]: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + models = {item["id"]: item for item in freeze.get("models", [])} + if model_id not in models: + raise ValueError("model is absent from the final freeze") + model = models[model_id] + checkpoint = Path(model["checkpoint"]) + if not checkpoint.is_file() or sha256(checkpoint) != model["checkpoint_sha256"]: + raise ValueError("frozen checkpoint is missing or SHA256 differs") + if not root.is_dir() or not (root / "data").is_dir(): + raise ValueError("EgoDexter root is invalid") + evaluations = [] + for inference_mode in INFERENCE_MODES: + config = Path(model["inference_configs"][inference_mode]["path"]) + validate_freeze_record( + freeze, model_id, model["checkpoint_sha256"], config, inference_mode, + ) + for input_mode in INPUT_MODES: + evaluations.append({ + "id": f"{model_id}_{inference_mode}_{input_mode}", + "model_id": model_id, + "freeze_record": str(freeze_path.resolve()), + "config": str(config.resolve()), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": model["checkpoint_sha256"], + "root": str(root.resolve()), + "input_mode": input_mode, + "inference_mode": inference_mode, + "window": 8, + "output_dir": str((output_root / inference_mode / input_mode).resolve()), + }) + return { + "schema_version": "phase8_egodexter_zero_shot_queue_v1", + "model_id": model_id, + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--model-id", required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + queue = build_queue(args.freeze_record, args.model_id, args.root, args.output_root) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_external_tail_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_external_tail_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..57d07512de8608b779e00ee27b66ee001473fca7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_external_tail_queue.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Build a hash-bound 100k-to200k minimum-LR external continuation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + +import yaml + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, condition: str, config_path: Path, config_sha256: str, + output_dir: Path, checkpoint: Path, checkpoint_sha256: str, + resume_step: int = 100000, end_step: int = 200000, +) -> dict[str, Any]: + if not config_path.is_file() or sha256(config_path) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("resume checkpoint is missing or SHA256 differs") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + if config.get("experiment", {}).get("branch") != "external_only": + raise ValueError("schedule tail is restricted to external-only configs") + max_steps = int(config["protocol"]["max_steps"]) + if max_steps != resume_step or not end_step > resume_step: + raise ValueError("tail requires resume_step=config max_steps < end_step") + expected_checkpoint = output_dir / f"step_{resume_step:07d}_final.pt" + if checkpoint.resolve() != expected_checkpoint.resolve(): + raise ValueError("checkpoint path is not the final artifact in output_dir") + required_caches = [] + for source in config["data"]["sources"]: + manifest = Path(source["cache_manifest"]) + report_path = manifest.parent / "cache_report.json" + if not manifest.is_file() or not report_path.is_file(): + raise ValueError(f"source cache is incomplete: {manifest}") + report = json.loads(report_path.read_text(encoding="utf-8")) + clips = report.get("clips", report.get("cached_clips")) + recorded = report.get("cache_manifest", {}) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or int(clips or -1) <= 0 + or recorded.get("sha256") != sha256(manifest) + ): + raise ValueError(f"source cache report is not hash-valid: {report_path}") + required_caches.append({ + "id": f"{source['dataset']}_{clips}", + "report": str(report_path.resolve()), + "manifest": str(manifest.resolve()), + "expected_clips": int(clips), + }) + return { + "schema_version": "phase8_external_schedule_tail_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": f"Exact-resume {condition} from {resume_step} to {end_step} at the registered minimum LR.", + "official_test_used": False, "h2o_training_data_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], + "required_caches": required_caches, + "stages": [{ + "id": f"{condition}_{end_step}_min_lr_tail", + "config": str(config_path.resolve()), + "config_sha256": config_sha256, + "output_dir": str(output_dir.resolve()), + "resume_from_step": resume_step, + "resume_checkpoint_sha256": checkpoint_sha256, + "stop_after_step": end_step, + "allow_schedule_tail": True, + }], + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--resume-step", type=int, default=100000) + parser.add_argument("--end-step", type=int, default=200000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, config_path=args.config, + config_sha256=args.config_sha256, output_dir=args.output_dir, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + resume_step=args.resume_step, end_step=args.end_step, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_h2o_adapted_validation_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_h2o_adapted_validation_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c9eec9bc1340e152be7824e02131c5ed03efc0b7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_h2o_adapted_validation_queue.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-mode formal H2O adaptation validation queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_external import sha256 +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_h2o_adapted_validation_queue import validate_queue + + +def build_queue(freeze_path: Path, root: Path, output_root: Path) -> dict[str, Any]: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + if ( + freeze.get("status") != "h2o_adaptation_candidate_frozen" + or freeze.get("selection_split") != "h2o_train_group_heldout_only" + or freeze.get("h2o_official_validation_used_for_selection") is not False + or freeze.get("h2o_training_data_used") is not True + or freeze.get("official_test_used") is not False + ): + raise ValueError("adaptation freeze record is incomplete") + checkpoint = freeze.get("checkpoint", {}) + config = freeze.get("config", {}) + manifest = freeze.get("h2o_validation_manifest", {}) + for record, label in ( + (checkpoint, "checkpoint"), (config, "config"), (manifest, "manifest"), + ): + path = Path(record.get("path", "")) + if not path.is_file() or sha256(path) != record.get("sha256"): + raise ValueError(f"frozen {label} is missing or SHA256 differs") + if Path(manifest["path"]).name != "official_val.jsonl": + raise ValueError("only canonical H2O official validation is allowed") + if set(freeze.get("frozen_h2o_input_modes", [])) != set(INPUT_MODES): + raise ValueError("adaptation freeze record does not bind all input modes") + if not root.is_dir() or not (root / "subject3").is_dir(): + raise ValueError("H2O root does not contain the canonical validation subject") + evaluations = [{ + "id": f"{freeze['winner']}_formal_{mode}", + "input_mode": mode, + "config": str(Path(config["path"]).resolve()), + "checkpoint": str(Path(checkpoint["path"]).resolve()), + "checkpoint_sha256": checkpoint["sha256"], + "freeze_record": str(freeze_path.resolve()), + "root": str(root.resolve()), + "manifest": str(Path(manifest["path"]).resolve()), + "output_dir": str((output_root / mode).resolve()), + "bootstrap_resamples": 2000, + } for mode in INPUT_MODES] + queue = { + "schema_version": "phase8_h2o_adapted_validation_queue_v1", + "purpose": "Formal validation of one train-heldout-frozen H2O adaptation candidate.", + "selection_split": "h2o_train_group_heldout_only", + "allowed_physical_gpus": [0, 1, 2, 3], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "evaluations": evaluations, + } + validate_queue(queue) + return queue + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + queue = build_queue(args.freeze_record, args.root, args.output_root) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_left_root_relative_sidecars.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_left_root_relative_sidecars.py new file mode 100644 index 0000000000000000000000000000000000000000..1613c74abf4e6474d9947f19ff38ba45a442d1aa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_left_root_relative_sidecars.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Attach target-only historical-left joint supervision to existing caches.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def left_only_target( + target: torch.Tensor, + source_valid: torch.Tensor, + translation_valid: torch.Tensor, + frame_valid: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + if target.shape[-2:] != (21, 3): + raise ValueError("target must end in [21,3]") + if source_valid.shape != target.shape[:-1]: + raise ValueError("source-valid shape differs from target") + if translation_valid.shape != target.shape[:-2]: + raise ValueError("translation-valid shape differs from target") + if frame_valid.shape != target.shape[:-3]: + raise ValueError("frame-valid shape differs from target") + valid = ( + source_valid.bool() + & translation_valid.bool()[..., None] + & frame_valid.bool()[..., None, None] + ) + valid[..., 1, :] = False + target = target.clone().masked_fill(~valid[..., None], float("nan")) + return target, valid + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--expected-source-manifest-sha256", required=True) + parser.add_argument("--expected-cache-manifest-sha256", required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--resume", action="store_true") + parser.add_argument("--torch-threads", type=int, default=0) + args = parser.parse_args() + if sha256(args.source_manifest) != args.expected_source_manifest_sha256: + parser.error("source manifest SHA256 differs") + if sha256(args.cache_manifest) != args.expected_cache_manifest_sha256: + parser.error("cache manifest SHA256 differs") + if args.torch_threads < 0: + parser.error("--torch-threads cannot be negative") + if args.torch_threads: + torch.set_num_threads(args.torch_threads) + torch.set_num_interop_threads(1) + if args.resume: + if not (args.output_dir / "sidecars").is_dir(): + parser.error("--resume requires an existing sidecars directory") + elif args.output_dir.exists(): + parser.error("output directory already exists") + if args.dataset == "HOI4D": + if args.root is None: + parser.error("HOI4D requires --root") + dataset = HOI4DClipDataset( + args.root, args.source_manifest, args.mano_root, + ) + else: + dataset = ARCTICClipDataset(args.source_manifest, args.mano_root) + rows = read_jsonl(args.cache_manifest) + args.output_dir.mkdir(parents=True, exist_ok=args.resume) + sidecars = args.output_dir / "sidecars" + sidecars.mkdir(exist_ok=args.resume) + augmented: list[dict[str, Any] | None] = [None] * len(rows) + left_hand_frames = 0 + right_joint_count = 0 + root_norm_max_mm = 0.0 + started = time.monotonic() + order = sorted( + range(len(rows)), + key=lambda position: ( + str(rows[position]["physical_recording_id"]), + int(rows[position]["source_clip_index"]), + ), + ) + for processed, position in enumerate(order, start=1): + row = rows[position] + source_index = int(row["source_clip_index"]) + path = sidecars / f"clip_{source_index:07d}.npz" + if path.is_file() and args.resume: + try: + with np.load(path, allow_pickle=False) as sidecar: + if set(sidecar.files) != { + "joint3d_root_relative", "joint3d_root_relative_valid", + }: + raise ValueError("unexpected sidecar keys") + target = torch.from_numpy(sidecar["joint3d_root_relative"]) + valid = torch.from_numpy( + sidecar["joint3d_root_relative_valid"] + ).bool() + except (OSError, ValueError, EOFError): + preserved = path.with_name( + f"{path.name}.invalid_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}" + ) + path.rename(preserved) + if not path.is_file(): + target, source_valid = dataset.source_root_relative_joint3d(source_index) + with np.load(row["cache_path"], allow_pickle=False) as cache: + translation_valid = torch.from_numpy(cache["translation_valid"]).bool() + frame_valid = torch.from_numpy(cache["frame_valid"]).bool() + target, valid = left_only_target( + target, source_valid, translation_valid, frame_valid, + ) + temporary = path.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed( + handle, + joint3d_root_relative=target.numpy(), + joint3d_root_relative_valid=valid.numpy(), + ) + temporary.replace(path) + output_row = dict(row) + output_row.update({ + "joint3d_root_relative_sidecar_path": str(path.resolve()), + "joint3d_root_relative_sidecar_sha256": sha256(path), + "joint3d_root_relative_scope": "historical_left_only", + }) + augmented[position] = output_row + left_hand_frames += int(valid[..., 0, :].any(-1).sum()) + right_joint_count += int(valid[..., 1, :].sum()) + finite_roots = valid[..., 0, 0] + if finite_roots.any(): + root_norm_max_mm = max( + root_norm_max_mm, + float(torch.linalg.vector_norm(target[..., 0, 0, :][finite_roots], dim=-1).max() * 1000.0), + ) + if processed % 500 == 0 or processed == len(order): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": processed, + "clips": len(order), + "clips_per_second": processed / max(elapsed, 1e-9), + "eta_seconds": (len(order) - processed) / max(processed / elapsed, 1e-9), + }), flush=True) + if any(row is None for row in augmented): + raise RuntimeError("augmented manifest contains missing rows") + manifest = args.output_dir / "cache_manifest.jsonl" + manifest.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in augmented), + encoding="utf-8", + ) + elapsed = time.monotonic() - started + report = { + "schema_version": "phase8_left_root_relative_sidecars_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "dataset": args.dataset, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "base_cache_manifest": {"path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest)}, + "augmented_cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "clips": len(rows), + "left_hand_frames": left_hand_frames, + "right_valid_joint_count": right_joint_count, + "root_norm_max_mm": root_norm_max_mm, + "shape_supervision_restored": False, + "vertices_supervision_restored": False, + "camera_joint3d_supervision_restored": False, + "wall_seconds": elapsed, + "clips_per_second": len(rows) / max(elapsed, 1e-9), + "bytes": sum(path.stat().st_size for path in sidecars.iterdir()), + "resume_invocation": bool(args.resume), + "torch_threads": args.torch_threads or torch.get_num_threads(), + "official_test_used": False, + } + report_path = args.output_dir / "sidecar_report.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if not left_hand_frames or right_joint_count or root_norm_max_mm >= 1e-4: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_specialist_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_specialist_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa0f9aa72435130c16fcd98a84a0963d098f45f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_specialist_eval_queue.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-domain evaluation queue for one external checkpoint.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +DOMAINS = { + "HOT3D": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_only"), + }, + "HOI4D": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_d_k", "rgb_only"), + }, + "ARCTIC": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_val2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_only"), + }, +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, condition: str, step: int, config: Path, config_sha256: str, + checkpoint: Path, checkpoint_sha256: str, output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap resamples must be positive") + evaluations = [] + for dataset, domain in DOMAINS.items(): + manifest = Path(domain["cache_manifest"]) + if not manifest.is_file(): + raise ValueError(f"held-out manifest is missing: {manifest}") + slug = dataset.lower() + for input_mode in domain["input_modes"]: + evaluations.append({ + "id": f"{condition}_step{step}_{dataset}_{input_mode}", + "dataset": dataset, + "matrix_role": "primary_matched_rgb_k" if input_mode == "rgb_k" else "input_diagnostic", + "config": str(config.resolve()), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str((output_root / f"{condition}_step{step}" / f"{slug}_{input_mode}").resolve()), + }) + return { + "schema_version": "phase8_specialist_cross_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "Frozen matched RGB-K cross-domain matrix plus RGB-only and HOI4D RGB-D-K diagnostics.", + "condition": condition, "checkpoint_step": step, + "h2o_training_data_used": False, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, + config=args.config, config_sha256=args.config_sha256, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_stage7_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_stage7_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5db2287015b04a005106f0656ae4231c42687dcb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase8_stage7_eval_queue.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Build a hash-bound Stage 7 external held-out evaluation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase8_specialist_eval_queue import sha256 + + +STAGE7_DOMAINS = { + "HOT3D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), + "HOI4D": ( + "/SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/" + "hoi4d_heldout_left_root_relative_sidecars_v1/cache_manifest.jsonl", + "rgb_d_k", + ), + "ARCTIC": ( + "/SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/" + "arctic_p2_val_left_root_relative_sidecars_v1/cache_manifest.jsonl", + "rgb_k", + ), +} + + +def build_queue( + *, condition: str, step: int, config: Path, config_sha256: str, + checkpoint: Path, checkpoint_sha256: str, output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if condition not in {"L0_sampler_only", "L1_left_root_relative"}: + raise ValueError("condition is not a frozen Stage 7 condition") + if step != 10000 or bootstrap_resamples <= 0: + raise ValueError("Stage 7 evaluation requires step10k and positive resamples") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + evaluations = [] + for dataset, (manifest_string, input_mode) in STAGE7_DOMAINS.items(): + manifest = Path(manifest_string) + if not manifest.is_file() or "h2o" in str(manifest).lower(): + raise ValueError(f"invalid Stage 7 held-out manifest: {manifest}") + evaluations.append({ + "id": f"{condition}_step10000_{dataset}_{input_mode}", + "dataset": dataset, "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, "bootstrap_resamples": bootstrap_resamples, + "output_dir": str((output_root / condition / f"{dataset}_{input_mode}").resolve()), + }) + return { + "schema_version": "phase8_stage7_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "condition": condition, "checkpoint_step": step, + "evaluation_split": "external_heldout_only", + "h2o_training_data_used": False, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, config=args.config, + config_sha256=args.config_sha256, checkpoint=args.checkpoint, + checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_final_deployment_plan.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_final_deployment_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..bd59e8112af6f89be4d8c8387647095fdb424bf8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_final_deployment_plan.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""Build the post-selection formal-validation and deployment-audit job plan.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +LENGTHS = [1, 2, 4, 8, 16, 32, 64] +ORDERING_LENGTHS = [31, 64, 257] + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def derive_causal_config(config: dict[str, Any]) -> dict[str, Any]: + result = deepcopy(config) + if result.get("model", {}).get("temporal_attention_mode") != "bidirectional": + raise ValueError("final checkpoint config is not the frozen bidirectional control") + result["model"]["temporal_attention_mode"] = "causal" + return result + + +def write_causal_config(source: Path, output: Path) -> str: + original = yaml.safe_load(source.read_text(encoding="utf-8")) + causal = derive_causal_config(original) + output.parent.mkdir(parents=True, exist_ok=True) + rendered = yaml.safe_dump(causal, sort_keys=False) + if output.exists(): + if yaml.safe_load(output.read_text(encoding="utf-8")) != causal: + raise ValueError("existing final causal config differs") + else: + temporary = output.with_suffix(".tmp") + temporary.write_text(rendered, encoding="utf-8") + temporary.replace(output) + return sha256(output) + + +def build_plan( + *, freeze_path: Path, freeze_state_path: Path, output_root: Path, + worker_state_root: Path, causal_config_path: Path, h2o_root: Path, +) -> dict[str, Any]: + state = read_json(freeze_state_path) + freeze = read_json(freeze_path) + if ( + state.get("status") != "complete" + or state.get("freeze_sha256") != sha256(freeze_path) + or freeze.get("status") != "phase9_final_unified_checkpoint_frozen" + or freeze.get("h2o_official_validation_used") is not False + or freeze.get("h2o_official_validation_used_for_selection") is not False + or freeze.get("official_test_used") is not False + ): + raise ValueError("final deployment freeze is incomplete or unbound") + checkpoint = freeze["checkpoint"] + config = freeze["config"] + validation = freeze["h2o_validation_manifest"] + training = freeze["h2o_training_manifest"] + for record, label in ( + (checkpoint, "checkpoint"), (config, "config"), + (validation, "validation manifest"), (training, "training manifest"), + ): + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"frozen final {label} differs") + causal_sha = write_causal_config(Path(config["path"]), causal_config_path) + if not h2o_root.is_dir(): + raise ValueError("canonical H2O root is missing") + common = { + "checkpoint": checkpoint["path"], + "checkpoint_sha256": checkpoint["sha256"], + "checkpoint_step": checkpoint["step"], + "config": config["path"], "config_sha256": config["sha256"], + "freeze_record": str(freeze_path.resolve()), + "freeze_record_sha256": sha256(freeze_path), + "root": str(h2o_root.resolve()), + } + jobs = [] + for gpu, mode in enumerate(INPUT_MODES): + jobs.append({ + **common, "id": f"formal_{mode}", "kind": "formal_validation", + "physical_gpu_id": gpu, "input_mode": mode, + "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output_dir": str((output_root / "formal_h2o" / mode).resolve()), + }) + jobs.append({ + **common, "id": "variable_length", "kind": "variable_length", + "physical_gpu_id": 0, "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output": str((output_root / "audits" / "variable_length.json").resolve()), + "lengths": LENGTHS, + }) + for index, frames in enumerate(ORDERING_LENGTHS, start=1): + for mode in ("offline", "causal"): + job_config = config if mode == "offline" else { + "path": str(causal_config_path.resolve()), "sha256": causal_sha, + } + jobs.append({ + **common, "id": f"{mode}_w8_{frames}", "kind": "sequence", + "physical_gpu_id": index, "mode": mode, "window": 8, + "frames": frames, "config": job_config["path"], + "config_sha256": job_config["sha256"], + "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output": str(( + output_root / "audits" / f"{mode}_w8_{frames}.json" + ).resolve()), + }) + jobs.append({ + **common, "id": "latency_vram", "kind": "profile", + "physical_gpu_id": 3, "manifest": training["path"], + "manifest_sha256": training["sha256"], + "resolution_hw": freeze["resolution_hw"], + "output": str((output_root / "audits" / "latency_vram.json").resolve()), + }) + ids = [job["id"] for job in jobs] + outputs = [job.get("output", job.get("output_dir")) for job in jobs] + if len(jobs) != 11 or len(set(ids)) != 11 or len(set(outputs)) != 11: + raise ValueError("final deployment jobs are not unique and complete") + workers = [] + for gpu in range(4): + workers.append({ + "id": f"gpu{gpu}", "physical_gpu_id": gpu, + "state": str((worker_state_root / f"gpu{gpu}_state.json").resolve()), + "job_ids": [job["id"] for job in jobs if job["physical_gpu_id"] == gpu], + }) + assigned = [identifier for worker in workers for identifier in worker["job_ids"]] + if sorted(assigned) != sorted(ids) or len(set(assigned)) != 11: + raise ValueError("final deployment worker assignment overlaps or omits jobs") + return { + "schema_version": "phase9_final_deployment_plan_v1", + "status": "frozen_ready_post_selection", + "created_utc": freeze["created_utc"], + "freeze": {"path": str(freeze_path.resolve()), "sha256": sha256(freeze_path)}, + "winner": freeze["winner"], + "selected_mechanism": freeze["selected_mechanism"], + "resolution_hw": freeze["resolution_hw"], + "shared_augmentation": freeze["shared_augmentation"], + "checkpoint": checkpoint, "config": config, + "causal_config": { + "path": str(causal_config_path.resolve()), "sha256": causal_sha, + "only_change": "model.temporal_attention_mode=causal", + }, + "jobs": jobs, "workers": workers, + "official_validation_checkpoint_count": 1, + "formal_validation_modes": list(INPUT_MODES), + "variable_lengths": LENGTHS, + "sequence_contract": { + "offline_window": 8, "causal_window": 8, + "ordering_lengths": ORDERING_LENGTHS, + }, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze", type=Path, required=True) + parser.add_argument("--freeze-state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--causal-config", type=Path, required=True) + parser.add_argument("--h2o-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + freeze_path=args.freeze, freeze_state_path=args.freeze_state, + output_root=args.output_root, worker_state_root=args.worker_state_root, + causal_config_path=args.causal_config, h2o_root=args.h2o_root, + ) + if args.output.exists(): + if read_json(args.output) != plan: + raise ValueError("existing final deployment plan differs") + else: + atomic_json(args.output, plan) + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_plan_state_v1", + "status": "complete", "plan": str(args.output.resolve()), + "plan_sha256": sha256(args.output), "job_count": len(plan["jobs"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_plan_state_v1", + "status": "failed_resumable", + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }) + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_fold_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_fold_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..e98a67efcafc5b55c0d5ea9199882374ee8b7a3c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_fold_configs.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Generate hash-bound six-fold Phase 9 unified training configurations.""" + +from __future__ import annotations + +import argparse +import copy +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path + +import yaml + +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--multifold-index", type=Path, required=True) + parser.add_argument("--base-config", type=Path, action="append", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--run-root", type=Path, required=True) + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--data-readiness-state", type=Path, required=True) + parser.add_argument("--data-finalize-plan-sha256", required=True) + parser.add_argument("--initialization-checkpoint", type=Path, required=True) + parser.add_argument("--initialization-checkpoint-sha256", required=True) + parser.add_argument( + "--refresh", action="store_true", + help="Replace preregistered configs only when no training checkpoint exists.", + ) + args = parser.parse_args() + if (args.output_dir.exists() or args.registry.exists()) and not args.refresh: + parser.error("fold config output and registry must be new") + if args.refresh and args.run_root.exists() and any(args.run_root.rglob("*.pt")): + parser.error("cannot refresh fold configs after a training checkpoint exists") + if sha256(args.initialization_checkpoint) != args.initialization_checkpoint_sha256: + parser.error("initialization checkpoint SHA256 differs") + index = json.loads(args.multifold_index.read_text(encoding="utf-8")) + if index.get("status") != "complete" or index.get("official_test_used") is not False: + parser.error("multifold index is incomplete or lacks test isolation") + folds = [str(fold["id"]) for fold in index["folds"]] + args.output_dir.mkdir(parents=True, exist_ok=args.refresh) + conditions = [] + for base_path in args.base_config: + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + mixture = str(base["experiment"]["condition"]) + for fold in folds: + config = copy.deepcopy(base) + condition = f"{mixture}_{fold}" + config["name"] = f"phase9_{condition.lower()}_s20260717" + config["experiment"]["condition"] = condition + config["experiment"]["h2o_selection_fold"] = fold + h2o = next( + source for source in config["data"]["sources"] + if str(source["dataset"]).upper() == "H2O" + ) + h2o["cache_manifest"] = str( + (args.multifold_index.parent / f"{fold}_train.jsonl").resolve() + ) + config["data"]["validation_sources"] = [{ + "dataset": "H2O", "source_id": f"H2O_{fold}_heldout", + "split_role": "train_fold_heldout", + "cache_manifest": str( + (args.multifold_index.parent / f"{fold}_heldout.jsonl").resolve() + ), + "K_input_dropout": 0.0, + }] + path = args.output_dir / f"{condition.lower()}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + errors = validate_phase9_unified_contract(config, path) + if errors: + raise ValueError(f"invalid generated fold config {path}: {'; '.join(errors)}") + max_steps = int(config["protocol"]["max_steps"]) + conditions.append({ + "condition": condition, + "mixture": mixture, + "h2o_selection_fold": fold, + "config": str(path.resolve()), "config_sha256": sha256(path), + "initialization_checkpoint": str(args.initialization_checkpoint.resolve()), + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "output_dir": str((args.run_root / condition.lower()).resolve()), + "log_dir": str((args.run_root.parent / "queues" / "folds" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"scale{max_steps}", "stop_after_step": max_steps}, + ], + }) + registry = { + "schema_version": "phase9_h2o_multifold_training_queue_v1", + "status": "frozen_before_fold_training", + "created_utc": datetime.now(timezone.utc).isoformat(), + "multifold_index": { + "path": str(args.multifold_index.resolve()), + "sha256": sha256(args.multifold_index), + }, + "data_readiness_state": str(args.data_readiness_state.resolve()), + "data_finalize_plan_sha256": args.data_finalize_plan_sha256, + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "allowed_physical_gpus": [0, 1, 2, 3], + "prohibited_physical_gpus": [4, 5], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "conditions": conditions, + "shards": { + str(shard): [ + condition["condition"] for index, condition in enumerate(conditions) + if index % 3 == shard + ] + for shard in range(3) + }, + } + args.registry.parent.mkdir(parents=True, exist_ok=True) + args.registry.write_text(json.dumps(registry, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "registry": str(args.registry.resolve()), "sha256": sha256(args.registry), + "conditions": len(conditions), "shards": registry["shards"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_h2o_multifold.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_h2o_multifold.py new file mode 100644 index 0000000000000000000000000000000000000000..89dc683c2a03af0cb1fa1de79ebed7e7d3cf24bb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_h2o_multifold.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Build deterministic H2O official-train-only subject and family folds.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.audit_phase9_source_coverage import quantiles + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def family(row: dict[str, Any]) -> str: + parts = str(row["physical_recording_id"]).split("/") + if len(parts) < 2 or parts[1][:1] not in {"h", "k", "o"}: + raise ValueError("H2O recording lacks h/k/o family") + return parts[1][:1] + + +def fold_definitions(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + subjects = sorted({str(row["subject_id"]) for row in rows}) + families = sorted({family(row) for row in rows}) + if subjects != ["subject1", "subject2", "subject3"] or families != ["h", "k", "o"]: + raise ValueError("unexpected H2O official-train subjects or families") + definitions = [ + {"id": f"loso_{subject}", "axis": "subject", "heldout_value": subject} + for subject in subjects + ] + definitions.extend( + {"id": f"lofamily_{value}", "axis": "family", "heldout_value": value} + for value in families + ) + return definitions + + +def split_rows( + rows: list[dict[str, Any]], definition: dict[str, Any], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + if definition["axis"] == "subject": + heldout = [row for row in rows if row["subject_id"] == definition["heldout_value"]] + else: + heldout = [row for row in rows if family(row) == definition["heldout_value"]] + heldout_groups = {row["physical_recording_id"] for row in heldout} + train = [row for row in rows if row["physical_recording_id"] not in heldout_groups] + train_groups = {row["physical_recording_id"] for row in train} + if not train or not heldout or train_groups & heldout_groups: + raise ValueError("H2O fold is empty or leaks a physical recording") + if len(train) + len(heldout) != len(rows): + raise ValueError("H2O fold does not partition the cache") + return train, heldout + + +def numeric_stats(rows: list[dict[str, Any]]) -> dict[str, Any]: + side_frames = [0, 0] + hand_sizes: list[float] = [] + depths: list[float] = [] + for row in rows: + with np.load(row["cache_path"], allow_pickle=False) as archive: + valid_frame = archive["frame_valid"].astype(bool) + translation_valid = archive["translation_valid"].astype(bool) + translation = archive["wrist_root_translation"] + joint_valid = archive["joint2d_valid"].astype(bool) + joints = archive["joint2d"] + image_hw = archive["image_hw"] + height, width = int(image_hw[0]), int(image_hw[1]) + for time_index in np.flatnonzero(valid_frame): + for side in range(2): + if not translation_valid[time_index, side]: + continue + side_frames[side] += 1 + depths.append(float(translation[time_index, side, 2])) + points = joints[time_index, side] + valid = joint_valid[time_index, side] & np.isfinite(points).all(axis=-1) + valid &= ( + (points[:, 0] >= 0) & (points[:, 0] < width) + & (points[:, 1] >= 0) & (points[:, 1] < height) + ) + if valid.any(): + extent = points[valid].max(axis=0) - points[valid].min(axis=0) + hand_sizes.append(float(extent.max())) + return { + "left_hand_frames": side_frames[0], "right_hand_frames": side_frames[1], + "wrist_depth_m": quantiles(depths), + "projected_hand_size_px": quantiles(hand_sizes), + "family_clips": dict(sorted(Counter(family(row) for row in rows).items())), + } + + +def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + temporary.replace(path) + + +def build( + cache_manifest: Path, cache_report: Path, output_dir: Path, +) -> dict[str, Any]: + report = json.loads(cache_report.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" or report.get("dataset") != "H2O" + or report.get("split_role") != "official_train" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest) + ): + raise ValueError("H2O cache report is not an isolated official-train cache") + rows = [ + json.loads(line) for line in cache_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if len(rows) != 7000 or {row.get("dataset_id") for row in rows} != {"H2O"}: + raise ValueError("H2O multifold requires the canonical 7,000-clip cache") + output_dir.mkdir(parents=True, exist_ok=False) + folds = [] + for definition in fold_definitions(rows): + train, heldout = split_rows(rows, definition) + train_path = output_dir / f"{definition['id']}_train.jsonl" + heldout_path = output_dir / f"{definition['id']}_heldout.jsonl" + write_jsonl(train_path, train) + write_jsonl(heldout_path, heldout) + folds.append({ + **definition, + "train": {"path": str(train_path.resolve()), "sha256": sha256(train_path), + "clips": len(train), "recordings": len({row['physical_recording_id'] for row in train}), + **numeric_stats(train)}, + "heldout": {"path": str(heldout_path.resolve()), "sha256": sha256(heldout_path), + "clips": len(heldout), "recordings": len({row['physical_recording_id'] for row in heldout}), + **numeric_stats(heldout)}, + }) + return { + "schema_version": "phase9_h2o_train_multifold_v1", + "status": "complete", + "source_cache_manifest": {"path": str(cache_manifest.resolve()), "sha256": sha256(cache_manifest)}, + "selection_metrics": ["fold_macro_absolute_mpjpe", "worst_fold_absolute_mpjpe"], + "folds": folds, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--cache-report", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists() or args.output_dir.exists(): + parser.error("multifold output already exists") + try: + result = build(args.cache_manifest, args.cache_report, args.output_dir) + except (OSError, ValueError, KeyError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_hot_scale_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_hot_scale_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..02461a594c28ac7532731ee53ffecf3708076071 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_hot_scale_configs.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Generate matched J40 HOT10K/HOT50K data-volume configurations.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +from pathlib import Path + +import yaml + +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--run-root", type=Path, required=True) + parser.add_argument("--data-readiness-state", type=Path, required=True) + parser.add_argument("--data-finalize-plan-sha256", required=True) + parser.add_argument("--initialization-checkpoint", type=Path, required=True) + parser.add_argument("--initialization-checkpoint-sha256", required=True) + parser.add_argument( + "--refresh", action="store_true", + help="Replace preregistered configs only when no training checkpoint exists.", + ) + args = parser.parse_args() + if (args.output_dir.exists() or args.registry.exists()) and not args.refresh: + parser.error("outputs must be new") + if args.refresh and args.run_root.exists() and any(args.run_root.rglob("*.pt")): + parser.error("cannot refresh HOT scale configs after a training checkpoint exists") + if sha256(args.initialization_checkpoint) != args.initialization_checkpoint_sha256: + parser.error("initialization checkpoint SHA256 differs") + base = yaml.safe_load(args.base_config.read_text(encoding="utf-8")) + if base["experiment"]["condition"] != "J40": + parser.error("base config must be J40") + args.output_dir.mkdir(parents=True, exist_ok=args.refresh) + hot_manifests = { + "J40_HOT10K": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl", + "J40_HOT50K": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_50000_v1/cache_manifest.jsonl", + } + conditions = [] + for condition, hot_manifest in hot_manifests.items(): + config = copy.deepcopy(base) + config["name"] = f"phase9_{condition.lower()}_s20260717" + config["experiment"]["condition"] = condition + hot = next(source for source in config["data"]["sources"] if source["dataset"] == "HOT3D") + hot["cache_manifest"] = hot_manifest + path = args.output_dir / f"{condition.lower()}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + errors = validate_phase9_unified_contract(config, path) + if errors: + raise ValueError(f"invalid generated HOT scale config: {'; '.join(errors)}") + conditions.append({ + "condition": condition, "config": str(path.resolve()), + "config_sha256": sha256(path), + "initialization_checkpoint": str(args.initialization_checkpoint.resolve()), + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "output_dir": str((args.run_root / condition.lower()).resolve()), + "log_dir": str((args.run_root.parent / "queues" / "hot_scale" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": "scale505k", "stop_after_step": 505000}, + ], + }) + registry = { + "schema_version": "phase9_hot_unique_scale_training_queue_v1", + "status": "frozen_before_hot_scale_training", + "data_readiness_state": str(args.data_readiness_state.resolve()), + "data_finalize_plan_sha256": args.data_finalize_plan_sha256, + "prerequisite_states": [ + {"condition": condition, "path": str( + (args.data_readiness_state.parent / f"{condition.lower()}_state.json").resolve() + )} for condition in ("J25", "J40", "J55") + ], + "allowed_physical_gpus": [0, 1, 2, 3], + "prohibited_physical_gpus": [4, 5], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "conditions": conditions, + } + args.registry.write_text(json.dumps(registry, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "registry": str(args.registry.resolve()), "sha256": sha256(args.registry), + "conditions": [condition["condition"] for condition in conditions], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_last2_evaluation_plan.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_last2_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe26e4c5fc7553a82ce13c2dda94c111b6b189b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_last2_evaluation_plan.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Freeze one ordered last-2 candidate's 25 matched evaluations.""" + +from __future__ import annotations + +import argparse +import fcntl +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_evaluation_plan import ( + completed_training_jobs, + evaluation_record, +) +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_control_plan(path: Path, expected_sha256: str) -> dict[str, Any]: + if not path.is_file() or sha256(path) != expected_sha256: + raise ValueError("last-2 control evaluation plan differs") + plan = read_json(path) + if ( + plan.get("status") != "frozen_ready" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or len(plan.get("evaluations", [])) != 25 + ): + raise ValueError("last-2 control evaluation contract differs") + return plan + + +def build_plan( + *, candidate: str, training_controller_plan_path: Path, + training_controller_state_path: Path, output_root: Path, + worker_state_root: Path, distributed_assignment_path: Path, + distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or controller_state.get("h2o_official_validation_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("last-2 training controller is not complete and bound") + registry = read_json(registry_path) + if registry.get("candidate") != candidate: + raise ValueError("last-2 training registry candidate differs") + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + if candidate == "5e7": + control_path = Path(registry["base_evaluation_plan"]["path"]) + control_sha256 = registry["base_evaluation_plan"]["sha256"] + elif candidate == "1e6": + five_decision_path = Path(registry["five_e7_decision"]["path"]) + if ( + not five_decision_path.is_file() + or registry["five_e7_decision"]["sha256"] != sha256(five_decision_path) + ): + raise ValueError("conditional 1e-6 decision binding differs") + five_decision = read_json(five_decision_path) + control_path = Path(five_decision["evaluation_plan"]["path"]) + control_sha256 = five_decision["evaluation_plan"]["sha256"] + else: + raise ValueError("unknown last-2 evaluation candidate") + control = validate_control_plan(control_path, control_sha256) + control_items = {item["id"]: item for item in control["evaluations"]} + evaluations = [] + for identifier, control_item in control_items.items(): + role = control_item["training_role"] + job = jobs[role] + evaluations.append(evaluation_record( + evaluation_id=identifier, + job=job, + manifest=Path(control_item["cache_manifest"]), + mode=control_item["input_mode"], + role=control_item["evaluation_role"], + output=output_root / Path(control_item["output_dir"]).relative_to( + control["output_root"] + ), + )) + ids = [item["id"] for item in evaluations] + if len(ids) != 25 or len(set(ids)) != 25 or set(ids) != set(control_items): + raise ValueError("last-2 evaluation IDs differ from control") + control_reports = { + identifier: { + "path": str((Path(item["output_dir"]) / "evaluation.json").resolve()), + "sha256": sha256(Path(item["output_dir"]) / "evaluation.json"), + "evaluation_role": item["evaluation_role"], + "input_mode": item["input_mode"], + } + for identifier, item in control_items.items() + } + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_last2_evaluation_plan_v1", + "status": "frozen_ready", "candidate": candidate, + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "control_evaluation_plan": { + "path": str(control_path.resolve()), "sha256": control_sha256, + }, + "control_reports": control_reports, + "winner": registry["winner"], + "resolution_hw": registry["resolution_hw"], + "shared_augmentation": registry["shared_augmentation"], + "backbone_learning_rate": registry["backbone_learning_rate"], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "gate": "macro_and_worst_domain_must_both_strictly_improve", + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--candidate", choices=("5e7", "1e6"), required=True) + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + candidate=args.candidate, + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing last-2 evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_last2_evaluation_plan_state_v1", + "status": "failed_resumable", "candidate": args.candidate, + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_last2_evaluation_plan_state_v1", + "status": "complete", "candidate": args.candidate, + "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_last2_training_registry.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_last2_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..2a04b4420ca861e79c5a34cb4af9de021c0a7306 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_last2_training_registry.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +"""Freeze ordered DINO Base last-2 training registries after Stage 8.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.build_phase9_resolution_training_registry import ( + FOLDS, + atomic_json, + sha256, + write_config, +) +from scripts.train_phase7_external import validate_phase9_unified_contract + + +CANDIDATES = { + "5e7": {"phase9_stage": "last2_5e7", "backbone_learning_rate": 5e-7}, + "1e6": {"phase9_stage": "last2_1e6", "backbone_learning_rate": 1e-6}, +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_stage8( + controller_plan_path: Path, controller_state_path: Path, +) -> tuple[dict[str, Any], dict[str, Any], Path]: + state = read_json(controller_state_path) + decision_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(controller_plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not decision_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(decision_path) + ): + raise ValueError("Stage 8 decision controller is not complete and bound") + decision = read_json(decision_path) + evaluation_plan_path = Path(state.get("evaluation_plan", "")) + if ( + decision.get("status") != "complete" + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + or not evaluation_plan_path.is_file() + or state.get("evaluation_plan_sha256") != sha256(evaluation_plan_path) + or decision.get("evaluation_plan", {}).get("sha256") + != sha256(evaluation_plan_path) + ): + raise ValueError("Stage 8 decision/evaluation binding differs") + return decision, read_json(evaluation_plan_path), evaluation_plan_path + + +def selected_base( + stage8_decision: dict[str, Any], stage8_plan: dict[str, Any], + stage8_plan_path: Path, +) -> tuple[dict[str, Any], Path, str, bool]: + if stage8_decision["shared_augmentation_accepted"]: + base_plan = stage8_plan + base_plan_path = stage8_plan_path + mechanism = "shared_augmentation" + shared_augmentation = True + else: + preceding = stage8_decision["stage9_preceding_mechanism_gate"] + if ( + preceding.get("source_mechanism") != "resolution" + or preceding.get("stage9_last2_admitted") is not True + or stage8_plan.get("control", {}).get("kind") + != "resolution_896x512_candidate" + ): + raise ValueError("no selected preceding mechanism admits Stage 9") + base_plan_path = Path(stage8_plan["control"]["evaluation_plan"]["path"]) + if ( + not base_plan_path.is_file() + or stage8_plan["control"]["evaluation_plan"]["sha256"] + != sha256(base_plan_path) + ): + raise ValueError("selected resolution control plan differs") + base_plan = read_json(base_plan_path) + mechanism = "resolution" + shared_augmentation = False + if set(base_plan["training_jobs"]) != {"full", *FOLDS}: + raise ValueError("selected last-2 base training roles differ") + return base_plan, base_plan_path, mechanism, shared_augmentation + + +def derive_last2_config( + base: dict[str, Any], *, condition: str, candidate: str, + resolution_hw: list[int], shared_augmentation: bool, + stage8_decision_sha256: str, +) -> dict[str, Any]: + spec = CANDIDATES[candidate] + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = spec["phase9_stage"] + experiment["last2_resolution_hw"] = list(resolution_hw) + experiment["last2_shared_augmentation"] = bool(shared_augmentation) + experiment["stage8_decision_sha256"] = stage8_decision_sha256 + model = config["model"] + if model.get("encoder") != "dinov3": + raise ValueError("last-2 base does not use DINOv3") + if model.get("dinov3_model", "dinov3_vitb16") != "dinov3_vitb16": + raise ValueError("last-2 base is not DINO Base") + model["dinov3_trainable_last_blocks"] = 2 + config["protocol"]["backbone_learning_rate"] = spec[ + "backbone_learning_rate" + ] + return config + + +def validate_matched_last2( + base: dict[str, Any], derived: dict[str, Any], candidate: str, +) -> None: + for key in ("seed", "loss", "assets", "precision"): + if derived[key] != base[key]: + raise ValueError(f"last-2 config changes matched {key}") + base_model = deepcopy(base["model"]) + derived_model = deepcopy(derived["model"]) + base_model.pop("dinov3_trainable_last_blocks", None) + if derived_model.pop("dinov3_trainable_last_blocks", None) != 2: + raise ValueError("last-2 config does not train exactly two blocks") + if base_model != derived_model: + raise ValueError("last-2 config changes non-admitted model parameters") + base_protocol = deepcopy(base["protocol"]) + derived_protocol = deepcopy(derived["protocol"]) + base_protocol.pop("backbone_learning_rate", None) + actual_lr = derived_protocol.pop("backbone_learning_rate", None) + if actual_lr != CANDIDATES[candidate]["backbone_learning_rate"]: + raise ValueError("last-2 backbone learning rate differs") + if base_protocol != derived_protocol: + raise ValueError("last-2 config changes optimizer/scheduler horizon") + if derived["data"] != base["data"]: + raise ValueError("last-2 config changes data, mixture or augmentation") + + +def validate_conditional_1e6(path: Path | None) -> dict[str, Any]: + if path is None or not path.is_file(): + raise ValueError("1e-6 requires a frozen 5e-7 decision report") + report = read_json(path) + if ( + report.get("status") != "complete" + or report.get("candidate") != "5e7" + or report.get("gate", {}).get("macro_strictly_improved") is not True + or report.get("gate", {}).get("worst_domain_strictly_improved") is not True + or report.get("gate", {}).get("accepted") is not True + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError("5e-7 did not pass strict macro and worst-domain gates") + evaluation_plan = Path(report.get("evaluation_plan", {}).get("path", "")) + if ( + not evaluation_plan.is_file() + or report["evaluation_plan"].get("sha256") != sha256(evaluation_plan) + ): + raise ValueError("5e-7 decision evaluation plan differs") + return report + + +def build_registry( + *, candidate: str, stage8_controller_plan_path: Path, + stage8_controller_state_path: Path, last2_plan_path: Path, + output_root: Path, five_e7_decision_path: Path | None, +) -> dict[str, Any]: + if candidate not in CANDIDATES: + raise ValueError("unknown last-2 candidate") + stage8_decision, stage8_plan, stage8_plan_path = validate_stage8( + stage8_controller_plan_path, stage8_controller_state_path, + ) + decision_path = stage8_decision_path(stage8_controller_state_path) + preceding = stage8_decision["stage9_preceding_mechanism_gate"] + if preceding.get("stage9_last2_admitted") is not True: + raise ValueError("Stage 9 is not admitted by the preceding mechanism") + five_e7 = ( + validate_conditional_1e6(five_e7_decision_path) + if candidate == "1e6" else None + ) + base_plan, base_plan_path, mechanism, shared_augmentation = selected_base( + stage8_decision, stage8_plan, stage8_plan_path, + ) + resolution_hw = list(stage8_decision["resolution_hw"]) + if base_plan["resolution_hw"] != resolution_hw: + raise ValueError("last-2 base resolution differs from Stage 8 decision") + base_registry_path = Path(base_plan["training_registry"]["path"]) + if ( + not base_registry_path.is_file() + or base_plan["training_registry"]["sha256"] != sha256(base_registry_path) + ): + raise ValueError("last-2 base registry differs") + base_registry = read_json(base_registry_path) + last2_plan = read_json(last2_plan_path) + expected = last2_plan[ + "candidate_5e7" if candidate == "5e7" else "conditional_candidate_1e6" + ] + if ( + last2_plan.get("official_test_used") is not False + or expected.get("dinov3_trainable_last_blocks") != 2 + or float(expected.get("backbone_learning_rate")) + != CANDIDATES[candidate]["backbone_learning_rate"] + or last2_plan.get("dino_large") != "not_admitted" + ): + raise ValueError("frozen last-2 plan differs") + + target_step = int(base_registry["target_step"]) + label = candidate + config_root = output_root / label / "phase9" / "configs" + conditions = [] + for role in ("full", *FOLDS): + job = base_plan["training_jobs"][role] + config_path = Path(job["config"]) + if not config_path.is_file() or job["config_sha256"] != sha256(config_path): + raise ValueError(f"last-2 base config differs: {role}") + base = yaml.safe_load(config_path.read_text(encoding="utf-8")) + prefix = "S9L5" if candidate == "5e7" else "S9L10" + condition = f"{prefix}_{stage8_decision['winner'].split(':', 1)[0]}_{role}" + derived = derive_last2_config( + base, condition=condition, candidate=candidate, + resolution_hw=resolution_hw, + shared_augmentation=shared_augmentation, + stage8_decision_sha256=sha256(decision_path), + ) + validate_matched_last2(base, derived, candidate) + derived_path = config_root / f"{condition.lower()}.yaml" + errors = validate_phase9_unified_contract(derived, derived_path) + if errors: + raise ValueError("; ".join(errors)) + write_config(derived_path, derived) + run_dir = output_root / label / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"last-2 run exists before freeze: {run_dir}") + conditions.append({ + "condition": condition, "role": role, + "config": str(derived_path.resolve()), + "config_sha256": sha256(derived_path), + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / label / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": base_registry[ + "matched_source_exposure_batches" + ], + "expected_source_exposure_frames": base_registry[ + "matched_source_exposure_frames" + ], + }) + return { + "schema_version": "phase9_last2_training_registry_v1", + "status": "frozen_ready", "created_utc": stage8_decision["created_utc"], + "candidate": candidate, + "backbone_learning_rate": CANDIDATES[candidate]["backbone_learning_rate"], + "winner": stage8_decision["winner"], + "resolution_hw": resolution_hw, + "shared_augmentation": shared_augmentation, + "selected_preceding_mechanism": mechanism, + "stage8_decision": { + "path": str(decision_path.resolve()), + "sha256": sha256(decision_path), + }, + "base_evaluation_plan": { + "path": str(base_plan_path.resolve()), "sha256": sha256(base_plan_path), + }, + "base_training_registry": { + "path": str(base_registry_path.resolve()), "sha256": sha256(base_registry_path), + }, + "five_e7_decision": ( + {"path": str(five_e7_decision_path.resolve()), + "sha256": sha256(five_e7_decision_path)} + if five_e7 is not None else None + ), + "last2_plan": { + "path": str(last2_plan_path.resolve()), "sha256": sha256(last2_plan_path), + }, + "target_step": target_step, + "matched_source_exposure_batches": base_registry[ + "matched_source_exposure_batches" + ], + "matched_source_exposure_frames": base_registry[ + "matched_source_exposure_frames" + ], + "data_readiness_state": base_registry["data_readiness_state"], + "data_readiness_state_sha256": base_registry["data_readiness_state_sha256"], + "data_finalize_plan_sha256": base_registry["data_finalize_plan_sha256"], + "data_artifacts": base_registry["data_artifacts"], + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def stage8_decision_path(controller_state_path: Path) -> Path: + state = read_json(controller_state_path) + return Path(state["decision_report"]["path"]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--candidate", choices=tuple(CANDIDATES), required=True) + parser.add_argument("--stage8-controller-plan", type=Path, required=True) + parser.add_argument("--stage8-controller-state", type=Path, required=True) + parser.add_argument("--last2-plan", type=Path, required=True) + parser.add_argument("--five-e7-decision", type=Path) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + registry = build_registry( + candidate=args.candidate, + stage8_controller_plan_path=args.stage8_controller_plan, + stage8_controller_state_path=args.stage8_controller_state, + last2_plan_path=args.last2_plan, + output_root=args.output_root, + five_e7_decision_path=args.five_e7_decision, + ) + if args.output_registry.exists(): + if read_json(args.output_registry) != registry: + raise ValueError("existing last-2 training registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_last2_registry_state_v1", + "status": "failed_resumable", "candidate": args.candidate, + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_last2_registry_state_v1", + "status": "complete", "candidate": args.candidate, + "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_resolution_evaluation_plan.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_resolution_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..6817a02586ce001cae349a38ad3b8510e49cff7f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_resolution_evaluation_plan.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Freeze Stage 7 evaluations from completed matched-resolution training.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +EXTERNAL_MODES = { + "HOT3D": ("rgb_k", "rgb_only"), + "HOI4D": ("rgb_d_k", "rgb_k", "rgb_only"), + "ARCTIC": ("rgb_k", "rgb_only"), +} +EXTERNAL_CACHE_IDS = { + "HOT3D": "hot3d_heldout", + "HOI4D": "hoi4d_heldout", + "ARCTIC": "arctic_heldout", +} +H2O_MODES = ("rgb_d_k", "rgb_k", "rgb_only") + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def completed_training_jobs( + registry_path: Path, registry: dict[str, Any], state_root: Path, +) -> dict[str, dict[str, Any]]: + registry_hash = sha256(registry_path) + result = {} + for job in registry["conditions"]: + condition = job["condition"] + state_path = state_root / f"{condition.lower()}.json" + if not state_path.is_file(): + raise ValueError(f"resolution training state is missing: {condition}") + state = read_json(state_path) + marker = state.get("last_completed", {}) + checkpoint = Path(marker.get("checkpoint", "")) + if ( + state.get("status") != "complete" + or state.get("queue_sha256") != registry_hash + or state.get("official_test_used") is not False + or marker.get("completed_step") != registry["target_step"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + ): + raise ValueError(f"resolution training endpoint differs: {condition}") + result[job["role"]] = { + **job, + "state": str(state_path.resolve()), + "state_sha256": sha256(state_path), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": marker["checkpoint_sha256"], + "gpu_hours": state["gpu_hours_consumed"], + } + if set(result) != { + "full", "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + }: + raise ValueError("resolution training roles differ") + return result + + +def evaluation_record( + *, evaluation_id: str, job: dict[str, Any], manifest: Path, + mode: str, role: str, output: Path, +) -> dict[str, Any]: + config = Path(job["config"]) + if not config.is_file() or sha256(config) != job["config_sha256"]: + raise ValueError(f"resolution evaluation config differs: {evaluation_id}") + if not manifest.is_file(): + raise ValueError(f"resolution evaluation manifest missing: {evaluation_id}") + return { + "id": evaluation_id, + "training_role": job["role"], + "config": str(config.resolve()), + "config_sha256": job["config_sha256"], + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": mode, + "evaluation_role": role, + "output_dir": str(output.resolve()), + } + + +def build_plan( + *, training_controller_plan_path: Path, training_controller_state_path: Path, + cache_plan_path: Path, output_root: Path, worker_state_root: Path, + distributed_assignment_path: Path, distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("resolution training controller is not complete and bound") + registry = read_json(registry_path) + if ( + registry.get("status") != "frozen_ready" + or registry.get("official_test_used") is not False + or registry.get("h2o_official_validation_used_for_selection") is not False + or registry.get("gate", {}).get("worst_domain_relative_regression_limit") + != controller_plan["worst_domain_relative_regression_limit"] + ): + raise ValueError("resolution training registry contract differs") + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + + cache_plan = read_json(cache_plan_path) + caches = {item["id"]: item for item in cache_plan["caches"]} + evaluations = [] + full = jobs["full"] + for dataset, modes in EXTERNAL_MODES.items(): + cache = caches[EXTERNAL_CACHE_IDS[dataset]] + manifest = Path(cache["manifest"]) + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=full, manifest=manifest, + mode=mode, role="phase9_external_heldout", + output=output_root / "full" / dataset.lower() / mode, + )) + for fold, job in jobs.items(): + if fold == "full": + continue + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + validation = config["data"].get("validation_sources", []) + if len(validation) != 1 or validation[0].get("dataset") != "H2O": + raise ValueError(f"resolution fold heldout differs: {fold}") + manifest = Path(validation[0]["cache_manifest"]) + for mode in H2O_MODES: + identifier = f"{fold}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=job, manifest=manifest, + mode=mode, role="phase9_h2o_fold_heldout", + output=output_root / "h2o" / fold / mode, + )) + ids = [item["id"] for item in evaluations] + outputs = [item["output_dir"] for item in evaluations] + if len(evaluations) != 25 or len(set(ids)) != 25 or len(set(outputs)) != 25: + raise ValueError("resolution evaluation IDs/outputs are not unique and complete") + + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_resolution_evaluation_plan_v1", + "status": "frozen_ready", + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "cache_execution_plan": { + "path": str(cache_plan_path.resolve()), "sha256": sha256(cache_plan_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "winner": registry["winner"], + "winner_checkpoint": registry["winner_checkpoint"], + "winner_config": registry["winner_config"], + "control_evidence": registry["control_evidence"], + "gate": registry["gate"], + "resolution_hw": [512, 896], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--cache-plan", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + cache_plan_path=args.cache_plan, output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing resolution evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_resolution_evaluation_plan_state_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_resolution_evaluation_plan_state_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_resolution_training_registry.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_resolution_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..3d10ab153ad63a19c9638d018c484bcd86b3254b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_resolution_training_registry.py @@ -0,0 +1,453 @@ +#!/usr/bin/env python3 +"""Freeze matched 896 training jobs from the selected 640 checkpoint.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +import re +from typing import Any + +import torch +import yaml + + +FOLDS = ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", +) +RESOLUTION_HW = [512, 896] +WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT = 0.01 +SOURCE_MANIFESTS = { + "H2O": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/h2o_train7000/cache_manifest.jsonl" + ), + "HOT3D": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/hot3d_train100000/cache_manifest.jsonl" + ), + "HOI4D": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/hoi4d_train37304_left_root/cache_manifest.jsonl" + ), + "ARCTIC": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/arctic_train21339_left_root/cache_manifest.jsonl" + ), +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_text(path: Path, value: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(value, encoding="utf-8") + temporary.replace(path) + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + atomic_text(path, json.dumps(value, indent=2) + "\n") + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def checkpoint_metadata( + path: Path, expected_sha256: str, expected_config_sha256: str, +) -> dict[str, Any]: + if not path.is_file() or sha256(path) != expected_sha256: + raise ValueError("selected 640 checkpoint hash differs") + payload = torch.load(path, map_location="cpu", weights_only=False) + extra = payload.get("extra", {}) + step = int(payload.get("step", -1)) + filename = re.search(r"step_(\d+)", path.name) + if ( + step <= 2000 + or filename is None + or int(filename.group(1)) != step + or extra.get("config_sha256") != expected_config_sha256 + or extra.get("official_test_used") is not False + or not extra.get("source_exposure_batches") + or not extra.get("external_initialization_checkpoint") + ): + raise ValueError("selected 640 checkpoint metadata differs") + return { + "step": step, + "source_exposure_batches": extra["source_exposure_batches"], + "source_exposure_frames": extra.get("source_exposure_frames", {}), + "completed_source_exposure_milestones": extra.get( + "completed_source_exposure_milestones", [] + ), + "initialization_checkpoint": extra["external_initialization_checkpoint"], + } + + +def derive_config( + base: dict[str, Any], *, condition: str, target_step: int, + h2o_train_manifest: str, h2o_heldout_manifest: str | None, + winner: str, winner_checkpoint_sha256: str, +) -> dict[str, Any]: + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = "resolution_896x512" + experiment["resolution_control_winner"] = winner + experiment["resolution_control_checkpoint_sha256"] = winner_checkpoint_sha256 + data = config["data"] + data["resolution_hw"] = list(RESOLUTION_HW) + for source in data["sources"]: + dataset = str(source["dataset"]).upper() + source["cache_manifest"] = ( + h2o_train_manifest if dataset == "H2O" else SOURCE_MANIFESTS[dataset] + ) + if h2o_heldout_manifest is None: + data.pop("validation_sources", None) + else: + validation = data.get("validation_sources", []) + if len(validation) != 1 or str(validation[0].get("dataset", "")).upper() != "H2O": + raise ValueError("fold base config lacks exactly one H2O heldout") + validation[0]["cache_manifest"] = h2o_heldout_manifest + return config + + +def validate_matched_config( + base: dict[str, Any], derived: dict[str, Any], target_step: int, +) -> None: + if ( + derived["seed"] != base["seed"] + or derived["model"] != base["model"] + or derived["loss"] != base["loss"] + or derived["assets"] != base["assets"] + or derived["precision"] != base["precision"] + or derived["data"]["T"] != base["data"]["T"] + or derived["data"]["batch_size"] != base["data"]["batch_size"] + or derived["data"].get("photometric_augmentation") + != base["data"].get("photometric_augmentation") + ): + raise ValueError("resolution config changes a matched model/data invariant") + base_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() if key != "cache_manifest" + } + for item in base["data"]["sources"] + } + derived_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() if key != "cache_manifest" + } + for item in derived["data"]["sources"] + } + if base_sources != derived_sources: + raise ValueError("resolution config changes source mixture or source settings") + if base["protocol"] != derived["protocol"]: + raise ValueError("resolution config changes optimizer/scheduler protocol") + + +def verify_readiness( + selection: dict[str, Any], readiness_path: Path, expected_plan_sha256: str, +) -> dict[str, Any]: + readiness = read_json(readiness_path) + audit_path = Path(readiness.get("audit", {}).get("path", "")) + if ( + readiness.get("status") != "complete" + or readiness.get("plan_sha256") != expected_plan_sha256 + or readiness.get("official_test_used") is not False + or readiness.get("h2o_official_validation_used") is not False + or readiness.get("winner") != selection.get("winner") + or readiness.get("winner_checkpoint") != selection.get("winner_checkpoint") + or readiness.get("winner_config") != selection.get("winner_config") + or not audit_path.is_file() + or readiness.get("audit", {}).get("sha256") != sha256(audit_path) + ): + raise ValueError("resolution cache readiness differs from selected winner") + audit = read_json(audit_path) + if ( + audit.get("status") != "complete" + or audit.get("plan_sha256") != expected_plan_sha256 + or audit.get("resolution_hw") != RESOLUTION_HW + or audit.get("official_test_used") is not False + or audit.get("h2o_official_validation_used") is not False + or not audit.get("multifold", {}).get("physical_recording_isolation") + or not audit.get("multifold", {}).get("deterministic_rebuild_hashes_match") + ): + raise ValueError("resolution cache audit differs") + return readiness + + +def write_config(path: Path, config: dict[str, Any]) -> None: + text = yaml.safe_dump(config, sort_keys=False, width=1000) + if path.exists(): + if path.read_text(encoding="utf-8") != text: + raise ValueError(f"existing resolution config differs: {path}") + return + atomic_text(path, text) + + +def build_registry( + *, selection_path: Path, readiness_path: Path, cache_plan_path: Path, + unified_queue_path: Path, fold_queue_path: Path, output_root: Path, +) -> dict[str, Any]: + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("unified selection is not complete and isolated") + cache_plan_sha256 = sha256(cache_plan_path) + readiness = verify_readiness(selection, readiness_path, cache_plan_sha256) + + winner = str(selection["winner"]) + mixture = winner.split(":", 1)[0] + if mixture not in {"J25", "J40", "J55"}: + raise ValueError("selected winner mixture is unknown") + winner_row = next( + (row for row in selection["candidates"] if row["id"] == winner), None + ) + if ( + winner_row is None + or winner_row.get("checkpoint") != selection["winner_checkpoint"] + or winner_row.get("config") != selection["winner_config"] + ): + raise ValueError("selected winner row is missing") + + unified_queue = read_json(unified_queue_path) + fold_queue = read_json(fold_queue_path) + full_job = next( + (item for item in unified_queue["conditions"] if item["condition"] == mixture), + None, + ) + if full_job is None: + raise ValueError("selected mixture is missing from the full-data queue") + selected_config = selection["winner_config"] + if ( + Path(selected_config["path"]).resolve() != Path(full_job["config"]).resolve() + or selected_config["sha256"] != full_job["config_sha256"] + or sha256(full_job["config"]) != full_job["config_sha256"] + ): + raise ValueError("selected config differs from the frozen full-data queue") + metadata = checkpoint_metadata( + Path(selection["winner_checkpoint"]["path"]), + selection["winner_checkpoint"]["sha256"], + selected_config["sha256"], + ) + initialization = metadata["initialization_checkpoint"] + initialization_path = Path(full_job["initialization_checkpoint"]) + if ( + Path(initialization.get("path", "")).resolve() + != initialization_path.resolve() + or initialization.get("sha256") != full_job["initialization_checkpoint_sha256"] + or not initialization_path.is_file() + or sha256(initialization_path) != full_job["initialization_checkpoint_sha256"] + ): + raise ValueError("selected checkpoint initialization differs") + + multifold = read_json( + output_root / "manifests" / "h2o_multifold_index.json" + ) + if ( + multifold.get("status") != "complete" + or multifold.get("official_test_used") is not False + or multifold.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution multifold index is not complete and isolated") + folds = {item["id"]: item for item in multifold["folds"]} + if set(folds) != set(FOLDS): + raise ValueError("resolution multifold IDs differ") + + config_root = output_root / "phase9" / "configs" + conditions = [] + base_full = yaml.safe_load(Path(full_job["config"]).read_text(encoding="utf-8")) + job_specs: list[tuple[str, dict[str, Any], str, str | None]] = [ + ("full", base_full, SOURCE_MANIFESTS["H2O"], None) + ] + fold_jobs = {item["condition"]: item for item in fold_queue["conditions"]} + for fold in FOLDS: + condition_id = f"{mixture}_{fold}" + if condition_id not in fold_jobs: + raise ValueError(f"selected mixture fold config is missing: {fold}") + base = yaml.safe_load( + Path(fold_jobs[condition_id]["config"]).read_text(encoding="utf-8") + ) + job_specs.append(( + fold, base, folds[fold]["train"]["path"], folds[fold]["heldout"]["path"] + )) + + target_step = int(metadata["step"]) + for role, base, h2o_train, h2o_heldout in job_specs: + condition = f"S7R_{mixture}_{role}" + config = derive_config( + base, condition=condition, target_step=target_step, + h2o_train_manifest=h2o_train, h2o_heldout_manifest=h2o_heldout, + winner=winner, + winner_checkpoint_sha256=selection["winner_checkpoint"]["sha256"], + ) + validate_matched_config(base, config, target_step) + config_path = config_root / f"{condition.lower()}.yaml" + write_config(config_path, config) + run_dir = output_root / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"resolution run output exists before registry freeze: {run_dir}") + conditions.append({ + "condition": condition, + "role": role, + "config": str(config_path.resolve()), + "config_sha256": sha256(config_path), + "initialization_checkpoint": full_job["initialization_checkpoint"], + "initialization_checkpoint_sha256": full_job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": metadata["source_exposure_batches"], + "expected_source_exposure_frames": metadata["source_exposure_frames"], + }) + + manifests = {} + for dataset, path in SOURCE_MANIFESTS.items(): + manifests[dataset] = {"path": path, "sha256": sha256(path)} + cache_plan = read_json(cache_plan_path) + artifact_paths = { + Path(item["manifest"]).resolve() for item in cache_plan["caches"] + } | { + Path(item["manifest"]).resolve() for item in cache_plan["sidecars"] + } | { + Path(cache_plan["multifold"]["index"]).resolve(), + } + for fold in folds.values(): + artifact_paths.add(Path(fold["train"]["path"]).resolve()) + artifact_paths.add(Path(fold["heldout"]["path"]).resolve()) + data_artifacts = [ + {"path": str(path), "sha256": sha256(path)} + for path in sorted(artifact_paths) + ] + registry = { + "schema_version": "phase9_resolution_training_registry_v1", + "status": "frozen_ready", + "created_utc": readiness["completed_utc"], + "winner": winner, + "winner_checkpoint": selection["winner_checkpoint"], + "winner_config": selection["winner_config"], + "control_evidence": winner_row, + "target_step": target_step, + "matched_source_exposure_batches": metadata["source_exposure_batches"], + "matched_source_exposure_frames": metadata["source_exposure_frames"], + "completed_source_exposure_milestones": metadata[ + "completed_source_exposure_milestones" + ], + "resolution_hw": RESOLUTION_HW, + "data_readiness_state": str(readiness_path.resolve()), + "data_readiness_state_sha256": sha256(readiness_path), + "data_finalize_plan_sha256": cache_plan_sha256, + "data_artifacts": data_artifacts, + "source_manifests": manifests, + "selection_report": { + "path": str(selection_path.resolve()), "sha256": sha256(selection_path), + }, + "cache_execution_plan": { + "path": str(cache_plan_path.resolve()), "sha256": cache_plan_sha256, + }, + "gate": { + "macro_absolute_mm_must_strictly_improve": True, + "worst_domain_relative_regression_limit": ( + WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT + ), + }, + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + return registry + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-report", type=Path, required=True) + parser.add_argument("--readiness-state", type=Path, required=True) + parser.add_argument("--cache-plan", type=Path, required=True) + parser.add_argument("--unified-queue", type=Path, required=True) + parser.add_argument("--fold-queue", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.state.is_file(): + state = read_json(args.state) + if state.get("status") == "complete": + if ( + args.output_registry.is_file() + and state.get("registry_sha256") == sha256(args.output_registry) + ): + print(json.dumps(state, indent=2)) + return + parser.error("completed resolution registry state differs") + try: + registry = build_registry( + selection_path=args.selection_report, + readiness_path=args.readiness_state, + cache_plan_path=args.cache_plan, + unified_queue_path=args.unified_queue, + fold_queue_path=args.fold_queue, + output_root=args.output_root, + ) + if args.output_registry.exists(): + existing = read_json(args.output_registry) + if existing != registry: + raise ValueError("existing resolution training registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_resolution_training_registry_state_v1", + "status": "failed_resumable", + "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_resolution_training_registry_state_v1", + "status": "complete", + "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "winner": registry["winner"], + "winner_checkpoint": registry["winner_checkpoint"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_selection_binding_recovery_plan.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_selection_binding_recovery_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..429d2680d06f834a198213ceaf1c0bf978888527 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_selection_binding_recovery_plan.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Freeze canonical re-evaluations for Phase 9 selection path mismatches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def canonical_config(condition: str) -> Path: + return Path( + "/home/jiasen/foundation_hand/artifacts/phase9/registry/fold_configs" + ) / f"{condition.lower()}.yaml" + + +def build_plan( + *, assignment_path: Path, audit_path: Path, selection_plan_path: Path, + failure_backup_root: Path, +) -> dict[str, Any]: + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + audit = json.loads(audit_path.read_text(encoding="utf-8")) + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + assignment_hash = sha256(assignment_path) + if ( + assignment.get("status") + != "frozen_before_distributed_recovery_or_stage7_work" + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + or audit.get("status") != "complete_path_only_recovery_required" + or audit.get("distributed_assignment", {}).get("sha256") + != assignment_hash + or audit.get("selection_plan", {}).get("sha256") + != sha256(selection_plan_path) + or selection_plan.get("official_test_used") is not False + ): + raise ValueError("selection recovery source contract differs") + assigned = { + item["id"]: item + for item in assignment["phase9_selection_recovery"]["evaluations"] + } + if len(assigned) != 11 or set(assigned) != set(audit["mismatch_ids"]): + raise ValueError("selection recovery assignment IDs differ") + records_by_id = {item["id"]: item for item in audit["records"]} + evaluations = [] + for identifier in sorted(assigned): + source = records_by_id[identifier] + owner_record = assigned[identifier] + if source.get("binding_status") != "path_mismatch_content_identical": + raise ValueError(f"recovery is not path-only: {identifier}") + config = canonical_config(source["condition"]) + if ( + not config.is_file() + or sha256(config) != source["config"]["declared_sha256"] + ): + raise ValueError(f"canonical config differs: {identifier}") + checkpoint = Path(source["checkpoint"]["path"]) + checkpoint_hash = source["checkpoint"]["declared_sha256"] + manifest = Path(source["cache_manifest"]["expected_path"]) + manifest_hash = source["cache_manifest"]["expected_sha256"] + if ( + not checkpoint.is_file() or sha256(checkpoint) != checkpoint_hash + or not manifest.is_file() or sha256(manifest) != manifest_hash + ): + raise ValueError(f"canonical recovery input differs: {identifier}") + owner = owner_record["owner"] + root = Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + determinism = source["determinism"] + evaluations.append({ + "id": identifier, + "owner": owner, + "physical_gpu_id": owner_record["physical_gpu_id"], + "condition": source["condition"], + "checkpoint_id": source["checkpoint_id"], + "input_mode": "rgb_d_k", + "evaluation_role": "phase9_h2o_fold_heldout", + "config": str(config.resolve()), + "config_sha256": sha256(config), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_hash, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": manifest_hash, + "output_dir": str(( + root / "evaluations" / source["condition"] + / source["checkpoint_id"] / "rgb_d_k" + ).resolve()), + "prior_report": source["report"], + "expected_sample_counts": source["sample_counts"], + "expected_determinism": { + "metrics_sha256": determinism["metrics_sha256"], + "grouped_bootstrap_ci_sha256": determinism[ + "grouped_bootstrap_ci_sha256" + ], + "raw_predictions_sha256": determinism[ + "raw_predictions" + ]["declared_sha256"], + "per_hand_rows_sha256": determinism[ + "per_hand_rows" + ]["declared_sha256"], + "take_metrics_sha256": determinism[ + "take_metrics" + ]["declared_sha256"], + }, + }) + workers = [] + for owner in ("taku3", "server_new"): + allowlist = assignment["machines"][owner]["physical_gpu_allowlist"] + for gpu in allowlist: + ids = [ + item["id"] for item in evaluations + if item["owner"] == owner and item["physical_gpu_id"] == gpu + ] + if not ids: + continue + root = Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + workers.append({ + "id": f"{owner}_gpu{gpu}", "owner": owner, + "physical_gpu_id": gpu, + "state": str((root / "states" / f"gpu{gpu}.json").resolve()), + "log": str((root / "logs" / f"gpu{gpu}.log").resolve()), + "evaluation_ids": ids, + }) + assigned_ids = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(evaluations) != 11 + or len(assigned_ids) != 11 + or len(set(assigned_ids)) != 11 + or set(assigned_ids) != set(assigned) + ): + raise ValueError("selection recovery workers are not disjoint and complete") + backup_files = {} + for name in ( + "unified_selection_state.json", "unified_selection.log", + "unified_selection_watcher.log", + ): + path = failure_backup_root / name + if not path.is_file(): + raise ValueError(f"selection failure backup missing: {path}") + backup_files[name] = sha256(path) + repository = assignment_path.resolve().parents[3] + code_paths = [ + repository / "scripts/evaluate_phase7_external.py", + repository / "scripts/summarize_phase9_unified_selection.py", + repository / "scripts/run_phase9_selection_binding_recovery.py", + repository / "scripts/finalize_phase9_selection_binding_recovery.py", + repository / "scripts/merge_phase9_selection_binding_recovery.py", + ] + code_bindings = [] + for path in code_paths: + if not path.is_file(): + raise ValueError(f"selection recovery code missing: {path}") + code_bindings.append({"path": str(path), "sha256": sha256(path)}) + return { + "schema_version": "phase9_selection_binding_recovery_plan_v2", + "status": "frozen_before_recovery_evaluation", + "reason": "migration_path_binding_differs_with_identical_manifest_sha256", + "scientific_failure": False, + "resource_scheduling_amendment_only": True, + "distributed_assignment": { + "path": str(assignment_path.resolve()), "sha256": assignment_hash, + }, + "mismatch_manifest": { + "path": str(audit_path.resolve()), "sha256": sha256(audit_path), + }, + "selection_plan": { + "path": str(selection_plan_path.resolve()), + "sha256": sha256(selection_plan_path), + }, + "failure_backup": { + "root": str(failure_backup_root.resolve()), + "files": backup_files, + }, + "code_bindings": code_bindings, + "release_manifests": { + owner: str((Path( + assignment["phase9_selection_recovery"][ + f"{owner}_recovery_root" + ] + ) / "release_manifest.json").resolve()) + for owner in ("taku3", "server_new") + }, + "canonical_fold_milestone_root": selection_plan["fold_milestone_root"], + "dry_run_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts/selection_binding_recovery_v2/dry_run", + "canonical_merge_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/selection_binding_recovery_v2/merge_state.json", + "canonical_merge_backup_root": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/recovery_backups/selection_binding_v2_20260731", + "selection_state": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/unified_selection_state.json", + "selection_log": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/unified_selection.log", + "evaluations": evaluations, + "workers": workers, + "bootstrap_resamples": 2000, + "requirements": [ + "evaluate only assigned mismatches in new recovery roots", + "bind canonical config manifest checkpoint and expected SHA256", + "validate sample counts role isolation metrics and artifact determinism", + "run temporary JSON and CSV summarizer before canonical merge", + "atomically replace each mismatched canonical output under one merge lock", + "preserve failed selection and replaced output evidence" + ], + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--audit", type=Path, required=True) + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--failure-backup-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("recovery plan output must be new") + result = build_plan( + assignment_path=args.assignment, audit_path=args.audit, + selection_plan_path=args.selection_plan, + failure_backup_root=args.failure_backup_root, + ) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_shared_augmentation_evaluation_plan.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_shared_augmentation_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..e381262202ce3e6f36fd1a7cbc71286aa7b745ca --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_shared_augmentation_evaluation_plan.py @@ -0,0 +1,282 @@ +#!/usr/bin/env python3 +"""Freeze Stage 8 evaluations after shared-augmentation training completes.""" + +from __future__ import annotations + +import argparse +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.build_phase9_resolution_evaluation_plan import ( + EXTERNAL_MODES, + H2O_MODES, + completed_training_jobs, + evaluation_record, +) +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +HELDOUT_640 = { + "HOT3D": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "HOI4D": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "ARCTIC": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/arctic_val2048_fullgroups_v2/cache_manifest.jsonl", +} +HELDOUT_896_IDS = { + "HOT3D": "hot3d_heldout", "HOI4D": "hoi4d_heldout", + "ARCTIC": "arctic_heldout", +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def control_reports_896(registry: dict[str, Any]) -> dict[str, dict[str, str]]: + path = Path(registry["control"]["evaluation_plan"]["path"]) + if ( + not path.is_file() + or registry["control"]["evaluation_plan"]["sha256"] != sha256(path) + ): + raise ValueError("Stage 8 896 control evaluation plan differs") + plan = read_json(path) + reports = {} + for item in plan["evaluations"]: + reports[item["id"]] = { + "path": str((Path(item["output_dir"]) / "evaluation.json").resolve()), + "evaluation_role": item["evaluation_role"], + "input_mode": item["input_mode"], + } + return reports + + +def control_reports_640(registry: dict[str, Any]) -> dict[str, dict[str, str]]: + control = registry["control"]["control_evidence"] + mixture = control["mixture"] + external_id = control["external_checkpoint_id"] + fold_id = control["fold_checkpoint_id"] + external_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/external_milestones" + ) + final_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold" + ) + milestone_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold_milestones" + ) + reports = {} + for dataset, modes in EXTERNAL_MODES.items(): + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + reports[identifier] = { + "path": str(( + external_root / mixture / external_id + / f"{dataset.lower()}_{mode}" / "evaluation.json" + ).resolve()), + "evaluation_role": "phase9_external_heldout", + "input_mode": mode, + } + for fold in FOLDS: + condition = f"{mixture}_{fold}" + for mode in H2O_MODES: + path = ( + final_root / condition / mode / "evaluation.json" + if fold_id == "final" + else milestone_root / condition / fold_id / mode / "evaluation.json" + ) + reports[f"{fold}_{mode}"] = { + "path": str(path.resolve()), + "evaluation_role": "phase9_h2o_fold_heldout", + "input_mode": mode, + } + return reports + + +def validate_control_reports(reports: dict[str, dict[str, str]]) -> None: + if len(reports) != 25: + raise ValueError("Stage 8 control report count differs") + for identifier, item in reports.items(): + path = Path(item["path"]) + if not path.is_file(): + raise ValueError(f"Stage 8 control report missing: {identifier}") + report = read_json(path) + if ( + report.get("status") != f"evaluated_{item['evaluation_role']}" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"Stage 8 control report differs: {identifier}") + item["sha256"] = sha256(path) + + +def build_plan( + *, training_controller_plan_path: Path, training_controller_state_path: Path, + resolution_cache_plan_path: Path, output_root: Path, worker_state_root: Path, + distributed_assignment_path: Path, distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or controller_state.get("h2o_official_validation_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("shared augmentation training is not complete and bound") + registry = read_json(registry_path) + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + resolution_hw = registry["resolution_hw"] + if resolution_hw == [512, 896]: + cache_plan = read_json(resolution_cache_plan_path) + cache_by_id = {item["id"]: item for item in cache_plan["caches"]} + heldouts = { + dataset: Path(cache_by_id[identifier]["manifest"]) + for dataset, identifier in HELDOUT_896_IDS.items() + } + control_reports = control_reports_896(registry) + elif resolution_hw == [368, 640]: + heldouts = {dataset: Path(path) for dataset, path in HELDOUT_640.items()} + control_reports = control_reports_640(registry) + else: + raise ValueError("shared augmentation resolution differs") + validate_control_reports(control_reports) + + evaluations = [] + full = jobs["full"] + for dataset, modes in EXTERNAL_MODES.items(): + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=full, manifest=heldouts[dataset], + mode=mode, role="phase9_external_heldout", + output=output_root / "full" / dataset.lower() / mode, + )) + for fold in FOLDS: + job = jobs[fold] + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + validation = config["data"].get("validation_sources", []) + if len(validation) != 1 or validation[0].get("dataset") != "H2O": + raise ValueError(f"augmentation fold heldout differs: {fold}") + manifest = Path(validation[0]["cache_manifest"]) + for mode in H2O_MODES: + evaluations.append(evaluation_record( + evaluation_id=f"{fold}_{mode}", job=job, manifest=manifest, + mode=mode, role="phase9_h2o_fold_heldout", + output=output_root / "h2o" / fold / mode, + )) + ids = [item["id"] for item in evaluations] + if len(ids) != 25 or len(set(ids)) != 25: + raise ValueError("shared augmentation evaluation IDs differ") + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_shared_augmentation_evaluation_plan_v1", + "status": "frozen_ready", + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "winner": registry["winner"], + "resolution_hw": resolution_hw, + "resolution_decision": registry["resolution_decision"], + "control": registry["control"], + "control_reports": control_reports, + "gate": registry["gate"], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--resolution-cache-plan", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + resolution_cache_plan_path=args.resolution_cache_plan, + output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing augmentation evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_eval_plan_state_v1", + "status": "failed_resumable", "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_shared_augmentation_eval_plan_state_v1", + "status": "complete", "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_shared_augmentation_training_registry.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_shared_augmentation_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..5867d7bdf6a01d537e221a7d5d1c01f6c0b2d69f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_phase9_shared_augmentation_training_registry.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Freeze Stage 8 shared-augmentation jobs after the resolution decision.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS +from scripts.build_phase9_resolution_training_registry import ( + FOLDS, + atomic_json, + checkpoint_metadata, + sha256, + write_config, +) +from scripts.train_phase7_external import validate_phase9_unified_contract + + +GEOMETRY_AUGMENTATION = { + "enabled": True, + "probability": 0.8, + "scale_min": 0.9, + "scale_max": 1.1, + "translation_fraction": 0.05, +} +DEPTH_CORRUPTION_DATASETS = {"H2O", "HOI4D"} +WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT = 0.01 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def derive_augmentation_config( + base: dict[str, Any], *, condition: str, resolution_hw: list[int], + resolution_decision_sha256: str, +) -> dict[str, Any]: + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = ( + "shared_augmentation_896x512" + if resolution_hw == [512, 896] + else "shared_augmentation_640" + ) + experiment["resolution_decision_sha256"] = resolution_decision_sha256 + data = config["data"] + if data["resolution_hw"] != resolution_hw: + raise ValueError("augmentation base config resolution differs") + data["geometry_augmentation"] = deepcopy(GEOMETRY_AUGMENTATION) + for source in data["sources"]: + dataset = str(source["dataset"]).upper() + source["depth_corruption_probability"] = ( + 0.3 if dataset in DEPTH_CORRUPTION_DATASETS else 0.0 + ) + return config + + +def validate_matched_augmentation( + base: dict[str, Any], derived: dict[str, Any], resolution_hw: list[int], +) -> None: + if ( + derived["seed"] != base["seed"] + or derived["model"] != base["model"] + or derived["loss"] != base["loss"] + or derived["assets"] != base["assets"] + or derived["precision"] != base["precision"] + or derived["protocol"] != base["protocol"] + or derived["data"]["resolution_hw"] != resolution_hw + or derived["data"]["T"] != base["data"]["T"] + or derived["data"]["batch_size"] != base["data"]["batch_size"] + or derived["data"].get("photometric_augmentation") + != base["data"].get("photometric_augmentation") + or derived["data"].get("validation_sources") + != base["data"].get("validation_sources") + ): + raise ValueError("augmentation config changes a matched invariant") + base_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() + if key != "depth_corruption_probability" + } + for item in base["data"]["sources"] + } + derived_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() + if key != "depth_corruption_probability" + } + for item in derived["data"]["sources"] + } + if base_sources != derived_sources: + raise ValueError("augmentation config changes source mixture/manifests") + if derived["data"]["geometry_augmentation"] != GEOMETRY_AUGMENTATION: + raise ValueError("augmentation affine parameters differ") + + +def data_artifacts_from_configs(configs: list[dict[str, Any]]) -> list[dict[str, str]]: + paths = set() + for config in configs: + for source in config["data"]["sources"]: + paths.add(Path(source["cache_manifest"]).resolve()) + for source in config["data"].get("validation_sources", []): + paths.add(Path(source["cache_manifest"]).resolve()) + return [ + {"path": str(path), "sha256": sha256(path)} for path in sorted(paths) + ] + + +def base_jobs_896( + resolution_state: dict[str, Any], decision: dict[str, Any], +) -> tuple[dict[str, dict[str, Any]], dict[str, Any]]: + evaluation_plan_path = Path(resolution_state["evaluation_plan"]) + if ( + not evaluation_plan_path.is_file() + or resolution_state.get("evaluation_plan_sha256") + != sha256(evaluation_plan_path) + ): + raise ValueError("accepted 896 evaluation plan differs") + evaluation_plan = read_json(evaluation_plan_path) + registry_path = Path(evaluation_plan["training_registry"]["path"]) + if evaluation_plan["training_registry"]["sha256"] != sha256(registry_path): + raise ValueError("accepted 896 training registry differs") + registry = read_json(registry_path) + jobs = { + role: { + "role": role, + "config": job["config"], + "config_sha256": job["config_sha256"], + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + } + for role, job in registry_job_map(registry).items() + } + context = { + "target_step": registry["target_step"], + "source_exposure_batches": registry["matched_source_exposure_batches"], + "source_exposure_frames": registry["matched_source_exposure_frames"], + "data_readiness_state": registry["data_readiness_state"], + "data_readiness_state_sha256": registry["data_readiness_state_sha256"], + "data_finalize_plan_sha256": registry["data_finalize_plan_sha256"], + "data_artifacts": registry["data_artifacts"], + "control": { + "kind": "resolution_896x512_candidate", + "evaluation_plan": { + "path": str(evaluation_plan_path.resolve()), + "sha256": sha256(evaluation_plan_path), + }, + "decision_report": decision, + }, + } + return jobs, context + + +def registry_job_map(registry: dict[str, Any]) -> dict[str, dict[str, Any]]: + result = {item["role"]: item for item in registry["conditions"]} + if set(result) != {"full", *FOLDS}: + raise ValueError("seven matched control roles differ") + return result + + +def base_jobs_640( + decision: dict[str, Any], unified_queue_path: Path, fold_queue_path: Path, + selection_path: Path, +) -> tuple[dict[str, dict[str, Any]], dict[str, Any]]: + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("winner") != decision.get("winner") + or selection.get("winner_checkpoint") != decision.get("control_checkpoint") + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("retained 640 selection evidence differs") + mixture = selection["winner"].split(":", 1)[0] + unified = read_json(unified_queue_path) + folds = read_json(fold_queue_path) + full = next(item for item in unified["conditions"] if item["condition"] == mixture) + if ( + Path(selection["winner_config"]["path"]).resolve() + != Path(full["config"]).resolve() + or selection["winner_config"]["sha256"] != full["config_sha256"] + ): + raise ValueError("retained 640 winner config differs from its mixture") + metadata = checkpoint_metadata( + Path(selection["winner_checkpoint"]["path"]), + selection["winner_checkpoint"]["sha256"], + selection["winner_config"]["sha256"], + ) + initialization = metadata["initialization_checkpoint"] + if ( + Path(initialization.get("path", "")).resolve() + != Path(full["initialization_checkpoint"]).resolve() + or initialization.get("sha256") != full["initialization_checkpoint_sha256"] + ): + raise ValueError("retained 640 initialization differs") + jobs = { + "full": { + "role": "full", "config": full["config"], + "config_sha256": full["config_sha256"], + "initialization_checkpoint": full["initialization_checkpoint"], + "initialization_checkpoint_sha256": full[ + "initialization_checkpoint_sha256" + ], + } + } + fold_jobs = {item["condition"]: item for item in folds["conditions"]} + for fold in FOLDS: + item = fold_jobs[f"{mixture}_{fold}"] + jobs[fold] = { + "role": fold, "config": item["config"], + "config_sha256": item["config_sha256"], + "initialization_checkpoint": full["initialization_checkpoint"], + "initialization_checkpoint_sha256": full[ + "initialization_checkpoint_sha256" + ], + } + readiness = Path(unified["data_readiness_state"]) + if not readiness.is_file(): + raise ValueError("retained 640 data readiness is missing") + configs = [ + yaml.safe_load(Path(item["config"]).read_text(encoding="utf-8")) + for item in jobs.values() + ] + context = { + "target_step": metadata["step"], + "source_exposure_batches": metadata["source_exposure_batches"], + "source_exposure_frames": metadata["source_exposure_frames"], + "data_readiness_state": str(readiness.resolve()), + "data_readiness_state_sha256": sha256(readiness), + "data_finalize_plan_sha256": unified["data_finalize_plan_sha256"], + "data_artifacts": data_artifacts_from_configs(configs), + "control": { + "kind": "frozen_640_winner", + "selection_report": { + "path": str(selection_path.resolve()), "sha256": sha256(selection_path), + }, + "control_evidence": next( + item for item in selection["candidates"] + if item["id"] == selection["winner"] + ), + "decision_report": decision, + }, + } + return jobs, context + + +def build_registry( + *, resolution_controller_plan_path: Path, + resolution_controller_state_path: Path, augmentation_plan_path: Path, + unified_queue_path: Path, fold_queue_path: Path, selection_path: Path, + output_root: Path, +) -> dict[str, Any]: + resolution_plan = read_json(resolution_controller_plan_path) + resolution_state = read_json(resolution_controller_state_path) + decision_path = Path(resolution_state.get("decision_report", {}).get("path", "")) + if ( + resolution_state.get("status") != "complete" + or resolution_state.get("plan_sha256") != sha256(resolution_controller_plan_path) + or resolution_state.get("official_test_used") is not False + or resolution_state.get("h2o_official_validation_used") is not False + or Path(resolution_plan["decision_report"]).resolve() != decision_path.resolve() + or not decision_path.is_file() + or resolution_state.get("decision_report", {}).get("sha256") + != sha256(decision_path) + ): + raise ValueError("resolution decision controller is not complete and bound") + decision = read_json(decision_path) + if ( + decision.get("status") != "complete" + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution decision report is not complete and isolated") + resolution_hw = decision["accepted_resolution_hw"] + if resolution_hw not in ([368, 640], [512, 896]): + raise ValueError("resolution decision value differs") + augmentation_plan = read_json(augmentation_plan_path) + if ( + augmentation_plan.get("official_test_used") is not False + or { + key: value for key, value in augmentation_plan.get("candidate", {}).get( + "geometry_augmentation", {} + ).items() if key in GEOMETRY_AUGMENTATION + } != GEOMETRY_AUGMENTATION + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "applicable_sources" + ) != ["H2O", "HOI4D"] + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "probability" + ) != 0.3 + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "conditions" + ) != list(DEPTH_CORRUPTIONS) + ): + raise ValueError("shared augmentation frozen plan differs") + + if resolution_hw == [512, 896]: + base_jobs, context = base_jobs_896(resolution_state, decision) + else: + base_jobs, context = base_jobs_640( + decision, unified_queue_path, fold_queue_path, selection_path, + ) + mixture = decision["winner"].split(":", 1)[0] + resolution_label = "896x512" if resolution_hw == [512, 896] else "640x368" + config_root = output_root / resolution_label / "phase9" / "configs" + conditions = [] + base_configs = [] + for role in ("full", *FOLDS): + job = base_jobs[role] + path = Path(job["config"]) + if not path.is_file() or sha256(path) != job["config_sha256"]: + raise ValueError(f"augmentation base config differs: {role}") + base = yaml.safe_load(path.read_text(encoding="utf-8")) + condition = f"S8A_{mixture}_{role}" + derived = derive_augmentation_config( + base, condition=condition, resolution_hw=resolution_hw, + resolution_decision_sha256=sha256(decision_path), + ) + validate_matched_augmentation(base, derived, resolution_hw) + config_path = config_root / f"{condition.lower()}.yaml" + errors = validate_phase9_unified_contract(derived, config_path) + if errors: + raise ValueError("; ".join(errors)) + write_config(config_path, derived) + run_dir = output_root / resolution_label / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"augmentation run exists before freeze: {run_dir}") + target_step = int(context["target_step"]) + conditions.append({ + "condition": condition, "role": role, + "config": str(config_path.resolve()), "config_sha256": sha256(config_path), + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / resolution_label / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": context[ + "source_exposure_batches" + ], + "expected_source_exposure_frames": context["source_exposure_frames"], + }) + base_configs.append(base) + data_artifacts = data_artifacts_from_configs(base_configs) + context_artifacts = { + item["path"]: item["sha256"] for item in context["data_artifacts"] + } + if any( + context_artifacts.get(item["path"]) != item["sha256"] + for item in data_artifacts + ): + raise ValueError("augmentation data artifacts differ from control") + # Preserve the stronger control set, including heldout and fold-index hashes. + data_artifacts = context["data_artifacts"] + return { + "schema_version": "phase9_shared_augmentation_training_registry_v1", + "status": "frozen_ready", + "created_utc": decision["created_utc"], + "winner": decision["winner"], + "resolution_hw": resolution_hw, + "resolution_decision": { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + }, + "shared_augmentation_plan": { + "path": str(augmentation_plan_path.resolve()), + "sha256": sha256(augmentation_plan_path), + }, + "control": context["control"], + "target_step": context["target_step"], + "matched_source_exposure_batches": context["source_exposure_batches"], + "matched_source_exposure_frames": context["source_exposure_frames"], + "data_readiness_state": context["data_readiness_state"], + "data_readiness_state_sha256": context["data_readiness_state_sha256"], + "data_finalize_plan_sha256": context["data_finalize_plan_sha256"], + "data_artifacts": data_artifacts, + "gate": { + "macro_absolute_mm_must_strictly_improve": True, + "worst_domain_relative_regression_limit": ( + WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT + ), + "stage9_preceding_mechanism_requires_worst_strict_improvement": True, + }, + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--resolution-controller-plan", type=Path, required=True) + parser.add_argument("--resolution-controller-state", type=Path, required=True) + parser.add_argument("--augmentation-plan", type=Path, required=True) + parser.add_argument("--unified-queue", type=Path, required=True) + parser.add_argument("--fold-queue", type=Path, required=True) + parser.add_argument("--selection-report", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + registry = build_registry( + resolution_controller_plan_path=args.resolution_controller_plan, + resolution_controller_state_path=args.resolution_controller_state, + augmentation_plan_path=args.augmentation_plan, + unified_queue_path=args.unified_queue, + fold_queue_path=args.fold_queue, + selection_path=args.selection_report, + output_root=args.output_root, + ) + if args.output_registry.exists(): + if read_json(args.output_registry) != registry: + raise ValueError("existing augmentation registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_registry_state_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_shared_augmentation_registry_state_v1", + "status": "complete", "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "resolution_hw": registry["resolution_hw"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/build_sota_ground_truth.py b/home/wuyifan/EgoNet_train_20261008/scripts/build_sota_ground_truth.py new file mode 100644 index 0000000000000000000000000000000000000000..d859aa4924bd3147b0a16d71a3f7164a13e2f25e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/build_sota_ground_truth.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Build the immutable H2O GT bundle shared by all SOTA baseline evaluations.""" + +from __future__ import annotations + +import argparse +import hashlib +from pathlib import Path + +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import ( + load_float_record, + load_joint_record, + load_mano_record, +) +from foundation_hand.evaluation.sota import GroundTruthBundle, load_frame_index +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models.mano import ManoCameraLayer + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=256) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + keys, takes, frame_ids = load_frame_index(args.manifest) + count = len(keys) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + pose = np.zeros((count, 2, 48), dtype=np.float32) + shape = np.zeros((count, 2, 10), dtype=np.float32) + valid = np.zeros((count, 2), dtype=bool) + intrinsics = np.zeros((count, 3, 3), dtype=np.float32) + intrinsics_cache: dict[str, np.ndarray] = {} + + for index, (take_name, frame_id) in enumerate(zip(takes, frame_ids, strict=True)): + take = args.root / str(take_name) + stem = f"{int(frame_id):06d}" + joint_record = load_joint_record(take / "hand_pose" / f"{stem}.txt") + mano_record = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + if not np.array_equal(joint_record.annotation_valid, mano_record.annotation_valid): + raise ValueError(f"Joint/MANO validity mismatch: {keys[index]}") + valid[index] = joint_record.annotation_valid + joints[index] = joint_record.joints_camera_m + pose[index] = mano_record.pose_axis_angle + shape[index] = mano_record.shape + if str(take_name) not in intrinsics_cache: + values = load_float_record(take / "cam_intrinsics.txt") + intrinsics_cache[str(take_name)] = intrinsics_from_h2o(values)[0] + intrinsics[index] = intrinsics_cache[str(take_name)] + + joints[~valid] = np.nan + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + device = torch.device(args.device) + mano = ManoCameraLayer(args.mano_root).to(device).eval() + for start in range(0, count, args.batch_size): + end = min(start + args.batch_size, count) + pose_tensor = torch.from_numpy(pose[start:end]).to(device) + shape_tensor = torch.from_numpy(shape[start:end]).to(device) + wrist_tensor = torch.from_numpy(np.nan_to_num(joints[start:end, :, 0])).to(device) + with torch.no_grad(): + batch_vertices, _ = mano( + axis_angle_to_matrix(pose_tensor.reshape(end - start, 2, 16, 3)), + shape_tensor, + wrist_tensor, + ) + vertices[start:end] = batch_vertices.cpu().numpy() + vertices[~valid] = np.nan + + bundle = GroundTruthBundle( + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + annotation_valid=valid, + intrinsics=intrinsics, + metadata={ + "source": "H2O official validation cam4", + "official_test_used": False, + "manifest": str(args.manifest.resolve()), + "manifest_sha256": sha256(args.manifest), + "frames": count, + "runs": len(args.manifest.read_text(encoding="utf-8").splitlines()), + "takes": len(set(map(str, takes.tolist()))), + "joint_order": "H2O/OpenPose wrist-thumb-index-middle-ring-pinky", + "units": "meters", + }, + ) + bundle.save(args.output) + print(f"saved {count} frames to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase4_jitter_predictions.py b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase4_jitter_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..c638edc649e36a24ec91b04ad2594e22ffe09fcd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase4_jitter_predictions.py @@ -0,0 +1,399 @@ +#!/usr/bin/env python3 +"""Cache hash-bound raw official-validation predictions for jitter evaluation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +CACHE_VERSION = 1 +FPS = 30.0 +FRAME_ARRAYS = ( + "clip_index", + "frame_id", + "frame_valid", + "K", + "pred_rotation_matrices", + "pred_shape", + "pred_wrist_translation", + "pred_joints_camera", + "pred_vertices_camera", + "pred_direct_2d_px", + "target_rotation_matrices", + "target_shape", + "target_wrist_translation", + "target_joints_camera", + "target_vertices_camera", + "target_2d_px", + "joint_annotation_valid", + "joint_element_valid", + "mano_annotation_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def take_slug(take: str) -> str: + parts = Path(take).parts + if len(parts) != 4 or parts[-1] != "cam4": + raise ValueError(f"unexpected H2O take: {take}") + return "__".join(parts) + + +def manifest_frame_count(path: Path) -> int: + identities: set[tuple[str, int]] = set() + rows = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + record = json.loads(line) + take = str(record["take"]) + for frame_id in record["frame_ids"]: + identity = (take, int(frame_id)) + if identity in identities: + raise ValueError(f"duplicate manifest frame: {take}/{int(frame_id)}") + identities.add(identity) + rows += 1 + if rows == 0: + raise ValueError("prediction cache manifest is empty") + return rows + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def apply_input_condition( + batch: dict[str, Any], condition: str, +) -> dict[str, Any]: + if condition == "complete": + return batch + model_batch = dict(batch) + if condition == "missing_depth": + model_batch["depth_available"] = torch.zeros_like(batch["depth_available"]) + model_batch["depth_m"] = torch.zeros_like(batch["depth_m"]) + model_batch["depth_pixel_valid"] = torch.zeros_like(batch["depth_pixel_valid"]) + return model_batch + if condition == "missing_k": + model_batch["K_available"] = torch.zeros_like(batch["K_available"]) + identity = torch.eye(3, dtype=batch["K"].dtype, device=batch["K"].device) + model_batch["K"] = identity.expand_as(batch["K"]).clone() + return model_batch + raise ValueError(f"unsupported input condition: {condition}") + + +def target_geometry( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for jitter cache targets") + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, joints = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + return rotations, vertices, joints + + +def validate_cache_arrays( + arrays: dict[str, np.ndarray], + *, + take: str, + expected_frame_ids: list[int], + checkpoint_sha256: str, + config_sha256: str, + manifest_sha256: str, + input_condition: str = "complete", +) -> None: + missing = sorted(set(FRAME_ARRAYS) - arrays.keys()) + if missing: + raise ValueError(f"raw jitter cache is missing arrays: {missing}") + if int(arrays["cache_version"]) != CACHE_VERSION: + raise ValueError("raw jitter cache version mismatch") + scalar_expectations = { + "take": take, + "checkpoint_sha256": checkpoint_sha256, + "config_sha256": config_sha256, + "manifest_sha256": manifest_sha256, + } + for key, expected in scalar_expectations.items(): + if str(arrays[key]) != expected: + raise ValueError(f"raw jitter cache {key} mismatch") + if input_condition != "complete" and str(arrays.get("input_condition", "")) != input_condition: + raise ValueError("raw jitter cache input condition mismatch") + frame_ids = arrays["frame_id"].astype(np.int64).tolist() + if frame_ids != expected_frame_ids or len(frame_ids) != len(set(frame_ids)): + raise ValueError(f"raw jitter cache frame sequence mismatch for {take}") + for key in FRAME_ARRAYS: + if arrays[key].shape[0] != len(frame_ids): + raise ValueError(f"raw jitter cache time dimension mismatch: {key}") + if np.issubdtype(arrays[key].dtype, np.floating): + finite = np.isfinite(arrays[key]) + if key.startswith("target_"): + # Invalid annotations are intentionally retained as NaN. + continue + if not finite.all(): + raise ValueError(f"raw jitter cache prediction is non-finite: {key}") + + +def load_valid_cache( + path: Path, + **expected: object, +) -> dict[str, np.ndarray] | None: + if not path.is_file(): + return None + try: + with np.load(path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + validate_cache_arrays(arrays, **expected) + except (OSError, KeyError, ValueError): + return None + return arrays + + +def build_model( + config: dict[str, Any], checkpoint: Path, device: torch.device, +) -> tuple[BimanualReconstructionModel, int]: + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(checkpoint, model, optimizer=None, map_location=device) + return model, int(state["step"]) + + +def infer_take( + *, + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + input_condition: str, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + subset = Subset(dataset, clip_indices) + loader = DataLoader( + subset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + for global_clip_index, batch_cpu in zip(clip_indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + target_rotations, target_vertices, _ = target_geometry(batch, model) + model_batch = apply_input_condition(batch, input_condition) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(model_batch) + valid_times = int(batch["frame_valid"][0].sum()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor( + (width, height), device=device, + ) + values: dict[str, torch.Tensor] = { + "clip_index": torch.full( + (valid_times,), global_clip_index, device=device, dtype=torch.int64, + ), + "frame_id": batch["frame_id"][0, :valid_times], + "frame_valid": batch["frame_valid"][0, :valid_times], + "K": batch["K"][0, :valid_times], + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0, :valid_times], + "pred_shape": prediction["mano_shape"][0, :valid_times], + "pred_wrist_translation": prediction["wrist_root_translation"][0, :valid_times], + "pred_joints_camera": prediction["joints_camera"][0, :valid_times], + "pred_vertices_camera": prediction["vertices_camera"][0, :valid_times], + "pred_direct_2d_px": direct_2d[0, :valid_times], + "target_rotation_matrices": target_rotations[0, :valid_times], + "target_shape": batch["mano_shape"][0, :valid_times], + "target_wrist_translation": batch["wrist_root_translation"][0, :valid_times], + "target_joints_camera": batch["joint3d_camera"][0, :valid_times], + "target_vertices_camera": target_vertices[0, :valid_times], + "target_2d_px": batch["joint2d"][0, :valid_times], + "joint_annotation_valid": batch["joint_annotation_valid"][0, :valid_times], + "joint_element_valid": batch["joint_element_valid"][0, :valid_times], + "mano_annotation_valid": batch["mano_annotation_valid"][0, :valid_times], + } + for key, value in values.items(): + array = value.detach().float().cpu().numpy() if value.is_floating_point() else value.cpu().numpy() + chunks[key].append(array) + return {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), default=0) + parser.add_argument("--max-clips", type=int) + parser.add_argument( + "--input-condition", choices=("complete", "missing_depth", "missing_k"), + default="complete", + ) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("jitter cache is hard-gated to official validation") + if args.max_clips is not None and args.max_clips < 1: + parser.error("--max-clips must be positive") + if not torch.cuda.is_available(): + parser.error("CUDA is required") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + config_hash = sha256(args.config) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (int(config["data"]["T"]),), (int(config["data"]["stride"]),), + max_clips=args.max_clips, + oracle_crop_enabled=config["model"].get("oracle_crop_mode", "none") != "none", + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + expected_frames = { + take: [ + frame_id + for index in indices + for frame_id in dataset.clips[index].frame_ids + ] + for take, indices in indices_by_take.items() + } + if any(len(values) != len(set(values)) for values in expected_frames.values()): + raise ValueError("jitter cache requires non-overlapping inference clips") + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model: BimanualReconstructionModel | None = None + checkpoint_step: int | None = None + records = [] + for take_index, (take, clip_indices) in enumerate(indices_by_take.items(), start=1): + output = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "manifest_sha256": manifest_hash, + "input_condition": args.input_condition, + } + arrays = load_valid_cache(output, **expected) + status = "reused" + if arrays is None: + if output.exists(): + raise ValueError(f"existing jitter cache failed validation: {output}") + if model is None: + model, checkpoint_step = build_model(config, args.checkpoint, device) + arrays = infer_take( + dataset=dataset, clip_indices=clip_indices, model=model, + device=device, dtype=dtype, input_condition=args.input_condition, + ) + arrays.update({ + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + "take": np.asarray(take), + "fps": np.asarray(FPS, dtype=np.float32), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "manifest_sha256": np.asarray(manifest_hash), + "input_condition": np.asarray(args.input_condition), + }) + validate_cache_arrays(arrays, **expected) + save_npz_atomic(output, arrays) + status = "written" + records.append({ + "take": take, "clips": len(clip_indices), + "frames": len(expected_frames[take]), "path": str(output), + "sha256": sha256(output), "status": status, + }) + print( + f"[{take_index}/{len(indices_by_take)}] {take}: " + f"{records[-1]['frames']} frames ({status})", + flush=True, + ) + if checkpoint_step is None: + # Read the step only when every cache was reused. + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + checkpoint_step = int(state["step"]) + total_frames = sum(record["frames"] for record in records) + full_validation = args.max_clips is None + expected_full_frames = manifest_frame_count(args.manifest) + if full_validation and total_frames != expected_full_frames: + raise ValueError( + "official-validation cache does not cover every manifest frame exactly once" + ) + report = { + "status": "complete", + "official_test_used": False, + "split_role": "official_validation", + "scope": "full" if full_validation else "smoke", + "fps": FPS, + "temporal_length": int(config["data"]["T"]), + "clip_boundary_filter_reset_required": True, + "input_condition": args.input_condition, + "missing_rgb_status": "unsupported_no_rgb_availability_or_training_dropout", + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": checkpoint_step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, + stdout=subprocess.PIPE, check=False, + ).stdout.strip(), + "clips": len(dataset), "frames": total_frames, + "expected_manifest_frames": expected_full_frames, "takes": records, + } + (args.output_dir / "cache_manifest.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "clips": report["clips"], + "frames": report["frames"], "takes": len(records), + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase6_sequence_predictions.py b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase6_sequence_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..5914ff7c6988c0f4da8b47b226fbbf1b7c0337e7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase6_sequence_predictions.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Cache bounded-window Phase 6 sequence predictions in the frozen raw schema.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from scripts.cache_phase4_jitter_predictions import ( + CACHE_VERSION, + FPS, + build_model, + load_valid_cache, + manifest_frame_count, + move_to_device, + save_npz_atomic, + sha256, + take_slug, + target_geometry, + validate_cache_arrays, +) + + +def validate_sequence_config(config: dict, mode: str) -> None: + """Validate model causality; frame iteration itself always supplies T=1.""" + + attention_mode = config["model"].get("temporal_attention_mode", "bidirectional") + expected_attention = "causal" if mode == "causal" else "bidirectional" + if attention_mode != expected_attention: + raise ValueError("sequence mode differs from config temporal attention mode") + + +def offline_stride(window: int, mode: str) -> int | None: + return max(window // 2, 1) if mode == "offline" else None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--max-takes", type=int) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("sequence cache is hard-gated to official validation") + if args.window < 1: + parser.error("window must be positive") + if args.max_takes is not None and args.max_takes < 1: + parser.error("max-takes must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + try: + validate_sequence_config(config, args.mode) + except ValueError as error: + parser.error(str(error)) + + config_hash = sha256(args.config) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (1,), (1,), + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + if args.max_takes is not None: + indices_by_take = dict(list(indices_by_take.items())[: args.max_takes]) + expected_frames = { + take: [dataset.clips[index].frame_ids[0] for index in indices] + for take, indices in indices_by_take.items() + } + if any(len(ids) != len(set(ids)) for ids in expected_frames.values()): + raise ValueError("sequence cache input contains duplicate take/frame identities") + + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model = None + checkpoint_step = None + records = [] + maximum_gpu_window = 0 + maximum_cpu_buffer = 0 + for take_index, (take, indices) in enumerate(indices_by_take.items(), start=1): + output_path = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "manifest_sha256": manifest_hash, + "input_condition": "complete", + } + arrays = load_valid_cache(output_path, **expected) + status = "reused" + if arrays is None: + if output_path.exists(): + raise ValueError(f"existing sequence cache failed validation: {output_path}") + if model is None: + model, checkpoint_step = build_model(config, args.checkpoint, device) + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.mode, window_size=args.window, + offline_stride=offline_stride(args.window, args.mode), + ), + device=device, autocast_dtype=dtype, + ) + target_chunks: dict[str, list[np.ndarray]] = defaultdict(list) + loader = DataLoader( + Subset(dataset, indices), batch_size=1, shuffle=False, + num_workers=0, collate_fn=collate_h2o_clips, pin_memory=True, + ) + + def frames(): + for global_index, batch_cpu in zip(indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + rotations, vertices, _ = target_geometry(batch, model) + values = { + # One output file is one continuous take. Frame gaps and + # frame_valid, not the source dataset index, delimit segments. + "clip_index": np.asarray([0], dtype=np.int64), + "frame_id": batch_cpu["frame_id"][0].numpy(), + "frame_valid": batch_cpu["frame_valid"][0].numpy(), + "K": batch_cpu["K"][0].numpy(), + "target_rotation_matrices": rotations[0].float().cpu().numpy(), + "target_shape": batch_cpu["mano_shape"][0].numpy(), + "target_wrist_translation": batch_cpu["wrist_root_translation"][0].numpy(), + "target_joints_camera": batch_cpu["joint3d_camera"][0].numpy(), + "target_vertices_camera": vertices[0].float().cpu().numpy(), + "target_2d_px": batch_cpu["joint2d"][0].numpy(), + "joint_annotation_valid": batch_cpu["joint_annotation_valid"][0].numpy(), + "joint_element_valid": batch_cpu["joint_element_valid"][0].numpy(), + "mano_annotation_valid": batch_cpu["mano_annotation_valid"][0].numpy(), + } + for key, value in values.items(): + target_chunks[key].append(value) + yield batch_cpu + + prediction = runner.infer(frames()) + height, width = config["data"]["resolution_hw"] + predicted = { + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0].float().numpy(), + "pred_shape": prediction["mano_shape"][0].float().numpy(), + "pred_wrist_translation": prediction["wrist_root_translation"][0].float().numpy(), + "pred_joints_camera": prediction["joints_camera"][0].float().numpy(), + "pred_vertices_camera": prediction["vertices_camera"][0].float().numpy(), + "pred_direct_2d_px": ( + prediction["joint2d_norm"][0].float() + * torch.tensor((width, height)) + ).numpy(), + } + arrays = { + **{key: np.concatenate(values, axis=0) for key, values in target_chunks.items()}, + **predicted, + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + "take": np.asarray(take), + "fps": np.asarray(FPS, dtype=np.float32), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "manifest_sha256": np.asarray(manifest_hash), + "input_condition": np.asarray("complete"), + "sequence_mode": np.asarray(args.mode), + "sequence_window": np.asarray(args.window, dtype=np.int32), + } + validate_cache_arrays(arrays, **expected) + save_npz_atomic(output_path, arrays) + maximum_gpu_window = max(maximum_gpu_window, runner.maximum_resident_frames) + maximum_cpu_buffer = max(maximum_cpu_buffer, runner.maximum_input_buffer_frames) + status = "written" + records.append({ + "take": take, "clips": len(indices), "frames": len(expected_frames[take]), + "path": str(output_path), "sha256": sha256(output_path), "status": status, + }) + print(f"[{take_index}/{len(indices_by_take)}] {take} ({status})", flush=True) + + if checkpoint_step is None: + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + checkpoint_step = int(state["step"]) + total_frames = sum(record["frames"] for record in records) + expected_total = ( + manifest_frame_count(args.manifest) if args.max_takes is None + else sum(len(frame_ids) for frame_ids in expected_frames.values()) + ) + if total_frames != expected_total: + raise ValueError("sequence cache does not cover the frozen manifest exactly") + report = { + "status": "complete", + "experiment": "P6_S5_length_generalized_inference", + "official_test_used": False, + "official_validation_used_for_selection": False, + "split_role": "official_validation", + "scope": "full" if args.max_takes is None else "smoke", + "fps": FPS, + "temporal_length": 1, + "sequence_mode": args.mode, + "sequence_window": args.window, + "offline_stride": offline_stride(args.window, args.mode), + "stitching": "center" if args.mode == "offline" else None, + "maximum_gpu_window_frames": maximum_gpu_window, + "maximum_cpu_input_buffer_frames": maximum_cpu_buffer, + "input_condition": "complete", + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": checkpoint_step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + "clips": len(dataset), "frames": total_frames, + "expected_manifest_frames": expected_total, "takes": records, + } + (args.output_dir / "cache_manifest.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "mode": args.mode, "window": args.window, + "frames": total_frames, "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase7_h2o_train.py b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase7_h2o_train.py new file mode 100644 index 0000000000000000000000000000000000000000..14a83bba28b96456e9238ece26d398545cc921eb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase7_h2o_train.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Build a bounded canonical cache from H2O official train only.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import math +from pathlib import Path +import time + +import numpy as np + +from foundation_hand.data import H2OCam4Dataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from scripts.cache_phase7_hot3d import ( + validate_cached_resolution, + validated_target_hw, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_train_manifest_path(path: Path) -> None: + if path.name != "official_train.jsonl": + raise ValueError("H2O adaptation cache requires canonical official_train.jsonl") + + +def center_out(values: list[int]) -> list[int]: + values = sorted(values) + center = (len(values) - 1) // 2 + order = [center] + distance = 1 + while len(order) < len(values): + if center + distance < len(values): + order.append(center + distance) + if center - distance >= 0: + order.append(center - distance) + distance += 1 + return [values[index] for index in order] + + +def balanced_clip_indices( + clips: list, count: int, max_recordings: int, +) -> list[int]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, clip in enumerate(clips): + parts = Path(clip.take).parts + groups[(parts[0], "/".join(parts[:-1]))].append(index) + strata: dict[str, list[tuple[str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[0]].append(key) + selected_groups: list[tuple[str, str]] = [] + cursor = 0 + while len(selected_groups) < min(max_recordings, len(groups)): + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected_groups.append(strata[subject][cursor]) + progress = True + if len(selected_groups) == max_recordings: + break + if not progress: + break + cursor += 1 + ordered = {key: center_out(groups[key]) for key in selected_groups} + selected = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in selected_groups: + if cursor < len(ordered[key]): + selected.append(ordered[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def rgb_uint8(rgb: np.ndarray) -> np.ndarray: + image = np.transpose(rgb, (0, 2, 3, 1)) + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int, required=True) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument("--resume", action="store_true") + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + validate_train_manifest_path(args.source_manifest) + if min(args.clips, args.max_recordings) <= 0: + parser.error("clip and recording counts must be positive") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + dataset = H2OCam4Dataset( + args.root, args.source_manifest, target_hw=target_hw, + clip_lengths=(8,), strides=(1,), + ) + candidate_count = min( + len(dataset), args.clips + max(32, math.ceil(args.clips * 0.1)), + ) + selected = balanced_clip_indices(dataset.clips, candidate_count, args.max_recordings) + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced H2O train clips are available") + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", "vertices_camera", + } + cached: dict[int, dict] = {} + skipped: list[int] = [] + started = time.monotonic() + for position, source_index in enumerate(selected, 1): + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise RuntimeError(f"invalid existing cache: {output}") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + else: + sample = dataset[(source_index, 0)] + has_supervision = bool(sample["translation_valid"].any()) + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + clip = dataset.clips[source_index] + parts = Path(clip.take).parts + if has_supervision: + cached[source_index] = { + "dataset_id": "H2O", + "subject_id": parts[0], + "sequence_id": "/".join(parts[1:-1]), + "physical_recording_id": "/".join(parts[:-1]), + "camera_id": "cam4", "stream_id": "cam4-rgb", + "headset_id": "H2O-ego", "source_clip_index": source_index, + "source_group_key": f"H2O/{'/'.join(parts[:-1])}", + "resolution_hw": list(target_hw), + "cache_path": str(output.resolve()), "cache_sha256": sha256(output), + } + else: + skipped.append(source_index) + if position % 10 == 0 or position == len(selected): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": position, "requested": len(selected), + "cached": len(cached), "skipped_no_supervision": len(skipped), + "clips_per_second": position / elapsed, + }), flush=True) + ordered_valid = [index for index in selected if index in cached][:args.clips] + if len(ordered_valid) == args.clips: + break + manifest = args.output_dir / "cache_manifest.jsonl" + temporary_manifest = manifest.with_suffix(".tmp") + temporary_manifest.write_text( + "".join(json.dumps(cached[index], sort_keys=True) + "\n" for index in ordered_valid), + encoding="utf-8", + ) + temporary_manifest.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": "complete" if len(ordered_valid) == args.clips else "insufficient_valid_clips", + "dataset": "H2O", "split_role": "official_train", + "source_manifest": { + "path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest), + }, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "requested_clips": args.clips, "candidate_clips_processed": position, + "resolution_hw": list(target_hw), + "cached_clips": len(ordered_valid), "valid_candidate_files": len(cached), + "recordings": len({cached[index]["physical_recording_id"] for index in ordered_valid}), + "skipped_no_supervision": skipped, + "wall_seconds": elapsed, "clips_per_second": position / elapsed, + "bytes": sum(Path(cached[index]["cache_path"]).stat().st_size for index in ordered_valid), + "resume_invocation": bool(args.resume), + "h2o_official_validation_used": False, "official_test_used": False, + } + (args.output_dir / "cache_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase7_hot3d.py b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase7_hot3d.py new file mode 100644 index 0000000000000000000000000000000000000000..7f6273de04231e6edb06c4fbfdacf1fe2547e592 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase7_hot3d.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Build a bounded, source-hash-bound HOT3D clip cache.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +import time + +import numpy as np + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def validated_target_hw(values: tuple[int, int] | list[int]) -> tuple[int, int]: + """Validate the full-frame cache resolution used by every source writer.""" + + if len(values) != 2: + raise ValueError("target resolution must contain height and width") + height, width = (int(value) for value in values) + if min(height, width) <= 0: + raise ValueError("target resolution dimensions must be positive") + return height, width + + +def validate_cached_resolution( + archive: np.lib.npyio.NpzFile, target_hw: tuple[int, int], +) -> None: + if "image_hw" not in archive.files: + raise ValueError("cached payload lacks image_hw") + image_hw = tuple(int(value) for value in np.asarray(archive["image_hw"]).reshape(-1)) + if image_hw != target_hw: + raise ValueError( + f"cached payload resolution {image_hw} does not match requested {target_hw}" + ) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def sha256_json(value: object) -> str: + payload = json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + return hashlib.sha256(payload).hexdigest() + + +def decode_position_slice( + decode_order: list[int], position_range: tuple[int, int] | None, +) -> tuple[list[int], tuple[int, int] | None]: + if position_range is None: + return decode_order, None + start, stop = position_range + if start < 0 or stop <= start or stop > len(decode_order): + raise ValueError( + f"invalid prefill position range [{start}, {stop}) for {len(decode_order)} candidates" + ) + return decode_order[start:stop], (start, stop) + + +def balanced_recording_keys( + groups: dict[tuple[str, str, str], list[int]], max_recordings: int, +) -> list[tuple[str, str, str]]: + strata: dict[tuple[str, str], list[tuple[str, str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[:2]].append(key) + selected: list[tuple[str, str, str]] = [] + cursor = 0 + while len(selected) < min(max_recordings, len(groups)): + progress = False + for stratum in sorted(strata): + if cursor < len(strata[stratum]): + selected.append(strata[stratum][cursor]) + progress = True + if len(selected) == max_recordings: + break + if not progress: + break + cursor += 1 + return selected + + +def balanced_indices( + rows: list[dict], count: int, max_recordings: int | None = None, +) -> list[int]: + groups: dict[tuple[str, str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + groups[(row["headset"], row["participant_id"], row["recording_id"])].append(index) + keys = sorted(groups) + if max_recordings is not None: + if max_recordings <= 0: + raise ValueError("max_recordings must be positive") + keys = balanced_recording_keys(groups, max_recordings) + selected: list[int] = [] + cursor = 0 + while len(selected) < min(count, len(rows)): + progress = False + for key in keys: + values = groups[key] + if cursor < len(values): + selected.append(values[cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def cache_candidate_count(requested: int, available: int) -> int: + return min(available, requested + max(64, int(np.ceil(requested * 0.1)))) + + +def first_valid_indices( + selected: list[int], cached: dict[int, dict], requested: int, +) -> list[int]: + return [index for index in selected if index in cached][:requested] + + +def should_stop_decoding( + selected: list[int], cached: dict[int, dict], requested: int, + decode_all_candidates: bool, +) -> bool: + """Stop early only when full candidate decoding was not requested.""" + + return ( + not decode_all_candidates + and len(first_valid_indices(selected, cached, requested)) == requested + ) + + +def rgb_uint8(rgb: np.ndarray) -> np.ndarray: + image = np.transpose(rgb, (0, 2, 3, 1)) + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument( + "--decode-all-candidates", action="store_true", + help="Decode the complete balanced overdraw pool before freezing the valid prefix.", + ) + parser.add_argument( + "--prefill-position-range", type=int, nargs=2, metavar=("START", "STOP"), + help=( + "Decode a zero-based half-open slice of the frozen candidate order into " + "a staging cache; no deployable cache manifest is produced." + ), + ) + parser.add_argument("--resume", action="store_true") + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + if args.clips < 1: + parser.error("--clips must be positive") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing output clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + dataset = HOT3DClipDataset( + args.root, args.source_manifest, args.toolkit_root, args.mano_root, + K_input_dropout=0.0, provider_cache_size=2, target_hw=target_hw, + ) + candidate_count = cache_candidate_count(args.clips, len(dataset.rows)) + selected = balanced_indices(dataset.rows, candidate_count, args.max_recordings) + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced candidates are available") + # Decode in recording order to avoid reopening VRS files for every clip. + full_decode_order = sorted( + selected, + key=lambda index: ( + dataset.rows[index]["recording_id"], + dataset.rows[index]["stream_id"], + dataset.rows[index]["timestamps_ns"][0], + ), + ) + prefill_range = ( + tuple(args.prefill_position_range) + if args.prefill_position_range is not None else None + ) + try: + decode_order, prefill_range = decode_position_slice( + full_decode_order, prefill_range, + ) + except ValueError as error: + parser.error(str(error)) + if prefill_range is not None and not args.decode_all_candidates: + parser.error("--prefill-position-range requires --decode-all-candidates") + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", + } + cache_rows: dict[int, dict] = {} + skipped_no_supervision: list[int] = [] + started = time.monotonic() + for position, source_index in enumerate(decode_order, 1): + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + try: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise ValueError("required cache arrays missing") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + if { + "source_hand_annotation_present", "geometry_convention_compatible", + }.issubset(archive.files): + masked_geometry = int(np.count_nonzero( + archive["source_hand_annotation_present"] + & ~archive["geometry_convention_compatible"] + )) + else: + # The previous strict writer raised before saving any + # clip containing a regeneration mismatch. + masked_geometry = 0 + except Exception as error: + raise RuntimeError(f"existing resume cache is invalid: {output}: {error}") from error + else: + sample = dataset[(source_index, 0)] + has_supervision = bool(sample["translation_valid"].any()) + masked_geometry = int(( + sample["source_hand_annotation_present"] + & ~sample["geometry_convention_compatible"] + ).sum()) + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + if has_supervision: + row = dataset.rows[source_index] + cache_rows[source_index] = { + "dataset_id": "HOT3D", + "subject_id": row["participant_id"], + "sequence_id": row["recording_id"], + "physical_recording_id": row["recording_id"], + "camera_id": row["stream_id"], + "stream_id": row["stream_id"], + "headset_id": row["headset"], + "source_clip_index": source_index, + "source_group_key": row["group_key"], + "resolution_hw": list(target_hw), + "geometry_masked_hand_frames": masked_geometry, + "cache_path": str(output.resolve()), + "cache_sha256": sha256(output), + } + else: + skipped_no_supervision.append(source_index) + if position % 10 == 0 or position == len(decode_order): + elapsed = time.monotonic() - started + print(json.dumps({ + "decoded": position, "total": len(decode_order), + "cached": len(cache_rows), + "skipped_no_supervision": len(skipped_no_supervision), + "clips_per_second": position / elapsed, + "eta_seconds": (len(decode_order) - position) / (position / elapsed), + }), flush=True) + if prefill_range is None and should_stop_decoding( + selected, cache_rows, args.clips, args.decode_all_candidates, + ): + break + if prefill_range is None: + ordered_cached = first_valid_indices(selected, cache_rows, args.clips) + manifest = args.output_dir / "cache_manifest.jsonl" + status = "complete" if len(ordered_cached) == args.clips else "insufficient_valid_clips" + mode = "deployable_cache" + else: + ordered_cached = [index for index in decode_order if index in cache_rows] + manifest = args.output_dir / "prefill_manifest.jsonl" + status = ( + "complete" + if len(ordered_cached) + len(skipped_no_supervision) == len(decode_order) + else "incomplete_prefill" + ) + mode = "staged_prefill" + temporary_manifest = manifest.with_suffix(".tmp") + temporary_manifest.write_text( + "".join(json.dumps(cache_rows[index], sort_keys=True) + "\n" for index in ordered_cached), + encoding="utf-8", + ) + temporary_manifest.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": status, + "mode": mode, + "official_test_used": False, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "clips": len(ordered_cached), + "candidate_clips_processed": position, + "full_candidate_clips": len(full_decode_order), + "requested_target_clips": args.clips, + "resolution_hw": list(target_hw), + "max_recordings": args.max_recordings, + "candidate_position_range": list(prefill_range) if prefill_range else None, + "candidate_source_indices_sha256": sha256_json(full_decode_order), + "recordings": len({cache_rows[index]["source_group_key"] for index in ordered_cached}), + "skipped_no_supervision": skipped_no_supervision, + "geometry_masked_hand_frames": sum( + cache_rows[index]["geometry_masked_hand_frames"] for index in ordered_cached + ), + "geometry_masked_source_indices": [ + index for index in ordered_cached + if cache_rows[index]["geometry_masked_hand_frames"] + ], + "decode_all_candidates": bool(args.decode_all_candidates), + "resume_invocation": bool(args.resume), + "wall_seconds": elapsed, + "clips_per_second": position / elapsed, + "bytes": sum(Path(cache_rows[index]["cache_path"]).stat().st_size for index in ordered_cached), + } + report_path = args.output_dir / "cache_report.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase7_unified_source.py b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase7_unified_source.py new file mode 100644 index 0000000000000000000000000000000000000000..72c1f102f49f8b1c31bd065469ea43d9f629b1cf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/cache_phase7_unified_source.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Build resumable controlled caches for HOI4D or ARCTIC unified clips.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import math +from pathlib import Path +import time + +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset +from foundation_hand.data.schema import InvalidSourceSampleError +from scripts.cache_phase7_hot3d import ( + rgb_uint8, + validate_cached_resolution, + validated_target_hw, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def center_out(values: list[int]) -> list[int]: + values = sorted(values) + center = (len(values) - 1) // 2 + order = [center] + distance = 1 + while len(order) < len(values): + if center + distance < len(values): + order.append(center + distance) + if center - distance >= 0: + order.append(center - distance) + distance += 1 + return [values[index] for index in order] + + +def balanced_source_indices( + rows: list[dict], count: int, max_recordings: int, +) -> list[int]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + groups[(str(row["subject_id"]), str(row["physical_recording_id"]))].append(index) + strata: dict[str, list[tuple[str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[0]].append(key) + selected_groups: list[tuple[str, str]] = [] + cursor = 0 + while len(selected_groups) < min(max_recordings, len(groups)): + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected_groups.append(strata[subject][cursor]) + progress = True + if len(selected_groups) == max_recordings: + break + if not progress: + break + cursor += 1 + ordered = {key: center_out(groups[key]) for key in selected_groups} + selected: list[int] = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in selected_groups: + if cursor < len(ordered[key]): + selected.append(ordered[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def hand_side_source_indices(rows: list[dict], required_side: str) -> list[int]: + if required_side == "any": + return list(range(len(rows))) + if required_side not in {"left", "right"}: + raise ValueError("required hand side must be any, left or right") + return [ + index for index, row in enumerate(rows) + if any(required_side in sides for sides in row.get("hand_sides", [])) + ] + + +def cache_candidate_count(requested: int, available: int) -> int: + """Overdraw a deterministic candidate pool so invalid clips can be replaced.""" + return min(available, requested + max(32, math.ceil(requested * 0.1))) + + +def first_valid_indices( + selected: list[int], cached: dict[int, dict], requested: int, +) -> list[int]: + return [index for index in selected if index in cached][:requested] + + +def should_stop_decoding( + selected: list[int], cached: dict[int, dict], requested: int, + decode_all_candidates: bool, +) -> bool: + """Stop early only when full candidate decoding was not requested.""" + + return ( + not decode_all_candidates + and len(first_valid_indices(selected, cached, requested)) == requested + ) + + +def cache_completion_status( + requested: int, selected: list[int], cached: dict[int, dict], processed: int, + accept_all_valid: bool, +) -> str: + if accept_all_valid: + return "complete" if processed == len(selected) else "incomplete_source_scan" + return "complete" if len(first_valid_indices(selected, cached, requested)) == requested else "insufficient_valid_clips" + + +def recording_local_batches( + decode_order: list[int], rows: list[dict], batch_size: int = 2, +) -> list[list[int]]: + if batch_size < 1: + raise ValueError("prefetch batch size must be positive") + batches: list[list[int]] = [] + start = 0 + while start < len(decode_order): + recording = rows[decode_order[start]]["physical_recording_id"] + end = start + while ( + end < len(decode_order) + and rows[decode_order[end]]["physical_recording_id"] == recording + ): + end += 1 + group = decode_order[start:end] + batches.extend( + group[offset:offset + batch_size] + for offset in range(0, len(group), batch_size) + ) + start = end + return batches + + +def cache_row( + source_row: dict, source_index: int, output: Path, dataset: str, + target_hw: tuple[int, int], + right_geometry_masked_frames: int = 0, +) -> dict: + return { + "dataset_id": dataset, + "subject_id": str(source_row["subject_id"]), + "sequence_id": str(source_row["physical_recording_id"]), + "physical_recording_id": str(source_row["physical_recording_id"]), + "camera_id": str(source_row["camera_id"]), + "stream_id": str(source_row["camera_id"]), + "headset_id": str(source_row.get("serial_id", source_row["subject_id"])), + "source_clip_index": source_index, + "source_group_key": str(source_row["group_key"]), + "resolution_hw": list(target_hw), + "cache_path": str(output.resolve()), + "cache_sha256": sha256(output), + "right_geometry_masked_frames": int(right_geometry_masked_frames), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int, required=True) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument( + "--required-hand-side", choices=("any", "left", "right"), default="any", + help="Optional source-manifest hand-presence filter before balancing.", + ) + parser.add_argument( + "--prefetch-batch-size", type=int, default=0, + help="Optional exact recording-local prefetch batch; 0 keeps the original decoder.", + ) + parser.add_argument( + "--decode-all-candidates", action="store_true", + help="Decode the complete balanced overdraw pool before freezing the valid prefix.", + ) + parser.add_argument( + "--accept-all-valid", action="store_true", + help="For a full source manifest, cache every valid clip and report invalid clips explicitly.", + ) + parser.add_argument("--resume", action="store_true") + parser.add_argument("--torch-threads", type=int, default=0) + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + if min(args.clips, args.max_recordings) <= 0: + parser.error("clip and recording counts must be positive") + if args.torch_threads < 0: + parser.error("--torch-threads cannot be negative") + if args.torch_threads: + torch.set_num_threads(args.torch_threads) + torch.set_num_interop_threads(1) + if args.dataset == "HOI4D": + if args.root is None: + parser.error("HOI4D requires --root") + dataset = HOI4DClipDataset( + args.root, args.source_manifest, args.mano_root, target_hw=target_hw, + ) + else: + dataset = ARCTICClipDataset( + args.source_manifest, args.mano_root, target_hw=target_hw, + ) + eligible = hand_side_source_indices(dataset.rows, args.required_hand_side) + if args.accept_all_valid and args.clips != len(eligible): + parser.error("--accept-all-valid requires --clips to equal all eligible source clips") + eligible_rows = [dataset.rows[index] for index in eligible] + candidate_count = cache_candidate_count(args.clips, len(eligible_rows)) + selected = [ + eligible[index] + for index in balanced_source_indices( + eligible_rows, candidate_count, args.max_recordings, + ) + ] + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced candidates are available") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + # Group source reads to retain decoded sequence/provider state. + decode_order = sorted( + selected, + key=lambda index: ( + dataset.rows[index]["physical_recording_id"], + dataset.rows[index].get("frame_ids", dataset.rows[index].get("frame_ids_1based"))[0], + ), + ) + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", "geometry_convention_compatible", + } + cached: dict[int, dict] = {} + skipped_no_supervision: list[int] = [] + skipped_invalid_source: list[dict[str, str | int]] = [] + started = time.monotonic() + if args.prefetch_batch_size < 0: + parser.error("--prefetch-batch-size cannot be negative") + batches = ( + recording_local_batches(decode_order, dataset.rows, args.prefetch_batch_size) + if args.dataset == "HOI4D" and args.prefetch_batch_size + else [[index] for index in decode_order] + ) + position = 0 + for batch_indices in batches: + missing = [ + index for index in batch_indices + if not (clips_dir / f"clip_{index:07d}.npz").is_file() + ] + if args.dataset == "HOI4D" and args.prefetch_batch_size and missing: + dataset.prefetch_clip_indices(missing) + for source_index in batch_indices: + position += 1 + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise RuntimeError(f"invalid existing cache: {output}") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + right_geometry_masked_frames = int(np.count_nonzero( + archive["translation_valid"][..., 1] + & ~archive["mano_annotation_valid"][..., 1] + )) if args.dataset == "HOI4D" else 0 + else: + try: + sample = dataset[(source_index, 0)] + except InvalidSourceSampleError as error: + if not args.accept_all_valid: + raise + skipped_invalid_source.append({ + "source_clip_index": source_index, + "reason": str(error), + }) + has_supervision = False + else: + has_supervision = bool(sample["translation_valid"].any()) + right_geometry_masked_frames = int(( + sample["translation_valid"][..., 1] + & ~sample["mano_annotation_valid"][..., 1] + ).sum()) if args.dataset == "HOI4D" else 0 + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + if not has_supervision: + if not skipped_invalid_source or skipped_invalid_source[-1]["source_clip_index"] != source_index: + skipped_no_supervision.append(source_index) + else: + cached[source_index] = cache_row( + dataset.rows[source_index], source_index, output, args.dataset, + target_hw, + right_geometry_masked_frames, + ) + if position % 10 == 0 or position == len(decode_order): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": position, "requested": len(decode_order), + "cached": len(cached), "skipped_no_supervision": len(skipped_no_supervision), + "skipped_invalid_source": len(skipped_invalid_source), + "clips_per_second": position / elapsed, + "eta_seconds": (len(decode_order) - position) / (position / elapsed), + }), flush=True) + if args.dataset == "HOI4D" and args.prefetch_batch_size: + dataset.clear_prefetch() + if should_stop_decoding( + selected, cached, args.clips, + args.decode_all_candidates or args.accept_all_valid, + ): + break + ordered_cached = first_valid_indices(selected, cached, args.clips) + manifest = args.output_dir / "cache_manifest.jsonl" + manifest_temporary = manifest.with_suffix(".tmp") + manifest_temporary.write_text( + "".join(json.dumps(cached[index], sort_keys=True) + "\n" for index in ordered_cached), + encoding="utf-8", + ) + manifest_temporary.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": cache_completion_status( + args.clips, selected, cached, position, args.accept_all_valid, + ), + "dataset": args.dataset, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "requested_clips": args.clips, "candidate_clips_processed": position, + "resolution_hw": list(target_hw), + "cached_clips": len(ordered_cached), "valid_candidate_files": len(cached), + "recordings": len({cached[index]["source_group_key"] for index in ordered_cached}), + "required_hand_side": args.required_hand_side, + "eligible_source_clips": len(eligible), + "accept_all_valid": bool(args.accept_all_valid), + "all_eligible_processed": position == len(selected), + "cached_valid_clips": len(ordered_cached), + "decode_all_candidates": bool(args.decode_all_candidates), + "skipped_no_supervision": skipped_no_supervision, + "skipped_invalid_source": skipped_invalid_source, + "right_geometry_masked_frames": sum( + cached[index]["right_geometry_masked_frames"] for index in ordered_cached + ), + "right_geometry_masked_source_indices": [ + index for index in ordered_cached + if cached[index]["right_geometry_masked_frames"] + ], + "wall_seconds": elapsed, "clips_per_second": position / elapsed, + "bytes": sum(Path(cached[index]["cache_path"]).stat().st_size for index in ordered_cached), + "resume_invocation": bool(args.resume), "official_test_used": False, + "torch_threads": args.torch_threads or torch.get_num_threads(), + } + (args.output_dir / "cache_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/capture_environment.py b/home/wuyifan/EgoNet_train_20261008/scripts/capture_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3d38bbd2ddfca1e23fdbc2eb2518240f885a2f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/capture_environment.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Capture phase-2 environment without exposing unrelated environment variables.""" + +from __future__ import annotations + +import json +import platform +import subprocess +from pathlib import Path + +import cv2 +import numpy as np +import torch + + +def command(args: list[str]) -> str: + return subprocess.run(args, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.strip() + + +def main() -> None: + output = Path("artifacts/phase2/environment") + output.mkdir(parents=True, exist_ok=True) + report = { + "captured_at": command(["date", "--iso-8601=seconds"]), + "platform": platform.platform(), "python": platform.python_version(), + "torch": torch.__version__, "torch_cuda": torch.version.cuda, "cuda_available": torch.cuda.is_available(), + "cuda_devices": [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())], + "bf16_supported": [torch.cuda.is_bf16_supported(index) for index in range(torch.cuda.device_count())], + "numpy": np.__version__, "opencv": cv2.__version__, + "nvidia_smi": command(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free,driver_version", "--format=csv,noheader"]), + "git_status": command(["git", "status", "--short"]), + "git_head": command(["git", "rev-parse", "HEAD"]), + "dinov3_commit": command(["git", "-C", "third_party/dinov3", "rev-parse", "HEAD"]), + "manopth_commit": command(["git", "-C", "third_party/manopth", "rev-parse", "HEAD"]), + "h2oplayer_commit": command(["git", "-C", "third_party/h2oplayer", "rev-parse", "HEAD"]), + } + (output / "environment.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/capture_phase4_provenance.py b/home/wuyifan/EgoNet_train_20261008/scripts/capture_phase4_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..805db38ce73a5086e3677718bcaf2d864e418d7f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/capture_phase4_provenance.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Capture the Phase 4 entry state without reading the official test split.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import subprocess +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import cv2 +import numpy as np +import torch + + +def command(args: list[str], cwd: Path) -> str: + result = subprocess.run( + args, + cwd=cwd, + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + return result.stdout.strip() + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/freeze/entry")) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + output = (root / args.output_dir).resolve() if not args.output_dir.is_absolute() else args.output_dir + output.mkdir(parents=True, exist_ok=True) + + checkpoint_index = json.loads( + (root / "artifacts/phase3/reports/long_tail_checkpoints.json").read_text(encoding="utf-8") + ) + checkpoints = [] + for run in checkpoint_index["runs"].values(): + role = run["roles"]["tail_best_absolute"] + path = Path(role["path"]) + checkpoints.append({ + "seed": int(run["seed"]), + "step": int(role["step"]), + "path": str(path), + "registered_sha256": role["sha256"], + "observed_sha256": sha256(path), + "bytes": path.stat().st_size, + "evaluation": role["evaluation"], + }) + + protected_inputs = { + "official_train_manifest": root / "artifacts/phase2/data_audit/manifests/official_train.jsonl", + "official_val_manifest": root / "artifacts/phase2/data_audit/manifests/official_val.jsonl", + "fixed_validation_subset": root / "artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json", + } + report = { + "captured_at": datetime.now(ZoneInfo("Asia/Hong_Kong")).isoformat(), + "project_root": str(root), + "git_head": command(["git", "rev-parse", "HEAD"], root), + "git_status": command(["git", "status", "--short", "--branch"], root), + "git_diff_stat": command(["git", "diff", "--stat"], root), + "git_diff_sha256": hashlib.sha256(command(["git", "diff", "--binary"], root).encode()).hexdigest(), + "platform": platform.platform(), + "python": platform.python_version(), + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "cuda_devices": [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())], + "numpy": np.__version__, + "opencv": cv2.__version__, + "nvidia_smi": command([ + "nvidia-smi", + "--query-gpu=index,name,uuid,memory.total,memory.used,memory.free,utilization.gpu", + "--format=csv,noheader", + ], root), + "submodules": command(["git", "submodule", "status"], root), + "checkpoints": checkpoints, + "protected_inputs": { + name: {"path": str(path.resolve()), "sha256": sha256(path), "bytes": path.stat().st_size} + for name, path in protected_inputs.items() + }, + "official_test_used": False, + "official_test_note": "The official test manifest and files are intentionally not read or hashed.", + } + (output / "entry_provenance.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + (output / "git_status.txt").write_text(report["git_status"] + "\n", encoding="utf-8") + (output / "git_diff.patch").write_text(command(["git", "diff", "--binary"], root) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "captured", + "output": str(output), + "git_head": report["git_head"], + "checkpoint_hashes_match": all( + item["registered_sha256"] == item["observed_sha256"] for item in checkpoints + ), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/capture_phase5_provenance.py b/home/wuyifan/EgoNet_train_20261008/scripts/capture_phase5_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..bb59cafe4facd03ad4fb3b51fc4bb96eea8d77da --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/capture_phase5_provenance.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Capture Phase 5 entry provenance without touching the official test split.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import subprocess +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import torch + + +def command(args: list[str], cwd: Path) -> str: + return subprocess.run( + args, cwd=cwd, check=False, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + ).stdout.strip() + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase5/freeze/entry")) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + output = args.output_dir if args.output_dir.is_absolute() else root / args.output_dir + output.mkdir(parents=True, exist_ok=True) + + baselines = [ + { + "name": f"p0_512_seed{seed}", + "checkpoint": root / f"artifacts/phase3/depth_dropout_runs_commit7583772/depth_dropout00_geometry_m3_l1_t1_s{seed}/best.pt", + "evaluation": root / f"artifacts/phase3/depth_dropout_full_validation/depth_dropout00_geometry_m3_l1_t1_s{seed}/best_absolute/evaluation.json", + } + for seed in (20260716, 20260717, 20260718) + ] + [{ + "name": "unified_640_tail_seed20260718", + "checkpoint": Path("/SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/best.pt"), + "evaluation": root / "artifacts/phase3/long_tail_full_validation/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/tail_best_absolute/evaluation.json", + }] + baseline_records = [] + for baseline in baselines: + evaluation = json.loads(baseline["evaluation"].read_text(encoding="utf-8")) + checkpoint = baseline["checkpoint"] + observed_hash = sha256(checkpoint) + baseline_records.append({ + "name": baseline["name"], + "checkpoint": str(checkpoint.resolve()), + "registered_sha256": evaluation["checkpoint"]["sha256"], + "observed_sha256": observed_hash, + "hash_matches": observed_hash == evaluation["checkpoint"]["sha256"], + "step": evaluation["checkpoint"]["step"], + "evaluation": str(baseline["evaluation"].resolve()), + "absolute_mpjpe_mm": evaluation["metrics"]["absolute_mpjpe_mm"]["mean"], + "official_test_used": evaluation["official_test_used"], + }) + + protected = { + "official_train": root / "artifacts/phase2/data_audit/manifests/official_train.jsonl", + "official_validation": root / "artifacts/phase2/data_audit/manifests/official_val.jsonl", + "fixed_validation_subset_640": root / "artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json", + "phase5_oof_folds": root / "artifacts/phase5/splits/subject_oof_v1/folds.json", + } + report = { + "captured_at": datetime.now(ZoneInfo("Asia/Hong_Kong")).isoformat(), + "status": "captured", + "project_root": str(root), + "git_head": command(["git", "rev-parse", "HEAD"], root), + "git_status": command(["git", "status", "--short", "--branch"], root), + "git_diff_sha256": hashlib.sha256( + command(["git", "diff", "--binary"], root).encode() + ).hexdigest(), + "platform": platform.platform(), + "python": platform.python_version(), + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "nvidia_smi": command([ + "nvidia-smi", "--query-gpu=index,name,uuid,memory.total,memory.used,memory.free,utilization.gpu", + "--format=csv,noheader", + ], root), + "disk": command(["df", "-h", str(root), "/SSD2", "/SSD3"], root), + "active_compute_processes": command([ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid,process_name,used_memory", + "--format=csv,noheader", + ], root), + "baselines": baseline_records, + "protected_inputs": { + name: {"path": str(path.resolve()), "sha256": sha256(path), "bytes": path.stat().st_size} + for name, path in protected.items() + }, + "official_test_used": False, + "official_test_note": "Official test manifests, files, predictions, and hashes were intentionally not accessed.", + } + (output / "entry_provenance.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + (output / "git_status.txt").write_text(report["git_status"] + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], + "output": str(output), + "baseline_hashes_match": all(row["hash_matches"] for row in baseline_records), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase3_resume.py b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase3_resume.py new file mode 100644 index 0000000000000000000000000000000000000000..82924e82bed187f735fe17acf6647623b4b1e206 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase3_resume.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Compare uninterrupted and resumed Phase 3 final states exactly.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +from pathlib import Path + + +def worker(reference_path: Path, resumed_path: Path) -> None: + import numpy as np + import torch + + reference = torch.load(reference_path, map_location="cpu", weights_only=False) + resumed = torch.load(resumed_path, map_location="cpu", weights_only=False) + + def equal(left, right) -> bool: + if torch.is_tensor(left) and torch.is_tensor(right): + return left.dtype == right.dtype and left.shape == right.shape and torch.equal(left, right) + if isinstance(left, np.ndarray) and isinstance(right, np.ndarray): + return left.dtype == right.dtype and left.shape == right.shape and np.array_equal(left, right) + if isinstance(left, dict) and isinstance(right, dict): + return left.keys() == right.keys() and all(equal(left[key], right[key]) for key in left) + if isinstance(left, (tuple, list)) and isinstance(right, type(left)): + return len(left) == len(right) and all(equal(a, b) for a, b in zip(left, right)) + return left == right + + result = { + "reference_step": int(reference["step"]), + "resumed_step": int(resumed["step"]), + "model_exact": equal(reference["model"], resumed["model"]), + "optimizer_exact": equal(reference["optimizer"], resumed["optimizer"]), + "python_rng_exact": equal(reference["python_rng"], resumed["python_rng"]), + "numpy_rng_exact": equal(reference["numpy_rng"], resumed["numpy_rng"]), + "torch_rng_exact": equal(reference["torch_rng"], resumed["torch_rng"]), + "cuda_rng_exact": equal(reference["cuda_rng"], resumed["cuda_rng"]), + } + print(json.dumps(result)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("reference_root", type=Path, nargs="?") + parser.add_argument("resumed_root", type=Path, nargs="?") + parser.add_argument("--expected-runs", type=int) + parser.add_argument("--checkpoint-name", default="step_0100000_final.pt") + parser.add_argument("--expected-step", type=int, default=100_000) + parser.add_argument("--worker", nargs=2, type=Path) + args = parser.parse_args() + if args.worker: + worker(*args.worker) + return + if args.reference_root is None or args.resumed_root is None: + parser.error("reference_root and resumed_root are required") + + # The resumed root defines the audited subset while a larger reference matrix + # may still be running. + run_names = sorted( + path.name for path in args.resumed_root.iterdir() + if path.is_dir() and not path.name.startswith("_") + ) + if args.expected_runs is not None and len(run_names) != args.expected_runs: + raise ValueError(f"expected {args.expected_runs} runs, found {len(run_names)}") + records = [] + for run_name in run_names: + reference_path = args.reference_root / run_name / args.checkpoint_name + resumed_path = args.resumed_root / run_name / args.checkpoint_name + if not reference_path.is_file() or not resumed_path.is_file(): + raise FileNotFoundError(f"missing final checkpoint for {run_name}") + process = subprocess.run( + [ + sys.executable, str(Path(__file__).resolve()), "--worker", + str(reference_path), str(resumed_path), + ], + check=True, capture_output=True, text=True, + ) + records.append({"run": run_name, **json.loads(process.stdout)}) + + passed = bool(records) and all( + row["reference_step"] == row["resumed_step"] == args.expected_step + and row["model_exact"] and row["optimizer_exact"] + and row["python_rng_exact"] and row["numpy_rng_exact"] + and row["torch_rng_exact"] and row["cuda_rng_exact"] + for row in records + ) + payload = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "reference_root": str(args.reference_root), + "resumed_root": str(args.resumed_root), + "runs": records, + } + output = args.resumed_root / "exact_resume_audit.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": payload["status"], "runs": len(records), "output": str(output)}, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase5_alignment_calibrators.py b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase5_alignment_calibrators.py new file mode 100644 index 0000000000000000000000000000000000000000..5921cddec59bf99669817ea5ddbe8fee1c4c6335 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase5_alignment_calibrators.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Compare shared multi-checkpoint and per-seed OOF calibrators.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + + +CONDITIONS = ( + "coarse", + "robust_alignment_unscaled", + "calibrated_always", + "calibrated_confidence", +) +METRICS = ("absolute_mpjpe_mm", "z_mae_mm", "z_p95_mm", "z_cvar95_mm") + + +def load_report(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "fitted" + or report.get("result_role") != "train_oof_cross_validated_threshold_selection" + or report.get("official_validation_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"comparison requires a train-OOF-only calibration report: {path}") + return report + + +def compare_reports( + shared: dict[str, Any], per_seed: list[dict[str, Any]], +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + if int(shared.get("expected_banks_per_fold", -1)) <= 1: + raise ValueError("shared report is not a multi-checkpoint calibration") + expected_seeds = {int(seed) for seed in shared.get("coarse_seeds", [])} + specific = {} + for report in per_seed: + seeds = [int(seed) for seed in report.get("coarse_seeds", [])] + if int(report.get("expected_banks_per_fold", -1)) != 1 or len(seeds) != 1: + raise ValueError("each per-seed report must contain one seed and one bank per fold") + if seeds[0] in specific: + raise ValueError(f"duplicate per-seed report: {seeds[0]}") + specific[seeds[0]] = report + if set(specific) != expected_seeds: + raise ValueError( + f"per-seed reports do not match shared seeds: {sorted(specific)} vs {sorted(expected_seeds)}" + ) + + rows = [] + for seed in sorted(expected_seeds): + shared_metrics = shared["metrics_by_seed"][str(seed)] + specific_metrics = specific[seed]["metrics"] + for metric in METRICS: + shared_coarse = float(shared_metrics["coarse"][metric]) + specific_coarse = float(specific_metrics["coarse"][metric]) + if abs(shared_coarse - specific_coarse) > 1e-9: + raise ValueError(f"seed {seed} coarse {metric} mismatch") + for condition in CONDITIONS: + row: dict[str, Any] = {"seed": seed, "condition": condition} + for metric in METRICS: + shared_value = float(shared_metrics[condition][metric]) + specific_value = float(specific_metrics[condition][metric]) + row[f"shared_{metric}"] = shared_value + row[f"per_seed_{metric}"] = specific_value + row[f"shared_minus_per_seed_{metric}"] = shared_value - specific_value + rows.append(row) + + calibrated = [row for row in rows if row["condition"] == "calibrated_always"] + summary = { + "status": "compared", + "experiment_class": "train_oof_shared_vs_per_seed_calibrator_ablation", + "seeds": sorted(expected_seeds), + "primary_condition": "calibrated_always", + "shared_absolute_better_seed_count": sum( + row["shared_minus_per_seed_absolute_mpjpe_mm"] < 0 for row in calibrated + ), + "mean_shared_minus_per_seed_absolute_mpjpe_mm": sum( + row["shared_minus_per_seed_absolute_mpjpe_mm"] for row in calibrated + ) / len(calibrated), + "mean_shared_minus_per_seed_z_p95_mm": sum( + row["shared_minus_per_seed_z_p95_mm"] for row in calibrated + ) / len(calibrated), + "official_validation_used": False, + "official_test_used": False, + } + return rows, summary + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--shared", type=Path, required=True) + parser.add_argument("--per-seed", type=Path, action="append", required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("comparison refuses to overwrite outputs") + shared = load_report(args.shared) + per_seed = [load_report(path) for path in args.per_seed] + rows, summary = compare_reports(shared, per_seed) + report = { + **summary, + "shared_report": str(args.shared.resolve()), + "per_seed_reports": [str(path.resolve()) for path in args.per_seed], + "rows": rows, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase6_paired_evaluations.py b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase6_paired_evaluations.py new file mode 100644 index 0000000000000000000000000000000000000000..6720f4f081aba86cf6a2f3152e427076a0f95dad --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase6_paired_evaluations.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Pair two frozen Phase 6 evaluation outputs by take/frame/side.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + + +METRIC_ALIASES = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm",), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm",), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm",), + "root_relative_mpvpe_mm": ("root_relative_mpvpe_mm",), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm",), + "translation_x_mae_mm": ("translation_x_mae_mm",), + "translation_y_mae_mm": ("translation_y_mae_mm",), + "translation_z_mae_mm": ("translation_z_mae_mm",), + "direct_2d_error_px": ("direct_2d_error_px",), + "projected_mano_2d_px": ("projected_mano_2d_px", "mano_projected_2d_error_px"), + "direct_mano_consistency_px": ( + "direct_mano_consistency_px", "direct_mano_2d_consistency_px", + ), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_rows(path: Path, condition: str | None) -> dict[tuple[str, int, str], dict[str, float]]: + output = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + if condition is not None and row.get("condition") != condition: + continue + if row.get("annotation_valid") not in (None, "1", "True", "true"): + continue + identity = (row["take"], int(row["frame_id"]), row["side"]) + if identity in output: + raise ValueError(f"duplicate paired identity: {identity}") + metrics = {} + for canonical, aliases in METRIC_ALIASES.items(): + source = next((alias for alias in aliases if row.get(alias, "") != ""), None) + if source is not None: + metrics[canonical] = float(row[source]) + output[identity] = metrics + if not output: + raise ValueError(f"no rows selected from {path}") + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--baseline-dir", type=Path, required=True) + parser.add_argument("--candidate-dir", type=Path, required=True) + parser.add_argument("--baseline-condition") + parser.add_argument("--candidate-condition") + parser.add_argument("--baseline-label", required=True) + parser.add_argument("--candidate-label", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + baseline_path = args.baseline_dir / "per_hand_frame_metrics.csv" + candidate_path = args.candidate_dir / "per_hand_frame_metrics.csv" + baseline = load_rows(baseline_path, args.baseline_condition) + candidate = load_rows(candidate_path, args.candidate_condition) + if set(baseline) != set(candidate): + raise ValueError("paired evaluations have different take/frame/side identities") + common_metrics = sorted( + set().union(*(set(row) for row in baseline.values())) + & set().union(*(set(row) for row in candidate.values())) + ) + if not common_metrics: + raise ValueError("paired evaluations have no common metrics") + frame_rows = [] + for identity in sorted(baseline): + take, frame_id, side = identity + row: dict[str, object] = {"take": take, "frame_id": frame_id, "side": side} + for metric in common_metrics: + if metric not in baseline[identity] or metric not in candidate[identity]: + continue + delta = candidate[identity][metric] - baseline[identity][metric] + row[f"baseline_{metric}"] = baseline[identity][metric] + row[f"candidate_{metric}"] = candidate[identity][metric] + row[f"delta_{metric}"] = delta + frame_rows.append(row) + rng = np.random.default_rng(20260717) + paired_rows = [] + for metric in common_metrics: + selected = [row for row in frame_rows if f"delta_{metric}" in row] + frame_delta = np.asarray([float(row[f"delta_{metric}"]) for row in selected]) + by_take: dict[str, list[float]] = defaultdict(list) + for row in selected: + by_take[str(row["take"])].append(float(row[f"delta_{metric}"])) + takes = sorted(by_take) + take_delta = np.asarray([ + np.mean(by_take[take]) for take in takes + ]) + indices = rng.integers(0, len(take_delta), size=(10_000, len(take_delta))) + bootstrap = take_delta[indices].mean(axis=1) + paired_rows.append({ + "candidate": args.candidate_label, "baseline": args.baseline_label, + "metric": metric, "hands": len(frame_delta), "takes": len(takes), + "frame_weighted_delta": float(frame_delta.mean()), + "take_equal_delta": float(take_delta.mean()), + "ci95_low": float(np.percentile(bootstrap, 2.5)), + "ci95_high": float(np.percentile(bootstrap, 97.5)), + "largest_sample_gain": float(frame_delta.min()), + "largest_sample_harm": float(frame_delta.max()), + "largest_take_gain": float(take_delta.min()), + "largest_take_harm": float(take_delta.max()), + }) + args.output_dir.mkdir(parents=True, exist_ok=True) + for filename, rows in ( + ("per_hand_frame_deltas.csv", frame_rows), + ("paired_take_bootstrap_ci.csv", paired_rows), + ): + with (args.output_dir / filename).open("x", newline="", encoding="utf-8") as handle: + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "paired", + "official_test_used": False, + "baseline": { + "label": args.baseline_label, "directory": str(args.baseline_dir.resolve()), + "condition": args.baseline_condition, "rows_sha256": sha256(baseline_path), + }, + "candidate": { + "label": args.candidate_label, "directory": str(args.candidate_dir.resolve()), + "condition": args.candidate_condition, "rows_sha256": sha256(candidate_path), + }, + "paired_identities": len(frame_rows), + "physical_takes": len({str(row["take"]) for row in frame_rows}), + "metrics": paired_rows, + } + (args.output_dir / "comparison.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_adaptation_forgetting.py b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_adaptation_forgetting.py new file mode 100644 index 0000000000000000000000000000000000000000..e1cb408e3922668217c70a3eddaf0c68cfd7748b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_adaptation_forgetting.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Paired external forgetting comparison for an H2O-adapted checkpoint.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.compare_phase8_specialist_curve import ( + MEAN_METRICS, + _load_rows, + _paired_bootstrap, +) + + +def _load_reference(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError("reference is not a strict external-heldout result") + return report + + +def _load_candidate(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_adaptation_external_heldout" + or report.get("evaluation_role") != "adaptation_external_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError("candidate is not an adaptation forgetting result") + return report + + +def compare( + reference_path: Path, + candidate_path: Path, + *, + seed: int = 20260717, + resamples: int = 2000, +) -> dict[str, Any]: + reference = _load_reference(reference_path) + candidate = _load_candidate(candidate_path) + for field in ("input_mode", "clips", "frames"): + if reference.get(field) != candidate.get(field): + raise ValueError(f"evaluation {field} differs") + if reference["cache_manifest"] != candidate["cache_manifest"]: + raise ValueError("evaluation cache manifest differs") + reference_rows = _load_rows(reference_path, reference) + candidate_rows = _load_rows(candidate_path, candidate) + if set(reference_rows) != set(candidate_rows): + raise ValueError("per-hand frame identities differ") + metrics: dict[str, Any] = {} + for metric in MEAN_METRICS: + metrics[metric] = { + "reference_global_mean": reference["metrics"][metric]["mean"], + "candidate_global_mean": candidate["metrics"][metric]["mean"], + **_paired_bootstrap( + reference_rows, candidate_rows, metric, "mean", seed, resamples, + ), + } + metrics["translation_z_recording_p95_mm"] = { + "reference_global_p95": reference["metrics"]["translation_z_mae_mm"]["p95"], + "candidate_global_p95": candidate["metrics"]["translation_z_mae_mm"]["p95"], + **_paired_bootstrap( + reference_rows, candidate_rows, "translation_z_mae_mm", "p95", + seed, resamples, + ), + } + return { + "schema_version": "phase8_adaptation_forgetting_comparison_v1", + "status": "complete", + "delta_definition": "adapted_candidate_minus_external_reference; positive is forgetting", + "reference": { + "evaluation": str(reference_path.resolve()), + "checkpoint": reference["checkpoint"], + }, + "candidate": { + "evaluation": str(candidate_path.resolve()), + "checkpoint": candidate["checkpoint"], + }, + "input_mode": reference["input_mode"], + "cache_manifest": reference["cache_manifest"], + "per_hand_identity_count": len(reference_rows), + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "metrics": metrics, + "selection_use": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-evaluation", type=Path, required=True) + parser.add_argument("--candidate-evaluation", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = compare( + args.reference_evaluation, args.candidate_evaluation, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_h2o_trainheldout.py b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_h2o_trainheldout.py new file mode 100644 index 0000000000000000000000000000000000000000..f823fbc57892f9bf3c1192807b564b7ad628c97a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_h2o_trainheldout.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Compare H2O train-heldout baselines separately by deployable input mode.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.select_phase7_h2o_adaptation import ( + METRIC_SPECS, + paired_recording_bootstrap, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def checked_artifact(report: dict[str, Any], name: str) -> Path: + record = report[name] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"{name} is missing or SHA256 differs: {path}") + return path + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("selection_split") != "h2o_train_group_heldout_only" + or manifest.get("h2o_official_validation_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("comparison manifest violates the train-heldout boundary") + by_mode: dict[str, list[dict[str, Any]]] = {} + cache_hashes: set[str] = set() + seen: set[tuple[str, str]] = set() + valid_status_roles = { + ("evaluated_h2o_train_group_heldout", "h2o_train_group_heldout"), + ("evaluated_h2o_train_group_heldout_control", "h2o_train_group_heldout_control"), + } + for item in manifest.get("candidates", []): + condition = str(item["condition"]) + report_path = Path(item["evaluation"]) + report = json.loads(report_path.read_text(encoding="utf-8")) + status_role = (report.get("status"), report.get("evaluation_role")) + mode = str(report.get("input_mode")) + if ( + status_role not in valid_status_roles + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or Path(report["cache_manifest"]["path"]).name != "train_group_heldout.jsonl" + ): + raise ValueError(f"invalid H2O train-heldout result: {report_path}") + if (condition, mode) in seen: + raise ValueError(f"duplicate condition/mode: {condition}/{mode}") + seen.add((condition, mode)) + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + cache = checked_artifact(report, "cache_manifest") + rows = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + cache_hashes.add(report["cache_manifest"]["sha256"]) + metrics = { + name: float(report["metrics"][row_metric][statistic]) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + by_mode.setdefault(mode, []).append({ + "condition": condition, "evaluation": str(report_path.resolve()), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config.resolve()), "cache_manifest": str(cache.resolve()), + "per_hand_rows": str(rows.resolve()), "metrics": metrics, + }) + if len(cache_hashes) != 1: + raise ValueError("candidates use different train-heldout manifests") + if not by_mode: + raise ValueError("comparison manifest has no candidates") + modes: dict[str, Any] = {} + for mode, candidates in sorted(by_mode.items()): + if len(candidates) < 2: + raise ValueError(f"input mode requires at least two candidates: {mode}") + order = sorted(candidates, key=lambda row: ( + row["metrics"]["absolute_mpjpe_mm"], + row["metrics"]["root_relative_mpjpe_mm"], + row["condition"], + )) + winner = order[0] + paired = {} + for candidate in order[1:]: + paired[candidate["condition"]] = { + name: paired_recording_bootstrap( + Path(winner["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + modes[mode] = { + "winner": winner["condition"], + "order": [candidate["condition"] for candidate in order], + "candidates": order, + "paired_recording_bootstrap_vs_winner": paired, + } + return { + "status": "compared_h2o_train_group_heldout_by_input_mode", + "selection_split": "h2o_train_group_heldout_only", + "selection_rule": "lowest Absolute MPJPE separately within each input mode", + "modes": modes, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_h2o_zero_shot.py b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c3efcc36b714f01f46834472c98a2b59014f8f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_h2o_zero_shot.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Compare already-frozen external checkpoints on H2O validation diagnostically.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import Any + +from scripts.compare_phase8_h2o_trainheldout import checked_artifact +from scripts.select_phase7_h2o_adaptation import METRIC_SPECS, paired_recording_bootstrap + + +BOUNDARY = "frozen_external_checkpoints_h2o_official_validation_diagnostic_only" + + +def _metrics(report: dict[str, Any]) -> dict[str, float]: + values = { + name: float(report["metrics"][row_metric][statistic]) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + if not all(math.isfinite(value) for value in values.values()): + raise ValueError("zero-shot report contains non-finite metrics") + return values + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("comparison_boundary") != BOUNDARY + or manifest.get("checkpoint_selection_frozen_before_h2o") is not True + or manifest.get("h2o_official_validation_used_for_external_selection") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("comparison manifest violates the frozen zero-shot boundary") + reference_condition = str(manifest.get("reference_condition", "")) + by_mode: dict[str, list[dict[str, Any]]] = {} + validation_hashes: set[str] = set() + seen: set[tuple[str, str]] = set() + for item in manifest.get("candidates", []): + condition = str(item["condition"]) + path = Path(item["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + mode = str(report.get("input_mode")) + if ( + report.get("status") != "evaluated_strict_h2o_zero_shot" + or report.get("evaluation_role") != "strict_external_zero_shot" + or report.get("h2o_training_data_used") is not False + or report.get("h2o_official_validation_used") is not True + or report.get("h2o_official_validation_used_for_external_selection") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid frozen H2O zero-shot result: {path}") + if (condition, mode) in seen: + raise ValueError(f"duplicate condition/mode: {condition}/{mode}") + seen.add((condition, mode)) + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + rows = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + validation = checked_artifact(report, "manifest") + validation_hashes.add(report["manifest"]["sha256"]) + by_mode.setdefault(mode, []).append({ + "condition": condition, + "evaluation": str(path.resolve()), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config), + "validation_manifest": str(validation), + "per_hand_rows": str(rows), + "metrics": _metrics(report), + }) + if len(validation_hashes) != 1 or not by_mode: + raise ValueError("zero-shot candidates must use one frozen validation manifest") + modes: dict[str, Any] = {} + for mode, candidates in sorted(by_mode.items()): + references = [row for row in candidates if row["condition"] == reference_condition] + if len(references) != 1 or len(candidates) < 2: + raise ValueError(f"mode lacks one reference and at least one candidate: {mode}") + reference = references[0] + comparisons = {} + for candidate in candidates: + if candidate is reference: + continue + comparisons[candidate["condition"]] = { + name: paired_recording_bootstrap( + Path(reference["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + modes[mode] = { + "reference": reference, + "candidates": [row for row in candidates if row is not reference], + "paired_candidate_minus_reference": comparisons, + } + return { + "status": "compared_frozen_h2o_zero_shot_diagnostic_only", + "comparison_boundary": BOUNDARY, + "selection_performed": False, + "reference_condition": reference_condition, + "modes": modes, + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_specialist_curve.py b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_specialist_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..92a78c396b10552bb60b3407b9e9686f7859ad84 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_specialist_curve.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Compare two frozen specialist checkpoints on identical external rows.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +MEAN_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", +) +IDENTITY_FIELDS = ( + "dataset", "physical_recording_id", "camera_id", "frame_id", "side", +) + + +def _load_report(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError(f"evaluation violates external curve contract: {path}") + return report + + +def _load_rows(report_path: Path, report: dict[str, Any]) -> dict[tuple[str, ...], dict[str, str]]: + specification = report["per_hand_rows"] + row_path = Path( + specification["path"] if isinstance(specification, dict) else specification, + ) + if not row_path.is_absolute(): + row_path = report_path.parent / row_path + if isinstance(specification, dict): + digest = hashlib.sha256(row_path.read_bytes()).hexdigest() + if digest != specification.get("sha256"): + raise ValueError(f"per-hand row SHA256 differs: {row_path}") + with row_path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + indexed: dict[tuple[str, ...], dict[str, str]] = {} + for row in rows: + identity = tuple(str(row[field]) for field in IDENTITY_FIELDS) + if identity in indexed: + raise ValueError(f"duplicate per-hand identity: {identity}") + indexed[identity] = row + if not indexed: + raise ValueError(f"evaluation has no per-hand rows: {row_path}") + return indexed + + +def _recording_statistic( + rows: dict[tuple[str, ...], dict[str, str]], metric: str, statistic: str, +) -> dict[tuple[str, str], float]: + grouped: dict[tuple[str, str], list[float]] = {} + for identity, row in rows.items(): + value = float(row[metric]) + if math.isfinite(value): + grouped.setdefault((identity[0], identity[1]), []).append(value) + if statistic == "mean": + reduce = np.mean + elif statistic == "p95": + reduce = lambda values: np.quantile(values, 0.95) + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + return {key: float(reduce(values)) for key, values in grouped.items()} + + +def _paired_bootstrap( + reference: dict[tuple[str, str], dict[str, str]], + candidate: dict[tuple[str, str], dict[str, str]], + metric: str, + statistic: str, + seed: int, + resamples: int, +) -> dict[str, Any]: + reference_values = _recording_statistic(reference, metric, statistic) + candidate_values = _recording_statistic(candidate, metric, statistic) + if set(reference_values) != set(candidate_values): + raise ValueError(f"finite recording coverage differs for {metric}/{statistic}") + keys = sorted(reference_values) + delta = np.asarray( + [candidate_values[key] - reference_values[key] for key in keys], + dtype=np.float64, + ) + rng = np.random.default_rng(seed) + sampled = delta[ + rng.integers(0, len(delta), size=(resamples, len(delta))) + ].mean(axis=1) + return { + "recording_statistic": statistic, + "recording_count": len(keys), + "mean_delta": float(delta.mean()), + "ci95_low": float(np.percentile(sampled, 2.5)), + "ci95_high": float(np.percentile(sampled, 97.5)), + } + + +def compare( + reference_path: Path, + candidate_path: Path, + *, + seed: int = 20260717, + resamples: int = 2000, +) -> dict[str, Any]: + reference_report = _load_report(reference_path) + candidate_report = _load_report(candidate_path) + for field in ("input_mode", "clips", "frames"): + if reference_report.get(field) != candidate_report.get(field): + raise ValueError(f"evaluation {field} differs") + if reference_report["cache_manifest"] != candidate_report["cache_manifest"]: + raise ValueError("evaluation cache manifest differs") + reference_rows = _load_rows(reference_path, reference_report) + candidate_rows = _load_rows(candidate_path, candidate_report) + if set(reference_rows) != set(candidate_rows): + raise ValueError("per-hand frame identities differ") + metrics: dict[str, Any] = {} + for metric in MEAN_METRICS: + reference_summary = reference_report["metrics"].get(metric) or {} + candidate_summary = candidate_report["metrics"].get(metric) or {} + metrics[metric] = { + "reference_global_mean": reference_summary.get("mean"), + "candidate_global_mean": candidate_summary.get("mean"), + **_paired_bootstrap( + reference_rows, candidate_rows, metric, "mean", seed, resamples, + ), + } + z_reference = reference_report["metrics"]["translation_z_mae_mm"] + z_candidate = candidate_report["metrics"]["translation_z_mae_mm"] + metrics["translation_z_recording_p95_mm"] = { + "reference_global_p95": z_reference.get("p95"), + "candidate_global_p95": z_candidate.get("p95"), + **_paired_bootstrap( + reference_rows, candidate_rows, "translation_z_mae_mm", "p95", + seed, resamples, + ), + } + absolute = metrics["absolute_mpjpe_mm"] + return { + "schema_version": "phase8_specialist_curve_comparison_v1", + "status": "complete", + "delta_definition": "candidate_minus_reference; negative favors candidate", + "reference": { + "evaluation": str(reference_path.resolve()), + "checkpoint_step": reference_report["checkpoint_step"], + "checkpoint": reference_report["checkpoint"], + }, + "candidate": { + "evaluation": str(candidate_path.resolve()), + "checkpoint_step": candidate_report["checkpoint_step"], + "checkpoint": candidate_report["checkpoint"], + }, + "input_mode": reference_report["input_mode"], + "cache_manifest": reference_report["cache_manifest"], + "per_hand_identity_count": len(reference_rows), + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "metrics": metrics, + "candidate_absolute_lower": ( + float(absolute["candidate_global_mean"]) + < float(absolute["reference_global_mean"]) + ), + "candidate_absolute_ci_excludes_zero": absolute["ci95_high"] < 0.0, + "h2o_training_data_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-evaluation", type=Path, required=True) + parser.add_argument("--candidate-evaluation", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + args.reference_evaluation, args.candidate_evaluation, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_stage7_left.py b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_stage7_left.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e522e3d109275545d58a7f4c7402d090b00fce --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/compare_phase8_stage7_left.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Compare matched Stage 7 left-supervision screens on external held-out data.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.select_phase7_h2o_adaptation import paired_recording_bootstrap + + +CONDITIONS = ("L0_sampler_only", "L1_left_root_relative") +DATASETS = ("HOT3D", "HOI4D", "ARCTIC") +METRICS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "source_root_relative_mpjpe_mm": ("source_root_relative_mpjpe_mm", "mean"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def checked(report: dict[str, Any], name: str) -> Path: + record = report[name] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"{name} is missing or SHA256 differs: {path}") + return path + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("evaluation_split") != "external_heldout_only" + or manifest.get("h2o_training_data_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("Stage 7 comparison boundary flags are invalid") + reports: dict[str, dict[str, dict[str, Any]]] = {condition: {} for condition in CONDITIONS} + for item in manifest.get("evaluations", []): + condition, dataset = str(item["condition"]), str(item["dataset"]) + if condition not in reports or dataset not in DATASETS: + raise ValueError(f"unexpected condition/dataset: {condition}/{dataset}") + if dataset in reports[condition]: + raise ValueError(f"duplicate condition/dataset: {condition}/{dataset}") + path = Path(item["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid external evaluation: {path}") + rows = checked(report, "per_hand_rows") + cache = checked(report, "cache_manifest") + checked(report, "checkpoint") + checked(report, "config") + reports[condition][dataset] = { + "path": str(path.resolve()), "report": report, + "rows": rows, "cache": cache, + } + for condition in CONDITIONS: + if set(reports[condition]) != set(DATASETS): + raise ValueError(f"{condition} does not contain all external domains") + datasets: dict[str, Any] = {} + for dataset in DATASETS: + reference = reports[CONDITIONS[0]][dataset] + candidate = reports[CONDITIONS[1]][dataset] + for key in ("sha256",): + if reference["report"]["cache_manifest"][key] != candidate["report"]["cache_manifest"][key]: + raise ValueError(f"{dataset} cache differs between L0 and L1") + if reference["report"]["input_mode"] != candidate["report"]["input_mode"]: + raise ValueError(f"{dataset} input mode differs between L0 and L1") + condition_metrics: dict[str, Any] = {} + for condition, record in ((CONDITIONS[0], reference), (CONDITIONS[1], candidate)): + report_metrics = record["report"]["metrics"] + condition_metrics[condition] = { + metric: ( + None if report_metrics.get(row_metric) is None + else float(report_metrics[row_metric][statistic]) + ) + for metric, (row_metric, statistic) in METRICS.items() + } + paired = { + metric: paired_recording_bootstrap( + reference["rows"], candidate["rows"], row_metric, statistic, + seed, resamples, + ) + for metric, (row_metric, statistic) in METRICS.items() + if condition_metrics[CONDITIONS[0]][metric] is not None + and condition_metrics[CONDITIONS[1]][metric] is not None + } + datasets[dataset] = { + "cache_manifest_sha256": reference["report"]["cache_manifest"]["sha256"], + "input_mode": reference["report"]["input_mode"], + "conditions": condition_metrics, + "paired_L1_minus_L0": paired, + } + macro: dict[str, Any] = {} + for metric in ("absolute_mpjpe_mm", "root_relative_mpjpe_mm"): + values = { + condition: [datasets[dataset]["conditions"][condition][metric] for dataset in DATASETS] + for condition in CONDITIONS + } + macro[metric] = { + **{condition: sum(rows) / len(rows) for condition, rows in values.items()}, + } + macro[metric]["L1_minus_L0"] = ( + macro[metric][CONDITIONS[1]] - macro[metric][CONDITIONS[0]] + ) + left_datasets = ("HOI4D", "ARCTIC") + source_values = { + condition: [ + datasets[dataset]["conditions"][condition]["source_root_relative_mpjpe_mm"] + for dataset in left_datasets + ] + for condition in CONDITIONS + } + if any(value is None for values in source_values.values() for value in values): + raise ValueError("left held-out source-root supervision is missing") + macro["source_root_relative_mpjpe_mm"] = { + condition: sum(values) / len(values) for condition, values in source_values.items() + } + macro["source_root_relative_mpjpe_mm"]["L1_minus_L0"] = ( + macro["source_root_relative_mpjpe_mm"][CONDITIONS[1]] + - macro["source_root_relative_mpjpe_mm"][CONDITIONS[0]] + ) + source_gain = -macro["source_root_relative_mpjpe_mm"]["L1_minus_L0"] + accepted = ( + source_gain >= 0.5 + and macro["absolute_mpjpe_mm"]["L1_minus_L0"] <= 1.0 + and macro["root_relative_mpjpe_mm"]["L1_minus_L0"] <= 1.0 + ) + return { + "schema_version": "phase8_stage7_left_comparison_v1", + "status": "complete", "datasets": datasets, "dataset_macro": macro, + "gate": { + "minimum_source_root_gain_mm": 0.5, + "maximum_absolute_regression_mm": 1.0, + "maximum_root_relative_regression_mm": 1.0, + "accepted": accepted, + }, + "h2o_training_data_used": False, "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/derive_phase9_hot_subset.py b/home/wuyifan/EgoNet_train_20261008/scripts/derive_phase9_hot_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..abbd427229e098170eb3c8a45d4aef55ad057922 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/derive_phase9_hot_subset.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Derive a deterministic headset/recording-balanced HOT3D cache subset.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict, deque +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def balanced_subset(rows: list[dict[str, Any]], clips: int) -> list[dict[str, Any]]: + if clips <= 0 or clips > len(rows): + raise ValueError("subset size must be in [1, source rows]") + unique_indices = {int(row["source_clip_index"]) for row in rows} + if len(unique_indices) != len(rows): + raise ValueError("source cache contains duplicate source_clip_index values") + grouped: dict[str, dict[str, deque[dict[str, Any]]]] = defaultdict(dict) + by_recording: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for row in rows: + headset = str(row.get("headset_id", "unknown")) + recording = str(row["physical_recording_id"]) + by_recording[(headset, recording)].append(row) + for (headset, recording), recording_rows in by_recording.items(): + grouped[headset][recording] = deque(sorted( + recording_rows, key=lambda row: int(row["source_clip_index"]), + )) + + headsets = sorted(grouped) + recording_cursor = {headset: 0 for headset in headsets} + recording_ids = { + headset: sorted(grouped[headset]) for headset in headsets + } + selected: list[dict[str, Any]] = [] + while len(selected) < clips: + progress = False + for headset in headsets: + ids = recording_ids[headset] + for _ in range(len(ids)): + cursor = recording_cursor[headset] % len(ids) + recording_cursor[headset] += 1 + queue = grouped[headset][ids[cursor]] + if queue: + selected.append(queue.popleft()) + progress = True + break + if len(selected) == clips: + break + if not progress: + raise RuntimeError("balanced subset exhausted before requested size") + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--source-report", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + report = json.loads(args.source_report.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(args.source_manifest) + ): + parser.error("source cache report does not bind a complete manifest") + rows = load_jsonl(args.source_manifest) + selected = balanced_subset(rows, args.clips) + missing = [row["cache_path"] for row in selected if not Path(row["cache_path"]).is_file()] + if missing: + parser.error(f"selected cache payload is missing: {missing[0]}") + args.output_dir.mkdir(parents=True) + manifest = args.output_dir / "cache_manifest.jsonl" + temporary = manifest.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in selected), + encoding="utf-8", + ) + temporary.replace(manifest) + headset_counts = Counter(str(row.get("headset_id", "unknown")) for row in selected) + stream_counts = Counter(str(row.get("stream_id", "unknown")) for row in selected) + recording_counts = Counter(str(row["physical_recording_id"]) for row in selected) + output = { + "schema_version": "phase9_hot_balanced_subset_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "source_cache_manifest": { + "path": str(args.source_manifest.resolve()), + "sha256": sha256(args.source_manifest), + "rows": len(rows), + }, + "source_cache_report": { + "path": str(args.source_report.resolve()), + "sha256": sha256(args.source_report), + }, + "cache_manifest": { + "path": str(manifest.resolve()), + "sha256": sha256(manifest), + }, + "clips": len(selected), + "unique_source_clip_indices": len({int(row["source_clip_index"]) for row in selected}), + "recordings": len(recording_counts), + "headset_clip_counts": dict(sorted(headset_counts.items())), + "stream_clip_counts": dict(sorted(stream_counts.items())), + "recording_clip_count_min": min(recording_counts.values()), + "recording_clip_count_max": max(recording_counts.values()), + "payload_copy_bytes": 0, + "payloads_referenced_from_parent": True, + "official_test_used": False, + } + report_path = args.output_dir / "cache_report.json" + report_path.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8") + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase3.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase3.py new file mode 100644 index 0000000000000000000000000000000000000000..4acdc8f9c12791353d8d2fd3653421539f757245 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase3.py @@ -0,0 +1,1155 @@ +#!/usr/bin/env python3 +"""Audited Phase 3 validation with MANO meshes, tail metrics, and take CIs.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.phase4 import ( + action_name, + bimanual_asymmetry, + depth_validity_bucket, + find_failure_intervals, + load_action_label, + local_depth_statistics, + summarize_group_metrics, +) +from foundation_hand.evaluation.selection import select_visualization_frames +from foundation_hand.evaluation.visualization import ( + MeshLayer, + draw_skeleton, + project_mesh_layers, + render_mesh_layers, + save_attention_figure, + save_camera_views, +) +from foundation_hand.geometry.camera import project_points, unproject_depth +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +SIDES = ("left", "right") +PREDICTED_COLORS = ((32, 190, 105), (235, 112, 45)) +TARGET_COLORS = ((40, 160, 245), (215, 55, 190)) +FINGERTIP_INDICES = (4, 8, 12, 16, 20) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_clip_indices_manifest( + path: Path, + *, + source_manifest: Path, + data_config: dict[str, object], + dataset_length: int, +) -> tuple[list[int], dict[str, object]]: + record = json.loads(path.read_text(encoding="utf-8")) + contract = record.get("dataset_contract", {}) + resolution = [int(value) for value in data_config["resolution_hw"]] + if record.get("source_manifest_sha256") != sha256(source_manifest): + raise ValueError("clip subset source-manifest hash mismatch") + if int(record.get("source_clip_count", -1)) != dataset_length: + raise ValueError("clip subset source length mismatch") + if contract.get("resolution_hw") != resolution: + raise ValueError("clip subset resolution mismatch") + if int(contract.get("T", -1)) != int(data_config["T"]): + raise ValueError("clip subset temporal length mismatch") + if int(contract.get("stride", -1)) != int(data_config["stride"]): + raise ValueError("clip subset stride mismatch") + indices = [int(index) for index in record.get("clip_indices", [])] + if len(indices) != int(record.get("count", -1)) or len(indices) != len(set(indices)): + raise ValueError("clip subset count/uniqueness mismatch") + if not indices or min(indices) < 0 or max(indices) >= dataset_length: + raise ValueError("clip subset index out of bounds") + return indices, record + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def rgb_from_batch(batch: dict[str, Any], time_index: int) -> np.ndarray: + rgb = batch["rgb"][0, time_index].float().cpu().permute(1, 2, 0).numpy() + return np.clip((rgb * RGB_STD + RGB_MEAN) * 255.0, 0, 255).astype(np.uint8) + + +def hand_size_bucket(size: float | None) -> str | None: + if size is None: + return None + if size < 64: + return "small" + if size < 128: + return "medium" + return "large" + + +def wrist_depth_bucket(depth: float | None) -> str | None: + if depth is None: + return None + if depth < 0.5: + return "near" + if depth < 0.8: + return "middle" + return "far" + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + return + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def temporal_position_bias_report(model: BimanualReconstructionModel) -> dict[str, object]: + layers = [] + for layer_index, layer in enumerate(model.decoder.temporal): + bias = getattr(layer, "relative_position_bias", None) + if bias is None: + continue + values = bias.detach().float().cpu().numpy() + max_distance = int(layer.relative_bias_max_distance) + layers.append({ + "layer": layer_index, + "offsets_key_minus_query": list(range(-max_distance, max_distance + 1)), + "shape": list(values.shape), + "mean": float(values.mean()), + "std": float(values.std()), + "max_abs": float(np.abs(values).max()), + "per_head_bias": values.tolist(), + }) + return { + "mode": model.config.temporal_position_mode, + "sign_convention": "key_time_minus_query_time", + "layers": layers, + } + + +def add_label(image: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image.copy() + box_height = 8 + 18 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], box_height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (6, 17 + 18 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.38, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def attach_gt_geometry( + batch: dict[str, Any], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor]: + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + vertices, joints = model.mano_layer( + axis_angle_to_matrix(pose), + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + return vertices, joints + + +def run_model( + model: BimanualReconstructionModel, + batch: dict[str, Any], + dtype: torch.dtype, +) -> dict[str, Any]: + with torch.autocast("cuda", dtype=dtype): + return model(batch) + + +def save_depth_geometry( + output: Path, batch: dict[str, Any], time_index: int, title: str, +) -> None: + depth = batch["depth_m"][0, time_index, 0].float().cpu().numpy() + valid = batch["depth_pixel_valid"][0, time_index, 0].bool().cpu().numpy() + K = batch["K"][0, time_index].float().cpu().numpy() + xyz, xyz_valid = unproject_depth(depth, K) + fig, axes = plt.subplots(2, 3, figsize=(13, 7), constrained_layout=True) + values = ( + (depth, "depth (m)", "viridis"), + (valid, "depth validity", "gray"), + (xyz[..., 2], "Z (m)", "viridis"), + (np.where(xyz_valid, xyz[..., 0], np.nan), "X (m)", "coolwarm"), + (np.where(xyz_valid, xyz[..., 1], np.nan), "Y (m)", "coolwarm"), + (np.linalg.norm(xyz, axis=-1), "XYZ norm (m)", "viridis"), + ) + for axis, (value, name, cmap) in zip(axes.flat, values, strict=True): + artist = axis.imshow(value, cmap=cmap) + axis.set_title(name) + axis.axis("off") + fig.colorbar(artist, ax=axis, shrink=0.75) + fig.suptitle(title) + fig.savefig(output, dpi=150) + plt.close(fig) + + +def render_frame_bundle( + output_dir: Path, + image: np.ndarray, + K: np.ndarray, + predicted_vertices: np.ndarray, + target_vertices: np.ndarray, + predicted_joints: np.ndarray, + target_joints_2d: np.ndarray, + direct_joints_2d: np.ndarray, + mano_joints_2d: np.ndarray, + valid_hands: np.ndarray, + faces: tuple[np.ndarray, np.ndarray], + title_lines: tuple[str, ...], +) -> np.ndarray: + predicted_layers = [ + MeshLayer(predicted_vertices[hand], faces[hand], PREDICTED_COLORS[hand], 0.58) + for hand in range(2) + ] + target_layers = [ + MeshLayer(target_vertices[hand], faces[hand], TARGET_COLORS[hand], 0.50) + for hand in range(2) if valid_hands[hand] + ] + predicted_render = render_mesh_layers(image, project_mesh_layers(predicted_layers, K)) + target_render = render_mesh_layers(image, project_mesh_layers(target_layers, K)) + joint_render = render_mesh_layers( + image, project_mesh_layers(target_layers + predicted_layers, K), + ) + panels = [image, target_render, predicted_render, joint_render] + names = ("RGB", "GT MANO", "predicted MANO", "joint z-buffer overlay") + labeled_panels = [] + for panel, name in zip(panels, names, strict=True): + labeled_panels.append(add_label(panel, (name,))) + mosaic = np.concatenate(( + np.concatenate(labeled_panels[:2], axis=1), + np.concatenate(labeled_panels[2:], axis=1), + ), axis=0) + cv2.imwrite(str(output_dir / "mesh_rgb_overlay.png"), cv2.cvtColor(add_label(mosaic, title_lines), cv2.COLOR_RGB2BGR)) + + for hand, side in enumerate(SIDES): + layers = [predicted_layers[hand]] + if valid_hands[hand]: + layers.insert(0, MeshLayer(target_vertices[hand], faces[hand], TARGET_COLORS[hand], 0.50)) + rendered = render_mesh_layers(image, project_mesh_layers(layers, K)) + cv2.imwrite(str(output_dir / f"{side}_mesh_overlay.png"), cv2.cvtColor(add_label(rendered, title_lines), cv2.COLOR_RGB2BGR)) + + skeleton = image.copy() + for hand in range(2): + if valid_hands[hand]: + skeleton = draw_skeleton(skeleton, target_joints_2d[hand], (255, 255, 255), marker="cross") + skeleton = draw_skeleton(skeleton, direct_joints_2d[hand], PREDICTED_COLORS[hand], marker="circle", draw_edges=False) + skeleton = draw_skeleton(skeleton, mano_joints_2d[hand], TARGET_COLORS[hand], marker="ring") + skeleton = add_label(skeleton, title_lines + ("GT=white cross; direct-2D=dot; projected predicted MANO=ring",)) + cv2.imwrite(str(output_dir / "skeleton_consistency_overlay.png"), cv2.cvtColor(skeleton, cv2.COLOR_RGB2BGR)) + return add_label(joint_render, title_lines) + + +def visualize_selections( + selections: list[dict[str, object]], + dataset: H2OCam4Dataset, + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + config: dict[str, Any], + output_root: Path, +) -> None: + faces = tuple(layer.th_faces.cpu().numpy() for layer in model.mano_layer.layers) + modalities = "RGB" + ("+Depth" if config["model"].get("use_depth") else "") + ("+K" if config["model"].get("use_rays") else "") + for selection_index, selection in enumerate(selections): + clip_index = int(selection["clip_index"]) + requested_time = int(selection["time_index"]) + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(): + target_vertices, _ = attach_gt_geometry(batch, model) + prediction = run_model(model, batch, dtype) + valid_times = int(batch["frame_valid"][0].sum()) + time_index = min(requested_time, valid_times - 1) + sample_dir = output_root / f"{selection_index:02d}_{selection['subject']}_{str(selection['sequence']).replace('/', '_')}_{int(selection['frame_id']):06d}" + sample_dir.mkdir(parents=True, exist_ok=True) + valid_hands = batch["mano_annotation_valid"][0, time_index].bool().cpu().numpy() + K = batch["K"][0, time_index].float().cpu().numpy() + image = rgb_from_batch(batch, time_index) + predicted_vertices = prediction["vertices_camera"][0, time_index].float().cpu().numpy() + target_vertices_np = target_vertices[0, time_index].float().cpu().numpy() + predicted_joints = prediction["joints_camera"][0, time_index].float() + mano_2d, _ = project_points(predicted_joints, batch["K"][0, time_index].float()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"][0, time_index].float().cpu().numpy() * np.asarray((width, height)) + title_lines = ( + f"{selection['subject']}/{selection['sequence']}/{int(selection['frame_id'])} | L/R valid={int(valid_hands[0])}/{int(valid_hands[1])}", + f"config={config['name']} input={modalities} presence=unsupervised", + f"selection={','.join(str(reason) for reason in selection['reasons'])}", + ) + render_frame_bundle( + sample_dir, image, K, predicted_vertices, target_vertices_np, + predicted_joints.cpu().numpy(), batch["joint2d"][0, time_index].float().cpu().numpy(), + direct_2d, mano_2d.cpu().numpy(), valid_hands, faces, title_lines, + ) + save_camera_views( + sample_dir / "camera_3d_front_side.png", predicted_vertices, target_vertices_np, + valid_hands, " | ".join(title_lines[:2]), + ) + save_depth_geometry(sample_dir / "depth_xyz.png", batch, time_index, " | ".join(title_lines[:2])) + + attention = prediction["attention"] + grid_hw = (height // int(config["model"].get("patch_size", 16)), width // int(config["model"].get("patch_size", 16))) + rgb_attention = attention["rgb_cross_attention"][0, -1, time_index].float().cpu().numpy() + save_attention_figure( + sample_dir / "rgb_attention_raw_shared_scale.png", image, + rgb_attention[0], rgb_attention[1], grid_hw, "RGB | " + " | ".join(title_lines[:2]), + ) + if "depth_cross_attention" in attention: + depth_attention = attention["depth_cross_attention"][0, -1, time_index].float().cpu().numpy() + save_attention_figure( + sample_dir / "depth_attention_raw_shared_scale.png", image, + depth_attention[0], depth_attention[1], grid_hw, "Depth | " + " | ".join(title_lines[:2]), + ) + if "temporal_attention" in attention: + temporal = attention["temporal_attention"][0, -1].float().cpu().numpy() + shared_max = max(float(temporal.max()), 1e-8) + fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True) + artist = None + for hand, side in enumerate(SIDES): + artist = axes[hand].imshow(temporal[hand], vmin=0, vmax=shared_max, cmap="viridis") + axes[hand].set_title(side) + axes[hand].set_xlabel("key frame") + axes[hand].set_ylabel("query frame") + fig.colorbar(artist, ax=axes, label="raw head-averaged attention weight") + fig.suptitle("last-layer, head-averaged temporal attention; not calibrated probability") + fig.savefig(sample_dir / "temporal_attention_raw_shared_scale.png", dpi=160) + plt.close(fig) + + video_path = sample_dir / "clip_mesh_overlay.mp4" + writer = cv2.VideoWriter(str(video_path), cv2.VideoWriter_fourcc(*"mp4v"), 4.0, (width, height)) + for clip_time in range(valid_times): + clip_image = rgb_from_batch(batch, clip_time) + clip_K = batch["K"][0, clip_time].float().cpu().numpy() + clip_valid = batch["mano_annotation_valid"][0, clip_time].bool().cpu().numpy() + pred_layers = [ + MeshLayer(prediction["vertices_camera"][0, clip_time, hand].float().cpu().numpy(), faces[hand], PREDICTED_COLORS[hand], 0.58) + for hand in range(2) + ] + gt_layers = [ + MeshLayer(target_vertices[0, clip_time, hand].float().cpu().numpy(), faces[hand], TARGET_COLORS[hand], 0.50) + for hand in range(2) if clip_valid[hand] + ] + rendered = render_mesh_layers(clip_image, project_mesh_layers(gt_layers + pred_layers, clip_K)) + rendered = add_label(rendered, ( + f"{selection['subject']}/{selection['sequence']} frame={int(batch['frame_id'][0, clip_time])}", + f"L/R valid={int(clip_valid[0])}/{int(clip_valid[1])} config={config['name']} input={modalities}", + )) + writer.write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + writer.release() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + parser.add_argument("--clip-indices-manifest", type=Path) + parser.add_argument("--num-workers", type=int, default=0) + parser.add_argument("--seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--skip-visualizations", action="store_true") + parser.add_argument( + "--phase4-diagnostics", + action="store_true", + help=( + "Add signed translation, action, asymmetry, local-depth, group, " + "CVaR, and long-failure diagnostics without changing model inference." + ), + ) + parser.add_argument( + "--drop-depth", action="store_true", + help="Mark metric depth unavailable at inference while retaining the RGB-D-K checkpoint.", + ) + parser.add_argument( + "--drop-k", action="store_true", + help="Mark intrinsics/ray conditioning unavailable at inference while retaining the RGB-D-K checkpoint.", + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + max_clips=args.max_clips, + oracle_crop_enabled=( + config["model"].get("oracle_crop_mode", "none") != "none" + ), + ) + subset_record = None + evaluation_dataset = dataset + if args.clip_indices_manifest is not None: + if args.max_clips is not None: + parser.error("--max-clips and --clip-indices-manifest are mutually exclusive") + if not args.skip_visualizations: + parser.error("clip-index subset evaluation requires --skip-visualizations") + indices, subset_record = load_clip_indices_manifest( + args.clip_indices_manifest, + source_manifest=args.manifest, + data_config=data_config, + dataset_length=len(dataset), + ) + evaluation_dataset = Subset(dataset, indices) + loader = DataLoader( + evaluation_dataset, batch_size=1, shuffle=False, num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + values: dict[str, list[float]] = defaultdict(list) + per_joint: dict[str, list[float]] = defaultdict(list) + attention_values: dict[str, list[float]] = defaultdict(list) + temporal_by_distance: dict[int, list[float]] = defaultdict(list) + temporal_by_signed_distance: dict[int, list[float]] = defaultdict(list) + frame_rows: list[dict[str, object]] = [] + temporal_rows: list[dict[str, object]] = [] + oracle_refinement_values: dict[str, list[float]] = defaultdict(list) + selection_records: list[dict[str, object]] = [] + frame_count = 0 + + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = move_to_device(batch_cpu, device) + target_vertices, _ = attach_gt_geometry(batch, model) + if args.drop_depth: + batch["depth_input_available"] = torch.zeros_like(batch["frame_valid"], dtype=torch.bool) + batch["depth_available"] = batch["depth_input_available"] + if args.drop_k: + batch["K_input_available"] = torch.zeros_like(batch["frame_valid"], dtype=torch.bool) + batch["K_available"] = batch["K_input_available"] + prediction = run_model(model, batch, dtype) + frame_valid = batch["frame_valid"].bool() + if "mixed_projection_success" in prediction: + mixed_valid = frame_valid[..., None].expand_as( + prediction["mixed_projection_success"], + ) + mixed_diagnostics = { + "mixed_projection_success_fraction": prediction[ + "mixed_projection_success" + ].float(), + "mixed_projection_support_count": prediction[ + "mixed_projection_support_count" + ].float(), + "mixed_projection_conditioning": prediction[ + "mixed_projection_conditioning" + ].float(), + "mixed_projection_inlier_ratio": prediction[ + "mixed_projection_inlier_ratio" + ].float(), + "mixed_projection_residual_scale_px": prediction[ + "mixed_projection_residual_scale_px" + ].float(), + } + for key, diagnostic in mixed_diagnostics.items(): + values[key].extend(diagnostic[mixed_valid].cpu().tolist()) + joint_annotation = batch["joint_annotation_valid"].bool() & frame_valid[..., None] + mano_annotation = batch["mano_annotation_valid"].bool() & frame_valid[..., None] + joint_valid = batch["joint_element_valid"].bool() & joint_annotation[..., None] + frame_count += int(frame_valid.sum()) + + target_joints = torch.nan_to_num(batch["joint3d_camera"]) + predicted_joints = prediction["joints_camera"].float() + absolute_joint_error = torch.linalg.vector_norm(predicted_joints - target_joints, dim=-1) * 1000.0 + predicted_relative = predicted_joints - predicted_joints[..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + relative_joint_error = torch.linalg.vector_norm(predicted_relative - target_relative, dim=-1) * 1000.0 + translation_signed_error = ( + prediction["wrist_root_translation"].float() + - torch.nan_to_num(batch["wrist_root_translation"]) + ) * 1000.0 + translation_error = translation_signed_error.abs() + + oracle_refinement = "coarse_joints_camera" in prediction + if oracle_refinement: + coarse_joints = prediction["coarse_joints_camera"].float() + coarse_absolute_joint_error = torch.linalg.vector_norm( + coarse_joints - target_joints, dim=-1, + ) * 1000.0 + coarse_relative = coarse_joints - coarse_joints[..., :1, :] + coarse_relative_joint_error = torch.linalg.vector_norm( + coarse_relative - target_relative, dim=-1, + ) * 1000.0 + coarse_translation_error = ( + prediction["coarse_wrist_root_translation"].float() + - torch.nan_to_num(batch["wrist_root_translation"]) + ).abs() * 1000.0 + rotation_delta_degrees = torch.linalg.vector_norm( + prediction["oracle_crop_rotation_delta_axis_angle"].float(), + dim=-1, + ).mean(dim=-1) * (180.0 / np.pi) + shape_delta_l2 = torch.linalg.vector_norm( + prediction["oracle_crop_shape_delta"].float(), dim=-1, + ) + delta_z_mm = prediction["oracle_crop_delta_z"].float().squeeze(-1) * 1000.0 + + vertex_error = torch.linalg.vector_norm(prediction["vertices_camera"].float() - target_vertices, dim=-1) * 1000.0 + predicted_vertex_relative = prediction["vertices_camera"].float() - prediction["wrist_root_translation"].float()[..., None, :] + target_vertex_relative = target_vertices - torch.nan_to_num(batch["wrist_root_translation"])[..., None, :] + relative_vertex_error = torch.linalg.vector_norm(predicted_vertex_relative - target_vertex_relative, dim=-1) * 1000.0 + if oracle_refinement: + coarse_vertices = prediction["coarse_vertices_camera"].float() + coarse_vertex_error = torch.linalg.vector_norm( + coarse_vertices - target_vertices, dim=-1, + ) * 1000.0 + coarse_vertex_relative = ( + coarse_vertices + - prediction["coarse_wrist_root_translation"].float()[..., None, :] + ) + coarse_relative_vertex_error = torch.linalg.vector_norm( + coarse_vertex_relative - target_vertex_relative, dim=-1, + ) * 1000.0 + + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor((width, height), device=device) + legacy_direct_2d = prediction["joint2d_norm"] * torch.tensor((width, height), device=device) + mano_2d, mano_positive = project_points(predicted_joints, batch["K"].float()) + target_2d = torch.nan_to_num(batch["joint2d"]) + direct_2d_error = torch.linalg.vector_norm(direct_2d - target_2d, dim=-1) + legacy_direct_2d_error = torch.linalg.vector_norm(legacy_direct_2d - target_2d, dim=-1) + mano_2d_error = torch.linalg.vector_norm(mano_2d - target_2d, dim=-1) + direct_mano_consistency = torch.linalg.vector_norm(direct_2d - mano_2d, dim=-1) + + for hand, side in enumerate(SIDES): + mask = joint_valid[..., hand, :] + hand_mask = mano_annotation[..., hand] + values[f"{side}_absolute_mpjpe_mm"].extend( + absolute_joint_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_root_relative_mpjpe_mm"].extend( + relative_joint_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_direct_2d_error_px"].extend( + direct_2d_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_legacy_bf16_direct_2d_error_px"].extend( + legacy_direct_2d_error[..., hand, :][mask].float().cpu().tolist() + ) + projected_mask = mask & mano_positive[..., hand, :] + values[f"{side}_mano_projected_2d_error_px"].extend( + mano_2d_error[..., hand, :][projected_mask].cpu().tolist() + ) + values[f"{side}_direct_mano_2d_consistency_px"].extend( + direct_mano_consistency[..., hand, :][projected_mask].cpu().tolist() + ) + values[f"{side}_absolute_mpvpe_mm"].extend(vertex_error[..., hand, :].mean(-1)[hand_mask].cpu().tolist()) + values[f"{side}_root_relative_mpvpe_mm"].extend(relative_vertex_error[..., hand, :].mean(-1)[hand_mask].cpu().tolist()) + for axis_index, axis in enumerate("xyz"): + values[f"{side}_translation_{axis}_mae_mm"].extend(translation_error[..., hand, axis_index][joint_annotation[..., hand]].cpu().tolist()) + if args.phase4_diagnostics: + values[f"{side}_translation_{axis}_signed_error_mm"].extend( + translation_signed_error[..., hand, axis_index][ + joint_annotation[..., hand] + ].cpu().tolist() + ) + for joint_index in range(21): + joint_mask = mask[..., joint_index] + per_joint[f"{side}_{joint_index:02d}_absolute_mpjpe_mm"].extend( + absolute_joint_error[..., hand, joint_index][joint_mask].cpu().tolist() + ) + fingertip_mask = mask[..., list(FINGERTIP_INDICES)] + fingertip_count = fingertip_mask.sum(-1) + values[f"{side}_fingertip_mpjpe_mm"].extend( + ( + (absolute_joint_error[..., hand, list(FINGERTIP_INDICES)] * fingertip_mask).sum(-1) + / fingertip_count.clamp_min(1) + )[fingertip_count > 0].cpu().tolist() + ) + + if predicted_joints.shape[1] > 1: + pair_valid = joint_annotation[:, 1:] & joint_annotation[:, :-1] + predicted_wrist_velocity = prediction["wrist_root_translation"][:, 1:] - prediction["wrist_root_translation"][:, :-1] + target_wrist_velocity = torch.nan_to_num(batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1]) + wrist_velocity_error = torch.linalg.vector_norm(predicted_wrist_velocity - target_wrist_velocity, dim=-1) * 1000.0 + values["wrist_velocity_error_mm_per_frame"].extend(wrist_velocity_error[pair_valid].float().cpu().tolist()) + predicted_joint_velocity = predicted_joints[:, 1:] - predicted_joints[:, :-1] + target_joint_velocity = target_joints[:, 1:] - target_joints[:, :-1] + pair_joint_valid = joint_valid[:, 1:] & joint_valid[:, :-1] + joint_velocity_error = torch.linalg.vector_norm(predicted_joint_velocity - target_joint_velocity, dim=-1) * 1000.0 + values["joint_velocity_error_mm_per_frame"].extend(joint_velocity_error[pair_joint_valid].cpu().tolist()) + acceleration_valid = None + acceleration_error = None + if predicted_wrist_velocity.shape[1] > 1: + acceleration_valid = pair_valid[:, 1:] & pair_valid[:, :-1] + predicted_acceleration = predicted_wrist_velocity[:, 1:] - predicted_wrist_velocity[:, :-1] + target_acceleration = target_wrist_velocity[:, 1:] - target_wrist_velocity[:, :-1] + acceleration_error = torch.linalg.vector_norm(predicted_acceleration - target_acceleration, dim=-1) * 1000.0 + values["wrist_acceleration_error_mm_per_frame2"].extend(acceleration_error[acceleration_valid].float().cpu().tolist()) + + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + for transition_index in range(pair_valid.shape[1]): + for hand, side in enumerate(SIDES): + if not bool(pair_valid[0, transition_index, hand]): + continue + valid_joint_mask = pair_joint_valid[0, transition_index, hand] + joint_value = ( + float(joint_velocity_error[0, transition_index, hand][valid_joint_mask].mean()) + if bool(valid_joint_mask.any()) else None + ) + acceleration_value = None + if ( + transition_index > 0 + and acceleration_valid is not None + and bool(acceleration_valid[0, transition_index - 1, hand]) + ): + acceleration_value = float(acceleration_error[0, transition_index - 1, hand]) + temporal_rows.append({ + "clip_index": clip_index, + "transition_index": transition_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id_from": int(batch["frame_id"][0, transition_index]), + "frame_id_to": int(batch["frame_id"][0, transition_index + 1]), + "side": side, + "wrist_velocity_error_mm_per_frame": float(wrist_velocity_error[0, transition_index, hand]), + "joint_velocity_error_mm_per_frame": joint_value, + "wrist_acceleration_error_mm_per_frame2": acceleration_value, + "identity_switch_fraction": None, + }) + + wrong_sequence: list[bool | None] = [] + valid_length = int(frame_valid[0].sum()) + for time_index in range(valid_length): + annotation_state = "".join(str(int(value)) for value in joint_annotation[0, time_index].int().cpu().tolist()) + both_valid = bool(joint_annotation[0, time_index].all()) + wrong_side = None + if both_valid: + correct = 0.5 * ( + absolute_joint_error[0, time_index, 0].mean() + + absolute_joint_error[0, time_index, 1].mean() + ) + swapped = 0.5 * ( + torch.linalg.vector_norm(predicted_joints[0, time_index, 0] - target_joints[0, time_index, 1], dim=-1).mean() + + torch.linalg.vector_norm(predicted_joints[0, time_index, 1] - target_joints[0, time_index, 0], dim=-1).mean() + ) * 1000.0 + wrong_side = bool(swapped < correct) + values["wrong_side_preference"].append(float(wrong_side)) + wrong_sequence.append(wrong_side) + valid_hand_errors = [ + float(absolute_joint_error[0, time_index, hand].mean()) + for hand in range(2) if joint_annotation[0, time_index, hand] + ] + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + frame_id = int(batch["frame_id"][0, time_index]) + sizes: list[float | None] = [None, None] + depths: list[float | None] = [None, None] + for hand in range(2): + is_valid = bool(joint_annotation[0, time_index, hand]) + if is_valid: + extent = batch["joint2d"][0, time_index, hand].max(0).values - batch["joint2d"][0, time_index, hand].min(0).values + sizes[hand] = float(extent.max()) + depths[hand] = float(batch["wrist_root_translation"][0, time_index, hand, 2]) + valid_sizes = [value for value in sizes if value is not None] + valid_depths = [value for value in depths if value is not None] + asymmetry = bimanual_asymmetry(sizes, depths) + if args.phase4_diagnostics: + action_label = load_action_label(args.root, take, frame_id) + action = action_name(action_label) + action_family = str(batch["sequence_id"][0]).split("/", 1)[0] + depth_np = batch["depth_m"][0, time_index, 0].float().cpu().numpy() + depth_valid_np = ( + batch["depth_pixel_valid"][0, time_index, 0].bool().cpu().numpy() + ) + else: + action_label = None + action = None + action_family = None + depth_np = None + depth_valid_np = None + for hand in range(2): + is_valid = bool(joint_annotation[0, time_index, hand]) + size = sizes[hand] + depth = depths[hand] + local_depth: dict[str, float | int | None] = {} + if args.phase4_diagnostics and is_valid: + local_depth = local_depth_statistics( + depth_np, + depth_valid_np, + batch["joint2d"][0, time_index, hand].float().cpu().numpy(), + ) + local_median = local_depth.get("depth_median_m") + local_surface_minus_wrist = ( + float(local_median) - float(depth) + if local_median is not None and depth is not None + else None + ) + row = { + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "side": SIDES[hand], + "annotation_valid": int(is_valid), + "annotation_state": annotation_state, + "hand_size_px": size, + "hand_size_bucket": hand_size_bucket(size), + "wrist_depth_m": depth, + "depth_bucket": wrist_depth_bucket(depth), + "absolute_mpjpe_mm": float(absolute_joint_error[0, time_index, hand].mean()) if is_valid else None, + "root_relative_mpjpe_mm": float(relative_joint_error[0, time_index, hand].mean()) if is_valid else None, + "absolute_mpvpe_mm": float(vertex_error[0, time_index, hand].mean()) if bool(mano_annotation[0, time_index, hand]) else None, + "root_relative_mpvpe_mm": float(relative_vertex_error[0, time_index, hand].mean()) if bool(mano_annotation[0, time_index, hand]) else None, + "direct_2d_error_px": float(direct_2d_error[0, time_index, hand].mean()) if is_valid else None, + "legacy_bf16_direct_2d_error_px": float(legacy_direct_2d_error[0, time_index, hand].mean()) if is_valid else None, + "mano_projected_2d_error_px": float(mano_2d_error[0, time_index, hand].mean()) if is_valid else None, + "direct_mano_2d_consistency_px": float(direct_mano_consistency[0, time_index, hand].mean()) if is_valid else None, + "fingertip_mpjpe_mm": float(absolute_joint_error[0, time_index, hand, list(FINGERTIP_INDICES)].mean()) if is_valid else None, + "translation_x_mae_mm": float(translation_error[0, time_index, hand, 0]) if is_valid else None, + "translation_y_mae_mm": float(translation_error[0, time_index, hand, 1]) if is_valid else None, + "translation_z_mae_mm": float(translation_error[0, time_index, hand, 2]) if is_valid else None, + "wrong_side_preference": int(wrong_side) if wrong_side is not None else None, + } + if args.phase4_diagnostics: + predicted_translation = prediction["wrist_root_translation"][ + 0, time_index, hand + ].float() + target_translation = batch["wrist_root_translation"][ + 0, time_index, hand + ].float() + row.update({ + "action_family": action_family, + "action_label": action_label, + "action_name": action, + **asymmetry, + "local_depth_valid_fraction": local_depth.get("valid_fraction"), + "local_depth_validity_bucket": depth_validity_bucket( + local_depth.get("valid_fraction") + ), + "local_depth_median_m": local_median, + "local_depth_q10_m": local_depth.get("depth_q10_m"), + "local_depth_q90_m": local_depth.get("depth_q90_m"), + "local_depth_iqr_m": local_depth.get("depth_iqr_m"), + "local_depth_discontinuity_m": local_depth.get( + "depth_discontinuity_m" + ), + "local_surface_minus_wrist_z_m": local_surface_minus_wrist, + "predicted_wrist_x_m": ( + float(predicted_translation[0]) if is_valid else None + ), + "predicted_wrist_y_m": ( + float(predicted_translation[1]) if is_valid else None + ), + "predicted_wrist_z_m": ( + float(predicted_translation[2]) if is_valid else None + ), + "target_wrist_x_m": float(target_translation[0]) if is_valid else None, + "target_wrist_y_m": float(target_translation[1]) if is_valid else None, + "target_wrist_z_m": float(target_translation[2]) if is_valid else None, + "translation_x_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 0]) + if is_valid else None + ), + "translation_y_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 1]) + if is_valid else None + ), + "translation_z_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 2]) + if is_valid else None + ), + }) + if oracle_refinement: + mano_is_valid = bool(mano_annotation[0, time_index, hand]) + oracle_fields = { + "coarse_absolute_mpjpe_mm": ( + float(coarse_absolute_joint_error[0, time_index, hand].mean()) + if is_valid else None + ), + "coarse_root_relative_mpjpe_mm": ( + float(coarse_relative_joint_error[0, time_index, hand].mean()) + if is_valid else None + ), + "coarse_absolute_mpvpe_mm": ( + float(coarse_vertex_error[0, time_index, hand].mean()) + if mano_is_valid else None + ), + "coarse_root_relative_mpvpe_mm": ( + float(coarse_relative_vertex_error[0, time_index, hand].mean()) + if mano_is_valid else None + ), + "coarse_fingertip_mpjpe_mm": ( + float(coarse_absolute_joint_error[ + 0, time_index, hand, list(FINGERTIP_INDICES) + ].mean()) + if is_valid else None + ), + "coarse_translation_z_mae_mm": ( + float(coarse_translation_error[0, time_index, hand, 2]) + if is_valid else None + ), + "oracle_crop_delta_z_mm": ( + float(delta_z_mm[0, time_index, hand]) + if is_valid else None + ), + "oracle_crop_rotation_delta_geodesic_deg": ( + float(rotation_delta_degrees[0, time_index, hand]) + if is_valid else None + ), + "oracle_crop_shape_delta_l2": ( + float(shape_delta_l2[0, hand]) if is_valid else None + ), + "oracle_crop_rgb_available": int( + prediction["oracle_crop_rgb_available"][0, time_index, hand] + ), + "oracle_crop_depth_available": int( + prediction["oracle_crop_depth_available_effective"][ + 0, time_index, hand + ] + ), + } + row.update(oracle_fields) + if is_valid: + for key, value in oracle_fields.items(): + if key.startswith("oracle_crop_") and value is not None: + oracle_refinement_values[key].append(float(value)) + frame_rows.append(row) + selection_records.append({ + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "annotation_state": annotation_state, + "hand_size_bucket": hand_size_bucket(float(np.mean(valid_sizes))) if valid_sizes else None, + "depth_bucket": wrist_depth_bucket(float(np.mean(valid_depths))) if valid_depths else None, + "absolute_mpjpe_mm": float(np.mean(valid_hand_errors)) if valid_hand_errors else None, + }) + for transition_index, (previous, current) in enumerate( + zip(wrong_sequence[:-1], wrong_sequence[1:], strict=True) + ): + if previous is not None and current is not None: + identity_switch = float(previous != current) + values["identity_switch_fraction"].append(identity_switch) + temporal_rows.append({ + "clip_index": clip_index, + "transition_index": transition_index, + "take": f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4", + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id_from": int(batch["frame_id"][0, transition_index]), + "frame_id_to": int(batch["frame_id"][0, transition_index + 1]), + "side": "bimanual", + "wrist_velocity_error_mm_per_frame": None, + "joint_velocity_error_mm_per_frame": None, + "wrist_acceleration_error_mm_per_frame2": None, + "identity_switch_fraction": identity_switch, + }) + + attention = prediction["attention"] + rgb = attention["rgb_cross_attention"][:, -1] + left, right = rgb[..., 0, :], rgb[..., 1, :] + attention_values["rgb_same_peak"].extend((left.argmax(-1) == right.argmax(-1))[frame_valid].float().cpu().tolist()) + attention_values["rgb_left_right_cosine"].extend(torch.nn.functional.cosine_similarity(left, right, dim=-1)[frame_valid].float().cpu().tolist()) + attention_values["rgb_update_norm"].extend(attention["rgb_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + for key in ("depth_fusion_gate", "depth_fusion_gate_raw", "depth_update_norm", "gated_depth_update_norm"): + if key in attention: + attention_values[key].extend(attention[key][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + if "temporal_update_norm" in attention: + attention_values["temporal_update_norm"].extend( + attention["temporal_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist() + ) + if "temporal_attention" in attention: + temporal = attention["temporal_attention"][:, -1] + for hand in range(2): + valid_indices = torch.where(frame_valid[0])[0] + for query_index in valid_indices: + weights = temporal[0, hand, query_index, valid_indices].float() + normalized = weights / weights.sum().clamp_min(1e-8) + if normalized.numel() > 1: + entropy = -(normalized * normalized.clamp_min(1e-8).log()).sum() / np.log(normalized.numel()) + attention_values["temporal_normalized_entropy"].append(float(entropy)) + attention_values["temporal_diagonal"].append(float(temporal[0, hand, query_index, query_index])) + for key_index, key_frame in enumerate(valid_indices): + signed_distance = int(key_frame) - int(query_index) + temporal_by_distance[abs(signed_distance)].append(float(weights[key_index])) + temporal_by_signed_distance[signed_distance].append(float(weights[key_index])) + + selections = select_visualization_frames(selection_records, seed=args.seed) + strata_counts = { + field: { + str(value): sum(record.get(field) == value for record in selection_records) + for value in values_to_count + } + for field, values_to_count in ( + ("hand_size_bucket", ("small", "medium", "large")), + ("depth_bucket", ("near", "middle", "far")), + ("annotation_state", ("00", "01", "10", "11")), + ) + } + selection_manifest = { + "seed": args.seed, + "source_manifest": str(args.manifest.resolve()), + "clip_indices_manifest": ( + { + "path": str(args.clip_indices_manifest.resolve()), + "sha256": sha256(args.clip_indices_manifest), + "version": subset_record.get("version"), + "count": subset_record.get("count"), + } + if args.clip_indices_manifest is not None else None + ), + "checkpoint": str(args.checkpoint.resolve()), + "selection_policy": "random4 + error P50/P90/P95/worst + size/depth/valid-state medians", + "strata_counts": strata_counts, + "unavailable_requested_strata": [ + f"{field}={value}" + for field, counts in strata_counts.items() + for value, count in counts.items() if count == 0 + ], + "samples": selections, + } + (args.output_dir / "selection_manifest.json").write_text(json.dumps(selection_manifest, indent=2) + "\n", encoding="utf-8") + write_csv(args.output_dir / "per_hand_frame_metrics.csv", frame_rows) + write_csv(args.output_dir / "per_temporal_transition_metrics.csv", temporal_rows) + phase4_group_rows: list[dict[str, object]] = [] + phase4_failure_rows: list[dict[str, object]] = [] + if args.phase4_diagnostics: + phase4_metrics = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + ) + if oracle_refinement_values: + phase4_metrics += ( + "coarse_absolute_mpjpe_mm", + "coarse_root_relative_mpjpe_mm", + "coarse_absolute_mpvpe_mm", + "coarse_root_relative_mpvpe_mm", + "coarse_fingertip_mpjpe_mm", + "coarse_translation_z_mae_mm", + "oracle_crop_delta_z_mm", + "oracle_crop_rotation_delta_geodesic_deg", + "oracle_crop_shape_delta_l2", + ) + phase4_group_rows = summarize_group_metrics( + frame_rows, + phase4_metrics, + ( + "take", + "action_family", + "action_label", + "action_name", + "hand_size_bucket", + "depth_bucket", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", + ), + ) + phase4_failure_rows = find_failure_intervals( + frame_rows, + metric="translation_z_mae_mm", + threshold=40.0, + minimum_frames=3, + ) + find_failure_intervals( + frame_rows, + metric="absolute_mpjpe_mm", + threshold=50.0, + minimum_frames=3, + ) + write_csv(args.output_dir / "phase4_group_metrics.csv", phase4_group_rows) + write_csv(args.output_dir / "phase4_failure_intervals.csv", phase4_failure_rows) + + joint_rows = [] + for name, metric_values in sorted(per_joint.items()): + side, joint_index, _ = name.split("_", 2) + joint_rows.append({"side": side, "joint_index": int(joint_index), **distribution_summary(metric_values)}) + write_csv(args.output_dir / "per_joint_metrics.csv", joint_rows) + + bootstrap_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", "direct_2d_error_px", "mano_projected_2d_error_px", + "translation_z_mae_mm", "fingertip_mpjpe_mm", "wrong_side_preference", + ) + bootstrap_rows = bootstrap_take_means( + frame_rows, bootstrap_metrics, seed=args.seed, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "bootstrap_ci.csv", bootstrap_rows) + temporal_bootstrap_metrics = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", + ) + temporal_bootstrap_rows = bootstrap_take_means( + temporal_rows, temporal_bootstrap_metrics, + seed=args.seed, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "temporal_bootstrap_ci.csv", temporal_bootstrap_rows) + + distribution_metrics = {key: distribution_summary(metric_values) for key, metric_values in sorted(values.items())} + combined_keys = { + "absolute_mpjpe_mm": ("left_absolute_mpjpe_mm", "right_absolute_mpjpe_mm"), + "root_relative_mpjpe_mm": ("left_root_relative_mpjpe_mm", "right_root_relative_mpjpe_mm"), + "absolute_mpvpe_mm": ("left_absolute_mpvpe_mm", "right_absolute_mpvpe_mm"), + "root_relative_mpvpe_mm": ("left_root_relative_mpvpe_mm", "right_root_relative_mpvpe_mm"), + "direct_2d_error_px": ("left_direct_2d_error_px", "right_direct_2d_error_px"), + "legacy_bf16_direct_2d_error_px": ("left_legacy_bf16_direct_2d_error_px", "right_legacy_bf16_direct_2d_error_px"), + "mano_projected_2d_error_px": ("left_mano_projected_2d_error_px", "right_mano_projected_2d_error_px"), + "direct_mano_2d_consistency_px": ("left_direct_mano_2d_consistency_px", "right_direct_mano_2d_consistency_px"), + "fingertip_mpjpe_mm": ("left_fingertip_mpjpe_mm", "right_fingertip_mpjpe_mm"), + "translation_z_mae_mm": ("left_translation_z_mae_mm", "right_translation_z_mae_mm"), + } + for combined, components in combined_keys.items(): + distribution_metrics[combined] = distribution_summary(values[components[0]] + values[components[1]]) + + attention_report = { + key: distribution_summary(metric_values) for key, metric_values in sorted(attention_values.items()) + } + attention_report["temporal_attention_by_absolute_frame_distance"] = { + str(distance): distribution_summary(metric_values) + for distance, metric_values in sorted(temporal_by_distance.items()) + } + attention_report["temporal_attention_by_signed_frame_distance"] = { + str(distance): distribution_summary(metric_values) + for distance, metric_values in sorted(temporal_by_signed_distance.items()) + } + (args.output_dir / "attention_diagnostics.json").write_text(json.dumps(attention_report, indent=2) + "\n", encoding="utf-8") + position_bias_report = temporal_position_bias_report(model) + (args.output_dir / "temporal_position_bias.json").write_text( + json.dumps(position_bias_report, indent=2) + "\n", encoding="utf-8", + ) + + report = { + "status": "evaluated", + "split_role": "official_validation" if "val" in args.manifest.name else "non_test_evaluation", + "official_test_used": False, + "config": config, + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": sha256(args.checkpoint), + "step": int(checkpoint_state["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "inference_modality_override": { + "drop_depth": bool(args.drop_depth), + "drop_k": bool(args.drop_k), + "availability_contract": "input_and_legacy_flags_v2", + }, + "clips": len(evaluation_dataset), + "clip_indices_manifest": ( + { + "path": str(args.clip_indices_manifest.resolve()), + "sha256": sha256(args.clip_indices_manifest), + "version": subset_record.get("version"), + "count": subset_record.get("count"), + } + if args.clip_indices_manifest is not None else None + ), + "frames": frame_count, + "data_loader_workers": args.num_workers, + "metrics": distribution_metrics, + "attention": attention_report, + "temporal_position_bias": position_bias_report, + "bootstrap": bootstrap_rows, + "temporal_bootstrap": temporal_bootstrap_rows, + "phase4_diagnostics": { + "enabled": bool(args.phase4_diagnostics), + "group_rows": len(phase4_group_rows), + "failure_intervals": len(phase4_failure_rows), + "local_depth_contract": ( + "GT-joint region on aligned resized metric depth; surface statistics are " + "diagnostic and are not wrist-depth targets" + if args.phase4_diagnostics else None + ), + "failure_thresholds": ( + {"translation_z_mae_mm": 40.0, "absolute_mpjpe_mm": 50.0} + if args.phase4_diagnostics else None + ), + }, + "oracle_crop_refinement": { + "enabled": bool(oracle_refinement_values), + "gt_location_at_inference": bool(oracle_refinement_values), + "coarse_checkpoint_sha256": config.get("experiment", {}).get( + "coarse_checkpoint_sha256" + ), + "metrics": { + key: distribution_summary(metric_values) + for key, metric_values in sorted(oracle_refinement_values.items()) + }, + }, + "metric_definitions": { + "absolute_mpjpe_mm": "valid-joint-weighted Euclidean camera-space joint error", + "direct_2d_error_px": "valid-joint-weighted direct-head pixel error; frame means are used for take bootstrap", + "legacy_bf16_direct_2d_error_px": "Phase 2 compatibility metric that scales bf16 normalized coordinates before float conversion", + "absolute_mpvpe_mm": "mean Euclidean camera-space vertex error; MVE/MPVPE", + "root_relative_mpvpe_mm": "vertex error after subtracting each wrist/root", + "wrong_side_preference": "swapped L/R joint assignment has lower combined cost than semantic assignment", + "identity_switch_fraction": "adjacent both-valid frames change wrong-side assignment preference", + "translation_axis_signed_error_mm": "predicted camera-space wrist axis minus GT wrist axis", + "cvar95": "mean of observations at or above the empirical 95th percentile", + "attention": "last-layer, PyTorch head-averaged attention weights; not calibrated probability", + }, + "presence_note": "H2O annotation validity is not presence; no presence metric is reported.", + "device": torch.cuda.get_device_name(device), + "trainable_parameters": sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad), + "frozen_parameters": sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad), + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + + if not args.skip_visualizations: + visualize_selections( + selections, dataset, model, device, dtype, config, + args.output_dir / "visualization_audit", + ) + print(json.dumps({ + "status": report["status"], "clips": report["clips"], "frames": report["frames"], + "absolute_mpjpe_mm": distribution_metrics["absolute_mpjpe_mm"]["mean"], + "absolute_mpvpe_mm": distribution_metrics["absolute_mpvpe_mm"]["mean"], + "output_dir": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase4_jitter.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase4_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..01ef42bd758f0d15f63365ddcabec5115ffd2f99 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase4_jitter.py @@ -0,0 +1,767 @@ +#!/usr/bin/env python3 +"""Evaluate preregistered inference-only temporal filters from raw caches.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +import numpy as np +import torch + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.temporal_filter import ( + apply_by_segment, + butterworth_zero_phase, + derivative_norms, + ema, + ema_low_frequency_delay_frames, + filter_rotation_matrices, + high_frequency_energy_ratio, + rotation_geodesic_degrees, + valid_segments, +) +from foundation_hand.models.mano import ManoCameraLayer + + +FPS = 30.0 +FINGERTIPS = (4, 8, 12, 16, 20) + + +@dataclass(frozen=True) +class FilterCondition: + name: str + family: str + value: float | None + causal_status: str + latency_frames: float | None + + +def condition_grid() -> dict[str, FilterCondition]: + conditions = { + "F0_raw": FilterCondition("F0_raw", "F0", None, "raw", 0.0), + } + for alpha in (0.2, 0.4, 0.6): + name = f"F1_ema_alpha{alpha:g}" + conditions[name] = FilterCondition( + name, "F1", alpha, "causal", ema_low_frequency_delay_frames(alpha), + ) + for cutoff in (2.0, 4.0, 6.0): + name = f"F2_butterworth_{cutoff:g}hz" + conditions[name] = FilterCondition( + name, "F2", cutoff, "offline_zero_phase", None, + ) + return conditions + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty jitter report: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_take(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + if float(arrays["fps"]) != FPS: + raise ValueError(f"jitter cache fps mismatch: {path}") + return arrays + + +def filtered_parameters( + arrays: dict[str, np.ndarray], condition: FilterCondition, +) -> tuple[np.ndarray, np.ndarray, int]: + translation = arrays["pred_wrist_translation"].astype(np.float32) + rotations = arrays["pred_rotation_matrices"].astype(np.float32) + if condition.family == "F0": + return translation.copy(), rotations.copy(), 0 + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + if condition.family == "F1": + assert condition.value is not None + translation, fallback_translation = apply_by_segment( + translation, segments, + lambda values: ema(values, condition.value), minimum_frames=1, + ) + rotations, fallback_rotation = apply_by_segment( + rotations, segments, + lambda values: filter_rotation_matrices( + values, lambda quaternion: ema(quaternion, condition.value), + ), + minimum_frames=1, + ) + elif condition.family == "F2": + assert condition.value is not None + operation = lambda values: butterworth_zero_phase( + values, condition.value, FPS, order=2, + ) + translation, fallback_translation = apply_by_segment( + translation, segments, operation, minimum_frames=4, + ) + rotations, fallback_rotation = apply_by_segment( + rotations, segments, + lambda values: filter_rotation_matrices(values, operation), + minimum_frames=4, + ) + else: + raise ValueError(f"unsupported filter family: {condition.family}") + if fallback_translation != fallback_rotation: + raise AssertionError("translation/rotation filter fallback counts differ") + return translation, rotations, fallback_translation + + +def rebuild_geometry( + rotations: np.ndarray, + shape: np.ndarray, + translation: np.ndarray, + mano: ManoCameraLayer, + device: torch.device, + chunk_size: int = 256, +) -> tuple[np.ndarray, np.ndarray]: + vertices = [] + joints = [] + for start in range(0, len(rotations), chunk_size): + stop = min(start + chunk_size, len(rotations)) + with torch.inference_mode(): + chunk_vertices, chunk_joints = mano( + torch.from_numpy(rotations[start:stop]).to(device), + torch.from_numpy(shape[start:stop]).to(device), + torch.from_numpy(translation[start:stop]).to(device), + ) + vertices.append(chunk_vertices.cpu().numpy()) + joints.append(chunk_joints.cpu().numpy()) + return np.concatenate(vertices), np.concatenate(joints) + + +def project_points(points: np.ndarray, intrinsics: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + z = points[..., 2] + positive = np.isfinite(points).all(axis=-1) & (z > 1e-8) + safe_z = np.where(positive, z, 1.0) + x = intrinsics[:, None, None, 0, 0] * points[..., 0] / safe_z + x += intrinsics[:, None, None, 0, 2] + y = intrinsics[:, None, None, 1, 1] * points[..., 1] / safe_z + y += intrinsics[:, None, None, 1, 2] + projected = np.stack((x, y), axis=-1) + projected[~positive] = np.nan + return projected, positive + + +def append_finite(output: dict[str, list[float]], key: str, values: Iterable[float]) -> None: + output[key].extend(float(value) for value in values if np.isfinite(value)) + + +def per_frame_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + vertices: np.ndarray, + rotations: np.ndarray, + translation: np.ndarray, + frame_selected: np.ndarray, +) -> tuple[dict[str, list[float]], np.ndarray, np.ndarray]: + output: dict[str, list[float]] = defaultdict(list) + target_joints = arrays["target_joints_camera"] + target_vertices = arrays["target_vertices_camera"] + target_translation = arrays["target_wrist_translation"] + joint_valid = arrays["joint_element_valid"].astype(bool) + joint_valid &= frame_selected[:, None, None] + mano_valid = arrays["mano_annotation_valid"].astype(bool) + mano_valid &= frame_selected[:, None] + + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + joint_relative = joints - joints[..., :1, :] + target_joint_relative = target_joints - target_joints[..., :1, :] + root_joint_error = np.linalg.norm( + joint_relative - target_joint_relative, axis=-1, + ) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + vertex_relative = vertices - translation[..., None, :] + target_vertex_relative = target_vertices - target_translation[..., None, :] + root_vertex_error = np.linalg.norm( + vertex_relative - target_vertex_relative, axis=-1, + ) * 1000.0 + translation_signed = (translation - target_translation) * 1000.0 + + projected, projected_positive = project_points(joints, arrays["K"]) + projected_valid = joint_valid & projected_positive + target_2d = arrays["target_2d_px"] + projected_error = np.linalg.norm(projected - target_2d, axis=-1) + consistency = np.linalg.norm(projected - arrays["pred_direct_2d_px"], axis=-1) + direct_error = np.linalg.norm(arrays["pred_direct_2d_px"] - target_2d, axis=-1) + rotation_error = rotation_geodesic_degrees( + rotations, arrays["target_rotation_matrices"], + ).mean(axis=-1) + + for time_index in range(len(joints)): + for hand in range(2): + valid_joints = joint_valid[time_index, hand] + if valid_joints.any(): + append_finite(output, "absolute_mpjpe_mm", [ + joint_error[time_index, hand, valid_joints].mean() + ]) + append_finite(output, "root_relative_mpjpe_mm", [ + root_joint_error[time_index, hand, valid_joints].mean() + ]) + fingertip_valid = valid_joints[list(FINGERTIPS)] + if fingertip_valid.any(): + fingertip_values = joint_error[ + time_index, hand, list(FINGERTIPS) + ][fingertip_valid] + append_finite(output, "fingertip_mpjpe_mm", [fingertip_values.mean()]) + append_finite(output, "direct_2d_error_px", [ + direct_error[time_index, hand, valid_joints].mean() + ]) + valid_projected = projected_valid[time_index, hand] + if valid_projected.any(): + append_finite(output, "projected_mano_2d_error_px", [ + projected_error[time_index, hand, valid_projected].mean() + ]) + append_finite(output, "direct_mano_consistency_px", [ + consistency[time_index, hand, valid_projected].mean() + ]) + for axis, name in enumerate("xyz"): + append_finite(output, f"translation_{name}_signed_error_mm", [ + translation_signed[time_index, hand, axis] + ]) + append_finite(output, f"translation_{name}_mae_mm", [ + abs(translation_signed[time_index, hand, axis]) + ]) + if mano_valid[time_index, hand]: + append_finite(output, "absolute_mpvpe_mm", [ + vertex_error[time_index, hand].mean() + ]) + append_finite(output, "root_relative_mpvpe_mm", [ + root_vertex_error[time_index, hand].mean() + ]) + append_finite(output, "rotation_geodesic_error_deg", [ + rotation_error[time_index, hand] + ]) + return output, projected, joint_valid + + +def selected_segments( + arrays: dict[str, np.ndarray], frame_selected: np.ndarray, +) -> list[np.ndarray]: + return valid_segments( + arrays["clip_index"], arrays["frame_id"], + arrays["frame_valid"].astype(bool) & frame_selected, + ) + + +def temporal_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + projected: np.ndarray, + frame_selected: np.ndarray, +) -> dict[str, list[float]]: + output: dict[str, list[float]] = defaultdict(list) + segments = selected_segments(arrays, frame_selected) + target = arrays["target_joints_camera"] + annotation = arrays["joint_element_valid"].astype(bool) + for indices in segments: + for hand in range(2): + predicted_hand = joints[indices, hand] + target_hand = target[indices, hand] + valid_hand = annotation[indices, hand] + for order, error_name in ( + (1, "joint_velocity_error_mm_per_s"), + (2, "joint_acceleration_error_mm_per_s2"), + ): + if len(indices) <= order: + continue + predicted_derivative = np.diff(predicted_hand, n=order, axis=0) * FPS**order + target_derivative = np.diff(target_hand, n=order, axis=0) * FPS**order + derivative_valid = np.stack([ + valid_hand[start : len(valid_hand) - order + start] + for start in range(order + 1) + ]).all(axis=0) + errors = np.linalg.norm( + predicted_derivative - target_derivative, axis=-1, + ) * 1000.0 + for row, valid in zip(errors, derivative_valid, strict=True): + if valid.any(): + append_finite(output, error_name, [row[valid].mean()]) + translation_hand = joints[indices, hand, 0] + target_translation_hand = arrays["target_wrist_translation"][indices, hand] + translation_valid = arrays["joint_annotation_valid"][indices, hand].astype(bool) + for order, error_name in ( + (1, "wrist_velocity_error_mm_per_s"), + (2, "wrist_acceleration_error_mm_per_s2"), + ): + if len(indices) <= order: + continue + predicted_derivative = np.diff( + translation_hand, n=order, axis=0, + ) * FPS**order + target_derivative = np.diff( + target_translation_hand, n=order, axis=0, + ) * FPS**order + derivative_valid = np.stack([ + translation_valid[start : len(translation_valid) - order + start] + for start in range(order + 1) + ]).all(axis=0) + errors = np.linalg.norm( + predicted_derivative - target_derivative, axis=-1, + ) * 1000.0 + append_finite(output, error_name, errors[derivative_valid]) + if len(indices) >= 3: + acceleration = derivative_norms(predicted_hand, FPS, 2) * 1000.0 + append_finite( + output, "predicted_3d_joint_acceleration_mm_per_s2", + acceleration.mean(axis=-1), + ) + projected_acceleration = derivative_norms( + projected[indices, hand], FPS, 2, + ) + append_finite( + output, "predicted_2d_joint_acceleration_px_per_s2", + np.nanmean(projected_acceleration, axis=-1), + ) + if len(indices) >= 4: + jerk = derivative_norms(predicted_hand, FPS, 3) * 1000.0 + append_finite( + output, "predicted_3d_joint_jerk_mm_per_s3", + jerk.mean(axis=-1), + ) + projected_jerk = derivative_norms(projected[indices, hand], FPS, 3) + append_finite( + output, "predicted_2d_joint_jerk_px_per_s3", + np.nanmean(projected_jerk, axis=-1), + ) + append_finite(output, "high_frequency_energy_ratio", [ + high_frequency_energy_ratio(predicted_hand, FPS, 6.0) + ]) + if len(indices) >= 3: + velocity = derivative_norms(predicted_hand, FPS, 1).mean(axis=-1) + append_finite(output, "velocity_variation_m_per_s", [ + np.std(velocity) + ]) + + # Report jumps at clip boundaries without allowing the filter to cross them. + for index in range(1, len(joints)): + if ( + frame_selected[index - 1] + and frame_selected[index] + and arrays["frame_valid"][index - 1] + and arrays["frame_valid"][index] + and arrays["frame_id"][index] == arrays["frame_id"][index - 1] + 1 + and arrays["clip_index"][index] != arrays["clip_index"][index - 1] + ): + jump = np.linalg.norm(joints[index] - joints[index - 1], axis=-1) * 1000.0 + append_finite( + output, "clip_boundary_discontinuity_mm", jump.mean(axis=-1), + ) + return output + + +def identity_switch_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + frame_selected: np.ndarray, +) -> dict[str, list[float]]: + wrong: list[bool | None] = [] + target = arrays["target_joints_camera"] + annotation = arrays["joint_annotation_valid"].astype(bool) + for index in range(len(joints)): + if not frame_selected[index] or not annotation[index].all(): + wrong.append(None) + continue + semantic = ( + np.linalg.norm(joints[index, 0] - target[index, 0], axis=-1).mean() + + np.linalg.norm(joints[index, 1] - target[index, 1], axis=-1).mean() + ) + swapped = ( + np.linalg.norm(joints[index, 0] - target[index, 1], axis=-1).mean() + + np.linalg.norm(joints[index, 1] - target[index, 0], axis=-1).mean() + ) + wrong.append(bool(swapped < semantic)) + switches = [] + for indices in selected_segments(arrays, frame_selected): + for previous, current in zip(indices[:-1], indices[1:], strict=True): + if wrong[previous] is not None and wrong[current] is not None: + switches.append(float(wrong[previous] != wrong[current])) + return {"identity_switch_fraction": switches} + + +def summarize_condition( + values: dict[str, list[float]], + condition: FilterCondition, + scope: str, +) -> list[dict[str, object]]: + return [ + { + "scope": scope, "condition": condition.name, + "family": condition.family, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + "metric": metric, **distribution_summary(observations), + } + for metric, observations in sorted(values.items()) + ] + + +def metric_lookup(rows: list[dict[str, object]], condition: str, metric: str) -> dict[str, object]: + matches = [ + row for row in rows + if row["condition"] == condition and row["metric"] == metric + ] + if len(matches) != 1: + raise ValueError(f"expected one jitter metric row for {condition}/{metric}") + return matches[0] + + +def build_overview( + metric_rows: list[dict[str, object]], conditions: list[FilterCondition], + scope: str, +) -> list[dict[str, object]]: + raw_name = "F0_raw" + keys = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "z_p95_mm": ("translation_z_mae_mm", "p95"), + "velocity_error_mm_per_s": ("joint_velocity_error_mm_per_s", "mean"), + "acceleration_error_mm_per_s2": ("joint_acceleration_error_mm_per_s2", "mean"), + "jitter_3d_acceleration_mm_per_s2": ( + "predicted_3d_joint_acceleration_mm_per_s2", "mean", + ), + "jitter_3d_jerk_mm_per_s3": ("predicted_3d_joint_jerk_mm_per_s3", "mean"), + "jitter_2d_acceleration_px_per_s2": ( + "predicted_2d_joint_acceleration_px_per_s2", "mean", + ), + "jitter_2d_jerk_px_per_s3": ("predicted_2d_joint_jerk_px_per_s3", "mean"), + "high_frequency_energy_ratio": ("high_frequency_energy_ratio", "mean"), + } + raw = { + name: float(metric_lookup(metric_rows, raw_name, metric)[statistic]) + for name, (metric, statistic) in keys.items() + } + output = [] + for condition in conditions: + values = { + name: float(metric_lookup(metric_rows, condition.name, metric)[statistic]) + for name, (metric, statistic) in keys.items() + } + row: dict[str, object] = { + "scope": scope, "condition": condition.name, + "family": condition.family, "filter_value": condition.value, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + } + for name, value in values.items(): + row[name] = value + row[f"{name}_delta"] = value - raw[name] + guardrails = [ + 100.0 * (values[name] - raw[name]) / raw[name] + for name in ( + "absolute_mpjpe_mm", "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", "z_p95_mm", + ) + ] + reductions = [ + (raw[name] - values[name]) / raw[name] + for name in ( + "jitter_3d_acceleration_mm_per_s2", + "jitter_3d_jerk_mm_per_s3", + "jitter_2d_acceleration_px_per_s2", + "jitter_2d_jerk_px_per_s3", + ) + ] + row["maximum_accuracy_degradation_percent"] = max(guardrails) + row["accuracy_guardrail_passed"] = bool(max(guardrails) <= 1.0) + row["jitter_reduction_score"] = float(np.mean(reductions)) + row["accuracy_delta"] = row["absolute_mpjpe_mm_delta"] + row["jitter_delta"] = row["jitter_3d_acceleration_mm_per_s2_delta"] + row["velocity_error_delta"] = row["velocity_error_mm_per_s_delta"] + row["acceleration_error_delta"] = row[ + "acceleration_error_mm_per_s2_delta" + ] + row["selected_for_full_validation"] = False + output.append(row) + return output + + +def paired_take_bootstrap_rows( + take_rows: list[dict[str, object]], + conditions: list[FilterCondition], + *, + samples: int, + seed: int = 20260716, +) -> list[dict[str, object]]: + if samples < 1: + raise ValueError("bootstrap samples must be positive") + index = { + (str(row["take"]), str(row["condition"]), str(row["metric"])): row + for row in take_rows + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(conditions): + if condition.family == "F0": + continue + for metric_index, metric in enumerate(metrics): + for statistic_name in ("mean", "p95"): + paired = [] + raw_values = [] + filtered_values = [] + for take in takes: + raw = index.get((take, "F0_raw", metric)) + filtered = index.get((take, condition.name, metric)) + if raw is None or filtered is None: + continue + raw_value = raw.get(statistic_name) + filtered_value = filtered.get(statistic_name) + if raw_value is None or filtered_value is None: + continue + raw_float = float(raw_value) + filtered_float = float(filtered_value) + if not np.isfinite(raw_float) or not np.isfinite(filtered_float): + continue + raw_values.append(raw_float) + filtered_values.append(filtered_float) + paired.append(filtered_float - raw_float) + deltas = np.asarray(paired, dtype=np.float64) + if not len(deltas): + continue + rng = np.random.default_rng(np.random.SeedSequence([ + seed, condition_index, metric_index, + 0 if statistic_name == "mean" else 1, + ])) + indices = rng.integers(0, len(deltas), size=(samples, len(deltas))) + bootstrap = deltas[indices].mean(axis=1) + output.append({ + "scope": take_rows[0]["scope"], + "condition": condition.name, + "family": condition.family, + "metric": metric, + "take_statistic": statistic_name, + "takes": len(deltas), + "raw": float(np.mean(raw_values)), + "filtered": float(np.mean(filtered_values)), + "filtered_minus_raw": float(deltas.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def choose_filter_conditions(overview: list[dict[str, object]]) -> dict[str, str | None]: + selected: dict[str, str | None] = {"F1": None, "F2": None} + for family in selected: + candidates = [ + row for row in overview + if row["family"] == family and row["accuracy_guardrail_passed"] + ] + if not candidates: + continue + candidates.sort(key=lambda row: ( + -float(row["jitter_reduction_score"]), + float(row["acceleration_error_mm_per_s2"]), + float(row["absolute_mpjpe_mm"]), + -float(row["filter_value"]), + )) + selected[family] = str(candidates[0]["condition"]) + candidates[0]["selected_for_full_validation"] = True + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument( + "--scope", choices=("smoke", "subset", "full"), required=True, + ) + parser.add_argument("--subset-manifest", type=Path) + parser.add_argument("--selection-json", type=Path) + parser.add_argument("--conditions") + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise ValueError("jitter output directory must be new or empty") + cache_manifest = json.loads( + (args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8") + ) + expected_cache_scope = "smoke" if args.scope == "smoke" else "full" + if ( + cache_manifest.get("status") != "complete" + or cache_manifest.get("official_test_used") is not False + or float(cache_manifest.get("fps")) != FPS + or cache_manifest.get("scope") != expected_cache_scope + or ( + expected_cache_scope == "full" + and (cache_manifest.get("clips") != 1495 or cache_manifest.get("frames") != 11638) + ) + ): + raise ValueError("invalid raw jitter cache manifest") + grid = condition_grid() + if args.conditions: + requested = [value.strip() for value in args.conditions.split(",") if value.strip()] + else: + requested = list(grid) + if not requested or set(requested) - set(grid) or "F0_raw" not in requested: + raise ValueError("jitter conditions must be registered and include F0_raw") + if args.scope == "subset": + if args.subset_manifest is None or args.selection_json is not None: + raise ValueError("subset scope requires only --subset-manifest") + subset = json.loads(args.subset_manifest.read_text(encoding="utf-8")) + selected_clip_indices = {int(value) for value in subset["clip_indices"]} + if ( + len(selected_clip_indices) != 256 + or subset.get("source_manifest_sha256") + != cache_manifest["manifest"]["sha256"] + or subset.get("official_test_used", False) is not False + ): + raise ValueError("jitter tuning subset must be the frozen 256 clips") + elif args.scope == "full": + if args.selection_json is None or args.subset_manifest is not None: + raise ValueError("full scope requires only --selection-json") + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + selected_names = { + value for value in selection["selected_conditions"].values() + if value is not None + } + if set(requested) != {"F0_raw", *selected_names}: + raise ValueError("full evaluation conditions differ from frozen subset selection") + selected_clip_indices = None + else: + if args.selection_json is not None or args.subset_manifest is not None: + raise ValueError("smoke scope does not accept selection/subset inputs") + selected_clip_indices = None + + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + conditions = [grid[name] for name in requested] + global_values: dict[str, dict[str, list[float]]] = { + condition.name: defaultdict(list) for condition in conditions + } + take_rows = [] + fallback_rows = [] + for take_record in cache_manifest["takes"]: + arrays = load_take(Path(take_record["path"])) + frame_selected = ( + np.ones(len(arrays["frame_id"]), dtype=bool) + if selected_clip_indices is None else + np.isin(arrays["clip_index"], list(selected_clip_indices)) + ) + if not frame_selected.any(): + continue + take = str(arrays["take"]) + for condition in conditions: + translation, rotations, fallbacks = filtered_parameters(arrays, condition) + vertices, joints = rebuild_geometry( + rotations, arrays["pred_shape"].astype(np.float32), + translation, mano, device, + ) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, rotations, translation, frame_selected, + ) + for metric, values in temporal_metrics( + arrays, joints, projected, frame_selected, + ).items(): + metrics[metric].extend(values) + for metric, values in identity_switch_metrics( + arrays, joints, frame_selected, + ).items(): + metrics[metric].extend(values) + for metric, observations in metrics.items(): + global_values[condition.name][metric].extend(observations) + summary = distribution_summary(observations) + take_rows.append({ + "scope": args.scope, "take": take, + "condition": condition.name, "family": condition.family, + "metric": metric, **summary, + }) + fallback_rows.append({ + "scope": args.scope, "take": take, + "condition": condition.name, + "fallback_segments": fallbacks, + }) + metric_rows = [] + for condition in conditions: + metric_rows.extend(summarize_condition( + global_values[condition.name], condition, args.scope, + )) + overview = build_overview(metric_rows, conditions, args.scope) + if args.scope == "full": + for row in overview: + row["selected_for_full_validation"] = row["family"] != "F0" + paired_rows = paired_take_bootstrap_rows( + take_rows, conditions, samples=args.bootstrap_samples, + ) + selection_payload = None + if args.scope == "subset": + selected = choose_filter_conditions(overview) + selection_payload = { + "status": "selected", + "official_test_used": False, + "selection_scope": "frozen_official_validation_subset_256", + "subset_manifest": str(args.subset_manifest.resolve()), + "checkpoint": cache_manifest["checkpoint"], + "selected_conditions": selected, + "rule": ( + "<=1% maximum accuracy degradation; maximize mean relative " + "3D/2D acceleration/jerk reduction; then acceleration error, " + "absolute MPJPE, weaker smoothing" + ), + } + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "jitter_selection.json").write_text( + json.dumps(selection_payload, indent=2) + "\n", encoding="utf-8", + ) + write_csv(args.output_dir / "jitter_condition_metrics.csv", metric_rows) + write_csv(args.output_dir / "jitter_take_metrics.csv", take_rows) + write_csv(args.output_dir / "jitter_filter_fallbacks.csv", fallback_rows) + write_csv(args.output_dir / "jitter_raw_vs_filtered.csv", overview) + if paired_rows: + write_csv( + args.output_dir / "jitter_paired_take_bootstrap_ci.csv", paired_rows, + ) + report = { + "status": "evaluated", + "official_test_used": False, + "result_role": ( + "engineering_smoke" if args.scope == "smoke" + else "filtered_inference_secondary_results" + ), + "raw_model_results_remain_primary": True, + "scope": args.scope, + "fps": FPS, + "cache_manifest": str((args.cache_dir / "cache_manifest.json").resolve()), + "conditions": requested, + "selection": selection_payload, + "outputs": { + "overview": "jitter_raw_vs_filtered.csv", + "metrics": "jitter_condition_metrics.csv", + "take_metrics": "jitter_take_metrics.csv", + "fallbacks": "jitter_filter_fallbacks.csv", + "paired_take_bootstrap_ci": ( + "jitter_paired_take_bootstrap_ci.csv" if paired_rows else None + ), + }, + } + (args.output_dir / "jitter_evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "scope": args.scope, + "conditions": requested, "selection": selection_payload, + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase5_causal_state.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1f9b2876ea7a730a657e4ef9d6b15250842bed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase5_causal_state.py @@ -0,0 +1,554 @@ +#!/usr/bin/env python3 +"""Evaluate OOF-frozen causal wrist-z state estimators on official validation.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +import numpy as np + +from foundation_hand.evaluation.causal_state import ( + causal_constant_velocity_kalman, + measurement_uncertainty_multiplier, +) +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.temporal_filter import ( + apply_by_segment, + butterworth_zero_phase, + ema, + valid_segments, +) +try: + from scripts.evaluate_phase4_jitter import ( + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, + ) +except ModuleNotFoundError: # Direct `python scripts/...` execution. + from evaluate_phase4_jitter import ( # type: ignore[no-redef] + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, + ) + + +FPS = 30.0 + + +@dataclass(frozen=True) +class Condition: + name: str + family: str + causal_status: str + latency_frames: float | None + + +CONDITIONS = ( + Condition("coarse", "coarse", "causal", 0.0), + Condition("calibrated_per_frame", "calibrated", "causal", 0.0), + Condition("ema_alpha0.6", "ema", "causal_fixed_lag", (1.0 - 0.6) / 0.6), + Condition("butterworth_2hz", "butterworth", "offline_zero_phase", None), + Condition("fixed_kalman", "fixed_kalman", "causal_state", 0.0), + Condition("uncertainty_kalman", "uncertainty_kalman", "causal_state", 0.0), +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def uncertainty_base(prediction: dict[str, np.ndarray]) -> np.ndarray: + available = prediction["alignment_applied"].astype(bool) + base = measurement_uncertainty_multiplier( + prediction["confidence"], + prediction["inlier_ratio"], + prediction["residual_scale_m"], + prediction["valid_fraction"], + prediction["quality"], + 1.0, + ) + return np.where(available, base, 5.0) + + +def condition_z( + arrays: dict[str, np.ndarray], + prediction: dict[str, np.ndarray], + condition: Condition, + selection: dict[str, object], +) -> tuple[np.ndarray, np.ndarray, int]: + coarse = arrays["pred_wrist_translation"][..., 2].astype(np.float64) + available = prediction["alignment_applied"].astype(bool) + correction = np.where(available, prediction["calibrated_delta_z_m"], 0.0) + measurement = coarse + correction + variance = np.full_like(measurement, np.nan) + if condition.family == "coarse": + return coarse.copy(), variance, 0 + if condition.family == "calibrated": + return measurement, variance, 0 + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + if condition.family == "ema": + filtered, fallback = apply_by_segment( + measurement, segments, lambda values: ema(values, 0.6), minimum_frames=1, + ) + return filtered, variance, fallback + if condition.family == "butterworth": + filtered, fallback = apply_by_segment( + measurement, + segments, + lambda values: butterworth_zero_phase(values, 2.0, FPS, order=2), + minimum_frames=4, + ) + return filtered, variance, fallback + parameters = selection["selected"][condition.family] + multiplier = np.ones_like(measurement) + if condition.family == "uncertainty_kalman": + strength = float(parameters["uncertainty_strength"]) + base = uncertainty_base(prediction) + multiplier = 1.0 + strength * (base - 1.0) + measurement_available = np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), measurement.shape, + ) + filtered, variance = causal_constant_velocity_kalman( + measurement, + frame_id=arrays["frame_id"], + segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], + measurement_available=measurement_available, + process_sigma_m_per_frame2=float(parameters["process_sigma_m_per_frame2"]), + measurement_sigma_m=float(parameters["measurement_sigma_m"]), + uncertainty_multiplier=multiplier, + ) + return filtered, variance, 0 + + +def translated_geometry( + arrays: dict[str, np.ndarray], z_m: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + coarse_z = arrays["pred_wrist_translation"][..., 2] + delta = z_m - coarse_z + translation = arrays["pred_wrist_translation"].astype(np.float64).copy() + joints = arrays["pred_joints_camera"].astype(np.float64).copy() + vertices = arrays["pred_vertices_camera"].astype(np.float64).copy() + translation[..., 2] = z_m + joints[..., 2] += delta[..., None] + vertices[..., 2] += delta[..., None] + return translation, joints, vertices + + +def append_metrics( + destination: dict[str, list[float]], source: dict[str, Iterable[float]], +) -> None: + for metric, values in source.items(): + destination[metric].extend(float(value) for value in values if np.isfinite(value)) + + +def response_diagnostics( + arrays: dict[str, np.ndarray], z_m: np.ndarray, +) -> dict[str, list[float]]: + output: dict[str, list[float]] = defaultdict(list) + target = arrays["target_wrist_translation"][..., 2] + hand_valid = arrays["joint_annotation_valid"].astype(bool) + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + for indices in segments: + for hand in range(2): + selected = indices[hand_valid[indices, hand]] + if len(selected) < 3 or np.any(np.diff(selected) != 1): + continue + pred_velocity = np.diff(z_m[selected, hand]) + target_velocity = np.diff(target[selected, hand]) + step = np.abs(target_velocity) >= 0.005 + if step.any(): + output["step_same_frame_absolute_error_mm"].extend( + (np.abs(pred_velocity[step] - target_velocity[step]) * 1000.0).tolist() + ) + output["step_same_frame_gain"].extend( + (pred_velocity[step] / target_velocity[step]).tolist() + ) + correlations = [] + for lag in range(4): + pred = pred_velocity[lag:] + truth = target_velocity[: len(target_velocity) - lag or None] + if len(pred) < 3 or np.std(pred) < 1e-10 or np.std(truth) < 1e-10: + correlations.append(float("-inf")) + else: + correlations.append(float(np.corrcoef(pred, truth)[0, 1])) + if np.isfinite(correlations).any(): + output["estimated_causal_lag_frames"].append(float(np.argmax(correlations))) + if len(selected) >= 8: + error = np.abs(z_m[selected, hand] - target[selected, hand]) * 1000.0 + output["segment_endpoint_drift_delta_mm"].append(float(error[-1] - error[0])) + output["segment_length_frames"].append(float(len(selected))) + starts = np.concatenate([indices[:1] for indices in segments]) if segments else np.empty(0, dtype=int) + if len(starts): + calibrated = arrays["_calibrated_measurement_z_m"] + output["boundary_reset_difference_mm"].extend( + (np.abs(z_m[starts] - calibrated[starts]) * 1000.0).reshape(-1).tolist() + ) + return output + + +def missing_transition_diagnostics( + arrays: dict[str, np.ndarray], + prediction: dict[str, np.ndarray], + selection: dict[str, object], + family: str, +) -> dict[str, list[float]]: + parameters = selection["selected"][family] + coarse = arrays["pred_wrist_translation"][..., 2].astype(np.float64) + available = prediction["alignment_applied"].astype(bool) + full_measurement = coarse + np.where( + available, prediction["calibrated_delta_z_m"], 0.0, + ) + missing_measurement = full_measurement.copy() + multiplier = np.ones_like(full_measurement) + missing_mask = np.zeros_like(available) + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + for indices in segments: + if len(indices) >= 6: + missing_mask[indices[3:5]] = True + missing_measurement[missing_mask] = coarse[missing_mask] + if family == "uncertainty_kalman": + strength = float(parameters["uncertainty_strength"]) + base = uncertainty_base(prediction) + base[missing_mask] = 5.0 + multiplier = 1.0 + strength * (base - 1.0) + measurement_available = np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), full_measurement.shape, + ) + filtered, _ = causal_constant_velocity_kalman( + missing_measurement, + frame_id=arrays["frame_id"], segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], measurement_available=measurement_available, + process_sigma_m_per_frame2=float(parameters["process_sigma_m_per_frame2"]), + measurement_sigma_m=float(parameters["measurement_sigma_m"]), + uncertainty_multiplier=multiplier, + ) + target = arrays["target_wrist_translation"][..., 2] + hand_valid = arrays["joint_annotation_valid"].astype(bool) + output: dict[str, list[float]] = defaultdict(list) + selected = missing_mask & hand_valid + output["simulated_missing_span_z_mae_mm"].extend( + (np.abs(filtered - target)[selected] * 1000.0).tolist() + ) + for indices in segments: + if len(indices) < 6: + continue + recovery = indices[5] + valid = hand_valid[recovery] + output["first_recovery_frame_z_mae_mm"].extend( + (np.abs(filtered[recovery] - target[recovery])[valid] * 1000.0).tolist() + ) + return output + + +def paired_bootstrap( + take_rows: list[dict[str, object]], *, samples: int, seed: int = 20260716, +) -> list[dict[str, object]]: + index = { + (str(row["take"]), str(row["condition"]), str(row["metric"]), statistic): + float(row[statistic]) + for row in take_rows + for statistic in ("mean", "p95") + if row.get(statistic) is not None and np.isfinite(float(row[statistic])) + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(CONDITIONS): + if condition.name == "calibrated_per_frame": + continue + for metric_index, metric in enumerate(metrics): + for statistic_index, statistic in enumerate(("mean", "p95")): + pairs = [ + ( + index[(take, condition.name, metric, statistic)], + index[(take, "calibrated_per_frame", metric, statistic)], + ) + for take in takes + if (take, condition.name, metric, statistic) in index + and (take, "calibrated_per_frame", metric, statistic) in index + ] + if not pairs: + continue + delta = np.asarray([filtered - raw for filtered, raw in pairs]) + rng = np.random.default_rng(np.random.SeedSequence( + (seed, condition_index, metric_index, statistic_index), + )) + bootstrap = delta[ + rng.integers(0, len(delta), size=(samples, len(delta))) + ].mean(axis=1) + output.append({ + "reference": "calibrated_per_frame", "condition": condition.name, + "metric": metric, "take_statistic": statistic, "takes": len(delta), + "condition_minus_reference": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def build_overview(metric_rows: list[dict[str, object]]) -> list[dict[str, object]]: + index = { + (str(row["condition"]), str(row["metric"])): row for row in metric_rows + } + fields = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "z_mae_mm": ("translation_z_mae_mm", "mean"), + "z_p95_mm": ("translation_z_mae_mm", "p95"), + "velocity_error_mm_per_s": ("joint_velocity_error_mm_per_s", "mean"), + "acceleration_error_mm_per_s2": ("joint_acceleration_error_mm_per_s2", "mean"), + "predicted_acceleration_mm_per_s2": ( + "predicted_3d_joint_acceleration_mm_per_s2", "mean", + ), + "predicted_jerk_mm_per_s3": ("predicted_3d_joint_jerk_mm_per_s3", "mean"), + "high_frequency_energy_ratio": ("high_frequency_energy_ratio", "mean"), + "estimated_causal_lag_frames": ("estimated_causal_lag_frames", "mean"), + } + reference = { + name: float(index[("calibrated_per_frame", metric)][statistic]) + for name, (metric, statistic) in fields.items() + } + output = [] + for condition in CONDITIONS: + values = { + name: float(index[(condition.name, metric)][statistic]) + for name, (metric, statistic) in fields.items() + } + row: dict[str, object] = { + "reference": "calibrated_per_frame", "condition": condition.name, + "family": condition.family, "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + } + for name, value in values.items(): + row[name] = value + row[f"{name}_delta"] = value - reference[name] + row["accuracy_delta"] = row["absolute_mpjpe_mm_delta"] + row["jitter_delta"] = row["predicted_acceleration_mm_per_s2_delta"] + row["velocity_error_delta"] = row["velocity_error_mm_per_s_delta"] + row["acceleration_error_delta"] = row["acceleration_error_mm_per_s2_delta"] + row["static_guardrail_passed"] = bool( + float(row["absolute_mpjpe_mm_delta"]) <= 0.2 + and float(row["z_mae_mm_delta"]) <= 0.2 + and float(row["z_p95_mm_delta"]) <= 0.2 + ) + row["retained_causal_candidate"] = bool( + condition.name == "uncertainty_kalman" + and row["static_guardrail_passed"] + and float(row["jitter_delta"]) < 0.0 + and float(row["velocity_error_delta"]) < 0.0 + and float(row["acceleration_error_delta"]) < 0.0 + ) + output.append(row) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-evaluation-dir", type=Path, required=True) + parser.add_argument("--selection-json", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument( + "--continuous-take-state", + action="store_true", + help="Keep state across model inference windows until a take/frame discontinuity.", + ) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("causal-state output directory must be new or empty") + cache_manifest_path = args.cache_dir / "cache_manifest.json" + alignment_report_path = args.alignment_evaluation_dir / "evaluation.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + alignment_report = json.loads(alignment_report_path.read_text(encoding="utf-8")) + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + or cache.get("frames") != 11638 + or float(cache.get("fps")) != FPS + ): + raise ValueError("invalid complete official-validation cache contract") + if ( + alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + or alignment_report.get("coarse_checkpoint", {}).get("sha256") + != cache.get("checkpoint", {}).get("sha256") + ): + raise ValueError("alignment evaluation does not match the raw cache") + if ( + selection.get("status") != "selected" + or selection.get("official_validation_used") is not False + or selection.get("official_test_used") is not False + or "coarse z is always" not in selection.get("measurement_contract", "") + ): + raise ValueError("causal-state parameters are not valid train-OOF selections") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + global_values = {condition.name: defaultdict(list) for condition in CONDITIONS} + take_rows = [] + response_rows = [] + missing_values = { + family: defaultdict(list) for family in ("fixed_kalman", "uncertainty_kalman") + } + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw-cache take hash mismatch: {take_path}") + arrays = load_npz(take_path) + if args.continuous_take_state: + arrays["clip_index"] = np.zeros_like(arrays["clip_index"]) + stem = "__".join(Path(str(arrays["take"])).parts) + prediction_path = args.alignment_evaluation_dir / "predictions" / f"{stem}.npz" + prediction = load_npz(prediction_path) + if not np.array_equal(arrays["frame_id"], prediction["frame_id"]): + raise ValueError(f"alignment frame mismatch: {arrays['take']}") + calibrated_measurement = arrays["pred_wrist_translation"][..., 2] + np.where( + prediction["alignment_applied"], prediction["calibrated_delta_z_m"], 0.0, + ) + arrays["_calibrated_measurement_z_m"] = calibrated_measurement + saved: dict[str, np.ndarray] = {"frame_id": arrays["frame_id"]} + for condition in CONDITIONS: + z_m, variance, fallbacks = condition_z(arrays, prediction, condition, selection) + translation, joints, vertices = translated_geometry(arrays, z_m) + selected = arrays["frame_valid"].astype(bool) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, arrays["pred_rotation_matrices"], translation, selected, + ) + append_metrics(metrics, temporal_metrics(arrays, joints, projected, selected)) + append_metrics(metrics, identity_switch_metrics(arrays, joints, selected)) + response = response_diagnostics(arrays, z_m) + append_metrics(metrics, response) + for metric, observations in metrics.items(): + global_values[condition.name][metric].extend(observations) + take_rows.append({ + "take": str(arrays["take"]), "condition": condition.name, + "family": condition.family, "metric": metric, + **distribution_summary(observations), + }) + for metric, observations in response.items(): + response_rows.append({ + "take": str(arrays["take"]), "condition": condition.name, + "metric": metric, **distribution_summary(observations), + }) + saved[f"{condition.name}_z_m"] = z_m + saved[f"{condition.name}_variance_m2"] = variance + saved[f"{condition.name}_fallback_segments"] = np.asarray(fallbacks) + for family in missing_values: + append_metrics( + missing_values[family], + missing_transition_diagnostics(arrays, prediction, selection, family), + ) + np.savez_compressed(prediction_root / f"{stem}.npz", **saved) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + metric_rows = [] + for condition in CONDITIONS: + for metric, observations in sorted(global_values[condition.name].items()): + metric_rows.append({ + "condition": condition.name, "family": condition.family, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, "metric": metric, + **distribution_summary(observations), + }) + missing_rows = [ + {"condition": family, "metric": metric, **distribution_summary(observations)} + for family, values in missing_values.items() + for metric, observations in sorted(values.items()) + ] + bootstrap_rows = paired_bootstrap( + take_rows, samples=args.bootstrap_samples, + ) + overview_rows = build_overview(metric_rows) + write_csv(args.output_dir / "metrics.csv", metric_rows) + write_csv(args.output_dir / "overview.csv", overview_rows) + write_csv(args.output_dir / "take_metrics.csv", take_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap_rows) + write_csv(args.output_dir / "response_diagnostics.csv", response_rows) + write_csv(args.output_dir / "missing_modality_transition.csv", missing_rows) + report = { + "status": "evaluated", + "experiment_class": "preregistered_confirmatory_causal_state", + "result_role": "deployable_causal_translation_z_state_ablation", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "alignment_evaluation": {"path": str(alignment_report_path.resolve()), "sha256": sha256(alignment_report_path)}, + "selection": {"path": str(args.selection_json.resolve()), "sha256": sha256(args.selection_json)}, + "checkpoint": cache["checkpoint"], + "conditions": [condition.__dict__ for condition in CONDITIONS], + "state_scope": "translation z only; pose/shape and translation x/y unchanged", + "measurement_contract": selection["measurement_contract"], + "boundary_contract": ( + "reset at invalid frame, frame discontinuity, and take boundary" + if args.continuous_take_state else + "reset at invalid frame, frame discontinuity, and frozen model clip boundary; never cross take" + ), + "continuous_take_state": args.continuous_take_state, + "long_sequence_limitation": ( + None if args.continuous_take_state else + "the inherited no-cross-clip rule limits a continuous state segment to the cache clip length" + ), + "missing_modality_diagnostic": "simulated local-alignment loss uses exact coarse-z fallback with high uncertainty; the unified coarse model's missing Depth/K static fallback was audited in Stage 3", + "outputs": { + "metrics": "metrics.csv", "take_metrics": "take_metrics.csv", + "overview": "overview.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "response": "response_diagnostics.csv", + "missing_transition": "missing_modality_transition.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "evaluated", "frames": cache["frames"], + "conditions": [condition.name for condition in CONDITIONS], + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase5_metric_alignment.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase5_metric_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f686d340bef0e1a05bb1555d8d89dcd10f1938 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase5_metric_alignment.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +"""Evaluate deployable predicted-location wrist-z alignment on frozen raw caches.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import cv2 +import joblib +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.alignment_calibration import ( + FEATURE_NAMES, + features_from_take, + projected_hand_scale_px, +) +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + + +FINGERTIPS = (4, 8, 12, 16, 20) +CALIBRATED_CONDITIONS = ( + "coarse", + "robust_alignment_unscaled", + "calibrated_always", + "calibrated_confidence", + "missing_depth_fallback", + "missing_k_fallback", +) +RAW_CONDITIONS = ("coarse", "robust_alignment_unscaled") +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + first_fields = list(rows[0]) + extra_fields = sorted({key for row in rows for key in row} - set(first_fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=first_fields + extra_fields, lineterminator="\n", + ) + writer.writeheader() + writer.writerows(rows) + + +def _velocity(translation: np.ndarray, frame_ids: np.ndarray) -> np.ndarray: + output = np.zeros_like(translation, dtype=np.float32) + contiguous = frame_ids[1:] == frame_ids[:-1] + 1 + output[1:][contiguous] = translation[1:][contiguous] - translation[:-1][contiguous] + return output + + +def alignment_arrays( + arrays: dict[str, np.ndarray], data_root: Path, +) -> dict[str, np.ndarray]: + take = str(arrays["take"]) + take_dir = data_root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + time = len(arrays["frame_id"]) + diagnostics: dict[str, list[np.ndarray]] = defaultdict(list) + overlap = [] + predicted_depth_order = [] + for time_index, frame_id in enumerate(arrays["frame_id"]): + depth_mm = cv2.imread( + str(take_dir / "depth" / f"{int(frame_id):06d}.png"), cv2.IMREAD_UNCHANGED, + ) + if depth_mm is None or depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{int(frame_id):06d}") + depth_m, depth_valid = depth_mm_to_m(depth_mm) + masks = [] + predicted_surface_medians = [] + for hand in range(2): + result, samples = align_wrist_z( + arrays["pred_vertices_camera"][time_index, hand], + K_raw, depth_m, depth_valid, + ) + if samples is None: + raise AssertionError("complete-modality evaluation has no depth samples") + for field, value in result.as_dict().items(): + diagnostics[f"alignment_{field}"].append(np.asarray(value)) + masks.append(np.unpackbits( + samples.silhouette_packed, bitorder="little", + count=samples.silhouette_hw[0] * samples.silhouette_hw[1], + ).astype(bool)) + predicted_surface_medians.append(float(np.median( + samples.predicted_depth_m[samples.visible_vertex], + ))) + intersection = np.logical_and(masks[0], masks[1]).sum() + union = np.logical_or(masks[0], masks[1]).sum() + overlap.append(intersection / max(union, 1)) + predicted_depth_order.append(np.sign( + predicted_surface_medians[1] - predicted_surface_medians[0] + )) + values = { + key: np.stack(items).reshape(time, 2) + for key, items in diagnostics.items() + } + pred_joints_raw, _ = project_points(arrays["pred_joints_camera"], K_raw) + resized_hw = arrays["K"].shape # Cache K is already aligned to model image. + del resized_hw + # Recover resized dimensions from principal-point scaling used by the 640x368 cache. + width, height = 640.0, 368.0 + raw_to_resized = np.asarray((width / raw_hw[1], height / raw_hw[0]), dtype=np.float32) + mano_resized = pred_joints_raw * raw_to_resized + values.update({ + "frame_id": arrays["frame_id"], + "pred_wrist_translation": arrays["pred_wrist_translation"], + "coarse_hand_scale_px": projected_hand_scale_px( + pred_joints_raw, source_hw=raw_hw, target_hw=(int(height), int(width)), + ), + "coarse_direct_mano_consistency_px": np.linalg.norm( + arrays["pred_direct_2d_px"] - mano_resized, axis=-1, + ).mean(axis=-1), + "silhouette_overlap_fraction": np.asarray(overlap, dtype=np.float32), + "predicted_depth_order": np.asarray(predicted_depth_order, dtype=np.int8), + "coarse_wrist_velocity_m_per_frame": _velocity( + arrays["pred_wrist_translation"], arrays["frame_id"], + ), + }) + return values + + +def correction_grid( + geometry: dict[str, np.ndarray], package: dict[str, object], +) -> tuple[dict[str, np.ndarray], np.ndarray, np.ndarray]: + features = features_from_take(geometry) + flat = features.reshape(-1, features.shape[-1]) + calibrated = np.clip(package["regressor"].predict(flat), -0.12, 0.12).reshape(features.shape[:2]) + confidence = package["confidence"].predict_proba(flat)[:, 1].reshape(features.shape[:2]) + available = geometry["alignment_applied"].astype(bool) + threshold = float(package["confidence_threshold"]) + raw = np.where(available, geometry["alignment_delta_z_m"], 0.0) + calibrated_available = np.where(available, calibrated, 0.0) + gated = np.where(available & (confidence >= threshold), calibrated, 0.0) + zero = np.zeros_like(raw) + return { + "coarse": zero, + "robust_alignment_unscaled": raw, + "calibrated_always": calibrated_available, + "calibrated_confidence": gated, + "missing_depth_fallback": zero, + "missing_k_fallback": zero, + }, calibrated, confidence + + +def hand_size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def take_rows( + arrays: dict[str, np.ndarray], + geometry: dict[str, np.ndarray], + corrections: dict[str, np.ndarray], + calibrated: np.ndarray, + confidence: np.ndarray, +) -> tuple[list[dict[str, object]], list[dict[str, object]]]: + frame_rows = [] + temporal_rows = [] + take = str(arrays["take"]) + for condition, correction in corrections.items(): + joints = arrays["pred_joints_camera"].astype(np.float64).copy() + vertices = arrays["pred_vertices_camera"].astype(np.float64).copy() + translation = arrays["pred_wrist_translation"].astype(np.float64).copy() + joints[..., 2] += correction[..., None] + vertices[..., 2] += correction[..., None] + translation[..., 2] += correction + projected, _ = project_points(joints, arrays["K"]) + frame_valid = arrays["frame_valid"].astype(bool) + valid = arrays["mano_annotation_valid"].astype(bool) & frame_valid[:, None] + for time_index, hand in zip(*np.where(valid), strict=True): + target_joints = arrays["target_joints_camera"][time_index, hand] + target_vertices = arrays["target_vertices_camera"][time_index, hand] + pred_joints = joints[time_index, hand] + pred_vertices = vertices[time_index, hand] + joint_error = np.linalg.norm(pred_joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(pred_vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (pred_joints - pred_joints[:1]) - (target_joints - target_joints[:1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (pred_vertices - pred_joints[:1]) - (target_vertices - target_joints[:1]), axis=-1, + ) * 1000.0 + z_signed = 1000.0 * ( + translation[time_index, hand, 2] + - arrays["target_wrist_translation"][time_index, hand, 2] + ) + translation_signed = 1000.0 * ( + translation[time_index, hand] + - arrays["target_wrist_translation"][time_index, hand] + ) + target_2d = arrays["target_2d_px"][time_index, hand] + direct_2d = arrays["pred_direct_2d_px"][time_index, hand] + scale = float(geometry["coarse_hand_scale_px"][time_index, hand]) + target_depth = float(arrays["target_wrist_translation"][time_index, hand, 2]) + frame_rows.append({ + "condition": condition, + "take": take, + "subject": take.split("/")[0], + "action_family": take.split("/")[1], + "frame_id": int(arrays["frame_id"][time_index]), + "side": "right" if hand else "left", + "hand_size_bucket": hand_size_bucket(scale), + "depth_bucket": depth_bucket(target_depth), + "absolute_mpjpe_mm": float(joint_error.mean()), + "root_relative_mpjpe_mm": float(root_joint_error.mean()), + "absolute_mpvpe_mm": float(vertex_error.mean()), + "root_relative_mpvpe_mm": float(root_vertex_error.mean()), + "fingertip_mpjpe_mm": float(joint_error[list(FINGERTIPS)].mean()), + "translation_x_mae_mm": abs(float(translation_signed[0])), + "translation_y_mae_mm": abs(float(translation_signed[1])), + "translation_z_mae_mm": abs(float(z_signed)), + "translation_x_signed_error_mm": float(translation_signed[0]), + "translation_y_signed_error_mm": float(translation_signed[1]), + "translation_z_signed_error_mm": float(z_signed), + "direct_2d_error_px": float(np.linalg.norm(direct_2d - target_2d, axis=-1).mean()), + "mano_projected_2d_error_px": float(np.linalg.norm(projected[time_index, hand] - target_2d, axis=-1).mean()), + "direct_mano_2d_consistency_px": float( + np.linalg.norm(direct_2d - projected[time_index, hand], axis=-1).mean() + ), + "raw_alignment_delta_z_mm": 1000.0 * float(geometry["alignment_delta_z_m"][time_index, hand]), + "calibrated_delta_z_mm": 1000.0 * float(calibrated[time_index, hand]), + "applied_delta_z_mm": 1000.0 * float(correction[time_index, hand]), + "alignment_confidence": float(confidence[time_index, hand]), + "alignment_support": int(geometry["alignment_valid_support_count"][time_index, hand]), + "alignment_quality": float(geometry["alignment_conditioning_quality"][time_index, hand]), + }) + + contiguous = arrays["frame_id"][1:] == arrays["frame_id"][:-1] + 1 + for hand in range(2): + transition_valid = contiguous & valid[1:, hand] & valid[:-1, hand] + indices = np.where(transition_valid)[0] + pred_velocity = joints[1:, hand] - joints[:-1, hand] + target_velocity = arrays["target_joints_camera"][1:, hand] - arrays["target_joints_camera"][:-1, hand] + for index in indices: + temporal_rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][index + 1]), + "side": "right" if hand else "left", + "joint_velocity_error_mm_per_frame": float( + np.linalg.norm(pred_velocity[index] - target_velocity[index], axis=-1).mean() * 1000.0 + ), + }) + acceleration_valid = transition_valid[1:] & transition_valid[:-1] + acceleration_indices = np.where(acceleration_valid)[0] + pred_acceleration = pred_velocity[1:] - pred_velocity[:-1] + target_acceleration = target_velocity[1:] - target_velocity[:-1] + for index in acceleration_indices: + temporal_rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][index + 2]), + "side": "right" if hand else "left", + "joint_acceleration_error_mm_per_frame2": float( + np.linalg.norm(pred_acceleration[index] - target_acceleration[index], axis=-1).mean() * 1000.0 + ), + "predicted_joint_acceleration_mm_per_frame2": float( + np.linalg.norm(pred_acceleration[index], axis=-1).mean() * 1000.0 + ), + }) + both_valid = valid.all(axis=1) + wrong_side: list[bool | None] = [] + for time_index in range(len(valid)): + if not both_valid[time_index]: + wrong_side.append(None) + continue + correct = 0.5 * ( + np.linalg.norm( + joints[time_index, 0] - arrays["target_joints_camera"][time_index, 0], + axis=-1, + ).mean() + + np.linalg.norm( + joints[time_index, 1] - arrays["target_joints_camera"][time_index, 1], + axis=-1, + ).mean() + ) + swapped = 0.5 * ( + np.linalg.norm( + joints[time_index, 0] - arrays["target_joints_camera"][time_index, 1], + axis=-1, + ).mean() + + np.linalg.norm( + joints[time_index, 1] - arrays["target_joints_camera"][time_index, 0], + axis=-1, + ).mean() + ) + wrong_side.append(bool(swapped < correct)) + for index, (previous, current) in enumerate( + zip(wrong_side[:-1], wrong_side[1:], strict=True) + ): + if contiguous[index] and previous is not None and current is not None: + temporal_rows.append({ + "condition": condition, + "take": take, + "frame_id": int(arrays["frame_id"][index + 1]), + "side": "bimanual", + "identity_switch_fraction": float(previous != current), + }) + return frame_rows, temporal_rows + + +def aggregate_rows( + frame_rows: list[dict[str, object]], + temporal_rows: list[dict[str, object]], + conditions: tuple[str, ...] = CALIBRATED_CONDITIONS, +) -> list[dict[str, object]]: + output = [] + for condition in conditions: + selected = [row for row in frame_rows if row["condition"] == condition] + for metric in METRICS: + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row[metric] for row in selected), + }) + temporal_selected = [row for row in temporal_rows if row["condition"] == condition] + for metric in ( + "joint_velocity_error_mm_per_frame", + "joint_acceleration_error_mm_per_frame2", + "predicted_joint_acceleration_mm_per_frame2", + "identity_switch_fraction", + ): + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row.get(metric) for row in temporal_selected), + }) + for group in ("side", "hand_size_bucket", "depth_bucket", "take", "action_family"): + values = sorted({str(row[group]) for row in selected}) + for value in values: + grouped = [row for row in selected if str(row[group]) == value] + for metric in METRICS: + output.append({ + "condition": condition, "group": group, "value": value, "metric": metric, + **distribution_summary(row[metric] for row in grouped), + }) + return output + + +def paired_take_bootstrap( + frame_rows: list[dict[str, object]], + *, + conditions: tuple[str, ...] = CALIBRATED_CONDITIONS, + samples: int = 10_000, + seed: int = 20260716, +) -> list[dict[str, object]]: + take_means: dict[tuple[str, str, str], float] = {} + takes = sorted({str(row["take"]) for row in frame_rows}) + for condition in conditions: + for take in takes: + rows = [row for row in frame_rows if row["condition"] == condition and row["take"] == take] + for metric in METRICS: + take_means[(condition, take, metric)] = float(np.mean([float(row[metric]) for row in rows])) + output = [] + rng = np.random.default_rng(seed) + for condition in conditions[1:]: + for metric in METRICS: + delta = np.asarray([ + take_means[(condition, take, metric)] - take_means[("coarse", take, metric)] + for take in takes + ]) + indices = rng.integers(0, len(delta), size=(samples, len(delta))) + boot = delta[indices].mean(axis=1) + output.append({ + "condition": condition, "metric": metric, "takes": len(takes), + "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--calibrator", type=Path) + parser.add_argument("--calibration-json", type=Path) + parser.add_argument("--raw-only", action="store_true") + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("metric-alignment output directory must be new or empty") + cache = json.loads((args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + ): + raise ValueError("official-validation cache contract is invalid") + if args.raw_only: + if args.calibrator is not None or args.calibration_json is not None: + parser.error("--raw-only cannot accept calibrator inputs") + calibration = None + package = None + conditions = RAW_CONDITIONS + else: + if args.calibrator is None or args.calibration_json is None: + parser.error("calibrated evaluation requires --calibrator and --calibration-json") + calibration = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration.get("status") != "fitted" + or calibration.get("official_validation_used") is not False + or calibration.get("official_test_used") is not False + or calibration.get("model", {}).get("sha256") != sha256(args.calibrator) + ): + raise ValueError("OOF calibration contract is invalid") + package = joblib.load(args.calibrator) + if tuple(package["feature_names"]) != FEATURE_NAMES: + raise ValueError("calibrator feature schema mismatch") + conditions = CALIBRATED_CONDITIONS + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + all_frame_rows = [] + all_temporal_rows = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw-cache take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + geometry = alignment_arrays(arrays, args.data_root) + if args.raw_only: + zero = np.zeros_like(geometry["alignment_delta_z_m"]) + available = geometry["alignment_applied"].astype(bool) + corrections = { + "coarse": zero, + "robust_alignment_unscaled": np.where( + available, geometry["alignment_delta_z_m"], 0.0, + ), + } + calibrated, confidence = zero, zero + else: + corrections, calibrated, confidence = correction_grid(geometry, package) + frame_rows, temporal_rows = take_rows( + arrays, geometry, corrections, calibrated, confidence, + ) + all_frame_rows.extend(frame_rows) + all_temporal_rows.extend(temporal_rows) + np.savez_compressed( + prediction_root / f"{'__'.join(Path(str(arrays['take'])).parts)}.npz", + frame_id=arrays["frame_id"], + raw_alignment_delta_z_m=geometry["alignment_delta_z_m"], + calibrated_delta_z_m=calibrated, + confidence=confidence, + gated_delta_z_m=( + zero if args.raw_only else corrections["calibrated_confidence"] + ), + support=geometry["alignment_valid_support_count"], + projected_support=geometry["alignment_projected_support_count"], + quality=geometry["alignment_conditioning_quality"], + alignment_applied=geometry["alignment_applied"], + inlier_ratio=geometry["alignment_inlier_ratio"], + residual_scale_m=geometry["alignment_residual_scale_m"], + valid_fraction=geometry["alignment_valid_fraction"], + foreground_fraction=geometry["alignment_foreground_fraction"], + background_fraction=geometry["alignment_background_fraction"], + depth_discontinuity_m=geometry["alignment_depth_discontinuity_m"], + silhouette_overlap_fraction=geometry["silhouette_overlap_fraction"], + coarse_hand_scale_px=geometry["coarse_hand_scale_px"], + coarse_direct_mano_consistency_px=geometry[ + "coarse_direct_mano_consistency_px" + ], + coarse_wrist_velocity_m_per_frame=geometry[ + "coarse_wrist_velocity_m_per_frame" + ], + predicted_depth_order=geometry["predicted_depth_order"], + ) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + aggregate = aggregate_rows(all_frame_rows, all_temporal_rows, conditions) + paired = paired_take_bootstrap(all_frame_rows, conditions=conditions) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_frame_rows) + write_csv(args.output_dir / "per_temporal_metrics.csv", all_temporal_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + missing_fallback_exact = None if args.raw_only else all( + next(row for row in aggregate if row["condition"] == condition and row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm")["mean"] + == next(row for row in aggregate if row["condition"] == "coarse" and row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm")["mean"] + for condition in ("missing_depth_fallback", "missing_k_fallback") + ) + report = { + "status": "evaluated", + "experiment_class": "ablation" if args.raw_only else "deployable_ablation", + "result_role": ( + "fixed_raw_predicted_location_alignment_without_learned_confidence" + if args.raw_only else "deployable_predicted_location_metric_alignment" + ), + "official_validation_used": True, + "official_validation_used_for_model_or_threshold_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str((args.cache_dir / "cache_manifest.json").resolve()), "sha256": sha256(args.cache_dir / "cache_manifest.json")}, + "coarse_checkpoint": cache["checkpoint"], + "calibration": ( + None if args.raw_only else + {"path": str(args.calibration_json.resolve()), "sha256": sha256(args.calibration_json)} + ), + "calibrator": ( + None if args.raw_only else + {"path": str(args.calibrator.resolve()), "sha256": sha256(args.calibrator)} + ), + "conditions": list(conditions), + "confidence_threshold": None if args.raw_only else float(package["confidence_threshold"]), + "location": "coarse predicted MANO projection; no GT location/bbox/crop", + "correction": "translation z only; pose/shape and coarse outputs retained", + "solver": { + "loss": "MAD-scaled Huber IRLS", + "minimum_support": 20, + "maximum_raw_residual_m": 0.15, + "maximum_delta_m": 0.12, + "surface_location": "frontmost predicted MANO vertices at coarse projection", + }, + "missing_depth_k_fallback_exact": missing_fallback_exact, + "missing_rgb_status": "not_supported_by_frozen_coarse_cache; no claim", + "added_temporal_latency_frames": 0, + "outputs": { + "per_hand": "per_hand_frame_metrics.csv", + "per_temporal": "per_temporal_metrics.csv", + "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "frames": cache["frames"], + "missing_fallback_exact": missing_fallback_exact, "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase5_missing_modality.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase5_missing_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0ac6c2f8b9d554603ecc696a9392e1f97bb9bf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase5_missing_modality.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Evaluate true missing-Depth/K coarse-model caches against complete input.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import project_points +try: + from scripts.evaluate_phase4_jitter import identity_switch_metrics, temporal_metrics +except ModuleNotFoundError: # Direct `python scripts/...` execution. + from evaluate_phase4_jitter import identity_switch_metrics, temporal_metrics # type: ignore[no-redef] + + +CONDITIONS = ("complete", "missing_depth", "missing_k") +FINGERTIPS = (4, 8, 12, 16, 20) +STATIC_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "translation_x_signed_error_mm", "translation_y_signed_error_mm", + "translation_z_signed_error_mm", "direct_2d_error_px", + "mano_projected_2d_error_px", "direct_mano_2d_consistency_px", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def frame_rows(arrays: dict[str, np.ndarray], condition: str) -> list[dict[str, Any]]: + rows = [] + take = str(arrays["take"]) + projected, _ = project_points(arrays["pred_joints_camera"], arrays["K"][:, None]) + valid = arrays["frame_valid"].astype(bool)[:, None] & arrays["mano_annotation_valid"].astype(bool) + for time_index, hand in zip(*np.where(valid), strict=True): + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + vertices = arrays["pred_vertices_camera"][time_index, hand].astype(np.float64) + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_vertices = arrays["target_vertices_camera"][time_index, hand].astype(np.float64) + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (joints - joints[:1]) - (target_joints - target_joints[:1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (vertices - joints[:1]) - (target_vertices - target_joints[:1]), axis=-1, + ) * 1000.0 + translation_signed = 1000.0 * ( + arrays["pred_wrist_translation"][time_index, hand] + - arrays["target_wrist_translation"][time_index, hand] + ) + direct = arrays["pred_direct_2d_px"][time_index, hand] + target_2d = arrays["target_2d_px"][time_index, hand] + target_scale = float(np.max(np.ptp(target_2d, axis=0))) + rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][time_index]), + "side": "right" if hand else "left", + "hand_size_bucket": size_bucket(target_scale), + "wrist_depth_bucket": depth_bucket(float(arrays["target_wrist_translation"][time_index, hand, 2])), + "absolute_mpjpe_mm": float(joint_error.mean()), + "root_relative_mpjpe_mm": float(root_joint_error.mean()), + "absolute_mpvpe_mm": float(vertex_error.mean()), + "root_relative_mpvpe_mm": float(root_vertex_error.mean()), + "fingertip_mpjpe_mm": float(joint_error[list(FINGERTIPS)].mean()), + "translation_x_mae_mm": abs(float(translation_signed[0])), + "translation_y_mae_mm": abs(float(translation_signed[1])), + "translation_z_mae_mm": abs(float(translation_signed[2])), + "translation_x_signed_error_mm": float(translation_signed[0]), + "translation_y_signed_error_mm": float(translation_signed[1]), + "translation_z_signed_error_mm": float(translation_signed[2]), + "direct_2d_error_px": float(np.linalg.norm(direct - target_2d, axis=-1).mean()), + "mano_projected_2d_error_px": float( + np.linalg.norm(projected[time_index, hand] - target_2d, axis=-1).mean() + ), + "direct_mano_2d_consistency_px": float( + np.linalg.norm(direct - projected[time_index, hand], axis=-1).mean() + ), + }) + return rows + + +def matched_cache_arrays( + reference: dict[str, np.ndarray], candidate: dict[str, np.ndarray], +) -> bool: + keys = ( + "frame_id", "frame_valid", "K", "target_rotation_matrices", "target_shape", + "target_wrist_translation", "target_joints_camera", "target_vertices_camera", + "target_2d_px", "joint_annotation_valid", "joint_element_valid", + "mano_annotation_valid", + ) + return all(np.array_equal(reference[key], candidate[key], equal_nan=True) for key in keys) + + +def aggregate_static(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + output = [] + group_fields: dict[str, str | None] = { + "all": None, "side": "side", "hand_size": "hand_size_bucket", + "wrist_depth": "wrist_depth_bucket", + } + for condition in CONDITIONS: + condition_rows = [row for row in rows if row["condition"] == condition] + for group, field in group_fields.items(): + values = ["all"] if field is None else sorted({str(row[field]) for row in condition_rows}) + for value in values: + selected = condition_rows if field is None else [ + row for row in condition_rows if str(row[field]) == value + ] + for metric in STATIC_METRICS: + output.append({ + "condition": condition, "group": group, "value": value, + "metric": metric, + **distribution_summary([float(row[metric]) for row in selected]), + }) + return output + + +def take_metric_rows( + static_rows: list[dict[str, Any]], dynamic: dict[tuple[str, str], dict[str, list[float]]], +) -> list[dict[str, Any]]: + output = [] + takes = sorted({str(row["take"]) for row in static_rows}) + for condition in CONDITIONS: + for take in takes: + selected = [ + row for row in static_rows + if row["condition"] == condition and row["take"] == take + ] + for metric in STATIC_METRICS: + output.append({ + "condition": condition, "take": take, "metric": metric, + **distribution_summary([float(row[metric]) for row in selected]), + }) + for metric, observations in sorted(dynamic[(condition, take)].items()): + output.append({ + "condition": condition, "take": take, "metric": metric, + **distribution_summary(observations), + }) + return output + + +def paired_take_bootstrap( + take_rows: list[dict[str, Any]], samples: int = 10_000, seed: int = 20260716, +) -> list[dict[str, Any]]: + index = { + (row["condition"], row["take"], row["metric"]): float(row["mean"]) + for row in take_rows + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(CONDITIONS[1:]): + for metric_index, metric in enumerate(metrics): + pairs = [ + (index[(condition, take, metric)], index[("complete", take, metric)]) + for take in takes + if (condition, take, metric) in index and ("complete", take, metric) in index + ] + if not pairs: + continue + delta = np.asarray([missing - complete for missing, complete in pairs]) + rng = np.random.default_rng(np.random.SeedSequence((seed, condition_index, metric_index))) + bootstrap = delta[rng.integers(0, len(delta), size=(samples, len(delta)))].mean(axis=1) + output.append({ + "reference": "complete", "condition": condition, "metric": metric, + "takes": len(delta), "condition_minus_reference": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def load_manifest( + path: Path, expected_condition: str, expected_scope: str = "full", +) -> dict[str, Any]: + manifest = json.loads(path.read_text(encoding="utf-8")) + condition = manifest.get("input_condition", "complete") + if ( + manifest.get("status") != "complete" or manifest.get("scope") != expected_scope + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + or condition != expected_condition + ): + raise ValueError(f"invalid {expected_condition} cache manifest") + if expected_scope == "full" and ( + manifest.get("frames") != 11638 or manifest.get("clips") != 1495 + ): + raise ValueError(f"invalid {expected_condition} full-cache coverage") + return manifest + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--complete-cache", type=Path, required=True) + parser.add_argument("--missing-depth-cache", type=Path, required=True) + parser.add_argument("--missing-k-cache", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--scope", choices=("full", "smoke"), default="full") + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("missing-modality evaluation output must be new or empty") + cache_dirs = { + "complete": args.complete_cache, + "missing_depth": args.missing_depth_cache, + "missing_k": args.missing_k_cache, + } + manifests = { + condition: load_manifest(path / "cache_manifest.json", condition, args.scope) + for condition, path in cache_dirs.items() + } + coverage = {(manifest["clips"], manifest["frames"]) for manifest in manifests.values()} + if len(coverage) != 1: + raise ValueError("missing-modality cache coverage differs") + checkpoint_hashes = {manifest["checkpoint"]["sha256"] for manifest in manifests.values()} + manifest_hashes = {manifest["manifest"]["sha256"] for manifest in manifests.values()} + if len(checkpoint_hashes) != 1 or len(manifest_hashes) != 1: + raise ValueError("missing-modality caches do not share checkpoint/split") + takes_by_condition = { + condition: {record["take"]: record for record in manifest["takes"]} + for condition, manifest in manifests.items() + } + if any(set(records) != set(takes_by_condition["complete"]) for records in takes_by_condition.values()): + raise ValueError("missing-modality cache take grids differ") + static_rows: list[dict[str, Any]] = [] + dynamic: dict[tuple[str, str], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for take in sorted(takes_by_condition["complete"]): + arrays_by_condition = {} + for condition in CONDITIONS: + record = takes_by_condition[condition][take] + path = Path(record["path"]) + if sha256(path) != record["sha256"]: + raise ValueError(f"cache take hash mismatch: {path}") + arrays_by_condition[condition] = load_npz(path) + reference = arrays_by_condition["complete"] + for condition, arrays in arrays_by_condition.items(): + if condition != "complete" and not matched_cache_arrays(reference, arrays): + raise ValueError(f"cache frame/GT mismatch: {take}/{condition}") + static_rows.extend(frame_rows(arrays, condition)) + selected = arrays["frame_valid"].astype(bool) + temporal = temporal_metrics( + arrays, arrays["pred_joints_camera"], arrays["pred_direct_2d_px"], selected, + ) + identity = identity_switch_metrics(arrays, arrays["pred_joints_camera"], selected) + for metric, observations in {**temporal, **identity}.items(): + dynamic[(condition, take)][metric].extend( + float(value) for value in observations if np.isfinite(value) + ) + + group_rows = aggregate_static(static_rows) + take_rows = take_metric_rows(static_rows, dynamic) + bootstrap = paired_take_bootstrap(take_rows, samples=args.bootstrap_samples) + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", static_rows) + write_csv(args.output_dir / "group_metrics.csv", group_rows) + write_csv(args.output_dir / "take_metrics.csv", take_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap) + overview_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", "direct_2d_error_px", + "mano_projected_2d_error_px", + ) + overview = { + condition: { + metric: next( + row for row in group_rows + if row["condition"] == condition and row["group"] == "all" and row["metric"] == metric + ) + for metric in overview_metrics + } + for condition in CONDITIONS + } + report = { + "status": "evaluated", + "experiment_class": "preregistered_missing_modality_fallback_diagnostic", + "result_role": "true_coarse_model_input_ablation", + "reference": "complete", + "conditions": list(CONDITIONS), + "scope": args.scope, + "checkpoint_sha256": next(iter(checkpoint_hashes)), + "cache_manifests": { + condition: {"path": str((path / "cache_manifest.json").resolve()), "sha256": sha256(path / "cache_manifest.json")} + for condition, path in cache_dirs.items() + }, + "overview": overview, + "missing_rgb_status": "unsupported_no_rgb_availability_or_training_dropout", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "conditions": report["conditions"], + "frames": manifests["complete"]["frames"], "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_harm_risk.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..42c2af30c8069268484c386d654a282509505b07 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_harm_risk.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""Run the single frozen validation comparison for the OOF harm-risk gate.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import joblib +import numpy as np + +from foundation_hand.evaluation.harm_risk import ( + HARM_RISK_FEATURE_NAMES, + harm_risk_features, +) +from scripts.evaluate_phase6_mixed_projection import ( + METRICS, + aggregate_rows, + sha256, + take_rows, + write_csv, +) + + +ALWAYS = "coarse_wrist_ray__z_calibrated_always" +RISK = "coarse_wrist_ray__z_harm_risk" +SPECS = [ + {"id": "direct_xyz_coarse__z_coarse", "assembly": "direct_xyz_coarse", "z_mode": "coarse"}, + {"id": "direct_xyz_z_only__z_calibrated_always", "assembly": "direct_xyz_z_only", "z_mode": "calibrated_always"}, + {"id": ALWAYS, "assembly": "coarse_wrist_ray", "z_mode": "calibrated_always"}, + {"id": RISK, "assembly": "coarse_wrist_ray", "z_mode": "calibrated_confidence_0p6"}, +] + + +def paired_take_bootstrap( + rows: list[dict[str, object]], *, samples: int = 10_000, seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + output = [] + rng = np.random.default_rng(seed) + for metric in METRICS: + delta = [] + for take in takes: + candidate = [ + float(row[metric]) for row in rows + if row["condition"] == RISK and row["take"] == take + ] + reference = [ + float(row[metric]) for row in rows + if row["condition"] == ALWAYS and row["take"] == take + ] + delta.append(float(np.mean(candidate) - np.mean(reference))) + values = np.asarray(delta) + indices = rng.integers(0, len(values), size=(samples, len(values))) + boot = values[indices].mean(axis=1) + output.append({ + "condition": RISK, "reference": ALWAYS, "metric": metric, + "takes": len(takes), "delta_mean": float(values.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-dir", type=Path, required=True) + parser.add_argument("--risk-selection", type=Path, required=True) + parser.add_argument("--risk-package", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + cache_path = args.cache_dir / "cache_manifest.json" + alignment_path = args.alignment_dir / "evaluation.json" + cache = json.loads(cache_path.read_text(encoding="utf-8")) + alignment_report = json.loads(alignment_path.read_text(encoding="utf-8")) + risk_report = json.loads(args.risk_selection.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("scope") != "full" + or cache.get("official_test_used") is not False + or alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_path) + or risk_report.get("status") != "admitted_for_one_frozen_validation" + or risk_report.get("official_validation_used") is not False + or risk_report.get("official_test_used") is not False + or risk_report.get("package", {}).get("sha256") != sha256(args.risk_package) + ): + raise ValueError("cache/alignment/OOF-risk isolation contract failed") + package = joblib.load(args.risk_package) + if tuple(package["feature_names"]) != HARM_RISK_FEATURE_NAMES: + raise ValueError("risk package feature schema mismatch") + thresholds = package["selected_thresholds"] + if thresholds is None or thresholds != { + "expected_gain_threshold_mm": risk_report["selected"]["expected_gain_threshold_mm"], + "harm_probability_threshold": risk_report["selected"]["harm_probability_threshold"], + }: + raise ValueError("risk thresholds differ from frozen OOF selection") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + all_rows = [] + coverage_rows = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + raw_path = Path(take_record["path"]) + if sha256(raw_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {raw_path}") + with np.load(raw_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + diagnostic_path = args.alignment_dir / "predictions" / raw_path.name + with np.load(diagnostic_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + if not np.array_equal(arrays["frame_id"], alignment["frame_id"]): + raise ValueError(f"alignment frame mismatch: {raw_path}") + available = alignment["alignment_applied"].astype(bool) + calibrated = np.where(available, alignment["calibrated_delta_z_m"], 0.0) + raw = np.where(available, alignment["raw_alignment_delta_z_m"], 0.0) + features = harm_risk_features( + calibrated_delta_z_m=calibrated, + raw_delta_z_m=raw, + confidence=alignment["confidence"], + alignment_available=available, + raw_alignment_available=available, + valid_support_count=alignment["support"], + projected_support_count=alignment["projected_support"], + inlier_ratio=alignment["inlier_ratio"], + residual_scale_m=alignment["residual_scale_m"], + valid_fraction=alignment["valid_fraction"], + foreground_fraction=alignment["foreground_fraction"], + background_fraction=alignment["background_fraction"], + depth_discontinuity_m=alignment["depth_discontinuity_m"], + conditioning_quality=alignment["quality"], + silhouette_overlap_fraction=alignment["silhouette_overlap_fraction"], + coarse_hand_scale_px=alignment["coarse_hand_scale_px"], + coarse_direct_mano_consistency_px=alignment[ + "coarse_direct_mano_consistency_px" + ], + coarse_wrist_translation=arrays["pred_wrist_translation"], + coarse_wrist_velocity_m_per_frame=alignment[ + "coarse_wrist_velocity_m_per_frame" + ], + predicted_depth_order=alignment["predicted_depth_order"], + ) + flat = features.reshape(-1, features.shape[-1]) + expected_gain = package["regressor"].predict(flat).reshape(features.shape[:2]) + harm_probability = package["classifier"].predict_proba(flat)[:, 1].reshape( + features.shape[:2] + ) + gate = ( + available + & (expected_gain >= thresholds["expected_gain_threshold_mm"]) + & (harm_probability <= thresholds["harm_probability_threshold"]) + ) + risk_alignment = dict(alignment) + risk_alignment["gated_delta_z_m"] = np.where(gate, calibrated, 0.0) + rows, saved = take_rows(arrays, risk_alignment, SPECS) + all_rows.extend(rows) + coverage_rows.append({ + "take": str(arrays["take"]), "samples": int(gate.size), + "available": int(available.sum()), "applied": int(gate.sum()), + "coverage": float(gate.mean()), + "mean_expected_gain_mm": float(expected_gain.mean()), + "mean_harm_probability": float(harm_probability.mean()), + }) + output = prediction_root / raw_path.name + np.savez_compressed( + output, **saved, expected_gain_mm=expected_gain.astype(np.float32), + harm_probability=harm_probability.astype(np.float32), risk_gate=gate, + risk_delta_z_m=np.where(gate, calibrated, 0.0), + ) + take_records.append({ + "take": str(arrays["take"]), "frames": len(arrays["frame_id"]), + "path": str(output), "sha256": sha256(output), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + aggregate = aggregate_rows(all_rows, SPECS) + paired = paired_take_bootstrap(all_rows) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "coverage_by_take.csv", coverage_rows) + primary = { + row["condition"]: row for row in aggregate + if row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm" + } + report = { + "status": "evaluated_single_frozen_oof_risk_policy", + "experiment": "P6_S3_harm_aware_risk_gate", + "experiment_class": "exploratory_deployable_frozen_oof_policy", + "official_validation_used": True, + "official_validation_used_for_threshold_selection": False, + "official_test_used": False, + "oracle_information": False, + "conditions": SPECS, + "risk_thresholds": thresholds, + "coverage": float(sum(row["applied"] for row in coverage_rows) / sum( + row["samples"] for row in coverage_rows + )), + "always_absolute_mpjpe_mm": float(primary[ALWAYS]["mean"]), + "risk_absolute_mpjpe_mm": float(primary[RISK]["mean"]), + "absolute_delta_mm": float(primary[RISK]["mean"] - primary[ALWAYS]["mean"]), + "new_rank_one": float(primary[RISK]["mean"]) < 19.174950061401493, + "cache_manifest": {"path": str(cache_path.resolve()), "sha256": sha256(cache_path)}, + "alignment_evaluation": { + "path": str(alignment_path.resolve()), "sha256": sha256(alignment_path), + }, + "risk_selection": { + "path": str(args.risk_selection.resolve()), "sha256": sha256(args.risk_selection), + }, + "risk_package": {"path": str(args.risk_package.resolve()), "sha256": sha256(args.risk_package)}, + "checkpoint": cache["checkpoint"], "calibrator": alignment_report["calibrator"], + "takes": take_records, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..cf5426ac585026170b1b28ff18476ce0d6656dcb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_mixed_projection.py @@ -0,0 +1,471 @@ +#!/usr/bin/env python3 +"""Evaluate frozen Phase 6 mixed-projection assemblies on validation caches.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.mixed_projection import ( + coarse_wrist_ray_translation, + direct_wrist_ray_translation, + solve_mixed_projection_batch, +) + + +FINGERTIPS = (4, 8, 12, 16, 20) +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + "direct_2d_error_px", + "projected_mano_2d_px", + "direct_mano_consistency_px", +) +REFERENCE = "direct_xyz_z_only__z_calibrated_always" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def condition_specs(selection: dict[str, Any]) -> list[dict[str, object]]: + winner = selection["winner"] + support = int(winner["minimum_support"]) + delta = float(winner["huber_delta_px"]) + output: list[dict[str, object]] = [ + {"id": "direct_xyz_coarse__z_coarse", "assembly": "direct_xyz_coarse", "z_mode": "coarse"}, + {"id": REFERENCE, "assembly": "direct_xyz_z_only", "z_mode": "calibrated_always"}, + {"id": "direct_xyz_z_only__z_raw_alignment", "assembly": "direct_xyz_z_only", "z_mode": "raw_alignment"}, + {"id": "direct_xyz_z_only__z_calibrated_confidence_0p6", "assembly": "direct_xyz_z_only", "z_mode": "calibrated_confidence_0p6"}, + ] + for z_mode in ( + "coarse", "raw_alignment", "calibrated_always", "calibrated_confidence_0p6", + ): + output.extend(( + {"id": f"coarse_wrist_ray__z_{z_mode}", "assembly": "coarse_wrist_ray", "z_mode": z_mode}, + {"id": f"direct_2d_wrist_ray__z_{z_mode}", "assembly": "direct_2d_wrist_ray", "z_mode": z_mode}, + { + "id": f"mixed_wls_s{support}__z_{z_mode}", + "assembly": "mixed_projection_21j_wls", "z_mode": z_mode, + "minimum_support": support, "huber_delta_px": None, + }, + { + "id": f"mixed_huber_d{delta:g}_s{support}__z_{z_mode}", + "assembly": "robust_mixed_projection", "z_mode": z_mode, + "minimum_support": support, "huber_delta_px": delta, + }, + )) + return output + + +def correction_grid(alignment: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + available = alignment["alignment_applied"].astype(bool) + raw = np.where(available, alignment["raw_alignment_delta_z_m"], 0.0) + calibrated = np.where(available, alignment["calibrated_delta_z_m"], 0.0) + confidence = np.where(available, alignment["gated_delta_z_m"], 0.0) + return { + "coarse": np.zeros_like(raw), + "raw_alignment": raw, + "calibrated_always": calibrated, + "calibrated_confidence_0p6": confidence, + } + + +def project(points: np.ndarray, K: np.ndarray) -> np.ndarray: + z = np.maximum(points[..., 2], 1e-8) + return np.stack(( + K[:, None, 0, 0] * points[..., 0] / z + K[:, None, 0, 2], + K[:, None, 1, 1] * points[..., 1] / z + K[:, None, 1, 2], + ), axis=-1) + + +def assemble( + spec: dict[str, object], + *, + coarse: np.ndarray, + root_relative_joints: np.ndarray, + anchors: np.ndarray, + K: np.ndarray, + z: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + direct = coarse.copy() + direct[:, 2] = z + ray = coarse_wrist_ray_translation(coarse, z) + assembly = spec["assembly"] + diagnostics: dict[str, np.ndarray] = {} + if assembly in {"direct_xyz_coarse", "direct_xyz_z_only"}: + return direct, diagnostics + if assembly == "coarse_wrist_ray": + return ray, diagnostics + if assembly == "direct_2d_wrist_ray": + translation, valid = direct_wrist_ray_translation(anchors, K, z, ray) + diagnostics.update({"success": valid, "failure_reason": np.where(valid, "ok", "invalid_k_or_anchor")}) + return translation, diagnostics + result = solve_mixed_projection_batch( + root_relative_joints, anchors, K, z, ray, + image_hw=(368, 640), minimum_support=int(spec["minimum_support"]), + robust_huber_delta_px=( + None if spec["huber_delta_px"] is None else float(spec["huber_delta_px"]) + ), + ) + diagnostics.update({ + "support_count": result.support_count, + "residual_scale_px": result.residual_scale_px, + "conditioning": result.conditioning, + "inlier_ratio": result.inlier_ratio, + "uncertainty_x_m": result.uncertainty_xy_m[:, 0], + "uncertainty_y_m": result.uncertainty_xy_m[:, 1], + "success": result.failure_reason == "ok", + "failure_reason": result.failure_reason, + }) + return result.translation_m, diagnostics + + +def hand_size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def take_rows( + arrays: dict[str, np.ndarray], + alignment: dict[str, np.ndarray], + specs: list[dict[str, object]], +) -> tuple[list[dict[str, object]], dict[str, np.ndarray]]: + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + time_index, hand = np.where(valid) + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + coarse_joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + coarse_vertices = arrays["pred_vertices_camera"][time_index, hand].astype(np.float64) + root_relative = coarse_joints - coarse_joints[:, :1] + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + K = arrays["K"][time_index].astype(np.float64) + corrections = correction_grid(alignment) + coarse_projected = project(coarse_joints, K) + scale = np.ptp(coarse_projected, axis=1).max(axis=-1) + frame_rows = [] + saved: dict[str, list[np.ndarray]] = defaultdict(list) + for spec in specs: + condition = str(spec["id"]) + z_mode = str(spec["z_mode"]) + z = coarse[:, 2] + corrections[z_mode][time_index, hand] + translation, diagnostics = assemble( + spec, coarse=coarse, root_relative_joints=root_relative, + anchors=anchors, K=K, z=z, + ) + shift = translation - coarse + joints = coarse_joints + shift[:, None] + vertices = coarse_vertices + shift[:, None] + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_vertices = arrays["target_vertices_camera"][time_index, hand].astype(np.float64) + target_translation = arrays["target_wrist_translation"][time_index, hand].astype(np.float64) + target_2d = arrays["target_2d_px"][time_index, hand].astype(np.float64) + projected = project(joints, K) + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (joints - joints[:, :1]) - (target_joints - target_joints[:, :1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (vertices - joints[:, :1]) - (target_vertices - target_joints[:, :1]), axis=-1, + ) * 1000.0 + signed_translation = (translation - target_translation) * 1000.0 + success = diagnostics.get("success", np.ones(len(translation), dtype=bool)) + failure = diagnostics.get("failure_reason", np.full(len(translation), "ok")) + support = diagnostics.get("support_count", np.full(len(translation), 21)) + residual_scale = diagnostics.get("residual_scale_px", np.zeros(len(translation))) + conditioning = diagnostics.get("conditioning", np.ones(len(translation))) + inlier_ratio = diagnostics.get("inlier_ratio", np.ones(len(translation))) + uncertainty_x = diagnostics.get("uncertainty_x_m", np.zeros(len(translation))) + uncertainty_y = diagnostics.get("uncertainty_y_m", np.zeros(len(translation))) + for index in range(len(translation)): + current_time, current_hand = int(time_index[index]), int(hand[index]) + direct_error = np.linalg.norm(anchors[index] - target_2d[index], axis=-1).mean() + projected_error = np.linalg.norm(projected[index] - target_2d[index], axis=-1).mean() + consistency = np.linalg.norm(projected[index] - anchors[index], axis=-1).mean() + frame_rows.append({ + "condition": condition, + "assembly": spec["assembly"], + "z_mode": z_mode, + "take": take, + "subject": take.split("/")[0], + "action_family": take.split("/")[1], + "frame_id": int(arrays["frame_id"][current_time]), + "side": "right" if current_hand else "left", + "hand_size_bucket": hand_size_bucket(float(scale[index])), + "depth_bucket": depth_bucket(float(target_translation[index, 2])), + "absolute_mpjpe_mm": float(joint_error[index].mean()), + "root_relative_mpjpe_mm": float(root_joint_error[index].mean()), + "absolute_mpvpe_mm": float(vertex_error[index].mean()), + "root_relative_mpvpe_mm": float(root_vertex_error[index].mean()), + "fingertip_mpjpe_mm": float(joint_error[index, FINGERTIPS].mean()), + "translation_x_mae_mm": abs(float(signed_translation[index, 0])), + "translation_y_mae_mm": abs(float(signed_translation[index, 1])), + "translation_z_mae_mm": abs(float(signed_translation[index, 2])), + "translation_x_signed_error_mm": float(signed_translation[index, 0]), + "translation_y_signed_error_mm": float(signed_translation[index, 1]), + "translation_z_signed_error_mm": float(signed_translation[index, 2]), + "direct_2d_error_px": float(direct_error), + "projected_mano_2d_px": float(projected_error), + "direct_mano_consistency_px": float(consistency), + "applied_delta_z_mm": float(1000.0 * corrections[z_mode][current_time, current_hand]), + "support_count": int(support[index]), + "residual_scale_px": float(residual_scale[index]), + "conditioning": float(conditioning[index]), + "inlier_ratio": float(inlier_ratio[index]), + "uncertainty_x_mm": float(1000.0 * uncertainty_x[index]), + "uncertainty_y_mm": float(1000.0 * uncertainty_y[index]), + "solve_success": bool(success[index]), + "failure_reason": str(failure[index]), + }) + saved[f"translation__{condition}"].append(translation.astype(np.float32)) + saved[f"success__{condition}"].append(success.astype(bool)) + saved_arrays: dict[str, np.ndarray] = { + "frame_id": arrays["frame_id"], + "valid_time_index": time_index.astype(np.int64), + "valid_hand_index": hand.astype(np.int64), + } + saved_arrays.update({key: value[0] for key, value in saved.items()}) + return frame_rows, saved_arrays + + +def aggregate_rows( + rows: list[dict[str, object]], specs: list[dict[str, object]], +) -> list[dict[str, object]]: + output = [] + for spec in specs: + condition = str(spec["id"]) + selected = [row for row in rows if row["condition"] == condition] + for metric in METRICS: + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row[metric] for row in selected), + }) + for group in ("side", "hand_size_bucket", "depth_bucket", "take", "action_family"): + for value in sorted({str(row[group]) for row in selected}): + grouped = [row for row in selected if str(row[group]) == value] + for metric in METRICS: + output.append({ + "condition": condition, "group": group, "value": value, + "metric": metric, + **distribution_summary(row[metric] for row in grouped), + }) + output.append({ + "condition": condition, "group": "all", "value": "all", + "metric": "solve_success_fraction", + **distribution_summary(float(row["solve_success"]) for row in selected), + }) + return output + + +def paired_take_bootstrap( + rows: list[dict[str, object]], specs: list[dict[str, object]], + *, samples: int = 10_000, seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + take_mean: dict[tuple[str, str, str], float] = {} + for spec in specs: + condition = str(spec["id"]) + for take in takes: + selected = [row for row in rows if row["condition"] == condition and row["take"] == take] + for metric in METRICS: + take_mean[(condition, take, metric)] = float(np.mean([row[metric] for row in selected])) + output = [] + rng = np.random.default_rng(seed) + for spec in specs: + condition = str(spec["id"]) + if condition == REFERENCE: + continue + for metric in METRICS: + delta = np.asarray([ + take_mean[(condition, take, metric)] - take_mean[(REFERENCE, take, metric)] + for take in takes + ]) + indices = rng.integers(0, len(delta), size=(samples, len(delta))) + boot = delta[indices].mean(axis=1) + output.append({ + "condition": condition, "reference": REFERENCE, "metric": metric, + "takes": len(takes), "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-dir", type=Path, required=True) + parser.add_argument("--oof-selection", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + cache_manifest_path = args.cache_dir / "cache_manifest.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + alignment_report_path = args.alignment_dir / "evaluation.json" + alignment_report = json.loads(alignment_report_path.read_text(encoding="utf-8")) + selection = json.loads(args.oof_selection.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("scope") != "full" + or cache.get("official_test_used") is not False + or alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + or selection.get("status") != "selected_oof_only" + or selection.get("official_validation_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("cache/alignment/OOF isolation contract failed") + specs = condition_specs(selection) + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_dir = args.output_dir / "predictions" + prediction_dir.mkdir() + all_rows = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + alignment_path = args.alignment_dir / "predictions" / take_path.name + with np.load(alignment_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + if not np.array_equal(arrays["frame_id"], alignment["frame_id"]): + raise ValueError(f"alignment frame mismatch: {take_path}") + rows, saved = take_rows(arrays, alignment, specs) + all_rows.extend(rows) + output_path = prediction_dir / take_path.name + np.savez_compressed(output_path, **saved) + take_records.append({ + "take": str(arrays["take"]), "frames": len(arrays["frame_id"]), + "path": str(output_path), "sha256": sha256(output_path), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + aggregate = aggregate_rows(all_rows, specs) + paired = paired_take_bootstrap(all_rows, specs) + reference_rows = { + (row["take"], row["frame_id"], row["side"]): row + for row in all_rows if row["condition"] == REFERENCE + } + case_rows = [] + for spec in specs: + condition = str(spec["id"]) + if condition == REFERENCE: + continue + selected = [row for row in all_rows if row["condition"] == condition] + deltas = np.asarray([ + float(row["absolute_mpjpe_mm"]) + - float(reference_rows[(row["take"], row["frame_id"], row["side"])]["absolute_mpjpe_mm"]) + for row in selected + ]) + for role, indices in ( + ("largest_gain", np.argsort(deltas)[:10]), + ("largest_harm", np.argsort(deltas)[-10:][::-1]), + ): + for rank, index in enumerate(indices, start=1): + row = selected[int(index)] + case_rows.append({ + "condition": condition, "role": role, "rank": rank, + "take": row["take"], "frame_id": row["frame_id"], "side": row["side"], + "absolute_delta_mm": float(deltas[index]), + "candidate_absolute_mpjpe_mm": row["absolute_mpjpe_mm"], + "reference_absolute_mpjpe_mm": reference_rows[ + (row["take"], row["frame_id"], row["side"]) + ]["absolute_mpjpe_mm"], + "support_count": row["support_count"], + "residual_scale_px": row["residual_scale_px"], + "conditioning": row["conditioning"], + "inlier_ratio": row["inlier_ratio"], + "failure_reason": row["failure_reason"], + }) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "largest_gain_harm.csv", case_rows) + primary_rows = [ + row for row in aggregate + if row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm" + ] + best = min(primary_rows, key=lambda row: float(row["mean"])) + reference = next(row for row in primary_rows if row["condition"] == REFERENCE) + guardrail = min(0.2, 0.01 * float(reference["mean"])) + report = { + "status": "evaluated_frozen_oof_selection", + "experiment": "P6_S1_cache_mixed_projection", + "experiment_class": "preregistered_cache_only_deployable_ablation", + "official_validation_used": True, + "official_validation_used_for_solver_constant_selection": False, + "official_test_used": False, + "oracle_information": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "alignment_evaluation": {"path": str(alignment_report_path.resolve()), "sha256": sha256(alignment_report_path)}, + "oof_selection": {"path": str(args.oof_selection.resolve()), "sha256": sha256(args.oof_selection)}, + "checkpoint": cache["checkpoint"], + "calibrator": alignment_report["calibrator"], + "conditions": specs, + "reference_condition": REFERENCE, + "reference_absolute_mpjpe_mm": float(reference["mean"]), + "best_condition": best["condition"], + "best_absolute_mpjpe_mm": float(best["mean"]), + "best_delta_mm": float(best["mean"] - reference["mean"]), + "new_rank_one": float(best["mean"]) < 19.45484110440441, + "geometry_secondary_guardrail_passed": float(best["mean"]) <= float(reference["mean"]) + guardrail, + "takes": take_records, + "outputs": { + "per_hand": "per_hand_frame_metrics.csv", "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "largest_gain_harm": "largest_gain_harm.csv", "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "reference": report["reference_absolute_mpjpe_mm"], + "best_condition": report["best_condition"], "best": report["best_absolute_mpjpe_mm"], + "new_rank_one": report["new_rank_one"], "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_pa_mpjpe.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_pa_mpjpe.py new file mode 100644 index 0000000000000000000000000000000000000000..59e3ad31371664ffe62f535f94ff288f2eaece36 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_pa_mpjpe.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Evaluate seed17 rigid and standard Procrustes-aligned MPJPE.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def summary(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": len(array), "mean": float(array.mean()), + "p50": float(np.percentile(array, 50)), + "p95": float(np.percentile(array, 95)), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + ): + raise ValueError("raw cache isolation contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + values: dict[str, list[float]] = defaultdict(list) + rows = [] + for take_record in manifest["takes"]: + path = Path(take_record["path"]) + if sha256(path) != take_record["sha256"]: + raise ValueError(f"cache take hash mismatch: {path}") + with np.load(path, allow_pickle=False) as archive: + predicted = archive["pred_joints_camera"] + target = archive["target_joints_camera"] + valid = archive["joint_annotation_valid"].astype(bool) & archive[ + "frame_valid" + ][:, None].astype(bool) + frame_ids = archive["frame_id"] + take = str(archive["take"]) + for hand, side in enumerate(("left", "right")): + indices = np.where(valid[:, hand])[0] + rigid = aligned_mpjpe_mm( + predicted[indices, hand], target[indices, hand], estimate_scale=False, + ) + similarity = aligned_mpjpe_mm( + predicted[indices, hand], target[indices, hand], estimate_scale=True, + ) + values["rigid_aligned_mpjpe_mm"].extend(rigid.tolist()) + values["pa_mpjpe_mm"].extend(similarity.tolist()) + values[f"{side}_rigid_aligned_mpjpe_mm"].extend(rigid.tolist()) + values[f"{side}_pa_mpjpe_mm"].extend(similarity.tolist()) + rows.extend({ + "take": take, "frame_id": int(frame_ids[index]), "side": side, + "rigid_aligned_mpjpe_mm": float(rigid[position]), + "pa_mpjpe_mm": float(similarity[position]), + } for position, index in enumerate(indices)) + with (args.output_dir / "per_hand_frame_metrics.csv").open( + "x", newline="", encoding="utf-8", + ) as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "evaluated", + "experiment": "P6_pose_alignment_metric_addendum", + "official_test_used": False, + "metric_definitions": { + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation, and scale", + "rigid_aligned_mpjpe_mm": "per-hand SE(3) Kabsch; removes translation and rotation only", + }, + "translation_only_system_invariance": True, + "metrics": {key: summary(items) for key, items in values.items()}, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_state_ray.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_state_ray.py new file mode 100644 index 0000000000000000000000000000000000000000..a44aac603af5f949a790d4f714314f029344abdf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase6_state_ray.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Compose frozen causal-state z estimates with the coarse wrist camera ray.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.mixed_projection import coarse_wrist_ray_translation +from scripts.evaluate_phase4_jitter import ( + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, +) +from scripts.evaluate_phase5_causal_state import response_diagnostics +from scripts.evaluate_phase6_mixed_projection import METRICS, aggregate_rows, take_rows + + +STATE_CONDITIONS = ( + "coarse", + "calibrated_per_frame", + "ema_alpha0.6", + "butterworth_2hz", + "fixed_kalman", + "uncertainty_kalman", +) +REFERENCE = "calibrated_per_frame__coarse_wrist_ray" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def assemble_state_ray_geometry( + coarse_translation_m: np.ndarray, + coarse_joints_m: np.ndarray, + coarse_vertices_m: np.ndarray, + state_z_m: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Preserve each coarse wrist ray and rigidly translate its hand geometry.""" + + coarse_translation = np.asarray(coarse_translation_m, dtype=np.float64) + state_z = np.asarray(state_z_m, dtype=np.float64) + safe_z = np.where( + np.isfinite(state_z) & (state_z > 0.05), + state_z, + coarse_translation[..., 2], + ) + translation = coarse_wrist_ray_translation(coarse_translation, safe_z) + shift = translation - coarse_translation + joints = np.asarray(coarse_joints_m, dtype=np.float64) + shift[..., None, :] + vertices = np.asarray(coarse_vertices_m, dtype=np.float64) + shift[..., None, :] + return translation, joints, vertices + + +def paired_bootstrap( + rows: list[dict[str, object]], + conditions: list[str], + *, + samples: int, + seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + means: dict[tuple[str, str, str], float] = {} + for condition in conditions: + for take in takes: + selected = [ + row for row in rows + if row["condition"] == condition and row["take"] == take + ] + for metric in METRICS: + means[(condition, take, metric)] = float( + np.mean([float(row[metric]) for row in selected]) + ) + output = [] + for condition_index, condition in enumerate(conditions): + if condition == REFERENCE: + continue + for metric_index, metric in enumerate(METRICS): + delta = np.asarray([ + means[(condition, take, metric)] - means[(REFERENCE, take, metric)] + for take in takes + ]) + rng = np.random.default_rng( + np.random.SeedSequence((seed, condition_index, metric_index)) + ) + bootstrap = delta[ + rng.integers(0, len(delta), size=(samples, len(delta))) + ].mean(axis=1) + output.append({ + "condition": condition, + "reference": REFERENCE, + "metric": metric, + "takes": len(takes), + "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--state-evaluation-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + + cache_manifest_path = args.cache_dir / "cache_manifest.json" + state_report_path = args.state_evaluation_dir / "evaluation.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + state_report = json.loads(state_report_path.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("sequence_mode") != "causal" + or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + or state_report.get("status") != "evaluated" + or state_report.get("official_test_used") is not False + or state_report.get("official_validation_used_for_parameter_selection") is not False + or state_report.get("continuous_take_state") is not True + or state_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + ): + raise ValueError("causal cache/state isolation contract failed") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_dir = args.output_dir / "predictions" + prediction_dir.mkdir() + specs = [ + { + "id": f"{condition}__coarse_wrist_ray", + "assembly": "coarse_wrist_ray", + "z_mode": "calibrated_always", + } + for condition in STATE_CONDITIONS + ] + all_rows: list[dict[str, object]] = [] + temporal_values = { + str(spec["id"]): defaultdict(list) for spec in specs + } + temporal_take_rows: list[dict[str, object]] = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {take_path}") + arrays = load_npz(take_path) + arrays["clip_index"] = np.zeros_like(arrays["clip_index"]) + state_path = args.state_evaluation_dir / "predictions" / take_path.name + state = load_npz(state_path) + if not np.array_equal(arrays["frame_id"], state["frame_id"]): + raise ValueError(f"state frame mismatch: {take_path}") + arrays["_calibrated_measurement_z_m"] = state["calibrated_per_frame_z_m"] + saved: dict[str, np.ndarray] = {"frame_id": arrays["frame_id"]} + for spec, state_condition in zip(specs, STATE_CONDITIONS, strict=True): + condition = str(spec["id"]) + z_m = state[f"{state_condition}_z_m"].astype(np.float64) + correction = z_m - arrays["pred_wrist_translation"][..., 2] + alignment = { + "alignment_applied": np.isfinite(correction), + "raw_alignment_delta_z_m": correction, + "calibrated_delta_z_m": correction, + "gated_delta_z_m": correction, + } + rows, _ = take_rows(arrays, alignment, [spec]) + all_rows.extend(rows) + translation, joints, vertices = assemble_state_ray_geometry( + arrays["pred_wrist_translation"], + arrays["pred_joints_camera"], + arrays["pred_vertices_camera"], + z_m, + ) + selected = arrays["frame_valid"].astype(bool) + _, projected, _ = per_frame_metrics( + arrays, + joints, + vertices, + arrays["pred_rotation_matrices"], + translation, + selected, + ) + values = temporal_metrics(arrays, joints, projected, selected) + identity = identity_switch_metrics(arrays, joints, selected) + values.update(identity) + values.update(response_diagnostics(arrays, z_m)) + for metric, observations in values.items(): + finite = [float(value) for value in observations if np.isfinite(value)] + temporal_values[condition][metric].extend(finite) + temporal_take_rows.append({ + "take": str(arrays["take"]), + "condition": condition, + "metric": metric, + **distribution_summary(finite), + }) + saved[f"translation__{condition}"] = translation.astype(np.float32) + saved[f"z_variance_m2__{condition}"] = state[ + f"{state_condition}_variance_m2" + ].astype(np.float32) + output_path = prediction_dir / take_path.name + np.savez_compressed(output_path, **saved) + take_records.append({ + "take": str(arrays["take"]), + "frames": len(arrays["frame_id"]), + "path": str(output_path), + "sha256": sha256(output_path), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + aggregate = aggregate_rows(all_rows, specs) + conditions = [str(spec["id"]) for spec in specs] + paired = paired_bootstrap( + all_rows, conditions, samples=args.bootstrap_samples, + ) + temporal_rows = [ + {"condition": condition, "metric": metric, **distribution_summary(values)} + for condition in conditions + for metric, values in sorted(temporal_values[condition].items()) + ] + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "temporal_metrics.csv", temporal_rows) + write_csv(args.output_dir / "temporal_take_metrics.csv", temporal_take_rows) + + static_index = { + (str(row["condition"]), str(row["metric"])): row + for row in aggregate if row["group"] == "all" and row["value"] == "all" + } + temporal_index = { + (str(row["condition"]), str(row["metric"])): row for row in temporal_rows + } + overview = [] + for condition in conditions: + row: dict[str, object] = { + "condition": condition, + "absolute_mpjpe_mm": static_index[(condition, "absolute_mpjpe_mm")]["mean"], + "absolute_mpvpe_mm": static_index[(condition, "absolute_mpvpe_mm")]["mean"], + "fingertip_mpjpe_mm": static_index[(condition, "fingertip_mpjpe_mm")]["mean"], + "translation_x_mae_mm": static_index[(condition, "translation_x_mae_mm")]["mean"], + "translation_y_mae_mm": static_index[(condition, "translation_y_mae_mm")]["mean"], + "translation_z_mae_mm": static_index[(condition, "translation_z_mae_mm")]["mean"], + "translation_z_p95_mm": static_index[(condition, "translation_z_mae_mm")]["p95"], + "projected_mano_2d_px": static_index[(condition, "projected_mano_2d_px")]["mean"], + } + for metric in ( + "joint_velocity_error_mm_per_s", + "joint_acceleration_error_mm_per_s2", + "predicted_3d_joint_acceleration_mm_per_s2", + "predicted_3d_joint_jerk_mm_per_s3", + "high_frequency_energy_ratio", + "estimated_causal_lag_frames", + ): + if (condition, metric) in temporal_index: + row[metric] = temporal_index[(condition, metric)]["mean"] + overview.append(row) + reference = next(row for row in overview if row["condition"] == REFERENCE) + for row in overview: + row["absolute_delta_mm"] = float(row["absolute_mpjpe_mm"]) - float( + reference["absolute_mpjpe_mm"] + ) + row["static_guardrail_passed"] = bool( + float(row["absolute_delta_mm"]) <= 0.2 + and float(row["translation_z_mae_mm"]) + <= float(reference["translation_z_mae_mm"]) + 0.2 + and float(row["translation_z_p95_mm"]) + <= float(reference["translation_z_p95_mm"]) + 0.2 + ) + write_csv(args.output_dir / "overview.csv", overview) + report = { + "status": "evaluated_frozen_causal_state_coarse_ray", + "experiment_class": "preregistered_frozen_parameter_causal_state_composition", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + "oracle_information": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "state_evaluation": {"path": str(state_report_path.resolve()), "sha256": sha256(state_report_path)}, + "selection": state_report["selection"], + "assembly": "coarse wrist camera ray recomputed at each frozen state z", + "reference": REFERENCE, + "conditions": conditions, + "takes": take_records, + "outputs": { + "overview": "overview.csv", + "per_hand": "per_hand_frame_metrics.csv", + "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "temporal": "temporal_metrics.csv", + "temporal_takes": "temporal_take_metrics.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": report["status"], "overview": overview}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase7_egodexter_zero_shot.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase7_egodexter_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..d9afe80a0f18d42d100ec440bdaeeb35b14f9e7f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase7_egodexter_zero_shot.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Evaluate a fully frozen Phase 7 model on EgoDexter exactly once.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import time +from typing import Any, Iterator + +import numpy as np +import torch +import yaml + +from foundation_hand.data.egodexter_dataset import ( + EgoDexterSequenceDataset, FINGERTIP_JOINT_INDICES, SEQUENCES, +) +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.train_phase7_external import assert_physical_gpu_idle + + +FINGER_NAMES = ("thumb", "index", "middle", "ring", "little") +MODEL_INPUT_FIELDS = { + "rgb", "depth_m", "depth_pixel_valid", "K", "K_available", + "K_input_available", "depth_available", "depth_input_available", "frame_valid", +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_summary(values: list[float]) -> dict[str, float | int] | None: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if not len(array): + return None + return { + "count": int(len(array)), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + } + + +def validate_freeze_record( + record: dict[str, Any], model_id: str, checkpoint_sha: str, + config_path: Path, inference_mode: str, +) -> dict[str, Any]: + if ( + record.get("status") != "phase7_final_models_frozen" + or record.get("egodexter_used_for_training_or_selection") is not False + or record.get("official_test_used") is not False + ): + raise ValueError("Phase 7 final model set is not EgoDexter-eligible") + models = {item["id"]: item for item in record.get("models", [])} + if model_id not in models: + raise ValueError(f"model is absent from the final freeze: {model_id}") + model = models[model_id] + if model.get("checkpoint_sha256") != checkpoint_sha: + raise ValueError("checkpoint differs from final model freeze") + config_record = model.get("inference_configs", {}).get(inference_mode, {}) + if ( + Path(config_record.get("path", "")).resolve() != config_path.resolve() + or config_record.get("sha256") != sha256(config_path) + ): + raise ValueError("inference config differs from final model freeze") + mapping = record.get("egodexter_sequence_handedness", {}) + if set(mapping) != set(SEQUENCES) or any(side not in {"left", "right"} for side in mapping.values()): + raise ValueError("EgoDexter sequence handedness is not fully frozen") + return model + + +def model_frame(frame: dict[str, object]) -> dict[str, object]: + return {key: frame[key] for key in MODEL_INPUT_FIELDS} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--model-id", required=True) + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--input-mode", choices=("rgb_d_k", "rgb_k", "rgb_only"), required=True) + parser.add_argument("--inference-mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, default=8) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + checkpoint_sha = sha256(args.checkpoint) + freeze = json.loads(args.freeze_record.read_text(encoding="utf-8")) + validate_freeze_record( + freeze, args.model_id, checkpoint_sha, args.config, args.inference_mode, + ) + assert_physical_gpu_idle(args.physical_gpu_id) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + attention_mode = config["model"].get("temporal_attention_mode", "bidirectional") + required_attention = "causal" if args.inference_mode == "causal" else "bidirectional" + if attention_mode != required_attention: + parser.error("inference mode and temporal attention mode differ") + assets = config["assets"] + device = torch.device("cuda") + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + sequence_handedness = freeze["egodexter_sequence_handedness"] + rows: list[dict[str, Any]] = [] + raw_prediction, raw_target, raw_valid = [], [], [] + raw_sequence, raw_frame, raw_side = [], [], [] + maximum_gpu_window = 0 + maximum_cpu_buffer = 0 + total_frames = 0 + started = time.perf_counter() + torch.cuda.reset_peak_memory_stats() + for sequence_index, sequence in enumerate(SEQUENCES): + dataset = EgoDexterSequenceDataset( + args.root, sequence, hand_side=sequence_handedness[sequence], + target_hw=tuple(config["data"]["resolution_hw"]), + ) + targets: list[np.ndarray] = [] + target_valid: list[np.ndarray] = [] + frame_ids: list[int] = [] + + def frames() -> Iterator[dict[str, object]]: + for index in range(len(dataset)): + frame = dataset.frame(index, args.input_mode) + targets.append(frame["target_fingertips_camera_m"].numpy()) + target_valid.append(frame["target_fingertip_valid"].numpy()) + frame_ids.append(int(frame["frame_id"])) + yield model_frame(frame) + + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.inference_mode, window_size=args.window, + offline_stride=(args.window // 2 if args.inference_mode == "offline" else None), + ), + device=device, autocast_dtype=dtype, + ) + output = runner.infer(frames()) + predicted = output["joints_camera"][0, :, dataset.side_index][ + :, FINGERTIP_JOINT_INDICES + ].numpy() + target = np.stack(targets) + valid = np.stack(target_valid) & np.isfinite(predicted).all(axis=-1) + error = np.linalg.norm(predicted - target, axis=-1) * 1000.0 + for frame_index, frame_id in enumerate(frame_ids): + for finger, name in enumerate(FINGER_NAMES): + rows.append({ + "model_id": args.model_id, "sequence": sequence, + "frame_id": frame_id, "hand_side": dataset.hand_side, + "finger": name, "target_visible": bool(valid[frame_index, finger]), + "fingertip_error_mm": ( + float(error[frame_index, finger]) if valid[frame_index, finger] else math.nan + ), + }) + raw_prediction.append(predicted) + raw_target.append(target) + raw_valid.append(valid) + raw_sequence.append(np.full(len(dataset), sequence_index, dtype=np.int16)) + raw_frame.append(np.asarray(frame_ids, dtype=np.int32)) + raw_side.append(np.full(len(dataset), dataset.side_index, dtype=np.int8)) + total_frames += len(dataset) + maximum_gpu_window = max(maximum_gpu_window, runner.maximum_resident_frames) + maximum_cpu_buffer = max(maximum_cpu_buffer, runner.maximum_input_buffer_frames) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + args.output_dir.mkdir(parents=True) + row_path = args.output_dir / "per_fingertip_metrics.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed( + raw_path, predicted_fingertips_camera_m=np.concatenate(raw_prediction), + target_fingertips_camera_m=np.concatenate(raw_target), + target_visible=np.concatenate(raw_valid), sequence_index=np.concatenate(raw_sequence), + frame_id=np.concatenate(raw_frame), side_index=np.concatenate(raw_side), + ) + visible = [row["fingertip_error_mm"] for row in rows if row["target_visible"]] + report = { + "status": "evaluated_frozen_egodexter_zero_shot", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "model_id": args.model_id, "checkpoint_step": int(state["step"]), + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": checkpoint_sha}, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "freeze_record": {"path": str(args.freeze_record.resolve()), "sha256": sha256(args.freeze_record)}, + "input_mode": args.input_mode, "inference_mode": args.inference_mode, + "causal": args.inference_mode == "causal", "window": args.window, + "frames": total_frames, "visible_fingertips": len(visible), + "coverage_fraction": len(visible) / (total_frames * len(FINGER_NAMES)), + "fingertip_error_mm": finite_summary(visible), + "per_finger": { + finger: finite_summary([ + row["fingertip_error_mm"] for row in rows + if row["finger"] == finger and row["target_visible"] + ]) for finger in FINGER_NAMES + }, + "per_sequence": { + sequence: finite_summary([ + row["fingertip_error_mm"] for row in rows + if row["sequence"] == sequence and row["target_visible"] + ]) for sequence in SEQUENCES + }, + "sequence_handedness": sequence_handedness, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": total_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + "maximum_gpu_window_frames": maximum_gpu_window, + "maximum_cpu_input_buffer_frames": maximum_cpu_buffer, + }, + "per_fingertip_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "gt_passed_to_model": False, "per_frame_gt_slot_selection_used": False, + "egodexter_used_for_training_or_selection": False, "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase7_external.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..b067ba132f65bcdbd91712c730da0ff052e1e2f6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase7_external.py @@ -0,0 +1,749 @@ +#!/usr/bin/env python3 +"""Unified held-out evaluation for Phase 7 external-only checkpoints.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import CachedUnifiedClipDataset, collate_h2o_clips +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from foundation_hand.geometry.camera import project_points +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.train_experiment import attach_gt_vertices, move_to_device +from scripts.train_phase7_external import assert_physical_gpu_idle + + +TIP_INDICES = (4, 8, 12, 16, 20) + + +def checkpoint_h2o_training_data_used(checkpoint_extra: dict[str, Any]) -> bool: + """Read H2O exposure without relabelling historical H2O checkpoints.""" + + explicit = checkpoint_extra.get("h2o_training_data_used") + if isinstance(explicit, bool): + return explicit + experiment = checkpoint_extra.get("config", {}).get("experiment", {}) + phase = experiment.get("phase") + # Phase 3-6 checkpoints predate the explicit provenance flag and were + # trained on the canonical H2O train split. + if isinstance(phase, int) and 3 <= phase <= 6: + return True + raise ValueError("checkpoint lacks auditable H2O-training provenance") + + +def validate_evaluation_role( + role: str, config: dict[str, Any], dataset_ids: set[str], + checkpoint_extra: dict[str, Any], cache_manifest: Path, +) -> None: + branch = config.get("experiment", {}).get("branch") + if role == "external_heldout": + if branch != "external_only": + raise ValueError("external evaluation config is not external-only") + if "H2O" in dataset_ids or checkpoint_extra.get("h2o_training_data_used") is not False: + raise ValueError("external evaluator refuses H2O data or training exposure") + elif role == "h2o_train_group_heldout": + if branch != "h2o_adaptation": + raise ValueError("H2O train-heldout evaluation requires an adaptation config") + if dataset_ids != {"H2O"}: + raise ValueError("H2O train-heldout evaluation requires a pure H2O cache") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("adaptation checkpoint lacks H2O-training provenance") + if cache_manifest.name != "train_group_heldout.jsonl": + raise ValueError("adaptation selection requires the frozen train-group-heldout manifest") + elif role == "h2o_train_group_heldout_control": + if dataset_ids != {"H2O"}: + raise ValueError("H2O train-heldout control requires a pure H2O cache") + checkpoint_h2o_training_data_used(checkpoint_extra) + if cache_manifest.name != "train_group_heldout.jsonl": + raise ValueError("H2O control requires the frozen train-group-heldout manifest") + elif role == "adaptation_external_heldout": + if branch != "h2o_adaptation": + raise ValueError("adaptation forgetting evaluation requires an adaptation config") + if not dataset_ids or not dataset_ids.issubset({"HOT3D", "HOI4D", "ARCTIC"}): + raise ValueError("adaptation forgetting evaluation requires pure external held-out data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("adaptation forgetting checkpoint lacks H2O-training provenance") + if "h2o" in str(cache_manifest).lower(): + raise ValueError("adaptation forgetting evaluation refuses H2O cache paths") + elif role == "phase9_external_heldout": + if branch != "phase9_unified": + raise ValueError("Phase 9 external evaluation requires a unified config") + if not dataset_ids or not dataset_ids.issubset({"HOT3D", "HOI4D", "ARCTIC"}): + raise ValueError("Phase 9 external evaluation requires pure external held-out data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("Phase 9 unified checkpoint lacks H2O-training provenance") + if "h2o" in str(cache_manifest).lower(): + raise ValueError("Phase 9 external evaluation refuses H2O cache paths") + elif role == "phase9_h2o_fold_heldout": + fold = str(config.get("experiment", {}).get("h2o_selection_fold", "")) + if branch != "phase9_unified" or not fold: + raise ValueError("Phase 9 fold evaluation requires a fold-specific unified config") + if dataset_ids != {"H2O"}: + raise ValueError("Phase 9 fold evaluation requires pure H2O train-heldout data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("Phase 9 fold checkpoint lacks H2O-training provenance") + expected = f"{fold}_heldout.jsonl" + if cache_manifest.name != expected: + raise ValueError(f"Phase 9 fold cache must be {expected}") + else: + raise ValueError(f"unsupported evaluation role: {role}") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_progress_heartbeat(path: Path | None, value: dict[str, Any]) -> None: + if path is None: + return + payload = { + "schema_version": "phase9_evaluation_progress_heartbeat_v1", + "updated_utc": datetime.now(timezone.utc).isoformat(), + "evaluator_pid": os.getpid(), + "h2o_official_validation_used": False, + "official_test_used": False, + **value, + } + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def direct_child_pids(pid: int) -> list[int]: + path = Path(f"/proc/{pid}/task/{pid}/children") + try: + return sorted(int(value) for value in path.read_text().split()) + except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError): + return [] + + +def finite_summary(values: list[float]) -> dict[str, float | int] | None: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if not len(array): + return None + p95 = float(np.quantile(array, .95)) + tail = array[array >= p95] + return { + "count": int(len(array)), "mean": float(array.mean()), + "median": float(np.median(array)), "p90": float(np.quantile(array, .90)), + "p95": p95, "p99": float(np.quantile(array, .99)), + "cvar95": float(tail.mean()), "max": float(array.max()), + } + + +def tensor_to_numpy(value: torch.Tensor) -> np.ndarray: + """Move persisted floating predictions to a NumPy-supported dtype.""" + value = value.detach().cpu() + if value.is_floating_point() and value.dtype == torch.bfloat16: + value = value.float() + return value.numpy() + + +def append_valid_frame_arrays( + raw: dict[str, list[np.ndarray]], values: dict[str, torch.Tensor], + frame_valid: torch.Tensor, +) -> None: + """Persist variable-length clips on one contiguous valid-frame axis.""" + + valid = tensor_to_numpy(frame_valid.bool()).reshape(-1) + batch, time = frame_valid.shape + for key, value in values.items(): + array = tensor_to_numpy(value) + if array.shape[:2] != (batch, time): + raise ValueError(f"raw temporal field shape differs from frame_valid: {key}") + flattened = array.reshape(batch * time, *array.shape[2:]) + raw.setdefault(key, []).append(flattened[valid]) + + +def hand_size_bucket(size_px: float) -> str: + if size_px < 64.0: + return "small_lt64" + if size_px < 128.0: + return "medium_64_128" + return "large_ge128" + + +def depth_bucket(depth_m: float) -> str: + return "far_gt0.8m" if depth_m > .8 else "near_le0.8m" + + +def apply_input_mode(batch: dict[str, Any], mode: str) -> None: + frame = batch["frame_valid"].bool() + if mode == "rgb_d_k": + batch["K_input_available"] = frame.clone() + elif mode == "rgb_k": + batch["K_input_available"] = frame.clone() + batch["depth_input_available"] = torch.zeros_like(frame) + elif mode == "rgb_only": + batch["K_input_available"] = torch.zeros_like(frame) + batch["depth_input_available"] = torch.zeros_like(frame) + else: + raise ValueError(f"unsupported input mode: {mode}") + batch["K_available"] = batch["K_input_available"] + batch["depth_available"] = batch["depth_input_available"] + + +def grouped_bootstrap( + rows: list[dict[str, Any]], metric: str, seed: int, resamples: int, +) -> dict[str, float | int] | None: + groups: dict[str, list[float]] = {} + for row in rows: + value = row.get(metric) + if value is not None and math.isfinite(float(value)): + groups.setdefault(str(row["physical_recording_id"]), []).append(float(value)) + if not groups: + return None + keys = sorted(groups) + generator = np.random.default_rng(seed) + estimates = [] + for _ in range(resamples): + sampled = generator.choice(keys, size=len(keys), replace=True) + values = [value for key in sampled for value in groups[str(key)]] + estimates.append(float(np.mean(values))) + return { + "groups": len(keys), "resamples": resamples, + "estimate": float(np.mean([value for values in groups.values() for value in values])), + "ci95_low": float(np.quantile(estimates, .025)), + "ci95_high": float(np.quantile(estimates, .975)), + } + + +def metric_fields() -> tuple[str, ...]: + return ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "source_root_relative_mpjpe_mm", + "rigid_se3_mpjpe_mm", "pa_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "direct_2d_error_px", + "projected_mano_2d_error_px", "direct_mano_consistency_px", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "translation_x_signed_mm", "translation_y_signed_mm", "translation_z_signed_mm", + ) + + +def ray_depth_diagnostic_row( + prediction: dict[str, torch.Tensor], batch: dict[str, Any], + batch_index: int, frame: int, side: int, translation_valid: bool, +) -> dict[str, float | bool]: + fields: dict[str, float | bool] = { + "ray_depth_confidence": math.nan, + "ray_depth_raw_delta_z_mm": math.nan, + "ray_depth_applied_delta_z_mm": math.nan, + "ray_depth_support_count": math.nan, + "ray_depth_local_valid_fraction": math.nan, + "ray_depth_correction_valid": False, + "ray_depth_base_z_error_mm": math.nan, + "ray_depth_final_z_error_mm": math.nan, + "ray_depth_harm_mm": math.nan, + } + if "ray_depth_confidence" not in prediction: + return fields + selector = (batch_index, frame, side) + support_count = int(prediction["ray_depth_support_count"][selector]) + fields.update({ + "ray_depth_confidence": float(prediction["ray_depth_confidence"][selector]), + "ray_depth_raw_delta_z_mm": float( + prediction["ray_depth_raw_delta_z_m"][selector] * 1000.0 + ), + "ray_depth_applied_delta_z_mm": float( + prediction["ray_depth_applied_delta_z_m"][selector] * 1000.0 + ), + "ray_depth_support_count": float(support_count), + "ray_depth_local_valid_fraction": support_count / 9.0, + "ray_depth_correction_valid": bool( + prediction["ray_depth_correction_valid"][selector] + ), + }) + if translation_valid: + target_z = batch["wrist_root_translation"][selector][2] + base_error = (prediction["ray_depth_base_z_m"][selector] - target_z).abs() * 1000.0 + final_error = ( + prediction["wrist_root_translation"][selector][2] - target_z + ).abs() * 1000.0 + fields.update({ + "ray_depth_base_z_error_mm": float(base_error), + "ray_depth_final_z_error_mm": float(final_error), + "ray_depth_harm_mm": float(final_error - base_error), + }) + return fields + + +def supervision_coverage(rows: list[dict[str, Any]]) -> dict[str, float | int]: + total = len(rows) + result: dict[str, float | int] = {"hand_rows": total} + for name, field in ( + ("joint3d", "joint3d_supervision"), + ("source_root_relative", "source_root_relative_supervision"), + ("translation", "translation_supervision"), + ("vertices", "vertices_supervision"), + ): + count = sum(bool(row.get(field, False)) for row in rows) + result[f"{name}_valid_hands"] = count + result[f"{name}_valid_fraction"] = count / total if total else 0.0 + return result + + +def make_row( + prediction: dict[str, torch.Tensor], batch: dict[str, Any], + batch_index: int, frame: int, side: int, +) -> dict[str, Any]: + side_name = ("left", "right")[side] + frame_valid = bool(batch["frame_valid"][batch_index, frame]) + translation_valid = frame_valid and bool(batch["translation_valid"][batch_index, frame, side]) + joint_mask = batch["joint3d_valid"][batch_index, frame, side].bool() & frame_valid + joint2d_mask = batch["joint2d_valid"][batch_index, frame, side].bool() & frame_valid + vertices_valid = frame_valid and bool(batch["vertices_valid"][batch_index, frame, side]) + source_relative_mask = torch.zeros_like(joint_mask) + if "joint3d_root_relative_valid" in batch: + source_relative_mask = ( + batch["joint3d_root_relative_valid"][batch_index, frame, side].bool() + & frame_valid + ) + row: dict[str, Any] = { + "dataset": str(batch["dataset_id"][batch_index]), + "subject_id": str(batch["subject_id"][batch_index]), + "physical_recording_id": str(batch["physical_recording_id"][batch_index]), + "camera_id": str(batch["camera_id"][batch_index]), + "headset_id": str(batch["headset_id"][batch_index]), + "frame_id": int(batch["frame_id"][batch_index, frame]), + "side": side_name, + "joint3d_supervision": bool(joint_mask.any()), + "source_root_relative_supervision": bool(source_relative_mask.any()), + "vertices_supervision": vertices_valid, + "translation_supervision": translation_valid, + } + row.update(ray_depth_diagnostic_row( + prediction, batch, batch_index, frame, side, translation_valid, + )) + for field in metric_fields(): + row[field] = math.nan + if translation_valid: + residual_mm = ( + prediction["wrist_root_translation"][batch_index, frame, side] + - batch["wrist_root_translation"][batch_index, frame, side] + ).float().cpu().numpy() * 1000.0 + for axis_index, axis in enumerate("xyz"): + row[f"translation_{axis}_signed_mm"] = float(residual_mm[axis_index]) + row[f"translation_{axis}_mae_mm"] = float(abs(residual_mm[axis_index])) + depth = float(batch["wrist_root_translation"][batch_index, frame, side, 2]) + row["wrist_depth_m"] = depth + row["depth_bucket"] = depth_bucket(depth) + else: + row["wrist_depth_m"] = math.nan + row["depth_bucket"] = "N/A" + if joint2d_mask.any(): + visible_joint_count = int(joint2d_mask.sum()) + row["visible_joint_count"] = visible_joint_count + row["occlusion_bucket"] = ( + "severe_le7" if visible_joint_count <= 7 + else ("partial_8_15" if visible_joint_count <= 15 else "visible_ge16") + ) + target_2d = batch["joint2d"][batch_index, frame, side].float() + height, width = batch["rgb"].shape[-2:] + direct = prediction["joint2d_norm"][batch_index, frame, side].float() * target_2d.new_tensor((width, height)) + predicted_3d = prediction["joints_camera"][batch_index, frame, side].float() + projected, positive = project_points( + predicted_3d, batch["K"][batch_index, frame].float(), + ) + valid_2d = joint2d_mask & torch.isfinite(target_2d).all(-1) + projected_valid = valid_2d & positive + row["direct_2d_error_px"] = float( + torch.linalg.vector_norm(direct - target_2d, dim=-1)[valid_2d].mean() + ) + if projected_valid.any(): + row["projected_mano_2d_error_px"] = float( + torch.linalg.vector_norm(projected - target_2d, dim=-1)[projected_valid].mean() + ) + row["direct_mano_consistency_px"] = float( + torch.linalg.vector_norm(direct - projected, dim=-1)[projected_valid].mean() + ) + valid_points = target_2d[valid_2d] + extent = valid_points.max(0).values - valid_points.min(0).values + size = float(extent.max()) + row["projected_hand_size_px"] = size + row["size_bucket"] = hand_size_bucket(size) + else: + row["visible_joint_count"] = 0 + row["occlusion_bucket"] = "unlabelled" + row["projected_hand_size_px"] = math.nan + row["size_bucket"] = "N/A" + if joint_mask.any(): + predicted_joints = prediction["joints_camera"][batch_index, frame, side].float() + target_joints = batch["joint3d_camera"][batch_index, frame, side].float() + errors = torch.linalg.vector_norm(predicted_joints - target_joints, dim=-1) * 1000.0 + row["absolute_mpjpe_mm"] = float(errors[joint_mask].mean()) + relative_prediction = predicted_joints - predicted_joints[:1] + relative_target = target_joints - target_joints[:1] + relative_error = torch.linalg.vector_norm(relative_prediction - relative_target, dim=-1) * 1000.0 + row["root_relative_mpjpe_mm"] = float(relative_error[joint_mask].mean()) + tips = torch.as_tensor(TIP_INDICES, device=joint_mask.device) + tip_mask = joint_mask[tips] + if tip_mask.any(): + row["fingertip_mpjpe_mm"] = float(errors[tips][tip_mask].mean()) + if bool(joint_mask.all()): + pred_np = predicted_joints.detach().cpu().numpy()[None] + target_np = target_joints.detach().cpu().numpy()[None] + row["rigid_se3_mpjpe_mm"] = float(aligned_mpjpe_mm( + pred_np, target_np, estimate_scale=False, + )[0]) + row["pa_mpjpe_mm"] = float(aligned_mpjpe_mm( + pred_np, target_np, estimate_scale=True, + )[0]) + if source_relative_mask.any(): + predicted_joints = prediction["joints_camera"][batch_index, frame, side].float() + predicted_relative = predicted_joints - predicted_joints[:1] + target_relative = batch["joint3d_root_relative"][batch_index, frame, side].float() + source_error = torch.linalg.vector_norm( + predicted_relative - target_relative, dim=-1, + ) * 1000.0 + row["source_root_relative_mpjpe_mm"] = float( + source_error[source_relative_mask].mean() + ) + if vertices_valid: + vertex_error = torch.linalg.vector_norm( + prediction["vertices_camera"][batch_index, frame, side].float() + - batch["vertices_camera"][batch_index, frame, side].float(), dim=-1, + ) * 1000.0 + row["mpvpe_mm"] = float(vertex_error.mean()) + return row + + +def aggregate(rows: list[dict[str, Any]]) -> dict[str, Any]: + result = {field: finite_summary([row[field] for row in rows]) for field in metric_fields()} + result["supervision_coverage"] = { + "overall": supervision_coverage(rows), + "left": supervision_coverage([row for row in rows if row["side"] == "left"]), + "right": supervision_coverage([row for row in rows if row["side"] == "right"]), + } + for split_name, selector in { + "left": lambda row: row["side"] == "left", + "right": lambda row: row["side"] == "right", + "near": lambda row: row["depth_bucket"] == "near_le0.8m", + "far": lambda row: row["depth_bucket"] == "far_gt0.8m", + "small": lambda row: row["size_bucket"] == "small_lt64", + "medium": lambda row: row["size_bucket"] == "medium_64_128", + "large": lambda row: row["size_bucket"] == "large_ge128", + }.items(): + selected = [row for row in rows if selector(row)] + result[f"bucket_{split_name}"] = { + "hands": len(selected), + "supervision_coverage": supervision_coverage(selected), + "absolute_mpjpe_mm": finite_summary([row["absolute_mpjpe_mm"] for row in selected]), + "translation_z_mae_mm": finite_summary([row["translation_z_mae_mm"] for row in selected]), + "fingertip_mpjpe_mm": finite_summary([row["fingertip_mpjpe_mm"] for row in selected]), + } + for field, prefix in (("headset_id", "headset"), ("occlusion_bucket", "occlusion")): + for value in sorted({str(row[field]) for row in rows}): + selected = [row for row in rows if str(row[field]) == value] + normalized = "".join(character.lower() if character.isalnum() else "_" for character in value) + result[f"bucket_{prefix}_{normalized}"] = { + "hands": len(selected), + "supervision_coverage": supervision_coverage(selected), + "absolute_mpjpe_mm": finite_summary([ + row["absolute_mpjpe_mm"] for row in selected + ]), + "root_relative_mpjpe_mm": finite_summary([ + row["root_relative_mpjpe_mm"] for row in selected + ]), + "translation_z_mae_mm": finite_summary([ + row["translation_z_mae_mm"] for row in selected + ]), + "fingertip_mpjpe_mm": finite_summary([ + row["fingertip_mpjpe_mm"] for row in selected + ]), + } + ray_rows = [row for row in rows if math.isfinite(float(row["ray_depth_confidence"]))] + result["ray_depth_diagnostics"] = None + if ray_rows: + correction_rows = [row for row in ray_rows if row["ray_depth_correction_valid"]] + result["ray_depth_diagnostics"] = { + "hands": len(ray_rows), + "correction_valid_hands": len(correction_rows), + "correction_valid_fraction": len(correction_rows) / len(ray_rows), + "confidence": finite_summary([row["ray_depth_confidence"] for row in ray_rows]), + "raw_delta_z_mm": finite_summary([row["ray_depth_raw_delta_z_mm"] for row in ray_rows]), + "applied_delta_z_mm": finite_summary([row["ray_depth_applied_delta_z_mm"] for row in ray_rows]), + "support_count": finite_summary([row["ray_depth_support_count"] for row in ray_rows]), + "local_valid_fraction": finite_summary([ + row["ray_depth_local_valid_fraction"] for row in ray_rows + ]), + "base_z_error_mm": finite_summary([row["ray_depth_base_z_error_mm"] for row in ray_rows]), + "final_z_error_mm": finite_summary([row["ray_depth_final_z_error_mm"] for row in ray_rows]), + "harm_mm": finite_summary([row["ray_depth_harm_mm"] for row in correction_rows]), + "harm_fraction": ( + float(np.mean([row["ray_depth_harm_mm"] > 0 for row in correction_rows])) + if correction_rows else None + ), + } + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--expected-cache-manifest-sha256") + parser.add_argument("--input-mode", choices=("rgb_d_k", "rgb_k", "rgb_only"), required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument( + "--allow-physical-gpus-4-5", action="store_true", + help="Explicit resource override; default preserves the historical GPU0-3 contract.", + ) + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--evaluation-id") + parser.add_argument("--heartbeat-path", type=Path) + parser.add_argument("--heartbeat-seconds", type=float, default=30.0) + parser.add_argument( + "--evaluation-role", + choices=( + "external_heldout", "h2o_train_group_heldout", + "h2o_train_group_heldout_control", "adaptation_external_heldout", + "phase9_external_heldout", "phase9_h2o_fold_heldout", + ), + default="external_heldout", + ) + args = parser.parse_args() + if args.heartbeat_seconds < 1: + parser.error("heartbeat interval must be at least one second") + if (args.heartbeat_path is None) != (args.evaluation_id is None): + parser.error("evaluation ID and heartbeat path must be provided together") + if sha256(args.checkpoint) != args.expected_checkpoint_sha256: + parser.error("checkpoint SHA256 differs from frozen expected value") + if ( + args.expected_cache_manifest_sha256 is not None + and sha256(args.cache_manifest) != args.expected_cache_manifest_sha256 + ): + parser.error("cache manifest SHA256 differs from frozen expected value") + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + allowed_physical_gpus = {0, 1, 2, 3} + if args.allow_physical_gpus_4_5: + allowed_physical_gpus.update((4, 5)) + if args.physical_gpu_id not in allowed_physical_gpus: + parser.error("physical GPU must be one of 0-3; GPU4-5 are reserved") + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + heartbeat_path = args.heartbeat_path + if heartbeat_path is not None: + if heartbeat_path.resolve().parent != args.output_dir.resolve(): + parser.error("evaluation heartbeat must be inside the output directory") + write_progress_heartbeat(heartbeat_path, { + "status": "initializing", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "processed_clips": 0, "processed_frames": 0, + "dataloader_worker_pids": [], + }) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + dataset = CachedUnifiedClipDataset(args.cache_manifest, K_input_dropout=0.0) + write_progress_heartbeat(heartbeat_path, { + "status": "data_ready", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": 0, + "processed_frames": 0, "dataloader_worker_pids": [], + }) + loader = DataLoader( + dataset, batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).cuda().eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location="cuda") + validate_evaluation_role( + args.evaluation_role, config, + {str(row["dataset_id"]).upper() for row in dataset.rows}, + state["extra"], args.cache_manifest, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + rows: list[dict[str, Any]] = [] + raw: dict[str, list[np.ndarray]] = {} + started = time.perf_counter() + last_heartbeat = started + processed_clips = 0 + processed_frames = 0 + torch.cuda.reset_peak_memory_stats() + with torch.inference_mode(): + for batch in loader: + processed_clips += len(batch["dataset_id"]) + apply_input_mode(batch, args.input_mode) + batch = move_to_device(batch, torch.device("cuda")) + if args.evaluation_role in { + "h2o_train_group_heldout", "h2o_train_group_heldout_control", + "phase9_h2o_fold_heldout", + }: + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + processed_frames += int(batch["frame_valid"].sum()) + now = time.perf_counter() + if now - last_heartbeat >= args.heartbeat_seconds: + write_progress_heartbeat(heartbeat_path, { + "status": "running", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), + "processed_clips": processed_clips, + "processed_frames": processed_frames, + "dataloader_worker_pids": direct_child_pids(os.getpid()), + }) + last_heartbeat = now + persisted = { + "predicted_joints_camera": prediction["joints_camera"], + "predicted_vertices_camera": prediction["vertices_camera"], + "predicted_wrist_root_translation": prediction["wrist_root_translation"], + "predicted_joint2d_norm": prediction["joint2d_norm"], + "predicted_mano_rotation_matrices": prediction["mano_rotation_matrices"], + "predicted_mano_shape": prediction["mano_shape"], + "target_mano_pose": batch["mano_pose"], + "mano_pose_valid": batch["mano_pose_valid"], + "target_joints_camera": batch["joint3d_camera"], + "target_vertices_camera": batch["vertices_camera"], + "target_wrist_root_translation": batch["wrist_root_translation"], + "target_joint2d": batch["joint2d"], + "joint3d_valid": batch["joint3d_valid"], + "vertices_valid": batch["vertices_valid"], + "translation_valid": batch["translation_valid"], + "joint2d_valid": batch["joint2d_valid"], + "frame_valid": batch["frame_valid"], + "K": batch["K"], + "frame_id": batch["frame_id"], + } + if "joint3d_root_relative" in batch: + persisted.update({ + "target_joint3d_root_relative": batch["joint3d_root_relative"], + "joint3d_root_relative_valid": batch["joint3d_root_relative_valid"], + }) + for key in ( + "ray_depth_wrist2d_norm", "ray_depth_log_base_z", + "ray_depth_base_z_m", "ray_depth_raw_delta_z_m", + "ray_depth_applied_delta_z_m", "ray_depth_confidence_logit", + "ray_depth_confidence", "ray_depth_local_statistics", + "ray_depth_support_count", "ray_depth_correction_valid", + "ray_depth_K_input_available", + ): + if key in prediction: + persisted[key] = prediction[key] + append_valid_frame_arrays(raw, persisted, batch["frame_valid"]) + batch_size, time_count = batch["frame_valid"].shape + for batch_index in range(batch_size): + for frame in range(time_count): + if not bool(batch["frame_valid"][batch_index, frame]): + continue + for side in range(2): + rows.append(make_row(prediction, batch, batch_index, frame, side)) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + write_progress_heartbeat(heartbeat_path, { + "status": "finalizing", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": processed_clips, + "processed_frames": processed_frames, + "dataloader_worker_pids": direct_child_pids(os.getpid()), + }) + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed(raw_path, **{ + key: np.concatenate(values, axis=0) for key, values in raw.items() + }) + row_path = args.output_dir / "per_hand_frame_metrics.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + take_rows = [] + for take in sorted({str(row["physical_recording_id"]) for row in rows}): + selected = [row for row in rows if row["physical_recording_id"] == take] + record: dict[str, Any] = {"physical_recording_id": take, "hands": len(selected)} + for field in metric_fields(): + summary = finite_summary([row[field] for row in selected]) + record[field] = summary["mean"] if summary is not None else math.nan + take_rows.append(record) + take_path = args.output_dir / "take_metrics.csv" + with take_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(take_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(take_rows) + bootstrap = { + field: grouped_bootstrap(rows, field, int(config["seed"]), args.bootstrap_resamples) + for field in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "source_root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + report = { + "status": { + "external_heldout": "evaluated", + "h2o_train_group_heldout": "evaluated_h2o_train_group_heldout", + "h2o_train_group_heldout_control": "evaluated_h2o_train_group_heldout_control", + "adaptation_external_heldout": "evaluated_adaptation_external_heldout", + "phase9_external_heldout": "evaluated_phase9_external_heldout", + "phase9_h2o_fold_heldout": "evaluated_phase9_h2o_fold_heldout", + }[args.evaluation_role], + "evaluation_role": args.evaluation_role, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "experiment": config["name"], "checkpoint_step": int(state["step"]), + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": args.expected_checkpoint_sha256}, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "cache_manifest": {"path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest)}, + "input_mode": args.input_mode, "clips": len(dataset), "frames": processed_frames, + "hands_rows": len(rows), "metrics": aggregate(rows), "grouped_bootstrap_ci": bootstrap, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": processed_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + }, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "raw_prediction_layout": "axis0 is the ordered sequence of frame_valid=true frames", + "per_hand_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "take_metrics": {"path": str(take_path.resolve()), "sha256": sha256(take_path)}, + "official_test_used": False, + "h2o_training_data_used": checkpoint_h2o_training_data_used(state["extra"]), + "h2o_official_validation_used": False, + "oracle_information_used": False, + "metric_definitions": { + "rigid_se3_mpjpe_mm": "per-hand Kabsch; removes translation and rotation", + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation and scale", + }, + } + output = args.output_dir / "evaluation.json" + output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + write_progress_heartbeat(heartbeat_path, { + "status": "complete", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": processed_clips, + "processed_frames": processed_frames, + "evaluation_report": str(output.resolve()), + "evaluation_report_sha256": sha256(output), + "dataloader_worker_pids": [], + }) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase7_h2o_zero_shot.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase7_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..dde27a07128671619a11c73262c329644068bc26 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase7_h2o_zero_shot.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Strict one-shot H2O validation evaluation of a frozen external generalist.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.evaluate_phase7_external import ( + aggregate, + apply_input_mode, + finite_summary, + grouped_bootstrap, + make_row, + metric_fields, + sha256, + tensor_to_numpy, +) +from scripts.train_experiment import attach_gt_vertices, move_to_device +from scripts.train_phase7_external import assert_physical_gpu_idle + + +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") +EVALUATION_ROLES = ( + "strict_external_zero_shot", "h2o_adapted_formal", + "phase9_unified_formal", +) + + +def validate_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + status = record.get("status") + if status not in { + "external_generalist_frozen", "external_architecture_candidate_frozen", + }: + raise ValueError("external checkpoint is not frozen") + if status == "external_architecture_candidate_frozen" and ( + record.get("selected_within_family") is not True + or record.get("overall_external_generalist_winner") is not False + ): + raise ValueError("external architecture candidate role is ambiguous") + if record.get("checkpoint_sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen external generalist") + if record.get("official_test_used") is not False: + raise ValueError("freeze record must explicitly exclude official test") + if record.get("h2o_official_validation_used_for_external_selection") is not False: + raise ValueError("external selection must precede H2O validation access") + if not record.get("external_selection_sha256"): + raise ValueError("freeze record lacks external selection SHA256") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from freeze record") + + +def validate_adaptation_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + if record.get("status") != "h2o_adaptation_candidate_frozen": + raise ValueError("H2O adaptation candidate is not frozen") + checkpoint = record.get("checkpoint", {}) + if checkpoint.get("sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen adaptation candidate") + if record.get("h2o_official_validation_used_for_selection") is not False: + raise ValueError("adaptation selection must use H2O train-heldout only") + if record.get("official_test_used") is not False: + raise ValueError("adaptation freeze record must explicitly exclude official test") + if not record.get("adaptation_selection_sha256"): + raise ValueError("adaptation freeze record lacks selection SHA256") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from adaptation freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from adaptation freeze record") + + +def validate_phase9_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + if record.get("status") != "phase9_final_unified_checkpoint_frozen": + raise ValueError("Phase 9 final unified checkpoint is not frozen") + if record.get("checkpoint", {}).get("sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen Phase 9 final checkpoint") + if ( + record.get("selection_complete") is not True + or record.get("stage9_final_decision_complete") is not True + or record.get("h2o_official_validation_used_for_selection") is not False + or record.get("official_test_used") is not False + or not record.get("selection_chain_sha256") + ): + raise ValueError("Phase 9 final selection provenance is incomplete") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from Phase 9 freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from Phase 9 freeze record") + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"cannot write empty metric rows: {path}") + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(rows) + + +def append_valid_frame_arrays( + raw: dict[str, list[np.ndarray]], values: dict[str, torch.Tensor], + frame_valid: torch.Tensor, +) -> None: + """Persist variable-length clips as one contiguous valid-frame axis.""" + + valid = tensor_to_numpy(frame_valid.bool()).reshape(-1) + batch, time = frame_valid.shape + for key, value in values.items(): + array = tensor_to_numpy(value) + if array.shape[:2] != (batch, time): + raise ValueError(f"raw temporal field shape differs from frame_valid: {key}") + flattened = array.reshape(batch * time, *array.shape[2:]) + raw.setdefault(key, []).append(flattened[valid]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--input-mode", choices=INPUT_MODES, required=True) + parser.add_argument( + "--evaluation-role", choices=EVALUATION_ROLES, + default="strict_external_zero_shot", + ) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--frame-stride", type=int, default=1) + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.physical_gpu_id not in {0, 1, 2, 3}: + parser.error("physical GPU must be one of 0-3; GPU4-5 are reserved") + import os + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + if sha256(args.checkpoint) != args.expected_checkpoint_sha256: + parser.error("checkpoint SHA256 differs from frozen expected value") + freeze_record = json.loads(args.freeze_record.read_text(encoding="utf-8")) + if args.evaluation_role == "strict_external_zero_shot": + validate_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + elif args.evaluation_role == "h2o_adapted_formal": + validate_adaptation_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + else: + validate_phase9_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + expected_branch = { + "strict_external_zero_shot": "external_only", + "h2o_adapted_formal": "h2o_adaptation", + "phase9_unified_formal": "phase9_unified", + }[args.evaluation_role] + if config.get("experiment", {}).get("branch") != expected_branch: + raise ValueError(f"checkpoint config branch is not {expected_branch}") + dataset = H2OCam4Dataset( + args.root, args.manifest, + target_hw=tuple(config["data"]["resolution_hw"]), + clip_lengths=(args.clip_length,), strides=(args.frame_stride,), + ) + loader = DataLoader( + dataset, batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).cuda().eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location="cuda") + expected_h2o_training = args.evaluation_role != "strict_external_zero_shot" + if state["extra"].get("h2o_training_data_used") is not expected_h2o_training: + raise ValueError("checkpoint H2O-training provenance differs from evaluation role") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + rows: list[dict[str, Any]] = [] + raw: dict[str, list[np.ndarray]] = {} + processed_frames = 0 + started = time.perf_counter() + torch.cuda.reset_peak_memory_stats() + with torch.inference_mode(): + for batch in loader: + apply_input_mode(batch, args.input_mode) + batch = move_to_device(batch, torch.device("cuda")) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + processed_frames += int(batch["frame_valid"].sum()) + persisted = { + "predicted_joints_camera": prediction["joints_camera"], + "predicted_vertices_camera": prediction["vertices_camera"], + "predicted_wrist_root_translation": prediction["wrist_root_translation"], + "predicted_joint2d_norm": prediction["joint2d_norm"], + "predicted_mano_rotation_matrices": prediction["mano_rotation_matrices"], + "predicted_mano_shape": prediction["mano_shape"], + "target_joints_camera": batch["joint3d_camera"], + "target_vertices_camera": batch["vertices_camera"], + "target_wrist_root_translation": batch["wrist_root_translation"], + "target_joint2d": batch["joint2d"], + "joint3d_valid": batch["joint3d_valid"], + "vertices_valid": batch["vertices_valid"], + "translation_valid": batch["translation_valid"], + "joint2d_valid": batch["joint2d_valid"], + "frame_valid": batch["frame_valid"], + "K": batch["K"], + "frame_id": batch["frame_id"], + } + append_valid_frame_arrays(raw, persisted, batch["frame_valid"]) + batch_size, time_count = batch["frame_valid"].shape + for batch_index in range(batch_size): + for frame in range(time_count): + if not bool(batch["frame_valid"][batch_index, frame]): + continue + for side in range(2): + rows.append(make_row(prediction, batch, batch_index, frame, side)) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed(raw_path, **{ + key: np.concatenate(values, axis=0) for key, values in raw.items() + }) + row_path = args.output_dir / "per_hand_frame_metrics.csv" + write_csv(row_path, rows) + take_rows = [] + for take in sorted({str(row["physical_recording_id"]) for row in rows}): + selected = [row for row in rows if row["physical_recording_id"] == take] + record: dict[str, Any] = {"physical_recording_id": take, "hands": len(selected)} + for field in metric_fields(): + summary = finite_summary([row[field] for row in selected]) + record[field] = summary["mean"] if summary is not None else math.nan + take_rows.append(record) + take_path = args.output_dir / "take_metrics.csv" + write_csv(take_path, take_rows) + bootstrap = { + field: grouped_bootstrap( + rows, field, int(config["seed"]), args.bootstrap_resamples, + ) + for field in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + report = { + "status": { + "strict_external_zero_shot": "evaluated_strict_h2o_zero_shot", + "h2o_adapted_formal": "evaluated_h2o_adapted_formal", + "phase9_unified_formal": "evaluated_phase9_unified_formal", + }[args.evaluation_role], + "evaluation_role": args.evaluation_role, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "experiment": config["name"], "checkpoint_step": int(state["step"]), + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": args.expected_checkpoint_sha256, + }, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "freeze_record": { + "path": str(args.freeze_record.resolve()), "sha256": sha256(args.freeze_record), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "input_mode": args.input_mode, "clips": len(dataset), "frames": processed_frames, + "hands_rows": len(rows), "metrics": aggregate(rows), + "grouped_bootstrap_ci": bootstrap, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": processed_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + }, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "raw_prediction_layout": "axis0 is the ordered sequence of frame_valid=true frames", + "per_hand_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "take_metrics": {"path": str(take_path.resolve()), "sha256": sha256(take_path)}, + "h2o_training_data_used": expected_h2o_training, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + "oracle_information_used": False, + "metric_definitions": { + "rigid_se3_mpjpe_mm": "per-hand Kabsch; removes translation and rotation", + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation and scale", + }, + } + output = args.output_dir / "evaluation.json" + output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase8_translation_oracles.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase8_translation_oracles.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3f03e6d4363d51d6d533cf00426e064d9d61b4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_phase8_translation_oracles.py @@ -0,0 +1,355 @@ +#!/usr/bin/env python3 +"""Evaluation-only ray/z/root-relative decomposition from persisted predictions.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +CONDITIONS = ( + "raw", + "predicted_pose_shape_gt_translation", + "predicted_ray_gt_z", + "gt_ray_predicted_z", + "predicted_root_relative_gt_translation", + "predicted_translation_gt_root_relative", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def flatten_leading(array: np.ndarray, trailing_dimensions: int) -> np.ndarray: + trailing = array.shape[-trailing_dimensions:] + return array.reshape(-1, *trailing) + + +def axis_angle_to_matrix(axis_angle: np.ndarray) -> np.ndarray: + angle = np.linalg.norm(axis_angle, axis=-1) + safe = np.maximum(angle, 1e-12) + axis = axis_angle / safe[..., None] + x, y, z = np.moveaxis(axis, -1, 0) + zero = np.zeros_like(x) + skew = np.stack(( + zero, -z, y, z, zero, -x, -y, x, zero, + ), axis=-1).reshape(*axis.shape[:-1], 3, 3) + identity = np.broadcast_to(np.eye(3), skew.shape) + matrix = ( + identity + np.sin(angle)[..., None, None] * skew + + (1.0 - np.cos(angle))[..., None, None] * (skew @ skew) + ) + return np.where((angle < 1e-12)[..., None, None], identity, matrix) + + +def decompose(arrays: dict[str, np.ndarray]) -> dict[str, Any]: + pred_joints = flatten_leading(arrays["predicted_joints_camera"], 3) + target_joints = flatten_leading(arrays["target_joints_camera"], 3) + pred_translation = flatten_leading( + arrays["predicted_wrist_root_translation"], 2, + ) + target_translation = flatten_leading( + arrays["target_wrist_root_translation"], 2, + ) + joint_valid = flatten_leading(arrays["joint3d_valid"], 2).astype(bool) + translation_valid = flatten_leading( + arrays["translation_valid"], 1, + ).astype(bool) + if not ( + pred_joints.shape[:2] == target_joints.shape[:2] + == pred_translation.shape[:2] == target_translation.shape[:2] + == joint_valid.shape[:2] + ): + raise ValueError("raw prediction arrays do not share frame/hand axes") + pred_relative = pred_joints - pred_joints[..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + pred_z = pred_translation[..., 2] + target_z = target_translation[..., 2] + safe_pred_z = np.where(np.abs(pred_z) > 1e-6, pred_z, np.nan) + safe_target_z = np.where(np.abs(target_z) > 1e-6, target_z, np.nan) + pred_ray = pred_translation[..., :2] / safe_pred_z[..., None] + target_ray = target_translation[..., :2] / safe_target_z[..., None] + pred_ray_gt_z_translation = np.concatenate( + (pred_ray * target_z[..., None], target_z[..., None]), axis=-1, + ) + gt_ray_pred_z_translation = np.concatenate( + (target_ray * pred_z[..., None], pred_z[..., None]), axis=-1, + ) + condition_joints = { + "raw": pred_joints, + "predicted_pose_shape_gt_translation": ( + pred_relative + target_translation[..., None, :] + ), + "predicted_ray_gt_z": ( + pred_relative + pred_ray_gt_z_translation[..., None, :] + ), + "gt_ray_predicted_z": ( + pred_relative + gt_ray_pred_z_translation[..., None, :] + ), + "predicted_root_relative_gt_translation": ( + pred_relative + target_translation[..., None, :] + ), + "predicted_translation_gt_root_relative": ( + target_relative + pred_translation[..., None, :] + ), + } + condition_errors: dict[str, np.ndarray] = {} + annotation_valid = joint_valid.any(axis=-1) & translation_valid + positive_depth = ( + np.isfinite(pred_z) & np.isfinite(target_z) + & (pred_z > 0.05) & (target_z > 0.05) + ) + hand_valid = annotation_valid & positive_depth + for name, joints in condition_joints.items(): + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + numerator = np.where(joint_valid, joint_error, 0.0).sum(axis=-1) + denominator = joint_valid.sum(axis=-1) + error = numerator / np.maximum(denominator, 1) + condition_errors[name] = np.where(hand_valid, error, np.nan) + translation_residual = (pred_translation - target_translation) * 1000.0 + ray_residual = pred_ray - target_ray + result = { + "condition_errors_mm": condition_errors, + "translation_residual_mm": translation_residual, + "ray_residual": ray_residual, + "predicted_z_m": pred_z, + "target_z_m": target_z, + "valid": hand_valid, + "annotation_valid": annotation_valid, + "positive_depth": positive_depth, + } + if "K" in arrays: + K = flatten_leading(arrays["K"], 2) + if K.shape[0] != hand_valid.shape[0]: + raise ValueError("K frame axis differs from prediction frame axis") + result["K"] = np.broadcast_to(K[:, None], (*hand_valid.shape, 3, 3)) + if {"predicted_mano_rotation_matrices", "target_mano_pose", "mano_pose_valid"}.issubset(arrays): + predicted_rotation = flatten_leading( + arrays["predicted_mano_rotation_matrices"], 4, + )[..., 0, :, :] + target_pose = flatten_leading(arrays["target_mano_pose"], 2) + pose_valid = flatten_leading(arrays["mano_pose_valid"], 1).astype(bool) + target_rotation = axis_angle_to_matrix(target_pose[..., :3]) + relative = predicted_rotation @ np.swapaxes(target_rotation, -1, -2) + cosine = np.clip( + (np.trace(relative, axis1=-2, axis2=-1) - 1.0) / 2.0, + -1.0, 1.0, + ) + result["global_orientation_geodesic_deg"] = np.degrees(np.arccos(cosine)) + result["global_orientation_valid"] = pose_valid + return result + + +def finite_summary(values: np.ndarray) -> dict[str, float | int] | None: + values = np.asarray(values, dtype=np.float64) + values = values[np.isfinite(values)] + if not values.size: + return None + return { + "count": int(values.size), "mean": float(values.mean()), + "median": float(np.median(values)), + "p95": float(np.quantile(values, 0.95)), + } + + +def correlation(x: np.ndarray, y: np.ndarray, valid: np.ndarray) -> float | None: + mask = valid & np.isfinite(x) & np.isfinite(y) + if mask.sum() < 2 or np.std(x[mask]) == 0 or np.std(y[mask]) == 0: + return None + return float(np.corrcoef(x[mask], y[mask])[0, 1]) + + +def build_report(result: dict[str, Any]) -> dict[str, Any]: + errors = result["condition_errors_mm"] + raw_mean = float(np.nanmean(errors["raw"])) + conditions = {} + for name in CONDITIONS: + summary = finite_summary(errors[name]) + if summary is None: + conditions[name] = None + continue + gain = raw_mean - float(summary["mean"]) + conditions[name] = { + **summary, "gain_vs_raw_mm": gain, + "gain_vs_raw_percent": 100.0 * gain / raw_mean, + } + fix_z_gain = raw_mean - float(np.nanmean(errors["predicted_ray_gt_z"])) + fix_ray_gain = raw_mean - float(np.nanmean(errors["gt_ray_predicted_z"])) + fix_translation_gain = raw_mean - float(np.nanmean( + errors["predicted_root_relative_gt_translation"], + )) + interaction = fix_translation_gain - fix_z_gain - fix_ray_gain + residual = result["translation_residual_mm"] + valid = result["valid"] + axis = { + name: { + "signed_mm": finite_summary(residual[..., index][valid]), + "absolute_mm": finite_summary(np.abs(residual[..., index][valid])), + } + for index, name in enumerate("xyz") + } + axis["correlation"] = { + "x_y": correlation(residual[..., 0], residual[..., 1], valid), + "x_z": correlation(residual[..., 0], residual[..., 2], valid), + "y_z": correlation(residual[..., 1], residual[..., 2], valid), + } + orientation = result.get("global_orientation_geodesic_deg") + orientation_valid = result.get("global_orientation_valid") + return { + "status": "evaluated_oracle_diagnostic_only", + "deployable_claim": False, + "selection_use": False, + "official_test_used": False, + "validity_audit": { + "annotation_valid_hands": int(result["annotation_valid"].sum()), + "positive_depth_hands": int(result["valid"].sum()), + "excluded_nonpositive_or_near_depth": int( + (result["annotation_valid"] & ~result["positive_depth"]).sum() + ), + "minimum_ray_depth_m": 0.05, + }, + "conditions": conditions, + "translation_attribution": { + "fix_z_gain_mm": fix_z_gain, + "fix_ray_gain_mm": fix_ray_gain, + "fix_all_translation_gain_mm": fix_translation_gain, + "nonadditive_interaction_mm": interaction, + "note": "Counterfactual gains are not assumed additive; interaction is reported explicitly.", + }, + "translation_axis_error": axis, + "ray_residual_norm": finite_summary( + np.linalg.norm(result["ray_residual"], axis=-1)[valid], + ), + "global_orientation_geodesic_deg": ( + finite_summary(orientation[orientation_valid]) + if orientation is not None and orientation_valid is not None else None + ), + } + + +def bucket_report(result: dict[str, Any], rows: list[dict[str, Any]]) -> dict[str, Any]: + shape = result["valid"].shape + flat_rows = np.asarray(rows, dtype=object).reshape(shape) + target_z = result["target_z_m"] + selectors: dict[str, np.ndarray] = { + "side_left": np.vectorize(lambda row: row.get("side") == "left")(flat_rows), + "side_right": np.vectorize(lambda row: row.get("side") == "right")(flat_rows), + "depth_near_le0.5m": target_z <= 0.5, + "depth_mid_0.5_0.8m": (target_z > 0.5) & (target_z <= 0.8), + "depth_far_gt0.8m": target_z > 0.8, + } + for size in ("small_lt64", "medium_64_128", "large_ge128"): + selectors[f"size_{size}"] = np.vectorize( + lambda row, expected=size: row.get("size_bucket") == expected, + )(flat_rows) + K = result.get("K") + if K is not None: + focal = np.sqrt(K[..., 0, 0] * K[..., 1, 1]) + finite = focal[result["valid"] & np.isfinite(focal)] + if finite.size: + low, high = np.quantile(finite, (1.0 / 3.0, 2.0 / 3.0)) + selectors["focal_low"] = focal <= low + selectors["focal_mid"] = (focal > low) & (focal <= high) + selectors["focal_high"] = focal > high + errors = result["condition_errors_mm"] + output: dict[str, Any] = {} + for name, selector in selectors.items(): + mask = result["valid"] & selector + raw = finite_summary(errors["raw"][mask]) + if raw is None: + output[name] = None + continue + raw_mean = float(raw["mean"]) + output[name] = { + "raw_absolute_mpjpe_mm": raw, + "fix_z_gain_mm": raw_mean - float(np.nanmean(errors["predicted_ray_gt_z"][mask])), + "fix_ray_gain_mm": raw_mean - float(np.nanmean(errors["gt_ray_predicted_z"][mask])), + "fix_translation_gain_mm": raw_mean - float(np.nanmean( + errors["predicted_root_relative_gt_translation"][mask], + )), + } + output["occlusion"] = { + "status": "N/A" if not any("occlusion_bucket" in row for row in rows) else "available", + "reason": "Phase 7 per-hand rows do not persist a common occlusion bucket", + } + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--raw-predictions", type=Path, required=True) + parser.add_argument("--per-hand-rows", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + args.output_dir.mkdir(parents=True, exist_ok=True) + with np.load(args.raw_predictions) as loaded: + result = decompose({key: loaded[key] for key in loaded.files}) + rows = list(csv.DictReader(args.per_hand_rows.open(encoding="utf-8"))) + flat_count = result["valid"].size + if len(rows) != flat_count: + raise ValueError( + f"per-hand rows ({len(rows)}) differ from raw frame-hand count ({flat_count})" + ) + errors = result["condition_errors_mm"] + output_rows = [] + for index, row in enumerate(rows): + record = { + key: row.get(key, "") for key in ( + "dataset", "subject_id", "physical_recording_id", "camera_id", + "frame_id", "side", "depth_bucket", "size_bucket", + ) + } + flat_index = np.unravel_index(index, result["valid"].shape) + for condition in CONDITIONS: + record[f"{condition}_absolute_mpjpe_mm"] = float( + errors[condition][flat_index] + ) + for axis_index, axis in enumerate("xyz"): + record[f"translation_{axis}_signed_mm"] = float( + result["translation_residual_mm"][flat_index][axis_index] + ) + record["target_wrist_depth_m"] = float(result["target_z_m"][flat_index]) + record["predicted_wrist_depth_m"] = float(result["predicted_z_m"][flat_index]) + record["ray_residual_norm"] = float(np.linalg.norm(result["ray_residual"][flat_index])) + if "K" in result: + record["fx_px"] = float(result["K"][flat_index][0, 0]) + record["fy_px"] = float(result["K"][flat_index][1, 1]) + output_rows.append(record) + csv_path = args.output_dir / "per_hand_oracle_decomposition.csv" + with csv_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(output_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(output_rows) + report = build_report(result) + report["buckets"] = bucket_report(result, rows) + report.update({ + "raw_predictions": { + "path": str(args.raw_predictions.resolve()), + "sha256": sha256(args.raw_predictions), + }, + "per_hand_input": { + "path": str(args.per_hand_rows.resolve()), + "sha256": sha256(args.per_hand_rows), + }, + "per_hand_output": {"path": str(csv_path.resolve()), "sha256": sha256(csv_path)}, + }) + path = args.output_dir / "oracle_decomposition.json" + path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_sota_bundle.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_sota_bundle.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a226aebdf5591829184aa3e54525238a05d83a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_sota_bundle.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Evaluate one standardized external-model prediction bundle on H2O.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + evaluate_prediction_bundle, + write_csv_rows, +) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--prediction", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument( + "--pixel-scale", + type=float, + default=0.5, + help="Map raw H2O pixels to the Phase 3 640x368 evaluation scale.", + ) + parser.add_argument("--temporal-clip-length", type=int, default=8) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + prediction = PredictionBundle.load(args.prediction) + ground_truth = GroundTruthBundle.load(args.ground_truth) + report, frame_rows, temporal_rows = evaluate_prediction_bundle( + prediction, + ground_truth, + bootstrap_seed=args.bootstrap_seed, + bootstrap_samples=args.bootstrap_samples, + pixel_scale=args.pixel_scale, + temporal_clip_length=args.temporal_clip_length, + ) + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + write_csv_rows(args.output_dir / "per_hand_frame_metrics.csv", frame_rows) + write_csv_rows(args.output_dir / "per_temporal_transition_metrics.csv", temporal_rows) + print(json.dumps({ + "model": report["model_name"], + "coverage": report["coverage"]["hand_frame_fraction"], + "absolute_mpjpe_mm": report["metrics_success_conditioned"][ + "absolute_mpjpe_mm" + ]["mean"], + "root_relative_mpjpe_mm": report["metrics_success_conditioned"][ + "root_relative_mpjpe_mm" + ]["mean"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_tiny.py b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_tiny.py new file mode 100644 index 0000000000000000000000000000000000000000..d1416cb0dd5df06fc941ee11a654e30062cf3517 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/evaluate_tiny.py @@ -0,0 +1,426 @@ +#!/usr/bin/env python3 +"""Deterministic full tiny-set evaluation and visualization.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path + +import cv2 +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def draw_points(image: np.ndarray, points: np.ndarray, color: tuple[int, int, int], marker: bool) -> None: + for point in points: + if not np.isfinite(point).all(): + continue + xy = tuple(np.rint(point).astype(int)) + if marker: + cv2.drawMarker(image, xy, color, cv2.MARKER_CROSS, 8, 1) + else: + cv2.circle(image, xy, 3, color, -1) + + +def mean(values: list[float]) -> float | None: + return float(np.mean(values)) if values else None + + +def image_size_bucket(max_side_px: float) -> str: + if max_side_px < 64: + return "small_lt64px" + if max_side_px < 128: + return "medium_64_128px" + return "large_ge128px" + + +def depth_bucket(depth_m: float) -> str: + if depth_m < 0.5: + return "near_lt0.5m" + if depth_m < 0.8: + return "middle_0.5_0.8m" + return "far_ge0.8m" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--train-log", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args(); args.output_dir.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=args.max_clips, + oracle_crop_enabled=( + config["model"].get("oracle_crop_mode", "none") != "none" + ), + ) + loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_h2o_clips) + model_config = ModelConfig(**config["model"], dinov3_source=assets["dinov3_source"], dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"]) + device = torch.device(f"cuda:{args.gpu}") + model = BimanualReconstructionModel(model_config).to(device).eval() + load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + + values: dict[str, list[float]] = defaultdict(list) + loss_values: dict[str, list[float]] = defaultdict(list) + frame_rows: list[dict[str, object]] = [] + saved_overlays: list[Path] = [] + attention_same_peak = [] + attention_cosine = [] + depth_attention_same_peak = [] + temporal_attention_diagonal = [] + temporal_attention_entropy = [] + bimanual_cross_attention = [] + depth_gates = [] + raw_depth_gates = [] + rgb_update_norms = [] + depth_update_norms = [] + gated_depth_update_norms = [] + structured_diagnostics: dict[str, list[float]] = defaultdict(list) + visualization_index = 0 + saved_sequence_diagnostics = False + frame_count = 0 + bucket_values: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + + with torch.inference_mode(): + for batch in loader: + batch = {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + gt_vertices, _ = model.mano_layer( + axis_angle_to_matrix(pose), torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + mano_valid = (batch["mano_annotation_valid"].bool() & batch["frame_valid"].bool()[..., None])[..., None, None] + batch["vertices_camera"] = torch.where(mano_valid, gt_vertices, torch.full_like(gt_vertices, torch.nan)) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + for key, value in losses.items(): + loss_values[key].append(float(value)) + + frame_valid = batch["frame_valid"].bool() + frame_count += int(frame_valid.sum()) + ann = batch["joint_annotation_valid"].bool() & frame_valid[..., None] + joint_valid = batch["joint_element_valid"].bool() & ann[..., None] + target_joints = torch.nan_to_num(batch["joint3d_camera"]) + joint_error = torch.linalg.vector_norm(prediction["joints_camera"] - target_joints, dim=-1) * 1000 + pred_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + relative_error = torch.linalg.vector_norm(pred_relative - target_relative, dim=-1) * 1000 + translation_error = (prediction["wrist_root_translation"] - torch.nan_to_num(batch["wrist_root_translation"])).abs() * 1000 + height, width = map(int, batch["image_hw"][0].tolist()) + predicted_2d = prediction["joint2d_norm"] * torch.tensor((width, height), device=device) + target_2d = torch.nan_to_num(batch["joint2d"]) + error_2d = torch.linalg.vector_norm(predicted_2d - target_2d, dim=-1) + if "structured_translation_delta" in prediction: + valid_hands = frame_valid[..., None].expand(-1, -1, 2) + structured_diagnostics["translation_delta_norm_mm"].extend( + ( + torch.linalg.vector_norm( + prediction["structured_translation_delta"], dim=-1, + )[valid_hands] * 1000.0 + ).float().cpu().tolist() + ) + structured_diagnostics["rotation_delta_norm_deg"].extend( + ( + torch.linalg.vector_norm( + prediction["structured_rotation_delta_axis_angle"], dim=-1, + )[valid_hands[..., None].expand(-1, -1, -1, 16)] + * (180.0 / np.pi) + ).float().cpu().tolist() + ) + structured_diagnostics["shape_delta_abs"].extend( + prediction["structured_shape_delta"].abs().reshape(-1).float().cpu().tolist() + ) + pixel_scale = torch.tensor((width, height), device=device) + structured_diagnostics["joint2d_delta_px"].extend( + torch.linalg.vector_norm( + prediction["structured_joint2d_delta"] * pixel_scale, + dim=-1, + )[valid_hands[..., None].expand(-1, -1, -1, 21)].float().cpu().tolist() + ) + structured_diagnostics["sample_offset_norm_px"].extend( + torch.linalg.vector_norm( + prediction["structured_sample_offsets"] * pixel_scale, + dim=-1, + )[frame_valid[..., None, None, None].expand( + -1, -1, 2, 7, prediction["structured_sample_offsets"].shape[-2], + )].float().cpu().tolist() + ) + + if not saved_sequence_diagnostics: + subject = batch["subject_id"][0] + sequence = batch["sequence_id"][0] + title_prefix = f"{config['name']} | {subject}/{sequence}" + if "temporal_attention" in prediction["attention"]: + temporal_plot = prediction["attention"]["temporal_attention"][0, -1].float().cpu().numpy() + fig, axes = plt.subplots(1, 2, figsize=(9, 4)) + for hand, side in enumerate(("left", "right")): + axes[hand].imshow(temporal_plot[hand], vmin=0, vmax=max(float(temporal_plot.max()), 1e-8), cmap="viridis") + axes[hand].set_title(f"{side} temporal attention") + axes[hand].set_xlabel("key frame") + axes[hand].set_ylabel("query frame") + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_temporal_attention.png", dpi=160) + plt.close(fig) + valid_times = frame_valid[0].cpu().numpy() + time_axis = np.arange(int(valid_times.sum())) + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for hand, side in enumerate(("left", "right")): + hand_valid = ann[0, :, hand].cpu().numpy() & valid_times + pred_z = prediction["wrist_root_translation"][0, :, hand, 2].float().cpu().numpy()[valid_times] + gt_z = batch["wrist_root_translation"][0, :, hand, 2].float().cpu().numpy()[valid_times] + axes[0].plot(time_axis, pred_z, label=f"{side} pred") + axes[0].plot(time_axis[hand_valid[valid_times]], gt_z[hand_valid[valid_times]], "--", label=f"{side} GT") + per_frame = joint_error[0, :, hand].mean(-1).float().cpu().numpy()[valid_times] + axes[1].plot(time_axis[hand_valid[valid_times]], per_frame[hand_valid[valid_times]], label=side) + axes[0].set_title("Camera-space wrist z") + axes[0].set_ylabel("meters") + axes[1].set_title("Per-frame absolute MPJPE") + axes[1].set_ylabel("mm") + for axis in axes: + axis.set_xlabel("frame in clip") + axis.grid(alpha=0.25) + axis.legend() + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_translation_and_mpjpe.png", dpi=160) + plt.close(fig) + if "depth_fusion_gate" in prediction["attention"]: + gates = prediction["attention"]["depth_fusion_gate"][0, :, :, :, 0].float().cpu().numpy() + fig, axes = plt.subplots(1, 2, figsize=(10, 4)) + for hand, side in enumerate(("left", "right")): + for layer in range(gates.shape[0]): + axes[hand].plot(gates[layer, valid_times, hand], label=f"layer {layer}") + axes[hand].set_title(f"{side} depth gate") + axes[hand].set_xlabel("frame in clip") + axes[hand].set_ylim(0, 1) + axes[hand].grid(alpha=0.25) + axes[hand].legend() + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_depth_gate.png", dpi=160) + plt.close(fig) + saved_sequence_diagnostics = True + + for hand, side in enumerate(("left", "right")): + mask = joint_valid[..., hand, :] + values[f"{side}_absolute_mpjpe_mm"].extend(joint_error[..., hand, :][mask].float().cpu().tolist()) + values[f"{side}_root_relative_mpjpe_mm"].extend(relative_error[..., hand, :][mask].float().cpu().tolist()) + values[f"{side}_joint2d_error_px"].extend(error_2d[..., hand, :][mask].float().cpu().tolist()) + hand_mask = ann[..., hand] + for axis_index, axis in enumerate("xyz"): + values[f"{side}_translation_{axis}_mae_mm"].extend(translation_error[..., hand, axis_index][hand_mask].float().cpu().tolist()) + + rgb_attention = prediction["attention"]["rgb_cross_attention"][:, -1] + left_attention, right_attention = rgb_attention[..., 0, :], rgb_attention[..., 1, :] + valid_flat = frame_valid + attention_same_peak.extend((left_attention.argmax(-1) == right_attention.argmax(-1))[valid_flat].cpu().tolist()) + cosine = torch.nn.functional.cosine_similarity(left_attention, right_attention, dim=-1) + attention_cosine.extend(cosine[valid_flat].float().cpu().tolist()) + if "depth_fusion_gate" in prediction["attention"]: + depth_gates.extend(prediction["attention"]["depth_fusion_gate"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + raw_depth_gates.extend(prediction["attention"]["depth_fusion_gate_raw"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + depth_update_norms.extend(prediction["attention"]["depth_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + gated_depth_update_norms.extend(prediction["attention"]["gated_depth_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + depth_attention = prediction["attention"]["depth_cross_attention"][:, -1] + depth_attention_same_peak.extend( + (depth_attention[..., 0, :].argmax(-1) == depth_attention[..., 1, :].argmax(-1))[frame_valid].cpu().tolist() + ) + rgb_update_norms.extend(prediction["attention"]["rgb_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + + if "temporal_attention" in prediction["attention"]: + temporal = prediction["attention"]["temporal_attention"][:, -1] + for batch_index in range(temporal.shape[0]): + valid_indices = torch.where(frame_valid[batch_index])[0] + for hand_index in range(2): + for query_index in valid_indices: + weights = temporal[batch_index, hand_index, query_index, valid_indices].float() + weights = weights / weights.sum().clamp_min(1e-8) + temporal_attention_diagonal.append(float(temporal[batch_index, hand_index, query_index, query_index])) + if weights.numel() > 1: + entropy = -(weights * weights.clamp_min(1e-8).log()).sum() / np.log(weights.numel()) + temporal_attention_entropy.append(float(entropy)) + if "bimanual_attention" in prediction["attention"]: + bimanual = prediction["attention"]["bimanual_attention"][:, -1] + cross = 0.5 * (bimanual[..., 0, 1] + bimanual[..., 1, 0]) + bimanual_cross_attention.extend(cross[frame_valid].float().cpu().tolist()) + + if prediction["wrist_root_translation"].shape[1] > 1: + velocity_valid = ann[:, 1:] & ann[:, :-1] + predicted_velocity = prediction["wrist_root_translation"][:, 1:] - prediction["wrist_root_translation"][:, :-1] + target_velocity = torch.nan_to_num(batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1]) + velocity_error = torch.linalg.vector_norm(predicted_velocity - target_velocity, dim=-1) * 1000 + values["temporal_velocity_error_mm_per_frame"].extend(velocity_error[velocity_valid].float().cpu().tolist()) + if predicted_velocity.shape[1] > 1: + acceleration_valid = velocity_valid[:, 1:] & velocity_valid[:, :-1] + predicted_acceleration = predicted_velocity[:, 1:] - predicted_velocity[:, :-1] + target_acceleration = target_velocity[:, 1:] - target_velocity[:, :-1] + acceleration_error = torch.linalg.vector_norm(predicted_acceleration - target_acceleration, dim=-1) * 1000 + values["temporal_acceleration_error_mm_per_frame2"].extend( + acceleration_error[acceleration_valid].float().cpu().tolist() + ) + + for time_index in range(batch["rgb"].shape[1]): + if not frame_valid[0, time_index]: + continue + for hand, side in enumerate(("left", "right")): + is_valid = bool(ann[0, time_index, hand]) + annotation_state = "".join( + str(int(value)) for value in ann[0, time_index].int().cpu().tolist() + ) + max_side_px = None + wrist_depth_m = None + if is_valid: + points = batch["joint2d"][0, time_index, hand] + extent = points.max(dim=0).values - points.min(dim=0).values + max_side_px = float(extent.max()) + wrist_depth_m = float(batch["wrist_root_translation"][0, time_index, hand, 2]) + absolute_error = float(joint_error[0, time_index, hand].mean()) + root_error = float(relative_error[0, time_index, hand].mean()) + z_error = float(translation_error[0, time_index, hand, 2]) + for bucket in ( + f"image_size/{image_size_bucket(max_side_px)}", + f"wrist_depth/{depth_bucket(wrist_depth_m)}", + f"annotation_state/{annotation_state}", + ): + bucket_values[bucket]["absolute_mpjpe_mm"].append(absolute_error) + bucket_values[bucket]["root_relative_mpjpe_mm"].append(root_error) + bucket_values[bucket]["translation_z_mae_mm"].append(z_error) + frame_rows.append({ + "subject": batch["subject_id"][0], "sequence": batch["sequence_id"][0], + "frame_id": int(batch["frame_id"][0, time_index]), "side": side, + "annotation_valid": int(is_valid), + "annotation_state": annotation_state, + "hand_max_side_px": max_side_px, + "wrist_depth_m": wrist_depth_m, + "absolute_mpjpe_mm": float(joint_error[0, time_index, hand].mean()) if is_valid else None, + "root_relative_mpjpe_mm": float(relative_error[0, time_index, hand].mean()) if is_valid else None, + "joint2d_error_px": float(error_2d[0, time_index, hand].mean()) if is_valid else None, + **{f"pred_t_{axis}_m": float(prediction["wrist_root_translation"][0, time_index, hand, index]) for index, axis in enumerate("xyz")}, + **{f"gt_t_{axis}_m": float(batch["wrist_root_translation"][0, time_index, hand, index]) if is_valid else None for index, axis in enumerate("xyz")}, + }) + + if visualization_index < 16: + rgb = batch["rgb"][0, time_index].float().cpu().permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + for hand, color in enumerate(((50, 220, 50), (50, 80, 255))): + if ann[0, time_index, hand]: + draw_points(image, batch["joint2d"][0, time_index, hand].float().cpu().numpy(), (255, 255, 255), True) + draw_points(image, predicted_2d[0, time_index, hand].float().cpu().numpy(), color, False) + modalities = "RGB" + ("+Depth" if config["model"].get("use_depth") else "") + ("+K" if config["model"].get("use_rays") else "") + lines = ( + f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/{int(batch['frame_id'][0,time_index])} GT=x pred=dot", + f"config={config['name']} input={modalities}", + f"GT valid L={int(ann[0,time_index,0])} R={int(ann[0,time_index,1])} presence=unsupervised", + ) + cv2.rectangle(image, (0, 0), (width, 62), (0, 0, 0), -1) + for line_index, label in enumerate(lines): + cv2.putText(image, label, (6, 17 + 19 * line_index), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (255, 255, 255), 1) + overlay_path = args.output_dir / f"{visualization_index:02d}_prediction_overlay.jpg" + cv2.imwrite(str(overlay_path), image); saved_overlays.append(overlay_path) + grid_h, grid_w = height // 16, width // 16 + for hand, side in enumerate(("left", "right")): + heat = rgb_attention[0, time_index, hand].float().cpu().numpy().reshape(grid_h, grid_w) + heat = (heat - heat.min()) / max(float(heat.max() - heat.min()), 1e-8) + heat = cv2.resize(np.uint8(heat * 255), (width, height), interpolation=cv2.INTER_CUBIC) + heat = cv2.applyColorMap(heat, cv2.COLORMAP_TURBO) + cv2.imwrite(str(args.output_dir / f"{visualization_index:02d}_{side}_attention.jpg"), cv2.addWeighted(image, .55, heat, .45, 0)) + if "depth_cross_attention" in prediction["attention"]: + depth_attention = prediction["attention"]["depth_cross_attention"][:, -1] + depth_heat = depth_attention[0, time_index, hand].float().cpu().numpy().reshape(grid_h, grid_w) + depth_heat = (depth_heat - depth_heat.min()) / max(float(depth_heat.max() - depth_heat.min()), 1e-8) + depth_heat = cv2.resize(np.uint8(depth_heat * 255), (width, height), interpolation=cv2.INTER_CUBIC) + depth_heat = cv2.applyColorMap(depth_heat, cv2.COLORMAP_TURBO) + cv2.imwrite( + str(args.output_dir / f"{visualization_index:02d}_{side}_depth_attention.jpg"), + cv2.addWeighted(image, .55, depth_heat, .45, 0), + ) + visualization_index += 1 + + with (args.output_dir / "per_frame_metrics.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(frame_rows[0])); writer.writeheader(); writer.writerows(frame_rows) + + train_rows = [json.loads(line) for line in args.train_log.read_text(encoding="utf-8").splitlines() if line] + fig, axes = plt.subplots(1, 3, figsize=(15, 4)) + axes[0].plot([row["step"] for row in train_rows], [row["losses"]["total"] for row in train_rows]); axes[0].set_title("Total loss") + axes[1].plot([row["step"] for row in train_rows], [row["metrics"]["absolute_camera_mpjpe_mm"] for row in train_rows]); axes[1].set_title("Batch absolute MPJPE (mm)") + axes[2].plot([row["step"] for row in train_rows], [row["metrics"]["translation_z_mae_mm"] for row in train_rows]); axes[2].set_title("Batch z MAE (mm)") + for axis in axes: axis.set_xlabel("step"); axis.grid(alpha=.25) + fig.tight_layout(); fig.savefig(args.output_dir / "training_curves.png", dpi=160); plt.close(fig) + + metrics = {key: mean(item) for key, item in values.items()} + metrics.update({ + "all_absolute_mpjpe_mm": mean(values["left_absolute_mpjpe_mm"] + values["right_absolute_mpjpe_mm"]), + "all_root_relative_mpjpe_mm": mean(values["left_root_relative_mpjpe_mm"] + values["right_root_relative_mpjpe_mm"]), + "all_joint2d_error_px": mean(values["left_joint2d_error_px"] + values["right_joint2d_error_px"]), + "rgb_attention_same_peak_fraction": mean([float(value) for value in attention_same_peak]), + "rgb_attention_left_right_cosine": mean(attention_cosine), + "depth_attention_same_peak_fraction": mean([float(value) for value in depth_attention_same_peak]), + "temporal_attention_diagonal_mean": mean(temporal_attention_diagonal), + "temporal_attention_normalized_entropy": mean(temporal_attention_entropy), + "bimanual_cross_attention_mean": mean(bimanual_cross_attention), + "depth_gate_mean": mean(depth_gates), + "depth_gate_min": float(min(depth_gates)) if depth_gates else None, + "depth_gate_max": float(max(depth_gates)) if depth_gates else None, + "depth_gate_raw_mean": mean(raw_depth_gates), + "depth_gate_raw_min": float(min(raw_depth_gates)) if raw_depth_gates else None, + "depth_gate_raw_max": float(max(raw_depth_gates)) if raw_depth_gates else None, + "rgb_update_norm_mean": mean(rgb_update_norms), + "depth_update_norm_mean": mean(depth_update_norms), + "gated_depth_update_norm_mean": mean(gated_depth_update_norms), + }) + report = { + "status": "evaluated", "checkpoint": str(args.checkpoint.resolve()), + "split_role": "official_train_tiny_overfit" if "tiny" in args.manifest.name else "non_test_evaluation", + "official_test_used": False, + "clips": len(dataset), "frames": frame_count, + "metrics": metrics, "mean_weighted_losses": {key: mean(item) for key, item in loss_values.items()}, + "structured_residual_diagnostics": { + key: { + "mean": mean(items), + "p95": float(np.percentile(items, 95)) if items else None, + "maximum": float(max(items)) if items else None, + } + for key, items in sorted(structured_diagnostics.items()) + }, + "buckets": { + bucket: {"valid_hands": len(items["absolute_mpjpe_mm"]), **{key: mean(values) for key, values in items.items()}} + for bucket, items in sorted(bucket_values.items()) + }, + "occlusion_bucket": "UNAVAILABLE: H2O annotation_valid is not an occlusion or presence label.", + } + if "tiny" in args.manifest.name: + report["success_thresholds"] = {"absolute_mpjpe_mm": 15.0, "root_relative_mpjpe_mm": 8.0, "joint2d_error_px": 8.0} + report["tiny_overfit_passed"] = bool( + metrics["all_absolute_mpjpe_mm"] < 15 and metrics["all_root_relative_mpjpe_mm"] < 8 and metrics["all_joint2d_error_px"] < 8 + ) + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/extract_phase4_oracle_local_depth.py b/home/wuyifan/EgoNet_train_20261008/scripts/extract_phase4_oracle_local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd7ff0e89f1308c39a663fd8afde461e7acc2f5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/extract_phase4_oracle_local_depth.py @@ -0,0 +1,324 @@ +#!/usr/bin/env python3 +"""Extract frozen-model A1 oracle local-depth features without test access.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import tempfile +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.local_depth import oracle_local_depth_features +from foundation_hand.evaluation.phase4 import ( + action_name, + bimanual_asymmetry, + load_action_label, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +SIDES = ("left", "right") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_save_npz(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{path.name}.", suffix=".npz", dir=path.parent, + ) + os.close(descriptor) + temporary = Path(temporary_name) + try: + np.savez_compressed(temporary, **arrays) + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError("A1 extraction produced no valid hand rows") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--split-role", choices=("official_train", "official_validation"), required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--expected-manifest-sha256", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--max-clips", type=int) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if "test" in args.manifest.name.lower() or "test" in args.split_role: + raise ValueError("Phase 4 A1 explicitly prohibits official-test access") + output_npz = args.output_dir / "features.npz" + output_csv = args.output_dir / "samples.csv" + output_json = args.output_dir / "extraction.json" + if any(path.exists() for path in (output_npz, output_csv, output_json)): + raise FileExistsError(f"refusing to overwrite existing A1 extraction in {args.output_dir}") + + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + if checkpoint_hash != args.expected_checkpoint_sha256: + raise ValueError("checkpoint hash differs from the registered Phase 3 reference") + if manifest_hash != args.expected_manifest_sha256: + raise ValueError("manifest hash differs from the registered Phase 4 protected input") + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), + (int(data_config["stride"]),), + max_clips=args.max_clips, + ) + loader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint_state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + chunks: dict[str, list[np.ndarray]] = { + "control": [], + "local": [], + "coarse_translation_m": [], + "target_translation_m": [], + "coarse_joints_m": [], + "target_joints_m": [], + "direct_joints_2d_px": [], + "target_joints_2d_px": [], + "K_resized": [], + } + rows: list[dict[str, object]] = [] + raw_intrinsics: dict[str, np.ndarray] = {} + control_names: tuple[str, ...] | None = None + local_names: tuple[str, ...] | None = None + + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = move_to_device(batch_cpu, device) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + frame_valid = batch["frame_valid"][0].bool() + annotation_valid = batch["joint_annotation_valid"][0].bool() & frame_valid[:, None] + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"][0].float().cpu().numpy() + direct_2d *= np.asarray((width, height), dtype=np.float32) + coarse_translation = prediction["wrist_root_translation"][0].float().cpu().numpy() + coarse_joints = prediction["joints_camera"][0].float().cpu().numpy() + target_translation = batch["wrist_root_translation"][0].float().cpu().numpy() + target_joints = batch["joint3d_camera"][0].float().cpu().numpy() + target_2d_resized = batch["joint2d"][0].float().cpu().numpy() + + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + take_dir = args.root / take + if take not in raw_intrinsics: + K_raw, raw_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + raw_intrinsics[take] = K_raw + else: + K_raw = raw_intrinsics[take] + raw_hw = None + + for time_index in torch.where(frame_valid)[0].cpu().tolist(): + frame_id = int(batch["frame_id"][0, time_index]) + stem = f"{frame_id:06d}" + raw_depth_mm = cv2.imread( + str(take_dir / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED, + ) + if raw_depth_mm is None: + raise RuntimeError(f"cannot read raw depth {take_dir}/depth/{stem}.png") + if raw_hw is not None and raw_depth_mm.shape != raw_hw: + raise ValueError(f"raw depth/K size mismatch at {take}/{stem}") + raw_depth_m, raw_depth_valid = depth_mm_to_m(raw_depth_mm) + target_2d_raw, positive = project_points(target_joints[time_index], K_raw) + + frame_sizes: list[float | None] = [None, None] + frame_depths: list[float | None] = [None, None] + for hand in range(2): + if bool(annotation_valid[time_index, hand]): + extent = ( + target_2d_resized[time_index, hand].max(axis=0) + - target_2d_resized[time_index, hand].min(axis=0) + ) + frame_sizes[hand] = float(extent.max()) + frame_depths[hand] = float(target_translation[time_index, hand, 2]) + asymmetry = bimanual_asymmetry(frame_sizes, frame_depths) + label = load_action_label(args.root, take, frame_id) + + clip_features: dict[str, list[np.ndarray]] = {key: [] for key in chunks} + clip_rows: list[dict[str, object]] = [] + for hand, side in enumerate(SIDES): + if not bool(annotation_valid[time_index, hand]): + continue + if not bool(positive[hand].all()): + raise ValueError(f"valid GT hand projects behind camera at {take}/{stem}/{side}") + features = oracle_local_depth_features( + raw_depth_m, + raw_depth_valid, + target_2d_raw[hand], + K_raw, + coarse_translation[time_index, hand], + hand, + ) + if control_names is None: + control_names, local_names = features.control_names, features.local_names + elif features.control_names != control_names or features.local_names != local_names: + raise AssertionError("A1 feature schema changed within one extraction") + clip_features["control"].append(features.control) + clip_features["local"].append(features.local) + clip_features["coarse_translation_m"].append(coarse_translation[time_index, hand]) + clip_features["target_translation_m"].append(target_translation[time_index, hand]) + clip_features["coarse_joints_m"].append(coarse_joints[time_index, hand]) + clip_features["target_joints_m"].append(target_joints[time_index, hand]) + clip_features["direct_joints_2d_px"].append(direct_2d[time_index, hand]) + clip_features["target_joints_2d_px"].append(target_2d_resized[time_index, hand]) + clip_features["K_resized"].append( + batch["K"][0, time_index].float().cpu().numpy() + ) + clip_rows.append({ + "sample_index": len(rows) + len(clip_rows), + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "side": side, + "side_index": hand, + "action_family": str(batch["sequence_id"][0]).split("/", 1)[0], + "action_label": label, + "action_name": action_name(label), + "hand_size_px": frame_sizes[hand], + "wrist_depth_m": frame_depths[hand], + "bimanual_size_ratio": asymmetry["bimanual_size_ratio"], + "bimanual_depth_gap_m": asymmetry["bimanual_depth_gap_m"], + "bimanual_asymmetry_bucket": asymmetry["bimanual_asymmetry_bucket"], + "local_depth_valid_fraction": features.local_valid_fraction, + "local_depth_discontinuity_m": features.local_depth_discontinuity_m, + }) + if clip_rows: + for key, values in clip_features.items(): + chunks[key].append(np.stack(values).astype(np.float32)) + rows.extend(clip_rows) + + if (clip_index + 1) % 250 == 0: + print( + f"clips={clip_index + 1}/{len(dataset)} valid_hands={len(rows)}", + flush=True, + ) + + if control_names is None or local_names is None: + raise ValueError("A1 extraction found no annotation-valid hands") + arrays = {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + sample_count = len(rows) + if any(value.shape[0] != sample_count for value in arrays.values()): + raise AssertionError("A1 array and metadata row counts differ") + arrays["target_residual_z_m"] = ( + arrays["target_translation_m"][:, 2] - arrays["coarse_translation_m"][:, 2] + ).astype(np.float32) + if not all(np.isfinite(value).all() for value in arrays.values()): + raise ValueError("A1 extraction contains non-finite values") + + args.output_dir.mkdir(parents=True, exist_ok=True) + atomic_save_npz(output_npz, arrays) + write_csv(output_csv, rows) + report = { + "status": "extracted", + "phase": 4, + "wave": "A1_oracle_local_depth", + "split_role": args.split_role, + "official_test_used": False, + "oracle_contract": ( + "GT 2D joints locate multiscale regions in original aligned metric depth only; " + "GT wrist depth is a target and is never an input feature." + ), + "control_contract": ( + "The control receives the same oracle location, K, side and coarse translation " + "but no local depth or XYZ statistics." + ), + "config": str(args.config.resolve()), + "data_root": str(args.root.resolve()), + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": checkpoint_hash, + "step": int(checkpoint_state["step"]), + }, + "dataset_clips": len(dataset), + "valid_hand_samples": sample_count, + "control_dim": len(control_names), + "local_dim": len(local_names), + "control_feature_names": list(control_names), + "local_feature_names": list(local_names), + "precision": config["precision"], + "device": torch.cuda.get_device_name(device), + "outputs": { + "features": str(output_npz.resolve()), + "samples": str(output_csv.resolve()), + }, + } + output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": "complete", "samples": sample_count, "output": str(args.output_dir)})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_fold_milestone_recovery.py b/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_fold_milestone_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..146372c43331db29514bf7bbef1d96c7be0c0103 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_fold_milestone_recovery.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Validate recovered fold milestones and atomically complete canonical states.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.run_phase9_fold_milestone_eval import ( + atomic_json, + h2o_milestones, + milestone_checkpoint, + sha256, +) +from scripts.run_phase9_fold_shard import fold_evaluation_complete +from scripts.run_phase9_external_milestone_eval import stable_checkpoint_sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def expected_shard_evaluations( + registry: dict[str, Any], shard: int, output_root: Path, +) -> list[str]: + conditions = {item["condition"]: item for item in registry["conditions"]} + expected: list[str] = [] + for condition_id in registry["shards"][str(shard)]: + condition = conditions[condition_id] + config_path = Path(condition["config"]) + if sha256(config_path) != condition["config_sha256"]: + raise RuntimeError(f"fold config hash differs: {condition_id}") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + heldout = Path(config["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + run_dir = Path(condition["output_dir"]) + for milestone_id in h2o_milestones(config): + checkpoint = milestone_checkpoint(run_dir, milestone_id) + if checkpoint is None: + raise RuntimeError(f"missing checkpoint: {condition_id}:{milestone_id}") + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + evaluation_id = f"{condition_id}_{milestone_id}_{mode}" + output = output_root / condition_id / milestone_id / mode + if not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + raise RuntimeError(f"invalid recovered output: {evaluation_id}") + expected.append(evaluation_id) + return expected + + +def finalize(plan_path: Path) -> dict[str, Any]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + plan_hash = sha256(plan_path) + if plan.get("official_test_used") is not False: + raise RuntimeError("recovery plan must explicitly exclude official test") + registry_path = Path(plan["registry"]) + if sha256(registry_path) != plan["registry_sha256"]: + raise RuntimeError("registry SHA256 differs") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + worker_states: dict[str, str] = {} + recovered_ids: set[str] = set() + for worker in plan["workers"]: + state_path = Path(worker["state"]) + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or state.get("recovery_plan_sha256") != plan_hash + or state.get("recovery_worker_id") != worker["id"] + or set(state.get("assigned_evaluation_ids", [])) + != set(worker["evaluation_ids"]) + or not set(worker["evaluation_ids"]).issubset(state.get("completed_ids", [])) + ): + raise RuntimeError(f"incomplete recovery worker: {worker['id']}") + overlap = recovered_ids.intersection(worker["evaluation_ids"]) + if overlap: + raise RuntimeError(f"overlapping recovery IDs: {sorted(overlap)}") + recovered_ids.update(worker["evaluation_ids"]) + worker_states[worker["id"]] = sha256(state_path) + + completed_states: dict[str, Any] = {} + for shard_record in plan["canonical_states"]: + shard = int(shard_record["shard"]) + state_path = Path(shard_record["path"]) + if sha256(state_path) != shard_record["failed_state_sha256"]: + raise RuntimeError(f"canonical shard{shard} state changed during recovery") + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("registry_sha256") != plan["registry_sha256"] + or state.get("official_test_used") is not False + ): + raise RuntimeError(f"canonical shard{shard} binding differs") + expected = expected_shard_evaluations( + registry, shard, Path(plan["output_root"]), + ) + if len(expected) != 54 or len(set(expected)) != 54: + raise RuntimeError(f"shard{shard} expected evaluation count differs") + if not set(state.get("completed_ids", [])).union(recovered_ids).issuperset(expected): + raise RuntimeError(f"shard{shard} recovery coverage is incomplete") + state["recovered_failure"] = state.pop("failure", None) + state["status"] = "complete" + state["completed_ids"] = expected + state["allowed_physical_gpus"] = [0, 1, 2, 3, 4, 5] + state["resource_amendment"] = "gpu_4_5_evaluator_authorization_only_20260730" + state["recovery_plan"] = str(plan_path.resolve()) + state["recovery_plan_sha256"] = plan_hash + state["recovery_worker_state_sha256"] = worker_states + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state.pop("waiting_for", None) + atomic_json(state_path, state) + completed_states[str(shard)] = { + "path": str(state_path.resolve()), + "sha256": sha256(state_path), + "completed_ids": len(expected), + } + return { + "schema_version": "phase9_fold_milestone_recovery_merge_v1", + "status": "complete", + "recovery_plan": str(plan_path.resolve()), + "recovery_plan_sha256": plan_hash, + "canonical_states": completed_states, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + result = finalize(args.plan) + args.report.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.report, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_last2.py b/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_last2.py new file mode 100644 index 0000000000000000000000000000000000000000..a32e407fc52390193f3f562b6d9ab92d00625032 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_last2.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Freeze the ordered Stage 9 decision after both candidate controllers finish.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +import time +from typing import Any + +from scripts.phase9_distributed_assignment import detect_machine, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if detect_machine(assignment, None) != "taku3": + raise ValueError("last-2 finalizer is owned only by Taku3") + if ( + plan.get("schema_version") != "phase9_last2_finalizer_plan_v1" + or plan.get("candidate_order") != ["5e7", "1e6"] + or plan.get("selection_rule") + != "retain_preceding_then_5e7_then_1e6_only_on_each_strict_gate" + or plan.get("dino_large_admitted") is not False + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("last-2 finalizer contract differs") + for candidate in plan["candidate_order"]: + spec = plan["candidates"][candidate] + plan_path = Path(spec["plan"]) + if not plan_path.is_file() or sha256(plan_path) != spec["plan_sha256"]: + raise ValueError(f"last-2 {candidate} plan binding differs") + controller_plan = read_json(plan_path) + if ( + controller_plan.get("candidate") != candidate + or Path(controller_plan["controller_state"]).resolve() + != Path(spec["state"]).resolve() + or Path(controller_plan["decision_report"]).resolve() + != Path(spec["report"]).resolve() + ): + raise ValueError(f"last-2 {candidate} paths differ") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"last-2 finalizer binding differs: {path}") + + +def candidate_result( + candidate: str, spec: dict[str, Any], +) -> tuple[str, dict[str, Any] | None, dict[str, Any] | None]: + state_path = Path(spec["state"]) + if not state_path.is_file(): + return "waiting", None, None + state = read_json(state_path) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed"): + return "failed", state, None + return "waiting", state, None + if ( + state.get("candidate") != candidate + or state.get("plan_sha256") != spec["plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + return "failed", state, None + report_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + not report_path.is_file() + or report_path.resolve() != Path(spec["report"]).resolve() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + ): + return "failed", state, None + report = read_json(report_path) + accepted = report.get("gate", {}).get("accepted") + if ( + report.get("schema_version") != "phase9_last2_candidate_decision_v1" + or report.get("status") != "complete" + or report.get("candidate") != candidate + or accepted not in {True, False} + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + return "failed", state, report + if accepted and ( + report.get("gate", {}).get("macro_strictly_improved") is not True + or report.get("gate", {}).get("worst_domain_strictly_improved") is not True + or state.get("admitted") is not True + ): + return "failed", state, report + return "complete", state, report + + +def build_final_report( + plan: dict[str, Any], results: dict[str, tuple[dict[str, Any], dict[str, Any]]], + *, created_utc: str | None = None, +) -> dict[str, Any]: + five_state, five = results["5e7"] + one_state, one = results["1e6"] + if one["gate"]["accepted"] and not five["gate"]["accepted"]: + raise ValueError("1e-6 cannot be accepted after a rejected 5e-7 candidate") + if one["gate"]["accepted"]: + selected = "last2_1e6" + selected_report = one + elif five["gate"]["accepted"]: + selected = "last2_5e7" + selected_report = five + else: + selected = "preceding_mechanism" + selected_report = None + reports = {} + for candidate, (state, report) in results.items(): + path = Path(plan["candidates"][candidate]["report"]) + reports[candidate] = { + "path": str(path.resolve()), + "sha256": sha256(path), + "admitted": state.get("admitted") is True, + "accepted": report["gate"]["accepted"], + "decision": report["decision"], + "candidate_training_gpu_hours": float( + report.get("candidate_training_gpu_hours", 0.0) + ), + } + total_gpu_hours = sum( + item["candidate_training_gpu_hours"] for item in reports.values() + ) + return { + "schema_version": "phase9_last2_final_decision_v1", + "status": "complete", + "created_utc": created_utc or utc_now(), + "candidate_order": list(plan["candidate_order"]), + "selection_rule": plan["selection_rule"], + "selected": selected, + "last2_accepted": selected_report is not None, + "selected_candidate_report": ( + reports["1e6"] if selected == "last2_1e6" + else reports["5e7"] if selected == "last2_5e7" + else None + ), + "selected_candidate_training_jobs": ( + selected_report.get("candidate_training_jobs") + if selected_report is not None else None + ), + "candidate_reports": reports, + "total_candidate_training_gpu_hours": total_gpu_hours, + "rejection_disclosure": { + candidate: report.get("not_admitted_reason") + or report.get("gate", {}).get("rejection_reason") + for candidate, (_, report) in results.items() + if report["gate"]["accepted"] is False + }, + "dino_large_admitted": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("last-2 finalizer state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_last2_finalizer_state_v1", + "status": "waiting_for_candidate_controllers", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing last-2 finalizer state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + statuses = {} + ready = {} + failed = None + for candidate in plan["candidate_order"]: + status, candidate_state, report = candidate_result( + candidate, plan["candidates"][candidate], + ) + statuses[candidate] = status + if status == "failed": + failed = candidate + elif status == "complete": + assert candidate_state is not None and report is not None + ready[candidate] = (candidate_state, report) + state["candidate_statuses"] = statuses + state["updated_utc"] = utc_now() + if failed is not None: + state["status"] = "failed_candidate_binding" + state["failure_candidate"] = failed + atomic_json(args.state, state) + raise SystemExit(1) + if len(ready) == len(plan["candidate_order"]): + break + state["status"] = "waiting_for_candidate_controllers" + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + report_path = Path(plan["report"]) + report_path.parent.mkdir(parents=True, exist_ok=True) + state.setdefault("decision_created_utc", utc_now()) + state["status"] = "publishing_decision" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + report = build_final_report( + plan, ready, created_utc=state["decision_created_utc"], + ) + if report_path.exists(): + if read_json(report_path) != report: + state["status"] = "failed_existing_report_differs" + atomic_json(args.state, state) + raise SystemExit(1) + else: + atomic_json(report_path, report) + state["status"] = "complete" + state["decision"] = report["selected"] + state["decision_report"] = { + "path": str(report_path.resolve()), "sha256": sha256(report_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_resolution_cache.py b/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e6d32a6109f73a7c0dc2b0fdefe9cb8fa15bc6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_resolution_cache.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Finalize Phase 9 resolution caches after every source worker completes.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +import time +from typing import Any + +from scripts.audit_phase9_resolution_cache import audit +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + sha256, + validate_plan_bindings, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_admission(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + path = Path(plan["admission_state"]) + if not path.is_file(): + raise ValueError("resolution admission state is missing") + state = json.loads(path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution admission state differs") + return state + + +def inspect_workers( + plan_path: Path, plan: dict[str, Any], admission: dict[str, Any] +) -> tuple[str, list[dict[str, Any]]]: + records = [] + overall = "complete" + for worker in plan["workers"]: + path = Path(worker["state"]) + if not path.is_file(): + overall = "waiting_for_workers" + records.append({"worker": worker["id"], "status": "missing"}) + continue + state = json.loads(path.read_text(encoding="utf-8")) + status = state.get("status") + if str(status).startswith("failed"): + overall = "failed_dependency" + elif status != "complete" and overall != "failed_dependency": + overall = "waiting_for_workers" + if ( + state.get("worker") != worker["id"] + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution worker state differs: {worker['id']}") + if status == "complete" and ( + state.get("winner") != admission.get("winner") + or state.get("winner_checkpoint") != admission.get("winner_checkpoint") + or state.get("winner_config") != admission.get("winner_config") + or state.get("admission_state_sha256") != sha256(plan["admission_state"]) + ): + raise ValueError(f"resolution worker winner binding differs: {worker['id']}") + records.append({ + "worker": worker["id"], + "status": status, + "state": str(path.resolve()), + "state_sha256": sha256(path), + }) + return overall, records + + +def validate_existing_completion( + plan_path: Path, plan: dict[str, Any], state: dict[str, Any] +) -> bool: + audit_path = Path(plan["audit_output"]) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == sha256(plan_path) + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and audit_path.is_file() + and state.get("audit", {}).get("sha256") == sha256(audit_path) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan_bindings(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["readiness_state"]).resolve(): + parser.error("readiness state path differs from plan") + + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.state.is_file(): + existing = json.loads(args.state.read_text(encoding="utf-8")) + if validate_existing_completion(args.plan, plan, existing): + print(json.dumps(existing, indent=2)) + return + if existing.get("plan_sha256") not in (None, sha256(args.plan)): + parser.error("existing readiness state belongs to another plan") + + state: dict[str, Any] = { + "schema_version": "phase9_resolution_cache_readiness_v1", + "status": "waiting_for_admission", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, + "official_test_used": False, + } + while True: + try: + admission = validate_admission(args.plan, plan) + worker_status, workers = inspect_workers(args.plan, plan, admission) + except ValueError as error: + if "admission state is missing" in str(error): + state["status"] = "waiting_for_admission" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_validation" + state["failure"] = str(error) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + state["workers"] = workers + state["status"] = worker_status + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if worker_status == "failed_dependency": + raise SystemExit(1) + if worker_status != "complete": + time.sleep(args.poll_seconds) + continue + break + + audit_path = Path(plan["audit_output"]) + if audit_path.exists(): + existing_audit = json.loads(audit_path.read_text(encoding="utf-8")) + if ( + existing_audit.get("status") != "complete" + or existing_audit.get("plan_sha256") != sha256(args.plan) + or existing_audit.get("official_test_used") is not False + or existing_audit.get("h2o_official_validation_used") is not False + ): + state["status"] = "failed_existing_audit" + atomic_json(args.state, state) + raise SystemExit(1) + else: + state["status"] = "auditing" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + try: + result = audit(plan) + except Exception as error: + state["status"] = "failed_audit" + state["failure"] = f"{type(error).__name__}: {error}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise + result.update({ + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "admission_state": str(Path(plan["admission_state"]).resolve()), + "admission_state_sha256": sha256(plan["admission_state"]), + "winner": admission["winner"], + "winner_checkpoint": admission["winner_checkpoint"], + "winner_config": admission["winner_config"], + "worker_states": workers, + }) + audit_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(audit_path, result) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["admission_state_sha256"] = sha256(plan["admission_state"]) + state["winner"] = admission["winner"] + state["winner_checkpoint"] = admission["winner_checkpoint"] + state["winner_config"] = admission["winner_config"] + state["audit"] = { + "path": str(audit_path.resolve()), + "sha256": sha256(audit_path), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_selection_binding_recovery.py b/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d8d4a11430f20985ff8c87f96eb749783db882 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/finalize_phase9_selection_binding_recovery.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Publish one host's complete selection recovery as an immutable release.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +from typing import Any + +from scripts.run_phase9_selection_binding_recovery import ( + atomic_json, + validate_recovered_output, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def release_root(plan: dict[str, Any], owner: str) -> Path: + assignment = json.loads( + Path(plan["distributed_assignment"]["path"]).read_text(encoding="utf-8") + ) + return Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + + +def build_release( + *, plan_path: Path, owner: str, output: Path, +) -> dict[str, Any]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + plan_hash = sha256(plan_path) + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"selection recovery code binding differs: {path}") + root = release_root(plan, owner).resolve() + if output.parent.resolve() != root: + raise ValueError("selection recovery release must live at its frozen root") + owner_workers = [item for item in plan["workers"] if item["owner"] == owner] + owner_evaluations = [ + item for item in plan["evaluations"] if item["owner"] == owner + ] + expected_ids = {item["id"] for item in owner_evaluations} + completed_ids: set[str] = set() + worker_states = [] + for worker in owner_workers: + state_path = Path(worker["state"]) + if not state_path.is_file(): + raise ValueError(f"selection recovery worker state missing: {worker['id']}") + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("owner") != owner + or state.get("plan_sha256") != plan_hash + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or set(state.get("completed_ids", [])) + != set(worker["evaluation_ids"]) + ): + raise ValueError( + f"selection recovery worker state differs: {worker['id']}" + ) + completed_ids.update(state["completed_ids"]) + worker_states.append({ + "id": worker["id"], "path": str(state_path.resolve()), + "sha256": sha256(state_path), + }) + if completed_ids != expected_ids: + raise ValueError("selection recovery completed IDs differ") + evaluation_evidence = [] + files = [] + seen_relative_paths: set[str] = set() + for item in owner_evaluations: + evidence = validate_recovered_output(item) + directory = Path(item["output_dir"]).resolve() + try: + relative_output = directory.relative_to(root) + except ValueError as error: + raise ValueError("recovery output is outside owner root") from error + for path in sorted(directory.rglob("*")): + if path.is_symlink() or not path.is_file(): + if path.is_symlink(): + raise ValueError(f"recovery release refuses symlink: {path}") + continue + relative = str(path.resolve().relative_to(root)) + if relative in seen_relative_paths: + raise ValueError(f"duplicate recovery release path: {relative}") + seen_relative_paths.add(relative) + files.append({ + "path": relative, "sha256": sha256(path), + "bytes": path.stat().st_size, + }) + evaluation_evidence.append({ + "id": item["id"], "output_dir": str(relative_output), **evidence, + }) + return { + "schema_version": "phase9_selection_binding_recovery_release_v1", + "status": "complete_immutable_release", + "created_utc": datetime.now(timezone.utc).isoformat(), + "owner": owner, + "plan": {"path": str(plan_path.resolve()), "sha256": plan_hash}, + "distributed_assignment": plan["distributed_assignment"], + "root": str(root), + "worker_states": worker_states, + "evaluation_ids": sorted(expected_ids), + "evaluations": evaluation_evidence, + "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "read_only_after_publish": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--owner", choices=("taku3", "server_new"), required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = build_release(plan_path=args.plan, owner=args.owner, output=args.output) + if args.output.exists(): + existing = json.loads(args.output.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("owner") == args.owner + and existing.get("plan", {}).get("sha256") + == result["plan"]["sha256"] + and existing.get("files") == result["files"] + and existing.get("evaluations") == result["evaluations"] + ): + print(json.dumps(existing, indent=2)) + return + parser.error("existing recovery release differs") + atomic_json(args.output, result) + for item in result["files"]: + os.chmod(Path(result["root"]) / item["path"], 0o444) + os.chmod(args.output, 0o444) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase4_oracle_local_depth.py b/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase4_oracle_local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..61cdc0efdd02dd690411a6cae7f8faf78c60a242 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase4_oracle_local_depth.py @@ -0,0 +1,605 @@ +#!/usr/bin/env python3 +"""Fit and evaluate the Phase 4 A1 bounded oracle wrist-z diagnostic.""" + +from __future__ import annotations + +import argparse +import copy +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.nn.functional as F + +from foundation_hand.evaluation.local_depth import BoundedZResidualRegressor +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import project_points + + +FINGERTIPS = (4, 8, 12, 16, 20) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV {path}") + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def stable_take_holdout(takes: list[str], modulus: int = 5) -> np.ndarray: + """Select a deterministic official-train-only holdout by complete take.""" + + if modulus < 2: + raise ValueError("holdout modulus must be at least two") + output = [] + for take in takes: + digest = hashlib.sha256(take.encode("utf-8")).digest() + output.append(int.from_bytes(digest[:8], "little") % modulus == 0) + return np.asarray(output, dtype=bool) + + +def padded_control(control: np.ndarray, local_dim: int) -> np.ndarray: + if control.ndim != 2 or control.shape[1] > local_dim: + raise ValueError("invalid control/local feature dimensions") + output = np.zeros((control.shape[0], local_dim), dtype=np.float32) + output[:, : control.shape[1]] = control + return output + + +def standardizer(features: np.ndarray, fit_mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + values = features[fit_mask].astype(np.float64) + mean = values.mean(axis=0).astype(np.float32) + std = values.std(axis=0).astype(np.float32) + std[std < 1e-6] = 1.0 + return mean, std + + +def fit_regressor( + features: np.ndarray, + target_m: np.ndarray, + train_mask: np.ndarray, + holdout_mask: np.ndarray, + *, + device: torch.device, + seed: int, + hidden_dim: int, + max_residual_m: float, + learning_rate: float, + weight_decay: float, + batch_size: int, + epochs: int, + patience: int, +) -> tuple[BoundedZResidualRegressor, np.ndarray, np.ndarray, list[dict[str, float | int]]]: + mean, std = standardizer(features, train_mask) + normalized = (features.astype(np.float32) - mean) / std + x = torch.from_numpy(normalized).to(device) + target = torch.from_numpy(target_m.astype(np.float32)).to(device) + train_indices = torch.from_numpy(np.where(train_mask)[0]).to(device) + holdout_indices = torch.from_numpy(np.where(holdout_mask)[0]).to(device) + if not train_indices.numel() or not holdout_indices.numel(): + raise ValueError("official-train fit/holdout split is empty") + + torch.manual_seed(seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(seed) + model = BoundedZResidualRegressor( + features.shape[1], hidden_dim=hidden_dim, max_residual_m=max_residual_m, + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=learning_rate, weight_decay=weight_decay, + ) + generator = torch.Generator(device=device).manual_seed(seed) + best_state = copy.deepcopy(model.state_dict()) + best_holdout = float("inf") + stale = 0 + history: list[dict[str, float | int]] = [] + for epoch in range(1, epochs + 1): + model.train() + shuffled = train_indices[torch.randperm(train_indices.numel(), generator=generator, device=device)] + losses = [] + for start in range(0, shuffled.numel(), batch_size): + indices = shuffled[start : start + batch_size] + optimizer.zero_grad(set_to_none=True) + prediction = model(x[indices]) + loss = F.smooth_l1_loss(prediction, target[indices], beta=0.01) + if not torch.isfinite(loss): + raise FloatingPointError("non-finite A1 training loss") + loss.backward() + optimizer.step() + losses.append(float(loss.detach())) + model.eval() + with torch.inference_mode(): + holdout_prediction = model(x[holdout_indices]) + holdout_mae = float((holdout_prediction - target[holdout_indices]).abs().mean()) + history.append({ + "epoch": epoch, + "train_smooth_l1": float(np.mean(losses)), + "holdout_residual_mae_m": holdout_mae, + }) + if holdout_mae < best_holdout - 1e-6: + best_holdout = holdout_mae + best_state = copy.deepcopy(model.state_dict()) + stale = 0 + else: + stale += 1 + if stale >= patience: + break + model.load_state_dict(best_state) + return model, mean, std, history + + +def infer_residual( + model: BoundedZResidualRegressor, + features: np.ndarray, + mean: np.ndarray, + std: np.ndarray, + device: torch.device, + batch_size: int = 8192, +) -> np.ndarray: + model.eval() + output = [] + with torch.inference_mode(): + for start in range(0, features.shape[0], batch_size): + values = (features[start : start + batch_size].astype(np.float32) - mean) / std + output.append(model(torch.from_numpy(values).to(device)).cpu().numpy()) + result = np.concatenate(output).astype(np.float32) + if not np.isfinite(result).all(): + raise FloatingPointError("A1 residual inference produced non-finite values") + return result + + +def variant_metrics( + arrays: dict[str, np.ndarray], residual_m: np.ndarray, +) -> dict[str, np.ndarray]: + coarse_translation = arrays["coarse_translation_m"] + target_translation = arrays["target_translation_m"] + coarse_joints = arrays["coarse_joints_m"] + target_joints = arrays["target_joints_m"] + refined_translation = coarse_translation.copy() + refined_translation[:, 2] += residual_m + refined_joints = coarse_joints.copy() + refined_joints[:, :, 2] += residual_m[:, None] + joint_error = np.linalg.norm(refined_joints - target_joints, axis=-1) * 1000.0 + relative_prediction = refined_joints - refined_joints[:, :1] + relative_target = target_joints - target_joints[:, :1] + relative_error = np.linalg.norm(relative_prediction - relative_target, axis=-1) * 1000.0 + translation_error = (refined_translation - target_translation) * 1000.0 + projected, positive = project_points(refined_joints, arrays["K_resized"]) + if not bool(positive.all()): + raise ValueError("A1 refined MANO joints project behind the camera") + target_2d = arrays["target_joints_2d_px"] + direct_2d = arrays["direct_joints_2d_px"] + return { + "absolute_mpjpe_mm": joint_error.mean(axis=1), + "root_relative_mpjpe_mm": relative_error.mean(axis=1), + "fingertip_mpjpe_mm": joint_error[:, FINGERTIPS].mean(axis=1), + "translation_z_signed_error_mm": translation_error[:, 2], + "translation_z_mae_mm": np.abs(translation_error[:, 2]), + "direct_2d_error_px": np.linalg.norm(direct_2d - target_2d, axis=-1).mean(axis=1), + "mano_projected_2d_error_px": np.linalg.norm(projected - target_2d, axis=-1).mean(axis=1), + "direct_mano_consistency_px": np.linalg.norm(direct_2d - projected, axis=-1).mean(axis=1), + "residual_magnitude_mm": np.abs(residual_m) * 1000.0, + "predicted_wrist_xyz_m": refined_translation, + "predicted_joints_m": refined_joints, + } + + +def temporal_metrics( + metadata: list[dict[str, str]], + target_translation: np.ndarray, + predictions: dict[str, dict[str, np.ndarray]], +) -> dict[str, dict[str, np.ndarray]]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(metadata): + groups[(row["take"], row["side"])].append(index) + output = { + variant: { + "wrist_velocity_error_mm_per_frame": [], + "wrist_acceleration_error_mm_per_frame2": [], + } + for variant in predictions + } + for indices in groups.values(): + ordered = sorted(indices, key=lambda index: int(metadata[index]["frame_id"])) + for position in range(1, len(ordered)): + previous, current = ordered[position - 1], ordered[position] + if int(metadata[current]["frame_id"]) != int(metadata[previous]["frame_id"]) + 1: + continue + target_velocity = target_translation[current] - target_translation[previous] + for variant, metrics in predictions.items(): + wrist = metrics["predicted_wrist_xyz_m"] + error = np.linalg.norm((wrist[current] - wrist[previous]) - target_velocity) * 1000.0 + output[variant]["wrist_velocity_error_mm_per_frame"].append(float(error)) + for position in range(2, len(ordered)): + first, second, third = ordered[position - 2 : position + 1] + frame_ids = [int(metadata[index]["frame_id"]) for index in (first, second, third)] + if frame_ids[1] != frame_ids[0] + 1 or frame_ids[2] != frame_ids[1] + 1: + continue + target_acceleration = target_translation[third] - 2 * target_translation[second] + target_translation[first] + for variant, metrics in predictions.items(): + wrist = metrics["predicted_wrist_xyz_m"] + acceleration = wrist[third] - 2 * wrist[second] + wrist[first] + error = np.linalg.norm(acceleration - target_acceleration) * 1000.0 + output[variant]["wrist_acceleration_error_mm_per_frame2"].append(float(error)) + return { + variant: {metric: np.asarray(values, dtype=np.float32) for metric, values in metrics.items()} + for variant, metrics in output.items() + } + + +def summarize_groups( + metadata: list[dict[str, str]], + variants: dict[str, dict[str, np.ndarray]], + temporal: dict[str, dict[str, np.ndarray]], + challenge: dict[str, Any], +) -> list[dict[str, object]]: + farthest = float(challenge["thresholds"]["farthest_observed_wrist_depth_p80_m"]) + challenge_clips = set(int(value) for value in challenge["clip_indices"]) + masks = { + "all": np.ones(len(metadata), dtype=bool), + "left": np.asarray([row["side"] == "left" for row in metadata]), + "right": np.asarray([row["side"] == "right" for row in metadata]), + "small": np.asarray([float(row["hand_size_px"]) < 64.0 for row in metadata]), + "farthest_observed": np.asarray([ + float(row["wrist_depth_m"]) >= farthest for row in metadata + ]), + "strong_asymmetry": np.asarray([ + row["bimanual_asymmetry_bucket"] == "strong" for row in metadata + ]), + "challenge": np.asarray([int(row["clip_index"]) in challenge_clips for row in metadata]), + } + rows: list[dict[str, object]] = [] + scalar_metrics = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", + ) + for group, mask in masks.items(): + for variant, metrics in variants.items(): + for metric in scalar_metrics: + rows.append({ + "group": group, + "variant": variant, + "metric": metric, + **distribution_summary(metrics[metric][mask]), + }) + for variant, metrics in temporal.items(): + for metric, values in metrics.items(): + rows.append({ + "group": "all_contiguous_transitions", + "variant": variant, + "metric": metric, + **distribution_summary(values), + }) + return rows + + +def paired_take_bootstrap( + metadata: list[dict[str, str]], + variants: dict[str, dict[str, np.ndarray]], + *, + seed: int, + samples: int, +) -> list[dict[str, object]]: + take_indices: dict[str, list[int]] = defaultdict(list) + for index, row in enumerate(metadata): + take_indices[row["take"]].append(index) + rng = np.random.default_rng(seed) + rows: list[dict[str, object]] = [] + comparisons = (("local", "coarse"), ("local", "control"), ("control", "coarse")) + metric_stats = ( + ("absolute_mpjpe_mm", "mean"), + ("translation_z_mae_mm", "mean"), + ("translation_z_mae_mm", "p95"), + ("fingertip_mpjpe_mm", "mean"), + ("mano_projected_2d_error_px", "mean"), + ) + take_names = sorted(take_indices) + for candidate, reference in comparisons: + for metric, statistic in metric_stats: + deltas = [] + for take in take_names: + indices = take_indices[take] + candidate_values = variants[candidate][metric][indices] + reference_values = variants[reference][metric][indices] + if statistic == "mean": + delta = float(candidate_values.mean() - reference_values.mean()) + else: + delta = float(np.percentile(candidate_values, 95) - np.percentile(reference_values, 95)) + deltas.append(delta) + deltas_array = np.asarray(deltas, dtype=np.float64) + bootstrap_indices = rng.integers(0, len(deltas_array), size=(samples, len(deltas_array))) + distribution = deltas_array[bootstrap_indices].mean(axis=1) + rows.append({ + "candidate": candidate, + "reference": reference, + "metric": metric, + "per_take_statistic": statistic, + "take_count": len(deltas_array), + "paired_delta_candidate_minus_reference": float(deltas_array.mean()), + "ci95_low": float(np.percentile(distribution, 2.5)), + "ci95_high": float(np.percentile(distribution, 97.5)), + "bootstrap_samples": samples, + "bootstrap_seed": seed, + }) + return rows + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--train-extraction", type=Path, required=True) + parser.add_argument("--validation-extraction", type=Path, required=True) + parser.add_argument("--challenge-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--fit-seed", type=int, default=4401) + parser.add_argument("--holdout-modulus", type=int, default=5) + parser.add_argument("--hidden-dim", type=int, default=128) + parser.add_argument("--max-residual-m", type=float, default=0.15) + parser.add_argument("--learning-rate", type=float, default=3e-3) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--batch-size", type=int, default=4096) + parser.add_argument("--epochs", type=int, default=80) + parser.add_argument("--patience", type=int, default=12) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + return parser.parse_args() + + +def load_extraction(path: Path) -> tuple[dict[str, np.ndarray], list[dict[str, str]], dict[str, Any]]: + report = json.loads((path / "extraction.json").read_text(encoding="utf-8")) + if report.get("official_test_used") is not False: + raise ValueError("A1 extraction does not explicitly preserve official-test isolation") + arrays = dict(np.load(path / "features.npz")) + rows = read_csv(path / "samples.csv") + if any(value.shape[0] != len(rows) for value in arrays.values()): + raise ValueError(f"array/CSV length mismatch in {path}") + return arrays, rows, report + + +def main() -> None: + args = parse_args() + output_files = ( + args.output_dir / "results.json", + args.output_dir / "group_metrics.csv", + args.output_dir / "validation_predictions.csv", + args.output_dir / "paired_take_bootstrap_ci.csv", + args.output_dir / "regressors.pt", + ) + if any(path.exists() for path in output_files): + raise FileExistsError(f"refusing to overwrite existing A1 result in {args.output_dir}") + train, train_rows, train_report = load_extraction(args.train_extraction) + validation, validation_rows, validation_report = load_extraction(args.validation_extraction) + if train_report["split_role"] != "official_train": + raise ValueError("A1 fitting requires official_train extraction") + if validation_report["split_role"] != "official_validation": + raise ValueError("A1 reporting requires official_validation extraction") + if train_report["checkpoint"]["sha256"] != validation_report["checkpoint"]["sha256"]: + raise ValueError("train/validation A1 extractions use different frozen checkpoints") + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + if challenge.get("checkpoint_selection_allowed") is not False: + raise ValueError("challenge subset is not registered as secondary-only") + + holdout_mask = stable_take_holdout( + [row["take"] for row in train_rows], modulus=args.holdout_modulus, + ) + train_mask = ~holdout_mask + local_dim = train["local"].shape[1] + train_features = { + "control": padded_control(train["control"], local_dim), + "local": train["local"], + } + validation_features = { + "control": padded_control(validation["control"], local_dim), + "local": validation["local"], + } + device = torch.device(f"cuda:{args.gpu}") + regressors: dict[str, BoundedZResidualRegressor] = {} + scalers: dict[str, tuple[np.ndarray, np.ndarray]] = {} + histories: dict[str, list[dict[str, float | int]]] = {} + for index, variant in enumerate(("control", "local")): + model, mean, std, history = fit_regressor( + train_features[variant], + train["target_residual_z_m"], + train_mask, + holdout_mask, + device=device, + seed=args.fit_seed + index, + hidden_dim=args.hidden_dim, + max_residual_m=args.max_residual_m, + learning_rate=args.learning_rate, + weight_decay=args.weight_decay, + batch_size=args.batch_size, + epochs=args.epochs, + patience=args.patience, + ) + regressors[variant] = model + scalers[variant] = (mean, std) + histories[variant] = history + + residuals = {"coarse": np.zeros(len(validation_rows), dtype=np.float32)} + for variant in ("control", "local"): + mean, std = scalers[variant] + residuals[variant] = infer_residual( + regressors[variant], validation_features[variant], mean, std, device, + ) + variants = { + variant: variant_metrics(validation, residual) + for variant, residual in residuals.items() + } + coarse_root = variants["coarse"]["root_relative_mpjpe_mm"] + coarse_direct = variants["coarse"]["direct_2d_error_px"] + for variant in ("control", "local"): + if not np.allclose(variants[variant]["root_relative_mpjpe_mm"], coarse_root, atol=1e-4): + raise AssertionError("uniform A1 z residual changed root-relative geometry") + if not np.array_equal(variants[variant]["direct_2d_error_px"], coarse_direct): + raise AssertionError("A1 residual changed the frozen direct-2D head") + + temporal = temporal_metrics( + validation_rows, validation["target_translation_m"], variants, + ) + group_rows = summarize_groups(validation_rows, variants, temporal, challenge) + bootstrap_rows = paired_take_bootstrap( + validation_rows, + variants, + seed=args.fit_seed, + samples=args.bootstrap_samples, + ) + prediction_rows: list[dict[str, object]] = [] + for index, metadata in enumerate(validation_rows): + row: dict[str, object] = dict(metadata) + for variant, metrics in variants.items(): + for metric in ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", + ): + row[f"{variant}_{metric}"] = float(metrics[metric][index]) + prediction_rows.append(row) + + def summary_value(group: str, variant: str, metric: str, statistic: str) -> float: + match = next( + row for row in group_rows + if row["group"] == group and row["variant"] == variant and row["metric"] == metric + ) + return float(match[statistic]) + + coarse_z_p95 = summary_value("all", "coarse", "translation_z_mae_mm", "p95") + local_z_p95 = summary_value("all", "local", "translation_z_mae_mm", "p95") + reductions = { + "full_validation_z_p95_percent": 100.0 * (coarse_z_p95 - local_z_p95) / coarse_z_p95, + } + for group in ("small", "farthest_observed", "right"): + coarse_value = summary_value(group, "coarse", "absolute_mpjpe_mm", "mean") + local_value = summary_value(group, "local", "absolute_mpjpe_mm", "mean") + reductions[f"{group}_absolute_mpjpe_percent"] = 100.0 * (coarse_value - local_value) / coarse_value + gate_metric = ( + reductions["full_validation_z_p95_percent"] >= 20.0 + or reductions["small_absolute_mpjpe_percent"] >= 15.0 + or reductions["farthest_observed_absolute_mpjpe_percent"] >= 15.0 + ) + gate_no_regression = True # Exact by construction and asserted above. + gate = { + "registered_condition": ( + "z P95 reduction >=20% OR small/farthest-observed absolute MPJPE reduction >=15%; " + "root-relative and direct-2D degradation <=2%" + ), + "metric_gate_pass": bool(gate_metric), + "no_regression_gate_pass": gate_no_regression, + "formal_A1_gate_pass": bool(gate_metric and gate_no_regression), + "depth_increment_condition": ( + "A2 additionally requires local-depth to retain meaningful improvement beyond the " + "same-capacity oracle-location control; reported but not silently assumed." + ), + "reductions_percent": reductions, + } + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "group_metrics.csv", group_rows) + write_csv(args.output_dir / "validation_predictions.csv", prediction_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap_rows) + torch.save({ + "wave": "A1_oracle_local_depth", + "fit_seed": args.fit_seed, + "input_dim": local_dim, + "hidden_dim": args.hidden_dim, + "max_residual_m": args.max_residual_m, + "models": { + variant: {key: value.detach().cpu() for key, value in model.state_dict().items()} + for variant, model in regressors.items() + }, + "scalers": { + variant: {"mean": mean, "std": std} + for variant, (mean, std) in scalers.items() + }, + }, args.output_dir / "regressors.pt") + report = { + "status": "evaluated", + "phase": 4, + "wave": "A1_oracle_local_depth", + "official_test_used": False, + "frozen_checkpoint": validation_report["checkpoint"], + "train_manifest": train_report["manifest"], + "validation_manifest": validation_report["manifest"], + "challenge_manifest": { + "path": str(args.challenge_manifest.resolve()), + "sha256": sha256(args.challenge_manifest), + "role": "secondary diagnostic only; never checkpoint selection", + }, + "protocol": { + "fit_data": "official_train only", + "fit_holdout": ( + f"whole-take SHA256 modulus-{args.holdout_modulus} holdout within official_train" + ), + "validation": "complete official validation, one independent report", + "control": "same input dimension and MLP parameter count; local-depth fields zeroed", + "hidden_dim": args.hidden_dim, + "max_residual_m": args.max_residual_m, + "learning_rate": args.learning_rate, + "weight_decay": args.weight_decay, + "batch_size": args.batch_size, + "maximum_epochs": args.epochs, + "early_stopping_patience": args.patience, + "fit_seed": args.fit_seed, + }, + "sample_counts": { + "official_train_fit": int(train_mask.sum()), + "official_train_holdout": int(holdout_mask.sum()), + "official_validation": len(validation_rows), + }, + "parameter_counts": { + variant: sum(parameter.numel() for parameter in model.parameters()) + for variant, model in regressors.items() + }, + "histories": histories, + "gate": gate, + "outputs": { + "group_metrics": str((args.output_dir / "group_metrics.csv").resolve()), + "validation_predictions": str((args.output_dir / "validation_predictions.csv").resolve()), + "paired_take_bootstrap_ci": str((args.output_dir / "paired_take_bootstrap_ci.csv").resolve()), + "regressors": str((args.output_dir / "regressors.pt").resolve()), + }, + } + (args.output_dir / "results.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": "complete", "gate": gate, "output": str(args.output_dir)})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase5_alignment_calibrator.py b/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase5_alignment_calibrator.py new file mode 100644 index 0000000000000000000000000000000000000000..68eb72f652ec43cc343bed31e01e11a7f82287e7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase5_alignment_calibrator.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +"""Fit shared metric-alignment correction/confidence using OOF banks only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +import joblib +import numpy as np +from sklearn.linear_model import HuberRegressor, LogisticRegression +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler + +from foundation_hand.evaluation.alignment_calibration import FEATURE_NAMES, features_from_take + +THRESHOLD_GRID = (0.50, 0.60, 0.70, 0.80, 0.90, 0.95, 1.01) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_bank_layout( + manifests: list[dict[str, Any]], expected_banks_per_fold: int, +) -> dict[str, Any]: + if expected_banks_per_fold < 1: + raise ValueError("expected banks per fold must be positive") + observed_pairs: set[tuple[int, str]] = set() + observed_fold_seeds: set[tuple[int, int]] = set() + fold_counts: Counter[int] = Counter() + seed_folds: dict[int, set[int]] = defaultdict(set) + for manifest in manifests: + fold = int(manifest["fold"]) + checkpoint = str(manifest["checkpoint"]["sha256"]) + pair = (fold, checkpoint) + if pair in observed_pairs: + raise ValueError(f"duplicate OOF fold/checkpoint bank: {pair}") + observed_pairs.add(pair) + fold_counts[fold] += 1 + seed = manifest.get("seed") + if seed is None: + if expected_banks_per_fold > 1: + raise ValueError("expanded OOF banks require an explicit coarse seed") + continue + seed = int(seed) + fold_seed = (fold, seed) + if fold_seed in observed_fold_seeds: + raise ValueError(f"duplicate OOF fold/seed bank: {fold_seed}") + observed_fold_seeds.add(fold_seed) + seed_folds[seed].add(fold) + if set(fold_counts) != {0, 1, 2}: + raise ValueError(f"shared calibrator requires folds 0/1/2, got {set(fold_counts)}") + if any(fold_counts[fold] != expected_banks_per_fold for fold in range(3)): + raise ValueError( + "OOF bank count per fold differs from --expected-banks-per-fold: " + f"{dict(sorted(fold_counts.items()))}" + ) + if expected_banks_per_fold > 1: + if len(seed_folds) != expected_banks_per_fold: + raise ValueError( + f"expected {expected_banks_per_fold} coarse seeds, got {sorted(seed_folds)}" + ) + incomplete = {seed: sorted(folds) for seed, folds in seed_folds.items() if folds != {0, 1, 2}} + if incomplete: + raise ValueError(f"each coarse seed must cover folds 0/1/2: {incomplete}") + return { + "banks_per_fold": {str(fold): fold_counts[fold] for fold in range(3)}, + "coarse_seeds": sorted(seed_folds), + } + + +def load_bank( + bank_dirs: list[Path], expected_banks_per_fold: int = 1, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = { + key: [] for key in ( + "features", "target_residual_z_m", "raw_delta_z_m", "alignment_applied", + "pred_joints_m", "target_joints_m", "side", "hand_scale_px", + "frame_id", "subject", "take", "coarse_seed", "checkpoint", + ) + } + manifests = [] + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("bank_version") != 2 + or manifest.get("scope") != "full_fold" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("leakage_audit", {}).get("passed") is not True + or manifest.get("official_test_used") is not False + or manifest.get("official_validation_used_for_assignment") is not False + ): + raise ValueError(f"calibrator requires a complete leakage-free OOF bank: {bank_dir}") + manifests.append(manifest) + validate_bank_layout(manifests, expected_banks_per_fold) + for bank_dir, manifest in zip(bank_dirs, manifests, strict=True): + seed = int(manifest.get("seed", -1)) + checkpoint = str(manifest["checkpoint"]["sha256"]) + for take_record in manifest["takes"]: + with np.load(take_record["path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + time = len(arrays["frame_id"]) + features = features_from_take(arrays) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays[ + "frame_valid" + ][:, None].astype(bool) + hand_indices = np.broadcast_to(np.arange(2)[None], (time, 2)) + frame_ids = np.broadcast_to(arrays["frame_id"][:, None], (time, 2)) + chunks["features"].append(features[valid]) + chunks["target_residual_z_m"].append(arrays["translation_residual_m"][..., 2][valid]) + chunks["raw_delta_z_m"].append(arrays["alignment_delta_z_m"][valid]) + chunks["alignment_applied"].append(arrays["alignment_applied"][valid]) + chunks["pred_joints_m"].append(arrays["pred_joints_camera"][valid]) + chunks["target_joints_m"].append(arrays["target_joints_camera"][valid]) + chunks["side"].append(hand_indices[valid]) + chunks["hand_scale_px"].append(arrays["coarse_hand_scale_px"][valid]) + chunks["frame_id"].append(frame_ids[valid]) + chunks["subject"].append(np.full(valid.sum(), str(arrays["subject"]))) + chunks["take"].append(np.full(valid.sum(), str(arrays["take"]))) + chunks["coarse_seed"].append(np.full(valid.sum(), seed, dtype=np.int64)) + chunks["checkpoint"].append(np.full(valid.sum(), checkpoint)) + return {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + + +def correction_metrics(samples: dict[str, np.ndarray], correction_m: np.ndarray) -> dict[str, float]: + correction = np.asarray(correction_m, dtype=np.float64) + pred_joints = samples["pred_joints_m"].astype(np.float64).copy() + pred_joints[..., 2] += correction[:, None] + target_joints = samples["target_joints_m"].astype(np.float64) + joint_error_mm = np.linalg.norm(pred_joints - target_joints, axis=-1) * 1000.0 + z_error_mm = np.abs(samples["target_residual_z_m"] - correction) * 1000.0 + p95 = float(np.percentile(z_error_mm, 95)) + return { + "absolute_mpjpe_mm": float(joint_error_mm.mean()), + "z_mae_mm": float(z_error_mm.mean()), + "z_p95_mm": p95, + "z_cvar95_mm": float(z_error_mm[z_error_mm >= p95].mean()), + } + + +def fit_regressor(features: np.ndarray, target: np.ndarray): + return make_pipeline( + StandardScaler(), + HuberRegressor(epsilon=1.35, alpha=1e-4, max_iter=400, tol=1e-5), + ).fit(features, target) + + +def fit_confidence(features: np.ndarray, helpful: np.ndarray): + if np.unique(helpful).size < 2: + raise ValueError("alignment helpfulness target has only one class") + return make_pipeline( + StandardScaler(), + LogisticRegression(max_iter=1000, class_weight="balanced", C=1.0), + ).fit(features, helpful) + + +def select_confidence_threshold( + samples: dict[str, np.ndarray], + calibrated_correction_m: np.ndarray, + confidence: np.ndarray, +) -> tuple[float, list[dict[str, float | bool]]]: + coarse = correction_metrics(samples, np.zeros(len(confidence))) + guardrail_mm = min(0.2, 0.01 * coarse["absolute_mpjpe_mm"]) + available = samples["alignment_applied"].astype(bool) + rows = [] + for threshold in THRESHOLD_GRID: + applied = available & (confidence >= threshold) + correction = np.where(applied, calibrated_correction_m, 0.0) + metrics = correction_metrics(samples, correction) + rows.append({ + "threshold": threshold, + "available_fraction": float(available.mean()), + "applied_fraction": float(applied.mean()), + **metrics, + "absolute_guardrail_passed": bool( + metrics["absolute_mpjpe_mm"] <= coarse["absolute_mpjpe_mm"] + guardrail_mm + ), + }) + eligible = [row for row in rows if row["absolute_guardrail_passed"]] + if not eligible: + return 1.01, rows + eligible.sort(key=lambda row: ( + float(row["absolute_mpjpe_mm"]), + float(row["z_p95_mm"]), + float(row["applied_fraction"]), + )) + return float(eligible[0]["threshold"]), rows + + +def write_predictions( + path: Path, + samples: dict[str, np.ndarray], + calibrated: np.ndarray, + confidence: np.ndarray, + threshold: float, +) -> None: + with path.open("x", newline="", encoding="utf-8") as handle: + fields = ( + "sample_index", "coarse_seed", "checkpoint_sha256", "subject", "take", "frame_id", "side", + "target_residual_z_mm", "raw_alignment_delta_z_mm", + "calibrated_delta_z_mm", "confidence", "alignment_available", "applied", + ) + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for index in range(len(calibrated)): + writer.writerow({ + "sample_index": index, + "coarse_seed": int(samples.get("coarse_seed", np.full(len(calibrated), -1))[index]), + "checkpoint_sha256": str(samples.get("checkpoint", np.full(len(calibrated), ""))[index]), + "subject": samples["subject"][index], + "take": samples["take"][index], + "frame_id": int(samples["frame_id"][index]), + "side": "right" if int(samples["side"][index]) else "left", + "target_residual_z_mm": 1000.0 * samples["target_residual_z_m"][index], + "raw_alignment_delta_z_mm": 1000.0 * samples["raw_delta_z_m"][index], + "calibrated_delta_z_mm": 1000.0 * calibrated[index], + "confidence": confidence[index], + "alignment_available": bool(samples["alignment_applied"][index]), + "applied": bool( + samples["alignment_applied"][index] + and confidence[index] >= threshold + ), + }) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--expected-banks-per-fold", type=int, default=1) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("calibrator output directory must be new or empty") + samples = load_bank(args.bank_dir, args.expected_banks_per_fold) + features = samples["features"] + target = samples["target_residual_z_m"].astype(np.float64) + raw_delta = samples["raw_delta_z_m"].astype(np.float64) + available = samples["alignment_applied"].astype(bool) + subjects = samples["subject"] + cv_correction = np.zeros_like(target) + cv_confidence = np.zeros_like(target) + fold_records = [] + for heldout_subject in sorted(set(subjects.tolist())): + heldout = subjects == heldout_subject + train = ~heldout + regressor = fit_regressor(features[train], target[train]) + helpful = available[train] & ( + np.abs(target[train] - raw_delta[train]) < np.abs(target[train]) + ) + confidence_model = fit_confidence(features[train], helpful) + cv_correction[heldout] = np.clip(regressor.predict(features[heldout]), -0.12, 0.12) + cv_confidence[heldout] = confidence_model.predict_proba(features[heldout])[:, 1] + fold_records.append({ + "heldout_subject": heldout_subject, + "train_samples": int(train.sum()), + "heldout_samples": int(heldout.sum()), + "raw_helpful_fraction_train": float(helpful.mean()), + }) + threshold, threshold_rows = select_confidence_threshold( + samples, cv_correction, cv_confidence, + ) + raw_available = np.where(available, raw_delta, 0.0) + calibrated_available = np.where(available, cv_correction, 0.0) + selected_correction = np.where( + available & (cv_confidence >= threshold), cv_correction, 0.0, + ) + metrics = { + "coarse": correction_metrics(samples, np.zeros_like(target)), + "robust_alignment_unscaled": correction_metrics(samples, raw_available), + "calibrated_always": correction_metrics(samples, calibrated_available), + "calibrated_confidence": correction_metrics(samples, selected_correction), + } + corrections = { + "coarse": np.zeros_like(target), + "robust_alignment_unscaled": raw_available, + "calibrated_always": calibrated_available, + "calibrated_confidence": selected_correction, + } + metrics_by_seed = {} + for seed in sorted(set(samples["coarse_seed"].tolist())): + if int(seed) < 0: + continue + mask = samples["coarse_seed"] == seed + subset = { + key: value[mask] + for key, value in samples.items() + if key in ("target_residual_z_m", "pred_joints_m", "target_joints_m") + } + metrics_by_seed[str(int(seed))] = { + condition: correction_metrics(subset, correction[mask]) + for condition, correction in corrections.items() + } + + final_regressor = fit_regressor(features, target) + final_helpful = available & (np.abs(target - raw_delta) < np.abs(target)) + final_confidence = fit_confidence(features, final_helpful) + args.output_dir.mkdir(parents=True, exist_ok=True) + model_path = args.output_dir / "alignment_calibrator.joblib" + joblib.dump({ + "version": "phase5_oof_alignment_calibrator_v1", + "feature_names": FEATURE_NAMES, + "regressor": final_regressor, + "confidence": final_confidence, + "confidence_threshold": threshold, + "correction_bound_m": 0.12, + }, model_path) + predictions_path = args.output_dir / "oof_calibration_predictions.csv" + write_predictions( + predictions_path, samples, cv_correction, cv_confidence, threshold, + ) + report = { + "status": "fitted", + "experiment_class": "preregistered_oof_calibration", + "result_role": "train_oof_cross_validated_threshold_selection", + "official_validation_used": False, + "official_test_used": False, + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "expected_banks_per_fold": args.expected_banks_per_fold, + "coarse_seeds": sorted({int(seed) for seed in samples["coarse_seed"] if int(seed) >= 0}), + "samples": len(target), + "subjects": sorted(set(subjects.tolist())), + "features": list(FEATURE_NAMES), + "leave_one_subject_out": fold_records, + "confidence_target": "available raw robust delta reduces absolute wrist-z error", + "threshold_grid": list(THRESHOLD_GRID), + "selected_threshold": threshold, + "threshold_selection_rule": "minimize OOF absolute MPJPE among <=min(0.2mm,1%) guardrail candidates; tie-break z P95 then lower apply fraction", + "threshold_rows": threshold_rows, + "metrics": metrics, + "metrics_by_seed": metrics_by_seed, + "model": {"path": str(model_path.resolve()), "sha256": sha256(model_path)}, + "predictions": {"path": str(predictions_path.resolve()), "sha256": sha256(predictions_path)}, + } + (args.output_dir / "calibration.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "samples": report["samples"], + "selected_threshold": threshold, "metrics": metrics, + "official_validation_used": False, "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase5_causal_state.py b/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bf8459c36303256261ef7ad38e7a1f322f501a9f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase5_causal_state.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Select causal translation-z state parameters using train OOF sequences only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.causal_state import ( + causal_constant_velocity_kalman, + measurement_uncertainty_multiplier, +) + + +PROCESS_SIGMAS = (0.002, 0.005, 0.01, 0.02, 0.05) +MEASUREMENT_SIGMAS = (0.0025, 0.005, 0.01, 0.02) +UNCERTAINTY_STRENGTHS = (0.5, 1.0, 2.0) +GUARDRAIL_MM = 0.2 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_calibration_predictions(path: Path) -> dict[tuple[str, int, str], dict[str, float | bool]]: + output = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + key = (row["take"], int(row["frame_id"]), row["side"]) + if key in output: + raise ValueError(f"duplicate OOF calibration prediction: {key}") + output[key] = { + "calibrated_delta_z_m": float(row["calibrated_delta_z_mm"]) / 1000.0, + "confidence": float(row["confidence"]), + "available": row["alignment_available"] == "True", + } + return output + + +def load_sequences( + bank_dirs: list[Path], prediction_csv: Path, +) -> tuple[list[dict[str, np.ndarray]], list[dict[str, Any]]]: + predictions = read_calibration_predictions(prediction_csv) + sequences = [] + manifests = [] + consumed: set[tuple[str, int, str]] = set() + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("bank_version") != 2 + or manifest.get("scope") != "full_fold" + or manifest.get("official_test_used") is not False + ): + raise ValueError(f"invalid OOF bank: {bank_dir}") + manifests.append(manifest) + for record in manifest["takes"]: + with np.load(record["path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + time = len(arrays["frame_id"]) + calibrated = np.zeros((time, 2), dtype=np.float32) + confidence = np.zeros((time, 2), dtype=np.float32) + available = np.zeros((time, 2), dtype=bool) + prediction_present = np.zeros((time, 2), dtype=bool) + for index, frame_id in enumerate(arrays["frame_id"]): + for hand, side in enumerate(("left", "right")): + key = (str(arrays["take"]), int(frame_id), side) + if key not in predictions: + continue + row = predictions[key] + calibrated[index, hand] = float(row["calibrated_delta_z_m"]) + confidence[index, hand] = float(row["confidence"]) + available[index, hand] = bool(row["available"]) + prediction_present[index, hand] = True + consumed.add(key) + expected = arrays["mano_annotation_valid"].astype(bool) & arrays[ + "frame_valid" + ][:, None].astype(bool) + if np.any(expected & ~prediction_present): + raise ValueError(f"missing OOF calibration rows for {arrays['take']}") + uncertainty_base = measurement_uncertainty_multiplier( + confidence, + arrays["alignment_inlier_ratio"], + arrays["alignment_residual_scale_m"], + arrays["alignment_valid_fraction"], + arrays["alignment_conditioning_quality"], + 1.0, + ) + uncertainty_base = np.where(available, uncertainty_base, 5.0) + sequences.append({ + "take": np.asarray(arrays["take"]), + "clip_index": arrays["clip_index"], + "frame_id": arrays["frame_id"], + "frame_valid": arrays["frame_valid"].astype(bool), + "hand_valid": expected, + "coarse_z_m": arrays["pred_wrist_translation"][..., 2], + "measurement_z_m": arrays["pred_wrist_translation"][..., 2] + np.where( + available, calibrated, 0.0, + ), + "target_z_m": arrays["target_wrist_translation"][..., 2], + "pred_joints_m": arrays["pred_joints_camera"], + "target_joints_m": arrays["target_joints_camera"], + # The deployable coarse model remains a measurement even when + # local Depth/K alignment is unavailable. In that case the + # correction falls back to zero and uncertainty is maximal. + "measurement_available": np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), (time, 2), + ).copy(), + "alignment_available": available, + "uncertainty_multiplier_base": uncertainty_base, + }) + if consumed != set(predictions): + raise ValueError("OOF calibration predictions do not exactly match bank samples") + return sequences, manifests + + +def summarize_filter( + sequences: list[dict[str, np.ndarray]], + *, + process_sigma: float | None, + measurement_sigma: float | None, + uncertainty_strength: float, +) -> dict[str, float]: + absolute = [] + z_error = [] + velocity_error = [] + acceleration_error = [] + predicted_acceleration = [] + predicted_jerk = [] + for arrays in sequences: + measurement = arrays["measurement_z_m"] + if process_sigma is None or measurement_sigma is None: + filtered = measurement + else: + base = arrays["uncertainty_multiplier_base"] + multiplier = 1.0 + uncertainty_strength * (base - 1.0) + filtered, _ = causal_constant_velocity_kalman( + measurement, + frame_id=arrays["frame_id"], + segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], + measurement_available=arrays["measurement_available"], + process_sigma_m_per_frame2=process_sigma, + measurement_sigma_m=measurement_sigma, + uncertainty_multiplier=multiplier, + ) + correction = filtered - arrays["coarse_z_m"] + joints = arrays["pred_joints_m"].astype(np.float64).copy() + joints[..., 2] += correction[..., None] + valid = arrays["hand_valid"] + joint_error = np.linalg.norm(joints - arrays["target_joints_m"], axis=-1).mean(axis=-1) + absolute.extend((joint_error[valid] * 1000.0).tolist()) + z_error.extend((np.abs(filtered - arrays["target_z_m"])[valid] * 1000.0).tolist()) + contiguous = ( + (arrays["frame_id"][1:] == arrays["frame_id"][:-1] + 1) + & (arrays["clip_index"][1:] == arrays["clip_index"][:-1]) + ) + for hand in range(2): + pair_valid = contiguous & valid[1:, hand] & valid[:-1, hand] + pred_velocity = np.diff(filtered[:, hand]) + target_velocity = np.diff(arrays["target_z_m"][:, hand]) + velocity_error.extend((np.abs(pred_velocity - target_velocity)[pair_valid] * 1000.0).tolist()) + if len(filtered) < 3: + continue + triple_valid = pair_valid[1:] & pair_valid[:-1] + pred_acceleration = np.diff(filtered[:, hand], n=2) + target_acceleration = np.diff(arrays["target_z_m"][:, hand], n=2) + acceleration_error.extend((np.abs(pred_acceleration - target_acceleration)[triple_valid] * 1000.0).tolist()) + predicted_acceleration.extend((np.abs(pred_acceleration)[triple_valid] * 1000.0).tolist()) + if len(filtered) >= 4: + quad_valid = triple_valid[1:] & triple_valid[:-1] + jerk = np.diff(filtered[:, hand], n=3) + predicted_jerk.extend((np.abs(jerk)[quad_valid] * 1000.0).tolist()) + absolute_array = np.asarray(absolute) + z_array = np.asarray(z_error) + return { + "absolute_mpjpe_mm": float(absolute_array.mean()), + "z_mae_mm": float(z_array.mean()), + "z_p95_mm": float(np.percentile(z_array, 95)), + "velocity_error_mm_per_frame": float(np.mean(velocity_error)), + "acceleration_error_mm_per_frame2": float(np.mean(acceleration_error)), + "predicted_acceleration_mm_per_frame2": float(np.mean(predicted_acceleration)), + "predicted_jerk_mm_per_frame3": float(np.mean(predicted_jerk)), + } + + +def select_candidate(rows: list[dict[str, Any]], baseline: dict[str, float]) -> dict[str, Any]: + eligible = [ + row for row in rows + if float(row["absolute_mpjpe_mm"]) <= baseline["absolute_mpjpe_mm"] + GUARDRAIL_MM + and float(row["z_mae_mm"]) <= baseline["z_mae_mm"] + GUARDRAIL_MM + and float(row["z_p95_mm"]) <= baseline["z_p95_mm"] + GUARDRAIL_MM + ] + if not eligible: + raise ValueError("no causal-state candidate passes the OOF static guardrails") + return min(eligible, key=lambda row: ( + float(row["predicted_acceleration_mm_per_frame2"]), + float(row["acceleration_error_mm_per_frame2"]), + float(row["velocity_error_mm_per_frame"]), + float(row["absolute_mpjpe_mm"]), + )) + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("causal-state output directory must be new or empty") + sequences, manifests = load_sequences(args.bank_dir, args.calibration_predictions) + baseline = summarize_filter( + sequences, process_sigma=None, measurement_sigma=None, uncertainty_strength=0.0, + ) + rows = [] + for process_sigma in PROCESS_SIGMAS: + for measurement_sigma in MEASUREMENT_SIGMAS: + for family, strengths in ( + ("fixed_kalman", (0.0,)), + ("uncertainty_kalman", UNCERTAINTY_STRENGTHS), + ): + for strength in strengths: + rows.append({ + "family": family, + "process_sigma_m_per_frame2": process_sigma, + "measurement_sigma_m": measurement_sigma, + "uncertainty_strength": strength, + **summarize_filter( + sequences, + process_sigma=process_sigma, + measurement_sigma=measurement_sigma, + uncertainty_strength=strength, + ), + }) + selected = { + family: select_candidate( + [row for row in rows if row["family"] == family], baseline, + ) + for family in ("fixed_kalman", "uncertainty_kalman") + } + args.output_dir.mkdir(parents=True, exist_ok=True) + grid_path = args.output_dir / "causal_state_oof_grid.csv" + write_csv(grid_path, rows) + report = { + "status": "selected", + "experiment_class": "train_oof_causal_state_selection", + "official_validation_used": False, + "official_test_used": False, + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "calibration_predictions": { + "path": str(args.calibration_predictions.resolve()), + "sha256": sha256(args.calibration_predictions), + }, + "sequences": len(sequences), + "baseline_calibrated_per_frame": baseline, + "guardrail_mm": GUARDRAIL_MM, + "selection_rule": "within +0.2 mm OOF Absolute/z-MAE/z-P95 guardrails, minimize predicted acceleration then acceleration error, velocity error, and Absolute MPJPE", + "measurement_contract": "coarse z is always the causal measurement on valid frames; unavailable local alignment applies zero correction with maximum uncertainty", + "selected": selected, + "grid": {"path": str(grid_path.resolve()), "sha256": sha256(grid_path), "rows": len(rows)}, + } + (args.output_dir / "causal_state_selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": report["status"], "selected": selected}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase6_harm_risk.py b/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase6_harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..ebfa2bd15ba7b93b4781f9835dd9f649c8e8904c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/fit_phase6_harm_risk.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python3 +"""Fit the preregistered OOF-only Phase 6 harmful-correction risk model.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import joblib +import numpy as np +from sklearn.ensemble import HistGradientBoostingClassifier, HistGradientBoostingRegressor +from sklearn.metrics import brier_score_loss, roc_auc_score +from sklearn.model_selection import GroupKFold + +from foundation_hand.evaluation.mixed_projection import coarse_wrist_ray_translation + + +FEATURE_NAMES = ( + "calibrated_delta_z_m", "abs_calibrated_delta_z_m", + "raw_delta_z_m", "abs_raw_delta_z_m", "raw_calibrated_disagreement_m", + "existing_confidence", "alignment_available", "raw_alignment_available", + "valid_support_count", "projected_support_count", "inlier_ratio", + "residual_scale_m", "valid_fraction", "foreground_fraction", + "background_fraction", "depth_discontinuity_m", "conditioning_quality", + "silhouette_overlap_fraction", "coarse_hand_scale_px", + "coarse_direct_mano_consistency_px", "coarse_z_m", "coarse_ray_x", + "coarse_ray_y", "coarse_wrist_velocity_norm_m_per_frame", + "predicted_depth_order", "side_right", +) +GAIN_THRESHOLDS_MM = (-0.5, 0.0, 0.25, 0.5, 1.0, 2.0) +HARM_THRESHOLDS = (0.2, 0.3, 0.4, 0.5, 0.6) +SEED = 20260717 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_calibration_predictions( + path: Path, +) -> dict[tuple[int, str, int, int], tuple[float, float, bool]]: + lookup = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + hand = 1 if row["side"] == "right" else 0 + key = (int(row["coarse_seed"]), row["take"], int(row["frame_id"]), hand) + if key in lookup: + raise ValueError(f"duplicate calibration prediction: {key}") + lookup[key] = ( + float(row["calibrated_delta_z_mm"]) / 1000.0, + float(row["confidence"]), row["alignment_available"] == "True", + ) + if len(lookup) != 333_936: + raise ValueError(f"calibration prediction coverage changed: {len(lookup)}") + return lookup + + +def harm_cvar95( + coarse_absolute_mm: np.ndarray, + corrected_absolute_mm: np.ndarray, + applied: np.ndarray, +) -> float: + harm = np.where( + applied, np.maximum(corrected_absolute_mm - coarse_absolute_mm, 0.0), 0.0, + ) + threshold = np.percentile(harm, 95) + return float(harm[harm >= threshold].mean()) + + +def evaluate_policy( + *, + coarse_absolute_mm: np.ndarray, + corrected_absolute_mm: np.ndarray, + applied: np.ndarray, + seed_take_groups: np.ndarray, +) -> dict[str, float]: + final = np.where(applied, corrected_absolute_mm, coarse_absolute_mm) + by_group: dict[str, list[float]] = defaultdict(list) + coarse_by_group: dict[str, list[float]] = defaultdict(list) + for group, value, coarse in zip( + seed_take_groups, final, coarse_absolute_mm, strict=True, + ): + by_group[str(group)].append(float(value)) + coarse_by_group[str(group)].append(float(coarse)) + group_values = {key: float(np.mean(values)) for key, values in by_group.items()} + take_deltas = np.asarray([ + group_values[key] - float(np.mean(coarse_by_group[key])) for key in group_values + ]) + return { + "coverage": float(applied.mean()), + "absolute_frame_mean_mm": float(final.mean()), + "absolute_take_mean_mm": float(np.mean(list(group_values.values()))), + "harm_fraction_gt_0p5mm": float( + (applied & ((corrected_absolute_mm - coarse_absolute_mm) > 0.5)).mean() + ), + "harm_cvar95_mm": harm_cvar95( + coarse_absolute_mm, corrected_absolute_mm, applied, + ), + "worst_seed_take_harm_mm": float(take_deltas.max()), + } + + +def models() -> tuple[HistGradientBoostingRegressor, HistGradientBoostingClassifier]: + common = dict( + max_iter=150, learning_rate=0.05, max_depth=3, + min_samples_leaf=40, l2_regularization=1.0, + early_stopping=False, random_state=SEED, + ) + return HistGradientBoostingRegressor(**common), HistGradientBoostingClassifier(**common) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--calibration-json", type=Path, required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + calibration_report = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration_report.get("status") != "fitted" + or calibration_report.get("official_validation_used") is not False + or calibration_report.get("official_test_used") is not False + or calibration_report.get("samples") != 333_936 + or calibration_report.get("predictions", {}).get("sha256") + != sha256(args.calibration_predictions) + ): + raise ValueError("expanded OOF calibration contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + calibration = load_calibration_predictions(args.calibration_predictions) + + feature_chunks = [] + gain_chunks = [] + coarse_chunks = [] + corrected_chunks = [] + available_chunks = [] + physical_groups = [] + seed_take_groups = [] + sample_rows = [] + bank_records = [] + for bank_index, registered in enumerate(calibration_report["bank_manifests"], start=1): + manifest_path = Path(registered["path"]) + if sha256(manifest_path) != registered["sha256"]: + raise ValueError(f"bank manifest hash mismatch: {manifest_path}") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("official_test_used") is not False + or manifest.get("leakage_audit", {}).get("passed") is not True + ): + raise ValueError(f"bank isolation contract failed: {manifest_path}") + seed = int(manifest["seed"]) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + needed = ( + "frame_id", "frame_valid", "pred_wrist_translation", + "pred_joints_camera", "target_joints_camera", + "mano_annotation_valid", "alignment_delta_z_m", "alignment_applied", + "alignment_valid_support_count", "alignment_projected_support_count", + "alignment_inlier_ratio", "alignment_residual_scale_m", + "alignment_valid_fraction", "alignment_foreground_fraction", + "alignment_background_fraction", "alignment_depth_discontinuity_m", + "alignment_conditioning_quality", "silhouette_overlap_fraction", + "coarse_hand_scale_px", "coarse_direct_mano_consistency_px", + "coarse_wrist_velocity_m_per_frame", "predicted_depth_order", + ) + arrays = {key: archive[key] for key in needed} + take = str(archive["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + time_index, hand = np.where(valid) + count = len(time_index) + calibrated = np.zeros(count, dtype=np.float64) + confidence = np.zeros(count, dtype=np.float64) + available = np.zeros(count, dtype=bool) + for index, (time_value, hand_value) in enumerate( + zip(time_index, hand, strict=True), + ): + key = (seed, take, int(arrays["frame_id"][time_value]), int(hand_value)) + calibrated[index], confidence[index], available[index] = calibration[key] + raw = arrays["alignment_delta_z_m"][time_index, hand].astype(np.float64) + raw_available = arrays["alignment_applied"][time_index, hand].astype(bool) + calibrated = np.where(available, calibrated, 0.0) + raw = np.where(raw_available, raw, 0.0) + coarse_translation = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + coarse_joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + corrected_translation = coarse_wrist_ray_translation( + coarse_translation, coarse_translation[:, 2] + calibrated, + ) + corrected_joints = coarse_joints + ( + corrected_translation - coarse_translation + )[:, None] + coarse_absolute = np.linalg.norm(coarse_joints - target_joints, axis=-1).mean(axis=1) * 1000.0 + corrected_absolute = np.linalg.norm( + corrected_joints - target_joints, axis=-1, + ).mean(axis=1) * 1000.0 + gain = coarse_absolute - corrected_absolute + z = np.maximum(coarse_translation[:, 2], 1e-6) + overlap = arrays["silhouette_overlap_fraction"][time_index] + depth_order = arrays["predicted_depth_order"][time_index] + velocity = arrays["coarse_wrist_velocity_m_per_frame"][time_index, hand] + features = np.column_stack(( + calibrated, np.abs(calibrated), raw, np.abs(raw), np.abs(raw - calibrated), + confidence, available, raw_available, + arrays["alignment_valid_support_count"][time_index, hand], + arrays["alignment_projected_support_count"][time_index, hand], + arrays["alignment_inlier_ratio"][time_index, hand], + arrays["alignment_residual_scale_m"][time_index, hand], + arrays["alignment_valid_fraction"][time_index, hand], + arrays["alignment_foreground_fraction"][time_index, hand], + arrays["alignment_background_fraction"][time_index, hand], + arrays["alignment_depth_discontinuity_m"][time_index, hand], + arrays["alignment_conditioning_quality"][time_index, hand], overlap, + arrays["coarse_hand_scale_px"][time_index, hand], + arrays["coarse_direct_mano_consistency_px"][time_index, hand], + coarse_translation[:, 2], coarse_translation[:, 0] / z, + coarse_translation[:, 1] / z, np.linalg.norm(velocity, axis=1), + depth_order, hand.astype(np.float64), + )).astype(np.float32) + features = np.nan_to_num(features, nan=0.0, posinf=1e6, neginf=-1e6) + feature_chunks.append(features) + gain_chunks.append(gain.astype(np.float32)) + coarse_chunks.append(coarse_absolute.astype(np.float32)) + corrected_chunks.append(corrected_absolute.astype(np.float32)) + available_chunks.append(available) + physical_groups.extend([take] * count) + seed_take_groups.extend([f"{seed}:{take}"] * count) + sample_rows.extend({ + "coarse_seed": seed, "take": take, + "frame_id": int(arrays["frame_id"][time_value]), + "side": "right" if hand_value else "left", + } for time_value, hand_value in zip(time_index, hand, strict=True)) + bank_records.append({ + "path": str(manifest_path), "sha256": registered["sha256"], + "seed": seed, "fold": int(manifest["fold"]), + }) + print(f"[{bank_index}/9] fold{manifest['fold']} seed{seed} loaded", flush=True) + + X = np.concatenate(feature_chunks) + gain = np.concatenate(gain_chunks) + coarse_absolute = np.concatenate(coarse_chunks) + corrected_absolute = np.concatenate(corrected_chunks) + available = np.concatenate(available_chunks) + groups = np.asarray(physical_groups) + seed_take = np.asarray(seed_take_groups) + if X.shape != (333_936, len(FEATURE_NAMES)) or len(set(zip( + (row["coarse_seed"] for row in sample_rows), + (row["take"] for row in sample_rows), + (row["frame_id"] for row in sample_rows), + (row["side"] for row in sample_rows), + ))) != len(sample_rows): + raise ValueError("OOF feature coverage or uniqueness changed") + + harmful = gain < -0.5 + harm_magnitude = np.maximum(-gain, 0.0) + regression_weight = 1.0 + 4.0 * np.minimum(harm_magnitude / 10.0, 5.0) + classifier_weight = 1.0 + 8.0 * np.minimum(harm_magnitude / 10.0, 5.0) + predicted_gain = np.zeros_like(gain) + predicted_harm = np.zeros_like(gain) + fold_id = np.full(len(gain), -1, dtype=np.int8) + splitter = GroupKFold(n_splits=5) + for fold, (train, heldout) in enumerate(splitter.split(X, gain, groups), start=0): + regressor, classifier = models() + regressor.fit(X[train], gain[train], sample_weight=regression_weight[train]) + classifier.fit(X[train], harmful[train], sample_weight=classifier_weight[train]) + predicted_gain[heldout] = regressor.predict(X[heldout]) + predicted_harm[heldout] = classifier.predict_proba(X[heldout])[:, 1] + fold_id[heldout] = fold + print(f"cross-fit {fold + 1}/5: {len(heldout)} held-out samples", flush=True) + if np.any(fold_id < 0): + raise AssertionError("cross-fitting omitted samples") + + coarse_policy = evaluate_policy( + coarse_absolute_mm=coarse_absolute, corrected_absolute_mm=corrected_absolute, + applied=np.zeros_like(available), seed_take_groups=seed_take, + ) + always_policy = evaluate_policy( + coarse_absolute_mm=coarse_absolute, corrected_absolute_mm=corrected_absolute, + applied=available, seed_take_groups=seed_take, + ) + grid_rows = [] + for gain_threshold in GAIN_THRESHOLDS_MM: + for harm_threshold in HARM_THRESHOLDS: + applied = available & (predicted_gain >= gain_threshold) & ( + predicted_harm <= harm_threshold + ) + row = { + "expected_gain_threshold_mm": gain_threshold, + "harm_probability_threshold": harm_threshold, + **evaluate_policy( + coarse_absolute_mm=coarse_absolute, + corrected_absolute_mm=corrected_absolute, + applied=applied, seed_take_groups=seed_take, + ), + } + row["absolute_delta_vs_always_mm"] = ( + row["absolute_take_mean_mm"] - always_policy["absolute_take_mean_mm"] + ) + row["harm_cvar_reduction_fraction"] = 1.0 - ( + row["harm_cvar95_mm"] / max(always_policy["harm_cvar95_mm"], 1e-12) + ) + row["admission_passed"] = bool( + row["absolute_delta_vs_always_mm"] <= 0.1 + and row["coverage"] >= 0.2 + and row["harm_cvar_reduction_fraction"] >= 0.2 + ) + grid_rows.append(row) + eligible = [row for row in grid_rows if row["admission_passed"]] + eligible.sort(key=lambda row: ( + row["absolute_take_mean_mm"], row["harm_cvar95_mm"], + row["worst_seed_take_harm_mm"], row["coverage"], + )) + selected = eligible[0] if eligible else None + + final_regressor, final_classifier = models() + final_regressor.fit(X, gain, sample_weight=regression_weight) + final_classifier.fit(X, harmful, sample_weight=classifier_weight) + package_path = args.output_dir / "harm_risk_package.joblib" + joblib.dump({ + "version": "phase6_harm_risk_v1", + "feature_names": FEATURE_NAMES, + "regressor": final_regressor, + "classifier": final_classifier, + "selected_thresholds": None if selected is None else { + "expected_gain_threshold_mm": selected["expected_gain_threshold_mm"], + "harm_probability_threshold": selected["harm_probability_threshold"], + }, + "harm_definition_mm": 0.5, + "seed": SEED, + }, package_path) + + prediction_rows = [] + for index, identity in enumerate(sample_rows): + prediction_rows.append({ + "sample_index": index, **identity, "cv_fold": int(fold_id[index]), + "coarse_absolute_mpjpe_mm": float(coarse_absolute[index]), + "corrected_absolute_mpjpe_mm": float(corrected_absolute[index]), + "realized_gain_mm": float(gain[index]), + "predicted_gain_mm": float(predicted_gain[index]), + "harmful_gt_0p5mm": bool(harmful[index]), + "predicted_harm_probability": float(predicted_harm[index]), + "alignment_available": bool(available[index]), + }) + write_csv(args.output_dir / "cross_fitted_predictions.csv", prediction_rows) + write_csv(args.output_dir / "threshold_grid.csv", grid_rows) + report = { + "status": "admitted_for_one_frozen_validation" if selected is not None else "rejected_oof_gate", + "experiment": "P6_S3_harm_aware_risk_gate", + "experiment_class": "exploratory_oof_only_cross_fitted_risk_model", + "official_validation_used": False, + "official_test_used": False, + "oracle_information_at_inference": False, + "samples": len(X), "physical_takes": len(set(groups)), + "seed_take_groups": len(set(seed_take)), "features": list(FEATURE_NAMES), + "cross_validation": "5-fold GroupKFold by physical take across coarse seeds", + "cross_fitted_gain_mae_mm": float(np.mean(np.abs(predicted_gain - gain))), + "cross_fitted_harm_brier": float(brier_score_loss(harmful, predicted_harm)), + "cross_fitted_harm_roc_auc": float(roc_auc_score(harmful, predicted_harm)), + "coarse_policy": coarse_policy, "always_policy": always_policy, + "selected": selected, "eligible_conditions": len(eligible), + "package": {"path": str(package_path), "sha256": sha256(package_path)}, + "calibration": { + "json": str(args.calibration_json.resolve()), + "json_sha256": sha256(args.calibration_json), + "predictions": str(args.calibration_predictions.resolve()), + "predictions_sha256": sha256(args.calibration_predictions), + }, + "banks": bank_records, + "outputs": { + "threshold_grid": "threshold_grid.csv", + "cross_fitted_predictions": "cross_fitted_predictions.csv", + }, + } + (args.output_dir / "risk_selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "selected": selected, + "gain_mae_mm": report["cross_fitted_gain_mae_mm"], + "harm_auc": report["cross_fitted_harm_roc_auc"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/freeze_phase7_h2o_adaptation_validation.py b/home/wuyifan/EgoNet_train_20261008/scripts/freeze_phase7_h2o_adaptation_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..2298467e46db7bcb7e74db4bb2211252cb82a353 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/freeze_phase7_h2o_adaptation_validation.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Freeze a train-heldout-selected adaptation candidate before H2O validation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_external import sha256 +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES + + +def build_freeze_record(selection_path: Path, validation_manifest: Path) -> dict[str, Any]: + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if ( + selection.get("status") != "selected_h2o_adaptation_train_group_heldout" + or selection.get("selection_split") != "h2o_train_group_heldout_only" + or selection.get("h2o_official_validation_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("adaptation selection is not eligible for validation freeze") + winner = selection.get("winner") + candidates = [item for item in selection.get("candidates", []) if item["candidate"] == winner] + if len(candidates) != 1: + raise ValueError("adaptation winner is missing or duplicated") + candidate = candidates[0] + checkpoint, config = Path(candidate["checkpoint"]), Path(candidate["config"]) + if sha256(checkpoint) != candidate["checkpoint_sha256"]: + raise ValueError("adaptation checkpoint SHA256 mismatch") + if sha256(config) != candidate["config_sha256"]: + raise ValueError("adaptation config SHA256 mismatch") + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only canonical H2O official validation may be frozen") + return { + "status": "h2o_adaptation_candidate_frozen", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "winner": winner, + "checkpoint": { + "path": str(checkpoint.resolve()), + "sha256": candidate["checkpoint_sha256"], + "step": candidate["checkpoint_step"], + }, + "config": { + "path": str(config.resolve()), + "sha256": candidate["config_sha256"], + }, + "adaptation_selection_path": str(selection_path.resolve()), + "adaptation_selection_sha256": sha256(selection_path), + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used_for_selection": False, + "h2o_validation_manifest": { + "path": str(validation_manifest.resolve()), + "sha256": sha256(validation_manifest), + }, + "frozen_h2o_input_modes": list(INPUT_MODES), + "h2o_training_data_used": True, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection", type=Path, required=True) + parser.add_argument("--validation-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = build_freeze_record(args.selection, args.validation_manifest) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/freeze_phase7_h2o_zero_shot.py b/home/wuyifan/EgoNet_train_20261008/scripts/freeze_phase7_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..002866bbe6508fa9e5db8985698182f6eaab4657 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/freeze_phase7_h2o_zero_shot.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Freeze H2O zero-shot exposure only after external selection is immutable.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path + +from scripts.build_phase7_scale_eval_queue import sha256 + + +def build_freeze_record(selection_path: Path, manifest: Path) -> dict: + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if ( + selection.get("status") != "selected_external_generalist_no_h2o" + or selection.get("h2o_training_data_used") is not False + or selection.get("h2o_official_validation_used_for_external_selection") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("external generalist selection is not freeze-eligible") + checkpoint = Path(selection["checkpoint"]["path"]) + config = Path(selection["config"]["path"]) + if sha256(checkpoint) != selection["checkpoint"]["sha256"]: + raise ValueError("selected checkpoint hash mismatch") + if sha256(config) != selection["config"]["sha256"]: + raise ValueError("selected config hash mismatch") + if manifest.name != "official_val.jsonl": + raise ValueError("only canonical H2O official_val.jsonl can be frozen") + return { + "status": "external_generalist_frozen", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "checkpoint_path": str(checkpoint.resolve()), + "checkpoint_sha256": selection["checkpoint"]["sha256"], + "checkpoint_step": selection["checkpoint"]["step"], + "config_path": str(config.resolve()), "config_sha256": selection["config"]["sha256"], + "external_selection_path": str(selection_path.resolve()), + "external_selection_sha256": sha256(selection_path), + "frozen_h2o_input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "h2o_validation_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-selection", type=Path, required=True) + parser.add_argument("--h2o-validation-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + record = build_freeze_record(args.external_selection, args.h2o_validation_manifest) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/freeze_phase9_final_deployment.py b/home/wuyifan/EgoNet_train_20261008/scripts/freeze_phase9_final_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..fab8e06ab8f566b0f721a6d89481379322349a41 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/freeze_phase9_final_deployment.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python3 +"""Freeze the unique final Phase 9 checkpoint for post-selection deployment audits.""" + +from __future__ import annotations + +import argparse +import hashlib +import fcntl +import json +from pathlib import Path +from typing import Any + +import torch +import yaml + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def complete_controller( + plan_path: Path, state_path: Path, *, decision_path: Path | None = None, +) -> tuple[dict[str, Any], Path]: + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not report_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or (decision_path is not None and report_path.resolve() != decision_path.resolve()) + ): + raise ValueError(f"controller decision is incomplete or unbound: {state_path}") + report = read_json(report_path) + if report.get("status") != "complete" or report.get("official_test_used") is not False: + raise ValueError(f"controller decision is not isolated: {report_path}") + return report, report_path + + +def normalized_job(job: dict[str, Any], source: str) -> dict[str, Any]: + checkpoint = Path(job.get("checkpoint", job.get("path", ""))) + checkpoint_sha = job.get("checkpoint_sha256", job.get("sha256")) + config = Path(job.get("config", "")) + config_sha = job.get("config_sha256") + if ( + not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha + or not config.is_file() or sha256(config) != config_sha + ): + raise ValueError(f"selected full job differs: {source}") + return { + "source": source, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha, + "config": str(config.resolve()), + "config_sha256": config_sha, + } + + +def preceding_full_job( + stage8: dict[str, Any], selection: dict[str, Any], +) -> tuple[dict[str, Any], str, bool, list[int]]: + resolution_hw = list(stage8["resolution_hw"]) + if stage8.get("shared_augmentation_accepted") is True: + job = normalized_job( + stage8["candidate_training_jobs"]["full"], + "stage8_shared_augmentation_full", + ) + return job, "shared_augmentation", True, resolution_hw + control = stage8["control"] + if control.get("kind") == "resolution_896x512_candidate": + path = Path(control["evaluation_plan"]["path"]) + if not path.is_file() or sha256(path) != control["evaluation_plan"]["sha256"]: + raise ValueError("selected resolution evaluation plan differs") + plan = read_json(path) + job = normalized_job(plan["training_jobs"]["full"], "stage7_resolution_full") + return job, "resolution", False, resolution_hw + if control.get("kind") == "frozen_640_winner": + record = control["selection_report"] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError("selected 640 selection report differs") + selected = read_json(path) + if selected.get("winner") != selection.get("winner"): + raise ValueError("selected 640 winner differs") + job = normalized_job({ + "checkpoint": selected["winner_checkpoint"]["path"], + "checkpoint_sha256": selected["winner_checkpoint"]["sha256"], + "config": selected["winner_config"]["path"], + "config_sha256": selected["winner_config"]["sha256"], + }, "phase9_frozen_640_winner") + return job, "frozen_640_winner", False, resolution_hw + raise ValueError("Stage 8 selected control kind differs") + + +def checkpoint_contract(job: dict[str, Any], resolution_hw: list[int]) -> int: + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + if ( + config.get("experiment", {}).get("branch") != "phase9_unified" + or config.get("experiment", {}).get("official_test_used") is not False + or list(config.get("data", {}).get("resolution_hw", [])) != resolution_hw + ): + raise ValueError("final deployment config contract differs") + state = torch.load(job["checkpoint"], map_location="cpu", weights_only=False) + extra = state.get("extra", {}) + if ( + extra.get("config") != config + or extra.get("h2o_training_data_used") is not True + or extra.get("official_test_used") is not False + or not isinstance(state.get("model"), dict) + ): + raise ValueError("final deployment checkpoint provenance differs") + return int(state["step"]) + + +def build_freeze( + *, selection_plan_path: Path, selection_state_path: Path, + stage8_plan_path: Path, stage8_state_path: Path, + last2_plan_path: Path, last2_state_path: Path, + validation_manifest: Path, validation_manifest_sha256: str, + training_manifest: Path, training_manifest_sha256: str, +) -> dict[str, Any]: + selection_plan = read_json(selection_plan_path) + selection_state = read_json(selection_state_path) + selection_path = Path(selection_plan["output_json"]) + if ( + selection_state.get("status") != "complete" + or selection_state.get("plan_sha256") != sha256(selection_plan_path) + or selection_state.get("official_test_used") is not False + or selection_state.get("h2o_official_validation_used") is not False + or not selection_path.is_file() + ): + raise ValueError("unified selection is incomplete or unbound") + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("winner") != selection_state.get("winner") + or selection.get("winner_checkpoint") != selection_state.get("winner_checkpoint") + or selection.get("winner_config") != selection_state.get("winner_config") + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("unified selection report differs") + required_plan = {item["id"]: item for item in selection_plan["required_states"]} + required_state = { + item["id"]: item for item in selection_state.get("required_states", []) + } + if len(required_plan) != 9 or set(required_state) != set(required_plan): + raise ValueError("unified selection required-state chain differs") + for identifier, item in required_state.items(): + path = Path(item["path"]) + expected_path = Path(required_plan[identifier]["path"]) + if ( + path.resolve() != expected_path.resolve() + or not path.is_file() or sha256(path) != item["sha256"] + ): + raise ValueError(f"unified selection required state differs: {identifier}") + payload = read_json(path) + if payload.get("status") != "complete" or payload.get("official_test_used") is not False: + raise ValueError(f"unified selection required state is incomplete: {identifier}") + + stage8_plan = read_json(stage8_plan_path) + stage8, stage8_path = complete_controller( + stage8_plan_path, stage8_state_path, + decision_path=Path(stage8_plan["decision_report"]), + ) + last2_plan = read_json(last2_plan_path) + last2, last2_path = complete_controller( + last2_plan_path, last2_state_path, + decision_path=Path(last2_plan["report"]), + ) + if stage8.get("winner") != selection.get("winner"): + raise ValueError("Stage 8 winner differs from unified selection") + + preceding, mechanism, shared_augmentation, resolution_hw = preceding_full_job( + stage8, selection, + ) + selected = str(last2["selected"]) + if selected in {"last2_5e7", "last2_1e6"}: + candidate = "5e7" if selected == "last2_5e7" else "1e6" + report_record = last2["selected_candidate_report"] + candidate_path = Path(report_record["path"]) + if not candidate_path.is_file() or sha256(candidate_path) != report_record["sha256"]: + raise ValueError("selected last-2 candidate report differs") + candidate_report = read_json(candidate_path) + if ( + candidate_report.get("candidate") != candidate + or candidate_report.get("gate", {}).get("accepted") is not True + ): + raise ValueError("selected last-2 gate differs") + job = normalized_job( + candidate_report["candidate_training_jobs"]["full"], selected, + ) + mechanism = selected + shared_augmentation = bool(candidate_report["shared_augmentation"]) + resolution_hw = list(candidate_report["resolution_hw"]) + elif selected == "preceding_mechanism": + job = preceding + else: + raise ValueError("last-2 final selection differs") + + step = checkpoint_contract(job, resolution_hw) + for path, expected, label in ( + (validation_manifest, validation_manifest_sha256, "official validation"), + (training_manifest, training_manifest_sha256, "official train"), + ): + if not path.is_file() or sha256(path) != expected: + raise ValueError(f"{label} manifest differs") + chain = { + "unified_selection_plan": sha256(selection_plan_path), + "unified_selection_state": sha256(selection_state_path), + "unified_selection": sha256(selection_path), + "stage8_controller_plan": sha256(stage8_plan_path), + "stage8_controller_state": sha256(stage8_state_path), + "stage8_decision": sha256(stage8_path), + "last2_finalizer_plan": sha256(last2_plan_path), + "last2_finalizer_state": sha256(last2_state_path), + "last2_final_decision": sha256(last2_path), + } + chain_hash = hashlib.sha256( + json.dumps(chain, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + return { + "schema_version": "phase9_final_deployment_freeze_v1", + "status": "phase9_final_unified_checkpoint_frozen", + "created_utc": last2["created_utc"], + "winner": selection["winner"], + "selected_mechanism": mechanism, + "resolution_hw": resolution_hw, + "shared_augmentation": shared_augmentation, + "checkpoint": { + "path": job["checkpoint"], "sha256": job["checkpoint_sha256"], + "step": step, + }, + "config": {"path": job["config"], "sha256": job["config_sha256"]}, + "selection_chain": chain, + "selection_chain_sha256": chain_hash, + "selection_complete": True, + "stage9_final_decision_complete": True, + "frozen_h2o_input_modes": list(INPUT_MODES), + "h2o_validation_manifest": { + "path": str(validation_manifest.resolve()), + "sha256": validation_manifest_sha256, + }, + "h2o_training_manifest": { + "path": str(training_manifest.resolve()), + "sha256": training_manifest_sha256, + }, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--selection-state", type=Path, required=True) + parser.add_argument("--stage8-plan", type=Path, required=True) + parser.add_argument("--stage8-state", type=Path, required=True) + parser.add_argument("--last2-plan", type=Path, required=True) + parser.add_argument("--last2-state", type=Path, required=True) + parser.add_argument("--validation-manifest", type=Path, required=True) + parser.add_argument("--validation-manifest-sha256", required=True) + parser.add_argument("--training-manifest", type=Path, required=True) + parser.add_argument("--training-manifest-sha256", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = build_freeze( + selection_plan_path=args.selection_plan, + selection_state_path=args.selection_state, + stage8_plan_path=args.stage8_plan, stage8_state_path=args.stage8_state, + last2_plan_path=args.last2_plan, last2_state_path=args.last2_state, + validation_manifest=args.validation_manifest, + validation_manifest_sha256=args.validation_manifest_sha256, + training_manifest=args.training_manifest, + training_manifest_sha256=args.training_manifest_sha256, + ) + if args.output.exists(): + if read_json(args.output) != result: + raise ValueError("existing final deployment freeze differs") + else: + atomic_json(args.output, result) + state = { + "schema_version": "phase9_final_deployment_freeze_state_v1", + "status": "complete", "freeze": str(args.output.resolve()), + "freeze_sha256": sha256(args.output), + "checkpoint_sha256": result["checkpoint"]["sha256"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_freeze_state_v1", + "status": "failed_resumable", + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used": False, + "official_test_used": False, + }) + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c27472cd14392687856490a5d6fd1c44ee7bc4d7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_configs.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Generate the pre-registered Phase 3 decoder/temporal core configs.""" + +from __future__ import annotations + +import argparse +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +LAYOUTS = { + "l0": "sequential", + "l1": "alternating", + "l2": "hybrid_reread", +} +MATRIX_ROWS = ( + ("l0", "t0"), + ("l0", "t1"), + ("l1", "t0"), + ("l1", "t1"), + ("l2", "t1"), +) +MODALITIES = { + "m0": {"use_depth": False, "use_rays": False}, + "m3": {"use_depth": True, "use_rays": True}, +} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + + rows = [] + for modality, modality_values in MODALITIES.items(): + for layout, temporal in MATRIX_ROWS: + for seed in SEEDS: + name = f"core_{modality}_{layout}_{temporal}_s{seed}" + config = { + "name": name, + "seed": seed, + "experiment": { + "phase": 3, + "matrix": "decoder_temporal_core", + "modality": modality.upper(), + "layout": layout.upper(), + "temporal": temporal.upper(), + "registered_axes": ["layout", "temporal_attention", "modality"], + }, + "data": { + "resolution_hw": [288, 512], + "T": 8, + "stride": 1, + "batch_size": 1, + }, + "model": { + "encoder": "dinov3", + "decoder_dim": 512, + "decoder_layers": 3, + "attention_heads": 8, + "decoder_mode": LAYOUTS[layout], + "use_temporal": temporal == "t1", + "use_depth": modality_values["use_depth"], + "depth_mode": "log_depth", + "depth_gate_mode": "fixed", + "depth_gate_fixed_value": 0.5, + "use_rays": modality_values["use_rays"], + "use_bimanual_interaction": True, + "predict_presence": True, + "require_mano": True, + }, + "loss": { + "joint2d": 1.0, + "joint3d_camera": 10.0, + "vertices_camera": 1.0, + "local_pose": 1.0, + "global_orientation": 1.0, + "shape": 0.1, + "translation": 10.0, + "reprojection": 1.0, + "temporal_velocity": 0.1, + "temporal_acceleration": 0.05, + "bimanual_relative_wrist": 1.0, + "presence": 0.0, + }, + "assets": { + "dinov3_source": "third_party/dinov3", + "dinov3_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "mano_root": "/SSD3/jiasen/foundation_hand/pretrained/mano", + }, + "precision": "bf16", + "protocol": { + "max_steps": 100000, + "num_workers": 4, + "checkpoint_interval": 25000, + "validation_interval": 5000, + "validation_batches": 256, + "learning_rate": 5e-5, + "min_learning_rate": 5e-6, + "warmup_steps": 500, + "early_stopping_patience": 0, + "validation_subset_manifest": "artifacts/phase3/validation_subset/validation_subset_256.json", + }, + } + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": modality.upper(), "layout": layout.upper(), + "decoder_mode": LAYOUTS[layout], "temporal": temporal.upper(), + "use_depth": int(modality_values["use_depth"]), + "use_rays": int(modality_values["use_rays"]), + "depth_gate": 0.5 if modality_values["use_depth"] else "not_used", + }) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} configs under {args.output_dir}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_depth_fusion_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_depth_fusion_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..a1436a0b91cc980e884999390c44c9a0fda0795f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_depth_fusion_configs.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Generate the first independent Phase 3 Depth fusion/representation controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = { + "gate025": { + "depth_mode": "log_depth", "depth_gate_mode": "fixed", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.25, + }, + "learned_gate": { + "depth_mode": "log_depth", "depth_gate_mode": "learned", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.5, + }, + "geometry": { + "depth_mode": "geometry", "depth_gate_mode": "fixed", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.5, + }, +} + + +def matrix_row(path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(path), "name": config["name"], "seed": config["seed"], + "modality": "M3", "layout": "L1", "temporal": "T1", + "variant": config["experiment"]["variant"], + "depth_mode": model["depth_mode"], + "depth_gate_mode": model["depth_gate_mode"], + "depth_gate_floor": model["depth_gate_floor"], + "depth_gate_fixed_value": model["depth_gate_fixed_value"], + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_fusion_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_fusion_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, changes in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / f"core_m3_l1_t1_s{seed}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, "matrix": "depth_fusion", "modality": "M3", + "layout": "L1", "temporal": "T1", "variant": variant, + "registered_axes": ["depth_fusion_or_representation"], + "reference": "P0_M3_L1_T1_fixed_gate_0.5", + } + config["model"].update(changes) + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append(matrix_row(path, config, "new_formal_run")) + rows.sort(key=lambda row: (str(row["variant"]), int(row["seed"]))) + write_matrix(args.runs_csv, rows) + write_matrix(args.matrix_csv, rows) + print(f"generated {len(rows)} Depth fusion configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_dropout_dose_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_dropout_dose_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..ff442de59dcd384b1d69070f92c29d57f47b2214 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_dropout_dose_configs.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Generate lower-dose Geometry modality-dropout Phase 3 controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = {"dropout005_geometry": 0.05, "dropout010_geometry": 0.10} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/dropout_dose_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/dropout_dose_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, probability in VARIANTS.items(): + for seed in SEEDS: + base_path = ( + args.base_config_dir + / f"depth_dropout00_geometry_m3_l1_t1_s{seed}.yaml" + ) + config = copy.deepcopy( + yaml.safe_load(base_path.read_text(encoding="utf-8")) + ) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "depth_modality_dropout_dose", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": variant, + "registered_axes": ["modality_dropout_dose"], + "reference": "D2_dropout00_and_dropout02_endpoints", + } + config["model"]["modality_dropout_prob"] = probability + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), + "name": name, + "seed": seed, + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "depth_mode": "geometry", + "variant": variant, + "modality_dropout_prob": probability, + "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(rows[0]), lineterminator="\n" + ) + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} dropout-dose configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_long_tail_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_long_tail_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..45500ef2d771d2f985343c04d4f262ebc1d0645a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_long_tail_configs.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Generate the preregistered E.3 low-learning-rate tail configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/photometric"), + ) + parser.add_argument( + "--checkpoint-root", type=Path, + default=Path("artifacts/phase3/photometric_runs_commit239b0bf"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/long_tail_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + source_name = f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + base_path = args.base_config_dir / f"{source_name}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "low_lr_tail", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": "photometric_on_r640x368_tail150k", + "registered_axes": ["training_duration"], + "reference": source_name, + } + config["protocol"]["max_steps"] = 150_000 + config["protocol"]["lr_schedule_steps"] = 100_000 + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + checkpoint = args.checkpoint_root / source_name / "step_0100000_final.pt" + rows.append({ + "config": str(path.resolve()), "name": name, "seed": seed, + "resume_checkpoint": str(checkpoint.resolve()), + "start_step": 100_000, "max_steps": 150_000, + "lr_schedule_steps": 100_000, "min_learning_rate": 5e-6, + "changed_variable": "training_duration_only", + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} E.3 low-LR-tail configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_modality_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_modality_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c89255f39b11007505204124621076e0d01704eb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_modality_configs.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Generate the new M1/M2 runs for the Phase 3 modality matrix.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +NEW_MODALITIES = { + "M1": {"use_depth": False, "use_rays": True}, + "M2": {"use_depth": True, "use_rays": False}, +} + + +def matrix_row(config_path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(config_path), + "name": config["name"], + "seed": config["seed"], + "modality": config["experiment"]["modality"], + "layout": config["experiment"]["layout"], + "temporal": config["experiment"]["temporal"], + "use_depth": int(model["use_depth"]), + "use_rays": int(model["use_rays"]), + "depth_gate": 0.5 if model["use_depth"] else "not_used", + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/modality")) + parser.add_argument("--new-runs-csv", type=Path, default=Path("artifacts/phase3/reports/modality_new_runs.csv")) + parser.add_argument("--full-matrix-csv", type=Path, default=Path("artifacts/phase3/reports/modality_config_matrix.csv")) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + new_rows = [] + full_rows = [] + for seed in SEEDS: + references = {} + for modality in ("M0", "M3"): + path = args.core_config_dir / f"core_{modality.lower()}_l1_t1_s{seed}.yaml" + config = yaml.safe_load(path.read_text(encoding="utf-8")) + references[modality] = config + full_rows.append(matrix_row(path, config, "reused_core_matrix")) + + for modality, flags in NEW_MODALITIES.items(): + config = copy.deepcopy(references["M3"]) + name = f"modality_{modality.lower()}_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "modality_causal", + "modality": modality, + "layout": "L1", + "temporal": "T1", + "registered_axes": ["modality"], + "decoder_promotion_source": "decoder_temporal_core_best_absolute_full_val", + } + config["model"]["use_depth"] = flags["use_depth"] + config["model"]["use_rays"] = flags["use_rays"] + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + row = matrix_row(path, config, "new_formal_run") + new_rows.append(row) + full_rows.append(row) + + new_rows.sort(key=lambda row: (str(row["modality"]), int(row["seed"]))) + full_rows.sort(key=lambda row: (str(row["modality"]), int(row["seed"]))) + write_matrix(args.new_runs_csv, new_rows) + write_matrix(args.full_matrix_csv, full_rows) + print(f"generated {len(new_rows)} new configs and {len(full_rows)} full-matrix rows") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_modality_dropout_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_modality_dropout_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c2841dce151e58be976b8e49d194d5faab3c2e69 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_modality_dropout_configs.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Generate same-commit geometry controls for M3 modality-dropout training.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +DROP_PROB = 0.2 +VARIANTS = {"dropout00_geometry": 0.0, "dropout02_geometry": DROP_PROB} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_dropout_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_dropout_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, probability in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / f"depth_geometry_m3_l1_t1_s{seed}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, "matrix": "depth_modality_dropout", "modality": "M3", + "layout": "L1", "temporal": "T1", "variant": variant, + "registered_axes": ["modality_dropout"], + "reference": "dropout00_geometry_same_commit", + } + config["model"]["modality_dropout_prob"] = probability + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "depth_mode": "geometry", "variant": variant, + "modality_dropout_prob": probability, "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} same-commit geometry modality-dropout configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_photometric_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_photometric_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..138bc89f81a2c18daf910344d7768488270af82f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_photometric_configs.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Generate same-code Phase 3 photometric augmentation off/on controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = {"off": False, "on": True} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/resolution"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/photometric"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/photometric_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/photometric_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, enabled in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"photometric_{variant}_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "photometric_augmentation", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": f"photometric_{variant}_r640x368", + "registered_axes": ["photometric_augmentation"], + "reference": "E1_promoted_r640x368", + } + config["data"]["photometric_augmentation"] = { + "enabled": enabled, + "probability": 0.8, + "brightness": 0.2, + "contrast": 0.2, + "saturation": 0.2, + "hue": 0.05, + } + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "variant": f"photometric_{variant}", + "photometric_enabled": enabled, + "resolution_h": 368, "resolution_w": 640, + "source": "new_same_commit_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} photometric off/on configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_resolution_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_resolution_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..4bc5c0e1550283a14452e8ffc4a36f9ed606302c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_resolution_configs.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Generate the 640x368 Phase 3 resolution controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VALIDATION_SUBSET = ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" +) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/resolution"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/resolution_640_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/resolution_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + base_path = ( + args.base_config_dir + / f"depth_dropout005_geometry_m3_l1_t1_s{seed}.yaml" + ) + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "resolution", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": "dropout005_geometry_r640x368", + "registered_axes": ["input_resolution"], + "reference": "dropout005_geometry_r512x288_D3", + } + config["data"]["resolution_hw"] = [368, 640] + config["protocol"]["validation_subset_manifest"] = VALIDATION_SUBSET + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "depth_mode": "geometry", "variant": "r640x368", + "resolution_h": 368, "resolution_w": 640, + "modality_dropout_prob": 0.05, "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} 640x368 resolution configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_temporal_position_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_temporal_position_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..12031161423294f686ba8f955d905e9de947f069 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase3_temporal_position_configs.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Generate the P0/P1 relative temporal-position experiment configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) + + +def matrix_row(config_path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(config_path), + "name": config["name"], + "seed": config["seed"], + "modality": config["experiment"]["modality"], + "layout": config["experiment"]["layout"], + "temporal": config["experiment"]["temporal"], + "position": config["experiment"].get("position", "P0"), + "temporal_position_mode": model.get("temporal_position_mode", "none"), + "relative_bias_max_distance": model.get("temporal_relative_bias_max_distance", "not_used"), + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/temporal_position")) + parser.add_argument( + "--new-runs-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_new_runs.csv"), + ) + parser.add_argument( + "--p0-runs-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_p0_reused_runs.csv"), + ) + parser.add_argument( + "--full-matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + new_rows = [] + p0_rows = [] + full_rows = [] + for seed in SEEDS: + p0_path = args.core_config_dir / f"core_m3_l1_t1_s{seed}.yaml" + p0 = yaml.safe_load(p0_path.read_text(encoding="utf-8")) + p0_row_config = copy.deepcopy(p0) + p0_row_config["experiment"]["position"] = "P0" + p0_row = matrix_row(p0_path, p0_row_config, "reused_core_matrix") + p0_rows.append(p0_row) + full_rows.append(p0_row) + + p1 = copy.deepcopy(p0) + name = f"temporal_p1_m3_l1_t1_s{seed}" + p1["name"] = name + p1["experiment"] = { + "phase": 3, + "matrix": "temporal_position", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "position": "P1", + "registered_axes": ["temporal_position"], + "reference": "P0_no_temporal_position_reused_core_m3_l1_t1", + } + p1["model"]["temporal_position_mode"] = "relative_bias" + p1["model"]["temporal_relative_bias_max_distance"] = 15 + p1_path = args.output_dir / f"{name}.yaml" + p1_path.write_text(yaml.safe_dump(p1, sort_keys=False), encoding="utf-8") + row = matrix_row(p1_path, p1, "new_formal_run") + new_rows.append(row) + full_rows.append(row) + + write_matrix(args.new_runs_csv, new_rows) + write_matrix(args.p0_runs_csv, p0_rows) + write_matrix(args.full_matrix_csv, full_rows) + print(f"generated {len(new_rows)} new configs and {len(full_rows)} P0/P1 rows") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase4_a3_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase4_a3_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..11d025bc0e7dd6e7f56fcad7fc54c12e8e9b509d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase4_a3_configs.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Generate hash-bound A3 oracle-crop tiny/health/formal configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +import json +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +MODES = { + "rgb": "oracle_rgb", + "depth_k": "oracle_depth_k", + "rgb_depth_k": "oracle_rgb_depth_k", +} +STAGES = { + "tiny2k": { + "stage": "tiny", "max_steps": 2_000, "checkpoint_interval": 500, + "validation_interval": 500, "warmup_steps": 100, + "validation_subset_manifest": None, + }, + "health25k": { + "stage": "health", "max_steps": 25_000, + "checkpoint_interval": 5_000, "validation_interval": 5_000, + "warmup_steps": 500, + "validation_subset_manifest": ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" + ), + }, + "formal100k": { + "stage": "formal", "max_steps": 100_000, + "checkpoint_interval": 25_000, "validation_interval": 5_000, + "warmup_steps": 500, + "validation_subset_manifest": ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" + ), + }, +} + + +def protocol(stage: dict[str, object]) -> dict[str, object]: + output = { + "max_steps": stage["max_steps"], + "num_workers": 4, + "checkpoint_interval": stage["checkpoint_interval"], + "validation_interval": stage["validation_interval"], + "validation_batches": 256, + "learning_rate": 5e-5, + "min_learning_rate": 5e-6, + "warmup_steps": stage["warmup_steps"], + "early_stopping_patience": 0, + "lr_schedule_steps": stage["max_steps"], + } + if stage["validation_subset_manifest"] is not None: + output["validation_subset_manifest"] = stage["validation_subset_manifest"] + return output + + +def build_config( + base: dict, + mode_slug: str, + stage_slug: str, + checkpoint: dict, +) -> dict: + result = copy.deepcopy(base) + mode = MODES[mode_slug] + stage = STAGES[stage_slug] + seed = int(base["seed"]) + name = f"phase4_a3_{mode_slug}_r640x368_s{seed}_{stage_slug}" + result["name"] = name + result["experiment"] = { + "phase": 4, + "wave": "A", + "cell": "A3", + "stage": stage["stage"], + "oracle_crop_mode": mode, + "reference": base["name"], + "changed_variable": "oracle_raw_high_resolution_crop_residual_only", + "coarse_checkpoint_path": checkpoint["path"], + "coarse_checkpoint_sha256": checkpoint["sha256"], + "coarse_checkpoint_step": checkpoint["step"], + "gt_location_at_train_and_validation": True, + "deployable_inference": False, + "official_test_used": False, + } + result["model"].update({ + "oracle_crop_mode": mode, + "freeze_coarse_for_oracle_crop": True, + }) + result["sampling"] = {"mode": "uniform"} + result["protocol"] = protocol(stage) + return result + + +def write_config_matrices( + rows: list[dict[str, object]], + matrix_csv: Path, + formal_matrix_csv: Path, +) -> list[dict[str, object]]: + if not rows: + raise ValueError("at least one A3 configuration row is required") + matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + if not formal_rows: + raise ValueError("A3 configuration matrix has no formal rows") + formal_matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + return formal_rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--checkpoint-index", type=Path, + default=Path("artifacts/phase3/reports/long_tail_checkpoints.json"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase4/a3_oracle_crop"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/a3_oracle_crop_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/a3_oracle_crop_formal_config_matrix.csv"), + ) + args = parser.parse_args() + checkpoint_index = json.loads(args.checkpoint_index.read_text(encoding="utf-8")) + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + "longtail_photometric_on_geometry_m3_l1_t1_" + f"r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + run = checkpoint_index["runs"][base["name"]] + checkpoint = run["roles"]["tail_best_absolute"] + if int(run["seed"]) != seed or int(checkpoint["step"]) not in range(100_000, 150_001): + raise ValueError(f"invalid frozen checkpoint record for seed {seed}") + for mode_slug, mode in MODES.items(): + for stage_slug in STAGES: + if stage_slug != "formal100k" and seed != SEEDS[0]: + continue + generated = build_config(base, mode_slug, stage_slug, checkpoint) + output_path = args.output_dir / f"{generated['name']}.yaml" + output_path.write_text( + yaml.safe_dump(generated, sort_keys=False), encoding="utf-8", + ) + rows.append({ + "config": str(output_path.resolve()), + "name": generated["name"], + "seed": seed, + "mode": mode, + "stage": STAGES[stage_slug]["stage"], + "max_steps": STAGES[stage_slug]["max_steps"], + "initialization_checkpoint": checkpoint["path"], + "initialization_checkpoint_sha256": checkpoint["sha256"], + "initialization_checkpoint_step": checkpoint["step"], + "gt_location": True, + "official_test_used": False, + }) + formal_rows = write_config_matrices( + rows, args.matrix_csv, args.formal_matrix_csv, + ) + print(json.dumps({ + "status": "generated", "configs": len(rows), + "output_dir": str(args.output_dir), "matrix_csv": str(args.matrix_csv), + "formal_configs": len(formal_rows), + "formal_matrix_csv": str(args.formal_matrix_csv), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase4_b0_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase4_b0_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..374500c074dfdc0d588ae23fef22449cd82d1893 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase4_b0_configs.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Generate preregistered Phase 4 B0 axis-aware loss configurations.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +AXIS_WEIGHTS = (0.5, 0.5, 2.0) +HUBER_BETA_M = 0.01 + + +def b0_config(base: dict, seed: int, stage: str) -> dict: + config = copy.deepcopy(base) + config["seed"] = seed + suffix = { + "smoke": "smoke1", + "tiny": "tiny2k", + "health": "health25k", + "formal": "formal100k", + }[stage] + config["name"] = f"phase4_b0_axis_huber_r640x368_s{seed}_{suffix}" + config["experiment"] = { + "phase": 4, + "wave": "B", + "cell": "B0", + "stage": stage, + "reference": f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}", + "changed_variable": "translation_loss_only", + "frozen_model_recipe": True, + "official_test_used": False, + } + config["loss"]["translation_mode"] = "axis_huber" + config["loss"]["translation_axis_weights"] = list(AXIS_WEIGHTS) + config["loss"]["translation_huber_beta_m"] = HUBER_BETA_M + protocol = config["protocol"] + if stage == "smoke": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 1, + "lr_schedule_steps": 1, + "warmup_steps": 0, + "checkpoint_interval": 1, + "validation_interval": 1, + }) + elif stage == "tiny": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 2_000, + "lr_schedule_steps": 2_000, + "warmup_steps": 100, + "checkpoint_interval": 500, + "validation_interval": 500, + }) + elif stage == "health": + protocol.update({ + "max_steps": 25_000, + "lr_schedule_steps": 25_000, + "warmup_steps": 500, + "checkpoint_interval": 5_000, + "validation_interval": 5_000, + }) + elif stage == "formal": + protocol.update({ + "max_steps": 100_000, + "lr_schedule_steps": 100_000, + "warmup_steps": 500, + "checkpoint_interval": 25_000, + "validation_interval": 5_000, + }) + return config + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, default=Path("configs/phase3/long_tail"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase4/b0_axis_loss")) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b0_axis_loss_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b0_axis_loss_formal_config_matrix.csv"), + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + stages = ("smoke", "tiny", "health", "formal") if seed == SEEDS[0] else ("formal",) + for stage in stages: + config = b0_config(base, seed, stage) + path = args.output_dir / f"{config['name']}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), + "name": config["name"], + "seed": seed, + "stage": stage, + "run_name": f"{stage}_seed{seed}", + "max_steps": config["protocol"]["max_steps"], + "changed_variable": "translation loss L1 -> axis Huber", + "translation_axis_weights": "0.5,0.5,2.0", + "translation_huber_beta_m": HUBER_BETA_M, + "official_test_used": False, + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + with args.formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + print(f"generated {len(rows)} Phase 4 B0 configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase4_b2_configs.py b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase4_b2_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..fa886d4b37a143c5c5e844620f87afaea3cec7f1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/generate_phase4_b2_configs.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Generate preregistered Phase 4 B2 balanced-sampling configurations.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +FULL_SAMPLER_MANIFEST = Path( + "/home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/" + "train_geometry_balanced_v1.json" +) +TINY_SAMPLER_MANIFEST = Path( + "/home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/" + "tiny_train_geometry_balanced_v1.json" +) + + +def b2_config(base: dict, seed: int, stage: str) -> dict: + config = copy.deepcopy(base) + config["seed"] = seed + suffix = { + "smoke": "smoke1", + "tiny": "tiny2k", + "health": "health25k", + "formal": "formal100k", + }[stage] + config["name"] = f"phase4_b2_balanced_sampler_r640x368_s{seed}_{suffix}" + config["experiment"] = { + "phase": 4, + "wave": "B", + "cell": "B2", + "stage": stage, + "reference": f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}", + "changed_variable": "training_sampler_only", + "frozen_model_recipe": True, + "official_test_used": False, + } + config["sampling"] = { + "mode": "balanced", + "manifest": str( + TINY_SAMPLER_MANIFEST if stage == "tiny" else FULL_SAMPLER_MANIFEST + ), + } + protocol = config["protocol"] + if stage == "smoke": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 1, + "lr_schedule_steps": 1, + "warmup_steps": 0, + "checkpoint_interval": 1, + "validation_interval": 1, + }) + elif stage == "tiny": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 2_000, + "lr_schedule_steps": 2_000, + "warmup_steps": 100, + "checkpoint_interval": 500, + "validation_interval": 500, + }) + elif stage == "health": + protocol.update({ + "max_steps": 25_000, + "lr_schedule_steps": 25_000, + "warmup_steps": 500, + "checkpoint_interval": 5_000, + "validation_interval": 5_000, + }) + elif stage == "formal": + protocol.update({ + "max_steps": 100_000, + "lr_schedule_steps": 100_000, + "warmup_steps": 500, + "checkpoint_interval": 25_000, + "validation_interval": 5_000, + }) + return config + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("configs/phase4/b2_balanced_sampling"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b2_balanced_sampling_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path( + "artifacts/phase4/reports/b2_balanced_sampling_formal_config_matrix.csv" + ), + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + stages = ("smoke", "tiny", "health", "formal") if seed == SEEDS[0] else ("formal",) + for stage in stages: + config = b2_config(base, seed, stage) + path = args.output_dir / f"{config['name']}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), + "name": config["name"], + "seed": seed, + "stage": stage, + "run_name": f"{stage}_seed{seed}", + "max_steps": config["protocol"]["max_steps"], + "changed_variable": "uniform -> train-only balanced sampling", + "sampling_manifest": config["sampling"]["manifest"], + "official_test_used": False, + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + with args.formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + print(f"generated {len(rows)} Phase 4 B2 configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/import_phase9_distributed_cache_worker_state.py b/home/wuyifan/EgoNet_train_20261008/scripts/import_phase9_distributed_cache_worker_state.py new file mode 100644 index 0000000000000000000000000000000000000000..c41dc656030e78d58876c0bd9ad515c24f18ffac --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/import_phase9_distributed_cache_worker_state.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Normalize one external Stage 7 cache worker onto the central admission.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.phase9_distributed_assignment import load_assignment +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +HOST_LOCAL_ADMISSION_FIELDS = frozenset({"admitted_utc", "available_gib"}) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: Any) -> str: + payload = json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def scientific_admission(value: dict[str, Any]) -> dict[str, Any]: + return { + key: item for key, item in value.items() + if key not in HOST_LOCAL_ADMISSION_FIELDS + } + + +def validate_admission_pair( + source: dict[str, Any], central: dict[str, Any], expected_plan_sha256: str, +) -> dict[str, Any]: + for label, value in (("source", source), ("central", central)): + if ( + value.get("schema_version") != "phase9_resolution_admission_v1" + or value.get("status") != "complete" + or value.get("scientific_stage_admitted") is not True + or value.get("plan_sha256") != expected_plan_sha256 + or value.get("official_test_used") is not False + or value.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"{label} admission contract differs") + source_scientific = scientific_admission(source) + central_scientific = scientific_admission(central) + if source_scientific != central_scientific: + differing = sorted( + key for key in set(source_scientific) | set(central_scientific) + if source_scientific.get(key) != central_scientific.get(key) + ) + raise ValueError(f"distributed admission scientific binding differs: {differing}") + return { + "host_local_operational_fields": sorted(HOST_LOCAL_ADMISSION_FIELDS), + "source_operational_values": { + key: source[key] for key in sorted(HOST_LOCAL_ADMISSION_FIELDS) + }, + "central_operational_values": { + key: central[key] for key in sorted(HOST_LOCAL_ADMISSION_FIELDS) + }, + "normalized_scientific_binding_sha256": json_sha256(source_scientific), + } + + +def external_cache_worker_owner( + assignment: dict[str, Any], worker_id: str, +) -> str: + state_id = f"{worker_id}_cache_worker" + owners = { + item["id"]: item["owner"] + for item in assignment["stage7_cache_ownership"]["states"] + } + owner = owners.get(state_id) + if owner is None: + raise ValueError(f"distributed cache worker is undeclared: {worker_id}") + if owner == assignment["central_owner"]: + raise ValueError(f"cache worker is not external-owned: {worker_id}") + return owner + + +def validate_release_metadata( + release: dict[str, Any], receive: dict[str, Any], *, + source_owner: str, source_worker_sha256: str, bridge_plan_sha256: str, +) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != source_owner + or release.get("plan_sha256") != bridge_plan_sha256 + or release.get("producer_worker_state", {}).get("sha256") + != source_worker_sha256 + or release.get("live_reverse_sync_forbidden") is not True + or release.get("read_only_after_receive") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache release binding differs") + if ( + receive.get("status") != "complete" + or receive.get("plan_sha256") != bridge_plan_sha256 + or receive.get("release_file_count") != release.get("file_count") + or receive.get("release_total_bytes") != release.get("total_bytes") + or receive.get("live_reverse_sync_performed") is not False + or receive.get("official_test_used") is not False + or receive.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache receive binding differs") + released = { + item["id"]: (item["path"], item["file_count"], item["total_bytes"]) + for item in release.get("artifacts", []) + } + installed = { + item["id"]: (item["path"], item["file_count"], item["total_bytes"]) + for item in receive.get("installed", []) + } + if released != installed: + raise ValueError("external cache installed artifacts differ from release") + + +def validate_released_cache_files( + release: dict[str, Any], expected_files: list[dict[str, Any]], + resolution_hw: list[int], +) -> list[dict[str, Any]]: + root = Path(release["release_root"]) + inventory = {item["path"]: item for item in release["files"]} + results = [] + for expected in expected_files: + path = Path(expected["path"]) + relative = str(path.relative_to(root)) + record = inventory.get(relative) + if ( + record is None or record.get("sha256") != expected["sha256"] + or record.get("bytes") != path.stat().st_size + or not path.is_file() or sha256(path) != expected["sha256"] + ): + raise ValueError(f"external cache release file hash differs: {path}") + if path.name == "cache_report.json": + report = read_json(path) + if ( + report.get("status") != "complete" + or report.get("resolution_hw") != resolution_hw + or report.get("resume_invocation") is not True + or report.get("official_test_used") is not False + ): + raise ValueError(f"external cache report contract differs: {path}") + results.append({ + "path": str(path.resolve()), "sha256": expected["sha256"], + "release_relative_path": relative, "bytes": record["bytes"], + }) + return results + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("status") != "frozen" + or plan.get("central_owner") != "taku3" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("distributed admission import plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"distributed admission import binding differs: {path}") + assignment = load_assignment(plan) + if sha256(plan_path) == plan.get("superseded_plan_sha256"): + raise ValueError("distributed admission import plan identity differs") + return assignment + + +def build_imported_state(plan_path: Path, plan: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + assignment = validate_plan(plan_path, plan) + worker_id = plan["worker_id"] + source_owner = external_cache_worker_owner(assignment, worker_id) + if source_owner != plan["source_owner"]: + raise ValueError("distributed admission source owner differs") + source_admission_path = Path(plan["source_admission"]["evidence_path"]) + central_admission_path = Path(plan["central_admission"]["path"]) + source_worker_path = Path(plan["source_worker_state"]["evidence_path"]) + release_path = Path(plan["cache_release"]["evidence_path"]) + receive_path = Path(plan["cache_receive"]["path"]) + for path, expected in ( + (source_admission_path, plan["source_admission"]["sha256"]), + (central_admission_path, plan["central_admission"]["sha256"]), + (source_worker_path, plan["source_worker_state"]["sha256"]), + (release_path, plan["cache_release"]["sha256"]), + (receive_path, plan["cache_receive"]["sha256"]), + ): + if not path.is_file() or sha256(path) != expected: + raise ValueError(f"distributed admission evidence differs: {path}") + source_admission = read_json(source_admission_path) + central_admission = read_json(central_admission_path) + source_worker = read_json(source_worker_path) + release = read_json(release_path) + receive = read_json(receive_path) + admission = validate_admission_pair( + source_admission, central_admission, plan["cache_execution_plan_sha256"], + ) + if ( + source_worker.get("status") != "complete" + or source_worker.get("worker") != worker_id + or source_worker.get("plan_sha256") != plan["cache_execution_plan_sha256"] + or source_worker.get("admission_state_sha256") != plan["source_admission"]["sha256"] + or source_worker.get("winner") != central_admission["winner"] + or source_worker.get("winner_checkpoint") != central_admission["winner_checkpoint"] + or source_worker.get("winner_config") != central_admission["winner_config"] + or source_worker.get("official_test_used") is not False + or source_worker.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache worker scientific binding differs") + checkpoint = Path(source_worker["winner_checkpoint"]["path"]) + config = Path(source_worker["winner_config"]["path"]) + if ( + not checkpoint.is_file() + or sha256(checkpoint) != source_worker["winner_checkpoint"]["sha256"] + or not config.is_file() + or sha256(config) != source_worker["winner_config"]["sha256"] + ): + raise ValueError("external cache worker winner artifact differs") + validate_release_metadata( + release, receive, source_owner=source_owner, + source_worker_sha256=plan["source_worker_state"]["sha256"], + bridge_plan_sha256=plan["cache_release"]["plan_sha256"], + ) + if ( + release.get("file_count") != plan["cache_release"]["file_count"] + or release.get("total_bytes") != plan["cache_release"]["total_bytes"] + ): + raise ValueError("external cache release inventory totals differ") + if release["producer_worker_state"].get("value") != source_worker: + raise ValueError("external cache release worker value differs") + released_files = validate_released_cache_files( + release, plan["expected_cache_files"], plan["resolution_hw"], + ) + imported = deepcopy(source_worker) + imported["admission_state"] = str(central_admission_path.resolve()) + imported["admission_state_sha256"] = plan["central_admission"]["sha256"] + imported["distributed_admission_import"] = { + "schema_version": "phase9_distributed_admission_import_v1", + "status": "complete", "imported_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "worker": worker_id, "source_owner": source_owner, + "central_owner": assignment["central_owner"], + **admission, + "source_admission": { + "original_path": plan["source_admission"]["original_path"], + "evidence_path": str(source_admission_path.resolve()), + "sha256": plan["source_admission"]["sha256"], + }, + "central_admission": { + "path": str(central_admission_path.resolve()), + "sha256": plan["central_admission"]["sha256"], + }, + "source_worker_state": { + "original_path": plan["source_worker_state"]["original_path"], + "evidence_path": str(source_worker_path.resolve()), + "sha256": plan["source_worker_state"]["sha256"], + }, + "cache_release": { + "evidence_path": str(release_path.resolve()), + "sha256": plan["cache_release"]["sha256"], + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + }, + "cache_receive": { + "path": str(receive_path.resolve()), + "sha256": plan["cache_receive"]["sha256"], + }, + "released_cache_files": released_files, + "source_worker_state_preserved_unmodified": True, + "ordinary_single_host_binding_gate_changed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + audit = { + "schema_version": "phase9_distributed_admission_import_audit_v1", + "status": "complete", "created_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "worker": worker_id, "source_owner": source_owner, + "central_owner": assignment["central_owner"], + "source_admission_sha256": plan["source_admission"]["sha256"], + "central_admission_sha256": plan["central_admission"]["sha256"], + "host_local_operational_fields": admission["host_local_operational_fields"], + "normalized_scientific_binding_sha256": admission[ + "normalized_scientific_binding_sha256" + ], + "cache_release_sha256": plan["cache_release"]["sha256"], + "cache_receive_sha256": plan["cache_receive"]["sha256"], + "cache_release_file_count": release["file_count"], + "cache_release_total_bytes": release["total_bytes"], + "ordinary_single_host_binding_gate_changed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + return imported, audit + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output-state", type=Path, required=True) + parser.add_argument("--audit-output", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + if args.output_state.resolve() != Path(plan["output_state"]).resolve(): + parser.error("distributed admission output state differs") + if args.audit_output.resolve() != Path(plan["audit_output"]).resolve(): + parser.error("distributed admission audit output differs") + with Path(f"{args.output_state}.import.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + imported, audit = build_imported_state(args.plan, plan) + existing = read_json(args.output_state) if args.output_state.is_file() else None + if existing and existing.get("distributed_admission_import", {}).get( + "plan_sha256" + ) == sha256(args.plan): + if not args.audit_output.is_file(): + parser.error("imported worker exists without its audit") + print(json.dumps(existing, indent=2)) + return + atomic_json(args.output_state, imported) + audit["imported_worker_state"] = { + "path": str(args.output_state.resolve()), "sha256": sha256(args.output_state), + } + atomic_json(args.audit_output, audit) + print(json.dumps(imported, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/inspect_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/inspect_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..dad107db9c8f8406ee3a87089dcc0316a72f4fbb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/inspect_h2o.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +"""Inventory an extracted H2O egocentric dataset using only the standard library.""" + +from __future__ import annotations + +import argparse +import json +import struct +from collections import Counter, defaultdict +from pathlib import Path + + +CORE_FRAME_MODALITIES = { + "rgb", + "rgb256", + "depth", + "cam_pose", + "hand_pose", + "hand_pose_mano", + "obj_pose", + "obj_pose_rt", +} +TRAIN_LABEL_MODALITIES = {"action_label", "verb_label"} + + +def image_info(path: Path) -> dict[str, object]: + with path.open("rb") as handle: + header = handle.read(32) + if header.startswith(b"\x89PNG\r\n\x1a\n"): + width, height, bit_depth, color_type = struct.unpack(">IIBB", header[16:26]) + channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(color_type) + return { + "format": "PNG", + "width": width, + "height": height, + "bit_depth_per_channel": bit_depth, + "channels": channels, + "png_color_type": color_type, + } + + if header.startswith(b"\xff\xd8"): + handle.seek(2) + while True: + marker_start = handle.read(1) + if not marker_start: + break + if marker_start != b"\xff": + continue + marker = handle.read(1) + while marker == b"\xff": + marker = handle.read(1) + if marker in {b"\xd8", b"\xd9"}: + continue + size_raw = handle.read(2) + if len(size_raw) != 2: + break + size = struct.unpack(">H", size_raw)[0] + if marker and marker[0] in { + 0xC0, + 0xC1, + 0xC2, + 0xC3, + 0xC5, + 0xC6, + 0xC7, + 0xC9, + 0xCA, + 0xCB, + 0xCD, + 0xCE, + 0xCF, + }: + payload = handle.read(6) + bits, height, width, channels = struct.unpack(">BHHB", payload) + return { + "format": "JPEG", + "width": width, + "height": height, + "bit_depth_per_channel": bits, + "channels": channels, + } + handle.seek(size - 2, 1) + return {"format": "unknown"} + + +def numeric_frame_ids(files: list[Path]) -> set[int]: + return {int(path.stem) for path in files if path.stem.isdigit()} + + +def inspect_text(path: Path) -> dict[str, object]: + values = path.read_text(encoding="utf-8").split() + numeric = [] + for value in values[:8]: + try: + numeric.append(float(value)) + except ValueError: + numeric.append(value) + return {"value_count": len(values), "first_values": numeric} + + +def inspect_splits(root: Path) -> dict[str, object]: + result: dict[str, object] = {} + split_root = root / "label_split" + for split_path in sorted(split_root.glob("*.txt")): + lines = [line.strip() for line in split_path.read_text().splitlines() if line.strip()] + if split_path.name.startswith("pose_"): + missing = sum(not (root / line).is_file() for line in lines) + result[split_path.name] = { + "rows": len(lines), + "missing_paths": missing, + "first": lines[0] if lines else None, + "last": lines[-1] if lines else None, + } + else: + header = lines[0].split() if lines else [] + rows = [line.split() for line in lines[1:]] + path_index = header.index("path") if "path" in header else 1 + missing = sum(not (root / row[path_index]).is_dir() for row in rows) + class_counts: Counter[str] = Counter() + if "action_label" in header: + label_index = header.index("action_label") + class_counts.update(row[label_index] for row in rows) + result[split_path.name] = { + "rows": len(rows), + "columns": header, + "missing_paths": missing, + "class_counts": dict(sorted(class_counts.items(), key=lambda item: int(item[0]))), + } + return result + + +def inspect_dataset(root: Path) -> dict[str, object]: + modalities: dict[str, dict[str, object]] = defaultdict( + lambda: {"files": 0, "bytes": 0, "suffixes": set(), "sample": None} + ) + subject_take_counts: Counter[str] = Counter() + subject_rgb_frames: Counter[str] = Counter() + scene_take_counts: Counter[str] = Counter() + cameras: Counter[str] = Counter() + alignment_issue_counts: Counter[str] = Counter() + unexpected_alignment_issue_counts: Counter[str] = Counter() + alignment_examples: list[dict[str, object]] = [] + missing_modality_directory_takes: Counter[str] = Counter() + unexpected_modality_directory_takes: Counter[str] = Counter() + scalar_label_counts: dict[str, Counter[str]] = { + "action_label": Counter(), + "verb_label": Counter(), + "obj_pose": Counter(), + "obj_pose_rt": Counter(), + } + hand_presence: dict[str, Counter[str]] = { + "hand_pose": Counter(), + "hand_pose_mano": Counter(), + } + + take_dirs = sorted(root.glob("subject*/*/*/cam4")) + for cam4 in take_dirs: + subject, scene, take = cam4.parts[-4:-1] + subject_take_counts[subject] += 1 + scene_take_counts[f"{subject}/{scene}"] += 1 + for camera_dir in cam4.parent.glob("cam*"): + if camera_dir.is_dir(): + cameras[camera_dir.name] += 1 + + files_by_modality: dict[str, list[Path]] = {} + for child in sorted(cam4.iterdir()): + if child.is_dir(): + files = [entry for entry in child.iterdir() if entry.is_file()] + files_by_modality[child.name] = files + stats = modalities[child.name] + stats["files"] = int(stats["files"]) + len(files) + stats["bytes"] = int(stats["bytes"]) + sum(entry.stat().st_size for entry in files) + suffixes = stats["suffixes"] + assert isinstance(suffixes, set) + suffixes.update(entry.suffix.lower() for entry in files) + if stats["sample"] is None and files: + sample_path = sorted(files)[0] + sample: dict[str, object] = {"path": str(sample_path.relative_to(root))} + if sample_path.suffix.lower() in {".png", ".jpg", ".jpeg"}: + sample.update(image_info(sample_path)) + elif sample_path.suffix.lower() == ".txt": + sample.update(inspect_text(sample_path)) + stats["sample"] = sample + if child.name in scalar_label_counts: + for entry in files: + values = entry.read_text(encoding="utf-8").split() + if values: + scalar_label_counts[child.name][str(int(float(values[0])))] += 1 + if child.name in hand_presence: + right_flag_index = 64 if child.name == "hand_pose" else 62 + for entry in files: + values = entry.read_text(encoding="utf-8").split() + if len(values) <= right_flag_index: + hand_presence[child.name]["malformed"] += 1 + continue + left = int(float(values[0])) != 0 + right = int(float(values[right_flag_index])) != 0 + state = { + (True, True): "both", + (True, False): "left_only", + (False, True): "right_only", + (False, False): "neither", + }[(left, right)] + hand_presence[child.name][state] += 1 + elif child.is_file(): + stats = modalities[child.name] + stats["files"] = int(stats["files"]) + 1 + stats["bytes"] = int(stats["bytes"]) + child.stat().st_size + suffixes = stats["suffixes"] + assert isinstance(suffixes, set) + suffixes.add(child.suffix.lower()) + if stats["sample"] is None: + stats["sample"] = { + "path": str(child.relative_to(root)), + **inspect_text(child), + } + + expected_modalities = set(CORE_FRAME_MODALITIES) + if subject != "subject4": + expected_modalities.update(TRAIN_LABEL_MODALITIES) + actual_modalities = set(files_by_modality) + for modality in expected_modalities - actual_modalities: + missing_modality_directory_takes[modality] += 1 + for modality in actual_modalities - expected_modalities: + unexpected_modality_directory_takes[modality] += 1 + + rgb_ids = numeric_frame_ids(files_by_modality.get("rgb", [])) + subject_rgb_frames[subject] += len(rgb_ids) + for modality, files in files_by_modality.items(): + ids = numeric_frame_ids(files) + if ids and ids != rgb_ids: + missing = len(rgb_ids - ids) + extra = len(ids - rgb_ids) + if modality in expected_modalities: + alignment_issue_counts[modality] += 1 + alignment_scope = "expected" + else: + unexpected_alignment_issue_counts[modality] += 1 + alignment_scope = "unexpected" + if len(alignment_examples) < 20: + alignment_examples.append( + { + "take": f"{subject}/{scene}/{take}", + "modality": modality, + "scope": alignment_scope, + "missing_vs_rgb": missing, + "extra_vs_rgb": extra, + } + ) + + serializable_modalities = {} + for name, stats in sorted(modalities.items()): + serializable_modalities[name] = { + **stats, + "suffixes": sorted(stats["suffixes"]), + } + + object_stats = {} + for object_dir in sorted((root / "object").glob("*")): + if object_dir.is_dir(): + object_stats[object_dir.name] = sorted(path.name for path in object_dir.iterdir() if path.is_file()) + + return { + "root": str(root.resolve()), + "subjects": sorted(subject_take_counts), + "take_count": sum(subject_take_counts.values()), + "take_counts_by_subject": dict(sorted(subject_take_counts.items())), + "rgb_frames_by_subject": dict(sorted(subject_rgb_frames.items())), + "rgb_frames_total": sum(subject_rgb_frames.values()), + "take_counts_by_subject_scene": dict(sorted(scene_take_counts.items())), + "camera_directories": dict(sorted(cameras.items())), + "modalities": serializable_modalities, + "frame_alignment_issue_takes": dict(sorted(alignment_issue_counts.items())), + "unexpected_frame_alignment_issue_takes": dict(sorted(unexpected_alignment_issue_counts.items())), + "frame_alignment_examples": alignment_examples, + "missing_modality_directory_takes": dict(sorted(missing_modality_directory_takes.items())), + "unexpected_modality_directory_takes": dict(sorted(unexpected_modality_directory_takes.items())), + "per_frame_label_counts": { + name: dict(sorted(counts.items(), key=lambda item: int(item[0]))) + for name, counts in scalar_label_counts.items() + }, + "hand_presence_counts": { + name: dict(sorted(counts.items())) for name, counts in hand_presence.items() + }, + "objects": object_stats, + "splits": inspect_splits(root), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path, help="Extracted H2O root") + parser.add_argument("--output", type=Path, help="Write JSON to this path") + args = parser.parse_args() + report = inspect_dataset(args.root) + payload = json.dumps(report, indent=2, ensure_ascii=False) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(payload, encoding="utf-8") + print(payload, end="") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/merge_phase9_hot_prefill.py b/home/wuyifan/EgoNet_train_20261008/scripts/merge_phase9_hot_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..a7db862b539b070f3f4174295d1c83bcbc7a2dfa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/merge_phase9_hot_prefill.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Atomically hardlink completed HOT3D prefill shards into a live cache.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path + +from scripts.cache_phase7_hot3d import sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_prefill_reports(reports: list[dict]) -> None: + if not reports: + raise ValueError("at least one prefill report is required") + for report in reports: + if ( + report.get("status") != "complete" + or report.get("mode") != "staged_prefill" + or report.get("official_test_used") is not False + ): + raise ValueError("prefill report is incomplete or lacks test isolation") + stable_keys = ( + "full_candidate_clips", "requested_target_clips", "max_recordings", + "candidate_source_indices_sha256", + ) + for key in stable_keys: + if len({json.dumps(report.get(key), sort_keys=True) for report in reports}) != 1: + raise ValueError(f"prefill reports disagree on {key}") + source_hashes = {report["source_manifest"]["sha256"] for report in reports} + if len(source_hashes) != 1: + raise ValueError("prefill reports disagree on source manifest SHA256") + ranges = sorted(tuple(report["candidate_position_range"]) for report in reports) + if any(first[1] > second[0] for first, second in zip(ranges, ranges[1:])): + raise ValueError("prefill position ranges overlap") + + +def merge_prefills( + target_output_dir: Path, prefill_output_dirs: list[Path], report_path: Path, +) -> dict: + reports = [ + json.loads((path / "cache_report.json").read_text(encoding="utf-8")) + for path in prefill_output_dirs + ] + validate_prefill_reports(reports) + target_clips = target_output_dir / "clips" + if not target_clips.is_dir(): + raise ValueError("target cache clips directory does not exist") + if (target_output_dir / "cache_manifest.jsonl").exists(): + raise ValueError("target deployable manifest is already frozen") + linked = existing_identical = 0 + shard_records = [] + for output_dir, report in zip(prefill_output_dirs, reports, strict=True): + manifest = output_dir / "prefill_manifest.jsonl" + if sha256(manifest) != report["cache_manifest"]["sha256"]: + raise ValueError(f"prefill manifest SHA256 differs: {manifest}") + rows = [ + json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if len(rows) != int(report["clips"]): + raise ValueError(f"prefill manifest row count differs: {manifest}") + for row in rows: + source = Path(row["cache_path"]) + expected_name = f"clip_{int(row['source_clip_index']):07d}.npz" + if source.name != expected_name or not source.is_file(): + raise ValueError(f"invalid staged cache path: {source}") + if sha256(source) != row["cache_sha256"]: + raise ValueError(f"staged cache SHA256 differs: {source}") + target = target_clips / expected_name + try: + os.link(source, target) + linked += 1 + except FileExistsError: + if sha256(target) != row["cache_sha256"]: + raise ValueError(f"target cache collision differs: {target}") + existing_identical += 1 + shard_records.append({ + "output_dir": str(output_dir.resolve()), + "report_sha256": sha256(output_dir / "cache_report.json"), + "manifest_sha256": sha256(manifest), + "candidate_position_range": report["candidate_position_range"], + "clips": len(rows), + }) + result = { + "schema_version": "phase9_hot_prefill_merge_v1", + "status": "complete", "created_utc": utc_now(), + "target_output_dir": str(target_output_dir.resolve()), + "linked": linked, "existing_identical": existing_identical, + "shards": shard_records, "official_test_used": False, + } + report_path.parent.mkdir(parents=True, exist_ok=True) + temporary = report_path.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(report_path) + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--target-output-dir", type=Path, required=True) + parser.add_argument("--prefill-output-dir", type=Path, action="append", required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + result = merge_prefills( + args.target_output_dir, args.prefill_output_dir, args.report, + ) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/merge_phase9_selection_binding_recovery.py b/home/wuyifan/EgoNet_train_20261008/scripts/merge_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..b71938506149e999f92a5aa6039455009504e185 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/merge_phase9_selection_binding_recovery.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""Dry-run, validate, and atomically merge Phase 9 selection recovery.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any, Callable + +from scripts.run_phase9_selection_binding_recovery import ( + atomic_json, + validate_recovered_output, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_release( + *, release_path: Path, plan_path: Path, plan: dict[str, Any], owner: str, +) -> dict[str, Any]: + if not release_path.is_file(): + raise ValueError(f"selection recovery release missing: {owner}") + release = json.loads(release_path.read_text(encoding="utf-8")) + root = release_path.parent.resolve() + expected_ids = { + item["id"] for item in plan["evaluations"] if item["owner"] == owner + } + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != owner + or release.get("plan", {}).get("sha256") != sha256(plan_path) + or Path(str(release.get("root", ""))).resolve() != root + or set(release.get("evaluation_ids", [])) != expected_ids + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or release.get("read_only_after_publish") is not True + ): + raise ValueError(f"selection recovery release contract differs: {owner}") + seen = set() + total_bytes = 0 + for item in release.get("files", []): + relative = Path(item["path"]) + if relative.is_absolute() or ".." in relative.parts or str(relative) in seen: + raise ValueError(f"invalid recovery release path: {relative}") + seen.add(str(relative)) + path = root / relative + if ( + not path.is_file() + or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"selection recovery release file differs: {path}") + total_bytes += item["bytes"] + if ( + len(seen) != release.get("file_count") + or total_bytes != release.get("total_bytes") + ): + raise ValueError(f"selection recovery release inventory differs: {owner}") + evidence = {item["id"]: item for item in release["evaluations"]} + if set(evidence) != expected_ids: + raise ValueError(f"selection recovery release evidence differs: {owner}") + for item in plan["evaluations"]: + if item["owner"] != owner: + continue + relative_output = Path(evidence[item["id"]]["output_dir"]) + if (root / relative_output).resolve() != Path(item["output_dir"]).resolve(): + raise ValueError(f"selection recovery output path differs: {item['id']}") + validate_recovered_output(item) + return release + + +def symlink_copy(source: str, destination: str) -> str: + os.symlink(str(Path(source).resolve()), destination) + return destination + + +def recovered_output_map( + plan: dict[str, Any], releases: dict[str, dict[str, Any]], + release_paths: dict[str, Path], +) -> dict[str, Path]: + result = {} + for owner, release in releases.items(): + root = release_paths[owner].parent.resolve() + by_id = {item["id"]: item for item in release["evaluations"]} + for item in plan["evaluations"]: + if item["owner"] == owner: + result[item["id"]] = root / by_id[item["id"]]["output_dir"] + return result + + +def run_dry_selection( + *, plan: dict[str, Any], recovered: dict[str, Path], +) -> dict[str, Any]: + selection_plan_path = Path(plan["selection_plan"]["path"]) + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + dry_root = Path(plan["dry_run_root"]) / sha256(selection_plan_path) + milestone_root = dry_root / "h2o_multifold_milestones" + output_json = dry_root / "unified_selection.json" + output_csv = dry_root / "unified_selection.csv" + if output_json.is_file() and output_csv.is_file(): + report = json.loads(output_json.read_text(encoding="utf-8")) + if ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + ): + return { + "root": str(dry_root.resolve()), + "json": {"path": str(output_json.resolve()), "sha256": sha256(output_json)}, + "csv": {"path": str(output_csv.resolve()), "sha256": sha256(output_csv)}, + "winner": report["winner"], + } + raise ValueError("existing selection dry-run output differs") + if dry_root.exists(): + shutil.rmtree(dry_root) + dry_root.mkdir(parents=True) + shutil.copytree( + Path(selection_plan["fold_milestone_root"]), milestone_root, + copy_function=symlink_copy, + ) + for item in plan["evaluations"]: + target = ( + milestone_root / item["condition"] / item["checkpoint_id"] + / item["input_mode"] + ) + if target.is_symlink() or target.is_file(): + target.unlink() + elif target.is_dir(): + shutil.rmtree(target) + os.symlink(str(recovered[item["id"]].resolve()), target, target_is_directory=True) + command = [ + sys.executable, "-m", "scripts.summarize_phase9_unified_selection", + "--external-root", selection_plan["external_root"], + "--fold-final-root", selection_plan["fold_final_root"], + "--fold-milestone-root", str(milestone_root.resolve()), + "--multifold-index", selection_plan["multifold_index"], + "--output-json", str(output_json.resolve()), + "--output-csv", str(output_csv.resolve()), + ] + log_path = dry_root / "summarizer.log" + with log_path.open("x", encoding="utf-8") as log: + result = subprocess.run( + command, cwd=Path.cwd(), stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + if result.returncode or not output_json.is_file() or not output_csv.is_file(): + raise ValueError(f"selection dry-run summarizer failed: {result.returncode}") + report = json.loads(output_json.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError("selection dry-run report isolation differs") + return { + "root": str(dry_root.resolve()), + "json": {"path": str(output_json.resolve()), "sha256": sha256(output_json)}, + "csv": {"path": str(output_csv.resolve()), "sha256": sha256(output_csv)}, + "log": {"path": str(log_path.resolve()), "sha256": sha256(log_path)}, + "winner": report["winner"], + } + + +def canonical_output(plan: dict[str, Any], item: dict[str, Any]) -> Path: + return ( + Path(plan["canonical_fold_milestone_root"]) + / item["condition"] / item["checkpoint_id"] / item["input_mode"] + ) + + +def prepare_outputs( + *, plan: dict[str, Any], recovered: dict[str, Path], +) -> dict[str, Path]: + prepared = {} + for item in plan["evaluations"]: + canonical = canonical_output(plan, item) + destination = canonical.parent / f".{canonical.name}.selection_recovery_v2_ready" + if destination.exists(): + shutil.rmtree(destination) + shutil.copytree(recovered[item["id"]], destination, copy_function=shutil.copy2) + candidate = {**item, "output_dir": str(destination.resolve())} + validate_recovered_output(candidate) + prepared[item["id"]] = destination + return prepared + + +def merge_outputs( + *, plan_path: Path, plan: dict[str, Any], prepared: dict[str, Path], + dry_run: dict[str, Any], releases: dict[str, dict[str, Any]], + release_paths: dict[str, Path], state_path: Path, +) -> dict[str, Any]: + backup_root = Path(plan["canonical_merge_backup_root"]) + backup_root.mkdir(parents=True, exist_ok=True) + lock_path = backup_root.parent / ".selection_binding_v2_merge.lock" + plan_hash = sha256(plan_path) + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if state_path.is_file(): + existing = json.loads(state_path.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == plan_hash + ): + return existing + if existing.get("plan_sha256") not in {None, plan_hash}: + raise ValueError("existing selection merge state differs") + replacements = [] + try: + for item in plan["evaluations"]: + canonical = canonical_output(plan, item) + backup = ( + backup_root / item["condition"] / item["checkpoint_id"] + / item["input_mode"] + ) + if backup.exists(): + raise ValueError(f"selection merge backup already exists: {backup}") + if not canonical.is_dir(): + raise ValueError(f"selection canonical output missing: {canonical}") + backup.parent.mkdir(parents=True, exist_ok=True) + os.replace(canonical, backup) + try: + os.replace(prepared[item["id"]], canonical) + except Exception: + os.replace(backup, canonical) + raise + replacements.append((item, canonical, backup)) + except Exception: + for item, canonical, backup in reversed(replacements): + staging = canonical.parent / f".{canonical.name}.rollback_recovered" + if staging.exists(): + shutil.rmtree(staging) + os.replace(canonical, staging) + os.replace(backup, canonical) + raise + merged = [] + for item, canonical, backup in replacements: + candidate = {**item, "output_dir": str(canonical.resolve())} + evidence = validate_recovered_output(candidate) + merged.append({ + "id": item["id"], "canonical_output": str(canonical.resolve()), + "backup_output": str(backup.resolve()), **evidence, + }) + state = { + "schema_version": "phase9_selection_binding_recovery_merge_state_v1", + "status": "complete", "completed_utc": datetime.now(timezone.utc).isoformat(), + "plan": str(plan_path.resolve()), "plan_sha256": plan_hash, + "dry_run": dry_run, + "releases": { + owner: { + "path": str(release_paths[owner].resolve()), + "sha256": sha256(release_paths[owner]), + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + } + for owner, release in releases.items() + }, + "merged": merged, + "failure_backup": plan["failure_backup"], + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(state_path, state) + return state + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--taku3-release", type=Path, required=True) + parser.add_argument("--server-new-release", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if ( + plan.get("official_test_used") is not False + or args.state.resolve() != Path(plan["canonical_merge_state"]).resolve() + ): + parser.error("selection merge plan/state contract differs") + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + parser.error(f"selection recovery code binding differs: {path}") + release_paths = { + "taku3": args.taku3_release, "server_new": args.server_new_release, + } + releases = { + owner: validate_release( + release_path=path, plan_path=args.plan, plan=plan, owner=owner, + ) + for owner, path in release_paths.items() + } + recovered = recovered_output_map(plan, releases, release_paths) + dry_run = run_dry_selection(plan=plan, recovered=recovered) + prepared = prepare_outputs(plan=plan, recovered=recovered) + state = merge_outputs( + plan_path=args.plan, plan=plan, prepared=prepared, dry_run=dry_run, + releases=releases, release_paths=release_paths, state_path=args.state, + ) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/merge_sota_bundles.py b/home/wuyifan/EgoNet_train_20261008/scripts/merge_sota_bundles.py new file mode 100644 index 0000000000000000000000000000000000000000..584ee70fdf4d271fce83b8faeacf785e8d0e4324 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/merge_sota_bundles.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Merge disjoint inference shards and restore official-manifest frame order.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("inputs", nargs="+", type=Path) + args = parser.parse_args() + bundles = [PredictionBundle.load(path) for path in args.inputs] + names = {bundle.model_name for bundle in bundles} + if len(names) != 1: + raise ValueError(f"Shard model names differ: {names}") + has_vertices = {bundle.vertices_camera_m is not None for bundle in bundles} + if len(has_vertices) != 1: + raise ValueError("Shard vertex availability differs") + keys, _, _ = load_frame_index(args.manifest) + order_lookup = {str(key): index for index, key in enumerate(keys)} + concatenated_keys = np.concatenate([bundle.frame_keys for bundle in bundles]) + if set(map(str, concatenated_keys.tolist())) != set(map(str, keys.tolist())): + raise ValueError("Merged shards do not exactly cover the manifest") + order = np.argsort([order_lookup[str(key)] for key in concatenated_keys]) + metadata = dict(bundles[0].metadata) + metadata.pop("num_shards", None) + metadata.pop("shard_index", None) + for name in ( + "refined_windows", + "missing_detection_windows", + "tail_hand_frames_falling_back_to_wilor", + "root_iterations_total", + "smooth_iterations_total", + "run_count", + "new_initializations", + "new_optimizations", + ): + if all(name in bundle.metadata for bundle in bundles): + metadata[name] = sum(int(bundle.metadata[name]) for bundle in bundles) + delta_name = "initializer_mesh_reconstruction_delta_mm" + if all(delta_name in bundle.metadata for bundle in bundles): + weights = np.asarray( + [int(bundle.metadata.get("refined_windows", 0)) for bundle in bundles], + dtype=np.float64, + ) + values = np.asarray( + [float(bundle.metadata[delta_name]) for bundle in bundles], + dtype=np.float64, + ) + if weights.sum() > 0: + metadata[delta_name] = float(np.average(values, weights=weights)) + metadata.update({ + "merged_shards": len(bundles), + "shard_inputs": [str(path.resolve()) for path in args.inputs], + }) + PredictionBundle( + model_name=bundles[0].model_name, + frame_keys=concatenated_keys[order], + takes=np.concatenate([bundle.takes for bundle in bundles])[order], + frame_ids=np.concatenate([bundle.frame_ids for bundle in bundles])[order], + joints_camera_m=np.concatenate([ + bundle.joints_camera_m for bundle in bundles + ])[order], + detected=np.concatenate([bundle.detected for bundle in bundles])[order], + confidence=np.concatenate([bundle.confidence for bundle in bundles])[order], + vertices_camera_m=( + np.concatenate([bundle.vertices_camera_m for bundle in bundles])[order] + if True in has_vertices + else None + ), + metadata=metadata, + ).save(args.output) + print(f"merged {len(bundles)} shards into {args.output}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/phase9_distributed_assignment.py b/home/wuyifan/EgoNet_train_20261008/scripts/phase9_distributed_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..a244226e86486c4dc547fe55431fa31f45e015c4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/phase9_distributed_assignment.py @@ -0,0 +1,156 @@ +"""Shared ownership checks for distributed Phase 9 controllers.""" + +from __future__ import annotations + +import json +from pathlib import Path +import socket +from typing import Any + +from scripts.run_phase9_unified_train_queue import sha256 + + +MACHINES = ("taku3", "server_new") + + +def load_assignment(plan: dict[str, Any]) -> dict[str, Any]: + binding = plan.get("distributed_assignment", {}) + path = Path(str(binding.get("path", ""))) + if not path.is_file() or sha256(path) != binding.get("sha256"): + raise ValueError("distributed assignment binding differs") + assignment = json.loads(path.read_text(encoding="utf-8")) + if ( + assignment.get("schema_version") + != "foundation_phase9_distributed_assignment_v2" + or assignment.get("central_owner") != "taku3" + or assignment.get("selection_owner") != "taku3" + or assignment.get("report_owner") != "taku3" + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + or assignment.get("writer_contract", {}).get( + "single_writer_per_output" + ) is not True + or assignment.get("writer_contract", {}).get( + "live_reverse_sync_forbidden" + ) is not True + ): + raise ValueError("distributed assignment contract differs") + return assignment + + +def detect_machine(assignment: dict[str, Any], requested: str | None) -> str: + host = socket.gethostname() + matches = [ + machine for machine in MACHINES + if assignment["machines"][machine]["hostname"] == host + ] + if requested is not None: + if requested not in MACHINES or assignment["machines"][requested]["hostname"] != host: + raise ValueError("requested distributed machine differs from hostname") + return requested + if len(matches) != 1: + raise ValueError(f"hostname is not uniquely assigned: {host}") + return matches[0] + + +def gpu_allowlist(assignment: dict[str, Any], machine: str) -> list[int]: + allowed = assignment["machines"][machine]["physical_gpu_allowlist"] + if ( + not isinstance(allowed, list) + or not allowed + or len(allowed) != len(set(allowed)) + or any(not isinstance(gpu, int) for gpu in allowed) + ): + raise ValueError(f"distributed GPU allowlist differs: {machine}") + if machine == "server_new" and allowed != [0, 1, 2, 5]: + raise ValueError("server_new GPU allowlist must be exactly 0/1/2/5") + return allowed + + +def role_owners(assignment: dict[str, Any]) -> dict[str, str]: + records = assignment["stage_condition_ownership"]["roles"] + result = {item["role"]: item["owner"] for item in records} + expected = { + "full", "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + } + if set(result) != expected or len(records) != len(result): + raise ValueError("distributed role ownership differs") + if any(owner not in MACHINES for owner in result.values()): + raise ValueError("distributed role owner is unknown") + return result + + +def condition_owners( + registry: dict[str, Any], assignment: dict[str, Any], +) -> dict[str, str]: + owners = role_owners(assignment) + result = {} + for item in registry["conditions"]: + condition = item["condition"] + role = item.get("role") + if role not in owners or condition in result: + raise ValueError(f"distributed training role differs: {condition}") + result[condition] = owners[role] + if len(result) != 7: + raise ValueError("distributed training registry must contain seven jobs") + return result + + +def controller_state_path(plan: dict[str, Any], machine: str) -> Path: + states = plan.get("controller_states", {}) + if set(states) != set(MACHINES): + raise ValueError("distributed controller states differ") + paths = [str(Path(value).resolve()) for value in states.values()] + if len(paths) != len(set(paths)): + raise ValueError("distributed controller states are not unique") + return Path(states[machine]) + + +def distribute_evaluations( + *, evaluations: list[dict[str, Any]], assignment: dict[str, Any], + worker_state_root: Path, +) -> list[dict[str, Any]]: + owners = role_owners(assignment) + grouped: dict[str, list[dict[str, Any]]] = {machine: [] for machine in MACHINES} + for item in evaluations: + role = item.get("training_role") + if role not in owners: + raise ValueError(f"distributed evaluation role differs: {item.get('id')}") + owner = owners[role] + item["owner"] = owner + grouped[owner].append(item) + workers = [] + for owner in MACHINES: + gpus = gpu_allowlist(assignment, owner) + buckets: dict[int, list[str]] = {gpu: [] for gpu in gpus} + for index, item in enumerate(grouped[owner]): + buckets[gpus[index % len(gpus)]].append(item["id"]) + for gpu, identifiers in buckets.items(): + if not identifiers: + continue + workers.append({ + "id": f"{owner}_gpu{gpu}", "owner": owner, + "physical_gpu_id": gpu, + "state": str(( + worker_state_root / owner / f"gpu{gpu}_state.json" + ).resolve()), + "evaluation_ids": identifiers, + }) + ids = [item["id"] for item in evaluations] + assigned = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(ids) != len(set(ids)) + or len(assigned) != len(ids) + or len(set(assigned)) != len(ids) + or set(assigned) != set(ids) + ): + raise ValueError("distributed evaluation workers overlap or omit IDs") + return workers + + +def local_workers(workers: list[dict[str, Any]], machine: str) -> list[dict[str, Any]]: + result = [item for item in workers if item.get("owner") == machine] + if any(item.get("owner") not in MACHINES for item in workers): + raise ValueError("distributed evaluation worker owner differs") + return result diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/postprocess_video_jitter.py b/home/wuyifan/EgoNet_train_20261008/scripts/postprocess_video_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..0b737af92d0fc6c2aa7713b0b03d209f6147eb86 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/postprocess_video_jitter.py @@ -0,0 +1,927 @@ +#!/usr/bin/env python3 +"""Cache raw long-sequence predictions and render jitter-smoothed MANO demos. + +This is an offline visualization postprocessor. It does not change the model, +checkpoint, evaluator, or reported metrics. Missing raw caches are reconstructed +with the exact checkpoint and non-overlapping temporal chunks recorded in the +source selection manifest. Later filter changes reuse those caches. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from scipy.signal import butter, sosfiltfilt +from scipy.spatial.transform import Rotation + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + MeshLayer, + project_mesh_layers, + render_mesh_layers, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.training.checkpoint import load_checkpoint + + +LEFT_COLOR_RGB = (40, 100, 235) +RIGHT_COLOR_RGB = (235, 55, 55) +MESH_ALPHA = 0.55 +CACHE_VERSION = 1 +RAW_CACHE_KEYS = ( + "mano_rotations_6d", + "mano_rotation_matrices", + "mano_shape", + "wrist_root_translation", + "vertices_camera", + "joints_camera", + "joint2d_norm", + "presence_logit", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_json_atomic(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + os.replace(temporary, path) + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def add_header(image_rgb: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image_rgb.copy() + height = 8 + 22 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, + line, + (8, 20 + 22 * index), + cv2.FONT_HERSHEY_SIMPLEX, + 0.55, + (255, 255, 255), + 1, + cv2.LINE_AA, + ) + return output + + +class FFmpegVideoWriter: + """Stream BGR frames to an atomic, Mac-compatible H.264 MP4.""" + + def __init__( + self, + path: Path, + fps: float, + frame_hw: tuple[int, int], + *, + crf: int, + preset: str, + ) -> None: + self.path = path + self.frame_hw = frame_hw + self.frames_written = 0 + path.parent.mkdir(parents=True, exist_ok=True) + self.temporary = path.with_name(f".{path.stem}.tmp-{os.getpid()}.mp4") + height, width = frame_hw + command = [ + "ffmpeg", + "-nostdin", + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "rawvideo", + "-pix_fmt", + "bgr24", + "-s:v", + f"{width}x{height}", + "-r", + f"{fps:.8g}", + "-i", + "pipe:0", + "-an", + "-c:v", + "libx264", + "-preset", + preset, + "-crf", + str(crf), + "-pix_fmt", + "yuv420p", + "-movflags", + "+faststart", + str(self.temporary), + ] + self.process = subprocess.Popen( + command, + stdin=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + def write(self, frame_bgr: np.ndarray) -> None: + height, width = self.frame_hw + if frame_bgr.shape != (height, width, 3) or frame_bgr.dtype != np.uint8: + raise ValueError( + f"invalid video frame {frame_bgr.shape}/{frame_bgr.dtype}; " + f"expected {(height, width, 3)}/uint8" + ) + if self.process.stdin is None: + raise RuntimeError("ffmpeg stdin is unavailable") + try: + self.process.stdin.write(np.ascontiguousarray(frame_bgr).tobytes()) + except BrokenPipeError as error: + stderr = self._read_stderr() + raise RuntimeError(f"ffmpeg stopped while writing {self.path}: {stderr}") from error + self.frames_written += 1 + + def _read_stderr(self) -> str: + if self.process.stderr is None: + return "" + return self.process.stderr.read().decode("utf-8", errors="replace").strip() + + def close(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + stderr = self._read_stderr() + return_code = self.process.wait() + if return_code != 0: + self.temporary.unlink(missing_ok=True) + raise RuntimeError(f"ffmpeg failed for {self.path}: {stderr}") + os.replace(self.temporary, self.path) + + def abort(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + if self.process.poll() is None: + self.process.terminate() + try: + self.process.wait(timeout=5) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + self.temporary.unlink(missing_ok=True) + + +def lowpass(values: np.ndarray, cutoff_hz: float, fps: float, order: int) -> np.ndarray: + if not 0.0 < cutoff_hz < fps / 2.0: + raise ValueError(f"cutoff must be in (0, {fps / 2.0}), got {cutoff_hz}") + if values.shape[0] < max(12, order * 6): + raise ValueError(f"sequence too short for zero-phase filtering: {values.shape[0]}") + sections = butter(order, cutoff_hz, btype="lowpass", fs=fps, output="sos") + return np.asarray(sosfiltfilt(sections, values, axis=0), dtype=np.float32) + + +def smooth_rotations( + matrices: np.ndarray, + cutoff_hz: float, + fps: float, + order: int, +) -> np.ndarray: + """Low-pass SO(3) trajectories through sign-continuous unit quaternions.""" + + if matrices.ndim != 5 or matrices.shape[1:] != (2, 16, 3, 3): + raise ValueError(f"unexpected rotation shape: {matrices.shape}") + frame_count = matrices.shape[0] + quaternions = Rotation.from_matrix(matrices.reshape(-1, 3, 3)).as_quat() + quaternions = quaternions.reshape(frame_count, 2, 16, 4) + for frame_index in range(1, frame_count): + dots = np.sum( + quaternions[frame_index - 1] * quaternions[frame_index], + axis=-1, + ) + quaternions[frame_index][dots < 0.0] *= -1.0 + filtered = lowpass(quaternions, cutoff_hz, fps, order) + norms = np.linalg.norm(filtered, axis=-1, keepdims=True) + if np.any(norms < 1e-6): + raise RuntimeError("quaternion low-pass produced a near-zero norm") + filtered /= norms + smoothed = Rotation.from_quat(filtered.reshape(-1, 4)).as_matrix() + return smoothed.reshape(matrices.shape).astype(np.float32) + + +def smooth_prediction( + raw: dict[str, np.ndarray], + *, + translation_cutoff_hz: float, + rotation_cutoff_hz: float, + fps: float, + order: int, +) -> dict[str, np.ndarray]: + shape = raw["mano_shape"] + stable_shape = np.median(shape, axis=0, keepdims=True).astype(np.float32) + return { + "frame_ids": raw["frame_ids"].copy(), + "mano_rotation_matrices": smooth_rotations( + raw["mano_rotation_matrices"], rotation_cutoff_hz, fps, order + ), + "mano_shape": np.repeat(stable_shape, shape.shape[0], axis=0), + "wrist_root_translation": lowpass( + raw["wrist_root_translation"], translation_cutoff_hz, fps, order + ), + } + + +def build_model( + config: dict[str, Any], + checkpoint_path: Path, + checkpoint_step: int, + device: torch.device, +) -> BimanualReconstructionModel: + assets = config["assets"] + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + state = load_checkpoint(checkpoint_path, model, optimizer=None, map_location=device) + if int(state["step"]) != checkpoint_step: + raise ValueError( + f"checkpoint step mismatch: expected {checkpoint_step}, got {state['step']}" + ) + return model + + +def infer_case( + *, + case: dict[str, Any], + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + checkpoint_sha256: str, +) -> dict[str, np.ndarray]: + values: dict[str, list[np.ndarray]] = defaultdict(list) + observed_frame_ids: list[int] = [] + for clip_number, clip_index in enumerate(clip_indices, start=1): + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + clip_frame_ids = sample["frame_id"].cpu().numpy().astype(np.int32) + observed_frame_ids.extend(int(value) for value in clip_frame_ids) + for key in RAW_CACHE_KEYS: + if key in prediction: + values[key].append(prediction[key][0].float().cpu().numpy()) + del prediction, batch + if clip_number % 25 == 0 or clip_number == len(clip_indices): + print( + f" inference {clip_number}/{len(clip_indices)} chunks " + f"({len(observed_frame_ids)}/{len(case['frame_ids'])} frames)", + flush=True, + ) + + expected_frame_ids = [int(value) for value in case["frame_ids"]] + if observed_frame_ids != expected_frame_ids: + raise RuntimeError( + f"inference frame mismatch for {case['take']}: " + f"{len(observed_frame_ids)} != {len(expected_frame_ids)}" + ) + arrays = { + key: np.concatenate(chunks, axis=0).astype(np.float32) + for key, chunks in values.items() + } + arrays.update({ + "frame_ids": np.asarray(observed_frame_ids, dtype=np.int32), + "take": np.asarray(str(case["take"])), + "checkpoint_sha256": np.asarray(checkpoint_sha256), + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + }) + required = { + "mano_rotation_matrices", + "mano_shape", + "wrist_root_translation", + "vertices_camera", + "joints_camera", + } + missing = sorted(required - arrays.keys()) + if missing: + raise RuntimeError(f"model output is missing cache fields: {missing}") + for key, value in arrays.items(): + if np.issubdtype(value.dtype, np.floating) and not np.isfinite(value).all(): + raise RuntimeError(f"non-finite values in raw output {key} for {case['take']}") + return arrays + + +def load_raw_cache( + path: Path, + *, + case: dict[str, Any], + checkpoint_sha256: str, +) -> dict[str, np.ndarray] | None: + if not path.is_file(): + return None + try: + with np.load(path, allow_pickle=False) as archive: + raw = {key: archive[key] for key in archive.files} + if int(raw["cache_version"]) != CACHE_VERSION: + return None + if str(raw["take"]) != str(case["take"]): + return None + if str(raw["checkpoint_sha256"]) != checkpoint_sha256: + return None + expected = np.asarray(case["frame_ids"], dtype=np.int32) + if not np.array_equal(raw["frame_ids"], expected): + return None + return raw + except (KeyError, OSError, ValueError): + return None + + +def rebuild_mano_geometry( + prediction: dict[str, np.ndarray], + mano_layer: ManoCameraLayer, + device: torch.device, + *, + batch_size: int = 128, +) -> None: + vertices: list[np.ndarray] = [] + joints: list[np.ndarray] = [] + frame_count = prediction["frame_ids"].shape[0] + for start in range(0, frame_count, batch_size): + stop = min(start + batch_size, frame_count) + rotations = torch.from_numpy( + prediction["mano_rotation_matrices"][start:stop] + ).to(device) + shape = torch.from_numpy(prediction["mano_shape"][start:stop]).to(device) + translation = torch.from_numpy( + prediction["wrist_root_translation"][start:stop] + ).to(device) + with torch.inference_mode(): + vertex_batch, joint_batch = mano_layer(rotations, shape, translation) + vertices.append(vertex_batch.float().cpu().numpy()) + joints.append(joint_batch.float().cpu().numpy()) + prediction["vertices_camera"] = np.concatenate(vertices, axis=0).astype(np.float32) + prediction["joints_camera"] = np.concatenate(joints, axis=0).astype(np.float32) + + +def acceleration_stats(points_m: np.ndarray) -> dict[str, float]: + acceleration_mm = np.linalg.norm(np.diff(points_m, n=2, axis=0), axis=-1) * 1000.0 + return { + "mean_mm_per_frame2": float(acceleration_mm.mean()), + "p50_mm_per_frame2": float(np.percentile(acceleration_mm, 50)), + "p95_mm_per_frame2": float(np.percentile(acceleration_mm, 95)), + } + + +def displacement_stats(raw_m: np.ndarray, smoothed_m: np.ndarray) -> dict[str, float]: + displacement_mm = np.linalg.norm(smoothed_m - raw_m, axis=-1) * 1000.0 + return { + "mean_mm": float(displacement_mm.mean()), + "p50_mm": float(np.percentile(displacement_mm, 50)), + "p95_mm": float(np.percentile(displacement_mm, 95)), + "max_mm": float(displacement_mm.max()), + } + + +def rotation_displacement_stats( + raw_matrices: np.ndarray, + smoothed_matrices: np.ndarray, +) -> dict[str, float]: + relative = np.swapaxes(raw_matrices, -1, -2) @ smoothed_matrices + radians = Rotation.from_matrix(relative.reshape(-1, 3, 3)).magnitude() + degrees = np.degrees(radians) + return { + "mean_degrees": float(degrees.mean()), + "p50_degrees": float(np.percentile(degrees, 50)), + "p95_degrees": float(np.percentile(degrees, 95)), + "max_degrees": float(degrees.max()), + } + + +def jitter_metrics( + raw: dict[str, np.ndarray], + smoothed: dict[str, np.ndarray], +) -> dict[str, Any]: + raw_wrist = acceleration_stats(raw["wrist_root_translation"]) + smooth_wrist = acceleration_stats(smoothed["wrist_root_translation"]) + raw_vertices = acceleration_stats(raw["vertices_camera"]) + smooth_vertices = acceleration_stats(smoothed["vertices_camera"]) + + def reduction(raw_value: float, smooth_value: float) -> float: + return float((1.0 - smooth_value / max(raw_value, 1e-12)) * 100.0) + + return { + "wrist_acceleration_raw": raw_wrist, + "wrist_acceleration_smoothed": smooth_wrist, + "wrist_acceleration_mean_reduction_percent": reduction( + raw_wrist["mean_mm_per_frame2"], smooth_wrist["mean_mm_per_frame2"] + ), + "vertex_acceleration_raw": raw_vertices, + "vertex_acceleration_smoothed": smooth_vertices, + "vertex_acceleration_mean_reduction_percent": reduction( + raw_vertices["mean_mm_per_frame2"], + smooth_vertices["mean_mm_per_frame2"], + ), + "wrist_filter_displacement": displacement_stats( + raw["wrist_root_translation"], smoothed["wrist_root_translation"] + ), + "vertex_filter_displacement": displacement_stats( + raw["vertices_camera"], smoothed["vertices_camera"] + ), + "rotation_filter_displacement": rotation_displacement_stats( + raw["mano_rotation_matrices"], smoothed["mano_rotation_matrices"] + ), + "raw_shape_temporal_std_mean": float(raw["mano_shape"].std(axis=0).mean()), + } + + +def probe_video(path: Path, expected_frames: int, frame_hw: tuple[int, int]) -> None: + command = [ + "ffprobe", + "-v", + "error", + "-select_streams", + "v:0", + "-count_frames", + "-show_entries", + "stream=codec_name,pix_fmt,width,height,nb_read_frames", + "-of", + "json", + str(path), + ] + report = json.loads(subprocess.check_output(command, text=True)) + streams = report.get("streams", []) + if len(streams) != 1: + raise RuntimeError(f"expected one video stream in {path}") + stream = streams[0] + height, width = frame_hw + observed = ( + stream.get("codec_name"), + stream.get("pix_fmt"), + int(stream.get("width", -1)), + int(stream.get("height", -1)), + int(stream.get("nb_read_frames", -1)), + ) + expected = ("h264", "yuv420p", width, height, expected_frames) + if observed != expected: + raise RuntimeError(f"video validation failed for {path}: {observed} != {expected}") + + +def render_case( + *, + case: dict[str, Any], + raw: dict[str, np.ndarray], + smoothed: dict[str, np.ndarray], + source_case_dir: Path, + output_case_dir: Path, + data_root: Path, + faces: tuple[np.ndarray, np.ndarray], + fps: float, + translation_cutoff_hz: float, + rotation_cutoff_hz: float, + filter_order: int, + crf: int, + preset: str, +) -> dict[str, Any]: + output_case_dir.mkdir(parents=True, exist_ok=True) + take_dir = data_root / str(case["take"]) + raw_K, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + height, width = source_hw + output_paths = { + "smoothed_overlay": output_case_dir / "predicted_mano_overlay_smoothed.mp4", + "smoothed_side_by_side": output_case_dir / "side_by_side_smoothed.mp4", + "raw_vs_smoothed": output_case_dir / "raw_vs_smoothed.mp4", + } + writers = [ + FFmpegVideoWriter(output_paths["smoothed_overlay"], fps, source_hw, crf=crf, preset=preset), + FFmpegVideoWriter( + output_paths["smoothed_side_by_side"], + fps, + (height, width * 2), + crf=crf, + preset=preset, + ), + FFmpegVideoWriter( + output_paths["raw_vs_smoothed"], + fps, + (height, width * 2), + crf=crf, + preset=preset, + ), + ] + raw_overlay_path = source_case_dir / "predicted_mano_overlay.mp4" + raw_capture = cv2.VideoCapture(str(raw_overlay_path)) + if not raw_capture.isOpened(): + for writer in writers: + writer.abort() + raise RuntimeError(f"failed to open source overlay: {raw_overlay_path}") + + frame_ids = [int(value) for value in case["frame_ids"]] + preview = None + comparison_preview = None + try: + for frame_index, frame_id in enumerate(frame_ids): + raw_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), + cv2.IMREAD_COLOR, + ) + if raw_bgr is None or raw_bgr.shape[:2] != source_hw: + raise RuntimeError(f"raw RGB decode/shape failure: {take_dir}/{frame_id}") + ok, source_overlay_bgr = raw_capture.read() + if not ok or source_overlay_bgr.shape[:2] != source_hw: + raise RuntimeError( + f"source overlay ended at frame {frame_index}: {raw_overlay_path}" + ) + raw_rgb = cv2.cvtColor(raw_bgr, cv2.COLOR_BGR2RGB) + layers = [ + MeshLayer( + smoothed["vertices_camera"][frame_index, hand], + faces[hand], + LEFT_COLOR_RGB if hand == 0 else RIGHT_COLOR_RGB, + MESH_ALPHA, + ) + for hand in range(2) + ] + rendered = render_mesh_layers(raw_rgb, project_mesh_layers(layers, raw_K)) + rendered = add_header(rendered, ( + f"Post-processed MANO | zero-phase low-pass | left=BLUE right=RED alpha={MESH_ALPHA:.2f}", + f"{case['subject']}/{case['sequence']} | frame={frame_id} " + f"({frame_index + 1}/{len(frame_ids)}) | translation={translation_cutoff_hz:g} Hz " + f"rotation={rotation_cutoff_hz:g} Hz order={filter_order}", + )) + original_panel = add_header(raw_rgb, ("Original cam4 RGB",)) + side_by_side = np.concatenate((original_panel, rendered), axis=1) + source_overlay_rgb = cv2.cvtColor(source_overlay_bgr, cv2.COLOR_BGR2RGB) + raw_vs_smoothed = np.concatenate((source_overlay_rgb, rendered), axis=1) + + writers[0].write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + writers[1].write(cv2.cvtColor(side_by_side, cv2.COLOR_RGB2BGR)) + writers[2].write(cv2.cvtColor(raw_vs_smoothed, cv2.COLOR_RGB2BGR)) + if frame_index == len(frame_ids) // 2: + preview = rendered.copy() + comparison_preview = raw_vs_smoothed.copy() + if (frame_index + 1) % 100 == 0 or frame_index + 1 == len(frame_ids): + print(f" render {frame_index + 1}/{len(frame_ids)} frames", flush=True) + + extra, _ = raw_capture.read() + if extra: + raise RuntimeError(f"source overlay has extra frames: {raw_overlay_path}") + for writer in writers: + writer.close() + except BaseException: + for writer in writers: + if writer.process.poll() is None or writer.temporary.exists(): + writer.abort() + raise + finally: + raw_capture.release() + + if preview is None or comparison_preview is None: + raise RuntimeError(f"no preview generated for {case['take']}") + preview_path = output_case_dir / "preview_smoothed.png" + comparison_preview_path = output_case_dir / "preview_raw_vs_smoothed.png" + cv2.imwrite(str(preview_path), cv2.cvtColor(preview, cv2.COLOR_RGB2BGR)) + cv2.imwrite( + str(comparison_preview_path), + cv2.cvtColor(comparison_preview, cv2.COLOR_RGB2BGR), + ) + probe_video(output_paths["smoothed_overlay"], len(frame_ids), source_hw) + probe_video( + output_paths["smoothed_side_by_side"], + len(frame_ids), + (height, width * 2), + ) + probe_video( + output_paths["raw_vs_smoothed"], + len(frame_ids), + (height, width * 2), + ) + metrics = jitter_metrics(raw, smoothed) + record = { + "take": case["take"], + "subject": case["subject"], + "sequence": case["sequence"], + "category": case["category"], + "rank": case["rank"], + "frame_count": len(frame_ids), + "source_case": str(source_case_dir.resolve()), + "raw_prediction_cache": str((output_case_dir / "raw_prediction.npz").resolve()), + "smoothed_prediction_cache": str( + (output_case_dir / "smoothed_prediction.npz").resolve() + ), + "videos": {key: str(path.resolve()) for key, path in output_paths.items()}, + "preview": str(preview_path.resolve()), + "raw_vs_smoothed_preview": str(comparison_preview_path.resolve()), + "jitter_metrics": metrics, + } + write_json_atomic(output_case_dir / "case_postprocess.json", record) + record["preview_rgb"] = preview + return record + + +def save_contact_sheet(path: Path, records: list[dict[str, Any]]) -> None: + if not records: + return + panels = [] + for record in records: + panel = cv2.resize(record["preview_rgb"], (384, 216), interpolation=cv2.INTER_AREA) + panel = add_header(panel, ( + f"{record['category']} #{record['rank']} | " + f"jitter -{record['jitter_metrics']['vertex_acceleration_mean_reduction_percent']:.1f}%", + )) + panels.append(panel) + while len(panels) % 5: + panels.append(np.zeros_like(panels[0])) + rows = [np.concatenate(panels[index : index + 5], axis=1) for index in range(0, len(panels), 5)] + sheet = np.concatenate(rows, axis=0) + cv2.imwrite(str(path), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR)) + + +def source_case_directory(source_dir: Path, case: dict[str, Any]) -> Path: + category_dir = "best_cases" if case["category"] == "best" else "failure_cases" + recorded = Path(case["videos"]["original"]).parent.name + path = source_dir / category_dir / recorded + if not path.is_dir(): + raise FileNotFoundError(f"source case directory missing: {path}") + return path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Re-infer missing raw MANO caches and render zero-phase jitter-smoothed demos." + ) + parser.add_argument( + "--source-dir", + type=Path, + default=Path("artifacts/phase3/video_cases_best_model_long_sequences"), + ) + parser.add_argument("--output-dir", type=Path) + parser.add_argument("--data-root", type=Path, default=Path("data/H2O/extracted")) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--category", choices=("all", "best", "failure"), default="all") + parser.add_argument("--max-cases", type=int) + parser.add_argument("--translation-cutoff-hz", type=float, default=3.0) + parser.add_argument("--rotation-cutoff-hz", type=float, default=4.0) + parser.add_argument("--filter-order", type=int, default=2) + parser.add_argument("--crf", type=int, default=18) + parser.add_argument( + "--ffmpeg-preset", + choices=("ultrafast", "superfast", "veryfast", "faster", "fast", "medium"), + default="fast", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + source_dir = args.source_dir.resolve() + if args.output_dir is None: + output_dir = source_dir.with_name(f"{source_dir.name}_smoothed") + else: + output_dir = args.output_dir.resolve() + data_root = args.data_root.resolve() + if source_dir == output_dir: + raise ValueError("source and output directories must differ") + if args.filter_order < 1: + raise ValueError("filter order must be positive") + if not 0 <= args.crf <= 51: + raise ValueError("CRF must be in [0, 51]") + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required to reconstruct missing raw prediction caches") + device = torch.device(f"cuda:{args.gpu}") + + selection_path = source_dir / "selection_manifest.json" + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if selection.get("status") != "complete" or selection.get("official_test_used") is not False: + raise ValueError("source selection manifest is incomplete or uses official test data") + config_path = Path(selection["config"]) + checkpoint = selection["checkpoint"] + checkpoint_path = Path(checkpoint["path"]) + expected_checkpoint_hash = str(checkpoint["sha256"]) + observed_checkpoint_hash = sha256(checkpoint_path) + if observed_checkpoint_hash != expected_checkpoint_hash: + raise ValueError("checkpoint hash differs from the source selection manifest") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + fps = float(selection["visualization_fps"]) + lowpass(np.zeros((32, 1), dtype=np.float32), args.translation_cutoff_hz, fps, args.filter_order) + lowpass(np.zeros((32, 1), dtype=np.float32), args.rotation_cutoff_hz, fps, args.filter_order) + + cases = [ + case + for case in selection["cases"] + if args.category == "all" or case["category"] == args.category + ] + if args.max_cases is not None: + if args.max_cases < 1: + raise ValueError("max cases must be positive") + cases = cases[: args.max_cases] + if not cases: + raise ValueError(f"no cases selected for category={args.category}") + output_dir.mkdir(parents=True, exist_ok=True) + + data_config = config["data"] + render_manifest_path = source_dir / "render_input_manifest.jsonl" + model_t = int(data_config["T"]) + dataset = H2OCam4Dataset( + data_root, + render_manifest_path, + tuple(data_config["resolution_hw"]), + (model_t,), + (int(data_config["stride"]),), + ) + clip_indices_by_take: dict[str, list[int]] = defaultdict(list) + for clip_index, clip in enumerate(dataset.clips): + clip_indices_by_take[clip.take].append(clip_index) + + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model: BimanualReconstructionModel | None = None + mano_layer: ManoCameraLayer | None = None + faces: tuple[np.ndarray, np.ndarray] | None = None + records: list[dict[str, Any]] = [] + for case_index, case in enumerate(cases, start=1): + source_case_dir = source_case_directory(source_dir, case) + category_dir = "best_cases" if case["category"] == "best" else "failure_cases" + output_case_dir = output_dir / category_dir / source_case_dir.name + output_case_dir.mkdir(parents=True, exist_ok=True) + raw_cache_path = output_case_dir / "raw_prediction.npz" + print( + f"[{case_index}/{len(cases)}] {case['category']} #{case['rank']} " + f"{case['take']} ({len(case['frame_ids'])} frames)", + flush=True, + ) + raw = load_raw_cache( + raw_cache_path, + case=case, + checkpoint_sha256=expected_checkpoint_hash, + ) + if raw is None: + if model is None: + print("loading frozen model checkpoint", flush=True) + model = build_model( + config, + checkpoint_path, + int(checkpoint["step"]), + device, + ) + mano_layer = model.mano_layer + if mano_layer is None: + raise RuntimeError("loaded model has no MANO layer") + faces = tuple(layer.th_faces.cpu().numpy() for layer in mano_layer.layers) + raw = infer_case( + case=case, + dataset=dataset, + clip_indices=clip_indices_by_take[str(case["take"])], + model=model, + device=device, + dtype=dtype, + checkpoint_sha256=expected_checkpoint_hash, + ) + save_npz_atomic(raw_cache_path, raw) + print(f" saved raw cache: {raw_cache_path}", flush=True) + else: + print(f" reusing raw cache: {raw_cache_path}", flush=True) + + if mano_layer is None: + mano_layer = ManoCameraLayer(config["assets"]["mano_root"]).to(device).eval() + if faces is None: + faces = tuple(layer.th_faces.cpu().numpy() for layer in mano_layer.layers) + smoothed = smooth_prediction( + raw, + translation_cutoff_hz=args.translation_cutoff_hz, + rotation_cutoff_hz=args.rotation_cutoff_hz, + fps=fps, + order=args.filter_order, + ) + rebuild_mano_geometry(smoothed, mano_layer, device) + save_npz_atomic(output_case_dir / "smoothed_prediction.npz", smoothed) + record = render_case( + case=case, + raw=raw, + smoothed=smoothed, + source_case_dir=source_case_dir, + output_case_dir=output_case_dir, + data_root=data_root, + faces=faces, + fps=fps, + translation_cutoff_hz=args.translation_cutoff_hz, + rotation_cutoff_hz=args.rotation_cutoff_hz, + filter_order=args.filter_order, + crf=args.crf, + preset=args.ffmpeg_preset, + ) + records.append(record) + print( + " mean vertex acceleration reduction: " + f"{record['jitter_metrics']['vertex_acceleration_mean_reduction_percent']:.1f}%", + flush=True, + ) + + save_contact_sheet(output_dir / "contact_sheet_smoothed.png", records) + serializable_records = [ + {key: value for key, value in record.items() if key != "preview_rgb"} + for record in records + ] + summary = { + "status": "complete", + "purpose": "offline visualization-only jitter postprocessing", + "source_dir": str(source_dir), + "source_selection_manifest": str(selection_path), + "checkpoint": checkpoint, + "model_inference_policy": ( + f"same frozen checkpoint and non-overlapping T={model_t} chunks as source render" + ), + "raw_cache_policy": ( + "render-relevant raw outputs are cached before filtering and reused on later runs" + ), + "postprocessing": { + "translation": "zero-phase Butterworth low-pass in camera XYZ", + "translation_cutoff_hz": args.translation_cutoff_hz, + "rotation": "zero-phase Butterworth low-pass on sign-continuous unit quaternions", + "rotation_cutoff_hz": args.rotation_cutoff_hz, + "filter_order": args.filter_order, + "shape": "per-take temporal median, held constant", + "fps": fps, + "phase_lag_frames": 0, + }, + "video_encoding": { + "codec": "H.264", + "pixel_format": "yuv420p", + "crf": args.crf, + "preset": args.ffmpeg_preset, + }, + "metrics_are_official_evaluation": False, + "cases": serializable_records, + } + write_json_atomic(output_dir / "postprocess_manifest.json", summary) + mean_reductions = [ + record["jitter_metrics"]["vertex_acceleration_mean_reduction_percent"] + for record in records + ] + readme = f"""# Jitter-Smoothed Long-Sequence Video Cases + +This directory is a visualization-only postprocessing of `{source_dir}`. The +model, checkpoint, official evaluation, and source artifacts are unchanged. + +Missing predictions were reconstructed with the same frozen checkpoint and +non-overlapping T={model_t} inference policy as the source demo. Each case keeps +`raw_prediction.npz` before filtering, so filter parameters can be adjusted and +videos regenerated without running the reconstruction model again. + +The offline filter is a zero-phase order-{args.filter_order} Butterworth low-pass: + +- wrist translation cutoff: {args.translation_cutoff_hz:g} Hz; +- MANO rotation cutoff: {args.rotation_cutoff_hz:g} Hz; +- MANO shape: temporal median held fixed within each take. + +Zero-phase filtering introduces no visual time shift but uses future frames, so +these videos do not represent a causal real-time system. H.264/yuv420p output is +used for macOS playback. `raw_vs_smoothed.mp4` is the clearest A/B view. + +Across the {len(records)} rendered cases, mean per-case vertex-acceleration +reduction is {float(np.mean(mean_reductions)):.1f}%. See +`postprocess_manifest.json` and each `case_postprocess.json` for details. +""" + (output_dir / "README.md").write_text(readme, encoding="utf-8") + print(json.dumps({ + "status": "complete", + "output_dir": str(output_dir), + "case_count": len(records), + "mean_vertex_acceleration_reduction_percent": float(np.mean(mean_reductions)), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/prepare_phase9_storage_overflow.py b/home/wuyifan/EgoNet_train_20261008/scripts/prepare_phase9_storage_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..8e5f5a81b71ffeca38c3c4a0820da0a212058a66 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/prepare_phase9_storage_overflow.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Bind unopened Phase 9 fold outputs to a larger physical volume.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def bind_directory(logical: Path, physical: Path) -> str: + if logical.is_symlink(): + if logical.resolve() != physical.resolve(): + raise RuntimeError(f"existing symlink has wrong target: {logical}") + return "existing_identical" + if logical.exists(): + raise RuntimeError(f"logical output already exists: {logical}") + physical.mkdir(parents=True, exist_ok=True) + logical.parent.mkdir(parents=True, exist_ok=True) + os.symlink(physical, logical, target_is_directory=True) + if not logical.is_symlink() or logical.resolve() != physical.resolve(): + raise RuntimeError(f"failed to bind output: {logical}") + return "created" + + +def prepare(plan: dict[str, Any], plan_path: Path) -> dict[str, Any]: + if plan.get("official_test_used") is not False: + raise ValueError("plan must explicitly exclude official test") + registry_path = Path(plan["fold_training_registry"]) + if sha256(registry_path) != plan["fold_training_registry_sha256"]: + raise ValueError("fold registry hash mismatch") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + raise ValueError("fold registry must explicitly exclude official test") + conditions = {row["condition"]: row for row in registry["conditions"]} + logical_roots = { + key: Path(value) for key, value in plan["logical_evaluation_roots"].items() + } + physical_root = Path(plan["physical_root"]) + rows = [] + for condition_id in plan["conditions"]: + if condition_id not in conditions: + raise ValueError(f"condition is absent from registry: {condition_id}") + condition = conditions[condition_id] + bindings = { + "run": ( + Path(condition["output_dir"]), + physical_root / "runs" / "h2o_multifold" / condition_id.lower(), + ), + "final_evaluation": ( + logical_roots["final"] / condition_id, + physical_root / "evaluations" / "h2o_multifold" / condition_id, + ), + "milestone_evaluation": ( + logical_roots["milestone"] / condition_id, + physical_root / "evaluations" / "h2o_multifold_milestones" / condition_id, + ), + } + for kind, (logical, physical) in bindings.items(): + status = bind_directory(logical, physical) + rows.append({ + "condition": condition_id, "kind": kind, "status": status, + "logical": str(logical), "physical": str(physical), + }) + return { + "schema_version": "phase9_storage_overflow_report_v1", + "status": "complete", + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "bindings": rows, + "scientific_protocol_changed": False, + "official_test_used": False, + "completed_utc": utc_now(), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output report already exists") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + report = prepare(plan, args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/probe_memory.py b/home/wuyifan/EgoNet_train_20261008/scripts/probe_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..c37fb1447ab5553ded97429d5473f5c2582a7123 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/probe_memory.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""4090 memory matrix using official random DINOv3 architecture (never training).""" + +from __future__ import annotations + +import argparse +import csv +import json +import platform +import time +from pathlib import Path + +import torch +from torch import nn + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.encoders import PatchFeatures + + +class ProbeDinoEncoder(nn.Module): + def __init__(self, backbone: nn.Module, output_dim: int = 512) -> None: + super().__init__() + self.backbone = backbone.requires_grad_(False).eval() + self.projection = nn.Linear(768, output_dim) + self.patch_size = 16 + + def train(self, mode: bool = True): + super().train(mode) + self.backbone.eval() + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + with torch.no_grad(): + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + return PatchFeatures(self.projection(raw), (images.shape[-2] // 16, images.shape[-1] // 16), 16) + + +def make_batch(batch_size: int, time_steps: int, height: int, width: int, device: torch.device) -> dict[str, torch.Tensor]: + K = torch.tensor([[width * 0.5, 0, width * 0.5], [0, width * 0.5, height * 0.5], [0, 0, 1]], device=device, dtype=torch.float32) + return { + "rgb": torch.randn(batch_size, time_steps, 3, height, width, device=device), + "depth_m": torch.rand(batch_size, time_steps, 1, height, width, device=device) + 0.3, + "depth_pixel_valid": torch.ones(batch_size, time_steps, 1, height, width, device=device, dtype=torch.bool), + "K": K[None, None].expand(batch_size, time_steps, -1, -1).clone(), + "K_available": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + "depth_available": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + "frame_valid": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + } + + +def run_case(backbone: nn.Module, case: dict[str, object], device: torch.device) -> dict[str, object]: + height, width = case["height"], case["width"] + dtype = torch.bfloat16 if case["precision"] == "bf16" else torch.float16 + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats(device) + config = ModelConfig( + encoder="tiny_debug", decoder_dim=512, decoder_layers=int(case["decoder_layers"]), attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, depth_mode="log_depth", use_rays=True, + use_bimanual_interaction=True, gradient_checkpointing=bool(case["gradient_checkpointing"]), + ) + model = BimanualReconstructionModel(config) + model.rgb_encoder = ProbeDinoEncoder(backbone, 512) + model.to(device).train() + batch = make_batch(int(case["batch_size"]), int(case["T"]), int(height), int(width), device) + start = time.perf_counter() + try: + with torch.autocast("cuda", dtype=dtype): + output = model(batch) + loss = ( + output["joint2d_norm"].square().mean() + + output["mano_rotations_6d"].square().mean() + + output["wrist_root_translation"].square().mean() + + output["mano_shape_sequence"].square().mean() + ) + forward_end = time.perf_counter() + loss.backward() + torch.cuda.synchronize(device) + end = time.perf_counter() + case.update({ + "status": "ok", "forward_s": forward_end - start, "forward_backward_s": end - start, + "frames_per_s": int(case["batch_size"]) * int(case["T"]) / (end - start), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30, + "loss_finite": bool(torch.isfinite(loss)), + }) + except torch.cuda.OutOfMemoryError as error: + case.update({"status": "oom", "error": str(error).splitlines()[0], "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30}) + finally: + del model, batch + torch.cuda.empty_cache() + return case + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--quick", action="store_true", help="Probe the core matrix; omit extra checkpoint/layer variants") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + torch.cuda.set_device(args.gpu) + device = torch.device("cuda") + from dinov3.hub.backbones import dinov3_vitb16 + torch.manual_seed(20260716) + backbone = dinov3_vitb16(pretrained=False).to(device) + cases = [] + for width, height in ((384, 224), (512, 288), (640, 368)): + for T in (1, 4, 8, 16): + for batch_size in (1, 2): + for precision in ("bf16", "fp16"): + cases.append({"width": width, "height": height, "T": T, "batch_size": batch_size, "precision": precision, "decoder_layers": 3, "gradient_checkpointing": False}) + if not args.quick: + for layers in (2, 3): + for checkpointing in (False, True): + for batch_size in (1, 2): + cases.append({"width": 512, "height": 288, "T": 8, "batch_size": batch_size, "precision": "bf16", "decoder_layers": layers, "gradient_checkpointing": checkpointing}) + + results = [] + for index, case in enumerate(cases): + case.update({"case": index, "gpu": torch.cuda.get_device_name(device), "random_architecture_only": True, "dinov3": "official dinov3_vitb16 pretrained=False", "seed": 20260716}) + result = run_case(backbone, case, device) + results.append(result) + print(json.dumps(result), flush=True) + fields = sorted({key for result in results for key in result}) + with (args.output_dir / "memory_probe.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader(); writer.writerows(results) + summary = { + "warning": "Architecture-only memory probe with official randomly initialized DINOv3 ViT-B/16. Not a training/quality result.", + "torch": torch.__version__, "python": platform.python_version(), "gpu": torch.cuda.get_device_name(device), + "case_count": len(results), "ok": sum(row["status"] == "ok" for row in results), "oom": sum(row["status"] == "oom" for row in results), + "results_csv": str((args.output_dir / "memory_probe.csv").resolve()), + } + (args.output_dir / "memory_probe_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/profile_phase5_alignment_solver.py b/home/wuyifan/EgoNet_train_20261008/scripts/profile_phase5_alignment_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..842eb2831c09853c1731c7bd7a4e3d1276cad639 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/profile_phase5_alignment_solver.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Profile the deployable per-frame predicted-MANO/depth alignment solver.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import resource +import time +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def latency_summary(values_ms: list[float]) -> dict[str, float | int]: + values = np.asarray(values_ms, dtype=np.float64) + if not values.size or not np.isfinite(values).all(): + raise ValueError("latency samples must be non-empty and finite") + return { + "frames": int(len(values)), + "mean_ms": float(values.mean()), + "std_ms": float(values.std()), + "p50_ms": float(np.percentile(values, 50)), + "p90_ms": float(np.percentile(values, 90)), + "p95_ms": float(np.percentile(values, 95)), + "minimum_ms": float(values.min()), + "maximum_ms": float(values.max()), + "throughput_frames_per_second": float(1000.0 / values.mean()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--frames", type=int, default=128) + parser.add_argument("--warmup", type=int, default=8) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite profile: {args.output}") + if args.frames < 1 or args.warmup < 0: + parser.error("frames must be positive and warmup non-negative") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("scope") != "full" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + ): + raise ValueError("profile requires a complete official-validation raw cache") + take_record = manifest["takes"][0] + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError("profile take cache hash mismatch") + with np.load(take_path, allow_pickle=False) as archive: + frame_ids = archive["frame_id"][:args.frames].astype(np.int64) + vertices = archive["pred_vertices_camera"][:args.frames].astype(np.float32) + take = str(archive["take"]) + take_dir = args.data_root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + + depths = [] + for frame_id in frame_ids: + depth_mm = cv2.imread( + str(take_dir / "depth" / f"{int(frame_id):06d}.png"), cv2.IMREAD_UNCHANGED, + ) + if depth_mm is None or depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{int(frame_id):06d}") + depths.append(depth_mm_to_m(depth_mm)) + cv2.setNumThreads(1) + for index in range(min(args.warmup, len(frame_ids))): + for hand in range(2): + align_wrist_z(vertices[index, hand], K_raw, *depths[index]) + + elapsed_ms = [] + applied = [] + support = [] + for index in range(len(frame_ids)): + started = time.perf_counter_ns() + for hand in range(2): + diagnostics, _ = align_wrist_z( + vertices[index, hand], K_raw, *depths[index], + ) + applied.append(diagnostics.applied) + support.append(diagnostics.valid_support_count) + elapsed_ms.append((time.perf_counter_ns() - started) / 1_000_000.0) + + report = { + "status": "profiled", + "experiment_class": "engineering_profile_not_model_selection", + "official_validation_used": True, + "official_validation_used_for_model_or_threshold_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], + "take": take, + "frame_range": [int(frame_ids[0]), int(frame_ids[-1])], + "latency": { + **latency_summary(elapsed_ms), + "scope": "CPU per-frame two-hand projection/depth sampling/IRLS; raw depth predecoded; excludes coarse model and file I/O", + }, + "applied_hand_fraction": float(np.mean(applied)), + "support_count_mean": float(np.mean(support)), + "peak_process_rss_mib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0, + "cpu": platform.processor(), + "opencv_threads": cv2.getNumThreads(), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/profile_phase5_model.py b/home/wuyifan/EgoNet_train_20261008/scripts/profile_phase5_model.py new file mode 100644 index 0000000000000000000000000000000000000000..08e09f54b448c025820f47f08d473f2dfbf8948b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/profile_phase5_model.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Profile a frozen candidate on one official-train clip without model selection.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader +from torch.utils.flop_counter import FlopCounterMode + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def move_to_device(batch: dict[str, object], device: torch.device) -> dict[str, object]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def parameter_counts(model: torch.nn.Module) -> dict[str, int]: + trainable = sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad) + frozen = sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad) + return {"trainable": trainable, "frozen": frozen, "total": trainable + frozen} + + +def percentile_summary(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + if not array.size or not np.isfinite(array).all(): + raise ValueError("latency measurements must be non-empty and finite") + return { + "iterations": int(len(array)), + "mean_ms": float(array.mean()), + "std_ms": float(array.std()), + "p50_ms": float(np.percentile(array, 50)), + "p90_ms": float(np.percentile(array, 90)), + "p95_ms": float(np.percentile(array, 95)), + "minimum_ms": float(array.min()), + "maximum_ms": float(array.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--warmup", type=int, default=20) + parser.add_argument("--iterations", type=int, default=100) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite profile: {args.output}") + if args.warmup < 1 or args.iterations < 1: + parser.error("warmup and iterations must be positive") + if "test" in args.manifest.name.lower() or "val" in args.manifest.name.lower(): + parser.error("profiling is restricted to official-train data") + checkpoint_hash = sha256(args.checkpoint) + if checkpoint_hash != args.expected_checkpoint_sha256: + parser.error("checkpoint hash mismatch") + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data = config["data"] + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data["resolution_hw"]), + (int(data["T"]),), + (int(data["stride"]),), + max_clips=1, + ) + loader = DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + batch = move_to_device(next(iter(loader)), device) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + if checkpoint.get("extra", {}).get("config") != config: + raise ValueError("profiling config differs from checkpoint embedded config") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + for _ in range(args.warmup): + model(batch) + torch.cuda.synchronize(device) + torch.cuda.reset_peak_memory_stats(device) + starts = [torch.cuda.Event(enable_timing=True) for _ in range(args.iterations)] + ends = [torch.cuda.Event(enable_timing=True) for _ in range(args.iterations)] + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + for start, end in zip(starts, ends, strict=True): + start.record() + model(batch) + end.record() + torch.cuda.synchronize(device) + latency = percentile_summary([start.elapsed_time(end) for start, end in zip(starts, ends, strict=True)]) + peak_vram_gib = torch.cuda.max_memory_allocated(device) / 2**30 + + flop_counter = FlopCounterMode(display=False) + # FlopCounterMode's module tracker requires an autograd graph in PyTorch 2.6. + # This single pass is excluded from the inference latency measurements above. + with torch.autocast("cuda", dtype=dtype), flop_counter: + model(batch) + supported_flops = int(flop_counter.get_total_flops()) + report = { + "status": "profiled", + "experiment_class": "engineering_profile_not_model_selection", + "official_validation_used": False, + "official_test_used": False, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], check=True, text=True, stdout=subprocess.PIPE, + ).stdout.strip(), + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": int(checkpoint["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "input": { + "batch_size": 1, + "clip_length": int(data["T"]), + "resolution_hw": list(data["resolution_hw"]), + "modalities": ["RGB", "Depth", "K"], + "precision": config["precision"], + }, + "parameters": parameter_counts(model), + "supported_operator_flops_per_clip": supported_flops, + "flops_scope": "PyTorch FlopCounterMode supported operators; forward only; unsupported custom operators are not estimated", + "latency": {**latency, "scope": "GPU model forward only; excludes data loading and host preprocessing"}, + "peak_allocated_vram_gib": peak_vram_gib, + "gpu": torch.cuda.get_device_name(device), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/rank_phase7_external.py b/home/wuyifan/EgoNet_train_20261008/scripts/rank_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..0a13c2df62d7118453c90ff38151bfa4acf049f4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/rank_phase7_external.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Rank Phase 7 external checkpoints without frame-count weighting or H2O.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_p95_mm", +) + + +def dense_ranks(values: dict[str, float]) -> dict[str, int]: + ordered = sorted(set(values.values())) + return {name: ordered.index(value) + 1 for name, value in values.items()} + + +def evaluation_metrics(report: dict[str, Any]) -> dict[str, float]: + metrics = report["metrics"] + values = { + "absolute_mpjpe_mm": metrics["absolute_mpjpe_mm"]["mean"], + "root_relative_mpjpe_mm": metrics["root_relative_mpjpe_mm"]["mean"], + "fingertip_mpjpe_mm": metrics["fingertip_mpjpe_mm"]["mean"], + "translation_z_p95_mm": metrics["translation_z_mae_mm"]["p95"], + } + if any(value is None or not math.isfinite(float(value)) for value in values.values()): + raise ValueError("selection metrics must all be finite") + return {key: float(value) for key, value in values.items()} + + +def load_entries(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if manifest.get("selection_split") != "external_heldout_only": + raise ValueError("selection manifest must be external_heldout_only") + expected = set(manifest["datasets"]) + if expected != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("selection requires exactly HOT3D, HOI4D and ARCTIC") + entries: list[dict[str, Any]] = [] + pairs: set[tuple[str, str]] = set() + steps: set[int] = set() + for item in manifest["evaluations"]: + condition = str(item["condition"]) + dataset = str(item["dataset"]) + pair = (condition, dataset) + if pair in pairs: + raise ValueError(f"duplicate condition/dataset pair: {pair}") + pairs.add(pair) + if dataset not in expected: + raise ValueError(f"unexpected dataset: {dataset}") + path = Path(item["path"]).resolve() + report = json.loads(path.read_text(encoding="utf-8")) + cache_path = str(report["cache_manifest"]["path"]).lower() + if "h2o" in cache_path or report.get("h2o_training_data_used") is not False: + raise ValueError("external ranking refuses H2O data or training exposure") + if report.get("official_test_used") is not False: + raise ValueError("external ranking refuses official-test evaluation") + step = int(report["checkpoint_step"]) + steps.add(step) + entries.append({ + "condition": condition, + "dataset": dataset, + "input_mode": report["input_mode"], + "checkpoint_step": step, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "evaluation_path": str(path), + **evaluation_metrics(report), + }) + conditions = {entry["condition"] for entry in entries} + missing = {(condition, dataset) for condition in conditions for dataset in expected} - pairs + if missing: + raise ValueError(f"incomplete condition/dataset grid: {sorted(missing)}") + if len(steps) != 1: + raise ValueError(f"checkpoint steps are not matched: {sorted(steps)}") + return entries + + +def pareto_frontier(vectors: dict[str, list[float]]) -> list[str]: + frontier = [] + for condition, vector in vectors.items(): + dominated = any( + other != condition + and all(left <= right for left, right in zip(other_vector, vector)) + and any(left < right for left, right in zip(other_vector, vector)) + for other, other_vector in vectors.items() + ) + if not dominated: + frontier.append(condition) + return sorted(frontier) + + +def rank_entries(entries: list[dict[str, Any]]) -> dict[str, Any]: + steps = {int(entry["checkpoint_step"]) for entry in entries} + if len(steps) != 1: + raise ValueError(f"checkpoint steps are not matched: {sorted(steps)}") + datasets = sorted({entry["dataset"] for entry in entries}) + conditions = sorted({entry["condition"] for entry in entries}) + lookup = {(entry["condition"], entry["dataset"]): entry for entry in entries} + dataset_ranks: dict[str, dict[str, float]] = {} + vectors = {condition: [] for condition in conditions} + for dataset in datasets: + metric_ranks = { + metric: dense_ranks({ + condition: lookup[(condition, dataset)][metric] + for condition in conditions + }) + for metric in METRICS + } + dataset_ranks[dataset] = {} + for condition in conditions: + score = sum(metric_ranks[metric][condition] for metric in METRICS) / len(METRICS) + dataset_ranks[dataset][condition] = score + vectors[condition].extend( + lookup[(condition, dataset)][metric] for metric in METRICS + ) + macro = { + condition: sum(dataset_ranks[dataset][condition] for dataset in datasets) / len(datasets) + for condition in conditions + } + order = sorted(conditions, key=lambda condition: ( + macro[condition], + sum(lookup[(condition, dataset)]["absolute_mpjpe_mm"] for dataset in datasets), + sum(lookup[(condition, dataset)]["root_relative_mpjpe_mm"] for dataset in datasets), + condition, + )) + return { + "matched_checkpoint_step": entries[0]["checkpoint_step"], + "dataset_ranks": dataset_ranks, + "macro_mean_rank": macro, + "pareto_frontier": pareto_frontier(vectors), + "order": order, + "winner": order[0], + "entries": entries, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + result = { + "status": "ranked_external_only", + "selection_rule": "dataset metric ranks -> macro mean rank -> Absolute/root-relative tie-break", + "frame_count_weighted": False, + "h2o_used": False, + "official_test_used": False, + **rank_entries(load_entries(manifest)), + } + args.output_dir.mkdir(parents=True, exist_ok=False) + (args.output_dir / "ranking.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + with (args.output_dir / "ranking.csv").open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, + fieldnames=( + "condition", "macro_mean_rank", "on_pareto_frontier", + ), + lineterminator="\n", + ) + writer.writeheader() + for condition in result["order"]: + writer.writerow({ + "condition": condition, + "macro_mean_rank": result["macro_mean_rank"][condition], + "on_pareto_frontier": condition in result["pareto_frontier"], + }) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/recover_phase9_arctic_resolution_cache.py b/home/wuyifan/EgoNet_train_20261008/scripts/recover_phase9_arctic_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f62598bfecb94ccf2457dade735b0bca9d13fc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/recover_phase9_arctic_resolution_cache.py @@ -0,0 +1,561 @@ +#!/usr/bin/env python3 +"""Restore the Stage 7 ARCTIC cache to the frozen 640 source-index set.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +from typing import Any + +import cv2 +import numpy as np + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + cache_step_complete, + sha256, + validate_plan_bindings, +) + + +IDENTITY_FIELDS = ( + "dataset_id", + "subject_id", + "physical_recording_id", + "source_group_key", + "camera_id", + "stream_id", + "headset_id", +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def load_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def indexed_rows( + rows: list[dict[str, Any]], label: str, +) -> tuple[list[int], dict[int, dict[str, Any]]]: + order = [int(row["source_clip_index"]) for row in rows] + if len(order) != len(set(order)): + duplicates = sorted({value for value in order if order.count(value) > 1}) + raise ValueError(f"{label} has duplicate source clip indices: {duplicates}") + return order, dict(zip(order, rows, strict=True)) + + +def compare_source_sets( + control_rows: list[dict[str, Any]], candidate_rows: list[dict[str, Any]], +) -> dict[str, Any]: + control_order, control = indexed_rows(control_rows, "control manifest") + candidate_order, candidate = indexed_rows(candidate_rows, "candidate manifest") + control_set, candidate_set = set(control), set(candidate) + missing = sorted(control_set - candidate_set) + extra = sorted(candidate_set - control_set) + drift = [] + for source_index in control_order: + if source_index not in candidate: + continue + differing = { + field: { + "control": control[source_index].get(field), + "candidate": candidate[source_index].get(field), + } + for field in IDENTITY_FIELDS + if control[source_index].get(field) != candidate[source_index].get(field) + } + if differing: + drift.append({"source_clip_index": source_index, "fields": differing}) + control_groups = {row["source_group_key"] for row in control_rows} + candidate_groups = { + candidate[index]["source_group_key"] + for index in control_order if index in candidate + } + return { + "control_count": len(control_order), + "candidate_count": len(candidate_order), + "control_unique_count": len(control_set), + "candidate_unique_count": len(candidate_set), + "missing_source_clip_indices": missing, + "extra_source_clip_indices": extra, + "identity_drift": drift, + "control_group_count": len(control_groups), + "candidate_accepted_group_count": len(candidate_groups), + "missing_groups": sorted(control_groups - candidate_groups), + "extra_groups": sorted(candidate_groups - control_groups), + } + + +def canonical_rows( + control_rows: list[dict[str, Any]], candidate_rows: list[dict[str, Any]], +) -> list[dict[str, Any]]: + comparison = compare_source_sets(control_rows, candidate_rows) + if ( + comparison["missing_source_clip_indices"] + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC source-index or group contract differs") + control_order, _ = indexed_rows(control_rows, "control manifest") + _, candidate = indexed_rows(candidate_rows, "candidate manifest") + return [candidate[index] for index in control_order] + + +def write_jsonl_atomic(path: Path, rows: list[dict[str, Any]]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + temporary.replace(path) + + +def preserve_file(source: Path, destination: Path) -> dict[str, Any]: + destination.parent.mkdir(parents=True, exist_ok=True) + source_hash = sha256(source) + if destination.exists(): + if not destination.is_file() or sha256(destination) != source_hash: + raise ValueError(f"preserved recovery evidence differs: {destination}") + else: + shutil.copy2(source, destination) + os.chmod(destination, 0o444) + return { + "path": str(destination.resolve()), + "sha256": source_hash, + "bytes": source.stat().st_size, + } + + +def quarantine_payload( + row: dict[str, Any], quarantine_root: Path, pass_id: str, +) -> dict[str, Any]: + source = Path(row["cache_path"]) + expected_hash = row["cache_sha256"] + if not source.is_file() or sha256(source) != expected_hash: + raise ValueError(f"extra ARCTIC payload differs: {source}") + destination = quarantine_root / pass_id / source.name + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + if not destination.is_file() or sha256(destination) != expected_hash: + raise ValueError(f"ARCTIC quarantine collision differs: {destination}") + source.unlink() + else: + source.replace(destination) + os.chmod(destination, 0o444) + return { + "source_clip_index": int(row["source_clip_index"]), + "path": str(destination.resolve()), + "sha256": expected_hash, + "bytes": destination.stat().st_size, + } + + +def payload_audit(rows: list[dict[str, Any]]) -> dict[str, Any]: + totals = { + "bytes": 0, + "clips_with_translation_supervision": 0, + "translation_valid_elements": 0, + "joint3d_valid_elements": 0, + "mano_annotation_valid_elements": 0, + } + probes: dict[int, dict[str, Any]] = {} + probe_positions = {0, len(rows) // 2, len(rows) - 1} + for position, row in enumerate(rows): + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"canonical ARCTIC payload differs: {path}") + with np.load(path, allow_pickle=False) as archive: + image_hw = [int(value) for value in archive["image_hw"].reshape(-1)] + if image_hw != [512, 896]: + raise ValueError(f"canonical ARCTIC resolution differs: {path}") + translation = np.asarray(archive["translation_valid"], dtype=bool) + joint3d = np.asarray(archive["joint3d_valid"], dtype=bool) + mano = np.asarray(archive["mano_annotation_valid"], dtype=bool) + if not translation.any(): + raise ValueError(f"canonical ARCTIC clip lacks supervision: {path}") + totals["bytes"] += path.stat().st_size + totals["clips_with_translation_supervision"] += 1 + totals["translation_valid_elements"] += int(translation.sum()) + totals["joint3d_valid_elements"] += int(joint3d.sum()) + totals["mano_annotation_valid_elements"] += int(mano.sum()) + if position in probe_positions: + probes[position] = { + "position": position, + "source_clip_index": int(row["source_clip_index"]), + "path": str(path.resolve()), + "sha256": row["cache_sha256"], + "image_hw": image_hw, + "frame_ids": archive["frame_id"].astype(int).tolist(), + "translation_valid_elements": int(translation.sum()), + "joint3d_valid_elements": int(joint3d.sum()), + } + return {**totals, "probes": [probes[key] for key in sorted(probes)]} + + +def source_extra_audit( + *, source_manifest: Path, control_report: dict[str, Any], + candidate_report: dict[str, Any], candidate_by_index: dict[int, dict[str, Any]], + extra_indices: list[int], mano_root: Path, +) -> list[dict[str, Any]]: + source_rows = [ + json.loads(line) + for line in source_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + control_skipped = {int(value) for value in control_report["skipped_no_supervision"]} + candidate_skipped = { + int(value) for value in candidate_report["skipped_no_supervision"] + } + low_dataset = ARCTICClipDataset( + source_manifest, mano_root, target_hw=(368, 640), + ) + high_dataset = ARCTICClipDataset( + source_manifest, mano_root, target_hw=(512, 896), + ) + results = [] + for source_index in extra_indices: + source = source_rows[source_index] + candidate = candidate_by_index[source_index] + images = [] + for value in source["image_paths"]: + path = Path(value) + image = cv2.imread(str(path), cv2.IMREAD_COLOR) + images.append({ + "path": str(path.resolve()), + "exists": path.is_file(), + "bytes": path.stat().st_size if path.is_file() else None, + "decoded_hw": list(image.shape[:2]) if image is not None else None, + }) + if any(not item["exists"] or item["decoded_hw"] != [600, 840] for item in images): + raise ValueError(f"ARCTIC extra source image differs: {source_index}") + mano_path, camera_path = Path(source["mano_path"]), Path(source["camera_path"]) + if not mano_path.is_file() or not camera_path.is_file(): + raise ValueError(f"ARCTIC extra annotation is missing: {source_index}") + mano_value = np.load(mano_path, allow_pickle=True).item() + camera_value = np.load(camera_path, allow_pickle=True).item() + if not {"left", "right"}.issubset(mano_value) or not { + "R_k_cam_np", "T_k_cam_np", "intrinsics", "dist8", + }.issubset(camera_value): + raise ValueError(f"ARCTIC extra annotation contract differs: {source_index}") + low = low_dataset[(source_index, 0)] + high = high_dataset[(source_index, 0)] + low_count = int(low["translation_valid"].sum()) + high_count = int(high["translation_valid"].sum()) + if ( + source_index not in control_skipped + or source_index in candidate_skipped + or low_count != 0 + or high_count <= 0 + or source["group_key"] != candidate["source_group_key"] + or source["physical_recording_id"] != candidate["physical_recording_id"] + ): + raise ValueError(f"ARCTIC extra acceptance reason differs: {source_index}") + results.append({ + "source_clip_index": source_index, + "classification": "resolution_dependent_supervision_boundary", + "control_640_reason": "skipped_no_supervision", + "control_640_translation_valid_elements": low_count, + "candidate_896_translation_valid_elements": high_count, + "subject_id": source["subject_id"], + "physical_recording_id": source["physical_recording_id"], + "source_group_key": source["group_key"], + "frame_ids_1based": source["frame_ids_1based"], + "images": images, + "mano_annotation": { + "path": str(mano_path.resolve()), "bytes": mano_path.stat().st_size, + "sides": sorted(mano_value), + }, + "camera_annotation": { + "path": str(camera_path.resolve()), "bytes": camera_path.stat().st_size, + "required_fields_present": True, + }, + }) + return results + + +def validate_recovery_plan(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("status") != "frozen" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("ARCTIC recovery plan isolation differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"ARCTIC recovery binding differs: {path}") + execution_path = Path(plan["execution_plan"]["path"]) + execution = json.loads(execution_path.read_text(encoding="utf-8")) + if sha256(execution_path) != plan["execution_plan"]["sha256"]: + raise ValueError("ARCTIC execution plan binding differs") + validate_plan_bindings(execution) + return execution + + +def canonicalize_pass( + *, plan_path: Path, plan: dict[str, Any], pass_id: str, +) -> dict[str, Any]: + manifest_path = Path(plan["candidate_manifest"]) + report_path = Path(plan["candidate_report"]) + control_manifest_path = Path(plan["control_manifest"]["path"]) + control_report_path = Path(plan["control_report"]["path"]) + evidence_root = Path(plan["evidence_root"]) / pass_id + raw_manifest = preserve_file(manifest_path, evidence_root / "raw_cache_manifest.jsonl") + raw_report = preserve_file(report_path, evidence_root / "raw_cache_report.json") + control_rows = load_jsonl(control_manifest_path) + candidate_rows = load_jsonl(manifest_path) + control_report = json.loads(control_report_path.read_text(encoding="utf-8")) + candidate_report = json.loads(report_path.read_text(encoding="utf-8")) + comparison = compare_source_sets(control_rows, candidate_rows) + expected_extra = plan["expected_extra_source_clip_indices"] + if ( + comparison["control_count"] != plan["expected_clips"] + or comparison["candidate_count"] != plan["raw_candidate_clips"] + or comparison["missing_source_clip_indices"] + or comparison["extra_source_clip_indices"] != expected_extra + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC cache mismatch is outside the frozen recovery scope") + _, candidate_by_index = indexed_rows(candidate_rows, "candidate manifest") + extras = source_extra_audit( + source_manifest=Path(plan["source_manifest"]["path"]), + control_report=control_report, + candidate_report=candidate_report, + candidate_by_index=candidate_by_index, + extra_indices=expected_extra, + mano_root=Path(plan["mano_root"]), + ) + quarantined = [ + quarantine_payload(candidate_by_index[index], Path(plan["quarantine_root"]), pass_id) + for index in expected_extra + ] + accepted = canonical_rows(control_rows, candidate_rows) + coverage = payload_audit(accepted) + if coverage["clips_with_translation_supervision"] != plan["expected_clips"]: + raise ValueError("ARCTIC canonical supervision coverage differs") + write_jsonl_atomic(manifest_path, accepted) + manifest_hash = sha256(manifest_path) + canonical_report = dict(candidate_report) + canonical_report.update({ + "status": "complete", + "cached_clips": plan["expected_clips"], + "cached_valid_clips": plan["expected_clips"], + "valid_candidate_files": plan["expected_clips"], + "recordings": comparison["control_group_count"], + "bytes": coverage["bytes"], + "cache_manifest": { + "path": str(manifest_path.resolve()), "sha256": manifest_hash, + }, + "canonical_filter": { + "schema_version": "phase9_arctic_resolution_canonical_filter_v1", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "control_manifest": plan["control_manifest"], + "raw_manifest": raw_manifest, + "raw_report": raw_report, + "excluded_resolution_dependent_source_indices": expected_extra, + "quarantined_payloads": quarantined, + "ordering": "frozen_640_control_source_index_order", + "logical_clip_set_changed_from_control": False, + }, + "supervision_coverage": coverage, + "h2o_official_validation_used": False, + "official_test_used": False, + }) + atomic_json(report_path, canonical_report) + return { + "pass_id": pass_id, + "raw_manifest": raw_manifest, + "raw_report": raw_report, + "comparison": comparison, + "extra_source_audit": extras, + "quarantined_payloads": quarantined, + "canonical_manifest": { + "path": str(manifest_path.resolve()), "sha256": manifest_hash, + "rows": len(accepted), + }, + "canonical_report": { + "path": str(report_path.resolve()), "sha256": sha256(report_path), + }, + "supervision_coverage": coverage, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--audit-only", action="store_true") + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + execution = validate_recovery_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + workers = {item["id"]: item for item in execution["workers"]} + worker = workers["arctic"] + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("ARCTIC recovery state path differs from execution plan") + initial_step, resume_step = worker["steps"][:2] + if args.audit_only: + control_rows = load_jsonl(Path(plan["control_manifest"]["path"])) + candidate_rows = load_jsonl(Path(plan["candidate_manifest"])) + comparison = compare_source_sets(control_rows, candidate_rows) + _, candidate_by_index = indexed_rows(candidate_rows, "candidate manifest") + control_report = json.loads( + Path(plan["control_report"]["path"]).read_text(encoding="utf-8") + ) + candidate_report = json.loads( + Path(plan["candidate_report"]).read_text(encoding="utf-8") + ) + expected_extra = plan["expected_extra_source_clip_indices"] + if ( + comparison["control_count"] != plan["expected_clips"] + or comparison["candidate_count"] != plan["raw_candidate_clips"] + or comparison["missing_source_clip_indices"] + or comparison["extra_source_clip_indices"] != expected_extra + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC preflight mismatch is outside recovery scope") + result = { + "schema_version": "phase9_arctic_resolution_mismatch_audit_v1", + "status": "complete", + "created_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "control_manifest": plan["control_manifest"], + "candidate_manifest": { + "path": str(Path(plan["candidate_manifest"]).resolve()), + "sha256": sha256(plan["candidate_manifest"]), + }, + "candidate_report": { + "path": str(Path(plan["candidate_report"]).resolve()), + "sha256": sha256(plan["candidate_report"]), + }, + "comparison": comparison, + "extra_source_audit": source_extra_audit( + source_manifest=Path(plan["source_manifest"]["path"]), + control_report=control_report, + candidate_report=candidate_report, + candidate_by_index=candidate_by_index, + extra_indices=expected_extra, + mano_root=Path(plan["mano_root"]), + ), + "mutation_performed": False, + "expected_clips_changed": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(Path(plan["preflight_audit_output"]), result) + print(json.dumps(result, indent=2)) + return + lock_path = Path(f"{args.state}.lock") + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state = json.loads(args.state.read_text(encoding="utf-8")) + if ( + state.get("worker") != "arctic" + or state.get("plan_sha256") != plan["execution_plan"]["sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + parser.error("ARCTIC failed state binding differs") + existing = state.get("canonical_set_recovery") + if existing and existing.get("status") == "complete": + if not cache_step_complete(initial_step, False) or not cache_step_complete( + resume_step, True + ): + parser.error("completed ARCTIC recovery outputs differ") + print(json.dumps(state, indent=2)) + return + if state.get("status") != "failed_resumable": + parser.error("ARCTIC recovery requires failed_resumable input state") + result: dict[str, Any] = { + "schema_version": "phase9_arctic_resolution_canonical_recovery_v1", + "status": "running", "started_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "failure_state_sha256": sha256(args.state), + "passes": [], "official_test_used": False, + "h2o_official_validation_used": False, + } + state["canonical_set_recovery"] = result + atomic_json(args.state, state) + initial = canonicalize_pass(plan_path=args.plan, plan=plan, pass_id="initial") + if not cache_step_complete(initial_step, False): + raise ValueError("initial ARCTIC canonical cache validation failed") + result["passes"].append(initial) + if initial_step["id"] not in state["completed_steps"]: + state["completed_steps"].append(initial_step["id"]) + command = list(resume_step["resume_command"]) + log_path = Path(plan["resume_log"]) + attempt = { + "step": resume_step["id"], "kind": "cache", + "recovery": "canonical_set_exact_resume_verify", + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_step"] = resume_step["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + completed = subprocess.run( + command, cwd=Path.cwd(), env=dict(os.environ, PYTHONPATH=str(Path.cwd())), + stdout=log, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = completed.returncode + if completed.returncode: + state["status"] = "failed_resumable" + result["status"] = "failed_resume_command" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(completed.returncode) + resumed = canonicalize_pass( + plan_path=args.plan, plan=plan, pass_id="resume_verify", + ) + result["passes"].append(resumed) + if not cache_step_complete(initial_step, False) or not cache_step_complete( + resume_step, True + ): + raise ValueError("resumed ARCTIC canonical cache validation failed") + if resume_step["id"] not in state["completed_steps"]: + state["completed_steps"].append(resume_step["id"]) + result["status"] = "complete" + result["completed_utc"] = utc_now() + result["canonical_manifest_sha256"] = sha256(plan["candidate_manifest"]) + result["canonical_report_sha256"] = sha256(plan["candidate_report"]) + atomic_json(Path(plan["audit_output"]), result) + result["audit_output"] = { + "path": str(Path(plan["audit_output"]).resolve()), + "sha256": sha256(plan["audit_output"]), + } + state["status"] = "waiting_for_remaining_steps" + state["updated_utc"] = utc_now() + state["failure_evidence_preserved"] = state.get("failure") + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/render_best_worst_video_cases.py b/home/wuyifan/EgoNet_train_20261008/scripts/render_best_worst_video_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..04f5d1c2379da5af6f1d151193c5df89ce67d78b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/render_best_worst_video_cases.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +"""Render ranked full-take videos for the frozen Phase 3 candidate.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + MeshLayer, + project_mesh_layers, + render_mesh_layers, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +LEFT_COLOR_RGB = (40, 100, 235) +RIGHT_COLOR_RGB = (235, 55, 55) +MESH_ALPHA = 0.55 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def _mean(rows: list[dict[str, str]], field: str) -> float: + values = np.asarray([float(row[field]) for row in rows], dtype=np.float64) + if not np.isfinite(values).all(): + raise ValueError(f"non-finite {field} in sequence ranking rows") + return float(values.mean()) + + +def rank_video_sequences( + rows: list[dict[str, str]], *, count: int, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Rank validation takes by all annotation-valid hand-frame errors.""" + + grouped: dict[str, list[dict[str, str]]] = defaultdict(list) + for row in rows: + grouped[row["take"]].append(row) + + candidates = [] + for take, take_rows in grouped.items(): + valid_rows = [row for row in take_rows if int(row["annotation_valid"]) == 1] + if not valid_rows: + continue + observed = { + (int(row["frame_id"]), row["side"]) + for row in take_rows + } + if len(observed) != len(take_rows): + raise ValueError(f"duplicate evaluated hand-frame rows in {take}") + errors = np.asarray( + [float(row["absolute_mpjpe_mm"]) for row in valid_rows], + dtype=np.float64, + ) + if not np.isfinite(errors).all(): + raise ValueError(f"non-finite ranking errors in {take}") + first = valid_rows[0] + evaluated_frame_ids = sorted({int(row["frame_id"]) for row in take_rows}) + annotated_frame_ids = sorted({int(row["frame_id"]) for row in valid_rows}) + candidates.append({ + "take": take, + "subject": first["subject"], + "sequence": first["sequence"], + "evaluation_frame_ids": evaluated_frame_ids, + "evaluated_frame_count": len(evaluated_frame_ids), + "annotated_frame_count": len(annotated_frame_ids), + "annotated_hand_frames": len(valid_rows), + "absolute_mpjpe_mm_mean": float(errors.mean()), + "absolute_mpjpe_mm_p50": float(np.median(errors)), + "absolute_mpjpe_mm_max": float(errors.max()), + "root_relative_mpjpe_mm_mean": _mean(valid_rows, "root_relative_mpjpe_mm"), + "direct_2d_error_px_mean": _mean(valid_rows, "direct_2d_error_px"), + "translation_x_mae_mm_mean": _mean(valid_rows, "translation_x_mae_mm"), + "translation_y_mae_mm_mean": _mean(valid_rows, "translation_y_mae_mm"), + "translation_z_mae_mm_mean": _mean(valid_rows, "translation_z_mae_mm"), + }) + if len(candidates) < count * 2: + raise ValueError( + f"need at least {count * 2} validation takes, found {len(candidates)}" + ) + best = sorted( + candidates, + key=lambda row: (row["absolute_mpjpe_mm_mean"], row["take"]), + )[:count] + failure = sorted( + candidates, + key=lambda row: (-row["absolute_mpjpe_mm_mean"], row["take"]), + )[:count] + if {row["take"] for row in best} & {row["take"] for row in failure}: + raise AssertionError("best and failure sequence selections overlap") + return best, failure + + +def source_frame_ids(data_root: Path, take: str) -> list[int]: + frame_ids = sorted( + int(path.stem) for path in (data_root / take / "rgb").glob("*.png") + ) + if not frame_ids: + raise ValueError(f"no raw RGB frames in {data_root / take}") + expected = list(range(frame_ids[0], frame_ids[-1] + 1)) + if frame_ids != expected: + raise ValueError(f"raw RGB frames are not contiguous in {data_root / take}") + return frame_ids + + +def case_directory_name(rank: int, case: dict[str, Any]) -> str: + sequence = str(case["sequence"]).replace("/", "_") + first_frame, last_frame = case["frame_ids"][0], case["frame_ids"][-1] + return ( + f"{rank:02d}_{case['subject']}_{sequence}_" + f"frames_{first_frame:06d}_{last_frame:06d}" + ) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def add_header(image_rgb: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image_rgb.copy() + height = 8 + 22 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (8, 20 + 22 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.55, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def open_writer(path: Path, fps: float, frame_hw: tuple[int, int]) -> cv2.VideoWriter: + height, width = frame_hw + writer = cv2.VideoWriter( + str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height), + ) + if not writer.isOpened(): + raise RuntimeError(f"failed to open video writer: {path}") + return writer + + +def frame_error_lookup( + rows: list[dict[str, str]], take: str, +) -> dict[int, float]: + values: dict[int, list[float]] = defaultdict(list) + for row in rows: + if row["take"] != take or int(row["annotation_valid"]) != 1: + continue + values[int(row["frame_id"])].append(float(row["absolute_mpjpe_mm"])) + return {frame_id: float(np.mean(errors)) for frame_id, errors in values.items()} + + +def render_case( + *, + case: dict[str, Any], + rank: int, + category: str, + output_dir: Path, + dataset: H2OCam4Dataset, + clip_indices: list[int], + metric_rows: list[dict[str, str]], + data_root: Path, + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + faces: tuple[np.ndarray, np.ndarray], + fps: float, + model_t: int, +) -> dict[str, Any]: + output_dir.mkdir(parents=True, exist_ok=False) + take_dir = data_root / str(case["take"]) + raw_K, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + original_path = output_dir / "original_rgb.mp4" + overlay_path = output_dir / "predicted_mano_overlay.mp4" + comparison_path = output_dir / "side_by_side.mp4" + original_writer = open_writer(original_path, fps, source_hw) + overlay_writer = open_writer(overlay_path, fps, source_hw) + comparison_writer = open_writer( + comparison_path, fps, (source_hw[0], source_hw[1] * 2), + ) + errors = frame_error_lookup(metric_rows, str(case["take"])) + expected_frame_ids = list(case["frame_ids"]) + preview = None + rendered_frame_ids: list[int] = [] + try: + for clip_index in clip_indices: + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + clip_frame_ids = [int(value) for value in sample["frame_id"].tolist()] + for time_index, frame_id in enumerate(clip_frame_ids): + raw_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), + cv2.IMREAD_COLOR, + ) + if raw_bgr is None or raw_bgr.shape[:2] != source_hw: + raise RuntimeError( + f"raw RGB decode/shape failure: {take_dir}/{frame_id}" + ) + raw_rgb = cv2.cvtColor(raw_bgr, cv2.COLOR_BGR2RGB) + layers = [ + MeshLayer( + prediction["vertices_camera"][0, time_index, hand] + .float().cpu().numpy(), + faces[hand], + LEFT_COLOR_RGB if hand == 0 else RIGHT_COLOR_RGB, + MESH_ALPHA, + ) + for hand in range(2) + ] + rendered = render_mesh_layers( + raw_rgb, project_mesh_layers(layers, raw_K), + ) + frame_error = errors.get(frame_id) + error_label = ( + f"{frame_error:.2f} mm" + if frame_error is not None else "n/a (not evaluated)" + ) + global_index = len(rendered_frame_ids) + rendered = add_header(rendered, ( + f"{category} #{rank} | predicted MANO | left=BLUE right=RED alpha={MESH_ALPHA:.2f}", + f"{case['subject']}/{case['sequence']} | frame={frame_id} ({global_index + 1}/{len(expected_frame_ids)}) | take MPJPE={case['absolute_mpjpe_mm_mean']:.2f} mm | frame={error_label}", + )) + original_panel = add_header(raw_rgb, ("Original cam4 RGB",)) + comparison = np.concatenate((original_panel, rendered), axis=1) + + original_writer.write(raw_bgr) + overlay_writer.write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + comparison_writer.write(cv2.cvtColor(comparison, cv2.COLOR_RGB2BGR)) + rendered_frame_ids.append(frame_id) + if global_index == len(expected_frame_ids) // 2: + preview = comparison + del prediction, batch + finally: + original_writer.release() + overlay_writer.release() + comparison_writer.release() + + if rendered_frame_ids != expected_frame_ids: + raise RuntimeError( + f"rendered frame sequence mismatch for {case['take']}: " + f"{len(rendered_frame_ids)} != {len(expected_frame_ids)}" + ) + if preview is None: + raise RuntimeError(f"no preview generated for {case['take']}") + preview_path = output_dir / "preview.png" + cv2.imwrite(str(preview_path), cv2.cvtColor(preview, cv2.COLOR_RGB2BGR)) + record = { + **case, + "rank": rank, + "category": category, + "selection_requirement": "official-validation take with finite annotation-valid metrics", + "ranking_metric": "mean absolute MPJPE over all annotation-valid hand-frames in the take", + "inference_policy": f"contiguous full raw take, non-overlapping T={model_t} chunks with final partial chunk", + "colors_rgb": { + "left": list(LEFT_COLOR_RGB), "right": list(RIGHT_COLOR_RGB), + }, + "mesh_alpha": MESH_ALPHA, + "visualization_fps": fps, + "duration_seconds": len(expected_frame_ids) / fps, + "videos": { + "original": str(original_path.resolve()), + "predicted_mano_overlay": str(overlay_path.resolve()), + "side_by_side": str(comparison_path.resolve()), + }, + "preview": str(preview_path.resolve()), + } + (output_dir / "case.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + record["preview_rgb"] = preview + return record + + +def save_contact_sheet(output: Path, records: list[dict[str, Any]]) -> None: + panels = [] + for record in records: + preview = record["preview_rgb"] + panel = cv2.resize(preview, (384, 216), interpolation=cv2.INTER_AREA) + panel = add_header(panel, ( + f"{record['category']} #{record['rank']} | {record['absolute_mpjpe_mm_mean']:.2f} mm | {len(record['frame_ids'])} frames", + )) + panels.append(panel) + rows = [np.concatenate(panels[:5], axis=1), np.concatenate(panels[5:], axis=1)] + sheet = np.concatenate(rows, axis=0) + cv2.imwrite(str(output), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR)) + + +def save_case_summary(output: Path, records: list[dict[str, Any]]) -> None: + lines = [ + "# Ranked Long-Sequence Video Summary", + "", + "Takes are ranked by mean camera-space absolute MPJPE over every", + "annotation-valid official-validation hand-frame. Videos render each full raw", + "take continuously; frames outside the evaluated annotation runs do not affect", + "the ranking. All metric values below use only valid evaluation rows.", + "", + ] + for category, title in (("best", "Best Sequences"), ("failure", "Worst Sequences")): + lines.extend([ + f"## {title}", + "", + "| Rank | Take | Raw frames | Seconds | Evaluated frames | Abs MPJPE | Root-relative | Direct 2D | z MAE |", + "|---:|---|---:|---:|---:|---:|---:|---:|---:|", + ]) + for record in records: + if record["category"] != category: + continue + lines.append( + f"| {record['rank']} | `{record['take']}` | {len(record['frame_ids'])} | " + f"{record['duration_seconds']:.2f} | {record['evaluated_frame_count']} | " + f"{record['absolute_mpjpe_mm_mean']:.2f} mm | " + f"{record['root_relative_mpjpe_mm_mean']:.2f} mm | " + f"{record['direct_2d_error_px_mean']:.2f} px | " + f"{record['translation_z_mae_mm_mean']:.2f} mm |" + ) + lines.append("") + lines.extend([ + "Left MANO is blue, right MANO is red, and mesh alpha is 0.55. The", + "prediction-only overlay uses raw 1280x720 cam4 RGB and the original camera", + "intrinsics. GT meshes are not rendered. Official test was not used.", + "", + ]) + output.write_text("\n".join(lines), encoding="utf-8") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--evaluation-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--count", type=int, default=5) + parser.add_argument("--fps", type=float, default=30.0) + args = parser.parse_args() + if args.count != 5: + raise ValueError("the showcase requires exactly five best and five failure cases") + if args.fps <= 0: + raise ValueError("fps must be positive") + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError(f"refusing to overwrite non-empty output: {args.output_dir}") + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + metric_path = args.evaluation_dir / "per_hand_frame_metrics.csv" + report_path = args.evaluation_dir / "evaluation.json" + metric_rows = read_csv(metric_path) + report = json.loads(report_path.read_text(encoding="utf-8")) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + if ( + report.get("split_role") != "official_validation" + or report.get("official_test_used") is not False + or report.get("checkpoint", {}).get("sha256") != checkpoint_hash + or report.get("manifest", {}).get("sha256") != manifest_hash + ): + raise ValueError("evaluation/checkpoint/manifest provenance mismatch") + + best, failure = rank_video_sequences(metric_rows, count=args.count) + selected = best + failure + for case in selected: + case["frame_ids"] = source_frame_ids(args.data_root, str(case["take"])) + case["raw_frame_count"] = len(case["frame_ids"]) + + render_manifest_path = args.output_dir / "render_input_manifest.jsonl" + render_manifest_path.write_text( + "".join( + json.dumps({"take": case["take"], "frame_ids": case["frame_ids"]}) + "\n" + for case in selected + ), + encoding="utf-8", + ) + model_t = int(data_config["T"]) + dataset = H2OCam4Dataset( + args.data_root, render_manifest_path, tuple(data_config["resolution_hw"]), + (model_t,), (int(data_config["stride"]),), + ) + clip_indices_by_take: dict[str, list[int]] = defaultdict(list) + for clip_index, clip in enumerate(dataset.clips): + clip_indices_by_take[clip.take].append(clip_index) + + device = torch.device(f"cuda:{args.gpu}") + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint( + args.checkpoint, model, optimizer=None, map_location=device, + ) + if int(checkpoint_state["step"]) != int(report["checkpoint"]["step"]): + raise ValueError("checkpoint step differs from source evaluation") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + faces = tuple(layer.th_faces.cpu().numpy() for layer in model.mano_layer.layers) + + rendered_records = [] + for category, cases, parent_name in ( + ("best", best, "best_cases"), + ("failure", failure, "failure_cases"), + ): + parent = args.output_dir / parent_name + parent.mkdir(exist_ok=False) + for rank, case in enumerate(cases, start=1): + print( + f"rendering {category} #{rank}: {case['take']} " + f"({len(case['frame_ids'])} frames)", + flush=True, + ) + record = render_case( + case=case, rank=rank, category=category, + output_dir=parent / case_directory_name(rank, case), + dataset=dataset, + clip_indices=clip_indices_by_take[str(case["take"])], + metric_rows=metric_rows, data_root=args.data_root.resolve(), + model=model, device=device, dtype=dtype, faces=faces, + fps=args.fps, model_t=model_t, + ) + rendered_records.append(record) + + save_contact_sheet(args.output_dir / "contact_sheet.png", rendered_records) + save_case_summary(args.output_dir / "CASE_SUMMARY.md", rendered_records) + serializable_records = [ + {key: value for key, value in record.items() if key != "preview_rgb"} + for record in rendered_records + ] + manifest = { + "status": "complete", + "official_test_used": False, + "source_split": "official_validation", + "selection_policy": ( + "lowest/highest take mean absolute MPJPE over all annotation-valid " + "official-validation hand-frames" + ), + "render_policy": ( + "all contiguous raw frames in each selected take, including frames " + "outside evaluated annotation runs" + ), + "config": str(args.config.resolve()), + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": checkpoint_hash, + "step": int(checkpoint_state["step"]), + }, + "source_manifest": { + "path": str(args.manifest.resolve()), + "sha256": manifest_hash, + }, + "source_evaluation": str(args.evaluation_dir.resolve()), + "render_input_manifest": str(render_manifest_path.resolve()), + "model_input_resolution_hw": list(data_config["resolution_hw"]), + "model_temporal_window": model_t, + "render_space": "raw cam4 RGB resolution with original camera intrinsics", + "videos_are_prediction_only": True, + "visualization_fps": args.fps, + "cases": serializable_records, + } + (args.output_dir / "selection_manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8", + ) + readme = f"""# Best Model Long-Sequence Video Cases + +This directory uses the Phase 3 seed-20260718 step-140k tail-best checkpoint. +The five best and five worst cases are distinct official-validation takes, +ranked by mean camera-space absolute MPJPE across all annotation-valid +hand-frames in each take. + +Each case contains: + +- `original_rgb.mp4`: untouched full raw cam4 RGB sequence; +- `predicted_mano_overlay.mp4`: prediction-only MANO, left blue and right red; +- `side_by_side.mp4`: original and overlay comparison; +- `preview.png` and `case.json`. + +All raw frames from the selected take are rendered continuously, including +frames outside the evaluated annotation runs. Those frames display `n/a` for +the frame metric and do not affect ranking. Inference uses non-overlapping +T={model_t} chunks, matching the formal evaluator, with a final partial chunk. + +Playback is {args.fps:g} fps, matching the H2O capture rate. Mesh alpha is +0.55. Camera-space vertices are projected onto raw 1280x720 RGB with original +cam4 intrinsics. GT meshes are not rendered. Official test was not used. + +See `CASE_SUMMARY.md` for the ranking and metric breakdown, `contact_sheet.png` +for the visual index, and `selection_manifest.json` for full provenance. +""" + (args.output_dir / "README.md").write_text(readme, encoding="utf-8") + print(json.dumps({ + "status": "complete", + "output_dir": str(args.output_dir.resolve()), + "fps": args.fps, + "best_take_mpjpe_mm": [row["absolute_mpjpe_mm_mean"] for row in best], + "failure_take_mpjpe_mm": [ + row["absolute_mpjpe_mm_mean"] for row in failure + ], + "frame_counts": [len(row["frame_ids"]) for row in selected], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/render_phase4_filtered_cases.py b/home/wuyifan/EgoNet_train_20261008/scripts/render_phase4_filtered_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea9f5f1022a50e8c55ff0fe3b30b1d019fb4375 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/render_phase4_filtered_cases.py @@ -0,0 +1,517 @@ +#!/usr/bin/env python3 +"""Render deterministic raw/filtered failure videos from audited jitter caches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + OPENPOSE_HAND_EDGES, + draw_skeleton, + project_camera_points, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models.mano import ManoCameraLayer +try: + from scripts.evaluate_phase4_jitter import ( + condition_grid, + filtered_parameters, + load_take, + rebuild_geometry, + ) +except ModuleNotFoundError: + from evaluate_phase4_jitter import ( # type: ignore[no-redef] + condition_grid, + filtered_parameters, + load_take, + rebuild_geometry, + ) + + +RAW_COLOR = (245, 145, 45) +FILTERED_COLOR = (35, 210, 235) +GT_COLOR = (70, 220, 105) +AXIS_COLORS = ((235, 80, 80), (70, 190, 90), (80, 130, 240)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +class FFmpegWriter: + def __init__(self, path: Path, fps: float, frame_hw: tuple[int, int]) -> None: + self.path = path + self.frame_hw = frame_hw + self.frames = 0 + path.parent.mkdir(parents=True, exist_ok=True) + self.temporary = path.with_name(f".{path.stem}.tmp-{os.getpid()}.mp4") + height, width = frame_hw + self.process = subprocess.Popen([ + "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-y", + "-f", "rawvideo", "-pix_fmt", "bgr24", "-s:v", f"{width}x{height}", + "-r", f"{fps:g}", "-i", "pipe:0", "-an", "-c:v", "libx264", + "-preset", "fast", "-crf", "18", "-pix_fmt", "yuv420p", + "-movflags", "+faststart", str(self.temporary), + ], stdin=subprocess.PIPE, stderr=subprocess.PIPE) + + def write(self, frame_bgr: np.ndarray) -> None: + if frame_bgr.shape != (*self.frame_hw, 3) or frame_bgr.dtype != np.uint8: + raise ValueError("video frame shape/dtype mismatch") + if self.process.stdin is None: + raise RuntimeError("ffmpeg stdin unavailable") + self.process.stdin.write(np.ascontiguousarray(frame_bgr).tobytes()) + self.frames += 1 + + def close(self) -> None: + assert self.process.stdin is not None + self.process.stdin.close() + stderr = self.process.stderr.read().decode("utf-8", errors="replace") if self.process.stderr else "" + return_code = self.process.wait() + if return_code: + self.temporary.unlink(missing_ok=True) + raise RuntimeError(f"ffmpeg failed: {stderr.strip()}") + os.replace(self.temporary, self.path) + + def abort(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + if self.process.poll() is None: + self.process.terminate() + self.process.wait(timeout=10) + self.temporary.unlink(missing_ok=True) + + +def add_header(image: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image.copy() + height = 8 + 24 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (9, 21 + 24 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.58, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def ranked_failure_takes( + cache_manifest: dict[str, Any], count: int, +) -> list[dict[str, object]]: + records = [] + for record in cache_manifest["takes"]: + arrays = load_take(Path(record["path"])) + error = np.linalg.norm( + arrays["pred_joints_camera"] - arrays["target_joints_camera"], axis=-1, + ) * 1000.0 + valid = arrays["joint_element_valid"].astype(bool) + values = error[valid] + if not len(values) or not np.isfinite(values).all(): + continue + records.append({ + "take": str(arrays["take"]), "path": record["path"], + "frames": len(arrays["frame_id"]), + "raw_absolute_mpjpe_mm": float(values.mean()), + }) + if len(records) < count: + raise ValueError("not enough annotated takes for filtered video cases") + return sorted( + records, key=lambda row: (-float(row["raw_absolute_mpjpe_mm"]), str(row["take"])), + )[:count] + + +def project_joints(joints: np.ndarray, K: np.ndarray) -> np.ndarray: + pixels, z = project_camera_points(joints, K) + pixels[z <= 1e-8] = np.nan + return pixels + + +def overlay_joints( + image_rgb: np.ndarray, + joints: np.ndarray, + K: np.ndarray, + color: tuple[int, int, int], + valid_hands: np.ndarray | None = None, +) -> np.ndarray: + output = image_rgb + for hand in range(2): + if valid_hands is not None and not bool(valid_hands[hand]): + continue + output = draw_skeleton( + output, project_joints(joints[hand], K), color, + marker="ring" if color == GT_COLOR else "circle", + ) + return output + + +def side_limits(*joint_sequences: np.ndarray) -> tuple[float, float, float, float]: + points = np.concatenate([values.reshape(-1, 3) for values in joint_sequences]) + finite = points[np.isfinite(points).all(axis=-1)] + if not len(finite): + return -0.4, 0.4, 0.2, 0.9 + x0, x1 = np.percentile(finite[:, 0], (1, 99)) + z0, z1 = np.percentile(finite[:, 2], (1, 99)) + x_margin = max(0.03, 0.1 * (x1 - x0)) + z_margin = max(0.03, 0.1 * (z1 - z0)) + return x0 - x_margin, x1 + x_margin, z0 - z_margin, z1 + z_margin + + +def camera_side_panel( + raw_joints: np.ndarray, + filtered_joints: np.ndarray, + target_joints: np.ndarray, + valid_hands: np.ndarray, + limits: tuple[float, float, float, float], + frame_id: int, + size: tuple[int, int] = (540, 960), +) -> np.ndarray: + height, width = size + panel = np.full((height, width, 3), 248, dtype=np.uint8) + x0, x1, z0, z1 = limits + + def point(value: np.ndarray) -> tuple[int, int]: + x = int(round(50 + (value[0] - x0) / max(x1 - x0, 1e-6) * (width - 100))) + y = int(round(height - 45 - (value[2] - z0) / max(z1 - z0, 1e-6) * (height - 100))) + return x, y + + cv2.rectangle(panel, (50, 45), (width - 50, height - 45), (50, 50, 50), 1) + for joints, color, valid_only in ( + (target_joints, GT_COLOR, True), + (raw_joints, RAW_COLOR, False), + (filtered_joints, FILTERED_COLOR, False), + ): + for hand in range(2): + if valid_only and not valid_hands[hand]: + continue + finite = np.isfinite(joints[hand]).all(axis=-1) + for start, end in OPENPOSE_HAND_EDGES: + if finite[start] and finite[end]: + cv2.line(panel, point(joints[hand, start]), point(joints[hand, end]), color, 2, cv2.LINE_AA) + for joint_index in np.flatnonzero(finite): + cv2.circle(panel, point(joints[hand, joint_index]), 2, color, -1, cv2.LINE_AA) + panel = add_header(panel, ( + f"Camera side view x/z | frame={frame_id}", + "GT=green raw=orange filtered=cyan", + )) + return panel + + +def trace_panel( + raw_error: np.ndarray, + filtered_error: np.ndarray, + valid: np.ndarray, + current: int, + side: str, + size: tuple[int, int] = (540, 1920), +) -> np.ndarray: + height, width = size + panel = np.full((height, width, 3), 250, dtype=np.uint8) + finite_values = np.concatenate((raw_error[valid], filtered_error[valid])) + limit = max(10.0, float(np.percentile(np.abs(finite_values), 99))) if finite_values.size else 10.0 + left, right = 70, width - 35 + band_height = (height - 70) // 3 + for axis, axis_name in enumerate("xyz"): + top = 48 + axis * band_height + bottom = top + band_height - 12 + middle = (top + bottom) // 2 + cv2.line(panel, (left, middle), (right, middle), (150, 150, 150), 1) + cv2.putText(panel, f"{axis_name} +/-{limit:.0f}mm", (8, top + 18), cv2.FONT_HERSHEY_SIMPLEX, 0.48, AXIS_COLORS[axis], 1, cv2.LINE_AA) + + def points(values: np.ndarray) -> list[np.ndarray]: + output = [] + segment = [] + for index, value in enumerate(values[:, axis]): + if valid[index] and np.isfinite(value): + x = int(round(left + index / max(len(values) - 1, 1) * (right - left))) + y = int(round(middle - np.clip(value / limit, -1, 1) * (bottom - top) / 2)) + segment.append((x, y)) + elif segment: + output.append(np.asarray(segment, dtype=np.int32)) + segment = [] + if segment: + output.append(np.asarray(segment, dtype=np.int32)) + return output + + for segment in points(raw_error): + if len(segment) >= 2: + cv2.polylines(panel, [segment], False, (115, 115, 115), 1, cv2.LINE_AA) + for segment in points(filtered_error): + if len(segment) >= 2: + cv2.polylines(panel, [segment], False, AXIS_COLORS[axis], 2, cv2.LINE_AA) + current_x = int(round(left + current / max(len(raw_error) - 1, 1) * (right - left))) + cv2.line(panel, (current_x, 42), (current_x, height - 20), (20, 20, 20), 1) + return add_header(panel, ( + f"Signed wrist xyz error | {side} hand | raw=gray filtered=color", + )) + + +def worst_side(arrays: dict[str, np.ndarray]) -> int: + valid = arrays["joint_annotation_valid"].astype(bool) + signed_z = ( + arrays["pred_wrist_translation"] - arrays["target_wrist_translation"] + )[..., 2] * 1000.0 + means = [ + float(np.mean(np.abs(signed_z[:, hand][valid[:, hand]]))) + if valid[:, hand].any() else -1.0 + for hand in range(2) + ] + return int(np.argmax(means)) + + +def render_case( + *, + arrays: dict[str, np.ndarray], + condition_name: str, + filtered_translation: np.ndarray, + filtered_joints: np.ndarray, + data_root: Path, + output_dir: Path, +) -> dict[str, object]: + take = str(arrays["take"]) + take_dir = data_root / take + raw_K, source_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + output_dir.mkdir(parents=True, exist_ok=False) + paths = { + "raw_vs_filtered_30fps": output_dir / "raw_vs_filtered_30fps.mp4", + "raw_vs_filtered_4fps": output_dir / "raw_vs_filtered_4fps.mp4", + "failure_diagnostic_30fps": output_dir / "failure_diagnostic_30fps.mp4", + } + writers = { + "raw_vs_filtered_30fps": FFmpegWriter( + paths["raw_vs_filtered_30fps"], 30.0, (source_hw[0], source_hw[1] * 2), + ), + "raw_vs_filtered_4fps": FFmpegWriter( + paths["raw_vs_filtered_4fps"], 4.0, (source_hw[0], source_hw[1] * 2), + ), + "failure_diagnostic_30fps": FFmpegWriter( + paths["failure_diagnostic_30fps"], 30.0, (1080, 1920), + ), + } + side = worst_side(arrays) + side_name = "left" if side == 0 else "right" + valid_side = arrays["joint_annotation_valid"][:, side].astype(bool) + raw_error = ( + arrays["pred_wrist_translation"][:, side] + - arrays["target_wrist_translation"][:, side] + ) * 1000.0 + filtered_error = ( + filtered_translation[:, side] - arrays["target_wrist_translation"][:, side] + ) * 1000.0 + limits = side_limits( + arrays["pred_joints_camera"], filtered_joints, + arrays["target_joints_camera"], + ) + frame_hashes: dict[str, list[str]] = {key: [] for key in writers} + try: + for index, frame_id in enumerate(arrays["frame_id"].astype(int)): + image_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), cv2.IMREAD_COLOR, + ) + if image_bgr is None or image_bgr.shape[:2] != source_hw: + raise RuntimeError(f"raw RGB failure for {take}/{frame_id}") + image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) + raw_panel = overlay_joints( + image_rgb, arrays["pred_joints_camera"][index], raw_K, RAW_COLOR, + ) + raw_panel = add_header(raw_panel, ( + f"RAW model | {take} | frame={frame_id}", + "MANO joints=orange | 30 fps physical time", + )) + filtered_panel = overlay_joints( + image_rgb, filtered_joints[index], raw_K, FILTERED_COLOR, + ) + filtered_panel = add_header(filtered_panel, ( + f"FILTERED {condition_name} | {take} | frame={frame_id}", + "MANO joints=cyan | inference-only secondary", + )) + comparison_rgb = np.concatenate((raw_panel, filtered_panel), axis=1) + comparison_bgr = cv2.cvtColor(comparison_rgb, cv2.COLOR_RGB2BGR) + for key in ("raw_vs_filtered_30fps", "raw_vs_filtered_4fps"): + writers[key].write(comparison_bgr) + frame_hashes[key].append(hashlib.sha256(comparison_bgr.tobytes()).hexdigest()) + + diagnostic_overlay = overlay_joints( + image_rgb, arrays["target_joints_camera"][index], raw_K, + GT_COLOR, arrays["joint_annotation_valid"][index], + ) + diagnostic_overlay = overlay_joints( + diagnostic_overlay, arrays["pred_joints_camera"][index], raw_K, + RAW_COLOR, + ) + diagnostic_overlay = overlay_joints( + diagnostic_overlay, filtered_joints[index], raw_K, FILTERED_COLOR, + ) + diagnostic_overlay = add_header(diagnostic_overlay, ( + f"GT/raw/filtered overlay | {take} | frame={frame_id}", + "GT=green raw=orange filtered=cyan", + )) + top_left = cv2.resize(diagnostic_overlay, (960, 540), interpolation=cv2.INTER_AREA) + top_right = camera_side_panel( + arrays["pred_joints_camera"][index], filtered_joints[index], + arrays["target_joints_camera"][index], + arrays["joint_annotation_valid"][index], limits, frame_id, + ) + trace = trace_panel( + raw_error, filtered_error, valid_side, index, side_name, + ) + diagnostic_rgb = np.concatenate(( + np.concatenate((top_left, top_right), axis=1), trace, + ), axis=0) + diagnostic_bgr = cv2.cvtColor(diagnostic_rgb, cv2.COLOR_RGB2BGR) + writers["failure_diagnostic_30fps"].write(diagnostic_bgr) + frame_hashes["failure_diagnostic_30fps"].append( + hashlib.sha256(diagnostic_bgr.tobytes()).hexdigest() + ) + except Exception: + for writer in writers.values(): + writer.abort() + raise + for writer in writers.values(): + writer.close() + videos = { + key: { + "path": str(path.resolve()), "sha256": sha256(path), + "frames": writers[key].frames, + "fps": 4.0 if key.endswith("4fps") else 30.0, + "frame_pixel_sha256": frame_hashes[key], + } + for key, path in paths.items() + } + record = { + "take": take, "condition": condition_name, + "frames": len(arrays["frame_id"]), "trace_side": side_name, + "official_test_used": False, "videos": videos, + } + (output_dir / "case.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + return record + + +def assert_deterministic( + records: list[dict[str, object]], reference_manifest: Path, +) -> None: + reference = json.loads(reference_manifest.read_text(encoding="utf-8")) + reference_index = { + (record["take"], record["condition"]): record for record in reference["cases"] + } + observed_keys = {(record["take"], record["condition"]) for record in records} + if observed_keys != set(reference_index): + raise ValueError("visualization audit case grid mismatch") + for record in records: + other = reference_index.get((record["take"], record["condition"])) + if other is None: + raise ValueError("visualization audit case grid mismatch") + for video_name, video in record["videos"].items(): + if video["frame_pixel_sha256"] != other["videos"][video_name]["frame_pixel_sha256"]: + raise ValueError(f"visualization pixels are non-deterministic: {video_name}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--selection-json", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--case-count", type=int, default=3) + parser.add_argument("--audit-against", type=Path) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("filtered video output must be new or empty") + cache_manifest = json.loads( + (args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8") + ) + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + if ( + cache_manifest.get("status") != "complete" + or cache_manifest.get("official_test_used") is not False + or cache_manifest.get("scope") != "full" + or cache_manifest.get("clips") != 1495 + or cache_manifest.get("frames") != 11638 + or selection.get("status") != "selected" + or selection.get("official_test_used") is not False + or selection.get("selection_scope") + != "frozen_official_validation_subset_256" + or selection.get("checkpoint", {}).get("sha256") + != cache_manifest.get("checkpoint", {}).get("sha256") + ): + raise ValueError("filtered video cache/selection provenance mismatch") + selected_conditions = [ + value for family, value in sorted(selection["selected_conditions"].items()) + if value is not None + ] + if not selected_conditions: + raise ValueError("no eligible filter condition was selected") + grid = condition_grid() + cases = ranked_failure_takes(cache_manifest, args.case_count) + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + records = [] + for condition_name in selected_conditions: + condition = grid[condition_name] + for rank, case in enumerate(cases, start=1): + arrays = load_take(Path(case["path"])) + filtered_translation, filtered_rotations, _ = filtered_parameters( + arrays, condition, + ) + _, filtered_joints = rebuild_geometry( + filtered_rotations, arrays["pred_shape"].astype(np.float32), + filtered_translation, mano, device, + ) + record = render_case( + arrays=arrays, condition_name=condition_name, + filtered_translation=filtered_translation, + filtered_joints=filtered_joints, + data_root=args.data_root, + output_dir=( + args.output_dir / condition_name + / f"{rank:02d}_{str(case['take']).replace('/', '__')}" + ), + ) + record["rank"] = rank + record["raw_absolute_mpjpe_mm"] = case["raw_absolute_mpjpe_mm"] + records.append(record) + if args.audit_against is not None: + assert_deterministic(records, args.audit_against) + manifest = { + "status": "complete", + "official_test_used": False, + "result_role": "filtered_inference_secondary_results", + "cache_checkpoint": cache_manifest["checkpoint"], + "selection_json": str(args.selection_json.resolve()), + "conditions": selected_conditions, + "case_selection": "highest raw take-level absolute MPJPE", + "deterministic_against": ( + str(args.audit_against.resolve()) if args.audit_against else None + ), + "deterministic_pixel_audit_passed": args.audit_against is not None, + "cases": records, + } + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "video_manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "conditions": selected_conditions, + "cases": len(records), "deterministic_audit": args.audit_against is not None, + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/render_phase5_alignment_failure_cases.py b/home/wuyifan/EgoNet_train_20261008/scripts/render_phase5_alignment_failure_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..051fe5d245d148f74274f9d9d3dc2463f44468db --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/render_phase5_alignment_failure_cases.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +"""Render deterministic predicted-MANO/depth alignment failure diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import matplotlib +import numpy as np + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def select_cases( + rows: list[dict[str, str]], refined_condition: str, +) -> list[dict[str, Any]]: + keyed: dict[tuple[str, int, str], dict[str, dict[str, str]]] = {} + for row in rows: + if row["condition"] not in ("coarse", refined_condition): + continue + key = (row["take"], int(row["frame_id"]), row["side"]) + keyed.setdefault(key, {})[row["condition"]] = row + pairs = [ + (key, values["coarse"], values[refined_condition]) + for key, values in keyed.items() + if set(values) == {"coarse", refined_condition} + ] + if not pairs: + raise ValueError("no matched coarse/refined frame rows") + + def z(row: dict[str, str]) -> float: + return float(row["translation_z_mae_mm"]) + + role_candidates = { + "right_far_small_tail": sorted( + ( + item for item in pairs + if item[0][2] == "right" and ( + item[1]["depth_bucket"] == "far" + or item[1]["hand_size_bucket"] == "small" + ) + ), + key=lambda item: (-z(item[1]), item[0]), + ), + "largest_z_gain": sorted( + pairs, key=lambda item: (-(z(item[1]) - z(item[2])), item[0]), + ), + "largest_z_harm": sorted( + pairs, key=lambda item: (-(z(item[2]) - z(item[1])), item[0]), + ), + } + selected = [] + used: set[tuple[str, int, str]] = set() + for role, candidates in role_candidates.items(): + choice = next((item for item in candidates if item[0] not in used), None) + if choice is None: + raise ValueError(f"cannot select a unique case for {role}") + key, coarse, refined = choice + used.add(key) + selected.append({ + "role": role, + "take": key[0], + "frame_id": key[1], + "side": key[2], + "coarse_z_mae_mm": z(coarse), + "refined_z_mae_mm": z(refined), + "z_mae_delta_mm": z(refined) - z(coarse), + "coarse_absolute_mpjpe_mm": float(coarse["absolute_mpjpe_mm"]), + "refined_absolute_mpjpe_mm": float(refined["absolute_mpjpe_mm"]), + "applied_delta_z_mm": float(refined["applied_delta_z_mm"]), + "alignment_confidence": float(refined["alignment_confidence"]), + "alignment_support": int(refined["alignment_support"]), + "alignment_quality": float(refined["alignment_quality"]), + "depth_bucket": coarse["depth_bucket"], + "hand_size_bucket": coarse["hand_size_bucket"], + }) + return selected + + +def inlier_masks( + observed_depth_m: np.ndarray, + predicted_depth_m: np.ndarray, + sample_valid: np.ndarray, + delta_z_m: float, + residual_scale_m: float, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + residual = observed_depth_m - predicted_depth_m + eligible = sample_valid & np.isfinite(residual) & (np.abs(residual) <= 0.15) + scale = max(float(residual_scale_m), 0.003) + inlier = eligible & (np.abs(residual - float(delta_z_m)) <= 1.345 * scale) + return eligible, inlier, eligible & ~inlier + + +def crop_bounds( + points_px: np.ndarray, image_hw: tuple[int, int], minimum_size: int = 240, +) -> tuple[int, int, int, int]: + height, width = image_hw + points = np.asarray(points_px, dtype=np.float64).reshape(-1, 2) + points = points[np.isfinite(points).all(axis=1)] + if not len(points): + return 0, 0, width, height + low, high = points.min(axis=0), points.max(axis=0) + center = (low + high) / 2.0 + size = max(float(np.max(high - low) + 120.0), float(minimum_size)) + size = min(size, float(width), float(height)) + x0 = int(np.clip(round(center[0] - size / 2), 0, width - size)) + y0 = int(np.clip(round(center[1] - size / 2), 0, height - size)) + return x0, y0, int(x0 + size), int(y0 + size) + + +def draw_points( + axis: plt.Axes, points: np.ndarray, color: str, label: str, + *, marker: str = "o", size: float = 10.0, alpha: float = 0.9, +) -> None: + values = np.asarray(points) + finite = np.isfinite(values).all(axis=-1) + axis.scatter( + values[finite, 0], values[finite, 1], s=size, c=color, + marker=marker, alpha=alpha, label=label, linewidths=0.4, + ) + + +def render_case( + case: dict[str, Any], + *, + cache_arrays: dict[str, np.ndarray], + alignment_arrays: dict[str, np.ndarray], + data_root: Path, + output: Path, +) -> dict[str, Any]: + frame_ids = cache_arrays["frame_id"].astype(np.int64) + matches = np.where(frame_ids == int(case["frame_id"]))[0] + if len(matches) != 1: + raise ValueError(f"frame is not unique in raw cache: {case}") + index = int(matches[0]) + hand = 1 if case["side"] == "right" else 0 + take_dir = data_root / case["take"] + frame_name = f"{int(case['frame_id']):06d}.png" + rgb_bgr = cv2.imread(str(take_dir / "rgb" / frame_name), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(take_dir / "depth" / frame_name), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise FileNotFoundError(f"missing RGB/depth for {case['take']}/{frame_name}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + if tuple(rgb.shape[:2]) != raw_hw or tuple(depth_mm.shape) != raw_hw: + raise ValueError("raw RGB/depth/intrinsics dimensions disagree") + depth_m, depth_valid = depth_mm_to_m(depth_mm) + coarse_vertices = cache_arrays["pred_vertices_camera"][index, hand] + diagnostics, surface = align_wrist_z(coarse_vertices, K_raw, depth_m, depth_valid) + if surface is None: + raise AssertionError("complete-modality case has no surface samples") + stored_delta = float(alignment_arrays["raw_alignment_delta_z_m"][index, hand]) + if abs(diagnostics.delta_z_m - stored_delta) > 1e-8: + raise ValueError("rerender alignment delta differs from evaluated prediction") + correction = float(alignment_arrays["calibrated_delta_z_m"][index, hand]) + eligible, inlier, outlier = inlier_masks( + surface.observed_depth_m, surface.predicted_depth_m, + surface.sample_valid, diagnostics.delta_z_m, diagnostics.residual_scale_m, + ) + + coarse_joints = cache_arrays["pred_joints_camera"][index, hand].astype(np.float64) + target_joints = cache_arrays["target_joints_camera"][index, hand].astype(np.float64) + refined_joints = coarse_joints.copy() + refined_joints[:, 2] += correction + coarse_px, _ = project_points(coarse_joints, K_raw) + refined_px, _ = project_points(refined_joints, K_raw) + target_px, _ = project_points(target_joints, K_raw) + bounds = crop_bounds( + np.concatenate((coarse_px, target_px, surface.projected_vertices_px[surface.visible_vertex])), + raw_hw, + ) + x0, y0, x1, y1 = bounds + offset = np.asarray((x0, y0)) + + figure, axes = plt.subplots(2, 3, figsize=(16, 9), dpi=120) + rgb_axis = axes[0, 0] + rgb_axis.imshow(rgb[y0:y1, x0:x1]) + draw_points(rgb_axis, target_px - offset, "#2ca02c", "GT", marker="x", size=24) + draw_points(rgb_axis, coarse_px - offset, "#d6278b", "coarse", size=16) + draw_points(rgb_axis, refined_px - offset, "#00a6d6", "refined", marker="+", size=24) + rgb_axis.set_title(f"RGB projection | {case['side']}") + rgb_axis.legend(loc="upper right", fontsize=8) + rgb_axis.axis("off") + + depth_axis = axes[0, 1] + depth_display = np.where(depth_valid, depth_m, np.nan) + depth_axis.imshow(depth_display[y0:y1, x0:x1], cmap="turbo", vmin=0.25, vmax=1.25) + projected = surface.projected_vertices_px - offset + draw_points(depth_axis, projected[inlier], "#39d353", "IRLS inlier", size=13) + draw_points(depth_axis, projected[outlier], "#ff4d4f", "eligible outlier", marker="x", size=17) + invalid_visible = surface.visible_vertex & ~eligible + draw_points(depth_axis, projected[invalid_visible], "#dddddd", "invalid", size=5, alpha=0.45) + depth_axis.set_title("Observed metric depth + surface samples") + depth_axis.legend(loc="upper right", fontsize=7) + depth_axis.axis("off") + + scatter_axis = axes[0, 2] + predicted = surface.predicted_depth_m[eligible] + observed = surface.observed_depth_m[eligible] + scatter_axis.scatter(predicted[inlier[eligible]], observed[inlier[eligible]], s=9, c="#39d353", label="inlier") + scatter_axis.scatter(predicted[outlier[eligible]], observed[outlier[eligible]], s=12, c="#ff4d4f", marker="x", label="outlier") + if len(predicted): + low = float(min(predicted.min(), observed.min())) + high = float(max(predicted.max(), observed.max())) + grid = np.linspace(low, high, 100) + scatter_axis.plot(grid, grid, color="#666666", linewidth=1, label="surface identity") + scatter_axis.plot(grid, grid + diagnostics.delta_z_m, color="#d6278b", linewidth=1.3, label="raw IRLS shift") + scatter_axis.plot(grid, grid + correction, color="#00a6d6", linewidth=1.3, label="calibrated shift") + scatter_axis.set_xlabel("predicted MANO surface z (m)") + scatter_axis.set_ylabel("observed depth z (m)") + scatter_axis.set_title("Metric correspondence") + scatter_axis.grid(alpha=0.2) + scatter_axis.legend(fontsize=7) + + side_axis = axes[1, 0] + target_vertices = cache_arrays["target_vertices_camera"][index, hand] + refined_vertices = coarse_vertices.astype(np.float64).copy() + refined_vertices[:, 2] += correction + sample = np.arange(0, len(coarse_vertices), 6) + side_axis.scatter(coarse_vertices[sample, 2], coarse_vertices[sample, 0], s=3, c="#d6278b", alpha=0.35, label="coarse") + side_axis.scatter(refined_vertices[sample, 2], refined_vertices[sample, 0], s=3, c="#00a6d6", alpha=0.35, label="refined") + side_axis.scatter(target_vertices[sample, 2], target_vertices[sample, 0], s=3, c="#2ca02c", alpha=0.35, label="GT") + side_axis.set_xlabel("camera z (m)") + side_axis.set_ylabel("camera x (m)") + side_axis.set_title("Camera side view") + side_axis.grid(alpha=0.2) + side_axis.legend(fontsize=7) + side_axis.set_aspect("equal", adjustable="datalim") + + trace_axis = axes[1, 1] + start, stop = max(0, index - 20), min(len(frame_ids), index + 21) + trace_frames = frame_ids[start:stop] + coarse_signed = 1000.0 * ( + cache_arrays["pred_wrist_translation"][start:stop, hand, 2] + - cache_arrays["target_wrist_translation"][start:stop, hand, 2] + ) + refined_signed = coarse_signed + 1000.0 * alignment_arrays["calibrated_delta_z_m"][start:stop, hand] + trace_axis.plot(trace_frames, coarse_signed, color="#d6278b", label="coarse signed z") + trace_axis.plot(trace_frames, refined_signed, color="#00a6d6", label="refined signed z") + trace_axis.axhline(0.0, color="#555555", linewidth=0.8) + trace_axis.axvline(case["frame_id"], color="#111111", linestyle="--", linewidth=0.8) + trace_axis.set_xlabel("frame") + trace_axis.set_ylabel("pred - GT wrist z (mm)") + trace_axis.set_title("Local signed-z trace") + trace_axis.grid(alpha=0.2) + trace_axis.legend(fontsize=7) + + text_axis = axes[1, 2] + text_axis.axis("off") + text_axis.text(0.0, 1.0, "\n".join(( + f"role: {case['role']}", + f"take/frame: {case['take']} / {case['frame_id']}", + f"side, size, depth: {case['side']}, {case['hand_size_bucket']}, {case['depth_bucket']}", + f"coarse -> refined z MAE: {case['coarse_z_mae_mm']:.2f} -> {case['refined_z_mae_mm']:.2f} mm", + f"coarse -> refined MPJPE: {case['coarse_absolute_mpjpe_mm']:.2f} -> {case['refined_absolute_mpjpe_mm']:.2f} mm", + f"raw IRLS / calibrated delta-z: {1000.0 * diagnostics.delta_z_m:.2f} / {1000.0 * correction:.2f} mm", + f"support / inlier ratio: {diagnostics.valid_support_count} / {diagnostics.inlier_ratio:.3f}", + f"residual scale: {1000.0 * diagnostics.residual_scale_m:.2f} mm", + f"valid / foreground / background: {diagnostics.valid_fraction:.3f} / {diagnostics.foreground_fraction:.3f} / {diagnostics.background_fraction:.3f}", + f"depth discontinuity: {1000.0 * diagnostics.depth_discontinuity_m:.2f} mm", + f"conditioning / learned confidence: {diagnostics.conditioning_quality:.3f} / {case['alignment_confidence']:.3f}", + "selection: official-validation secondary diagnostic only", + )), va="top", family="monospace", fontsize=10) + figure.suptitle("Phase 5 predicted-location MANO-depth alignment diagnostic", fontsize=14) + figure.tight_layout() + output.parent.mkdir(parents=True, exist_ok=True) + figure.savefig(output) + plt.close(figure) + return { + **case, + "image": str(output.resolve()), + "image_sha256": sha256(output), + "eligible_surface_samples": int(eligible.sum()), + "inlier_surface_samples": int(inlier.sum()), + "outlier_surface_samples": int(outlier.sum()), + "rerender_raw_delta_z_mm": 1000.0 * diagnostics.delta_z_m, + "rerender_residual_scale_mm": 1000.0 * diagnostics.residual_scale_m, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-dir", type=Path, required=True) + parser.add_argument("--raw-cache-manifest", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--condition", default="calibrated_always") + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("visualization output directory must be new or empty") + evaluation = json.loads((args.evaluation_dir / "evaluation.json").read_text(encoding="utf-8")) + cache = json.loads(args.raw_cache_manifest.read_text(encoding="utf-8")) + if evaluation.get("official_test_used") is not False or cache.get("official_test_used") is not False: + raise ValueError("failure visualization requires test-free inputs") + if args.condition not in evaluation.get("conditions", []): + raise ValueError(f"condition is absent from evaluation: {args.condition}") + cases = select_cases( + load_csv(args.evaluation_dir / "per_hand_frame_metrics.csv"), args.condition, + ) + cache_by_take = {record["take"]: record for record in cache["takes"]} + records = [] + for case in cases: + cache_record = cache_by_take[case["take"]] + cache_path = Path(cache_record["path"]) + if sha256(cache_path) != cache_record["sha256"]: + raise ValueError(f"raw-cache hash mismatch: {cache_path}") + with np.load(cache_path, allow_pickle=False) as archive: + cache_arrays = {key: archive[key] for key in archive.files} + prediction_path = args.evaluation_dir / "predictions" / f"{'__'.join(Path(case['take']).parts)}.npz" + with np.load(prediction_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + filename = f"{case['role']}__{'__'.join(Path(case['take']).parts)}__f{case['frame_id']:06d}__{case['side']}.png" + records.append(render_case( + case, cache_arrays=cache_arrays, alignment_arrays=alignment, + data_root=args.data_root, output=args.output_dir / filename, + )) + report = { + "status": "complete", + "result_role": "official_validation_secondary_failure_diagnostic", + "selection_rule": ["right far/small maximum coarse z error", "largest refined z gain", "largest refined z harm"], + "condition": args.condition, + "evaluation": str(args.evaluation_dir.resolve()), + "raw_cache_manifest": str(args.raw_cache_manifest.resolve()), + "cases": records, + "used_for_model_or_threshold_selection": False, + "oracle_information_at_inference": False, + "official_test_used": False, + } + manifest_path = args.output_dir / "manifest.json" + manifest_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "cases": len(records), + "manifest": str(manifest_path), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/render_sota_projection_audit.py b/home/wuyifan/EgoNet_train_20261008/scripts/render_sota_projection_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..212336420b5c6d1a025fd254f26dc10df78e55fa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/render_sota_projection_audit.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Render deterministic GT/prediction projection checks for SOTA bundles.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + align_prediction, +) + + +EDGES = tuple( + edge + for finger_start in (1, 5, 9, 13, 17) + for edge in ( + (0, finger_start), + (finger_start, finger_start + 1), + (finger_start + 1, finger_start + 2), + (finger_start + 2, finger_start + 3), + ) +) +SIDE_COLORS = ((255, 200, 0), (0, 80, 255)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def project(points: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + normalized = points[..., :2] / points[..., 2:3] + return normalized @ intrinsics[:2, :2].T + intrinsics[:2, 2] + + +def draw_hand( + image: np.ndarray, + points: np.ndarray, + color: tuple[int, int, int], + *, + thickness: int, + radius: int, +) -> None: + rounded = np.rint(points).astype(np.int32) + for start, end in EDGES: + cv2.line( + image, + tuple(rounded[start]), + tuple(rounded[end]), + color, + thickness, + cv2.LINE_AA, + ) + for point in rounded: + cv2.circle(image, tuple(point), radius, color, -1, cv2.LINE_AA) + + +def make_panel( + image: np.ndarray, + label: str, + predicted: np.ndarray, + target: np.ndarray, + intrinsics: np.ndarray, + detected: np.ndarray, +) -> tuple[np.ndarray, float | None]: + panel = image.copy() + for hand in (0, 1): + draw_hand( + panel, + project(target[hand], intrinsics), + (245, 245, 245), + thickness=4, + radius=4, + ) + if detected[hand]: + draw_hand( + panel, + project(predicted[hand], intrinsics), + SIDE_COLORS[hand], + thickness=2, + radius=3, + ) + valid_hands = np.flatnonzero(detected) + error = None + if valid_hands.size: + error = float( + np.linalg.norm( + predicted[valid_hands] - target[valid_hands], axis=-1 + ).mean() + * 1000.0 + ) + cv2.rectangle(panel, (0, 0), (panel.shape[1], 46), (10, 10, 10), -1) + text = f"{label} Abs={error:.1f} mm" if error is not None else f"{label} missed" + cv2.putText( + panel, + text, + (12, 31), + cv2.FONT_HERSHEY_SIMPLEX, + 0.8, + (255, 255, 255), + 2, + cv2.LINE_AA, + ) + return panel, error + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--prediction", action="append", required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=6) + parser.add_argument("--panel-width", type=int, default=480) + args = parser.parse_args() + if args.samples <= 0 or args.panel_width <= 0: + raise ValueError("samples and panel width must be positive") + + ground_truth = GroundTruthBundle.load(args.ground_truth) + bundles: list[tuple[str, PredictionBundle, Path]] = [] + labels = set() + for spec in args.prediction: + label, separator, raw_path = spec.partition("=") + if not separator or not label or not raw_path or label in labels: + raise ValueError(f"Invalid or duplicate prediction spec: {spec}") + labels.add(label) + path = Path(raw_path).resolve() + bundles.append((label, align_prediction(PredictionBundle.load(path), ground_truth), path)) + + eligible = ground_truth.annotation_valid.all(axis=1) + for _, bundle, _ in bundles: + eligible &= bundle.detected.all(axis=1) + candidate_indices = np.flatnonzero(eligible) + if candidate_indices.size < args.samples: + raise ValueError("Not enough jointly valid/detected frames for projection audit") + positions = np.rint( + np.linspace(0, candidate_indices.size - 1, args.samples) + ).astype(np.int64) + selected = candidate_indices[positions] + + output_rows = [] + record_rows: list[dict[str, Any]] = [] + for frame_index in selected: + take = str(ground_truth.takes[frame_index]) + frame_id = int(ground_truth.frame_ids[frame_index]) + path = args.root / take / "rgb" / f"{frame_id:06d}.png" + image = cv2.imread(str(path)) + if image is None: + raise RuntimeError(f"Image decode failure: {path}") + panels = [] + for label, bundle, _ in bundles: + panel, error = make_panel( + image, + label, + bundle.joints_camera_m[frame_index], + ground_truth.joints_camera_m[frame_index], + ground_truth.intrinsics[frame_index], + bundle.detected[frame_index], + ) + height = round(panel.shape[0] * args.panel_width / panel.shape[1]) + panels.append(cv2.resize(panel, (args.panel_width, height))) + record_rows.append({ + "frame_key": str(ground_truth.frame_keys[frame_index]), + "model": label, + "absolute_mpjpe_mm": error, + }) + output_rows.append(np.concatenate(panels, axis=1)) + + audit_models = [] + height, width = image.shape[:2] + for label, bundle, path in bundles: + detected_points = bundle.joints_camera_m[bundle.detected] + K = np.repeat(ground_truth.intrinsics[:, None], 2, axis=1)[bundle.detected] + uv = np.einsum( + "nij,nkj->nki", + K[:, :2, :2], + detected_points[..., :2] / detected_points[..., 2:3], + ) + K[:, None, :2, 2] + in_frame = ( + (uv[..., 0] >= 0) + & (uv[..., 0] < width) + & (uv[..., 1] >= 0) + & (uv[..., 1] < height) + ) + audit_models.append({ + "label": label, + "prediction": str(path), + "prediction_sha256": sha256(path), + "detected_hand_frames": int(bundle.detected.sum()), + "finite_detected_fraction": float(np.isfinite(detected_points).all(axis=-1).mean()), + "positive_depth_fraction": float((detected_points[..., 2] > 0).mean()), + "projected_joint_in_frame_fraction": float(in_frame.mean()), + "wrist_z_m_percentiles": np.percentile( + detected_points[:, 0, 2], (1, 50, 99) + ).tolist(), + }) + + args.output_dir.mkdir(parents=True, exist_ok=True) + contact_sheet = np.concatenate(output_rows, axis=0) + contact_path = args.output_dir / "projection_contact_sheet.jpg" + if not cv2.imwrite(str(contact_path), contact_sheet, [cv2.IMWRITE_JPEG_QUALITY, 92]): + raise RuntimeError(f"Failed to write {contact_path}") + payload = { + "status": "pass", + "official_test_used": False, + "selection": "evenly spaced among frames valid and detected for every model", + "legend": "GT white; prediction left cyan and right red", + "selected_frame_keys": [ + str(ground_truth.frame_keys[index]) for index in selected + ], + "per_selected_frame": record_rows, + "models": audit_models, + "contact_sheet": str(contact_path.resolve()), + "contact_sheet_sha256": sha256(contact_path), + } + (args.output_dir / "visual_audit.json").write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(payload, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_dynhamr_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_dynhamr_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..84bdce419fb36846d43852afe76b93928b2290ea --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_dynhamr_h2o.py @@ -0,0 +1,627 @@ +#!/usr/bin/env python3 +"""Run the released Dyn-HaMR TTO pipeline zero-shot on H2O validation runs.""" + +from __future__ import annotations + +import argparse +import contextlib +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from scipy.interpolate import interp1d +from scipy.spatial.transform import Rotation, Slerp + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, frame_key +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--rescale-factor", type=float, default=1.3) + parser.add_argument("--max-runs", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + parser.add_argument( + "--run-indices", + nargs="*", + type=int, + help="Explicit global manifest-run order; overrides modulo sharding.", + ) + return parser.parse_args() + + +def _load_manifest_runs(path: Path) -> list[dict[str, Any]]: + runs = [json.loads(line) for line in path.read_text().splitlines() if line.strip()] + for run_index, run in enumerate(runs): + take = str(run["take"]) + if not take.endswith("/cam4"): + raise ValueError(f"Dyn-HaMR evaluation is cam4-only: {take}") + run["global_run_index"] = run_index + run["frame_ids"] = [int(value) for value in run["frame_ids"]] + return runs + + +def _import_hamer_runner(repo: Path) -> Any: + path = repo / "third-party" / "hamer" / "run.py" + spec = importlib.util.spec_from_file_location("dynhamr_released_hamer_runner", path) + if spec is None or spec.loader is None: + raise ImportError(f"Cannot import released HaMeR runner: {path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _to_numpy(value: Any) -> np.ndarray: + if torch.is_tensor(value): + return value.detach().float().cpu().numpy() + return np.asarray(value) + + +def _interpolate_rotvec(values: np.ndarray, visible: np.ndarray) -> np.ndarray: + output = values.copy() + indices = np.flatnonzero(visible) + if len(indices) < 2: + return output + times = np.arange(indices[0], indices[-1] + 1) + rotations = Rotation.from_rotvec(values[indices].reshape(len(indices), -1, 3)) + joint_count = rotations.as_rotvec().shape[1] + for joint in range(joint_count): + slerp = Slerp(indices, Rotation.from_rotvec(values[indices, joint])) + output[times, joint] = slerp(times).as_rotvec() + return output + + +def _interpolate_linear(values: np.ndarray, visible: np.ndarray) -> np.ndarray: + output = values.copy() + indices = np.flatnonzero(visible) + if len(indices) < 2: + return output + times = np.arange(indices[0], indices[-1] + 1) + function = interp1d(indices, values[indices], axis=0, kind="linear") + output[times] = function(times) + return output + + +def _extract_initialization( + frame_paths: list[Path], + raw_data: list[dict[str, Any]], + results: dict[str, Any], +) -> dict[str, np.ndarray]: + count = len(frame_paths) + pose = np.full((2, count, 15, 3), np.nan, dtype=np.float32) + orient = np.full((2, count, 1, 3), np.nan, dtype=np.float32) + shape = np.full((2, count, 10), np.nan, dtype=np.float32) + translation = np.full((2, count, 3), np.nan, dtype=np.float32) + keypoints = np.full((2, count, 21, 3), np.nan, dtype=np.float32) + confidence = np.full((2, count), np.nan, dtype=np.float32) + + for frame_index, (path, cleaned) in enumerate(zip(frame_paths, raw_data, strict=True)): + result = results[str(path)] + sides = np.asarray(result["tid"], dtype=np.int64) + for local, side in enumerate(sides): + mano = result["mano"][local] + hand_matrix = _to_numpy(mano["hand_pose"]).reshape(15, 3, 3) + root_matrix = _to_numpy(mano["global_orient"]).reshape(3, 3) + pose[side, frame_index] = Rotation.from_matrix(hand_matrix).as_rotvec() + orient[side, frame_index, 0] = Rotation.from_matrix(root_matrix).as_rotvec() + shape[side, frame_index] = _to_numpy(mano["betas"]).reshape(10) + translation[side, frame_index] = np.asarray( + result["cam_trans"][local], dtype=np.float32 + ) + keypoints[side, frame_index] = np.asarray( + result["extra_data"][local], dtype=np.float32 + ) + confidence[side, frame_index] = float( + cleaned["left_conf" if side == 0 else "right_conf"] + ) + + active = np.isfinite(pose).all(axis=(-1, -2)) + recovered = np.zeros_like(active) + vis_mask = np.full((2, count), -1.0, dtype=np.float32) + for side in (0, 1): + indices = np.flatnonzero(active[side]) + if len(indices) < 2: + continue + interval = slice(indices[0], indices[-1] + 1) + recovered[side, interval] = True + vis_mask[side, interval] = 0.0 + vis_mask[side, active[side]] = 1.0 + pose[side] = _interpolate_rotvec(pose[side], active[side]) + orient[side] = _interpolate_rotvec(orient[side], active[side]) + shape[side] = _interpolate_linear(shape[side], active[side]) + translation[side] = _interpolate_linear(translation[side], active[side]) + keypoints[side] = _interpolate_linear(keypoints[side], active[side]) + confidence[side] = _interpolate_linear(confidence[side], active[side]) + # The released file loader represents frames outside each recovered track + # with zeros and excludes them through the ternary visibility mask. + for values in (pose, orient, shape, translation, keypoints): + np.nan_to_num(values, copy=False) + return { + "pose": pose, + "orient": orient[:, :, 0], + "shape": shape, + "translation": translation, + "keypoints": keypoints, + "confidence": confidence, + "active": active, + "recovered": recovered, + "vis_mask": vis_mask, + } + + +def _run_official_initialization( + repo: Path, + frame_paths: list[Path], + detector: Any, + hamer_model: torch.nn.Module, + hamer_config: Any, + runner: Any, + rescale_factor: float, +) -> dict[str, np.ndarray]: + raw_data = runner.extract_raw_bboxes(frame_paths, detector, vis_dir=None) + cleaned_data = runner.clean_bbox_sequences(raw_data, vis_dir=None) + results = runner.run_hamer_on_cleaned_bboxes( + cleaned_data, + hamer_model, + hamer_config, + None, + SimpleNamespace( + rescale_factor=rescale_factor, + render=False, + res_folder=str(repo / "outputs" / "unused.pkl"), + ), + ) + return _extract_initialization(frame_paths, cleaned_data, results) + + +class _InactiveBMCLoss: + """Avoid loading unavailable BMC assets when all official bio weights are zero.""" + + def __init__(self, *_: Any, **__: Any) -> None: + pass + + def compute_loss(self, *_: Any, **__: Any) -> Any: + raise RuntimeError("BMC loss called although the released bio weight is zero") + + +def _run_optimizer_exact( + optimizer: Any, + observed: dict[str, Any], + iterations: int, +) -> int: + """Run the released outer-loop and early-stop logic without file checkpoints.""" + + optimizer.cur_step = 0 + optimizer.loss.cur_step = 0 + completed = 0 + for iteration in range(iterations): + optimizer.cur_step = iteration + optimizer.loss.cur_step = iteration + optimizer.optim_step(observed, iteration, writer=None) + completed = iteration + 1 + if np.isnan(optimizer.cur_loss): + raise FloatingPointError(f"{optimizer.name} produced NaN") + if optimizer.reached_max and optimizer.reached_max_iter < 0: + optimizer.reached_max_iter = iteration - 1 + if ( + optimizer.reached_max + and iteration - optimizer.reached_max_iter >= optimizer.max_chunk_steps + ): + break + loss_change = optimizer.prev_loss - optimizer.cur_loss + if optimizer.last_updated == iteration - 1 and loss_change == 0: + break + if ( + (optimizer.cur_loss < 0 and loss_change < 100) + or (iteration - optimizer.last_updated >= optimizer.max_chunk_steps) + or (loss_change < 20 and iteration - optimizer.last_updated > 5) + ): + optimizer.add_chunk += 1 + optimizer.last_updated = iteration + optimizer.prev_loss = optimizer.cur_loss + return completed + + +def _optimize_run( + repo: Path, + initialization: dict[str, np.ndarray], + intrinsics: np.ndarray, + device: torch.device, + log_path: Path, +) -> tuple[np.ndarray, np.ndarray, dict[str, int]]: + sys.path.insert(0, str(repo / "dyn-hamr")) + from body_model import MANO + from optim import losses as loss_module + from optim.base_scene import BaseSceneModel + from optim.optimizers import RootOptimizer, SmoothOptimizer + from util.logger import Logger + + active_sides = np.flatnonzero(initialization["recovered"].any(axis=1)) + count = initialization["pose"].shape[1] + output_joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + output_vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + if len(active_sides) == 0: + return output_joints, output_vertices, {"root_iterations": 0, "smooth_iterations": 0} + + loss_module.BMCLoss = _InactiveBMCLoss + config = yaml.safe_load((repo / "dyn-hamr" / "confs" / "optim.yaml").read_text())[ + "optim" + ] + all_weights = config["loss_weights"] + stage_weights = [ + {name: values[stage] for name, values in all_weights.items()} + for stage in range(3) + ] + options = dict(config["options"]) + options["vis_every"] = -1 + options["save_meshes"] = False + + batch = len(active_sides) + mano = MANO( + batch_size=batch * count, + pose2rot=True, + model_path=str(repo / "_DATA" / "data" / "mano"), + gender="neutral", + num_hand_joints=15, + mean_params=str(repo / "_DATA" / "data" / "mano_mean_params.npz"), + create_body_pose=False, + ).to(device) + scene = BaseSceneModel( + batch, + count, + mano, + None, + use_init=True, + opt_cams=False, + opt_scale=False, + async_tracks=True, + ) + observed: dict[str, Any] = { + "joints2d": torch.from_numpy(initialization["keypoints"][active_sides]).to(device), + "init_body_pose": torch.from_numpy(initialization["pose"][active_sides]).to(device), + "init_body_shape": torch.from_numpy(initialization["shape"][active_sides]).to(device), + "init_root_orient": torch.from_numpy(initialization["orient"][active_sides]).to(device), + "init_trans": torch.from_numpy(initialization["translation"][active_sides]).to(device), + "is_right": torch.from_numpy( + np.broadcast_to(active_sides[:, None], (batch, count)).astype(np.float32).copy() + ).to(device), + "vis_mask": torch.from_numpy(initialization["vis_mask"][active_sides]).to(device), + } + cam_data = { + "cam_R": torch.eye(3, device=device)[None].repeat(count, 1, 1), + "cam_t": torch.zeros(count, 3, device=device), + "intrins": torch.from_numpy( + np.stack( + [ + intrinsics[:, 0, 0], + intrinsics[:, 1, 1], + intrinsics[:, 0, 2], + intrinsics[:, 1, 2], + ], + axis=-1, + ).astype(np.float32) + ).to(device), + "static": True, + } + scene.initialize(observed, cam_data) + scene = scene.to(device) + Logger.init(str(log_path)) + + root_optimizer = RootOptimizer(scene, stage_weights, **options) + root_iterations = _run_optimizer_exact( + root_optimizer, observed, int(config["root"]["num_iters"]) + ) + smooth_options = dict(options) + smooth_options["opt_scale"] = bool(config["smooth"]["opt_scale"]) + smooth_optimizer = SmoothOptimizer(scene, stage_weights, **smooth_options) + smooth_iterations = _run_optimizer_exact( + smooth_optimizer, observed, int(config["smooth"]["num_iters"]) + ) + + with torch.inference_mode(): + prediction = scene.pred_params_mano(observed["is_right"]) + predicted_joints = prediction["joints3d"].float().cpu().numpy() + predicted_vertices = prediction["verts3d"].float().cpu().numpy() + for local, side in enumerate(active_sides): + valid = initialization["recovered"][side] + output_joints[valid, side] = predicted_joints[local, valid] + output_vertices[valid, side] = predicted_vertices[local, valid] + del root_optimizer, smooth_optimizer, scene, mano + torch.cuda.empty_cache() + plt.close("all") + return output_joints, output_vertices, { + "root_iterations": root_iterations, + "smooth_iterations": smooth_iterations, + } + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "detector", + "root", + "manifest", + "ground_truth", + "cache_dir", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + args.cache_dir.mkdir(parents=True, exist_ok=True) + args.output.parent.mkdir(parents=True, exist_ok=True) + + enable_legacy_mano_loading() + hamer_root = args.repo / "third-party" / "hamer" + sys.path.insert(0, str(hamer_root)) + sys.path.insert(0, str(args.repo / "dyn-hamr")) + os.chdir(args.repo) + from hamer.models import load_hamer + from ultralytics import YOLO + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + hamer_model, hamer_config = load_hamer(str(args.repo)) + hamer_model = hamer_model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + hamer_runner = _import_hamer_runner(args.repo) + + all_runs = _load_manifest_runs(args.manifest) + if args.run_indices is not None: + if len(set(args.run_indices)) != len(args.run_indices): + raise ValueError("Explicit run indices contain duplicates") + if any(index < 0 or index >= len(all_runs) for index in args.run_indices): + raise ValueError("Explicit run index is outside the manifest") + selected = [all_runs[index] for index in args.run_indices] + else: + selected = [ + run + for run in all_runs + if int(run["global_run_index"]) % args.num_shards == args.shard_index + ] + if args.max_runs is not None: + selected = selected[: args.max_runs] + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + + frame_keys: list[str] = [] + takes: list[str] = [] + frame_ids: list[int] = [] + run_outputs: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]] = [] + total_root_iterations = 0 + total_smooth_iterations = 0 + initialized_runs = 0 + optimized_runs = 0 + initialization_seconds = 0.0 + optimization_seconds = 0.0 + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for selected_index, run in enumerate(selected): + run_index = int(run["global_run_index"]) + take = str(run["take"]) + ids = np.asarray(run["frame_ids"], dtype=np.int64) + keys = np.asarray([frame_key(take, int(value)) for value in ids], dtype=np.str_) + frame_paths = [ + args.root / take / "rgb" / f"{int(value):06d}.png" for value in ids + ] + if not all(path.is_file() for path in frame_paths): + raise FileNotFoundError(f"Missing H2O RGB frame in run {run_index}") + run_dir = args.cache_dir / f"run_{run_index:03d}" + run_dir.mkdir(parents=True, exist_ok=True) + init_path = run_dir / "initialization.npz" + pred_path = run_dir / "prediction.npz" + log_path = run_dir / "optimizer.log" + if init_path.is_file(): + with np.load(init_path, allow_pickle=False) as data: + initialization = {name: data[name].copy() for name in data.files} + else: + if device.type == "cuda": + torch.cuda.synchronize(device) + stage_started = time.perf_counter() + with log_path.open("a", encoding="utf-8") as log, contextlib.redirect_stdout( + log + ), contextlib.redirect_stderr(log): + initialization = _run_official_initialization( + args.repo, + frame_paths, + detector, + hamer_model, + hamer_config, + hamer_runner, + args.rescale_factor, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + initialization_seconds += time.perf_counter() - stage_started + np.savez_compressed(init_path, **initialization) + initialized_runs += 1 + confidence = initialization["confidence"] + recovered = initialization["recovered"] + if pred_path.is_file(): + with np.load(pred_path, allow_pickle=False) as data: + run_joints = data["joints"].copy() + run_vertices = data["vertices"].copy() + iteration_counts = json.loads(str(data["iteration_counts_json"].item())) + else: + indices = np.asarray([gt_index[str(key)] for key in keys], dtype=np.int64) + # The released optimizer prints full pose tensors for every LBFGS + # closure. Logger still records scalar losses in optimizer.log. + if device.type == "cuda": + torch.cuda.synchronize(device) + stage_started = time.perf_counter() + with Path(os.devnull).open("w") as sink, contextlib.redirect_stdout( + sink + ), contextlib.redirect_stderr(sink): + run_joints, run_vertices, iteration_counts = _optimize_run( + args.repo, + initialization, + ground_truth.intrinsics[indices], + device, + log_path, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + optimization_seconds += time.perf_counter() - stage_started + np.savez_compressed( + pred_path, + joints=run_joints, + vertices=run_vertices, + iteration_counts_json=np.asarray(json.dumps(iteration_counts)), + ) + optimized_runs += 1 + total_root_iterations += int(iteration_counts["root_iterations"]) + total_smooth_iterations += int(iteration_counts["smooth_iterations"]) + frame_keys.extend(keys.tolist()) + takes.extend([take] * len(ids)) + frame_ids.extend(ids.tolist()) + run_outputs.append((run_joints, run_vertices, recovered.T, confidence.T)) + print( + f"Dyn-HaMR run {selected_index + 1}/{len(selected)} " + f"global={run_index} frames={len(ids)} " + f"iters={iteration_counts['root_iterations']}/{iteration_counts['smooth_iterations']}", + flush=True, + ) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "Dyn-HaMR", + "scope": "RGB detector/HaMeR initialization + per-run Root/Smooth test-time optimization", + "frames": int(sum(len(run["frame_ids"]) for run in selected)), + "runs": len(selected), + "processing_seconds": processing_seconds, + "frames_per_second": int(sum(len(run["frame_ids"]) for run in selected)) / processing_seconds, + "initialization_seconds": initialization_seconds, + "optimization_seconds": optimization_seconds, + "cache_and_host_overhead_seconds": processing_seconds - initialization_seconds - optimization_seconds, + "root_iterations": total_root_iterations, + "smooth_iterations": total_smooth_iterations, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + joints = np.concatenate([value[0] for value in run_outputs], axis=0) + vertices = np.concatenate([value[1] for value in run_outputs], axis=0) + detected = np.concatenate([value[2] for value in run_outputs], axis=0) + confidence = np.concatenate([value[3] for value in run_outputs], axis=0) + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + hamer_commit = subprocess.check_output( + ["git", "-C", str(hamer_root), "rev-parse", "HEAD"], text=True + ).strip() + hamer_checkpoint = args.repo / "_DATA" / "hamer_ckpts" / "checkpoints" / "hamer.ckpt" + reconstruction_parameters = sum( + parameter.numel() for parameter in hamer_model.parameters() + ) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/ZhengdiYu/Dyn-HaMR", + "repository_commit": commit, + "hamer_repository_commit": hamer_commit, + "hamer_checkpoint": str(hamer_checkpoint), + "hamer_checkpoint_sha256": sha256(hamer_checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": ( + "full RGB video, released enhanced YOLO/HaMeR tracker, known static H2O cam4 K, " + "per-contiguous-run Root and Smooth test-time optimization" + ), + "training_exposure": ( + "Dyn-HaMR is test-time optimization; released HaMeR initializer training includes " + "H2O3D but not H2O; no H2O fine-tuning" + ), + "fine_tuning": "not applicable: adaptation is per-video test-time optimization", + "camera_policy": "known static H2O cam4 extrinsics/intrinsics; no SLAM or GT pose", + "optimizer_config": str(args.repo / "dyn-hamr" / "confs" / "optim.yaml"), + "optimizer_config_sha256": sha256(args.repo / "dyn-hamr" / "confs" / "optim.yaml"), + "root_iterations_total": total_root_iterations, + "smooth_iterations_total": total_smooth_iterations, + "run_count": len(selected), + "new_initializations": initialized_runs, + "new_optimizations": optimized_runs, + "rescale_factor": args.rescale_factor, + "detector_confidence_threshold": 0.5, + "temporal": True, + "temporal_protocol": "each official validation manifest run optimized independently", + "optional_hmp_prior_used": False, + "inactive_bmc_asset_policy": ( + "BMC object initialization skipped because released bio weights are zero in all stages" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + "explicit_run_indices": args.run_indices, + } + bundle = PredictionBundle( + model_name="Dyn-HaMR-zero-shot-TTO", + frame_keys=np.asarray(frame_keys, dtype=np.str_), + takes=np.asarray(takes, dtype=np.str_), + frame_ids=np.asarray(frame_ids, dtype=np.int64), + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_foundation_hand_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_foundation_hand_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..52771dd5f05a9772cec1488dad3789b731bb9065 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_foundation_hand_h2o.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Export the promoted Phase 3 model into the common SOTA prediction schema.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.evaluation.sota import PredictionBundle, frame_key, load_frame_index +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--max-clips", type=int) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + keys, takes, frame_ids = load_frame_index(args.manifest) + key_to_index = {str(key): index for index, key in enumerate(keys)} + count = len(keys) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), + (int(data_config["stride"]),), + max_clips=args.max_clips, + ) + loader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint( + args.checkpoint, model, optimizer=None, map_location=device + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + exported = 0 + processed_clips = 0 + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = { + name: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for name, value in batch_cpu.items() + } + with torch.autocast("cuda", dtype=dtype): + output = model(batch) + valid_length = int(batch["frame_valid"][0].sum()) + output_joints = output["joints_camera"][0, :valid_length].float().cpu().numpy() + output_vertices = output["vertices_camera"][0, :valid_length].float().cpu().numpy() + for time_index in range(valid_length): + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + frame_id_value = int(batch["frame_id"][0, time_index]) + index = key_to_index[frame_key(take, frame_id_value)] + joints[index] = output_joints[time_index] + vertices[index] = output_vertices[time_index] + detected[index] = True + exported += 1 + processed_clips = clip_index + 1 + if (clip_index + 1) % 100 == 0 or clip_index + 1 == len(loader): + print(f"FoundationHand clips {clip_index + 1}/{len(loader)}", flush=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + processed_frames = int(detected.all(axis=1).sum()) + if args.timing_output is not None: + timing_output = args.timing_output.resolve() + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "FoundationHand-Phase3", + "scope": "RGB+Depth+K decode/preprocessing + BF16 T=8 model forward + host result transfer", + "frames": processed_frames, + "clips": processed_clips, + "processing_seconds": processing_seconds, + "frames_per_second": processed_frames / processing_seconds, + "clips_per_second": processed_clips / processing_seconds, + "amortized_ms_per_frame": 1000.0 * processing_seconds / processed_frames, + "clip_length": int(data_config["T"]), + "resolution_hw": data_config["resolution_hw"], + "batch_size_clips": 1, + "num_workers": args.num_workers, + "precision": config["precision"], + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + if args.max_clips is not None: + processed = detected.all(axis=1) + keys, takes, frame_ids = keys[processed], takes[processed], frame_ids[processed] + joints, vertices = joints[processed], vertices[processed] + detected, confidence = detected[processed], confidence[processed] + elif exported != count: + raise RuntimeError(f"Expected {count} exported frames, observed {exported}") + + repository_commit = subprocess.check_output( + ["git", "rev-parse", "HEAD"], text=True + ).strip() + parameter_count = sum(parameter.numel() for parameter in model.parameters()) + trainable_parameter_count = sum( + parameter.numel() for parameter in model.parameters() if parameter.requires_grad + ) + bundle = PredictionBundle( + model_name="FoundationHand-Phase3", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata={ + "repository_commit_at_export": repository_commit, + "training_commit": "d4019222835132fcbcc850ba49e6e0b53ab352b3", + "checkpoint": str(args.checkpoint.resolve()), + "checkpoint_sha256": sha256(args.checkpoint), + "checkpoint_step": int(checkpoint_state["step"]), + "parameter_count": parameter_count, + "trainable_parameter_count_at_export": trainable_parameter_count, + "input": "full RGB + aligned metric Depth + H2O K, T=8", + "temporal": True, + "temporal_window": int(data_config["T"]), + "detector": False, + "fixed_semantic_slots": True, + "official_test_used": False, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_hamba_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_hamba_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..80aca96be62d8cdd4d3d9c34afa69fc86f906300 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_hamba_h2o.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Run the released Hamba checkpoint on H2O with a common hand detector.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, load_frame_index +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--preprocess-repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256") + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=8) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "preprocess_repo", + "checkpoint", + "config", + "detector", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + if args.checkpoint_sha256 is not None and ( + len(args.checkpoint_sha256) != 64 + or any(character not in "0123456789abcdef" for character in args.checkpoint_sha256) + ): + raise ValueError("--checkpoint-sha256 must be 64 lowercase hexadecimal characters") + + sys.path.insert(0, str(args.preprocess_repo)) + sys.path.insert(0, str(args.repo)) + enable_legacy_mano_loading() + os.chdir(args.repo) + + from hamba.configs import get_config + from hamba.models import HAMBA + from ultralytics import YOLO + from wilor.datasets.vitdet_dataset import ViTDetDataset + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + config = get_config(str(args.config), update_cachedir=True) + config.defrost() + config.MODEL.BBOX_SHAPE = [192, 256] + config.MODEL.BACKBONE.pop("PRETRAINED_WEIGHTS", None) + config.MODEL.pop("PRETRAINED_WEIGHTS_INIT_REGRESSION", None) + config.freeze() + if not config.MODEL.USE_INIT_REGRESSION: + raise ValueError("This adapter requires the released initial-regressor configuration") + model = HAMBA(config, init_renderer=False) + checkpoint = torch.load( + args.checkpoint, + map_location="cpu", + weights_only=False, + mmap=True, + ) + model.load_state_dict(checkpoint["state_dict"], strict=True) + del checkpoint + model = model.to(device).eval() + + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch["keypoints_2d"] = torch.zeros((batch_size, 21, 3), dtype=torch.float32) + batch["is_valid"] = torch.ones(batch_size, dtype=torch.int64) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + record_indices = np.asarray([record[0] for record in records]) + intrinsic = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (intrinsic[:, 0, 0] + intrinsic[:, 1, 1]) + principal = intrinsic[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + camera = torch.stack(( + pred_cam[:, 1] + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), dim=-1).float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + batch_joints += camera[:, None] + batch_vertices += camera[:, None] + for local, (frame_index, side, score, _) in enumerate(records): + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + dataset = ViTDetDataset( + config, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"Hamba detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + kernel_path = Path(sys.modules["selective_scan_cuda_oflex"].__file__).resolve() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/humansensinglab/Hamba", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": args.checkpoint_sha256 or sha256(args.checkpoint), + "config": str(args.config), + "config_sha256": sha256(args.config), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector hand boxes, per-hand crops", + "training_exposure": "zero-shot H2O; release config includes H2O3D but not H2O", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "camera_policy": "cam_crop_to_full algebra with known H2O focal/principal point", + "preprocessing": "official HaMeR-compatible crop geometry shared with WiLoR", + "joint_source": "released Hamba initial regressor; no GT or external 2D joints", + "test_time_augmentation": False, + "selective_scan_kernel": str(kernel_path), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="Hamba-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_handdgp_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_handdgp_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..6a22aa27e858db7aa398de80e9399957e95d783b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_handdgp_h2o.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Run the released FreiHAND HandDGP checkpoint zero-shot on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import cv2 +import kornia +import numpy as np +import torch + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + load_frame_index, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=32) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--crop-scale", type=float, default=1.3) + parser.add_argument("--input-size", type=int, default=224) + parser.add_argument("--canonical-focal", type=float, default=1000.0) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def _prepare_crop( + image_rgb: np.ndarray, + box_xyxy: np.ndarray, + intrinsic: np.ndarray, + *, + is_left: bool, + input_size: int, + crop_scale: float, + canonical_focal: float, + generate_patch_image: Any, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Apply the released square crop and canonical-intrinsics rectification.""" + + image = image_rgb + box = np.asarray(box_xyxy, dtype=np.float32).copy() + K = np.asarray(intrinsic, dtype=np.float32).copy() + if is_left: + width = image.shape[1] + image = np.ascontiguousarray(image[:, ::-1]) + box[[0, 2]] = (width - 1) - box[[2, 0]] + K[0, 2] = (width - 1) - K[0, 2] + + width = float(box[2] - box[0]) + height = float(box[3] - box[1]) + side = max(width, height) + center = np.asarray( + [(box[0] + box[2]) * 0.5, (box[1] + box[3]) * 0.5], + dtype=np.float32, + ) + square_box = ( + float(center[0] - 0.5 * side), + float(center[1] - 0.5 * side), + side, + side, + ) + crop, _, _, _, _ = generate_patch_image( + cvimg=image, + bbox=square_box, + scale=crop_scale, + rot=0.0, + shift=(0.0, 0.0), + do_flip=False, + out_shape=(input_size, input_size), + shift_wh=None, + mask=None, + ) + crop_tensor = torch.from_numpy(np.ascontiguousarray(crop)).float() + crop_tensor = crop_tensor.permute(2, 0, 1) / 255.0 + + # FreiHAND hands are centered close to the optical axis. For arbitrary + # detector crops, use the equivalent box-centered virtual camera and map + # its ray back to the raw H2O camera after inference. + focal_scaled = K[[0, 1], [0, 1]] * input_size / (side * crop_scale) + crop_intrinsic = np.asarray( + [ + [focal_scaled[0], 0.0, input_size * 0.5], + [0.0, focal_scaled[1], input_size * 0.5], + [0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + canonical_intrinsic = np.asarray( + [ + [canonical_focal, 0.0, input_size * 0.5], + [0.0, canonical_focal, input_size * 0.5], + [0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + rectification = torch.from_numpy( + canonical_intrinsic @ np.linalg.inv(crop_intrinsic) + ) + crop_tensor = kornia.geometry.transform.warp_affine( + crop_tensor.unsqueeze(0), + rectification[:2, :3].unsqueeze(0), + dsize=(input_size, input_size), + mode="bilinear", + padding_mode="zeros", + align_corners=True, + ).squeeze(0) + ray_offset = (center - K[:2, 2]) / K[[0, 1], [0, 1]] + return ( + crop_tensor, + torch.from_numpy(canonical_intrinsic), + torch.from_numpy(ray_offset.astype(np.float32)), + ) + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "checkpoint", + "detector", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from src.models.handdgp import HandDGP + from third_party.HandMesh.utils.preprocessing import generate_patch_image + from ultralytics import YOLO + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], + takes[: args.max_frames], + frame_ids[: args.max_frames], + ) + count = len(keys) + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack( + [ground_truth.intrinsics[gt_index[str(key)]] for key in keys] + ) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + model = HandDGP( + batch_size=args.reconstruction_batch_size, + imagenet_pretrain=False, + input_size=args.input_size, + ) + checkpoint = torch.load( + args.checkpoint, + map_location="cpu", + weights_only=False, + mmap=True, + ) + state_dict = { + name.removeprefix("model."): value + for name, value in checkpoint["state_dict"].items() + } + model.load_state_dict(state_dict, strict=True) + del checkpoint, state_dict + model = model.to(device).eval() + + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + queue: list[ + tuple[int, int, float, torch.Tensor, torch.Tensor, torch.Tensor] + ] = [] + + def flush_queue(force: bool = False) -> None: + while len(queue) >= args.reconstruction_batch_size or (force and queue): + batch_size = min(args.reconstruction_batch_size, len(queue)) + records = queue[:batch_size] + del queue[:batch_size] + images = torch.stack([record[3] for record in records]).to(device) + camera = torch.stack([record[4] for record in records]).to(device) + with torch.inference_mode(): + output = model(images, camera, hand_scale=0.2) + batch_joints = output["keypoints3D_cs"].float().cpu().numpy() + batch_vertices = output["mesh_vertices3D_cs"].float().cpu().numpy() + ray_offsets = torch.stack([record[5] for record in records]).numpy() + batch_joints[..., :2] += ( + ray_offsets[:, None] * batch_joints[..., 2:3] + ) + batch_vertices[..., :2] += ( + ray_offsets[:, None] * batch_vertices[..., 2:3] + ) + for local, (frame_index, side, score, _, _, _) in enumerate(records): + if side == 0: + batch_joints[local, :, 0] *= -1.0 + batch_vertices[local, :, 0] *= -1.0 + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images_bgr = [ + cv2.imread( + str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png") + ) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images_bgr): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images_bgr, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + image_rgb = cv2.cvtColor(images_bgr[local], cv2.COLOR_BGR2RGB) + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop, crop_intrinsic, ray_offset = _prepare_crop( + image_rgb, + boxes[choice], + intrinsics[frame_index], + is_left=side == 0, + input_size=args.input_size, + crop_scale=args.crop_scale, + canonical_focal=args.canonical_focal, + generate_patch_image=generate_patch_image, + ) + queue.append( + ( + frame_index, + side, + float(scores[choice]), + crop, + crop_intrinsic, + ray_offset, + ) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"HandDGP detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + handmesh_commit = subprocess.check_output( + [ + "git", + "-C", + str((args.repo / "third_party" / "HandMesh").resolve()), + "rev-parse", + "HEAD", + ], + text=True, + ).strip() + # Decoder upsampling matrices are fixed and repeated along the configured + # batch dimension. Count one copy so the reported model size is invariant + # to inference batch size. + reconstruction_parameters = sum( + parameter[0].numel() + if name.startswith("decoder3d.up_transform.") + else parameter.numel() + for name, parameter in model.named_parameters() + ) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/nianticlabs/HandDGP", + "repository_commit": commit, + "handmesh_repository_commit": handmesh_commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector boxes, per-hand crops", + "training_exposure": "released checkpoint trained only on FreiHAND; no H2O or H2O3D", + "fine_tuning": "not available: official repository contains inference/evaluation only", + "confidence_threshold": args.confidence_threshold, + "crop_scale": args.crop_scale, + "input_size": args.input_size, + "canonical_focal": args.canonical_focal, + "preprocessing": ( + "official square crop and canonical-intrinsics rectification; " + "left hands reflected before the right-hand model and mapped back in camera x" + ), + "camera_policy": ( + "official DGP in a box-centered virtual crop camera; known H2O K " + "maps the crop ray back to raw cam4" + ), + "joint_conversion": "official MPII output already matches H2O/OpenPose convention", + "hand_scale_m": 0.2, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="HandDGP-FreiHAND-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_hawor_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_hawor_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..d65afad091f550bdebc7783b6a1acebccb125a46 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_hawor_h2o.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Run HaWoR's official tracked camera-space hand stage on H2O validation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-left", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--confidence-threshold", type=float, default=0.2) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def contiguous_runs(takes: np.ndarray, frame_ids: np.ndarray) -> list[np.ndarray]: + starts = [0] + for index in range(1, len(frame_ids)): + if takes[index] != takes[index - 1] or frame_ids[index] != frame_ids[index - 1] + 1: + starts.append(index) + starts.append(len(frame_ids)) + return [np.arange(starts[i], starts[i + 1]) for i in range(len(starts) - 1)] + + +def main() -> None: + args = parse_args() + for name in ( + "repo", "checkpoint", "detector", "mano_left", "mano_right", "root", + "manifest", "ground_truth", "output", + ): + setattr(args, name, Path(getattr(args, name)).resolve()) + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + targets = ( + (args.repo / "_DATA" / "data" / "mano" / "MANO_RIGHT.pkl", args.mano_right), + (args.repo / "_DATA" / "data_left" / "mano_left" / "MANO_LEFT.pkl", args.mano_left), + ) + for target, source in targets: + if not target.exists(): + target.symlink_to(source) + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from ultralytics import YOLO + from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + from hawor.utils.process import run_mano, run_mano_left + from hawor.configs import get_config + from hawor.utils.rotation import rotation_matrix_to_angle_axis + from lib.models.hawor import HAWOR + + from foundation_hand.evaluation.sota import GroundTruthBundle + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + all_runs = contiguous_runs(takes, frame_ids) + selected_runs = [ + run for index, run in enumerate(all_runs) + if index % args.num_shards == args.shard_index + ] + selected_mask = np.zeros(count, dtype=bool) + for run in selected_runs: + selected_mask[run] = True + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + enable_legacy_mano_loading() + model_config = args.checkpoint.parent.parent / "model_config.yaml" + config = get_config(str(model_config), update_cachedir=True) + if config.MODEL.BACKBONE.TYPE == "vit" and "BBOX_SHAPE" not in config.MODEL: + config.defrost() + config.MODEL.BBOX_SHAPE = [192, 256] + config.freeze() + model = HAWOR.load_from_checkpoint( + str(args.checkpoint), + strict=False, + cfg=config, + map_location=device, + weights_only=False, + ) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + boxes = np.full((count, 2, 4), np.nan, dtype=np.float32) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for run_number, run_indices in enumerate(selected_runs, start=1): + if getattr(detector, "predictor", None) is not None: + for tracker in getattr(detector.predictor, "trackers", []): + if hasattr(tracker, "reset"): + tracker.reset() + image_paths = [ + args.root / str(takes[index]) / "rgb" / f"{int(frame_ids[index]):06d}.png" + for index in run_indices + ] + for local, image_path in enumerate(image_paths): + image = cv2.imread(str(image_path)) + if image is None: + raise RuntimeError(f"Image decode failure: {image_path}") + with torch.no_grad(): + result = detector.track( + image, + conf=args.confidence_threshold, + persist=True, + verbose=False, + )[0] + result_boxes = result.boxes.xyxy.float().cpu().numpy() + result_classes = result.boxes.cls.long().cpu().numpy() + result_scores = result.boxes.conf.float().cpu().numpy() + frame_index = int(run_indices[local]) + for side in (0, 1): + choices = np.flatnonzero(result_classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(result_scores[choices])]) + boxes[frame_index, side] = result_boxes[choice] + confidence[frame_index, side] = result_scores[choice] + + for side in (0, 1): + available = run_indices[np.isfinite(boxes[run_indices, side]).all(axis=1)] + # The released video pipeline requires two detections, then linearly + # interpolates missing boxes between the first and last detection. + if available.size < 2: + continue + segment = np.arange(int(available[0]), int(available[-1]) + 1) + for coordinate in range(4): + boxes[segment, side, coordinate] = np.interp( + frame_ids[segment], + frame_ids[available], + boxes[available, side, coordinate], + ) + segment_paths = np.asarray([ + str(args.root / str(takes[index]) / "rgb" / f"{int(frame_ids[index]):06d}.png") + for index in segment + ]) + K = intrinsics[int(segment[0])] + focal = float(0.5 * (K[0, 0] + K[1, 1])) + center = np.asarray([K[0, 2], K[1, 2]], dtype=np.float32) + results = model.inference( + segment_paths, + boxes[segment, side], + img_focal=focal, + img_center=center, + device=str(device), + do_flip=(side == 0), + ) + root_rotation = rotation_matrix_to_angle_axis( + results["pred_rotmat"][None, :, 0] + ) + hand_pose = rotation_matrix_to_angle_axis( + results["pred_rotmat"][None, :, 1:] + ) + if side == 0: + root_rotation[..., 1:] *= -1 + hand_pose[..., 1:] *= -1 + # Keep the exact official left/right MANO conversion after canonical + # left-hand input flipping. + if side == 0: + mano_output = run_mano_left( + results["pred_trans"][None, :, 0], + root_rotation, + hand_pose, + betas=results["pred_shape"][None], + ) + else: + mano_output = run_mano( + results["pred_trans"][None, :, 0], + root_rotation, + hand_pose, + betas=results["pred_shape"][None], + ) + joints[segment, side] = mano_output["joints"][0].float().cpu().numpy() + vertices[segment, side] = mano_output["vertices"][0].float().cpu().numpy() + detected[segment, side] = True + print( + f"HaWoR run {run_number}: frames through {int(run_indices[-1]) + 1}/{count}", + flush=True, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + selected_frames = int(selected_mask.sum()) + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "HaWoR", + "scope": "RGB decode + tracked detector + bbox interpolation + temporal reconstruction + MANO conversion", + "frames": selected_frames, + "detected_hand_frames": int(detected[selected_mask].sum()), + "processing_seconds": processing_seconds, + "frames_per_second": selected_frames / processing_seconds, + "temporal_window": 16, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + keys = keys[selected_mask] + takes = takes[selected_mask] + frame_ids = frame_ids[selected_mask] + joints = joints[selected_mask] + vertices = vertices[selected_mask] + detected = detected[selected_mask] + confidence = confidence[selected_mask] + bundle = PredictionBundle( + model_name="HaWoR-camera", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata={ + "official_repository": "https://github.com/ThunderVVV/HaWoR", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "tracked per-hand RGB crops in contiguous 16-frame windows", + "confidence_threshold": args.confidence_threshold, + "temporal": True, + "temporal_window": 16, + "side_assignment": "official tracked detector handedness; highest confidence per side/frame", + "bbox_gap_policy": "official linear interpolation between first/last per-run detections", + "camera_conversion": "official get_trans with H2O fx/fy mean and principal point", + "excluded_for_camera_metrics": ["DROID-SLAM", "Metric3D", "world-space infiller"], + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_pad_hand_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_pad_hand_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb890442b99e6018c5aa3ca6ca6c2cc4d695ed5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_pad_hand_h2o.py @@ -0,0 +1,501 @@ +#!/usr/bin/env python3 +"""Run the released PAD-Hand WiLoR refinement pipeline on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import types +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + load_frame_index, +) +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +MANO_TO_OPENPOSE = np.asarray( + [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20], + dtype=np.int64, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def install_torch_scatter_compat() -> None: + """Provide the single torch-scatter operation used by the released model.""" + + if "torch_scatter" in sys.modules: + return + + def scatter_add( + source: torch.Tensor, + index: torch.Tensor, + dim: int = -1, + out: torch.Tensor | None = None, + dim_size: int | None = None, + ) -> torch.Tensor: + if out is None: + output_shape = list(source.shape) + output_shape[dim] = ( + dim_size if dim_size is not None else int(index.max().item()) + 1 + ) + out = source.new_zeros(output_shape) + index_shape = [1] * source.ndim + index_shape[dim] = index.numel() + expanded_index = index.reshape(index_shape).expand_as(source) + return out.scatter_add_(dim, expanded_index, source) + + module = types.ModuleType("torch_scatter") + module.scatter_add = scatter_add + sys.modules["torch_scatter"] = module + + +def enable_legacy_checkpoint_loading() -> None: + """Restore the pre-PyTorch-2.6 default for trusted official checkpoints.""" + + original_load = torch.load + + def load(*args: Any, **kwargs: Any) -> Any: + kwargs.setdefault("weights_only", False) + return original_load(*args, **kwargs) + + torch.load = load + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--pad-repo", type=Path, required=True) + parser.add_argument("--wilor-repo", type=Path, required=True) + parser.add_argument("--pad-checkpoint", type=Path, required=True) + parser.add_argument("--wilor-checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument("--diffusion-steps", type=int, default=4) + parser.add_argument("--kappa-degrees", type=float, default=15.0) + parser.add_argument("--seed", type=int, default=20260720) + parser.add_argument("--max-takes", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def stable_window_seed(base_seed: int, take: str, side: int, frame_id: int) -> int: + payload = f"{base_seed}|{take}|{side}|{frame_id}".encode("utf-8") + return int.from_bytes(hashlib.sha256(payload).digest()[:8], "little") % (2**31) + + +def contiguous_runs(frame_ids: np.ndarray) -> list[np.ndarray]: + if frame_ids.size == 0: + return [] + boundaries = np.flatnonzero(np.diff(frame_ids) != 1) + 1 + return [part for part in np.split(np.arange(frame_ids.size), boundaries) if part.size] + + +def main() -> None: + args = parse_args() + for name in ( + "pad_repo", + "wilor_repo", + "pad_checkpoint", + "wilor_checkpoint", + "detector", + "mano_right", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + if args.diffusion_steps <= 0: + raise ValueError("--diffusion-steps must be positive") + + required_pad_assets = ( + "processed_MANO_RIGHT.pkl", + "MeshConv_template.ply", + "MeshConv_transform.pkl", + ) + for filename in required_pad_assets: + asset = args.pad_repo / "assets" / filename + if not asset.is_file(): + raise FileNotFoundError(f"Missing released PAD-Hand asset: {asset}") + wilor_mano = args.wilor_repo / "mano_data" / "MANO_RIGHT.pkl" + if not wilor_mano.exists(): + wilor_mano.symlink_to(args.mano_right) + + keys, takes, frame_ids = load_frame_index(args.manifest) + unique_takes = list(dict.fromkeys(map(str, takes.tolist()))) + if args.max_takes is not None: + unique_takes = unique_takes[: args.max_takes] + selected_takes = { + take + for index, take in enumerate(unique_takes) + if index % args.num_shards == args.shard_index + } + selected = np.asarray([str(take) in selected_takes for take in takes], dtype=bool) + keys, takes, frame_ids = keys[selected], takes[selected], frame_ids[selected] + if not len(keys): + raise ValueError("Shard contains no frames") + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + enable_legacy_mano_loading() + enable_legacy_checkpoint_loading() + sys.path.insert(0, str(args.wilor_repo)) + os.chdir(args.wilor_repo) + from ultralytics import YOLO + from wilor.datasets.vitdet_dataset import ViTDetDataset + from wilor.models import load_wilor + + wilor_model, wilor_cfg = load_wilor( + checkpoint_path=str(args.wilor_checkpoint), + cfg_path=str(args.wilor_repo / "pretrained_models" / "model_config.yaml"), + ) + wilor_model = wilor_model.to(device).eval() + detector = YOLO(str(args.detector)).to(device) + + count = len(keys) + relative_joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + relative_vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + cameras = np.full((count, 2, 3), np.nan, dtype=np.float32) + global_orient = np.full((count, 2, 1, 3, 3), np.nan, dtype=np.float32) + hand_pose = np.full((count, 2, 15, 3, 3), np.nan, dtype=np.float32) + betas = np.full((count, 2, 10), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = wilor_model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + record_indices = np.asarray([record[0] for record in records]) + K = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (K[:, 0, 0] + K[:, 1, 1]) + principal = K[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + camera = torch.stack( + ( + pred_cam[:, 1] + + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), + dim=-1, + ).float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + batch_global = ( + output["pred_mano_params"]["global_orient"].float().cpu().numpy() + ) + batch_pose = output["pred_mano_params"]["hand_pose"].float().cpu().numpy() + batch_betas = output["pred_mano_params"]["betas"].float().cpu().numpy() + for local, (frame_index, side, score, _) in enumerate(records): + relative_joints[frame_index, side] = batch_joints[local] + relative_vertices[frame_index, side] = batch_vertices[local] + cameras[frame_index, side] = camera[local] + global_orient[frame_index, side] = batch_global[local] + hand_pose[frame_index, side] = batch_pose[local] + betas[frame_index, side] = batch_betas[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop_dataset = ViTDetDataset( + wilor_cfg, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), crop_dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"PAD-Hand WiLoR initialization {end}/{count}", flush=True) + flush_queue(force=True) + + install_torch_scatter_compat() + sys.path.insert(0, str(args.pad_repo)) + os.chdir(args.pad_repo) + from models.MANO import MANO + from models.difussionsampler import DiffusionSampler + from models.pad_hand import PAD_Hand + from models.utils import batch_euler2matzxy, rotmat2eulerzxy + + pad_model = PAD_Hand( + device=device, + seqlen=16, + decoder=True, + d_model=512, + nhead=8, + d_hid=512, + nlayers=4, + dropout=0.1, + ).to(device) + checkpoint = torch.load(args.pad_checkpoint, map_location=device, weights_only=False) + pad_model.load_state_dict(checkpoint["model"]) + pad_model.eval() + pad_model.mode = "test" + mano = MANO("RIGHT", device) + sampler = DiffusionSampler( + args.diffusion_steps, np.deg2rad(args.kappa_degrees), device + ) + + refined_joints = relative_joints.copy() + refined_vertices = relative_vertices.copy() + refined_windows = 0 + missing_detection_windows = 0 + tail_frames = 0 + initializer_mesh_delta_sum = 0.0 + initializer_mesh_delta_count = 0 + + for take in dict.fromkeys(map(str, takes.tolist())): + take_indices = np.flatnonzero(takes == take) + order = np.argsort(frame_ids[take_indices]) + take_indices = take_indices[order] + take_frame_ids = frame_ids[take_indices] + for run_positions in contiguous_runs(take_frame_ids): + run_indices = take_indices[run_positions] + tail_frames += len(run_indices) % 16 * 2 + for side in (0, 1): + for window_start in range(0, len(run_indices) - 15, 16): + window = run_indices[window_start : window_start + 16] + if not detected[window, side].all(): + missing_detection_windows += 1 + continue + rotmats = np.concatenate( + (global_orient[window, side], hand_pose[window, side]), axis=1 + ) + rotmats_t = torch.from_numpy(rotmats).to(device) + betas_t = torch.from_numpy(betas[window, side]).to(device) + y0_pose = rotmat2eulerzxy(rotmats_t.reshape(-1, 3, 3)).reshape( + 1, 16, 48 + ) + y0_shape = betas_t.unsqueeze(0) + y0_shape_t = y0_shape.reshape(-1, 10) + y0_rotmat = batch_euler2matzxy(y0_pose.reshape(-1, 3))[0].reshape( + -1, 16, 3, 3 + ) + y0_mano = mano.forward(betas=y0_shape_t, thetas_rotmat=y0_rotmat) + y0_vertices = y0_mano.vertices + comparison_vertices = y0_vertices.detach().cpu().numpy().copy() + if side == 0: + comparison_vertices[..., 0] *= -1 + initializer_mesh_delta_sum += float( + np.linalg.norm( + comparison_vertices - relative_vertices[window, side], axis=-1 + ).sum() + ) + initializer_mesh_delta_count += comparison_vertices.shape[0] * 778 + + src_mask = torch.ones((1, 16), dtype=torch.bool, device=device) + x0_pose_pred = y0_pose.clone() + window_seed = stable_window_seed( + args.seed, take, side, int(frame_ids[window[0]]) + ) + torch.manual_seed(window_seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(window_seed) + with torch.no_grad(): + for step in range(args.diffusion_steps, 0, -1): + if step == args.diffusion_steps: + step_batch = torch.full( + (1,), float(args.diffusion_steps), device=device + ) + noisy_pose = y0_pose + np.deg2rad( + args.kappa_degrees + ) * torch.randn_like(y0_pose) + else: + step_batch = torch.full( + (1,), step, device=device, dtype=torch.long + ) + noisy_pose = sampler.q_sample( + x0_pose_pred, y0_pose - x0_pose_pred, step_batch + ) + noisy_rotmat = batch_euler2matzxy( + noisy_pose.reshape(-1, 3) + )[0].reshape(-1, 16, 3, 3) + noisy_mano = mano.forward( + betas=y0_shape_t, thetas_rotmat=noisy_rotmat + ) + _, decoder_prediction = pad_model.forward( + y0_vertices.reshape(1, 16, 778, 3), + noisy_mano.vertices.reshape(1, 16, 778, 3), + step_batch.float(), + src_mask, + mano, + y0_shape_t, + ) + refined_rotmat = decoder_prediction[-2] + refined_mano = decoder_prediction[-1] + x0_pose_pred = rotmat2eulerzxy( + refined_rotmat.reshape(-1, 3, 3) + ).reshape(1, 16, 48) + vertices_out = refined_mano.vertices.detach().cpu().numpy() + joints_out = refined_mano.joints.detach().cpu().numpy()[ + :, MANO_TO_OPENPOSE + ] + if side == 0: + vertices_out[..., 0] *= -1 + joints_out[..., 0] *= -1 + refined_vertices[window, side] = vertices_out + refined_joints[window, side] = joints_out + refined_windows += 1 + + joints_camera = refined_joints + cameras[:, :, None] + vertices_camera = refined_vertices + cameras[:, :, None] + pad_commit = subprocess.check_output( + ["git", "-C", str(args.pad_repo), "rev-parse", "HEAD"], text=True + ).strip() + wilor_commit = subprocess.check_output( + ["git", "-C", str(args.wilor_repo), "rev-parse", "HEAD"], text=True + ).strip() + wilor_parameters = sum(parameter.numel() for parameter in wilor_model.parameters()) + detector_parameters = sum( + parameter.numel() for parameter in detector.model.parameters() + ) + pad_parameters = sum(parameter.numel() for parameter in pad_model.parameters()) + metadata = { + "official_repository": "https://github.com/DominoAI-Lab/PAD-Hand-CVPR-2026", + "repository_commit": pad_commit, + "base_wilor_repository_commit": wilor_commit, + "checkpoint": str(args.pad_checkpoint), + "checkpoint_sha256": sha256(args.pad_checkpoint), + "base_wilor_checkpoint": str(args.wilor_checkpoint), + "base_wilor_checkpoint_sha256": sha256(args.wilor_checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "pad_parameter_count": pad_parameters, + "reconstruction_parameter_count": wilor_parameters + pad_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": ( + wilor_parameters + pad_parameters + detector_parameters + ), + "input": ( + "full RGB detector, per-detection RGB crop WiLoR initialization, " + "per-side non-overlapping 16-frame PAD-Hand diffusion refinement" + ), + "temporal": True, + "temporal_window": 16, + "diffusion_steps": args.diffusion_steps, + "kappa_degrees": args.kappa_degrees, + "sampling_seed": args.seed, + "sampling_seed_policy": "SHA256(base seed, take, side, first frame)", + "refined_windows": refined_windows, + "missing_detection_windows": missing_detection_windows, + "tail_hand_frames_falling_back_to_wilor": tail_frames, + "initializer_mesh_reconstruction_delta_mm": ( + 1000.0 * initializer_mesh_delta_sum / initializer_mesh_delta_count + if initializer_mesh_delta_count + else None + ), + "camera_policy": "h2o_intrinsics", + "camera_conversion": ( + "WiLoR cam_crop_to_full algebra with known H2O focal/principal point; " + "PAD-Hand does not update camera translation" + ), + "side_assignment": "official WiLoR detector handedness; independent PAD-Hand refinement", + "training_exposure": ( + "paper trains on DexYCB/HO3D; released checkpoint does not label its " + "training split; no H2O fine-tuning" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="PAD-Hand-WiLoR-H2O-K", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints_camera, + vertices_camera_m=vertices_camera, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase3_full_validation.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase3_full_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..fd398945a306fb8176703ee7bb83eb8f92f6d408 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase3_full_validation.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python3 +"""Evaluate every registered Phase 3 core checkpoint on official validation.""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import queue +import shlex +import subprocess +import threading +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +VAL_MANIFEST = Path("artifacts/phase2/data_audit/manifests/official_val.jsonl") + + +@dataclass(frozen=True) +class EvaluationJob: + name: str + run_name: str + role: str + config: Path + checkpoint: Path + output: Path + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + output = {} + for line in result.stdout.splitlines(): + index, uuid = (part.strip() for part in line.split(",", 1)) + output[int(index)] = uuid + return output + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if not line.strip(): + continue + uuid, pid = (part.strip() for part in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +DEFAULT_CHECKPOINT_FILES = { + "step_025k": "step_0025000.pt", + "step_050k": "step_0050000.pt", + "step_075k": "step_0075000.pt", + "step_100k": "step_0100000.pt", + "best_absolute": "best.pt", + "best_z": "best_z.pt", + "final": "step_0100000_final.pt", +} + + +def checkpoint_roles( + run_dir: Path, checkpoint_files: dict[str, str] | None = None, +) -> tuple[tuple[str, Path], ...]: + definitions = DEFAULT_CHECKPOINT_FILES if checkpoint_files is None else checkpoint_files + return tuple((role, run_dir / filename) for role, filename in definitions.items()) + + +def load_checkpoint_files(path: Path | None) -> dict[str, str]: + if path is None: + return dict(DEFAULT_CHECKPOINT_FILES) + values = json.loads(path.read_text(encoding="utf-8")) + if ( + not isinstance(values, dict) + or not values + or any(not isinstance(role, str) or not role for role in values) + or any( + not isinstance(filename, str) or Path(filename).name != filename + for filename in values.values() + ) + ): + raise ValueError("checkpoint spec must be a non-empty role-to-filename JSON object") + return values + + +def validation_state_path(output_root: Path, filename: str) -> Path: + if Path(filename).name != filename or not filename.endswith(".json"): + raise ValueError("state filename must be a JSON basename") + return output_root / filename + + +def build_jobs( + matrix_csv: Path, + run_root: Path, + output_root: Path, + roles: tuple[str, ...] | None = None, + checkpoint_files: dict[str, str] | None = None, +) -> list[EvaluationJob]: + available_roles = checkpoint_roles(Path("unused"), checkpoint_files) + selected_roles = set(roles or (role for role, _ in available_roles)) + with matrix_csv.open(newline="", encoding="utf-8") as handle: + matrix_rows = list(csv.DictReader(handle)) + jobs = [] + for row in matrix_rows: + config = Path(row["config"]) + run_name = row.get("run_name") or config.stem + for role, checkpoint in checkpoint_roles(run_root / run_name, checkpoint_files): + if role not in selected_roles: + continue + jobs.append(EvaluationJob( + name=f"{run_name}__{role}", run_name=run_name, role=role, + config=config, checkpoint=checkpoint, + output=output_root / run_name / role, + )) + return jobs + + +def validate_job_grid(jobs: list[EvaluationJob], roles: tuple[str, ...]) -> int: + """Validate one evaluation per run and selected checkpoint role.""" + if not jobs: + raise ValueError("evaluation matrix produced no jobs") + selected_roles = set(roles) + run_names = {job.run_name for job in jobs} + job_keys = {(job.run_name, job.role) for job in jobs} + expected_jobs = len(run_names) * len(selected_roles) + if len(job_keys) != len(jobs): + raise ValueError("evaluation matrix contains duplicate run/checkpoint-role jobs") + if len(jobs) != expected_jobs: + raise ValueError( + f"expected {len(run_names)} runs x {len(selected_roles)} checkpoint roles " + f"= {expected_jobs} jobs, got {len(jobs)}" + ) + return len(run_names) + + +def command_for( + job: EvaluationJob, gpu: int, num_workers: int, + drop_depth: bool = False, drop_k: bool = False, + phase4_diagnostics: bool = False, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/evaluate_phase3.py", + "--config", str(job.config), + "--root", DATA_ROOT, + "--manifest", str(VAL_MANIFEST), + "--checkpoint", str(job.checkpoint), + "--output-dir", str(job.output), + "--gpu", "0", + "--num-workers", str(num_workers), + "--bootstrap-samples", "10000", + "--skip-visualizations", + ] + if drop_depth: + command.append("--drop-depth") + if drop_k: + command.append("--drop-k") + if phase4_diagnostics: + command.append("--phase4-diagnostics") + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def completed_evaluation(path: Path, job: EvaluationJob) -> bool: + report_path = path / "evaluation.json" + if not report_path.is_file(): + return False + try: + report = json.loads(report_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return False + return ( + report.get("status") == "evaluated" + and report.get("official_test_used") is False + and Path(report.get("checkpoint", {}).get("path", "")).resolve() == job.checkpoint.resolve() + and report.get("clips") == 1495 + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + parser.add_argument("--run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--output-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--gpus", default="0,1,2,3,5") + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument("--roles") + parser.add_argument("--checkpoint-spec", type=Path) + parser.add_argument("--drop-depth", action="store_true") + parser.add_argument("--drop-k", action="store_true") + parser.add_argument("--phase4-diagnostics", action="store_true") + parser.add_argument("--state-filename", default="validation_state.json") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + if VAL_MANIFEST.name != "official_val.jsonl": + parser.error("full validation launcher is hard-gated to official_val.jsonl") + if args.num_workers < 0: + parser.error("--num-workers must be non-negative") + try: + state_path = validation_state_path(args.output_root, args.state_filename) + except ValueError as error: + parser.error(str(error)) + + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + known_gpus = gpu_uuid_map() + unknown = sorted(set(gpus) - set(known_gpus)) + if unknown: + parser.error(f"unknown GPU indices: {unknown}") + + try: + checkpoint_files = load_checkpoint_files(args.checkpoint_spec) + except (OSError, json.JSONDecodeError, ValueError) as error: + parser.error(str(error)) + known_roles = tuple(checkpoint_files) + roles = ( + known_roles if args.roles is None + else tuple(value.strip() for value in args.roles.split(",") if value.strip()) + ) + unknown_roles = sorted(set(roles) - set(known_roles)) + if not roles or unknown_roles: + parser.error(f"invalid --roles; selected={roles}, unknown={unknown_roles}") + jobs = build_jobs( + args.matrix_csv, args.run_root, args.output_root, roles, checkpoint_files, + ) + try: + run_count = validate_job_grid(jobs, roles) + except ValueError as error: + parser.error(str(error)) + missing_configs = sorted({str(job.config) for job in jobs if not job.config.is_file()}) + missing_checkpoints = sorted({str(job.checkpoint) for job in jobs if not job.checkpoint.is_file()}) + if missing_configs or missing_checkpoints: + parser.error(json.dumps({ + "missing_configs": missing_configs, + "missing_checkpoints": missing_checkpoints, + }, indent=2)) + if args.dry_run: + print(json.dumps({ + "runs": run_count, "jobs": len(jobs), "gpus": gpus, "roles": roles, + "official_test_used": False, + "first_command": shlex.join(command_for( + jobs[0], gpus[0], args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + )[0]), + "last_command": shlex.join(command_for( + jobs[-1], gpus[-1], args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + )[0]), + "drop_depth": args.drop_depth, "drop_k": args.drop_k, + "phase4_diagnostics": args.phase4_diagnostics, + "state_file": str(state_path), + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + work: queue.Queue[EvaluationJob] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "manifest": str(VAL_MANIFEST), + "roles": roles, "official_test_used": False, "jobs": {}, + "checkpoint_spec": str(args.checkpoint_spec) if args.checkpoint_spec else None, + "drop_depth": args.drop_depth, "drop_k": args.drop_k, + "phase4_diagnostics": args.phase4_diagnostics, + "state_file": str(state_path), + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for job in jobs: + if completed_evaluation(job.output, job): + state["jobs"][job.name] = { + "status": "skipped_completed", "output": str(job.output), + "checkpoint": str(job.checkpoint), "role": job.role, + } + continue + if job.output.exists() and any(job.output.iterdir()): + state["jobs"][job.name] = { + "status": "blocked_existing_incomplete", "output": str(job.output), + "checkpoint": str(job.checkpoint), "role": job.role, + } + stop_launching.set() + continue + work.put(job) + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + job = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for( + job, gpu, args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + ) + log_path = log_root / f"{job.name}.log" + with state_lock: + state["jobs"][job.name] = { + "status": "running", "run": job.run_name, "role": job.role, + "config": str(job.config), "checkpoint": str(job.checkpoint), + "gpu": gpu, "gpu_uuid": gpu_uuid, "started_utc": utc_now(), + "output": str(job.output), "log": str(log_path), + "command": shlex.join(command), + } + persist() + job.output.mkdir(parents=True, exist_ok=False) + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][job.name]["pid"] = process.pid + persist() + return_code = process.wait() + valid_output = completed_evaluation(job.output, job) + with state_lock: + state["jobs"][job.name].update({ + "status": "completed" if return_code == 0 and valid_output else "failed", + "return_code": return_code, "output_validated": valid_output, + "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0 or not valid_output: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,), name=f"gpu-{gpu}") for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [ + name for name, record in state["jobs"].items() + if record["status"] in {"failed", "blocked_existing_incomplete"} + ] + state["status"] = "failed" if failed else "completed" + state["finished_utc"] = utc_now() + state["failed_jobs"] = failed + state["remaining_queue"] = work.qsize() + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase3_matrix.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase3_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..9e84d3da6831ce5604a00315099bb13709db6c57 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase3_matrix.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Run a pre-registered Phase 3 config queue on explicitly allowed idle GPUs.""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import queue +import shlex +import subprocess +import threading +import time +from datetime import datetime, timezone +from pathlib import Path + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +TRAIN_MANIFEST = "artifacts/phase2/data_audit/manifests/official_train.jsonl" +VAL_MANIFEST = "artifacts/phase2/data_audit/manifests/official_val.jsonl" +VAL_SUBSET = "artifacts/phase3/validation_subset/validation_subset_256.json" + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + output = {} + for line in result.stdout.splitlines(): + index, uuid = (part.strip() for part in line.split(",", 1)) + output[int(index)] = uuid + return output + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if not line.strip(): + continue + uuid, pid = (part.strip() for part in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +def command_for( + config: Path, + output_dir: Path, + gpu: int, + resume: Path | None = None, + validation_subset: Path | str = VAL_SUBSET, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/train_experiment.py", + "--config", str(config), + "--root", DATA_ROOT, + "--manifest", TRAIN_MANIFEST, + "--val-manifest", VAL_MANIFEST, + "--validation-subset-manifest", str(validation_subset), + "--output-dir", str(output_dir), + "--max-steps", "100000", + "--num-workers", "4", + "--checkpoint-interval", "25000", + "--validation-interval", "5000", + "--validation-batches", "256", + "--learning-rate", "5e-5", + "--min-learning-rate", "5e-6", + "--warmup-steps", "500", + "--early-stopping-patience", "0", + ] + if resume is not None: + command.extend(("--resume", str(resume))) + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + parser.add_argument("--output-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--gpus", default="0,1,2,3,5") + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--resume-root", type=Path) + parser.add_argument("--resume-step", type=int, default=75_000) + parser.add_argument( + "--validation-subset-manifest", type=Path, default=Path(VAL_SUBSET), + ) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + known_gpus = gpu_uuid_map() + unknown = sorted(set(gpus) - set(known_gpus)) + if unknown: + parser.error(f"unknown GPU indices: {unknown}") + + with args.matrix_csv.open(newline="", encoding="utf-8") as handle: + configs = [Path(row["config"]) for row in csv.DictReader(handle)] + missing = [str(path) for path in configs if not path.is_file()] + if missing: + parser.error(f"missing configs: {missing}") + jobs = [ + ( + config, + args.output_root / config.stem, + ( + args.resume_root / config.stem / f"step_{args.resume_step:07d}.pt" + if args.resume_root is not None else None + ), + ) + for config in configs + ] + missing_resume = [str(resume) for _, _, resume in jobs if resume and not resume.is_file()] + if missing_resume: + parser.error(f"missing resume checkpoints: {missing_resume}") + if args.dry_run: + print(json.dumps({ + "jobs": len(jobs), "gpus": gpus, + "commands": [ + shlex.join(command_for( + config, output, gpus[index % len(gpus)], resume, + args.validation_subset_manifest, + )[0]) + for index, (config, output, resume) in enumerate(jobs) + ], + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + state_path = args.output_root / "matrix_state.json" + work: queue.Queue[tuple[Path, Path, Path | None]] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "jobs": {}, + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for config, output, resume in jobs: + summary = output / "summary.json" + if summary.is_file() and json.loads(summary.read_text(encoding="utf-8")).get("status") == "completed": + state["jobs"][config.stem] = {"status": "skipped_completed", "output": str(output)} + continue + if output.exists() and any(output.iterdir()): + state["jobs"][config.stem] = { + "status": "blocked_existing_incomplete", "output": str(output), + } + stop_launching.set() + continue + work.put((config, output, resume)) + + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + config, output, resume = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for( + config, output, gpu, resume, args.validation_subset_manifest, + ) + log_path = log_root / f"{config.stem}.log" + with state_lock: + state["jobs"][config.stem] = { + "status": "running", "gpu": gpu, "gpu_uuid": gpu_uuid, + "started_utc": utc_now(), "output": str(output), + "log": str(log_path), "command": shlex.join(command), + "resume_checkpoint": str(resume) if resume is not None else None, + } + persist() + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][config.stem]["pid"] = process.pid + persist() + return_code = process.wait() + with state_lock: + state["jobs"][config.stem].update({ + "status": "completed" if return_code == 0 else "failed", + "return_code": return_code, "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,), name=f"gpu-{gpu}") for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [name for name, record in state["jobs"].items() if record["status"] in {"failed", "blocked_existing_incomplete"}] + state["status"] = "failed" if failed else "completed" + state["finished_utc"] = utc_now() + state["failed_jobs"] = failed + state["remaining_queue"] = work.qsize() + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase4_a3_matrix.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase4_a3_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..277b30257fd62aa997b6837b566ef7af2b34fe65 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase4_a3_matrix.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Run the preregistered Phase 4 A3 formal matrix on explicitly allowed GPUs.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import queue +import shlex +import subprocess +import threading +from datetime import datetime, timezone +from pathlib import Path + +import yaml + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +TRAIN_MANIFEST = "artifacts/phase2/data_audit/manifests/official_train.jsonl" +VAL_MANIFEST = "artifacts/phase2/data_audit/manifests/official_val.jsonl" +VAL_SUBSET = ( + "artifacts/phase3/validation_subset/resolution_640x368/" + "validation_subset_256.json" +) +EXPECTED_SEEDS = {20260716, 20260717, 20260718} +MODE_SLUGS = { + "oracle_rgb": "rgb", + "oracle_depth_k": "depth_k", + "oracle_rgb_depth_k": "rgb_depth_k", +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + return { + int(index.strip()): uuid.strip() + for line in result.stdout.splitlines() + for index, uuid in [line.split(",", 1)] + } + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + [ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid", + "--format=csv,noheader,nounits", + ], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if line.strip(): + uuid, pid = (value.strip() for value in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +def load_jobs( + matrix_csv: Path, + config_root: Path, + output_root: Path, +) -> list[dict[str, object]]: + with matrix_csv.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + observed = {(int(row["seed"]), row["mode"]) for row in rows} + expected = {(seed, mode) for seed in EXPECTED_SEEDS for mode in MODE_SLUGS} + if len(rows) != 9 or observed != expected: + raise ValueError("A3 formal matrix must contain exactly three modes x three seeds") + + jobs = [] + for row in rows: + seed = int(row["seed"]) + mode = row["mode"] + if row["stage"] != "formal" or int(row["max_steps"]) != 100_000: + raise ValueError("A3 matrix contains a non-formal or non-100k row") + if row["gt_location"] != "True" or row["official_test_used"] != "False": + raise ValueError("A3 formal matrix violates oracle/test-isolation contract") + config = config_root / Path(row["config"]).name + checkpoint = Path(row["initialization_checkpoint"]) + if not config.is_file() or not checkpoint.is_file(): + raise FileNotFoundError(f"missing A3 config/checkpoint: {config}, {checkpoint}") + if file_sha256(checkpoint) != row["initialization_checkpoint_sha256"]: + raise ValueError(f"initialization checkpoint hash mismatch for seed {seed}") + config_record = yaml.safe_load(config.read_text(encoding="utf-8")) + experiment = config_record.get("experiment", {}) + if ( + int(config_record["seed"]) != seed + or config_record["name"] != row["name"] + or experiment.get("oracle_crop_mode") != mode + or experiment.get("coarse_checkpoint_sha256") + != row["initialization_checkpoint_sha256"] + ): + raise ValueError(f"matrix/config mismatch for {config}") + jobs.append({ + "name": row["name"], + "seed": seed, + "mode": mode, + "config": config, + "checkpoint": checkpoint, + "output": output_root / row["name"], + }) + return jobs + + +def command_for( + job: dict[str, object], gpu: int, validation_subset: Path, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/train_experiment.py", + "--config", str(job["config"]), + "--root", DATA_ROOT, + "--manifest", TRAIN_MANIFEST, + "--val-manifest", VAL_MANIFEST, + "--validation-subset-manifest", str(validation_subset), + "--output-dir", str(job["output"]), + "--max-steps", "100000", + "--num-workers", "4", + "--checkpoint-interval", "25000", + "--validation-interval", "5000", + "--validation-batches", "256", + "--learning-rate", "5e-5", + "--min-learning-rate", "5e-6", + "--lr-schedule-steps", "100000", + "--warmup-steps", "500", + "--early-stopping-patience", "0", + "--init-checkpoint", str(job["checkpoint"]), + ] + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, required=True) + parser.add_argument( + "--config-root", type=Path, default=Path("configs/phase4/a3_oracle_crop"), + ) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--gpus", default="0,1,2,3,4,5") + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--validation-subset-manifest", type=Path, default=Path(VAL_SUBSET), + ) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + if not gpus or len(gpus) != len(set(gpus)): + parser.error("--gpus must contain unique GPU indices") + known_gpus = gpu_uuid_map() + if set(gpus) - set(known_gpus): + parser.error("--gpus contains an unknown GPU index") + if not args.validation_subset_manifest.is_file(): + parser.error("fixed validation subset is missing") + jobs = load_jobs(args.matrix_csv, args.config_root, args.output_root) + if args.dry_run: + print(json.dumps({ + "status": "dry_run", "jobs": len(jobs), "gpus": gpus, + "commands": [ + shlex.join(command_for(job, gpus[index % len(gpus)], args.validation_subset_manifest)[0]) + for index, job in enumerate(jobs) + ], + "official_test_used": False, + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + state_path = args.output_root / "matrix_state.json" + work: queue.Queue[dict[str, object]] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "official_test_used": False, "jobs": {}, + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for job in jobs: + output = job["output"] + summary = output / "summary.json" + if summary.is_file() and json.loads(summary.read_text(encoding="utf-8")).get("status") == "completed": + state["jobs"][job["name"]] = { + "status": "skipped_completed", "output": str(output), + } + elif output.exists() and any(output.iterdir()): + state["jobs"][job["name"]] = { + "status": "blocked_existing_incomplete", "output": str(output), + } + stop_launching.set() + else: + work.put(job) + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + job = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for(job, gpu, args.validation_subset_manifest) + log_path = log_root / f"{job['name']}.log" + with state_lock: + state["jobs"][job["name"]] = { + "status": "running", "gpu": gpu, "gpu_uuid": gpu_uuid, + "started_utc": utc_now(), "output": str(job["output"]), + "log": str(log_path), "command": shlex.join(command), + } + persist() + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][job["name"]]["pid"] = process.pid + persist() + return_code = process.wait() + with state_lock: + state["jobs"][job["name"]].update({ + "status": "completed" if return_code == 0 else "failed", + "return_code": return_code, "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,)) for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [ + name for name, record in state["jobs"].items() + if record["status"] in {"failed", "blocked_existing_incomplete"} + ] + state.update({ + "status": "failed" if failed else "completed", + "finished_utc": utc_now(), "failed_jobs": failed, + "remaining_queue": work.qsize(), + }) + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_adaptation_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_adaptation_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c94ba7f43f0ea64e794d451c852510a306db20e6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_adaptation_eval_queue.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Evaluate H2O adaptation checkpoints on frozen train-heldout groups.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_split") != "h2o_train_group_heldout_only" + ): + raise ValueError("adaptation evaluation queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("adaptation evaluation queue is empty") + for item in queue["evaluations"]: + if Path(item["cache_manifest"]).name != "train_group_heldout.jsonl": + raise ValueError("adaptation evaluation must use train_group_heldout.jsonl") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_train_group_heldout" + and report.get("evaluation_role") == "h2o_train_group_heldout" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("h2o_training_data_used") is True + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item.get("input_mode", "rgb_d_k"), + "--evaluation-role", "h2o_train_group_heldout", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty adaptation evaluation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_adaptation_forgetting_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_adaptation_forgetting_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa5b7a46bc6f95f83b75eb328abef01a86875a1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_adaptation_forgetting_queue.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Evaluate H2O-adapted checkpoints on frozen external held-out caches.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_use") is not False + or queue.get("evaluation_split") != "external_heldout_forgetting_diagnostic_only" + ): + raise ValueError("adaptation forgetting queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("adaptation forgetting queue is empty") + for item in queue["evaluations"]: + if "h2o" in str(item["cache_manifest"]).lower(): + raise ValueError("adaptation forgetting queue refuses H2O cache paths") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_adaptation_external_heldout" + and report.get("evaluation_role") == "adaptation_external_heldout" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("h2o_training_data_used") is True + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--evaluation-role", "adaptation_external_heldout", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "selection_use": False, "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty forgetting evaluation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_adaptation_train_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_adaptation_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff2769a01a27e87301e9a37028692b23f43a562 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_adaptation_train_queue.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 7 H2O adaptation stages on idle GPUs 0-3.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_train_queue import ( + atomic_json, + cache_report_ready, + idle_gpu, + sha256, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def stage_marker(item: dict[str, Any]) -> Path: + return Path(item["output_dir"]) / ".phase7_queue" / f"{item['id']}.json" + + +def completed_matches(item: dict[str, Any]) -> bool: + marker_path = stage_marker(item) + if not marker_path.is_file(): + return False + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and int(marker.get("completed_step", -1)) == int(item["stop_after_step"]) + and marker.get("config_sha256") == item["config_sha256"] + and marker.get("h2o_training_data_used") is True + and marker.get("h2o_official_validation_used") is False + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", item["config"], "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(item["stop_after_step"]), + ] + if item.get("resume_checkpoint") is not None: + command.extend(("--resume", item["resume_checkpoint"])) + elif item.get("resume_from_step") is not None: + resume = Path(item["output_dir"]) / f"step_{int(item['resume_from_step']):07d}_final.pt" + command.extend(("--resume", str(resume))) + elif not item.get("neutral_start", False): + command.extend(("--init-checkpoint", item["init_checkpoint"])) + return command + + +def validate_stage_inputs(item: dict[str, Any]) -> None: + config = Path(item["config"]) + if not config.is_file() or sha256(config) != item["config_sha256"]: + raise RuntimeError(f"frozen config missing or SHA mismatch: {config}") + output = Path(item["output_dir"]) + resume_checkpoint = item.get("resume_checkpoint") + resume_step = item.get("resume_from_step") + if resume_checkpoint is not None: + resume = Path(resume_checkpoint) + if ( + not resume.is_file() + or sha256(resume) != item.get("resume_checkpoint_sha256") + ): + raise RuntimeError(f"explicit resume checkpoint is missing or has a SHA mismatch: {resume}") + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"explicit-resume adaptation output is not empty: {output}") + elif resume_step is None and item.get("neutral_start", False): + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new neutral-control output is not empty: {output}") + elif resume_step is None: + initialization = Path(item["init_checkpoint"]) + if ( + not initialization.is_file() + or sha256(initialization) != item["init_checkpoint_sha256"] + ): + raise RuntimeError(f"frozen initialization missing or SHA mismatch: {initialization}") + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new adaptation output is not empty: {output}") + else: + resume = output / f"step_{int(resume_step):07d}_final.pt" + if not resume.is_file(): + raise RuntimeError(f"resume checkpoint is missing: {resume}") + + +def write_stage_marker(item: dict[str, Any], gpu: int) -> dict[str, Any]: + output = Path(item["output_dir"]) + summary = json.loads((output / "summary.json").read_text(encoding="utf-8")) + step = int(item["stop_after_step"]) + checkpoint = output / f"step_{step:07d}_final.pt" + if ( + int(summary.get("completed_step", -1)) != step + or summary.get("h2o_training_data_used") is not True + or summary.get("official_test_used") is not False + or not checkpoint.is_file() + ): + raise RuntimeError(f"adaptation summary failed stage contract: {item['id']}") + marker = { + "status": "complete", "id": item["id"], "completed_utc": utc_now(), + "completed_step": step, "physical_gpu_id": gpu, + "config": str(Path(item["config"]).resolve()), + "config_sha256": item["config_sha256"], + "checkpoint": str(checkpoint.resolve()), "checkpoint_sha256": sha256(checkpoint), + "wall_seconds": summary.get("wall_seconds"), + "gpu_hours": summary.get("gpu_hours"), + "frames_per_second": summary.get("frames_per_second"), + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + marker_path = stage_marker(item) + marker_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(marker_path, marker) + return marker + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + ): + parser.error("adaptation queue exposure flags are not explicit and valid") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_caches", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": [0, 1, 2, 3], + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + while not all(cache_report_ready(item) for item in queue["required_caches"]): + state["status"] = "waiting_for_caches" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + for index, item in enumerate(queue["stages"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + validate_stage_inputs(item) + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + command = training_command(item, gpu) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0: + marker = write_stage_marker(item, gpu) + state["completed_ids"].append(item["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + break + state["status"] = "failed_non_resource" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["stages"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_external_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_external_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..a41353ff9900a376e42d6fd5e72a03b55d48a27c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_external_eval_queue.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Wait for idle GPU0-3 slots and run a frozen Phase 7 evaluation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def completed_matches(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("official_test_used") is False + and report.get("h2o_training_data_used") is False + and ( + item.get("cache_manifest_sha256") is None + or report.get("cache_manifest", {}).get("sha256") == item["cache_manifest_sha256"] + ) + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], + "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 1000)), + ] + if item.get("cache_manifest_sha256") is not None: + command.extend(( + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + )) + return command + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + # A second observation narrows the race with non-FoundationHand users. + time.sleep(1.0) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if queue.get("official_test_used") is not False: + parser.error("queue must explicitly set official_test_used=false") + items = queue["evaluations"] + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + state["status"] = "running" + for index, item in enumerate(items): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["updated_utc"] = utc_now() + state["waiting_for_idle_gpu"] = True + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + state["waiting_for_idle_gpu"] = False + output_dir = Path(item["output_dir"]) + if output_dir.exists() and any(output_dir.iterdir()): + state["status"] = "failed_existing_output" + state["failure"] = { + "id": item["id"], "reason": f"nonempty output: {output_dir}", + } + atomic_json(args.state, state) + raise SystemExit(1) + command = evaluator_command(item, gpu) + attempt = { + "id": item["id"], "gpu": gpu, "start_utc": utc_now(), + "command": command, + } + state["attempts"].append(attempt) + atomic_json(args.state, state) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + attempt["log"] = str(log_path.resolve()) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + break + tail = log_path.read_text(encoding="utf-8", errors="replace")[-4096:] + if ( + "is not idle" in tail + and (not output_dir.exists() or not any(output_dir.iterdir())) + ): + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_non_resource" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(items) + state["updated_utc"] = utc_now() + state["waiting_for_idle_gpu"] = False + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_external_train_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_external_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..7d97cea3b8039b51ace8f9e31f76e944c5001e83 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_external_train_queue.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 7 external scale stages when caches and GPUs are ready.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def cache_report_ready(item: dict[str, Any]) -> bool: + report_path = Path(item["report"]) + manifest_path = Path(item["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + clip_count = report.get("clips", report.get("cached_clips")) + recorded_manifest = report.get("cache_manifest", {}) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(clip_count or -1) == int(item["expected_clips"]) + and Path(recorded_manifest.get("path", "")).resolve() == manifest_path.resolve() + and recorded_manifest.get("sha256") == sha256(manifest_path) + ) + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1.0) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def stage_marker(item: dict[str, Any]) -> Path: + return Path(item["output_dir"]) / ".phase7_queue" / f"{item['id']}.json" + + +def completed_matches(item: dict[str, Any]) -> bool: + marker_path = stage_marker(item) + if not marker_path.is_file(): + return False + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and int(marker.get("completed_step", -1)) == int(item["stop_after_step"]) + and marker.get("config_sha256") == item["config_sha256"] + and marker.get("h2o_training_data_used") is False + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", item["config"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(item["stop_after_step"]), + ] + resume_step = item.get("resume_from_step") + if resume_step is not None: + resume = Path(item["output_dir"]) / f"step_{int(resume_step):07d}_final.pt" + command.extend(("--resume", str(resume))) + if item.get("allow_schedule_tail") is True: + command.append("--allow-schedule-tail") + return command + + +def validate_stage_inputs(item: dict[str, Any]) -> None: + config = Path(item["config"]) + if not config.is_file() or sha256(config) != item["config_sha256"]: + raise RuntimeError(f"frozen config missing or SHA mismatch: {config}") + resume_step = item.get("resume_from_step") + output = Path(item["output_dir"]) + if resume_step is None: + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new-stage output is not empty: {output}") + else: + resume = output / f"step_{int(resume_step):07d}_final.pt" + if not resume.is_file(): + raise RuntimeError(f"resume checkpoint is missing: {resume}") + expected_resume_sha = item.get("resume_checkpoint_sha256") + if expected_resume_sha is not None and sha256(resume) != expected_resume_sha: + raise RuntimeError(f"resume checkpoint SHA256 mismatch: {resume}") + + +def write_stage_marker(item: dict[str, Any], gpu: int) -> dict[str, Any]: + output = Path(item["output_dir"]) + summary = json.loads((output / "summary.json").read_text(encoding="utf-8")) + step = int(item["stop_after_step"]) + checkpoint = output / f"step_{step:07d}_final.pt" + if ( + int(summary.get("completed_step", -1)) != step + or summary.get("h2o_training_data_used") is not False + or summary.get("official_test_used") is not False + or not checkpoint.is_file() + ): + raise RuntimeError(f"training summary did not satisfy stage contract: {item['id']}") + marker = { + "status": "complete", "id": item["id"], "completed_utc": utc_now(), + "completed_step": step, "physical_gpu_id": gpu, + "config": str(Path(item["config"]).resolve()), + "config_sha256": item["config_sha256"], + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": sha256(checkpoint), + "wall_seconds": summary.get("wall_seconds"), + "gpu_hours": summary.get("gpu_hours"), + "frames_per_second": summary.get("frames_per_second"), + "schedule_tail_enabled": summary.get("schedule_tail_enabled", False), + "schedule_tail_learning_rate": summary.get("schedule_tail_learning_rate"), + "h2o_training_data_used": False, "official_test_used": False, + } + marker_path = stage_marker(item) + marker_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(marker_path, marker) + return marker + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if queue.get("official_test_used") is not False: + parser.error("queue must explicitly set official_test_used=false") + if queue.get("h2o_training_data_used") is not False: + parser.error("queue must explicitly set h2o_training_data_used=false") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_caches", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), + "h2o_training_data_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + + while not all(cache_report_ready(item) for item in queue["required_caches"]): + state["status"] = "waiting_for_caches" + state["updated_utc"] = utc_now() + state["ready_caches"] = [ + item["id"] for item in queue["required_caches"] if cache_report_ready(item) + ] + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + for index, item in enumerate(queue["stages"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + try: + validate_stage_inputs(item) + except RuntimeError as error: + state["status"] = "failed_input_contract" + state["failure"] = {"id": item["id"], "reason": str(error)} + atomic_json(args.state, state) + raise SystemExit(str(error)) + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + command = training_command(item, gpu) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0: + marker = write_stage_marker(item, gpu) + state["completed_ids"].append(item["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + break + tail = log_path.read_text(encoding="utf-8", errors="replace")[-4096:] + output = Path(item["output_dir"]) + if "is not idle" in tail and (not output.exists() or not any(output.iterdir())): + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_non_resource_or_partial_output" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + + state["status"] = "complete" + state["current_index"] = len(queue["stages"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_h2o_adapted_validation_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_h2o_adapted_validation_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a3d4e4f667ade06aec102d29481ffdde764ac9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_h2o_adapted_validation_queue.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Run a frozen three-mode H2O validation package for an adapted checkpoint.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_split") != "h2o_train_group_heldout_only" + or queue.get("h2o_official_validation_used_for_selection") is not False + ): + raise ValueError("adapted validation exposure flags are invalid") + items = queue.get("evaluations", []) + if {item.get("input_mode") for item in items} != set(INPUT_MODES) or len(items) != 3: + raise ValueError("adapted validation queue requires exactly three unique input modes") + if len({item.get("checkpoint_sha256") for item in items}) != 1: + raise ValueError("adapted validation modes must use one frozen checkpoint") + if len({item.get("freeze_record") for item in items}) != 1: + raise ValueError("adapted validation modes must use one freeze record") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_adapted_formal" + and report.get("evaluation_role") == "h2o_adapted_formal" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is True + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--freeze-record", item["freeze_record"], "--root", item["root"], + "--manifest", item["manifest"], "--input-mode", item["input_mode"], + "--evaluation-role", "h2o_adapted_formal", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty adapted validation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_h2o_zero_shot_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_h2o_zero_shot_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9916057aef5704cf28f9a5084d7b3e2bc821cdc0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_h2o_zero_shot_queue.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Run the frozen three-mode strict H2O zero-shot evaluation package.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_training_data_used") is not False + or queue.get("h2o_official_validation_used_for_external_selection") is not False + ): + raise ValueError("strict zero-shot exposure flags are invalid") + items = queue.get("evaluations", []) + if {item.get("input_mode") for item in items} != set(INPUT_MODES) or len(items) != 3: + raise ValueError("strict zero-shot queue requires exactly three unique input modes") + if len({item.get("checkpoint_sha256") for item in items}) != 1: + raise ValueError("strict zero-shot modes must use one frozen checkpoint") + if len({item.get("manifest") for item in items}) != 1: + raise ValueError("strict zero-shot modes must use one frozen validation manifest") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_strict_h2o_zero_shot" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is False + and report.get("h2o_official_validation_used_for_external_selection") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--freeze-record", item["freeze_record"], "--root", item["root"], + "--manifest", item["manifest"], "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "official_test_used": False, "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty zero-shot output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_heldout_cache_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_heldout_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..2163297840a13304a2b53d0503dc025a689c1d1e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase7_heldout_cache_queue.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Launch formal external held-out caches as their train caches complete.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import shlex +import subprocess +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def dependency_ready(item: dict[str, Any]) -> bool: + report_path = Path(item["dependency"]) + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + count = report.get("clips", report.get("cached_clips", 0)) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(count) >= 10000 + ) + + +def output_complete(item: dict[str, Any]) -> bool: + output = Path(item["output_dir"]) + report_path = output / "cache_report.json" + manifest_path = output / "cache_manifest.jsonl" + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + cache_manifest = report.get("cache_manifest", {}) + expected_recordings = item.get("physical_recordings") + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(report.get("clips", report.get("cached_clips", 0))) == 2048 + and report.get("source_manifest", {}).get("sha256") == item["source_manifest_sha256"] + and Path(cache_manifest.get("path", "")).resolve() == manifest_path.resolve() + and cache_manifest.get("sha256") == sha256(manifest_path) + and ( + expected_recordings is None + or int(report.get("recordings", -1)) == int(expected_recordings) + ) + ) + + +def command_tokens(command: str) -> tuple[list[str], dict[str, str]]: + tokens = shlex.split(command) + environment = dict(os.environ) + while tokens and "=" in tokens[0] and not tokens[0].startswith("-"): + key, value = tokens.pop(0).split("=", 1) + if key != "PYTHONPATH": + raise ValueError(f"unexpected command environment assignment: {key}") + environment[key] = str((Path.cwd() / value).resolve()) + if not tokens: + raise ValueError("cache command is empty") + return tokens, environment + + +def process_alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except (ProcessLookupError, PermissionError): + return False + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False or plan.get("h2o_used") is not False: + parser.error("held-out cache plan must be external-only and non-test") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_train_caches", "plan": str(args.plan.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), "completed_ids": [], + "active": {}, "attempts": [], "official_test_used": False, "h2o_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan") != str(args.plan.resolve()): + parser.error("existing state belongs to a different plan") + state = previous + pending = {item["dataset"]: item for item in plan["sources"]} + processes: dict[str, subprocess.Popen[str]] = {} + while len(state["completed_ids"]) < len(pending): + for dataset, item in pending.items(): + if dataset in state["completed_ids"]: + continue + if output_complete(item): + state["completed_ids"].append(dataset) + state["active"].pop(dataset, None) + atomic_json(args.state, state) + continue + active = state["active"].get(dataset) + if active and process_alive(int(active["pid"])): + continue + if not dependency_ready(item): + continue + output = Path(item["output_dir"]) + command_key = "resume_command" if output.exists() else "start_command" + command, environment = command_tokens(item[command_key]) + log_path = args.state.parent / f"heldout_cache_{dataset.lower()}.log" + attempt = { + "dataset": dataset, "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), "mode": command_key, + } + state["attempts"].append(attempt) + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, + ) + processes[dataset] = process + state["active"][dataset] = {"pid": process.pid, "log": str(log_path.resolve())} + state["status"] = "running" + atomic_json(args.state, state) + finished = [] + for dataset, active in list(state["active"].items()): + process = processes.get(dataset) + if process is not None: + returncode = process.poll() + if returncode is None: + continue + state["active"][dataset]["returncode"] = returncode + processes.pop(dataset) + elif process_alive(int(active["pid"])): + continue + # A completed report is validated on the next loop. A dead process + # without one is retained as a failure rather than silently retried. + item = pending[dataset] + if output_complete(item): + finished.append(dataset) + else: + state["status"] = "failed_incomplete_output" + state["failure"] = {"dataset": dataset, "log": active["log"]} + atomic_json(args.state, state) + raise SystemExit(1) + for dataset in finished: + if dataset not in state["completed_ids"]: + state["completed_ids"].append(dataset) + state["active"].pop(dataset, None) + state["updated_utc"] = utc_now() + state["ready_dependencies"] = [ + dataset for dataset, item in pending.items() if dependency_ready(item) + ] + atomic_json(args.state, state) + if len(state["completed_ids"]) < len(pending): + time.sleep(args.poll_seconds) + state["status"] = "complete" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase8_egodexter_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase8_egodexter_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9d96eeb623ad017721160ed288970aa05e10ae3a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase8_egodexter_queue.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Run a frozen EgoDexter queue on atomically claimed physical GPU0-3.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("egodexter_used_for_training_or_selection") is not False + or not queue.get("evaluations") + ): + raise ValueError("EgoDexter queue boundary flags are invalid") + expected = { + (mode, input_mode) + for mode in ("offline", "causal") + for input_mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + actual = { + (item.get("inference_mode"), item.get("input_mode")) + for item in queue["evaluations"] + } + if actual != expected or len(queue["evaluations"]) != len(expected): + raise ValueError("EgoDexter queue must contain the exact six-condition grid") + if {item.get("model_id") for item in queue["evaluations"]} != {queue.get("model_id")}: + raise ValueError("EgoDexter queue mixes model IDs") + + +def completed_matches(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_frozen_egodexter_zero_shot" + and report.get("model_id") == item["model_id"] + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("inference_mode") == item["inference_mode"] + and report.get("egodexter_used_for_training_or_selection") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_egodexter_zero_shot", + "--model-id", item["model_id"], + "--freeze-record", item["freeze_record"], + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--root", item["root"], "--input-mode", item["input_mode"], + "--inference-mode", item["inference_mode"], + "--window", str(item.get("window", 8)), + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists(): + raise RuntimeError(f"EgoDexter output already exists: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase8_h2o_control_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase8_h2o_control_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..6106550a604d35b15aecabb34d29f911e7f8d1c9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase8_h2o_control_eval_queue.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Run hash-bound H2O train-heldout controls without changing their provenance.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("selection_split") != "h2o_train_group_heldout_only" + ): + raise ValueError("H2O control queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("H2O control queue is empty") + for item in queue["evaluations"]: + if Path(item["cache_manifest"]).name != "train_group_heldout.jsonl": + raise ValueError("H2O control must use train_group_heldout.jsonl") + if not isinstance(item.get("expected_h2o_training_data_used"), bool): + raise ValueError("control item must freeze expected H2O provenance") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_train_group_heldout_control" + and report.get("evaluation_role") == "h2o_train_group_heldout_control" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is item["expected_h2o_training_data_used"] + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--evaluation-role", "h2o_train_group_heldout_control", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty H2O control output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode != 0 or not completed_matches(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(item["id"]) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_data_finalize_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_data_finalize_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..8d1a4cd4bc05e33467e6e5aa5cf12294d155a053 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_data_finalize_queue.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Wait for Phase 9 base caches, then freeze subsets and left sidecars.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def base_cache_ready(item: dict[str, Any]) -> bool: + manifest = Path(item["manifest"]) + report_path = Path(item["report"]) + if not manifest.is_file() or not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(manifest) + ): + return False + if item["dataset"] == "HOT3D": + return int(report.get("clips", -1)) == int(item["expected_clips"]) + return ( + report.get("accept_all_valid") is True + and report.get("all_eligible_processed") is True + and int(report.get("cached_valid_clips", 0)) > 0 + ) + + +def artifact_complete(item: dict[str, Any]) -> bool: + report_path = Path(item["report"]) + manifest = Path(item["manifest"]) + if not report_path.is_file() or not manifest.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + key = "augmented_cache_manifest" if item["kind"] == "left_sidecar" else "cache_manifest" + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get(key, {}).get("sha256") == sha256(manifest) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("finalize plan must explicitly exclude official test") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_data_finalize_state_v1", + "status": "waiting_for_base_caches", + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "started_utc": utc_now(), + "updated_utc": utc_now(), + "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != sha256(args.plan): + parser.error("existing state is bound to a different plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + base_caches = {item["dataset"]: item for item in plan["base_caches"]} + for item in plan["artifacts"]: + if artifact_complete(item): + continue + prerequisite = base_caches[item["requires_base_cache"]] + while not base_cache_ready(prerequisite): + state["status"] = "waiting_for_base_cache" + state["current_artifact"] = item["id"] + state["waiting_for_dataset"] = item["requires_base_cache"] + state["ready_base_caches"] = [ + dataset for dataset, base in base_caches.items() + if base_cache_ready(base) + ] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = [str(value) for value in item["command"]] + if item["kind"] == "left_sidecar": + base_manifest = Path(item["base_cache_manifest"]) + command = [ + value.replace("{BASE_CACHE_SHA256}", sha256(base_manifest)) + for value in command + ] + if (Path(item["output_dir"]) / "sidecars").is_dir(): + command.append("--resume") + log_path = Path(item["log"]) + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "id": item["id"], "start_utc": utc_now(), + "command": command, "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_artifact"] = item["id"] + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode or not artifact_complete(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "returncode": result.returncode} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["artifacts"] = [{ + "id": item["id"], "manifest": item["manifest"], + "manifest_sha256": sha256(item["manifest"]), + "report": item["report"], "report_sha256": sha256(item["report"]), + } for item in plan["artifacts"]] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_distributed_resolution_cache_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_distributed_resolution_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9e349530aae1d53571708b4637ace42ed029b9e5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_distributed_resolution_cache_queue.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Enforce distributed cache ownership before entering the existing queue.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import sys + +from scripts.phase9_distributed_assignment import detect_machine, load_assignment + + +CACHE_OWNERS = { + "h2o": "taku3", + "hot3d": "server_new", + "hoi4d": "taku3", + "arctic": "taku3", +} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--assignment-sha256", required=True) + parser.add_argument("--worker", choices=tuple(CACHE_OWNERS), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + assignment = load_assignment({"distributed_assignment": { + "path": str(args.assignment.resolve()), + "sha256": args.assignment_sha256, + }}) + machine = detect_machine(assignment, None) + if CACHE_OWNERS[args.worker] != machine: + parser.error(f"cache worker {args.worker} is owned by {CACHE_OWNERS[args.worker]}") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + matches = [item for item in plan["workers"] if item["id"] == args.worker] + if ( + len(matches) != 1 + or Path(matches[0]["state"]).resolve() != args.state.resolve() + or plan.get("official_test_used") is not False + ): + parser.error("distributed cache worker plan/state differs") + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_cache_queue", + "--plan", str(args.plan.resolve()), "--worker", args.worker, + "--state", str(args.state.resolve()), + "--poll-seconds", str(args.poll_seconds), + ] + os.execv(sys.executable, command) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_expanded_coverage_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_expanded_coverage_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c69ac4d00155e8221d06fc56dc05c3fd3890b3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_expanded_coverage_queue.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Run frozen source-coverage audits after Phase 9 data finalization.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import readiness_complete + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def audit_complete(item: dict[str, Any]) -> bool: + output = Path(item["output"]) + if not output.is_file(): + return False + report = json.loads(output.read_text(encoding="utf-8")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("cache_manifest", {}).get("sha256") == sha256(item["cache_manifest"]) + and report.get("source_manifest", {}).get("sha256") == sha256(item["source_manifest"]) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("coverage plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_expanded_coverage_state_v1", + "status": "waiting_for_data", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "updated_utc": utc_now(), "completed_ids": [], "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing coverage state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not readiness_complete(plan): + state["status"] = "waiting_for_data" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + for item in plan["audits"]: + if audit_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + continue + output = Path(item["output"]) + if output.exists(): + raise RuntimeError(f"incomplete coverage output already exists: {output}") + command = [ + sys.executable, "-m", "scripts.audit_phase9_source_coverage", + "--dataset", item["dataset"], + "--source-manifest", item["source_manifest"], + "--cache-manifest", item["cache_manifest"], + "--output", item["output"], + ] + log_path = args.state.parent / f"expanded_coverage_{item['dataset'].lower()}.log" + attempt = { + "id": item["id"], "start_utc": utc_now(), + "command": command, "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not audit_complete(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_external_milestone_eval.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_external_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..6b01ab8a3b01110cdfecc246e0022914527b06f1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_external_milestone_eval.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Evaluate Phase 9 unified milestone checkpoints on native external held-outs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3, 4, 5) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def stable_checkpoint_sha256( + path: str | Path, + *, + stable_seconds: float = 2.0, + poll_seconds: float = 0.25, + timeout_seconds: float = 300.0, +) -> str: + """Hash a checkpoint only after a non-atomic torch.save has quiesced.""" + checkpoint = Path(path) + started = time.monotonic() + previous = (checkpoint.stat().st_size, checkpoint.stat().st_mtime_ns) + stable_since = time.monotonic() + while True: + if time.monotonic() - started > timeout_seconds: + raise TimeoutError(f"checkpoint did not stabilize: {checkpoint}") + time.sleep(poll_seconds) + before = checkpoint.stat() + signature = (before.st_size, before.st_mtime_ns) + if signature != previous: + previous = signature + stable_since = time.monotonic() + continue + if time.monotonic() - stable_since < stable_seconds: + continue + digest = sha256(checkpoint) + after = checkpoint.stat() + if (after.st_size, after.st_mtime_ns) == signature: + return digest + previous = (after.st_size, after.st_mtime_ns) + stable_since = time.monotonic() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def checkpoint_path(condition: dict[str, Any], checkpoint: dict[str, Any]) -> Path | None: + run = Path(condition["run_dir"]) + if checkpoint["kind"] == "final": + path = run / f"step_{int(checkpoint['step']):07d}_final.pt" + return path if path.is_file() else None + matches = sorted(run.glob(f"milestone_{checkpoint['milestone_id']}_step_*.pt")) + if len(matches) > 1: + raise RuntimeError(f"multiple checkpoint files for milestone {checkpoint['milestone_id']}") + return matches[0] if matches else None + + +def evaluation_complete( + output_dir: Path, checkpoint_hash: str, manifest_hash: str, input_mode: str, +) -> bool: + path = output_dir / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_phase9_external_heldout" + and report.get("evaluation_role") == "phase9_external_heldout" + and report.get("checkpoint", {}).get("sha256") == checkpoint_hash + and report.get("cache_manifest", {}).get("sha256") == manifest_hash + and report.get("input_mode") == input_mode + and report.get("h2o_training_data_used") is True + and report.get("official_test_used") is False + ) + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def evaluator_command( + condition: dict[str, Any], checkpoint: Path, checkpoint_hash: str, + source: dict[str, Any], gpu: int, output: Path, +) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", condition["config"], + "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", source["cache_manifest"], + "--expected-cache-manifest-sha256", source["cache_manifest_sha256"], + "--input-mode", source["input_mode"], + "--output-dir", str(output), + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(source.get("bootstrap_resamples", 2000)), + "--evaluation-role", "phase9_external_heldout", + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--condition", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + registry = json.loads(args.registry.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + parser.error("registry must explicitly exclude official test") + conditions = {item["condition"]: item for item in registry["conditions"]} + if args.condition not in conditions: + parser.error("unknown condition") + condition = conditions[args.condition] + config = Path(condition["config"]) + if not config.is_file() or sha256(config) != condition["config_sha256"]: + parser.error("frozen config is missing or changed") + for source in registry["sources"]: + manifest = Path(source["cache_manifest"]) + if not manifest.is_file() or sha256(manifest) != source["cache_manifest_sha256"]: + parser.error(f"held-out manifest is missing or changed: {source['id']}") + registry_hash = sha256(args.registry) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_external_milestone_eval_state_v1", + "status": "waiting_for_checkpoint", "condition": args.condition, + "registry": str(args.registry.resolve()), "registry_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("registry_sha256") != registry_hash: + parser.error("existing state is bound to another registry version") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for checkpoint_spec in condition["checkpoints"]: + while True: + checkpoint = checkpoint_path(condition, checkpoint_spec) + if checkpoint is not None: + break + state["status"] = "waiting_for_checkpoint" + state["waiting_for"] = checkpoint_spec["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for source in registry["sources"]: + evaluation_id = f"{args.condition}_{checkpoint_spec['id']}_{source['id']}" + output = Path(registry["evaluation_root"]) / args.condition / checkpoint_spec["id"] / source["id"] + if evaluation_complete( + output, checkpoint_hash, source["cache_manifest_sha256"], source["input_mode"], + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + continue + while True: + gpu = idle_gpu() + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + if output.exists() and any(output.iterdir()): + release_physical_gpu_claim(gpu) + state["status"] = "failed_existing_output" + state["failure"] = {"id": evaluation_id, "output": str(output)} + atomic_json(args.state, state) + raise SystemExit(1) + command = evaluator_command( + condition, checkpoint, checkpoint_hash, source, gpu, output, + ) + log_path = args.state.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not evaluation_complete( + output, checkpoint_hash, source["cache_manifest_sha256"], source["input_mode"], + ): + state["status"] = "failed" + state["failure"] = {"id": evaluation_id, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_final_deployment_controller.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_final_deployment_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..a64e86ece28d0bcd9b90218507b54ae5ab7ae529 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_final_deployment_controller.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +"""Wait for final selection, then supervise formal validation and deployment audits.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + if ( + plan.get("schema_version") != "phase9_final_deployment_controller_plan_v1" + or plan.get("job_count") != 11 or plan.get("worker_count") != 4 + or plan.get("allowed_physical_gpus") != [0, 1, 2, 3] + or plan.get("official_validation_checkpoint_count") != 1 + or plan.get("h2o_official_validation_used_for_selection") is not False + or plan.get("official_test_used") is not False + ): + raise ValueError("final deployment controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"final deployment binding differs: {path}") + + +def final_decision_ready(plan: dict[str, Any]) -> bool: + state_path = Path(plan["last2_finalizer_state"]) + if not state_path.is_file(): + return False + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["last2_finalizer_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and report_path.is_file() + and state.get("decision_report", {}).get("sha256") == sha256(report_path) + and report_path.resolve() == Path(plan["last2_final_decision"]).resolve() + ) + + +def worker_status(path: Path, plan_hash: str) -> str: + if not path.is_file(): + return "missing" + state = read_json(path) + if state.get("plan_sha256") != plan_hash: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def pid_matches(pid: int, worker: str, dynamic_plan: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_final_deployment_worker" in command + and f"--worker {worker}" in command + and str(dynamic_plan.resolve()) in command + ) + + +def launch_worker(dynamic_plan: Path, worker: dict[str, Any], log_path: Path) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_final_deployment_worker", + "--plan", str(dynamic_plan.resolve()), "--worker", worker["id"], + "--state", worker["state"], + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def run_command(command: list[str], state: dict[str, Any], state_path: Path, label: str) -> None: + state["status"] = label + state[f"{label}_command"] = command + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = f"failed_{label}" + state[f"{label}_returncode"] = result.returncode + atomic_json(state_path, state) + raise SystemExit(result.returncode) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["controller_state"]).resolve(): + parser.error("final deployment controller state differs") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_final_deployment_controller_state_v1", + "status": "waiting_for_final_selection", "started_utc": utc_now(), + "updated_utc": utc_now(), "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "workers": {}, + "h2o_official_validation_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing final deployment controller state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not final_decision_ready(plan): + state["status"] = "waiting_for_final_selection" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + freeze = Path(plan["freeze"]) + freeze_command = [ + sys.executable, "-m", "scripts.freeze_phase9_final_deployment", + "--selection-plan", plan["selection_plan"], + "--selection-state", plan["selection_state"], + "--stage8-plan", plan["stage8_plan"], + "--stage8-state", plan["stage8_state"], + "--last2-plan", plan["last2_finalizer_plan"], + "--last2-state", plan["last2_finalizer_state"], + "--validation-manifest", plan["validation_manifest"], + "--validation-manifest-sha256", plan["validation_manifest_sha256"], + "--training-manifest", plan["training_manifest"], + "--training-manifest-sha256", plan["training_manifest_sha256"], + "--output", str(freeze), "--state", plan["freeze_state"], + ] + run_command(freeze_command, state, args.state, "freezing_final_checkpoint") + freeze_state = read_json(plan["freeze_state"]) + if ( + freeze_state.get("status") != "complete" or not freeze.is_file() + or freeze_state.get("freeze_sha256") != sha256(freeze) + ): + state["status"] = "failed_freeze_binding" + atomic_json(args.state, state) + raise SystemExit(1) + + dynamic_plan = Path(plan["dynamic_plan"]) + dynamic_command = [ + sys.executable, "-m", "scripts.build_phase9_final_deployment_plan", + "--freeze", str(freeze), "--freeze-state", plan["freeze_state"], + "--output-root", plan["output_root"], + "--worker-state-root", plan["worker_state_root"], + "--causal-config", plan["causal_config"], + "--h2o-root", plan["h2o_root"], + "--output", str(dynamic_plan), "--state", plan["dynamic_plan_state"], + ] + run_command(dynamic_command, state, args.state, "building_deployment_plan") + dynamic_state = read_json(plan["dynamic_plan_state"]) + if ( + dynamic_state.get("status") != "complete" or not dynamic_plan.is_file() + or dynamic_state.get("plan_sha256") != sha256(dynamic_plan) + ): + state["status"] = "failed_dynamic_plan_binding" + atomic_json(args.state, state) + raise SystemExit(1) + dynamic_hash = sha256(dynamic_plan) + dynamic = read_json(dynamic_plan) + state["dynamic_plan_sha256"] = dynamic_hash + state.setdefault("workers", {}) + while True: + statuses = {} + for worker in dynamic["workers"]: + path = Path(worker["state"]) + status = worker_status(path, dynamic_hash) + statuses[worker["id"]] = status + if status == "complete" or status.startswith("failed"): + continue + previous_pid = int(state["workers"].get(worker["id"], {}).get("pid", -1)) + if not pid_matches(previous_pid, worker["id"], dynamic_plan): + pid = launch_worker( + dynamic_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(status.startswith("failed") for status in statuses.values()): + state["status"] = "failed_deployment_worker" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = "running_post_selection_audits" + state["h2o_official_validation_used"] = True + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + report = Path(plan["summary_report"]) + if not report.is_file(): + run_command([ + sys.executable, "-m", "scripts.summarize_phase9_final_deployment", + "--plan", str(dynamic_plan), "--output", str(report), + ], state, args.state, "summarizing_deployment") + summary = read_json(report) + if ( + summary.get("status") != "complete" + or summary.get("deployment_contract", {}).get("passed") is not True + or summary.get("h2o_official_validation_used_for_selection") is not False + or summary.get("official_test_used") is not False + ): + state["status"] = "failed_deployment_summary" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["summary_report"] = {"path": str(report.resolve()), "sha256": sha256(report)} + state["checkpoint"] = summary["checkpoint"] + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["h2o_official_validation_used"] = True + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_final_deployment_worker.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_final_deployment_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ad40a896ea1c75803d879094f935440c2aae9c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_final_deployment_worker.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Run one disjoint final deployment worker with resumable output validation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_artifact(record: dict[str, Any]) -> bool: + path = Path(record.get("path", "")) + return path.is_file() and record.get("sha256") == sha256(path) + + +def completed_matches(job: dict[str, Any]) -> bool: + kind = job["kind"] + path = ( + Path(job["output_dir"]) / "evaluation.json" + if kind == "formal_validation" else Path(job["output"]) + ) + if not path.is_file(): + return False + try: + report = read_json(path) + except (OSError, json.JSONDecodeError): + return False + common = ( + report.get("checkpoint", {}).get("sha256") == job["checkpoint_sha256"] + and report.get("config", {}).get("sha256") == job["config_sha256"] + and report.get("manifest", {}).get("sha256") == job["manifest_sha256"] + and report.get("official_test_used") is False + ) + if not common: + return False + report_step = report.get("checkpoint", {}).get( + "step", report.get("checkpoint_step") + ) + if int(report_step if report_step is not None else -1) != job["checkpoint_step"]: + return False + if kind == "formal_validation": + return ( + report.get("status") == "evaluated_phase9_unified_formal" + and report.get("evaluation_role") == "phase9_unified_formal" + and report.get("input_mode") == job["input_mode"] + and report.get("freeze_record", {}).get("sha256") + == job["freeze_record_sha256"] + and report.get("h2o_official_validation_used") is True + and report.get("h2o_official_validation_used_for_selection") is False + and report.get("h2o_training_data_used") is True + and all(validate_artifact(report[key]) for key in ( + "raw_predictions", "per_hand_rows", "take_metrics", + )) + ) + if kind == "variable_length": + results = report.get("forward_results", []) + return ( + report.get("status") == "completed" + and report.get("official_validation_used") is True + and [item.get("T") for item in results] == job["lengths"] + and all(item.get("all_finite") is True for item in results) + ) + if kind == "sequence": + bounded = ( + int(report.get("maximum_gpu_window_frames", 10**9)) <= job["window"] + and int(report.get("maximum_cpu_input_buffer_frames", 10**9)) + <= (job["window"] if job["mode"] == "causal" else 12) + ) + causal = report.get("invariance") + causal_ok = job["mode"] != "causal" or ( + isinstance(causal, dict) + and causal.get("future_perturbation_bitwise_zero") is True + and causal.get("prefix_passed") is True + ) + mode_ok = ( + report.get("causal") is (job["mode"] == "causal") + and report.get("offline_stride") + == (None if job["mode"] == "causal" else 4) + and report.get("stitching") + == (None if job["mode"] == "causal" else "center") + ) + return ( + report.get("status") == "passed" + and report.get("mode") == job["mode"] + and report.get("window") == job["window"] + and report.get("requested_frames") == job["frames"] + and report.get("output_frames") == job["frames"] + and report.get("frame_ids_strictly_increasing") is True + and report.get("finite") is True + and report.get("official_validation_used_for_selection") is False + and bounded and causal_ok and mode_ok + ) + if kind == "profile": + latency = report.get("latency", {}) + return ( + report.get("status") == "profiled" + and report.get("official_validation_used") is False + and report.get("input", {}).get("resolution_hw") == job["resolution_hw"] + and float(latency.get("p50_ms", 0)) > 0 + and float(latency.get("p95_ms", 0)) > 0 + and float(report.get("peak_allocated_vram_gib", 0)) > 0 + ) + return False + + +def command(job: dict[str, Any]) -> list[str]: + common = ["--config", job["config"], "--checkpoint", job["checkpoint"]] + if job["kind"] == "formal_validation": + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + *common, "--expected-checkpoint-sha256", job["checkpoint_sha256"], + "--freeze-record", job["freeze_record"], "--root", job["root"], + "--manifest", job["manifest"], "--input-mode", job["input_mode"], + "--evaluation-role", "phase9_unified_formal", + "--output-dir", job["output_dir"], "--physical-gpu-id", + str(job["physical_gpu_id"]), "--bootstrap-resamples", "2000", + ] + if job["kind"] == "variable_length": + return [ + sys.executable, "-m", "scripts.audit_phase6_variable_length", + *common, "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--gpu", str(job["physical_gpu_id"]), + "--repeats", "2", + ] + if job["kind"] == "sequence": + return [ + sys.executable, "-m", "scripts.audit_phase6_sequence_inference", + *common, "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--mode", job["mode"], + "--window", str(job["window"]), "--frames", str(job["frames"]), + "--gpu", str(job["physical_gpu_id"]), + ] + if job["kind"] == "profile": + return [ + sys.executable, "-m", "scripts.profile_phase5_model", + *common, "--expected-checkpoint-sha256", job["checkpoint_sha256"], + "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--gpu", str(job["physical_gpu_id"]), + "--warmup", "20", "--iterations", "100", + ] + raise ValueError(f"unknown final deployment job kind: {job['kind']}") + + +def output_target(job: dict[str, Any]) -> Path: + return Path(job.get("output", job.get("output_dir", ""))) + + +def archive_incomplete(job: dict[str, Any]) -> str | None: + target = output_target(job) + if not target.exists(): + return None + recovery = target.parent / "recovery" + recovery.mkdir(parents=True, exist_ok=True) + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + destination = recovery / f"{target.name}.{stamp}.incomplete" + suffix = 0 + while destination.exists(): + suffix += 1 + destination = recovery / f"{target.name}.{stamp}.{suffix}.incomplete" + shutil.move(str(target), str(destination)) + return str(destination.resolve()) + + +def validate_plan(plan: dict[str, Any], worker: dict[str, Any]) -> dict[str, dict[str, Any]]: + if ( + plan.get("status") != "frozen_ready_post_selection" + or plan.get("official_validation_checkpoint_count") != 1 + or plan.get("h2o_official_validation_used_for_selection") is not False + or plan.get("official_test_used") is not False + or worker.get("physical_gpu_id") not in {0, 1, 2, 3} + ): + raise ValueError("final deployment worker contract differs") + jobs = {job["id"]: job for job in plan["jobs"]} + if len(jobs) != 11 or any(identifier not in jobs for identifier in worker["job_ids"]): + raise ValueError("final deployment worker jobs differ") + if any(jobs[identifier]["physical_gpu_id"] != worker["physical_gpu_id"] for identifier in worker["job_ids"]): + raise ValueError("final deployment worker GPU assignment differs") + return jobs + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + worker = next((item for item in plan["workers"] if item["id"] == args.worker), None) + if worker is None: + parser.error("unknown final deployment worker") + try: + jobs = validate_plan(plan, worker) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("final deployment worker state differs") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_final_deployment_worker_state_v1", + "status": "running", "worker": args.worker, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing final deployment worker state differs") + if state.get("status") == "complete": + invalid = [ + identifier for identifier in worker["job_ids"] + if not completed_matches(jobs[identifier]) + ] + if invalid: + state["status"] = "failed_completed_output_binding" + state["failure"] = {"invalid_completed_ids": invalid} + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + print(json.dumps(state, indent=2)) + return + for identifier in worker["job_ids"]: + job = jobs[identifier] + target = output_target(job) + lock_path = Path(f"{target}.lock") + lock_path.parent.mkdir(parents=True, exist_ok=True) + with lock_path.open("a+", encoding="utf-8") as output_lock: + fcntl.flock(output_lock.fileno(), fcntl.LOCK_EX) + if completed_matches(job): + if identifier not in state["completed_ids"]: + state["completed_ids"].append(identifier) + atomic_json(args.state, state) + continue + archived = archive_incomplete(job) + attempt = { + "id": identifier, "kind": job["kind"], + "physical_gpu_id": job["physical_gpu_id"], + "start_utc": utc_now(), "command": command(job), + } + log_path = args.state.parent / f"{identifier}.log" + attempt["log"] = str(log_path.resolve()) + if archived: + attempt["archived_incomplete_output"] = archived + state["current_id"] = identifier + state["status"] = "running" + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ) + if job["kind"] == "formal_validation": + environment["CUDA_VISIBLE_DEVICES"] = str(job["physical_gpu_id"]) + else: + environment.pop("CUDA_VISIBLE_DEVICES", None) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + attempt["command"], cwd=Path.cwd(), env=environment, + stdout=log, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not completed_matches(job): + state["status"] = "failed_job" + state["failure"] = {"id": identifier, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(identifier) + atomic_json(args.state, state) + state["status"] = "complete" + state["current_id"] = None + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_fold_milestone_eval.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_fold_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..bae92c4c4151e059eb56207d37420d72fa6d3dbe --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_fold_milestone_eval.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +"""Evaluate H2O-bearing milestones for Phase 9 group-CV replicas.""" + +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any, Iterator + +import yaml + +from scripts.run_phase9_fold_shard import fold_evaluation_complete +from scripts.run_phase9_external_milestone_eval import stable_checkpoint_sha256 +from scripts.run_phase9_unified_train_queue import parse_physical_gpu_ids +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3, 4, 5) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def h2o_milestones(config: dict[str, Any]) -> list[str]: + return [ + str(milestone["id"]) + for milestone in config["protocol"].get("source_exposure_milestones", []) + if "H2O" in milestone.get("minimum_batches", {}) + ] + + +def milestone_checkpoint(run_dir: Path, milestone_id: str) -> Path | None: + matches = sorted(run_dir.glob(f"milestone_{milestone_id}_step_*.pt")) + if len(matches) > 1: + raise RuntimeError(f"multiple checkpoints found for milestone {milestone_id}") + return matches[0] if matches else None + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +@contextmanager +def exclusive_evaluation_output(output: Path) -> Iterator[None]: + output.parent.mkdir(parents=True, exist_ok=True) + lock_path = output.parent / f".{output.name}.phase9-evaluation.lock" + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(lock.fileno(), fcntl.LOCK_UN) + + +def recovery_assignment( + plan_path: Path, worker_id: str, registry_hash: str, +) -> tuple[dict[str, Any], str]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + raise ValueError("recovery plan must explicitly exclude official test") + if plan.get("registry_sha256") != registry_hash: + raise ValueError("recovery plan registry SHA256 differs") + matches = [item for item in plan["workers"] if item["id"] == worker_id] + if len(matches) != 1: + raise ValueError(f"recovery worker must be unique: {worker_id}") + return matches[0], sha256(plan_path) + + +def evaluation_command( + config_path: Path, checkpoint: Path, checkpoint_hash: str, + heldout: Path, heldout_hash: str, mode: str, output: Path, gpu: int, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", str(config_path), "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", str(heldout), + "--expected-cache-manifest-sha256", heldout_hash, + "--input-mode", mode, "--output-dir", str(output), + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", "phase9_h2o_fold_heldout", + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--shard", type=int, choices=(0, 1, 2), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--recovery-plan", type=Path) + parser.add_argument("--worker-id") + args = parser.parse_args() + registry = json.loads(args.registry.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + parser.error("fold registry must explicitly exclude official test") + conditions = {item["condition"]: item for item in registry["conditions"]} + assigned = registry["shards"][str(args.shard)] + registry_hash = sha256(args.registry) + selected_ids: set[str] | None = None + recovery_plan_hash: str | None = None + if (args.recovery_plan is None) != (args.worker_id is None): + parser.error("--recovery-plan and --worker-id must be provided together") + if args.recovery_plan is not None: + try: + worker, recovery_plan_hash = recovery_assignment( + args.recovery_plan, args.worker_id, registry_hash, + ) + except (KeyError, TypeError, ValueError) as error: + parser.error(str(error)) + if int(worker["shard"]) != args.shard: + parser.error("recovery worker shard differs") + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("recovery worker state path differs") + if tuple(worker["allowed_physical_gpus"]) != args.allowed_physical_gpus: + parser.error("recovery worker GPU assignment differs") + selected_ids = set(worker["evaluation_ids"]) + if len(selected_ids) != len(worker["evaluation_ids"]): + parser.error("recovery worker contains duplicate evaluation IDs") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_fold_milestone_eval_state_v1", + "status": "waiting_for_checkpoint", "shard": args.shard, + "registry": str(args.registry.resolve()), "registry_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(args.allowed_physical_gpus), + "official_test_used": False, + } + if recovery_plan_hash is not None: + state.update({ + "recovery_plan": str(args.recovery_plan.resolve()), + "recovery_plan_sha256": recovery_plan_hash, + "recovery_worker_id": args.worker_id, + "assigned_evaluation_ids": sorted(selected_ids), + "resource_amendment": "gpu_4_5_evaluator_authorization_only_20260730", + }) + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("registry_sha256") != registry_hash: + parser.error("existing state belongs to another registry") + if recovery_plan_hash is not None and ( + previous.get("recovery_plan_sha256") != recovery_plan_hash + or previous.get("recovery_worker_id") != args.worker_id + or set(previous.get("assigned_evaluation_ids", [])) != selected_ids + or tuple(previous.get("allowed_physical_gpus", ())) + != args.allowed_physical_gpus + ): + parser.error("existing recovery state belongs to another assignment") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for condition_id in assigned: + condition = conditions[condition_id] + config_path = Path(condition["config"]) + if sha256(config_path) != condition["config_sha256"]: + parser.error(f"fold config hash differs: {condition_id}") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + heldout = Path(config["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + run_dir = Path(condition["output_dir"]) + for milestone_id in h2o_milestones(config): + milestone_ids = { + f"{condition_id}_{milestone_id}_{mode}" + for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + if selected_ids is not None and not (milestone_ids & selected_ids): + continue + while True: + checkpoint = milestone_checkpoint(run_dir, milestone_id) + if checkpoint is not None: + break + state["status"] = "waiting_for_checkpoint" + state["waiting_for"] = f"{condition_id}:{milestone_id}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + evaluation_id = f"{condition_id}_{milestone_id}_{mode}" + if selected_ids is not None and evaluation_id not in selected_ids: + continue + output = args.output_root / condition_id / milestone_id / mode + if fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + continue + with exclusive_evaluation_output(output): + if fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + continue + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty incomplete output: {output}") + while True: + gpu = idle_gpu(args.allowed_physical_gpus) + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = evaluation_command( + config_path, checkpoint, checkpoint_hash, + heldout, heldout_hash, mode, output, gpu, + ) + log_path = args.state.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + state["status"] = "failed" + state["failure"] = { + "id": evaluation_id, "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + if selected_ids is not None and not selected_ids.issubset(state["completed_ids"]): + missing = sorted(selected_ids - set(state["completed_ids"])) + parser.error(f"recovery assignment contains unknown IDs: {missing}") + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_fold_overflow.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_fold_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..348d8b3162e8c54d6a313eb7961b75b243c63ab6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_fold_overflow.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 9 fold conditions early on otherwise idle capacity.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def prerequisite_states_complete(plan: dict[str, Any]) -> bool: + for item in plan["prerequisite_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("overflow plan must explicitly exclude official test") + registry = Path(plan["fold_training_registry"]) + if sha256(registry) != plan["fold_training_registry_sha256"]: + parser.error("fold training registry SHA256 differs") + registry_payload = json.loads(registry.read_text(encoding="utf-8")) + registered = {item["condition"] for item in registry_payload["conditions"]} + if not plan["conditions"] or any(item not in registered for item in plan["conditions"]): + parser.error("overflow condition is not in the frozen fold registry") + + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + state: dict[str, Any] = { + "schema_version": "phase9_fold_overflow_state_v1", + "status": "waiting_for_prerequisites", + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "started_utc": utc_now(), + "updated_utc": utc_now(), + "completed_conditions": [], + "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing overflow state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + + while not prerequisite_states_complete(plan): + state["status"] = "waiting_for_prerequisites" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + child_root = Path(plan["child_state_root"]) + child_root.mkdir(parents=True, exist_ok=True) + for condition in plan["conditions"]: + if condition in state["completed_conditions"]: + continue + child_state = child_root / f"{condition.lower()}.json" + command = [ + sys.executable, + "-m", + "scripts.run_phase9_unified_train_queue", + "--queue", + str(registry), + "--condition", + condition, + "--state", + str(child_state), + "--poll-seconds", + str(args.poll_seconds), + "--allowed-physical-gpus", + str(plan["physical_gpu_id"]), + ] + log_path = args.state.parent / f"overflow_{condition.lower()}.log" + attempt = { + "condition": condition, + "start_utc": utc_now(), + "command": command, + "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "running_condition" + state["current_condition"] = condition + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, + stdout=log, + stderr=subprocess.STDOUT, + text=True, + check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode: + state["status"] = "failed_resumable" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_conditions"].append(condition) + atomic_json(args.state, state) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_fold_shard.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_fold_shard.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6b518537959a2149496efd6fae0f33badb5dc7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_fold_shard.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Run a shard of Phase 9 H2O group-CV replicas and formal fold evaluations.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) +from scripts.run_phase9_unified_train_queue import parse_physical_gpu_ids + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def main_training_complete(plan: dict[str, Any]) -> bool: + for item in plan["main_training_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def main_training_gate_satisfied( + plan: dict[str, Any], start_before_main_complete: bool, +) -> bool: + return start_before_main_complete or main_training_complete(plan) + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def fold_evaluation_complete( + output: Path, checkpoint_hash: str, manifest_hash: str, mode: str, +) -> bool: + report_path = output / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_phase9_h2o_fold_heldout" + and report.get("evaluation_role") == "phase9_h2o_fold_heldout" + and report.get("checkpoint", {}).get("sha256") == checkpoint_hash + and report.get("cache_manifest", {}).get("sha256") == manifest_hash + and report.get("input_mode") == mode + and report.get("official_test_used") is False + ) + + +def run_fold_evaluations( + condition: dict[str, Any], state: dict[str, Any], state_path: Path, + evaluation_root: Path, poll_seconds: float, + allowed_gpus: tuple[int, ...] = ALLOWED_GPUS, +) -> None: + step = int(condition["stages"][-1]["stop_after_step"]) + checkpoint = Path(condition["output_dir"]) / f"step_{step:07d}_final.pt" + checkpoint_hash = sha256(checkpoint) + config = Path(condition["config"]) + config_payload = __import__("yaml").safe_load(config.read_text(encoding="utf-8")) + heldout = Path(config_payload["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + output = evaluation_root / condition["condition"] / mode + evaluation_id = f"{condition['condition']}_{mode}" + if fold_evaluation_complete(output, checkpoint_hash, heldout_hash, mode): + if evaluation_id not in state["completed_evaluations"]: + state["completed_evaluations"].append(evaluation_id) + continue + while True: + gpu = idle_gpu(allowed_gpus) + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu_evaluation" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + time.sleep(poll_seconds) + if output.exists() and any(output.iterdir()): + release_physical_gpu_claim(gpu) + raise RuntimeError(f"nonempty incomplete fold evaluation output: {output}") + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", str(config), "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", str(heldout), + "--expected-cache-manifest-sha256", heldout_hash, + "--input-mode", mode, "--output-dir", str(output), + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", "phase9_h2o_fold_heldout", + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + log_path = state_path.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "type": "fold_evaluation", + "start_utc": utc_now(), "physical_gpu_id": gpu, + "command": command, "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "evaluating_fold" + atomic_json(state_path, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + raise RuntimeError(f"fold evaluation failed: {evaluation_id}") + state["completed_evaluations"].append(evaluation_id) + atomic_json(state_path, state) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--shard", type=int, choices=(0, 1, 2), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--start-before-main-complete", action="store_true") + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("fold shard plan must explicitly exclude official test") + registry_path = Path(plan["fold_training_registry"]) + if sha256(registry_path) != plan["fold_training_registry_sha256"]: + parser.error("fold training registry SHA256 differs") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + conditions = {item["condition"]: item for item in registry["conditions"]} + assigned = registry["shards"][str(args.shard)] + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_fold_shard_state_v1", + "status": "waiting_for_main_training", "shard": args.shard, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_conditions": [], "completed_evaluations": [], "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing shard state belongs to another plan") + state = previous + previous_gpus = tuple(state.get("allowed_physical_gpus", ALLOWED_GPUS)) + if state.get("attempts") and previous_gpus != args.allowed_physical_gpus: + parser.error("cannot change allowed GPUs after this shard has attempted work") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + state["allowed_physical_gpus"] = list(args.allowed_physical_gpus) + state["start_before_main_complete"] = bool(args.start_before_main_complete) + if args.start_before_main_complete: + state["resource_amendment"] = "user_authorized_all_idle_gpus_20260727" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + while not main_training_gate_satisfied(plan, args.start_before_main_complete): + state["status"] = "waiting_for_main_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_root = Path(plan["fold_evaluation_root"]) + for condition_id in assigned: + condition = conditions[condition_id] + if condition_id not in state["completed_conditions"]: + child_state = args.state.parent / "fold_jobs" / f"{condition_id.lower()}.json" + child_state.parent.mkdir(parents=True, exist_ok=True) + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry_path), "--condition", condition_id, + "--state", str(child_state), "--poll-seconds", str(args.poll_seconds), + "--allowed-physical-gpus", + ",".join(str(gpu) for gpu in args.allowed_physical_gpus), + ] + log_path = args.state.parent / f"{condition_id.lower()}_training.log" + attempt = { + "id": condition_id, "type": "fold_training", + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "training_fold" + state["current_condition"] = condition_id + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode: + state["status"] = "failed_fold_training" + state["failure"] = {"condition": condition_id, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_conditions"].append(condition_id) + atomic_json(args.state, state) + try: + run_fold_evaluations( + condition, state, args.state, evaluation_root, args.poll_seconds, + args.allowed_physical_gpus, + ) + except RuntimeError as error: + state["status"] = "failed_fold_evaluation" + state["failure"] = {"condition": condition_id, "reason": str(error)} + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_hot_cache_release_bridge.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_hot_cache_release_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f786874c313bcb438d540641b84f917de27431 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_hot_cache_release_bridge.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Publish and receive the immutable server_new Stage 7 HOT3D cache release.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + cache_step_complete, + sha256, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any] | None: + candidate = Path(path) + if not candidate.is_file(): + return None + return json.loads(candidate.read_text(encoding="utf-8")) + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("publisher_owner") != "server_new" + or plan.get("receiver_owner") != "taku3" + ): + raise ValueError("HOT cache release bridge plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"HOT cache bridge binding differs: {path}") + root = Path(plan["release_root"]) + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("HOT cache release root is not /SSD2") + for item in plan["artifacts"]: + path = Path(item["path"]) + if root not in path.parents or path == root: + raise ValueError("HOT cache release artifact is outside release root") + if Path(plan["staging_root"]).parts[:2] != ("/", "SSD2"): + raise ValueError("HOT cache staging root is not /SSD2") + + +def inventory_tree(root: Path, directory: Path) -> list[dict[str, Any]]: + if not directory.is_dir() or directory.is_symlink(): + raise ValueError(f"HOT release artifact directory differs: {directory}") + records = [] + for path in sorted(directory.rglob("*")): + if path.is_symlink(): + raise ValueError(f"HOT release refuses symlink: {path}") + if not path.is_file(): + continue + records.append({ + "path": str(path.relative_to(root)), "bytes": path.stat().st_size, + "sha256": sha256(path), + }) + return records + + +def validate_primary(plan: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]] | None: + queue_path = Path(plan["producer_queue_state"]["path"]) + primary_path = Path(plan["producer_worker_state"]) + queue = read_json(queue_path) + primary = read_json(primary_path) + if queue is None or primary is None: + return None + if queue.get("status") != "complete": + return None + if ( + queue.get("plan_sha256") != plan["producer_queue_state"]["plan_sha256"] + or queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + ): + raise ValueError("HOT producer queue completion binding differs") + execution_path = Path(plan["cache_execution_plan"]["path"]) + execution = json.loads(execution_path.read_text(encoding="utf-8")) + worker = next(item for item in execution["workers"] if item["id"] == "hot3d") + expected_steps = [item["id"] for item in worker["steps"]] + if ( + primary.get("status") != "complete" + or primary.get("worker") != "hot3d" + or primary.get("plan_sha256") != plan["cache_execution_plan"]["sha256"] + or primary.get("completed_steps") != expected_steps + or primary.get("official_test_used") is not False + or primary.get("h2o_official_validation_used") is not False + ): + raise ValueError("HOT primary worker completion differs") + for step in worker["steps"]: + if step["id"].endswith("resume_verify") and not cache_step_complete(step, True): + raise ValueError(f"HOT deployable resume output differs: {step['id']}") + return queue, primary + + +def publish(plan_path: Path, plan: dict[str, Any]) -> bool: + completion = validate_primary(plan) + if completion is None: + return False + queue, primary = completion + release_path = Path(plan["release_state"]) + if release_path.is_file(): + existing = json.loads(release_path.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return True + raise ValueError("existing HOT cache release differs") + root = Path(plan["release_root"]) + files: list[dict[str, Any]] = [] + artifact_records = [] + for item in plan["artifacts"]: + records = inventory_tree(root, Path(item["path"])) + files.extend(records) + artifact_records.append({ + "id": item["id"], "path": item["path"], + "relative_path": str(Path(item["path"]).relative_to(root)), + "file_count": len(records), + "total_bytes": sum(record["bytes"] for record in records), + }) + relative_paths = [item["path"] for item in files] + if len(relative_paths) != len(set(relative_paths)): + raise ValueError("HOT release inventory contains duplicate paths") + release = { + "schema_version": "phase9_hot_cache_immutable_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), "release_root": str(root.resolve()), + "producer_queue_state": { + "path": str(Path(plan["producer_queue_state"]["path"]).resolve()), + "sha256": sha256(plan["producer_queue_state"]["path"]), + "completed_utc": queue.get("completed_utc"), + }, + "producer_worker_state": { + "path": str(Path(plan["producer_worker_state"]).resolve()), + "sha256": sha256(plan["producer_worker_state"]), + "value": primary, + }, + "artifacts": artifact_records, "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "single_deployable_manifest_writer": "original_resolution_cache_runner", + "live_reverse_sync_forbidden": True, + "read_only_after_receive": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(release_path, release) + os.chmod(release_path, 0o444) + return True + + +def fetch_remote_json(host: str, path: str, timeout: float) -> dict[str, Any] | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if completed.returncode: + return None + try: + value = json.loads(completed.stdout) + except json.JSONDecodeError: + return None + return value if isinstance(value, dict) else None + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or release.get("live_reverse_sync_forbidden") is not True + or release.get("read_only_after_receive") is not True + ): + raise ValueError("HOT immutable release contract differs") + paths = [item["path"] for item in release.get("files", [])] + if ( + len(paths) != len(set(paths)) + or len(paths) != release.get("file_count") + or sum(item["bytes"] for item in release["files"]) != release.get("total_bytes") + ): + raise ValueError("HOT immutable release inventory differs") + for value in paths: + relative = Path(value) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError(f"HOT immutable release path is unsafe: {relative}") + + +def write_external_proxy(plan: dict[str, Any], queue: dict[str, Any] | None) -> None: + state_path = Path(plan["local_worker_state"]) + state = read_json(state_path) + if state is None or state.get("status") == "complete": + return + backup = Path(plan["local_state_backup"]) + if not backup.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(state_path, backup) + os.chmod(backup, 0o444) + if state.get("plan_sha256") != plan["cache_execution_plan"]["sha256"]: + raise ValueError("local HOT proxy state binding differs") + state.update({ + "status": "waiting_for_server_new_immutable_release", + "updated_utc": utc_now(), "external_owner": "server_new", + "external_queue_status": (queue or {}).get("status", "unavailable"), + "external_queue_updated_utc": (queue or {}).get("updated_utc"), + "live_reverse_sync_forbidden": True, + "h2o_official_validation_used": False, "official_test_used": False, + }) + atomic_json(state_path, state) + + +def verify_staging(staging: Path, release: dict[str, Any]) -> None: + for item in release["files"]: + path = staging / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] or sha256(path) != item["sha256"] + ): + raise ValueError(f"received HOT cache file differs: {path}") + + +def install_artifacts(plan: dict[str, Any], release: dict[str, Any], staging: Path) -> list[dict[str, Any]]: + installed = [] + backup_root = Path(plan["receive_backup_root"]) + for item in release["artifacts"]: + destination = Path(item["path"]) + source = staging / item["relative_path"] + backup = backup_root / item["relative_path"] + if destination.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + if backup.exists(): + raise ValueError(f"HOT receive backup already exists: {backup}") + os.replace(destination, backup) + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination) + for path in destination.rglob("*"): + os.chmod(path, 0o555 if path.is_dir() else 0o444) + os.chmod(destination, 0o555) + installed.append({ + "id": item["id"], "path": str(destination.resolve()), + "backup": str(backup.resolve()) if backup.exists() else None, + "file_count": item["file_count"], "total_bytes": item["total_bytes"], + }) + return installed + + +def receive(plan_path: Path, plan: dict[str, Any], state_path: Path) -> bool: + timeout = float(plan["ssh_timeout_seconds"]) + queue = fetch_remote_json( + plan["remote_host"], plan["producer_queue_state"]["path"], timeout, + ) + release = fetch_remote_json(plan["remote_host"], plan["release_state"], timeout) + if release is None: + write_external_proxy(plan, queue) + atomic_json(state_path, { + "schema_version": "phase9_hot_cache_receive_state_v1", + "status": "waiting_for_server_new_immutable_release", + "updated_utc": utc_now(), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "remote_queue_status": (queue or {}).get("status", "unavailable"), + "h2o_official_validation_used": False, "official_test_used": False, + }) + return False + validate_release(plan_path, plan, release) + if (read_json(state_path) or {}).get("status") == "complete": + return True + staging = Path(plan["staging_root"]) + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".release_files.txt" + file_list.write_text("".join(item["path"] + "\n" for item in release["files"]), encoding="utf-8") + command = [ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['remote_host']}:{Path(plan['release_root']).resolve()}/", + f"{staging.resolve()}/", + ] + completed = subprocess.run(command, check=False) + if completed.returncode: + raise RuntimeError(f"HOT immutable rsync failed: {completed.returncode}") + verify_staging(staging, release) + installed = install_artifacts(plan, release, staging) + remote_state = release["producer_worker_state"]["value"] + state_temporary = Path(plan["local_worker_state"]).with_suffix(".remote.tmp") + state_temporary.write_text(json.dumps(remote_state, indent=2) + "\n", encoding="utf-8") + if sha256(state_temporary) != release["producer_worker_state"]["sha256"]: + state_temporary.unlink() + raise ValueError("HOT received worker state differs") + os.replace(state_temporary, plan["local_worker_state"]) + result = { + "schema_version": "phase9_hot_cache_receive_state_v1", + "status": "complete", "completed_utc": utc_now(), + "updated_utc": utc_now(), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), "release_state": plan["release_state"], + "release_file_count": release["file_count"], + "release_total_bytes": release["total_bytes"], "installed": installed, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, result) + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--state", type=Path) + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1 and not args.once: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + state_path = Path(plan["release_state"] if args.role == "publish" else plan["receive_state"]) + if args.state and args.state.resolve() != state_path.resolve(): + parser.error("HOT cache bridge state path differs") + state_path.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{state_path}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + complete = publish(args.plan, plan) if args.role == "publish" else receive( + args.plan, plan, state_path, + ) + if complete or args.once: + print(json.dumps(read_json(state_path) or {"status": "waiting"}, indent=2)) + return + time.sleep(args.poll_seconds) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_hot_prefill_merge_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_hot_prefill_merge_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..0044df9b517929b1658514cfee1e03e7f397a52a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_hot_prefill_merge_queue.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Wait for frozen HOT prefill shards and merge them into the primary cache.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +import time + +from scripts.cache_phase7_hot3d import sha256 +from scripts.merge_phase9_hot_prefill import merge_prefills + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def prefill_complete(path: Path) -> bool: + report = path / "cache_report.json" + if not report.is_file(): + return False + value = json.loads(report.read_text(encoding="utf-8")) + return value.get("status") == "complete" and value.get("mode") == "staged_prefill" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("prefill plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + prefill_dirs = [Path(item["output_dir"]) for item in plan["shards"]] + state = { + "schema_version": "phase9_hot_prefill_merge_queue_v1", + "status": "waiting_for_prefill", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing state belongs to another prefill plan") + if previous.get("status") == "complete": + print(json.dumps(previous, indent=2)) + return + state = previous + while not all(prefill_complete(path) for path in prefill_dirs): + state["status"] = "waiting_for_prefill" + state["ready_shards"] = [str(path) for path in prefill_dirs if prefill_complete(path)] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "merging" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + result = merge_prefills( + Path(plan["target_output_dir"]), prefill_dirs, Path(plan["merge_report"]), + ) + state.update({ + "status": "complete", "updated_utc": utc_now(), + "merge_report": str(Path(plan["merge_report"]).resolve()), + "merge_report_sha256": sha256(Path(plan["merge_report"])), + "linked": result["linked"], + "existing_identical": result["existing_identical"], + }) + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_hot_prefill_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_hot_prefill_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..404aa2ad2ed1207d4650a0580a92722f4073d778 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_hot_prefill_queue.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +"""Run disjoint HOT3D cache prefills, merge them, and resume the canonical writer.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.cache_phase7_hot3d import sha256 +from scripts.merge_phase9_hot_prefill import merge_prefills + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def command_value(command: list[str], option: str) -> str: + try: + return command[command.index(option) + 1] + except (ValueError, IndexError) as error: + raise ValueError(f"prefill command lacks {option}") from error + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("resolution_hw") != [512, 896] + ): + raise ValueError("HOT prefill plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"HOT prefill binding differs: {path}") + source = Path(plan["source_manifest"]["path"]) + if not source.is_file() or sha256(source) != plan["source_manifest"]["sha256"]: + raise ValueError("HOT prefill source manifest differs") + target = Path(plan["target_output_dir"]) + if target.parts[:2] != ("/", "SSD2"): + raise ValueError("HOT prefill target is not on /SSD2") + shards = plan["shards"] + ranges = [tuple(item["candidate_position_range"]) for item in shards] + expected_start = 0 + outputs: set[Path] = set() + for shard, (start, stop) in zip(shards, ranges, strict=True): + if start != expected_start or stop <= start: + raise ValueError("HOT prefill ranges are not a contiguous partition") + expected_start = stop + output = Path(shard["output_dir"]) + if output.parts[:2] != ("/", "SSD2") or output == target or output in outputs: + raise ValueError("HOT prefill output ownership differs") + outputs.add(output) + command = shard["command"] + if ( + command_value(command, "--output-dir") != str(output) + or command_value(command, "--source-manifest") != str(source) + or command_value(command, "--prefill-position-range") != str(start) + or command[command.index("--prefill-position-range") + 2] != str(stop) + or command[command.index("--target-hw") + 1:command.index("--target-hw") + 3] + != ["512", "896"] + or "--decode-all-candidates" not in command + ): + raise ValueError(f"HOT prefill command differs: {shard['id']}") + if expected_start != int(plan["full_candidate_clips"]): + raise ValueError("HOT prefill ranges do not cover the candidate order") + if len({item["id"] for item in shards}) != len(shards): + raise ValueError("HOT prefill shard IDs are not unique") + if Path(plan["state"]).resolve() == plan_path.resolve(): + raise ValueError("HOT prefill state collides with its plan") + + +def prefill_complete(shard: dict[str, Any], plan: dict[str, Any]) -> bool: + output = Path(shard["output_dir"]) + report_path = output / "cache_report.json" + manifest_path = output / "prefill_manifest.jsonl" + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + start, stop = shard["candidate_position_range"] + processed = int(report.get("clips", -1)) + len( + report.get("skipped_no_supervision", []) + ) + return ( + report.get("status") == "complete" + and report.get("mode") == "staged_prefill" + and report.get("official_test_used") is False + and report.get("resolution_hw") == plan["resolution_hw"] + and report.get("candidate_position_range") == [start, stop] + and report.get("full_candidate_clips") == plan["full_candidate_clips"] + and report.get("requested_target_clips") == plan["requested_target_clips"] + and report.get("candidate_source_indices_sha256") + == plan["candidate_source_indices_sha256"] + and report.get("source_manifest", {}).get("sha256") + == plan["source_manifest"]["sha256"] + and report.get("cache_manifest", {}).get("sha256") == sha256(manifest_path) + and processed == stop - start + ) + + +def shard_pid_matches(pid: int, shard: dict[str, Any]) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + start, stop = shard["candidate_position_range"] + return ( + "scripts.cache_phase7_hot3d" in command + and f"--prefill-position-range {start} {stop}" in command + and f"--output-dir {Path(shard['output_dir']).resolve()}" in command + ) + + +def primary_pid_matches(pid: int, plan: dict[str, Any]) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_resolution_cache_queue" in command + and "--worker hot3d" in command + and f"--state {Path(plan['primary_state']).resolve()}" in command + ) + + +def launch(command: list[str], log_path: Path) -> int: + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def runtime_command(shard: dict[str, Any]) -> list[str]: + command = list(shard["command"]) + if Path(shard["output_dir"]).exists() and "--resume" not in command: + command.append("--resume") + return command + + +def primary_status(plan: dict[str, Any]) -> str: + path = Path(plan["primary_state"]) + if not path.is_file(): + return "missing" + state = json.loads(path.read_text(encoding="utf-8")) + if ( + state.get("plan_sha256") != plan["cache_execution_plan"]["sha256"] + or state.get("worker") != "hot3d" + or state.get("official_test_used") is not False + ): + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("HOT prefill state path differs from plan") + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_hot_prefill_queue_v1", + "status": "prefilling", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "shards": {}, "primary": {}, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing HOT prefill state belongs to another plan") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + statuses: dict[str, str] = {} + for shard in plan["shards"]: + identifier = shard["id"] + complete = prefill_complete(shard, plan) + statuses[identifier] = "complete" if complete else "running" + if complete: + continue + previous = state.setdefault("shards", {}).get(identifier, {}) + pid = int(previous.get("pid", -1)) + if not shard_pid_matches(pid, shard): + attempts = int(previous.get("attempts", 0)) + 1 + command = runtime_command(shard) + pid = launch(command, Path(shard["log"])) + state["shards"][identifier] = { + "pid": pid, "attempts": attempts, + "launched_utc": utc_now(), "command": command, + } + state["shard_statuses"] = statuses + state["updated_utc"] = utc_now() + if all(status == "complete" for status in statuses.values()): + break + state["status"] = "prefilling" + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + merge_path = Path(plan["merge_report"]) + if merge_path.is_file(): + merge = json.loads(merge_path.read_text(encoding="utf-8")) + if merge.get("status") != "complete": + parser.error("existing HOT prefill merge report differs") + else: + state["status"] = "merging" + atomic_json(args.state, state) + merge = merge_prefills( + Path(plan["target_output_dir"]), + [Path(item["output_dir"]) for item in plan["shards"]], + merge_path, + ) + state["merge_report"] = { + "path": str(merge_path.resolve()), "sha256": sha256(merge_path), + "linked": merge["linked"], + "existing_identical": merge["existing_identical"], + } + while True: + status = primary_status(plan) + state["primary_status"] = status + if status == "complete": + break + if status.startswith("failed") and status != "failed_resumable": + state["status"] = "failed_primary_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + pid = int(state.setdefault("primary", {}).get("pid", -1)) + if not primary_pid_matches(pid, plan): + command = list(plan["primary_resume_command"]) + pid = launch(command, Path(plan["primary_log"])) + state["primary"] = { + "pid": pid, "launched_utc": utc_now(), "command": command, + } + state["status"] = "merged_waiting_for_canonical_writer" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_last2_candidate_controller.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_last2_candidate_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8a1689c26bf3c9735e969e1bf77208b7844390 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_last2_candidate_controller.py @@ -0,0 +1,510 @@ +#!/usr/bin/env python3 +"""Run or formally reject one ordered DINO Base last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_resolution_evaluation_controller import ( + hard_failure as evaluation_hard_failure, + launch_worker as launch_evaluation_worker, + pid_matches as evaluation_pid_matches, + should_launch as should_launch_evaluation, + worker_status, +) +from scripts.run_phase9_resolution_training_controller import ( + condition_status, + hard_failure as training_hard_failure, + pid_matches as training_pid_matches, +) +from scripts.run_phase9_shared_augmentation_training_controller import ( + launch_worker as launch_training_worker, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("candidate") not in {"5e7", "1e6"} + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("training_job_count") != 7 + or plan.get("evaluation_count") != 25 + or plan.get("evaluation_worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + ): + raise ValueError("last-2 candidate controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"last-2 candidate binding differs: {path}") + + +def admission(plan: dict[str, Any]) -> tuple[str, str, dict[str, Any] | None]: + state_path = Path(plan["admission_controller_state"]) + if not state_path.is_file(): + return "waiting", "upstream_state_missing", None + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed"): + return "failed", "upstream_controller_failed", None + return "waiting", "upstream_controller_incomplete", None + if ( + state.get("plan_sha256") != plan["admission_controller_plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not report_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or report_path.resolve() + != Path(plan["admission_decision_report"]).resolve() + ): + return "failed", "upstream_decision_binding_differs", None + report = read_json(report_path) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + return "failed", "upstream_decision_isolation_differs", None + if plan["candidate"] == "5e7": + admitted = report.get("stage9_preceding_mechanism_gate", {}).get( + "stage9_last2_admitted" + ) is True + reason = ( + "preceding_mechanism_macro_and_worst_improved" + if admitted else "preceding_mechanism_gate_failed" + ) + else: + admitted = ( + report.get("candidate") == "5e7" + and report.get("gate", {}).get("macro_strictly_improved") is True + and report.get("gate", {}).get("worst_domain_strictly_improved") is True + and report.get("gate", {}).get("accepted") is True + ) + reason = "five_e7_strict_gate_passed" if admitted else "five_e7_gate_failed" + return ("admitted" if admitted else "rejected"), reason, report + + +def formal_rejection( + plan: dict[str, Any], reason: str, upstream: dict[str, Any], output: Path, +) -> dict[str, Any]: + return { + "schema_version": "phase9_last2_candidate_decision_v1", + "status": "complete", "candidate": plan["candidate"], + "created_utc": utc_now(), + "decision": f"not_admitted_last2_{plan['candidate']}", + "not_admitted_reason": reason, + "gate": { + "macro_strictly_improved": False, + "worst_domain_strictly_improved": False, + "accepted": False, + }, + "upstream_decision": { + "path": str(Path(plan["admission_decision_report"]).resolve()), + "sha256": sha256(plan["admission_decision_report"]), + }, + "training_started": False, + "evaluation_started": False, + "dino_large_admitted": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("last-2 controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + static_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_last2_candidate_controller_state_v1", + "status": "waiting_for_admission", "candidate": plan["candidate"], + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "machine": machine, + "controller_pid": os.getpid(), + "training_workers": {}, "evaluation_workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != static_hash: + parser.error("existing last-2 controller state differs") + if state.get("machine") != machine: + parser.error("existing last-2 state belongs to another machine") + if state.get("status") in {"complete", "complete_local"}: + print(json.dumps(state, indent=2)) + return + while True: + admission_status, reason, upstream = admission(plan) + if admission_status == "waiting": + state["status"] = "waiting_for_admission" + state["waiting_reason"] = reason + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + if admission_status == "failed": + state["status"] = "failed_admission_binding" + state["failure"] = reason + atomic_json(args.state, state) + raise SystemExit(1) + break + + decision_path = Path(plan["decision_report"]) + if admission_status == "rejected": + assert upstream is not None + if machine != "taku3": + while not decision_path.is_file(): + state["status"] = "waiting_for_central_rejection_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "complete_local" + state["admitted"] = False + state["decision_report"] = { + "path": str(decision_path.resolve()), + "sha256": sha256(decision_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + if not decision_path.exists(): + decision_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json( + decision_path, + formal_rejection(plan, reason, upstream, decision_path), + ) + report = read_json(decision_path) + if ( + report.get("status") != "complete" + or report.get("candidate") != plan["candidate"] + or report.get("decision") + != f"not_admitted_last2_{plan['candidate']}" + or report.get("not_admitted_reason") != reason + or report.get("training_started") is not False + or report.get("evaluation_started") is not False + or report.get("upstream_decision", {}).get("sha256") + != sha256(plan["admission_decision_report"]) + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + state["status"] = "failed_rejection_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["admitted"] = False + state["decision"] = report["decision"] + state["decision_report"] = { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + registry = Path(plan["training_registry"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_last2_training_registry", + "--candidate", plan["candidate"], + "--stage8-controller-plan", plan["stage8_controller_plan"], + "--stage8-controller-state", plan["stage8_controller_state"], + "--last2-plan", plan["last2_plan"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), + "--state", plan["training_registry_state"], + ] + if plan["candidate"] == "1e6": + builder_command.extend(("--five-e7-decision", plan["admission_decision_report"])) + if machine == "taku3": + state["status"] = "building_training_registry" + state["training_builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_training_registry_builder" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + registry_hash = sha256(registry) + registry_payload = read_json(registry) + conditions = [item["condition"] for item in registry_payload["conditions"]] + owners = condition_owners(registry_payload, assignment) + if ( + registry_payload.get("candidate") != plan["candidate"] + or len(conditions) != plan["training_job_count"] + or len(set(conditions)) != len(conditions) + or registry_payload.get("official_test_used") is not False + ): + state["status"] = "failed_training_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_hash + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("training_workers", {}) + training_state_root = Path(plan["training_state_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = training_state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_hash) + statuses[condition] = status + if training_hard_failure(status) or status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["training_workers"].get(condition, {}).get("pid", -1) + ) + if not training_pid_matches(previous_pid, condition, registry): + pid = launch_training_worker( + condition, registry, condition_state, + Path(plan["training_log_root"]) / f"{condition.lower()}.log", + allowed_gpus, + ) + state["training_workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["training_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(training_hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + training_completion = { + "schema_version": "phase9_last2_training_completion_state_v1", + "status": "complete", "candidate": plan["candidate"], + "completed_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "training_registry": str(registry.resolve()), + "training_registry_sha256": registry_hash, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if machine == "taku3": + atomic_json(Path(plan["training_completion_state"]), training_completion) + else: + while not Path(plan["training_completion_state"]).is_file(): + state["status"] = "waiting_for_central_training_aggregate_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + eval_builder = [ + sys.executable, "-m", "scripts.build_phase9_last2_evaluation_plan", + "--candidate", plan["candidate"], + "--training-controller-plan", str(args.plan), + "--training-controller-state", plan["training_completion_state"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["evaluation_worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["evaluation_builder_command"] = eval_builder + atomic_json(args.state, state) + result = subprocess.run(eval_builder, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_hash = sha256(evaluation_plan) + dynamic = read_json(evaluation_plan) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["evaluation_worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = evaluation_hash + state["owned_evaluation_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("evaluation_workers", {}) + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + worker_state = Path(worker["state"]) + status = worker_status(worker_state, evaluation_hash) + statuses[worker["id"]] = status + if not should_launch_evaluation(worker, machine, status): + continue + previous_pid = int( + state["evaluation_workers"].get(worker["id"], {}).get("pid", -1) + ) + if not evaluation_pid_matches( + previous_pid, worker["id"], evaluation_plan, + ): + pid = launch_evaluation_worker( + evaluation_plan, worker, + Path(plan["evaluation_worker_log_root"]) / f"{worker['id']}.log", + ) + state["evaluation_workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["evaluation_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "training_workers": state["training_workers"], + "evaluation_workers": state["evaluation_workers"], + } + if any(evaluation_hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["admitted"] = True + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + if not decision_path.exists(): + command = [ + sys.executable, "-m", "scripts.summarize_phase9_last2_decision", + "--plan", str(evaluation_plan), "--output", str(decision_path), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = read_json(decision_path) + if ( + report.get("status") != "complete" + or report.get("candidate") != plan["candidate"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != evaluation_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["admitted"] = True + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["decision_report"] = { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_last2_resume_training.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_last2_resume_training.py new file mode 100644 index 0000000000000000000000000000000000000000..b169e799e229b526fefbaa79729dba29e9466d86 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_last2_resume_training.py @@ -0,0 +1,859 @@ +#!/usr/bin/env python3 +"""Freeze and supervise the resource-only Stage 9 1e-6 training resume.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import getpass +import hashlib +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import time +from typing import Any + + +SCHEMA = "phase9_last2_1e6_resume_training_amendment_v1" +STATE_SCHEMA = "phase9_last2_1e6_resume_training_supervisor_v1" +CONTROL_SCHEMA = "phase9_last2_1e6_resume_control_v1" +EXTERNAL_ROLES = {"loso_subject2", "loso_subject3", "lofamily_k"} +EXPECTED_ROLES = { + "full", + "loso_subject1", + "loso_subject2", + "loso_subject3", + "lofamily_h", + "lofamily_k", + "lofamily_o", +} +RESUMABLE_STATUSES = { + "missing", + "waiting_for_data", + "waiting_for_prerequisites", + "waiting_for_idle_gpu", + "running", + "failed_resumable", +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: str | Path, value: dict[str, Any]) -> None: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name( + f".{destination.name}.tmp.{os.getpid()}.{time.time_ns()}" + ) + with temporary.open("w", encoding="utf-8") as handle: + json.dump(value, handle, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, destination) + + +def binding(path: str | Path) -> dict[str, str]: + resolved = Path(path).resolve() + if not resolved.is_file(): + raise ValueError(f"binding is missing: {resolved}") + return {"path": str(resolved), "sha256": sha256(resolved)} + + +def validate_binding(value: dict[str, Any], label: str) -> Path: + path = Path(str(value.get("path", ""))) + digest = value.get("sha256") + if not path.is_file() or not isinstance(digest, str) or sha256(path) != digest: + raise ValueError(f"{label} binding differs: {path}") + return path + + +def process_command(pid: int) -> str | None: + try: + return Path(f"/proc/{pid}/cmdline").read_bytes().replace( + b"\0", b" " + ).decode("utf-8", errors="replace") + except (FileNotFoundError, PermissionError, ProcessLookupError): + return None + + +def matching_pids(*needles: str) -> list[int]: + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + command = process_command(int(entry.name)) + if command and all(needle in command for needle in needles): + matches.append(int(entry.name)) + return sorted(matches) + + +def world_adapter_active_pids(formal_root: str) -> list[int]: + runners = ( + "scripts.run_world_adapter_formal_training_v1", + "scripts.control_world_adapter_formal_evaluation_v1", + "scripts.train_phase7_external", + "scripts.evaluate_phase7_external", + ) + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + command = process_command(int(entry.name)) + if command and formal_root in command and any(item in command for item in runners): + matches.append(int(entry.name)) + return sorted(matches) + + +def validate_world_adapter_terminal( + amendment: dict[str, Any], *, require_inactive: bool = True +) -> None: + evidence = amendment["world_adapter_isolation"] + training_path = validate_binding(evidence["training_controller"], "WA training") + evaluation_path = validate_binding( + evidence["evaluation_controller"], "WA evaluation" + ) + report_path = validate_binding(evidence["comparison_report"], "WA comparison") + training = read_json(training_path) + evaluation = read_json(evaluation_path) + report = read_json(report_path) + if ( + training.get("status") != "training_complete_evaluation_locked" + or training.get("training_job_count") != 42 + or training.get("current_stage_complete") != 42 + or training.get("workers") != {} + or training.get("official_test_used") is not False + or evaluation.get("status") != "complete_report_only_no_promotion" + or evaluation.get("evaluation_job_count") != 150 + or evaluation.get("completed_evaluation_jobs") != 150 + or evaluation.get("workers") != {} + or evaluation.get("official_test_used") is not False + or report.get("status") != "complete_report_only_no_promotion" + ): + raise ValueError("World Adapter formal run is not terminal and isolated") + active = world_adapter_active_pids(evidence["formal_root"]) + if require_inactive and active: + raise RuntimeError(f"World Adapter workers are active: {active}") + + +def validate_original_plan_bindings(plan: dict[str, Any]) -> None: + for item in plan.get("bindings", []): + validate_binding(item, "original plan") + + +def role_owners(assignment: dict[str, Any]) -> dict[str, str]: + records = assignment["stage_condition_ownership"]["roles"] + owners = {item["role"]: item["owner"] for item in records} + if set(owners) != EXPECTED_ROLES or len(records) != len(owners): + raise ValueError("original distributed role ownership differs") + return owners + + +def freeze(args: argparse.Namespace) -> None: + output = args.output.resolve() + if output.exists(): + raise ValueError(f"amendment output already exists: {output}") + original_plan_path = args.original_plan.resolve() + original_state_path = args.original_state.resolve() + registry_path = args.training_registry.resolve() + assignment_path = args.distributed_assignment.resolve() + original_plan = read_json(original_plan_path) + original_state = read_json(original_state_path) + registry = read_json(registry_path) + assignment = read_json(assignment_path) + validate_original_plan_bindings(original_plan) + owners = role_owners(assignment) + plan_hash = sha256(original_plan_path) + registry_hash = sha256(registry_path) + if ( + original_plan.get("candidate") != "1e6" + or original_plan.get("training_registry") != str(registry_path) + or original_plan.get("distributed_assignment", {}).get("path") + != str(assignment_path) + or original_plan.get("distributed_assignment", {}).get("sha256") + != sha256(assignment_path) + or original_state.get("plan_sha256") != plan_hash + or original_state.get("training_registry_sha256") != registry_hash + or original_state.get("official_test_used") is not False + or registry.get("status") != "frozen_ready" + or registry.get("candidate") != "1e6" + or registry.get("backbone_learning_rate") != 1e-6 + or registry.get("target_step") != 405000 + or registry.get("official_test_used") is not False + or len(registry.get("conditions", [])) != 7 + ): + raise ValueError("original 1e-6 plan, state, or registry differs") + state_root = Path(original_plan["training_state_root"]).resolve() + mappings = [] + observed_roles = set() + for item in registry["conditions"]: + condition = item["condition"] + role = item["role"] + observed_roles.add(role) + logical_owner = owners[role] + if (role in EXTERNAL_ROLES) != (logical_owner == "server_new"): + raise ValueError(f"unexpected original owner for {role}") + config_path = validate_binding( + {"path": item["config"], "sha256": item["config_sha256"]}, + f"config {condition}", + ) + initialization = validate_binding( + { + "path": item["initialization_checkpoint"], + "sha256": item["initialization_checkpoint_sha256"], + }, + f"initialization {condition}", + ) + mappings.append( + { + "condition": condition, + "role": role, + "logical_owner": logical_owner, + "execution_owner": "taku3", + "priority": 0 if logical_owner == "taku3" else 1, + "config": str(config_path), + "config_sha256": item["config_sha256"], + "initialization_checkpoint": str(initialization), + "initialization_checkpoint_sha256": item[ + "initialization_checkpoint_sha256" + ], + "output_dir": item["output_dir"], + "state": str(state_root / f"{condition.lower()}.json"), + } + ) + if observed_roles != EXPECTED_ROLES: + raise ValueError("1e-6 registry roles differ") + created = utc_now() + value = { + "schema_version": SCHEMA, + "status": "frozen_training_approved", + "created_utc": created, + "candidate": "1e6", + "authorization": { + "status": "approved", + "authorized_by": args.authorized_by, + "authorized_utc": created, + "request": args.authorization_note, + }, + "repository": str(args.repository.resolve()), + "python": str(args.python.resolve()), + "orchestrator": binding(Path(__file__).resolve()), + "original_controller_plan": binding(original_plan_path), + "original_controller_state_after_fail_closed_restart": binding( + original_state_path + ), + "training_registry": binding(registry_path), + "distributed_assignment": binding(assignment_path), + "training_runner": binding(args.training_runner.resolve()), + "model_training_runner": binding(args.model_training_runner.resolve()), + "training_mappings": mappings, + "supervisor_state": str(args.supervisor_state.resolve()), + "training_completion_report": str(args.completion_report.resolve()), + "control_file": str(args.control_file.resolve()), + "scheduling": { + "physical_gpu_allowlist": [0, 1, 2, 3, 4, 5], + "max_concurrent_training_workers": 4, + "minimum_gpu_slots_reserved_for_world_adapter": 2, + "cpu_nice": 10, + "io_class": "best-effort", + "io_priority": 7, + "existing_taku3_conditions_first": True, + }, + "world_adapter_isolation": { + "formal_root": args.world_adapter_formal_root, + "training_controller": binding(args.world_adapter_training_state), + "evaluation_controller": binding(args.world_adapter_evaluation_state), + "comparison_report": binding(args.world_adapter_comparison_report), + "training_jobs_complete": 42, + "evaluation_jobs_complete": 150, + "automatic_model_promotion": False, + }, + "external_owner_preflight": { + "host": "taku-g2", + "checked_utc": args.external_owner_checked_utc, + "matching_1e6_process_count": args.external_owner_process_count, + "canonical_training_states_present": sum( + Path(item["state"]).is_file() + for item in mappings + if item["logical_owner"] == "server_new" + ), + }, + "original_controller_restart_result": { + "status": original_state.get("status"), + "gpu_training_started": False, + "reason": "registry builder rejected existing runs before worker launch", + }, + "resource_schedule_amendment_only": True, + "external_process_preemption_forbidden": True, + "external_processes_preempted": False, + "scientific_fields_changed": [], + "model_changed": False, + "data_changed": False, + "seed_changed": False, + "optimizer_changed": False, + "learning_rate_changed": False, + "horizon_changed": False, + "metric_changed": False, + "selection_gate_changed": False, + "evaluation_started": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + validate_world_adapter_terminal(value) + atomic_json(output, value) + os.chmod(output, 0o444) + print(json.dumps({"path": str(output), "sha256": sha256(output)}, indent=2)) + + +def validate_amendment(path: Path) -> tuple[dict[str, Any], dict[str, Any]]: + amendment = read_json(path) + false_fields = ( + "external_processes_preempted", + "model_changed", + "data_changed", + "seed_changed", + "optimizer_changed", + "learning_rate_changed", + "horizon_changed", + "metric_changed", + "selection_gate_changed", + "evaluation_started", + "h2o_official_validation_used", + "official_test_used", + ) + if ( + amendment.get("schema_version") != SCHEMA + or amendment.get("status") != "frozen_training_approved" + or amendment.get("candidate") != "1e6" + or amendment.get("authorization", {}).get("status") != "approved" + or amendment.get("resource_schedule_amendment_only") is not True + or amendment.get("external_process_preemption_forbidden") is not True + or amendment.get("scientific_fields_changed") != [] + or any(amendment.get(key) is not False for key in false_fields) + ): + raise ValueError("1e-6 resume amendment contract differs") + orchestrator = validate_binding(amendment["orchestrator"], "orchestrator") + if orchestrator.resolve() != Path(__file__).resolve(): + raise ValueError("running orchestrator path differs from amendment") + original_plan_path = validate_binding( + amendment["original_controller_plan"], "original controller plan" + ) + original_state_path = validate_binding( + amendment["original_controller_state_after_fail_closed_restart"], + "original controller state", + ) + registry_path = validate_binding(amendment["training_registry"], "registry") + assignment_path = validate_binding( + amendment["distributed_assignment"], "distributed assignment" + ) + validate_binding(amendment["training_runner"], "training runner") + validate_binding(amendment["model_training_runner"], "model training runner") + original_plan = read_json(original_plan_path) + original_state = read_json(original_state_path) + registry = read_json(registry_path) + assignment = read_json(assignment_path) + validate_original_plan_bindings(original_plan) + owners = role_owners(assignment) + if ( + original_plan.get("candidate") != "1e6" + or original_plan.get("training_registry") != str(registry_path) + or original_state.get("plan_sha256") != sha256(original_plan_path) + or original_state.get("training_registry_sha256") != sha256(registry_path) + or registry.get("status") != "frozen_ready" + or registry.get("candidate") != "1e6" + or registry.get("backbone_learning_rate") != 1e-6 + or registry.get("target_step") != 405000 + or len(registry.get("conditions", [])) != 7 + ): + raise ValueError("bound original 1e-6 artifacts differ") + schedule = amendment.get("scheduling", {}) + if ( + schedule.get("physical_gpu_allowlist") != [0, 1, 2, 3, 4, 5] + or schedule.get("max_concurrent_training_workers") != 4 + or schedule.get("minimum_gpu_slots_reserved_for_world_adapter") != 2 + or schedule.get("cpu_nice") != 10 + or schedule.get("io_priority") != 7 + ): + raise ValueError("1e-6/World Adapter scheduling isolation differs") + preflight = amendment.get("external_owner_preflight", {}) + if ( + preflight.get("host") != "taku-g2" + or preflight.get("matching_1e6_process_count") != 0 + or preflight.get("canonical_training_states_present") != 0 + ): + raise ValueError("external owner preflight does not permit G3 execution") + jobs = {item["condition"]: item for item in registry["conditions"]} + mappings = amendment.get("training_mappings", []) + if len(mappings) != 7 or len({item.get("condition") for item in mappings}) != 7: + raise ValueError("resume mappings must contain seven unique conditions") + state_root = Path(original_plan["training_state_root"]).resolve() + for mapping in mappings: + condition = mapping.get("condition") + job = jobs.get(condition) + role = mapping.get("role") + if ( + job is None + or role != job.get("role") + or mapping.get("logical_owner") != owners.get(role) + or mapping.get("execution_owner") != "taku3" + or mapping.get("config") != job.get("config") + or mapping.get("config_sha256") != job.get("config_sha256") + or mapping.get("initialization_checkpoint") + != job.get("initialization_checkpoint") + or mapping.get("output_dir") != job.get("output_dir") + or Path(mapping.get("state", "")).resolve() + != state_root / f"{condition.lower()}.json" + ): + raise ValueError(f"resume mapping differs: {condition}") + validate_binding( + {"path": mapping["config"], "sha256": mapping["config_sha256"]}, + f"mapped config {condition}", + ) + validate_world_adapter_terminal(amendment, require_inactive=False) + return amendment, registry + + +def queue_pids(mapping: dict[str, Any], registry: Path) -> list[int]: + return matching_pids( + "scripts.run_phase9_unified_train_queue", + f"--condition {mapping['condition']}", + str(registry.resolve()), + str(Path(mapping["state"]).resolve()), + ) + + +def training_child_pids(mapping: dict[str, Any]) -> list[int]: + return matching_pids( + "scripts.train_phase7_external", + f"--output-dir {mapping['output_dir']}", + f"--config {mapping['config']}", + ) + + +def state_status(mapping: dict[str, Any], registry_hash: str) -> str: + path = Path(mapping["state"]) + if not path.is_file(): + return "missing" + try: + value = read_json(path) + except (OSError, json.JSONDecodeError): + return "unreadable" + if ( + value.get("queue_sha256") != registry_hash + or value.get("condition") != mapping["condition"] + or value.get("official_test_used") is not False + ): + return "failed_state_binding" + return str(value.get("status", "missing")) + + +def control_requested(amendment_path: Path, amendment: dict[str, Any]) -> bool: + path = Path(amendment["control_file"]) + if not path.is_file(): + return False + value = read_json(path) + return ( + value.get("schema_version") == CONTROL_SCHEMA + and value.get("amendment_sha256") == sha256(amendment_path) + and value.get("status") == "pause_requested" + ) + + +def terminate_queues( + amendment: dict[str, Any], registry: Path, grace_seconds: float = 30.0 +) -> dict[str, Any]: + matched = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + signals = [] + for condition, pids in matched.items(): + for pid in pids: + try: + os.killpg(pid, signal.SIGTERM) + signals.append({"condition": condition, "pid": pid, "signal": "SIGTERM"}) + except ProcessLookupError: + pass + deadline = time.monotonic() + grace_seconds + while time.monotonic() < deadline: + remaining = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + if not any(remaining.values()): + return {"matched": matched, "signals": signals, "remaining": remaining} + time.sleep(0.5) + remaining = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + return {"matched": matched, "signals": signals, "remaining": remaining} + + +def launch_worker(amendment: dict[str, Any], mapping: dict[str, Any]) -> tuple[int, list[str]]: + schedule = amendment["scheduling"] + command = [ + "ionice", + "-c", + "2", + "-n", + str(schedule["io_priority"]), + "nice", + "-n", + str(schedule["cpu_nice"]), + amendment["python"], + "-m", + "scripts.run_phase9_unified_train_queue", + "--queue", + amendment["training_registry"]["path"], + "--condition", + mapping["condition"], + "--state", + mapping["state"], + "--poll-seconds", + "30", + "--allowed-physical-gpus", + ",".join(str(item) for item in schedule["physical_gpu_allowlist"]), + ] + log_path = Path(amendment["supervisor_state"]).parent / "training_logs" / ( + f"{mapping['condition'].lower()}.log" + ) + log_path.parent.mkdir(parents=True, exist_ok=True) + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, + cwd=amendment["repository"], + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + text=True, + start_new_session=True, + ) + return process.pid, command + + +def ensure_workers( + amendment: dict[str, Any], registry: dict[str, Any], state: dict[str, Any] +) -> dict[str, str]: + registry_path = Path(amendment["training_registry"]["path"]) + registry_hash = amendment["training_registry"]["sha256"] + mappings = sorted( + amendment["training_mappings"], key=lambda item: (item["priority"], item["condition"]) + ) + statuses = { + mapping["condition"]: state_status(mapping, registry_hash) + for mapping in mappings + } + terminal = { + condition: status + for condition, status in statuses.items() + if status not in RESUMABLE_STATUSES and status != "complete" + } + if terminal: + raise RuntimeError(f"terminal training state: {terminal}") + active = [] + for mapping in mappings: + pids = queue_pids(mapping, registry_path) + if len(pids) > 1: + raise RuntimeError(f"multiple queue writers: {mapping['condition']}={pids}") + if pids: + active.append(mapping["condition"]) + record = state.setdefault("workers", {}).setdefault(mapping["condition"], {}) + record["pid"] = pids[0] + record["adopted_utc"] = utc_now() + maximum = amendment["scheduling"]["max_concurrent_training_workers"] + slots = maximum - len(active) + if slots < 0: + raise RuntimeError(f"1e-6 worker cap exceeded: {len(active)} > {maximum}") + jobs = {item["condition"]: item for item in registry["conditions"]} + for mapping in mappings: + if slots <= 0 or statuses[mapping["condition"]] == "complete": + continue + if mapping["condition"] in active: + continue + children = training_child_pids(mapping) + if children: + raise RuntimeError( + f"orphan training child blocks relaunch: {mapping['condition']}={children}" + ) + job = jobs[mapping["condition"]] + if mapping["config_sha256"] != job["config_sha256"]: + raise ValueError(f"config changed before launch: {mapping['condition']}") + record = state.setdefault("workers", {}).setdefault( + mapping["condition"], {"launches": 0} + ) + launches = int(record.get("launches", 0)) + if launches >= 3: + raise RuntimeError(f"relaunch limit reached: {mapping['condition']}") + pid, command = launch_worker(amendment, mapping) + record.update( + { + "pid": pid, + "launches": launches + 1, + "launched_utc": utc_now(), + "command": command, + } + ) + active.append(mapping["condition"]) + slots -= 1 + print(f"launched {mapping['condition']} pid={pid}", flush=True) + state["active_conditions"] = active + state["reserved_gpu_slots"] = 6 - len(active) + if state["reserved_gpu_slots"] < amendment["scheduling"][ + "minimum_gpu_slots_reserved_for_world_adapter" + ]: + raise RuntimeError("World Adapter GPU reservation was violated") + return statuses + + +def validate_completion( + amendment_path: Path, amendment: dict[str, Any], registry: dict[str, Any] +) -> dict[str, Any]: + registry_hash = amendment["training_registry"]["sha256"] + jobs = {item["condition"]: item for item in registry["conditions"]} + completed = [] + for mapping in amendment["training_mappings"]: + state_path = Path(mapping["state"]) + value = read_json(state_path) + job = jobs[mapping["condition"]] + marker = value.get("last_completed", {}) + checkpoint = Path(str(marker.get("checkpoint", ""))) + if ( + value.get("status") != "complete" + or value.get("queue_sha256") != registry_hash + or value.get("condition") != mapping["condition"] + or value.get("official_test_used") is not False + or marker.get("completed_step") != 405000 + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or queue_pids(mapping, Path(amendment["training_registry"]["path"])) + or training_child_pids(mapping) + ): + raise ValueError(f"terminal training output differs: {mapping['condition']}") + completed.append( + { + "condition": mapping["condition"], + "role": mapping["role"], + "logical_owner": mapping["logical_owner"], + "execution_owner": "taku3", + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": marker["checkpoint_sha256"], + "state": str(state_path.resolve()), + "state_sha256": sha256(state_path), + } + ) + return { + "schema_version": "phase9_last2_1e6_resume_training_completion_v1", + "status": "training_complete_evaluation_not_started", + "completed_utc": utc_now(), + "amendment": {"path": str(amendment_path), "sha256": sha256(amendment_path)}, + "training_registry": amendment["training_registry"], + "conditions": completed, + "condition_count": 7, + "evaluation_started": False, + "scientific_fields_changed": [], + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def run(args: argparse.Namespace) -> None: + amendment_path = args.amendment.resolve() + amendment, registry = validate_amendment(amendment_path) + state_path = args.state.resolve() + if state_path != Path(amendment["supervisor_state"]).resolve(): + raise ValueError("supervisor state path differs from amendment") + state_path.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{state_path}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state = { + "schema_version": STATE_SCHEMA, + "status": "starting", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "amendment": str(amendment_path), + "amendment_sha256": sha256(amendment_path), + "supervisor_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if state_path.is_file(): + previous = read_json(state_path) + if previous.get("amendment_sha256") != sha256(amendment_path): + raise ValueError("existing supervisor state belongs to another amendment") + if previous.get("status") == "complete": + print(json.dumps(previous, indent=2)) + return + state = previous + state["supervisor_pid"] = os.getpid() + state["resumed_utc"] = utc_now() + while True: + validate_world_adapter_terminal(amendment, require_inactive=False) + world_adapter_pids = world_adapter_active_pids( + amendment["world_adapter_isolation"]["formal_root"] + ) + if world_adapter_pids: + termination = terminate_queues( + amendment, Path(amendment["training_registry"]["path"]) + ) + state["status"] = "paused_for_world_adapter" + state["world_adapter_active_pids"] = world_adapter_pids + state["world_adapter_pause"] = termination + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if any(termination["remaining"].values()): + raise RuntimeError( + "some queue workers survived the World Adapter priority pause" + ) + return + if control_requested(amendment_path, amendment): + termination = terminate_queues( + amendment, Path(amendment["training_registry"]["path"]) + ) + state["status"] = "paused_by_manual_request" + state["pause"] = termination + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if any(termination["remaining"].values()): + raise RuntimeError("some queue workers survived the pause request") + return + statuses = ensure_workers(amendment, registry, state) + state["training_statuses"] = statuses + state["status"] = "training" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if all(status == "complete" for status in statuses.values()): + report = validate_completion(amendment_path, amendment, registry) + report_path = Path(amendment["training_completion_report"]) + if report_path.is_file(): + raise ValueError(f"completion report already exists: {report_path}") + atomic_json(report_path, report) + os.chmod(report_path, 0o444) + state["status"] = "complete" + state["training_completion_report"] = binding(report_path) + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + print(json.dumps(state, indent=2)) + return + time.sleep(args.poll_seconds) + + +def control(args: argparse.Namespace) -> None: + amendment_path = args.amendment.resolve() + amendment, _ = validate_amendment(amendment_path) + path = Path(amendment["control_file"]) + value = { + "schema_version": CONTROL_SCHEMA, + "status": "pause_requested" if args.action == "pause" else "cleared", + "created_utc": utc_now(), + "requested_by": f"{getpass.getuser()}@{socket.gethostname()}", + "amendment": str(amendment_path), + "amendment_sha256": sha256(amendment_path), + "note": args.note, + } + atomic_json(path, value) + print(json.dumps({"path": str(path), "sha256": sha256(path)}, indent=2)) + + +def status(args: argparse.Namespace) -> None: + amendment, registry = validate_amendment(args.amendment.resolve()) + registry_hash = amendment["training_registry"]["sha256"] + statuses = { + item["condition"]: state_status(item, registry_hash) + for item in amendment["training_mappings"] + } + active = { + item["condition"]: queue_pids( + item, Path(amendment["training_registry"]["path"]) + ) + for item in amendment["training_mappings"] + } + print( + json.dumps( + { + "amendment_sha256": sha256(args.amendment), + "training_statuses": statuses, + "active_queue_pids": active, + "world_adapter_active_pids": world_adapter_active_pids( + amendment["world_adapter_isolation"]["formal_root"] + ), + "target_step": registry["target_step"], + }, + indent=2, + ) + ) + + +def parser() -> argparse.ArgumentParser: + result = argparse.ArgumentParser() + subparsers = result.add_subparsers(dest="command", required=True) + freeze_parser = subparsers.add_parser("freeze") + freeze_parser.add_argument("--original-plan", type=Path, required=True) + freeze_parser.add_argument("--original-state", type=Path, required=True) + freeze_parser.add_argument("--training-registry", type=Path, required=True) + freeze_parser.add_argument("--distributed-assignment", type=Path, required=True) + freeze_parser.add_argument("--repository", type=Path, required=True) + freeze_parser.add_argument("--python", type=Path, required=True) + freeze_parser.add_argument("--training-runner", type=Path, required=True) + freeze_parser.add_argument("--model-training-runner", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-formal-root", required=True) + freeze_parser.add_argument("--world-adapter-training-state", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-evaluation-state", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-comparison-report", type=Path, required=True) + freeze_parser.add_argument("--external-owner-checked-utc", required=True) + freeze_parser.add_argument("--external-owner-process-count", type=int, required=True) + freeze_parser.add_argument("--authorized-by", required=True) + freeze_parser.add_argument("--authorization-note", required=True) + freeze_parser.add_argument("--supervisor-state", type=Path, required=True) + freeze_parser.add_argument("--completion-report", type=Path, required=True) + freeze_parser.add_argument("--control-file", type=Path, required=True) + freeze_parser.add_argument("--output", type=Path, required=True) + freeze_parser.set_defaults(function=freeze) + run_parser = subparsers.add_parser("run") + run_parser.add_argument("--amendment", type=Path, required=True) + run_parser.add_argument("--state", type=Path, required=True) + run_parser.add_argument("--poll-seconds", type=float, default=30.0) + run_parser.set_defaults(function=run) + status_parser = subparsers.add_parser("status") + status_parser.add_argument("--amendment", type=Path, required=True) + status_parser.set_defaults(function=status) + control_parser = subparsers.add_parser("control") + control_parser.add_argument("action", choices=("pause", "resume")) + control_parser.add_argument("--amendment", type=Path, required=True) + control_parser.add_argument("--note") + control_parser.set_defaults(function=control) + return result + + +def main() -> None: + args = parser().parse_args() + if getattr(args, "poll_seconds", 30.0) < 1: + raise ValueError("poll interval must be at least one second") + args.function(args) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_cache_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..880a58c8892f00aa6bfa02fb81d2bf8683a0808c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_cache_queue.py @@ -0,0 +1,372 @@ +#!/usr/bin/env python3 +"""Run one winner-gated, resumable Phase 9 resolution cache worker.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def validate_plan_bindings(plan: dict[str, Any]) -> None: + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution execution plan lacks official-data isolation") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution plan binding differs: {path}") + validate_execution_contract(plan) + + +def validate_execution_contract(plan: dict[str, Any]) -> None: + root = Path(plan["physical_root"]) + output_directories = [Path(path) for path in plan["output_directories"]] + if len(output_directories) != len(set(output_directories)): + raise ValueError("resolution output directories are not unique") + if any(path != root and root not in path.parents for path in output_directories): + raise ValueError("resolution output directory is outside the physical root") + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("resolution physical root is not on /SSD2") + + worker_ids: set[str] = set() + owned_outputs: dict[Path, str] = {} + cache_steps: list[dict[str, Any]] = [] + for worker in plan["workers"]: + worker_id = worker["id"] + if worker_id in worker_ids: + raise ValueError(f"duplicate resolution worker: {worker_id}") + worker_ids.add(worker_id) + if Path(worker["state"]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution worker state is not on /SSD2: {worker_id}") + step_ids: set[str] = set() + for step in worker["steps"]: + if step["id"] in step_ids: + raise ValueError(f"duplicate step in resolution worker: {worker_id}") + step_ids.add(step["id"]) + if step["kind"] in {"cache", "sidecar"}: + output = Path(step["output_dir"]) + owner = owned_outputs.setdefault(output, worker_id) + if owner != worker_id: + raise ValueError(f"resolution output has multiple writers: {output}") + if step["kind"] == "cache": + cache_steps.append(step) + for command_name in ("start_command", "resume_command"): + command = step[command_name] + if command and not any( + command[index:index + 3] == ["--target-hw", "512", "896"] + for index in range(len(command) - 2) + ): + raise ValueError( + f"resolution cache command lacks 512x896 target: " + f"{worker_id}/{step['id']}/{command_name}" + ) + + cache_contracts = { + (item["manifest"], item["report"], int(item["clips"])) + for item in plan["caches"] + } + step_contracts = { + (step["manifest"], step["report"], int(step["expected_clips"])) + for step in cache_steps + } + if not cache_contracts <= step_contracts: + raise ValueError("resolution audit cache lacks a matching writer step") + + +def selection_winner(plan: dict[str, Any]) -> dict[str, Any] | None: + state_path = Path(plan["selection_state"]) + report_path = Path(plan["selection_report"]) + if not state_path.is_file() or not report_path.is_file(): + return None + state = json.loads(state_path.read_text(encoding="utf-8")) + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or state.get("winner") != report.get("winner") + or state.get("winner_checkpoint") != report.get("winner_checkpoint") + ): + return None + checkpoint = Path(report["winner_checkpoint"]["path"]) + config = Path(report["winner_config"]["path"]) + if ( + not checkpoint.is_file() + or sha256(checkpoint) != report["winner_checkpoint"]["sha256"] + or not config.is_file() + or sha256(config) != report["winner_config"]["sha256"] + ): + return None + return { + "winner": report["winner"], + "winner_checkpoint": report["winner_checkpoint"], + "winner_config": report["winner_config"], + } + + +def ensure_admission(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any] | None: + admission_path = Path(plan["admission_state"]) + admission_path.parent.mkdir(parents=True, exist_ok=True) + lock_path = Path(f"{admission_path}.lock") + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if admission_path.is_file(): + admission = json.loads(admission_path.read_text(encoding="utf-8")) + if ( + admission.get("status") != "complete" + or admission.get("plan_sha256") != sha256(plan_path) + or admission.get("official_test_used") is not False + ): + raise ValueError("resolution admission state differs") + return admission + winner = selection_winner(plan) + if winner is None: + return None + root = Path(plan["physical_root"]) + if root.exists() or any(Path(path).exists() for path in plan["output_directories"]): + raise ValueError("resolution output exists before admission") + available_gib = shutil.disk_usage(root.parent).free / (1024 ** 3) + if available_gib < float(plan["minimum_available_gib"]): + raise ValueError("SSD2 free space is below the frozen admission minimum") + admission = { + "schema_version": "phase9_resolution_admission_v1", + "status": "complete", + "admitted_utc": utc_now(), + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "scientific_stage_admitted": True, + "trigger": "frozen_full_data_640_winner_complete", + "available_gib": available_gib, + **winner, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(admission_path, admission) + return admission + + +def cache_step_complete(step: dict[str, Any], require_resume: bool) -> bool: + report_path = Path(step["report"]) + manifest_path = Path(step["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + count = report.get("cached_clips", report.get("clips")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and tuple(report.get("resolution_hw", ())) == (512, 896) + and report.get("source_manifest", {}).get("sha256") + == step["source_manifest_sha256"] + and report.get("cache_manifest", {}).get("sha256") == sha256(manifest_path) + and int(count) == int(step["expected_clips"]) + and (not require_resume or report.get("resume_invocation") is True) + ) + + +def sidecar_step_complete(step: dict[str, Any]) -> bool: + report_path = Path(step["report"]) + manifest_path = Path(step["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("base_cache_manifest", {}).get("sha256") + == sha256(step["base_manifest"]) + and report.get("augmented_cache_manifest", {}).get("sha256") + == sha256(manifest_path) + and int(report.get("clips", -1)) == int(step["expected_clips"]) + and report.get("right_valid_joint_count") == 0 + and float(report.get("root_norm_max_mm", 1.0)) < 1e-4 + and ( + not step.get("require_resume") + or report.get("resume_invocation") is True + ) + ) + + +def multifold_step_complete(step: dict[str, Any]) -> bool: + path = Path(step["index"]) + if not path.is_file(): + return False + index = json.loads(path.read_text(encoding="utf-8")) + return ( + index.get("status") == "complete" + and index.get("official_test_used") is False + and index.get("h2o_official_validation_used") is False + and index.get("source_cache_manifest", {}).get("sha256") + == sha256(step["source_manifest"]) + and len(index.get("folds", [])) == 6 + ) + + +def step_complete(step: dict[str, Any]) -> bool: + if step["kind"] == "cache": + return cache_step_complete(step, bool(step.get("require_resume"))) + if step["kind"] == "sidecar": + return sidecar_step_complete(step) + if step["kind"] == "multifold": + return multifold_step_complete(step) + raise ValueError(f"unsupported resolution step kind: {step['kind']}") + + +def runtime_command(step: dict[str, Any]) -> list[str]: + if step["kind"] == "cache": + output = Path(step["output_dir"]) + command = step["resume_command"] if output.exists() else step["start_command"] + elif step["kind"] == "sidecar": + output = Path(step["output_dir"]) + command = step["resume_command"] if output.exists() else step["start_command"] + else: + command = step["command"] + base_hash = sha256(step["base_manifest"]) if step.get("base_manifest") else None + return [base_hash if token == "{BASE_CACHE_SHA256}" else token for token in command] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan_bindings(plan) + except ValueError as error: + parser.error(str(error)) + workers = {worker["id"]: worker for worker in plan["workers"]} + if args.worker not in workers: + parser.error(f"unknown resolution worker: {args.worker}") + worker = workers[args.worker] + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("worker state path differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + state_lock = Path(f"{args.state}.lock").open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + plan_hash = sha256(args.plan) + state = { + "schema_version": "phase9_resolution_cache_worker_state_v1", + "status": "waiting_for_640_winner", + "worker": args.worker, + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "started_utc": utc_now(), + "updated_utc": utc_now(), + "completed_steps": [], + "attempts": [], + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash or previous.get("worker") != args.worker: + parser.error("existing resolution state belongs to another plan/worker") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + try: + admission = ensure_admission(args.plan, plan) + except ValueError as error: + state["status"] = "failed_admission" + state["failure"] = str(error) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + if admission is not None: + break + state["status"] = "waiting_for_640_winner" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["admission_state"] = plan["admission_state"] + state["admission_state_sha256"] = sha256(plan["admission_state"]) + state["winner"] = admission["winner"] + state["winner_checkpoint"] = admission["winner_checkpoint"] + state["winner_config"] = admission["winner_config"] + atomic_json(args.state, state) + for step in worker["steps"]: + if step["id"] in state["completed_steps"] and step_complete(step): + continue + if step.get("always_run") is not True and step_complete(step): + state["completed_steps"].append(step["id"]) + atomic_json(args.state, state) + continue + command = runtime_command(step) + log_path = args.state.parent / f"{args.worker}_{step['id']}.log" + attempt = { + "step": step["id"], "kind": step["kind"], + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_step"] = step["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ, PYTHONPATH=str(Path.cwd())) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not step_complete(step): + state["status"] = "failed_resumable" + state["failure"] = { + "step": step["id"], "returncode": result.returncode, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + if step["id"] not in state["completed_steps"]: + state["completed_steps"].append(step["id"]) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_cache_supervisor.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_cache_supervisor.py new file mode 100644 index 0000000000000000000000000000000000000000..8eddded62d805d7d1f45f69aa0d13b3d7ad675e9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_cache_supervisor.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Supervise owner-bound Stage 7 cache workers and the readiness finalizer.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def process_matches(tokens: list[str]) -> list[int]: + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (OSError, UnicodeDecodeError): + continue + if all(token in command for token in tokens): + matches.append(int(entry.name)) + return sorted(matches) + + +def read_json(path: str | Path) -> dict[str, Any] | None: + candidate = Path(path) + if not candidate.is_file(): + return None + return json.loads(candidate.read_text(encoding="utf-8")) + + +def latest_progress(path: Path) -> dict[str, Any] | None: + if not path.is_file(): + return None + with path.open("rb") as handle: + handle.seek(0, os.SEEK_END) + size = handle.tell() + handle.seek(max(0, size - 256 * 1024)) + lines = handle.read().decode("utf-8", errors="replace").splitlines() + for line in reversed(lines): + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and any( + key in value for key in ("processed", "decoded", "cached", "clips") + ): + return value + return None + + +def classify_failure(state: dict[str, Any], transient_returncodes: set[int]) -> str: + status = str(state.get("status", "missing")) + if not status.startswith("failed"): + return "not_failed" + if status != "failed_resumable": + return "terminal_failure" + returncode = state.get("failure", {}).get("returncode") + if returncode == 0: + return "terminal_contract_mismatch" + if returncode in transient_returncodes: + return "known_transient_resumable" + return "terminal_unregistered_resumable" + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("owner") != "taku3" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution supervisor plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution supervisor binding differs: {path}") + execution = plan["cache_execution_plan"] + path = Path(execution["path"]) + if not path.is_file() or sha256(path) != execution["sha256"]: + raise ValueError("resolution supervisor cache execution plan differs") + ids = [worker["id"] for worker in plan["local_workers"]] + if len(ids) != len(set(ids)) or "hot3d" in ids: + raise ValueError("resolution supervisor local ownership differs") + if Path(plan["disk"]["path"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution supervisor disk is not /SSD2") + if Path(plan["state"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution supervisor state is not /SSD2") + + +def launch(command: list[str], log_path: Path) -> int: + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ, PYTHONPATH=str(Path.cwd())), + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def local_worker_snapshot( + worker: dict[str, Any], *, plan_hash: str, now: float, + transient_returncodes: set[int], +) -> dict[str, Any]: + state_path = Path(worker["state"]) + state = read_json(state_path) + controllers = process_matches(worker["process_tokens"]) + result: dict[str, Any] = { + "id": worker["id"], "owner": "taku3", + "state": str(state_path.resolve()), "controller_pids": controllers, + } + if state is None: + result.update(status="missing", classification="missing_state") + return result + if ( + state.get("worker") != worker["id"] + or state.get("plan_sha256") != plan_hash + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + result.update(status=state.get("status"), classification="terminal_binding_mismatch") + return result + attempt = state.get("attempts", [])[-1] if state.get("attempts") else {} + log_path = Path(attempt["log"]) if attempt.get("log") else None + state_mtime = state_path.stat().st_mtime + result.update({ + "status": state.get("status"), "current_step": state.get("current_step"), + "completed_steps": state.get("completed_steps", []), + "state_sha256": sha256(state_path), + "state_heartbeat_age_seconds": round(max(0.0, now - state_mtime), 3), + "classification": classify_failure(state, transient_returncodes), + "log": str(log_path.resolve()) if log_path else None, + "log_mtime_age_seconds": ( + round(max(0.0, now - log_path.stat().st_mtime), 3) + if log_path and log_path.is_file() else None + ), + "progress": latest_progress(log_path) if log_path else None, + }) + return result + + +def remote_json(host: str, path: str, timeout: float) -> dict[str, Any] | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if completed.returncode: + return None + try: + value = json.loads(completed.stdout) + except json.JSONDecodeError: + return None + return value if isinstance(value, dict) else None + + +def external_snapshot(external: dict[str, Any]) -> dict[str, Any]: + queue = remote_json( + external["host"], external["queue_state"], external["ssh_timeout_seconds"], + ) + release = remote_json( + external["host"], external["release_state"], external["ssh_timeout_seconds"], + ) + if queue is None: + return { + "id": external["id"], "owner": external["owner"], + "status": "remote_unreachable_or_state_missing", + "classification": "external_monitor_alert", + } + status = str(queue.get("status", "missing")) + if release and release.get("status") == "complete_immutable_release": + display_status = "immutable_release_ready" + elif status == "complete": + display_status = "waiting_for_immutable_release" + else: + display_status = "waiting_for_server_new_immutable_release" + return { + "id": external["id"], "owner": external["owner"], + "status": display_status, "queue_status": status, + "queue_updated_utc": queue.get("updated_utc"), + "shard_statuses": queue.get("shard_statuses", {}), + "release_status": release.get("status") if release else "missing", + "classification": "external_owned_monitor_only", + } + + +def alarms_for( + workers: list[dict[str, Any]], *, log_stale_seconds: float, +) -> list[dict[str, Any]]: + alarms = [] + for worker in workers: + classification = worker.get("classification") + if classification and classification.startswith("terminal"): + alarms.append({"worker": worker["id"], "reason": classification}) + if ( + worker.get("status") == "running" + and not worker.get("controller_pids") + ): + alarms.append({"worker": worker["id"], "reason": "running_state_without_controller"}) + age = worker.get("log_mtime_age_seconds") + if ( + worker.get("status") == "running" and age is not None + and age > log_stale_seconds + ): + alarms.append({"worker": worker["id"], "reason": "stale_progress_log", "age_seconds": age}) + return alarms + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1 and not args.once: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("resolution supervisor state path differs") + execution_hash = plan["cache_execution_plan"]["sha256"] + transient = {int(value) for value in plan["known_transient_returncodes"]} + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + existing = read_json(args.state) or {} + recovery_attempts = dict(existing.get("recovery_attempts", {})) + while True: + now = time.time() + local = [ + local_worker_snapshot( + worker, plan_hash=execution_hash, now=now, + transient_returncodes=transient, + ) + for worker in plan["local_workers"] + ] + recoveries = [] + for worker, snapshot in zip(plan["local_workers"], local, strict=True): + restartable = ( + snapshot["classification"] == "known_transient_resumable" + or snapshot["status"] in worker.get("restartable_statuses", []) + ) + attempts = int(recovery_attempts.get(worker["id"], 0)) + if ( + restartable and not snapshot["controller_pids"] + and attempts < int(plan["max_exact_resume_attempts"]) + ): + pid = launch(worker["resume_command"], Path(worker["supervisor_log"])) + attempts += 1 + recovery_attempts[worker["id"]] = attempts + recoveries.append({ + "worker": worker["id"], "pid": pid, "attempt": attempts, + "kind": "exact_frozen_queue_resume", "launched_utc": utc_now(), + }) + external = [external_snapshot(item) for item in plan["external_workers"]] + finalizer = plan["finalizer"] + finalizer_pids = process_matches(finalizer["process_tokens"]) + readiness = read_json(finalizer["state"]) + blocking_failure = any( + str(worker.get("status", "")).startswith("failed") for worker in local + ) + finalizer_recovery = None + if ( + not finalizer_pids + and (readiness or {}).get("status") != "complete" + and not blocking_failure + ): + pid = launch(finalizer["command"], Path(finalizer["log"])) + finalizer_pids = [pid] + finalizer_recovery = { + "pid": pid, "kind": "readiness_finalizer_restart", + "launched_utc": utc_now(), + } + disk = shutil.disk_usage(plan["disk"]["path"]) + disk_record = { + "path": plan["disk"]["path"], + "free_gib": round(disk.free / (1024 ** 3), 3), + "total_gib": round(disk.total / (1024 ** 3), 3), + } + alarms = alarms_for( + local, log_stale_seconds=float(plan["log_stale_seconds"]), + ) + if disk_record["free_gib"] < float(plan["disk"]["minimum_free_gib"]): + alarms.append({"worker": "disk", "reason": "minimum_free_space_breached"}) + state = { + "schema_version": "phase9_resolution_cache_supervisor_state_v1", + "status": "alert" if alarms else "monitoring", + "updated_utc": utc_now(), "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), "local_workers": local, + "external_workers": external, + "readiness": { + "status": (readiness or {}).get("status", "missing"), + "updated_utc": (readiness or {}).get("updated_utc"), + "finalizer_pids": finalizer_pids, + "recovery": finalizer_recovery, + }, + "disk": disk_record, "alarms": alarms, + "recoveries_this_poll": recoveries, + "recovery_attempts": recovery_attempts, + "max_exact_resume_attempts": plan["max_exact_resume_attempts"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + if args.once: + print(json.dumps(state, indent=2)) + return + time.sleep(args.poll_seconds) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_evaluation_controller.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..64ea48925512f43aa2084947f82545ea83ac8f44 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_evaluation_controller.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""Supervise Stage 7 evaluation workers and freeze the resolution decision.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or plan.get("evaluation_count") != 25 + or plan.get("worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + ): + raise ValueError("resolution evaluation controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution evaluation binding differs: {path}") + + +def training_complete(plan: dict[str, Any]) -> bool: + path = Path( + plan.get("training_controller_states", {}).get( + "taku3", plan["training_controller_state"] + ) + ) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + registry = Path(state.get("training_registry", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["training_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and registry.is_file() + and state.get("training_registry_sha256") == sha256(registry) + ) + + +def pid_matches(pid: int, worker: str, evaluation_plan: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_resolution_evaluation_worker" in command + and f"--worker {worker}" in command + and str(evaluation_plan.resolve()) in command + ) + + +def worker_status(path: Path, plan_sha256: str) -> str: + if not path.is_file(): + return "missing" + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_sha256: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def hard_failure(status: str) -> bool: + return status.startswith("failed") and status != "failed_resumable" + + +def should_launch(worker: dict[str, Any], machine: str, status: str) -> bool: + return ( + worker.get("owner") == machine + and status != "complete" + and not hard_failure(status) + ) + + +def launch_worker( + evaluation_plan: Path, worker: dict[str, Any], log_path: Path, +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_evaluation_worker", + "--plan", str(evaluation_plan.resolve()), "--worker", worker["id"], + "--state", worker["state"], "--poll-seconds", "30", + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("resolution evaluation controller state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + static_plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_evaluation_controller_state_v1", + "status": "waiting_for_resolution_training", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_plan_hash, + "machine": machine, + "controller_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != static_plan_hash: + parser.error("existing evaluation controller state differs") + if state.get("machine") != machine: + parser.error("existing evaluation state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not training_complete(plan): + state["status"] = "waiting_for_resolution_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_resolution_evaluation_plan", + "--training-controller-plan", plan["training_controller_plan"], + "--training-controller-state", plan["training_controller_state"], + "--cache-plan", plan["cache_execution_plan"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_plan_hash = sha256(evaluation_plan) + dynamic = json.loads(evaluation_plan.read_text(encoding="utf-8")) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = evaluation_plan_hash + state["owned_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("workers", {}) + + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + worker_state = Path(worker["state"]) + status = worker_status(worker_state, evaluation_plan_hash) + statuses[worker["id"]] = status + if not should_launch(worker, machine, status): + continue + previous_pid = int( + state["workers"].get(worker["id"], {}).get("pid", -1) + ) + if not pid_matches(previous_pid, worker["id"], evaluation_plan): + pid = launch_worker( + evaluation_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "worker_processes": state["workers"], + } + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + decision = Path(plan["decision_report"]) + if not decision.exists(): + command = [ + sys.executable, "-m", "scripts.summarize_phase9_resolution_decision", + "--plan", str(evaluation_plan), + "--control-external-root", plan["control_external_root"], + "--control-fold-final-root", plan["control_fold_final_root"], + "--control-fold-milestone-root", plan["control_fold_milestone_root"], + "--output", str(decision), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = json.loads(decision.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != evaluation_plan_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["accepted_resolution_hw"] = report["accepted_resolution_hw"] + state["decision_report"] = { + "path": str(decision.resolve()), "sha256": sha256(decision), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_evaluation_resource_recovery.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_evaluation_resource_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..2edf205a25ace56f727b1148bf1478dc02fbc5fa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_evaluation_resource_recovery.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Rebind one unstarted logical evaluation worker to an idle allowed GPU.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.train_phase7_external import assert_physical_gpu_idle + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_amendment(path: Path, value: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + plan_path = Path(value.get("evaluation_plan", {}).get("path", "")) + controller_plan = Path(value.get("controller_plan", "")) + if ( + value.get("schema_version") != "phase9_resolution_evaluation_resource_amendment_v1" + or value.get("status") != "frozen" + or value.get("worker") != "server_new_gpu5" + or value.get("owner") != "server_new" + or value.get("planned_physical_gpu_id") != 5 + or value.get("replacement_physical_gpu_id") not in {0, 1, 2} + or value.get("evaluation_ids") + != ["loso_subject3_rgb_d_k", "lofamily_k_rgb_k"] + or value.get("requires_dynamic_idle_check") is not True + or value.get("external_process_preemption_forbidden") is not True + or value.get("scientific_fields_changed") != [] + or any(value.get(key) is not False for key in ( + "model_changed", "data_changed", "seed_changed", "metric_changed", + "selection_gate_changed", "official_test_used", + "h2o_official_validation_used", + )) + or not plan_path.is_file() + or sha256(plan_path) != value.get("evaluation_plan", {}).get("sha256") + or not controller_plan.is_file() + or sha256(controller_plan) != value.get("controller_plan_sha256") + ): + raise ValueError("resolution evaluation resource amendment differs") + plan = read_json(plan_path) + worker = next(item for item in plan["workers"] if item["id"] == value["worker"]) + if ( + worker.get("owner") != value["owner"] + or worker.get("physical_gpu_id") != value["planned_physical_gpu_id"] + or worker.get("evaluation_ids") != value["evaluation_ids"] + or worker.get("state") != value["original_state"] + or value["replacement_physical_gpu_id"] not in {0, 1, 2, 5} + or plan.get("official_test_used") is not False + ): + raise ValueError("resolution evaluation recovery worker binding differs") + if not path.is_file(): + raise ValueError("resolution evaluation resource amendment is unreadable") + return plan, worker + + +def imported_state( + recovery: dict[str, Any], amendment_path: Path, amendment: dict[str, Any], + original_plan_path: Path, +) -> dict[str, Any]: + if ( + recovery.get("status") != "complete" + or recovery.get("worker") != amendment["worker"] + or recovery.get("owner") != amendment["owner"] + or recovery.get("assigned_evaluation_ids") != amendment["evaluation_ids"] + or recovery.get("completed_ids") != amendment["evaluation_ids"] + or recovery.get("official_test_used") is not False + or recovery.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution evaluation recovery state differs") + return { + **recovery, + "schema_version": "phase9_resolution_evaluation_worker_state_v1", + "plan": str(original_plan_path.resolve()), + "plan_sha256": amendment["evaluation_plan"]["sha256"], + "physical_gpu_id": amendment["replacement_physical_gpu_id"], + "planned_physical_gpu_id": amendment["planned_physical_gpu_id"], + "resource_amendment": { + "path": str(amendment_path.resolve()), "sha256": sha256(amendment_path), + "reason": amendment["reason"], + }, + "source_recovery_state": { + "path": str(Path(amendment["recovery_state"]).resolve()), + "sha256": sha256(amendment["recovery_state"]), + }, + "imported_utc": utc_now(), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--amendment", type=Path, required=True) + args = parser.parse_args() + amendment = read_json(args.amendment) + try: + plan, worker = validate_amendment(args.amendment, amendment) + assert_physical_gpu_idle(amendment["replacement_physical_gpu_id"]) + except (ValueError, RuntimeError) as error: + parser.error(str(error)) + + original_state = Path(amendment["original_state"]) + backup = Path(amendment["original_state_backup"]) + if original_state.is_file(): + old = read_json(original_state) + if old.get("status") != "waiting_for_idle_gpu" or old.get("attempts") != []: + parser.error("logical GPU5 worker is not an unstarted waiter") + backup.parent.mkdir(parents=True, exist_ok=True) + if backup.exists() and sha256(backup) != sha256(original_state): + parser.error("logical GPU5 waiter backup differs") + if not backup.exists(): + shutil.copy2(original_state, backup) + os.chmod(backup, 0o444) + original_state.unlink() + + amended = deepcopy(plan) + amended_worker = next(item for item in amended["workers"] if item["id"] == amendment["worker"]) + amended_worker["physical_gpu_id"] = amendment["replacement_physical_gpu_id"] + amended_worker["state"] = amendment["recovery_state"] + amended["resource_schedule_amendment"] = { + "path": str(args.amendment.resolve()), "sha256": sha256(args.amendment), + } + recovery_plan = Path(amendment["recovery_plan"]) + if recovery_plan.exists() and read_json(recovery_plan) != amended: + parser.error("existing resolution evaluation recovery plan differs") + if not recovery_plan.exists(): + atomic_json(recovery_plan, amended) + os.chmod(recovery_plan, 0o444) + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_evaluation_worker", + "--plan", str(recovery_plan.resolve()), "--worker", amendment["worker"], + "--state", amendment["recovery_state"], "--poll-seconds", "30", + ] + result = subprocess.run(command, check=False) + if result.returncode: + raise SystemExit(result.returncode) + recovery = read_json(amendment["recovery_state"]) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if any(not evaluation_complete(evaluations[identifier]) for identifier in amendment["evaluation_ids"]): + raise ValueError("resolution evaluation recovery output differs") + imported = imported_state( + recovery, args.amendment, amendment, + Path(amendment["evaluation_plan"]["path"]), + ) + temporary = original_state.with_suffix(".importing") + atomic_json(temporary, imported) + os.replace(temporary, original_state) + controller_command = [ + sys.executable, "-u", "-m", "scripts.run_phase9_resolution_evaluation_controller", + "--plan", amendment["controller_plan"], "--state", amendment["controller_state"], + "--machine", "server_new", "--poll-seconds", "30", + ] + with Path(amendment["controller_log"]).open("a", encoding="utf-8") as log: + process = subprocess.Popen( + controller_command, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + print(json.dumps({ + "status": "complete", "imported_state": str(original_state.resolve()), + "imported_state_sha256": sha256(original_state), + "controller_pid": process.pid, "completed_utc": utc_now(), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_evaluation_worker.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_evaluation_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..71abe7979fd0b9d390223e80008f859de2a7200b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_evaluation_worker.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +"""Run one fixed-GPU shard of Stage 7 resolution evaluations.""" + +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time +from typing import Any, Iterator + +from scripts.phase9_distributed_assignment import ( + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +@contextmanager +def output_lock(output: Path) -> Iterator[None]: + output.parent.mkdir(parents=True, exist_ok=True) + path = output.parent / f".{output.name}.resolution-evaluation.lock" + with path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + yield + + +def evaluation_complete(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + bindings_match = ( + report.get("status") == f"evaluated_{item['evaluation_role']}" + and report.get("evaluation_role") == item["evaluation_role"] + and report.get("input_mode") == item["input_mode"] + and report.get("checkpoint", {}).get("path") == item["checkpoint"] + and report.get("checkpoint", {}).get("sha256") + == item["checkpoint_sha256"] + and report.get("config", {}).get("path") == item["config"] + and report.get("config", {}).get("sha256") == item["config_sha256"] + and report.get("cache_manifest", {}).get("path") + == item["cache_manifest"] + and report.get("cache_manifest", {}).get("sha256") + == item["cache_manifest_sha256"] + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + ) + if not bindings_match: + return False + for key in ("raw_predictions", "per_hand_rows", "take_metrics"): + artifact = report.get(key, {}) + path = Path(str(artifact.get("path", ""))) + if not path.is_file() or artifact.get("sha256") != sha256(path): + return False + return ( + isinstance(report.get("clips"), int) and report["clips"] > 0 + and isinstance(report.get("frames"), int) and report["frames"] > 0 + ) + + +def validate_inputs(items: list[dict[str, Any]]) -> None: + expected: dict[Path, str] = {} + for item in items: + for path_key, hash_key in ( + ("config", "config_sha256"), + ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256"), + ): + path = Path(item[path_key]) + digest = item[hash_key] + if path in expected and expected[path] != digest: + raise ValueError(f"evaluation input has conflicting hashes: {path}") + expected[path] = digest + for path, digest in expected.items(): + if not path.is_file() or sha256(path) != digest: + raise ValueError(f"resolution evaluation input differs: {path}") + + +def evaluation_command( + item: dict[str, Any], gpu: int, heartbeat_path: Path | None = None, + heartbeat_seconds: float = 30.0, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", item["evaluation_role"], + ] + if heartbeat_path is not None: + command.extend(( + "--evaluation-id", item["id"], + "--heartbeat-path", str(heartbeat_path.resolve()), + "--heartbeat-seconds", str(heartbeat_seconds), + )) + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def process_command(pid: int) -> str | None: + path = Path(f"/proc/{pid}/cmdline") + try: + return path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (FileNotFoundError, PermissionError, ProcessLookupError, UnicodeDecodeError): + return None + + +def evaluator_pid_matches(pid: int, item: dict[str, Any]) -> bool: + command = process_command(pid) + return bool( + command + and "scripts.evaluate_phase7_external" in command + and f"--evaluation-id {item['id']}" in command + and f"--output-dir {item['output_dir']}" in command + and f"--checkpoint {item['checkpoint']}" in command + ) + + +def process_descendants(pid: int) -> list[int]: + observed: set[int] = set() + pending = [pid] + while pending: + parent = pending.pop() + path = Path(f"/proc/{parent}/task/{parent}/children") + try: + children = [int(value) for value in path.read_text().split()] + except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError): + children = [] + for child in children: + if child not in observed: + observed.add(child) + pending.append(child) + return sorted(observed) + + +def validate_progress_heartbeat( + path: Path, item: dict[str, Any], evaluator_pid: int, +) -> dict[str, Any]: + value = json.loads(path.read_text(encoding="utf-8")) + if ( + value.get("schema_version") != "phase9_evaluation_progress_heartbeat_v1" + or value.get("evaluation_id") != item["id"] + or value.get("evaluator_pid") != evaluator_pid + or value.get("output_dir") != str(Path(item["output_dir"]).resolve()) + or value.get("official_test_used") is not False + or value.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution evaluator heartbeat differs: {item['id']}") + return value + + +def terminate_owned_process(process: subprocess.Popen[str]) -> None: + if process.poll() is not None: + return + try: + os.killpg(process.pid, 15) + except ProcessLookupError: + return + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, 9) + except ProcessLookupError: + pass + process.wait(timeout=15) + + +def run_evaluation_child( + *, command: list[str], environment: dict[str, str], log_path: Path, + heartbeat_path: Path, item: dict[str, Any], state: dict[str, Any], + state_path: Path, worker_heartbeat_seconds: float, + stall_timeout_seconds: float, +) -> tuple[int, str | None]: + started = time.monotonic() + last_progress = started + last_heartbeat_write = 0.0 + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + state["child"] = { + "pid": process.pid, "evaluation_id": item["id"], + "command": command, "started_utc": utc_now(), + } + atomic_json(state_path, state) + failure: str | None = None + try: + while process.poll() is None: + now = time.monotonic() + if not evaluator_pid_matches(process.pid, item): + failure = "evaluator_pid_or_cmdline_differs" + terminate_owned_process(process) + break + progress = None + if heartbeat_path.is_file(): + progress = validate_progress_heartbeat( + heartbeat_path, item, process.pid, + ) + age = time.time() - heartbeat_path.stat().st_mtime + last_progress = now - max(0.0, age) + if now - last_progress > stall_timeout_seconds: + failure = "evaluator_progress_stalled" + terminate_owned_process(process) + break + if now - last_heartbeat_write >= worker_heartbeat_seconds: + state["heartbeat"] = { + "updated_utc": utc_now(), "worker_pid": os.getpid(), + "evaluator_pid": process.pid, + "evaluator_cmdline_verified": True, + "descendant_pids": process_descendants(process.pid), + "log_mtime": log_path.stat().st_mtime, + "progress": progress, + "stall_timeout_seconds": stall_timeout_seconds, + } + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + last_heartbeat_write = now + time.sleep(min(5.0, worker_heartbeat_seconds)) + except Exception: + terminate_owned_process(process) + raise + returncode = process.wait() + return returncode, failure + + +def claim_when_idle(gpu: int, state: dict[str, Any], state_path: Path, poll: float) -> None: + while True: + try: + idle = assert_physical_gpu_idle(gpu) is None + except RuntimeError: + idle = False + if idle and claim_physical_gpu(gpu): + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + else: + return + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + time.sleep(poll) + + +def archive_incomplete_output( + item: dict[str, Any], state: dict[str, Any], state_path: Path, +) -> None: + output = Path(item["output_dir"]) + if not output.exists() or not any(output.iterdir()): + return + root = state_path.parent / "failed_outputs" / item["id"] + root.mkdir(parents=True, exist_ok=True) + destination = root / f"attempt_{len(state['attempts']):03d}" + if destination.exists(): + raise ValueError(f"incomplete evaluation archive already exists: {destination}") + shutil.move(str(output), str(destination)) + state.setdefault("archived_incomplete_outputs", []).append({ + "id": item["id"], "source": str(output.resolve()), + "archive": str(destination.resolve()), "archived_utc": utc_now(), + }) + atomic_json(state_path, state) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if ( + plan.get("status") != "frozen_ready" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + ): + parser.error("resolution evaluation plan is not frozen and isolated") + workers = {item["id"]: item for item in plan["workers"]} + if args.worker not in workers: + parser.error("unknown resolution evaluation worker") + worker = workers[args.worker] + try: + assignment = load_assignment(plan) + machine = detect_machine(assignment, None) + except ValueError as error: + parser.error(str(error)) + if worker.get("owner") != machine: + parser.error("evaluation worker is externally owned on this host") + if worker.get("physical_gpu_id") not in gpu_allowlist(assignment, machine): + parser.error("evaluation worker GPU is not allowed on this host") + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("resolution evaluation worker state differs from plan") + evaluations = {item["id"]: item for item in plan["evaluations"]} + items = [evaluations[identifier] for identifier in worker["evaluation_ids"]] + try: + validate_inputs(items) + except ValueError as error: + parser.error(str(error)) + + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_evaluation_worker_state_v1", + "status": "running", "worker": args.worker, + "physical_gpu_id": worker["physical_gpu_id"], + "owner": machine, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "assigned_evaluation_ids": worker["evaluation_ids"], + "completed_ids": [], "attempts": [], + "worker_pid": os.getpid(), + "started_utc": utc_now(), "updated_utc": utc_now(), + "resource_amendment": "user_authorized_idle_gpus_0_5_20260730", + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if ( + state.get("plan_sha256") != plan_hash + or state.get("worker") != args.worker + or state.get("owner") != machine + or state.get("assigned_evaluation_ids") != worker["evaluation_ids"] + ): + parser.error("existing evaluation worker state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + gpu = int(worker["physical_gpu_id"]) + for item in items: + if evaluation_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + with output_lock(Path(item["output_dir"])): + if evaluation_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + prior_attempts = sum( + attempt.get("id") == item["id"] + for attempt in state["attempts"] + ) + if prior_attempts >= plan["max_attempts_per_evaluation"]: + state["status"] = "failed_terminal_attempt_limit" + state["failure"] = { + "id": item["id"], "attempts": prior_attempts, + "reason": "maximum exact-resume attempts exhausted", + } + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + archive_incomplete_output(item, state, args.state) + claim_when_idle(gpu, state, args.state, args.poll_seconds) + heartbeat_path = Path(item["output_dir"]) / "evaluation_heartbeat.json" + command = evaluation_command( + item, gpu, heartbeat_path, + plan["evaluator_progress_heartbeat_seconds"], + ) + log_path = args.state.parent / "logs" / f"{item['id']}.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "id": item["id"], "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_evaluation"] = item["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + returncode, failure = run_evaluation_child( + command=command, environment=environment, + log_path=log_path, heartbeat_path=heartbeat_path, + item=item, state=state, state_path=args.state, + worker_heartbeat_seconds=plan["worker_heartbeat_seconds"], + stall_timeout_seconds=plan["stall_timeout_seconds"], + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = returncode + attempt["supervisor_failure"] = failure + state["updated_utc"] = utc_now() + if returncode or failure or not evaluation_complete(item): + attempt_count = sum( + value.get("id") == item["id"] + for value in state["attempts"] + ) + state["status"] = ( + "failed_terminal_attempt_limit" + if attempt_count >= plan["max_attempts_per_evaluation"] + else "failed_resumable" + ) + state["failure"] = { + "id": item["id"], "returncode": returncode, + "supervisor_failure": failure, + "attempts": attempt_count, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(returncode or 1) + state["completed_ids"].append(item["id"]) + state.pop("child", None) + state.pop("failure", None) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_training_controller.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..d6998ea02b27bfb0fc1d9a1c08cff8d426138ced --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_resolution_training_controller.py @@ -0,0 +1,268 @@ +#!/usr/bin/env python3 +"""Admit and supervise matched Phase 9 resolution training jobs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or float(plan.get("worst_domain_relative_regression_limit", -1)) != 0.01 + ): + raise ValueError("resolution training controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution training binding differs: {path}") + + +def readiness_complete(plan: dict[str, Any]) -> bool: + path = Path(plan["readiness_state"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + audit = Path(state.get("audit", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["cache_execution_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and audit.is_file() + and state.get("audit", {}).get("sha256") == sha256(audit) + ) + + +def pid_matches(pid: int, condition: str, registry: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_unified_train_queue" in command + and f"--condition {condition}" in command + and str(registry.resolve()) in command + ) + + +def condition_status(state_path: Path, registry_sha256: str) -> str: + if not state_path.is_file(): + return "missing" + state = json.loads(state_path.read_text(encoding="utf-8")) + if state.get("queue_sha256") != registry_sha256: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def hard_failure(status: str) -> bool: + return status.startswith("failed") and status != "failed_resumable" + + +def launch_worker( + condition: str, registry: Path, state_path: Path, log_path: Path, + allowed_gpus: list[int], +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry.resolve()), "--condition", condition, + "--state", str(state_path.resolve()), "--poll-seconds", "30", + "--allowed-physical-gpus", ",".join(str(gpu) for gpu in allowed_gpus), + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("resolution training controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_training_controller_state_v1", + "status": "waiting_for_cache_readiness", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "machine": machine, + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing controller state belongs to another plan") + if state.get("machine") != machine: + parser.error("existing controller state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not readiness_complete(plan): + state["status"] = "waiting_for_cache_readiness" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry = Path(plan["training_registry"]) + builder_state = Path(plan["registry_builder_state"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_resolution_training_registry", + "--selection-report", plan["selection_report"], + "--readiness-state", plan["readiness_state"], + "--cache-plan", plan["cache_execution_plan"], + "--unified-queue", plan["unified_training_queue"], + "--fold-queue", plan["fold_training_queue"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), "--state", str(builder_state), + ] + if machine == "taku3": + state["status"] = "building_registry" + state["builder_command"] = builder_command + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_registry_builder" + state["builder_returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry_sha256 = sha256(registry) + registry_payload = json.loads(registry.read_text(encoding="utf-8")) + conditions = [item["condition"] for item in registry_payload["conditions"]] + owners = condition_owners(registry_payload, assignment) + if ( + len(conditions) != 7 + or len(set(conditions)) != 7 + or registry_payload.get("gate", {}).get( + "worst_domain_relative_regression_limit" + ) != plan["worst_domain_relative_regression_limit"] + or registry_payload.get("official_test_used") is not False + ): + state["status"] = "failed_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_sha256 + state["conditions"] = conditions + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("workers", {}) + + state_root = Path(plan["training_state_root"]) + log_root = Path(plan["training_log_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_sha256) + statuses[condition] = status + if hard_failure(status): + continue + if status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["workers"].get(condition, {}).get("pid", -1) + ) + if not pid_matches(previous_pid, condition, registry): + pid = launch_worker( + condition, registry, condition_state, + log_root / f"{condition.lower()}.log", + allowed_gpus, + ) + state["workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["condition_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + state["status"] = "complete" if machine == "taku3" else "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_selection_binding_recovery.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..1de788859399ebc11c495022e81815866e615f7d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_selection_binding_recovery.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python3 +"""Run one disjoint Phase 9 selection-binding recovery worker.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import socket +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def json_sha256(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def validate_input(path: str, expected_sha256: str, label: str) -> None: + candidate = Path(path) + if not candidate.is_file() or sha256(candidate) != expected_sha256: + raise ValueError(f"selection recovery {label} differs: {candidate}") + + +def validate_recovered_output(item: dict[str, Any]) -> dict[str, Any]: + output = Path(item["output_dir"]) + report_path = output / "evaluation.json" + if not report_path.is_file(): + raise ValueError(f"selection recovery report missing: {item['id']}") + report = json.loads(report_path.read_text(encoding="utf-8")) + expected_bindings = { + "config": (item["config"], item["config_sha256"]), + "checkpoint": (item["checkpoint"], item["checkpoint_sha256"]), + "cache_manifest": ( + item["cache_manifest"], item["cache_manifest_sha256"], + ), + } + for key, (path, digest) in expected_bindings.items(): + binding = report.get(key, {}) + if ( + Path(str(binding.get("path", ""))).resolve() != Path(path).resolve() + or binding.get("sha256") != digest + ): + raise ValueError( + f"selection recovery {key} binding differs: {item['id']}" + ) + if ( + report.get("status") != "evaluated_phase9_h2o_fold_heldout" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or { + key: report.get(key) + for key in ("clips", "frames", "hands_rows") + } != item["expected_sample_counts"] + ): + raise ValueError(f"selection recovery role/sample contract differs: {item['id']}") + expected = item["expected_determinism"] + artifacts = { + "raw_predictions": expected["raw_predictions_sha256"], + "per_hand_rows": expected["per_hand_rows_sha256"], + "take_metrics": expected["take_metrics_sha256"], + } + for key, expected_hash in artifacts.items(): + binding = report.get(key, {}) + path = Path(str(binding.get("path", ""))) + if ( + binding.get("sha256") != expected_hash + or not path.is_file() + or sha256(path) != expected_hash + ): + raise ValueError( + f"selection recovery deterministic artifact differs: " + f"{item['id']}:{key}" + ) + if ( + json_sha256(report.get("metrics")) != expected["metrics_sha256"] + or json_sha256(report.get("grouped_bootstrap_ci")) + != expected["grouped_bootstrap_ci_sha256"] + ): + raise ValueError(f"selection recovery deterministic metrics differ: {item['id']}") + return { + "report": str(report_path.resolve()), + "report_sha256": sha256(report_path), + "sample_counts": item["expected_sample_counts"], + "metrics_sha256": expected["metrics_sha256"], + "raw_predictions_sha256": expected["raw_predictions_sha256"], + } + + +def archive_incomplete_output(item: dict[str, Any]) -> str | None: + output = Path(item["output_dir"]) + if not output.exists() or not any(output.iterdir()): + return None + root = output.parents[3] / "incomplete_outputs" + root.mkdir(parents=True, exist_ok=True) + suffix = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") + destination = root / f"{item['id']}.{suffix}" + shutil.move(str(output), str(destination)) + return str(destination.resolve()) + + +def evaluation_command(item: dict[str, Any], gpu: int, bootstrap: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], + "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(bootstrap), + "--evaluation-role", item["evaluation_role"], + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--owner", choices=("taku3", "server_new"), required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + assignment_path = Path(plan["distributed_assignment"]["path"]) + if ( + plan.get("official_test_used") is not False + or not assignment_path.is_file() + or sha256(assignment_path) != plan["distributed_assignment"]["sha256"] + ): + parser.error("selection recovery plan/assignment binding differs") + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + parser.error(f"selection recovery code binding differs: {path}") + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + if socket.gethostname() != assignment["machines"][args.owner]["hostname"]: + parser.error("selection recovery owner does not match this host") + matches = [item for item in plan["workers"] if item["id"] == args.worker] + if len(matches) != 1 or matches[0]["owner"] != args.owner: + parser.error("selection recovery worker owner differs") + worker = matches[0] + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("selection recovery worker state differs") + gpu = int(worker["physical_gpu_id"]) + if gpu not in assignment["machines"][args.owner]["physical_gpu_allowlist"]: + parser.error("selection recovery GPU is not allowed on this host") + evaluations = {item["id"]: item for item in plan["evaluations"]} + assigned = [evaluations[identifier] for identifier in worker["evaluation_ids"]] + if any( + item["owner"] != args.owner or item["physical_gpu_id"] != gpu + for item in assigned + ): + parser.error("selection recovery evaluation assignment differs") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_selection_binding_recovery_worker_state_v1", + "status": "waiting_for_gpu", "owner": args.owner, + "worker": args.worker, "physical_gpu_id": gpu, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "assigned_evaluation_ids": worker["evaluation_ids"], + "completed_ids": [], "attempts": [], + "started_utc": utc_now(), "updated_utc": utc_now(), + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if ( + previous.get("plan_sha256") != plan_hash + or previous.get("owner") != args.owner + or previous.get("worker") != args.worker + or previous.get("assigned_evaluation_ids") + != worker["evaluation_ids"] + ): + parser.error("existing selection recovery state differs") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for item in assigned: + for key in ("config", "checkpoint", "cache_manifest"): + validate_input(item[key], item[f"{key}_sha256"], key) + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError): + evidence = None + if evidence is not None: + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + continue + output = Path(item["output_dir"]) + lock_path = output.parent / f".{output.name}.selection-recovery.lock" + output.parent.mkdir(parents=True, exist_ok=True) + with lock_path.open("a+", encoding="utf-8") as output_lock: + fcntl.flock(output_lock.fileno(), fcntl.LOCK_EX) + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError): + evidence = None + if evidence is not None: + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + atomic_json(args.state, state) + continue + archived = archive_incomplete_output(item) + while True: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + state["status"] = "waiting_for_gpu" + state["waiting_for"] = item["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + if claim_physical_gpu(gpu): + break + state["status"] = "waiting_for_gpu_claim" + state["waiting_for"] = item["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = evaluation_command( + item, gpu, int(plan["bootstrap_resamples"]) + ) + attempt = { + "evaluation_id": item["id"], "start_utc": utc_now(), + "command": command, + } + if archived is not None: + attempt["archived_incomplete_output"] = archived + state["status"] = "running" + state["current_evaluation"] = item["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + env = dict(os.environ) + env["CUDA_VISIBLE_DEVICES"] = str(gpu) + env["PYTHONUNBUFFERED"] = "1" + try: + result = subprocess.run( + command, cwd=Path.cwd(), env=env, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError) as error: + state["status"] = "failed_resumable" + state["failure"] = f"{type(error).__name__}: {error}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + if result.returncode: + state["status"] = "failed_resumable" + state["failure"] = f"evaluator exited {result.returncode}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + state.pop("failure", None) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if set(state["completed_ids"]) != set(worker["evaluation_ids"]): + state["status"] = "failed_state_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state.pop("waiting_for", None) + state.pop("current_evaluation", None) + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_selection_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_selection_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6bcd0a5ebe87d4b4d325dff8080e1954ad4aaa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_selection_queue.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Wait for complete Phase 9 evidence and freeze unified candidate selection.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def evidence_complete(plan: dict[str, Any]) -> bool: + for item in plan["required_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def selection_complete(plan: dict[str, Any]) -> bool: + output = Path(plan["output_json"]) + if not output.is_file(): + return False + report = json.loads(output.read_text(encoding="utf-8")) + checkpoint = Path(report.get("winner_checkpoint", {}).get("path", "")) + config = Path(report.get("winner_config", {}).get("path", "")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + and checkpoint.is_file() + and report.get("winner_checkpoint", {}).get("sha256") == sha256(checkpoint) + and config.is_file() + and report.get("winner_config", {}).get("sha256") == sha256(config) + and Path(plan["output_csv"]).is_file() + ) + + +def archive_incomplete_outputs(plan: dict[str, Any], state_path: Path) -> list[str]: + outputs = [Path(plan["output_json"]), Path(plan["output_csv"])] + temporary_outputs = [ + path.with_suffix(path.suffix + ".tmp") for path in outputs + ] + existing = [path for path in outputs + temporary_outputs if path.exists()] + if not existing: + return [] + root = state_path.parent / "selection_incomplete_outputs" + root.mkdir(parents=True, exist_ok=True) + archived = [] + for path in existing: + destination = root / f"{path.name}.{len(list(root.iterdir())):03d}" + shutil.move(str(path), str(destination)) + archived.append(str(destination.resolve())) + return archived + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("selection plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state_lock = Path(f"{args.state}.lock").open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state = { + "schema_version": "phase9_selection_state_v1", + "status": "waiting_for_evidence", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "updated_utc": utc_now(), "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing selection state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not evidence_complete(plan): + state["status"] = "waiting_for_evidence" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + if not selection_complete(plan): + archived = archive_incomplete_outputs(plan, args.state) + if archived: + state.setdefault("archived_incomplete_outputs", []).extend(archived) + atomic_json(args.state, state) + command = [ + sys.executable, "-m", "scripts.summarize_phase9_unified_selection", + "--external-root", plan["external_root"], + "--fold-final-root", plan["fold_final_root"], + "--fold-milestone-root", plan["fold_milestone_root"], + "--multifold-index", plan["multifold_index"], + "--output-json", plan["output_json"], + "--output-csv", plan["output_csv"], + ] + log_path = args.state.parent / "unified_selection.log" + state["status"] = "running" + state["attempt"] = { + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + state["attempt"]["end_utc"] = utc_now() + state["attempt"]["returncode"] = result.returncode + if result.returncode or not selection_complete(plan): + state["status"] = "failed" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + report = json.loads(Path(plan["output_json"]).read_text(encoding="utf-8")) + state["status"] = "complete" + state["winner"] = report["winner"] + state["winner_checkpoint"] = report["winner_checkpoint"] + state["winner_config"] = report["winner_config"] + state["required_states"] = [ + { + "id": item["id"], "path": str(Path(item["path"]).resolve()), + "sha256": sha256(item["path"]), + } + for item in plan["required_states"] + ] + state["h2o_official_validation_used"] = False + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_shared_augmentation_evaluation_controller.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_shared_augmentation_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..1f0c887433e7319788e98fec0e732a102fc70c38 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_shared_augmentation_evaluation_controller.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""Supervise Stage 8 evaluations and freeze augmentation/Stage 9 gates.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_resolution_evaluation_controller import ( + hard_failure, + launch_worker, + pid_matches, + should_launch, + worker_status, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("evaluation_count") != 25 + or plan.get("worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + ): + raise ValueError("shared augmentation evaluation plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"shared augmentation evaluation binding differs: {path}") + + +def training_complete(plan: dict[str, Any]) -> bool: + path = Path( + plan.get("training_controller_states", {}).get( + "taku3", plan["training_controller_state"] + ) + ) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + registry = Path(state.get("training_registry", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["training_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and registry.is_file() + and state.get("training_registry_sha256") == sha256(registry) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("shared augmentation evaluation state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + static_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_shared_augmentation_evaluation_controller_state_v1", + "status": "waiting_for_augmentation_training", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "machine": machine, + "controller_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != static_hash: + parser.error("existing augmentation evaluation state differs") + if state.get("machine") != machine: + parser.error("existing augmentation evaluation machine differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not training_complete(plan): + state["status"] = "waiting_for_augmentation_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + builder_command = [ + sys.executable, "-m", + "scripts.build_phase9_shared_augmentation_evaluation_plan", + "--training-controller-plan", plan["training_controller_plan"], + "--training-controller-state", plan["training_controller_state"], + "--resolution-cache-plan", plan["resolution_cache_plan"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + dynamic_hash = sha256(evaluation_plan) + dynamic = json.loads(evaluation_plan.read_text(encoding="utf-8")) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = dynamic_hash + state["owned_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("workers", {}) + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + path = Path(worker["state"]) + status = worker_status(path, dynamic_hash) + statuses[worker["id"]] = status + if not should_launch(worker, machine, status): + continue + previous_pid = int( + state["workers"].get(worker["id"], {}).get("pid", -1) + ) + if not pid_matches(previous_pid, worker["id"], evaluation_plan): + pid = launch_worker( + evaluation_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "worker_processes": state["workers"], + } + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + decision = Path(plan["decision_report"]) + if not decision.exists(): + command = [ + sys.executable, "-m", + "scripts.summarize_phase9_shared_augmentation_decision", + "--plan", str(evaluation_plan), "--output", str(decision), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = json.loads(decision.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != dynamic_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["stage9_last2_admitted"] = report[ + "stage9_preceding_mechanism_gate" + ]["stage9_last2_admitted"] + state["decision_report"] = { + "path": str(decision.resolve()), "sha256": sha256(decision), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_shared_augmentation_training_controller.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_shared_augmentation_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..191670dce11e49ef1c417651529cdb49bca1cec2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_shared_augmentation_training_controller.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Supervise Stage 8 shared-augmentation training after resolution freeze.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_resolution_training_controller import ( + condition_status, + hard_failure, + pid_matches, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or plan.get("job_count") != 7 + or float(plan.get("worst_domain_relative_regression_limit", -1)) != 0.01 + ): + raise ValueError("shared augmentation training plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"shared augmentation binding differs: {path}") + + +def resolution_decision_complete(plan: dict[str, Any]) -> bool: + state_path = Path(plan["resolution_controller_state"]) + if not state_path.is_file(): + return False + state = json.loads(state_path.read_text(encoding="utf-8")) + report = Path(state.get("decision_report", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["resolution_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and report.is_file() + and state.get("decision_report", {}).get("sha256") == sha256(report) + ) + + +def launch_worker( + condition: str, registry: Path, state_path: Path, log_path: Path, + allowed_gpus: list[int], +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry.resolve()), "--condition", condition, + "--state", str(state_path.resolve()), "--poll-seconds", "30", + "--allowed-physical-gpus", ",".join(str(gpu) for gpu in allowed_gpus), + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("shared augmentation controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_shared_augmentation_training_controller_state_v1", + "status": "waiting_for_resolution_decision", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "machine": machine, + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing shared augmentation controller state differs") + if state.get("machine") != machine: + parser.error("existing shared augmentation state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not resolution_decision_complete(plan): + state["status"] = "waiting_for_resolution_decision" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry = Path(plan["training_registry"]) + builder_command = [ + sys.executable, "-m", + "scripts.build_phase9_shared_augmentation_training_registry", + "--resolution-controller-plan", plan["resolution_controller_plan"], + "--resolution-controller-state", plan["resolution_controller_state"], + "--augmentation-plan", plan["shared_augmentation_plan"], + "--unified-queue", plan["unified_training_queue"], + "--fold-queue", plan["fold_training_queue"], + "--selection-report", plan["selection_report"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), + "--state", plan["registry_builder_state"], + ] + if machine == "taku3": + state["status"] = "building_registry" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_registry_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + registry_hash = sha256(registry) + payload = json.loads(registry.read_text(encoding="utf-8")) + conditions = [item["condition"] for item in payload["conditions"]] + owners = condition_owners(payload, assignment) + if ( + len(conditions) != plan["job_count"] + or len(set(conditions)) != plan["job_count"] + or payload.get("shared_augmentation_plan", {}).get("sha256") + != plan["shared_augmentation_plan_sha256"] + or payload.get("gate", {}).get("worst_domain_relative_regression_limit") + != plan["worst_domain_relative_regression_limit"] + or payload.get("official_test_used") is not False + ): + state["status"] = "failed_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_hash + state["resolution_hw"] = payload["resolution_hw"] + state["conditions"] = conditions + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("workers", {}) + + state_root = Path(plan["training_state_root"]) + log_root = Path(plan["training_log_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_hash) + statuses[condition] = status + if hard_failure(status) or status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["workers"].get(condition, {}).get("pid", -1) + ) + if not pid_matches(previous_pid, condition, registry): + pid = launch_worker( + condition, registry, condition_state, + log_root / f"{condition.lower()}.log", + allowed_gpus, + ) + state["workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["condition_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + state["status"] = "complete" if machine == "taku3" else "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_unified_train_queue.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_unified_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f904f748a1ecc505a0efe794951a67ddb4acb67b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_phase9_unified_train_queue.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python3 +"""Run one hash-bound Phase 9 unified mixture through smoke, health, and scale.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any +import re + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def parse_physical_gpu_ids(value: str) -> tuple[int, ...]: + try: + gpu_ids = tuple(int(item.strip()) for item in value.split(",") if item.strip()) + except ValueError as error: + raise argparse.ArgumentTypeError("GPU IDs must be comma-separated integers") from error + if not gpu_ids or len(set(gpu_ids)) != len(gpu_ids): + raise argparse.ArgumentTypeError("GPU IDs must be nonempty and unique") + if any(gpu < 0 or gpu > 5 for gpu in gpu_ids): + raise argparse.ArgumentTypeError("physical GPU IDs must be between 0 and 5") + return gpu_ids + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def attempt_gpu_hours(attempts: list[dict[str, Any]]) -> float: + seconds = 0.0 + for attempt in attempts: + if not attempt.get("start_utc") or not attempt.get("end_utc"): + continue + start = datetime.fromisoformat(attempt["start_utc"]) + end = datetime.fromisoformat(attempt["end_utc"]) + seconds += max(0.0, (end - start).total_seconds()) + return seconds / 3600.0 + + +def state_lock_path(state_path: Path) -> Path: + return Path(f"{state_path}.lock") + + +def readiness_complete(queue: dict[str, Any]) -> bool: + state_path = Path(queue["data_readiness_state"]) + if not state_path.is_file(): + return False + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or state.get("plan_sha256") != queue["data_finalize_plan_sha256"] + or ( + queue.get("data_readiness_state_sha256") is not None + and queue["data_readiness_state_sha256"] != sha256(state_path) + ) + ): + return False + for artifact in state.get("artifacts", []): + manifest = Path(artifact["manifest"]) + if not manifest.is_file() or sha256(manifest) != artifact["manifest_sha256"]: + return False + for artifact in queue.get("data_artifacts", []): + path = Path(artifact["path"]) + if not path.is_file() or sha256(path) != artifact["sha256"]: + return False + return True + + +def prerequisite_states_complete(registry: dict[str, Any]) -> bool: + for item in registry.get("prerequisite_states", []): + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def prerequisite_gate_satisfied( + registry: dict[str, Any], start_before_prerequisites: bool, +) -> bool: + return start_before_prerequisites or prerequisite_states_complete(registry) + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def marker_path(queue: dict[str, Any], stage: dict[str, Any]) -> Path: + return Path(queue["output_dir"]) / ".phase9_queue" / f"{stage['id']}.json" + + +def stage_complete(queue: dict[str, Any], stage: dict[str, Any]) -> bool: + path = marker_path(queue, stage) + if not path.is_file(): + return False + marker = json.loads(path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and marker.get("config_sha256") == queue["config_sha256"] + and int(marker.get("completed_step", -1)) == int(stage["stop_after_step"]) + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command( + queue: dict[str, Any], stage: dict[str, Any], gpu: int, + previous_checkpoint: Path | None, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", queue["config"], + "--output-dir", queue["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(stage["stop_after_step"]), + ] + if previous_checkpoint is None: + command.extend(("--init-checkpoint", queue["initialization_checkpoint"])) + else: + command.extend(("--resume", str(previous_checkpoint))) + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def latest_resumable_checkpoint( + queue: dict[str, Any], stage: dict[str, Any], previous_checkpoint: Path | None, +) -> Path | None: + target = int(stage["stop_after_step"]) + previous_step = -1 + if previous_checkpoint is not None: + match = re.search(r"step_(\d+)", previous_checkpoint.name) + previous_step = int(match.group(1)) if match else -1 + candidates = [] + for path in Path(queue["output_dir"]).glob("step_*.pt"): + match = re.fullmatch(r"step_(\d+)(?:_final)?\.pt", path.name) + if match is None: + continue + step = int(match.group(1)) + if previous_step < step < target and path.is_file(): + candidates.append((step, path)) + return max(candidates, default=(previous_step, previous_checkpoint))[1] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--condition", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--start-before-prerequisites", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + registry = json.loads(args.queue.read_text(encoding="utf-8")) + conditions = {item["condition"]: item for item in registry["conditions"]} + if args.condition not in conditions: + parser.error(f"condition not registered: {args.condition}") + queue = conditions[args.condition] + if registry.get("official_test_used") is not False: + parser.error("queue must explicitly exclude official test") + config = Path(queue["config"]) + initialization = Path(queue["initialization_checkpoint"]) + if not config.is_file() or sha256(config) != queue["config_sha256"]: + parser.error("frozen config is missing or has changed") + if not initialization.is_file() or sha256(initialization) != queue["initialization_checkpoint_sha256"]: + parser.error("frozen initialization checkpoint is missing or has changed") + args.state.parent.mkdir(parents=True, exist_ok=True) + lock_path = state_lock_path(args.state) + state_lock = lock_path.open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + registry_hash = sha256(args.queue) + state = { + "schema_version": "phase9_unified_train_state_v1", + "status": "waiting_for_data", + "condition": args.condition, + "queue": str(args.queue.resolve()), "queue_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "attempts": [], "completed_stages": [], + "allowed_physical_gpus": list(args.allowed_physical_gpus), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue_sha256") != registry_hash: + parser.error("existing state is bound to another queue version") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for attempt in state.get("attempts", []): + if attempt.get("start_utc") and not attempt.get("end_utc"): + attempt["end_utc"] = utc_now() + attempt["returncode"] = None + attempt["interrupted_before_queue_restart"] = True + previous_gpus = tuple(state.get("allowed_physical_gpus", ALLOWED_GPUS)) + if state.get("attempts") and previous_gpus != args.allowed_physical_gpus: + parser.error("cannot change allowed GPUs after this queue has attempted work") + previous_early_start = bool(state.get("start_before_prerequisites", False)) + if state.get("attempts") and previous_early_start != args.start_before_prerequisites: + parser.error("cannot change prerequisite scheduling after attempted work") + state["allowed_physical_gpus"] = list(args.allowed_physical_gpus) + state["start_before_prerequisites"] = bool(args.start_before_prerequisites) + if args.start_before_prerequisites: + state["resource_amendment"] = "user_authorized_all_idle_gpus_20260727" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + while not readiness_complete({**registry, **queue}): + state["status"] = "waiting_for_data" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + while not prerequisite_gate_satisfied(registry, args.start_before_prerequisites): + state["status"] = "waiting_for_prerequisites" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + previous_checkpoint: Path | None = None + for stage in queue["stages"]: + if stage_complete(queue, stage): + previous_checkpoint = Path( + json.loads(marker_path(queue, stage).read_text(encoding="utf-8"))["checkpoint"] + ) + if stage["id"] not in state["completed_stages"]: + state["completed_stages"].append(stage["id"]) + continue + previous_checkpoint = latest_resumable_checkpoint( + queue, stage, previous_checkpoint, + ) + while True: + gpu = idle_gpu(args.allowed_physical_gpus) + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + break + command = training_command(queue, stage, gpu, previous_checkpoint) + log_path = Path(queue["log_dir"]) / f"{stage['id']}.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "stage": stage["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_stage"] = stage["id"] + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode: + periodic = sorted(Path(queue["output_dir"]).glob("step_*.pt")) + latest = periodic[-1] if periodic else None + state["status"] = "failed_resumable" if periodic else "failed" + state["failure"] = { + "stage": stage["id"], "returncode": result.returncode, + "latest_checkpoint": str(latest.resolve()) if latest else None, + "latest_checkpoint_sha256": sha256(latest) if latest else None, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode) + checkpoint = Path(queue["output_dir"]) / f"step_{int(stage['stop_after_step']):07d}_final.pt" + summary = json.loads((Path(queue["output_dir"]) / "summary.json").read_text(encoding="utf-8")) + marker = { + "status": "complete", "condition": args.condition, + "stage": stage["id"], "completed_utc": utc_now(), + "completed_step": int(stage["stop_after_step"]), + "physical_gpu_id": gpu, "config": str(config.resolve()), + "config_sha256": queue["config_sha256"], + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": sha256(checkpoint), + "source_manifest_sha256": summary["source_manifest_sha256"], + "source_exposure_batches": summary["source_exposure_batches"], + "wall_seconds": summary["wall_seconds"], + "gpu_hours": summary["gpu_hours"], + "frames_per_second": summary["frames_per_second"], + "peak_vram_gib": summary["peak_vram_gib"], + "official_test_used": False, + } + path = marker_path(queue, stage) + path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(path, marker) + previous_checkpoint = checkpoint + state["completed_stages"].append(stage["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + + state["status"] = "complete" + state["gpu_hours_consumed"] = attempt_gpu_hours(state["attempts"]) + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_qort_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_qort_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..9c50b6afa211f8c32cd790f2fc21f36ea2055aa0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_qort_h2o.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Run the official QORT-Former H2O checkpoint on the common cam4 validation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +import torch +import torchvision.transforms as transforms +from PIL import Image + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + repo = args.repo.resolve() + sys.path.insert(0, str(repo)) + from lib.qort_former import QORT_Former + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys = keys[: args.max_frames] + takes = takes[: args.max_frames] + frame_ids = frame_ids[: args.max_frames] + count = len(keys) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = QORT_Former(num_classes=11).to(device).eval() + model.load_state_dict(checkpoint, strict=True) + transform = transforms.Compose([ + transforms.Resize((540, 960)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + + # QORT's released inference denormalizes u/v by the raw image size and z by + # 1000 mm. H2O K then deterministically maps released (u,v,z) to camera XYZ. + from foundation_hand.evaluation.sota import GroundTruthBundle + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + detected = np.ones((count, 2), dtype=bool) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for start in range(0, count, args.batch_size): + end = min(start + args.batch_size, count) + images = [] + image_sizes = [] + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True): + path = args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png" + with Image.open(path) as image: + rgb = image.convert("RGB") + image_sizes.append(rgb.size) + images.append(transform(rgb)) + batch = torch.stack(images).to(device) + with torch.no_grad(): + outputs = model(batch) + logits = outputs["pred_logits"] + predictions = outputs["pred_keypoints"] + batch_indices = torch.arange(end - start, device=device) + left_index = logits[:, :, 9].argmax(dim=1) + right_index = logits[:, :, 10].argmax(dim=1) + left = predictions[0, batch_indices, left_index].reshape(-1, 21, 3) + right = predictions[1, batch_indices, right_index].reshape(-1, 21, 3) + uvz = torch.stack((left, right), dim=1).float().cpu().numpy() + scores = torch.stack(( + logits[batch_indices, left_index, 9].sigmoid(), + logits[batch_indices, right_index, 10].sigmoid(), + ), dim=1).float().cpu().numpy() + confidence[start:end] = scores + for local_index, (width, height) in enumerate(image_sizes): + uvz[local_index, ..., 0] *= width + uvz[local_index, ..., 1] *= height + z = uvz[local_index, ..., 2] + K = intrinsics[start + local_index] + joints[start + local_index, ..., 0] = (uvz[local_index, ..., 0] - K[0, 2]) / K[0, 0] * z + joints[start + local_index, ..., 1] = (uvz[local_index, ..., 1] - K[1, 2]) / K[1, 1] * z + joints[start + local_index, ..., 2] = z + if end % 100 == 0 or end == count: + print(f"QORT-Former {end}/{count}", flush=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output.resolve() + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "QORT-Former", + "scope": "RGB decode + resize/normalize + model forward + camera conversion", + "frames": count, + "processing_seconds": processing_seconds, + "frames_per_second": count / processing_seconds, + "batch_size": args.batch_size, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(repo), "rev-parse", "HEAD"], text=True + ).strip() + parameter_count = sum(parameter.numel() for parameter in model.parameters()) + bundle = PredictionBundle( + model_name="QORT-Former", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + detected=detected, + confidence=confidence, + vertices_camera_m=None, + metadata={ + "official_repository": "https://github.com/kcsayem/QORT-Former", + "repository_commit": commit, + "checkpoint": str(args.checkpoint.resolve()), + "checkpoint_sha256": sha256(args.checkpoint), + "parameter_count": parameter_count, + "input": "full RGB, resized to 960x540", + "temporal": False, + "detector": False, + "output_conversion": "official normalized u,v,z; raw H2O K unprojection", + "original_paper_metric": "mean endpoint error over 21 joints", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_wildhands_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_wildhands_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e77900e883aa37cc0b9aee3c5e030263be10f9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_wildhands_h2o.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Run the released WildHands checkpoint on H2O with a common hand detector.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import types +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, load_frame_index +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix + + +MANO_TO_OPENPOSE = np.asarray( + [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20], + dtype=np.int64, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-dir", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=1.75) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def install_pytorch3d_rotation_compatibility() -> None: + """Provide the three pure-PyTorch transforms used by the official model.""" + + rotation_conversions = types.ModuleType("pytorch3d.transforms.rotation_conversions") + rotation_conversions.axis_angle_to_matrix = axis_angle_to_matrix + rotation_conversions.rotation_6d_to_matrix = rotation_6d_to_matrix + rotation_conversions.matrix_to_rotation_6d = ( + lambda matrix: matrix[..., :2, :].clone().reshape(matrix.shape[:-2] + (6,)) + ) + transforms = types.ModuleType("pytorch3d.transforms") + transforms.rotation_conversions = rotation_conversions + pytorch3d = types.ModuleType("pytorch3d") + pytorch3d.transforms = transforms + sys.modules.update({ + "pytorch3d": pytorch3d, + "pytorch3d.transforms": transforms, + "pytorch3d.transforms.rotation_conversions": rotation_conversions, + }) + + +def recursive_to(value: Any, device: torch.device) -> Any: + if torch.is_tensor(value): + return value.to(device) + if isinstance(value, dict): + return {name: recursive_to(item, device) for name, item in value.items()} + if isinstance(value, tuple): + return tuple(recursive_to(item, device) for item in value) + if isinstance(value, list): + return [recursive_to(item, device) for item in value] + return value + + +def main() -> None: + args = parse_args() + for name in ("repo", "checkpoint", "detector", "mano_dir", "root", "manifest", "ground_truth", "output"): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + + os.environ["WILDHANDS_MANO_DIR"] = str(args.mano_dir) + sys.path.insert(0, str(args.repo)) + enable_legacy_mano_loading() + install_pytorch3d_rotation_compatibility() + os.chdir(args.repo) + + from ultralytics import YOLO + from wildhands.configs.parser import construct_args + from wildhands.datasets.dataset import WildHandsDataset + from wildhands.models.wrapper import WildHandsWrapper + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + config = construct_args() + model = WildHandsWrapper(config) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + ignored = ("head_o", "arti_head", "grasp_classifier") + state = { + name: value + for name, value in checkpoint["state_dict"].items() + if not any(token in name for token in ignored) + } + model.load_state_dict(state) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, Any]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = recursive_to(default_collate([record[3] for record in records]), device) + with torch.no_grad(): + output = model(batch) + right_joints = output["pred.j3d.cam.r"].float().cpu().numpy() + left_joints = output["pred.j3d.cam.l"].float().cpu().numpy() + right_vertices = output["pred.v3d.cam.r"].float().cpu().numpy() + left_vertices = output["pred.v3d.cam.l"].float().cpu().numpy() + for local, (frame_index, side, score, _) in enumerate(records): + batch_joints = right_joints[local] if side else left_joints[local] + batch_vertices = right_vertices[local] if side else left_vertices[local] + joints[frame_index, side] = batch_joints[MANO_TO_OPENPOSE] + vertices[frame_index, side] = batch_vertices + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images_bgr = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images_bgr): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images_bgr, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + rgb = cv2.cvtColor(images_bgr[local], cv2.COLOR_BGR2RGB) + intrinsic = intrinsics[frame_index] + focal = float(0.5 * (intrinsic[0, 0] + intrinsic[1, 1])) + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + dataset = WildHandsDataset( + config, + rgb, + boxes[[choice]], + np.asarray([side], dtype=np.float32), + focal_length=focal, + rescale_factor=args.rescale_factor, + intrx=intrinsic, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"WildHands detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/ap229997/hands", + "repository_branch": "demo", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector hand boxes, per-hand crops", + "training_exposure": "zero-shot H2O; released model trained on ARCTIC, AssemblyHands, and EPIC", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "camera_policy": "official WildHands weak-perspective conversion with known H2O intrinsics", + "joint_conversion": "official MANO output reordered to H2O/OpenPose convention", + "pytorch3d_compatibility": "three official pure-torch rotation formulas supplied without renderer", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="WildHands-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/run_wilor_h2o.py b/home/wuyifan/EgoNet_train_20261008/scripts/run_wilor_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..cabd7ffbda3772dd8a1d4c3d23a13f7eba864eb0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/run_wilor_h2o.py @@ -0,0 +1,346 @@ +#!/usr/bin/env python3 +"""Run the complete official WiLoR detector + reconstruction pipeline on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--official-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument( + "--camera-policy", + choices=("official", "h2o_intrinsics", "both"), + default="official", + ) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.repo = args.repo.resolve() + args.checkpoint = args.checkpoint.resolve() + args.detector = args.detector.resolve() + args.mano_right = args.mano_right.resolve() + args.root = args.root.resolve() + args.manifest = args.manifest.resolve() + if args.ground_truth is not None: + args.ground_truth = args.ground_truth.resolve() + args.output = args.output.resolve() + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + if args.official_output is not None: + args.official_output = args.official_output.resolve() + mano_target = args.repo / "mano_data" / "MANO_RIGHT.pkl" + if not mano_target.exists(): + mano_target.symlink_to(args.mano_right) + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from ultralytics import YOLO + from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + from wilor.datasets.vitdet_dataset import ViTDetDataset + from wilor.models import load_wilor + from wilor.utils.renderer import cam_crop_to_full + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + intrinsics = None + if args.camera_policy in ("h2o_intrinsics", "both"): + if args.ground_truth is None: + raise ValueError("--camera-policy h2o_intrinsics requires --ground-truth") + from foundation_hand.evaluation.sota import GroundTruthBundle + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ + ground_truth.intrinsics[gt_index[str(key)]] for key in keys + ]) + if args.camera_policy == "both" and args.official_output is None: + raise ValueError("--camera-policy both requires --official-output") + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + + enable_legacy_mano_loading() + model, model_cfg = load_wilor( + checkpoint_path=str(args.checkpoint), + cfg_path=str(args.repo / "pretrained_models" / "model_config.yaml"), + ) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + official_joints = ( + np.full_like(joints, np.nan) if args.camera_policy == "both" else None + ) + official_vertices = ( + np.full_like(vertices, np.nan) if args.camera_policy == "both" else None + ) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + img_size = batch["img_size"].float() + official_focal = ( + model_cfg.EXTRA.FOCAL_LENGTH + / model_cfg.MODEL.IMAGE_SIZE + * img_size.max() + ) + official_camera_tensor = cam_crop_to_full( + pred_cam, box_center, box_size, img_size, official_focal + ) + calibrated_camera_tensor = None + if args.camera_policy in ("h2o_intrinsics", "both"): + record_indices = np.asarray([record[0] for record in records]) + K = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (K[:, 0, 0] + K[:, 1, 1]) + principal = K[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + calibrated_camera_tensor = torch.stack(( + pred_cam[:, 1] + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), dim=-1) + camera_tensor = ( + calibrated_camera_tensor + if calibrated_camera_tensor is not None + else official_camera_tensor + ) + camera = camera_tensor.float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + relative_joints = batch_joints.copy() + relative_vertices = batch_vertices.copy() + batch_joints += camera[:, None] + batch_vertices += camera[:, None] + if args.camera_policy == "both": + official_camera = official_camera_tensor.float().cpu().numpy() + batch_official_joints = relative_joints + official_camera[:, None] + batch_official_vertices = relative_vertices + official_camera[:, None] + for local, (frame_index, side, score, _) in enumerate(records): + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + if args.camera_policy == "both": + official_joints[frame_index, side] = batch_official_joints[local] + official_vertices[frame_index, side] = batch_official_vertices[local] + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop_dataset = ViTDetDataset( + model_cfg, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append(( + frame_index, side, float(scores[choice]), crop_dataset[0] + )) + flush_queue() + if end % 100 == 0 or end == count: + print(f"WiLoR detector {end}/{count}", flush=True) + flush_queue(force=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "WiLoR", + "scope": "RGB decode + detector + crop preprocessing + reconstruction + camera conversion", + "frames": count, + "detected_hand_frames": int(detected.sum()), + "processing_seconds": processing_seconds, + "frames_per_second": count / processing_seconds, + "detector_batch_size": args.detector_batch_size, + "reconstruction_batch_size": args.reconstruction_batch_size, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + effective_policy = ( + "h2o_intrinsics" if args.camera_policy == "both" else args.camera_policy + ) + metadata = { + "official_repository": "https://github.com/rolpotamias/WiLoR", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB detector, per-detection RGB crop reconstruction", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "official detector handedness; highest-confidence detection per side", + "camera_policy": effective_policy, + "camera_conversion": ( + "official cam_crop_to_full with released assumed focal" + if effective_policy == "official" + else "cam_crop_to_full algebra with known H2O focal/principal point" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name=( + "WiLoR-official-camera" + if effective_policy == "official" + else "WiLoR-H2O-K-calibrated" + ), + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + if args.camera_policy == "both": + official_metadata = dict(metadata) + official_metadata.update({ + "camera_policy": "official", + "camera_conversion": "official cam_crop_to_full with released assumed focal", + }) + PredictionBundle( + model_name="WiLoR-official-camera", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=official_joints, + vertices_camera_m=official_vertices, + detected=detected, + confidence=confidence, + metadata=official_metadata, + ).save(args.official_output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/screen_phase6_mixed_projection_oof.py b/home/wuyifan/EgoNet_train_20261008/scripts/screen_phase6_mixed_projection_oof.py new file mode 100644 index 0000000000000000000000000000000000000000..71c0f7f48655721114a3fab67f4c9847cfdf1a0e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/screen_phase6_mixed_projection_oof.py @@ -0,0 +1,484 @@ +#!/usr/bin/env python3 +"""Select Phase 6 mixed-projection constants on train OOF predictions only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.mixed_projection import ( + coarse_wrist_ray_translation, + direct_wrist_ray_translation, + solve_mixed_projection_batch, +) + + +FINGERTIPS = (4, 8, 12, 16, 20) +Z_MODES = ( + "coarse", + "raw_alignment", + "calibrated_always", + "calibrated_confidence_0p6", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_cross_validated_calibration( + path: Path, +) -> dict[tuple[int, str, int, int], tuple[float, float, bool]]: + lookup: dict[tuple[int, str, int, int], tuple[float, float, bool]] = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + hand = 1 if row["side"] == "right" else 0 + key = ( + int(row["coarse_seed"]), row["take"], int(row["frame_id"]), hand, + ) + if key in lookup: + raise ValueError(f"duplicate calibration row: {key}") + lookup[key] = ( + float(row["calibrated_delta_z_mm"]) / 1000.0, + float(row["confidence"]), + row["alignment_available"] == "True", + ) + if len(lookup) != 333_936: + raise ValueError(f"expanded calibration row count changed: {len(lookup)}") + return lookup + + +def candidate_specs() -> list[dict[str, object]]: + output: list[dict[str, object]] = [] + for z_mode in Z_MODES: + output.extend(( + {"id": f"direct_xyz__z_{z_mode}", "assembly": "direct_xyz", "z_mode": z_mode}, + {"id": f"coarse_wrist_ray__z_{z_mode}", "assembly": "coarse_wrist_ray", "z_mode": z_mode}, + {"id": f"direct_2d_wrist_ray__z_{z_mode}", "assembly": "direct_2d_wrist_ray", "z_mode": z_mode}, + )) + for support in (4, 8, 12): + output.append({ + "id": f"mixed_wls_s{support}__z_{z_mode}", + "assembly": "mixed_projection_21j_wls", + "z_mode": z_mode, + "minimum_support": support, + "huber_delta_px": None, + }) + for delta in (2.0, 4.0, 8.0, 16.0): + output.append({ + "id": f"mixed_huber_d{delta:g}_s{support}__z_{z_mode}", + "assembly": "robust_mixed_projection", + "z_mode": z_mode, + "minimum_support": support, + "huber_delta_px": delta, + }) + return output + + +def corrections_for_take( + arrays: dict[str, np.ndarray], + *, + seed: int, + calibration: dict[tuple[int, str, int, int], tuple[float, float, bool]], +) -> tuple[dict[str, np.ndarray], np.ndarray, np.ndarray]: + time = len(arrays["frame_id"]) + calibrated = np.zeros((time, 2), dtype=np.float64) + confidence = np.zeros((time, 2), dtype=np.float64) + available = np.zeros((time, 2), dtype=bool) + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + for time_index, hand in zip(*np.where(valid), strict=True): + key = (seed, take, int(arrays["frame_id"][time_index]), int(hand)) + try: + calibrated[time_index, hand], confidence[time_index, hand], available[time_index, hand] = calibration[key] + except KeyError as error: + raise ValueError(f"missing cross-validated calibration row: {key}") from error + raw_available = arrays["alignment_applied"].astype(bool) + raw = np.where(raw_available, arrays["alignment_delta_z_m"], 0.0) + always = np.where(available, calibrated, 0.0) + gated = np.where(available & (confidence >= 0.6), calibrated, 0.0) + return { + "coarse": np.zeros((time, 2), dtype=np.float64), + "raw_alignment": raw, + "calibrated_always": always, + "calibrated_confidence_0p6": gated, + }, calibrated, confidence + + +def assemble( + spec: dict[str, object], + *, + coarse: np.ndarray, + root_relative_joints: np.ndarray, + anchors: np.ndarray, + K: np.ndarray, + z: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + direct = coarse.copy() + direct[:, 2] = z + ray = coarse_wrist_ray_translation(coarse, z) + assembly = spec["assembly"] + diagnostics: dict[str, np.ndarray] = {} + if assembly == "direct_xyz": + return direct, diagnostics + if assembly == "coarse_wrist_ray": + return ray, diagnostics + if assembly == "direct_2d_wrist_ray": + translation, valid = direct_wrist_ray_translation(anchors, K, z, ray) + diagnostics["success"] = valid + return translation, diagnostics + result = solve_mixed_projection_batch( + root_relative_joints, anchors, K, z, ray, + image_hw=(368, 640), + minimum_support=int(spec["minimum_support"]), + robust_huber_delta_px=( + None if spec["huber_delta_px"] is None else float(spec["huber_delta_px"]) + ), + ) + diagnostics.update({ + "support_count": result.support_count, + "residual_scale_px": result.residual_scale_px, + "conditioning": result.conditioning, + "inlier_ratio": result.inlier_ratio, + "uncertainty_x_m": result.uncertainty_xy_m[:, 0], + "uncertainty_y_m": result.uncertainty_xy_m[:, 1], + "success": result.failure_reason == "ok", + "failure_reason": result.failure_reason, + }) + return result.translation_m, diagnostics + + +def project(points: np.ndarray, K: np.ndarray) -> np.ndarray: + z = np.maximum(points[..., 2], 1e-8) + return np.stack(( + K[:, None, 0, 0] * points[..., 0] / z + K[:, None, 0, 2], + K[:, None, 1, 1] * points[..., 1] / z + K[:, None, 1, 2], + ), axis=-1) + + +def evaluate_translation( + arrays: dict[str, np.ndarray], + indices: tuple[np.ndarray, np.ndarray], + translation: np.ndarray, +) -> dict[str, np.ndarray]: + time_index, hand = indices + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + shift = translation - coarse + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + shift[:, None] + target = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_translation = arrays["target_wrist_translation"][time_index, hand].astype(np.float64) + joint_error = np.linalg.norm(joints - target, axis=-1) * 1000.0 + signed_translation = (translation - target_translation) * 1000.0 + K = arrays["K_resized"][time_index].astype(np.float64) + projected = project(joints, K) + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + target_2d = arrays["target_2d_px"][time_index, hand].astype(np.float64) + return { + "absolute_mpjpe_mm": joint_error.mean(axis=1), + "fingertip_mpjpe_mm": joint_error[:, FINGERTIPS].mean(axis=1), + "translation_x_mae_mm": np.abs(signed_translation[:, 0]), + "translation_y_mae_mm": np.abs(signed_translation[:, 1]), + "translation_z_mae_mm": np.abs(signed_translation[:, 2]), + "projected_mano_2d_px": np.linalg.norm(projected - target_2d, axis=-1).mean(axis=1), + "direct_mano_consistency_px": np.linalg.norm(projected - anchors, axis=-1).mean(axis=1), + } + + +def distribution(values: np.ndarray) -> dict[str, float]: + values = np.asarray(values, dtype=np.float64) + threshold = float(np.percentile(values, 95)) + return { + "mean": float(values.mean()), + "p95": threshold, + "cvar95": float(values[values >= threshold].mean()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--calibration-json", type=Path, required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + calibration_report = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration_report.get("status") != "fitted" + or calibration_report.get("official_validation_used") is not False + or calibration_report.get("official_test_used") is not False + or calibration_report.get("samples") != 333_936 + or calibration_report.get("predictions", {}).get("sha256") + != sha256(args.calibration_predictions) + ): + raise ValueError("expanded OOF calibration contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + calibration = load_cross_validated_calibration(args.calibration_predictions) + specs = candidate_specs() + spec_by_id = {str(spec["id"]): spec for spec in specs} + per_take: dict[tuple[str, int, str], dict[str, float]] = {} + values: dict[str, dict[str, list[np.ndarray]]] = { + str(spec["id"]): defaultdict(list) for spec in specs + } + bank_records = [] + sample_order: list[tuple[int, str, int, int]] = [] + + for bank_index, registered in enumerate(calibration_report["bank_manifests"], start=1): + manifest_path = Path(registered["path"]) + if sha256(manifest_path) != registered["sha256"]: + raise ValueError(f"bank manifest hash mismatch: {manifest_path}") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("official_test_used") is not False + or manifest.get("leakage_audit", {}).get("passed") is not True + ): + raise ValueError(f"bank isolation contract failed: {manifest_path}") + seed = int(manifest["seed"]) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + needed = ( + "frame_id", "frame_valid", "K_resized", "pred_wrist_translation", + "pred_joints_camera", "pred_direct_2d_px", "target_wrist_translation", + "target_joints_camera", "target_2d_px", "mano_annotation_valid", + "alignment_delta_z_m", "alignment_applied", + ) + arrays = {key: archive[key] for key in needed} + arrays["take"] = archive["take"] + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + indices = np.where(valid) + time_index, hand = indices + corrections, _, _ = corrections_for_take( + arrays, seed=seed, calibration=calibration, + ) + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + root_relative = joints - joints[:, :1] + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + K = arrays["K_resized"][time_index].astype(np.float64) + take_sample_keys = [ + (seed, take, int(arrays["frame_id"][t]), int(h)) + for t, h in zip(time_index, hand, strict=True) + ] + sample_order.extend(take_sample_keys) + for spec in specs: + candidate_id = str(spec["id"]) + z_mode = str(spec["z_mode"]) + refined_z = coarse[:, 2] + corrections[z_mode][time_index, hand] + translation, diagnostics = assemble( + spec, coarse=coarse, root_relative_joints=root_relative, + anchors=anchors, K=K, z=refined_z, + ) + metrics = evaluate_translation(arrays, indices, translation) + for metric, metric_values in metrics.items(): + values[candidate_id][metric].append(metric_values.astype(np.float32)) + success = diagnostics.get("success", np.ones(len(translation), dtype=bool)) + per_take[(candidate_id, seed, take)] = { + "absolute_mpjpe_mm": float(metrics["absolute_mpjpe_mm"].mean()), + "fingertip_mpjpe_mm": float(metrics["fingertip_mpjpe_mm"].mean()), + "translation_x_mae_mm": float(metrics["translation_x_mae_mm"].mean()), + "translation_y_mae_mm": float(metrics["translation_y_mae_mm"].mean()), + "translation_z_mae_mm": float(metrics["translation_z_mae_mm"].mean()), + "projected_mano_2d_px": float(metrics["projected_mano_2d_px"].mean()), + "success_fraction": float(success.mean()), + } + bank_records.append({ + "manifest": str(manifest_path), "sha256": registered["sha256"], + "seed": seed, "fold": int(manifest["fold"]), + "heldout_subject": manifest["heldout_subject"], + "takes": len(manifest["takes"]), "frames": int(manifest["frames"]), + }) + print(f"[{bank_index}/9] fold{manifest['fold']} seed{seed} complete", flush=True) + + if len(sample_order) != 333_936 or len(set(sample_order)) != len(sample_order): + raise ValueError("OOF sample coverage or uniqueness changed") + summary_rows = [] + concatenated: dict[str, dict[str, np.ndarray]] = {} + for spec in specs: + candidate_id = str(spec["id"]) + candidate_values = { + metric: np.concatenate(chunks) + for metric, chunks in values[candidate_id].items() + } + concatenated[candidate_id] = candidate_values + take_rows = [value for (name, _, _), value in per_take.items() if name == candidate_id] + z_mode = str(spec["z_mode"]) + baseline_id = f"direct_xyz__z_{z_mode}" + row: dict[str, object] = { + **spec, + "samples": len(candidate_values["absolute_mpjpe_mm"]), + "seed_take_groups": len(take_rows), + "absolute_frame_mean_mm": float(candidate_values["absolute_mpjpe_mm"].mean()), + "absolute_take_mean_mm": float(np.mean([item["absolute_mpjpe_mm"] for item in take_rows])), + "fingertip_frame_mean_mm": float(candidate_values["fingertip_mpjpe_mm"].mean()), + "translation_x_mae_mm": float(candidate_values["translation_x_mae_mm"].mean()), + "translation_x_p95_mm": float(np.percentile(candidate_values["translation_x_mae_mm"], 95)), + "translation_y_mae_mm": float(candidate_values["translation_y_mae_mm"].mean()), + "translation_y_p95_mm": float(np.percentile(candidate_values["translation_y_mae_mm"], 95)), + "translation_z_mae_mm": float(candidate_values["translation_z_mae_mm"].mean()), + "projected_mano_2d_px": float(candidate_values["projected_mano_2d_px"].mean()), + "direct_mano_consistency_px": float(candidate_values["direct_mano_consistency_px"].mean()), + "success_fraction": float(np.mean([item["success_fraction"] for item in take_rows])), + } + if candidate_id == baseline_id: + row.update({ + "absolute_frame_delta_vs_same_z_direct_mm": 0.0, + "absolute_take_delta_vs_same_z_direct_mm": 0.0, + "largest_take_harm_mm": 0.0, + "largest_sample_harm_mm": 0.0, + "absolute_guardrail_passed": True, + }) + summary_rows.append(row) + + row_by_id = {str(row["id"]): row for row in summary_rows} + for row in summary_rows: + candidate_id = str(row["id"]) + baseline_id = f"direct_xyz__z_{row['z_mode']}" + if candidate_id == baseline_id: + continue + baseline = row_by_id[baseline_id] + take_deltas = [] + for (name, seed, take), item in per_take.items(): + if name != candidate_id: + continue + take_deltas.append( + item["absolute_mpjpe_mm"] + - per_take[(baseline_id, seed, take)]["absolute_mpjpe_mm"] + ) + sample_delta = ( + concatenated[candidate_id]["absolute_mpjpe_mm"] + - concatenated[baseline_id]["absolute_mpjpe_mm"] + ) + frame_delta = float(row["absolute_frame_mean_mm"] - baseline["absolute_frame_mean_mm"]) + take_delta = float(row["absolute_take_mean_mm"] - baseline["absolute_take_mean_mm"]) + guardrail = min(0.2, 0.01 * float(baseline["absolute_frame_mean_mm"])) + row.update({ + "absolute_frame_delta_vs_same_z_direct_mm": frame_delta, + "absolute_take_delta_vs_same_z_direct_mm": take_delta, + "largest_take_harm_mm": float(np.max(take_deltas)), + "largest_sample_harm_mm": float(np.max(sample_delta)), + "absolute_guardrail_passed": frame_delta <= guardrail, + }) + + eligible = [ + row for row in summary_rows + if row["assembly"] != "direct_xyz" and row["absolute_guardrail_passed"] + ] + eligible.sort(key=lambda row: ( + float(row["absolute_take_mean_mm"]), + float(row["largest_take_harm_mm"]), + max(float(row["translation_x_p95_mm"]), float(row["translation_y_p95_mm"])), + float(row["projected_mano_2d_px"]), + distribution(concatenated[str(row["id"])]["absolute_mpjpe_mm"])["cvar95"], + 0 if row["assembly"] == "mixed_projection_21j_wls" else 1, + )) + if not eligible: + raise RuntimeError("no mixed-projection setting passes the preregistered guardrail") + best_take = float(eligible[0]["absolute_take_mean_mm"]) + tied = [row for row in eligible if float(row["absolute_take_mean_mm"]) <= best_take + 0.02] + tied.sort(key=lambda row: ( + float(row["largest_take_harm_mm"]), + max(float(row["translation_x_p95_mm"]), float(row["translation_y_p95_mm"])), + float(row["projected_mano_2d_px"]), + distribution(concatenated[str(row["id"])]["absolute_mpjpe_mm"])["cvar95"], + 0 if row["assembly"] == "mixed_projection_21j_wls" else 1, + )) + winner = tied[0] + winner_id = str(winner["id"]) + baseline_id = f"direct_xyz__z_{winner['z_mode']}" + winner_delta = ( + concatenated[winner_id]["absolute_mpjpe_mm"] + - concatenated[baseline_id]["absolute_mpjpe_mm"] + ) + order_gain = np.argsort(winner_delta)[:20] + order_harm = np.argsort(winner_delta)[-20:][::-1] + case_rows = [] + for role, order in (("largest_gain", order_gain), ("largest_harm", order_harm)): + for rank, index in enumerate(order, start=1): + seed, take, frame_id, hand = sample_order[int(index)] + case_rows.append({ + "role": role, "rank": rank, "sample_index": int(index), + "seed": seed, "take": take, "frame_id": frame_id, + "side": "right" if hand else "left", + "winner": winner_id, "baseline": baseline_id, + "absolute_delta_mm": float(winner_delta[index]), + "winner_absolute_mpjpe_mm": float(concatenated[winner_id]["absolute_mpjpe_mm"][index]), + "baseline_absolute_mpjpe_mm": float(concatenated[baseline_id]["absolute_mpjpe_mm"][index]), + }) + + write_csv(args.output_dir / "oof_grid.csv", summary_rows) + write_csv(args.output_dir / "largest_gain_harm.csv", case_rows) + report = { + "status": "selected_oof_only", + "experiment": "P6_S1_cache_mixed_projection", + "official_validation_used": False, + "official_test_used": False, + "oracle_information": False, + "samples": len(sample_order), + "seed_take_groups": len({(seed, take) for seed, take, _, _ in sample_order}), + "physical_takes": len({take for _, take, _, _ in sample_order}), + "seeds": sorted({seed for seed, _, _, _ in sample_order}), + "banks": bank_records, + "calibration": { + "json": str(args.calibration_json.resolve()), + "json_sha256": sha256(args.calibration_json), + "cross_validated_predictions": str(args.calibration_predictions.resolve()), + "predictions_sha256": sha256(args.calibration_predictions), + "confidence_threshold": 0.6, + }, + "grid": { + "conditions": len(specs), "minimum_support": [4, 8, 12], + "huber_delta_px": [2.0, 4.0, 8.0, 16.0], + "irls_iterations": 5, + "mask": "predicted finite + positive z>0.05m + in-frame anchor", + "fallback": "coarse wrist ray at same selected z; direct xyz if K invalid", + }, + "selection_rule": ( + "minimize seed-take-equal Absolute within same-z direct guardrail; " + "0.02mm tie band then largest-take harm, xy P95, projected 2D, CVaR95, WLS simplicity" + ), + "winner": winner, + "same_z_direct_baseline": row_by_id[baseline_id], + "outputs": {"grid": "oof_grid.csv", "largest_gain_harm": "largest_gain_harm.csv"}, + } + (args.output_dir / "selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "winner": winner_id, + "absolute_take_mean_mm": winner["absolute_take_mean_mm"], + "absolute_delta_mm": winner["absolute_take_delta_vs_same_z_direct_mm"], + "projected_mano_2d_px": winner["projected_mano_2d_px"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/seed_phase9_cache_hardlinks.py b/home/wuyifan/EgoNet_train_20261008/scripts/seed_phase9_cache_hardlinks.py new file mode 100644 index 0000000000000000000000000000000000000000..24c63f0ecef2de0911cd4cb725ab7bafc274d7f5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/seed_phase9_cache_hardlinks.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Seed an expanded cache with hash-verified hardlinks from an older cache.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def seed_hardlinks( + manifest: Path, output_dir: Path, expected_dataset: str, +) -> dict[str, Any]: + rows = [ + json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not rows or {row.get("dataset_id") for row in rows} != {expected_dataset}: + raise ValueError("source cache manifest dataset differs from expectation") + clips_dir = output_dir / "clips" + clips_dir.mkdir(parents=True, exist_ok=True) + logical_bytes = 0 + reused = 0 + for row in rows: + source = Path(row["cache_path"]) + if not source.is_file() or sha256(source) != row["cache_sha256"]: + raise ValueError(f"source payload is missing or differs: {source}") + target = clips_dir / source.name + if target.exists(): + if not target.is_file() or sha256(target) != row["cache_sha256"]: + raise ValueError(f"existing target payload differs: {target}") + else: + os.link(source, target) + logical_bytes += source.stat().st_size + reused += 1 + return { + "schema_version": "phase9_cache_hardlink_seed_v1", + "status": "complete", + "dataset": expected_dataset, + "source_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "output_dir": str(output_dir.resolve()), + "hardlinked_clips": reused, + "logical_bytes": logical_bytes, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-cache-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--dataset", choices=("HOT3D", "HOI4D", "ARCTIC"), required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + if args.report.exists(): + parser.error("report already exists") + try: + result = seed_hardlinks(args.source_cache_manifest, args.output_dir, args.dataset) + except (OSError, ValueError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.report.parent.mkdir(parents=True, exist_ok=True) + temporary = args.report.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.report) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/select_phase7_external_continuation.py b/home/wuyifan/EgoNet_train_20261008/scripts/select_phase7_external_continuation.py new file mode 100644 index 0000000000000000000000000000000000000000..b9332b63326456953ca11d008b1a0f69c2b42c24 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/select_phase7_external_continuation.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Select the final external checkpoint across frozen continuation steps.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.rank_phase7_external import METRICS, dense_ranks, evaluation_metrics, pareto_frontier +from scripts.build_phase7_scale_eval_queue import sha256 + + +DATASETS = ("ARCTIC", "HOI4D", "HOT3D") + + +def load_candidates(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if manifest.get("selection_split") != "external_heldout_only": + raise ValueError("continuation selection must be external-heldout only") + if set(manifest.get("datasets", [])) != set(DATASETS): + raise ValueError("continuation selection requires all three external datasets") + entries: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + for item in manifest.get("evaluations", []): + candidate, dataset = str(item["candidate"]), str(item["dataset"]) + if dataset not in DATASETS or (candidate, dataset) in seen: + raise ValueError(f"invalid or duplicate candidate/dataset pair: {(candidate, dataset)}") + seen.add((candidate, dataset)) + path = Path(item["path"]).resolve() + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or "h2o" in str(report["cache_manifest"]["path"]).lower() + ): + raise ValueError(f"non-external evaluation in continuation selection: {path}") + checkpoint = Path(report["checkpoint"]["path"]) + config = Path(report["config"]["path"]) + if sha256(checkpoint) != report["checkpoint"]["sha256"]: + raise ValueError(f"checkpoint hash mismatch: {checkpoint}") + if sha256(config) != report["config"]["sha256"]: + raise ValueError(f"config hash mismatch: {config}") + take_path = Path(report["take_metrics"]["path"]) + if sha256(take_path) != report["take_metrics"]["sha256"]: + raise ValueError(f"take metrics hash mismatch: {take_path}") + per_hand_path = Path(report["per_hand_rows"]["path"]) + if sha256(per_hand_path) != report["per_hand_rows"]["sha256"]: + raise ValueError(f"per-hand metrics hash mismatch: {per_hand_path}") + entries.append({ + "candidate": candidate, "dataset": dataset, + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint_path": str(checkpoint.resolve()), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config_path": str(config.resolve()), + "config_sha256": report["config"]["sha256"], + "evaluation_path": str(path), "take_metrics_path": str(take_path.resolve()), + "per_hand_metrics_path": str(per_hand_path.resolve()), + **evaluation_metrics(report), + }) + candidates = {entry["candidate"] for entry in entries} + missing = {(candidate, dataset) for candidate in candidates for dataset in DATASETS} - seen + if missing or len(candidates) < 2: + raise ValueError(f"incomplete continuation candidate grid: {sorted(missing)}") + for candidate in candidates: + selected = [entry for entry in entries if entry["candidate"] == candidate] + for field in ("checkpoint_step", "checkpoint_path", "checkpoint_sha256", "config_path", "config_sha256"): + if len({entry[field] for entry in selected}) != 1: + raise ValueError(f"candidate {candidate} has inconsistent {field}") + return entries + + +def rank_candidates(entries: list[dict[str, Any]]) -> dict[str, Any]: + candidates = sorted({entry["candidate"] for entry in entries}) + lookup = {(entry["candidate"], entry["dataset"]): entry for entry in entries} + dataset_ranks: dict[str, dict[str, float]] = {} + vectors = {candidate: [] for candidate in candidates} + for dataset in DATASETS: + ranks = { + metric: dense_ranks({candidate: lookup[(candidate, dataset)][metric] for candidate in candidates}) + for metric in METRICS + } + dataset_ranks[dataset] = {} + for candidate in candidates: + dataset_ranks[dataset][candidate] = sum(ranks[metric][candidate] for metric in METRICS) / len(METRICS) + vectors[candidate].extend(lookup[(candidate, dataset)][metric] for metric in METRICS) + macro = { + candidate: sum(dataset_ranks[dataset][candidate] for dataset in DATASETS) / len(DATASETS) + for candidate in candidates + } + order = sorted(candidates, key=lambda candidate: ( + macro[candidate], + sum(lookup[(candidate, dataset)]["absolute_mpjpe_mm"] for dataset in DATASETS), + sum(lookup[(candidate, dataset)]["root_relative_mpjpe_mm"] for dataset in DATASETS), + candidate, + )) + return { + "dataset_ranks": dataset_ranks, "macro_mean_rank": macro, + "pareto_frontier": pareto_frontier(vectors), "order": order, "winner": order[0], + } + + +def read_take_values( + path: Path, metric: str, statistic: str = "mean", +) -> dict[str, float]: + with path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + grouped: dict[str, list[float]] = {} + for row in rows: + value = float(row[metric]) + if math.isfinite(value): + grouped.setdefault(row["physical_recording_id"], []).append(value) + if statistic == "mean": + values = {key: float(np.mean(group)) for key, group in grouped.items()} + elif statistic == "p95": + values = {key: float(np.quantile(group, .95)) for key, group in grouped.items()} + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + if not values: + raise ValueError(f"no finite {metric} take values: {path}") + return values + + +def paired_take_bootstrap( + reference_path: Path, candidate_path: Path, metric: str, seed: int, resamples: int, + statistic: str = "mean", +) -> dict[str, Any]: + reference = read_take_values(reference_path, metric, statistic) + candidate = read_take_values(candidate_path, metric, statistic) + if set(reference) != set(candidate): + raise ValueError(f"paired take IDs differ for {metric}") + keys = sorted(reference) + delta = np.asarray([candidate[key] - reference[key] for key in keys], dtype=np.float64) + rng = np.random.default_rng(seed) + samples = delta[rng.integers(0, len(delta), size=(resamples, len(delta)))].mean(axis=1) + return { + "unit": "physical_recording", "recording_statistic": statistic, + "take_count": len(delta), + "delta_definition": "candidate_minus_reference; negative favors candidate", + "mean_delta": float(delta.mean()), + "ci95_low": float(np.percentile(samples, 2.5)), + "ci95_high": float(np.percentile(samples, 97.5)), + "resamples": resamples, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--funnel-selection", type=Path, required=True) + parser.add_argument("--expected-funnel-winner", required=True) + parser.add_argument("--reference-candidate", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--seed", type=int, default=20260717) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + funnel = json.loads(args.funnel_selection.read_text(encoding="utf-8")) + if ( + funnel.get("status") != "ranked_external_only" + or funnel.get("winner") != args.expected_funnel_winner + or funnel.get("h2o_used") is not False + or funnel.get("official_test_used") is not False + ): + parser.error("funnel selection does not match the frozen external-only decision") + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + entries = load_candidates(manifest) + ranking = rank_candidates(entries) + if args.reference_candidate not in ranking["order"]: + parser.error("reference candidate is absent") + lookup = {(entry["candidate"], entry["dataset"]): entry for entry in entries} + paired: dict[str, Any] = {} + paired_specs = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), + } + for candidate in ranking["order"]: + if candidate == args.reference_candidate: + continue + paired[candidate] = { + dataset: { + metric_name: paired_take_bootstrap( + Path(lookup[(args.reference_candidate, dataset)]["per_hand_metrics_path"]), + Path(lookup[(candidate, dataset)]["per_hand_metrics_path"]), + row_metric, args.seed, args.bootstrap_resamples, statistic, + ) + for metric_name, (row_metric, statistic) in paired_specs.items() + } + for dataset in DATASETS + } + winner = ranking["winner"] + winner_entries = [entry for entry in entries if entry["candidate"] == winner] + first = winner_entries[0] + result = { + "status": "selected_external_generalist_no_h2o", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "selection_rule": "dataset metric ranks -> macro mean rank -> Absolute/root-relative tie-break", + "selection_split": "external_heldout_only", "frame_count_weighted": False, + "funnel_selection": { + "path": str(args.funnel_selection.resolve()), "sha256": sha256(args.funnel_selection), + "winner": args.expected_funnel_winner, + }, + "candidate_manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "reference_candidate": args.reference_candidate, + **ranking, "entries": entries, "paired_take_bootstrap": paired, + "checkpoint": { + "path": first["checkpoint_path"], "sha256": first["checkpoint_sha256"], + "step": first["checkpoint_step"], + }, + "config": {"path": first["config_path"], "sha256": first["config_sha256"]}, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/select_phase7_h2o_adaptation.py b/home/wuyifan/EgoNet_train_20261008/scripts/select_phase7_h2o_adaptation.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8d06a6082f25489ca5816a83149e0eba2424aa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/select_phase7_h2o_adaptation.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Select a Phase 7 adaptation branch using H2O train-group-heldout only.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.build_phase7_scale_eval_queue import sha256 + + +PRIMARY_METRIC = "absolute_mpjpe_mm" +METRIC_SPECS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} +IDENTITY_FIELDS = ("physical_recording_id", "camera_id", "frame_id", "side") + + +def checked_artifact(record: dict[str, Any], name: str) -> Path: + artifact = record[name] + path = Path(artifact["path"]).resolve() + if not path.is_file() or sha256(path) != artifact["sha256"]: + raise ValueError(f"{name} is missing or has a SHA256 mismatch: {path}") + return path + + +def load_candidates(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if ( + manifest.get("selection_split") != "h2o_train_group_heldout_only" + or manifest.get("h2o_official_validation_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("selection manifest violates the H2O train-heldout boundary") + candidates: list[dict[str, Any]] = [] + names: set[str] = set() + cache_sha256: set[str] = set() + for item in manifest.get("candidates", []): + name = str(item["candidate"]) + if name in names: + raise ValueError(f"duplicate candidate: {name}") + names.add(name) + report_path = Path(item["evaluation"]).resolve() + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_h2o_train_group_heldout" + or report.get("evaluation_role") != "h2o_train_group_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or Path(report["cache_manifest"]["path"]).name != "train_group_heldout.jsonl" + ): + raise ValueError(f"candidate is not a valid train-heldout evaluation: {report_path}") + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + per_hand = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + cache = checked_artifact(report, "cache_manifest") + cache_sha256.add(report["cache_manifest"]["sha256"]) + metrics = { + metric: float(report["metrics"][row_metric]["mean"]) + for metric, (row_metric, statistic) in METRIC_SPECS.items() + if statistic == "mean" + } + metrics["translation_z_p95_mm"] = float( + report["metrics"]["translation_z_mae_mm"]["p95"] + ) + if not all(math.isfinite(value) for value in metrics.values()): + raise ValueError(f"candidate contains non-finite metrics: {name}") + candidates.append({ + "candidate": name, + "evaluation": str(report_path), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config), + "config_sha256": report["config"]["sha256"], + "cache_manifest": str(cache), + "cache_manifest_sha256": report["cache_manifest"]["sha256"], + "per_hand_rows": str(per_hand), + "metrics": metrics, + }) + if len(candidates) < 2: + raise ValueError("adaptation selection requires at least two candidates") + if len(cache_sha256) != 1: + raise ValueError("adaptation candidates use different train-heldout manifests") + return candidates + + +def read_paired_rows(path: Path, metric: str) -> dict[tuple[str, ...], float]: + result: dict[tuple[str, ...], float] = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + identity = tuple(str(row[field]) for field in IDENTITY_FIELDS) + if identity in result: + raise ValueError(f"duplicate per-hand identity: {identity}") + result[identity] = float(row[metric]) + return result + + +def paired_recording_bootstrap( + reference: Path, + candidate: Path, + metric: str, + statistic: str, + seed: int, + resamples: int, +) -> dict[str, Any]: + reference_rows = read_paired_rows(reference, metric) + candidate_rows = read_paired_rows(candidate, metric) + if set(reference_rows) != set(candidate_rows): + raise ValueError(f"paired per-hand identities differ for {metric}") + grouped: dict[str, list[tuple[float, float]]] = {} + for identity in sorted(reference_rows): + reference_value, candidate_value = reference_rows[identity], candidate_rows[identity] + if math.isfinite(reference_value) and math.isfinite(candidate_value): + grouped.setdefault(identity[0], []).append((reference_value, candidate_value)) + if not grouped: + raise ValueError(f"no finite paired values for {metric}") + deltas = [] + for recording in sorted(grouped): + values = np.asarray(grouped[recording], dtype=np.float64) + if statistic == "mean": + delta = values[:, 1].mean() - values[:, 0].mean() + elif statistic == "p95": + delta = np.quantile(values[:, 1], .95) - np.quantile(values[:, 0], .95) + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + deltas.append(float(delta)) + array = np.asarray(deltas, dtype=np.float64) + rng = np.random.default_rng(seed) + samples = array[rng.integers(0, len(array), size=(resamples, len(array)))].mean(1) + return { + "unit": "physical_recording", + "recording_statistic": statistic, + "recordings": len(array), + "delta_definition": "candidate_minus_reference; negative favors candidate", + "mean_delta": float(array.mean()), + "ci95_low": float(np.quantile(samples, .025)), + "ci95_high": float(np.quantile(samples, .975)), + "resamples": resamples, + } + + +def select( + manifest: dict[str, Any], seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + candidates = load_candidates(manifest) + order = sorted(candidates, key=lambda item: ( + item["metrics"][PRIMARY_METRIC], + item["metrics"]["root_relative_mpjpe_mm"], + item["metrics"]["fingertip_mpjpe_mm"], + item["candidate"], + )) + reference = order[0] + paired = {} + for candidate in order[1:]: + paired[candidate["candidate"]] = { + metric_name: paired_recording_bootstrap( + Path(reference["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for metric_name, (row_metric, statistic) in METRIC_SPECS.items() + } + return { + "status": "selected_h2o_adaptation_train_group_heldout", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "selection_rule": "lowest train-group-heldout Absolute MPJPE; root-relative then fingertip tie-break; no multi-seed or one-percent gate", + "selection_split": "h2o_train_group_heldout_only", + "primary_metric": PRIMARY_METRIC, + "winner": reference["candidate"], + "order": [item["candidate"] for item in order], + "candidates": candidates, + "paired_recording_bootstrap_vs_winner": paired, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + result = select( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, + resamples=args.bootstrap_resamples, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase4_a3.py b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase4_a3.py new file mode 100644 index 0000000000000000000000000000000000000000..d8de0510886c2ea270a8dc11eb799add21226b64 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase4_a3.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +"""Real-batch equality/backward smoke for the A3 oracle crop refiner.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def attach_gt_vertices( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> None: + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + with torch.no_grad(): + vertices, _ = model.mano_layer( + axis_angle_to_matrix(pose), + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = ( + batch["mano_annotation_valid"].bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where( + valid, vertices, torch.full_like(vertices, torch.nan), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--mode", choices=( + "oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k", + ), required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + actual_hash = file_sha256(args.checkpoint) + if actual_hash != args.expected_checkpoint_sha256: + parser.error( + f"checkpoint hash mismatch: {actual_hash} != {args.expected_checkpoint_sha256}" + ) + args.output_dir.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load(args.base_config.read_text(encoding="utf-8")) + seed = int(config["seed"]) + torch.manual_seed(seed) + data, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + photometric_augmentation=data.get("photometric_augmentation"), + augmentation_seed=seed, oracle_crop_enabled=True, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + device = torch.device(f"cuda:{args.gpu}") + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + common_model = { + **config["model"], + "dinov3_source": assets["dinov3_source"], + "dinov3_weights": assets["dinov3_weights"], + "mano_root": assets["mano_root"], + } + base = BimanualReconstructionModel(ModelConfig(**common_model)).to(device).eval() + load_checkpoint(args.checkpoint, base, optimizer=None, map_location=device) + refined_config = ModelConfig( + **common_model, oracle_crop_mode=args.mode, + freeze_coarse_for_oracle_crop=True, + ) + refined = BimanualReconstructionModel(refined_config).to(device).eval() + initialization = load_model_initialization( + args.checkpoint, refined, + allowed_missing_prefixes=("oracle_crop_",), map_location=device, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + base_output = base(batch) + refined_output = refined(batch) + comparisons = { + "joint2d": torch.equal( + base_output["joint2d_norm"], refined_output["joint2d_norm"], + ), + "rotations": torch.equal( + base_output["mano_rotation_matrices"], + refined_output["coarse_mano_rotation_matrices"], + ) and torch.equal( + refined_output["mano_rotation_matrices"], + refined_output["coarse_mano_rotation_matrices"], + ), + "shape": torch.equal( + base_output["mano_shape"], refined_output["coarse_mano_shape"], + ) and torch.equal( + refined_output["mano_shape"], refined_output["coarse_mano_shape"], + ), + "translation": torch.equal( + base_output["wrist_root_translation"], + refined_output["coarse_wrist_root_translation"], + ) and torch.equal( + refined_output["wrist_root_translation"], + refined_output["coarse_wrist_root_translation"], + ), + "joints": torch.equal( + base_output["joints_camera"], refined_output["coarse_joints_camera"], + ) and torch.equal( + refined_output["joints_camera"], refined_output["coarse_joints_camera"], + ), + "vertices": torch.equal( + base_output["vertices_camera"], refined_output["coarse_vertices_camera"], + ) and torch.equal( + refined_output["vertices_camera"], refined_output["coarse_vertices_camera"], + ), + } + if not all(comparisons.values()): + raise RuntimeError(f"zero-init coarse/refined equality failed: {comparisons}") + del base, base_output, refined_output + torch.cuda.empty_cache() + + refined.train() + attach_gt_vertices(batch, refined) + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + trainable = { + name: value for name, value in refined.named_parameters() + if value.requires_grad + } + if not trainable or any(not name.startswith("oracle_crop_") for name in trainable): + raise RuntimeError("A3 smoke found trainable non-oracle parameters") + optimizer = torch.optim.AdamW(trainable.values(), lr=5e-5, weight_decay=0.05) + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=dtype): + prediction = refined(batch) + losses = criterion(prediction, batch) + losses["total"].backward() + gradients_finite = all( + parameter.grad is None or bool(torch.isfinite(parameter.grad).all()) + for parameter in trainable.values() + ) + heads_with_gradient = sorted( + name for name, parameter in trainable.items() + if parameter.grad is not None and bool(torch.count_nonzero(parameter.grad)) + ) + if not gradients_finite or not heads_with_gradient: + raise RuntimeError("A3 smoke backward did not produce finite head gradients") + optimizer.step() + smoke_checkpoint = args.output_dir / "smoke_checkpoint.pt" + save_checkpoint( + smoke_checkpoint, refined, optimizer, 1, + extra={ + "phase": 4, "wave": "A3", "mode": args.mode, + "coarse_checkpoint_sha256": actual_hash, + "official_test_used": False, + }, + exclude_prefixes=("rgb_encoder.backbone.",), + ) + reloaded = BimanualReconstructionModel(refined_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + [value for value in reloaded.parameters() if value.requires_grad], + lr=5e-5, weight_decay=0.05, + ) + resume = load_checkpoint( + smoke_checkpoint, reloaded, reloaded_optimizer, map_location=device, + ) + reload_exact = all( + key.startswith("rgb_encoder.backbone.") + or torch.equal(value, reloaded.state_dict()[key]) + for key, value in refined.state_dict().items() + ) + payload = { + "status": "passed", + "official_test_used": False, + "mode": args.mode, + "seed": seed, + "coarse_checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": actual_hash, + "step": initialization["step"], + }, + "initialization_residual_missing_keys": initialization["residual_missing_keys"], + "checkpoint_excluded_prefixes": initialization[ + "checkpoint_excluded_prefixes" + ], + "zero_init_exact": comparisons, + "trainable_parameters": sum(value.numel() for value in trainable.values()), + "trainable_names_oracle_only": True, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "gradients_finite": gradients_finite, + "heads_with_gradient": heads_with_gradient, + "checkpoint_reload_exact": bool(reload_exact and resume["step"] == 1), + "oracle_crop_available_fraction": float( + batch["oracle_crop_available"].float().mean() + ), + "oracle_crop_depth_available_fraction": float( + batch["oracle_crop_depth_available"].float().mean() + ), + } + if not payload["checkpoint_reload_exact"]: + raise RuntimeError("A3 smoke checkpoint reload was not exact") + (args.output_dir / "smoke.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(payload, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase5_structured.py b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase5_structured.py new file mode 100644 index 0000000000000000000000000000000000000000..32656058c47b6e540b61932cf600b3a86860e640 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase5_structured.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Real-checkpoint forward/backward smoke for Phase 5 structured refinement.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("structured smoke output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if not config.get("model", {}).get("structured_hand_refinement", False): + raise ValueError("smoke requires a structured-hand config") + expected_hash = config.get("experiment", {}).get("coarse_checkpoint_sha256") + if sha256(args.checkpoint) != expected_hash: + raise ValueError("coarse checkpoint hash does not match the registered config") + seed = int(config["seed"]) + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("structured_",), + map_location=device, + ) + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-6, weight_decay=0.05) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + exact_zero_init = { + "joint2d": torch.equal(prediction["joint2d_norm"], prediction["coarse_joint2d_norm"]), + "rotation": torch.equal( + prediction["mano_rotation_matrices"], + prediction["coarse_mano_rotation_matrices"], + ), + "shape_sequence": torch.equal( + prediction["mano_shape_sequence"], + prediction["coarse_mano_shape_sequence"], + ), + "shape": torch.equal(prediction["mano_shape"], prediction["coarse_mano_shape"]), + "translation": torch.equal( + prediction["wrist_root_translation"], + prediction["coarse_wrist_root_translation"], + ), + } + losses["total"].backward() + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + residual_head_gradients = { + name: bool( + parameter.grad is not None and torch.isfinite(parameter.grad).all() + ) + for name, parameter in model.named_parameters() + if name.startswith("structured_") and name.endswith("weight") + } + required_head_gradients = { + name: finite for name, finite in residual_head_gradients.items() + if model_config.structured_refine_translation + or not name.startswith("structured_translation_head.") + } + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + args.output_dir.mkdir(parents=True, exist_ok=True) + checkpoint = args.output_dir / "structured_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, step=1, + extra={"kind": "phase5_structured_real_checkpoint_smoke"}, + exclude_prefixes=("rgb_encoder.backbone.",), + ) + expected_state = { + key: value.detach().cpu().clone() + for key, value in model.state_dict().items() + if not key.startswith("rgb_encoder.backbone.") + } + del prediction, losses, model, optimizer, criterion + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW(reloaded.parameters(), lr=5e-6, weight_decay=0.05) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected_state.items() + ) + shared_initialization_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("structured_", "rgb_encoder.backbone.")) + ] + passed = bool( + all(exact_zero_init.values()) + and all(required_head_gradients.values()) + and all(np.isfinite(value) for value in loss_values.values()) + and not shared_initialization_missing + and resume_exact + and resumed["step"] == 1 + ) + result = { + "status": "passed" if passed else "failed", + "experiment_class": "engineering_real_checkpoint_smoke", + "formal_training": False, + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "seed": seed, + "resolution_hw": data["resolution_hw"], + "T": data["T"], + "precision": config["precision"], + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_initialization_missing, + "exact_zero_initialization": exact_zero_init, + "losses": loss_values, + "losses_finite": all(np.isfinite(value) for value in loss_values.values()), + "gradient_norm": gradient_norm, + "residual_head_gradients_finite": residual_head_gradients, + "required_residual_head_gradients_finite": required_head_gradients, + "elapsed_s": elapsed, + "frames_per_s": int(data["T"]) / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "smoke_checkpoint": { + "path": str(checkpoint.resolve()), "sha256": sha256(checkpoint), + }, + "trainable_parameters": sum( + parameter.numel() for parameter in reloaded.parameters() + if parameter.requires_grad + ), + "frozen_parameters": sum( + parameter.numel() for parameter in reloaded.parameters() + if not parameter.requires_grad + ), + } + (args.output_dir / "smoke.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": result["status"], "exact_zero_initialization": exact_zero_init, + "resume_exact": resume_exact, "checkpoint": result["smoke_checkpoint"], + }, indent=2)) + if result["status"] != "passed": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase6_mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase6_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..e77188fd1466a88d3953ae576c22e44590e495bc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase6_mixed_projection.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Real-checkpoint smoke for differentiable Phase 6 mixed projection.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def prefix(batch: dict[str, object], length: int) -> dict[str, object]: + output = {} + for key, value in batch.items(): + output[key] = ( + value[:, :length] if torch.is_tensor(value) and value.ndim >= 2 + and value.shape[1] == batch["frame_valid"].shape[1] + else value + ) + return output + + +def attach_gt_vertices( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> None: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for the real-batch smoke") + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, _ = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = ( + batch["mano_annotation_valid"].bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where( + valid, vertices, torch.full_like(vertices, torch.nan), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if config["model"].get("translation_parameterization") != "mixed_projection": + parser.error("smoke requires mixed_projection") + if sha256(args.checkpoint) != config["experiment"]["coarse_checkpoint_sha256"]: + parser.error("checkpoint hash differs from preregistration") + seed = int(config["seed"]) + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("mixed_log_tz_head",), + map_location=device, + ) + model.initialize_mixed_log_tz_from_direct_head() + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + learning_rate = float(config["protocol"]["learning_rate"]) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + attach_gt_vertices(batch, model) + args.output_dir.mkdir(parents=True, exist_ok=True) + excluded = checkpoint_excluded_prefixes(model) + initialized_checkpoint = args.output_dir / "mixed_projection_initialized_step0.pt" + save_checkpoint( + initialized_checkpoint, model, optimizer, 0, + extra={"kind": "phase6_mixed_projection_initialized_step0"}, + exclude_prefixes=excluded, + ) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + success_fraction = float(prediction["mixed_projection_success"].float().mean()) + teacher_z_difference_mm = float( + 1000.0 * ( + prediction["wrist_root_translation"][..., 2] + - prediction["mixed_projection_direct_teacher_translation"][..., 2] + ).abs().mean() + ) + losses["total"].backward() + gradient_groups = { + "log_tz": ["mixed_log_tz_head."], + "joint2d": ["joint2d_head."], + "pose": ["rotation_head."], + "shape": ["shape_head."], + "decoder": ["decoder."], + } + gradients = {} + for group, prefixes in gradient_groups.items(): + selected = [ + parameter.grad for name, parameter in model.named_parameters() + if parameter.requires_grad and name.startswith(tuple(prefixes)) + ] + gradients[group] = bool( + selected + and all(value is None or torch.isfinite(value).all() for value in selected) + and any(value.abs().sum() > 0 for value in selected if value is not None) + ) + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + model.eval() + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + t1 = model(prefix(batch, 1)) + t1_finite = bool( + torch.isfinite(t1["wrist_root_translation"]).all() + and torch.isfinite(t1["joints_camera"]).all() + ) + checkpoint = args.output_dir / "mixed_projection_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, 1, + extra={"kind": "phase6_mixed_projection_real_checkpoint_smoke"}, + exclude_prefixes=excluded, + ) + expected = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + if not key.startswith(excluded) + } + del model, optimizer, criterion, prediction, losses, t1 + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + reloaded, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected.items() + ) + shared_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("mixed_log_tz_head", "rgb_encoder.backbone.")) + ] + passed = bool( + all(np.isfinite(value) for value in loss_values.values()) + and success_fraction >= 0.99 + and all(gradients.values()) + and t1_finite + and resume_exact + and resumed["step"] == 1 + and not shared_missing + ) + report = { + "status": "passed" if passed else "failed", + "experiment": "P6_S2_differentiable_mixed_projection", + "experiment_class": "engineering_real_checkpoint_smoke", + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_missing, + "mixed_log_tz_initialization": "first-order log-softplus linearization", + "losses": loss_values, + "success_fraction": success_fraction, + "teacher_z_difference_mm": teacher_z_difference_mm, + "gradient_groups_finite_nonzero": gradients, + "gradient_norm": gradient_norm, + "T1_finite": t1_finite, + "T8_finite": all(np.isfinite(value) for value in loss_values.values()), + "elapsed_s": elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "initialized_checkpoint": { + "path": str(initialized_checkpoint.resolve()), + "sha256": sha256(initialized_checkpoint), + "step": 0, + }, + "checkpoint": {"path": str(checkpoint.resolve()), "sha256": sha256(checkpoint)}, + "trainable_parameters": sum(p.numel() for p in reloaded.parameters() if p.requires_grad), + "frozen_parameters": sum(p.numel() for p in reloaded.parameters() if not p.requires_grad), + } + (args.output_dir / "smoke.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "success_fraction": success_fraction, + "gradients": gradients, "resume_exact": resume_exact, + "output": str(args.output_dir), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase6_spatial_joint2d.py b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase6_spatial_joint2d.py new file mode 100644 index 0000000000000000000000000000000000000000..9c44a3f4073745881c46c5bdcea4843985a927ff --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_phase6_spatial_joint2d.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Real-checkpoint smoke for the Phase 6 spatial joint localizer.""" + +from __future__ import annotations + +import argparse +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, +) +from scripts.smoke_phase6_mixed_projection import attach_gt_vertices, prefix, sha256 + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if config["model"].get("joint2d_parameterization") != "spatial_heatmap": + parser.error("spatial smoke requires joint2d_parameterization=spatial_heatmap") + if sha256(args.checkpoint) != config["experiment"]["coarse_checkpoint_sha256"]: + parser.error("checkpoint hash differs from preregistration") + seed = int(config["seed"]) + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("joint_localization_",), + map_location=device, + ) + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + learning_rate = float(config["protocol"]["learning_rate"]) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + attach_gt_vertices(batch, model) + args.output_dir.mkdir(parents=True, exist_ok=True) + excluded = checkpoint_excluded_prefixes(model) + initialized_checkpoint = args.output_dir / "spatial_joint2d_initialized_step0.pt" + save_checkpoint( + initialized_checkpoint, model, optimizer, 0, + extra={"kind": "phase6_spatial_joint2d_initialized_step0"}, + exclude_prefixes=excluded, + ) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + height, width = map(int, batch["image_hw"][0].tolist()) + teacher_difference_px = float(( + (prediction["joint2d_norm"] - prediction["joint2d_linear_teacher_norm"]) + * prediction["joint2d_norm"].new_tensor((width, height)) + ).abs().mean()) + entropy = prediction["joint2d_heatmap_entropy"] + entropy_finite_bounded = bool( + torch.isfinite(entropy).all() and (entropy >= 0).all() and (entropy <= 1.0 + 1e-6).all() + ) + losses["total"].backward() + groups = { + "embedding": ("joint_localization_embedding",), + "query": ("joint_localization_query.",), + "feature": ("joint_localization_feature.",), + "offset": ("joint_localization_offset.",), + "decoder": ("decoder.",), + } + gradients = {} + for group, prefixes in groups.items(): + selected = [ + parameter.grad for name, parameter in model.named_parameters() + if parameter.requires_grad and name.startswith(prefixes) + ] + gradients[group] = bool( + selected + and all(value is None or torch.isfinite(value).all() for value in selected) + and any(value is not None and value.abs().sum() > 0 for value in selected) + ) + teacher_frozen = all(not parameter.requires_grad for parameter in model.joint2d_head.parameters()) + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + model.eval() + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + t1 = model(prefix(batch, 1)) + t1_finite = bool( + torch.isfinite(t1["joint2d_norm"]).all() + and torch.isfinite(t1["wrist_root_translation"]).all() + ) + checkpoint = args.output_dir / "spatial_joint2d_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, 1, + extra={"kind": "phase6_spatial_joint2d_real_checkpoint_smoke"}, + exclude_prefixes=excluded, + ) + expected = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + if not key.startswith(excluded) + } + del model, optimizer, criterion, prediction, losses, t1 + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + reloaded, learning_rate=learning_rate, backbone_learning_rate=None, + ), lr=learning_rate, weight_decay=0.05, + ) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected.items() + ) + shared_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("joint_localization_", "rgb_encoder.backbone.")) + ] + passed = bool( + all(np.isfinite(value) for value in loss_values.values()) + and all(gradients.values()) and teacher_frozen and entropy_finite_bounded + and t1_finite and resume_exact and resumed["step"] == 1 and not shared_missing + ) + report = { + "status": "passed" if passed else "failed", + "experiment": "P6_S3B_spatial_2d_anchors", + "experiment_class": "engineering_real_checkpoint_smoke", + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_missing, + "losses": loss_values, + "teacher_difference_px": teacher_difference_px, + "teacher_frozen": teacher_frozen, + "entropy_finite_bounded": entropy_finite_bounded, + "gradient_groups_finite_nonzero": gradients, + "gradient_norm": gradient_norm, + "T1_finite": t1_finite, + "T8_finite": all(np.isfinite(value) for value in loss_values.values()), + "elapsed_s": elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "initialized_checkpoint": { + "path": str(initialized_checkpoint.resolve()), + "sha256": sha256(initialized_checkpoint), "step": 0, + }, + "checkpoint": {"path": str(checkpoint.resolve()), "sha256": sha256(checkpoint)}, + } + (args.output_dir / "smoke.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "gradients": gradients, + "resume_exact": resume_exact, "output": str(args.output_dir), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/smoke_real_batch.py b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_real_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..7581b85b5a1e7d58affbf1c719ca10b12c981c1f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/smoke_real_batch.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Real H2O batch structural smoke test; uses debug RGB encoder when weights are absent.""" + +from __future__ import annotations + +import argparse +import json +import time +from pathlib import Path + +import cv2 +import numpy as np +import torch +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint, save_checkpoint + + +def parameter_counts(model: torch.nn.Module) -> tuple[int, int]: + trainable = sum(value.numel() for value in model.parameters() if value.requires_grad) + frozen = sum(value.numel() for value in model.parameters() if not value.requires_grad) + return trainable, frozen + + +def draw_overlay(batch: dict[str, torch.Tensor], output: dict[str, torch.Tensor], path: Path) -> None: + rgb = batch["rgb"][0, 0].detach().cpu().permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + height, width = image.shape[:2] + predicted = output["joint2d_norm"][0, 0].detach().float().cpu().numpy() * np.array((width, height)) + target = batch["joint2d"][0, 0].detach().float().cpu().numpy() + annotation_valid = batch["joint_annotation_valid"][0, 0].cpu().numpy() + for hand, color in enumerate(((50, 220, 50), (50, 80, 255))): + for point in predicted[hand]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, color, -1) + if annotation_valid[hand]: + for point in target[hand]: + cv2.drawMarker(image, tuple(np.rint(point).astype(int)), (255, 255, 255), cv2.MARKER_CROSS, 7, 1) + label = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/{int(batch['frame_id'][0,0])} debug_encoder RGB-D-K" + cv2.rectangle(image, (0, 0), (width, 32), (0, 0, 0), -1) + cv2.putText(image, label, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (255, 255, 255), 1) + cv2.imwrite(str(path), image) + + attention = output["attention"]["rgb_cross_attention"][0, -1, 0].detach().float().cpu().numpy() + grid_h, grid_w = height // 16, width // 16 + for hand, side in enumerate(("left", "right")): + heat = attention[hand].reshape(grid_h, grid_w) + heat = (heat - heat.min()) / max(float(heat.max() - heat.min()), 1e-8) + heat = cv2.resize(np.rint(heat * 255).astype(np.uint8), (width, height), interpolation=cv2.INTER_CUBIC) + heat = cv2.applyColorMap(heat, cv2.COLORMAP_TURBO) + mixed = cv2.addWeighted(image, 0.55, heat, 0.45, 0) + cv2.imwrite(str(path.with_name(path.stem + f"_{side}_rgb_attention.jpg")), mixed) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + torch.manual_seed(20260716); np.random.seed(20260716) + device = torch.device(f"cuda:{args.gpu}") + dataset = H2OCam4Dataset(args.root, args.manifest, (288, 512), (8,), (1,), max_clips=2) + loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_h2o_clips) + batch = next(iter(loader)) + batch = {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + config = ModelConfig( + encoder="tiny_debug", decoder_dim=256, decoder_layers=3, attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, depth_mode="log_depth", + use_rays=True, use_bimanual_interaction=True, require_mano=False, + ) + model = BimanualReconstructionModel(config).to(device).train() + loss_function = BimanualLoss(LossConfig()).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) + torch.cuda.reset_peak_memory_stats(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = loss_function(prediction, batch) + losses["total"].backward() + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000)) + optimizer.step(); torch.cuda.synchronize(device) + elapsed = time.perf_counter() - start + checkpoint = args.output_dir / "real_batch_smoke.pt" + save_checkpoint(checkpoint, model, optimizer, 1, {"kind": "structural_smoke_debug_encoder"}) + reloaded = BimanualReconstructionModel(config).to(device) + reloaded_optimizer = torch.optim.AdamW(reloaded.parameters(), lr=1e-4) + resume = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all(torch.equal(model.state_dict()[key], value) for key, value in reloaded.state_dict().items()) + trainable, frozen = parameter_counts(model) + result = { + "status": "passed_structural_smoke_only", "formal_training": False, + "limitation": "tiny_debug RGB encoder and no MANO assets; joint/vertex/reprojection losses are zero", + "seed": 20260716, "resolution_hw": [288, 512], "T": 8, "stride": 1, "batch_size": 1, "precision": "bf16", + "decoder": "alternating", "depth": "log_depth", "rays": True, + "trainable_parameters": trainable, "frozen_parameters": frozen, + "elapsed_s": elapsed, "frames_per_s": 8 / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30, + "gradient_norm": gradient_norm, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "losses_finite": all(bool(torch.isfinite(value)) for value in losses.values()), + "resume_success": bool(resume_exact and resume["step"] == 1), "checkpoint": str(checkpoint.resolve()), + "input_shapes": {key: list(value.shape) for key, value in batch.items() if torch.is_tensor(value)}, + "output_shapes": {key: list(value.shape) for key, value in prediction.items() if torch.is_tensor(value)}, + "attention_shapes": {key: list(value.shape) for key, value in prediction["attention"].items()}, + } + (args.output_dir / "real_batch_smoke.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + draw_overlay(batch, prediction, args.output_dir / "real_batch_prediction_overlay.jpg") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/split_phase7_h2o_train_cache.py b/home/wuyifan/EgoNet_train_20261008/scripts/split_phase7_h2o_train_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..add4ccef194d122b76ef5d116d75a15fe37c347a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/split_phase7_h2o_train_cache.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Create deterministic recording-group H2O train-fit/heldout cache manifests.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def assign_group_folds(rows: list[dict[str, Any]], folds: int, seed: int) -> dict[str, int]: + if folds < 2: + raise ValueError("at least two folds are required") + subjects: dict[str, set[str]] = defaultdict(set) + group_subject: dict[str, str] = {} + for row in rows: + if str(row.get("dataset_id", "")).upper() != "H2O": + raise ValueError("H2O train cache split refuses non-H2O rows") + group = str(row["physical_recording_id"]) + subject = str(row["subject_id"]) + if group in group_subject and group_subject[group] != subject: + raise ValueError(f"physical recording spans subjects: {group}") + group_subject[group] = subject + subjects[subject].add(group) + assignments: dict[str, int] = {} + for subject, groups in sorted(subjects.items()): + ordered = sorted(groups, key=lambda group: hashlib.sha256( + f"{seed}|{subject}|{group}".encode("utf-8") + ).hexdigest()) + for index, group in enumerate(ordered): + assignments[group] = index % folds + return assignments + + +def split_rows( + rows: list[dict[str, Any]], assignments: dict[str, int], heldout_fold: int, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + fit, heldout = [], [] + for row in rows: + target = heldout if assignments[str(row["physical_recording_id"])] == heldout_fold else fit + target.append(row) + if not fit or not heldout: + raise ValueError("fit and heldout manifests must both be nonempty") + fit_groups = {row["physical_recording_id"] for row in fit} + heldout_groups = {row["physical_recording_id"] for row in heldout} + if fit_groups & heldout_groups: + raise AssertionError("physical recording leakage across H2O train split") + return fit, heldout + + +def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), encoding="utf-8", + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--cache-report", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--folds", type=int, default=5) + parser.add_argument("--heldout-fold", type=int, default=0) + parser.add_argument("--seed", type=int, default=20260717) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + if not 0 <= args.heldout_fold < args.folds: + parser.error("heldout fold is outside the fold range") + cache_report = json.loads(args.cache_report.read_text(encoding="utf-8")) + if ( + cache_report.get("status") != "complete" + or cache_report.get("dataset") != "H2O" + or cache_report.get("split_role") != "official_train" + or cache_report.get("h2o_official_validation_used") is not False + or cache_report.get("official_test_used") is not False + or cache_report["cache_manifest"]["sha256"] != sha256(args.cache_manifest) + ): + parser.error("cache report does not prove a complete official-train-only cache") + rows = [ + json.loads(line) for line in args.cache_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + assignments = assign_group_folds(rows, args.folds, args.seed) + fit, heldout = split_rows(rows, assignments, args.heldout_fold) + args.output_dir.mkdir(parents=True) + fit_path = args.output_dir / "train_fit.jsonl" + heldout_path = args.output_dir / "train_group_heldout.jsonl" + write_jsonl(fit_path, fit) + write_jsonl(heldout_path, heldout) + record = { + "status": "frozen_h2o_train_group_split", "schema_version": "phase7_h2o_train_group_cv_v1", + "source_cache_manifest": { + "path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest), + }, + "folds": args.folds, "heldout_fold": args.heldout_fold, "seed": args.seed, + "group_key": "(dataset_id, subject_id, physical_recording_id)", + "fit": { + "path": str(fit_path.resolve()), "sha256": sha256(fit_path), "clips": len(fit), + "recordings": len({row["physical_recording_id"] for row in fit}), + }, + "heldout": { + "path": str(heldout_path.resolve()), "sha256": sha256(heldout_path), + "clips": len(heldout), + "recordings": len({row["physical_recording_id"] for row in heldout}), + }, + "assignments": assignments, "recording_overlap": [], + "h2o_official_validation_used": False, "official_test_used": False, + } + (args.output_dir / "split.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_core.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_core.py new file mode 100644 index 0000000000000000000000000000000000000000..5e82cefcfac1b2f5833989ea3e5058a087bbd01f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_core.py @@ -0,0 +1,405 @@ +#!/usr/bin/env python3 +"""Summarize the pre-registered Phase 3 decoder/temporal core matrix.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import Iterable + +import numpy as np + + +CHECKPOINT_ROLES = ( + "step_025k", "step_050k", "step_075k", "step_100k", + "best_absolute", "best_z", "final", +) +FRAME_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "wrong_side_preference", +) +REPORT_METRICS = FRAME_METRICS + ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "identity_switch_fraction", +) +PAIR_DEFINITIONS = ( + ("l0_temporal", "L0", "T1", "L0", "T0"), + ("l1_temporal", "L1", "T1", "L1", "T0"), + ("alternating_without_temporal", "L1", "T0", "L0", "T0"), + ("alternating_with_temporal", "L1", "T1", "L0", "T1"), + ("hybrid_reread_vs_sequential", "L2", "T1", "L0", "T1"), + ("hybrid_reread_vs_alternating", "L2", "T1", "L1", "T1"), +) +OBSERVATION_KEY = ( + "clip_index", "time_index", "take", "subject", "sequence", + "frame_id", "side", "annotation_valid", "annotation_state", +) +TEMPORAL_OBSERVATION_KEY = ( + "clip_index", "transition_index", "take", "subject", "sequence", + "frame_id_from", "frame_id_to", "side", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: Iterable[dict[str, object]]) -> None: + rows = list(rows) + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fieldnames = list(rows[0]) + if any(list(row) != fieldnames for row in rows): + raise ValueError(f"inconsistent CSV fields for {path}") + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: str | None) -> float | None: + if value is None or value == "": + return None + result = float(value) + return result if math.isfinite(result) else None + + +def paired_take_differences( + candidate_rows: list[dict[str, str]], + reference_rows: list[dict[str, str]], + metric: str, + observation_key: tuple[str, ...] = OBSERVATION_KEY, +) -> dict[str, float]: + if len(candidate_rows) != len(reference_rows): + raise ValueError("paired evaluations have different observation counts") + take_values: dict[str, list[float]] = defaultdict(list) + frame_values = [] + for candidate, reference in zip(candidate_rows, reference_rows, strict=True): + if any(candidate[key] != reference[key] for key in observation_key): + raise ValueError("paired evaluations do not have identical observation order") + candidate_value = optional_float(candidate.get(metric)) + reference_value = optional_float(reference.get(metric)) + if candidate_value is None or reference_value is None: + continue + difference = candidate_value - reference_value + take_values[candidate["take"]].append(difference) + frame_values.append(difference) + if not take_values: + raise ValueError(f"no paired values for {metric}") + take_means = np.asarray([ + np.mean(values, dtype=np.float64) for _, values in sorted(take_values.items()) + ], dtype=np.float64) + return { + "take_equal_mean_delta": float(take_means.mean()), + "frame_weighted_mean_delta": float(np.mean(frame_values, dtype=np.float64)), + "take_count": int(take_means.size), + "observation_count": int(len(frame_values)), + "take_means": take_means, + } + + +def bootstrap_take_values( + take_values: np.ndarray, + seed: int = 20260716, + samples: int = 10_000, +) -> tuple[float, float]: + if take_values.ndim != 1 or take_values.size == 0: + raise ValueError("take_values must be a non-empty vector") + rng = np.random.default_rng(seed) + indices = rng.integers(0, take_values.size, size=(samples, take_values.size)) + means = take_values[indices].mean(axis=1) + return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5)) + + +def metric_mean(report: dict, name: str) -> float | None: + entry = report["metrics"].get(name) + if entry is not None: + return entry.get("mean") + if name in {"translation_x_mae_mm", "translation_y_mae_mm"}: + components = [ + report["metrics"][f"{side}_{name}"] for side in ("left", "right") + ] + count = sum(int(component["count"]) for component in components) + if count: + return sum( + float(component["mean"]) * int(component["count"]) + for component in components + ) / count + return None + + +def attention_mean(report: dict, name: str) -> float | None: + entry = report["attention"].get(name) + return None if entry is None else entry.get("mean") + + +def load_report(path: Path) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("official_test_used") is not False: + raise ValueError(f"invalid formal evaluation: {path}") + if report.get("split_role") != "official_validation" or report.get("clips") != 1495: + raise ValueError(f"incomplete or non-validation evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--temporal-evaluation-root", type=Path) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + report_paths = sorted(args.evaluation_root.glob("core_*/*/evaluation.json")) + if len(report_paths) != 210: + raise ValueError(f"expected 210 checkpoint evaluations, found {len(report_paths)}") + + all_rows = [] + best_rows = [] + reports_by_key: dict[tuple[str, str, str, int, str], tuple[Path, dict]] = {} + checkpoints: dict[str, dict[str, object]] = {} + collected_bootstrap = [] + for path in report_paths: + report = load_report(path) + config = report["config"] + experiment = config["experiment"] + run_name = path.parent.parent.name + role = path.parent.name + if role not in CHECKPOINT_ROLES: + raise ValueError(f"unregistered checkpoint role: {role}") + seed = int(config["seed"]) + training_summary = json.loads((args.run_root / run_name / "summary.json").read_text(encoding="utf-8")) + row: dict[str, object] = { + "run": run_name, + "modality": experiment["modality"], + "layout": experiment["layout"], + "temporal": experiment["temporal"], + "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "rgb_same_peak": attention_mean(report, "rgb_same_peak"), + "rgb_left_right_cosine": attention_mean(report, "rgb_left_right_cosine"), + "temporal_normalized_entropy": attention_mean(report, "temporal_normalized_entropy"), + "temporal_diagonal": attention_mean(report, "temporal_diagonal"), + "depth_fusion_gate": attention_mean(report, "depth_fusion_gate"), + "depth_fusion_gate_raw": attention_mean(report, "depth_fusion_gate_raw"), + "rgb_update_norm": attention_mean(report, "rgb_update_norm"), + "depth_update_norm": attention_mean(report, "depth_update_norm"), + "gated_depth_update_norm": attention_mean(report, "gated_depth_update_norm"), + "trainable_parameters": training_summary["trainable_parameters"], + "frozen_parameters": training_summary["frozen_parameters"], + "peak_vram_gib": training_summary["peak_vram_gib"], + "training_frames_per_s": training_summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + reports_by_key[(experiment["modality"], experiment["layout"], experiment["temporal"], seed, role)] = (path, report) + for bootstrap in report["bootstrap"]: + collected_bootstrap.append({ + "run": run_name, "modality": experiment["modality"], + "layout": experiment["layout"], "temporal": experiment["temporal"], + "seed": seed, "checkpoint_role": role, **bootstrap, + }) + checkpoint_record = checkpoints.setdefault(run_name, { + "config": config["name"], "modality": experiment["modality"], + "layout": experiment["layout"], "temporal": experiment["temporal"], + "seed": seed, "roles": {}, + }) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + write_csv(args.output_dir / "checkpoint_comparison.csv", all_rows) + write_csv(args.output_dir / "comparison.csv", best_rows) + write_csv(args.output_dir / "bootstrap_ci.csv", collected_bootstrap) + (args.output_dir / "checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for group_key in sorted({ + (row["modality"], row["layout"], row["temporal"]) for row in best_rows + }): + group = [row for row in best_rows if (row["modality"], row["layout"], row["temporal"]) == group_key] + if len(group) != 3: + raise ValueError(f"expected three seeds for {group_key}, got {len(group)}") + record: dict[str, object] = { + "modality": group_key[0], "layout": group_key[1], "temporal": group_key[2], + "seeds": [row["seed"] for row in group], + } + for metric in REPORT_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), + "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = {"mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1))} + aggregate.append(record) + + paired_rows = [] + for modality in ("M0", "M3"): + for comparison, candidate_layout, candidate_temporal, reference_layout, reference_temporal in PAIR_DEFINITIONS: + per_metric_by_seed: dict[str, list[dict[str, float]]] = defaultdict(list) + for seed in (20260716, 20260717, 20260718): + candidate_path, _ = reports_by_key[(modality, candidate_layout, candidate_temporal, seed, "best_absolute")] + reference_path, _ = reports_by_key[(modality, reference_layout, reference_temporal, seed, "best_absolute")] + candidate_rows = read_csv(candidate_path.parent / "per_hand_frame_metrics.csv") + reference_rows = read_csv(reference_path.parent / "per_hand_frame_metrics.csv") + for metric in FRAME_METRICS: + result = paired_take_differences(candidate_rows, reference_rows, metric) + per_metric_by_seed[metric].append({"seed": seed, **result}) + for metric in FRAME_METRICS: + results = per_metric_by_seed[metric] + stacked = np.stack([result["take_means"] for result in results], axis=0) + take_values = stacked.mean(axis=0) + ci_low, ci_high = bootstrap_take_values(take_values, args.seed, args.bootstrap_samples) + seed_deltas = [float(result["take_equal_mean_delta"]) for result in results] + paired_rows.append({ + "modality": modality, + "comparison": comparison, + "candidate": f"{candidate_layout}-{candidate_temporal}", + "reference": f"{reference_layout}-{reference_temporal}", + "metric": metric, + "delta_definition": "candidate_minus_reference_lower_is_better", + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "take_count": int(results[0]["take_count"]), + "observations_per_seed": int(results[0]["observation_count"]), + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + write_csv(args.output_dir / "paired_bootstrap_ci.csv", paired_rows) + + paired_temporal_rows = [] + if args.temporal_evaluation_root is not None: + temporal_metrics = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", + ) + for modality in ("M0", "M3"): + for comparison, candidate_layout, candidate_temporal, reference_layout, reference_temporal in PAIR_DEFINITIONS: + per_metric_by_seed: dict[str, list[dict[str, float]]] = defaultdict(list) + for seed in (20260716, 20260717, 20260718): + candidate_source, _ = reports_by_key[(modality, candidate_layout, candidate_temporal, seed, "best_absolute")] + reference_source, _ = reports_by_key[(modality, reference_layout, reference_temporal, seed, "best_absolute")] + candidate_path = ( + args.temporal_evaluation_root / candidate_source.parent.parent.name + / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + reference_path = ( + args.temporal_evaluation_root / reference_source.parent.parent.name + / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + candidate_rows = read_csv(candidate_path) + reference_rows = read_csv(reference_path) + for metric in temporal_metrics: + result = paired_take_differences( + candidate_rows, reference_rows, metric, + observation_key=TEMPORAL_OBSERVATION_KEY, + ) + per_metric_by_seed[metric].append({"seed": seed, **result}) + for metric in temporal_metrics: + results = per_metric_by_seed[metric] + stacked = np.stack([result["take_means"] for result in results], axis=0) + take_values = stacked.mean(axis=0) + ci_low, ci_high = bootstrap_take_values(take_values, args.seed, args.bootstrap_samples) + seed_deltas = [float(result["take_equal_mean_delta"]) for result in results] + paired_temporal_rows.append({ + "modality": modality, + "comparison": comparison, + "candidate": f"{candidate_layout}-{candidate_temporal}", + "reference": f"{reference_layout}-{reference_temporal}", + "metric": metric, + "delta_definition": "candidate_minus_reference_lower_is_better", + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "take_count": int(results[0]["take_count"]), + "observations_per_seed": int(results[0]["observation_count"]), + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + write_csv(args.output_dir / "paired_temporal_bootstrap_ci.csv", paired_temporal_rows) + + payload = { + "status": "complete", + "official_test_used": False, + "checkpoint_selection": "best_absolute selected only by the registered fixed 256-clip validation subset", + "evaluations": len(report_paths), + "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_bootstrap": { + "path": str((args.output_dir / "paired_bootstrap_ci.csv").resolve()), + "definition": "For each seed and take, compute paired per-observation candidate-reference deltas; average seeds within take; bootstrap the 24 take means.", + "temporal_path": ( + str((args.output_dir / "paired_temporal_bootstrap_ci.csv").resolve()) + if paired_temporal_rows else None + ), + "temporal_metric_limitation": ( + None if paired_temporal_rows + else "Provide --temporal-evaluation-root with transition exports to compute paired temporal take CIs." + ), + }, + "source_hashes": { + "full_validation_launcher_provenance": sha256(args.evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(report_paths), + "best_absolute_runs": len(best_rows), "paired_rows": len(paired_rows), + "paired_temporal_rows": len(paired_temporal_rows), + "output_dir": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_depth_fusion.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_depth_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2a737a31f0909731dfc210277fff9c0a27cda9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_depth_fusion.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +"""Summarize the registered Phase 3 Depth fusion/representation controls.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + write_csv, + ) + + +VARIANTS = ("P0_fixed05", "gate025", "learned_gate", "geometry") +NEW_VARIANTS = ("gate025", "learned_gate", "geometry") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def run_name(variant: str, seed: int) -> str: + if variant == "P0_fixed05": + return f"core_m3_l1_t1_s{seed}" + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_variant = None if variant == "P0_fixed05" else variant + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or (expected_variant is not None and experiment.get("variant") != expected_variant) + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal depth-fusion evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--new-run-root", type=Path, default=Path("artifacts/phase3/depth_fusion_runs")) + parser.add_argument("--core-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--new-evaluation-root", type=Path, default=Path("artifacts/phase3/depth_fusion_full_validation")) + parser.add_argument("--core-temporal-root", type=Path, default=Path("artifacts/phase3/temporal_position_p0_diagnostics")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + rows = [] + best_rows = [] + checkpoints: dict[str, dict] = {} + bootstrap_rows = [] + for variant in VARIANTS: + evaluation_root = args.core_evaluation_root if variant == "P0_fixed05" else args.new_evaluation_root + run_root = args.core_run_root if variant == "P0_fixed05" else args.new_run_root + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal run: {name}") + checkpoint_record = {"variant": variant, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + report_path = evaluation_root / name / role / "evaluation.json" + report = load_report(report_path, variant, seed) + reports[(variant, seed, role)] = (report_path, report) + row = { + "run": name, "variant": variant, "modality": "M3", + "layout": "L1", "temporal": "T1", "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in ( + "temporal_normalized_entropy", "temporal_diagonal", + "temporal_update_norm", "depth_fusion_gate", + "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ): + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, **item, + } for item in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(report_path.resolve()), + } + + expected_rows = len(VARIANTS) * len(SEEDS) * len(CHECKPOINT_ROLES) + if len(rows) != expected_rows or len(best_rows) != len(VARIANTS) * len(SEEDS): + raise ValueError(f"expected {expected_rows} rows, got {len(rows)}") + write_csv(args.output_dir / "depth_fusion_checkpoint_comparison.csv", rows) + write_csv(args.output_dir / "depth_fusion_comparison.csv", best_rows) + write_csv(args.output_dir / "depth_fusion_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "depth_fusion_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant, "modality": "M3", "layout": "L1", "temporal": "T1"} + for metric in FRAME_METRICS + TEMPORAL_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), + "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", "peak_vram_gib", + "training_frames_per_s", + ): + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + report_path, _ = reports[(variant, seed, "best_absolute")] + frame_cache[(variant, seed)] = read_csv(report_path.parent / "per_hand_frame_metrics.csv") + temporal_root = args.core_temporal_root if variant == "P0_fixed05" else args.new_evaluation_root + temporal_cache[(variant, seed)] = read_csv( + temporal_root / run_name(variant, seed) / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for variant in NEW_VARIANTS: + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {"candidate": frame_cache[(variant, seed)], "P0": frame_cache[("P0_fixed05", seed)]}, + metric, {"candidate": 1.0, "P0": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": f"{variant}-P0_fixed05", + "contrast": "+1*candidate -1*P0", + "metric": metric, + "delta_definition": "candidate minus fixed-gate-0.5 P0; lower is better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_fusion_bootstrap_ci.csv", paired_rows) + + temporal_rows = [] + for variant in NEW_VARIANTS: + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {"candidate": temporal_cache[(variant, seed)], "P0": temporal_cache[("P0_fixed05", seed)]}, + metric, {"candidate": 1.0, "P0": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": f"{variant}-P0_fixed05", + "contrast": "+1*candidate -1*P0", + "metric": metric, + "delta_definition": "candidate minus fixed-gate-0.5 P0; lower is better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_fusion_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", + "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "formal_validation_clips_per_run": 1495, + "evaluations": len(rows), + "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_depth_fusion_bootstrap_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_depth_fusion_temporal_ci.csv").resolve()), + "source_hashes": { + "new_validation_launcher": sha256(args.new_evaluation_root / "launcher_provenance.json"), + "core_validation_launcher": sha256(args.core_evaluation_root / "launcher_provenance.json"), + "matrix": sha256(Path("artifacts/phase3/reports/depth_fusion_new_runs.csv")), + }, + } + (args.output_dir / "depth_fusion_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "best_absolute_runs": len(best_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_dropout.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..f35a51389b1ce94b0b81b50bdffe572d73543924 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_dropout.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Summarize the same-commit Phase 3 geometry modality-dropout matrix.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) + + +VARIANTS = ("dropout00_geometry", "dropout02_geometry") + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown dropout variant: {variant}") + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "depth_modality_dropout" + or experiment.get("variant") != variant + or experiment.get("modality") != "M3" + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid complete-modality dropout evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row[metric] is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--run-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_runs_commit7583772"), + ) + parser.add_argument( + "--evaluation-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports = {} + checkpoint_rows = [] + best_rows = [] + checkpoints = {} + bootstrap_rows = [] + diagnostics = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((args.run_root / name / "summary.json").read_text(encoding="utf-8")) + provenance = json.loads( + (args.run_root / name / "run_provenance.json").read_text(encoding="utf-8") + ) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != "75837726f7eb8232b747932cbf536a834821e24d" + ): + raise ValueError(f"invalid formal dropout training run: {name}") + checkpoint_record = {"variant": variant, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = args.evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("dropout matrix is incomplete") + write_csv(args.output_dir / "depth_dropout_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "depth_dropout_comparison.csv", best_rows) + write_csv(args.output_dir / "depth_dropout_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "depth_dropout_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + diagnostics + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "dropout02": frame_cache[("dropout02_geometry", seed)], + "dropout00": frame_cache[("dropout00_geometry", seed)], + }, + metric, {"dropout02": 1.0, "dropout00": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": "dropout02_geometry-dropout00_geometry", + "metric": metric, "delta_definition": "dropout02 minus dropout00; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_bootstrap_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "dropout02": temporal_cache[("dropout02_geometry", seed)], + "dropout00": temporal_cache[("dropout00_geometry", seed)], + }, + metric, {"dropout02": 1.0, "dropout00": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": "dropout02_geometry-dropout00_geometry", + "metric": metric, "delta_definition": "dropout02 minus dropout00; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": "75837726f7eb8232b747932cbf536a834821e24d", + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str( + (args.output_dir / "paired_depth_dropout_bootstrap_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_depth_dropout_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "depth_dropout_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_dropout_dose.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_dropout_dose.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cbe8b0c7d099c4541ed67e9338ec4ffe15eac6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_dropout_dose.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +"""Summarize D.2 endpoints together with the D.3 dropout-dose sweep.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) + + +TRAINING_COMMIT = "75837726f7eb8232b747932cbf536a834821e24d" +VARIANTS = ( + "dropout00_geometry", "dropout005_geometry", + "dropout010_geometry", "dropout02_geometry", +) +ENDPOINT_VARIANTS = {"dropout00_geometry", "dropout02_geometry"} +COMPARISONS = ( + ("dropout005_geometry", "dropout00_geometry"), + ("dropout010_geometry", "dropout00_geometry"), + ("dropout02_geometry", "dropout00_geometry"), + ("dropout010_geometry", "dropout005_geometry"), + ("dropout02_geometry", "dropout010_geometry"), + ("dropout02_geometry", "dropout005_geometry"), +) + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown dropout-dose variant: {variant}") + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def matrix_for(variant: str) -> str: + return ( + "depth_modality_dropout" + if variant in ENDPOINT_VARIANTS else "depth_modality_dropout_dose" + ) + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row[metric] is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != matrix_for(variant) + or experiment.get("variant") != variant + or experiment.get("modality") != "M3" + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid complete dropout-dose evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--endpoint-run-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_runs_commit7583772"), + ) + parser.add_argument( + "--dose-run-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_runs_commit7583772"), + ) + parser.add_argument( + "--endpoint-evaluation-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--dose-evaluation-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + diagnostics = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + reports = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + for variant in VARIANTS: + run_root = ( + args.endpoint_run_root if variant in ENDPOINT_VARIANTS else args.dose_run_root + ) + evaluation_root = ( + args.endpoint_evaluation_root + if variant in ENDPOINT_VARIANTS else args.dose_evaluation_root + ) + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text()) + provenance = json.loads((run_root / name / "run_provenance.json").read_text()) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid dropout-dose training run: {name}") + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 84 or len(best_rows) != 12: + raise ValueError("dropout-dose matrix is incomplete") + write_csv(args.output_dir / "dropout_dose_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "dropout_dose_comparison.csv", best_rows) + write_csv(args.output_dir / "dropout_dose_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "dropout_dose_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n" + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + diagnostics + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + temporal_rows = [] + for candidate, reference in COMPARISONS: + comparison = f"{candidate}-{reference}" + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(candidate, seed)], + "reference": frame_cache[(reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(candidate, seed)], + "reference": temporal_cache[(reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_dropout_dose_ci.csv", paired_rows) + write_csv(args.output_dir / "paired_dropout_dose_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_dropout_dose_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_dropout_dose_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "dropout_dose_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_dropout_dose_fallback.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_dropout_dose_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..2daef68597394f8412587333dcbf489ce2f188f0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_dropout_dose_fallback.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""Summarize complete and missing-modality behavior across four dropout doses.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_dropout_dose import ( + COMPARISONS as DOSE_COMPARISONS, ENDPOINT_VARIANTS, VARIANTS, + matrix_for, run_name, + ) + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_dropout_dose import ( + COMPARISONS as DOSE_COMPARISONS, ENDPOINT_VARIANTS, VARIANTS, + matrix_for, run_name, + ) + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_depth, expected_k = CONDITIONS[condition] + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != matrix_for(variant) + or experiment.get("variant") != variant + or int(report["config"]["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid dropout-dose fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--endpoint-complete-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--dose-complete-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument( + "--endpoint-fallback-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_fallback"), + ) + parser.add_argument( + "--dose-fallback-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_fallback"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + diagnostics = ( + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + for variant in VARIANTS: + if variant in ENDPOINT_VARIANTS: + root = ( + args.endpoint_complete_root if condition == "complete" + else args.endpoint_fallback_root / condition + ) + else: + root = ( + args.dose_complete_root if condition == "complete" + else args.dose_fallback_root / condition + ) + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 48: + raise ValueError(f"expected 48 dropout-dose fallback rows, got {len(rows)}") + write_csv(args.output_dir / "dropout_dose_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + diagnostics: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": ( + float(np.std(values, ddof=1)) if len(values) > 1 else None + ), + } + aggregate.append(record) + + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + for candidate, reference in DOSE_COMPARISONS: + contrasts.append(( + f"{condition}:{candidate}-{reference}", + (condition, candidate), (condition, reference), + )) + + paired_rows = [] + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_dropout_dose_fallback_ci.csv", paired_rows) + write_csv( + args.output_dir / "paired_dropout_dose_fallback_temporal_ci.csv", temporal_rows + ) + + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + equality.append({ + "variant": variant, + "seed": seed, + "frame_metrics_identical": ( + frame_cache[("drop_k", variant, seed)] + == frame_cache[("drop_both", variant, seed)] + ), + }) + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "paired_frame": str( + (args.output_dir / "paired_dropout_dose_fallback_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_dropout_dose_fallback_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "dropout_dose_fallback_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + all_equal = all(row["frame_metrics_identical"] for row in equality) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all_equal, + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + if not all_equal: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_fallback.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..5e26939c7294190d782e80c1a8713655ecf32cb7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_fallback.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""Summarize missing Depth/K inference behavior for the geometry dropout matrix.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from scripts.summarize_phase3_dropout import VARIANTS, run_name +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from summarize_phase3_dropout import VARIANTS, run_name + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_depth, expected_k = CONDITIONS[condition] + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("variant") != variant + or int(report["config"]["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--complete-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--fallback-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_fallback"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + diagnostics = ( + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + reports = {} + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + root = args.complete_root if condition == "complete" else args.fallback_root / condition + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + reports[(condition, variant, seed)] = path + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 24: + raise ValueError(f"expected 24 fallback rows, got {len(rows)}") + write_csv(args.output_dir / "depth_dropout_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + diagnostics: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + } + aggregate.append(record) + + paired_rows = [] + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + contrasts.append(( + f"{condition}:dropout02-dropout00", + (condition, "dropout02_geometry"), + (condition, "dropout00_geometry"), + )) + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_fallback_ci.csv", paired_rows) + + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_fallback_temporal_ci.csv", temporal_rows) + + # Geometry needs K for XYZ construction, so drop-K and drop-both should be identical. + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + k_rows = frame_cache[("drop_k", variant, seed)] + both_rows = frame_cache[("drop_both", variant, seed)] + equality.append({ + "variant": variant, "seed": seed, + "frame_metrics_identical": k_rows == both_rows, + }) + payload = { + "status": "complete", "official_test_used": False, + "geometry_k_dependency": ( + "When K is unavailable, XYZ/logZ geometry tokens and ray conditioning are both " + "disabled. Therefore drop_k and drop_both are expected to be identical." + ), + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "paired_frame": str( + (args.output_dir / "paired_depth_dropout_fallback_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_depth_dropout_fallback_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "depth_dropout_fallback_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all( + row["frame_metrics_identical"] for row in equality + ), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_long_tail.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_long_tail.py new file mode 100644 index 0000000000000000000000000000000000000000..d113631c873a7e249781efb84b821f65e074cebd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_long_tail.py @@ -0,0 +1,337 @@ +#!/usr/bin/env python3 +"""Summarize the preregistered Phase 3 100k-to-150k low-LR tail.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, sha256, write_csv, + ) + from scripts.summarize_phase3_photometric import DIAGNOSTICS +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, sha256, write_csv, + ) + from summarize_phase3_photometric import DIAGNOSTICS + + +TRAINING_COMMIT = "d4019222835132fcbcc850ba49e6e0b53ab352b3" +REFERENCE_ROLE = "reference_best_absolute" +TAIL_ROLES = ( + "tail_step_125k", "tail_step_150k", "tail_best_absolute", + "tail_best_z", "tail_final", +) +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", "translation_z_mae_mm", +) + + +def reference_name(seed: int) -> str: + return f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + + +def tail_name(seed: int) -> str: + return f"longtail_{reference_name(seed)}" + + +def load_report(path: Path, seed: int, tail: bool) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + override = report.get("inference_modality_override", {}) + expected_matrix = "low_lr_tail" if tail else "photometric_augmentation" + expected_variant = ( + "photometric_on_r640x368_tail150k" if tail + else "photometric_on_r640x368" + ) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != expected_matrix + or experiment.get("variant") != expected_variant + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or int(config["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid long-tail evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def load_resume_audit(path: Path) -> dict: + audit = json.loads(path.read_text(encoding="utf-8")) + expected = {tail_name(seed) for seed in SEEDS} + rows = audit.get("runs", []) + if ( + audit.get("status") != "passed" + or audit.get("official_test_used") is not False + or {row.get("run") for row in rows} != expected + or any( + row.get("reference_step") != 150_000 + or row.get("resumed_step") != 150_000 + or not all(row.get(key) is True for key in ( + "model_exact", "optimizer_exact", "python_rng_exact", + "numpy_rng_exact", "torch_rng_exact", "cuda_rng_exact", + )) + for row in rows + ) + ): + raise ValueError(f"invalid long-tail exact-resume audit: {path}") + return {"status": "passed", "runs": len(rows), "path": str(path.resolve()), "sha256": sha256(path)} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--reference-evaluation-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--tail-run-root", type=Path, + default=Path("artifacts/phase3/long_tail_runs_commitd401922"), + ) + parser.add_argument( + "--tail-evaluation-root", type=Path, + default=Path("artifacts/phase3/long_tail_full_validation"), + ) + parser.add_argument( + "--resume-root", type=Path, + default=Path("artifacts/phase3/long_tail_resume_from125k"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports = {} + checkpoint_rows = [] + checkpoints = {} + training_audit = {} + for seed in SEEDS: + name = tail_name(seed) + run_dir = args.tail_run_root / name + summary = json.loads((run_dir / "summary.json").read_text(encoding="utf-8")) + provenance_path = Path(summary["run_provenance"]) + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + expected_resume = ( + Path("/SSD3/jiasen/foundation_hand/phase3_artifacts/photometric_runs_commit239b0bf") + / reference_name(seed) / "step_0100000_final.pt" + ) + schedule = summary.get("learning_rate_schedule", {}) + if ( + summary.get("status") != "completed" + or summary.get("start_step") != 100_000 + or summary.get("completed_step") != 150_000 + or schedule.get("total_steps") != 100_000 + or schedule.get("training_max_steps") != 150_000 + or schedule.get("min_lr") != 5e-6 + or provenance.get("git_commit") != TRAINING_COMMIT + or provenance.get("git_status") != "" + or Path(provenance.get("resume_checkpoint", "")).resolve() != expected_resume.resolve() + ): + raise ValueError(f"invalid long-tail training run: {name}") + training_audit[name] = { + "seed": seed, "start_step": 100_000, "completed_step": 150_000, + "lr_schedule_steps": 100_000, "min_lr": 5e-6, + "provenance": str(provenance_path), "provenance_sha256": sha256(provenance_path), + } + checkpoints[name] = {"seed": seed, "roles": {}} + paths = { + REFERENCE_ROLE: ( + args.reference_evaluation_root / reference_name(seed) + / "best_absolute" / "evaluation.json" + ), + **{ + role: args.tail_evaluation_root / name / role / "evaluation.json" + for role in TAIL_ROLES + }, + } + for role, path in paths.items(): + tail = role != REFERENCE_ROLE + report = load_report(path, seed, tail) + reports[(role, seed)] = path + row = { + "run": name, "seed": seed, "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "tail_training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + if len(checkpoint_rows) != 18: + raise ValueError(f"expected 18 reference/tail rows, got {len(checkpoint_rows)}") + write_csv(args.output_dir / "long_tail_checkpoint_comparison.csv", checkpoint_rows) + (args.output_dir / "long_tail_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + primary_roles = (REFERENCE_ROLE, "tail_best_absolute") + aggregate = [] + for role in primary_roles: + group = [row for row in checkpoint_rows if row["checkpoint_role"] == role] + record = {"role": role} + for metric in FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS: + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + joint_cache = {} + for role in primary_roles: + for seed in SEEDS: + parent = reports[(role, seed)].parent + frame_cache[(role, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(role, seed)] = read_csv(parent / "per_temporal_transition_metrics.csv") + joint_cache[(role, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in read_csv(parent / "per_joint_metrics.csv") + } + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + return contrast_take_differences( + { + "reference": cache[(REFERENCE_ROLE, seed)], + "tail": cache[("tail_best_absolute", seed)], + }, + metric, {"reference": -1.0, "tail": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in FRAME_METRICS: + paired_rows.append({ + "comparison": "tail_best-reference_best", "metric": metric, + "delta_definition": "tail minus reference; lower is better", + **aggregate_seed_contrasts( + [paired(metric, seed) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ), + }) + write_csv(args.output_dir / "paired_long_tail_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + temporal_rows.append({ + "comparison": "tail_best-reference_best", "metric": metric, + "delta_definition": "tail minus reference; lower is better", + **aggregate_seed_contrasts( + [paired(metric, seed, temporal=True) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ), + }) + write_csv(args.output_dir / "paired_long_tail_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": "tail_best-reference_best", + "subgroup_axis": subgroup[0], "subgroup_value": subgroup[1], + "metric": metric, + "delta_definition": "tail minus reference; lower is better", + } + try: + result = aggregate_seed_contrasts( + [paired(metric, seed, subgroup=subgroup) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ) + except ValueError as error: + if "no paired values" not in str(error): + raise + result = { + "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, + "seed_20260717_delta": None, + "seed_20260718_delta": None, + "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + } + available = False + else: + available = True + subgroup_rows.append({**prefix, "available": available, **result}) + write_csv(args.output_dir / "paired_long_tail_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + for side in ("left", "right"): + for joint_index in range(21): + reference = np.asarray([ + joint_cache[(REFERENCE_ROLE, seed)][(side, joint_index)] for seed in SEEDS + ]) + tail = np.asarray([ + joint_cache[("tail_best_absolute", seed)][(side, joint_index)] for seed in SEEDS + ]) + joint_rows.append({ + "side": side, "joint_index": joint_index, + "reference_seed_mean_mm": float(reference.mean()), + "tail_seed_mean_mm": float(tail.mean()), + "tail_minus_reference_seed_mean_mm": float((tail - reference).mean()), + "tail_minus_reference_seed_sample_std_mm": float((tail - reference).std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "long_tail_per_joint_comparison.csv", joint_rows) + + resume_audit = load_resume_audit(args.resume_root / "exact_resume_audit.json") + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(checkpoint_rows), "aggregate": aggregate, + "training_audit": training_audit, "exact_resume": resume_audit, + } + output = args.output_dir / "long_tail_comparison.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "output": str(output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_modality.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..086229a9170bafceb69ba11354aba9b9c2f33897 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_modality.py @@ -0,0 +1,445 @@ +#!/usr/bin/env python3 +"""Summarize the Phase 3 four-modality causal matrix.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import Iterable + +import numpy as np + + +SEEDS = (20260716, 20260717, 20260718) +MODALITIES = ("M0", "M1", "M2", "M3") +CHECKPOINT_ROLES = ( + "step_025k", "step_050k", "step_075k", "step_100k", + "best_absolute", "best_z", "final", +) +FRAME_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "wrong_side_preference", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", +) +REPORT_METRICS = FRAME_METRICS + TEMPORAL_METRICS +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", +) +FRAME_KEY = ( + "clip_index", "time_index", "take", "subject", "sequence", + "frame_id", "side", "annotation_valid", "annotation_state", +) +TEMPORAL_KEY = ( + "clip_index", "transition_index", "take", "subject", "sequence", + "frame_id_from", "frame_id_to", "side", +) +CONTRASTS = ( + ("K_without_depth", {"M1": 1.0, "M0": -1.0}), + ("K_with_depth", {"M3": 1.0, "M2": -1.0}), + ("Depth_without_K", {"M2": 1.0, "M0": -1.0}), + ("Depth_with_K", {"M3": 1.0, "M1": -1.0}), + ("Depth_K_interaction", {"M3": 1.0, "M2": -1.0, "M1": -1.0, "M0": 1.0}), +) +SUBGROUPS = ( + ("side", "left"), ("side", "right"), + ("hand_size_bucket", "small"), ("hand_size_bucket", "medium"), + ("hand_size_bucket", "large"), + ("depth_bucket", "near"), ("depth_bucket", "middle"), + ("depth_bucket", "far"), +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: Iterable[dict[str, object]]) -> None: + rows = list(rows) + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fieldnames = list(rows[0]) + if any(list(row) != fieldnames for row in rows): + raise ValueError(f"inconsistent CSV fields for {path}") + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: str | None) -> float | None: + if value is None or value == "": + return None + result = float(value) + return result if math.isfinite(result) else None + + +def run_name(modality: str, seed: int) -> str: + prefix = "core" if modality in {"M0", "M3"} else "modality" + return f"{prefix}_{modality.lower()}_l1_t1_s{seed}" + + +def load_report(path: Path, modality: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != modality + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal modality evaluation: {path}") + return report + + +def metric_mean(report: dict, name: str) -> float | None: + entry = report["metrics"].get(name) + if entry is not None: + return entry.get("mean") + if name in {"translation_x_mae_mm", "translation_y_mae_mm"}: + components = [report["metrics"][f"{side}_{name}"] for side in ("left", "right")] + count = sum(int(component["count"]) for component in components) + if count: + return sum( + float(component["mean"]) * int(component["count"]) + for component in components + ) / count + return None + + +def attention_mean(report: dict, name: str) -> float | None: + entry = report["attention"].get(name) + return None if entry is None else entry.get("mean") + + +def bootstrap(values: np.ndarray, seed: int, samples: int) -> tuple[float, float]: + if values.ndim != 1 or values.size == 0: + raise ValueError("bootstrap values must be a non-empty vector") + rng = np.random.default_rng(seed) + indices = rng.integers(0, values.size, size=(samples, values.size)) + means = values[indices].mean(axis=1) + return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5)) + + +def contrast_take_differences( + rows_by_modality: dict[str, list[dict[str, str]]], + metric: str, + coefficients: dict[str, float], + observation_key: tuple[str, ...], + subgroup: tuple[str, str] | None = None, +) -> dict[str, object]: + modalities = tuple(coefficients) + reference_rows = rows_by_modality[modalities[0]] + if any(len(rows_by_modality[modality]) != len(reference_rows) for modality in modalities[1:]): + raise ValueError("contrast evaluations have different observation counts") + take_values: dict[str, list[float]] = defaultdict(list) + observation_values = [] + for index, reference in enumerate(reference_rows): + aligned = [rows_by_modality[modality][index] for modality in modalities] + if any( + any(row[key] != reference[key] for key in observation_key) + for row in aligned[1:] + ): + raise ValueError("contrast evaluations do not have identical observation order") + if subgroup is not None and reference.get(subgroup[0]) != subgroup[1]: + continue + values = [optional_float(row.get(metric)) for row in aligned] + if any(value is None for value in values): + continue + difference = sum( + coefficients[modality] * float(value) + for modality, value in zip(modalities, values, strict=True) + ) + take_values[reference["take"]].append(difference) + observation_values.append(difference) + if not take_values: + raise ValueError(f"no paired values for metric={metric}, subgroup={subgroup}") + return { + "take_means": { + take: float(np.mean(values, dtype=np.float64)) + for take, values in sorted(take_values.items()) + }, + "observation_mean": float(np.mean(observation_values, dtype=np.float64)), + "observation_count": len(observation_values), + } + + +def aggregate_seed_contrasts( + seed_results: list[dict[str, object]], seed: int, samples: int, +) -> dict[str, object]: + common_takes = set(seed_results[0]["take_means"]) + for result in seed_results[1:]: + common_takes &= set(result["take_means"]) + if not common_takes: + raise ValueError("seed contrasts have no common takes") + take_values = np.asarray([ + np.mean([result["take_means"][take] for result in seed_results]) + for take in sorted(common_takes) + ], dtype=np.float64) + ci_low, ci_high = bootstrap(take_values, seed, samples) + seed_deltas = [float(np.mean(list(result["take_means"].values()))) for result in seed_results] + return { + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "frame_weighted_delta_mean": float(np.mean([ + result["observation_mean"] for result in seed_results + ])), + "take_count": len(common_takes), + "observations_per_seed": int(seed_results[0]["observation_count"]), + "bootstrap_samples": samples, + "bootstrap_seed": seed, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--modality-run-root", type=Path, default=Path("artifacts/phase3/modality_runs")) + parser.add_argument("--core-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--modality-evaluation-root", type=Path, default=Path("artifacts/phase3/modality_full_validation")) + parser.add_argument("--core-temporal-root", type=Path, default=Path("artifacts/phase3/core_temporal_validation_v2")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + all_rows = [] + best_rows = [] + checkpoints: dict[str, dict[str, object]] = {} + collected_bootstrap = [] + for modality in MODALITIES: + evaluation_root = args.core_evaluation_root if modality in {"M0", "M3"} else args.modality_evaluation_root + run_root = args.core_run_root if modality in {"M0", "M3"} else args.modality_run_root + for seed in SEEDS: + name = run_name(modality, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal training run: {name}") + checkpoint_record = { + "modality": modality, "layout": "L1", "temporal": "T1", + "seed": seed, "roles": {}, + } + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, modality, seed) + reports[(modality, seed, role)] = (path, report) + row: dict[str, object] = { + "run": name, "modality": modality, "layout": "L1", "temporal": "T1", + "seed": seed, "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "temporal_normalized_entropy": attention_mean(report, "temporal_normalized_entropy"), + "temporal_diagonal": attention_mean(report, "temporal_diagonal"), + "depth_fusion_gate": attention_mean(report, "depth_fusion_gate"), + "depth_fusion_gate_raw": attention_mean(report, "depth_fusion_gate_raw"), + "rgb_update_norm": attention_mean(report, "rgb_update_norm"), + "depth_update_norm": attention_mean(report, "depth_update_norm"), + "gated_depth_update_norm": attention_mean(report, "gated_depth_update_norm"), + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + collected_bootstrap.extend({ + "run": name, "modality": modality, "seed": seed, + "checkpoint_role": role, **bootstrap_row, + } for bootstrap_row in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(all_rows) != 84 or len(best_rows) != 12: + raise ValueError(f"expected 84 checkpoint rows and 12 best rows, got {len(all_rows)}, {len(best_rows)}") + write_csv(args.output_dir / "modality_checkpoint_comparison.csv", all_rows) + write_csv(args.output_dir / "modality_comparison.csv", best_rows) + write_csv(args.output_dir / "modality_bootstrap_ci.csv", collected_bootstrap) + (args.output_dir / "modality_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for modality in MODALITIES: + group = [row for row in best_rows if row["modality"] == modality] + if len(group) != 3: + raise ValueError(f"expected three seeds for {modality}, got {len(group)}") + record: dict[str, object] = {"modality": modality, "layout": "L1", "temporal": "T1"} + for metric in REPORT_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + } + aggregate.append(record) + + frame_cache: dict[tuple[str, int], list[dict[str, str]]] = {} + temporal_cache: dict[tuple[str, int], list[dict[str, str]]] = {} + for modality in MODALITIES: + for seed in SEEDS: + report_path, _ = reports[(modality, seed, "best_absolute")] + frame_cache[(modality, seed)] = read_csv(report_path.parent / "per_hand_frame_metrics.csv") + temporal_root = args.core_temporal_root if modality in {"M0", "M3"} else args.modality_evaluation_root + temporal_cache[(modality, seed)] = read_csv( + temporal_root / run_name(modality, seed) / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for contrast, coefficients in CONTRASTS: + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {modality: frame_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "metric": metric, + "delta_definition": "contrast_delta_lower_is_better_except_interaction_is_additivity_residual", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_bootstrap_ci.csv", paired_rows) + + subgroup_rows = [] + unavailable_subgroups: set[tuple[str, str]] = set() + for contrast, coefficients in CONTRASTS[:4]: + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "subgroup_axis": subgroup[0], "subgroup": subgroup[1], "metric": metric, + "delta_definition": "contrast_delta_lower_is_better", + } + try: + seed_results = [ + contrast_take_differences( + {modality: frame_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, FRAME_KEY, subgroup, + ) + for seed in SEEDS + ] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable_subgroups.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, + "take_equal_mean_delta": None, "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, "seed_20260717_delta": None, + "seed_20260718_delta": None, "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_subgroup_ci.csv", subgroup_rows) + + temporal_rows = [] + for contrast, coefficients in CONTRASTS: + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {modality: temporal_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "metric": metric, + "delta_definition": "contrast_delta_lower_is_better_except_interaction_is_additivity_residual", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "formal_validation_clips_per_run": 1495, + "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "causal_contrasts": { + "paired_frame": str((args.output_dir / "paired_modality_bootstrap_ci.csv").resolve()), + "paired_subgroups": str((args.output_dir / "paired_modality_subgroup_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_modality_temporal_ci.csv").resolve()), + "definition": "Within each seed and observation, apply the registered modality contrast; average within take, average seeds within take, then bootstrap equal-weight take means.", + "unavailable_subgroups": [ + {"axis": axis, "value": value} + for axis, value in sorted(unavailable_subgroups) + ], + }, + "source_hashes": { + "core_validation_launcher": sha256(args.core_evaluation_root / "launcher_provenance.json"), + "modality_validation_launcher": sha256(args.modality_evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "modality_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(all_rows), + "best_absolute_runs": len(best_rows), "paired_rows": len(paired_rows), + "subgroup_rows": len(subgroup_rows), "temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_photometric.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_photometric.py new file mode 100644 index 0000000000000000000000000000000000000000..a6cef761d482c983cc6ad19adc664c7f0754d534 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_photometric.py @@ -0,0 +1,467 @@ +#!/usr/bin/env python3 +"""Summarize the paired Phase 3 photometric augmentation experiment.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) + + +TRAINING_COMMIT = "239b0bf8850dd5533d3b3f4236cf856b4e826af6" +VARIANTS = ("off", "on") +DIAGNOSTICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", +) +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", "translation_z_mae_mm", +) +SCIENTIFIC_LOG_EXCLUSIONS = { + "timestamp", "frames_per_s", "peak_vram_gib", "photometric_augmentation", +} + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown photometric variant: {variant}") + return f"photometric_{variant}_geometry_m3_l1_t1_r640x368_s{seed}" + + +def reference_run_name(seed: int) -> str: + return f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + augmentation = config.get("data", {}).get("photometric_augmentation", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "photometric_augmentation" + or experiment.get("variant") != f"photometric_{variant}_r640x368" + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or bool(augmentation.get("enabled")) != (variant == "on") + or int(config["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid formal photometric evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def canonical_scientific_record(record: dict) -> bytes: + filtered = { + key: value for key, value in record.items() + if key not in SCIENTIFIC_LOG_EXCLUSIONS + } + return json.dumps( + filtered, sort_keys=True, separators=(",", ":"), allow_nan=False, + ).encode("utf-8") + + +def audit_off_reference(off_path: Path, reference_path: Path) -> dict: + digest = hashlib.sha256() + compared = 0 + with off_path.open(encoding="utf-8") as off_handle, reference_path.open( + encoding="utf-8" + ) as reference_handle: + for compared, (off_line, reference_line) in enumerate( + zip(off_handle, reference_handle, strict=True), start=1, + ): + off_record = canonical_scientific_record(json.loads(off_line)) + reference_record = canonical_scientific_record(json.loads(reference_line)) + if off_record != reference_record: + raise ValueError( + f"off/reference scientific trajectory differs at record {compared}" + ) + digest.update(off_record) + digest.update(b"\n") + if compared != 100_000: + raise ValueError(f"expected 100000 compared records, got {compared}") + return { + "records": compared, "scientific_fields_exact": True, + "canonical_sha256": digest.hexdigest(), + } + + +def augmentation_statistics(path: Path, variant: str) -> dict: + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + if len(rows) != 100_000: + raise ValueError(f"expected 100000 augmentation records: {path}") + diagnostics = [row.get("photometric_augmentation") for row in rows] + if any(item is None for item in diagnostics): + raise ValueError(f"missing photometric diagnostics: {path}") + applied = np.asarray([float(item["applied_fraction"]) for item in diagnostics]) + if np.any((applied < 0.0) | (applied > 1.0)): + raise ValueError(f"invalid applied fraction: {path}") + expected_identity = variant == "off" + factor_limits = { + "brightness_mean": (0.8, 1.2), + "contrast_mean": (0.8, 1.2), + "saturation_mean": (0.8, 1.2), + "hue_mean": (-0.05, 0.05), + } + factor_stats = {} + for key, (low, high) in factor_limits.items(): + values = np.asarray([float(item[key]) for item in diagnostics]) + if expected_identity: + identity = 0.0 if key == "hue_mean" else 1.0 + if not np.all(values == identity): + raise ValueError(f"off run has non-identity {key}: {path}") + if np.any((values < low - 1e-7) | (values > high + 1e-7)): + raise ValueError(f"{key} outside registered range: {path}") + factor_stats[key] = { + "mean": float(values.mean()), "min": float(values.min()), + "max": float(values.max()), + } + if expected_identity and np.any(applied != 0.0): + raise ValueError(f"off run reports applied augmentation: {path}") + return { + "records": len(rows), "applied_fraction_mean": float(applied.mean()), + "factors": factor_stats, + } + + +def load_resume_audit(path: Path, variant: str) -> dict: + audit = json.loads(path.read_text(encoding="utf-8")) + expected_names = {run_name(variant, seed) for seed in SEEDS} + records = audit.get("runs", []) + if ( + audit.get("status") != "passed" + or audit.get("official_test_used") is not False + or {record.get("run") for record in records} != expected_names + or any( + record.get("reference_step") != 100_000 + or record.get("resumed_step") != 100_000 + or not all( + record.get(key) is True for key in ( + "model_exact", "optimizer_exact", "python_rng_exact", + "numpy_rng_exact", "torch_rng_exact", "cuda_rng_exact", + ) + ) + for record in records + ) + ): + raise ValueError(f"invalid {variant} exact-resume audit: {path}") + return { + "status": "passed", "variant": variant, "runs": len(records), + "path": str(path.resolve()), "sha256": sha256(path), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--run-root", type=Path, + default=Path("artifacts/phase3/photometric_runs_commit239b0bf"), + ) + parser.add_argument( + "--evaluation-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--off-reference-root", type=Path, + default=Path("artifacts/phase3/resolution_640_runs_attempt2_commit7583772"), + ) + parser.add_argument( + "--off-resume-root", type=Path, + default=Path("artifacts/phase3/photometric_resume_from75k"), + ) + parser.add_argument( + "--on-resume-root", type=Path, + default=Path("artifacts/phase3/photometric_on_resume_from75k"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("artifacts/phase3/reports"), + ) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + resume_audits = { + variant: load_resume_audit( + ( + args.off_resume_root if variant == "off" + else args.on_resume_root + ) / "exact_resume_audit.json", + variant, + ) + for variant in VARIANTS + } + + reports: dict[tuple[str, int, str], Path] = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + training_audit = {} + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + run_dir = args.run_root / name + summary = json.loads((run_dir / "summary.json").read_text(encoding="utf-8")) + provenance = json.loads( + (run_dir / "run_provenance.json").read_text(encoding="utf-8") + ) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid photometric training run: {name}") + training_audit[name] = { + "variant": variant, "seed": seed, + "augmentation": augmentation_statistics( + run_dir / "train_metrics.jsonl", variant, + ), + } + if variant == "off": + training_audit[name]["e1_reference"] = audit_off_reference( + run_dir / "train_metrics.jsonl", + args.off_reference_root / reference_run_name(seed) / "train_metrics.jsonl", + ) + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = args.evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("photometric matrix is incomplete") + write_csv(args.output_dir / "photometric_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "photometric_comparison.csv", best_rows) + write_csv(args.output_dir / "photometric_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "photometric_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + (args.output_dir / "photometric_training_audit.json").write_text( + json.dumps({"status": "passed", "runs": training_audit}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + joint_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv( + parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + joint_cache[(variant, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in read_csv(parent / "per_joint_metrics.csv") + } + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + return contrast_take_differences( + {"off": cache[("off", seed)], "on": cache[("on", seed)]}, + metric, {"off": -1.0, "on": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in FRAME_METRICS: + results = [paired(metric, seed) for seed in SEEDS] + paired_rows.append({ + "comparison": "on-off", "metric": metric, + "delta_definition": "augmentation on minus off; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [paired(metric, seed, temporal=True) for seed in SEEDS] + temporal_rows.append({ + "comparison": "on-off", "metric": metric, + "delta_definition": "augmentation on minus off; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + unavailable = set() + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": "on-off", "subgroup_axis": subgroup[0], + "subgroup_value": subgroup[1], "metric": metric, + "bucket_source": "aligned augmentation-off reference rows", + "delta_definition": "augmentation on minus off; lower is better", + } + try: + results = [paired(metric, seed, subgroup=subgroup) for seed in SEEDS] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, "seed_delta_mean": None, + "seed_delta_sample_std": None, "seed_20260716_delta": None, + "seed_20260717_delta": None, "seed_20260718_delta": None, + "frame_weighted_delta_mean": None, "take_count": 0, + "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + for side in ("left", "right"): + for joint_index in range(21): + off = np.asarray([ + joint_cache[("off", seed)][(side, joint_index)] for seed in SEEDS + ]) + on = np.asarray([ + joint_cache[("on", seed)][(side, joint_index)] for seed in SEEDS + ]) + delta = on - off + joint_rows.append({ + "side": side, "joint_index": joint_index, + "off_seed_mean_mm": float(off.mean()), + "off_seed_sample_std_mm": float(off.std(ddof=1)), + "on_seed_mean_mm": float(on.mean()), + "on_seed_sample_std_mm": float(on.std(ddof=1)), + "on_minus_off_seed_mean_mm": float(delta.mean()), + "on_minus_off_seed_sample_std_mm": float(delta.std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "photometric_per_joint_comparison.csv", joint_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_photometric_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_photometric_temporal_ci.csv").resolve() + ), + "paired_subgroups": str( + (args.output_dir / "paired_photometric_subgroup_ci.csv").resolve() + ), + "per_joint": str( + (args.output_dir / "photometric_per_joint_comparison.csv").resolve() + ), + "training_audit": str( + (args.output_dir / "photometric_training_audit.json").resolve() + ), + "exact_resume": { + "status": "passed", "runs": sum( + audit["runs"] for audit in resume_audits.values() + ), + "variants": resume_audits, + }, + "unavailable_subgroups": [ + {"axis": axis, "value": value} for axis, value in sorted(unavailable) + ], + "source_hashes": { + "training_launcher": sha256(args.run_root / "launcher_provenance.json"), + "validation_launcher": sha256( + args.evaluation_root / "launcher_provenance.json" + ), + }, + } + (args.output_dir / "photometric_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "per_joint_rows": len(joint_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_photometric_fallback.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_photometric_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..e865911f92e2e957592fba42b7916a5421d6348b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_photometric_fallback.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Summarize missing-modality behavior for the final photometric candidate.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from scripts.summarize_phase3_photometric import DIAGNOSTICS, VARIANTS, run_name +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from summarize_phase3_photometric import DIAGNOSTICS, VARIANTS, run_name + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + augmentation = config.get("data", {}).get("photometric_augmentation", {}) + override = report.get("inference_modality_override", {}) + expected_depth, expected_k = CONDITIONS[condition] + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "photometric_augmentation" + or experiment.get("variant") != f"photometric_{variant}_r640x368" + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or bool(augmentation.get("enabled")) != (variant == "on") + or int(config["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid photometric fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--complete-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--fallback-root", type=Path, + default=Path("artifacts/phase3/photometric_fallback_validation"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("artifacts/phase3/reports"), + ) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + root = args.complete_root if condition == "complete" else args.fallback_root / condition + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 24: + raise ValueError(f"expected 24 complete/fallback rows, got {len(rows)}") + write_csv(args.output_dir / "photometric_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + } + aggregate.append(record) + + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + contrasts.append(( + f"{condition}:on-off", (condition, "on"), (condition, "off"), + )) + + paired_rows = [] + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_fallback_ci.csv", paired_rows) + write_csv( + args.output_dir / "paired_photometric_fallback_temporal_ci.csv", temporal_rows, + ) + + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + equality.append({ + "variant": variant, "seed": seed, + "frame_rows_identical": ( + frame_cache[("drop_k", variant, seed)] + == frame_cache[("drop_both", variant, seed)] + ), + "temporal_rows_identical": ( + temporal_cache[("drop_k", variant, seed)] + == temporal_cache[("drop_both", variant, seed)] + ), + }) + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "geometry_k_dependency": ( + "When K is unavailable, ray conditioning and XYZ/logZ geometry are disabled; " + "drop_k and drop_both are therefore expected to be identical." + ), + } + output = args.output_dir / "photometric_fallback_comparison.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all( + row["frame_rows_identical"] and row["temporal_rows_identical"] + for row in equality + ), + "output": str(output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_resolution.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..669c9bad9451479da904b1d35b1873d764686a56 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_resolution.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Summarize the paired Phase 3 512x288 versus 640x368 resolution study.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) + + +TRAINING_COMMIT = "75837726f7eb8232b747932cbf536a834821e24d" +VARIANTS = ("r512x288", "r640x368") +RESOLUTIONS = {"r512x288": (288, 512), "r640x368": (368, 640)} +NORMALIZED_2D_METRICS = ( + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", +) +PAIRED_FRAME_METRICS = FRAME_METRICS + tuple( + f"{metric}_at_512_width" for metric in NORMALIZED_2D_METRICS +) +DIAGNOSTICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", +) + + +def run_name(variant: str, seed: int) -> str: + if variant == "r512x288": + return f"depth_dropout005_geometry_m3_l1_t1_s{seed}" + if variant == "r640x368": + return f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + raise ValueError(f"unknown resolution variant: {variant}") + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + expected_matrix = ( + "depth_modality_dropout_dose" if variant == "r512x288" else "resolution" + ) + expected_variant = ( + "dropout005_geometry" + if variant == "r512x288" else "dropout005_geometry_r640x368" + ) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != expected_matrix + or experiment.get("variant") != expected_variant + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(report["config"]["data"]["resolution_hw"]) != RESOLUTIONS[variant] + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid formal resolution evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def add_normalized_2d_columns( + rows: list[dict[str, str]], variant: str, +) -> list[dict[str, str]]: + scale = 512.0 / RESOLUTIONS[variant][1] + output = [] + for row in rows: + adapted = dict(row) + for metric in NORMALIZED_2D_METRICS: + value = adapted.get(metric) + adapted[f"{metric}_at_512_width"] = ( + "" if value in {None, ""} else str(float(value) * scale) + ) + output.append(adapted) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--reference-run-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_runs_commit7583772"), + ) + parser.add_argument( + "--candidate-run-root", type=Path, + default=Path("artifacts/phase3/resolution_640_runs_attempt2_commit7583772"), + ) + parser.add_argument( + "--reference-evaluation-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument( + "--candidate-evaluation-root", type=Path, + default=Path("artifacts/phase3/resolution_640_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], Path] = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + for variant in VARIANTS: + run_root = ( + args.reference_run_root if variant == "r512x288" + else args.candidate_run_root + ) + evaluation_root = ( + args.reference_evaluation_root if variant == "r512x288" + else args.candidate_evaluation_root + ) + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text()) + provenance = json.loads((run_root / name / "run_provenance.json").read_text()) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid resolution training run: {name}") + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "resolution_h": RESOLUTIONS[variant][0], + "resolution_w": RESOLUTIONS[variant][1], + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in NORMALIZED_2D_METRICS: + value = row[metric] + row[f"{metric}_at_512_width"] = ( + None if value is None else value * 512.0 / RESOLUTIONS[variant][1] + ) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("resolution matrix is incomplete") + write_csv(args.output_dir / "resolution_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "resolution_comparison.csv", best_rows) + write_csv(args.output_dir / "resolution_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "resolution_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n" + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + PAIRED_FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = add_normalized_2d_columns( + read_csv(parent / "per_hand_frame_metrics.csv"), variant, + ) + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + # Reference is inserted first so subgroup membership always comes from + # the fixed 512x288 evaluation rather than changing with resolution. + return contrast_take_differences( + { + "reference": cache[("r512x288", seed)], + "candidate": cache[("r640x368", seed)], + }, + metric, {"reference": -1.0, "candidate": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in PAIRED_FRAME_METRICS: + results = [paired(metric, seed) for seed in SEEDS] + paired_rows.append({ + "comparison": "r640x368-r512x288", "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [paired(metric, seed, temporal=True) for seed in SEEDS] + temporal_rows.append({ + "comparison": "r640x368-r512x288", "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + unavailable = set() + subgroup_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px_at_512_width", "fingertip_mpjpe_mm", + "translation_z_mae_mm", + ) + for subgroup in SUBGROUPS: + for metric in subgroup_metrics: + prefix = { + "comparison": "r640x368-r512x288", + "subgroup_axis": subgroup[0], "subgroup_value": subgroup[1], + "metric": metric, + "bucket_source": "r512x288 reference rows", + "delta_definition": "candidate minus reference; lower is better", + } + try: + results = [paired(metric, seed, subgroup=subgroup) for seed in SEEDS] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, "seed_20260717_delta": None, + "seed_20260718_delta": None, "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + joint_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + rows = read_csv(parent / "per_joint_metrics.csv") + joint_cache[(variant, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in rows + } + for side in ("left", "right"): + for joint_index in range(21): + reference = np.array([ + joint_cache[("r512x288", seed)][(side, joint_index)] for seed in SEEDS + ]) + candidate = np.array([ + joint_cache[("r640x368", seed)][(side, joint_index)] for seed in SEEDS + ]) + delta = candidate - reference + joint_rows.append({ + "side": side, "joint_index": joint_index, + "r512x288_seed_mean_mm": float(reference.mean()), + "r512x288_seed_sample_std_mm": float(reference.std(ddof=1)), + "r640x368_seed_mean_mm": float(candidate.mean()), + "r640x368_seed_sample_std_mm": float(candidate.std(ddof=1)), + "candidate_minus_reference_seed_mean_mm": float(delta.mean()), + "candidate_minus_reference_seed_sample_std_mm": float(delta.std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "resolution_per_joint_comparison.csv", joint_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "evaluation_contract": { + "raw_2d": "processed-input pixels, retained for audit", + "normalized_2d": "640 metrics multiplied by 512/640; 512 unchanged", + "subgroup_membership": "always inherited from aligned r512x288 reference rows", + }, + "paired_frame": str((args.output_dir / "paired_resolution_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_resolution_temporal_ci.csv").resolve() + ), + "paired_subgroups": str( + (args.output_dir / "paired_resolution_subgroup_ci.csv").resolve() + ), + "per_joint": str( + (args.output_dir / "resolution_per_joint_comparison.csv").resolve() + ), + "unavailable_subgroups": [ + {"axis": axis, "value": value} for axis, value in sorted(unavailable) + ], + "source_hashes": { + "reference_validation_launcher": sha256( + args.reference_evaluation_root / "launcher_provenance_sixth.json" + ), + "candidate_training_launcher": sha256( + args.candidate_run_root / "launcher_provenance.json" + ), + }, + } + (args.output_dir / "resolution_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "per_joint_rows": len(joint_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_temporal_position.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_temporal_position.py new file mode 100644 index 0000000000000000000000000000000000000000..a85351446385b326384584b1928ed219e889d36c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase3_temporal_position.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python3 +"""Summarize the Phase 3 P0/P1 temporal-position experiment.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + REPORT_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + sha256, + write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + REPORT_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + sha256, + write_csv, + ) + + +POSITIONS = ("P0", "P1") +ATTENTION_METRICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", +) + + +def position_run_name(position: str, seed: int) -> str: + if position == "P0": + return f"core_m3_l1_t1_s{seed}" + if position == "P1": + return f"temporal_p1_m3_l1_t1_s{seed}" + raise ValueError(f"unknown temporal position: {position}") + + +def load_report(path: Path, position: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + observed_position = experiment.get("position", "P0") + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or observed_position != position + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal temporal-position evaluation: {path}") + return report + + +def flatten_bias_report(position: str, seed: int, report: dict) -> list[dict[str, object]]: + rows = [] + bias_report = report["temporal_position_bias"] + for layer in bias_report["layers"]: + offsets = layer["offsets_key_minus_query"] + for head, values in enumerate(layer["per_head_bias"]): + for offset, value in zip(offsets, values, strict=True): + rows.append({ + "position": position, "seed": seed, "layer": int(layer["layer"]), + "head": head, "offset_key_minus_query": int(offset), "bias": float(value), + }) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--p0-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--p1-run-root", type=Path, default=Path("artifacts/phase3/temporal_position_runs")) + parser.add_argument("--p0-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--p1-evaluation-root", type=Path, default=Path("artifacts/phase3/temporal_position_full_validation")) + parser.add_argument("--p0-diagnostic-root", type=Path, default=Path("artifacts/phase3/temporal_position_p0_diagnostics")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + diagnostics: dict[tuple[str, int], tuple[Path, dict]] = {} + all_rows = [] + best_rows = [] + checkpoints = {} + for position in POSITIONS: + run_root = args.p0_run_root if position == "P0" else args.p1_run_root + evaluation_root = args.p0_evaluation_root if position == "P0" else args.p1_evaluation_root + for seed in SEEDS: + name = position_run_name(position, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal training run: {name}") + checkpoint_record = {"position": position, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, position, seed) + reports[(position, seed, role)] = (path, report) + row: dict[str, object] = { + "run": name, "position": position, "seed": seed, + "checkpoint_role": role, "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), "evaluation": str(path.resolve()), + } + + diagnostic_path = ( + args.p0_diagnostic_root / name / "best_absolute" / "evaluation.json" + if position == "P0" + else args.p1_evaluation_root / name / "best_absolute" / "evaluation.json" + ) + diagnostic = load_report(diagnostic_path, position, seed) + formal_best = reports[(position, seed, "best_absolute")][1] + for metric in REPORT_METRICS: + if metric_mean(diagnostic, metric) != metric_mean(formal_best, metric): + raise ValueError(f"diagnostic metric drift for {name}: {metric}") + diagnostics[(position, seed)] = (diagnostic_path, diagnostic) + + if len(all_rows) != 42 or len(best_rows) != 6: + raise ValueError(f"expected 42 checkpoint rows and 6 best rows, got {len(all_rows)}, {len(best_rows)}") + write_csv(args.output_dir / "temporal_position_checkpoint_comparison.csv", all_rows) + + for row in best_rows: + diagnostic = diagnostics[(str(row["position"]), int(row["seed"]))][1] + for metric in ATTENTION_METRICS: + row[metric] = attention_mean(diagnostic, metric) + write_csv(args.output_dir / "temporal_position_comparison.csv", best_rows) + (args.output_dir / "temporal_position_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for position in POSITIONS: + group = [row for row in best_rows if row["position"] == position] + record: dict[str, object] = {"position": position, "seeds": list(SEEDS)} + for metric in REPORT_METRICS + ATTENTION_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("trainable_parameters", "peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + } + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + attention_distance_rows = [] + bias_rows = [] + for position in POSITIONS: + for seed in SEEDS: + path, report = diagnostics[(position, seed)] + frame_cache[(position, seed)] = read_csv(path.parent / "per_hand_frame_metrics.csv") + temporal_cache[(position, seed)] = read_csv(path.parent / "per_temporal_transition_metrics.csv") + for distance_mode, report_key in ( + ("absolute", "temporal_attention_by_absolute_frame_distance"), + ("signed_key_minus_query", "temporal_attention_by_signed_frame_distance"), + ): + for distance, distribution in report["attention"][report_key].items(): + attention_distance_rows.append({ + "position": position, "seed": seed, "distance_mode": distance_mode, + "distance": int(distance), **distribution, + }) + bias_rows.extend(flatten_bias_report(position, seed, report)) + write_csv(args.output_dir / "temporal_position_attention_by_distance.csv", attention_distance_rows) + if not bias_rows: + raise ValueError("P1 diagnostic evaluations did not export relative-position bias") + write_csv(args.output_dir / "temporal_position_bias.csv", bias_rows) + + grouped_bias: dict[tuple[int, int, int], list[float]] = {} + for row in bias_rows: + key = (int(row["layer"]), int(row["head"]), int(row["offset_key_minus_query"])) + grouped_bias.setdefault(key, []).append(float(row["bias"])) + bias_aggregate_rows = [{ + "position": "P1", "layer": layer, "head": head, "offset_key_minus_query": offset, + "seed_mean_bias": float(np.mean(values)), + "seed_sample_std_bias": float(np.std(values, ddof=1)), + "seed_20260716_bias": values[0], "seed_20260717_bias": values[1], + "seed_20260718_bias": values[2], + } for (layer, head, offset), values in sorted(grouped_bias.items())] + write_csv(args.output_dir / "temporal_position_bias_aggregate.csv", bias_aggregate_rows) + + paired_rows = [] + coefficients = {"P1": 1.0, "P0": -1.0} + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {position: frame_cache[(position, seed)] for position in POSITIONS}, + metric, coefficients, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": "P1_minus_P0", "metric": metric, + "delta_definition": "P1_minus_P0_lower_is_better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_temporal_position_bootstrap_ci.csv", paired_rows) + + paired_temporal_rows = [] + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {position: temporal_cache[(position, seed)] for position in POSITIONS}, + metric, coefficients, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + paired_temporal_rows.append({ + "comparison": "P1_minus_P0", "metric": metric, + "delta_definition": "P1_minus_P0_lower_is_better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_temporal_position_temporal_ci.csv", paired_temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_temporal_position_bootstrap_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_temporal_position_temporal_ci.csv").resolve()), + "attention_distance": str((args.output_dir / "temporal_position_attention_by_distance.csv").resolve()), + "bias_aggregate": str((args.output_dir / "temporal_position_bias_aggregate.csv").resolve()), + "source_hashes": { + "p0_diagnostic_launcher": sha256(args.p0_diagnostic_root / "launcher_provenance.json"), + "p1_validation_launcher": sha256(args.p1_evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "temporal_position_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "paired_rows": len(paired_rows), "paired_temporal_rows": len(paired_temporal_rows), + "bias_rows": len(bias_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_a1.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_a1.py new file mode 100644 index 0000000000000000000000000000000000000000..72611727f8c8853380b2b3d4d31e8389d70b79e3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_a1.py @@ -0,0 +1,359 @@ +#!/usr/bin/env python3 +"""Aggregate the three frozen-checkpoint Phase 4 A1 oracle diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary + +if __package__: + from scripts.fit_phase4_oracle_local_depth import paired_take_bootstrap +else: + from fit_phase4_oracle_local_depth import paired_take_bootstrap + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = ("coarse", "control", "local") +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", +) +STABLE_FIELDS = ( + "sample_index", + "clip_index", + "time_index", + "take", + "subject", + "sequence", + "frame_id", + "side", + "side_index", + "action_family", + "action_label", + "action_name", + "hand_size_px", + "wrist_depth_m", + "bimanual_size_ratio", + "bimanual_depth_gap_m", + "bimanual_asymmetry_bucket", + "local_depth_valid_fraction", + "local_depth_discontinuity_m", +) + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV {path}") + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_seed_results(root: Path) -> tuple[ + dict[int, list[dict[str, str]]], dict[int, dict[str, Any]], list[dict[str, str]] +]: + rows_by_seed: dict[int, list[dict[str, str]]] = {} + reports: dict[int, dict[str, Any]] = {} + reference: list[dict[str, str]] | None = None + for seed in SEEDS: + fit = root / f"seed_{seed}" / "fit" + rows = read_csv(fit / "validation_predictions.csv") + report = json.loads((fit / "results.json").read_text(encoding="utf-8")) + if report.get("official_test_used") is not False: + raise ValueError(f"seed {seed} did not preserve official-test isolation") + if reference is None: + reference = rows + else: + if len(rows) != len(reference): + raise ValueError("A1 seed validation row counts differ") + for index, (candidate, expected) in enumerate(zip(rows, reference, strict=True)): + for field in STABLE_FIELDS: + if candidate[field] != expected[field]: + raise ValueError( + f"A1 seed metadata mismatch at row {index}, field {field}" + ) + rows_by_seed[seed] = rows + reports[seed] = report + if reference is None: + raise ValueError("no A1 seed results found") + return rows_by_seed, reports, reference + + +def aggregate_predictions( + rows_by_seed: dict[int, list[dict[str, str]]], +) -> dict[str, dict[str, np.ndarray]]: + output: dict[str, dict[str, np.ndarray]] = {} + for variant in VARIANTS: + output[variant] = {} + for metric in METRICS: + per_seed = np.asarray([ + [float(row[f"{variant}_{metric}"]) for row in rows_by_seed[seed]] + for seed in SEEDS + ], dtype=np.float64) + output[variant][metric] = per_seed.mean(axis=0) + return output + + +def group_masks( + rows: list[dict[str, str]], challenge: dict[str, Any], +) -> dict[str, np.ndarray]: + farthest = float(challenge["thresholds"]["farthest_observed_wrist_depth_p80_m"]) + challenge_clips = {int(value) for value in challenge["clip_indices"]} + return { + "all": np.ones(len(rows), dtype=bool), + "left": np.asarray([row["side"] == "left" for row in rows]), + "right": np.asarray([row["side"] == "right" for row in rows]), + "small": np.asarray([float(row["hand_size_px"]) < 64.0 for row in rows]), + "farthest_observed": np.asarray([ + float(row["wrist_depth_m"]) >= farthest for row in rows + ]), + "strong_asymmetry": np.asarray([ + row["bimanual_asymmetry_bucket"] == "strong" for row in rows + ]), + "challenge": np.asarray([ + int(row["clip_index"]) in challenge_clips for row in rows + ]), + } + + +def aggregate_group_rows( + predictions: dict[str, dict[str, np.ndarray]], masks: dict[str, np.ndarray], +) -> list[dict[str, object]]: + rows: list[dict[str, object]] = [] + for group, mask in masks.items(): + for variant in VARIANTS: + for metric in METRICS: + rows.append({ + "group": group, + "variant": variant, + "metric": metric, + "seed_scope": "per-frame mean over seeds 20260716/17/18", + **distribution_summary(predictions[variant][metric][mask]), + }) + return rows + + +def find_value( + rows: list[dict[str, object]], group: str, variant: str, metric: str, statistic: str, +) -> float: + record = next( + row for row in rows + if row["group"] == group and row["variant"] == variant and row["metric"] == metric + ) + return float(record[statistic]) + + +def seed_summary_rows(reports: dict[int, dict[str, Any]]) -> list[dict[str, object]]: + rows = [] + for seed in SEEDS: + report = reports[seed] + reductions = report["gate"]["reductions_percent"] + rows.append({ + "seed": seed, + "checkpoint_step": report["frozen_checkpoint"]["step"], + "checkpoint_sha256": report["frozen_checkpoint"]["sha256"], + "formal_A1_gate_pass": report["gate"]["formal_A1_gate_pass"], + **reductions, + "control_best_epoch": min( + report["histories"]["control"], + key=lambda row: row["holdout_residual_mae_m"], + )["epoch"], + "local_best_epoch": min( + report["histories"]["local"], + key=lambda row: row["holdout_residual_mae_m"], + )["epoch"], + }) + return rows + + +def markdown_report( + report: dict[str, Any], group_rows: list[dict[str, object]], seed_rows: list[dict[str, object]], +) -> str: + gate = report["gate"] + lines = [ + "# Phase 4 A1 Oracle Local-Depth Diagnostic", + "", + "## Decision", + "", + f"- Formal gate: **{'PASS' if gate['formal_A1_gate_pass'] else 'FAIL'}**.", + f"- Action: **{gate['decision']}**.", + "- Official test used: no.", + "- A2 predicted-location diagnostic is not admitted when A1 fails the preregistered gate.", + "", + "## Three-Seed Aggregate", + "", + "| Metric / group | Coarse | Oracle-location control | Oracle local depth | Reduction vs coarse |", + "|---|---:|---:|---:|---:|", + ] + table_specs = ( + ("z P95 / all", "all", "translation_z_mae_mm", "p95"), + ("absolute MPJPE / all", "all", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / small", "small", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / farthest-observed", "farthest_observed", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / right", "right", "absolute_mpjpe_mm", "mean"), + ("projected MANO 2D / all", "all", "mano_projected_2d_error_px", "mean"), + ) + for label, group, metric, statistic in table_specs: + values = { + variant: find_value(group_rows, group, variant, metric, statistic) + for variant in VARIANTS + } + reduction = 100.0 * (values["coarse"] - values["local"]) / values["coarse"] + lines.append( + f"| {label} | {values['coarse']:.2f} | {values['control']:.2f} | " + f"{values['local']:.2f} | {reduction:.2f}% |" + ) + lines.extend(( + "", + "The aggregate uses the per-frame mean error over the three frozen Phase 3 checkpoints, matching the Phase 4 Wave 0 aggregation convention. The local-depth regressor improves the tail beyond the same-capacity oracle-location control, but the registered full-validation/far-small thresholds are not reached.", + "", + "## Seed Stability", + "", + "| Seed | z P95 reduction | Small absolute reduction | Farthest-observed absolute reduction | Gate | Local best epoch |", + "|---:|---:|---:|---:|---|---:|", + )) + for row in seed_rows: + lines.append( + f"| {row['seed']} | {row['full_validation_z_p95_percent']:.2f}% | " + f"{row['small_absolute_mpjpe_percent']:.2f}% | " + f"{row['farthest_observed_absolute_mpjpe_percent']:.2f}% | " + f"{'pass' if row['formal_A1_gate_pass'] else 'fail'} | {row['local_best_epoch']} |" + ) + lines.extend(( + "", + "Seed 20260718 is the limiting case: its train-only holdout selected epoch 1 and its local-depth gain over the frozen coarse output is small. This prevents a robust three-seed claim even though seeds 20260716 and 20260717 individually pass.", + "", + "## Interpretation", + "", + "- Engineering correctness is established: data/hash isolation, raw depth/K alignment, feature schema, bounded residual, and exact root-relative/direct-2D invariance all passed.", + "- Local depth contains useful information beyond oracle location alone, but the gain is checkpoint-dependent and narrowly misses the preregistered aggregate threshold.", + "- Per the Phase 4 stop rule, do not implement the deployable local-depth branch or A2 at this point. Shift the next metric-z effort to matched axis-aware loss and train-only balanced-sampling controls; A3 remains an independent appearance upper-bound diagnostic.", + "", + "## Sources", + "", + f"- Input root: `{report['input_root']}`", + f"- Aggregate table: `{report['outputs']['comparison_csv']}`", + f"- Take bootstrap: `{report['outputs']['paired_take_bootstrap_ci']}`", + )) + return "\n".join(lines) + "\n" + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--input-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument( + "--challenge-manifest", type=Path, + default=Path("artifacts/phase4/challenge_subset/official_val_challenge_128.json"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + rows_by_seed, reports, metadata = load_seed_results(args.input_root) + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + predictions = aggregate_predictions(rows_by_seed) + group_rows = aggregate_group_rows(predictions, group_masks(metadata, challenge)) + bootstrap_rows = paired_take_bootstrap( + metadata, + predictions, + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + seed_rows = seed_summary_rows(reports) + + coarse_z_p95 = find_value(group_rows, "all", "coarse", "translation_z_mae_mm", "p95") + local_z_p95 = find_value(group_rows, "all", "local", "translation_z_mae_mm", "p95") + reductions = { + "full_validation_z_p95_percent": 100.0 * (coarse_z_p95 - local_z_p95) / coarse_z_p95, + } + for group in ("small", "farthest_observed", "right"): + coarse = find_value(group_rows, group, "coarse", "absolute_mpjpe_mm", "mean") + local = find_value(group_rows, group, "local", "absolute_mpjpe_mm", "mean") + reductions[f"{group}_absolute_mpjpe_percent"] = 100.0 * (coarse - local) / coarse + metric_pass = ( + reductions["full_validation_z_p95_percent"] >= 20.0 + or reductions["small_absolute_mpjpe_percent"] >= 15.0 + or reductions["farthest_observed_absolute_mpjpe_percent"] >= 15.0 + ) + invariance_pass = all( + abs(find_value(group_rows, "all", "local", metric, "mean") + - find_value(group_rows, "all", "coarse", metric, "mean")) <= 1e-4 + for metric in ("root_relative_mpjpe_mm", "direct_2d_error_px") + ) + formal_pass = bool(metric_pass and invariance_pass) + output_csv = args.output_dir / "a1_oracle_local_depth_comparison.csv" + output_bootstrap = args.output_dir / "paired_take_bootstrap_ci.csv" + output_seed = args.output_dir / "a1_oracle_local_depth_seed_stability.csv" + output_json = args.output_dir / "A1_ORACLE_LOCAL_DEPTH.json" + output_md = args.output_dir / "A1_ORACLE_LOCAL_DEPTH.md" + report = { + "status": "complete", + "phase": 4, + "wave": "A1_oracle_local_depth", + "official_test_used": False, + "input_root": str(args.input_root.resolve()), + "seed_scope": list(SEEDS), + "aggregation": "per-frame mean error over three seeds, then distribution summary", + "checkpoint_rule": "Phase 3 fixed-subset tail-best-absolute per seed", + "gate": { + "formal_A1_gate_pass": formal_pass, + "metric_gate_pass": bool(metric_pass), + "invariance_gate_pass": bool(invariance_pass), + "decision": ( + "ADMIT_A2" if formal_pass + else "STOP_LOCAL_DEPTH_BRANCH_AND_SHIFT_TO_LOSS_SAMPLING_OR_BACKBONE_CONTROLS" + ), + "thresholds": { + "full_validation_z_p95_reduction_percent": 20.0, + "small_or_farthest_absolute_mpjpe_reduction_percent": 15.0, + "root_relative_and_direct_2d_max_degradation_percent": 2.0, + }, + "observed_reductions_percent": reductions, + }, + "seed_results": seed_rows, + "outputs": { + "comparison_csv": str(output_csv.resolve()), + "paired_take_bootstrap_ci": str(output_bootstrap.resolve()), + "seed_stability_csv": str(output_seed.resolve()), + "markdown": str(output_md.resolve()), + }, + } + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(output_csv, group_rows) + write_csv(output_bootstrap, bootstrap_rows) + write_csv(output_seed, seed_rows) + output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + output_md.write_text(markdown_report(report, group_rows, seed_rows), encoding="utf-8") + print(json.dumps({"status": "complete", "gate": report["gate"]}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_a3.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_a3.py new file mode 100644 index 0000000000000000000000000000000000000000..d41d5683a4d4ffc98d31e2e3e2bd85c042d499e2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_a3.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +"""Summarize A3 refined predictions against their exact frozen coarse outputs.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Mapping + +try: + from scripts.summarize_phase4_control import ( + RECONSTRUCTION_KEY, + RECONSTRUCTION_METADATA, + SEEDS, + aggregate_seed_rows, + assert_pair_alignment, + distribution_rows, + groups, + paired_take_bootstrap, + read_csv, + statistic, + write_csv, + ) +except ModuleNotFoundError: + from summarize_phase4_control import ( # type: ignore[no-redef] + RECONSTRUCTION_KEY, + RECONSTRUCTION_METADATA, + SEEDS, + aggregate_seed_rows, + assert_pair_alignment, + distribution_rows, + groups, + paired_take_bootstrap, + read_csv, + statistic, + write_csv, + ) + + +MODES = ("oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k") +METRIC_PAIRS = { + "absolute_mpjpe_mm": "coarse_absolute_mpjpe_mm", + "root_relative_mpjpe_mm": "coarse_root_relative_mpjpe_mm", + "absolute_mpvpe_mm": "coarse_absolute_mpvpe_mm", + "root_relative_mpvpe_mm": "coarse_root_relative_mpvpe_mm", + "fingertip_mpjpe_mm": "coarse_fingertip_mpjpe_mm", + "translation_z_mae_mm": "coarse_translation_z_mae_mm", +} +METRICS = tuple(METRIC_PAIRS) + + +def discover_evaluations(root: Path, role: str) -> dict[str, dict[int, Path]]: + output: dict[str, dict[int, Path]] = {mode: {} for mode in MODES} + for report_path in sorted(root.glob(f"*/{role}/evaluation.json")): + report = json.loads(report_path.read_text(encoding="utf-8")) + oracle = report.get("oracle_crop_refinement", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("clips") != 1495 + or report.get("phase4_diagnostics", {}).get("enabled") is not True + or oracle.get("enabled") is not True + or oracle.get("gt_location_at_inference") is not True + ): + raise ValueError(f"invalid complete A3 evaluation: {report_path}") + config = report["config"] + mode = config["experiment"]["oracle_crop_mode"] + seed = int(config["seed"]) + if mode not in output or seed in output[mode]: + raise ValueError(f"unexpected or duplicate A3 mode/seed: {mode}/{seed}") + if ( + oracle.get("coarse_checkpoint_sha256") + != config["experiment"]["coarse_checkpoint_sha256"] + ): + raise ValueError(f"coarse checkpoint identity missing: {report_path}") + output[mode][seed] = report_path.parent + for mode, records in output.items(): + if tuple(sorted(records)) != SEEDS: + raise ValueError( + f"expected seeds {SEEDS} for {mode}, found {tuple(sorted(records))}" + ) + return output + + +def coarse_rows(rows: list[dict[str, str]]) -> list[dict[str, object]]: + output = [] + for source in rows: + row: dict[str, object] = dict(source) + for metric, coarse_metric in METRIC_PAIRS.items(): + if coarse_metric not in source: + raise ValueError(f"missing A3 coarse metric {coarse_metric}") + row[metric] = source[coarse_metric] + output.append(row) + return output + + +def compute_gate( + coarse_absolute: float, + refined_absolute: float, + coarse_fingertip: float, + refined_fingertip: float, + coarse_root_mpvpe: float, + refined_root_mpvpe: float, +) -> dict[str, float | bool]: + fingertip_gain = 100.0 * (coarse_fingertip - refined_fingertip) / coarse_fingertip + root_mpvpe_gain = 100.0 * ( + coarse_root_mpvpe - refined_root_mpvpe + ) / coarse_root_mpvpe + absolute_degradation = 100.0 * ( + refined_absolute - coarse_absolute + ) / coarse_absolute + return { + "fingertip_improvement_percent": fingertip_gain, + "root_relative_mpvpe_improvement_percent": root_mpvpe_gain, + "absolute_mpjpe_degradation_percent": absolute_degradation, + "accuracy_gain_passed": bool( + fingertip_gain >= 10.0 or root_mpvpe_gain >= 10.0 + ), + "absolute_guardrail_passed": bool(absolute_degradation <= 2.0), + "promotion_gate_passed": bool( + (fingertip_gain >= 10.0 or root_mpvpe_gain >= 10.0) + and absolute_degradation <= 2.0 + ), + } + + +def rename_distribution_conditions( + rows: list[dict[str, object]], mode: str, scope: str, +) -> None: + for row in rows: + row["mode"] = mode + row["scope"] = scope + row["condition"] = { + "reference": "coarse", + "candidate": "refined", + "candidate_minus_reference": "refined_minus_coarse", + }[row["condition"]] + + +def gate_from_distributions( + rows: list[dict[str, object]], mode: str, +) -> dict[str, float | bool]: + def overall(metric: str, condition: str) -> float: + matches = [ + row for row in rows + if row["group_field"] == "all" and row["group_value"] == "all" + and row["metric"] == metric and row["condition"] == condition + ] + if len(matches) != 1: + raise ValueError(f"missing overall {mode}/{metric}/{condition}") + return float(matches[0]["mean"]) + + return compute_gate( + overall("absolute_mpjpe_mm", "coarse"), + overall("absolute_mpjpe_mm", "refined"), + overall("fingertip_mpjpe_mm", "coarse"), + overall("fingertip_mpjpe_mm", "refined"), + overall("root_relative_mpvpe_mm", "coarse"), + overall("root_relative_mpvpe_mm", "refined"), + ) + + +def assert_coarse_identical_across_modes( + raw_by_mode: Mapping[str, Mapping[int, list[dict[str, str]]]], +) -> None: + reference_mode = MODES[0] + for seed in SEEDS: + reference = { + tuple(row[field] for field in RECONSTRUCTION_KEY): tuple( + row[coarse_metric] for coarse_metric in METRIC_PAIRS.values() + ) + for row in raw_by_mode[reference_mode][seed] + } + for mode in MODES[1:]: + candidate = { + tuple(row[field] for field in RECONSTRUCTION_KEY): tuple( + row[coarse_metric] for coarse_metric in METRIC_PAIRS.values() + ) + for row in raw_by_mode[mode][seed] + } + if candidate != reference: + raise ValueError( + f"frozen coarse outputs differ across A3 modes for seed {seed}" + ) + + +def seed_deltas( + raw_by_seed: Mapping[int, list[dict[str, str]]], mode: str, +) -> list[dict[str, object]]: + output = [] + for seed in SEEDS: + rows = [ + row for row in raw_by_seed[seed] + if int(row["annotation_valid"]) == 1 + ] + for metric, coarse_metric in METRIC_PAIRS.items(): + coarse = statistic((row.get(coarse_metric) for row in rows), "mean") + refined = statistic((row.get(metric) for row in rows), "mean") + if coarse is None or refined is None: + continue + output.append({ + "mode": mode, "seed": seed, "metric": metric, + "coarse": coarse, "refined": refined, + "refined_minus_coarse": refined - coarse, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--role", default="best_absolute") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--challenge-manifest", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + evaluations = discover_evaluations(args.evaluation_root, args.role) + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + challenge_indices = {int(value) for value in challenge["clip_indices"]} + if ( + len(challenge_indices) != int(challenge["count"]) + or challenge.get("source_clip_count") != 1495 + or challenge.get("checkpoint_selection_allowed") is not False + or challenge.get("training_sampler_use_allowed") is not False + or challenge.get("official_test_used") is not False + ): + raise ValueError("invalid frozen official-validation challenge subset") + raw_by_mode = { + mode: { + seed: read_csv(evaluations[mode][seed] / "per_hand_frame_metrics.csv") + for seed in SEEDS + } + for mode in MODES + } + assert_coarse_identical_across_modes(raw_by_mode) + + comparison_output = [] + paired_output = [] + seed_output = [] + gates = {} + challenge_diagnostics = {} + for mode_index, mode in enumerate(MODES): + refined = aggregate_seed_rows( + raw_by_mode[mode], RECONSTRUCTION_KEY, METRICS, + ) + coarse = aggregate_seed_rows( + {seed: coarse_rows(raw_by_mode[mode][seed]) for seed in SEEDS}, + RECONSTRUCTION_KEY, METRICS, + ) + assert_pair_alignment( + coarse, refined, RECONSTRUCTION_KEY, RECONSTRUCTION_METADATA, + ) + distributions = distribution_rows( + coarse, refined, METRICS, require_annotation_valid=True, + ) + rename_distribution_conditions(distributions, mode, "full_validation") + comparison_output.extend(distributions) + + valid_coarse = [row for row in coarse if int(row["annotation_valid"]) == 1] + valid_refined = [row for row in refined if int(row["annotation_valid"]) == 1] + paired = paired_take_bootstrap( + valid_coarse, valid_refined, METRICS, groups(valid_coarse), + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + mode_index, + ) + paired.extend(paired_take_bootstrap( + valid_coarse, valid_refined, ("translation_z_mae_mm",), + groups(valid_coarse), statistics=("p95", "cvar95"), + bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 100 + mode_index, + )) + for row in paired: + row["mode"] = mode + row["scope"] = "full_validation" + row["coarse"] = row.pop("reference") + row["refined"] = row.pop("candidate") + row["refined_minus_coarse"] = row.pop("candidate_minus_reference") + paired_output.extend(paired) + seed_output.extend(seed_deltas(raw_by_mode[mode], mode)) + + gates[mode] = gate_from_distributions(distributions, mode) + + challenge_coarse = [ + row for row in coarse if int(row["clip_index"]) in challenge_indices + ] + challenge_refined = [ + row for row in refined if int(row["clip_index"]) in challenge_indices + ] + challenge_distributions = distribution_rows( + challenge_coarse, challenge_refined, METRICS, + require_annotation_valid=True, + ) + rename_distribution_conditions( + challenge_distributions, mode, "challenge_secondary", + ) + comparison_output.extend(challenge_distributions) + challenge_diagnostics[mode] = gate_from_distributions( + challenge_distributions, mode, + ) + challenge_paired = paired_take_bootstrap( + [row for row in challenge_coarse if int(row["annotation_valid"]) == 1], + [row for row in challenge_refined if int(row["annotation_valid"]) == 1], + METRICS, [("all", "all"), ("side", "left"), ("side", "right")], + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 200 + mode_index, + ) + for row in challenge_paired: + row["mode"] = mode + row["scope"] = "challenge_secondary" + row["coarse"] = row.pop("reference") + row["refined"] = row.pop("candidate") + row["refined_minus_coarse"] = row.pop("candidate_minus_reference") + paired_output.extend(challenge_paired) + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "a3_oracle_crop_comparison.csv", comparison_output) + write_csv( + args.output_dir / "a3_oracle_crop_paired_take_bootstrap_ci.csv", + paired_output, + ) + write_csv(args.output_dir / "a3_oracle_crop_seed_stability.csv", seed_output) + report = { + "status": "summarized", + "official_test_used": False, + "role": args.role, + "seeds": list(SEEDS), + "modes": list(MODES), + "aggregation": "aligned per-frame error averaged over three seeds", + "confidence_interval_unit": "paired official-validation take", + "coarse_consistency_across_modes": True, + "challenge_subset": { + "manifest": str(args.challenge_manifest.resolve()), + "clips": len(challenge_indices), + "role": "secondary_diagnostic_only", + "checkpoint_selection_allowed": False, + "diagnostics": challenge_diagnostics, + }, + "promotion_rule": ( + "fingertip MPJPE or root-relative MPVPE improves >=10%, and " + "absolute MPJPE degrades <=2%" + ), + "gates": gates, + } + (args.output_dir / "A3_ORACLE_CROP.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_control.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_control.py new file mode 100644 index 0000000000000000000000000000000000000000..786bf74861d7bf81eeee203f188c84966ad92b02 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_control.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +"""Compare a three-seed Phase 4 control with the matched 100k B-ref.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path +from typing import Iterable, Mapping + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary + + +SEEDS = (20260716, 20260717, 20260718) +RECONSTRUCTION_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "identity_switch_fraction", +) +RECONSTRUCTION_KEY = ("clip_index", "time_index", "side") +TEMPORAL_KEY = ("clip_index", "transition_index", "side") +RECONSTRUCTION_METADATA = ( + "take", + "frame_id", + "side", + "annotation_valid", + "hand_size_bucket", + "depth_bucket", + "action_family", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", +) +GROUP_FIELDS = ( + "side", + "hand_size_bucket", + "depth_bucket", + "action_family", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", +) + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report {path}") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: object) -> float | None: + if value in (None, ""): + return None + result = float(value) + return result if np.isfinite(result) else None + + +def discover_evaluations(root: Path, role: str) -> dict[int, Path]: + output = {} + for report_path in sorted(root.glob(f"*/{role}/evaluation.json")): + report = json.loads(report_path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("official_test_used") is not False: + raise ValueError(f"invalid evaluation report: {report_path}") + if report.get("phase4_diagnostics", {}).get("enabled") is not True: + raise ValueError(f"Phase 4 diagnostics missing: {report_path}") + seed = int(report["config"]["seed"]) + if seed in output: + raise ValueError(f"duplicate seed {seed} under {root}") + output[seed] = report_path.parent + if tuple(sorted(output)) != SEEDS: + raise ValueError(f"expected seeds {SEEDS}, found {tuple(sorted(output))} under {root}") + return output + + +def row_key(row: Mapping[str, object], fields: tuple[str, ...]) -> tuple[str, ...]: + return tuple(str(row[field]) for field in fields) + + +def aggregate_seed_rows( + rows_by_seed: Mapping[int, list[dict[str, str]]], + key_fields: tuple[str, ...], + metric_fields: tuple[str, ...], +) -> list[dict[str, object]]: + maps = { + seed: {row_key(row, key_fields): row for row in rows} + for seed, rows in rows_by_seed.items() + } + keys = set(maps[SEEDS[0]]) + if any(set(maps[seed]) != keys for seed in SEEDS[1:]): + raise ValueError("three-seed exported row keys do not align") + output = [] + for key in sorted(keys): + first = maps[SEEDS[0]][key] + row: dict[str, object] = dict(first) + for metric in metric_fields: + values = [ + optional_float(maps[seed][key].get(metric)) for seed in SEEDS + ] + finite = [value for value in values if value is not None] + row[metric] = float(np.mean(finite)) if finite else None + output.append(row) + return output + + +def assert_pair_alignment( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + key_fields: tuple[str, ...], + metadata_fields: tuple[str, ...], +) -> None: + reference_map = {row_key(row, key_fields): row for row in reference} + candidate_map = {row_key(row, key_fields): row for row in candidate} + if reference_map.keys() != candidate_map.keys(): + raise ValueError("candidate/reference exported row keys do not align") + for key, reference_row in reference_map.items(): + candidate_row = candidate_map[key] + for field in metadata_fields: + if str(reference_row.get(field, "")) != str(candidate_row.get(field, "")): + raise ValueError(f"candidate/reference metadata mismatch at {key}/{field}") + + +def groups(rows: list[dict[str, object]]) -> list[tuple[str, str]]: + output = [("all", "all")] + for field in GROUP_FIELDS: + values = sorted({str(row.get(field)) for row in rows if row.get(field) not in (None, "")}) + output.extend((field, value) for value in values) + return output + + +def selected_rows( + rows: list[dict[str, object]], group_field: str, group_value: str, +) -> list[dict[str, object]]: + if group_field == "all": + return rows + return [row for row in rows if str(row.get(group_field)) == group_value] + + +def distribution_rows( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + metrics: tuple[str, ...], + *, + require_annotation_valid: bool, +) -> list[dict[str, object]]: + if require_annotation_valid: + reference = [row for row in reference if int(row["annotation_valid"]) == 1] + candidate = [row for row in candidate if int(row["annotation_valid"]) == 1] + output = [] + for group_field, group_value in groups(reference): + reference_group = selected_rows(reference, group_field, group_value) + candidate_group = selected_rows(candidate, group_field, group_value) + for metric in metrics: + summaries = { + "reference": distribution_summary(row.get(metric) for row in reference_group), + "candidate": distribution_summary(row.get(metric) for row in candidate_group), + } + for condition, summary in summaries.items(): + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "condition": condition, + **summary, + "mean_relative_percent": None, + }) + delta = { + statistic: ( + summaries["candidate"][statistic] - summaries["reference"][statistic] + if summaries["candidate"][statistic] is not None + and summaries["reference"][statistic] is not None else None + ) + for statistic in ("mean", "p50", "p90", "p95", "p99", "cvar95") + } + reference_mean = summaries["reference"]["mean"] + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "condition": "candidate_minus_reference", + "count": summaries["candidate"]["count"], + "std": None, + **delta, + "mean_relative_percent": ( + 100.0 * delta["mean"] / reference_mean + if delta["mean"] is not None and reference_mean not in (None, 0) else None + ), + }) + return output + + +def statistic(values: Iterable[object], name: str) -> float | None: + array = np.asarray( + [value for item in values if (value := optional_float(item)) is not None], + dtype=np.float64, + ) + if not array.size: + return None + if name == "mean": + return float(array.mean()) + threshold = float(np.percentile(array, 95)) + if name == "p95": + return threshold + if name == "cvar95": + return float(array[array >= threshold].mean()) + raise ValueError(f"unknown statistic {name}") + + +def paired_take_bootstrap( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + metrics: tuple[str, ...], + group_specs: list[tuple[str, str]], + *, + statistics: tuple[str, ...], + bootstrap_samples: int, + seed: int, +) -> list[dict[str, object]]: + output = [] + for group_index, (group_field, group_value) in enumerate(group_specs): + reference_group = selected_rows(reference, group_field, group_value) + candidate_group = selected_rows(candidate, group_field, group_value) + reference_by_take: dict[str, list[dict[str, object]]] = defaultdict(list) + candidate_by_take: dict[str, list[dict[str, object]]] = defaultdict(list) + for row in reference_group: + reference_by_take[str(row["take"])].append(row) + for row in candidate_group: + candidate_by_take[str(row["take"])].append(row) + takes = sorted(set(reference_by_take) & set(candidate_by_take)) + for metric_index, metric in enumerate(metrics): + for statistic_index, statistic_name in enumerate(statistics): + paired = [] + reference_values = [] + candidate_values = [] + for take in takes: + reference_value = statistic( + (row.get(metric) for row in reference_by_take[take]), statistic_name, + ) + candidate_value = statistic( + (row.get(metric) for row in candidate_by_take[take]), statistic_name, + ) + if reference_value is None or candidate_value is None: + continue + reference_values.append(reference_value) + candidate_values.append(candidate_value) + paired.append(candidate_value - reference_value) + deltas = np.asarray(paired, dtype=np.float64) + if not deltas.size: + continue + rng = np.random.default_rng( + np.random.SeedSequence([seed, group_index, metric_index, statistic_index]) + ) + indices = rng.integers( + 0, deltas.size, size=(bootstrap_samples, deltas.size), + ) + distribution = deltas[indices].mean(axis=1) + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "statistic": f"take_{statistic_name}", + "takes": int(deltas.size), + "reference": float(np.mean(reference_values)), + "candidate": float(np.mean(candidate_values)), + "candidate_minus_reference": float(deltas.mean()), + "ci_low": float(np.percentile(distribution, 2.5)), + "ci_high": float(np.percentile(distribution, 97.5)), + "bootstrap_samples": bootstrap_samples, + }) + return output + + +def per_seed_deltas( + reference_dirs: Mapping[int, Path], + candidate_dirs: Mapping[int, Path], +) -> list[dict[str, object]]: + output = [] + for seed in SEEDS: + reference = [ + row for row in read_csv(reference_dirs[seed] / "per_hand_frame_metrics.csv") + if int(row["annotation_valid"]) == 1 + ] + candidate = [ + row for row in read_csv(candidate_dirs[seed] / "per_hand_frame_metrics.csv") + if int(row["annotation_valid"]) == 1 + ] + for metric in RECONSTRUCTION_METRICS: + reference_mean = statistic((row.get(metric) for row in reference), "mean") + candidate_mean = statistic((row.get(metric) for row in candidate), "mean") + if reference_mean is None or candidate_mean is None: + continue + output.append({ + "seed": seed, + "metric": metric, + "reference": reference_mean, + "candidate": candidate_mean, + "candidate_minus_reference": candidate_mean - reference_mean, + }) + return output + + +def lookup_distribution( + rows: list[dict[str, object]], group_field: str, group_value: str, + metric: str, condition: str, +) -> dict[str, object]: + matches = [ + row for row in rows + if row["group_field"] == group_field and row["group_value"] == group_value + and row["metric"] == metric and row["condition"] == condition + ] + if len(matches) != 1: + raise ValueError(f"expected one distribution row, found {len(matches)}") + return matches[0] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-root", type=Path, required=True) + parser.add_argument("--candidate-root", type=Path, required=True) + parser.add_argument("--role", default="best_absolute") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--prefix", required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + reference_dirs = discover_evaluations(args.reference_root, args.role) + candidate_dirs = discover_evaluations(args.candidate_root, args.role) + reconstruction = {} + temporal = {} + for name, directories in (("reference", reference_dirs), ("candidate", candidate_dirs)): + reconstruction[name] = aggregate_seed_rows({ + seed: read_csv(directory / "per_hand_frame_metrics.csv") + for seed, directory in directories.items() + }, RECONSTRUCTION_KEY, RECONSTRUCTION_METRICS) + temporal[name] = aggregate_seed_rows({ + seed: read_csv(directory / "per_temporal_transition_metrics.csv") + for seed, directory in directories.items() + }, TEMPORAL_KEY, TEMPORAL_METRICS) + assert_pair_alignment( + reconstruction["reference"], reconstruction["candidate"], + RECONSTRUCTION_KEY, RECONSTRUCTION_METADATA, + ) + assert_pair_alignment( + temporal["reference"], temporal["candidate"], + TEMPORAL_KEY, ("take", "frame_id_from", "frame_id_to", "side"), + ) + reconstruction_rows = distribution_rows( + reconstruction["reference"], reconstruction["candidate"], + RECONSTRUCTION_METRICS, require_annotation_valid=True, + ) + temporal_rows = distribution_rows( + temporal["reference"], temporal["candidate"], + TEMPORAL_METRICS, require_annotation_valid=False, + ) + valid_reference = [ + row for row in reconstruction["reference"] if int(row["annotation_valid"]) == 1 + ] + valid_candidate = [ + row for row in reconstruction["candidate"] if int(row["annotation_valid"]) == 1 + ] + group_specs = groups(valid_reference) + paired_rows = paired_take_bootstrap( + valid_reference, valid_candidate, RECONSTRUCTION_METRICS, + group_specs, statistics=("mean",), + bootstrap_samples=args.bootstrap_samples, seed=args.seed, + ) + paired_rows.extend(paired_take_bootstrap( + valid_reference, valid_candidate, ("translation_z_mae_mm",), + group_specs, statistics=("p95", "cvar95"), + bootstrap_samples=args.bootstrap_samples, seed=args.seed + 1, + )) + paired_rows.extend(paired_take_bootstrap( + temporal["reference"], temporal["candidate"], TEMPORAL_METRICS, + [("all", "all"), ("side", "left"), ("side", "right")], + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 2, + )) + seed_rows = per_seed_deltas(reference_dirs, candidate_dirs) + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / f"{args.prefix}_comparison.csv", reconstruction_rows + temporal_rows) + write_csv(args.output_dir / f"{args.prefix}_paired_take_bootstrap_ci.csv", paired_rows) + write_csv(args.output_dir / f"{args.prefix}_seed_stability.csv", seed_rows) + + def reduction(group_field: str, group_value: str, metric: str, statistic_name: str) -> float: + reference = lookup_distribution( + reconstruction_rows, group_field, group_value, metric, "reference", + )[statistic_name] + candidate = lookup_distribution( + reconstruction_rows, group_field, group_value, metric, "candidate", + )[statistic_name] + return 100.0 * (float(reference) - float(candidate)) / float(reference) + + gate = { + "z_p95_reduction_percent": reduction( + "all", "all", "translation_z_mae_mm", "p95", + ), + "small_absolute_reduction_percent": reduction( + "hand_size_bucket", "small", "absolute_mpjpe_mm", "mean", + ), + } + report = { + "status": "summarized", + "official_test_used": False, + "reference_root": str(args.reference_root.resolve()), + "candidate_root": str(args.candidate_root.resolve()), + "role": args.role, + "seeds": list(SEEDS), + "aggregation": "mean each aligned per-frame error over three seeds before distributions", + "confidence_interval_unit": "paired official-validation take", + "gate_diagnostics": gate, + "outputs": { + "comparison": f"{args.prefix}_comparison.csv", + "paired_take_bootstrap_ci": f"{args.prefix}_paired_take_bootstrap_ci.csv", + "seed_stability": f"{args.prefix}_seed_stability.csv", + }, + } + (args.output_dir / f"{args.prefix}.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_wave0.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_wave0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3340a99b19f9ae02a56d0a239a6f936d60ab8a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase4_wave0.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +"""Aggregate three frozen Phase 3 references into Phase 4 Wave 0 diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.phase4 import find_failure_intervals + + +SEEDS = (20260716, 20260717, 20260718) +MEAN_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", +) +STABLE_FIELDS = ( + "clip_index", + "time_index", + "take", + "subject", + "sequence", + "frame_id", + "side", + "annotation_valid", + "annotation_state", + "hand_size_px", + "hand_size_bucket", + "wrist_depth_m", + "depth_bucket", + "action_family", + "action_label", + "action_name", + "bimanual_size_ratio", + "bimanual_depth_gap_m", + "right_minus_left_depth_m", + "bimanual_asymmetry_bucket", + "local_depth_valid_fraction", + "local_depth_validity_bucket", + "local_depth_median_m", + "local_depth_q10_m", + "local_depth_q90_m", + "local_depth_iqr_m", + "local_depth_discontinuity_m", + "local_surface_minus_wrist_z_m", + "target_wrist_x_m", + "target_wrist_y_m", + "target_wrist_z_m", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + return + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: object) -> float | None: + if value in (None, ""): + return None + number = float(value) + return number if np.isfinite(number) else None + + +def classify_failure(row: dict[str, Any]) -> str: + if not int(row["annotation_valid"]): + return "annotation_invalid" + wrong_side = optional_float(row.get("wrong_side_preference_mean")) + z_error = float(row["translation_z_mae_mm_mean"]) + root_error = float(row["root_relative_mpjpe_mm_mean"]) + direct_2d = float(row["direct_2d_error_px_mean"]) + conditions = { + "identity": wrong_side is not None and wrong_side >= 0.5, + "z": z_error >= 40.0, + "articulation": root_error >= 30.0, + "localization_2d": direct_2d >= 20.0, + } + active = [name for name, enabled in conditions.items() if enabled] + if not active: + return "nominal" + if active == ["z"]: + return "z_translation_dominant" + if active == ["articulation"]: + return "articulation_dominant" + if active == ["localization_2d"]: + return "localization_2d_dominant" + if active == ["identity"]: + return "identity_assignment" + return "mixed_failure" + + +def aggregate_seed_rows(rows_by_seed: dict[int, list[dict[str, str]]]) -> list[dict[str, Any]]: + reference = rows_by_seed[SEEDS[0]] + for seed in SEEDS[1:]: + rows = rows_by_seed[seed] + if len(rows) != len(reference): + raise ValueError(f"seed {seed} row count differs: {len(rows)} != {len(reference)}") + output: list[dict[str, Any]] = [] + for index, reference_row in enumerate(reference): + row: dict[str, Any] = {field: reference_row.get(field, "") for field in STABLE_FIELDS} + for seed in SEEDS[1:]: + candidate = rows_by_seed[seed][index] + for field in STABLE_FIELDS: + if candidate.get(field, "") != reference_row.get(field, ""): + raise ValueError(f"target field mismatch at row {index}, seed {seed}, {field}") + row["annotation_valid"] = int(reference_row["annotation_valid"]) + row["clip_index"] = int(reference_row["clip_index"]) + row["time_index"] = int(reference_row["time_index"]) + row["frame_id"] = int(reference_row["frame_id"]) + for metric in MEAN_METRICS + ("wrong_side_preference",): + values = [optional_float(rows_by_seed[seed][index].get(metric)) for seed in SEEDS] + finite = np.asarray([value for value in values if value is not None], dtype=np.float64) + row[f"{metric}_mean"] = float(finite.mean()) if finite.size else None + row[f"{metric}_std"] = float(finite.std(ddof=1)) if finite.size > 1 else 0.0 if finite.size else None + row["failure_type"] = classify_failure(row) + output.append(row) + return output + + +def take_side_metrics(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for row in rows: + if int(row["annotation_valid"]): + grouped[(str(row["take"]), str(row["side"]))].append(row) + output = [] + for (take, side), items in sorted(grouped.items()): + record: dict[str, Any] = { + "take": take, + "side": side, + "valid_hand_frames": len(items), + "action_family": items[0]["action_family"], + "hand_size_px_mean": np.mean([float(row["hand_size_px"]) for row in items]), + "wrist_depth_m_mean": np.mean([float(row["wrist_depth_m"]) for row in items]), + "local_depth_valid_fraction_mean": np.mean([ + float(row["local_depth_valid_fraction"]) for row in items + if row["local_depth_valid_fraction"] not in (None, "") + ]), + "strong_asymmetry_fraction": np.mean([ + row["bimanual_asymmetry_bucket"] == "strong" for row in items + if row["bimanual_asymmetry_bucket"] not in (None, "") + ]), + } + for metric in ( + "absolute_mpjpe_mm_mean", + "root_relative_mpjpe_mm_mean", + "absolute_mpvpe_mm_mean", + "fingertip_mpjpe_mm_mean", + "direct_2d_error_px_mean", + "mano_projected_2d_error_px_mean", + "translation_x_mae_mm_mean", + "translation_y_mae_mm_mean", + "translation_z_mae_mm_mean", + "translation_z_signed_error_mm_mean", + ): + summary = distribution_summary(row[metric] for row in items) + base = metric.removesuffix("_mean") + record[f"{base}_mean"] = summary["mean"] + record[f"{base}_p95"] = summary["p95"] + record[f"{base}_cvar95"] = summary["cvar95"] + output.append(record) + return output + + +def select_challenge_subset( + rows: list[dict[str, Any]], + *, + seed: int, + target_clips: int = 128, +) -> tuple[list[int], list[dict[str, Any]], dict[str, float]]: + if target_clips < 112: + raise ValueError("challenge subset needs at least 112 clips for failure/control coverage") + valid = [row for row in rows if int(row["annotation_valid"])] + depths = np.asarray([float(row["wrist_depth_m"]) for row in valid], dtype=np.float64) + farthest_observed_threshold = float(np.percentile(depths, 80)) + z_median = float(np.median([row["translation_z_mae_mm_mean"] for row in valid])) + selected: dict[int, dict[str, Any]] = {} + failure_clips: set[int] = set() + + def sample_record(row: dict[str, Any], reason: str) -> dict[str, Any]: + return { + "clip_index": int(row["clip_index"]), + "time_index": int(row["time_index"]), + "take": row["take"], + "frame_id": int(row["frame_id"]), + "side": row["side"], + "action_label": int(row["action_label"]), + "action_name": row["action_name"], + "hand_size_px": float(row["hand_size_px"]), + "wrist_depth_m": float(row["wrist_depth_m"]), + "absolute_mpjpe_mm_mean": float(row["absolute_mpjpe_mm_mean"]), + "translation_z_mae_mm_mean": float(row["translation_z_mae_mm_mean"]), + "reasons": [reason], + } + + def add_failure( + candidates: list[dict[str, Any]], + count: int, + reason: str, + metric: str, + ) -> None: + if count <= 0: + return + ordered = sorted( + candidates, + key=lambda row: (-float(row[metric]), str(row["take"]), int(row["frame_id"]), str(row["side"])), + ) + added = 0 + for row in ordered: + clip_index = int(row["clip_index"]) + if clip_index in selected: + if reason not in selected[clip_index]["reasons"]: + selected[clip_index]["reasons"].append(reason) + continue + selected[clip_index] = sample_record(row, reason) + failure_clips.add(clip_index) + added += 1 + if added >= count: + break + + for side, right_count, left_count in (("right", 12, 0), ("left", 0, 8)): + add_failure( + [row for row in valid if row["side"] == side], + right_count + left_count, + "high_z_error", + "translation_z_mae_mm_mean", + ) + for side in ("left", "right"): + add_failure( + [row for row in valid if row["side"] == side], + 8, + "high_absolute_error", + "absolute_mpjpe_mm_mean", + ) + add_failure([ + row for row in valid + if row["side"] == side + and row["hand_size_bucket"] == "small" + and float(row["wrist_depth_m"]) >= farthest_observed_threshold + ], 6, "farthest_observed_small_hand", "translation_z_mae_mm_mean") + add_failure([ + row for row in valid + if row["side"] == side and row["bimanual_asymmetry_bucket"] == "strong" + ], 6, "strong_bimanual_asymmetry", "translation_z_mae_mm_mean") + add_failure([ + row for row in valid + if row["side"] == side and int(row["action_label"]) != 0 + ], 2, "object_interaction", "absolute_mpjpe_mm_mean") + + for side in ("left", "right"): + side_count = sum(selected[index]["side"] == side for index in failure_clips) + add_failure( + [row for row in valid if row["side"] == side], + max(0, 32 - side_count), + "failure_balance_fill", + "translation_z_mae_mm_mean", + ) + + # Add one ordinary low-z control for every take and side. These 48 clips + # prevent the diagnostic from collapsing onto a few known failure takes. + controls = [row for row in valid if float(row["translation_z_mae_mm_mean"]) <= z_median] + for take in sorted({str(row["take"]) for row in valid}): + for side in ("left", "right"): + candidates = [ + row for row in controls + if row["take"] == take + and row["side"] == side + and int(row["clip_index"]) not in selected + ] + candidates.sort(key=lambda row: ( + abs(float(row["translation_z_mae_mm_mean"]) - z_median), + int(row["frame_id"]), + )) + if candidates: + record = sample_record(candidates[0], "take_side_low_z_control") + selected[int(record["clip_index"])] = record + + challenge_samples = [selected[index] for index in sorted(failure_clips)] + rng = np.random.default_rng(seed) + challenge_order = rng.permutation(len(challenge_samples)) + for challenge_index in challenge_order: + if len(selected) >= target_clips: + break + challenge = challenge_samples[int(challenge_index)] + matches = [ + row for row in controls + if int(row["action_label"]) == int(challenge["action_label"]) + and row["side"] == challenge["side"] + and int(row["clip_index"]) not in selected + ] + if not matches: + continue + matches.sort(key=lambda row: ( + abs(float(row["hand_size_px"]) - float(challenge["hand_size_px"])) + / max(float(challenge["hand_size_px"]), 1.0) + + abs(float(row["wrist_depth_m"]) - float(challenge["wrist_depth_m"])) / 0.1, + str(row["take"]), + int(row["frame_id"]), + )) + match = matches[0] + record = sample_record(match, "same_action_low_z_matched_control") + record["matched_to_clip_index"] = int(challenge["clip_index"]) + selected[int(record["clip_index"])] = record + + if len(selected) < target_clips: + ordinary = sorted( + controls, + key=lambda row: ( + abs(float(row["translation_z_mae_mm_mean"]) - z_median), + int(row["action_label"]), + str(row["side"]), + int(row["clip_index"]), + ), + ) + for row in ordinary: + if len(selected) >= target_clips: + break + clip_index = int(row["clip_index"]) + if clip_index in selected: + continue + selected[clip_index] = sample_record(row, "ordinary_action_matched_fill") + samples = sorted(selected.values(), key=lambda row: int(row["clip_index"])) + return [int(row["clip_index"]) for row in samples], samples, { + "farthest_observed_wrist_depth_p80_m": farthest_observed_threshold, + "reference_z_error_median_mm": z_median, + } + + +def compare_legacy_outputs( + evaluation_root: Path, + checkpoint_index: dict[str, Any], +) -> list[dict[str, Any]]: + records = [] + for run in checkpoint_index["runs"].values(): + seed = int(run["seed"]) + original = Path(run["roles"]["tail_best_absolute"]["evaluation"]).parent + current = evaluation_root / f"seed_{seed}" + original_report = json.loads((original / "evaluation.json").read_text(encoding="utf-8")) + current_report = json.loads((current / "evaluation.json").read_text(encoding="utf-8")) + exact = True + for metric, summary in original_report["metrics"].items(): + for statistic, value in summary.items(): + exact &= current_report["metrics"][metric][statistic] == value + for filename in ("per_hand_frame_metrics.csv", "per_temporal_transition_metrics.csv"): + old_rows = read_csv(original / filename) + new_rows = read_csv(current / filename) + exact &= len(old_rows) == len(new_rows) + if exact: + for old_row, new_row in zip(old_rows, new_rows, strict=True): + exact &= all(new_row[key] == value for key, value in old_row.items()) + records.append({ + "seed": seed, + "checkpoint_sha256": current_report["checkpoint"]["sha256"], + "manifest_sha256": current_report["manifest"]["sha256"], + "clips": current_report["clips"], + "frames": current_report["frames"], + "legacy_outputs_exact": bool(exact), + "source_phase3_evaluation": str(original), + "phase4_evaluation": str(current.resolve()), + }) + if not all(record["legacy_outputs_exact"] for record in records): + raise ValueError("Phase 4 evaluator does not reproduce Phase 3 outputs exactly") + return sorted(records, key=lambda row: int(row["seed"])) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--evaluation-root", + type=Path, + default=Path("artifacts/phase4/wave0/reference_evaluations"), + ) + parser.add_argument( + "--checkpoint-index", + type=Path, + default=Path("artifacts/phase3/reports/long_tail_checkpoints.json"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/reports")) + parser.add_argument( + "--challenge-output", + type=Path, + default=Path("artifacts/phase4/challenge_subset/official_val_challenge_128.json"), + ) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + args.challenge_output.parent.mkdir(parents=True, exist_ok=True) + + checkpoint_index = json.loads(args.checkpoint_index.read_text(encoding="utf-8")) + consistency = compare_legacy_outputs(args.evaluation_root, checkpoint_index) + rows_by_seed = { + seed: read_csv(args.evaluation_root / f"seed_{seed}" / "per_hand_frame_metrics.csv") + for seed in SEEDS + } + aggregated = aggregate_seed_rows(rows_by_seed) + valid = [row for row in aggregated if int(row["annotation_valid"])] + take_rows = take_side_metrics(aggregated) + write_csv(args.output_dir / "take_side_metrics.csv", take_rows) + write_csv(args.output_dir / "failure_taxonomy.csv", aggregated) + + failure_intervals = find_failure_intervals( + [ + {**row, "translation_z_mae_mm": row["translation_z_mae_mm_mean"]} + for row in aggregated + ], + metric="translation_z_mae_mm", + threshold=40.0, + minimum_frames=3, + ) + find_failure_intervals( + [ + {**row, "absolute_mpjpe_mm": row["absolute_mpjpe_mm_mean"]} + for row in aggregated + ], + metric="absolute_mpjpe_mm", + threshold=50.0, + minimum_frames=3, + ) + write_csv(args.output_dir / "wave0_failure_intervals.csv", failure_intervals) + + bootstrap_metrics = tuple(f"{metric}_mean" for metric in MEAN_METRICS[:10]) + bootstrap_rows = bootstrap_take_means( + valid, + bootstrap_metrics, + seed=args.seed, + samples=10_000, + ) + write_csv(args.output_dir / "wave0_reference_take_bootstrap_ci.csv", bootstrap_rows) + + clip_indices, challenge_samples, thresholds = select_challenge_subset( + aggregated, + seed=args.seed, + target_clips=128, + ) + validation_manifest = Path( + json.loads( + (args.evaluation_root / f"seed_{SEEDS[0]}" / "evaluation.json").read_text( + encoding="utf-8" + ) + )["manifest"]["path"] + ) + challenge_manifest = { + "version": "phase4_official_val_challenge_v1", + "seed": args.seed, + "count": len(clip_indices), + "source_manifest": str(validation_manifest), + "source_manifest_sha256": sha256(validation_manifest), + "source_clip_count": 1495, + "dataset_contract": {"resolution_hw": [368, 640], "T": 8, "stride": 1}, + "source_checkpoints": [ + {"seed": record["seed"], "sha256": record["checkpoint_sha256"]} + for record in consistency + ], + "selection_policy": ( + "secondary diagnostic only: high z/absolute error, farthest-observed small hands, " + "strong bimanual asymmetry, object interaction, same-action low-z controls, and " + "ordinary matched fill" + ), + "thresholds": thresholds, + "far_note": ( + "Official validation has no valid wrist z >= 0.8 m. The challenge therefore uses " + "the observed validation wrist-depth P80 and labels it farthest-observed, not far." + ), + "checkpoint_selection_allowed": False, + "training_sampler_use_allowed": False, + "official_test_used": False, + "clip_indices": sorted(clip_indices), + "reason_counts": dict(Counter( + reason for sample in challenge_samples for reason in sample["reasons"] + )), + "samples": challenge_samples, + } + args.challenge_output.write_text( + json.dumps(challenge_manifest, indent=2) + "\n", encoding="utf-8" + ) + write_csv(args.challenge_output.with_suffix(".csv"), challenge_samples) + + taxonomy_counts = Counter(str(row["failure_type"]) for row in aggregated) + report = { + "status": "passed", + "official_test_used": False, + "evaluator_commit": "222b247cbf574faa9c9051832d0d51077df4573c", + "consistency": consistency, + "valid_hand_frames": len(valid), + "failure_taxonomy_counts": dict(taxonomy_counts), + "long_failure_intervals": len(failure_intervals), + "challenge_manifest": str(args.challenge_output.resolve()), + "challenge_manifest_sha256": sha256(args.challenge_output), + "challenge_clips": len(clip_indices), + } + (args.output_dir / "WAVE0_AUDIT.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase7_sequence_cache.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase7_sequence_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee2c43bea6622923c9cf4735cfd8610f5aeae19 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase7_sequence_cache.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Summarize frozen offline/causal sequence caches with static and dynamic metrics.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from foundation_hand.models.mano import ManoCameraLayer +from scripts.evaluate_phase4_jitter import ( + condition_grid, filtered_parameters, identity_switch_metrics, load_take, + per_frame_metrics, rebuild_geometry, temporal_metrics, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_manifest(manifest: dict[str, Any], path: Path) -> None: + if ( + manifest.get("status") != "complete" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_validation_used_for_selection") is not False + or manifest.get("official_test_used") is not False + or manifest.get("sequence_mode") not in {"offline", "causal"} + or int(manifest.get("sequence_window", -1)) < 1 + ): + raise ValueError(f"invalid frozen sequence cache manifest: {path}") + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"cannot write empty sequence summary: {path}") + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + + +def aligned_metrics(arrays: dict[str, np.ndarray], joints: np.ndarray) -> dict[str, list[float]]: + values: dict[str, list[float]] = defaultdict(list) + valid = arrays["joint_annotation_valid"].astype(bool) + valid &= arrays["frame_valid"][:, None].astype(bool) + for side in range(2): + indices = np.where(valid[:, side])[0] + if not len(indices): + continue + target = arrays["target_joints_camera"][indices, side] + predicted = joints[indices, side] + values["rigid_se3_mpjpe_mm"].extend(aligned_mpjpe_mm( + predicted, target, estimate_scale=False, + ).tolist()) + values["pa_mpjpe_mm"].extend(aligned_mpjpe_mm( + predicted, target, estimate_scale=True, + ).tolist()) + return values + + +def continuous_take_arrays(arrays: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + """Normalize legacy frame-iterator indices to one continuous take stream.""" + + if str(arrays.get("sequence_mode", "")) not in {"offline", "causal"}: + raise ValueError("take cache is not a bounded sequence-inference cache") + normalized = dict(arrays) + normalized["clip_index"] = np.zeros_like(arrays["frame_id"], dtype=np.int64) + return normalized + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--bootstrap-samples", type=int, default=2000) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + validate_manifest(manifest, manifest_path) + args.output_dir.mkdir(parents=True) + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + condition = condition_grid()["F0_raw"] + global_values: dict[str, list[float]] = defaultdict(list) + take_rows: list[dict[str, Any]] = [] + for take_record in manifest["takes"]: + path = Path(take_record["path"]) + if sha256(path) != take_record["sha256"]: + raise ValueError(f"take cache hash mismatch: {path}") + arrays = continuous_take_arrays(load_take(path)) + translation, rotations, _ = filtered_parameters(arrays, condition) + vertices, joints = rebuild_geometry( + rotations, arrays["pred_shape"].astype(np.float32), translation, + mano, device, + ) + selected = arrays["frame_valid"].astype(bool) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, rotations, translation, selected, + ) + for metric, observations in temporal_metrics( + arrays, joints, projected, selected, + ).items(): + metrics[metric].extend(observations) + for metric, observations in identity_switch_metrics( + arrays, joints, selected, + ).items(): + metrics[metric].extend(observations) + for metric, observations in aligned_metrics(arrays, joints).items(): + metrics[metric].extend(observations) + row: dict[str, Any] = {"take": str(arrays["take"]), "frames": len(joints)} + for metric, observations in metrics.items(): + global_values[metric].extend(observations) + summary = distribution_summary(observations) + row[metric] = summary["mean"] + row[f"{metric}_p95"] = summary["p95"] + take_rows.append(row) + all_fields = sorted({key for row in take_rows for key in row}) + normalized_rows = [{key: row.get(key) for key in all_fields} for row in take_rows] + write_csv(args.output_dir / "take_metrics.csv", normalized_rows) + metric_rows = [ + {"metric": metric, **distribution_summary(observations)} + for metric, observations in sorted(global_values.items()) + ] + write_csv(args.output_dir / "metrics.csv", metric_rows) + metric_names = sorted(global_values) + bootstrap = bootstrap_take_means( + take_rows, metric_names, seed=20260717, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "take_bootstrap_ci.csv", bootstrap) + report = { + "status": "evaluated_frozen_sequence_cache", + "sequence_mode": manifest["sequence_mode"], + "causal": manifest["sequence_mode"] == "causal", + "window": manifest["sequence_window"], + "offline_stride": manifest.get("offline_stride"), + "frames": manifest["frames"], "takes": len(manifest["takes"]), + "metrics": {row["metric"]: { + key: value for key, value in row.items() if key != "metric" + } for row in metric_rows}, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], "config": manifest["config"], + "bounded_memory": { + "maximum_gpu_window_frames": manifest["maximum_gpu_window_frames"], + "maximum_cpu_input_buffer_frames": manifest["maximum_cpu_input_buffer_frames"], + }, + "take_metrics": "take_metrics.csv", "take_bootstrap_ci": "take_bootstrap_ci.csv", + "official_validation_used_for_selection": False, "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "mode": report["sequence_mode"], + "absolute_mpjpe_mm": report["metrics"]["absolute_mpjpe_mm"]["mean"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase8_cross_domain_matrix.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase8_cross_domain_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec718b00fb86cb246600b0fafc8acaeb0e86941 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase8_cross_domain_matrix.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Summarize a frozen external cross-domain matrix without frame weighting.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "rigid_se3_mpjpe_mm", + "pa_mpjpe_mm", "mpvpe_mm", "fingertip_mpjpe_mm", + "projected_mano_2d_error_px", "translation_x_mae_mm", + "translation_y_mae_mm", "translation_z_mae_mm", +) + + +def metric_mean(report: dict[str, Any], metric: str) -> float: + value = report.get("metrics", {}).get(metric) + if not isinstance(value, dict) or value.get("mean") is None: + return math.nan + return float(value["mean"]) + + +def summarize(manifest: Path, output_dir: Path) -> dict[str, Any]: + specification = json.loads(manifest.read_text(encoding="utf-8")) + if specification.get("official_test_used") is not False: + raise ValueError("matrix manifest must set official_test_used=false") + entries = specification.get("entries", []) + if not entries: + raise ValueError("matrix manifest is empty") + if output_dir.exists() and any(output_dir.iterdir()): + raise ValueError("output directory must be new or empty") + output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, Any]] = [] + checkpoint_by_condition: dict[str, str] = {} + seen: set[tuple[str, str]] = set() + for entry in entries: + condition, dataset = str(entry["condition"]), str(entry["dataset"]) + key = (condition, dataset) + if key in seen: + raise ValueError(f"duplicate matrix cell: {condition}/{dataset}") + seen.add(key) + path = Path(entry["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"non-external or non-frozen matrix result: {path}") + checkpoint_sha = str(report["checkpoint"]["sha256"]) + prior = checkpoint_by_condition.setdefault(condition, checkpoint_sha) + if prior != checkpoint_sha: + raise ValueError(f"condition uses multiple checkpoints: {condition}") + row: dict[str, Any] = { + "condition": condition, "dataset": dataset, + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint_sha256": checkpoint_sha, + "input_mode": report["input_mode"], + "clips": int(report["clips"]), "frames": int(report["frames"]), + "evaluation": str(path.resolve()), + } + coverage = report.get("metrics", {}).get("supervision_coverage") + if not isinstance(coverage, dict): + raise ValueError(f"matrix result lacks supervision coverage: {path}") + for scope in ("overall", "left", "right"): + scoped = coverage.get(scope) + if not isinstance(scoped, dict): + raise ValueError(f"matrix result lacks {scope} supervision coverage: {path}") + for supervision in ("joint3d", "translation", "vertices"): + key = f"{supervision}_valid_fraction" + if scoped.get(key) is None: + raise ValueError(f"matrix result lacks {scope}/{key}: {path}") + row[f"{scope}_{key}"] = float(scoped[key]) + row.update({metric: metric_mean(report, metric) for metric in METRICS}) + z_summary = report.get("metrics", {}).get("translation_z_mae_mm") or {} + row["translation_z_p95_mm"] = float(z_summary.get("p95", math.nan)) + rows.append(row) + conditions = sorted({row["condition"] for row in rows}) + datasets = sorted({row["dataset"] for row in rows}) + expected = {(condition, dataset) for condition in conditions for dataset in datasets} + if seen != expected: + missing = sorted(expected - seen) + raise ValueError(f"cross-domain matrix is incomplete: {missing}") + + ranks: dict[str, dict[str, float]] = {condition: {} for condition in conditions} + for dataset in datasets: + selected = sorted( + (row for row in rows if row["dataset"] == dataset), + key=lambda row: row["absolute_mpjpe_mm"], + ) + for rank, row in enumerate(selected, 1): + ranks[row["condition"]][dataset] = float(rank) + mean_rank = { + condition: sum(ranks[condition].values()) / len(datasets) + for condition in conditions + } + absolute = { + condition: { + row["dataset"]: row["absolute_mpjpe_mm"] + for row in rows if row["condition"] == condition + } + for condition in conditions + } + pareto = [] + for condition in conditions: + dominated = any( + other != condition + and all(absolute[other][dataset] <= absolute[condition][dataset] for dataset in datasets) + and any(absolute[other][dataset] < absolute[condition][dataset] for dataset in datasets) + for other in conditions + ) + if not dominated: + pareto.append(condition) + + csv_path = output_dir / "cross_domain_matrix.csv" + with csv_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "complete", "selection": "dataset_macro_mean_rank", + "conditions": conditions, "datasets": datasets, + "dataset_ranks": ranks, "mean_rank": mean_rank, + "pareto_frontier": pareto, "rows": rows, + "official_test_used": False, + } + (output_dir / "summary.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + try: + result = summarize(args.manifest, args.output_dir) + except ValueError as error: + parser.error(str(error)) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase8_egodexter.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase8_egodexter.py new file mode 100644 index 0000000000000000000000000000000000000000..20bc81db0816cfd08d32c419fc3c157447dbb500 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase8_egodexter.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Summarize the complete frozen Phase 8 EgoDexter zero-shot grid.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_egodexter_zero_shot import sha256 + + +def summarize(queue_paths: list[Path]) -> dict[str, Any]: + rows = [] + model_ids: set[str] = set() + for queue_path in queue_paths: + queue = json.loads(queue_path.read_text(encoding="utf-8")) + if ( + queue.get("egodexter_used_for_training_or_selection") is not False + or queue.get("official_test_used") is not False + ): + raise ValueError("EgoDexter queue boundary flags are invalid") + model_ids.add(queue["model_id"]) + for item in queue["evaluations"]: + report_path = Path(item["output_dir"]) / "evaluation.json" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_frozen_egodexter_zero_shot" + or report.get("model_id") != item["model_id"] + or report.get("input_mode") != item["input_mode"] + or report.get("inference_mode") != item["inference_mode"] + or report.get("checkpoint", {}).get("sha256") != item["checkpoint_sha256"] + or report.get("egodexter_used_for_training_or_selection") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid EgoDexter report: {report_path}") + for artifact in ("per_fingertip_rows", "raw_predictions"): + record = report[artifact] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"EgoDexter {artifact} is missing or differs") + metric = report["fingertip_error_mm"] + rows.append({ + "model_id": item["model_id"], + "inference_mode": item["inference_mode"], + "input_mode": item["input_mode"], + "mean_fingertip_mm": metric["mean"], + "median_fingertip_mm": metric["median"], + "p95_fingertip_mm": metric["p95"], + "visible_fingertips": report["visible_fingertips"], + "coverage_fraction": report["coverage_fraction"], + "frames": report["frames"], + "fps": report["runtime"]["frames_per_second"], + "peak_vram_gib": report["runtime"]["peak_vram_gib"], + "maximum_gpu_window_frames": report["runtime"]["maximum_gpu_window_frames"], + "maximum_cpu_input_buffer_frames": report["runtime"]["maximum_cpu_input_buffer_frames"], + "per_finger": report["per_finger"], + "per_sequence": report["per_sequence"], + "evaluation": str(report_path.resolve()), + "evaluation_sha256": sha256(report_path), + }) + expected = len(model_ids) * 6 + identities = { + (row["model_id"], row["inference_mode"], row["input_mode"]) + for row in rows + } + if len(rows) != expected or len(identities) != expected: + raise ValueError("EgoDexter summary is not a complete unique grid") + return { + "schema_version": "phase8_egodexter_summary_v1", + "status": "complete_frozen_zero_shot", + "models": sorted(model_ids), + "conditions": rows, + "selection_use": False, + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", action="append", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("summary outputs must not exist") + try: + result = summarize(args.queue) + except (KeyError, OSError, ValueError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + csv_fields = [ + "model_id", "inference_mode", "input_mode", "mean_fingertip_mm", + "median_fingertip_mm", "p95_fingertip_mm", "visible_fingertips", + "coverage_fraction", "frames", "fps", "peak_vram_gib", + "maximum_gpu_window_frames", "maximum_cpu_input_buffer_frames", + "evaluation", "evaluation_sha256", + ] + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=csv_fields, lineterminator="\n") + writer.writeheader() + writer.writerows({key: row[key] for key in csv_fields} for row in result["conditions"]) + print(json.dumps({"status": result["status"], "conditions": len(result["conditions"])}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_final_deployment.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_final_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..8a16fb5023edce3600880e38c45f2309e30f30c8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_final_deployment.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Summarize formal H2O disclosure and the final deployment contract.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.run_phase9_final_deployment_worker import completed_matches +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def mean_metric(report: dict[str, Any], name: str) -> float: + value = report["metrics"][name] + return float(value["mean"] if isinstance(value, dict) else value) + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + jobs = {job["id"]: job for job in plan["jobs"]} + if len(jobs) != 11 or any(not completed_matches(job) for job in jobs.values()): + raise ValueError("final deployment jobs are not complete and bound") + formal = {} + formal_gpu_hours = 0.0 + for mode in plan["formal_validation_modes"]: + job = jobs[f"formal_{mode}"] + path = Path(job["output_dir"]) / "evaluation.json" + report = read_json(path) + formal_gpu_hours += float(report["runtime"]["wall_seconds"]) / 3600.0 + formal[mode] = { + "report": {"path": str(path.resolve()), "sha256": sha256(path)}, + "absolute_mpjpe_mm": mean_metric(report, "absolute_mpjpe_mm"), + "root_relative_mpjpe_mm": mean_metric(report, "root_relative_mpjpe_mm"), + "fingertip_mpjpe_mm": mean_metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": float( + report["metrics"]["translation_z_mae_mm"]["p95"] + ), + "frames": int(report["frames"]), + "peak_vram_gib": float(report["runtime"]["peak_vram_gib"]), + } + variable_job = jobs["variable_length"] + variable_path = Path(variable_job["output"]) + variable = read_json(variable_path) + sequence = {} + for mode in ("offline", "causal"): + sequence[mode] = {} + for frames in plan["sequence_contract"]["ordering_lengths"]: + job = jobs[f"{mode}_w8_{frames}"] + path = Path(job["output"]) + report = read_json(path) + sequence[mode][str(frames)] = { + "report": {"path": str(path.resolve()), "sha256": sha256(path)}, + "throughput_fps": float(report["throughput_fps"]), + "peak_allocated_gib": float(report["peak_allocated_gib"]), + "maximum_gpu_window_frames": int(report["maximum_gpu_window_frames"]), + "maximum_cpu_input_buffer_frames": int( + report["maximum_cpu_input_buffer_frames"] + ), + "invariance": report.get("invariance"), + } + profile_path = Path(jobs["latency_vram"]["output"]) + profile = read_json(profile_path) + attempts = [] + total_gpu_seconds = 0.0 + for worker in plan["workers"]: + state_path = Path(worker["state"]) + state = read_json(state_path) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + ): + raise ValueError(f"final deployment worker state differs: {worker['id']}") + for attempt in state.get("attempts", []): + start = datetime.fromisoformat(attempt["start_utc"]) + end = datetime.fromisoformat(attempt["end_utc"]) + seconds = (end - start).total_seconds() + if seconds < 0: + raise ValueError("final deployment attempt duration is negative") + total_gpu_seconds += seconds + attempts.append({ + "worker": worker["id"], "id": attempt["id"], + "kind": attempt["kind"], "physical_gpu_id": attempt["physical_gpu_id"], + "start_utc": attempt["start_utc"], "end_utc": attempt["end_utc"], + "returncode": attempt["returncode"], + "gpu_hours": seconds / 3600.0, + "archived_incomplete_output": attempt.get("archived_incomplete_output"), + }) + return { + "schema_version": "phase9_final_deployment_summary_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "final_checkpoint_deployment_contract_passed", + "winner": plan["winner"], + "selected_mechanism": plan["selected_mechanism"], + "resolution_hw": plan["resolution_hw"], + "shared_augmentation": plan["shared_augmentation"], + "checkpoint": plan["checkpoint"], "config": plan["config"], + "formal_h2o_validation": formal, + "formal_h2o_validation_checkpoint_count": 1, + "formal_h2o_validation_gpu_hours": formal_gpu_hours, + "formal_h2o_validation_used_for_selection": False, + "variable_length": { + "report": {"path": str(variable_path.resolve()), "sha256": sha256(variable_path)}, + "lengths": [item["T"] for item in variable["forward_results"]], + "all_finite": all(item["all_finite"] for item in variable["forward_results"]), + }, + "sequence_inference": sequence, + "latency_vram": { + "report": {"path": str(profile_path.resolve()), "sha256": sha256(profile_path)}, + "latency": profile["latency"], + "peak_allocated_vram_gib": profile["peak_allocated_vram_gib"], + "supported_operator_flops_per_clip": profile[ + "supported_operator_flops_per_clip" + ], + }, + "deployment_attempts": attempts, + "deployment_total_gpu_hours": total_gpu_seconds / 3600.0, + "recovery_disclosure": [ + attempt for attempt in attempts + if attempt["returncode"] != 0 + or attempt["archived_incomplete_output"] is not None + ], + "deployment_contract": { + "t_1_2_4_8_16_32_64": True, + "offline_overlap_w8_31_64_257": True, + "causal_rolling_w8_31_64_257": True, + "future_prefix_invariance": True, + "bounded_memory": True, + "fresh_resolution_latency_vram": True, + "passed": True, + }, + "selection_mutated_after_formal_validation": False, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = summarize(args.plan) + if args.output.exists(): + existing = read_json(args.output) + for key in ("created_utc",): + existing.pop(key, None) + result.pop(key, None) + if existing != result: + raise ValueError("existing final deployment summary differs") + else: + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(read_json(args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_hot_scale.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_hot_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..ed40258b5b96d9a269aa993872a60e029faed81f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_hot_scale.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Summarize the matched Phase 9 HOT unique-coverage experiment.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + +from scripts.select_phase7_external_continuation import paired_take_bootstrap + + +METRICS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "pa_mpjpe_mm": ("pa_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_x_mae_mm": ("translation_x_mae_mm", "mean"), + "translation_y_mae_mm": ("translation_y_mae_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} + + +def load_evaluation(path: Path) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(path) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_phase9_external_heldout" + or report.get("evaluation_role") != "phase9_external_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("official_test_used") is not False + ): + raise ValueError(f"evaluation role/isolation mismatch: {path}") + return report + + +def scalar(report: dict[str, Any], metric: str, statistic: str) -> float: + value = float(report["metrics"][metric][statistic]) + if not math.isfinite(value): + raise ValueError(f"non-finite {metric}.{statistic}") + return value + + +def result_row( + condition: str, unique_clips: int, source_id: str, report: dict[str, Any], +) -> dict[str, Any]: + metrics = { + output: scalar(report, metric, statistic) + for output, (metric, statistic) in METRICS.items() + } + for name in ("aria", "quest3"): + bucket = report["metrics"].get(f"bucket_headset_{name}") + metrics[f"{name}_absolute_mpjpe_mm"] = ( + None if not bucket else float(bucket["absolute_mpjpe_mm"]["mean"]) + ) + return { + "condition": condition, + "hot_unique_clips": unique_clips, + "source_id": source_id, + "checkpoint": report["checkpoint"], + "metrics": metrics, + } + + +def summarize( + registry: dict[str, Any], evaluation_root: Path, control_root: Path, +) -> dict[str, Any]: + if registry.get("official_test_used") is not False: + raise ValueError("registry must explicitly exclude official test") + clip_counts = {"J40_HOT10K": 10_000, "J40_HOT50K": 50_000} + rows: list[dict[str, Any]] = [] + checkpoint_hashes: dict[str, str] = {} + for condition in registry["conditions"]: + condition_id = str(condition["condition"]) + if condition_id not in clip_counts: + continue + hashes = set() + for source in registry["sources"]: + source_id = str(source["id"]) + report = load_evaluation( + evaluation_root / condition_id / "final505k" / source_id + / "evaluation.json" + ) + if report["cache_manifest"]["sha256"] != source["cache_manifest_sha256"]: + raise ValueError(f"manifest hash mismatch: {condition_id}/{source_id}") + hashes.add(str(report["checkpoint"]["sha256"])) + rows.append(result_row( + condition_id, clip_counts[condition_id], source_id, report, + )) + if len(hashes) != 1: + raise ValueError(f"condition uses multiple checkpoints: {condition_id}") + checkpoint_hashes[condition_id] = hashes.pop() + + control_id = "J40_HOT100K" + hashes = set() + for source in registry["sources"]: + source_id = str(source["id"]) + report = load_evaluation(control_root / source_id / "evaluation.json") + if report["cache_manifest"]["sha256"] != source["cache_manifest_sha256"]: + raise ValueError(f"control manifest hash mismatch: {source_id}") + hashes.add(str(report["checkpoint"]["sha256"])) + rows.append(result_row(control_id, 100_000, source_id, report)) + if len(hashes) != 1: + raise ValueError("HOT100K control uses multiple checkpoints") + checkpoint_hashes[control_id] = hashes.pop() + + controls = { + row["source_id"]: row for row in rows if row["condition"] == control_id + } + for row in rows: + control = controls[row["source_id"]] + row["delta_vs_hot100k"] = { + metric: ( + None if value is None or control["metrics"][metric] is None + else value - control["metrics"][metric] + ) + for metric, value in row["metrics"].items() + } + paired: dict[str, dict[str, dict[str, Any]]] = {} + for condition_id in clip_counts: + paired[condition_id] = {} + for source in registry["sources"]: + source_id = str(source["id"]) + candidate_dir = evaluation_root / condition_id / "final505k" / source_id + reference_dir = control_root / source_id + paired[condition_id][source_id] = { + metric: paired_take_bootstrap( + reference_dir / "take_metrics.csv", + candidate_dir / "take_metrics.csv", + metric, seed=20260717, resamples=2000, + ) + for metric in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + paired[condition_id][source_id]["translation_z_p95_mm"] = ( + paired_take_bootstrap( + reference_dir / "per_hand_frame_metrics.csv", + candidate_dir / "per_hand_frame_metrics.csv", + "translation_z_mae_mm", seed=20260717, resamples=2000, + statistic="p95", + ) + ) + return { + "schema_version": "phase9_hot_unique_scale_summary_v1", + "status": "complete", + "comparison": "matched_J40_final505k_source_exposure", + "checkpoint_sha256": checkpoint_hashes, + "rows": rows, + "paired_recording_bootstrap_vs_hot100k": paired, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--control-root", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("summary outputs must be new") + result = summarize( + json.loads(args.registry.read_text(encoding="utf-8")), + args.evaluation_root, args.control_root, + ) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + fields = [ + "condition", "hot_unique_clips", "source_id", "checkpoint_sha256", + *METRICS, "aria_absolute_mpjpe_mm", "quest3_absolute_mpjpe_mm", + *[f"delta_{metric}" for metric in METRICS], + ] + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for row in result["rows"]: + writer.writerow({ + "condition": row["condition"], + "hot_unique_clips": row["hot_unique_clips"], + "source_id": row["source_id"], + "checkpoint_sha256": row["checkpoint"]["sha256"], + **row["metrics"], + **{ + f"delta_{metric}": row["delta_vs_hot100k"][metric] + for metric in METRICS + }, + }) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_last2_decision.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_last2_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..0c773ab0e98bd5e250e22c0e2fbd1ae392be8b95 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_last2_decision.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Apply the strict macro-and-worst gate to one last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.summarize_phase9_resolution_decision import ( + NATIVE_EXTERNAL, + checked_report, + h2o_guardrails, + metric, +) + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def strict_gate( + control_domains: dict[str, float], candidate_domains: dict[str, float], +) -> dict[str, Any]: + if set(control_domains) != {"h2o", "hot3d", "hoi4d", "arctic"}: + raise ValueError("last-2 control domains differ") + if set(candidate_domains) != set(control_domains): + raise ValueError("last-2 candidate domains differ") + control_macro = sum(control_domains.values()) / 4 + candidate_macro = sum(candidate_domains.values()) / 4 + control_worst = max(control_domains.values()) + candidate_worst = max(candidate_domains.values()) + macro = candidate_macro < control_macro + worst = candidate_worst < control_worst + return { + "control_macro_absolute_mm": control_macro, + "candidate_macro_absolute_mm": candidate_macro, + "macro_delta_mm": candidate_macro - control_macro, + "macro_strictly_improved": macro, + "control_worst_domain_absolute_mm": control_worst, + "candidate_worst_domain_absolute_mm": candidate_worst, + "worst_domain_delta_mm": candidate_worst - control_worst, + "worst_domain_strictly_improved": worst, + "accepted": macro and worst, + } + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if len(evaluations) != 25: + raise ValueError("last-2 evaluation count differs") + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"last-2 evaluation incomplete: {item['id']}") + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + control_reports = {} + for identifier, item in plan["control_reports"].items(): + path = Path(item["path"]) + if not path.is_file() or item["sha256"] != sha256(path): + raise ValueError(f"last-2 control report hash differs: {identifier}") + control_reports[identifier] = checked_report( + path, item["evaluation_role"], item["input_mode"], + ) + control_external = { + dataset: control_reports[f"full_{dataset}_{mode}"] + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = { + (fold, mode): control_reports[f"{fold}_{mode}"] + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + gate = strict_gate(control_domains, candidate_domains) + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + candidate = plan["candidate"] + return { + "schema_version": "phase9_last2_candidate_decision_v1", + "status": "complete", "candidate": candidate, + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": ( + f"accept_last2_{candidate}" if gate["accepted"] + else f"reject_last2_{candidate}" + ), + "backbone_learning_rate": plan["backbone_learning_rate"], + "resolution_hw": plan["resolution_hw"], + "shared_augmentation": plan["shared_augmentation"], + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "control_evaluation_plan": plan["control_evaluation_plan"], + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "dino_large_admitted": False, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("last-2 candidate decision output must be new") + result = summarize(args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_resolution_decision.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_resolution_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..0341ee8e004ae8b5d4fc699ded58fb19dfec1eab --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_resolution_decision.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Apply the frozen Stage 7 resolution gate and report all guardrails.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +FOLDS = ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", +) +NATIVE_EXTERNAL = { + "hot3d": "rgb_k", "hoi4d": "rgb_d_k", "arctic": "rgb_k", +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def checked_report(path: Path, role: str, mode: str) -> dict[str, Any]: + report = read_json(path) + if ( + report.get("status") != f"evaluated_{role}" + or report.get("evaluation_role") != role + or report.get("input_mode") != mode + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution decision input differs: {path}") + return report + + +def metric(report: dict[str, Any], name: str, statistic: str = "mean") -> float: + value = report.get("metrics", {}).get(name, {}).get(statistic) + if value is None or not math.isfinite(float(value)): + raise ValueError(f"missing finite metric {name}.{statistic}") + return float(value) + + +def h2o_guardrails(reports: dict[tuple[str, str], dict[str, Any]]) -> dict[str, Any]: + result = {} + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + selected = [reports[(fold, mode)] for fold in FOLDS] + absolute = [metric(report, "absolute_mpjpe_mm") for report in selected] + root = [metric(report, "root_relative_mpjpe_mm") for report in selected] + fingertip = [metric(report, "fingertip_mpjpe_mm") for report in selected] + z_tail = [ + metric(report, "translation_z_mae_mm", "p95") for report in selected + ] + result[mode] = { + "absolute_macro_mm": sum(absolute) / len(absolute), + "absolute_worst_fold_mm": max(absolute), + "root_relative_macro_mm": sum(root) / len(root), + "fingertip_macro_mm": sum(fingertip) / len(fingertip), + "translation_z_p95_macro_mm": sum(z_tail) / len(z_tail), + "translation_z_p95_worst_fold_mm": max(z_tail), + "fold_absolute_mm": dict(zip(FOLDS, absolute, strict=True)), + } + return result + + +def gate_decision( + control_domains: dict[str, float], candidate_domains: dict[str, float], + relative_limit: float, +) -> dict[str, Any]: + if set(control_domains) != {"h2o", "hot3d", "hoi4d", "arctic"}: + raise ValueError("resolution control domains differ") + if set(candidate_domains) != set(control_domains): + raise ValueError("resolution candidate domains differ") + control_macro = sum(control_domains.values()) / 4 + candidate_macro = sum(candidate_domains.values()) / 4 + control_worst = max(control_domains.values()) + candidate_worst = max(candidate_domains.values()) + worst_relative_regression = (candidate_worst - control_worst) / control_worst + macro_improved = candidate_macro < control_macro + worst_passed = worst_relative_regression <= relative_limit + return { + "control_macro_absolute_mm": control_macro, + "candidate_macro_absolute_mm": candidate_macro, + "macro_delta_mm": candidate_macro - control_macro, + "macro_strictly_improved": macro_improved, + "control_worst_domain_absolute_mm": control_worst, + "candidate_worst_domain_absolute_mm": candidate_worst, + "worst_domain_relative_regression": worst_relative_regression, + "worst_domain_relative_regression_limit": relative_limit, + "worst_domain_gate_passed": worst_passed, + "accepted": macro_improved and worst_passed, + } + + +def summarize( + plan_path: Path, control_external_root: Path, + control_fold_final_root: Path, control_fold_milestone_root: Path, +) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"resolution evaluation is incomplete: {item['id']}") + + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + + control = plan["control_evidence"] + mixture = control["mixture"] + external_id = control["external_checkpoint_id"] + fold_id = control["fold_checkpoint_id"] + control_external = { + dataset: checked_report( + control_external_root / mixture / external_id + / f"{dataset}_{mode}" / "evaluation.json", + "phase9_external_heldout", mode, + ) + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = {} + for fold in FOLDS: + condition = f"{mixture}_{fold}" + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + path = ( + control_fold_final_root / condition / mode / "evaluation.json" + if fold_id == "final" + else control_fold_milestone_root / condition / fold_id + / mode / "evaluation.json" + ) + control_h2o_reports[(fold, mode)] = checked_report( + path, "phase9_h2o_fold_heldout", mode, + ) + + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + for dataset, expected in control["absolute_mm"].items(): + if not math.isclose(control_domains[dataset], float(expected), abs_tol=1e-8): + raise ValueError(f"resolution control evidence differs: {dataset}") + gate = gate_decision( + control_domains, candidate_domains, + float(plan["gate"]["worst_domain_relative_regression_limit"]), + ) + + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + return { + "schema_version": "phase9_resolution_decision_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "accept_896x512" if gate["accepted"] else "retain_640x368", + "accepted_resolution_hw": [512, 896] if gate["accepted"] else [368, 640], + "control_resolution_hw": [368, 640], + "candidate_resolution_hw": [512, 896], + "winner": plan["winner"], + "control_checkpoint": plan["winner_checkpoint"], + "candidate_full_checkpoint": { + "path": plan["training_jobs"]["full"]["checkpoint"], + "sha256": plan["training_jobs"]["full"]["checkpoint_sha256"], + }, + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--control-external-root", type=Path, required=True) + parser.add_argument("--control-fold-final-root", type=Path, required=True) + parser.add_argument("--control-fold-milestone-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("resolution decision output must be new") + result = summarize( + args.plan, args.control_external_root, args.control_fold_final_root, + args.control_fold_milestone_root, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_resolution_evaluation_metrics.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_resolution_evaluation_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc33c1d7f19286e4dc4a9a36f79f012afae244c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_resolution_evaluation_metrics.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +"""Write the complete paired 640/896 Stage 7 metric inventory.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +FIELDS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "pa_mpjpe_mm": ("pa_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_x_mae_mm": ("translation_x_mae_mm", "mean"), + "translation_y_mae_mm": ("translation_y_mae_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def metric_values(report: dict[str, Any]) -> dict[str, float]: + result = {} + for label, (metric, statistic) in FIELDS.items(): + value = report.get("metrics", {}).get(metric, {}).get(statistic) + if not isinstance(value, (int, float)) or not math.isfinite(float(value)): + raise ValueError(f"resolution metric is missing or nonfinite: {label}") + result[label] = float(value) + return result + + +def control_path(plan: dict[str, Any], item: dict[str, Any], identifier: str) -> Path: + control = plan["control_evidence"] + mixture = control["mixture"] + if identifier.startswith("full_"): + name = identifier.removeprefix("full_") + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/external_milestones") + / mixture / control["external_checkpoint_id"] / name / "evaluation.json" + ) + fold = item["training_role"] + mode = item["input_mode"] + condition = f"{mixture}_{fold}" + if control["fold_checkpoint_id"] == "final": + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold") + / condition / mode / "evaluation.json" + ) + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold_milestones") + / condition / control["fold_checkpoint_id"] / mode / "evaluation.json" + ) + + +def checked_report(path: Path, item: dict[str, Any]) -> dict[str, Any]: + report = read_json(path) + if ( + report.get("status") != f"evaluated_{item['evaluation_role']}" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution paired report binding differs: {path}") + return report + + +def hot_headsets(report: dict[str, Any]) -> dict[str, Any]: + result = {} + for headset in ("aria", "quest3"): + metrics = report.get("metrics", {}).get(f"bucket_headset_{headset}", {}) + result[headset] = { + key: float(metrics[source][statistic]) + for key, (source, statistic) in FIELDS.items() + if source in metrics and statistic in metrics[source] + } + return result + + +def summarize(plan_path: Path, decision_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + decision = read_json(decision_path) + if ( + decision.get("status") != "complete" + or decision.get("evaluation_plan", {}).get("sha256") != sha256(plan_path) + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution decision binding differs") + owners = { + identifier: worker["owner"] + for worker in plan["workers"] for identifier in worker["evaluation_ids"] + } + rows = [] + for item in plan["evaluations"]: + if not evaluation_complete(item): + raise ValueError(f"resolution evaluation is incomplete: {item['id']}") + candidate_path = Path(item["output_dir"]) / "evaluation.json" + candidate = checked_report(candidate_path, item) + baseline_path = control_path(plan, item, item["id"]) + baseline = checked_report(baseline_path, item) + candidate_metrics = metric_values(candidate) + baseline_metrics = metric_values(baseline) + row = { + "evaluation_id": item["id"], "owner": owners[item["id"]], + "training_role": item["training_role"], "input_mode": item["input_mode"], + "evaluation_role": item["evaluation_role"], + "checkpoint_sha256": item["checkpoint_sha256"], + "config_sha256": item["config_sha256"], + "cache_manifest_sha256": item["cache_manifest_sha256"], + "clips": candidate["clips"], "frames": candidate["frames"], + "wall_seconds": candidate["runtime"]["wall_seconds"], + "gpu_hours": candidate["runtime"]["wall_seconds"] / 3600.0, + "candidate_report_sha256": sha256(candidate_path), + "control_report_sha256": sha256(baseline_path), + "candidate": candidate_metrics, "control": baseline_metrics, + "delta": { + key: candidate_metrics[key] - baseline_metrics[key] + for key in FIELDS + }, + "candidate_grouped_recording_ci": candidate["grouped_bootstrap_ci"], + "control_grouped_recording_ci": baseline["grouped_bootstrap_ci"], + } + if item["id"].startswith("full_hot3d_"): + row["hot3d_headset"] = { + "candidate": hot_headsets(candidate), "control": hot_headsets(baseline), + } + rows.append(row) + return { + "schema_version": "phase9_resolution_evaluation_metrics_v1", + "status": "complete", "created_utc": datetime.now(timezone.utc).isoformat(), + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "decision_report": {"path": str(decision_path.resolve()), "sha256": sha256(decision_path)}, + "evaluation_count": len(rows), "paired_control_count": len(rows), + "paired_by_evaluation_id_and_identical_heldout_contract": True, + "candidate_evaluation_gpu_hours": sum(row["gpu_hours"] for row in rows), + "candidate_training_gpu_hours": decision["candidate_training_gpu_hours"], + "control_domain_absolute_mm": decision["control_domain_absolute_mm"], + "candidate_domain_absolute_mm": decision["candidate_domain_absolute_mm"], + "gate": decision["gate"], "h2o_guardrails": decision["h2o_guardrails"], + "rows": rows, + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def write_csv(path: Path, report: dict[str, Any]) -> None: + fieldnames = [ + "evaluation_id", "owner", "training_role", "input_mode", "clips", "frames", + "wall_seconds", "gpu_hours", "checkpoint_sha256", "config_sha256", + "cache_manifest_sha256", "candidate_report_sha256", "control_report_sha256", + ] + [f"{prefix}_{field}" for prefix in ("candidate", "control", "delta") for field in FIELDS] + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + for source in report["rows"]: + row = {key: source[key] for key in fieldnames if key in source} + for prefix in ("candidate", "control", "delta"): + for field in FIELDS: + row[f"{prefix}_{field}"] = source[prefix][field] + writer.writerow(row) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--decision", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("resolution metric outputs must be new") + result = summarize(args.plan, args.decision) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output_json, result) + write_csv(args.output_csv, result) + print(json.dumps({ + "status": "complete", "json_sha256": sha256(args.output_json), + "csv_sha256": sha256(args.output_csv), "evaluation_count": 25, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_shared_augmentation_decision.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_shared_augmentation_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..161b1cb515462f41add17769350833b0a3a9cc3c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_shared_augmentation_decision.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Apply Stage 8 gate and freeze whether Stage 9 has a valid predecessor.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.summarize_phase9_resolution_decision import ( + NATIVE_EXTERNAL, + checked_report, + gate_decision, + h2o_guardrails, + metric, +) + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def stage9_preceding_gate( + augmentation_accepted: bool, augmentation_gate: dict[str, Any], + resolution_decision: dict[str, Any], +) -> dict[str, Any]: + augmentation_worst_improved = ( + augmentation_gate["candidate_worst_domain_absolute_mm"] + < augmentation_gate["control_worst_domain_absolute_mm"] + ) + if augmentation_accepted: + source = "shared_augmentation" + passed = ( + augmentation_gate["macro_strictly_improved"] + and augmentation_worst_improved + ) + else: + source = "resolution" + resolution_gate = resolution_decision["gate"] + passed = ( + resolution_decision["decision"] == "accept_896x512" + and resolution_gate["macro_strictly_improved"] + and resolution_gate["candidate_worst_domain_absolute_mm"] + < resolution_gate["control_worst_domain_absolute_mm"] + ) + return { + "source_mechanism": source, + "macro_and_worst_domain_strictly_improved": passed, + "stage9_last2_admitted": passed, + } + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if len(evaluations) != 25: + raise ValueError("shared augmentation evaluation count differs") + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"augmentation evaluation incomplete: {item['id']}") + + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + control_reports = {} + for identifier, item in plan["control_reports"].items(): + path = Path(item["path"]) + if not path.is_file() or item["sha256"] != sha256(path): + raise ValueError(f"augmentation control report hash differs: {identifier}") + control_reports[identifier] = checked_report( + path, item["evaluation_role"], item["input_mode"], + ) + control_external = { + dataset: control_reports[f"full_{dataset}_{mode}"] + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = { + (fold, mode): control_reports[f"{fold}_{mode}"] + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + resolution_path = Path(plan["resolution_decision"]["path"]) + if ( + not resolution_path.is_file() + or plan["resolution_decision"]["sha256"] != sha256(resolution_path) + ): + raise ValueError("augmentation resolution decision binding differs") + resolution = read_json(resolution_path) + expected_control_domains = ( + resolution["candidate_domain_absolute_mm"] + if resolution["decision"] == "accept_896x512" + else resolution["control_domain_absolute_mm"] + ) + for dataset, expected in expected_control_domains.items(): + if not math.isclose(control_domains[dataset], float(expected), abs_tol=1e-8): + raise ValueError(f"augmentation selected control differs: {dataset}") + gate = gate_decision( + control_domains, candidate_domains, + float(plan["gate"]["worst_domain_relative_regression_limit"]), + ) + preceding = stage9_preceding_gate(gate["accepted"], gate, resolution) + + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + accepted = bool(gate["accepted"]) + return { + "schema_version": "phase9_shared_augmentation_decision_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "accept_shared_augmentation" if accepted else "reject_shared_augmentation", + "shared_augmentation_accepted": accepted, + "selected_mechanism": "shared_augmentation" if accepted else "control", + "resolution_hw": plan["resolution_hw"], + "winner": plan["winner"], + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "stage9_preceding_mechanism_gate": preceding, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "control": plan["control"], + "resolution_decision": plan["resolution_decision"], + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("shared augmentation decision output must be new") + result = summarize(args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_unified_selection.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_unified_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..829747f7fdc5bbde018e1e0026d893dd7ea8fc8c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_phase9_unified_selection.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Select a Phase 9 unified candidate with dataset-equal group-CV evidence.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +CANDIDATES = { + "J25": [ + ("all20", "all_sources_20k"), + ("all50", "all_sources_50k"), + ("all100", "all_sources_100k"), + ("final405k", "final"), + ], + "J40": [ + ("nonhot20", "nonhot_20k"), + ("nonhot50_hot100", "nonhot_50k_hot_100k"), + ("nonhot100_hot200", "nonhot_100k_hot_200k"), + ("final505k", "final"), + ], + "J55": [ + ("nonhot20", "nonhot_20k"), + ("nonhot50", "nonhot_50k"), + ("nonhot100_hot367", "nonhot_100k_hot_367k"), + ("final675k", "final"), + ], +} +NATIVE_EXTERNAL = { + "hot3d": "hot3d_rgb_k", + "hoi4d": "hoi4d_rgb_d_k", + "arctic": "arctic_rgb_k", +} +METRICS = { + "absolute": "absolute_mpjpe_mm", + "root_relative": "root_relative_mpjpe_mm", + "fingertip": "fingertip_mpjpe_mm", +} + + +def evaluation(path: Path, expected_role: str) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(path) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("evaluation_role") != expected_role + or report.get("status") != f"evaluated_{expected_role}" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"evaluation role/isolation mismatch: {path}") + return report + + +def validate_multifold_index(index: dict[str, Any]) -> list[dict[str, Any]]: + expected_folds = { + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + } + folds = index.get("folds", []) + ids = [fold.get("id") for fold in folds] + if ( + index.get("status") != "complete" + or index.get("h2o_official_validation_used") is not False + or index.get("official_test_used") is not False + or index.get("selection_metrics") + != ["fold_macro_absolute_mpjpe", "worst_fold_absolute_mpjpe"] + or len(ids) != 6 + or set(ids) != expected_folds + or any( + not fold.get("heldout", {}).get("sha256") + or not fold.get("heldout", {}).get("path") + for fold in folds + ) + ): + raise ValueError("multifold index selection/isolation contract differs") + return folds + + +def mean_metric(report: dict[str, Any], metric: str) -> float: + value = report["metrics"][metric] + if value is None or not math.isfinite(float(value["mean"])): + raise ValueError(f"missing finite metric: {metric}") + return float(value["mean"]) + + +def rank_values(values: dict[str, float]) -> dict[str, float]: + ordered = sorted(values.items(), key=lambda item: (item[1], item[0])) + ranks: dict[str, float] = {} + position = 0 + while position < len(ordered): + end = position + 1 + while end < len(ordered) and ordered[end][1] == ordered[position][1]: + end += 1 + rank = (position + 1 + end) / 2.0 + for key, _ in ordered[position:end]: + ranks[key] = rank + position = end + return ranks + + +def pareto_frontier(rows: list[dict[str, Any]], datasets: tuple[str, ...]) -> set[str]: + frontier = set() + for row in rows: + dominated = any( + other["id"] != row["id"] + and all(other["absolute_mm"][dataset] <= row["absolute_mm"][dataset] for dataset in datasets) + and any(other["absolute_mm"][dataset] < row["absolute_mm"][dataset] for dataset in datasets) + for other in rows + ) + if not dominated: + frontier.add(row["id"]) + return frontier + + +def summarize( + external_root: Path, fold_final_root: Path, fold_milestone_root: Path, + folds: list[dict[str, Any]], +) -> dict[str, Any]: + rows: list[dict[str, Any]] = [] + for mixture, candidates in CANDIDATES.items(): + for external_id, fold_id in candidates: + candidate_id = f"{mixture}:{external_id}" + external_reports = { + dataset: evaluation( + external_root / mixture / external_id / source_id / "evaluation.json", + "phase9_external_heldout", + ) + for dataset, source_id in NATIVE_EXTERNAL.items() + } + if ( + len({json.dumps(report["checkpoint"], sort_keys=True) for report in external_reports.values()}) != 1 + or len({json.dumps(report["config"], sort_keys=True) for report in external_reports.values()}) != 1 + ): + raise ValueError(f"external checkpoint/config binding differs: {candidate_id}") + fold_reports = [] + for fold_record in folds: + fold = fold_record["id"] + condition = f"{mixture}_{fold}" + root = fold_final_root if fold_id == "final" else fold_milestone_root / condition / fold_id + path = ( + root / condition / "rgb_d_k" / "evaluation.json" + if fold_id == "final" + else root / "rgb_d_k" / "evaluation.json" + ) + report = evaluation(path, "phase9_h2o_fold_heldout") + if ( + report.get("input_mode") != "rgb_d_k" + or report.get("cache_manifest", {}).get("path") + != fold_record["heldout"]["path"] + or report.get("cache_manifest", {}).get("sha256") + != fold_record["heldout"]["sha256"] + ): + raise ValueError(f"fold heldout binding differs: {condition}") + fold_reports.append(report) + h2o_absolute = [mean_metric(report, METRICS["absolute"]) for report in fold_reports] + row = { + "id": candidate_id, "mixture": mixture, + "external_checkpoint_id": external_id, + "fold_checkpoint_id": fold_id, + "checkpoint": external_reports["hot3d"]["checkpoint"], + "config": external_reports["hot3d"]["config"], + "absolute_mm": { + "h2o": sum(h2o_absolute) / len(h2o_absolute), + **{ + dataset: mean_metric(report, METRICS["absolute"]) + for dataset, report in external_reports.items() + }, + }, + "h2o_worst_fold_absolute_mm": max(h2o_absolute), + "h2o_fold_absolute_mm": dict(zip( + [fold["id"] for fold in folds], h2o_absolute, strict=True, + )), + "h2o_fold_macro_root_relative_mm": sum( + mean_metric(report, METRICS["root_relative"]) for report in fold_reports + ) / len(fold_reports), + "h2o_fold_macro_fingertip_mm": sum( + mean_metric(report, METRICS["fingertip"]) for report in fold_reports + ) / len(fold_reports), + } + rows.append(row) + datasets = ("h2o", "hot3d", "hoi4d", "arctic") + for dataset in datasets: + ranks = rank_values({row["id"]: row["absolute_mm"][dataset] for row in rows}) + best = min(row["absolute_mm"][dataset] for row in rows) + for row in rows: + row.setdefault("dataset_rank", {})[dataset] = ranks[row["id"]] + row.setdefault("normalized_regression_from_best", {})[dataset] = ( + row["absolute_mm"][dataset] - best + ) / best + frontier = pareto_frontier(rows, datasets) + for row in rows: + row["dataset_equal_mean_rank"] = sum(row["dataset_rank"].values()) / len(datasets) + row["worst_dataset_normalized_regression"] = max( + row["normalized_regression_from_best"].values() + ) + row["pareto_frontier"] = row["id"] in frontier + ordered = sorted(rows, key=lambda row: ( + row["dataset_equal_mean_rank"], + row["worst_dataset_normalized_regression"], + sum(row["absolute_mm"].values()), + row["id"], + )) + return { + "schema_version": "phase9_unified_selection_v1", + "status": "complete", + "selection_rule": "dataset_equal_mean_rank_then_worst_normalized_regression_then_sum", + "normalization": "candidate_minus_per_dataset_best divided by per_dataset_best", + "winner": ordered[0]["id"], + "winner_checkpoint": ordered[0]["checkpoint"], + "winner_config": ordered[0]["config"], + "pareto_frontier": sorted(frontier), + "candidates": ordered, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-root", type=Path, required=True) + parser.add_argument("--fold-final-root", type=Path, required=True) + parser.add_argument("--fold-milestone-root", type=Path, required=True) + parser.add_argument("--multifold-index", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("selection outputs must be new") + index = json.loads(args.multifold_index.read_text(encoding="utf-8")) + result = summarize( + args.external_root, args.fold_final_root, args.fold_milestone_root, + validate_multifold_index(index), + ) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + csv_temporary = args.output_csv.with_suffix(args.output_csv.suffix + ".tmp") + json_temporary = args.output_json.with_suffix(args.output_json.suffix + ".tmp") + with csv_temporary.open("x", newline="", encoding="utf-8") as handle: + fields = [ + "id", "mixture", "external_checkpoint_id", "fold_checkpoint_id", + "h2o_absolute_mm", "hot3d_absolute_mm", "hoi4d_absolute_mm", + "arctic_absolute_mm", "h2o_worst_fold_absolute_mm", + "dataset_equal_mean_rank", "worst_dataset_normalized_regression", + "pareto_frontier", + ] + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for row in result["candidates"]: + writer.writerow({ + **{key: row[key] for key in fields if key in row}, + **{f"{dataset}_absolute_mm": row["absolute_mm"][dataset] for dataset in ("h2o", "hot3d", "hoi4d", "arctic")}, + }) + json_temporary.write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + csv_temporary.replace(args.output_csv) + json_temporary.replace(args.output_json) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_pilots.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_pilots.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3328105d986f49810eb62ccfe40cd8a9d5dd0e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_pilots.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Create reproducible comparison tables and curves from completed pilots.""" + +from __future__ import annotations + +import argparse +import csv +import json +from datetime import datetime +from pathlib import Path + +import matplotlib.pyplot as plt + + +EXPERIMENTS_30MIN = { + "B Sequential RGB": "b_sequential_v1", + "C Alternating RGB": "c_alternating_v1", + "D Alternating RGB+K": "d_rgb_k_v1", + "E Alternating RGB+Depth": "e_rgb_depth_fixed_v1", + "F Alternating RGB+Depth+K": "f_rgb_depth_k_fixed_v1", +} + +EXPERIMENTS_2H = { + "C Alternating RGB": { + "result": "c_alternating_v3_resume_step50", + "segments": ["c_alternating_v1", "c_alternating_v2_resume_step25", "c_alternating_v3_resume_step50"], + }, + "D Alternating RGB+K": {"result": "d_rgb_k_v1", "segments": ["d_rgb_k_v1"]}, + "F Alternating RGB+Depth+K": {"result": "f_rgb_depth_k_fixed_v1", "segments": ["f_rgb_depth_k_fixed_v1"]}, +} + + +def load_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--pilot-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--suite", choices=("30min", "2h"), default="30min") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + rows = [] + bucket_rows = [] + curves = {} + if args.suite == "30min": + experiments = { + label: {"result": directory, "segments": [directory]} + for label, directory in EXPERIMENTS_30MIN.items() + } + else: + experiments = EXPERIMENTS_2H + for label, experiment in experiments.items(): + directory = experiment["result"] + root = args.pilot_root / directory + summary = load_json(root / "summary.json") + evaluation = load_json(root / "full_validation_best" / "evaluation.json") + validation = [] + training_records = [] + for segment in experiment["segments"]: + segment_root = args.pilot_root / segment + if (segment_root / "validation.jsonl").is_file(): + validation.extend(json.loads(line) for line in (segment_root / "validation.jsonl").read_text().splitlines()) + if (segment_root / "metrics.jsonl").is_file(): + training_records.extend(json.loads(line) for line in (segment_root / "metrics.jsonl").read_text().splitlines()) + validation.sort(key=lambda item: item["step"]) + training_records.sort(key=lambda item: item["step"]) + best_record = min(validation, key=lambda item: item["metrics"]["absolute_camera_mpjpe_mm"]) + metrics = evaluation["metrics"] + first_timestamp = datetime.fromisoformat(training_records[0]["timestamp"]) + last_timestamp = datetime.fromisoformat(training_records[-1]["timestamp"]) + wall_minutes = (last_timestamp - first_timestamp).total_seconds() / 60 + rows.append({ + "experiment": label, + "best_step": best_record["step"], + "trained_steps": summary["completed_step"], + "elapsed_minutes": wall_minutes, + "peak_vram_gib": summary["peak_vram_gib"], + "frames_per_s": summary["frames_per_s"], + "subset_best_absolute_mpjpe_mm": best_record["metrics"]["absolute_camera_mpjpe_mm"], + "full_absolute_mpjpe_mm": metrics["all_absolute_mpjpe_mm"], + "full_root_relative_mpjpe_mm": metrics["all_root_relative_mpjpe_mm"], + "full_joint2d_error_px": metrics["all_joint2d_error_px"], + "z_mae_mm": (metrics["left_translation_z_mae_mm"] + metrics["right_translation_z_mae_mm"]) / 2, + "velocity_error_mm_per_frame": metrics["temporal_velocity_error_mm_per_frame"], + "acceleration_error_mm_per_frame2": metrics["temporal_acceleration_error_mm_per_frame2"], + "rgb_attention_same_peak_fraction": metrics["rgb_attention_same_peak_fraction"], + "temporal_attention_entropy": metrics["temporal_attention_normalized_entropy"], + "depth_gate_mean": metrics["depth_gate_mean"], + "best_checkpoint": summary["best_checkpoint"], + }) + for bucket, values in evaluation["buckets"].items(): + bucket_rows.append({"experiment": label, "bucket": bucket, **values}) + curves[label] = validation + + with (args.output_dir / "comparison.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + with (args.output_dir / "bucket_comparison.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(bucket_rows[0])) + writer.writeheader() + writer.writerows(bucket_rows) + (args.output_dir / "comparison.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8") + + fig, axes = plt.subplots(1, 3, figsize=(16, 4.5)) + metric_names = ( + ("absolute_camera_mpjpe_mm", "Absolute MPJPE (mm)"), + ("root_relative_mpjpe_mm", "Root-relative MPJPE (mm)"), + ("translation_z_mae_mm", "Translation z MAE (mm)"), + ) + for label, records in curves.items(): + steps = [record["step"] for record in records] + for axis, (metric, title) in zip(axes, metric_names, strict=True): + axis.plot(steps, [record["metrics"][metric] for record in records], label=label) + axis.set_title(title) + axis.set_xlabel("step") + axis.grid(alpha=0.25) + axes[0].legend(fontsize=7) + fig.tight_layout() + fig.savefig(args.output_dir / "validation_curves.png", dpi=180) + plt.close(fig) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_sota_evaluation.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_sota_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..b46e9cca845bda5ca51a6087e12136c3f45da2b0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_sota_evaluation.py @@ -0,0 +1,813 @@ +#!/usr/bin/env python3 +"""Build the reproducible FoundationHand external-baseline comparison report.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +from foundation_hand.evaluation.sota import paired_take_bootstrap, write_csv_rows + + +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "joint_acceleration_error_mm_per_frame2", +) + +PROTOCOLS = { + "FoundationHand-Phase3": ( + "h2o_trained", + "H2O train;validation 子集选模", + ), + "QORT-Former": ("h2o_trained", "H2O train"), + "WiLoR-H2O-K": ("zero_shot", "无 H2O 微调;训练含 H2O3D"), + "HaWoR-camera": ("zero_shot", "发布权重无 H2O 微调"), + "WildHands-zero-shot": ( + "zero_shot", + "无 H2O;训练用 ARCTIC/AssemblyHands/EPIC", + ), + "Hamba-zero-shot": ( + "zero_shot", + "无 H2O;训练含 H2O3D", + ), + "PAD-Hand-WiLoR": ( + "zero_shot", + "无 H2O;论文训练用 DexYCB/HO3D,release checkpoint 未标具体版本", + ), + "HandDGP-zero-shot": ( + "zero_shot", + "无 H2O/H2O3D;发布权重仅用 FreiHAND 训练", + ), + "Dyn-HaMR-TTO": ( + "test_time_optimization", + "无 H2O;HaMeR initializer 含 H2O3D;每段视频独立 TTO", + ), + "WiLoR-native-camera": ("diagnostic", "同一 WiLoR 权重;原生 demo camera"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_rows(path: Path) -> list[dict[str, Any]]: + with path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + for row in rows: + for key, value in tuple(row.items()): + if value == "": + row[key] = None + return rows + + +def parameters(metadata: dict[str, Any]) -> tuple[int, int]: + if "end_to_end_parameter_count" in metadata: + return ( + int(metadata["reconstruction_parameter_count"]), + int(metadata["end_to_end_parameter_count"]), + ) + count = int(metadata["parameter_count"]) + return count, count + + +def metric_mean(report: dict[str, Any], metric: str) -> float | None: + summary = report["metrics_success_conditioned"].get(metric) + return None if summary is None else summary["mean"] + + +def temporal_mean(report: dict[str, Any], metric: str) -> float | None: + summary = report["temporal_metrics_success_conditioned"].get(metric) + return None if summary is None else summary["mean"] + + +def fmt(value: float | int | None, digits: int = 3) -> str: + if value is None: + return "N/A" + return f"{float(value):.{digits}f}" + + +def fmt_params(value: int) -> str: + return f"{value / 1_000_000:.1f}M" + + +def load_evaluation(label: str, directory: Path) -> dict[str, Any]: + report_path = directory / "evaluation.json" + frame_path = directory / "per_hand_frame_metrics.csv" + temporal_path = directory / "per_temporal_transition_metrics.csv" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("split_role") != "official_validation" + or report.get("official_test_used") is not False + ): + raise ValueError(f"Not a complete official-validation evaluation: {directory}") + model_parameters, end_to_end_parameters = parameters(report["prediction_metadata"]) + track, h2o_exposure = PROTOCOLS.get( + label, + ("uncategorized", report["prediction_metadata"].get("training_exposure", "Unknown")), + ) + row: dict[str, Any] = { + "label": label, + "model_name": report["model_name"], + "evaluation_track": track, + "h2o_exposure": h2o_exposure, + "input": report["prediction_metadata"].get("input"), + "temporal": report["prediction_metadata"].get("temporal"), + "model_parameter_count": model_parameters, + "end_to_end_parameter_count": end_to_end_parameters, + "frames": report["frames"], + "takes": report["takes"], + "annotation_valid_hand_frames": report["coverage"]["annotation_valid_hand_frames"], + "successful_hand_frames": report["coverage"]["successful_hand_frames"], + "coverage": report["coverage"]["hand_frame_fraction"], + "temporal_pair_coverage": report["coverage"]["temporal_pair_fraction"], + **{metric: metric_mean(report, metric) for metric in METRICS}, + **{metric: temporal_mean(report, metric) for metric in TEMPORAL_METRICS}, + **report["failure_aware"], + "evaluation_json": str(report_path.resolve()), + "evaluation_json_sha256": sha256(report_path), + "frame_metrics_csv": str(frame_path.resolve()), + "frame_metrics_csv_sha256": sha256(frame_path), + "temporal_metrics_csv": str(temporal_path.resolve()), + "temporal_metrics_csv_sha256": sha256(temporal_path), + } + for side in ("left", "right"): + row[f"{side}_coverage"] = report["per_side"][side]["coverage"] + row[f"{side}_absolute_mpjpe_mm"] = report["per_side"][side][ + "absolute_mpjpe_mm" + ]["mean"] + row[f"{side}_root_relative_mpjpe_mm"] = report["per_side"][side][ + "root_relative_mpjpe_mm" + ]["mean"] + return { + "label": label, + "directory": directory, + "report": report, + "frame_rows": read_rows(frame_path), + "summary": row, + } + + +def markdown_report( + evaluations: list[dict[str, Any]], + paired_rows: list[dict[str, Any]], + refinement_rows: list[dict[str, Any]], + dynhamr_hawor_rows: list[dict[str, Any]], + speed_report: dict[str, Any] | None, + *, + manifest: Path, + manifest_hash: str, + ground_truth: Path, + ground_truth_hash: str, + bootstrap_seed: int, + bootstrap_samples: int, +) -> str: + rows = [evaluation["summary"] for evaluation in evaluations] + foundation_evaluation = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "FoundationHand-Phase3" + ) + foundation_trainable = foundation_evaluation["report"]["prediction_metadata"].get( + "trainable_parameter_count_at_export" + ) + foundation_row = foundation_evaluation["summary"] + rows_by_label = {row["label"]: row for row in rows} + + comparative_note = "" + if "HaWoR-camera" in rows_by_label: + hawor_row = rows_by_label["HaWoR-camera"] + hawor_root = next( + row for row in paired_rows + if row["candidate"] == "HaWoR-camera" + and row["metric"] == "root_relative_mpjpe_mm" + ) + comparative_note = ( + "作为跨赛道描述性配对,FoundationHand 在 absolute joints/mesh、fingertip、z 和时间误差上更低;" + f"HaWoR 的逐帧 root-relative 均值虽低 " + f"{foundation_row['root_relative_mpjpe_mm'] - hawor_row['root_relative_mpjpe_mm']:.3f} mm," + f"但 take-equal paired delta 为 {hawor_root['candidate_minus_baseline']:+.3f} mm、" + f"95% CI [{hawor_root['ci95_low']:.3f}, {hawor_root['ci95_high']:.3f}]," + "只能判为等价,不能声称 HaWoR 显著更好。HaWoR 的 2D 优势有 paired CI 支持。" + ) + + qort_note = "" + if "QORT-Former" in rows_by_label: + qort_row = rows_by_label["QORT-Former"] + qort_note = ( + "具体到 QORT-Former:公开 checkpoint 在本 validation 上为 left/right " + f"{qort_row['left_absolute_mpjpe_mm']:.3f}/" + f"{qort_row['right_absolute_mpjpe_mm']:.3f} mm,没有达到论文 test 的 " + "20.1/19.9 mm 水平。它说明“公开权重在当前开发集未重现论文量级”," + "但 split 不同,所以不是论文数字错误的充分证据。" + ) + wildhands_note = "" + if "WildHands-zero-shot" in rows_by_label: + wildhands_row = rows_by_label["WildHands-zero-shot"] + wildhands_note = ( + "WildHands 发布权重在本协议的 root-relative MPJPE 为 " + f"{wildhands_row['root_relative_mpjpe_mm']:.3f} mm,与论文 H2O validation " + f"GT-box 结果 31.08 mm 相差 " + f"{wildhands_row['root_relative_mpjpe_mm'] - 31.08:.3f} mm," + "支持当前模型与关节适配的正确性。" + f"但 absolute MPJPE/z MAE 达 {wildhands_row['absolute_mpjpe_mm']:.3f}/" + f"{wildhands_row['translation_z_mae_mm']:.3f} mm,说明相对姿态接近论文量级不代表" + "绝对 camera-space 深度准确。" + ) + pad_note = "" + if "PAD-Hand-WiLoR" in rows_by_label and "WiLoR-H2O-K" in rows_by_label: + pad_row = rows_by_label["PAD-Hand-WiLoR"] + wilor_row = rows_by_label["WiLoR-H2O-K"] + pad_root = next( + row for row in refinement_rows + if row["metric"] == "root_relative_mpjpe_mm" + ) + pad_note = ( + "PAD-Hand 与 WiLoR 使用相同检测、初始化和 camera translation;其 16 帧扩散 refinement " + f"使 root-relative MPJPE 增加 " + f"{pad_row['root_relative_mpjpe_mm'] - wilor_row['root_relative_mpjpe_mm']:.3f} mm " + f"(take-equal paired delta {pad_root['candidate_minus_baseline']:+.3f} mm," + f"95% CI [{pad_root['ci95_low']:.3f}, {pad_root['ci95_high']:.3f}])," + f"但 joint velocity/acceleration error 从 " + f"{wilor_row['joint_velocity_error_mm_per_frame']:.3f}/" + f"{wilor_row['joint_acceleration_error_mm_per_frame2']:.3f} 降至 " + f"{pad_row['joint_velocity_error_mm_per_frame']:.3f}/" + f"{pad_row['joint_acceleration_error_mm_per_frame2']:.3f}。" + "因此它在 H2O 上是平滑性收益而非空间精度 SOTA。" + ) + dynhamr_note = "" + if "Dyn-HaMR-TTO" in rows_by_label: + dynhamr_row = rows_by_label["Dyn-HaMR-TTO"] + dynhamr_evaluation = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "Dyn-HaMR-TTO" + ) + dynhamr_metadata = dynhamr_evaluation["report"]["prediction_metadata"] + dynhamr_note = ( + "Dyn-HaMR 不是一次前向的重建网络:本表按每个 official-validation 连续 run " + "独立执行发布的 Root/Smooth test-time optimization,并使用已知静态 cam4 K。" + f"其 Coverage/absolute/root-relative MPJPE 为 {100 * dynhamr_row['coverage']:.2f}%/" + f"{dynhamr_row['absolute_mpjpe_mm']:.3f}/{dynhamr_row['root_relative_mpjpe_mm']:.3f} mm。" + f"94 个 run 共执行 {int(dynhamr_metadata['root_iterations_total']):,}/" + f"{int(dynhamr_metadata['smooth_iterations_total']):,} 次 Root/Smooth 外循环。" + "因此它属于高计算量 TTO 系统赛道,不能当作与 HaWoR/WiLoR 同成本的 feed-forward 模型。" + ) + if dynhamr_hawor_rows: + root_contrast = next( + row for row in dynhamr_hawor_rows + if row["metric"] == "root_relative_mpjpe_mm" + ) + dynhamr_note += ( + " 与 HaWoR 直接配对时,Dyn-HaMR 的 root-relative take-equal delta 为 " + f"{root_contrast['candidate_minus_baseline']:+.3f} mm,95% CI " + f"[{root_contrast['ci95_low']:.3f}, {root_contrast['ci95_high']:.3f}]," + "不能宣称任一方法显著更好。" + ) + h2o_trained = [row for row in rows if row["evaluation_track"] == "h2o_trained"] + zero_shot = [row for row in rows if row["evaluation_track"] == "zero_shot"] + test_time_optimization = [ + row for row in rows if row["evaluation_track"] == "test_time_optimization" + ] + diagnostics = [row for row in rows if row["evaluation_track"] == "diagnostic"] + uncategorized = [row for row in rows if row["evaluation_track"] == "uncategorized"] + h2o_absolute_winner = min( + (row for row in h2o_trained if row["absolute_mpjpe_mm"] is not None), + key=lambda row: row["absolute_mpjpe_mm"], + ) + h2o_root_winner = min( + (row for row in h2o_trained if row["root_relative_mpjpe_mm"] is not None), + key=lambda row: row["root_relative_mpjpe_mm"], + ) + zero_absolute_winner = min( + (row for row in zero_shot if row["absolute_mpjpe_mm"] is not None), + key=lambda row: row["absolute_mpjpe_mm"], + ) + zero_root_winner = min( + (row for row in zero_shot if row["root_relative_mpjpe_mm"] is not None), + key=lambda row: row["root_relative_mpjpe_mm"], + ) + zero_mesh_winner = min( + (row for row in zero_shot if row["absolute_mpvpe_mm"] is not None), + key=lambda row: row["absolute_mpvpe_mm"], + ) + zero_projected_winner = min( + (row for row in zero_shot if row["projected_2d_error_px"] is not None), + key=lambda row: row["projected_2d_error_px"], + ) + table_header = ( + "| 模型 | H2O 暴露 | 输入 | Params (模型/E2E) | Coverage | Abs MPJPE | " + "Root MPJPE | MPVPE | Root MPVPE | 2D | Fingertip | z MAE | PCK20 | AUC0-50 |" + ) + table_divider = ( + "|---|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|" + ) + speed_section: list[str] = [] + if speed_report is not None: + speed_by_label = { + row["setting_id"]: row for row in speed_report["rows"] + } + speed_section = [ + "", + "## 推理速度", + "", + ( + "同一 94 帧 H2O 连续片段、RTX 4090、包含 RGB 解码/预处理/所需 detector/" + "重建与 camera conversion 的本机实测中,批处理/时序摊销吞吐为:" + f"FoundationHand T8 {speed_by_label['FoundationHand-T8']['median_fps']:.2f} FPS," + f"QORT batch16 {speed_by_label['QORT-b16']['median_fps']:.2f} FPS," + f"WiLoR batch16 {speed_by_label['WiLoR-b16']['median_fps']:.2f} FPS," + f"HaWoR T16 {speed_by_label['HaWoR-T16']['median_fps']:.2f} FPS," + f"Dyn-HaMR TTO {speed_by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS。" + ), + "", + ( + "QORT/WiLoR 的 batch1 在线吞吐分别为 " + f"{speed_by_label['QORT-b1']['median_fps']:.2f}/" + f"{speed_by_label['WiLoR-b1']['median_fps']:.2f} FPS。" + "FoundationHand 的独立纯模型 profile 为 " + f"{speed_report['foundation_model_only_profile']['p50_ms_per_t8_clip']:.2f} ms/T8 clip," + f"即 {speed_report['foundation_model_only_profile']['amortized_frames_per_second']:.1f} frame/s;" + "完整数据路径为 T=8 RGB+Depth+K,因此二者不是同一计时口径。" + "HaWoR 与 Dyn-HaMR 是离线时序/TTO 方法,摊销 ms/frame 不是因果单帧延迟。" + "完整口径、重复范围与 Dyn-HaMR 开销拆分见 `INFERENCE_SPEED_REPORT.md`。" + ), + ] + + def result_line(row: dict[str, Any]) -> str: + return ( + f"| {row['label']} | {row['h2o_exposure']} | {row['input']} | " + f"{fmt_params(row['model_parameter_count'])}/{fmt_params(row['end_to_end_parameter_count'])} | " + f"{100 * row['coverage']:.2f}% | {fmt(row['absolute_mpjpe_mm'])} | " + f"{fmt(row['root_relative_mpjpe_mm'])} | {fmt(row['absolute_mpvpe_mm'])} | " + f"{fmt(row['root_relative_mpvpe_mm'])} | {fmt(row['projected_2d_error_px'])} | " + f"{fmt(row['fingertip_mpjpe_mm'])} | {fmt(row['translation_z_mae_mm'])} | " + f"{100 * row['absolute_pck_20mm']:.2f}% | {row['absolute_auc_0_50mm']:.4f} |" + ) + + lines = [ + "# FoundationHand 外部 SOTA 统一复评报告", + "", + "## 公平性结论", + "", + ( + "把 FoundationHand/QORT 与外部发布权重排成一个训练条件等价的 SOTA 总榜是不公平的。" + "前两者使用 H2O 训练,其余方法没有在 H2O 上微调;因此本报告改为域内训练与" + "零样本泛化两条前向赛道,并把逐视频优化方法单列为 TTO 赛道。" + "所有模型仍共享同一 validation、GT、坐标系和 evaluator。" + ), + "", + ( + f"H2O 域内训练赛道中,absolute/root-relative MPJPE 最低的分别是 " + f"**{h2o_absolute_winner['label']} ({fmt(h2o_absolute_winner['absolute_mpjpe_mm'])} mm)** " + f"和 **{h2o_root_winner['label']} ({fmt(h2o_root_winner['root_relative_mpjpe_mm'])} mm)**。" + "这仍是系统级比较:FoundationHand 使用 RGB+metric Depth+K、T=8,QORT 使用单帧 RGB。" + ), + "", + ( + f"H2O 零样本 RGB 赛道中,absolute/root-relative MPJPE 最低的分别是 " + f"**{zero_absolute_winner['label']} ({fmt(zero_absolute_winner['absolute_mpjpe_mm'])} mm)** " + f"和 **{zero_root_winner['label']} ({fmt(zero_root_winner['root_relative_mpjpe_mm'])} mm)**;" + f"absolute MPVPE 最低的是 **{zero_mesh_winner['label']} " + f"({fmt(zero_mesh_winner['absolute_mpvpe_mm'])} mm)**,投影 2D 最低的是 " + f"**{zero_projected_winner['label']} ({fmt(zero_projected_winner['projected_2d_error_px'])} px)**。" + ), + "", + comparative_note, + "", + ( + "这是一份同数据、同 GT、同坐标系、同评估器的开发集复评,不是可直接发表的官方-test " + "SOTA 声明。FoundationHand 的模型选择使用过该 validation split 的固定子集;各方法的输入模态和训练数据也不同。" + ), + "", + "## H2O 域内训练赛道", + "", + ( + "误差均为越低越好;Coverage、PCK、AUC 越高越好。MPJPE/MPVPE 是检测成功样本上的均值;" + "失败不会被静默删除,而是通过 Coverage 和 failure-aware PCK/AUC 计入。2D 误差按 Phase3 " + "约定缩放到 640x368 评估像素。" + ), + "", + table_header, + table_divider, + ] + lines.extend(result_line(row) for row in h2o_trained) + lines.extend([ + "", + "## H2O 零样本 RGB 赛道", + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in zero_shot) + if test_time_optimization: + lines.extend([ + "", + "## H2O 零样本 Test-Time Optimization 赛道", + "", + ( + "该表使用同一 H2O validation 和 evaluator,但方法在每段测试视频上优化模型变量," + "计算预算显著高于一次前向方法,因此不参与上方 zero-shot feed-forward winner 判定。" + ), + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in test_time_optimization) + if diagnostics or uncategorized: + lines.extend([ + "", + "## 诊断与未分类结果", + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in diagnostics + uncategorized) + lines.extend([ + "", + "### 左右手拆分", + "", + "| 模型 | Left coverage | Left Abs | Left Root | Right coverage | Right Abs | Right Root |", + "|---|---:|---:|---:|---:|---:|---:|", + ]) + for row in rows: + lines.append( + f"| {row['label']} | {100 * row['left_coverage']:.2f}% | " + f"{fmt(row['left_absolute_mpjpe_mm'])} | " + f"{fmt(row['left_root_relative_mpjpe_mm'])} | " + f"{100 * row['right_coverage']:.2f}% | " + f"{fmt(row['right_absolute_mpjpe_mm'])} | " + f"{fmt(row['right_root_relative_mpjpe_mm'])} |" + ) + lines.extend([ + "", + "WiLoR-H2O-K 使用已知 H2O 内参代入官方 `cam_crop_to_full` 代数,没有使用 GT pose 或拟合参数。" + "`WiLoR-native-camera` 保留发布 demo 的假设焦距,仅用于展示原样 camera translation 在 H2O 上的行为,不参与主结论。", + "", + ( + f"参数量由实际加载模块逐参数计数。FoundationHand 总参数 126.8M 中,export 时可训练参数为 " + f"{fmt_params(int(foundation_trainable)) if foundation_trainable is not None else 'N/A'}(DINO 冻结);" + "外部 RGB 方法的 E2E 数量包含实际使用的公开 detector。HaWoR 的 camera-space 表不加载与该任务无关的 " + "DROID-SLAM、Metric3D 和 world-space infiller。Dyn-HaMR 的参数数目是实际使用的 HaMeR initializer " + "与 detector;逐 run 优化变量随帧数变化,不计作网络参数。" + ), + "", + "QORT-Former 不输出 MANO mesh,因此 MPVPE 为 N/A。其 normalized `(u,v,z)` 反归一化和 K 反投影逐式复现了它所基于的官方 [H2OTR `pixel2cam`](https://github.com/chohoseong/H2OTR/blob/master/util/ops.py),不是用 GT pose 拟合得到的坐标。", + *speed_section, + "", + "## 时间指标", + "", + "| 模型 | Pair coverage | Wrist velocity | Joint velocity | Wrist acceleration | Joint acceleration |", + "|---|---:|---:|---:|---:|---:|", + ]) + for row in rows: + lines.append( + f"| {row['label']} | {100 * row['temporal_pair_coverage']:.2f}% | " + f"{fmt(row['wrist_velocity_error_mm_per_frame'])} | " + f"{fmt(row['joint_velocity_error_mm_per_frame'])} | " + f"{fmt(row['wrist_acceleration_error_mm_per_frame2'])} | " + f"{fmt(row['joint_acceleration_error_mm_per_frame2'])} |" + ) + lines.extend([ + "", + "时间差分只在同一连续 run、同一 Phase3 T=8 clip 内计算;检测失败的 pair 由 pair coverage 单独报告。", + "", + "### PAD-Hand refinement 诊断", + "", + pad_note, + "", + "### Dyn-HaMR TTO 诊断", + "", + dynhamr_note, + "", + "## 配对统计", + "", + ( + f"下表为候选模型减 FoundationHand 的 take-equal paired bootstrap;负值表示候选误差更低。" + f"每项只使用两模型都成功的精确交集,{bootstrap_samples:,} 次重采样,seed={bootstrap_seed}。" + ), + "", + "| 候选 | Metric | Paired hands | Takes | Delta | 95% CI |", + "|---|---|---:|---:|---:|---:|", + ]) + for row in paired_rows: + if row["metric"] not in ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", + ): + continue + lines.append( + f"| {row['candidate']} | {row['metric']} | {row['paired_hand_frames']} | " + f"{row['take_count']} | {fmt(row['candidate_minus_baseline'])} | " + f"[{fmt(row['ci95_low'])}, {fmt(row['ci95_high'])}] |" + ) + lines.extend([ + "", + "## 与论文原表的关系", + "", + "| 工作 | 论文报告 | 为什么不能与本表直接混排 |", + "|---|---|---|", + "| QORT-Former | H2O official test mean end-point error: left 20.1 mm, right 19.9 mm | 本报告是 official validation;论文未报告本 split 数字。指标形式接近,但 split 不同。 |", + "| WiLoR | FreiHAND PA-MPJPE/PA-MPVPE 5.5/5.1 mm;HO3D 7.5/7.7 mm | 数据集不同,且经过 Procrustes alignment;本表是 H2O 绝对 camera-space。 |", + "| HaWoR | DexYCB PA-MPJPE 4.76 mm、AUC 90.5 | 数据集不同,且 PA 对齐;本表只评 camera-space hand stage,不含 SLAM、Metric3D、world-space infiller。 |", + "| WildHands | H2O validation zero-shot root-relative MPJPE 31.08 mm、MRRPE 49.49 mm | 论文主要 ablation 使用 GT hand boxes;本表使用公开 detector,并额外报告 absolute camera-space、mesh、coverage。 |", + "| Hamba | FreiHAND PA-MPJPE/PA-MPVPE 5.8/5.5 mm(无 TTA) | 论文不报告 H2O;数据集不同且经 Procrustes alignment。本表发布配置含 H2O3D,但未含 H2O。 |", + "| PAD-Hand | DexYCB WiLoR→PAD-Hand: PA-MPJPE 4.88→4.63 mm、MPJPE 12.75→10.56 mm、ACCEL 6.70→3.34 | 本表是 H2O zero-shot,且保留 WiLoR camera translation;release checkpoint 未在 README 标明对应 DexYCB/HO3D 版本。 |", + "| HandDGP | FreiHAND camera-space MJE/MVE 46.3/46.3 mm | 发布权重仅用 FreiHAND;本表使用 H2O detector crop、已知 K 和同一 camera-space evaluator。 |", + "| Dyn-HaMR | 论文在动态相机视频上报告 global 4D hand-motion 指标 | 论文目标含相机运动与 world-space trajectory;本表因 H2O cam4 静止且 K 已知,只评每段 TTO 后的 camera-space hand 输出。 |", + "", + "因此,本复评能够检查公开 checkpoint 在同一 H2O validation 上的实际行为,但不能单独证实或否定论文 official-test 数字。", + "", + qort_note, + "", + wildhands_note, + "", + "原始来源:QORT-Former [paper](https://arxiv.org/abs/2502.19769) / [official repo](https://github.com/kcsayem/QORT-Former);WiLoR [paper](https://arxiv.org/abs/2409.12259) / [official repo](https://github.com/rolpotamias/WiLoR);HaWoR [paper](https://arxiv.org/abs/2501.02973) / [official repo](https://github.com/ThunderVVV/HaWoR);WildHands [ECCV page](https://eccv.ecva.net/virtual/2024/poster/2450) / [official repo](https://github.com/ap229997/hands);Hamba [NeurIPS paper](https://proceedings.neurips.cc/paper_files/paper/2024/hash/03e9a69e5b686c316a07d73f0cf5e225-Abstract-Conference.html) / [official repo](https://github.com/humansensinglab/Hamba);PAD-Hand [CVPR paper](https://openaccess.thecvf.com/content/CVPR2026/html/Ismayilzada_PAD-Hand_Physics-Aware_Diffusion_for_Hand_Motion_Recovery_CVPR_2026_paper.html) / [official repo](https://github.com/DominoAI-Lab/PAD-Hand-CVPR-2026);HandDGP [project](https://nianticlabs.github.io/handdgp/) / [official repo](https://github.com/nianticlabs/HandDGP);Dyn-HaMR [CVPR paper](https://openaccess.thecvf.com/content/CVPR2025/html/Yu_Dyn-HaMR_Recovering_4D_Interacting_Hand_Motion_from_a_Dynamic_Camera_CVPR_2025_paper.html) / [official repo](https://github.com/ZhengdiYu/Dyn-HaMR)。", + "", + "## 协议与公平性边界", + "", + f"- Manifest: `{manifest}`,SHA256 `{manifest_hash}`。", + f"- Ground truth bundle: `{ground_truth}`,SHA256 `{ground_truth_hash}`。", + f"- 样本:{rows[0]['frames']:,} 帧、{rows[0]['takes']} takes、{rows[0]['annotation_valid_hand_frames']:,} 个 annotation-valid hand-frames。", + "- Split:H2O official validation(subject3 held-out runs);official test(subject4)未使用。", + "- Camera:全部输出统一成 raw cam4 的 x-right/y-down/z-forward metric XYZ,再由同一 K 投影。", + "- 关节:H2O 左/右各 21 joints;mesh 统一为对应 MANO 778 vertices。", + "- FoundationHand 输入 RGB+metric Depth+K、T=8;QORT 输入单帧 RGB;WiLoR/WildHands/Hamba/HandDGP 输入 RGB detector/crop;HaWoR 与 PAD-Hand 输入 T=16 RGB track;Dyn-HaMR 对每个完整连续 run 做 TTO。协议一致不等于输入模态或计算预算一致。", + "- FoundationHand checkpoint 在 validation 固定子集上被选择;因此本报告用于开发期横向复评,最终无偏结论必须在冻结后一次性跑 official test。", + "- 直接运行 WiLoR/HaWoR/WildHands/Hamba/PAD-Hand/HandDGP 是有效的 H2O out-of-box 泛化测试,但不能解释为这些模型在 H2O 充分微调后的上限。Dyn-HaMR 已通过官方定义的 per-video TTO 适配测试序列。", + "- HandDGP 官方仓库只有 inference/evaluation;WiLoR/Hamba 只保留训练模块而缺少完整 runner/config;HaWoR 官方 README 仍写明训练代码将后续发布;PAD-Hand 仅发布 demo。自行编写微调器会形成新的派生训练配方,不能标成官方 fine-tuned baseline。", + "- 真正的 H2O fine-tuning 对照需要统一 H2O train、冻结 validation/test、同 detector/K、相同输入预算和选模规则,并同时报告 pretrained 与 fine-tuned;当前公开资产不足以严格完成这一实验。", + "- WiLoR/HaWoR 声明 CC BY-NC-ND 4.0,Hamba 声明 CC BY-NC 4.0;WildHands、QORT 与 PAD-Hand 在审计 commit 未见明确 LICENSE。MANO/Ultralytics 等依赖另有许可。当前下载与运行仅用于本地研究复评,不代表可重分发模型资产。", + "", + "## 已录用开源候选审计", + "", + "| 工作 | 状态 | 本报告处理 |", + "|---|---|---|", + "| PAD-Hand | CVPR 2026 Highlight;官方 demo 与 checkpoint | 纳入 zero-shot temporal 表;与相同 WiLoR initializer 成对报告。 |", + "| WildHands | ECCV 2024;官方代码与 checkpoint;论文明确 H2O zero-shot | 纳入零样本量化表。 |", + "| Hamba | NeurIPS 2024;官方推理代码与 checkpoint | 纳入零样本量化表;使用共同 detector 与官方 crop/initial-regressor。 |", + "| ViDiHand | 2026-06 arXiv;1.3B video diffusion + 37M decoder;metric two-hand camera-space 输出 | 方法与 H2O 高度匹配,但官方仓库仅 README,明确写明 code will be released soon;当前无 checkpoint/推理/训练代码。 |", + "| Dyn-HaMR | CVPR 2025 Highlight;官方代码、HaMeR 权重与 TTO 配置 | 已按每个连续 run、静态已知 H2O K 完整运行,单列 TTO 赛道;不是可微调 feed-forward baseline。 |", + "| HandDGP | ECCV 2024;官方 FreiHAND checkpoint 与 camera-space 推理 | 已用发布权重、官方 rectification/DGP 和共同 detector 纳入 zero-shot 表;仓库无训练入口。 |", + "| EgoHandICL | ICLR 2026;官方仓库 commit `16e5690` 含名义训练/推理文件 | 推理脚本引用未发布的 `handicl` 核心 package;Hugging Face 仅有数据/标注压缩包而无 checkpoint,README 还含 `` 与空权重路径,不能形成可审计推理或微调。 |", + "| MaskHand | ICCV 2025 | 项目页只有论文与演示;截至 2026-07-20,论文所指官方 GitHub 返回 404,无 checkpoint,无法同权重复评。 |", + "| Pose-Guided Temporal Enhancement | CVPR 2025 | 未找到作者公开的推理仓库或 checkpoint。 |", + "| OmniHands | ACM TOG 2026;官方代码与 image/video/multiview checkpoints | 任务核心是双手交互及 temporal/multiview,发布 demo 的相机输出/评估协议与本表单手 camera-space 协议不同,暂不混排。 |", + "| Enhancing Monocular 3D Hand Reconstruction with Learned Texture Priors | WACV 2026;公开 texture-supervised HaMeR 权重 | 仓库仍将完整 code release 标为未完成;待稳定发布后可按 HaMeR camera adapter 加入。 |", + "| HandOS | CVPR 2025 | 官方项目当前未提供可下载 checkpoint,无法做同权重复评。 |", + "| PS-HPME / Pseudo-Stereo-Hand | Knowledge-Based Systems 2026;目标为单目 camera-space mesh | 论文给出的官方 GitHub 地址在本次审计返回 404,无法下载代码或 checkpoint。 |", + "| SesaHand | ICLR 2026;生成数据增强重建 | 不是独立重建推理模型,官方仓库的 pretrained model 与 samples 仍标为 TBD。 |", + "| POEM-v2 | TPAMI 2025;代码/权重公开 | 多视图方法;当前冻结 H2O 产物只有 cam4,不能伪装成公平单目基线。 |", + "", + "## 公开实现与资产溯源", + "", + ]) + for evaluation in evaluations: + metadata = evaluation["report"]["prediction_metadata"] + lines.append(f"### {evaluation['label']}") + lines.append("") + if metadata.get("official_repository"): + lines.append(f"- Official repository: {metadata['official_repository']}") + lines.append(f"- Repository commit: `{metadata['repository_commit']}`") + elif metadata.get("training_commit"): + lines.append(f"- Training commit: `{metadata['training_commit']}`") + lines.append( + f"- Repository commit at export: `{metadata['repository_commit_at_export']}`" + ) + checkpoint = metadata.get("checkpoint", metadata.get("hamer_checkpoint")) + checkpoint_hash = metadata.get( + "checkpoint_sha256", metadata.get("hamer_checkpoint_sha256") + ) + lines.append(f"- Checkpoint: `{checkpoint}`") + lines.append(f"- Checkpoint SHA256: `{checkpoint_hash}`") + if metadata.get("detector_checkpoint"): + lines.append(f"- Detector: `{metadata['detector_checkpoint']}`") + lines.append( + f"- Detector SHA256: `{metadata['detector_checkpoint_sha256']}`" + ) + if metadata.get("base_wilor_checkpoint"): + lines.append( + f"- Base WiLoR commit: `{metadata['base_wilor_repository_commit']}`" + ) + lines.append(f"- Base WiLoR: `{metadata['base_wilor_checkpoint']}`") + lines.append( + f"- Base WiLoR SHA256: `{metadata['base_wilor_checkpoint_sha256']}`" + ) + lines.append(f"- Evaluation JSON SHA256: `{evaluation['summary']['evaluation_json_sha256']}`") + lines.append("") + lines.extend([ + "## 可复现产物", + "", + "- `comparison.csv`: 完整主表机器可读版本。", + "- `paired_take_bootstrap.csv`: 全指标配对差值与 CI。", + "- `pad_hand_vs_wilor_paired_take_bootstrap.csv`: PAD-Hand refinement 相对同一 WiLoR initializer 的配对差值。", + "- `dynhamr_vs_hawor_paired_take_bootstrap.csv`: Dyn-HaMR TTO 相对最强 zero-shot 前向 HaWoR 的直接配对差值。", + "- `INFERENCE_SPEED_REPORT.md`、`speed_comparison.csv` 与 `speed_report.json`: 同机统一推理速度、原始 timing 哈希和 Dyn-HaMR TTO 开销拆分。", + "- `report.json`: 汇总、论文协议旁注和所有输入文件 hash。", + "- `visual_audit/projection_contact_sheet.jpg` 与 `visual_audit/visual_audit.json`: 固定样本投影和全量正深度/画内统计。", + "- 各 evaluation 目录保留逐 hand-frame 与逐 temporal-transition CSV,可重算全部统计。", + "", + ]) + return "\n".join(lines) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--evaluation", + action="append", + required=True, + help="LABEL=directory containing evaluation.json and metric CSV files", + ) + parser.add_argument("--foundation-label", default="FoundationHand-Phase3") + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + + evaluations = [] + labels = set() + for spec in args.evaluation: + label, separator, raw_directory = spec.partition("=") + if not separator or not label or not raw_directory: + raise ValueError(f"Invalid --evaluation value: {spec}") + if label in labels: + raise ValueError(f"Duplicate evaluation label: {label}") + labels.add(label) + evaluations.append(load_evaluation(label, Path(raw_directory).resolve())) + if args.foundation_label not in labels: + raise ValueError(f"Missing foundation label: {args.foundation_label}") + baseline = next( + evaluation for evaluation in evaluations + if evaluation["label"] == args.foundation_label + ) + paired_rows: list[dict[str, Any]] = [] + for evaluation in evaluations: + if evaluation is baseline or evaluation["label"] == "WiLoR-native-camera": + continue + contrasts = paired_take_bootstrap( + baseline["frame_rows"], + evaluation["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + paired_rows.extend({ + "baseline": args.foundation_label, + "candidate": evaluation["label"], + **contrast, + } for contrast in contrasts) + + refinement_rows: list[dict[str, Any]] = [] + if "WiLoR-H2O-K" in labels and "PAD-Hand-WiLoR" in labels: + wilor = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "WiLoR-H2O-K" + ) + pad_hand = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "PAD-Hand-WiLoR" + ) + refinement_rows = [ + { + "baseline": "WiLoR-H2O-K", + "candidate": "PAD-Hand-WiLoR", + **contrast, + } + for contrast in paired_take_bootstrap( + wilor["frame_rows"], + pad_hand["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + ] + + dynhamr_hawor_rows: list[dict[str, Any]] = [] + if "HaWoR-camera" in labels and "Dyn-HaMR-TTO" in labels: + hawor = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "HaWoR-camera" + ) + dynhamr = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "Dyn-HaMR-TTO" + ) + dynhamr_hawor_rows = [ + { + "baseline": "HaWoR-camera", + "candidate": "Dyn-HaMR-TTO", + **contrast, + } + for contrast in paired_take_bootstrap( + hawor["frame_rows"], + dynhamr["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + ] + + args.output_dir.mkdir(parents=True, exist_ok=True) + comparison_rows = [evaluation["summary"] for evaluation in evaluations] + write_csv_rows(args.output_dir / "comparison.csv", comparison_rows) + write_csv_rows(args.output_dir / "paired_take_bootstrap.csv", paired_rows) + if refinement_rows: + write_csv_rows( + args.output_dir / "pad_hand_vs_wilor_paired_take_bootstrap.csv", + refinement_rows, + ) + if dynhamr_hawor_rows: + write_csv_rows( + args.output_dir / "dynhamr_vs_hawor_paired_take_bootstrap.csv", + dynhamr_hawor_rows, + ) + manifest = args.manifest.resolve() + ground_truth = args.ground_truth.resolve() + speed_report_path = args.output_dir / "speed_report.json" + speed_report = ( + json.loads(speed_report_path.read_text(encoding="utf-8")) + if speed_report_path.is_file() + else None + ) + payload = { + "status": "complete", + "official_test_used": False, + "split_role": "official_validation", + "manifest": str(manifest), + "manifest_sha256": sha256(manifest), + "ground_truth": str(ground_truth), + "ground_truth_sha256": sha256(ground_truth), + "bootstrap_seed": args.bootstrap_seed, + "bootstrap_samples": args.bootstrap_samples, + "comparison": comparison_rows, + "paired_take_bootstrap": paired_rows, + "pad_hand_vs_wilor_paired_take_bootstrap": refinement_rows, + "dynhamr_vs_hawor_paired_take_bootstrap": dynhamr_hawor_rows, + "paper_reported_context": { + "QORT-Former": "H2O test MEE left/right 20.1/19.9 mm", + "WiLoR": "FreiHAND PA-MPJPE/PA-MPVPE 5.5/5.1 mm; HO3D 7.5/7.7 mm", + "HaWoR": "DexYCB PA-MPJPE 4.76 mm, AUC 90.5", + "WildHands": "H2O validation zero-shot MPJPE/MRRPE 31.08/49.49 mm", + "Hamba": "FreiHAND no-TTA PA-MPJPE/PA-MPVPE 5.8/5.5 mm", + "PAD-Hand": ( + "DexYCB WiLoR->PAD-Hand PA-MPJPE 4.88->4.63 mm, " + "MPJPE 12.75->10.56 mm, ACCEL 6.70->3.34" + ), + "HandDGP": "FreiHAND camera-space MJE/MVE 46.3/46.3 mm", + "Dyn-HaMR": "global 4D hand-motion reconstruction on dynamic-camera videos", + }, + } + if speed_report is not None: + payload["speed_benchmark"] = { + "path": str(speed_report_path.resolve()), + "sha256": sha256(speed_report_path), + "status": speed_report.get("status"), + } + (args.output_dir / "report.json").write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + report_text = markdown_report( + evaluations, + paired_rows, + refinement_rows, + dynhamr_hawor_rows, + speed_report, + manifest=manifest, + manifest_hash=payload["manifest_sha256"], + ground_truth=ground_truth, + ground_truth_hash=payload["ground_truth_sha256"], + bootstrap_seed=args.bootstrap_seed, + bootstrap_samples=args.bootstrap_samples, + ) + (args.output_dir / "SOTA_EVALUATION_REPORT.md").write_text( + report_text, encoding="utf-8" + ) + print(json.dumps({ + "models": [evaluation["label"] for evaluation in evaluations], + "output_dir": str(args.output_dir.resolve()), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/summarize_sota_speed.py b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_sota_speed.py new file mode 100644 index 0000000000000000000000000000000000000000..11ebd0914d721320b8787f1e806411a282dab0cc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/summarize_sota_speed.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Summarize synchronized external-baseline speed measurements.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +SETTINGS = { + "FoundationHand-T8": ("FoundationHand", "temporal_clip", "RGB+Depth+K, T=8, clip batch=1"), + "QORT-b1": ("QORT-Former", "framewise", "batch=1"), + "QORT-b16": ("QORT-Former", "batched", "batch=16"), + "WiLoR-b1": ("WiLoR", "framewise", "detector/reconstruction batch=1"), + "WiLoR-b16": ("WiLoR", "batched", "detector/reconstruction batch=16"), + "HaWoR-T16": ("HaWoR", "offline_temporal", "tracked temporal window=16"), + "Dyn-HaMR-TTO": ("Dyn-HaMR", "test_time_optimization", "one 94-frame run"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--timing", action="append", required=True, help="SETTING=timing.json") + parser.add_argument("--foundation-profile", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + + grouped: dict[str, list[tuple[Path, dict[str, Any]]]] = {} + for spec in args.timing: + label, separator, raw_path = spec.partition("=") + if not separator or label not in SETTINGS or not raw_path: + raise ValueError(f"Invalid timing specification: {spec}") + path = Path(raw_path).resolve() + payload = json.loads(path.read_text(encoding="utf-8")) + if payload.get("schema_version") != "foundation_hand_external_speed_v1": + raise ValueError(f"Unexpected timing schema: {path}") + if int(payload.get("frames", 0)) != 94: + raise ValueError(f"Benchmark must contain exactly 94 frames: {path}") + grouped.setdefault(label, []).append((path, payload)) + + missing = set(SETTINGS) - set(grouped) + if missing: + raise ValueError(f"Missing benchmark settings: {sorted(missing)}") + + rows: list[dict[str, Any]] = [] + raw_measurements: dict[str, list[dict[str, Any]]] = {} + for label, (model, mode, setting) in SETTINGS.items(): + measurements = grouped[label] + fps = np.asarray([item[1]["frames_per_second"] for item in measurements]) + seconds = np.asarray([item[1]["processing_seconds"] for item in measurements]) + row = { + "setting_id": label, + "model": model, + "mode": mode, + "setting": setting, + "repeats": len(measurements), + "frames_per_repeat": 94, + "median_processing_seconds": float(np.median(seconds)), + "median_fps": float(np.median(fps)), + "min_fps": float(fps.min()), + "max_fps": float(fps.max()), + "amortized_ms_per_frame": float(1000.0 / np.median(fps)), + } + rows.append(row) + raw_measurements[label] = [ + { + "path": str(path), + "sha256": sha256(path), + **payload, + } + for path, payload in measurements + ] + + by_label = {row["setting_id"]: row for row in rows} + dyn = raw_measurements["Dyn-HaMR-TTO"][0] + foundation_profile_path = args.foundation_profile.resolve() + foundation_profile = json.loads( + foundation_profile_path.read_text(encoding="utf-8") + ) + foundation_forward_ms = float(foundation_profile["latency"]["p50_ms"]) + foundation_model_fps = 8_000.0 / foundation_forward_ms + dyn_initializer_fps = dyn["frames"] / dyn["initialization_seconds"] + dyn_optimizer_fraction = dyn["optimization_seconds"] / dyn["processing_seconds"] + throughput_order = [ + "FoundationHand-T8", "QORT-b16", "WiLoR-b16", "HaWoR-T16", "Dyn-HaMR-TTO" + ] + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "speed_comparison.csv", rows) + report_payload = { + "status": "complete", + "schema_version": "foundation_hand_external_speed_report_v1", + "date": "2026-07-21", + "hardware": "NVIDIA GeForce RTX 4090", + "physical_gpu_policy": ( + "QORT/WiLoR/HaWoR repeats used idle physical GPU0; " + "Dyn-HaMR used idle physical GPU1; all GPUs are identical RTX 4090 cards" + ), + "workload": "first official H2O validation contiguous run (94 RGB frames)", + "timed_scope": ( + "RGB decode/preprocessing through final camera-space conversion; " + "model loading and prediction serialization excluded" + ), + "cuda_synchronized": True, + "rows": rows, + "raw_measurements": raw_measurements, + "foundation_model_only_profile": { + "path": str(foundation_profile_path), + "sha256": sha256(foundation_profile_path), + "p50_ms_per_t8_clip": foundation_forward_ms, + "amortized_frames_per_second": foundation_model_fps, + "scope": foundation_profile["latency"]["scope"], + }, + "dynhamr_diagnostics": { + "initializer_fps": dyn_initializer_fps, + "initializer_seconds": dyn["initialization_seconds"], + "optimization_seconds": dyn["optimization_seconds"], + "optimizer_fraction": dyn_optimizer_fraction, + "root_iterations": dyn["root_iterations"], + "smooth_iterations": dyn["smooth_iterations"], + }, + } + (args.output_dir / "speed_report.json").write_text( + json.dumps(report_payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + lines = [ + "# FoundationHand 外部方法推理速度复评", + "", + "## 结论", + "", + ( + f"在相同 94 帧 H2O RGB 连续片段和 RTX 4090 上,批处理吞吐排序为 " + f"**FoundationHand ({by_label['FoundationHand-T8']['median_fps']:.2f} FPS) > " + f"QORT-Former ({by_label['QORT-b16']['median_fps']:.2f} FPS) > " + f"WiLoR ({by_label['WiLoR-b16']['median_fps']:.2f} FPS) > " + f"HaWoR ({by_label['HaWoR-T16']['median_fps']:.2f} FPS) > " + f"Dyn-HaMR ({by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS)**。" + ), + "", + ( + "QORT/WiLoR 是逐帧前向方法;FoundationHand 使用 T=8 RGB+Depth+K clip;" + "HaWoR 必须看到时序窗口/连续 track;" + "Dyn-HaMR 对整段测试视频优化。因此 FPS 可比较系统计算成本,但 HaWoR/Dyn-HaMR 的" + "摊销 ms/frame 不是因果单帧响应延迟。" + ), + "", + "## 端到端摊销吞吐", + "", + "计时包含 RGB 解码、官方预处理、需要的 detector、重建和 camera-space 转换;不包含权重加载与 NPZ 写盘。", + "", + "| 方法 | 模式 | 设置 | 重复 | Median FPS | 范围 | 摊销 ms/frame |", + "|---|---|---|---:|---:|---:|---:|", + ] + for label in throughput_order: + row = by_label[label] + lines.append( + f"| {row['model']} | {row['mode']} | {row['setting']} | {row['repeats']} | " + f"{row['median_fps']:.3f} | {row['min_fps']:.3f}-{row['max_fps']:.3f} | " + f"{row['amortized_ms_per_frame']:.2f} |" + ) + lines.extend([ + "", + "## Batch-1 在线前向", + "", + "| 方法 | Median FPS | 范围 | ms/frame |", + "|---|---:|---:|---:|", + ]) + for label in ("QORT-b1", "WiLoR-b1"): + row = by_label[label] + lines.append( + f"| {row['model']} | {row['median_fps']:.3f} | " + f"{row['min_fps']:.3f}-{row['max_fps']:.3f} | " + f"{row['amortized_ms_per_frame']:.2f} |" + ) + lines.extend([ + "", + "HaWoR 和 Dyn-HaMR 不列入 batch-1 在线表:前者是非因果 tracked temporal inference,后者是整段 TTO。", + "", + "## FoundationHand 开销拆分", + "", + ( + f"FoundationHand 完整 RGB+Depth+K 数据路径的中位吞吐为 " + f"{by_label['FoundationHand-T8']['median_fps']:.2f} FPS(" + f"{by_label['FoundationHand-T8']['amortized_ms_per_frame']:.2f} ms/frame 摊销)。" + f"独立的 100 次 GPU forward 计时 P50 为 {foundation_forward_ms:.2f} ms/T=8 clip," + f"等价于 {foundation_model_fps:.1f} frame/s 的纯模型吞吐;两者差额主要来自 RGB/Depth 解码、" + "640x368 预处理、worker 启动和 host-device/host result transfer。" + ), + "", + ( + "FoundationHand 的 T=8 需要先获得一个 8 帧窗口,因此上述 14.2 ms/frame 是系统吞吐," + "不是零缓冲的单帧响应延迟。" + ), + "", + "## Dyn-HaMR 开销拆分", + "", + ( + f"Dyn-HaMR 的 detector+HaMeR 初始化耗时 {dyn['initialization_seconds']:.2f} s," + f"相当于 {dyn_initializer_fps:.2f} FPS;32 次 Root + 300 次 Smooth TTO 耗时 " + f"{dyn['optimization_seconds']:.2f} s,占完整推理时间 {100 * dyn_optimizer_fraction:.2f}%。" + f"完整 94 帧用时 {dyn['processing_seconds']:.2f} s,即 " + f"{by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS。" + ), + "", + "## 公平性边界", + "", + "- FoundationHand/QORT/WiLoR/HaWoR 各重复 3 次并报告中位数和范围;Dyn-HaMR 因完整 TTO 昂贵,报告一次无缓存的完整官方优化。", + "- QORT/WiLoR 的 batch=16 数字是吞吐,不是单请求延迟。", + "- HaWoR 速度只覆盖本 SOTA 报告使用的 camera-space hand stage,不包含 DROID-SLAM、Metric3D 或 world-space infiller。", + "- FoundationHand 使用 RGB+metric Depth+K 且不需要 detector;外部方法为 RGB,因此这是已部署系统吞吐比较,不是输入模态等价的 backbone benchmark。", + "- Dyn-HaMR 使用已知静态 H2O K,因此不包含 VIPE/DROID-SLAM;包含与量化结果完全相同的 Root/Smooth TTO。", + "- FoundationHand/QORT/WiLoR/HaWoR 重复测量使用空闲物理 GPU0;Dyn-HaMR 使用空闲物理 GPU1。六张卡均为 RTX 4090。", + "- 这些是本机 release-code 系统测速,不应与论文在其他 GPU、分辨率或只计 model-forward 的 FPS 直接混排。", + "", + "## 可复现产物", + "", + "- `speed_comparison.csv`: 汇总速度表。", + "- `speed_report.json`: 原始 timing 路径、SHA256、计时范围与 Dyn-HaMR 分段耗时。", + "- 原始同步 timing JSON 位于 `artifacts/sota/speed_benchmark_20260721/`。", + "", + ]) + (args.output_dir / "INFERENCE_SPEED_REPORT.md").write_text( + "\n".join(lines), encoding="utf-8" + ) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_last2_candidate_admission.py b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_last2_candidate_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..ab89a845500fc88174c957806b8b2318ca3e8e0a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_last2_candidate_admission.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Forward-sync one frozen last-2 admission to its remote owner controller.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def upstream_files(plan: dict[str, Any]) -> list[Path]: + state_path = Path(plan["admission_controller_state"]) + report_path = Path(plan["admission_decision_report"]) + if not state_path.is_file() or not report_path.is_file(): + raise NotReady("last-2 upstream decision is not complete") + state = read_json(state_path) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != plan["admission_controller_plan_sha256"] + or state.get("decision_report", {}).get("path") != str(report_path.resolve()) + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or state.get("official_test_used") is not False + ): + raise NotReady("last-2 upstream decision is not complete") + files = [report_path, state_path] + stage8_state = Path(plan["stage8_controller_state"]) + if stage8_state not in files: + stage8 = read_json(stage8_state) + stage8_report = Path(stage8["decision_report"]["path"]) + files.extend((stage8_report, stage8_state)) + return files + + +def admission_payload(plan: dict[str, Any]) -> tuple[str, list[Path], list[dict[str, str]]]: + files = upstream_files(plan) + central_path = Path(plan["controller_states"]["taku3"]) + if not central_path.is_file(): + raise NotReady("central last-2 candidate has not consumed admission") + central = read_json(central_path) + decision_path = Path(plan["decision_report"]) + if central.get("status") == "complete" and central.get("admitted") is False: + if not decision_path.is_file() or central.get("decision_report", {}).get("sha256") != sha256(decision_path): + raise ValueError("central last-2 rejection binding differs") + return "rejected", files + [decision_path, central_path], [] + registry_path = Path(plan["training_registry"]) + if not registry_path.is_file() or not central.get("training_registry_sha256"): + raise NotReady("central last-2 training registry is not frozen") + if ( + central.get("plan_sha256") != sha256(Path(central["plan"])) + or central.get("training_registry") != str(registry_path.resolve()) + or central.get("training_registry_sha256") != sha256(registry_path) + or central.get("official_test_used") is not False + ): + raise ValueError("central last-2 controller binding differs") + registry = read_json(registry_path) + owners = condition_owners(registry, load_assignment(plan)) + conditions = registry.get("conditions", []) + if ( + registry.get("status") != "frozen_ready" + or registry.get("candidate") != plan["candidate"] + or len(conditions) != 7 + or sum(owner == "server_new" for owner in owners.values()) != 3 + or registry.get("official_test_used") is not False + ): + raise ValueError("last-2 registry contract differs") + files.extend((Path(plan["training_registry_state"]), + *[Path(item["config"]) for item in conditions], registry_path)) + prerequisites, seen = [], set() + for item in conditions: + pair = (item["initialization_checkpoint"], item["initialization_checkpoint_sha256"]) + if pair not in seen: prerequisites.append({"path": pair[0], "sha256": pair[1]}); seen.add(pair) + for item in registry["data_artifacts"]: + pair = (item["path"], item["sha256"]) + if pair not in seen: prerequisites.append({"path": pair[0], "sha256": pair[1]}); seen.add(pair) + return "admitted", files, prerequisites + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = Path(state).parent.parent / "server_new.log" + command = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_last2_candidate_controller --plan " + str(plan_path.resolve()) + + " --state " + state + " --machine server_new --poll-seconds 30 >> " + + str(log) + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: raise RuntimeError("remote last-2 controller launch failed") + time.sleep(2) + probe = subprocess.run([ + "ssh", "server_new", "pgrep", "-fo", + f"scripts.run_phase9_last2_candidate_controller.*last2_v3/{plan['candidate']}.*server_new.json", + ], stdout=subprocess.PIPE, text=True, check=False) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote last-2 controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + admission, files, prerequisites = admission_payload(plan) + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"central last-2 prerequisite differs: {path}") + if remote_sha256("server_new", path) != item["sha256"]: + raise ValueError(f"remote last-2 prerequisite differs: {path}") + registry = Path(plan["training_registry"]) + ordered = [path for path in files if path != registry] + ([registry] if registry in files else []) + installed = [install_file("server_new", path) for path in ordered] + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_last2_candidate_admission_sync_v1", + "status": "complete", "candidate": plan["candidate"], "admission": admission, + "completed_utc": utc_now(), "plan_sha256": sha256(plan_path), + "installed": installed, "immutable_prerequisites": prerequisites, + "registry_installed_last": registry in files, "remote_controller_pid": pid, + "official_test_used": False, "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_last2_candidate_admission_sync_v1", + "status": "waiting_for_candidate_admission", "candidate": plan["candidate"], + "watcher_pid": os.getpid(), "updated_utc": utc_now(), "detail": str(error), + "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_last2_training_completion.py b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_last2_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..6c9fa4facf8e3fbbde000e22bcab8de5e9a983fc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_last2_training_completion.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Completion-only remote training handoff for an admitted last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_resolution_training_completion import active_writer_pids +from scripts.sync_phase9_shared_augmentation_training_completion import ( + file_record, install, json_sha256, validate_terminal, +) + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(path: Path, plan: dict[str, Any]) -> None: + conditions = plan.get("conditions", []) + if ( + plan.get("schema_version") != "phase9_last2_training_completion_plan_v1" + or plan.get("status") != "frozen" + or plan.get("candidate") not in {"5e7", "1e6"} + or len(conditions) != 3 or len(set(conditions)) != 3 + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("target_step") != 405000 + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + ): + raise ValueError("last-2 training completion plan differs") + for binding in plan["bindings"]: + candidate = Path(binding["path"]) + if not candidate.is_file() or sha256(candidate) != binding["sha256"]: + raise ValueError(f"last-2 completion binding differs: {candidate}") + if not path.is_file(): raise ValueError("last-2 completion plan is unreadable") + + +def registry_jobs(plan: dict[str, Any]) -> tuple[Path, dict[str, Any], dict[str, Any]]: + path = Path(plan["training_registry"]["path"]) + if not path.is_file() or sha256(path) != plan["training_registry"]["sha256"]: + raise ValueError("last-2 training registry hash differs") + registry = read_json(path); jobs = {item["condition"]: item for item in registry["conditions"]} + owners = condition_owners(registry, load_assignment(plan)) + remote = [condition for condition in jobs if owners[condition] == "server_new"] + if ( + registry.get("status") != "frozen_ready" + or registry.get("candidate") != plan["candidate"] + or remote != plan["conditions"] + or registry.get("target_step") != 405000 + or registry.get("official_test_used") is not False + ): + raise ValueError("last-2 training registry contract differs") + return path, registry, jobs + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + registry_path, _, jobs = registry_jobs(plan) + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): raise NotReady("remote last-2 controller is missing") + controller = read_json(controller_path) + statuses = controller.get("training_statuses", {}) + if any(statuses.get(condition) != "complete" for condition in plan["conditions"]): + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("remote last-2 controller failed") + raise NotReady("remote last-2 training is still running") + if ( + controller.get("plan_sha256") != plan["controller_plan"]["sha256"] + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("official_test_used") is not False + ): + raise ValueError("remote last-2 controller binding differs") + root, state_root = Path(plan["release_root"]), Path(plan["training_state_root"]) + records, files = [], [] + for condition in plan["conditions"]: + job = jobs[condition]; state_path = state_root / f"{condition.lower()}.json" + state = read_json(state_path) + if state.get("queue_sha256") != sha256(registry_path): + raise ValueError(f"last-2 state registry binding differs: {condition}") + if active_writer_pids(job["output_dir"]): raise NotReady(f"last-2 writer exists: {condition}") + checkpoint, evidence = validate_terminal(job, state) + pair = [file_record(root, "checkpoint", checkpoint), + file_record(root, "training_state", state_path)] + files.extend(pair); records.append({ + "condition": condition, "role": job["role"], + "checkpoint_sha256": sha256(checkpoint), + "final_total_loss": float(evidence["metric"]["losses"]["total"]), + "metrics_sha256": evidence["metrics_sha256"], + "summary_sha256": evidence["summary_sha256"], "files": pair, + }) + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): return read_json(output) + records, files = source_records(plan) + value = { + "schema_version": "phase9_last2_training_completion_release_v1", + "status": "complete_immutable_release", "candidate": plan["candidate"], + "created_utc": utc_now(), "plan_sha256": sha256(plan_path), + "training_registry": plan["training_registry"], "release_root": plan["release_root"], + "conditions": records, "files": files, "file_count": 6, + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, "live_reverse_sync_performed": False, + "results_before_terminal_states": True, "official_test_used": False, + } + atomic_json(output, value); os.chmod(output, 0o444) + for item in files: os.chmod(item["absolute_path"], 0o444) + return value + + +def fetch(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run(["ssh", "server_new", "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, check=False) + if result.returncode: raise NotReady("remote last-2 release is unavailable") + return json.loads(result.stdout) + + +def validate_release(plan_path: Path, plan: dict[str, Any], value: dict[str, Any]) -> None: + files = value.get("files", []) + if ( + value.get("schema_version") != "phase9_last2_training_completion_release_v1" + or value.get("status") != "complete_immutable_release" + or value.get("candidate") != plan["candidate"] + or value.get("plan_sha256") != sha256(plan_path) + or value.get("training_registry") != plan["training_registry"] + or [item.get("condition") for item in value.get("conditions", [])] != plan["conditions"] + or len(files) != 6 or len({item.get("path") for item in files}) != 6 + or value.get("results_before_terminal_states") is not True + or value.get("official_test_used") is not False + ): + raise ValueError("last-2 immutable release differs") + + +def central_ready(plan: dict[str, Any]) -> bool: + path = Path(plan["training_completion_state"]) + if not path.is_file(): return False + value = read_json(path) + return (value.get("status") == "complete" and value.get("candidate") == plan["candidate"] + and value.get("training_registry_sha256") == plan["training_registry"]["sha256"] + and value.get("official_test_used") is False) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): return read_json(output) + release = fetch(plan); validate_release(plan_path, plan, release) + installed = install(plan, release) + deadline = time.monotonic() + 120 + while time.monotonic() < deadline and not central_ready(plan): time.sleep(2) + if not central_ready(plan): raise TimeoutError("central last-2 training did not converge") + value = { + "schema_version": "phase9_last2_training_completion_receive_v1", + "status": "complete", "candidate": plan["candidate"], "completed_utc": utc_now(), + "plan_sha256": sha256(plan_path), "release_sha256": json_sha256(release), + "installed": installed, "file_count": 6, "total_bytes": release["total_bytes"], + "results_before_terminal_states": True, "official_test_used": False, + } + atomic_json(output, value); return value + + +def main() -> None: + parser = argparse.ArgumentParser(); parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + try: validate_plan(args.plan, plan) + except ValueError as error: parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True); deadline = time.monotonic() + args.wait_timeout_seconds + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + value = publish(args.plan, plan) if args.role == "publish" else receive(args.plan, plan) + print(json.dumps(value, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(Path(f"{target}.watcher.json"), { + "schema_version": "phase9_last2_training_completion_watcher_v1", + "status": "waiting_for_terminal_source", "candidate": plan["candidate"], + "role": args.role, "watcher_pid": os.getpid(), "updated_utc": utc_now(), + "detail": str(error), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_resolution_evaluation_completion.py b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_resolution_evaluation_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..7213c888087d9e7daec2af464ac979afd0e504fa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_resolution_evaluation_completion.py @@ -0,0 +1,450 @@ +#!/usr/bin/env python3 +"""Publish and import terminal server_new Stage 7 evaluation evidence.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +class NotReady(RuntimeError): + """A healthy source dependency has not reached its terminal state.""" + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: dict[str, Any]) -> str: + payload = (json.dumps(value, indent=2) + "\n").encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + if ( + plan.get("schema_version") + != "phase9_resolution_evaluation_completion_release_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or scientific.get("amendment_scope") + != "terminal_evaluation_state_and_result_handoff_only" + or any( + scientific.get(key) is not False + for key in ( + "model_changed", "data_changed", "seed_changed", + "metric_changed", "selection_gate_changed", + ) + ) + ): + raise ValueError("resolution evaluation completion plan contract differs") + for key in ( + "release_root", "staging_root", "release_state", "receive_state", + ): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution evaluation completion {key} is not /SSD2") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution evaluation completion binding differs: {path}") + if not plan_path.is_file(): + raise ValueError("resolution evaluation completion plan is unreadable") + + +def remote_inventory(plan: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]: + path = Path(plan["evaluation_plan"]["path"]) + if not path.is_file() or sha256(path) != plan["evaluation_plan"]["sha256"]: + raise ValueError("resolution evaluation plan hash differs") + dynamic = read_json(path) + workers = [item for item in dynamic["workers"] if item["owner"] == "server_new"] + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + assigned = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(dynamic["evaluations"]) != 25 + or len(dynamic["workers"]) != 10 + or len(workers) != 4 + or len(assigned) != 9 + or len(set(assigned)) != 9 + or any(evaluations[identifier]["training_role"] not in { + "loso_subject2", "loso_subject3", "lofamily_k", + } for identifier in assigned) + or dynamic.get("official_test_used") is not False + or dynamic.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new resolution evaluation ownership differs") + return dynamic, workers + + +def active_evaluator_pids(evaluation_id: str, proc_root: Path = Path("/proc")) -> list[int]: + result = [] + token = f"--evaluation-id {evaluation_id}" + for entry in proc_root.iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (FileNotFoundError, PermissionError, ProcessLookupError, UnicodeDecodeError): + continue + if "scripts.evaluate_phase7_external" in command and token in command: + result.append(int(entry.name)) + return sorted(result) + + +def release_file(root: Path, kind: str, path: Path) -> dict[str, Any]: + if not path.is_file() or path.is_symlink() or root not in path.resolve().parents: + raise ValueError(f"resolution evaluation release artifact differs: {path}") + return { + "kind": kind, + "path": str(path.resolve().relative_to(root.resolve())), + "absolute_path": str(path.resolve()), + "bytes": path.stat().st_size, + "sha256": sha256(path), + } + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + dynamic, workers = remote_inventory(plan) + dynamic_hash = plan["evaluation_plan"]["sha256"] + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): + raise NotReady("server_new evaluation controller state is missing") + controller = read_json(controller_path) + if controller.get("status") not in {"complete_local", "complete"}: + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("server_new evaluation controller failed") + raise NotReady("server_new evaluation controller is still running") + if ( + controller.get("machine") != "server_new" + or controller.get("evaluation_plan_sha256") != dynamic_hash + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new evaluation controller binding differs") + + root = Path(plan["release_root"]) + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + records = [] + files = [] + for worker in workers: + state_path = Path(worker["state"]) + if not state_path.is_file(): + raise NotReady(f"server_new evaluation worker is missing: {worker['id']}") + state = read_json(state_path) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed_terminal"): + raise ValueError(f"server_new evaluation worker failed: {worker['id']}") + raise NotReady(f"server_new evaluation worker is still running: {worker['id']}") + if ( + state.get("worker") != worker["id"] + or state.get("owner") != "server_new" + or state.get("plan_sha256") != dynamic_hash + or state.get("assigned_evaluation_ids") != worker["evaluation_ids"] + or state.get("completed_ids") != worker["evaluation_ids"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"server_new evaluation worker binding differs: {worker['id']}") + files.append(release_file(root, "worker_state", state_path)) + for identifier in worker["evaluation_ids"]: + if active_evaluator_pids(identifier): + raise NotReady(f"server_new evaluator still exists: {identifier}") + item = evaluations[identifier] + if not evaluation_complete(item): + raise ValueError(f"server_new evaluation result differs: {identifier}") + report_path = Path(item["output_dir"]) / "evaluation.json" + report = read_json(report_path) + result_files = [release_file(root, "evaluation_report", report_path)] + for key in ("raw_predictions", "per_hand_rows", "take_metrics"): + artifact = report[key] + path = Path(artifact["path"]) + record = release_file(root, key, path) + if record["sha256"] != artifact["sha256"]: + raise ValueError(f"server_new result artifact hash differs: {identifier}") + result_files.append(record) + files.extend(result_files) + records.append({ + "evaluation_id": identifier, + "worker": worker["id"], + "checkpoint_sha256": item["checkpoint_sha256"], + "config_sha256": item["config_sha256"], + "cache_manifest_sha256": item["cache_manifest_sha256"], + "clips": report["clips"], "frames": report["frames"], + "wall_seconds": report["runtime"]["wall_seconds"], + "gpu_hours": report["runtime"]["wall_seconds"] / 3600.0, + "evaluation_report_sha256": sha256(report_path), + "files": result_files, + }) + files.append(release_file(root, "controller_state", controller_path)) + paths = [item["path"] for item in files] + if len(records) != 9 or len(files) != 41 or len(paths) != len(set(paths)): + raise ValueError("server_new evaluation release inventory differs") + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + existing = read_json(output) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution evaluation release differs") + records, files = source_records(plan) + result = { + "schema_version": "phase9_resolution_evaluation_completion_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "destination_owner": "taku3", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_root": str(Path(plan["release_root"]).resolve()), + "evaluation_plan": plan["evaluation_plan"], + "evaluations": records, "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "results_before_terminal_states": True, + "single_writer_per_output": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, result) + os.chmod(output, 0o444) + for item in files: + os.chmod(item["absolute_path"], 0o444) + return result + + +def fetch_release(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", plan["source_host"], + "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + timeout=float(plan["ssh_timeout_seconds"]), + ) + if result.returncode: + raise NotReady("server_new evaluation completion release is unavailable") + try: + value = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise ValueError("server_new evaluation completion release is unreadable") from error + return value + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + files = release.get("files", []) + paths = [item.get("path") for item in files] + _, workers = remote_inventory(plan) + expected_ids = { + identifier for worker in workers for identifier in worker["evaluation_ids"] + } + records = release.get("evaluations", []) + record_ids = [item.get("evaluation_id") for item in records] + kind_counts = Counter(item.get("kind") for item in files) + if ( + release.get("schema_version") + != "phase9_resolution_evaluation_completion_release_v1" + or release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("destination_owner") != "taku3" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("evaluation_plan") != plan["evaluation_plan"] + or len(records) != 9 + or len(record_ids) != len(set(record_ids)) + or set(record_ids) != expected_ids + or len(files) != 41 or len(paths) != len(set(paths)) + or kind_counts != { + "evaluation_report": 9, "raw_predictions": 9, + "per_hand_rows": 9, "take_metrics": 9, + "worker_state": 4, "controller_state": 1, + } + or release.get("file_count") != 41 + or sum(item.get("bytes", -1) for item in files) != release.get("total_bytes") + or release.get("completion_only_reverse_release") is not True + or release.get("live_reverse_sync_performed") is not False + or release.get("results_before_terminal_states") is not True + or release.get("single_writer_per_output") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution evaluation immutable release differs") + for value in paths: + path = Path(str(value)) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"unsafe resolution evaluation release path: {path}") + file_hashes = {(item["path"], item["sha256"]) for item in files} + for record in records: + result_files = record.get("files", []) + if ( + len(result_files) != 4 + or record.get("evaluation_report_sha256") + != next( + (item["sha256"] for item in result_files + if item.get("kind") == "evaluation_report"), None, + ) + or any((item.get("path"), item.get("sha256")) not in file_hashes + for item in result_files) + ): + raise ValueError("resolution evaluation release result binding differs") + + +def verify_file(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"resolution evaluation completion file differs: {path}") + return path + + +def install_release(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root = Path(plan["release_root"]) + staging = Path(plan["staging_root"]) + pending = [] + installed = [] + for item in release["files"]: + destination = root / item["path"] + if destination.exists(): + verify_file(root, item) + installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".pending_evaluation_release_files.txt" + file_list.write_text( + "".join(item["path"] + "\n" for item in pending), encoding="utf-8", + ) + result = subprocess.run([ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['source_host']}:{root.resolve()}/", f"{staging.resolve()}/", + ], check=False) + if result.returncode: + raise RuntimeError(f"resolution evaluation rsync failed: {result.returncode}") + for item in pending: + verify_file(staging, item) + order = {"evaluation_report": 0, "raw_predictions": 0, "per_hand_rows": 0, + "take_metrics": 0, "controller_state": 1, "worker_state": 2} + for item in sorted(pending, key=lambda value: (order[value["kind"]], value["path"])): + source = staging / item["path"] + destination = root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + raise ValueError(f"resolution evaluation destination appeared: {destination}") + os.replace(source, destination) + os.chmod(destination, 0o444) + verify_file(root, item) + installed.append({**item, "resumed_existing": False}) + return sorted(installed, key=lambda item: item["path"]) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): + existing = read_json(output) + if existing.get("status") == "complete" and existing.get("plan_sha256") == sha256(plan_path): + return existing + raise ValueError("existing resolution evaluation receive state differs") + release = fetch_release(plan) + validate_release(plan_path, plan, release) + installed = install_release(plan, release) + result = { + "schema_version": "phase9_resolution_evaluation_completion_receive_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state": plan["release_state"], + "release_sha256": json_sha256(release), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "installed": installed, + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "results_before_terminal_states": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, result) + return result + + +def wait_for_result( + role: str, plan_path: Path, plan: dict[str, Any], timeout_seconds: float, +) -> dict[str, Any]: + deadline = time.monotonic() + timeout_seconds + watcher_path = Path( + f"{plan['release_state' if role == 'publish' else 'receive_state']}.watcher.json" + ) + while True: + try: + return publish(plan_path, plan) if role == "publish" else receive(plan_path, plan) + except NotReady as error: + if timeout_seconds <= 0 or time.monotonic() >= deadline: + raise + atomic_json(watcher_path, { + "schema_version": "phase9_resolution_evaluation_completion_watcher_v1", + "status": "waiting_for_terminal_source", "role": role, + "watcher_pid": os.getpid(), "updated_utc": utc_now(), + "detail": str(error), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "h2o_official_validation_used": False, "official_test_used": False, + }) + time.sleep(min(30.0, max(1.0, deadline - time.monotonic()))) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = wait_for_result( + args.role, args.plan, plan, args.wait_timeout_seconds, + ) + except Exception as error: + atomic_json(Path(f"{target}.failure.json"), { + "schema_version": "phase9_resolution_evaluation_completion_failure_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "role": args.role, "failure": f"{type(error).__name__}: {error}", + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, "official_test_used": False, + }) + raise + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_resolution_training_completion.py b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_resolution_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..34c74406bf5162cc0d980d780e5ef77133e4776c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_resolution_training_completion.py @@ -0,0 +1,569 @@ +#!/usr/bin/env python3 +"""Publish and import terminal server_new Stage 7 training evidence.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any +import zipfile + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +EXPECTED_CONDITIONS = ( + "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", + "S7R_J25_lofamily_k", +) +EXPECTED_STAGES = ("smoke2", "health2k", "matched_405000") + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + if ( + plan.get("schema_version") + != "phase9_resolution_training_completion_release_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("read_only_after_publish") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or scientific.get("amendment_scope") + != "terminal_state_and_final_checkpoint_handoff_only" + or any( + scientific.get(key) is not False + for key in ( + "model_changed", "data_changed", "seed_changed", + "optimizer_changed", "horizon_changed", + "selection_gate_changed", + ) + ) + ): + raise ValueError("resolution training completion plan contract differs") + if tuple(item["condition"] for item in plan.get("conditions", [])) != EXPECTED_CONDITIONS: + raise ValueError("resolution training completion conditions differ") + for key in ("release_root", "staging_root"): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution training completion {key} is not /SSD2") + if Path(plan["release_state"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution training completion release state is not /SSD2") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution completion binding differs: {path}") + if sha256(plan_path) == "": + raise ValueError("resolution completion plan is unreadable") + + +def last_json_record(path: Path, tail_bytes: int = 1 << 20) -> dict[str, Any]: + with path.open("rb") as handle: + handle.seek(0, os.SEEK_END) + size = handle.tell() + handle.seek(max(0, size - tail_bytes)) + lines = handle.read().splitlines() + for line in reversed(lines): + if line.strip(): + value = json.loads(line) + if not isinstance(value, dict): + break + return value + raise ValueError(f"terminal metric record is unavailable: {path}") + + +def validate_condition_payload( + expected: dict[str, Any], job: dict[str, Any], state: dict[str, Any], + metric: dict[str, Any], summary: dict[str, Any], +) -> None: + marker = state.get("last_completed", {}) + attempts = state.get("attempts", []) + losses = metric.get("losses", {}) + if ( + state.get("status") != "complete" + or state.get("condition") != expected["condition"] + or state.get("queue_sha256") != expected["training_registry_sha256"] + or state.get("official_test_used") is not False + or tuple(state.get("completed_stages", [])) != EXPECTED_STAGES + or tuple(item.get("stage") for item in attempts) != EXPECTED_STAGES + or any(item.get("returncode") != 0 for item in attempts) + or marker.get("status") != "complete" + or marker.get("stage") != "matched_405000" + or marker.get("completed_step") != 405000 + or marker.get("checkpoint") != expected["checkpoint"] + or marker.get("checkpoint_sha256") != expected["checkpoint_sha256"] + or marker.get("config") != job["config"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or metric.get("step") != 405000 + or not isinstance(losses, dict) + or not losses + or any( + not isinstance(value, (int, float)) or not math.isfinite(float(value)) + for value in losses.values() + ) + or summary.get("status") != "completed" + or summary.get("completed_step") != 405000 + or summary.get("protocol_max_steps") != 405000 + or summary.get("registered_run_end_step") != 405000 + or summary.get("final_checkpoint") != expected["checkpoint"] + or summary.get("final_checkpoint_sha256") != expected["checkpoint_sha256"] + or summary.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or summary.get("official_test_used") is not False + ): + raise ValueError( + f"resolution terminal training evidence differs: {expected['condition']}" + ) + + +def writer_matches(command: str, output_dir: str) -> bool: + return ( + "scripts.train_phase7_external" in command + and f"--output-dir {output_dir}" in command + ) + + +def active_writer_pids(output_dir: str, proc_root: Path = Path("/proc")) -> list[int]: + result = [] + for entry in proc_root.iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (FileNotFoundError, PermissionError, UnicodeDecodeError, ProcessLookupError): + continue + if writer_matches(command, output_dir): + result.append(int(entry.name)) + return sorted(result) + + +def verify_checkpoint_archive(path: Path) -> None: + if not zipfile.is_zipfile(path): + raise ValueError(f"resolution final checkpoint archive differs: {path}") + with zipfile.ZipFile(path) as archive: + if not archive.namelist() or archive.testzip() is not None: + raise ValueError(f"resolution final checkpoint is truncated: {path}") + + +def validate_source_completion(plan: dict[str, Any]) -> list[dict[str, Any]]: + assignment = load_assignment(plan) + registry_path = Path(plan["training_registry"]["path"]) + registry = read_json(registry_path) + if sha256(registry_path) != plan["training_registry"]["sha256"]: + raise ValueError("resolution completion registry hash differs") + jobs = {item["condition"]: item for item in registry["conditions"]} + owners = condition_owners(registry, assignment) + controller_path = Path(plan["source_controller_state"]["path"]) + controller = read_json(controller_path) + if ( + sha256(controller_path) != plan["source_controller_state"]["sha256"] + or controller.get("status") != "complete_local" + or controller.get("machine") != "server_new" + or controller.get("plan_sha256") + != plan["training_controller_plan"]["sha256"] + or controller.get("training_registry_sha256") + != plan["training_registry"]["sha256"] + or controller.get("condition_statuses") + != {condition: "complete" for condition in EXPECTED_CONDITIONS} + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new resolution controller completion differs") + + records = [] + root = Path(plan["release_root"]) + for expected in plan["conditions"]: + condition = expected["condition"] + if condition not in jobs or owners.get(condition) != "server_new": + raise ValueError(f"resolution completion ownership differs: {condition}") + job = jobs[condition] + config = Path(job["config"]) + state_path = Path(expected["state"]) + checkpoint = Path(expected["checkpoint"]) + metrics = Path(expected["metrics"]) + summary_path = Path(expected["summary"]) + for path in (state_path, checkpoint, metrics, summary_path, config): + if not path.is_file() or path.is_symlink(): + raise ValueError(f"resolution terminal artifact differs: {path}") + if ( + sha256(config) != job["config_sha256"] + or sha256(state_path) != expected["state_sha256"] + or checkpoint.stat().st_size != expected["checkpoint_bytes"] + or sha256(checkpoint) != expected["checkpoint_sha256"] + or sha256(metrics) != expected["metrics_sha256"] + or sha256(summary_path) != expected["summary_sha256"] + ): + raise ValueError(f"resolution terminal artifact hash differs: {condition}") + if active_writer_pids(job["output_dir"]): + raise ValueError(f"resolution output still has a writer: {condition}") + state = read_json(state_path) + metric = last_json_record(metrics) + summary = read_json(summary_path) + validate_condition_payload(expected, job, state, metric, summary) + verify_checkpoint_archive(checkpoint) + condition_files = [] + for kind, path in (("checkpoint", checkpoint), ("training_state", state_path)): + if root not in path.parents: + raise ValueError(f"resolution release file is outside root: {path}") + condition_files.append({ + "kind": kind, + "path": str(path.relative_to(root)), + "absolute_path": str(path.resolve()), + "bytes": path.stat().st_size, + "sha256": sha256(path), + }) + records.append({ + "condition": condition, + "role": job["role"], + "completed_utc": state["completed_utc"], + "gpu_hours": state["gpu_hours_consumed"], + "wall_seconds": marker_wall_seconds(state), + "final_total_loss": float(metric["losses"]["total"]), + "metrics_sha256": expected["metrics_sha256"], + "summary_sha256": expected["summary_sha256"], + "checkpoint_archive_crc_verified": True, + "active_writer_pids": [], + "files": condition_files, + }) + return records + + +def marker_wall_seconds(state: dict[str, Any]) -> float: + marker = state.get("last_completed", {}) + value = marker.get("wall_seconds") + if not isinstance(value, (int, float)) or not math.isfinite(float(value)): + raise ValueError("resolution terminal wall time differs") + return float(value) + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + existing = read_json(output) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution completion release differs") + conditions = validate_source_completion(plan) + files = [item for condition in conditions for item in condition["files"]] + paths = [item["path"] for item in files] + if len(paths) != 6 or len(set(paths)) != 6: + raise ValueError("resolution completion release inventory differs") + release = { + "schema_version": "phase9_resolution_training_completion_release_v1", + "status": "complete_immutable_release", + "created_utc": utc_now(), + "owner": "server_new", + "destination_owner": "taku3", + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "release_root": str(Path(plan["release_root"]).resolve()), + "source_controller_state": plan["source_controller_state"], + "conditions": conditions, + "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "read_only_after_publish": True, + "single_writer_per_output": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(output, release) + os.chmod(output, 0o444) + for item in files: + os.chmod(Path(item["absolute_path"]), 0o444) + return release + + +def fetch_remote_json(host: str, path: str, timeout: float) -> dict[str, Any]: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if result.returncode: + raise ValueError("resolution completion release is unavailable") + try: + value = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise ValueError("resolution completion release is unreadable") from error + if not isinstance(value, dict): + raise ValueError("resolution completion release is not an object") + return value + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + files = release.get("files", []) + paths = [item.get("path") for item in files] + if ( + release.get("schema_version") + != "phase9_resolution_training_completion_release_v1" + or release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("destination_owner") != "taku3" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("completion_only_reverse_release") is not True + or release.get("live_reverse_sync_performed") is not False + or release.get("read_only_after_publish") is not True + or release.get("single_writer_per_output") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or len(files) != 6 + or len(paths) != len(set(paths)) + or release.get("file_count") != 6 + or sum(item.get("bytes", -1) for item in files) != release.get("total_bytes") + ): + raise ValueError("resolution completion immutable release differs") + expected = { + (item["state_sha256"], item["checkpoint_sha256"]) + for item in plan["conditions"] + } + observed = { + ( + next(file["sha256"] for file in item["files"] if file["kind"] == "training_state"), + next(file["sha256"] for file in item["files"] if file["kind"] == "checkpoint"), + ) + for item in release.get("conditions", []) + } + if expected != observed: + raise ValueError("resolution completion condition hashes differ") + for value in paths: + path = Path(str(value)) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"unsafe resolution completion release path: {path}") + + +def verify_record(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"resolution completion file differs: {path}") + return path + + +def validate_global_completion_payload( + controller: dict[str, Any], registry_sha256: str, + conditions: dict[str, dict[str, Any]], +) -> None: + expected = { + "S7R_J25_full", "S7R_J25_loso_subject1", "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", "S7R_J25_lofamily_h", + "S7R_J25_lofamily_k", "S7R_J25_lofamily_o", + } + if ( + controller.get("status") != "complete" + or controller.get("machine") != "taku3" + or controller.get("training_registry_sha256") != registry_sha256 + or controller.get("condition_statuses") + != {condition: "complete" for condition in sorted(expected)} + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + or set(conditions) != expected + or any( + state.get("status") != "complete" + or state.get("queue_sha256") != registry_sha256 + or state.get("last_completed", {}).get("completed_step") != 405000 + or state.get("official_test_used") is not False + for state in conditions.values() + ) + ): + raise ValueError("global resolution training completion differs") + + +def install_release(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root = Path(plan["release_root"]) + staging = Path(plan["staging_root"]) + pending = [] + installed = [] + for item in release["files"]: + destination = root / item["path"] + if destination.exists(): + verify_record(root, item) + installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".pending_release_files.txt" + file_list.write_text( + "".join(item["path"] + "\n" for item in pending), encoding="utf-8", + ) + result = subprocess.run([ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['source_host']}:{root.resolve()}/", f"{staging.resolve()}/", + ], check=False) + if result.returncode: + raise RuntimeError(f"resolution completion rsync failed: {result.returncode}") + for item in pending: + verify_record(staging, item) + for kind in ("checkpoint", "training_state"): + for item in pending: + if item["kind"] != kind: + continue + source = staging / item["path"] + destination = root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + raise ValueError(f"resolution completion destination appeared: {destination}") + os.replace(source, destination) + os.chmod(destination, 0o444) + verify_record(root, item) + installed.append({**item, "resumed_existing": False}) + return sorted(installed, key=lambda item: item["path"]) + + +def backup_central_controller(plan: dict[str, Any]) -> dict[str, str]: + source = Path(plan["central_controller_state"]) + destination = Path(plan["central_controller_backup"]) + if destination.exists(): + return {"path": str(destination.resolve()), "sha256": sha256(destination)} + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + os.chmod(destination, 0o444) + return {"path": str(destination.resolve()), "sha256": sha256(destination)} + + +def wait_for_global_completion(plan: dict[str, Any]) -> dict[str, Any]: + deadline = time.monotonic() + float(plan["central_completion_timeout_seconds"]) + registry_hash = plan["training_registry"]["sha256"] + state_root = Path(plan["training_state_root"]) + while time.monotonic() < deadline: + controller = read_json(plan["central_controller_state"]) + registry = read_json(plan["training_registry"]["path"]) + states = { + item["condition"]: read_json( + state_root / f"{item['condition'].lower()}.json" + ) + for item in registry["conditions"] + } + try: + validate_global_completion_payload(controller, registry_hash, states) + except ValueError: + time.sleep(2) + continue + return controller + raise TimeoutError("central resolution training controller did not converge") + + +def receive(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + if state_path.is_file(): + existing = read_json(state_path) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution completion receive state differs") + release = fetch_remote_json( + plan["source_host"], plan["release_state"], + float(plan["ssh_timeout_seconds"]), + ) + validate_release(plan_path, plan, release) + backup = backup_central_controller(plan) + installed = install_release(plan, release) + controller = wait_for_global_completion(plan) + result = { + "schema_version": "phase9_resolution_training_completion_receive_v1", + "status": "complete", + "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "release_state": plan["release_state"], + "release_sha256": sha256_bytes(release), + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + "installed": installed, + "central_controller_backup": backup, + "central_controller_state": { + "path": str(Path(plan["central_controller_state"]).resolve()), + "sha256": sha256(plan["central_controller_state"]), + "status": controller["status"], + }, + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(state_path, result) + return result + + +def sha256_bytes(value: dict[str, Any]) -> str: + import hashlib + payload = (json.dumps(value, indent=2) + "\n").encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--state", type=Path) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + expected = Path( + plan["release_state"] if args.role == "publish" else plan["receive_state"] + ) + if args.state and args.state.resolve() != expected.resolve(): + parser.error("resolution completion state path differs") + expected.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{expected}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = publish(args.plan, plan) if args.role == "publish" else receive( + args.plan, plan, expected, + ) + except Exception as error: + failure = Path(f"{expected}.failure.json") + atomic_json(failure, { + "schema_version": "phase9_resolution_training_completion_failure_v1", + "status": "failed_resumable", + "updated_utc": utc_now(), + "role": args.role, + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used": False, + "official_test_used": False, + }) + raise + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_resolution_training_handoff.py b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_resolution_training_handoff.py new file mode 100644 index 0000000000000000000000000000000000000000..e55e92fce4239842ceb0765c72f32f3d506032e7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_resolution_training_handoff.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Publish central Stage 7 readiness and registry to server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +import subprocess +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + unchanged_fields = ( + "model_changed", + "data_changed", + "seed_changed", + "optimizer_changed", + "horizon_changed", + "selection_gate_changed", + ) + if ( + plan.get("schema_version") + != "phase9_resolution_distributed_training_handoff_amendment_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "taku3" + or plan.get("destination_owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("readiness_published_last") is not True + or plan.get("immutable_sync") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("server_new_physical_gpu_allowlist") != [0, 1, 2, 5] + or plan.get("external_owned_conditions") != [ + "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", + "S7R_J25_lofamily_k", + ] + or scientific.get("amendment_scope") + != "resource_scheduling_and_immutable_handoff_only" + or any(scientific.get(field) is not False for field in unchanged_fields) + ): + raise ValueError("resolution training handoff plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution training handoff binding differs: {path}") + + +def ordered_handoff_files(plan: dict[str, Any]) -> list[dict[str, Any]]: + records = list(plan["files"]) + if ( + not records or records[-1].get("role") != "readiness" + or any(item.get("role") == "readiness" for item in records[:-1]) + or len({item["path"] for item in records}) != len(records) + ): + raise ValueError("resolution readiness must be published uniquely and last") + return records + + +def remote_sha256(host: str, path: str) -> str | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "sha256sum", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode or not completed.stdout.strip(): + return None + return completed.stdout.split()[0] + + +def prepare_remote_parent(host: str, path: str) -> None: + parent = str(Path(path).parent) + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "mkdir", "-p", parent], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode: + detail = completed.stderr.strip() or f"returncode={completed.returncode}" + raise ValueError(f"cannot prepare resolution handoff parent {parent}: {detail}") + + +def validate_remote_cache_receive(plan: dict[str, Any]) -> None: + item = plan["remote_cache_receive_state"] + if remote_sha256(plan["destination_host"], item["path"]) != item["sha256"]: + raise ValueError("server_new cache receive state hash differs") + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", plan["destination_host"], "cat", item["path"]], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode: + raise ValueError("server_new cache receive state is unreadable") + try: + state = json.loads(completed.stdout) + except json.JSONDecodeError as error: + raise ValueError("server_new cache receive state is unreadable") from error + if ( + state.get("status") != "complete" + or state.get("file_count") != item["file_count"] + or state.get("total_bytes") != item["total_bytes"] + or state.get("read_only") is not True + or state.get("live_reverse_sync_performed") is not False + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new cache receive state contract differs") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(plan) + records = ordered_handoff_files(plan) + validate_remote_cache_receive(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("resolution training handoff state differs") + if args.state.is_file(): + existing = read_json(args.state) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == sha256(args.plan) + ): + print(json.dumps(existing, indent=2)) + return + parser.error("existing resolution training handoff state differs") + published = [] + for item in records: + source = Path(item["path"]) + if not source.is_file() or sha256(source) != item["sha256"]: + parser.error(f"resolution handoff source differs: {source}") + try: + prepare_remote_parent(plan["destination_host"], str(source.resolve())) + except ValueError as error: + parser.error(str(error)) + completed = subprocess.run([ + "rsync", "-a", "--chmod=F444", str(source.resolve()), + f"{plan['destination_host']}:{source.resolve()}", + ], check=False) + if completed.returncode: + raise SystemExit(completed.returncode) + if remote_sha256(plan["destination_host"], str(source.resolve())) != item["sha256"]: + parser.error(f"resolution handoff remote hash differs: {source}") + published.append(item) + state = { + "schema_version": "phase9_resolution_training_handoff_state_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "destination": plan["destination_host"], "published": published, + "readiness_published_last": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_shared_augmentation_admission.py b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_shared_augmentation_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c3d14120047c2df37a4932378ce275eb8da7e8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_shared_augmentation_admission.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Forward-sync frozen Stage 8 admission and start the remote owner controller.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def admission_files(plan: dict[str, Any]) -> tuple[list[Path], list[dict[str, str]]]: + controller_path = Path(plan["controller_states"]["taku3"]) + if not controller_path.is_file(): + raise NotReady("central Stage 8 controller state is missing") + controller = read_json(controller_path) + registry_path = Path(plan["training_registry"]) + if not registry_path.is_file() or not controller.get("training_registry_sha256"): + raise NotReady("central Stage 8 registry is not frozen yet") + if ( + controller.get("plan_sha256") != sha256(plan_path_from_state(controller)) + or controller.get("training_registry") != str(registry_path.resolve()) + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("central Stage 8 controller binding differs") + registry = read_json(registry_path) + assignment = load_assignment(plan) + owners = condition_owners(registry, assignment) + conditions = registry.get("conditions", []) + if ( + registry.get("status") != "frozen_ready" + or len(conditions) != 7 + or len({item["condition"] for item in conditions}) != 7 + or sum(owner == "server_new" for owner in owners.values()) != 3 + or registry.get("official_test_used") is not False + or registry.get("h2o_official_validation_used_for_selection") is not False + ): + raise ValueError("Stage 8 training registry contract differs") + resolution_state = Path(plan["resolution_controller_state"]) + state = read_json(resolution_state) + decision = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != plan["resolution_controller_plan_sha256"] + or not decision.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(decision) + or state.get("official_test_used") is not False + ): + raise ValueError("Stage 8 resolution admission binding differs") + files = [ + decision, resolution_state, Path(plan["registry_builder_state"]), + *[Path(item["config"]) for item in conditions], registry_path, + ] + for path in files: + if not path.is_file(): + raise ValueError(f"Stage 8 admission file is missing: {path}") + prerequisites = [] + seen = set() + for item in conditions: + pair = (item["initialization_checkpoint"], item["initialization_checkpoint_sha256"]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + for item in registry["data_artifacts"]: + pair = (item["path"], item["sha256"]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + return files, prerequisites + + +def plan_path_from_state(state: dict[str, Any]) -> Path: + path = Path(state.get("plan", "")) + if not path.is_file(): + raise ValueError("Stage 8 controller plan is missing") + return path + + +def remote_sha256(host: str, path: Path) -> str | None: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "sha256sum", str(path)], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, check=False, + ) + return result.stdout.split()[0] if result.returncode == 0 else None + + +def install_file(host: str, path: Path) -> dict[str, Any]: + digest = sha256(path) + observed = remote_sha256(host, path) + if observed is not None: + if observed != digest: + raise ValueError(f"remote Stage 8 admission destination differs: {path}") + return {"path": str(path.resolve()), "sha256": digest, "resumed_existing": True} + temporary = Path(f"{path}.incoming-stage8-v3") + mkdir = subprocess.run( + ["ssh", host, "mkdir", "-p", str(path.parent)], check=False, + ) + if mkdir.returncode: + raise RuntimeError(f"remote Stage 8 admission mkdir failed: {path.parent}") + copied = subprocess.run( + ["rsync", "-a", str(path), f"{host}:{temporary}"], check=False, + ) + if copied.returncode or remote_sha256(host, temporary) != digest: + raise RuntimeError(f"remote Stage 8 admission staging differs: {path}") + installed = subprocess.run( + ["ssh", host, "mv", str(temporary), str(path)], check=False, + ) + if installed.returncode or remote_sha256(host, path) != digest: + raise RuntimeError(f"remote Stage 8 admission install differs: {path}") + return {"path": str(path.resolve()), "sha256": digest, "resumed_existing": False} + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/controller_logs/server_new_training.log" + command = ( + "cd /home/jiasen/foundation_hand && mkdir -p " + str(Path(log).parent) + + " && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_shared_augmentation_training_controller --plan " + + str(plan_path.resolve()) + " --state " + state + + " --machine server_new --poll-seconds 30 >> " + log + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", plan["source_host"], command], check=False) + if result.returncode: + raise RuntimeError("remote Stage 8 controller launch failed") + time.sleep(2) + probe = subprocess.run( + ["ssh", plan["source_host"], "pgrep", "-fo", + "scripts.run_phase9_shared_augmentation_training_controller.*shared_augmentation_v3.*server_new.json"], + stdout=subprocess.PIPE, text=True, check=False, + ) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote Stage 8 controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + files, prerequisites = admission_files(plan) + host = plan["source_host"] + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"local Stage 8 prerequisite differs: {path}") + if remote_sha256(host, path) != item["sha256"]: + raise ValueError(f"remote Stage 8 immutable prerequisite differs: {path}") + registry = Path(plan["training_registry"]) + installed = [] + for path in [item for item in files if item != registry] + [registry]: + installed.append(install_file(host, path)) + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_shared_augmentation_admission_sync_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "installed": installed, "immutable_prerequisites": prerequisites, + "remote_controller_pid": pid, + "registry_installed_last": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args() + plan = read_json(args.plan) + plan["source_host"] = "server_new" + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan) + atomic_json(args.state, result) + print(json.dumps(result, indent=2)) + return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: + raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_admission_sync_v1", + "status": "waiting_for_frozen_registry", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, "official_test_used": False, + }) + time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_shared_augmentation_evaluation_admission.py b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_shared_augmentation_evaluation_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..77f49003f8c121544b93407abc20a771830f37e0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_shared_augmentation_evaluation_admission.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Forward-sync the frozen Stage 8 evaluation plan to server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def frozen_payload(plan: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, str]]]: + dynamic_path = Path(plan["evaluation_plan"]) + central_state = Path(plan["controller_states"]["taku3"]) + if not dynamic_path.is_file() or not central_state.is_file(): + raise NotReady("central Stage 8 evaluation plan is not frozen yet") + state = read_json(central_state) + dynamic = read_json(dynamic_path) + if not state.get("evaluation_plan_sha256"): + raise NotReady("central Stage 8 evaluation controller has not admitted the plan") + if ( + state.get("plan_sha256") != sha256(Path(state["plan"])) + or state.get("evaluation_plan") != str(dynamic_path.resolve()) + or state.get("evaluation_plan_sha256") != sha256(dynamic_path) + or len(dynamic.get("evaluations", [])) != 25 + or len(dynamic.get("workers", [])) != 10 + or dynamic.get("worker_heartbeat_seconds") != 30 + or dynamic.get("stall_timeout_seconds") != 900 + or dynamic.get("official_test_used") is not False + ): + raise ValueError("Stage 8 evaluation admission binding differs") + remote_ids = { + identifier for worker in dynamic["workers"] if worker["owner"] == "server_new" + for identifier in worker["evaluation_ids"] + } + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + if len(remote_ids) != 9: + raise ValueError("Stage 8 remote evaluation ownership differs") + prerequisites = [] + seen = set() + for identifier in sorted(remote_ids): + item = evaluations[identifier] + for path_key, hash_key in ( + ("config", "config_sha256"), ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256"), + ): + pair = (item[path_key], item[hash_key]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + return dynamic, prerequisites + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/controller_logs/server_new_evaluation.log" + command = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_shared_augmentation_evaluation_controller --plan " + + str(plan_path.resolve()) + " --state " + state + + " --machine server_new --poll-seconds 30 >> " + log + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: + raise RuntimeError("remote Stage 8 evaluation controller launch failed") + time.sleep(2) + probe = subprocess.run([ + "ssh", "server_new", "pgrep", "-fo", + "scripts.run_phase9_shared_augmentation_evaluation_controller.*shared_augmentation_v3.*server_new.json", + ], stdout=subprocess.PIPE, text=True, check=False) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote Stage 8 evaluation controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + _, prerequisites = frozen_payload(plan) + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"central Stage 8 evaluation prerequisite differs: {path}") + if remote_sha256("server_new", path) != item["sha256"]: + raise ValueError(f"remote Stage 8 evaluation prerequisite differs: {path}") + dynamic = Path(plan["evaluation_plan"]) + files = [ + Path(plan["training_controller_state"]), Path(plan["evaluation_plan_state"]), + dynamic, + ] + installed = [install_file("server_new", path) for path in files[:-1]] + installed.append(install_file("server_new", dynamic)) + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_shared_augmentation_evaluation_admission_sync_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "evaluation_plan_sha256": sha256(dynamic), "installed": installed, + "immutable_prerequisites": prerequisites, "evaluation_plan_installed_last": True, + "remote_controller_pid": pid, "official_test_used": False, + "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_evaluation_admission_sync_v1", + "status": "waiting_for_frozen_evaluation_plan", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "plan_sha256": sha256(args.plan), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_shared_augmentation_training_completion.py b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_shared_augmentation_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..8c94bcfcd6549c3e5607171cb2a612bd1d6b3b3e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_shared_augmentation_training_completion.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Completion-only server_new to taku3 handoff for Stage 8 training.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_resolution_training_completion import ( + active_writer_pids, + last_json_record, + verify_checkpoint_archive, +) + + +EXPECTED = ( + "S8A_J25_loso_subject2", "S8A_J25_loso_subject3", "S8A_J25_lofamily_k", +) + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: dict[str, Any]) -> str: + return hashlib.sha256((json.dumps(value, indent=2) + "\n").encode()).hexdigest() + + +def validate_plan(path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("schema_version") + != "phase9_shared_augmentation_training_completion_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or tuple(plan.get("conditions", [])) != EXPECTED + or plan.get("target_step") != 405000 + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("Stage 8 training completion plan contract differs") + for key in ("release_root", "staging_root", "release_state", "receive_state"): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"Stage 8 completion {key} is not /SSD2") + for binding in plan["bindings"]: + candidate = Path(binding["path"]) + if not candidate.is_file() or sha256(candidate) != binding["sha256"]: + raise ValueError(f"Stage 8 completion binding differs: {candidate}") + if not path.is_file(): + raise ValueError("Stage 8 completion plan is unreadable") + + +def registry_payload(plan: dict[str, Any]) -> tuple[Path, dict[str, Any], dict[str, Any]]: + path = Path(plan["training_registry"]["path"]) + if not path.is_file() or sha256(path) != plan["training_registry"]["sha256"]: + raise ValueError("Stage 8 training registry hash differs") + registry = read_json(path) + owners = condition_owners(registry, load_assignment(plan)) + jobs = {item["condition"]: item for item in registry["conditions"]} + if ( + registry.get("status") != "frozen_ready" + or registry.get("target_step") != 405000 + or tuple(condition for condition in jobs if owners[condition] == "server_new") + != EXPECTED + or registry.get("official_test_used") is not False + ): + raise ValueError("Stage 8 training registry contract differs") + return path, registry, jobs + + +def validate_terminal(job: dict[str, Any], state: dict[str, Any]) -> tuple[Path, dict[str, Any]]: + marker = state.get("last_completed", {}) + checkpoint = Path(marker.get("checkpoint", "")) + metrics = Path(job["output_dir"]) / "metrics.jsonl" + summary_path = Path(job["output_dir"]) / "summary.json" + if not checkpoint.is_file() or not metrics.is_file() or not summary_path.is_file(): + raise ValueError(f"Stage 8 terminal artifact is missing: {job['condition']}") + metric = last_json_record(metrics) + summary = read_json(summary_path) + losses = metric.get("losses", {}) + if ( + state.get("status") != "complete" + or state.get("condition") != job["condition"] + or marker.get("completed_step") != 405000 + or marker.get("config") != job["config"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") != job["expected_source_exposure_batches"] + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or metric.get("step") != 405000 + or not losses + or any(not isinstance(value, (int, float)) or not math.isfinite(float(value)) + for value in losses.values()) + or summary.get("status") != "completed" + or summary.get("completed_step") != 405000 + or summary.get("final_checkpoint_sha256") != marker["checkpoint_sha256"] + or summary.get("official_test_used") is not False + or state.get("official_test_used") is not False + ): + raise ValueError(f"Stage 8 terminal evidence differs: {job['condition']}") + verify_checkpoint_archive(checkpoint) + return checkpoint, {"metric": metric, "summary": summary, + "metrics_sha256": sha256(metrics), + "summary_sha256": sha256(summary_path)} + + +def file_record(root: Path, kind: str, path: Path) -> dict[str, Any]: + if not path.is_file() or path.is_symlink() or root not in path.resolve().parents: + raise ValueError(f"Stage 8 release file differs: {path}") + return {"kind": kind, "path": str(path.resolve().relative_to(root.resolve())), + "absolute_path": str(path.resolve()), "bytes": path.stat().st_size, + "sha256": sha256(path)} + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + registry_path, _, jobs = registry_payload(plan) + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): + raise NotReady("server_new Stage 8 controller state is missing") + controller = read_json(controller_path) + if controller.get("status") != "complete_local": + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("server_new Stage 8 controller failed") + raise NotReady("server_new Stage 8 training is still running") + if ( + controller.get("plan_sha256") != plan["training_controller_plan"]["sha256"] + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("condition_statuses") != {condition: "complete" for condition in EXPECTED} + or controller.get("official_test_used") is not False + ): + raise ValueError("server_new Stage 8 controller binding differs") + root = Path(plan["release_root"]) + state_root = Path(plan["training_state_root"]) + records, files = [], [] + for condition in EXPECTED: + job = jobs[condition] + state_path = state_root / f"{condition.lower()}.json" + state = read_json(state_path) + if state.get("queue_sha256") != sha256(registry_path): + raise ValueError(f"Stage 8 state registry binding differs: {condition}") + if active_writer_pids(job["output_dir"]): + raise NotReady(f"Stage 8 writer still exists: {condition}") + checkpoint, evidence = validate_terminal(job, state) + condition_files = [file_record(root, "checkpoint", checkpoint), + file_record(root, "training_state", state_path)] + files.extend(condition_files) + records.append({ + "condition": condition, "role": job["role"], + "checkpoint_sha256": sha256(checkpoint), + "final_total_loss": float(evidence["metric"]["losses"]["total"]), + "metrics_sha256": evidence["metrics_sha256"], + "summary_sha256": evidence["summary_sha256"], + "gpu_hours": state["gpu_hours_consumed"], "files": condition_files, + }) + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + value = read_json(output) + if value.get("status") == "complete_immutable_release" and value.get("plan_sha256") == sha256(plan_path): + return value + raise ValueError("existing Stage 8 release differs") + records, files = source_records(plan) + value = { + "schema_version": "phase9_shared_augmentation_training_completion_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "destination_owner": "taku3", + "plan_sha256": sha256(plan_path), "release_root": plan["release_root"], + "training_registry": plan["training_registry"], + "conditions": records, "files": files, "file_count": 6, + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, "live_reverse_sync_performed": False, + "results_before_terminal_states": True, "single_writer_per_output": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, value) + os.chmod(output, 0o444) + for item in files: + os.chmod(item["absolute_path"], 0o444) + return value + + +def fetch(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run(["ssh", plan["source_host"], "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, check=False) + if result.returncode: + raise NotReady("server_new Stage 8 release is unavailable") + return json.loads(result.stdout) + + +def validate_release(plan_path: Path, plan: dict[str, Any], value: dict[str, Any]) -> None: + files = value.get("files", []) + if ( + value.get("schema_version") != "phase9_shared_augmentation_training_completion_release_v1" + or value.get("status") != "complete_immutable_release" + or value.get("plan_sha256") != sha256(plan_path) + or value.get("training_registry") != plan["training_registry"] + or tuple(item.get("condition") for item in value.get("conditions", [])) != EXPECTED + or len(files) != 6 or len({item.get("path") for item in files}) != 6 + or sum(item.get("bytes", -1) for item in files) != value.get("total_bytes") + or value.get("results_before_terminal_states") is not True + or value.get("official_test_used") is not False + ): + raise ValueError("Stage 8 immutable release differs") + + +def verify(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if (not path.is_file() or path.is_symlink() or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"]): + raise ValueError(f"Stage 8 completion file differs: {path}") + return path + + +def install(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root, staging = Path(plan["release_root"]), Path(plan["staging_root"]) + pending, installed = [], [] + for item in release["files"]: + if (root / item["path"]).exists(): + verify(root, item); installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + listing = staging / ".pending_stage8_files.txt" + listing.write_text("".join(item["path"] + "\n" for item in pending), encoding="utf-8") + result = subprocess.run(["rsync", "-a", "--partial", f"--files-from={listing}", + f"{plan['source_host']}:{root}/", f"{staging}/"], check=False) + if result.returncode: + raise RuntimeError("Stage 8 completion rsync failed") + for item in pending: verify(staging, item) + for kind in ("checkpoint", "training_state"): + for item in pending: + if item["kind"] != kind: continue + source, destination = staging / item["path"], root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination); os.chmod(destination, 0o444) + verify(root, item); installed.append({**item, "resumed_existing": False}) + return installed + + +def central_complete(plan: dict[str, Any]) -> bool: + path = Path(plan["central_controller_state"]) + if not path.is_file(): return False + value = read_json(path) + return (value.get("status") == "complete" + and value.get("training_registry_sha256") == plan["training_registry"]["sha256"] + and value.get("official_test_used") is False) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): return read_json(output) + release = fetch(plan); validate_release(plan_path, plan, release) + backup = Path(plan["central_controller_backup"]) + if not backup.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(plan["central_controller_state"], backup); os.chmod(backup, 0o444) + installed = install(plan, release) + deadline = time.monotonic() + plan["central_completion_timeout_seconds"] + while time.monotonic() < deadline and not central_complete(plan): time.sleep(2) + if not central_complete(plan): raise TimeoutError("central Stage 8 controller did not converge") + value = { + "schema_version": "phase9_shared_augmentation_training_completion_receive_v1", + "status": "complete", "completed_utc": utc_now(), + "plan_sha256": sha256(plan_path), "release_sha256": json_sha256(release), + "file_count": 6, "total_bytes": release["total_bytes"], "installed": installed, + "results_before_terminal_states": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, value); return value + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + try: validate_plan(args.plan, plan) + except ValueError as error: parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True) + deadline = time.monotonic() + args.wait_timeout_seconds + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + value = publish(args.plan, plan) if args.role == "publish" else receive(args.plan, plan) + print(json.dumps(value, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(Path(f"{target}.watcher.json"), { + "schema_version": "phase9_shared_augmentation_training_completion_watcher_v1", + "status": "waiting_for_terminal_source", "role": args.role, + "watcher_pid": os.getpid(), "updated_utc": utc_now(), "detail": str(error), + "plan_sha256": sha256(args.plan), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_taku_resolution_caches.py b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_taku_resolution_caches.py new file mode 100644 index 0000000000000000000000000000000000000000..84cb358bfea905f09ef6978f46deff950973aab4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/sync_phase9_taku_resolution_caches.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python3 +"""Publish and install Taku3-owned Stage 7 caches on server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("source_owner") != "taku3" + or plan.get("destination_owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("live_reverse_sync_forbidden") is not True + ): + raise ValueError("Taku3 cache sync plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"Taku3 cache sync binding differs: {path}") + root = Path(plan["release_root"]) + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("Taku3 cache sync root is not /SSD2") + for item in plan["artifacts"]: + path = Path(item["path"]) + if root not in path.parents: + raise ValueError(f"Taku3 cache artifact is outside release root: {path}") + + +def known_payload_hashes(manifests: list[str]) -> dict[Path, str]: + known: dict[Path, str] = {} + hash_fields = ( + ("cache_path", "cache_sha256"), + ("joint3d_root_relative_sidecar_path", "joint3d_root_relative_sidecar_sha256"), + ) + for value in manifests: + for line in Path(value).read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + row = json.loads(line) + for path_field, hash_field in hash_fields: + if row.get(path_field) and row.get(hash_field): + path = Path(row[path_field]).resolve() + digest = row[hash_field] + previous = known.setdefault(path, digest) + if previous != digest: + raise ValueError(f"conflicting manifest payload hash: {path}") + return known + + +def inventory_artifacts( + root: Path, artifacts: list[dict[str, Any]], known: dict[Path, str], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + files: list[dict[str, Any]] = [] + artifact_records = [] + seen: set[str] = set() + for item in artifacts: + artifact = Path(item["path"]) + if not artifact.exists() or artifact.is_symlink(): + raise ValueError(f"Taku3 cache artifact differs: {artifact}") + candidates = [artifact] if artifact.is_file() else sorted(artifact.rglob("*")) + start = len(files) + for path in candidates: + if path.is_symlink(): + raise ValueError(f"Taku3 cache release refuses symlink: {path}") + if not path.is_file(): + continue + relative = str(path.relative_to(root)) + if relative in seen: + raise ValueError(f"duplicate Taku3 cache release path: {relative}") + seen.add(relative) + digest = known.get(path.resolve()) + if digest is None: + digest = sha256(path) + files.append({ + "path": relative, "sha256": digest, "bytes": path.stat().st_size, + }) + selected = files[start:] + artifact_records.append({ + "id": item["id"], "path": str(artifact.resolve()), + "relative_path": str(artifact.relative_to(root)), + "kind": "file" if artifact.is_file() else "directory", + "file_count": len(selected), + "total_bytes": sum(record["bytes"] for record in selected), + }) + return files, artifact_records + + +def validate_readiness(plan: dict[str, Any]) -> dict[str, Any]: + path = Path(plan["readiness_state"]["path"]) + state = read_json(path) + audit = Path(state.get("audit", {}).get("path", "")) + if ( + state.get("status") != "complete" + or sha256(path) != plan["readiness_state"]["sha256"] + or state.get("plan_sha256") != plan["cache_execution_plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not audit.is_file() + or state.get("audit", {}).get("sha256") != sha256(audit) + ): + raise ValueError("Taku3 cache release readiness differs") + return state + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + readiness = validate_readiness(plan) + output = Path(plan["release_state"]) + if output.is_file(): + release = read_json(output) + if ( + release.get("status") == "complete_immutable_release" + and release.get("plan_sha256") == sha256(plan_path) + ): + return release + raise ValueError("existing Taku3 cache release differs") + root = Path(plan["release_root"]) + known = known_payload_hashes(plan["payload_manifests"]) + files, artifacts = inventory_artifacts(root, plan["artifacts"], known) + release = { + "schema_version": "phase9_taku_cache_immutable_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "taku3", "destination_owner": "server_new", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_root": str(root.resolve()), + "readiness_state": { + "path": str(Path(plan["readiness_state"]["path"]).resolve()), + "sha256": plan["readiness_state"]["sha256"], + "audit": readiness["audit"], + }, + "artifacts": artifacts, "files": files, "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "payload_hash_source": "globally_audited_cache_and_sidecar_manifests", + "read_only_after_publish": True, "live_reverse_sync_forbidden": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, release) + os.chmod(output, 0o444) + for item in plan["artifacts"]: + path = Path(item["path"]) + if path.is_file(): + os.chmod(path, 0o444) + continue + for candidate in path.rglob("*"): + os.chmod(candidate, 0o555 if candidate.is_dir() else 0o444) + os.chmod(path, 0o555) + return release + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != "taku3" + or release.get("destination_owner") != "server_new" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("read_only_after_publish") is not True + or release.get("live_reverse_sync_forbidden") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or len(release.get("files", [])) != release.get("file_count") + or sum(item["bytes"] for item in release["files"]) != release.get("total_bytes") + ): + raise ValueError("Taku3 cache immutable release differs") + paths = [item["path"] for item in release["files"]] + if len(paths) != len(set(paths)) or any( + Path(path).is_absolute() or ".." in Path(path).parts for path in paths + ): + raise ValueError("Taku3 cache release paths differ") + + +def push(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + release = read_json(plan["release_state"]) + validate_release(plan_path, plan, release) + file_list = Path(plan["push_file_list"]) + file_list.parent.mkdir(parents=True, exist_ok=True) + file_list.write_text( + "".join(item["path"] + "\n" for item in release["files"]), + encoding="utf-8", + ) + state = { + "schema_version": "phase9_taku_cache_push_state_v1", + "status": "syncing", "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state_sha256": sha256(plan["release_state"]), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "destination": plan["destination_host"], + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, state) + staging = Path(plan["destination_staging_root"]) + command = [ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{Path(plan['release_root']).resolve()}/", + f"{plan['destination_host']}:{staging.resolve()}/", + ] + completed = subprocess.run(command, check=False) + state["returncode"] = completed.returncode + state["updated_utc"] = utc_now() + state["status"] = "synced_waiting_for_remote_install" if not completed.returncode else "failed_resumable" + atomic_json(state_path, state) + if completed.returncode: + raise SystemExit(completed.returncode) + return state + + +def verify_files(root: Path, release: dict[str, Any]) -> None: + for item in release["files"]: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] or sha256(path) != item["sha256"] + ): + raise ValueError(f"received Taku3 cache file differs: {path}") + + +def install(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + release = read_json(plan["release_state"]) + validate_release(plan_path, plan, release) + staging = Path(plan["destination_staging_root"]) + verify_files(staging, release) + root = Path(plan["release_root"]) + installed = [] + for item in release["artifacts"]: + source = staging / item["relative_path"] + destination = root / item["relative_path"] + if destination.exists(): + raise ValueError(f"Taku3 cache destination already exists: {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination) + if destination.is_file(): + os.chmod(destination, 0o444) + else: + for path in destination.rglob("*"): + os.chmod(path, 0o555 if path.is_dir() else 0o444) + os.chmod(destination, 0o555) + installed.append(item) + state = { + "schema_version": "phase9_taku_cache_receive_state_v1", + "status": "complete", "completed_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state_sha256": sha256(plan["release_state"]), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "installed": installed, "read_only": True, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, state) + return state + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "push", "install"), required=True) + parser.add_argument("--state", type=Path) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + expected_state = { + "publish": Path(plan["release_state"]), + "push": Path(plan["push_state"]), + "install": Path(plan["destination_receive_state"]), + }[args.role] + if args.state and args.state.resolve() != expected_state.resolve(): + parser.error("Taku3 cache sync state differs") + expected_state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{expected_state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.role == "publish": + result = publish(args.plan, plan) + elif args.role == "push": + result = push(args.plan, plan, expected_state) + else: + result = install(args.plan, plan, expected_state) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/train_experiment.py b/home/wuyifan/EgoNet_train_20261008/scripts/train_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..0773e54df5b6b201d2dd25e039341ea338b675c6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/train_experiment.py @@ -0,0 +1,776 @@ +#!/usr/bin/env python3 +"""Formal H2O camera-space training entry point with hard asset/geometry gates.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import random +import shlex +import socket +import subprocess +import sys +import time +from dataclasses import asdict +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import ( + H2OCam4Dataset, + ResumableRandomBatchSampler, + ResumableWeightedBatchSampler, + collate_h2o_clips, + load_balanced_sampling_weights, +) +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.metrics import camera_metrics +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, + set_scheduled_learning_rate, +) +from foundation_hand.training.schedule import warmup_cosine_learning_rate + + +def git_state() -> str: + return subprocess.run(["git", "status", "--short"], text=True, stdout=subprocess.PIPE, check=False).stdout + + +def git_commit() -> str | None: + result = subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=False, + ) + return result.stdout.strip() or None + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def resolved_weight_path(value: str) -> Path: + path = Path(value) + return path / "model.safetensors" if path.is_dir() else path + + +def capture_run_provenance( + args: argparse.Namespace, + config: dict, + output_path: Path, +) -> Path: + assets = config["assets"] + tracked_files = { + "config": args.config, + "train_manifest": args.manifest, + "validation_manifest": args.val_manifest, + "validation_subset": args.validation_subset_manifest, + "sampling_manifest": Path(config.get("sampling", {}).get("manifest", "")), + "initialization_checkpoint": args.init_checkpoint, + "dinov3_weights": resolved_weight_path(assets["dinov3_weights"]), + "mano_left": Path(assets["mano_root"]) / "MANO_LEFT.pkl", + "mano_right": Path(assets["mano_root"]) / "MANO_RIGHT.pkl", + } + hashes = { + name: {"path": str(path.resolve()), "sha256": file_sha256(path)} + for name, path in tracked_files.items() if path is not None and path.is_file() + } + gpu_inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid,name,memory.total", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, + ).stdout.strip().splitlines() + provenance = { + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "hostname": socket.gethostname(), + "git_commit": git_commit(), + "git_status": git_state(), + "command_argv": [sys.executable, *sys.argv], + "command_shell": shlex.join([sys.executable, *sys.argv]), + "working_directory": str(Path.cwd()), + "config": config, + "seed": int(config["seed"]), + "cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "gpu_inventory": gpu_inventory, + "python": sys.version, + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "hashes": hashes, + "resume_checkpoint": str(args.resume.resolve()) if args.resume else None, + "initialization_checkpoint": ( + str(args.init_checkpoint.resolve()) if args.init_checkpoint else None + ), + } + output_path.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8") + return output_path + + +def load_validation_subset( + path: Path, + validation_manifest: Path, + data_config: dict, + dataset_size: int, +) -> tuple[list[int], dict]: + record = json.loads(path.read_text(encoding="utf-8")) + if record.get("source_manifest_sha256") != file_sha256(validation_manifest): + raise ValueError("validation subset source-manifest hash does not match --val-manifest") + contract = record.get("dataset_contract", {}) + expected = { + "resolution_hw": list(data_config["resolution_hw"]), + "T": int(data_config["T"]), + "stride": int(data_config["stride"]), + } + for key, value in expected.items(): + if contract.get(key) != value: + raise ValueError(f"validation subset contract mismatch for {key}: {contract.get(key)} != {value}") + indices = [int(index) for index in record["clip_indices"]] + if len(indices) != len(set(indices)) or not indices: + raise ValueError("validation subset indices must be non-empty and unique") + if min(indices) < 0 or max(indices) >= dataset_size: + raise ValueError("validation subset index is outside the validation dataset") + return indices, record + + +def preflight(config: dict, root: Path, manifest: Path) -> list[str]: + blockers = [] + if not root.is_dir(): blockers.append(f"dataset root missing: {root}") + if not manifest.is_file(): blockers.append(f"manifest missing: {manifest}") + assets = config.get("assets", {}) + source = Path(assets.get("dinov3_source") or "") + weights = Path(assets.get("dinov3_weights") or "") + mano_root = Path(assets.get("mano_root") or "") + if not (source / "hubconf.py").is_file(): blockers.append(f"official DINOv3 source missing: {source}") + valid_weight = weights.is_file() or (weights.is_dir() and (weights / "model.safetensors").is_file()) + if not valid_weight: blockers.append("DINOv3 pretrained weight missing; formal training forbids random DINO") + for side in ("LEFT", "RIGHT"): + if not (mano_root / f"MANO_{side}.pkl").is_file(): blockers.append(f"licensed MANO_{side}.pkl missing") + coordinate_report = Path("artifacts/phase2/coordinate_audit/mano_audit.json") + if not coordinate_report.is_file(): blockers.append("numerical MANO reconstruction/translation audit has not passed") + else: + audit = json.loads(coordinate_report.read_text(encoding="utf-8")) + if audit.get("status") != "passed": blockers.append("MANO coordinate audit exists but did not pass") + return blockers + + +def protocol_mismatches(config: dict, args: argparse.Namespace) -> list[str]: + """Reject formal runs whose CLI silently diverges from the registered config.""" + + protocol = config.get("protocol") + if protocol is None: + return [] + actual = { + "max_steps": args.max_steps, + "num_workers": args.num_workers, + "checkpoint_interval": args.checkpoint_interval, + "validation_interval": args.validation_interval, + "validation_batches": args.validation_batches, + "learning_rate": args.learning_rate, + "min_learning_rate": args.min_learning_rate, + "warmup_steps": args.warmup_steps, + "early_stopping_patience": args.early_stopping_patience, + } + mismatches = [ + f"protocol {key}={protocol.get(key)} but CLI resolved {value}" + for key, value in actual.items() if protocol.get(key) != value + ] + if "lr_schedule_steps" in protocol: + resolved_schedule_steps = ( + args.max_steps if args.lr_schedule_steps is None else args.lr_schedule_steps + ) + if protocol["lr_schedule_steps"] != resolved_schedule_steps: + mismatches.append( + "protocol lr_schedule_steps=" + f"{protocol['lr_schedule_steps']} but CLI resolved {resolved_schedule_steps}" + ) + registered_subset = protocol.get("validation_subset_manifest") + actual_subset = str(args.validation_subset_manifest) if args.validation_subset_manifest else None + if registered_subset != actual_subset: + mismatches.append( + f"protocol validation_subset_manifest={registered_subset} but CLI resolved {actual_subset}" + ) + return mismatches + + +def attach_gt_vertices(batch: dict[str, torch.Tensor], model: BimanualReconstructionModel) -> None: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for formal geometry supervision") + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, _ = model.mano_layer(rotations, torch.nan_to_num(batch["mano_shape"]), torch.nan_to_num(batch["wrist_root_translation"])) + valid = ( + batch.get("vertices_valid", batch["mano_annotation_valid"]).bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where(valid, vertices, torch.full_like(vertices, torch.nan)) + + +def move_to_device(batch: dict, device: torch.device) -> dict: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def photometric_diagnostics(batch: dict[str, torch.Tensor]) -> dict[str, float]: + parameters = batch.get("photometric_aug_params") + if parameters is None: + return {} + values = parameters[batch["frame_valid"].bool()] + if values.numel() == 0: + return {} + return { + "applied_fraction": float(values[:, 0].mean()), + "brightness_mean": float(values[:, 1].mean()), + "contrast_mean": float(values[:, 2].mean()), + "saturation_mean": float(values[:, 3].mean()), + "hue_mean": float(values[:, 4].mean()), + } + + +def run_validation( + model: BimanualReconstructionModel, + criterion: BimanualLoss, + loader: DataLoader, + device: torch.device, + dtype: torch.dtype, + max_batches: int, +) -> dict[str, dict[str, float]]: + """Run a bounded deterministic validation pass without changing train RNG.""" + + was_training = model.training + model.eval() + loss_values: dict[str, list[float]] = {} + metric_values: dict[str, list[float]] = {} + with torch.inference_mode(): + for batch_index, batch in enumerate(loader): + if batch_index >= max_batches: + break + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + for key, value in losses.items(): + scalar = float(value) + if math.isfinite(scalar): + loss_values.setdefault(key, []).append(scalar) + for key, value in camera_metrics(prediction, batch).items(): + if math.isfinite(value): + metric_values.setdefault(key, []).append(value) + model.train(was_training) + return { + "losses": {key: sum(values) / len(values) for key, values in loss_values.items()}, + "metrics": {key: sum(values) / len(values) for key, values in metric_values.items()}, + } + + +def validation_state_from_log(path: Path, metric: str) -> tuple[float, int]: + if not path.is_file(): + return float("inf"), 0 + best = float("inf") + no_improvement = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + record = json.loads(line) + value = record.get("metrics", {}).get(metric) + if value is not None and math.isfinite(value): + if float(value) < best: + best = float(value) + no_improvement = 0 + else: + no_improvement += 1 + return best, no_improvement + + +def attention_diagnostics(prediction: dict, batch: dict) -> dict[str, float | None]: + attention = prediction.get("attention", {}) + frame_valid = batch["frame_valid"].bool() + result: dict[str, float | None] = {} + if "rgb_cross_attention" in attention: + weights = attention["rgb_cross_attention"][:, -1] + left, right = weights[..., 0, :], weights[..., 1, :] + result["rgb_attention_same_peak_fraction"] = float( + (left.argmax(-1) == right.argmax(-1))[frame_valid].float().mean() + ) + result["rgb_attention_left_right_cosine"] = float( + torch.nn.functional.cosine_similarity(left, right, dim=-1)[frame_valid].mean() + ) + if "depth_fusion_gate" in attention: + result["depth_gate_mean"] = float(attention["depth_fusion_gate"][:, -1][frame_valid].float().mean()) + result["depth_gate_raw_mean"] = float(attention["depth_fusion_gate_raw"][:, -1][frame_valid].float().mean()) + result["gated_depth_update_norm_mean"] = float( + attention["gated_depth_update_norm"][:, -1][frame_valid].float().mean() + ) + if "temporal_attention" in attention: + weights = attention["temporal_attention"][:, -1] + entropy_values = [] + for batch_index in range(weights.shape[0]): + valid_indices = torch.where(frame_valid[batch_index])[0] + if valid_indices.numel() <= 1: + continue + selected = weights[batch_index, :, valid_indices][:, :, valid_indices].float() + selected = selected / selected.sum(dim=-1, keepdim=True).clamp_min(1e-8) + entropy = -(selected * selected.clamp_min(1e-8).log()).sum(dim=-1) / math.log(valid_indices.numel()) + entropy_values.append(entropy.mean()) + result["temporal_attention_normalized_entropy"] = ( + float(torch.stack(entropy_values).mean()) if entropy_values else None + ) + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--val-manifest", type=Path) + parser.add_argument("--validation-subset-manifest", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--max-steps", type=int, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--checkpoint-interval", type=int, default=100) + parser.add_argument("--learning-rate", type=float, default=1e-4) + parser.add_argument("--min-learning-rate", type=float) + parser.add_argument("--lr-schedule-steps", type=int) + parser.add_argument("--warmup-steps", type=int, default=0) + parser.add_argument("--depth-gate-warmup-steps", type=int, default=0) + parser.add_argument("--validation-interval", type=int, default=500) + parser.add_argument("--validation-batches", type=int, default=32) + parser.add_argument("--max-minutes", type=float) + parser.add_argument("--early-stopping-patience", type=int, default=0) + args = parser.parse_args() + if args.checkpoint_interval <= 0: + parser.error("--checkpoint-interval must be positive") + if args.validation_interval <= 0: + parser.error("--validation-interval must be positive") + if args.validation_batches <= 0: + parser.error("--validation-batches must be positive") + if args.max_minutes is not None and args.max_minutes <= 0: + parser.error("--max-minutes must be positive") + if args.early_stopping_patience < 0: + parser.error("--early-stopping-patience must be non-negative") + if args.resume is not None and args.init_checkpoint is not None: + parser.error("--resume and --init-checkpoint are mutually exclusive") + lr_schedule_steps = ( + args.max_steps if args.lr_schedule_steps is None else args.lr_schedule_steps + ) + if not 0 < lr_schedule_steps <= args.max_steps: + parser.error("--lr-schedule-steps must be in (0, max-steps]") + if not 0 <= args.warmup_steps < lr_schedule_steps: + parser.error("--warmup-steps must be in [0, lr-schedule-steps)") + min_learning_rate = args.learning_rate if args.min_learning_rate is None else args.min_learning_rate + if not 0 <= min_learning_rate <= args.learning_rate: + parser.error("--min-learning-rate must be in [0, learning-rate]") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + deterministic_training = bool( + config.get("protocol", {}).get("deterministic_training", False) + ) + if deterministic_training: + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.use_deterministic_algorithms(True) + torch.backends.cudnn.benchmark = False + oracle_crop_mode = config.get("model", {}).get("oracle_crop_mode", "none") + structured_refinement = bool( + config.get("model", {}).get("structured_hand_refinement", False) + ) + mixed_projection = ( + config.get("model", {}).get( + "translation_parameterization", "direct_xyz", + ) == "mixed_projection" + ) + spatial_joint2d = ( + config.get("model", {}).get( + "joint2d_parameterization", "hand_token_linear", + ) == "spatial_heatmap" + ) + matched_control_initialization = bool( + config.get("experiment", {}).get("matched_control_initialization", False) + ) + residual_initialization = ( + oracle_crop_mode != "none" or structured_refinement + or mixed_projection or spatial_joint2d + ) + if residual_initialization and args.resume is None and args.init_checkpoint is None: + parser.error("registered residual training requires --init-checkpoint on a new run") + if ( + not residual_initialization + and not matched_control_initialization + and args.init_checkpoint is not None + ): + parser.error( + "--init-checkpoint is restricted to registered residual or matched-control runs" + ) + if args.init_checkpoint is not None: + if not args.init_checkpoint.is_file(): + parser.error(f"initialization checkpoint missing: {args.init_checkpoint}") + expected_init_hash = config.get("experiment", {}).get("coarse_checkpoint_sha256") + actual_init_hash = file_sha256(args.init_checkpoint) + if expected_init_hash != actual_init_hash: + parser.error( + "initialization checkpoint hash mismatch: " + f"{actual_init_hash} != {expected_init_hash}" + ) + protocol_errors = protocol_mismatches(config, args) + if protocol_errors: + parser.error("; ".join(protocol_errors)) + if args.validation_subset_manifest is not None and args.val_manifest is None: + parser.error("--validation-subset-manifest requires --val-manifest") + if args.output_dir.exists() and any(args.output_dir.iterdir()) and args.resume is None: + parser.error("--output-dir must be new or empty unless --resume is provided") + args.output_dir.mkdir(parents=True, exist_ok=True) + blockers = preflight(config, args.root, args.manifest) + if args.val_manifest is not None and not args.val_manifest.is_file(): + blockers.append(f"validation manifest missing: {args.val_manifest}") + if args.validation_subset_manifest is not None and not args.validation_subset_manifest.is_file(): + blockers.append(f"validation subset manifest missing: {args.validation_subset_manifest}") + if blockers: + result = {"status": "blocked_preflight", "config": str(args.config), "blockers": blockers, "timestamp": datetime.now(timezone.utc).isoformat()} + (args.output_dir / "BLOCKED.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + raise SystemExit(2) + + provenance_name = "run_provenance.json" if args.resume is None else f"resume_provenance_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json" + provenance_path = capture_run_provenance(args, config, args.output_dir / provenance_name) + sampling_config = config.get("sampling", {"mode": "uniform"}) + sampling_mode = str(sampling_config.get("mode", "uniform")) + if sampling_mode not in {"uniform", "balanced"}: + parser.error(f"unsupported sampling mode: {sampling_mode}") + checkpoint_context = { + "config": config, + "external_frozen_backbone": config["assets"]["dinov3_weights"], + "sampler": ( + "global_step_weighted_v1" if sampling_mode == "balanced" + else "global_step_seeded_v1" + ), + "git_commit": git_commit(), + "run_provenance": str(provenance_path), + "run_provenance_sha256": file_sha256(provenance_path), + "initialization_checkpoint": ( + { + "path": str(args.init_checkpoint.resolve()), + "sha256": file_sha256(args.init_checkpoint), + } + if args.init_checkpoint is not None else None + ), + } + + seed = int(config["seed"]); random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + data_config, model_values, assets = config["data"], config["model"], config["assets"] + photometric_config = data_config.get("photometric_augmentation") + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + photometric_augmentation=photometric_config, + augmentation_seed=seed, + oracle_crop_enabled=oracle_crop_mode != "none", + ) + model_config = ModelConfig(**model_values, dinov3_source=assets["dinov3_source"], dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"]) + device = torch.device("cuda") + model = BimanualReconstructionModel(model_config).to(device) + initialization_record = None + if args.init_checkpoint is not None: + allowed_missing_prefixes = ( + (("oracle_crop_",) if oracle_crop_mode != "none" else ()) + + (("structured_",) if structured_refinement else ()) + + (("mixed_log_tz_head",) if mixed_projection else ()) + + (("joint_localization_",) if spatial_joint2d else ()) + ) + initialization_record = load_model_initialization( + args.init_checkpoint, model, + allowed_missing_prefixes=allowed_missing_prefixes, map_location=device, + require_residual=residual_initialization, + ) + checkpoint_context["initialization_checkpoint"].update({ + "source_step": initialization_record["step"], + "residual_missing_keys": initialization_record["residual_missing_keys"], + "checkpoint_excluded_prefixes": initialization_record[ + "checkpoint_excluded_prefixes" + ], + }) + if mixed_projection: + model.initialize_mixed_log_tz_from_direct_head() + checkpoint_context["initialization_checkpoint"].update({ + "mixed_log_tz_initialization": ( + "first-order log-softplus linearization of frozen direct-z head" + ), + "direct_xyz_teacher_frozen": True, + }) + loss_config = LossConfig(**config.get("loss", {})) + criterion = BimanualLoss(loss_config).to(device) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, + learning_rate=args.learning_rate, + backbone_learning_rate=config.get("protocol", {}).get( + "backbone_learning_rate" + ), + ), + lr=args.learning_rate, + weight_decay=0.05, + ) + excluded_checkpoint_prefixes = checkpoint_excluded_prefixes(model) + start_step = 0 + if args.resume: + start_step = int(load_checkpoint(args.resume, model, optimizer, device)["step"]) + set_scheduled_learning_rate(optimizer, args.learning_rate) + sampling_manifest_record = None + if sampling_mode == "balanced": + sampling_manifest = sampling_config.get("manifest") + if not sampling_manifest: + raise ValueError("balanced sampling requires sampling.manifest") + weights, sampling_manifest_record = load_balanced_sampling_weights( + sampling_manifest, args.manifest, data_config, len(dataset), + ) + batch_sampler = ResumableWeightedBatchSampler( + weights, int(data_config["batch_size"]), seed, start_step, args.max_steps, + include_epoch=photometric_config is not None, + ) + else: + batch_sampler = ResumableRandomBatchSampler( + len(dataset), int(data_config["batch_size"]), seed, start_step, args.max_steps, + include_epoch=photometric_config is not None, + ) + loader_generator = torch.Generator().manual_seed(seed + 10_000_000) + loader = DataLoader( + dataset, batch_sampler=batch_sampler, generator=loader_generator, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + val_loader = None + val_dataset_size = 0 + val_evaluated_samples = 0 + validation_subset_record = None + if args.val_manifest is not None: + val_dataset = H2OCam4Dataset( + args.root, args.val_manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + oracle_crop_enabled=oracle_crop_mode != "none", + ) + val_dataset_size = len(val_dataset) + if args.validation_subset_manifest is not None: + validation_indices, validation_subset_record = load_validation_subset( + args.validation_subset_manifest, args.val_manifest, data_config, len(val_dataset), + ) + expected_batches = math.ceil(len(validation_indices) / int(data_config["batch_size"])) + if args.validation_batches != expected_batches: + raise ValueError( + f"--validation-batches must be {expected_batches} to evaluate the complete fixed subset" + ) + val_evaluated_samples = len(validation_indices) + else: + val_evaluated_samples = min( + len(val_dataset), args.validation_batches * int(data_config["batch_size"]), + ) + validation_generator = torch.Generator().manual_seed(seed + 20_000_000) + validation_indices = torch.randperm( + len(val_dataset), generator=validation_generator, + )[:val_evaluated_samples].tolist() + validation_subset = Subset(val_dataset, validation_indices) + val_loader = DataLoader( + validation_subset, batch_size=int(data_config["batch_size"]), shuffle=False, + generator=torch.Generator().manual_seed(seed + 30_000_000), + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + log_path = args.output_dir / "train_metrics.jsonl" + validation_log_path = args.output_dir / "validation.jsonl" + best_metric_name = "absolute_camera_mpjpe_mm" + best_metric, no_improvement_validations = validation_state_from_log(validation_log_path, best_metric_name) + best_z_metric_name = "translation_z_mae_mm" + best_z_metric, _ = validation_state_from_log(validation_log_path, best_z_metric_name) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + completed_step = start_step + processed_frames = 0 + last_validation_step = -1 + stopped_for_time = False + stopped_for_early_stopping = False + for step, batch in zip(range(start_step, args.max_steps), loader, strict=True): + if args.max_minutes is not None and time.perf_counter() - started >= args.max_minutes * 60: + stopped_for_time = True + break + batch = move_to_device(batch, device) + processed_frames += int(batch["frame_valid"].sum()) + learning_rate = warmup_cosine_learning_rate( + step, lr_schedule_steps, args.learning_rate, min_learning_rate, + args.warmup_steps, + ) + set_scheduled_learning_rate(optimizer, learning_rate) + optimizer.zero_grad(set_to_none=True) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_diagnostics = criterion.translation_diagnostics(prediction, batch) + if not torch.isfinite(losses["total"]): + raise FloatingPointError(f"NaN/Inf loss at step {step}") + losses["total"].backward() + depth_gate_warmup_active = step < args.depth_gate_warmup_steps + if depth_gate_warmup_active: + for name, parameter in model.named_parameters(): + if ".depth_gate." in name: + parameter.grad = None + grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) + if not torch.isfinite(grad_norm): + raise FloatingPointError(f"NaN/Inf gradient at step {step}") + optimizer.step() + completed_step = step + 1 + record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": step + 1, "seed": seed, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "loss_diagnostics": { + key: float(value.detach()) for key, value in loss_diagnostics.items() + }, + "metrics": camera_metrics(prediction, batch), "gradient_norm": float(grad_norm), + "diagnostics": attention_diagnostics(prediction, batch), + "photometric_augmentation": photometric_diagnostics(batch), + "learning_rate": learning_rate, + "depth_gate_warmup_active": depth_gate_warmup_active, + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "frames_per_s": processed_frames / (time.perf_counter() - started), + } + with log_path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(record) + "\n") + if completed_step % args.checkpoint_interval == 0: + save_checkpoint( + args.output_dir / f"step_{completed_step:07d}.pt", model, optimizer, completed_step, + checkpoint_context, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if val_loader is not None and completed_step % args.validation_interval == 0: + validation = run_validation(model, criterion, val_loader, device, dtype, args.validation_batches) + validation_record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": completed_step, + "batches": args.validation_batches, **validation, + } + with validation_log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(validation_record) + "\n") + last_validation_step = completed_step + current_metric = validation["metrics"].get(best_metric_name, float("inf")) + current_z_metric = validation["metrics"].get(best_z_metric_name, float("inf")) + if current_metric < best_metric: + best_metric = current_metric + no_improvement_validations = 0 + save_checkpoint( + args.output_dir / "best.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_metric_name: best_metric}, "checkpoint_role": "best_absolute"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + else: + no_improvement_validations += 1 + if current_z_metric < best_z_metric: + best_z_metric = current_z_metric + save_checkpoint( + args.output_dir / "best_z.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_z_metric_name: best_z_metric}, "checkpoint_role": "best_z"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if args.early_stopping_patience and no_improvement_validations >= args.early_stopping_patience: + stopped_for_early_stopping = True + break + if val_loader is not None and completed_step > 0 and last_validation_step != completed_step: + validation = run_validation(model, criterion, val_loader, device, dtype, args.validation_batches) + validation_record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": completed_step, + "batches": args.validation_batches, **validation, + } + with validation_log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(validation_record) + "\n") + current_metric = validation["metrics"].get(best_metric_name, float("inf")) + current_z_metric = validation["metrics"].get(best_z_metric_name, float("inf")) + if current_metric < best_metric: + best_metric = current_metric + save_checkpoint( + args.output_dir / "best.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_metric_name: best_metric}, "checkpoint_role": "best_absolute"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if current_z_metric < best_z_metric: + best_z_metric = current_z_metric + save_checkpoint( + args.output_dir / "best_z.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_z_metric_name: best_z_metric}, "checkpoint_role": "best_z"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + final_checkpoint = args.output_dir / f"step_{completed_step:07d}_final.pt" + save_checkpoint( + final_checkpoint, model, optimizer, completed_step, + {**checkpoint_context, "checkpoint_role": "final"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + summary = { + "status": ( + "stopped_early_validation" if stopped_for_early_stopping else + "stopped_time_budget" if stopped_for_time else "completed" + ), + "config": config, "model_config": asdict(model_config), "loss_config": asdict(loss_config), + "seed": seed, "dataset_clips": len(dataset), "validation_manifest": str(args.val_manifest) if args.val_manifest else None, + "validation_dataset_clips": val_dataset_size, "validation_evaluated_samples": val_evaluated_samples, + "validation_sampling": ( + validation_subset_record.get("version") if validation_subset_record is not None else + "fixed_seed_uniform_random_subset_v1" if val_loader is not None else None + ), + "validation_subset_manifest": str(args.validation_subset_manifest.resolve()) if args.validation_subset_manifest else None, + "run_provenance": str(provenance_path), + "initialization": checkpoint_context["initialization_checkpoint"], + "start_step": start_step, "completed_step": completed_step, "requested_max_steps": args.max_steps, + "elapsed_minutes": (time.perf_counter() - started) / 60, + "sampler": checkpoint_context["sampler"], + "sampling_manifest": ( + str(Path(sampling_config["manifest"]).resolve()) + if sampling_manifest_record is not None else None + ), + "learning_rate_schedule": { + "name": "warmup_cosine_clamped", "base_lr": args.learning_rate, + "min_lr": min_learning_rate, "warmup_steps": args.warmup_steps, + "total_steps": lr_schedule_steps, + "training_max_steps": args.max_steps, + "backbone_lr_scale": next( + ( + float(group["lr_scale"]) + for group in optimizer.param_groups + if group.get("group_name") == "dinov3_backbone" + ), + None, + ), + "deterministic_training": deterministic_training, + }, + "best_validation": {best_metric_name: best_metric if math.isfinite(best_metric) else None}, + "best_z_validation": {best_z_metric_name: best_z_metric if math.isfinite(best_z_metric) else None}, + "best_z_checkpoint": str(args.output_dir / "best_z.pt") if (args.output_dir / "best_z.pt").is_file() else None, + "early_stopping_patience": args.early_stopping_patience, + "validation_checks_without_improvement": no_improvement_validations, + "best_checkpoint": str(args.output_dir / "best.pt") if (args.output_dir / "best.pt").is_file() else None, + "final_checkpoint": str(final_checkpoint), "git_status": git_state(), + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "frames_per_s": processed_frames / max(time.perf_counter() - started, 1e-6), + "precision": config["precision"], "gpu": torch.cuda.get_device_name(device), + "trainable_parameters": sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad), + "frozen_parameters": sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad), + } + (args.output_dir / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/scripts/train_phase7_external.py b/home/wuyifan/EgoNet_train_20261008/scripts/train_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..fba61b4edae8c4636a2bb46343fa410e3885120a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/scripts/train_phase7_external.py @@ -0,0 +1,1316 @@ +#!/usr/bin/env python3 +"""External-only Phase 7 training over hash-bound unified clip caches.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import copy +from dataclasses import asdict +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import random +import shlex +import socket +import subprocess +import sys +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import ( + CachedUnifiedClipDataset, + ResumableMixtureBatchSampler, + UnifiedConcatDataset, + collate_h2o_clips, +) +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint, save_checkpoint +from foundation_hand.training.metrics import camera_metrics +from foundation_hand.training.optimizer import ( + clear_staged_later_gradients, + checkpoint_excluded_prefixes, + optimizer_parameter_groups, + set_scheduled_learning_rate, + set_staged_parameter_group_phase, + staged_optimizer_parameter_groups, +) +from foundation_hand.training.schedule import warmup_cosine_learning_rate +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +PHASE9_H2O_TRAIN_MANIFESTS = { + "full_data_640": Path( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "h2o_official_train7000_v1/cache_manifest.jsonl" + ), + "resolution_896x512": Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/h2o_train7000/cache_manifest.jsonl" + ), +} +PHASE9_H2O_TRAIN_MANIFESTS.update({ + "shared_augmentation_640": PHASE9_H2O_TRAIN_MANIFESTS["full_data_640"], + "shared_augmentation_896x512": PHASE9_H2O_TRAIN_MANIFESTS[ + "resolution_896x512" + ], +}) +PHASE9_H2O_FOLD_ROOTS = { + "full_data_640": Path("artifacts/phase9/manifests/h2o_multifold_v1"), + "resolution_896x512": Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "manifests/h2o_multifold_v1" + ), +} +PHASE9_H2O_FOLD_ROOTS.update({ + "shared_augmentation_640": PHASE9_H2O_FOLD_ROOTS["full_data_640"], + "shared_augmentation_896x512": PHASE9_H2O_FOLD_ROOTS[ + "resolution_896x512" + ], +}) +PHASE9_DATASETS = ("H2O", "HOT3D", "HOI4D", "ARCTIC") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def git_output(*arguments: str) -> str: + return subprocess.run( + ["git", *arguments], text=True, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=False, + ).stdout.strip() + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def assert_physical_gpu_idle(physical_gpu_id: int) -> None: + """Fail before CUDA allocation if another compute process owns the GPU.""" + + inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ).stdout.splitlines() + mapping = { + int(line.split(",", 1)[0].strip()): line.split(",", 1)[1].strip() + for line in inventory if line.strip() + } + if physical_gpu_id not in mapping: + raise RuntimeError(f"physical GPU {physical_gpu_id} is not present") + compute = subprocess.run( + [ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid,process_name", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ).stdout.splitlines() + owners = [line for line in compute if line.split(",", 1)[0].strip() == mapping[physical_gpu_id]] + if owners: + raise RuntimeError( + f"physical GPU {physical_gpu_id} is not idle: " + "; ".join(owners) + ) + + +def claim_physical_gpu(physical_gpu_id: int) -> bool: + """Atomically reserve an idle GPU across FoundationHand queue processes.""" + + path = Path(f"/tmp/foundation_hand_{os.getuid()}_gpu{physical_gpu_id}.claim") + owner = os.getpid() + while True: + try: + descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + try: + recorded = int(path.read_text(encoding="ascii").strip()) + except (OSError, ValueError): + recorded = -1 + if recorded == owner: + return True + try: + os.kill(recorded, 0) + except (OSError, ValueError): + try: + path.unlink() + except FileNotFoundError: + pass + continue + return False + else: + with os.fdopen(descriptor, "w", encoding="ascii") as handle: + handle.write(f"{owner}\n") + return True + + +def release_physical_gpu_claim(physical_gpu_id: int) -> None: + """Release a claim owned by this process after a failed stability check.""" + + path = Path(f"/tmp/foundation_hand_{os.getuid()}_gpu{physical_gpu_id}.claim") + try: + if int(path.read_text(encoding="ascii").strip()) == os.getpid(): + path.unlink() + except (FileNotFoundError, OSError, ValueError): + return + + +def contains_h2o(value: str) -> bool: + return any(part.lower() == "h2o" for part in Path(value).parts) + + +def load_cache_rows(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def validate_external_contract(config: dict[str, Any], config_path: Path) -> list[str]: + errors: list[str] = [] + experiment = config.get("experiment", {}) + if int(experiment.get("phase", -1)) not in {7, 8}: + errors.append("external-only experiment.phase must be 7 or 8") + if experiment.get("branch") != "external_only": + errors.append("experiment.branch must be external_only") + if experiment.get("uses_h2o_training_data") is not False: + errors.append("uses_h2o_training_data must be explicitly false") + if config.get("model", {}).get("dinov3_trainable_last_blocks", 0) != 0: + errors.append("Phase 7 external screen requires frozen DINO") + if float(config.get("model", {}).get("modality_dropout_prob", 0.0)) != 0.0: + errors.append("model modality dropout is frame-wise; use source clip dropout instead") + sources = config.get("data", {}).get("sources", []) + if not sources: + errors.append("at least one external source is required") + source_ids: set[str] = set() + for source in sources: + name = str(source.get("dataset", "")) + source_id = str(source.get("source_id", name)) + if source_id in source_ids: + errors.append(f"duplicate external source_id: {source_id}") + source_ids.add(source_id) + manifest = str(source.get("cache_manifest", "")) + if name.upper() not in {"HOT3D", "HOI4D", "ARCTIC"}: + errors.append(f"unsupported external source: {name}") + if contains_h2o(manifest) or name.upper() == "H2O": + errors.append(f"H2O source forbidden in external-only training: {manifest}") + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"source weight must be positive: {name}") + if name.upper() == "HOT3D" and float(source.get("K_input_dropout", -1)) != 0.3: + errors.append("HOT3D K_input_dropout must equal frozen clip-level 0.3") + if contains_h2o(str(config_path)): + errors.append("external-only config path must not be under an H2O directory") + if "initialization_checkpoint" in experiment: + errors.append("external-only configs may not define initialization_checkpoint") + return errors + + +def validate_adaptation_contract(config: dict[str, Any]) -> list[str]: + errors: list[str] = [] + experiment = config.get("experiment", {}) + if int(experiment.get("phase", -1)) not in {7, 8}: + errors.append("adaptation experiment.phase must be 7 or 8") + if experiment.get("branch") != "h2o_adaptation": + errors.append("experiment.branch must be h2o_adaptation") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("H2O adaptation must explicitly use H2O training data") + expected_init = str(experiment.get("initialization_checkpoint_sha256", "")) + if len(expected_init) != 64: + errors.append("adaptation requires a frozen initialization checkpoint SHA256") + if config.get("model", {}).get("dinov3_trainable_last_blocks", 0) != 0: + errors.append("adaptation requires frozen DINO") + if float(config.get("model", {}).get("modality_dropout_prob", 0.0)) != 0.0: + errors.append("use source clip dropout instead of frame-wise model dropout") + sources = config.get("data", {}).get("sources", []) + if not sources or not any(str(source.get("dataset", "")).upper() == "H2O" for source in sources): + errors.append("adaptation requires an H2O official-train source") + allowed = {"H2O", "HOT3D", "HOI4D", "ARCTIC"} + source_ids: set[str] = set() + for source in sources: + name = str(source.get("dataset", "")).upper() + source_id = str(source.get("source_id", name)) + if source_id in source_ids: + errors.append(f"duplicate adaptation source_id: {source_id}") + source_ids.add(source_id) + role = str(source.get("split_role", "")) + if name not in allowed: + errors.append(f"unsupported adaptation source: {name}") + if name == "H2O" and role != "official_train": + errors.append("H2O adaptation source must be official_train") + if name == "H2O" and Path(str(source.get("cache_manifest", ""))).name != "train_fit.jsonl": + errors.append("H2O adaptation training requires frozen train_fit.jsonl") + if name != "H2O" and role != "external_train": + errors.append(f"external replay source must be external_train: {name}") + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"source weight must be positive: {name}") + if name == "HOT3D" and float(source.get("K_input_dropout", -1)) != 0.3: + errors.append("HOT3D replay K_input_dropout must equal 0.3") + if sources and not math.isclose( + sum(float(source.get("weight", 0.0)) for source in sources), 1.0, + rel_tol=0.0, abs_tol=1e-8, + ): + errors.append("adaptation source weights must sum to one") + validation_sources = config.get("data", {}).get("validation_sources", []) + if len(validation_sources) != 1: + errors.append("adaptation requires exactly one H2O train-group-heldout source") + else: + validation = validation_sources[0] + if ( + str(validation.get("dataset", "")).upper() != "H2O" + or validation.get("split_role") != "train_group_heldout" + or Path(str(validation.get("cache_manifest", ""))).name + != "train_group_heldout.jsonl" + ): + errors.append("adaptation validation must be frozen H2O train_group_heldout.jsonl") + staged = config.get("protocol", {}).get("staged_adaptation") + if staged is not None: + prefixes = staged.get("initial_trainable_prefixes", []) + unfreeze_step = int(staged.get("unfreeze_step", -1)) + scale = float(staged.get("unfrozen_learning_rate_scale", -1.0)) + if not isinstance(prefixes, list) or not prefixes or not all( + isinstance(prefix, str) and prefix for prefix in prefixes + ): + errors.append("staged adaptation requires nonempty trainable prefixes") + if not 0 < unfreeze_step < int(config.get("protocol", {}).get("max_steps", 0)): + errors.append("staged adaptation unfreeze_step must be within training horizon") + if not 0.0 < scale <= 1.0: + errors.append("staged adaptation LR scale must be in (0, 1]") + return errors + + +def validate_h2o_neutral_control_contract(config: dict[str, Any]) -> list[str]: + """Validate the random-task-head H2O control without faking an init checkpoint.""" + + experiment = config.get("experiment", {}) + errors: list[str] = [] + if int(experiment.get("phase", -1)) != 8: + errors.append("neutral H2O control must be registered in Phase 8") + if experiment.get("branch") != "h2o_neutral_control": + errors.append("neutral H2O control branch is invalid") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("neutral H2O control must explicitly use H2O training data") + if experiment.get("neutral_task_heads") is not True: + errors.append("neutral H2O control must explicitly declare neutral_task_heads=true") + if any(key.startswith("initialization_checkpoint") for key in experiment): + errors.append("neutral H2O control forbids initialization checkpoint fields") + adaptation_view = copy.deepcopy(config) + adaptation_view["experiment"].update({ + "phase": 7, + "branch": "h2o_adaptation", + "initialization_checkpoint_sha256": "0" * 64, + }) + errors.extend(validate_adaptation_contract(adaptation_view)) + sources = config.get("data", {}).get("sources", []) + if len(sources) != 1 or str(sources[0].get("dataset", "")).upper() != "H2O": + errors.append("neutral H2O control must use only H2O official train") + return errors + + +def validate_phase9_unified_contract( + config: dict[str, Any], config_path: Path, +) -> list[str]: + """Validate the shared four-source Phase 9 direct-XYZ training contract.""" + + errors: list[str] = [] + experiment = config.get("experiment", {}) + specialization = experiment.get("data_only_amendment") == "arctic_h2o_s9_v2_20260917" + data = config.get("data", {}) + model = config.get("model", {}) + loss = config.get("loss", {}) + if int(experiment.get("phase", -1)) != 9: + errors.append("Phase 9 unified training requires experiment.phase=9") + if experiment.get("branch") != "phase9_unified": + errors.append("Phase 9 unified training requires branch=phase9_unified") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("Phase 9 unified training must declare H2O training use") + if experiment.get("h2o_official_validation_used_for_selection") is not False: + errors.append("H2O official validation must be excluded from selection") + if experiment.get("official_test_used") is not False: + errors.append("official test must be explicitly unused") + if len(str(experiment.get("initialization_checkpoint_sha256", ""))) != 64: + errors.append("Phase 9 requires a hash-bound external initialization") + if "phase9" not in {part.lower() for part in config_path.parts}: + errors.append("Phase 9 unified config must live under configs/phase9") + + phase9_stage = str(experiment.get("phase9_stage", "full_data_640")) + last2_stage = phase9_stage in {"last2_5e7", "last2_1e6"} + expected_model = { + "decoder_mode": "alternating", + "use_temporal": True, + "translation_parameterization": "direct_xyz", + "dinov3_trainable_last_blocks": 2 if last2_stage else 0, + "temporal_attention_mode": "bidirectional", + } + for key, expected in expected_model.items(): + if model.get(key) != expected: + errors.append(f"Phase 9 frozen model contract requires {key}={expected}") + if not math.isclose( + float(loss.get("joint3d_root_relative", 0.0)), + 10.0, + rel_tol=0.0, + abs_tol=1e-8, + ): + errors.append( + "Phase 9 frozen loss contract requires joint3d_root_relative=10.0" + ) + resolution = list(data.get("resolution_hw", [])) + if last2_stage: + expected_resolution = list(experiment.get("last2_resolution_hw", [])) + if expected_resolution not in ([368, 640], [512, 896]): + errors.append("Phase 9 last-2 requires a frozen 640 or 896 resolution") + h2o_contract_stage = ( + "resolution_896x512" + if expected_resolution == [512, 896] + else "full_data_640" + ) + else: + expected_resolution = { + "full_data_640": [368, 640], + "resolution_896x512": [512, 896], + "shared_augmentation_640": [368, 640], + "shared_augmentation_896x512": [512, 896], + }.get(phase9_stage) + h2o_contract_stage = phase9_stage + if expected_resolution is None: + errors.append(f"unsupported Phase 9 stage contract: {phase9_stage}") + elif resolution != expected_resolution or int(data.get("T", -1)) != 8: + errors.append( + f"Phase 9 {phase9_stage} contract requires " + f"{expected_resolution[1]}x{expected_resolution[0]} and T=8" + ) + shared_augmentation_stage = phase9_stage in { + "shared_augmentation_640", "shared_augmentation_896x512", + } or (last2_stage and experiment.get("last2_shared_augmentation") is True) + geometry = data.get("geometry_augmentation", {}) + expected_geometry = { + "enabled": True, "probability": 0.8, + "scale_min": 0.9, "scale_max": 1.1, + "translation_fraction": 0.05, + } + if shared_augmentation_stage: + if geometry != expected_geometry: + errors.append("Phase 9 shared geometry augmentation parameters differ") + elif bool(geometry.get("enabled", False)): + errors.append("Phase 9 shared geometry augmentation is not yet admitted") + if last2_stage: + if model.get("encoder") != "dinov3": + errors.append("Phase 9 last-2 requires the shared DINOv3 encoder") + if model.get("dinov3_model", "dinov3_vitb16") != "dinov3_vitb16": + errors.append("Phase 9 last-2 admits DINO Base only") + expected_backbone_lr = 5e-7 if phase9_stage == "last2_5e7" else 1e-6 + actual_backbone_lr = config.get("protocol", {}).get( + "backbone_learning_rate" + ) + if actual_backbone_lr is None or not math.isclose( + float(actual_backbone_lr), expected_backbone_lr, + rel_tol=0.0, abs_tol=1e-15, + ): + errors.append( + f"Phase 9 {phase9_stage} requires backbone learning rate " + f"{expected_backbone_lr}" + ) + elif config.get("protocol", {}).get("backbone_learning_rate") is not None: + errors.append("Phase 9 frozen-DINO stages forbid backbone learning rate") + if int(config.get("seed", -1)) != 20260717: + errors.append("Phase 9 primary seed must be 20260717") + + sources = data.get("sources", []) + names = [str(source.get("dataset", "")).upper() for source in sources] + if specialization: + if len(sources) != 2 or set(names) != {"H2O", "ARCTIC"}: + errors.append("Specialization requires exactly H2O and ARCTIC") + weights = {source["dataset"]: float(source["weight"]) for source in sources} + if not any(all(math.isclose(weights.get(k, -1), v, abs_tol=1e-10) + for k, v in pair.items()) + for pair in ({"H2O": 0.5, "ARCTIC": 0.5}, + {"H2O": 1 / 3, "ARCTIC": 2 / 3})): + errors.append("Unregistered specialization ratio") + if phase9_stage != "last2_1e6": + errors.append("Specialization must retain last2_1e6") + parent_config = Path(experiment["parent_config"]) + if sha256(parent_config) != experiment["parent_config_sha256"]: + errors.append("Parent configuration hash differs") + parent = yaml.safe_load(parent_config.read_text()) + for section in ("model", "loss", "precision"): + if config[section] != parent[section]: + errors.append(f"Specialization changed parent {section}") + expected_protocol = copy.deepcopy(parent["protocol"]) + for milestone in expected_protocol.get("source_exposure_milestones", []): + milestone["minimum_batches"] = { + k: v for k, v in milestone["minimum_batches"].items() + if k in {"H2O", "ARCTIC"} + } + if config["protocol"] != expected_protocol: + errors.append("Data-only experiment must preserve the complete Stage 9 protocol") + if {k: v for k, v in data.items() if k != "sources"} != { + k: v for k, v in parent["data"].items() if k != "sources" + }: + errors.append("Data-only experiment changed augmentation, batch size, or sequence settings") + if experiment["initialization_checkpoint_sha256"] != parent["experiment"]["initialization_checkpoint_sha256"]: + errors.append("Data-only experiment must use the same E40 initialization as Stage 9") + if config["seed"] != parent["seed"]: + errors.append("Data-only experiment changed the Stage 9 seed") + for source in sources: + original = next((s for s in parent["data"]["sources"] + if s["dataset"] == source["dataset"]), None) + if original is None: + errors.append("Unknown source in data-only experiment") + continue + if {k: v for k, v in source.items() if k != "weight"} != { + k: v for k, v in original.items() if k != "weight" + }: + errors.append(f"Specialization changed source contract: {source['dataset']}") + elif len(sources) != 4 or set(names) != set(PHASE9_DATASETS): + errors.append("Phase 9 unified training requires exactly H2O/HOT3D/HOI4D/ARCTIC") + source_ids = [str(source.get("source_id", source.get("dataset", ""))) for source in sources] + if len(set(source_ids)) != len(source_ids): + errors.append("Phase 9 sampling source IDs must be unique") + if sources and not math.isclose( + sum(float(source.get("weight", 0.0)) for source in sources), + 1.0, rel_tol=0.0, abs_tol=1e-8, + ): + errors.append("Phase 9 source weights must sum to one") + for source, name in zip(sources, names): + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"Phase 9 source weight must be positive: {name}") + expected_role = "official_train" if name == "H2O" else "external_train" + if source.get("split_role") != expected_role: + errors.append(f"Phase 9 {name} split role must be {expected_role}") + expected_k_dropout = 0.3 if name == "HOT3D" else 0.0 + if float(source.get("K_input_dropout", -1.0)) != expected_k_dropout: + errors.append(f"Phase 9 {name} K_input_dropout must equal {expected_k_dropout}") + corruption_probability = float( + source.get("depth_corruption_probability", 0.0) + ) + expected_corruption_probability = ( + 0.3 if shared_augmentation_stage and name in {"H2O", "HOI4D"} + else 0.0 + ) + if not math.isclose( + corruption_probability, expected_corruption_probability, + rel_tol=0.0, abs_tol=1e-12, + ): + errors.append( + f"Phase 9 {name} depth corruption probability must equal " + f"{expected_corruption_probability}" + ) + + selection_fold = experiment.get("h2o_selection_fold") + h2o_sources = [source for source, name in zip(sources, names) if name == "H2O"] + validation_sources = data.get("validation_sources", []) + if h2o_sources: + h2o_manifest = Path(str(h2o_sources[0].get("cache_manifest", ""))).resolve() + expected_h2o_manifest = PHASE9_H2O_TRAIN_MANIFESTS.get( + h2o_contract_stage + ) + fold_root = PHASE9_H2O_FOLD_ROOTS.get(h2o_contract_stage) + if selection_fold is None: + if ( + expected_h2o_manifest is None + or h2o_manifest != expected_h2o_manifest.resolve() + ): + errors.append( + "Phase 9 full run must use its stage-matched frozen H2O train cache" + ) + if validation_sources: + errors.append("Phase 9 full run cannot validate on leaked train subsets") + else: + if fold_root is None: + errors.append("Phase 9 fold stage has no admitted manifest root") + fold_root = Path("/__invalid_phase9_fold_root__") + expected_train = (fold_root.resolve() / f"{selection_fold}_train.jsonl") + expected_heldout = ( + fold_root.resolve() / f"{selection_fold}_heldout.jsonl" + ) + if h2o_manifest != expected_train: + errors.append("Phase 9 fold run H2O train manifest does not match its fold") + if len(validation_sources) != 1: + errors.append("Phase 9 fold run requires exactly its H2O heldout source") + elif ( + str(validation_sources[0].get("dataset", "")).upper() != "H2O" + or Path(str(validation_sources[0].get("cache_manifest", ""))).resolve() + != expected_heldout + ): + errors.append("Phase 9 fold validation manifest does not match its fold") + + valid_source_ids = set(source_ids) + milestone_ids: set[str] = set() + for milestone in config.get("protocol", {}).get("source_exposure_milestones", []): + milestone_id = str(milestone.get("id", "")) + minimum = milestone.get("minimum_batches", {}) + if not milestone_id or milestone_id in milestone_ids: + errors.append("Phase 9 exposure milestone IDs must be nonempty and unique") + milestone_ids.add(milestone_id) + if not minimum or not set(minimum).issubset(valid_source_ids): + errors.append(f"invalid source keys in exposure milestone: {milestone_id}") + if any(int(value) <= 0 for value in minimum.values()): + errors.append(f"exposure milestone counts must be positive: {milestone_id}") + return errors + + +def reached_source_exposure_milestones( + milestones: list[dict[str, Any]], + counts: Counter[str], + completed: set[str], +) -> list[str]: + reached = [] + for milestone in milestones: + milestone_id = str(milestone["id"]) + if milestone_id in completed: + continue + minimum = milestone["minimum_batches"] + if all(counts[source_id] >= int(target) for source_id, target in minimum.items()): + reached.append(milestone_id) + return reached + + +def checkpoint_context_with_exposure( + context: dict[str, Any], + source_batches: Counter[str], + source_frames: Counter[str], + depth_conditions: Counter[str], + completed_milestones: set[str], +) -> dict[str, Any]: + return { + **context, + "source_exposure_batches": dict(source_batches), + "source_exposure_frames": dict(source_frames), + "depth_input_condition_frames": dict(depth_conditions), + "completed_source_exposure_milestones": sorted(completed_milestones), + } + + +def validate_cache_manifest( + path: Path, expected_dataset: str, allow_h2o: bool = False, +) -> tuple[list[dict], list[str]]: + errors: list[str] = [] + if not path.is_file(): + return [], [f"cache manifest missing: {path}"] + rows = load_cache_rows(path) + if not rows: + errors.append(f"cache manifest is empty: {path}") + for index, row in enumerate(rows): + dataset = str(row.get("dataset_id", "")) + cache_path = Path(str(row.get("cache_path", ""))) + if dataset.upper() != expected_dataset.upper(): + errors.append(f"row {index} dataset mismatch: {dataset} != {expected_dataset}") + if not allow_h2o and ( + dataset.upper() == "H2O" or contains_h2o(str(cache_path)) + ): + errors.append(f"row {index} contains forbidden H2O data") + if not cache_path.is_file(): + errors.append(f"row {index} cache missing: {cache_path}") + if not row.get("cache_sha256"): + errors.append(f"row {index} lacks cache_sha256") + if len(errors) >= 20: + errors.append("additional cache errors omitted") + break + return rows, errors + + +def write_provenance( + output: Path, + config_path: Path, + config: dict[str, Any], + source_hashes: dict[str, str], + resume: Path | None, + initialization_checkpoint: Path | None = None, +) -> dict[str, Any]: + inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid,name,memory.total,memory.used", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, + ).stdout.strip().splitlines() + record = { + "timestamp_utc": utc_now(), + "hostname": socket.gethostname(), + "git_commit": git_output("rev-parse", "HEAD"), + "git_status": git_output("status", "--short"), + "command_argv": [sys.executable, *sys.argv], + "command_shell": shlex.join([sys.executable, *sys.argv]), + "working_directory": str(Path.cwd()), + "config_path": str(config_path.resolve()), + "config_sha256": sha256(config_path), + "config": config, + "source_manifest_sha256": source_hashes, + "resume_checkpoint": str(resume.resolve()) if resume else None, + "cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "gpu_inventory": inventory, + "python": sys.version, + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "external_only_neutral_heads": ( + config.get("experiment", {}).get("branch") == "external_only" + ), + "neutral_task_heads": ( + config.get("experiment", {}).get("branch") + in {"external_only", "h2o_neutral_control"} + ), + "initialization_checkpoint": ( + { + "path": str(initialization_checkpoint.resolve()), + "sha256": sha256(initialization_checkpoint), + } + if initialization_checkpoint is not None else None + ), + "h2o_initialization_used": False, + "h2o_training_data_used": bool( + config.get("experiment", {}).get("uses_h2o_training_data", False) + ), + "official_test_used": False, + } + name = "run_provenance.json" if resume is None else f"resume_provenance_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json" + (output / name).write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + return record + + +def source_batch_counts(batch: dict[str, Any]) -> dict[str, int]: + values = batch.get("sampling_source_id", batch.get("dataset_id", [])) + if isinstance(values, str): + values = [values] + return dict(Counter(str(value) for value in values)) + + +def source_frame_counts(batch: dict[str, Any]) -> dict[str, int]: + datasets = batch.get("sampling_source_id", batch.get("dataset_id", [])) + if isinstance(datasets, str): + datasets = [datasets] + valid = batch["frame_valid"].detach().cpu() + counts: Counter[str] = Counter() + for index, dataset in enumerate(datasets): + counts[str(dataset)] += int(valid[index].sum()) + return dict(counts) + + +def depth_input_condition_counts(batch: dict[str, Any]) -> dict[str, int]: + codes = batch.get("depth_input_condition_code") + if codes is None: + return {} + names = {0: "source_unavailable", 1: "rgb_k", 2: "clean_rgb_d_k"} + names.update({3 + index: f"corrupted_{name}" for index, name in enumerate(DEPTH_CORRUPTIONS)}) + values = codes.detach().cpu().reshape(-1).tolist() + return dict(Counter(names.get(int(value), f"unknown_{int(value)}") for value in values)) + + +def gpu_telemetry(physical_gpu_id: int) -> dict[str, float] | None: + result = subprocess.run( + [ + "nvidia-smi", f"--id={physical_gpu_id}", + "--query-gpu=utilization.gpu,memory.used", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + if result.returncode != 0 or not result.stdout.strip(): + return None + utilization, memory = result.stdout.strip().split(",")[:2] + return { + "gpu_utilization_percent": float(utilization.strip()), + "gpu_memory_used_mib": float(memory.strip()), + } + + +def run_validation( + model: BimanualReconstructionModel, + criterion: BimanualLoss, + loaders: dict[str, DataLoader], + device: torch.device, + dtype: torch.dtype, + max_batches: int, +) -> dict[str, Any]: + was_training = model.training + model.eval() + sources: dict[str, Any] = {} + with torch.inference_mode(): + for name, loader in loaders.items(): + metric_rows: list[dict[str, float]] = [] + loss_rows: list[dict[str, float]] = [] + for batch_index, batch in enumerate(loader): + if batch_index >= max_batches: + break + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + metric_rows.append(camera_metrics(prediction, batch)) + loss_rows.append({key: float(value) for key, value in losses.items()}) + sources[name] = { + "batches": len(metric_rows), + "metrics": { + key: float(np.mean([row[key] for row in metric_rows if math.isfinite(row.get(key, math.nan))])) + for key in sorted({key for row in metric_rows for key in row}) + if any(math.isfinite(row.get(key, math.nan)) for row in metric_rows) + }, + "losses": { + key: float(np.mean([row[key] for row in loss_rows if math.isfinite(row.get(key, math.nan))])) + for key in sorted({key for row in loss_rows for key in row}) + if any(math.isfinite(row.get(key, math.nan)) for row in loss_rows) + }, + } + model.train(was_training) + absolute = [ + record["metrics"]["absolute_camera_mpjpe_mm"] + for record in sources.values() + if "absolute_camera_mpjpe_mm" in record["metrics"] + ] + return { + "sources": sources, + "macro_absolute_camera_mpjpe_mm": float(np.mean(absolute)) if absolute else None, + } + + +def build_datasets( + config: dict[str, Any], seed: int, allow_h2o: bool = False, +) -> tuple[UnifiedConcatDataset, list[int], list[float], dict[str, str]]: + data = config["data"] + expected_resolution_hw = tuple(int(value) for value in data["resolution_hw"]) + datasets = [] + sizes: list[int] = [] + weights: list[float] = [] + hashes: dict[str, str] = {} + for source in data["sources"]: + manifest = Path(source["cache_manifest"]).resolve() + _, errors = validate_cache_manifest( + manifest, str(source["dataset"]), allow_h2o=allow_h2o, + ) + if errors: + raise ValueError("; ".join(errors)) + source_id = str(source.get("source_id", source["dataset"])) + if source_id in hashes: + raise ValueError(f"duplicate training source_id: {source_id}") + dataset = CachedUnifiedClipDataset( + manifest, + K_input_dropout=float(source.get("K_input_dropout", 0.0)), + dropout_seed=seed, + photometric_augmentation=data.get("photometric_augmentation"), + depth_input_dropout=float(source.get("depth_input_dropout", 0.0)), + depth_corruption_probability=float( + source.get("depth_corruption_probability", 0.0) + ), + joint3d_root_relative_scope=str( + source.get("joint3d_root_relative_scope", "auto") + ), + source_id=source_id, + expected_resolution_hw=expected_resolution_hw, + geometry_augmentation=data.get("geometry_augmentation"), + ) + datasets.append(dataset) + sizes.append(len(dataset)) + weights.append(float(source["weight"])) + hashes[source_id] = sha256(manifest) + return UnifiedConcatDataset(datasets), sizes, weights, hashes + + +def build_validation_loaders( + config: dict[str, Any], seed: int, batch_size: int, workers: int, + allow_h2o: bool = False, +) -> dict[str, DataLoader]: + loaders: dict[str, DataLoader] = {} + expected_resolution_hw = tuple( + int(value) for value in config["data"]["resolution_hw"] + ) + for source in config.get("data", {}).get("validation_sources", []): + name = str(source.get("source_id", source["dataset"])) + manifest = Path(source["cache_manifest"]).resolve() + _, errors = validate_cache_manifest( + manifest, str(source["dataset"]), allow_h2o=allow_h2o, + ) + if errors: + raise ValueError("; ".join(errors)) + dataset = CachedUnifiedClipDataset( + manifest, + K_input_dropout=float(source.get("K_input_dropout", 0.0)), + dropout_seed=seed, + joint3d_root_relative_scope=str( + source.get("joint3d_root_relative_scope", "auto") + ), + source_id=str(source.get("source_id", source["dataset"])), + expected_resolution_hw=expected_resolution_hw, + ) + loaders[name] = DataLoader( + dataset, batch_size=batch_size, shuffle=False, num_workers=workers, + persistent_workers=workers > 0, collate_fn=collate_h2o_clips, + pin_memory=True, + ) + return loaders + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument( + "--allow-physical-gpus-4-5", action="store_true", + help="Explicit resource override; default preserves the historical GPU0-3 contract.", + ) + parser.add_argument("--stop-after-step", type=int) + parser.add_argument( + "--allow-schedule-tail", action="store_true", + help="Allow external-only exact resume beyond max_steps at the clamped minimum LR.", + ) + args = parser.parse_args() + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + branch = str(config.get("experiment", {}).get("branch", "")) + if branch == "external_only": + errors = validate_external_contract(config, args.config) + if args.init_checkpoint is not None: + errors.append("external-only training forbids checkpoint initialization") + elif branch == "h2o_adaptation": + errors = validate_adaptation_contract(config) + if args.resume is None and args.init_checkpoint is None: + errors.append("new H2O adaptation requires --init-checkpoint") + if args.resume is not None and args.init_checkpoint is not None: + errors.append("--resume and --init-checkpoint are mutually exclusive") + elif branch == "h2o_neutral_control": + errors = validate_h2o_neutral_control_contract(config) + if args.init_checkpoint is not None: + errors.append("neutral H2O control forbids --init-checkpoint") + elif branch == "phase9_unified": + errors = validate_phase9_unified_contract(config, args.config) + if args.resume is None and args.init_checkpoint is None: + errors.append("new Phase 9 unified training requires --init-checkpoint") + if args.resume is not None and args.init_checkpoint is not None: + errors.append("--resume and --init-checkpoint are mutually exclusive") + else: + errors = [f"unsupported Phase 7 training branch: {branch}"] + if errors: + parser.error("; ".join(errors)) + if args.init_checkpoint is not None: + if not args.init_checkpoint.is_file(): + parser.error(f"initialization checkpoint missing: {args.init_checkpoint}") + expected = config["experiment"]["initialization_checkpoint_sha256"] + actual = sha256(args.init_checkpoint) + if actual != expected: + parser.error(f"initialization checkpoint SHA256 mismatch: {actual} != {expected}") + if args.output_dir.exists() and any(args.output_dir.iterdir()) and args.resume is None: + parser.error("--output-dir must be new or empty unless --resume is supplied") + visible = os.environ.get("CUDA_VISIBLE_DEVICES") + if visible != str(args.physical_gpu_id): + parser.error( + "CUDA_VISIBLE_DEVICES must name exactly --physical-gpu-id for auditable launch" + ) + allowed_physical_gpus = {0, 1, 2, 3} + if args.allow_physical_gpus_4_5: + allowed_physical_gpus.update((4, 5)) + if args.physical_gpu_id not in allowed_physical_gpus: + parser.error("Phase 7 may use only physical GPUs 0-3; GPU4-5 are reserved") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + protocol = config["protocol"] + max_steps = int(protocol["max_steps"]) + run_end_step = max_steps if args.stop_after_step is None else int(args.stop_after_step) + checkpoint_interval = int(protocol["checkpoint_interval"]) + validation_interval = int(protocol["validation_interval"]) + validation_batches = int(protocol["validation_batches"]) + telemetry_interval = int(protocol.get("telemetry_interval", 100)) + workers = int(protocol["num_workers"]) + batch_size = int(config["data"]["batch_size"]) + seed = int(config["seed"]) + if min(max_steps, checkpoint_interval, validation_interval, validation_batches, telemetry_interval) <= 0: + parser.error("step, checkpoint, and validation values must be positive") + if run_end_step <= 0: + parser.error("--stop-after-step must be positive") + if run_end_step > max_steps and not args.allow_schedule_tail: + parser.error("--stop-after-step exceeds protocol.max_steps without --allow-schedule-tail") + if args.allow_schedule_tail and branch != "external_only": + parser.error("--allow-schedule-tail is restricted to external-only training") + + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + allow_h2o = branch in { + "h2o_adaptation", "h2o_neutral_control", "phase9_unified", + } + train_dataset, source_sizes, source_weights, source_hashes = build_datasets( + config, seed, allow_h2o=allow_h2o, + ) + validation_loaders = build_validation_loaders( + config, seed, batch_size, workers, allow_h2o=allow_h2o, + ) + assets = config["assets"] + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + device = torch.device("cuda") + assert_physical_gpu_idle(args.physical_gpu_id) + provenance = write_provenance( + args.output_dir, args.config, config, source_hashes, args.resume, + args.init_checkpoint, + ) + model = BimanualReconstructionModel(model_config).to(device) + initialization_state = None + if args.init_checkpoint is not None: + specialization = config["experiment"].get("data_only_amendment") == "arctic_h2o_s9_v2_20260917" + if specialization: + payload = torch.load(args.init_checkpoint, map_location="cpu", weights_only=False) + if tuple(payload.get("excluded_model_prefixes", ())) != ("rgb_encoder.backbone.",): + raise RuntimeError("E40 exclusion contract differs from historical Stage 9") + missing = set(model.state_dict()) - set(payload["model"]) + if set(payload["model"]) - set(model.state_dict()): + raise RuntimeError("Unexpected E40 tensors") + if missing != {k for k in model.state_dict() if k.startswith("rgb_encoder.backbone.")}: + raise RuntimeError("E40 must supply every non-backbone tensor") + pretrained_backbone = {k: v.detach().cpu().clone() for k, v in model.state_dict().items() if k in missing} + initialization_state = load_checkpoint( + args.init_checkpoint, model, optimizer=None, map_location=device, + ) + if specialization: + if initialization_state["step"] != 200000: + raise RuntimeError("Data-only experiment must initialize from exact E40 200K") + if initialization_state["extra"].get("h2o_training_data_used") is not False: + raise RuntimeError("E40 initialization must retain no-H2O provenance") + if initialization_state["extra"].get("official_test_used") is not False: + raise RuntimeError("Parent official-test isolation is missing") + current = model.state_dict() + assert all(torch.equal(current[k].detach().cpu(), v) for k, v in payload["model"].items()) + assert all(torch.equal(current[k].detach().cpu(), v) for k, v in pretrained_backbone.items()) + composition = { + "initialization_checkpoint": str(args.init_checkpoint.resolve()), + "initialization_checkpoint_sha256": sha256(args.init_checkpoint), + "source_step": 200000, "new_stage_start_step": 0, + "loaded_non_backbone_tensors": len(payload["model"]), + "pretrained_backbone_tensors_preserved": len(pretrained_backbone), + "all_non_backbone_tensors_equal_E40": True, + "depth_and_K_reinitialized": False, + "matches_historical_stage9_initialization": True, + } + (args.output_dir / "initialization_composition.json").write_text(json.dumps(composition, indent=2) + "\n") + del payload, pretrained_backbone, current + elif initialization_state.get("extra", {}).get("h2o_training_data_used") is not False: + raise RuntimeError("adaptation initialization lacks strict no-H2O provenance") + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + learning_rate = float(protocol["learning_rate"]) + minimum_lr = float(protocol["min_learning_rate"]) + warmup_steps = int(protocol["warmup_steps"]) + staged_adaptation = protocol.get("staged_adaptation") + staged_prefixes: tuple[str, ...] = () + if staged_adaptation is not None: + staged_prefixes = tuple(staged_adaptation["initial_trainable_prefixes"]) + parameter_groups = staged_optimizer_parameter_groups( + model, + learning_rate=learning_rate, + initial_trainable_prefixes=staged_prefixes, + unfrozen_learning_rate_scale=float( + staged_adaptation["unfrozen_learning_rate_scale"] + ), + ) + else: + backbone_learning_rate = protocol.get("backbone_learning_rate") + parameter_groups = optimizer_parameter_groups( + model, + learning_rate=learning_rate, + backbone_learning_rate=( + float(backbone_learning_rate) + if backbone_learning_rate is not None else None + ), + ) + optimizer = torch.optim.AdamW( + parameter_groups, + lr=learning_rate, weight_decay=float(protocol.get("weight_decay", 0.05)), + ) + start_step = 0 + resume_extra: dict[str, Any] | None = None + if args.resume is not None: + if not args.resume.is_file(): + parser.error(f"resume checkpoint missing: {args.resume}") + state = load_checkpoint(args.resume, model, optimizer, device) + start_step = int(state["step"]) + resume_extra = state.get("extra", {}) + if resume_extra.get("config_sha256") != provenance["config_sha256"]: + raise RuntimeError("resume config hash differs from checkpoint") + if resume_extra.get("source_manifest_sha256") != source_hashes: + raise RuntimeError("resume source manifests differ from checkpoint") + set_scheduled_learning_rate(optimizer, learning_rate) + if start_step >= max_steps and not args.allow_schedule_tail: + parser.error(f"checkpoint step {start_step} is not below max_steps {max_steps}") + if start_step >= run_end_step: + parser.error( + f"checkpoint step {start_step} is not below this invocation's end step {run_end_step}" + ) + + batch_sampler = ResumableMixtureBatchSampler( + source_sizes, source_weights, batch_size, seed, start_step, run_end_step, + include_epoch=bool(config["data"].get("photometric_augmentation")), + ) + loader = DataLoader( + train_dataset, batch_sampler=batch_sampler, + generator=torch.Generator().manual_seed(seed + 10_000_000), + num_workers=workers, persistent_workers=workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + context = { + "phase": int(config.get("experiment", {}).get("phase", 7)), + "branch": branch, + "config": config, + "config_sha256": provenance["config_sha256"], + "source_manifest_sha256": source_hashes, + "h2o_training_data_used": allow_h2o, + "h2o_checkpoint_initialization_used": False, + "external_initialization_checkpoint": ( + { + "path": str(args.init_checkpoint.resolve()), + "sha256": sha256(args.init_checkpoint), + "source_step": int(initialization_state["step"]), + } + if args.init_checkpoint is not None + else ( + resume_extra.get("external_initialization_checkpoint") + if resume_extra is not None else None + ) + ), + "official_test_used": False, + "checkpoint_role": "periodic", + "schedule_tail": { + "enabled": bool(args.allow_schedule_tail), + "registered_max_steps": max_steps, + "run_end_step": run_end_step, + "learning_rate_after_horizon": minimum_lr, + }, + } + excluded = () if config["experiment"].get("data_only_amendment") else checkpoint_excluded_prefixes(model) + log_path = args.output_dir / "train_metrics.jsonl" + val_path = args.output_dir / "validation.jsonl" + started = time.perf_counter() + processed_frames = 0 + completed_step = start_step + iterator = iter(loader) + telemetry_samples: list[dict[str, float]] = [] + cumulative_source_batches: Counter[str] = Counter( + (resume_extra or {}).get("source_exposure_batches", {}) + ) + cumulative_source_frames: Counter[str] = Counter( + (resume_extra or {}).get("source_exposure_frames", {}) + ) + cumulative_depth_conditions: Counter[str] = Counter( + (resume_extra or {}).get("depth_input_condition_frames", {}) + ) + exposure_milestones = list(protocol.get("source_exposure_milestones", [])) + completed_exposure_milestones = set( + (resume_extra or {}).get("completed_source_exposure_milestones", []) + ) + torch.cuda.reset_peak_memory_stats(device) + for step in range(start_step, run_end_step): + fetch_started = time.perf_counter() + batch = next(iterator) + data_seconds = time.perf_counter() - fetch_started + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + step_source_batches = source_batch_counts(batch) + step_source_frames = source_frame_counts(batch) + step_depth_conditions = depth_input_condition_counts(batch) + cumulative_source_batches.update(step_source_batches) + cumulative_source_frames.update(step_source_frames) + cumulative_depth_conditions.update(step_depth_conditions) + processed_frames += int(batch["frame_valid"].sum()) + scheduled_lr = warmup_cosine_learning_rate( + step, max_steps, learning_rate, minimum_lr, warmup_steps, + ) + staged_later_active = bool( + staged_adaptation is not None + and step >= int(staged_adaptation["unfreeze_step"]) + ) + if staged_adaptation is not None: + set_staged_parameter_group_phase( + optimizer, active=staged_later_active, + ) + set_scheduled_learning_rate(optimizer, scheduled_lr) + optimizer.zero_grad(set_to_none=True) + forward_start = torch.cuda.Event(enable_timing=True) + forward_end = torch.cuda.Event(enable_timing=True) + backward_end = torch.cuda.Event(enable_timing=True) + forward_start.record() + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + forward_end.record() + if not torch.isfinite(losses["total"]): + raise FloatingPointError(f"non-finite loss at step {step + 1}") + losses["total"].backward() + if staged_adaptation is not None and not staged_later_active: + clear_staged_later_gradients(model, staged_prefixes) + group_norms = { + group["group_name"]: float(torch.linalg.vector_norm(torch.stack([ + p.grad.detach().float().norm() for p in group["params"] if p.grad is not None + ]))) for group in optimizer.param_groups + } + gradient_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) + if not torch.isfinite(gradient_norm): + raise FloatingPointError(f"non-finite gradient at step {step + 1}") + optimizer.step() + backward_end.record() + torch.cuda.synchronize(device) + completed_step = step + 1 + elapsed = time.perf_counter() - started + record = { + "timestamp_utc": utc_now(), + "step": completed_step, + "seed": seed, + "source_counts": step_source_batches, + "source_frame_counts": step_source_frames, + "depth_input_condition_counts": step_depth_conditions, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "metrics": camera_metrics(prediction, batch), + "gradient_norm": float(gradient_norm), + "gradient_group_norms_preclip": group_norms, + "clip_scale": min(1.0, 10.0 / (float(gradient_norm) + 1e-6)), + "optimizer_group_lrs": {g["group_name"]: g["lr"] for g in optimizer.param_groups}, + "learning_rate": scheduled_lr, + "staged_adaptation": ( + { + "later_group_active": staged_later_active, + "unfreeze_step": int(staged_adaptation["unfreeze_step"]), + "unfrozen_learning_rate_scale": float( + staged_adaptation["unfrozen_learning_rate_scale"] + ), + } + if staged_adaptation is not None else None + ), + "timing": { + "data_loading_seconds": data_seconds, + "forward_seconds": forward_start.elapsed_time(forward_end) / 1000.0, + "backward_optimizer_seconds": forward_end.elapsed_time(backward_end) / 1000.0, + "steps_per_second": (completed_step - start_step) / elapsed, + "frames_per_second": processed_frames / elapsed, + }, + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + } + if completed_step == start_step + 1 or completed_step % telemetry_interval == 0: + telemetry = gpu_telemetry(args.physical_gpu_id) + if telemetry is not None: + telemetry_samples.append(telemetry) + record["gpu_telemetry"] = telemetry + with log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + if completed_step % checkpoint_interval == 0: + save_checkpoint( + args.output_dir / f"step_{completed_step:07d}.pt", + model, optimizer, completed_step, + checkpoint_context_with_exposure( + context, cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + newly_reached = reached_source_exposure_milestones( + exposure_milestones, cumulative_source_batches, + completed_exposure_milestones, + ) + for milestone_id in newly_reached: + completed_exposure_milestones.add(milestone_id) + save_checkpoint( + args.output_dir + / f"milestone_{milestone_id}_step_{completed_step:07d}.pt", + model, optimizer, completed_step, + checkpoint_context_with_exposure( + context, cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + if validation_loaders and completed_step % validation_interval == 0: + result = run_validation( + model, criterion, validation_loaders, device, dtype, validation_batches, + ) + with val_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"timestamp_utc": utc_now(), "step": completed_step, **result}) + "\n") + + final_path = args.output_dir / f"step_{completed_step:07d}_final.pt" + save_checkpoint( + final_path, model, optimizer, completed_step, + checkpoint_context_with_exposure( + {**context, "checkpoint_role": "final"}, + cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + elapsed = time.perf_counter() - started + schedule_tail_argument = " --allow-schedule-tail" if args.allow_schedule_tail else "" + resource_override_argument = ( + " --allow-physical-gpus-4-5" if args.allow_physical_gpus_4_5 else "" + ) + resume_command = ( + f"CUDA_VISIBLE_DEVICES= {shlex.quote(sys.executable)} " + f"-m scripts.train_phase7_external --config {shlex.quote(str(args.config.resolve()))} " + f"--output-dir {shlex.quote(str(args.output_dir.resolve()))} " + f"--resume {shlex.quote(str(final_path.resolve()))} " + f"--physical-gpu-id {args.physical_gpu_id}{schedule_tail_argument}" + f"{resource_override_argument}" + ) + (args.output_dir / "resume_command.txt").write_text(resume_command + "\n", encoding="utf-8") + summary = { + "status": ( + "completed_schedule_tail" + if args.allow_schedule_tail and completed_step == run_end_step and completed_step > max_steps + else ("completed" if completed_step == max_steps else "paused_requested") + ), + "start_timestamp_utc": datetime.fromtimestamp( + time.time() - elapsed, timezone.utc, + ).isoformat(), + "end_timestamp_utc": utc_now(), + "start_step": start_step, + "completed_step": completed_step, + "protocol_max_steps": max_steps, + "registered_run_end_step": run_end_step, + "schedule_tail_enabled": bool(args.allow_schedule_tail), + "schedule_tail_learning_rate": minimum_lr if args.allow_schedule_tail else None, + "wall_seconds": elapsed, + "gpu_ids_visible": os.environ.get("CUDA_VISIBLE_DEVICES"), + "physical_gpu_id": args.physical_gpu_id, + "gpu_hours": elapsed / 3600.0, + "train_samples_per_second": ( + (completed_step - start_step) * batch_size / max(elapsed, 1e-9) + ), + "optimizer_steps_per_second": (completed_step - start_step) / max(elapsed, 1e-9), + "frames_per_second": processed_frames / max(elapsed, 1e-9), + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "gpu_utilization_percent_mean": ( + float(np.mean([value["gpu_utilization_percent"] for value in telemetry_samples])) + if telemetry_samples else None + ), + "gpu_telemetry_samples": len(telemetry_samples), + "final_checkpoint": str(final_path.resolve()), + "final_checkpoint_sha256": sha256(final_path), + "resume_command": resume_command, + "source_manifest_sha256": source_hashes, + "official_test_used": False, + "h2o_training_data_used": allow_h2o, + "model_config": asdict(model_config), + "source_exposure_batches": dict(cumulative_source_batches), + "source_exposure_frames": dict(cumulative_source_frames), + "depth_input_condition_frames": dict(cumulative_depth_conditions), + "completed_source_exposure_milestones": sorted( + completed_exposure_milestones + ), + "staged_adaptation": staged_adaptation, + } + (args.output_dir / "summary.json").write_text( + json.dumps(summary, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/PKG-INFO b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..620eae1cf16816e8b6f85bc64184fc9d6654ac92 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/PKG-INFO @@ -0,0 +1,18 @@ +Metadata-Version: 2.4 +Name: foundation-hand +Version: 0.1.0 +Summary: Full-frame token-based bimanual reconstruction research code +Requires-Python: <3.12,>=3.11 +Requires-Dist: einops>=0.8 +Requires-Dist: numpy>=2.0 +Requires-Dist: opencv-python-headless>=4.10 +Requires-Dist: Pillow>=10 +Requires-Dist: PyYAML>=6 +Requires-Dist: scipy>=1.13 +Requires-Dist: torch>=2.6 +Requires-Dist: torchvision>=0.21 +Requires-Dist: tqdm>=4.66 +Provides-Extra: dev +Requires-Dist: pytest>=8; extra == "dev" +Provides-Extra: mano +Requires-Dist: smplx>=0.1.28; extra == "mano" diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/SOURCES.txt b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..41e91bffda7c0b0e844c367e275687fe7b4f6dc7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/SOURCES.txt @@ -0,0 +1,16 @@ +README.md +pyproject.toml +src/foundation_hand/__init__.py +src/foundation_hand.egg-info/PKG-INFO +src/foundation_hand.egg-info/SOURCES.txt +src/foundation_hand.egg-info/dependency_links.txt +src/foundation_hand.egg-info/requires.txt +src/foundation_hand.egg-info/top_level.txt +src/foundation_hand/data/__init__.py +src/foundation_hand/data/h2o_fields.py +src/foundation_hand/geometry/__init__.py +src/foundation_hand/geometry/camera.py +src/foundation_hand/geometry/mano_translation.py +tests/test_camera_geometry.py +tests/test_h2o_fields.py +tests/test_mano_translation.py \ No newline at end of file diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/dependency_links.txt b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/requires.txt b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..11a43ceccd64d950bbf022a5b8750dd7f449011f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/requires.txt @@ -0,0 +1,15 @@ +einops>=0.8 +numpy>=2.0 +opencv-python-headless>=4.10 +Pillow>=10 +PyYAML>=6 +scipy>=1.13 +torch>=2.6 +torchvision>=0.21 +tqdm>=4.66 + +[dev] +pytest>=8 + +[mano] +smplx>=0.1.28 diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/top_level.txt b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..6079d899260f4660e036318093285d2af7c1c176 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand.egg-info/top_level.txt @@ -0,0 +1 @@ +foundation_hand diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/__init__.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e2e8cc628c3ac4153bb9f660cad3e0083b5cb2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/__init__.py @@ -0,0 +1,4 @@ +"""Unified full-frame bimanual reconstruction research package.""" + +__version__ = "0.1.0" + diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/__init__.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92b384d9e870d1f786ec2172145012828e61a7bb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/__init__.py @@ -0,0 +1,49 @@ +"""Dataset parsing and batching.""" + +from .h2o_fields import H2OJointRecord, H2OManoRecord, parse_joint_record, parse_mano_record + +__all__ = [ + "H2OJointRecord", + "H2OManoRecord", + "parse_joint_record", + "parse_mano_record", +] +from foundation_hand.data.h2o_dataset import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.cached_unified_dataset import CachedUnifiedClipDataset, UnifiedConcatDataset +from foundation_hand.data.egodexter_dataset import EgoDexterSequenceDataset +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.samplers import ( + ResumableMixtureBatchSampler, + ResumableRandomBatchSampler, + ResumableWeightedBatchSampler, + load_balanced_sampling_weights, +) +from foundation_hand.data.schema import ( + INPUT_AVAILABILITY_KEYS, + SUPERVISION_MASK_KEYS, + deterministic_clip_keep, + input_availability, + supervision_mask, +) + +__all__ = [ + "H2OCam4Dataset", + "HOT3DClipDataset", + "HOI4DClipDataset", + "ARCTICClipDataset", + "CachedUnifiedClipDataset", + "EgoDexterSequenceDataset", + "UnifiedConcatDataset", + "ResumableMixtureBatchSampler", + "ResumableRandomBatchSampler", + "ResumableWeightedBatchSampler", + "collate_h2o_clips", + "load_balanced_sampling_weights", + "INPUT_AVAILABILITY_KEYS", + "SUPERVISION_MASK_KEYS", + "deterministic_clip_keep", + "input_availability", + "supervision_mask", +] diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/arctic_dataset.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/arctic_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f22c15913e63b81fc8c79314d132d1f92d63d91a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/arctic_dataset.py @@ -0,0 +1,322 @@ +"""ARCTIC P2 rectified full-frame clips in the Phase 7 unified schema.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.h2o_dataset import ( + RGB_MEAN, + RGB_STD, + PhotometricAugmentation, + _resize_pad, + apply_photometric_augmentation, + sample_photometric_parameters, +) +from foundation_hand.geometry.camera import project_points, resize_and_pad_intrinsics +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import ( + axis_angle_to_matrix, + matrix_to_axis_angle, +) +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.data.schema import ( + InvalidSourceSampleError, + source_root_relative_joint_target, +) + + +def transform_points(points: torch.Tensor, world_to_camera: torch.Tensor) -> torch.Tensor: + if points.shape[-1] != 3 or world_to_camera.shape[-2:] != (4, 4): + raise ValueError("expected points [...,N,3] and transforms [...,4,4]") + return torch.einsum( + "...ij,...nj->...ni", world_to_camera[..., :3, :3], points, + ) + world_to_camera[..., None, :3, 3] + + +def geometry_compatibility_mask( + hand_valid: torch.Tensor, vertex_error_mm: torch.Tensor, +) -> torch.Tensor: + """Apply the frozen 1 mm MANO convention gate per frame and hand.""" + + return hand_valid & torch.isfinite(vertex_error_mm) & (vertex_error_mm < 1.0) + + +def compose_camera_global_orientation( + world_axis_angle: torch.Tensor, world_to_camera: torch.Tensor, +) -> torch.Tensor: + world_rotation = axis_angle_to_matrix(world_axis_angle) + camera_rotation = world_to_camera[..., :3, :3] @ world_rotation + return matrix_to_axis_angle(camera_rotation) + + +class ARCTICClipDataset(Dataset[dict[str, Any]]): + """Use P2 train or P2 val only; view 0 is rectified before model input.""" + + source_hw = (600, 840) + original_hw = (2000, 2800) + + def __init__( + self, + manifest: str | Path, + mano_root: str | Path, + target_hw: tuple[int, int] = (368, 640), + photometric_augmentation: Mapping[str, Any] | None = None, + augmentation_seed: int = 20260717, + hand_valid_policy: str = "legacy_wrist", + ) -> None: + self.manifest = Path(manifest).resolve() + self.target_hw = tuple(target_hw) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.augmentation_seed = int(augmentation_seed) + if hand_valid_policy not in {"legacy_wrist", "visible_mesh"}: + raise ValueError(f"unknown ARCTIC hand validity policy: {hand_valid_policy}") + self.hand_valid_policy = hand_valid_policy + self.rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not self.rows or any(row.get("dataset_id") != "ARCTIC" for row in self.rows): + raise ValueError("manifest must be non-empty and ARCTIC-only") + if any(row.get("protocol") != "P2" for row in self.rows): + raise ValueError("ARCTIC adapter accepts protocol P2 only") + if any(row.get("split_role") not in {"arctic_p2_train", "arctic_p2_val"} for row in self.rows): + raise ValueError("ARCTIC manifest may contain P2 train or val only") + if any(row.get("official_test_used") is not False for row in self.rows): + raise ValueError("ARCTIC manifest lacks test-isolation declaration") + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + self._source_mano = { + side: ManoLayer( + mano_root=str(mano_root), side=side, use_pca=False, + ncomps=45, flat_hand_mean=False, + ) + for side in ("left", "right") + } + self._target_mano = ManoCameraLayer(mano_root, fix_left_shapedirs=True) + self._cached_sequence: str | None = None + self._cached_mano: dict[str, Any] | None = None + self._cached_camera: dict[str, Any] | None = None + + def __len__(self) -> int: + return len(self.rows) + + def _sequence(self, row: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + sequence = str(row["physical_recording_id"]) + if self._cached_sequence != sequence: + self._cached_mano = np.load(row["mano_path"], allow_pickle=True).item() + self._cached_camera = np.load(row["camera_path"], allow_pickle=True).item() + self._cached_sequence = sequence + assert self._cached_mano is not None and self._cached_camera is not None + return self._cached_mano, self._cached_camera + + def source_root_relative_joint3d( + self, index: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Regenerate source-compatible camera-frame joints without images.""" + + row = self.rows[int(index)] + indices = [int(value) for value in row["array_indices_0based"]] + mano, camera = self._sequence(row) + rotation = torch.from_numpy(camera["R_k_cam_np"][indices].astype(np.float32)) + joints = torch.full((len(indices), 2, 21, 3), float("nan")) + hand_valid = torch.ones((len(indices), 2), dtype=torch.bool) + for side_index, side in enumerate(("left", "right")): + values = mano[side] + raw_pose = torch.from_numpy(np.concatenate(( + values["rot"][indices], values["pose"][indices], + ), axis=-1).astype(np.float32)) + beta = torch.from_numpy( + np.repeat( + np.asarray(values["shape"], dtype=np.float32)[None], + len(indices), axis=0, + ) + ) + with torch.no_grad(): + _, joints_mm = self._source_mano[side](raw_pose, beta) + relative_world = (joints_mm - joints_mm[:, :1]) / 1000.0 + joints[:, side_index] = torch.einsum( + "tij,tnj->tni", rotation, relative_world, + ) + return source_root_relative_joint_target(joints, hand_valid) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + indices = [int(value) for value in row["array_indices_0based"]] + frame_ids = [int(value) for value in row["frame_ids_1based"]] + mano, camera = self._sequence(row) + K_original = np.asarray(camera["intrinsics"], dtype=np.float32) + input_scale = self.source_hw[1] / self.original_hw[1] + if abs(input_scale - self.source_hw[0] / self.original_hw[0]) > 1e-9: + raise ValueError("ARCTIC ego speedup scale is anisotropic") + K_input = resize_and_pad_intrinsics( + K_original, self.original_hw, self.source_hw, + ) + distortion = np.asarray(camera["dist8"], dtype=np.float64) + parameters = sample_photometric_parameters( + self.photometric_augmentation, self.augmentation_seed, clip_index, epoch, + ) + rgb_rows = [] + resized_hw = pad_left_top = None + for path in row["image_paths"]: + bgr = cv2.imread(path, cv2.IMREAD_COLOR) + if bgr is None or bgr.shape[:2] != self.source_hw: + raise InvalidSourceSampleError(f"invalid ARCTIC ego image: {path}") + rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) + # Downloaded ego speedup images are scaled raw full frames. Rectify + # them to the undistorted camera frame used by ARCTIC P2 geometry. + rgb = cv2.undistort(rgb, K_input, distortion, None, K_input) + rgb = apply_photometric_augmentation(rgb, parameters) + rgb, resized_hw, pad_left_top = _resize_pad( + rgb, self.target_hw, cv2.INTER_LINEAR, + ) + rgb_rows.append( + np.transpose((rgb.astype(np.float32) / 255.0 - RGB_MEAN) / RGB_STD, (2, 0, 1)) + ) + assert resized_hw is not None and pad_left_top is not None + K = resize_and_pad_intrinsics( + K_input, self.source_hw, resized_hw, pad_left_top, + ) + time = len(indices) + source_vertices = torch.full((time, 2, 778, 3), float("nan")) + source_joints = torch.full((time, 2, 21, 3), float("nan")) + pose_camera = torch.full((time, 2, 48), float("nan")) + shape = torch.full((time, 2, 10), float("nan")) + wrist = torch.full((time, 2, 3), float("nan")) + world_to_camera = torch.eye(4)[None].repeat(time, 1, 1) + world_to_camera[:, :3, :3] = torch.from_numpy(camera["R_k_cam_np"][indices]) + world_to_camera[:, :3, 3] = torch.from_numpy(camera["T_k_cam_np"][indices, :, 0]) + for side_index, side in enumerate(("left", "right")): + values = mano[side] + raw_pose = torch.from_numpy(np.concatenate(( + values["rot"][indices], values["pose"][indices], + ), axis=-1).astype(np.float32)) + beta = torch.from_numpy( + np.repeat(np.asarray(values["shape"], dtype=np.float32)[None], time, axis=0) + ) + translation_world = torch.from_numpy(values["trans"][indices].astype(np.float32)) + with torch.no_grad(): + vertices_mm, joints_mm = self._source_mano[side](raw_pose, beta) + vertices_world = vertices_mm / 1000.0 + translation_world[:, None] + joints_world = joints_mm / 1000.0 + translation_world[:, None] + source_vertices[:, side_index] = transform_points(vertices_world, world_to_camera) + source_joints[:, side_index] = transform_points(joints_world, world_to_camera) + full_pose = raw_pose.clone() + full_pose[:, 3:] += self._source_mano[side].th_hands_mean + full_pose[:, :3] = compose_camera_global_orientation( + full_pose[:, :3], world_to_camera, + ) + pose_camera[:, side_index] = full_pose + shape[:, side_index] = beta + wrist[:, side_index] = source_joints[:, side_index, 0] + + K_tensor = torch.from_numpy(np.repeat(K[None], time, axis=0)) + source_joint2d, source_positive = project_points(source_joints, K_tensor) + height, width = self.target_hw + in_frame = ( + source_positive & torch.isfinite(source_joint2d).all(-1) + & (source_joint2d[..., 0] >= 0) & (source_joint2d[..., 0] < width) + & (source_joint2d[..., 1] >= 0) & (source_joint2d[..., 1] < height) + ) + if self.hand_valid_policy == "visible_mesh": + mesh_uv, mesh_positive = project_points(source_vertices, K_tensor) + mesh_in_frame = ( + mesh_positive & torch.isfinite(mesh_uv).all(-1) + & (mesh_uv[..., 0] >= 0) & (mesh_uv[..., 0] < width) + & (mesh_uv[..., 1] >= 0) & (mesh_uv[..., 1] < height) + ) + hand_valid = mesh_in_frame.any(-1) + else: + hand_valid = in_frame[..., 0] & (in_frame.sum(-1) >= 3) + rotations = axis_angle_to_matrix( + torch.nan_to_num(pose_camera).reshape(time, 2, 16, 3) + ) + with torch.no_grad(): + target_vertices, target_joints = self._target_mano( + rotations, torch.nan_to_num(shape), torch.nan_to_num(wrist), + ) + vertex_error_mm = torch.linalg.vector_norm( + target_vertices - source_vertices, dim=-1, + ).amax(dim=-1) * 1000.0 + geometry_valid = geometry_compatibility_mask(hand_valid, vertex_error_mm) + joint2d_valid = in_frame & hand_valid[..., None] + joint3d_valid = geometry_valid[..., None].expand(-1, -1, 21) + root_relative_joints, root_relative_valid = source_root_relative_joint_target( + source_joints, hand_valid, + ) + target_projected, _ = project_points(target_joints, K_tensor) + projection_error = torch.linalg.vector_norm( + target_projected - source_joint2d, dim=-1, + ) + for tensor, valid in ( + (target_vertices, geometry_valid), (target_joints, geometry_valid), + (source_joint2d, hand_valid), (pose_camera, hand_valid), + (shape, geometry_valid), (wrist, hand_valid), + ): + mask = valid + while mask.ndim < tensor.ndim: + mask = mask.unsqueeze(-1) + tensor.masked_fill_(~mask, float("nan")) + output: dict[str, Any] = { + "rgb": torch.from_numpy(np.stack(rgb_rows)), + "depth_m": torch.zeros((time, 1, *self.target_hw), dtype=torch.float32), + "depth_pixel_valid": torch.zeros((time, 1, *self.target_hw), dtype=torch.bool), + "K": K_tensor, + "camera_pose": world_to_camera, + "joint3d_camera": target_joints, + "joint3d_root_relative": root_relative_joints, + "joint2d": source_joint2d, + "joint_element_valid": joint3d_valid, + "mano_pose": pose_camera, + "mano_shape": shape, + "mano_translation_raw": torch.full_like(wrist, float("nan")), + "wrist_root_translation": wrist, + "joint_annotation_valid": geometry_valid, + "mano_annotation_valid": geometry_valid, + "joint2d_valid": joint2d_valid, + "joint3d_valid": joint3d_valid, + "joint3d_root_relative_valid": root_relative_valid, + "translation_valid": hand_valid, + "mano_pose_valid": hand_valid, + "shape_valid": geometry_valid, + "vertices_valid": geometry_valid, + "reprojection_valid": joint3d_valid, + "vertices_camera": target_vertices, + "presence_target": hand_valid.float(), + "presence_label_valid": torch.zeros((time, 2), dtype=torch.bool), + "presence_valid": torch.zeros((time, 2), dtype=torch.bool), + "depth_available": torch.zeros(time, dtype=torch.bool), + "K_available": torch.ones(time, dtype=torch.bool), + "depth_input_available": torch.zeros(time, dtype=torch.bool), + "K_input_available": torch.ones(time, dtype=torch.bool), + "K_supervision_valid": torch.ones(time, dtype=torch.bool), + "frame_valid": torch.ones(time, dtype=torch.bool), + "hand_side_id": torch.tensor((0, 1))[None].expand(time, -1).clone(), + "timestamp_ns": torch.tensor(indices, dtype=torch.long), + "frame_id": torch.tensor(frame_ids, dtype=torch.long), + "source_vertex_regen_error_mm": vertex_error_mm, + "geometry_convention_compatible": geometry_valid, + "projection_roundtrip_error_px": projection_error, + "photometric_aug_params": torch.from_numpy(np.repeat(parameters[None], time, axis=0)), + "image_hw": torch.tensor(self.target_hw, dtype=torch.long), + "dataset_id": "ARCTIC", + "subject_id": str(row["subject_id"]), + "sequence_id": str(row["physical_recording_id"]), + "physical_recording_id": str(row["physical_recording_id"]), + "camera_id": "ego_view_0_rectified", + "stream_id": "ego_rgb_rectified", + "headset_id": str(row["subject_id"]), + } + return output diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/cached_unified_dataset.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/cached_unified_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..616b65592175b6ec7b745ca8e448fe1292b5c713 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/cached_unified_dataset.py @@ -0,0 +1,465 @@ +"""Hash-bound controlled cache for unified external clips.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import ConcatDataset, Dataset + +from foundation_hand.data.h2o_dataset import ( + RGB_MEAN, + RGB_STD, + PhotometricAugmentation, + apply_photometric_augmentation, + sample_photometric_parameters, +) +from foundation_hand.data.schema import deterministic_clip_keep + + +DEPTH_CORRUPTIONS = ( + "quantization", "random_holes", "edge_erosion", "edge_dilation", + "local_invalid", "additive_noise", "multiplicative_noise", + "registration_shift", "sparse_outliers", "global_bias", +) + + +@dataclass(frozen=True) +class FullFrameGeometryAugmentation: + enabled: bool = False + probability: float = 0.0 + scale_min: float = 1.0 + scale_max: float = 1.0 + translation_fraction: float = 0.0 + + @classmethod + def from_mapping( + cls, value: Mapping[str, Any] | None, + ) -> "FullFrameGeometryAugmentation": + config = cls() if value is None else cls(**dict(value)) + if not 0.0 <= config.probability <= 1.0: + raise ValueError("geometry augmentation probability must be in [0, 1]") + if not 0.5 <= config.scale_min <= config.scale_max <= 2.0: + raise ValueError("geometry augmentation scale range must be within [0.5, 2.0]") + if not 0.0 <= config.translation_fraction <= 0.25: + raise ValueError("geometry translation fraction must be in [0, 0.25]") + if config.enabled and config.probability <= 0.0: + raise ValueError("enabled geometry augmentation requires positive probability") + return config + + +def sample_full_frame_affine( + config: FullFrameGeometryAugmentation, + seed: int, + source_clip_index: int, + epoch: int, + image_hw: tuple[int, int], +) -> tuple[np.ndarray, bool]: + """Sample one GT-independent affine shared by every frame and modality.""" + + matrix = np.eye(3, dtype=np.float32) + if not config.enabled: + return matrix, False + generator = np.random.default_rng( + int(seed) * 1_000_003 + int(source_clip_index) * 97_409 + int(epoch) * 65_537 + ) + if float(generator.random()) >= config.probability: + return matrix, False + height, width = image_hw + scale = float(generator.uniform(config.scale_min, config.scale_max)) + dx = float(generator.uniform(-1.0, 1.0) * config.translation_fraction * width) + dy = float(generator.uniform(-1.0, 1.0) * config.translation_fraction * height) + center_x, center_y = (width - 1.0) / 2.0, (height - 1.0) / 2.0 + matrix[0, 0] = scale + matrix[1, 1] = scale + matrix[0, 2] = (1.0 - scale) * center_x + dx + matrix[1, 2] = (1.0 - scale) * center_y + dy + return matrix, True + + +def apply_full_frame_affine( + rgb_u8: np.ndarray, + arrays: dict[str, np.ndarray], + matrix: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + """Warp full-frame inputs and update K/2D supervision with the same affine.""" + + rgb = np.asarray(rgb_u8) + if rgb.ndim != 4 or rgb.shape[-1] != 3: + raise ValueError(f"expected T,H,W,3 RGB cache, got {rgb.shape}") + time, height, width, _ = rgb.shape + if "image_hw" in arrays and tuple( + int(value) for value in np.asarray(arrays["image_hw"]).reshape(-1) + ) != (height, width): + raise ValueError("cached image_hw differs from RGB payload shape") + transform = np.asarray(matrix, dtype=np.float32) + if transform.shape != (3, 3) or not np.allclose(transform[2], (0.0, 0.0, 1.0)): + raise ValueError("full-frame geometry transform must be a 3x3 affine") + affine = transform[:2] + warped_rgb = np.stack([ + cv2.warpAffine( + frame, affine, (width, height), flags=cv2.INTER_LINEAR, + borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0), + ) + for frame in rgb + ]) + updated = dict(arrays) + if "depth_m" in updated and "depth_pixel_valid" in updated: + depth = np.asarray(updated["depth_m"], dtype=np.float32) + valid = np.asarray(updated["depth_pixel_valid"], dtype=bool) + if depth.shape != valid.shape or depth.shape != (time, 1, height, width): + raise ValueError("cached depth/valid geometry shape differs from RGB") + warped_depth = np.stack([ + cv2.warpAffine( + frame[0], affine, (width, height), flags=cv2.INTER_NEAREST, + borderMode=cv2.BORDER_CONSTANT, borderValue=0.0, + )[None] + for frame in depth + ]).astype(np.float32) + warped_valid = np.stack([ + cv2.warpAffine( + frame[0].astype(np.uint8), affine, (width, height), + flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, + borderValue=0, + )[None] + for frame in valid + ]).astype(bool) + updated["depth_m"] = np.where(warped_valid, warped_depth, 0.0).astype(np.float32) + updated["depth_pixel_valid"] = warped_valid + if "K" in updated: + intrinsics = np.asarray(updated["K"], dtype=np.float32) + if intrinsics.shape != (time, 3, 3): + raise ValueError("cached K shape differs from RGB time dimension") + updated["K"] = np.einsum("ij,tjk->tik", transform, intrinsics).astype(np.float32) + if "joint2d" in updated: + joints = np.asarray(updated["joint2d"], dtype=np.float32).copy() + joints_x = joints[..., 0].copy() + joints_y = joints[..., 1].copy() + joints[..., 0] = ( + transform[0, 0] * joints_x + + transform[0, 1] * joints_y + + transform[0, 2] + ) + joints[..., 1] = ( + transform[1, 0] * joints_x + + transform[1, 1] * joints_y + + transform[1, 2] + ) + updated["joint2d"] = joints + return warped_rgb, updated + + +def _shift(array: np.ndarray, dy: int, dx: int, fill: float | bool) -> np.ndarray: + result = np.full_like(array, fill) + source_y = slice(max(0, -dy), array.shape[-2] - max(0, dy)) + target_y = slice(max(0, dy), array.shape[-2] - max(0, -dy)) + source_x = slice(max(0, -dx), array.shape[-1] - max(0, dx)) + target_x = slice(max(0, dx), array.shape[-1] - max(0, -dx)) + result[..., target_y, target_x] = array[..., source_y, source_x] + return result + + +def corrupt_metric_depth( + depth_m: np.ndarray, + pixel_valid: np.ndarray, + corruption: str, + seed: int, +) -> tuple[np.ndarray, np.ndarray]: + """Apply one deterministic clip-level sensor corruption to model inputs.""" + + if corruption not in DEPTH_CORRUPTIONS: + raise ValueError(f"unsupported depth corruption: {corruption}") + depth = np.asarray(depth_m, dtype=np.float32).copy() + valid = np.asarray(pixel_valid, dtype=bool).copy() + generator = np.random.default_rng(seed) + if corruption == "quantization": + quantum = float(generator.choice((0.002, 0.005, 0.010))) + depth[valid] = np.round(depth[valid] / quantum) * quantum + elif corruption == "random_holes": + valid &= generator.random(valid.shape) >= 0.10 + elif corruption == "edge_erosion": + neighbors = [ + _shift(valid, dy, dx, False) + for dy in (-1, 0, 1) for dx in (-1, 0, 1) + ] + valid = np.logical_and.reduce(neighbors) + elif corruption == "edge_dilation": + offsets = [(dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)] + shifted_valid = [ + _shift(valid, dy, dx, False) + for dy, dx in offsets + ] + shifted_depth = [ + np.where(mask, _shift(depth, dy, dx, 0.0), np.inf) + for mask, (dy, dx) in zip(shifted_valid, offsets, strict=True) + ] + dilated = np.logical_or.reduce(shifted_valid) + nearest_foreground = np.minimum.reduce(shifted_depth) + depth = np.where(dilated, nearest_foreground, depth) + valid = dilated + elif corruption == "local_invalid": + height, width = valid.shape[-2:] + box_h, box_w = max(1, height // 5), max(1, width // 5) + top = int(generator.integers(0, max(1, height - box_h + 1))) + left = int(generator.integers(0, max(1, width - box_w + 1))) + valid[..., top : top + box_h, left : left + box_w] = False + elif corruption == "additive_noise": + noise = generator.normal(0.0, 0.0075, size=depth.shape).astype(np.float32) + depth[valid] += noise[valid] + elif corruption == "multiplicative_noise": + scale = generator.normal(1.0, 0.015, size=depth.shape).astype(np.float32) + depth[valid] *= scale[valid] + elif corruption == "registration_shift": + dy, dx = generator.integers(-3, 4, size=2) + depth = _shift(depth, int(dy), int(dx), 0.0) + valid = _shift(valid, int(dy), int(dx), False) + elif corruption == "sparse_outliers": + outliers = valid & (generator.random(valid.shape) < 0.02) + offsets = generator.uniform(-0.08, 0.08, size=depth.shape).astype(np.float32) + depth[outliers] += offsets[outliers] + elif corruption == "global_bias": + depth[valid] += float(generator.uniform(-0.04, 0.04)) + depth = np.where(valid, np.clip(depth, 0.02, 3.0), 0.0).astype(np.float32) + return depth, valid + + +class CachedUnifiedClipDataset(Dataset[dict[str, Any]]): + """Read bounded Phase 7 clip caches without source-format assumptions.""" + + def __init__( + self, + manifest: str | Path, + K_input_dropout: float = 0.0, + dropout_seed: int = 20260717, + photometric_augmentation: Mapping[str, Any] | None = None, + depth_input_dropout: float = 0.0, + depth_corruption_probability: float = 0.0, + joint3d_root_relative_scope: str = "auto", + source_id: str | None = None, + max_clips: int | None = None, + expected_resolution_hw: tuple[int, int] | None = None, + geometry_augmentation: Mapping[str, Any] | None = None, + ) -> None: + self.manifest = Path(manifest).resolve() + self.K_input_dropout = float(K_input_dropout) + self.dropout_seed = int(dropout_seed) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.geometry_augmentation = FullFrameGeometryAugmentation.from_mapping( + geometry_augmentation + ) + self.depth_input_dropout = float(depth_input_dropout) + self.depth_corruption_probability = float(depth_corruption_probability) + root_relative_scope = str(joint3d_root_relative_scope) + self.joint3d_root_relative_scope = { + "historical_left_only": "left_only", + }.get(root_relative_scope, root_relative_scope) + self.source_id = source_id + self.expected_resolution_hw = ( + tuple(int(value) for value in expected_resolution_hw) + if expected_resolution_hw is not None else None + ) + if not 0.0 <= self.K_input_dropout <= 1.0: + raise ValueError("K_input_dropout must be in [0, 1]") + if not 0.0 <= self.depth_input_dropout <= 1.0: + raise ValueError("depth_input_dropout must be in [0, 1]") + if not 0.0 <= self.depth_corruption_probability <= 1.0: + raise ValueError("depth_corruption_probability must be in [0, 1]") + if self.joint3d_root_relative_scope not in {"auto", "disabled", "left_only"}: + raise ValueError( + "joint3d_root_relative_scope must be auto, disabled, left_only " + "or historical_left_only" + ) + rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + self.rows = rows[:max_clips] + declared_resolutions = { + tuple(int(value) for value in row["resolution_hw"]) + for row in self.rows if "resolution_hw" in row + } + if len(declared_resolutions) > 1: + raise ValueError("cache manifest mixes multiple resolutions") + if self.expected_resolution_hw is not None: + if declared_resolutions and declared_resolutions != {self.expected_resolution_hw}: + raise ValueError( + f"cache resolution {sorted(declared_resolutions)} does not match " + f"configured {self.expected_resolution_hw}" + ) + if not declared_resolutions and self.expected_resolution_hw != (368, 640): + raise ValueError( + "legacy cache without resolution metadata is approved only for 640x368" + ) + for row in self.rows: + path = Path(row["cache_path"]) + if not path.is_file(): + raise FileNotFoundError(path) + if self.rows and self.expected_resolution_hw is not None and not declared_resolutions: + with np.load(self.rows[0]["cache_path"], allow_pickle=False) as archive: + if "image_hw" not in archive.files: + raise ValueError("legacy cache payload lacks image_hw") + actual = tuple(int(value) for value in archive["image_hw"].reshape(-1)) + if actual != self.expected_resolution_hw: + raise ValueError( + f"legacy cache resolution {actual} does not match configured " + f"{self.expected_resolution_hw}" + ) + + def __len__(self) -> int: + return len(self.rows) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + with np.load(row["cache_path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + rgb = arrays.pop("rgb_u8") + if self.geometry_augmentation.enabled: + image_hw = tuple(int(value) for value in arrays["image_hw"].reshape(-1)) + geometry_matrix, geometry_applied = sample_full_frame_affine( + self.geometry_augmentation, + self.dropout_seed + 307, + int(row["source_clip_index"]), + epoch, + image_hw, + ) + if geometry_applied: + rgb, arrays = apply_full_frame_affine(rgb, arrays, geometry_matrix) + arrays["geometry_aug_matrix"] = np.repeat( + geometry_matrix[None], len(arrays["frame_valid"]), axis=0, + ) + arrays["geometry_aug_applied"] = np.full( + len(arrays["frame_valid"]), geometry_applied, dtype=bool, + ) + parameters = sample_photometric_parameters( + self.photometric_augmentation, + self.dropout_seed, + int(row["source_clip_index"]), + epoch, + ) + rgb = np.stack([ + apply_photometric_augmentation(frame, parameters) for frame in rgb + ]) + rgb = rgb.astype(np.float32) / 255.0 + rgb = (rgb - RGB_MEAN) / RGB_STD + arrays["rgb"] = np.transpose(rgb, (0, 3, 1, 2)) + output = {key: torch.from_numpy(np.asarray(value)) for key, value in arrays.items()} + sidecar_path = row.get("joint3d_root_relative_sidecar_path") + if self.joint3d_root_relative_scope == "disabled": + output["joint3d_root_relative"] = torch.full_like( + output["joint3d_camera"], float("nan"), + ) + output["joint3d_root_relative_valid"] = torch.zeros_like( + output["joint3d_valid"], dtype=torch.bool, + ) + elif sidecar_path is not None: + with np.load(sidecar_path, allow_pickle=False) as sidecar: + relative = torch.from_numpy(sidecar["joint3d_root_relative"]) + relative_valid = torch.from_numpy( + sidecar["joint3d_root_relative_valid"] + ).bool() + if ( + relative.shape != output["joint3d_camera"].shape + or relative_valid.shape != output["joint3d_valid"].shape + or relative_valid[..., 1, :].any() + ): + raise RuntimeError("invalid historical-left root-relative sidecar") + output["joint3d_root_relative"] = relative.masked_fill( + ~relative_valid[..., None], float("nan"), + ) + output["joint3d_root_relative_valid"] = relative_valid + if self.joint3d_root_relative_scope == "left_only": + if ( + "joint3d_root_relative" not in output + or "joint3d_root_relative_valid" not in output + ): + raise RuntimeError("left-only scope requires cached root-relative targets") + relative_valid = output["joint3d_root_relative_valid"].bool().clone() + relative_valid[..., 1, :] = False + output["joint3d_root_relative_valid"] = relative_valid + output["joint3d_root_relative"] = output[ + "joint3d_root_relative" + ].masked_fill(~relative_valid[..., None], float("nan")) + keep_K = deterministic_clip_keep( + 1.0 - self.K_input_dropout, + self.dropout_seed, + int(row["source_clip_index"]), + epoch, + ) + output["K_input_available"] = torch.full( + output["frame_valid"].shape, keep_K, dtype=torch.bool, + ) + output["K_available"] = output["K_input_available"].clone() + source_depth_available = output["depth_input_available"].bool() + keep_depth = deterministic_clip_keep( + 1.0 - self.depth_input_dropout, + self.dropout_seed + 101, + int(row["source_clip_index"]), epoch, + ) + corrupt_depth = keep_depth and deterministic_clip_keep( + self.depth_corruption_probability, + self.dropout_seed + 211, + int(row["source_clip_index"]), epoch, + ) + condition_code = 0 + if bool(source_depth_available.any()) and not keep_depth: + output["depth_input_available"] = torch.zeros_like(source_depth_available) + condition_code = 1 + elif bool(source_depth_available.any()) and corrupt_depth: + corruption_index = ( + self.dropout_seed * 31 + int(row["source_clip_index"]) * 17 + epoch + ) % len(DEPTH_CORRUPTIONS) + corruption = DEPTH_CORRUPTIONS[corruption_index] + depth, valid = corrupt_metric_depth( + output["depth_m"].numpy(), output["depth_pixel_valid"].numpy(), + corruption, + seed=(self.dropout_seed * 1_000_003 + int(row["source_clip_index"]) * 97 + epoch), + ) + output["depth_m"] = torch.from_numpy(depth) + output["depth_pixel_valid"] = torch.from_numpy(valid) + condition_code = 3 + corruption_index + elif bool(source_depth_available.any()): + condition_code = 2 + output["depth_available"] = output["depth_input_available"].clone() + output["depth_input_condition_code"] = torch.full( + output["frame_valid"].shape, condition_code, dtype=torch.long, + ) + output["photometric_aug_params"] = torch.from_numpy( + np.repeat(parameters[None], len(output["frame_valid"]), axis=0) + ) + for key in ( + "dataset_id", "subject_id", "sequence_id", "physical_recording_id", + "camera_id", "stream_id", "headset_id", + ): + output[key] = row[key] + output["sampling_source_id"] = self.source_id or row["dataset_id"] + return output + + +class UnifiedConcatDataset(ConcatDataset): + """Concat dataset that preserves the sampler-provided augmentation epoch.""" + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + global_index, epoch = int(index[0]), int(index[1]) + else: + global_index, epoch = int(index), 0 + if global_index < 0: + global_index += len(self) + if global_index < 0 or global_index >= len(self): + raise IndexError("dataset index out of range") + dataset_index = int(np.searchsorted( + self.cumulative_sizes, global_index, side="right", + )) + previous = 0 if dataset_index == 0 else self.cumulative_sizes[dataset_index - 1] + return self.datasets[dataset_index][(global_index - previous, epoch)] diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/egodexter_dataset.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/egodexter_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..096ba3b2ab29316e3a92ab05dede9abf8ddbd85c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/egodexter_dataset.py @@ -0,0 +1,151 @@ +"""EgoDexter full-frame RGB-D sequence adapter for frozen zero-shot evaluation.""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Iterator + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD, _resize_pad +from foundation_hand.geometry.camera import depth_mm_to_m, resize_and_pad_intrinsics + + +SEQUENCES = ("Desk", "Fruits", "Kitchen", "Rotunda") +FINGERTIP_JOINT_INDICES = (4, 8, 12, 16, 20) + + +def parse_fingertip_line( + line: str, dimensions: int, *, missing_value: float = 0.0, +) -> np.ndarray: + groups = [group.strip() for group in line.split(";") if group.strip()] + if not 1 <= len(groups) <= 5: + raise ValueError(f"expected one to five fingertips, got {len(groups)}") + values = [[float(value.strip()) for value in group.split(",")] for group in groups] + present = np.asarray(values, dtype=np.float32) + if present.shape != (len(groups), dimensions): + raise ValueError(f"expected fingertip width {dimensions}, got {present.shape}") + array = np.full((5, dimensions), missing_value, dtype=np.float32) + array[: len(groups)] = present + return array + + +def load_depth_intrinsics(calibration_path: str | Path) -> np.ndarray: + text = Path(calibration_path).read_text(encoding="utf-8") + section = text.split("Depth Intrisics Matrix:", 1) + if len(section) != 2: + raise ValueError("depth intrinsics section missing") + rows = [] + for line in section[1].strip().splitlines()[:3]: + values = re.findall(r"[-+]?\d+(?:\.\d+)?", line) + if len(values) != 3: + raise ValueError(f"invalid depth intrinsics row: {line}") + rows.append([float(value) for value in values]) + K = np.asarray(rows, dtype=np.float32) + if K.shape != (3, 3) or not np.allclose(K[2], (0.0, 0.0, 1.0)): + raise ValueError("invalid depth intrinsics matrix") + return K + + +class EgoDexterSequenceDataset: + """Expose one sequence in order without using its annotations as model input.""" + + def __init__( + self, + root: str | Path, + sequence: str, + *, + hand_side: str, + target_hw: tuple[int, int] = (368, 640), + ) -> None: + if sequence not in SEQUENCES: + raise ValueError(f"unknown EgoDexter sequence: {sequence}") + if hand_side not in {"left", "right"}: + raise ValueError("hand_side must be frozen per sequence as left or right") + self.root = Path(root).resolve() + self.sequence = sequence + self.hand_side = hand_side + self.side_index = 0 if hand_side == "left" else 1 + self.target_hw = tuple(target_hw) + self.sequence_root = self.root / "data" / sequence + self.K_source = load_depth_intrinsics(self.root / "CameraCalibration_640x480.txt") + self.rgb_paths = sorted( + (self.sequence_root / "color_on_depth").glob("image_*_color_on_depth.png") + ) + self.depth_paths = sorted((self.sequence_root / "depth").glob("image_*_depth.png")) + lines_2d = (self.sequence_root / "annotation.txt").read_text( + encoding="utf-8", + ).splitlines() + lines_3d = (self.sequence_root / "annotation.txt_3D.txt").read_text( + encoding="utf-8", + ).splitlines() + lengths = {len(self.rgb_paths), len(self.depth_paths), len(lines_2d), len(lines_3d)} + if len(lengths) != 1 or not self.rgb_paths: + raise ValueError(f"EgoDexter sequence streams/annotations differ: {lengths}") + self.fingertips_2d = np.stack([ + parse_fingertip_line(line, 2, missing_value=-1.0) for line in lines_2d + ]) + self.fingertips_3d_m = np.stack([ + parse_fingertip_line(line, 3) for line in lines_3d + ]) / 1000.0 + + def __len__(self) -> int: + return len(self.rgb_paths) + + def _load(self, index: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + rgb_bgr = cv2.imread(str(self.rgb_paths[index]), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(self.depth_paths[index]), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise RuntimeError(f"EgoDexter decode failed: {self.sequence}/{index}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + if rgb.shape[:2] != (480, 640) or depth_mm.shape != (480, 640): + raise ValueError(f"unexpected EgoDexter resolution: {rgb.shape}/{depth_mm.shape}") + rgb, resized_hw, pad_left_top = _resize_pad(rgb, self.target_hw, cv2.INTER_AREA) + depth_mm, depth_hw, depth_pad = _resize_pad( + depth_mm, self.target_hw, cv2.INTER_NEAREST, + ) + if depth_hw != resized_hw or depth_pad != pad_left_top: + raise AssertionError("EgoDexter RGB/depth preprocessing diverged") + K = resize_and_pad_intrinsics( + self.K_source, (480, 640), resized_hw, pad_left_top, + ) + return rgb, depth_mm, K + + def frame(self, index: int, input_mode: str) -> dict[str, object]: + if input_mode not in {"rgb_d_k", "rgb_k", "rgb_only"}: + raise ValueError(f"unsupported input mode: {input_mode}") + rgb, depth_mm, K = self._load(index) + depth_m, depth_valid = depth_mm_to_m(depth_mm) + rgb = rgb.astype(np.float32) / 255.0 + rgb = (rgb - RGB_MEAN) / RGB_STD + K_available = input_mode != "rgb_only" + depth_available = input_mode == "rgb_d_k" + fingertips = self.fingertips_3d_m[index].copy() + fingertip_valid = np.linalg.norm(fingertips, axis=-1) > 0.0 + fingertips[~fingertip_valid] = np.nan + return { + "rgb": torch.from_numpy(np.transpose(rgb, (2, 0, 1))).float()[None, None], + "depth_m": torch.from_numpy(depth_m[None]).float()[None, None], + "depth_pixel_valid": torch.from_numpy(depth_valid[None])[None, None], + "K": torch.from_numpy(K).float()[None, None], + "K_available": torch.tensor([[K_available]], dtype=torch.bool), + "K_input_available": torch.tensor([[K_available]], dtype=torch.bool), + "depth_available": torch.tensor([[depth_available]], dtype=torch.bool), + "depth_input_available": torch.tensor([[depth_available]], dtype=torch.bool), + "frame_valid": torch.ones((1, 1), dtype=torch.bool), + "sequence_id": self.sequence, + "frame_id": index, + "hand_side": self.hand_side, + "hand_side_index": self.side_index, + "target_fingertips_camera_m": torch.from_numpy(fingertips), + "target_fingertip_valid": torch.from_numpy(fingertip_valid), + "target_fingertips_2d_source": torch.from_numpy(self.fingertips_2d[index]), + "K_supervision": torch.from_numpy(K).float(), + } + + def iter_frames(self, input_mode: str) -> Iterator[dict[str, object]]: + for index in range(len(self)): + yield self.frame(index, input_mode) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/h2o_dataset.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/h2o_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f771d19779fc8abbe5e010465f753057a4dd31 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/h2o_dataset.py @@ -0,0 +1,407 @@ +"""Cam4-only H2O RGB-D-K clip dataset with explicit annotation masks.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterable, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record, load_mano_record +from foundation_hand.data.oracle_crop import ( + crop_resize_intrinsics, + crop_resize_with_padding, + oracle_square_crop_spec, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points, resize_and_pad_intrinsics + +RGB_MEAN = np.asarray([0.485, 0.456, 0.406], dtype=np.float32) +RGB_STD = np.asarray([0.229, 0.224, 0.225], dtype=np.float32) + + +@dataclass(frozen=True) +class ClipRef: + take: str + frame_ids: tuple[int, ...] + + +@dataclass(frozen=True) +class PhotometricAugmentation: + enabled: bool = False + probability: float = 0.8 + brightness: float = 0.2 + contrast: float = 0.2 + saturation: float = 0.2 + hue: float = 0.05 + + @classmethod + def from_mapping( + cls, values: Mapping[str, Any] | None, + ) -> "PhotometricAugmentation": + config = cls(**dict(values or {})) + if not 0.0 <= config.probability <= 1.0: + raise ValueError("photometric probability must be in [0, 1]") + for name in ("brightness", "contrast", "saturation"): + if not 0.0 <= getattr(config, name) < 1.0: + raise ValueError(f"photometric {name} must be in [0, 1)") + if not 0.0 <= config.hue <= 0.5: + raise ValueError("photometric hue must be in [0, 0.5]") + return config + + +def sample_photometric_parameters( + config: PhotometricAugmentation, + seed: int, + clip_index: int, + epoch: int, +) -> np.ndarray: + """Return applied, brightness, contrast, saturation, and hue.""" + + identity = np.asarray([0.0, 1.0, 1.0, 1.0, 0.0], dtype=np.float32) + if not config.enabled: + return identity + rng = np.random.default_rng(np.random.SeedSequence([seed, clip_index, epoch])) + if rng.random() >= config.probability: + return identity + return np.asarray([ + 1.0, + rng.uniform(1.0 - config.brightness, 1.0 + config.brightness), + rng.uniform(1.0 - config.contrast, 1.0 + config.contrast), + rng.uniform(1.0 - config.saturation, 1.0 + config.saturation), + rng.uniform(-config.hue, config.hue), + ], dtype=np.float32) + + +def apply_photometric_augmentation( + rgb: np.ndarray, parameters: np.ndarray, +) -> np.ndarray: + """Apply a fixed-order color transform without changing image geometry.""" + + if float(parameters[0]) == 0.0: + return rgb + _, brightness, contrast, saturation, hue = parameters.astype(np.float32) + image = rgb.astype(np.float32) / 255.0 + image *= brightness + channel_mean = image.mean(axis=(0, 1), keepdims=True) + image = (image - channel_mean) * contrast + channel_mean + luminance = ( + image[..., 0:1] * 0.299 + + image[..., 1:2] * 0.587 + + image[..., 2:3] * 0.114 + ) + image = (image - luminance) * saturation + luminance + image = np.clip(image, 0.0, 1.0) + if float(hue) != 0.0: + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + hsv[..., 0] = np.mod(hsv[..., 0] + float(hue) * 360.0, 360.0) + image = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) + return np.rint(np.clip(image, 0.0, 1.0) * 255.0).astype(np.uint8) + + +def _load_jsonl(path: Path) -> list[dict[str, Any]]: + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + + +def _fit_resize(source_hw: tuple[int, int], target_hw: tuple[int, int]) -> tuple[tuple[int, int], tuple[int, int]]: + source_h, source_w = source_hw + target_h, target_w = target_hw + scale = min(target_w / source_w, target_h / source_h) + resized_h = max(1, round(source_h * scale)) + resized_w = max(1, round(source_w * scale)) + pad_top = (target_h - resized_h) // 2 + pad_left = (target_w - resized_w) // 2 + return (resized_h, resized_w), (pad_left, pad_top) + + +def _resize_pad(array: np.ndarray, target_hw: tuple[int, int], interpolation: int, fill: int | float = 0) -> tuple[np.ndarray, tuple[int, int], tuple[int, int]]: + resized_hw, pad_left_top = _fit_resize(array.shape[:2], target_hw) + resized = cv2.resize(array, (resized_hw[1], resized_hw[0]), interpolation=interpolation) + target_h, target_w = target_hw + pad_left, pad_top = pad_left_top + if array.ndim == 3: + output = np.full((target_h, target_w, array.shape[2]), fill, dtype=array.dtype) + else: + output = np.full((target_h, target_w), fill, dtype=array.dtype) + output[pad_top : pad_top + resized_hw[0], pad_left : pad_left + resized_hw[1]] = resized + return output, resized_hw, pad_left_top + + +class H2OCam4Dataset(Dataset[dict[str, Any]]): + """Read only cam4 clips; annotation-invalid numerical targets become NaN.""" + + def __init__( + self, + root: str | Path, + manifest: str | Path, + target_hw: tuple[int, int] = (288, 512), + clip_lengths: Iterable[int] = (8,), + strides: Iterable[int] = (1,), + window_step: int | None = None, + allow_partial: bool = True, + max_clips: int | None = None, + photometric_augmentation: Mapping[str, Any] | None = None, + augmentation_seed: int = 0, + oracle_crop_enabled: bool = False, + ) -> None: + self.root = Path(root).resolve() + self.manifest = Path(manifest).resolve() + self.target_hw = tuple(target_hw) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.augmentation_seed = int(augmentation_seed) + self.oracle_crop_enabled = bool(oracle_crop_enabled) + lengths = tuple(sorted(set(int(value) for value in clip_lengths))) + strides = tuple(sorted(set(int(value) for value in strides))) + if not lengths or not set(lengths).issubset({1, 2, 4, 8, 16}): + raise ValueError(f"Unsupported clip lengths: {lengths}") + if not strides or not set(strides).issubset({1, 2, 4}): + raise ValueError(f"Unsupported strides: {strides}") + self.clips: list[ClipRef] = [] + for record in _load_jsonl(self.manifest): + take = str(record["take"]) + if not take.endswith("cam4"): + raise ValueError(f"Manifest is not cam4-only: {take}") + available = tuple(int(value) for value in record["frame_ids"]) + for length in lengths: + for stride in strides: + span = (length - 1) * stride + 1 + step = window_step or span + for start in range(0, len(available), step): + ids = available[start : start + span : stride] + if len(ids) == length or (allow_partial and ids): + self.clips.append(ClipRef(take=take, frame_ids=ids)) + if max_clips is not None and len(self.clips) >= max_clips: + return + + def __len__(self) -> int: + return len(self.clips) + + def _load_frame( + self, + take: Path, + frame_id: int, + photometric_parameters: np.ndarray, + ) -> dict[str, np.ndarray | bool | int]: + stem = f"{frame_id:06d}" + rgb_bgr = cv2.imread(str(take / "rgb" / f"{stem}.png"), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(take / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise RuntimeError(f"Missing/decode failure at {take}/{stem}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + K, source_hw = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + if rgb.shape[:2] != source_hw or depth_mm.shape != source_hw: + raise ValueError(f"RGB/depth/K mismatch at {take}/{stem}") + joints = load_joint_record(take / "hand_pose" / f"{stem}.txt") + mano = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + if not np.array_equal(joints.annotation_valid, mano.annotation_valid): + raise ValueError(f"Joint/MANO valid disagreement at {take}/{stem}") + rgb = apply_photometric_augmentation(rgb, photometric_parameters) + oracle_crops = ( + self._extract_oracle_crops( + rgb, depth_mm, K, joints.joints_camera_m, + joints.annotation_valid, + ) + if self.oracle_crop_enabled else {} + ) + rgb, resized_hw, pad_left_top = _resize_pad(rgb, self.target_hw, cv2.INTER_AREA) + depth_mm, depth_resized_hw, depth_pad = _resize_pad(depth_mm, self.target_hw, cv2.INTER_NEAREST) + if depth_resized_hw != resized_hw or depth_pad != pad_left_top: + raise AssertionError("RGB/depth preprocessing diverged") + K_out = resize_and_pad_intrinsics(K, source_hw, resized_hw, pad_left_top) + depth_m, depth_valid = depth_mm_to_m(depth_mm) + + joint2d, positive_z = project_points(joints.joints_camera_m, K_out) + joint_valid = np.broadcast_to(joints.annotation_valid[:, None], (2, 21)).copy() & positive_z + + joint3d = joints.joints_camera_m.copy() + pose = mano.pose_axis_angle.copy() + shape = mano.shape.copy() + raw_translation = mano.translation_raw_m.copy() + wrist_translation = joints.joints_camera_m[:, 0].copy() + for hand in range(2): + if not joints.annotation_valid[hand]: + joint3d[hand] = np.nan + joint2d[hand] = np.nan + wrist_translation[hand] = np.nan + if not mano.annotation_valid[hand]: + pose[hand] = np.nan + shape[hand] = np.nan + raw_translation[hand] = np.nan + + rgb_float = rgb.astype(np.float32) / 255.0 + rgb_float = (rgb_float - RGB_MEAN) / RGB_STD + cam_pose = load_float_record(take / "cam_pose" / f"{stem}.txt").reshape(4, 4).astype(np.float32) + return { + "rgb": np.transpose(rgb_float, (2, 0, 1)), + "depth_m": depth_m[None], + "depth_pixel_valid": depth_valid[None], + "K": K_out, + "camera_pose": cam_pose, + "joint3d_camera": joint3d, + "joint2d": joint2d, + "joint_element_valid": joint_valid, + "mano_pose": pose, + "mano_shape": shape, + "mano_translation_raw": raw_translation, + "wrist_root_translation": wrist_translation, + "joint_annotation_valid": joints.annotation_valid, + "mano_annotation_valid": mano.annotation_valid, + "joint2d_valid": joint_valid, + "joint3d_valid": joint_valid, + "translation_valid": joints.annotation_valid.copy(), + "mano_pose_valid": mano.annotation_valid.copy(), + "shape_valid": mano.annotation_valid.copy(), + "vertices_valid": mano.annotation_valid.copy(), + "reprojection_valid": joint_valid.copy(), + # No reliable H2O field supplies on-screen presence. + "presence_target": np.full((2,), np.nan, dtype=np.float32), + "presence_label_valid": np.zeros((2,), dtype=bool), + "presence_valid": np.zeros((2,), dtype=bool), + "depth_available": True, + "K_available": True, + "depth_input_available": True, + "K_input_available": True, + "K_supervision_valid": True, + "hand_side_id": np.asarray((0, 1), dtype=np.int64), + "timestamp_ns": np.int64(round(frame_id * 1_000_000_000 / 30)), + "frame_id": frame_id, + **oracle_crops, + } + + @staticmethod + def _extract_oracle_crops( + rgb: np.ndarray, + depth_mm: np.ndarray, + K: np.ndarray, + joints_camera_m: np.ndarray, + annotation_valid: np.ndarray, + ) -> dict[str, np.ndarray]: + """Extract fixed A3 crops from raw aligned inputs and GT location.""" + + output_hw = (224, 224) + crops_rgb = np.zeros((2, 3, *output_hw), dtype=np.float32) + crops_depth = np.zeros((2, 1, *output_hw), dtype=np.float32) + crops_depth_valid = np.zeros((2, 1, *output_hw), dtype=bool) + crops_K = np.zeros((2, 3, 3), dtype=np.float32) + boxes = np.full((2, 4), -1, dtype=np.int32) + available = np.zeros(2, dtype=bool) + depth_available = np.zeros(2, dtype=bool) + joint2d_raw, positive_z = project_points(joints_camera_m, K) + for hand in range(2): + joint_valid = ( + np.full(21, bool(annotation_valid[hand]), dtype=bool) + & positive_z[hand] + & np.isfinite(joint2d_raw[hand]).all(axis=-1) + ) + spec = oracle_square_crop_spec( + joint2d_raw[hand], joint_valid, rgb.shape[:2], + ) + if spec is None: + continue + crop_rgb = crop_resize_with_padding( + rgb, spec, interpolation=cv2.INTER_LINEAR, + ) + crop_depth_mm = crop_resize_with_padding( + depth_mm, spec, interpolation=cv2.INTER_NEAREST, + ) + depth_m, valid = depth_mm_to_m(crop_depth_mm) + rgb_float = crop_rgb.astype(np.float32) / 255.0 + rgb_float = (rgb_float - RGB_MEAN) / RGB_STD + crops_rgb[hand] = np.transpose(rgb_float, (2, 0, 1)) + crops_depth[hand, 0] = depth_m + crops_depth_valid[hand, 0] = valid + crops_K[hand] = crop_resize_intrinsics(K, spec) + boxes[hand] = (spec.x0, spec.y0, spec.x1, spec.y1) + available[hand] = True + depth_available[hand] = bool(valid.any()) + return { + "oracle_crop_rgb": crops_rgb, + "oracle_crop_depth_m": crops_depth, + "oracle_crop_depth_pixel_valid": crops_depth_valid, + "oracle_crop_K": crops_K, + "oracle_crop_box_xyxy_raw": boxes, + "oracle_crop_available": available, + "oracle_crop_depth_available": depth_available, + } + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + clip = self.clips[clip_index] + take = self.root / clip.take + parts = Path(clip.take).parts + photometric_parameters = sample_photometric_parameters( + self.photometric_augmentation, + self.augmentation_seed, + clip_index, + epoch, + ) + frames = [ + self._load_frame(take, frame_id, photometric_parameters) + for frame_id in clip.frame_ids + ] + tensor_keys = set(frames[0]) - {"frame_id"} + output: dict[str, Any] = {} + for key in tensor_keys: + values = np.stack([np.asarray(frame[key]) for frame in frames]) + output[key] = torch.from_numpy(values) + output["frame_valid"] = torch.ones(len(frames), dtype=torch.bool) + output["dataset_id"] = "H2O" + output["subject_id"] = parts[0] + output["sequence_id"] = "/".join(parts[1:-1]) + output["physical_recording_id"] = "/".join(parts[:-1]) + output["camera_id"] = "cam4" + output["headset_id"] = "H2O-ego" + output["stream_id"] = "cam4-rgb" + output["frame_id"] = torch.tensor(clip.frame_ids, dtype=torch.long) + output["image_hw"] = torch.tensor(self.target_hw, dtype=torch.long) + output["photometric_aug_params"] = torch.from_numpy( + np.repeat(photometric_parameters[None], len(frames), axis=0) + ) + return output + + +def _pad_time(value: torch.Tensor, target_t: int, fill: float | int | bool) -> torch.Tensor: + if value.shape[0] == target_t: + return value + shape = (target_t - value.shape[0],) + value.shape[1:] + padding = torch.full(shape, fill, dtype=value.dtype) + return torch.cat((value, padding), dim=0) + + +def collate_h2o_clips(samples: list[dict[str, Any]]) -> dict[str, Any]: + """Pad variable length clips without repeating frames.""" + + max_t = max(int(sample["frame_valid"].shape[0]) for sample in samples) + metadata = { + "dataset_id", "subject_id", "sequence_id", "physical_recording_id", + "camera_id", "headset_id", "stream_id", "sampling_source_id", + "filtered_tile_id", "input_mode", + } + metadata &= set(samples[0]) + result: dict[str, Any] = {key: [sample[key] for sample in samples] for key in metadata} + nan_keys = { + "joint3d_camera", "joint3d_root_relative", "joint2d", "mano_pose", "mano_shape", + "mano_translation_raw", "wrist_root_translation", "presence_target", + "vertices_camera", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", + } + for key in samples[0]: + if key in metadata: + continue + values = [sample[key] for sample in samples] + if key == "image_hw": + result[key] = torch.stack(values) + continue + fill: float | int | bool = float("nan") if key in nan_keys else False if values[0].dtype == torch.bool else -1 if key == "frame_id" else 0 + result[key] = torch.stack([_pad_time(value, max_t, fill) for value in values]) + result["clip_length"] = torch.tensor([sample["frame_valid"].shape[0] for sample in samples], dtype=torch.long) + return result diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/h2o_fields.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/h2o_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..397172b7f7d4c4ac7f0040d4797d5b079e5264a3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/h2o_fields.py @@ -0,0 +1,88 @@ +"""Strict parsers for the released H2O per-frame hand records.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +HAND_COUNT = 2 +JOINTS_PER_HAND = 21 +JOINT_RECORD_VALUES_PER_HAND = 64 +JOINT_RECORD_VALUES = 128 +MANO_RECORD_VALUES_PER_HAND = 62 +MANO_RECORD_VALUES = 124 +MANO_POSE_DIMS = 48 +MANO_SHAPE_DIMS = 10 + +LEFT = 0 +RIGHT = 1 + + +@dataclass(frozen=True) +class H2OJointRecord: + """Camera-space OpenPose-order hand joints and annotation validity.""" + + annotation_valid: np.ndarray # [2] bool + joints_camera_m: np.ndarray # [2, 21, 3] float32; invalid rows are not supervision + + +@dataclass(frozen=True) +class H2OManoRecord: + """Raw H2O MANO fit parameters and annotation validity.""" + + annotation_valid: np.ndarray # [2] bool + translation_raw_m: np.ndarray # [2, 3] + pose_axis_angle: np.ndarray # [2, 48], global first + shape: np.ndarray # [2, 10] + + +def load_float_record(path: str | Path) -> np.ndarray: + """Load one whitespace-separated H2O text record without accepting bad tokens.""" + + text = Path(path).read_text(encoding="utf-8") + values = np.fromstring(text, dtype=np.float64, sep=" ") + if values.size != len(text.split()): + raise ValueError(f"Non-numeric or malformed value in {path}") + return values + + +def parse_joint_record(values: np.ndarray) -> H2OJointRecord: + values = np.asarray(values, dtype=np.float64).reshape(-1) + if values.size != JOINT_RECORD_VALUES: + raise ValueError(f"Expected {JOINT_RECORD_VALUES} hand_pose values, got {values.size}") + + hands = values.reshape(HAND_COUNT, JOINT_RECORD_VALUES_PER_HAND) + valid = hands[:, 0] != 0 + joints = hands[:, 1:].reshape(HAND_COUNT, JOINTS_PER_HAND, 3).astype(np.float32) + return H2OJointRecord(annotation_valid=valid, joints_camera_m=joints) + + +def parse_mano_record(values: np.ndarray) -> H2OManoRecord: + values = np.asarray(values, dtype=np.float64).reshape(-1) + if values.size != MANO_RECORD_VALUES: + raise ValueError(f"Expected {MANO_RECORD_VALUES} hand_pose_mano values, got {values.size}") + + hands = values.reshape(HAND_COUNT, MANO_RECORD_VALUES_PER_HAND) + valid = hands[:, 0] != 0 + translation = hands[:, 1:4].astype(np.float32) + pose = hands[:, 4 : 4 + MANO_POSE_DIMS].astype(np.float32) + shape = hands[:, 4 + MANO_POSE_DIMS :].astype(np.float32) + if shape.shape != (HAND_COUNT, MANO_SHAPE_DIMS): + raise AssertionError(f"Unexpected MANO shape slice: {shape.shape}") + return H2OManoRecord( + annotation_valid=valid, + translation_raw_m=translation, + pose_axis_angle=pose, + shape=shape, + ) + + +def load_joint_record(path: str | Path) -> H2OJointRecord: + return parse_joint_record(load_float_record(path)) + + +def load_mano_record(path: str | Path) -> H2OManoRecord: + return parse_mano_record(load_float_record(path)) + diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/hoi4d_dataset.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/hoi4d_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..af4abbb4603ca6f7cf9396f9905a8b83137ff377 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/hoi4d_dataset.py @@ -0,0 +1,443 @@ +"""HOI4D RGB-D-K clips with explicit wrist-root and supervision semantics.""" + +from __future__ import annotations + +import json +import pickle +from pathlib import Path +import subprocess +from typing import Any, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.h2o_dataset import ( + RGB_MEAN, + RGB_STD, + PhotometricAugmentation, + _resize_pad, + apply_photometric_augmentation, + sample_photometric_parameters, +) +from foundation_hand.geometry.camera import ( + depth_mm_to_m, + project_points, + resize_and_pad_intrinsics, +) +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.data.schema import ( + InvalidSourceSampleError, + source_root_relative_joint_target, +) + + +def load_hoi4d_mano_annotation(path: str | Path) -> dict[str, np.ndarray]: + """Load one source annotation while classifying payload corruption narrowly.""" + + source = Path(path) + try: + with source.open("rb") as handle: + annotation = pickle.load(handle) + values = { + "poseCoeff": np.asarray(annotation["poseCoeff"], dtype=np.float32), + "beta": np.asarray(annotation["beta"], dtype=np.float32), + "trans": np.asarray(annotation["trans"], dtype=np.float32), + "kps2D": np.asarray(annotation["kps2D"], dtype=np.float32), + } + except (OSError, EOFError, pickle.UnpicklingError, KeyError, TypeError, ValueError) as error: + raise InvalidSourceSampleError( + f"invalid HOI4D MANO annotation payload: {source}: {error}" + ) from error + expected = { + "poseCoeff": (48,), "beta": (10,), "trans": (3,), "kps2D": (21, 2), + } + mismatches = [ + f"{key}={values[key].shape} expected={shape}" + for key, shape in expected.items() if values[key].shape != shape + ] + if mismatches: + raise InvalidSourceSampleError( + f"invalid HOI4D MANO annotation shapes: {source}: {'; '.join(mismatches)}" + ) + return values + + +def hoi4d_geometry_compatibility_mask( + hand_valid: torch.Tensor, vertex_error_mm: torch.Tensor, +) -> torch.Tensor: + """Keep historical-left mesh masked and apply the frozen 1 mm right gate.""" + + geometry_valid = ( + hand_valid & torch.isfinite(vertex_error_mm) & (vertex_error_mm < 1.0) + ) + geometry_valid[..., 0] = False + return geometry_valid + + +def decode_video_frames( + path: str | Path, + frame_ids: list[int], + source_hw: tuple[int, int], + pixel_format: str, + dtype: str, + channels: int, + fps: float | None = None, +) -> np.ndarray: + """Decode exact sorted frame indices while preserving 16-bit depth.""" + + if not frame_ids or frame_ids != sorted(set(frame_ids)): + raise ValueError("HOI4D decoded frame IDs must be non-empty, sorted and unique") + contiguous = frame_ids == list(range(frame_ids[0], frame_ids[-1] + 1)) + if fps is not None and contiguous: + if fps <= 0: + raise ValueError("HOI4D fps must be positive") + command = [ + "ffmpeg", "-v", "error", "-ss", f"{frame_ids[0] / fps:.9f}", + "-i", str(path), "-frames:v", str(len(frame_ids)), + "-f", "rawvideo", "-pix_fmt", pixel_format, "-", + ] + else: + expression = frame_select_expression(frame_ids) + command = [ + "ffmpeg", "-v", "error", "-i", str(path), "-vf", f"select={expression}", + "-vsync", "0", "-frames:v", str(len(frame_ids)), + "-f", "rawvideo", "-pix_fmt", pixel_format, "-", + ] + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) + if result.returncode != 0: + raise RuntimeError(f"ffmpeg decode failed for {path}: {result.stderr.decode(errors='replace')}") + height, width = source_hw + expected = len(frame_ids) * height * width * channels * np.dtype(dtype).itemsize + if len(result.stdout) != expected: + raise RuntimeError( + f"decoded byte count mismatch for {path}: {len(result.stdout)} != {expected}" + ) + shape = (len(frame_ids), height, width) if channels == 1 else ( + len(frame_ids), height, width, channels, + ) + return np.frombuffer(result.stdout, dtype=dtype).reshape(shape).copy() + + +def frame_select_expression(frame_ids: list[int]) -> str: + contiguous = frame_ids == list(range(frame_ids[0], frame_ids[-1] + 1)) + if contiguous: + return f"between(n\\,{frame_ids[0]}\\,{frame_ids[-1]})" + return "+".join(f"eq(n\\,{frame})" for frame in frame_ids) + + +class HOI4DClipDataset(Dataset[dict[str, Any]]): + """Load group-split HOI4D clips into the Phase 7 unified schema.""" + + source_hw = (1080, 1920) + + def __init__( + self, + root: str | Path, + manifest: str | Path, + mano_root: str | Path, + target_hw: tuple[int, int] = (368, 640), + photometric_augmentation: Mapping[str, Any] | None = None, + augmentation_seed: int = 20260717, + ) -> None: + self.root = Path(root).resolve() + self.manifest = Path(manifest).resolve() + self.target_hw = tuple(target_hw) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.augmentation_seed = int(augmentation_seed) + self.rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not self.rows or any(row.get("dataset_id") != "HOI4D" for row in self.rows): + raise ValueError("manifest must be non-empty and HOI4D-only") + if any(row.get("official_test_used") is not False for row in self.rows): + raise ValueError("HOI4D manifest lacks official-test isolation declaration") + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + self._source_mano = { + side: ManoLayer( + mano_root=str(mano_root), side=side, use_pca=False, + ncomps=45, flat_hand_mean=True, + ) + for side in ("left", "right") + } + self._target_mano = ManoCameraLayer(mano_root, fix_left_shapedirs=True) + self._prefetched_recording: str | None = None + self._prefetched_rgb: dict[int, np.ndarray] = {} + self._prefetched_depth: dict[int, np.ndarray] = {} + + def __len__(self) -> int: + return len(self.rows) + + def _annotation_path(self, row: dict[str, Any], frame: int, side: str) -> Path: + return ( + self.root / "Hand_pose" / f"handpose_{side}_hand" + / row["physical_recording_id"] / f"{frame}.pickle" + ) + + def prefetch_clip_indices(self, clip_indices: list[int]) -> None: + if not clip_indices: + self.clear_prefetch() + return + rows = [self.rows[index] for index in clip_indices] + recordings = {str(row["physical_recording_id"]) for row in rows} + rgb_paths = {str(row["rgb_video"]) for row in rows} + depth_paths = {str(row["depth_video"]) for row in rows} + frame_rates = {float(row["fps"]) for row in rows} + if ( + len(recordings) != 1 or len(rgb_paths) != 1 + or len(depth_paths) != 1 or len(frame_rates) != 1 + ): + raise ValueError("HOI4D prefetch batch must stay within one physical recording") + frame_ids = sorted({int(frame) for row in rows for frame in row["frame_ids"]}) + rgb = decode_video_frames( + next(iter(rgb_paths)), frame_ids, self.source_hw, "rgb24", "u1", 3, + fps=next(iter(frame_rates)), + ) + depth = decode_video_frames( + next(iter(depth_paths)), frame_ids, self.source_hw, "gray16le", " None: + self._prefetched_recording = None + self._prefetched_rgb = {} + self._prefetched_depth = {} + + def source_root_relative_joint3d( + self, index: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Regenerate source-compatible joints without decoding RGB-D video.""" + + row = self.rows[int(index)] + frame_ids = [int(value) for value in row["frame_ids"]] + joints = torch.full((len(frame_ids), 2, 21, 3), float("nan")) + hand_valid = torch.zeros((len(frame_ids), 2), dtype=torch.bool) + for side_index, side in enumerate(("left", "right")): + frame_indices = [] + poses = [] + shapes = [] + for frame_index, frame in enumerate(frame_ids): + path = self._annotation_path(row, frame, side) + if not path.is_file(): + continue + annotation = load_hoi4d_mano_annotation(path) + poses.append(annotation["poseCoeff"]) + shapes.append(annotation["beta"]) + frame_indices.append(frame_index) + if not frame_indices: + continue + with torch.no_grad(): + _, joints_mm = self._source_mano[side]( + torch.from_numpy(np.stack(poses)), + torch.from_numpy(np.stack(shapes)), + ) + relative = (joints_mm - joints_mm[:, :1]) / 1000.0 + joints[frame_indices, side_index] = relative + hand_valid[frame_indices, side_index] = True + return source_root_relative_joint_target(joints, hand_valid) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + frame_ids = [int(value) for value in row["frame_ids"]] + fps = float(row["fps"]) + use_prefetch = ( + self._prefetched_recording == str(row["physical_recording_id"]) + and all(frame in self._prefetched_rgb for frame in frame_ids) + and all(frame in self._prefetched_depth for frame in frame_ids) + ) + if use_prefetch: + rgb_raw = np.stack([self._prefetched_rgb[frame] for frame in frame_ids]) + depth_raw = np.stack([self._prefetched_depth[frame] for frame in frame_ids]) + else: + rgb_raw = decode_video_frames( + row["rgb_video"], frame_ids, self.source_hw, "rgb24", "u1", 3, + fps=fps, + ) + depth_raw = decode_video_frames( + row["depth_video"], frame_ids, self.source_hw, "gray16le", " None: + """Compatibility needed by the official SMPL-X loader on Python 3.11.""" + + if not hasattr(inspect, "getargspec"): + inspect.getargspec = inspect.getfullargspec # type: ignore[attr-defined] + aliases = { + "bool": np.bool_, "int": np.int64, "float": np.float64, + "complex": np.complex128, "object": np.object_, + "unicode": np.str_, "str": np.str_, + } + for name, value in aliases.items(): + if name not in np.__dict__: + setattr(np, name, value) + + +def load_hot3d_api(toolkit_root: str | Path) -> dict[str, Any]: + """Import the pinned official toolkit without copying or rewriting it.""" + + toolkit = Path(toolkit_root).resolve() + source = toolkit / "hot3d" + if not (source / "dataset_api.py").is_file(): + raise FileNotFoundError(f"official HOT3D toolkit missing: {source}") + source_text = str(source) + if source_text not in sys.path: + sys.path.insert(0, source_text) + enable_hot3d_runtime_compatibility() + from dataset_api import Hot3dDataProvider + from data_loaders.loader_hand_poses import Handedness, load_mano_shape_params + from data_loaders.loader_object_library import load_object_library + from data_loaders.mano_layer import MANOHandModel + from projectaria_tools.core.calibration import FISHEYE624, LINEAR + from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions + from projectaria_tools.core.stream_id import StreamId + return { + "Hot3dDataProvider": Hot3dDataProvider, + "Handedness": Handedness, + "load_mano_shape_params": load_mano_shape_params, + "load_object_library": load_object_library, + "MANOHandModel": MANOHandModel, + "LINEAR": LINEAR, + "FISHEYE624": FISHEYE624, + "TimeDomain": TimeDomain, + "TimeQueryOptions": TimeQueryOptions, + "StreamId": StreamId, + } + + +def transform_points(points: np.ndarray, transform: np.ndarray) -> np.ndarray: + points = np.asarray(points, dtype=np.float64) + transform = np.asarray(transform, dtype=np.float64) + if transform.shape != (4, 4): + raise ValueError("transform must be 4x4") + return (points @ transform[:3, :3].T + transform[:3, 3]).astype(np.float32) + + +def linear_camera_matrix(calibration: Any) -> np.ndarray: + focal = np.asarray(calibration.get_focal_lengths(), dtype=np.float64) + principal = np.asarray(calibration.get_principal_point(), dtype=np.float64) + if focal.size != 2 or principal.size != 2: + raise ValueError("HOT3D linear calibration is not pinhole fx/fy/cx/cy") + return np.asarray([ + [focal[0], 0.0, principal[0]], + [0.0, focal[1], principal[1]], + [0.0, 0.0, 1.0], + ], dtype=np.float32) + + +def pca_to_full_local_pose( + coefficients: np.ndarray, + source_layer: Any, +) -> torch.Tensor: + coefficients_t = torch.as_tensor(coefficients, dtype=torch.float32) + if coefficients_t.shape != (15,): + raise ValueError(f"HOT3D MANO PCA pose must have 15 values, got {coefficients_t.shape}") + return ( + coefficients_t @ source_layer.hand_components[:15].detach().cpu() + + source_layer.pose_mean[3:].detach().cpu() + ).reshape(15, 3) + + +def geometry_valid_mask( + annotation_present: torch.Tensor, + vertex_error_mm: torch.Tensor, + threshold_mm: float = 1.0, +) -> torch.Tensor: + """Enable geometry supervision only where MANO regeneration passes audit.""" + + return ( + annotation_present.bool() + & torch.isfinite(vertex_error_mm) + & (vertex_error_mm < threshold_mm) + ) + + +def hot3d_supervision_masks( + geometry_valid: torch.Tensor, + source_vertices: torch.Tensor, + joint2d: torch.Tensor, + positive_depth: torch.Tensor, + projection_error: torch.Tensor, + K: torch.Tensor, + image_hw: tuple[int, int], + max_projection_error_px: float = 2.0, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Keep full-hand 3D targets for visible hands, but only visible 2D joints.""" + + height, width = image_hw + mesh_uv, mesh_positive = project_points(source_vertices, K) + mesh_in_frame = ( + mesh_positive & torch.isfinite(mesh_uv).all(-1) + & (mesh_uv[..., 0] >= 0) & (mesh_uv[..., 0] < width) + & (mesh_uv[..., 1] >= 0) & (mesh_uv[..., 1] < height) + ) + hand_valid = geometry_valid & mesh_in_frame.any(-1) + joint_in_frame = ( + positive_depth & torch.isfinite(joint2d).all(-1) + & (joint2d[..., 0] >= 0) & (joint2d[..., 0] < width) + & (joint2d[..., 1] >= 0) & (joint2d[..., 1] < height) + ) + joint2d_valid = ( + hand_valid[..., None] & joint_in_frame + & torch.isfinite(projection_error) + & (projection_error <= max_projection_error_px) + ) + joint3d_valid = hand_valid[..., None].expand_as(joint2d_valid) + return hand_valid, joint2d_valid, joint3d_valid + + +def quest_linear_camera_calibration( + device: Any, stream_id: Any, linear_model: Any, native_model: Any, +) -> tuple[Any, Any]: + """Use Quest3's native device-to-camera transform with its rectified intrinsics.""" + + T_device_camera, _ = device.get_camera_calibration( + stream_id, camera_model=native_model, + ) + _, linear_calibration = device.get_camera_calibration( + stream_id, camera_model=linear_model, + ) + return T_device_camera, linear_calibration + + +class HOT3DClipDataset(Dataset[dict[str, Any]]): + """Decode rectilinear HOT3D clips through the official toolkit.""" + + def __init__( + self, + root: str | Path, + manifest: str | Path, + toolkit_root: str | Path, + mano_root: str | Path, + target_hw: tuple[int, int] = (368, 640), + K_input_dropout: float = 0.3, + dropout_seed: int = 20260717, + max_clips: int | None = None, + provider_cache_size: int = 2, + ) -> None: + self.root = Path(root).resolve() + self.manifest = Path(manifest).resolve() + self.toolkit_root = Path(toolkit_root).resolve() + self.mano_root = Path(mano_root).resolve() + self.target_hw = tuple(int(value) for value in target_hw) + self.K_input_dropout = float(K_input_dropout) + self.dropout_seed = int(dropout_seed) + self.provider_cache_size = int(provider_cache_size) + if not 0.0 <= self.K_input_dropout <= 1.0: + raise ValueError("K_input_dropout must be in [0, 1]") + if self.provider_cache_size < 1: + raise ValueError("provider_cache_size must be positive") + rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + for row in rows: + if row.get("dataset") != "HOT3D" or row.get("have_hand_object_pose_gt") is not True: + raise ValueError("HOT3D manifest contains a non-GT or foreign row") + if len(row.get("timestamps_ns", [])) == 0: + raise ValueError("HOT3D manifest contains an empty clip") + self.rows = rows[:max_clips] + self._api: dict[str, Any] | None = None + self._object_library: Any | None = None + self._source_mano: Any | None = None + self._target_mano: ManoCameraLayer | None = None + self._providers: OrderedDict[str, Any] = OrderedDict() + + def __len__(self) -> int: + return len(self.rows) + + def _initialize_runtime(self) -> None: + if self._api is not None: + return + self._api = load_hot3d_api(self.toolkit_root) + self._object_library = self._api["load_object_library"]( + str(self.root / "assets") + ) + self._source_mano = self._api["MANOHandModel"]( + str(self.mano_root), joint_mapper=None, + ) + self._target_mano = ManoCameraLayer( + self.mano_root, fix_left_shapedirs=True, + ).eval() + + def _provider(self, recording: str) -> Any: + self._initialize_runtime() + if recording in self._providers: + provider = self._providers.pop(recording) + self._providers[recording] = provider + return provider + assert self._api is not None + provider = self._api["Hot3dDataProvider"]( + sequence_folder=str(self.root / recording), + object_library=self._object_library, + mano_hand_model=self._source_mano, + ) + self._providers[recording] = provider + while len(self._providers) > self.provider_cache_size: + self._providers.popitem(last=False) + return provider + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + provider = self._provider(str(row["recording_id"])) + assert self._api is not None and self._target_mano is not None + hand_provider = provider.mano_hand_data_provider + if hand_provider is None: + raise RuntimeError("GT HOT3D row has no official MANO provider") + device = provider.device_data_provider + pose_provider = provider.device_pose_data_provider + stream_id = self._api["StreamId"](str(row["stream_id"])) + is_aria = str(row["headset"]) == "Aria" + keep_K = deterministic_clip_keep( + 1.0 - self.K_input_dropout, + self.dropout_seed, + clip_index, + epoch, + ) + shape_params = torch.as_tensor( + self._api["load_mano_shape_params"]( + str(self.root / row["recording_id"] / "mano_hand_pose_trajectory.jsonl") + ), + dtype=torch.float32, + ) + + frames: list[dict[str, Any]] = [] + source_vertices: list[np.ndarray] = [] + pose_targets: list[np.ndarray] = [] + shape_targets: list[np.ndarray] = [] + wrist_targets: list[np.ndarray] = [] + hand_valid_rows: list[np.ndarray] = [] + raw_calibrations: list[Any] = [] + resize_contracts: list[tuple[tuple[int, int], tuple[int, int], tuple[int, int]]] = [] + for timestamp_ns in row["timestamps_ns"]: + timestamp_ns = int(timestamp_ns) + hand_with_dt = hand_provider.get_pose_at_timestamp( + timestamp_ns, + self._api["TimeQueryOptions"].CLOSEST, + self._api["TimeDomain"].TIME_CODE, + 20_000_000, + ) + headset_with_dt = pose_provider.get_pose_at_timestamp( + timestamp_ns, + self._api["TimeQueryOptions"].CLOSEST, + self._api["TimeDomain"].TIME_CODE, + 20_000_000, + ) + if hand_with_dt is None or headset_with_dt is None: + raise RuntimeError( + f"HOT3D 20ms synchronization failure recording={row['recording_id']} " + f"stream={row['stream_id']} timestamp_ns={timestamp_ns} " + f"hand_missing={hand_with_dt is None} " + f"headset_missing={headset_with_dt is None}" + ) + if is_aria: + T_device_camera, calibration = device.get_online_camera_calibration( + stream_id, timestamp_ns, camera_model=self._api["LINEAR"], + ) + else: + T_device_camera, calibration = quest_linear_camera_calibration( + device, stream_id, self._api["LINEAR"], self._api["FISHEYE624"], + ) + image = device.get_undistorted_image(timestamp_ns, stream_id) + if image is None: + raise RuntimeError("official HOT3D provider returned no image") + if image.ndim == 2: + image = np.repeat(image[..., None], 3, axis=-1) + if image.ndim != 3 or image.shape[-1] != 3: + raise ValueError(f"unexpected HOT3D image shape: {image.shape}") + K_raw = linear_camera_matrix(calibration) + image, resized_hw, pad_left_top = _resize_pad( + image, self.target_hw, cv2.INTER_AREA, + ) + K = resize_and_pad_intrinsics( + K_raw, tuple(int(v) for v in calibration.get_image_size()[::-1]), + resized_hw, pad_left_top, + ) + source_hw = tuple(int(v) for v in calibration.get_image_size()[::-1]) + T_world_camera = ( + headset_with_dt.pose3d.T_world_device @ T_device_camera + ) + T_camera_world = np.asarray(T_world_camera.inverse().to_matrix()) + + poses = np.full((2, 48), np.nan, dtype=np.float32) + shapes = np.full((2, 10), np.nan, dtype=np.float32) + wrists = np.full((2, 3), np.nan, dtype=np.float32) + vertices = np.full((2, 778, 3), np.nan, dtype=np.float32) + valid = np.zeros(2, dtype=bool) + collection = hand_with_dt.pose3d_collection + for handedness, side in ( + (self._api["Handedness"].Left, 0), + (self._api["Handedness"].Right, 1), + ): + if handedness not in collection.poses: + continue + hand = collection.poses[handedness] + source_layer = ( + self._source_mano.mano_layer_left + if side == 0 else self._source_mano.mano_layer_right + ) + local_pose = pca_to_full_local_pose(hand.joint_angles, source_layer) + R_camera_world = torch.as_tensor( + T_camera_world[:3, :3], dtype=torch.float32, + ) + R_world_wrist = torch.as_tensor( + hand.wrist_pose.to_matrix()[:3, :3], dtype=torch.float32, + ) + global_pose = matrix_to_axis_angle( + (R_camera_world @ R_world_wrist)[None], + )[0] + source_vertex = hand_provider.get_hand_mesh_vertices(hand) + if source_vertex is None: + continue + # The official provider's mesh is authoritative. Wrist position + # is obtained from its native MANO root by undoing the global + # raw-translation convention through the source layer below. + native_output = source_layer( + betas=shape_params[None], + global_orient=matrix_to_axis_angle(R_world_wrist[None]), + hand_pose=torch.as_tensor(hand.joint_angles)[None], + transl=torch.as_tensor(hand.wrist_pose.to_matrix()[:3, 3])[None], + return_verts=True, + ) + wrist_world = native_output.joints[0, 0].detach().cpu().numpy() + poses[side] = torch.cat((global_pose, local_pose.reshape(-1))).numpy() + shapes[side] = shape_params.numpy() + wrists[side] = transform_points(wrist_world[None], T_camera_world)[0] + vertices[side] = transform_points( + source_vertex.detach().cpu().numpy(), T_camera_world, + ) + valid[side] = True + rgb = image.astype(np.float32) / 255.0 + rgb = (rgb - RGB_MEAN) / RGB_STD + frames.append({ + "rgb": np.transpose(rgb, (2, 0, 1)), + "K": K.astype(np.float32), + "camera_pose": np.asarray(T_world_camera.to_matrix(), dtype=np.float32), + "timestamp_ns": np.int64(timestamp_ns), + "frame_id": np.int64(timestamp_ns), + "hand_pose_time_delta_ns": np.int64(hand_with_dt.time_delta_ns), + "headset_time_delta_ns": np.int64(headset_with_dt.time_delta_ns), + }) + source_vertices.append(vertices) + pose_targets.append(poses) + shape_targets.append(shapes) + wrist_targets.append(wrists) + hand_valid_rows.append(valid) + raw_calibrations.append(calibration) + resize_contracts.append((source_hw, resized_hw, pad_left_top)) + + pose_tensor = torch.from_numpy(np.stack(pose_targets)) + shape_tensor = torch.from_numpy(np.stack(shape_targets)) + wrist_tensor = torch.from_numpy(np.stack(wrist_targets)) + valid_tensor = torch.from_numpy(np.stack(hand_valid_rows)) + rotations = axis_angle_to_matrix( + torch.nan_to_num(pose_tensor).reshape(len(frames), 2, 16, 3) + ) + with torch.no_grad(): + target_vertices, target_joints = self._target_mano( + rotations, torch.nan_to_num(shape_tensor), + torch.nan_to_num(wrist_tensor), + ) + source_vertex_tensor = torch.from_numpy(np.stack(source_vertices)) + vertex_error_mm = torch.linalg.vector_norm( + target_vertices - source_vertex_tensor, dim=-1, + ).amax(dim=-1) * 1000.0 + geometry_valid = geometry_valid_mask(valid_tensor, vertex_error_mm) + + K_tensor = torch.from_numpy(np.stack([frame["K"] for frame in frames])) + joint2d, positive = project_points(target_joints, K_tensor) + time = len(frames) + projection_error = torch.full((time, 2, 21), float("nan")) + for frame_index, calibration in enumerate(raw_calibrations): + source_hw, resized_hw, (pad_left, pad_top) = resize_contracts[frame_index] + scale_x = resized_hw[1] / source_hw[1] + scale_y = resized_hw[0] / source_hw[0] + for side in range(2): + if not geometry_valid[frame_index, side]: + continue + for joint_index, point in enumerate(target_joints[frame_index, side]): + source_uv = calibration.project(point.detach().cpu().numpy()) + if source_uv is None: + continue + resized_uv = torch.tensor( + ( + float(source_uv[0]) * scale_x + pad_left, + float(source_uv[1]) * scale_y + pad_top, + ), + dtype=joint2d.dtype, + ) + projection_error[frame_index, side, joint_index] = ( + torch.linalg.vector_norm( + resized_uv - joint2d[frame_index, side, joint_index] + ) + ) + geometry_valid, joint2d_valid, joint3d_valid = hot3d_supervision_masks( + geometry_valid, source_vertex_tensor, joint2d, positive, + projection_error, K_tensor, self.target_hw, + ) + for tensor in (target_vertices, target_joints, joint2d, pose_tensor, shape_tensor, wrist_tensor): + mask = geometry_valid + while mask.ndim < tensor.ndim: + mask = mask.unsqueeze(-1) + tensor.masked_fill_(~mask, float("nan")) + output: dict[str, Any] = { + "rgb": torch.from_numpy(np.stack([frame["rgb"] for frame in frames])), + "depth_m": torch.zeros((time, 1, *self.target_hw), dtype=torch.float32), + "depth_pixel_valid": torch.zeros((time, 1, *self.target_hw), dtype=torch.bool), + "K": K_tensor, + "camera_pose": torch.from_numpy(np.stack([frame["camera_pose"] for frame in frames])), + "joint3d_camera": target_joints, + "joint2d": joint2d, + "joint_element_valid": joint3d_valid, + "mano_pose": pose_tensor, + "mano_shape": shape_tensor, + "mano_translation_raw": torch.full_like(wrist_tensor, float("nan")), + "wrist_root_translation": wrist_tensor, + "joint_annotation_valid": geometry_valid, + "mano_annotation_valid": geometry_valid, + "joint2d_valid": joint2d_valid, + "joint3d_valid": joint3d_valid, + "translation_valid": geometry_valid, + "mano_pose_valid": geometry_valid, + "shape_valid": geometry_valid, + "vertices_valid": geometry_valid, + "reprojection_valid": joint2d_valid, + "vertices_camera": target_vertices, + "presence_target": torch.full((time, 2), float("nan")), + "presence_label_valid": torch.zeros((time, 2), dtype=torch.bool), + "presence_valid": torch.zeros((time, 2), dtype=torch.bool), + "depth_available": torch.zeros(time, dtype=torch.bool), + "K_available": torch.full((time,), keep_K, dtype=torch.bool), + "depth_input_available": torch.zeros(time, dtype=torch.bool), + "K_input_available": torch.full((time,), keep_K, dtype=torch.bool), + "K_supervision_valid": torch.ones(time, dtype=torch.bool), + "frame_valid": torch.ones(time, dtype=torch.bool), + "hand_side_id": torch.tensor((0, 1))[None].expand(time, -1).clone(), + "timestamp_ns": torch.tensor([frame["timestamp_ns"] for frame in frames]), + "frame_id": torch.tensor([frame["frame_id"] for frame in frames]), + "hand_pose_time_delta_ns": torch.tensor([frame["hand_pose_time_delta_ns"] for frame in frames]), + "headset_time_delta_ns": torch.tensor([frame["headset_time_delta_ns"] for frame in frames]), + "source_vertex_regen_error_mm": vertex_error_mm, + "source_hand_annotation_present": valid_tensor, + "geometry_convention_compatible": geometry_valid, + "projection_roundtrip_error_px": projection_error, + "image_hw": torch.tensor(self.target_hw, dtype=torch.long), + "dataset_id": "HOT3D", + "subject_id": str(row["participant_id"]), + "sequence_id": str(row["recording_id"]), + "physical_recording_id": str(row["recording_id"]), + "camera_id": str(row["stream_id"]), + "stream_id": str(row["stream_id"]), + "headset_id": str(row["headset"]), + } + return output diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/oracle_crop.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/oracle_crop.py new file mode 100644 index 0000000000000000000000000000000000000000..b615a58c3762a9ab88ed870acf5b6bc532d8ba6e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/oracle_crop.py @@ -0,0 +1,105 @@ +"""Pre-registered raw-image crop geometry for the A3 oracle diagnostic.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import cv2 +import numpy as np + +from foundation_hand.geometry.camera import resize_and_pad_intrinsics + + +@dataclass(frozen=True) +class OracleCropSpec: + x0: int + y0: int + side: int + source_hw: tuple[int, int] + output_hw: tuple[int, int] = (224, 224) + + @property + def x1(self) -> int: + return self.x0 + self.side + + @property + def y1(self) -> int: + return self.y0 + self.side + + +def oracle_square_crop_spec( + joints_2d: np.ndarray, + joint_valid: np.ndarray, + source_hw: tuple[int, int], + *, + margin: float = 1.5, + min_side: int = 96, + min_points: int = 4, + output_hw: tuple[int, int] = (224, 224), +) -> OracleCropSpec | None: + """Build the fixed A3 square ROI from valid GT joint locations.""" + + points = np.asarray(joints_2d, dtype=np.float64) + valid = np.asarray(joint_valid, dtype=bool) + if points.shape != (21, 2) or valid.shape != (21,): + raise ValueError("expected joints [21,2] and validity [21]") + source_h, source_w = (int(value) for value in source_hw) + output_h, output_w = (int(value) for value in output_hw) + if min(source_h, source_w, output_h, output_w, min_side, min_points) <= 0: + raise ValueError("image sizes, minimum side, and minimum points must be positive") + if margin < 1.0: + raise ValueError("crop margin must be at least 1") + valid &= np.isfinite(points).all(axis=-1) + if int(valid.sum()) < min_points: + return None + selected = points[valid] + lower = selected.min(axis=0) + upper = selected.max(axis=0) + center = 0.5 * (lower + upper) + side = int(np.ceil(max(float(np.max(upper - lower)) * margin, float(min_side)))) + x0 = int(np.floor(float(center[0]) - side / 2.0)) + y0 = int(np.floor(float(center[1]) - side / 2.0)) + if x0 >= source_w or y0 >= source_h or x0 + side <= 0 or y0 + side <= 0: + return None + return OracleCropSpec(x0, y0, side, (source_h, source_w), (output_h, output_w)) + + +def crop_resize_with_padding( + array: np.ndarray, + spec: OracleCropSpec, + *, + interpolation: int, + fill: int | float = 0, +) -> np.ndarray: + """Apply an integer square crop, explicit padding, then one resize.""" + + value = np.asarray(array) + if value.shape[:2] != spec.source_hw: + raise ValueError(f"source shape {value.shape[:2]} does not match {spec.source_hw}") + crop_shape = (spec.side, spec.side) + value.shape[2:] + crop = np.full(crop_shape, fill, dtype=value.dtype) + source_h, source_w = spec.source_hw + source_x0, source_y0 = max(0, spec.x0), max(0, spec.y0) + source_x1, source_y1 = min(source_w, spec.x1), min(source_h, spec.y1) + if source_x1 > source_x0 and source_y1 > source_y0: + target_x0, target_y0 = source_x0 - spec.x0, source_y0 - spec.y0 + crop[ + target_y0 : target_y0 + source_y1 - source_y0, + target_x0 : target_x0 + source_x1 - source_x0, + ] = value[source_y0:source_y1, source_x0:source_x1] + output_h, output_w = spec.output_hw + return cv2.resize(crop, (output_w, output_h), interpolation=interpolation) + + +def crop_resize_intrinsics(K: np.ndarray, spec: OracleCropSpec) -> np.ndarray: + """Update raw intrinsics for the exact integer-crop/resize transform.""" + + matrix = np.asarray(K, dtype=np.float32) + if matrix.shape != (3, 3): + raise ValueError(f"expected K [3,3], got {matrix.shape}") + crop_K = matrix.copy() + crop_K[0, 2] -= spec.x0 + crop_K[1, 2] -= spec.y0 + return resize_and_pad_intrinsics( + crop_K, (spec.side, spec.side), spec.output_hw, (0, 0), + ) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/samplers.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..bf66124e4179cb7965c062132f17b2124003d6c8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/samplers.py @@ -0,0 +1,240 @@ +"""Deterministic batch sampling that can resume exactly from a global step.""" + +from __future__ import annotations + +import math +import hashlib +import json +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import torch +from torch.utils.data import Sampler + + +SampleIndex = int | tuple[int, int] + + +class ResumableRandomBatchSampler(Sampler[list[SampleIndex]]): + """Generate an epoch permutation from ``seed + epoch``. + + The batch at a given global step is a pure function of the dataset size, + batch size, seed, and step. Reconstructing the sampler with ``start_step`` + therefore produces the same remaining batches after a checkpoint resume. + """ + + def __init__( + self, + dataset_size: int, + batch_size: int, + seed: int, + start_step: int, + end_step: int, + include_epoch: bool = False, + ) -> None: + if dataset_size <= 0: + raise ValueError("dataset_size must be positive") + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0 <= start_step <= end_step: + raise ValueError(f"Invalid step range: [{start_step}, {end_step})") + self.dataset_size = dataset_size + self.batch_size = batch_size + self.seed = seed + self.start_step = start_step + self.end_step = end_step + self.include_epoch = include_epoch + self.steps_per_epoch = math.ceil(dataset_size / batch_size) + + def __len__(self) -> int: + return self.end_step - self.start_step + + def __iter__(self) -> Iterator[list[SampleIndex]]: + cached_epoch = -1 + permutation: list[int] = [] + for step in range(self.start_step, self.end_step): + epoch, batch_in_epoch = divmod(step, self.steps_per_epoch) + if epoch != cached_epoch: + generator = torch.Generator().manual_seed(self.seed + epoch) + permutation = torch.randperm(self.dataset_size, generator=generator).tolist() + cached_epoch = epoch + start = batch_in_epoch * self.batch_size + indices = permutation[start : min(start + self.batch_size, self.dataset_size)] + if self.include_epoch: + yield [(index, epoch) for index in indices] + else: + yield indices + + +class ResumableWeightedBatchSampler(Sampler[list[SampleIndex]]): + """Draw a deterministic weighted epoch with replacement. + + Each epoch contains ``dataset_size`` draws. The draw sequence is a pure + function of the weights, seed, and epoch, so resuming at a global step + reproduces the uninterrupted batches exactly. + """ + + def __init__( + self, + weights: torch.Tensor | list[float], + batch_size: int, + seed: int, + start_step: int, + end_step: int, + include_epoch: bool = False, + ) -> None: + values = torch.as_tensor(weights, dtype=torch.float64, device="cpu") + if values.ndim != 1 or values.numel() == 0: + raise ValueError("weights must be a non-empty one-dimensional sequence") + if not torch.isfinite(values).all() or bool((values <= 0).any()): + raise ValueError("weights must be finite and strictly positive") + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0 <= start_step <= end_step: + raise ValueError(f"Invalid step range: [{start_step}, {end_step})") + self.weights = values + self.dataset_size = int(values.numel()) + self.batch_size = batch_size + self.seed = seed + self.start_step = start_step + self.end_step = end_step + self.include_epoch = include_epoch + self.steps_per_epoch = math.ceil(self.dataset_size / batch_size) + + def __len__(self) -> int: + return self.end_step - self.start_step + + def __iter__(self) -> Iterator[list[SampleIndex]]: + cached_epoch = -1 + draws: list[int] = [] + for step in range(self.start_step, self.end_step): + epoch, batch_in_epoch = divmod(step, self.steps_per_epoch) + if epoch != cached_epoch: + generator = torch.Generator().manual_seed(self.seed + epoch) + draws = torch.multinomial( + self.weights, + num_samples=self.dataset_size, + replacement=True, + generator=generator, + ).tolist() + cached_epoch = epoch + start = batch_in_epoch * self.batch_size + indices = draws[start : min(start + self.batch_size, self.dataset_size)] + if self.include_epoch: + yield [(index, epoch) for index in indices] + else: + yield indices + + +class ResumableMixtureBatchSampler(Sampler[list[SampleIndex]]): + """Draw an exact-resume batch from a registered dataset mixture. + + Source selection is independent of source length, so a large frame-count + dataset cannot silently dominate a registered mixture. Sampling within a + source is uniform with replacement and is a pure function of global step. + """ + + def __init__( + self, + source_sizes: list[int] | tuple[int, ...], + source_weights: list[float] | tuple[float, ...], + batch_size: int, + seed: int, + start_step: int, + end_step: int, + include_epoch: bool = False, + ) -> None: + sizes = torch.as_tensor(source_sizes, dtype=torch.int64) + weights = torch.as_tensor(source_weights, dtype=torch.float64) + if sizes.ndim != 1 or sizes.numel() == 0 or bool((sizes <= 0).any()): + raise ValueError("source_sizes must be a non-empty positive sequence") + if weights.shape != sizes.shape: + raise ValueError("source_weights must match source_sizes") + if not torch.isfinite(weights).all() or bool((weights <= 0).any()): + raise ValueError("source_weights must be finite and positive") + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0 <= start_step <= end_step: + raise ValueError(f"Invalid step range: [{start_step}, {end_step})") + self.source_sizes = sizes + self.source_weights = weights / weights.sum() + self.source_offsets = torch.cat((sizes.new_zeros(1), sizes.cumsum(0)[:-1])) + self.batch_size = int(batch_size) + self.seed = int(seed) + self.start_step = int(start_step) + self.end_step = int(end_step) + self.include_epoch = bool(include_epoch) + self.steps_per_epoch = math.ceil(int(sizes.sum()) / self.batch_size) + + def __len__(self) -> int: + return self.end_step - self.start_step + + def __iter__(self) -> Iterator[list[SampleIndex]]: + for step in range(self.start_step, self.end_step): + generator = torch.Generator().manual_seed(self.seed + step) + source_ids = torch.multinomial( + self.source_weights, + num_samples=self.batch_size, + replacement=True, + generator=generator, + ) + indices: list[SampleIndex] = [] + epoch = step // self.steps_per_epoch + for source_id in source_ids.tolist(): + local_index = int(torch.randint( + int(self.source_sizes[source_id]), + (1,), generator=generator, + )) + global_index = int(self.source_offsets[source_id]) + local_index + indices.append((global_index, epoch) if self.include_epoch else global_index) + yield indices + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_balanced_sampling_weights( + path: str | Path, + train_manifest: str | Path, + data_config: dict[str, Any], + dataset_size: int, +) -> tuple[list[float], dict[str, Any]]: + """Validate and load a train-only Phase 4 balanced-sampling manifest.""" + + manifest_path = Path(path) + train_manifest_path = Path(train_manifest) + record = json.loads(manifest_path.read_text(encoding="utf-8")) + if record.get("version") != "phase4_train_geometry_balanced_v1": + raise ValueError("unsupported balanced-sampling manifest version") + if record.get("split_role") != "official_train" or record.get("official_test_used") is not False: + raise ValueError("balanced sampling must be built from official train only") + if record.get("source_manifest_sha256") != _sha256(train_manifest_path): + raise ValueError("balanced-sampling source hash does not match --manifest") + contract = record.get("dataset_contract", {}) + expected_contract = { + "resolution_hw": list(data_config["resolution_hw"]), + "T": int(data_config["T"]), + "stride": int(data_config["stride"]), + } + for key, expected in expected_contract.items(): + if contract.get(key) != expected: + raise ValueError( + f"balanced-sampling contract mismatch for {key}: " + f"{contract.get(key)} != {expected}" + ) + rows = record.get("clips", []) + if len(rows) != dataset_size or record.get("clip_count") != dataset_size: + raise ValueError("balanced-sampling clip count does not match the training dataset") + indices = [row.get("clip_index") for row in rows] + if indices != list(range(dataset_size)): + raise ValueError("balanced-sampling clip indices must be ordered and complete") + weights = torch.as_tensor([row.get("weight") for row in rows], dtype=torch.float64) + if not torch.isfinite(weights).all() or bool((weights <= 0).any()): + raise ValueError("balanced-sampling weights must be finite and strictly positive") + return weights.tolist(), record diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/schema.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..15e3e8a1bdb388388060e4f27b01fbea4fa22104 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/data/schema.py @@ -0,0 +1,89 @@ +"""Unified multi-source sample supervision and modality contracts.""" + +from __future__ import annotations + +from typing import Mapping + +import torch + + +class InvalidSourceSampleError(RuntimeError): + """A manifest row points to missing, unreadable, or malformed source data.""" + + +SUPERVISION_MASK_KEYS = ( + "joint2d_valid", + "joint3d_valid", + "joint3d_root_relative_valid", + "translation_valid", + "mano_pose_valid", + "shape_valid", + "vertices_valid", + "reprojection_valid", + "presence_valid", + "K_supervision_valid", +) + + +def source_root_relative_joint_target( + joints_camera: torch.Tensor, + hand_valid: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Keep credible source-layer joint geometry separate from MANO compatibility.""" + + if joints_camera.shape[-2:] != (21, 3): + raise ValueError("source joints must end in [21,3]") + if hand_valid.shape != joints_camera.shape[:-2]: + raise ValueError("hand-valid mask differs from source joint prefix") + relative = joints_camera - joints_camera[..., :1, :] + valid = hand_valid[..., None] & torch.isfinite(relative).all(dim=-1) + relative = relative.masked_fill(~valid[..., None], float("nan")) + return relative, valid + +INPUT_AVAILABILITY_KEYS = ( + "depth_input_available", + "K_input_available", +) + + +def supervision_mask( + batch: Mapping[str, torch.Tensor], + key: str, + fallback: torch.Tensor, +) -> torch.Tensor: + """Resolve a Phase 7 mask while preserving historical batch behavior.""" + + value = batch.get(key) + return fallback.bool() if value is None else value.bool() + + +def input_availability( + batch: Mapping[str, torch.Tensor], + key: str, + legacy_key: str, + fallback: torch.Tensor, +) -> torch.Tensor: + """Keep model-input availability separate from geometry supervision.""" + + value = batch.get(key) + if value is None: + value = batch.get(legacy_key, fallback) + return value.bool() + + +def deterministic_clip_keep( + probability: float, + seed: int, + clip_index: int, + epoch: int, +) -> bool: + """Deterministic clip-level Bernoulli used by external input dropout.""" + + if not 0.0 <= probability <= 1.0: + raise ValueError("probability must be in [0, 1]") + generator = torch.Generator(device="cpu") + generator.manual_seed( + (int(seed) * 1_000_003 + int(clip_index) * 9_176 + int(epoch)) + % (2**63 - 1) + ) + return bool(torch.rand((), generator=generator).item() < probability) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/__init__.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..981c62ba4cc30967189bc146bb40d8fe3e3635f8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/__init__.py @@ -0,0 +1,6 @@ +"""Evaluation and visualization utilities for camera-space reconstruction.""" + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.selection import select_visualization_frames + +__all__ = ["bootstrap_take_means", "distribution_summary", "select_visualization_frames"] diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/alignment_calibration.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/alignment_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..458feac1e2e30ca149ae69fd3fa91bdb346d0d02 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/alignment_calibration.py @@ -0,0 +1,70 @@ +"""Shared feature contract for OOF metric-alignment calibration and inference.""" + +from __future__ import annotations + +import numpy as np + + +FEATURE_NAMES = ( + "raw_alignment_delta_z_m", + "log_valid_support_count", + "inlier_ratio", + "residual_scale_m", + "valid_fraction", + "foreground_fraction", + "background_fraction", + "depth_discontinuity_m", + "conditioning_quality", + "coarse_wrist_z_m", + "log_hand_scale_px", + "direct_mano_consistency_px", + "silhouette_overlap_fraction", + "coarse_velocity_z_m_per_frame", + "side_right", +) + + +def projected_hand_scale_px( + projected_joints_px: np.ndarray, + *, + source_hw: tuple[int, int], + target_hw: tuple[int, int], +) -> np.ndarray: + """Measure projected hand extent after mapping source pixels to model pixels.""" + + source_height, source_width = source_hw + target_height, target_width = target_hw + if min(source_height, source_width, target_height, target_width) <= 0: + raise ValueError("source and target image dimensions must be positive") + scale = np.asarray( + (target_width / source_width, target_height / source_height), dtype=np.float32, + ) + resized = np.asarray(projected_joints_px, dtype=np.float32) * scale + return np.ptp(resized, axis=-2).max(axis=-1) + + +def features_from_take(arrays: dict[str, np.ndarray]) -> np.ndarray: + """Create `[time,left/right,feature]` geometry-only calibration inputs.""" + + time = len(arrays["frame_id"]) + side_right = np.broadcast_to(np.asarray((0.0, 1.0), dtype=np.float32), (time, 2)) + overlap = np.broadcast_to(arrays["silhouette_overlap_fraction"][:, None], (time, 2)) + values = ( + arrays["alignment_delta_z_m"], + np.log1p(arrays["alignment_valid_support_count"]), + arrays["alignment_inlier_ratio"], + arrays["alignment_residual_scale_m"], + arrays["alignment_valid_fraction"], + arrays["alignment_foreground_fraction"], + arrays["alignment_background_fraction"], + arrays["alignment_depth_discontinuity_m"], + arrays["alignment_conditioning_quality"], + arrays["pred_wrist_translation"][..., 2], + np.log1p(np.maximum(arrays["coarse_hand_scale_px"], 0.0)), + arrays["coarse_direct_mano_consistency_px"], + overlap, + arrays["coarse_wrist_velocity_m_per_frame"][..., 2], + side_right, + ) + features = np.stack(values, axis=-1).astype(np.float64) + return np.nan_to_num(features, nan=0.0, posinf=0.0, neginf=0.0) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/causal_state.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..66dea1ca7230f736d8ffb5f32f645ed7b862f4b7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/causal_state.py @@ -0,0 +1,121 @@ +"""Causal translation-z state estimators for Phase 5 deployment.""" + +from __future__ import annotations + +import numpy as np + + +def measurement_uncertainty_multiplier( + confidence: np.ndarray, + inlier_ratio: np.ndarray, + residual_scale_m: np.ndarray, + valid_fraction: np.ndarray, + conditioning_quality: np.ndarray, + strength: float, +) -> np.ndarray: + """Map bounded geometry diagnostics to a deterministic measurement-noise scale.""" + + if strength < 0.0: + raise ValueError("uncertainty strength must be non-negative") + components = np.stack(( + 1.0 - np.clip(confidence, 0.0, 1.0), + 1.0 - np.clip(inlier_ratio, 0.0, 1.0), + np.clip(residual_scale_m / 0.02, 0.0, 2.0) / 2.0, + 1.0 - np.clip(valid_fraction, 0.0, 1.0), + 1.0 - np.clip(conditioning_quality, 0.0, 1.0), + ), axis=-1) + return np.clip(1.0 + strength * components.mean(axis=-1), 1.0, 5.0) + + +def causal_constant_velocity_kalman( + measurement_m: np.ndarray, + *, + frame_id: np.ndarray, + segment_id: np.ndarray | None = None, + valid: np.ndarray, + measurement_available: np.ndarray, + process_sigma_m_per_frame2: float, + measurement_sigma_m: float, + uncertainty_multiplier: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray]: + """Filter `[time,hand]` z measurements without crossing invalid/discontinuous frames.""" + + measurement = np.asarray(measurement_m, dtype=np.float64) + frame_id = np.asarray(frame_id, dtype=np.int64) + segment = ( + np.zeros(len(measurement), dtype=np.int64) + if segment_id is None else np.asarray(segment_id) + ) + valid = np.asarray(valid, dtype=bool) + available = np.asarray(measurement_available, dtype=bool) + if measurement.ndim != 2 or measurement.shape[1] != 2: + raise ValueError("measurement_m must have shape [time,2]") + if ( + frame_id.shape != (len(measurement),) + or segment.shape != (len(measurement),) + or valid.shape != (len(measurement),) + ): + raise ValueError("frame_id, segment_id, and valid must have shape [time]") + if available.shape != measurement.shape: + raise ValueError("measurement_available must match measurement_m") + if process_sigma_m_per_frame2 <= 0.0 or measurement_sigma_m <= 0.0: + raise ValueError("Kalman noise scales must be positive") + if uncertainty_multiplier is None: + multiplier = np.ones_like(measurement) + else: + multiplier = np.asarray(uncertainty_multiplier, dtype=np.float64) + if multiplier.shape != measurement.shape or np.any(multiplier < 1.0): + raise ValueError("uncertainty_multiplier must match measurements and be >=1") + + output = measurement.copy() + variance = np.full_like(measurement, np.nan) + transition = np.asarray(((1.0, 1.0), (0.0, 1.0)), dtype=np.float64) + observation = np.asarray((1.0, 0.0), dtype=np.float64) + q = process_sigma_m_per_frame2**2 * np.asarray( + ((0.25, 0.5), (0.5, 1.0)), dtype=np.float64, + ) + + for hand in range(2): + initialized = False + state = np.zeros(2, dtype=np.float64) + covariance = np.eye(2, dtype=np.float64) + previous_frame = -1 + previous_segment: object = None + for index in range(len(measurement)): + contiguous = ( + initialized + and frame_id[index] == previous_frame + 1 + and segment[index] == previous_segment + ) + if not valid[index] or not contiguous: + initialized = False + if not valid[index]: + output[index, hand] = measurement[index, hand] + previous_frame = int(frame_id[index]) + previous_segment = segment[index] + continue + if not initialized: + if not available[index, hand] or not np.isfinite(measurement[index, hand]): + output[index, hand] = measurement[index, hand] + previous_frame = int(frame_id[index]) + previous_segment = segment[index] + continue + state[:] = (measurement[index, hand], 0.0) + initial_variance = (measurement_sigma_m * multiplier[index, hand]) ** 2 + covariance = np.diag((initial_variance, 4.0 * initial_variance)) + initialized = True + else: + state = transition @ state + covariance = transition @ covariance @ transition.T + q + if available[index, hand] and np.isfinite(measurement[index, hand]): + r = (measurement_sigma_m * multiplier[index, hand]) ** 2 + innovation = measurement[index, hand] - observation @ state + innovation_variance = float(observation @ covariance @ observation + r) + gain = covariance @ observation / innovation_variance + state = state + gain * innovation + covariance = (np.eye(2) - np.outer(gain, observation)) @ covariance + output[index, hand] = state[0] + variance[index, hand] = covariance[0, 0] + previous_frame = int(frame_id[index]) + previous_segment = segment[index] + return output.astype(np.float32), variance.astype(np.float32) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/harm_risk.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc2a46bd4f7c4cdcee6de1fbb10dfb6b37add31 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/harm_risk.py @@ -0,0 +1,71 @@ +"""Predicted-only feature contract for Phase 6 harmful-correction risk.""" + +from __future__ import annotations + +import numpy as np + + +HARM_RISK_FEATURE_NAMES = ( + "calibrated_delta_z_m", "abs_calibrated_delta_z_m", + "raw_delta_z_m", "abs_raw_delta_z_m", "raw_calibrated_disagreement_m", + "existing_confidence", "alignment_available", "raw_alignment_available", + "valid_support_count", "projected_support_count", "inlier_ratio", + "residual_scale_m", "valid_fraction", "foreground_fraction", + "background_fraction", "depth_discontinuity_m", "conditioning_quality", + "silhouette_overlap_fraction", "coarse_hand_scale_px", + "coarse_direct_mano_consistency_px", "coarse_z_m", "coarse_ray_x", + "coarse_ray_y", "coarse_wrist_velocity_norm_m_per_frame", + "predicted_depth_order", "side_right", +) + + +def harm_risk_features( + *, + calibrated_delta_z_m: np.ndarray, + raw_delta_z_m: np.ndarray, + confidence: np.ndarray, + alignment_available: np.ndarray, + raw_alignment_available: np.ndarray, + valid_support_count: np.ndarray, + projected_support_count: np.ndarray, + inlier_ratio: np.ndarray, + residual_scale_m: np.ndarray, + valid_fraction: np.ndarray, + foreground_fraction: np.ndarray, + background_fraction: np.ndarray, + depth_discontinuity_m: np.ndarray, + conditioning_quality: np.ndarray, + silhouette_overlap_fraction: np.ndarray, + coarse_hand_scale_px: np.ndarray, + coarse_direct_mano_consistency_px: np.ndarray, + coarse_wrist_translation: np.ndarray, + coarse_wrist_velocity_m_per_frame: np.ndarray, + predicted_depth_order: np.ndarray, +) -> np.ndarray: + calibrated = np.asarray(calibrated_delta_z_m, dtype=np.float64) + raw = np.asarray(raw_delta_z_m, dtype=np.float64) + if calibrated.ndim != 2 or calibrated.shape[1] != 2 or raw.shape != calibrated.shape: + raise ValueError("risk delta-z arrays must have shape [time,2]") + time = len(calibrated) + overlap = np.broadcast_to( + np.asarray(silhouette_overlap_fraction)[:, None], (time, 2), + ) + depth_order = np.broadcast_to( + np.asarray(predicted_depth_order)[:, None], (time, 2), + ) + side = np.broadcast_to(np.asarray((0.0, 1.0)), (time, 2)) + translation = np.asarray(coarse_wrist_translation, dtype=np.float64) + z = np.maximum(translation[..., 2], 1e-6) + velocity_norm = np.linalg.norm(coarse_wrist_velocity_m_per_frame, axis=-1) + values = ( + calibrated, np.abs(calibrated), raw, np.abs(raw), np.abs(raw - calibrated), + confidence, alignment_available, raw_alignment_available, + valid_support_count, projected_support_count, inlier_ratio, + residual_scale_m, valid_fraction, foreground_fraction, + background_fraction, depth_discontinuity_m, conditioning_quality, + overlap, coarse_hand_scale_px, coarse_direct_mano_consistency_px, + translation[..., 2], translation[..., 0] / z, translation[..., 1] / z, + velocity_norm, depth_order, side, + ) + features = np.stack(values, axis=-1).astype(np.float32) + return np.nan_to_num(features, nan=0.0, posinf=1e6, neginf=-1e6) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/local_depth.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7ba9904db72607171a18a6c7415efd2a09ffdf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/local_depth.py @@ -0,0 +1,231 @@ +"""Oracle local-depth feature extraction and bounded wrist-z residual models.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +import torch +from torch import nn + + +ANCHOR_JOINTS = (0, 4, 5, 8, 9, 12, 13, 16, 17, 20) +WINDOW_RADII = (3, 7, 15) +BBOX_MARGINS = (0.10, 0.30, 0.60) +DEPTH_STAT_NAMES = ( + "valid_fraction", + "q10_m", + "q25_m", + "q50_m", + "q75_m", + "q90_m", + "iqr_m", + "discontinuity_m", +) + + +def _depth_statistics(depth_m: np.ndarray, valid: np.ndarray) -> np.ndarray: + mask = np.asarray(valid, dtype=bool) & np.isfinite(depth_m) & (depth_m > 0.0) + valid_fraction = float(mask.mean()) if mask.size else 0.0 + values = np.asarray(depth_m, dtype=np.float64)[mask] + if not values.size: + return np.asarray([valid_fraction, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], dtype=np.float32) + q10, q25, q50, q75, q90 = np.percentile(values, (10, 25, 50, 75, 90)) + return np.asarray([ + valid_fraction, + q10, + q25, + q50, + q75, + q90, + q75 - q25, + q90 - q10, + ], dtype=np.float32) + + +def _clipped_region( + center_xy: np.ndarray, + half_size_xy: np.ndarray, + image_hw: tuple[int, int], +) -> tuple[slice, slice]: + height, width = image_hw + x0 = max(0, int(np.floor(float(center_xy[0] - half_size_xy[0])))) + y0 = max(0, int(np.floor(float(center_xy[1] - half_size_xy[1])))) + x1 = min(width, int(np.ceil(float(center_xy[0] + half_size_xy[0]))) + 1) + y1 = min(height, int(np.ceil(float(center_xy[1] + half_size_xy[1]))) + 1) + return slice(y0, max(y0, y1)), slice(x0, max(x0, x1)) + + +def _geometry_from_median( + center_xy: np.ndarray, + median_depth_m: float, + K: np.ndarray, +) -> np.ndarray: + if median_depth_m <= 0.0 or not np.isfinite(median_depth_m): + return np.zeros(5, dtype=np.float32) + x_ray = (float(center_xy[0]) - float(K[0, 2])) / float(K[0, 0]) + y_ray = (float(center_xy[1]) - float(K[1, 2])) / float(K[1, 1]) + return np.asarray([ + x_ray * median_depth_m, + y_ray * median_depth_m, + median_depth_m, + np.log(max(median_depth_m, 1e-6)), + 1.0, + ], dtype=np.float32) + + +@dataclass(frozen=True) +class OracleLocalDepthFeatures: + control: np.ndarray + local: np.ndarray + control_names: tuple[str, ...] + local_names: tuple[str, ...] + local_valid_fraction: float + local_depth_discontinuity_m: float + + +def oracle_local_depth_features( + depth_m: np.ndarray, + depth_valid: np.ndarray, + joints_2d_raw: np.ndarray, + K_raw: np.ndarray, + coarse_translation_m: np.ndarray, + side_index: int, +) -> OracleLocalDepthFeatures: + """Extract oracle-location features without using GT wrist depth as input.""" + + depth_m = np.asarray(depth_m, dtype=np.float32) + depth_valid = np.asarray(depth_valid, dtype=bool) + joints = np.asarray(joints_2d_raw, dtype=np.float32) + K = np.asarray(K_raw, dtype=np.float32) + coarse = np.asarray(coarse_translation_m, dtype=np.float32) + if depth_m.ndim != 2 or depth_valid.shape != depth_m.shape: + raise ValueError("raw metric depth and validity must be aligned HxW arrays") + if joints.shape != (21, 2) or K.shape != (3, 3) or coarse.shape != (3,): + raise ValueError("unexpected joint/K/coarse feature shape") + if side_index not in (0, 1): + raise ValueError("side_index must be 0 for left or 1 for right") + + height, width = depth_m.shape + finite = np.isfinite(joints).all(axis=-1) + if finite.any(): + minimum = joints[finite].min(axis=0) + maximum = joints[finite].max(axis=0) + center = 0.5 * (minimum + maximum) + extent = np.maximum(maximum - minimum, 1.0) + else: + center = np.asarray([width / 2.0, height / 2.0], dtype=np.float32) + extent = np.ones(2, dtype=np.float32) + + control_names = ( + "coarse_x_m", + "coarse_y_m", + "coarse_z_m", + "log_coarse_z", + "bbox_center_u_norm", + "bbox_center_v_norm", + "bbox_width_norm", + "bbox_height_norm", + "fx_norm", + "fy_norm", + "cx_norm", + "cy_norm", + "side_left", + "side_right", + ) + control = np.asarray([ + coarse[0], + coarse[1], + coarse[2], + np.log(max(float(coarse[2]), 1e-6)), + center[0] / width, + center[1] / height, + extent[0] / width, + extent[1] / height, + K[0, 0] / width, + K[1, 1] / height, + K[0, 2] / width, + K[1, 2] / height, + float(side_index == 0), + float(side_index == 1), + ], dtype=np.float32) + + local_values: list[float] = [] + local_names: list[str] = [] + anchor_validities: list[float] = [] + anchor_discontinuities: list[float] = [] + for joint_index in ANCHOR_JOINTS: + joint_center = joints[joint_index] if finite[joint_index] else center + for radius in WINDOW_RADII: + y_slice, x_slice = _clipped_region( + joint_center, + np.asarray([radius, radius], dtype=np.float32), + (height, width), + ) + statistics = _depth_statistics( + depth_m[y_slice, x_slice], depth_valid[y_slice, x_slice] + ) + geometry = _geometry_from_median(joint_center, float(statistics[3]), K) + prefix = f"joint{joint_index:02d}_r{radius}" + local_values.extend(statistics.tolist()) + local_names.extend(f"{prefix}_{name}" for name in DEPTH_STAT_NAMES) + local_values.extend(geometry.tolist()) + local_names.extend( + f"{prefix}_{name}" for name in ("median_x_m", "median_y_m", "median_z_m", "log_median_z", "median_valid") + ) + local_values.append(float(statistics[3] - coarse[2]) if statistics[0] > 0 else 0.0) + local_names.append(f"{prefix}_median_minus_coarse_z_m") + anchor_validities.append(float(statistics[0])) + anchor_discontinuities.append(float(statistics[7])) + + for margin in BBOX_MARGINS: + half_size = np.maximum(extent * (0.5 + margin), 4.0) + y_slice, x_slice = _clipped_region(center, half_size, (height, width)) + statistics = _depth_statistics(depth_m[y_slice, x_slice], depth_valid[y_slice, x_slice]) + geometry = _geometry_from_median(center, float(statistics[3]), K) + prefix = f"bbox_m{int(round(margin * 100)):02d}" + local_values.extend(statistics.tolist()) + local_names.extend(f"{prefix}_{name}" for name in DEPTH_STAT_NAMES) + local_values.extend(geometry.tolist()) + local_names.extend( + f"{prefix}_{name}" for name in ("median_x_m", "median_y_m", "median_z_m", "log_median_z", "median_valid") + ) + local_values.append(float(statistics[3] - coarse[2]) if statistics[0] > 0 else 0.0) + local_names.append(f"{prefix}_median_minus_coarse_z_m") + + local_array = np.asarray(local_values, dtype=np.float32) + if not np.isfinite(control).all() or not np.isfinite(local_array).all(): + raise ValueError("oracle local-depth feature extraction produced non-finite values") + return OracleLocalDepthFeatures( + control=control, + local=np.concatenate((control, local_array)).astype(np.float32), + control_names=control_names, + local_names=control_names + tuple(local_names), + local_valid_fraction=float(np.mean(anchor_validities)), + local_depth_discontinuity_m=float(np.mean(anchor_discontinuities)), + ) + + +class BoundedZResidualRegressor(nn.Module): + """Small zero-initialized residual MLP for an oracle diagnostic.""" + + def __init__( + self, + input_dim: int, + hidden_dim: int = 128, + max_residual_m: float = 0.15, + ) -> None: + super().__init__() + self.max_residual_m = float(max_residual_m) + self.network = nn.Sequential( + nn.Linear(input_dim, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, 1), + ) + nn.init.zeros_(self.network[-1].weight) + nn.init.zeros_(self.network[-1].bias) + + def forward(self, features: torch.Tensor) -> torch.Tensor: + return self.max_residual_m * torch.tanh(self.network(features).squeeze(-1)) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/metric_alignment.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/metric_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..918bb5bbce077ed9b0fdd77cdc2c0911ee799004 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/metric_alignment.py @@ -0,0 +1,333 @@ +"""Predicted-MANO to observed-depth alignment for deployable wrist-z correction.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass + +import cv2 +import numpy as np + +from foundation_hand.geometry.camera import project_points + + +@dataclass(frozen=True) +class AlignmentDiagnostics: + delta_z_m: float + applied: bool + valid_support_count: int + projected_support_count: int + inlier_ratio: float + residual_scale_m: float + valid_fraction: float + foreground_fraction: float + background_fraction: float + depth_discontinuity_m: float + conditioning_quality: float + + def as_dict(self) -> dict[str, float | int | bool]: + return asdict(self) + + +@dataclass(frozen=True) +class SurfaceSamples: + projected_vertices_px: np.ndarray + predicted_depth_m: np.ndarray + observed_depth_m: np.ndarray + visible_vertex: np.ndarray + sample_valid: np.ndarray + local_discontinuity_m: np.ndarray + silhouette_packed: np.ndarray + silhouette_hw: tuple[int, int] + + +def _empty_diagnostics(projected: int = 0) -> AlignmentDiagnostics: + return AlignmentDiagnostics( + delta_z_m=0.0, + applied=False, + valid_support_count=0, + projected_support_count=int(projected), + inlier_ratio=0.0, + residual_scale_m=0.0, + valid_fraction=0.0, + foreground_fraction=0.0, + background_fraction=0.0, + depth_discontinuity_m=0.0, + conditioning_quality=0.0, + ) + + +def robust_location_irls( + residuals_m: np.ndarray, + *, + base_weights: np.ndarray | None = None, + huber_k: float = 1.345, + iterations: int = 8, + minimum_scale_m: float = 0.003, + maximum_delta_m: float = 0.12, +) -> tuple[float, float, float]: + """Estimate a bounded common translation with MAD-scaled Huber IRLS.""" + + residuals = np.asarray(residuals_m, dtype=np.float64).reshape(-1) + finite = np.isfinite(residuals) + residuals = residuals[finite] + if not residuals.size: + return 0.0, 0.0, 0.0 + if base_weights is None: + weights = np.ones_like(residuals) + else: + input_weights = np.asarray(base_weights, dtype=np.float64).reshape(-1)[finite] + weights = np.clip(input_weights, 0.0, None) + if not np.any(weights > 0.0): + return 0.0, 0.0, 0.0 + + location = float(np.median(residuals)) + scale = max( + minimum_scale_m, + 1.4826 * float(np.median(np.abs(residuals - location))), + ) + for _ in range(iterations): + standardized = np.abs(residuals - location) / scale + robust = np.ones_like(standardized) + outside = standardized > huber_k + robust[outside] = huber_k / standardized[outside] + combined = weights * robust + if combined.sum() <= 1e-12: + return 0.0, scale, 0.0 + updated = float(np.sum(combined * residuals) / np.sum(combined)) + if abs(updated - location) < 1e-7: + location = updated + break + location = updated + location = float(np.clip(location, -maximum_delta_m, maximum_delta_m)) + inlier_ratio = float(np.mean(np.abs(residuals - location) <= huber_k * scale)) + return location, scale, inlier_ratio + + +def _visible_vertex_mask( + pixels: np.ndarray, + depth_m: np.ndarray, + image_hw: tuple[int, int], + cell_size: int, +) -> np.ndarray: + height, width = image_hw + finite = np.isfinite(pixels).all(axis=-1) & np.isfinite(depth_m) & (depth_m > 0.0) + inside = finite & (pixels[:, 0] >= 0) & (pixels[:, 0] < width) & ( + pixels[:, 1] >= 0 + ) & (pixels[:, 1] < height) + visible = np.zeros(len(pixels), dtype=bool) + indices = np.where(inside)[0] + if not len(indices): + return visible + cells_x = np.floor(pixels[indices, 0] / cell_size).astype(np.int64) + cells_y = np.floor(pixels[indices, 1] / cell_size).astype(np.int64) + cell_width = (width + cell_size - 1) // cell_size + cell_ids = cells_y * cell_width + cells_x + order = np.lexsort((depth_m[indices], cell_ids)) + sorted_ids = cell_ids[order] + first = np.r_[True, sorted_ids[1:] != sorted_ids[:-1]] + visible[indices[order[first]]] = True + return visible + + +def _sample_depth_regions( + depth_m: np.ndarray, + depth_valid: np.ndarray, + pixels: np.ndarray, + radius: int, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + height, width = depth_m.shape + count = len(pixels) + observed = np.full(count, np.nan, dtype=np.float32) + valid = np.zeros(count, dtype=bool) + discontinuity = np.full(count, np.nan, dtype=np.float32) + finite_pixels = np.isfinite(pixels).all(axis=-1) + centers = np.rint(np.where(finite_pixels[:, None], pixels, 0.0)).astype(np.int64) + offsets = np.arange(-radius, radius + 1, dtype=np.int64) + offset_y, offset_x = np.meshgrid(offsets, offsets, indexing="ij") + sample_x = centers[:, 0, None] + offset_x.reshape(1, -1) + sample_y = centers[:, 1, None] + offset_y.reshape(1, -1) + inside = finite_pixels[:, None] & (sample_x >= 0) & (sample_x < width) & ( + sample_y >= 0 + ) & (sample_y < height) + clipped_x = np.clip(sample_x, 0, width - 1) + clipped_y = np.clip(sample_y, 0, height - 1) + values = depth_m[clipped_y, clipped_x] + sample_valid = inside & depth_valid[clipped_y, clipped_x] & np.isfinite(values) & ( + values > 0.0 + ) + eligible = sample_valid.any(axis=1) + if np.any(eligible): + eligible_valid = sample_valid[eligible] + sorted_values = np.sort( + np.where(eligible_valid, values[eligible], np.inf), axis=1, + ) + counts = eligible_valid.sum(axis=1) + + def row_percentile(quantile: float) -> np.ndarray: + position = (counts - 1) * quantile + lower = np.floor(position).astype(np.int64) + upper = np.ceil(position).astype(np.int64) + fraction = position - lower + lower_value = np.take_along_axis(sorted_values, lower[:, None], axis=1)[:, 0] + upper_value = np.take_along_axis(sorted_values, upper[:, None], axis=1)[:, 0] + difference = upper_value - lower_value + interpolated = lower_value + difference * fraction + upper_stable = fraction >= 0.5 + interpolated[upper_stable] = ( + upper_value[upper_stable] + - difference[upper_stable] * (1.0 - fraction[upper_stable]) + ) + return interpolated + + q10, q50, q90 = (row_percentile(quantile) for quantile in (0.1, 0.5, 0.9)) + observed[eligible] = q50.astype(np.float32) + discontinuity[eligible] = (q90 - q10).astype(np.float32) + valid[eligible] = True + return observed, valid, discontinuity + + +def conservative_silhouette( + projected_vertices_px: np.ndarray, + visible_vertex: np.ndarray, + image_hw: tuple[int, int], + *, + downsample: int = 4, +) -> tuple[np.ndarray, tuple[int, int]]: + """Return a packed conservative projected-hull mask for bank/audit storage.""" + + height, width = image_hw + output_hw = ( + (height + downsample - 1) // downsample, + (width + downsample - 1) // downsample, + ) + mask = np.zeros(output_hw, dtype=np.uint8) + points = np.asarray(projected_vertices_px, dtype=np.float32)[visible_vertex] + points = points[np.isfinite(points).all(axis=-1)] / float(downsample) + if len(points) >= 3: + hull = cv2.convexHull(np.rint(points).astype(np.int32)) + cv2.fillConvexPoly(mask, hull, 1) + packed = np.packbits(mask.reshape(-1), bitorder="little") + return packed, output_hw + + +def sample_predicted_surface( + vertices_camera_m: np.ndarray, + K: np.ndarray, + depth_m: np.ndarray, + depth_valid: np.ndarray, + *, + cell_size: int = 4, + sample_radius: int = 2, + silhouette_downsample: int = 4, +) -> SurfaceSamples: + vertices = np.asarray(vertices_camera_m, dtype=np.float32) + depth = np.asarray(depth_m, dtype=np.float32) + valid = np.asarray(depth_valid, dtype=bool) + matrix = np.asarray(K, dtype=np.float32) + if vertices.ndim != 2 or vertices.shape[1] != 3: + raise ValueError("vertices must have shape [V,3]") + if depth.ndim != 2 or valid.shape != depth.shape or matrix.shape != (3, 3): + raise ValueError("depth, validity, or K shape mismatch") + pixels, positive = project_points(vertices, matrix) + visible = _visible_vertex_mask(pixels, vertices[:, 2], depth.shape, cell_size) + visible &= positive + observed, sample_valid, discontinuity = _sample_depth_regions( + depth, valid, pixels, sample_radius, + ) + sample_valid &= visible + packed, silhouette_hw = conservative_silhouette( + pixels, visible, depth.shape, downsample=silhouette_downsample, + ) + return SurfaceSamples( + projected_vertices_px=pixels.astype(np.float32), + predicted_depth_m=vertices[:, 2].astype(np.float32), + observed_depth_m=observed, + visible_vertex=visible, + sample_valid=sample_valid, + local_discontinuity_m=discontinuity, + silhouette_packed=packed, + silhouette_hw=silhouette_hw, + ) + + +def solve_wrist_delta_z( + samples: SurfaceSamples, + *, + minimum_support: int = 20, + maximum_raw_residual_m: float = 0.15, + discontinuity_scale_m: float = 0.04, + maximum_delta_m: float = 0.12, +) -> AlignmentDiagnostics: + residuals = samples.observed_depth_m - samples.predicted_depth_m + projected_count = int(samples.visible_vertex.sum()) + candidate = samples.sample_valid & np.isfinite(residuals) & ( + np.abs(residuals) <= maximum_raw_residual_m + ) + count = int(candidate.sum()) + if count < minimum_support: + return _empty_diagnostics(projected_count) + values = residuals[candidate].astype(np.float64) + discontinuity = samples.local_discontinuity_m[candidate].astype(np.float64) + weights = 1.0 / (1.0 + np.square(discontinuity / discontinuity_scale_m)) + delta, scale, inlier_ratio = robust_location_irls( + values, base_weights=weights, maximum_delta_m=maximum_delta_m, + ) + foreground_fraction = float(np.mean(values < delta - max(0.02, 2.5 * scale))) + background_fraction = float(np.mean(values > delta + max(0.03, 2.5 * scale))) + valid_fraction = count / max(projected_count, 1) + support_score = min(1.0, count / 80.0) + scale_score = float(np.exp(-scale / 0.025)) + contamination_score = max(0.0, 1.0 - foreground_fraction - background_fraction) + quality = float(np.clip( + support_score * inlier_ratio * scale_score * contamination_score, + 0.0, 1.0, + )) + return AlignmentDiagnostics( + delta_z_m=delta, + applied=True, + valid_support_count=count, + projected_support_count=projected_count, + inlier_ratio=inlier_ratio, + residual_scale_m=scale, + valid_fraction=valid_fraction, + foreground_fraction=foreground_fraction, + background_fraction=background_fraction, + depth_discontinuity_m=float(np.nanmedian(discontinuity)), + conditioning_quality=quality, + ) + + +def align_wrist_z( + vertices_camera_m: np.ndarray, + K: np.ndarray | None, + depth_m: np.ndarray | None, + depth_valid: np.ndarray | None, + *, + minimum_support: int = 20, +) -> tuple[AlignmentDiagnostics, SurfaceSamples | None]: + if K is None or depth_m is None or depth_valid is None: + return _empty_diagnostics(), None + matrix = np.asarray(K) + if matrix.shape != (3, 3) or not np.isfinite(matrix).all() or min( + float(matrix[0, 0]), float(matrix[1, 1]) + ) <= 0.0: + return _empty_diagnostics(), None + samples = sample_predicted_surface( + vertices_camera_m, matrix, depth_m, depth_valid, + ) + return solve_wrist_delta_z(samples, minimum_support=minimum_support), samples + + +def apply_translation_delta_z( + translation_m: np.ndarray, + joints_m: np.ndarray, + vertices_m: np.ndarray, + delta_z_m: float, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + translation = np.asarray(translation_m, dtype=np.float32).copy() + joints = np.asarray(joints_m, dtype=np.float32).copy() + vertices = np.asarray(vertices_m, dtype=np.float32).copy() + translation[..., 2] += float(delta_z_m) + joints[..., 2] += float(delta_z_m) + vertices[..., 2] += float(delta_z_m) + return translation, joints, vertices diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/metrics.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..2f904f95c1ee76ed1b12b0debaa6126225acc9c9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/metrics.py @@ -0,0 +1,100 @@ +"""Distribution summaries and take-level uncertainty estimates.""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence + +import numpy as np + + +PERCENTILES = (50, 90, 95, 99) + + +def finite_array(values: Iterable[float | int | None]) -> np.ndarray: + array = np.asarray([value for value in values if value is not None], dtype=np.float64) + return array[np.isfinite(array)] + + +def distribution_summary(values: Iterable[float | int | None]) -> dict[str, float | int | None]: + """Return central statistics, fixed tail percentiles, and upper-tail CVaR.""" + + array = finite_array(values) + if array.size == 0: + return { + "count": 0, + "mean": None, + "std": None, + **{f"p{percentile}": None for percentile in PERCENTILES}, + "cvar95": None, + } + p95 = float(np.percentile(array, 95)) + return { + "count": int(array.size), + "mean": float(array.mean()), + "std": float(array.std(ddof=0)), + **{ + f"p{percentile}": float(np.percentile(array, percentile)) + for percentile in PERCENTILES + }, + "cvar95": float(array[array >= p95].mean()), + } + + +def bootstrap_take_means( + rows: Sequence[Mapping[str, object]], + metric_names: Sequence[str], + *, + take_key: str = "take", + seed: int = 20260716, + samples: int = 10_000, +) -> list[dict[str, float | int | str | None]]: + """Bootstrap equally weighted take means and return percentile 95% CIs. + + Frame/hand observations are first averaged within each take. Resampling then + operates on takes, which avoids treating adjacent video frames as independent. + """ + + if samples <= 0: + raise ValueError("samples must be positive") + grouped: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for row in rows: + take = str(row[take_key]) + for metric in metric_names: + value = row.get(metric) + if value is None: + continue + number = float(value) + if np.isfinite(number): + grouped[take][metric].append(number) + + rng = np.random.default_rng(seed) + output: list[dict[str, float | int | str | None]] = [] + for metric in metric_names: + take_values = np.asarray( + [np.mean(items[metric]) for items in grouped.values() if items.get(metric)], + dtype=np.float64, + ) + if take_values.size == 0: + output.append({ + "metric": metric, + "take_count": 0, + "take_mean": None, + "ci95_low": None, + "ci95_high": None, + "bootstrap_samples": samples, + "seed": seed, + }) + continue + indices = rng.integers(0, take_values.size, size=(samples, take_values.size)) + bootstrap = take_values[indices].mean(axis=1) + output.append({ + "metric": metric, + "take_count": int(take_values.size), + "take_mean": float(take_values.mean()), + "ci95_low": float(np.percentile(bootstrap, 2.5)), + "ci95_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..ce3762b44d153f24c7d08a7639fb51bb788602e9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/mixed_projection.py @@ -0,0 +1,248 @@ +"""Predicted-anchor mixed-projection translation assembly.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + + +@dataclass(frozen=True) +class MixedProjectionBatchResult: + translation_m: np.ndarray + support_count: np.ndarray + residual_scale_px: np.ndarray + conditioning: np.ndarray + inlier_ratio: np.ndarray + uncertainty_xy_m: np.ndarray + failure_reason: np.ndarray + + +def coarse_wrist_ray_translation( + coarse_translation_m: np.ndarray, + refined_z_m: np.ndarray, + *, + minimum_depth_m: float = 0.05, +) -> np.ndarray: + """Change z while preserving the coarse camera ray.""" + + coarse = np.asarray(coarse_translation_m, dtype=np.float64) + z = np.asarray(refined_z_m, dtype=np.float64) + if coarse.shape[:-1] != z.shape or coarse.shape[-1] != 3: + raise ValueError("coarse translation and refined z shapes differ") + output = coarse.copy() + valid = ( + np.isfinite(coarse).all(axis=-1) + & np.isfinite(z) + & (coarse[..., 2] > minimum_depth_m) + & (z > minimum_depth_m) + ) + ratio = np.ones_like(z) + ratio[valid] = z[valid] / coarse[..., 2][valid] + output[..., :2] *= ratio[..., None] + output[..., 2] = np.where(np.isfinite(z), z, coarse[..., 2]) + return output + + +def direct_wrist_ray_translation( + anchors_px: np.ndarray, + intrinsics: np.ndarray, + refined_z_m: np.ndarray, + fallback_translation_m: np.ndarray, + *, + minimum_depth_m: float = 0.05, +) -> tuple[np.ndarray, np.ndarray]: + """Back-project the predicted direct-2D wrist at the selected depth.""" + + anchors = np.asarray(anchors_px, dtype=np.float64) + K = np.asarray(intrinsics, dtype=np.float64) + z = np.asarray(refined_z_m, dtype=np.float64) + fallback = np.asarray(fallback_translation_m, dtype=np.float64) + if anchors.shape[-2:] != (21, 2) or K.shape[-2:] != (3, 3): + raise ValueError("unexpected anchor or K shape") + output = fallback.copy() + wrist = anchors[..., 0, :] + fx, fy = K[..., 0, 0], K[..., 1, 1] + cx, cy = K[..., 0, 2], K[..., 1, 2] + valid = ( + np.isfinite(wrist).all(axis=-1) + & np.isfinite(K).all(axis=(-2, -1)) + & np.isfinite(z) + & (fx > 1e-8) + & (fy > 1e-8) + & (z > minimum_depth_m) + ) + output[..., 0] = np.where(valid, (wrist[..., 0] - cx) * z / fx, output[..., 0]) + output[..., 1] = np.where(valid, (wrist[..., 1] - cy) * z / fy, output[..., 1]) + output[..., 2] = np.where(np.isfinite(z), z, output[..., 2]) + return output, valid + + +def solve_mixed_projection_batch( + root_relative_joints_m: np.ndarray, + anchors_px: np.ndarray, + intrinsics: np.ndarray, + refined_z_m: np.ndarray, + fallback_translation_m: np.ndarray, + *, + image_hw: tuple[int, int], + minimum_support: int = 8, + robust_huber_delta_px: float | None = None, + irls_iterations: int = 5, + minimum_joint_depth_m: float = 0.05, + denominator_epsilon: float = 1e-10, +) -> MixedProjectionBatchResult: + """Solve tx/ty from predicted 2D anchors and MANO root-relative joints. + + Every solve mask is derived from predicted quantities. Failed solves keep + the supplied fallback x/y and the selected finite z. + """ + + joints = np.asarray(root_relative_joints_m, dtype=np.float64) + anchors = np.asarray(anchors_px, dtype=np.float64) + K = np.asarray(intrinsics, dtype=np.float64) + z = np.asarray(refined_z_m, dtype=np.float64) + fallback = np.asarray(fallback_translation_m, dtype=np.float64) + if joints.ndim != 3 or joints.shape[1:] != (21, 3): + raise ValueError(f"expected joints [N,21,3], got {joints.shape}") + count = joints.shape[0] + expected = { + "anchors": (count, 21, 2), + "intrinsics": (count, 3, 3), + "refined z": (count,), + "fallback": (count, 3), + } + for name, shape in expected.items(): + value = {"anchors": anchors, "intrinsics": K, "refined z": z, "fallback": fallback}[name] + if value.shape != shape: + raise ValueError(f"expected {name} {shape}, got {value.shape}") + if not 1 <= minimum_support <= 21: + raise ValueError("minimum_support must be in [1,21]") + if robust_huber_delta_px is not None and robust_huber_delta_px <= 0.0: + raise ValueError("Huber delta must be positive") + if irls_iterations < 1: + raise ValueError("IRLS iterations must be positive") + height, width = image_hw + if height <= 0 or width <= 0: + raise ValueError("image dimensions must be positive") + + fx, fy = K[:, 0, 0], K[:, 1, 1] + cx, cy = K[:, 0, 2], K[:, 1, 2] + joint_z = joints[..., 2] + z[:, None] + finite_k = np.isfinite(K).all(axis=(1, 2)) & (fx > 1e-8) & (fy > 1e-8) + finite_joint = np.isfinite(joints).all(axis=-1) + finite_anchor = np.isfinite(anchors).all(axis=-1) + in_frame = ( + (anchors[..., 0] >= 0.0) + & (anchors[..., 0] <= width - 1.0) + & (anchors[..., 1] >= 0.0) + & (anchors[..., 1] <= height - 1.0) + ) + mask = ( + finite_k[:, None] + & np.isfinite(z)[:, None] + & (joint_z > minimum_joint_depth_m) + & finite_joint + & finite_anchor + & in_frame + ) + support = mask.sum(axis=1).astype(np.int64) + + safe_joint_z = np.where(mask, joint_z, 1.0) + ax = fx[:, None] / safe_joint_z + ay = fy[:, None] / safe_joint_z + bx = anchors[..., 0] - cx[:, None] - fx[:, None] * joints[..., 0] / safe_joint_z + by = anchors[..., 1] - cy[:, None] - fy[:, None] * joints[..., 1] / safe_joint_z + ax = np.where(mask, ax, 0.0) + ay = np.where(mask, ay, 0.0) + bx = np.where(mask, bx, 0.0) + by = np.where(mask, by, 0.0) + + weights = mask.astype(np.float64) + + def solve(current_weights: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + denom_x = np.sum(current_weights * np.square(ax), axis=1) + denom_y = np.sum(current_weights * np.square(ay), axis=1) + tx = np.divide( + np.sum(current_weights * ax * bx, axis=1), denom_x, + out=np.full(count, np.nan), where=denom_x > denominator_epsilon, + ) + ty = np.divide( + np.sum(current_weights * ay * by, axis=1), denom_y, + out=np.full(count, np.nan), where=denom_y > denominator_epsilon, + ) + return tx, ty, denom_x, denom_y + + tx, ty, denom_x, denom_y = solve(weights) + if robust_huber_delta_px is not None: + for _ in range(irls_iterations): + residual = np.sqrt( + np.square(ax * tx[:, None] - bx) + + np.square(ay * ty[:, None] - by) + ) + robust = np.minimum( + 1.0, + robust_huber_delta_px / np.maximum(residual, 1e-12), + ) + weights = np.where(mask, robust, 0.0) + tx, ty, denom_x, denom_y = solve(weights) + + residual = np.sqrt( + np.square(ax * tx[:, None] - bx) + + np.square(ay * ty[:, None] - by) + ) + residual_masked = np.where(mask, residual, np.nan) + residual_scale = np.full(count, np.inf, dtype=np.float64) + has_support = support > 0 + if has_support.any(): + supported_residual = residual_masked[has_support] + median = np.nanmedian(supported_residual, axis=1) + mad = np.nanmedian( + np.abs(supported_residual - median[:, None]), axis=1, + ) + residual_scale[has_support] = 1.4826 * mad + if robust_huber_delta_px is None: + inlier = np.where(mask, True, False) + else: + inlier = mask & (residual <= robust_huber_delta_px) + inlier_ratio = np.divide( + inlier.sum(axis=1), support, + out=np.zeros(count, dtype=np.float64), where=support > 0, + ) + conditioning = np.divide( + np.minimum(denom_x, denom_y), np.maximum(denom_x, denom_y), + out=np.zeros(count, dtype=np.float64), where=np.maximum(denom_x, denom_y) > 0.0, + ) + uncertainty = np.stack(( + np.divide( + residual_scale, np.sqrt(denom_x), out=np.full(count, np.inf), + where=denom_x > denominator_epsilon, + ), + np.divide( + residual_scale, np.sqrt(denom_y), out=np.full(count, np.inf), + where=denom_y > denominator_epsilon, + ), + ), axis=-1) + + sufficient = support >= minimum_support + conditioned = (denom_x > denominator_epsilon) & (denom_y > denominator_epsilon) + finite_solution = np.isfinite(tx) & np.isfinite(ty) + success = finite_k & sufficient & conditioned & finite_solution + output = fallback.copy() + output[:, 0] = np.where(success, tx, output[:, 0]) + output[:, 1] = np.where(success, ty, output[:, 1]) + output[:, 2] = np.where(np.isfinite(z), z, output[:, 2]) + reason = np.full(count, "ok", dtype=" str: + return ACTION_NAMES.get(int(label), f"unknown_{int(label)}") + + +def load_action_label(data_root: str | Path, take: str, frame_id: int) -> int: + path = Path(data_root) / take / "action_label" / f"{int(frame_id):06d}.txt" + values = path.read_text(encoding="utf-8").split() + if len(values) != 1: + raise ValueError(f"expected one H2O action label in {path}, found {len(values)}") + label = int(values[0]) + if label not in ACTION_NAMES: + raise ValueError(f"unknown H2O action label {label} in {path}") + return label + + +def local_depth_statistics( + depth_m: np.ndarray, + depth_valid: np.ndarray, + joints_2d: np.ndarray, + *, + margin_fraction: float = 0.25, + minimum_size_px: int = 24, +) -> dict[str, float | int | None]: + """Summarize aligned metric depth in a conservative GT-joint region. + + This diagnostic intentionally describes visible surface geometry. It does + not equate the local depth median with the camera-space wrist center. + """ + + if depth_m.ndim != 2 or depth_valid.shape != depth_m.shape: + raise ValueError("depth and validity must be aligned HxW arrays") + points = np.asarray(joints_2d, dtype=np.float64) + finite = np.isfinite(points).all(axis=-1) + if not finite.any(): + return { + "roi_x0": None, + "roi_y0": None, + "roi_x1": None, + "roi_y1": None, + "pixel_count": 0, + "valid_fraction": None, + "depth_median_m": None, + "depth_q10_m": None, + "depth_q90_m": None, + "depth_iqr_m": None, + "depth_discontinuity_m": None, + } + points = points[finite] + minimum = points.min(axis=0) + maximum = points.max(axis=0) + center = 0.5 * (minimum + maximum) + extent = np.maximum(maximum - minimum, float(minimum_size_px)) + extent *= 1.0 + 2.0 * float(margin_fraction) + height, width = depth_m.shape + x0 = max(0, int(np.floor(center[0] - extent[0] / 2.0))) + y0 = max(0, int(np.floor(center[1] - extent[1] / 2.0))) + x1 = min(width, int(np.ceil(center[0] + extent[0] / 2.0)) + 1) + y1 = min(height, int(np.ceil(center[1] + extent[1] / 2.0)) + 1) + if x1 <= x0 or y1 <= y0: + return { + "roi_x0": x0, + "roi_y0": y0, + "roi_x1": x1, + "roi_y1": y1, + "pixel_count": 0, + "valid_fraction": None, + "depth_median_m": None, + "depth_q10_m": None, + "depth_q90_m": None, + "depth_iqr_m": None, + "depth_discontinuity_m": None, + } + region_valid = np.asarray(depth_valid[y0:y1, x0:x1], dtype=bool) + region_depth = np.asarray(depth_m[y0:y1, x0:x1], dtype=np.float64) + region_valid &= np.isfinite(region_depth) & (region_depth > 0.0) + values = region_depth[region_valid] + report: dict[str, float | int | None] = { + "roi_x0": x0, + "roi_y0": y0, + "roi_x1": x1, + "roi_y1": y1, + "pixel_count": int(region_valid.size), + "valid_fraction": float(region_valid.mean()), + "depth_median_m": None, + "depth_q10_m": None, + "depth_q90_m": None, + "depth_iqr_m": None, + "depth_discontinuity_m": None, + } + if values.size: + q10, q25, q50, q75, q90 = np.percentile(values, (10, 25, 50, 75, 90)) + report.update({ + "depth_median_m": float(q50), + "depth_q10_m": float(q10), + "depth_q90_m": float(q90), + "depth_iqr_m": float(q75 - q25), + "depth_discontinuity_m": float(q90 - q10), + }) + return report + + +def depth_validity_bucket(value: float | None) -> str | None: + if value is None or not np.isfinite(value): + return None + if value < 0.5: + return "low" + if value < 0.9: + return "partial" + return "high" + + +def bimanual_asymmetry( + hand_sizes_px: Sequence[float | None], + wrist_depths_m: Sequence[float | None], +) -> dict[str, float | str | None]: + if len(hand_sizes_px) != 2 or len(wrist_depths_m) != 2: + raise ValueError("bimanual asymmetry requires left/right pairs") + if any(value is None or not np.isfinite(value) for value in hand_sizes_px): + size_ratio = None + else: + small = max(min(float(hand_sizes_px[0]), float(hand_sizes_px[1])), 1e-6) + size_ratio = max(float(hand_sizes_px[0]), float(hand_sizes_px[1])) / small + if any(value is None or not np.isfinite(value) for value in wrist_depths_m): + depth_gap = None + signed_depth_gap = None + else: + signed_depth_gap = float(wrist_depths_m[1]) - float(wrist_depths_m[0]) + depth_gap = abs(signed_depth_gap) + + if size_ratio is None or depth_gap is None: + bucket = None + elif size_ratio >= 2.0 or depth_gap >= 0.20: + bucket = "strong" + elif size_ratio >= 1.5 or depth_gap >= 0.10: + bucket = "moderate" + else: + bucket = "balanced" + return { + "bimanual_size_ratio": size_ratio, + "bimanual_depth_gap_m": depth_gap, + "right_minus_left_depth_m": signed_depth_gap, + "bimanual_asymmetry_bucket": bucket, + } + + +def summarize_group_metrics( + rows: Sequence[Mapping[str, object]], + metrics: Sequence[str], + group_fields: Sequence[str], +) -> list[dict[str, object]]: + output: list[dict[str, object]] = [] + for group_field in group_fields: + groups: dict[str, list[Mapping[str, object]]] = defaultdict(list) + for row in rows: + value = row.get(group_field) + if value not in (None, ""): + groups[str(value)].append(row) + for group_value, group_rows in sorted(groups.items()): + for side in ("all", "left", "right"): + side_rows = ( + group_rows if side == "all" + else [row for row in group_rows if row.get("side") == side] + ) + for metric in metrics: + summary = distribution_summary(row.get(metric) for row in side_rows) + output.append({ + "group_field": group_field, + "group_value": group_value, + "side": side, + "metric": metric, + **summary, + }) + return output + + +def find_failure_intervals( + rows: Sequence[Mapping[str, object]], + *, + metric: str, + threshold: float, + minimum_frames: int = 3, +) -> list[dict[str, object]]: + """Find contiguous valid-frame intervals above a registered error threshold.""" + + grouped: dict[tuple[str, str], list[Mapping[str, object]]] = defaultdict(list) + for row in rows: + value = row.get(metric) + if row.get("annotation_valid") and value not in (None, ""): + grouped[(str(row["take"]), str(row["side"]))].append(row) + + intervals: list[dict[str, object]] = [] + for (take, side), group in sorted(grouped.items()): + ordered = sorted(group, key=lambda row: int(row["frame_id"])) + current: list[Mapping[str, object]] = [] + + def flush() -> None: + if len(current) < minimum_frames: + current.clear() + return + values = np.asarray([float(row[metric]) for row in current], dtype=np.float64) + intervals.append({ + "take": take, + "side": side, + "metric": metric, + "threshold": float(threshold), + "start_frame": int(current[0]["frame_id"]), + "end_frame": int(current[-1]["frame_id"]), + "frame_count": len(current), + "mean": float(values.mean()), + "maximum": float(values.max()), + "p95": float(np.percentile(values, 95)), + }) + current.clear() + + previous_frame: int | None = None + for row in ordered: + frame = int(row["frame_id"]) + above = float(row[metric]) >= threshold + if not above or (previous_frame is not None and frame != previous_frame + 1): + flush() + if above: + current.append(row) + previous_frame = frame + flush() + return sorted( + intervals, + key=lambda row: (-int(row["frame_count"]), -float(row["mean"]), str(row["take"])), + ) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/procrustes.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f5b53bcabf1384c6af810216589e897a459250 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/procrustes.py @@ -0,0 +1,46 @@ +"""Rigid and similarity-aligned 3D joint errors.""" + +from __future__ import annotations + +import numpy as np + + +def aligned_mpjpe_mm( + predicted_m: np.ndarray, + target_m: np.ndarray, + *, + estimate_scale: bool, +) -> np.ndarray: + """Return per-sample Kabsch/Umeyama MPJPE for arrays ending in [J,3].""" + + predicted = np.asarray(predicted_m, dtype=np.float64) + target = np.asarray(target_m, dtype=np.float64) + if predicted.shape != target.shape or predicted.ndim < 3 or predicted.shape[-1] != 3: + raise ValueError("predicted and target joints must share shape [...,J,3]") + prefix = predicted.shape[:-2] + joints = predicted.shape[-2] + source = predicted.reshape(-1, joints, 3) + destination = target.reshape(-1, joints, 3) + if not np.isfinite(source).all() or not np.isfinite(destination).all(): + raise ValueError("aligned MPJPE expects finite valid-hand joints") + source_mean = source.mean(axis=1, keepdims=True) + destination_mean = destination.mean(axis=1, keepdims=True) + source_centered = source - source_mean + destination_centered = destination - destination_mean + covariance = np.swapaxes(source_centered, 1, 2) @ destination_centered + left, singular, right_transposed = np.linalg.svd(covariance) + correction = np.ones((len(source), 3), dtype=np.float64) + correction[:, -1] = np.where( + np.linalg.det(left @ right_transposed) < 0.0, -1.0, 1.0, + ) + rotation = (left * correction[:, None, :]) @ right_transposed + aligned = source_centered @ rotation + if estimate_scale: + numerator = (singular * correction).sum(axis=1) + denominator = np.square(source_centered).sum(axis=(1, 2)) + scale = np.divide( + numerator, denominator, out=np.ones_like(numerator), where=denominator > 1e-12, + ) + aligned = aligned * scale[:, None, None] + error = np.linalg.norm(aligned - destination_centered, axis=-1).mean(axis=1) * 1000.0 + return error.reshape(prefix) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/selection.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/selection.py new file mode 100644 index 0000000000000000000000000000000000000000..0e01a5da365d139c657d71efd738c8b38b555d0c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/selection.py @@ -0,0 +1,69 @@ +"""Deterministic, auditable selection of qualitative validation examples.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence + +import numpy as np + + +def _nearest_rank(records: list[Mapping[str, object]], metric: str, percentile: float) -> Mapping[str, object] | None: + candidates = [record for record in records if record.get(metric) is not None] + if not candidates: + return None + values = np.asarray([float(record[metric]) for record in candidates], dtype=np.float64) + target = float(np.percentile(values, percentile)) + return candidates[int(np.argmin(np.abs(values - target)))] + + +def select_visualization_frames( + records: Sequence[Mapping[str, object]], + *, + seed: int = 20260716, + random_count: int = 4, + metric: str = "absolute_mpjpe_mm", +) -> list[dict[str, object]]: + """Select random, error-tail, scale, depth, and validity-state frames.""" + + if not records: + return [] + rng = np.random.default_rng(seed) + selected: dict[tuple[int, int], dict[str, object]] = {} + + def add(record: Mapping[str, object] | None, reason: str) -> None: + if record is None: + return + key = (int(record["clip_index"]), int(record["time_index"])) + if key not in selected: + selected[key] = { + "clip_index": key[0], + "time_index": key[1], + "subject": record["subject"], + "sequence": record["sequence"], + "take": record["take"], + "frame_id": int(record["frame_id"]), + "annotation_state": record["annotation_state"], + "hand_size_bucket": record.get("hand_size_bucket"), + "depth_bucket": record.get("depth_bucket"), + metric: record.get(metric), + "reasons": [], + } + selected[key]["reasons"].append(reason) + + random_count = min(random_count, len(records)) + for index in rng.choice(len(records), size=random_count, replace=False): + add(records[int(index)], "random") + + for percentile in (50, 90, 95, 100): + add(_nearest_rank(list(records), metric, percentile), f"error_p{percentile}") + + for field, values in ( + ("hand_size_bucket", ("small", "medium", "large")), + ("depth_bucket", ("near", "middle", "far")), + ("annotation_state", ("00", "01", "10", "11")), + ): + for value in values: + bucket = [record for record in records if record.get(field) == value] + add(_nearest_rank(bucket, metric, 50) if bucket else None, f"{field}={value}") + + return sorted(selected.values(), key=lambda item: (int(item["clip_index"]), int(item["time_index"]))) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/sota.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/sota.py new file mode 100644 index 0000000000000000000000000000000000000000..3eecabedfeca76d5b64506fb7b9aa9840c38c28f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/sota.py @@ -0,0 +1,630 @@ +"""Shared prediction format and fair H2O evaluation for external baselines.""" + +from __future__ import annotations + +import csv +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping, Sequence + +import numpy as np + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary + + +SCHEMA_VERSION = "foundation_hand_sota_prediction_v1" +SIDES = ("left", "right") +FINGERTIP_INDICES = (4, 8, 12, 16, 20) +PRIMARY_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", +) + + +def frame_key(take: str, frame_id: int) -> str: + return f"{take}/{frame_id:06d}" + + +def load_frame_index(manifest: str | Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Expand an official run manifest into its unique, deterministic frame order.""" + + takes: list[str] = [] + frame_ids: list[int] = [] + keys: list[str] = [] + seen: set[str] = set() + for line in Path(manifest).read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + record = json.loads(line) + take = str(record["take"]) + if not take.endswith("/cam4"): + raise ValueError(f"SOTA evaluation is cam4-only: {take}") + for value in record["frame_ids"]: + frame_id = int(value) + key = frame_key(take, frame_id) + if key in seen: + raise ValueError(f"Duplicate frame in manifest: {key}") + seen.add(key) + takes.append(take) + frame_ids.append(frame_id) + keys.append(key) + if not keys: + raise ValueError("Manifest contains no frames") + return ( + np.asarray(keys, dtype=np.str_), + np.asarray(takes, dtype=np.str_), + np.asarray(frame_ids, dtype=np.int64), + ) + + +@dataclass(frozen=True) +class PredictionBundle: + """Camera-space predictions aligned one-to-one with an official frame manifest.""" + + model_name: str + frame_keys: np.ndarray + takes: np.ndarray + frame_ids: np.ndarray + joints_camera_m: np.ndarray + detected: np.ndarray + confidence: np.ndarray + metadata: Mapping[str, Any] + vertices_camera_m: np.ndarray | None = None + + def validate(self) -> None: + count = len(self.frame_keys) + expected = { + "takes": (count,), + "frame_ids": (count,), + "joints_camera_m": (count, 2, 21, 3), + "detected": (count, 2), + "confidence": (count, 2), + } + for name, shape in expected.items(): + if np.asarray(getattr(self, name)).shape != shape: + raise ValueError( + f"{name} shape {np.asarray(getattr(self, name)).shape} != {shape}" + ) + if self.vertices_camera_m is not None: + vertices = np.asarray(self.vertices_camera_m) + if vertices.ndim != 4 or vertices.shape[:2] != (count, 2) or vertices.shape[-1] != 3: + raise ValueError(f"Unexpected vertices_camera_m shape: {vertices.shape}") + if len(set(map(str, self.frame_keys.tolist()))) != count: + raise ValueError("Prediction frame keys must be unique") + finite_joints = np.isfinite(self.joints_camera_m).all(axis=(-1, -2)) + if np.any(self.detected & ~finite_joints): + raise ValueError("Detected hands must have 21 finite camera-space joints") + if self.vertices_camera_m is not None: + finite_vertices = np.isfinite(self.vertices_camera_m).all(axis=(-1, -2)) + if np.any(self.detected & ~finite_vertices): + raise ValueError("Detected hands must have finite camera-space vertices") + + def save(self, path: str | Path) -> None: + self.validate() + payload: dict[str, np.ndarray] = { + "schema_version": np.asarray(SCHEMA_VERSION), + "model_name": np.asarray(self.model_name), + "frame_keys": np.asarray(self.frame_keys, dtype=np.str_), + "takes": np.asarray(self.takes, dtype=np.str_), + "frame_ids": np.asarray(self.frame_ids, dtype=np.int64), + "joints_camera_m": np.asarray(self.joints_camera_m, dtype=np.float32), + "detected": np.asarray(self.detected, dtype=np.bool_), + "confidence": np.asarray(self.confidence, dtype=np.float32), + "metadata_json": np.asarray(json.dumps(dict(self.metadata), sort_keys=True)), + } + if self.vertices_camera_m is not None: + payload["vertices_camera_m"] = np.asarray( + self.vertices_camera_m, dtype=np.float32 + ) + output = Path(path) + output.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(output, **payload) + + @classmethod + def load(cls, path: str | Path) -> "PredictionBundle": + with np.load(path, allow_pickle=False) as data: + version = str(data["schema_version"].item()) + if version != SCHEMA_VERSION: + raise ValueError(f"Unsupported prediction schema: {version}") + bundle = cls( + model_name=str(data["model_name"].item()), + frame_keys=data["frame_keys"].copy(), + takes=data["takes"].copy(), + frame_ids=data["frame_ids"].copy(), + joints_camera_m=data["joints_camera_m"].copy(), + detected=data["detected"].copy(), + confidence=data["confidence"].copy(), + metadata=json.loads(str(data["metadata_json"].item())), + vertices_camera_m=( + data["vertices_camera_m"].copy() + if "vertices_camera_m" in data.files + else None + ), + ) + bundle.validate() + return bundle + + +@dataclass(frozen=True) +class GroundTruthBundle: + frame_keys: np.ndarray + takes: np.ndarray + frame_ids: np.ndarray + joints_camera_m: np.ndarray + vertices_camera_m: np.ndarray + annotation_valid: np.ndarray + intrinsics: np.ndarray + metadata: Mapping[str, Any] + + def save(self, path: str | Path) -> None: + count = len(self.frame_keys) + if self.joints_camera_m.shape != (count, 2, 21, 3): + raise ValueError(f"Unexpected GT joints shape: {self.joints_camera_m.shape}") + if self.vertices_camera_m.shape[:2] != (count, 2): + raise ValueError(f"Unexpected GT vertices shape: {self.vertices_camera_m.shape}") + output = Path(path) + output.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + output, + schema_version=np.asarray("foundation_hand_sota_ground_truth_v1"), + frame_keys=np.asarray(self.frame_keys, dtype=np.str_), + takes=np.asarray(self.takes, dtype=np.str_), + frame_ids=np.asarray(self.frame_ids, dtype=np.int64), + joints_camera_m=np.asarray(self.joints_camera_m, dtype=np.float32), + vertices_camera_m=np.asarray(self.vertices_camera_m, dtype=np.float32), + annotation_valid=np.asarray(self.annotation_valid, dtype=np.bool_), + intrinsics=np.asarray(self.intrinsics, dtype=np.float32), + metadata_json=np.asarray(json.dumps(dict(self.metadata), sort_keys=True)), + ) + + @classmethod + def load(cls, path: str | Path) -> "GroundTruthBundle": + with np.load(path, allow_pickle=False) as data: + version = str(data["schema_version"].item()) + if version != "foundation_hand_sota_ground_truth_v1": + raise ValueError(f"Unsupported GT schema: {version}") + return cls( + frame_keys=data["frame_keys"].copy(), + takes=data["takes"].copy(), + frame_ids=data["frame_ids"].copy(), + joints_camera_m=data["joints_camera_m"].copy(), + vertices_camera_m=data["vertices_camera_m"].copy(), + annotation_valid=data["annotation_valid"].copy(), + intrinsics=data["intrinsics"].copy(), + metadata=json.loads(str(data["metadata_json"].item())), + ) + + +def align_prediction( + prediction: PredictionBundle, ground_truth: GroundTruthBundle +) -> PredictionBundle: + """Return predictions in GT order, rejecting missing or extra frame keys.""" + + gt_keys = list(map(str, ground_truth.frame_keys.tolist())) + pred_index = {str(key): index for index, key in enumerate(prediction.frame_keys.tolist())} + if set(pred_index) != set(gt_keys): + missing = sorted(set(gt_keys) - set(pred_index)) + extra = sorted(set(pred_index) - set(gt_keys)) + raise ValueError( + f"Prediction/GT frame mismatch: missing={missing[:3]} extra={extra[:3]}" + ) + order = np.asarray([pred_index[key] for key in gt_keys], dtype=np.int64) + return PredictionBundle( + model_name=prediction.model_name, + frame_keys=prediction.frame_keys[order], + takes=prediction.takes[order], + frame_ids=prediction.frame_ids[order], + joints_camera_m=prediction.joints_camera_m[order], + detected=prediction.detected[order], + confidence=prediction.confidence[order], + metadata=prediction.metadata, + vertices_camera_m=( + prediction.vertices_camera_m[order] + if prediction.vertices_camera_m is not None + else None + ), + ) + + +def _project(points: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + z = points[..., 2:3] + normalized = points[..., :2] / z + return np.einsum("nij,nhkj->nhki", intrinsics[:, :2, :2], normalized) + intrinsics[ + :, None, None, :2, 2 + ] + + +def _mean_or_none(value: np.ndarray) -> float | None: + finite = value[np.isfinite(value)] + return float(finite.mean()) if finite.size else None + + +def _auc_pck(errors_mm: np.ndarray, success: np.ndarray, maximum_mm: float = 50.0) -> float: + thresholds = np.linspace(0.0, maximum_mm, 101) + hits = success[..., None] & (errors_mm[..., None] <= thresholds) + pck = hits.reshape(-1, len(thresholds)).mean(axis=0) + return float(np.trapezoid(pck, thresholds) / maximum_mm) + + +def evaluate_prediction_bundle( + prediction: PredictionBundle, + ground_truth: GroundTruthBundle, + *, + bootstrap_seed: int = 20260716, + bootstrap_samples: int = 10_000, + pixel_scale: float = 1.0, + temporal_clip_length: int | None = 8, +) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]: + """Evaluate one model without silently dropping detector failures.""" + + prediction = align_prediction(prediction, ground_truth) + valid = ground_truth.annotation_valid.astype(bool) + finite = np.isfinite(prediction.joints_camera_m).all(axis=(-1, -2)) + success = valid & prediction.detected & finite + + joint_error = np.linalg.norm( + prediction.joints_camera_m - ground_truth.joints_camera_m, axis=-1 + ) * 1000.0 + pred_relative = prediction.joints_camera_m - prediction.joints_camera_m[:, :, :1] + gt_relative = ground_truth.joints_camera_m - ground_truth.joints_camera_m[:, :, :1] + relative_error = np.linalg.norm(pred_relative - gt_relative, axis=-1) * 1000.0 + projected = _project(prediction.joints_camera_m, ground_truth.intrinsics) + target_projected = _project(ground_truth.joints_camera_m, ground_truth.intrinsics) + if pixel_scale <= 0: + raise ValueError("pixel_scale must be positive") + projected_error = np.linalg.norm(projected - target_projected, axis=-1) * pixel_scale + translation_error = np.abs( + prediction.joints_camera_m[:, :, 0] - ground_truth.joints_camera_m[:, :, 0] + ) * 1000.0 + + vertex_error: np.ndarray | None = None + relative_vertex_error: np.ndarray | None = None + if prediction.vertices_camera_m is not None: + vertex_error = np.linalg.norm( + prediction.vertices_camera_m - ground_truth.vertices_camera_m, axis=-1 + ) * 1000.0 + pred_vertex_relative = ( + prediction.vertices_camera_m - prediction.joints_camera_m[:, :, None, 0] + ) + gt_vertex_relative = ( + ground_truth.vertices_camera_m - ground_truth.joints_camera_m[:, :, None, 0] + ) + relative_vertex_error = np.linalg.norm( + pred_vertex_relative - gt_vertex_relative, axis=-1 + ) * 1000.0 + + wrong_side: list[bool | None] = [] + for frame_index in range(len(ground_truth.frame_keys)): + if bool(valid[frame_index].all() and success[frame_index].all()): + correct = 0.5 * ( + joint_error[frame_index, 0].mean() + joint_error[frame_index, 1].mean() + ) + swapped = 500.0 * ( + np.linalg.norm( + prediction.joints_camera_m[frame_index, 0] + - ground_truth.joints_camera_m[frame_index, 1], + axis=-1, + ).mean() + + np.linalg.norm( + prediction.joints_camera_m[frame_index, 1] + - ground_truth.joints_camera_m[frame_index, 0], + axis=-1, + ).mean() + ) + wrong_side.append(bool(swapped < correct)) + else: + wrong_side.append(None) + + rows: list[dict[str, Any]] = [] + for frame_index in range(len(ground_truth.frame_keys)): + for hand, side in enumerate(SIDES): + is_valid = bool(valid[frame_index, hand]) + is_success = bool(success[frame_index, hand]) + row: dict[str, Any] = { + "frame_key": str(ground_truth.frame_keys[frame_index]), + "take": str(ground_truth.takes[frame_index]), + "frame_id": int(ground_truth.frame_ids[frame_index]), + "side": side, + "annotation_valid": int(is_valid), + "detected": int(prediction.detected[frame_index, hand]), + "evaluation_success": int(is_success), + "coverage_success": int(is_success) if is_valid else None, + "confidence": ( + float(prediction.confidence[frame_index, hand]) + if np.isfinite(prediction.confidence[frame_index, hand]) + else None + ), + "wrong_side_preference": ( + int(wrong_side[frame_index]) + if wrong_side[frame_index] is not None + else None + ), + } + metric_values = { + "absolute_mpjpe_mm": joint_error[frame_index, hand].mean(), + "root_relative_mpjpe_mm": relative_error[frame_index, hand].mean(), + "projected_2d_error_px": projected_error[frame_index, hand].mean(), + "fingertip_mpjpe_mm": joint_error[ + frame_index, hand, list(FINGERTIP_INDICES) + ].mean(), + "translation_x_mae_mm": translation_error[frame_index, hand, 0], + "translation_y_mae_mm": translation_error[frame_index, hand, 1], + "translation_z_mae_mm": translation_error[frame_index, hand, 2], + } + if vertex_error is not None and relative_vertex_error is not None: + metric_values.update({ + "absolute_mpvpe_mm": vertex_error[frame_index, hand].mean(), + "root_relative_mpvpe_mm": relative_vertex_error[ + frame_index, hand + ].mean(), + }) + for name in PRIMARY_METRICS: + row[name] = ( + float(metric_values[name]) + if is_success and name in metric_values + else None + ) + rows.append(row) + + temporal_rows: list[dict[str, Any]] = [] + run_positions = np.zeros(len(ground_truth.frame_keys), dtype=np.int64) + for index in range(1, len(run_positions)): + if ( + ground_truth.takes[index] == ground_truth.takes[index - 1] + and ground_truth.frame_ids[index] == ground_truth.frame_ids[index - 1] + 1 + ): + run_positions[index] = run_positions[index - 1] + 1 + for current in range(1, len(ground_truth.frame_keys)): + previous = current - 1 + consecutive = ( + ground_truth.takes[current] == ground_truth.takes[previous] + and ground_truth.frame_ids[current] == ground_truth.frame_ids[previous] + 1 + ) + clip_consecutive = ( + consecutive + and ( + temporal_clip_length is None + or run_positions[current] % temporal_clip_length != 0 + ) + ) + if not clip_consecutive: + continue + for hand, side in enumerate(SIDES): + gt_pair_valid = bool(valid[previous, hand] and valid[current, hand]) + pred_pair_valid = bool(success[previous, hand] and success[current, hand]) + wrist_velocity = None + joint_velocity = None + wrist_acceleration = None + joint_acceleration = None + gt_triplet_valid = False + pred_triplet_valid = False + if gt_pair_valid and pred_pair_valid: + predicted_delta = ( + prediction.joints_camera_m[current, hand] + - prediction.joints_camera_m[previous, hand] + ) + target_delta = ( + ground_truth.joints_camera_m[current, hand] + - ground_truth.joints_camera_m[previous, hand] + ) + velocity_error = np.linalg.norm(predicted_delta - target_delta, axis=-1) * 1000.0 + wrist_velocity = float(velocity_error[0]) + joint_velocity = float(velocity_error.mean()) + if previous >= 1: + before_previous = previous - 1 + triplet_consecutive = ( + ground_truth.takes[before_previous] == ground_truth.takes[current] + and ground_truth.frame_ids[before_previous] + 1 + == ground_truth.frame_ids[previous] + and ( + temporal_clip_length is None + or run_positions[current] % temporal_clip_length >= 2 + ) + ) + gt_triplet_valid = bool( + triplet_consecutive + and valid[before_previous, hand] + and valid[previous, hand] + and valid[current, hand] + ) + pred_triplet_valid = bool( + gt_triplet_valid + and success[before_previous, hand] + and success[previous, hand] + and success[current, hand] + ) + if pred_triplet_valid: + predicted_acceleration = ( + prediction.joints_camera_m[current, hand] + - 2 * prediction.joints_camera_m[previous, hand] + + prediction.joints_camera_m[before_previous, hand] + ) + target_acceleration = ( + ground_truth.joints_camera_m[current, hand] + - 2 * ground_truth.joints_camera_m[previous, hand] + + ground_truth.joints_camera_m[before_previous, hand] + ) + acceleration_error = np.linalg.norm( + predicted_acceleration - target_acceleration, axis=-1 + ) * 1000.0 + wrist_acceleration = float(acceleration_error[0]) + joint_acceleration = float(acceleration_error.mean()) + identity_switch = None + if wrong_side[previous] is not None and wrong_side[current] is not None: + identity_switch = int(wrong_side[previous] != wrong_side[current]) + temporal_rows.append({ + "take": str(ground_truth.takes[current]), + "side": side, + "frame_id_from": int(ground_truth.frame_ids[previous]), + "frame_id_to": int(ground_truth.frame_ids[current]), + "annotation_pair_valid": int(gt_pair_valid), + "evaluation_pair_success": int(gt_pair_valid and pred_pair_valid), + "annotation_triplet_valid": int(gt_triplet_valid), + "evaluation_triplet_success": int(pred_triplet_valid), + "wrist_velocity_error_mm_per_frame": wrist_velocity, + "joint_velocity_error_mm_per_frame": joint_velocity, + "wrist_acceleration_error_mm_per_frame2": wrist_acceleration, + "joint_acceleration_error_mm_per_frame2": joint_acceleration, + "identity_switch_fraction": identity_switch, + }) + + metric_summary = { + metric: distribution_summary(row[metric] for row in rows) + for metric in PRIMARY_METRICS + } + valid_joint = np.broadcast_to(valid[..., None], joint_error.shape) + success_joint = np.broadcast_to(success[..., None], joint_error.shape) + report: dict[str, Any] = { + "status": "evaluated", + "schema_version": SCHEMA_VERSION, + "model_name": prediction.model_name, + "frames": int(len(ground_truth.frame_keys)), + "takes": int(len(set(map(str, ground_truth.takes.tolist())))), + "official_test_used": False, + "split_role": "official_validation", + "prediction_metadata": dict(prediction.metadata), + "projected_2d_pixel_scale": pixel_scale, + "temporal_evaluation_clip_length": temporal_clip_length, + "coverage": { + "annotation_valid_hand_frames": int(valid.sum()), + "successful_hand_frames": int(success.sum()), + "hand_frame_fraction": float(success.sum() / valid.sum()), + "annotation_invalid_prediction_rate": float( + prediction.detected[~valid].mean() if np.any(~valid) else 0.0 + ), + "valid_temporal_pairs": int(sum(row["annotation_pair_valid"] for row in temporal_rows)), + "successful_temporal_pairs": int( + sum(row["evaluation_pair_success"] for row in temporal_rows) + ), + }, + "metrics_success_conditioned": metric_summary, + "failure_aware": { + "absolute_pck_20mm": float( + (success_joint & (joint_error <= 20.0))[valid_joint].mean() + ), + "absolute_pck_50mm": float( + (success_joint & (joint_error <= 50.0))[valid_joint].mean() + ), + "absolute_auc_0_50mm": _auc_pck( + joint_error[valid_joint], success_joint[valid_joint] + ), + "root_relative_pck_20mm": float( + (success_joint & (relative_error <= 20.0))[valid_joint].mean() + ), + "root_relative_pck_50mm": float( + (success_joint & (relative_error <= 50.0))[valid_joint].mean() + ), + "root_relative_auc_0_50mm": _auc_pck( + relative_error[valid_joint], success_joint[valid_joint] + ), + }, + "per_side": { + side: { + "coverage": float(success[:, hand].sum() / valid[:, hand].sum()), + **{ + metric: distribution_summary( + row[metric] for row in rows if row["side"] == side + ) + for metric in PRIMARY_METRICS + }, + } + for hand, side in enumerate(SIDES) + }, + "temporal_metrics_success_conditioned": { + name: distribution_summary(row[name] for row in temporal_rows) + for name in ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "joint_acceleration_error_mm_per_frame2", + "identity_switch_fraction", + ) + }, + "equal_take_bootstrap_ci": bootstrap_take_means( + rows, + ("coverage_success",) + PRIMARY_METRICS, + seed=bootstrap_seed, + samples=bootstrap_samples, + ), + } + valid_pairs = report["coverage"]["valid_temporal_pairs"] + report["coverage"]["temporal_pair_fraction"] = ( + float(report["coverage"]["successful_temporal_pairs"] / valid_pairs) + if valid_pairs + else None + ) + return report, rows, temporal_rows + + +def write_csv_rows(path: str | Path, rows: Sequence[Mapping[str, Any]]) -> None: + if not rows: + raise ValueError("Cannot write an empty metric table") + output = Path(path) + output.parent.mkdir(parents=True, exist_ok=True) + with output.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def paired_take_bootstrap( + baseline_rows: Sequence[Mapping[str, Any]], + candidate_rows: Sequence[Mapping[str, Any]], + metrics: Sequence[str] = PRIMARY_METRICS, + *, + seed: int = 20260716, + samples: int = 10_000, +) -> list[dict[str, Any]]: + """Bootstrap candidate-minus-baseline deltas on their exact success intersection.""" + + key_fields = ("frame_key", "side") + baseline = {tuple(row[field] for field in key_fields): row for row in baseline_rows} + candidate = {tuple(row[field] for field in key_fields): row for row in candidate_rows} + if set(baseline) != set(candidate): + raise ValueError("Paired metric tables do not contain identical hand-frame keys") + rng = np.random.default_rng(seed) + output: list[dict[str, Any]] = [] + for metric in metrics: + by_take: dict[str, list[float]] = defaultdict(list) + for key in baseline: + first = baseline[key].get(metric) + second = candidate[key].get(metric) + if first is None or second is None: + continue + if np.isfinite(float(first)) and np.isfinite(float(second)): + by_take[str(baseline[key]["take"])].append(float(second) - float(first)) + take_delta = np.asarray( + [np.mean(values) for values in by_take.values() if values], dtype=np.float64 + ) + if take_delta.size == 0: + output.append({ + "metric": metric, + "paired_hand_frames": 0, + "take_count": 0, + "candidate_minus_baseline": None, + "ci95_low": None, + "ci95_high": None, + }) + continue + indices = rng.integers(0, take_delta.size, size=(samples, take_delta.size)) + boot = take_delta[indices].mean(axis=1) + output.append({ + "metric": metric, + "paired_hand_frames": int(sum(len(values) for values in by_take.values())), + "take_count": int(take_delta.size), + "candidate_minus_baseline": float(take_delta.mean()), + "ci95_low": float(np.percentile(boot, 2.5)), + "ci95_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/subset.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/subset.py new file mode 100644 index 0000000000000000000000000000000000000000..250d37a0fa78a5caf231fa86d3948bce52f3f31d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/subset.py @@ -0,0 +1,72 @@ +"""Deterministic take-balanced, within-take stratified subset construction.""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Mapping, Sequence + +import numpy as np + + +def balanced_stratified_indices( + records: Sequence[Mapping[str, object]], + count: int, + *, + seed: int, +) -> list[int]: + """Balance quotas over takes and round-robin available within-take strata.""" + + if count <= 0 or count > len(records): + raise ValueError("count must be positive and no larger than the record count") + by_take: dict[str, list[Mapping[str, object]]] = defaultdict(list) + for record in records: + by_take[str(record["take"])].append(record) + takes = sorted(by_take) + if not takes: + return [] + + rng = np.random.default_rng(seed) + shuffled_takes = list(np.asarray(takes)[rng.permutation(len(takes))]) + base, remainder = divmod(count, len(takes)) + quotas = {take: base + int(position < remainder) for position, take in enumerate(shuffled_takes)} + selected: list[int] = [] + + for take in takes: + groups: dict[tuple[str, str, str], list[Mapping[str, object]]] = defaultdict(list) + for record in by_take[take]: + stratum = ( + str(record["hand_size_bucket"]), + str(record["depth_bucket"]), + str(record["annotation_state"]), + ) + groups[stratum].append(record) + group_keys = sorted(groups) + group_keys = [group_keys[int(index)] for index in rng.permutation(len(group_keys))] + for key in group_keys: + order = rng.permutation(len(groups[key])) + groups[key] = [groups[key][int(index)] for index in order] + cursors = {key: 0 for key in group_keys} + take_selected = 0 + while take_selected < min(quotas[take], len(by_take[take])): + progressed = False + for key in group_keys: + cursor = cursors[key] + if cursor >= len(groups[key]): + continue + selected.append(int(groups[key][cursor]["clip_index"])) + cursors[key] += 1 + take_selected += 1 + progressed = True + if take_selected >= quotas[take]: + break + if not progressed: + break + + if len(selected) < count: + selected_set = set(selected) + remaining = [int(record["clip_index"]) for record in records if int(record["clip_index"]) not in selected_set] + order = rng.permutation(len(remaining)) + selected.extend(remaining[int(index)] for index in order[: count - len(selected)]) + if len(selected) != count or len(set(selected)) != count: + raise AssertionError("subset construction failed to return unique requested indices") + return sorted(selected) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/temporal_filter.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/temporal_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..44b73366b267f458273c51efb3583dc1b4778020 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/temporal_filter.py @@ -0,0 +1,183 @@ +"""Inference-only temporal filters and jitter metrics with hard segment resets.""" + +from __future__ import annotations + +from collections.abc import Callable + +import numpy as np +from scipy.signal import butter, sosfiltfilt +from scipy.spatial.transform import Rotation + + +def valid_segments( + clip_ids: np.ndarray, + frame_ids: np.ndarray, + frame_valid: np.ndarray, +) -> list[np.ndarray]: + """Return contiguous valid indices without crossing clip or frame gaps.""" + + clip_ids = np.asarray(clip_ids) + frame_ids = np.asarray(frame_ids) + frame_valid = np.asarray(frame_valid, dtype=bool) + if not (clip_ids.ndim == frame_ids.ndim == frame_valid.ndim == 1): + raise ValueError("segment metadata must be one-dimensional") + if not (len(clip_ids) == len(frame_ids) == len(frame_valid)): + raise ValueError("segment metadata lengths differ") + output: list[np.ndarray] = [] + start: int | None = None + for index in range(len(frame_ids)): + continues = ( + start is not None + and frame_valid[index] + and clip_ids[index] == clip_ids[index - 1] + and frame_ids[index] == frame_ids[index - 1] + 1 + ) + if not continues: + if start is not None: + output.append(np.arange(start, index, dtype=np.int64)) + start = index if frame_valid[index] else None + if start is not None: + output.append(np.arange(start, len(frame_ids), dtype=np.int64)) + return output + + +def ema(values: np.ndarray, alpha: float) -> np.ndarray: + if not 0.0 < alpha <= 1.0: + raise ValueError("EMA alpha must be in (0, 1]") + values = np.asarray(values) + if values.ndim < 1 or values.shape[0] == 0: + raise ValueError("EMA requires a non-empty time dimension") + output = values.astype(np.float64, copy=True) + for index in range(1, len(output)): + output[index] = alpha * values[index] + (1.0 - alpha) * output[index - 1] + return output.astype(values.dtype, copy=False) + + +def butterworth_zero_phase( + values: np.ndarray, + cutoff_hz: float, + fps: float, + order: int = 2, +) -> np.ndarray: + values = np.asarray(values) + if values.ndim < 1 or values.shape[0] < 4: + raise ValueError("zero-phase filtering requires at least four frames") + if fps <= 0.0 or not 0.0 < cutoff_hz < fps / 2.0: + raise ValueError("Butterworth cutoff must lie below Nyquist") + if order < 1: + raise ValueError("Butterworth order must be positive") + sections = butter(order, cutoff_hz, btype="lowpass", fs=fps, output="sos") + # H2O inference clips have T=8. Explicit n-1 padding preserves the hard + # clip boundary while allowing a verified zero-phase filter on full clips. + filtered = sosfiltfilt( + sections, values.astype(np.float64), axis=0, padlen=values.shape[0] - 1, + ) + if not np.isfinite(filtered).all(): + raise FloatingPointError("Butterworth filtering produced NaN/Inf") + return filtered.astype(values.dtype) + + +def apply_by_segment( + values: np.ndarray, + segments: list[np.ndarray], + operation: Callable[[np.ndarray], np.ndarray], + *, + minimum_frames: int, +) -> tuple[np.ndarray, int]: + values = np.asarray(values) + output = values.copy() + fallback_segments = 0 + for indices in segments: + if len(indices) < minimum_frames: + fallback_segments += 1 + continue + filtered = operation(values[indices]) + if filtered.shape != values[indices].shape: + raise ValueError("temporal operation changed the signal shape") + output[indices] = filtered + return output, fallback_segments + + +def unwrap_quaternion_signs(quaternions: np.ndarray) -> np.ndarray: + quaternions = np.asarray(quaternions) + if quaternions.ndim < 2 or quaternions.shape[-1] != 4: + raise ValueError("quaternions must have shape [time, ..., 4]") + output = quaternions.copy() + for index in range(1, len(output)): + dots = np.sum(output[index - 1] * output[index], axis=-1) + output[index][dots < 0.0] *= -1.0 + return output + + +def filter_rotation_matrices( + matrices: np.ndarray, + operation: Callable[[np.ndarray], np.ndarray], +) -> np.ndarray: + matrices = np.asarray(matrices) + if matrices.ndim < 3 or matrices.shape[-2:] != (3, 3): + raise ValueError("rotation matrices must have shape [time, ..., 3, 3]") + original_shape = matrices.shape + quaternions = Rotation.from_matrix(matrices.reshape(-1, 3, 3)).as_quat() + quaternions = quaternions.reshape(*original_shape[:-2], 4) + quaternions = unwrap_quaternion_signs(quaternions) + filtered = operation(quaternions) + norms = np.linalg.norm(filtered, axis=-1, keepdims=True) + if not np.isfinite(norms).all() or np.any(norms < 1e-8): + raise FloatingPointError("quaternion filter produced invalid norms") + filtered = filtered / norms + result = Rotation.from_quat(filtered.reshape(-1, 4)).as_matrix() + return result.reshape(original_shape).astype(matrices.dtype) + + +def finite_differences( + values: np.ndarray, fps: float, order: int, +) -> np.ndarray: + values = np.asarray(values) + if fps <= 0.0 or order < 1: + raise ValueError("finite difference fps/order is invalid") + output = values + for _ in range(order): + output = np.diff(output, axis=0) * fps + return output + + +def derivative_norms(values: np.ndarray, fps: float, order: int) -> np.ndarray: + differences = finite_differences(values, fps, order) + return np.linalg.vector_norm(differences, axis=-1) + + +def high_frequency_energy_ratio( + values: np.ndarray, fps: float, threshold_hz: float = 6.0, +) -> float: + values = np.asarray(values, dtype=np.float64) + if values.ndim < 1 or values.shape[0] < 4: + raise ValueError("spectral metric requires at least four frames") + if not 0.0 < threshold_hz < fps / 2.0: + raise ValueError("spectral threshold must lie below Nyquist") + centered = values - values.mean(axis=0, keepdims=True) + spectrum = np.fft.rfft(centered, axis=0) + power = np.abs(spectrum) ** 2 + frequencies = np.fft.rfftfreq(values.shape[0], d=1.0 / fps) + non_dc = frequencies > 0.0 + denominator = float(power[non_dc].sum()) + if denominator == 0.0: + return 0.0 + return float(power[frequencies >= threshold_hz].sum() / denominator) + + +def rotation_geodesic_degrees( + prediction: np.ndarray, target: np.ndarray, +) -> np.ndarray: + prediction = np.asarray(prediction) + target = np.asarray(target) + if prediction.shape != target.shape or prediction.shape[-2:] != (3, 3): + raise ValueError("rotation geodesic inputs must be aligned matrices") + relative = np.swapaxes(target, -1, -2) @ prediction + cosine = np.clip((np.trace(relative, axis1=-2, axis2=-1) - 1.0) / 2.0, -1.0, 1.0) + return np.rad2deg(np.arccos(cosine)) + + +def ema_low_frequency_delay_frames(alpha: float) -> float: + if not 0.0 < alpha <= 1.0: + raise ValueError("EMA alpha must be in (0, 1]") + return (1.0 - alpha) / alpha diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/visualization.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..fcec3681b699141bd51a7d3ad49cab5dcf905f6c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/evaluation/visualization.py @@ -0,0 +1,202 @@ +"""Camera-correct MANO, skeleton, attention, and 3D visualizations.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +import textwrap + +import cv2 +import matplotlib.pyplot as plt +import numpy as np + + +OPENPOSE_HAND_EDGES = tuple( + (start + offset, start + offset + 1) + for start in (1, 5, 9, 13, 17) + for offset in range(3) +) + ((0, 1), (0, 5), (0, 9), (0, 13), (0, 17)) + + +@dataclass(frozen=True) +class MeshLayer: + vertices_camera: np.ndarray + faces: np.ndarray + color_rgb: tuple[int, int, int] + alpha: float = 0.55 + + +def project_camera_points(points: np.ndarray, K: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + points = np.asarray(points, dtype=np.float32) + z = points[..., 2] + safe_z = np.where(z > 1e-8, z, 1.0) + u = K[0, 0] * points[..., 0] / safe_z + K[0, 2] + v = K[1, 1] * points[..., 1] / safe_z + K[1, 2] + return np.stack((u, v), axis=-1), z + + +def render_mesh_layers(image_rgb: np.ndarray, layers: Sequence[MeshLayer]) -> np.ndarray: + """Rasterize constant-color triangular meshes with perspective-correct z-order.""" + + image = np.asarray(image_rgb, dtype=np.uint8) + height, width = image.shape[:2] + depth_buffer = np.full((height, width), np.inf, dtype=np.float32) + color_buffer = np.zeros((height, width, 3), dtype=np.float32) + alpha_buffer = np.zeros((height, width), dtype=np.float32) + + for layer in layers: + vertices = np.asarray(layer.vertices_camera, dtype=np.float32) + faces = np.asarray(layer.faces, dtype=np.int64) + # The caller supplies already projected xy by temporarily storing pixel x/y + # in vertices_camera x/y when using this low-level rasterizer. + projected = vertices[:, :2] + z_values = vertices[:, 2] + for face in faces: + z = z_values[face] + if np.any(z <= 1e-6) or not np.isfinite(z).all(): + continue + triangle = projected[face] + if not np.isfinite(triangle).all(): + continue + x_min = max(int(np.floor(triangle[:, 0].min())), 0) + x_max = min(int(np.ceil(triangle[:, 0].max())), width - 1) + y_min = max(int(np.floor(triangle[:, 1].min())), 0) + y_max = min(int(np.ceil(triangle[:, 1].max())), height - 1) + if x_min > x_max or y_min > y_max: + continue + x0, y0 = triangle[0] + x1, y1 = triangle[1] + x2, y2 = triangle[2] + denominator = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2) + if abs(float(denominator)) < 1e-8: + continue + yy, xx = np.mgrid[y_min : y_max + 1, x_min : x_max + 1] + px = xx.astype(np.float32) + 0.5 + py = yy.astype(np.float32) + 0.5 + w0 = ((y1 - y2) * (px - x2) + (x2 - x1) * (py - y2)) / denominator + w1 = ((y2 - y0) * (px - x2) + (x0 - x2) * (py - y2)) / denominator + w2 = 1.0 - w0 - w1 + inside = (w0 >= -1e-5) & (w1 >= -1e-5) & (w2 >= -1e-5) + inverse_z = w0 / z[0] + w1 / z[1] + w2 / z[2] + pixel_z = np.where(inverse_z > 1e-8, 1.0 / inverse_z, np.inf) + local_depth = depth_buffer[y_min : y_max + 1, x_min : x_max + 1] + update = inside & (pixel_z < local_depth) + if not np.any(update): + continue + local_depth[update] = pixel_z[update] + local_color = color_buffer[y_min : y_max + 1, x_min : x_max + 1] + local_color[update] = np.asarray(layer.color_rgb, dtype=np.float32) + local_alpha = alpha_buffer[y_min : y_max + 1, x_min : x_max + 1] + local_alpha[update] = float(layer.alpha) + + alpha = alpha_buffer[..., None] + rendered = image.astype(np.float32) * (1.0 - alpha) + color_buffer * alpha + return np.clip(rendered, 0, 255).astype(np.uint8) + + +def project_mesh_layers(layers: Sequence[MeshLayer], K: np.ndarray) -> list[MeshLayer]: + """Convert camera-space vertices to pixel-x, pixel-y, camera-z vertices.""" + + projected_layers = [] + for layer in layers: + pixels, z = project_camera_points(layer.vertices_camera, K) + pixel_vertices = np.concatenate((pixels, z[:, None]), axis=-1) + projected_layers.append(MeshLayer(pixel_vertices, layer.faces, layer.color_rgb, layer.alpha)) + return projected_layers + + +def draw_skeleton( + image_rgb: np.ndarray, + points: np.ndarray, + color_rgb: tuple[int, int, int], + *, + marker: str = "circle", + draw_edges: bool = True, +) -> np.ndarray: + image = image_rgb.copy() + finite = np.isfinite(points).all(axis=-1) + integer = np.rint(np.where(finite[:, None], points, 0)).astype(np.int32) + if draw_edges: + for start, end in OPENPOSE_HAND_EDGES: + if finite[start] and finite[end]: + cv2.line(image, tuple(integer[start]), tuple(integer[end]), color_rgb, 1, cv2.LINE_AA) + for index, point in enumerate(integer): + if not finite[index]: + continue + if marker == "cross": + cv2.drawMarker(image, tuple(point), color_rgb, cv2.MARKER_CROSS, 8, 1) + elif marker == "ring": + cv2.circle(image, tuple(point), 4, color_rgb, 1, cv2.LINE_AA) + else: + cv2.circle(image, tuple(point), 2, color_rgb, -1, cv2.LINE_AA) + return image + + +def save_attention_figure( + output: Path, + image_rgb: np.ndarray, + left: np.ndarray, + right: np.ndarray, + grid_hw: tuple[int, int], + title: str, +) -> None: + """Save raw and image overlays using a shared left/right attention scale.""" + + height, width = image_rgb.shape[:2] + left_grid = np.asarray(left, dtype=np.float32).reshape(grid_hw) + right_grid = np.asarray(right, dtype=np.float32).reshape(grid_hw) + lower = float(min(left_grid.min(), right_grid.min())) + upper = float(max(left_grid.max(), right_grid.max())) + if upper <= lower: + upper = lower + 1e-8 + fig, axes = plt.subplots(2, 2, figsize=(11, 7), constrained_layout=True) + images = [] + for column, (side, grid) in enumerate((('left', left_grid), ('right', right_grid))): + raw = axes[0, column].imshow(grid, cmap="turbo", vmin=lower, vmax=upper) + images.append(raw) + axes[0, column].set_title(f"{side}: raw weights") + axes[0, column].set_xlabel("patch x") + axes[0, column].set_ylabel("patch y") + upsampled = cv2.resize(grid, (width, height), interpolation=cv2.INTER_CUBIC) + axes[1, column].imshow(image_rgb) + axes[1, column].imshow(upsampled, cmap="turbo", alpha=0.45, vmin=lower, vmax=upper) + axes[1, column].set_title(f"{side}: RGB overlay") + axes[1, column].axis("off") + fig.colorbar(images[0], ax=axes, shrink=0.82, label="raw head-averaged attention weight") + wrapped_title = textwrap.fill(title, width=95) + fig.suptitle(f"{wrapped_title}\nlast layer, head-averaged; visualization is not calibrated probability", fontsize=11) + fig.savefig(output, dpi=160) + plt.close(fig) + + +def save_camera_views( + output: Path, + predicted: np.ndarray, + target: np.ndarray, + valid_hands: np.ndarray, + title: str, +) -> None: + fig, axes = plt.subplots(1, 2, figsize=(12, 5), constrained_layout=True) + colors = ("#22a06b", "#e56b2f") + for axis, view_name, horizontal_index in zip(axes, ("front", "side"), (0, 2), strict=True): + for hand in range(2): + axis.scatter( + predicted[hand, :, horizontal_index], predicted[hand, :, 1], + s=4, alpha=0.35, c=colors[hand], label=f"{'LR'[hand]} pred", + ) + if valid_hands[hand]: + axis.scatter( + target[hand, :, horizontal_index], target[hand, :, 1], + s=4, alpha=0.22, c="black", label=f"{'LR'[hand]} GT", + ) + axis.set_xlabel("x (m)" if horizontal_index == 0 else "z (m)") + axis.set_ylabel("y (m)") + axis.set_title(f"{view_name}: {'x-y' if horizontal_index == 0 else 'z-y'}") + axis.legend(fontsize=7) + axis.set_aspect("equal", adjustable="datalim") + axis.invert_yaxis() + axis.grid(alpha=0.25) + fig.suptitle(textwrap.fill(title, width=105), fontsize=11) + fig.savefig(output, dpi=160) + plt.close(fig) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/__init__.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..202e66331920bb936a0aeacff8fc23a08071a85e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/__init__.py @@ -0,0 +1,14 @@ +"""Camera and MANO geometry helpers.""" + +from .camera import depth_mm_to_m, intrinsics_from_h2o, project_points, unproject_depth +from .mano_translation import mano_raw_to_wrist, wrist_to_mano_raw + +__all__ = [ + "depth_mm_to_m", + "intrinsics_from_h2o", + "project_points", + "unproject_depth", + "mano_raw_to_wrist", + "wrist_to_mano_raw", +] + diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/camera.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..0f897cdebe7bd9cbd1a19c164a9b4909c72f6f4b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/camera.py @@ -0,0 +1,121 @@ +"""Camera-space geometry with explicit H2O units and image conventions.""" + +from __future__ import annotations + +from typing import overload + +import numpy as np +import torch + + +def intrinsics_from_h2o(values: np.ndarray) -> tuple[np.ndarray, tuple[int, int]]: + """Convert `fx fy cx cy width height` to K and `(height, width)`.""" + + values = np.asarray(values, dtype=np.float64).reshape(-1) + if values.size != 6: + raise ValueError(f"Expected 6 intrinsics values, got {values.size}") + fx, fy, cx, cy, width, height = values + if fx <= 0 or fy <= 0 or width <= 0 or height <= 0: + raise ValueError(f"Invalid intrinsics: {values.tolist()}") + K = np.array([[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]], dtype=np.float32) + return K, (int(round(height)), int(round(width))) + + +def depth_mm_to_m(depth_mm: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Convert released uint16 millimeter depth to metric depth plus validity.""" + + depth_m = np.asarray(depth_mm, dtype=np.float32) / 1000.0 + valid = np.isfinite(depth_m) & (depth_m > 0.0) + depth_m = np.where(valid, depth_m, 0.0).astype(np.float32) + return depth_m, valid + + +@overload +def project_points(points_camera: np.ndarray, K: np.ndarray) -> tuple[np.ndarray, np.ndarray]: ... + + +@overload +def project_points(points_camera: torch.Tensor, K: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: ... + + +def project_points(points_camera, K): + """Project x-right, y-down, z-forward camera points to image pixels.""" + + if isinstance(points_camera, torch.Tensor): + z = points_camera[..., 2] + safe_z = torch.where(z.abs() > 1e-8, z, torch.ones_like(z)) + fx, fy, cx, cy = K[..., 0, 0], K[..., 1, 1], K[..., 0, 2], K[..., 1, 2] + while fx.ndim < z.ndim: + fx, fy, cx, cy = (value.unsqueeze(-1) for value in (fx, fy, cx, cy)) + u = fx * points_camera[..., 0] / safe_z + cx + v = fy * points_camera[..., 1] / safe_z + cy + return torch.stack((u, v), dim=-1), z > 0 + + points = np.asarray(points_camera) + matrix = np.asarray(K) + z = points[..., 2] + safe_z = np.where(np.abs(z) > 1e-8, z, 1.0) + fx, fy, cx, cy = matrix[..., 0, 0], matrix[..., 1, 1], matrix[..., 0, 2], matrix[..., 1, 2] + while np.ndim(fx) < np.ndim(z): + fx, fy, cx, cy = (np.expand_dims(value, -1) for value in (fx, fy, cx, cy)) + u = fx * points[..., 0] / safe_z + cx + v = fy * points[..., 1] / safe_z + cy + return np.stack((u, v), axis=-1).astype(np.float32), z > 0 + + +def unproject_depth(depth_m: np.ndarray, K: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Unproject an HxW metric depth map to an HxWx3 camera-space point map.""" + + depth = np.asarray(depth_m, dtype=np.float32) + if depth.ndim != 2: + raise ValueError(f"Expected HxW depth, got {depth.shape}") + matrix = np.asarray(K, dtype=np.float32) + height, width = depth.shape + u, v = np.meshgrid(np.arange(width, dtype=np.float32), np.arange(height, dtype=np.float32)) + x = (u - matrix[0, 2]) * depth / matrix[0, 0] + y = (v - matrix[1, 2]) * depth / matrix[1, 1] + points = np.stack((x, y, depth), axis=-1) + valid = np.isfinite(depth) & (depth > 0.0) + points[~valid] = 0.0 + return points, valid + + +def resize_and_pad_intrinsics( + K: np.ndarray, + source_hw: tuple[int, int], + resized_hw: tuple[int, int], + pad_left_top: tuple[int, int] = (0, 0), +) -> np.ndarray: + """Update K for anisotropic resize followed by left/top pixel padding.""" + + source_h, source_w = source_hw + resized_h, resized_w = resized_hw + pad_left, pad_top = pad_left_top + if min(source_h, source_w, resized_h, resized_w) <= 0: + raise ValueError("Image sizes must be positive") + out = np.asarray(K, dtype=np.float32).copy() + sx = resized_w / source_w + sy = resized_h / source_h + out[0, 0] *= sx + out[0, 2] = out[0, 2] * sx + pad_left + out[1, 1] *= sy + out[1, 2] = out[1, 2] * sy + pad_top + return out + + +def patch_center_rays( + K: torch.Tensor, + grid_hw: tuple[int, int], + patch_size: int, +) -> torch.Tensor: + """Return unnormalized patch-center rays `[... , N, 3]`.""" + + grid_h, grid_w = grid_hw + dtype, device = K.dtype, K.device + u = (torch.arange(grid_w, dtype=dtype, device=device) + 0.5) * patch_size + v = (torch.arange(grid_h, dtype=dtype, device=device) + 0.5) * patch_size + vv, uu = torch.meshgrid(v, u, indexing="ij") + x = (uu.reshape(-1) - K[..., 0, 2].unsqueeze(-1)) / K[..., 0, 0].unsqueeze(-1) + y = (vv.reshape(-1) - K[..., 1, 2].unsqueeze(-1)) / K[..., 1, 1].unsqueeze(-1) + one = torch.ones_like(x) + return torch.stack((x, y, one), dim=-1) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/mano_compat.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/mano_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..92572790a447e15a1bed2ae8cfdec9473188276b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/mano_compat.py @@ -0,0 +1,26 @@ +"""Compatibility shim for the licensed MANO files and legacy chumpy loader.""" + +from __future__ import annotations + +import inspect + +import numpy as np + + +def enable_legacy_mano_loading() -> None: + """Restore names removed after the legacy MANO/chumpy release.""" + + if not hasattr(inspect, "getargspec"): + inspect.getargspec = inspect.getfullargspec # type: ignore[attr-defined] + aliases = { + "bool": bool, + "int": int, + "float": float, + "complex": complex, + "object": object, + "unicode": str, + "str": str, + } + for name, value in aliases.items(): + if name not in np.__dict__: + setattr(np, name, value) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/mano_translation.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/mano_translation.py new file mode 100644 index 0000000000000000000000000000000000000000..bd038e2956d172f29194b892244df021571b6ba5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/mano_translation.py @@ -0,0 +1,34 @@ +"""Conversion between H2O raw MANO translation and wrist/root translation.""" + +from __future__ import annotations + +import numpy as np +import torch + + +def mano_raw_to_wrist(raw_translation, mano_root_offset_m): + """Convert H2O raw MANO translation to camera-space MANO joint-0 position. + + H2OPlayer places native MANO joints using `joint_mm / 1000 + raw_translation`. + Therefore the wrist is the placed native joint 0, not the raw translation itself. + """ + + if isinstance(raw_translation, torch.Tensor): + return raw_translation + mano_root_offset_m + return np.asarray(raw_translation) + np.asarray(mano_root_offset_m) + + +def wrist_to_mano_raw(wrist_translation, mano_root_offset_m): + """Inverse of :func:`mano_raw_to_wrist`.""" + + if isinstance(wrist_translation, torch.Tensor): + return wrist_translation - mano_root_offset_m + return np.asarray(wrist_translation) - np.asarray(mano_root_offset_m) + + +def root_center_mano(vertices_m, joints_m): + """Root-center native MANO outputs while returning the removed root offset.""" + + root = joints_m[..., 0, :] + return vertices_m - root[..., None, :], joints_m - root[..., None, :], root + diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..a80850e3c6eaa88fd7f1501e539f629638d881bb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/mixed_projection.py @@ -0,0 +1,167 @@ +"""Differentiable mixed-projection translation solve.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch + + +@dataclass(frozen=True) +class TorchMixedProjectionResult: + translation_m: torch.Tensor + support_count: torch.Tensor + residual_scale_px: torch.Tensor + conditioning: torch.Tensor + inlier_ratio: torch.Tensor + uncertainty_xy_m: torch.Tensor + success: torch.Tensor + + +def _masked_lower_median(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + """Return the deterministic lower median along the joint dimension.""" + + if values.ndim != 2 or mask.shape != values.shape: + raise ValueError("masked median expects equal [N,J] tensors") + counts = mask.sum(dim=1) + ordered = torch.sort( + torch.where(mask, values, torch.full_like(values, torch.inf)), dim=1, + ).values + indices = ((counts - 1).clamp_min(0) // 2)[:, None] + selected = ordered.gather(1, indices).squeeze(1) + return torch.where(counts > 0, selected, torch.full_like(selected, torch.inf)) + + +def solve_mixed_projection_translation( + root_relative_joints_m: torch.Tensor, + anchors_px: torch.Tensor, + K: torch.Tensor, + refined_z_m: torch.Tensor, + fallback_translation_m: torch.Tensor, + *, + image_hw: tuple[int, int], + K_available: torch.Tensor | None = None, + minimum_support: int = 4, + huber_delta_px: float = 16.0, + irls_iterations: int = 5, + minimum_joint_depth_m: float = 0.05, + denominator_epsilon: float = 1e-10, +) -> TorchMixedProjectionResult: + """Solve tx/ty while retaining gradients through geometry and robust weights.""" + + if root_relative_joints_m.shape[-2:] != (21, 3): + raise ValueError("root-relative joints must end in [21,3]") + if anchors_px.shape != (*root_relative_joints_m.shape[:-1], 2): + raise ValueError("anchor shape differs from joints") + if K.shape != (*root_relative_joints_m.shape[:-2], 3, 3): + raise ValueError("K shape differs from joints") + if refined_z_m.shape != root_relative_joints_m.shape[:-2]: + raise ValueError("z shape differs from joints") + if fallback_translation_m.shape != (*refined_z_m.shape, 3): + raise ValueError("fallback translation shape differs from z") + if not 1 <= minimum_support <= 21: + raise ValueError("minimum_support must be in [1,21]") + if huber_delta_px <= 0.0 or irls_iterations < 1: + raise ValueError("Huber delta and IRLS iterations must be positive") + height, width = image_hw + if height <= 0 or width <= 0: + raise ValueError("image dimensions must be positive") + + prefix = refined_z_m.shape + count = refined_z_m.numel() + joints = root_relative_joints_m.reshape(count, 21, 3) + anchors = anchors_px.reshape(count, 21, 2) + intrinsics = K.reshape(count, 3, 3) + z = refined_z_m.reshape(count) + fallback = fallback_translation_m.reshape(count, 3) + available = ( + torch.ones(count, dtype=torch.bool, device=z.device) + if K_available is None else K_available.reshape(count).bool() + ) + fx, fy = intrinsics[:, 0, 0], intrinsics[:, 1, 1] + cx, cy = intrinsics[:, 0, 2], intrinsics[:, 1, 2] + joint_z = joints[..., 2] + z[:, None] + finite_k = torch.isfinite(intrinsics).all(dim=-1).all(dim=-1) & (fx > 1e-8) & (fy > 1e-8) + mask = ( + available[:, None] + & finite_k[:, None] + & torch.isfinite(z)[:, None] + & torch.isfinite(joints).all(dim=-1) + & torch.isfinite(anchors).all(dim=-1) + & (joint_z > minimum_joint_depth_m) + & (anchors[..., 0] >= 0.0) + & (anchors[..., 0] <= width - 1.0) + & (anchors[..., 1] >= 0.0) + & (anchors[..., 1] <= height - 1.0) + ) + support = mask.sum(dim=1) + safe_depth = torch.where(mask, joint_z, torch.ones_like(joint_z)) + ax = torch.where(mask, fx[:, None] / safe_depth, torch.zeros_like(safe_depth)) + ay = torch.where(mask, fy[:, None] / safe_depth, torch.zeros_like(safe_depth)) + bx = anchors[..., 0] - cx[:, None] - fx[:, None] * joints[..., 0] / safe_depth + by = anchors[..., 1] - cy[:, None] - fy[:, None] * joints[..., 1] / safe_depth + bx = torch.where(mask, bx, torch.zeros_like(bx)) + by = torch.where(mask, by, torch.zeros_like(by)) + + def solve(weights: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + denom_x = (weights * ax.square()).sum(dim=1) + denom_y = (weights * ay.square()).sum(dim=1) + tx = (weights * ax * bx).sum(dim=1) / denom_x.clamp_min(denominator_epsilon) + ty = (weights * ay * by).sum(dim=1) / denom_y.clamp_min(denominator_epsilon) + return tx, ty, denom_x, denom_y + + weights = mask.to(joints.dtype) + tx, ty, denom_x, denom_y = solve(weights) + for _ in range(irls_iterations): + residual = torch.sqrt( + (ax * tx[:, None] - bx).square() + + (ay * ty[:, None] - by).square() + + 1e-12 + ) + robust = torch.clamp(huber_delta_px / residual, max=1.0) + weights = torch.where(mask, robust, torch.zeros_like(robust)) + tx, ty, denom_x, denom_y = solve(weights) + + residual = torch.sqrt( + (ax * tx[:, None] - bx).square() + + (ay * ty[:, None] - by).square() + + 1e-12 + ) + median = _masked_lower_median(residual, mask) + mad = _masked_lower_median(torch.abs(residual - median[:, None]), mask) + scale = torch.where(support > 0, 1.4826 * mad, torch.full_like(mad, torch.inf)) + inlier_ratio = torch.where( + support > 0, + (mask & (residual <= huber_delta_px)).sum(dim=1).to(joints.dtype) + / support.clamp_min(1).to(joints.dtype), + torch.zeros_like(z), + ) + conditioning = torch.minimum(denom_x, denom_y) / torch.maximum( + denom_x, denom_y, + ).clamp_min(denominator_epsilon) + uncertainty = torch.stack(( + scale / torch.sqrt(denom_x.clamp_min(denominator_epsilon)), + scale / torch.sqrt(denom_y.clamp_min(denominator_epsilon)), + ), dim=-1) + success = ( + available & finite_k & (support >= minimum_support) + & (denom_x > denominator_epsilon) & (denom_y > denominator_epsilon) + & torch.isfinite(tx) & torch.isfinite(ty) + ) + solved = torch.stack((tx, ty, z), dim=-1) + translation = torch.where(success[:, None], solved, fallback) + finite_z = torch.isfinite(z) + use_selected_z = available & finite_k & finite_z + translation = torch.cat(( + translation[:, :2], + torch.where(use_selected_z, z, fallback[:, 2])[:, None], + ), dim=-1) + return TorchMixedProjectionResult( + translation_m=translation.reshape(*prefix, 3), + support_count=support.reshape(prefix), + residual_scale_px=scale.reshape(prefix), + conditioning=conditioning.reshape(prefix), + inlier_ratio=inlier_ratio.reshape(prefix), + uncertainty_xy_m=uncertainty.reshape(*prefix, 2), + success=success.reshape(prefix), + ) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/rotations.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/rotations.py new file mode 100644 index 0000000000000000000000000000000000000000..ed7d554d59c60675461eab9e9b0cf9e7b1728b77 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/geometry/rotations.py @@ -0,0 +1,70 @@ +"""Differentiable rotation representations used by prediction and losses.""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F + + +def rotation_6d_to_matrix(value: torch.Tensor) -> torch.Tensor: + if value.shape[-1] != 6: + raise ValueError(f"Expected rotation 6D, got {value.shape}") + first = F.normalize(value[..., :3], dim=-1) + second_raw = value[..., 3:] + second = F.normalize(second_raw - (first * second_raw).sum(dim=-1, keepdim=True) * first, dim=-1) + third = torch.cross(first, second, dim=-1) + return torch.stack((first, second, third), dim=-2) + + +def axis_angle_to_matrix(axis_angle: torch.Tensor) -> torch.Tensor: + """Rodrigues formula with a stable small-angle branch.""" + + if axis_angle.shape[-1] != 3: + raise ValueError(f"Expected axis-angle [...,3], got {axis_angle.shape}") + theta2 = (axis_angle * axis_angle).sum(dim=-1, keepdim=True) + theta = torch.sqrt(theta2.clamp_min(1e-16)) + a = torch.where(theta2 > 1e-8, torch.sin(theta) / theta, 1 - theta2 / 6 + theta2 * theta2 / 120) + # torch.where evaluates both branches, so the large-angle expression must + # also remain finite at exact zero for zero-initialized residual heads. + b = torch.where( + theta2 > 1e-8, + (1 - torch.cos(theta)) / theta2.clamp_min(1e-16), + 0.5 - theta2 / 24 + theta2 * theta2 / 720, + ) + x, y, z = axis_angle.unbind(dim=-1) + zero = torch.zeros_like(x) + skew = torch.stack((zero, -z, y, z, zero, -x, -y, x, zero), dim=-1).reshape(axis_angle.shape[:-1] + (3, 3)) + eye = torch.eye(3, dtype=axis_angle.dtype, device=axis_angle.device).expand(axis_angle.shape[:-1] + (3, 3)) + return eye + a.unsqueeze(-1) * skew + b.unsqueeze(-1) * (skew @ skew) + + +def matrix_to_axis_angle(matrix: torch.Tensor) -> torch.Tensor: + """Convert rotation matrices to axis-angle, including rotations near pi.""" + + if matrix.shape[-2:] != (3, 3): + raise ValueError(f"Expected rotation matrices, got {matrix.shape}") + m00, m01, m02 = matrix[..., 0, 0], matrix[..., 0, 1], matrix[..., 0, 2] + m10, m11, m12 = matrix[..., 1, 0], matrix[..., 1, 1], matrix[..., 1, 2] + m20, m21, m22 = matrix[..., 2, 0], matrix[..., 2, 1], matrix[..., 2, 2] + one = torch.ones_like(m00) + magnitudes = torch.sqrt(torch.stack(( + one + m00 + m11 + m22, + one + m00 - m11 - m22, + one - m00 + m11 - m22, + one - m00 - m11 + m22, + ), dim=-1).clamp_min(1e-12)) + candidates = torch.stack(( + torch.stack((magnitudes[..., 0].square(), m21 - m12, m02 - m20, m10 - m01), dim=-1), + torch.stack((m21 - m12, magnitudes[..., 1].square(), m01 + m10, m02 + m20), dim=-1), + torch.stack((m02 - m20, m01 + m10, magnitudes[..., 2].square(), m12 + m21), dim=-1), + torch.stack((m10 - m01, m02 + m20, m12 + m21, magnitudes[..., 3].square()), dim=-1), + ), dim=-2) + largest = magnitudes.argmax(dim=-1) + selected = candidates.gather(-2, largest[..., None, None].expand(largest.shape + (1, 4))).squeeze(-2) + divisor = 2 * magnitudes.gather(-1, largest[..., None]) + quaternion = selected / divisor + quaternion = torch.where(quaternion[..., :1] < 0, -quaternion, quaternion) + xyz = quaternion[..., 1:] + half_sine = torch.linalg.vector_norm(xyz, dim=-1, keepdim=True).clamp_min(1e-12) + angle = 2 * torch.atan2(half_sine, quaternion[..., :1]) + return xyz * (angle / half_sine) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/inference/__init__.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4e4eaa20d7002f3d29890cb7af9c24a735a8bf --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/inference/__init__.py @@ -0,0 +1,5 @@ +"""Length-generalized inference utilities.""" + +from .sequence import LengthGeneralizedInference, SequenceInferenceConfig + +__all__ = ["LengthGeneralizedInference", "SequenceInferenceConfig"] diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/inference/sequence.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/inference/sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..288f7b6fd1e09d0af4e624ed4c62a1ac13fcc4cc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/inference/sequence.py @@ -0,0 +1,212 @@ +"""Bounded-GPU-memory offline and causal sequence inference.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Iterable, Mapping + +import torch + + +@dataclass(frozen=True) +class SequenceInferenceConfig: + mode: str + window_size: int + offline_stride: int | None = None + stitching: str = "center" + + def __post_init__(self) -> None: + if self.mode not in {"offline", "causal"}: + raise ValueError(f"unknown sequence inference mode: {self.mode}") + if self.window_size < 1: + raise ValueError("window_size must be positive") + if self.offline_stride is not None and not 1 <= self.offline_stride <= self.window_size: + raise ValueError("offline_stride must be in [1, window_size]") + if self.stitching != "center": + raise ValueError("only fixed center stitching is registered") + + +class LengthGeneralizedInference: + """Run a model over a frame iterator without sequence-length GPU growth.""" + + _NON_TEMPORAL_OUTPUTS = { + "mano_shape_sequence", "coarse_mano_shape_sequence", "attention", + } + + def __init__( + self, + model: torch.nn.Module, + config: SequenceInferenceConfig, + *, + device: torch.device | str, + autocast_dtype: torch.dtype | None = None, + ) -> None: + self.model = model + self.config = config + self.device = torch.device(device) + self.autocast_dtype = autocast_dtype + model_config = getattr(model, "config", None) + attention_mode = getattr(model_config, "temporal_attention_mode", None) + if config.mode == "causal" and attention_mode != "causal": + raise ValueError( + "causal streaming requires temporal_attention_mode='causal'" + ) + self.maximum_resident_frames = 0 + self.maximum_input_buffer_frames = 0 + + @staticmethod + def _stack_frames(frames: list[Mapping[str, object]]) -> dict[str, object]: + if not frames: + raise ValueError("cannot stack an empty frame sequence") + output: dict[str, object] = {} + for key in frames[0]: + values = [frame[key] for frame in frames] + first = values[0] + if torch.is_tensor(first) and first.ndim >= 2 and first.shape[1] == 1: + if not all(torch.is_tensor(value) and value.shape[1] == 1 for value in values): + raise ValueError(f"inconsistent temporal field: {key}") + output[key] = torch.cat(values, dim=1) + else: + if torch.is_tensor(first) and not all( + torch.equal(first, value) for value in values[1:] + if torch.is_tensor(value) + ): + raise ValueError(f"non-temporal tensor changed within window: {key}") + output[key] = first + return output + + def _to_device(self, batch: Mapping[str, object]) -> dict[str, object]: + return { + key: value.to(self.device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + def _run_window(self, frames: list[Mapping[str, object]]) -> dict[str, object]: + self.maximum_resident_frames = max(self.maximum_resident_frames, len(frames)) + batch = self._to_device(self._stack_frames(frames)) + autocast_enabled = self.autocast_dtype is not None and self.device.type == "cuda" + with torch.inference_mode(), torch.autocast( + device_type=self.device.type, + dtype=self.autocast_dtype, + enabled=autocast_enabled, + ): + return self.model(batch) + + @classmethod + def _extract_frame( + cls, output: Mapping[str, object], index: int, time: int, + ) -> dict[str, torch.Tensor]: + frame: dict[str, torch.Tensor] = {} + for key, value in output.items(): + if ( + key not in cls._NON_TEMPORAL_OUTPUTS + and torch.is_tensor(value) + and value.ndim >= 2 + and value.shape[1] == time + ): + frame[key] = value[:, index : index + 1].detach().cpu() + if not frame: + raise ValueError("model output has no temporal tensors") + return frame + + @staticmethod + def _concatenate(frames: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]: + if not frames: + return {} + common = set.intersection(*(set(frame) for frame in frames)) + return { + key: torch.cat([frame[key] for frame in frames], dim=1) + for key in sorted(common) + } + + @staticmethod + def _window_starts(length: int, window: int, stride: int) -> list[int]: + if length <= window: + return [0] + starts = list(range(0, length - window + 1, stride)) + final = length - window + if starts[-1] != final: + starts.append(final) + return starts + + def infer_offline( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> dict[str, torch.Tensor]: + if self.config.mode != "offline": + raise ValueError("infer_offline requires mode='offline'") + window = self.config.window_size + stride = self.config.offline_stride or max(window // 2, 1) + buffer: list[Mapping[str, object]] = [] + buffer_start = 0 + total = 0 + next_start = 0 + last_start: int | None = None + selected: list[dict[str, torch.Tensor] | None] = [] + priority: list[int] = [] + + def run_window(start: int, local_frames: list[Mapping[str, object]]) -> None: + output = self._run_window(local_frames) + local_time = len(local_frames) + for local_index in range(local_time): + global_index = start + local_index + center_priority = min(local_index + 1, local_time - local_index) + if center_priority > priority[global_index]: + selected[global_index] = self._extract_frame( + output, local_index, local_time, + ) + priority[global_index] = center_priority + + for frame in frame_iterator: + buffer.append(frame) + selected.append(None) + priority.append(-1) + total += 1 + self.maximum_input_buffer_frames = max( + self.maximum_input_buffer_frames, len(buffer), + ) + while next_start + window <= total: + offset = next_start - buffer_start + run_window(next_start, buffer[offset : offset + window]) + last_start = next_start + next_start += stride + if last_start > buffer_start: + drop = last_start - buffer_start + del buffer[:drop] + buffer_start = last_start + if total == 0: + return {} + final_start = max(total - window, 0) + if last_start != final_start: + offset = final_start - buffer_start + run_window(final_start, buffer[offset:]) + if any(frame is None for frame in selected): + raise AssertionError("offline stitching omitted a frame") + return self._concatenate([frame for frame in selected if frame is not None]) + + def stream_causal( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> Iterable[dict[str, torch.Tensor]]: + if self.config.mode != "causal": + raise ValueError("stream_causal requires mode='causal'") + rolling: list[Mapping[str, object]] = [] + for frame in frame_iterator: + rolling.append(frame) + if len(rolling) > self.config.window_size: + rolling.pop(0) + self.maximum_input_buffer_frames = max( + self.maximum_input_buffer_frames, len(rolling), + ) + output = self._run_window(rolling) + yield self._extract_frame(output, len(rolling) - 1, len(rolling)) + + def infer_causal( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> dict[str, torch.Tensor]: + return self._concatenate(list(self.stream_causal(frame_iterator))) + + def infer( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> dict[str, torch.Tensor]: + if self.config.mode == "offline": + return self.infer_offline(frame_iterator) + return self.infer_causal(frame_iterator) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/__init__.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9cc5c23a03b9059a0eee77e5bb43735d2c70fcb3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/__init__.py @@ -0,0 +1,3 @@ +from foundation_hand.models.bimanual import BimanualReconstructionModel, ModelConfig + +__all__ = ["BimanualReconstructionModel", "ModelConfig"] diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/bimanual.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/bimanual.py new file mode 100644 index 0000000000000000000000000000000000000000..293df09ad9ecd40b19c972d672a48bdb870ac77d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/bimanual.py @@ -0,0 +1,1023 @@ +"""Unified RGB-D-K video bimanual reconstruction model.""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from pathlib import Path +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from foundation_hand.data.schema import input_availability +from foundation_hand.geometry.camera import patch_center_rays +from foundation_hand.geometry.mixed_projection import solve_mixed_projection_translation +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix +from foundation_hand.models.decoder import HandQueryDecoder +from foundation_hand.models.encoders import DepthGeometryEncoder, DinoV3Encoder, TinyPatchEncoder +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.models.structured_hand import ( + FINGER_PARTS, + PALM_PART, + ROOT_PART, + StructuredHandRefinement, +) + + +@dataclass +class ModelConfig: + encoder: str = "dinov3" + dinov3_source: str | None = None + dinov3_weights: str | None = None + dinov3_model: str = "dinov3_vitb16" + dinov3_dim: int = 768 + dinov3_trainable_last_blocks: int = 0 + decoder_dim: int = 512 + decoder_layers: int = 3 + attention_heads: int = 8 + patch_size: int = 16 + decoder_mode: str = "alternating" + use_temporal: bool = True + use_depth: bool = True + depth_mode: str = "log_depth" + use_rays: bool = True + use_bimanual_interaction: bool = True + depth_gate_floor: float = 0.0 + depth_gate_mode: str = "learned" + depth_gate_fixed_value: float = 0.5 + modality_dropout_prob: float = 0.0 + temporal_position_mode: str = "none" + temporal_relative_bias_max_distance: int = 15 + temporal_attention_mode: str = "bidirectional" + predict_presence: bool = True + mano_root: str | None = None + require_mano: bool = False + mano_fix_left_shapedirs: bool = False + gradient_checkpointing: bool = False + oracle_crop_mode: str = "none" + freeze_coarse_for_oracle_crop: bool = False + structured_hand_refinement: bool = False + structured_refinement_detach_locations: bool = True + structured_refinement_deterministic_detached_sampling: bool = False + structured_deformable_samples: int = 4 + structured_refine_translation: bool = True + translation_parameterization: str = "direct_xyz" + mixed_projection_minimum_support: int = 4 + mixed_projection_huber_delta_px: float = 16.0 + mixed_projection_irls_iterations: int = 5 + ray_depth_residual_max_m: float = 0.20 + ray_depth_enable_residual: bool = True + ray_depth_confidence_initial_logit: float = -4.0 + ray_depth_sample_radius_px: float = 8.0 + ray_depth_minimum_support: int = 3 + joint2d_parameterization: str = "hand_token_linear" + heatmap_offset_enabled: bool = True + heatmap_use_depth: bool = True + + +class BimanualReconstructionModel(nn.Module): + def __init__(self, config: ModelConfig, rgb_encoder: nn.Module | None = None) -> None: + super().__init__() + self.config = config + if not 0.0 <= config.modality_dropout_prob < 1.0: + raise ValueError("modality_dropout_prob must be in [0, 1)") + if config.oracle_crop_mode not in { + "none", "oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k", + }: + raise ValueError(f"unknown oracle crop mode: {config.oracle_crop_mode}") + if config.freeze_coarse_for_oracle_crop and config.oracle_crop_mode == "none": + raise ValueError("coarse freezing requires an oracle crop mode") + if config.structured_hand_refinement and config.oracle_crop_mode != "none": + raise ValueError("structured and oracle crop refinement are mutually exclusive") + if config.translation_parameterization not in { + "direct_xyz", "mixed_projection", "ray_depth_residual", + }: + raise ValueError( + f"unknown translation parameterization: {config.translation_parameterization}" + ) + if config.joint2d_parameterization not in { + "hand_token_linear", "spatial_heatmap", + }: + raise ValueError( + f"unknown joint2d parameterization: {config.joint2d_parameterization}" + ) + if ( + config.translation_parameterization in { + "mixed_projection", "ray_depth_residual", + } + and (config.structured_hand_refinement or config.oracle_crop_mode != "none") + ): + raise ValueError( + "mixed projection cannot be combined with an existing refinement branch" + ) + if config.ray_depth_residual_max_m <= 0.0: + raise ValueError("ray-depth residual bound must be positive") + if config.ray_depth_sample_radius_px <= 0.0: + raise ValueError("ray-depth sample radius must be positive") + if config.ray_depth_minimum_support <= 0: + raise ValueError("ray-depth minimum support must be positive") + if rgb_encoder is not None: + self.rgb_encoder = rgb_encoder + elif config.encoder == "dinov3": + if config.dinov3_source is None or config.dinov3_weights is None: + raise ValueError("Formal DINOv3 encoder requires explicit official source and local pretrained weights") + self.rgb_encoder = DinoV3Encoder( + Path(config.dinov3_source), Path(config.dinov3_weights), config.dinov3_model, + config.decoder_dim, config.dinov3_dim, frozen=True, + trainable_last_blocks=config.dinov3_trainable_last_blocks, + ) + elif config.encoder == "tiny_debug": + self.rgb_encoder = TinyPatchEncoder(config.decoder_dim, config.patch_size) + else: + raise ValueError(f"Unknown encoder: {config.encoder}") + if config.use_depth: + self.depth_encoder = DepthGeometryEncoder(config.decoder_dim, config.patch_size, config.depth_mode) + if config.use_rays: + self.ray_encoder = nn.Sequential(nn.Linear(4, config.decoder_dim), nn.GELU(), nn.Linear(config.decoder_dim, config.decoder_dim)) + self.hand_queries = nn.Parameter(torch.randn(2, config.decoder_dim) * 0.02) + self.side_embedding = nn.Parameter(torch.randn(2, config.decoder_dim) * 0.02) + self.decoder = HandQueryDecoder( + config.decoder_dim, config.decoder_layers, config.attention_heads, + config.use_depth, config.use_temporal, config.use_bimanual_interaction, config.decoder_mode, + config.gradient_checkpointing, config.depth_gate_floor, + config.depth_gate_mode, config.depth_gate_fixed_value, + config.temporal_position_mode, config.temporal_relative_bias_max_distance, + config.temporal_attention_mode, + ) + self.joint2d_head = nn.Linear(config.decoder_dim, 42) + if config.joint2d_parameterization == "spatial_heatmap": + dim = config.decoder_dim + self.joint_localization_embedding = nn.Parameter( + torch.randn(2, 21, dim) * 0.02, + ) + self.joint_localization_query = nn.Linear(dim, dim) + self.joint_localization_feature = nn.Sequential( + nn.LayerNorm(dim), nn.Linear(dim, dim), + ) + self.joint_localization_offset = nn.Sequential( + nn.LayerNorm(dim * 2), nn.Linear(dim * 2, 2), + ) + nn.init.zeros_(self.joint_localization_offset[-1].weight) + nn.init.zeros_(self.joint_localization_offset[-1].bias) + self.rotation_head = nn.Linear(config.decoder_dim, 16 * 6) + self.translation_head = nn.Linear(config.decoder_dim, 3) + if config.translation_parameterization == "mixed_projection": + self.mixed_log_tz_head = nn.Linear(config.decoder_dim, 1) + if config.translation_parameterization == "ray_depth_residual": + self.ray_depth_log_z_head = nn.Linear(config.decoder_dim, 1) + ray_depth_feature_dim = config.decoder_dim * 2 + 8 + self.ray_depth_delta_head = nn.Sequential( + nn.LayerNorm(ray_depth_feature_dim), + nn.Linear(ray_depth_feature_dim, config.decoder_dim), nn.GELU(), + nn.Linear(config.decoder_dim, 1), + ) + self.ray_depth_confidence_head = nn.Sequential( + nn.LayerNorm(ray_depth_feature_dim), + nn.Linear(ray_depth_feature_dim, config.decoder_dim), nn.GELU(), + nn.Linear(config.decoder_dim, 1), + ) + nn.init.zeros_(self.ray_depth_delta_head[-1].weight) + nn.init.zeros_(self.ray_depth_delta_head[-1].bias) + nn.init.zeros_(self.ray_depth_confidence_head[-1].weight) + self.ray_depth_confidence_head[-1].bias.data.fill_( + config.ray_depth_confidence_initial_logit, + ) + self.presence_head = nn.Linear(config.decoder_dim, 1) if config.predict_presence else None + self.shape_score = nn.Linear(config.decoder_dim, 1) + self.shape_head = nn.Linear(config.decoder_dim, 10) + self.mano_layer = ( + ManoCameraLayer( + config.mano_root, + fix_left_shapedirs=config.mano_fix_left_shapedirs, + ) + if config.mano_root is not None else None + ) + if config.require_mano and self.mano_layer is None: + raise ValueError("Formal camera-space MANO training requires a licensed mano_root") + self._initialize_structured_refiner() + self._initialize_oracle_crop_refiner() + self._initialize_prediction_heads() + if config.translation_parameterization == "mixed_projection": + # Retained only as a frozen missing-K/invalid-solve teacher fallback. + for parameter in self.translation_head.parameters(): + parameter.requires_grad_(False) + if config.joint2d_parameterization == "spatial_heatmap": + for parameter in self.joint2d_head.parameters(): + parameter.requires_grad_(False) + if config.freeze_coarse_for_oracle_crop: + for name, parameter in self.named_parameters(): + if not name.startswith("oracle_crop_"): + parameter.requires_grad_(False) + + def _initialize_oracle_crop_refiner(self) -> None: + mode = self.config.oracle_crop_mode + if mode == "none": + return + use_rgb = mode in {"oracle_rgb", "oracle_rgb_depth_k"} + use_depth = mode in {"oracle_depth_k", "oracle_rgb_depth_k"} + if use_depth and not self.config.use_depth: + raise ValueError("oracle Depth+K refinement requires the coarse depth encoder") + feature_dim = self.config.decoder_dim * (1 + int(use_rgb) + int(use_depth)) + feature_dim += int(use_rgb) + int(use_depth) + if use_depth: + feature_dim += 4 + self.oracle_crop_fusion = nn.Sequential( + nn.LayerNorm(feature_dim), + nn.Linear(feature_dim, self.config.decoder_dim), + nn.GELU(), + nn.Linear(self.config.decoder_dim, self.config.decoder_dim), + nn.GELU(), + ) + if use_rgb: + self.oracle_crop_rotation_head = nn.Linear( + self.config.decoder_dim, 16 * 3, + ) + self.oracle_crop_shape_head = nn.Linear(self.config.decoder_dim, 10) + nn.init.zeros_(self.oracle_crop_rotation_head.weight) + nn.init.zeros_(self.oracle_crop_rotation_head.bias) + nn.init.zeros_(self.oracle_crop_shape_head.weight) + nn.init.zeros_(self.oracle_crop_shape_head.bias) + if use_depth: + self.oracle_crop_delta_z_head = nn.Linear(self.config.decoder_dim, 1) + nn.init.zeros_(self.oracle_crop_delta_z_head.weight) + nn.init.zeros_(self.oracle_crop_delta_z_head.bias) + + def _initialize_structured_refiner(self) -> None: + if not self.config.structured_hand_refinement: + return + dim = self.config.decoder_dim + self.structured_refiner = StructuredHandRefinement( + dim, self.config.attention_heads, use_depth=self.config.use_depth, + samples=self.config.structured_deformable_samples, + ) + self.structured_root_orientation_head = nn.Linear(dim, 3) + self.structured_finger_rotation_head = nn.Linear(dim, 3 * 3) + self.structured_translation_head = nn.Linear(dim, 3) + self.structured_shape_head = nn.Linear(dim, 10) + self.structured_root_2d_head = nn.Linear(dim, 2) + self.structured_finger_2d_head = nn.Linear(dim, 4 * 2) + for head in ( + self.structured_root_orientation_head, + self.structured_finger_rotation_head, + self.structured_translation_head, + self.structured_shape_head, + self.structured_root_2d_head, + self.structured_finger_2d_head, + ): + nn.init.zeros_(head.weight) + nn.init.zeros_(head.bias) + + def _initialize_prediction_heads(self) -> None: + """Start metric heads from finite, physically valid neutral predictions.""" + + identity_6d = torch.tensor((1.0, 0.0, 0.0, 0.0, 1.0, 0.0)) + with torch.no_grad(): + nn.init.zeros_(self.joint2d_head.weight) + nn.init.zeros_(self.joint2d_head.bias) + nn.init.zeros_(self.rotation_head.weight) + self.rotation_head.bias.copy_(identity_6d.repeat(16)) + nn.init.zeros_(self.translation_head.weight) + # softplus(inverse_softplus(0.6)) starts the wrist at z=0.6 m. + self.translation_head.bias.copy_(torch.tensor((0.0, 0.0, -0.19587037))) + if self.config.translation_parameterization == "mixed_projection": + nn.init.zeros_(self.mixed_log_tz_head.weight) + self.mixed_log_tz_head.bias.fill_(torch.log(torch.tensor(0.6))) + if self.config.translation_parameterization == "ray_depth_residual": + nn.init.zeros_(self.ray_depth_log_z_head.weight) + self.ray_depth_log_z_head.bias.fill_(torch.log(torch.tensor(0.6))) + nn.init.zeros_(self.shape_head.weight) + nn.init.zeros_(self.shape_head.bias) + if self.presence_head is not None: + nn.init.zeros_(self.presence_head.weight) + nn.init.zeros_(self.presence_head.bias) + + def forward(self, batch: dict[str, torch.Tensor]) -> dict[str, Any]: + rgb = batch["rgb"] + if rgb.ndim != 5: + raise ValueError(f"Expected RGB [B,T,3,H,W], got {rgb.shape}") + batch_size, time, _, height, width = rgb.shape + frame_valid = batch["frame_valid"].bool() + features = self.rgb_encoder(rgb.reshape(batch_size * time, 3, height, width)) + tokens = features.tokens + if "K" in batch: + K = batch["K"].reshape(batch_size * time, 3, 3).to(tokens.dtype) + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ).reshape(batch_size * time) + else: + K = torch.eye(3, dtype=tokens.dtype, device=tokens.device)[None].expand(batch_size * time, -1, -1) + K_available = torch.zeros(batch_size * time, dtype=torch.bool, device=tokens.device) + if self.training and self.config.modality_dropout_prob > 0.0 and self.config.use_rays: + keep_probability = 1.0 - self.config.modality_dropout_prob + K_available = K_available & ( + torch.rand(K_available.shape, device=K_available.device) < keep_probability + ) + if self.config.use_rays: + rays = patch_center_rays(K, features.grid_hw, features.patch_size) + availability = K_available.reshape(-1, 1, 1) + ray_inputs = torch.cat((rays, availability.expand(-1, rays.shape[1], 1).to(rays.dtype)), dim=-1) + tokens = tokens + self.ray_encoder(ray_inputs) * availability.to(tokens.dtype) + rgb_tokens = tokens.reshape(batch_size, time, tokens.shape[1], tokens.shape[2]) + + depth_tokens = None + depth_available = input_availability( + batch, + "depth_input_available", + "depth_available", + torch.zeros( + (batch_size, time), device=rgb.device, dtype=torch.bool, + ), + ) & frame_valid + # Training-only independent modality dropout tests fallback robustness without + # mutating the dataset availability contract or validation behavior. + if self.training and self.config.modality_dropout_prob > 0.0: + keep_probability = 1.0 - self.config.modality_dropout_prob + if self.config.use_depth: + depth_available = depth_available & ( + torch.rand(depth_available.shape, device=depth_available.device) < keep_probability + ) + if self.config.use_depth: + depth_m = batch.get("depth_m") + depth_pixel_valid = batch.get("depth_pixel_valid") + if depth_m is None or depth_pixel_valid is None: + depth_m = torch.zeros((batch_size, time, 1, height, width), dtype=rgb.dtype, device=rgb.device) + depth_pixel_valid = torch.zeros_like(depth_m, dtype=torch.bool) + depth_available = torch.zeros_like(frame_valid) + if self.config.depth_mode == "geometry": + depth_available = depth_available & K_available.reshape(batch_size, time) + depth_features = self.depth_encoder( + depth_m.reshape(batch_size * time, 1, height, width).to(tokens.dtype), + depth_pixel_valid.reshape(batch_size * time, 1, height, width), K, + ) + if depth_features.grid_hw != features.grid_hw: + raise ValueError(f"RGB/depth patch grids differ: {features.grid_hw} vs {depth_features.grid_hw}") + depth_tokens = depth_features.tokens.reshape(batch_size, time, depth_features.tokens.shape[1], depth_features.tokens.shape[2]) + + initial_query = ( + self.hand_queries + self.side_embedding + )[None, None].expand(batch_size, time, -1, -1) + rgb_only_query = None + rgb_only_attention = None + if self.config.translation_parameterization == "ray_depth_residual": + rgb_only_query, rgb_only_attention = self.decoder( + initial_query, rgb_tokens, None, frame_valid, + torch.zeros_like(depth_available), self.side_embedding[None], + ) + query, attention = self.decoder( + initial_query, rgb_tokens, depth_tokens, frame_valid, + depth_available, self.side_embedding[None], + ) + linear_joint2d_norm = torch.sigmoid( + self.joint2d_head(query).reshape(batch_size, time, 2, 21, 2) + ) + joint2d_output: dict[str, torch.Tensor] = {} + if self.config.joint2d_parameterization == "spatial_heatmap": + joint2d_norm, joint2d_output = self._spatial_joint2d( + query, rgb_tokens, depth_tokens, depth_available, + features.grid_hw, + ) + joint2d_output["joint2d_linear_teacher_norm"] = linear_joint2d_norm.detach() + else: + joint2d_norm = linear_joint2d_norm + rotations_6d = self.rotation_head(query).reshape(batch_size, time, 2, 16, 6) + translation_token = rgb_only_query if rgb_only_query is not None else query + translation_raw = self.translation_head(translation_token) + wrist_translation = torch.cat( + (translation_raw[..., :2], F.softplus(translation_raw[..., 2:3]) + 1e-4), dim=-1 + ) + + score = self.shape_score(query).squeeze(-1).masked_fill(~frame_valid[:, :, None], -torch.inf) + shape_weights = torch.softmax(score, dim=1) + pooled = (query * shape_weights[..., None]).sum(dim=1) + shape = self.shape_head(pooled) + rotation_matrices = rotation_6d_to_matrix(rotations_6d) + shape_sequence = shape + expanded_shape = shape[:, None].expand(-1, time, -1, -1) + refined_translation = wrist_translation + mixed_projection_output: dict[str, torch.Tensor] = {} + if self.config.translation_parameterization == "mixed_projection": + refined_translation, mixed_projection_output = self._apply_mixed_projection( + batch, query, joint2d_norm, rotation_matrices, expanded_shape, + wrist_translation, frame_valid, height=height, width=width, + ) + ray_depth_output: dict[str, torch.Tensor] = {} + if self.config.translation_parameterization == "ray_depth_residual": + if rgb_only_query is None: + raise RuntimeError("ray-depth translation requires an RGB-only query") + refined_translation, ray_depth_output = self._apply_ray_depth_translation( + batch, rgb_only_query, query, wrist_translation, frame_valid, + depth_available, height=height, width=width, + ) + ray_depth_output["rgb_only_translation_attention"] = rgb_only_attention + structured_output: dict[str, torch.Tensor] = {} + if self.config.structured_hand_refinement: + ( + joint2d_norm, rotation_matrices, shape_sequence, + expanded_shape, refined_translation, structured_output, + ) = self._apply_structured_refinement( + query, joint2d_norm, rgb_tokens, depth_tokens, features.grid_hw, + frame_valid, depth_available, rotation_matrices, shape, + expanded_shape, wrist_translation, shape_weights, + ) + oracle_output: dict[str, torch.Tensor] = {} + if self.config.oracle_crop_mode != "none": + rotation_matrices, shape_sequence, expanded_shape, refined_translation, oracle_output = ( + self._apply_oracle_crop_refinement( + batch, query, rotation_matrices, shape, expanded_shape, + wrist_translation, shape_weights, frame_valid, + depth_available, + ) + ) + output: dict[str, Any] = { + "hand_tokens": query, + "joint2d_norm": joint2d_norm, + "mano_rotations_6d": rotations_6d, + "mano_rotation_matrices": rotation_matrices, + "mano_shape_sequence": shape_sequence, + "mano_shape": expanded_shape, + "wrist_root_translation": refined_translation, + "shape_pool_weights": shape_weights, + "attention": attention, + "translation_parameterization": self.config.translation_parameterization, + "joint2d_parameterization": self.config.joint2d_parameterization, + **joint2d_output, + **mixed_projection_output, + **ray_depth_output, + **structured_output, + **oracle_output, + } + if self.presence_head is not None: + output["presence_logit"] = self.presence_head(query).squeeze(-1) + if self.mano_layer is not None: + if self.config.oracle_crop_mode != "none": + coarse_vertices, coarse_joints = self.mano_layer( + output["coarse_mano_rotation_matrices"], + output["coarse_mano_shape"], + output["coarse_wrist_root_translation"], + ) + output["coarse_vertices_camera"] = coarse_vertices + output["coarse_joints_camera"] = coarse_joints + vertices, joints = self.mano_layer( + output["mano_rotation_matrices"], output["mano_shape"], output["wrist_root_translation"] + ) + output["vertices_camera"] = vertices + output["joints_camera"] = joints + return output + + def _spatial_joint2d( + self, + hand_tokens: torch.Tensor, + rgb_tokens: torch.Tensor, + depth_tokens: torch.Tensor | None, + depth_available: torch.Tensor, + grid_hw: tuple[int, int], + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + spatial = rgb_tokens + if self.config.heatmap_use_depth and depth_tokens is not None: + spatial = spatial + 0.5 * depth_tokens * depth_available[ + :, :, None, None + ].to(depth_tokens.dtype) + spatial = self.joint_localization_feature(spatial) + joint_query = self.joint_localization_query(hand_tokens)[..., None, :] + joint_query = joint_query + self.joint_localization_embedding[None, None] + logits = torch.einsum( + "bthjd,btsd->bthjs", joint_query, spatial, + ) / (spatial.shape[-1] ** 0.5) + probability_float = torch.softmax(logits.float(), dim=-1) + probabilities = probability_float.to(spatial.dtype) + grid_height, grid_width = grid_hw + if grid_height * grid_width != spatial.shape[-2]: + raise ValueError("joint heatmap grid differs from encoded feature grid") + rows, columns = torch.meshgrid( + torch.arange(grid_height, device=spatial.device), + torch.arange(grid_width, device=spatial.device), indexing="ij", + ) + centers = torch.stack(( + (columns.reshape(-1) + 0.5) / grid_width, + (rows.reshape(-1) + 0.5) / grid_height, + ), dim=-1).to(dtype=probability_float.dtype) + coordinates = torch.einsum("bthjs,sd->bthjd", probability_float, centers) + pooled = torch.einsum("bthjs,btsd->bthjd", probabilities, spatial) + raw_offset = self.joint_localization_offset(torch.cat((joint_query, pooled), dim=-1)) + patch_scale = raw_offset.new_tensor((1.0 / grid_width, 1.0 / grid_height)) + offset = ( + torch.tanh(raw_offset) * patch_scale + if self.config.heatmap_offset_enabled else torch.zeros_like(raw_offset) + ) + coordinates = (coordinates + offset).clamp(0.0, 1.0) + probability_float = probability_float.clamp_min(1e-12) + entropy = -( + probability_float * probability_float.log() + ).sum(dim=-1) / math.log(float(spatial.shape[-2])) + return coordinates, { + "joint2d_heatmap_logits": logits, + "joint2d_heatmap_entropy": entropy, + "joint2d_heatmap_confidence": 1.0 - entropy, + "joint2d_heatmap_offset_norm": offset, + } + + def initialize_mixed_log_tz_from_direct_head( + self, reference_raw: float = -0.19587037, + ) -> None: + """Linearize log(softplus(x)) around the historical 0.6 m prior.""" + + if self.config.translation_parameterization != "mixed_projection": + raise RuntimeError("mixed log-tz initialization requires mixed projection") + reference = self.translation_head.bias.new_tensor(reference_raw) + reference_depth = F.softplus(reference) + 1e-4 + slope = torch.sigmoid(reference) / reference_depth + with torch.no_grad(): + self.mixed_log_tz_head.weight.copy_( + slope * self.translation_head.weight[2:3] + ) + self.mixed_log_tz_head.bias.copy_( + torch.log(reference_depth) + + slope * (self.translation_head.bias[2:3] - reference) + ) + + def initialize_ray_depth_from_direct_head( + self, reference_raw: float = -0.19587037, + ) -> None: + """Warm-start RGB base-z while retaining the direct no-K fallback.""" + + if self.config.translation_parameterization != "ray_depth_residual": + raise RuntimeError("ray-depth initialization requires ray_depth_residual") + reference = self.translation_head.bias.new_tensor(reference_raw) + reference_depth = F.softplus(reference) + 1e-4 + slope = torch.sigmoid(reference) / reference_depth + with torch.no_grad(): + self.ray_depth_log_z_head.weight.copy_( + slope * self.translation_head.weight[2:3] + ) + self.ray_depth_log_z_head.bias.copy_( + torch.log(reference_depth) + + slope * (self.translation_head.bias[2:3] - reference) + ) + + def _sample_local_depth_statistics( + self, + batch: dict[str, torch.Tensor], + wrist_norm: torch.Tensor, + base_z: torch.Tensor, + available: torch.Tensor, + *, + height: int, + width: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Sample a deterministic 3x3 metric-depth stencil at predicted wrists.""" + + batch_size, time, hands = wrist_norm.shape[:3] + depth = batch.get("depth_m") + valid_image = batch.get("depth_pixel_valid") + if depth is None or valid_image is None: + statistics = base_z.new_zeros(batch_size, time, hands, 8) + support = torch.zeros_like(base_z, dtype=torch.long) + return statistics, support + radius = float(self.config.ray_depth_sample_radius_px) + offsets = wrist_norm.new_tensor([ + (-radius, -radius), (0.0, -radius), (radius, -radius), + (-radius, 0.0), (0.0, 0.0), (radius, 0.0), + (-radius, radius), (0.0, radius), (radius, radius), + ]) + offset_norm = offsets * offsets.new_tensor((2.0 / width, 2.0 / height)) + grid = wrist_norm[..., None, :] * 2.0 - 1.0 + offset_norm + in_frame = (grid.abs() <= 1.0).all(dim=-1) + grid = grid.reshape(batch_size * time, hands * 9, 1, 2).float() + sampled_depth = F.grid_sample( + depth.reshape(batch_size * time, 1, height, width).float(), + grid, mode="nearest", padding_mode="zeros", align_corners=False, + ).reshape(batch_size, time, hands, 9) + sampled_valid = F.grid_sample( + valid_image.reshape(batch_size * time, 1, height, width).float(), + grid, mode="nearest", padding_mode="zeros", align_corners=False, + ).reshape(batch_size, time, hands, 9) > 0.5 + valid = ( + sampled_valid & in_frame & available[..., None, None] + & torch.isfinite(sampled_depth) & (sampled_depth > 0.02) + & (sampled_depth < 3.0) + ) + support = valid.sum(dim=-1) + safe = torch.where(valid, sampled_depth, torch.zeros_like(sampled_depth)) + denominator = support.clamp_min(1).to(base_z.dtype) + mean = safe.sum(dim=-1) / denominator + variance = ( + torch.where(valid, (sampled_depth - mean[..., None]).square(), + torch.zeros_like(sampled_depth)).sum(dim=-1) + / denominator + ) + nan_values = torch.where( + valid, sampled_depth, + torch.full_like(sampled_depth, float("nan")), + ) + median = torch.nanmedian(nan_values, dim=-1).values + minimum = torch.where( + valid, sampled_depth, torch.full_like(sampled_depth, float("inf")), + ).min(dim=-1).values + maximum = torch.where( + valid, sampled_depth, torch.full_like(sampled_depth, float("-inf")), + ).max(dim=-1).values + any_valid = support > 0 + median = torch.where(any_valid, median, torch.zeros_like(median)) + minimum = torch.where(any_valid, minimum, torch.zeros_like(minimum)) + maximum = torch.where(any_valid, maximum, torch.zeros_like(maximum)) + statistics = torch.stack(( + support.to(base_z.dtype) / 9.0, + median, median - base_z, minimum, maximum, + maximum - minimum, mean, variance.clamp_min(0.0).sqrt(), + ), dim=-1).to(base_z.dtype) + return statistics, support + + def _apply_ray_depth_translation( + self, + batch: dict[str, torch.Tensor], + rgb_query: torch.Tensor, + fused_query: torch.Tensor, + direct_fallback: torch.Tensor, + frame_valid: torch.Tensor, + depth_available: torch.Tensor, + *, + height: int, + width: int, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + wrist_norm = torch.sigmoid( + self.joint2d_head(rgb_query).reshape(*rgb_query.shape[:3], 21, 2) + )[..., 0, :] + log_base_z = self.ray_depth_log_z_head(rgb_query).squeeze(-1).clamp(-3.0, 1.0) + base_z = torch.exp(log_base_z) + if "K" in batch: + K = batch["K"].to(rgb_query.dtype) + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ) & frame_valid + else: + K = torch.eye( + 3, dtype=rgb_query.dtype, device=rgb_query.device, + )[None, None].expand(*frame_valid.shape, -1, -1) + K_available = torch.zeros_like(frame_valid) + usable_depth = depth_available & K_available + statistics, support = self._sample_local_depth_statistics( + batch, wrist_norm, base_z, usable_depth, + height=height, width=width, + ) + features = torch.cat((rgb_query, fused_query - rgb_query, statistics), dim=-1) + raw_delta = float(self.config.ray_depth_residual_max_m) * torch.tanh( + self.ray_depth_delta_head(features).squeeze(-1) + ) + confidence_logit = self.ray_depth_confidence_head(features).squeeze(-1) + correction_valid = ( + usable_depth[:, :, None] + & (support >= int(self.config.ray_depth_minimum_support)) + ) + if not self.config.ray_depth_enable_residual: + correction_valid = torch.zeros_like(correction_valid) + confidence = torch.where( + correction_valid, torch.sigmoid(confidence_logit), + torch.zeros_like(confidence_logit), + ) + delta = torch.where(correction_valid, raw_delta, torch.zeros_like(raw_delta)) + refined_z = (base_z + confidence * delta).clamp(0.05, 3.0) + u = wrist_norm[..., 0] * float(width) + v = wrist_norm[..., 1] * float(height) + fx = K[..., 0, 0][:, :, None].clamp_min(1e-6) + fy = K[..., 1, 1][:, :, None].clamp_min(1e-6) + cx = K[..., 0, 2][:, :, None] + cy = K[..., 1, 2][:, :, None] + ray_x = (u - cx) / fx + ray_y = (v - cy) / fy + assembled = torch.stack((ray_x * refined_z, ray_y * refined_z, refined_z), dim=-1) + use_ray = K_available[:, :, None, None] & frame_valid[:, :, None, None] + translation = torch.where(use_ray, assembled, direct_fallback) + translation = torch.where( + frame_valid[:, :, None, None], translation, + torch.zeros_like(translation), + ) + return translation, { + "ray_depth_wrist2d_norm": wrist_norm, + "ray_depth_log_base_z": log_base_z, + "ray_depth_base_z_m": base_z, + "ray_depth_raw_delta_z_m": delta, + "ray_depth_applied_delta_z_m": confidence * delta, + "ray_depth_confidence_logit": confidence_logit, + "ray_depth_confidence": confidence, + "ray_depth_local_statistics": statistics, + "ray_depth_support_count": support, + "ray_depth_correction_valid": correction_valid, + "ray_depth_K_input_available": K_available, + "ray_depth_direct_fallback_translation": direct_fallback, + } + + def _apply_mixed_projection( + self, + batch: dict[str, torch.Tensor], + hand_tokens: torch.Tensor, + joint2d_norm: torch.Tensor, + rotation_matrices: torch.Tensor, + expanded_shape: torch.Tensor, + direct_translation: torch.Tensor, + frame_valid: torch.Tensor, + *, + height: int, + width: int, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + if self.mano_layer is None: + raise RuntimeError("mixed projection requires the MANO camera layer") + log_tz = self.mixed_log_tz_head(hand_tokens).squeeze(-1).clamp(-3.0, 1.0) + tz = torch.exp(log_tz) + zero_translation = torch.zeros_like(direct_translation) + _, canonical_joints = self.mano_layer( + rotation_matrices, expanded_shape, zero_translation, + ) + root_relative_joints = canonical_joints - canonical_joints[..., :1, :] + anchors_px = joint2d_norm * joint2d_norm.new_tensor((width, height)) + if "K" in batch: + K = batch["K"].to(joint2d_norm.dtype) + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ) & frame_valid + else: + K = torch.eye( + 3, dtype=joint2d_norm.dtype, device=joint2d_norm.device, + )[None, None].expand(*frame_valid.shape, -1, -1) + K_available = torch.zeros_like(frame_valid) + K = K[:, :, None].expand(-1, -1, 2, -1, -1) + K_available = K_available[:, :, None].expand(-1, -1, 2) + result = solve_mixed_projection_translation( + root_relative_joints, anchors_px, K, tz, direct_translation, + image_hw=(height, width), K_available=K_available, + minimum_support=self.config.mixed_projection_minimum_support, + huber_delta_px=self.config.mixed_projection_huber_delta_px, + irls_iterations=self.config.mixed_projection_irls_iterations, + ) + translation = torch.where( + frame_valid[:, :, None, None], + result.translation_m, + torch.zeros_like(result.translation_m), + ) + return translation, { + "mixed_projection_log_tz": log_tz, + "mixed_projection_direct_teacher_translation": direct_translation.detach(), + "mixed_projection_support_count": result.support_count, + "mixed_projection_residual_scale_px": result.residual_scale_px, + "mixed_projection_conditioning": result.conditioning, + "mixed_projection_inlier_ratio": result.inlier_ratio, + "mixed_projection_uncertainty_xy_m": result.uncertainty_xy_m, + "mixed_projection_success": result.success, + } + + def _apply_structured_refinement( + self, + coarse_hand_tokens: torch.Tensor, + coarse_joint2d_norm: torch.Tensor, + rgb_tokens: torch.Tensor, + depth_tokens: torch.Tensor | None, + grid_hw: tuple[int, int], + frame_valid: torch.Tensor, + depth_available: torch.Tensor, + coarse_rotations: torch.Tensor, + coarse_shape_sequence: torch.Tensor, + coarse_shape: torch.Tensor, + coarse_translation: torch.Tensor, + shape_pool_weights: torch.Tensor, + ) -> tuple[ + torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, + dict[str, torch.Tensor], + ]: + part_tokens, diagnostics = self.structured_refiner( + coarse_hand_tokens, coarse_joint2d_norm, rgb_tokens, depth_tokens, + grid_hw, frame_valid, depth_available, + detach_locations=self.config.structured_refinement_detach_locations, + deterministic_detached_sampling=( + self.config.structured_refinement_deterministic_detached_sampling + ), + ) + root_token = part_tokens[..., ROOT_PART, :] + palm_token = part_tokens[..., PALM_PART, :] + finger_tokens = part_tokens[..., FINGER_PARTS, :] + + root_rotation_delta = self._bounded_axis_angle( + self.structured_root_orientation_head(root_token), + ) + finger_rotation_delta = self._bounded_axis_angle( + self.structured_finger_rotation_head(finger_tokens).reshape( + *finger_tokens.shape[:-1], 3, 3, + ) + ) + rotation_delta = torch.cat(( + root_rotation_delta[..., None, :], + finger_rotation_delta.reshape(*finger_rotation_delta.shape[:3], 15, 3), + ), dim=-2) + rotation_delta = rotation_delta * frame_valid[ + :, :, None, None, None + ].to(rotation_delta.dtype) + refined_rotations = self._compose_rotation_residual( + coarse_rotations, rotation_delta, + ) + + if self.config.structured_refine_translation: + translation_raw = self.structured_translation_head(root_token) + translation_scale = torch.tensor( + (0.05, 0.05, 0.12), dtype=translation_raw.dtype, + device=translation_raw.device, + ) + translation_delta = translation_scale * translation_raw / torch.sqrt( + 1.0 + translation_raw.square(), + ) + translation_delta = translation_delta * frame_valid[ + :, :, None, None + ].to(translation_delta.dtype) + else: + translation_delta = torch.zeros_like(coarse_translation) + refined_translation = coarse_translation + translation_delta + + raw_shape_delta = torch.tanh(self.structured_shape_head(palm_token)) + shape_delta = ( + raw_shape_delta * shape_pool_weights[..., None] + ).sum(dim=1) + refined_shape_sequence = coarse_shape_sequence + shape_delta + refined_shape = coarse_shape + shape_delta[:, None] + + joint2d_delta = torch.zeros_like(coarse_joint2d_norm) + joint2d_delta[..., 0, :] = self.structured_root_2d_head(root_token) + joint2d_delta[..., 1:, :] = self.structured_finger_2d_head( + finger_tokens, + ).reshape(*finger_tokens.shape[:3], 20, 2) + joint2d_delta = 0.1 * torch.tanh(joint2d_delta) + joint2d_delta = joint2d_delta * frame_valid[ + :, :, None, None, None + ].to(joint2d_delta.dtype) + refined_joint2d = (coarse_joint2d_norm + joint2d_delta).clamp(0.0, 1.0) + return ( + refined_joint2d, refined_rotations, refined_shape_sequence, + refined_shape, refined_translation, + { + "coarse_joint2d_norm": coarse_joint2d_norm, + "coarse_mano_rotation_matrices": coarse_rotations, + "coarse_mano_shape_sequence": coarse_shape_sequence, + "coarse_mano_shape": coarse_shape, + "coarse_wrist_root_translation": coarse_translation, + "structured_part_tokens": part_tokens, + "structured_rotation_delta_axis_angle": rotation_delta, + "structured_translation_delta": translation_delta, + "structured_shape_delta": shape_delta, + "structured_joint2d_delta": joint2d_delta, + **diagnostics, + }, + ) + + @staticmethod + def _bounded_axis_angle(raw: torch.Tensor, maximum_radians: float = 0.35) -> torch.Tensor: + denominator = torch.sqrt(1.0 + (raw * raw).sum(dim=-1, keepdim=True)) + return maximum_radians * raw / denominator + + @staticmethod + def _compose_rotation_residual( + coarse: torch.Tensor, delta_axis_angle: torch.Tensor, + ) -> torch.Tensor: + delta_matrix = axis_angle_to_matrix(delta_axis_angle) + identity = torch.eye( + 3, dtype=delta_matrix.dtype, device=delta_matrix.device, + ) + # This is algebraically coarse @ delta_matrix, but its zero-residual + # path is coarse + coarse @ 0. Direct BF16 coarse @ I can re-round the + # coarse matrix and violate the registered exact initialization gate. + return coarse + coarse @ (delta_matrix - identity) + + def _apply_oracle_crop_refinement( + self, + batch: dict[str, torch.Tensor], + coarse_hand_tokens: torch.Tensor, + coarse_rotations: torch.Tensor, + coarse_shape_sequence: torch.Tensor, + coarse_shape: torch.Tensor, + coarse_translation: torch.Tensor, + shape_pool_weights: torch.Tensor, + frame_valid: torch.Tensor, + coarse_depth_available: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]: + required = {"oracle_crop_available"} + mode = self.config.oracle_crop_mode + use_rgb = mode in {"oracle_rgb", "oracle_rgb_depth_k"} + use_depth = mode in {"oracle_depth_k", "oracle_rgb_depth_k"} + if use_rgb: + required.add("oracle_crop_rgb") + if use_depth: + required.update({ + "oracle_crop_depth_m", "oracle_crop_depth_pixel_valid", + "oracle_crop_depth_available", "oracle_crop_K", + }) + missing = sorted(required - batch.keys()) + if missing: + raise ValueError(f"oracle crop mode requires batch fields: {missing}") + + batch_size, time, hands, dim = coarse_hand_tokens.shape + if hands != 2: + raise ValueError("oracle crop refinement expects two hand tokens") + roi_available = batch["oracle_crop_available"].bool() & frame_valid[:, :, None] + parts = [coarse_hand_tokens] + availability_parts = [] + rgb_available = roi_available if use_rgb else torch.zeros_like(roi_available) + if use_rgb: + local_rgb = batch["oracle_crop_rgb"] + if local_rgb.shape[:3] != (batch_size, time, hands): + raise ValueError(f"unexpected oracle RGB crop shape: {local_rgb.shape}") + local_hw = local_rgb.shape[-2:] + rgb_features = self.rgb_encoder( + local_rgb.reshape(batch_size * time * hands, 3, *local_hw), + ) + rgb_token = rgb_features.tokens.mean(dim=1).reshape( + batch_size, time, hands, dim, + ) + parts.append(rgb_token * rgb_available[..., None].to(rgb_token.dtype)) + availability_parts.append(rgb_available[..., None].to(rgb_token.dtype)) + + depth_available = torch.zeros_like(roi_available) + if use_depth: + local_depth = batch["oracle_crop_depth_m"] + local_valid = batch["oracle_crop_depth_pixel_valid"].bool() + local_K = batch["oracle_crop_K"].to(coarse_hand_tokens.dtype) + local_hw = local_depth.shape[-2:] + expected_prefix = (batch_size, time, hands) + if local_depth.shape[:3] != expected_prefix or local_K.shape[:3] != expected_prefix: + raise ValueError("unexpected oracle depth/K crop shape") + depth_available = ( + batch["oracle_crop_depth_available"].bool() + & roi_available + & coarse_depth_available[:, :, None] + ) + identity_K = torch.eye( + 3, dtype=local_K.dtype, device=local_K.device, + ).expand_as(local_K) + safe_local_K = torch.where( + depth_available[..., None, None], local_K, identity_K, + ) + depth_features = self.depth_encoder( + local_depth.reshape(batch_size * time * hands, 1, *local_hw).to(coarse_hand_tokens.dtype), + local_valid.reshape(batch_size * time * hands, 1, *local_hw), + safe_local_K.reshape(batch_size * time * hands, 3, 3), + ) + depth_token = depth_features.tokens.mean(dim=1).reshape( + batch_size, time, hands, dim, + ) + parts.append(depth_token * depth_available[..., None].to(depth_token.dtype)) + normalized_K = torch.stack(( + safe_local_K[..., 0, 0] / local_hw[1], + safe_local_K[..., 1, 1] / local_hw[0], + safe_local_K[..., 0, 2] / local_hw[1], + safe_local_K[..., 1, 2] / local_hw[0], + ), dim=-1) + parts.append(normalized_K * depth_available[..., None].to(normalized_K.dtype)) + availability_parts.append(depth_available[..., None].to(depth_token.dtype)) + parts.extend(availability_parts) + fused = self.oracle_crop_fusion(torch.cat(parts, dim=-1)) + + refined_rotations = coarse_rotations + refined_shape_sequence = coarse_shape_sequence + refined_shape = coarse_shape + rotation_delta = torch.zeros( + (*coarse_rotations.shape[:-2], 3), + dtype=coarse_rotations.dtype, device=coarse_rotations.device, + ) + shape_delta = torch.zeros_like(coarse_shape_sequence) + if use_rgb: + raw_rotation = self.oracle_crop_rotation_head(fused).reshape( + batch_size, time, hands, 16, 3, + ) + rotation_delta = self._bounded_axis_angle(raw_rotation) + rotation_delta = rotation_delta * rgb_available[..., None, None].to(rotation_delta.dtype) + refined_rotations = self._compose_rotation_residual( + coarse_rotations, rotation_delta, + ) + raw_shape = torch.tanh(self.oracle_crop_shape_head(fused)) + weights = shape_pool_weights * rgb_available.to(shape_pool_weights.dtype) + weights = weights / weights.sum(dim=1, keepdim=True).clamp_min(1e-8) + shape_delta = (raw_shape * weights[..., None]).sum(dim=1) + shape_delta = shape_delta * rgb_available.any(dim=1)[..., None].to(shape_delta.dtype) + refined_shape_sequence = coarse_shape_sequence + shape_delta + refined_shape = refined_shape_sequence[:, None].expand(-1, time, -1, -1) + + delta_z = torch.zeros_like(coarse_translation[..., 2:3]) + if use_depth: + delta_z = 0.15 * torch.tanh(self.oracle_crop_delta_z_head(fused)) + delta_z = delta_z * depth_available[..., None].to(delta_z.dtype) + refined_translation = coarse_translation + torch.cat( + (torch.zeros_like(coarse_translation[..., :2]), delta_z), dim=-1, + ) + return ( + refined_rotations, + refined_shape_sequence, + refined_shape, + refined_translation, + { + "coarse_mano_rotation_matrices": coarse_rotations, + "coarse_mano_shape_sequence": coarse_shape_sequence, + "coarse_mano_shape": coarse_shape, + "coarse_wrist_root_translation": coarse_translation, + "oracle_crop_rotation_delta_axis_angle": rotation_delta, + "oracle_crop_shape_delta": shape_delta, + "oracle_crop_delta_z": delta_z, + "oracle_crop_rgb_available": rgb_available, + "oracle_crop_depth_available_effective": depth_available, + }, + ) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/decoder.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..2031cad4d2a5790f82da07dec1958f33f6153c71 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/decoder.py @@ -0,0 +1,267 @@ +"""Factorized spatial-temporal semantic hand-query decoder.""" + +from __future__ import annotations + +from typing import Any + +import torch +from torch import nn +from torch.utils.checkpoint import checkpoint + + +class SpatialUpdate(nn.Module): + def __init__( + self, + dim: int, + heads: int, + use_depth: bool, + use_bimanual: bool, + depth_gate_floor: float, + depth_gate_mode: str, + depth_gate_fixed_value: float, + ) -> None: + super().__init__() + self.query_norm = nn.LayerNorm(dim) + self.rgb_norm = nn.LayerNorm(dim) + self.rgb_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.use_bimanual = use_bimanual + if use_bimanual: + self.hand_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.use_depth = use_depth + if not 0.0 <= depth_gate_floor < 1.0: + raise ValueError(f"depth_gate_floor must be in [0,1), got {depth_gate_floor}") + if depth_gate_mode not in {"learned", "fixed"}: + raise ValueError(f"Unknown depth_gate_mode: {depth_gate_mode}") + if not 0.0 <= depth_gate_fixed_value <= 1.0: + raise ValueError(f"depth_gate_fixed_value must be in [0,1], got {depth_gate_fixed_value}") + self.depth_gate_floor = depth_gate_floor + self.depth_gate_mode = depth_gate_mode + self.depth_gate_fixed_value = depth_gate_fixed_value + if use_depth: + self.depth_norm = nn.LayerNorm(dim) + self.depth_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.depth_gate = nn.Sequential(nn.Linear(dim * 2, dim), nn.GELU(), nn.Linear(dim, 1)) + nn.init.zeros_(self.depth_gate[-1].weight) + nn.init.zeros_(self.depth_gate[-1].bias) + self.ffn = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim * 4), nn.GELU(), nn.Linear(dim * 4, dim)) + + def forward( + self, + queries: torch.Tensor, + rgb: torch.Tensor, + depth: torch.Tensor | None, + depth_available: torch.Tensor, + side_bias: torch.Tensor, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + q = self.query_norm(queries + side_bias) + if self.use_bimanual: + hand_delta, _ = self.hand_attention(q, q, q, need_weights=False) + queries = queries + hand_delta + q = self.query_norm(queries + side_bias) + rgb_delta, rgb_attention = self.rgb_attention(q, self.rgb_norm(rgb), self.rgb_norm(rgb), need_weights=True) + queries = queries + rgb_delta + aux: dict[str, torch.Tensor] = { + "rgb_cross_attention": rgb_attention, + "rgb_update_norm": torch.linalg.vector_norm(rgb_delta, dim=-1), + } + if self.use_depth and depth is not None: + q = self.query_norm(queries + side_bias) + depth_delta, depth_attention = self.depth_attention(q, self.depth_norm(depth), self.depth_norm(depth), need_weights=True) + if self.depth_gate_mode == "fixed": + raw_gate = torch.full_like(depth_delta[..., :1], self.depth_gate_fixed_value) + else: + raw_gate = torch.sigmoid(self.depth_gate(torch.cat((q, depth_delta), dim=-1))) + gate = self.depth_gate_floor + (1.0 - self.depth_gate_floor) * raw_gate + gate = gate * depth_available[:, None, None].to(gate.dtype) + queries = queries + gate * depth_delta + aux.update({ + "depth_cross_attention": depth_attention, + "depth_fusion_gate": gate, + "depth_fusion_gate_raw": raw_gate * depth_available[:, None, None].to(raw_gate.dtype), + "depth_update_norm": torch.linalg.vector_norm(depth_delta, dim=-1), + "gated_depth_update_norm": torch.linalg.vector_norm(gate * depth_delta, dim=-1), + }) + queries = queries + self.ffn(queries) + return queries, aux + + +class TemporalUpdate(nn.Module): + def __init__( + self, + dim: int, + heads: int, + use_temporal: bool, + use_bimanual: bool, + position_mode: str = "none", + relative_bias_max_distance: int = 15, + attention_mode: str = "bidirectional", + ) -> None: + super().__init__() + if position_mode not in {"none", "relative_bias"}: + raise ValueError(f"Unknown temporal position mode: {position_mode}") + if position_mode != "none" and not use_temporal: + raise ValueError("temporal position conditioning requires use_temporal=True") + if relative_bias_max_distance < 1: + raise ValueError("relative_bias_max_distance must be positive") + if attention_mode not in {"bidirectional", "causal"}: + raise ValueError(f"Unknown temporal attention mode: {attention_mode}") + self.use_temporal = use_temporal + self.use_bimanual = use_bimanual + self.position_mode = position_mode + self.heads = heads + self.relative_bias_max_distance = relative_bias_max_distance + self.attention_mode = attention_mode + if use_temporal: + self.temporal_norm = nn.LayerNorm(dim) + self.temporal_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + if position_mode == "relative_bias": + self.relative_position_bias = nn.Parameter( + torch.zeros(heads, 2 * relative_bias_max_distance + 1) + ) + if use_bimanual: + self.bimanual_norm = nn.LayerNorm(dim) + self.bimanual_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + + def _relative_attention_bias( + self, batch_hands: int, time: int, dtype: torch.dtype, device: torch.device, + ) -> torch.Tensor | None: + if self.position_mode == "none": + return None + positions = torch.arange(time, device=device) + # Signed key-query displacement preserves ordered offline-video direction. + relative = positions[None, :] - positions[:, None] + relative = relative.clamp( + -self.relative_bias_max_distance, self.relative_bias_max_distance, + ) + self.relative_bias_max_distance + per_head = self.relative_position_bias[:, relative].to(dtype=dtype) + return per_head[None].expand(batch_hands, -1, -1, -1).reshape( + batch_hands * self.heads, time, time, + ) + + def _attention_mask( + self, batch_hands: int, time: int, dtype: torch.dtype, + device: torch.device, + ) -> torch.Tensor | None: + attention_mask = self._relative_attention_bias( + batch_hands, time, dtype, device, + ) + if self.attention_mode == "bidirectional": + return attention_mask + future = torch.triu( + torch.ones(time, time, dtype=torch.bool, device=device), diagonal=1, + ) + if attention_mask is None: + return future + return attention_mask.masked_fill(future[None], float("-inf")) + + def forward(self, tokens: torch.Tensor, frame_valid: torch.Tensor) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + batch, time, hands, dim = tokens.shape + aux: dict[str, torch.Tensor] = {} + if self.use_temporal: + per_hand = tokens.permute(0, 2, 1, 3).reshape(batch * hands, time, dim) + normalized = self.temporal_norm(per_hand) + key_padding = (~frame_valid)[:, None].expand(batch, hands, time).reshape(batch * hands, time) + attention_mask = self._attention_mask( + batch * hands, time, normalized.dtype, normalized.device, + ) + if attention_mask is not None and attention_mask.dtype != torch.bool: + float_padding = torch.zeros_like(key_padding, dtype=normalized.dtype) + key_padding_mask: torch.Tensor = float_padding.masked_fill(key_padding, float("-inf")) + else: + key_padding_mask = key_padding + delta, weights = self.temporal_attention( + normalized, normalized, normalized, + key_padding_mask=key_padding_mask, attn_mask=attention_mask, + need_weights=True, + ) + per_hand = per_hand + delta + tokens = per_hand.reshape(batch, hands, time, dim).permute(0, 2, 1, 3) + aux["temporal_attention"] = weights.reshape(batch, hands, time, time) + aux["temporal_update_norm"] = torch.linalg.vector_norm(delta, dim=-1).reshape(batch, hands, time).permute(0, 2, 1) + if self.use_bimanual: + pairs = tokens.reshape(batch * time, hands, dim) + normalized = self.bimanual_norm(pairs) + delta, weights = self.bimanual_attention(normalized, normalized, normalized, need_weights=True) + tokens = (pairs + delta).reshape(batch, time, hands, dim) + aux["bimanual_attention"] = weights.reshape(batch, time, hands, hands) + return tokens * frame_valid[:, :, None, None].to(tokens.dtype), aux + + +class HandQueryDecoder(nn.Module): + def __init__( + self, + dim: int, + layers: int, + heads: int, + use_depth: bool, + use_temporal: bool, + use_bimanual: bool, + mode: str, + gradient_checkpointing: bool = False, + depth_gate_floor: float = 0.0, + depth_gate_mode: str = "learned", + depth_gate_fixed_value: float = 0.5, + temporal_position_mode: str = "none", + temporal_relative_bias_max_distance: int = 15, + temporal_attention_mode: str = "bidirectional", + ) -> None: + super().__init__() + if mode not in {"sequential", "alternating", "hybrid_reread"}: + raise ValueError(f"Unknown decoder mode: {mode}") + self.mode = mode + self.gradient_checkpointing = gradient_checkpointing + self.temporal_enabled = True + self.spatial = nn.ModuleList([ + SpatialUpdate( + dim, heads, use_depth, use_bimanual, depth_gate_floor, + depth_gate_mode, depth_gate_fixed_value, + ) + for _ in range(layers) + ]) + temporal_layers = layers if mode == "alternating" else 1 + self.temporal = nn.ModuleList([ + TemporalUpdate( + dim, heads, use_temporal, use_bimanual, + temporal_position_mode, temporal_relative_bias_max_distance, + temporal_attention_mode, + ) + for _ in range(temporal_layers) + ]) + # With three spatial blocks this is S-S-T-S. The single temporal block + # and all parameters exactly match the sequential S-S-S-T baseline. + self.hybrid_temporal_after = max(layers - 2, 0) + + def forward(self, queries: torch.Tensor, rgb: torch.Tensor, depth: torch.Tensor | None, frame_valid: torch.Tensor, depth_available: torch.Tensor, side_bias: torch.Tensor) -> tuple[torch.Tensor, dict[str, Any]]: + batch, time, hands, dim = queries.shape + rgb_flat = rgb.reshape(batch * time, rgb.shape[2], dim) + depth_flat = None if depth is None else depth.reshape(batch * time, depth.shape[2], dim) + available_flat = depth_available.reshape(batch * time) + aux: dict[str, list[torch.Tensor]] = {} + for layer_index, spatial in enumerate(self.spatial): + spatial_args = (queries.reshape(batch * time, hands, dim), rgb_flat, depth_flat, available_flat, side_bias) + if self.gradient_checkpointing and self.training: + flat, layer_aux = checkpoint(spatial, *spatial_args, use_reentrant=False) + else: + flat, layer_aux = spatial(*spatial_args) + queries = flat.reshape(batch, time, hands, dim) * frame_valid[:, :, None, None].to(flat.dtype) + for key, value in layer_aux.items(): + aux.setdefault(key, []).append(value.reshape(batch, time, *value.shape[1:])) + if self.mode == "alternating" and self.temporal_enabled: + if self.gradient_checkpointing and self.training: + queries, temporal_aux = checkpoint(self.temporal[layer_index], queries, frame_valid, use_reentrant=False) + else: + queries, temporal_aux = self.temporal[layer_index](queries, frame_valid) + for key, value in temporal_aux.items(): + aux.setdefault(key, []).append(value) + elif self.mode == "hybrid_reread" and self.temporal_enabled and layer_index == self.hybrid_temporal_after: + if self.gradient_checkpointing and self.training: + queries, temporal_aux = checkpoint(self.temporal[0], queries, frame_valid, use_reentrant=False) + else: + queries, temporal_aux = self.temporal[0](queries, frame_valid) + for key, value in temporal_aux.items(): + aux.setdefault(key, []).append(value) + if self.mode == "sequential" and self.temporal_enabled: + queries, temporal_aux = self.temporal[0](queries, frame_valid) + for key, value in temporal_aux.items(): + aux.setdefault(key, []).append(value) + return queries, {key: torch.stack(values, dim=1) for key, values in aux.items()} diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/encoders.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..1b7c243f1cc84457e794d5e045b543f93d344f93 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/encoders.py @@ -0,0 +1,180 @@ +"""RGB and metric depth/geometry patch encoders.""" + +from __future__ import annotations + +from pathlib import Path +from typing import NamedTuple + +import torch +from torch import nn + + +class PatchFeatures(NamedTuple): + tokens: torch.Tensor + grid_hw: tuple[int, int] + patch_size: int + + +class TinyPatchEncoder(nn.Module): + """Debug-only encoder; never a substitute for a pretrained DINOv3 result.""" + + def __init__(self, output_dim: int, patch_size: int = 16, width: int = 64) -> None: + super().__init__() + self.patch_size = patch_size + self.output_dim = output_dim + self.network = nn.Sequential( + nn.Conv2d(3, width, 7, stride=2, padding=3), nn.GELU(), + nn.Conv2d(width, output_dim, patch_size // 2, stride=patch_size // 2), + ) + + def forward(self, images: torch.Tensor) -> PatchFeatures: + features = self.network(images) + return PatchFeatures(features.flatten(2).transpose(1, 2), features.shape[-2:], self.patch_size) + + +class DinoV3Encoder(nn.Module): + """Frozen official DINOv3 dense patch-token wrapper.""" + + def __init__( + self, + source_repo: str | Path, + weights: str | Path, + model_name: str = "dinov3_vitb16", + output_dim: int = 512, + input_dim: int = 768, + frozen: bool = True, + trainable_last_blocks: int = 0, + ) -> None: + super().__init__() + source_repo, weights = Path(source_repo), Path(weights) + self.backend = "torch_hub" + self.num_prefix_tokens = 0 + if weights.is_dir() and (weights / "model.safetensors").is_file(): + try: + from transformers import AutoModel + except ImportError as error: + raise ImportError("Transformers >=4.56 is required for local DINOv3 safetensors") from error + self.backbone = AutoModel.from_pretrained(str(weights), local_files_only=True) + self.backend = "transformers" + self.patch_size = int(self.backbone.config.patch_size) + self.num_prefix_tokens = 1 + int(self.backbone.config.num_register_tokens) + input_dim = int(self.backbone.config.hidden_size) + else: + if not (source_repo / "hubconf.py").is_file(): + raise FileNotFoundError(f"Official DINOv3 source repo not found: {source_repo}") + if not weights.is_file(): + raise FileNotFoundError( + f"DINOv3 pretrained weight not found: {weights}. Random DINO is not accepted for formal experiments." + ) + self.backbone = torch.hub.load( + str(source_repo), model_name, source="local", pretrained=True, weights=str(weights) + ) + self.patch_size = int(self.backbone.patch_size) + self.output_dim = output_dim + self.projection = nn.Linear(input_dim, output_dim) + if trainable_last_blocks < 0: + raise ValueError("trainable_last_blocks must be non-negative") + blocks = self._backbone_blocks() + if trainable_last_blocks > len(blocks): + raise ValueError( + f"requested {trainable_last_blocks} trainable DINO blocks, " + f"but the backbone has {len(blocks)}" + ) + if not frozen and trainable_last_blocks: + raise ValueError("full-backbone training and last-block training are mutually exclusive") + self.trainable_last_blocks = trainable_last_blocks + self.frozen = frozen and trainable_last_blocks == 0 + if frozen: + self.backbone.requires_grad_(False) + if trainable_last_blocks: + for block in blocks[-trainable_last_blocks:]: + block.requires_grad_(True) + self._backbone_final_norm().requires_grad_(True) + self._set_backbone_mode(False) + + def _backbone_blocks(self) -> nn.ModuleList: + blocks = getattr(self.backbone, "layer", None) + if blocks is None: + blocks = getattr(self.backbone, "blocks", None) + if not isinstance(blocks, nn.ModuleList): + raise TypeError("unsupported DINOv3 backbone: transformer blocks are unavailable") + return blocks + + def _backbone_final_norm(self) -> nn.Module: + norm = getattr(self.backbone, "norm", None) + if not isinstance(norm, nn.Module): + raise TypeError("unsupported DINOv3 backbone: final norm is unavailable") + return norm + + def _set_backbone_mode(self, mode: bool) -> None: + self.backbone.eval() + if self.trainable_last_blocks: + for block in self._backbone_blocks()[-self.trainable_last_blocks:]: + block.train(mode) + self._backbone_final_norm().train(mode) + + def train(self, mode: bool = True): + super().train(mode) + if self.frozen or self.trainable_last_blocks: + self._set_backbone_mode(mode) + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + height, width = images.shape[-2:] + if height % self.patch_size or width % self.patch_size: + raise ValueError(f"DINO input {height}x{width} must be divisible by patch size {self.patch_size}") + if self.frozen: + with torch.no_grad(): + if self.backend == "transformers": + raw = self.backbone(pixel_values=images).last_hidden_state[:, self.num_prefix_tokens :] + else: + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + else: + if self.backend == "transformers": + raw = self.backbone(pixel_values=images).last_hidden_state[:, self.num_prefix_tokens :] + else: + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + tokens = self.projection(raw) + return PatchFeatures(tokens, (height // self.patch_size, width // self.patch_size), self.patch_size) + + +class DepthGeometryEncoder(nn.Module): + """Aligned metric log-depth or XYZ/logZ patch encoder.""" + + def __init__(self, output_dim: int, patch_size: int = 16, mode: str = "log_depth") -> None: + super().__init__() + if mode not in {"log_depth", "geometry"}: + raise ValueError(f"Unknown depth mode: {mode}") + self.mode = mode + self.patch_size = patch_size + channels = 2 if mode == "log_depth" else 5 + hidden = max(32, output_dim // 4) + self.encoder = nn.Sequential( + nn.Conv2d(channels, hidden, 3, padding=1), nn.GELU(), + nn.Conv2d(hidden, output_dim, patch_size, stride=patch_size), + ) + # Start as a zero residual so the gate need not suppress random depth noise. + nn.init.zeros_(self.encoder[-1].weight) + nn.init.zeros_(self.encoder[-1].bias) + + def forward(self, depth_m: torch.Tensor, valid: torch.Tensor, K: torch.Tensor) -> PatchFeatures: + if depth_m.ndim != 4 or depth_m.shape[1] != 1: + raise ValueError(f"Expected [BT,1,H,W] depth, got {depth_m.shape}") + valid_float = valid.to(depth_m.dtype) + log_z = torch.where(valid, depth_m.clamp_min(1e-4).log(), torch.zeros_like(depth_m)) + if self.mode == "log_depth": + inputs = torch.cat((log_z, valid_float), dim=1) + else: + _, _, height, width = depth_m.shape + u = torch.arange(width, device=depth_m.device, dtype=depth_m.dtype).view(1, 1, 1, width) + v = torch.arange(height, device=depth_m.device, dtype=depth_m.dtype).view(1, 1, height, 1) + cx = K[:, 0, 2].view(-1, 1, 1, 1) + cy = K[:, 1, 2].view(-1, 1, 1, 1) + fx = K[:, 0, 0].view(-1, 1, 1, 1) + fy = K[:, 1, 1].view(-1, 1, 1, 1) + x = (u - cx) * depth_m / fx + y = (v - cy) * depth_m / fy + x, y = x * valid_float, y * valid_float + inputs = torch.cat((x, y, depth_m * valid_float, log_z, valid_float), dim=1) + features = self.encoder(inputs) + return PatchFeatures(features.flatten(2).transpose(1, 2), features.shape[-2:], self.patch_size) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/mano.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/mano.py new file mode 100644 index 0000000000000000000000000000000000000000..aa23fb1a21aee64238a7ae6ce20b24c346643482 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/mano.py @@ -0,0 +1,61 @@ +"""Independent left/right MANO layers with wrist-root camera translation.""" + +from __future__ import annotations + +from pathlib import Path + +import torch +from torch import nn + +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import matrix_to_axis_angle + + +class ManoCameraLayer(nn.Module): + """Run official manopth in native mm, root-center, then place wrist in camera meters.""" + + def __init__( + self, + mano_root: str | Path, + fix_left_shapedirs: bool = False, + ) -> None: + super().__init__() + root = Path(mano_root) + required = [root / "MANO_LEFT.pkl", root / "MANO_RIGHT.pkl"] + missing = [str(path) for path in required if not path.is_file()] + if missing: + raise FileNotFoundError(f"Licensed MANO assets missing: {missing}") + enable_legacy_mano_loading() + try: + from manopth.manolayer import ManoLayer + except ImportError as error: + raise ImportError("Install the pinned official manopth source before enabling MANO") from error + self.layers = nn.ModuleList([ + ManoLayer(mano_root=str(root), side="left", use_pca=False, ncomps=45, flat_hand_mean=True), + ManoLayer(mano_root=str(root), side="right", use_pca=False, ncomps=45, flat_hand_mean=True), + ]) + if fix_left_shapedirs: + # Match the official HOT3D provider's corrected MANO-left + # convention. The historical default remains unchanged for old + # H2O checkpoints. + with torch.no_grad(): + self.layers[0].th_shapedirs[:, 0, :].mul_(-1) + + def forward(self, rotation_matrices: torch.Tensor, shape: torch.Tensor, wrist_translation_m: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + if rotation_matrices.shape[-3:] != (16, 3, 3): + raise ValueError(f"Expected [...,2,16,3,3], got {rotation_matrices.shape}") + leading = rotation_matrices.shape[:-4] + if rotation_matrices.shape[-4] != 2: + raise ValueError("MANO hand dimension must be fixed [left,right]") + vertices_out, joints_out = [], [] + for hand, layer in enumerate(self.layers): + pose = matrix_to_axis_angle(rotation_matrices[..., hand, :, :, :]).reshape(-1, 48) + betas = shape[..., hand, :].reshape(-1, 10) + vertices_mm, joints_mm = layer(pose, betas) + root_mm = joints_mm[:, :1] + wrist = wrist_translation_m[..., hand, :].reshape(-1, 1, 3) + vertices = (vertices_mm - root_mm) / 1000.0 + wrist + joints = (joints_mm - root_mm) / 1000.0 + wrist + vertices_out.append(vertices.reshape(*leading, vertices.shape[-2], 3)) + joints_out.append(joints.reshape(*leading, joints.shape[-2], 3)) + return torch.stack(vertices_out, dim=-3), torch.stack(joints_out, dim=-3) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/structured_hand.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/structured_hand.py new file mode 100644 index 0000000000000000000000000000000000000000..e5d3e8dd8fc760012d2622d61a13fef716ae1703 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/models/structured_hand.py @@ -0,0 +1,192 @@ +"""Predicted-location structured hand refinement for Phase 5.""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + + +PART_COUNT = 7 +ROOT_PART = 0 +PALM_PART = 1 +FINGER_PARTS = slice(2, 7) + + +def structured_part_locations(joints_2d_norm: torch.Tensor) -> torch.Tensor: + """Map 21 predicted joints to root, palm, and five finger centers.""" + + if joints_2d_norm.ndim != 5 or joints_2d_norm.shape[-2:] != (21, 2): + raise ValueError("joint locations must have shape [B,T,2,21,2]") + root = joints_2d_norm[..., :1, :] + palm = joints_2d_norm[..., (0, 1, 5, 9, 13, 17), :].mean( + dim=-2, keepdim=True, + ) + fingers = torch.stack([ + joints_2d_norm[..., start : start + 4, :].mean(dim=-2) + for start in (1, 5, 9, 13, 17) + ], dim=-2) + return torch.cat((root, palm, fingers), dim=-2) + + +def kinematic_attention_mask(device: torch.device) -> torch.Tensor: + """Return a symmetric root-palm-finger graph mask for self-attention.""" + + allowed = torch.eye(PART_COUNT, dtype=torch.bool, device=device) + allowed[ROOT_PART, PALM_PART] = True + allowed[PALM_PART, ROOT_PART] = True + allowed[PALM_PART, FINGER_PARTS] = True + allowed[FINGER_PARTS, PALM_PART] = True + return ~allowed + + +class StructuredHandRefinement(nn.Module): + """Fuse coarse hand tokens with deformably sampled full-frame features.""" + + def __init__( + self, dim: int, heads: int, *, use_depth: bool, samples: int = 4, + maximum_offset_norm: float = 0.08, + ) -> None: + super().__init__() + if samples < 1: + raise ValueError("deformable sample count must be positive") + if not 0.0 < maximum_offset_norm <= 0.25: + raise ValueError("maximum normalized offset must be in (0,0.25]") + self.samples = samples + self.maximum_offset_norm = maximum_offset_norm + self.use_depth = use_depth + self.part_embedding = nn.Parameter(torch.randn(PART_COUNT, dim) * 0.02) + self.offset_head = nn.Linear(dim, samples * 2) + nn.init.zeros_(self.offset_head.weight) + nn.init.zeros_(self.offset_head.bias) + self.rgb_projection = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim)) + if use_depth: + self.depth_projection = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim)) + self.fusion_norm = nn.LayerNorm(dim) + self.graph_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.ffn = nn.Sequential( + nn.LayerNorm(dim), nn.Linear(dim, dim * 4), nn.GELU(), + nn.Linear(dim * 4, dim), + ) + + @staticmethod + def _sample( + tokens: torch.Tensor, + grid_hw: tuple[int, int], + locations: torch.Tensor, + *, + deterministic_detached: bool = False, + ) -> torch.Tensor: + batch, time, patches, dim = tokens.shape + grid_height, grid_width = grid_hw + if patches != grid_height * grid_width: + raise ValueError("feature token count does not match patch grid") + if locations.shape[:2] != (batch, time) or locations.shape[-1] != 2: + raise ValueError("sample locations must align with [B,T] tokens") + if deterministic_detached: + features = tokens.detach().reshape(batch * time, patches, dim) + coordinates = locations.reshape(batch * time, -1, 2) + x = coordinates[..., 0] * grid_width - 0.5 + y = coordinates[..., 1] * grid_height - 0.5 + x0, y0 = torch.floor(x), torch.floor(y) + x1, y1 = x0 + 1.0, y0 + 1.0 + + def corner(x_index: torch.Tensor, y_index: torch.Tensor) -> torch.Tensor: + valid = ( + (x_index >= 0.0) & (x_index < grid_width) + & (y_index >= 0.0) & (y_index < grid_height) + ) + flat_index = ( + y_index.clamp(0, grid_height - 1).long() * grid_width + + x_index.clamp(0, grid_width - 1).long() + ) + value = torch.gather( + features, + 1, + flat_index[..., None].expand(-1, -1, dim), + ) + return value * valid[..., None].to(value.dtype) + + sampled = ( + corner(x0, y0) * ((x1 - x) * (y1 - y))[..., None] + + corner(x1, y0) * ((x - x0) * (y1 - y))[..., None] + + corner(x0, y1) * ((x1 - x) * (y - y0))[..., None] + + corner(x1, y1) * ((x - x0) * (y - y0))[..., None] + ) + sampled = sampled.reshape(*locations.shape[:-1], dim).mean(dim=-2) + return sampled + feature_map = tokens.reshape( + batch * time, grid_height, grid_width, dim, + ).permute(0, 3, 1, 2) + flat_locations = locations.reshape(batch * time, -1, locations.shape[-2], 2) + grid = flat_locations.mul(2.0).sub(1.0) + sampled = F.grid_sample( + feature_map, grid, mode="bilinear", padding_mode="zeros", + align_corners=False, + ) + sampled = sampled.mean(dim=-1).transpose(1, 2) + return sampled.reshape(*locations.shape[:-2], dim) + + def forward( + self, + coarse_hand_tokens: torch.Tensor, + joint2d_norm: torch.Tensor, + rgb_tokens: torch.Tensor, + depth_tokens: torch.Tensor | None, + grid_hw: tuple[int, int], + frame_valid: torch.Tensor, + depth_available: torch.Tensor, + *, + detach_locations: bool, + deterministic_detached_sampling: bool = False, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + batch, time, hands, dim = coarse_hand_tokens.shape + if hands != 2: + raise ValueError("structured refinement expects two hands") + locations = structured_part_locations(joint2d_norm) + if detach_locations: + locations = locations.detach() + seeds = coarse_hand_tokens[..., None, :] + self.part_embedding + offsets = self.maximum_offset_norm * torch.tanh( + self.offset_head(seeds).reshape( + batch, time, hands, PART_COUNT, self.samples, 2, + ) + ) + sample_locations = locations[..., None, :] + offsets + sampled_rgb = self._sample( + rgb_tokens, + grid_hw, + sample_locations, + deterministic_detached=deterministic_detached_sampling, + ) + tokens = seeds + self.rgb_projection(sampled_rgb) + if self.use_depth and depth_tokens is not None: + sampled_depth = self._sample( + depth_tokens, + grid_hw, + sample_locations, + deterministic_detached=deterministic_detached_sampling, + ) + depth_mask = depth_available[:, :, None, None, None].to(sampled_depth.dtype) + tokens = tokens + self.depth_projection(sampled_depth) * depth_mask + graph_input = self.fusion_norm(tokens).reshape( + batch * time * hands, PART_COUNT, dim, + ) + graph_delta, graph_weights = self.graph_attention( + graph_input, graph_input, graph_input, + attn_mask=kinematic_attention_mask(graph_input.device), + need_weights=True, + ) + tokens = (graph_input + graph_delta).reshape( + batch, time, hands, PART_COUNT, dim, + ) + tokens = tokens + self.ffn(tokens) + tokens = tokens * frame_valid[:, :, None, None, None].to(tokens.dtype) + return tokens, { + "structured_part_locations": locations, + "structured_sample_offsets": offsets, + "structured_sample_locations": sample_locations, + "structured_graph_attention": graph_weights.reshape( + batch, time, hands, PART_COUNT, PART_COUNT, + ), + } diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/__init__.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d718428f981b8ec69c68dee3978a07ce6689678 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/__init__.py @@ -0,0 +1,3 @@ +from foundation_hand.training.losses import BimanualLoss, LossConfig + +__all__ = ["BimanualLoss", "LossConfig"] diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/checkpoint.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..17d23ba069d588aaeee71af0d863dc35ca9002fb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/checkpoint.py @@ -0,0 +1,97 @@ +"""Exact model/optimizer/RNG checkpoint save and resume.""" + +from __future__ import annotations + +import random +from pathlib import Path +from typing import Any + +import numpy as np +import torch + + +def save_checkpoint( + path: str | Path, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + step: int, + extra: dict[str, Any] | None = None, + exclude_prefixes: tuple[str, ...] = (), +) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + model_state = { + key: value for key, value in model.state_dict().items() + if not key.startswith(exclude_prefixes) + } + state = { + "model": model_state, "optimizer": optimizer.state_dict(), "step": step, + "excluded_model_prefixes": exclude_prefixes, + "python_rng": random.getstate(), "numpy_rng": np.random.get_state(), + "torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None, + "extra": extra or {}, + } + torch.save(state, path) + + +def load_checkpoint(path: str | Path, model: torch.nn.Module, optimizer: torch.optim.Optimizer | None = None, map_location: str | torch.device = "cpu") -> dict[str, Any]: + state = torch.load(path, map_location=map_location, weights_only=False) + excluded_prefixes = tuple(state.get("excluded_model_prefixes", ())) + incompatible = model.load_state_dict(state["model"], strict=not excluded_prefixes) + if incompatible.unexpected_keys: + raise RuntimeError(f"Unexpected checkpoint keys: {incompatible.unexpected_keys}") + disallowed_missing = [ + key for key in incompatible.missing_keys + if not key.startswith(excluded_prefixes) + ] + if disallowed_missing: + raise RuntimeError(f"Missing non-excluded checkpoint keys: {disallowed_missing}") + if optimizer is not None: + optimizer.load_state_dict(state["optimizer"]) + random.setstate(state["python_rng"]) + np.random.set_state(state["numpy_rng"]) + torch.set_rng_state(state["torch_rng"].cpu()) + if torch.cuda.is_available() and state["cuda_rng"] is not None: + torch.cuda.set_rng_state_all([value.cpu() for value in state["cuda_rng"]]) + return {"step": state["step"], "extra": state["extra"]} + + +def load_model_initialization( + path: str | Path, + model: torch.nn.Module, + *, + allowed_missing_prefixes: tuple[str, ...], + map_location: str | torch.device = "cpu", + require_residual: bool = True, +) -> dict[str, Any]: + """Load an old model into a registered residual extension only.""" + + if require_residual and not allowed_missing_prefixes: + raise ValueError("initialization requires explicit allowed missing prefixes") + state = torch.load(path, map_location=map_location, weights_only=False) + incompatible = model.load_state_dict(state["model"], strict=False) + if incompatible.unexpected_keys: + raise RuntimeError(f"Unexpected initialization keys: {incompatible.unexpected_keys}") + checkpoint_excluded_prefixes = tuple(state.get("excluded_model_prefixes", ())) + accepted_missing_prefixes = allowed_missing_prefixes + checkpoint_excluded_prefixes + disallowed_missing = [ + key for key in incompatible.missing_keys + if not key.startswith(accepted_missing_prefixes) + ] + if disallowed_missing: + raise RuntimeError( + f"Missing non-residual initialization keys: {disallowed_missing}" + ) + residual_missing = [ + key for key in incompatible.missing_keys + if key.startswith(allowed_missing_prefixes) + ] + if require_residual and not residual_missing: + raise RuntimeError("initialization did not add any registered residual parameters") + return { + "step": int(state["step"]), + "extra": state.get("extra", {}), + "missing_keys": sorted(incompatible.missing_keys), + "residual_missing_keys": sorted(residual_missing), + "checkpoint_excluded_prefixes": checkpoint_excluded_prefixes, + } diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/losses.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..6e409461719f8b6fac7cee4689ec7e5870df36fd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/losses.py @@ -0,0 +1,341 @@ +"""Mask-safe camera-space bimanual training losses.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch +import torch.nn.functional as F +from torch import nn + +from foundation_hand.data.schema import supervision_mask +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.geometry.camera import project_points + + +@dataclass +class LossConfig: + joint2d: float = 1.0 + joint2d_teacher: float = 0.0 + joint3d_camera: float = 10.0 + joint3d_root_relative: float = 0.0 + vertices_camera: float = 1.0 + local_pose: float = 1.0 + global_orientation: float = 1.0 + shape: float = 0.1 + translation: float = 10.0 + reprojection: float = 1.0 + temporal_velocity: float = 0.1 + temporal_acceleration: float = 0.05 + bimanual_relative_wrist: float = 1.0 + presence: float = 0.0 + translation_teacher: float = 0.0 + translation_mode: str = "l1" + translation_axis_weights: tuple[float, float, float] = (1.0, 1.0, 1.0) + translation_huber_beta_m: float = 0.01 + wrist_ray: float = 0.0 + robust_log_z: float = 0.0 + z_tail_cvar: float = 0.0 + depth_confidence_calibration: float = 0.0 + paired_modality_no_harm: float = 0.0 + + def __post_init__(self) -> None: + if self.translation_mode not in {"l1", "axis_huber"}: + raise ValueError(f"unsupported translation mode: {self.translation_mode}") + if len(self.translation_axis_weights) != 3: + raise ValueError("translation_axis_weights must contain x/y/z weights") + weights = tuple(float(value) for value in self.translation_axis_weights) + if any(value <= 0.0 for value in weights): + raise ValueError("translation axis weights must be positive") + if self.translation_huber_beta_m <= 0.0: + raise ValueError("translation_huber_beta_m must be positive") + self.translation_axis_weights = weights + + +def masked_mean(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + mask = torch.broadcast_to(mask, values.shape) + safe = torch.where(mask, values, torch.zeros_like(values)) + count = mask.sum() + return safe.sum() / count.clamp_min(1) + + +def masked_l1(prediction: torch.Tensor, target: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + safe_target = torch.where(torch.broadcast_to(mask, target.shape), target, torch.zeros_like(target)) + return masked_mean((prediction - safe_target).abs(), mask) + + +class BimanualLoss(nn.Module): + def __init__(self, config: LossConfig) -> None: + super().__init__() + self.config = config + + def _translation_loss( + self, + prediction: torch.Tensor, + target: torch.Tensor, + mask: torch.Tensor, + ) -> torch.Tensor: + if self.config.translation_mode == "l1": + return masked_l1(prediction, target, mask[..., None]) + safe_target = torch.where(mask[..., None], target, torch.zeros_like(target)) + elementwise = F.smooth_l1_loss( + prediction, + safe_target, + reduction="none", + beta=float(self.config.translation_huber_beta_m), + ) + weights = prediction.new_tensor(self.config.translation_axis_weights) + return masked_mean(elementwise * weights, mask[..., None]) + + def translation_diagnostics( + self, + prediction: dict[str, torch.Tensor], + batch: dict[str, torch.Tensor], + ) -> dict[str, torch.Tensor]: + """Return detached-loggable per-axis terms without changing total loss.""" + + frame = batch["frame_valid"].bool() + mask = supervision_mask( + batch, + "translation_valid", + batch["joint_annotation_valid"].bool(), + ) & frame[..., None] + target = torch.where( + mask[..., None], + batch["wrist_root_translation"], + torch.zeros_like(batch["wrist_root_translation"]), + ) + error = prediction["wrist_root_translation"] - target + if self.config.translation_mode == "axis_huber": + elementwise = F.smooth_l1_loss( + prediction["wrist_root_translation"], + target, + reduction="none", + beta=float(self.config.translation_huber_beta_m), + ) + weights = prediction["wrist_root_translation"].new_tensor( + self.config.translation_axis_weights + ) + else: + elementwise = error.abs() + weights = prediction["wrist_root_translation"].new_ones(3) + diagnostics: dict[str, torch.Tensor] = {} + for axis_index, axis in enumerate(("x", "y", "z")): + raw_mae = masked_mean(error[..., axis_index].abs(), mask) + axis_term = masked_mean(elementwise[..., axis_index], mask) + diagnostics[f"translation_{axis}_raw_mae_m"] = raw_mae + diagnostics[f"translation_{axis}_effective_loss_contribution"] = ( + axis_term * weights[axis_index] * float(self.config.translation) / 3.0 + ) + return diagnostics + + def forward(self, prediction: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: + frame = batch["frame_valid"].bool() + legacy_joint = batch["joint_annotation_valid"].bool() + legacy_mano = batch["mano_annotation_valid"].bool() + legacy_joint_elements = ( + batch["joint_element_valid"].bool() & legacy_joint[..., None] + ) + joint2d_valid = supervision_mask( + batch, "joint2d_valid", legacy_joint_elements, + ) & frame[..., None, None] + joint3d_valid = supervision_mask( + batch, "joint3d_valid", legacy_joint_elements, + ) & frame[..., None, None] + joint3d_root_relative_valid = supervision_mask( + batch, "joint3d_root_relative_valid", joint3d_valid, + ) & frame[..., None, None] + translation_valid = supervision_mask( + batch, "translation_valid", legacy_joint, + ) & frame[..., None] + pose_valid = supervision_mask( + batch, "mano_pose_valid", legacy_mano, + ) & frame[..., None] + shape_valid = supervision_mask( + batch, "shape_valid", legacy_mano, + ) & frame[..., None] + vertices_valid = supervision_mask( + batch, "vertices_valid", legacy_mano, + ) & frame[..., None] + image_hw = batch["image_hw"].to(prediction["joint2d_norm"].dtype) + wh = image_hw[:, None, None, None, [1, 0]] + target_2d_norm = batch["joint2d"].to(wh.dtype) / wh + joint_mask = joint2d_valid + + losses: dict[str, torch.Tensor] = {} + losses["joint2d"] = masked_l1(prediction["joint2d_norm"], target_2d_norm, joint_mask[..., None]) + if "joint2d_linear_teacher_norm" in prediction: + losses["joint2d_teacher"] = masked_l1( + prediction["joint2d_norm"], + prediction["joint2d_linear_teacher_norm"], + frame[..., None, None, None], + ) + else: + losses["joint2d_teacher"] = prediction["hand_tokens"].sum() * 0 + target_axis = batch["mano_pose"].reshape(*batch["mano_pose"].shape[:-1], 16, 3) + target_rot = axis_angle_to_matrix(torch.nan_to_num(target_axis)) + rotation_error = (prediction["mano_rotation_matrices"] - target_rot).abs() + losses["global_orientation"] = masked_mean( + rotation_error[..., :1, :, :], pose_valid[..., None, None, None], + ) + losses["local_pose"] = masked_mean( + rotation_error[..., 1:, :, :], pose_valid[..., None, None, None], + ) + losses["translation"] = self._translation_loss( + prediction["wrist_root_translation"], + batch["wrist_root_translation"], + translation_valid, + ) + if "mixed_projection_direct_teacher_translation" in prediction: + losses["translation_teacher"] = masked_l1( + prediction["wrist_root_translation"], + prediction["mixed_projection_direct_teacher_translation"], + translation_valid[..., None], + ) + else: + losses["translation_teacher"] = prediction["hand_tokens"].sum() * 0 + zero = prediction["hand_tokens"].sum() * 0 + if "ray_depth_wrist2d_norm" in prediction: + wrist_mask = joint2d_valid[..., 0] + losses["wrist_ray"] = masked_l1( + prediction["ray_depth_wrist2d_norm"], + target_2d_norm[..., 0, :], wrist_mask[..., None], + ) + target_z = batch["wrist_root_translation"][..., 2] + safe_target_z = torch.where( + translation_valid, target_z.clamp_min(1e-4), + torch.ones_like(target_z), + ) + losses["robust_log_z"] = masked_mean( + F.smooth_l1_loss( + prediction["ray_depth_log_base_z"], safe_target_z.log(), + reduction="none", beta=0.05, + ), + translation_valid, + ) + final_z_error = ( + prediction["wrist_root_translation"][..., 2] - target_z + ).abs() + valid_z_error = final_z_error[translation_valid] + if valid_z_error.numel(): + tail_count = max(1, int((valid_z_error.numel() + 19) // 20)) + losses["z_tail_cvar"] = torch.topk( + valid_z_error, k=tail_count, largest=True, + ).values.mean() + else: + losses["z_tail_cvar"] = zero + correction_valid = ( + prediction["ray_depth_correction_valid"].bool() + & translation_valid + ) + base_error = (prediction["ray_depth_base_z_m"] - target_z).abs() + corrected_error = final_z_error + helpful = (corrected_error < base_error).to( + prediction["ray_depth_confidence_logit"].dtype, + ) + confidence_bce = F.binary_cross_entropy_with_logits( + prediction["ray_depth_confidence_logit"], helpful, + reduction="none", + ) + losses["depth_confidence_calibration"] = masked_mean( + confidence_bce, correction_valid, + ) + losses["paired_modality_no_harm"] = masked_mean( + (corrected_error - base_error).clamp_min(0.0), + correction_valid, + ) + else: + losses["wrist_ray"] = zero + losses["robust_log_z"] = zero + losses["z_tail_cvar"] = zero + losses["depth_confidence_calibration"] = zero + losses["paired_modality_no_harm"] = zero + + shape_mask = shape_valid.any(dim=1) + safe_shape = torch.where( + shape_valid[..., None], batch["mano_shape"], + torch.zeros_like(batch["mano_shape"]), + ) + target_shape = ( + safe_shape.sum(dim=1) + / shape_valid.sum(dim=1).clamp_min(1)[..., None] + ) + losses["shape"] = masked_l1(prediction["mano_shape_sequence"], target_shape, shape_mask[..., None]) + + if "joints_camera" in prediction: + losses["joint3d_camera"] = masked_l1( + prediction["joints_camera"], batch["joint3d_camera"], + joint3d_valid[..., None], + ) + else: + losses["joint3d_camera"] = prediction["hand_tokens"].sum() * 0 + if "joints_camera" in prediction: + predicted_relative = ( + prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + ) + if "joint3d_root_relative" in batch: + target_relative = batch["joint3d_root_relative"] + else: + target_relative = ( + batch["joint3d_camera"] - batch["joint3d_camera"][..., :1, :] + ) + losses["joint3d_root_relative"] = masked_l1( + predicted_relative, target_relative, + joint3d_root_relative_valid[..., None], + ) + else: + losses["joint3d_root_relative"] = prediction["hand_tokens"].sum() * 0 + if "vertices_camera" in prediction and "vertices_camera" in batch: + losses["vertices_camera"] = masked_l1( + prediction["vertices_camera"], batch["vertices_camera"], + vertices_valid[..., None, None], + ) + else: + losses["vertices_camera"] = prediction["hand_tokens"].sum() * 0 + if "joints_camera" in prediction and "K" in batch: + projected, positive = project_points(prediction["joints_camera"], batch["K"]) + reprojection_norm = projected / wh + K_supervision_valid = supervision_mask( + batch, "K_supervision_valid", frame, + ) & frame + reprojection_valid = supervision_mask( + batch, "reprojection_valid", joint2d_valid, + ) + reprojection_mask = ( + reprojection_valid & positive & K_supervision_valid[..., None, None] + ) + losses["reprojection"] = masked_l1(reprojection_norm, target_2d_norm, reprojection_mask[..., None]) + else: + losses["reprojection"] = prediction["hand_tokens"].sum() * 0 + + wrists = prediction["wrist_root_translation"] + pair_valid = translation_valid.all(dim=-1) + target_relative = batch["wrist_root_translation"][:, :, 1] - batch["wrist_root_translation"][:, :, 0] + pred_relative = wrists[:, :, 1] - wrists[:, :, 0] + losses["bimanual_relative_wrist"] = masked_l1(pred_relative, target_relative, pair_valid[..., None]) + + velocity_valid = translation_valid[:, 1:] & translation_valid[:, :-1] + pred_velocity = wrists[:, 1:] - wrists[:, :-1] + target_velocity = batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1] + losses["temporal_velocity"] = masked_l1(pred_velocity, target_velocity, velocity_valid[..., None]) + acceleration_valid = velocity_valid[:, 1:] & velocity_valid[:, :-1] + pred_acceleration = pred_velocity[:, 1:] - pred_velocity[:, :-1] + target_acceleration = target_velocity[:, 1:] - target_velocity[:, :-1] + losses["temporal_acceleration"] = masked_l1(pred_acceleration, target_acceleration, acceleration_valid[..., None]) + + if "presence_logit" in prediction and self.config.presence > 0: + valid = supervision_mask( + batch, "presence_valid", batch["presence_label_valid"].bool(), + ) & frame[..., None] + target = torch.where(valid, batch["presence_target"], torch.zeros_like(batch["presence_target"])) + bce = F.binary_cross_entropy_with_logits(prediction["presence_logit"], target, reduction="none") + losses["presence"] = masked_mean(bce, valid) + else: + losses["presence"] = prediction["hand_tokens"].sum() * 0 + + weighted = { + name: value * float(getattr(self.config, name)) + for name, value in losses.items() + } + weighted["total"] = sum(weighted.values()) + return weighted diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/metrics.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..c3409994ee6d28374fbf42f8ccb1b191fee54eb2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/metrics.py @@ -0,0 +1,34 @@ +"""Camera-space metrics reported separately from root-relative accuracy.""" + +from __future__ import annotations + +import torch + +from foundation_hand.data.schema import supervision_mask + + +def camera_metrics(prediction: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> dict[str, float]: + frame = batch["frame_valid"].bool() + legacy_joint = batch["joint_annotation_valid"].bool() + joint_valid = supervision_mask( + batch, + "joint3d_valid", + batch["joint_element_valid"].bool() & legacy_joint[..., None], + ) & frame[..., None, None] + metrics: dict[str, float] = {} + translation_error = (prediction["wrist_root_translation"] - torch.nan_to_num(batch["wrist_root_translation"])).abs() + trans_mask = supervision_mask( + batch, "translation_valid", legacy_joint, + ) & frame[..., None] + for index, axis in enumerate("xyz"): + values = translation_error[..., index][trans_mask] + metrics[f"translation_{axis}_mae_mm"] = float(values.mean() * 1000) if values.numel() else float("nan") + if "joints_camera" in prediction: + target = torch.nan_to_num(batch["joint3d_camera"]) + error = torch.linalg.vector_norm(prediction["joints_camera"] - target, dim=-1) + metrics["absolute_camera_mpjpe_mm"] = float(error[joint_valid].mean() * 1000) if joint_valid.any() else float("nan") + pred_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + target_relative = target - target[..., :1, :] + relative_error = torch.linalg.vector_norm(pred_relative - target_relative, dim=-1) + metrics["root_relative_mpjpe_mm"] = float(relative_error[joint_valid].mean() * 1000) if joint_valid.any() else float("nan") + return metrics diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/optimizer.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa76830ba81297de3971dc7a8f3e956608f8890 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/optimizer.py @@ -0,0 +1,135 @@ +"""Optimizer grouping for low-learning-rate backbone adaptation.""" + +from __future__ import annotations + +import torch + + +BACKBONE_PREFIX = "rgb_encoder.backbone." + + +def optimizer_parameter_groups( + model: torch.nn.Module, + *, + learning_rate: float, + backbone_learning_rate: float | None, +) -> list[dict[str, object]]: + if learning_rate <= 0: + raise ValueError("learning_rate must be positive") + main_parameters = [] + backbone_parameters = [] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + target = backbone_parameters if name.startswith(BACKBONE_PREFIX) else main_parameters + target.append(parameter) + if not main_parameters: + raise ValueError("optimizer has no non-backbone trainable parameters") + if backbone_parameters and backbone_learning_rate is None: + raise ValueError("trainable DINOv3 blocks require backbone_learning_rate") + if not backbone_parameters and backbone_learning_rate is not None: + raise ValueError("backbone_learning_rate was set but no backbone parameter is trainable") + groups: list[dict[str, object]] = [{ + "params": main_parameters, + "lr": learning_rate, + "lr_scale": 1.0, + "group_name": "main", + }] + if backbone_parameters: + assert backbone_learning_rate is not None + if not 0 < backbone_learning_rate <= learning_rate: + raise ValueError("backbone_learning_rate must be in (0, learning_rate]") + groups.append({ + "params": backbone_parameters, + "lr": backbone_learning_rate, + "lr_scale": backbone_learning_rate / learning_rate, + "group_name": "dinov3_backbone", + }) + return groups + + +def staged_optimizer_parameter_groups( + model: torch.nn.Module, + *, + learning_rate: float, + initial_trainable_prefixes: tuple[str, ...], + unfrozen_learning_rate_scale: float, +) -> list[dict[str, object]]: + """Build stable parameter groups for a freeze-then-unfreeze schedule.""" + + if learning_rate <= 0: + raise ValueError("learning_rate must be positive") + if not initial_trainable_prefixes: + raise ValueError("initial_trainable_prefixes must not be empty") + if not 0.0 < unfrozen_learning_rate_scale <= 1.0: + raise ValueError("unfrozen_learning_rate_scale must be in (0, 1]") + initial_parameters = [] + later_parameters = [] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad or name.startswith(BACKBONE_PREFIX): + continue + target = ( + initial_parameters + if name.startswith(initial_trainable_prefixes) + else later_parameters + ) + target.append(parameter) + if not initial_parameters: + raise ValueError("staged optimizer has no initially trainable parameters") + if not later_parameters: + raise ValueError("staged optimizer has no later-unfrozen parameters") + return [ + { + "params": initial_parameters, + "lr": learning_rate, + "lr_scale": 1.0, + "group_name": "staged_initial", + }, + { + "params": later_parameters, + "lr": 0.0, + "lr_scale": 0.0, + "unfrozen_lr_scale": unfrozen_learning_rate_scale, + "group_name": "staged_later", + }, + ] + + +def set_staged_parameter_group_phase( + optimizer: torch.optim.Optimizer, *, active: bool, +) -> None: + """Switch the later group without changing optimizer parameter identity.""" + + for group in optimizer.param_groups: + if group.get("group_name") == "staged_later": + group["lr_scale"] = float(group["unfrozen_lr_scale"]) if active else 0.0 + + +def clear_staged_later_gradients( + model: torch.nn.Module, initial_trainable_prefixes: tuple[str, ...], +) -> None: + """Make the initial phase a true freeze while retaining stable groups.""" + + for name, parameter in model.named_parameters(): + if ( + parameter.requires_grad + and not name.startswith(BACKBONE_PREFIX) + and not name.startswith(initial_trainable_prefixes) + ): + parameter.grad = None + + +def set_scheduled_learning_rate( + optimizer: torch.optim.Optimizer, learning_rate: float, +) -> None: + for parameter_group in optimizer.param_groups: + parameter_group["lr"] = learning_rate * float(parameter_group.get("lr_scale", 1.0)) + + +def checkpoint_excluded_prefixes(model: torch.nn.Module) -> tuple[str, ...]: + backbone_is_trainable = any( + parameter.requires_grad + for name, parameter in model.named_parameters() + if name.startswith(BACKBONE_PREFIX) + ) + return () if backbone_is_trainable else (BACKBONE_PREFIX,) diff --git a/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/schedule.py b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..f230d5239a3acd995eb21f897e0a238b56883104 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/src/foundation_hand/training/schedule.py @@ -0,0 +1,26 @@ +"""Step-deterministic learning-rate schedules.""" + +from __future__ import annotations + +import math + + +def warmup_cosine_learning_rate( + step: int, + total_steps: int, + base_lr: float, + min_lr: float, + warmup_steps: int, +) -> float: + if total_steps <= 0: + raise ValueError("total_steps must be positive") + if not 0 <= warmup_steps < total_steps: + raise ValueError("warmup_steps must be in [0, total_steps)") + if not 0 <= min_lr <= base_lr: + raise ValueError("Expected 0 <= min_lr <= base_lr") + if warmup_steps and step < warmup_steps: + return base_lr * (step + 1) / warmup_steps + progress = (step - warmup_steps) / max(total_steps - warmup_steps - 1, 1) + progress = min(max(progress, 0.0), 1.0) + cosine = 0.5 * (1.0 + math.cos(math.pi * progress)) + return min_lr + (base_lr - min_lr) * cosine diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase4_visualizations.py b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase4_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1c582a84e8821a580d9da363f98d50ccc14b33 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase4_visualizations.py @@ -0,0 +1,30 @@ +import pytest + +from scripts.audit_phase4_visualizations import ( + deterministic_frame_hash_audit, + fraction, +) + + +def manifest(value): + return { + "cases": [{ + "take": "subject3/o2/3/cam4", "condition": "F1_ema_alpha0.4", + "videos": { + "raw_vs_filtered_30fps": {"frame_pixel_sha256": value}, + "raw_vs_filtered_4fps": {"frame_pixel_sha256": value}, + "failure_diagnostic_30fps": {"frame_pixel_sha256": value}, + }, + }], + } + + +def test_deterministic_hash_audit_requires_exact_frame_pixels(): + assert deterministic_frame_hash_audit(manifest(["a", "b"]), manifest(["a", "b"])) == 6 + with pytest.raises(ValueError, match="pixel mismatch"): + deterministic_frame_hash_audit(manifest(["a", "b"]), manifest(["a", "c"])) + + +def test_fraction_parses_ffprobe_rate(): + assert fraction("30/1") == 30.0 + assert fraction("120/30") == 4.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_alignment_visualizations.py b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_alignment_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..e26481ffcf599805d4df2d7a81e21556f026fe3e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_alignment_visualizations.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import copy +import hashlib +from pathlib import Path + +import cv2 +import numpy as np +import pytest + +from scripts.audit_phase5_alignment_visualizations import audit_manifests + + +def manifest(path: Path) -> dict[str, object]: + image = np.full((480, 640, 3), 127, dtype=np.uint8) + image[:, ::2] = 255 + assert cv2.imwrite(str(path), image) + digest = hashlib.sha256(path.read_bytes()).hexdigest() + return { + "status": "complete", + "result_role": "official_validation_secondary_failure_diagnostic", + "used_for_model_or_threshold_selection": False, + "official_test_used": False, + "cases": [{ + "role": "tail", "take": "subject3/x/0/cam4", "frame_id": 1, + "side": "right", "image": str(path), "image_sha256": digest, + }], + } + + +def test_visualization_audit_requires_equal_nonblank_pixels(tmp_path: Path) -> None: + primary = manifest(tmp_path / "primary.png") + rerun = manifest(tmp_path / "rerun.png") + + report = audit_manifests(primary, rerun) + + assert report["status"] == "passed" + assert report["deterministic_image_hashes_compared"] == 1 + + +def test_visualization_audit_rejects_metadata_or_test_use(tmp_path: Path) -> None: + primary = manifest(tmp_path / "primary.png") + rerun = manifest(tmp_path / "rerun.png") + changed = copy.deepcopy(rerun) + changed["cases"][0]["frame_id"] = 2 + with pytest.raises(ValueError, match="metadata mismatch"): + audit_manifests(primary, changed) + changed = copy.deepcopy(rerun) + changed["official_test_used"] = True + with pytest.raises(ValueError, match="manifest contract"): + audit_manifests(primary, changed) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_oof_bank.py b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad0296050e349e5c07647b8069c2de22b81c924 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_oof_bank.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +import json +import hashlib +from pathlib import Path + +import numpy as np +import pytest + +from scripts.audit_phase5_oof_bank import ( + depth_bucket, + cross_checkpoint_correlations, + distribution, + grouped_rows, + load_oof_banks, + size_bucket, + validity_bucket, + validate_bank_manifest, +) + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def write_full_bank(root: Path, fold: int) -> Path: + bank = root / f"fold{fold}" + take_dir = bank / "takes" + take_dir.mkdir(parents=True) + take = f"subject{fold + 1}/h1/0/cam4" + take_path = take_dir / f"take{fold}.npz" + time = 2 + residual = np.zeros((time, 2, 3), dtype=np.float32) + residual[..., 2] = np.asarray(((0.01, -0.02), (0.04, -0.08))) + target_translation = np.zeros((time, 2, 3), dtype=np.float32) + target_translation[..., 2] = np.asarray(((0.4, 0.6), (0.8, 1.0))) + np.savez_compressed( + take_path, + frame_id=np.asarray((0, 1)), + frame_valid=np.ones(time, dtype=bool), + mano_annotation_valid=np.ones((time, 2), dtype=bool), + translation_residual_m=residual, + target_wrist_translation=target_translation, + coarse_hand_scale_px=np.asarray(((40, 80), (140, 60)), dtype=np.float32), + alignment_valid_fraction=np.asarray(((0.1, 0.4), (0.8, 0.7)), dtype=np.float32), + ) + checkpoint = str(fold + 1) * 64 + manifest = { + "status": "complete", + "bank_version": 2, + "scope": "full_fold", + "result_role": "official_train_group_heldout_oof_predictions", + "fold": fold, + "seed": 20260716 + fold, + "checkpoint": {"sha256": checkpoint}, + "takes": [{"take": take, "path": str(take_path), "sha256": sha256(take_path)}], + "leakage_audit": {"passed": True}, + "official_validation_used_for_assignment": False, + "official_test_used": False, + "oracle_information_at_inference": False, + } + (bank / "bank_manifest.json").write_text(json.dumps(manifest), encoding="utf-8") + return bank + + +def test_oof_distribution_and_buckets() -> None: + result = distribution(np.asarray((-0.01, 0.02, -0.04, 0.08))) + assert result["count"] == 4 + assert result["mae_mm"] == pytest.approx(37.5) + assert result["maximum_mm"] == pytest.approx(80.0) + assert size_bucket(np.asarray((63.9, 64.0, 128.0))).tolist() == ["small", "medium", "large"] + assert depth_bucket(np.asarray((0.49, 0.5, 0.8))).tolist() == ["near", "middle", "far"] + assert validity_bucket(np.asarray((0.24, 0.25, 0.6))).tolist() == ["low", "partial", "strong"] + + +def test_oof_audit_rejects_smoke_bank(tmp_path: Path) -> None: + bank = tmp_path / "bank" + bank.mkdir() + (bank / "bank_manifest.json").write_text(json.dumps({ + "status": "complete", + "bank_version": 2, + "scope": "smoke", + "result_role": "official_train_group_heldout_oof_predictions", + "leakage_audit": {"passed": True}, + "official_validation_used_for_assignment": False, + "official_test_used": False, + "oracle_information_at_inference": False, + }), encoding="utf-8") + + with pytest.raises(ValueError, match="full-fold"): + validate_bank_manifest(bank / "bank_manifest.json") + with pytest.raises(ValueError, match="full-fold"): + load_oof_banks([bank]) + + +def test_oof_audit_rejects_pre_scale_fix_bank_version(tmp_path: Path) -> None: + bank = write_full_bank(tmp_path, 0) + manifest_path = bank / "bank_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + manifest["bank_version"] = 1 + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + + with pytest.raises(ValueError, match="full-fold"): + validate_bank_manifest(manifest_path) + + +def test_oof_audit_loads_three_full_folds_and_groups(tmp_path: Path) -> None: + samples, manifests = load_oof_banks([write_full_bank(tmp_path, fold) for fold in range(3)]) + + assert len(manifests) == 3 + assert len(samples["residual_z_m"]) == 12 + assert set(samples["fold"].tolist()) == {0, 1, 2} + rows = grouped_rows(samples) + assert rows[0]["group"] == "all" + assert rows[0]["p95_mm"] > 40.0 + correlations = cross_checkpoint_correlations(samples) + assert len(correlations) == 3 + assert all(row["status"].startswith("unavailable") for row in correlations.values()) + assert {int(seed) for seed in samples["coarse_seed"]} == {20260716, 20260717, 20260718} diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_periodic_checkpoints.py b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_periodic_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..792d23e69dbac59e0a8b4fa63d57cdb115e4bb7e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_periodic_checkpoints.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from scripts.audit_phase5_periodic_checkpoints import audit_run + + +def write_run(root: Path, *, step: int, validation: bool, dirty: bool = False) -> Path: + run = root / "run" + run.mkdir(parents=True) + torch.save({ + "step": step, + "model": {"weight": torch.ones(2)}, + "optimizer": {"state": {0: {"exp_avg": torch.zeros(2)}}}, + }, run / f"step_{step:07d}.pt") + (run / "run_provenance.json").write_text(json.dumps({ + "git_commit": "abc", + "git_status": " M dirty" if dirty else "", + "hashes": { + "train_manifest": {"sha256": "train"}, + "config": {"sha256": "config"}, + }, + }), encoding="utf-8") + (run / "train_metrics.jsonl").write_text(json.dumps({ + "step": step, "gradient_norm": 1.0, "frames_per_s": 50.0, + }) + "\n", encoding="utf-8") + if validation: + (run / "validation.jsonl").write_text(json.dumps({ + "step": step, "losses": {"total": 1.0}, "metrics": {"absolute": 2.0}, + }) + "\n", encoding="utf-8") + return run + + +def test_periodic_audit_accepts_train_only_and_validated_contracts(tmp_path: Path) -> None: + train_only = write_run(tmp_path / "train_only", step=25_000, validation=False) + validated = write_run(tmp_path / "validated", step=25_000, validation=True) + + assert audit_run(train_only, 25_000, 0)["status"] == "passed" + assert audit_run(validated, 25_000, 1)["status"] == "passed" + + +def test_periodic_audit_rejects_dirty_or_missing_validation(tmp_path: Path) -> None: + dirty = write_run(tmp_path / "dirty", step=25_000, validation=True, dirty=True) + missing = write_run(tmp_path / "missing", step=25_000, validation=False) + + assert audit_run(dirty, 25_000, 1)["status"] == "failed" + assert audit_run(missing, 25_000, 1)["status"] == "failed" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_residual_shift.py b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_residual_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..9f0561f8063d0f8bd69804752811c27aa84805b9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_audit_phase5_residual_shift.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import numpy as np + +from scripts.audit_phase5_residual_shift import depth_bucket, distribution, size_bucket + + +def test_residual_distribution_uses_absolute_tail_and_signed_mean() -> None: + result = distribution(np.asarray([-0.01, 0.02, -0.03, 0.04])) + assert result["count"] == 4 + assert abs(result["signed_mean_mm"] - 5.0) < 1e-9 + assert abs(result["mae_mm"] - 25.0) < 1e-9 + assert result["cvar95_mm"] == 40.0 + + +def test_phase5_residual_buckets_match_evaluator_contract() -> None: + assert [size_bucket(str(value)) for value in (63.9, 64.0, 127.9, 128.0)] == [ + "small", "medium", "medium", "large", + ] + assert [depth_bucket(str(value)) for value in (0.49, 0.5, 0.79, 0.8)] == [ + "near", "middle", "middle", "far", + ] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase4_checkpoint_index.py b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase4_checkpoint_index.py new file mode 100644 index 0000000000000000000000000000000000000000..f10a44fe8d6503e47bc8fdc9eeaf44285fdea6c6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase4_checkpoint_index.py @@ -0,0 +1,107 @@ +import json +from pathlib import Path + +import pytest + +from scripts.build_phase4_checkpoint_index import build_index + + +def write_report( + root: Path, relative: str, checkpoint: Path, *, + official_test_used: bool = False, sha256: str = "a" * 64, +) -> None: + path = root / relative / "evaluation.json" + path.parent.mkdir(parents=True) + path.write_text(json.dumps({ + "status": "evaluated", + "split_role": "official_validation", + "official_test_used": official_test_used, + "clips": 1495, + "frames": 11638, + "config": {"name": "candidate", "seed": 20260716}, + "checkpoint": { + "path": str(checkpoint), "sha256": sha256, "step": 100000, + }, + }), encoding="utf-8") + + +def test_build_index_is_sorted_and_tracks_full_validation_roles(tmp_path: Path): + checkpoint = tmp_path / "model.pt" + checkpoint.write_bytes(b"checkpoint") + root = tmp_path / "phase4" + write_report(root, "b0/full_validation/seed16/best_absolute", checkpoint) + write_report(root, "b0/full_validation/seed16/step_100k", checkpoint) + + result = build_index(root) + + assert result["official_test_used"] is False + assert result["evaluations"] == 2 + assert result["unique_checkpoints"] == 1 + assert [row["role"] for row in result["records"]] == [ + "best_absolute", "step_100k", + ] + assert all(row["run"] == "seed16" for row in result["records"]) + + +def test_build_index_rejects_official_test_leakage(tmp_path: Path): + checkpoint = tmp_path / "model.pt" + checkpoint.write_bytes(b"checkpoint") + root = tmp_path / "phase4" + write_report( + root, "candidate/full_validation/seed16/best_absolute", checkpoint, + official_test_used=True, + ) + + with pytest.raises(ValueError, match="test isolation"): + build_index(root) + + +def test_build_index_rejects_invalid_checkpoint_hash(tmp_path: Path): + checkpoint = tmp_path / "model.pt" + checkpoint.write_bytes(b"checkpoint") + root = tmp_path / "phase4" + write_report( + root, "candidate/full_validation/seed16/best_absolute", checkpoint, + sha256="not-a-hash", + ) + + with pytest.raises(ValueError, match="SHA256"): + build_index(root) + + +def test_build_index_skips_incomplete_validation_smoke(tmp_path: Path): + checkpoint = tmp_path / "model.pt" + checkpoint.write_bytes(b"checkpoint") + root = tmp_path / "phase4" + write_report(root, "candidate/full_validation/seed16/best_absolute", checkpoint) + smoke_path = root / "wave0/smoke/evaluation.json" + smoke_path.parent.mkdir(parents=True) + smoke_path.write_text(json.dumps({ + "status": "evaluated", + "split_role": "official_validation", + "official_test_used": False, + "clips": 1, + "frames": 8, + }), encoding="utf-8") + + result = build_index(root) + + assert result["evaluations"] == 1 + + +def test_build_index_follows_symlinked_full_validation(tmp_path: Path): + checkpoint = tmp_path / "model.pt" + checkpoint.write_bytes(b"checkpoint") + root = tmp_path / "phase4" + external = tmp_path / "ssd" / "a3_full_validation" + write_report(external, "seed16/best_absolute", checkpoint) + link = root / "a3" / "full_validation" + link.parent.mkdir(parents=True) + link.symlink_to(external, target_is_directory=True) + + result = build_index(root) + + assert result["evaluations"] == 1 + assert result["records"][0]["condition"] == "a3" + assert result["records"][0]["run"] == "seed16" + assert result["records"][0]["role"] == "best_absolute" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase5_group_folds.py b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase5_group_folds.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad9475916532fe48f4c88e3cdf9cb45da3f61d8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase5_group_folds.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import json +from pathlib import Path + +from scripts.build_phase5_group_folds import build_subject_folds + + +def write_source(path: Path) -> None: + records = [ + {"take": "subject1/h1/0/cam4", "run_index": 0, "frame_ids": [0, 1]}, + {"take": "subject1/o1/0/cam4", "run_index": 0, "frame_ids": [0]}, + {"take": "subject2/h1/0/cam4", "run_index": 0, "frame_ids": [0, 1, 2]}, + {"take": "subject2/h1/0/cam4", "run_index": 1, "frame_ids": [4]}, + {"take": "subject3/k1/0/cam4", "run_index": 0, "frame_ids": [0, 1]}, + ] + path.write_text("".join(json.dumps(row) + "\n" for row in records), encoding="utf-8") + + +def load_jsonl(path: Path) -> list[dict]: + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + + +def test_subject_folds_are_deterministic_and_leakage_free(tmp_path: Path) -> None: + source = tmp_path / "official_train.jsonl" + write_source(source) + first = build_subject_folds(source, tmp_path / "first") + second = build_subject_folds(source, tmp_path / "second") + + assert first["source_manifest_sha256"] == second["source_manifest_sha256"] + assert [fold["heldout_subject"] for fold in first["folds"]] == [ + "subject1", "subject2", "subject3", + ] + assert [fold["heldout_manifest_sha256"] for fold in first["folds"]] == [ + fold["heldout_manifest_sha256"] for fold in second["folds"] + ] + assert all(fold["leakage_audit"]["passed"] for fold in first["folds"]) + + heldout_ids = [] + for fold in first["folds"]: + root = tmp_path / "first" + train = load_jsonl(root / fold["train_manifest"]) + heldout = load_jsonl(root / fold["heldout_manifest"]) + assert {row["take"].split("/")[0] for row in train}.isdisjoint( + {row["take"].split("/")[0] for row in heldout} + ) + assert {row["take"] for row in train}.isdisjoint({row["take"] for row in heldout}) + heldout_ids.extend((row["take"], row["run_index"]) for row in heldout) + assert len(heldout_ids) == len(set(heldout_ids)) == 5 + + +def test_subject_folds_reject_duplicate_records(tmp_path: Path) -> None: + source = tmp_path / "official_train.jsonl" + row = {"take": "subject1/h1/0/cam4", "run_index": 0, "frame_ids": [0]} + source.write_text(json.dumps(row) + "\n" + json.dumps(row) + "\n", encoding="utf-8") + + try: + build_subject_folds(source, tmp_path / "folds") + except ValueError as error: + assert "duplicate" in str(error) + else: + raise AssertionError("duplicate source record was accepted") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase5_missing_alignment_package.py b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase5_missing_alignment_package.py new file mode 100644 index 0000000000000000000000000000000000000000..27bd1f7ee8868df39b226e41a04e9ee254fed4f5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase5_missing_alignment_package.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import numpy as np +import pytest + +from scripts.build_phase5_missing_alignment_package import build_package + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def make_cache(tmp_path: Path, condition: str = "missing_depth") -> Path: + cache = tmp_path / "cache" + takes = cache / "takes" + takes.mkdir(parents=True) + take_path = takes / "subject3__o1__0__cam4.npz" + np.savez_compressed( + take_path, + take=np.asarray("subject3/o1/0/cam4"), + frame_id=np.asarray([1, 2], dtype=np.int64), + pred_wrist_translation=np.zeros((2, 2, 3), dtype=np.float32), + ) + manifest = { + "status": "complete", + "scope": "smoke", + "split_role": "official_validation", + "input_condition": condition, + "checkpoint": {"sha256": "checkpoint"}, + "takes": [{"path": str(take_path), "sha256": sha256(take_path)}], + "official_test_used": False, + } + (cache / "cache_manifest.json").write_text( + json.dumps(manifest) + "\n", encoding="utf-8", + ) + return cache + + +def test_builds_exact_zero_alignment_package(tmp_path: Path) -> None: + cache = make_cache(tmp_path) + output = tmp_path / "output" + report = build_package(cache, output, "missing_depth", "smoke") + assert report["status"] == "evaluated" + assert report["input_condition"] == "missing_depth" + prediction_path = Path(report["takes"][0]["path"]) + with np.load(prediction_path, allow_pickle=False) as prediction: + assert prediction["frame_id"].tolist() == [1, 2] + assert prediction["alignment_applied"].shape == (2, 2) + assert not prediction["alignment_applied"].any() + for key in ( + "calibrated_delta_z_m", "confidence", "inlier_ratio", + "residual_scale_m", "valid_fraction", "quality", + ): + assert np.array_equal(prediction[key], np.zeros((2, 2), dtype=np.float32)) + + +def test_rejects_condition_mismatch(tmp_path: Path) -> None: + cache = make_cache(tmp_path, condition="missing_k") + with pytest.raises(ValueError, match="missing-input cache contract"): + build_package(cache, tmp_path / "output", "missing_depth", "smoke") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase5_oof_bank.py b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ffd6ac50bd721a3db9b00c7dc1852fbac51efe --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase5_oof_bank.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +import json +import hashlib +from pathlib import Path + +import pytest + +from scripts.build_phase5_group_folds import build_subject_folds +from scripts.build_phase5_oof_bank import resolve_fold_contract, validate_checkpoint_provenance + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def write_source(path: Path) -> None: + rows = [ + {"take": "subject1/h1/0/cam4", "run_index": 0, "frame_ids": [0]}, + {"take": "subject2/h1/0/cam4", "run_index": 0, "frame_ids": [0]}, + {"take": "subject3/k1/0/cam4", "run_index": 0, "frame_ids": [0]}, + ] + path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") + + +def test_oof_contract_binds_checkpoint_training_and_heldout_hashes(tmp_path: Path) -> None: + source = tmp_path / "official_train.jsonl" + write_source(source) + root = tmp_path / "folds" + report = build_subject_folds(source, root) + fold = report["folds"][2] + provenance = tmp_path / "run_provenance.json" + provenance.write_text(json.dumps({ + "git_status": "", + "hashes": {"train_manifest": {"sha256": fold["train_manifest_sha256"]}}, + }), encoding="utf-8") + + contract = resolve_fold_contract( + root / "folds.json", 2, root / fold["heldout_manifest"], provenance, + ) + + assert contract["fold"]["heldout_subject"] == "subject3" + assert contract["fold"]["leakage_audit"]["passed"] + + +def test_oof_contract_rejects_in_fold_checkpoint_provenance(tmp_path: Path) -> None: + source = tmp_path / "official_train.jsonl" + write_source(source) + root = tmp_path / "folds" + report = build_subject_folds(source, root) + fold = report["folds"][0] + provenance = tmp_path / "run_provenance.json" + provenance.write_text(json.dumps({ + "git_status": "", + "hashes": {"train_manifest": {"sha256": "wrong"}}, + }), encoding="utf-8") + + with pytest.raises(ValueError, match="training manifest"): + resolve_fold_contract( + root / "folds.json", 0, root / fold["heldout_manifest"], provenance, + ) + + +def test_checkpoint_provenance_binds_config_commit_and_final_step(tmp_path: Path) -> None: + config_path = tmp_path / "config.yaml" + config_path.write_text("protocol:\n max_steps: 100\n", encoding="utf-8") + config = {"protocol": {"max_steps": 100}} + provenance_path = tmp_path / "run_provenance.json" + provenance = { + "git_commit": "abc123", + "config": config, + "hashes": {"config": {"sha256": sha256(config_path)}}, + } + provenance_path.write_text(json.dumps(provenance), encoding="utf-8") + checkpoint = { + "step": 100, + "extra": { + "config": config, + "git_commit": "abc123", + "run_provenance_sha256": sha256(provenance_path), + "checkpoint_role": "final", + }, + } + + validate_checkpoint_provenance( + checkpoint, + config=config, + config_path=config_path, + run_provenance_path=provenance_path, + provenance=provenance, + ) + + +@pytest.mark.parametrize( + ("field", "value", "message"), + ( + ("git_commit", "wrong", "git commit"), + ("run_provenance_sha256", "wrong", "provenance hash"), + ("checkpoint_role", "periodic", "fixed-final"), + ), +) +def test_checkpoint_provenance_rejects_mismatch( + tmp_path: Path, field: str, value: str, message: str, +) -> None: + config_path = tmp_path / "config.yaml" + config_path.write_text("protocol:\n max_steps: 2\n", encoding="utf-8") + config = {"protocol": {"max_steps": 2}} + provenance_path = tmp_path / "run_provenance.json" + provenance = { + "git_commit": "clean-commit", + "config": config, + "hashes": {"config": {"sha256": sha256(config_path)}}, + } + provenance_path.write_text(json.dumps(provenance), encoding="utf-8") + extra = { + "config": config, + "git_commit": "clean-commit", + "run_provenance_sha256": sha256(provenance_path), + "checkpoint_role": "final", + } + extra[field] = value + + with pytest.raises(ValueError, match=message): + validate_checkpoint_provenance( + {"step": 2, "extra": extra}, + config=config, + config_path=config_path, + run_provenance_path=provenance_path, + provenance=provenance, + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase8_stage7_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase8_stage7_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f4571e6ccf7bf339884ebe6dcbc69bb93bc16231 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase8_stage7_eval_queue.py @@ -0,0 +1,38 @@ +from pathlib import Path + +import pytest + +from scripts.build_phase8_stage7_eval_queue import build_queue + + +def test_stage7_queue_binds_augmented_heldout_manifests(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + config, checkpoint = tmp_path / "config.yaml", tmp_path / "checkpoint.pt" + config.write_text("config", encoding="utf-8") + checkpoint.write_text("checkpoint", encoding="utf-8") + manifests = {} + for dataset, mode in (("HOT3D", "rgb_k"), ("HOI4D", "rgb_d_k"), ("ARCTIC", "rgb_k")): + path = tmp_path / f"{dataset}.jsonl" + path.write_text(dataset, encoding="utf-8") + manifests[dataset] = (str(path), mode) + monkeypatch.setattr("scripts.build_phase8_stage7_eval_queue.STAGE7_DOMAINS", manifests) + import hashlib + digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest() + queue = build_queue( + condition="L1_left_root_relative", step=10000, + config=config, config_sha256=digest(config), + checkpoint=checkpoint, checkpoint_sha256=digest(checkpoint), + output_root=tmp_path / "output", bootstrap_resamples=20, + ) + assert queue["h2o_training_data_used"] is False + assert queue["official_test_used"] is False + assert [row["input_mode"] for row in queue["evaluations"]] == ["rgb_k", "rgb_d_k", "rgb_k"] + assert all(row["cache_manifest_sha256"] for row in queue["evaluations"]) + + +def test_stage7_queue_rejects_unfrozen_condition(tmp_path: Path) -> None: + with pytest.raises(ValueError, match="frozen Stage 7"): + build_queue( + condition="posthoc", step=10000, config=tmp_path / "missing", + config_sha256="x", checkpoint=tmp_path / "missing", + checkpoint_sha256="x", output_root=tmp_path, bootstrap_resamples=20, + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase9_final_deployment_plan.py b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase9_final_deployment_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ffd0b6fdf59494e2e8a89101a9d6c50beb9f82 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_build_phase9_final_deployment_plan.py @@ -0,0 +1,70 @@ +import json +from pathlib import Path + +import yaml + +from scripts.build_phase9_final_deployment_plan import build_plan, derive_causal_config +from scripts.run_phase9_unified_train_queue import sha256 + + +def test_causal_config_changes_only_parameter_free_attention_mode() -> None: + original = { + "name": "winner", + "model": { + "encoder": "dinov3", "temporal_attention_mode": "bidirectional", + }, + "data": {"resolution_hw": [512, 896]}, + } + causal = derive_causal_config(original) + assert causal["model"]["temporal_attention_mode"] == "causal" + causal["model"]["temporal_attention_mode"] = "bidirectional" + assert causal == original + + +def test_dynamic_plan_has_one_checkpoint_and_disjoint_workers(tmp_path: Path) -> None: + config = tmp_path / "winner.yaml" + config.write_text(yaml.safe_dump({ + "model": {"temporal_attention_mode": "bidirectional"}, + }), encoding="utf-8") + checkpoint = tmp_path / "winner.pt" + checkpoint.write_text("checkpoint", encoding="utf-8") + validation = tmp_path / "official_val.jsonl" + training = tmp_path / "official_train.jsonl" + validation.write_text("validation", encoding="utf-8") + training.write_text("training", encoding="utf-8") + freeze = tmp_path / "freeze.json" + freeze.write_text(json.dumps({ + "status": "phase9_final_unified_checkpoint_frozen", + "created_utc": "2026-07-30T00:00:00+00:00", "winner": "J55:final", + "selected_mechanism": "resolution", "resolution_hw": [512, 896], + "shared_augmentation": False, + "checkpoint": { + "path": str(checkpoint), "sha256": sha256(checkpoint), "step": 12, + }, + "config": {"path": str(config), "sha256": sha256(config)}, + "h2o_validation_manifest": { + "path": str(validation), "sha256": sha256(validation), + }, + "h2o_training_manifest": { + "path": str(training), "sha256": sha256(training), + }, + "h2o_official_validation_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }), encoding="utf-8") + state = tmp_path / "freeze_state.json" + state.write_text(json.dumps({ + "status": "complete", "freeze_sha256": sha256(freeze), + }), encoding="utf-8") + root = tmp_path / "h2o" + root.mkdir() + plan = build_plan( + freeze_path=freeze, freeze_state_path=state, + output_root=tmp_path / "output", worker_state_root=tmp_path / "states", + causal_config_path=tmp_path / "causal.yaml", h2o_root=root, + ) + assert len(plan["jobs"]) == 11 + assert len(plan["workers"]) == 4 + assert len({job["checkpoint_sha256"] for job in plan["jobs"]}) == 1 + assigned = [identifier for worker in plan["workers"] for identifier in worker["job_ids"]] + assert len(assigned) == len(set(assigned)) == 11 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_cache_phase4_jitter_predictions.py b/home/wuyifan/EgoNet_train_20261008/tests/test_cache_phase4_jitter_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..19a2bfa4226b7e9fcba7e1f5b65f10da7caa25b6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_cache_phase4_jitter_predictions.py @@ -0,0 +1,119 @@ +import hashlib + +import numpy as np +import torch + +from scripts.cache_phase4_jitter_predictions import ( + CACHE_VERSION, + FRAME_ARRAYS, + apply_input_condition, + load_valid_cache, + manifest_frame_count, + save_npz_atomic, + take_slug, + validate_cache_arrays, +) + + +def cache_arrays(frame_ids=(3, 4)): + arrays = { + key: np.zeros((len(frame_ids), 1), dtype=np.float32) + for key in FRAME_ARRAYS + } + arrays["clip_index"] = np.zeros(len(frame_ids), dtype=np.int64) + arrays["frame_id"] = np.asarray(frame_ids, dtype=np.int64) + arrays["frame_valid"] = np.ones(len(frame_ids), dtype=bool) + arrays.update({ + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + "take": np.asarray("subject3/k2/0/cam4"), + "checkpoint_sha256": np.asarray("checkpoint"), + "config_sha256": np.asarray("config"), + "manifest_sha256": np.asarray("manifest"), + }) + return arrays + + +def expected(frame_ids=(3, 4)): + return { + "take": "subject3/k2/0/cam4", + "expected_frame_ids": list(frame_ids), + "checkpoint_sha256": "checkpoint", + "config_sha256": "config", + "manifest_sha256": "manifest", + } + + +def test_cache_contract_and_atomic_reuse(tmp_path): + path = tmp_path / "take.npz" + arrays = cache_arrays() + + validate_cache_arrays(arrays, **expected()) + save_npz_atomic(path, arrays) + loaded = load_valid_cache(path, **expected()) + + assert loaded is not None + assert loaded["frame_id"].tolist() == [3, 4] + assert hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_cache_rejects_frame_mismatch_and_slug_is_stable(tmp_path): + path = tmp_path / "take.npz" + save_npz_atomic(path, cache_arrays()) + + assert load_valid_cache(path, **expected((3, 5))) is None + assert take_slug("subject3/k2/0/cam4") == "subject3__k2__0__cam4" + + +def test_missing_modality_input_conditions_do_not_mutate_evaluation_batch(): + K = torch.tensor(((2.0, 0, 1), (0, 2.0, 1), (0, 0, 1))).expand(1, 2, 3, 3).clone() + batch = { + "depth_available": torch.ones(1, 2, dtype=torch.bool), + "depth_m": torch.ones(1, 2, 1, 4, 4), + "depth_pixel_valid": torch.ones(1, 2, 1, 4, 4, dtype=torch.bool), + "K_available": torch.ones(1, 2, dtype=torch.bool), + "K": K, + } + + missing_depth = apply_input_condition(batch, "missing_depth") + missing_k = apply_input_condition(batch, "missing_k") + + assert not missing_depth["depth_available"].any() + assert not missing_depth["depth_m"].any() + assert not missing_depth["depth_pixel_valid"].any() + assert not missing_k["K_available"].any() + torch.testing.assert_close( + missing_k["K"], torch.eye(3).expand_as(missing_k["K"]), + ) + assert batch["depth_available"].all() and batch["K_available"].all() + assert batch["depth_m"].all() + + +def test_missing_cache_condition_is_hash_bound(tmp_path): + path = tmp_path / "take.npz" + arrays = cache_arrays() + arrays["input_condition"] = np.asarray("missing_depth") + save_npz_atomic(path, arrays) + + assert load_valid_cache(path, **expected(), input_condition="missing_depth") is not None + assert load_valid_cache(path, **expected(), input_condition="missing_k") is None + + +def test_manifest_frame_count_is_length_independent_and_rejects_duplicates(tmp_path): + manifest = tmp_path / "official_val.jsonl" + manifest.write_text( + '{"take":"subject3/k2/0/cam4","frame_ids":[3,4]}\n' + '{"take":"subject3/k2/1/cam4","frame_ids":[3]}\n', + encoding="utf-8", + ) + assert manifest_frame_count(manifest) == 3 + + manifest.write_text( + '{"take":"subject3/k2/0/cam4","frame_ids":[3,3]}\n', + encoding="utf-8", + ) + try: + manifest_frame_count(manifest) + except ValueError as error: + assert "duplicate manifest frame" in str(error) + else: + raise AssertionError("duplicate manifest frames must fail cache creation") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_camera_geometry.py b/home/wuyifan/EgoNet_train_20261008/tests/test_camera_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..c765f367b0e6294781478212019cdd604463e280 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_camera_geometry.py @@ -0,0 +1,44 @@ +import numpy as np +import torch + +from foundation_hand.geometry.camera import ( + depth_mm_to_m, + intrinsics_from_h2o, + project_points, + resize_and_pad_intrinsics, + unproject_depth, +) + + +def test_depth_mm_to_m() -> None: + depth_m, valid = depth_mm_to_m(np.array([[0, 500, 1250]], dtype=np.uint16)) + np.testing.assert_allclose(depth_m, [[0.0, 0.5, 1.25]]) + assert valid.tolist() == [[False, True, True]] + + +def test_depth_projection_round_trip() -> None: + K, _ = intrinsics_from_h2o(np.array([600, 610, 2, 1, 4, 3])) + depth = np.array([[1.0, 1.1, 1.2, 1.3], [1.4, 0.0, 1.6, 1.7], [1.8, 1.9, 2.0, 2.1]]) + points, valid = unproject_depth(depth, K) + uv, positive = project_points(points.reshape(-1, 3), K) + expected_u, expected_v = np.meshgrid(np.arange(4), np.arange(3)) + expected = np.stack((expected_u, expected_v), axis=-1).reshape(-1, 2) + mask = valid.reshape(-1) & positive + np.testing.assert_allclose(uv[mask], expected[mask], atol=1e-5) + + +def test_resize_and_padding_updates_intrinsics() -> None: + K = np.array([[1000, 0, 640], [0, 900, 360], [0, 0, 1]], dtype=np.float32) + updated = resize_and_pad_intrinsics(K, (720, 1280), (288, 512), (0, 8)) + np.testing.assert_allclose(updated, [[400, 0, 256], [0, 360, 152], [0, 0, 1]]) + + +def test_batched_projection_with_hand_and_joint_dimensions() -> None: + K = torch.tensor([[[100.0, 0.0, 32.0], [0.0, 100.0, 24.0], [0.0, 0.0, 1.0]]]).expand(2, 3, -1, -1) + points = torch.zeros(2, 3, 2, 21, 3) + points[..., 2] = 1.0 + uv, positive = project_points(points, K) + assert uv.shape == (2, 3, 2, 21, 2) + assert torch.allclose(uv[..., 0], torch.full_like(uv[..., 0], 32.0)) + assert torch.allclose(uv[..., 1], torch.full_like(uv[..., 1], 24.0)) + assert positive.all() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_checkpoint.py b/home/wuyifan/EgoNet_train_20261008/tests/test_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..39af052be8a342dbacbe44856a2ac3ddc49129ad --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_checkpoint.py @@ -0,0 +1,113 @@ +import torch + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) + + +def test_checkpoint_exact_model_optimizer_resume(tmp_path): + config = ModelConfig(encoder="tiny_debug", decoder_dim=32, decoder_layers=1, attention_heads=4, use_depth=False, use_rays=False) + model = BimanualReconstructionModel(config) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) + expected = {key: value.detach().clone() for key, value in model.state_dict().items()} + path = tmp_path / "checkpoint.pt" + save_checkpoint(path, model, optimizer, step=7, extra={"config": "test"}) + with torch.no_grad(): + next(model.parameters()).add_(1) + state = load_checkpoint(path, model, optimizer) + assert state == {"step": 7, "extra": {"config": "test"}} + assert all(torch.equal(model.state_dict()[key], value) for key, value in expected.items()) + + +def test_checkpoint_can_exclude_external_frozen_prefix(tmp_path): + config = ModelConfig(encoder="tiny_debug", decoder_dim=32, decoder_layers=1, attention_heads=4, use_depth=False, use_rays=False) + model = BimanualReconstructionModel(config) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) + expected_head = model.translation_head.weight.detach().clone() + path = tmp_path / "checkpoint_external.pt" + save_checkpoint(path, model, optimizer, step=3, exclude_prefixes=("rgb_encoder.",)) + with torch.no_grad(): + model.translation_head.weight.add_(1) + state = load_checkpoint(path, model, optimizer) + assert state["step"] == 3 + assert torch.equal(model.translation_head.weight, expected_head) + + +def test_old_checkpoint_can_initialize_only_registered_oracle_parameters(tmp_path): + base_config = ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, use_depth=True, depth_mode="geometry", use_rays=True, + ) + base = BimanualReconstructionModel(base_config) + optimizer = torch.optim.AdamW(base.parameters(), lr=1e-3) + path = tmp_path / "base.pt" + save_checkpoint( + path, base, optimizer, step=17, + exclude_prefixes=("rgb_encoder.network.0.",), + ) + refined = BimanualReconstructionModel(ModelConfig( + **{ + **base_config.__dict__, + "oracle_crop_mode": "oracle_depth_k", + "freeze_coarse_for_oracle_crop": True, + } + )) + + record = load_model_initialization( + path, refined, allowed_missing_prefixes=("oracle_crop_",), + ) + + assert record["step"] == 17 + assert record["missing_keys"] + assert record["residual_missing_keys"] + assert all( + key.startswith(("oracle_crop_", "rgb_encoder.network.0.")) + for key in record["missing_keys"] + ) + for key, value in base.state_dict().items(): + if key.startswith("rgb_encoder.network.0."): + continue + assert torch.equal(refined.state_dict()[key], value) + + +def test_checkpoint_can_initialize_matched_control_without_optimizer(tmp_path): + config = ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, use_depth=False, use_rays=False, + ) + source = BimanualReconstructionModel(config) + optimizer = torch.optim.AdamW(source.parameters(), lr=1e-3) + path = tmp_path / "source.pt" + save_checkpoint(path, source, optimizer, step=19) + target = BimanualReconstructionModel(config) + record = load_model_initialization( + path, target, allowed_missing_prefixes=(), require_residual=False, + ) + assert record["step"] == 19 + assert record["missing_keys"] == [] + assert record["residual_missing_keys"] == [] + for key, value in source.state_dict().items(): + assert torch.equal(target.state_dict()[key], value) + + +def test_old_checkpoint_initializes_only_structured_residual_parameters(tmp_path): + config = ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, use_depth=True, use_rays=True, + ) + source = BimanualReconstructionModel(config) + optimizer = torch.optim.AdamW(source.parameters(), lr=1e-3) + path = tmp_path / "source.pt" + save_checkpoint(path, source, optimizer, step=23) + target = BimanualReconstructionModel(ModelConfig( + **{**config.__dict__, "structured_hand_refinement": True}, + )) + record = load_model_initialization( + path, target, allowed_missing_prefixes=("structured_",), + ) + assert record["step"] == 23 + assert record["residual_missing_keys"] + assert all(key.startswith("structured_") for key in record["missing_keys"]) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_compare_phase5_alignment_calibrators.py b/home/wuyifan/EgoNet_train_20261008/tests/test_compare_phase5_alignment_calibrators.py new file mode 100644 index 0000000000000000000000000000000000000000..cc48c5d6c0cb2601c32f1ebcc8925fe8803473c6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_compare_phase5_alignment_calibrators.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import copy + +import pytest + +from scripts.compare_phase5_alignment_calibrators import CONDITIONS, METRICS, compare_reports + + +def condition_metrics(offset: float) -> dict[str, dict[str, float]]: + return { + condition: { + metric: 20.0 + condition_index + metric_index + offset + for metric_index, metric in enumerate(METRICS) + } + for condition_index, condition in enumerate(CONDITIONS) + } + + +def report(seed: int, offset: float = 0.0) -> dict[str, object]: + return { + "expected_banks_per_fold": 1, + "coarse_seeds": [seed], + "metrics": condition_metrics(offset), + } + + +def test_compare_shared_and_per_seed_reports_uses_matched_coarse_baselines() -> None: + seeds = (20260716, 20260717, 20260718) + per_seed = [report(seed) for seed in seeds] + shared_metrics = {str(seed): condition_metrics(0.0) for seed in seeds} + for metrics in shared_metrics.values(): + for metric in METRICS: + metrics["calibrated_always"][metric] -= 0.5 + shared = { + "expected_banks_per_fold": 3, + "coarse_seeds": list(seeds), + "metrics_by_seed": shared_metrics, + } + + rows, summary = compare_reports(shared, per_seed) + + assert len(rows) == 12 + assert summary["shared_absolute_better_seed_count"] == 3 + assert summary["mean_shared_minus_per_seed_absolute_mpjpe_mm"] == pytest.approx(-0.5) + + +def test_compare_rejects_unmatched_coarse_or_missing_seed() -> None: + seeds = (20260716, 20260717, 20260718) + per_seed = [report(seed) for seed in seeds] + shared = { + "expected_banks_per_fold": 3, + "coarse_seeds": list(seeds), + "metrics_by_seed": {str(seed): condition_metrics(0.0) for seed in seeds}, + } + mismatched = copy.deepcopy(per_seed) + mismatched[0]["metrics"]["coarse"]["absolute_mpjpe_mm"] += 0.1 + with pytest.raises(ValueError, match="coarse absolute_mpjpe_mm mismatch"): + compare_reports(shared, mismatched) + with pytest.raises(ValueError, match="do not match shared seeds"): + compare_reports(shared, per_seed[:-1]) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_compare_phase8_specialist_curve.py b/home/wuyifan/EgoNet_train_20261008/tests/test_compare_phase8_specialist_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..912e487a98876b7368365aecc4069a1a58afb6b3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_compare_phase8_specialist_curve.py @@ -0,0 +1,75 @@ +import csv +import hashlib +import json + +import pytest + +from scripts.compare_phase8_specialist_curve import compare + + +def _bundle(tmp_path, name, step, offset=0.0, changed_frame=False): + rows = tmp_path / f"{name}.csv" + fields = ( + "dataset", "physical_recording_id", "camera_id", "frame_id", "side", + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + with rows.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + for recording, base in (("r1", 10.0), ("r2", 20.0)): + for index in range(2): + value = base + index + offset + writer.writerow({ + "dataset": "HOT3D", "physical_recording_id": recording, + "camera_id": "rgb", "frame_id": ( + "changed" if changed_frame and recording == "r2" and index == 1 + else str(index) + ), + "side": "right", "absolute_mpjpe_mm": value, + "root_relative_mpjpe_mm": value, "mpvpe_mm": value, + "fingertip_mpjpe_mm": value, + "translation_z_mae_mm": value, + }) + report = tmp_path / f"{name}.json" + report.write_text(json.dumps({ + "status": "evaluated", "evaluation_role": "external_heldout", + "h2o_training_data_used": False, "official_test_used": False, + "oracle_information_used": False, "input_mode": "rgb_k", + "clips": 4, "frames": 4, + "cache_manifest": {"path": "/cache", "sha256": "a" * 64}, + "checkpoint_step": step, + "checkpoint": {"path": f"/{name}.pt", "sha256": name * 64}, + "per_hand_rows": { + "path": str(rows), + "sha256": hashlib.sha256(rows.read_bytes()).hexdigest(), + }, + "metrics": { + metric: {"mean": 15.5 + offset, "p95": 21.0 + offset} + for metric in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + }, + }), encoding="utf-8") + return report + + +def test_specialist_curve_comparison_is_recording_paired(tmp_path) -> None: + reference = _bundle(tmp_path, "reference", 50000) + candidate = _bundle(tmp_path, "candidate", 100000, offset=-2.0) + result = compare(reference, candidate, seed=7, resamples=500) + absolute = result["metrics"]["absolute_mpjpe_mm"] + assert absolute["mean_delta"] == -2.0 + assert absolute["recording_count"] == 2 + assert result["candidate_absolute_ci_excludes_zero"] is True + assert result["official_test_used"] is False + + +def test_specialist_curve_comparison_rejects_frame_identity_change(tmp_path) -> None: + reference = _bundle(tmp_path, "reference", 50000) + candidate = _bundle( + tmp_path, "candidate", 100000, offset=-2.0, changed_frame=True, + ) + with pytest.raises(ValueError, match="identities differ"): + compare(reference, candidate, seed=7, resamples=50) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_compare_phase8_stage7_left.py b/home/wuyifan/EgoNet_train_20261008/tests/test_compare_phase8_stage7_left.py new file mode 100644 index 0000000000000000000000000000000000000000..e9a24ae971cfceaf868572364b3b95c90fef3c0e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_compare_phase8_stage7_left.py @@ -0,0 +1,58 @@ +import json +from pathlib import Path + +from scripts.compare_phase8_stage7_left import compare + + +def artifact(path: Path, content: str) -> dict: + import hashlib + + path.write_text(content, encoding="utf-8") + return {"path": str(path), "sha256": hashlib.sha256(content.encode()).hexdigest()} + + +def evaluation(tmp_path: Path, condition: str, dataset: str, absolute: float, root: float, source: float | None) -> Path: + prefix = tmp_path / f"{condition}_{dataset}" + prefix.mkdir() + rows = "physical_recording_id,camera_id,frame_id,side,absolute_mpjpe_mm,root_relative_mpjpe_mm,source_root_relative_mpjpe_mm\n" + rows += f"r0,c0,0,left,{absolute},{root},{'' if source is None else source}\n" + report = { + "status": "evaluated", "evaluation_role": "external_heldout", + "input_mode": "rgb_d_k" if dataset == "HOI4D" else "rgb_k", + "h2o_training_data_used": False, "official_test_used": False, + "metrics": { + "absolute_mpjpe_mm": {"mean": absolute}, + "root_relative_mpjpe_mm": {"mean": root}, + "source_root_relative_mpjpe_mm": None if source is None else {"mean": source}, + }, + "per_hand_rows": artifact(prefix / "rows.csv", rows), + "cache_manifest": artifact(prefix / "cache.jsonl", f"{dataset}\n"), + "checkpoint": artifact(prefix / "checkpoint.pt", condition), + "config": artifact(prefix / "config.yaml", condition), + } + path = prefix / "evaluation.json" + path.write_text(json.dumps(report), encoding="utf-8") + return path + + +def test_stage7_comparison_applies_frozen_gate(tmp_path: Path) -> None: + items = [] + for condition, offset in (("L0_sampler_only", 0.0), ("L1_left_root_relative", 0.2)): + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + source = None if dataset == "HOT3D" else 20.0 - 1.0 * (condition.startswith("L1")) + path = evaluation(tmp_path, condition, dataset, 30.0 + offset, 20.0 + offset, source) + items.append({"condition": condition, "dataset": dataset, "evaluation": str(path)}) + # Point both conditions at identical cache artifacts, as a real matched screen must. + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + l0 = json.loads(Path(next(row["evaluation"] for row in items if row["condition"].startswith("L0") and row["dataset"] == dataset)).read_text()) + l1_path = Path(next(row["evaluation"] for row in items if row["condition"].startswith("L1") and row["dataset"] == dataset)) + l1 = json.loads(l1_path.read_text()) + l1["cache_manifest"] = l0["cache_manifest"] + l1_path.write_text(json.dumps(l1), encoding="utf-8") + result = compare({ + "evaluation_split": "external_heldout_only", + "h2o_training_data_used": False, "official_test_used": False, + "evaluations": items, + }, resamples=20) + assert result["dataset_macro"]["source_root_relative_mpjpe_mm"]["L1_minus_L0"] == -1.0 + assert result["gate"]["accepted"] is True diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_dataset.py b/home/wuyifan/EgoNet_train_20261008/tests/test_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..546aba7d3fc6a000c1e4cb2c781aadee0069f7a9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_dataset.py @@ -0,0 +1,118 @@ +from pathlib import Path + +import pytest +import numpy as np +import torch + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import ( + PhotometricAugmentation, + apply_photometric_augmentation, + sample_photometric_parameters, +) + +ROOT = Path("/SSD3/jiasen/foundation_hand/H2O/extracted") +MANIFEST = Path("artifacts/phase2/data_audit/manifests/debug_cam4.jsonl") + + +@pytest.mark.skipif(not ROOT.exists() or not MANIFEST.exists(), reason="H2O cam4 debug data unavailable") +def test_real_dataset_contract_and_presence_separation(): + dataset = H2OCam4Dataset(ROOT, MANIFEST, (224, 384), (2,), (1,), max_clips=1) + sample = dataset[0] + assert sample["rgb"].shape == (2, 3, 224, 384) + assert sample["depth_m"].shape == (2, 1, 224, 384) + assert sample["joint3d_camera"].shape == (2, 2, 21, 3) + assert sample["camera_id"] == "cam4" + assert not sample["presence_label_valid"].any() + assert torch.isnan(sample["presence_target"]).all() + assert sample["dataset_id"] == "H2O" + assert sample["physical_recording_id"].startswith("subject") + assert sample["hand_side_id"][0].tolist() == [0, 1] + for key in ( + "joint2d_valid", "joint3d_valid", "translation_valid", + "mano_pose_valid", "shape_valid", "vertices_valid", + "presence_valid", "depth_input_available", "K_input_available", + "K_supervision_valid", + ): + assert key in sample + assert torch.equal(sample["translation_valid"], sample["joint_annotation_valid"]) + assert torch.equal(sample["mano_pose_valid"], sample["mano_annotation_valid"]) + + +@pytest.mark.skipif(not ROOT.exists() or not MANIFEST.exists(), reason="H2O cam4 debug data unavailable") +def test_oracle_crop_dataset_contract_is_explicit_and_raw_source_based(): + dataset = H2OCam4Dataset( + ROOT, MANIFEST, (224, 384), (2,), (1,), max_clips=1, + oracle_crop_enabled=True, + ) + + sample = dataset[0] + + assert sample["oracle_crop_rgb"].shape == (2, 2, 3, 224, 224) + assert sample["oracle_crop_depth_m"].shape == (2, 2, 1, 224, 224) + assert sample["oracle_crop_depth_pixel_valid"].shape == (2, 2, 1, 224, 224) + assert sample["oracle_crop_K"].shape == (2, 2, 3, 3) + assert sample["oracle_crop_box_xyxy_raw"].shape == (2, 2, 4) + assert sample["oracle_crop_available"].shape == (2, 2) + assert torch.all( + sample["oracle_crop_depth_available"] <= sample["oracle_crop_available"] + ) + boxes = sample["oracle_crop_box_xyxy_raw"][sample["oracle_crop_available"]] + assert torch.all(boxes[:, 2] - boxes[:, 0] >= 96) + assert torch.equal(boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]) + + +@pytest.mark.skipif(not ROOT.exists() or not MANIFEST.exists(), reason="H2O cam4 debug data unavailable") +def test_variable_length_padding_never_loops_frames(): + dataset = H2OCam4Dataset(ROOT, MANIFEST, (224, 384), (2, 4), (1,), max_clips=20) + short = dataset[0] + long = next(dataset[index] for index in range(len(dataset)) if len(dataset.clips[index].frame_ids) == 4) + batch = collate_h2o_clips([short, long]) + assert batch["frame_valid"].shape == (2, 4) + assert batch["frame_valid"][0].tolist() == [True, True, False, False] + assert batch["frame_id"][0, 2:].tolist() == [-1, -1] + + +def test_photometric_parameters_are_step_resumable_and_geometry_free(): + config = PhotometricAugmentation( + enabled=True, probability=1.0, brightness=0.2, + contrast=0.2, saturation=0.2, hue=0.05, + ) + first = sample_photometric_parameters(config, 17, 4, 2) + np.testing.assert_array_equal( + first, sample_photometric_parameters(config, 17, 4, 2) + ) + assert not np.array_equal(first, sample_photometric_parameters(config, 17, 4, 3)) + image = np.asarray([[[255, 0, 0], [0, 255, 0]]], dtype=np.uint8) + augmented = apply_photometric_augmentation(image, first) + assert augmented.shape == image.shape + assert augmented.dtype == image.dtype + + +@pytest.mark.skipif(not ROOT.exists() or not MANIFEST.exists(), reason="H2O cam4 debug data unavailable") +def test_photometric_clip_keeps_depth_k_and_targets_exact(): + common = dict( + root=ROOT, manifest=MANIFEST, target_hw=(224, 384), + clip_lengths=(2,), strides=(1,), max_clips=1, augmentation_seed=17, + ) + off = H2OCam4Dataset( + **common, photometric_augmentation={"enabled": False}, + )[(0, 2)] + default = H2OCam4Dataset( + root=ROOT, manifest=MANIFEST, target_hw=(224, 384), + clip_lengths=(2,), strides=(1,), max_clips=1, + )[0] + on = H2OCam4Dataset(**common, photometric_augmentation={ + "enabled": True, "probability": 1.0, "brightness": 0.2, + "contrast": 0.2, "saturation": 0.2, "hue": 0.05, + })[(0, 2)] + assert not torch.equal(off["rgb"], on["rgb"]) + assert torch.equal(default["rgb"], off["rgb"]) + assert torch.equal( + on["photometric_aug_params"][0], on["photometric_aug_params"][1] + ) + for key in ( + "depth_m", "depth_pixel_valid", "K", "joint3d_camera", "joint2d", + "mano_pose", "mano_shape", "wrist_root_translation", "frame_id", + ): + torch.testing.assert_close(off[key], on[key], equal_nan=True) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_differentiable_mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/tests/test_differentiable_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..9a620630e2eec2fedaec161f47872372ba3e8b3b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_differentiable_mixed_projection.py @@ -0,0 +1,79 @@ +import torch + +from foundation_hand.geometry.mixed_projection import solve_mixed_projection_translation + + +def synthetic(dtype=torch.float64): + K = torch.tensor( + [[600.0, 0.0, 320.0], [0.0, 580.0, 184.0], [0.0, 0.0, 1.0]], + dtype=dtype, + ) + x = torch.linspace(-0.04, 0.04, 21, dtype=dtype) + y = 0.025 * torch.sin(torch.linspace(0.0, torch.pi * 2.0, 21, dtype=dtype)) + z = torch.linspace(-0.015, 0.025, 21, dtype=dtype) + joints = torch.stack((x, y, z), dim=-1) + translation = torch.tensor([0.035, -0.018, 0.55], dtype=dtype) + camera = joints + translation + anchors = torch.stack(( + K[0, 0] * camera[:, 0] / camera[:, 2] + K[0, 2], + K[1, 1] * camera[:, 1] / camera[:, 2] + K[1, 2], + ), dim=-1) + return joints, anchors, K, translation + + +def test_differentiable_solver_recovers_exact_translation() -> None: + joints, anchors, K, translation = synthetic() + result = solve_mixed_projection_translation( + joints[None], anchors[None], K[None], translation[2:3], + torch.zeros(1, 3, dtype=joints.dtype), image_hw=(368, 640), + ) + torch.testing.assert_close(result.translation_m[0], translation, rtol=0, atol=1e-9) + assert result.success.item() + assert result.support_count.item() == 21 + + +def test_differentiable_solver_backpropagates_to_all_inputs() -> None: + joints, anchors, K, translation = synthetic(dtype=torch.float32) + joints = joints[None].requires_grad_() + anchors = anchors[None].requires_grad_() + z = translation[2:3].clone().requires_grad_() + result = solve_mixed_projection_translation( + joints, anchors, K[None], z, torch.zeros(1, 3), + image_hw=(368, 640), + ) + loss = result.translation_m.square().sum() + loss.backward() + assert joints.grad is not None and torch.isfinite(joints.grad).all() and joints.grad.abs().sum() > 0 + assert anchors.grad is not None and torch.isfinite(anchors.grad).all() and anchors.grad.abs().sum() > 0 + assert z.grad is not None and torch.isfinite(z.grad).all() and z.grad.abs().sum() > 0 + + +def test_differentiable_solver_invalid_k_uses_exact_fallback() -> None: + joints, anchors, K, translation = synthetic() + fallback = torch.tensor([[0.1, 0.2, 0.4]], dtype=joints.dtype) + result = solve_mixed_projection_translation( + joints[None], anchors[None], K[None], translation[2:3], fallback, + image_hw=(368, 640), K_available=torch.tensor([False]), + ) + torch.testing.assert_close( + result.translation_m, fallback, + ) + assert not result.success.item() + + +def test_differentiable_solver_supports_deterministic_cuda() -> None: + if not torch.cuda.is_available(): + return + joints, anchors, K, translation = synthetic(dtype=torch.float32) + previous = torch.are_deterministic_algorithms_enabled() + try: + torch.use_deterministic_algorithms(True) + result = solve_mixed_projection_translation( + joints[None].cuda(), anchors[None].cuda(), K[None].cuda(), + translation[2:3].cuda(), torch.zeros(1, 3, device="cuda"), + image_hw=(368, 640), + ) + assert result.success.item() + assert torch.isfinite(result.residual_scale_px).all() + finally: + torch.use_deterministic_algorithms(previous) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_dinov3_2d_pretrain.py b/home/wuyifan/EgoNet_train_20261008/tests/test_dinov3_2d_pretrain.py new file mode 100644 index 0000000000000000000000000000000000000000..0fb6d5ece186ff55d919fb904755ddd62379005b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_dinov3_2d_pretrain.py @@ -0,0 +1,249 @@ +import numpy as np +import pytest +import torch +from collections import Counter +from types import SimpleNamespace + +from experiments.dinov3_2d_pretrain.audit import project_geometry, recording_id, select_specs, summarize +from experiments.dinov3_2d_pretrain.eval_p0 import ( + SelectedDevFrames, decode_coordinates, pixel_summary, +) +from experiments.dinov3_2d_pretrain.full_index import ( + arctic_unreadable_reason, find_child, transformed_row, +) +from experiments.dinov3_2d_pretrain.loss import ( + KeypointPretrainLoss, OCCLUDED_IN_FRAME, OUT_OF_FRAME, UNREVIEWED, VISIBLE, +) +from experiments.dinov3_2d_pretrain.train_p0 import ( + PositionRange, QUOTAS, is_expected_hot3d_sync_error, source_and_ordinal, +) +from experiments.dinov3_2d_pretrain.train_p0b import lr_multiplier +from experiments.dinov3_2d_pretrain.visible_index import remap_row + + +def test_projection_bucket_is_not_called_visibility(): + joints = np.full((2, 21, 3), np.nan, np.float32) + joints[0, 0] = (0, 0, 1) + joints[0, 1] = (2, 0, 1) + K = np.array([[100, 0, 50], [0, 100, 50], [0, 0, 1]], np.float32) + uv, bucket = project_geometry(joints, K, 100, 100) + assert np.allclose(uv[0, 0], (50, 50)) + assert bucket[0, 0] == "in_frame" + assert bucket[0, 1] == "out_of_frame" + assert bucket[1, 0] == "unknown" + + +def test_recording_keys_are_source_specific(): + assert recording_id("H2O", {"take": "take_1"}) == "take_1" + assert recording_id("ARCTIC", {"physical_recording_id": "s01/clip"}) == "s01/clip" + assert recording_id("HOT3D", {"recording_id": "P0001_x"}) == "P0001_x" + + +def test_audit_can_take_distinct_frames_when_requested_frames_exceed_recordings(): + rows = {} + for source, key in (("H2O", "take"), ("ARCTIC", "physical_recording_id"), + ("HOT3D", "recording_id")): + rows[source] = [{key: "recording", "filtered_tile_id": f"{source}-{index}", + "expected_frame_ids": list(range(index * 8, index * 8 + 8))} + for index in range(3)] + dataset = SimpleNamespace(sources={source: SimpleNamespace(rows=value) for source, value in rows.items()}) + specs = select_specs(dataset, 2) + for source in ("H2O", "ARCTIC", "HOT3D"): + chosen = [row for spec, row in specs if spec["source"] == source] + assert len(chosen) == 2 + assert chosen[0]["expected_frame_ids"][4] != chosen[1]["expected_frame_ids"][4] + + +def test_review_report_keeps_unreviewed_separate_and_exposes_valid_mask_errors(): + manifest = {"samples": [{"sample_id": "a", "source": "H2O", "recording": "r", "joints": [ + {"side": 0, "joint": 0, "geometry_bucket": "in_frame", "joint2d_valid": True}, + {"side": 0, "joint": 1, "geometry_bucket": "in_frame", "joint2d_valid": False, "uv": [3, 5]}, + {"side": 0, "joint": 2, "geometry_bucket": "unknown", "joint2d_valid": False}, + ]}]} + report = summarize(manifest, {"a:0:0": "occluded_in_frame", "a:0:1": "visible"}, + {"a:0:1": [4, 5]}, + {"a:0:0": "occluded_in_frame", "a:0:1": "visible"})["source"]["H2O"] + assert report["review_state_count"]["unreviewed"] == 1 + assert report["review_coverage"] == pytest.approx(2 / 3) + assert report["joint2d_valid_by_geometry_proxy"] == {"in_frame": 1} + assert report["review_state_count"]["occluded_in_frame"] == 1 + assert report["joint2d_valid_as_visibility_errors"]["false_visible"] == 1 + assert report["joint2d_valid_as_visibility_errors"]["missed_visible"] == 1 + assert report["visible_projection_vs_manual_px"]["median"] == 1 + assert report["reviewer_agreement"]["double_reviewed_binary_joints"] == 2 + assert report["reviewer_agreement"]["agreement"] == 1 + with pytest.raises(ValueError): + summarize(manifest, {"bad:0:0": "visible"}) + + +def test_unknown_review_never_supervises_visibility_or_visible_coordinates(): + torch.manual_seed(1) + predictions = { + "infer_x": torch.randn(1, 2, 21, 8, requires_grad=True), + "infer_y": torch.randn(1, 2, 21, 8, requires_grad=True), + "visible_x": torch.randn(1, 2, 21, 8, requires_grad=True), + "visible_y": torch.randn(1, 2, 21, 8, requires_grad=True), + "visibility": torch.randn(1, 2, 21, 3, requires_grad=True), + } + uv = torch.full((1, 2, 21, 2), float("nan")) + uv[0, 0, :3] = torch.tensor([[3., 3.], [4., 4.], [5., 5.]]) + valid = torch.zeros((1, 2, 21), dtype=torch.bool) + valid[0, 0, :3] = True + states = torch.full((1, 2, 21), UNREVIEWED) + states[0, 0, 0] = VISIBLE + states[0, 0, 1] = OCCLUDED_IN_FRAME + states[0, 0, 2] = OUT_OF_FRAME + observed = torch.full_like(uv, float("nan")) + observed[0, 0, 0] = torch.tensor([3., 3.]) + total, details = KeypointPretrainLoss(image_hw=(8, 8))( + predictions, uv, valid, states, observed, + ) + assert details["infer_count"] == 2 + assert details["visible_count"] == 1 + assert details["status_count"] == 3 + total.backward() + assert torch.count_nonzero(predictions["visible_x"].grad[0, 0, 0]) + assert not torch.count_nonzero(predictions["visible_x"].grad[0, 0, 1]) + assert not torch.count_nonzero(predictions["infer_x"].grad[0, 0, 2]) + + +def test_no_reviewed_labels_does_not_create_visibility_gradient(): + prediction = {key: torch.randn(1, 2, 21, width, requires_grad=True) + for key, width in (("infer_x", 8), ("infer_y", 8), + ("visible_x", 8), ("visible_y", 8), ("visibility", 3))} + uv = torch.full((1, 2, 21, 2), 4.) + valid = torch.ones((1, 2, 21), dtype=torch.bool) + states = torch.full((1, 2, 21), UNREVIEWED) + total, details = KeypointPretrainLoss(image_hw=(8, 8))(prediction, uv, valid, states) + total.backward() + assert details["infer_count"] == 42 + assert details["visible_count"] == details["status_count"] == 0 + assert not torch.count_nonzero(prediction["visibility"].grad) + assert not torch.count_nonzero(prediction["visible_x"].grad) + + +def test_reviewed_visible_without_manual_point_does_not_use_projection_as_observed_gt(): + prediction = {key: torch.randn(1, 2, 21, width, requires_grad=True) + for key, width in (("infer_x", 8), ("infer_y", 8), + ("visible_x", 8), ("visible_y", 8), ("visibility", 3))} + uv = torch.full((1, 2, 21, 2), 4.) + valid = torch.ones((1, 2, 21), dtype=torch.bool) + states = torch.full((1, 2, 21), UNREVIEWED) + states[0, 0, 0] = VISIBLE + _, details = KeypointPretrainLoss(image_hw=(8, 8))(prediction, uv, valid, states) + assert details["infer_count"] == 42 + assert details["visible_count"] == 0 + assert details["status_count"] == 1 + + +def test_manual_visible_point_can_supervise_both_heads_when_projection_is_missing(): + prediction = {key: torch.randn(1, 2, 21, width, requires_grad=True) + for key, width in (("infer_x", 8), ("infer_y", 8), + ("visible_x", 8), ("visible_y", 8), ("visibility", 3))} + uv = torch.full((1, 2, 21, 2), float("nan")) + manual = uv.clone() + manual[0, 0, 0] = torch.tensor([3., 4.]) + valid = torch.zeros((1, 2, 21), dtype=torch.bool) + states = torch.full((1, 2, 21), UNREVIEWED) + states[0, 0, 0] = VISIBLE + _, details = KeypointPretrainLoss(image_hw=(8, 8))(prediction, uv, valid, states, manual) + assert details["infer_count"] == 1 + assert details["visible_count"] == 1 + + +def test_visible_child_remaps_gt_offset_without_changing_frame_identity(): + row = {"filtered_tile_id": "parent:11", "filtered_window_id": "parent", + "filtered_gt_path": "/old/gt.npz", "filtered_start_offset": 11, + "expected_frame_ids": [212], "recording_id": "recording"} + child = {"id": "child", "dataset": "HOT3D", "recording_id": "recording", + "parent_frame_slice": [8, 16], "parent_filtered_gt_path": "/old/gt.npz", + "filtered_gt_path": "/new/gt.npz"} + mapped = remap_row(row, "HOT3D", [child]) + assert mapped["filtered_tile_id"] == "child:3" + assert mapped["filtered_start_offset"] == 3 + assert mapped["filtered_gt_path"] == "/new/gt.npz" + assert mapped["expected_frame_ids"] == [212] + assert remap_row({**row, "filtered_start_offset": 7}, "HOT3D", [child]) is None + with pytest.raises(ValueError, match="mismatch"): + remap_row({**row, "recording_id": "other"}, "HOT3D", [child]) + + +def test_full_phase_index_uses_exact_hot3d_timestamp(tmp_path): + child = {"start": 4, "end": 12, "path": tmp_path / "gt.npz", + "frame_ids": np.arange(104, 112), + "row": {"id": "child", "recording_id": "recording", "stream_id": "214-1"}} + assert find_child([child], 3) is None + assert find_child([child], 7) == (child, 3) + template = {"filtered_tile_id": "parent:0", "filtered_start_offset": 0, + "expected_frame_ids": [100], "timestamps_ns": [1000]} + result = transformed_row(template, "HOT3D", child, 3, tmp_path, + {"recording": {"214-1": list(range(200))}}) + assert result["filtered_tile_id"] == "child:3" + assert result["filtered_start_offset"] == 3 + assert result["expected_frame_ids"] == [107] + assert result["timestamps_ns"] == [107] + + +def test_p0_global_source_cycle_and_ddp_shards(): + assignments = [source_and_ordinal(position) for position in range(120)] + assert Counter(source for source, _ in assignments[:60]) == QUOTAS + for source, quota in QUOTAS.items(): + assert sorted(ordinal for name, ordinal in assignments if name == source) == list(range(2 * quota)) + rank0 = list(PositionRange(2, 4, 0, 2, 24)) + rank1 = list(PositionRange(2, 4, 1, 2, 24)) + assert set(rank0).isdisjoint(rank1) + assert sorted(rank0 + rank1) == list(range(48, 96)) + + +def test_p0b_warmup_and_80k_cosine_schedule(): + assert lr_multiplier(0, 1000, 80000) == pytest.approx(.001) + assert lr_multiplier(999, 1000, 80000) == pytest.approx(1) + assert 0 < lr_multiplier(29999, 1000, 80000) < 1 + assert lr_multiplier(79999, 1000, 80000) == pytest.approx(0) + with pytest.raises(ValueError): + lr_multiplier(80000, 1000, 80000) + + +def test_p0_eval_decodes_bin_centers_and_reports_pixel_error(): + prediction = {"infer_x": torch.tensor([[[[0., 3.]]]]), + "infer_y": torch.tensor([[[[4., 0.]]]])} + assert decode_coordinates(prediction, 4).tolist() == [[[[6., 2.]]]] + result = pixel_summary([0., 10., 20.]) + assert result["median_px"] == 10. + assert result["pck10"] == pytest.approx(2 / 3) + + +def test_p0_eval_only_skips_known_hot3d_sync_failure(): + class Dataset: + rows = [{"filtered_tile_id": "bad", "recording_id": "recording"}] + + def __len__(self): + return len(self.rows) + + def __getitem__(self, spec): + raise RuntimeError("HOT3D 20ms synchronization failure recording=sample") + + selected = SelectedDevFrames(Dataset(), "HOT3D", phase=0, count=1) + assert selected[0] == {"unreadable_tile_id": "bad"} + selected.source = "H2O" + with pytest.raises(RuntimeError, match="20ms synchronization failure"): + selected[0] + + +def test_only_named_hot3d_sync_failure_may_be_resampled(): + error = RuntimeError("HOT3D 20ms synchronization failure recording=sample") + assert is_expected_hot3d_sync_error("HOT3D", error) + assert not is_expected_hot3d_sync_error("H2O", error) + assert not is_expected_hot3d_sync_error("HOT3D", RuntimeError("GT mismatch")) + + +def test_arctic_bounds_excludes_camera_tail_even_with_gt(tmp_path): + image = tmp_path / "frame.jpg" + image.write_bytes(b"valid file") + row = {"camera_path": "camera.npy", "mano_path": "mano.npy", + "array_indices_0based": [649], "image_paths": [str(image)]} + cache = {("camera.npy", "mano.npy"): {"camera_R": 649, "camera_T": 650, + "mano_left_rot": 650}} + assert arctic_unreadable_reason(row, cache) == "camera_R_index_649_outside_649" + row["array_indices_0based"] = [648] + assert arctic_unreadable_reason(row, cache) is None diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_dinov3_real.py b/home/wuyifan/EgoNet_train_20261008/tests/test_dinov3_real.py new file mode 100644 index 0000000000000000000000000000000000000000..b9025486d8ddf4ecc7537f257c32735138f46303 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_dinov3_real.py @@ -0,0 +1,39 @@ +from pathlib import Path + +import pytest +import torch + +from foundation_hand.models.encoders import DinoV3Encoder + + +WEIGHTS = Path("/SSD3/jiasen/foundation_hand/pretrained/dinov3") +SOURCE = Path("third_party/dinov3") + + +@pytest.mark.skipif(not (WEIGHTS / "model.safetensors").is_file(), reason="Local DINOv3 Base unavailable") +def test_real_dinov3_base_dense_tokens_and_frozen_gradients(): + encoder = DinoV3Encoder(SOURCE, WEIGHTS, output_dim=32, frozen=True) + features = encoder(torch.randn(1, 3, 64, 80)) + assert features.tokens.shape == (1, 20, 32) + assert features.grid_hw == (4, 5) + features.tokens.square().mean().backward() + assert encoder.projection.weight.grad is not None + assert all(parameter.grad is None for parameter in encoder.backbone.parameters()) + + +@pytest.mark.skipif(not (WEIGHTS / "model.safetensors").is_file(), reason="Local DINOv3 Base unavailable") +def test_real_dinov3_last_two_blocks_are_the_only_trainable_backbone_layers(): + encoder = DinoV3Encoder( + SOURCE, WEIGHTS, output_dim=32, frozen=True, trainable_last_blocks=2, + ) + blocks = encoder._backbone_blocks() + assert all(not parameter.requires_grad for block in blocks[:-2] for parameter in block.parameters()) + assert all(parameter.requires_grad for block in blocks[-2:] for parameter in block.parameters()) + assert all(parameter.requires_grad for parameter in encoder._backbone_final_norm().parameters()) + encoder.train() + assert not blocks[-3].training + assert blocks[-2].training and blocks[-1].training + features = encoder(torch.randn(1, 3, 64, 80)) + features.tokens.square().mean().backward() + assert all(parameter.grad is None for block in blocks[:-2] for parameter in block.parameters()) + assert any(parameter.grad is not None for block in blocks[-2:] for parameter in block.parameters()) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase3_subset.py b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase3_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..324efb5d030a0765a0954f086685b9acf965291f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase3_subset.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import hashlib +import json + +import pytest + +from scripts.evaluate_phase3 import load_clip_indices_manifest + + +def test_clip_indices_manifest_is_hash_and_contract_bound(tmp_path) -> None: + source = tmp_path / "val.jsonl" + source.write_text("{}\n", encoding="utf-8") + record = { + "version": "fixed-v1", + "count": 3, + "source_manifest_sha256": hashlib.sha256(source.read_bytes()).hexdigest(), + "source_clip_count": 5, + "dataset_contract": {"resolution_hw": [368, 640], "T": 8, "stride": 1}, + "clip_indices": [0, 2, 4], + } + path = tmp_path / "subset.json" + path.write_text(json.dumps(record), encoding="utf-8") + + indices, loaded = load_clip_indices_manifest( + path, + source_manifest=source, + data_config={"resolution_hw": [368, 640], "T": 8, "stride": 1}, + dataset_length=5, + ) + + assert indices == [0, 2, 4] + assert loaded["version"] == "fixed-v1" + + +def test_clip_indices_manifest_rejects_duplicate_indices(tmp_path) -> None: + source = tmp_path / "val.jsonl" + source.write_text("{}\n", encoding="utf-8") + path = tmp_path / "subset.json" + path.write_text(json.dumps({ + "count": 2, + "source_manifest_sha256": hashlib.sha256(source.read_bytes()).hexdigest(), + "source_clip_count": 3, + "dataset_contract": {"resolution_hw": [368, 640], "T": 8, "stride": 1}, + "clip_indices": [1, 1], + }), encoding="utf-8") + + with pytest.raises(ValueError, match="count/uniqueness"): + load_clip_indices_manifest( + path, + source_manifest=source, + data_config={"resolution_hw": [368, 640], "T": 8, "stride": 1}, + dataset_length=3, + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase4_jitter.py b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase4_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..ae5246197802cb6bc940e7e485c5531fba6e0fb8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase4_jitter.py @@ -0,0 +1,125 @@ +import numpy as np + +from scripts.evaluate_phase4_jitter import ( + build_overview, + choose_filter_conditions, + condition_grid, + paired_take_bootstrap_rows, + temporal_metrics, +) + + +def metric_rows(values_by_condition): + metric_names = ( + "absolute_mpjpe_mm", + "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", + "joint_velocity_error_mm_per_s", + "joint_acceleration_error_mm_per_s2", + "predicted_3d_joint_acceleration_mm_per_s2", + "predicted_3d_joint_jerk_mm_per_s3", + "predicted_2d_joint_acceleration_px_per_s2", + "predicted_2d_joint_jerk_px_per_s3", + "high_frequency_energy_ratio", + "clip_boundary_discontinuity_mm", + ) + rows = [] + for condition, values in values_by_condition.items(): + for metric in metric_names: + value = values.get(metric, 10.0) + rows.append({ + "condition": condition, "metric": metric, + "mean": value, "p95": value, + }) + return rows + + +def test_registered_grid_and_selection_respect_accuracy_guardrail(): + grid = condition_grid() + conditions = [ + grid["F0_raw"], grid["F1_ema_alpha0.2"], grid["F1_ema_alpha0.6"], + grid["F2_butterworth_2hz"], + ] + rows = metric_rows({ + "F0_raw": {}, + "F1_ema_alpha0.2": { + "predicted_3d_joint_acceleration_mm_per_s2": 5.0, + "predicted_3d_joint_jerk_mm_per_s3": 5.0, + "predicted_2d_joint_acceleration_px_per_s2": 5.0, + "predicted_2d_joint_jerk_px_per_s3": 5.0, + }, + "F1_ema_alpha0.6": { + "predicted_3d_joint_acceleration_mm_per_s2": 7.0, + "predicted_3d_joint_jerk_mm_per_s3": 7.0, + "predicted_2d_joint_acceleration_px_per_s2": 7.0, + "predicted_2d_joint_jerk_px_per_s3": 7.0, + }, + "F2_butterworth_2hz": { + "absolute_mpjpe_mm": 10.2, + "predicted_3d_joint_acceleration_mm_per_s2": 2.0, + "predicted_3d_joint_jerk_mm_per_s3": 2.0, + "predicted_2d_joint_acceleration_px_per_s2": 2.0, + "predicted_2d_joint_jerk_px_per_s3": 2.0, + }, + }) + + overview = build_overview(rows, conditions, "subset") + selected = choose_filter_conditions(overview) + + assert selected["F1"] == "F1_ema_alpha0.2" + assert selected["F2"] is None + ema_row = next( + row for row in overview if row["condition"] == "F1_ema_alpha0.2" + ) + assert ema_row["accuracy_delta"] == ema_row["absolute_mpjpe_mm_delta"] + assert ema_row["jitter_delta"] == -5.0 + assert "velocity_error_delta" in ema_row + assert "acceleration_error_delta" in ema_row + assert next( + row for row in overview if row["condition"] == "F2_butterworth_2hz" + )["accuracy_guardrail_passed"] is False + + +def test_temporal_target_windows_align_for_velocity_and_acceleration(): + frames = 4 + joints = np.zeros((frames, 2, 21, 3), dtype=np.float32) + joints[:, :, :, 0] = np.arange(frames)[:, None, None] * 0.001 + arrays = { + "clip_index": np.zeros(frames, dtype=np.int64), + "frame_id": np.arange(frames, dtype=np.int64), + "frame_valid": np.ones(frames, dtype=bool), + "target_joints_camera": joints.copy(), + "joint_element_valid": np.ones((frames, 2, 21), dtype=bool), + "target_wrist_translation": joints[:, :, 0].copy(), + "joint_annotation_valid": np.ones((frames, 2), dtype=bool), + } + projected = np.zeros((frames, 2, 21, 2), dtype=np.float32) + + metrics = temporal_metrics( + arrays, joints, projected, np.ones(frames, dtype=bool), + ) + + assert metrics["joint_velocity_error_mm_per_s"] == [0.0] * 6 + assert metrics["joint_acceleration_error_mm_per_s2"] == [0.0] * 4 + assert metrics["wrist_velocity_error_mm_per_s"] == [0.0] * 6 + assert metrics["wrist_acceleration_error_mm_per_s2"] == [0.0] * 4 + + +def test_paired_take_bootstrap_uses_take_deltas(): + conditions = [condition_grid()["F0_raw"], condition_grid()["F1_ema_alpha0.4"]] + rows = [] + for take, raw, filtered in (("a", 10.0, 8.0), ("b", 20.0, 17.0)): + for condition, value in (("F0_raw", raw), ("F1_ema_alpha0.4", filtered)): + rows.append({ + "scope": "subset", "take": take, "condition": condition, + "metric": "predicted_3d_joint_acceleration_mm_per_s2", + "mean": value, "p95": value + 1.0, + }) + + output = paired_take_bootstrap_rows(rows, conditions, samples=100) + + mean_row = next(row for row in output if row["take_statistic"] == "mean") + assert mean_row["takes"] == 2 + assert mean_row["filtered_minus_raw"] == -2.5 + assert mean_row["ci_high"] <= -2.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase5_causal_state.py b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..56f81dca3adab47e122b08114004400029645fc4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase5_causal_state.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import numpy as np + +from scripts.evaluate_phase5_causal_state import ( + CONDITIONS, + build_overview, + condition_z, + paired_bootstrap, + translated_geometry, + uncertainty_base, +) + + +def fixture_arrays() -> tuple[dict[str, np.ndarray], dict[str, np.ndarray], dict[str, object]]: + time = 8 + arrays = { + "pred_wrist_translation": np.zeros((time, 2, 3), dtype=np.float32), + "pred_joints_camera": np.zeros((time, 2, 21, 3), dtype=np.float32), + "pred_vertices_camera": np.zeros((time, 2, 5, 3), dtype=np.float32), + "clip_index": np.zeros(time, dtype=np.int64), + "frame_id": np.arange(time), + "frame_valid": np.ones(time, dtype=bool), + } + arrays["pred_wrist_translation"][..., 2] = 0.5 + arrays["pred_joints_camera"][..., 2] = 0.5 + arrays["pred_vertices_camera"][..., 2] = 0.5 + prediction = { + "alignment_applied": np.ones((time, 2), dtype=bool), + "calibrated_delta_z_m": np.full((time, 2), 0.01), + "confidence": np.ones((time, 2)), + "inlier_ratio": np.ones((time, 2)), + "residual_scale_m": np.zeros((time, 2)), + "valid_fraction": np.ones((time, 2)), + "quality": np.ones((time, 2)), + } + selected = { + "fixed_kalman": { + "process_sigma_m_per_frame2": 0.002, + "measurement_sigma_m": 0.02, + "uncertainty_strength": 0.0, + }, + "uncertainty_kalman": { + "process_sigma_m_per_frame2": 0.002, + "measurement_sigma_m": 0.02, + "uncertainty_strength": 2.0, + }, + } + return arrays, prediction, {"selected": selected} + + +def condition(name: str): + return next(item for item in CONDITIONS if item.name == name) + + +def test_calibrated_condition_has_exact_coarse_fallback() -> None: + arrays, prediction, selection = fixture_arrays() + prediction["alignment_applied"][3, 1] = False + z_m, _, _ = condition_z( + arrays, prediction, condition("calibrated_per_frame"), selection, + ) + assert z_m[2, 1] == np.float64(0.51) + assert z_m[3, 1] == np.float64(0.5) + assert uncertainty_base(prediction)[3, 1] == 5.0 + + +def test_kalman_resets_at_clip_boundary_and_uses_current_measurement() -> None: + arrays, prediction, selection = fixture_arrays() + prediction["calibrated_delta_z_m"][:4] = 0.0 + prediction["calibrated_delta_z_m"][4:] = 0.1 + arrays["clip_index"][4:] = 1 + z_m, _, _ = condition_z( + arrays, prediction, condition("uncertainty_kalman"), selection, + ) + np.testing.assert_allclose(z_m[4], 0.6, atol=1e-7) + + +def test_translation_z_shift_does_not_change_relative_geometry() -> None: + arrays, _, _ = fixture_arrays() + z_m = np.full((8, 2), 0.55) + translation, joints, vertices = translated_geometry(arrays, z_m) + np.testing.assert_allclose(translation[..., :2], arrays["pred_wrist_translation"][..., :2]) + np.testing.assert_allclose(joints[..., :2], arrays["pred_joints_camera"][..., :2]) + np.testing.assert_allclose(vertices[..., :2], arrays["pred_vertices_camera"][..., :2]) + np.testing.assert_allclose(joints[..., 2], 0.55) + np.testing.assert_allclose(vertices[..., 2], 0.55) + + +def test_overview_applies_static_guardrails_and_dynamic_gate() -> None: + metrics = ( + "absolute_mpjpe_mm", "absolute_mpvpe_mm", "fingertip_mpjpe_mm", + "translation_z_mae_mm", "joint_velocity_error_mm_per_s", + "joint_acceleration_error_mm_per_s2", + "predicted_3d_joint_acceleration_mm_per_s2", + "predicted_3d_joint_jerk_mm_per_s3", "high_frequency_energy_ratio", + "estimated_causal_lag_frames", + ) + rows = [] + for condition_item in CONDITIONS: + for metric in metrics: + reference = 10.0 + value = reference + if condition_item.name == "uncertainty_kalman": + value = 10.1 if metric in ( + "absolute_mpjpe_mm", "translation_z_mae_mm", + ) else 9.0 + rows.append({ + "condition": condition_item.name, "metric": metric, + "mean": value, "p95": value, + }) + overview = build_overview(rows) + selected = next(row for row in overview if row["condition"] == "uncertainty_kalman") + assert selected["static_guardrail_passed"] is True + assert selected["retained_causal_candidate"] is True + + +def test_paired_bootstrap_skips_undefined_take_statistics() -> None: + rows = [ + { + "take": "subject/take", "condition": "calibrated_per_frame", + "metric": "sparse_metric", "mean": 1.0, "p95": 1.0, + }, + { + "take": "subject/take", "condition": "coarse", + "metric": "sparse_metric", "mean": None, "p95": 2.0, + }, + ] + output = paired_bootstrap(rows, samples=10) + coarse = [row for row in output if row["condition"] == "coarse"] + assert len(coarse) == 1 + assert coarse[0]["take_statistic"] == "p95" + assert coarse[0]["condition_minus_reference"] == 1.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase5_metric_alignment.py b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase5_metric_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..996406e617baf24799eed9f3f94213107249ca5d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase5_metric_alignment.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import numpy as np +import pytest + +from scripts.evaluate_phase5_metric_alignment import ( + METRICS, + RAW_CONDITIONS, + paired_take_bootstrap, + take_rows, + write_csv, +) + + +def test_write_csv_accepts_velocity_and_acceleration_row_union(tmp_path) -> None: + output = tmp_path / "temporal.csv" + write_csv(output, [ + {"condition": "coarse", "velocity": 1.0}, + {"condition": "coarse", "acceleration": 2.0}, + ]) + lines = output.read_text().splitlines() + assert lines[0] == "condition,velocity,acceleration" + assert lines[1] == "coarse,1.0," + assert lines[2] == "coarse,,2.0" + + +def test_paired_take_bootstrap_uses_matched_take_deltas() -> None: + rows = [] + for take, coarse, refined in (("a", 10.0, 8.0), ("b", 20.0, 19.0)): + for condition, value in (("coarse", coarse), ("robust_alignment_unscaled", refined)): + row = {"condition": condition, "take": take} + for metric in METRICS: + row[metric] = value + rows.append(row) + # Add the remaining conditions as exact coarse fallbacks. + for take, coarse in (("a", 10.0), ("b", 20.0)): + for condition in ( + "calibrated_always", "calibrated_confidence", + "missing_depth_fallback", "missing_k_fallback", + ): + row = {"condition": condition, "take": take} + for metric in METRICS: + row[metric] = coarse + rows.append(row) + + output = paired_take_bootstrap(rows, samples=1000, seed=1) + target = next( + row for row in output + if row["condition"] == "robust_alignment_unscaled" + and row["metric"] == "absolute_mpjpe_mm" + ) + assert target["takes"] == 2 + assert target["delta_mean"] == -1.5 + assert target["ci_high"] <= -1.0 + + raw_output = paired_take_bootstrap(rows, conditions=RAW_CONDITIONS, samples=1000, seed=1) + assert {row["condition"] for row in raw_output} == {"robust_alignment_unscaled"} + + +def test_take_rows_applies_translation_z_once_to_all_mano_geometry() -> None: + correction = np.full((1, 2), 0.01, dtype=np.float32) + pred_joints = np.zeros((1, 2, 21, 3), dtype=np.float32) + pred_vertices = np.zeros((1, 2, 778, 3), dtype=np.float32) + pred_joints[..., 2] = 1.0 + pred_vertices[..., 2] = 1.0 + target_joints = pred_joints.copy() + target_vertices = pred_vertices.copy() + target_joints[..., 2] += correction[..., None] + target_vertices[..., 2] += correction[..., None] + pred_translation = np.zeros((1, 2, 3), dtype=np.float32) + pred_translation[..., 2] = 1.0 + target_translation = pred_translation.copy() + target_translation[..., 2] += correction + arrays = { + "take": np.asarray("subject3/o2/3/cam4"), + "frame_id": np.asarray((0,)), + "frame_valid": np.asarray((True,)), + "mano_annotation_valid": np.ones((1, 2), dtype=bool), + "pred_joints_camera": pred_joints, + "pred_vertices_camera": pred_vertices, + "pred_wrist_translation": pred_translation, + "target_joints_camera": target_joints, + "target_vertices_camera": target_vertices, + "target_wrist_translation": target_translation, + "target_2d_px": np.zeros((1, 2, 21, 2), dtype=np.float32), + "pred_direct_2d_px": np.zeros((1, 2, 21, 2), dtype=np.float32), + "K": np.broadcast_to(np.eye(3, dtype=np.float32), (1, 3, 3)), + } + geometry = { + "coarse_hand_scale_px": np.full((1, 2), 80.0), + "alignment_delta_z_m": correction, + "alignment_valid_support_count": np.full((1, 2), 40), + "alignment_conditioning_quality": np.ones((1, 2)), + } + + rows, _ = take_rows( + arrays, + geometry, + {"calibrated_confidence": correction}, + correction, + np.ones((1, 2)), + ) + + assert len(rows) == 2 + for row in rows: + assert row["absolute_mpjpe_mm"] == pytest.approx(0.0, abs=1e-4) + assert row["absolute_mpvpe_mm"] == pytest.approx(0.0, abs=1e-4) + assert row["translation_x_mae_mm"] == pytest.approx(0.0, abs=1e-4) + assert row["translation_y_mae_mm"] == pytest.approx(0.0, abs=1e-4) + assert row["translation_z_mae_mm"] == pytest.approx(0.0, abs=1e-4) + assert row["applied_delta_z_mm"] == pytest.approx(10.0) + + +def test_take_rows_reports_identity_preference_switch() -> None: + joints = np.zeros((2, 2, 21, 3), dtype=np.float32) + joints[..., 2] = 1.0 + joints[:, 1, :, 0] = 1.0 + target_joints = joints.copy() + target_joints[1] = target_joints[1, ::-1] + vertices = np.repeat(joints[:, :, :1], 778, axis=2) + target_vertices = vertices.copy() + translation = joints[:, :, 0].copy() + target_translation = target_joints[:, :, 0].copy() + arrays = { + "take": np.asarray("subject3/o2/3/cam4"), + "frame_id": np.asarray((0, 1)), + "frame_valid": np.asarray((True, True)), + "mano_annotation_valid": np.ones((2, 2), dtype=bool), + "pred_joints_camera": joints, + "pred_vertices_camera": vertices, + "pred_wrist_translation": translation, + "target_joints_camera": target_joints, + "target_vertices_camera": target_vertices, + "target_wrist_translation": target_translation, + "target_2d_px": np.zeros((2, 2, 21, 2), dtype=np.float32), + "pred_direct_2d_px": np.zeros((2, 2, 21, 2), dtype=np.float32), + "K": np.broadcast_to(np.eye(3, dtype=np.float32), (2, 3, 3)), + } + geometry = { + "coarse_hand_scale_px": np.full((2, 2), 80.0), + "alignment_delta_z_m": np.zeros((2, 2)), + "alignment_valid_support_count": np.full((2, 2), 40), + "alignment_conditioning_quality": np.ones((2, 2)), + } + + _, temporal = take_rows( + arrays, + geometry, + {"coarse": np.zeros((2, 2))}, + np.zeros((2, 2)), + np.ones((2, 2)), + ) + + identity = [row for row in temporal if "identity_switch_fraction" in row] + assert len(identity) == 1 + assert identity[0]["identity_switch_fraction"] == 1.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase5_missing_modality.py b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase5_missing_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..22ef125a2cc380958556e5695d63c8aa5db29643 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase5_missing_modality.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import numpy as np + +from scripts.evaluate_phase5_missing_modality import ( + matched_cache_arrays, + paired_take_bootstrap, +) + + +def test_matched_cache_arrays_allows_equal_nan_targets() -> None: + keys = ( + "frame_id", "frame_valid", "K", "target_rotation_matrices", "target_shape", + "target_wrist_translation", "target_joints_camera", "target_vertices_camera", + "target_2d_px", "joint_annotation_valid", "joint_element_valid", + "mano_annotation_valid", + ) + reference = {key: np.asarray([1.0, np.nan]) for key in keys} + candidate = {key: value.copy() for key, value in reference.items()} + + assert matched_cache_arrays(reference, candidate) + candidate["frame_id"][0] = 2 + assert not matched_cache_arrays(reference, candidate) + + +def test_paired_take_bootstrap_reports_missing_minus_complete() -> None: + rows = [] + for take, complete, missing_depth, missing_k in ( + ("a", 10.0, 12.0, 14.0), ("b", 20.0, 24.0, 26.0), + ): + for condition, value in ( + ("complete", complete), ("missing_depth", missing_depth), ("missing_k", missing_k), + ): + rows.append({"condition": condition, "take": take, "metric": "absolute_mpjpe_mm", "mean": value}) + + result = paired_take_bootstrap(rows, samples=1000, seed=1) + + depth = next(row for row in result if row["condition"] == "missing_depth") + intrinsics = next(row for row in result if row["condition"] == "missing_k") + assert depth["condition_minus_reference"] == 3.0 + assert intrinsics["condition_minus_reference"] == 5.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase6_mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase6_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..1aab461ebfcb036215feb60e49ca2936cfceb3ec --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase6_mixed_projection.py @@ -0,0 +1,51 @@ +import numpy as np + +from scripts.evaluate_phase6_mixed_projection import ( + REFERENCE, + condition_specs, + correction_grid, +) + + +def selection() -> dict[str, object]: + return { + "winner": { + "minimum_support": 4, + "huber_delta_px": 16.0, + } + } + + +def test_frozen_validation_matrix_has_all_assemblies_and_z_modes() -> None: + specs = condition_specs(selection()) + identifiers = {str(spec["id"]) for spec in specs} + assert len(specs) == len(identifiers) == 20 + assert REFERENCE in identifiers + for z_mode in ( + "coarse", "raw_alignment", "calibrated_always", + "calibrated_confidence_0p6", + ): + assert f"coarse_wrist_ray__z_{z_mode}" in identifiers + assert f"direct_2d_wrist_ray__z_{z_mode}" in identifiers + assert f"mixed_wls_s4__z_{z_mode}" in identifiers + assert f"mixed_huber_d16_s4__z_{z_mode}" in identifiers + + +def test_correction_grid_applies_only_available_alignment() -> None: + alignment = { + "alignment_applied": np.asarray([[True, False], [True, True]]), + "raw_alignment_delta_z_m": np.asarray([[0.1, 0.2], [0.3, 0.4]]), + "calibrated_delta_z_m": np.asarray([[0.01, 0.02], [0.03, 0.04]]), + "gated_delta_z_m": np.asarray([[0.001, 0.002], [0.003, 0.004]]), + } + grid = correction_grid(alignment) + np.testing.assert_array_equal(grid["coarse"], np.zeros((2, 2))) + np.testing.assert_array_equal( + grid["raw_alignment"], [[0.1, 0.0], [0.3, 0.4]], + ) + np.testing.assert_array_equal( + grid["calibrated_always"], [[0.01, 0.0], [0.03, 0.04]], + ) + np.testing.assert_array_equal( + grid["calibrated_confidence_0p6"], [[0.001, 0.0], [0.003, 0.004]], + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase6_state_ray.py b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase6_state_ray.py new file mode 100644 index 0000000000000000000000000000000000000000..d71b1c24b30e930c6823bfc9e6e43c9e95800ba6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_evaluate_phase6_state_ray.py @@ -0,0 +1,33 @@ +import numpy as np + +from scripts.evaluate_phase6_state_ray import assemble_state_ray_geometry + + +def test_state_ray_geometry_preserves_ray_and_rigid_geometry() -> None: + coarse = np.asarray([[[0.10, -0.05, 0.50], [-0.12, 0.08, 0.80]]]) + joints = coarse[..., None, :] + np.asarray([[[[0.01, 0.02, 0.03]], [[-0.02, 0.01, 0.04]]]]) + vertices = coarse[..., None, :] + np.asarray([[[[0.03, -0.01, 0.02]], [[0.01, -0.02, 0.05]]]]) + z = np.asarray([[0.75, 0.60]]) + + translation, refined_joints, refined_vertices = assemble_state_ray_geometry( + coarse, joints, vertices, z, + ) + + np.testing.assert_allclose(translation[..., :2] / translation[..., 2:], coarse[..., :2] / coarse[..., 2:]) + np.testing.assert_allclose(refined_joints - translation[..., None, :], joints - coarse[..., None, :]) + np.testing.assert_allclose(refined_vertices - translation[..., None, :], vertices - coarse[..., None, :]) + + +def test_state_ray_geometry_falls_back_for_invalid_depth() -> None: + coarse = np.asarray([[[0.10, -0.05, 0.50], [0.20, 0.10, 0.80]]]) + joints = np.broadcast_to(coarse[..., None, :], (1, 2, 2, 3)).copy() + vertices = np.broadcast_to(coarse[..., None, :], (1, 2, 3, 3)).copy() + z = np.asarray([[np.nan, 0.01]]) + + translation, refined_joints, refined_vertices = assemble_state_ray_geometry( + coarse, joints, vertices, z, + ) + + np.testing.assert_allclose(translation, coarse) + np.testing.assert_allclose(refined_joints, joints) + np.testing.assert_allclose(refined_vertices, vertices) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_external_baseline_adapters.py b/home/wuyifan/EgoNet_train_20261008/tests/test_external_baseline_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..d4e1d49ff588f5abf1ee654337aca43938de8500 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_external_baseline_adapters.py @@ -0,0 +1,49 @@ +import numpy as np + +from scripts.run_dynhamr_h2o import _interpolate_linear, _interpolate_rotvec +from scripts.run_handdgp_h2o import _prepare_crop + + +def test_handdgp_crop_preserves_box_center_ray_in_raw_camera(): + image = np.zeros((200, 300, 3), dtype=np.uint8) + intrinsic = np.asarray( + [[500.0, 0.0, 150.0], [0.0, 600.0, 100.0], [0.0, 0.0, 1.0]], + dtype=np.float32, + ) + + def fake_generate_patch_image(**kwargs): + height, width = kwargs["out_shape"] + return np.zeros((height, width, 3), dtype=np.uint8), None, None, None, None + + crop, canonical_intrinsic, ray_offset = _prepare_crop( + image, + np.asarray([100.0, 50.0, 140.0, 90.0], dtype=np.float32), + intrinsic, + is_left=False, + input_size=224, + crop_scale=1.3, + canonical_focal=1000.0, + generate_patch_image=fake_generate_patch_image, + ) + + assert tuple(crop.shape) == (3, 224, 224) + np.testing.assert_allclose( + canonical_intrinsic.numpy(), + [[1000.0, 0.0, 112.0], [0.0, 1000.0, 112.0], [0.0, 0.0, 1.0]], + ) + np.testing.assert_allclose(ray_offset.numpy(), [-0.06, -0.05], atol=1e-7) + + +def test_dynhamr_interpolation_fills_only_inside_visible_track(): + visible = np.asarray([False, True, False, True, False]) + values = np.asarray([[-9.0], [1.0], [-9.0], [3.0], [-9.0]]) + interpolated = _interpolate_linear(values, visible) + np.testing.assert_allclose(interpolated[:, 0], [-9.0, 1.0, 2.0, 3.0, -9.0]) + + rotations = np.zeros((5, 1, 3), dtype=np.float64) + rotations[0] = -9.0 + rotations[4] = -9.0 + rotations[3, 0, 2] = np.pi / 2 + interpolated_rotations = _interpolate_rotvec(rotations, visible) + np.testing.assert_allclose(interpolated_rotations[2, 0, 2], np.pi / 4) + np.testing.assert_allclose(interpolated_rotations[[0, 4]], rotations[[0, 4]]) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_fit_phase5_alignment_calibrator.py b/home/wuyifan/EgoNet_train_20261008/tests/test_fit_phase5_alignment_calibrator.py new file mode 100644 index 0000000000000000000000000000000000000000..de77b139dd62ce7ff90ce20afe2454f0df704380 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_fit_phase5_alignment_calibrator.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +import numpy as np +import pytest + +from foundation_hand.evaluation.alignment_calibration import ( + features_from_take, + projected_hand_scale_px, +) +from scripts.fit_phase5_alignment_calibrator import ( + correction_metrics, + select_confidence_threshold, + validate_bank_layout, + write_predictions, +) + + +def test_features_from_take_are_geometric_and_finite() -> None: + time = 3 + arrays = { + "frame_id": np.arange(time), + "alignment_delta_z_m": np.full((time, 2), 0.02), + "alignment_valid_support_count": np.full((time, 2), 30), + "alignment_inlier_ratio": np.ones((time, 2)), + "alignment_residual_scale_m": np.full((time, 2), 0.005), + "alignment_valid_fraction": np.full((time, 2), 0.5), + "alignment_foreground_fraction": np.zeros((time, 2)), + "alignment_background_fraction": np.zeros((time, 2)), + "alignment_depth_discontinuity_m": np.full((time, 2), 0.01), + "alignment_conditioning_quality": np.full((time, 2), 0.7), + "pred_wrist_translation": np.ones((time, 2, 3)), + "coarse_hand_scale_px": np.full((time, 2), 80.0), + "coarse_direct_mano_consistency_px": np.full((time, 2), 4.0), + "silhouette_overlap_fraction": np.zeros(time), + "coarse_wrist_velocity_m_per_frame": np.zeros((time, 2, 3)), + } + features = features_from_take(arrays) + assert features.shape == (time, 2, 15) + assert np.isfinite(features).all() + np.testing.assert_array_equal(features[:, :, -1], [[0, 1], [0, 1], [0, 1]]) + + +def test_projected_hand_scale_uses_model_pixel_coordinates() -> None: + joints = np.asarray(( + ((100.0, 50.0), (220.0, 130.0)), + ((400.0, 200.0), (480.0, 240.0)), + )) + + scale = projected_hand_scale_px( + joints, source_hw=(720, 1280), target_hw=(368, 640), + ) + + assert scale.tolist() == pytest.approx([60.0, 40.0]) + + +def synthetic_samples(target_z: np.ndarray) -> dict[str, np.ndarray]: + count = len(target_z) + pred_joints = np.zeros((count, 21, 3), dtype=np.float64) + target_joints = pred_joints.copy() + target_joints[..., 2] = target_z[:, None] + return { + "target_residual_z_m": target_z, + "pred_joints_m": pred_joints, + "target_joints_m": target_joints, + "alignment_applied": np.ones(count, dtype=bool), + } + + +def test_correction_metrics_and_threshold_selection_use_absolute_mpjpe() -> None: + target = np.asarray([0.02, 0.02, 0.02, -0.02]) + samples = synthetic_samples(target) + coarse = correction_metrics(samples, np.zeros(4)) + corrected = correction_metrics(samples, target) + assert corrected["absolute_mpjpe_mm"] == 0.0 + assert corrected["z_p95_mm"] == 0.0 + assert coarse["absolute_mpjpe_mm"] > 0.0 + + threshold, rows = select_confidence_threshold( + samples, target, np.asarray([0.99, 0.99, 0.99, 0.99]), + ) + assert threshold == 0.5 + assert rows[0]["absolute_mpjpe_mm"] == 0.0 + + +def test_threshold_selection_never_applies_unavailable_alignment() -> None: + target = np.asarray([0.02, 0.02]) + samples = synthetic_samples(target) + samples["alignment_applied"] = np.asarray([True, False]) + + threshold, rows = select_confidence_threshold( + samples, target, np.asarray([0.99, 0.99]), + ) + + assert threshold == 0.5 + assert rows[0]["available_fraction"] == 0.5 + assert rows[0]["applied_fraction"] == 0.5 + assert rows[0]["absolute_mpjpe_mm"] == pytest.approx(10.0) + + +def test_prediction_audit_marks_unavailable_alignment_as_fallback(tmp_path) -> None: + samples = { + "subject": np.asarray(["subject1", "subject1"]), + "take": np.asarray(["subject1/a/0/cam4", "subject1/a/0/cam4"]), + "frame_id": np.asarray([1, 2]), + "side": np.asarray([0, 1]), + "target_residual_z_m": np.asarray([0.02, 0.02]), + "raw_delta_z_m": np.asarray([0.01, 0.01]), + "alignment_applied": np.asarray([True, False]), + } + output = tmp_path / "predictions.csv" + + write_predictions( + output, samples, np.asarray([0.02, 0.02]), np.asarray([0.9, 0.9]), 0.5, + ) + + rows = output.read_text().splitlines() + assert rows[0].endswith("confidence,alignment_available,applied") + assert rows[1].endswith("0.9,True,True") + assert rows[2].endswith("0.9,False,False") + + +def bank_manifest(fold: int, seed: int, checkpoint: str) -> dict[str, object]: + return { + "fold": fold, + "seed": seed, + "checkpoint": {"sha256": checkpoint}, + } + + +def test_expanded_bank_layout_requires_complete_three_by_three_matrix() -> None: + seeds = (20260716, 20260717, 20260718) + manifests = [ + bank_manifest(fold, seed, f"{fold}-{seed}") + for fold in range(3) + for seed in seeds + ] + + layout = validate_bank_layout(manifests, expected_banks_per_fold=3) + + assert layout["banks_per_fold"] == {"0": 3, "1": 3, "2": 3} + assert layout["coarse_seeds"] == list(seeds) + + +def test_expanded_bank_layout_rejects_missing_or_duplicate_seed_fold() -> None: + seeds = (20260716, 20260717, 20260718) + manifests = [ + bank_manifest(fold, seed, f"{fold}-{seed}") + for fold in range(3) + for seed in seeds + ] + with pytest.raises(ValueError, match="bank count per fold"): + validate_bank_layout(manifests[:-1], expected_banks_per_fold=3) + manifests[-1] = bank_manifest(2, 20260717, "replacement-checkpoint") + with pytest.raises(ValueError, match="duplicate OOF fold/seed"): + validate_bank_layout(manifests, expected_banks_per_fold=3) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_fit_phase5_causal_state.py b/home/wuyifan/EgoNet_train_20261008/tests/test_fit_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..ed2caedd667e45f6c1ae4a86270a14f5423b1fa5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_fit_phase5_causal_state.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import pytest + +from scripts.fit_phase5_causal_state import select_candidate + + +def test_causal_state_selection_enforces_static_guardrails() -> None: + baseline = {"absolute_mpjpe_mm": 20.0, "z_mae_mm": 10.0, "z_p95_mm": 30.0} + rows = [ + { + "absolute_mpjpe_mm": 20.3, "z_mae_mm": 10.0, "z_p95_mm": 30.0, + "predicted_acceleration_mm_per_frame2": 0.1, + "acceleration_error_mm_per_frame2": 1.0, + "velocity_error_mm_per_frame": 1.0, + }, + { + "absolute_mpjpe_mm": 20.1, "z_mae_mm": 10.1, "z_p95_mm": 30.1, + "predicted_acceleration_mm_per_frame2": 0.2, + "acceleration_error_mm_per_frame2": 1.0, + "velocity_error_mm_per_frame": 1.0, + }, + ] + + assert select_candidate(rows, baseline) is rows[1] + + +def test_causal_state_selection_fails_closed() -> None: + baseline = {"absolute_mpjpe_mm": 20.0, "z_mae_mm": 10.0, "z_p95_mm": 30.0} + row = { + "absolute_mpjpe_mm": 20.3, "z_mae_mm": 10.3, "z_p95_mm": 30.3, + "predicted_acceleration_mm_per_frame2": 0.1, + "acceleration_error_mm_per_frame2": 1.0, + "velocity_error_mm_per_frame": 1.0, + } + with pytest.raises(ValueError, match="no causal-state candidate"): + select_candidate([row], baseline) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_freeze_phase9_final_deployment.py b/home/wuyifan/EgoNet_train_20261008/tests/test_freeze_phase9_final_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..1ff894dfdb1008a9ca29b11a2cf9a11be96687c9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_freeze_phase9_final_deployment.py @@ -0,0 +1,167 @@ +import json +from pathlib import Path + +import torch +import yaml + +from scripts.freeze_phase9_final_deployment import ( + build_freeze, + checkpoint_contract, + preceding_full_job, +) +from scripts.run_phase9_unified_train_queue import sha256 + + +def artifact(path: Path, value: str) -> tuple[str, str]: + path.write_text(value, encoding="utf-8") + import hashlib + return str(path), hashlib.sha256(path.read_bytes()).hexdigest() + + +def job(tmp_path: Path, name: str = "full") -> dict: + config = { + "experiment": {"branch": "phase9_unified", "official_test_used": False}, + "data": {"resolution_hw": [512, 896]}, + } + config_path = tmp_path / f"{name}.yaml" + config_path.write_text(yaml.safe_dump(config), encoding="utf-8") + checkpoint_path = tmp_path / f"{name}.pt" + torch.save({ + "step": 12, "model": {}, + "extra": { + "config": config, "h2o_training_data_used": True, + "official_test_used": False, + }, + }, checkpoint_path) + import hashlib + digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest() + return { + "checkpoint": str(checkpoint_path), + "checkpoint_sha256": digest(checkpoint_path), + "config": str(config_path), "config_sha256": digest(config_path), + } + + +def test_preceding_job_uses_accepted_shared_augmentation(tmp_path: Path) -> None: + full = job(tmp_path) + stage8 = { + "resolution_hw": [512, 896], "shared_augmentation_accepted": True, + "candidate_training_jobs": {"full": full}, + } + selected, mechanism, augmented, resolution = preceding_full_job(stage8, {}) + assert selected["checkpoint_sha256"] == full["checkpoint_sha256"] + assert mechanism == "shared_augmentation" + assert augmented is True + assert resolution == [512, 896] + + +def test_preceding_job_uses_bound_resolution_control(tmp_path: Path) -> None: + full = job(tmp_path) + evaluation_path = tmp_path / "resolution.json" + evaluation_path.write_text(json.dumps({"training_jobs": {"full": full}}), encoding="utf-8") + import hashlib + stage8 = { + "resolution_hw": [512, 896], "shared_augmentation_accepted": False, + "control": { + "kind": "resolution_896x512_candidate", + "evaluation_plan": { + "path": str(evaluation_path), + "sha256": hashlib.sha256(evaluation_path.read_bytes()).hexdigest(), + }, + }, + } + selected, mechanism, augmented, _ = preceding_full_job(stage8, {}) + assert selected["checkpoint_sha256"] == full["checkpoint_sha256"] + assert mechanism == "resolution" + assert augmented is False + + +def test_final_checkpoint_contract_checks_embedded_config(tmp_path: Path) -> None: + full = job(tmp_path) + assert checkpoint_contract({ + "checkpoint": full["checkpoint"], "config": full["config"], + }, [512, 896]) == 12 + + +def test_build_freeze_follows_complete_selection_chain(tmp_path: Path) -> None: + full = job(tmp_path) + selection_report = tmp_path / "selection.json" + winner_checkpoint = { + "path": full["checkpoint"], "sha256": full["checkpoint_sha256"], + } + winner_config = {"path": full["config"], "sha256": full["config_sha256"]} + selection_payload = { + "status": "complete", "winner": "J55:final", + "winner_checkpoint": winner_checkpoint, "winner_config": winner_config, + "h2o_official_validation_used": False, "official_test_used": False, + } + selection_report.write_text(json.dumps(selection_payload), encoding="utf-8") + required_plan = [] + required_state = [] + for index in range(9): + path = tmp_path / f"required_{index}.json" + path.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + }), encoding="utf-8") + required_plan.append({"id": f"required_{index}", "path": str(path)}) + required_state.append({ + "id": f"required_{index}", "path": str(path), "sha256": sha256(path), + }) + selection_plan = tmp_path / "selection_plan.json" + selection_plan.write_text(json.dumps({ + "output_json": str(selection_report), "required_states": required_plan, + }), encoding="utf-8") + selection_state = tmp_path / "selection_state.json" + selection_state.write_text(json.dumps({ + "status": "complete", "plan_sha256": sha256(selection_plan), + "winner": "J55:final", "winner_checkpoint": winner_checkpoint, + "winner_config": winner_config, + "required_states": required_state, + "h2o_official_validation_used": False, "official_test_used": False, + }), encoding="utf-8") + + stage8_report = tmp_path / "stage8.json" + stage8_report.write_text(json.dumps({ + "status": "complete", "winner": "J55:final", + "resolution_hw": [512, 896], "shared_augmentation_accepted": True, + "candidate_training_jobs": {"full": full}, + "h2o_official_validation_used": False, "official_test_used": False, + }), encoding="utf-8") + stage8_plan = tmp_path / "stage8_plan.json" + stage8_plan.write_text(json.dumps({"decision_report": str(stage8_report)}), encoding="utf-8") + stage8_state = tmp_path / "stage8_state.json" + stage8_state.write_text(json.dumps({ + "status": "complete", "plan_sha256": sha256(stage8_plan), + "decision_report": {"path": str(stage8_report), "sha256": sha256(stage8_report)}, + "h2o_official_validation_used": False, "official_test_used": False, + }), encoding="utf-8") + + last2_report = tmp_path / "last2.json" + last2_report.write_text(json.dumps({ + "status": "complete", "created_utc": "2026-07-30T00:00:00+00:00", + "selected": "preceding_mechanism", + "h2o_official_validation_used": False, "official_test_used": False, + }), encoding="utf-8") + last2_plan = tmp_path / "last2_plan.json" + last2_plan.write_text(json.dumps({"report": str(last2_report)}), encoding="utf-8") + last2_state = tmp_path / "last2_state.json" + last2_state.write_text(json.dumps({ + "status": "complete", "plan_sha256": sha256(last2_plan), + "decision_report": {"path": str(last2_report), "sha256": sha256(last2_report)}, + "h2o_official_validation_used": False, "official_test_used": False, + }), encoding="utf-8") + validation = tmp_path / "official_val.jsonl" + training = tmp_path / "official_train.jsonl" + validation.write_text("{}\n", encoding="utf-8") + training.write_text("{}\n", encoding="utf-8") + freeze = build_freeze( + selection_plan_path=selection_plan, selection_state_path=selection_state, + stage8_plan_path=stage8_plan, stage8_state_path=stage8_state, + last2_plan_path=last2_plan, last2_state_path=last2_state, + validation_manifest=validation, validation_manifest_sha256=sha256(validation), + training_manifest=training, training_manifest_sha256=sha256(training), + ) + assert freeze["selected_mechanism"] == "shared_augmentation" + assert freeze["checkpoint"]["sha256"] == full["checkpoint_sha256"] + assert freeze["selection_complete"] is True + assert freeze["h2o_official_validation_used"] is False diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_from_scratch_mean_pose_config.py b/home/wuyifan/EgoNet_train_20261008/tests/test_from_scratch_mean_pose_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c30002c1cf7dd57c7c8863f0d9d8bc89cbdf58ad --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_from_scratch_mean_pose_config.py @@ -0,0 +1,64 @@ +"""Keep the fresh RGB non-MoT/MoT comparison matched and smoke-only.""" + +import json +from pathlib import Path + + +CONFIG = json.loads((Path(__file__).resolve().parents[1] / "experiments" + / "from_scratch_mean_pose" / "config.json").read_text()) +N0 = json.loads((Path(__file__).resolve().parents[1] / "experiments" + / "u0_normalized6d" / "config.json").read_text()) + + +def test_b0_b1_share_a_teacher_free_fresh_rgb_contract(): + shared = CONFIG["shared"] + assert CONFIG["status"] == "smoke_only_formal_training_unapproved" + assert CONFIG["training_approved"] is False + assert set(CONFIG["arms"]) == {"B0", "B1"} + assert shared["initialization"]["foundation_hand_parent_checkpoint"] is None + assert Path(shared["initialization"]["dinov3_weights"]).name == "dinov3" + assert len(shared["initialization"]["dinov3_model_sha256"]) == 64 + assert shared["teacher"] == { + "create_model": False, "forward": False, + "distillation": False, "rgb_teacher_weight": 0.0, + } + assert shared["input"]["mode"] == "rgb" + assert shared["input"]["frames"] == 8 + assert not shared["input"]["depth_as_input"] + assert not shared["input"]["intrinsics_as_input"] + assert shared["data"]["global_batch"] == sum( + shared["data"]["source_quota_per_update"].values() + ) + assert shared["data"]["source_quota_per_update"] == N0["source_quota_per_update"] + assert shared["loss"] == { + "hard_pose_reweight": False, **N0["loss_coefficients"], "joint2d": 0.0, + } + assert shared["loss"]["reprojection"] == 1.0 + assert shared["precision"]["gt_axis_angle_to_matrix"] == "fp32_autocast_disabled" + assert shared["precision"]["predicted_6d_gram_schmidt"] == "fp32_autocast_disabled" + assert not shared["loss"]["hard_pose_reweight"] + assert all(shared["optimizer"][key] is None for key in ( + "maximum_updates", "warmup_updates", "learning_rates_by_stage", + "dino_freeze_unfreeze_updates", + )) + + +def test_mean_pose_delta_is_shared_and_architecture_is_the_only_arm_difference(): + shared = CONFIG["shared"] + pose = shared["pose"] + b0, b1 = CONFIG["arms"]["B0"], CONFIG["arms"]["B1"] + assert pose["local_pose_parameterization"] == "right_mean_pose_delta_rotation_6d" + assert pose["root_orientation_parameterization"] == "direct_camera_rotation_6d" + assert pose["delta_gt"] == "transpose(R_mean) @ R_gt" + assert pose["final_local_rotation"] == "R_mean @ R_delta_pred" + assert pose["mean_rotation"]["joints_per_side"] == 15 + assert pose["mean_rotation"]["fixed_buffer"] + assert pose["mean_rotation"]["source"] == "official_mano_left_and_right_pkl_hands_mean" + assert pose["mean_rotation"]["mano_geometry_layer_remains_flat_hand_mean"] + assert shared["normalization"]["source_weighting"] == "source_quota_per_update" + assert shared["normalization"]["statistics_asset"] == "statistics_mano_pkl_v2.json" + assert set(shared["initialization"]["mano_pkl_sha256"]) == {"left", "right"} + assert b0["architecture"] == "non_mot" + assert b1["architecture"] == "mot" + assert set(b0) - {"architecture", "spatial_decoder", "spatial_attention", "rgb_patch_tokens_updated_by_decoder"} == set() + assert set(b1) - {"architecture", "spatial_decoder", "spatial_attention", "rgb_patch_tokens_updated_by_decoder", "terminal_unused_rgb_output_path"} == set() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_from_scratch_mean_pose_runtime.py b/home/wuyifan/EgoNet_train_20261008/tests/test_from_scratch_mean_pose_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..d9c9c3ac225b38c4493d86f37250620df519aea5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_from_scratch_mean_pose_runtime.py @@ -0,0 +1,137 @@ +"""Exercise the new B0/B1 target path, not the historical N0/N1 trainer.""" + +from experiments.from_scratch_mean_pose.loss import FromScratchLoss, TERMS +from experiments.from_scratch_mean_pose.model import MeanDeltaRotationHead +from experiments.from_scratch_mean_pose.fit_targets import mano_pkl_mean +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from pathlib import Path +import torch +from torch import nn + + +def statistics(mean): + return { + "mean_local": mean.tolist(), "xyz_center": [0.0] * 3, "xyz_scale": 0.1, + "beta_center": [0.0] * 10, "beta_scale": [1.0] * 10, + "pose_center": torch.zeros(2, 16, 6).tolist(), + "pose_scale": torch.ones(2, 16, 6).tolist(), + } + + +def test_experiment_uses_this_repository_source(): + from foundation_hand.data import arctic_dataset + from pathlib import Path + + root = Path(__file__).resolve().parents[1] + assert Path(arctic_dataset.__file__).resolve().is_relative_to(root / "src") + + +def test_local_mean_comes_from_both_mano_pkl_files_not_flat_geometry_buffers(): + from manopth.manolayer import ManoLayer + + enable_legacy_mano_loading() + root = Path("/SSD3/jiasen/foundation_hand/pretrained/mano") + mean, hashes = mano_pkl_mean(root) + assert mean.shape == (2, 15, 3, 3) + assert set(hashes) == {"left", "right"} + assert not torch.allclose(torch.as_tensor(mean), torch.eye(3, dtype=torch.float64)) + for index, side in enumerate(("left", "right")): + flat = ManoLayer(mano_root=str(root), side=side, use_pca=False, flat_hand_mean=True) + native = flat.smpl_data["hands_mean"].reshape(15, 3) + assert torch.count_nonzero(flat.th_hands_mean) == 0 + assert torch.allclose(torch.as_tensor(mean[index]), + axis_angle_to_matrix(torch.as_tensor(native, dtype=torch.float64)), atol=1e-7) + + +def test_delta_head_starts_at_mean_and_only_has_the_original_rotation_linear(): + local_axis = torch.randn(2, 15, 3) * 0.3 + mean = axis_angle_to_matrix(local_axis) + linear = nn.Linear(8, 16 * 6) + with torch.no_grad(): + linear.weight.zero_() + linear.bias.copy_(torch.tensor([1., 0., 0., 0., 1., 0.]).repeat(16)) + head = MeanDeltaRotationHead(linear, mean) + result = head(torch.randn(1, 8, 2, 8)) + rotations = rotation_6d_to_matrix(result) + assert torch.allclose(rotations[..., 1:, :, :], mean[None, None], atol=2e-6) + assert torch.allclose(rotations[..., 0, :, :], torch.eye(3), atol=2e-6) + assert list(name for name, _ in head.named_parameters()) == ["linear.weight", "linear.bias"] + assert "mean_local" in dict(head.named_buffers()) + + +def test_fp32_delta_six_component_target_and_masks_under_bf16_autocast(): + torch.manual_seed(7) + mean_axis = torch.randn(2, 15, 3) * 0.2 + mean = axis_angle_to_matrix(mean_axis) + linear = nn.Linear(8, 16 * 6) + with torch.no_grad(): + linear.weight.zero_() + linear.bias.copy_(torch.tensor([1., 0., 0., 0., 1., 0.]).repeat(16)) + head = MeanDeltaRotationHead(linear, mean) + criterion = FromScratchLoss(statistics(mean), {key: 1.0 for key in TERMS}, { + "reprojection_depth_floor_m": 0.05, "reprojection_depth_penalty_per_m": 10.0, + }) + batch = {"mano_pose": torch.cat((torch.zeros(1, 8, 2, 1, 3), + mean_axis[None, None].expand(1, 8, -1, -1, -1)), dim=-2).reshape(1, 8, 2, 48)} + prediction = {"mano_rotations_6d": head(torch.randn(1, 8, 2, 8))} + valid = torch.ones(1, 8, 2, dtype=torch.bool) + with torch.autocast("cpu", dtype=torch.bfloat16): + root, local, target, predicted = criterion.pose_6d(prediction, batch, valid, valid) + assert float(root) < 1e-6 + assert float(local) < 1e-6 + assert target.dtype == predicted.dtype == torch.float32 + assert float((target.transpose(-1, -2) @ target - torch.eye(3)).abs().max()) < 1e-6 + assert float((predicted.transpose(-1, -2) @ predicted - torch.eye(3)).abs().max()) < 1e-6 + + bad = torch.ones_like(prediction["mano_rotations_6d"]) + bad[..., 1:, :] = torch.tensor([1., 0., 0., 0., 1., 0.]) + prediction["mano_rotations_6d"] = bad + empty = torch.zeros_like(valid) + root, local, _, _ = criterion.pose_6d(prediction, batch, empty, empty) + assert float(root) == float(local) == 0.0 + + +def test_reprojection_only_does_not_train_the_direct_2d_head(): + mean = torch.eye(3).repeat(2, 15, 1, 1) + coefficients = {key: 0.0 for key in TERMS} + coefficients["reprojection"] = 1.0 + criterion = FromScratchLoss(statistics(mean), coefficients, { + "reprojection_depth_floor_m": 0.05, "reprojection_depth_penalty_per_m": 10.0, + }) + direct_2d = torch.full((1, 3, 2, 21, 2), 0.5, requires_grad=True) + joints = torch.zeros(1, 3, 2, 21, 3) + joints[..., 0] = 0.1 + joints[..., 2] = 1.0 + joints.requires_grad_() + prediction = { + "joint2d_norm": direct_2d, + "joints_camera": joints, + "mano_rotations_6d": torch.tensor([1., 0., 0., 0., 1., 0.]).repeat(1, 3, 2, 16, 1), + "mano_shape_sequence": torch.zeros(1, 2, 10), + "wrist_root_translation": torch.zeros(1, 3, 2, 3), + "vertices_camera": torch.zeros(1, 3, 2, 1, 3), + } + batch = { + "frame_valid": torch.ones(1, 3, dtype=torch.bool), + "joint_annotation_valid": torch.ones(1, 3, 2, dtype=torch.bool), + "mano_annotation_valid": torch.ones(1, 3, 2, dtype=torch.bool), + "joint_element_valid": torch.ones(1, 3, 2, 21, dtype=torch.bool), + "image_hw": torch.tensor([[100, 100]]), + "joint2d": torch.zeros(1, 3, 2, 21, 2), + "joint2d_valid": torch.ones(1, 3, 2, 21, dtype=torch.bool), + "joint3d_camera": torch.zeros_like(joints), + "wrist_root_translation": torch.zeros(1, 3, 2, 3), + "mano_pose": torch.zeros(1, 3, 2, 48), + "mano_shape": torch.zeros(1, 3, 2, 10), + "vertices_camera": torch.zeros(1, 3, 2, 1, 3), + "K": torch.eye(3).repeat(1, 3, 1, 1), + "K_supervision_valid": torch.ones(1, 3, dtype=torch.bool), + "reprojection_valid": torch.ones(1, 3, 2, 21, dtype=torch.bool), + } + total, weighted, _ = criterion(prediction, batch) + assert weighted["joint2d"].item() == 0.0 + assert weighted["reprojection"].item() > 0.0 + total.backward() + assert direct_2d.grad is None + assert joints.grad is not None and joints.grad.abs().sum() > 0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_generate_phase4_a3_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_generate_phase4_a3_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..93c7cb214c90883225f188d7aba37adbc2c9ebd7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_generate_phase4_a3_configs.py @@ -0,0 +1,61 @@ +import csv + +from scripts.generate_phase4_a3_configs import build_config, write_config_matrices + + +def base(): + return { + "name": "reference_s20260716", "seed": 20260716, + "experiment": {"phase": 3}, + "data": {"resolution_hw": [368, 640], "T": 8, "stride": 1}, + "model": {"decoder_mode": "alternating", "use_temporal": True}, + "loss": {"translation": 10.0}, + "assets": {}, "precision": "bf16", "protocol": {}, + } + + +def checkpoint(): + return {"path": "/checkpoint.pt", "sha256": "a" * 64, "step": 135000} + + +def test_a3_depth_config_changes_only_registered_oracle_structure(): + result = build_config(base(), "depth_k", "health25k", checkpoint()) + + assert result["model"]["oracle_crop_mode"] == "oracle_depth_k" + assert result["model"]["freeze_coarse_for_oracle_crop"] is True + assert result["loss"] == {"translation": 10.0} + assert result["sampling"] == {"mode": "uniform"} + assert result["protocol"]["max_steps"] == 25000 + assert result["protocol"]["validation_subset_manifest"].endswith( + "resolution_640x368/validation_subset_256.json" + ) + assert result["experiment"]["coarse_checkpoint_sha256"] == "a" * 64 + assert result["experiment"]["gt_location_at_train_and_validation"] is True + assert result["experiment"]["deployable_inference"] is False + assert result["experiment"]["official_test_used"] is False + + +def test_a3_tiny_config_does_not_claim_fixed_validation_subset(): + result = build_config(base(), "rgb", "tiny2k", checkpoint()) + + assert result["protocol"]["max_steps"] == 2000 + assert result["protocol"]["warmup_steps"] == 100 + assert "validation_subset_manifest" not in result["protocol"] + + +def test_a3_formal_matrix_excludes_engineering_stages(tmp_path): + rows = [ + {"name": "tiny", "stage": "tiny", "official_test_used": False}, + {"name": "health", "stage": "health", "official_test_used": False}, + {"name": "formal", "stage": "formal", "official_test_used": False}, + ] + matrix_path = tmp_path / "all.csv" + formal_path = tmp_path / "formal.csv" + + formal_rows = write_config_matrices(rows, matrix_path, formal_path) + + assert formal_rows == [rows[-1]] + with formal_path.open(newline="", encoding="utf-8") as handle: + assert list(csv.DictReader(handle)) == [ + {"name": "formal", "stage": "formal", "official_test_used": "False"} + ] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_gkdt_feature_probe.py b/home/wuyifan/EgoNet_train_20261008/tests/test_gkdt_feature_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..abd668686e1ad74c7b756a7b28e9414bcddeafd7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_gkdt_feature_probe.py @@ -0,0 +1,78 @@ +import torch +from torch import nn + +from experiments.dinov3_2d_pretrain.gkdt_probe import ( + compatible_resume_contract, head_state, load_head, sample_mean_loss, +) +from experiments.dinov3_2d_pretrain.loss import KeypointPretrainLoss, UNREVIEWED +from experiments.dinov3_2d_pretrain.model import DinoKeypointPretrainer +from foundation_hand.models.encoders import PatchFeatures + + +class FakeFrozenEncoder(nn.Module): + trainable_last_blocks = 0 + + def __init__(self): + super().__init__() + self.backbone = nn.Linear(3, 3) + self.backbone.requires_grad_(False) + self.projection = nn.Linear(3, 8) + + def forward(self, images): + return PatchFeatures(self.projection(images.mean((-2, -1))).unsqueeze(1), (1, 1), 16) + + +def make_probe(): + return DinoKeypointPretrainer("unused", "unused", image_hw=(16, 16), width=8, + bin_pixels=4, layers=1, encoder=FakeFrozenEncoder()) + + +def test_gkdt_probe_keeps_backbone_frozen_and_restores_all_head_parameters(): + torch.manual_seed(1) + source = make_probe() + source.set_auxiliary_tuning(False) + assert not any(parameter.requires_grad for parameter in source.encoder.backbone.parameters()) + with torch.no_grad(): + source.encoder.projection.weight.fill_(2) + source.query.fill_(3) + saved = head_state(source) + assert "encoder.projection.weight" in saved + assert "encoder.backbone.weight" not in saved + target = make_probe() + load_head(target, saved) + assert torch.equal(target.encoder.projection.weight, source.encoder.projection.weight) + assert torch.equal(target.query, source.query) + assert target(torch.zeros(1, 3, 16, 16))["infer_x"].shape == (1, 2, 21, 4) + + +def test_microbatch_loss_and_gradient_match_serial_samples(): + torch.manual_seed(2) + uv = torch.tensor([[[[2., 3.]] * 21] * 2, [[[6., 7.]] * 21] * 2]) + valid = torch.ones(2, 2, 21, dtype=torch.bool) + valid[1, 0, 2:] = False + states = torch.full(valid.shape, UNREVIEWED) + criterion = KeypointPretrainLoss((16, 16), visible_weight=0, visibility_weight=0) + base = {name: torch.randn(2, 2, 21, width) + for name, width in (("infer_x", 4), ("infer_y", 4), + ("visible_x", 4), ("visible_y", 4), ("visibility", 3))} + batched = {key: value.clone().requires_grad_() for key, value in base.items()} + serial = {key: value.clone().requires_grad_() for key, value in base.items()} + batch_loss = sample_mean_loss(criterion, batched, uv, valid, states) + serial_loss = torch.stack([ + criterion({key: value[index:index + 1] for key, value in serial.items()}, + uv[index:index + 1], valid[index:index + 1], + states[index:index + 1])[0] for index in range(2) + ]).mean() + batch_loss.backward() + serial_loss.backward() + assert torch.allclose(batch_loss, serial_loss) + for key in base: + if batched[key].grad is not None: + assert torch.allclose(batched[key].grad, serial[key].grad) + + +def test_resume_allows_only_microbatch_change(): + old = {"backbone_sha256": "a", "global_batch": 24, "head_lr": 1e-4} + new = {**old, "micro_batch": 8} + assert compatible_resume_contract(old, new) + assert not compatible_resume_contract(old, {**new, "global_batch": 12}) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_h2o_fields.py b/home/wuyifan/EgoNet_train_20261008/tests/test_h2o_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..3e1c23d14c0c5bde7e4559c2f184813fec86df99 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_h2o_fields.py @@ -0,0 +1,39 @@ +import numpy as np +import pytest + +from foundation_hand.data.h2o_fields import parse_joint_record, parse_mano_record + + +def test_joint_record_indices_and_shapes() -> None: + values = np.arange(128, dtype=np.float64) + values[0] = 1 + values[64] = 0 + record = parse_joint_record(values) + assert record.annotation_valid.tolist() == [True, False] + assert record.joints_camera_m.shape == (2, 21, 3) + np.testing.assert_array_equal(record.joints_camera_m[0, 0], values[1:4]) + np.testing.assert_array_equal(record.joints_camera_m[1, 0], values[65:68]) + + +def test_mano_record_indices_and_shapes() -> None: + values = np.arange(124, dtype=np.float64) + values[0] = 0 + values[62] = 1 + record = parse_mano_record(values) + assert record.annotation_valid.tolist() == [False, True] + assert record.translation_raw_m.shape == (2, 3) + assert record.pose_axis_angle.shape == (2, 48) + assert record.shape.shape == (2, 10) + np.testing.assert_array_equal(record.translation_raw_m[0], values[1:4]) + np.testing.assert_array_equal(record.pose_axis_angle[0], values[4:52]) + np.testing.assert_array_equal(record.shape[0], values[52:62]) + np.testing.assert_array_equal(record.translation_raw_m[1], values[63:66]) + np.testing.assert_array_equal(record.pose_axis_angle[1], values[66:114]) + np.testing.assert_array_equal(record.shape[1], values[114:124]) + + +@pytest.mark.parametrize("length", [0, 59, 118, 123, 125]) +def test_mano_record_rejects_unofficial_lengths(length: int) -> None: + with pytest.raises(ValueError): + parse_mano_record(np.zeros(length)) + diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_harm_risk_features.py b/home/wuyifan/EgoNet_train_20261008/tests/test_harm_risk_features.py new file mode 100644 index 0000000000000000000000000000000000000000..2433cf078749961aff085ac4fb9cc28acb8aa504 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_harm_risk_features.py @@ -0,0 +1,30 @@ +import numpy as np + +from foundation_hand.evaluation.harm_risk import ( + HARM_RISK_FEATURE_NAMES, + harm_risk_features, +) + + +def test_harm_risk_feature_contract_is_predicted_only_and_finite() -> None: + time = 3 + hand = (time, 2) + features = harm_risk_features( + calibrated_delta_z_m=np.full(hand, 0.01), + raw_delta_z_m=np.full(hand, 0.02), confidence=np.full(hand, 0.7), + alignment_available=np.ones(hand, dtype=bool), + raw_alignment_available=np.ones(hand, dtype=bool), + valid_support_count=np.full(hand, 100), projected_support_count=np.full(hand, 120), + inlier_ratio=np.full(hand, 0.8), residual_scale_m=np.full(hand, 0.005), + valid_fraction=np.full(hand, 0.6), foreground_fraction=np.full(hand, 0.1), + background_fraction=np.full(hand, 0.2), depth_discontinuity_m=np.full(hand, 0.01), + conditioning_quality=np.full(hand, 0.9), silhouette_overlap_fraction=np.zeros(time), + coarse_hand_scale_px=np.full(hand, 80), + coarse_direct_mano_consistency_px=np.full(hand, 5), + coarse_wrist_translation=np.dstack((np.zeros(hand), np.zeros(hand), np.ones(hand))), + coarse_wrist_velocity_m_per_frame=np.zeros((time, 2, 3)), + predicted_depth_order=np.ones(time), + ) + assert features.shape == (time, 2, len(HARM_RISK_FEATURE_NAMES)) + assert np.isfinite(features).all() + assert features[0, 0, -1] == 0 and features[0, 1, -1] == 1 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_hot3d_supervision_masks.py b/home/wuyifan/EgoNet_train_20261008/tests/test_hot3d_supervision_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..78e1e20c79e447348dc12d5a5aea09852d83562f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_hot3d_supervision_masks.py @@ -0,0 +1,89 @@ +import torch + +from foundation_hand.data.hot3d_dataset import ( + hot3d_supervision_masks, + quest_linear_camera_calibration, +) + + +def test_visible_mesh_keeps_full_3d_but_masks_offscreen_2d() -> None: + K = torch.tensor([[[100.0, 0.0, 50.0], [0.0, 100.0, 50.0], [0.0, 0.0, 1.0]]]) + source_vertices = torch.tensor([[ + [[0.0, 0.0, 1.0], [1.0, 0.0, 1.0]], + [[2.0, 0.0, 1.0], [3.0, 0.0, 1.0]], + ]]) + joint2d = torch.full((1, 2, 21, 2), 50.0) + joint2d[0, 0, 1] = torch.tensor([150.0, 50.0]) + joint2d[0, 0, 3] = torch.tensor([8_000_000.0, 50.0]) + errors = torch.zeros((1, 2, 21)) + errors[0, 0, 2] = 3.0 + errors[0, 0, 4] = float("nan") + + hand, joint2d_mask, joint3d_mask = hot3d_supervision_masks( + torch.ones((1, 2), dtype=torch.bool), source_vertices, joint2d, + torch.ones((1, 2, 21), dtype=torch.bool), errors, K, (100, 100), + ) + + assert hand.tolist() == [[True, False]] + assert joint2d_mask[0, 0, :5].tolist() == [True, False, False, False, False] + assert not joint2d_mask[0, 1].any() + assert joint3d_mask[0, 0].all() + assert not joint3d_mask[0, 1].any() + + +def test_missing_geometry_remains_invalid_even_when_mesh_projects_inside() -> None: + K = torch.eye(3).unsqueeze(0) + source_vertices = torch.tensor([[[[0.0, 0.0, 1.0]], [[0.0, 0.0, 1.0]]]]) + joint2d = torch.zeros((1, 2, 21, 2)) + errors = torch.zeros((1, 2, 21)) + + hand, joint2d_mask, joint3d_mask = hot3d_supervision_masks( + torch.tensor([[False, True]]), source_vertices, joint2d, + torch.ones((1, 2, 21), dtype=torch.bool), errors, K, (100, 100), + ) + + assert hand.tolist() == [[False, True]] + assert not joint2d_mask[0, 0].any() + assert not joint3d_mask[0, 0].any() + assert joint2d_mask[0, 1].all() + assert joint3d_mask[0, 1].all() + + +def test_temporal_masks_are_independent_per_frame_and_hand() -> None: + K = torch.eye(3).repeat(8, 1, 1) + source_vertices = torch.tensor([[[[0.0, 0.0, 1.0]], [[2.0, 0.0, 1.0]]]]).repeat(8, 1, 1, 1) + source_vertices[1, 0, 0, 0] = 2.0 + source_vertices[1, 1, 0, 0] = 0.0 + joint2d = torch.zeros((8, 2, 21, 2)) + errors = torch.zeros((8, 2, 21)) + + hand, joint2d_mask, joint3d_mask = hot3d_supervision_masks( + torch.ones((8, 2), dtype=torch.bool), source_vertices, joint2d, + torch.ones((8, 2, 21), dtype=torch.bool), errors, K, (1, 1), + ) + + assert hand[0].tolist() == [True, False] + assert hand[1].tolist() == [False, True] + assert hand[2:].tolist() == [[True, False]] * 6 + assert torch.equal(joint2d_mask, joint3d_mask) + + +def test_quest_rectification_preserves_native_camera_extrinsic() -> None: + linear_model, native_model = object(), object() + native_transform, identity_transform = object(), object() + linear_calibration, native_calibration = object(), object() + + class Device: + def get_camera_calibration(self, stream_id, camera_model): + assert stream_id == "camera" + if camera_model is native_model: + return native_transform, native_calibration + if camera_model is linear_model: + return identity_transform, linear_calibration + raise AssertionError("unexpected calibration model") + + transform, calibration = quest_linear_camera_calibration( + Device(), "camera", linear_model, native_model, + ) + assert transform is native_transform + assert calibration is linear_calibration diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_losses.py b/home/wuyifan/EgoNet_train_20261008/tests/test_losses.py new file mode 100644 index 0000000000000000000000000000000000000000..617a8e3753e8de1b6790ba5962d2413d4241131a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_losses.py @@ -0,0 +1,99 @@ +import torch + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.losses import masked_l1 +from test_model import synthetic_batch + + +def test_annotation_invalid_nan_targets_do_not_leak(): + model = BimanualReconstructionModel(ModelConfig(encoder="tiny_debug", decoder_dim=64, decoder_layers=1, attention_heads=4)) + batch = synthetic_batch(time=2) + batch["joint_annotation_valid"][:, :, 0] = False + batch["mano_annotation_valid"][:, :, 0] = False + batch["joint_element_valid"][:, :, 0] = False + for key in ("joint2d", "joint3d_camera", "wrist_root_translation", "mano_pose", "mano_shape"): + batch[key][:, :, 0] = torch.nan + losses = BimanualLoss(LossConfig())(model(batch), batch) + assert all(torch.isfinite(value) for value in losses.values()) + + +def test_presence_loss_is_disabled_without_reliable_labels(): + model = BimanualReconstructionModel(ModelConfig(encoder="tiny_debug", decoder_dim=64, decoder_layers=1, attention_heads=4)) + batch = synthetic_batch(time=2) + losses = BimanualLoss(LossConfig(presence=0.0))(model(batch), batch) + assert losses["presence"].item() == 0.0 + + +def translation_inputs() -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]: + prediction = { + "wrist_root_translation": torch.tensor( + [[[[0.02, -0.02, 0.54], [0.02, -0.02, 0.54]]]], + requires_grad=True, + ), + } + batch = { + "frame_valid": torch.ones(1, 1, dtype=torch.bool), + "joint_annotation_valid": torch.ones(1, 1, 2, dtype=torch.bool), + "wrist_root_translation": torch.tensor( + [[[[0.0, 0.0, 0.50], [0.0, 0.0, 0.50]]]], + ), + } + return prediction, batch + + +def test_default_translation_loss_preserves_legacy_l1_exactly() -> None: + prediction, batch = translation_inputs() + criterion = BimanualLoss(LossConfig()) + mask = batch["joint_annotation_valid"] & batch["frame_valid"][..., None] + expected = masked_l1( + prediction["wrist_root_translation"], batch["wrist_root_translation"], mask[..., None], + ) + actual = criterion._translation_loss( + prediction["wrist_root_translation"], batch["wrist_root_translation"], mask, + ) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + +def test_axis_huber_preserves_mean_weight_and_emphasizes_z_gradient() -> None: + prediction, batch = translation_inputs() + criterion = BimanualLoss(LossConfig( + translation_mode="axis_huber", + translation_axis_weights=(0.5, 0.5, 2.0), + translation_huber_beta_m=0.01, + )) + mask = batch["joint_annotation_valid"] & batch["frame_valid"][..., None] + loss = criterion._translation_loss( + prediction["wrist_root_translation"], batch["wrist_root_translation"], mask, + ) + loss.backward() + gradient = prediction["wrist_root_translation"].grad.abs().mean(dim=(0, 1, 2)) + torch.testing.assert_close(gradient[2] / gradient[0], torch.tensor(4.0)) + diagnostics = criterion.translation_diagnostics(prediction, batch) + assert diagnostics["translation_z_effective_loss_contribution"] > diagnostics[ + "translation_x_effective_loss_contribution" + ] + + +def test_axis_huber_invalid_target_is_masked_without_leakage() -> None: + prediction, batch = translation_inputs() + batch["joint_annotation_valid"][..., 0] = False + batch["wrist_root_translation"][..., 0, :] = torch.nan + criterion = BimanualLoss(LossConfig( + translation_mode="axis_huber", + translation_axis_weights=(0.5, 0.5, 2.0), + )) + mask = batch["joint_annotation_valid"] & batch["frame_valid"][..., None] + loss = criterion._translation_loss( + prediction["wrist_root_translation"], batch["wrist_root_translation"], mask, + ) + assert torch.isfinite(loss) + + +def test_invalid_axis_loss_configuration_is_rejected() -> None: + try: + LossConfig(translation_mode="unknown") + except ValueError as error: + assert "unsupported translation mode" in str(error) + else: + raise AssertionError("invalid translation mode was accepted") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_mano_translation.py b/home/wuyifan/EgoNet_train_20261008/tests/test_mano_translation.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf896b502ce17fa08943acf5d6ec69f9143bf2b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_mano_translation.py @@ -0,0 +1,22 @@ +import numpy as np +import torch + +from foundation_hand.geometry.mano_translation import mano_raw_to_wrist, wrist_to_mano_raw + + +def test_numpy_translation_round_trip() -> None: + raw = np.array([[0.1, 0.2, 0.7], [-0.1, 0.0, 0.8]], dtype=np.float32) + root = np.array([[0.095, 0.005, -0.002], [-0.094, 0.004, 0.003]], dtype=np.float32) + wrist = mano_raw_to_wrist(raw, root) + np.testing.assert_allclose(wrist_to_mano_raw(wrist, root), raw, atol=1e-7) + + +def test_torch_translation_round_trip_and_gradient() -> None: + raw = torch.randn(4, 2, 3, requires_grad=True) + root = torch.randn(4, 2, 3) + wrist = mano_raw_to_wrist(raw, root) + recovered = wrist_to_mano_raw(wrist, root) + torch.testing.assert_close(recovered, raw) + recovered.sum().backward() + torch.testing.assert_close(raw.grad, torch.ones_like(raw)) + diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_metric_alignment.py b/home/wuyifan/EgoNet_train_20261008/tests/test_metric_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..c912480ebbb6109e5584cd0eb521f99210f62b11 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_metric_alignment.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +import numpy as np + +from foundation_hand.evaluation.metric_alignment import ( + _sample_depth_regions, + SurfaceSamples, + align_wrist_z, + apply_translation_delta_z, + robust_location_irls, + solve_wrist_delta_z, +) + + +def brute_depth_regions( + depth: np.ndarray, valid: np.ndarray, pixels: np.ndarray, radius: int, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + height, width = depth.shape + observed = np.full(len(pixels), np.nan, dtype=np.float32) + available = np.zeros(len(pixels), dtype=bool) + discontinuity = np.full(len(pixels), np.nan, dtype=np.float32) + for index, (u, v) in enumerate(pixels): + if not np.isfinite((u, v)).all(): + continue + x, y = int(round(float(u))), int(round(float(v))) + x0, x1 = max(0, x - radius), min(width, x + radius + 1) + y0, y1 = max(0, y - radius), min(height, y + radius + 1) + values = depth[y0:y1, x0:x1][valid[y0:y1, x0:x1]] + values = values[np.isfinite(values) & (values > 0.0)] + if values.size: + q10, q50, q90 = np.percentile(values, (10, 50, 90)) + observed[index] = q50 + discontinuity[index] = q90 - q10 + available[index] = True + return observed, available, discontinuity + + +def test_vectorized_depth_regions_match_brute_reference() -> None: + rng = np.random.default_rng(7) + depth = rng.uniform(0.2, 1.2, size=(17, 23)).astype(np.float32) + valid = rng.random(depth.shape) > 0.3 + depth[2, 3] = np.nan + pixels = rng.uniform((-3.0, -3.0), (26.0, 20.0), size=(200, 2)).astype(np.float32) + pixels[0] = np.nan + + expected = brute_depth_regions(depth, valid, pixels, radius=2) + actual = _sample_depth_regions(depth, valid, pixels, radius=2) + + np.testing.assert_allclose(actual[0], expected[0], rtol=0.0, atol=0.0, equal_nan=True) + np.testing.assert_array_equal(actual[1], expected[1]) + np.testing.assert_allclose(actual[2], expected[2], rtol=0.0, atol=0.0, equal_nan=True) + + +def test_robust_location_irls_rejects_large_outliers() -> None: + residuals = np.r_[np.full(80, 0.04), np.full(20, -0.12)] + delta, scale, inlier_ratio = robust_location_irls(residuals) + + assert abs(delta - 0.04) < 0.003 + assert scale >= 0.003 + assert inlier_ratio >= 0.79 + + +def test_predicted_surface_alignment_recovers_metric_z_shift() -> None: + grid_x, grid_y = np.meshgrid(np.linspace(-0.04, 0.04, 10), np.linspace(-0.04, 0.04, 10)) + vertices = np.stack((grid_x.ravel(), grid_y.ravel(), np.ones(100)), axis=-1).astype(np.float32) + K = np.asarray([[300.0, 0.0, 64.0], [0.0, 300.0, 64.0], [0.0, 0.0, 1.0]], dtype=np.float32) + depth = np.full((128, 128), 1.04, dtype=np.float32) + valid = np.ones_like(depth, dtype=bool) + + diagnostics, samples = align_wrist_z(vertices, K, depth, valid, minimum_support=15) + + assert samples is not None + assert diagnostics.applied + assert diagnostics.valid_support_count >= 15 + assert abs(diagnostics.delta_z_m - 0.04) < 1e-3 + assert diagnostics.conditioning_quality > 0.5 + + +def test_alignment_falls_back_when_depth_or_support_is_missing() -> None: + vertices = np.asarray([[0.0, 0.0, 1.0]], dtype=np.float32) + K = np.eye(3, dtype=np.float32) + diagnostics, samples = align_wrist_z(vertices, K, None, None) + assert not diagnostics.applied + assert diagnostics.delta_z_m == 0.0 + assert samples is None + + sparse = SurfaceSamples( + projected_vertices_px=np.zeros((3, 2), dtype=np.float32), + predicted_depth_m=np.ones(3, dtype=np.float32), + observed_depth_m=np.full(3, 1.02, dtype=np.float32), + visible_vertex=np.ones(3, dtype=bool), + sample_valid=np.ones(3, dtype=bool), + local_discontinuity_m=np.zeros(3, dtype=np.float32), + silhouette_packed=np.zeros(1, dtype=np.uint8), + silhouette_hw=(1, 1), + ) + diagnostics = solve_wrist_delta_z(sparse, minimum_support=4) + assert not diagnostics.applied + assert diagnostics.delta_z_m == 0.0 + + +def test_translation_only_delta_preserves_root_relative_geometry() -> None: + translation = np.asarray([0.1, 0.2, 0.7], dtype=np.float32) + joints = np.asarray([[0.1, 0.2, 0.7], [0.2, 0.3, 0.8]], dtype=np.float32) + vertices = np.asarray([[0.1, 0.2, 0.7], [0.0, 0.3, 0.75]], dtype=np.float32) + + refined_translation, refined_joints, refined_vertices = apply_translation_delta_z( + translation, joints, vertices, 0.04, + ) + + np.testing.assert_allclose(refined_joints - refined_translation, joints - translation) + np.testing.assert_allclose(refined_vertices - refined_translation, vertices - translation) + assert abs(float(refined_translation[2]) - 0.74) < 1e-6 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/tests/test_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a0934911dea4e087bb9db40ec570baaad3d186 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_mixed_projection.py @@ -0,0 +1,104 @@ +import numpy as np +import pytest + +from foundation_hand.evaluation.mixed_projection import ( + coarse_wrist_ray_translation, + direct_wrist_ray_translation, + solve_mixed_projection_batch, +) + + +def synthetic_case(K: np.ndarray | None = None): + if K is None: + K = np.asarray([[600.0, 0.0, 320.0], [0.0, 580.0, 184.0], [0.0, 0.0, 1.0]]) + x = np.linspace(-0.04, 0.04, 21) + y = 0.025 * np.sin(np.linspace(0.0, np.pi * 2.0, 21)) + z = np.linspace(-0.015, 0.025, 21) + joints = np.stack((x, y, z), axis=-1) + translation = np.asarray([0.035, -0.018, 0.55]) + camera = joints + translation + anchors = np.stack(( + K[0, 0] * camera[:, 0] / camera[:, 2] + K[0, 2], + K[1, 1] * camera[:, 1] / camera[:, 2] + K[1, 2], + ), axis=-1) + return joints, anchors, K, translation + + +@pytest.mark.parametrize("robust_delta", [None, 4.0]) +def test_mixed_projection_recovers_exact_translation(robust_delta): + joints, anchors, K, translation = synthetic_case() + result = solve_mixed_projection_batch( + joints[None], anchors[None], K[None], np.asarray([translation[2]]), + np.zeros((1, 3)), image_hw=(368, 640), minimum_support=8, + robust_huber_delta_px=robust_delta, + ) + np.testing.assert_allclose(result.translation_m[0], translation, atol=1e-10) + assert result.support_count[0] == 21 + assert result.failure_reason[0] == "ok" + + +def test_robust_mixed_projection_rejects_large_anchor_outlier(): + joints, anchors, K, translation = synthetic_case() + corrupted = anchors.copy() + corrupted[10] += np.asarray([140.0, -110.0]) + wls = solve_mixed_projection_batch( + joints[None], corrupted[None], K[None], np.asarray([translation[2]]), + np.zeros((1, 3)), image_hw=(368, 640), minimum_support=8, + ) + robust = solve_mixed_projection_batch( + joints[None], corrupted[None], K[None], np.asarray([translation[2]]), + np.zeros((1, 3)), image_hw=(368, 640), minimum_support=8, + robust_huber_delta_px=4.0, + ) + wls_error = np.linalg.norm(wls.translation_m[0, :2] - translation[:2]) + robust_error = np.linalg.norm(robust.translation_m[0, :2] - translation[:2]) + assert robust_error < 0.1 * wls_error + assert robust.inlier_ratio[0] < 1.0 + + +def test_mixed_projection_empty_mask_uses_fallback(): + joints, anchors, K, translation = synthetic_case() + anchors[:] = -100.0 + fallback = np.asarray([[0.1, 0.2, translation[2]]]) + result = solve_mixed_projection_batch( + joints[None], anchors[None], K[None], np.asarray([translation[2]]), + fallback, image_hw=(368, 640), minimum_support=4, + ) + np.testing.assert_array_equal(result.translation_m, fallback) + assert result.support_count[0] == 0 + assert result.failure_reason[0] == "insufficient_support" + + +def test_mixed_projection_supports_different_intrinsics(): + cases = [ + synthetic_case(np.asarray([[450.0, 0.0, 300.0], [0.0, 470.0, 170.0], [0.0, 0.0, 1.0]])), + synthetic_case(np.asarray([[900.0, 0.0, 330.0], [0.0, 850.0, 190.0], [0.0, 0.0, 1.0]])), + ] + result = solve_mixed_projection_batch( + np.stack([case[0] for case in cases]), + np.stack([case[1] for case in cases]), + np.stack([case[2] for case in cases]), + np.asarray([case[3][2] for case in cases]), + np.zeros((2, 3)), image_hw=(368, 640), minimum_support=8, + ) + np.testing.assert_allclose( + result.translation_m, np.stack([case[3] for case in cases]), atol=1e-10, + ) + + +def test_ray_assemblies_preserve_selected_constraints(): + coarse = np.asarray([[0.05, -0.03, 0.5]]) + z = np.asarray([0.6]) + coarse_ray = coarse_wrist_ray_translation(coarse, z) + np.testing.assert_allclose(coarse_ray, [[0.06, -0.036, 0.6]]) + _, anchors, K, _ = synthetic_case() + direct, valid = direct_wrist_ray_translation( + anchors[None], K[None], z, coarse_ray, + ) + assert valid[0] + expected = np.asarray([ + (anchors[0, 0] - K[0, 2]) * z[0] / K[0, 0], + (anchors[0, 1] - K[1, 2]) * z[0] / K[1, 1], + z[0], + ]) + np.testing.assert_allclose(direct[0], expected) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_model.py b/home/wuyifan/EgoNet_train_20261008/tests/test_model.py new file mode 100644 index 0000000000000000000000000000000000000000..914d00662db3716fbe7634d7c5a8a3d116165465 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_model.py @@ -0,0 +1,300 @@ +import pytest +import torch + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig + + +def synthetic_batch(time=4, height=64, width=64): + K = torch.tensor([[50.0, 0.0, width / 2], [0.0, 50.0, height / 2], [0.0, 0.0, 1.0]]) + return { + "rgb": torch.randn(2, time, 3, height, width), + "depth_m": torch.rand(2, time, 1, height, width) + 0.3, + "depth_pixel_valid": torch.ones(2, time, 1, height, width, dtype=torch.bool), + "K": K[None, None].expand(2, time, -1, -1).clone(), + "K_available": torch.ones(2, time, dtype=torch.bool), + "depth_available": torch.ones(2, time, dtype=torch.bool), + "frame_valid": torch.ones(2, time, dtype=torch.bool), + "image_hw": torch.tensor([[height, width], [height, width]]), + "joint2d": torch.rand(2, time, 2, 21, 2) * width, + "joint3d_camera": torch.rand(2, time, 2, 21, 3), + "joint_element_valid": torch.ones(2, time, 2, 21, dtype=torch.bool), + "joint_annotation_valid": torch.ones(2, time, 2, dtype=torch.bool), + "mano_annotation_valid": torch.ones(2, time, 2, dtype=torch.bool), + "mano_pose": torch.zeros(2, time, 2, 48), + "mano_shape": torch.zeros(2, time, 2, 10), + "wrist_root_translation": torch.rand(2, time, 2, 3), + "presence_target": torch.full((2, time, 2), torch.nan), + "presence_label_valid": torch.zeros(2, time, 2, dtype=torch.bool), + } + + +@pytest.mark.parametrize("mode", ["sequential", "alternating", "hybrid_reread"]) +@pytest.mark.parametrize("modalities", ["rgb", "rgb_k", "rgb_depth", "rgb_depth_k"]) +def test_all_model_modes_forward_backward(mode, modalities): + use_depth, use_rays = "depth" in modalities, "k" in modalities + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=2, attention_heads=4, + decoder_mode=mode, use_depth=use_depth, use_rays=use_rays, + )) + batch = synthetic_batch() + if "depth" not in modalities: + for key in ("depth_m", "depth_pixel_valid", "depth_available"): + batch.pop(key) + if "k" not in modalities: + for key in ("K", "K_available"): + batch.pop(key) + output = model(batch) + assert output["joint2d_norm"].shape == (2, 4, 2, 21, 2) + assert (output["wrist_root_translation"][..., 2] > 0).all() + if use_depth: + expected_gate = 0.5 + 0.5 * model.config.depth_gate_floor + assert torch.allclose( + output["attention"]["depth_fusion_gate"], + torch.full_like(output["attention"]["depth_fusion_gate"], expected_gate), + ) + loss = BimanualLoss(LossConfig())(output, batch)["total"] + loss.backward() + assert torch.isfinite(loss) + for head in (model.joint2d_head, model.rotation_head, model.translation_head, model.shape_head): + assert any(parameter.grad is not None and torch.isfinite(parameter.grad).all() for parameter in head.parameters()) + + +def test_t1_and_padding_are_finite(): + model = BimanualReconstructionModel(ModelConfig(encoder="tiny_debug", decoder_dim=64, decoder_layers=1, attention_heads=4)) + batch = synthetic_batch(time=1) + batch["frame_valid"][1, 0] = True + output = model(batch) + assert torch.isfinite(output["hand_tokens"]).all() + + +def test_phase9_896x512_full_frame_forward_backward_is_finite() -> None: + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, decoder_mode="alternating", use_depth=True, + use_rays=True, use_temporal=True, + )) + batch = synthetic_batch(time=1, height=512, width=896) + batch = { + key: value[:1] if isinstance(value, torch.Tensor) and value.shape[0] == 2 else value + for key, value in batch.items() + } + output = model(batch) + loss = BimanualLoss(LossConfig())(output, batch)["total"] + loss.backward() + assert output["joint2d_norm"].shape == (1, 1, 2, 21, 2) + assert torch.isfinite(output["wrist_root_translation"]).all() + assert torch.isfinite(loss) + + +def test_fixed_depth_gate_is_exact_and_not_learned(): + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=2, attention_heads=4, + use_depth=True, depth_gate_mode="fixed", depth_gate_fixed_value=0.25, + )) + output = model(synthetic_batch()) + gate = output["attention"]["depth_fusion_gate"] + assert torch.allclose(gate, torch.full_like(gate, 0.25)) + + +def test_modality_dropout_is_training_only_and_probability_is_valid(): + with pytest.raises(ValueError): + BimanualReconstructionModel(ModelConfig(modality_dropout_prob=1.0)) + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, use_depth=True, use_rays=True, + modality_dropout_prob=1.0 - 1e-6, + )) + batch = synthetic_batch(time=2) + model.eval() + eval_output = model(batch) + assert eval_output["attention"]["depth_fusion_gate"].abs().sum() > 0 + model.train() + torch.manual_seed(0) + train_output = model(batch) + assert train_output["attention"]["depth_fusion_gate"].abs().sum() == 0 + + +def test_hybrid_reread_exactly_matches_sequential_parameterization(): + common = dict( + encoder="tiny_debug", decoder_dim=64, decoder_layers=3, + attention_heads=4, use_depth=True, use_temporal=True, + ) + sequential = BimanualReconstructionModel(ModelConfig(**common, decoder_mode="sequential")) + hybrid = BimanualReconstructionModel(ModelConfig(**common, decoder_mode="hybrid_reread")) + sequential_parameters = { + name: parameter.shape for name, parameter in sequential.decoder.named_parameters() + } + hybrid_parameters = { + name: parameter.shape for name, parameter in hybrid.decoder.named_parameters() + } + assert sequential_parameters == hybrid_parameters + assert sum(parameter.numel() for parameter in sequential.decoder.parameters()) == sum( + parameter.numel() for parameter in hybrid.decoder.parameters() + ) + assert len(sequential.decoder.spatial) == len(hybrid.decoder.spatial) == 3 + assert len(sequential.decoder.temporal) == len(hybrid.decoder.temporal) == 1 + + +def test_hybrid_reread_temporal_output_is_followed_by_spatial_update(): + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=3, + attention_heads=4, decoder_mode="hybrid_reread", use_depth=False, + use_temporal=True, + )) + calls = [] + handles = [] + for index, layer in enumerate(model.decoder.spatial): + handles.append(layer.register_forward_hook(lambda _m, _i, _o, index=index: calls.append(f"S{index}"))) + handles.append(model.decoder.temporal[0].register_forward_hook(lambda _m, _i, _o: calls.append("T"))) + output = model(synthetic_batch()) + for handle in handles: + handle.remove() + assert calls == ["S0", "S1", "T", "S2"] + assert output["attention"]["temporal_attention"].shape[1] == 1 + assert output["attention"]["temporal_update_norm"].shape == (2, 1, 4, 2) + + +def test_zero_initialized_relative_temporal_bias_matches_position_free_model(): + common = dict( + encoder="tiny_debug", decoder_dim=64, decoder_layers=2, + attention_heads=4, decoder_mode="alternating", use_depth=False, + use_rays=False, use_temporal=True, + ) + torch.manual_seed(7) + position_free = BimanualReconstructionModel(ModelConfig(**common)) + torch.manual_seed(7) + relative = BimanualReconstructionModel(ModelConfig( + **common, temporal_position_mode="relative_bias", + temporal_relative_bias_max_distance=15, + )) + missing, unexpected = relative.load_state_dict(position_free.state_dict(), strict=False) + assert unexpected == [] + assert missing == [ + "decoder.temporal.0.relative_position_bias", + "decoder.temporal.1.relative_position_bias", + ] + batch = synthetic_batch(time=4) + position_free.eval() + relative.eval() + baseline = position_free(batch) + candidate = relative(batch) + assert torch.allclose(candidate["hand_tokens"], baseline["hand_tokens"], atol=1e-6) + assert torch.allclose( + candidate["attention"]["temporal_attention"], + baseline["attention"]["temporal_attention"], atol=1e-6, + ) + + +def test_relative_temporal_bias_supports_padding_and_receives_gradient(): + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=2, + attention_heads=4, decoder_mode="alternating", use_depth=False, + use_rays=False, use_temporal=True, temporal_position_mode="relative_bias", + temporal_relative_bias_max_distance=15, + )) + batch = synthetic_batch(time=16) + batch["frame_valid"][1, 9:] = False + output = model(batch) + assert torch.isfinite(output["hand_tokens"]).all() + output["hand_tokens"].square().mean().backward() + for layer in model.decoder.temporal: + assert layer.relative_position_bias.shape == (4, 31) + assert layer.relative_position_bias.grad is not None + assert torch.isfinite(layer.relative_position_bias.grad).all() + + +def test_temporal_position_requires_temporal_attention(): + with pytest.raises(ValueError, match="requires use_temporal"): + BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, use_temporal=False, + temporal_position_mode="relative_bias", + )) + + +def test_structured_refinement_zero_init_matches_coarse_model() -> None: + common = dict( + encoder="tiny_debug", decoder_dim=64, decoder_layers=2, + attention_heads=4, use_depth=True, use_rays=True, + depth_gate_mode="fixed", depth_gate_fixed_value=0.5, + ) + torch.manual_seed(23) + coarse = BimanualReconstructionModel(ModelConfig(**common)).eval() + refined = BimanualReconstructionModel(ModelConfig( + **common, structured_hand_refinement=True, + )).eval() + missing, unexpected = refined.load_state_dict(coarse.state_dict(), strict=False) + assert unexpected == [] + assert missing and all(name.startswith("structured_") for name in missing) + batch = synthetic_batch(time=3) + with torch.no_grad(): + baseline = coarse(batch) + candidate = refined(batch) + for key in ( + "joint2d_norm", "mano_rotation_matrices", "mano_shape_sequence", + "mano_shape", "wrist_root_translation", + ): + torch.testing.assert_close(candidate[key], baseline[key], rtol=0, atol=0) + assert candidate["structured_part_tokens"].shape == (2, 3, 2, 7, 64) + assert candidate["structured_sample_locations"].shape == (2, 3, 2, 7, 4, 2) + assert candidate["structured_graph_attention"].shape == (2, 3, 2, 7, 7) + + +def test_structured_refinement_forward_backward_and_missing_depth_fallback() -> None: + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, use_depth=True, use_rays=True, + structured_hand_refinement=True, + )) + batch = synthetic_batch(time=2) + batch["depth_available"].zero_() + output = model(batch) + loss = BimanualLoss(LossConfig())(output, batch)["total"] + loss.backward() + assert torch.isfinite(loss) + for head in ( + model.structured_translation_head, model.structured_finger_rotation_head, + model.structured_shape_head, model.structured_finger_2d_head, + ): + assert head.weight.grad is not None + assert torch.isfinite(head.weight.grad).all() + assert output["structured_translation_delta"].abs().sum() == 0 + + +def test_structured_and_oracle_refinement_are_mutually_exclusive() -> None: + with pytest.raises(ValueError, match="mutually exclusive"): + BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, structured_hand_refinement=True, + oracle_crop_mode="oracle_rgb", + )) + + +def test_structured_pose_only_mode_keeps_translation_exactly_coarse() -> None: + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, use_depth=True, use_rays=True, + structured_hand_refinement=True, structured_refine_translation=False, + )) + with torch.no_grad(): + model.structured_translation_head.weight.fill_(1.0) + model.structured_translation_head.bias.fill_(1.0) + model.structured_root_2d_head.bias.fill_(0.2) + output = model(synthetic_batch(time=2)) + torch.testing.assert_close( + output["wrist_root_translation"], + output["coarse_wrist_root_translation"], rtol=0, atol=0, + ) + assert output["structured_translation_delta"].abs().sum() == 0 + assert output["structured_joint2d_delta"].abs().sum() > 0 + + +def test_formal_dino_requires_explicit_assets(tmp_path): + with pytest.raises(ValueError, match="explicit official source"): + BimanualReconstructionModel(ModelConfig()) + repo = tmp_path / "repo" + repo.mkdir() + (repo / "hubconf.py").write_text("", encoding="utf-8") + with pytest.raises(FileNotFoundError, match="pretrained weight"): + BimanualReconstructionModel(ModelConfig(dinov3_source=str(repo), dinov3_weights=str(tmp_path / "missing.pth"))) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_model_mixed_projection.py b/home/wuyifan/EgoNet_train_20261008/tests/test_model_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..361f6f6bc0b57e7f6c626dfffbf55eca736e4789 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_model_mixed_projection.py @@ -0,0 +1,109 @@ +import torch +from torch import nn + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig + + +class FakeMano(nn.Module): + def __init__(self) -> None: + super().__init__() + x = torch.linspace(-0.04, 0.04, 21) + y = 0.02 * torch.sin(torch.linspace(0.0, torch.pi * 2.0, 21)) + z = torch.linspace(-0.01, 0.02, 21) + self.register_buffer("joints", torch.stack((x, y, z), dim=-1)) + vertices = torch.stack(( + torch.linspace(-0.05, 0.05, 778), + torch.linspace(0.03, -0.03, 778), + torch.linspace(-0.015, 0.025, 778), + ), dim=-1) + self.register_buffer("vertices", vertices) + + def forward(self, rotations, shape, translation): + prefix = translation.shape[:-1] + pose_signal = rotations[..., 1:, 0, 1].mean(dim=-1) + shape_signal = shape.mean(dim=-1) + joints = self.joints.expand(*prefix, -1, -1).clone() + joints[..., 1:, 0] += 0.002 * pose_signal[..., None] + joints[..., 1:, 1] += 0.001 * shape_signal[..., None] + vertices = self.vertices.expand(*prefix, -1, -1).clone() + vertices[..., 1:, 0] += 0.002 * pose_signal[..., None] + vertices[..., 1:, 1] += 0.001 * shape_signal[..., None] + return vertices + translation[..., None, :], joints + translation[..., None, :] + + +def batch(time: int = 2) -> dict[str, torch.Tensor]: + height, width = 32, 48 + K = torch.tensor([[50.0, 0.0, width / 2], [0.0, 50.0, height / 2], [0.0, 0.0, 1.0]]) + return { + "rgb": torch.randn(1, time, 3, height, width), + "depth_m": torch.rand(1, time, 1, height, width) + 0.3, + "depth_pixel_valid": torch.ones(1, time, 1, height, width, dtype=torch.bool), + "K": K[None, None].expand(1, time, -1, -1).clone(), + "K_available": torch.ones(1, time, dtype=torch.bool), + "depth_available": torch.ones(1, time, dtype=torch.bool), + "frame_valid": torch.ones(1, time, dtype=torch.bool), + } + + +def model() -> BimanualReconstructionModel: + result = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, use_depth=True, use_rays=True, + translation_parameterization="mixed_projection", + )) + result.mano_layer = FakeMano() + return result + + +def test_mixed_projection_model_is_finite_and_backpropagates() -> None: + candidate = model() + with torch.no_grad(): + for head in ( + candidate.mixed_log_tz_head, candidate.joint2d_head, + candidate.rotation_head, candidate.shape_head, + ): + head.weight.normal_(std=1e-3) + output = candidate(batch()) + assert output["translation_parameterization"] == "mixed_projection" + assert output["mixed_projection_success"].all() + assert torch.isfinite(output["wrist_root_translation"]).all() + loss = output["wrist_root_translation"].square().sum() + loss.backward() + for module in ( + candidate.mixed_log_tz_head, + candidate.joint2d_head, + candidate.rotation_head, + candidate.shape_head, + candidate.decoder.spatial[0].rgb_attention, + ): + assert any( + parameter.grad is not None + and torch.isfinite(parameter.grad).all() + and parameter.grad.abs().sum() > 0 + for parameter in module.parameters() + if parameter.requires_grad + ) + assert all(not parameter.requires_grad for parameter in candidate.translation_head.parameters()) + + +def test_mixed_projection_missing_k_falls_back_to_direct_teacher() -> None: + candidate = model().eval() + inputs = batch() + inputs["K_available"][:] = False + with torch.no_grad(): + output = candidate(inputs) + torch.testing.assert_close( + output["wrist_root_translation"], + output["mixed_projection_direct_teacher_translation"], + ) + assert not output["mixed_projection_success"].any() + + +def test_direct_xyz_default_has_no_mixed_parameters() -> None: + direct = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, + )) + assert direct.config.translation_parameterization == "direct_xyz" + assert not hasattr(direct, "mixed_log_tz_head") + assert not any(name.startswith("mixed_") for name, _ in direct.named_parameters()) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_model_ray_depth_translation.py b/home/wuyifan/EgoNet_train_20261008/tests/test_model_ray_depth_translation.py new file mode 100644 index 0000000000000000000000000000000000000000..d0a5fab2cfbef45110b416dbc2c9894c6a30f330 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_model_ray_depth_translation.py @@ -0,0 +1,233 @@ +import torch +from torch import nn + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.losses import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint, save_checkpoint + + +class FakeMano(nn.Module): + def __init__(self) -> None: + super().__init__() + joints = torch.zeros(21, 3) + joints[:, 0] = torch.linspace(-0.04, 0.04, 21) + vertices = torch.zeros(778, 3) + self.register_buffer("joints", joints) + self.register_buffer("vertices", vertices) + + def forward(self, rotations, shape, translation): + prefix = translation.shape[:-1] + joints = self.joints.expand(*prefix, -1, -1) + translation[..., None, :] + vertices = self.vertices.expand(*prefix, -1, -1) + translation[..., None, :] + return vertices, joints + + +def batch(time: int = 2) -> dict[str, torch.Tensor]: + height, width = 32, 48 + K = torch.tensor([ + [50.0, 0.0, width / 2], [0.0, 50.0, height / 2], [0.0, 0.0, 1.0], + ]) + result = { + "rgb": torch.randn(1, time, 3, height, width), + "depth_m": torch.full((1, time, 1, height, width), 0.55), + "depth_pixel_valid": torch.ones(1, time, 1, height, width, dtype=torch.bool), + "K": K[None, None].expand(1, time, -1, -1).clone(), + "K_input_available": torch.ones(1, time, dtype=torch.bool), + "K_supervision_valid": torch.ones(1, time, dtype=torch.bool), + "depth_input_available": torch.ones(1, time, dtype=torch.bool), + "frame_valid": torch.ones(1, time, dtype=torch.bool), + } + return result + + +def model() -> BimanualReconstructionModel: + result = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, use_depth=True, use_rays=True, + translation_parameterization="ray_depth_residual", + )) + result.mano_layer = FakeMano() + return result + + +def test_ray_depth_zero_initialization_and_gradient_paths() -> None: + candidate = model() + with torch.no_grad(): + candidate.ray_depth_log_z_head.weight.normal_(std=1e-3) + candidate.joint2d_head.weight.normal_(std=1e-3) + inputs = batch() + output = candidate(inputs) + assert output["translation_parameterization"] == "ray_depth_residual" + assert torch.equal( + output["ray_depth_applied_delta_z_m"], + torch.zeros_like(output["ray_depth_applied_delta_z_m"]), + ) + assert torch.all(output["ray_depth_confidence"] < 0.02) + assert output["ray_depth_correction_valid"].all() + assert torch.isfinite(output["wrist_root_translation"]).all() + loss = output["wrist_root_translation"].square().sum() + loss.backward() + for module in ( + candidate.ray_depth_log_z_head, candidate.joint2d_head, + candidate.decoder.spatial[0].rgb_attention, + ): + assert any( + parameter.grad is not None and torch.isfinite(parameter.grad).all() + and parameter.grad.abs().sum() > 0 + for parameter in module.parameters() if parameter.requires_grad + ) + + +def test_ray_depth_sampling_broadcasts_clip_availability_at_t8() -> None: + candidate = model().eval() + with torch.no_grad(): + output = candidate(batch(time=8)) + assert output["ray_depth_support_count"].shape == (1, 8, 2) + assert torch.equal( + output["ray_depth_support_count"], + torch.full((1, 8, 2), 9, dtype=torch.long), + ) + + +def test_ray_depth_missing_depth_and_k_fallbacks_are_exact() -> None: + candidate = model().eval() + inputs = batch() + inputs["depth_input_available"][:] = False + with torch.no_grad(): + no_depth = candidate(inputs) + assert not no_depth["ray_depth_correction_valid"].any() + assert torch.equal( + no_depth["ray_depth_applied_delta_z_m"], + torch.zeros_like(no_depth["ray_depth_applied_delta_z_m"]), + ) + inputs["K_input_available"][:] = False + with torch.no_grad(): + no_k = candidate(inputs) + changed_k_inputs = {key: value.clone() for key, value in inputs.items()} + changed_k_inputs["K"][:, :, 0, 0] *= 3.0 + changed_k_inputs["K"][:, :, 1, 1] *= 0.5 + changed_k = candidate(changed_k_inputs) + torch.testing.assert_close( + no_k["wrist_root_translation"], + no_k["ray_depth_direct_fallback_translation"], + ) + torch.testing.assert_close( + no_k["wrist_root_translation"], changed_k["wrist_root_translation"], + ) + + +def test_ray_depth_backprojection_round_trip_supports_different_intrinsics() -> None: + candidate = model().eval() + inputs = batch(time=2) + inputs["K"][0, 0] = torch.tensor([ + [80.0, 0.0, 19.0], [0.0, 75.0, 14.0], [0.0, 0.0, 1.0], + ]) + inputs["K"][0, 1] = torch.tensor([ + [140.0, 0.0, 29.0], [0.0, 125.0, 20.0], [0.0, 0.0, 1.0], + ]) + wrist_norm = torch.tensor([0.35, 0.65]) + wrist_logit = torch.logit(wrist_norm) + with torch.no_grad(): + candidate.joint2d_head.weight.zero_() + candidate.joint2d_head.bias.reshape(21, 2).copy_( + wrist_logit.expand(21, -1), + ) + candidate.ray_depth_log_z_head.weight.zero_() + candidate.ray_depth_log_z_head.bias.fill_(torch.log(torch.tensor(0.75))) + output = candidate(inputs) + + translation = output["wrist_root_translation"][0] + K = inputs["K"][0, :, None] + projected_u = K[..., 0, 0] * translation[..., 0] / translation[..., 2] + K[..., 0, 2] + projected_v = K[..., 1, 1] * translation[..., 1] / translation[..., 2] + K[..., 1, 2] + expected_u = torch.full_like(projected_u, wrist_norm[0] * 48.0) + expected_v = torch.full_like(projected_v, wrist_norm[1] * 32.0) + torch.testing.assert_close(projected_u, expected_u, rtol=1e-5, atol=1e-5) + torch.testing.assert_close(projected_v, expected_v, rtol=1e-5, atol=1e-5) + assert not torch.equal(translation[0, :, :2], translation[1, :, :2]) + + +def test_ray_rgb_base_z_condition_disables_depth_residual() -> None: + candidate = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, use_depth=True, use_rays=True, + translation_parameterization="ray_depth_residual", + ray_depth_enable_residual=False, + )).eval() + candidate.mano_layer = FakeMano() + with torch.no_grad(): + candidate.ray_depth_delta_head[-1].bias.fill_(1.0) + output = candidate(batch()) + assert not output["ray_depth_correction_valid"].any() + assert torch.equal( + output["ray_depth_applied_delta_z_m"], + torch.zeros_like(output["ray_depth_applied_delta_z_m"]), + ) + + +def test_ray_and_rgb_base_z_are_invariant_to_depth_content() -> None: + candidate = model().eval() + clean = batch() + changed = {key: value.clone() for key, value in clean.items()} + changed["depth_m"].fill_(1.25) + with torch.no_grad(): + clean_output = candidate(clean) + changed_output = candidate(changed) + torch.testing.assert_close( + clean_output["ray_depth_wrist2d_norm"], + changed_output["ray_depth_wrist2d_norm"], rtol=0.0, atol=0.0, + ) + torch.testing.assert_close( + clean_output["ray_depth_base_z_m"], + changed_output["ray_depth_base_z_m"], rtol=0.0, atol=0.0, + ) + + +def test_ray_depth_losses_are_finite_and_keep_hidden_k_supervision() -> None: + candidate = model() + inputs = batch() + inputs["K_input_available"][:] = False + prediction = candidate(inputs) + batch_size, time = inputs["frame_valid"].shape + inputs.update({ + "joint_annotation_valid": torch.ones(batch_size, time, 2, dtype=torch.bool), + "mano_annotation_valid": torch.zeros(batch_size, time, 2, dtype=torch.bool), + "joint_element_valid": torch.ones(batch_size, time, 2, 21, dtype=torch.bool), + "joint2d_valid": torch.ones(batch_size, time, 2, 21, dtype=torch.bool), + "joint3d_valid": torch.zeros(batch_size, time, 2, 21, dtype=torch.bool), + "translation_valid": torch.ones(batch_size, time, 2, dtype=torch.bool), + "mano_pose_valid": torch.zeros(batch_size, time, 2, dtype=torch.bool), + "shape_valid": torch.zeros(batch_size, time, 2, dtype=torch.bool), + "vertices_valid": torch.zeros(batch_size, time, 2, dtype=torch.bool), + "reprojection_valid": torch.ones(batch_size, time, 2, 21, dtype=torch.bool), + "joint2d": prediction["joint2d_norm"].detach() * torch.tensor((48.0, 32.0)), + "joint3d_camera": torch.zeros(batch_size, time, 2, 21, 3), + "wrist_root_translation": prediction["wrist_root_translation"].detach(), + "mano_pose": torch.zeros(batch_size, time, 2, 48), + "mano_shape": torch.zeros(batch_size, time, 2, 10), + "vertices_camera": torch.zeros(batch_size, time, 2, 778, 3), + "image_hw": torch.tensor([[32, 48]]), + }) + losses = BimanualLoss(LossConfig( + wrist_ray=1.0, robust_log_z=5.0, z_tail_cvar=0.5, + depth_confidence_calibration=0.5, paired_modality_no_harm=1.0, + ))(prediction, inputs) + assert all(torch.isfinite(value) for value in losses.values()) + assert inputs["K_supervision_valid"].all() + + +def test_ray_depth_checkpoint_round_trip_is_exact(tmp_path) -> None: + original = model().eval() + optimizer = torch.optim.AdamW(original.parameters(), lr=1e-4) + inputs = batch() + with torch.no_grad(): + expected = original(inputs)["wrist_root_translation"].clone() + path = tmp_path / "ray_depth.pt" + save_checkpoint(path, original, optimizer, step=17, extra={"official_test_used": False}) + restored = model().eval() + restored_optimizer = torch.optim.AdamW(restored.parameters(), lr=1e-4) + state = load_checkpoint(path, restored, restored_optimizer, map_location="cpu") + with torch.no_grad(): + actual = restored(inputs)["wrist_root_translation"] + assert state["step"] == 17 + torch.testing.assert_close(actual, expected, rtol=0.0, atol=0.0) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_optimizer_groups.py b/home/wuyifan/EgoNet_train_20261008/tests/test_optimizer_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..f785eb1b5d0e981b6256cc0d5ed6ca77b23b0c75 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_optimizer_groups.py @@ -0,0 +1,86 @@ +import pytest +import torch +from torch import nn + +from foundation_hand.training.optimizer import ( + clear_staged_later_gradients, + checkpoint_excluded_prefixes, + optimizer_parameter_groups, + set_scheduled_learning_rate, + set_staged_parameter_group_phase, + staged_optimizer_parameter_groups, +) + + +class ToyModel(nn.Module): + def __init__(self, train_backbone: bool) -> None: + super().__init__() + self.rgb_encoder = nn.Module() + self.rgb_encoder.backbone = nn.Linear(2, 2) + self.head = nn.Linear(2, 1) + self.aux = nn.Linear(2, 1) + self.rgb_encoder.backbone.requires_grad_(train_backbone) + + +def test_optimizer_groups_apply_frozen_backbone_contract() -> None: + model = ToyModel(train_backbone=False) + groups = optimizer_parameter_groups( + model, learning_rate=5e-6, backbone_learning_rate=None, + ) + assert [group["group_name"] for group in groups] == ["main"] + assert checkpoint_excluded_prefixes(model) == ("rgb_encoder.backbone.",) + + +def test_optimizer_groups_preserve_low_lr_ratio_and_checkpoint_backbone() -> None: + model = ToyModel(train_backbone=True) + groups = optimizer_parameter_groups( + model, learning_rate=5e-6, backbone_learning_rate=5e-7, + ) + optimizer = torch.optim.AdamW(groups) + set_scheduled_learning_rate(optimizer, 2e-6) + assert [group["lr"] for group in optimizer.param_groups] == pytest.approx([2e-6, 2e-7]) + assert checkpoint_excluded_prefixes(model) == () + + +def test_optimizer_groups_reject_lr_without_matching_trainable_backbone() -> None: + with pytest.raises(ValueError, match="no backbone"): + optimizer_parameter_groups( + ToyModel(train_backbone=False), + learning_rate=5e-6, + backbone_learning_rate=5e-7, + ) + with pytest.raises(ValueError, match="require backbone_learning_rate"): + optimizer_parameter_groups( + ToyModel(train_backbone=True), + learning_rate=5e-6, + backbone_learning_rate=None, + ) + + +def test_staged_groups_keep_identity_and_switch_later_lr() -> None: + model = ToyModel(train_backbone=False) + groups = staged_optimizer_parameter_groups( + model, + learning_rate=1e-4, + initial_trainable_prefixes=("head.",), + unfrozen_learning_rate_scale=0.1, + ) + optimizer = torch.optim.AdamW(groups, lr=1e-4) + later_ids = {id(parameter) for parameter in optimizer.param_groups[1]["params"]} + set_staged_parameter_group_phase(optimizer, active=False) + set_scheduled_learning_rate(optimizer, 5e-5) + assert optimizer.param_groups[1]["lr"] == 0.0 + set_staged_parameter_group_phase(optimizer, active=True) + set_scheduled_learning_rate(optimizer, 5e-5) + assert optimizer.param_groups[1]["lr"] == pytest.approx(5e-6) + assert later_ids == {id(parameter) for parameter in optimizer.param_groups[1]["params"]} + + +def test_staged_freeze_clears_only_later_gradients() -> None: + model = ToyModel(train_backbone=False) + for parameter in model.parameters(): + if parameter.requires_grad: + parameter.grad = torch.ones_like(parameter) + clear_staged_later_gradients(model, ("head.",)) + assert all(parameter.grad is not None for parameter in model.head.parameters()) + assert all(parameter.grad is None for parameter in model.aux.parameters()) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_oracle_crop.py b/home/wuyifan/EgoNet_train_20261008/tests/test_oracle_crop.py new file mode 100644 index 0000000000000000000000000000000000000000..87e279ee9752dd3ce205ebd6ed47974a9ad19c10 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_oracle_crop.py @@ -0,0 +1,58 @@ +import cv2 +import numpy as np + +from foundation_hand.data.oracle_crop import ( + OracleCropSpec, + crop_resize_intrinsics, + crop_resize_with_padding, + oracle_square_crop_spec, +) +from foundation_hand.geometry.camera import project_points + + +def test_oracle_crop_uses_registered_margin_and_minimum_side(): + joints = np.zeros((21, 2), dtype=np.float32) + joints[:4] = np.asarray([[100, 100], [140, 100], [140, 120], [100, 120]]) + valid = np.zeros(21, dtype=bool) + valid[:4] = True + + spec = oracle_square_crop_spec(joints, valid, (720, 1280)) + + assert spec == OracleCropSpec(72, 62, 96, (720, 1280), (224, 224)) + + +def test_oracle_crop_requires_four_valid_finite_points(): + joints = np.zeros((21, 2), dtype=np.float32) + valid = np.zeros(21, dtype=bool) + valid[:4] = True + joints[3] = np.nan + + assert oracle_square_crop_spec(joints, valid, (720, 1280)) is None + + +def test_crop_padding_keeps_requested_roi_instead_of_shifting(): + image = np.arange(16, dtype=np.uint8).reshape(4, 4) + spec = OracleCropSpec(-2, -1, 6, (4, 4), (6, 6)) + + crop = crop_resize_with_padding( + image, spec, interpolation=cv2.INTER_NEAREST, fill=99, + ) + + assert np.all(crop[:1] == 99) + assert np.all(crop[:, :2] == 99) + assert np.array_equal(crop[1:5, 2:6], image) + + +def test_crop_intrinsics_preserve_projection_under_crop_resize(): + K = np.asarray([[900.0, 0.0, 640.0], [0.0, 910.0, 360.0], [0.0, 0.0, 1.0]]) + points = np.asarray([ + [0.0, 0.0, 0.8], [0.04, -0.02, 0.8], [-0.03, 0.05, 1.0], + ], dtype=np.float32) + spec = OracleCropSpec(488, 208, 304, (720, 1280), (224, 224)) + + raw_pixels, _ = project_points(points, K) + expected = (raw_pixels - np.asarray([spec.x0, spec.y0])) * (224.0 / spec.side) + crop_pixels, positive_z = project_points(points, crop_resize_intrinsics(K, spec)) + + assert positive_z.all() + assert np.allclose(crop_pixels, expected, atol=1e-5) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_oracle_crop_refiner.py b/home/wuyifan/EgoNet_train_20261008/tests/test_oracle_crop_refiner.py new file mode 100644 index 0000000000000000000000000000000000000000..4321be020b125ae6de4de3b077d7cd917c6cb0ee --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_oracle_crop_refiner.py @@ -0,0 +1,150 @@ +import torch + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig + + +def batch(depth_available: bool = True) -> dict[str, torch.Tensor]: + return { + "rgb": torch.randn(1, 2, 3, 32, 32), + "depth_m": torch.full((1, 2, 1, 32, 32), 0.7), + "depth_pixel_valid": torch.ones(1, 2, 1, 32, 32, dtype=torch.bool), + "K": torch.tensor( + [[[[30.0, 0.0, 16.0], [0.0, 30.0, 16.0], [0.0, 0.0, 1.0]]] * 2] + ), + "K_available": torch.ones(1, 2, dtype=torch.bool), + "depth_available": torch.ones(1, 2, dtype=torch.bool), + "frame_valid": torch.ones(1, 2, dtype=torch.bool), + "oracle_crop_rgb": torch.randn(1, 2, 2, 3, 32, 32), + "oracle_crop_depth_m": torch.full((1, 2, 2, 1, 32, 32), 0.7), + "oracle_crop_depth_pixel_valid": torch.ones( + 1, 2, 2, 1, 32, 32, dtype=torch.bool, + ), + "oracle_crop_K": torch.tensor( + [[[[[30.0, 0.0, 16.0], [0.0, 30.0, 16.0], [0.0, 0.0, 1.0]]] * 2] * 2] + ), + "oracle_crop_available": torch.ones(1, 2, 2, dtype=torch.bool), + "oracle_crop_depth_available": torch.full( + (1, 2, 2), depth_available, dtype=torch.bool, + ), + } + + +def config(mode: str) -> ModelConfig: + return ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, patch_size=16, use_temporal=True, + use_depth=True, depth_mode="geometry", use_rays=True, + oracle_crop_mode=mode, freeze_coarse_for_oracle_crop=True, + ) + + +def test_zero_initialized_oracle_rgb_depth_refiner_equals_coarse_output(): + model = BimanualReconstructionModel(config("oracle_rgb_depth_k")).eval() + + with torch.no_grad(): + output = model(batch()) + + assert torch.equal( + output["mano_rotation_matrices"], output["coarse_mano_rotation_matrices"], + ) + assert torch.equal(output["mano_shape"], output["coarse_mano_shape"]) + assert torch.equal( + output["wrist_root_translation"], output["coarse_wrist_root_translation"], + ) + assert torch.count_nonzero(output["oracle_crop_rotation_delta_axis_angle"]) == 0 + assert torch.count_nonzero(output["oracle_crop_shape_delta"]) == 0 + assert torch.count_nonzero(output["oracle_crop_delta_z"]) == 0 + + +def test_oracle_refiner_freezes_every_non_oracle_parameter(): + model = BimanualReconstructionModel(config("oracle_rgb_depth_k")) + + trainable = [name for name, value in model.named_parameters() if value.requires_grad] + + assert trainable + assert all(name.startswith("oracle_crop_") for name in trainable) + assert any("rotation_head" in name for name in trainable) + assert any("delta_z_head" in name for name in trainable) + + +def test_oracle_depth_refiner_has_strict_missing_depth_fallback(): + model = BimanualReconstructionModel(config("oracle_depth_k")).eval() + with torch.no_grad(): + model.oracle_crop_delta_z_head.bias.fill_(10.0) + + output = model(batch(depth_available=False)) + + assert torch.count_nonzero(output["oracle_crop_delta_z"]) == 0 + assert torch.equal( + output["wrist_root_translation"], output["coarse_wrist_root_translation"], + ) + + +def test_oracle_depth_refiner_respects_coarse_depth_availability(): + model = BimanualReconstructionModel(config("oracle_depth_k")).eval() + with torch.no_grad(): + model.oracle_crop_delta_z_head.bias.fill_(10.0) + unavailable = batch(depth_available=True) + unavailable["depth_available"].zero_() + + output = model(unavailable) + + assert torch.count_nonzero(output["oracle_crop_delta_z"]) == 0 + assert not output["oracle_crop_depth_available_effective"].any() + + +def test_invalid_oracle_roi_with_zero_intrinsics_has_finite_backward(): + model = BimanualReconstructionModel(config("oracle_rgb_depth_k")) + invalid = batch(depth_available=True) + invalid["oracle_crop_available"][:, :, 1] = False + invalid["oracle_crop_depth_available"][:, :, 1] = False + invalid["oracle_crop_depth_pixel_valid"][:, :, 1] = False + invalid["oracle_crop_depth_m"][:, :, 1] = 0 + invalid["oracle_crop_K"][:, :, 1] = 0 + + output = model(invalid) + loss = ( + output["mano_rotation_matrices"].sum() + + output["mano_shape"].sum() + + output["wrist_root_translation"].sum() + ) + loss.backward() + + assert torch.isfinite(output["oracle_crop_delta_z"]).all() + assert torch.count_nonzero(output["oracle_crop_delta_z"][:, :, 1]) == 0 + assert all( + value.grad is None or torch.isfinite(value.grad).all() + for value in model.parameters() if value.requires_grad + ) + + +def test_oracle_residual_heads_receive_finite_gradient_at_zero_init(): + model = BimanualReconstructionModel(config("oracle_rgb_depth_k")) + output = model(batch()) + loss = ( + output["mano_rotation_matrices"].sum() + + output["mano_shape"].sum() + + output["wrist_root_translation"].sum() + ) + + loss.backward() + + for name in ( + "oracle_crop_rotation_head.weight", + "oracle_crop_shape_head.weight", + "oracle_crop_delta_z_head.weight", + ): + gradient = dict(model.named_parameters())[name].grad + assert gradient is not None + assert torch.isfinite(gradient).all() + + +def test_rotation_residual_is_bit_exact_at_bfloat16_zero_with_gradient(): + coarse = torch.randn(32, 3, 3, dtype=torch.bfloat16) + delta = torch.zeros(32, 3, dtype=torch.bfloat16, requires_grad=True) + + refined = BimanualReconstructionModel._compose_rotation_residual(coarse, delta) + + assert torch.equal(refined, coarse) + refined.float().sum().backward() + assert torch.isfinite(delta.grad).all() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_core_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_core_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7d6ab21a26878bb8726507f1d0a2dd4d3a310a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_core_summary.py @@ -0,0 +1,29 @@ +import numpy as np + +from scripts.summarize_phase3_core import bootstrap_take_values, paired_take_differences + + +def row(take: str, value: float) -> dict[str, str]: + return { + "clip_index": "0", "time_index": "0", "take": take, + "subject": "subject1", "sequence": "seq", "frame_id": "1", + "side": "left", "annotation_valid": "1", "annotation_state": "11", + "absolute_mpjpe_mm": str(value), + } + + +def test_paired_take_differences_are_take_equal() -> None: + candidate = [row("a", 2.0), row("a", 4.0), row("b", 20.0)] + reference = [row("a", 1.0), row("a", 1.0), row("b", 10.0)] + result = paired_take_differences(candidate, reference, "absolute_mpjpe_mm") + assert result["take_equal_mean_delta"] == 6.0 + assert result["frame_weighted_mean_delta"] == 14.0 / 3.0 + np.testing.assert_allclose(result["take_means"], [2.0, 10.0]) + + +def test_bootstrap_take_values_is_deterministic() -> None: + values = np.asarray([1.0, 2.0, 3.0]) + first = bootstrap_take_values(values, seed=7, samples=1000) + second = bootstrap_take_values(values, seed=7, samples=1000) + assert first == second + assert first[0] <= values.mean() <= first[1] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_depth_fusion_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_depth_fusion_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..80beb4aa115b7850e000f073c499a3ce06ea5960 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_depth_fusion_configs.py @@ -0,0 +1,37 @@ +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).parents[1] + + +def load(path: Path) -> dict: + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def test_depth_fusion_variants_change_only_registered_fields() -> None: + for seed in (20260716, 20260717, 20260718): + base = load(ROOT / f"configs/phase3/core/core_m3_l1_t1_s{seed}.yaml") + for variant, expected in { + "gate025": ("log_depth", "fixed", 0.0, 0.25), + "learned_gate": ("log_depth", "learned", 0.0, 0.5), + "geometry": ("geometry", "fixed", 0.0, 0.5), + }.items(): + config = load(ROOT / f"configs/phase3/depth_fusion/depth_{variant}_m3_l1_t1_s{seed}.yaml") + assert config["data"] == base["data"] + assert config["loss"] == base["loss"] + assert config["assets"] == base["assets"] + assert config["protocol"] == base["protocol"] + model = dict(config["model"]) + for key in ("depth_mode", "depth_gate_mode", "depth_gate_floor", "depth_gate_fixed_value"): + model.pop(key) + reference = dict(base["model"]) + for key in ("depth_mode", "depth_gate_mode", "depth_gate_floor", "depth_gate_fixed_value"): + reference.pop(key, None) + assert model == reference + assert ( + config["model"]["depth_mode"], config["model"]["depth_gate_mode"], + config["model"]["depth_gate_floor"], config["model"]["depth_gate_fixed_value"], + ) == expected + assert config["experiment"]["variant"] == variant diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_depth_fusion_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_depth_fusion_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..c50d7e881c8b69e8449a10298358ab6d3f9ceaea --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_depth_fusion_summary.py @@ -0,0 +1,8 @@ +from scripts.summarize_phase3_depth_fusion import run_name + + +def test_depth_fusion_run_names_distinguish_reused_control_and_new_variants() -> None: + assert run_name("P0_fixed05", 7) == "core_m3_l1_t1_s7" + assert run_name("gate025", 7) == "depth_gate025_m3_l1_t1_s7" + assert run_name("learned_gate", 7) == "depth_learned_gate_m3_l1_t1_s7" + assert run_name("geometry", 7) == "depth_geometry_m3_l1_t1_s7" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_dose_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_dose_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..1cc371ea06d0d8da98cdab72422e005c1f48c9b4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_dose_configs.py @@ -0,0 +1,33 @@ +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).parents[1] + + +def test_dropout_dose_configs_only_change_registered_probability() -> None: + for seed in (20260716, 20260717, 20260718): + base = yaml.safe_load(( + ROOT + / f"configs/phase3/depth_fusion/depth_dropout00_geometry_m3_l1_t1_s{seed}.yaml" + ).read_text()) + for variant, probability in { + "dropout005_geometry": 0.05, + "dropout010_geometry": 0.10, + }.items(): + config = yaml.safe_load(( + ROOT / f"configs/phase3/depth_fusion/depth_{variant}_m3_l1_t1_s{seed}.yaml" + ).read_text()) + assert config["data"] == base["data"] + assert config["loss"] == base["loss"] + assert config["assets"] == base["assets"] + assert config["protocol"] == base["protocol"] + model = dict(config["model"]) + assert model.pop("modality_dropout_prob") == probability + base_model = dict(base["model"]) + base_model.pop("modality_dropout_prob") + assert model == base_model + assert config["experiment"]["registered_axes"] == [ + "modality_dropout_dose" + ] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_dose_fallback_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_dose_fallback_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..fddb01bc4504a6e71c75b944311b5f4f35ca37ab --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_dose_fallback_summary.py @@ -0,0 +1,11 @@ +from scripts.summarize_phase3_dropout_dose_fallback import CONDITIONS +from scripts.summarize_phase3_dropout_dose import COMPARISONS, VARIANTS + + +def test_dropout_dose_fallback_grid_is_complete() -> None: + assert CONDITIONS["complete"] == (False, False) + assert CONDITIONS["drop_depth"] == (True, False) + assert CONDITIONS["drop_k"] == (False, True) + assert CONDITIONS["drop_both"] == (True, True) + assert len(VARIANTS) == 4 + assert len(COMPARISONS) == 6 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_dose_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_dose_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..30817a09708ec7068cefcca43b6d45e95545c4a3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_dose_summary.py @@ -0,0 +1,17 @@ +import pytest + +from scripts.summarize_phase3_dropout_dose import ( + COMPARISONS, matrix_for, run_name, +) + + +def test_dropout_dose_summary_routes_endpoint_and_dose_variants() -> None: + assert matrix_for("dropout00_geometry") == "depth_modality_dropout" + assert matrix_for("dropout02_geometry") == "depth_modality_dropout" + assert matrix_for("dropout005_geometry") == "depth_modality_dropout_dose" + assert run_name("dropout010_geometry", 7) == ( + "depth_dropout010_geometry_m3_l1_t1_s7" + ) + assert ("dropout005_geometry", "dropout00_geometry") in COMPARISONS + with pytest.raises(ValueError): + run_name("unknown", 7) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..73055837d2ba31ff01db95b14ddf11c43bbee00a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_dropout_summary.py @@ -0,0 +1,15 @@ +import pytest + +from scripts.summarize_phase3_dropout import optional_aggregate, run_name + + +def test_dropout_run_name_and_optional_aggregate() -> None: + assert run_name("dropout00_geometry", 7) == "depth_dropout00_geometry_m3_l1_t1_s7" + assert run_name("dropout02_geometry", 7) == "depth_dropout02_geometry_m3_l1_t1_s7" + with pytest.raises(ValueError): + run_name("unknown", 7) + result = optional_aggregate( + [{"seed": 1, "x": None}, {"seed": 2, "x": None}], "x" + ) + assert result["mean"] is None + assert result["sample_std"] is None diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_evaluation.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..b593333b585921248691fcfef35574e70fccbd63 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_evaluation.py @@ -0,0 +1,116 @@ +import numpy as np + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.selection import select_visualization_frames +from foundation_hand.evaluation.subset import balanced_stratified_indices +from foundation_hand.evaluation.visualization import MeshLayer, project_mesh_layers, render_mesh_layers +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from scripts.evaluate_phase3 import temporal_position_bias_report + + +def test_distribution_summary_has_fixed_tail_percentiles(): + summary = distribution_summary([1, 2, 3, 4, None, float("nan")]) + assert summary["count"] == 4 + assert summary["mean"] == 2.5 + assert summary["p50"] == 2.5 + assert summary["p99"] > summary["p95"] + + +def test_take_bootstrap_weights_takes_not_frames(): + rows = [ + {"take": "a", "metric": 0.0}, + {"take": "a", "metric": 0.0}, + {"take": "a", "metric": 0.0}, + {"take": "b", "metric": 10.0}, + ] + first = bootstrap_take_means(rows, ["metric"], seed=7, samples=1000) + second = bootstrap_take_means(rows, ["metric"], seed=7, samples=1000) + assert first == second + assert first[0]["take_count"] == 2 + assert first[0]["take_mean"] == 5.0 + + +def test_visualization_selection_is_deterministic_and_auditable(): + records = [ + { + "clip_index": index, + "time_index": 0, + "subject": "subject3", + "sequence": f"k2/{index}", + "take": f"subject3/k2/{index}/cam4", + "frame_id": index, + "annotation_state": ("00", "01", "10", "11")[index % 4], + "hand_size_bucket": ("small", "medium", "large")[index % 3], + "depth_bucket": ("near", "middle", "far")[index % 3], + "absolute_mpjpe_mm": float(index), + } + for index in range(20) + ] + first = select_visualization_frames(records, seed=3) + second = select_visualization_frames(records, seed=3) + assert first == second + assert any("error_p95" in row["reasons"] for row in first) + assert all(row["reasons"] for row in first) + + +def test_mesh_renderer_uses_nearest_surface_z_order(): + image = np.zeros((32, 32, 3), dtype=np.uint8) + faces = np.asarray([[0, 1, 2]], dtype=np.int64) + far = MeshLayer( + np.asarray([[5, 5, 2], [27, 5, 2], [16, 27, 2]], dtype=np.float32), + faces, (255, 0, 0), 1.0, + ) + near = MeshLayer( + np.asarray([[5, 5, 1], [27, 5, 1], [16, 27, 1]], dtype=np.float32), + faces, (0, 255, 0), 1.0, + ) + rendered = render_mesh_layers(image, [far, near]) + assert tuple(rendered[14, 16]) == (0, 255, 0) + + +def test_project_mesh_layers_preserves_camera_z(): + layer = MeshLayer( + np.asarray([[0.1, 0.2, 1.0], [0.0, 0.0, 2.0], [0.1, 0.0, 1.0]], dtype=np.float32), + np.asarray([[0, 1, 2]], dtype=np.int64), (1, 2, 3), + ) + K = np.asarray([[100, 0, 50], [0, 100, 40], [0, 0, 1]], dtype=np.float32) + projected = project_mesh_layers([layer], K)[0].vertices_camera + np.testing.assert_allclose(projected[0], [60, 60, 1]) + np.testing.assert_allclose(projected[:, 2], layer.vertices_camera[:, 2]) + + +def test_balanced_subset_spans_takes_and_is_deterministic(): + records = [ + { + "clip_index": index, + "take": f"take_{index % 4}", + "hand_size_bucket": ("small", "medium")[index % 2], + "depth_bucket": ("near", "middle")[index % 2], + "annotation_state": ("01", "10", "11")[index % 3], + } + for index in range(40) + ] + first = balanced_stratified_indices(records, 20, seed=12) + second = balanced_stratified_indices(records, 20, seed=12) + assert first == second + assert len(first) == len(set(first)) == 20 + take_counts = { + take: sum(records[index]["take"] == take for index in first) + for take in {record["take"] for record in records} + } + assert set(take_counts.values()) == {5} + + +def test_temporal_position_bias_report_preserves_signed_offsets_and_heads(): + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, temporal_position_mode="relative_bias", + temporal_relative_bias_max_distance=2, + )) + model.decoder.temporal[0].relative_position_bias.data[1, 0] = -0.25 + report = temporal_position_bias_report(model) + assert report["mode"] == "relative_bias" + assert report["sign_convention"] == "key_time_minus_query_time" + assert report["layers"][0]["offsets_key_minus_query"] == [-2, -1, 0, 1, 2] + assert report["layers"][0]["shape"] == [4, 5] + assert report["layers"][0]["per_head_bias"][1][0] == -0.25 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_evaluation_audit.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_evaluation_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..1752e0c547048dc71e6139602ac2f9d4b157612a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_evaluation_audit.py @@ -0,0 +1,35 @@ +import csv +import json +import subprocess +import sys +from pathlib import Path + + +def write_csv(path: Path, values: list[float]) -> None: + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=("metric",)) + writer.writeheader() + writer.writerows({"metric": value} for value in values) + + +def test_evaluation_audit_checks_reports_and_csvs(tmp_path: Path): + output = tmp_path / "run" / "best_absolute" + output.mkdir(parents=True) + (output / "evaluation.json").write_text(json.dumps({ + "status": "evaluated", "official_test_used": False, + "split_role": "official_validation", "clips": 2, "frames": 3, + "checkpoint": {"sha256": "abc"}, "metrics": {"error": 1.0}, + }) + "\n", encoding="utf-8") + write_csv(output / "per_hand_frame_metrics.csv", [1.0, 2.0]) + write_csv(output / "per_temporal_transition_metrics.csv", [3.0]) + + subprocess.run([ + sys.executable, "scripts/audit_phase3_evaluations.py", str(tmp_path), + "--expected-evaluations", "1", "--expected-clips", "2", + "--expected-frames", "3", "--expected-frame-rows", "2", + "--expected-transition-rows", "1", + ], check=True) + audit = json.loads((tmp_path / "evaluation_audit.json").read_text()) + assert audit["status"] == "passed" + assert audit["total_frame_rows"] == 2 + assert audit["total_transition_rows"] == 1 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_fallback_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_fallback_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe12dc3413c207af6f57eb30489176674b84776 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_fallback_summary.py @@ -0,0 +1,10 @@ +from scripts.summarize_phase3_fallback import CONDITIONS + + +def test_fallback_conditions_encode_independent_requested_overrides() -> None: + assert CONDITIONS == { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), + } diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_full_validation_launcher.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_full_validation_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..a90361b51153f1187a6afcc2e36c41cdabe66c1c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_full_validation_launcher.py @@ -0,0 +1,115 @@ +from pathlib import Path + +import pytest + +from scripts.run_phase3_full_validation import ( + EvaluationJob, + build_jobs, + checkpoint_roles, + command_for, + load_checkpoint_files, + validation_state_path, + validate_job_grid, +) + + +def test_checkpoint_roles_cover_registered_validation_points() -> None: + roles = checkpoint_roles(Path("runs/example")) + assert [role for role, _ in roles] == [ + "step_025k", "step_050k", "step_075k", "step_100k", + "best_absolute", "best_z", "final", + ] + assert len({path for _, path in roles}) == 7 + + +def test_build_jobs_creates_seven_unique_outputs_per_run(tmp_path: Path) -> None: + matrix = tmp_path / "matrix.csv" + matrix.write_text("config\nconfigs/a.yaml\nconfigs/b.yaml\n", encoding="utf-8") + jobs = build_jobs(matrix, Path("runs"), Path("evaluations")) + assert len(jobs) == 14 + assert len({job.name for job in jobs}) == 14 + assert len({job.output for job in jobs}) == 14 + assert {job.run_name for job in jobs} == {"a", "b"} + + +def test_build_jobs_can_select_one_checkpoint_role(tmp_path: Path) -> None: + matrix = tmp_path / "matrix.csv" + matrix.write_text("config\nconfigs/a.yaml\nconfigs/b.yaml\n", encoding="utf-8") + jobs = build_jobs( + matrix, Path("runs"), Path("evaluations"), roles=("best_absolute",), + ) + assert len(jobs) == 2 + assert {job.role for job in jobs} == {"best_absolute"} + + +def test_build_jobs_uses_explicit_run_name_when_registered(tmp_path: Path) -> None: + matrix = tmp_path / "matrix.csv" + matrix.write_text( + "config,run_name\nconfigs/a.yaml,formal_seed20260716\n", + encoding="utf-8", + ) + jobs = build_jobs( + matrix, Path("runs"), Path("evaluations"), roles=("best_absolute",), + ) + assert jobs[0].run_name == "formal_seed20260716" + assert jobs[0].checkpoint == Path("runs/formal_seed20260716/best.pt") + + +def test_custom_checkpoint_spec_preserves_explicit_role_order(tmp_path: Path) -> None: + spec = tmp_path / "roles.json" + spec.write_text( + '{"tail_step_125k":"step_0125000.pt","tail_final":"step_0150000_final.pt"}' + ) + definitions = load_checkpoint_files(spec) + assert checkpoint_roles(Path("run"), definitions) == ( + ("tail_step_125k", Path("run/step_0125000.pt")), + ("tail_final", Path("run/step_0150000_final.pt")), + ) + + +def test_validate_job_grid_accepts_arbitrary_matrix_size(tmp_path: Path) -> None: + matrix = tmp_path / "matrix.csv" + matrix.write_text( + "config\nconfigs/a.yaml\nconfigs/b.yaml\nconfigs/c.yaml\n", + encoding="utf-8", + ) + roles = ("best_absolute", "best_z") + jobs = build_jobs(matrix, Path("runs"), Path("evaluations"), roles=roles) + assert validate_job_grid(jobs, roles) == 3 + + +def test_validate_job_grid_rejects_duplicate_run_stems(tmp_path: Path) -> None: + matrix = tmp_path / "matrix.csv" + matrix.write_text( + "config\nfirst/a.yaml\nsecond/a.yaml\n", + encoding="utf-8", + ) + jobs = build_jobs( + matrix, Path("runs"), Path("evaluations"), roles=("best_absolute",), + ) + with pytest.raises(ValueError, match="duplicate"): + validate_job_grid(jobs, ("best_absolute",)) + + +def test_command_for_records_missing_modality_overrides() -> None: + job = EvaluationJob( + name="run__best_absolute", run_name="run", role="best_absolute", + config=Path("config.yaml"), checkpoint=Path("best.pt"), + output=Path("evaluation"), + ) + command, environment = command_for( + job, 2, 4, drop_depth=True, drop_k=True, phase4_diagnostics=True, + ) + assert "--drop-depth" in command + assert "--drop-k" in command + assert "--phase4-diagnostics" in command + assert environment["CUDA_VISIBLE_DEVICES"] == "2" + + +def test_validation_state_filename_can_preserve_staged_launches() -> None: + root = Path("evaluations") + assert validation_state_path( + root, "validation_state_best_absolute.json", + ) == root / "validation_state_best_absolute.json" + with pytest.raises(ValueError, match="JSON basename"): + validation_state_path(root, "../state.json") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_long_tail_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_long_tail_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..3b54048f49ddf4de100960f521f7940c80cfc5c0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_long_tail_configs.py @@ -0,0 +1,41 @@ +import csv +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).parents[1] + + +def test_long_tail_configs_only_change_duration_protocol_and_identity() -> None: + for seed in (20260716, 20260717, 20260718): + source_name = f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + tail_name = f"longtail_{source_name}" + source = yaml.safe_load(( + ROOT / f"configs/phase3/photometric/{source_name}.yaml" + ).read_text()) + tail = yaml.safe_load(( + ROOT / f"configs/phase3/long_tail/{tail_name}.yaml" + ).read_text()) + assert tail["data"] == source["data"] + assert tail["model"] == source["model"] + assert tail["loss"] == source["loss"] + assert tail["assets"] == source["assets"] + assert tail["precision"] == source["precision"] + source_protocol = dict(source["protocol"]) + tail_protocol = dict(tail["protocol"]) + assert tail_protocol.pop("max_steps") == 150_000 + assert tail_protocol.pop("lr_schedule_steps") == 100_000 + assert source_protocol.pop("max_steps") == 100_000 + assert tail_protocol == source_protocol + assert tail["experiment"]["registered_axes"] == ["training_duration"] + + +def test_long_tail_matrix_uses_original_final_checkpoints() -> None: + path = ROOT / "artifacts/phase3/reports/long_tail_config_matrix.csv" + with path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + assert len(rows) == 3 + assert {int(row["seed"]) for row in rows} == {20260716, 20260717, 20260718} + assert all(row["resume_checkpoint"].endswith("step_0100000_final.pt") for row in rows) + assert all(int(row["lr_schedule_steps"]) == 100_000 for row in rows) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_long_tail_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_long_tail_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..5c39f38995305cb5205dcc036f5686c00291cc66 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_long_tail_summary.py @@ -0,0 +1,65 @@ +import json + +import pytest + +from scripts.summarize_phase3_long_tail import ( + REFERENCE_ROLE, TAIL_ROLES, load_resume_audit, reference_name, tail_name, +) +from scripts.summarize_phase3_modality import write_csv + + +def test_long_tail_names_and_roles_are_fixed() -> None: + assert reference_name(7) == "photometric_on_geometry_m3_l1_t1_r640x368_s7" + assert tail_name(7) == "longtail_photometric_on_geometry_m3_l1_t1_r640x368_s7" + assert REFERENCE_ROLE == "reference_best_absolute" + assert TAIL_ROLES == ( + "tail_step_125k", "tail_step_150k", "tail_best_absolute", + "tail_best_z", "tail_final", + ) + + +def test_long_tail_resume_audit_requires_exact_150k_state(tmp_path) -> None: + rows = [] + for seed in (20260716, 20260717, 20260718): + rows.append({ + "run": tail_name(seed), "reference_step": 150000, + "resumed_step": 150000, "model_exact": True, + "optimizer_exact": True, "python_rng_exact": True, + "numpy_rng_exact": True, "torch_rng_exact": True, + "cuda_rng_exact": True, + }) + path = tmp_path / "exact_resume_audit.json" + path.write_text(json.dumps({ + "status": "passed", "official_test_used": False, "runs": rows, + })) + assert load_resume_audit(path)["runs"] == 3 + rows[0]["optimizer_exact"] = False + path.write_text(json.dumps({ + "status": "passed", "official_test_used": False, "runs": rows, + })) + with pytest.raises(ValueError, match="invalid long-tail exact-resume audit"): + load_resume_audit(path) + + +def test_long_tail_subgroup_rows_keep_one_csv_schema(tmp_path) -> None: + common = { + "comparison": "tail_best-reference_best", "subgroup_axis": "depth_bucket", + "metric": "absolute_mpjpe_mm", "delta_definition": "lower is better", + "take_equal_mean_delta": None, "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, "seed_20260717_delta": None, + "seed_20260718_delta": None, "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": 10_000, "bootstrap_seed": 20260716, + } + rows = [ + {**common, "subgroup_value": "far", "available": False}, + { + **common, "subgroup_value": "near", "available": True, + "take_equal_mean_delta": -0.1, "take_count": 24, + "observations_per_seed": 100, + }, + ] + output = tmp_path / "subgroups.csv" + write_csv(output, rows) + assert output.read_text().count("\n") == 3 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_modality_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_modality_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..96a46985c650a05a3f41b35e6d5295536035cb21 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_modality_configs.py @@ -0,0 +1,37 @@ +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).parents[1] + + +def load(path: Path) -> dict: + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def model_without_modality_flags(config: dict) -> dict: + model = dict(config["model"]) + model.pop("use_depth") + model.pop("use_rays") + return model + + +def test_modality_configs_change_only_registered_modality_flags() -> None: + for seed in (20260716, 20260717, 20260718): + m0 = load(ROOT / f"configs/phase3/core/core_m0_l1_t1_s{seed}.yaml") + m3 = load(ROOT / f"configs/phase3/core/core_m3_l1_t1_s{seed}.yaml") + m1 = load(ROOT / f"configs/phase3/modality/modality_m1_l1_t1_s{seed}.yaml") + m2 = load(ROOT / f"configs/phase3/modality/modality_m2_l1_t1_s{seed}.yaml") + assert model_without_modality_flags(m0) == model_without_modality_flags(m1) + assert model_without_modality_flags(m0) == model_without_modality_flags(m2) + assert model_without_modality_flags(m0) == model_without_modality_flags(m3) + assert (m0["model"]["use_depth"], m0["model"]["use_rays"]) == (False, False) + assert (m1["model"]["use_depth"], m1["model"]["use_rays"]) == (False, True) + assert (m2["model"]["use_depth"], m2["model"]["use_rays"]) == (True, False) + assert (m3["model"]["use_depth"], m3["model"]["use_rays"]) == (True, True) + for config in (m1, m2): + assert config["experiment"]["matrix"] == "modality_causal" + assert config["experiment"]["layout"] == "L1" + assert config["experiment"]["temporal"] == "T1" + assert config["experiment"]["registered_axes"] == ["modality"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_modality_dropout_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_modality_dropout_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c6156f6b8d54cbe91c2d97f38ed338364e8c7784 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_modality_dropout_configs.py @@ -0,0 +1,28 @@ +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).parents[1] + + +def test_dropout_configs_only_change_registered_training_field() -> None: + for seed in (20260716, 20260717, 20260718): + base = yaml.safe_load( + (ROOT / f"configs/phase3/depth_fusion/depth_geometry_m3_l1_t1_s{seed}.yaml").read_text() + ) + for variant, probability in { + "dropout00_geometry": 0.0, "dropout02_geometry": 0.2, + }.items(): + config = yaml.safe_load( + (ROOT / f"configs/phase3/depth_fusion/depth_{variant}_m3_l1_t1_s{seed}.yaml").read_text() + ) + assert config["data"] == base["data"] + assert config["loss"] == base["loss"] + assert config["assets"] == base["assets"] + assert config["protocol"] == base["protocol"] + model = dict(config["model"]) + assert model.pop("modality_dropout_prob") == probability + assert model == base["model"] + assert config["model"]["depth_mode"] == "geometry" + assert config["experiment"]["registered_axes"] == ["modality_dropout"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_modality_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_modality_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..97e9bf3d60feedb6933c7483283cfc5bc5a4bfe1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_modality_summary.py @@ -0,0 +1,59 @@ +import pytest + +from scripts.summarize_phase3_modality import ( + FRAME_KEY, + aggregate_seed_contrasts, + contrast_take_differences, + run_name, +) + + +def row(index: int, value: float, side: str = "left") -> dict[str, str]: + return { + "clip_index": str(index), "time_index": "0", "take": f"take{index % 2}", + "subject": "s", "sequence": "q", "frame_id": str(index), "side": side, + "annotation_valid": "1", "annotation_state": "11", "hand_size_bucket": "small", + "metric": str(value), + } + + +def test_run_name_selects_reused_and_new_roots() -> None: + assert run_name("M0", 7) == "core_m0_l1_t1_s7" + assert run_name("M3", 7) == "core_m3_l1_t1_s7" + assert run_name("M1", 7) == "modality_m1_l1_t1_s7" + assert run_name("M2", 7) == "modality_m2_l1_t1_s7" + + +def test_contrast_take_differences_computes_interaction_and_subgroup() -> None: + rows = { + "M0": [row(0, 10), row(1, 20, "right")], + "M1": [row(0, 8), row(1, 18, "right")], + "M2": [row(0, 7), row(1, 17, "right")], + "M3": [row(0, 4), row(1, 14, "right")], + } + result = contrast_take_differences( + rows, "metric", {"M3": 1, "M2": -1, "M1": -1, "M0": 1}, FRAME_KEY, + ) + assert result["observation_mean"] == pytest.approx(-1.0) + left = contrast_take_differences( + rows, "metric", {"M1": 1, "M0": -1}, FRAME_KEY, ("side", "left"), + ) + assert left["observation_count"] == 1 + assert left["observation_mean"] == pytest.approx(-2.0) + + +def test_contrast_rejects_misaligned_observations() -> None: + rows = {"M1": [row(0, 1)], "M0": [row(1, 2)]} + with pytest.raises(ValueError, match="identical observation order"): + contrast_take_differences(rows, "metric", {"M1": 1, "M0": -1}, FRAME_KEY) + + +def test_aggregate_seed_contrasts_uses_common_equal_weight_takes() -> None: + seed_results = [ + {"take_means": {"a": value, "b": value + 2}, "observation_mean": value + 1, "observation_count": 4} + for value in (1.0, 2.0, 3.0) + ] + result = aggregate_seed_contrasts(seed_results, seed=3, samples=100) + assert result["take_equal_mean_delta"] == pytest.approx(3.0) + assert result["take_count"] == 2 + assert result["observations_per_seed"] == 4 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_periodic_checkpoint_audit.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_periodic_checkpoint_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..3795d204e095655b79e9cca60e8f974a8203764e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_periodic_checkpoint_audit.py @@ -0,0 +1,96 @@ +import json +import subprocess +import sys +from pathlib import Path + +import torch + + +def test_periodic_checkpoint_audit_uses_isolated_loader(tmp_path: Path): + run_root = tmp_path / "runs" + run_dir = run_root / "example_run" + run_dir.mkdir(parents=True) + torch.save( + {"step": 25_000, "model": {"weight": torch.ones(2)}}, + run_dir / "step_0025000.pt", + ) + (run_dir / "validation.jsonl").write_text( + json.dumps({"step": 25_000, "losses": {"total": 1.25}}) + "\n", + encoding="utf-8", + ) + (run_dir / "run_provenance.json").write_text( + json.dumps({"git_commit": "abc123"}) + "\n", encoding="utf-8", + ) + + subprocess.run( + [ + sys.executable, + "scripts/audit_phase3_periodic_checkpoints.py", + str(run_root), + "--step", "25000", + "--expected-runs", "1", + ], + check=True, + ) + audit = json.loads((run_root / "checkpoint_audit_25k.json").read_text()) + assert audit["status"] == "passed" + assert audit["runs"][0]["run_commit"] == "abc123" + assert audit["runs"][0]["validation_records"] == 1 + assert audit["runs"][0]["model_finite"] is True + + repeated = subprocess.run( + [ + sys.executable, + "scripts/audit_phase3_periodic_checkpoints.py", + str(run_root), "--step", "25000", "--expected-runs", "1", + ], + text=True, capture_output=True, + ) + assert repeated.returncode != 0 + assert "refusing to overwrite" in repeated.stderr + + +def test_periodic_checkpoint_audit_can_isolate_run_prefix(tmp_path: Path): + run_root = tmp_path / "runs" + for name in ("formal_seed16", "health_seed16"): + run_dir = run_root / name + run_dir.mkdir(parents=True) + torch.save( + {"step": 25_000, "model": {"weight": torch.ones(2)}}, + run_dir / "step_0025000.pt", + ) + (run_dir / "validation.jsonl").write_text( + json.dumps({"step": 25_000, "losses": {"total": 1.25}}) + "\n", + encoding="utf-8", + ) + (run_dir / "run_provenance.json").write_text( + json.dumps({"git_commit": name}) + "\n", encoding="utf-8", + ) + subprocess.run( + [ + sys.executable, + "scripts/audit_phase3_periodic_checkpoints.py", + str(run_root), + "--step", "25000", + "--expected-runs", "1", + "--run-prefix", "formal_", + ], + check=True, + ) + audit = json.loads( + (run_root / "checkpoint_audit_formal_25k.json").read_text() + ) + assert audit["run_prefix"] == "formal_" + assert [row["run"] for row in audit["runs"]] == ["formal_seed16"] + + custom = tmp_path / "custom" / "initial6.json" + subprocess.run( + [ + sys.executable, + "scripts/audit_phase3_periodic_checkpoints.py", + str(run_root), "--step", "25000", "--expected-runs", "2", + "--output", str(custom), + ], + check=True, + ) + assert json.loads(custom.read_text())["status"] == "passed" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_photometric_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_photometric_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..fa10275ffb9a37c03af97931f499eb84cef4706a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_photometric_configs.py @@ -0,0 +1,28 @@ +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).parents[1] + + +def test_photometric_configs_change_only_registered_switch(): + for seed in (20260716, 20260717, 20260718): + off = yaml.safe_load(( + ROOT / f"configs/phase3/photometric/photometric_off_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ).read_text()) + on = yaml.safe_load(( + ROOT / f"configs/phase3/photometric/photometric_on_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ).read_text()) + assert off["model"] == on["model"] + assert off["loss"] == on["loss"] + assert off["assets"] == on["assets"] + assert off["protocol"] == on["protocol"] + off_data, on_data = dict(off["data"]), dict(on["data"]) + off_aug = dict(off_data.pop("photometric_augmentation")) + on_aug = dict(on_data.pop("photometric_augmentation")) + assert off_data == on_data + assert off_aug.pop("enabled") is False + assert on_aug.pop("enabled") is True + assert off_aug == on_aug + assert off["experiment"]["registered_axes"] == ["photometric_augmentation"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_photometric_fallback_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_photometric_fallback_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..108a3492111377ac34615fe7a7bce3c7c8403380 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_photometric_fallback_summary.py @@ -0,0 +1,43 @@ +import json + +import pytest + +from scripts.summarize_phase3_photometric_fallback import CONDITIONS, load_report + + +def test_photometric_fallback_conditions_are_independent() -> None: + assert CONDITIONS == { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), + } + + +def test_load_report_rejects_annotation_or_override_mismatch(tmp_path) -> None: + path = tmp_path / "evaluation.json" + report = { + "status": "evaluated", + "official_test_used": False, + "split_role": "official_validation", + "clips": 1495, + "config": { + "seed": 20260716, + "experiment": { + "matrix": "photometric_augmentation", + "variant": "photometric_on_r640x368", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + }, + "data": { + "resolution_hw": [368, 640], + "photometric_augmentation": {"enabled": True}, + }, + }, + "inference_modality_override": {"drop_depth": True, "drop_k": False}, + } + path.write_text(json.dumps(report), encoding="utf-8") + assert load_report(path, "on", 20260716, "drop_depth") == report + with pytest.raises(ValueError, match="invalid photometric fallback report"): + load_report(path, "on", 20260716, "drop_k") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_photometric_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_photometric_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..4457a38f5bca7bc12306e9f05b8d5aff44d6c2a5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_photometric_summary.py @@ -0,0 +1,68 @@ +import json + +import pytest + +from scripts.summarize_phase3_photometric import ( + audit_off_reference, + canonical_scientific_record, + load_resume_audit, + run_name, +) + + +def test_run_name_encodes_only_registered_variant_and_seed() -> None: + assert run_name("off", 7) == "photometric_off_geometry_m3_l1_t1_r640x368_s7" + assert run_name("on", 8) == "photometric_on_geometry_m3_l1_t1_r640x368_s8" + with pytest.raises(ValueError, match="unknown photometric variant"): + run_name("other", 9) + + +def test_scientific_record_excludes_only_runtime_and_new_diagnostics() -> None: + reference = {"step": 1, "losses": {"total": 2.0}} + candidate = { + **reference, + "timestamp": "later", + "frames_per_s": 10.0, + "peak_vram_gib": 3.0, + "photometric_augmentation": {"applied_fraction": 0.0}, + } + assert canonical_scientific_record(reference) == canonical_scientific_record(candidate) + candidate["losses"] = {"total": 2.1} + assert canonical_scientific_record(reference) != canonical_scientific_record(candidate) + + +def test_off_reference_audit_rejects_a_scientific_difference(tmp_path) -> None: + off = tmp_path / "off.jsonl" + reference = tmp_path / "reference.jsonl" + off.write_text(json.dumps({"step": 1, "loss": 2}) + "\n", encoding="utf-8") + reference.write_text(json.dumps({"step": 1, "loss": 3}) + "\n", encoding="utf-8") + with pytest.raises(ValueError, match="differs at record 1"): + audit_off_reference(off, reference) + + +def test_resume_audit_requires_all_exact_states(tmp_path) -> None: + path = tmp_path / "audit.json" + records = [] + for seed in (20260716, 20260717, 20260718): + records.append({ + "run": run_name("on", seed), + "reference_step": 100000, + "resumed_step": 100000, + "model_exact": True, + "optimizer_exact": True, + "python_rng_exact": True, + "numpy_rng_exact": True, + "torch_rng_exact": True, + "cuda_rng_exact": True, + }) + path.write_text(json.dumps({ + "status": "passed", "official_test_used": False, "runs": records, + }), encoding="utf-8") + result = load_resume_audit(path, "on") + assert result["runs"] == 3 + records[0]["model_exact"] = False + path.write_text(json.dumps({ + "status": "passed", "official_test_used": False, "runs": records, + }), encoding="utf-8") + with pytest.raises(ValueError, match="invalid on exact-resume audit"): + load_resume_audit(path, "on") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_resolution_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_resolution_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..3d0df2e243aba4d6008bf073c0388cea9bd83ccd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_resolution_configs.py @@ -0,0 +1,34 @@ +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).parents[1] + + +def test_resolution_configs_only_change_resolution() -> None: + for seed in (20260716, 20260717, 20260718): + base = yaml.safe_load(( + ROOT + / f"configs/phase3/depth_fusion/depth_dropout005_geometry_m3_l1_t1_s{seed}.yaml" + ).read_text()) + config = yaml.safe_load(( + ROOT + / f"configs/phase3/resolution/depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ).read_text()) + assert config["model"] == base["model"] + assert config["loss"] == base["loss"] + assert config["assets"] == base["assets"] + protocol = dict(config["protocol"]) + assert protocol.pop("validation_subset_manifest").endswith( + "resolution_640x368/validation_subset_256.json" + ) + base_protocol = dict(base["protocol"]) + base_protocol.pop("validation_subset_manifest") + assert protocol == base_protocol + data = dict(config["data"]) + assert data.pop("resolution_hw") == [368, 640] + base_data = dict(base["data"]) + assert base_data.pop("resolution_hw") == [288, 512] + assert data == base_data + assert config["experiment"]["registered_axes"] == ["input_resolution"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_resolution_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_resolution_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..5f14ca0048af157076b17c90aad64ecfd446d398 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_resolution_summary.py @@ -0,0 +1,21 @@ +import pytest + +from scripts.summarize_phase3_resolution import ( + RESOLUTIONS, add_normalized_2d_columns, run_name, +) + + +def test_resolution_summary_names_and_normalizes_pixels() -> None: + assert run_name("r512x288", 7) == "depth_dropout005_geometry_m3_l1_t1_s7" + assert run_name("r640x368", 7).endswith("r640x368_s7") + rows = add_normalized_2d_columns([{ + "direct_2d_error_px": "10", + "mano_projected_2d_error_px": "20", + "direct_mano_2d_consistency_px": "", + }], "r640x368") + assert rows[0]["direct_2d_error_px_at_512_width"] == "8.0" + assert rows[0]["mano_projected_2d_error_px_at_512_width"] == "16.0" + assert rows[0]["direct_mano_2d_consistency_px_at_512_width"] == "" + assert RESOLUTIONS["r640x368"] == (368, 640) + with pytest.raises(ValueError): + run_name("unknown", 7) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_resume_verification.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_resume_verification.py new file mode 100644 index 0000000000000000000000000000000000000000..184f7ac45602a6f9d299b66ab8e68bc3b6bd7001 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_resume_verification.py @@ -0,0 +1,82 @@ +import json +import subprocess +import sys +from pathlib import Path + +import torch + +from scripts.run_phase3_matrix import command_for + + +def test_matrix_resume_command_keeps_registered_schedule(tmp_path: Path): + resume = tmp_path / "step_0075000.pt" + subset = tmp_path / "validation_subset.json" + command, environment = command_for( + Path("config.yaml"), tmp_path / "output", 2, resume, subset, + ) + assert command[command.index("--resume") + 1] == str(resume) + assert command[command.index("--max-steps") + 1] == "100000" + assert command[command.index("--validation-interval") + 1] == "5000" + assert command[command.index("--validation-subset-manifest") + 1] == str(subset) + assert environment["CUDA_VISIBLE_DEVICES"] == "2" + + +def test_exact_resume_comparison_accepts_identical_training_state(tmp_path: Path): + reference_root = tmp_path / "reference" + resumed_root = tmp_path / "resumed" + run_name = "run_a" + (reference_root / run_name).mkdir(parents=True) + (resumed_root / run_name).mkdir(parents=True) + state = { + "step": 100_000, + "model": {"weight": torch.arange(3)}, + "optimizer": {"state": {0: {"step": torch.tensor(2)}}}, + "python_rng": (3, (1, 2, 3), None), + "numpy_rng": ("MT19937", __import__("numpy").arange(3), 2, 0, 0.0), + "torch_rng": torch.arange(4, dtype=torch.uint8), + "cuda_rng": [torch.arange(2, dtype=torch.uint8)], + } + for root in (reference_root, resumed_root): + torch.save(state, root / run_name / "step_0100000_final.pt") + + subprocess.run( + [ + sys.executable, "scripts/compare_phase3_resume.py", + str(reference_root), str(resumed_root), "--expected-runs", "1", + ], + check=True, + ) + audit = json.loads((resumed_root / "exact_resume_audit.json").read_text()) + assert audit["status"] == "passed" + assert audit["runs"][0]["model_exact"] is True + assert audit["runs"][0]["optimizer_exact"] is True + + +def test_exact_resume_comparison_accepts_custom_final_step(tmp_path: Path): + reference_root = tmp_path / "reference" + resumed_root = tmp_path / "resumed" + run_name = "run_tail" + state = { + "step": 150_000, + "model": {"weight": torch.arange(2)}, + "optimizer": {"state": {}}, + "python_rng": (3, (1, 2), None), + "numpy_rng": ("MT19937", __import__("numpy").arange(2), 1, 0, 0.0), + "torch_rng": torch.arange(3, dtype=torch.uint8), + "cuda_rng": [torch.arange(2, dtype=torch.uint8)], + } + for root in (reference_root, resumed_root): + (root / run_name).mkdir(parents=True) + torch.save(state, root / run_name / "step_0150000_final.pt") + subprocess.run( + [ + sys.executable, "scripts/compare_phase3_resume.py", + str(reference_root), str(resumed_root), "--expected-runs", "1", + "--checkpoint-name", "step_0150000_final.pt", + "--expected-step", "150000", + ], + check=True, + ) + audit = json.loads((resumed_root / "exact_resume_audit.json").read_text()) + assert audit["status"] == "passed" + assert audit["runs"][0]["reference_step"] == 150_000 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_temporal_position_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_temporal_position_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..cc92ec134e2d00ea9961455fa44ce362c9076497 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_temporal_position_configs.py @@ -0,0 +1,35 @@ +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).parents[1] + + +def load(path: Path) -> dict: + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def test_p1_changes_only_registered_temporal_position_fields() -> None: + for seed in (20260716, 20260717, 20260718): + p0 = load(ROOT / f"configs/phase3/core/core_m3_l1_t1_s{seed}.yaml") + p1 = load(ROOT / f"configs/phase3/temporal_position/temporal_p1_m3_l1_t1_s{seed}.yaml") + assert p1["data"] == p0["data"] + assert p1["loss"] == p0["loss"] + assert p1["assets"] == p0["assets"] + assert p1["precision"] == p0["precision"] + assert p1["protocol"] == p0["protocol"] + p1_model = dict(p1["model"]) + assert p1_model.pop("temporal_position_mode") == "relative_bias" + assert p1_model.pop("temporal_relative_bias_max_distance") == 15 + assert p1_model == p0["model"] + assert p1["experiment"] == { + "phase": 3, + "matrix": "temporal_position", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "position": "P1", + "registered_axes": ["temporal_position"], + "reference": "P0_no_temporal_position_reused_core_m3_l1_t1", + } diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_temporal_position_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_temporal_position_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..3f47461bfed93f07710c228b22ef628daecab8d0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_temporal_position_summary.py @@ -0,0 +1,35 @@ +import pytest + +from scripts.summarize_phase3_temporal_position import ( + flatten_bias_report, + position_run_name, +) + + +def test_position_run_name_maps_reused_and_new_runs() -> None: + assert position_run_name("P0", 7) == "core_m3_l1_t1_s7" + assert position_run_name("P1", 7) == "temporal_p1_m3_l1_t1_s7" + with pytest.raises(ValueError, match="unknown"): + position_run_name("P2", 7) + + +def test_flatten_bias_report_preserves_layer_head_offset_mapping() -> None: + report = { + "temporal_position_bias": { + "mode": "relative_bias", + "layers": [{ + "layer": 2, + "offsets_key_minus_query": [-1, 0, 1], + "per_head_bias": [[0.1, 0.2, 0.3], [-0.1, -0.2, -0.3]], + }], + }, + } + rows = flatten_bias_report("P1", 9, report) + assert len(rows) == 6 + assert rows[0] == { + "position": "P1", "seed": 9, "layer": 2, "head": 0, + "offset_key_minus_query": -1, "bias": 0.1, + } + assert rows[-1]["head"] == 1 + assert rows[-1]["offset_key_minus_query"] == 1 + assert rows[-1]["bias"] == -0.3 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_validation_subset_adaptation.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_validation_subset_adaptation.py new file mode 100644 index 0000000000000000000000000000000000000000..e230e37cdd87195946eccf406f21b32de3fa117d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase3_validation_subset_adaptation.py @@ -0,0 +1,28 @@ +import json +import subprocess +import sys +from pathlib import Path + + +ROOT = Path(__file__).parents[1] + + +def test_validation_subset_adaptation_preserves_selection(tmp_path: Path) -> None: + source = ROOT / "artifacts/phase3/validation_subset/validation_subset_256.json" + output = tmp_path / "validation_subset.json" + subprocess.run([ + sys.executable, + str(ROOT / "scripts/adapt_phase3_validation_subset.py"), + "--source", str(source), + "--output", str(output), + "--resolution-hw", "368", "640", + ], check=True) + before = json.loads(source.read_text()) + after = json.loads(output.read_text()) + assert after["clip_indices"] == before["clip_indices"] + assert after["take_counts"] == before["take_counts"] + assert after["stratum_counts"] == before["stratum_counts"] + assert after["dataset_contract"] == { + **before["dataset_contract"], "resolution_hw": [368, 640], + } + assert after["parent_selection_manifest_sha256"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_a1_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_a1_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..b13d39c70ce073459ee065af642e6680b9f425cd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_a1_summary.py @@ -0,0 +1,51 @@ +import numpy as np + +from scripts.summarize_phase4_a1 import aggregate_predictions, group_masks + + +def test_aggregate_predictions_uses_per_frame_seed_mean() -> None: + rows = {} + for seed, value in ((20260716, 1.0), (20260717, 2.0), (20260718, 3.0)): + row = {} + for variant in ("coarse", "control", "local"): + for metric in ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", + ): + row[f"{variant}_{metric}"] = str(value) + rows[seed] = [row] + aggregated = aggregate_predictions(rows) + assert aggregated["local"]["translation_z_mae_mm"][0] == 2.0 + + +def test_group_masks_keep_farthest_observed_distinct_from_unavailable_far() -> None: + rows = [ + { + "side": "left", + "hand_size_px": "50", + "wrist_depth_m": "0.55", + "bimanual_asymmetry_bucket": "strong", + "clip_index": "7", + }, + { + "side": "right", + "hand_size_px": "100", + "wrist_depth_m": "0.40", + "bimanual_asymmetry_bucket": "balanced", + "clip_index": "8", + }, + ] + challenge = { + "thresholds": {"farthest_observed_wrist_depth_p80_m": 0.53}, + "clip_indices": [7], + } + masks = group_masks(rows, challenge) + np.testing.assert_array_equal(masks["farthest_observed"], (True, False)) + np.testing.assert_array_equal(masks["challenge"], (True, False)) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_b0_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_b0_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..fa6330271e70920564275fb0af97ed73f02ba16d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_b0_configs.py @@ -0,0 +1,46 @@ +import yaml + +from scripts.generate_phase4_b0_configs import AXIS_WEIGHTS, b0_config + + +def base_config() -> dict: + return yaml.safe_load(""" +name: reference +seed: 1 +loss: + translation: 10.0 +protocol: + max_steps: 150000 + lr_schedule_steps: 100000 + warmup_steps: 500 + checkpoint_interval: 25000 + validation_interval: 5000 +""") + + +def test_b0_formal_changes_only_registered_loss_fields_and_metadata() -> None: + base = base_config() + config = b0_config(base, 20260716, "formal") + assert config["loss"]["translation_mode"] == "axis_huber" + assert config["loss"]["translation_axis_weights"] == list(AXIS_WEIGHTS) + assert sum(config["loss"]["translation_axis_weights"]) / 3 == 1.0 + assert config["protocol"] == {**base["protocol"], "max_steps": 100_000} + assert config["name"].endswith("_formal100k") + assert config["protocol"]["max_steps"] == 100_000 + assert config["protocol"]["lr_schedule_steps"] == 100_000 + assert "translation_mode" not in base["loss"] + + +def test_b0_health_is_explicitly_short_and_not_formal() -> None: + config = b0_config(base_config(), 20260716, "health") + assert config["protocol"]["max_steps"] == 25_000 + assert config["protocol"]["lr_schedule_steps"] == 25_000 + assert config["experiment"]["stage"] == "health" + + +def test_b0_smoke_and_tiny_do_not_claim_a_validation_subset() -> None: + base = base_config() + base["protocol"]["validation_subset_manifest"] = "fixed.json" + for stage in ("smoke", "tiny"): + config = b0_config(base, 20260716, stage) + assert "validation_subset_manifest" not in config["protocol"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_b2_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_b2_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3cff5c7455d9c94212169e8ed82e9214d6f01a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_b2_configs.py @@ -0,0 +1,47 @@ +import yaml + +from scripts.generate_phase4_b2_configs import ( + FULL_SAMPLER_MANIFEST, + TINY_SAMPLER_MANIFEST, + b2_config, +) + + +def base_config() -> dict: + return yaml.safe_load(""" +name: reference +seed: 1 +loss: + translation: 10.0 +protocol: + max_steps: 150000 + lr_schedule_steps: 100000 + warmup_steps: 500 + checkpoint_interval: 25000 + validation_interval: 5000 + validation_subset_manifest: fixed.json +""") + + +def test_b2_formal_changes_only_sampler_metadata_and_maximum_step() -> None: + base = base_config() + config = b2_config(base, 20260716, "formal") + assert config["loss"] == base["loss"] + assert config["sampling"] == { + "mode": "balanced", "manifest": str(FULL_SAMPLER_MANIFEST), + } + assert config["protocol"] == {**base["protocol"], "max_steps": 100_000} + assert config["name"].endswith("_formal100k") + assert "sampling" not in base + + +def test_b2_short_stages_obey_validation_and_manifest_contracts() -> None: + smoke = b2_config(base_config(), 20260716, "smoke") + tiny = b2_config(base_config(), 20260716, "tiny") + health = b2_config(base_config(), 20260716, "health") + assert "validation_subset_manifest" not in smoke["protocol"] + assert "validation_subset_manifest" not in tiny["protocol"] + assert health["protocol"]["validation_subset_manifest"] == "fixed.json" + assert smoke["sampling"]["manifest"] == str(FULL_SAMPLER_MANIFEST) + assert tiny["sampling"]["manifest"] == str(TINY_SAMPLER_MANIFEST) + assert health["sampling"]["manifest"] == str(FULL_SAMPLER_MANIFEST) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_evaluation.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..d1382fecc40234f6af8a6a0f8b285fd971f7c34b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_evaluation.py @@ -0,0 +1,65 @@ +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.phase4 import ( + bimanual_asymmetry, + find_failure_intervals, + local_depth_statistics, + summarize_group_metrics, +) + + +def test_distribution_summary_reports_upper_tail_cvar95() -> None: + summary = distribution_summary(range(1, 101)) + assert summary["p95"] == 95.05 + assert summary["cvar95"] == 98.0 + + +def test_local_depth_statistics_uses_aligned_conservative_region() -> None: + depth = np.full((20, 30), 0.5, dtype=np.float32) + valid = np.ones_like(depth, dtype=bool) + valid[:2] = False + joints = np.asarray([[10.0, 8.0], [18.0, 14.0]], dtype=np.float32) + report = local_depth_statistics( + depth, valid, joints, margin_fraction=0.0, minimum_size_px=4, + ) + assert report["valid_fraction"] == 1.0 + assert report["depth_median_m"] == 0.5 + assert report["depth_discontinuity_m"] == 0.0 + + +def test_asymmetry_thresholds_are_fixed_and_side_agnostic() -> None: + strong = bimanual_asymmetry((100.0, 45.0), (0.45, 0.70)) + assert strong["bimanual_asymmetry_bucket"] == "strong" + assert np.isclose(strong["right_minus_left_depth_m"], 0.25) + balanced = bimanual_asymmetry((80.0, 75.0), (0.50, 0.55)) + assert balanced["bimanual_asymmetry_bucket"] == "balanced" + + +def test_failure_intervals_do_not_cross_frame_gaps() -> None: + rows = [ + { + "take": "subject3/o2/3/cam4", + "side": "right", + "frame_id": frame, + "annotation_valid": 1, + "translation_z_mae_mm": value, + } + for frame, value in ((1, 45), (2, 50), (3, 55), (5, 80), (6, 90), (7, 100)) + ] + intervals = find_failure_intervals( + rows, metric="translation_z_mae_mm", threshold=40.0, + ) + assert [(row["start_frame"], row["end_frame"]) for row in intervals] == [(5, 7), (1, 3)] + + +def test_group_summary_keeps_left_right_and_all_views() -> None: + rows = [ + {"take": "a", "side": "left", "absolute_mpjpe_mm": 10.0}, + {"take": "a", "side": "right", "absolute_mpjpe_mm": 30.0}, + ] + summary = summarize_group_metrics(rows, ("absolute_mpjpe_mm",), ("take",)) + lookup = {(row["group_value"], row["side"]): row for row in summary} + assert lookup[("a", "all")]["mean"] == 20.0 + assert lookup[("a", "left")]["mean"] == 10.0 + assert lookup[("a", "right")]["mean"] == 30.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_local_depth.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..5da8e5aabdaadb183434065792f82b01e3ab1dd7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_local_depth.py @@ -0,0 +1,121 @@ +import numpy as np +import torch + +from foundation_hand.evaluation.local_depth import ( + ANCHOR_JOINTS, + BBOX_MARGINS, + WINDOW_RADII, + BoundedZResidualRegressor, + oracle_local_depth_features, +) +from scripts.fit_phase4_oracle_local_depth import ( + padded_control, + stable_take_holdout, + temporal_metrics, + variant_metrics, +) + + +def test_oracle_local_depth_features_are_finite_and_do_not_need_gt_wrist_depth() -> None: + height, width = 72, 128 + depth = np.full((height, width), 0.6, dtype=np.float32) + valid = np.ones_like(depth, dtype=bool) + joints = np.stack((np.linspace(30, 80, 21), np.linspace(20, 50, 21)), axis=-1).astype(np.float32) + K = np.asarray([[100, 0, 64], [0, 100, 36], [0, 0, 1]], dtype=np.float32) + features = oracle_local_depth_features( + depth, valid, joints, K, np.asarray([0.0, 0.0, 0.5], dtype=np.float32), 1, + ) + expected_local_only = (len(ANCHOR_JOINTS) * len(WINDOW_RADII) + len(BBOX_MARGINS)) * 14 + assert features.control.shape == (14,) + assert features.local.shape == (14 + expected_local_only,) + assert len(features.local_names) == features.local.size + assert np.isfinite(features.local).all() + assert features.local_valid_fraction == 1.0 + assert features.local_depth_discontinuity_m == 0.0 + + +def test_missing_depth_is_encoded_by_validity_without_nan() -> None: + depth = np.zeros((32, 32), dtype=np.float32) + valid = np.zeros_like(depth, dtype=bool) + joints = np.full((21, 2), 16.0, dtype=np.float32) + K = np.asarray([[50, 0, 16], [0, 50, 16], [0, 0, 1]], dtype=np.float32) + features = oracle_local_depth_features( + depth, valid, joints, K, np.asarray([0.0, 0.0, 0.5], dtype=np.float32), 0, + ) + assert np.isfinite(features.local).all() + assert features.local_valid_fraction == 0.0 + + +def test_bounded_residual_regressor_starts_as_exact_coarse_reference() -> None: + model = BoundedZResidualRegressor(10, hidden_dim=16, max_residual_m=0.15) + output = model(torch.randn(8, 10)) + torch.testing.assert_close(output, torch.zeros_like(output)) + loss = (output - 0.05).square().mean() + loss.backward() + assert model.network[-1].weight.grad is not None + assert torch.isfinite(model.network[-1].weight.grad).all() + + +def test_control_padding_preserves_same_input_dimension_without_depth() -> None: + control = np.arange(12, dtype=np.float32).reshape(3, 4) + padded = padded_control(control, 9) + np.testing.assert_array_equal(padded[:, :4], control) + np.testing.assert_array_equal(padded[:, 4:], 0.0) + + +def test_take_holdout_is_deterministic_and_never_splits_take() -> None: + takes = ["subject1/a/1/cam4", "subject1/a/1/cam4", "subject2/b/2/cam4"] + first = stable_take_holdout(takes) + second = stable_take_holdout(takes) + np.testing.assert_array_equal(first, second) + assert first[0] == first[1] + + +def test_uniform_z_residual_preserves_root_relative_and_direct_2d() -> None: + coarse_joints = np.zeros((2, 21, 3), dtype=np.float32) + coarse_joints[..., 2] = 0.5 + coarse_joints[:, :, 0] = np.linspace(-0.02, 0.02, 21) + target_joints = coarse_joints.copy() + target_joints[..., 2] += np.asarray((0.05, -0.03), dtype=np.float32)[:, None] + K = np.repeat( + np.asarray([[[500, 0, 320], [0, 500, 184], [0, 0, 1]]], dtype=np.float32), + 2, + axis=0, + ) + target_2d = np.stack([ + 500 * target_joints[..., 0] / target_joints[..., 2] + 320, + 500 * target_joints[..., 1] / target_joints[..., 2] + 184, + ], axis=-1) + arrays = { + "coarse_translation_m": coarse_joints[:, 0].copy(), + "target_translation_m": target_joints[:, 0].copy(), + "coarse_joints_m": coarse_joints, + "target_joints_m": target_joints, + "K_resized": K, + "target_joints_2d_px": target_2d, + "direct_joints_2d_px": target_2d.copy(), + } + coarse = variant_metrics(arrays, np.zeros(2, dtype=np.float32)) + refined = variant_metrics(arrays, np.asarray((0.05, -0.03), dtype=np.float32)) + np.testing.assert_allclose(refined["absolute_mpjpe_mm"], 0.0, atol=1e-4) + np.testing.assert_allclose( + refined["root_relative_mpjpe_mm"], coarse["root_relative_mpjpe_mm"], atol=1e-5, + ) + np.testing.assert_array_equal(refined["direct_2d_error_px"], coarse["direct_2d_error_px"]) + + +def test_temporal_metrics_do_not_cross_frame_gaps() -> None: + metadata = [ + {"take": "s/a/1/cam4", "side": "right", "frame_id": value} + for value in (1, 2, 4) + ] + target = np.zeros((3, 3), dtype=np.float32) + wrist = np.zeros((3, 3), dtype=np.float32) + wrist[:, 2] = (0.0, 0.01, 1.0) + output = temporal_metrics( + metadata, + target, + {"coarse": {"predicted_wrist_xyz_m": wrist}}, + ) + assert output["coarse"]["wrist_velocity_error_mm_per_frame"].shape == (1,) + assert output["coarse"]["wrist_acceleration_error_mm_per_frame2"].shape == (0,) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_wave0_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_wave0_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..e35bc21f7235b209a2f7f07a171f76076ee26306 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase4_wave0_summary.py @@ -0,0 +1,42 @@ +from scripts.summarize_phase4_wave0 import classify_failure, select_challenge_subset + + +def diagnostic_row(index: int, *, z: float, root: float = 10.0, direct: float = 5.0): + return { + "clip_index": index, + "time_index": 0, + "take": f"subject3/o2/{index % 8}/cam4", + "frame_id": index, + "side": "right" if index % 2 else "left", + "annotation_valid": 1, + "action_label": 1 + index % 3, + "action_name": "action", + "hand_size_px": 30.0 + index, + "hand_size_bucket": "small" if index < 20 else "medium", + "wrist_depth_m": 0.4 + index / 200.0, + "bimanual_asymmetry_bucket": "strong" if index % 5 == 0 else "balanced", + "absolute_mpjpe_mm_mean": z + 5.0, + "translation_z_mae_mm_mean": z, + "root_relative_mpjpe_mm_mean": root, + "direct_2d_error_px_mean": direct, + "wrong_side_preference_mean": 0.0, + } + + +def test_failure_taxonomy_separates_z_from_articulation_and_mixed() -> None: + assert classify_failure(diagnostic_row(0, z=50.0)) == "z_translation_dominant" + assert classify_failure(diagnostic_row(1, z=10.0, root=35.0)) == "articulation_dominant" + assert classify_failure(diagnostic_row(2, z=50.0, root=35.0)) == "mixed_failure" + + +def test_challenge_selection_is_deterministic_and_unique() -> None: + rows = [diagnostic_row(index, z=float(index)) for index in range(200)] + first = select_challenge_subset(rows, seed=7, target_clips=128) + second = select_challenge_subset(rows, seed=7, target_clips=128) + assert first == second + indices, samples, thresholds = first + assert len(indices) == len(set(indices)) == len(samples) == 128 + assert thresholds["farthest_observed_wrist_depth_p80_m"] > 0.5 + reasons = {reason for sample in samples for reason in sample["reasons"]} + assert "high_z_error" in reasons + assert "same_action_low_z_matched_control" in reasons diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_causal_state.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..0b7a506e56f478ea5330f7fc93125a2662044004 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_causal_state.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import numpy as np + +from foundation_hand.evaluation.causal_state import ( + causal_constant_velocity_kalman, + measurement_uncertainty_multiplier, +) + + +def filter_values(values: np.ndarray, **kwargs) -> np.ndarray: + measurement = np.stack((values, values), axis=1) + result, _ = causal_constant_velocity_kalman( + measurement, + frame_id=np.arange(len(values)), + valid=np.ones(len(values), dtype=bool), + measurement_available=np.ones_like(measurement, dtype=bool), + process_sigma_m_per_frame2=0.002, + measurement_sigma_m=0.01, + **kwargs, + ) + return result[:, 0] + + +def test_constant_velocity_filter_is_causal_and_preserves_constant_signal() -> None: + values = np.full(20, 0.75, dtype=np.float32) + np.testing.assert_allclose(filter_values(values), values, atol=1e-7) + + changed = values.copy() + changed[10:] = 0.9 + prefix = filter_values(values[:10]) + np.testing.assert_array_equal(filter_values(changed)[:10], prefix) + + +def test_filter_resets_at_frame_discontinuity() -> None: + measurement = np.asarray(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), dtype=np.float32) + filtered, _ = causal_constant_velocity_kalman( + measurement, + frame_id=np.asarray((0, 1, 8)), + valid=np.ones(3, dtype=bool), + measurement_available=np.ones_like(measurement, dtype=bool), + process_sigma_m_per_frame2=0.002, + measurement_sigma_m=0.01, + ) + assert filtered[1, 0] < 1.0 + assert filtered[2, 0] == 5.0 + + +def test_filter_resets_at_clip_boundary() -> None: + measurement = np.asarray(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), dtype=np.float32) + filtered, _ = causal_constant_velocity_kalman( + measurement, + frame_id=np.asarray((0, 1, 2)), + segment_id=np.asarray((4, 4, 5)), + valid=np.ones(3, dtype=bool), + measurement_available=np.ones_like(measurement, dtype=bool), + process_sigma_m_per_frame2=0.002, + measurement_sigma_m=0.01, + ) + assert filtered[1, 0] < 1.0 + assert filtered[2, 0] == 5.0 + + +def test_larger_uncertainty_reduces_measurement_update() -> None: + values = np.asarray((0.0, 0.0, 1.0), dtype=np.float32) + low = filter_values(values, uncertainty_multiplier=np.ones((3, 2))) + high = filter_values(values, uncertainty_multiplier=np.asarray(((1, 1), (1, 1), (5, 5)))) + assert high[-1] < low[-1] + + +def test_uncertainty_multiplier_is_bounded_and_quality_aware() -> None: + good = measurement_uncertainty_multiplier( + np.asarray([1.0]), np.asarray([1.0]), np.asarray([0.0]), + np.asarray([1.0]), np.asarray([1.0]), 2.0, + ) + poor = measurement_uncertainty_multiplier( + np.asarray([0.0]), np.asarray([0.0]), np.asarray([0.1]), + np.asarray([0.0]), np.asarray([0.0]), 2.0, + ) + assert good[0] == 1.0 + assert 1.0 < poor[0] <= 5.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_oof_config_matrix.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_oof_config_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..7174130458ec0097d075fe0921f52de52159d391 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_oof_config_matrix.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +FOLDS = { + "subject1": ( + 0, + "0b4fe0e970ab7db45a18176834c54586a3d613dd2b1c063ea04d5d8ea6e96aac", + "e5f1c714e64cbd86b6b604716c44143e2cd6e16aee6445033e46ef4333949293", + ), + "subject2": ( + 1, + "7a21c688a3f624e13df580fe485c6795945bbef4d4412864c2e508ffc990a515", + "43f38def2d0651ae655cfba36f55666bcacbba2af2221d776bbc20c9f7aaed0c", + ), + "subject3": ( + 2, + "1eaf0e571899d9469c4c5f054ade2e6a7d9d15c0acba62077ab938077ab62a65", + "363e9af06a074eef0c3861f5ec2e11d0fdb2159ac857644d3285e6bc93caa670", + ), +} + + +def test_phase5_oof_config_matrix_covers_all_seed_fold_pairs() -> None: + root = Path("configs/phase5/stage2") + observed = set() + normalized = [] + for subject, (fold, train_hash, heldout_hash) in FOLDS.items(): + for seed in SEEDS: + path = root / f"phase5_s2_oof_{subject}_p005_geometry_r640x368_s{seed}.yaml" + config = yaml.safe_load(path.read_text(encoding="utf-8")) + experiment = config["experiment"] + assert config["name"] == path.stem + assert config["seed"] == seed + assert experiment["oof_fold"] == fold + assert experiment["heldout_subject"] == subject + assert experiment["train_manifest_sha256"] == train_hash + assert experiment["heldout_manifest_sha256"] == heldout_hash + assert experiment["checkpoint_rule"] == "fixed_final_100k_no_heldout_selection" + assert config["protocol"]["max_steps"] == 100_000 + assert config["model"]["modality_dropout_prob"] == 0.05 + observed.add((fold, seed)) + + comparable = dict(config) + comparable.pop("name") + comparable.pop("seed") + comparable["experiment"] = dict(experiment) + for key in ( + "oof_fold", "heldout_subject", "train_manifest_sha256", + "heldout_manifest_sha256", + ): + comparable["experiment"].pop(key) + normalized.append(comparable) + + assert observed == {(fold, seed) for fold in range(3) for seed in SEEDS} + assert all(config == normalized[0] for config in normalized[1:]) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_stage5_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_stage5_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..64826ede4f908c8125491178d57f3c56e98015e7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_stage5_configs.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).resolve().parents[1] + + +def load(name: str) -> dict: + path = ROOT / "configs" / "phase5" / "stage5" / name + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def test_stage5_structured_screen_has_matched_control() -> None: + structured = load("phase5_s5_structured_refine25k_p005_r640x368_s20260716.yaml") + control = load("phase5_s5_matched_coarse_continue25k_p005_r640x368_s20260716.yaml") + assert structured["seed"] == control["seed"] == 20260716 + assert structured["experiment"]["coarse_checkpoint_sha256"] == control[ + "experiment" + ]["coarse_checkpoint_sha256"] + for section in ("data", "loss", "assets", "precision", "protocol"): + assert structured[section] == control[section] + candidate_model = dict(structured["model"]) + assert candidate_model.pop("structured_hand_refinement") is True + assert candidate_model.pop("structured_refinement_detach_locations") is True + assert candidate_model.pop("structured_deformable_samples") == 4 + assert candidate_model == control["model"] + assert control["experiment"]["matched_control_initialization"] is True + assert structured["protocol"] == { + "max_steps": 25000, + "num_workers": 4, + "checkpoint_interval": 25000, + "validation_interval": 5000, + "validation_batches": 256, + "learning_rate": 5e-6, + "min_learning_rate": 5e-6, + "warmup_steps": 0, + "early_stopping_patience": 0, + "validation_subset_manifest": "artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json", + "lr_schedule_steps": 25000, + } + + +def test_stage5_tiny_gate_keeps_the_candidate_architecture() -> None: + structured = load("phase5_s5_structured_refine25k_p005_r640x368_s20260716.yaml") + tiny = load("phase5_s5_structured_tiny2k_p005_r640x368_s20260716.yaml") + assert tiny["model"] == structured["model"] + assert tiny["loss"] == structured["loss"] + assert tiny["data"]["resolution_hw"] == structured["data"]["resolution_hw"] + assert tiny["data"]["T"] == structured["data"]["T"] + assert tiny["protocol"]["max_steps"] == 2000 + assert tiny["protocol"]["validation_subset_manifest"] is None + + +def test_stage5_pose_only_followup_changes_only_translation_residual_axis() -> None: + joint = load("phase5_s5_structured_refine25k_p005_r640x368_s20260716.yaml") + pose = load("phase5_s5_structured_pose_refine25k_p005_r640x368_s20260716.yaml") + joint_model = dict(joint["model"]) + pose_model = dict(pose["model"]) + assert pose_model.pop("structured_refine_translation") is False + assert joint_model == pose_model + for section in ("data", "loss", "assets", "precision", "protocol"): + assert joint[section] == pose[section] + tiny = load("phase5_s5_structured_pose_tiny2k_p005_r640x368_s20260716.yaml") + assert tiny["model"] == pose["model"] + assert tiny["loss"] == pose["loss"] + assert tiny["protocol"]["max_steps"] == 2000 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_stage6_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_stage6_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4317dc0114cd249008d74736f333c06901c06e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase5_stage6_configs.py @@ -0,0 +1,48 @@ +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).resolve().parents[1] + + +def load(name: str) -> dict: + path = ROOT / "configs" / "phase5" / "stage6" / name + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def test_stage6_last_two_block_screen_has_a_matched_frozen_control() -> None: + candidate = load( + "phase5_s6_dinov3_last2_lr5e7_continue25k_p0_r640x368_s20260717.yaml" + ) + control = load("phase5_s6_frozen_continue25k_p0_r640x368_s20260717.yaml") + assert candidate["seed"] == control["seed"] == 20260717 + assert candidate["experiment"]["coarse_checkpoint_sha256"] == control[ + "experiment" + ]["coarse_checkpoint_sha256"] + for section in ("data", "loss", "assets", "precision"): + assert candidate[section] == control[section] + candidate_model = dict(candidate["model"]) + control_model = dict(control["model"]) + assert candidate_model.pop("dinov3_trainable_last_blocks") == 2 + assert control_model.pop("dinov3_trainable_last_blocks") == 0 + assert candidate_model == control_model + candidate_protocol = dict(candidate["protocol"]) + assert candidate_protocol.pop("backbone_learning_rate") == 5e-7 + assert candidate_protocol == control["protocol"] + + +def test_stage6_smoke_matches_the_formal_last_two_block_model() -> None: + smoke = load("phase5_s6_dinov3_last2_lr5e7_smoke2_p0_r640x368_s20260717.yaml") + formal = load( + "phase5_s6_dinov3_last2_lr5e7_continue25k_p0_r640x368_s20260717.yaml" + ) + assert smoke["model"] == formal["model"] + assert smoke["loss"] == formal["loss"] + assert smoke["experiment"]["coarse_checkpoint_sha256"] == formal[ + "experiment" + ]["coarse_checkpoint_sha256"] + assert smoke["protocol"]["backbone_learning_rate"] == 5e-7 + assert smoke["protocol"]["deterministic_training"] is True + assert smoke["protocol"]["max_steps"] == 2 + assert smoke["protocol"]["validation_subset_manifest"] is None diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..9207564e0b1ffe56d4b2a67bd19a8ebad3764be5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_configs.py @@ -0,0 +1,57 @@ +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_t1_diagnostic_config_freezes_phase5_architecture() -> None: + path = ROOT / "configs/phase6/stage0/phase6_s0_t1_eval_p0_r640x368_s20260717.yaml" + config = yaml.safe_load(path.read_text(encoding="utf-8")) + assert config["data"]["T"] == 1 + assert config["data"]["resolution_hw"] == [368, 640] + assert config["model"]["decoder_mode"] == "alternating" + assert config["model"]["temporal_position_mode"] == "none" + assert config["model"]["depth_gate_mode"] == "fixed" + assert config["model"]["depth_gate_fixed_value"] == 0.5 + assert config["model"]["modality_dropout_prob"] == 0.0 + assert config["protocol"]["official_validation_used_for_selection"] is False + assert config["protocol"]["official_test_used"] is False + + +def test_stage2_candidate_control_are_matched_except_translation() -> None: + root = ROOT / "configs/phase6/stage2" + candidate = yaml.safe_load((root / "phase6_s2_mixed_projection_continue25k_p0_r640x368_s20260717.yaml").read_text()) + control = yaml.safe_load((root / "phase6_s2_direct_xyz_control_continue25k_p0_r640x368_s20260717.yaml").read_text()) + assert candidate["seed"] == control["seed"] == 20260717 + assert candidate["data"] == control["data"] + assert candidate["protocol"] == control["protocol"] + candidate_model = dict(candidate["model"]) + control_model = dict(control["model"]) + assert candidate_model.pop("translation_parameterization") == "mixed_projection" + assert control_model.pop("translation_parameterization") == "direct_xyz" + assert candidate_model.pop("mixed_projection_minimum_support") == 4 + assert candidate_model.pop("mixed_projection_huber_delta_px") == 16.0 + assert candidate_model.pop("mixed_projection_irls_iterations") == 5 + assert candidate_model == control_model + candidate_loss = dict(candidate["loss"]) + control_loss = dict(control["loss"]) + assert candidate_loss.pop("translation_teacher") == 1.0 + assert control_loss.pop("translation_teacher") == 0.0 + assert candidate_loss == control_loss + + +def test_stage3b_spatial_configs_freeze_tiny_and_formal_gates() -> None: + root = ROOT / "configs/phase6/stage3b" + tiny = yaml.safe_load((root / "phase6_s3b_spatial_heatmap_tiny2k_p0_r640x368_s20260717.yaml").read_text()) + formal = yaml.safe_load((root / "phase6_s3b_spatial_heatmap_continue25k_p0_r640x368_s20260717.yaml").read_text()) + for config in (tiny, formal): + assert config["seed"] == 20260717 + assert config["model"]["joint2d_parameterization"] == "spatial_heatmap" + assert config["model"]["heatmap_offset_enabled"] is True + assert config["model"]["heatmap_use_depth"] is True + assert config["loss"]["joint2d_teacher"] == 1.0 + assert config["protocol"]["official_test_used"] is False + assert tiny["protocol"]["max_steps"] == 2000 + assert formal["protocol"]["max_steps"] == 25000 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_harm_risk.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..8576148bd09747961c7e2d4f32db34ee10d3beed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_harm_risk.py @@ -0,0 +1,19 @@ +import numpy as np + +from scripts.fit_phase6_harm_risk import evaluate_policy, harm_cvar95 + + +def test_harm_cvar_and_policy_respect_fallback() -> None: + coarse = np.asarray([10.0, 10.0, 10.0, 10.0]) + corrected = np.asarray([8.0, 12.0, 9.0, 20.0]) + applied = np.asarray([True, False, True, False]) + groups = np.asarray(["a", "a", "b", "b"]) + result = evaluate_policy( + coarse_absolute_mm=coarse, corrected_absolute_mm=corrected, + applied=applied, seed_take_groups=groups, + ) + assert result["coverage"] == 0.5 + assert result["absolute_frame_mean_mm"] == 9.25 + assert result["absolute_take_mean_mm"] == 9.25 + assert result["harm_fraction_gt_0p5mm"] == 0.0 + assert harm_cvar95(coarse, corrected, applied) == 0.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_stage4_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_stage4_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..2c297a5029fdfdec59c579dd7a07995b27c2c4b9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_stage4_configs.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from pathlib import Path + +import yaml + + +ROOT = Path(__file__).resolve().parents[1] + + +def load(path: str) -> dict: + return yaml.safe_load((ROOT / path).read_text(encoding="utf-8")) + + +def test_phase6_structured_pose_formal_is_matched_to_direct_control() -> None: + candidate = load( + "configs/phase6/stage4/phase6_s4_structured_pose_continue25k_p0_r640x368_s20260717.yaml" + ) + control = load( + "configs/phase6/stage2/phase6_s2_direct_xyz_control_continue25k_p0_r640x368_s20260717.yaml" + ) + assert candidate["seed"] == control["seed"] == 20260717 + assert candidate["experiment"]["coarse_checkpoint_sha256"] == control[ + "experiment" + ]["coarse_checkpoint_sha256"] + for section in ("data", "loss", "assets", "precision", "protocol"): + assert candidate[section] == control[section] + model = dict(candidate["model"]) + assert model.pop("structured_hand_refinement") is True + assert model.pop("structured_refinement_detach_locations") is True + assert model.pop("structured_refinement_deterministic_detached_sampling") is True + assert model.pop("structured_deformable_samples") == 4 + assert model.pop("structured_refine_translation") is False + assert model == control["model"] + + +def test_phase6_structured_pose_tiny_keeps_formal_architecture() -> None: + candidate = load( + "configs/phase6/stage4/phase6_s4_structured_pose_continue25k_p0_r640x368_s20260717.yaml" + ) + tiny = load( + "configs/phase6/stage4/phase6_s4_structured_pose_tiny2k_p0_r640x368_s20260717.yaml" + ) + assert tiny["model"] == candidate["model"] + assert tiny["loss"] == candidate["loss"] + assert tiny["protocol"]["max_steps"] == 2000 + assert tiny["protocol"]["validation_subset_manifest"] is None diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_variable_length.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_variable_length.py new file mode 100644 index 0000000000000000000000000000000000000000..01cc37ba02d39f3277c26903f5b5653f74ec275a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase6_variable_length.py @@ -0,0 +1,119 @@ +import pytest +import torch + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig + + +def batch(time: int) -> dict[str, torch.Tensor]: + height, width = 32, 48 + K = torch.tensor([ + [50.0, 0.0, width / 2], + [0.0, 50.0, height / 2], + [0.0, 0.0, 1.0], + ]) + return { + "rgb": torch.randn(1, time, 3, height, width), + "depth_m": torch.rand(1, time, 1, height, width) + 0.3, + "depth_pixel_valid": torch.ones(1, time, 1, height, width, dtype=torch.bool), + "K": K[None, None].expand(1, time, -1, -1).clone(), + "K_available": torch.ones(1, time, dtype=torch.bool), + "depth_available": torch.ones(1, time, dtype=torch.bool), + "frame_valid": torch.ones(1, time, dtype=torch.bool), + } + + +@pytest.mark.parametrize("time", [1, 8, 31, 64]) +def test_tensor_shape_variable_length_is_finite(time: int) -> None: + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, use_depth=True, use_rays=True, + decoder_mode="alternating", temporal_position_mode="none", + )).eval() + with torch.no_grad(): + output = model(batch(time)) + assert output["hand_tokens"].shape == (1, time, 2, 32) + assert output["wrist_root_translation"].shape == (1, time, 2, 3) + assert output["attention"]["temporal_attention"].shape == (1, 1, 2, time, time) + assert torch.isfinite(output["hand_tokens"]).all() + assert torch.isfinite(output["wrist_root_translation"]).all() + + +def test_bidirectional_model_fails_future_and_prefix_invariance() -> None: + torch.manual_seed(20260717) + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=2, + attention_heads=4, use_depth=True, use_rays=True, + decoder_mode="alternating", temporal_position_mode="none", + )).eval() + full = batch(8) + perturbed = {key: value.clone() for key, value in full.items()} + perturbed["rgb"][:, 4:] = -perturbed["rgb"][:, 4:] + perturbed["depth_m"][:, 4:] = 0.0 + perturbed["depth_pixel_valid"][:, 4:] = False + perturbed["depth_available"][:, 4:] = False + prefix = {key: value[:, :4].clone() for key, value in full.items()} + with torch.no_grad(): + original_output = model(full) + perturbed_output = model(perturbed) + prefix_output = model(prefix) + future_difference = ( + original_output["hand_tokens"][:, :4] + - perturbed_output["hand_tokens"][:, :4] + ).abs().max() + prefix_difference = ( + original_output["hand_tokens"][:, :4] + - prefix_output["hand_tokens"] + ).abs().max() + assert future_difference > 0 + assert prefix_difference > 0 + + +def test_causal_model_passes_future_and_prefix_invariance() -> None: + torch.manual_seed(20260717) + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=2, + attention_heads=4, use_depth=True, use_rays=True, + decoder_mode="alternating", temporal_position_mode="none", + temporal_attention_mode="causal", + )).eval() + full = batch(8) + perturbed = {key: value.clone() for key, value in full.items()} + perturbed["rgb"][:, 4:] = -perturbed["rgb"][:, 4:] + perturbed["depth_m"][:, 4:] = 0.0 + perturbed["depth_pixel_valid"][:, 4:] = False + perturbed["depth_available"][:, 4:] = False + prefix = {key: value[:, :4].clone() for key, value in full.items()} + with torch.no_grad(): + original_output = model(full) + perturbed_output = model(perturbed) + prefix_output = model(prefix) + torch.testing.assert_close( + original_output["hand_tokens"][:, :4], + perturbed_output["hand_tokens"][:, :4], rtol=0, atol=0, + ) + torch.testing.assert_close( + original_output["hand_tokens"][:, :4], + prefix_output["hand_tokens"], rtol=0, atol=1e-6, + ) + torch.testing.assert_close( + original_output["wrist_root_translation"][:, :4], + prefix_output["wrist_root_translation"], rtol=0, atol=1e-6, + ) + attention = original_output["attention"]["temporal_attention"] + future = torch.triu(torch.ones(8, 8, dtype=torch.bool), diagonal=1) + assert torch.equal(attention[..., future], torch.zeros_like(attention[..., future])) + + +def test_temporal_attention_mode_is_parameter_free_checkpoint_compatible() -> None: + common = dict( + encoder="tiny_debug", decoder_dim=32, decoder_layers=2, + attention_heads=4, use_depth=True, use_rays=True, + decoder_mode="alternating", temporal_position_mode="none", + ) + bidirectional = BimanualReconstructionModel(ModelConfig(**common)) + causal = BimanualReconstructionModel(ModelConfig( + **common, temporal_attention_mode="causal", + )) + causal.load_state_dict(bidirectional.state_dict(), strict=True) + assert bidirectional.config.temporal_attention_mode == "bidirectional" + assert set(bidirectional.state_dict()) == set(causal.state_dict()) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1653506117dda7ec2cc57aee93443b5c77be74 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_configs.py @@ -0,0 +1,56 @@ +from pathlib import Path + +import pytest + +from scripts.build_phase7_adaptation_configs import adaptation_config, validate_adaptation_inputs + + +def records() -> tuple[dict, dict, dict]: + selection = { + "status": "selected_external_generalist_no_h2o", + "checkpoint": {"sha256": "a" * 64, "step": 100000}, + "h2o_training_data_used": False, "official_test_used": False, + } + zero_shot = { + "status": "complete", "completed_ids": [ + "h2o_strict_zero_shot_rgb_d_k", "h2o_strict_zero_shot_rgb_k", + "h2o_strict_zero_shot_rgb_only", + ], + "h2o_training_data_used": False, "official_test_used": False, + } + split = { + "status": "frozen_h2o_train_group_split", "recording_overlap": [], + "fit": {"path": "/h2o/train_fit.jsonl"}, + "heldout": {"path": "/h2o/train_group_heldout.jsonl"}, + "h2o_official_validation_used": False, "official_test_used": False, + } + return selection, zero_shot, split + + +def base_config() -> dict: + return { + "data": {"sources": [ + {"dataset": "HOT3D", "weight": 0.4, "cache_manifest": "/hot", "K_input_dropout": 0.3}, + {"dataset": "HOI4D", "weight": 0.4, "cache_manifest": "/hoi", "K_input_dropout": 0.0}, + {"dataset": "ARCTIC", "weight": 0.2, "cache_manifest": "/arc", "K_input_dropout": 0.0}, + ]}, + "model": {"modality_dropout_prob": 0.0, "dinov3_trainable_last_blocks": 0}, + } + + +def test_adaptation_configs_are_matched_a1_and_a2() -> None: + selection, zero_shot, split = records() + validate_adaptation_inputs(selection, zero_shot, split) + a1 = adaptation_config(base_config(), selection, split, "A1") + a2 = adaptation_config(base_config(), selection, split, "A2") + assert [source["weight"] for source in a1["data"]["sources"]] == [1.0] + assert [source["weight"] for source in a2["data"]["sources"]] == [0.5, 0.2, 0.2, 0.1] + assert a1["data"]["validation_sources"][0]["split_role"] == "train_group_heldout" + assert a2["experiment"]["initialization_checkpoint_sha256"] == "a" * 64 + + +def test_adaptation_config_gate_requires_completed_zero_shot() -> None: + selection, zero_shot, split = records() + zero_shot["completed_ids"].pop() + with pytest.raises(ValueError, match="zero-shot"): + validate_adaptation_inputs(selection, zero_shot, split) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..4eca6940fb324b59fb2c587b6c967dc7fe05d927 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_eval_queue.py @@ -0,0 +1,31 @@ +import pytest + +from scripts.run_phase7_adaptation_eval_queue import evaluator_command, validate_queue + + +def queue() -> dict: + return { + "official_test_used": False, "h2o_official_validation_used": False, + "h2o_training_data_used": True, + "selection_split": "h2o_train_group_heldout_only", + "evaluations": [{ + "id": "A1_20k", "config": "/config", "checkpoint": "/checkpoint", + "checkpoint_sha256": "a" * 64, + "cache_manifest": "/split/train_group_heldout.jsonl", + "output_dir": "/output", "input_mode": "rgb_d_k", + }], + } + + +def test_adaptation_eval_queue_forces_train_heldout_role() -> None: + validate_queue(queue()) + command = evaluator_command(queue()["evaluations"][0], 2) + assert command[command.index("--evaluation-role") + 1] == "h2o_train_group_heldout" + assert command[command.index("--physical-gpu-id") + 1] == "2" + + +def test_adaptation_eval_queue_rejects_official_validation() -> None: + value = queue() + value["evaluations"][0]["cache_manifest"] = "/official_val.jsonl" + with pytest.raises(ValueError, match="train_group_heldout"): + validate_queue(value) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_evaluator.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..303016932768d069952732b6554480f80a0cd42e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_evaluator.py @@ -0,0 +1,67 @@ +from pathlib import Path + +import pytest + +from scripts.evaluate_phase7_external import ( + checkpoint_h2o_training_data_used, + validate_evaluation_role, +) + + +def test_external_evaluation_default_contract_remains_strict() -> None: + validate_evaluation_role( + "external_heldout", {"experiment": {"branch": "external_only"}}, + {"HOT3D"}, {"h2o_training_data_used": False}, Path("heldout.jsonl"), + ) + with pytest.raises(ValueError, match="refuses H2O"): + validate_evaluation_role( + "external_heldout", {"experiment": {"branch": "external_only"}}, + {"H2O"}, {"h2o_training_data_used": False}, Path("heldout.jsonl"), + ) + + +def test_adaptation_evaluation_only_accepts_train_group_heldout() -> None: + config = {"experiment": {"branch": "h2o_adaptation"}} + extra = {"h2o_training_data_used": True} + validate_evaluation_role( + "h2o_train_group_heldout", config, {"H2O"}, extra, + Path("train_group_heldout.jsonl"), + ) + with pytest.raises(ValueError, match="frozen train-group-heldout"): + validate_evaluation_role( + "h2o_train_group_heldout", config, {"H2O"}, extra, + Path("official_val.jsonl"), + ) + + +def test_adaptation_forgetting_only_accepts_external_heldout() -> None: + config = {"experiment": {"branch": "h2o_adaptation"}} + extra = {"h2o_training_data_used": True} + validate_evaluation_role( + "adaptation_external_heldout", config, {"HOT3D"}, extra, + Path("hot3d_heldout/cache_manifest.jsonl"), + ) + with pytest.raises(ValueError, match="pure external"): + validate_evaluation_role( + "adaptation_external_heldout", config, {"H2O"}, extra, + Path("train_group_heldout.jsonl"), + ) + + +def test_h2o_trainheldout_control_preserves_checkpoint_provenance() -> None: + external = {"h2o_training_data_used": False} + historical_h2o = {"config": {"experiment": {"phase": 5}}} + for extra in (external, historical_h2o): + validate_evaluation_role( + "h2o_train_group_heldout_control", {}, {"H2O"}, extra, + Path("train_group_heldout.jsonl"), + ) + assert checkpoint_h2o_training_data_used(external) is False + assert checkpoint_h2o_training_data_used(historical_h2o) is True + with pytest.raises(ValueError, match="auditable H2O-training provenance"): + checkpoint_h2o_training_data_used({}) + with pytest.raises(ValueError, match="frozen train-group-heldout"): + validate_evaluation_role( + "h2o_train_group_heldout_control", {}, {"H2O"}, external, + Path("official_val.jsonl"), + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_forgetting_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_forgetting_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..d6f6fce3726ae200404ae4226ff689a34fbeee25 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_forgetting_queue.py @@ -0,0 +1,33 @@ +import pytest + +from scripts.run_phase7_adaptation_forgetting_queue import evaluator_command, validate_queue + + +def queue() -> dict: + return { + "official_test_used": False, "h2o_official_validation_used": False, + "h2o_training_data_used": True, "selection_use": False, + "evaluation_split": "external_heldout_forgetting_diagnostic_only", + "evaluations": [{ + "id": "A1_HOT3D", "config": "/config", "checkpoint": "/checkpoint", + "checkpoint_sha256": "a" * 64, + "cache_manifest": "/cache/hot3d_heldout/cache_manifest.jsonl", + "output_dir": "/output", "input_mode": "rgb_k", + }], + } + + +def test_forgetting_queue_forces_diagnostic_role() -> None: + validate_queue(queue()) + command = evaluator_command(queue()["evaluations"][0], 2) + assert command[command.index("--evaluation-role") + 1] == "adaptation_external_heldout" + assert command[command.index("--physical-gpu-id") + 1] == "2" + + +def test_forgetting_queue_refuses_selection_use_and_h2o_paths() -> None: + value = queue(); value["selection_use"] = True + with pytest.raises(ValueError, match="boundary"): + validate_queue(value) + value = queue(); value["evaluations"][0]["cache_manifest"] = "/cache/h2o/train.jsonl" + with pytest.raises(ValueError, match="H2O"): + validate_queue(value) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_train_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..65f0818eec86fdd1074db02ebcf9b837166c429b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_adaptation_train_queue.py @@ -0,0 +1,54 @@ +import hashlib +from pathlib import Path + +import pytest + +from scripts.run_phase7_adaptation_train_queue import training_command, validate_stage_inputs + + +def test_adaptation_queue_uses_frozen_init_then_exact_resume(tmp_path: Path) -> None: + base = { + "id": "A1_20k", "config": "/config.yaml", + "output_dir": str(tmp_path / "run"), "stop_after_step": 20000, + "init_checkpoint": "/external.pt", "init_checkpoint_sha256": "a" * 64, + } + command = training_command(base, gpu=2) + assert command[command.index("--physical-gpu-id") + 1] == "2" + assert command[command.index("--init-checkpoint") + 1] == "/external.pt" + resumed = {**base, "id": "A1_50k", "resume_from_step": 20000, "stop_after_step": 50000} + command = training_command(resumed, gpu=1) + assert "--init-checkpoint" not in command + assert command[command.index("--resume") + 1].endswith("step_0020000_final.pt") + explicit = { + **base, "id": "A1_50k_retry", "output_dir": str(tmp_path / "retry"), + "resume_checkpoint": "/run/step_0024000.pt", "stop_after_step": 50000, + } + command = training_command(explicit, gpu=0) + assert command[command.index("--resume") + 1] == "/run/step_0024000.pt" + + +def test_explicit_resume_is_hash_bound_and_requires_clean_output(tmp_path: Path) -> None: + config = tmp_path / "config.yaml"; config.write_text("config", encoding="utf-8") + resume = tmp_path / "step.pt"; resume.write_bytes(b"state") + item = { + "config": str(config), + "config_sha256": hashlib.sha256(config.read_bytes()).hexdigest(), + "output_dir": str(tmp_path / "output"), + "resume_checkpoint": str(resume), + "resume_checkpoint_sha256": hashlib.sha256(resume.read_bytes()).hexdigest(), + } + validate_stage_inputs(item) + item["resume_checkpoint_sha256"] = "0" * 64 + with pytest.raises(RuntimeError, match="SHA mismatch"): + validate_stage_inputs(item) + + +def test_neutral_control_queue_starts_without_checkpoint(tmp_path: Path) -> None: + item = { + "id": "B2", "config": "/config.yaml", + "output_dir": str(tmp_path / "neutral"), "stop_after_step": 20000, + "neutral_start": True, + } + command = training_command(item, gpu=3) + assert "--init-checkpoint" not in command + assert "--resume" not in command diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_arctic_adapter.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_arctic_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..864e391fd63ce30d8033ff165896c010cdc10373 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_arctic_adapter.py @@ -0,0 +1,44 @@ +import torch + +from foundation_hand.data.arctic_dataset import ( + compose_camera_global_orientation, + geometry_compatibility_mask, + InvalidSourceSampleError, + transform_points, +) + + +def test_arctic_world_to_camera_transform() -> None: + points = torch.tensor([[[1.0, 2.0, 3.0]]]) + transform = torch.eye(4)[None] + transform[:, :3, 3] = torch.tensor((4.0, 5.0, 6.0)) + torch.testing.assert_close( + transform_points(points, transform), torch.tensor([[[5.0, 7.0, 9.0]]]), + ) + + +def test_arctic_camera_global_orientation_composition() -> None: + angle = torch.tensor([[0.0, 0.0, 0.3]]) + camera_angle = torch.tensor(0.4) + transform = torch.eye(4)[None] + transform[:, :3, :3] = torch.tensor([[ + [torch.cos(camera_angle), -torch.sin(camera_angle), 0.0], + [torch.sin(camera_angle), torch.cos(camera_angle), 0.0], + [0.0, 0.0, 1.0], + ]]) + result = compose_camera_global_orientation(angle, transform) + assert torch.allclose(result[:, 2], torch.tensor([0.7]), atol=1e-5) + + +def test_arctic_geometry_gate_masks_isolated_source_mismatch_without_relaxing_1mm() -> None: + hand_valid = torch.tensor([[True, True], [True, True]]) + errors_mm = torch.tensor([[35.0, 0.25], [0.999, 14.0]]) + compatible = geometry_compatibility_mask(hand_valid, errors_mm) + assert compatible.tolist() == [[False, True], [True, False]] + assert hand_valid[1, 1] + assert not compatible[1, 1] + + +def test_arctic_invalid_source_sample_is_a_narrow_runtime_error() -> None: + assert issubclass(InvalidSourceSampleError, RuntimeError) + assert InvalidSourceSampleError is not RuntimeError diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_arctic_manifest.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_arctic_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..e5faa47173b405e4744e4d10c5a80b2d8282293a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_arctic_manifest.py @@ -0,0 +1,15 @@ +from pathlib import Path + +from scripts.build_phase7_arctic_manifests import read_p2_train_val_without_test + + +def test_arctic_protocol_reader_stops_before_test_identities(tmp_path: Path) -> None: + protocol = tmp_path / "protocol.json" + protocol.write_text( + '{\n"train": ["s01/a"],\n"val": ["s05/b"],\n' + '"test": ["PROHIBITED_SENTINEL"]\n}\n', + encoding="utf-8", + ) + record = read_p2_train_val_without_test(protocol) + assert record == {"train": ["s01/a"], "val": ["s05/b"]} + assert "PROHIBITED_SENTINEL" not in str(record) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_cache.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..f03011d101bc7e9546b5f179caa17c0fca6a1ead --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_cache.py @@ -0,0 +1,90 @@ +import numpy as np +import pytest + +from scripts.cache_phase7_hot3d import ( + balanced_indices, + cache_candidate_count, + decode_position_slice, + first_valid_indices, + rgb_uint8, + should_stop_decoding, + validate_cached_resolution, + validated_target_hw, +) + + +def test_balanced_hot3d_cache_selection_spans_recordings() -> None: + rows = [] + for recording in ("a", "b", "c"): + for clip in range(3): + rows.append({ + "headset": "Aria", "participant_id": "P1", + "recording_id": recording, "clip": clip, + }) + selected = balanced_indices(rows, 6) + assert [rows[index]["recording_id"] for index in selected[:3]] == ["a", "b", "c"] + + +def test_rgb_cache_roundtrip_is_uint8_bounded() -> None: + rgb = np.zeros((2, 3, 4, 5), dtype=np.float32) + result = rgb_uint8(rgb) + assert result.shape == (2, 4, 5, 3) + assert result.dtype == np.uint8 + assert result.min() >= 0 and result.max() <= 255 + + +def test_cache_resolution_contract_accepts_stage7_and_rejects_mixed_resume( + tmp_path, +) -> None: + assert validated_target_hw([512, 896]) == (512, 896) + with pytest.raises(ValueError, match="positive"): + validated_target_hw([0, 896]) + cache = tmp_path / "clip.npz" + np.savez_compressed(cache, image_hw=np.array([368, 640], dtype=np.int64)) + with np.load(cache, allow_pickle=False) as archive: + validate_cached_resolution(archive, (368, 640)) + with np.load(cache, allow_pickle=False) as archive: + with pytest.raises(ValueError, match="does not match"): + validate_cached_resolution(archive, (512, 896)) + + +def test_balanced_cache_can_bound_recording_open_count() -> None: + rows = [] + for headset in ("Aria", "Quest3"): + for participant in ("P1", "P2"): + for recording in ("a", "b", "c"): + for clip in range(20): + rows.append({ + "headset": headset, "participant_id": participant, + "recording_id": recording, "clip": clip, + }) + selected = balanced_indices(rows, 32, max_recordings=4) + keys = { + (rows[index]["headset"], rows[index]["participant_id"], rows[index]["recording_id"]) + for index in selected + } + assert len(selected) == 32 + assert len(keys) == 4 + assert {key[0] for key in keys} == {"Aria", "Quest3"} + assert {key[1] for key in keys} == {"P1", "P2"} + + +def test_hot3d_cache_overdraw_and_backfill_are_deterministic() -> None: + assert cache_candidate_count(10000, 20000) == 11000 + assert cache_candidate_count(128, 140) == 140 + assert first_valid_indices( + [10, 11, 12, 13], {10: {}, 12: {}, 13: {}}, 3, + ) == [10, 12, 13] + assert should_stop_decoding( + [10, 11, 12, 13], {10: {}, 12: {}, 13: {}}, 3, False, + ) + assert not should_stop_decoding( + [10, 11, 12, 13], {10: {}, 12: {}, 13: {}}, 3, True, + ) + + +def test_hot3d_prefill_range_is_half_open_and_bounded() -> None: + order = [8, 4, 3, 9, 1] + assert decode_position_slice(order, (1, 4)) == ([4, 3, 9], (1, 4)) + with pytest.raises(ValueError, match="invalid prefill position range"): + decode_position_slice(order, (4, 6)) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_egodexter_adapter.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_egodexter_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..06a82329998fe0cafe82234f443f795b18ce1e2f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_egodexter_adapter.py @@ -0,0 +1,64 @@ +from pathlib import Path + +import cv2 +import numpy as np +import pytest +import torch + +from foundation_hand.data.egodexter_dataset import ( + EgoDexterSequenceDataset, + load_depth_intrinsics, + parse_fingertip_line, +) + + +def make_dataset(tmp_path: Path) -> Path: + root = tmp_path / "egodexter" + sequence = root / "data" / "Desk" + (sequence / "color_on_depth").mkdir(parents=True) + (sequence / "depth").mkdir() + (root / "CameraCalibration_640x480.txt").write_text( + "Depth Intrisics Matrix:\n 475.62 0 311.125\n0 475.62 245.965\n0 0 1\n\nColor Intrisics Matrix:\n", + encoding="utf-8", + ) + rgb = np.full((480, 640, 3), 127, dtype=np.uint8) + depth = np.full((480, 640), 500, dtype=np.uint16) + cv2.imwrite(str(sequence / "color_on_depth" / "image_00000_color_on_depth.png"), rgb) + cv2.imwrite(str(sequence / "depth" / "image_00000_depth.png"), depth) + (sequence / "annotation.txt").write_text( + "1, 2; 3, 4; 5, 6; 7, 8; 9, 10; \n", encoding="utf-8", + ) + (sequence / "annotation.txt_3D.txt").write_text( + "10, 20, 500; 0, 0, 0; 30, 40, 600; 40, 50, 700; 50, 60, 800; \n", + encoding="utf-8", + ) + return root + + +def test_egodexter_parser_and_calibration(tmp_path: Path) -> None: + root = make_dataset(tmp_path) + assert parse_fingertip_line("1, 2; 3, 4; 5, 6; 7, 8; 9, 10;", 2).shape == (5, 2) + K = load_depth_intrinsics(root / "CameraCalibration_640x480.txt") + np.testing.assert_allclose(K[0], (475.62, 0.0, 311.125)) + partial = parse_fingertip_line("1, 2; 3, 4; 5, 6;", 2, missing_value=-1.0) + np.testing.assert_array_equal(partial[3:], -np.ones((2, 2), dtype=np.float32)) + + +def test_egodexter_frame_separates_input_availability_and_targets(tmp_path: Path) -> None: + dataset = EgoDexterSequenceDataset( + make_dataset(tmp_path), "Desk", hand_side="left", target_hw=(368, 640), + ) + frame = dataset.frame(0, "rgb_only") + assert frame["rgb"].shape == (1, 1, 3, 368, 640) + assert frame["depth_m"].shape == (1, 1, 1, 368, 640) + assert not frame["K_input_available"].any() + assert not frame["depth_input_available"].any() + assert frame["K_supervision"].shape == (3, 3) + assert frame["target_fingertip_valid"].tolist() == [True, False, True, True, True] + assert torch.isnan(frame["target_fingertips_camera_m"][1]).all() + + +def test_egodexter_requires_frozen_sequence_handedness(tmp_path: Path) -> None: + root = make_dataset(tmp_path) + with pytest.raises(ValueError, match="hand_side"): + EgoDexterSequenceDataset(root, "Desk", hand_side="unknown") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_egodexter_evaluator.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_egodexter_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..c5be25ad894021b06869f5563cfa80d146931081 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_egodexter_evaluator.py @@ -0,0 +1,54 @@ +import hashlib +import json +from pathlib import Path + +import pytest +import torch + +from scripts.evaluate_phase7_egodexter_zero_shot import ( + finite_summary, model_frame, validate_freeze_record, +) + + +def test_egodexter_model_input_excludes_all_targets() -> None: + frame = { + "rgb": torch.zeros(1, 1, 3, 4, 4), "depth_m": torch.zeros(1, 1, 1, 4, 4), + "depth_pixel_valid": torch.zeros(1, 1, 1, 4, 4, dtype=torch.bool), + "K": torch.eye(3).reshape(1, 1, 3, 3), "K_available": torch.ones(1, 1, dtype=torch.bool), + "K_input_available": torch.ones(1, 1, dtype=torch.bool), + "depth_available": torch.ones(1, 1, dtype=torch.bool), + "depth_input_available": torch.ones(1, 1, dtype=torch.bool), + "frame_valid": torch.ones(1, 1, dtype=torch.bool), + "target_fingertips_camera_m": torch.ones(5, 3), + "target_fingertip_valid": torch.ones(5, dtype=torch.bool), + } + inputs = model_frame(frame) + assert "target_fingertips_camera_m" not in inputs + assert "target_fingertip_valid" not in inputs + + +def test_egodexter_freeze_requires_sequence_level_mapping(tmp_path: Path) -> None: + config = tmp_path / "config.yaml" + config.write_text("config", encoding="utf-8") + digest = hashlib.sha256(config.read_bytes()).hexdigest() + record = { + "status": "phase7_final_models_frozen", + "egodexter_used_for_training_or_selection": False, "official_test_used": False, + "models": [{ + "id": "model", "checkpoint_sha256": "checkpoint", + "inference_configs": {"offline": {"path": str(config), "sha256": digest}}, + }], + "egodexter_sequence_handedness": { + "Desk": "right", "Fruits": "right", "Kitchen": "right", "Rotunda": "right", + }, + } + validate_freeze_record(record, "model", "checkpoint", config, "offline") + del record["egodexter_sequence_handedness"]["Desk"] + with pytest.raises(ValueError, match="handedness"): + validate_freeze_record(record, "model", "checkpoint", config, "offline") + + +def test_fingertip_summary_reports_required_statistics() -> None: + assert finite_summary([1.0, 2.0, 3.0]) == { + "count": 3, "mean": 2.0, "median": 2.0, "p95": pytest.approx(2.9), + } diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_continuation.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_continuation.py new file mode 100644 index 0000000000000000000000000000000000000000..fd5c459f8d9a74beaada8ef53fe1b8b8c55bebb6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_continuation.py @@ -0,0 +1,79 @@ +import csv +import hashlib +import json +from pathlib import Path + +from scripts.freeze_phase7_h2o_zero_shot import build_freeze_record +from scripts.select_phase7_external_continuation import paired_take_bootstrap, rank_candidates + + +def test_cross_step_rank_is_dataset_macro_not_frame_weighted() -> None: + entries = [] + for dataset, abs_a, abs_b in ( + ("HOT3D", 2.0, 1.0), ("HOI4D", 1.0, 2.0), ("ARCTIC", 1.0, 2.0), + ): + for candidate, absolute in (("step50k", abs_a), ("step100k", abs_b)): + entries.append({ + "candidate": candidate, "dataset": dataset, + "absolute_mpjpe_mm": absolute, + "root_relative_mpjpe_mm": absolute, + "fingertip_mpjpe_mm": absolute, + "translation_z_p95_mm": absolute, + }) + assert rank_candidates(entries)["winner"] == "step50k" + + +def test_paired_bootstrap_uses_identical_take_ids(tmp_path: Path) -> None: + paths = [] + for name, values in (("a", (2.0, 4.0)), ("b", (1.0, 3.0))): + path = tmp_path / f"{name}.csv" + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=("physical_recording_id", "absolute_mpjpe_mm")) + writer.writeheader() + writer.writerows([ + {"physical_recording_id": "r1", "absolute_mpjpe_mm": values[0]}, + {"physical_recording_id": "r2", "absolute_mpjpe_mm": values[1]}, + ]) + paths.append(path) + result = paired_take_bootstrap(paths[0], paths[1], "absolute_mpjpe_mm", 7, 100) + assert result["mean_delta"] == -1.0 + assert result["take_count"] == 2 + + +def test_paired_bootstrap_can_compare_recording_p95(tmp_path: Path) -> None: + paths = [] + for name, values in (("a", (1.0, 10.0)), ("b", (1.0, 5.0))): + path = tmp_path / f"{name}.csv" + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=("physical_recording_id", "z")) + writer.writeheader() + writer.writerows([ + {"physical_recording_id": "r1", "z": values[0]}, + {"physical_recording_id": "r1", "z": values[1]}, + ]) + paths.append(path) + result = paired_take_bootstrap(paths[0], paths[1], "z", 7, 100, "p95") + assert result["mean_delta"] < 0 + assert result["recording_statistic"] == "p95" + + +def test_zero_shot_freeze_hash_binds_completed_external_selection(tmp_path: Path) -> None: + checkpoint = tmp_path / "checkpoint.pt" + config = tmp_path / "config.yaml" + manifest = tmp_path / "official_val.jsonl" + checkpoint.write_bytes(b"checkpoint") + config.write_text("config", encoding="utf-8") + manifest.write_text("manifest", encoding="utf-8") + digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest() + selection = tmp_path / "selection.json" + selection.write_text(json.dumps({ + "status": "selected_external_generalist_no_h2o", + "checkpoint": {"path": str(checkpoint), "sha256": digest(checkpoint), "step": 100000}, + "config": {"path": str(config), "sha256": digest(config)}, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + }), encoding="utf-8") + record = build_freeze_record(selection, manifest) + assert record["status"] == "external_generalist_frozen" + assert record["h2o_validation_manifest"]["sha256"] == digest(manifest) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c80568e3cbd6817d2cd041d1083f1d61d785eb6d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_eval_queue.py @@ -0,0 +1,47 @@ +import json +from pathlib import Path + +from scripts.run_phase7_external_eval_queue import completed_matches, evaluator_command + + +def item(tmp_path: Path) -> dict: + return { + "id": "E40_HOT3D", "config": "config.yaml", + "checkpoint": "model.pt", "checkpoint_sha256": "abc", + "cache_manifest": "cache.jsonl", "input_mode": "rgb_k", + "output_dir": str(tmp_path / "evaluation"), "bootstrap_resamples": 10, + } + + +def test_eval_queue_command_binds_physical_gpu() -> None: + command = evaluator_command(item(Path("/tmp")), 2) + assert command[-2:] == ["--bootstrap-resamples", "10"] + assert command[command.index("--physical-gpu-id") + 1] == "2" + + +def test_eval_queue_command_freezes_manifest_hash_when_registered() -> None: + value = item(Path("/tmp")) + value["cache_manifest_sha256"] = "cache-sha" + command = evaluator_command(value, 1) + assert command[command.index("--expected-cache-manifest-sha256") + 1] == "cache-sha" + + +def test_eval_queue_only_skips_matching_external_result(tmp_path: Path) -> None: + value = item(tmp_path) + output = Path(value["output_dir"]) + output.mkdir() + (output / "evaluation.json").write_text(json.dumps({ + "status": "evaluated", "checkpoint": {"sha256": "abc"}, + "input_mode": "rgb_k", "official_test_used": False, + "h2o_training_data_used": False, + }), encoding="utf-8") + assert completed_matches(value) + value["checkpoint_sha256"] = "different" + assert not completed_matches(value) + + +def test_eval_queue_process_log_is_not_part_of_evaluation_output() -> None: + source = Path(__file__).resolve().parents[1] / "scripts" / "run_phase7_external_eval_queue.py" + text = source.read_text(encoding="utf-8") + assert 'args.state.parent / f"{args.queue.stem}_{item[\'id\']}.log"' in text + assert 'output_dir / "evaluator_process.log"' not in text diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_evaluator.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..3bec9226ae59485f210b2d85544f5e67e993f85f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_evaluator.py @@ -0,0 +1,159 @@ +import math + +import numpy as np +import torch + +from scripts.evaluate_phase7_external import ( + append_valid_frame_arrays, + aggregate, + depth_bucket, + finite_summary, + grouped_bootstrap, + hand_size_bucket, + ray_depth_diagnostic_row, + supervision_coverage, + tensor_to_numpy, + validate_evaluation_role, +) + + +def test_phase7_metric_summary_reports_tail_and_cvar() -> None: + result = finite_summary([1.0, 2.0, 3.0, 100.0, math.nan]) + assert result is not None + assert result["count"] == 4 + assert result["max"] == 100.0 + assert result["cvar95"] == 100.0 + + +def test_phase7_fixed_bucket_boundaries() -> None: + assert hand_size_bucket(63.9) == "small_lt64" + assert hand_size_bucket(64.0) == "medium_64_128" + assert hand_size_bucket(128.0) == "large_ge128" + assert depth_bucket(.8) == "near_le0.8m" + assert depth_bucket(.8001) == "far_gt0.8m" + + +def test_group_bootstrap_uses_physical_recordings() -> None: + rows = [ + {"physical_recording_id": "a", "metric": 1.0}, + {"physical_recording_id": "a", "metric": 3.0}, + {"physical_recording_id": "b", "metric": 5.0}, + ] + result = grouped_bootstrap(rows, "metric", seed=17, resamples=100) + assert result is not None + assert result["groups"] == 2 + assert result["estimate"] == 3.0 + + +def test_raw_prediction_writer_converts_bfloat16_to_float32() -> None: + result = tensor_to_numpy(torch.tensor([1.25], dtype=torch.bfloat16)) + assert result.dtype == np.float32 + np.testing.assert_allclose(result, np.array([1.25], dtype=np.float32)) + + +def test_raw_prediction_writer_flattens_partial_final_clip() -> None: + raw: dict[str, list[np.ndarray]] = {} + append_valid_frame_arrays( + raw, {"value": torch.arange(8).reshape(1, 8, 1)}, + torch.ones((1, 8), dtype=torch.bool), + ) + append_valid_frame_arrays( + raw, {"value": torch.arange(8, 14).reshape(1, 6, 1)}, + torch.ones((1, 6), dtype=torch.bool), + ) + combined = np.concatenate(raw["value"], axis=0) + assert combined.shape == (14, 1) + assert combined[:, 0].tolist() == list(range(14)) + + +def test_ray_depth_diagnostic_row_reports_base_harm_and_support() -> None: + prediction = { + "ray_depth_confidence": torch.tensor([[[.25, .0]]]), + "ray_depth_raw_delta_z_m": torch.tensor([[[.04, .0]]]), + "ray_depth_applied_delta_z_m": torch.tensor([[[.01, .0]]]), + "ray_depth_support_count": torch.tensor([[[6, 0]]]), + "ray_depth_correction_valid": torch.tensor([[[True, False]]]), + "ray_depth_base_z_m": torch.tensor([[[.70, .80]]]), + "wrist_root_translation": torch.tensor([[[[.0, .0, .71], [.0, .0, .80]]]]), + } + batch = { + "wrist_root_translation": torch.tensor([[[[.0, .0, .68], [.0, .0, .80]]]]), + } + row = ray_depth_diagnostic_row(prediction, batch, 0, 0, 0, True) + assert row["ray_depth_confidence"] == .25 + assert row["ray_depth_support_count"] == 6 + assert row["ray_depth_local_valid_fraction"] == 6 / 9 + assert row["ray_depth_correction_valid"] is True + assert math.isclose(row["ray_depth_base_z_error_mm"], 20.0, abs_tol=1e-4) + assert math.isclose(row["ray_depth_final_z_error_mm"], 30.0, abs_tol=1e-4) + assert math.isclose(row["ray_depth_harm_mm"], 10.0, abs_tol=1e-4) + + +def test_supervision_coverage_exposes_partial_hand_labels() -> None: + rows = [ + {"joint3d_supervision": True, "translation_supervision": True, "vertices_supervision": True}, + {"joint3d_supervision": False, "translation_supervision": True, "vertices_supervision": False}, + ] + coverage = supervision_coverage(rows) + assert coverage["hand_rows"] == 2 + assert coverage["joint3d_valid_fraction"] == .5 + assert coverage["source_root_relative_valid_hands"] == 0 + assert coverage["source_root_relative_valid_fraction"] == 0.0 + assert coverage["translation_valid_fraction"] == 1.0 + assert coverage["vertices_valid_fraction"] == .5 + + +def test_phase9_evaluation_roles_enforce_external_and_matching_fold(tmp_path) -> None: + unified = { + "experiment": { + "branch": "phase9_unified", "h2o_selection_fold": "loso_subject1", + }, + } + extra = {"h2o_training_data_used": True} + validate_evaluation_role( + "phase9_external_heldout", unified, {"HOT3D"}, extra, + tmp_path / "hot_heldout.jsonl", + ) + validate_evaluation_role( + "phase9_h2o_fold_heldout", unified, {"H2O"}, extra, + tmp_path / "loso_subject1_heldout.jsonl", + ) + try: + validate_evaluation_role( + "phase9_h2o_fold_heldout", unified, {"H2O"}, extra, + tmp_path / "loso_subject2_heldout.jsonl", + ) + except ValueError as error: + assert "loso_subject1_heldout" in str(error) + else: + raise AssertionError("mismatched Phase 9 fold was accepted") + + +def test_aggregate_reports_headset_and_occlusion_buckets() -> None: + base = { + field: math.nan for field in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "source_root_relative_mpjpe_mm", "rigid_se3_mpjpe_mm", + "pa_mpjpe_mm", "mpvpe_mm", "fingertip_mpjpe_mm", + "direct_2d_error_px", "projected_mano_2d_error_px", + "direct_mano_consistency_px", "translation_x_mae_mm", + "translation_y_mae_mm", "translation_z_mae_mm", + "translation_x_signed_mm", "translation_y_signed_mm", + "translation_z_signed_mm", + ) + } + base.update({ + "side": "right", "depth_bucket": "near_le0.8m", + "size_bucket": "small_lt64", "joint3d_supervision": False, + "source_root_relative_supervision": False, + "translation_supervision": False, "vertices_supervision": False, + "ray_depth_confidence": math.nan, + }) + rows = [ + {**base, "headset_id": "Aria", "occlusion_bucket": "visible_ge16"}, + {**base, "headset_id": "Quest3", "occlusion_bucket": "partial_8_15"}, + ] + result = aggregate(rows) + assert result["bucket_headset_aria"]["hands"] == 1 + assert result["bucket_headset_quest3"]["hands"] == 1 + assert result["bucket_occlusion_partial_8_15"]["hands"] == 1 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_ranking.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_ranking.py new file mode 100644 index 0000000000000000000000000000000000000000..6b493669c9a008b27a5ac5eba78a5f820a4308f1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_ranking.py @@ -0,0 +1,43 @@ +import pytest + +from scripts.rank_phase7_external import dense_ranks, pareto_frontier, rank_entries + + +def test_external_ranking_is_dataset_macro_not_frame_weighted() -> None: + entries = [] + for condition, values in { + "balanced": {"ARCTIC": 2.0, "HOI4D": 2.0, "HOT3D": 2.0}, + "specialist": {"ARCTIC": 3.0, "HOI4D": 3.0, "HOT3D": 1.0}, + }.items(): + for dataset, value in values.items(): + entries.append({ + "condition": condition, "dataset": dataset, + "checkpoint_step": 10_000, + **{metric: value for metric in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", "translation_z_p95_mm", + )}, + }) + result = rank_entries(entries) + assert result["winner"] == "balanced" + + +def test_dense_rank_and_pareto_are_minimization_based() -> None: + assert dense_ranks({"a": 1.0, "b": 2.0, "c": 2.0}) == {"a": 1, "b": 2, "c": 2} + assert pareto_frontier({"a": [1.0, 2.0], "b": [2.0, 2.0], "c": [0.5, 3.0]}) == ["a", "c"] + + +def test_external_ranking_rejects_mismatched_steps() -> None: + entries = [] + for condition, step in (("a", 2_000), ("b", 10_000)): + for dataset in ("ARCTIC", "HOI4D", "HOT3D"): + entries.append({ + "condition": condition, "dataset": dataset, + "checkpoint_step": step, + "absolute_mpjpe_mm": 1.0, + "root_relative_mpjpe_mm": 1.0, + "fingertip_mpjpe_mm": 1.0, + "translation_z_p95_mm": 1.0, + }) + with pytest.raises(ValueError, match="not matched"): + rank_entries(entries) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_train_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..dd611c57cfa2f4b659fb437b91bcc1e9dbe7ae5a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_train_queue.py @@ -0,0 +1,96 @@ +import hashlib +import json +from pathlib import Path + +from scripts.run_phase7_external_train_queue import ( + cache_report_ready, + completed_matches, + training_command, + validate_stage_inputs, +) + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_cache_report_requires_complete_hash_bound_external_cache(tmp_path: Path) -> None: + manifest = tmp_path / "cache_manifest.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + report = tmp_path / "cache_report.json" + report.write_text(json.dumps({ + "status": "complete", "official_test_used": False, "cached_clips": 1, + "cache_manifest": {"path": str(manifest), "sha256": digest(manifest)}, + }), encoding="utf-8") + item = {"id": "source", "report": str(report), "manifest": str(manifest), "expected_clips": 1} + assert cache_report_ready(item) + manifest.write_text("changed\n", encoding="utf-8") + assert not cache_report_ready(item) + + +def test_training_command_uses_allowed_physical_gpu_and_exact_resume(tmp_path: Path) -> None: + item = { + "id": "E40_10k", "config": "frozen.yaml", + "output_dir": str(tmp_path / "run"), "stop_after_step": 10000, + "resume_from_step": 2000, + } + command = training_command(item, 3) + assert command[command.index("--physical-gpu-id") + 1] == "3" + assert command[command.index("--stop-after-step") + 1] == "10000" + assert command[command.index("--resume") + 1].endswith("step_0002000_final.pt") + + +def test_training_command_registers_explicit_schedule_tail(tmp_path: Path) -> None: + item = { + "id": "G_E40_200k", "config": "frozen.yaml", + "output_dir": str(tmp_path / "run"), "stop_after_step": 200000, + "resume_from_step": 100000, "allow_schedule_tail": True, + } + command = training_command(item, 2) + assert command[command.index("--resume") + 1].endswith("step_0100000_final.pt") + assert command[-1] == "--allow-schedule-tail" + + +def test_resume_checkpoint_sha_is_hash_bound(tmp_path: Path) -> None: + config = tmp_path / "config.yaml" + config.write_text("frozen\n", encoding="utf-8") + output = tmp_path / "run" + output.mkdir() + resume = output / "step_0100000_final.pt" + resume.write_bytes(b"checkpoint") + item = { + "config": str(config), "config_sha256": digest(config), + "output_dir": str(output), "resume_from_step": 100000, + "resume_checkpoint_sha256": digest(resume), + } + validate_stage_inputs(item) + item["resume_checkpoint_sha256"] = "0" * 64 + try: + validate_stage_inputs(item) + except RuntimeError as error: + assert "SHA256 mismatch" in str(error) + else: + raise AssertionError("mismatched resume checkpoint was accepted") + + +def test_completed_stage_requires_checkpoint_hash_and_no_h2o(tmp_path: Path) -> None: + output = tmp_path / "run" + marker_dir = output / ".phase7_queue" + marker_dir.mkdir(parents=True) + checkpoint = output / "step_0002000_final.pt" + checkpoint.write_bytes(b"checkpoint") + item = { + "id": "E40_2k", "output_dir": str(output), + "stop_after_step": 2000, "config_sha256": "config", + } + marker = { + "status": "complete", "completed_step": 2000, + "config_sha256": "config", "checkpoint": str(checkpoint), + "checkpoint_sha256": digest(checkpoint), + "h2o_training_data_used": False, "official_test_used": False, + } + (marker_dir / "E40_2k.json").write_text(json.dumps(marker), encoding="utf-8") + assert completed_matches(item) + marker["h2o_training_data_used"] = True + (marker_dir / "E40_2k.json").write_text(json.dumps(marker), encoding="utf-8") + assert not completed_matches(item) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_trainer.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..afa062d66d7014100ecadd5623e6539c0b899f35 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_external_trainer.py @@ -0,0 +1,437 @@ +from pathlib import Path +import os + +import yaml + +from scripts.train_phase7_external import ( + contains_h2o, + validate_adaptation_contract, + validate_external_contract, + validate_h2o_neutral_control_contract, + claim_physical_gpu, + release_physical_gpu_claim, + depth_input_condition_counts, + checkpoint_context_with_exposure, + reached_source_exposure_milestones, + validate_phase9_unified_contract, +) +from collections import Counter + + +def minimal_config() -> dict: + return { + "experiment": { + "phase": 7, "branch": "external_only", + "uses_h2o_training_data": False, + }, + "data": {"sources": [{ + "dataset": "HOT3D", "cache_manifest": "/external/hot3d/cache.jsonl", + "weight": 1.0, "K_input_dropout": 0.3, + }]}, + "model": {"dinov3_trainable_last_blocks": 0, "modality_dropout_prob": 0.0}, + } + + +def test_external_contract_accepts_hot3d() -> None: + assert validate_external_contract( + minimal_config(), Path("configs/phase7/e100.yaml"), + ) == [] + + +def test_external_contract_requires_unique_sampling_source_ids() -> None: + config = minimal_config() + config["data"]["sources"] = [ + {**config["data"]["sources"][0], "weight": 0.5}, + {**config["data"]["sources"][0], "weight": 0.5}, + ] + errors = validate_external_contract(config, Path("configs/phase8/left.yaml")) + assert any("duplicate external source_id" in error for error in errors) + config["data"]["sources"][0]["source_id"] = "HOT_general" + config["data"]["sources"][1]["source_id"] = "HOT_left" + assert validate_external_contract( + config, Path("configs/phase8/left.yaml"), + ) == [] + phase8 = minimal_config() + phase8["experiment"]["phase"] = 8 + assert validate_external_contract( + phase8, Path("configs/phase8/s_hot.yaml"), + ) == [] + + +def test_external_contract_rejects_h2o_and_initialization() -> None: + config = minimal_config() + config["data"]["sources"][0].update({ + "dataset": "H2O", "cache_manifest": "/data/H2O/train.jsonl", + }) + config["experiment"]["initialization_checkpoint"] = "/phase6/best.pt" + errors = validate_external_contract(config, Path("configs/phase7/bad.yaml")) + assert any("H2O source forbidden" in error for error in errors) + assert any("initialization_checkpoint" in error for error in errors) + + +def test_h2o_path_detection_is_component_based() -> None: + assert contains_h2o("/SSD3/foundation_hand/H2O/train.jsonl") + assert not contains_h2o("/tmp/no_h2o_training/config.yaml") + + +def test_adaptation_contract_requires_h2o_train_and_external_init() -> None: + config = { + "experiment": { + "phase": 7, "branch": "h2o_adaptation", + "uses_h2o_training_data": True, + "initialization_checkpoint_sha256": "a" * 64, + }, + "data": {"sources": [ + { + "dataset": "H2O", "cache_manifest": "/cache/h2o/train_fit.jsonl", + "split_role": "official_train", "weight": 0.5, + "K_input_dropout": 0.0, + }, + { + "dataset": "HOT3D", "cache_manifest": "/cache/hot3d/train.jsonl", + "split_role": "external_train", "weight": 0.5, + "K_input_dropout": 0.3, + }, + ], "validation_sources": [{ + "dataset": "H2O", "split_role": "train_group_heldout", + "cache_manifest": "/cache/h2o/train_group_heldout.jsonl", + }]}, + "model": {"dinov3_trainable_last_blocks": 0, "modality_dropout_prob": 0.0}, + } + assert validate_adaptation_contract(config) == [] + config["experiment"]["phase"] = 8 + assert validate_adaptation_contract(config) == [] + config["data"]["sources"][0]["split_role"] = "official_validation" + assert any("official_train" in error for error in validate_adaptation_contract(config)) + + +def test_phase8_neutral_h2o_control_has_no_fake_initialization() -> None: + config = { + "experiment": { + "phase": 8, "branch": "h2o_neutral_control", + "uses_h2o_training_data": True, "neutral_task_heads": True, + }, + "data": { + "sources": [{ + "dataset": "H2O", "cache_manifest": "/cache/h2o/train_fit.jsonl", + "split_role": "official_train", "weight": 1.0, + "K_input_dropout": 0.0, + }], + "validation_sources": [{ + "dataset": "H2O", "split_role": "train_group_heldout", + "cache_manifest": "/cache/h2o/train_group_heldout.jsonl", + }], + }, + "model": {"dinov3_trainable_last_blocks": 0, "modality_dropout_prob": 0.0}, + } + assert validate_h2o_neutral_control_contract(config) == [] + config["experiment"]["initialization_checkpoint_sha256"] = "a" * 64 + assert any( + "forbids initialization" in error + for error in validate_h2o_neutral_control_contract(config) + ) + + +def test_gpu_claim_is_atomic_and_reentrant_for_owner(tmp_path: Path, monkeypatch) -> None: + monkeypatch.setattr("scripts.train_phase7_external.Path", lambda value: tmp_path / Path(value).name) + assert claim_physical_gpu(2) + assert claim_physical_gpu(2) + release_physical_gpu_claim(2) + assert not (tmp_path / f"foundation_hand_{os.getuid()}_gpu2.claim").exists() + + +def test_depth_condition_exposure_names_are_stable() -> None: + import torch + + batch = {"depth_input_condition_code": torch.tensor([[0, 1, 2, 3, 12]])} + assert depth_input_condition_counts(batch) == { + "source_unavailable": 1, + "rgb_k": 1, + "clean_rgb_d_k": 1, + "corrupted_quantization": 1, + "corrupted_global_bias": 1, + } + + +def test_adaptation_contract_rejects_disguised_official_validation_cache() -> None: + config = { + "experiment": { + "phase": 7, "branch": "h2o_adaptation", + "uses_h2o_training_data": True, + "initialization_checkpoint_sha256": "a" * 64, + }, + "data": { + "sources": [{ + "dataset": "H2O", "cache_manifest": "/cache/h2o/official_val.jsonl", + "split_role": "official_train", "weight": 1.0, "K_input_dropout": 0.0, + }], + "validation_sources": [{ + "dataset": "H2O", "split_role": "train_group_heldout", + "cache_manifest": "/cache/h2o/train_group_heldout.jsonl", + }], + }, + "model": {"dinov3_trainable_last_blocks": 0, "modality_dropout_prob": 0.0}, + } + assert any("train_fit.jsonl" in error for error in validate_adaptation_contract(config)) + + +def phase9_config() -> dict: + return { + "seed": 20260717, + "experiment": { + "phase": 9, "branch": "phase9_unified", + "uses_h2o_training_data": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "initialization_checkpoint_sha256": "a" * 64, + }, + "data": { + "resolution_hw": [368, 640], "T": 8, + "sources": [ + {"dataset": "H2O", "source_id": "H2O", "split_role": "official_train", "weight": 0.25, "K_input_dropout": 0.0, "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/h2o_official_train7000_v1/cache_manifest.jsonl"}, + {"dataset": "HOT3D", "source_id": "HOT3D", "split_role": "external_train", "weight": 0.25, "K_input_dropout": 0.3, "cache_manifest": "/cache/hot/train.jsonl"}, + {"dataset": "HOI4D", "source_id": "HOI4D", "split_role": "external_train", "weight": 0.25, "K_input_dropout": 0.0, "cache_manifest": "/cache/hoi/train.jsonl"}, + {"dataset": "ARCTIC", "source_id": "ARCTIC", "split_role": "external_train", "weight": 0.25, "K_input_dropout": 0.0, "cache_manifest": "/cache/arctic/train.jsonl"}, + ], + }, + "model": { + "decoder_mode": "alternating", "use_temporal": True, + "translation_parameterization": "direct_xyz", + "dinov3_trainable_last_blocks": 0, + "temporal_attention_mode": "bidirectional", + }, + "loss": {"joint3d_root_relative": 10.0}, + "protocol": {"source_exposure_milestones": [{ + "id": "all20", "minimum_batches": { + "H2O": 20, "HOT3D": 20, "HOI4D": 20, "ARCTIC": 20, + }, + }]}, + } + + +def test_phase9_unified_contract_freezes_four_source_direct_xyz() -> None: + config = phase9_config() + assert validate_phase9_unified_contract( + config, Path("configs/phase9/mixtures/j25.yaml"), + ) == [] + config["model"]["translation_parameterization"] = "ray_depth_residual" + assert any( + "translation_parameterization=direct_xyz" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/mixtures/j25.yaml"), + ) + ) + config = phase9_config() + config["loss"]["joint3d_root_relative"] = 0.0 + assert any( + "joint3d_root_relative=10.0" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/mixtures/j25.yaml"), + ) + ) + config = phase9_config() + config["model"]["dinov3_trainable_last_blocks"] = 2 + config["protocol"]["backbone_learning_rate"] = 5e-7 + assert any( + "dinov3_trainable_last_blocks=0" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/backbone/last2.yaml"), + ) + ) + + +def test_phase9_unified_contract_requires_explicit_high_resolution_stage() -> None: + config = phase9_config() + config["data"]["resolution_hw"] = [512, 896] + assert any( + "full_data_640" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/resolution/high.yaml"), + ) + ) + config["experiment"]["phase9_stage"] = "resolution_896x512" + assert any( + "stage-matched" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/resolution/high.yaml"), + ) + ) + config["data"]["sources"][0]["cache_manifest"] = ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/h2o_train7000/cache_manifest.jsonl" + ) + assert validate_phase9_unified_contract( + config, Path("configs/phase9/resolution/high.yaml"), + ) == [] + + +def test_phase9_high_resolution_fold_requires_stage_matched_manifests() -> None: + config = phase9_config() + config["experiment"].update({ + "phase9_stage": "resolution_896x512", + "h2o_selection_fold": "lofamily_o", + }) + config["data"]["resolution_hw"] = [512, 896] + fold_root = ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "manifests/h2o_multifold_v1" + ) + config["data"]["sources"][0]["cache_manifest"] = ( + f"{fold_root}/lofamily_o_train.jsonl" + ) + config["data"]["validation_sources"] = [{ + "dataset": "H2O", + "cache_manifest": f"{fold_root}/lofamily_o_heldout.jsonl", + }] + assert validate_phase9_unified_contract( + config, Path("configs/phase9/resolution/lofamily_o.yaml"), + ) == [] + config["data"]["validation_sources"][0]["cache_manifest"] = ( + "artifacts/phase9/manifests/h2o_multifold_v1/lofamily_o_heldout.jsonl" + ) + assert any( + "fold validation manifest" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/resolution/lofamily_o.yaml"), + ) + ) + + +def test_phase9_unified_contract_keeps_shared_geometry_augmentation_gated() -> None: + config = phase9_config() + config["data"]["geometry_augmentation"] = { + "enabled": True, "probability": 0.8, + "scale_min": 0.9, "scale_max": 1.1, + "translation_fraction": 0.05, + } + assert any( + "not yet admitted" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/augmentation/shared.yaml"), + ) + ) + + +def test_phase9_shared_augmentation_requires_exact_frozen_contract() -> None: + config = phase9_config() + config["experiment"]["phase9_stage"] = "shared_augmentation_640" + config["data"]["geometry_augmentation"] = { + "enabled": True, "probability": 0.8, + "scale_min": 0.9, "scale_max": 1.1, + "translation_fraction": 0.05, + } + for source in config["data"]["sources"]: + if source["dataset"] in {"H2O", "HOI4D"}: + source["depth_corruption_probability"] = 0.3 + assert validate_phase9_unified_contract( + config, Path("configs/phase9/augmentation/shared_640.yaml"), + ) == [] + config["data"]["geometry_augmentation"]["scale_max"] = 1.2 + assert any( + "parameters differ" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/augmentation/shared_640.yaml"), + ) + ) + + +def test_phase9_nonaugmentation_stages_reject_depth_corruption() -> None: + config = phase9_config() + config["data"]["sources"][0]["depth_corruption_probability"] = 0.3 + assert any( + "depth corruption probability" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/mixtures/j25.yaml"), + ) + ) + + +def test_phase9_last2_requires_base_two_blocks_and_exact_lr() -> None: + config = phase9_config() + config["experiment"].update({ + "phase9_stage": "last2_5e7", + "last2_resolution_hw": [368, 640], + "last2_shared_augmentation": False, + }) + config["model"]["encoder"] = "dinov3" + config["model"]["dinov3_trainable_last_blocks"] = 2 + config["protocol"]["backbone_learning_rate"] = 5e-7 + assert validate_phase9_unified_contract( + config, Path("configs/phase9/last2/base_5e7.yaml"), + ) == [] + config["model"]["dinov3_model"] = "dinov3_vitl16" + assert any( + "DINO Base only" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/last2/large_5e7.yaml"), + ) + ) + + +def test_phase9_last2_1e6_is_distinct_conditional_contract() -> None: + config = phase9_config() + config["experiment"].update({ + "phase9_stage": "last2_1e6", + "last2_resolution_hw": [368, 640], + "last2_shared_augmentation": False, + }) + config["model"]["encoder"] = "dinov3" + config["model"]["dinov3_trainable_last_blocks"] = 2 + config["protocol"]["backbone_learning_rate"] = 5e-7 + assert any( + "1e-06" in error + for error in validate_phase9_unified_contract( + config, Path("configs/phase9/last2/base_1e6.yaml"), + ) + ) + config["protocol"]["backbone_learning_rate"] = 1e-6 + assert validate_phase9_unified_contract( + config, Path("configs/phase9/last2/base_1e6.yaml"), + ) == [] + + +def test_phase9_unified_contract_rejects_nontrain_h2o_path() -> None: + config = phase9_config() + config["data"]["sources"][0]["cache_manifest"] = "/cache/H2O/official_val.jsonl" + errors = validate_phase9_unified_contract( + config, Path("configs/phase9/mixtures/j25.yaml"), + ) + assert any("H2O train cache" in error for error in errors) + + +def test_source_exposure_milestones_and_resume_context_are_exact() -> None: + milestones = [{"id": "all20", "minimum_batches": {"H2O": 20, "HOT3D": 20}}] + counts = Counter({"H2O": 20, "HOT3D": 19}) + assert reached_source_exposure_milestones(milestones, counts, set()) == [] + counts["HOT3D"] = 20 + assert reached_source_exposure_milestones(milestones, counts, set()) == ["all20"] + context = checkpoint_context_with_exposure( + {"config_sha256": "a" * 64}, counts, + Counter({"H2O": 160, "HOT3D": 160}), + Counter({"clean_rgb_d_k": 160}), {"all20"}, + ) + assert context["source_exposure_batches"] == {"H2O": 20, "HOT3D": 20} + assert context["completed_source_exposure_milestones"] == ["all20"] + + +def test_scale100k_configs_freeze_matched_compute_and_scheduler() -> None: + root = Path(__file__).resolve().parents[1] + configs = { + name: yaml.safe_load(( + root / "configs" / "phase7" / "external" + / f"phase7_{name.lower()}_scale100k_s20260717.yaml" + ).read_text(encoding="utf-8")) + for name in ("E40", "E70", "E100") + } + assert all(validate_external_contract(config, Path(name)) == [] for name, config in configs.items()) + assert configs["E40"]["protocol"] == configs["E70"]["protocol"] == configs["E100"]["protocol"] + assert configs["E40"]["loss"] == configs["E70"]["loss"] == configs["E100"]["loss"] + for key in ("resolution_hw", "T", "batch_size", "photometric_augmentation"): + assert configs["E40"]["data"][key] == configs["E70"]["data"][key] == configs["E100"]["data"][key] + e40_model = dict(configs["E40"]["model"]) + e70_model = dict(configs["E70"]["model"]) + e100_model = dict(configs["E100"]["model"]) + assert e40_model == e70_model + assert e100_model.pop("use_depth") is False + assert e40_model.pop("use_depth") is True + assert e100_model == e40_model diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_freeze_queue_builders.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_freeze_queue_builders.py new file mode 100644 index 0000000000000000000000000000000000000000..683bb6890875f6c66f21ad91eb04ed94a5e9959a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_freeze_queue_builders.py @@ -0,0 +1,41 @@ +import json +from pathlib import Path + +import pytest + +from scripts.build_phase7_continuation_manifest import build_manifest +from scripts.build_phase7_h2o_zero_shot_queue import build_queue + + +def test_continuation_manifest_binds_all_datasets_and_steps(tmp_path: Path) -> None: + for step in (50000, 100000): + for dataset, mode in (("HOT3D", "rgb_k"), ("HOI4D", "rgb_d_k"), ("ARCTIC", "rgb_k")): + path = tmp_path / f"e40_scale_step{step}_{dataset.lower()}_heldout2048_{mode}" + path.mkdir() + (path / "evaluation.json").write_text( + json.dumps({"checkpoint_step": step}), encoding="utf-8", + ) + manifest = build_manifest(tmp_path, "E40", (50000, 100000)) + assert len(manifest["evaluations"]) == 6 + assert manifest["official_test_used"] is False + + +def test_zero_shot_queue_is_exact_three_mode_grid(tmp_path: Path) -> None: + freeze = tmp_path / "freeze.json" + freeze.write_text(json.dumps({ + "status": "external_generalist_frozen", "checkpoint_path": "/checkpoint.pt", + "checkpoint_sha256": "a" * 64, "config_path": "/config.yaml", + "h2o_validation_manifest": {"path": "/official_val.jsonl"}, + }), encoding="utf-8") + queue = build_queue(freeze, tmp_path / "h2o", tmp_path / "output") + assert {item["input_mode"] for item in queue["evaluations"]} == { + "rgb_d_k", "rgb_k", "rgb_only", + } + assert all(item["checkpoint_sha256"] == "a" * 64 for item in queue["evaluations"]) + + +def test_zero_shot_queue_rejects_unfrozen_record(tmp_path: Path) -> None: + freeze = tmp_path / "freeze.json" + freeze.write_text('{"status":"selected"}', encoding="utf-8") + with pytest.raises(ValueError, match="incomplete"): + build_queue(freeze, tmp_path, tmp_path / "output") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_adaptation_selection.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_adaptation_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..fdc82dea9653161d7a82cacaf2e897577bcfe6cd --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_adaptation_selection.py @@ -0,0 +1,105 @@ +import csv +import hashlib +import json +from pathlib import Path + +import pytest + +from scripts.select_phase7_h2o_adaptation import ( + paired_recording_bootstrap, + select, +) + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def artifact(path: Path) -> dict[str, str]: + return {"path": str(path), "sha256": digest(path)} + + +def write_rows(path: Path, offset: float) -> None: + fields = ( + "physical_recording_id", "camera_id", "frame_id", "side", + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + for recording, frame, base in (("r1", 0, 10.0), ("r1", 1, 20.0), ("r2", 0, 30.0)): + writer.writerow({ + "physical_recording_id": recording, "camera_id": "cam4", + "frame_id": frame, "side": "right", + **{field: base + offset for field in fields[4:]}, + }) + + +def make_candidate(tmp_path: Path, name: str, offset: float) -> dict[str, str]: + root = tmp_path / name + root.mkdir() + checkpoint = root / "checkpoint.pt"; checkpoint.write_bytes(name.encode()) + config = root / "config.yaml"; config.write_text(name, encoding="utf-8") + cache = tmp_path / "train_group_heldout.jsonl" + if not cache.exists(): + cache.write_text("{}\n", encoding="utf-8") + rows = root / "per_hand_frame_metrics.csv"; write_rows(rows, offset) + take = root / "take_metrics.csv"; take.write_text("physical_recording_id\nr1\n", encoding="utf-8") + means = { + "absolute_mpjpe_mm": 20.0 + offset, + "root_relative_mpjpe_mm": 15.0 + offset, + "mpvpe_mm": 19.0 + offset, + "fingertip_mpjpe_mm": 24.0 + offset, + "translation_z_mae_mm": 10.0 + offset, + } + report = { + "status": "evaluated_h2o_train_group_heldout", + "evaluation_role": "h2o_train_group_heldout", + "checkpoint_step": 20000, + "checkpoint": artifact(checkpoint), "config": artifact(config), + "cache_manifest": artifact(cache), "per_hand_rows": artifact(rows), + "take_metrics": artifact(take), + "metrics": { + field: {"mean": value, "p95": value + 5.0} + for field, value in means.items() + }, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + evaluation = root / "evaluation.json" + evaluation.write_text(json.dumps(report), encoding="utf-8") + return {"candidate": name, "evaluation": str(evaluation)} + + +def test_selects_lower_absolute_and_bootstraps_recordings(tmp_path: Path) -> None: + manifest = { + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used": False, "official_test_used": False, + "candidates": [make_candidate(tmp_path, "A1", 0.0), make_candidate(tmp_path, "A2", -2.0)], + } + result = select(manifest, seed=7, resamples=100) + assert result["winner"] == "A2" + paired = result["paired_recording_bootstrap_vs_winner"]["A1"]["absolute_mpjpe_mm"] + assert paired["recordings"] == 2 + assert paired["mean_delta"] == pytest.approx(2.0) + + +def test_paired_bootstrap_rejects_different_frame_identity(tmp_path: Path) -> None: + first, second = tmp_path / "first.csv", tmp_path / "second.csv" + write_rows(first, 0.0); write_rows(second, 1.0) + text = second.read_text(encoding="utf-8").replace("r2,cam4,0", "r3,cam4,0") + second.write_text(text, encoding="utf-8") + with pytest.raises(ValueError, match="identities differ"): + paired_recording_bootstrap(first, second, "absolute_mpjpe_mm", "mean", 7, 10) + + +def test_selection_refuses_validation_exposure(tmp_path: Path) -> None: + manifest = { + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used": True, "official_test_used": False, + "candidates": [], + } + with pytest.raises(ValueError, match="boundary"): + select(manifest) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_adaptation_validation.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_adaptation_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..5b169394bccb0e1aaf6689c7e6ef3dc2292ed770 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_adaptation_validation.py @@ -0,0 +1,98 @@ +import hashlib +import json +from pathlib import Path + +from scripts.build_phase8_h2o_adapted_validation_queue import build_queue +from scripts.freeze_phase7_h2o_adaptation_validation import build_freeze_record +from scripts.run_phase7_h2o_adapted_validation_queue import evaluator_command, validate_queue + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_freeze_binds_train_heldout_winner_before_validation(tmp_path: Path) -> None: + checkpoint = tmp_path / "checkpoint.pt"; checkpoint.write_bytes(b"checkpoint") + config = tmp_path / "config.yaml"; config.write_text("config", encoding="utf-8") + validation = tmp_path / "official_val.jsonl"; validation.write_text("{}\n", encoding="utf-8") + selection = tmp_path / "selection.json" + selection.write_text(json.dumps({ + "status": "selected_h2o_adaptation_train_group_heldout", + "selection_split": "h2o_train_group_heldout_only", "winner": "A1", + "candidates": [{ + "candidate": "A1", "checkpoint": str(checkpoint), + "checkpoint_sha256": digest(checkpoint), "checkpoint_step": 50000, + "config": str(config), "config_sha256": digest(config), + }], + "h2o_official_validation_used": False, "official_test_used": False, + }), encoding="utf-8") + result = build_freeze_record(selection, validation) + assert result["winner"] == "A1" + assert result["h2o_validation_manifest"]["sha256"] == digest(validation) + + +def test_adapted_validation_queue_is_exact_three_mode_grid() -> None: + evaluations = [{ + "id": mode, "input_mode": mode, "checkpoint_sha256": "a" * 64, + "checkpoint": "/checkpoint", "config": "/config", "freeze_record": "/freeze", + "root": "/h2o", "manifest": "/official_val.jsonl", "output_dir": f"/{mode}", + } for mode in ("rgb_d_k", "rgb_k", "rgb_only")] + queue = { + "official_test_used": False, "h2o_training_data_used": True, + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used_for_selection": False, + "evaluations": evaluations, + } + validate_queue(queue) + command = evaluator_command(evaluations[0], 2) + assert command[command.index("--evaluation-role") + 1] == "h2o_adapted_formal" + + +def test_builder_binds_nested_adaptation_freeze_artifacts(tmp_path: Path) -> None: + checkpoint = tmp_path / "checkpoint.pt"; checkpoint.write_bytes(b"checkpoint") + config = tmp_path / "config.yaml"; config.write_text("config", encoding="utf-8") + manifest = tmp_path / "official_val.jsonl"; manifest.write_text("{}\n", encoding="utf-8") + freeze = tmp_path / "freeze.json" + freeze.write_text(json.dumps({ + "status": "h2o_adaptation_candidate_frozen", "winner": "H2_direct", + "selection_split": "h2o_train_group_heldout_only", + "checkpoint": {"path": str(checkpoint), "sha256": digest(checkpoint), "step": 25000}, + "config": {"path": str(config), "sha256": digest(config)}, + "h2o_validation_manifest": {"path": str(manifest), "sha256": digest(manifest)}, + "frozen_h2o_input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }), encoding="utf-8") + (tmp_path / "subject3").mkdir() + queue = build_queue(freeze, tmp_path, tmp_path / "outputs") + assert [item["input_mode"] for item in queue["evaluations"]] == [ + "rgb_d_k", "rgb_k", "rgb_only", + ] + assert {item["checkpoint_sha256"] for item in queue["evaluations"]} == { + digest(checkpoint), + } + + +def test_builder_rejects_h2o_parent_instead_of_extracted_root(tmp_path: Path) -> None: + checkpoint = tmp_path / "checkpoint.pt"; checkpoint.write_bytes(b"checkpoint") + config = tmp_path / "config.yaml"; config.write_text("config", encoding="utf-8") + manifest = tmp_path / "official_val.jsonl"; manifest.write_text("{}\n", encoding="utf-8") + freeze = tmp_path / "freeze.json" + freeze.write_text(json.dumps({ + "status": "h2o_adaptation_candidate_frozen", "winner": "H2_direct", + "selection_split": "h2o_train_group_heldout_only", + "checkpoint": {"path": str(checkpoint), "sha256": digest(checkpoint), "step": 25000}, + "config": {"path": str(config), "sha256": digest(config)}, + "h2o_validation_manifest": {"path": str(manifest), "sha256": digest(manifest)}, + "frozen_h2o_input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }), encoding="utf-8") + try: + build_queue(freeze, tmp_path, tmp_path / "outputs") + except ValueError as error: + assert "canonical validation subject" in str(error) + else: + raise AssertionError("parent H2O root should be rejected") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_train_cache.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_train_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e53cde64c5292eb1719b765b863cc8f92a7a2e26 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_train_cache.py @@ -0,0 +1,31 @@ +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from scripts.cache_phase7_h2o_train import ( + balanced_clip_indices, + validate_train_manifest_path, +) + + +def test_h2o_train_cache_balances_subjects_and_takes() -> None: + clips = [] + for subject in ("subject1", "subject2"): + for take in ("a", "b", "c"): + for frame in range(8): + clips.append(SimpleNamespace( + take=f"{subject}/{take}/1/cam4", frame_ids=(frame,), + )) + selected = balanced_clip_indices(clips, count=24, max_recordings=4) + takes = {"/".join(Path(clips[index].take).parts[:-1]) for index in selected} + subjects = {Path(clips[index].take).parts[0] for index in selected} + assert len(selected) == 24 + assert len(takes) == 4 + assert subjects == {"subject1", "subject2"} + + +def test_h2o_train_cache_rejects_non_train_manifest(tmp_path: Path) -> None: + validate_train_manifest_path(tmp_path / "official_train.jsonl") + with pytest.raises(ValueError, match="official_train"): + validate_train_manifest_path(tmp_path / "official_val.jsonl") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_train_split.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_train_split.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1de47c10f3633edd8db08d3540937f71978357 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_train_split.py @@ -0,0 +1,33 @@ +from scripts.split_phase7_h2o_train_cache import assign_group_folds, split_rows + + +def rows() -> list[dict]: + result = [] + for subject in ("s1", "s2"): + for take in range(5): + for clip in range(2): + result.append({ + "dataset_id": "H2O", "subject_id": subject, + "physical_recording_id": f"{subject}/take{take}", + "source_clip_index": clip, + }) + return result + + +def test_group_split_is_deterministic_balanced_and_leak_free() -> None: + values = rows() + first = assign_group_folds(values, 5, 20260717) + second = assign_group_folds(values, 5, 20260717) + assert first == second + fit, heldout = split_rows(values, first, 0) + fit_groups = {row["physical_recording_id"] for row in fit} + heldout_groups = {row["physical_recording_id"] for row in heldout} + assert not fit_groups & heldout_groups + assert {row["subject_id"] for row in heldout} == {"s1", "s2"} + assert len(heldout_groups) == 2 + + +def test_every_recording_stays_in_one_fold() -> None: + assignments = assign_group_folds(rows(), 5, 20260717) + assert len(assignments) == 10 + assert all(0 <= fold < 5 for fold in assignments.values()) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_zero_shot.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..5c203c3a02cba3423f5a42fc75beae6a0ba4f2f0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_zero_shot.py @@ -0,0 +1,135 @@ +import hashlib +from pathlib import Path + +import numpy as np +import pytest +import torch + +from scripts.evaluate_phase7_h2o_zero_shot import ( + append_valid_frame_arrays, + validate_adaptation_freeze_record, + validate_freeze_record, + validate_phase9_freeze_record, +) + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_h2o_zero_shot_requires_frozen_external_selection(tmp_path: Path) -> None: + manifest = tmp_path / "official_val.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + record = { + "status": "external_generalist_frozen", + "checkpoint_sha256": "checkpoint", + "external_selection_sha256": "selection", + "official_test_used": False, + "h2o_official_validation_used_for_external_selection": False, + "frozen_h2o_input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "h2o_validation_manifest": { + "path": str(manifest), "sha256": digest(manifest), + }, + } + validate_freeze_record(record, "checkpoint", manifest, "rgb_only") + with pytest.raises(ValueError, match="checkpoint differs"): + validate_freeze_record(record, "other", manifest, "rgb_only") + with pytest.raises(ValueError, match="input mode"): + validate_freeze_record(record, "checkpoint", manifest, "depth_only") + + +def test_h2o_zero_shot_preserves_architecture_candidate_role(tmp_path: Path) -> None: + manifest = tmp_path / "official_val.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + record = { + "status": "external_architecture_candidate_frozen", + "selected_within_family": True, + "overall_external_generalist_winner": False, + "checkpoint_sha256": "checkpoint", + "external_selection_sha256": "selection", + "official_test_used": False, + "h2o_official_validation_used_for_external_selection": False, + "frozen_h2o_input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "h2o_validation_manifest": { + "path": str(manifest), "sha256": digest(manifest), + }, + } + validate_freeze_record(record, "checkpoint", manifest, "rgb_k") + record["overall_external_generalist_winner"] = True + with pytest.raises(ValueError, match="role is ambiguous"): + validate_freeze_record(record, "checkpoint", manifest, "rgb_k") + + +def test_h2o_zero_shot_rejects_noncanonical_manifest(tmp_path: Path) -> None: + manifest = tmp_path / "other.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + record = { + "status": "external_generalist_frozen", + "checkpoint_sha256": "checkpoint", + "external_selection_sha256": "selection", + "official_test_used": False, + "h2o_official_validation_used_for_external_selection": False, + "frozen_h2o_input_modes": ["rgb_d_k"], + "h2o_validation_manifest": { + "path": str(manifest), "sha256": digest(manifest), + }, + } + with pytest.raises(ValueError, match="canonical H2O official validation"): + validate_freeze_record(record, "checkpoint", manifest, "rgb_d_k") + + +def test_h2o_adapted_formal_requires_train_heldout_freeze(tmp_path: Path) -> None: + manifest = tmp_path / "official_val.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + record = { + "status": "h2o_adaptation_candidate_frozen", + "checkpoint": {"sha256": "checkpoint"}, + "adaptation_selection_sha256": "selection", + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "frozen_h2o_input_modes": ["rgb_d_k"], + "h2o_validation_manifest": { + "path": str(manifest.resolve()), "sha256": digest(manifest), + }, + } + validate_adaptation_freeze_record(record, "checkpoint", manifest, "rgb_d_k") + record["h2o_official_validation_used_for_selection"] = True + with pytest.raises(ValueError, match="train-heldout"): + validate_adaptation_freeze_record(record, "checkpoint", manifest, "rgb_d_k") + + +def test_phase9_formal_requires_complete_post_selection_freeze(tmp_path: Path) -> None: + manifest = tmp_path / "official_val.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + record = { + "status": "phase9_final_unified_checkpoint_frozen", + "checkpoint": {"sha256": "checkpoint"}, + "selection_complete": True, + "stage9_final_decision_complete": True, + "selection_chain_sha256": "a" * 64, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "frozen_h2o_input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "h2o_validation_manifest": { + "path": str(manifest.resolve()), "sha256": digest(manifest), + }, + } + validate_phase9_freeze_record(record, "checkpoint", manifest, "rgb_k") + record["selection_complete"] = False + with pytest.raises(ValueError, match="selection provenance"): + validate_phase9_freeze_record(record, "checkpoint", manifest, "rgb_k") + + +def test_raw_cache_flattens_variable_length_clips_to_valid_frames() -> None: + raw: dict[str, list[np.ndarray]] = {} + append_valid_frame_arrays( + raw, {"value": torch.arange(8).reshape(1, 8, 1)}, + torch.ones((1, 8), dtype=torch.bool), + ) + append_valid_frame_arrays( + raw, {"value": torch.arange(8, 14).reshape(1, 6, 1)}, + torch.ones((1, 6), dtype=torch.bool), + ) + combined = np.concatenate(raw["value"], axis=0) + assert combined.shape == (14, 1) + assert combined[:, 0].tolist() == list(range(14)) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_zero_shot_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_zero_shot_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..4367b012ac2c783f0c69b367b9e6d7283dfc4775 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_h2o_zero_shot_queue.py @@ -0,0 +1,30 @@ +import pytest + +from scripts.run_phase7_h2o_zero_shot_queue import validate_queue + + +def queue() -> dict: + return { + "official_test_used": False, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "evaluations": [ + { + "id": mode, "input_mode": mode, "checkpoint_sha256": "sha", + "manifest": "/official_val.jsonl", + } + for mode in ("rgb_d_k", "rgb_k", "rgb_only") + ], + } + + +def test_zero_shot_queue_requires_complete_frozen_mode_grid() -> None: + validate_queue(queue()) + incomplete = queue() + incomplete["evaluations"].pop() + with pytest.raises(ValueError, match="three unique input modes"): + validate_queue(incomplete) + mismatched = queue() + mismatched["evaluations"][0]["checkpoint_sha256"] = "other" + with pytest.raises(ValueError, match="one frozen checkpoint"): + validate_queue(mismatched) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_heldout_cache_plan.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_heldout_cache_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..675b79835b4c37a30c194451bd5ce0b5dbafd5d9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_heldout_cache_plan.py @@ -0,0 +1,23 @@ +import hashlib +import json +from pathlib import Path + + +def test_formal_external_heldout_cache_plan_is_hash_bound_and_macro_balanced() -> None: + root = Path(__file__).resolve().parents[1] + plan = json.loads(( + root / "artifacts" / "phase7" / "registry" + / "external_heldout_cache_plan.json" + ).read_text(encoding="utf-8")) + assert plan["clips_per_dataset"] == 2048 + assert plan["official_test_used"] is False + assert plan["h2o_used"] is False + assert {item["dataset"] for item in plan["sources"]} == {"HOT3D", "HOI4D", "ARCTIC"} + for item in plan["sources"]: + manifest = Path(item["source_manifest"]) + assert manifest.is_file() + assert hashlib.sha256(manifest.read_bytes()).hexdigest() == item["source_manifest_sha256"] + assert item["physical_recordings"] == item["max_recordings"] + assert "official" not in item["output_dir"].lower() + assert "test" not in item["output_dir"].lower() + assert "/phase7_artifacts/cache/" in item["output_dir"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_heldout_cache_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_heldout_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..ab64c13c6f4656208c747a5e98c19991b6d4a6e7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_heldout_cache_queue.py @@ -0,0 +1,45 @@ +import json +from pathlib import Path + +from scripts.run_phase7_heldout_cache_queue import ( + command_tokens, + dependency_ready, + output_complete, +) + + +def test_heldout_cache_command_extracts_repo_pythonpath() -> None: + command, environment = command_tokens("PYTHONPATH=src python -m cache_tool --clips 2048") + assert command[:3] == ["python", "-m", "cache_tool"] + assert environment["PYTHONPATH"].endswith("/foundation_hand/src") + + +def test_heldout_cache_dependency_requires_complete_10k_report(tmp_path: Path) -> None: + report = tmp_path / "cache_report.json" + report.write_text(json.dumps({"status": "complete", "clips": 10000, "official_test_used": False}), encoding="utf-8") + assert dependency_ready({"dependency": str(report)}) + report.write_text(json.dumps({"status": "incomplete", "clips": 10000, "official_test_used": False}), encoding="utf-8") + assert not dependency_ready({"dependency": str(report)}) + + +def test_heldout_cache_output_validates_manifest_hash(tmp_path: Path) -> None: + output = tmp_path / "out" + output.mkdir() + manifest = output / "cache_manifest.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + import hashlib + digest = hashlib.sha256(manifest.read_bytes()).hexdigest() + (output / "cache_report.json").write_text(json.dumps({ + "status": "complete", "clips": 2048, "official_test_used": False, + "recordings": 62, + "source_manifest": {"sha256": "source"}, + "cache_manifest": {"path": str(manifest), "sha256": digest}, + }), encoding="utf-8") + assert output_complete({ + "output_dir": str(output), "source_manifest_sha256": "source", + "physical_recordings": 62, + }) + assert not output_complete({ + "output_dir": str(output), "source_manifest_sha256": "source", + "physical_recordings": 63, + }) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_hoi4d_adapter.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_hoi4d_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..1fade71e41d445df1deaebbfac08817121f466c0 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_hoi4d_adapter.py @@ -0,0 +1,71 @@ +import pickle +from pathlib import Path + +import numpy as np +import pytest +import subprocess + +from foundation_hand.data.hoi4d_dataset import ( + decode_video_frames, + frame_select_expression, + hoi4d_geometry_compatibility_mask, + load_hoi4d_mano_annotation, +) +from foundation_hand.data.schema import InvalidSourceSampleError +import torch + + +def test_decode_requires_sorted_unique_frames() -> None: + with pytest.raises(ValueError, match="sorted and unique"): + decode_video_frames("unused", [3, 1], (2, 2), "gray16le", " None: + commands = [] + + def run(command, **kwargs): + commands.append(command) + return subprocess.CompletedProcess(command, 0, stdout=bytes(2 * 2 * 2), stderr=b"") + + monkeypatch.setattr(subprocess, "run", run) + result = decode_video_frames( + "video", [15, 16], (2, 2), "gray16le", "u1", 1, fps=15, + ) + assert result.shape == (2, 2, 2) + assert commands[0][commands[0].index("-ss") + 1] == "1.000000000" + assert commands[0].index("-ss") < commands[0].index("-i") + assert "-vf" not in commands[0] + + +def test_invalid_hoi4d_annotation_is_classified_as_source_payload(tmp_path: Path) -> None: + path = tmp_path / "invalid.pickle" + with path.open("wb") as handle: + pickle.dump({ + "poseCoeff": np.zeros(47), "beta": np.zeros(10), + "trans": np.zeros(3), "kps2D": np.zeros((21, 2)), + }, handle) + with pytest.raises(InvalidSourceSampleError, match="poseCoeff"): + load_hoi4d_mano_annotation(path) + + +def test_hoi4d_annotation_loader_does_not_hide_non_payload_errors( + tmp_path: Path, monkeypatch, +) -> None: + path = tmp_path / "valid.pickle" + path.write_bytes(b"payload") + + def unexpected(_handle): + raise RuntimeError("scientific failure") + + monkeypatch.setattr(pickle, "load", unexpected) + with pytest.raises(RuntimeError, match="scientific failure"): + load_hoi4d_mano_annotation(path) + + +def test_hoi4d_geometry_gate_masks_historical_left_and_right_over_one_mm() -> None: + hand_valid = torch.ones(2, 2, dtype=torch.bool) + error_mm = torch.tensor([[0.1, 0.9], [0.2, 1.01]]) + result = hoi4d_geometry_compatibility_mask(hand_valid, error_mm) + assert result.tolist() == [[False, True], [False, False]] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_hoi4d_manifest.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_hoi4d_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..40af01f3c733aaa1c7d53534db9ec8ee6a835d20 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_hoi4d_manifest.py @@ -0,0 +1,23 @@ +from pathlib import Path + +from scripts.build_phase7_hoi4d_manifests import ( + SERIALS, + discover_hand_frames, + split_for_serial, +) + + +def test_hoi4d_split_holds_out_complete_serial() -> None: + assert split_for_serial(SERIALS[-1], SERIALS[-1]) == "heldout" + assert all(split_for_serial(serial, SERIALS[-1]) == "train" for serial in SERIALS[:-1]) + + +def test_hoi4d_discovery_preserves_side_slots(tmp_path: Path) -> None: + for side, frames in (("left", (1,)), ("right", (1, 2))): + directory = tmp_path / "Hand_pose" / f"handpose_{side}_hand" / "serial/H1/recording" + directory.mkdir(parents=True) + for frame in frames: + (directory / f"{frame}.pickle").touch() + rows = discover_hand_frames(tmp_path) + assert rows["serial/H1/recording"][1] == {"left", "right"} + assert rows["serial/H1/recording"][2] == {"right"} diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_hot3d_adapter.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_hot3d_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..b86769928fc8bdf55220b57a016f948a2630dbb1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_hot3d_adapter.py @@ -0,0 +1,69 @@ +import numpy as np +import torch + +from foundation_hand.data.hot3d_dataset import ( + geometry_valid_mask, + linear_camera_matrix, + pca_to_full_local_pose, + transform_points, +) +from scripts.build_phase7_hot3d_manifests import ( + contiguous_clips, + nearest_timestamp, + participant_split, +) + + +class Calibration: + def get_focal_lengths(self): + return np.asarray((500.0, 510.0)) + + def get_principal_point(self): + return np.asarray((320.0, 240.0)) + + +class SourceLayer: + hand_components = torch.eye(45)[:15] + pose_mean = torch.arange(48, dtype=torch.float32) / 100.0 + + +def test_hot3d_camera_transform_and_intrinsics() -> None: + transform = np.eye(4) + transform[:3, 3] = (1.0, -2.0, 3.0) + result = transform_points(np.asarray([[0.5, 0.25, 1.0]]), transform) + np.testing.assert_allclose(result, [[1.5, -1.75, 4.0]]) + np.testing.assert_array_equal( + linear_camera_matrix(Calibration()), + [[500.0, 0.0, 320.0], [0.0, 510.0, 240.0], [0.0, 0.0, 1.0]], + ) + + +def test_hot3d_pca_expansion_includes_official_hand_mean() -> None: + coefficients = np.arange(15, dtype=np.float32) + full = pca_to_full_local_pose(coefficients, SourceLayer()) + expected = torch.cat((torch.arange(15, dtype=torch.float32), torch.zeros(30))) + expected += SourceLayer.pose_mean[3:] + torch.testing.assert_close(full.reshape(-1), expected) + + +def test_hot3d_geometry_audit_masks_only_failing_frame_and_side() -> None: + present = torch.tensor([[True, True], [True, False]]) + errors = torch.tensor([[0.25, 5.056], [0.99, float("nan")]]) + torch.testing.assert_close( + geometry_valid_mask(present, errors), + torch.tensor([[True, False], [True, False]]), + ) + + +def test_hot3d_manifest_split_and_temporal_grouping() -> None: + train, heldout = participant_split([f"P{i:04d}" for i in range(1, 9)]) + assert not train & heldout + assert train | heldout == {f"P{i:04d}" for i in range(1, 9)} + timestamps = [0, 33, 66, 99, 132, 165, 198, 231, 1_000] + clips = contiguous_clips((value * 1_000_000 for value in timestamps), 4) + assert clips == [ + [0, 33_000_000, 66_000_000, 99_000_000], + [132_000_000, 165_000_000, 198_000_000, 231_000_000], + ] + assert nearest_timestamp(105, [0, 100, 200], 10) == 100 + assert nearest_timestamp(120, [0, 100, 200], 10) is None diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_mano_convention.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_mano_convention.py new file mode 100644 index 0000000000000000000000000000000000000000..046687ab1f2a496903873cf8c7cca2b0fe773ccb --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_mano_convention.py @@ -0,0 +1,33 @@ +from pathlib import Path + +import pytest +import torch + +from foundation_hand.models.mano import ManoCameraLayer + + +MANO_ROOT = Path("/SSD3/jiasen/foundation_hand/pretrained/mano") + + +@pytest.mark.skipif(not MANO_ROOT.exists(), reason="licensed MANO unavailable") +def test_hot3d_left_shapedirs_fix_is_explicit_and_default_off() -> None: + historical = ManoCameraLayer(MANO_ROOT) + corrected = ManoCameraLayer(MANO_ROOT, fix_left_shapedirs=True) + torch.testing.assert_close( + corrected.layers[0].th_shapedirs[:, 0, :], + -historical.layers[0].th_shapedirs[:, 0, :], + rtol=0, + atol=0, + ) + torch.testing.assert_close( + corrected.layers[0].th_shapedirs[:, 1:, :], + historical.layers[0].th_shapedirs[:, 1:, :], + rtol=0, + atol=0, + ) + torch.testing.assert_close( + corrected.layers[1].th_shapedirs, + historical.layers[1].th_shapedirs, + rtol=0, + atol=0, + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_mixture_sampler.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_mixture_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..b34a16fdc36607fd1b5e5aa999460a26a08d502a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_mixture_sampler.py @@ -0,0 +1,34 @@ +from foundation_hand.data.samplers import ResumableMixtureBatchSampler + + +def test_mixture_sampler_exact_resume() -> None: + full = list(ResumableMixtureBatchSampler( + [7, 11, 13], [0.4, 0.4, 0.2], 4, 20260717, 0, 20, True, + )) + resumed = list(ResumableMixtureBatchSampler( + [7, 11, 13], [0.4, 0.4, 0.2], 4, 20260717, 7, 20, True, + )) + assert resumed == full[7:] + + +def test_mixture_sampler_uses_registered_source_weights() -> None: + batches = ResumableMixtureBatchSampler( + [10, 10, 10], [0.4, 0.4, 0.2], 100, 17, 0, 100, + ) + counts = [0, 0, 0] + for batch in batches: + for index in batch: + counts[min(int(index) // 10, 2)] += 1 + fractions = [count / sum(counts) for count in counts] + assert abs(fractions[0] - 0.4) < 0.02 + assert abs(fractions[1] - 0.4) < 0.02 + assert abs(fractions[2] - 0.2) < 0.02 + + +def test_mixture_sampler_rejects_invalid_contract() -> None: + try: + ResumableMixtureBatchSampler([1, 2], [1.0], 1, 0, 0, 1) + except ValueError as error: + assert "match" in str(error) + else: + raise AssertionError("invalid mixture was accepted") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_scale_eval_queue_builder.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_scale_eval_queue_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef7e24389bd59f7945ebdaab54b43a8e669d5d8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_scale_eval_queue_builder.py @@ -0,0 +1,65 @@ +import hashlib +import json +from pathlib import Path + +from scripts.build_phase7_scale_eval_queue import build_queue, stage_suffix + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_scale_eval_queue_requires_markers_and_formal_cache_grid(tmp_path: Path) -> None: + sources = [] + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + output = tmp_path / dataset + output.mkdir() + manifest = output / "cache_manifest.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + (output / "cache_report.json").write_text(json.dumps({ + "status": "complete", "clips": 2048, "official_test_used": False, + "source_manifest": {"sha256": f"{dataset}-source"}, + "cache_manifest": {"path": str(manifest), "sha256": digest(manifest)}, + }), encoding="utf-8") + sources.append({ + "dataset": dataset, "output_dir": str(output), + "source_manifest_sha256": f"{dataset}-source", + }) + roots = {} + for condition in ("E40", "E70", "E100"): + run = tmp_path / f"run_{condition}" + marker_dir = run / ".phase7_queue" + marker_dir.mkdir(parents=True) + checkpoint = run / "step_0002000_final.pt" + checkpoint.write_bytes(condition.encode()) + config = run / "config.yaml" + config.write_text(condition, encoding="utf-8") + (marker_dir / f"{condition}_scale_2k.json").write_text(json.dumps({ + "status": "complete", "completed_step": 2000, + "official_test_used": False, "h2o_training_data_used": False, + "checkpoint": str(checkpoint), "checkpoint_sha256": digest(checkpoint), + "config": str(config), "config_sha256": digest(config), + }), encoding="utf-8") + roots[condition] = run + queue = build_queue( + {"official_test_used": False, "h2o_used": False, "sources": sources}, + roots, 2000, tmp_path / "evaluations", + ) + assert len(queue["evaluations"]) == 9 + modes = {(item["id"].split("_")[0], item["id"].split("_")[1]): item["input_mode"] for item in queue["evaluations"]} + assert modes[("E40", "HOI4D")] == "rgb_d_k" + assert modes[("E100", "HOI4D")] == "rgb_k" + assert queue["official_test_used"] is False + selected = build_queue( + {"official_test_used": False, "h2o_used": False, "sources": sources}, + roots, 2000, tmp_path / "selected_evaluations", ("E40", "E70"), + ) + assert len(selected["evaluations"]) == 6 + assert {item["id"].split("_")[0] for item in selected["evaluations"]} == { + "E40", "E70", + } + + +def test_scale_eval_queue_supports_registered_long_horizons() -> None: + assert stage_suffix(50000) == "50k" + assert stage_suffix(100000) == "100k" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_sequence_cache_config.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_sequence_cache_config.py new file mode 100644 index 0000000000000000000000000000000000000000..7d8f2a026a1ed9f6c3d36fd4fd07b25de6bdbba7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_sequence_cache_config.py @@ -0,0 +1,22 @@ +import pytest + +from scripts.cache_phase6_sequence_predictions import offline_stride, validate_sequence_config + + +def test_sequence_cache_accepts_training_temporal_length_metadata() -> None: + bidirectional = {"data": {"T": 8}, "model": {"temporal_attention_mode": "bidirectional"}} + causal = {"data": {"T": 8}, "model": {"temporal_attention_mode": "causal"}} + validate_sequence_config(bidirectional, "offline") + validate_sequence_config(causal, "causal") + + +def test_sequence_cache_still_enforces_attention_causality() -> None: + config = {"data": {"T": 8}, "model": {"temporal_attention_mode": "bidirectional"}} + with pytest.raises(ValueError, match="attention"): + validate_sequence_config(config, "causal") + + +def test_single_frame_offline_stride_is_valid() -> None: + assert offline_stride(1, "offline") == 1 + assert offline_stride(8, "offline") == 4 + assert offline_stride(8, "causal") is None diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_sequence_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_sequence_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..7034304ba94544a29ce59e2bebccc3004eff8823 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_sequence_summary.py @@ -0,0 +1,34 @@ +import numpy as np +import pytest + +from scripts.summarize_phase7_sequence_cache import continuous_take_arrays, validate_manifest + + +def manifest() -> dict: + return { + "status": "complete", "split_role": "official_validation", + "official_validation_used_for_selection": False, "official_test_used": False, + "sequence_mode": "causal", "sequence_window": 8, + } + + +def test_sequence_summary_accepts_frozen_nonselection_cache() -> None: + validate_manifest(manifest(), "manifest") + + +def test_sequence_summary_rejects_selection_or_test_exposure() -> None: + value = manifest() + value["official_validation_used_for_selection"] = True + with pytest.raises(ValueError, match="invalid frozen"): + validate_manifest(value, "manifest") + + +def test_sequence_take_normalizes_legacy_per_frame_clip_indices() -> None: + arrays = { + "sequence_mode": np.asarray("causal"), + "frame_id": np.asarray([10, 11, 12]), + "clip_index": np.asarray([100, 101, 102]), + } + normalized = continuous_take_arrays(arrays) + assert normalized["clip_index"].tolist() == [0, 0, 0] + assert arrays["clip_index"].tolist() == [100, 101, 102] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_supervision_schema.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_supervision_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..6c37d678959ab63788bb83b71168c85f970bf464 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_supervision_schema.py @@ -0,0 +1,143 @@ +import copy + +import torch + +from foundation_hand.data.schema import deterministic_clip_keep +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from test_model import synthetic_batch + + +def equivalent_phase7_masks(batch: dict[str, torch.Tensor]) -> None: + joint = batch["joint_element_valid"] & batch["joint_annotation_valid"][..., None] + batch["joint2d_valid"] = joint.clone() + batch["joint3d_valid"] = joint.clone() + batch["translation_valid"] = batch["joint_annotation_valid"].clone() + batch["mano_pose_valid"] = batch["mano_annotation_valid"].clone() + batch["shape_valid"] = batch["mano_annotation_valid"].clone() + batch["vertices_valid"] = batch["mano_annotation_valid"].clone() + batch["reprojection_valid"] = joint.clone() + batch["presence_valid"] = batch["presence_label_valid"].clone() + batch["depth_input_available"] = batch["depth_available"].clone() + batch["K_input_available"] = batch["K_available"].clone() + batch["K_supervision_valid"] = batch["frame_valid"].clone() + + +def test_equivalent_phase7_masks_preserve_legacy_h2o_losses_exactly() -> None: + torch.manual_seed(17) + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, + )) + batch = synthetic_batch(time=2) + prediction = model(batch) + criterion = BimanualLoss(LossConfig()) + legacy = criterion(prediction, batch) + equivalent_phase7_masks(batch) + unified = criterion(prediction, batch) + assert legacy.keys() == unified.keys() + for key in legacy: + torch.testing.assert_close(legacy[key], unified[key], rtol=0, atol=0) + + +def test_translation_and_joint3d_supervision_are_independent() -> None: + torch.manual_seed(18) + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, + )) + batch = synthetic_batch(time=2) + equivalent_phase7_masks(batch) + batch["translation_valid"].zero_() + prediction = model(batch) + prediction["joints_camera"] = torch.zeros_like(batch["joint3d_camera"]) + losses = BimanualLoss(LossConfig())(prediction, batch) + assert losses["translation"].item() == 0.0 + assert losses["joint3d_camera"].item() > 0.0 + + +def test_source_root_relative_joint_loss_is_independent_of_camera_joint_mask() -> None: + torch.manual_seed(180) + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, + )) + batch = synthetic_batch(time=2) + equivalent_phase7_masks(batch) + target = batch["joint3d_camera"] - batch["joint3d_camera"][..., :1, :] + batch["joint3d_root_relative"] = target + batch["joint3d_root_relative_valid"] = batch["joint3d_valid"].clone() + batch["joint3d_valid"].zero_() + batch["joint3d_camera"].fill_(torch.nan) + prediction = model(batch) + prediction["joints_camera"] = torch.zeros_like(target) + losses = BimanualLoss(LossConfig(joint3d_root_relative=10.0))(prediction, batch) + assert losses["joint3d_camera"].item() == 0.0 + assert losses["joint3d_root_relative"].item() > 0.0 + assert torch.isfinite(losses["total"]) + + +def test_partial_nan_supervision_is_mask_safe() -> None: + torch.manual_seed(19) + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, + )) + batch = synthetic_batch(time=2) + equivalent_phase7_masks(batch) + batch["mano_pose_valid"].zero_() + batch["shape_valid"].zero_() + batch["joint2d_valid"].zero_() + batch["joint3d_valid"].zero_() + for key in ("mano_pose", "mano_shape", "joint2d", "joint3d_camera"): + batch[key].fill_(torch.nan) + losses = BimanualLoss(LossConfig())(model(batch), batch) + assert losses["translation"].item() > 0.0 + assert all(torch.isfinite(value) for value in losses.values()) + + +def test_direct_2d_can_remain_valid_when_mano_reprojection_is_masked() -> None: + torch.manual_seed(21) + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, + )) + batch = synthetic_batch(time=2) + equivalent_phase7_masks(batch) + batch["reprojection_valid"].zero_() + losses = BimanualLoss(LossConfig())(model(batch), batch) + assert losses["joint2d"].item() > 0.0 + assert losses["reprojection"].item() == 0.0 + + +def test_hidden_input_K_does_not_remove_supervision_K() -> None: + torch.manual_seed(20) + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=64, decoder_layers=1, + attention_heads=4, use_depth=False, use_rays=True, + )).eval() + hidden = synthetic_batch(time=2) + equivalent_phase7_masks(hidden) + hidden["K_input_available"].zero_() + no_k = copy.deepcopy(hidden) + no_k.pop("K") + no_k.pop("K_available") + no_k.pop("K_input_available") + with torch.no_grad(): + hidden_output = model(hidden) + no_k_output = model(no_k) + torch.testing.assert_close( + hidden_output["hand_tokens"], no_k_output["hand_tokens"], + rtol=0, atol=0, + ) + assert hidden["K_supervision_valid"].all() + + +def test_external_dropout_is_clip_consistent_and_reproducible() -> None: + values = [deterministic_clip_keep(0.7, 20260717, 9, 3) for _ in range(5)] + assert len(set(values)) == 1 + sequence = [ + deterministic_clip_keep(0.7, 20260717, index, 3) + for index in range(64) + ] + assert any(sequence) and not all(sequence) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_unified_cache.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_unified_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..f673327802d75c9c2f4684620c50ca7cc40fb5ed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase7_unified_cache.py @@ -0,0 +1,81 @@ +from scripts.cache_phase7_unified_source import ( + balanced_source_indices, + cache_completion_status, + cache_candidate_count, + center_out, + first_valid_indices, + hand_side_source_indices, + recording_local_batches, + should_stop_decoding, +) + + +def test_prefetch_is_explicit_opt_in_in_cache_script() -> None: + from pathlib import Path + + source = ( + Path(__file__).resolve().parents[1] / "scripts" + / "cache_phase7_unified_source.py" + ).read_text(encoding="utf-8") + assert 'args.dataset == "HOI4D" and args.prefetch_batch_size and missing' in source + + +def test_center_out_starts_at_recording_middle() -> None: + assert center_out(list(range(7)))[:5] == [3, 4, 2, 5, 1] + + +def test_unified_cache_selection_balances_subjects_and_recordings() -> None: + rows = [] + for subject in ("s1", "s2"): + for recording in ("a", "b", "c"): + for frame in range(10): + rows.append({ + "subject_id": subject, + "physical_recording_id": f"{subject}/{recording}", + "frame": frame, + }) + selected = balanced_source_indices(rows, 20, max_recordings=4) + groups = {rows[index]["physical_recording_id"] for index in selected} + subjects = {rows[index]["subject_id"] for index in selected} + assert len(selected) == 20 + assert len(groups) == 4 + assert subjects == {"s1", "s2"} + + +def test_unified_cache_overdraw_backfills_invalid_candidates() -> None: + assert cache_candidate_count(512, 1000) == 564 + assert cache_candidate_count(128, 140) == 140 + selected = [10, 11, 12, 13, 14] + cached = {10: {}, 12: {}, 13: {}, 14: {}} + assert first_valid_indices(selected, cached, 3) == [10, 12, 13] + assert should_stop_decoding(selected, cached, 3, decode_all_candidates=False) + assert not should_stop_decoding(selected, cached, 3, decode_all_candidates=True) + + +def test_full_manifest_cache_accepts_every_valid_clip_without_weakening_fixed_count() -> None: + selected = [0, 1, 2, 3] + cached = {0: {}, 2: {}, 3: {}} + assert cache_completion_status(4, selected, cached, 4, True) == "complete" + assert cache_completion_status(4, selected, cached, 4, False) == "insufficient_valid_clips" + assert cache_completion_status(4, selected, cached, 3, True) == "incomplete_source_scan" + + +def test_recording_local_prefetch_batches_do_not_cross_groups() -> None: + rows = [ + {"physical_recording_id": recording} + for recording in ("a", "a", "a", "a", "a", "b", "b") + ] + assert recording_local_batches(list(range(7)), rows, batch_size=4) == [ + [0, 1, 2, 3], [4], [5, 6], + ] + + +def test_hand_side_filter_preserves_source_indices() -> None: + rows = [ + {"hand_sides": [["right"], ["right"]]}, + {"hand_sides": [["left"], ["left", "right"]]}, + {"hand_sides": []}, + ] + assert hand_side_source_indices(rows, "any") == [0, 1, 2] + assert hand_side_source_indices(rows, "left") == [1] + assert hand_side_source_indices(rows, "right") == [0, 1] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..da84907c4e3836b9b3b000f2e32852bdb2c0655a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_configs.py @@ -0,0 +1,145 @@ +from pathlib import Path + +import pytest +import yaml + +from scripts.train_phase7_external import validate_adaptation_contract + + +ROOT = Path("configs/phase8/stage6") +FILES = { + "H1": ROOT / "phase8_h1_direct_g200_h2o_only_s20260717.yaml", + "H2": ROOT / "phase8_h2_direct_g200_h2o80_replay20_s20260717.yaml", + "H3": ROOT / "phase8_h3_direct_g200_h2o50_replay50_s20260717.yaml", + "H4": ROOT / "phase8_h4_direct_g200_h2o_dropout005_s20260717.yaml", +} +RAY_H1 = ROOT / "phase8_h1_ray_r2step50_h2o_only_s20260717.yaml" +RAY_FILES = { + "H1": RAY_H1, + "H2": ROOT / "phase8_h2_ray_r2step50_h2o80_replay20_s20260717.yaml", + "H3": ROOT / "phase8_h3_ray_r2step50_h2o50_replay50_s20260717.yaml", + "H4": ROOT / "phase8_h4_ray_r2step50_h2o_dropout005_s20260717.yaml", +} +RAY_R2 = Path("configs/phase8/stage5/phase8_r2_ray_depth_e40_s20260717.yaml") +H5_DIRECT = ROOT / "phase8_h5_direct_g200_staged_s20260717.yaml" +H5_RAY = ROOT / "phase8_h5_ray_r2step50_staged_s20260717.yaml" + + +def load_configs() -> dict[str, dict]: + return { + name: yaml.safe_load(path.read_text(encoding="utf-8")) + for name, path in FILES.items() + } + + +@pytest.mark.parametrize("name", FILES) +def test_phase8_adaptation_configs_pass_frozen_contract(name: str) -> None: + config = load_configs()[name] + assert validate_adaptation_contract(config) == [] + assert config["seed"] == 20260717 + assert config["experiment"]["phase"] == 8 + assert config["experiment"]["selection_split"] == "h2o_train_group_heldout_only" + assert config["experiment"]["official_test_used"] is False + + +def test_phase8_replay_is_h2o_exposure_matched_and_keeps_e40_ratio() -> None: + configs = load_configs() + for name, steps in (("H2", 25000), ("H3", 40000)): + weights = { + source["dataset"]: source["weight"] + for source in configs[name]["data"]["sources"] + } + assert weights["H2O"] * steps == pytest.approx(20000) + external = sum(weights[key] for key in ("HOT3D", "HOI4D", "ARCTIC")) + assert [weights[key] / external for key in ("HOT3D", "HOI4D", "ARCTIC")] == pytest.approx( + [0.4, 0.4, 0.2] + ) + + +def test_phase8_h4_dropout_is_clip_source_only_and_validation_is_clean() -> None: + config = load_configs()["H4"] + source = config["data"]["sources"][0] + validation = config["data"]["validation_sources"][0] + assert source["K_input_dropout"] == pytest.approx(0.05) + assert source["depth_input_dropout"] == pytest.approx(0.05) + assert validation["K_input_dropout"] == 0.0 + assert "depth_input_dropout" not in validation + assert config["model"]["modality_dropout_prob"] == 0.0 + + +def test_phase8_h1_h4_share_model_loss_and_optimizer_contract() -> None: + configs = load_configs() + reference = configs["H1"] + optimizer_keys = ( + "max_steps", "learning_rate", "min_learning_rate", "warmup_steps", + "weight_decay", "batch_size", + ) + for name in ("H2", "H3", "H4"): + candidate = configs[name] + assert candidate["model"] == reference["model"] + assert candidate["loss"] == reference["loss"] + for key in optimizer_keys[:-1]: + assert candidate["protocol"][key] == reference["protocol"][key] + assert candidate["data"]["batch_size"] == reference["data"]["batch_size"] + + +def test_phase8_ray_h1_preserves_r2_model_and_loss() -> None: + adaptation = yaml.safe_load(RAY_H1.read_text(encoding="utf-8")) + external = yaml.safe_load(RAY_R2.read_text(encoding="utf-8")) + assert validate_adaptation_contract(adaptation) == [] + external_model = dict(external["model"]) + external_model["dinov3_trainable_last_blocks"] = 0 + assert adaptation["model"] == external_model + assert adaptation["loss"] == external["loss"] + assert adaptation["experiment"]["initialization_checkpoint_sha256"] == ( + "b9a6c10a01e1a076f69a015072442346b9a1d5c5368bbb854e86a94acd4dc765" + ) + + +@pytest.mark.parametrize("name", RAY_FILES) +def test_phase8_ray_adaptation_configs_preserve_r2_contract(name: str) -> None: + adaptation = yaml.safe_load(RAY_FILES[name].read_text(encoding="utf-8")) + external = yaml.safe_load(RAY_R2.read_text(encoding="utf-8")) + assert validate_adaptation_contract(adaptation) == [] + external_model = dict(external["model"]) + external_model["dinov3_trainable_last_blocks"] = 0 + assert adaptation["model"] == external_model + assert adaptation["loss"] == external["loss"] + assert adaptation["experiment"]["initialization_checkpoint_sha256"] == ( + "b9a6c10a01e1a076f69a015072442346b9a1d5c5368bbb854e86a94acd4dc765" + ) + + +def test_phase8_ray_replay_is_exposure_matched() -> None: + configs = { + name: yaml.safe_load(path.read_text(encoding="utf-8")) + for name, path in RAY_FILES.items() + } + for name, steps in (("H2", 25000), ("H3", 40000)): + weights = { + source["dataset"]: source["weight"] + for source in configs[name]["data"]["sources"] + } + assert weights["H2O"] * steps == pytest.approx(20000) + external = sum(weights[key] for key in ("HOT3D", "HOI4D", "ARCTIC")) + assert [weights[key] / external for key in ("HOT3D", "HOI4D", "ARCTIC")] == pytest.approx( + [0.4, 0.4, 0.2] + ) + + +def test_phase8_ray_h4_dropout_matches_direct_h4() -> None: + direct = load_configs()["H4"] + ray = yaml.safe_load(RAY_FILES["H4"].read_text(encoding="utf-8")) + assert ray["data"] == direct["data"] + assert ray["protocol"] == direct["protocol"] + + +@pytest.mark.parametrize("path", (H5_DIRECT, H5_RAY)) +def test_phase8_h5_staged_contract_is_frozen_and_resumable(path: Path) -> None: + config = yaml.safe_load(path.read_text(encoding="utf-8")) + assert validate_adaptation_contract(config) == [] + staged = config["protocol"]["staged_adaptation"] + assert staged["unfreeze_step"] == 5000 + assert staged["unfrozen_learning_rate_scale"] == pytest.approx(0.1) + assert "depth_encoder." in staged["initial_trainable_prefixes"] + assert config["protocol"]["checkpoint_interval"] == 2000 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_eval_builder.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_eval_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..f85d7a09466d1af134c61aae8dc7765e438ffaaa --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_eval_builder.py @@ -0,0 +1,54 @@ +import hashlib +from pathlib import Path + +import pytest + +from scripts.build_phase8_adaptation_eval_queue import HELDOUT, build_queue + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_adaptation_eval_builder_is_three_mode_trainheldout_only( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + config = tmp_path / "config.yaml" + checkpoint = tmp_path / "model.pt" + heldout = tmp_path / "train_group_heldout.jsonl" + config.write_text("name: test\n", encoding="utf-8") + checkpoint.write_bytes(b"checkpoint") + heldout.write_text("{}\n", encoding="utf-8") + monkeypatch.setattr("scripts.build_phase8_adaptation_eval_queue.HELDOUT", heldout) + queue = build_queue( + condition="H1", step=20000, + config=config, config_sha256=digest(config), + checkpoint=checkpoint, checkpoint_sha256=digest(checkpoint), + output_root=tmp_path / "evaluations", bootstrap_resamples=2000, + ) + assert queue["selection_split"] == "h2o_train_group_heldout_only" + assert queue["h2o_official_validation_used"] is False + assert queue["official_test_used"] is False + assert [row["input_mode"] for row in queue["evaluations"]] == [ + "rgb_d_k", "rgb_k", "rgb_only", + ] + assert all(Path(row["cache_manifest"]).name == "train_group_heldout.jsonl" for row in queue["evaluations"]) + + +def test_adaptation_eval_builder_rejects_hash_mismatch( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + config = tmp_path / "config.yaml" + checkpoint = tmp_path / "model.pt" + heldout = tmp_path / "train_group_heldout.jsonl" + config.write_text("name: test\n", encoding="utf-8") + checkpoint.write_bytes(b"checkpoint") + heldout.write_text("{}\n", encoding="utf-8") + monkeypatch.setattr("scripts.build_phase8_adaptation_eval_queue.HELDOUT", heldout) + with pytest.raises(ValueError, match="config"): + build_queue( + condition="H1", step=20000, + config=config, config_sha256="0" * 64, + checkpoint=checkpoint, checkpoint_sha256=digest(checkpoint), + output_root=tmp_path / "evaluations", bootstrap_resamples=2000, + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_forgetting_builder.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_forgetting_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..86941655e8dd671588ac5758ed3d9d91b4543f97 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_forgetting_builder.py @@ -0,0 +1,61 @@ +import hashlib +from pathlib import Path + +import pytest + +from scripts.build_phase8_adaptation_forgetting_queue import build_queue + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_forgetting_builder_uses_three_external_native_modes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + config = tmp_path / "config.yaml" + checkpoint = tmp_path / "model.pt" + config.write_text("name: test\n", encoding="utf-8") + checkpoint.write_bytes(b"checkpoint") + domains = {} + for dataset, mode in (("HOT3D", "rgb_k"), ("HOI4D", "rgb_d_k"), ("ARCTIC", "rgb_k")): + manifest = tmp_path / dataset.lower() / "cache_manifest.jsonl" + manifest.parent.mkdir() + manifest.write_text("{}\n", encoding="utf-8") + domains[dataset] = (str(manifest), mode) + monkeypatch.setattr("scripts.build_phase8_adaptation_forgetting_queue.DOMAINS", domains) + queue = build_queue( + condition="H2", step=25000, + config=config, config_sha256=digest(config), + checkpoint=checkpoint, checkpoint_sha256=digest(checkpoint), + output_root=tmp_path / "evaluations", bootstrap_resamples=2000, + ) + assert queue["selection_use"] is False + assert queue["h2o_official_validation_used"] is False + assert queue["official_test_used"] is False + assert [(item["dataset"], item["input_mode"]) for item in queue["evaluations"]] == [ + ("HOT3D", "rgb_k"), ("HOI4D", "rgb_d_k"), ("ARCTIC", "rgb_k"), + ] + + +def test_forgetting_builder_rejects_h2o_manifest( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + config = tmp_path / "config.yaml" + checkpoint = tmp_path / "model.pt" + manifest = tmp_path / "h2o" / "cache_manifest.jsonl" + manifest.parent.mkdir() + config.write_text("name: test\n", encoding="utf-8") + checkpoint.write_bytes(b"checkpoint") + manifest.write_text("{}\n", encoding="utf-8") + monkeypatch.setattr( + "scripts.build_phase8_adaptation_forgetting_queue.DOMAINS", + {"BAD": (str(manifest), "rgb_k")}, + ) + with pytest.raises(ValueError, match="invalid"): + build_queue( + condition="H2", step=25000, + config=config, config_sha256=digest(config), + checkpoint=checkpoint, checkpoint_sha256=digest(checkpoint), + output_root=tmp_path / "evaluations", bootstrap_resamples=2000, + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_forgetting_comparison.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_forgetting_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e3e193ce8827e4c37bf28670520340bd3d4c35 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_adaptation_forgetting_comparison.py @@ -0,0 +1,70 @@ +import csv +import hashlib +import json +from pathlib import Path + +import pytest + +from scripts.compare_phase8_adaptation_forgetting import compare + + +METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", +) + + +def write_result(root: Path, *, adapted: bool, offset: float) -> Path: + root.mkdir() + rows = root / "rows.csv" + fieldnames = [ + "dataset", "physical_recording_id", "camera_id", "frame_id", "side", + *METRICS, + ] + with rows.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames) + writer.writeheader() + for recording in ("r1", "r2"): + writer.writerow({ + "dataset": "HOT3D", "physical_recording_id": recording, + "camera_id": "c", "frame_id": "1", "side": "right", + **{metric: 10.0 + offset for metric in METRICS}, + }) + digest = hashlib.sha256(rows.read_bytes()).hexdigest() + manifest = {"path": "/cache/manifest.jsonl", "sha256": "m" * 64} + report = { + "status": "evaluated_adaptation_external_heldout" if adapted else "evaluated", + "evaluation_role": "adaptation_external_heldout" if adapted else "external_heldout", + "h2o_training_data_used": adapted, + "h2o_official_validation_used": False, + "official_test_used": False, + "oracle_information_used": False, + "input_mode": "rgb_k", "clips": 1, "frames": 1, + "cache_manifest": manifest, + "checkpoint": {"path": "/model.pt", "sha256": ("a" if adapted else "b") * 64}, + "per_hand_rows": {"path": str(rows), "sha256": digest}, + "metrics": { + metric: {"mean": 10.0 + offset, "p95": 10.0 + offset} + for metric in METRICS + }, + } + path = root / "evaluation.json" + path.write_text(json.dumps(report), encoding="utf-8") + return path + + +def test_forgetting_comparison_is_recording_paired(tmp_path: Path) -> None: + reference = write_result(tmp_path / "reference", adapted=False, offset=0.0) + candidate = write_result(tmp_path / "candidate", adapted=True, offset=2.0) + report = compare(reference, candidate, resamples=100) + absolute = report["metrics"]["absolute_mpjpe_mm"] + assert absolute["mean_delta"] == pytest.approx(2.0) + assert absolute["ci95_low"] == pytest.approx(2.0) + assert report["selection_use"] is False + + +def test_forgetting_comparison_rejects_reversed_provenance(tmp_path: Path) -> None: + reference = write_result(tmp_path / "reference", adapted=True, offset=0.0) + candidate = write_result(tmp_path / "candidate", adapted=False, offset=2.0) + with pytest.raises(ValueError, match="reference"): + compare(reference, candidate, resamples=100) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_checkpoint_drift.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_checkpoint_drift.py new file mode 100644 index 0000000000000000000000000000000000000000..47d2cf61b495b7c8e08093050fcd440fe4f882c5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_checkpoint_drift.py @@ -0,0 +1,46 @@ +import hashlib +from pathlib import Path + +import pytest +import torch + +from scripts.analyze_phase8_checkpoint_drift import analyze + + +def write_checkpoint(path: Path, state: dict[str, torch.Tensor], step: int) -> str: + torch.save({ + "model": state, "step": step, + "extra": {"h2o_training_data_used": step > 0, "official_test_used": False}, + }, path) + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_checkpoint_drift_groups_and_values(tmp_path: Path) -> None: + reference = tmp_path / "reference.pt" + candidate = tmp_path / "candidate.pt" + reference_sha = write_checkpoint(reference, { + "decoder.block.weight": torch.tensor([3.0, 4.0]), + "translation_head.bias": torch.tensor([1.0]), + }, 0) + candidate_sha = write_checkpoint(candidate, { + "decoder.block.weight": torch.tensor([6.0, 8.0]), + "translation_head.bias": torch.tensor([2.0]), + }, 20) + report = analyze(reference, reference_sha, candidate, candidate_sha) + decoder = report["groups"]["decoder"] + assert decoder["reference_l2"] == pytest.approx(5.0) + assert decoder["delta_l2"] == pytest.approx(5.0) + assert decoder["relative_l2"] == pytest.approx(1.0) + assert report["groups"]["translation_head"]["delta_max_abs"] == 1.0 + assert report["official_test_used"] is False + + +def test_checkpoint_drift_rejects_hash_and_key_mismatch(tmp_path: Path) -> None: + reference = tmp_path / "reference.pt" + candidate = tmp_path / "candidate.pt" + reference_sha = write_checkpoint(reference, {"head.weight": torch.ones(1)}, 0) + candidate_sha = write_checkpoint(candidate, {"other.weight": torch.ones(1)}, 1) + with pytest.raises(ValueError, match="SHA256"): + analyze(reference, "0" * 64, candidate, candidate_sha) + with pytest.raises(ValueError, match="keys differ"): + analyze(reference, reference_sha, candidate, candidate_sha) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_cross_domain_matrix.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_cross_domain_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b0febb156a549650ce8e1e26b87ebecc1ec9da --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_cross_domain_matrix.py @@ -0,0 +1,92 @@ +import json + +from scripts.summarize_phase8_cross_domain_matrix import summarize + + +def evaluation(path, condition, dataset, value, checkpoint): + path.write_text(json.dumps({ + "status": "evaluated", "evaluation_role": "external_heldout", + "h2o_training_data_used": False, "official_test_used": False, + "checkpoint": {"sha256": checkpoint}, "checkpoint_step": 100000, + "input_mode": "rgb_k", "clips": 2, "frames": 16, + "metrics": { + "absolute_mpjpe_mm": {"mean": value}, + "translation_z_mae_mm": {"mean": value / 2, "p95": value}, + "supervision_coverage": { + scope: { + "joint3d_valid_fraction": 1.0, + "translation_valid_fraction": 1.0, + "vertices_valid_fraction": 1.0, + } + for scope in ("overall", "left", "right") + }, + }, + "experiment": condition, "dataset": dataset, + }), encoding="utf-8") + + +def test_cross_domain_summary_uses_macro_rank_and_pareto(tmp_path) -> None: + entries = [] + values = { + ("A", "HOT3D"): 10, ("A", "HOI4D"): 30, + ("B", "HOT3D"): 20, ("B", "HOI4D"): 20, + } + for (condition, dataset), value in values.items(): + path = tmp_path / f"{condition}_{dataset}.json" + evaluation(path, condition, dataset, value, f"checkpoint-{condition}") + entries.append({"condition": condition, "dataset": dataset, "evaluation": str(path)}) + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({ + "official_test_used": False, "entries": entries, + }), encoding="utf-8") + report = summarize(manifest, tmp_path / "output") + assert report["mean_rank"] == {"A": 1.5, "B": 1.5} + assert report["pareto_frontier"] == ["A", "B"] + assert all(row["left_joint3d_valid_fraction"] == 1.0 for row in report["rows"]) + assert (tmp_path / "output" / "cross_domain_matrix.csv").is_file() + + +def test_cross_domain_summary_rejects_missing_supervision_coverage(tmp_path) -> None: + path = tmp_path / "result.json" + evaluation(path, "A", "HOT3D", 10, "checkpoint-A") + report = json.loads(path.read_text(encoding="utf-8")) + del report["metrics"]["supervision_coverage"] + path.write_text(json.dumps(report), encoding="utf-8") + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({ + "official_test_used": False, + "entries": [{"condition": "A", "dataset": "HOT3D", "evaluation": str(path)}], + }), encoding="utf-8") + try: + summarize(manifest, tmp_path / "output") + except ValueError as error: + assert "supervision coverage" in str(error) + else: + raise AssertionError("missing supervision coverage was accepted") + + +def test_cross_domain_summary_rejects_incomplete_matrix(tmp_path) -> None: + path = tmp_path / "only.json" + evaluation(path, "A", "HOT3D", 10, "checkpoint-A") + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps({ + "official_test_used": False, + "entries": [{"condition": "A", "dataset": "HOT3D", "evaluation": str(path)}], + }), encoding="utf-8") + # One condition by one dataset is a complete matrix, so duplicate a second + # condition without its HOT3D counterpart to create a missing cell. + other = tmp_path / "other.json" + evaluation(other, "B", "HOI4D", 20, "checkpoint-B") + manifest.write_text(json.dumps({ + "official_test_used": False, + "entries": [ + {"condition": "A", "dataset": "HOT3D", "evaluation": str(path)}, + {"condition": "B", "dataset": "HOI4D", "evaluation": str(other)}, + ], + }), encoding="utf-8") + try: + summarize(manifest, tmp_path / "output") + except ValueError as error: + assert "incomplete" in str(error) + else: + raise AssertionError("incomplete matrix was accepted") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_depth_corruption.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_depth_corruption.py new file mode 100644 index 0000000000000000000000000000000000000000..cc5a281a07e42893c1d814df8cf2e44cc7b9ba41 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_depth_corruption.py @@ -0,0 +1,94 @@ +import numpy as np +import pytest +import json +from pathlib import Path + +from foundation_hand.data.cached_unified_dataset import ( + CachedUnifiedClipDataset, + DEPTH_CORRUPTIONS, + corrupt_metric_depth, +) + + +@pytest.mark.parametrize("corruption", DEPTH_CORRUPTIONS) +def test_depth_corruptions_are_deterministic_finite_and_bounded(corruption: str) -> None: + depth = np.linspace(0.2, 1.2, 2 * 1 * 16 * 24, dtype=np.float32).reshape(2, 1, 16, 24) + valid = np.ones_like(depth, dtype=bool) + first_depth, first_valid = corrupt_metric_depth(depth, valid, corruption, seed=17) + second_depth, second_valid = corrupt_metric_depth(depth, valid, corruption, seed=17) + np.testing.assert_array_equal(first_depth, second_depth) + np.testing.assert_array_equal(first_valid, second_valid) + assert np.isfinite(first_depth).all() + assert (first_depth[~first_valid] == 0).all() + assert (first_depth[first_valid] >= 0.02).all() + assert (first_depth[first_valid] <= 3.0).all() + + +def test_depth_corruption_does_not_mutate_targets() -> None: + depth = np.full((1, 1, 8, 8), 0.6, dtype=np.float32) + valid = np.ones_like(depth, dtype=bool) + original_depth, original_valid = depth.copy(), valid.copy() + corrupt_metric_depth(depth, valid, "global_bias", seed=5) + np.testing.assert_array_equal(depth, original_depth) + np.testing.assert_array_equal(valid, original_valid) + + +def cached_dataset(tmp_path: Path, **kwargs) -> CachedUnifiedClipDataset: + cache = tmp_path / "clip.npz" + np.savez_compressed( + cache, + rgb_u8=np.zeros((2, 16, 24, 3), dtype=np.uint8), + frame_valid=np.ones(2, dtype=bool), + depth_m=np.full((2, 1, 16, 24), 0.6, dtype=np.float32), + depth_pixel_valid=np.ones((2, 1, 16, 24), dtype=bool), + depth_input_available=np.ones(2, dtype=bool), + K_supervision_valid=np.ones(2, dtype=bool), + ) + row = { + "cache_path": str(cache), "source_clip_index": 9, + "dataset_id": "HOI4D", "subject_id": "s", "sequence_id": "q", + "physical_recording_id": "r", "camera_id": "c", "stream_id": "c", + "headset_id": "h", + } + manifest = tmp_path / "cache_manifest.jsonl" + manifest.write_text(json.dumps(row) + "\n", encoding="utf-8") + return CachedUnifiedClipDataset(manifest, **kwargs) + + +def test_depth_input_dropout_keeps_geometry_supervision(tmp_path: Path) -> None: + sample = cached_dataset(tmp_path, depth_input_dropout=1.0)[0] + assert not sample["depth_input_available"].any() + assert sample["K_supervision_valid"].all() + assert (sample["depth_input_condition_code"] == 1).all() + assert (sample["depth_m"] == 0.6).all() + + +def test_dataset_depth_corruption_is_clip_deterministic(tmp_path: Path) -> None: + dataset = cached_dataset(tmp_path, depth_corruption_probability=1.0) + first, second = dataset[(0, 3)], dataset[(0, 3)] + assert (first["depth_input_condition_code"] >= 3).all() + assert np.array_equal(first["depth_m"].numpy(), second["depth_m"].numpy()) + assert np.array_equal( + first["depth_pixel_valid"].numpy(), second["depth_pixel_valid"].numpy(), + ) + + +def test_cached_dataset_rejects_resolution_mismatch_and_legacy_highres( + tmp_path: Path, +) -> None: + cache = tmp_path / "clip_resolution.npz" + np.savez_compressed(cache, image_hw=np.array([512, 896], dtype=np.int64)) + row = { + "cache_path": str(cache), "source_clip_index": 0, + "dataset_id": "ARCTIC", "resolution_hw": [512, 896], + } + manifest = tmp_path / "resolution_manifest.jsonl" + manifest.write_text(json.dumps(row) + "\n", encoding="utf-8") + CachedUnifiedClipDataset(manifest, expected_resolution_hw=(512, 896)) + with pytest.raises(ValueError, match="does not match"): + CachedUnifiedClipDataset(manifest, expected_resolution_hw=(368, 640)) + + row.pop("resolution_hw") + manifest.write_text(json.dumps(row) + "\n", encoding="utf-8") + with pytest.raises(ValueError, match="legacy cache"): + CachedUnifiedClipDataset(manifest, expected_resolution_hw=(512, 896)) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_egodexter_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_egodexter_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c7b3175067353c0996bf9985a2d540f14c2e38a7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_egodexter_queue.py @@ -0,0 +1,52 @@ +import hashlib +import json +from pathlib import Path + +from scripts.build_phase8_egodexter_queue import build_queue +from scripts.run_phase8_egodexter_queue import evaluator_command, validate_queue + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_egodexter_queue_is_hash_bound_six_condition_grid(tmp_path: Path) -> None: + checkpoint = tmp_path / "checkpoint.pt"; checkpoint.write_bytes(b"checkpoint") + offline = tmp_path / "offline.yaml"; offline.write_text("offline", encoding="utf-8") + causal = tmp_path / "causal.yaml"; causal.write_text("causal", encoding="utf-8") + (tmp_path / "data").mkdir() + freeze = tmp_path / "freeze.json" + freeze.write_text(json.dumps({ + "status": "phase7_final_models_frozen", + "models": [{ + "id": "model", "checkpoint": str(checkpoint), + "checkpoint_sha256": digest(checkpoint), + "inference_configs": { + "offline": {"path": str(offline), "sha256": digest(offline)}, + "causal": {"path": str(causal), "sha256": digest(causal)}, + }, + }], + "egodexter_sequence_handedness": { + "Desk": "left", "Fruits": "left", "Kitchen": "left", "Rotunda": "left", + }, + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + }), encoding="utf-8") + queue = build_queue(freeze, "model", tmp_path, tmp_path / "outputs") + validate_queue(queue) + assert len(queue["evaluations"]) == 6 + command = evaluator_command(queue["evaluations"][0], 2) + assert command[command.index("--physical-gpu-id") + 1] == "2" + + +def test_egodexter_queue_rejects_selection_exposure() -> None: + queue = { + "model_id": "model", "official_test_used": False, + "egodexter_used_for_training_or_selection": True, "evaluations": [{}], + } + try: + validate_queue(queue) + except ValueError as error: + assert "boundary" in str(error) + else: + raise AssertionError("selection-exposed EgoDexter queue should be rejected") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_egodexter_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_egodexter_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..186ac518e85fcf06f639ffe1d1e7e3c19c2c4a64 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_egodexter_summary.py @@ -0,0 +1,47 @@ +import hashlib +import json +from pathlib import Path + +from scripts.summarize_phase8_egodexter import summarize + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_egodexter_summary_requires_and_preserves_six_condition_grid(tmp_path: Path) -> None: + evaluations = [] + for mode in ("offline", "causal"): + for input_mode in ("rgb_d_k", "rgb_k", "rgb_only"): + output = tmp_path / mode / input_mode + output.mkdir(parents=True) + rows = output / "rows.csv"; rows.write_text("x\n", encoding="utf-8") + raw = output / "raw.npz"; raw.write_bytes(b"raw") + report = { + "status": "evaluated_frozen_egodexter_zero_shot", "model_id": "model", + "input_mode": input_mode, "inference_mode": mode, + "checkpoint": {"sha256": "a" * 64}, + "egodexter_used_for_training_or_selection": False, "official_test_used": False, + "fingertip_error_mm": {"mean": 1.0, "median": 0.9, "p95": 2.0}, + "visible_fingertips": 5, "coverage_fraction": 1.0, "frames": 1, + "runtime": {"frames_per_second": 3.0, "peak_vram_gib": 1.0, + "maximum_gpu_window_frames": 8, + "maximum_cpu_input_buffer_frames": 12}, + "per_finger": {}, "per_sequence": {}, + "per_fingertip_rows": {"path": str(rows), "sha256": digest(rows)}, + "raw_predictions": {"path": str(raw), "sha256": digest(raw)}, + } + (output / "evaluation.json").write_text(json.dumps(report), encoding="utf-8") + evaluations.append({ + "model_id": "model", "input_mode": input_mode, + "inference_mode": mode, "checkpoint_sha256": "a" * 64, + "output_dir": str(output), + }) + queue = tmp_path / "queue.json" + queue.write_text(json.dumps({ + "model_id": "model", "evaluations": evaluations, + "egodexter_used_for_training_or_selection": False, "official_test_used": False, + }), encoding="utf-8") + result = summarize([queue]) + assert result["status"] == "complete_frozen_zero_shot" + assert len(result["conditions"]) == 6 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_external_tail_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_external_tail_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..a587b5273522fd1287733c8e45c54e103e303f0e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_external_tail_queue.py @@ -0,0 +1,56 @@ +import hashlib +import json + +from scripts.build_phase8_external_tail_queue import build_queue + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def fixtures(tmp_path): + cache = tmp_path / "cache"; cache.mkdir() + manifest = cache / "cache_manifest.jsonl"; manifest.write_text("{}\n", encoding="utf-8") + report = cache / "cache_report.json" + report.write_text(json.dumps({ + "status": "complete", "official_test_used": False, "cached_clips": 1, + "cache_manifest": {"path": str(manifest), "sha256": digest(manifest)}, + }), encoding="utf-8") + config = tmp_path / "config.yaml" + config.write_text( + "experiment:\n branch: external_only\n" + "data:\n sources:\n - dataset: HOT3D\n cache_manifest: " + str(manifest) + "\n" + "protocol:\n max_steps: 100000\n min_learning_rate: 5e-6\n", + encoding="utf-8", + ) + output = tmp_path / "run"; output.mkdir() + checkpoint = output / "step_0100000_final.pt"; checkpoint.write_bytes(b"checkpoint") + return config, output, checkpoint + + +def test_external_tail_queue_is_exact_resume_and_cache_bound(tmp_path) -> None: + config, output, checkpoint = fixtures(tmp_path) + queue = build_queue( + condition="S_HOT", config_path=config, config_sha256=digest(config), + output_dir=output, checkpoint=checkpoint, checkpoint_sha256=digest(checkpoint), + ) + stage = queue["stages"][0] + assert stage["resume_from_step"] == 100000 + assert stage["stop_after_step"] == 200000 + assert stage["allow_schedule_tail"] is True + assert stage["resume_checkpoint_sha256"] == digest(checkpoint) + assert queue["required_caches"][0]["expected_clips"] == 1 + + +def test_external_tail_queue_rejects_h2o_branch(tmp_path) -> None: + config, output, checkpoint = fixtures(tmp_path) + config.write_text(config.read_text(encoding="utf-8").replace("external_only", "h2o_adaptation"), encoding="utf-8") + try: + build_queue( + condition="bad", config_path=config, config_sha256=digest(config), + output_dir=output, checkpoint=checkpoint, checkpoint_sha256=digest(checkpoint), + ) + except ValueError as error: + assert "external-only" in str(error) + else: + raise AssertionError("H2O tail was accepted") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_h2o_control_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_h2o_control_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..921f4631f79dc177f023f38d5f4b97775891195d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_h2o_control_eval_queue.py @@ -0,0 +1,36 @@ +import pytest + +from scripts.run_phase8_h2o_control_eval_queue import evaluator_command, validate_queue + + +def queue() -> dict: + return { + "official_test_used": False, + "h2o_official_validation_used": False, + "selection_split": "h2o_train_group_heldout_only", + "evaluations": [{ + "id": "B0", "config": "/config", "checkpoint": "/checkpoint", + "checkpoint_sha256": "a" * 64, + "cache_manifest": "/split/train_group_heldout.jsonl", + "input_mode": "rgb_k", "output_dir": "/output", + "expected_h2o_training_data_used": False, + }], + } + + +def test_h2o_control_queue_freezes_role_and_provenance() -> None: + validate_queue(queue()) + command = evaluator_command(queue()["evaluations"][0], 2) + assert command[command.index("--evaluation-role") + 1] == "h2o_train_group_heldout_control" + assert command[command.index("--physical-gpu-id") + 1] == "2" + + +def test_h2o_control_queue_rejects_nonfrozen_split_or_provenance() -> None: + value = queue() + value["evaluations"][0]["cache_manifest"] = "/official_val.jsonl" + with pytest.raises(ValueError, match="train_group_heldout"): + validate_queue(value) + value = queue() + del value["evaluations"][0]["expected_h2o_training_data_used"] + with pytest.raises(ValueError, match="provenance"): + validate_queue(value) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_h2o_trainheldout_comparison.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_h2o_trainheldout_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..38714028c603ebec1643088153670e39f6ea87b8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_h2o_trainheldout_comparison.py @@ -0,0 +1,72 @@ +import csv +import hashlib +import json + +from scripts.compare_phase8_h2o_trainheldout import compare + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def evaluation(root, name, offset, role): + root.mkdir() + checkpoint, config, cache = root / "checkpoint.pt", root / "config.yaml", root / "train_group_heldout.jsonl" + checkpoint.write_bytes(name.encode()) + config.write_text(name, encoding="utf-8") + cache.write_text("{}\n", encoding="utf-8") + rows = root / "per_hand.csv" + with rows.open("w", newline="", encoding="utf-8") as handle: + fields = ["physical_recording_id", "camera_id", "frame_id", "side", + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm"] + writer = csv.DictWriter(handle, fieldnames=fields); writer.writeheader() + for take in ("a", "b"): + writer.writerow({ + "physical_recording_id": take, "camera_id": "cam4", "frame_id": 0, + "side": "right", "absolute_mpjpe_mm": 10 + offset, + "root_relative_mpjpe_mm": 8 + offset, "mpvpe_mm": 9 + offset, + "fingertip_mpjpe_mm": 12 + offset, "translation_z_mae_mm": 5 + offset, + }) + take = root / "take.csv"; take.write_text("physical_recording_id\na\n", encoding="utf-8") + status = "evaluated_h2o_train_group_heldout" if role == "h2o_train_group_heldout" else "evaluated_h2o_train_group_heldout_control" + report = root / "evaluation.json" + report.write_text(json.dumps({ + "status": status, "evaluation_role": role, "input_mode": "rgb_d_k", + "h2o_training_data_used": True, "h2o_official_validation_used": False, + "official_test_used": False, "checkpoint_step": 20000, + "checkpoint": {"path": str(checkpoint), "sha256": digest(checkpoint)}, + "config": {"path": str(config), "sha256": digest(config)}, + "cache_manifest": {"path": str(cache), "sha256": digest(cache)}, + "per_hand_rows": {"path": str(rows), "sha256": digest(rows)}, + "take_metrics": {"path": str(take), "sha256": digest(take)}, + "metrics": { + "absolute_mpjpe_mm": {"mean": 10 + offset}, + "root_relative_mpjpe_mm": {"mean": 8 + offset}, + "mpvpe_mm": {"mean": 9 + offset}, + "fingertip_mpjpe_mm": {"mean": 12 + offset}, + "translation_z_mae_mm": {"mean": 5 + offset, "p95": 7 + offset}, + }, + }), encoding="utf-8") + return report + + +def test_h2o_comparison_accepts_control_and_adaptation_by_mode(tmp_path) -> None: + control = evaluation(tmp_path / "control", "B2", 0, "h2o_train_group_heldout_control") + adapted = evaluation(tmp_path / "adapted", "B3", 2, "h2o_train_group_heldout") + # Both reports must reference the exact same cache artifact. + adapted_report = json.loads(adapted.read_text(encoding="utf-8")) + control_report = json.loads(control.read_text(encoding="utf-8")) + adapted_report["cache_manifest"] = control_report["cache_manifest"] + adapted.write_text(json.dumps(adapted_report), encoding="utf-8") + result = compare({ + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used": False, "official_test_used": False, + "candidates": [ + {"condition": "B2", "evaluation": str(control)}, + {"condition": "B3", "evaluation": str(adapted)}, + ], + }, seed=7, resamples=50) + assert result["modes"]["rgb_d_k"]["winner"] == "B2" + paired = result["modes"]["rgb_d_k"]["paired_recording_bootstrap_vs_winner"]["B3"] + assert paired["absolute_mpjpe_mm"]["mean_delta"] == 2.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_h2o_zero_shot_comparison.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_h2o_zero_shot_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..c88080365b87f4cabf8b2b5badc1c02a7a2c86c3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_h2o_zero_shot_comparison.py @@ -0,0 +1,89 @@ +import csv +import hashlib +import json + +import pytest + +from scripts.compare_phase8_h2o_zero_shot import BOUNDARY, compare + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def evaluation(root, name, offset): + root.mkdir() + checkpoint, config, manifest = root / "checkpoint.pt", root / "config.yaml", root / "official_val.jsonl" + checkpoint.write_bytes(name.encode()) + config.write_text(name, encoding="utf-8") + manifest.write_text("{}\n", encoding="utf-8") + rows = root / "per_hand.csv" + fields = ["physical_recording_id", "camera_id", "frame_id", "side", + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm"] + with rows.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields); writer.writeheader() + for recording in ("a", "b"): + writer.writerow({ + "physical_recording_id": recording, "camera_id": "cam4", + "frame_id": 0, "side": "right", "absolute_mpjpe_mm": 10 + offset, + "root_relative_mpjpe_mm": 8 + offset, "mpvpe_mm": 9 + offset, + "fingertip_mpjpe_mm": 12 + offset, "translation_z_mae_mm": 5 + offset, + }) + take = root / "take.csv"; take.write_text("physical_recording_id\na\n", encoding="utf-8") + report = root / "evaluation.json" + report.write_text(json.dumps({ + "status": "evaluated_strict_h2o_zero_shot", + "evaluation_role": "strict_external_zero_shot", "input_mode": "rgb_k", + "h2o_training_data_used": False, "h2o_official_validation_used": True, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, "checkpoint_step": 100000, + "checkpoint": {"path": str(checkpoint), "sha256": digest(checkpoint)}, + "config": {"path": str(config), "sha256": digest(config)}, + "manifest": {"path": str(manifest), "sha256": digest(manifest)}, + "per_hand_rows": {"path": str(rows), "sha256": digest(rows)}, + "take_metrics": {"path": str(take), "sha256": digest(take)}, + "metrics": { + "absolute_mpjpe_mm": {"mean": 10 + offset}, + "root_relative_mpjpe_mm": {"mean": 8 + offset}, + "mpvpe_mm": {"mean": 9 + offset}, + "fingertip_mpjpe_mm": {"mean": 12 + offset}, + "translation_z_mae_mm": {"mean": 5 + offset, "p95": 7 + offset}, + }, + }), encoding="utf-8") + return report + + +def manifest(reference, candidate): + return { + "comparison_boundary": BOUNDARY, + "checkpoint_selection_frozen_before_h2o": True, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + "reference_condition": "reference", + "candidates": [ + {"condition": "reference", "evaluation": str(reference)}, + {"condition": "candidate", "evaluation": str(candidate)}, + ], + } + + +def test_zero_shot_comparison_is_paired_diagnostic_without_selection(tmp_path) -> None: + reference = evaluation(tmp_path / "reference", "r", 0) + candidate = evaluation(tmp_path / "candidate", "c", -2) + candidate_report = json.loads(candidate.read_text(encoding="utf-8")) + candidate_report["manifest"] = json.loads(reference.read_text(encoding="utf-8"))["manifest"] + candidate.write_text(json.dumps(candidate_report), encoding="utf-8") + result = compare(manifest(reference, candidate), seed=7, resamples=50) + assert result["selection_performed"] is False + paired = result["modes"]["rgb_k"]["paired_candidate_minus_reference"]["candidate"] + assert paired["absolute_mpjpe_mm"]["mean_delta"] == -2.0 + + +def test_zero_shot_comparison_rejects_selection_exposure(tmp_path) -> None: + reference = evaluation(tmp_path / "reference", "r", 0) + candidate = evaluation(tmp_path / "candidate", "c", 1) + specification = manifest(reference, candidate) + specification["h2o_official_validation_used_for_external_selection"] = True + with pytest.raises(ValueError, match="boundary"): + compare(specification) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_left_root_relative_supervision.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_left_root_relative_supervision.py new file mode 100644 index 0000000000000000000000000000000000000000..b4b265de08e2d7bdb5b56c25454977bd0bc1833a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_left_root_relative_supervision.py @@ -0,0 +1,136 @@ +import json +from pathlib import Path + +import numpy as np +import torch + +from foundation_hand.data.cached_unified_dataset import CachedUnifiedClipDataset +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.data.schema import source_root_relative_joint_target +from scripts.build_phase8_left_root_relative_sidecars import left_only_target +from scripts.train_phase7_external import source_batch_counts, source_frame_counts + + +def test_source_root_relative_target_restores_valid_left_joints_only() -> None: + joints = torch.zeros(2, 2, 21, 3) + joints[..., 0] = torch.linspace(0.1, 0.2, 21) + joints[..., 1] = torch.linspace(-0.03, 0.03, 21) + joints[:, :, :, 2] = 0.7 + hand_valid = torch.tensor([[True, True], [True, False]]) + target, valid = source_root_relative_joint_target(joints, hand_valid) + assert valid[0, 0].all() and valid[0, 1].all() + assert valid[1, 0].all() and not valid[1, 1].any() + torch.testing.assert_close(target[0, 0, 0], torch.zeros(3)) + assert torch.isnan(target[1, 1]).all() + + +def test_source_root_relative_target_rejects_bad_shape() -> None: + try: + source_root_relative_joint_target( + torch.zeros(2, 20, 3), torch.ones(2, dtype=torch.bool), + ) + except ValueError as error: + assert "21,3" in str(error) + else: + raise AssertionError("invalid joint convention was accepted") + + +def test_left_only_target_intersects_cache_validity() -> None: + target = torch.randn(2, 2, 21, 3) + target -= target[..., :1, :] + source_valid = torch.ones(2, 2, 21, dtype=torch.bool) + translation_valid = torch.tensor([[True, True], [False, True]]) + frame_valid = torch.ones(2, dtype=torch.bool) + filtered, valid = left_only_target( + target, source_valid, translation_valid, frame_valid, + ) + assert valid[0, 0].all() + assert not valid[0, 1].any() + assert not valid[1].any() + assert torch.isnan(filtered[0, 1]).all() + torch.testing.assert_close(filtered[0, 0, 0], torch.zeros(3)) + + +def _sidecar_dataset(tmp_path: Path, scope: str) -> CachedUnifiedClipDataset: + tmp_path.mkdir(parents=True, exist_ok=True) + cache = tmp_path / "clip.npz" + joint_shape = (2, 2, 21, 3) + np.savez_compressed( + cache, + rgb_u8=np.zeros((2, 8, 8, 3), dtype=np.uint8), + frame_valid=np.ones(2, dtype=bool), + joint3d_camera=np.zeros(joint_shape, dtype=np.float32), + joint3d_valid=np.ones(joint_shape[:-1], dtype=bool), + depth_m=np.zeros((2, 1, 8, 8), dtype=np.float32), + depth_pixel_valid=np.zeros((2, 1, 8, 8), dtype=bool), + depth_input_available=np.zeros(2, dtype=bool), + ) + relative = np.zeros(joint_shape, dtype=np.float32) + relative[..., 0] = np.linspace(0.0, 0.1, 21) + valid = np.zeros(joint_shape[:-1], dtype=bool) + valid[:, 0] = True + sidecar = tmp_path / "sidecar.npz" + np.savez_compressed( + sidecar, + joint3d_root_relative=relative, + joint3d_root_relative_valid=valid, + ) + row = { + "cache_path": str(cache), + "joint3d_root_relative_sidecar_path": str(sidecar), + "source_clip_index": 0, + "dataset_id": "HOI4D", "subject_id": "H1", "sequence_id": "r", + "physical_recording_id": "r", "camera_id": "c", "stream_id": "c", + "headset_id": "c", + } + manifest = tmp_path / f"{scope}.jsonl" + manifest.write_text(json.dumps(row) + "\n", encoding="utf-8") + return CachedUnifiedClipDataset( + manifest, joint3d_root_relative_scope=scope, + ) + + +def test_cached_sidecar_restores_only_left_root_relative_target(tmp_path: Path) -> None: + sample = _sidecar_dataset(tmp_path, "auto")[0] + assert sample["joint3d_root_relative_valid"][:, 0].all() + assert not sample["joint3d_root_relative_valid"][:, 1].any() + assert torch.isnan(sample["joint3d_root_relative"][:, 1]).all() + + +def test_cached_scope_can_disable_all_root_relative_supervision(tmp_path: Path) -> None: + sample = _sidecar_dataset(tmp_path, "disabled")[0] + assert not sample["joint3d_root_relative_valid"].any() + assert torch.isnan(sample["joint3d_root_relative"]).all() + + +def test_historical_left_only_scope_alias_matches_left_only(tmp_path: Path) -> None: + expected = _sidecar_dataset(tmp_path / "expected", "left_only")[0] + aliased = _sidecar_dataset( + tmp_path / "aliased", "historical_left_only", + )[0] + torch.testing.assert_close( + aliased["joint3d_root_relative"], + expected["joint3d_root_relative"], + equal_nan=True, + ) + torch.testing.assert_close( + aliased["joint3d_root_relative_valid"], + expected["joint3d_root_relative_valid"], + ) + + +def test_sampling_source_id_keeps_duplicate_dataset_exposure_separate() -> None: + batch = { + "dataset_id": ["HOI4D", "HOI4D"], + "sampling_source_id": ["HOI4D_general", "HOI4D_left"], + "frame_valid": torch.tensor([[True, True], [True, False]]), + } + assert source_batch_counts(batch) == {"HOI4D_general": 1, "HOI4D_left": 1} + assert source_frame_counts(batch) == {"HOI4D_general": 2, "HOI4D_left": 1} + + +def test_cached_sampling_source_id_is_collated_as_metadata(tmp_path: Path) -> None: + dataset = _sidecar_dataset(tmp_path, "auto") + batch = collate_h2o_clips([dataset[0], dataset[0]]) + assert batch["sampling_source_id"] == ["HOI4D", "HOI4D"] + assert batch["frame_valid"].shape == (2, 2) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_paired_input_modes.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_paired_input_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..df8063d1dcdc38f738c51d0c82dbe1687c64a147 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_paired_input_modes.py @@ -0,0 +1,91 @@ +import csv +import json +from pathlib import Path + +import numpy as np + +from scripts.analyze_phase8_paired_input_modes import analyze + + +def bundle(path: Path, mode: str, translation: np.ndarray) -> None: + path.mkdir() + target_translation = np.zeros_like(translation) + target_translation[..., 2] = 1.0 + target_joints = np.repeat(target_translation[..., None, :], 21, axis=-2) + predicted_joints = target_joints + (translation - target_translation)[..., None, :] + np.savez_compressed( + path / "raw_predictions.npz", + predicted_wrist_root_translation=translation, + target_wrist_root_translation=target_translation, + predicted_joints_camera=predicted_joints, + target_joints_camera=target_joints, + translation_valid=np.ones(translation.shape[:-1], dtype=bool), + joint3d_valid=np.ones((*translation.shape[:-1], 21), dtype=bool), + frame_id=np.arange(translation.shape[0]), + ) + (path / "evaluation.json").write_text(json.dumps({ + "checkpoint": {"sha256": "checkpoint"}, + "cache_manifest": {"sha256": "cache"}, + "input_mode": mode, "official_test_used": False, + }), encoding="utf-8") + with (path / "per_hand_frame_metrics.csv").open("w", newline="", encoding="utf-8") as handle: + fields = ["dataset", "subject_id", "physical_recording_id", "camera_id", "frame_id", "side"] + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader() + for frame in range(translation.shape[0]): + for side in range(translation.shape[1]): + writer.writerow({ + "dataset": "H2O", "subject_id": "s1", + "physical_recording_id": f"take{frame}", "camera_id": "cam4", + "frame_id": frame, "side": ("left", "right")[side], + }) + + +def test_paired_depth_diagnostic_reports_gain_harm_and_direction(tmp_path: Path) -> None: + base = np.zeros((2, 2, 3), dtype=np.float32) + base[..., 2] = 1.10 + depth = base.copy() + depth[0, ..., 2] = 1.02 + depth[1, ..., 2] = 1.20 + base_dir, depth_dir = tmp_path / "base", tmp_path / "depth" + bundle(base_dir, "rgb_k", base) + bundle(depth_dir, "rgb_d_k", depth) + report = analyze(base_dir, depth_dir, tmp_path / "out", seed=7, resamples=50) + assert report["hands_with_translation"] == 4 + assert report["depth_harm_fraction_mpjpe"] == 0.5 + assert report["axis_diagnostics"]["z"]["direction_agreement_fraction"] == 0.5 + assert report["grouped_bootstrap_ci"]["mpjpe_gain_mm"]["groups"] == 2 + assert (tmp_path / "out" / "largest_harm_cases.csv").is_file() + + +def test_paired_depth_diagnostic_rejects_different_checkpoint(tmp_path: Path) -> None: + translation = np.zeros((1, 2, 3), dtype=np.float32) + translation[..., 2] = 1.0 + base_dir, depth_dir = tmp_path / "base", tmp_path / "depth" + bundle(base_dir, "rgb_k", translation) + bundle(depth_dir, "rgb_d_k", translation) + report = json.loads((depth_dir / "evaluation.json").read_text(encoding="utf-8")) + report["checkpoint"]["sha256"] = "different" + (depth_dir / "evaluation.json").write_text(json.dumps(report), encoding="utf-8") + try: + analyze(base_dir, depth_dir, tmp_path / "out", seed=7, resamples=10) + except ValueError as error: + assert "same checkpoint" in str(error) + else: + raise AssertionError("mismatched checkpoint pair was accepted") + + +def test_paired_depth_diagnostic_accepts_h2o_validation_manifest(tmp_path: Path) -> None: + translation = np.zeros((1, 2, 3), dtype=np.float32) + translation[..., 2] = 1.0 + base_dir, depth_dir = tmp_path / "base", tmp_path / "depth" + bundle(base_dir, "rgb_k", translation) + bundle(depth_dir, "rgb_d_k", translation) + for directory in (base_dir, depth_dir): + path = directory / "evaluation.json" + report = json.loads(path.read_text(encoding="utf-8")) + report["manifest"] = report.pop("cache_manifest") + report["h2o_official_validation_used_for_external_selection"] = False + path.write_text(json.dumps(report), encoding="utf-8") + result = analyze(base_dir, depth_dir, tmp_path / "out", seed=7, resamples=10) + assert result["observation_manifest"]["sha256"] == "cache" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_specialist_eval_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_specialist_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..6d4ef4c9faa35b0ff55e33a3069cedfc57602985 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_specialist_eval_queue.py @@ -0,0 +1,59 @@ +import hashlib +from pathlib import Path + +from scripts import build_phase8_specialist_eval_queue as builder + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_specialist_queue_is_hash_bound_and_dataset_macro(tmp_path, monkeypatch) -> None: + config = tmp_path / "config.yaml" + checkpoint = tmp_path / "step.pt" + config.write_text("name: specialist\n", encoding="utf-8") + checkpoint.write_bytes(b"checkpoint") + domains = {} + for dataset, modes in ( + ("HOT3D", ("rgb_k", "rgb_only")), + ("HOI4D", ("rgb_k", "rgb_d_k", "rgb_only")), + ("ARCTIC", ("rgb_k", "rgb_only")), + ): + manifest = tmp_path / f"{dataset}.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + domains[dataset] = {"cache_manifest": str(manifest), "input_modes": modes} + monkeypatch.setattr(builder, "DOMAINS", domains) + queue = builder.build_queue( + condition="S_HOI", step=100000, + config=config, config_sha256=digest(config), + checkpoint=checkpoint, checkpoint_sha256=digest(checkpoint), + output_root=tmp_path / "evaluations", bootstrap_resamples=2000, + ) + assert queue["official_test_used"] is False + assert queue["h2o_training_data_used"] is False + assert [item["dataset"] for item in queue["evaluations"]] == [ + "HOT3D", "HOT3D", "HOI4D", "HOI4D", "HOI4D", "ARCTIC", "ARCTIC", + ] + assert [item["input_mode"] for item in queue["evaluations"]] == [ + "rgb_k", "rgb_only", "rgb_k", "rgb_d_k", "rgb_only", "rgb_k", "rgb_only", + ] + assert sum(item["matrix_role"] == "primary_matched_rgb_k" for item in queue["evaluations"]) == 3 + assert all(item["bootstrap_resamples"] == 2000 for item in queue["evaluations"]) + + +def test_specialist_queue_rejects_checkpoint_hash_mismatch(tmp_path) -> None: + config = tmp_path / "config.yaml" + checkpoint = tmp_path / "step.pt" + config.write_text("name: specialist\n", encoding="utf-8") + checkpoint.write_bytes(b"checkpoint") + try: + builder.build_queue( + condition="S_HOI", step=100000, + config=config, config_sha256=digest(config), + checkpoint=checkpoint, checkpoint_sha256="0" * 64, + output_root=tmp_path / "evaluations", bootstrap_resamples=10, + ) + except ValueError as error: + assert "checkpoint" in str(error) + else: + raise AssertionError("mismatched checkpoint hash was accepted") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_stage7_left_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_stage7_left_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1c886021bbce43f59f1c0f38252c0c5c60ee8d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_stage7_left_configs.py @@ -0,0 +1,52 @@ +from copy import deepcopy +from pathlib import Path + +import yaml + +from scripts.train_phase7_external import validate_external_contract + + +ROOT = Path(__file__).resolve().parents[1] +L0_PATH = ROOT / "configs/phase8/stage7/phase8_l0_left_sampler_control_s20260717.yaml" +L1_PATH = ROOT / "configs/phase8/stage7/phase8_l1_left_root_relative_s20260717.yaml" + + +def load(path: Path) -> dict: + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def test_stage7_configs_obey_external_only_contract() -> None: + for path in (L0_PATH, L1_PATH): + config = load(path) + assert validate_external_contract(config, path) == [] + assert config["seed"] == 20260717 + assert config["model"]["translation_parameterization"] == "direct_xyz" + assert sum(source["weight"] for source in config["data"]["sources"]) == 1.0 + assert len({source["source_id"] for source in config["data"]["sources"]}) == 4 + + +def test_l0_l1_only_differ_by_preregistered_root_supervision() -> None: + l0, l1 = load(L0_PATH), load(L1_PATH) + assert l0["loss"]["joint3d_root_relative"] == 0.0 + assert l1["loss"]["joint3d_root_relative"] == 10.0 + scopes0 = [source["joint3d_root_relative_scope"] for source in l0["data"]["sources"]] + scopes1 = [source["joint3d_root_relative_scope"] for source in l1["data"]["sources"]] + assert scopes0 == ["disabled"] * 4 + assert scopes1 == ["disabled", "disabled", "left_only", "left_only"] + normalized0, normalized1 = deepcopy(l0), deepcopy(l1) + normalized0["name"] = normalized1["name"] + normalized0["experiment"]["condition"] = normalized1["experiment"]["condition"] + normalized0["loss"]["joint3d_root_relative"] = 10.0 + for source, scope in zip( + normalized0["data"]["sources"], scopes1, strict=True, + ): + source["joint3d_root_relative_scope"] = scope + assert normalized0 == normalized1 + + +def test_stage7_heldout_targets_are_identical_between_conditions() -> None: + l0, l1 = load(L0_PATH), load(L1_PATH) + assert l0["data"]["validation_sources"] == l1["data"]["validation_sources"] + assert [source["joint3d_root_relative_scope"] for source in l0["data"]["validation_sources"]] == [ + "disabled", "left_only", "left_only", + ] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_translation_oracles.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_translation_oracles.py new file mode 100644 index 0000000000000000000000000000000000000000..04d6b1739fd3cb5e40b790c4144bc58e57d652b1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase8_translation_oracles.py @@ -0,0 +1,53 @@ +import numpy as np + +from scripts.evaluate_phase8_translation_oracles import ( + axis_angle_to_matrix, + build_report, + decompose, +) + + +def arrays() -> dict[str, np.ndarray]: + target_t = np.array([[[0.1, 0.2, 1.0], [-0.1, 0.2, 1.0]]]) + pred_t = np.array([[[0.24, 0.4, 2.0], [-0.2, 0.4, 2.0]]]) + relative = np.zeros((1, 2, 21, 3)) + relative[..., :, 0] = np.linspace(0.0, 0.1, 21) + target_joints = relative + target_t[..., None, :] + pred_joints = relative + pred_t[..., None, :] + return { + "predicted_joints_camera": pred_joints, + "target_joints_camera": target_joints, + "predicted_wrist_root_translation": pred_t, + "target_wrist_root_translation": target_t, + "joint3d_valid": np.ones((1, 2, 21), dtype=bool), + "translation_valid": np.ones((1, 2), dtype=bool), + } + + +def test_translation_oracles_isolate_ray_z_and_pose() -> None: + result = decompose(arrays()) + errors = result["condition_errors_mm"] + np.testing.assert_allclose( + errors["predicted_pose_shape_gt_translation"], 0.0, atol=1e-10, + ) + np.testing.assert_allclose( + errors["predicted_root_relative_gt_translation"], 0.0, atol=1e-10, + ) + np.testing.assert_allclose(errors["predicted_translation_gt_root_relative"], errors["raw"]) + assert np.nanmean(errors["predicted_ray_gt_z"]) < np.nanmean(errors["raw"]) + assert np.nanmean(errors["gt_ray_predicted_z"]) < np.nanmean(errors["raw"]) + + +def test_translation_oracle_report_is_explicitly_non_deployable() -> None: + report = build_report(decompose(arrays())) + assert report["deployable_claim"] is False + assert report["selection_use"] is False + assert report["official_test_used"] is False + assert "nonadditive_interaction_mm" in report["translation_attribution"] + assert report["global_orientation_geodesic_deg"] is None + + +def test_axis_angle_rotation_supports_geodesic_audit() -> None: + rotations = axis_angle_to_matrix(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, np.pi / 2]])) + np.testing.assert_allclose(rotations[0], np.eye(3), atol=1e-12) + np.testing.assert_allclose(rotations[1] @ np.array([1.0, 0.0, 0.0]), [0.0, 1.0, 0.0], atol=1e-12) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_arctic_resolution_recovery.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_arctic_resolution_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..055410e1e50e025aab92bba4fbd4e65e16a45fc5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_arctic_resolution_recovery.py @@ -0,0 +1,68 @@ +import json +from pathlib import Path + +import pytest + +from scripts.recover_phase9_arctic_resolution_cache import ( + canonical_rows, + compare_source_sets, + indexed_rows, + write_jsonl_atomic, +) + + +def row(index: int, group: str = "g") -> dict: + return { + "source_clip_index": index, + "dataset_id": "ARCTIC", + "subject_id": "s1", + "physical_recording_id": group, + "source_group_key": f"ARCTIC/{group}", + "camera_id": "ego", + "stream_id": "ego", + "headset_id": "s1", + "cache_path": f"/cache/clip_{index:07d}.npz", + "cache_sha256": str(index) * 64, + } + + +def test_source_set_audit_finds_one_extra_without_group_drift() -> None: + control = [row(4, "a"), row(2, "b")] + candidate = [row(2, "b"), row(9, "a"), row(4, "a")] + result = compare_source_sets(control, candidate) + assert result["missing_source_clip_indices"] == [] + assert result["extra_source_clip_indices"] == [9] + assert result["identity_drift"] == [] + assert result["missing_groups"] == [] + assert result["extra_groups"] == [] + + +def test_canonical_rows_follow_frozen_control_order() -> None: + control = [row(7, "a"), row(2, "b"), row(5, "a")] + candidate = [row(5, "a"), row(11, "b"), row(2, "b"), row(7, "a")] + assert [item["source_clip_index"] for item in canonical_rows(control, candidate)] == [ + 7, 2, 5, + ] + + +def test_canonical_rows_reject_missing_or_identity_drift() -> None: + with pytest.raises(ValueError, match="contract differs"): + canonical_rows([row(1), row(2)], [row(1)]) + changed = row(2) + changed["subject_id"] = "s2" + with pytest.raises(ValueError, match="contract differs"): + canonical_rows([row(1), row(2)], [row(1), changed]) + + +def test_duplicate_indices_fail_closed() -> None: + with pytest.raises(ValueError, match="duplicate source clip indices"): + indexed_rows([row(3), row(3)], "candidate manifest") + + +def test_jsonl_publication_is_ordered_and_atomic(tmp_path: Path) -> None: + output = tmp_path / "manifest.jsonl" + values = [row(8), row(1)] + write_jsonl_atomic(output, values) + loaded = [json.loads(line) for line in output.read_text().splitlines()] + assert [item["source_clip_index"] for item in loaded] == [8, 1] + assert not output.with_suffix(".tmp").exists() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_data_finalize.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_data_finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..f79f012275554bbdd277888fb98b334a7c0d77e8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_data_finalize.py @@ -0,0 +1,72 @@ +import json +from pathlib import Path + +from scripts.derive_phase9_hot_subset import balanced_subset +from scripts.run_phase9_data_finalize_queue import artifact_complete, base_cache_ready, sha256 + + +def hot_rows() -> list[dict]: + rows = [] + index = 0 + for headset in ("aria", "quest3"): + for recording in range(2): + for _ in range(5): + rows.append({ + "source_clip_index": index, + "physical_recording_id": f"{headset}_{recording}", + "headset_id": headset, + }) + index += 1 + return rows + + +def test_hot_subset_balances_headsets_and_recordings() -> None: + selected = balanced_subset(hot_rows(), 12) + assert len({row["source_clip_index"] for row in selected}) == 12 + assert {row["headset_id"] for row in selected} == {"aria", "quest3"} + counts = {} + for row in selected: + counts[row["physical_recording_id"]] = counts.get(row["physical_recording_id"], 0) + 1 + assert max(counts.values()) - min(counts.values()) <= 1 + + +def test_hot_subset_rejects_duplicate_source_indices() -> None: + rows = hot_rows() + rows[1]["source_clip_index"] = rows[0]["source_clip_index"] + try: + balanced_subset(rows, 5) + except ValueError as error: + assert "duplicate" in str(error) + else: + raise AssertionError("duplicate source index was accepted") + + +def test_finalize_readiness_is_hash_bound(tmp_path: Path) -> None: + manifest = tmp_path / "cache_manifest.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + report = tmp_path / "cache_report.json" + report.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + "cache_manifest": {"sha256": sha256(manifest)}, "clips": 100, + }), encoding="utf-8") + item = { + "dataset": "HOT3D", "manifest": str(manifest), + "report": str(report), "expected_clips": 100, + } + assert base_cache_ready(item) + manifest.write_text("changed\n", encoding="utf-8") + assert not base_cache_ready(item) + + +def test_finalize_augmented_artifact_contract(tmp_path: Path) -> None: + manifest = tmp_path / "cache_manifest.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + report = tmp_path / "sidecar_report.json" + report.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + "augmented_cache_manifest": {"sha256": sha256(manifest)}, + }), encoding="utf-8") + assert artifact_complete({ + "kind": "left_sidecar", "manifest": str(manifest), + "report": str(report), + }) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_data_scale.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_data_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..2492423308ba9d3c2d02abdea543defebc1b7840 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_data_scale.py @@ -0,0 +1,65 @@ +import hashlib +import json +from pathlib import Path + +import numpy as np + +from scripts.audit_phase9_source_coverage import build_report +from scripts.seed_phase9_cache_hardlinks import seed_hardlinks + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def write_clip(path: Path, frame_offset: int = 0) -> None: + frame_valid = np.ones(2, dtype=bool) + translation_valid = np.ones((2, 2), dtype=bool) + joint2d_valid = np.ones((2, 2, 21), dtype=bool) + joint2d = np.zeros((2, 2, 21, 2), dtype=np.float32) + joint2d[..., 0] = np.arange(21) + translation = np.zeros((2, 2, 3), dtype=np.float32) + translation[..., 2] = 0.6 + valid_common = np.ones((2, 2), dtype=bool) + np.savez_compressed( + path, frame_valid=frame_valid, translation_valid=translation_valid, + joint2d_valid=joint2d_valid, joint2d=joint2d, + wrist_root_translation=translation, + K=np.repeat(np.array([[[500.0, 0, 320], [0, 500, 184], [0, 0, 1]]]), 2, axis=0), + image_hw=np.array([368, 640]), frame_id=np.arange(2) + frame_offset, + depth_input_available=np.ones(2, dtype=bool), + depth_pixel_valid=np.ones((2, 1, 2, 2), dtype=bool), + joint3d_valid=np.ones((2, 2, 21), dtype=bool), + mano_pose_valid=valid_common, shape_valid=valid_common, + vertices_valid=valid_common, + ) + + +def test_hardlink_seed_and_coverage_audit(tmp_path: Path) -> None: + source_rows = [ + {"dataset_id": "HOI4D", "subject_id": "H1", "physical_recording_id": "r1", + "camera_id": "cam", "frame_ids": [0, 1]}, + {"dataset_id": "HOI4D", "subject_id": "H1", "physical_recording_id": "r1", + "camera_id": "cam", "frame_ids": [1, 2]}, + ] + source_manifest = tmp_path / "source.jsonl" + source_manifest.write_text("".join(json.dumps(row) + "\n" for row in source_rows)) + clips = tmp_path / "old" / "clips"; clips.mkdir(parents=True) + cache_rows = [] + for index in range(2): + clip = clips / f"clip_{index:07d}.npz"; write_clip(clip, index) + cache_rows.append({ + "dataset_id": "HOI4D", "subject_id": "H1", "physical_recording_id": "r1", + "camera_id": "cam", "headset_id": "cam", "source_clip_index": index, + "cache_path": str(clip), "cache_sha256": digest(clip), + }) + cache_manifest = tmp_path / "cache.jsonl" + cache_manifest.write_text("".join(json.dumps(row) + "\n" for row in cache_rows)) + seeded = seed_hardlinks(cache_manifest, tmp_path / "expanded", "HOI4D") + assert seeded["hardlinked_clips"] == 2 + assert (tmp_path / "expanded/clips/clip_0000000.npz").stat().st_ino == clips.joinpath("clip_0000000.npz").stat().st_ino + report = build_report("HOI4D", source_manifest, cache_manifest) + assert report["source"]["unique_image_observations"] == 3 + assert report["source"]["clip_overlap_fraction"] == 0.25 + assert report["cache"]["unique_cached_frames"] == 3 + assert report["cache"]["bimanual_frames"] == 4 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_distributed_admission_import.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_distributed_admission_import.py new file mode 100644 index 0000000000000000000000000000000000000000..c2410e1126e49a3109302852d7bcca5143d65ab5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_distributed_admission_import.py @@ -0,0 +1,156 @@ +from copy import deepcopy +import hashlib +import json +from pathlib import Path + +import pytest + +from scripts.finalize_phase9_resolution_cache import inspect_workers +from scripts.import_phase9_distributed_cache_worker_state import ( + external_cache_worker_owner, + validate_admission_pair, + validate_released_cache_files, + validate_release_metadata, +) +from scripts.run_phase9_resolution_cache_queue import sha256 + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def admission() -> dict: + return { + "schema_version": "phase9_resolution_admission_v1", + "status": "complete", "admitted_utc": "source-time", + "available_gib": 100.0, "plan": "/plan", "plan_sha256": "a" * 64, + "scientific_stage_admitted": True, "trigger": "frozen_winner", + "winner": "winner", "winner_checkpoint": {"path": "/ckpt", "sha256": "b" * 64}, + "winner_config": {"path": "/config", "sha256": "c" * 64}, + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def test_only_host_local_admission_fields_may_differ() -> None: + source = admission() + central = deepcopy(source) + central["admitted_utc"] = "central-time" + central["available_gib"] = 200.0 + result = validate_admission_pair(source, central, "a" * 64) + assert result["host_local_operational_fields"] == ["admitted_utc", "available_gib"] + + +@pytest.mark.parametrize("field", [ + "winner", "winner_checkpoint", "winner_config", "plan_sha256", + "official_test_used", +]) +def test_scientific_or_isolation_admission_drift_is_rejected(field: str) -> None: + source = admission() + central = deepcopy(source) + if field == "official_test_used": + source[field] = True + elif field == "plan_sha256": + source[field] = "d" * 64 + elif isinstance(source[field], dict): + source[field]["sha256"] = "d" * 64 + else: + source[field] = "different" + with pytest.raises(ValueError, match="admission"): + validate_admission_pair(source, central, "a" * 64) + + +def release_values() -> tuple[dict, dict]: + artifacts = [{"id": "hot3d_train", "path": "/cache", "file_count": 2, "total_bytes": 3}] + release = { + "status": "complete_immutable_release", "owner": "server_new", + "plan_sha256": "d" * 64, + "producer_worker_state": {"sha256": "e" * 64}, + "artifacts": artifacts, "file_count": 2, "total_bytes": 3, + "live_reverse_sync_forbidden": True, "read_only_after_receive": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + receive = { + "status": "complete", "plan_sha256": "d" * 64, + "release_file_count": 2, "release_total_bytes": 3, + "installed": artifacts, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + return release, receive + + +@pytest.mark.parametrize("mutation", [ + "release_plan", "worker_hash", "file_count", "total_bytes", "receive_official", +]) +def test_cache_release_or_receive_hash_binding_drift_is_rejected(mutation: str) -> None: + release, receive = release_values() + if mutation == "release_plan": + release["plan_sha256"] = "f" * 64 + elif mutation == "worker_hash": + release["producer_worker_state"]["sha256"] = "f" * 64 + elif mutation == "file_count": + receive["release_file_count"] = 4 + elif mutation == "total_bytes": + receive["release_total_bytes"] = 4 + else: + receive["official_test_used"] = True + with pytest.raises(ValueError, match="binding"): + validate_release_metadata( + release, receive, source_owner="server_new", + source_worker_sha256="e" * 64, bridge_plan_sha256="d" * 64, + ) + + +def test_cache_manifest_hash_drift_is_rejected(tmp_path: Path) -> None: + root = tmp_path / "release" + path = root / "cache" / "cache_manifest.jsonl" + path.parent.mkdir(parents=True) + path.write_text('{"source_clip_index":1}\n', encoding="utf-8") + expected = {"path": str(path), "sha256": sha256(path)} + release = { + "release_root": str(root), + "files": [{ + "path": "cache/cache_manifest.jsonl", "bytes": path.stat().st_size, + "sha256": sha256(path), + }], + } + assert validate_released_cache_files(release, [expected], [512, 896]) + release["files"][0]["sha256"] = "f" * 64 + with pytest.raises(ValueError, match="file hash differs"): + validate_released_cache_files(release, [expected], [512, 896]) + + +def test_local_worker_cannot_use_distributed_admission_import() -> None: + assignment = { + "central_owner": "taku3", + "stage7_cache_ownership": {"states": [ + {"id": "h2o_cache_worker", "owner": "taku3"}, + {"id": "hot3d_cache_worker", "owner": "server_new"}, + ]}, + } + with pytest.raises(ValueError, match="not external-owned"): + external_cache_worker_owner(assignment, "h2o") + assert external_cache_worker_owner(assignment, "hot3d") == "server_new" + + +def test_ordinary_finalizer_still_requires_exact_admission_hash(tmp_path: Path) -> None: + plan_path = tmp_path / "plan.json" + plan_path.write_text("{}\n", encoding="utf-8") + admission_path = tmp_path / "admission.json" + admission_path.write_text("{}\n", encoding="utf-8") + worker_path = tmp_path / "worker.json" + winner = "winner" + checkpoint = {"path": "/ckpt", "sha256": "b" * 64} + config = {"path": "/config", "sha256": "c" * 64} + worker_path.write_text(json.dumps({ + "status": "complete", "worker": "h2o", + "plan_sha256": digest(plan_path), "admission_state_sha256": "d" * 64, + "winner": winner, "winner_checkpoint": checkpoint, "winner_config": config, + "official_test_used": False, "h2o_official_validation_used": False, + }), encoding="utf-8") + plan = {"admission_state": str(admission_path), "workers": [{ + "id": "h2o", "state": str(worker_path), + }]} + with pytest.raises(ValueError, match="winner binding differs"): + inspect_workers(plan_path, plan, { + "winner": winner, "winner_checkpoint": checkpoint, "winner_config": config, + }) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_distributed_assignment.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_distributed_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..18f454e8026049e8b3dda69ec1a7acce6462efc6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_distributed_assignment.py @@ -0,0 +1,151 @@ +import json +from pathlib import Path + +from scripts.phase9_distributed_assignment import ( + condition_owners, + distribute_evaluations, + gpu_allowlist, + load_assignment, + role_owners, +) +from scripts.run_phase9_selection_binding_recovery import ( + json_sha256, + validate_recovered_output, +) +from scripts.run_phase9_unified_train_queue import sha256 + + +ROOT = Path(__file__).resolve().parents[1] +ASSIGNMENT = ( + ROOT / "artifacts/phase9/registry/foundation_phase9_distributed_assignment_v2.json" +) + + +def assignment() -> dict: + return load_assignment({"distributed_assignment": { + "path": str(ASSIGNMENT), "sha256": sha256(ASSIGNMENT), + }}) + + +def test_distributed_assignment_freezes_exact_role_owners_and_server_gpus() -> None: + value = assignment() + assert role_owners(value) == { + "full": "taku3", + "loso_subject1": "taku3", + "loso_subject2": "server_new", + "loso_subject3": "server_new", + "lofamily_h": "taku3", + "lofamily_k": "server_new", + "lofamily_o": "taku3", + } + assert gpu_allowlist(value, "taku3") == [0, 1, 2, 3, 4, 5] + assert gpu_allowlist(value, "server_new") == [0, 1, 2, 5] + assert value["selection_owner"] == "taku3" + assert value["report_owner"] == "taku3" + assert value["writer_contract"]["live_reverse_sync_forbidden"] is True + + +def test_training_and_evaluation_partitions_are_disjoint() -> None: + value = assignment() + registry = {"conditions": [ + {"condition": f"S7R_J55_{role}", "role": role} + for role in role_owners(value) + ]} + owners = condition_owners(registry, value) + assert sum(owner == "taku3" for owner in owners.values()) == 4 + assert sum(owner == "server_new" for owner in owners.values()) == 3 + + role_ids = value["stage_evaluation_ownership"]["evaluation_ids_by_role"] + evaluations = [ + {"id": identifier, "training_role": record["role"]} + for record in role_ids for identifier in record["ids"] + ] + workers = distribute_evaluations( + evaluations=evaluations, assignment=value, + worker_state_root=Path("/tmp/phase9-distributed-test"), + ) + assert len(workers) == 10 + assigned = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + assert len(assigned) == len(set(assigned)) == 25 + assert set(assigned) == {item["id"] for item in evaluations} + assert { + worker["physical_gpu_id"] + for worker in workers if worker["owner"] == "server_new" + } == {0, 1, 2, 5} + by_id = {item["id"]: item for item in evaluations} + for worker in workers: + assert all(by_id[identifier]["owner"] == worker["owner"] for identifier in worker["evaluation_ids"]) + + +def test_selection_binding_audit_is_complete_and_path_only() -> None: + path = ROOT / "artifacts/phase9/reports/selection_binding_mismatch_manifest_20260731.json" + report = json.loads(path.read_text(encoding="utf-8")) + assert report["selection_critical_report_count"] == 72 + assert report["canonical_report_count"] == 61 + assert report["mismatch_count"] == 11 + assert report["binding_status_counts"] == { + "canonical": 61, + "path_mismatch_content_identical": 11, + } + assert report["summarizer_binding_gate_changed"] is False + assert report["evaluation_reports_modified"] is False + assert report["official_test_used"] is False + + +def test_recovery_output_requires_exact_samples_and_determinism(tmp_path) -> None: + output = tmp_path / "output" + output.mkdir() + config = tmp_path / "config.yaml" + checkpoint = tmp_path / "checkpoint.pt" + manifest = tmp_path / "heldout.jsonl" + raw = output / "raw_predictions.npz" + rows = output / "per_hand_frame_metrics.csv" + takes = output / "take_metrics.csv" + for path, content in ( + (config, b"config"), (checkpoint, b"checkpoint"), + (manifest, b"manifest"), (raw, b"raw"), + (rows, b"rows"), (takes, b"takes"), + ): + path.write_bytes(content) + metrics = {"absolute_mpjpe_mm": {"mean": 1.25}} + bootstrap = {"absolute_mpjpe_mm": {"mean": 1.25}} + report = { + "status": "evaluated_phase9_h2o_fold_heldout", + "evaluation_role": "phase9_h2o_fold_heldout", + "input_mode": "rgb_d_k", + "config": {"path": str(config.resolve()), "sha256": sha256(config)}, + "checkpoint": {"path": str(checkpoint.resolve()), "sha256": sha256(checkpoint)}, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "clips": 2, "frames": 3, "hands_rows": 4, + "metrics": metrics, "grouped_bootstrap_ci": bootstrap, + "raw_predictions": {"path": str(raw.resolve()), "sha256": sha256(raw)}, + "per_hand_rows": {"path": str(rows.resolve()), "sha256": sha256(rows)}, + "take_metrics": {"path": str(takes.resolve()), "sha256": sha256(takes)}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + (output / "evaluation.json").write_text(json.dumps(report), encoding="utf-8") + item = { + "id": "test", "output_dir": str(output), + "evaluation_role": "phase9_h2o_fold_heldout", "input_mode": "rgb_d_k", + "config": str(config.resolve()), "config_sha256": sha256(config), + "checkpoint": str(checkpoint.resolve()), "checkpoint_sha256": sha256(checkpoint), + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "expected_sample_counts": {"clips": 2, "frames": 3, "hands_rows": 4}, + "expected_determinism": { + "metrics_sha256": json_sha256(metrics), + "grouped_bootstrap_ci_sha256": json_sha256(bootstrap), + "raw_predictions_sha256": sha256(raw), + "per_hand_rows_sha256": sha256(rows), + "take_metrics_sha256": sha256(takes), + }, + } + assert validate_recovered_output(item)["sample_counts"]["frames"] == 3 + item["expected_sample_counts"]["frames"] = 4 + try: + validate_recovered_output(item) + except ValueError as error: + assert "role/sample contract differs" in str(error) + else: + raise AssertionError("selection recovery accepted a sample-count mismatch") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_expanded_coverage_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_expanded_coverage_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..50f3ceb82628ddf84b7e91a5e5e564520941159e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_expanded_coverage_queue.py @@ -0,0 +1,24 @@ +import json +from pathlib import Path + +from scripts.run_phase9_expanded_coverage_queue import audit_complete, sha256 + + +def test_coverage_completion_binds_source_and_cache_manifests(tmp_path: Path) -> None: + source = tmp_path / "source.jsonl" + cache = tmp_path / "cache.jsonl" + output = tmp_path / "audit.json" + source.write_text("{}\n", encoding="utf-8") + cache.write_text("{}\n", encoding="utf-8") + output.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + "source_manifest": {"sha256": sha256(source)}, + "cache_manifest": {"sha256": sha256(cache)}, + }), encoding="utf-8") + item = { + "source_manifest": str(source), "cache_manifest": str(cache), + "output": str(output), + } + assert audit_complete(item) + cache.write_text("changed\n", encoding="utf-8") + assert not audit_complete(item) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_external_milestone_eval.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_external_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..462a156ab3efe0ef660a9b5df72ef6de1cd6630f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_external_milestone_eval.py @@ -0,0 +1,56 @@ +import json +from pathlib import Path + +from scripts.run_phase9_external_milestone_eval import ( + ALLOWED_GPUS, + checkpoint_path, + evaluation_complete, + sha256, + stable_checkpoint_sha256, +) + + +def test_user_authorized_all_physical_gpus_for_evaluation() -> None: + assert ALLOWED_GPUS == (0, 1, 2, 3, 4, 5) + + +def test_milestone_checkpoint_discovery_requires_unique_file(tmp_path: Path) -> None: + condition = {"run_dir": str(tmp_path)} + spec = {"kind": "milestone", "milestone_id": "all20"} + assert checkpoint_path(condition, spec) is None + first = tmp_path / "milestone_all20_step_0000100.pt" + first.write_bytes(b"first") + assert checkpoint_path(condition, spec) == first + (tmp_path / "milestone_all20_step_0000101.pt").write_bytes(b"second") + try: + checkpoint_path(condition, spec) + except RuntimeError as error: + assert "multiple" in str(error) + else: + raise AssertionError("duplicate milestone files were accepted") + + +def test_phase9_external_evaluation_completion_contract(tmp_path: Path) -> None: + output = tmp_path / "evaluation" + output.mkdir() + report = { + "status": "evaluated_phase9_external_heldout", + "evaluation_role": "phase9_external_heldout", + "checkpoint": {"sha256": "a" * 64}, + "cache_manifest": {"sha256": "b" * 64}, + "input_mode": "rgb_k", "h2o_training_data_used": True, + "official_test_used": False, + } + (output / "evaluation.json").write_text(json.dumps(report), encoding="utf-8") + assert evaluation_complete(output, "a" * 64, "b" * 64, "rgb_k") + report["official_test_used"] = True + (output / "evaluation.json").write_text(json.dumps(report), encoding="utf-8") + assert not evaluation_complete(output, "a" * 64, "b" * 64, "rgb_k") + + +def test_checkpoint_hash_waits_for_stable_file(tmp_path: Path) -> None: + checkpoint = tmp_path / "milestone.pt" + checkpoint.write_bytes(b"complete checkpoint") + assert stable_checkpoint_sha256( + checkpoint, stable_seconds=0.01, poll_seconds=0.005, + ) == sha256(checkpoint) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_final_deployment_controller.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_final_deployment_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..6c89bb9fd956e77120fc08dc0afcb7bac4a090e1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_final_deployment_controller.py @@ -0,0 +1,36 @@ +import json +from pathlib import Path + +from scripts.run_phase9_final_deployment_controller import ( + final_decision_ready, + validate_plan, +) +from scripts.run_phase9_unified_train_queue import sha256 + + +def test_final_deployment_waits_for_bound_last2_decision(tmp_path: Path) -> None: + controller_plan = tmp_path / "last2_plan.json" + controller_plan.write_text("{}", encoding="utf-8") + report = tmp_path / "last2_report.json" + report.write_text(json.dumps({"status": "complete"}), encoding="utf-8") + state = tmp_path / "last2_state.json" + state.write_text(json.dumps({ + "status": "complete", "plan_sha256": sha256(controller_plan), + "decision_report": {"path": str(report), "sha256": sha256(report)}, + "h2o_official_validation_used": False, "official_test_used": False, + }), encoding="utf-8") + plan = { + "last2_finalizer_state": str(state), + "last2_finalizer_plan_sha256": sha256(controller_plan), + "last2_final_decision": str(report), + } + assert final_decision_ready(plan) + payload = json.loads(state.read_text(encoding="utf-8")) + payload["h2o_official_validation_used"] = True + state.write_text(json.dumps(payload), encoding="utf-8") + assert not final_decision_ready(plan) + + +def test_checked_in_final_deployment_plan_is_hash_bound() -> None: + path = Path("artifacts/phase9/registry/final_deployment_controller_plan.json") + validate_plan(json.loads(path.read_text(encoding="utf-8"))) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_final_deployment_worker.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_final_deployment_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..0272bbe5b3222548e92fcea6c20ee8f13fb50c6b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_final_deployment_worker.py @@ -0,0 +1,42 @@ +import json +from pathlib import Path + +from scripts.run_phase9_final_deployment_worker import completed_matches + + +def test_sequence_completion_requires_bounded_causal_invariance(tmp_path: Path) -> None: + checkpoint = tmp_path / "checkpoint.pt" + config = tmp_path / "config.yaml" + manifest = tmp_path / "official_val.jsonl" + for path in (checkpoint, config, manifest): + path.write_text(path.name, encoding="utf-8") + import hashlib + digest = lambda path: hashlib.sha256(path.read_bytes()).hexdigest() + output = tmp_path / "sequence.json" + job = { + "kind": "sequence", "mode": "causal", "window": 8, "frames": 31, + "checkpoint_step": 12, + "checkpoint_sha256": digest(checkpoint), + "config_sha256": digest(config), "manifest_sha256": digest(manifest), + "output": str(output), + } + report = { + "status": "passed", "mode": "causal", "window": 8, + "causal": True, "offline_stride": None, "stitching": None, + "requested_frames": 31, "output_frames": 31, + "frame_ids_strictly_increasing": True, "finite": True, + "maximum_gpu_window_frames": 8, "maximum_cpu_input_buffer_frames": 8, + "invariance": { + "future_perturbation_bitwise_zero": True, "prefix_passed": True, + }, + "checkpoint": {"sha256": digest(checkpoint), "step": 12}, + "config": {"sha256": digest(config)}, + "manifest": {"sha256": digest(manifest)}, + "official_validation_used_for_selection": False, + "official_test_used": False, + } + output.write_text(json.dumps(report), encoding="utf-8") + assert completed_matches(job) + report["maximum_cpu_input_buffer_frames"] = 9 + output.write_text(json.dumps(report), encoding="utf-8") + assert not completed_matches(job) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..99a41299b62f6fbe4074b6e3d0fdc4fbe2bacab4 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_configs.py @@ -0,0 +1,29 @@ +import json +from pathlib import Path + +import yaml + +from scripts.build_phase9_fold_configs import sha256 +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def test_generated_fold_registry_and_configs_are_isolated() -> None: + root = Path(__file__).resolve().parents[1] + registry_path = root / "artifacts/phase9/registry/h2o_multifold_training_queue.json" + if not registry_path.is_file(): + return + registry = json.loads(registry_path.read_text(encoding="utf-8")) + assert registry["official_test_used"] is False + assert len(registry["conditions"]) == 18 + assert sorted(len(values) for values in registry["shards"].values()) == [6, 6, 6] + for condition in registry["conditions"]: + path = Path(condition["config"]) + assert sha256(path) == condition["config_sha256"] + config = yaml.safe_load(path.read_text(encoding="utf-8")) + assert validate_phase9_unified_contract(config, path) == [] + assert config["loss"]["joint3d_root_relative"] == 10.0 + fold = condition["h2o_selection_fold"] + h2o = next(source for source in config["data"]["sources"] if source["dataset"] == "H2O") + assert Path(h2o["cache_manifest"]).name == f"{fold}_train.jsonl" + heldout = config["data"]["validation_sources"][0]["cache_manifest"] + assert Path(heldout).name == f"{fold}_heldout.jsonl" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_milestone_eval.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..4a29e0b36f8d80f8589414ea636f99cef1f1d947 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_milestone_eval.py @@ -0,0 +1,90 @@ +import json +from pathlib import Path +import threading + +from scripts.run_phase9_fold_milestone_eval import ( + ALLOWED_GPUS, + evaluation_command, + exclusive_evaluation_output, + h2o_milestones, + milestone_checkpoint, + recovery_assignment, + sha256, +) + + +def test_user_authorized_all_physical_gpus_for_fold_evaluation() -> None: + assert ALLOWED_GPUS == (0, 1, 2, 3, 4, 5) + + +def test_h2o_milestones_exclude_hot_only_checkpoints() -> None: + config = {"protocol": {"source_exposure_milestones": [ + {"id": "hot50", "minimum_batches": {"HOT3D": 50000}}, + {"id": "nonhot20", "minimum_batches": {"H2O": 20000, "HOI4D": 20000}}, + ]}} + assert h2o_milestones(config) == ["nonhot20"] + + +def test_milestone_checkpoint_requires_one_atomic_result(tmp_path: Path) -> None: + assert milestone_checkpoint(tmp_path, "nonhot20") is None + path = tmp_path / "milestone_nonhot20_step_0010000.pt" + path.write_bytes(b"checkpoint") + assert milestone_checkpoint(tmp_path, "nonhot20") == path + + +def test_evaluator_gpu45_authorization_is_forwarded_only_when_needed( + tmp_path: Path, +) -> None: + arguments = (tmp_path / "config.yaml", tmp_path / "checkpoint.pt", "a" * 64, + tmp_path / "heldout.jsonl", "b" * 64, "rgb_k", + tmp_path / "output") + assert "--allow-physical-gpus-4-5" not in evaluation_command(*arguments, 3) + assert "--allow-physical-gpus-4-5" in evaluation_command(*arguments, 4) + assert "--allow-physical-gpus-4-5" in evaluation_command(*arguments, 5) + + +def test_recovery_worker_is_hash_bound_and_unique(tmp_path: Path) -> None: + plan = tmp_path / "plan.json" + plan.write_text(json.dumps({ + "official_test_used": False, + "registry_sha256": "a" * 64, + "workers": [{"id": "gpu4", "shard": 1}], + }), encoding="utf-8") + assignment, plan_hash = recovery_assignment(plan, "gpu4", "a" * 64) + assert assignment["shard"] == 1 + assert plan_hash == sha256(plan) + + +def test_recovery_worker_rejects_registry_drift(tmp_path: Path) -> None: + plan = tmp_path / "plan.json" + plan.write_text(json.dumps({ + "official_test_used": False, + "registry_sha256": "a" * 64, + "workers": [{"id": "gpu4", "shard": 1}], + }), encoding="utf-8") + try: + recovery_assignment(plan, "gpu4", "b" * 64) + except ValueError as error: + assert "registry SHA256 differs" in str(error) + else: + raise AssertionError("registry drift was accepted") + + +def test_evaluation_output_lock_is_mutually_exclusive(tmp_path: Path) -> None: + output = tmp_path / "condition" / "rgb_k" + started = threading.Event() + acquired = threading.Event() + + def contender() -> None: + started.set() + with exclusive_evaluation_output(output): + acquired.set() + + with exclusive_evaluation_output(output): + thread = threading.Thread(target=contender) + thread.start() + assert started.wait(timeout=1) + assert not acquired.wait(timeout=0.1) + assert acquired.wait(timeout=1) + thread.join(timeout=1) + assert not thread.is_alive() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_overflow.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..939145307bbe0badd8937e5846781fdb52cb0b37 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_overflow.py @@ -0,0 +1,29 @@ +import json +from pathlib import Path + +from scripts.run_phase9_fold_overflow import prerequisite_states_complete + + +def test_overflow_prerequisites_are_complete_and_test_isolated(tmp_path: Path) -> None: + main_state = tmp_path / "main.json" + eval_state = tmp_path / "eval.json" + plan = { + "prerequisite_states": [ + {"path": str(main_state)}, + {"path": str(eval_state)}, + ], + } + for path in (main_state, eval_state): + path.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + }), encoding="utf-8") + assert prerequisite_states_complete(plan) + eval_state.write_text(json.dumps({ + "status": "complete", "official_test_used": True, + }), encoding="utf-8") + assert not prerequisite_states_complete(plan) + + +def test_overflow_prerequisites_fail_closed_when_missing(tmp_path: Path) -> None: + plan = {"prerequisite_states": [{"path": str(tmp_path / "missing.json")}]} + assert not prerequisite_states_complete(plan) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_shard.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_shard.py new file mode 100644 index 0000000000000000000000000000000000000000..ebf95310a8415f3f5ef5990a774946c5e322602f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_fold_shard.py @@ -0,0 +1,40 @@ +import json +from pathlib import Path + +from scripts.run_phase9_fold_shard import ( + fold_evaluation_complete, + main_training_complete, + main_training_gate_satisfied, +) + + +def test_fold_shard_waits_for_all_main_conditions(tmp_path: Path) -> None: + states = [] + for condition in ("J25", "J40", "J55"): + path = tmp_path / f"{condition}.json" + path.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + }), encoding="utf-8") + states.append({"condition": condition, "path": str(path)}) + plan = {"main_training_states": states} + assert main_training_complete(plan) + payload = json.loads(Path(states[-1]["path"]).read_text(encoding="utf-8")) + payload["status"] = "running" + Path(states[-1]["path"]).write_text(json.dumps(payload), encoding="utf-8") + assert not main_training_complete(plan) + assert main_training_gate_satisfied(plan, start_before_main_complete=True) + assert not main_training_gate_satisfied(plan, start_before_main_complete=False) + + +def test_fold_evaluation_completion_is_hash_and_mode_bound(tmp_path: Path) -> None: + output = tmp_path / "eval" + output.mkdir() + (output / "evaluation.json").write_text(json.dumps({ + "status": "evaluated_phase9_h2o_fold_heldout", + "evaluation_role": "phase9_h2o_fold_heldout", + "checkpoint": {"sha256": "a" * 64}, + "cache_manifest": {"sha256": "b" * 64}, + "input_mode": "rgb_d_k", "official_test_used": False, + }), encoding="utf-8") + assert fold_evaluation_complete(output, "a" * 64, "b" * 64, "rgb_d_k") + assert not fold_evaluation_complete(output, "a" * 64, "b" * 64, "rgb_only") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_geometry_augmentation.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_geometry_augmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..906bbf5880dc97ec5aa66ea96b8cda636b94aab5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_geometry_augmentation.py @@ -0,0 +1,134 @@ +import json +from pathlib import Path + +import numpy as np + +from foundation_hand.data.cached_unified_dataset import ( + CachedUnifiedClipDataset, + FullFrameGeometryAugmentation, + _shift, + apply_full_frame_affine, + corrupt_metric_depth, + sample_full_frame_affine, +) +from foundation_hand.geometry.camera import project_points + + +def test_full_frame_affine_is_clip_deterministic_and_gt_independent() -> None: + config = FullFrameGeometryAugmentation.from_mapping({ + "enabled": True, + "probability": 1.0, + "scale_min": 0.9, + "scale_max": 1.1, + "translation_fraction": 0.05, + }) + first, first_applied = sample_full_frame_affine(config, 17, 9, 3, (80, 120)) + second, second_applied = sample_full_frame_affine(config, 17, 9, 3, (80, 120)) + changed, _ = sample_full_frame_affine(config, 17, 9, 4, (80, 120)) + np.testing.assert_array_equal(first, second) + assert first_applied and second_applied + assert not np.array_equal(first, changed) + + +def test_full_frame_affine_preserves_projection_and_depth_validity() -> None: + time, height, width = 2, 8, 10 + rgb = np.zeros((time, height, width, 3), dtype=np.uint8) + rgb[:, 3, 4] = 255 + depth = np.zeros((time, 1, height, width), dtype=np.float32) + valid = np.zeros_like(depth, dtype=bool) + depth[:, :, 3, 4] = 0.7 + valid[:, :, 3, 4] = True + K = np.repeat( + np.array([[[8.0, 0.0, 4.5], [0.0, 8.0, 3.5], [0.0, 0.0, 1.0]]], dtype=np.float32), + time, axis=0, + ) + points = np.array([[[0.1, -0.1, 0.7]]], dtype=np.float32) + joints, _ = project_points(points, K[:1]) + matrix = np.array( + [[1.2, 0.0, -0.4], [0.0, 1.2, 0.3], [0.0, 0.0, 1.0]], + dtype=np.float32, + ) + warped_rgb, updated = apply_full_frame_affine(rgb, { + "image_hw": np.array([height, width], dtype=np.int64), + "depth_m": depth, + "depth_pixel_valid": valid, + "K": K, + "joint2d": np.repeat(joints[:, None], time, axis=0), + }, matrix) + projected, _ = project_points(points, updated["K"][:1]) + expected = joints.copy() + expected[..., 0] = 1.2 * expected[..., 0] - 0.4 + expected[..., 1] = 1.2 * expected[..., 1] + 0.3 + np.testing.assert_allclose(projected, expected, atol=1e-5) + np.testing.assert_allclose(updated["joint2d"][0, 0], expected[0], atol=1e-5) + assert warped_rgb.shape == rgb.shape + assert updated["depth_m"].shape == depth.shape + assert updated["depth_pixel_valid"].dtype == bool + assert np.all(updated["depth_m"][~updated["depth_pixel_valid"]] == 0.0) + + +def test_registration_shift_keeps_depth_and_validity_synchronized() -> None: + depth = np.zeros((1, 1, 12, 12), dtype=np.float32) + valid = np.zeros_like(depth, dtype=bool) + depth[..., 5, 6] = 0.7 + valid[..., 5, 6] = True + seed = 19 + dy, dx = np.random.default_rng(seed).integers(-3, 4, size=2) + expected_depth = _shift(depth, int(dy), int(dx), 0.0) + expected_valid = _shift(valid, int(dy), int(dx), False) + shifted_depth, shifted_valid = corrupt_metric_depth( + depth, valid, "registration_shift", seed, + ) + np.testing.assert_array_equal(shifted_valid, expected_valid) + np.testing.assert_allclose(shifted_depth, expected_depth) + assert np.count_nonzero(shifted_depth) == np.count_nonzero(shifted_valid) == 1 + + +def test_cached_geometry_augmentation_updates_k_while_retaining_supervision( + tmp_path: Path, +) -> None: + time, height, width = 2, 16, 24 + cache = tmp_path / "clip.npz" + K = np.repeat( + np.array([[[20.0, 0.0, 12.0], [0.0, 20.0, 8.0], [0.0, 0.0, 1.0]]], dtype=np.float32), + time, axis=0, + ) + np.savez_compressed( + cache, + rgb_u8=np.zeros((time, height, width, 3), dtype=np.uint8), + image_hw=np.array([height, width], dtype=np.int64), + frame_valid=np.ones(time, dtype=bool), + depth_m=np.full((time, 1, height, width), 0.6, dtype=np.float32), + depth_pixel_valid=np.ones((time, 1, height, width), dtype=bool), + depth_input_available=np.ones(time, dtype=bool), + K=K, + K_supervision_valid=np.ones(time, dtype=bool), + joint2d=np.zeros((time, 2, 21, 2), dtype=np.float32), + ) + row = { + "cache_path": str(cache), "source_clip_index": 4, + "dataset_id": "HOI4D", "subject_id": "s", "sequence_id": "q", + "physical_recording_id": "r", "camera_id": "c", "stream_id": "c", + "headset_id": "h", + } + manifest = tmp_path / "cache_manifest.jsonl" + manifest.write_text(json.dumps(row) + "\n", encoding="utf-8") + dataset = CachedUnifiedClipDataset( + manifest, + K_input_dropout=1.0, + geometry_augmentation={ + "enabled": True, "probability": 1.0, + "scale_min": 1.1, "scale_max": 1.1, + "translation_fraction": 0.0, + }, + ) + first = dataset[(0, 2)] + second = dataset[(0, 2)] + np.testing.assert_array_equal( + first["geometry_aug_matrix"].numpy(), + second["geometry_aug_matrix"].numpy(), + ) + assert first["geometry_aug_applied"].all() + assert not first["K_input_available"].any() + assert first["K_supervision_valid"].all() + assert not np.array_equal(first["K"].numpy(), K) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_h2o_multifold.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_h2o_multifold.py new file mode 100644 index 0000000000000000000000000000000000000000..f17365957219b273fa01ef5f7cf5cee8bec47a99 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_h2o_multifold.py @@ -0,0 +1,29 @@ +from scripts.build_phase9_h2o_multifold import fold_definitions, split_rows + + +def rows() -> list[dict]: + return [ + {"dataset_id": "H2O", "subject_id": subject, + "physical_recording_id": f"{subject}/{family}1/{take}"} + for subject in ("subject1", "subject2", "subject3") + for family in ("h", "k", "o") + for take in range(2) + ] + + +def test_h2o_multifold_defines_subject_and_family_folds() -> None: + definitions = fold_definitions(rows()) + assert [item["id"] for item in definitions] == [ + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + ] + + +def test_h2o_multifold_keeps_physical_recordings_isolated() -> None: + source = rows() + for definition in fold_definitions(source): + train, heldout = split_rows(source, definition) + assert {row["physical_recording_id"] for row in train}.isdisjoint( + {row["physical_recording_id"] for row in heldout} + ) + assert len(train) + len(heldout) == len(source) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_cache_release_bridge.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_cache_release_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..40bde613845b1cd34de9f777313ad00b8ba9f81b --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_cache_release_bridge.py @@ -0,0 +1,60 @@ +import json +from pathlib import Path + +import pytest + +from scripts.run_phase9_hot_cache_release_bridge import ( + inventory_tree, + validate_release, + verify_staging, +) +from scripts.run_phase9_resolution_cache_queue import sha256 + + +def test_inventory_is_relative_hash_bound_and_sorted(tmp_path: Path) -> None: + artifact = tmp_path / "cache" / "hot" + artifact.mkdir(parents=True) + (artifact / "b").write_bytes(b"b") + (artifact / "a").write_bytes(b"a") + records = inventory_tree(tmp_path, artifact) + assert [item["path"] for item in records] == ["cache/hot/a", "cache/hot/b"] + assert records[0]["sha256"] == sha256(artifact / "a") + + +def test_inventory_rejects_symlink(tmp_path: Path) -> None: + artifact = tmp_path / "cache" + artifact.mkdir() + (tmp_path / "payload").write_text("x", encoding="utf-8") + (artifact / "link").symlink_to(tmp_path / "payload") + with pytest.raises(ValueError, match="symlink"): + inventory_tree(tmp_path, artifact) + + +def test_release_rejects_duplicate_or_unsafe_paths(tmp_path: Path) -> None: + plan_path = tmp_path / "plan.json" + plan_path.write_text("{}\n", encoding="utf-8") + plan = {"release_root": str(tmp_path / "root")} + base = { + "status": "complete_immutable_release", "owner": "server_new", + "plan_sha256": sha256(plan_path), + "release_root": str((tmp_path / "root").resolve()), + "official_test_used": False, "h2o_official_validation_used": False, + "live_reverse_sync_forbidden": True, "read_only_after_receive": True, + "files": [{"path": "../bad", "bytes": 1, "sha256": "a" * 64}], + "file_count": 1, "total_bytes": 1, + } + with pytest.raises(ValueError, match="unsafe"): + validate_release(plan_path, plan, base) + + +def test_staging_verification_checks_bytes_and_hash(tmp_path: Path) -> None: + path = tmp_path / "cache" / "payload" + path.parent.mkdir() + path.write_bytes(b"payload") + release = {"files": [{ + "path": "cache/payload", "bytes": 7, "sha256": sha256(path), + }]} + verify_staging(tmp_path, release) + path.write_bytes(b"changed") + with pytest.raises(ValueError, match="differs"): + verify_staging(tmp_path, release) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_prefill.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc7d16b71fe0195177cf3dac54537e79908269f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_prefill.py @@ -0,0 +1,143 @@ +import json +import os +from pathlib import Path + +import pytest + +from scripts.cache_phase7_hot3d import sha256 +from scripts.merge_phase9_hot_prefill import merge_prefills, validate_prefill_reports +from scripts.run_phase9_hot_prefill_queue import ( + prefill_complete, + runtime_command, + validate_plan, +) + + +def report(position_range: list[int], digest: str = "a" * 64) -> dict: + return { + "status": "complete", "mode": "staged_prefill", + "official_test_used": False, "full_candidate_clips": 10, + "requested_target_clips": 8, "max_recordings": 3, + "candidate_source_indices_sha256": digest, + "candidate_position_range": position_range, + "source_manifest": {"sha256": "b" * 64}, + } + + +def test_prefill_reports_reject_overlap_and_selection_drift() -> None: + with pytest.raises(ValueError, match="overlap"): + validate_prefill_reports([report([2, 6]), report([5, 8])]) + with pytest.raises(ValueError, match="candidate_source_indices_sha256"): + validate_prefill_reports([report([2, 5]), report([5, 8], "c" * 64)]) + + +def test_phase9_prefill_plan_partitions_the_far_candidate_suffix() -> None: + root = Path(__file__).resolve().parents[1] + plan = json.loads( + (root / "artifacts/phase9/registry/hot_prefill_plan.json").read_text( + encoding="utf-8" + ) + ) + assert plan["official_test_used"] is False + ranges = [item["candidate_position_range"] for item in plan["shards"]] + assert ranges[0][0] == plan["primary_writer_position_range"][1] + assert ranges[-1][1] == plan["full_candidate_clips"] + assert all(first[1] == second[0] for first, second in zip(ranges, ranges[1:])) + + +def make_prefill(root: Path, source_index: int, position_range: list[int]) -> Path: + output = root / f"prefill_{source_index}" + clips = output / "clips" + clips.mkdir(parents=True) + cache = clips / f"clip_{source_index:07d}.npz" + cache.write_bytes(f"payload-{source_index}".encode()) + row = { + "source_clip_index": source_index, + "cache_path": str(cache.resolve()), "cache_sha256": sha256(cache), + } + manifest = output / "prefill_manifest.jsonl" + manifest.write_text(json.dumps(row) + "\n", encoding="utf-8") + value = report(position_range) + value.update({ + "clips": 1, + "cache_manifest": {"path": str(manifest), "sha256": sha256(manifest)}, + }) + (output / "cache_report.json").write_text( + json.dumps(value) + "\n", encoding="utf-8", + ) + return output + + +def test_prefill_merge_hardlinks_without_freezing_target_manifest(tmp_path: Path) -> None: + target = tmp_path / "target" + (target / "clips").mkdir(parents=True) + first = make_prefill(tmp_path, 7, [2, 3]) + second = make_prefill(tmp_path, 9, [4, 5]) + result = merge_prefills(target, [first, second], tmp_path / "merge.json") + assert result["linked"] == 2 + assert not (target / "cache_manifest.jsonl").exists() + assert os.stat(first / "clips/clip_0000007.npz").st_ino == os.stat( + target / "clips/clip_0000007.npz" + ).st_ino + + +def test_prefill_merge_rejects_nonidentical_existing_target(tmp_path: Path) -> None: + target = tmp_path / "target" + (target / "clips").mkdir(parents=True) + prefill = make_prefill(tmp_path, 7, [2, 3]) + (target / "clips/clip_0000007.npz").write_bytes(b"different") + with pytest.raises(ValueError, match="collision differs"): + merge_prefills(target, [prefill], tmp_path / "merge.json") + + +def test_distributed_prefill_completion_binds_resolution_and_candidate_order( + tmp_path: Path, +) -> None: + output = make_prefill(tmp_path, 7, [2, 3]) + value = json.loads((output / "cache_report.json").read_text(encoding="utf-8")) + value["resolution_hw"] = [512, 896] + (output / "cache_report.json").write_text( + json.dumps(value) + "\n", encoding="utf-8", + ) + shard = {"output_dir": str(output), "candidate_position_range": [2, 3]} + plan = { + "resolution_hw": [512, 896], "full_candidate_clips": 10, + "requested_target_clips": 8, + "candidate_source_indices_sha256": "a" * 64, + "source_manifest": {"sha256": "b" * 64}, + } + assert prefill_complete(shard, plan) + value["candidate_source_indices_sha256"] = "c" * 64 + (output / "cache_report.json").write_text( + json.dumps(value) + "\n", encoding="utf-8", + ) + assert not prefill_complete(shard, plan) + + +def test_distributed_prefill_resume_does_not_change_frozen_command(tmp_path: Path) -> None: + output = tmp_path / "partial" + shard = {"output_dir": str(output), "command": ["python", "cache"]} + assert runtime_command(shard) == ["python", "cache"] + output.mkdir() + assert runtime_command(shard) == ["python", "cache", "--resume"] + assert shard["command"] == ["python", "cache"] + + +def test_distributed_896_prefill_plan_is_hash_bound_and_contiguous() -> None: + root = Path(__file__).resolve().parents[1] + registry = root / "artifacts/phase9/registry" + for name in ( + "hot_prefill_896_distributed_plan.json", + "hot_prefill_896_distributed_plan_v2.json", + ): + path = registry / name + plan = json.loads(path.read_text(encoding="utf-8")) + validate_plan(path, plan) + assert len(plan["shards"]) == 8 + assert plan["shards"][0]["candidate_position_range"][0] == 0 + assert plan["shards"][-1]["candidate_position_range"][1] == 110000 + assert all( + first["candidate_position_range"][1] + == second["candidate_position_range"][0] + for first, second in zip(plan["shards"], plan["shards"][1:]) + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_scale_configs.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_scale_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..d638b5be53ee0642d8d5879113fab513a435ddf5 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_scale_configs.py @@ -0,0 +1,26 @@ +import json +from pathlib import Path + +import yaml + +from scripts.build_phase9_hot_scale_configs import sha256 +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def test_generated_hot_scale_configs_change_only_hot_cache_identity() -> None: + root = Path(__file__).resolve().parents[1] + registry_path = root / "artifacts/phase9/registry/hot_scale_training_queue.json" + if not registry_path.is_file(): + return + registry = json.loads(registry_path.read_text(encoding="utf-8")) + assert registry["official_test_used"] is False + assert {item["condition"] for item in registry["conditions"]} == { + "J40_HOT10K", "J40_HOT50K", + } + for item in registry["conditions"]: + path = Path(item["config"]) + assert sha256(path) == item["config_sha256"] + config = yaml.safe_load(path.read_text(encoding="utf-8")) + assert validate_phase9_unified_contract(config, path) == [] + assert config["loss"]["joint3d_root_relative"] == 10.0 + assert config["protocol"]["max_steps"] == 505000 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_scale_summary.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_scale_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..37ee561d5b7342db37afa3ce9f16033b33bcd5f3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_hot_scale_summary.py @@ -0,0 +1,103 @@ +import json +from pathlib import Path + +import pytest + +from scripts.summarize_phase9_hot_scale import load_evaluation, summarize + + +SOURCES = ( + "hot3d_rgb_k", "hot3d_rgb_only", "hoi4d_rgb_d_k", "hoi4d_rgb_k", + "hoi4d_rgb_only", "arctic_rgb_k", "arctic_rgb_only", +) + + +def evaluation(value: float, checkpoint_hash: str, manifest_hash: str = "d" * 64) -> dict: + metrics = { + name: {"mean": value, "p95": value + 1.0} + for name in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "pa_mpjpe_mm", + "mpvpe_mm", "fingertip_mpjpe_mm", "translation_x_mae_mm", + "translation_y_mae_mm", "translation_z_mae_mm", + ) + } + metrics["bucket_headset_aria"] = { + "absolute_mpjpe_mm": {"mean": value + 2.0}, + } + metrics["bucket_headset_quest3"] = { + "absolute_mpjpe_mm": {"mean": value + 3.0}, + } + return { + "status": "evaluated_phase9_external_heldout", + "evaluation_role": "phase9_external_heldout", + "h2o_training_data_used": True, + "official_test_used": False, + "checkpoint": {"path": "/checkpoint.pt", "sha256": checkpoint_hash}, + "cache_manifest": {"path": "/manifest.jsonl", "sha256": manifest_hash}, + "metrics": metrics, + } + + +def write_report(path: Path, value: float, checkpoint_hash: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(evaluation(value, checkpoint_hash)), encoding="utf-8") + header = ( + "physical_recording_id,absolute_mpjpe_mm,root_relative_mpjpe_mm," + "fingertip_mpjpe_mm,translation_z_mae_mm\n" + ) + rows = f"take_a,{value},{value},{value},{value}\ntake_b,{value + 2},{value + 2},{value + 2},{value + 2}\n" + (path.parent / "take_metrics.csv").write_text(header + rows, encoding="utf-8") + (path.parent / "per_hand_frame_metrics.csv").write_text( + header + rows, encoding="utf-8", + ) + + +def test_hot_scale_summary_uses_matched_final_control(tmp_path: Path) -> None: + root = tmp_path / "scale" + control = tmp_path / "control" + for condition, value, checkpoint_hash in ( + ("J40_HOT10K", 30.0, "a" * 64), + ("J40_HOT50K", 20.0, "b" * 64), + ): + for source in SOURCES: + write_report( + root / condition / "final505k" / source / "evaluation.json", + value, checkpoint_hash, + ) + for source in SOURCES: + write_report(control / source / "evaluation.json", 10.0, "c" * 64) + registry = { + "official_test_used": False, + "conditions": [ + {"condition": "J40_HOT10K"}, {"condition": "J40_HOT50K"}, + ], + "sources": [ + {"id": source, "cache_manifest_sha256": "d" * 64} + for source in SOURCES + ], + } + result = summarize(registry, root, control) + assert len(result["rows"]) == 21 + ten = next( + row for row in result["rows"] + if row["condition"] == "J40_HOT10K" and row["source_id"] == "hot3d_rgb_k" + ) + assert ten["delta_vs_hot100k"]["absolute_mpjpe_mm"] == 20.0 + paired = result["paired_recording_bootstrap_vs_hot100k"] + assert paired["J40_HOT10K"]["hot3d_rgb_k"]["absolute_mpjpe_mm"][ + "mean_delta" + ] == 20.0 + assert paired["J40_HOT50K"]["hot3d_rgb_k"]["translation_z_p95_mm"][ + "mean_delta" + ] == 10.0 + assert result["checkpoint_sha256"]["J40_HOT100K"] == "c" * 64 + assert result["official_test_used"] is False + + +def test_hot_scale_summary_rejects_wrong_evaluation_role(tmp_path: Path) -> None: + path = tmp_path / "evaluation.json" + report = evaluation(1.0, "a" * 64) + report["evaluation_role"] = "official_test" + path.write_text(json.dumps(report), encoding="utf-8") + with pytest.raises(ValueError, match="role/isolation"): + load_evaluation(path) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_candidate_admission_sync.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_candidate_admission_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..2429fdacd68c727f5f697f4b634d8f411bd20e04 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_candidate_admission_sync.py @@ -0,0 +1,5 @@ +from scripts.sync_phase9_last2_candidate_admission import NotReady + + +def test_last2_admission_wait_is_resumable() -> None: + assert issubclass(NotReady, RuntimeError) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_candidate_controller.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_candidate_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..0da4190602605545bc7bf107cf0a33580bc445ae --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_candidate_controller.py @@ -0,0 +1,42 @@ +import json +from pathlib import Path + +from scripts.run_phase9_last2_candidate_controller import admission +from scripts.run_phase9_resolution_evaluation_controller import should_launch +from scripts.run_phase9_unified_train_queue import sha256 + + +def test_5e7_admission_requires_stage8_strict_preceding_gate(tmp_path: Path) -> None: + report = tmp_path / "stage8.json" + report.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + "h2o_official_validation_used": False, + "stage9_preceding_mechanism_gate": {"stage9_last2_admitted": True}, + }), encoding="utf-8") + state = tmp_path / "state.json" + state.write_text(json.dumps({ + "status": "complete", "plan_sha256": "a" * 64, + "official_test_used": False, "h2o_official_validation_used": False, + "decision_report": {"path": str(report), "sha256": sha256(report)}, + }), encoding="utf-8") + plan = { + "candidate": "5e7", "admission_controller_state": str(state), + "admission_controller_plan_sha256": "a" * 64, + "admission_decision_report": str(report), + } + status, _, _ = admission(plan) + assert status == "admitted" + payload = json.loads(report.read_text(encoding="utf-8")) + payload["stage9_preceding_mechanism_gate"]["stage9_last2_admitted"] = False + report.write_text(json.dumps(payload), encoding="utf-8") + state_payload = json.loads(state.read_text(encoding="utf-8")) + state_payload["decision_report"]["sha256"] = sha256(report) + state.write_text(json.dumps(state_payload), encoding="utf-8") + status, _, _ = admission(plan) + assert status == "rejected" + + +def test_last2_controller_never_launches_external_evaluation_worker() -> None: + worker = {"owner": "server_new"} + assert not should_launch(worker, "taku3", "missing") + assert should_launch(worker, "server_new", "missing") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_decision.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..e122ffb1b7c6d0669b3da314f68be951ae9f999c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_decision.py @@ -0,0 +1,13 @@ +from scripts.summarize_phase9_last2_decision import strict_gate + + +def test_last2_gate_requires_strict_macro_and_worst_gain() -> None: + control = {"h2o": 30.0, "hot3d": 50.0, "hoi4d": 28.0, "arctic": 35.0} + passed = strict_gate( + control, {"h2o": 29.0, "hot3d": 49.9, "hoi4d": 27.0, "arctic": 34.0}, + ) + assert passed["accepted"] + stable_worst = strict_gate( + control, {"h2o": 20.0, "hot3d": 50.0, "hoi4d": 20.0, "arctic": 20.0}, + ) + assert not stable_worst["accepted"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_distributed_completion_arm.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_distributed_completion_arm.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d058cc18004c508511f67254520748f7d77fd8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_distributed_completion_arm.py @@ -0,0 +1,5 @@ +from scripts.arm_phase9_last2_distributed_completion import remote_conditions + + +def test_last2_remote_condition_count_is_enforced() -> None: + assert callable(remote_conditions) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_evaluation_plan.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..5e56a7118a351ced3af5ffa97d8a70c4400b2af1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_evaluation_plan.py @@ -0,0 +1,14 @@ +from scripts.build_phase9_last2_evaluation_plan import validate_control_plan + + +def test_last2_control_plan_validator_is_exposed() -> None: + assert callable(validate_control_plan) + + +def test_last2_plan_builder_includes_progress_supervision() -> None: + import inspect + from scripts.build_phase9_last2_evaluation_plan import build_plan + + source = inspect.getsource(build_plan) + assert '"worker_heartbeat_seconds": 30' in source + assert '"max_attempts_per_evaluation": 2' in source diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_finalizer.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_finalizer.py new file mode 100644 index 0000000000000000000000000000000000000000..02a8a25a1920d67c6209ca54320a593db860b2fe --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_finalizer.py @@ -0,0 +1,136 @@ +import json +from pathlib import Path + +import pytest + +from scripts.finalize_phase9_last2 import ( + build_final_report, + candidate_result, + validate_plan, +) +from scripts.run_phase9_unified_train_queue import sha256 + + +def write_candidate( + root: Path, candidate: str, *, admitted: bool, accepted: bool, + gpu_hours: float = 0.0, +) -> tuple[dict, dict]: + report_path = root / f"{candidate}_report.json" + report_path.write_text(json.dumps({ + "schema_version": "phase9_last2_candidate_decision_v1", + "status": "complete", "candidate": candidate, + "decision": f"accept_{candidate}" if accepted else f"reject_{candidate}", + "gate": { + "macro_strictly_improved": accepted, + "worst_domain_strictly_improved": accepted, + "accepted": accepted, + }, + "candidate_training_gpu_hours": gpu_hours, + "candidate_training_jobs": ( + {"full": {"checkpoint_sha256": "a" * 64}} if admitted else None + ), + "official_test_used": False, + "h2o_official_validation_used": False, + }), encoding="utf-8") + plan_path = root / f"{candidate}_plan.json" + plan_path.write_text("{}", encoding="utf-8") + state_path = root / f"{candidate}_state.json" + state_path.write_text(json.dumps({ + "status": "complete", "candidate": candidate, + "plan_sha256": sha256(plan_path), "admitted": admitted, + "decision_report": { + "path": str(report_path), "sha256": sha256(report_path), + }, + "official_test_used": False, + "h2o_official_validation_used": False, + }), encoding="utf-8") + spec = { + "plan": str(plan_path), "plan_sha256": sha256(plan_path), + "state": str(state_path), "report": str(report_path), + } + status, state, report = candidate_result(candidate, spec) + assert status == "complete" + assert state is not None and report is not None + return state, report + + +@pytest.mark.parametrize( + ("five", "one", "expected"), + [ + ((True, True), (True, True), "last2_1e6"), + ((True, True), (True, False), "last2_5e7"), + ((False, False), (False, False), "preceding_mechanism"), + ], +) +def test_finalizer_preserves_ordered_gate( + tmp_path: Path, five: tuple[bool, bool], one: tuple[bool, bool], + expected: str, +) -> None: + plan = { + "candidate_order": ["5e7", "1e6"], + "selection_rule": "retain_preceding_then_5e7_then_1e6_only_on_each_strict_gate", + "candidates": { + "5e7": {"report": str(tmp_path / "5e7_report.json")}, + "1e6": {"report": str(tmp_path / "1e6_report.json")}, + }, + } + results = { + "5e7": write_candidate( + tmp_path, "5e7", admitted=five[0], accepted=five[1], gpu_hours=7.0, + ), + "1e6": write_candidate( + tmp_path, "1e6", admitted=one[0], accepted=one[1], gpu_hours=11.0, + ), + } + report = build_final_report(plan, results) + assert report["selected"] == expected + assert report["official_test_used"] is False + assert report["dino_large_admitted"] is False + assert report["total_candidate_training_gpu_hours"] == 18.0 + if expected == "preceding_mechanism": + assert report["selected_candidate_training_jobs"] is None + else: + assert report["selected_candidate_training_jobs"]["full"][ + "checkpoint_sha256" + ] == "a" * 64 + + +def test_finalizer_rejects_impossible_1e6_acceptance(tmp_path: Path) -> None: + plan = { + "candidate_order": ["5e7", "1e6"], + "selection_rule": "retain_preceding_then_5e7_then_1e6_only_on_each_strict_gate", + "candidates": { + "5e7": {"report": str(tmp_path / "5e7_report.json")}, + "1e6": {"report": str(tmp_path / "1e6_report.json")}, + }, + } + results = { + "5e7": write_candidate(tmp_path, "5e7", admitted=False, accepted=False), + "1e6": write_candidate(tmp_path, "1e6", admitted=True, accepted=True), + } + with pytest.raises(ValueError, match="cannot be accepted"): + build_final_report(plan, results) + + +def test_candidate_result_rejects_accepted_without_both_strict_gates( + tmp_path: Path, +) -> None: + state, report = write_candidate(tmp_path, "5e7", admitted=True, accepted=True) + report_path = tmp_path / "5e7_report.json" + report["gate"]["worst_domain_strictly_improved"] = False + report_path.write_text(json.dumps(report), encoding="utf-8") + state_path = tmp_path / "5e7_state.json" + state["decision_report"]["sha256"] = sha256(report_path) + state_path.write_text(json.dumps(state), encoding="utf-8") + spec = { + "plan": str(tmp_path / "5e7_plan.json"), + "plan_sha256": sha256(tmp_path / "5e7_plan.json"), + "state": str(state_path), "report": str(report_path), + } + status, _, _ = candidate_result("5e7", spec) + assert status == "failed" + + +def test_checked_in_finalizer_plan_is_hash_bound() -> None: + plan_path = Path("artifacts/phase9/registry/last2_finalizer_plan.json") + validate_plan(json.loads(plan_path.read_text(encoding="utf-8"))) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_training_completion.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..9d21d16c8e14a290a3dadefa5c02e8f3d6eab14d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_training_completion.py @@ -0,0 +1,11 @@ +from scripts.sync_phase9_last2_training_completion import central_ready + + +def test_last2_training_completion_is_candidate_bound(tmp_path) -> None: + state = tmp_path / "state.json" + state.write_text('{"status":"complete","candidate":"5e7","training_registry_sha256":"a","official_test_used":false}') + plan = {"training_completion_state": str(state), "candidate": "5e7", + "training_registry": {"sha256": "a"}} + assert central_ready(plan) + plan["candidate"] = "1e6" + assert not central_ready(plan) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_training_registry.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1e51158eaeddf38161691ca80fc175d59fadee --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_last2_training_registry.py @@ -0,0 +1,55 @@ +from scripts.build_phase9_last2_training_registry import ( + derive_last2_config, + validate_matched_last2, +) + + +def phase9_shared_test_config() -> dict: + sources = [] + for dataset, weight, dropout in ( + ("H2O", 0.25, 0.0), ("HOT3D", 0.25, 0.3), + ("HOI4D", 0.25, 0.0), ("ARCTIC", 0.25, 0.0), + ): + sources.append({ + "dataset": dataset, "source_id": dataset, + "split_role": "official_train" if dataset == "H2O" else "external_train", + "weight": weight, "K_input_dropout": dropout, + "cache_manifest": f"/cache/{dataset}/manifest.jsonl", + }) + return { + "name": "control", "seed": 20260717, + "experiment": { + "phase": 9, "branch": "phase9_unified", "condition": "J25", + "uses_h2o_training_data": True, + "initialization_checkpoint_sha256": "a" * 64, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }, + "data": { + "resolution_hw": [368, 640], "T": 8, "batch_size": 1, + "photometric_augmentation": {"enabled": True}, "sources": sources, + }, + "model": { + "encoder": "dinov3", "dinov3_trainable_last_blocks": 0, + "decoder_mode": "alternating", "use_temporal": True, + "translation_parameterization": "direct_xyz", + "temporal_attention_mode": "bidirectional", + }, + "loss": {"joint3d_root_relative": 10.0}, + "assets": {"dinov3_source": "x", "dinov3_weights": "y", "mano_root": "z"}, + "precision": "bf16", + "protocol": {"max_steps": 405000, "learning_rate": 5e-5}, + } + + +def test_last2_5e7_changes_only_two_blocks_and_backbone_lr() -> None: + base = phase9_shared_test_config() + derived = derive_last2_config( + base, condition="S9L5_J25_full", candidate="5e7", + resolution_hw=[368, 640], shared_augmentation=False, + stage8_decision_sha256="a" * 64, + ) + validate_matched_last2(base, derived, "5e7") + assert derived["model"]["dinov3_trainable_last_blocks"] == 2 + assert derived["protocol"]["backbone_learning_rate"] == 5e-7 + assert derived["data"] == base["data"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_audit.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..2d5a65ef354025026be02080c33b64672a2e4c1c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_audit.py @@ -0,0 +1,62 @@ +import hashlib +import json +from pathlib import Path + +import numpy as np + +from scripts.audit_phase9_resolution_cache import ( + EXPECTED_HW, + audit_payload, + source_index_digest, +) + + +def test_source_index_digest_is_order_sensitive() -> None: + first = [{"source_clip_index": 1}, {"source_clip_index": 2}] + second = list(reversed(first)) + assert source_index_digest(first) != source_index_digest(second) + + +def test_resolution_payload_audits_geometry_and_depth(tmp_path: Path) -> None: + time = 8 + xyz = np.zeros((time, 2, 21, 3), dtype=np.float32) + xyz[..., 2] = 1.0 + intrinsics = np.repeat(np.eye(3, dtype=np.float32)[None], time, axis=0) + intrinsics[:, 0, 0] = 500.0 + intrinsics[:, 1, 1] = 500.0 + intrinsics[:, 0, 2] = 448.0 + intrinsics[:, 1, 2] = 256.0 + joint2d = np.zeros((time, 2, 21, 2), dtype=np.float32) + joint2d[..., 0] = 448.0 + joint2d[..., 1] = 256.0 + path = tmp_path / "clip.npz" + np.savez_compressed( + path, + image_hw=np.asarray(EXPECTED_HW), + rgb_u8=np.zeros((time, *EXPECTED_HW, 3), dtype=np.uint8), + depth_m=np.ones((time, 1, *EXPECTED_HW), dtype=np.float32), + depth_pixel_valid=np.ones((time, 1, *EXPECTED_HW), dtype=bool), + K=intrinsics, + joint3d_camera=xyz, + joint3d_valid=np.ones((time, 2, 21), dtype=bool), + joint2d=joint2d, + reprojection_valid=np.ones((time, 2, 21), dtype=bool), + ) + result = audit_payload(path) + assert result["projection_error_max_px"] == 0.0 + assert result["depth_valid_fraction"] == 1.0 + + +def test_resolution_payload_rejects_upsampled_640_shape(tmp_path: Path) -> None: + path = tmp_path / "clip.npz" + np.savez_compressed( + path, + image_hw=np.asarray((368, 640)), + rgb_u8=np.zeros((8, 368, 640, 3), dtype=np.uint8), + ) + try: + audit_payload(path) + except ValueError as error: + assert "resolution differs" in str(error) + else: + raise AssertionError("640 payload was accepted as a 896 cache") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_finalize.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_finalize.py new file mode 100644 index 0000000000000000000000000000000000000000..a12aa6a08e2cfab80dc599e5a1f2f58f6d6bfb26 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_finalize.py @@ -0,0 +1,64 @@ +import hashlib +import json +from pathlib import Path + +from scripts.finalize_phase9_resolution_cache import ( + inspect_workers, + validate_existing_completion, +) + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_workers_must_share_plan_and_winner_bindings(tmp_path: Path) -> None: + plan_path = tmp_path / "plan.json" + plan_path.write_text("{}\n", encoding="utf-8") + admission_path = tmp_path / "admission.json" + admission_path.write_text("{}\n", encoding="utf-8") + worker_path = tmp_path / "worker.json" + winner = {"id": "winner"} + checkpoint = {"path": "/checkpoint", "sha256": "a" * 64} + config = {"path": "/config", "sha256": "b" * 64} + worker_path.write_text(json.dumps({ + "status": "complete", + "worker": "h2o", + "plan_sha256": digest(plan_path), + "official_test_used": False, + "h2o_official_validation_used": False, + "winner": winner, + "winner_checkpoint": checkpoint, + "winner_config": config, + "admission_state_sha256": digest(admission_path), + }), encoding="utf-8") + plan = { + "admission_state": str(admission_path), + "workers": [{"id": "h2o", "state": str(worker_path)}], + } + admission = { + "winner": winner, + "winner_checkpoint": checkpoint, + "winner_config": config, + } + status, records = inspect_workers(plan_path, plan, admission) + assert status == "complete" + assert records[0]["state_sha256"] == digest(worker_path) + + +def test_completed_readiness_is_bound_to_audit(tmp_path: Path) -> None: + plan_path = tmp_path / "plan.json" + plan_path.write_text("{}\n", encoding="utf-8") + audit_path = tmp_path / "audit.json" + audit_path.write_text('{"status":"complete"}\n', encoding="utf-8") + plan = {"audit_output": str(audit_path)} + state = { + "status": "complete", + "plan_sha256": digest(plan_path), + "official_test_used": False, + "h2o_official_validation_used": False, + "audit": {"sha256": digest(audit_path)}, + } + assert validate_existing_completion(plan_path, plan, state) + audit_path.write_text("{}\n", encoding="utf-8") + assert not validate_existing_completion(plan_path, plan, state) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..88cc7452023762772056e40fe7f08c319076f05a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_queue.py @@ -0,0 +1,43 @@ +import json +from pathlib import Path + +from scripts.run_phase9_resolution_cache_queue import ( + cache_step_complete, + runtime_command, +) + + +def test_partial_cache_uses_resume_command(tmp_path: Path) -> None: + output = tmp_path / "cache" + step = { + "kind": "cache", "output_dir": str(output), + "start_command": ["writer", "--new"], + "resume_command": ["writer", "--resume"], + } + assert runtime_command(step) == ["writer", "--new"] + output.mkdir() + assert runtime_command(step) == ["writer", "--resume"] + + +def test_cache_completion_requires_896_resume_and_hashes(tmp_path: Path) -> None: + manifest = tmp_path / "cache_manifest.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + import hashlib + manifest_hash = hashlib.sha256(manifest.read_bytes()).hexdigest() + report = tmp_path / "cache_report.json" + report.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + "resolution_hw": [512, 896], "resume_invocation": True, + "cached_clips": 1, + "source_manifest": {"sha256": "a" * 64}, + "cache_manifest": {"sha256": manifest_hash}, + }), encoding="utf-8") + step = { + "report": str(report), "manifest": str(manifest), + "source_manifest_sha256": "a" * 64, "expected_clips": 1, + } + assert cache_step_complete(step, require_resume=True) + payload = json.loads(report.read_text(encoding="utf-8")) + payload["resolution_hw"] = [368, 640] + report.write_text(json.dumps(payload), encoding="utf-8") + assert not cache_step_complete(step, require_resume=True) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_supervisor.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_supervisor.py new file mode 100644 index 0000000000000000000000000000000000000000..d1b51b3cacbb9c79922fbb4b632de534aab25341 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_cache_supervisor.py @@ -0,0 +1,42 @@ +import json +from pathlib import Path + +from scripts.run_phase9_resolution_cache_supervisor import ( + alarms_for, + classify_failure, + latest_progress, + process_matches, +) + + +def test_contract_mismatch_is_terminal_not_resumable() -> None: + state = {"status": "failed_resumable", "failure": {"returncode": 0}} + assert classify_failure(state, {-9, -15, 137, 143}) == "terminal_contract_mismatch" + + +def test_only_registered_transient_returncode_is_resumable() -> None: + state = {"status": "failed_resumable", "failure": {"returncode": 143}} + assert classify_failure(state, {143}) == "known_transient_resumable" + assert classify_failure(state, {-9}) == "terminal_unregistered_resumable" + + +def test_latest_progress_ignores_non_json_lines(tmp_path: Path) -> None: + log = tmp_path / "worker.log" + log.write_text( + "warning\n" + json.dumps({"processed": 41, "cached": 40}) + "\ntrace\n", + encoding="utf-8", + ) + assert latest_progress(log) == {"processed": 41, "cached": 40} + + +def test_running_worker_without_controller_or_fresh_log_alerts() -> None: + workers = [{ + "id": "arctic", "status": "running", "classification": "not_failed", + "controller_pids": [], "log_mtime_age_seconds": 901, + }] + reasons = {item["reason"] for item in alarms_for(workers, log_stale_seconds=900)} + assert reasons == {"running_state_without_controller", "stale_progress_log"} + + +def test_process_match_requires_every_token() -> None: + assert process_matches(["definitely-not-a-real-process-token-92745"]) == [] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_decision.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..3c126214d425812d917cb103fc3702142a8d7e08 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_decision.py @@ -0,0 +1,19 @@ +from scripts.summarize_phase9_resolution_decision import gate_decision + + +def test_resolution_gate_requires_macro_gain_and_caps_worst_regression() -> None: + control = {"h2o": 30.0, "hot3d": 50.0, "hoi4d": 28.0, "arctic": 35.0} + accepted = gate_decision( + control, + {"h2o": 29.0, "hot3d": 50.4, "hoi4d": 27.0, "arctic": 34.0}, + 0.01, + ) + assert accepted["accepted"] + rejected_worst = gate_decision( + control, + {"h2o": 20.0, "hot3d": 50.6, "hoi4d": 20.0, "arctic": 20.0}, + 0.01, + ) + assert not rejected_worst["accepted"] + rejected_macro = gate_decision(control, dict(control), 0.01) + assert not rejected_macro["accepted"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_completion.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..20c8efbbf25dc8ccea812199fe0c78c51451bb2a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_completion.py @@ -0,0 +1,72 @@ +import json +from pathlib import Path + +import pytest + +from scripts.run_phase9_unified_train_queue import sha256 +from scripts.sync_phase9_resolution_evaluation_completion import ( + active_evaluator_pids, + remote_inventory, + verify_file, +) + + +def test_active_evaluator_detection_is_evaluation_id_exact(tmp_path: Path) -> None: + commands = { + "101": "python -m scripts.evaluate_phase7_external --evaluation-id fold_a", + "102": "python -m scripts.evaluate_phase7_external --evaluation-id fold_b", + "103": "python unrelated.py --evaluation-id fold_a", + } + for pid, command in commands.items(): + directory = tmp_path / pid + directory.mkdir() + (directory / "cmdline").write_bytes(command.replace(" ", "\0").encode()) + assert active_evaluator_pids("fold_a", tmp_path) == [101] + + +def test_result_file_hash_and_partial_transfer_are_rejected(tmp_path: Path) -> None: + item = {"path": "evaluations/fold/result.json", "bytes": 4, "sha256": "a" * 64} + with pytest.raises(ValueError, match="file differs"): + verify_file(tmp_path, item) + path = tmp_path / item["path"] + path.parent.mkdir(parents=True) + path.write_text("data", encoding="utf-8") + with pytest.raises(ValueError, match="file differs"): + verify_file(tmp_path, item) + item["sha256"] = sha256(path) + assert verify_file(tmp_path, item) == path + + +def test_remote_inventory_has_exact_owner_bound_ids(tmp_path: Path) -> None: + evaluations = [ + {"id": f"remote_{index}", "training_role": "loso_subject2"} + for index in range(9) + ] + [ + {"id": f"local_{index}", "training_role": "full"} + for index in range(16) + ] + workers = [ + { + "id": f"server_new_gpu{gpu}", "owner": "server_new", + "evaluation_ids": [f"remote_{index}" for index in range(gpu, 9, 4)], + } + for gpu in range(4) + ] + [ + {"id": f"taku3_gpu{gpu}", "owner": "taku3", "evaluation_ids": []} + for gpu in range(6) + ] + dynamic = { + "evaluations": evaluations, "workers": workers, + "official_test_used": False, "h2o_official_validation_used": False, + } + path = tmp_path / "plan.json" + path.write_text(json.dumps(dynamic), encoding="utf-8") + plan = {"evaluation_plan": {"path": str(path), "sha256": sha256(path)}} + observed, remote = remote_inventory(plan) + assert observed == dynamic + assert len(remote) == 4 + dynamic["evaluations"][0]["training_role"] = "full" + path.write_text(json.dumps(dynamic), encoding="utf-8") + plan["evaluation_plan"]["sha256"] = sha256(path) + with pytest.raises(ValueError, match="ownership differs"): + remote_inventory(plan) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_controller.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..2510bd09443734c5a46ae5347698812cadc0df0d --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_controller.py @@ -0,0 +1,42 @@ +import json +from pathlib import Path + +from scripts.run_phase9_resolution_evaluation_controller import ( + hard_failure, + should_launch, + training_complete, +) +from scripts.run_phase9_unified_train_queue import sha256 + + +def test_evaluation_controller_training_gate_is_hash_bound(tmp_path: Path) -> None: + registry = tmp_path / "registry.json" + registry.write_text("{}\n", encoding="utf-8") + state = tmp_path / "state.json" + state.write_text(json.dumps({ + "status": "complete", "plan_sha256": "a" * 64, + "official_test_used": False, "h2o_official_validation_used": False, + "training_registry": str(registry), + "training_registry_sha256": sha256(registry), + }), encoding="utf-8") + plan = { + "training_controller_state": str(state), + "training_controller_plan_sha256": "a" * 64, + } + assert training_complete(plan) + registry.write_text("changed\n", encoding="utf-8") + assert not training_complete(plan) + + +def test_evaluation_controller_restarts_only_resumable_failures() -> None: + assert not hard_failure("failed_resumable") + assert hard_failure("failed_state_binding") + + +def test_evaluation_controller_launches_only_locally_owned_workers() -> None: + worker = {"owner": "server_new"} + assert not should_launch(worker, "taku3", "missing") + assert should_launch(worker, "server_new", "missing") + assert should_launch(worker, "server_new", "failed_resumable") + assert not should_launch(worker, "server_new", "failed_state_binding") + assert not should_launch(worker, "server_new", "complete") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_metrics.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..15a9efb0037b9fda79d3e6af0521dac120f20ad7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_metrics.py @@ -0,0 +1,21 @@ +import pytest + +from scripts.summarize_phase9_resolution_evaluation_metrics import metric_values + + +def test_metric_inventory_includes_all_registered_resolution_fields() -> None: + report = {"metrics": { + "absolute_mpjpe_mm": {"mean": 1.0}, + "root_relative_mpjpe_mm": {"mean": 2.0}, + "pa_mpjpe_mm": {"mean": 3.0}, "mpvpe_mm": {"mean": 4.0}, + "fingertip_mpjpe_mm": {"mean": 5.0}, + "translation_x_mae_mm": {"mean": 6.0}, + "translation_y_mae_mm": {"mean": 7.0}, + "translation_z_mae_mm": {"mean": 8.0, "p95": 9.0}, + }} + values = metric_values(report) + assert values["pa_mpjpe_mm"] == 3.0 + assert values["translation_z_p95_mm"] == 9.0 + report["metrics"]["mpvpe_mm"]["mean"] = float("nan") + with pytest.raises(ValueError, match="nonfinite"): + metric_values(report) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_plan.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..a909ff784a55f5d517c03a468f97a70664f8fbc7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_plan.py @@ -0,0 +1,12 @@ +from scripts.build_phase9_resolution_evaluation_plan import ( + EXTERNAL_MODES, + H2O_MODES, +) + + +def test_resolution_evaluation_contract_has_exact_25_ids() -> None: + external = sum(len(modes) for modes in EXTERNAL_MODES.values()) + h2o = 6 * len(H2O_MODES) + assert external == 7 + assert h2o == 18 + assert external + h2o == 25 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_resource_recovery.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_resource_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..ce2805988fe02836a3925b3a0371bcb94c5bcaa9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_resource_recovery.py @@ -0,0 +1,33 @@ +from scripts.run_phase9_resolution_evaluation_resource_recovery import imported_state + + +def test_imported_recovery_state_preserves_original_plan_binding(tmp_path) -> None: + source = tmp_path / "recovery.json" + source.write_text("{}", encoding="utf-8") + amendment_path = tmp_path / "amendment.json" + amendment_path.write_text("{}", encoding="utf-8") + plan = tmp_path / "plan.json" + plan.write_text("{}", encoding="utf-8") + amendment = { + "worker": "server_new_gpu5", "owner": "server_new", + "evaluation_ids": ["a", "b"], "replacement_physical_gpu_id": 1, + "planned_physical_gpu_id": 5, "reason": "external_process", + "evaluation_plan": {"sha256": "a" * 64}, + "recovery_state": str(source), + } + recovery = { + "status": "complete", "worker": "server_new_gpu5", "owner": "server_new", + "assigned_evaluation_ids": ["a", "b"], "completed_ids": ["a", "b"], + "official_test_used": False, "h2o_official_validation_used": False, + } + value = imported_state(recovery, amendment_path, amendment, plan) + assert value["plan_sha256"] == "a" * 64 + assert value["physical_gpu_id"] == 1 + assert value["planned_physical_gpu_id"] == 5 + recovery["completed_ids"] = ["a"] + try: + imported_state(recovery, amendment_path, amendment, plan) + except ValueError: + pass + else: + raise AssertionError("partial recovery state was accepted") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_worker.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..06dc06ff8632589d618769c6365e59ca39c0304a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_evaluation_worker.py @@ -0,0 +1,113 @@ +import json +import os +from pathlib import Path + +from scripts.run_phase9_unified_train_queue import sha256 +from scripts.run_phase9_resolution_evaluation_worker import ( + evaluation_command, + evaluation_complete, + validate_progress_heartbeat, +) + + +def item(tmp_path: Path) -> dict: + return { + "id": "fold_rgb_d_k", "evaluation_role": "phase9_h2o_fold_heldout", + "input_mode": "rgb_d_k", "checkpoint": "/checkpoint.pt", + "checkpoint_sha256": "a" * 64, "config": "/config.yaml", + "config_sha256": "b" * 64, "cache_manifest": "/cache.jsonl", + "cache_manifest_sha256": "c" * 64, + "output_dir": str(tmp_path / "output"), + } + + +def test_evaluation_completion_checks_all_bindings(tmp_path: Path) -> None: + record = item(tmp_path) + output = Path(record["output_dir"]) + output.mkdir() + artifacts = {} + for name, contents in ( + ("raw_predictions.npz", b"raw"), + ("per_hand_frame_metrics.csv", b"metric\n1\n"), + ("take_metrics.csv", b"take\n1\n"), + ): + path = output / name + path.write_bytes(contents) + artifacts[name] = {"path": str(path), "sha256": sha256(path)} + (output / "evaluation.json").write_text(json.dumps({ + "status": "evaluated_phase9_h2o_fold_heldout", + "evaluation_role": record["evaluation_role"], + "input_mode": record["input_mode"], + "checkpoint": {"path": record["checkpoint"], "sha256": "a" * 64}, + "config": {"path": record["config"], "sha256": "b" * 64}, + "cache_manifest": {"path": record["cache_manifest"], "sha256": "c" * 64}, + "clips": 1, "frames": 8, + "raw_predictions": artifacts["raw_predictions.npz"], + "per_hand_rows": artifacts["per_hand_frame_metrics.csv"], + "take_metrics": artifacts["take_metrics.csv"], + "official_test_used": False, "h2o_official_validation_used": False, + }), encoding="utf-8") + assert evaluation_complete(record) + payload = json.loads((output / "evaluation.json").read_text(encoding="utf-8")) + payload["input_mode"] = "rgb_only" + (output / "evaluation.json").write_text(json.dumps(payload), encoding="utf-8") + assert not evaluation_complete(record) + + +def test_evaluation_completion_rejects_result_hash_mismatch(tmp_path: Path) -> None: + record = item(tmp_path) + output = Path(record["output_dir"]) + output.mkdir() + artifact = output / "artifact" + artifact.write_text("result", encoding="utf-8") + reference = {"path": str(artifact), "sha256": sha256(artifact)} + (output / "evaluation.json").write_text(json.dumps({ + "status": "evaluated_phase9_h2o_fold_heldout", + "evaluation_role": record["evaluation_role"], + "input_mode": record["input_mode"], + "checkpoint": {"path": record["checkpoint"], "sha256": "a" * 64}, + "config": {"path": record["config"], "sha256": "b" * 64}, + "cache_manifest": {"path": record["cache_manifest"], "sha256": "c" * 64}, + "clips": 1, "frames": 8, "raw_predictions": reference, + "per_hand_rows": reference, "take_metrics": reference, + "official_test_used": False, "h2o_official_validation_used": False, + }), encoding="utf-8") + assert evaluation_complete(record) + artifact.write_text("changed", encoding="utf-8") + assert not evaluation_complete(record) + + +def test_progress_heartbeat_is_exactly_bound(tmp_path: Path) -> None: + record = item(tmp_path) + path = tmp_path / "heartbeat.json" + value = { + "schema_version": "phase9_evaluation_progress_heartbeat_v1", + "evaluation_id": record["id"], "evaluator_pid": os.getpid(), + "output_dir": str(Path(record["output_dir"]).resolve()), + "official_test_used": False, "h2o_official_validation_used": False, + } + path.write_text(json.dumps(value), encoding="utf-8") + assert validate_progress_heartbeat(path, record, os.getpid()) == value + value["evaluation_id"] = "different" + path.write_text(json.dumps(value), encoding="utf-8") + try: + validate_progress_heartbeat(path, record, os.getpid()) + except ValueError: + pass + else: + raise AssertionError("mismatched heartbeat was accepted") + + +def test_gpu45_command_has_explicit_authorization(tmp_path: Path) -> None: + record = item(tmp_path) + assert "--allow-physical-gpus-4-5" in evaluation_command(record, 5) + assert "--allow-physical-gpus-4-5" not in evaluation_command(record, 3) + + +def test_evaluation_command_carries_progress_binding(tmp_path: Path) -> None: + record = item(tmp_path) + heartbeat = Path(record["output_dir"]) / "evaluation_heartbeat.json" + command = evaluation_command(record, 0, heartbeat, 30) + assert command[command.index("--evaluation-id") + 1] == record["id"] + assert command[command.index("--heartbeat-path") + 1] == str(heartbeat.resolve()) + assert command[command.index("--heartbeat-seconds") + 1] == "30" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_completion.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..18d16e1396a6930bf506213d943bd1e919583540 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_completion.py @@ -0,0 +1,173 @@ +import json +from pathlib import Path + +import pytest + +from scripts.run_phase9_unified_train_queue import sha256 +from scripts.sync_phase9_resolution_training_completion import ( + active_writer_pids, + install_release, + validate_condition_payload, + validate_global_completion_payload, + verify_record, + writer_matches, +) + + +REGISTRY_HASH = "a" * 64 + + +def valid_condition_payload() -> tuple[dict, dict, dict, dict, dict]: + condition = "S7R_J25_loso_subject2" + checkpoint = "/SSD2/root/final.pt" + config = "/SSD2/root/config.yaml" + expected = { + "condition": condition, + "training_registry_sha256": REGISTRY_HASH, + "checkpoint": checkpoint, + "checkpoint_sha256": "b" * 64, + } + job = { + "config": config, + "config_sha256": "c" * 64, + "expected_source_exposure_batches": {"H2O": 1}, + } + marker = { + "status": "complete", "stage": "matched_405000", + "completed_step": 405000, "checkpoint": checkpoint, + "checkpoint_sha256": "b" * 64, "config": config, + "config_sha256": "c" * 64, + "source_exposure_batches": {"H2O": 1}, + } + state = { + "status": "complete", "condition": condition, + "queue_sha256": REGISTRY_HASH, "official_test_used": False, + "completed_stages": ["smoke2", "health2k", "matched_405000"], + "attempts": [ + {"stage": "smoke2", "returncode": 0}, + {"stage": "health2k", "returncode": 0}, + {"stage": "matched_405000", "returncode": 0}, + ], + "last_completed": marker, + } + metric = {"step": 405000, "losses": {"total": 0.5, "pose": 0.2}} + summary = { + "status": "completed", "completed_step": 405000, + "protocol_max_steps": 405000, "registered_run_end_step": 405000, + "final_checkpoint": checkpoint, "final_checkpoint_sha256": "b" * 64, + "source_exposure_batches": {"H2O": 1}, "official_test_used": False, + } + return expected, job, state, metric, summary + + +def test_exact_terminal_condition_passes() -> None: + validate_condition_payload(*valid_condition_payload()) + + +@pytest.mark.parametrize("location", ["state", "marker", "metric", "summary"]) +def test_non_exact_terminal_step_is_rejected(location: str) -> None: + expected, job, state, metric, summary = valid_condition_payload() + if location == "state": + state["completed_stages"][-1] = "matched_404999" + elif location == "marker": + state["last_completed"]["completed_step"] = 404999 + elif location == "metric": + metric["step"] = 404999 + else: + summary["completed_step"] = 404999 + with pytest.raises(ValueError, match="terminal training evidence differs"): + validate_condition_payload(expected, job, state, metric, summary) + + +def test_nonfinite_terminal_loss_is_rejected() -> None: + expected, job, state, metric, summary = valid_condition_payload() + metric["losses"]["total"] = float("nan") + with pytest.raises(ValueError, match="terminal training evidence differs"): + validate_condition_payload(expected, job, state, metric, summary) + + +def test_writer_detection_is_output_exact(tmp_path: Path) -> None: + output = "/SSD2/run/subject2" + command = f"python -m scripts.train_phase7_external --output-dir {output}" + assert writer_matches(command, output) + assert not writer_matches(command, "/SSD2/run/subject3") + for pid, value in (("101", command), ("102", command), ("103", "python idle.py")): + directory = tmp_path / pid + directory.mkdir() + (directory / "cmdline").write_bytes(value.replace(" ", "\0").encode()) + assert active_writer_pids(output, tmp_path) == [101, 102] + + +def test_partial_transfer_and_hash_mismatch_are_rejected(tmp_path: Path) -> None: + item = {"path": "runs/final.pt", "bytes": 7, "sha256": "a" * 64} + with pytest.raises(ValueError, match="file differs"): + verify_record(tmp_path, item) + path = tmp_path / item["path"] + path.parent.mkdir(parents=True) + path.write_bytes(b"payload") + with pytest.raises(ValueError, match="file differs"): + verify_record(tmp_path, item) + item["sha256"] = sha256(path) + assert verify_record(tmp_path, item) == path + + +def test_partial_install_resumes_exact_existing_file( + tmp_path: Path, monkeypatch, +) -> None: + root = tmp_path / "root" + staging = tmp_path / "staging" + checkpoint = root / "runs/final.pt" + checkpoint.parent.mkdir(parents=True) + checkpoint.write_bytes(b"checkpoint") + state_source = staging / "queues/state.json" + state_source.parent.mkdir(parents=True) + state_source.write_bytes(b"state") + records = [ + {"kind": "checkpoint", "path": "runs/final.pt", "bytes": 10, + "sha256": sha256(checkpoint)}, + {"kind": "training_state", "path": "queues/state.json", "bytes": 5, + "sha256": sha256(state_source)}, + ] + plan = {"release_root": str(root), "staging_root": str(staging), + "source_host": "server_new"} + release = {"files": records} + monkeypatch.setattr( + "scripts.sync_phase9_resolution_training_completion.subprocess.run", + lambda *args, **kwargs: type("Result", (), {"returncode": 0})(), + ) + installed = install_release(plan, release) + assert (root / "queues/state.json").read_bytes() == b"state" + by_path = {item["path"]: item for item in installed} + assert by_path["runs/final.pt"]["resumed_existing"] is True + assert by_path["queues/state.json"]["resumed_existing"] is False + + +def valid_global_payload() -> tuple[dict, dict[str, dict]]: + conditions = { + "S7R_J25_full", "S7R_J25_loso_subject1", "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", "S7R_J25_lofamily_h", + "S7R_J25_lofamily_k", "S7R_J25_lofamily_o", + } + controller = { + "status": "complete", "machine": "taku3", + "training_registry_sha256": REGISTRY_HASH, + "condition_statuses": {condition: "complete" for condition in sorted(conditions)}, + "official_test_used": False, "h2o_official_validation_used": False, + } + states = { + condition: { + "status": "complete", "queue_sha256": REGISTRY_HASH, + "last_completed": {"completed_step": 405000}, + "official_test_used": False, + } + for condition in conditions + } + return controller, states + + +def test_cross_machine_completion_converges_only_with_all_seven() -> None: + controller, states = valid_global_payload() + validate_global_completion_payload(controller, REGISTRY_HASH, states) + states.pop("S7R_J25_lofamily_k") + with pytest.raises(ValueError, match="global resolution training completion differs"): + validate_global_completion_payload(controller, REGISTRY_HASH, states) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_controller.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..9b08a93c0a793f40846f13018f9e468afddcfc74 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_controller.py @@ -0,0 +1,38 @@ +import json +from pathlib import Path + +from scripts.run_phase9_resolution_training_controller import ( + condition_status, + hard_failure, + readiness_complete, +) +from scripts.run_phase9_unified_train_queue import sha256 + + +def test_controller_readiness_requires_bound_audit(tmp_path: Path) -> None: + audit = tmp_path / "audit.json" + audit.write_text("{}\n", encoding="utf-8") + state = tmp_path / "readiness.json" + state.write_text(json.dumps({ + "status": "complete", "plan_sha256": "a" * 64, + "official_test_used": False, "h2o_official_validation_used": False, + "audit": {"path": str(audit), "sha256": sha256(audit)}, + }), encoding="utf-8") + plan = { + "readiness_state": str(state), + "cache_execution_plan_sha256": "a" * 64, + } + assert readiness_complete(plan) + audit.write_text("changed\n", encoding="utf-8") + assert not readiness_complete(plan) + + +def test_condition_status_requires_registry_binding(tmp_path: Path) -> None: + state = tmp_path / "condition.json" + state.write_text(json.dumps({ + "status": "complete", "queue_sha256": "a" * 64, + }), encoding="utf-8") + assert condition_status(state, "a" * 64) == "complete" + assert condition_status(state, "b" * 64) == "failed_state_binding" + assert not hard_failure("failed_resumable") + assert hard_failure("failed_state_binding") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_handoff.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_handoff.py new file mode 100644 index 0000000000000000000000000000000000000000..d374b355f7001da32d51107634d180442d8be609 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_handoff.py @@ -0,0 +1,128 @@ +import pytest + +from scripts.sync_phase9_resolution_training_handoff import ( + ordered_handoff_files, + prepare_remote_parent, + validate_plan, +) + + +def valid_plan(tmp_path) -> dict: + binding = tmp_path / "binding" + binding.write_text("bound\n", encoding="utf-8") + from scripts.run_phase9_resolution_cache_queue import sha256 + + return { + "schema_version": + "phase9_resolution_distributed_training_handoff_amendment_v1", + "status": "frozen", + "source_owner": "taku3", + "destination_owner": "server_new", + "official_test_used": False, + "h2o_official_validation_used": False, + "readiness_published_last": True, + "immutable_sync": True, + "single_writer_per_output": True, + "live_reverse_sync_forbidden": True, + "server_new_physical_gpu_allowlist": [0, 1, 2, 5], + "external_owned_conditions": [ + "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", + "S7R_J25_lofamily_k", + ], + "scientific_contract": { + "amendment_scope": "resource_scheduling_and_immutable_handoff_only", + "model_changed": False, + "data_changed": False, + "seed_changed": False, + "optimizer_changed": False, + "horizon_changed": False, + "selection_gate_changed": False, + }, + "bindings": [{"path": str(binding), "sha256": sha256(binding)}], + } + + +def test_plan_accepts_scheduling_only_amendment(tmp_path) -> None: + validate_plan(valid_plan(tmp_path)) + + +@pytest.mark.parametrize("field", [ + "model_changed", "data_changed", "seed_changed", "optimizer_changed", + "horizon_changed", "selection_gate_changed", +]) +def test_plan_rejects_scientific_contract_change(tmp_path, field: str) -> None: + plan = valid_plan(tmp_path) + plan["scientific_contract"][field] = True + with pytest.raises(ValueError, match="contract differs"): + validate_plan(plan) + + +@pytest.mark.parametrize(("field", "value"), [ + ("server_new_physical_gpu_allowlist", [0, 1, 2, 3, 5]), + ("external_owned_conditions", ["S7R_J25_loso_subject2"]), + ("immutable_sync", False), + ("single_writer_per_output", False), + ("live_reverse_sync_forbidden", False), +]) +def test_plan_rejects_distributed_execution_contract_change( + tmp_path, field: str, value, +) -> None: + plan = valid_plan(tmp_path) + plan[field] = value + with pytest.raises(ValueError, match="contract differs"): + validate_plan(plan) + + +def test_readiness_is_published_last() -> None: + plan = {"files": [ + {"path": "/config", "role": "config"}, + {"path": "/audit", "role": "audit"}, + {"path": "/registry", "role": "registry"}, + {"path": "/readiness", "role": "readiness"}, + ]} + assert ordered_handoff_files(plan)[-1]["role"] == "readiness" + + +@pytest.mark.parametrize("files", [ + [{"path": "/readiness", "role": "readiness"}, {"path": "/config", "role": "config"}], + [{"path": "/readiness", "role": "readiness"}, {"path": "/readiness2", "role": "readiness"}], + [{"path": "/same", "role": "config"}, {"path": "/same", "role": "readiness"}], +]) +def test_unsafe_handoff_order_is_rejected(files: list[dict]) -> None: + with pytest.raises(ValueError): + ordered_handoff_files({"files": files}) + + +def test_prepare_remote_parent_uses_frozen_absolute_parent(monkeypatch) -> None: + calls = [] + + class Completed: + returncode = 0 + stderr = "" + + def fake_run(command, **kwargs): + calls.append((command, kwargs)) + return Completed() + + monkeypatch.setattr( + "scripts.sync_phase9_resolution_training_handoff.subprocess.run", fake_run, + ) + prepare_remote_parent("server_new", "/SSD2/example/configs/job.yaml") + assert calls[0][0] == [ + "ssh", "-o", "BatchMode=yes", "server_new", + "mkdir", "-p", "/SSD2/example/configs", + ] + + +def test_prepare_remote_parent_failure_is_terminal(monkeypatch) -> None: + class Completed: + returncode = 1 + stderr = "permission denied" + + monkeypatch.setattr( + "scripts.sync_phase9_resolution_training_handoff.subprocess.run", + lambda *args, **kwargs: Completed(), + ) + with pytest.raises(ValueError, match="permission denied"): + prepare_remote_parent("server_new", "/SSD2/example/configs/job.yaml") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_registry.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..2c902e0961c710f01adf812d779e3ac581228dd6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_resolution_training_registry.py @@ -0,0 +1,92 @@ +from pathlib import Path + +import torch + +from scripts.build_phase9_resolution_training_registry import ( + SOURCE_MANIFESTS, + checkpoint_metadata, + derive_config, + validate_matched_config, +) + + +def phase9_config() -> dict: + sources = [] + for dataset, weight, dropout in ( + ("H2O", 0.25, 0.0), ("HOT3D", 0.25, 0.3), + ("HOI4D", 0.25, 0.0), ("ARCTIC", 0.25, 0.0), + ): + sources.append({ + "dataset": dataset, "source_id": dataset, + "split_role": "official_train" if dataset == "H2O" else "external_train", + "weight": weight, "K_input_dropout": dropout, + "cache_manifest": f"/control/{dataset}/cache_manifest.jsonl", + }) + return { + "name": "control", "seed": 20260717, + "experiment": { + "phase": 9, "branch": "phase9_unified", "condition": "J25", + "uses_h2o_training_data": True, + "initialization_checkpoint_sha256": "a" * 64, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }, + "data": { + "resolution_hw": [368, 640], "T": 8, "batch_size": 1, + "photometric_augmentation": {"enabled": True}, "sources": sources, + }, + "model": {"encoder": "dinov3", "dinov3_trainable_last_blocks": 0}, + "loss": {"joint3d_root_relative": 10.0}, + "assets": {"dinov3_source": "x", "dinov3_weights": "y", "mano_root": "z"}, + "precision": "bf16", + "protocol": { + "max_steps": 405000, "learning_rate": 5e-5, + "source_exposure_milestones": [], + }, + } + + +def test_resolution_config_changes_only_stage_paths_and_horizon() -> None: + base = phase9_config() + derived = derive_config( + base, + condition="S7R_J25_full", + target_step=12345, + h2o_train_manifest=SOURCE_MANIFESTS["H2O"], + h2o_heldout_manifest=None, + winner="J25:all20", + winner_checkpoint_sha256="c" * 64, + ) + validate_matched_config(base, derived, 12345) + assert derived["data"]["resolution_hw"] == [512, 896] + assert { + source["dataset"]: source["cache_manifest"] + for source in derived["data"]["sources"] + } == SOURCE_MANIFESTS + assert derived["model"] == base["model"] + assert derived["loss"] == base["loss"] + assert derived["protocol"] == base["protocol"] + assert derived["protocol"]["max_steps"] == 405000 + + +def test_selected_checkpoint_metadata_binds_step_config_and_exposure( + tmp_path: Path, +) -> None: + path = tmp_path / "milestone_step_0012345.pt" + torch.save({ + "step": 12345, + "extra": { + "config_sha256": "a" * 64, + "official_test_used": False, + "source_exposure_batches": {"H2O": 10}, + "source_exposure_frames": {"H2O": 80}, + "external_initialization_checkpoint": { + "path": "/init.pt", "sha256": "b" * 64, "source_step": 1, + }, + }, + }, path) + import hashlib + digest = hashlib.sha256(path.read_bytes()).hexdigest() + metadata = checkpoint_metadata(path, digest, "a" * 64) + assert metadata["step"] == 12345 + assert metadata["source_exposure_batches"] == {"H2O": 10} diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_selection_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_selection_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..6464b93b0aee331197d44f6b899fe8af7fe460ac --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_selection_queue.py @@ -0,0 +1,37 @@ +import json +from pathlib import Path + +from scripts.run_phase9_selection_queue import ( + archive_incomplete_outputs, + evidence_complete, +) + + +def test_selection_evidence_requires_every_isolated_state(tmp_path: Path) -> None: + paths = [] + for index in range(3): + path = tmp_path / f"state{index}.json" + path.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + }), encoding="utf-8") + paths.append({"path": str(path)}) + plan = {"required_states": paths} + assert evidence_complete(plan) + Path(paths[1]["path"]).write_text(json.dumps({ + "status": "running", "official_test_used": False, + }), encoding="utf-8") + assert not evidence_complete(plan) + + +def test_selection_queue_archives_partial_output_pair(tmp_path: Path) -> None: + output_json = tmp_path / "selection.json" + output_csv = tmp_path / "selection.csv" + output_json.write_text("partial\n", encoding="utf-8") + state = tmp_path / "queue" / "state.json" + state.parent.mkdir() + archived = archive_incomplete_outputs({ + "output_json": str(output_json), "output_csv": str(output_csv), + }, state) + assert len(archived) == 1 + assert not output_json.exists() + assert Path(archived[0]).read_text(encoding="utf-8") == "partial\n" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_admission_sync.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_admission_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..5d594992ea73fe9dad12b03a479024752d9dcd97 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_admission_sync.py @@ -0,0 +1,15 @@ +from pathlib import Path + +from scripts.sync_phase9_shared_augmentation_admission import plan_path_from_state + + +def test_stage8_controller_state_plan_must_exist(tmp_path: Path) -> None: + plan = tmp_path / "plan.json" + plan.write_text("{}", encoding="utf-8") + assert plan_path_from_state({"plan": str(plan)}) == plan + try: + plan_path_from_state({"plan": str(tmp_path / "missing")}) + except ValueError: + pass + else: + raise AssertionError("missing Stage 8 plan was accepted") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_decision.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6760b7fca3ef91406c4c0846cbde218c7d6598 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_decision.py @@ -0,0 +1,27 @@ +from scripts.summarize_phase9_shared_augmentation_decision import ( + stage9_preceding_gate, +) + + +def test_stage9_gate_requires_strict_worst_improvement() -> None: + augmentation_gate = { + "macro_strictly_improved": True, + "control_worst_domain_absolute_mm": 50.0, + "candidate_worst_domain_absolute_mm": 50.1, + } + resolution = { + "decision": "accept_896x512", + "gate": { + "macro_strictly_improved": True, + "control_worst_domain_absolute_mm": 52.0, + "candidate_worst_domain_absolute_mm": 50.0, + }, + } + accepted_but_not_strict = stage9_preceding_gate( + True, augmentation_gate, resolution, + ) + assert not accepted_but_not_strict["stage9_last2_admitted"] + rejected_augmentation = stage9_preceding_gate( + False, augmentation_gate, resolution, + ) + assert rejected_augmentation["stage9_last2_admitted"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_admission.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..adf2ef539945bc4b8948b498d4bc23701d68668f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_admission.py @@ -0,0 +1,5 @@ +from scripts.sync_phase9_shared_augmentation_evaluation_admission import NotReady + + +def test_stage8_evaluation_waiting_is_not_terminal_failure() -> None: + assert issubclass(NotReady, RuntimeError) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_completion_arm.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_completion_arm.py new file mode 100644 index 0000000000000000000000000000000000000000..4f6f284060d497ddb5c4f445b027a4e08e1f3b3f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_completion_arm.py @@ -0,0 +1,5 @@ +from scripts.arm_phase9_shared_augmentation_evaluation_completion import utc_now + + +def test_stage8_completion_arm_uses_utc_timestamp() -> None: + assert "+00:00" in utc_now() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_controller.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c359332c136444ea9de4f34760d59164dde2f3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_controller.py @@ -0,0 +1,33 @@ +import json +from pathlib import Path + +from scripts.run_phase9_shared_augmentation_evaluation_controller import ( + training_complete, +) +from scripts.run_phase9_resolution_evaluation_controller import should_launch +from scripts.run_phase9_unified_train_queue import sha256 + + +def test_augmentation_evaluation_waits_for_bound_training(tmp_path: Path) -> None: + registry = tmp_path / "registry.json" + registry.write_text("{}\n", encoding="utf-8") + state = tmp_path / "state.json" + state.write_text(json.dumps({ + "status": "complete", "plan_sha256": "a" * 64, + "official_test_used": False, "h2o_official_validation_used": False, + "training_registry": str(registry), + "training_registry_sha256": sha256(registry), + }), encoding="utf-8") + plan = { + "training_controller_state": str(state), + "training_controller_plan_sha256": "a" * 64, + } + assert training_complete(plan) + registry.write_text("changed\n", encoding="utf-8") + assert not training_complete(plan) + + +def test_augmentation_controller_never_launches_external_worker() -> None: + worker = {"owner": "server_new"} + assert not should_launch(worker, "taku3", "missing") + assert should_launch(worker, "server_new", "failed_resumable") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_plan.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..25ba2c2ee9e5cb913e58c10e4a729e451b0db9e1 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_evaluation_plan.py @@ -0,0 +1,20 @@ +from scripts.build_phase9_shared_augmentation_evaluation_plan import ( + EXTERNAL_MODES, + H2O_MODES, +) + + +def test_shared_augmentation_evaluation_plan_has_25_ids() -> None: + assert sum(len(modes) for modes in EXTERNAL_MODES.values()) == 7 + assert 6 * len(H2O_MODES) == 18 + + +def test_shared_augmentation_uses_resolution_worker_supervision_contract() -> None: + source = __import__( + "inspect" + ).getsource(__import__( + "scripts.build_phase9_shared_augmentation_evaluation_plan", + fromlist=["build_plan"], + ).build_plan) + assert '"worker_heartbeat_seconds": 30' in source + assert '"stall_timeout_seconds": 900' in source diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_training_completion.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..9f7c1ca5869a4c545e6fa245ed0eb044bcbd2c62 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_training_completion.py @@ -0,0 +1,16 @@ +from scripts.sync_phase9_shared_augmentation_training_completion import EXPECTED, central_complete + + +def test_stage8_remote_owner_set_is_exact() -> None: + assert EXPECTED == ( + "S8A_J25_loso_subject2", "S8A_J25_loso_subject3", "S8A_J25_lofamily_k", + ) + + +def test_stage8_central_completion_is_registry_bound(tmp_path) -> None: + state = tmp_path / "state.json" + state.write_text('{"status":"complete","training_registry_sha256":"abc","official_test_used":false}') + plan = {"central_controller_state": str(state), "training_registry": {"sha256": "abc"}} + assert central_complete(plan) + plan["training_registry"]["sha256"] = "different" + assert not central_complete(plan) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_training_controller.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..c6966b4ec4472a2f1312485df8040f876b2688ed --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_training_controller.py @@ -0,0 +1,27 @@ +import json +from pathlib import Path + +from scripts.run_phase9_shared_augmentation_training_controller import ( + resolution_decision_complete, +) +from scripts.run_phase9_unified_train_queue import sha256 + + +def test_shared_augmentation_waits_for_bound_resolution_decision( + tmp_path: Path, +) -> None: + report = tmp_path / "decision.json" + report.write_text("{}\n", encoding="utf-8") + state = tmp_path / "state.json" + state.write_text(json.dumps({ + "status": "complete", "plan_sha256": "a" * 64, + "official_test_used": False, "h2o_official_validation_used": False, + "decision_report": {"path": str(report), "sha256": sha256(report)}, + }), encoding="utf-8") + plan = { + "resolution_controller_state": str(state), + "resolution_controller_plan_sha256": "a" * 64, + } + assert resolution_decision_complete(plan) + report.write_text("changed\n", encoding="utf-8") + assert not resolution_decision_complete(plan) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_training_registry.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..846f217d39f5f4dc3811f3ea43dfb71e69690f44 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_shared_augmentation_training_registry.py @@ -0,0 +1,57 @@ +from scripts.build_phase9_shared_augmentation_training_registry import ( + GEOMETRY_AUGMENTATION, + derive_augmentation_config, + validate_matched_augmentation, +) + + +def phase9_shared_test_config() -> dict: + sources = [] + for dataset, weight, dropout in ( + ("H2O", 0.25, 0.0), ("HOT3D", 0.25, 0.3), + ("HOI4D", 0.25, 0.0), ("ARCTIC", 0.25, 0.0), + ): + sources.append({ + "dataset": dataset, "source_id": dataset, + "split_role": "official_train" if dataset == "H2O" else "external_train", + "weight": weight, "K_input_dropout": dropout, + "cache_manifest": f"/cache/{dataset}/manifest.jsonl", + }) + return { + "name": "control", "seed": 20260717, + "experiment": { + "phase": 9, "branch": "phase9_unified", "condition": "J25", + "uses_h2o_training_data": True, + "initialization_checkpoint_sha256": "a" * 64, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }, + "data": { + "resolution_hw": [368, 640], "T": 8, "batch_size": 1, + "photometric_augmentation": {"enabled": True}, "sources": sources, + }, + "model": {"encoder": "dinov3", "dinov3_trainable_last_blocks": 0}, + "loss": {"joint3d_root_relative": 10.0}, + "assets": {"dinov3_source": "x", "dinov3_weights": "y", "mano_root": "z"}, + "precision": "bf16", + "protocol": {"max_steps": 405000, "learning_rate": 5e-5}, + } + + +def test_shared_augmentation_changes_only_frozen_input_transform() -> None: + base = phase9_shared_test_config() + derived = derive_augmentation_config( + base, condition="S8A_J25_full", resolution_hw=[368, 640], + resolution_decision_sha256="a" * 64, + ) + validate_matched_augmentation(base, derived, [368, 640]) + assert derived["data"]["geometry_augmentation"] == GEOMETRY_AUGMENTATION + probabilities = { + item["dataset"]: item["depth_corruption_probability"] + for item in derived["data"]["sources"] + } + assert probabilities == { + "H2O": 0.3, "HOT3D": 0.0, "HOI4D": 0.3, "ARCTIC": 0.0, + } + assert derived["model"] == base["model"] + assert derived["protocol"] == base["protocol"] diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_storage_overflow.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_storage_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..5decd970eaaca20bc00555918094ded163289155 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_storage_overflow.py @@ -0,0 +1,67 @@ +import hashlib +import json +from pathlib import Path + +import pytest + +from scripts.prepare_phase9_storage_overflow import bind_directory, prepare + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_bind_directory_is_idempotent_and_rejects_wrong_target(tmp_path: Path) -> None: + logical = tmp_path / "logical" / "condition" + physical = tmp_path / "physical" / "condition" + assert bind_directory(logical, physical) == "created" + assert bind_directory(logical, physical) == "existing_identical" + logical.unlink() + logical.symlink_to(tmp_path / "wrong", target_is_directory=True) + with pytest.raises(RuntimeError, match="wrong target"): + bind_directory(logical, physical) + + +def test_prepare_binds_only_allowlisted_registered_condition(tmp_path: Path) -> None: + logical_run = tmp_path / "logical_runs" / "condition_a" + registry = tmp_path / "registry.json" + registry.write_text(json.dumps({ + "official_test_used": False, + "conditions": [{"condition": "Condition_A", "output_dir": str(logical_run)}], + }), encoding="utf-8") + plan_path = tmp_path / "plan.json" + plan = { + "official_test_used": False, + "fold_training_registry": str(registry), + "fold_training_registry_sha256": digest(registry), + "conditions": ["Condition_A"], + "physical_root": str(tmp_path / "physical"), + "logical_evaluation_roots": { + "final": str(tmp_path / "final"), + "milestone": str(tmp_path / "milestone"), + }, + } + plan_path.write_text(json.dumps(plan), encoding="utf-8") + report = prepare(plan, plan_path) + assert len(report["bindings"]) == 3 + assert logical_run.is_symlink() + assert report["official_test_used"] is False + + +def test_prepare_rejects_registry_hash_drift(tmp_path: Path) -> None: + registry = tmp_path / "registry.json" + registry.write_text('{"official_test_used": false, "conditions": []}', encoding="utf-8") + plan_path = tmp_path / "plan.json" + plan_path.write_text("{}", encoding="utf-8") + plan = { + "official_test_used": False, + "fold_training_registry": str(registry), + "fold_training_registry_sha256": "0" * 64, + "conditions": [], "physical_root": str(tmp_path / "physical"), + "logical_evaluation_roots": { + "final": str(tmp_path / "final"), + "milestone": str(tmp_path / "milestone"), + }, + } + with pytest.raises(ValueError, match="hash mismatch"): + prepare(plan, plan_path) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_taku_cache_sync.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_taku_cache_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff6f2b48f90389433f9708b8af0c96eeee16cfe --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_taku_cache_sync.py @@ -0,0 +1,64 @@ +import json +from pathlib import Path + +import pytest + +from scripts.run_phase9_resolution_cache_queue import sha256 +from scripts.sync_phase9_taku_resolution_caches import ( + inventory_artifacts, + known_payload_hashes, + validate_release, +) + + +def test_inventory_uses_manifest_bound_payload_hash(tmp_path: Path) -> None: + root = tmp_path / "root" + artifact = root / "cache" + artifact.mkdir(parents=True) + payload = artifact / "clip.npz" + payload.write_bytes(b"payload") + manifest = artifact / "cache_manifest.jsonl" + manifest.write_text(json.dumps({ + "cache_path": str(payload.resolve()), "cache_sha256": sha256(payload), + }) + "\n", encoding="utf-8") + known = known_payload_hashes([str(manifest)]) + files, artifacts = inventory_artifacts( + root, [{"id": "cache", "path": str(artifact)}], known, + ) + by_path = {item["path"]: item for item in files} + assert by_path["cache/clip.npz"]["sha256"] == sha256(payload) + assert artifacts[0]["file_count"] == 2 + + +def test_conflicting_manifest_payload_hash_is_rejected(tmp_path: Path) -> None: + payload = tmp_path / "clip.npz" + payload.write_bytes(b"payload") + manifests = [] + for index, digest in enumerate(("a" * 64, "b" * 64)): + manifest = tmp_path / f"manifest{index}.jsonl" + manifest.write_text(json.dumps({ + "cache_path": str(payload.resolve()), "cache_sha256": digest, + }) + "\n", encoding="utf-8") + manifests.append(str(manifest)) + with pytest.raises(ValueError, match="conflicting"): + known_payload_hashes(manifests) + + +def test_release_rejects_duplicate_paths(tmp_path: Path) -> None: + plan_path = tmp_path / "plan.json" + plan_path.write_text("{}\n", encoding="utf-8") + plan = {"release_root": str(tmp_path / "root")} + release = { + "status": "complete_immutable_release", "owner": "taku3", + "destination_owner": "server_new", "plan_sha256": sha256(plan_path), + "release_root": str((tmp_path / "root").resolve()), + "read_only_after_publish": True, "live_reverse_sync_forbidden": True, + "official_test_used": False, "h2o_official_validation_used": False, + "files": [ + {"path": "cache/a", "bytes": 1, "sha256": "a" * 64}, + {"path": "cache/a", "bytes": 1, "sha256": "a" * 64}, + ], + "file_count": 2, "total_bytes": 2, + } + with pytest.raises(ValueError, match="paths differ"): + validate_release(plan_path, plan, release) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_unified_selection.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_unified_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..88b1c3104a7a888f4206f96e35af3693ea6d69c2 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_unified_selection.py @@ -0,0 +1,66 @@ +import json + +from scripts.summarize_phase9_unified_selection import ( + evaluation, + pareto_frontier, + rank_values, + validate_multifold_index, +) + + +def test_rank_values_uses_average_tie_rank() -> None: + assert rank_values({"a": 1.0, "b": 1.0, "c": 3.0}) == { + "a": 1.5, "b": 1.5, "c": 3.0, + } + + +def test_pareto_frontier_excludes_strictly_dominated_candidate() -> None: + rows = [ + {"id": "a", "absolute_mm": {"h2o": 1.0, "hot": 2.0}}, + {"id": "b", "absolute_mm": {"h2o": 2.0, "hot": 3.0}}, + {"id": "c", "absolute_mm": {"h2o": 0.5, "hot": 4.0}}, + ] + assert pareto_frontier(rows, ("h2o", "hot")) == {"a", "c"} + + +def test_evaluation_rejects_official_validation_evidence(tmp_path) -> None: + path = tmp_path / "evaluation.json" + path.write_text(json.dumps({ + "status": "evaluated_phase9_h2o_fold_heldout", + "evaluation_role": "phase9_h2o_fold_heldout", + "official_test_used": False, + "h2o_official_validation_used": True, + }), encoding="utf-8") + try: + evaluation(path, "phase9_h2o_fold_heldout") + except ValueError as error: + assert "isolation mismatch" in str(error) + else: + raise AssertionError("official-validation evidence was accepted") + + +def test_multifold_index_requires_exact_train_only_six_fold_contract() -> None: + ids = [ + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + ] + index = { + "status": "complete", + "h2o_official_validation_used": False, + "official_test_used": False, + "selection_metrics": [ + "fold_macro_absolute_mpjpe", "worst_fold_absolute_mpjpe", + ], + "folds": [{ + "id": fold_id, + "heldout": {"path": f"{fold_id}.jsonl", "sha256": "a" * 64}, + } for fold_id in ids], + } + assert [fold["id"] for fold in validate_multifold_index(index)] == ids + index["h2o_official_validation_used"] = True + try: + validate_multifold_index(index) + except ValueError as error: + assert "contract differs" in str(error) + else: + raise AssertionError("official-validation multifold index was accepted") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_unified_train_queue.py b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_unified_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..414a3cbc7a2ca31bb876c1424110bc08519df5a9 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_phase9_unified_train_queue.py @@ -0,0 +1,126 @@ +import json +from pathlib import Path + +from scripts.run_phase9_unified_train_queue import ( + attempt_gpu_hours, + parse_physical_gpu_ids, + prerequisite_gate_satisfied, + readiness_complete, + latest_resumable_checkpoint, + prerequisite_states_complete, + sha256, + state_lock_path, + training_command, +) + + +def test_attempt_gpu_hours_includes_recovery_attempts() -> None: + attempts = [ + {"start_utc": "2026-01-01T00:00:00+00:00", "end_utc": "2026-01-01T01:00:00+00:00"}, + {"start_utc": "2026-01-01T01:00:00+00:00", "end_utc": "2026-01-01T01:30:00+00:00"}, + ] + assert attempt_gpu_hours(attempts) == 1.5 + + +def test_physical_gpu_override_accepts_all_server_gpus() -> None: + assert parse_physical_gpu_ids("3,4,5") == (3, 4, 5) + + +def test_state_lock_is_bound_to_exact_condition_state(tmp_path: Path) -> None: + state = tmp_path / "fold_jobs" / "j55_loso_subject1.json" + assert state_lock_path(state) == Path(f"{state}.lock") + + +def test_training_command_uses_external_init_then_exact_resume() -> None: + queue = { + "config": "/config.yaml", "output_dir": "/run", + "initialization_checkpoint": "/g200.pt", + } + stage = {"stop_after_step": 2} + initial = training_command(queue, stage, 1, None) + assert initial[-2:] == ["--init-checkpoint", "/g200.pt"] + resumed = training_command(queue, {"stop_after_step": 2000}, 2, Path("/run/step.pt")) + assert resumed[-2:] == ["--resume", "/run/step.pt"] + assert resumed[resumed.index("--physical-gpu-id") + 1] == "2" + gpu4 = training_command(queue, stage, 4, None) + assert "--allow-physical-gpus-4-5" in gpu4 + assert "--allow-physical-gpus-4-5" not in initial + + +def test_latest_periodic_checkpoint_resumes_without_repeating_stage( + tmp_path: Path, +) -> None: + output = tmp_path / "run" + output.mkdir() + previous = output / "step_0002000_final.pt" + previous.write_bytes(b"health") + (output / "step_0010000.pt").write_bytes(b"ten") + latest = output / "step_0020000.pt" + latest.write_bytes(b"twenty") + (output / "step_0030000_final.pt").write_bytes(b"target") + assert latest_resumable_checkpoint( + {"output_dir": str(output)}, {"stop_after_step": 30000}, previous, + ) == latest + + +def test_readiness_requires_hash_bound_complete_artifacts(tmp_path: Path) -> None: + manifest = tmp_path / "manifest.jsonl" + manifest.write_text("{}\n", encoding="utf-8") + state = tmp_path / "state.json" + state.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + "plan_sha256": "a" * 64, + "artifacts": [{ + "manifest": str(manifest), "manifest_sha256": sha256(manifest), + }], + }), encoding="utf-8") + queue = { + "data_readiness_state": str(state), + "data_finalize_plan_sha256": "a" * 64, + "data_readiness_state_sha256": sha256(state), + "data_artifacts": [{"path": str(manifest), "sha256": sha256(manifest)}], + } + assert readiness_complete(queue) + manifest.write_text("changed\n", encoding="utf-8") + assert not readiness_complete(queue) + + +def test_optional_readiness_state_hash_fails_closed(tmp_path: Path) -> None: + state = tmp_path / "state.json" + state.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + "plan_sha256": "a" * 64, + }), encoding="utf-8") + queue = { + "data_readiness_state": str(state), + "data_finalize_plan_sha256": "a" * 64, + "data_readiness_state_sha256": sha256(state), + } + assert readiness_complete(queue) + payload = json.loads(state.read_text(encoding="utf-8")) + payload["updated_utc"] = "later" + state.write_text(json.dumps(payload), encoding="utf-8") + assert not readiness_complete(queue) + + +def test_optional_prerequisite_states_fail_closed(tmp_path: Path) -> None: + assert prerequisite_states_complete({}) + state = tmp_path / "main.json" + state.write_text(json.dumps({ + "status": "running", "official_test_used": False, + }), encoding="utf-8") + registry = {"prerequisite_states": [{"path": str(state)}]} + assert not prerequisite_states_complete(registry) + assert not prerequisite_gate_satisfied( + registry, start_before_prerequisites=False, + ) + assert prerequisite_gate_satisfied( + registry, start_before_prerequisites=True, + ) + state.write_text(json.dumps({ + "status": "complete", "official_test_used": False, + }), encoding="utf-8") + assert prerequisite_states_complete(registry) + assert prerequisite_gate_satisfied( + registry, start_before_prerequisites=False, + ) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_procrustes.py b/home/wuyifan/EgoNet_train_20261008/tests/test_procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..8bab135a9f5fcfd7b304d177377c8feaee1f71f8 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_procrustes.py @@ -0,0 +1,25 @@ +import numpy as np + +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm + + +def test_rigid_and_similarity_alignment_remove_registered_transforms() -> None: + rng = np.random.default_rng(20260717) + target = rng.normal(size=(3, 21, 3)) * 0.03 + angle = 0.7 + rotation = np.asarray([ + [np.cos(angle), -np.sin(angle), 0.0], + [np.sin(angle), np.cos(angle), 0.0], + [0.0, 0.0, 1.0], + ]) + predicted_rigid = target @ rotation + np.asarray([0.2, -0.1, 0.6]) + assert aligned_mpjpe_mm( + predicted_rigid, target, estimate_scale=False, + ).max() < 1e-10 + predicted_similarity = 1.7 * target @ rotation + np.asarray([0.2, -0.1, 0.6]) + assert aligned_mpjpe_mm( + predicted_similarity, target, estimate_scale=True, + ).max() < 1e-10 + assert aligned_mpjpe_mm( + predicted_similarity, target, estimate_scale=False, + ).mean() > 1.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_profile_phase5_alignment_solver.py b/home/wuyifan/EgoNet_train_20261008/tests/test_profile_phase5_alignment_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f91e970cf5c3fbbbdd5a29dd173e5142d7cae3 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_profile_phase5_alignment_solver.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +import numpy as np +import pytest + +from scripts.profile_phase5_alignment_solver import latency_summary + + +def test_alignment_latency_summary() -> None: + result = latency_summary([2.0, 4.0, 6.0, 8.0]) + assert result["frames"] == 4 + assert result["mean_ms"] == pytest.approx(5.0) + assert result["p50_ms"] == pytest.approx(5.0) + assert result["throughput_frames_per_second"] == pytest.approx(200.0) + with pytest.raises(ValueError, match="finite"): + latency_summary([np.inf]) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_profile_phase5_model.py b/home/wuyifan/EgoNet_train_20261008/tests/test_profile_phase5_model.py new file mode 100644 index 0000000000000000000000000000000000000000..8c25cc2ecf400d4b438d2477a85543c5ee5bdfa6 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_profile_phase5_model.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +import numpy as np +import pytest +import torch + +from scripts.profile_phase5_model import parameter_counts, percentile_summary + + +def test_parameter_counts_separate_trainable_and_frozen() -> None: + model = torch.nn.Sequential(torch.nn.Linear(2, 3), torch.nn.Linear(3, 1)) + model[1].requires_grad_(False) + counts = parameter_counts(model) + assert counts == {"trainable": 9, "frozen": 4, "total": 13} + + +def test_latency_percentiles_are_finite() -> None: + result = percentile_summary([1.0, 2.0, 3.0, 4.0]) + assert result["iterations"] == 4 + assert result["mean_ms"] == pytest.approx(2.5) + assert result["p50_ms"] == pytest.approx(2.5) + with pytest.raises(ValueError, match="finite"): + percentile_summary([np.nan]) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_render_best_worst_video_cases.py b/home/wuyifan/EgoNet_train_20261008/tests/test_render_best_worst_video_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..2ece19eb6f1cc2f9455e528108c16e736b1ebb7e --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_render_best_worst_video_cases.py @@ -0,0 +1,74 @@ +from pathlib import Path + +import pytest + +from scripts.render_best_worst_video_cases import ( + LEFT_COLOR_RGB, + RIGHT_COLOR_RGB, + case_directory_name, + rank_video_sequences, + source_frame_ids, +) + + +def rows_for_take(take_index: int, error: float, *, valid: bool = True): + rows = [] + for frame_id in range(100, 108): + for side in ("left", "right"): + rows.append({ + "clip_index": str(take_index), + "time_index": str(frame_id - 100), + "frame_id": str(frame_id), + "side": side, + "annotation_valid": "1" if valid else "0", + "absolute_mpjpe_mm": str(error), + "root_relative_mpjpe_mm": str(error + 1), + "direct_2d_error_px": str(error + 2), + "translation_x_mae_mm": str(error + 3), + "translation_y_mae_mm": str(error + 4), + "translation_z_mae_mm": str(error + 5), + "take": f"subject3/k2/{take_index}/cam4", + "subject": "subject3", + "sequence": f"k2/{take_index}", + }) + return rows + + +def test_rank_video_sequences_filters_invalid_and_orders_distinct_takes() -> None: + rows = [] + for take_index in range(12): + rows.extend(rows_for_take(take_index, float(take_index + 1))) + rows.extend(rows_for_take(12, 0.01, valid=False)) + + best, failure = rank_video_sequences(rows, count=5) + assert [row["sequence"] for row in best] == [ + "k2/0", "k2/1", "k2/2", "k2/3", "k2/4", + ] + assert [row["sequence"] for row in failure] == [ + "k2/11", "k2/10", "k2/9", "k2/8", "k2/7", + ] + assert not ({row["take"] for row in best} & {row["take"] for row in failure}) + assert best[0]["evaluated_frame_count"] == 8 + assert best[0]["annotated_hand_frames"] == 16 + + +def test_video_case_names_and_side_colors_are_stable() -> None: + case = { + "subject": "subject3", "sequence": "o2/5", + "frame_ids": list(range(748)), + } + assert case_directory_name(2, case) == "02_subject3_o2_5_frames_000000_000747" + assert LEFT_COLOR_RGB[2] > LEFT_COLOR_RGB[0] + assert RIGHT_COLOR_RGB[0] > RIGHT_COLOR_RGB[2] + + +def test_source_frame_ids_requires_a_contiguous_raw_sequence(tmp_path: Path) -> None: + rgb = tmp_path / "subject3" / "k2" / "0" / "cam4" / "rgb" + rgb.mkdir(parents=True) + for frame_id in (0, 1, 2): + (rgb / f"{frame_id:06d}.png").touch() + assert source_frame_ids(tmp_path, "subject3/k2/0/cam4") == [0, 1, 2] + + (rgb / "000001.png").unlink() + with pytest.raises(ValueError, match="not contiguous"): + source_frame_ids(tmp_path, "subject3/k2/0/cam4") diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_render_phase4_filtered_cases.py b/home/wuyifan/EgoNet_train_20261008/tests/test_render_phase4_filtered_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..846b7e9c74631c143bc15aef776dd6f70bce236a --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_render_phase4_filtered_cases.py @@ -0,0 +1,46 @@ +import numpy as np + +from scripts.render_phase4_filtered_cases import ( + camera_side_panel, + ranked_failure_takes, + trace_panel, +) + + +def test_ranked_failure_takes_uses_raw_valid_joint_error(tmp_path): + records = [] + for index, error_mm in enumerate((1.0, 3.0, 2.0)): + path = tmp_path / f"take{index}.npz" + prediction = np.zeros((2, 2, 21, 3), dtype=np.float32) + target = prediction.copy() + prediction[..., 0] = error_mm / 1000.0 + np.savez_compressed( + path, fps=np.asarray(30.0), take=np.asarray(f"subject3/k2/{index}/cam4"), + frame_id=np.arange(2, dtype=np.int64), + pred_joints_camera=prediction, target_joints_camera=target, + joint_element_valid=np.ones((2, 2, 21), dtype=bool), + ) + records.append({"path": str(path)}) + + ranked = ranked_failure_takes({"takes": records}, 2) + + assert [row["take"] for row in ranked] == [ + "subject3/k2/1/cam4", "subject3/k2/2/cam4", + ] + + +def test_diagnostic_panels_have_stable_dimensions(): + joints = np.zeros((2, 21, 3), dtype=np.float32) + joints[..., 2] = 0.5 + side = camera_side_panel( + joints, joints, joints, np.ones(2, dtype=bool), + (-0.2, 0.2, 0.3, 0.7), frame_id=4, + ) + trace = trace_panel( + np.zeros((8, 3)), np.zeros((8, 3)), np.ones(8, dtype=bool), + current=3, side="right", + ) + + assert side.shape == (540, 960, 3) + assert trace.shape == (540, 1920, 3) + assert side.dtype == trace.dtype == np.uint8 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_render_phase5_alignment_failure_cases.py b/home/wuyifan/EgoNet_train_20261008/tests/test_render_phase5_alignment_failure_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d054940a1852006e646282da124009bcad5a49 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_render_phase5_alignment_failure_cases.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +import numpy as np + +from scripts.render_phase5_alignment_failure_cases import ( + crop_bounds, + inlier_masks, + select_cases, +) + + +def row( + condition: str, take: str, frame: int, side: str, + coarse_z: float, refined_z: float, + *, depth: str = "middle", size: str = "medium", +) -> dict[str, str]: + z = coarse_z if condition == "coarse" else refined_z + return { + "condition": condition, "take": take, "frame_id": str(frame), "side": side, + "translation_z_mae_mm": str(z), "depth_bucket": depth, + "hand_size_bucket": size, "absolute_mpjpe_mm": str(z + 10.0), + "applied_delta_z_mm": "1", "alignment_confidence": "0.8", + "alignment_support": "40", "alignment_quality": "0.7", + } + + +def test_case_selection_is_role_specific_and_unique() -> None: + specs = ( + ("a/b/0/cam4", 1, "right", 70.0, 20.0, "far", "small"), + ("a/b/1/cam4", 2, "left", 40.0, 5.0, "near", "large"), + ("a/b/2/cam4", 3, "right", 10.0, 35.0, "near", "large"), + ("a/b/3/cam4", 4, "right", 50.0, 45.0, "far", "medium"), + ) + rows = [] + for take, frame, side, coarse, refined, depth, size in specs: + rows.extend(( + row("coarse", take, frame, side, coarse, refined, depth=depth, size=size), + row("calibrated_always", take, frame, side, coarse, refined, depth=depth, size=size), + )) + + selected = select_cases(rows, "calibrated_always") + + assert [case["role"] for case in selected] == [ + "right_far_small_tail", "largest_z_gain", "largest_z_harm", + ] + assert len({(case["take"], case["frame_id"], case["side"]) for case in selected}) == 3 + assert selected[0]["take"] == "a/b/0/cam4" + assert selected[2]["take"] == "a/b/2/cam4" + + +def test_inlier_and_crop_contracts() -> None: + observed = np.asarray((1.01, 1.02, 1.2, np.nan)) + predicted = np.ones(4) + eligible, inlier, outlier = inlier_masks( + observed, predicted, np.ones(4, dtype=bool), 0.015, 0.005, + ) + assert eligible.tolist() == [True, True, False, False] + assert inlier.tolist() == [True, True, False, False] + assert not outlier.any() + assert crop_bounds(np.asarray(((10, 10), (20, 20))), (720, 1280)) == (0, 0, 240, 240) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_rotations.py b/home/wuyifan/EgoNet_train_20261008/tests/test_rotations.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef81517620de29f5c9875441f1a813642039960 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_rotations.py @@ -0,0 +1,32 @@ +import torch + +from foundation_hand.geometry.rotations import axis_angle_to_matrix, matrix_to_axis_angle, rotation_6d_to_matrix + + +def test_axis_angle_matrix_roundtrip(): + axis_angle = torch.randn(128, 3) * 0.5 + reconstructed = axis_angle_to_matrix(matrix_to_axis_angle(axis_angle_to_matrix(axis_angle))) + assert torch.allclose(reconstructed, axis_angle_to_matrix(axis_angle), atol=1e-5) + + +def test_arctic_near_pi_root_rotation_roundtrip(): + root = torch.tensor([-2.6335168, -1.6809837, 0.3293310], dtype=torch.float32) + matrix = axis_angle_to_matrix(root) + restored = axis_angle_to_matrix(matrix_to_axis_angle(matrix)) + + assert float((restored - matrix).abs().max()) < 3e-6 + + +def test_identity_6d_to_axis_angle_has_finite_gradient(): + rotation = torch.tensor([[1.0, 0.0, 0.0, 0.0, 1.0, 0.0]], requires_grad=True) + axis_angle = matrix_to_axis_angle(rotation_6d_to_matrix(rotation)) + axis_angle.square().sum().backward() + assert torch.isfinite(rotation.grad).all() + + +def test_zero_axis_angle_has_finite_gradient(): + axis_angle = torch.zeros(8, 3, requires_grad=True) + + axis_angle_to_matrix(axis_angle).sum().backward() + + assert torch.isfinite(axis_angle.grad).all() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_run_phase4_a3_matrix.py b/home/wuyifan/EgoNet_train_20261008/tests/test_run_phase4_a3_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..1e103a62393ad58cffcf5b7306569ac4b3766750 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_run_phase4_a3_matrix.py @@ -0,0 +1,61 @@ +import csv +import hashlib +from pathlib import Path + +import yaml + +from scripts.run_phase4_a3_matrix import MODE_SLUGS, command_for, load_jobs + + +def test_load_jobs_requires_and_resolves_complete_formal_matrix(tmp_path): + config_root = tmp_path / "configs" + config_root.mkdir() + checkpoint = tmp_path / "coarse.pt" + checkpoint.write_bytes(b"frozen") + checkpoint_hash = hashlib.sha256(b"frozen").hexdigest() + rows = [] + for seed in (20260716, 20260717, 20260718): + for mode, slug in MODE_SLUGS.items(): + name = f"phase4_a3_{slug}_r640x368_s{seed}_formal100k" + config = config_root / f"{name}.yaml" + config.write_text(yaml.safe_dump({ + "name": name, "seed": seed, + "experiment": { + "oracle_crop_mode": mode, + "coarse_checkpoint_sha256": checkpoint_hash, + }, + }), encoding="utf-8") + rows.append({ + "config": f"/different/worktree/{config.name}", "name": name, + "seed": seed, "mode": mode, "stage": "formal", "max_steps": 100000, + "initialization_checkpoint": str(checkpoint), + "initialization_checkpoint_sha256": checkpoint_hash, + "initialization_checkpoint_step": 135000, + "gt_location": True, "official_test_used": False, + }) + matrix = tmp_path / "matrix.csv" + with matrix.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + jobs = load_jobs(matrix, config_root, tmp_path / "outputs") + + assert len(jobs) == 9 + assert {job["seed"] for job in jobs} == {20260716, 20260717, 20260718} + assert {job["mode"] for job in jobs} == set(MODE_SLUGS) + assert all(job["output"].name == job["name"] for job in jobs) + + +def test_command_includes_frozen_initialization_and_protocol(tmp_path): + job = { + "config": Path("config.yaml"), "checkpoint": Path("coarse.pt"), + "output": tmp_path / "run", + } + + command, environment = command_for(job, 4, Path("subset.json")) + + assert command[command.index("--init-checkpoint") + 1] == "coarse.pt" + assert command[command.index("--lr-schedule-steps") + 1] == "100000" + assert command[command.index("--validation-batches") + 1] == "256" + assert environment["CUDA_VISIBLE_DEVICES"] == "4" diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_sampler.py b/home/wuyifan/EgoNet_train_20261008/tests/test_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..8b9763d3185e8d0381826f0cd685b70480a42458 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_sampler.py @@ -0,0 +1,76 @@ +import json + +import pytest + +from foundation_hand.data import ( + ResumableRandomBatchSampler, + ResumableWeightedBatchSampler, + load_balanced_sampling_weights, +) + + +def test_resumed_sampler_reproduces_uninterrupted_batches(): + full = list(ResumableRandomBatchSampler(11, 3, seed=17, start_step=0, end_step=12)) + resumed = list(ResumableRandomBatchSampler(11, 3, seed=17, start_step=5, end_step=12)) + assert resumed == full[5:] + + +def test_sampler_visits_each_item_once_per_epoch(): + sampler = ResumableRandomBatchSampler(11, 3, seed=17, start_step=0, end_step=4) + batches = list(sampler) + flattened = [index for batch in batches for index in batch] + assert len(batches[-1]) == 2 + assert sorted(flattened) == list(range(11)) + + +def test_sampler_epoch_metadata_preserves_indices_and_resume(): + plain = list(ResumableRandomBatchSampler(5, 2, 7, 0, 7)) + tagged = list(ResumableRandomBatchSampler(5, 2, 7, 0, 7, include_epoch=True)) + assert [[index for index, _ in batch] for batch in tagged] == plain + assert tagged[0][0][1] == 0 + assert tagged[3][0][1] == 1 + resumed = list(ResumableRandomBatchSampler(5, 2, 7, 3, 7, include_epoch=True)) + assert resumed == tagged[3:] + + +def test_weighted_sampler_resume_is_exact_and_epoch_tagged(): + full = list(ResumableWeightedBatchSampler([1, 1, 8, 1, 1], 2, 7, 0, 9, True)) + resumed = list(ResumableWeightedBatchSampler([1, 1, 8, 1, 1], 2, 7, 4, 9, True)) + assert resumed == full[4:] + assert all(epoch == step // 3 for step, batch in enumerate(full) for _, epoch in batch) + assert sum(index == 2 for batch in full for index, _ in batch) >= 8 + + +@pytest.mark.parametrize("weights", ([], [1, 0], [1, float("nan")])) +def test_weighted_sampler_rejects_invalid_weights(weights): + with pytest.raises(ValueError): + ResumableWeightedBatchSampler(weights, 1, 0, 0, 1) + + +def test_balanced_sampling_manifest_is_bound_to_train_hash_and_contract(tmp_path): + train = tmp_path / "official_train.jsonl" + train.write_text('{"take":"train"}\n', encoding="utf-8") + import hashlib + source_hash = hashlib.sha256(train.read_bytes()).hexdigest() + manifest = tmp_path / "balanced.json" + manifest.write_text(json.dumps({ + "version": "phase4_train_geometry_balanced_v1", + "split_role": "official_train", + "official_test_used": False, + "source_manifest_sha256": source_hash, + "dataset_contract": {"resolution_hw": [368, 640], "T": 8, "stride": 1}, + "clip_count": 2, + "clips": [ + {"clip_index": 0, "weight": 0.5}, + {"clip_index": 1, "weight": 2.0}, + ], + }), encoding="utf-8") + weights, loaded = load_balanced_sampling_weights( + manifest, train, {"resolution_hw": [368, 640], "T": 8, "stride": 1}, 2, + ) + assert weights == [0.5, 2.0] + assert loaded["split_role"] == "official_train" + with pytest.raises(ValueError, match="source hash"): + load_balanced_sampling_weights(manifest, tmp_path / "balanced.json", { + "resolution_hw": [368, 640], "T": 8, "stride": 1, + }, 2) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_schedule.py b/home/wuyifan/EgoNet_train_20261008/tests/test_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..7a06cfdcd85ce2509990955c809757d60f35ef1c --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_schedule.py @@ -0,0 +1,20 @@ +import pytest + +from foundation_hand.training.schedule import warmup_cosine_learning_rate + + +def test_warmup_cosine_schedule_endpoints_and_resume_determinism(): + kwargs = dict(total_steps=100, base_lr=1e-4, min_lr=1e-5, warmup_steps=10) + values = [warmup_cosine_learning_rate(step, **kwargs) for step in range(100)] + assert values[0] == pytest.approx(1e-5) + assert values[9] == pytest.approx(1e-4) + assert values[10] == pytest.approx(1e-4) + assert values[-1] == pytest.approx(1e-5) + assert values[37:] == [warmup_cosine_learning_rate(step, **kwargs) for step in range(37, 100)] + + +def test_warmup_cosine_clamps_to_minimum_after_registered_horizon(): + kwargs = dict(total_steps=100, base_lr=1e-4, min_lr=1e-5, warmup_steps=10) + assert warmup_cosine_learning_rate(99, **kwargs) == pytest.approx(1e-5) + assert warmup_cosine_learning_rate(100, **kwargs) == pytest.approx(1e-5) + assert warmup_cosine_learning_rate(149, **kwargs) == pytest.approx(1e-5) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_sequence_inference.py b/home/wuyifan/EgoNet_train_20261008/tests/test_sequence_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..cd8e3736f5f5fcb1cf20e1009e8bb4916a0734d7 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_sequence_inference.py @@ -0,0 +1,108 @@ +import torch +from torch import nn + +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from foundation_hand.models import BimanualReconstructionModel, ModelConfig + + +def frame(value: int) -> dict[str, torch.Tensor]: + height, width = 16, 24 + K = torch.tensor([ + [30.0, 0.0, width / 2], [0.0, 30.0, height / 2], [0.0, 0.0, 1.0], + ]) + return { + "rgb": torch.full((1, 1, 3, height, width), float(value)), + "depth_m": torch.full((1, 1, 1, height, width), 0.5), + "depth_pixel_valid": torch.ones(1, 1, 1, height, width, dtype=torch.bool), + "K": K[None, None], + "K_available": torch.ones(1, 1, dtype=torch.bool), + "depth_available": torch.ones(1, 1, dtype=torch.bool), + "frame_valid": torch.ones(1, 1, dtype=torch.bool), + } + + +class RecordingCausalModel(nn.Module): + def __init__(self) -> None: + super().__init__() + self.config = ModelConfig(encoder="tiny_debug", temporal_attention_mode="causal") + self.maximum_time = 0 + + def forward(self, batch): + values = batch["rgb"][:, :, 0, 0, 0] + self.maximum_time = max(self.maximum_time, values.shape[1]) + return {"wrist_root_translation": values[..., None, None].expand(-1, -1, 2, 3)} + + +def test_causal_257_frame_output_is_complete_ordered_and_bounded() -> None: + model = RecordingCausalModel() + runner = LengthGeneralizedInference( + model, SequenceInferenceConfig(mode="causal", window_size=8), device="cpu", + ) + output = runner.infer(frame(index) for index in range(257)) + assert output["wrist_root_translation"].shape == (1, 257, 2, 3) + torch.testing.assert_close( + output["wrist_root_translation"][0, :, 0, 0], torch.arange(257).float(), + ) + assert model.maximum_time == 8 + assert runner.maximum_resident_frames == 8 + assert runner.maximum_input_buffer_frames == 8 + + +def test_offline_center_stitching_outputs_each_frame_once() -> None: + model = RecordingCausalModel() + model.config.temporal_attention_mode = "bidirectional" + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig(mode="offline", window_size=8, offline_stride=4), + device="cpu", + ) + output = runner.infer(frame(index) for index in range(31)) + assert output["wrist_root_translation"].shape[1] == 31 + torch.testing.assert_close( + output["wrist_root_translation"][0, :, 0, 0], torch.arange(31).float(), + ) + assert model.maximum_time == 8 + assert runner.maximum_input_buffer_frames <= 12 + + +def test_offline_short_partial_sequence_is_complete() -> None: + model = RecordingCausalModel() + model.config.temporal_attention_mode = "bidirectional" + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig(mode="offline", window_size=8, offline_stride=4), + device="cpu", + ) + output = runner.infer(frame(index) for index in range(3)) + torch.testing.assert_close( + output["wrist_root_translation"][0, :, 0, 0], torch.arange(3).float(), + ) + assert runner.maximum_resident_frames == 3 + + +def test_causal_runner_rejects_bidirectional_model() -> None: + model = RecordingCausalModel() + model.config.temporal_attention_mode = "bidirectional" + try: + LengthGeneralizedInference( + model, SequenceInferenceConfig(mode="causal", window_size=8), device="cpu", + ) + except ValueError as error: + assert "temporal_attention_mode='causal'" in str(error) + else: + raise AssertionError("bidirectional model must not be labeled causal") + + +def test_real_tiny_causal_model_runs_31_frames_with_window8() -> None: + model = BimanualReconstructionModel(ModelConfig( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, use_depth=True, use_rays=True, + temporal_attention_mode="causal", + )).eval() + runner = LengthGeneralizedInference( + model, SequenceInferenceConfig(mode="causal", window_size=8), device="cpu", + ) + output = runner.infer(frame(index) for index in range(31)) + assert output["wrist_root_translation"].shape == (1, 31, 2, 3) + assert output["mano_shape"].shape == (1, 31, 2, 10) + assert torch.isfinite(output["wrist_root_translation"]).all() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_sota_evaluation.py b/home/wuyifan/EgoNet_train_20261008/tests/test_sota_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..70597d5bee1446fce858fbbdc58f2c7ab3eea520 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_sota_evaluation.py @@ -0,0 +1,127 @@ +import numpy as np + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + evaluate_prediction_bundle, + load_frame_index, + paired_take_bootstrap, +) + + +def synthetic_ground_truth() -> GroundTruthBundle: + frame_ids = np.asarray([1, 2, 3], dtype=np.int64) + takes = np.asarray(["subject3/a/0/cam4"] * 3) + keys = np.asarray([f"{takes[0]}/{value:06d}" for value in frame_ids]) + joints = np.zeros((3, 2, 21, 3), dtype=np.float32) + joints[..., 2] = 1.0 + joints[..., 0] = np.linspace(0.0, 0.1, 21) + vertices = np.repeat(joints[:, :, :1], 778, axis=2) + intrinsics = np.repeat( + np.asarray([[[100.0, 0.0, 50.0], [0.0, 100.0, 40.0], [0.0, 0.0, 1.0]]]), + 3, + axis=0, + ) + return GroundTruthBundle( + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + annotation_valid=np.ones((3, 2), dtype=bool), + intrinsics=intrinsics, + metadata={}, + ) + + +def test_manifest_expansion_rejects_duplicate_frames(tmp_path): + manifest = tmp_path / "val.jsonl" + manifest.write_text( + '{"take":"subject3/a/0/cam4","frame_ids":[1,2]}\n' + '{"take":"subject3/a/0/cam4","frame_ids":[2,3]}\n', + encoding="utf-8", + ) + try: + load_frame_index(manifest) + except ValueError as error: + assert "Duplicate frame" in str(error) + else: + raise AssertionError("duplicate frame was accepted") + + +def test_prediction_bundle_round_trip_without_pickle(tmp_path): + gt = synthetic_ground_truth() + prediction = PredictionBundle( + model_name="model", + frame_keys=gt.frame_keys[::-1], + takes=gt.takes[::-1], + frame_ids=gt.frame_ids[::-1], + joints_camera_m=gt.joints_camera_m[::-1], + vertices_camera_m=gt.vertices_camera_m[::-1], + detected=np.ones((3, 2), dtype=bool), + confidence=np.ones((3, 2), dtype=np.float32), + metadata={"commit": "abc"}, + ) + path = tmp_path / "prediction.npz" + prediction.save(path) + loaded = PredictionBundle.load(path) + assert loaded.model_name == "model" + assert loaded.metadata == {"commit": "abc"} + np.testing.assert_array_equal(loaded.frame_ids, [3, 2, 1]) + + +def test_evaluation_counts_detector_miss_in_coverage_and_failure_aware_pck(): + gt = synthetic_ground_truth() + joints = gt.joints_camera_m.copy() + joints[..., 0] += 0.01 + vertices = gt.vertices_camera_m.copy() + vertices[..., 0] += 0.01 + detected = np.ones((3, 2), dtype=bool) + detected[1, 0] = False + joints[1, 0] = np.nan + vertices[1, 0] = np.nan + prediction = PredictionBundle( + model_name="translated", + frame_keys=gt.frame_keys, + takes=gt.takes, + frame_ids=gt.frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=np.ones((3, 2), dtype=np.float32), + metadata={}, + ) + report, rows, temporal = evaluate_prediction_bundle( + prediction, gt, bootstrap_samples=100 + ) + assert report["coverage"]["hand_frame_fraction"] == 5 / 6 + assert report["metrics_success_conditioned"]["absolute_mpjpe_mm"]["mean"] == 10.0 + assert np.isclose( + report["metrics_success_conditioned"]["root_relative_mpjpe_mm"]["mean"], + 0.0, + atol=1e-6, + ) + assert np.isclose(report["metrics_success_conditioned"]["projected_2d_error_px"]["mean"], 1.0) + assert np.isclose(report["failure_aware"]["absolute_pck_20mm"], 5 / 6) + missed = [row for row in rows if row["annotation_valid"] and not row["detected"]] + assert len(missed) == 1 + assert missed[0]["absolute_mpjpe_mm"] is None + assert len(temporal) == 4 + assert sum(row["evaluation_pair_success"] for row in temporal) == 2 + + +def test_paired_bootstrap_uses_exact_success_intersection(): + baseline = [ + {"frame_key": "a/1", "side": "left", "take": "a", "metric": 10.0}, + {"frame_key": "b/1", "side": "left", "take": "b", "metric": 20.0}, + ] + candidate = [ + {"frame_key": "a/1", "side": "left", "take": "a", "metric": 12.0}, + {"frame_key": "b/1", "side": "left", "take": "b", "metric": None}, + ] + result = paired_take_bootstrap( + baseline, candidate, metrics=("metric",), samples=100, seed=2 + )[0] + assert result["paired_hand_frames"] == 1 + assert result["take_count"] == 1 + assert result["candidate_minus_baseline"] == 2.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_spatial_joint2d.py b/home/wuyifan/EgoNet_train_20261008/tests/test_spatial_joint2d.py new file mode 100644 index 0000000000000000000000000000000000000000..db9dd128a6db64292d32ccbb244a7726a2a23c61 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_spatial_joint2d.py @@ -0,0 +1,93 @@ +import torch + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_model_initialization, save_checkpoint + + +def batch(time=3): + height, width = 64, 96 + K = torch.tensor([ + [80.0, 0.0, width / 2], [0.0, 80.0, height / 2], [0.0, 0.0, 1.0], + ]) + return { + "rgb": torch.randn(1, time, 3, height, width), + "depth_m": torch.rand(1, time, 1, height, width) + 0.3, + "depth_pixel_valid": torch.ones(1, time, 1, height, width, dtype=torch.bool), + "K": K[None, None].expand(1, time, -1, -1).clone(), + "K_available": torch.ones(1, time, dtype=torch.bool), + "depth_available": torch.ones(1, time, dtype=torch.bool), + "frame_valid": torch.ones(1, time, dtype=torch.bool), + "image_hw": torch.tensor([[height, width]]), + "joint2d": torch.rand(1, time, 2, 21, 2) * torch.tensor((width, height)), + "joint3d_camera": torch.rand(1, time, 2, 21, 3), + "joint_element_valid": torch.ones(1, time, 2, 21, dtype=torch.bool), + "joint_annotation_valid": torch.ones(1, time, 2, dtype=torch.bool), + "mano_annotation_valid": torch.ones(1, time, 2, dtype=torch.bool), + "mano_pose": torch.zeros(1, time, 2, 48), + "mano_shape": torch.zeros(1, time, 2, 10), + "wrist_root_translation": torch.rand(1, time, 2, 3), + "presence_target": torch.full((1, time, 2), torch.nan), + "presence_label_valid": torch.zeros(1, time, 2, dtype=torch.bool), + } + + +def config(**overrides): + values = dict( + encoder="tiny_debug", decoder_dim=32, decoder_layers=1, + attention_heads=4, patch_size=16, use_depth=True, use_rays=True, + joint2d_parameterization="spatial_heatmap", + ) + values.update(overrides) + return ModelConfig(**values) + + +def test_spatial_joint2d_is_finite_bounded_and_backpropagates() -> None: + model = BimanualReconstructionModel(config()) + sample = batch() + output = model(sample) + assert output["joint2d_norm"].shape == (1, 3, 2, 21, 2) + assert (output["joint2d_norm"] >= 0).all() and (output["joint2d_norm"] <= 1).all() + assert output["joint2d_heatmap_entropy"].shape == (1, 3, 2, 21) + assert torch.isfinite(output["joint2d_heatmap_entropy"]).all() + assert output["joint2d_heatmap_offset_norm"].abs().sum() == 0 + assert all(not parameter.requires_grad for parameter in model.joint2d_head.parameters()) + loss = BimanualLoss(LossConfig(joint2d_teacher=1.0))(output, sample)["total"] + loss.backward() + gradients = [ + parameter.grad for name, parameter in model.named_parameters() + if name.startswith("joint_localization_") and parameter.requires_grad + ] + assert gradients and all(value is not None and torch.isfinite(value).all() for value in gradients) + assert any(value.abs().sum() > 0 for value in gradients) + + +def test_spatial_joint2d_depth_fallback_ignores_unavailable_depth() -> None: + torch.manual_seed(3) + model = BimanualReconstructionModel(config()).eval() + first = batch(time=2) + first["depth_available"].zero_() + second = {key: value.clone() for key, value in first.items()} + second["depth_m"].fill_(9.0) + second["depth_pixel_valid"].zero_() + with torch.no_grad(): + first_output = model(first)["joint2d_norm"] + second_output = model(second)["joint2d_norm"] + torch.testing.assert_close(first_output, second_output, rtol=0, atol=0) + + +def test_old_checkpoint_initializes_only_spatial_joint2d_parameters(tmp_path) -> None: + source = BimanualReconstructionModel(config( + joint2d_parameterization="hand_token_linear", + )) + optimizer = torch.optim.AdamW(source.parameters(), lr=1e-3) + path = tmp_path / "source.pt" + save_checkpoint(path, source, optimizer, step=7) + target = BimanualReconstructionModel(config()) + record = load_model_initialization( + path, target, allowed_missing_prefixes=("joint_localization_",), + ) + assert record["step"] == 7 + assert record["residual_missing_keys"] + assert all(key.startswith("joint_localization_") for key in record["missing_keys"]) + torch.testing.assert_close(target.joint2d_head.weight, source.joint2d_head.weight) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_structured_hand.py b/home/wuyifan/EgoNet_train_20261008/tests/test_structured_hand.py new file mode 100644 index 0000000000000000000000000000000000000000..32d156370892ac0abf29b36bd9e51165b34e32ae --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_structured_hand.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +import torch + +from foundation_hand.models.structured_hand import ( + StructuredHandRefinement, + kinematic_attention_mask, + structured_part_locations, +) + + +def test_structured_part_locations_use_predicted_joint_groups() -> None: + joints = torch.zeros(1, 1, 2, 21, 2) + joints[..., 0] = torch.arange(21) + locations = structured_part_locations(joints) + assert locations.shape == (1, 1, 2, 7, 2) + assert locations[0, 0, 0, 0, 0] == 0 + assert locations[0, 0, 0, 1, 0] == torch.tensor( + (0 + 1 + 5 + 9 + 13 + 17) / 6, + ) + torch.testing.assert_close( + locations[0, 0, 0, 2:, 0], + torch.tensor((2.5, 6.5, 10.5, 14.5, 18.5)), + ) + + +def test_kinematic_mask_allows_only_self_and_tree_edges() -> None: + mask = kinematic_attention_mask(torch.device("cpu")) + assert mask.shape == (7, 7) + assert not mask.diagonal().any() + assert not mask[0, 1] and not mask[1, 0] + assert not mask[1, 2:].any() and not mask[2:, 1].any() + assert mask[0, 2:].all() and mask[2:, 0].all() + assert mask[2, 3] + + +def test_deterministic_detached_sampling_matches_grid_sample() -> None: + tokens = torch.arange(2 * 12 * 3, dtype=torch.float32).reshape(2, 12, 3) + tokens = tokens.reshape(1, 2, 12, 3) + locations = torch.tensor([ + [[[[[0.20, 0.30], [0.75, 0.60]]]], [[[[0.45, 0.50], [0.90, 0.15]]]]] + ]) + reference = StructuredHandRefinement._sample(tokens, (3, 4), locations) + candidate = StructuredHandRefinement._sample( + tokens, (3, 4), locations, deterministic_detached=True, + ) + torch.testing.assert_close(candidate, reference, atol=1e-5, rtol=1e-5) + + +def test_deterministic_detached_sampling_backpropagates_to_locations_only() -> None: + tokens = torch.randn(1, 1, 12, 4, requires_grad=True) + locations = torch.tensor( + [[[[[[0.45, 0.55], [0.45, 0.55]]]]]], requires_grad=True, + ) + sampled = StructuredHandRefinement._sample( + tokens, (3, 4), locations, deterministic_detached=True, + ) + sampled.sum().backward() + assert tokens.grad is None + assert locations.grad is not None + assert torch.isfinite(locations.grad).all() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_summarize_phase4_a3.py b/home/wuyifan/EgoNet_train_20261008/tests/test_summarize_phase4_a3.py new file mode 100644 index 0000000000000000000000000000000000000000..2ac5e4657ec97ff41fe4dce0152a164bc150f21f --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_summarize_phase4_a3.py @@ -0,0 +1,138 @@ +import csv +import json +import subprocess +import sys + +from scripts.summarize_phase4_a3 import ( + coarse_rows, + compute_gate, + gate_from_distributions, + rename_distribution_conditions, +) + + +def test_coarse_rows_maps_registered_metrics_without_changing_metadata(): + source = { + "clip_index": "3", "time_index": "2", "side": "right", + "coarse_absolute_mpjpe_mm": "10", + "coarse_root_relative_mpjpe_mm": "8", + "coarse_absolute_mpvpe_mm": "11", + "coarse_root_relative_mpvpe_mm": "9", + "coarse_fingertip_mpjpe_mm": "12", + "coarse_translation_z_mae_mm": "7", + } + + row = coarse_rows([source])[0] + + assert row["clip_index"] == "3" + assert row["absolute_mpjpe_mm"] == "10" + assert row["root_relative_mpvpe_mm"] == "9" + assert row["fingertip_mpjpe_mm"] == "12" + + +def test_a3_gate_requires_effect_size_and_absolute_guardrail(): + passed = compute_gate(20.0, 20.3, 30.0, 26.7, 15.0, 14.8) + harmful = compute_gate(20.0, 20.5, 30.0, 26.0, 15.0, 13.0) + too_small = compute_gate(20.0, 19.0, 30.0, 28.0, 15.0, 14.0) + + assert passed["promotion_gate_passed"] is True + assert harmful["accuracy_gain_passed"] is True + assert harmful["absolute_guardrail_passed"] is False + assert harmful["promotion_gate_passed"] is False + assert too_small["accuracy_gain_passed"] is False + assert too_small["promotion_gate_passed"] is False + + +def test_distribution_scope_is_explicit_and_gate_uses_full_values(): + rows = [] + means = { + "absolute_mpjpe_mm": (20.0, 20.2), + "fingertip_mpjpe_mm": (30.0, 26.0), + "root_relative_mpvpe_mm": (15.0, 14.8), + } + for metric, (coarse, refined) in means.items(): + rows.extend([ + {"group_field": "all", "group_value": "all", "metric": metric, + "condition": "reference", "mean": coarse}, + {"group_field": "all", "group_value": "all", "metric": metric, + "condition": "candidate", "mean": refined}, + {"group_field": "all", "group_value": "all", "metric": metric, + "condition": "candidate_minus_reference", "mean": refined - coarse}, + ]) + + rename_distribution_conditions(rows, "oracle_rgb", "full_validation") + gate = gate_from_distributions(rows, "oracle_rgb") + + assert {row["scope"] for row in rows} == {"full_validation"} + assert gate["promotion_gate_passed"] is True + + +def test_a3_summary_end_to_end_keeps_challenge_secondary(tmp_path): + evaluation_root = tmp_path / "evaluations" + output_dir = tmp_path / "reports" + modes = ("oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k") + seeds = (20260716, 20260717, 20260718) + row = { + "clip_index": 0, "time_index": 0, "side": "right", + "take": "subject3/k2/0/cam4", "frame_id": 4, + "annotation_valid": 1, "hand_size_bucket": "small", + "depth_bucket": "middle", "action_family": "object_interaction", + "bimanual_asymmetry_bucket": "strong", + "local_depth_validity_bucket": "high", + "absolute_mpjpe_mm": 20.2, "root_relative_mpjpe_mm": 8.0, + "absolute_mpvpe_mm": 20.0, "root_relative_mpvpe_mm": 8.5, + "fingertip_mpjpe_mm": 26.0, "translation_z_mae_mm": 9.0, + "coarse_absolute_mpjpe_mm": 20.0, + "coarse_root_relative_mpjpe_mm": 10.0, + "coarse_absolute_mpvpe_mm": 20.0, + "coarse_root_relative_mpvpe_mm": 10.0, + "coarse_fingertip_mpjpe_mm": 30.0, + "coarse_translation_z_mae_mm": 10.0, + } + for mode in modes: + for seed in seeds: + run = evaluation_root / f"{mode}_{seed}" / "best_absolute" + run.mkdir(parents=True) + (run / "evaluation.json").write_text(json.dumps({ + "status": "evaluated", "official_test_used": False, + "clips": 1495, "phase4_diagnostics": {"enabled": True}, + "config": { + "seed": seed, + "experiment": { + "oracle_crop_mode": mode, + "coarse_checkpoint_sha256": f"coarse-{seed}", + }, + }, + "oracle_crop_refinement": { + "enabled": True, "gt_location_at_inference": True, + "coarse_checkpoint_sha256": f"coarse-{seed}", + }, + }), encoding="utf-8") + with (run / "per_hand_frame_metrics.csv").open( + "w", newline="", encoding="utf-8", + ) as handle: + writer = csv.DictWriter(handle, fieldnames=list(row)) + writer.writeheader() + writer.writerow(row) + challenge = tmp_path / "challenge.json" + challenge.write_text(json.dumps({ + "count": 1, "source_clip_count": 1495, "clip_indices": [0], + "checkpoint_selection_allowed": False, + "training_sampler_use_allowed": False, "official_test_used": False, + }), encoding="utf-8") + + subprocess.run([ + sys.executable, "scripts/summarize_phase4_a3.py", + "--evaluation-root", str(evaluation_root), + "--output-dir", str(output_dir), + "--challenge-manifest", str(challenge), + "--bootstrap-samples", "20", + ], check=True) + + report = json.loads((output_dir / "A3_ORACLE_CROP.json").read_text()) + assert report["coarse_consistency_across_modes"] is True + assert report["challenge_subset"]["role"] == "secondary_diagnostic_only" + assert all(gate["promotion_gate_passed"] for gate in report["gates"].values()) + with (output_dir / "a3_oracle_crop_comparison.csv").open(newline="") as handle: + scopes = {record["scope"] for record in csv.DictReader(handle)} + assert scopes == {"full_validation", "challenge_secondary"} diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_summarize_phase4_control.py b/home/wuyifan/EgoNet_train_20261008/tests/test_summarize_phase4_control.py new file mode 100644 index 0000000000000000000000000000000000000000..c24112b9e7b3163e6a2ad6efef5dd399e137c9cc --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_summarize_phase4_control.py @@ -0,0 +1,60 @@ +from scripts.summarize_phase4_control import ( + aggregate_seed_rows, + assert_pair_alignment, + paired_take_bootstrap, +) + + +def rows(value: float): + return [ + { + "clip_index": "0", "time_index": "0", "side": "left", + "take": "take_a", "frame_id": "1", "annotation_valid": "1", + "metric": str(value), + }, + { + "clip_index": "1", "time_index": "0", "side": "right", + "take": "take_b", "frame_id": "2", "annotation_valid": "1", + "metric": str(value + 2), + }, + ] + + +def test_three_seed_aggregation_aligns_rows_before_averaging(): + aggregated = aggregate_seed_rows( + {20260716: rows(3), 20260717: rows(6), 20260718: rows(9)}, + ("clip_index", "time_index", "side"), ("metric",), + ) + assert [row["metric"] for row in aggregated] == [6.0, 8.0] + + +def test_pair_alignment_rejects_changed_validation_metadata(): + reference = rows(3) + candidate = rows(2) + assert_pair_alignment( + reference, candidate, ("clip_index", "time_index", "side"), + ("take", "frame_id", "side"), + ) + candidate[0]["take"] = "validation_identity_changed" + try: + assert_pair_alignment( + reference, candidate, ("clip_index", "time_index", "side"), + ("take", "frame_id", "side"), + ) + except ValueError as error: + assert "metadata mismatch" in str(error) + else: + raise AssertionError("metadata mismatch was not rejected") + + +def test_take_bootstrap_uses_paired_take_deltas(): + reference = rows(10) + candidate = rows(8) + output = paired_take_bootstrap( + reference, candidate, ("metric",), [("all", "all")], + statistics=("mean", "p95"), bootstrap_samples=1000, seed=7, + ) + assert len(output) == 2 + assert all(row["takes"] == 2 for row in output) + assert all(row["candidate_minus_reference"] == -2.0 for row in output) + assert all(row["ci_low"] == row["ci_high"] == -2.0 for row in output) diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_temporal_filter.py b/home/wuyifan/EgoNet_train_20261008/tests/test_temporal_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..0439ca99a0260f55e3da5ff2404b6f616e571a60 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_temporal_filter.py @@ -0,0 +1,65 @@ +import numpy as np +from scipy.spatial.transform import Rotation + +from foundation_hand.evaluation.temporal_filter import ( + apply_by_segment, + butterworth_zero_phase, + derivative_norms, + ema, + ema_low_frequency_delay_frames, + filter_rotation_matrices, + high_frequency_energy_ratio, + rotation_geodesic_degrees, + valid_segments, +) + + +def test_segments_never_cross_clip_gap_or_invalid_frame(): + segments = valid_segments( + np.array([0, 0, 0, 1, 1, 1, 1]), + np.array([4, 5, 7, 8, 9, 10, 11]), + np.array([True, True, True, True, False, True, True]), + ) + + assert [indices.tolist() for indices in segments] == [[0, 1], [2], [3], [5, 6]] + + +def test_ema_resets_by_segment_and_reports_short_fallbacks(): + values = np.array([[0.0], [10.0], [100.0], [200.0]], dtype=np.float32) + output, fallbacks = apply_by_segment( + values, [np.array([0, 1]), np.array([2, 3])], + lambda selected: ema(selected, 0.5), minimum_frames=2, + ) + + np.testing.assert_allclose(output[:, 0], [0.0, 5.0, 100.0, 150.0]) + assert fallbacks == 0 + assert ema_low_frequency_delay_frames(0.2) == 4.0 + + +def test_butterworth_constant_and_spectral_metric_are_finite(): + constant = np.ones((8, 3), dtype=np.float32) + filtered = butterworth_zero_phase(constant, cutoff_hz=4.0, fps=30.0) + + np.testing.assert_allclose(filtered, constant, atol=1e-6) + assert high_frequency_energy_ratio(filtered, fps=30.0) == 0.0 + assert derivative_norms(filtered, fps=30.0, order=2).shape == (6,) + + +def test_quaternion_sign_unwrap_filter_stays_on_so3(): + angles = np.linspace(0.0, 0.4, 8) + matrices = Rotation.from_rotvec( + np.stack((np.zeros(8), angles, np.zeros(8)), axis=-1) + ).as_matrix().astype(np.float32) + filtered = filter_rotation_matrices( + matrices, + lambda values: butterworth_zero_phase(values, 4.0, 30.0), + ) + + identity = np.eye(3, dtype=np.float32) + np.testing.assert_allclose( + np.swapaxes(filtered, -1, -2) @ filtered, + np.repeat(identity[None], len(filtered), axis=0), + atol=1e-5, + ) + np.testing.assert_allclose(np.linalg.det(filtered), 1.0, atol=1e-5) + assert np.max(rotation_geodesic_degrees(filtered, matrices)) < 1.0 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_feature_probe.py b/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_feature_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..bed25fda5eca04651a5c54e32cb907e684d2b221 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_feature_probe.py @@ -0,0 +1,20 @@ +"""Shape and checkpoint-key contracts for the frozen ViTPose-L probe.""" + +import torch + +from experiments.dinov3_2d_pretrain.vitpose_probe import ViTPoseBackbone + + +def test_vitpose_backbone_patch_grid_and_key_names(): + backbone = ViTPoseBackbone(width=32, depth=1, heads=4).eval() + state = backbone.state_dict() + assert state["pos_embed"].shape == (1, 193, 32) + assert state["patch_embed.projection.weight"].shape == (32, 3, 16, 16) + assert state["layers.0.attn.qkv.weight"].shape == (96, 32) + assert state["layers.0.ffn.layers.0.0.weight"].shape == (128, 32) + + with torch.no_grad(): + tokens, grid = backbone(torch.randn(1, 3, 64, 96)) + assert grid == (4, 6) + assert tokens.shape == (1, 24, 32) + assert torch.isfinite(tokens).all() diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_mot_from_scratch.py b/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_mot_from_scratch.py new file mode 100644 index 0000000000000000000000000000000000000000..cc22d06f0c943bebb786a9150abef9bc4748cfad --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_mot_from_scratch.py @@ -0,0 +1,58 @@ +"""Contract checks that do not depend on occupied GPUs or large image assets.""" + +from experiments.vitpose_mot_from_scratch.data import ( + RESOLUTIONS, RESOLUTION_PCT, mask_invalid_joint3d, resolution_for, +) +from experiments.vitpose_mot_from_scratch.model import TrainableViTPoseEncoder +from experiments.vitpose_mot_from_scratch.evaluate import summarize +from experiments.dinov3_2d_pretrain.vitpose_probe import ViTPoseBackbone +from torch import nn +import torch + + +def test_source_resolution_distribution(): + for source, headset in (("H2O", None), ("ARCTIC", None), ("HOT3D", "Aria"), ("HOT3D", "Quest3")): + key = f"{source}_{headset}" if headset else source + actual = [sum(resolution_for(source, headset, index) == hw for index in range(10000)) / 100 + for hw in RESOLUTIONS] + assert all(abs(observed - expected) < 2 for observed, expected in zip(actual, RESOLUTION_PCT[key])) + + +def test_full_frame_resolutions_and_no_crop(): + assert RESOLUTIONS == ((512, 896), (368, 640), (512, 512)) + + +def test_missing_native_joint_cannot_be_supervised(): + joints = torch.zeros(8, 2, 21, 3) + joints[7, 1] = float("nan") + sample = {"joint3d_camera": joints, "joint3d_valid": torch.ones(8, 2, 21, dtype=torch.bool)} + mask_invalid_joint3d(sample) + assert not sample["joint3d_valid"][7, 1].any() + assert sample["joint3d_valid"][7, 0].all() + assert sample["joint3d_valid"][:7].all() + assert torch.isnan(sample["joint3d_camera"][7, 1]).all() + + +def test_vitpose_global_position_bias_reaches_every_patch(): + encoder = TrainableViTPoseEncoder.__new__(TrainableViTPoseEncoder) + nn.Module.__init__(encoder) + encoder.backbone = ViTPoseBackbone(32, 0, 4) + encoder.projection = nn.Identity() + encoder.trainable_last_blocks = 0 + image = torch.zeros(1, 3, 32, 32) + original = encoder(image).tokens + with torch.no_grad(): + encoder.backbone.pos_embed[:, 0, 0] += 1 + changed = encoder(image).tokens + assert not torch.allclose(original, changed) + + +def test_hard_pose_variance_diagnostic_reports_mean_collapse(): + rows = [] + for value in (0.0, 2.0, 4.0): + rows.append({"gt_local_6d": [[value] * 6] * 15, + "pred_local_6d": [[value / 2] * 6] * 15, + "local_pose_per_joint_deg": [3.0] * 15}) + result = summarize(rows) + assert abs(result["pred_gt_local_6d_variance_ratio_macro"] - 0.25) < 1e-8 + assert result["local_pose_per_joint_mean_deg"] == [3.0] * 15 diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_mot_io_v3.py b/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_mot_io_v3.py new file mode 100644 index 0000000000000000000000000000000000000000..7355da5caaaf526f56f9971d1ce42c8ed52e9487 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_mot_io_v3.py @@ -0,0 +1,35 @@ +"""The IO-only variant must leave the original HOT3D reader untouched.""" + +from types import SimpleNamespace + +from experiments.vitpose_mot_io_v3 import data +from experiments.vitpose_mot_io_v3.hot3d_hand_only import hand_only_provider +from experiments.vitpose_mot_io_v3.train import CONFIG +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +class Native: + def _provider(self, recording): + return recording + + +def test_hand_only_provider_is_bound_to_both_hot3d_resolutions(monkeypatch): + anchor = SimpleNamespace(native=Native()) + + def init_sources(dataset): + dataset.sources = {"HOT3D": anchor} + + monkeypatch.setattr(data.U0Dataset, "__init__", init_sources) + alternate = SimpleNamespace(native=Native()) + monkeypatch.setattr(data.base, "FilteredClipDataset", lambda *args: alternate) + + dataset = data.MixedResolutionDataset() + assert anchor.native._provider.__func__ is hand_only_provider + assert dataset._reader("HOT3D", (512, 512)) is alternate + assert alternate.native._provider.__func__ is hand_only_provider + assert HOT3DClipDataset._provider is not hand_only_provider + + +def test_io_variant_has_separate_provenance(): + assert CONFIG["experiment"] == "vitpose_l_mot_rgb_from_scratch_io_v3_20261007" + assert CONFIG["io"] == {"hot3d_provider": "hand_only", "prefetch_factor": 4} diff --git a/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_mot_io_v4.py b/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_mot_io_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..0633d4fa07f5be202696ee61cb75ddb969be9287 --- /dev/null +++ b/home/wuyifan/EgoNet_train_20261008/tests/test_vitpose_mot_io_v4.py @@ -0,0 +1,58 @@ +"""The prefetch-16 variant keeps the same HOT3D and training contracts.""" + +from types import SimpleNamespace + +import torch + +from experiments.vitpose_mot_io_v4 import data +from experiments.vitpose_mot_io_v4.hot3d_hand_only import hand_only_provider +from experiments.vitpose_mot_io_v4.train import CONFIG +from experiments.from_scratch_mean_pose import throughput_probe +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +class Native: + def _provider(self, recording): + return recording + + +def test_hand_only_provider_is_bound_to_both_hot3d_resolutions(monkeypatch): + anchor = SimpleNamespace(native=Native()) + + def init_sources(dataset): + dataset.sources = {"HOT3D": anchor} + + monkeypatch.setattr(data.U0Dataset, "__init__", init_sources) + alternate = SimpleNamespace(native=Native()) + monkeypatch.setattr(data.base, "FilteredClipDataset", lambda *args: alternate) + + dataset = data.MixedResolutionDataset() + assert anchor.native._provider.__func__ is hand_only_provider + assert dataset._reader("HOT3D", (512, 512)) is alternate + assert alternate.native._provider.__func__ is hand_only_provider + assert HOT3DClipDataset._provider is not hand_only_provider + + +def test_io_variant_has_separate_provenance(): + assert CONFIG["experiment"] == "vitpose_l_mot_rgb_from_scratch_io_v4_rotationfix_grouped_20261007" + assert CONFIG["io"] == {"hot3d_provider": "hand_only", "prefetch_factor": 16, "group_max_clips": 10} + + +def test_resolution_grouping_keeps_every_clip_and_mask(monkeypatch): + samples = [ + {"rgb": torch.empty(8, 3, *size), "clip": index, + "mask": torch.tensor(index % 2 == 0)} + for index, size in enumerate(((4, 6), (4, 4), (4, 6), + (4, 6), (4, 4))) + ] + monkeypatch.setattr(throughput_probe, "collate_probe_samples", lambda group: { + "clip": [sample["clip"] for sample in group], + "mask": torch.stack([sample["mask"] for sample in group]), + "size": tuple(group[0]["rgb"].shape[-2:]), + }) + grouped = throughput_probe.collate_matching_resolutions(samples, maximum=2) + assert [batch["clip"] for batch in grouped] == [[0, 2], [3], [1, 4]] + assert all(batch["mask"].tolist() == [index % 2 == 0 for index in batch["clip"]] + for batch in grouped) + assert all(batch["size"] == tuple(samples[batch["clip"][0]]["rgb"].shape[-2:]) + for batch in grouped) diff --git a/home/wuyifan/a7_canonical_gt_rotationfix_20260930/audit.json b/home/wuyifan/a7_canonical_gt_rotationfix_20260930/audit.json new file mode 100644 index 0000000000000000000000000000000000000000..f46269ec41e74e3fdd53789b4571a26a22860072 --- /dev/null +++ b/home/wuyifan/a7_canonical_gt_rotationfix_20260930/audit.json @@ -0,0 +1,1976 @@ +{ + "ready_for_training": true, + "source": "G1 fit on G2 original V5 native cache", + "original_g2_cache_unchanged": true, + "g1_inventory_sha256": "46b08af1d0b4285f4ed1fe7c207260482a9da934c16f8579cead4bef554be8b6", + "g2_inventory_sha256": "99667c7bf9c48eba4d339af41b5eacf3cc2bc1fddf557a04597d30fb22b85ab5", + "migrated_inventory_sha256": "b4394d2ab4428ff8b540cd9edbe40904efbefd67c4bb46f180206862513af0e8", + "g1_fit_audit_sha256": "92eb2bdbfb8e4279655caf12330150b4849706da197310af0c30f8bada915cf6", + "records": 380, + "expected_records": 380, + "fitted_left_frames": 192148, + "right_native_max_mm": 0.024374020901487936, + "adapter_checks": [ + { + "source": "ARCTIC", + "recording": "s01/box_grab_01", + "max_coordinate_difference": { + "vertices": 1.7881393432617188e-07, + "joints": 1.1920928955078125e-07, + "wrist": 5.960464477539063e-08, + "joint2d": 0.0001220703125, + "K": 0.0 + } + }, + { + "source": "ARCTIC", + "recording": "s02/box_grab_01", + "max_coordinate_difference": { + "vertices": 1.1920928955078125e-07, + "joints": 1.1920928955078125e-07, + "wrist": 5.960464477539063e-08, + "joint2d": 0.0001068115234375, + "K": 0.0 + } + }, + { + "source": "ARCTIC", + "recording": "s04/box_grab_01", + "max_coordinate_difference": { + "vertices": 1.7881393432617188e-07, + "joints": 1.4901161193847656e-07, + "wrist": 8.940696716308594e-08, + "joint2d": 0.0001220703125, + "K": 0.0 + } + }, + { + "source": "ARCTIC", + "recording": "s06/box_use_01", + "max_coordinate_difference": { + "vertices": 1.7881393432617188e-07, + "joints": 1.7881393432617188e-07, + "wrist": 1.4901161193847656e-07, + "joint2d": 0.00018310546875, + "K": 0.0 + } + }, + { + "source": "ARCTIC", + "recording": "s07/box_grab_01", + "max_coordinate_difference": { + "vertices": 1.7881393432617188e-07, + "joints": 1.4901161193847656e-07, + "wrist": 1.1920928955078125e-07, + "joint2d": 0.0001373291015625, + "K": 0.0 + } + }, + { + "source": "ARCTIC", + "recording": "s08/box_use_01", + "max_coordinate_difference": { + "vertices": 1.7881393432617188e-07, + "joints": 1.4901161193847656e-07, + "wrist": 1.1920928955078125e-07, + "joint2d": 0.00012969970703125, + "K": 0.0 + } + }, + { + "source": "ARCTIC", + "recording": "s09/capsulemachine_use_01", + "max_coordinate_difference": { + "vertices": 1.7881393432617188e-07, + "joints": 1.1920928955078125e-07, + "wrist": 7.450580596923828e-08, + "joint2d": 0.0001220703125, + "K": 0.0 + } + }, + { + "source": "ARCTIC", + "recording": "s10/box_use_01", + "max_coordinate_difference": { + "vertices": 1.7881393432617188e-07, + "joints": 1.4901161193847656e-07, + "wrist": 8.940696716308594e-08, + "joint2d": 0.000152587890625, + "K": 0.0 + } + }, + { + "source": "H2O", + "recording": "subject1/h1/0/cam4", + "max_coordinate_difference": { + "vertices": 5.960464477539063e-08, + "joints": 0.0, + "wrist": 0.0, + "joint2d": 6.103515625e-05, + "K": 0.0 + } + }, + { + "source": "H2O", + "recording": "subject2/h1/0/cam4", + "max_coordinate_difference": { + "vertices": 6.612390279769897e-08, + "joints": 0.0, + "wrist": 0.0, + "joint2d": 6.103515625e-05, + "K": 0.0 + } + }, + { + "source": "H2O", + "recording": "subject3/h1/0/cam4", + "max_coordinate_difference": { + "vertices": 6.51925802230835e-08, + "joints": 0.0, + "wrist": 0.0, + "joint2d": 6.103515625e-05, + "K": 0.0 + } + } + ], + "subjects": { + "ARCTIC_s01": { + "frames": 16645, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 16645, + "mean": 0.7325757946651478, + "p95": 0.8156646030832956, + "max": 0.8996251801952875 + }, + "root_relative_mpjpe_mm": { + "count": 16645, + "mean": 0.7624364060810668, + "p95": 0.8457549354682337, + "max": 0.9492092182139522 + }, + "mpvpe_mm": { + "count": 16645, + "mean": 1.6315431917680394, + "p95": 1.6840150957907378, + "max": 1.7255920216019895 + }, + "pa_mpjpe_mm": { + "count": 16645, + "mean": 0.7249944139911243, + "p95": 0.8057527235825549, + "max": 0.8936946772153754 + }, + "max_vertex_mm": { + "count": 16645, + "mean": 6.801088566048539, + "p95": 6.944862226125772, + "max": 7.068033813438242 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 1.6315431917680394, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 1.6840150957907378, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 7.068033813438242, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 0.5393819086505204, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.2031578642833147, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 16645, + "mpvpe_mm": { + "count": 16645, + "mean": 1.6315431917680394, + "p95": 1.6840150957907376, + "max": 1.7255920216019898 + }, + "max_vertex_mm": { + "count": 16645, + "mean": 6.801088566048539, + "p95": 6.944862226125772, + "max": 7.068033813438242 + }, + "wrist_adjustment_mm": { + "count": 16645, + "mean": 0.2412085914271211, + "p95": 0.35509149233777, + "max": 0.5393819086505204 + }, + "local_pose_adjustment_rms_rad": { + "count": 16645, + "mean": 0.1691367941644355, + "p95": 0.1806315121457685, + "max": 0.2031578642833147 + }, + "projection_disagreement_px": { + "count": 342646, + "mean": 0.7431593306942915, + "p95": 1.7844112122607658, + "max": 4.96450900324757 + }, + "scaled_pose_gradient": { + "count": 16645, + "mean": 2.6058124499952042e-05, + "p95": 5.244148418553199e-05, + "max": 0.0009081405867394412 + }, + "free_wrist_gradient_max": 8.386535910176462e-11, + "conditional_wrist_identity_error_mm": 1.1443916996305594e-13, + "shared_beta_gradient_max": 2.19332748418931e-08, + "worst_frames": [ + { + "mean_vertex_mm": 1.7255920216019898, + "max_vertex_mm": 6.742507156829454, + "record_index": 17, + "frame_index": 525 + }, + { + "mean_vertex_mm": 1.7253038308340065, + "max_vertex_mm": 6.7429613209657475, + "record_index": 17, + "frame_index": 524 + }, + { + "mean_vertex_mm": 1.7239607952559297, + "max_vertex_mm": 6.743188000653051, + "record_index": 17, + "frame_index": 523 + }, + { + "mean_vertex_mm": 1.723337810301474, + "max_vertex_mm": 6.740113682469324, + "record_index": 17, + "frame_index": 526 + }, + { + "mean_vertex_mm": 1.7224540483720836, + "max_vertex_mm": 6.735941941040799, + "record_index": 17, + "frame_index": 527 + }, + { + "mean_vertex_mm": 1.7219776462411585, + "max_vertex_mm": 6.732605877440824, + "record_index": 17, + "frame_index": 528 + }, + { + "mean_vertex_mm": 1.7199076631159853, + "max_vertex_mm": 6.743407183646556, + "record_index": 17, + "frame_index": 522 + }, + { + "mean_vertex_mm": 1.719816097684696, + "max_vertex_mm": 6.72579752203533, + "record_index": 20, + "frame_index": 204 + }, + { + "mean_vertex_mm": 1.719275654193502, + "max_vertex_mm": 6.73027137660607, + "record_index": 17, + "frame_index": 529 + }, + { + "mean_vertex_mm": 1.718624467631725, + "max_vertex_mm": 6.727333360092092, + "record_index": 20, + "frame_index": 203 + } + ] + } + }, + "ARCTIC_s02": { + "frames": 19278, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 19278, + "mean": 0.36829292375141187, + "p95": 0.40965120508440356, + "max": 0.4653154926043599 + }, + "root_relative_mpjpe_mm": { + "count": 19278, + "mean": 0.40754267024335766, + "p95": 0.47377773404166834, + "max": 0.5563702518593161 + }, + "mpvpe_mm": { + "count": 19278, + "mean": 0.8703610338431401, + "p95": 0.8887302597471487, + "max": 0.909471146147574 + }, + "pa_mpjpe_mm": { + "count": 19278, + "mean": 0.36344862884818674, + "p95": 0.4045296226447434, + "max": 0.46389296897368665 + }, + "max_vertex_mm": { + "count": 19278, + "mean": 3.525763399452658, + "p95": 3.617585664688315, + "max": 3.694799412746227 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 0.8703610338431401, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 0.8887302597471487, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 3.694799412746227, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 0.3332314076073453, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.09336032015757899, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 19278, + "mpvpe_mm": { + "count": 19278, + "mean": 0.8703610338431401, + "p95": 0.8887302597471487, + "max": 0.909471146147574 + }, + "max_vertex_mm": { + "count": 19278, + "mean": 3.525763399452658, + "p95": 3.617585664688315, + "max": 3.694799412746227 + }, + "wrist_adjustment_mm": { + "count": 19278, + "mean": 0.18281624478174952, + "p95": 0.2748357879215478, + "max": 0.33323140760734526 + }, + "local_pose_adjustment_rms_rad": { + "count": 19278, + "mean": 0.08171724538045216, + "p95": 0.08729111773449215, + "max": 0.09336032015757899 + }, + "projection_disagreement_px": { + "count": 384448, + "mean": 0.3796252008248015, + "p95": 0.8600624446967129, + "max": 2.5006223176384013 + }, + "scaled_pose_gradient": { + "count": 19278, + "mean": 9.704812457695061e-05, + "p95": 0.0002256106463573879, + "max": 0.004305021347152338 + }, + "free_wrist_gradient_max": 8.701306342118187e-11, + "conditional_wrist_identity_error_mm": 1.1123893155135927e-13, + "shared_beta_gradient_max": 1.6484539946335893e-07, + "worst_frames": [ + { + "mean_vertex_mm": 0.909471146147574, + "max_vertex_mm": 3.5296142257001297, + "record_index": 2, + "frame_index": 339 + }, + { + "mean_vertex_mm": 0.9070611872155768, + "max_vertex_mm": 3.522483678201654, + "record_index": 2, + "frame_index": 340 + }, + { + "mean_vertex_mm": 0.9068503444888496, + "max_vertex_mm": 3.5268105194306187, + "record_index": 2, + "frame_index": 338 + }, + { + "mean_vertex_mm": 0.9052344909688333, + "max_vertex_mm": 3.586208043462537, + "record_index": 2, + "frame_index": 185 + }, + { + "mean_vertex_mm": 0.9037907648281654, + "max_vertex_mm": 3.5331201393273974, + "record_index": 1, + "frame_index": 389 + }, + { + "mean_vertex_mm": 0.9033984900321212, + "max_vertex_mm": 3.5438846429091244, + "record_index": 1, + "frame_index": 390 + }, + { + "mean_vertex_mm": 0.9031597471488151, + "max_vertex_mm": 3.5238921704186366, + "record_index": 1, + "frame_index": 388 + }, + { + "mean_vertex_mm": 0.9029120466559646, + "max_vertex_mm": 3.667318352707339, + "record_index": 22, + "frame_index": 165 + }, + { + "mean_vertex_mm": 0.9027597440115119, + "max_vertex_mm": 3.6687872688285035, + "record_index": 22, + "frame_index": 166 + }, + { + "mean_vertex_mm": 0.9026873216584559, + "max_vertex_mm": 3.544039778317282, + "record_index": 22, + "frame_index": 544 + } + ] + } + }, + "ARCTIC_s04": { + "frames": 17234, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 17234, + "mean": 0.3341171112848381, + "p95": 0.3589518074050427, + "max": 0.4071870884628738 + }, + "root_relative_mpjpe_mm": { + "count": 17234, + "mean": 0.7988968867947328, + "p95": 0.8342162502213445, + "max": 0.8713487977572625 + }, + "mpvpe_mm": { + "count": 17234, + "mean": 0.8511861604759405, + "p95": 0.8668475028679387, + "max": 0.8823538964273689 + }, + "pa_mpjpe_mm": { + "count": 17234, + "mean": 0.3184061619471219, + "p95": 0.3420781943708586, + "max": 0.38093456780487156 + }, + "max_vertex_mm": { + "count": 17234, + "mean": 3.7511945332399943, + "p95": 3.8492017370536495, + "max": 3.9322529047615493 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 0.8511861604759405, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 0.8668475028679387, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 3.9322529047615493, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 0.7762393570469306, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.09093983059028203, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 17234, + "mpvpe_mm": { + "count": 17234, + "mean": 0.8511861604759404, + "p95": 0.8668475028679387, + "max": 0.8823538964273688 + }, + "max_vertex_mm": { + "count": 17234, + "mean": 3.7511945332399943, + "p95": 3.8492017370536495, + "max": 3.9322529047615493 + }, + "wrist_adjustment_mm": { + "count": 17234, + "mean": 0.7139591758897438, + "p95": 0.7529954399441589, + "max": 0.7762393570469306 + }, + "local_pose_adjustment_rms_rad": { + "count": 17234, + "mean": 0.07468039380692273, + "p95": 0.08140278032127989, + "max": 0.09093983059028203 + }, + "projection_disagreement_px": { + "count": 352794, + "mean": 0.34117145499079127, + "p95": 0.94834581564848, + "max": 2.5516924167942028 + }, + "scaled_pose_gradient": { + "count": 17234, + "mean": 1.9543870511280826e-05, + "p95": 4.2120939300627055e-05, + "max": 0.0007472770152770951 + }, + "free_wrist_gradient_max": 8.679634788677504e-11, + "conditional_wrist_identity_error_mm": 1.1443916996305594e-13, + "shared_beta_gradient_max": 1.107406076446938e-08, + "worst_frames": [ + { + "mean_vertex_mm": 0.8823538964273688, + "max_vertex_mm": 3.923703380151181, + "record_index": 17, + "frame_index": 325 + }, + { + "mean_vertex_mm": 0.8822017414924329, + "max_vertex_mm": 3.924410414985091, + "record_index": 17, + "frame_index": 324 + }, + { + "mean_vertex_mm": 0.8821937806399768, + "max_vertex_mm": 3.921985356872229, + "record_index": 17, + "frame_index": 326 + }, + { + "mean_vertex_mm": 0.8819523273528309, + "max_vertex_mm": 3.9201497463262687, + "record_index": 17, + "frame_index": 327 + }, + { + "mean_vertex_mm": 0.8818989276837391, + "max_vertex_mm": 3.911334914557502, + "record_index": 17, + "frame_index": 332 + }, + { + "mean_vertex_mm": 0.8818980385611045, + "max_vertex_mm": 3.9239673285047596, + "record_index": 17, + "frame_index": 323 + }, + { + "mean_vertex_mm": 0.8818832008294345, + "max_vertex_mm": 3.921055056445396, + "record_index": 17, + "frame_index": 322 + }, + { + "mean_vertex_mm": 0.8817905771970107, + "max_vertex_mm": 3.911723414830698, + "record_index": 17, + "frame_index": 331 + }, + { + "mean_vertex_mm": 0.8817711657969215, + "max_vertex_mm": 3.918192578058177, + "record_index": 17, + "frame_index": 328 + }, + { + "mean_vertex_mm": 0.881747108576281, + "max_vertex_mm": 3.9138360993699295, + "record_index": 17, + "frame_index": 330 + } + ] + } + }, + "ARCTIC_s06": { + "frames": 18381, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 18381, + "mean": 0.7016189836195462, + "p95": 0.7677371165326654, + "max": 0.8121411077879156 + }, + "root_relative_mpjpe_mm": { + "count": 18381, + "mean": 1.2447218152673452, + "p95": 1.3306521735225647, + "max": 1.4180773002615643 + }, + "mpvpe_mm": { + "count": 18381, + "mean": 1.041364712319974, + "p95": 1.1104674377198944, + "max": 1.1668861733602955 + }, + "pa_mpjpe_mm": { + "count": 18381, + "mean": 0.6846207336697431, + "p95": 0.7568170122956411, + "max": 0.8107122673215406 + }, + "max_vertex_mm": { + "count": 18381, + "mean": 3.443813648312737, + "p95": 3.6410800759312343, + "max": 3.9867981026665484 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 1.041364712319974, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 1.1104674377198944, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 3.9867981026665484, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 1.2615867037512378, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.13987488902361603, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 18381, + "mpvpe_mm": { + "count": 18381, + "mean": 1.041364712319974, + "p95": 1.1104674377198942, + "max": 1.1668861733602953 + }, + "max_vertex_mm": { + "count": 18381, + "mean": 3.443813648312737, + "p95": 3.6410800759312343, + "max": 3.9867981026665484 + }, + "wrist_adjustment_mm": { + "count": 18381, + "mean": 1.072971334213339, + "p95": 1.1859286722766913, + "max": 1.2615867037512378 + }, + "local_pose_adjustment_rms_rad": { + "count": 18381, + "mean": 0.10212621927609637, + "p95": 0.11724090211878259, + "max": 0.13987488902361603 + }, + "projection_disagreement_px": { + "count": 367116, + "mean": 0.5637317365966019, + "p95": 1.1586640478328272, + "max": 2.5035069039050066 + }, + "scaled_pose_gradient": { + "count": 18381, + "mean": 0.0006315434002730369, + "p95": 0.0013058364887236782, + "max": 0.03167675621864881 + }, + "free_wrist_gradient_max": 9.756773167168831e-11, + "conditional_wrist_identity_error_mm": 1.152775633689051e-13, + "shared_beta_gradient_max": 9.208311709737473e-06, + "worst_frames": [ + { + "mean_vertex_mm": 1.1668861733602953, + "max_vertex_mm": 3.403566942096125, + "record_index": 2, + "frame_index": 384 + }, + { + "mean_vertex_mm": 1.1666348759217213, + "max_vertex_mm": 3.495582446201549, + "record_index": 24, + "frame_index": 445 + }, + { + "mean_vertex_mm": 1.1666333007537857, + "max_vertex_mm": 3.4973819626680682, + "record_index": 24, + "frame_index": 446 + }, + { + "mean_vertex_mm": 1.1658121316447945, + "max_vertex_mm": 3.397256063482999, + "record_index": 2, + "frame_index": 383 + }, + { + "mean_vertex_mm": 1.165621631676478, + "max_vertex_mm": 3.4225918445160075, + "record_index": 2, + "frame_index": 385 + }, + { + "mean_vertex_mm": 1.1652355962970988, + "max_vertex_mm": 3.4974011290069034, + "record_index": 24, + "frame_index": 444 + }, + { + "mean_vertex_mm": 1.1649462561836172, + "max_vertex_mm": 3.5017828442152816, + "record_index": 24, + "frame_index": 447 + }, + { + "mean_vertex_mm": 1.16237142739062, + "max_vertex_mm": 3.4019782811477417, + "record_index": 2, + "frame_index": 382 + }, + { + "mean_vertex_mm": 1.1599065095983514, + "max_vertex_mm": 3.5077927738769676, + "record_index": 24, + "frame_index": 448 + }, + { + "mean_vertex_mm": 1.1596549705723695, + "max_vertex_mm": 3.5098446943590926, + "record_index": 24, + "frame_index": 443 + } + ] + } + }, + "ARCTIC_s07": { + "frames": 19143, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 19143, + "mean": 0.5520552992130325, + "p95": 0.616322531097121, + "max": 0.6622954639621833 + }, + "root_relative_mpjpe_mm": { + "count": 19143, + "mean": 1.021101246837515, + "p95": 1.0989050564716905, + "max": 1.1969670140198914 + }, + "mpvpe_mm": { + "count": 19143, + "mean": 0.792817222463574, + "p95": 0.8490709224998954, + "max": 0.8973302252482109 + }, + "pa_mpjpe_mm": { + "count": 19143, + "mean": 0.5450809195684259, + "p95": 0.6052759546238572, + "max": 0.6445391848756505 + }, + "max_vertex_mm": { + "count": 19143, + "mean": 2.7140079932908114, + "p95": 2.8796120349805925, + "max": 2.9993700856955137 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 0.792817222463574, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 0.8490709224998954, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 2.9993700856955137, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 1.0964893272698737, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.08711974575571332, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 19143, + "mpvpe_mm": { + "count": 19143, + "mean": 0.7928172224635739, + "p95": 0.8490709224998954, + "max": 0.8973302252482108 + }, + "max_vertex_mm": { + "count": 19143, + "mean": 2.7140079932908114, + "p95": 2.8796120349805925, + "max": 2.9993700856955137 + }, + "wrist_adjustment_mm": { + "count": 19143, + "mean": 0.9109342758183633, + "p95": 0.9941917330044575, + "max": 1.0964893272698737 + }, + "local_pose_adjustment_rms_rad": { + "count": 19143, + "mean": 0.06666438761944421, + "p95": 0.0760107563486988, + "max": 0.08711974575571332 + }, + "projection_disagreement_px": { + "count": 390033, + "mean": 0.5626049106238705, + "p95": 1.2614479677156263, + "max": 2.5722458623780042 + }, + "scaled_pose_gradient": { + "count": 19143, + "mean": 0.0003255734672662408, + "p95": 0.0006985408985185872, + "max": 0.01855667912312173 + }, + "free_wrist_gradient_max": 8.844258658768922e-11, + "conditional_wrist_identity_error_mm": 1.2412670766236365e-13, + "shared_beta_gradient_max": 1.4339042936433691e-06, + "worst_frames": [ + { + "mean_vertex_mm": 0.8973302252482108, + "max_vertex_mm": 2.6752156524114414, + "record_index": 1, + "frame_index": 533 + }, + { + "mean_vertex_mm": 0.8972421323155738, + "max_vertex_mm": 2.6712604931953368, + "record_index": 1, + "frame_index": 532 + }, + { + "mean_vertex_mm": 0.8969281641487442, + "max_vertex_mm": 2.677446068233139, + "record_index": 1, + "frame_index": 534 + }, + { + "mean_vertex_mm": 0.89669079758719, + "max_vertex_mm": 2.667860857600087, + "record_index": 1, + "frame_index": 531 + }, + { + "mean_vertex_mm": 0.8959482554353917, + "max_vertex_mm": 2.6806206575163913, + "record_index": 1, + "frame_index": 535 + }, + { + "mean_vertex_mm": 0.8957656287067864, + "max_vertex_mm": 2.6610564547991897, + "record_index": 1, + "frame_index": 530 + }, + { + "mean_vertex_mm": 0.8955555411589884, + "max_vertex_mm": 2.6540433754572956, + "record_index": 1, + "frame_index": 529 + }, + { + "mean_vertex_mm": 0.894959880325065, + "max_vertex_mm": 2.691889975890081, + "record_index": 28, + "frame_index": 397 + }, + { + "mean_vertex_mm": 0.8948062957550942, + "max_vertex_mm": 2.646737567804438, + "record_index": 1, + "frame_index": 528 + }, + { + "mean_vertex_mm": 0.8946032612880527, + "max_vertex_mm": 2.694112434342833, + "record_index": 28, + "frame_index": 398 + } + ] + } + }, + "ARCTIC_s08": { + "frames": 24529, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 24529, + "mean": 0.6492977305272559, + "p95": 0.7271758974524626, + "max": 0.8156481197178771 + }, + "root_relative_mpjpe_mm": { + "count": 24529, + "mean": 0.7035370985940137, + "p95": 0.7994900803383357, + "max": 0.9716180493494091 + }, + "mpvpe_mm": { + "count": 24529, + "mean": 1.6212909457200613, + "p95": 1.6641848340033898, + "max": 1.7117216569944869 + }, + "pa_mpjpe_mm": { + "count": 24529, + "mean": 0.6389205994795822, + "p95": 0.7185630127846092, + "max": 0.8069425003419625 + }, + "max_vertex_mm": { + "count": 24529, + "mean": 7.363345198642706, + "p95": 7.511741863783843, + "max": 7.754545762684625 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 1.6212909457200613, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 1.6641848340033898, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 7.754545762684625, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 0.5817247638786822, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.19111596714800258, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 24529, + "mpvpe_mm": { + "count": 24529, + "mean": 1.621290945720061, + "p95": 1.6641848340033896, + "max": 1.7117216569944869 + }, + "max_vertex_mm": { + "count": 24529, + "mean": 7.363345198642706, + "p95": 7.511741863783843, + "max": 7.754545762684625 + }, + "wrist_adjustment_mm": { + "count": 24529, + "mean": 0.277484914604166, + "p95": 0.38837091316490185, + "max": 0.5817247638786822 + }, + "local_pose_adjustment_rms_rad": { + "count": 24529, + "mean": 0.16581945162408027, + "p95": 0.17661350258104924, + "max": 0.19111596714800258 + }, + "projection_disagreement_px": { + "count": 504521, + "mean": 0.6338905888483347, + "p95": 1.5217417240264979, + "max": 4.985256781168362 + }, + "scaled_pose_gradient": { + "count": 24529, + "mean": 0.01091776275395813, + "p95": 0.024519988814303437, + "max": 0.19160796772964706 + }, + "free_wrist_gradient_max": 8.770939530222677e-11, + "conditional_wrist_identity_error_mm": 1.1188630228279524e-13, + "shared_beta_gradient_max": 8.716988361631347e-05, + "worst_frames": [ + { + "mean_vertex_mm": 1.7117216569944869, + "max_vertex_mm": 7.6881147679784005, + "record_index": 25, + "frame_index": 76 + }, + { + "mean_vertex_mm": 1.7111287826213217, + "max_vertex_mm": 7.6884011238513645, + "record_index": 25, + "frame_index": 77 + }, + { + "mean_vertex_mm": 1.7097369880209685, + "max_vertex_mm": 7.699401474996824, + "record_index": 25, + "frame_index": 75 + }, + { + "mean_vertex_mm": 1.7083990542935454, + "max_vertex_mm": 7.4450971185912875, + "record_index": 4, + "frame_index": 338 + }, + { + "mean_vertex_mm": 1.7073235392460455, + "max_vertex_mm": 7.721470597570369, + "record_index": 25, + "frame_index": 78 + }, + { + "mean_vertex_mm": 1.7065857203520056, + "max_vertex_mm": 7.523031022505265, + "record_index": 27, + "frame_index": 453 + }, + { + "mean_vertex_mm": 1.7055239844073071, + "max_vertex_mm": 7.706417654067612, + "record_index": 25, + "frame_index": 74 + }, + { + "mean_vertex_mm": 1.70442843989518, + "max_vertex_mm": 7.545860955202595, + "record_index": 27, + "frame_index": 452 + }, + { + "mean_vertex_mm": 1.703834202415628, + "max_vertex_mm": 7.553416587978311, + "record_index": 23, + "frame_index": 538 + }, + { + "mean_vertex_mm": 1.7033565093046774, + "max_vertex_mm": 7.5469598906156055, + "record_index": 23, + "frame_index": 539 + } + ] + } + }, + "ARCTIC_s09": { + "frames": 17699, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 17699, + "mean": 0.323981587412602, + "p95": 0.35282059308904656, + "max": 0.39064035854908785 + }, + "root_relative_mpjpe_mm": { + "count": 17699, + "mean": 0.441603346254122, + "p95": 0.4751747390944941, + "max": 0.5361388249244332 + }, + "mpvpe_mm": { + "count": 17699, + "mean": 0.49487717418159727, + "p95": 0.5137236191909984, + "max": 0.5511479015923854 + }, + "pa_mpjpe_mm": { + "count": 17699, + "mean": 0.31823433149112806, + "p95": 0.34614533329624836, + "max": 0.3810719533405717 + }, + "max_vertex_mm": { + "count": 17699, + "mean": 1.7528494126687486, + "p95": 1.7956273853941946, + "max": 1.8510787806539133 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 0.49487717418159727, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 0.5137236191909984, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 1.8510787806539133, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 0.4345805483199847, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.0566286889532597, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 17699, + "mpvpe_mm": { + "count": 17699, + "mean": 0.4948771741815972, + "p95": 0.5137236191909985, + "max": 0.5511479015923854 + }, + "max_vertex_mm": { + "count": 17699, + "mean": 1.7528494126687486, + "p95": 1.7956273853941946, + "max": 1.8510787806539133 + }, + "wrist_adjustment_mm": { + "count": 17699, + "mean": 0.33336059144259056, + "p95": 0.37420614647982664, + "max": 0.4345805483199847 + }, + "local_pose_adjustment_rms_rad": { + "count": 17699, + "mean": 0.04211032215544707, + "p95": 0.045936043549031386, + "max": 0.0566286889532597 + }, + "projection_disagreement_px": { + "count": 369899, + "mean": 0.257937081312986, + "p95": 0.520476833864324, + "max": 0.962448496942575 + }, + "scaled_pose_gradient": { + "count": 17699, + "mean": 0.000746717188048522, + "p95": 0.0016235806962768481, + "max": 0.015379464612705614 + }, + "free_wrist_gradient_max": 8.889955438462493e-11, + "conditional_wrist_identity_error_mm": 1.1443916996305594e-13, + "shared_beta_gradient_max": 1.1722704561116515e-05, + "worst_frames": [ + { + "mean_vertex_mm": 0.5511479015923854, + "max_vertex_mm": 1.7211178939336285, + "record_index": 25, + "frame_index": 326 + }, + { + "mean_vertex_mm": 0.5506159337461983, + "max_vertex_mm": 1.7159670221906558, + "record_index": 25, + "frame_index": 327 + }, + { + "mean_vertex_mm": 0.5473367901856242, + "max_vertex_mm": 1.722651868270408, + "record_index": 25, + "frame_index": 325 + }, + { + "mean_vertex_mm": 0.546927924020121, + "max_vertex_mm": 1.7310062272817341, + "record_index": 36, + "frame_index": 423 + }, + { + "mean_vertex_mm": 0.5467153233227843, + "max_vertex_mm": 1.7380589687057764, + "record_index": 36, + "frame_index": 422 + }, + { + "mean_vertex_mm": 0.5465002773921739, + "max_vertex_mm": 1.706911913579657, + "record_index": 36, + "frame_index": 424 + }, + { + "mean_vertex_mm": 0.5463155377463044, + "max_vertex_mm": 1.706657051780107, + "record_index": 25, + "frame_index": 328 + }, + { + "mean_vertex_mm": 0.5456606237604639, + "max_vertex_mm": 1.7490205580290314, + "record_index": 36, + "frame_index": 420 + }, + { + "mean_vertex_mm": 0.5455485156500781, + "max_vertex_mm": 1.74306612204294, + "record_index": 36, + "frame_index": 421 + }, + { + "mean_vertex_mm": 0.5454314314098319, + "max_vertex_mm": 1.7469739738357826, + "record_index": 36, + "frame_index": 419 + } + ] + } + }, + "ARCTIC_s10": { + "frames": 11655, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 11655, + "mean": 0.5948513272460592, + "p95": 0.6305263700976087, + "max": 0.6681218707371616 + }, + "root_relative_mpjpe_mm": { + "count": 11655, + "mean": 1.2243622477451153, + "p95": 1.292762577672015, + "max": 1.352246539324624 + }, + "mpvpe_mm": { + "count": 11655, + "mean": 0.8591563763557747, + "p95": 0.9073033935963973, + "max": 0.9206699303730203 + }, + "pa_mpjpe_mm": { + "count": 11655, + "mean": 0.577203659208211, + "p95": 0.6136443829792851, + "max": 0.6418065585152543 + }, + "max_vertex_mm": { + "count": 11655, + "mean": 2.9762201142479436, + "p95": 3.084000004830541, + "max": 3.1867487348396826 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 0.8591563763557747, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 0.9073033935963973, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 3.1867487348396826, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 1.2354373772070717, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.09393261792342705, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 11655, + "mpvpe_mm": { + "count": 11655, + "mean": 0.8591563763557746, + "p95": 0.9073033935963973, + "max": 0.9206699303730203 + }, + "max_vertex_mm": { + "count": 11655, + "mean": 2.9762201142479436, + "p95": 3.084000004830541, + "max": 3.1867487348396826 + }, + "wrist_adjustment_mm": { + "count": 11655, + "mean": 1.1117543432874237, + "p95": 1.171390306569584, + "max": 1.2354373772070717 + }, + "local_pose_adjustment_rms_rad": { + "count": 11655, + "mean": 0.07601429609585801, + "p95": 0.08419086128208385, + "max": 0.09393261792342705 + }, + "projection_disagreement_px": { + "count": 239144, + "mean": 0.5045823784075855, + "p95": 1.1981452147459322, + "max": 2.242398760940515 + }, + "scaled_pose_gradient": { + "count": 11655, + "mean": 1.4010903616752563e-05, + "p95": 2.3083801464547177e-05, + "max": 0.00032153737893436505 + }, + "free_wrist_gradient_max": 8.962786068877904e-11, + "conditional_wrist_identity_error_mm": 1.1443916996305594e-13, + "shared_beta_gradient_max": 9.416746064933715e-08, + "worst_frames": [ + { + "mean_vertex_mm": 0.9206699303730203, + "max_vertex_mm": 3.0070328022554187, + "record_index": 20, + "frame_index": 267 + }, + { + "mean_vertex_mm": 0.9205340764782055, + "max_vertex_mm": 3.0022916055882725, + "record_index": 13, + "frame_index": 480 + }, + { + "mean_vertex_mm": 0.9203388484296782, + "max_vertex_mm": 3.003235909591674, + "record_index": 20, + "frame_index": 266 + }, + { + "mean_vertex_mm": 0.9203103224877848, + "max_vertex_mm": 3.000374802373219, + "record_index": 13, + "frame_index": 479 + }, + { + "mean_vertex_mm": 0.9200341358211083, + "max_vertex_mm": 2.9653926986169226, + "record_index": 0, + "frame_index": 396 + }, + { + "mean_vertex_mm": 0.9197714560652013, + "max_vertex_mm": 2.9648997844050373, + "record_index": 0, + "frame_index": 397 + }, + { + "mean_vertex_mm": 0.9195282476566068, + "max_vertex_mm": 2.963756518082766, + "record_index": 0, + "frame_index": 395 + }, + { + "mean_vertex_mm": 0.9194490143610604, + "max_vertex_mm": 2.9639970509049953, + "record_index": 0, + "frame_index": 398 + }, + { + "mean_vertex_mm": 0.9194317134532536, + "max_vertex_mm": 3.012311692154931, + "record_index": 20, + "frame_index": 268 + }, + { + "mean_vertex_mm": 0.9194219881372893, + "max_vertex_mm": 2.987700289992375, + "record_index": 8, + "frame_index": 82 + } + ] + } + }, + "H2O_subject1": { + "frames": 17807, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 17807, + "mean": 0.5709988717777805, + "p95": 0.5975266387357364, + "max": 0.6604190771895423 + }, + "root_relative_mpjpe_mm": { + "count": 17807, + "mean": 0.7645941247965417, + "p95": 0.8503597275686932, + "max": 0.9702778991594472 + }, + "mpvpe_mm": { + "count": 17807, + "mean": 1.055893539400041, + "p95": 1.0801252801038455, + "max": 1.1142229446893543 + }, + "pa_mpjpe_mm": { + "count": 17807, + "mean": 0.5765591789418377, + "p95": 0.5993720290322909, + "max": 0.6574563931615541 + }, + "max_vertex_mm": { + "count": 17807, + "mean": 5.163659545017711, + "p95": 5.311179277127787, + "max": 5.460973247681051 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 1.055893539400041, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 1.0801252801038455, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 5.460973247681051, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 0.7343463628281965, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.12588628092908635, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 17807, + "mpvpe_mm": { + "count": 17807, + "mean": 1.055893539400041, + "p95": 1.0801252801038457, + "max": 1.1142229446893541 + }, + "max_vertex_mm": { + "count": 17807, + "mean": 5.163659545017711, + "p95": 5.311179277127787, + "max": 5.460973247681051 + }, + "wrist_adjustment_mm": { + "count": 17807, + "mean": 0.5155229605321572, + "p95": 0.6349979436714087, + "max": 0.7343463628281965 + }, + "local_pose_adjustment_rms_rad": { + "count": 17807, + "mean": 0.10729792532102651, + "p95": 0.1170228760789417, + "max": 0.12588628092908635 + }, + "projection_disagreement_px": { + "count": 373947, + "mean": 0.3689294676636142, + "p95": 0.8682852482895573, + "max": 2.3707790792633032 + }, + "scaled_pose_gradient": { + "count": 17807, + "mean": 1.2846871317558638e-05, + "p95": 2.568930887037707e-05, + "max": 0.0058939592903804496 + }, + "free_wrist_gradient_max": 8.779110771683918e-11, + "conditional_wrist_identity_error_mm": 1.1443916996305594e-13, + "shared_beta_gradient_max": 5.1711655513453055e-08, + "worst_frames": [ + { + "mean_vertex_mm": 1.1142229446893541, + "max_vertex_mm": 5.437617785194362, + "record_index": 41, + "frame_index": 57 + }, + { + "mean_vertex_mm": 1.1106841287815346, + "max_vertex_mm": 5.412072687096123, + "record_index": 41, + "frame_index": 58 + }, + { + "mean_vertex_mm": 1.1091970449557744, + "max_vertex_mm": 5.390049118185268, + "record_index": 41, + "frame_index": 56 + }, + { + "mean_vertex_mm": 1.1077785872890866, + "max_vertex_mm": 5.400378037825669, + "record_index": 41, + "frame_index": 51 + }, + { + "mean_vertex_mm": 1.1069212860315736, + "max_vertex_mm": 5.380569287970145, + "record_index": 41, + "frame_index": 53 + }, + { + "mean_vertex_mm": 1.106518450849887, + "max_vertex_mm": 5.382307986600824, + "record_index": 41, + "frame_index": 52 + }, + { + "mean_vertex_mm": 1.1063678341260736, + "max_vertex_mm": 5.391343900624949, + "record_index": 41, + "frame_index": 59 + }, + { + "mean_vertex_mm": 1.1063481704639495, + "max_vertex_mm": 5.382188141592368, + "record_index": 41, + "frame_index": 55 + }, + { + "mean_vertex_mm": 1.1058787730453226, + "max_vertex_mm": 5.397541290983635, + "record_index": 26, + "frame_index": 19 + }, + { + "mean_vertex_mm": 1.1053394096794777, + "max_vertex_mm": 5.384348294171555, + "record_index": 41, + "frame_index": 50 + } + ] + } + }, + "H2O_subject2": { + "frames": 19755, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 19755, + "mean": 1.4444676209034273, + "p95": 1.5517704268330421, + "max": 1.6459405155354472 + }, + "root_relative_mpjpe_mm": { + "count": 19755, + "mean": 2.441726089985031, + "p95": 2.5823358496437216, + "max": 2.7080337370877516 + }, + "mpvpe_mm": { + "count": 19755, + "mean": 2.54019047877839, + "p95": 2.6576726778449613, + "max": 2.7366807692655724 + }, + "pa_mpjpe_mm": { + "count": 19755, + "mean": 1.4218694993080545, + "p95": 1.5281404023370349, + "max": 1.6126607891866767 + }, + "max_vertex_mm": { + "count": 19755, + "mean": 9.305286146986015, + "p95": 9.629666107118743, + "max": 9.866526715645149 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 2.54019047877839, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 2.6576726778449613, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 9.866526715645149, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 2.467031608707351, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.255865240245347, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 19755, + "mpvpe_mm": { + "count": 19755, + "mean": 2.54019047877839, + "p95": 2.657672677844961, + "max": 2.736680769265572 + }, + "max_vertex_mm": { + "count": 19755, + "mean": 9.305286146986015, + "p95": 9.629666107118743, + "max": 9.866526715645149 + }, + "wrist_adjustment_mm": { + "count": 19755, + "mean": 2.0634562147464233, + "p95": 2.273382514668867, + "max": 2.4670316087073507 + }, + "local_pose_adjustment_rms_rad": { + "count": 19755, + "mean": 0.2167784112310339, + "p95": 0.23332025844880833, + "max": 0.255865240245347 + }, + "projection_disagreement_px": { + "count": 414855, + "mean": 1.1072674583244564, + "p95": 2.2493287894559355, + "max": 4.311432453443202 + }, + "scaled_pose_gradient": { + "count": 19755, + "mean": 1.3541217082424115e-05, + "p95": 2.0493926433376982e-05, + "max": 0.0006362025432354797 + }, + "free_wrist_gradient_max": 8.08562106158206e-11, + "conditional_wrist_identity_error_mm": 1.1194008084984329e-13, + "shared_beta_gradient_max": 6.004771667644489e-08, + "worst_frames": [ + { + "mean_vertex_mm": 2.736680769265572, + "max_vertex_mm": 9.572784406123438, + "record_index": 3, + "frame_index": 784 + }, + { + "mean_vertex_mm": 2.7360376835623694, + "max_vertex_mm": 9.506445851015945, + "record_index": 31, + "frame_index": 851 + }, + { + "mean_vertex_mm": 2.735316344764799, + "max_vertex_mm": 9.45397906957213, + "record_index": 31, + "frame_index": 852 + }, + { + "mean_vertex_mm": 2.7353114677448485, + "max_vertex_mm": 9.54416107407421, + "record_index": 31, + "frame_index": 850 + }, + { + "mean_vertex_mm": 2.7351232663448304, + "max_vertex_mm": 9.517390238255024, + "record_index": 31, + "frame_index": 884 + }, + { + "mean_vertex_mm": 2.7339726321829922, + "max_vertex_mm": 9.59736000561152, + "record_index": 3, + "frame_index": 785 + }, + { + "mean_vertex_mm": 2.7339232350891405, + "max_vertex_mm": 9.552372312421756, + "record_index": 3, + "frame_index": 783 + }, + { + "mean_vertex_mm": 2.733606885790698, + "max_vertex_mm": 9.587378973570583, + "record_index": 3, + "frame_index": 786 + }, + { + "mean_vertex_mm": 2.7333480762710867, + "max_vertex_mm": 9.47398067767814, + "record_index": 31, + "frame_index": 883 + }, + { + "mean_vertex_mm": 2.732832829304919, + "max_vertex_mm": 9.420970343693986, + "record_index": 31, + "frame_index": 853 + } + ] + } + }, + "H2O_subject3": { + "frames": 10022, + "four_mm": { + "absolute_mpjpe_mm": { + "count": 10022, + "mean": 0.868005333096278, + "p95": 0.9035908610912367, + "max": 0.9502311969307036 + }, + "root_relative_mpjpe_mm": { + "count": 10022, + "mean": 0.9722497835344045, + "p95": 1.0443284506432877, + "max": 1.163552803306032 + }, + "mpvpe_mm": { + "count": 10022, + "mean": 1.6313434340494806, + "p95": 1.6825759566197922, + "max": 1.7028371008052838 + }, + "pa_mpjpe_mm": { + "count": 10022, + "mean": 0.8351174572283151, + "p95": 0.881847330532826, + "max": 0.9301832826926147 + }, + "max_vertex_mm": { + "count": 10022, + "mean": 8.061024787658916, + "p95": 8.269196430197425, + "max": 8.445823388894581 + } + }, + "geometry_review": { + "geometry_review_pass": true, + "failures": [], + "checks": { + "mesh_mean_mm": { + "value": 1.6313434340494806, + "limit": 5.0 + }, + "mesh_frame_p95_mm": { + "value": 1.6825759566197922, + "limit": 8.0 + }, + "worst_vertex_mm": { + "value": 8.445823388894581, + "limit": 30.0 + }, + "worst_wrist_adjustment_mm": { + "value": 0.8222857619017607, + "limit": 20.0 + }, + "worst_local_pose_rms_rad": { + "value": 0.18303790239359904, + "limit": 0.5 + } + }, + "gradient_stationarity_is_not_an_acceptance_gate": true, + "not_a_global_optimality_claim": true + }, + "diagnostics": { + "frames": 10022, + "mpvpe_mm": { + "count": 10022, + "mean": 1.6313434340494806, + "p95": 1.6825759566197922, + "max": 1.7028371008052836 + }, + "max_vertex_mm": { + "count": 10022, + "mean": 8.061024787658916, + "p95": 8.269196430197425, + "max": 8.445823388894581 + }, + "wrist_adjustment_mm": { + "count": 10022, + "mean": 0.5405269686942896, + "p95": 0.6457414924086119, + "max": 0.8222857619017607 + }, + "local_pose_adjustment_rms_rad": { + "count": 10022, + "mean": 0.16507466603726786, + "p95": 0.17051074937803437, + "max": 0.18303790239359904 + }, + "projection_disagreement_px": { + "count": 210462, + "mean": 0.6483194534521236, + "p95": 1.7747057198481606, + "max": 4.625628620385631 + }, + "scaled_pose_gradient": { + "count": 10022, + "mean": 9.380500236646629e-06, + "p95": 1.8656058849975368e-05, + "max": 0.001337245486733462 + }, + "free_wrist_gradient_max": 8.672884632687783e-11, + "conditional_wrist_identity_error_mm": 1.1210126175528405e-13, + "shared_beta_gradient_max": 1.961970169936375e-08, + "worst_frames": [ + { + "mean_vertex_mm": 1.7028371008052836, + "max_vertex_mm": 7.798610843659563, + "record_index": 18, + "frame_index": 229 + }, + { + "mean_vertex_mm": 1.7025771826066913, + "max_vertex_mm": 7.786937699652141, + "record_index": 18, + "frame_index": 231 + }, + { + "mean_vertex_mm": 1.7023180884761426, + "max_vertex_mm": 7.7917800498101215, + "record_index": 18, + "frame_index": 230 + }, + { + "mean_vertex_mm": 1.7022339028367859, + "max_vertex_mm": 7.780332940899791, + "record_index": 18, + "frame_index": 232 + }, + { + "mean_vertex_mm": 1.7017784815587693, + "max_vertex_mm": 7.801065172666191, + "record_index": 18, + "frame_index": 228 + }, + { + "mean_vertex_mm": 1.701369731561119, + "max_vertex_mm": 7.764290768134367, + "record_index": 19, + "frame_index": 376 + }, + { + "mean_vertex_mm": 1.7012518216250445, + "max_vertex_mm": 7.942957868025567, + "record_index": 4, + "frame_index": 236 + }, + { + "mean_vertex_mm": 1.7010807794367555, + "max_vertex_mm": 7.763792913073132, + "record_index": 19, + "frame_index": 377 + }, + { + "mean_vertex_mm": 1.7010263046825254, + "max_vertex_mm": 7.77142222157684, + "record_index": 18, + "frame_index": 233 + }, + { + "mean_vertex_mm": 1.7007826185516282, + "max_vertex_mm": 7.767175104807747, + "record_index": 19, + "frame_index": 395 + } + ] + } + } + }, + "failures": [] +} diff --git a/home/wuyifan/a7_canonical_gt_rotationfix_20260930/cache/native_inventory.json b/home/wuyifan/a7_canonical_gt_rotationfix_20260930/cache/native_inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..e53ec3630ee01461456cdc811efe9d5e2f7f60e8 --- /dev/null +++ b/home/wuyifan/a7_canonical_gt_rotationfix_20260930/cache/native_inventory.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4394d2ab4428ff8b540cd9edbe40904efbefd67c4bb46f180206862513af0e8 +size 16731203 diff --git a/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json b/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..cad31aa3c066d03a4d6eaa558ffe5466682ba807 --- /dev/null +++ b/home/wuyifan/a7_canonical_gt_rotationfix_20260930/label_inventory.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0bd3135ee5cdda31e50109cefc8fc8083b0d57d9646c9eb6d2f7aeab9e904b62 +size 16840820 diff --git a/home/wuyifan/a7_canonical_gt_rotationfix_20260930/migration.json b/home/wuyifan/a7_canonical_gt_rotationfix_20260930/migration.json new file mode 100644 index 0000000000000000000000000000000000000000..b7b482f0a6de1b34ef7c35cbd538cd5ba69477c8 --- /dev/null +++ b/home/wuyifan/a7_canonical_gt_rotationfix_20260930/migration.json @@ -0,0 +1,1206 @@ +{ + "complete": true, + "new_native_inventory_sha256": "b4394d2ab4428ff8b540cd9edbe40904efbefd67c4bb46f180206862513af0e8", + "upstream_native_inventory_sha256": "99667c7bf9c48eba4d339af41b5eacf3cc2bc1fddf557a04597d30fb22b85ab5", + "records": [ + { + "source": "ARCTIC", + "recording": "s01/box_use_01", + "old_sha256": "6d4ec59f9615534af41f17d223e7c0447a92c114f943c098af89cd88a19c4c48", + "new_sha256": "1936dedac998f977cd462016d5e9f0ff044b7b5084e71774326177d6ad01f2dd", + "frames": 1, + "old_max_error_deg": 0.02028575291566689, + "new_max_error_deg": 1.4588707476255703e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/box_use_02", + "old_sha256": "99161596e750e5f7ee122772239c6552b2b44c697dd86d3646f66a00091460d0", + "new_sha256": "65ed8df9fb4404fae42f25639de7eead8a5e420b0e2a73cacb136440a2d12b77", + "frames": 2, + "old_max_error_deg": 0.078446672064873, + "new_max_error_deg": 1.041206260775764e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/capsulemachine_grab_01", + "old_sha256": "2d4793da20454660a38e8cc6448e3d30035866b70058ff546b27f0dd7ab61878", + "new_sha256": "a6eeade2287ef01907f9d2a959183c34f24b541d10ed0666d51131b469ff63be", + "frames": 1, + "old_max_error_deg": 0.10023217791943595, + "new_max_error_deg": 1.4334018256758036e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/capsulemachine_use_01", + "old_sha256": "98188235540be0850971b40e1b428d2fbed8243adde2917aba25fd6516a58522", + "new_sha256": "48167b6ec43ec1a7890792fbbcd7600f96d740f1ba6b6a3d24c52ad11fb8439a", + "frames": 2, + "old_max_error_deg": 0.02508102324526858, + "new_max_error_deg": 9.845886249161926e-07 + }, + { + "source": "ARCTIC", + "recording": "s01/espressomachine_use_01", + "old_sha256": "761ec39c3b03a7b8f1531c46fa25bdebae9e82cd26916c1db9668ca3ff233742", + "new_sha256": "886c90434d7d7e85bb62102b9dc4bd2469e47becb50ade3615c1ee675c1c4802", + "frames": 1, + "old_max_error_deg": 0.029381876082835285, + "new_max_error_deg": 5.43664948691879e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/ketchup_grab_01", + "old_sha256": "af6fa5d719b523bc75b539c61be03c9fc66bf20ebae7da67eb9a1a8871988c43", + "new_sha256": "ce9c4662223c36bb165af44ed55f422fce6aeb5d94dd3c011237b17432ba6ea8", + "frames": 3, + "old_max_error_deg": 0.025705584222564602, + "new_max_error_deg": 2.895422899519018e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/ketchup_use_02", + "old_sha256": "5919b7a6092dd658382c36c9b8566b0b2da4b1dbf657e982b0d583165829a4db", + "new_sha256": "8b75d9779aca8658b78f00d0cc1bcfc9490e952c9c1795810049494a566f1b5d", + "frames": 4, + "old_max_error_deg": 0.02294085024416835, + "new_max_error_deg": 3.086301318725179e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/laptop_grab_01", + "old_sha256": "6dba54bb20b3fe786a646680cacfe8ab901448278fd9765032d8b1a6a7db8d06", + "new_sha256": "5a72d8eddd871cae2ce0b2d5efc4a44139c3fc99aed9e8c254fe4c58ea65bc35", + "frames": 2, + "old_max_error_deg": 0.03363661349188469, + "new_max_error_deg": 3.7158120345014133e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/laptop_use_01", + "old_sha256": "7f0cacc417cde25796a98385f0cde2b2efcc5b060762e450130fab8e8694ccaf", + "new_sha256": "74ebe00137389cf9fea637e5d15a73b274d352e943a1110aa5adde4b8a44b035", + "frames": 1, + "old_max_error_deg": 0.04706415846952414, + "new_max_error_deg": 2.593967727242408e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/laptop_use_02", + "old_sha256": "c8f5a8b2876c4ffb79f7211b4c97cff92ebe634bba38a21c4908c0ff632bdc70", + "new_sha256": "65cab31553cfefaeae74bfb9cb90d4864212adf635c1ec66b540164268907515", + "frames": 1, + "old_max_error_deg": 0.03389339454697543, + "new_max_error_deg": 1.0824314429180193e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/laptop_use_03", + "old_sha256": "82c33b83fbf6228c71d7109c04f60fb23b12a033a5f5eb851e526c40c95781f6", + "new_sha256": "7fccaa6c575693bde98f23e385c9d1856bbd782d4b1648f2b234c0d992a7a0ff", + "frames": 3, + "old_max_error_deg": 1.191952106862281, + "new_max_error_deg": 2.1859651883344224e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/laptop_use_04", + "old_sha256": "4e03d663ea094304f1777651776320c424ae0e6bdb4b23ed41d6ad45d62fad4a", + "new_sha256": "d47a7f44c85c127fce36567904e4918830ed513b9e0fecdc0b68aed48063d410", + "frames": 7, + "old_max_error_deg": 0.16516333229109859, + "new_max_error_deg": 3.4001826963619067e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/microwave_use_01", + "old_sha256": "8591c7476979696793035162e9eecf4a378683d034f67ec4d103740efeb040b1", + "new_sha256": "2104ef4ccd1075e0a76a1c20ddc5d1983d71ea2684f3341d4c91c581706a3c76", + "frames": 2, + "old_max_error_deg": 0.12153307155342105, + "new_max_error_deg": 8.82896127963264e-07 + }, + { + "source": "ARCTIC", + "recording": "s01/mixer_grab_01", + "old_sha256": "1c495a72fb2f7cc86c85949c421ed8b52dac6c162c964a21fae59dc953a765a5", + "new_sha256": "2c8f3f140083cc55b2d0b4139503fbd130a89ea67c25dbf01f97ee08e7432b9e", + "frames": 2, + "old_max_error_deg": 0.019992315654703417, + "new_max_error_deg": 2.0986841286889787e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/mixer_use_01", + "old_sha256": "0ac40f94c4e5c1ac0407e6830d00da93b8f0e5c7dd060679600cf68a25ba53e8", + "new_sha256": "552b41b3c7201f99ed3f1f10aecd5d50932a4985883540bc7a8e3a118c25a6b4", + "frames": 1, + "old_max_error_deg": 0.04516317038620527, + "new_max_error_deg": 3.22531158762749e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/mixer_use_02", + "old_sha256": "24ba408a17382e85df785cc66dec01d1280c9c127856b6344e24b2c744663531", + "new_sha256": "977785b79b736606d42ec2310560a2025593c988749bba027c55992a9159b5b7", + "frames": 1, + "old_max_error_deg": 0.03193274753499086, + "new_max_error_deg": 4.723683265375636e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/notebook_use_02", + "old_sha256": "0e9fa446c4506d91313eb192528f37881c3d1b0423ebc89440ae95aea24bc32d", + "new_sha256": "601fe6cfd14d287f421cb551c1d160e5f3931b6ed9950feeeaff9290a0420c7b", + "frames": 2, + "old_max_error_deg": 0.2607729594310595, + "new_max_error_deg": 7.26862557905166e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/phone_use_02", + "old_sha256": "391647fa7f39fe1c790e8fb31a761b358fdec38cf9cbb92be19fa12eaacf05ff", + "new_sha256": "b582a6dfacbcdd911f6af1dabd34a925ffe35469b0064d09d081fd16ddbd4b72", + "frames": 4, + "old_max_error_deg": 0.26772696836662874, + "new_max_error_deg": 2.1891502748189678e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/scissors_grab_01", + "old_sha256": "4093fb7bdc432e45e467da7b62b4e5f088968a6f404baa500e99c4f8c4f5a6de", + "new_sha256": "ea8eecd2af3190097ac06107b67e59dccf5257deff9f690ffad4ed2bf73882c3", + "frames": 6, + "old_max_error_deg": 0.05113795798083718, + "new_max_error_deg": 2.4338768209375095e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/scissors_use_01", + "old_sha256": "c6c7da40e47e7d9a4f8699fce0f3160f29b27fc2e34253e9c47a377e7857779a", + "new_sha256": "807bd0bc7fa9e7ddb6d89be81de50593941b66c2487131b0151b0bf279239930", + "frames": 3, + "old_max_error_deg": 0.042461833597166716, + "new_max_error_deg": 4.257081708737704e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/scissors_use_02", + "old_sha256": "54b52e3848ce105dedbf9d4cf7efde848d49dde4af1510c659541599c6c52565", + "new_sha256": "2300629b9c7afbcd9773624086ad8df55f483bc021b8535299e6e525cff0903c", + "frames": 4, + "old_max_error_deg": 0.026547064329523414, + "new_max_error_deg": 3.2698704261728937e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/waffleiron_grab_01", + "old_sha256": "91987cc28f547dec19db91ebcae4dad95154fe08adbc4b695130e33ebe81c14b", + "new_sha256": "8e00c44e3858cfa2f84a5fdc30678ea416e621e169b111a7b5fa55b4b64c9c81", + "frames": 7, + "old_max_error_deg": 0.06391554796683158, + "new_max_error_deg": 2.369099067245149e-06 + }, + { + "source": "ARCTIC", + "recording": "s01/waffleiron_use_02", + "old_sha256": "483ab4785265dd9b74bafa02c6197a2b7ea70f90fbc84c8882668c893f1efa48", + "new_sha256": "106b38db661d73469ec64bda0b84a98782a0f772e26f7a03b3d45f3b713c3498", + "frames": 4, + "old_max_error_deg": 0.24546647398715762, + "new_max_error_deg": 3.3390944158515312e-06 + }, + { + "source": "ARCTIC", + "recording": "s02/espressomachine_grab_01", + "old_sha256": "aa8beaf3f1c6e5132d41b840ce913270fcdd109845110043976ce6faeacea09d", + "new_sha256": "d58785a3d19af10805100fc282b441026a9e52cf33ae71cff2886c5d733d435b", + "frames": 1, + "old_max_error_deg": 0.012021324815102678, + "new_max_error_deg": 1.7425115289293111e-06 + }, + { + "source": "ARCTIC", + "recording": "s02/ketchup_use_03", + "old_sha256": "352e326d186a696359815d754afd29e9363bda8da87e02629b40b3ce6abd7547", + "new_sha256": "f2ac990f29a8d94051f43244303bb79f8c83271f0cd55ac905d2e01b32393091", + "frames": 1, + "old_max_error_deg": 0.02266508607705195, + "new_max_error_deg": 2.5355320941368486e-06 + }, + { + "source": "ARCTIC", + "recording": "s02/microwave_use_01", + "old_sha256": "3bb1d03951d53255abf9d41edad24f30910f8bca16d38c3813c4b96def167d83", + "new_sha256": "d721c096734996db0a70353f10ccbc15016bf1e3a0e34fc4ea0b1580d18d2c51", + "frames": 1, + "old_max_error_deg": 0.02460350415437318, + "new_max_error_deg": 2.463911523626816e-06 + }, + { + "source": "ARCTIC", + "recording": "s02/mixer_use_01", + "old_sha256": "a2d07fd9b12cb2ce847bde0a1d2367de1f324570754f44c753e316c21eded7bf", + "new_sha256": "5068da7a60e5af22a6a2afcfc65c8be357e00a07adef2d99f1b16336aac90f8d", + "frames": 1, + "old_max_error_deg": 0.026628642338947083, + "new_max_error_deg": 5.236804286620188e-06 + }, + { + "source": "ARCTIC", + "recording": "s02/mixer_use_02", + "old_sha256": "a0f9d2e79d22a8e54a5551a25009764f01b1e2fab50c8468713c28b998cf650a", + "new_sha256": "865a6fb40ad709b3f629e5a4a00d2e3b3690a8f0d0ff86296846470110efe0eb", + "frames": 3, + "old_max_error_deg": 0.045377024556800864, + "new_max_error_deg": 3.8012356075881316e-06 + }, + { + "source": "ARCTIC", + "recording": "s02/mixer_use_04", + "old_sha256": "7ae651d6153a9204d6884514bfc57a6fdbfc2cc711cc673a37c2c1c3a3651155", + "new_sha256": "11b047aac5dc01fd77f99bf92215e06833a428b5d36900e0781c8610854615da", + "frames": 1, + "old_max_error_deg": 0.011505042425627105, + "new_max_error_deg": 1.4614174156979338e-06 + }, + { + "source": "ARCTIC", + "recording": "s02/notebook_use_02", + "old_sha256": "a9be8297ffafc34f73e7559547d61553346ae5dd8022c9b5ee06e22df9d5ef99", + "new_sha256": "fac05ef19985ddf07ad68e871bc8e361c7b0117d73028d3f3cc6ea807430e718", + "frames": 1, + "old_max_error_deg": 0.022723187101548442, + "new_max_error_deg": 5.073797043298063e-06 + }, + { + "source": "ARCTIC", + "recording": "s02/scissors_use_02", + "old_sha256": "7cf98a9348dd203f172e5219c9eede85e38f6ce8819727abbb7143a27ef340d4", + "new_sha256": "55a436bdf64e9704e526b19622ae8a07099e03480e760b5c42f2f3e2b21bbcd8", + "frames": 1, + "old_max_error_deg": 0.01287055778051425, + "new_max_error_deg": 1.9692355214055303e-06 + }, + { + "source": "ARCTIC", + "recording": "s02/waffleiron_use_01", + "old_sha256": "be88c7fe65d20abf618ad8a5d0efabb71bcd3942b185d3f95b7b6ff967e5ad6b", + "new_sha256": "e943b00c3d27965f388142f704bcc51f17c15e5c98d952a8877f1523ba602793", + "frames": 1, + "old_max_error_deg": 0.01903016469706164, + "new_max_error_deg": 2.6324068604933186e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/box_use_01", + "old_sha256": "52c342dd3c897c0e4ec6783c2f1659834df08134d4790e2a4364c311f57439e7", + "new_sha256": "666adfb959c95a7c9ddee8ea08591ee7523d2f7afda64978dc601a2aed609c37", + "frames": 2, + "old_max_error_deg": 0.02136624391544853, + "new_max_error_deg": 8.698546658378518e-07 + }, + { + "source": "ARCTIC", + "recording": "s04/box_use_02", + "old_sha256": "38c4f0be150a79aee91c193eccb47cae3e14c257602cd3301d2a89e9ab657cd0", + "new_sha256": "ed4ac9f9d18a524aaf5fe324d20dfe9347d96faf078bf3d0062752bae56ee86a", + "frames": 4, + "old_max_error_deg": 0.027322835288372704, + "new_max_error_deg": 1.9079844155889993e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/capsulemachine_grab_01", + "old_sha256": "46af691ecf8040bb63fa1e3b8f0d457ac661c3d3ec0271cde84ef4b683d0ddb2", + "new_sha256": "f32770c4485d08300eff484d0145c437f83b0c69cc3960b851d4dea61be2adba", + "frames": 1, + "old_max_error_deg": 0.01933741973748805, + "new_max_error_deg": 1.4410706839771026e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/capsulemachine_use_01", + "old_sha256": "43a917c8b2fc01667aadf380a1eb6f1169c7a072456e02098a9a9d29cd1b8802", + "new_sha256": "1b4a7f330ed4fb809bbe542e5a0abf841cf9f364fc2e37c0a21b09e796fe80cc", + "frames": 1, + "old_max_error_deg": 0.28665527170810434, + "new_max_error_deg": 2.2548456888225147e-07 + }, + { + "source": "ARCTIC", + "recording": "s04/capsulemachine_use_02", + "old_sha256": "104f8f81d8900b45dc01bfa862b53d56effda1089787c6b296a16bd57eb7490b", + "new_sha256": "1f228567112a1831c9fa4a2406142b304ac813a691e46c9aaf382247fac6326d", + "frames": 1, + "old_max_error_deg": 0.010278559489924802, + "new_max_error_deg": 1.7689643911291503e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/espressomachine_grab_01", + "old_sha256": "4a6400a79487c55074d45b2dbe2d091b0fc380a75ce90eb3a84d024316be6cc7", + "new_sha256": "f9119e23ebd8e083d2bc8be51e59b76682c3c7d8c6f90bb8638ffb9f3b28b6e0", + "frames": 3, + "old_max_error_deg": 0.340685779884475, + "new_max_error_deg": 2.4803434696056123e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/espressomachine_use_01_retake", + "old_sha256": "e90e7ccf329dd75ec306b7a8fc62ab71db32e26de38c8f0a7b44faddf9566405", + "new_sha256": "251c02b3ba7f2406d345b79f683e1d748b8a78fa60a430f18ab3114ed6f26e1e", + "frames": 12, + "old_max_error_deg": 0.08930492540949456, + "new_max_error_deg": 2.748446191804423e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/espressomachine_use_02", + "old_sha256": "13566934bae25955ce9432342a8a749252a0a097256f92bb70acdc9c463a09ad", + "new_sha256": "68305fb99484d8120d0147d4717ea108c760723d00651c573e403c5a8e39f0f6", + "frames": 1, + "old_max_error_deg": 0.12776311068750656, + "new_max_error_deg": 2.986241240059923e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/laptop_use_01", + "old_sha256": "4451724244e7602509e0cd023587cff0066c97b8459247618b045e9e4f999f58", + "new_sha256": "b2b0f31e1d4476c80e3447b3d09799f56d630d1d219b7aea8caa1e22718374f4", + "frames": 2, + "old_max_error_deg": 0.02407371668257271, + "new_max_error_deg": 1.3942425859862237e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/laptop_use_02", + "old_sha256": "5bee50da619e0745bda1ad9bafe30ee4468220617d08f686ffb8853c403f0a1f", + "new_sha256": "7dba503f31a7bdb961f909c2cbd0be90c9b0adf7a33b354971dbb480c442ada8", + "frames": 1, + "old_max_error_deg": 0.023087096778967104, + "new_max_error_deg": 1.0695725746380053e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/microwave_grab_01", + "old_sha256": "1b61c8bba2a22b64bca65f1b7e1107f84292dba9a493b242559bd5e1f3ee9a42", + "new_sha256": "66c1d45577dc75d222348941f38b2587d584b0d881e5a25c70c103462ab4a241", + "frames": 2, + "old_max_error_deg": 0.052515247219799915, + "new_max_error_deg": 1.6573749351295592e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/microwave_use_01", + "old_sha256": "02c8d728873a4469cea6456ce5f6b90e9c2b2b14bc6e543f34b052d34c5f1d53", + "new_sha256": "f0cf11914cf28a538319afe87a47aa201fb947c0c3db3cdb18794a11cf74fda5", + "frames": 3, + "old_max_error_deg": 0.20945776724885118, + "new_max_error_deg": 2.888762830228204e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/notebook_grab_01", + "old_sha256": "01fbedfca569843ae7848e64f3efd4e2fb6ea83801d88177aa8f16fa7f27d493", + "new_sha256": "2321b7b53c390da2347b7280f47865ae9e31ff14b1092fff78a4566e643dd098", + "frames": 2, + "old_max_error_deg": 0.04612143333928603, + "new_max_error_deg": 3.853337900186494e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/phone_use_02", + "old_sha256": "cee997aa8fb06899dd3961048c102b60b762fc1e7ec67283987c94ae4369cdc9", + "new_sha256": "ec8936cc56d1453000a97a11dfe5674dd22e05840129660e604cc190fb67ee42", + "frames": 1, + "old_max_error_deg": 0.011244879863017008, + "new_max_error_deg": 5.471524572617361e-07 + }, + { + "source": "ARCTIC", + "recording": "s04/scissors_use_01", + "old_sha256": "9538e66da5282e5b945ccbf6031fbccc3d9b752524c6f9b453ac203b7e2a6537", + "new_sha256": "dff7fa1cd7d300473aaf064ea80fad483e1b93f514c46e47847f76e6fe1ef1f7", + "frames": 3, + "old_max_error_deg": 0.2087296802063304, + "new_max_error_deg": 2.0830233900584806e-06 + }, + { + "source": "ARCTIC", + "recording": "s04/scissors_use_02", + "old_sha256": "8e7de3a903fa58c2c3da8ee73f9cc7e4c116862ca8158ba057a2e9b8e4665d30", + "new_sha256": "9957a11e9e4e3587b56caa0415f7d5c3355d1bc3cd4487568566537ec8fa3cfd", + "frames": 1, + "old_max_error_deg": 0.025201729295838197, + "new_max_error_deg": 1.0596988538107615e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/box_use_01", + "old_sha256": "06953628ebc0701e01f92710955b28367f3c950329c2beba774b56dfc109036f", + "new_sha256": "52e81ed2c2f7cf2b12aa18767c274c5774db374c4663c2d012b3384a4284d33c", + "frames": 1, + "old_max_error_deg": 0.01967049769299419, + "new_max_error_deg": 1.2421188408700628e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/box_use_02", + "old_sha256": "13dc195ba4c2710c385d26e0ff73c860846eb5b0b45641aa53be54a6b693d8f2", + "new_sha256": "f514c02eafe569a0e0d41765b7c25cb981f9d51149f4711378a68c3a8d784765", + "frames": 1, + "old_max_error_deg": 0.01484295198085541, + "new_max_error_deg": 2.332797187430803e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/capsulemachine_grab_01", + "old_sha256": "8369fc8370542f1a1b7a2bd43d1a4f2a6a17ab1d8c7c6b011c083453bfcbab63", + "new_sha256": "4387646f2aaa31eedbc913fd90d903c370b2df70042e9e77c95c0e7a307420bb", + "frames": 1, + "old_max_error_deg": 0.03269601277381102, + "new_max_error_deg": 1.8980059042635739e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/capsulemachine_use_02", + "old_sha256": "442291ee7d70c0e6b7234baa87d42e3e5c345314a1913e04728acb9033c4a832", + "new_sha256": "a1abf20b445c462194218dfb99e048f400972ca35b0f08fa3eb54b7cfb1a2290", + "frames": 2, + "old_max_error_deg": 1.7810110861237438, + "new_max_error_deg": 4.6710178687118345e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/espressomachine_use_04", + "old_sha256": "55829345ec7b766ffba68437f3ec4af9961f59634342826b5f04b1991f3adc03", + "new_sha256": "bced7f74927e727786687eff2afde32f9224d444eb27396f1b906e65b1e19cde", + "frames": 1, + "old_max_error_deg": 0.015924529750737618, + "new_max_error_deg": 2.7499608751852033e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/microwave_use_01", + "old_sha256": "7a4014cd5fd52efd85c884f7667bd622222334e4e64ce6b625f63738782f7d6b", + "new_sha256": "b7b4a81c17e71dc4fd5e05b7bdba88f6d97fa667529743de4c98be44fb537e02", + "frames": 1, + "old_max_error_deg": 0.012645671023572379, + "new_max_error_deg": 2.3051662266783858e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/microwave_use_02", + "old_sha256": "c392c477c31bb099800606867003cf72454e894c9cd40018df819aa98907faac", + "new_sha256": "c395722934aac3d5cf5cb8550887e6b0891ae168125c03615fba0552b0de9eb0", + "frames": 1, + "old_max_error_deg": 0.010854057500269791, + "new_max_error_deg": 2.1930663987602935e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/mixer_grab_01", + "old_sha256": "9d29d26c23ab986bec65198816978d424295329d19c3939950fad65f6f2fda27", + "new_sha256": "39c59451777cc96685cfe14d7bab503be9af31313be1356441cbf0e0fb9f6742", + "frames": 1, + "old_max_error_deg": 0.010590678139868807, + "new_max_error_deg": 2.4250794167524983e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/mixer_use_02", + "old_sha256": "3d79e082088294faa0c659f13a8261d4a6e09709f84f8e4eb76d0d432e5b21d3", + "new_sha256": "59260528e780118df43c01be13bfbcb5f28066dbd1149d24ece0e985fb06304c", + "frames": 2, + "old_max_error_deg": 0.018307334871846492, + "new_max_error_deg": 4.043907408867238e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/notebook_use_01", + "old_sha256": "065bb4dbe3fb54471772f458663ace3257f40dbe8057ebceb10d88f830ac3191", + "new_sha256": "8d1a97ddf31015d09ee22643e0e2f983b7dffff0ce73a0ea2cb3b09a0238ff53", + "frames": 1, + "old_max_error_deg": 0.02632126185660606, + "new_max_error_deg": 2.6765885011030645e-06 + }, + { + "source": "ARCTIC", + "recording": "s06/waffleiron_use_03", + "old_sha256": "3701b656079d526dcf5774252f7616dcaf4cc7a8cc31513d4c85ed047b54f4e8", + "new_sha256": "573aa0b6614437d6198943d638ab376c7c50f9c13b251e37954d8de243b05930", + "frames": 1, + "old_max_error_deg": 0.03221931468857697, + "new_max_error_deg": 1.6698367959678726e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/box_use_02", + "old_sha256": "3fa071cae72b10cc8069dcd7ca644319adc5c7ff31d13012aad9357717746dfd", + "new_sha256": "d99e10ff5dd0d16c71a0319fbc9bb0675fd45ceeaf5b85e62c656641763f14df", + "frames": 2, + "old_max_error_deg": 0.021756672821487907, + "new_max_error_deg": 2.1055374107118757e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/laptop_grab_01", + "old_sha256": "382cdb66f62251ea4f2106efbfbd489fd2c27dbdcd2ca80bac1e7f1a6ee8a6b4", + "new_sha256": "00f3dddd70d21f30e04c95f03950a03541d9a80c390feca7883ce93465f3338c", + "frames": 1, + "old_max_error_deg": 0.013280674621865406, + "new_max_error_deg": 1.3267456410520561e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/laptop_use_01", + "old_sha256": "3e830694006e5386fd5e28282e03d83c446bceb88968b440ecf23555de1218df", + "new_sha256": "5fb4f0e31b0dafcad41f28cd960d882131c62001044cd7c794f60ecc823ef91f", + "frames": 1, + "old_max_error_deg": 0.01841696819754015, + "new_max_error_deg": 2.4100350521354155e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/microwave_grab_01", + "old_sha256": "c828ec9d7ea3501133181dc64be1f0349186c47aee3348ba3c086930b7ddfbdb", + "new_sha256": "5de7c72156bf99cd3dc6c44531b7680a2b5584f603c0f12a8bcdfa979ecd1755", + "frames": 1, + "old_max_error_deg": 0.039526967509087615, + "new_max_error_deg": 1.7848161834558689e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/mixer_grab_01_retake", + "old_sha256": "30a743f821e00bf3e18d0c0985fd153e1b08b71957aa8a6f3c28d78cca0658f3", + "new_sha256": "453756bcb23252a4d45338d155ed4c42a67a230738596e9b1113f76b695b85a6", + "frames": 1, + "old_max_error_deg": 0.01176239139132443, + "new_max_error_deg": 2.5567732883079675e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/notebook_use_02", + "old_sha256": "2a95ed619f393c21caa364578941b4b3f6976030a23a3944136b6215edfb91e0", + "new_sha256": "d0c8b0edf32c9ff30ef3cf4a440323eaff214ae8500e9d7451137997027334c1", + "frames": 1, + "old_max_error_deg": 0.01446238546147144, + "new_max_error_deg": 5.885814616707503e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/phone_grab_01", + "old_sha256": "8b7e4f5545fded4aee3d4b725d12e9e49eb2f6753a6db24c90423eb8ea7178c4", + "new_sha256": "9033e9d4ec1a0d7ddf303e918373ea11c4850d26e271d69397bbabd9300bb037", + "frames": 1, + "old_max_error_deg": 2.886977709906265, + "new_max_error_deg": 1.341819362227359e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/phone_use_01", + "old_sha256": "bbb60b84929042c3219661b15e7e812e12091575ed6b85c73d53591bded905d3", + "new_sha256": "a6a6aae1a6526d697491e4910d671b5510282733e47dee40a4bcdaf91287aeb4", + "frames": 1, + "old_max_error_deg": 0.024429538374177488, + "new_max_error_deg": 2.3171063682717367e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/phone_use_02", + "old_sha256": "0cd36ba8d06eadcba24723c5aec380524628a1ea0360524a078434a5a220f9d4", + "new_sha256": "691b776ca828911d935c7bec2e7ad69df6d73af8bd59f6020e8ee43f02265d0f", + "frames": 3, + "old_max_error_deg": 0.10484512708298696, + "new_max_error_deg": 1.853342177484149e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/scissors_use_01", + "old_sha256": "4dbc4876da7d0a788cef02fca2e0222b6892aba52ed49be8068118aa0c6438a8", + "new_sha256": "78b4858cf6056b31ae5228a20b791eac0d66811453207f201308153a7b437a65", + "frames": 1, + "old_max_error_deg": 0.04125195608697176, + "new_max_error_deg": 1.735426973524746e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/waffleiron_grab_01", + "old_sha256": "1fca1ac0f50f18fea37e20da3237746e318ba72ac76c7635b03f36dcad7a0d87", + "new_sha256": "d25669081fdf71bd16d2100e3aeb17b4a8dcd9243924531994c5fe92113cfe25", + "frames": 2, + "old_max_error_deg": 0.017650690536717993, + "new_max_error_deg": 1.2850238750675997e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/waffleiron_use_01", + "old_sha256": "ed740c0c2e90009331ea16fe99ccfe418d99a6e60951f05d97a4d075cfd5c586", + "new_sha256": "c491d2f5ac22569b92c77254150e5c97adc2449ad426ff5f8a63c985937d3ce2", + "frames": 1, + "old_max_error_deg": 0.0338379400168366, + "new_max_error_deg": 3.0176351942785227e-06 + }, + { + "source": "ARCTIC", + "recording": "s07/waffleiron_use_02", + "old_sha256": "40c2aac9d20265ba0ea1d18edf9ab62b4225dd98dc7c1cdc940f759a5b1db987", + "new_sha256": "d1184887df66292d06d08bc5dbb26adab83a20cb39da25c855c9095d37a5dd5d", + "frames": 1, + "old_max_error_deg": 0.015255629005366868, + "new_max_error_deg": 1.2921713550569761e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/box_use_01", + "old_sha256": "57ee76fa4e0d82edfc289cb8396cff3eaaf65e04dff5dbf228a27fe4d85739ec", + "new_sha256": "dc8d76f9cd5928ff1e6bff6714aa5fb4430c37754cce23af046dec19e2fe615b", + "frames": 1, + "old_max_error_deg": 0.011397346030712335, + "new_max_error_deg": 2.158022628921257e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/box_use_02", + "old_sha256": "0f5dd53b431cec2a7f1a96a03af07c7482004bd73b7f3ae012470ec7bdd58c4a", + "new_sha256": "d1eaf226645f0c8fbdcaeb56a0f5f4743a91e437fb581d318d604e1cb1f649fc", + "frames": 1, + "old_max_error_deg": 0.013701719485873294, + "new_max_error_deg": 1.022973405204653e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/box_use_03", + "old_sha256": "e82997b64256c0eca88c6dce6db0d08d9c4e7fcd4699c376fe307683371a4278", + "new_sha256": "874e0d108d0ce35e39ea62ca0b2af2757efa4da78d02379a37a2233083e78a4e", + "frames": 1, + "old_max_error_deg": 0.03935503260402345, + "new_max_error_deg": 1.475474104310835e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/ketchup_use_01", + "old_sha256": "854a96323414bbb9b14a0e969e0db0380fcadf811b1d0fb69fab8c35f0028205", + "new_sha256": "34f0f8dd6474d6e6fe464aaa35ee11ffa01a264e83e669d57ee4cc8e4b3bde18", + "frames": 1, + "old_max_error_deg": 0.011355871156218531, + "new_max_error_deg": 1.6721678022921304e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/ketchup_use_02", + "old_sha256": "3bac9ed3f47346eb5bd8544c1c17973d51de74dda45fed9049bc4c20288ec823", + "new_sha256": "dcd31234f70682f32aaddcbc079864851f884240fe24b106fd81ff17191b21b4", + "frames": 1, + "old_max_error_deg": 0.03620223593030663, + "new_max_error_deg": 3.196406422178533e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/ketchup_use_03", + "old_sha256": "512627d7571d0d9b124cbf338541ea8c4849e73855a747cc48ef9f8f41177129", + "new_sha256": "2bbfa43c7ed56e1e2297a65d0c41bdf4ac24610bad7ab2d74f1586f02b495ad1", + "frames": 2, + "old_max_error_deg": 0.11116999237507093, + "new_max_error_deg": 3.180527724620532e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/laptop_use_02", + "old_sha256": "a27310a7e96c315968cdadbce22c32401084bfbbe3b9333c708e32fefd8df8ff", + "new_sha256": "bca907d47fa7af5fe9e2ee62d81b117bcca6b455a71bbb04e3cd14b6560ef579", + "frames": 2, + "old_max_error_deg": 0.02391208309031297, + "new_max_error_deg": 1.9035574973769656e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/laptop_use_03", + "old_sha256": "c50b557bd8ca5457e00865c96e4985125acbdd6281452fe7048a7164e44c9f4f", + "new_sha256": "e3d5a984d6b1da05ca6c0f6614b1e9e64728ded4255ff71c11989168d230e094", + "frames": 1, + "old_max_error_deg": 0.012896778385389777, + "new_max_error_deg": 1.745397485408893e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/microwave_use_01", + "old_sha256": "9e3967f2684289c27870e8e0ab7e234dd7155c3f6a8c6c8cd125c4e7228dda63", + "new_sha256": "b82c22fd5dda9cf9a24be17d7ca9ddf0d8f67704ebd0146a41c29fee49f46c91", + "frames": 1, + "old_max_error_deg": 0.01095681974654169, + "new_max_error_deg": 3.5945499207105e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/microwave_use_02", + "old_sha256": "edc8af4f8a3599ee8cfcd08226daeea5ef4d3d00afd1339584f18ef82dc30d05", + "new_sha256": "337b064c47ea7480768fdb11e6da2fb34f7b1b88103cbc2337697486bfafac19", + "frames": 2, + "old_max_error_deg": 0.018852005227437702, + "new_max_error_deg": 4.847747480473611e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/microwave_use_03", + "old_sha256": "cc2676287a546b60d4895898cb347b622ffd958690a1978d2558027ff4542e59", + "new_sha256": "610702340ae99397510a5ecebeabe51c00a9a4071d17aedecc7a1e34cb00c1b7", + "frames": 1, + "old_max_error_deg": 0.013615023664519667, + "new_max_error_deg": 1.7615094004546528e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/mixer_use_01", + "old_sha256": "983bddda36812694c68252d0ee0a07cf27990f02e967a887a269344e858c819c", + "new_sha256": "8236ccc86c068249b4b83ce086f9572ba735162f1f16dcc82fbd3f71a076bcf6", + "frames": 1, + "old_max_error_deg": 0.023354194080329214, + "new_max_error_deg": 2.8262869123536438e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/mixer_use_02", + "old_sha256": "34ae6d742f81ebbfa87cb9322512ebe8fbb7c02db34178cd477cfbd0f22be2e3", + "new_sha256": "d56714b8e0f066e3b469b2e9a29786fb3e492b3d85375fdd49622e72110e270e", + "frames": 2, + "old_max_error_deg": 0.11811014125776119, + "new_max_error_deg": 2.5660872862156856e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/mixer_use_03", + "old_sha256": "568336cf7c122f488bf23ea25dd9c2ccdc80026078e92535e4b146549e8f46e3", + "new_sha256": "aebb9b9b0f268cce346ba85a9426c26c4e81b8c6442a2ec1fd8a1530cde5a521", + "frames": 2, + "old_max_error_deg": 0.10147863692680598, + "new_max_error_deg": 7.425866331326654e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/mixer_use_04", + "old_sha256": "4c4fc828d8582600e64d243f5867964d948f2d0d3e87b3671f30700525a442f6", + "new_sha256": "ede19d03aeb5c8873fefa628f07714a71b3f8b218590827974b30a52eadace59", + "frames": 1, + "old_max_error_deg": 0.011422665846868867, + "new_max_error_deg": 1.5020432211123066e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/notebook_use_01", + "old_sha256": "85b0486bfda522cb837229fb5556ce27eda120da42100b02a155feae3bdb1873", + "new_sha256": "53328a390b62aa24dea27ed09bfd4f88cdb62896f2f5276910296a5df45a6baa", + "frames": 1, + "old_max_error_deg": 0.01771523871559872, + "new_max_error_deg": 1.535234130286378e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/phone_use_03", + "old_sha256": "ed733f0c7e1ace85cfc75e97ce7b521b0d6abe2b8315b7e69d9839ba39b978a6", + "new_sha256": "266609bfb651404fac80642cdd6e3b353b5d6d7d96d5107f8f7f37597dc63f23", + "frames": 1, + "old_max_error_deg": 0.01673232103362128, + "new_max_error_deg": 2.7026536143293036e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/scissors_use_01", + "old_sha256": "c283f143c6d116fb2dc395c6f6c53d4ab8e3089b92236ecda65aa422d8a8a018", + "new_sha256": "1ab754784c6ef615a104219c069573e81deed12ee71059ce1e7961fffa8ecd8b", + "frames": 1, + "old_max_error_deg": 0.4671619795459978, + "new_max_error_deg": 5.0765421978890425e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/scissors_use_03", + "old_sha256": "4d4c588d9b4a171dc8325443e16c7e630d244e741cf1a02f01f181c7d3865249", + "new_sha256": "12ea099948ed27908d1e5a990b7bda7cdb27d25398deade7207ec4d6db3e9b17", + "frames": 3, + "old_max_error_deg": 0.4781928591555669, + "new_max_error_deg": 3.9214247570437825e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/scissors_use_04", + "old_sha256": "2bff69e96ddb32f7ee0fc500bcfcc30558e52cbf350d6d9e6ed32cf8a0e2f548", + "new_sha256": "27c9554d3838e4f82f4fae547c3aa403767907efe16951ecc6f665d39bb97809", + "frames": 1, + "old_max_error_deg": 0.017198158984987784, + "new_max_error_deg": 4.685482431242319e-06 + }, + { + "source": "ARCTIC", + "recording": "s08/waffleiron_use_04", + "old_sha256": "29dbbbd518d76172883645c697955734879ef9e41bdb82fcdd1e18517e64b208", + "new_sha256": "9a470e29c242988d500a80ab517977b9e4f77176c79b6a021e2d0035e2487fc9", + "frames": 1, + "old_max_error_deg": 0.05303678016709874, + "new_max_error_deg": 5.161896128243181e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/capsulemachine_use_01", + "old_sha256": "82ea63f14ed0f1fb6223ffbbca1f36faf916604f566393fa50780f237d8bc77f", + "new_sha256": "218c709177936f37bc455406dcadcf05201c5b6bb1661dff076e0e1596e2eac5", + "frames": 5, + "old_max_error_deg": 0.1755820951395172, + "new_max_error_deg": 4.712939486473349e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/capsulemachine_use_04", + "old_sha256": "0854e2af8d6f0dbfe59c2039f24829ccbec0e37f9f75478d573c1c2c1bc74f16", + "new_sha256": "e42115972f7ca689f8b66a044b6fe24eaf21f49e12fc63cb2195909f2541df03", + "frames": 1, + "old_max_error_deg": 0.011934619164362366, + "new_max_error_deg": 1.5173511715106197e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/espressomachine_use_01", + "old_sha256": "bce2ebaf02188072ef76fe5f8b76e6f77c2afd1da3138bc05d66b939eb40d498", + "new_sha256": "4b9840e57b91c24a5bf4f94c5cd9037dbb3af332ca828508b76f5ecf8c860fda", + "frames": 1, + "old_max_error_deg": 0.011538022448227412, + "new_max_error_deg": 2.481231519287945e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/espressomachine_use_04", + "old_sha256": "9fd800c27537ac104b79fbd423ecd0f03f19eb5848c5a9c669401acb7344c035", + "new_sha256": "1ea53dcff335f689eda6c7af9be4e434dcb2585a2f0345935417954a30e79fb0", + "frames": 21, + "old_max_error_deg": 0.07751149773770113, + "new_max_error_deg": 5.116339873475604e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/ketchup_use_01", + "old_sha256": "c58cc31db96e6153de6487d23b234a2890ac50c3811944e15327d86649a73406", + "new_sha256": "1308786ed0430bfee46eb014e72b0dcd093007899eb313d7c3f51d3d241dc1a5", + "frames": 2, + "old_max_error_deg": 0.06588993450373085, + "new_max_error_deg": 5.711228541543684e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/ketchup_use_02", + "old_sha256": "5c760f8096982c2167e3d5b80de40781e7cba0a325ed9bd7f5c45e83e6e20954", + "new_sha256": "74064b2d3c40c73a7d21215732613b8b99008a946cc24cfe1707a2fd9c0d3572", + "frames": 2, + "old_max_error_deg": 0.03980176051903351, + "new_max_error_deg": 5.375728382365974e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/laptop_use_01", + "old_sha256": "9843b15fc8106137712c4ce1980a2a38d2230d60fab9b5cd0736baac6f2d953e", + "new_sha256": "f6184865380a03ee044ee33a58cbd33a71e0dcdd0810e3d06c36375794f19521", + "frames": 1, + "old_max_error_deg": 0.013250827413909417, + "new_max_error_deg": 3.3323933138494515e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/laptop_use_02", + "old_sha256": "ad76061e5e53c7a23482e0a33e92a3a1df976ed685e3209c0667f6d025f478ca", + "new_sha256": "5aa6809b49f38b209b2f7b7ef02f843dd0aea60f62322aa36a65f11dbc951d97", + "frames": 1, + "old_max_error_deg": 0.022928351067353546, + "new_max_error_deg": 3.1791272867961397e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/laptop_use_03", + "old_sha256": "852eccdccba81316d779b74c5df8b977e79a7a0404b941b66de508988365117f", + "new_sha256": "aa0e65b758053e641f94af44af55189ae02a1c479d06eb303fb9ba98bc139ebe", + "frames": 1, + "old_max_error_deg": 0.011431585907483216, + "new_max_error_deg": 3.546041888427828e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/microwave_use_02", + "old_sha256": "b019783ead9a75a0d781a16191ddaa86c4dd9bd7b75c4ded9f696beaf3c28837", + "new_sha256": "09c56d97d3744781456b790da991629818c3f1a61741684e4604eb0c0b214a1d", + "frames": 2, + "old_max_error_deg": 0.036068894178269625, + "new_max_error_deg": 4.375535498458921e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/microwave_use_03", + "old_sha256": "9c5764ba0d5671597126405801fd352376a7cfee1475b8845f0ab2099de84e00", + "new_sha256": "8e76242838e3bfa60f6954d951ef4d90e7efe8548c13a967eaf7b00c7e85b9f4", + "frames": 1, + "old_max_error_deg": 0.03028466091854701, + "new_max_error_deg": 7.321864344706368e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/microwave_use_04", + "old_sha256": "5a41752f47f1725d333d7c88bd25e52503cccf2f6e8eb90a4ebe5afec435ab2e", + "new_sha256": "98e9103d4205428b14ffacafafc54353f527a318869798dfaa1025eb94b9cf92", + "frames": 2, + "old_max_error_deg": 0.06615964553414717, + "new_max_error_deg": 5.418219798459937e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/mixer_use_01", + "old_sha256": "8f18aeb7c698ce50a23b6d4419906b89503afb7f2f3db73f72b821d43f7b0bd0", + "new_sha256": "812ddd3879f4a427f752a05129a9265383ce6b5883982567978fe5e97f4ece63", + "frames": 2, + "old_max_error_deg": 0.02426754176040595, + "new_max_error_deg": 1.5891161312090006e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/mixer_use_02", + "old_sha256": "49f76702e8bf68e2a2c25e4ee555597b6d5c0942fb99102dddd68b6e2047d076", + "new_sha256": "5927fb8c8991bbb9029751ab0a24799f94cfdd058bb16715202a95158265a7f6", + "frames": 1, + "old_max_error_deg": 0.2625468374254298, + "new_max_error_deg": 1.4396573088793558e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/mixer_use_03", + "old_sha256": "16e4d0f248ba667c60060b42e6faff4a5eb7b42ab54167d6d217c9a3cbb0328f", + "new_sha256": "291193e4cd11e79b7471dc5bcaa27143a8bf95db30588e2d358206d540b02fc9", + "frames": 2, + "old_max_error_deg": 0.0800246601152127, + "new_max_error_deg": 3.3547614132857014e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/mixer_use_04", + "old_sha256": "b9d76a7bd4c6cd935a61848eb0f6ca08fd914300ec901871f54fc43c9d629790", + "new_sha256": "580520e5add5262c0462faf795767292376f4878fc8f2383dab98c55770a7c30", + "frames": 1, + "old_max_error_deg": 0.13848238568650081, + "new_max_error_deg": 3.143009594957263e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/notebook_use_01", + "old_sha256": "f37d4df06e40d1c653d44043b58347500915a414501cf1397ae69a5c8bf68d47", + "new_sha256": "641a323e2fc7b0572f94d0722d3b579214b1157f0d8a9cbae846a6795ac60d41", + "frames": 2, + "old_max_error_deg": 0.06401498770255859, + "new_max_error_deg": 3.461842719334595e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/notebook_use_02", + "old_sha256": "4feda0b558efe29c193d76d8c740b8807c1fa7996b08bc85ebd00018d3018258", + "new_sha256": "e9624ccb9fa5fa5d7bd4df8a0e5a4129c747c2c8a330c9ac0e4d5c976ca12c47", + "frames": 2, + "old_max_error_deg": 0.17869141162964702, + "new_max_error_deg": 3.4568014255021013e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/phone_use_02", + "old_sha256": "f7beb8f4d1fff0f1ee8ed377490ec3ecdf4e7450630142fc36884ce95b86b937", + "new_sha256": "1a73de70341decded7432c80ebb3f9daa83413d66e0086b20073f75d6772f466", + "frames": 1, + "old_max_error_deg": 0.027349551540423758, + "new_max_error_deg": 2.588392187590604e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/phone_use_03", + "old_sha256": "e08c2c8f4a315a9bf60f0fdc576f9cb60d48ff3c04215e4c7c78e2c9c68f2fb4", + "new_sha256": "6094c84dbba6c32224143f5a06d4f4c7b072224fe5b50872545e310aae5e36ee", + "frames": 2, + "old_max_error_deg": 0.27041924542865964, + "new_max_error_deg": 3.038471259971342e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/scissors_use_02", + "old_sha256": "2d0cd95bb8da367794f08d5c139d4af95d91970c8a7a312834a1c0362e649e85", + "new_sha256": "816923625c97fda9aba01675124354dda071d45b4087a8d431c87866593e9cb8", + "frames": 8, + "old_max_error_deg": 0.03136987612299154, + "new_max_error_deg": 1.1283907815437917e-05 + }, + { + "source": "ARCTIC", + "recording": "s09/scissors_use_04", + "old_sha256": "f0c7c5ff18ff89a21b5703894c6cb08560df7d5129d554e4b9e5b5286a4e46b8", + "new_sha256": "01b9861cbc94f960f976d5d63d2a99cf386cb4be229f86bdc833e1c2dd069791", + "frames": 5, + "old_max_error_deg": 0.04018246274268935, + "new_max_error_deg": 9.021717293340297e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/waffleiron_use_01", + "old_sha256": "5b17edee80c17bd2c770daebdcfb9551646874211f6e4251bdbd37ccaa9bedf4", + "new_sha256": "0faa51122f1c28277b9029e1117a0863677a8f6ad8628d6674a30fda0c291883", + "frames": 2, + "old_max_error_deg": 0.04331669277539223, + "new_max_error_deg": 4.146684505723529e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/waffleiron_use_02", + "old_sha256": "62933f65bb17ae8aedef3dce119a08b1554e4cbe535c0aed2652a6d9724f04e2", + "new_sha256": "cb35ab36ed73eb7bf1670abb59f8145c0a4661a4768ec7e4aa31cf0fa4c3bce9", + "frames": 2, + "old_max_error_deg": 0.031043576080918275, + "new_max_error_deg": 3.01649476134704e-06 + }, + { + "source": "ARCTIC", + "recording": "s09/waffleiron_use_03", + "old_sha256": "f139ff4b7e11e8c83a3c8e0eea0da1669cec1c5b270c587cc0d7bf1af6b37d58", + "new_sha256": "9edf308bc5672ef0b9cbc28ade4dbb68e2190222d6924bc797f59b628ac08475", + "frames": 3, + "old_max_error_deg": 0.042249651117315316, + "new_max_error_deg": 1.0355085178857862e-05 + }, + { + "source": "ARCTIC", + "recording": "s10/box_use_01", + "old_sha256": "de533bf9d0af56e7045c7f581ec466af7469bf144ad1c3398b51bbab62c6fd06", + "new_sha256": "5f6ca1954d4bfde63a21199e21a8428fee546755ca076a9119f66553723caab5", + "frames": 1, + "old_max_error_deg": 0.01189324422046043, + "new_max_error_deg": 3.375215270788092e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/box_use_02", + "old_sha256": "3dcac0b03b45c86bd1afbca23715e44e2fe7fb78196bdbf13f6d4c2e967ea3fa", + "new_sha256": "01ca3621be31b5164e41b856d1ec6b33083aeeda7c056d6ed41b23b65b11c8c5", + "frames": 1, + "old_max_error_deg": 0.023721979097006643, + "new_max_error_deg": 2.4797419781281673e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/capsulemachine_use_02", + "old_sha256": "6b50bb3e47756a895e34692e602642e4065aba4e5eb6473cc2efa57c36be94df", + "new_sha256": "7d3588f61d957b231e3c5b4d3f02e287e2a543d4801ec85b725d954af6cdb8d8", + "frames": 2, + "old_max_error_deg": 0.034316713179515214, + "new_max_error_deg": 3.5636434171159286e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/ketchup_grab_01", + "old_sha256": "cf563493476c762026d4d55042b13ab6c72a458da4361a56b73ba8368eb245cf", + "new_sha256": "6d99dc220d5949b58fe2af633e9f92f3632662ef3b499efa5bb5563318254291", + "frames": 3, + "old_max_error_deg": 0.04764120679553758, + "new_max_error_deg": 4.279931072694839e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/ketchup_use_01", + "old_sha256": "7b2e1084eb57a8618cf9eb337f6caa67c48c557b553a3dcc3dabc37752632217", + "new_sha256": "af0120dad28b22a3d0fc34a7548370ec0f2f0884fb3ddb6e5492854c4005cedf", + "frames": 2, + "old_max_error_deg": 0.09804763835214877, + "new_max_error_deg": 3.941072460543096e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/ketchup_use_02", + "old_sha256": "72dab5327b56b56b8d7dcbd71a93a457e81095f5e5318d135f22d4c57fe43c48", + "new_sha256": "3552e44472814eb9c4c19a858e166731f81047c34da9e87bd210e9877dbd7630", + "frames": 2, + "old_max_error_deg": 0.016412056114832988, + "new_max_error_deg": 2.4620265694618625e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/laptop_use_02", + "old_sha256": "e2bf8dcefbf6b65a1f0fc6f55c5f5b7b2d0e1127a20ef868823a3da33855e4fe", + "new_sha256": "fb14c463df4078735e76523c84307fe7dbbd36351e6a7f9016c66e0bb3cda2f7", + "frames": 1, + "old_max_error_deg": 0.0200546949547608, + "new_max_error_deg": 4.840832172266222e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/mixer_use_01", + "old_sha256": "06be084cf92eeb86370a6876db8ebd95e4ca79318e56bf89642193f725a11263", + "new_sha256": "a50bf798fc7d7f0fbae98cfb72c4f32bcba3aa050504f91f259fb1b1b2100176", + "frames": 1, + "old_max_error_deg": 0.05835230735995874, + "new_max_error_deg": 1.7427388433683929e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/mixer_use_02", + "old_sha256": "7dac8a4c34d9f93730a4865b2a0fc2d10501cd7dd3be458e6091045bb230cb84", + "new_sha256": "f36820c1acd508e854c67358f196cf2dbe382a1fa04263652ce025e412beb0c7", + "frames": 2, + "old_max_error_deg": 0.047325234126923806, + "new_max_error_deg": 4.700510165255945e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/notebook_use_01", + "old_sha256": "9509970293d37c087ea5dbc38f8a3c92ebeb5820e78b2251cfc84ab09891f4b0", + "new_sha256": "464ccce0249fc2d13201b37cd9b15351d728270ffca38f5f54c68ac4f6379aea", + "frames": 3, + "old_max_error_deg": 0.02015849643918086, + "new_max_error_deg": 4.899251165514404e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/notebook_use_02", + "old_sha256": "e3759c0ff0f7dd8ac23a96bc7231051e8957b7dafe118fccbdbe1eadc96cb762", + "new_sha256": "127ce5477122f59219a97f247c67d14522017a4997cf6c8c4d7222eec53e04c5", + "frames": 3, + "old_max_error_deg": 0.12078981920973247, + "new_max_error_deg": 3.7130680247289143e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/phone_use_02", + "old_sha256": "ae292749b4e1e839490eeadea2dcc7a67066845d0410fc37306f96fb4fcc97ec", + "new_sha256": "db558572a71616ad38b0ac2ba448387b59ab11d2199ba7b3e5c3bd26092c34be", + "frames": 2, + "old_max_error_deg": 0.0878259243247752, + "new_max_error_deg": 1.4724741816475932e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/scissors_use_02", + "old_sha256": "4727208c6c3984072e81225311904d0856aafe0a2fbf1e3106623904dd21e608", + "new_sha256": "1f94633d3c9cbaaae58d82929ac89e3203e71f20f21f7dde7d8b78638aee291c", + "frames": 1, + "old_max_error_deg": 0.022366210179536956, + "new_max_error_deg": 1.8497678906418818e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/waffleiron_grab_01", + "old_sha256": "0b0493e9701738ece4eaef1d777c973fef921a75527d84a93d125c84176ea09e", + "new_sha256": "5637aae496e6f466cb19f9c481e9cca63d2e57f9b4b28ecdfadf3a06e6366435", + "frames": 1, + "old_max_error_deg": 0.07117094922754037, + "new_max_error_deg": 4.912054711585739e-06 + }, + { + "source": "ARCTIC", + "recording": "s10/waffleiron_use_02", + "old_sha256": "417d4a921bfa4c20d578808b3fc4e5ca9e8d1963c4678f6e98e423e4bbc2c8f4", + "new_sha256": "2fd58c5f13fb011d64efa37178455c2bbba2272f62c05839b72a3a520757b0be", + "frames": 1, + "old_max_error_deg": 0.041293105973227856, + "new_max_error_deg": 5.443073522043424e-06 + } + ], + "code_sha256": "25aae1c6fcd6de8e2cc864a9c9d28cacc834ba01fe918ae0bd4194d78d3639da", + "scan_sha256": "4026986c67c282aebed649eab2f36c25c51c8c106a550c2047f25ab0776639a2" +} diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/.gitignore b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bc1a1f6167d09c909aad37280b760bb715d0f1da --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/.gitignore @@ -0,0 +1,2 @@ +# Created by pytest automatically. +* diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/CACHEDIR.TAG b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/CACHEDIR.TAG new file mode 100644 index 0000000000000000000000000000000000000000..fce15ad7eaa74e5682b644c84efb75334c112f95 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/CACHEDIR.TAG @@ -0,0 +1,4 @@ +Signature: 8a477f597d28d172789f06886806bc55 +# This file is a cache directory tag created by pytest. +# For information about cache directory tags, see: +# https://bford.info/cachedir/spec.html diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/README.md b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b89018ced91c0a8af7f3f23ce8901870da89f3a0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/README.md @@ -0,0 +1,8 @@ +# pytest cache directory # + +This directory contains data from the pytest's cache plugin, +which provides the `--lf` and `--ff` options, as well as the `cache` fixture. + +**Do not** commit this to version control. + +See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information. diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/v/cache/lastfailed b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/v/cache/lastfailed new file mode 100644 index 0000000000000000000000000000000000000000..9e26dfeeb6e641a33dae4961196235bdb965b21b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/v/cache/lastfailed @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/v/cache/nodeids b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/v/cache/nodeids new file mode 100644 index 0000000000000000000000000000000000000000..374343db87e49728b713af596e7ba645d2f5b2fa --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/.pytest_cache/v/cache/nodeids @@ -0,0 +1,10 @@ +[ + "test_hot3d_rotation.py::Hot3dRotationTests::test_roundtrip_including_singular_angles", + "test_rotation_pi.py::test_matrix_axis_angle_gradients_identity_and_near_pi", + "test_rotation_pi.py::test_matrix_axis_angle_roundtrip_random_and_near_pi", + "test_rotation_pi.py::test_near_pi_arbitrary_axis", + "tests/test_hot3d_supervision_masks.py::test_missing_geometry_remains_invalid_even_when_mesh_projects_inside", + "tests/test_hot3d_supervision_masks.py::test_quest_rectification_preserves_native_camera_extrinsic", + "tests/test_hot3d_supervision_masks.py::test_temporal_masks_are_independent_per_frame_and_hand", + "tests/test_hot3d_supervision_masks.py::test_visible_mesh_keeps_full_3d_but_masks_offscreen_2d" +] \ No newline at end of file diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/audit_formal_stage.py b/home/wuyifan/a7_rotation_fix_20260930_code/audit_formal_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..68ad0c1c90c60fc8329518db2ec8956b0a6c137e --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/audit_formal_stage.py @@ -0,0 +1,133 @@ +"""Audit a completed formal stage endpoint without modifying training state.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +import math +from pathlib import Path +import statistics + +import torch + +from clean_train import INDEX, STAGES, sha, training_code_hashes + + +EXTREME_LOSS_THRESHOLD = 100.0 + + +def run(checkpoint: Path, metrics: Path, stage: str, update: int) -> dict: + state = torch.load(checkpoint, map_location="cpu", weights_only=False) + rows = [json.loads(line) for line in metrics.open()] + errors = [] + if not rows or len(rows) != update or [row["update"] for row in rows] != list(range(1, update + 1)): + errors.append("metrics do not contain every update through the requested endpoint") + if state["stage"] != stage or state["update"] != update: + errors.append("checkpoint stage or update differs from requested endpoint") + if state.get("smoke") or not state.get("complete_backbone"): + errors.append("checkpoint is smoke or lacks the complete backbone") + if state["world_size"] != 6 or len(state["rank_rng_states"]) != 6: + errors.append("checkpoint is not a complete six-rank state") + if state["next_global_sample_position"] != STAGES[stage]["offset"] + 6 * update: + errors.append("sampler cursor differs from the registered stage schedule") + if state["index_sha256"] != sha(INDEX) or state["code_sha256"] != training_code_hashes(): + errors.append("checkpoint data index or training code identity differs from current files") + if state.get("grad_clip") != 100.0: + errors.append("gradient clipping threshold differs from the frozen recipe") + exposure = Counter(state["exposures"]) + if sum(exposure.values()) != 6 * update: + errors.append("source/mode exposure ledger does not sum to global batch times updates") + if stage in ("S1", "S2", "S3"): + expected = {"H2O": 0.40, "ARCTIC": 0.35, "HOT3D": 0.25} + else: + expected = {"H2O": 0.35, "ARCTIC": 0.25, "HOT3D": 0.40} + source_exposure = { + source: sum(count for key, count in exposure.items() if key.startswith(source + ":")) + for source in expected + } + for source, fraction in expected.items(): + if abs(source_exposure[source] - 6 * update * fraction) > 6: + errors.append(f"{source} exposure differs from the registered quota") + expected_modes = { + "H2O:rgb", "H2O:rgb_k", "H2O:rgb_depth_k", + "ARCTIC:rgb", "ARCTIC:rgb_k", "HOT3D:rgb", "HOT3D:rgb_k", + } + if set(exposure) != expected_modes: + errors.append("one or more registered source/input modes are absent") + supervision = state.get("supervision_exposures") + if (not isinstance(supervision, dict) or not supervision + or sum(supervision.values()) <= 0 or min(supervision.values()) < 0): + errors.append("supervision ledger is empty or contains invalid counts") + if rows: + last = rows[-1] + if last["exposures"] != state["exposures"] or last.get("supervision_exposures") != supervision: + errors.append("final metrics row and checkpoint exposure ledgers differ") + if not all(math.isfinite(row["loss"]) and math.isfinite(row["grad_norm_max"]) for row in rows): + errors.append("nonfinite loss or gradient norm in the training history") + extreme_loss_updates = [row["update"] for row in rows + if math.isfinite(row["loss"]) + and row["loss"] > EXTREME_LOSS_THRESHOLD] + if extreme_loss_updates: + errors.append(f"extreme finite loss at updates {extreme_loss_updates[:20]}") + detailed = [row for row in rows if "grad_parameter_groups" in row] + required_groups = { + "rgb_encoder.projection", "depth_encoder", "ray_encoder", + "decoder.spatial", "joint2d_head", "rotation_head", + "translation_head", "shape_head", + } + if stage != "S1": + required_groups.update(("decoder.temporal", "shape_score")) + if stage == "S4": + required_groups.add("rgb_encoder.backbone") + if not all(any(row["grad_parameter_groups"].get(group, 0) > 0 for row in detailed) + for group in required_groups): + errors.append("a required trainable parameter group never received a nonzero gradient") + else: + detailed = [] + extreme_loss_updates = [] + window = min(100, len(rows)) + report = { + "status": "pass" if not errors else "fail", + "errors": errors, + "checkpoint": str(checkpoint), + "checkpoint_sha256": sha(checkpoint), + "stage": stage, + "update": update, + "training_code_sha256": state["code_sha256"]["clean_train.py"], + "source_exposure": source_exposure, + "source_mode_exposure": dict(exposure), + "supervision_ledger_keys": len(supervision or {}), + "supervision_elements": sum((supervision or {}).values()), + "first_window_loss_mean": statistics.mean(row["loss"] for row in rows[:window]) if rows else None, + "last_window_loss_mean": statistics.mean(row["loss"] for row in rows[-window:]) if rows else None, + "last_window_grad_norm_median": statistics.median(row["grad_norm_max"] for row in rows[-window:]) if rows else None, + "clipped_updates": sum(bool(row["clipped"]) for row in rows), + "max_batch_loss": max((row["loss"] for row in rows), default=None), + "extreme_loss_threshold": EXTREME_LOSS_THRESHOLD, + "extreme_loss_updates": extreme_loss_updates, + "detailed_rows": len(detailed), + } + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--metrics", type=Path, required=True) + parser.add_argument("--stage", choices=tuple(STAGES), required=True) + parser.add_argument("--update", type=int, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + report = run(args.checkpoint, args.metrics, args.stage, args.update) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2)) + if report["errors"]: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/audit_gt_projection.py b/home/wuyifan/a7_rotation_fix_20260930_code/audit_gt_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..3a92d42d3cad354945b06e3c8d86d25dae30e4d0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/audit_gt_projection.py @@ -0,0 +1,108 @@ +"""Freeze a 100-frame RGB/GT/K alignment gallery from trainable native clips.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from clean_train import ASSETS, MANIFESTS +from filtered_dataset import FilteredClipDataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.geometry.camera import project_points + + +QUOTAS = {"H2O": 40, "ARCTIC": 30, "HOT3D": 30} +CELL_HW = (200, 356) + + +def thumbnail(sample: dict, source: str, tile_id: str) -> tuple[np.ndarray, list[float], int]: + frame = len(sample["rgb"]) // 2 + rgb = sample["rgb"][frame].permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + points = sample["joint3d_camera"][frame] + K = sample["K"][frame] + projected, positive = project_points(points, K) + target = sample["joint2d"][frame] + valid = (sample["joint2d_valid"][frame] & sample["joint3d_valid"][frame] + & positive & torch.isfinite(target).all(-1)) + errors = torch.linalg.vector_norm(projected - target, dim=-1)[valid].tolist() + height, width = image.shape[:2] + for hand in range(2): + for joint in range(21): + if not bool(valid[hand, joint]): + continue + x, y = target[hand, joint].tolist() + px, py = projected[hand, joint].tolist() + if 0 <= x < width and 0 <= y < height: + cv2.circle(image, (round(x), round(y)), 3, (0, 255, 255), -1) + if 0 <= px < width and 0 <= py < height: + cv2.circle(image, (round(px), round(py)), 2, (255, 0, 255), -1) + cell_height, cell_width = CELL_HW + image = cv2.resize(image, (cell_width, cell_height - 28), interpolation=cv2.INTER_AREA) + cell = np.zeros((cell_height, cell_width, 3), dtype=np.uint8) + cell[:cell_height - 28] = image + label = f"{source} {tile_id[-22:]} valid={int(valid.sum())}" + cv2.putText(cell, label, (5, cell_height - 9), cv2.FONT_HERSHEY_SIMPLEX, + .38, (255, 255, 255), 1, cv2.LINE_AA) + return cell, errors, int(valid.sum()) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + args.output.mkdir(parents=True) + cells = [] + report = {"schema": "clean_gt_projection_audit_v1", "selection": "linspace over frozen trainable T8 manifests", + "total_frames": sum(QUOTAS.values()), "sources": {}} + for source, count in QUOTAS.items(): + manifest = MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl" + dataset = FilteredClipDataset( + source, manifest, 8, (368, 640), ASSETS["mano_root"], + Path(__file__).parent / "third_party", {"enabled": False}, + ) + indices = np.linspace(0, len(dataset) - 1, count, dtype=int) + errors = [] + valid_counts = [] + tiles = [] + for index in indices: + row = dataset.rows[int(index)] + tile_id = str(row["filtered_tile_id"]) + sample = dataset[{"source": source, "tile_id": tile_id, "epoch": 0, + "mode": "rgb_depth_k" if source == "H2O" else "rgb_k", + "position": 0, "source_ordinal": int(index)}] + cell, joint_errors, valid_count = thumbnail(sample, source, tile_id) + cells.append(cell) + errors.extend(joint_errors) + valid_counts.append(valid_count) + tiles.append(tile_id) + values = np.asarray(errors) + report["sources"][source] = { + "frames": count, "frames_with_valid_3d_and_2d": sum(x > 0 for x in valid_counts), + "valid_joints": len(errors), "mean_reprojection_px": float(values.mean()) if len(values) else None, + "p95_reprojection_px": float(np.quantile(values, .95)) if len(values) else None, + "max_reprojection_px": float(values.max()) if len(values) else None, + "tile_ids": tiles, + } + height, width = CELL_HW + gallery = np.zeros((10 * height, 10 * width, 3), dtype=np.uint8) + for number, cell in enumerate(cells): + row, col = divmod(number, 10) + gallery[row * height:(row + 1) * height, col * width:(col + 1) * width] = cell + if not cv2.imwrite(str(args.output / "gt_projection_100.jpg"), gallery): + raise RuntimeError("gallery write failed") + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({name: {key: value for key, value in row.items() if key != "tile_ids"} + for name, row in report["sources"].items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/audit_headset_sync.py b/home/wuyifan/a7_rotation_fix_20260930_code/audit_headset_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..679b0c33f13bd968d67a8980223428165da61a61 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/audit_headset_sync.py @@ -0,0 +1,104 @@ +"""Audit HOT3D camera-frame GT construction against native headset pose time.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import csv +from functools import lru_cache +import json +from pathlib import Path + +import numpy as np + +from preflight_index import tile_starts + + +MAX_DELTA_NS = 20_000_000 + + +@lru_cache(maxsize=256) +def trajectory(root: str) -> np.ndarray: + path = Path(root) / "headset_trajectory.csv" + with path.open(newline="") as stream: + stamps = np.asarray( + [int(row["timestamp[ns]"]) for row in csv.DictReader(stream)], dtype=np.int64, + ) + if len(stamps) == 0 or np.any(np.diff(stamps) <= 0): + raise ValueError(f"empty or nonmonotone headset trajectory: {path}") + return stamps + + +@lru_cache(maxsize=256) +def timeline(path: str, stream: str) -> np.ndarray: + return np.asarray(json.loads(Path(path).read_text())[stream], dtype=np.int64) + + +def deltas(target: np.ndarray, reference: np.ndarray) -> np.ndarray: + upper = np.searchsorted(reference, target).clip(0, len(reference) - 1) + lower = (upper - 1).clip(0, len(reference) - 1) + return np.minimum(np.abs(reference[upper] - target), np.abs(reference[lower] - target)) + + +def audit(manifest: Path) -> tuple[dict, list[dict]]: + counts = Counter() + recording_bad = Counter() + bad: list[dict] = [] + max_deltas = [] + for line in manifest.open(): + if not line.strip(): + continue + row = json.loads(line) + if row["dataset"] != "HOT3D": + continue + source = row["source"] + stamps = timeline(source["timestamps_path"], row["stream_id"])[ + int(row["start"]):int(row["end"]) + ] + if len(stamps) != row["frame_count"]: + raise ValueError(f"timeline length mismatch: {row['id']}") + delta = deltas(stamps, trajectory(source["root"])) + bad_frames = delta > MAX_DELTA_NS + bad_tiles = [start for start in tile_starts(len(stamps)) + if bool(bad_frames[start:start + 8].any())] + counts["windows"] += 1 + counts["frames"] += len(stamps) + counts["tiles"] += len(tile_starts(len(stamps))) + counts["bad_frames"] += int(bad_frames.sum()) + counts["bad_tiles"] += len(bad_tiles) + if bad_frames.any(): + counts["bad_windows"] += 1 + recording_bad[row["recording_id"]] += 1 + max_deltas.append(float(delta.max() / 1e6)) + bad.append({"window_id": row["id"], "recording_id": row["recording_id"], + "stream_id": row["stream_id"], "bad_frame_offsets": np.flatnonzero(bad_frames).tolist(), + "bad_tile_offsets": bad_tiles, "maximum_nearest_headset_delta_ms": float(delta.max() / 1e6)}) + report = { + "threshold_ms": 20, "counts": dict(counts), + "affected_recordings": len(recording_bad), + "worst_recordings_by_window_count": recording_bad.most_common(20), + "bad_window_delta_ms_median": float(np.median(max_deltas)) if max_deltas else 0, + "bad_window_delta_ms_max": max(max_deltas, default=0), + } + return report, bad + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--report", type=Path, required=True) + parser.add_argument("--bad-windows", type=Path, required=True) + args = parser.parse_args() + for path in (args.report, args.bad_windows): + if path.exists(): + raise FileExistsError(path) + report, bad = audit(args.manifest) + args.report.write_text(json.dumps(report, indent=2) + "\n") + with args.bad_windows.open("w") as stream: + for row in bad: + stream.write(json.dumps(row) + "\n") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/audit_input_modes.py b/home/wuyifan/a7_rotation_fix_20260930_code/audit_input_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c4c2ab8786bbffe21be79e147165f59b008111 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/audit_input_modes.py @@ -0,0 +1,58 @@ +"""Assert modality input dropout never changes camera or GT supervision.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from clean_train import ASSETS, MANIFESTS +from filtered_dataset import FilteredClipDataset + + +SUPERVISION = ( + "K", "K_supervision_valid", "joint2d", "joint2d_valid", + "joint3d_camera", "joint3d_valid", "wrist_root_translation", + "translation_valid", "mano_pose", "mano_pose_valid", "mano_shape", + "shape_valid", "vertices_valid", "reprojection_valid", +) + + +def main() -> None: + result = {} + for source in ("H2O", "ARCTIC", "HOT3D"): + manifest = MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl" + dataset = FilteredClipDataset( + source, manifest, 8, (368, 640), ASSETS["mano_root"], + Path(__file__).parent / "third_party", {"enabled": False}, + ) + row = dataset.rows[0] + spec = {"source": source, "tile_id": row["filtered_tile_id"], + "position": 0, "source_ordinal": 0, "epoch": 0} + modes = ("rgb", "rgb_k", "rgb_depth_k") if source == "H2O" else ("rgb", "rgb_k") + samples = {mode: dataset[{**spec, "mode": mode}] for mode in modes} + reference = samples["rgb"] + frame = reference["frame_valid"].bool() + if not bool(reference["K_supervision_valid"].any()): + raise AssertionError(f"{source} selected clip lacks K supervision") + for mode, sample in samples.items(): + torch.testing.assert_close(sample["rgb"], reference["rgb"]) + for name in SUPERVISION: + torch.testing.assert_close(sample[name], reference[name], equal_nan=True) + expected_K = frame if mode != "rgb" else torch.zeros_like(frame) + expected_depth = frame if mode == "rgb_depth_k" else torch.zeros_like(frame) + for canonical, alias, expected in ( + ("K_input_available", "K_available", expected_K), + ("depth_input_available", "depth_available", expected_depth), + ): + if not torch.equal(sample[canonical], expected) or not torch.equal(sample[alias], expected): + raise AssertionError(f"{source}:{mode} availability flags diverge") + result[source] = {"tile_id": spec["tile_id"], "modes": modes, + "K_supervised_frames": int(reference["K_supervision_valid"].sum()), + "GT_and_real_K_unchanged": True} + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/audit_schedule.py b/home/wuyifan/a7_rotation_fix_20260930_code/audit_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..d564389690154f78b10e1e20fca34b32a428afae --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/audit_schedule.py @@ -0,0 +1,50 @@ +"""Verify every registered T=8 tile is exposed before source-local reuse.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +from pathlib import Path + +from coverage_sampler import CoverageSampler, SOURCES + + +def audit(index: Path, stage: str, samples: int) -> dict: + sampler = CoverageSampler(index, stage) + seen = {source: set() for source in SOURCES} + exposures = Counter() + modes = Counter() + first_coverage = {} + for position in range(samples): + row = sampler.sample(position) + source = str(row["source"]) + ordinal = int(row["source_ordinal"]) + if ordinal < sampler.sizes[source] and row["tile_id"] in seen[source]: + raise AssertionError(f"tile repeated before coverage: {source} {row['tile_id']}") + seen[source].add(row["tile_id"]) + exposures[source] += 1 + modes[f"{source}:{row['mode']}"] += 1 + if source not in first_coverage and len(seen[source]) == sampler.sizes[source]: + first_coverage[source] = position + 1 + if any(len(seen[source]) != sampler.sizes[source] for source in SOURCES): + raise AssertionError("registered T=8 stage did not cover all source tiles") + return { + "stage": stage, "samples": samples, "status": "pass", + "tiles": sampler.sizes, "unique_tiles": {source: len(seen[source]) for source in SOURCES}, + "exposures": dict(exposures), "input_modes": dict(modes), + "first_complete_global_position": first_coverage, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--index", type=Path, required=True) + parser.add_argument("--stage", choices=("S1_S3", "S4"), required=True) + parser.add_argument("--samples", type=int, required=True) + args = parser.parse_args() + print(json.dumps(audit(args.index, args.stage, args.samples), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/benchmark_decode.py b/home/wuyifan/a7_rotation_fix_20260930_code/benchmark_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a2146c5035daa63e01ea7574caf358c84a6363 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/benchmark_decode.py @@ -0,0 +1,56 @@ +"""Measure uncached native clip decoding across spaced recordings.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys +import time + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import numpy as np +import torch + +from filtered_dataset import FilteredClipDataset + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--count", type=int, default=8) + parser.add_argument("--grouped", action="store_true", help="Read consecutive tiles in one recording") + args = parser.parse_args() + start = time.perf_counter() + dataset = FilteredClipDataset( + args.source, args.manifests / f"{args.source.lower()}_t8.jsonl", 8, + (368, 640), "/SSD3/jiasen/foundation_hand/pretrained/mano", + Path(__file__).parent / "third_party", {"enabled": False}, + ) + init_seconds = time.perf_counter() - start + indices = list(range(args.count)) if args.grouped else np.linspace( + 0, len(dataset) - 1, args.count, dtype=int, + ).tolist() + times = [] + recordings = [] + with torch.no_grad(): + for sequence, index in enumerate(indices): + row = dataset.rows[index] + spec = {"source": args.source, "tile_id": row["filtered_tile_id"], + "epoch": 0, "source_ordinal": sequence, "position": sequence, + "mode": "rgb_depth_k" if args.source == "H2O" else "rgb_k"} + mark = time.perf_counter() + sample = dataset[spec] + times.append(time.perf_counter() - mark) + recordings.append(sample["physical_recording_id"]) + print(json.dumps({"source": args.source, "count": len(times), + "recordings": len(set(recordings)), "init_seconds": init_seconds, + "decode_seconds": times, "median_seconds": float(np.median(times)), + "p95_seconds": float(np.quantile(times, .95)), + "clips_per_second_single_worker": len(times) / sum(times)}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/build_trainable_index.py b/home/wuyifan/a7_rotation_fix_20260930_code/build_trainable_index.py new file mode 100644 index 0000000000000000000000000000000000000000..03f9619e1b4a6beca9a51c0da26ab28d09d4d898 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/build_trainable_index.py @@ -0,0 +1,126 @@ +"""Apply audited HOT3D headset-pose eligibility without changing source GT.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +import os +from pathlib import Path +import sqlite3 + +from preflight_index import digest, tile_starts + + +def valid_runs(length: int, invalid: set[int]): + start = None + for position in range(length + 1): + good = position < length and position not in invalid + if good and start is None: + start = position + elif not good and start is not None: + yield start, position + start = None + + +def build(original: Path, audit: Path, bad_windows: Path, output: Path) -> dict: + if output.exists(): + raise FileExistsError(output) + report = json.loads(audit.read_text()) + if report["threshold_ms"] != 20 or report["counts"]["windows"] != 18962: + raise ValueError("headset synchronization audit is not the frozen full-data audit") + bad_rows = [json.loads(line) for line in bad_windows.open() if line.strip()] + if len(bad_rows) != report["counts"]["bad_windows"]: + raise ValueError("bad-window list differs from summary") + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_suffix(output.suffix + ".tmp") + if temporary.exists(): + raise FileExistsError(temporary) + source = sqlite3.connect(f"file:{original}?mode=ro", uri=True) + target = sqlite3.connect(temporary) + try: + source.backup(target) + target.execute("CREATE TABLE sync_exclusions (window_id TEXT PRIMARY KEY, bad_frame_offsets_json TEXT NOT NULL)") + lost_valid_frames = 0 + recovered_valid_frames = 0 + windows_without_t8 = 0 + for record in bad_rows: + window_id = record["window_id"] + row = target.execute( + "SELECT source,recording_id,frame_ids_json FROM windows WHERE window_id=?", + (window_id,), + ).fetchone() + if row is None or row[0] != "HOT3D": + raise ValueError(f"unknown HOT3D window {window_id}") + _, recording, frame_ids_json = row + frame_ids = json.loads(frame_ids_json) + invalid = set(record["bad_frame_offsets"]) + if not invalid or min(invalid) < 0 or max(invalid) >= len(frame_ids): + raise ValueError(f"bad frame offsets outside window {window_id}") + original_bad_tiles = [offset for (offset,) in target.execute( + "SELECT start_offset FROM tiles WHERE window_id=?", (window_id,), + ) if invalid.intersection(range(offset, offset + 8))] + if sorted(original_bad_tiles) != sorted(record["bad_tile_offsets"]): + raise ValueError(f"headset audit tile mapping differs: {window_id}") + target.execute("DELETE FROM tiles WHERE window_id=?", (window_id,)) + target.execute("INSERT INTO sync_exclusions VALUES (?,?)", + (window_id, json.dumps(sorted(invalid)))) + covered = set() + tile_count = 0 + for first, last in valid_runs(len(frame_ids), invalid): + if last - first < 8: + continue + for local_start in tile_starts(last - first): + offset = first + local_start + selected = frame_ids[offset:offset + 8] + if len(selected) != 8 or invalid.intersection(range(offset, offset + 8)): + raise AssertionError("trainable tile contains an invalid headset frame") + target.execute( + "INSERT INTO tiles VALUES (?,?,?,?,?,?)", + (f"{window_id}:{offset}", window_id, "HOT3D", recording, + offset, json.dumps(selected)), + ) + covered.update(range(offset, offset + 8)) + tile_count += 1 + if tile_count == 0: + windows_without_t8 += 1 + recovered_valid_frames += len(covered) + lost_valid_frames += (len(frame_ids) - len(invalid) - len(covered)) + counts = Counter(dict(target.execute("SELECT source, COUNT(*) FROM tiles GROUP BY source"))) + bad_tile_check = target.execute( + "SELECT COUNT(*) FROM tiles t JOIN sync_exclusions e ON t.window_id=e.window_id" + ).fetchone()[0] + target.commit() + except BaseException: + target.close() + source.close() + temporary.unlink(missing_ok=True) + raise + target.close() + source.close() + os.replace(temporary, output) + return { + "status": "pass", "original_index_sha256": digest(original), + "headset_sync_report_sha256": digest(audit), + "headset_bad_windows_sha256": digest(bad_windows), + "trainable_index_sha256": digest(output), "tiles_by_source": dict(counts), + "audited_windows_with_bad_headset_pose": len(bad_rows), + "windows_without_any_t8": windows_without_t8, + "valid_frames_covered_inside_affected_windows": recovered_valid_frames, + "valid_frames_not_packable_into_t8": lost_valid_frames, + "tiles_in_affected_windows": bad_tile_check, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--original", type=Path, required=True) + parser.add_argument("--audit", type=Path, required=True) + parser.add_argument("--bad-windows", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(build(args.original, args.audit, args.bad_windows, args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/clean_eval.py b/home/wuyifan/a7_rotation_fix_20260930_code/clean_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..888132d52b7c6e468fab8ecb62bac9627b82caf8 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/clean_eval.py @@ -0,0 +1,139 @@ +"""Evaluate a complete clean-GT checkpoint on frozen native-GT panels.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import ASSETS, INDEX, ROOT, model_for, sha, training_code_hashes +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.h2o_dataset import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +FOUR_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", +) + + +def dataset_for(source: str, manifest: Path): + hw = (512, 896) + if source == "H2O": + return H2OCam4Dataset( + "/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, hw, + clip_lengths=(8,), strides=(1,), window_step=8, + allow_partial=False, + ) + if source == "ARCTIC": + return ARCTICClipDataset(manifest, ASSETS["mano_root"], hw) + if source == "HOT3D": + return HOT3DClipDataset( + "/SSD3/jiasen/foundation_hand/HOT3D/dataset", manifest, + Path(__file__).parent / "third_party", ASSETS["mano_root"], + hw, K_input_dropout=0.0, + ) + raise ValueError(source) + + +def apply_mode(batch: dict, mode: str) -> None: + frame = batch["frame_valid"].bool() + K = frame.clone() if mode != "rgb" else torch.zeros_like(frame) + depth = frame.clone() if mode == "rgb_depth_k" else torch.zeros_like(frame) + batch["K_input_available"] = K + batch["depth_input_available"] = depth + batch["K_available"] = K.clone() + batch["depth_available"] = depth.clone() + if not (torch.equal(batch["K_input_available"], K) + and torch.equal(batch["depth_input_available"], depth)): + raise RuntimeError("input availability override failed") + + +def run(args: argparse.Namespace) -> dict: + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + if panel_report["train_manifest_sha256"] != "b4b0ac4bc4a771c9bc7626a9eec7f5f541ef96908a9a64d219192efd7b8f7f89": + raise RuntimeError("frozen training allowlist identity differs") + if args.role == "confirmation" and not args.final_checkpoint: + raise ValueError("confirmation is reserved for a frozen final checkpoint") + if args.source != "H2O" and args.mode == "rgb_depth_k": + raise ValueError("only H2O has real metric depth") + manifest = panels / f"{args.source.lower()}_{args.role}_t8.jsonl" + expected = panel_report["sources"][args.source][args.role]["manifest_sha256"] + if sha(manifest) != expected: + raise RuntimeError("validation panel SHA256 changed") + if args.output.exists(): + raise FileExistsError(args.output) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if not state.get("complete_backbone") or state["index_sha256"] != sha(INDEX): + raise RuntimeError("checkpoint lacks complete DINO or filtered-index identity") + if state.get("smoke", False) and not args.allow_smoke: + raise RuntimeError("smoke checkpoint is not valid for formal evaluation") + code_match = state["code_sha256"] == training_code_hashes() + if not code_match and not args.allow_smoke: + raise RuntimeError("evaluation code differs from checkpoint training code") + if args.role == "confirmation" and ( + state.get("smoke", False) or state["stage"] != "S4" + or state["update"] != 66667 + ): + raise RuntimeError("confirmation requires the frozen S4 endpoint") + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + dataset = dataset_for(args.source, manifest) + if args.limit is not None and not args.allow_smoke: + raise ValueError("subset evaluation must be marked as smoke") + limit = min(len(dataset), args.limit) if args.limit is not None else len(dataset) + rows = [] + with torch.inference_mode(): + for index in range(limit): + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"): + prediction = model(batch) + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows.append(make_row(prediction, batch, 0, frame, side)) + summary = aggregate(rows) + report = { + "role": args.role, "source": args.source, "input_mode": args.mode, + "checkpoint": str(args.checkpoint), "checkpoint_sha256": sha(args.checkpoint), + "checkpoint_stage": state["stage"], "checkpoint_update": state["update"], + "panel_sha256": expected, "clips": limit, "hands": len(rows), + "smoke": bool(args.allow_smoke), + "checkpoint_code_match": code_match, + "evaluator_sha256": sha(Path(__file__)), + "metric_impl_sha256": sha(Path(__file__).parent / "scripts/evaluate_phase7_external.py"), + "four_metrics": {name: summary[name] for name in FOUR_METRICS}, + "supervision_coverage": summary["supervision_coverage"], + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--role", choices=("development", "confirmation"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--final-checkpoint", action="store_true") + parser.add_argument("--allow-smoke", action="store_true") + parser.add_argument("--limit", type=int) + args = parser.parse_args() + print(json.dumps(run(args), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/clean_train.py b/home/wuyifan/a7_rotation_fix_20260930_code/clean_train.py new file mode 100644 index 0000000000000000000000000000000000000000..3887eb28769f77ab87cea0c5fa960955b78dcf80 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/clean_train.py @@ -0,0 +1,558 @@ +"""Fresh-DINO staged Foundation Hand training on the frozen filtered-GT index. + +Use torchrun for DDP. This entry never loads a learned Foundation Hand parent. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from contextlib import nullcontext +from datetime import timedelta +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import sys +import time + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import numpy as np +import torch +import torch.distributed as dist +from torch import nn +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader, Dataset, Sampler +from safetensors import safe_open + +from coverage_sampler import CoverageSampler, SOURCES +from filtered_dataset import FilteredClipDataset +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.losses import BimanualLoss, LossConfig +from foundation_hand.training.optimizer import optimizer_parameter_groups, set_scheduled_learning_rate +from foundation_hand.training.schedule import warmup_cosine_learning_rate +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925") +INDEX = ROOT / "cache/trainable_t8_index.sqlite" +MANIFESTS = ROOT / "cache" +EXPECTED_INDEX_SHA256 = "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462" +EXPECTED_MANIFEST_SHA256 = { + 1: {"ARCTIC": "489315448fef1a2adcb50d7ba162d3d376810d0fa652905330d5e3db77620c62", + "H2O": "7bca84c00e66e9680704d5c54b1001af637cda620ef4f31037626407dcd8dc88", + "HOT3D": "391c837142e5985bf45c505bc9c3f3daa7f220c3a4144bad51635ca1f632e15f"}, + 8: {"ARCTIC": "35b61473010ae198b036d3c549ae1b922439e35711e5bc76f7f06c58fd82e7e6", + "H2O": "74e20172e321b363523f05497b891834d88edd0f349acb58288a4e6f37e01a8a", + "HOT3D": "8630298efbce16764a0c1d7bc108f46675c26a9fc290553b7920420b74f877b7"}, +} +ASSETS = { + "dinov3_source": "/home/jiasen/foundation_hand/third_party/dinov3", + "dinov3_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "mano_root": "/SSD3/jiasen/foundation_hand/pretrained/mano", +} +STAGES = { + "S1": {"time": 1, "hw": (368, 640), "updates": 16667, + "coverage": "S1_S3", "offset": 0, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S2": {"time": 8, "hw": (368, 640), "updates": 50000, + "coverage": "S1_S3", "offset": 0, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S3": {"time": 8, "hw": (512, 896), "updates": 83334, + "coverage": "S1_S3", "offset": 300000, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S4": {"time": 8, "hw": (512, 896), "updates": 66667, + "coverage": "S4", "offset": 0, "max_lr": 1e-5, "min_lr": 1e-6, "last2": 2}, +} +LOSS = LossConfig( + joint2d=1.0, joint3d_camera=10.0, joint3d_root_relative=10.0, + vertices_camera=1.0, local_pose=1.0, global_orientation=1.0, + shape=.1, translation=10.0, reprojection=1.0, + temporal_velocity=.1, temporal_acceleration=.05, + bimanual_relative_wrist=1.0, presence=0.0, +) +FRESH_HEAD_WEIGHT_STD = 0.001 +FRESH_DEPTH_WEIGHT_STD = 0.001 +MONITORED_LOSSES = ( + "joint2d", "joint3d_camera", "joint3d_root_relative", "vertices_camera", + "local_pose", "global_orientation", "shape", "translation", + "reprojection", "temporal_velocity", "temporal_acceleration", + "bimanual_relative_wrist", +) +TRANSLATION_DIAGNOSTICS = tuple( + f"translation_{axis}_{suffix}" + for axis in ("x", "y", "z") + for suffix in ("raw_mae_m", "effective_loss_contribution") +) +MASK_FIELDS = ( + "joint2d_valid", "joint3d_valid", "joint3d_root_relative_valid", + "translation_valid", "mano_pose_valid", "shape_valid", + "vertices_valid", "reprojection_valid", +) + + +def sha(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def training_code_hashes() -> dict[str, str]: + code_root = Path(__file__).parent + paths = [code_root / name for name in ( + "clean_train.py", "filtered_dataset.py", "coverage_sampler.py", + "export_adapter_manifests.py", "build_trainable_index.py", + )] + list((code_root / "src/foundation_hand").rglob("*.py")) + list( + (code_root / "third_party/hot3d").rglob("*.py") + ) + return {str(path.relative_to(code_root)): sha(path) for path in sorted(paths)} + + +class MixedDataset(Dataset): + def __init__(self, time: int, hw: tuple[int, int]): + manifests = MANIFESTS / f"adapter_trainable_t{time}" + self.sources = { + source: FilteredClipDataset( + source, manifests / f"{source.lower()}_t{time}.jsonl", time, + hw, ASSETS["mano_root"], Path(__file__).parent / "third_party", + {"enabled": source != "HOT3D", "probability": .8}, + ) + for source in SOURCES + } + + def __len__(self) -> int: + return sum(map(len, self.sources.values())) + + def __getitem__(self, spec: dict): + return self.sources[str(spec["source"])][spec] + + +class PositionSampler(Sampler[dict]): + def __init__(self, coverage: CoverageSampler, first: int, last: int, rank: int, world: int): + self.coverage, self.first, self.last = coverage, first, last + self.rank, self.world = rank, world + + def __iter__(self): + yield from self.coverage.shard(self.first, self.last, self.rank, self.world) + + def __len__(self): + return (self.last - self.first) // self.world + + +class Objective(nn.Module): + def __init__(self, model: BimanualReconstructionModel): + super().__init__() + self.model = model + self.criterion = BimanualLoss(LOSS) + + def forward(self, batch: dict): + prediction = self.model(batch) + losses = self.criterion(prediction, batch) + with torch.no_grad(): + losses.update(self.criterion.translation_diagnostics(prediction, batch)) + return losses + + +def model_for(stage: str) -> BimanualReconstructionModel: + options = STAGES[stage] + config = ModelConfig( + encoder="dinov3", decoder_dim=512, decoder_layers=3, attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, + depth_mode="geometry", depth_gate_mode="fixed", depth_gate_fixed_value=.5, + use_rays=True, use_bimanual_interaction=True, predict_presence=True, + require_mano=True, mano_fix_left_shapedirs=True, + modality_dropout_prob=0.0, temporal_position_mode="none", + temporal_attention_mode="bidirectional", dinov3_trainable_last_blocks=options["last2"], + translation_parameterization="direct_xyz", **ASSETS, + ) + model = BimanualReconstructionModel(config) + if stage == "S1": + with torch.no_grad(): + for head in ( + model.joint2d_head, model.rotation_head, + model.translation_head, model.shape_head, + ): + nn.init.normal_(head.weight, std=FRESH_HEAD_WEIGHT_STD) + nn.init.normal_( + model.depth_encoder.encoder[-1].weight, + std=FRESH_DEPTH_WEIGHT_STD, + ) + model.presence_head.requires_grad_(False) + if stage == "S1": + model.decoder.temporal_enabled = False + model.decoder.temporal.requires_grad_(False) + return model + + +def verify_official_dino(model: BimanualReconstructionModel) -> dict: + weight_file = Path(ASSETS["dinov3_weights"]) / "model.safetensors" + backbone = model.rgb_encoder.backbone.state_dict() + with safe_open(str(weight_file), framework="pt", device="cpu") as weights: + if set(backbone) != set(weights.keys()): + raise RuntimeError("pretrained DINO tensor names differ from model backbone") + for name, value in backbone.items(): + if not torch.equal(value.cpu(), weights.get_tensor(name)): + raise RuntimeError(f"DINO differs from official weight: {name}") + return {"tensors_equal": len(backbone), "official_safetensors_sha256": sha(weight_file), + "projection_is_new": "projection.weight" not in backbone} + + +def rng_state(device: torch.device) -> dict: + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state(device)} + + +def restore_rng(state: dict, device: torch.device) -> None: + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"].cpu()) + torch.cuda.set_rng_state(state["cuda"].cpu(), device) + + +def gradient_group_norms(model: nn.Module) -> dict[str, float]: + squared: dict[str, torch.Tensor] = {} + for name, parameter in model.named_parameters(): + if parameter.grad is None: + continue + parts = name.split(".") + group = ".".join(parts[:2]) if parts[0] in ("rgb_encoder", "decoder") else parts[0] + squared[group] = squared.get(group, parameter.grad.new_zeros(())) + parameter.grad.float().square().sum() + return {name: float(value.sqrt()) for name, value in squared.items()} + + +def storage_guard(start: bool) -> None: + devices = {path.stat().st_dev for path in (ROOT, ROOT / "cache", ROOT / "checkpoints", ROOT / "logs", ROOT / "eval")} + if len(devices) != 1: + raise RuntimeError("run directories are not on the same filesystem") + free = shutil.disk_usage(ROOT).free + threshold = (300 if start else 200) * 1024**3 + if free < threshold: + raise RuntimeError(f"root disk free {free / 1024**3:.1f} GiB below stage guard") + checkpoint_bytes = sum( + path.stat().st_size for path in (ROOT / "checkpoints").rglob("*.pt") + if not any("smoke" in component for component in path.relative_to(ROOT).parts) + ) + if not start and checkpoint_bytes + 2 * 1024**3 > 40 * 1024**3: + raise RuntimeError("checkpoint budget cannot fit another full checkpoint") + + +def checkpoint( + path: Path, stage: str, update: int, model: nn.Module, + optimizer: torch.optim.Optimizer, counts: Counter, supervision_counts: Counter, + device: torch.device, + rank: int, world: int, code_hashes: dict, data_hashes: dict, smoke: bool, + grad_clip: float, +) -> None: + local_rng = rng_state(device) + all_rng = [None] * world if rank == 0 else None + if world > 1: + dist.gather_object(local_rng, all_rng, dst=0) + else: + all_rng = [local_rng] + if rank == 0: + storage_guard(False) + if path.exists() or path.with_suffix(".tmp").exists(): + raise FileExistsError(f"checkpoint path is occupied: {path}") + state = { + "model": model.state_dict(), "optimizer": optimizer.state_dict(), + "stage": stage, "update": update, "world_size": world, + "next_global_sample_position": STAGES[stage]["offset"] + update * 6, + "index_sha256": sha(INDEX), "code_sha256": code_hashes, + "data_sha256": data_hashes, + "rank_rng_states": all_rng, "exposures": dict(counts), + "supervision_exposures": dict(supervision_counts), + "scheduler": {"stage_local_update": update, "total_updates": STAGES[stage]["updates"]}, + "complete_backbone": True, + "smoke": smoke, + "grad_clip": grad_clip, + } + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + temporary.replace(path) + loaded = torch.load(path, map_location="cpu", weights_only=False) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("checkpoint load-back failed") + print(f"checkpoint {path} sha256={sha(path)}", flush=True) + if world > 1: + dist.barrier(device_ids=[device.index]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--stage", choices=tuple(STAGES), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, required=True, help="Stage-local endpoint") + parser.add_argument("--workers", type=int, default=2) + parser.add_argument("--resume", type=Path) + parser.add_argument("--parent", type=Path) + parser.add_argument("--save", action="store_true") + parser.add_argument("--smoke", action="store_true", + help="Allow an incomplete prior-stage checkpoint for isolated preflight only") + parser.add_argument("--grad-clip", type=float, default=100.0) + args = parser.parse_args() + stage = args.stage + options = STAGES[stage] + if not 0 < args.updates <= options["updates"]: + raise ValueError("updates outside registered stage budget") + if not math.isfinite(args.grad_clip) or args.grad_clip <= 0: + raise ValueError("grad clip threshold must be finite and positive") + if not args.resume and (stage == "S1") == bool(args.parent): + raise ValueError("S1 requires no parent; S2/S3/S4 require a complete prior-stage parent") + if args.resume and args.parent: + raise ValueError("resume and stage parent are mutually exclusive") + rank = int(os.environ.get("RANK", 0)) + world = int(os.environ.get("WORLD_SIZE", 1)) + local_rank = int(os.environ.get("LOCAL_RANK", 0)) + if world not in (1, 2, 3, 6) or 6 % world: + raise ValueError("world size must divide global batch 6") + accumulation = 6 // world + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.cuda.set_device(local_rank) + device = torch.device("cuda", local_rank) + if world > 1: + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + storage_guard(True) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh run output already contains training metrics") + if world > 1: + dist.barrier(device_ids=[local_rank]) + code_hashes = training_code_hashes() + selected_manifests = MANIFESTS / f"adapter_trainable_t{options['time']}" + data_hashes = {name: sha(selected_manifests / f"{name.lower()}_t{options['time']}.jsonl") + for name in SOURCES} + if sha(INDEX) != EXPECTED_INDEX_SHA256 or data_hashes != EXPECTED_MANIFEST_SHA256[options["time"]]: + raise RuntimeError("frozen filtered index or native adapter manifest changed") + seed = 20260925 + rank + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed(seed) + model = model_for(stage) + dino_audit = verify_official_dino(model) if rank == 0 and stage == "S1" else None + model = model.to(device) + start = 0 + counts: Counter = Counter() + supervision_counts: Counter = Counter() + previous = args.resume or args.parent + state = None + if previous: + state = torch.load(previous, map_location="cpu", weights_only=False) + if not state.get("complete_backbone") or state["index_sha256"] != sha(INDEX): + raise RuntimeError("parent/resume checkpoint lacks full DINO or filtered-index identity") + if args.resume: + if (state["stage"] != stage or state["world_size"] != world + or state["code_sha256"] != code_hashes or state["data_sha256"] != data_hashes): + raise RuntimeError("exact resume contract mismatch") + if bool(state.get("smoke", False)) != args.smoke: + raise RuntimeError("smoke and formal checkpoints cannot be interchanged") + if float(state.get("grad_clip", 10.0)) != args.grad_clip: + raise RuntimeError("resume changed the gradient clipping threshold") + start = int(state["update"]) + counts.update(state["exposures"]) + supervision_counts.update(state["supervision_exposures"]) + else: + previous_stage = {"S2": "S1", "S3": "S2", "S4": "S3"}[stage] + if state["stage"] != previous_stage: + raise RuntimeError("stage parent is not the immediately preceding stage") + if not args.smoke and ( + state["update"] != STAGES[previous_stage]["updates"] + or state.get("smoke", False) + ): + raise RuntimeError("formal training requires a complete non-smoke prior stage") + if not args.smoke and state["code_sha256"] != code_hashes: + raise RuntimeError("formal stage parent was built with different training code") + if not args.smoke and STAGES[previous_stage]["time"] == options["time"]: + if state["data_sha256"] != data_hashes: + raise RuntimeError("T8 adapter manifests changed across formal stages") + model.load_state_dict(state["model"], strict=True) + model.train() + params = [parameter for parameter in model.parameters() if parameter.requires_grad] + backbone_lr = 5e-7 if stage == "S4" else None + optimizer = torch.optim.AdamW( + optimizer_parameter_groups(model, learning_rate=options["max_lr"], + backbone_learning_rate=backbone_lr), weight_decay=.05, + ) + if args.resume: + optimizer.load_state_dict(state["optimizer"]) + restore_rng(state["rank_rng_states"][rank], device) + del state + if not start < args.updates: + raise ValueError("resume checkpoint is already at or beyond requested endpoint") + dataset = MixedDataset(options["time"], options["hw"]) + coverage = CoverageSampler(INDEX, options["coverage"]) + first = options["offset"] + start * 6 + last = options["offset"] + args.updates * 6 + sampler = PositionSampler(coverage, first, last, rank, world) + loader = DataLoader(dataset, batch_size=1, sampler=sampler, + num_workers=args.workers, collate_fn=collate_h2o_clips, + pin_memory=True, persistent_workers=args.workers > 0, + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + objective = Objective(model).to(device) + if world > 1: + objective = DDP(objective, device_ids=[local_rank], output_device=local_rank, + broadcast_buffers=False, find_unused_parameters=True) + if rank == 0: + log = (args.output / "metrics.jsonl").open("a", buffering=1) + if dino_audit: + print(json.dumps({"official_dino_audit": dino_audit}), flush=True) + start_clock = time.monotonic() + torch.cuda.reset_peak_memory_stats(device) + for update in range(start, args.updates): + lr = warmup_cosine_learning_rate(update, options["updates"], + options["max_lr"], options["min_lr"], 1000) + set_scheduled_learning_rate(optimizer, lr) + optimizer.zero_grad(set_to_none=True) + losses_total = torch.zeros((), device=device) + local_modes = Counter() + local_supervision = Counter() + detailed = update < 10 or (update + 1) % 100 == 0 or update + 1 == args.updates + local_details: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + for micro in range(accumulation): + cpu = next(iterator) + source_name = cpu["sampling_source_id"][0] + local_modes[f"{source_name}:{cpu['input_mode'][0]}"] += 1 + batch = move_to_device(cpu, device) + mode_key = f"{source_name}:{cpu['input_mode'][0]}" + for name in MASK_FIELDS: + if name in cpu: + for side in range(2): + local_supervision[f"{mode_key}:{side}:{name}"] += int( + cpu[name][:, :, side].sum() + ) + attach_gt_vertices(batch, model) + sync = objective.no_sync() if world > 1 and micro + 1 < accumulation else nullcontext() + with sync, torch.autocast("cuda", dtype=torch.bfloat16): + losses = objective(batch) + if not torch.isfinite(losses["total"]): + raise RuntimeError(f"nonfinite loss at {stage} update {update}") + (losses["total"] / accumulation).backward() + losses_total += losses["total"].detach() / accumulation + if detailed: + detail = local_details[mode_key] + detail["samples"] += 1 + detail["loss_sums"].update({name: float(losses[name].detach()) + for name in MONITORED_LOSSES + TRANSLATION_DIAGNOSTICS}) + detail["valid_elements"].update({name: int(cpu[name].sum()) + for name in MASK_FIELDS if name in cpu}) + grad_groups = gradient_group_norms(model) if detailed and rank == 0 else None + grad_norm = torch.nn.utils.clip_grad_norm_(params, args.grad_clip) + if not torch.isfinite(grad_norm): + raise RuntimeError(f"nonfinite gradient norm at {stage} update {update}") + norm_min, norm_max = grad_norm.detach().clone(), grad_norm.detach().clone() + if world > 1: + dist.all_reduce(norm_min, op=dist.ReduceOp.MIN) + dist.all_reduce(norm_max, op=dist.ReduceOp.MAX) + optimizer.step() + if world > 1: + dist.all_reduce(losses_total) + gathered = [None] * world + dist.all_gather_object(gathered, { + "modes": dict(local_modes), "supervision": dict(local_supervision), + "details": dict(local_details) if detailed else {}, + }) + else: + gathered = [{"modes": dict(local_modes), + "supervision": dict(local_supervision), + "details": dict(local_details) if detailed else {}}] + for value in gathered: + counts.update(value["modes"]) + supervision_counts.update(value["supervision"]) + if rank == 0: + row = {"stage": stage, "update": update + 1, + "loss": float(losses_total / world), + "grad_norm_min": float(norm_min), "grad_norm_max": float(norm_max), + "clipped": float(norm_max) > args.grad_clip, + "grad_clip_threshold": args.grad_clip, "lr": lr, + "exposures": dict(counts)} + if detailed: + source_sums: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + mode_sums: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + for value in gathered: + for source_mode, detail in value["details"].items(): + source_name = source_mode.split(":", 1)[0] + for target in (source_sums[source_name], mode_sums[source_mode]): + target["samples"] += detail["samples"] + target["loss_sums"].update(detail["loss_sums"]) + target["valid_elements"].update(detail["valid_elements"]) + row["loss_terms"] = { + name: sum(detail["loss_sums"][name] for detail in source_sums.values()) / 6 + for name in MONITORED_LOSSES + } + row["source_loss_terms"] = { + source_name: {name: detail["loss_sums"][name] / detail["samples"] + for name in MONITORED_LOSSES} + for source_name, detail in source_sums.items() + } + row["source_valid_elements"] = { + source_name: dict(detail["valid_elements"]) + for source_name, detail in source_sums.items() + } + row["source_mode_loss_terms"] = { + source_mode: {name: detail["loss_sums"][name] / detail["samples"] + for name in MONITORED_LOSSES} + for source_mode, detail in mode_sums.items() + } + row["source_mode_translation_axes"] = { + source_mode: {name: detail["loss_sums"][name] / detail["samples"] + for name in TRANSLATION_DIAGNOSTICS} + for source_mode, detail in mode_sums.items() + } + row["source_mode_valid_elements"] = { + source_mode: dict(detail["valid_elements"]) + for source_mode, detail in mode_sums.items() + } + row["supervision_exposures"] = dict(supervision_counts) + row["grad_parameter_groups"] = grad_groups + log.write(json.dumps(row) + "\n") + if args.updates <= 10 or (update + 1) % 500 == 0 or update + 1 == args.updates: + print(json.dumps(row), flush=True) + milestone = update + 1 + registered = options["updates"] + if milestone < args.updates and ( + milestone % 10000 == 0 or milestone in { + round(registered * .25), round(registered * .50), round(registered * .75), + } + ): + checkpoint(args.output / f"{stage.lower()}_update_{milestone:07d}.pt", + stage, milestone, model, optimizer, counts, supervision_counts, + device, rank, world, code_hashes, data_hashes, + args.smoke, args.grad_clip) + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start_clock + elapsed_max = torch.tensor(elapsed, device=device) + peak_memory = torch.tensor(torch.cuda.max_memory_allocated(device) / 1024**3, device=device) + if world > 1: + dist.all_reduce(elapsed_max, op=dist.ReduceOp.MAX) + dist.all_reduce(peak_memory, op=dist.ReduceOp.MAX) + if rank == 0: + log.close() + print(json.dumps({"stage": stage, "elapsed_seconds_max": float(elapsed_max), + "clips_per_second": (args.updates - start) * 6 / float(elapsed_max), + "peak_allocated_gib_per_rank_max": float(peak_memory)}), flush=True) + if args.save: + path = args.output / f"{stage.lower()}_update_{args.updates:07d}.pt" + checkpoint(path, stage, args.updates, model, optimizer, counts, + supervision_counts, + device, rank, world, code_hashes, data_hashes, + args.smoke, args.grad_clip) + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/compare_checkpoints.py b/home/wuyifan/a7_rotation_fix_20260930_code/compare_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7c8dbf5e02277d9cf98379adc69bf013f7f9ed --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/compare_checkpoints.py @@ -0,0 +1,62 @@ +"""Compare continuous and resumed training checkpoints tensor by tensor.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + + +def compare(left: Path, right: Path) -> dict: + a = torch.load(left, map_location="cpu", weights_only=False) + b = torch.load(right, map_location="cpu", weights_only=False) + if (a["stage"], a["update"], a["next_global_sample_position"], a["exposures"], + a.get("supervision_exposures"), a.get("grad_clip")) != ( + b["stage"], b["update"], b["next_global_sample_position"], b["exposures"], + b.get("supervision_exposures"), b.get("grad_clip") + ): + raise AssertionError("stage/update/sampler cursor/exposures/optimizer contract differ") + model_differences = [] + if set(a["model"]) != set(b["model"]): + raise AssertionError("model tensor key sets differ") + for key in a["model"]: + if not torch.equal(a["model"][key], b["model"][key]): + model_differences.append(key) + if a["optimizer"]["param_groups"] != b["optimizer"]["param_groups"]: + raise AssertionError("optimizer parameter groups differ") + optimizer_differences = [] + left_states, right_states = a["optimizer"]["state"], b["optimizer"]["state"] + if set(left_states) != set(right_states): + raise AssertionError("optimizer state parameter IDs differ") + for parameter in left_states: + if set(left_states[parameter]) != set(right_states[parameter]): + raise AssertionError(f"optimizer state fields differ for parameter {parameter}") + for key, value in left_states[parameter].items(): + other = right_states[parameter][key] + equal = torch.equal(value, other) if torch.is_tensor(value) else value == other + if not equal: + optimizer_differences.append(f"{parameter}:{key}") + result = {"status": "pass" if not model_differences and not optimizer_differences else "fail", + "model_tensors": len(a["model"]), "model_differences": model_differences[:10], + "optimizer_states": len(left_states), + "optimizer_differences": optimizer_differences[:10], + "stage": a["stage"], "update": a["update"], + "next_global_sample_position": a["next_global_sample_position"]} + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("left", type=Path) + parser.add_argument("right", type=Path) + args = parser.parse_args() + result = compare(args.left, args.right) + print(json.dumps(result, indent=2)) + if result["status"] != "pass": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/coverage_sampler.py b/home/wuyifan/a7_rotation_fix_20260930_code/coverage_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..2c00edc8e430b4c5421cb1491b0db472633be9fd --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/coverage_sampler.py @@ -0,0 +1,116 @@ +"""Stateless source quotas and source-local no-replacement GT tile coverage.""" + +from __future__ import annotations + +from collections import defaultdict +import hashlib +import random +import sqlite3 +from pathlib import Path + + +SOURCES = ("H2O", "ARCTIC", "HOT3D") +QUOTAS = {"S1_S3": (8, 7, 5), "S4": (7, 5, 8)} +RECORDING_BLOCK_TILES = 64 + + +def _seed(*values: object) -> int: + encoded = "|".join(map(str, values)).encode("utf-8") + return int.from_bytes(hashlib.blake2b(encoded, digest_size=8).digest(), "little") + + +class CoverageSampler: + """A global sample position determines one immutable tile and input mode. + + S2 and S3 share S1_S3 positions 0..799999. S4 uses a new independent + position space, seed, and coverage ledger. DDP rank r reads positions + start+r, start+r+world_size, etc.; resume needs only the next global + position and the frozen index/code hashes. + """ + + def __init__(self, index: str | Path, stage: str, seed: int = 20260925): + if stage not in QUOTAS: + raise ValueError(f"unknown coverage stage {stage}") + self.stage = stage + self.seed = int(seed) + self.quota = QUOTAS[stage] + self.by_recording: dict[str, dict[str, list[str]]] = { + name: defaultdict(list) for name in SOURCES + } + with sqlite3.connect(index) as connection: + rows = connection.execute( + "SELECT source, recording_id, tile_id FROM tiles " + "ORDER BY source, recording_id, tile_id" + ) + for source, recording, tile_id in rows: + self.by_recording[source][recording].append(tile_id) + self.sizes = { + source: sum(map(len, self.by_recording[source].values())) + for source in SOURCES + } + if min(self.sizes.values()) <= 0: + raise ValueError("each source must contain at least one tile") + self._permutation_cache: dict[tuple[str, int], list[str]] = {} + self._cycle_cache: tuple[int, list[str]] | None = None + + def source_and_ordinal(self, position: int) -> tuple[str, int]: + if position < 0: + raise ValueError("negative sample position") + cycle, within = divmod(position, sum(self.quota)) + if self._cycle_cache is None or self._cycle_cache[0] != cycle: + order = [source for source, count in zip(SOURCES, self.quota) for _ in range(count)] + random.Random(_seed(self.seed, self.stage, "source", cycle)).shuffle(order) + self._cycle_cache = (cycle, order) + else: + order = self._cycle_cache[1] + source = order[within] + source_index = SOURCES.index(source) + ordinal = cycle * self.quota[source_index] + order[:within].count(source) + return source, ordinal + + def _epoch_order(self, source: str, epoch: int) -> list[str]: + key = (source, epoch) + if key in self._permutation_cache: + return self._permutation_cache[key] + randomizer = random.Random(_seed(self.seed, self.stage, source, epoch)) + recordings = list(self.by_recording[source]) + randomizer.shuffle(recordings) + groups = [] + for recording in recordings: + group = self.by_recording[source][recording].copy() + randomizer.shuffle(group) + groups.append(group) + result: list[str] = [] + depth = 0 + while len(result) < self.sizes[source]: + for group in groups: + result.extend(group[depth:depth + RECORDING_BLOCK_TILES]) + depth += RECORDING_BLOCK_TILES + if len(result) != len(set(result)): + raise AssertionError(f"duplicate tile in {source} epoch {epoch}") + for old_key in list(self._permutation_cache): + if old_key[0] == source and old_key[1] < epoch - 1: + del self._permutation_cache[old_key] + self._permutation_cache[key] = result + return result + + def sample(self, position: int) -> dict[str, object]: + source, ordinal = self.source_and_ordinal(position) + epoch, offset = divmod(ordinal, self.sizes[source]) + tile_id = self._epoch_order(source, epoch)[offset] + mode_rng = random.Random(_seed(self.seed, self.stage, "mode", position)) + K_drop = {"H2O": .20, "ARCTIC": .50, "HOT3D": .30}[source] + K_available = mode_rng.random() >= K_drop + depth_available = source == "H2O" and K_available and mode_rng.random() >= .125 + mode = "rgb_depth_k" if depth_available else "rgb_k" if K_available else "rgb" + return { + "position": position, "source": source, "source_ordinal": ordinal, + "epoch": epoch, "tile_id": tile_id, "mode": mode, + } + + def shard(self, start: int, stop: int, rank: int, world_size: int): + if not 0 <= start <= stop or not 0 <= rank < world_size: + raise ValueError("invalid range or rank") + first = start + (rank - start) % world_size + for position in range(first, stop, world_size): + yield self.sample(position) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_formal_loss_spikes.py b/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_formal_loss_spikes.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f7417d5a9744b021aee827ed7f0b8e0e7bc4c2 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_formal_loss_spikes.py @@ -0,0 +1,85 @@ +"""Replay selected S1 sample positions with a fixed checkpoint for loss diagnosis.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for +from coverage_sampler import CoverageSampler +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def run(checkpoint: Path, updates: list[int]) -> dict: + state = torch.load(checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S1" or state.get("smoke"): + raise ValueError("diagnostic requires a formal S1 checkpoint") + torch.set_num_threads(2) + device = torch.device("cuda", 0) + model = model_for("S1") + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + criterion = BimanualLoss(LOSS) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + sampler = CoverageSampler(INDEX, "S1_S3") + results = [] + with torch.inference_mode(): + for update in updates: + for position in range((update - 1) * 6, update * 6): + spec = sampler.sample(position) + cpu = collate_h2o_clips([dataset[spec]]) + batch = move_to_device(cpu, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + joint_valid = batch["joint3d_valid"].bool() + reproj_valid = batch["reprojection_valid"].bool() + gt_z = batch["joint3d_camera"][..., 2][joint_valid] + pred_z = prediction["joints_camera"][..., 2][joint_valid] + gt_2d = batch["joint2d"][reproj_valid] + item = { + "update": update, + "position": position, + "source": spec["source"], + "mode": spec["mode"], + "tile_id": spec["tile_id"], + "loss": float(losses["total"]), + "terms": {name: float(value) for name, value in losses.items() + if name != "total" and float(value) != 0}, + "valid_joint_elements": int(joint_valid.sum()), + "valid_reprojection_elements": int(reproj_valid.sum()), + "gt_z_min_max_m": [float(gt_z.min()), float(gt_z.max())] if gt_z.numel() else None, + "pred_z_min_max_m": [float(pred_z.min()), float(pred_z.max())] if pred_z.numel() else None, + "gt_2d_min_max_px": [float(gt_2d.min()), float(gt_2d.max())] + if gt_2d.numel() else None, + "focal_px": [float(batch["K"][0, 0, 0, 0]), float(batch["K"][0, 0, 1, 1])], + } + results.append(item) + return {"checkpoint": str(checkpoint), "checkpoint_update": state["update"], + "sample_count": len(results), "samples": results} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--updates", type=int, nargs="+", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + report = run(args.checkpoint, args.updates) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({"output": str(args.output), "sample_count": report["sample_count"], + "top_losses": sorted(((row["loss"], row["position"], row["source"]) + for row in report["samples"]), reverse=True)[:10]})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_gradient_outliers.py b/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_gradient_outliers.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3f55b373393f1666b75068fe2a9f00adb5a5d0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_gradient_outliers.py @@ -0,0 +1,83 @@ +"""Read-only per-tile gradient probe for registered S2 sample positions.""" + +from __future__ import annotations + +import argparse +import json +import math + +import torch + +from clean_train import ( + INDEX, LOSS, MixedDataset, attach_gt_vertices, collate_h2o_clips, + gradient_group_norms, model_for, move_to_device, +) +from coverage_sampler import CoverageSampler +from foundation_hand.training.losses import BimanualLoss + + +def minimum(values: torch.Tensor, mask: torch.Tensor) -> float | None: + selected = values.detach()[mask] + return float(selected.min()) if selected.numel() else None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--steps", type=int, nargs="+", required=True) + args = parser.parse_args() + + torch.set_num_threads(2) + device = torch.device("cuda:0") + model = model_for("S2").to(device) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S2" or not state["complete_backbone"]: + raise ValueError("expected a full S2 checkpoint") + model.load_state_dict(state["model"], strict=True) + del state + model.train() + criterion = BimanualLoss(LOSS).to(device) + sampler = CoverageSampler(INDEX, "S1_S3") + dataset = MixedDataset(8, (368, 640)) + + for step in args.steps: + if step < 1: + raise ValueError("steps are 1-based") + for rank in range(6): + spec = sampler.sample((step - 1) * 6 + rank) + cpu = collate_h2o_clips([dataset[spec]]) + batch = move_to_device(cpu, device) + attach_gt_vertices(batch, model) + model.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + losses["total"].backward() + groups = gradient_group_norms(model) + + z = prediction["joints_camera"][..., 2].detach() + valid = batch["reprojection_valid"].bool() & (z > 0) + rotation = prediction["mano_rotations_6d"].detach().float() + first = torch.nn.functional.normalize(rotation[..., :3], dim=-1) + second = rotation[..., 3:] + residual = second - (first * second).sum(dim=-1, keepdim=True) * first + report = { + "step": step, + "rank": rank, + "source": spec["source"], + "tile_id": spec["tile_id"], + "mode": spec["mode"], + "loss": float(losses["total"].detach()), + "reprojection_loss": float(losses["reprojection"].detach()), + "grad_norm": math.sqrt(sum(value * value for value in groups.values())), + "grad_groups_top": sorted(groups.items(), key=lambda item: -item[1])[:5], + "min_positive_valid_joint_z_m": minimum(z, valid), + "positive_valid_joint_z_below_1cm": int((valid & (z < .01)).sum()), + "min_rotation_first_norm": float(rotation[..., :3].norm(dim=-1).min()), + "min_rotation_orthogonal_residual_norm": float(residual.norm(dim=-1).min()), + } + print(json.dumps(report), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_initial_gradients.py b/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_initial_gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..4e08e92d1aae8e056f4bd01f0229a09efa660043 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_initial_gradients.py @@ -0,0 +1,90 @@ +"""Measure each weighted loss contribution to the clean-start gradient.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for, sha +from coverage_sampler import CoverageSampler, SOURCES +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def grad_norms(model) -> dict[str, float]: + sums: dict[str, torch.Tensor] = {} + for name, parameter in model.named_parameters(): + if parameter.grad is None: + continue + parts = name.split(".") + group = ".".join(parts[:2]) if parts[0] in ("rgb_encoder", "decoder") else parts[0] + sums[group] = sums.get(group, parameter.grad.new_zeros(())) + parameter.grad.float().square().sum() + return {name: float(value.sqrt()) for name, value in sums.items()} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S1" or state["index_sha256"] != sha(INDEX): + raise ValueError("expected complete S1 checkpoint on trainable index") + torch.cuda.set_device(0) + model = model_for("S1").cuda().train() + model.load_state_dict(state["model"], strict=True) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + sampler = CoverageSampler(INDEX, "S1_S3") + specs = {} + for position in range(200): + spec = sampler.sample(position) + specs.setdefault(spec["source"], spec) + if len(specs) == len(SOURCES): + break + criterion = BimanualLoss(LOSS) + report = {"checkpoint_sha256": sha(args.checkpoint), "samples": {}} + for source, spec in specs.items(): + sample = dataset[spec] + batch = move_to_device(collate_h2o_clips([sample]), torch.device("cuda", 0)) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + losses = criterion(model(batch), batch) + components = {} + for name, value in losses.items(): + if name == "total" or float(value.detach()) == 0.0: + continue + model.zero_grad(set_to_none=True) + value.backward(retain_graph=True) + groups = grad_norms(model) + components[name] = {"weighted_loss": float(value.detach()), + "global_grad_norm": sum(x * x for x in groups.values()) ** .5, + "groups": groups} + model.zero_grad(set_to_none=True) + losses["total"].backward() + groups = grad_norms(model) + report["samples"][source] = { + "tile_id": spec["tile_id"], "mode": spec["mode"], + "total_loss": float(losses["total"].detach()), + "total_grad_norm": sum(x * x for x in groups.values()) ** .5, + "total_groups": groups, "components": components, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({source: { + "total_grad_norm": row["total_grad_norm"], + "largest_components": sorted( + ((name, entry["global_grad_norm"]) for name, entry in row["components"].items()), + key=lambda pair: pair[1], reverse=True, + )[:6], + "total_groups": row["total_groups"], + } for source, row in report["samples"].items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_s1_s2_temporal_transition.py b/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_s1_s2_temporal_transition.py new file mode 100644 index 0000000000000000000000000000000000000000..50fa8bf7a8f13085a4801d5b3286bc098be2ac1a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/diagnose_s1_s2_temporal_transition.py @@ -0,0 +1,85 @@ +"""Measure the temporal block's effect on a frozen staged model.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from clean_train import ROOT, model_for, sha +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--limit", type=int, default=32) + args = parser.parse_args() + if args.limit <= 0 or (args.source != "H2O" and args.mode == "rgb_depth_k"): + raise ValueError("invalid evaluation condition or limit") + + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + manifest = panels / f"{args.source.lower()}_development_t8.jsonl" + if sha(manifest) != panel_report["sources"][args.source]["development"]["manifest_sha256"]: + raise RuntimeError("frozen development panel changed") + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if (state["stage"] not in ("S1", "S2") or state["update"] < 2000 + or state.get("smoke") or not state.get("complete_backbone")): + raise RuntimeError("requires a complete formal S1/S2 checkpoint") + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + dataset = dataset_for(args.source, manifest) + limit = min(args.limit, len(dataset)) + rows = {False: [], True: []} + with torch.inference_mode(): + for index in range(limit): + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + for temporal_enabled in (False, True): + model.decoder.temporal_enabled = temporal_enabled + with torch.autocast(device.type, dtype=torch.bfloat16, + enabled=device.type == "cuda"): + prediction = model(batch) + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows[temporal_enabled].append( + make_row(prediction, batch, 0, frame, side) + ) + + summaries = {condition: aggregate(values) for condition, values in rows.items()} + counts_match = all( + summaries[False][metric]["count"] == summaries[True][metric]["count"] + for metric in FOUR_METRICS + ) + if not counts_match: + raise RuntimeError("temporal toggle changed metric denominators") + report = { + "checkpoint_sha256": sha(args.checkpoint), + "checkpoint_stage": state["stage"], "checkpoint_update": state["update"], + "source": args.source, "mode": args.mode, "clips": limit, + "temporal_off": {metric: summaries[False][metric] for metric in FOUR_METRICS}, + "temporal_on": {metric: summaries[True][metric] for metric in FOUR_METRICS}, + "temporal_on_minus_off": { + metric: summaries[True][metric]["mean"] - summaries[False][metric]["mean"] + for metric in FOUR_METRICS + }, + } + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/eval_stratified_probe.py b/home/wuyifan/a7_rotation_fix_20260930_code/eval_stratified_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..12e100450b2927f5f87f73686250de0a6ef0a932 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/eval_stratified_probe.py @@ -0,0 +1,195 @@ +"""Evaluate fixed, recording-spread development clips without checkpoint selection.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +import math +from pathlib import Path + +import torch + +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from clean_train import INDEX, ROOT, model_for, sha, training_code_hashes +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def choose_indices(manifest: Path, limit: int) -> tuple[list[int], int]: + groups: dict[str, list[int]] = defaultdict(list) + with manifest.open() as stream: + for index, line in enumerate(stream): + row = json.loads(line) + group = row.get("take", row.get("group_key")) + if not group: + raise ValueError(f"manifest row {index} has no recording group") + groups[str(group)].append(index) + if limit < len(groups): + raise ValueError("limit must include at least one clip per recording group") + + ordered: dict[str, list[int]] = {} + for group, indices in groups.items(): + size = len(indices) + priorities = [size // 2, size // 4, 3 * size // 4, 0, size - 1] + offsets = list(dict.fromkeys(priorities + list(range(size)))) + ordered[group] = [indices[offset] for offset in offsets] + + selected: list[int] = [] + for depth in range(max(map(len, ordered.values()))): + for group in sorted(ordered): + if depth < len(ordered[group]): + selected.append(ordered[group][depth]) + if len(selected) == limit: + return selected, len(groups) + raise ValueError("limit exceeds manifest length") + + +def paired_group_deltas(reference: list[dict], candidate: list[dict], field: str) -> dict: + if len(reference) != len(candidate): + raise RuntimeError("paired evaluations have different row counts") + groups: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for first, second in zip(reference, candidate): + if first[field] != second[field]: + raise RuntimeError(f"paired {field} identities differ") + for name in FOUR_METRICS: + first_value, second_value = float(first[name]), float(second[name]) + if math.isfinite(first_value) != math.isfinite(second_value): + raise RuntimeError(f"paired {name} validity differs for {field}={first[field]}") + if math.isfinite(first_value): + groups[str(first[field])][name].append(second_value - first_value) + return { + group: { + name: {"count": len(values), "mean_delta": sum(values) / len(values)} + for name, values in metrics.items() + } + for group, metrics in sorted(groups.items()) + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--compare-checkpoint", type=Path) + parser.add_argument("--reference-temporal-off", action="store_true") + parser.add_argument("--compare-temporal-off", action="store_true") + parser.add_argument("--paired-groups", action="store_true") + parser.add_argument("--hybrid-parent-root", action="store_true") + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--limit", type=int, default=32) + args = parser.parse_args() + if args.source != "H2O" and args.mode == "rgb_depth_k": + raise ValueError("only H2O has real metric depth") + if args.compare_temporal_off and not args.compare_checkpoint: + raise ValueError("--compare-temporal-off requires --compare-checkpoint") + if args.paired_groups and not args.compare_checkpoint: + raise ValueError("--paired-groups requires --compare-checkpoint") + if args.hybrid_parent_root and not args.compare_checkpoint: + raise ValueError("--hybrid-parent-root requires --compare-checkpoint") + + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + manifest = panels / f"{args.source.lower()}_development_t8.jsonl" + expected = panel_report["sources"][args.source]["development"]["manifest_sha256"] + if sha(manifest) != expected: + raise RuntimeError("frozen development panel changed") + dataset = dataset_for(args.source, manifest) + indices, groups = choose_indices(manifest, args.limit) + if len(dataset) != sum(1 for _ in manifest.open()): + raise RuntimeError("dataset indices differ from frozen manifest rows") + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + checkpoints = [args.checkpoint] + if args.compare_checkpoint: + checkpoints.append(args.compare_checkpoint) + models = [] + identities = [] + for model_index, path in enumerate(checkpoints): + state = torch.load(path, map_location="cpu", weights_only=False) + if (state.get("smoke") or not state.get("complete_backbone") + or state["index_sha256"] != sha(INDEX) + or state["code_sha256"] != training_code_hashes()): + raise RuntimeError(f"checkpoint is not a complete matching formal state: {path}") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + if ((model_index == 0 and args.reference_temporal_off) + or (model_index == 1 and args.compare_temporal_off)): + model.decoder.temporal_enabled = False + models.append(model.to(device).eval()) + identities.append({ + "checkpoint_sha256": sha(path), "stage": state["stage"], + "update": state["update"], + "temporal_enabled": bool(model.decoder.temporal_enabled), + }) + if args.hybrid_parent_root: + identities.append({ + **identities[1], "variant": "compare_local_reference_root", + "root_checkpoint_sha256": identities[0]["checkpoint_sha256"], + }) + rows = [[] for _ in identities] + with torch.inference_mode(): + for index in indices: + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, models[0]) + predictions = [] + for model in models: + with torch.autocast(device.type, dtype=torch.bfloat16, + enabled=device.type == "cuda"): + predictions.append(model(batch)) + if args.hybrid_parent_root: + parent, candidate = predictions + delta = parent["wrist_root_translation"] - candidate["wrist_root_translation"] + hybrid = dict(candidate) + hybrid["wrist_root_translation"] = parent["wrist_root_translation"] + hybrid["joints_camera"] = candidate["joints_camera"] + delta.unsqueeze(-2) + hybrid["vertices_camera"] = candidate["vertices_camera"] + delta.unsqueeze(-2) + predictions.append(hybrid) + for model_index, prediction in enumerate(predictions): + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows[model_index].append( + make_row(prediction, batch, 0, frame, side) + ) + summaries = [aggregate(values) for values in rows] + if any(summary[name]["count"] == 0 for summary in summaries for name in FOUR_METRICS): + raise RuntimeError("stratified probe has an empty metric denominator") + if len(summaries) >= 2 and any( + summaries[0][name]["count"] != summary[name]["count"] + for summary in summaries[1:] for name in FOUR_METRICS + ): + raise RuntimeError("paired checkpoints have different metric denominators") + if args.hybrid_parent_root: + paired_group_deltas(rows[0], rows[2], "physical_recording_id") + print(json.dumps({ + "source": args.source, "mode": args.mode, + "panel_sha256": expected, "selection": "recording_round_robin_center", + "selected_indices": indices, "recording_groups": groups, + "results": [ + {**identity, "four_metrics": {name: summary[name] for name in FOUR_METRICS}} + for identity, summary in zip(identities, summaries) + ], + "compare_minus_reference": { + name: summaries[1][name]["mean"] - summaries[0][name]["mean"] + for name in FOUR_METRICS + } if len(summaries) >= 2 else None, + "hybrid_minus_reference": { + name: summaries[2][name]["mean"] - summaries[0][name]["mean"] + for name in FOUR_METRICS + } if args.hybrid_parent_root else None, + "hybrid_minus_compare": { + name: summaries[2][name]["mean"] - summaries[1][name]["mean"] + for name in FOUR_METRICS + } if args.hybrid_parent_root else None, + "paired_groups": { + "headset": paired_group_deltas(rows[0], rows[1], "headset_id"), + "recording": paired_group_deltas(rows[0], rows[1], "physical_recording_id"), + } if args.paired_groups else None, + }, separators=(",", ":"))) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/export_adapter_manifests.py b/home/wuyifan/a7_rotation_fix_20260930_code/export_adapter_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..7120aeaf9b953c4f5a4a3ad64ee3c5deaaa3d5d9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/export_adapter_manifests.py @@ -0,0 +1,94 @@ +"""Translate frozen filtered tiles to the three existing native source adapters.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sqlite3 + + +def adapter_row(window: dict, tile_id: str, start: int, frames: list[int], time: int) -> dict: + dataset = window["dataset"] + source = window["source"] + selected = frames if time == 8 else [frames[0]] + shared = { + "filtered_tile_id": tile_id, + "filtered_window_id": window["id"], + "filtered_gt_path": window["filtered_gt_path"], + "filtered_start_offset": start, + "expected_frame_ids": selected, + } + if dataset == "ARCTIC": + offset = int(source["offset"]) + subject = window["recording_id"].split("/")[0] + return { + **shared, "dataset_id": "ARCTIC", "protocol": "P2", + "split_role": "arctic_p2_train", "subject_id": subject, + "physical_recording_id": window["recording_id"], + "group_key": f"ARCTIC/{subject}/{window['recording_id']}", + "camera_id": "ego_view_0_rectified", + "frame_ids_1based": selected, + "array_indices_0based": [frame - offset for frame in selected], + "image_paths": [source["rgb_template"].format(frame=frame) for frame in selected], + "mano_path": source["mano_path"], "camera_path": source["camera_path"], + "depth_input_available": False, "official_test_used": False, + } + if dataset == "H2O": + return {**shared, "take": window["recording_id"], "frame_ids": selected} + if dataset == "HOT3D": + path = Path(window["recording_id"]) + return { + **shared, "dataset": "HOT3D", "have_hand_object_pose_gt": True, + "recording_id": window["recording_id"], "participant_id": path.name.split("_")[0], + "stream_id": window["stream_id"], "headset": source["device"], + "timestamps_ns": window["_timestamps_ns"][start:start + len(selected)], + } + raise ValueError(f"foreign source {dataset}") + + +def export(index: Path, output: Path, time: int) -> dict[str, int]: + if time not in (1, 8): + raise ValueError("only T=1 and T=8 are registered") + output.mkdir(parents=True, exist_ok=False) + counts = {name: 0 for name in ("ARCTIC", "H2O", "HOT3D")} + files = {name: (output / f"{name.lower()}_t{time}.jsonl").open("w") for name in counts} + last_window = None + window = None + try: + with sqlite3.connect(index) as connection: + cursor = connection.execute( + "SELECT t.tile_id,t.window_id,t.source,t.start_offset,t.frame_ids_json," + "w.manifest_json FROM tiles t JOIN windows w ON t.window_id=w.window_id " + "ORDER BY t.source,t.window_id,t.start_offset" + ) + for tile_id, window_id, source_name, start, frames_json, manifest_json in cursor: + if window_id != last_window: + window = json.loads(manifest_json) + if source_name == "HOT3D": + timeline = json.loads(Path(window["source"]["timestamps_path"]).read_text()) + window["_timestamps_ns"] = timeline[str(window["stream_id"])][ + int(window["start"]):int(window["end"]) + ] + last_window = window_id + assert window is not None + row = adapter_row(window, tile_id, start, json.loads(frames_json), time) + files[source_name].write(json.dumps(row, separators=(",", ":")) + "\n") + counts[source_name] += 1 + finally: + for handle in files.values(): + handle.close() + return counts + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--index", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--time", type=int, choices=(1, 8), required=True) + args = parser.parse_args() + print(json.dumps(export(args.index, args.output, args.time), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/filtered_dataset.py b/home/wuyifan/a7_rotation_fix_20260930_code/filtered_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..ab36aee3e3c74559a40f03ce185464476858cd67 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/filtered_dataset.py @@ -0,0 +1,138 @@ +"""Use native source decoders while enforcing the frozen filtered-GT allowlist.""" + +from __future__ import annotations + +from functools import lru_cache +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS, corrupt_metric_depth +from foundation_hand.data.h2o_dataset import H2OCam4Dataset +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + +from coverage_sampler import _seed + + +@lru_cache(maxsize=256) +def filtered_valid(gt_path: str) -> tuple[np.ndarray, np.ndarray]: + with np.load(gt_path, allow_pickle=False) as payload: + return payload["frame_ids"].copy(), payload["valid"].astype(bool).copy() + + +MASKS = ( + "joint_element_valid", "joint_annotation_valid", "mano_annotation_valid", + "joint2d_valid", "joint3d_valid", "joint3d_root_relative_valid", + "translation_valid", "mano_pose_valid", "shape_valid", "vertices_valid", + "reprojection_valid", +) + + +def intersect_filtered_valid(sample: dict[str, Any], row: dict[str, Any]) -> None: + frame_ids, valid = filtered_valid(str(row["filtered_gt_path"])) + start = int(row["filtered_start_offset"]) + time = len(row["expected_frame_ids"]) + expected = np.asarray(row["expected_frame_ids"], dtype=np.int64) + if not np.array_equal(frame_ids[start:start + time], expected): + raise ValueError(f"filtered/native frame disagreement: {row['filtered_tile_id']}") + if sample["dataset_id"] == "HOT3D": + if not torch.equal(sample["timestamp_ns"], torch.as_tensor(row["timestamps_ns"])): + raise ValueError("HOT3D image and GT timeline disagree") + elif not torch.equal(sample["frame_id"], torch.from_numpy(expected)): + raise ValueError("image and filtered GT frame IDs disagree") + hand = torch.from_numpy(valid[start:start + time]).bool() + if hand.shape != (time, 2): + raise ValueError("filtered hand validity has wrong shape") + for key in MASKS: + if key not in sample: + continue + mask = sample[key] + if mask.shape[:2] != (time, 2) or mask.dtype != torch.bool: + raise ValueError(f"invalid native loss mask {key}: {mask.shape}") + expanded = hand + while expanded.ndim < mask.ndim: + expanded = expanded.unsqueeze(-1) + sample[key] = mask & expanded + + +class FilteredClipDataset(Dataset[dict[str, Any]]): + def __init__( + self, source: str, manifest: str | Path, time: int, target_hw: tuple[int, int], + mano_root: str | Path, hot3d_toolkit: str | Path, + photometric_augmentation: dict | None = None, + ) -> None: + self.source = source + self.rows = [json.loads(line) for line in Path(manifest).open() if line.strip()] + self.by_tile = {str(row["filtered_tile_id"]): index for index, row in enumerate(self.rows)} + if len(self.by_tile) != len(self.rows): + raise ValueError("duplicate filtered tile ID") + if source == "ARCTIC": + self.native = ARCTICClipDataset( + manifest, mano_root, target_hw, photometric_augmentation, 20260925, + hand_valid_policy="visible_mesh", + ) + elif source == "H2O": + self.native = H2OCam4Dataset( + "/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, target_hw, + clip_lengths=(time,), strides=(1,), window_step=time, + allow_partial=False, photometric_augmentation=photometric_augmentation, + augmentation_seed=20260925, + ) + elif source == "HOT3D": + self.native = HOT3DClipDataset( + "/SSD3/jiasen/foundation_hand/HOT3D/dataset", manifest, + hot3d_toolkit, mano_root, target_hw, K_input_dropout=0.0, + ) + else: + raise ValueError(f"foreign source {source}") + if len(self.native) != len(self.rows): + raise ValueError("native adapter clip count differs from filtered index") + + def __len__(self) -> int: + return len(self.rows) + + def __getitem__(self, spec: dict[str, Any]) -> dict[str, Any]: + if spec["source"] != self.source: + raise ValueError("sample source differs from native adapter") + index = self.by_tile[str(spec["tile_id"])] + row = self.rows[index] + sample = self.native[(index, int(spec["epoch"]))] + intersect_filtered_valid(sample, row) + frame = sample["frame_valid"].bool() + mode = str(spec["mode"]) + if mode not in ("rgb", "rgb_k", "rgb_depth_k"): + raise ValueError(f"foreign input mode {mode}") + if mode == "rgb_depth_k" and self.source != "H2O": + raise ValueError("only H2O supplies real metric depth") + sample["K_input_available"] = frame & (mode != "rgb") + sample["depth_input_available"] = frame & (mode == "rgb_depth_k") + sample["K_available"] = sample["K_input_available"].clone() + sample["depth_available"] = sample["depth_input_available"].clone() + condition_code = 2 if mode == "rgb_depth_k" else 1 if self.source == "H2O" else 0 + if self.source == "H2O" and mode == "rgb_depth_k": + import random + position = int(spec["position"]) + rng = random.Random(_seed(20260925, "depth", position)) + if rng.random() < .30: + corruption = DEPTH_CORRUPTIONS[rng.randrange(len(DEPTH_CORRUPTIONS))] + depth, pixel_valid = corrupt_metric_depth( + sample["depth_m"].numpy(), sample["depth_pixel_valid"].numpy(), + corruption, seed=_seed(20260925, "corruption", position), + ) + sample["depth_m"] = torch.from_numpy(depth) + sample["depth_pixel_valid"] = torch.from_numpy(pixel_valid) + condition_code = 3 + DEPTH_CORRUPTIONS.index(corruption) + sample["depth_input_condition_code"] = torch.full( + frame.shape, condition_code, dtype=torch.long, + ) + sample["sampling_source_id"] = self.source + sample["filtered_tile_id"] = row["filtered_tile_id"] + sample["input_mode"] = mode + sample["source_ordinal"] = torch.full(frame.shape, int(spec["source_ordinal"]), dtype=torch.long) + sample["coverage_epoch"] = torch.full(frame.shape, int(spec["epoch"]), dtype=torch.long) + return sample diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/freeze_eval_panels.py b/home/wuyifan/a7_rotation_fix_20260930_code/freeze_eval_panels.py new file mode 100644 index 0000000000000000000000000000000000000000..d84948d25345cda0de302ae204eaacf2a742d860 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/freeze_eval_panels.py @@ -0,0 +1,139 @@ +"""Freeze recording-disjoint development and confirmation GT panels.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path + +import numpy as np + +from audit_headset_sync import MAX_DELTA_NS, deltas, trajectory +from preflight_index import digest, tile_starts, EXPECTED_MANIFEST_SHA256 + + +SOURCES = { + "ARCTIC": Path("/SSD3/jiasen/foundation_hand/phase7_artifacts/manifests/arctic_p2_v2/arctic_p2_val_t8.jsonl"), + "H2O": Path("/SSD3/jiasen/foundation_hand/H2O/extracted/label_split/pose_val.txt"), + "HOT3D": Path("/SSD3/jiasen/foundation_hand/phase7_artifacts/manifests/hot3d_gt_v1_retry2/hot3d_heldout_t8.jsonl"), +} + + +def h2o_rows(path: Path) -> list[dict]: + by_take: dict[str, set[int]] = defaultdict(set) + for line in path.open(): + item = Path(line.strip()) + if not line.strip(): + continue + take = str(item.parents[1]) + if not take.endswith("cam4"): + raise ValueError(f"foreign H2O validation view {take}") + by_take[take].add(int(item.stem)) + rows = [] + for take, values in by_take.items(): + ids = sorted(values) + start = 0 + for position in range(1, len(ids) + 1): + if position < len(ids) and ids[position] == ids[position - 1] + 1: + continue + run = ids[start:position] + if len(run) >= 8: + for offset in tile_starts(len(run)): + rows.append({"take": take, "frame_ids": run[offset:offset + 8]}) + start = position + return rows + + +def load_jsonl(path: Path) -> list[dict]: + return [json.loads(line) for line in path.open() if line.strip()] + + +def recording(source: str, row: dict) -> str: + return row["take"] if source == "H2O" else row[ + "physical_recording_id" if source == "ARCTIC" else "recording_id" + ] + + +def clip_time(source: str, row: dict) -> int: + key = "frame_ids" if source == "H2O" else "frame_ids_1based" if source == "ARCTIC" else "timestamps_ns" + return int(row[key][0]) + + +def hot3d_headset_valid(row: dict) -> bool: + path = Path("/SSD3/jiasen/foundation_hand/HOT3D/dataset") / row["recording_id"] + stamps = np.asarray(row["timestamps_ns"], dtype=np.int64) + return bool(np.all(deltas(stamps, trajectory(str(path))) <= MAX_DELTA_NS)) + + +def freeze(train_manifest: Path, output: Path, per_recording: int = 8) -> dict: + if digest(train_manifest) != EXPECTED_MANIFEST_SHA256: + raise ValueError("training manifest differs from frozen allowlist") + if output.exists(): + raise FileExistsError(output) + train_recordings: dict[str, set[str]] = defaultdict(set) + for row in load_jsonl(train_manifest): + train_recordings[row["dataset"]].add(row["recording_id"]) + rows = { + "H2O": h2o_rows(SOURCES["H2O"]), + "ARCTIC": load_jsonl(SOURCES["ARCTIC"]), + "HOT3D": load_jsonl(SOURCES["HOT3D"]), + } + hot3d_total = len(rows["HOT3D"]) + rows["HOT3D"] = [row for row in rows["HOT3D"] if hot3d_headset_valid(row)] + plan: dict[str, dict] = {} + selected: dict[tuple[str, str], list[dict]] = {} + for source, values in rows.items(): + groups: dict[str, list[dict]] = defaultdict(list) + for row in values: + groups[recording(source, row)].append(row) + if train_recordings[source] & set(groups): + raise ValueError(f"{source} validation overlaps filtered train recordings") + ranked = sorted(groups, key=lambda name: hashlib.sha256( + f"clean-gt-eval-20260925|{source}|{name}".encode(), + ).digest()) + if len(ranked) < 2: + raise ValueError(f"{source} lacks disjoint validation recordings") + boundary = len(ranked) // 2 + plan[source] = {"train_recordings": len(train_recordings[source]), + "validation_recordings": len(ranked), "train_overlap": 0, + "source_sha256": digest(SOURCES[source])} + if source == "HOT3D": + plan[source]["candidate_clips"] = hot3d_total + plan[source]["clips_rejected_headset_sync"] = hot3d_total - len(values) + plan[source]["headset_sync_threshold_ms"] = MAX_DELTA_NS / 1e6 + for role, names in (("development", ranked[:boundary]), ("confirmation", ranked[boundary:])): + chosen = [] + for name in names: + candidates = sorted(groups[name], key=lambda row: clip_time(source, row)) + indices = np.linspace(0, len(candidates) - 1, + min(per_recording, len(candidates)), dtype=int) + chosen.extend(candidates[int(index)] for index in indices) + selected[source, role] = chosen + plan[source][role] = {"recordings": len(names), "clips": len(chosen), + "recording_ids": names} + output.mkdir(parents=True) + for (source, role), values in selected.items(): + path = output / f"{source.lower()}_{role}_t8.jsonl" + with path.open("w") as stream: + for row in values: + stream.write(json.dumps(row, separators=(",", ":")) + "\n") + plan[source][role]["manifest_sha256"] = digest(path) + report = {"status": "frozen", "train_manifest_sha256": EXPECTED_MANIFEST_SHA256, + "rule": "recording-disjoint, 8 spread T8 clips per recording; confirmation unopened for selection", + "sources": plan} + (output / "panels.json").write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--train-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(freeze(args.train_manifest, args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/preflight_index.py b/home/wuyifan/a7_rotation_fix_20260930_code/preflight_index.py new file mode 100644 index 0000000000000000000000000000000000000000..f5153a5cd84d39d0fd4e5779d33ab123eb1f11de --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/preflight_index.py @@ -0,0 +1,195 @@ +"""Audit the filtered GT allowlist and build a complete, immutable T=8 index. + +The index contains references only. It never copies or decodes source images. +""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +import os +from pathlib import Path +import sqlite3 + +import numpy as np + + +EXPECTED_MANIFEST_SHA256 = "b4b0ac4bc4a771c9bc7626a9eec7f5f541ef96908a9a64d219192efd7b8f7f89" +EXPECTED_WINDOWS = {"ARCTIC": 2939, "H2O": 928, "HOT3D": 18962} +EXPECTED_TILES = {"ARCTIC": 22750, "H2O": 6406, "HOT3D": 143930} + + +def digest(path: Path) -> str: + value = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(4 * 1024 * 1024), b""): + value.update(block) + return value.hexdigest() + + +def tile_starts(length: int, tile_size: int = 8) -> list[int]: + if length < tile_size: + raise ValueError(f"window has only {length} frames") + starts = list(range(0, length - tile_size + 1, tile_size)) + if starts[-1] + tile_size < length: + starts.append(length - tile_size) + covered = set().union(*(range(start, start + tile_size) for start in starts)) + if covered != set(range(length)): + raise AssertionError(f"tile coverage incomplete for length={length}") + return starts + + +def source_frame_paths(row: dict, frame_ids: np.ndarray) -> list[Path]: + source = row["source"] + if row["dataset"] == "HOT3D": + return [Path(source["root"]), Path(source["timestamps_path"])] + template = str(source["rgb_template"]) + paths = [Path(template.format(frame=int(frame_id))) for frame_id in frame_ids] + if row["dataset"] == "H2O": + root = Path(source["root"]) + paths += [root / "depth" / f"{int(frame_id):06d}.png" for frame_id in frame_ids] + paths += [root / "hand_pose" / f"{int(frame_id):06d}.txt" for frame_id in frame_ids] + paths += [root / "hand_pose_mano" / f"{int(frame_id):06d}.txt" for frame_id in frame_ids] + paths.append(root / "cam_intrinsics.txt") + elif row["dataset"] == "ARCTIC": + paths += [Path(source["mano_path"]), Path(source["camera_path"])] + return paths + + +def audit_window(row: dict, check_paths: bool) -> tuple[np.ndarray, np.ndarray, list[int]]: + if row.get("retained") is not True or row.get("filter_reason") != "retained": + raise ValueError("window is not retained") + name = row["dataset"] + if name not in EXPECTED_WINDOWS: + raise ValueError(f"foreign dataset {name}") + gt = Path(row["filtered_gt_path"]) + if not gt.is_file() or digest(gt) != row["gt_sha256"]: + raise ValueError(f"GT missing or hash mismatch: {gt}") + with np.load(gt, allow_pickle=False) as payload: + if "frame_ids" not in payload or "valid" not in payload: + raise ValueError("GT lacks frame_ids or valid") + frame_ids = payload["frame_ids"].astype(np.int64) + valid = payload["valid"].astype(bool) + if valid.shape != (len(frame_ids), 2): + raise ValueError(f"invalid hand mask shape {valid.shape}") + if name == "H2O" and "joints_native_m" not in payload: + raise ValueError("H2O lacks native joints") + length = int(row["frame_count"]) + if length != len(frame_ids) or length != int(row["end"]) - int(row["start"]): + raise ValueError("manifest/GT length disagreement") + if np.any(np.diff(frame_ids) <= 0): + raise ValueError("native frame IDs are not strictly increasing") + if name == "ARCTIC": + offset = int(row["source"]["offset"]) + if offset < 1 or not np.array_equal( + frame_ids, np.arange(int(row["start"]) + offset, int(row["end"]) + offset) + ): + raise ValueError("ARCTIC frame IDs disagree with registered sequence offset") + if name == "HOT3D": + timeline_path = Path(row["source"]["timestamps_path"]) + if not timeline_path.is_file(): + raise ValueError("HOT3D timeline is missing") + timeline = json.loads(timeline_path.read_text(encoding="utf-8")) + timestamps = timeline[str(row["stream_id"])][int(row["start"]):int(row["end"])] + if len(timestamps) != length: + raise ValueError("HOT3D timeline slice length mismatch") + if check_paths: + missing = next((str(path) for path in source_frame_paths(row, frame_ids) if not path.is_file() and not path.is_dir()), None) + if missing: + raise FileNotFoundError(missing) + return frame_ids, valid, tile_starts(length) + + +def build(manifest: Path, output: Path, check_paths: bool = True) -> dict: + if digest(manifest) != EXPECTED_MANIFEST_SHA256: + raise ValueError("filtered manifest SHA256 differs from frozen recipe") + if output.exists(): + raise FileExistsError(f"refusing to overwrite index: {output}") + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_suffix(output.suffix + ".tmp") + if temporary.exists(): + raise FileExistsError(f"unfinished index already exists: {temporary}") + connection = sqlite3.connect(temporary) + try: + connection.executescript(""" + CREATE TABLE windows ( + window_id TEXT PRIMARY KEY, source TEXT NOT NULL, + recording_id TEXT NOT NULL, stream_id TEXT, + manifest_json TEXT NOT NULL, frame_ids_json TEXT NOT NULL, + valid_left INTEGER NOT NULL, valid_right INTEGER NOT NULL + ); + CREATE TABLE tiles ( + tile_id TEXT PRIMARY KEY, window_id TEXT NOT NULL, + source TEXT NOT NULL, recording_id TEXT NOT NULL, + start_offset INTEGER NOT NULL, frame_ids_json TEXT NOT NULL, + FOREIGN KEY(window_id) REFERENCES windows(window_id) + ); + CREATE INDEX tiles_source_recording ON tiles(source, recording_id); + """) + windows: Counter[str] = Counter() + tiles: Counter[str] = Counter() + frame_entries: Counter[str] = Counter() + valid_hands: Counter[str] = Counter() + recordings: dict[str, set[str]] = {name: set() for name in EXPECTED_WINDOWS} + for line_number, line in enumerate(manifest.open(encoding="utf-8"), 1): + if not line.strip(): + continue + row = json.loads(line) + try: + frame_ids, valid, starts = audit_window(row, check_paths) + name = row["dataset"] + window_id = str(row["id"]) + recording_id = str(row["recording_id"]) + connection.execute( + "INSERT INTO windows VALUES (?,?,?,?,?,?,?,?)", + (window_id, name, recording_id, row.get("stream_id"), + json.dumps(row, separators=(",", ":")), + json.dumps(frame_ids.tolist()), int(valid[:, 0].sum()), int(valid[:, 1].sum())), + ) + for start in starts: + selected = frame_ids[start:start + 8].tolist() + connection.execute( + "INSERT INTO tiles VALUES (?,?,?,?,?,?)", + (f"{window_id}:{start}", window_id, name, recording_id, + start, json.dumps(selected)), + ) + windows[name] += 1 + tiles[name] += len(starts) + frame_entries[name] += len(frame_ids) + valid_hands[f"{name}:left"] += int(valid[:, 0].sum()) + valid_hands[f"{name}:right"] += int(valid[:, 1].sum()) + recordings[name].add(recording_id) + except Exception as error: + raise ValueError(f"manifest line {line_number}, id={row.get('id')}: {error}") from error + if dict(windows) != EXPECTED_WINDOWS or dict(tiles) != EXPECTED_TILES: + raise ValueError(f"coverage counts differ: windows={windows}, tiles={tiles}") + connection.commit() + except BaseException: + connection.close() + temporary.unlink(missing_ok=True) + raise + connection.close() + os.replace(temporary, output) + return { + "status": "pass", "manifest_sha256": EXPECTED_MANIFEST_SHA256, + "index_sha256": digest(output), "windows": dict(windows), + "tiles": dict(tiles), "frame_entries": dict(frame_entries), + "valid_hands": dict(valid_hands), + "recordings": {name: len(values) for name, values in recordings.items()}, + "source_paths_checked": check_paths, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--skip-source-paths", action="store_true") + args = parser.parse_args() + print(json.dumps(build(args.manifest, args.output, not args.skip_source_paths), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/probe_cold_start.py b/home/wuyifan/a7_rotation_fix_20260930_code/probe_cold_start.py new file mode 100644 index 0000000000000000000000000000000000000000..6344fe0a91a9615173f3021e4df3437da404629e --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/probe_cold_start.py @@ -0,0 +1,95 @@ +"""Compare cold-start gradient flow without changing data, loss, or LR.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch +from torch import nn + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for +from coverage_sampler import CoverageSampler, SOURCES +from diagnose_initial_gradients import grad_norms +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +VARIANTS = ( + ("zero_heads_zero_depth", 0.0, 0.0), + ("head_1e-2_zero_depth", 1e-2, 0.0), + ("head_1e-2_depth_1e-4", 1e-2, 1e-4), + ("head_5e-3_depth_1e-3", 5e-3, 1e-3), + ("head_1e-3_depth_1e-3", 1e-3, 1e-3), +) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + coverage = CoverageSampler(INDEX, "S1_S3") + specs = {} + for position in range(200): + spec = coverage.sample(position) + specs.setdefault(spec["source"], spec) + if len(specs) == len(SOURCES): + break + device = torch.device("cuda", 0) + batches = { + source: move_to_device(collate_h2o_clips([dataset[spec]]), device) + for source, spec in specs.items() + } + criterion = BimanualLoss(LOSS) + results = [] + for name, head_std, depth_std in VARIANTS: + torch.manual_seed(20260925) + model = model_for("S1") + with torch.no_grad(): + for head in ( + model.joint2d_head, model.rotation_head, + model.translation_head, model.shape_head, + ): + if head_std: + nn.init.normal_(head.weight, std=head_std) + else: + nn.init.zeros_(head.weight) + final_depth = model.depth_encoder.encoder[-1] + if depth_std: + nn.init.normal_(final_depth.weight, std=depth_std) + else: + nn.init.zeros_(final_depth.weight) + model.to(device).train() + item = {"variant": name, "head_std": head_std, "depth_std": depth_std, + "samples": {}} + for source, batch in batches.items(): + model.zero_grad(set_to_none=True) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + losses = criterion(model(batch), batch) + losses["total"].backward() + groups = grad_norms(model) + item["samples"][source] = { + "mode": specs[source]["mode"], + "loss": float(losses["total"].detach()), + "grad_norm": sum(x * x for x in groups.values()) ** .5, + "decoder_grad": groups.get("decoder.spatial", 0.0), + "projection_grad": groups.get("rgb_encoder.projection", 0.0), + "depth_grad": groups.get("depth_encoder", 0.0), + "translation_head_grad": groups.get("translation_head", 0.0), + } + results.append(item) + del model + torch.cuda.empty_cache() + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(results, indent=2) + "\n") + print(json.dumps(results, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/run_formal_stages.py b/home/wuyifan/a7_rotation_fix_20260930_code/run_formal_stages.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd55afacfa5d7d36a86318e62b0f4edd6bf4a47 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/run_formal_stages.py @@ -0,0 +1,186 @@ +"""Continue the registered six-GPU clean-GT stages after the S1 health gate.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import subprocess +import time + + +ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925") +CODE = ROOT / "code" +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +CHECKPOINTS = ROOT / "checkpoints" +LOGS = ROOT / "logs" +EVAL = ROOT / "eval" +RUN_TAG = "formal_v3" +S1_HEALTH_PIDFILE = LOGS / f"{RUN_TAG}_s1_health2k.pid" +S1_PIDFILE = LOGS / f"{RUN_TAG}_s1_full.pid" +ENDPOINTS = {"S1": 16667, "S2": 50000, "S3": 83334, "S4": 66667} +MODES = { + "H2O": ("rgb", "rgb_k", "rgb_depth_k"), + "ARCTIC": ("rgb", "rgb_k"), + "HOT3D": ("rgb", "rgb_k"), +} + + +def checksum(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def state(event: str, **details: object) -> None: + payload = {"event": event, "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S%z"), **details} + path = LOGS / f"{RUN_TAG}_controller_state.json" + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n") + temporary.replace(path) + print(json.dumps(payload), flush=True) + + +def endpoint(stage: str, update: int) -> Path: + return CHECKPOINTS / f"{RUN_TAG}_{stage.lower()}" / f"{stage.lower()}_update_{update:07d}.pt" + + +def process_running(pidfile: Path) -> bool: + if not pidfile.exists(): + return False + return subprocess.run( + ["start-stop-daemon", "--status", "--pidfile", str(pidfile)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, + ).returncode == 0 + + +def wait_for_s1_health() -> None: + target = endpoint("S1", 2000) + deadline = time.monotonic() + 3 * 3600 + if not process_running(S1_HEALTH_PIDFILE) and not target.is_file(): + raise RuntimeError("S1 health process is absent without a complete endpoint") + while process_running(S1_HEALTH_PIDFILE): + if time.monotonic() > deadline: + raise TimeoutError("S1 health exceeded its three-hour watchdog") + time.sleep(30) + if not target.is_file(): + raise RuntimeError("S1 health stopped without its complete formal endpoint") + + +def run_logged(command: list[str], log: Path) -> None: + if log.exists(): + raise FileExistsError(f"refusing to overwrite an existing run log: {log}") + print(json.dumps({"run": command, "log": str(log)}), flush=True) + with log.open("xb") as stream: + result = subprocess.run(command, cwd=CODE, stdout=stream, stderr=subprocess.STDOUT, + check=False) + if result.returncode != 0: + raise RuntimeError(f"command exited {result.returncode}; inspect {log}") + + +def audit(stage: str, update: int) -> dict: + target = endpoint(stage, update) + report_path = LOGS / f"{RUN_TAG}_{stage.lower()}_{update:07d}_audit.json" + if report_path.exists(): + report = json.loads(report_path.read_text()) + if report["status"] != "pass" or report["checkpoint_sha256"] != checksum(target): + raise RuntimeError(f"stale or failed endpoint audit: {report_path}") + else: + run_logged([ + PYTHON, str(CODE / "audit_formal_stage.py"), + "--checkpoint", str(target), + "--metrics", str(target.parent / "metrics.jsonl"), + "--stage", stage, "--update", str(update), + "--output", str(report_path), + ], LOGS / f"{RUN_TAG}_{stage.lower()}_{update:07d}_audit.console.log") + report = json.loads(report_path.read_text()) + if report["status"] != "pass": + raise RuntimeError(f"endpoint audit failed: {report_path}") + if update == 2000 and report["last_window_loss_mean"] > 2 * report["first_window_loss_mean"]: + raise RuntimeError(f"early-stage loss grew more than twofold: {report_path}") + state("audited", stage=stage, update=update, checkpoint_sha256=report["checkpoint_sha256"]) + return report + + +def train(stage: str, update: int, previous: Path) -> Path: + target = endpoint(stage, update) + if target.is_file(): + audit(stage, update) + return target + output = target.parent + command = [ + PYTHON, "-m", "torch.distributed.run", "--standalone", "--nproc_per_node=6", + "clean_train.py", "--stage", stage, "--output", str(output), + "--updates", str(update), "--workers", "2", "--save", + ] + if update == 2000: + if output.exists(): + raise FileExistsError(f"uncompleted formal stage requires diagnosis: {output}") + command += ["--parent", str(previous)] + else: + command += ["--resume", str(previous)] + label = "health2k" if update == 2000 else "full" + state("training", stage=stage, update=update, parent=str(previous)) + run_logged(command, LOGS / f"{RUN_TAG}_{stage.lower()}_{label}.console.log") + if not target.is_file(): + raise RuntimeError(f"training returned without endpoint: {target}") + audit(stage, update) + return target + + +def evaluate(stage: str, update: int, *, full: bool, confirmation: bool = False) -> None: + target = endpoint(stage, update) + role = "confirmation" if confirmation else "development" + conditions = [(source, mode) for source, modes in MODES.items() for mode in modes] + if not full: + conditions = [("H2O", "rgb_depth_k"), ("ARCTIC", "rgb_k"), ("HOT3D", "rgb_k")] + for source, mode in conditions: + tag = f"{RUN_TAG}_{stage.lower()}_{update:07d}_{role}_{source.lower()}_{mode}" + report_path = EVAL / "formal_stages" / f"{tag}.json" + if report_path.exists(): + report = json.loads(report_path.read_text()) + if (report["checkpoint_sha256"] != checksum(target) or report["source"] != source + or report["input_mode"] != mode or report["role"] != role): + raise RuntimeError(f"stale evaluation report: {report_path}") + continue + command = [ + PYTHON, str(CODE / "clean_eval.py"), "--checkpoint", str(target), + "--source", source, "--role", role, "--mode", mode, + "--output", str(report_path), + ] + if confirmation: + command.append("--final-checkpoint") + elif not full: + command += ["--allow-smoke", "--limit", "32"] + run_logged(command, LOGS / f"{tag}.console.log") + report = json.loads(report_path.read_text()) + if any(value["count"] == 0 for value in report["four_metrics"].values()): + raise RuntimeError(f"evaluation has an empty metric denominator: {report_path}") + state("evaluated", stage=stage, update=update, source=source, mode=mode, + role=role, report=str(report_path)) + + +def main() -> None: + try: + state("waiting_for_s1_health") + wait_for_s1_health() + audit("S1", 2000) + evaluate("S1", 2000, full=False) + parent = train("S1", ENDPOINTS["S1"], endpoint("S1", 2000)) + evaluate("S1", ENDPOINTS["S1"], full=False) + for stage in ("S2", "S3", "S4"): + short = train(stage, 2000, parent) + evaluate(stage, 2000, full=False) + parent = train(stage, ENDPOINTS[stage], short) + evaluate(stage, ENDPOINTS[stage], full=stage in ("S3", "S4")) + evaluate("S4", ENDPOINTS["S4"], full=True, confirmation=True) + state("complete", checkpoint=str(parent), checkpoint_sha256=checksum(parent)) + except Exception as error: + state("failed", error=f"{type(error).__name__}: {error}") + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/adapt_phase3_validation_subset.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/adapt_phase3_validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..3597f9540602b5d9249706b44f33431b996d1b6b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/adapt_phase3_validation_subset.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Clone a fixed validation selection under a new preprocessing contract.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--resolution-hw", type=int, nargs=2, required=True) + args = parser.parse_args() + + source = json.loads(args.source.read_text(encoding="utf-8")) + record = dict(source) + record["version"] = f"{source['version']}_resolution_contract_v1" + record["parent_selection_manifest"] = str(args.source.resolve()) + record["parent_selection_manifest_sha256"] = sha256(args.source) + record["dataset_contract"] = dict(source["dataset_contract"]) + record["dataset_contract"]["resolution_hw"] = list(args.resolution_hw) + record["adaptation"] = ( + "Clip indices and all selection metadata are copied exactly; only the " + "resize/padding resolution contract changes." + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "created", + "output": str(args.output), + "count": len(record["clip_indices"]), + "resolution_hw": record["dataset_contract"]["resolution_hw"], + "sha256": sha256(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/analyze_phase8_checkpoint_drift.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/analyze_phase8_checkpoint_drift.py new file mode 100644 index 0000000000000000000000000000000000000000..75eb62e3785a60f5e05394066d2518db310df246 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/analyze_phase8_checkpoint_drift.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Measure layerwise model-parameter drift between two hash-bound checkpoints.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import torch + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _model_state(path: Path, expected_sha256: str) -> tuple[dict[str, torch.Tensor], dict[str, Any]]: + actual = sha256(path) + if actual != expected_sha256: + raise ValueError(f"checkpoint SHA256 differs: {path}") + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + state = checkpoint.get("model") + if not isinstance(state, dict) or not state: + raise ValueError(f"checkpoint has no model state: {path}") + return state, { + "path": str(path.resolve()), "sha256": actual, + "step": int(checkpoint.get("step", -1)), + "h2o_training_data_used": checkpoint.get("extra", {}).get( + "h2o_training_data_used" + ), + "official_test_used": checkpoint.get("extra", {}).get("official_test_used"), + } + + +def _group(name: str, depth: int) -> str: + components = name.split(".") + return ".".join(components[:depth]) + + +def analyze( + reference_path: Path, + reference_sha256: str, + candidate_path: Path, + candidate_sha256: str, + *, + group_depth: int = 2, +) -> dict[str, Any]: + if group_depth <= 0: + raise ValueError("group_depth must be positive") + reference, reference_meta = _model_state(reference_path, reference_sha256) + candidate, candidate_meta = _model_state(candidate_path, candidate_sha256) + if set(reference) != set(candidate): + missing = sorted(set(reference) - set(candidate)) + extra = sorted(set(candidate) - set(reference)) + raise ValueError(f"model state keys differ; missing={missing[:5]} extra={extra[:5]}") + accumulators: dict[str, dict[str, float]] = {} + for name in sorted(reference): + before = reference[name] + after = candidate[name] + if before.shape != after.shape: + raise ValueError(f"parameter shape differs: {name}") + if not before.is_floating_point(): + continue + before64 = before.detach().to(dtype=torch.float64) + delta = after.detach().to(dtype=torch.float64) - before64 + groups = ("__overall__", _group(name, 1), _group(name, group_depth)) + for group in dict.fromkeys(groups): + values = accumulators.setdefault(group, { + "parameter_count": 0.0, "reference_sq_sum": 0.0, + "delta_sq_sum": 0.0, "delta_abs_sum": 0.0, + "delta_abs_max": 0.0, "tensor_count": 0.0, + }) + values["parameter_count"] += float(delta.numel()) + values["reference_sq_sum"] += float(before64.square().sum()) + values["delta_sq_sum"] += float(delta.square().sum()) + values["delta_abs_sum"] += float(delta.abs().sum()) + values["delta_abs_max"] = max( + values["delta_abs_max"], float(delta.abs().max()) if delta.numel() else 0.0, + ) + values["tensor_count"] += 1.0 + groups: dict[str, Any] = {} + for group, values in sorted(accumulators.items()): + count = int(values["parameter_count"]) + delta_l2 = math.sqrt(values["delta_sq_sum"]) + reference_l2 = math.sqrt(values["reference_sq_sum"]) + groups[group] = { + "parameter_count": count, + "tensor_count": int(values["tensor_count"]), + "reference_l2": reference_l2, + "delta_l2": delta_l2, + "relative_l2": delta_l2 / max(reference_l2, 1e-12), + "delta_mean_abs": values["delta_abs_sum"] / max(count, 1), + "delta_max_abs": values["delta_abs_max"], + } + return { + "schema_version": "phase8_checkpoint_drift_v1", + "status": "complete", + "reference": reference_meta, + "candidate": candidate_meta, + "group_depth": group_depth, + "groups": groups, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference", type=Path, required=True) + parser.add_argument("--reference-sha256", required=True) + parser.add_argument("--candidate", type=Path, required=True) + parser.add_argument("--candidate-sha256", required=True) + parser.add_argument("--group-depth", type=int, default=2) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = analyze( + args.reference, args.reference_sha256, + args.candidate, args.candidate_sha256, + group_depth=args.group_depth, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/analyze_phase8_paired_input_modes.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/analyze_phase8_paired_input_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..615c329bb99ebb1df93134ba095c09b527aa8fd7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/analyze_phase8_paired_input_modes.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Paired depth-contribution diagnostic for two frozen evaluation bundles.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_summary(values: np.ndarray) -> dict[str, float | int] | None: + values = np.asarray(values, dtype=np.float64) + values = values[np.isfinite(values)] + if not len(values): + return None + return { + "count": int(len(values)), "mean": float(values.mean()), + "median": float(np.median(values)), "p90": float(np.quantile(values, .9)), + "p95": float(np.quantile(values, .95)), "p99": float(np.quantile(values, .99)), + "min": float(values.min()), "max": float(values.max()), + } + + +def correlation(left: np.ndarray, right: np.ndarray) -> float | None: + finite = np.isfinite(left) & np.isfinite(right) + if finite.sum() < 2 or np.std(left[finite]) == 0 or np.std(right[finite]) == 0: + return None + return float(np.corrcoef(left[finite], right[finite])[0, 1]) + + +def optimal_slope(delta: np.ndarray, desired: np.ndarray) -> float | None: + finite = np.isfinite(delta) & np.isfinite(desired) + denominator = float(np.dot(delta[finite], delta[finite])) + if denominator <= 1e-12: + return None + return float(np.dot(delta[finite], desired[finite]) / denominator) + + +def grouped_bootstrap( + groups: np.ndarray, gains: np.ndarray, *, seed: int, resamples: int, +) -> dict[str, float | int]: + unique = np.unique(groups) + by_group = {group: gains[groups == group] for group in unique} + generator = np.random.default_rng(seed) + estimates = np.empty(resamples, dtype=np.float64) + for index in range(resamples): + sampled = generator.choice(unique, size=len(unique), replace=True) + values = np.concatenate([by_group[group] for group in sampled]) + estimates[index] = np.nanmean(values) + return { + "groups": int(len(unique)), "resamples": int(resamples), + "estimate": float(np.nanmean(gains)), + "ci95_low": float(np.quantile(estimates, .025)), + "ci95_high": float(np.quantile(estimates, .975)), + } + + +def load_bundle(directory: Path) -> tuple[dict[str, Any], dict[str, np.ndarray], list[dict[str, str]]]: + report_path = directory / "evaluation.json" + raw_path = directory / "raw_predictions.npz" + rows_path = directory / "per_hand_frame_metrics.csv" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("official_test_used") is not False + or report.get("h2o_official_validation_used_for_external_selection") is True + ): + raise ValueError("paired diagnostic refuses a bundle without official_test_used=false") + with np.load(raw_path) as archive: + raw = {key: archive[key] for key in archive.files} + with rows_path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + return report, raw, rows + + +def observation_manifest(report: dict[str, Any]) -> dict[str, Any]: + for name in ("cache_manifest", "manifest"): + value = report.get(name) + if isinstance(value, dict) and value.get("sha256"): + return value + raise ValueError("evaluation lacks a hash-bound observation manifest") + + +def validate_pair( + base_report: dict[str, Any], depth_report: dict[str, Any], + base: dict[str, np.ndarray], depth: dict[str, np.ndarray], + base_rows: list[dict[str, str]], depth_rows: list[dict[str, str]], +) -> None: + if base_report["checkpoint"]["sha256"] != depth_report["checkpoint"]["sha256"]: + raise ValueError("paired modes must use the same checkpoint") + if observation_manifest(base_report)["sha256"] != observation_manifest(depth_report)["sha256"]: + raise ValueError("paired modes must use the same cache manifest") + if base_report["input_mode"] != "rgb_k" or depth_report["input_mode"] != "rgb_d_k": + raise ValueError("expected base=rgb_k and depth=rgb_d_k") + for key in ( + "target_wrist_root_translation", "target_joints_camera", + "translation_valid", "joint3d_valid", "frame_id", + ): + if key not in base or key not in depth or not np.array_equal(base[key], depth[key], equal_nan=True): + raise ValueError(f"paired raw target alignment differs: {key}") + if len(base_rows) != len(depth_rows): + raise ValueError("paired per-hand row counts differ") + identity = ("dataset", "subject_id", "physical_recording_id", "camera_id", "frame_id", "side") + if any(any(left[key] != right[key] for key in identity) for left, right in zip(base_rows, depth_rows)): + raise ValueError("paired per-hand row identities differ") + + +def analyze( + base_dir: Path, depth_dir: Path, output_dir: Path, *, seed: int, resamples: int, +) -> dict[str, Any]: + base_report, base, base_rows = load_bundle(base_dir) + depth_report, depth, depth_rows = load_bundle(depth_dir) + validate_pair(base_report, depth_report, base, depth, base_rows, depth_rows) + if output_dir.exists() and any(output_dir.iterdir()): + raise ValueError("output directory must be new or empty") + output_dir.mkdir(parents=True, exist_ok=True) + + predicted_base = base["predicted_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + predicted_depth = depth["predicted_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + target = base["target_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + translation_valid = base["translation_valid"].reshape(-1).astype(bool) + delta = (predicted_depth - predicted_base) * 1000.0 + desired = (target - predicted_base) * 1000.0 + base_residual = (predicted_base - target) * 1000.0 + depth_residual = (predicted_depth - target) * 1000.0 + + base_joints = base["predicted_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + depth_joints = depth["predicted_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + target_joints = base["target_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + joint_valid = base["joint3d_valid"].reshape(-1, 21).astype(bool) + base_point_error = np.linalg.norm(base_joints - target_joints, axis=-1) * 1000.0 + depth_point_error = np.linalg.norm(depth_joints - target_joints, axis=-1) * 1000.0 + base_mpjpe = np.full(len(joint_valid), np.nan) + depth_mpjpe = np.full(len(joint_valid), np.nan) + for index, valid in enumerate(joint_valid): + if valid.any(): + base_mpjpe[index] = base_point_error[index, valid].mean() + depth_mpjpe[index] = depth_point_error[index, valid].mean() + + groups = np.asarray([row["physical_recording_id"] for row in base_rows], dtype=object) + if len(groups) != len(predicted_base): + raise ValueError("raw hand axis does not match per-hand metric rows") + valid = translation_valid & np.isfinite(base_residual).all(1) & np.isfinite(depth_residual).all(1) + joint_rows = np.isfinite(base_mpjpe) & np.isfinite(depth_mpjpe) + translation_gain = np.linalg.norm(base_residual, axis=1) - np.linalg.norm(depth_residual, axis=1) + mpjpe_gain = base_mpjpe - depth_mpjpe + + paired_rows: list[dict[str, Any]] = [] + for index, metadata in enumerate(base_rows): + if not (valid[index] or joint_rows[index]): + continue + record: dict[str, Any] = { + key: metadata[key] for key in + ("dataset", "subject_id", "physical_recording_id", "camera_id", "frame_id", "side") + } + for axis_index, axis in enumerate("xyz"): + record[f"depth_contribution_{axis}_mm"] = float(delta[index, axis_index]) + record[f"desired_correction_{axis}_mm"] = float(desired[index, axis_index]) + record[f"base_{axis}_error_mm"] = float(base_residual[index, axis_index]) + record[f"depth_{axis}_error_mm"] = float(depth_residual[index, axis_index]) + record["base_mpjpe_mm"] = float(base_mpjpe[index]) + record["depth_mpjpe_mm"] = float(depth_mpjpe[index]) + record["mpjpe_gain_mm"] = float(mpjpe_gain[index]) + record["translation_norm_gain_mm"] = float(translation_gain[index]) + paired_rows.append(record) + row_path = output_dir / "paired_hand_rows.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(paired_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(paired_rows) + harm_path = output_dir / "largest_harm_cases.csv" + harm_rows = sorted(paired_rows, key=lambda row: row["mpjpe_gain_mm"])[:100] + with harm_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(harm_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(harm_rows) + + axis_diagnostics = {} + for axis_index, axis in enumerate("xyz"): + selected = valid & np.isfinite(delta[:, axis_index]) & np.isfinite(desired[:, axis_index]) + axis_diagnostics[axis] = { + "base_signed_error_mm": finite_summary(base_residual[selected, axis_index]), + "depth_signed_error_mm": finite_summary(depth_residual[selected, axis_index]), + "depth_contribution_mm": finite_summary(delta[selected, axis_index]), + "desired_correction_mm": finite_summary(desired[selected, axis_index]), + "contribution_desired_correlation": correlation( + delta[selected, axis_index], desired[selected, axis_index], + ), + "optimal_depth_contribution_scale": optimal_slope( + delta[selected, axis_index], desired[selected, axis_index], + ), + "direction_agreement_fraction": float(np.mean( + np.sign(delta[selected, axis_index]) == np.sign(desired[selected, axis_index]) + )), + "absolute_error_gain_mm": finite_summary( + np.abs(base_residual[selected, axis_index]) - np.abs(depth_residual[selected, axis_index]) + ), + } + report = { + "status": "complete", + "class": "paired_input_oracle_diagnostic_only", + "deployable_claim": False, + "checkpoint": base_report["checkpoint"], + "observation_manifest": observation_manifest(base_report), + "base_input_mode": "rgb_k", "depth_input_mode": "rgb_d_k", + "hands_with_translation": int(valid.sum()), + "hands_with_joint3d": int(joint_rows.sum()), + "base_absolute_mpjpe_mm": float(np.nanmean(base_mpjpe[joint_rows])), + "depth_absolute_mpjpe_mm": float(np.nanmean(depth_mpjpe[joint_rows])), + "depth_mpjpe_gain_mm": finite_summary(mpjpe_gain[joint_rows]), + "depth_harm_fraction_mpjpe": float(np.mean(mpjpe_gain[joint_rows] < 0)), + "translation_norm_gain_mm": finite_summary(translation_gain[valid]), + "depth_harm_fraction_translation_norm": float(np.mean(translation_gain[valid] < 0)), + "axis_diagnostics": axis_diagnostics, + "grouped_bootstrap_ci": { + "mpjpe_gain_mm": grouped_bootstrap( + groups[joint_rows], mpjpe_gain[joint_rows], seed=seed, resamples=resamples, + ), + "translation_norm_gain_mm": grouped_bootstrap( + groups[valid], translation_gain[valid], seed=seed, resamples=resamples, + ), + }, + "paired_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "largest_harm_cases": {"path": str(harm_path.resolve()), "sha256": sha256(harm_path)}, + "official_test_used": False, + } + report_path = output_dir / "analysis.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-rgb-k-dir", type=Path, required=True) + parser.add_argument("--depth-rgb-d-k-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + report = analyze( + args.base_rgb_k_dir, args.depth_rgb_d_k_dir, args.output_dir, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/arm_phase9_last2_distributed_completion.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/arm_phase9_last2_distributed_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..d4159e763e607821df8bedef7283073b6dc8064b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/arm_phase9_last2_distributed_completion.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Carry one admitted last-2 candidate through both distributed handoffs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def write_state(path: Path, status: str, candidate: str, **extra: Any) -> None: + atomic_json(path, { + "schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": status, "candidate": candidate, "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "official_test_used": False, **extra, + }) + + +def wait_json(path: Path, predicate: Any, state_path: Path, candidate: str, label: str) -> dict[str, Any]: + while True: + if path.is_file(): + value = read_json(path) + if predicate(value): return value + if str(value.get("status", "")).startswith("failed"): + raise ValueError(f"last-2 dependency failed: {path}") + write_state(state_path, label, candidate, dependency=str(path.resolve())) + time.sleep(30) + + +def remote_conditions(plan: dict[str, Any], registry: dict[str, Any]) -> list[str]: + owners = condition_owners(registry, load_assignment(plan)) + result = [item["condition"] for item in registry["conditions"] + if owners[item["condition"]] == "server_new"] + if len(result) != 3: raise ValueError("last-2 remote condition count differs") + return result + + +def start_process(command: list[str], log: Path) -> int: + log.parent.mkdir(parents=True, exist_ok=True) + handle = log.open("a", encoding="utf-8") + process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=handle, + stderr=subprocess.STDOUT, text=True, start_new_session=True) + handle.close(); return process.pid + + +def start_remote(command: str) -> None: + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: raise RuntimeError("remote last-2 watcher launch failed") + + +def training_completion_plan(plan_path: Path, plan: dict[str, Any], registry_path: Path) -> dict[str, Any]: + registry = read_json(registry_path); conditions = remote_conditions(plan, registry) + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_last2_training_completion.py") + return { + "schema_version": "phase9_last2_training_completion_plan_v1", "status": "frozen", + "candidate": plan["candidate"], "source_owner": "server_new", + "destination_owner": "taku3", "conditions": conditions, "target_step": 405000, + "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/last2_v3/{plan['candidate']}/recovery/training_completion_staging", + "training_state_root": plan["training_state_root"], + "source_controller_state": plan["controller_states"]["server_new"], + "training_completion_state": plan["training_completion_state"], + "release_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_training_completion_release.json", + "receive_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_training_completion_receive.json", + "training_registry": {"path": str(registry_path.resolve()), "sha256": sha256(registry_path)}, + "controller_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "distributed_assignment": plan["distributed_assignment"], + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "results_before_terminal_states": True, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + {"path": str(registry_path.resolve()), "sha256": sha256(registry_path)}, + plan["distributed_assignment"], + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def evaluation_completion_plan(plan_path: Path, plan: dict[str, Any], dynamic: Path) -> dict[str, Any]: + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + return { + "schema_version": "phase9_resolution_evaluation_completion_release_plan_v1", + "status": "frozen", "source_owner": "server_new", "destination_owner": "taku3", + "source_host": "server_new", "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/last2_v3/{plan['candidate']}/recovery/evaluation_completion_staging", + "source_controller_state": plan["controller_states"]["server_new"], + "release_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_evaluation_completion_release.json", + "receive_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_evaluation_completion_receive.json", + "ssh_timeout_seconds": 30, + "evaluation_plan": {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "single_writer_per_output": True, "results_before_terminal_states": True, + "read_only_after_publish": True, + "scientific_contract": { + "amendment_scope": "terminal_evaluation_state_and_result_handoff_only", + "model_changed": False, "data_changed": False, "seed_changed": False, + "metric_changed": False, "selection_gate_changed": False, + }, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + plan["distributed_assignment"], + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def sync_plan_and_bridge(output: Path, value: dict[str, Any], bridge: Path) -> None: + if output.exists() and read_json(output) != value: raise ValueError(f"existing plan differs: {output}") + if not output.exists(): output.parent.mkdir(parents=True, exist_ok=True); atomic_json(output, value) + for path in (bridge, output): + installed = install_file("server_new", path) + if installed["sha256"] != sha256(path): raise ValueError(f"remote sync differs: {path}") + + +def sync_evaluation_admission(plan: dict[str, Any], dynamic: Path) -> None: + payload = read_json(dynamic) + remote_ids = {identifier for worker in payload["workers"] if worker["owner"] == "server_new" + for identifier in worker["evaluation_ids"]} + evaluations = {item["id"]: item for item in payload["evaluations"]} + for identifier in remote_ids: + item = evaluations[identifier] + for path_key, hash_key in (("config", "config_sha256"), + ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256")): + if remote_sha256("server_new", Path(item[path_key])) != item[hash_key]: + raise ValueError(f"remote last-2 evaluation input differs: {identifier}") + for path in (Path(plan["training_completion_state"]), + Path(plan["evaluation_plan_state"]), dynamic): + install_file("server_new", path) + + +def run(plan_path: Path, state_path: Path) -> dict[str, Any]: + plan = read_json(plan_path); candidate = plan["candidate"] + sync_state = Path(f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{candidate}/admission_sync_state.json") + admitted = wait_json(sync_state, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_admission_sync") + if admitted.get("admission") == "rejected": + return {"schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": "complete_formal_rejection", "candidate": candidate, + "completed_utc": utc_now(), "official_test_used": False} + registry_path = Path(plan["training_registry"]) + wait_json(registry_path, lambda value: value.get("status") == "frozen_ready", + state_path, candidate, "waiting_for_training_registry") + training_plan_path = plan_path.parent / f"last2_{candidate}_training_completion_plan_v1.json" + training_value = training_completion_plan(plan_path, plan, registry_path) + training_bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_last2_training_completion.py") + sync_plan_and_bridge(training_plan_path, training_value, training_bridge) + log_root = Path(f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{candidate}/completion_logs") + receive_pid = start_process([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_last2_training_completion", "--plan", str(training_plan_path), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], log_root / "training_receive.log") + start_remote( + "cd /home/jiasen/foundation_hand && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + f"scripts.sync_phase9_last2_training_completion --plan {training_plan_path} --role publish " + f"--wait-timeout-seconds 1209600 >> {log_root / 'training_publish.log'} 2>&1 < /dev/null" + ) + receive_state = Path(training_value["receive_state"]) + wait_json(receive_state, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_training_completion_return") + dynamic = Path(plan["evaluation_plan"]) + wait_json(dynamic, lambda value: value.get("status") == "frozen_ready", + state_path, candidate, "waiting_for_evaluation_plan") + sync_evaluation_admission(plan, dynamic) + evaluation_plan_path = plan_path.parent / f"last2_{candidate}_evaluation_completion_plan_v1.json" + evaluation_value = evaluation_completion_plan(plan_path, plan, dynamic) + evaluation_bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + sync_plan_and_bridge(evaluation_plan_path, evaluation_value, evaluation_bridge) + evaluation_receive_pid = start_process([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_resolution_evaluation_completion", "--plan", str(evaluation_plan_path), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], log_root / "evaluation_receive.log") + start_remote( + "cd /home/jiasen/foundation_hand && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + f"scripts.sync_phase9_resolution_evaluation_completion --plan {evaluation_plan_path} --role publish " + f"--wait-timeout-seconds 1209600 >> {log_root / 'evaluation_publish.log'} 2>&1 < /dev/null" + ) + central = Path(plan["controller_states"]["taku3"]) + final = wait_json(central, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_central_candidate_decision") + return { + "schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": "complete", "candidate": candidate, "completed_utc": utc_now(), + "training_receive_pid": receive_pid, "evaluation_receive_pid": evaluation_receive_pid, + "decision_report": final["decision_report"], "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser(); parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True); args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + result = run(args.plan, args.state); atomic_json(args.state, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/arm_phase9_shared_augmentation_evaluation_completion.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/arm_phase9_shared_augmentation_evaluation_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..2213de6d5ae74ec16fc626ba2609582464fcd890 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/arm_phase9_shared_augmentation_evaluation_completion.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Arm completion-only Stage 8 evaluation return after its plan freezes.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def completion_plan(static_plan_path: Path, static: dict[str, Any]) -> dict[str, Any]: + dynamic = Path(static["evaluation_plan"]) + admission = Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/" + "evaluation_admission_sync_state.json" + ) + if not dynamic.is_file() or not admission.is_file(): + raise RuntimeError("Stage 8 evaluation admission is not complete") + admitted = read_json(admission) + if admitted.get("status") != "complete" or admitted.get("evaluation_plan_sha256") != sha256(dynamic): + raise RuntimeError("Stage 8 evaluation admission is not complete") + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + assignment = Path(static["distributed_assignment"]["path"]) + return { + "schema_version": "phase9_resolution_evaluation_completion_release_plan_v1", + "status": "frozen", "source_owner": "server_new", "destination_owner": "taku3", + "source_host": "server_new", + "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts/shared_augmentation/896x512/recovery/server_evaluation_completion_staging_v1", + "source_controller_state": static["controller_states"]["server_new"], + "release_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/server_evaluation_completion_release_state_v1.json", + "receive_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/server_evaluation_completion_receive_state_v1.json", + "ssh_timeout_seconds": 30, + "evaluation_plan": {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "single_writer_per_output": True, "results_before_terminal_states": True, + "read_only_after_publish": True, + "scientific_contract": { + "amendment_scope": "terminal_evaluation_state_and_result_handoff_only", + "model_changed": False, "data_changed": False, "seed_changed": False, + "metric_changed": False, "selection_gate_changed": False, + }, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(static_plan_path.resolve()), "sha256": sha256(static_plan_path)}, + {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + {"path": str(assignment.resolve()), "sha256": sha256(assignment)}, + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def arm(static_plan_path: Path, output_plan: Path) -> dict[str, Any]: + static = read_json(static_plan_path) + plan = completion_plan(static_plan_path, static) + if output_plan.exists() and read_json(output_plan) != plan: + raise ValueError("existing Stage 8 evaluation completion plan differs") + if not output_plan.exists(): + output_plan.parent.mkdir(parents=True, exist_ok=True); atomic_json(output_plan, plan) + copied = subprocess.run(["rsync", "-a", str(output_plan), f"server_new:{output_plan}.incoming"], check=False) + if copied.returncode: + raise RuntimeError("Stage 8 evaluation completion plan sync failed") + installed = subprocess.run(["ssh", "server_new", "mv", f"{output_plan}.incoming", str(output_plan)], check=False) + if installed.returncode: + raise RuntimeError("Stage 8 evaluation completion plan install failed") + log_root = Path("/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/completion_logs") + log_root.mkdir(parents=True, exist_ok=True) + receive = subprocess.Popen([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_resolution_evaluation_completion", "--plan", str(output_plan), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], stdin=subprocess.DEVNULL, stdout=(log_root / "evaluation_receive.log").open("a"), + stderr=subprocess.STDOUT, text=True, start_new_session=True) + remote = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.sync_phase9_resolution_evaluation_completion --plan " + str(output_plan) + + " --role publish --wait-timeout-seconds 1209600 >> " + + str(log_root / "evaluation_publish.log") + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", remote], check=False) + if result.returncode: + raise RuntimeError("Stage 8 evaluation completion publisher launch failed") + return { + "schema_version": "phase9_shared_augmentation_evaluation_completion_arm_v1", + "status": "complete", "completed_utc": utc_now(), + "completion_plan": str(output_plan.resolve()), + "completion_plan_sha256": sha256(output_plan), "receiver_pid": receive.pid, + "official_test_used": False, "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--static-plan", type=Path, required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = arm(args.static_plan, args.output_plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except RuntimeError as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_evaluation_completion_arm_v1", + "status": "waiting_for_evaluation_admission", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_coordinates.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_coordinates.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca4d235ec4f8a6ed42e9e7528951c26225cab2b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_coordinates.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Create reproducible camera/depth/joint audit artifacts for H2O cam4.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record +from foundation_hand.geometry.camera import ( + depth_mm_to_m, + intrinsics_from_h2o, + project_points, + unproject_depth, +) + +HAND_COLORS = ((50, 220, 50), (50, 80, 255)) # BGR: left green, right red +HAND_EDGES = ( + (0, 1), (1, 2), (2, 3), (3, 4), + (0, 5), (5, 6), (6, 7), (7, 8), + (0, 9), (9, 10), (10, 11), (11, 12), + (0, 13), (13, 14), (14, 15), (15, 16), + (0, 17), (17, 18), (18, 19), (19, 20), +) + + +def choose_samples(frame_csv: Path, count: int) -> list[dict[str, str]]: + with frame_csv.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + buckets: dict[str, list[dict[str, str]]] = {} + for row in rows: + key = f"{row['subject']}:{row['joint_left_valid']}{row['joint_right_valid']}" + buckets.setdefault(key, []).append(row) + selected: list[dict[str, str]] = [] + keys = sorted(buckets) + cursor = {key: 0 for key in keys} + while len(selected) < count and keys: + next_keys = [] + for key in keys: + candidates = buckets[key] + index = cursor[key] + if index < len(candidates): + # Walk each bucket across time rather than taking adjacent frames. + pos = min(len(candidates) - 1, round(index * max(1, len(candidates) - 1) / max(1, count // len(keys)))) + selected.append(candidates[pos]) + cursor[key] += 1 + next_keys.append(key) + if len(selected) == count: + break + keys = next_keys + return selected + + +def draw_joints(image: np.ndarray, uv: np.ndarray, valid_z: np.ndarray, color: tuple[int, int, int]) -> None: + inside = valid_z & (uv[:, 0] >= 0) & (uv[:, 0] < image.shape[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < image.shape[0]) + for start, end in HAND_EDGES: + if inside[start] and inside[end]: + cv2.line(image, tuple(np.rint(uv[start]).astype(int)), tuple(np.rint(uv[end]).astype(int)), color, 2) + for index, point in enumerate(uv): + if inside[index]: + radius = 5 if index == 0 else 3 + cv2.circle(image, tuple(np.rint(point).astype(int)), radius, color, -1) + + +def write_colored_ply(path: Path, xyz: np.ndarray, rgb: np.ndarray, valid: np.ndarray, stride: int = 8) -> int: + points = xyz[::stride, ::stride][valid[::stride, ::stride]] + colors = rgb[::stride, ::stride][valid[::stride, ::stride]] + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="ascii") as handle: + handle.write("ply\nformat ascii 1.0\n") + handle.write(f"element vertex {len(points)}\n") + handle.write("property float x\nproperty float y\nproperty float z\n") + handle.write("property uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n") + for point, color in zip(points, colors, strict=True): + handle.write(f"{point[0]:.6f} {point[1]:.6f} {point[2]:.6f} {int(color[0])} {int(color[1])} {int(color[2])}\n") + return len(points) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=24) + args = parser.parse_args() + + root = args.root.resolve() + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + selected = choose_samples(args.frame_csv, args.samples) + result_rows = [] + roundtrip_errors = [] + + for sample_index, row in enumerate(selected): + take = root / row["subject"] / row["scene"] / row["take"] / "cam4" + frame = f"{int(row['frame_id']):06d}" + rgb_bgr = cv2.imread(str(take / "rgb" / f"{frame}.png"), cv2.IMREAD_COLOR) + depth_raw = cv2.imread(str(take / "depth" / f"{frame}.png"), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_raw is None: + raise RuntimeError(f"Could not decode sample {take}/{frame}") + K, expected_hw = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + if rgb_bgr.shape[:2] != expected_hw or depth_raw.shape != expected_hw: + raise ValueError(f"RGB/depth/K size mismatch at {take}/{frame}") + depth_m, depth_valid = depth_mm_to_m(depth_raw) + xyz, xyz_valid = unproject_depth(depth_m, K) + + # Pixel -> camera -> pixel should recover exact pixel centers for every valid depth. + sparse_xyz = xyz[::16, ::16].reshape(-1, 3) + sparse_valid = xyz_valid[::16, ::16].reshape(-1) + uv_back, positive = project_points(sparse_xyz[sparse_valid], K) + vv, uu = np.meshgrid(np.arange(0, expected_hw[0], 16), np.arange(0, expected_hw[1], 16), indexing="ij") + uv_reference = np.stack((uu, vv), axis=-1).reshape(-1, 2)[sparse_valid] + pixel_error = np.linalg.norm(uv_back[positive] - uv_reference[positive], axis=-1) + roundtrip_errors.extend(pixel_error.tolist()) + + overlay = rgb_bgr.copy() + joints = load_joint_record(take / "hand_pose" / f"{frame}.txt") + hand_stats = [] + for hand_index, color in enumerate(HAND_COLORS): + if joints.annotation_valid[hand_index]: + uv, positive_z = project_points(joints.joints_camera_m[hand_index], K) + draw_joints(overlay, uv, positive_z, color) + hand_stats.append({"side": ("left", "right")[hand_index], "annotation_valid": True, "projected_in_frame": int(((uv[:, 0] >= 0) & (uv[:, 0] < expected_hw[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < expected_hw[0]) & positive_z).sum())}) + else: + hand_stats.append({"side": ("left", "right")[hand_index], "annotation_valid": False, "projected_in_frame": None}) + + valid_depth = depth_m[depth_valid] + clipped = np.clip(depth_m, 0, np.quantile(valid_depth, 0.99) if valid_depth.size else 1.0) + depth_u8 = np.rint(255 * clipped / max(float(clipped.max()), 1e-6)).astype(np.uint8) + depth_color = cv2.applyColorMap(depth_u8, cv2.COLORMAP_TURBO) + depth_color[~depth_valid] = 0 + edges = cv2.Canny(depth_u8, 30, 90) + alignment = rgb_bgr.copy() + alignment[edges > 0] = (0, 255, 255) + + label = f"{row['subject']}/{row['scene']}/{row['take']}/{frame} L={row['joint_left_valid']} R={row['joint_right_valid']}" + for image in (overlay, depth_color, alignment): + cv2.rectangle(image, (0, 0), (image.shape[1], 34), (0, 0, 0), -1) + cv2.putText(image, label, (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) + prefix = f"{sample_index:02d}_{row['subject']}_{row['scene']}_{row['take']}_{frame}" + cv2.imwrite(str(output / f"{prefix}_joint_overlay.jpg"), overlay) + cv2.imwrite(str(output / f"{prefix}_depth.jpg"), depth_color) + cv2.imwrite(str(output / f"{prefix}_depth_edges_rgb.jpg"), alignment) + ply_count = write_colored_ply(output / f"{prefix}_pointcloud.ply", xyz, cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB), xyz_valid) + result_rows.append({ + "sample": prefix, + "subject": row["subject"], "scene": row["scene"], "take": row["take"], "frame_id": int(row["frame_id"]), + "K": K.tolist(), "depth_dtype": str(depth_raw.dtype), "depth_valid_fraction": float(depth_valid.mean()), + "depth_min_m": float(valid_depth.min()), "depth_p50_m": float(np.quantile(valid_depth, 0.5)), "depth_p95_m": float(np.quantile(valid_depth, 0.95)), "depth_max_m": float(valid_depth.max()), + "pixel_roundtrip_max": float(pixel_error.max()) if pixel_error.size else None, + "pointcloud_vertices": ply_count, "hands": hand_stats, + }) + + errors = np.asarray(roundtrip_errors) + report = { + "root": str(root), "sample_count": len(result_rows), "selection": "round-robin across subject and annotation-valid combinations, spread over time", + "camera_convention_supported_by_projection": "x-right, y-down, z-forward; u=fx*x/z+cx, v=fy*y/z+cy", + "depth_unit": "released uint16 millimeters converted by /1000 to meters", + "pixel_unprojection_projection_roundtrip": {"count": int(errors.size), "mean_px": float(errors.mean()), "p95_px": float(np.quantile(errors, 0.95)), "max_px": float(errors.max())}, + "mano_numeric_reconstruction": "BLOCKED_MISSING_LICENSED_MANO_ASSETS", + "samples": result_rows, + } + (output / "coordinate_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: report[key] for key in ("sample_count", "camera_convention_supported_by_projection", "depth_unit", "pixel_unprojection_projection_roundtrip", "mano_numeric_reconstruction")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_mano.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_mano.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ae1a83d4f165c9542c997f6cd3bd7ceeff5b46 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_mano.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Numerically reproduce H2O MANO fits before formal training is allowed.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record, load_mano_record +from foundation_hand.geometry.camera import intrinsics_from_h2o, project_points +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.mano_translation import mano_raw_to_wrist, wrist_to_mano_raw + + +def stats(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values) + return {"count": int(array.size), "mean_mm": float(array.mean()), "p50_mm": float(np.quantile(array, .5)), "p95_mm": float(np.quantile(array, .95)), "max_mm": float(array.max())} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=50) + args = parser.parse_args(); args.output_dir.mkdir(parents=True, exist_ok=True) + required = [args.mano_root / "MANO_LEFT.pkl", args.mano_root / "MANO_RIGHT.pkl"] + if not all(path.is_file() for path in required): + report = {"status": "blocked", "reason": "licensed MANO assets missing", "required": [str(path) for path in required]} + (args.output_dir / "mano_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)); raise SystemExit(2) + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + layers = [ManoLayer(mano_root=str(args.mano_root), side=side, use_pca=False, ncomps=45, flat_hand_mean=True) for side in ("left", "right")] + with args.frame_csv.open(newline="", encoding="utf-8") as handle: rows = [row for row in csv.DictReader(handle) if row["joint_left_valid"] == "1" and row["joint_right_valid"] == "1"] + rows = [rows[round(index * (len(rows)-1) / max(args.samples-1, 1))] for index in range(args.samples)] + errors = {"left": [], "right": []}; roundtrip = {"left": [], "right": []}; root_offsets = {"left": [], "right": []} + for sample_index, row in enumerate(rows): + take = args.root / row["subject"] / row["scene"] / row["take"] / "cam4"; stem = f"{int(row['frame_id']):06d}" + joints_gt = load_joint_record(take / "hand_pose" / f"{stem}.txt"); mano = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + image = cv2.imread(str(take / "rgb" / f"{stem}.png")); K, _ = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + for hand, side in enumerate(("left", "right")): + with torch.no_grad(): vertices_mm, joints_mm = layers[hand](torch.from_numpy(mano.pose_axis_angle[hand:hand+1]), torch.from_numpy(mano.shape[hand:hand+1])) + native_joints_m = joints_mm[0].numpy() / 1000.0; reconstructed = native_joints_m + mano.translation_raw_m[hand] + per_joint = np.linalg.norm(reconstructed - joints_gt.joints_camera_m[hand], axis=-1) * 1000 + errors[side].extend(per_joint.tolist()); root_offsets[side].append(native_joints_m[0].tolist()) + wrist = mano_raw_to_wrist(mano.translation_raw_m[hand], native_joints_m[0]); raw_back = wrist_to_mano_raw(wrist, native_joints_m[0]) + roundtrip[side].append(float(np.linalg.norm(raw_back - mano.translation_raw_m[hand]) * 1000)) + if sample_index < 10: + uv, positive = project_points(reconstructed, K) + for point, valid in zip(uv, positive, strict=True): + if valid: cv2.circle(image, tuple(np.rint(point).astype(int)), 3, ((50,220,50),(50,80,255))[hand], -1) + if sample_index < 10: cv2.imwrite(str(args.output_dir / f"{sample_index:02d}_{row['subject']}_{row['scene']}_{row['take']}_{stem}_mano_overlay.jpg"), image) + report = { + "status": "passed" if max(stats(errors[side])["p95_mm"] for side in errors) < 5 else "failed", + "configuration": {"use_pca": False, "ncomps": 45, "flat_hand_mean": True, "native_output_unit": "mm", "placed_output_unit": "m"}, + "joint_reconstruction": {side: stats(values) for side, values in errors.items()}, + "translation_semantics": "raw translation places the MANO model origin; wrist = raw + native MANO joint0 / 1000", + "raw_to_wrist_root_offsets_m": root_offsets, + "translation_roundtrip": {side: stats(values) for side, values in roundtrip.items()}, + } + (args.output_dir / "mano_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: report[key] for key in ("status", "joint_reconstruction", "translation_semantics", "translation_roundtrip")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase2_cam4.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase2_cam4.py new file mode 100644 index 0000000000000000000000000000000000000000..147fa879e7466f0015130321ffba9dec3915f615 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase2_cam4.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +"""Reproducible full-record audit of the extracted H2O cam4 dataset.""" + +from __future__ import annotations + +import argparse +import csv +import json +import random +from collections import Counter +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import ( + load_float_record, + parse_joint_record, + parse_mano_record, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + +CORE_FRAME_MODALITIES = ( + "rgb", + "depth", + "cam_pose", + "hand_pose", + "hand_pose_mano", + "obj_pose", + "obj_pose_rt", +) +SIDES = ("left", "right") + + +def quantiles(values: list[float] | np.ndarray) -> dict[str, float | int | None]: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if array.size == 0: + return {"count": 0, "mean": None, "p50": None, "p95": None, "max": None} + return { + "count": int(array.size), + "mean": float(array.mean()), + "p50": float(np.quantile(array, 0.50)), + "p95": float(np.quantile(array, 0.95)), + "max": float(array.max()), + } + + +def ids_in(directory: Path) -> set[int]: + return {int(path.stem) for path in directory.iterdir() if path.is_file() and path.stem.isdigit()} + + +def sample_evenly(items: list[Path], count: int) -> list[Path]: + if count <= 0 or not items: + return [] + if len(items) <= count: + return items + indices = np.linspace(0, len(items) - 1, count, dtype=int) + return [items[index] for index in indices] + + +def make_contact_sheet(rows: list[dict[str, object]], output: Path, title: str) -> None: + if not rows: + return + tile_w, tile_h = 320, 205 + columns = 4 + result_rows = (len(rows) + columns - 1) // columns + canvas = np.zeros((result_rows * tile_h + 36, columns * tile_w, 3), dtype=np.uint8) + cv2.putText(canvas, title, (8, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) + for index, row in enumerate(rows): + image = cv2.imread(str(row["rgb_path"]), cv2.IMREAD_COLOR) + if image is None: + continue + image = cv2.resize(image, (tile_w, 180), interpolation=cv2.INTER_AREA) + label = str(row["label"]) + cv2.rectangle(image, (0, 0), (tile_w, 24), (0, 0, 0), -1) + cv2.putText(image, label[:52], (4, 17), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (255, 255, 255), 1) + y = 36 + (index // columns) * tile_h + x = (index % columns) * tile_w + canvas[y : y + 180, x : x + tile_w] = image + output.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(output), canvas) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--depth-samples-per-take", type=int, default=2) + parser.add_argument("--invalid-visual-samples", type=int, default=40) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + root = args.root.resolve() + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + rng = random.Random(args.seed) + + take_dirs = sorted(root.glob("subject*/*/*/cam4")) + if not take_dirs: + raise RuntimeError(f"No cam4 takes found below {root}") + + take_rows: list[dict[str, object]] = [] + depth_candidates: list[Path] = [] + invalid_visuals: dict[str, list[dict[str, object]]] = {"left": [], "right": []} + record_lengths = {"hand_pose": Counter(), "hand_pose_mano": Counter(), "cam_pose": Counter()} + valid_combinations = Counter() + valid_agreement = Counter() + projection_counts = {side: Counter() for side in SIDES} + raw_to_wrist_offsets = {side: [] for side in SIDES} + raw_wrist_distance_mm = {side: [] for side in SIDES} + rotation_det_errors: list[float] = [] + rotation_orth_errors: list[float] = [] + pose_last_row_errors: list[float] = [] + intrinsics_rows: list[list[float]] = [] + image_shapes = Counter() + missing_by_modality = Counter() + extra_by_modality = Counter() + frame_count = 0 + nonfinite_records = Counter() + + frame_csv = output / "frame_audit.csv" + frame_fields = [ + "subject", + "scene", + "take", + "frame_id", + "joint_left_valid", + "joint_right_valid", + "mano_left_valid", + "mano_right_valid", + "left_joints_in_frame", + "right_joints_in_frame", + "left_wrist_in_frame", + "right_wrist_in_frame", + "left_raw_to_wrist_mm", + "right_raw_to_wrist_mm", + "rgb_path", + ] + + with frame_csv.open("w", newline="", encoding="utf-8") as frame_handle: + writer = csv.DictWriter(frame_handle, fieldnames=frame_fields) + writer.writeheader() + + for cam4 in take_dirs: + subject, scene, take = cam4.parts[-4:-1] + K_values = load_float_record(cam4 / "cam_intrinsics.txt") + K, expected_hw = intrinsics_from_h2o(K_values) + intrinsics_rows.append(K_values.tolist()) + + frame_sets = {name: ids_in(cam4 / name) for name in CORE_FRAME_MODALITIES} + rgb_ids = frame_sets["rgb"] + for name, ids in frame_sets.items(): + missing_by_modality[name] += len(rgb_ids - ids) + extra_by_modality[name] += len(ids - rgb_ids) + + rgb_paths = sorted((cam4 / "rgb").glob("*.png")) + depth_paths = sorted((cam4 / "depth").glob("*.png")) + depth_candidates.extend(sample_evenly(depth_paths, args.depth_samples_per_take)) + if rgb_paths: + sample_rgb = cv2.imread(str(rgb_paths[0]), cv2.IMREAD_COLOR) + if sample_rgb is None: + raise RuntimeError(f"Could not decode {rgb_paths[0]}") + image_shapes[str(tuple(sample_rgb.shape))] += 1 + if sample_rgb.shape[:2] != expected_hw: + raise ValueError( + f"K image size {expected_hw} does not match RGB {sample_rgb.shape[:2]} at {cam4}" + ) + + take_rows.append( + { + "subject": subject, + "scene": scene, + "take": take, + "frames": len(rgb_ids), + **{f"missing_{name}": len(rgb_ids - ids) for name, ids in frame_sets.items()}, + **{f"extra_{name}": len(ids - rgb_ids) for name, ids in frame_sets.items()}, + } + ) + + for frame_id in sorted(rgb_ids): + stem = f"{frame_id:06d}" + joint_values = load_float_record(cam4 / "hand_pose" / f"{stem}.txt") + mano_values = load_float_record(cam4 / "hand_pose_mano" / f"{stem}.txt") + pose_values = load_float_record(cam4 / "cam_pose" / f"{stem}.txt") + record_lengths["hand_pose"][str(joint_values.size)] += 1 + record_lengths["hand_pose_mano"][str(mano_values.size)] += 1 + record_lengths["cam_pose"][str(pose_values.size)] += 1 + if not np.isfinite(joint_values).all(): + nonfinite_records["hand_pose"] += 1 + if not np.isfinite(mano_values).all(): + nonfinite_records["hand_pose_mano"] += 1 + if not np.isfinite(pose_values).all(): + nonfinite_records["cam_pose"] += 1 + + joints = parse_joint_record(joint_values) + mano = parse_mano_record(mano_values) + joint_key = tuple(bool(value) for value in joints.annotation_valid) + mano_key = tuple(bool(value) for value in mano.annotation_valid) + valid_combinations[f"joint_{int(joint_key[0])}{int(joint_key[1])}"] += 1 + valid_combinations[f"mano_{int(mano_key[0])}{int(mano_key[1])}"] += 1 + valid_agreement[str(joint_key == mano_key)] += 1 + + camera_pose = pose_values.reshape(4, 4) + rotation = camera_pose[:3, :3] + rotation_det_errors.append(abs(float(np.linalg.det(rotation)) - 1.0)) + rotation_orth_errors.append(float(np.linalg.norm(rotation.T @ rotation - np.eye(3)))) + pose_last_row_errors.append(float(np.linalg.norm(camera_pose[3] - np.array([0, 0, 0, 1])))) + + frame_row: dict[str, object] = { + "subject": subject, + "scene": scene, + "take": take, + "frame_id": frame_id, + "joint_left_valid": int(joints.annotation_valid[0]), + "joint_right_valid": int(joints.annotation_valid[1]), + "mano_left_valid": int(mano.annotation_valid[0]), + "mano_right_valid": int(mano.annotation_valid[1]), + "rgb_path": str(cam4 / "rgb" / f"{stem}.png"), + } + + for side_index, side in enumerate(SIDES): + in_frame_count = -1 + wrist_in_frame = -1 + distance_mm = float("nan") + if joints.annotation_valid[side_index]: + uv, positive = project_points(joints.joints_camera_m[side_index], K) + inside = ( + positive + & (uv[:, 0] >= 0) + & (uv[:, 0] < expected_hw[1]) + & (uv[:, 1] >= 0) + & (uv[:, 1] < expected_hw[0]) + ) + in_frame_count = int(inside.sum()) + wrist_in_frame = int(inside[0]) + projection_counts[side]["valid"] += 1 + projection_counts[side]["any_joint_in_frame"] += int(inside.any()) + projection_counts[side]["all_joints_in_frame"] += int(inside.all()) + projection_counts[side]["wrist_in_frame"] += int(inside[0]) + projection_counts[side]["all_positive_z"] += int(positive.all()) + + if joints.annotation_valid[side_index] and mano.annotation_valid[side_index]: + offset = ( + joints.joints_camera_m[side_index, 0] + - mano.translation_raw_m[side_index] + ) + raw_to_wrist_offsets[side].append(offset.astype(np.float64)) + distance_mm = float(np.linalg.norm(offset) * 1000.0) + raw_wrist_distance_mm[side].append(distance_mm) + + frame_row[f"{side}_joints_in_frame"] = in_frame_count + frame_row[f"{side}_wrist_in_frame"] = wrist_in_frame + frame_row[f"{side}_raw_to_wrist_mm"] = distance_mm + + if not joints.annotation_valid[side_index]: + invalid_visuals[side].append( + { + "rgb_path": cam4 / "rgb" / f"{stem}.png", + "label": f"{subject}/{scene}/{take}/{stem} {side} ann=0", + } + ) + + writer.writerow(frame_row) + frame_count += 1 + + take_csv = output / "take_audit.csv" + with take_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(take_rows[0])) + writer.writeheader() + writer.writerows(take_rows) + + depth_rows: list[dict[str, object]] = [] + pooled_depth: list[np.ndarray] = [] + for path in depth_candidates: + depth_mm = cv2.imread(str(path), cv2.IMREAD_UNCHANGED) + if depth_mm is None: + raise RuntimeError(f"Could not decode depth {path}") + depth_m, valid = depth_mm_to_m(depth_mm) + positive = depth_m[valid] + sampled = positive[::64] if positive.size else positive + pooled_depth.append(sampled) + depth_rows.append( + { + "path": str(path), + "dtype": str(depth_mm.dtype), + "height": depth_mm.shape[0], + "width": depth_mm.shape[1], + "zero_fraction": float((depth_mm == 0).mean()), + "positive_min_m": float(positive.min()) if positive.size else None, + "positive_p50_m": float(np.quantile(positive, 0.50)) if positive.size else None, + "positive_p95_m": float(np.quantile(positive, 0.95)) if positive.size else None, + "positive_p99_m": float(np.quantile(positive, 0.99)) if positive.size else None, + "positive_max_m": float(positive.max()) if positive.size else None, + "fraction_gt_3_86m": float((depth_m > 3.86).mean()), + "fraction_gt_5_46m": float((depth_m > 5.46).mean()), + } + ) + + depth_csv = output / "depth_sample_stats.csv" + with depth_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(depth_rows[0])) + writer.writeheader() + writer.writerows(depth_rows) + + selected_invalid = {} + for side in SIDES: + candidates = invalid_visuals[side] + rng.shuffle(candidates) + selected_invalid[side] = candidates[: args.invalid_visual_samples] + make_contact_sheet( + selected_invalid[side], + output / f"annotation_invalid_{side}_contact_sheet.jpg", + f"H2O cam4 {side}: annotation_valid=0 (not a presence label)", + ) + + intrinsics = np.asarray(intrinsics_rows, dtype=np.float64) + combined_depth = np.concatenate(pooled_depth) if pooled_depth else np.empty(0) + summary = { + "root": str(root), + "seed": args.seed, + "take_count": len(take_dirs), + "frame_count": frame_count, + "camera": "cam4_only", + "record_length_distributions": { + name: dict(counter) for name, counter in record_lengths.items() + }, + "valid_combinations": dict(valid_combinations), + "joint_mano_valid_agreement": dict(valid_agreement), + "annotation_valid_is_presence": False, + "presence_fields_found": False, + "presence_training_recommendation": "disabled_until_reliable_labels_exist", + "projection_from_annotation_valid_joints": { + side: dict(counter) for side, counter in projection_counts.items() + }, + "raw_mano_translation_is_wrist": False, + "raw_to_wrist_offset_m": { + side: { + "x": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 0]), + "y": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 1]), + "z": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 2]), + "norm_mm": quantiles(raw_wrist_distance_mm[side]), + } + for side in SIDES + }, + "frame_alignment": { + "missing_by_modality": dict(missing_by_modality), + "extra_by_modality": dict(extra_by_modality), + }, + "nonfinite_records": dict(nonfinite_records), + "camera_pose": { + "det_rotation_abs_error": quantiles(rotation_det_errors), + "orthogonality_frobenius_error": quantiles(rotation_orth_errors), + "last_row_error": quantiles(pose_last_row_errors), + }, + "intrinsics": { + "count": int(intrinsics.shape[0]), + "fx": quantiles(intrinsics[:, 0]), + "fy": quantiles(intrinsics[:, 1]), + "cx": quantiles(intrinsics[:, 2]), + "cy": quantiles(intrinsics[:, 3]), + "width_values": sorted(set(intrinsics[:, 4].tolist())), + "height_values": sorted(set(intrinsics[:, 5].tolist())), + }, + "rgb_shapes_by_take": dict(image_shapes), + "depth_audit": { + "sampling": "uniform frames within every take; all sampled pixels decoded", + "sample_count": len(depth_rows), + "samples_per_take": args.depth_samples_per_take, + "positive_depth_m": quantiles(combined_depth), + "zero_fraction_across_sample_means": quantiles( + [float(row["zero_fraction"]) for row in depth_rows] + ), + }, + "visibility_or_occlusion_fields": [], + "outputs": { + "frame_csv": str(frame_csv), + "take_csv": str(take_csv), + "depth_csv": str(depth_csv), + "invalid_contact_sheets": { + side: str(output / f"annotation_invalid_{side}_contact_sheet.jpg") + for side in SIDES + }, + }, + } + (output / "cam4_audit_summary.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(summary, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() + diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase3_evaluations.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase3_evaluations.py new file mode 100644 index 0000000000000000000000000000000000000000..49def655a023b3142313873e6958a56e53230566 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase3_evaluations.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Audit complete Phase 3 official-validation outputs.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path + + +def json_finite(value) -> bool: + if isinstance(value, float): + return math.isfinite(value) + if isinstance(value, dict): + return all(json_finite(item) for item in value.values()) + if isinstance(value, (list, tuple)): + return all(json_finite(item) for item in value) + return True + + +def audit_csv(path: Path, expected_rows: int) -> tuple[int, bool]: + rows = 0 + finite = True + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + rows += 1 + for value in row.values(): + if value in (None, ""): + continue + try: + numeric = float(value) + except ValueError: + continue + finite = finite and math.isfinite(numeric) + return rows, finite and rows == expected_rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("evaluation_root", type=Path) + parser.add_argument("--expected-evaluations", type=int, required=True) + parser.add_argument("--expected-clips", type=int, default=1495) + parser.add_argument("--expected-frames", type=int, default=11638) + parser.add_argument("--expected-frame-rows", type=int, default=23276) + parser.add_argument("--expected-transition-rows", type=int, default=30293) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + + reports = sorted(args.evaluation_root.glob("*/*/evaluation.json")) + records = [] + for path in reports: + report = json.loads(path.read_text(encoding="utf-8")) + frame_rows, frame_csv_valid = audit_csv( + path.parent / "per_hand_frame_metrics.csv", args.expected_frame_rows, + ) + transition_rows, transition_csv_valid = audit_csv( + path.parent / "per_temporal_transition_metrics.csv", + args.expected_transition_rows, + ) + passed = ( + report.get("status") == "evaluated" + and report.get("official_test_used") is False + and report.get("split_role") == "official_validation" + and report.get("clips") == args.expected_clips + and report.get("frames") == args.expected_frames + and json_finite(report) + and frame_csv_valid + and transition_csv_valid + ) + records.append({ + "run": path.parents[1].name, + "role": path.parent.name, + "report": str(path), + "checkpoint_sha256": report.get("checkpoint", {}).get("sha256"), + "frame_rows": frame_rows, + "transition_rows": transition_rows, + "passed": passed, + }) + + passed = len(records) == args.expected_evaluations and all( + record["passed"] for record in records + ) + payload = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "evaluations": len(records), + "expected_evaluations": args.expected_evaluations, + "total_frame_rows": sum(record["frame_rows"] for record in records), + "total_transition_rows": sum(record["transition_rows"] for record in records), + "records": records, + } + output = args.output or args.evaluation_root / "evaluation_audit.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": payload["status"], "evaluations": len(records), + "output": str(output), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase3_periodic_checkpoints.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase3_periodic_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..800daf71cffb5e2c37ca0ecb20384214bdd44b88 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase3_periodic_checkpoints.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Audit periodic Phase 3 checkpoints with one isolated loader per run.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +from pathlib import Path + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def worker(checkpoint_path: Path) -> None: + import torch + + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + model_finite = all( + not torch.is_tensor(value) or torch.isfinite(value).all().item() + for value in checkpoint.get("model", {}).values() + ) + print(json.dumps({ + "step": int(checkpoint["step"]), + "model_finite": model_finite, + "bytes": checkpoint_path.stat().st_size, + "sha256": sha256(checkpoint_path), + })) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_root", type=Path, nargs="?") + parser.add_argument("--step", type=int) + parser.add_argument("--expected-runs", type=int) + parser.add_argument("--run-prefix") + parser.add_argument("--output", type=Path) + parser.add_argument("--worker", type=Path) + args = parser.parse_args() + + if args.worker is not None: + worker(args.worker) + return + if args.run_root is None or args.step is None: + parser.error("run_root and --step are required") + + checkpoint_name = f"step_{args.step:07d}.pt" + run_dirs = sorted( + path.parent for path in args.run_root.glob(f"*/{checkpoint_name}") + if path.parent.is_dir() + and (args.run_prefix is None or path.parent.name.startswith(args.run_prefix)) + ) + if args.expected_runs is not None and len(run_dirs) != args.expected_runs: + raise ValueError( + f"expected {args.expected_runs} {checkpoint_name} files, found {len(run_dirs)}" + ) + + records = [] + for run_dir in run_dirs: + checkpoint_path = run_dir / checkpoint_name + process = subprocess.run( + [sys.executable, str(Path(__file__).resolve()), "--worker", str(checkpoint_path)], + check=True, capture_output=True, text=True, + ) + checkpoint_record = json.loads(process.stdout) + validation_rows = [ + json.loads(line) for line in (run_dir / "validation.jsonl").read_text( + encoding="utf-8" + ).splitlines() if line.strip() + ] + matching_validation = [ + row for row in validation_rows if int(row["step"]) == args.step + ] + provenance_path = run_dir / "run_provenance.json" + if not provenance_path.is_file(): + candidates = sorted(run_dir.glob("resume_provenance_*.json")) + if len(candidates) != 1: + raise FileNotFoundError( + f"expected one run/resume provenance file in {run_dir}" + ) + provenance_path = candidates[0] + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + records.append({ + "run": run_dir.name, + **checkpoint_record, + "run_commit": provenance.get("git_commit"), + "validation_records": len(matching_validation), + "validation_total_loss": ( + matching_validation[0]["losses"]["total"] + if len(matching_validation) == 1 else None + ), + }) + + passed = bool(records) and all( + record["step"] == args.step + and record["model_finite"] + and record["validation_records"] == 1 + for record in records + ) + result = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "expected_step": args.step, + "run_prefix": args.run_prefix, + "runs": records, + } + suffix = f"{args.step // 1000}k" if args.step % 1000 == 0 else str(args.step) + prefix = f"{args.run_prefix.rstrip('_-')}_" if args.run_prefix else "" + output_path = ( + args.output + if args.output is not None + else args.run_root / f"checkpoint_audit_{prefix}{suffix}.json" + ) + if output_path.exists(): + raise FileExistsError(f"refusing to overwrite checkpoint audit: {output_path}") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": result["status"], "runs": len(records), "output": str(output_path) + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase3_run_checkpoints.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase3_run_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..e64c457dd74c0cd479f2c2f786f5f4e3c7ad56b5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase3_run_checkpoints.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Audit one completed Phase 3 run in an isolated process.""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +from pathlib import Path + +import torch + + +FINAL_ROLES = { + "step_100k": "step_0100000.pt", + "best_absolute": "best.pt", + "best_z": "best_z.pt", + "final": "step_0100000_final.pt", +} + + +def load_roles(path: Path | None) -> dict[str, str]: + if path is None: + return dict(FINAL_ROLES) + values = json.loads(path.read_text(encoding="utf-8")) + if ( + not isinstance(values, dict) + or not values + or any(not isinstance(role, str) or not role for role in values) + or any( + not isinstance(filename, str) or Path(filename).name != filename + for filename in values.values() + ) + ): + raise ValueError("checkpoint spec must be a non-empty role-to-filename JSON object") + return values + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_dir", type=Path) + parser.add_argument("--completed-step", type=int, default=100_000) + parser.add_argument("--checkpoint-spec", type=Path) + args = parser.parse_args() + roles = load_roles(args.checkpoint_spec) + summary = json.loads((args.run_dir / "summary.json").read_text(encoding="utf-8")) + result = { + "run": args.run_dir.name, + "summary_status": summary.get("status"), + "completed_step": summary.get("completed_step"), + "official_test_used": False, + "roles": {}, + } + for role, filename in roles.items(): + path = args.run_dir / filename + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + finite = all( + not torch.is_tensor(value) or torch.isfinite(value).all().item() + for value in checkpoint.get("model", {}).values() + ) + result["roles"][role] = { + "path": str(path), + "bytes": path.stat().st_size, + "sha256": sha256(path), + "step": int(checkpoint["step"]), + "model_finite": finite, + } + del checkpoint + gc.collect() + result["status"] = "passed" if ( + result["summary_status"] == "completed" + and result["completed_step"] == args.completed_step + and all(item["model_finite"] for item in result["roles"].values()) + ) else "failed" + output = args.run_dir / "final_checkpoint_audit.json" + output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"run": args.run_dir.name, "status": result["status"]})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase4_visualizations.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase4_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..afb6efba5a62c71bf21add06f75168566c1a33f0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase4_visualizations.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Audit raw/filtered Phase 4 videos and deterministic rerender pixels.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def fraction(value: str) -> float: + numerator, denominator = value.split("/", 1) + return float(numerator) / float(denominator) + + +def probe_video(path: Path) -> dict[str, object]: + process = subprocess.run([ + "ffprobe", "-v", "error", "-select_streams", "v:0", + "-show_entries", "stream=codec_name,pix_fmt,width,height,avg_frame_rate,nb_frames,duration", + "-of", "json", str(path), + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) + streams = json.loads(process.stdout).get("streams", []) + if len(streams) != 1: + raise ValueError(f"expected one video stream: {path}") + stream = streams[0] + return { + "codec": stream.get("codec_name"), + "pixel_format": stream.get("pix_fmt"), + "width": int(stream["width"]), "height": int(stream["height"]), + "fps": fraction(stream["avg_frame_rate"]), + "frames": int(stream["nb_frames"]), + "duration_seconds": float(stream["duration"]), + } + + +def decoded_frame_audit(path: Path, expected_frames: int) -> list[dict[str, object]]: + capture = cv2.VideoCapture(str(path)) + if not capture.isOpened(): + raise RuntimeError(f"cannot decode video: {path}") + records = [] + try: + for index in sorted({0, expected_frames // 2, expected_frames - 1}): + capture.set(cv2.CAP_PROP_POS_FRAMES, index) + ok, frame = capture.read() + if not ok or frame is None: + raise RuntimeError(f"cannot decode frame {index}: {path}") + std = float(frame.std()) + nonzero_fraction = float(np.count_nonzero(frame) / frame.size) + if std < 1.0 or nonzero_fraction < 0.05: + raise ValueError(f"blank/degenerate frame {index}: {path}") + records.append({ + "frame_index": index, "std": std, + "nonzero_fraction": nonzero_fraction, + "pixel_sha256": hashlib.sha256(frame.tobytes()).hexdigest(), + }) + finally: + capture.release() + return records + + +def audit_video( + path: Path, + *, + expected_frames: int, + expected_fps: float, + expected_sha256: str | None = None, + require_h264: bool = False, +) -> dict[str, object]: + if not path.is_file(): + raise FileNotFoundError(path) + digest = sha256(path) + if expected_sha256 is not None and digest != expected_sha256: + raise ValueError(f"video SHA256 mismatch: {path}") + probe = probe_video(path) + if probe["frames"] != expected_frames: + raise ValueError(f"video frame count mismatch: {path}") + if abs(float(probe["fps"]) - expected_fps) > 1e-3: + raise ValueError(f"video fps mismatch: {path}") + if require_h264 and ( + probe["codec"] != "h264" or probe["pixel_format"] != "yuv420p" + ): + raise ValueError(f"filtered video codec contract mismatch: {path}") + return { + "path": str(path.resolve()), "sha256": digest, **probe, + "decoded_frames": decoded_frame_audit(path, expected_frames), + "passed": True, + } + + +def deterministic_frame_hash_audit( + primary: dict[str, Any], rerun: dict[str, Any], +) -> int: + def index(manifest: dict[str, Any]) -> dict[tuple[str, str, str], list[str]]: + return { + (record["take"], record["condition"], video_name): video["frame_pixel_sha256"] + for record in manifest["cases"] + for video_name, video in record["videos"].items() + } + left, right = index(primary), index(rerun) + if left.keys() != right.keys(): + raise ValueError("deterministic video case grid mismatch") + for key in left: + if left[key] != right[key]: + raise ValueError(f"deterministic frame pixel mismatch: {key}") + return sum(len(values) for values in left.values()) + + +def audit_raw_manifest(manifest: dict[str, Any]) -> list[dict[str, object]]: + if manifest.get("status") != "complete" or manifest.get("official_test_used") is not False: + raise ValueError("invalid raw video manifest") + fps = float(manifest["visualization_fps"]) + records = [] + for case in manifest["cases"]: + frame_count = len(case["frame_ids"]) + for role, path in case["videos"].items(): + records.append({ + "set": "raw_model_primary_results", "take": case["take"], + "condition": "raw", "role": role, + **audit_video( + Path(path), expected_frames=frame_count, expected_fps=fps, + ), + }) + return records + + +def audit_filtered_manifest(manifest: dict[str, Any]) -> list[dict[str, object]]: + if ( + manifest.get("status") != "complete" + or manifest.get("official_test_used") is not False + or manifest.get("result_role") != "filtered_inference_secondary_results" + ): + raise ValueError("invalid filtered video manifest") + records = [] + expected_roles = { + "raw_vs_filtered_30fps", "raw_vs_filtered_4fps", + "failure_diagnostic_30fps", + } + for case in manifest["cases"]: + if set(case["videos"]) != expected_roles: + raise ValueError("filtered video role grid mismatch") + for role, video in case["videos"].items(): + records.append({ + "set": "filtered_inference_secondary_results", + "take": case["take"], "condition": case["condition"], + "role": role, + **audit_video( + Path(video["path"]), expected_frames=int(video["frames"]), + expected_fps=float(video["fps"]), + expected_sha256=video["sha256"], require_h264=True, + ), + }) + return records + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--raw-manifest", type=Path, required=True) + parser.add_argument("--filtered-manifest", type=Path, required=True) + parser.add_argument("--filtered-rerun-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite visualization audit: {args.output}") + raw = json.loads(args.raw_manifest.read_text(encoding="utf-8")) + filtered = json.loads(args.filtered_manifest.read_text(encoding="utf-8")) + rerun = json.loads(args.filtered_rerun_manifest.read_text(encoding="utf-8")) + records = audit_raw_manifest(raw) + records.extend(audit_filtered_manifest(filtered)) + records.extend(audit_filtered_manifest(rerun)) + compared_frames = deterministic_frame_hash_audit(filtered, rerun) + report = { + "status": "passed", + "official_test_used": False, + "videos": len(records), + "deterministic_frame_hashes_compared": compared_frames, + "raw_model_primary_results_kept_separate": True, + "filtered_inference_secondary_results_kept_separate": True, + "records": records, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "passed", "videos": len(records), + "deterministic_frame_hashes_compared": compared_frames, + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_alignment_visualizations.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_alignment_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..3ebd0b9fb31f916e3a2c0aaa08e79f95d53b848a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_alignment_visualizations.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Audit deterministic Phase 5 alignment diagnostic images.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def case_without_path(case: dict[str, Any]) -> dict[str, Any]: + return {key: value for key, value in case.items() if key not in ("image", "image_sha256")} + + +def image_audit(case: dict[str, Any]) -> dict[str, Any]: + path = Path(case["image"]) + digest = sha256(path) + if digest != case["image_sha256"]: + raise ValueError(f"manifest image hash mismatch: {path}") + image = cv2.imread(str(path), cv2.IMREAD_COLOR) + if image is None: + raise ValueError(f"cannot decode diagnostic image: {path}") + std = float(image.std()) + nonzero_fraction = float(np.count_nonzero(image) / image.size) + if min(image.shape[:2]) < 480 or std < 5.0 or nonzero_fraction < 0.2: + raise ValueError(f"blank or degenerate diagnostic image: {path}") + return { + "role": case["role"], "path": str(path.resolve()), "sha256": digest, + "width": int(image.shape[1]), "height": int(image.shape[0]), + "pixel_std": std, "nonzero_fraction": nonzero_fraction, + } + + +def audit_manifests( + primary: dict[str, Any], rerun: dict[str, Any], +) -> dict[str, Any]: + for manifest in (primary, rerun): + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_validation_secondary_failure_diagnostic" + or manifest.get("official_test_used") is not False + or manifest.get("used_for_model_or_threshold_selection") is not False + ): + raise ValueError("invalid alignment visualization manifest contract") + left = {case["role"]: case for case in primary["cases"]} + right = {case["role"]: case for case in rerun["cases"]} + if left.keys() != right.keys() or len(left) != len(primary["cases"]): + raise ValueError("visualization role grid mismatch or duplicate role") + primary_records, rerun_records = [], [] + for role in left: + if case_without_path(left[role]) != case_without_path(right[role]): + raise ValueError(f"visualization case metadata mismatch: {role}") + primary_record = image_audit(left[role]) + rerun_record = image_audit(right[role]) + if primary_record["sha256"] != rerun_record["sha256"]: + raise ValueError(f"deterministic image hash mismatch: {role}") + primary_records.append(primary_record) + rerun_records.append(rerun_record) + return { + "status": "passed", + "result_role": "deterministic_official_validation_visualization_audit", + "cases": len(left), + "deterministic_image_hashes_compared": len(left), + "primary": primary_records, + "rerun": rerun_records, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--primary-manifest", type=Path, required=True) + parser.add_argument("--rerun-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError("visualization audit refuses to overwrite output") + primary = json.loads(args.primary_manifest.read_text(encoding="utf-8")) + rerun = json.loads(args.rerun_manifest.read_text(encoding="utf-8")) + report = audit_manifests(primary, rerun) + report.update({ + "primary_manifest": str(args.primary_manifest.resolve()), + "rerun_manifest": str(args.rerun_manifest.resolve()), + }) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "cases": report["cases"], + "output": str(args.output), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_oof_bank.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..3d6814f9f1d8ebb1112e0086b5e5f95a44cd9f77 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_oof_bank.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python3 +"""Audit Phase 5 group-heldout coarse banks before refiner fitting.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + + +TAIL_ADMISSION_P95_MM = 40.0 +SEEDS = (20260716, 20260717, 20260718) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def distribution(values_m: np.ndarray) -> dict[str, float | int]: + values_mm = np.asarray(values_m, dtype=np.float64).reshape(-1) * 1000.0 + values_mm = values_mm[np.isfinite(values_mm)] + if not values_mm.size: + raise ValueError("cannot summarize an empty residual distribution") + absolute = np.abs(values_mm) + p95 = float(np.percentile(absolute, 95)) + return { + "count": int(len(values_mm)), + "signed_mean_mm": float(values_mm.mean()), + "signed_std_mm": float(values_mm.std()), + "mae_mm": float(absolute.mean()), + "p50_mm": float(np.percentile(absolute, 50)), + "p90_mm": float(np.percentile(absolute, 90)), + "p95_mm": p95, + "p99_mm": float(np.percentile(absolute, 99)), + "cvar95_mm": float(absolute[absolute >= p95].mean()), + "maximum_mm": float(absolute.max()), + } + + +def size_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 64.0, "small", np.where(values < 128.0, "medium", "large")) + + +def depth_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 0.5, "near", np.where(values < 0.8, "middle", "far")) + + +def validity_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 0.25, "low", np.where(values < 0.60, "partial", "strong")) + + +def validate_bank_manifest(path: Path) -> dict[str, Any]: + manifest = json.loads(path.read_text(encoding="utf-8")) + required = ( + manifest.get("status") == "complete", + manifest.get("bank_version") == 2, + manifest.get("scope") == "full_fold", + manifest.get("result_role") == "official_train_group_heldout_oof_predictions", + manifest.get("leakage_audit", {}).get("passed") is True, + manifest.get("official_validation_used_for_assignment") is False, + manifest.get("official_test_used") is False, + manifest.get("oracle_information_at_inference") is False, + ) + if not all(required): + raise ValueError(f"OOF audit requires a complete leakage-free full-fold bank: {path}") + return manifest + + +def load_oof_banks(bank_dirs: list[Path]) -> tuple[dict[str, np.ndarray], list[dict[str, Any]]]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + manifests = [] + observed_pairs: set[tuple[int, str]] = set() + keys_by_checkpoint: dict[str, set[str]] = defaultdict(set) + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = validate_bank_manifest(manifest_path) + manifests.append(manifest) + fold = int(manifest["fold"]) + checkpoint = str(manifest["checkpoint"]["sha256"]) + pair = (fold, checkpoint) + if pair in observed_pairs: + raise ValueError(f"duplicate fold/checkpoint bank: {pair}") + observed_pairs.add(pair) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take bank hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in ( + "frame_id", "frame_valid", "mano_annotation_valid", + "translation_residual_m", "target_wrist_translation", + "coarse_hand_scale_px", "alignment_valid_fraction", + )} + valid = arrays["frame_valid"].astype(bool)[:, None] & arrays[ + "mano_annotation_valid" + ].astype(bool) + time = len(arrays["frame_id"]) + side = np.broadcast_to(np.asarray(("left", "right"))[None], (time, 2)) + frame = np.broadcast_to(arrays["frame_id"][:, None], (time, 2)) + take = str(take_record["take"]) + subject, action_family = take.split("/")[:2] + sample_keys = np.asarray([ + f"{take}|{int(frame_id)}|{hand}" + for frame_id, hand in zip(frame[valid], side[valid], strict=True) + ]) + duplicate_keys = keys_by_checkpoint[checkpoint].intersection(sample_keys.tolist()) + if duplicate_keys: + raise ValueError(f"duplicate samples within checkpoint bank: {take}") + keys_by_checkpoint[checkpoint].update(sample_keys.tolist()) + count = int(valid.sum()) + chunks["residual_z_m"].append(arrays["translation_residual_m"][..., 2][valid]) + chunks["side"].append(side[valid]) + chunks["frame_id"].append(frame[valid]) + chunks["sample_key"].append(sample_keys) + chunks["subject"].append(np.full(count, subject)) + chunks["action_family"].append(np.full(count, action_family)) + chunks["take"].append(np.full(count, take)) + chunks["fold"].append(np.full(count, fold, dtype=np.int16)) + chunks["coarse_seed"].append(np.full(count, int(manifest.get("seed", -1)), dtype=np.int64)) + chunks["checkpoint"].append(np.full(count, checkpoint)) + chunks["hand_scale_px"].append(arrays["coarse_hand_scale_px"][valid]) + chunks["wrist_depth_m"].append(arrays["target_wrist_translation"][..., 2][valid]) + chunks["local_depth_valid_fraction"].append(arrays["alignment_valid_fraction"][valid]) + if {int(manifest["fold"]) for manifest in manifests} != {0, 1, 2}: + raise ValueError("OOF audit requires coverage of folds 0/1/2") + return {key: np.concatenate(values) for key, values in chunks.items()}, manifests + + +def validation_reference(a1_root: Path) -> tuple[list[dict[str, Any]], np.ndarray]: + rows = [] + values = [] + for seed in SEEDS: + with np.load(a1_root / f"seed_{seed}" / "validation" / "features.npz", allow_pickle=False) as archive: + residual = archive["target_residual_z_m"].astype(np.float64) + rows.append({"seed": seed, **distribution(residual)}) + values.append(residual) + return rows, np.concatenate(values) + + +def cross_checkpoint_correlations(samples: dict[str, np.ndarray]) -> dict[str, Any]: + maps: dict[str, dict[str, float]] = defaultdict(dict) + metadata: dict[str, dict[str, int]] = {} + for checkpoint, key, residual, fold, seed in zip( + samples["checkpoint"], samples["sample_key"], samples["residual_z_m"], + samples["fold"], samples["coarse_seed"], strict=True, + ): + checkpoint = str(checkpoint) + maps[checkpoint][str(key)] = float(residual) + metadata[checkpoint] = {"fold": int(fold), "seed": int(seed)} + results = {} + checkpoints = sorted(maps) + for left_index, left in enumerate(checkpoints): + for right in checkpoints[left_index + 1:]: + overlap = sorted(set(maps[left]).intersection(maps[right])) + name = f"{left[:12]}_{right[:12]}" + if len(overlap) < 2: + results[name] = { + "status": "unavailable_no_overlapping_group_heldout_samples", + "overlap": len(overlap), + "pearson": None, + "left": {"checkpoint": left, **metadata[left]}, + "right": {"checkpoint": right, **metadata[right]}, + } + else: + x = np.asarray([maps[left][key] for key in overlap]) + y = np.asarray([maps[right][key] for key in overlap]) + results[name] = { + "status": "available", + "overlap": len(overlap), + "pearson": float(np.corrcoef(x, y)[0, 1]), + "left": {"checkpoint": left, **metadata[left]}, + "right": {"checkpoint": right, **metadata[right]}, + } + return results + + +def grouped_rows(samples: dict[str, np.ndarray]) -> list[dict[str, Any]]: + residual = samples["residual_z_m"] + groups: dict[str, np.ndarray] = { + "fold": samples["fold"].astype(str), + "checkpoint": samples["checkpoint"], + "side": samples["side"], + "subject": samples["subject"], + "action_family": samples["action_family"], + "take": samples["take"], + "hand_size": size_bucket(samples["hand_scale_px"]), + "wrist_depth": depth_bucket(samples["wrist_depth_m"]), + "local_depth_validity": validity_bucket(samples["local_depth_valid_fraction"]), + } + if np.all(samples["coarse_seed"] >= 0): + groups["coarse_seed"] = samples["coarse_seed"].astype(str) + rows = [{"source": "oof", "group": "all", "value": "all", **distribution(residual)}] + for field, values in groups.items(): + for value in sorted(set(values.tolist())): + rows.append({ + "source": "oof", "group": field, "value": value, + **distribution(residual[values == value]), + }) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--validation-a1-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("OOF audit refuses to overwrite outputs") + samples, manifests = load_oof_banks(args.bank_dir) + oof = distribution(samples["residual_z_m"]) + validation_rows, validation_values = validation_reference(args.validation_a1_root) + validation = distribution(validation_values) + quantiles = np.linspace(0.0, 1.0, 101) + quantile_l1_mm = float(np.mean(np.abs( + np.quantile(np.abs(samples["residual_z_m"]), quantiles) + - np.quantile(np.abs(validation_values), quantiles) + )) * 1000.0) + rows = grouped_rows(samples) + rows.extend({ + "source": "validation", "group": "seed", "value": row["seed"], + **{key: value for key, value in row.items() if key != "seed"}, + } for row in validation_rows) + rows.append({"source": "validation", "group": "all", "value": "all", **validation}) + tail_passed = bool(oof["p95_mm"] >= TAIL_ADMISSION_P95_MM) + report = { + "status": "passed" if tail_passed else "insufficient_oof_tail", + "experiment_class": "preregistered_data_admission_audit", + "residual_definition": "GT wrist z minus group-heldout coarse predicted wrist z", + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "folds": sorted({int(manifest["fold"]) for manifest in manifests}), + "checkpoints": sorted({str(manifest["checkpoint"]["sha256"]) for manifest in manifests}), + "coarse_seeds": sorted({ + int(manifest["seed"]) for manifest in manifests if manifest.get("seed") is not None + }), + "samples": len(samples["residual_z_m"]), + "takes": len(set(samples["take"].tolist())), + "oof": oof, + "validation_reference_by_seed": validation_rows, + "validation_reference_all": validation, + "absolute_residual_quantile_l1_distance_mm": quantile_l1_mm, + "tail_admission": { + "threshold_p95_mm": TAIL_ADMISSION_P95_MM, + "passed": tail_passed, + "rule": "do not fit a formal refiner if group-heldout OOF z P95 remains below 40 mm", + }, + "cross_checkpoint_pearson": cross_checkpoint_correlations(samples), + "leakage_audit_passed": all(manifest["leakage_audit"]["passed"] for manifest in manifests), + "official_validation_used_for_training_or_thresholds": False, + "official_test_used": False, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(json.dumps({ + "status": report["status"], "samples": report["samples"], "takes": report["takes"], + "oof": oof, "validation": validation, "official_test_used": False, + }, indent=2)) + if not tail_passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_periodic_checkpoints.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_periodic_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..d039ac0e31f689bff49638990e6f519f51a0a996 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_periodic_checkpoints.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Audit Phase 5 periodic checkpoints, logs, provenance, and validation contract.""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +from pathlib import Path + +import torch + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_tree(value: object) -> bool: + if torch.is_tensor(value): + return bool(torch.isfinite(value).all()) if value.is_floating_point() else True + if isinstance(value, dict): + return all(finite_tree(item) for item in value.values()) + if isinstance(value, (list, tuple)): + return all(finite_tree(item) for item in value) + return True + + +def audit_run(run_dir: Path, step: int, expected_validation_records: int) -> dict[str, object]: + checkpoint_path = run_dir / f"step_{step:07d}.pt" + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + checkpoint_record = { + "path": str(checkpoint_path.resolve()), + "bytes": checkpoint_path.stat().st_size, + "sha256": sha256(checkpoint_path), + "step": int(checkpoint["step"]), + "model_finite": finite_tree(checkpoint.get("model", {})), + "optimizer_finite": finite_tree(checkpoint.get("optimizer", {})), + } + del checkpoint + gc.collect() + + provenance = json.loads((run_dir / "run_provenance.json").read_text(encoding="utf-8")) + train_lines = [ + line for line in (run_dir / "train_metrics.jsonl").read_text(encoding="utf-8").splitlines() + if line.strip() + ] + last_train = json.loads(train_lines[-1]) if train_lines else {} + validation_path = run_dir / "validation.jsonl" + validation_rows = ( + [json.loads(line) for line in validation_path.read_text(encoding="utf-8").splitlines() if line.strip()] + if validation_path.is_file() else [] + ) + matching_validation = [row for row in validation_rows if int(row["step"]) == step] + finite_validation = finite_tree(matching_validation) + passed = ( + checkpoint_record["step"] == step + and checkpoint_record["model_finite"] + and checkpoint_record["optimizer_finite"] + and provenance.get("git_status") in ("", None) + and int(last_train.get("step", -1)) >= step + and len(matching_validation) == expected_validation_records + and finite_validation + ) + return { + "run": run_dir.name, + "status": "passed" if passed else "failed", + "checkpoint": checkpoint_record, + "git_commit": provenance.get("git_commit"), + "git_status_clean": provenance.get("git_status") in ("", None), + "train_manifest": provenance.get("hashes", {}).get("train_manifest"), + "config": provenance.get("hashes", {}).get("config"), + "last_train_step": last_train.get("step"), + "last_gradient_norm": last_train.get("gradient_norm"), + "last_frames_per_s": last_train.get("frames_per_s"), + "validation_records_at_step": len(matching_validation), + "expected_validation_records_at_step": expected_validation_records, + "validation_finite": finite_validation, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_root", type=Path) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--expected-runs", type=int, required=True) + parser.add_argument("--expected-validation-records", type=int, choices=(0, 1), required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite audit: {args.output}") + checkpoint_name = f"step_{args.step:07d}.pt" + run_dirs = sorted(path.parent for path in args.run_root.glob(f"*/{checkpoint_name}")) + if len(run_dirs) != args.expected_runs: + raise ValueError( + f"expected {args.expected_runs} {checkpoint_name} files, found {len(run_dirs)}" + ) + records = [ + audit_run(run_dir, args.step, args.expected_validation_records) + for run_dir in run_dirs + ] + passed = bool(records) and all(record["status"] == "passed" for record in records) + report = { + "status": "passed" if passed else "failed", + "expected_step": args.step, + "expected_runs": args.expected_runs, + "expected_validation_records_at_step": args.expected_validation_records, + "runs": records, + "official_test_used": False, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "runs": len(records), "output": str(args.output), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_residual_shift.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_residual_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..62c3bfe1f2b6ba39dc8a5cfb4b4c19d0c926de49 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase5_residual_shift.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Audit in-fold train versus held-out validation coarse z residual shift.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import numpy as np + + +SEEDS = (20260716, 20260717, 20260718) + + +def distribution(values_m: np.ndarray) -> dict[str, float | int]: + values_mm = np.asarray(values_m, dtype=np.float64) * 1000.0 + absolute = np.abs(values_mm) + p95 = float(np.percentile(absolute, 95)) + return { + "count": int(len(values_mm)), + "signed_mean_mm": float(values_mm.mean()), + "mae_mm": float(absolute.mean()), + "p50_mm": float(np.percentile(absolute, 50)), + "p90_mm": float(np.percentile(absolute, 90)), + "p95_mm": p95, + "p99_mm": float(np.percentile(absolute, 99)), + "cvar95_mm": float(absolute[absolute >= p95].mean()), + } + + +def load_rows(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def size_bucket(value: str) -> str: + size = float(value) + return "small" if size < 64.0 else "medium" if size < 128.0 else "large" + + +def depth_bucket(value: str) -> str: + depth = float(value) + return "near" if depth < 0.5 else "middle" if depth < 0.8 else "far" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--a1-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("residual-shift audit refuses to overwrite outputs") + + split_values: dict[str, dict[int, np.ndarray]] = {"train": {}, "validation": {}} + split_rows: dict[str, list[dict[str, str]]] = {} + summary_rows = [] + group_rows = [] + for split in split_values: + metadata_reference: list[tuple[str, str, str]] | None = None + for seed in SEEDS: + root = args.a1_root / f"seed_{seed}" / split + with np.load(root / "features.npz", allow_pickle=False) as archive: + values = archive["target_residual_z_m"].astype(np.float64) + rows = load_rows(root / "samples.csv") + if len(rows) != len(values): + raise ValueError(f"feature/metadata length mismatch for {split}/{seed}") + metadata = [(row["take"], row["frame_id"], row["side"]) for row in rows] + if metadata_reference is None: + metadata_reference = metadata + split_rows[split] = rows + elif metadata != metadata_reference: + raise ValueError(f"sample alignment differs across seeds for {split}") + split_values[split][seed] = values + result = distribution(values) + summary_rows.append({"split": split, "seed": seed, "group": "all", "value": "all", **result}) + + groups: dict[tuple[str, str], list[int]] = {} + for index, row in enumerate(rows): + values_by_group = { + "side": row["side"], + "action_family": row["action_family"], + "hand_size": size_bucket(row["hand_size_px"]), + "wrist_depth": depth_bucket(row["wrist_depth_m"]), + "take": row["take"], + } + for field, value in values_by_group.items(): + groups.setdefault((field, value), []).append(index) + for (field, value), indices in sorted(groups.items()): + group_rows.append({ + "split": split, "seed": seed, "group": field, "value": value, + **distribution(values[np.asarray(indices, dtype=np.int64)]), + }) + + correlations = {} + for split, by_seed in split_values.items(): + matrix = np.corrcoef([by_seed[seed] for seed in SEEDS]) + correlations[split] = { + f"{left}_{right}": float(matrix[left_index, right_index]) + for left_index, left in enumerate(SEEDS) + for right_index, right in enumerate(SEEDS) + if left_index < right_index + } + gaps = {} + for seed in SEEDS: + train = distribution(split_values["train"][seed]) + validation = distribution(split_values["validation"][seed]) + gaps[str(seed)] = { + "mae_ratio_validation_over_train": validation["mae_mm"] / train["mae_mm"], + "p95_ratio_validation_over_train": validation["p95_mm"] / train["p95_mm"], + "mae_gap_mm": validation["mae_mm"] - train["mae_mm"], + "p95_gap_mm": validation["p95_mm"] - train["p95_mm"], + } + report = { + "status": "audited", + "experiment_class": "diagnostic_existing_predictions", + "source": "Phase 4 A1 frozen coarse feature banks", + "residual_definition": "GT wrist z minus coarse predicted wrist z", + "seeds": list(SEEDS), + "summary": summary_rows, + "cross_seed_pearson": correlations, + "validation_over_train_gap": gaps, + "sample_alignment_across_seeds": True, + "official_test_used": False, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + rows_to_write = summary_rows + group_rows + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows_to_write[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows_to_write) + print(json.dumps({ + "status": report["status"], + "train": [row for row in summary_rows if row["split"] == "train"], + "validation": [row for row in summary_rows if row["split"] == "validation"], + "correlations": correlations, + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase6_sequence_inference.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase6_sequence_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e78513782072066d17259a1a4014e154227187ec --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase6_sequence_inference.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Audit a frozen checkpoint through the bounded arbitrary-length API.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import time +from collections import defaultdict +from pathlib import Path + +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def clone_batch(batch: dict[str, object]) -> dict[str, object]: + return { + key: value.clone() if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, required=True) + parser.add_argument("--frames", type=int, default=257) + parser.add_argument("--take") + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output must not already exist") + if args.manifest.name != "official_val.jsonl": + parser.error("sequence audit is hard-gated to official validation") + if args.frames < 1 or args.window < 1: + parser.error("frames and window must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + configured_mode = config["model"].get( + "temporal_attention_mode", "bidirectional", + ) + expected_mode = "causal" if args.mode == "causal" else "bidirectional" + if configured_mode != expected_mode: + parser.error("config temporal mode differs from requested audit mode") + + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (1,), (1,), + ) + by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + by_take[clip.take].append(index) + take = args.take + if take is None: + take = next((name for name, indices in by_take.items() if len(indices) >= args.frames), None) + if take is None or len(by_take.get(take, ())) < args.frames: + raise ValueError("no requested take contains the audit frame count") + indices = by_take[take][: args.frames] + + loader = DataLoader( + Subset(dataset, indices), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.mode, window_size=args.window, + offline_stride=(args.window // 2 if args.mode == "offline" else None), + ), + device=device, autocast_dtype=dtype, + ) + frame_ids: list[int] = [] + + def frames(): + for batch in loader: + frame_ids.append(int(batch["frame_id"][0, 0])) + yield batch + + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + output = runner.infer(frames()) + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + output_time = int(output["wrist_root_translation"].shape[1]) + finite = all(torch.isfinite(value).all() for value in output.values()) + + invariance = None + if args.mode == "causal": + invariant_loader = DataLoader( + Subset(dataset, indices[:8]), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ) + first = list(invariant_loader) + full = runner._stack_frames(first) + perturbed = clone_batch(full) + perturbed["rgb"][:, 4:] = -perturbed["rgb"][:, 4:] + perturbed["depth_m"][:, 4:] = 0 + perturbed["depth_pixel_valid"][:, 4:] = False + perturbed["depth_available"][:, 4:] = False + prefix = { + key: value[:, :4] if torch.is_tensor(value) and value.ndim >= 2 + and value.shape[1] == 8 else value + for key, value in full.items() + } + full = runner._to_device(full) + perturbed = runner._to_device(perturbed) + prefix = runner._to_device(prefix) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + full_output = model(full) + perturbed_output = model(perturbed) + prefix_output = model(prefix) + future_delta = float(( + full_output["wrist_root_translation"][:, :4] + - perturbed_output["wrist_root_translation"][:, :4] + ).abs().max()) + monolithic_prefix_delta = float(( + full_output["wrist_root_translation"][:, :4] + - prefix_output["wrist_root_translation"] + ).abs().max()) + stream_full = runner.infer_causal(first)["wrist_root_translation"][:, :4] + stream_prefix = runner.infer_causal(first[:4])["wrist_root_translation"] + prefix_delta = float((stream_full - stream_prefix).abs().max()) + invariance = { + "future_perturbation_max_abs_m": future_delta, + "future_perturbation_bitwise_zero": future_delta == 0.0, + "streaming_prefix_max_abs_m": prefix_delta, + "prefix_tolerance_m": 1e-6, + "prefix_passed": prefix_delta <= 1e-6, + "monolithic_full_vs_short_batch_max_abs_m": monolithic_prefix_delta, + "monolithic_batch_size_numerical_invariance": monolithic_prefix_delta <= 1e-6, + } + + invariance_passed = invariance is None or ( + invariance["future_perturbation_bitwise_zero"] and invariance["prefix_passed"] + ) + order_passed = len(frame_ids) == args.frames and all( + right > left for left, right in zip(frame_ids, frame_ids[1:]) + ) + memory_passed = ( + runner.maximum_resident_frames <= args.window + and runner.maximum_input_buffer_frames <= ( + args.window if args.mode == "causal" else args.window + args.window // 2 + ) + ) + report = { + "status": "passed" if ( + finite and output_time == args.frames and order_passed + and memory_passed and invariance_passed + ) else "failed", + "experiment": "P6_S5_length_generalized_inference", + "experiment_class": "frozen_checkpoint_engineering_audit", + "official_test_used": False, + "official_validation_used_for_selection": False, + "mode": args.mode, + "causal": args.mode == "causal", + "window": args.window, + "offline_stride": args.window // 2 if args.mode == "offline" else None, + "stitching": "center" if args.mode == "offline" else None, + "take": take, + "requested_frames": args.frames, + "output_frames": output_time, + "frame_ids_strictly_increasing": order_passed, + "finite": finite, + "elapsed_s": elapsed, + "throughput_fps": args.frames / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "maximum_gpu_window_frames": runner.maximum_resident_frames, + "maximum_cpu_input_buffer_frames": runner.maximum_input_buffer_frames, + "invariance": invariance, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": int(checkpoint["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if report["status"] != "passed": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase6_variable_length.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase6_variable_length.py new file mode 100644 index 0000000000000000000000000000000000000000..85097343ce2bb9177f32360d1e752196baa31a45 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase6_variable_length.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +"""Audit the frozen Phase 5 model's variable-length and causality contract.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import statistics +import subprocess +import time +from collections import defaultdict +from pathlib import Path +from typing import Any + +import torch +import yaml + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +LENGTHS = (1, 2, 4, 8, 16, 32, 64) +OUTPUT_KEYS = ( + "hand_tokens", "joint2d_norm", "mano_rotation_matrices", "mano_shape", + "wrist_root_translation", "joints_camera", "vertices_camera", +) +MODEL_INPUT_KEYS = ( + "rgb", "depth_m", "depth_pixel_valid", "K", "K_available", + "depth_available", "frame_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_model( + config: dict[str, Any], checkpoint: Path, device: torch.device, +) -> tuple[BimanualReconstructionModel, int]: + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(checkpoint, model, optimizer=None, map_location=device) + return model, int(state["step"]) + + +def contiguous_real_sequence( + root: Path, manifest: Path, resolution_hw: tuple[int, int], length: int, +) -> tuple[dict[str, torch.Tensor], str, list[int]]: + dataset = H2OCam4Dataset( + root, manifest, resolution_hw, clip_lengths=(1,), strides=(1,), + window_step=1, allow_partial=False, + ) + by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + by_take[clip.take].append(index) + selected: list[int] | None = None + selected_take = "" + for take, indices in by_take.items(): + frame_ids = [dataset.clips[index].frame_ids[0] for index in indices] + for start in range(0, len(indices) - length + 1): + candidate = frame_ids[start : start + length] + if all(right == left + 1 for left, right in zip(candidate[:-1], candidate[1:])): + selected = indices[start : start + length] + selected_take = take + break + if selected is not None: + break + if selected is None: + raise RuntimeError(f"no contiguous {length}-frame validation prefix") + samples = [dataset[index] for index in selected] + batch_frames = collate_h2o_clips(samples) + sequence = {} + for key in MODEL_INPUT_KEYS: + value = batch_frames[key] + if value.shape[0] != length or value.shape[1] != 1: + raise ValueError(f"unexpected T=1 collate shape for {key}: {value.shape}") + sequence[key] = value[:, 0].unsqueeze(0) + frame_ids = batch_frames["frame_id"][:, 0].tolist() + return sequence, selected_take, [int(value) for value in frame_ids] + + +def prefix(batch: dict[str, torch.Tensor], length: int, device: torch.device) -> dict[str, torch.Tensor]: + return {key: value[:, :length].to(device, non_blocking=True) for key, value in batch.items()} + + +def run_once( + model: BimanualReconstructionModel, + batch: dict[str, torch.Tensor], + dtype: torch.dtype, +) -> dict[str, Any]: + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + return model(batch) + + +def output_snapshot(output: dict[str, Any]) -> dict[str, torch.Tensor]: + return {key: output[key].detach().float().cpu() for key in OUTPUT_KEYS} + + +def max_prefix_differences( + left: dict[str, torch.Tensor], right: dict[str, torch.Tensor], length: int, +) -> dict[str, float]: + return { + key: float((left[key][:, :length] - right[key][:, :length]).abs().max()) + for key in OUTPUT_KEYS + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--repeats", type=int, default=2) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("variable-length audit is hard-gated to official validation") + if args.output.exists(): + parser.error("output must not exist") + if args.repeats < 1: + parser.error("repeats must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + real, take, frame_ids = contiguous_real_sequence( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), max(LENGTHS), + ) + model, step = build_model(config, args.checkpoint, device) + results = [] + snapshots: dict[int, dict[str, torch.Tensor]] = {} + for length in LENGTHS: + current = prefix(real, length, device) + run_once(model, current, dtype) + torch.cuda.synchronize(device) + torch.cuda.reset_peak_memory_stats(device) + latencies = [] + output: dict[str, Any] | None = None + repeats = args.repeats if length <= 16 else 1 + for _ in range(repeats): + start = time.perf_counter() + output = run_once(model, current, dtype) + torch.cuda.synchronize(device) + latencies.append(1000.0 * (time.perf_counter() - start)) + assert output is not None + snapshots[length] = output_snapshot(output) + temporal_attention = output["attention"]["temporal_attention"] + finite = { + key: bool(torch.isfinite(output[key]).all().item()) for key in OUTPUT_KEYS + } + results.append({ + "T": length, + "finite": finite, + "all_finite": all(finite.values()), + "hand_token_shape": list(output["hand_tokens"].shape), + "temporal_attention_shape": list(temporal_attention.shape), + "temporal_attention_elements": temporal_attention.numel(), + "temporal_attention_bytes": temporal_attention.numel() * temporal_attention.element_size(), + "latency_ms_p50": float(statistics.median(latencies)), + "latency_ms_samples": latencies, + "peak_allocated_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + }) + del output, current + torch.cuda.empty_cache() + print(f"T={length} complete", flush=True) + + base8 = prefix(real, 8, device) + changed8 = {key: value.clone() for key, value in base8.items()} + changed8["rgb"][:, 4:] = 1.0 - changed8["rgb"][:, 4:] + changed8["depth_m"][:, 4:] = 0.0 + changed8["depth_pixel_valid"][:, 4:] = False + changed8["depth_available"][:, 4:] = False + original8 = output_snapshot(run_once(model, base8, dtype)) + perturbed8 = output_snapshot(run_once(model, changed8, dtype)) + future_differences = max_prefix_differences(original8, perturbed8, 4) + prefix_differences = max_prefix_differences(snapshots[8], snapshots[4], 4) + window_comparisons = [] + reference = snapshots[64] + for length in LENGTHS: + first_joint_delta_mm = float( + torch.linalg.vector_norm( + snapshots[length]["joints_camera"][:, 0] + - reference["joints_camera"][:, 0], dim=-1, + ).mean() * 1000.0 + ) + window_comparisons.append({ + "T": length, + "first_frame_joint_delta_vs_T64_mm": first_joint_delta_mm, + "first_frame_wrist_max_delta_vs_T64_m": float( + (snapshots[length]["wrist_root_translation"][:, 0] + - reference["wrist_root_translation"][:, 0]).abs().max() + ), + }) + report = { + "status": "completed", + "experiment": "P6_S0_variable_length_contract", + "official_validation_used": True, + "official_validation_used_for_selection": False, + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + "device": args.gpu, + "take": take, + "frame_ids": frame_ids, + "forward_results": results, + "window_comparisons": window_comparisons, + "future_perturbation": { + "changed_frames": [4, 5, 6, 7], + "compared_frames": [0, 1, 2, 3], + "maximum_absolute_differences": future_differences, + "strict_zero_passed": all(value == 0.0 for value in future_differences.values()), + }, + "prefix_invariance": { + "prefix_T": 4, "full_T": 8, + "maximum_absolute_differences": prefix_differences, + "strict_zero_passed": all(value == 0.0 for value in prefix_differences.values()), + }, + "contract": { + "tensor_shape_variable_length": all(item["all_finite"] for item in results), + "offline_bidirectional_variable_length": True, + "bounded_memory_causal_streaming": False, + "historical_causal_description": "causal z-state postprocessor over noncausal T=8 coarse predictions", + }, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], + "future_strict_zero": report["future_perturbation"]["strict_zero_passed"], + "prefix_strict_zero": report["prefix_invariance"]["strict_zero_passed"], + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_arctic.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_arctic.py new file mode 100644 index 0000000000000000000000000000000000000000..782a56fcee3691d848037cb01ef48c6c9763b4c5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_arctic.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Deterministic numeric and visual audit for ARCTIC P2 train view 0.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + "max": float(array.max()), + } + + +def select_indices(rows: list[dict], count: int) -> list[int]: + recordings: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + recordings[(row["subject_id"], row["physical_recording_id"])].append(index) + strata: dict[str, list[int]] = defaultdict(list) + for (subject, _), indices in sorted(recordings.items()): + strata[subject].append(indices[len(indices) // 2]) + selected, cursor = [], 0 + while len(selected) < count: + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected.append(strata[subject][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) != count: + raise RuntimeError(f"only {len(selected)} subject/recording strata available") + return selected + + +def denormalize(image: torch.Tensor) -> np.ndarray: + value = image.permute(1, 2, 0).numpy() + return np.rint(np.clip((value * RGB_STD + RGB_MEAN) * 255.0, 0, 255)).astype(np.uint8) + + +def render(case: dict, output: Path) -> None: + image = case["image"].copy() + for side, color in enumerate(((40, 190, 250), (250, 100, 60))): + for point in case["joint2d"][side][case["joint_valid"][side]]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, color, -1) + cv2.putText( + image, f"{case['category']} {case['recording']}", (10, 24), + cv2.FONT_HERSHEY_SIMPLEX, .55, (255, 255, 255), 2, cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=16) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + dataset = ARCTICClipDataset(args.manifest, args.mano_root) + indices = select_indices(dataset.rows, args.clips) + enabled_regen, excluded_left, enabled_reprojection = [], [], [] + wrist_depth, hand_size, cases, hand_counts = [], [], [], [] + side_frames = {"left": 0, "right": 0} + root_relative_side_frames = {"left": 0, "right": 0} + root_relative_root_norm_mm: list[float] = [] + for index in indices: + sample = dataset[index] + enabled_regen.extend(sample["source_vertex_regen_error_mm"][sample["vertices_valid"]].tolist()) + left = sample["translation_valid"][:, 0] + excluded_left.extend(sample["source_vertex_regen_error_mm"][:, 0][left].tolist()) + for side_index, side in enumerate(("left", "right")): + valid = sample["joint3d_root_relative_valid"][:, side_index] + root_relative_side_frames[side] += int(valid.any(dim=-1).sum()) + root_relative_root_norm_mm.extend( + (torch.linalg.vector_norm( + sample["joint3d_root_relative"][:, side_index, 0], dim=-1, + )[valid[:, 0]] * 1000.0).tolist() + ) + enabled_reprojection.extend( + sample["projection_roundtrip_error_px"][sample["reprojection_valid"]].tolist() + ) + for frame in range(len(sample["frame_valid"])): + valid_hands = sample["translation_valid"][frame] + hand_counts.append(int(valid_hands.sum())) + sizes = [] + for side_index, side in enumerate(("left", "right")): + if not valid_hands[side_index]: + continue + side_frames[side] += 1 + wrist_depth.append(float(sample["wrist_root_translation"][frame, side_index, 2])) + points = sample["joint2d"][frame, side_index][sample["joint2d_valid"][frame, side_index]] + if len(points): + sizes.append(float((points.max(0).values - points.min(0).values).max())) + hand_size.extend(sizes) + points = sample["joint2d"][frame][sample["joint2d_valid"][frame]] + height, width = sample["rgb"].shape[-2:] + border = ( + float(torch.stack((points[:, 0], points[:, 1], width - points[:, 0], height - points[:, 1])).amin()) + if len(points) else float("inf") + ) + z = sample["wrist_root_translation"][frame, valid_hands, 2] + cases.append({ + "recording": sample["physical_recording_id"], + "image": denormalize(sample["rgb"][frame]), + "joint2d": sample["joint2d"][frame].numpy(), + "joint_valid": sample["joint2d_valid"][frame].numpy(), + "count": int(valid_hands.sum()), + "z": float(z.mean()) if len(z) else float("nan"), + "size": max(sizes, default=0.0), "border": border, + }) + valid_cases = [row for row in cases if row["count"] > 0] + selectors = { + "near": min(valid_cases, key=lambda row: row["z"]), + "far": max(valid_cases, key=lambda row: row["z"]), + "small": min(valid_cases, key=lambda row: row["size"]), + "border": min(valid_cases, key=lambda row: row["border"]), + "bimanual": next(row for row in valid_cases if row["count"] == 2), + } + single = next((row for row in valid_cases if row["count"] == 1), None) + if single is not None: + selectors["single"] = single + visuals = {} + for category, value in selectors.items(): + path = args.output_dir / f"{category}.png" + render(dict(value, category=category), path) + visuals[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + report = { + "status": "pending", "official_test_used": False, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clips": len(indices), "frames": len(cases), "clip_indices": indices, + "side_frames": side_frames, + "no_visible_hand_frames": hand_counts.count(0), + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "source_regeneration_mm": quantiles(enabled_regen), + "enabled_reprojection_roundtrip_px": quantiles(enabled_reprojection), + "excluded_left_geometry_regeneration_mm": quantiles(excluded_left), + "wrist_depth_m": quantiles(wrist_depth), + "projected_hand_size_px": quantiles(hand_size), + "image_contract": "full 840x600 ego view (0.3x 2800x2000), cv2 undistort with scaled K/dist8, then full-frame resize/pad", + "partial_supervision_contract": { + "right": "2D/3D/translation/pose/shape/vertices/reprojection", + "left": "direct-2D/translation/pose only", + }, + "source_compatible_root_relative_joint3d": { + "side_frames": root_relative_side_frames, + "root_norm_mm": quantiles(root_relative_root_norm_mm), + "shape_vertices_enabled": False, + "claim": "source-compatible legacy MANO joint target only; not corrected-MANO regeneration", + }, + "visualizations": visuals, + } + passed = ( + len(cases) >= 100 and report["source_regeneration_mm"]["max"] < 1.0 + and report["enabled_reprojection_roundtrip_px"]["p95"] < 1.0 + and all(value > 0 for value in side_frames.values()) + and all(value > 0 for value in root_relative_side_frames.values()) + and report["source_compatible_root_relative_joint3d"]["root_norm_mm"]["max"] < 1e-4 + and report["bimanual_frames"] > 0 + ) + report["status"] = "passed" if passed else "failed" + (args.output_dir / "audit.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_egodexter.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_egodexter.py new file mode 100644 index 0000000000000000000000000000000000000000..acd74ce8142f1d6b95335fba94e4dbd155454225 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_egodexter.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Deterministic no-model EgoDexter source audit for Phase 7.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path + +import numpy as np + +from foundation_hand.data.egodexter_dataset import EgoDexterSequenceDataset, SEQUENCES + + +def finite_summary(values: np.ndarray) -> dict[str, float | int]: + values = values[np.isfinite(values)] + return { + "count": int(len(values)), + "median": float(np.median(values)), + "p95": float(np.quantile(values, .95)), + "max": float(values.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--decode-frames-per-sequence", type=int, default=25) + args = parser.parse_args() + if args.decode_frames_per_sequence < 1: + parser.error("--decode-frames-per-sequence must be positive") + report: dict[str, object] = { + "status": "numeric_adapter_passed_handedness_freeze_pending", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "dataset": "EgoDexter", + "training_or_selection_use": False, + "official_test_used": False, + "camera_frame": "depth_camera", + "depth_units_input": "millimeters", + "model_units": "meters", + "rgb_stream": "color_on_depth full frame", + "input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "sequence_handedness": "must be frozen before first model inference", + "sequences": {}, + } + total_frames = 0 + total_visible = 0 + total_annotated = 0 + for sequence in SEQUENCES: + dataset = EgoDexterSequenceDataset(args.root, sequence, hand_side="left") + xyz = dataset.fingertips_3d_m + valid = np.linalg.norm(xyz, axis=-1) > 0.0 + uv = np.full_like(xyz[..., :2], np.nan) + uv[..., 0] = ( + dataset.K_source[0, 0] * xyz[..., 0] + / np.where(valid, xyz[..., 2], np.nan) + dataset.K_source[0, 2] + ) + uv[..., 1] = ( + dataset.K_source[1, 1] * xyz[..., 1] + / np.where(valid, xyz[..., 2], np.nan) + dataset.K_source[1, 2] + ) + error = np.linalg.norm(uv - dataset.fingertips_2d, axis=-1)[valid] + sample_indices = np.linspace( + 0, len(dataset) - 1, + min(args.decode_frames_per_sequence, len(dataset)), dtype=np.int64, + ) + depth_valid_fraction = [] + for index in sample_indices: + _, depth_mm, _ = dataset._load(int(index)) + depth_valid_fraction.append(float((depth_mm > 0).mean())) + lines = (dataset.sequence_root / "annotation.txt_3D.txt").read_text( + encoding="utf-8", + ).splitlines() + sequence_report = { + "frames": len(dataset), + "visible_fingertips": int(valid.sum()), + "annotated_frames": int(np.any(valid, axis=1).sum()), + "partial_annotation_rows": sum( + len([group for group in line.split(";") if group.strip()]) < 5 + for line in lines + ), + "projection_roundtrip_px": finite_summary(error), + "decoded_frames": len(sample_indices), + "depth_valid_fraction_mean": float(np.mean(depth_valid_fraction)), + } + report["sequences"][sequence] = sequence_report + total_frames += len(dataset) + total_visible += int(valid.sum()) + total_annotated += int(np.any(valid, axis=1).sum()) + report["totals"] = { + "frames": total_frames, + "visible_fingertips": total_visible, + "annotated_frames": total_annotated, + "decoded_numeric_audit_frames": args.decode_frames_per_sequence * len(SEQUENCES), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_hoi4d.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_hoi4d.py new file mode 100644 index 0000000000000000000000000000000000000000..db2cfc39662dcb4bb7473cb83d81701c37149f39 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_hoi4d.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Deterministic numeric and visual audit of the Phase 7 HOI4D adapter.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + "max": float(array.max()), + } + + +def select_indices(rows: list[dict], count: int) -> list[int]: + strata: dict[tuple[str, str], list[int]] = {} + seen: set[str] = set() + for index, row in enumerate(rows): + side_sets = [set(value) for value in row["hand_sides"]] + hand_class = ( + "bimanual" if any(len(value) == 2 for value in side_sets) else + "left" if any("left" in value for value in side_sets) else "right" + ) + key = (row["subject_id"], hand_class) + if row["physical_recording_id"] in seen: + continue + seen.add(row["physical_recording_id"]) + strata.setdefault(key, []).append(index) + selected: list[int] = [] + keys = sorted(strata) + cursor = 0 + while len(selected) < count: + progress = False + for key in keys: + if cursor < len(strata[key]): + selected.append(strata[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) != count: + raise RuntimeError(f"only {len(selected)} stratified clips found") + return selected + + +def denormalize(image: torch.Tensor) -> np.ndarray: + value = image.permute(1, 2, 0).numpy() + return np.rint(np.clip((value * RGB_STD + RGB_MEAN) * 255.0, 0, 255)).astype(np.uint8) + + +def render(case: dict, output: Path) -> None: + image = case["image"].copy() + colors = ((40, 190, 250), (250, 100, 60)) + for side in range(2): + for point in case["joint2d"][side][case["joint_valid"][side]]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, colors[side], -1) + depth = case["depth"] + valid = depth > 0 + depth_color = np.zeros((*depth.shape, 3), dtype=np.uint8) + if valid.any(): + scale = np.quantile(depth[valid], .95) + normalized = np.clip(depth / max(scale, 1e-6), 0, 1) + depth_color = cv2.applyColorMap( + np.rint(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO, + )[..., ::-1] + depth_color[~valid] = 0 + combined = np.concatenate((image, depth_color), axis=1) + cv2.putText( + combined, f"{case['category']} {case['recording']}", (10, 24), + cv2.FONT_HERSHEY_SIMPLEX, .55, (255, 255, 255), 2, cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(combined, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=16) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + dataset = HOI4DClipDataset(args.root, args.manifest, args.mano_root) + indices = select_indices(dataset.rows, args.clips) + projection, regeneration, incompatible_left, depth_fraction, wrist_depth, hand_size = [], [], [], [], [], [] + cases: list[dict] = [] + side_frames = {"left": 0, "right": 0} + root_relative_side_frames = {"left": 0, "right": 0} + root_relative_root_norm_mm: list[float] = [] + hand_counts: list[int] = [] + for index in indices: + sample = dataset[index] + projection.extend(sample["projection_roundtrip_error_px"][sample["joint2d_valid"]].tolist()) + regeneration.extend(sample["source_vertex_regen_error_mm"][sample["vertices_valid"]].tolist()) + left_present = sample["translation_valid"][:, 0] + incompatible_left.extend(sample["source_vertex_regen_error_mm"][:, 0][left_present].tolist()) + for side_index, side in enumerate(("left", "right")): + valid = sample["joint3d_root_relative_valid"][:, side_index] + root_relative_side_frames[side] += int(valid.any(dim=-1).sum()) + root_relative_root_norm_mm.extend( + (torch.linalg.vector_norm( + sample["joint3d_root_relative"][:, side_index, 0], dim=-1, + )[valid[:, 0]] * 1000.0).tolist() + ) + for frame in range(len(sample["frame_valid"])): + valid_hands = sample["translation_valid"][frame] + hand_counts.append(int(valid_hands.sum())) + for side_index, side in enumerate(("left", "right")): + if valid_hands[side_index]: + side_frames[side] += 1 + wrist_depth.append(float(sample["wrist_root_translation"][frame, side_index, 2])) + points = sample["joint2d"][frame, side_index][sample["joint2d_valid"][frame, side_index]] + extent = points.max(0).values - points.min(0).values + hand_size.append(float(extent.max())) + depth_fraction.append(float(sample["depth_pixel_valid"][frame].float().mean())) + points = sample["joint2d"][frame][sample["joint2d_valid"][frame]] + height, width = sample["rgb"].shape[-2:] + border = min( + torch.stack((points[:, 0], points[:, 1], width - points[:, 0], height - points[:, 1])).amin().item() + if len(points) else float("inf"), + 1e9, + ) + cases.append({ + "recording": sample["physical_recording_id"], + "image": denormalize(sample["rgb"][frame]), + "depth": sample["depth_m"][frame, 0].numpy(), + "joint2d": sample["joint2d"][frame].numpy(), + "joint_valid": sample["joint2d_valid"][frame].numpy(), + "count": int(valid_hands.sum()), + "z": float(sample["wrist_root_translation"][frame, valid_hands, 2].mean()), + "size": max([ + float((sample["joint2d"][frame, side][sample["joint2d_valid"][frame, side]].max(0).values - sample["joint2d"][frame, side][sample["joint2d_valid"][frame, side]].min(0).values).max()) + for side in range(2) if sample["joint2d_valid"][frame, side].any() + ], default=0.0), + "border": border, + }) + selectors = { + "near": min(cases, key=lambda row: row["z"]), + "far": max(cases, key=lambda row: row["z"]), + "small": min(cases, key=lambda row: row["size"]), + "border": min(cases, key=lambda row: row["border"]), + "single": next(row for row in cases if row["count"] == 1), + "bimanual": next(row for row in cases if row["count"] == 2), + } + visuals = {} + for category, value in selectors.items(): + case = dict(value, category=category) + path = args.output_dir / f"{category}.png" + render(case, path) + visuals[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + report = { + "status": "pending", + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clip_indices": indices, + "clips": len(indices), "frames": len(cases), + "side_frames": side_frames, + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "projection_roundtrip_px": quantiles(projection), + "source_regeneration_mm": quantiles(regeneration), + "excluded_left_geometry_regeneration_mm": quantiles(incompatible_left), + "partial_supervision_contract": { + "right": "2D/3D/translation/pose/shape/vertices/reprojection", + "left": "direct-2D/translation/pose only", + "reason": "historical HOI4D MANO-left shapedirs cannot regenerate under corrected HOT3D/SMPL-X convention within 1 mm", + }, + "source_compatible_root_relative_joint3d": { + "side_frames": root_relative_side_frames, + "root_norm_mm": quantiles(root_relative_root_norm_mm), + "shape_vertices_enabled": False, + "claim": "source-compatible legacy MANO joint target only; not corrected-MANO regeneration", + }, + "depth_valid_fraction": quantiles(depth_fraction), + "wrist_depth_m": quantiles(wrist_depth), + "projected_hand_size_px": quantiles(hand_size), + "rgb_depth_sync": "same released aligned frame index decoded from both streams", + "depth_decode": "FFmpeg gray16le retained; millimeters converted to meters", + "visualizations": visuals, + "official_test_used": False, + } + passed = ( + len(cases) >= 100 and report["projection_roundtrip_px"]["median"] < .5 + and report["projection_roundtrip_px"]["p95"] < 1.0 + and report["source_regeneration_mm"]["max"] < 1.0 + and all(value > 0 for value in side_frames.values()) + and all(value > 0 for value in root_relative_side_frames.values()) + and report["source_compatible_root_relative_joint3d"]["root_norm_mm"]["max"] < 1e-4 + and report["single_hand_frames"] > 0 and report["bimanual_frames"] > 0 + ) + report["status"] = "passed" if passed else "failed" + (args.output_dir / "audit.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_hot3d.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_hot3d.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb6e7fdb573f9f019252e1e8a5aab2b5086a635 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase7_hot3d.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Deterministic HOT3D numeric and full-frame visualization audit.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def select_clip_indices(rows: list[dict], count: int) -> list[int]: + strata: dict[tuple[str, str], list[int]] = {} + seen_recordings: set[tuple[str, str, str]] = set() + for index, row in enumerate(rows): + hand_class = "single" if min(row.get("hand_count", [2])) == 1 else "bimanual" + key = (row["headset"], hand_class) + recording_key = (row["headset"], hand_class, row["recording_id"]) + if recording_key in seen_recordings: + continue + seen_recordings.add(recording_key) + strata.setdefault(key, []).append(index) + ordered_keys = sorted(strata) + selected: list[int] = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in ordered_keys: + values = strata[key] + if cursor < len(values): + selected.append(values[cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) < count: + raise RuntimeError(f"only {len(selected)} stratified clips available") + return selected + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), + "mean": float(array.mean()), + "median": float(np.median(array)), + "p95": float(np.quantile(array, 0.95)), + "max": float(array.max()), + } + + +def denormalize(rgb: torch.Tensor) -> np.ndarray: + image = rgb.permute(1, 2, 0).cpu().numpy() + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def render_case(case: dict, output: Path) -> None: + image = case["image"].copy() + colors = ((40, 190, 250), (250, 100, 60)) + for side in range(2): + valid = case["joint_valid"][side] + for point in case["joint2d"][side][valid]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, colors[side], -1) + cv2.putText( + image, + f"{case['category']} {case['recording']} {case['stream']}", + (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2, + cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=13) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + dataset = HOT3DClipDataset( + args.root, args.manifest, args.toolkit_root, args.mano_root, + K_input_dropout=0.3, dropout_seed=20260717, + ) + indices = select_clip_indices(dataset.rows, args.clips) + projection_errors: list[float] = [] + regeneration_errors: list[float] = [] + wrist_depths: list[float] = [] + hand_sizes: list[float] = [] + hand_counts: list[int] = [] + hand_sync_ms: list[float] = [] + headset_sync_ms: list[float] = [] + frame_cases: list[dict] = [] + headset_counts: dict[str, int] = {} + K_keep: list[bool] = [] + for index in indices: + sample = dataset[(index, 0)] + headset_counts[sample["headset_id"]] = headset_counts.get(sample["headset_id"], 0) + int(sample["frame_valid"].sum()) + projection_errors.extend(sample["projection_roundtrip_error_px"][torch.isfinite(sample["projection_roundtrip_error_px"])].tolist()) + regeneration_errors.extend(sample["source_vertex_regen_error_mm"][sample["translation_valid"]].tolist()) + hand_sync_ms.extend((sample["hand_pose_time_delta_ns"].abs() / 1e6).tolist()) + headset_sync_ms.extend((sample["headset_time_delta_ns"].abs() / 1e6).tolist()) + K_keep.append(bool(sample["K_input_available"][0])) + for frame_index in range(int(sample["frame_valid"].sum())): + valid_hands = sample["translation_valid"][frame_index] + hand_counts.append(int(valid_hands.sum())) + joint_valid = sample["joint2d_valid"][frame_index] + for side in range(2): + if not valid_hands[side]: + continue + wrist_depths.append(float(sample["wrist_root_translation"][frame_index, side, 2])) + points = sample["joint2d"][frame_index, side][joint_valid[side]] + if len(points): + extent = points.max(0).values - points.min(0).values + hand_sizes.append(float(extent.max())) + points_all = sample["joint2d"][frame_index][joint_valid] + if len(points_all): + h, w = sample["rgb"].shape[-2:] + border = torch.stack((points_all[:, 0], points_all[:, 1], w - points_all[:, 0], h - points_all[:, 1])).amin().item() + else: + border = float("inf") + valid_depth = sample["wrist_root_translation"][frame_index, :, 2][valid_hands] + frame_cases.append({ + "recording": sample["physical_recording_id"], + "stream": sample["stream_id"], + "image": denormalize(sample["rgb"][frame_index]), + "joint2d": sample["joint2d"][frame_index].cpu().numpy(), + "joint_valid": joint_valid.cpu().numpy(), + "hand_count": int(valid_hands.sum()), + "depth": float(valid_depth.mean()) if len(valid_depth) else float("nan"), + "border": float(border), + "size": float(max( + [ + (sample["joint2d"][frame_index, side][joint_valid[side]].max(0).values - sample["joint2d"][frame_index, side][joint_valid[side]].min(0).values).max().item() + for side in range(2) if joint_valid[side].any() + ], default=0.0, + )), + }) + + selectors = { + "near": lambda rows: min(rows, key=lambda row: row["depth"]), + "far": lambda rows: max(rows, key=lambda row: row["depth"]), + "border": lambda rows: min(rows, key=lambda row: row["border"]), + "small": lambda rows: min(rows, key=lambda row: row["size"]), + "single": lambda rows: next(row for row in rows if row["hand_count"] == 1), + "bimanual": lambda rows: next(row for row in rows if row["hand_count"] == 2), + } + visualizations = {} + for category, selector in selectors.items(): + case = dict(selector(frame_cases)) + case["category"] = category + path = args.output_dir / f"{category}.png" + render_case(case, path) + visualizations[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + audit = { + "status": "passed", + "official_test_used": False, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clip_indices": indices, + "clips": len(indices), + "frames": len(frame_cases), + "headset_frame_counts": headset_counts, + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "projection_roundtrip_px": quantiles(projection_errors), + "source_regeneration_mm": quantiles(regeneration_errors), + "hand_pose_sync_ms": quantiles(hand_sync_ms), + "headset_sync_ms": quantiles(headset_sync_ms), + "wrist_depth_m": quantiles(wrist_depths), + "projected_hand_size_px": quantiles(hand_sizes), + "K_input_kept_clips": int(sum(K_keep)), + "K_input_dropped_clips": int(len(K_keep) - sum(K_keep)), + "visualizations": visualizations, + } + passed = ( + audit["frames"] >= 100 + and audit["projection_roundtrip_px"]["median"] < 0.5 + and audit["projection_roundtrip_px"]["p95"] < 1.0 + and audit["source_regeneration_mm"]["max"] < 1.0 + and audit["single_hand_frames"] > 0 + and audit["bimanual_frames"] > 0 + ) + audit["status"] = "passed" if passed else "failed" + output = args.output_dir / "audit.json" + output.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") + print(json.dumps(audit, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase9_resolution_cache.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase9_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..440147147d411ed3f266dfde7363c9c87e5f944f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase9_resolution_cache.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Audit true-source Phase 9 resolution caches and train-only folds.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +EXPECTED_HW = (512, 896) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def source_index_digest(rows: list[dict[str, Any]]) -> str: + values = [int(row["source_clip_index"]) for row in rows] + payload = json.dumps(values, separators=(",", ":")).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def projection_error_px(archive: np.lib.npyio.NpzFile) -> float: + xyz = archive["joint3d_camera"] + target = archive["joint2d"] + intrinsics = archive["K"] + z = xyz[..., 2] + projected = np.empty_like(target) + projected[..., 0] = ( + intrinsics[:, None, None, 0, 0] * xyz[..., 0] / z + + intrinsics[:, None, None, 0, 2] + ) + projected[..., 1] = ( + intrinsics[:, None, None, 1, 1] * xyz[..., 1] / z + + intrinsics[:, None, None, 1, 2] + ) + valid = ( + archive["reprojection_valid"].astype(bool) + & archive["joint3d_valid"].astype(bool) + & np.isfinite(projected).all(axis=-1) + & (z > 1e-6) + ) + if not valid.any(): + return 0.0 + return float(np.linalg.norm(projected[valid] - target[valid], axis=-1).max()) + + +def audit_payload(path: Path) -> dict[str, Any]: + with np.load(path, allow_pickle=False) as archive: + if tuple(int(value) for value in archive["image_hw"].reshape(-1)) != EXPECTED_HW: + raise ValueError(f"payload resolution differs: {path}") + if archive["rgb_u8"].shape != (8, *EXPECTED_HW, 3): + raise ValueError(f"RGB shape differs: {path}") + if archive["depth_m"].shape != (8, 1, *EXPECTED_HW): + raise ValueError(f"depth shape differs: {path}") + if archive["depth_pixel_valid"].shape != (8, 1, *EXPECTED_HW): + raise ValueError(f"depth validity shape differs: {path}") + valid_depth = archive["depth_pixel_valid"].astype(bool) + depth = archive["depth_m"] + if valid_depth.any() and ( + not np.isfinite(depth[valid_depth]).all() + or not (depth[valid_depth] > 0).all() + ): + raise ValueError(f"valid depth contains nonpositive/nonfinite values: {path}") + intrinsics = archive["K"] + if ( + intrinsics.shape != (8, 3, 3) + or not np.isfinite(intrinsics).all() + or not (intrinsics[:, 0, 0] > 0).all() + or not (intrinsics[:, 1, 1] > 0).all() + or not np.allclose(intrinsics[:, 2], (0.0, 0.0, 1.0), atol=1e-6) + ): + raise ValueError(f"intrinsics contract differs: {path}") + error = projection_error_px(archive) + if error > 1.0: + raise ValueError(f"projection error exceeds 1 px ({error}): {path}") + return { + "path": str(path.resolve()), + "projection_error_max_px": error, + "depth_valid_fraction": float(valid_depth.mean()), + } + + +def audit_cache(item: dict[str, Any]) -> dict[str, Any]: + report_path = Path(item["report"]) + manifest_path = Path(item["manifest"]) + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or tuple(report.get("resolution_hw", ())) != EXPECTED_HW + or report.get("source_manifest", {}).get("sha256") + != item["source_manifest_sha256"] + or report.get("cache_manifest", {}).get("sha256") != sha256(manifest_path) + or report.get("resume_invocation") is not True + ): + raise ValueError(f"cache report contract differs: {item['id']}") + rows = read_jsonl(manifest_path) + if ( + len(rows) != int(item["clips"]) + or len({int(row["source_clip_index"]) for row in rows}) != len(rows) + or {row.get("dataset_id") for row in rows} != {item["dataset"]} + or any(tuple(row.get("resolution_hw", ())) != EXPECTED_HW for row in rows) + ): + raise ValueError(f"cache manifest contract differs: {item['id']}") + if item.get("recordings") is not None and len({ + row["physical_recording_id"] for row in rows + }) != int(item["recordings"]): + raise ValueError(f"recording count differs: {item['id']}") + control_rows = read_jsonl(Path(item["control_manifest"])) + if [row["source_clip_index"] for row in rows] != [ + row["source_clip_index"] for row in control_rows + ]: + raise ValueError(f"source clip selection differs from 640 control: {item['id']}") + payload_bytes = 0 + for row in rows: + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"payload hash differs: {path}") + payload_bytes += path.stat().st_size + samples = [audit_payload(Path(rows[index]["cache_path"])) for index in { + 0, len(rows) // 2, len(rows) - 1, + }] + return { + "id": item["id"], + "dataset": item["dataset"], + "clips": len(rows), + "recordings": len({row["physical_recording_id"] for row in rows}), + "manifest": str(manifest_path.resolve()), + "manifest_sha256": sha256(manifest_path), + "source_index_sha256": source_index_digest(rows), + "control_source_index_sha256": source_index_digest(control_rows), + "payload_bytes": payload_bytes, + "all_payload_sha256_verified": True, + "samples": samples, + } + + +def audit_sidecar(item: dict[str, Any]) -> dict[str, Any]: + report = json.loads(Path(item["report"]).read_text(encoding="utf-8")) + base_rows = read_jsonl(Path(item["base_manifest"])) + rows = read_jsonl(Path(item["manifest"])) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("base_cache_manifest", {}).get("sha256") + != sha256(item["base_manifest"]) + or report.get("augmented_cache_manifest", {}).get("sha256") + != sha256(item["manifest"]) + or report.get("right_valid_joint_count") != 0 + or float(report.get("root_norm_max_mm", math.inf)) >= 1e-4 + or report.get("shape_supervision_restored") is not False + or report.get("vertices_supervision_restored") is not False + or report.get("camera_joint3d_supervision_restored") is not False + or len(rows) != len(base_rows) + ): + raise ValueError(f"sidecar report contract differs: {item['id']}") + for base, row in zip(base_rows, rows, strict=True): + if ( + row["source_clip_index"] != base["source_clip_index"] + or row["cache_path"] != base["cache_path"] + or row["cache_sha256"] != base["cache_sha256"] + or row.get("joint3d_root_relative_scope") != "historical_left_only" + or sha256(row["joint3d_root_relative_sidecar_path"]) + != row["joint3d_root_relative_sidecar_sha256"] + ): + raise ValueError(f"sidecar row binding differs: {item['id']}") + return { + "id": item["id"], + "clips": len(rows), + "manifest_sha256": sha256(item["manifest"]), + "left_hand_frames": report["left_hand_frames"], + "all_sidecar_sha256_verified": True, + } + + +def audit_multifold(item: dict[str, Any], h2o_rows: list[dict[str, Any]]) -> dict[str, Any]: + index = json.loads(Path(item["index"]).read_text(encoding="utf-8")) + rebuild = json.loads(Path(item["rebuild_index"]).read_text(encoding="utf-8")) + if ( + index.get("status") != "complete" + or index.get("official_test_used") is not False + or index.get("h2o_official_validation_used") is not False + or index.get("source_cache_manifest", {}).get("sha256") + != sha256(item["source_manifest"]) + or len(index.get("folds", [])) != 6 + ): + raise ValueError("resolution multifold index contract differs") + if ( + rebuild.get("status") != "complete" + or rebuild.get("official_test_used") is not False + or rebuild.get("h2o_official_validation_used") is not False + or rebuild.get("source_cache_manifest", {}).get("sha256") + != index["source_cache_manifest"]["sha256"] + or [fold["id"] for fold in rebuild.get("folds", [])] + != [fold["id"] for fold in index["folds"]] + or [ + (fold["train"]["sha256"], fold["heldout"]["sha256"]) + for fold in rebuild["folds"] + ] != [ + (fold["train"]["sha256"], fold["heldout"]["sha256"]) + for fold in index["folds"] + ] + ): + raise ValueError("resolution multifold deterministic rebuild differs") + base_groups = {row["physical_recording_id"] for row in h2o_rows} + fold_audits = [] + for fold in index["folds"]: + train = read_jsonl(Path(fold["train"]["path"])) + heldout = read_jsonl(Path(fold["heldout"]["path"])) + train_groups = {row["physical_recording_id"] for row in train} + heldout_groups = {row["physical_recording_id"] for row in heldout} + if ( + train_groups & heldout_groups + or train_groups | heldout_groups != base_groups + or len(train) + len(heldout) != len(h2o_rows) + or sha256(fold["train"]["path"]) != fold["train"]["sha256"] + or sha256(fold["heldout"]["path"]) != fold["heldout"]["sha256"] + ): + raise ValueError(f"resolution multifold leakage/binding differs: {fold['id']}") + fold_audits.append({ + "id": fold["id"], "train_clips": len(train), + "heldout_clips": len(heldout), "group_overlap": 0, + }) + return { + "folds": fold_audits, + "physical_recording_isolation": True, + "deterministic_rebuild_hashes_match": True, + } + + +def audit(plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution execution plan lacks official-data isolation") + caches = [audit_cache(item) for item in plan["caches"]] + cache_by_id = {item["id"]: item for item in plan["caches"]} + h2o_rows = read_jsonl(Path(cache_by_id["h2o_train"]["manifest"])) + sidecars = [audit_sidecar(item) for item in plan["sidecars"]] + multifold = audit_multifold(plan["multifold"], h2o_rows) + return { + "schema_version": "phase9_resolution_cache_audit_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "resolution_hw": list(EXPECTED_HW), + "caches": caches, + "sidecars": sidecars, + "multifold": multifold, + "official_test_used": False, + "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("audit output must be new") + result = audit(json.loads(args.plan.read_text(encoding="utf-8"))) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase9_selection_bindings.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase9_selection_bindings.py new file mode 100644 index 0000000000000000000000000000000000000000..7a41a0a543656c690e7a0853f340aaabd6a65cac --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase9_selection_bindings.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Audit every fold report consumed by the frozen Phase 9 selection.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.summarize_phase9_unified_selection import ( + CANDIDATES, + evaluation, + validate_multifold_index, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def json_sha256(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def candidate_records() -> list[tuple[str, str, str]]: + records = [] + for mixture, candidates in CANDIDATES.items(): + for _, fold_checkpoint_id in candidates: + for fold in ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + ): + records.append((mixture, fold_checkpoint_id, fold)) + return records + + +def evaluation_path( + *, fold_final_root: Path, fold_milestone_root: Path, + condition: str, checkpoint_id: str, +) -> Path: + if checkpoint_id == "final": + return fold_final_root / condition / "rgb_d_k" / "evaluation.json" + return ( + fold_milestone_root / condition / checkpoint_id + / "rgb_d_k" / "evaluation.json" + ) + + +def file_binding(record: dict[str, Any], key: str) -> dict[str, Any]: + binding = record.get(key, {}) + path = Path(str(binding.get("path", ""))) + declared = str(binding.get("sha256", "")) + exists = path.is_file() + actual = sha256(path) if exists else None + return { + "path": str(path), + "declared_sha256": declared, + "actual_sha256": actual, + "exists": exists, + "sha256_matches": exists and declared == actual, + } + + +def artifact_binding(report: dict[str, Any], key: str) -> dict[str, Any]: + binding = report.get(key, {}) + path = Path(str(binding.get("path", ""))) + declared = str(binding.get("sha256", "")) + exists = path.is_file() + actual = sha256(path) if exists else None + return { + "path": str(path), + "declared_sha256": declared, + "actual_sha256": actual, + "exists": exists, + "sha256_matches": exists and declared == actual, + } + + +def audit_report( + *, report_path: Path, condition: str, checkpoint_id: str, + expected_manifest_path: str, expected_manifest_sha256: str, +) -> dict[str, Any]: + report = evaluation(report_path, "phase9_h2o_fold_heldout") + cache = file_binding(report, "cache_manifest") + expected_path = Path(expected_manifest_path) + expected_exists = expected_path.is_file() + expected_actual_sha = sha256(expected_path) if expected_exists else None + cache.update({ + "expected_path": expected_manifest_path, + "expected_sha256": expected_manifest_sha256, + "expected_path_exists": expected_exists, + "expected_path_actual_sha256": expected_actual_sha, + "path_matches": cache["path"] == expected_manifest_path, + "content_matches_expected": ( + cache["declared_sha256"] == expected_manifest_sha256 + and cache["actual_sha256"] == expected_manifest_sha256 + and expected_actual_sha == expected_manifest_sha256 + ), + }) + if not cache["content_matches_expected"]: + binding_status = "content_mismatch" + elif not cache["path_matches"]: + binding_status = "path_mismatch_content_identical" + else: + binding_status = "canonical" + result = { + "id": f"{condition}_{checkpoint_id}_rgb_d_k", + "condition": condition, + "checkpoint_id": checkpoint_id, + "input_mode": "rgb_d_k", + "report": { + "path": str(report_path.resolve()), + "sha256": sha256(report_path), + }, + "binding_status": binding_status, + "cache_manifest": cache, + "config": file_binding(report, "config"), + "checkpoint": file_binding(report, "checkpoint"), + "sample_counts": { + "clips": report.get("clips"), + "frames": report.get("frames"), + "hands_rows": report.get("hands_rows"), + }, + "determinism": { + "metrics_sha256": json_sha256(report.get("metrics")), + "grouped_bootstrap_ci_sha256": json_sha256( + report.get("grouped_bootstrap_ci") + ), + "raw_predictions": artifact_binding(report, "raw_predictions"), + "per_hand_rows": artifact_binding(report, "per_hand_rows"), + "take_metrics": artifact_binding(report, "take_metrics"), + }, + "evaluation_role": report.get("evaluation_role"), + "official_test_used": report.get("official_test_used"), + "h2o_official_validation_used": report.get( + "h2o_official_validation_used" + ), + } + required_bindings = [result["config"], result["checkpoint"]] + required_artifacts = [ + result["determinism"]["raw_predictions"], + result["determinism"]["per_hand_rows"], + result["determinism"]["take_metrics"], + ] + if not all(item["sha256_matches"] for item in required_bindings + required_artifacts): + result["binding_status"] = "referenced_artifact_mismatch" + return result + + +def build_audit( + *, selection_plan_path: Path, assignment_path: Path, +) -> dict[str, Any]: + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + if ( + selection_plan.get("official_test_used") is not False + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + ): + raise ValueError("selection audit must explicitly exclude official test") + index_path = Path(selection_plan["multifold_index"]) + index = json.loads(index_path.read_text(encoding="utf-8")) + folds = { + fold["id"]: fold for fold in validate_multifold_index(index) + } + records = [] + for mixture, checkpoint_id, fold in candidate_records(): + condition = f"{mixture}_{fold}" + path = evaluation_path( + fold_final_root=Path(selection_plan["fold_final_root"]), + fold_milestone_root=Path(selection_plan["fold_milestone_root"]), + condition=condition, checkpoint_id=checkpoint_id, + ) + records.append(audit_report( + report_path=path, condition=condition, + checkpoint_id=checkpoint_id, + expected_manifest_path=folds[fold]["heldout"]["path"], + expected_manifest_sha256=folds[fold]["heldout"]["sha256"], + )) + mismatches = [ + record for record in records + if record["binding_status"] != "canonical" + ] + assigned = { + item["id"] + for item in assignment["phase9_selection_recovery"]["evaluations"] + } + mismatch_ids = {item["id"] for item in mismatches} + status_counts = { + status: sum(item["binding_status"] == status for item in records) + for status in sorted({item["binding_status"] for item in records}) + } + if len(records) != 72 or len({item["id"] for item in records}) != 72: + raise ValueError("selection-critical report set is not exactly 72 unique IDs") + if mismatch_ids != assigned: + raise ValueError( + "selection mismatch IDs differ from frozen distributed assignment: " + f"missing={sorted(assigned - mismatch_ids)} " + f"unexpected={sorted(mismatch_ids - assigned)}" + ) + if any( + item["binding_status"] != "path_mismatch_content_identical" + for item in mismatches + ): + raise ValueError("selection mismatch includes a non-path-only failure") + return { + "schema_version": "phase9_selection_binding_mismatch_manifest_v1", + "status": "complete_path_only_recovery_required", + "created_utc": datetime.now(timezone.utc).isoformat(), + "selection_plan": { + "path": str(selection_plan_path.resolve()), + "sha256": sha256(selection_plan_path), + }, + "distributed_assignment": { + "path": str(assignment_path.resolve()), + "sha256": sha256(assignment_path), + }, + "multifold_index": { + "path": str(index_path.resolve()), "sha256": sha256(index_path), + }, + "selection_critical_report_count": len(records), + "canonical_report_count": len(records) - len(mismatches), + "mismatch_count": len(mismatches), + "binding_status_counts": status_counts, + "mismatch_ids": sorted(mismatch_ids), + "records": records, + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("audit output must be new") + result = build_audit( + selection_plan_path=args.selection_plan, + assignment_path=args.assignment, + ) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase9_source_coverage.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase9_source_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..db9555573bedef023846df78f2f866856869bee5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/audit_phase9_source_coverage.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Audit unique source coverage and cached geometric distributions.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def recording_id(row: dict[str, Any]) -> str: + return str(row.get("physical_recording_id", row.get("recording_id", "unknown"))) + + +def subject_id(row: dict[str, Any]) -> str: + return str(row.get("subject_id", row.get("participant_id", "unknown"))) + + +def frame_tokens(row: dict[str, Any]) -> list[str]: + values = ( + row.get("timestamps_ns") or row.get("timestamps_seconds") + or row.get("frame_ids") or row.get("frame_ids_1based") + or row.get("image_paths") or [] + ) + group = recording_id(row) + return [f"{group}:{value}" for value in values] + + +def action_family(dataset: str, recording: str) -> str: + parts = recording.split("/") + if dataset == "H2O" and len(parts) > 1: + return parts[1][:1] + if dataset == "HOI4D": + fields = [part for part in parts if part.startswith(("C", "N", "S"))] + return "/".join(fields[:3]) if fields else "unknown" + if dataset == "ARCTIC" and len(parts) > 1: + return parts[-1].rsplit("_", 1)[0] + return "unknown" + + +def quantiles(values: list[float]) -> dict[str, float | int | None]: + finite = np.asarray(values, dtype=np.float64) + finite = finite[np.isfinite(finite)] + if not len(finite): + return {"count": 0, "mean": None, "p05": None, "median": None, "p95": None} + return { + "count": int(len(finite)), "mean": float(finite.mean()), + "p05": float(np.percentile(finite, 5)), + "median": float(np.percentile(finite, 50)), + "p95": float(np.percentile(finite, 95)), + } + + +def source_summary(dataset: str, rows: list[dict[str, Any]]) -> dict[str, Any]: + tokens = [token for row in rows for token in frame_tokens(row)] + recordings = {recording_id(row) for row in rows} + return { + "clips": len(rows), + "subjects_or_participants": sorted({subject_id(row) for row in rows}), + "physical_recordings": len(recordings), + "headsets": sorted({str(row.get("headset", row.get("serial_id", "unknown"))) for row in rows}), + "cameras_or_streams": sorted({str(row.get("camera_id", row.get("stream_id", "unknown"))) for row in rows}), + "frame_references": len(tokens), + "unique_image_observations": len(set(tokens)) if tokens else None, + "clip_overlap_fraction": (1.0 - len(set(tokens)) / len(tokens)) if tokens else None, + "action_or_object_families": dict(sorted(Counter( + action_family(dataset, recording) for recording in recordings + ).items())), + } + + +def cache_numeric_summary(rows: list[dict[str, Any]]) -> dict[str, Any]: + unique_frames: set[str] = set() + side_frames = [0, 0] + single_frames = bimanual_frames = valid_frames = 0 + joint_visible = joint_total = 0 + border_hands = projected_outlier_hands = 0 + hand_sizes: list[float] = [] + wrist_depths: list[float] = [] + fx_values: list[float] = [] + fy_values: list[float] = [] + fov_x_values: list[float] = [] + depth_valid_fractions: list[float] = [] + supervision = Counter() + for row in rows: + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"cache payload is missing or differs: {path}") + with np.load(path, allow_pickle=False) as archive: + frame_valid = archive["frame_valid"].astype(bool) + translation_valid = archive["translation_valid"].astype(bool) + joint2d_valid = archive["joint2d_valid"].astype(bool) + joint2d = archive["joint2d"] + translation = archive["wrist_root_translation"] + K = archive["K"] + image_hw = archive["image_hw"] + frame_ids = archive["frame_id"] + depth_available = archive["depth_input_available"].astype(bool) + depth_pixel_valid = archive["depth_pixel_valid"].astype(bool) + for key in ( + "joint2d_valid", "joint3d_valid", "translation_valid", + "mano_pose_valid", "shape_valid", "vertices_valid", + ): + supervision[key] += int(np.count_nonzero(archive[key])) + group = row["physical_recording_id"] + for time_index in np.flatnonzero(frame_valid): + unique_frames.add(f"{group}:{int(frame_ids[time_index])}") + valid_frames += 1 + present = translation_valid[time_index] + side_frames[0] += int(present[0]) + side_frames[1] += int(present[1]) + single_frames += int(present.sum() == 1) + bimanual_frames += int(present.sum() == 2) + matrix = K[time_index] + fx_values.append(float(matrix[0, 0])) + fy_values.append(float(matrix[1, 1])) + fov_x_values.append(float(2 * np.arctan(float(image_hw[1]) / (2 * matrix[0, 0])))) + if depth_available[time_index]: + depth_valid_fractions.append(float(depth_pixel_valid[time_index].mean())) + for side in range(2): + if not present[side]: + continue + valid = joint2d_valid[time_index, side] + points_all = joint2d[time_index, side] + height, width = int(image_hw[0]), int(image_hw[1]) + finite = np.isfinite(points_all).all(axis=-1) + in_frame = ( + finite & (points_all[:, 0] >= 0) & (points_all[:, 0] < width) + & (points_all[:, 1] >= 0) & (points_all[:, 1] < height) + ) + visible = valid & in_frame + joint_visible += int(visible.sum()) + joint_total += int(len(valid)) + valid_finite = valid & finite + if valid_finite.any(): + raw_points = points_all[valid_finite] + raw_extent = raw_points.max(axis=0) - raw_points.min(axis=0) + projected_outlier_hands += int(raw_extent.max() > 4 * max(height, width)) + if visible.any(): + points = points_all[visible] + extent = points.max(axis=0) - points.min(axis=0) + hand_sizes.append(float(extent.max())) + border_hands += int( + points[:, 0].min() < 8 or points[:, 0].max() >= width - 8 + or points[:, 1].min() < 8 or points[:, 1].max() >= height - 8 + ) + wrist_depths.append(float(translation[time_index, side, 2])) + return { + "unique_cached_frames": len(unique_frames), + "valid_frame_references": valid_frames, + "left_hand_frames": side_frames[0], + "right_hand_frames": side_frames[1], + "single_hand_frames": single_frames, + "bimanual_frames": bimanual_frames, + "joint_visibility_fraction": joint_visible / joint_total if joint_total else None, + "occlusion_proxy_fraction": 1.0 - joint_visible / joint_total if joint_total else None, + "border_hand_frames": border_hands, + "projected_geometry_outlier_hand_frames": projected_outlier_hands, + "projected_hand_size_px": quantiles(hand_sizes), + "wrist_depth_m": quantiles(wrist_depths), + "fx_px": quantiles(fx_values), + "fy_px": quantiles(fy_values), + "horizontal_fov_radians": quantiles(fov_x_values), + "depth_valid_fraction": quantiles(depth_valid_fractions), + "supervision_valid_elements": dict(supervision), + } + + +def build_report( + dataset: str, source_manifest: Path, cache_manifest: Path, +) -> dict[str, Any]: + source_rows, cache_rows = read_jsonl(source_manifest), read_jsonl(cache_manifest) + cached_indices = {int(row["source_clip_index"]) for row in cache_rows} + if len(cached_indices) != len(cache_rows): + raise ValueError("cache manifest contains duplicate source clip indices") + if {row.get("dataset_id") for row in cache_rows} != {dataset}: + raise ValueError("cache manifest dataset differs from request") + return { + "schema_version": "phase9_source_coverage_v1", + "status": "complete", + "dataset": dataset, + "source_manifest": {"path": str(source_manifest.resolve()), "sha256": sha256(source_manifest)}, + "cache_manifest": {"path": str(cache_manifest.resolve()), "sha256": sha256(cache_manifest)}, + "source": source_summary(dataset, source_rows), + "cache": { + "clips": len(cache_rows), + "source_clip_coverage_fraction": len(cache_rows) / len(source_rows), + "subjects_or_participants": sorted({subject_id(row) for row in cache_rows}), + "physical_recordings": len({recording_id(row) for row in cache_rows}), + **cache_numeric_summary(cache_rows), + }, + "optimizer_exposure_is_unique_coverage": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("H2O", "HOT3D", "HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = build_report(args.dataset, args.source_manifest, args.cache_manifest) + except (OSError, ValueError, KeyError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_manifests.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..51063b592a532d6c453c612b141931ae3ac86d48 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_manifests.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Build reproducible cam4-only H2O run manifests from official pose lists.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path + + +def contiguous_runs(frame_ids: list[int]) -> list[list[int]]: + if not frame_ids: + return [] + runs = [[frame_ids[0]]] + for frame_id in frame_ids[1:]: + if frame_id == runs[-1][-1] + 1: + runs[-1].append(frame_id) + else: + runs.append([frame_id]) + return runs + + +def official_records(path: Path) -> list[dict[str, object]]: + grouped: dict[str, list[int]] = defaultdict(list) + for line in path.read_text(encoding="utf-8").splitlines(): + relative = Path(line.strip()) + if not line.strip(): + continue + if relative.parts[-3] != "cam4" or relative.parts[-2] != "rgb": + raise ValueError(f"Not a cam4 RGB record: {line}") + take = Path(*relative.parts[:-2]) + grouped[str(take)].append(int(relative.stem)) + records = [] + for take, ids in sorted(grouped.items()): + for run_index, run in enumerate(contiguous_runs(sorted(set(ids)))): + records.append({"take": take, "run_index": run_index, "frame_ids": run}) + return records + + +def write_jsonl(path: Path, records: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as handle: + for record in records: + handle.write(json.dumps(record, separators=(",", ":")) + "\n") + + +def build_debug_records(frame_csv: Path, window: int = 16, per_category: int = 4) -> list[dict[str, object]]: + categories: dict[str, list[dict[str, str]]] = defaultdict(list) + with frame_csv.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + key = row["joint_left_valid"] + row["joint_right_valid"] + categories[key].append(row) + selected = [] + for category, rows in sorted(categories.items()): + if category not in {"01", "10", "11"}: + continue + indices = [round(i * (len(rows) - 1) / max(per_category - 1, 1)) for i in range(per_category)] + for row_index in indices: + row = rows[row_index] + center = int(row["frame_id"]) + start = max(0, center - window // 2) + take_path = Path(row["rgb_path"]).parents[1] + available = sorted(int(path.stem) for path in (take_path / "rgb").glob("*.png")) + valid_ids = set(available) + frames = [frame_id for frame_id in range(start, start + window) if frame_id in valid_ids] + selected.append({ + "take": "/".join(take_path.parts[-4:]), + "run_index": len(selected), + "frame_ids": frames, + "debug_center_valid": category, + "debug_center_frame": center, + }) + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--pose-list-dir", type=Path, required=True) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + summary = {} + for split in ("train", "val", "test"): + records = official_records(args.pose_list_dir / f"pose_{split}.txt") + output = args.output_dir / f"official_{split}.jsonl" + write_jsonl(output, records) + summary[split] = { + "path": str(output.resolve()), + "runs": len(records), + "frames": sum(len(record["frame_ids"]) for record in records), + "subjects": sorted({str(record["take"]).split("/")[0] for record in records}), + } + debug = build_debug_records(args.frame_csv) + debug_path = args.output_dir / "debug_cam4.jsonl" + write_jsonl(debug_path, debug) + summary["debug"] = {"path": str(debug_path.resolve()), "runs": len(debug), "frames": sum(len(record["frame_ids"]) for record in debug)} + tiny = [] + for category in ("01", "10", "11"): + tiny.extend([record for record in debug if record["debug_center_valid"] == category][:2]) + tiny_path = args.output_dir / "tiny_overfit_cam4.jsonl" + write_jsonl(tiny_path, tiny) + summary["tiny_overfit"] = { + "path": str(tiny_path.resolve()), + "runs": len(tiny), + "frames": sum(len(record["frame_ids"]) for record in tiny), + "center_valid_combinations": {category: 2 for category in ("01", "10", "11")}, + } + summary["policy"] = "Official pose split; clips are generated inside each contiguous take/run and never cross camera, sequence, or subject." + (args.output_dir / "manifest_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase3_val_subset.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase3_val_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5c9941a59e168b9e49e961c4a41f3556b97aa9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase3_val_subset.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Build the fixed 256-clip Phase 3 validation subset from input-only strata.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.subset import balanced_stratified_indices + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def size_bucket(value: float) -> str: + if value < 64: + return "small" + if value < 128: + return "medium" + return "large" + + +def depth_bucket(value: float) -> str: + if value < 0.5: + return "near" + if value < 0.8: + return "middle" + return "far" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--per-hand-frames", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--count", type=int, default=256) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + with args.per_hand_frames.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + grouped: dict[int, list[dict[str, str]]] = defaultdict(list) + for row in rows: + grouped[int(row["clip_index"])].append(row) + + clip_records: list[dict[str, object]] = [] + for clip_index, clip_rows in sorted(grouped.items()): + sizes = [float(row["hand_size_px"]) for row in clip_rows if row["hand_size_px"]] + depths = [float(row["wrist_depth_m"]) for row in clip_rows if row["wrist_depth_m"]] + states = [row["annotation_state"] for row in clip_rows] + state_counts = Counter(states) + # Preserve rare one-hand-valid clips as a stratum instead of letting the + # dominant both-valid frames erase them. + annotation_state = "01" if state_counts["01"] else "10" if state_counts["10"] else state_counts.most_common(1)[0][0] + median_size = float(np.median(sizes)) if sizes else float("nan") + median_depth = float(np.median(depths)) if depths else float("nan") + first = clip_rows[0] + clip_records.append({ + "clip_index": clip_index, + "take": first["take"], + "subject": first["subject"], + "sequence": first["sequence"], + "first_frame_id": min(int(row["frame_id"]) for row in clip_rows), + "last_frame_id": max(int(row["frame_id"]) for row in clip_rows), + "hand_size_px_median": median_size, + "hand_size_bucket": size_bucket(median_size) if np.isfinite(median_size) else "unavailable", + "wrist_depth_m_median": median_depth, + "depth_bucket": depth_bucket(median_depth) if np.isfinite(median_depth) else "unavailable", + "annotation_state": annotation_state, + }) + + selected_indices = balanced_stratified_indices(clip_records, args.count, seed=args.seed) + selected_set = set(selected_indices) + selected_records = [record for record in clip_records if int(record["clip_index"]) in selected_set] + take_counts = Counter(str(record["take"]) for record in selected_records) + stratum_counts = Counter( + (str(record["hand_size_bucket"]), str(record["depth_bucket"]), str(record["annotation_state"])) + for record in selected_records + ) + manifest = { + "version": "phase3_stratified_256_v1", + "seed": args.seed, + "count": len(selected_indices), + "source_manifest": str(args.source_manifest.resolve()), + "source_manifest_sha256": sha256(args.source_manifest), + "source_clip_count": len(clip_records), + "dataset_contract": {"resolution_hw": [288, 512], "T": 8, "stride": 1, "allow_partial": True}, + "selection_inputs": "take, GT-projected hand extent, wrist depth, annotation validity; model errors are excluded", + "selection_policy": "balanced take quotas plus deterministic round-robin within-take size/depth/valid strata", + "clip_indices": selected_indices, + "take_counts": dict(sorted(take_counts.items())), + "stratum_counts": {"/".join(key): value for key, value in sorted(stratum_counts.items())}, + "official_test_used": False, + } + manifest_path = args.output_dir / "validation_subset_256.json" + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + + csv_path = args.output_dir / "validation_subset_256.csv" + with csv_path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(selected_records[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(selected_records) + (args.output_dir / "validation_subset_256.sha256").write_text( + f"{sha256(manifest_path)} {manifest_path.name}\n{sha256(csv_path)} {csv_path.name}\n", + encoding="utf-8", + ) + print(json.dumps({ + "status": "created", "count": len(selected_indices), "takes": len(take_counts), + "take_count_min": min(take_counts.values()), "take_count_max": max(take_counts.values()), + "manifest": str(manifest_path), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase4_balanced_sampler.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase4_balanced_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..da8852e7b9d01cedc7c28961a16d8b599e3a06a0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase4_balanced_sampler.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""Build a deterministic train-only geometry-balanced sampling manifest.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from collections import Counter +from pathlib import Path + +import numpy as np + +from foundation_hand.data import H2OCam4Dataset +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record +from foundation_hand.evaluation.phase4 import bimanual_asymmetry +from foundation_hand.geometry.camera import ( + intrinsics_from_h2o, + project_points, + resize_and_pad_intrinsics, +) + + +AXES = ( + "left_size_bucket", + "right_size_bucket", + "left_depth_bucket", + "right_depth_bucket", + "asymmetry_bucket", + "action_family", + "annotation_valid_state", +) +WEIGHT_MIN = 0.5 +WEIGHT_MAX = 3.0 +TAKE_FACTOR_MIN = 2.0 / 3.0 +TAKE_FACTOR_MAX = 1.5 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def fit_resize( + source_hw: tuple[int, int], target_hw: tuple[int, int], +) -> tuple[tuple[int, int], tuple[int, int]]: + source_h, source_w = source_hw + target_h, target_w = target_hw + scale = min(target_w / source_w, target_h / source_h) + resized = (max(1, round(source_h * scale)), max(1, round(source_w * scale))) + return resized, ((target_w - resized[1]) // 2, (target_h - resized[0]) // 2) + + +def size_bucket(value: float | None) -> str: + if value is None: + return "unavailable" + if value < 64.0: + return "small" + if value < 128.0: + return "medium" + return "large" + + +def depth_bucket(value: float | None) -> str: + if value is None: + return "unavailable" + if value < 0.5: + return "near" + if value < 0.8: + return "middle" + return "far" + + +def median_or_none(values: list[float]) -> float | None: + return float(np.median(values)) if values else None + + +def validity_state(valid_counts: list[int], frame_count: int) -> str: + frequent = [count / frame_count >= 0.5 for count in valid_counts] + if frequent == [True, True]: + return "both" + if frequent == [True, False]: + return "left_only" + if frequent == [False, True]: + return "right_only" + return "sparse" + + +def clip_geometry_record( + root: Path, + clip_index: int, + clip, + target_hw: tuple[int, int], + intrinsics_cache: dict[str, np.ndarray], +) -> dict[str, object]: + take_dir = root / clip.take + if clip.take not in intrinsics_cache: + K_raw, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + resized_hw, pad_left_top = fit_resize(source_hw, target_hw) + intrinsics_cache[clip.take] = resize_and_pad_intrinsics( + K_raw, source_hw, resized_hw, pad_left_top, + ) + K = intrinsics_cache[clip.take] + sizes: list[list[float]] = [[], []] + depths: list[list[float]] = [[], []] + valid_counts = [0, 0] + ratios: list[float] = [] + gaps: list[float] = [] + for frame_id in clip.frame_ids: + joints = load_joint_record(take_dir / "hand_pose" / f"{frame_id:06d}.txt") + joints_2d, positive = project_points(joints.joints_camera_m, K) + frame_sizes: list[float | None] = [None, None] + frame_depths: list[float | None] = [None, None] + for hand in range(2): + if not bool(joints.annotation_valid[hand]) or not bool(positive[hand].all()): + continue + extent = joints_2d[hand].max(axis=0) - joints_2d[hand].min(axis=0) + size = float(extent.max()) + depth = float(joints.joints_camera_m[hand, 0, 2]) + sizes[hand].append(size) + depths[hand].append(depth) + valid_counts[hand] += 1 + frame_sizes[hand] = size + frame_depths[hand] = depth + asymmetry = bimanual_asymmetry(frame_sizes, frame_depths) + if asymmetry["bimanual_size_ratio"] is not None: + ratios.append(float(asymmetry["bimanual_size_ratio"])) + gaps.append(float(asymmetry["bimanual_depth_gap_m"])) + median_sizes = [median_or_none(values) for values in sizes] + median_depths = [median_or_none(values) for values in depths] + aggregate_asymmetry = bimanual_asymmetry(median_sizes, median_depths) + parts = Path(clip.take).parts + return { + "clip_index": clip_index, + "take": clip.take, + "frame_count": len(clip.frame_ids), + "action_family": parts[1], + "annotation_valid_state": validity_state(valid_counts, len(clip.frame_ids)), + "left_valid_fraction": valid_counts[0] / len(clip.frame_ids), + "right_valid_fraction": valid_counts[1] / len(clip.frame_ids), + "left_hand_size_px": median_sizes[0], + "right_hand_size_px": median_sizes[1], + "left_wrist_depth_m": median_depths[0], + "right_wrist_depth_m": median_depths[1], + "median_size_ratio": median_or_none(ratios), + "median_depth_gap_m": median_or_none(gaps), + "left_size_bucket": size_bucket(median_sizes[0]), + "right_size_bucket": size_bucket(median_sizes[1]), + "left_depth_bucket": depth_bucket(median_depths[0]), + "right_depth_bucket": depth_bucket(median_depths[1]), + "asymmetry_bucket": aggregate_asymmetry["bimanual_asymmetry_bucket"] or "unavailable", + } + + +def assign_weights(records: list[dict[str, object]]) -> dict[str, object]: + if not records: + raise ValueError("cannot balance an empty clip set") + frequencies = { + axis: Counter(str(record[axis]) for record in records) for axis in AXES + } + take_counts = Counter(str(record["take"]) for record in records) + median_take_count = float(np.median(list(take_counts.values()))) + raw_weights = [] + for record in records: + marginal = [] + for axis in AXES: + counts = frequencies[axis] + count = counts[str(record[axis])] + marginal.append(math.sqrt(len(records) / (len(counts) * count))) + geometry_factor = float(np.mean(marginal)) + take_factor = math.sqrt(median_take_count / take_counts[str(record["take"])]) + take_factor = float(np.clip(take_factor, TAKE_FACTOR_MIN, TAKE_FACTOR_MAX)) + raw_weights.append(geometry_factor * take_factor) + record["geometry_rarity_factor"] = geometry_factor + record["take_frequency_factor"] = take_factor + scale = float(np.mean(raw_weights)) + weights = np.clip(np.asarray(raw_weights) / scale, WEIGHT_MIN, WEIGHT_MAX) + for record, weight in zip(records, weights, strict=True): + record["weight"] = float(weight) + return { + "axis_frequencies": { + axis: dict(sorted(counts.items())) for axis, counts in frequencies.items() + }, + "take_clip_count_min": min(take_counts.values()), + "take_clip_count_median": median_take_count, + "take_clip_count_max": max(take_counts.values()), + "weight_min": float(weights.min()), + "weight_mean": float(weights.mean()), + "weight_max": float(weights.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--expected-manifest-sha256", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--resolution-hw", type=int, nargs=2, default=(368, 640)) + parser.add_argument("--T", type=int, default=8) + parser.add_argument("--stride", type=int, default=1) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args() + if "test" in args.manifest.name.lower() or "val" in args.manifest.name.lower(): + raise ValueError("balanced sampler builder accepts official train only") + manifest_hash = sha256(args.manifest) + if manifest_hash != args.expected_manifest_sha256: + raise ValueError("official-train manifest hash mismatch") + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite {args.output}") + target_hw = tuple(args.resolution_hw) + dataset = H2OCam4Dataset( + args.root, args.manifest, target_hw, (args.T,), (args.stride,), + max_clips=args.max_clips, + ) + cache: dict[str, np.ndarray] = {} + records = [] + for clip_index, clip in enumerate(dataset.clips): + records.append(clip_geometry_record( + args.root, clip_index, clip, target_hw, cache, + )) + if (clip_index + 1) % 500 == 0: + print(f"clips={clip_index + 1}/{len(dataset)}", flush=True) + summary = assign_weights(records) + output = { + "version": "phase4_train_geometry_balanced_v1", + "phase": 4, + "wave": "B2", + "split_role": "official_train", + "official_test_used": False, + "source_manifest": str(args.manifest.resolve()), + "source_manifest_sha256": manifest_hash, + "dataset_contract": { + "resolution_hw": list(target_hw), "T": args.T, "stride": args.stride, + "allow_partial": True, + }, + "clip_count": len(records), + "policy": { + "axes": list(AXES), + "marginal_weight": "inverse square root of train-only clip frequency", + "combination": "mean marginal rarity multiplied by capped take-frequency correction", + "weight_cap": [WEIGHT_MIN, WEIGHT_MAX], + "take_factor_cap": [TAKE_FACTOR_MIN, TAKE_FACTOR_MAX], + "draws": "dataset_size draws with replacement per seed+epoch", + "validation_identity_used": False, + }, + "summary": summary, + "clips": records, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": "complete", "clips": len(records), **summary}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase4_checkpoint_index.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase4_checkpoint_index.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c866726979ff9b6154bd9fcd36293264747a33 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase4_checkpoint_index.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Build a deterministic index of Phase 4 official-validation checkpoints.""" + +from __future__ import annotations + +import argparse +import json +import os +import re +from pathlib import Path +from typing import Any + + +SHA256 = re.compile(r"[0-9a-f]{64}") +OFFICIAL_VALIDATION_CLIPS = 1495 +OFFICIAL_VALIDATION_FRAMES = 11638 + + +def evaluation_reports(root: Path) -> list[Path]: + """Find reports through SSD-backed artifact symlinks without following cycles.""" + reports = [] + visited_directories: set[Path] = set() + for directory, names, files in os.walk(root, followlinks=True): + directory_path = Path(directory) + resolved_directory = directory_path.resolve() + if resolved_directory in visited_directories: + names.clear() + continue + visited_directories.add(resolved_directory) + names[:] = sorted( + name for name in names + if (directory_path / name).resolve() not in visited_directories + ) + if "evaluation.json" in files: + reports.append(directory_path / "evaluation.json") + return sorted(reports) + + +def logical_location(root: Path, report_path: Path) -> tuple[str, str, str]: + parts = report_path.relative_to(root).parts + if "full_validation" in parts: + index = parts.index("full_validation") + if len(parts) <= index + 3: + raise ValueError(f"invalid full-validation path: {report_path}") + condition = "/".join(parts[:index]) + return condition, parts[index + 1], parts[index + 2] + if len(parts) < 2: + raise ValueError(f"invalid evaluation path: {report_path}") + return parts[0], report_path.parent.name, "reference" + + +def build_index(root: Path) -> dict[str, Any]: + root = root.resolve() + records = [] + for report_path in evaluation_reports(root): + report = json.loads(report_path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("split_role") != "official_validation": + continue + if report.get("official_test_used") is not False: + raise ValueError(f"official-validation report lacks test isolation: {report_path}") + # Real-checkpoint smokes use the validation split but are not complete + # evaluations and must not enter the formal checkpoint index. + if ( + report.get("clips") != OFFICIAL_VALIDATION_CLIPS + or report.get("frames") != OFFICIAL_VALIDATION_FRAMES + ): + continue + checkpoint = report.get("checkpoint") + if not isinstance(checkpoint, dict): + raise ValueError(f"missing checkpoint record: {report_path}") + sha256 = checkpoint.get("sha256") + if not isinstance(sha256, str) or SHA256.fullmatch(sha256) is None: + raise ValueError(f"invalid checkpoint SHA256: {report_path}") + checkpoint_path = Path(str(checkpoint.get("path", ""))) + if not checkpoint_path.is_file(): + raise FileNotFoundError(f"indexed checkpoint is missing: {checkpoint_path}") + step = checkpoint.get("step") + if not isinstance(step, int) or step < 0: + raise ValueError(f"invalid checkpoint step: {report_path}") + condition, run, role = logical_location(root, report_path) + config = report.get("config", {}) + records.append({ + "condition": condition, + "run": run, + "role": role, + "config": config.get("name"), + "seed": config.get("seed"), + "checkpoint_path": str(checkpoint_path.resolve()), + "checkpoint_sha256": sha256, + "checkpoint_step": step, + "evaluation_path": str(report_path.resolve()), + "clips": report.get("clips"), + "frames": report.get("frames"), + }) + if not records: + raise ValueError(f"no official-validation evaluations found under {root}") + unique_checkpoints = { + (record["checkpoint_path"], record["checkpoint_sha256"]) + for record in records + } + return { + "status": "indexed", + "official_test_used": False, + "evaluations": len(records), + "unique_checkpoints": len(unique_checkpoints), + "records": records, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--phase4-root", type=Path, default=Path("artifacts/phase4"), + ) + parser.add_argument( + "--output", type=Path, + default=Path("artifacts/phase4/reports/checkpoints.json"), + ) + args = parser.parse_args() + payload = build_index(args.phase4_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": payload["status"], + "evaluations": payload["evaluations"], + "unique_checkpoints": payload["unique_checkpoints"], + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase5_group_folds.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase5_group_folds.py new file mode 100644 index 0000000000000000000000000000000000000000..996077ed4feed509db4ffefe17c0a09ae4f40367 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase5_group_folds.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Build deterministic subject-held-out OOF manifests from official train only.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None: + with path.open("w", encoding="utf-8") as handle: + for record in records: + handle.write(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n") + + +def record_id(record: dict[str, Any]) -> tuple[str, int]: + return str(record["take"]), int(record["run_index"]) + + +def subject(record: dict[str, Any]) -> str: + return str(record["take"]).split("/", 1)[0] + + +def fold_summary(records: list[dict[str, Any]]) -> dict[str, Any]: + return { + "records": len(records), + "frames": sum(len(record["frame_ids"]) for record in records), + "takes": len({str(record["take"]) for record in records}), + "subjects": sorted({subject(record) for record in records}), + "action_families": sorted({str(record["take"]).split("/")[1] for record in records}), + } + + +def build_subject_folds(source_manifest: Path, output_root: Path) -> dict[str, Any]: + records = [ + json.loads(line) + for line in source_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not records: + raise ValueError("source manifest is empty") + ids = [record_id(record) for record in records] + if len(ids) != len(set(ids)): + raise ValueError("source manifest contains duplicate take/run records") + for record in records: + if not record.get("frame_ids"): + raise ValueError(f"record has no frames: {record_id(record)}") + + by_subject: dict[str, list[dict[str, Any]]] = defaultdict(list) + for record in records: + by_subject[subject(record)].append(record) + subjects = sorted(by_subject) + if len(subjects) < 2: + raise ValueError("subject-held-out OOF requires at least two subjects") + + output_root.mkdir(parents=True, exist_ok=True) + folds = [] + heldout_ids: set[tuple[str, int]] = set() + for fold_index, heldout_subject in enumerate(subjects): + fold_dir = output_root / f"fold_{fold_index}_{heldout_subject}" + fold_dir.mkdir(parents=True, exist_ok=True) + heldout = sorted(by_subject[heldout_subject], key=record_id) + train = sorted( + (record for record in records if subject(record) != heldout_subject), + key=record_id, + ) + train_path = fold_dir / "train.jsonl" + heldout_path = fold_dir / "heldout.jsonl" + write_jsonl(train_path, train) + write_jsonl(heldout_path, heldout) + + train_takes = {str(record["take"]) for record in train} + heldout_takes = {str(record["take"]) for record in heldout} + train_subjects = {subject(record) for record in train} + heldout_subjects = {subject(record) for record in heldout} + leakage_free = not (train_takes & heldout_takes) and not ( + train_subjects & heldout_subjects + ) + if not leakage_free: + raise RuntimeError(f"group leakage detected in fold {fold_index}") + current_ids = {record_id(record) for record in heldout} + if heldout_ids & current_ids: + raise RuntimeError("a source record appears in more than one heldout fold") + heldout_ids.update(current_ids) + folds.append({ + "fold": fold_index, + "heldout_subject": heldout_subject, + "train_manifest": str(train_path.relative_to(output_root)), + "train_manifest_sha256": sha256(train_path), + "heldout_manifest": str(heldout_path.relative_to(output_root)), + "heldout_manifest_sha256": sha256(heldout_path), + "train": fold_summary(train), + "heldout": fold_summary(heldout), + "leakage_audit": { + "take_overlap": [], + "subject_overlap": [], + "passed": True, + }, + }) + + if heldout_ids != set(ids): + raise RuntimeError("heldout folds do not form an exact partition of official train") + report = { + "version": "phase5_subject_oof_v1", + "status": "frozen", + "source_role": "official_train", + "source_manifest": str(source_manifest.resolve()), + "source_manifest_sha256": sha256(source_manifest), + "assignment": "one complete official-train subject per heldout fold", + "group_unit": "subject; take/recording is indivisible", + "folds": folds, + "source": fold_summary(records), + "coverage_audit": { + "heldout_records": len(heldout_ids), + "source_records": len(records), + "exact_partition": True, + }, + "official_validation_used_for_assignment": False, + "official_test_used": False, + } + (output_root / "folds.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + args = parser.parse_args() + report = build_subject_folds(args.source_manifest, args.output_root) + print(json.dumps({ + "status": report["status"], + "version": report["version"], + "folds": len(report["folds"]), + "source": report["source"], + "official_test_used": report["official_test_used"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase5_missing_alignment_package.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase5_missing_alignment_package.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9247dc5bb746e3387abd07ad37a634e36ece53 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase5_missing_alignment_package.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Build an exact zero-alignment package for true missing-input causal audits.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def validate_cache( + manifest: dict[str, Any], expected_condition: str, expected_scope: str, +) -> None: + if ( + manifest.get("status") != "complete" + or manifest.get("scope") != expected_scope + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + or manifest.get("input_condition") != expected_condition + ): + raise ValueError("invalid true missing-input cache contract") + if expected_scope == "full" and ( + manifest.get("clips") != 1495 or manifest.get("frames") != 11638 + ): + raise ValueError("invalid full-cache coverage") + + +def fallback_prediction(arrays: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + frame_id = arrays["frame_id"] + translation = arrays["pred_wrist_translation"] + if frame_id.ndim != 1 or translation.shape[:2] != (len(frame_id), 2): + raise ValueError("invalid cache take dimensions") + shape = (len(frame_id), 2) + zeros = np.zeros(shape, dtype=np.float32) + return { + "frame_id": frame_id.astype(np.int64, copy=False), + "calibrated_delta_z_m": zeros, + "alignment_applied": np.zeros(shape, dtype=bool), + "confidence": zeros.copy(), + "inlier_ratio": zeros.copy(), + "residual_scale_m": zeros.copy(), + "valid_fraction": zeros.copy(), + "quality": zeros.copy(), + } + + +def build_package( + cache_dir: Path, + output_dir: Path, + expected_condition: str, + expected_scope: str, +) -> dict[str, Any]: + if output_dir.exists() and any(output_dir.iterdir()): + raise FileExistsError("fallback alignment output must be new or empty") + manifest_path = cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + validate_cache(manifest, expected_condition, expected_scope) + output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = output_dir / "predictions" + prediction_root.mkdir() + records = [] + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"cache take hash mismatch: {take_path}") + arrays = load_npz(take_path) + stem = "__".join(Path(str(arrays["take"])).parts) + prediction_path = prediction_root / f"{stem}.npz" + np.savez_compressed(prediction_path, **fallback_prediction(arrays)) + records.append({ + "take": str(arrays["take"]), + "path": str(prediction_path.resolve()), + "sha256": sha256(prediction_path), + }) + report = { + "status": "evaluated", + "experiment_class": "preregistered_missing_input_causal_diagnostic", + "result_role": "exact_zero_alignment_max_uncertainty_input_package", + "input_condition": expected_condition, + "scope": expected_scope, + "cache_manifest": { + "path": str(manifest_path.resolve()), + "sha256": sha256(manifest_path), + }, + "coarse_checkpoint": manifest["checkpoint"], + "alignment_contract": ( + "alignment_applied=false and delta-z=0 for every hand/frame; " + "causal uncertainty evaluator maps unavailable alignment to maximum noise" + ), + "takes": records, + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + } + (output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument( + "--expected-condition", choices=("missing_depth", "missing_k"), required=True, + ) + parser.add_argument("--scope", choices=("full", "smoke"), default="full") + args = parser.parse_args() + report = build_package( + args.cache_dir, args.output_dir, args.expected_condition, args.scope, + ) + print(json.dumps({ + "status": report["status"], + "condition": report["input_condition"], + "takes": len(report["takes"]), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase5_oof_bank.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..3199c0ded583d5c1ea631b3681edadbb755d4337 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase5_oof_bank.py @@ -0,0 +1,525 @@ +#!/usr/bin/env python3 +"""Build a resume-safe group-held-out coarse prediction bank for Phase 5.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.alignment_calibration import projected_hand_scale_px +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +BANK_VERSION = 2 +SIDES = ("left", "right") +FRAME_ARRAYS = ( + "clip_index", + "frame_id", + "frame_valid", + "K_resized", + "K_raw", + "rgb_available", + "depth_available", + "K_available", + "pred_rotation_matrices", + "pred_shape", + "pred_wrist_translation", + "pred_joints_camera", + "pred_vertices_camera", + "pred_direct_2d_px", + "pred_joints_raw_px", + "pred_vertices_raw_px", + "pred_surface_depth_m", + "observed_surface_depth_m", + "observed_surface_xyz_m", + "surface_visible", + "surface_sample_valid", + "surface_local_discontinuity_m", + "silhouette_packed", + "silhouette_overlap_fraction", + "predicted_depth_order", + "alignment_delta_z_m", + "alignment_applied", + "alignment_valid_support_count", + "alignment_projected_support_count", + "alignment_inlier_ratio", + "alignment_residual_scale_m", + "alignment_valid_fraction", + "alignment_foreground_fraction", + "alignment_background_fraction", + "alignment_depth_discontinuity_m", + "alignment_conditioning_quality", + "coarse_direct_mano_consistency_px", + "coarse_hand_scale_px", + "coarse_wrist_velocity_m_per_frame", + "target_rotation_matrices", + "target_pose_axis_angle", + "target_shape", + "target_wrist_translation", + "target_joints_camera", + "target_vertices_camera", + "target_2d_px", + "translation_residual_m", + "joint_annotation_valid", + "joint_element_valid", + "mano_annotation_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def take_slug(take: str) -> str: + parts = Path(take).parts + if len(parts) != 4 or parts[-1] != "cam4": + raise ValueError(f"unexpected H2O take: {take}") + return "__".join(parts) + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def resolve_fold_contract( + folds_manifest: Path, + fold_index: int, + heldout_manifest: Path, + run_provenance: Path, +) -> dict[str, Any]: + folds = json.loads(folds_manifest.read_text(encoding="utf-8")) + if ( + folds.get("version") != "phase5_subject_oof_v1" + or folds.get("status") != "frozen" + or folds.get("source_role") != "official_train" + or folds.get("official_test_used") is not False + ): + raise ValueError("invalid or unfrozen Phase 5 OOF manifest") + matches = [record for record in folds["folds"] if int(record["fold"]) == fold_index] + if len(matches) != 1: + raise ValueError(f"fold {fold_index} is not uniquely registered") + fold = matches[0] + registered_heldout = folds_manifest.parent / fold["heldout_manifest"] + if heldout_manifest.resolve() != registered_heldout.resolve(): + raise ValueError("heldout manifest path differs from registered fold") + if sha256(heldout_manifest) != fold["heldout_manifest_sha256"]: + raise ValueError("heldout manifest hash differs from registered fold") + provenance = json.loads(run_provenance.read_text(encoding="utf-8")) + train_hash = provenance.get("hashes", {}).get("train_manifest", {}).get("sha256") + if train_hash != fold["train_manifest_sha256"]: + raise ValueError("checkpoint training manifest is not the registered fold train split") + if provenance.get("git_status") not in ("", None): + raise ValueError("OOF bank requires a checkpoint trained from a clean worktree") + return {"folds": folds, "fold": fold, "provenance": provenance} + + +def validate_checkpoint_provenance( + checkpoint: dict[str, Any], + *, + config: dict[str, Any], + config_path: Path, + run_provenance_path: Path, + provenance: dict[str, Any], +) -> None: + """Bind the extraction checkpoint to its clean training run and config.""" + + extra = checkpoint.get("extra", {}) + provenance_config_hash = provenance.get("hashes", {}).get("config", {}).get("sha256") + if provenance_config_hash != sha256(config_path): + raise ValueError("extraction config hash differs from checkpoint run provenance") + if provenance.get("config") != config or extra.get("config") != config: + raise ValueError("extraction config differs from checkpoint embedded config") + if extra.get("git_commit") != provenance.get("git_commit"): + raise ValueError("checkpoint git commit differs from run provenance") + if extra.get("run_provenance_sha256") != sha256(run_provenance_path): + raise ValueError("checkpoint run provenance hash mismatch") + protocol = config.get("protocol", {}) + if extra.get("checkpoint_role") != "final" or int(checkpoint.get("step", -1)) != int( + protocol.get("max_steps", -2) + ): + raise ValueError("OOF bank requires the preregistered fixed-final checkpoint") + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def target_geometry( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + pose_axis_angle = batch["mano_pose"].reshape(*batch["mano_pose"].shape[:-1], 16, 3) + rotations = axis_angle_to_matrix(torch.nan_to_num(pose_axis_angle)) + with torch.no_grad(): + vertices, joints = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = batch["mano_annotation_valid"].bool()[..., None, None] + vertices = torch.where(valid, vertices, torch.full_like(vertices, torch.nan)) + joints = torch.where(valid, joints, torch.full_like(joints, torch.nan)) + return pose_axis_angle, rotations, vertices, joints + + +def _observed_xyz( + pixels: np.ndarray, observed_depth_m: np.ndarray, K: np.ndarray, +) -> np.ndarray: + z = observed_depth_m.astype(np.float32) + xyz = np.full((*z.shape, 3), np.nan, dtype=np.float32) + valid = np.isfinite(z) & (z > 0.0) & np.isfinite(pixels).all(axis=-1) + xyz[..., 2][valid] = z[valid] + xyz[..., 0][valid] = (pixels[..., 0][valid] - K[0, 2]) * z[valid] / K[0, 0] + xyz[..., 1][valid] = (pixels[..., 1][valid] - K[1, 2]) * z[valid] / K[1, 1] + return xyz + + +def _velocity(translation: np.ndarray, frame_ids: np.ndarray) -> np.ndarray: + output = np.zeros_like(translation, dtype=np.float32) + contiguous = frame_ids[1:] == frame_ids[:-1] + 1 + output[1:][contiguous] = translation[1:][contiguous] - translation[:-1][contiguous] + return output + + +def infer_take( + *, + root: Path, + take: str, + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + loader = DataLoader( + Subset(dataset, clip_indices), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + take_dir = root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + silhouette_hw: tuple[int, int] | None = None + for global_clip_index, batch_cpu in zip(clip_indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + target_pose, target_rotations, target_vertices, target_joints = target_geometry(batch, model) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + valid_times = int(batch["frame_valid"][0].sum()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor( + (width, height), device=device, + ) + pred_vertices = prediction["vertices_camera"][0, :valid_times].float().cpu().numpy() + pred_joints = prediction["joints_camera"][0, :valid_times].float().cpu().numpy() + frame_ids = batch["frame_id"][0, :valid_times].cpu().numpy().astype(np.int64) + surface_fields: dict[str, list[np.ndarray]] = defaultdict(list) + for time_index, frame_id in enumerate(frame_ids): + stem = f"{int(frame_id):06d}" + raw_depth_mm = cv2.imread(str(take_dir / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED) + if raw_depth_mm is None or raw_depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{stem}") + raw_depth_m, raw_depth_valid = depth_mm_to_m(raw_depth_mm) + packed_masks = [] + medians = [] + for hand in range(2): + diagnostics, samples = align_wrist_z( + pred_vertices[time_index, hand], K_raw, raw_depth_m, raw_depth_valid, + ) + if samples is None: + raise AssertionError("full-modality OOF extraction unexpectedly lacks surface samples") + if silhouette_hw is None: + silhouette_hw = samples.silhouette_hw + elif silhouette_hw != samples.silhouette_hw: + raise AssertionError("silhouette shape changed within OOF bank") + observed_xyz = _observed_xyz( + samples.projected_vertices_px, samples.observed_depth_m, K_raw, + ) + surface_fields["pred_vertices_raw_px"].append(samples.projected_vertices_px) + surface_fields["pred_surface_depth_m"].append(samples.predicted_depth_m) + surface_fields["observed_surface_depth_m"].append(samples.observed_depth_m) + surface_fields["observed_surface_xyz_m"].append(observed_xyz) + surface_fields["surface_visible"].append(samples.visible_vertex) + surface_fields["surface_sample_valid"].append(samples.sample_valid) + surface_fields["surface_local_discontinuity_m"].append(samples.local_discontinuity_m) + surface_fields["silhouette_packed"].append(samples.silhouette_packed) + for field, value in diagnostics.as_dict().items(): + surface_fields[f"alignment_{field}"].append(np.asarray(value)) + packed_masks.append(np.unpackbits( + samples.silhouette_packed, bitorder="little", + count=samples.silhouette_hw[0] * samples.silhouette_hw[1], + ).astype(bool)) + medians.append(float(np.median(samples.predicted_depth_m[samples.visible_vertex]))) + intersection = np.logical_and(packed_masks[0], packed_masks[1]).sum() + union = np.logical_or(packed_masks[0], packed_masks[1]).sum() + surface_fields["silhouette_overlap_fraction"].append( + np.asarray(intersection / max(union, 1), dtype=np.float32) + ) + surface_fields["predicted_depth_order"].append( + np.asarray(np.sign(medians[1] - medians[0]), dtype=np.int8) + ) + + mano_2d_raw, _ = project_points(pred_joints, K_raw) + direct_np = direct_2d[0, :valid_times].cpu().numpy() + raw_to_resized = np.asarray( + (width / raw_hw[1], height / raw_hw[0]), dtype=np.float32, + ) + consistency = np.linalg.norm( + direct_np - mano_2d_raw * raw_to_resized, axis=-1, + ).mean(axis=-1) + hand_scale = projected_hand_scale_px( + mano_2d_raw, source_hw=raw_hw, target_hw=(height, width), + ) + values: dict[str, np.ndarray] = { + "clip_index": np.full(valid_times, global_clip_index, dtype=np.int64), + "frame_id": frame_ids, + "frame_valid": batch["frame_valid"][0, :valid_times].cpu().numpy(), + "K_resized": batch["K"][0, :valid_times].float().cpu().numpy(), + "K_raw": np.broadcast_to(K_raw, (valid_times, 3, 3)).copy(), + "rgb_available": batch["frame_valid"][0, :valid_times].cpu().numpy(), + "depth_available": batch["depth_available"][0, :valid_times].cpu().numpy(), + "K_available": batch["K_available"][0, :valid_times].cpu().numpy(), + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0, :valid_times].float().cpu().numpy(), + "pred_shape": prediction["mano_shape"][0, :valid_times].float().cpu().numpy(), + "pred_wrist_translation": prediction["wrist_root_translation"][0, :valid_times].float().cpu().numpy(), + "pred_joints_camera": pred_joints, + "pred_vertices_camera": pred_vertices, + "pred_direct_2d_px": direct_np, + "pred_joints_raw_px": mano_2d_raw.astype(np.float32), + "coarse_direct_mano_consistency_px": consistency.astype(np.float32), + "coarse_hand_scale_px": hand_scale.astype(np.float32), + "target_rotation_matrices": target_rotations[0, :valid_times].float().cpu().numpy(), + "target_pose_axis_angle": target_pose[0, :valid_times].float().cpu().numpy(), + "target_shape": batch["mano_shape"][0, :valid_times].float().cpu().numpy(), + "target_wrist_translation": batch["wrist_root_translation"][0, :valid_times].float().cpu().numpy(), + "target_joints_camera": target_joints[0, :valid_times].float().cpu().numpy(), + "target_vertices_camera": target_vertices[0, :valid_times].float().cpu().numpy(), + "target_2d_px": batch["joint2d"][0, :valid_times].float().cpu().numpy(), + "joint_annotation_valid": batch["joint_annotation_valid"][0, :valid_times].cpu().numpy(), + "joint_element_valid": batch["joint_element_valid"][0, :valid_times].cpu().numpy(), + "mano_annotation_valid": batch["mano_annotation_valid"][0, :valid_times].cpu().numpy(), + } + values["translation_residual_m"] = ( + values["target_wrist_translation"] - values["pred_wrist_translation"] + ) + for key, hand_values in surface_fields.items(): + stacked = np.stack(hand_values) + if key not in ("silhouette_overlap_fraction", "predicted_depth_order"): + stacked = stacked.reshape(valid_times, 2, *stacked.shape[1:]) + values[key] = stacked + for key, value in values.items(): + chunks[key].append(value) + + arrays = {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + arrays["coarse_wrist_velocity_m_per_frame"] = _velocity( + arrays["pred_wrist_translation"], arrays["frame_id"], + ) + arrays["silhouette_hw"] = np.asarray(silhouette_hw, dtype=np.int32) + return arrays + + +def validate_bank_arrays( + arrays: dict[str, np.ndarray], + *, + take: str, + expected_frame_ids: list[int], + checkpoint_sha256: str, + config_sha256: str, + heldout_manifest_sha256: str, + fold_index: int, +) -> None: + missing = sorted(set(FRAME_ARRAYS) - arrays.keys()) + if missing: + raise ValueError(f"OOF bank is missing arrays: {missing}") + scalars = { + "bank_version": BANK_VERSION, + "take": take, + "checkpoint_sha256": checkpoint_sha256, + "config_sha256": config_sha256, + "heldout_manifest_sha256": heldout_manifest_sha256, + "fold_index": fold_index, + } + for key, expected in scalars.items(): + if str(arrays[key]) != str(expected): + raise ValueError(f"OOF bank scalar mismatch: {key}") + frame_ids = arrays["frame_id"].astype(np.int64).tolist() + if frame_ids != expected_frame_ids or len(frame_ids) != len(set(frame_ids)): + raise ValueError(f"OOF bank frame sequence mismatch for {take}") + for key in FRAME_ARRAYS: + if arrays[key].shape[0] != len(frame_ids): + raise ValueError(f"OOF bank time dimension mismatch: {key}") + if np.issubdtype(arrays[key].dtype, np.floating) and key.startswith("pred_"): + if not np.isfinite(arrays[key]).all(): + raise ValueError(f"non-finite coarse prediction array: {key}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--run-provenance", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--folds-manifest", type=Path, required=True) + parser.add_argument("--fold", type=int, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args() + if "test" in str(args.manifest).lower() or "val" in args.manifest.name.lower(): + parser.error("OOF bank accepts only registered official-train heldout manifests") + contract = resolve_fold_contract( + args.folds_manifest, args.fold, args.manifest, args.run_provenance, + ) + checkpoint_hash = sha256(args.checkpoint) + if checkpoint_hash != args.expected_checkpoint_sha256: + parser.error("checkpoint hash differs from the registered extraction command") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + config_hash = sha256(args.config) + heldout_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (int(config["data"]["T"]),), (int(config["data"]["stride"]),), + max_clips=args.max_clips, + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + expected_frames = { + take: [frame for index in indices for frame in dataset.clips[index].frame_ids] + for take, indices in indices_by_take.items() + } + if any(len(frames) != len(set(frames)) for frames in expected_frames.values()): + raise ValueError("OOF bank requires non-overlapping heldout inference clips") + + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + validate_checkpoint_provenance( + checkpoint, + config=config, + config_path=args.config, + run_provenance_path=args.run_provenance, + provenance=contract["provenance"], + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + records = [] + for take_index, (take, clip_indices) in enumerate(indices_by_take.items(), start=1): + output = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "heldout_manifest_sha256": heldout_hash, + "fold_index": args.fold, + } + if output.exists(): + with np.load(output, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + validate_bank_arrays(arrays, **expected) + status = "reused" + else: + arrays = infer_take( + root=args.root, take=take, dataset=dataset, clip_indices=clip_indices, + model=model, device=device, dtype=dtype, + ) + arrays.update({ + "bank_version": np.asarray(BANK_VERSION, dtype=np.int32), + "take": np.asarray(take), + "subject": np.asarray(take.split("/")[0]), + "action_family": np.asarray(take.split("/")[1]), + "side_names": np.asarray(SIDES), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "heldout_manifest_sha256": np.asarray(heldout_hash), + "fold_index": np.asarray(args.fold, dtype=np.int32), + }) + validate_bank_arrays(arrays, **expected) + save_npz_atomic(output, arrays) + status = "written" + records.append({ + "take": take, "clips": len(clip_indices), "frames": len(expected_frames[take]), + "path": str(output.resolve()), "sha256": sha256(output), "status": status, + }) + print(f"[{take_index}/{len(indices_by_take)}] {take}: {status}", flush=True) + + total_frames = sum(record["frames"] for record in records) + full_fold = args.max_clips is None + if full_fold and total_frames != int(contract["fold"]["heldout"]["frames"]): + raise ValueError("OOF bank heldout frame coverage differs from frozen fold") + report = { + "status": "complete", + "bank_version": BANK_VERSION, + "result_role": "official_train_group_heldout_oof_predictions", + "experiment_class": "preregistered_data_construction", + "official_validation_used_for_assignment": False, + "official_test_used": False, + "oracle_information_at_inference": False, + "gt_usage": "bank targets and post-hoc residual audit only", + "fold": args.fold, + "seed": int(config["seed"]), + "heldout_subject": contract["fold"]["heldout_subject"], + "folds_manifest": {"path": str(args.folds_manifest.resolve()), "sha256": sha256(args.folds_manifest)}, + "train_manifest_sha256": contract["fold"]["train_manifest_sha256"], + "heldout_manifest": {"path": str(args.manifest.resolve()), "sha256": heldout_hash}, + "leakage_audit": contract["fold"]["leakage_audit"], + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, "step": int(checkpoint["step"])}, + "run_provenance": {"path": str(args.run_provenance.resolve()), "sha256": sha256(args.run_provenance)}, + "training_git_commit": contract["provenance"]["git_commit"], + "extractor_git_commit": subprocess.run(["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, check=False).stdout.strip(), + "scope": "full_fold" if full_fold else "smoke", + "clips": len(dataset), "frames": total_frames, "takes": records, + "surface_contract": { + "location": "coarse MANO projection only", + "depth_source": "original aligned H2O metric depth", + "surface": "frontmost projected MANO vertex per 4-pixel cell", + "silhouette": "packed quarter-resolution conservative projected vertex hull", + "solver": "bounded MAD-scaled Huber IRLS; translation-z only", + "hand_scale": "projected coarse MANO joint extent in model-resized pixels", + }, + "arrays": list(FRAME_ARRAYS), + } + (args.output_dir / "bank_manifest.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "fold": args.fold, "clips": report["clips"], + "frames": report["frames"], "takes": len(records), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_adaptation_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_adaptation_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9e5cbc986e127ee1269792135884adc311eaa1 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_adaptation_configs.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Build matched A1/A2 configs after strict external zero-shot is complete.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +from pathlib import Path +from typing import Any + +import yaml + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_adaptation_inputs( + selection: dict[str, Any], zero_shot_state: dict[str, Any], split: dict[str, Any], +) -> None: + if ( + selection.get("status") != "selected_external_generalist_no_h2o" + or selection.get("h2o_training_data_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("external selection is not adaptation-eligible") + if ( + zero_shot_state.get("status") != "complete" + or set(zero_shot_state.get("completed_ids", [])) != { + "h2o_strict_zero_shot_rgb_d_k", "h2o_strict_zero_shot_rgb_k", + "h2o_strict_zero_shot_rgb_only", + } + or zero_shot_state.get("official_test_used") is not False + or zero_shot_state.get("h2o_training_data_used") is not False + ): + raise ValueError("strict three-mode H2O zero-shot must complete before adaptation") + if ( + split.get("status") != "frozen_h2o_train_group_split" + or split.get("h2o_official_validation_used") is not False + or split.get("official_test_used") is not False + or split.get("recording_overlap") != [] + ): + raise ValueError("H2O train-only group split is invalid") + + +def adaptation_config( + base: dict[str, Any], selection: dict[str, Any], split: dict[str, Any], branch: str, +) -> dict[str, Any]: + config = copy.deepcopy(base) + config["name"] = f"phase7_{branch.lower()}_scale100k_s20260717" + config["experiment"] = { + "phase": 7, "branch": "h2o_adaptation", "stage": "adaptation_scale_100k", + "condition": branch, "uses_h2o_training_data": True, + "initialization_checkpoint_sha256": selection["checkpoint"]["sha256"], + "initialization_checkpoint_step": selection["checkpoint"]["step"], + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + h2o_source = { + "dataset": "H2O", "split_role": "official_train", "weight": 1.0, + "cache_manifest": split["fit"]["path"], "K_input_dropout": 0.0, + } + if branch == "A1": + sources = [h2o_source] + elif branch == "A2": + source_lookup = { + str(source["dataset"]).upper(): copy.deepcopy(source) + for source in base["data"]["sources"] + } + if set(source_lookup) != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("winning external config is not the E40 three-source mixture") + h2o_source["weight"] = 0.5 + replay_weights = {"HOT3D": 0.2, "HOI4D": 0.2, "ARCTIC": 0.1} + sources = [h2o_source] + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + source = source_lookup[dataset] + source["weight"] = replay_weights[dataset] + source["split_role"] = "external_train" + sources.append(source) + else: + raise ValueError(f"unknown adaptation condition: {branch}") + config["data"]["sources"] = sources + config["data"]["validation_sources"] = [{ + "dataset": "H2O", "split_role": "train_group_heldout", + "cache_manifest": split["heldout"]["path"], "K_input_dropout": 0.0, + }] + config["model"]["modality_dropout_prob"] = 0.0 + config["model"]["dinov3_trainable_last_blocks"] = 0 + return config + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-selection", type=Path, required=True) + parser.add_argument("--zero-shot-state", type=Path, required=True) + parser.add_argument("--h2o-train-split", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + selection = json.loads(args.external_selection.read_text(encoding="utf-8")) + zero_shot = json.loads(args.zero_shot_state.read_text(encoding="utf-8")) + split = json.loads(args.h2o_train_split.read_text(encoding="utf-8")) + validate_adaptation_inputs(selection, zero_shot, split) + base_path = Path(selection["config"]["path"]) + if sha256(base_path) != selection["config"]["sha256"]: + parser.error("selected external config hash mismatch") + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + args.output_dir.mkdir(parents=True) + outputs = {} + for branch in ("A1", "A2"): + config = adaptation_config(base, selection, split, branch) + output = args.output_dir / f"phase7_{branch.lower()}_scale100k_s20260717.yaml" + output.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + outputs[branch] = {"path": str(output.resolve()), "sha256": sha256(output)} + record = { + "status": "adaptation_configs_frozen", "configs": outputs, + "external_selection": { + "path": str(args.external_selection.resolve()), "sha256": sha256(args.external_selection), + }, + "strict_zero_shot_state": { + "path": str(args.zero_shot_state.resolve()), "sha256": sha256(args.zero_shot_state), + }, + "h2o_train_split": { + "path": str(args.h2o_train_split.resolve()), "sha256": sha256(args.h2o_train_split), + }, + "h2o_official_validation_used_for_selection": False, "official_test_used": False, + } + (args.output_dir / "freeze.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_arctic_manifests.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_arctic_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..0dee727076139bcc1bfab8100719f0369d8ff69d --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_arctic_manifests.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Build ARCTIC P2 train/val manifests without reading the P2 test list.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_p2_train_val_without_test(path: Path) -> dict[str, list[str]]: + lines: list[str] = [] + saw_test_key = False + with path.open("r", encoding="utf-8") as handle: + for line in handle: + if line.lstrip().startswith('"test"'): + saw_test_key = True + break + lines.append(line) + if not saw_test_key: + raise ValueError("protocol does not contain a test boundary") + prefix = "".join(lines).rstrip() + if prefix.endswith(","): + prefix = prefix[:-1] + record = json.loads(prefix + "\n}\n") + if set(record) != {"train", "val"}: + raise ValueError(f"expected only train/val before test boundary, got {set(record)}") + return record + + +def sequence_rows( + data_root: Path, sequence: str, split: str, clip_length: int, window_step: int, +) -> tuple[list[dict[str, Any]], list[str]]: + subject, take = sequence.split("/", 1) + mano_path = data_root / "raw_seqs" / subject / f"{take}.mano.npy" + camera_path = data_root / "raw_seqs" / subject / f"{take}.egocam.dist.npy" + image_dir = data_root / "cropped_images" / subject / take / "0" + missing = [str(path) for path in (mano_path, camera_path, image_dir) if not path.exists()] + if missing: + return [], missing + mano = np.load(mano_path, allow_pickle=True).item() + frame_count = int(len(mano["right"]["rot"])) + if frame_count != int(len(mano["left"]["rot"])): + raise ValueError(f"left/right frame count differs for {sequence}") + images = sorted(image_dir.glob("*.jpg")) + if len(images) != frame_count: + return [], [f"{sequence}: image count {len(images)} != MANO frames {frame_count}"] + rows = [] + for first in range(1, frame_count - clip_length + 2, window_step): + frame_ids = list(range(first, first + clip_length)) + rows.append({ + "dataset_id": "ARCTIC", + "protocol": "P2", + "split_role": f"arctic_p2_{split}", + "subject_id": subject, + "physical_recording_id": sequence, + "group_key": f"ARCTIC/{subject}/{sequence}", + "camera_id": "ego_view_0_rectified", + "frame_ids_1based": frame_ids, + "array_indices_0based": [value - 1 for value in frame_ids], + "image_paths": [str((image_dir / f"{value:05d}.jpg").resolve()) for value in frame_ids], + "mano_path": str(mano_path.resolve()), + "camera_path": str(camera_path.resolve()), + "depth_input_available": False, + "official_test_used": False, + }) + return rows, [] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--protocol", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--window-step", type=int, default=8) + parser.add_argument("--allow-documented-missing-sequence-exclusions", action="store_true") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + split = read_p2_train_val_without_test(args.protocol) + manifests = {} + missing: dict[str, list[str]] = {} + split_subjects: dict[str, set[str]] = {} + for role in ("train", "val"): + rows = [] + for sequence in split[role]: + sequence_values, absent = sequence_rows( + args.data_root, sequence, role, args.clip_length, args.window_step, + ) + rows.extend(sequence_values) + if absent: + missing[sequence] = absent + path = args.output_dir / f"arctic_p2_{role}_t{args.clip_length}.jsonl" + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + subjects = {row["subject_id"] for row in rows} + split_subjects[role] = subjects + manifests[role] = { + "path": str(path.resolve()), "sha256": sha256(path), + "clips": len(rows), "sequences": len({row["physical_recording_id"] for row in rows}), + "subjects": sorted(subjects), + } + overlap = sorted(split_subjects["train"] & split_subjects["val"]) + usable = not overlap and all(value["clips"] for value in manifests.values()) + status = ( + "passed" if usable and not missing else + "passed_with_documented_exclusions" + if usable and args.allow_documented_missing_sequence_exclusions else + "failed" + ) + report = { + "version": "phase7_arctic_p2_manifest_v1", + "status": status, + "protocol_path": str(args.protocol.resolve()), + "protocol_sha256": sha256(args.protocol), + "test_boundary_contract": "reader stops on the P2 test key before reading any test identity", + "clip_length": args.clip_length, "window_step": args.window_step, + "manifests": manifests, + "train_val_subject_overlap": overlap, + "missing_assets": missing, + "missing_sequence_policy": ( + "exclude entire physical recording from P2 train" + if args.allow_documented_missing_sequence_exclusions else "strict failure" + ), + "official_test_used": False, + } + (args.output_dir / "manifest_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not status.startswith("passed"): + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_continuation_manifest.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_continuation_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5feb4a5390224c6a49a11bd3846c9c91d88ea8 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_continuation_manifest.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Bind frozen 50k/100k external evaluations for final checkpoint selection.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from scripts.build_phase7_scale_eval_queue import input_mode + + +DATASETS = ("HOT3D", "HOI4D", "ARCTIC") + + +def build_manifest(evaluation_root: Path, condition: str, steps: tuple[int, ...]) -> dict: + evaluations = [] + for step in steps: + for dataset in DATASETS: + mode = input_mode(condition, dataset) + path = ( + evaluation_root + / f"{condition.lower()}_scale_step{step}_{dataset.lower()}_heldout2048_{mode}" + / "evaluation.json" + ).resolve() + if not path.is_file(): + raise ValueError(f"continuation evaluation missing: {path}") + report = json.loads(path.read_text(encoding="utf-8")) + if int(report.get("checkpoint_step", -1)) != step: + raise ValueError(f"continuation evaluation step mismatch: {path}") + evaluations.append({ + "candidate": f"{condition}_step{step}", "dataset": dataset, + "path": str(path), + }) + return { + "schema_version": "phase7_external_continuation_selection_v1", + "selection_split": "external_heldout_only", "datasets": list(DATASETS), + "condition": condition, "candidate_steps": list(steps), + "h2o_training_data_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--condition", default="E40", choices=("E40", "E70", "E100")) + parser.add_argument("--steps", type=int, nargs="+", default=(50000, 100000)) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + manifest = build_manifest(args.evaluation_root, args.condition, tuple(args.steps)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + print(json.dumps(manifest, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_h2o_zero_shot_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_h2o_zero_shot_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..75fc0a82c687ff6af3ff04114659af6756484fe7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_h2o_zero_shot_queue.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Build the hash-bound three-mode strict H2O zero-shot queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_h2o_zero_shot_queue import validate_queue + + +def build_queue(freeze_path: Path, root: Path, output_root: Path) -> dict: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + status = freeze.get("status") + if status not in { + "external_generalist_frozen", "external_architecture_candidate_frozen", + }: + raise ValueError("external freeze record is incomplete") + if status == "external_architecture_candidate_frozen" and ( + freeze.get("selected_within_family") is not True + or freeze.get("overall_external_generalist_winner") is not False + ): + raise ValueError("external architecture candidate role is ambiguous") + checkpoint = freeze["checkpoint_path"] + checkpoint_sha256 = freeze["checkpoint_sha256"] + manifest = freeze["h2o_validation_manifest"]["path"] + evaluations = [{ + "id": f"h2o_strict_zero_shot_{mode}", "input_mode": mode, + "config": freeze["config_path"], "checkpoint": checkpoint, + "checkpoint_sha256": checkpoint_sha256, + "freeze_record": str(freeze_path.resolve()), "root": str(root.resolve()), + "manifest": manifest, + "output_dir": str((output_root / mode).resolve()), + "bootstrap_resamples": 2000, + } for mode in INPUT_MODES] + queue = { + "schema_version": "phase7_h2o_strict_zero_shot_queue_v1", + "purpose": "One frozen external checkpoint evaluated once in three H2O input modes", + "external_freeze_status": status, + "allowed_physical_gpus": [0, 1, 2, 3], + "official_test_used": False, "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "evaluations": evaluations, + } + validate_queue(queue) + return queue + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + queue = build_queue(args.freeze_record, args.root, args.output_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_hoi4d_manifests.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_hoi4d_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebe2622b2f7c2957b904af4295816fe440fd0c9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_hoi4d_manifests.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Build deterministic group-isolated HOI4D train/held-out clip manifests.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +SERIALS = tuple(f"ZY2021080000{index}" for index in range(1, 5)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def discover_hand_frames(root: Path) -> dict[str, dict[int, set[str]]]: + recordings: dict[str, dict[int, set[str]]] = defaultdict(lambda: defaultdict(set)) + hand_root = root / "Hand_pose" + for side in ("left", "right"): + base = hand_root / f"handpose_{side}_hand" + for directory, _, filenames in os.walk(base): + frame_names = [name for name in filenames if name.endswith(".pickle")] + if not frame_names: + continue + relative = Path(directory).relative_to(base).as_posix() + for name in frame_names: + recordings[relative][int(Path(name).stem)].add(side) + return recordings + + +def split_for_serial(serial: str, heldout_serial: str) -> str: + if serial not in SERIALS: + raise ValueError(f"unknown HOI4D serial: {serial}") + return "heldout" if serial == heldout_serial else "train" + + +def recording_assets(root: Path, recording: str) -> tuple[Path, Path, Path]: + rgb = root / "HOI4D_release" / recording / "align_rgb" / "image.mp4" + depth = ( + root / "HOI4D_release" / "HOI4D_depth_video" / recording + / "align_depth" / "depth_video.avi" + ) + serial = recording.split("/", 1)[0] + K = root / "camera" / serial / "intrin.npy" + return rgb, depth, K + + +def make_rows( + root: Path, + recordings: dict[str, dict[int, set[str]]], + heldout_serial: str, + clip_length: int, + window_step: int, +) -> tuple[dict[str, list[dict[str, Any]]], list[dict[str, str]]]: + rows: dict[str, list[dict[str, Any]]] = {"train": [], "heldout": []} + missing: list[dict[str, str]] = [] + for recording in sorted(recordings): + rgb, depth, K = recording_assets(root, recording) + absent = [str(path) for path in (rgb, depth, K) if not path.is_file()] + if absent: + missing.append({"recording": recording, "missing": ";".join(absent)}) + continue + frames = recordings[recording] + available = sorted(frames) + if not available: + continue + serial, subject = recording.split("/")[:2] + split = split_for_serial(serial, heldout_serial) + frame_set = set(available) + for start in range(available[0], available[-1] + 1, window_step): + ids = list(range(start, start + clip_length)) + if not all(frame in frame_set for frame in ids): + continue + rows[split].append({ + "dataset_id": "HOI4D", + "split_role": f"external_{split}_group_split", + "serial_id": serial, + "subject_id": subject, + "physical_recording_id": recording, + "group_key": f"HOI4D/{subject}/{recording}", + "camera_id": serial, + "fps": 15.0, + "frame_ids": ids, + "timestamps_seconds": [frame / 15.0 for frame in ids], + "hand_sides": [sorted(frames[frame]) for frame in ids], + "rgb_video": str(rgb.resolve()), + "depth_video": str(depth.resolve()), + "K_path": str(K.resolve()), + "official_test_used": False, + }) + return rows, missing + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--heldout-serial", choices=SERIALS, default=SERIALS[-1]) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--window-step", type=int, default=8) + parser.add_argument("--allow-documented-missing-asset-exclusions", action="store_true") + args = parser.parse_args() + if args.clip_length <= 0 or args.window_step <= 0: + parser.error("clip length and window step must be positive") + args.output_dir.mkdir(parents=True, exist_ok=False) + recordings = discover_hand_frames(args.root) + rows, missing = make_rows( + args.root, recordings, args.heldout_serial, + args.clip_length, args.window_step, + ) + manifests = {} + for split, values in rows.items(): + path = args.output_dir / f"hoi4d_{split}_t{args.clip_length}.jsonl" + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in values), + encoding="utf-8", + ) + manifests[split] = { + "path": str(path.resolve()), "sha256": sha256(path), + "clips": len(values), + "subjects": sorted({row["subject_id"] for row in values}), + "recordings": len({row["physical_recording_id"] for row in values}), + "hand_frames": { + side: sum(side in sides for row in values for sides in row["hand_sides"]) + for side in ("left", "right") + }, + } + usable = all(rows.values()) + exclusions_allowed = bool(args.allow_documented_missing_asset_exclusions) + report = { + "version": "phase7_hoi4d_group_split_v1", + "status": ( + "passed" if usable and not missing else + "passed_with_documented_exclusions" if usable and exclusions_allowed else + "failed" + ), + "heldout_policy": "entire device/subject serial held out", + "heldout_serial": args.heldout_serial, + "grouping": "dataset, subject, complete physical recording", + "clip_length": args.clip_length, + "window_step": args.window_step, + "manifests": manifests, + "missing_assets": missing, + "missing_asset_recordings": len(missing), + "missing_asset_policy": ( + "excluded from both training and held-out evaluation; retained in audit" + if exclusions_allowed else "strict failure" + ), + "official_test_used": False, + } + (args.output_dir / "manifest_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not report["status"].startswith("passed"): + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_hot3d_manifests.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_hot3d_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6baac33d76e1336f6bdc82c4a417627d8c123c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_hot3d_manifests.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Build GT-only HOT3D recording-group manifests through official mask APIs.""" + +from __future__ import annotations + +import argparse +import bisect +from collections import Counter +import hashlib +import json +from pathlib import Path +import subprocess +import sys +from typing import Iterable + +from foundation_hand.data.hot3d_dataset import load_hot3d_api + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def participant_split(participants: Iterable[str]) -> tuple[set[str], set[str]]: + ordered = sorted(set(participants)) + if len(ordered) < 4: + raise ValueError("HOT3D participant split requires at least four GT participants") + heldout = {participant for index, participant in enumerate(ordered) if index % 4 == 3} + return set(ordered) - heldout, heldout + + +def contiguous_clips( + timestamps_ns: Iterable[int], + length: int, + max_gap_ns: int = 100_000_000, +) -> list[list[int]]: + timestamps = sorted(set(int(value) for value in timestamps_ns)) + runs: list[list[int]] = [] + current: list[int] = [] + for timestamp in timestamps: + if current and timestamp - current[-1] > max_gap_ns: + runs.append(current) + current = [] + current.append(timestamp) + if current: + runs.append(current) + clips: list[list[int]] = [] + for run in runs: + clips.extend(run[start : start + length] for start in range(0, len(run), length) if len(run[start : start + length]) == length) + return clips + + +def nearest_timestamp( + timestamp_ns: int, + reference_ns: list[int], + maximum_delta_ns: int, +) -> int | None: + position = bisect.bisect_left(reference_ns, int(timestamp_ns)) + candidates = reference_ns[max(0, position - 1) : position + 1] + if not candidates: + return None + nearest = min(candidates, key=lambda value: abs(value - timestamp_ns)) + return nearest if abs(nearest - timestamp_ns) <= maximum_delta_ns else None + + +def write_jsonl(path: Path, rows: list[dict]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--max-recordings", type=int) + parser.add_argument("--max-clips-per-recording-stream", type=int) + args = parser.parse_args() + if args.clip_length < 1: + parser.error("--clip-length must be positive") + + api = load_hot3d_api(args.toolkit_root) + source = args.toolkit_root.resolve() / "hot3d" + if str(source) not in sys.path: + sys.path.insert(0, str(source)) + from data_loaders.loader_hand_poses import load_hand_poses + from data_loaders.loader_masks import combine_mask_data, load_mask_data + + metadata_paths = sorted(args.root.glob("P*/metadata.json")) + metadata: list[tuple[Path, dict]] = [] + no_gt_count = 0 + for path in metadata_paths: + record = json.loads(path.read_text(encoding="utf-8")) + if record.get("have_hand_object_pose_gt") is not True: + no_gt_count += 1 + continue + metadata.append((path.parent, record)) + if args.max_recordings is not None: + metadata = metadata[: args.max_recordings] + participants = [record["participant_id"] for _, record in metadata] + train_participants, heldout_participants = participant_split(participants) + rows: dict[str, list[dict]] = {"train": [], "heldout": []} + skipped: Counter[str] = Counter() + counts: Counter[str] = Counter() + required_masks = ( + "mask_hand_visible.csv", + "mask_headset_pose_available.csv", + "mask_good_exposure.csv", + "mask_qa_pass.csv", + ) + for recording_dir, record in metadata: + missing = [ + name for name in required_masks + if not (recording_dir / "masks" / name).is_file() + ] + if missing: + skipped["missing_masks"] += 1 + continue + masks = [ + load_mask_data(str(recording_dir / "masks" / name)) + for name in required_masks + ] + combined = combine_mask_data(masks, "and") + hand_poses = load_hand_poses( + str(recording_dir / "mano_hand_pose_trajectory.jsonl") + ) + hand_timestamps = sorted(hand_poses) + streams = ["214-1"] if record["headset"] == "Aria" else ["1201-1", "1201-2"] + split = "train" if record["participant_id"] in train_participants else "heldout" + for stream_id in streams: + stream_mask = combined.data.get(stream_id) + if stream_mask is None: + skipped[f"missing_stream_{stream_id}"] += 1 + continue + timestamp_to_pose = { + timestamp: nearest_timestamp(timestamp, hand_timestamps, 20_000_000) + for timestamp, valid in stream_mask.items() if valid + } + timestamp_to_pose = { + timestamp: pose_timestamp + for timestamp, pose_timestamp in timestamp_to_pose.items() + if pose_timestamp is not None + } + clips = contiguous_clips(timestamp_to_pose, args.clip_length) + if args.max_clips_per_recording_stream is not None: + clips = clips[: args.max_clips_per_recording_stream] + for clip_index, timestamps in enumerate(clips): + rows[split].append({ + "dataset": "HOT3D", + "split": split, + "participant_id": record["participant_id"], + "recording_id": record["recording_name"], + "physical_recording_id": record["recording_name"], + "headset": record["headset"], + "stream_id": stream_id, + "clip_index_in_stream": clip_index, + "timestamps_ns": timestamps, + "hand_pose_timestamp_ns": [timestamp_to_pose[value] for value in timestamps], + "hand_count": [ + len(hand_poses[timestamp_to_pose[value]].poses) + for value in timestamps + ], + "have_hand_object_pose_gt": True, + "depth_input_available": False, + "K_input_dropout": 0.3, + "group_key": f"HOT3D/{record['participant_id']}/{record['recording_name']}", + }) + counts[f"{split}/{record['headset']}/{stream_id}"] += len(clips) + + args.output_dir.mkdir(parents=True, exist_ok=True) + paths = {} + for split, split_rows in rows.items(): + path = args.output_dir / f"hot3d_{split}_t{args.clip_length}.jsonl" + write_jsonl(path, split_rows) + paths[split] = {"path": str(path.resolve()), "sha256": sha256(path), "clips": len(split_rows)} + toolkit_commit = subprocess.run( + ["git", "-C", str(args.toolkit_root), "rev-parse", "HEAD"], + text=True, stdout=subprocess.PIPE, check=True, + ).stdout.strip() + audit = { + "status": "built", + "official_test_used": False, + "gt_metadata_records": len(metadata), + "excluded_no_gt_metadata_records": no_gt_count, + "train_participants": sorted(train_participants), + "heldout_participants": sorted(heldout_participants), + "participant_overlap": sorted(train_participants & heldout_participants), + "counts": dict(sorted(counts.items())), + "skipped": dict(sorted(skipped.items())), + "clip_length": args.clip_length, + "required_masks": list(required_masks), + "pose_contract": "nearest official MANO timestamp within 20ms; one or two hands allowed", + "toolkit": {"path": str(args.toolkit_root.resolve()), "git_commit": toolkit_commit}, + "manifests": paths, + } + output = args.output_dir / "hot3d_manifest_audit.json" + output.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") + print(json.dumps(audit, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_scale_eval_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_scale_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..104816c1155e66759d9276dae8052af0f372be82 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase7_scale_eval_queue.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Build a hash-bound formal evaluation queue for a matched scale step.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.run_phase7_heldout_cache_queue import output_complete + + +CONDITIONS = ("E40", "E70", "E100") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def stage_suffix(step: int) -> str: + suffixes = {2000: "2k", 10000: "10k", 50000: "50k", 100000: "100k"} + try: + return suffixes[step] + except KeyError as error: + raise ValueError(f"unsupported formal matched step: {step}") from error + + +def read_marker(run_root: Path, condition: str, step: int) -> dict[str, Any]: + marker_path = run_root / ".phase7_queue" / f"{condition}_scale_{stage_suffix(step)}.json" + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker["checkpoint"]) + config = Path(marker["config"]) + if ( + marker.get("status") != "complete" + or int(marker.get("completed_step", -1)) != step + or marker.get("official_test_used") is not False + or marker.get("h2o_training_data_used") is not False + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or not config.is_file() + or marker.get("config_sha256") != sha256(config) + ): + raise ValueError(f"scale marker failed frozen contract: {marker_path}") + return marker + + +def input_mode(condition: str, dataset: str) -> str: + if dataset == "HOI4D" and condition != "E100": + return "rgb_d_k" + return "rgb_k" + + +def build_queue( + plan: dict[str, Any], run_roots: dict[str, Path], step: int, + evaluation_root: Path, conditions: tuple[str, ...] = CONDITIONS, +) -> dict[str, Any]: + if plan.get("official_test_used") is not False or plan.get("h2o_used") is not False: + raise ValueError("formal cache plan is not external-only") + sources = {item["dataset"]: item for item in plan["sources"]} + if set(sources) != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("formal cache plan lacks the complete dataset grid") + for item in sources.values(): + if not output_complete(item): + raise ValueError(f"formal held-out cache is incomplete: {item['dataset']}") + markers = { + condition: read_marker(run_roots[condition], condition, step) + for condition in conditions + } + evaluations = [] + for condition in conditions: + marker = markers[condition] + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + source = sources[dataset] + mode = input_mode(condition, dataset) + evaluations.append({ + "id": f"{condition}_{dataset}_scale_step{step}_{mode}", + "config": marker["config"], + "checkpoint": marker["checkpoint"], + "checkpoint_sha256": marker["checkpoint_sha256"], + "cache_manifest": str( + (Path(source["output_dir"]) / "cache_manifest.jsonl").resolve() + ), + "input_mode": mode, + "output_dir": str(( + evaluation_root + / f"{condition.lower()}_scale_step{step}_{dataset.lower()}_heldout2048_{mode}" + ).resolve()), + "bootstrap_resamples": 2000, + }) + return { + "schema_version": "phase7_external_eval_queue_v1", + "purpose": f"Formal matched external scale evaluation at step {step}", + "matched_step": step, "selection_split": "external_heldout_only", + "official_test_used": False, "h2o_training_data_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--formal-cache-plan", type=Path, required=True) + parser.add_argument( + "--step", type=int, choices=(2000, 10000, 50000, 100000), required=True, + ) + parser.add_argument( + "--conditions", nargs="+", choices=CONDITIONS, default=list(CONDITIONS), + ) + parser.add_argument("--e40-run", type=Path, required=True) + parser.add_argument("--e70-run", type=Path, required=True) + parser.add_argument("--e100-run", type=Path, required=True) + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output queue already exists") + plan = json.loads(args.formal_cache_plan.read_text(encoding="utf-8")) + queue = build_queue( + plan, {"E40": args.e40_run, "E70": args.e70_run, "E100": args.e100_run}, + args.step, args.evaluation_root, tuple(args.conditions), + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_adaptation_eval_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_adaptation_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..73840a2414c7276121f0302064f82599ffb40c11 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_adaptation_eval_queue.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-mode H2O train-heldout adaptation evaluation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +HELDOUT = Path( + "/home/jiasen/foundation_hand/artifacts/phase7/manifests/" + "h2o_train_group_cv_v1/train_group_heldout.jsonl" +) +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, + condition: str, + step: int, + config: Path, + config_sha256: str, + checkpoint: Path, + checkpoint_sha256: str, + output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not condition or any(character.isspace() for character in condition): + raise ValueError("condition must be a nonempty whitespace-free identifier") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap_resamples must be positive") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + if not HELDOUT.is_file(): + raise ValueError("frozen H2O train-group-heldout manifest is missing") + evaluations = [ + { + "id": f"{condition}_step{step}_{input_mode}", + "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(HELDOUT.resolve()), + "cache_manifest_sha256": sha256(HELDOUT), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str( + (output_root / f"{condition}_step{step}_{input_mode}").resolve() + ), + } + for input_mode in INPUT_MODES + ] + return { + "schema_version": "phase8_adaptation_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "Three-mode H2O train-group-heldout selection evaluation.", + "selection_split": "h2o_train_group_heldout_only", + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, + step=args.step, + config=args.config, + config_sha256=args.config_sha256, + checkpoint=args.checkpoint, + checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_adaptation_forgetting_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_adaptation_forgetting_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8f458e2c336aefbba9a75f8127f54f089f1f6f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_adaptation_forgetting_queue.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Build hash-bound external forgetting diagnostics for an H2O-adapted model.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +DOMAINS = { + "HOT3D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), + "HOI4D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_d_k", + ), + "ARCTIC": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "arctic_val2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, + condition: str, + step: int, + config: Path, + config_sha256: str, + checkpoint: Path, + checkpoint_sha256: str, + output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not condition or any(character.isspace() for character in condition): + raise ValueError("condition must be a nonempty whitespace-free identifier") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap_resamples must be positive") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + evaluations = [] + for dataset, (manifest_string, input_mode) in DOMAINS.items(): + manifest = Path(manifest_string) + if not manifest.is_file() or "h2o" in str(manifest).lower(): + raise ValueError(f"external forgetting manifest is invalid: {manifest}") + evaluations.append({ + "id": f"{condition}_step{step}_{dataset}_{input_mode}", + "dataset": dataset, + "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str( + (output_root / f"{condition}_step{step}" / f"{dataset}_{input_mode}").resolve() + ), + }) + return { + "schema_version": "phase8_adaptation_forgetting_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "External held-out forgetting diagnostic only; never used for H2O selection.", + "evaluation_split": "external_heldout_forgetting_diagnostic_only", + "selection_use": False, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, + config=args.config, config_sha256=args.config_sha256, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_egodexter_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_egodexter_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..e2873ce3d5a27694cfbb51342326605472cc5f09 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_egodexter_queue.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Build one frozen model's six-condition EgoDexter zero-shot queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_egodexter_zero_shot import sha256, validate_freeze_record + + +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") +INFERENCE_MODES = ("offline", "causal") + + +def build_queue( + freeze_path: Path, model_id: str, root: Path, output_root: Path, +) -> dict[str, Any]: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + models = {item["id"]: item for item in freeze.get("models", [])} + if model_id not in models: + raise ValueError("model is absent from the final freeze") + model = models[model_id] + checkpoint = Path(model["checkpoint"]) + if not checkpoint.is_file() or sha256(checkpoint) != model["checkpoint_sha256"]: + raise ValueError("frozen checkpoint is missing or SHA256 differs") + if not root.is_dir() or not (root / "data").is_dir(): + raise ValueError("EgoDexter root is invalid") + evaluations = [] + for inference_mode in INFERENCE_MODES: + config = Path(model["inference_configs"][inference_mode]["path"]) + validate_freeze_record( + freeze, model_id, model["checkpoint_sha256"], config, inference_mode, + ) + for input_mode in INPUT_MODES: + evaluations.append({ + "id": f"{model_id}_{inference_mode}_{input_mode}", + "model_id": model_id, + "freeze_record": str(freeze_path.resolve()), + "config": str(config.resolve()), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": model["checkpoint_sha256"], + "root": str(root.resolve()), + "input_mode": input_mode, + "inference_mode": inference_mode, + "window": 8, + "output_dir": str((output_root / inference_mode / input_mode).resolve()), + }) + return { + "schema_version": "phase8_egodexter_zero_shot_queue_v1", + "model_id": model_id, + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--model-id", required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + queue = build_queue(args.freeze_record, args.model_id, args.root, args.output_root) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_external_tail_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_external_tail_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..57d07512de8608b779e00ee27b66ee001473fca7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_external_tail_queue.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Build a hash-bound 100k-to200k minimum-LR external continuation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + +import yaml + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, condition: str, config_path: Path, config_sha256: str, + output_dir: Path, checkpoint: Path, checkpoint_sha256: str, + resume_step: int = 100000, end_step: int = 200000, +) -> dict[str, Any]: + if not config_path.is_file() or sha256(config_path) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("resume checkpoint is missing or SHA256 differs") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + if config.get("experiment", {}).get("branch") != "external_only": + raise ValueError("schedule tail is restricted to external-only configs") + max_steps = int(config["protocol"]["max_steps"]) + if max_steps != resume_step or not end_step > resume_step: + raise ValueError("tail requires resume_step=config max_steps < end_step") + expected_checkpoint = output_dir / f"step_{resume_step:07d}_final.pt" + if checkpoint.resolve() != expected_checkpoint.resolve(): + raise ValueError("checkpoint path is not the final artifact in output_dir") + required_caches = [] + for source in config["data"]["sources"]: + manifest = Path(source["cache_manifest"]) + report_path = manifest.parent / "cache_report.json" + if not manifest.is_file() or not report_path.is_file(): + raise ValueError(f"source cache is incomplete: {manifest}") + report = json.loads(report_path.read_text(encoding="utf-8")) + clips = report.get("clips", report.get("cached_clips")) + recorded = report.get("cache_manifest", {}) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or int(clips or -1) <= 0 + or recorded.get("sha256") != sha256(manifest) + ): + raise ValueError(f"source cache report is not hash-valid: {report_path}") + required_caches.append({ + "id": f"{source['dataset']}_{clips}", + "report": str(report_path.resolve()), + "manifest": str(manifest.resolve()), + "expected_clips": int(clips), + }) + return { + "schema_version": "phase8_external_schedule_tail_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": f"Exact-resume {condition} from {resume_step} to {end_step} at the registered minimum LR.", + "official_test_used": False, "h2o_training_data_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], + "required_caches": required_caches, + "stages": [{ + "id": f"{condition}_{end_step}_min_lr_tail", + "config": str(config_path.resolve()), + "config_sha256": config_sha256, + "output_dir": str(output_dir.resolve()), + "resume_from_step": resume_step, + "resume_checkpoint_sha256": checkpoint_sha256, + "stop_after_step": end_step, + "allow_schedule_tail": True, + }], + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--resume-step", type=int, default=100000) + parser.add_argument("--end-step", type=int, default=200000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, config_path=args.config, + config_sha256=args.config_sha256, output_dir=args.output_dir, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + resume_step=args.resume_step, end_step=args.end_step, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_h2o_adapted_validation_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_h2o_adapted_validation_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c9eec9bc1340e152be7824e02131c5ed03efc0b7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_h2o_adapted_validation_queue.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-mode formal H2O adaptation validation queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_external import sha256 +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_h2o_adapted_validation_queue import validate_queue + + +def build_queue(freeze_path: Path, root: Path, output_root: Path) -> dict[str, Any]: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + if ( + freeze.get("status") != "h2o_adaptation_candidate_frozen" + or freeze.get("selection_split") != "h2o_train_group_heldout_only" + or freeze.get("h2o_official_validation_used_for_selection") is not False + or freeze.get("h2o_training_data_used") is not True + or freeze.get("official_test_used") is not False + ): + raise ValueError("adaptation freeze record is incomplete") + checkpoint = freeze.get("checkpoint", {}) + config = freeze.get("config", {}) + manifest = freeze.get("h2o_validation_manifest", {}) + for record, label in ( + (checkpoint, "checkpoint"), (config, "config"), (manifest, "manifest"), + ): + path = Path(record.get("path", "")) + if not path.is_file() or sha256(path) != record.get("sha256"): + raise ValueError(f"frozen {label} is missing or SHA256 differs") + if Path(manifest["path"]).name != "official_val.jsonl": + raise ValueError("only canonical H2O official validation is allowed") + if set(freeze.get("frozen_h2o_input_modes", [])) != set(INPUT_MODES): + raise ValueError("adaptation freeze record does not bind all input modes") + if not root.is_dir() or not (root / "subject3").is_dir(): + raise ValueError("H2O root does not contain the canonical validation subject") + evaluations = [{ + "id": f"{freeze['winner']}_formal_{mode}", + "input_mode": mode, + "config": str(Path(config["path"]).resolve()), + "checkpoint": str(Path(checkpoint["path"]).resolve()), + "checkpoint_sha256": checkpoint["sha256"], + "freeze_record": str(freeze_path.resolve()), + "root": str(root.resolve()), + "manifest": str(Path(manifest["path"]).resolve()), + "output_dir": str((output_root / mode).resolve()), + "bootstrap_resamples": 2000, + } for mode in INPUT_MODES] + queue = { + "schema_version": "phase8_h2o_adapted_validation_queue_v1", + "purpose": "Formal validation of one train-heldout-frozen H2O adaptation candidate.", + "selection_split": "h2o_train_group_heldout_only", + "allowed_physical_gpus": [0, 1, 2, 3], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "evaluations": evaluations, + } + validate_queue(queue) + return queue + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + queue = build_queue(args.freeze_record, args.root, args.output_root) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_left_root_relative_sidecars.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_left_root_relative_sidecars.py new file mode 100644 index 0000000000000000000000000000000000000000..1613c74abf4e6474d9947f19ff38ba45a442d1aa --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_left_root_relative_sidecars.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Attach target-only historical-left joint supervision to existing caches.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def left_only_target( + target: torch.Tensor, + source_valid: torch.Tensor, + translation_valid: torch.Tensor, + frame_valid: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + if target.shape[-2:] != (21, 3): + raise ValueError("target must end in [21,3]") + if source_valid.shape != target.shape[:-1]: + raise ValueError("source-valid shape differs from target") + if translation_valid.shape != target.shape[:-2]: + raise ValueError("translation-valid shape differs from target") + if frame_valid.shape != target.shape[:-3]: + raise ValueError("frame-valid shape differs from target") + valid = ( + source_valid.bool() + & translation_valid.bool()[..., None] + & frame_valid.bool()[..., None, None] + ) + valid[..., 1, :] = False + target = target.clone().masked_fill(~valid[..., None], float("nan")) + return target, valid + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--expected-source-manifest-sha256", required=True) + parser.add_argument("--expected-cache-manifest-sha256", required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--resume", action="store_true") + parser.add_argument("--torch-threads", type=int, default=0) + args = parser.parse_args() + if sha256(args.source_manifest) != args.expected_source_manifest_sha256: + parser.error("source manifest SHA256 differs") + if sha256(args.cache_manifest) != args.expected_cache_manifest_sha256: + parser.error("cache manifest SHA256 differs") + if args.torch_threads < 0: + parser.error("--torch-threads cannot be negative") + if args.torch_threads: + torch.set_num_threads(args.torch_threads) + torch.set_num_interop_threads(1) + if args.resume: + if not (args.output_dir / "sidecars").is_dir(): + parser.error("--resume requires an existing sidecars directory") + elif args.output_dir.exists(): + parser.error("output directory already exists") + if args.dataset == "HOI4D": + if args.root is None: + parser.error("HOI4D requires --root") + dataset = HOI4DClipDataset( + args.root, args.source_manifest, args.mano_root, + ) + else: + dataset = ARCTICClipDataset(args.source_manifest, args.mano_root) + rows = read_jsonl(args.cache_manifest) + args.output_dir.mkdir(parents=True, exist_ok=args.resume) + sidecars = args.output_dir / "sidecars" + sidecars.mkdir(exist_ok=args.resume) + augmented: list[dict[str, Any] | None] = [None] * len(rows) + left_hand_frames = 0 + right_joint_count = 0 + root_norm_max_mm = 0.0 + started = time.monotonic() + order = sorted( + range(len(rows)), + key=lambda position: ( + str(rows[position]["physical_recording_id"]), + int(rows[position]["source_clip_index"]), + ), + ) + for processed, position in enumerate(order, start=1): + row = rows[position] + source_index = int(row["source_clip_index"]) + path = sidecars / f"clip_{source_index:07d}.npz" + if path.is_file() and args.resume: + try: + with np.load(path, allow_pickle=False) as sidecar: + if set(sidecar.files) != { + "joint3d_root_relative", "joint3d_root_relative_valid", + }: + raise ValueError("unexpected sidecar keys") + target = torch.from_numpy(sidecar["joint3d_root_relative"]) + valid = torch.from_numpy( + sidecar["joint3d_root_relative_valid"] + ).bool() + except (OSError, ValueError, EOFError): + preserved = path.with_name( + f"{path.name}.invalid_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}" + ) + path.rename(preserved) + if not path.is_file(): + target, source_valid = dataset.source_root_relative_joint3d(source_index) + with np.load(row["cache_path"], allow_pickle=False) as cache: + translation_valid = torch.from_numpy(cache["translation_valid"]).bool() + frame_valid = torch.from_numpy(cache["frame_valid"]).bool() + target, valid = left_only_target( + target, source_valid, translation_valid, frame_valid, + ) + temporary = path.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed( + handle, + joint3d_root_relative=target.numpy(), + joint3d_root_relative_valid=valid.numpy(), + ) + temporary.replace(path) + output_row = dict(row) + output_row.update({ + "joint3d_root_relative_sidecar_path": str(path.resolve()), + "joint3d_root_relative_sidecar_sha256": sha256(path), + "joint3d_root_relative_scope": "historical_left_only", + }) + augmented[position] = output_row + left_hand_frames += int(valid[..., 0, :].any(-1).sum()) + right_joint_count += int(valid[..., 1, :].sum()) + finite_roots = valid[..., 0, 0] + if finite_roots.any(): + root_norm_max_mm = max( + root_norm_max_mm, + float(torch.linalg.vector_norm(target[..., 0, 0, :][finite_roots], dim=-1).max() * 1000.0), + ) + if processed % 500 == 0 or processed == len(order): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": processed, + "clips": len(order), + "clips_per_second": processed / max(elapsed, 1e-9), + "eta_seconds": (len(order) - processed) / max(processed / elapsed, 1e-9), + }), flush=True) + if any(row is None for row in augmented): + raise RuntimeError("augmented manifest contains missing rows") + manifest = args.output_dir / "cache_manifest.jsonl" + manifest.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in augmented), + encoding="utf-8", + ) + elapsed = time.monotonic() - started + report = { + "schema_version": "phase8_left_root_relative_sidecars_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "dataset": args.dataset, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "base_cache_manifest": {"path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest)}, + "augmented_cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "clips": len(rows), + "left_hand_frames": left_hand_frames, + "right_valid_joint_count": right_joint_count, + "root_norm_max_mm": root_norm_max_mm, + "shape_supervision_restored": False, + "vertices_supervision_restored": False, + "camera_joint3d_supervision_restored": False, + "wall_seconds": elapsed, + "clips_per_second": len(rows) / max(elapsed, 1e-9), + "bytes": sum(path.stat().st_size for path in sidecars.iterdir()), + "resume_invocation": bool(args.resume), + "torch_threads": args.torch_threads or torch.get_num_threads(), + "official_test_used": False, + } + report_path = args.output_dir / "sidecar_report.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if not left_hand_frames or right_joint_count or root_norm_max_mm >= 1e-4: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_specialist_eval_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_specialist_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa0f9aa72435130c16fcd98a84a0963d098f45f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_specialist_eval_queue.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-domain evaluation queue for one external checkpoint.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +DOMAINS = { + "HOT3D": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_only"), + }, + "HOI4D": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_d_k", "rgb_only"), + }, + "ARCTIC": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_val2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_only"), + }, +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, condition: str, step: int, config: Path, config_sha256: str, + checkpoint: Path, checkpoint_sha256: str, output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap resamples must be positive") + evaluations = [] + for dataset, domain in DOMAINS.items(): + manifest = Path(domain["cache_manifest"]) + if not manifest.is_file(): + raise ValueError(f"held-out manifest is missing: {manifest}") + slug = dataset.lower() + for input_mode in domain["input_modes"]: + evaluations.append({ + "id": f"{condition}_step{step}_{dataset}_{input_mode}", + "dataset": dataset, + "matrix_role": "primary_matched_rgb_k" if input_mode == "rgb_k" else "input_diagnostic", + "config": str(config.resolve()), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str((output_root / f"{condition}_step{step}" / f"{slug}_{input_mode}").resolve()), + }) + return { + "schema_version": "phase8_specialist_cross_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "Frozen matched RGB-K cross-domain matrix plus RGB-only and HOI4D RGB-D-K diagnostics.", + "condition": condition, "checkpoint_step": step, + "h2o_training_data_used": False, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, + config=args.config, config_sha256=args.config_sha256, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_stage7_eval_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_stage7_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5db2287015b04a005106f0656ae4231c42687dcb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase8_stage7_eval_queue.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Build a hash-bound Stage 7 external held-out evaluation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase8_specialist_eval_queue import sha256 + + +STAGE7_DOMAINS = { + "HOT3D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), + "HOI4D": ( + "/SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/" + "hoi4d_heldout_left_root_relative_sidecars_v1/cache_manifest.jsonl", + "rgb_d_k", + ), + "ARCTIC": ( + "/SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/" + "arctic_p2_val_left_root_relative_sidecars_v1/cache_manifest.jsonl", + "rgb_k", + ), +} + + +def build_queue( + *, condition: str, step: int, config: Path, config_sha256: str, + checkpoint: Path, checkpoint_sha256: str, output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if condition not in {"L0_sampler_only", "L1_left_root_relative"}: + raise ValueError("condition is not a frozen Stage 7 condition") + if step != 10000 or bootstrap_resamples <= 0: + raise ValueError("Stage 7 evaluation requires step10k and positive resamples") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + evaluations = [] + for dataset, (manifest_string, input_mode) in STAGE7_DOMAINS.items(): + manifest = Path(manifest_string) + if not manifest.is_file() or "h2o" in str(manifest).lower(): + raise ValueError(f"invalid Stage 7 held-out manifest: {manifest}") + evaluations.append({ + "id": f"{condition}_step10000_{dataset}_{input_mode}", + "dataset": dataset, "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, "bootstrap_resamples": bootstrap_resamples, + "output_dir": str((output_root / condition / f"{dataset}_{input_mode}").resolve()), + }) + return { + "schema_version": "phase8_stage7_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "condition": condition, "checkpoint_step": step, + "evaluation_split": "external_heldout_only", + "h2o_training_data_used": False, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, config=args.config, + config_sha256=args.config_sha256, checkpoint=args.checkpoint, + checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_final_deployment_plan.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_final_deployment_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..bd59e8112af6f89be4d8c8387647095fdb424bf8 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_final_deployment_plan.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""Build the post-selection formal-validation and deployment-audit job plan.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +LENGTHS = [1, 2, 4, 8, 16, 32, 64] +ORDERING_LENGTHS = [31, 64, 257] + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def derive_causal_config(config: dict[str, Any]) -> dict[str, Any]: + result = deepcopy(config) + if result.get("model", {}).get("temporal_attention_mode") != "bidirectional": + raise ValueError("final checkpoint config is not the frozen bidirectional control") + result["model"]["temporal_attention_mode"] = "causal" + return result + + +def write_causal_config(source: Path, output: Path) -> str: + original = yaml.safe_load(source.read_text(encoding="utf-8")) + causal = derive_causal_config(original) + output.parent.mkdir(parents=True, exist_ok=True) + rendered = yaml.safe_dump(causal, sort_keys=False) + if output.exists(): + if yaml.safe_load(output.read_text(encoding="utf-8")) != causal: + raise ValueError("existing final causal config differs") + else: + temporary = output.with_suffix(".tmp") + temporary.write_text(rendered, encoding="utf-8") + temporary.replace(output) + return sha256(output) + + +def build_plan( + *, freeze_path: Path, freeze_state_path: Path, output_root: Path, + worker_state_root: Path, causal_config_path: Path, h2o_root: Path, +) -> dict[str, Any]: + state = read_json(freeze_state_path) + freeze = read_json(freeze_path) + if ( + state.get("status") != "complete" + or state.get("freeze_sha256") != sha256(freeze_path) + or freeze.get("status") != "phase9_final_unified_checkpoint_frozen" + or freeze.get("h2o_official_validation_used") is not False + or freeze.get("h2o_official_validation_used_for_selection") is not False + or freeze.get("official_test_used") is not False + ): + raise ValueError("final deployment freeze is incomplete or unbound") + checkpoint = freeze["checkpoint"] + config = freeze["config"] + validation = freeze["h2o_validation_manifest"] + training = freeze["h2o_training_manifest"] + for record, label in ( + (checkpoint, "checkpoint"), (config, "config"), + (validation, "validation manifest"), (training, "training manifest"), + ): + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"frozen final {label} differs") + causal_sha = write_causal_config(Path(config["path"]), causal_config_path) + if not h2o_root.is_dir(): + raise ValueError("canonical H2O root is missing") + common = { + "checkpoint": checkpoint["path"], + "checkpoint_sha256": checkpoint["sha256"], + "checkpoint_step": checkpoint["step"], + "config": config["path"], "config_sha256": config["sha256"], + "freeze_record": str(freeze_path.resolve()), + "freeze_record_sha256": sha256(freeze_path), + "root": str(h2o_root.resolve()), + } + jobs = [] + for gpu, mode in enumerate(INPUT_MODES): + jobs.append({ + **common, "id": f"formal_{mode}", "kind": "formal_validation", + "physical_gpu_id": gpu, "input_mode": mode, + "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output_dir": str((output_root / "formal_h2o" / mode).resolve()), + }) + jobs.append({ + **common, "id": "variable_length", "kind": "variable_length", + "physical_gpu_id": 0, "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output": str((output_root / "audits" / "variable_length.json").resolve()), + "lengths": LENGTHS, + }) + for index, frames in enumerate(ORDERING_LENGTHS, start=1): + for mode in ("offline", "causal"): + job_config = config if mode == "offline" else { + "path": str(causal_config_path.resolve()), "sha256": causal_sha, + } + jobs.append({ + **common, "id": f"{mode}_w8_{frames}", "kind": "sequence", + "physical_gpu_id": index, "mode": mode, "window": 8, + "frames": frames, "config": job_config["path"], + "config_sha256": job_config["sha256"], + "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output": str(( + output_root / "audits" / f"{mode}_w8_{frames}.json" + ).resolve()), + }) + jobs.append({ + **common, "id": "latency_vram", "kind": "profile", + "physical_gpu_id": 3, "manifest": training["path"], + "manifest_sha256": training["sha256"], + "resolution_hw": freeze["resolution_hw"], + "output": str((output_root / "audits" / "latency_vram.json").resolve()), + }) + ids = [job["id"] for job in jobs] + outputs = [job.get("output", job.get("output_dir")) for job in jobs] + if len(jobs) != 11 or len(set(ids)) != 11 or len(set(outputs)) != 11: + raise ValueError("final deployment jobs are not unique and complete") + workers = [] + for gpu in range(4): + workers.append({ + "id": f"gpu{gpu}", "physical_gpu_id": gpu, + "state": str((worker_state_root / f"gpu{gpu}_state.json").resolve()), + "job_ids": [job["id"] for job in jobs if job["physical_gpu_id"] == gpu], + }) + assigned = [identifier for worker in workers for identifier in worker["job_ids"]] + if sorted(assigned) != sorted(ids) or len(set(assigned)) != 11: + raise ValueError("final deployment worker assignment overlaps or omits jobs") + return { + "schema_version": "phase9_final_deployment_plan_v1", + "status": "frozen_ready_post_selection", + "created_utc": freeze["created_utc"], + "freeze": {"path": str(freeze_path.resolve()), "sha256": sha256(freeze_path)}, + "winner": freeze["winner"], + "selected_mechanism": freeze["selected_mechanism"], + "resolution_hw": freeze["resolution_hw"], + "shared_augmentation": freeze["shared_augmentation"], + "checkpoint": checkpoint, "config": config, + "causal_config": { + "path": str(causal_config_path.resolve()), "sha256": causal_sha, + "only_change": "model.temporal_attention_mode=causal", + }, + "jobs": jobs, "workers": workers, + "official_validation_checkpoint_count": 1, + "formal_validation_modes": list(INPUT_MODES), + "variable_lengths": LENGTHS, + "sequence_contract": { + "offline_window": 8, "causal_window": 8, + "ordering_lengths": ORDERING_LENGTHS, + }, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze", type=Path, required=True) + parser.add_argument("--freeze-state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--causal-config", type=Path, required=True) + parser.add_argument("--h2o-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + freeze_path=args.freeze, freeze_state_path=args.freeze_state, + output_root=args.output_root, worker_state_root=args.worker_state_root, + causal_config_path=args.causal_config, h2o_root=args.h2o_root, + ) + if args.output.exists(): + if read_json(args.output) != plan: + raise ValueError("existing final deployment plan differs") + else: + atomic_json(args.output, plan) + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_plan_state_v1", + "status": "complete", "plan": str(args.output.resolve()), + "plan_sha256": sha256(args.output), "job_count": len(plan["jobs"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_plan_state_v1", + "status": "failed_resumable", + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }) + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_fold_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_fold_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..e98a67efcafc5b55c0d5ea9199882374ee8b7a3c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_fold_configs.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Generate hash-bound six-fold Phase 9 unified training configurations.""" + +from __future__ import annotations + +import argparse +import copy +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path + +import yaml + +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--multifold-index", type=Path, required=True) + parser.add_argument("--base-config", type=Path, action="append", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--run-root", type=Path, required=True) + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--data-readiness-state", type=Path, required=True) + parser.add_argument("--data-finalize-plan-sha256", required=True) + parser.add_argument("--initialization-checkpoint", type=Path, required=True) + parser.add_argument("--initialization-checkpoint-sha256", required=True) + parser.add_argument( + "--refresh", action="store_true", + help="Replace preregistered configs only when no training checkpoint exists.", + ) + args = parser.parse_args() + if (args.output_dir.exists() or args.registry.exists()) and not args.refresh: + parser.error("fold config output and registry must be new") + if args.refresh and args.run_root.exists() and any(args.run_root.rglob("*.pt")): + parser.error("cannot refresh fold configs after a training checkpoint exists") + if sha256(args.initialization_checkpoint) != args.initialization_checkpoint_sha256: + parser.error("initialization checkpoint SHA256 differs") + index = json.loads(args.multifold_index.read_text(encoding="utf-8")) + if index.get("status") != "complete" or index.get("official_test_used") is not False: + parser.error("multifold index is incomplete or lacks test isolation") + folds = [str(fold["id"]) for fold in index["folds"]] + args.output_dir.mkdir(parents=True, exist_ok=args.refresh) + conditions = [] + for base_path in args.base_config: + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + mixture = str(base["experiment"]["condition"]) + for fold in folds: + config = copy.deepcopy(base) + condition = f"{mixture}_{fold}" + config["name"] = f"phase9_{condition.lower()}_s20260717" + config["experiment"]["condition"] = condition + config["experiment"]["h2o_selection_fold"] = fold + h2o = next( + source for source in config["data"]["sources"] + if str(source["dataset"]).upper() == "H2O" + ) + h2o["cache_manifest"] = str( + (args.multifold_index.parent / f"{fold}_train.jsonl").resolve() + ) + config["data"]["validation_sources"] = [{ + "dataset": "H2O", "source_id": f"H2O_{fold}_heldout", + "split_role": "train_fold_heldout", + "cache_manifest": str( + (args.multifold_index.parent / f"{fold}_heldout.jsonl").resolve() + ), + "K_input_dropout": 0.0, + }] + path = args.output_dir / f"{condition.lower()}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + errors = validate_phase9_unified_contract(config, path) + if errors: + raise ValueError(f"invalid generated fold config {path}: {'; '.join(errors)}") + max_steps = int(config["protocol"]["max_steps"]) + conditions.append({ + "condition": condition, + "mixture": mixture, + "h2o_selection_fold": fold, + "config": str(path.resolve()), "config_sha256": sha256(path), + "initialization_checkpoint": str(args.initialization_checkpoint.resolve()), + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "output_dir": str((args.run_root / condition.lower()).resolve()), + "log_dir": str((args.run_root.parent / "queues" / "folds" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"scale{max_steps}", "stop_after_step": max_steps}, + ], + }) + registry = { + "schema_version": "phase9_h2o_multifold_training_queue_v1", + "status": "frozen_before_fold_training", + "created_utc": datetime.now(timezone.utc).isoformat(), + "multifold_index": { + "path": str(args.multifold_index.resolve()), + "sha256": sha256(args.multifold_index), + }, + "data_readiness_state": str(args.data_readiness_state.resolve()), + "data_finalize_plan_sha256": args.data_finalize_plan_sha256, + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "allowed_physical_gpus": [0, 1, 2, 3], + "prohibited_physical_gpus": [4, 5], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "conditions": conditions, + "shards": { + str(shard): [ + condition["condition"] for index, condition in enumerate(conditions) + if index % 3 == shard + ] + for shard in range(3) + }, + } + args.registry.parent.mkdir(parents=True, exist_ok=True) + args.registry.write_text(json.dumps(registry, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "registry": str(args.registry.resolve()), "sha256": sha256(args.registry), + "conditions": len(conditions), "shards": registry["shards"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_h2o_multifold.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_h2o_multifold.py new file mode 100644 index 0000000000000000000000000000000000000000..89dc683c2a03af0cb1fa1de79ebed7e7d3cf24bb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_h2o_multifold.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Build deterministic H2O official-train-only subject and family folds.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.audit_phase9_source_coverage import quantiles + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def family(row: dict[str, Any]) -> str: + parts = str(row["physical_recording_id"]).split("/") + if len(parts) < 2 or parts[1][:1] not in {"h", "k", "o"}: + raise ValueError("H2O recording lacks h/k/o family") + return parts[1][:1] + + +def fold_definitions(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + subjects = sorted({str(row["subject_id"]) for row in rows}) + families = sorted({family(row) for row in rows}) + if subjects != ["subject1", "subject2", "subject3"] or families != ["h", "k", "o"]: + raise ValueError("unexpected H2O official-train subjects or families") + definitions = [ + {"id": f"loso_{subject}", "axis": "subject", "heldout_value": subject} + for subject in subjects + ] + definitions.extend( + {"id": f"lofamily_{value}", "axis": "family", "heldout_value": value} + for value in families + ) + return definitions + + +def split_rows( + rows: list[dict[str, Any]], definition: dict[str, Any], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + if definition["axis"] == "subject": + heldout = [row for row in rows if row["subject_id"] == definition["heldout_value"]] + else: + heldout = [row for row in rows if family(row) == definition["heldout_value"]] + heldout_groups = {row["physical_recording_id"] for row in heldout} + train = [row for row in rows if row["physical_recording_id"] not in heldout_groups] + train_groups = {row["physical_recording_id"] for row in train} + if not train or not heldout or train_groups & heldout_groups: + raise ValueError("H2O fold is empty or leaks a physical recording") + if len(train) + len(heldout) != len(rows): + raise ValueError("H2O fold does not partition the cache") + return train, heldout + + +def numeric_stats(rows: list[dict[str, Any]]) -> dict[str, Any]: + side_frames = [0, 0] + hand_sizes: list[float] = [] + depths: list[float] = [] + for row in rows: + with np.load(row["cache_path"], allow_pickle=False) as archive: + valid_frame = archive["frame_valid"].astype(bool) + translation_valid = archive["translation_valid"].astype(bool) + translation = archive["wrist_root_translation"] + joint_valid = archive["joint2d_valid"].astype(bool) + joints = archive["joint2d"] + image_hw = archive["image_hw"] + height, width = int(image_hw[0]), int(image_hw[1]) + for time_index in np.flatnonzero(valid_frame): + for side in range(2): + if not translation_valid[time_index, side]: + continue + side_frames[side] += 1 + depths.append(float(translation[time_index, side, 2])) + points = joints[time_index, side] + valid = joint_valid[time_index, side] & np.isfinite(points).all(axis=-1) + valid &= ( + (points[:, 0] >= 0) & (points[:, 0] < width) + & (points[:, 1] >= 0) & (points[:, 1] < height) + ) + if valid.any(): + extent = points[valid].max(axis=0) - points[valid].min(axis=0) + hand_sizes.append(float(extent.max())) + return { + "left_hand_frames": side_frames[0], "right_hand_frames": side_frames[1], + "wrist_depth_m": quantiles(depths), + "projected_hand_size_px": quantiles(hand_sizes), + "family_clips": dict(sorted(Counter(family(row) for row in rows).items())), + } + + +def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + temporary.replace(path) + + +def build( + cache_manifest: Path, cache_report: Path, output_dir: Path, +) -> dict[str, Any]: + report = json.loads(cache_report.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" or report.get("dataset") != "H2O" + or report.get("split_role") != "official_train" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest) + ): + raise ValueError("H2O cache report is not an isolated official-train cache") + rows = [ + json.loads(line) for line in cache_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if len(rows) != 7000 or {row.get("dataset_id") for row in rows} != {"H2O"}: + raise ValueError("H2O multifold requires the canonical 7,000-clip cache") + output_dir.mkdir(parents=True, exist_ok=False) + folds = [] + for definition in fold_definitions(rows): + train, heldout = split_rows(rows, definition) + train_path = output_dir / f"{definition['id']}_train.jsonl" + heldout_path = output_dir / f"{definition['id']}_heldout.jsonl" + write_jsonl(train_path, train) + write_jsonl(heldout_path, heldout) + folds.append({ + **definition, + "train": {"path": str(train_path.resolve()), "sha256": sha256(train_path), + "clips": len(train), "recordings": len({row['physical_recording_id'] for row in train}), + **numeric_stats(train)}, + "heldout": {"path": str(heldout_path.resolve()), "sha256": sha256(heldout_path), + "clips": len(heldout), "recordings": len({row['physical_recording_id'] for row in heldout}), + **numeric_stats(heldout)}, + }) + return { + "schema_version": "phase9_h2o_train_multifold_v1", + "status": "complete", + "source_cache_manifest": {"path": str(cache_manifest.resolve()), "sha256": sha256(cache_manifest)}, + "selection_metrics": ["fold_macro_absolute_mpjpe", "worst_fold_absolute_mpjpe"], + "folds": folds, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--cache-report", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists() or args.output_dir.exists(): + parser.error("multifold output already exists") + try: + result = build(args.cache_manifest, args.cache_report, args.output_dir) + except (OSError, ValueError, KeyError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_hot_scale_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_hot_scale_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..02461a594c28ac7532731ee53ffecf3708076071 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_hot_scale_configs.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Generate matched J40 HOT10K/HOT50K data-volume configurations.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +from pathlib import Path + +import yaml + +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--run-root", type=Path, required=True) + parser.add_argument("--data-readiness-state", type=Path, required=True) + parser.add_argument("--data-finalize-plan-sha256", required=True) + parser.add_argument("--initialization-checkpoint", type=Path, required=True) + parser.add_argument("--initialization-checkpoint-sha256", required=True) + parser.add_argument( + "--refresh", action="store_true", + help="Replace preregistered configs only when no training checkpoint exists.", + ) + args = parser.parse_args() + if (args.output_dir.exists() or args.registry.exists()) and not args.refresh: + parser.error("outputs must be new") + if args.refresh and args.run_root.exists() and any(args.run_root.rglob("*.pt")): + parser.error("cannot refresh HOT scale configs after a training checkpoint exists") + if sha256(args.initialization_checkpoint) != args.initialization_checkpoint_sha256: + parser.error("initialization checkpoint SHA256 differs") + base = yaml.safe_load(args.base_config.read_text(encoding="utf-8")) + if base["experiment"]["condition"] != "J40": + parser.error("base config must be J40") + args.output_dir.mkdir(parents=True, exist_ok=args.refresh) + hot_manifests = { + "J40_HOT10K": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl", + "J40_HOT50K": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_50000_v1/cache_manifest.jsonl", + } + conditions = [] + for condition, hot_manifest in hot_manifests.items(): + config = copy.deepcopy(base) + config["name"] = f"phase9_{condition.lower()}_s20260717" + config["experiment"]["condition"] = condition + hot = next(source for source in config["data"]["sources"] if source["dataset"] == "HOT3D") + hot["cache_manifest"] = hot_manifest + path = args.output_dir / f"{condition.lower()}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + errors = validate_phase9_unified_contract(config, path) + if errors: + raise ValueError(f"invalid generated HOT scale config: {'; '.join(errors)}") + conditions.append({ + "condition": condition, "config": str(path.resolve()), + "config_sha256": sha256(path), + "initialization_checkpoint": str(args.initialization_checkpoint.resolve()), + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "output_dir": str((args.run_root / condition.lower()).resolve()), + "log_dir": str((args.run_root.parent / "queues" / "hot_scale" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": "scale505k", "stop_after_step": 505000}, + ], + }) + registry = { + "schema_version": "phase9_hot_unique_scale_training_queue_v1", + "status": "frozen_before_hot_scale_training", + "data_readiness_state": str(args.data_readiness_state.resolve()), + "data_finalize_plan_sha256": args.data_finalize_plan_sha256, + "prerequisite_states": [ + {"condition": condition, "path": str( + (args.data_readiness_state.parent / f"{condition.lower()}_state.json").resolve() + )} for condition in ("J25", "J40", "J55") + ], + "allowed_physical_gpus": [0, 1, 2, 3], + "prohibited_physical_gpus": [4, 5], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "conditions": conditions, + } + args.registry.write_text(json.dumps(registry, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "registry": str(args.registry.resolve()), "sha256": sha256(args.registry), + "conditions": [condition["condition"] for condition in conditions], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_last2_evaluation_plan.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_last2_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe26e4c5fc7553a82ce13c2dda94c111b6b189b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_last2_evaluation_plan.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Freeze one ordered last-2 candidate's 25 matched evaluations.""" + +from __future__ import annotations + +import argparse +import fcntl +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_evaluation_plan import ( + completed_training_jobs, + evaluation_record, +) +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_control_plan(path: Path, expected_sha256: str) -> dict[str, Any]: + if not path.is_file() or sha256(path) != expected_sha256: + raise ValueError("last-2 control evaluation plan differs") + plan = read_json(path) + if ( + plan.get("status") != "frozen_ready" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or len(plan.get("evaluations", [])) != 25 + ): + raise ValueError("last-2 control evaluation contract differs") + return plan + + +def build_plan( + *, candidate: str, training_controller_plan_path: Path, + training_controller_state_path: Path, output_root: Path, + worker_state_root: Path, distributed_assignment_path: Path, + distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or controller_state.get("h2o_official_validation_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("last-2 training controller is not complete and bound") + registry = read_json(registry_path) + if registry.get("candidate") != candidate: + raise ValueError("last-2 training registry candidate differs") + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + if candidate == "5e7": + control_path = Path(registry["base_evaluation_plan"]["path"]) + control_sha256 = registry["base_evaluation_plan"]["sha256"] + elif candidate == "1e6": + five_decision_path = Path(registry["five_e7_decision"]["path"]) + if ( + not five_decision_path.is_file() + or registry["five_e7_decision"]["sha256"] != sha256(five_decision_path) + ): + raise ValueError("conditional 1e-6 decision binding differs") + five_decision = read_json(five_decision_path) + control_path = Path(five_decision["evaluation_plan"]["path"]) + control_sha256 = five_decision["evaluation_plan"]["sha256"] + else: + raise ValueError("unknown last-2 evaluation candidate") + control = validate_control_plan(control_path, control_sha256) + control_items = {item["id"]: item for item in control["evaluations"]} + evaluations = [] + for identifier, control_item in control_items.items(): + role = control_item["training_role"] + job = jobs[role] + evaluations.append(evaluation_record( + evaluation_id=identifier, + job=job, + manifest=Path(control_item["cache_manifest"]), + mode=control_item["input_mode"], + role=control_item["evaluation_role"], + output=output_root / Path(control_item["output_dir"]).relative_to( + control["output_root"] + ), + )) + ids = [item["id"] for item in evaluations] + if len(ids) != 25 or len(set(ids)) != 25 or set(ids) != set(control_items): + raise ValueError("last-2 evaluation IDs differ from control") + control_reports = { + identifier: { + "path": str((Path(item["output_dir"]) / "evaluation.json").resolve()), + "sha256": sha256(Path(item["output_dir"]) / "evaluation.json"), + "evaluation_role": item["evaluation_role"], + "input_mode": item["input_mode"], + } + for identifier, item in control_items.items() + } + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_last2_evaluation_plan_v1", + "status": "frozen_ready", "candidate": candidate, + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "control_evaluation_plan": { + "path": str(control_path.resolve()), "sha256": control_sha256, + }, + "control_reports": control_reports, + "winner": registry["winner"], + "resolution_hw": registry["resolution_hw"], + "shared_augmentation": registry["shared_augmentation"], + "backbone_learning_rate": registry["backbone_learning_rate"], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "gate": "macro_and_worst_domain_must_both_strictly_improve", + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--candidate", choices=("5e7", "1e6"), required=True) + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + candidate=args.candidate, + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing last-2 evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_last2_evaluation_plan_state_v1", + "status": "failed_resumable", "candidate": args.candidate, + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_last2_evaluation_plan_state_v1", + "status": "complete", "candidate": args.candidate, + "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_last2_training_registry.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_last2_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..2a04b4420ca861e79c5a34cb4af9de021c0a7306 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_last2_training_registry.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +"""Freeze ordered DINO Base last-2 training registries after Stage 8.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.build_phase9_resolution_training_registry import ( + FOLDS, + atomic_json, + sha256, + write_config, +) +from scripts.train_phase7_external import validate_phase9_unified_contract + + +CANDIDATES = { + "5e7": {"phase9_stage": "last2_5e7", "backbone_learning_rate": 5e-7}, + "1e6": {"phase9_stage": "last2_1e6", "backbone_learning_rate": 1e-6}, +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_stage8( + controller_plan_path: Path, controller_state_path: Path, +) -> tuple[dict[str, Any], dict[str, Any], Path]: + state = read_json(controller_state_path) + decision_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(controller_plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not decision_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(decision_path) + ): + raise ValueError("Stage 8 decision controller is not complete and bound") + decision = read_json(decision_path) + evaluation_plan_path = Path(state.get("evaluation_plan", "")) + if ( + decision.get("status") != "complete" + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + or not evaluation_plan_path.is_file() + or state.get("evaluation_plan_sha256") != sha256(evaluation_plan_path) + or decision.get("evaluation_plan", {}).get("sha256") + != sha256(evaluation_plan_path) + ): + raise ValueError("Stage 8 decision/evaluation binding differs") + return decision, read_json(evaluation_plan_path), evaluation_plan_path + + +def selected_base( + stage8_decision: dict[str, Any], stage8_plan: dict[str, Any], + stage8_plan_path: Path, +) -> tuple[dict[str, Any], Path, str, bool]: + if stage8_decision["shared_augmentation_accepted"]: + base_plan = stage8_plan + base_plan_path = stage8_plan_path + mechanism = "shared_augmentation" + shared_augmentation = True + else: + preceding = stage8_decision["stage9_preceding_mechanism_gate"] + if ( + preceding.get("source_mechanism") != "resolution" + or preceding.get("stage9_last2_admitted") is not True + or stage8_plan.get("control", {}).get("kind") + != "resolution_896x512_candidate" + ): + raise ValueError("no selected preceding mechanism admits Stage 9") + base_plan_path = Path(stage8_plan["control"]["evaluation_plan"]["path"]) + if ( + not base_plan_path.is_file() + or stage8_plan["control"]["evaluation_plan"]["sha256"] + != sha256(base_plan_path) + ): + raise ValueError("selected resolution control plan differs") + base_plan = read_json(base_plan_path) + mechanism = "resolution" + shared_augmentation = False + if set(base_plan["training_jobs"]) != {"full", *FOLDS}: + raise ValueError("selected last-2 base training roles differ") + return base_plan, base_plan_path, mechanism, shared_augmentation + + +def derive_last2_config( + base: dict[str, Any], *, condition: str, candidate: str, + resolution_hw: list[int], shared_augmentation: bool, + stage8_decision_sha256: str, +) -> dict[str, Any]: + spec = CANDIDATES[candidate] + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = spec["phase9_stage"] + experiment["last2_resolution_hw"] = list(resolution_hw) + experiment["last2_shared_augmentation"] = bool(shared_augmentation) + experiment["stage8_decision_sha256"] = stage8_decision_sha256 + model = config["model"] + if model.get("encoder") != "dinov3": + raise ValueError("last-2 base does not use DINOv3") + if model.get("dinov3_model", "dinov3_vitb16") != "dinov3_vitb16": + raise ValueError("last-2 base is not DINO Base") + model["dinov3_trainable_last_blocks"] = 2 + config["protocol"]["backbone_learning_rate"] = spec[ + "backbone_learning_rate" + ] + return config + + +def validate_matched_last2( + base: dict[str, Any], derived: dict[str, Any], candidate: str, +) -> None: + for key in ("seed", "loss", "assets", "precision"): + if derived[key] != base[key]: + raise ValueError(f"last-2 config changes matched {key}") + base_model = deepcopy(base["model"]) + derived_model = deepcopy(derived["model"]) + base_model.pop("dinov3_trainable_last_blocks", None) + if derived_model.pop("dinov3_trainable_last_blocks", None) != 2: + raise ValueError("last-2 config does not train exactly two blocks") + if base_model != derived_model: + raise ValueError("last-2 config changes non-admitted model parameters") + base_protocol = deepcopy(base["protocol"]) + derived_protocol = deepcopy(derived["protocol"]) + base_protocol.pop("backbone_learning_rate", None) + actual_lr = derived_protocol.pop("backbone_learning_rate", None) + if actual_lr != CANDIDATES[candidate]["backbone_learning_rate"]: + raise ValueError("last-2 backbone learning rate differs") + if base_protocol != derived_protocol: + raise ValueError("last-2 config changes optimizer/scheduler horizon") + if derived["data"] != base["data"]: + raise ValueError("last-2 config changes data, mixture or augmentation") + + +def validate_conditional_1e6(path: Path | None) -> dict[str, Any]: + if path is None or not path.is_file(): + raise ValueError("1e-6 requires a frozen 5e-7 decision report") + report = read_json(path) + if ( + report.get("status") != "complete" + or report.get("candidate") != "5e7" + or report.get("gate", {}).get("macro_strictly_improved") is not True + or report.get("gate", {}).get("worst_domain_strictly_improved") is not True + or report.get("gate", {}).get("accepted") is not True + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError("5e-7 did not pass strict macro and worst-domain gates") + evaluation_plan = Path(report.get("evaluation_plan", {}).get("path", "")) + if ( + not evaluation_plan.is_file() + or report["evaluation_plan"].get("sha256") != sha256(evaluation_plan) + ): + raise ValueError("5e-7 decision evaluation plan differs") + return report + + +def build_registry( + *, candidate: str, stage8_controller_plan_path: Path, + stage8_controller_state_path: Path, last2_plan_path: Path, + output_root: Path, five_e7_decision_path: Path | None, +) -> dict[str, Any]: + if candidate not in CANDIDATES: + raise ValueError("unknown last-2 candidate") + stage8_decision, stage8_plan, stage8_plan_path = validate_stage8( + stage8_controller_plan_path, stage8_controller_state_path, + ) + decision_path = stage8_decision_path(stage8_controller_state_path) + preceding = stage8_decision["stage9_preceding_mechanism_gate"] + if preceding.get("stage9_last2_admitted") is not True: + raise ValueError("Stage 9 is not admitted by the preceding mechanism") + five_e7 = ( + validate_conditional_1e6(five_e7_decision_path) + if candidate == "1e6" else None + ) + base_plan, base_plan_path, mechanism, shared_augmentation = selected_base( + stage8_decision, stage8_plan, stage8_plan_path, + ) + resolution_hw = list(stage8_decision["resolution_hw"]) + if base_plan["resolution_hw"] != resolution_hw: + raise ValueError("last-2 base resolution differs from Stage 8 decision") + base_registry_path = Path(base_plan["training_registry"]["path"]) + if ( + not base_registry_path.is_file() + or base_plan["training_registry"]["sha256"] != sha256(base_registry_path) + ): + raise ValueError("last-2 base registry differs") + base_registry = read_json(base_registry_path) + last2_plan = read_json(last2_plan_path) + expected = last2_plan[ + "candidate_5e7" if candidate == "5e7" else "conditional_candidate_1e6" + ] + if ( + last2_plan.get("official_test_used") is not False + or expected.get("dinov3_trainable_last_blocks") != 2 + or float(expected.get("backbone_learning_rate")) + != CANDIDATES[candidate]["backbone_learning_rate"] + or last2_plan.get("dino_large") != "not_admitted" + ): + raise ValueError("frozen last-2 plan differs") + + target_step = int(base_registry["target_step"]) + label = candidate + config_root = output_root / label / "phase9" / "configs" + conditions = [] + for role in ("full", *FOLDS): + job = base_plan["training_jobs"][role] + config_path = Path(job["config"]) + if not config_path.is_file() or job["config_sha256"] != sha256(config_path): + raise ValueError(f"last-2 base config differs: {role}") + base = yaml.safe_load(config_path.read_text(encoding="utf-8")) + prefix = "S9L5" if candidate == "5e7" else "S9L10" + condition = f"{prefix}_{stage8_decision['winner'].split(':', 1)[0]}_{role}" + derived = derive_last2_config( + base, condition=condition, candidate=candidate, + resolution_hw=resolution_hw, + shared_augmentation=shared_augmentation, + stage8_decision_sha256=sha256(decision_path), + ) + validate_matched_last2(base, derived, candidate) + derived_path = config_root / f"{condition.lower()}.yaml" + errors = validate_phase9_unified_contract(derived, derived_path) + if errors: + raise ValueError("; ".join(errors)) + write_config(derived_path, derived) + run_dir = output_root / label / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"last-2 run exists before freeze: {run_dir}") + conditions.append({ + "condition": condition, "role": role, + "config": str(derived_path.resolve()), + "config_sha256": sha256(derived_path), + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / label / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": base_registry[ + "matched_source_exposure_batches" + ], + "expected_source_exposure_frames": base_registry[ + "matched_source_exposure_frames" + ], + }) + return { + "schema_version": "phase9_last2_training_registry_v1", + "status": "frozen_ready", "created_utc": stage8_decision["created_utc"], + "candidate": candidate, + "backbone_learning_rate": CANDIDATES[candidate]["backbone_learning_rate"], + "winner": stage8_decision["winner"], + "resolution_hw": resolution_hw, + "shared_augmentation": shared_augmentation, + "selected_preceding_mechanism": mechanism, + "stage8_decision": { + "path": str(decision_path.resolve()), + "sha256": sha256(decision_path), + }, + "base_evaluation_plan": { + "path": str(base_plan_path.resolve()), "sha256": sha256(base_plan_path), + }, + "base_training_registry": { + "path": str(base_registry_path.resolve()), "sha256": sha256(base_registry_path), + }, + "five_e7_decision": ( + {"path": str(five_e7_decision_path.resolve()), + "sha256": sha256(five_e7_decision_path)} + if five_e7 is not None else None + ), + "last2_plan": { + "path": str(last2_plan_path.resolve()), "sha256": sha256(last2_plan_path), + }, + "target_step": target_step, + "matched_source_exposure_batches": base_registry[ + "matched_source_exposure_batches" + ], + "matched_source_exposure_frames": base_registry[ + "matched_source_exposure_frames" + ], + "data_readiness_state": base_registry["data_readiness_state"], + "data_readiness_state_sha256": base_registry["data_readiness_state_sha256"], + "data_finalize_plan_sha256": base_registry["data_finalize_plan_sha256"], + "data_artifacts": base_registry["data_artifacts"], + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def stage8_decision_path(controller_state_path: Path) -> Path: + state = read_json(controller_state_path) + return Path(state["decision_report"]["path"]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--candidate", choices=tuple(CANDIDATES), required=True) + parser.add_argument("--stage8-controller-plan", type=Path, required=True) + parser.add_argument("--stage8-controller-state", type=Path, required=True) + parser.add_argument("--last2-plan", type=Path, required=True) + parser.add_argument("--five-e7-decision", type=Path) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + registry = build_registry( + candidate=args.candidate, + stage8_controller_plan_path=args.stage8_controller_plan, + stage8_controller_state_path=args.stage8_controller_state, + last2_plan_path=args.last2_plan, + output_root=args.output_root, + five_e7_decision_path=args.five_e7_decision, + ) + if args.output_registry.exists(): + if read_json(args.output_registry) != registry: + raise ValueError("existing last-2 training registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_last2_registry_state_v1", + "status": "failed_resumable", "candidate": args.candidate, + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_last2_registry_state_v1", + "status": "complete", "candidate": args.candidate, + "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_resolution_evaluation_plan.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_resolution_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..6817a02586ce001cae349a38ad3b8510e49cff7f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_resolution_evaluation_plan.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Freeze Stage 7 evaluations from completed matched-resolution training.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +EXTERNAL_MODES = { + "HOT3D": ("rgb_k", "rgb_only"), + "HOI4D": ("rgb_d_k", "rgb_k", "rgb_only"), + "ARCTIC": ("rgb_k", "rgb_only"), +} +EXTERNAL_CACHE_IDS = { + "HOT3D": "hot3d_heldout", + "HOI4D": "hoi4d_heldout", + "ARCTIC": "arctic_heldout", +} +H2O_MODES = ("rgb_d_k", "rgb_k", "rgb_only") + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def completed_training_jobs( + registry_path: Path, registry: dict[str, Any], state_root: Path, +) -> dict[str, dict[str, Any]]: + registry_hash = sha256(registry_path) + result = {} + for job in registry["conditions"]: + condition = job["condition"] + state_path = state_root / f"{condition.lower()}.json" + if not state_path.is_file(): + raise ValueError(f"resolution training state is missing: {condition}") + state = read_json(state_path) + marker = state.get("last_completed", {}) + checkpoint = Path(marker.get("checkpoint", "")) + if ( + state.get("status") != "complete" + or state.get("queue_sha256") != registry_hash + or state.get("official_test_used") is not False + or marker.get("completed_step") != registry["target_step"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + ): + raise ValueError(f"resolution training endpoint differs: {condition}") + result[job["role"]] = { + **job, + "state": str(state_path.resolve()), + "state_sha256": sha256(state_path), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": marker["checkpoint_sha256"], + "gpu_hours": state["gpu_hours_consumed"], + } + if set(result) != { + "full", "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + }: + raise ValueError("resolution training roles differ") + return result + + +def evaluation_record( + *, evaluation_id: str, job: dict[str, Any], manifest: Path, + mode: str, role: str, output: Path, +) -> dict[str, Any]: + config = Path(job["config"]) + if not config.is_file() or sha256(config) != job["config_sha256"]: + raise ValueError(f"resolution evaluation config differs: {evaluation_id}") + if not manifest.is_file(): + raise ValueError(f"resolution evaluation manifest missing: {evaluation_id}") + return { + "id": evaluation_id, + "training_role": job["role"], + "config": str(config.resolve()), + "config_sha256": job["config_sha256"], + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": mode, + "evaluation_role": role, + "output_dir": str(output.resolve()), + } + + +def build_plan( + *, training_controller_plan_path: Path, training_controller_state_path: Path, + cache_plan_path: Path, output_root: Path, worker_state_root: Path, + distributed_assignment_path: Path, distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("resolution training controller is not complete and bound") + registry = read_json(registry_path) + if ( + registry.get("status") != "frozen_ready" + or registry.get("official_test_used") is not False + or registry.get("h2o_official_validation_used_for_selection") is not False + or registry.get("gate", {}).get("worst_domain_relative_regression_limit") + != controller_plan["worst_domain_relative_regression_limit"] + ): + raise ValueError("resolution training registry contract differs") + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + + cache_plan = read_json(cache_plan_path) + caches = {item["id"]: item for item in cache_plan["caches"]} + evaluations = [] + full = jobs["full"] + for dataset, modes in EXTERNAL_MODES.items(): + cache = caches[EXTERNAL_CACHE_IDS[dataset]] + manifest = Path(cache["manifest"]) + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=full, manifest=manifest, + mode=mode, role="phase9_external_heldout", + output=output_root / "full" / dataset.lower() / mode, + )) + for fold, job in jobs.items(): + if fold == "full": + continue + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + validation = config["data"].get("validation_sources", []) + if len(validation) != 1 or validation[0].get("dataset") != "H2O": + raise ValueError(f"resolution fold heldout differs: {fold}") + manifest = Path(validation[0]["cache_manifest"]) + for mode in H2O_MODES: + identifier = f"{fold}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=job, manifest=manifest, + mode=mode, role="phase9_h2o_fold_heldout", + output=output_root / "h2o" / fold / mode, + )) + ids = [item["id"] for item in evaluations] + outputs = [item["output_dir"] for item in evaluations] + if len(evaluations) != 25 or len(set(ids)) != 25 or len(set(outputs)) != 25: + raise ValueError("resolution evaluation IDs/outputs are not unique and complete") + + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_resolution_evaluation_plan_v1", + "status": "frozen_ready", + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "cache_execution_plan": { + "path": str(cache_plan_path.resolve()), "sha256": sha256(cache_plan_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "winner": registry["winner"], + "winner_checkpoint": registry["winner_checkpoint"], + "winner_config": registry["winner_config"], + "control_evidence": registry["control_evidence"], + "gate": registry["gate"], + "resolution_hw": [512, 896], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--cache-plan", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + cache_plan_path=args.cache_plan, output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing resolution evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_resolution_evaluation_plan_state_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_resolution_evaluation_plan_state_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_resolution_training_registry.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_resolution_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..3d10ab153ad63a19c9638d018c484bcd86b3254b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_resolution_training_registry.py @@ -0,0 +1,453 @@ +#!/usr/bin/env python3 +"""Freeze matched 896 training jobs from the selected 640 checkpoint.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +import re +from typing import Any + +import torch +import yaml + + +FOLDS = ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", +) +RESOLUTION_HW = [512, 896] +WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT = 0.01 +SOURCE_MANIFESTS = { + "H2O": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/h2o_train7000/cache_manifest.jsonl" + ), + "HOT3D": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/hot3d_train100000/cache_manifest.jsonl" + ), + "HOI4D": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/hoi4d_train37304_left_root/cache_manifest.jsonl" + ), + "ARCTIC": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/arctic_train21339_left_root/cache_manifest.jsonl" + ), +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_text(path: Path, value: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(value, encoding="utf-8") + temporary.replace(path) + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + atomic_text(path, json.dumps(value, indent=2) + "\n") + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def checkpoint_metadata( + path: Path, expected_sha256: str, expected_config_sha256: str, +) -> dict[str, Any]: + if not path.is_file() or sha256(path) != expected_sha256: + raise ValueError("selected 640 checkpoint hash differs") + payload = torch.load(path, map_location="cpu", weights_only=False) + extra = payload.get("extra", {}) + step = int(payload.get("step", -1)) + filename = re.search(r"step_(\d+)", path.name) + if ( + step <= 2000 + or filename is None + or int(filename.group(1)) != step + or extra.get("config_sha256") != expected_config_sha256 + or extra.get("official_test_used") is not False + or not extra.get("source_exposure_batches") + or not extra.get("external_initialization_checkpoint") + ): + raise ValueError("selected 640 checkpoint metadata differs") + return { + "step": step, + "source_exposure_batches": extra["source_exposure_batches"], + "source_exposure_frames": extra.get("source_exposure_frames", {}), + "completed_source_exposure_milestones": extra.get( + "completed_source_exposure_milestones", [] + ), + "initialization_checkpoint": extra["external_initialization_checkpoint"], + } + + +def derive_config( + base: dict[str, Any], *, condition: str, target_step: int, + h2o_train_manifest: str, h2o_heldout_manifest: str | None, + winner: str, winner_checkpoint_sha256: str, +) -> dict[str, Any]: + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = "resolution_896x512" + experiment["resolution_control_winner"] = winner + experiment["resolution_control_checkpoint_sha256"] = winner_checkpoint_sha256 + data = config["data"] + data["resolution_hw"] = list(RESOLUTION_HW) + for source in data["sources"]: + dataset = str(source["dataset"]).upper() + source["cache_manifest"] = ( + h2o_train_manifest if dataset == "H2O" else SOURCE_MANIFESTS[dataset] + ) + if h2o_heldout_manifest is None: + data.pop("validation_sources", None) + else: + validation = data.get("validation_sources", []) + if len(validation) != 1 or str(validation[0].get("dataset", "")).upper() != "H2O": + raise ValueError("fold base config lacks exactly one H2O heldout") + validation[0]["cache_manifest"] = h2o_heldout_manifest + return config + + +def validate_matched_config( + base: dict[str, Any], derived: dict[str, Any], target_step: int, +) -> None: + if ( + derived["seed"] != base["seed"] + or derived["model"] != base["model"] + or derived["loss"] != base["loss"] + or derived["assets"] != base["assets"] + or derived["precision"] != base["precision"] + or derived["data"]["T"] != base["data"]["T"] + or derived["data"]["batch_size"] != base["data"]["batch_size"] + or derived["data"].get("photometric_augmentation") + != base["data"].get("photometric_augmentation") + ): + raise ValueError("resolution config changes a matched model/data invariant") + base_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() if key != "cache_manifest" + } + for item in base["data"]["sources"] + } + derived_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() if key != "cache_manifest" + } + for item in derived["data"]["sources"] + } + if base_sources != derived_sources: + raise ValueError("resolution config changes source mixture or source settings") + if base["protocol"] != derived["protocol"]: + raise ValueError("resolution config changes optimizer/scheduler protocol") + + +def verify_readiness( + selection: dict[str, Any], readiness_path: Path, expected_plan_sha256: str, +) -> dict[str, Any]: + readiness = read_json(readiness_path) + audit_path = Path(readiness.get("audit", {}).get("path", "")) + if ( + readiness.get("status") != "complete" + or readiness.get("plan_sha256") != expected_plan_sha256 + or readiness.get("official_test_used") is not False + or readiness.get("h2o_official_validation_used") is not False + or readiness.get("winner") != selection.get("winner") + or readiness.get("winner_checkpoint") != selection.get("winner_checkpoint") + or readiness.get("winner_config") != selection.get("winner_config") + or not audit_path.is_file() + or readiness.get("audit", {}).get("sha256") != sha256(audit_path) + ): + raise ValueError("resolution cache readiness differs from selected winner") + audit = read_json(audit_path) + if ( + audit.get("status") != "complete" + or audit.get("plan_sha256") != expected_plan_sha256 + or audit.get("resolution_hw") != RESOLUTION_HW + or audit.get("official_test_used") is not False + or audit.get("h2o_official_validation_used") is not False + or not audit.get("multifold", {}).get("physical_recording_isolation") + or not audit.get("multifold", {}).get("deterministic_rebuild_hashes_match") + ): + raise ValueError("resolution cache audit differs") + return readiness + + +def write_config(path: Path, config: dict[str, Any]) -> None: + text = yaml.safe_dump(config, sort_keys=False, width=1000) + if path.exists(): + if path.read_text(encoding="utf-8") != text: + raise ValueError(f"existing resolution config differs: {path}") + return + atomic_text(path, text) + + +def build_registry( + *, selection_path: Path, readiness_path: Path, cache_plan_path: Path, + unified_queue_path: Path, fold_queue_path: Path, output_root: Path, +) -> dict[str, Any]: + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("unified selection is not complete and isolated") + cache_plan_sha256 = sha256(cache_plan_path) + readiness = verify_readiness(selection, readiness_path, cache_plan_sha256) + + winner = str(selection["winner"]) + mixture = winner.split(":", 1)[0] + if mixture not in {"J25", "J40", "J55"}: + raise ValueError("selected winner mixture is unknown") + winner_row = next( + (row for row in selection["candidates"] if row["id"] == winner), None + ) + if ( + winner_row is None + or winner_row.get("checkpoint") != selection["winner_checkpoint"] + or winner_row.get("config") != selection["winner_config"] + ): + raise ValueError("selected winner row is missing") + + unified_queue = read_json(unified_queue_path) + fold_queue = read_json(fold_queue_path) + full_job = next( + (item for item in unified_queue["conditions"] if item["condition"] == mixture), + None, + ) + if full_job is None: + raise ValueError("selected mixture is missing from the full-data queue") + selected_config = selection["winner_config"] + if ( + Path(selected_config["path"]).resolve() != Path(full_job["config"]).resolve() + or selected_config["sha256"] != full_job["config_sha256"] + or sha256(full_job["config"]) != full_job["config_sha256"] + ): + raise ValueError("selected config differs from the frozen full-data queue") + metadata = checkpoint_metadata( + Path(selection["winner_checkpoint"]["path"]), + selection["winner_checkpoint"]["sha256"], + selected_config["sha256"], + ) + initialization = metadata["initialization_checkpoint"] + initialization_path = Path(full_job["initialization_checkpoint"]) + if ( + Path(initialization.get("path", "")).resolve() + != initialization_path.resolve() + or initialization.get("sha256") != full_job["initialization_checkpoint_sha256"] + or not initialization_path.is_file() + or sha256(initialization_path) != full_job["initialization_checkpoint_sha256"] + ): + raise ValueError("selected checkpoint initialization differs") + + multifold = read_json( + output_root / "manifests" / "h2o_multifold_index.json" + ) + if ( + multifold.get("status") != "complete" + or multifold.get("official_test_used") is not False + or multifold.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution multifold index is not complete and isolated") + folds = {item["id"]: item for item in multifold["folds"]} + if set(folds) != set(FOLDS): + raise ValueError("resolution multifold IDs differ") + + config_root = output_root / "phase9" / "configs" + conditions = [] + base_full = yaml.safe_load(Path(full_job["config"]).read_text(encoding="utf-8")) + job_specs: list[tuple[str, dict[str, Any], str, str | None]] = [ + ("full", base_full, SOURCE_MANIFESTS["H2O"], None) + ] + fold_jobs = {item["condition"]: item for item in fold_queue["conditions"]} + for fold in FOLDS: + condition_id = f"{mixture}_{fold}" + if condition_id not in fold_jobs: + raise ValueError(f"selected mixture fold config is missing: {fold}") + base = yaml.safe_load( + Path(fold_jobs[condition_id]["config"]).read_text(encoding="utf-8") + ) + job_specs.append(( + fold, base, folds[fold]["train"]["path"], folds[fold]["heldout"]["path"] + )) + + target_step = int(metadata["step"]) + for role, base, h2o_train, h2o_heldout in job_specs: + condition = f"S7R_{mixture}_{role}" + config = derive_config( + base, condition=condition, target_step=target_step, + h2o_train_manifest=h2o_train, h2o_heldout_manifest=h2o_heldout, + winner=winner, + winner_checkpoint_sha256=selection["winner_checkpoint"]["sha256"], + ) + validate_matched_config(base, config, target_step) + config_path = config_root / f"{condition.lower()}.yaml" + write_config(config_path, config) + run_dir = output_root / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"resolution run output exists before registry freeze: {run_dir}") + conditions.append({ + "condition": condition, + "role": role, + "config": str(config_path.resolve()), + "config_sha256": sha256(config_path), + "initialization_checkpoint": full_job["initialization_checkpoint"], + "initialization_checkpoint_sha256": full_job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": metadata["source_exposure_batches"], + "expected_source_exposure_frames": metadata["source_exposure_frames"], + }) + + manifests = {} + for dataset, path in SOURCE_MANIFESTS.items(): + manifests[dataset] = {"path": path, "sha256": sha256(path)} + cache_plan = read_json(cache_plan_path) + artifact_paths = { + Path(item["manifest"]).resolve() for item in cache_plan["caches"] + } | { + Path(item["manifest"]).resolve() for item in cache_plan["sidecars"] + } | { + Path(cache_plan["multifold"]["index"]).resolve(), + } + for fold in folds.values(): + artifact_paths.add(Path(fold["train"]["path"]).resolve()) + artifact_paths.add(Path(fold["heldout"]["path"]).resolve()) + data_artifacts = [ + {"path": str(path), "sha256": sha256(path)} + for path in sorted(artifact_paths) + ] + registry = { + "schema_version": "phase9_resolution_training_registry_v1", + "status": "frozen_ready", + "created_utc": readiness["completed_utc"], + "winner": winner, + "winner_checkpoint": selection["winner_checkpoint"], + "winner_config": selection["winner_config"], + "control_evidence": winner_row, + "target_step": target_step, + "matched_source_exposure_batches": metadata["source_exposure_batches"], + "matched_source_exposure_frames": metadata["source_exposure_frames"], + "completed_source_exposure_milestones": metadata[ + "completed_source_exposure_milestones" + ], + "resolution_hw": RESOLUTION_HW, + "data_readiness_state": str(readiness_path.resolve()), + "data_readiness_state_sha256": sha256(readiness_path), + "data_finalize_plan_sha256": cache_plan_sha256, + "data_artifacts": data_artifacts, + "source_manifests": manifests, + "selection_report": { + "path": str(selection_path.resolve()), "sha256": sha256(selection_path), + }, + "cache_execution_plan": { + "path": str(cache_plan_path.resolve()), "sha256": cache_plan_sha256, + }, + "gate": { + "macro_absolute_mm_must_strictly_improve": True, + "worst_domain_relative_regression_limit": ( + WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT + ), + }, + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + return registry + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-report", type=Path, required=True) + parser.add_argument("--readiness-state", type=Path, required=True) + parser.add_argument("--cache-plan", type=Path, required=True) + parser.add_argument("--unified-queue", type=Path, required=True) + parser.add_argument("--fold-queue", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.state.is_file(): + state = read_json(args.state) + if state.get("status") == "complete": + if ( + args.output_registry.is_file() + and state.get("registry_sha256") == sha256(args.output_registry) + ): + print(json.dumps(state, indent=2)) + return + parser.error("completed resolution registry state differs") + try: + registry = build_registry( + selection_path=args.selection_report, + readiness_path=args.readiness_state, + cache_plan_path=args.cache_plan, + unified_queue_path=args.unified_queue, + fold_queue_path=args.fold_queue, + output_root=args.output_root, + ) + if args.output_registry.exists(): + existing = read_json(args.output_registry) + if existing != registry: + raise ValueError("existing resolution training registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_resolution_training_registry_state_v1", + "status": "failed_resumable", + "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_resolution_training_registry_state_v1", + "status": "complete", + "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "winner": registry["winner"], + "winner_checkpoint": registry["winner_checkpoint"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_selection_binding_recovery_plan.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_selection_binding_recovery_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..429d2680d06f834a198213ceaf1c0bf978888527 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_selection_binding_recovery_plan.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Freeze canonical re-evaluations for Phase 9 selection path mismatches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def canonical_config(condition: str) -> Path: + return Path( + "/home/jiasen/foundation_hand/artifacts/phase9/registry/fold_configs" + ) / f"{condition.lower()}.yaml" + + +def build_plan( + *, assignment_path: Path, audit_path: Path, selection_plan_path: Path, + failure_backup_root: Path, +) -> dict[str, Any]: + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + audit = json.loads(audit_path.read_text(encoding="utf-8")) + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + assignment_hash = sha256(assignment_path) + if ( + assignment.get("status") + != "frozen_before_distributed_recovery_or_stage7_work" + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + or audit.get("status") != "complete_path_only_recovery_required" + or audit.get("distributed_assignment", {}).get("sha256") + != assignment_hash + or audit.get("selection_plan", {}).get("sha256") + != sha256(selection_plan_path) + or selection_plan.get("official_test_used") is not False + ): + raise ValueError("selection recovery source contract differs") + assigned = { + item["id"]: item + for item in assignment["phase9_selection_recovery"]["evaluations"] + } + if len(assigned) != 11 or set(assigned) != set(audit["mismatch_ids"]): + raise ValueError("selection recovery assignment IDs differ") + records_by_id = {item["id"]: item for item in audit["records"]} + evaluations = [] + for identifier in sorted(assigned): + source = records_by_id[identifier] + owner_record = assigned[identifier] + if source.get("binding_status") != "path_mismatch_content_identical": + raise ValueError(f"recovery is not path-only: {identifier}") + config = canonical_config(source["condition"]) + if ( + not config.is_file() + or sha256(config) != source["config"]["declared_sha256"] + ): + raise ValueError(f"canonical config differs: {identifier}") + checkpoint = Path(source["checkpoint"]["path"]) + checkpoint_hash = source["checkpoint"]["declared_sha256"] + manifest = Path(source["cache_manifest"]["expected_path"]) + manifest_hash = source["cache_manifest"]["expected_sha256"] + if ( + not checkpoint.is_file() or sha256(checkpoint) != checkpoint_hash + or not manifest.is_file() or sha256(manifest) != manifest_hash + ): + raise ValueError(f"canonical recovery input differs: {identifier}") + owner = owner_record["owner"] + root = Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + determinism = source["determinism"] + evaluations.append({ + "id": identifier, + "owner": owner, + "physical_gpu_id": owner_record["physical_gpu_id"], + "condition": source["condition"], + "checkpoint_id": source["checkpoint_id"], + "input_mode": "rgb_d_k", + "evaluation_role": "phase9_h2o_fold_heldout", + "config": str(config.resolve()), + "config_sha256": sha256(config), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_hash, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": manifest_hash, + "output_dir": str(( + root / "evaluations" / source["condition"] + / source["checkpoint_id"] / "rgb_d_k" + ).resolve()), + "prior_report": source["report"], + "expected_sample_counts": source["sample_counts"], + "expected_determinism": { + "metrics_sha256": determinism["metrics_sha256"], + "grouped_bootstrap_ci_sha256": determinism[ + "grouped_bootstrap_ci_sha256" + ], + "raw_predictions_sha256": determinism[ + "raw_predictions" + ]["declared_sha256"], + "per_hand_rows_sha256": determinism[ + "per_hand_rows" + ]["declared_sha256"], + "take_metrics_sha256": determinism[ + "take_metrics" + ]["declared_sha256"], + }, + }) + workers = [] + for owner in ("taku3", "server_new"): + allowlist = assignment["machines"][owner]["physical_gpu_allowlist"] + for gpu in allowlist: + ids = [ + item["id"] for item in evaluations + if item["owner"] == owner and item["physical_gpu_id"] == gpu + ] + if not ids: + continue + root = Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + workers.append({ + "id": f"{owner}_gpu{gpu}", "owner": owner, + "physical_gpu_id": gpu, + "state": str((root / "states" / f"gpu{gpu}.json").resolve()), + "log": str((root / "logs" / f"gpu{gpu}.log").resolve()), + "evaluation_ids": ids, + }) + assigned_ids = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(evaluations) != 11 + or len(assigned_ids) != 11 + or len(set(assigned_ids)) != 11 + or set(assigned_ids) != set(assigned) + ): + raise ValueError("selection recovery workers are not disjoint and complete") + backup_files = {} + for name in ( + "unified_selection_state.json", "unified_selection.log", + "unified_selection_watcher.log", + ): + path = failure_backup_root / name + if not path.is_file(): + raise ValueError(f"selection failure backup missing: {path}") + backup_files[name] = sha256(path) + repository = assignment_path.resolve().parents[3] + code_paths = [ + repository / "scripts/evaluate_phase7_external.py", + repository / "scripts/summarize_phase9_unified_selection.py", + repository / "scripts/run_phase9_selection_binding_recovery.py", + repository / "scripts/finalize_phase9_selection_binding_recovery.py", + repository / "scripts/merge_phase9_selection_binding_recovery.py", + ] + code_bindings = [] + for path in code_paths: + if not path.is_file(): + raise ValueError(f"selection recovery code missing: {path}") + code_bindings.append({"path": str(path), "sha256": sha256(path)}) + return { + "schema_version": "phase9_selection_binding_recovery_plan_v2", + "status": "frozen_before_recovery_evaluation", + "reason": "migration_path_binding_differs_with_identical_manifest_sha256", + "scientific_failure": False, + "resource_scheduling_amendment_only": True, + "distributed_assignment": { + "path": str(assignment_path.resolve()), "sha256": assignment_hash, + }, + "mismatch_manifest": { + "path": str(audit_path.resolve()), "sha256": sha256(audit_path), + }, + "selection_plan": { + "path": str(selection_plan_path.resolve()), + "sha256": sha256(selection_plan_path), + }, + "failure_backup": { + "root": str(failure_backup_root.resolve()), + "files": backup_files, + }, + "code_bindings": code_bindings, + "release_manifests": { + owner: str((Path( + assignment["phase9_selection_recovery"][ + f"{owner}_recovery_root" + ] + ) / "release_manifest.json").resolve()) + for owner in ("taku3", "server_new") + }, + "canonical_fold_milestone_root": selection_plan["fold_milestone_root"], + "dry_run_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts/selection_binding_recovery_v2/dry_run", + "canonical_merge_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/selection_binding_recovery_v2/merge_state.json", + "canonical_merge_backup_root": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/recovery_backups/selection_binding_v2_20260731", + "selection_state": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/unified_selection_state.json", + "selection_log": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/unified_selection.log", + "evaluations": evaluations, + "workers": workers, + "bootstrap_resamples": 2000, + "requirements": [ + "evaluate only assigned mismatches in new recovery roots", + "bind canonical config manifest checkpoint and expected SHA256", + "validate sample counts role isolation metrics and artifact determinism", + "run temporary JSON and CSV summarizer before canonical merge", + "atomically replace each mismatched canonical output under one merge lock", + "preserve failed selection and replaced output evidence" + ], + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--audit", type=Path, required=True) + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--failure-backup-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("recovery plan output must be new") + result = build_plan( + assignment_path=args.assignment, audit_path=args.audit, + selection_plan_path=args.selection_plan, + failure_backup_root=args.failure_backup_root, + ) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_shared_augmentation_evaluation_plan.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_shared_augmentation_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..e381262202ce3e6f36fd1a7cbc71286aa7b745ca --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_shared_augmentation_evaluation_plan.py @@ -0,0 +1,282 @@ +#!/usr/bin/env python3 +"""Freeze Stage 8 evaluations after shared-augmentation training completes.""" + +from __future__ import annotations + +import argparse +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.build_phase9_resolution_evaluation_plan import ( + EXTERNAL_MODES, + H2O_MODES, + completed_training_jobs, + evaluation_record, +) +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +HELDOUT_640 = { + "HOT3D": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "HOI4D": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "ARCTIC": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/arctic_val2048_fullgroups_v2/cache_manifest.jsonl", +} +HELDOUT_896_IDS = { + "HOT3D": "hot3d_heldout", "HOI4D": "hoi4d_heldout", + "ARCTIC": "arctic_heldout", +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def control_reports_896(registry: dict[str, Any]) -> dict[str, dict[str, str]]: + path = Path(registry["control"]["evaluation_plan"]["path"]) + if ( + not path.is_file() + or registry["control"]["evaluation_plan"]["sha256"] != sha256(path) + ): + raise ValueError("Stage 8 896 control evaluation plan differs") + plan = read_json(path) + reports = {} + for item in plan["evaluations"]: + reports[item["id"]] = { + "path": str((Path(item["output_dir"]) / "evaluation.json").resolve()), + "evaluation_role": item["evaluation_role"], + "input_mode": item["input_mode"], + } + return reports + + +def control_reports_640(registry: dict[str, Any]) -> dict[str, dict[str, str]]: + control = registry["control"]["control_evidence"] + mixture = control["mixture"] + external_id = control["external_checkpoint_id"] + fold_id = control["fold_checkpoint_id"] + external_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/external_milestones" + ) + final_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold" + ) + milestone_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold_milestones" + ) + reports = {} + for dataset, modes in EXTERNAL_MODES.items(): + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + reports[identifier] = { + "path": str(( + external_root / mixture / external_id + / f"{dataset.lower()}_{mode}" / "evaluation.json" + ).resolve()), + "evaluation_role": "phase9_external_heldout", + "input_mode": mode, + } + for fold in FOLDS: + condition = f"{mixture}_{fold}" + for mode in H2O_MODES: + path = ( + final_root / condition / mode / "evaluation.json" + if fold_id == "final" + else milestone_root / condition / fold_id / mode / "evaluation.json" + ) + reports[f"{fold}_{mode}"] = { + "path": str(path.resolve()), + "evaluation_role": "phase9_h2o_fold_heldout", + "input_mode": mode, + } + return reports + + +def validate_control_reports(reports: dict[str, dict[str, str]]) -> None: + if len(reports) != 25: + raise ValueError("Stage 8 control report count differs") + for identifier, item in reports.items(): + path = Path(item["path"]) + if not path.is_file(): + raise ValueError(f"Stage 8 control report missing: {identifier}") + report = read_json(path) + if ( + report.get("status") != f"evaluated_{item['evaluation_role']}" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"Stage 8 control report differs: {identifier}") + item["sha256"] = sha256(path) + + +def build_plan( + *, training_controller_plan_path: Path, training_controller_state_path: Path, + resolution_cache_plan_path: Path, output_root: Path, worker_state_root: Path, + distributed_assignment_path: Path, distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or controller_state.get("h2o_official_validation_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("shared augmentation training is not complete and bound") + registry = read_json(registry_path) + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + resolution_hw = registry["resolution_hw"] + if resolution_hw == [512, 896]: + cache_plan = read_json(resolution_cache_plan_path) + cache_by_id = {item["id"]: item for item in cache_plan["caches"]} + heldouts = { + dataset: Path(cache_by_id[identifier]["manifest"]) + for dataset, identifier in HELDOUT_896_IDS.items() + } + control_reports = control_reports_896(registry) + elif resolution_hw == [368, 640]: + heldouts = {dataset: Path(path) for dataset, path in HELDOUT_640.items()} + control_reports = control_reports_640(registry) + else: + raise ValueError("shared augmentation resolution differs") + validate_control_reports(control_reports) + + evaluations = [] + full = jobs["full"] + for dataset, modes in EXTERNAL_MODES.items(): + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=full, manifest=heldouts[dataset], + mode=mode, role="phase9_external_heldout", + output=output_root / "full" / dataset.lower() / mode, + )) + for fold in FOLDS: + job = jobs[fold] + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + validation = config["data"].get("validation_sources", []) + if len(validation) != 1 or validation[0].get("dataset") != "H2O": + raise ValueError(f"augmentation fold heldout differs: {fold}") + manifest = Path(validation[0]["cache_manifest"]) + for mode in H2O_MODES: + evaluations.append(evaluation_record( + evaluation_id=f"{fold}_{mode}", job=job, manifest=manifest, + mode=mode, role="phase9_h2o_fold_heldout", + output=output_root / "h2o" / fold / mode, + )) + ids = [item["id"] for item in evaluations] + if len(ids) != 25 or len(set(ids)) != 25: + raise ValueError("shared augmentation evaluation IDs differ") + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_shared_augmentation_evaluation_plan_v1", + "status": "frozen_ready", + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "winner": registry["winner"], + "resolution_hw": resolution_hw, + "resolution_decision": registry["resolution_decision"], + "control": registry["control"], + "control_reports": control_reports, + "gate": registry["gate"], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--resolution-cache-plan", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + resolution_cache_plan_path=args.resolution_cache_plan, + output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing augmentation evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_eval_plan_state_v1", + "status": "failed_resumable", "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_shared_augmentation_eval_plan_state_v1", + "status": "complete", "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_shared_augmentation_training_registry.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_shared_augmentation_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..5867d7bdf6a01d537e221a7d5d1c01f6c0b2d69f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_phase9_shared_augmentation_training_registry.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Freeze Stage 8 shared-augmentation jobs after the resolution decision.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS +from scripts.build_phase9_resolution_training_registry import ( + FOLDS, + atomic_json, + checkpoint_metadata, + sha256, + write_config, +) +from scripts.train_phase7_external import validate_phase9_unified_contract + + +GEOMETRY_AUGMENTATION = { + "enabled": True, + "probability": 0.8, + "scale_min": 0.9, + "scale_max": 1.1, + "translation_fraction": 0.05, +} +DEPTH_CORRUPTION_DATASETS = {"H2O", "HOI4D"} +WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT = 0.01 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def derive_augmentation_config( + base: dict[str, Any], *, condition: str, resolution_hw: list[int], + resolution_decision_sha256: str, +) -> dict[str, Any]: + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = ( + "shared_augmentation_896x512" + if resolution_hw == [512, 896] + else "shared_augmentation_640" + ) + experiment["resolution_decision_sha256"] = resolution_decision_sha256 + data = config["data"] + if data["resolution_hw"] != resolution_hw: + raise ValueError("augmentation base config resolution differs") + data["geometry_augmentation"] = deepcopy(GEOMETRY_AUGMENTATION) + for source in data["sources"]: + dataset = str(source["dataset"]).upper() + source["depth_corruption_probability"] = ( + 0.3 if dataset in DEPTH_CORRUPTION_DATASETS else 0.0 + ) + return config + + +def validate_matched_augmentation( + base: dict[str, Any], derived: dict[str, Any], resolution_hw: list[int], +) -> None: + if ( + derived["seed"] != base["seed"] + or derived["model"] != base["model"] + or derived["loss"] != base["loss"] + or derived["assets"] != base["assets"] + or derived["precision"] != base["precision"] + or derived["protocol"] != base["protocol"] + or derived["data"]["resolution_hw"] != resolution_hw + or derived["data"]["T"] != base["data"]["T"] + or derived["data"]["batch_size"] != base["data"]["batch_size"] + or derived["data"].get("photometric_augmentation") + != base["data"].get("photometric_augmentation") + or derived["data"].get("validation_sources") + != base["data"].get("validation_sources") + ): + raise ValueError("augmentation config changes a matched invariant") + base_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() + if key != "depth_corruption_probability" + } + for item in base["data"]["sources"] + } + derived_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() + if key != "depth_corruption_probability" + } + for item in derived["data"]["sources"] + } + if base_sources != derived_sources: + raise ValueError("augmentation config changes source mixture/manifests") + if derived["data"]["geometry_augmentation"] != GEOMETRY_AUGMENTATION: + raise ValueError("augmentation affine parameters differ") + + +def data_artifacts_from_configs(configs: list[dict[str, Any]]) -> list[dict[str, str]]: + paths = set() + for config in configs: + for source in config["data"]["sources"]: + paths.add(Path(source["cache_manifest"]).resolve()) + for source in config["data"].get("validation_sources", []): + paths.add(Path(source["cache_manifest"]).resolve()) + return [ + {"path": str(path), "sha256": sha256(path)} for path in sorted(paths) + ] + + +def base_jobs_896( + resolution_state: dict[str, Any], decision: dict[str, Any], +) -> tuple[dict[str, dict[str, Any]], dict[str, Any]]: + evaluation_plan_path = Path(resolution_state["evaluation_plan"]) + if ( + not evaluation_plan_path.is_file() + or resolution_state.get("evaluation_plan_sha256") + != sha256(evaluation_plan_path) + ): + raise ValueError("accepted 896 evaluation plan differs") + evaluation_plan = read_json(evaluation_plan_path) + registry_path = Path(evaluation_plan["training_registry"]["path"]) + if evaluation_plan["training_registry"]["sha256"] != sha256(registry_path): + raise ValueError("accepted 896 training registry differs") + registry = read_json(registry_path) + jobs = { + role: { + "role": role, + "config": job["config"], + "config_sha256": job["config_sha256"], + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + } + for role, job in registry_job_map(registry).items() + } + context = { + "target_step": registry["target_step"], + "source_exposure_batches": registry["matched_source_exposure_batches"], + "source_exposure_frames": registry["matched_source_exposure_frames"], + "data_readiness_state": registry["data_readiness_state"], + "data_readiness_state_sha256": registry["data_readiness_state_sha256"], + "data_finalize_plan_sha256": registry["data_finalize_plan_sha256"], + "data_artifacts": registry["data_artifacts"], + "control": { + "kind": "resolution_896x512_candidate", + "evaluation_plan": { + "path": str(evaluation_plan_path.resolve()), + "sha256": sha256(evaluation_plan_path), + }, + "decision_report": decision, + }, + } + return jobs, context + + +def registry_job_map(registry: dict[str, Any]) -> dict[str, dict[str, Any]]: + result = {item["role"]: item for item in registry["conditions"]} + if set(result) != {"full", *FOLDS}: + raise ValueError("seven matched control roles differ") + return result + + +def base_jobs_640( + decision: dict[str, Any], unified_queue_path: Path, fold_queue_path: Path, + selection_path: Path, +) -> tuple[dict[str, dict[str, Any]], dict[str, Any]]: + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("winner") != decision.get("winner") + or selection.get("winner_checkpoint") != decision.get("control_checkpoint") + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("retained 640 selection evidence differs") + mixture = selection["winner"].split(":", 1)[0] + unified = read_json(unified_queue_path) + folds = read_json(fold_queue_path) + full = next(item for item in unified["conditions"] if item["condition"] == mixture) + if ( + Path(selection["winner_config"]["path"]).resolve() + != Path(full["config"]).resolve() + or selection["winner_config"]["sha256"] != full["config_sha256"] + ): + raise ValueError("retained 640 winner config differs from its mixture") + metadata = checkpoint_metadata( + Path(selection["winner_checkpoint"]["path"]), + selection["winner_checkpoint"]["sha256"], + selection["winner_config"]["sha256"], + ) + initialization = metadata["initialization_checkpoint"] + if ( + Path(initialization.get("path", "")).resolve() + != Path(full["initialization_checkpoint"]).resolve() + or initialization.get("sha256") != full["initialization_checkpoint_sha256"] + ): + raise ValueError("retained 640 initialization differs") + jobs = { + "full": { + "role": "full", "config": full["config"], + "config_sha256": full["config_sha256"], + "initialization_checkpoint": full["initialization_checkpoint"], + "initialization_checkpoint_sha256": full[ + "initialization_checkpoint_sha256" + ], + } + } + fold_jobs = {item["condition"]: item for item in folds["conditions"]} + for fold in FOLDS: + item = fold_jobs[f"{mixture}_{fold}"] + jobs[fold] = { + "role": fold, "config": item["config"], + "config_sha256": item["config_sha256"], + "initialization_checkpoint": full["initialization_checkpoint"], + "initialization_checkpoint_sha256": full[ + "initialization_checkpoint_sha256" + ], + } + readiness = Path(unified["data_readiness_state"]) + if not readiness.is_file(): + raise ValueError("retained 640 data readiness is missing") + configs = [ + yaml.safe_load(Path(item["config"]).read_text(encoding="utf-8")) + for item in jobs.values() + ] + context = { + "target_step": metadata["step"], + "source_exposure_batches": metadata["source_exposure_batches"], + "source_exposure_frames": metadata["source_exposure_frames"], + "data_readiness_state": str(readiness.resolve()), + "data_readiness_state_sha256": sha256(readiness), + "data_finalize_plan_sha256": unified["data_finalize_plan_sha256"], + "data_artifacts": data_artifacts_from_configs(configs), + "control": { + "kind": "frozen_640_winner", + "selection_report": { + "path": str(selection_path.resolve()), "sha256": sha256(selection_path), + }, + "control_evidence": next( + item for item in selection["candidates"] + if item["id"] == selection["winner"] + ), + "decision_report": decision, + }, + } + return jobs, context + + +def build_registry( + *, resolution_controller_plan_path: Path, + resolution_controller_state_path: Path, augmentation_plan_path: Path, + unified_queue_path: Path, fold_queue_path: Path, selection_path: Path, + output_root: Path, +) -> dict[str, Any]: + resolution_plan = read_json(resolution_controller_plan_path) + resolution_state = read_json(resolution_controller_state_path) + decision_path = Path(resolution_state.get("decision_report", {}).get("path", "")) + if ( + resolution_state.get("status") != "complete" + or resolution_state.get("plan_sha256") != sha256(resolution_controller_plan_path) + or resolution_state.get("official_test_used") is not False + or resolution_state.get("h2o_official_validation_used") is not False + or Path(resolution_plan["decision_report"]).resolve() != decision_path.resolve() + or not decision_path.is_file() + or resolution_state.get("decision_report", {}).get("sha256") + != sha256(decision_path) + ): + raise ValueError("resolution decision controller is not complete and bound") + decision = read_json(decision_path) + if ( + decision.get("status") != "complete" + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution decision report is not complete and isolated") + resolution_hw = decision["accepted_resolution_hw"] + if resolution_hw not in ([368, 640], [512, 896]): + raise ValueError("resolution decision value differs") + augmentation_plan = read_json(augmentation_plan_path) + if ( + augmentation_plan.get("official_test_used") is not False + or { + key: value for key, value in augmentation_plan.get("candidate", {}).get( + "geometry_augmentation", {} + ).items() if key in GEOMETRY_AUGMENTATION + } != GEOMETRY_AUGMENTATION + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "applicable_sources" + ) != ["H2O", "HOI4D"] + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "probability" + ) != 0.3 + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "conditions" + ) != list(DEPTH_CORRUPTIONS) + ): + raise ValueError("shared augmentation frozen plan differs") + + if resolution_hw == [512, 896]: + base_jobs, context = base_jobs_896(resolution_state, decision) + else: + base_jobs, context = base_jobs_640( + decision, unified_queue_path, fold_queue_path, selection_path, + ) + mixture = decision["winner"].split(":", 1)[0] + resolution_label = "896x512" if resolution_hw == [512, 896] else "640x368" + config_root = output_root / resolution_label / "phase9" / "configs" + conditions = [] + base_configs = [] + for role in ("full", *FOLDS): + job = base_jobs[role] + path = Path(job["config"]) + if not path.is_file() or sha256(path) != job["config_sha256"]: + raise ValueError(f"augmentation base config differs: {role}") + base = yaml.safe_load(path.read_text(encoding="utf-8")) + condition = f"S8A_{mixture}_{role}" + derived = derive_augmentation_config( + base, condition=condition, resolution_hw=resolution_hw, + resolution_decision_sha256=sha256(decision_path), + ) + validate_matched_augmentation(base, derived, resolution_hw) + config_path = config_root / f"{condition.lower()}.yaml" + errors = validate_phase9_unified_contract(derived, config_path) + if errors: + raise ValueError("; ".join(errors)) + write_config(config_path, derived) + run_dir = output_root / resolution_label / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"augmentation run exists before freeze: {run_dir}") + target_step = int(context["target_step"]) + conditions.append({ + "condition": condition, "role": role, + "config": str(config_path.resolve()), "config_sha256": sha256(config_path), + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / resolution_label / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": context[ + "source_exposure_batches" + ], + "expected_source_exposure_frames": context["source_exposure_frames"], + }) + base_configs.append(base) + data_artifacts = data_artifacts_from_configs(base_configs) + context_artifacts = { + item["path"]: item["sha256"] for item in context["data_artifacts"] + } + if any( + context_artifacts.get(item["path"]) != item["sha256"] + for item in data_artifacts + ): + raise ValueError("augmentation data artifacts differ from control") + # Preserve the stronger control set, including heldout and fold-index hashes. + data_artifacts = context["data_artifacts"] + return { + "schema_version": "phase9_shared_augmentation_training_registry_v1", + "status": "frozen_ready", + "created_utc": decision["created_utc"], + "winner": decision["winner"], + "resolution_hw": resolution_hw, + "resolution_decision": { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + }, + "shared_augmentation_plan": { + "path": str(augmentation_plan_path.resolve()), + "sha256": sha256(augmentation_plan_path), + }, + "control": context["control"], + "target_step": context["target_step"], + "matched_source_exposure_batches": context["source_exposure_batches"], + "matched_source_exposure_frames": context["source_exposure_frames"], + "data_readiness_state": context["data_readiness_state"], + "data_readiness_state_sha256": context["data_readiness_state_sha256"], + "data_finalize_plan_sha256": context["data_finalize_plan_sha256"], + "data_artifacts": data_artifacts, + "gate": { + "macro_absolute_mm_must_strictly_improve": True, + "worst_domain_relative_regression_limit": ( + WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT + ), + "stage9_preceding_mechanism_requires_worst_strict_improvement": True, + }, + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--resolution-controller-plan", type=Path, required=True) + parser.add_argument("--resolution-controller-state", type=Path, required=True) + parser.add_argument("--augmentation-plan", type=Path, required=True) + parser.add_argument("--unified-queue", type=Path, required=True) + parser.add_argument("--fold-queue", type=Path, required=True) + parser.add_argument("--selection-report", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + registry = build_registry( + resolution_controller_plan_path=args.resolution_controller_plan, + resolution_controller_state_path=args.resolution_controller_state, + augmentation_plan_path=args.augmentation_plan, + unified_queue_path=args.unified_queue, + fold_queue_path=args.fold_queue, + selection_path=args.selection_report, + output_root=args.output_root, + ) + if args.output_registry.exists(): + if read_json(args.output_registry) != registry: + raise ValueError("existing augmentation registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_registry_state_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_shared_augmentation_registry_state_v1", + "status": "complete", "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "resolution_hw": registry["resolution_hw"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_sota_ground_truth.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_sota_ground_truth.py new file mode 100644 index 0000000000000000000000000000000000000000..d859aa4924bd3147b0a16d71a3f7164a13e2f25e --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/build_sota_ground_truth.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Build the immutable H2O GT bundle shared by all SOTA baseline evaluations.""" + +from __future__ import annotations + +import argparse +import hashlib +from pathlib import Path + +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import ( + load_float_record, + load_joint_record, + load_mano_record, +) +from foundation_hand.evaluation.sota import GroundTruthBundle, load_frame_index +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models.mano import ManoCameraLayer + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=256) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + keys, takes, frame_ids = load_frame_index(args.manifest) + count = len(keys) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + pose = np.zeros((count, 2, 48), dtype=np.float32) + shape = np.zeros((count, 2, 10), dtype=np.float32) + valid = np.zeros((count, 2), dtype=bool) + intrinsics = np.zeros((count, 3, 3), dtype=np.float32) + intrinsics_cache: dict[str, np.ndarray] = {} + + for index, (take_name, frame_id) in enumerate(zip(takes, frame_ids, strict=True)): + take = args.root / str(take_name) + stem = f"{int(frame_id):06d}" + joint_record = load_joint_record(take / "hand_pose" / f"{stem}.txt") + mano_record = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + if not np.array_equal(joint_record.annotation_valid, mano_record.annotation_valid): + raise ValueError(f"Joint/MANO validity mismatch: {keys[index]}") + valid[index] = joint_record.annotation_valid + joints[index] = joint_record.joints_camera_m + pose[index] = mano_record.pose_axis_angle + shape[index] = mano_record.shape + if str(take_name) not in intrinsics_cache: + values = load_float_record(take / "cam_intrinsics.txt") + intrinsics_cache[str(take_name)] = intrinsics_from_h2o(values)[0] + intrinsics[index] = intrinsics_cache[str(take_name)] + + joints[~valid] = np.nan + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + device = torch.device(args.device) + mano = ManoCameraLayer(args.mano_root).to(device).eval() + for start in range(0, count, args.batch_size): + end = min(start + args.batch_size, count) + pose_tensor = torch.from_numpy(pose[start:end]).to(device) + shape_tensor = torch.from_numpy(shape[start:end]).to(device) + wrist_tensor = torch.from_numpy(np.nan_to_num(joints[start:end, :, 0])).to(device) + with torch.no_grad(): + batch_vertices, _ = mano( + axis_angle_to_matrix(pose_tensor.reshape(end - start, 2, 16, 3)), + shape_tensor, + wrist_tensor, + ) + vertices[start:end] = batch_vertices.cpu().numpy() + vertices[~valid] = np.nan + + bundle = GroundTruthBundle( + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + annotation_valid=valid, + intrinsics=intrinsics, + metadata={ + "source": "H2O official validation cam4", + "official_test_used": False, + "manifest": str(args.manifest.resolve()), + "manifest_sha256": sha256(args.manifest), + "frames": count, + "runs": len(args.manifest.read_text(encoding="utf-8").splitlines()), + "takes": len(set(map(str, takes.tolist()))), + "joint_order": "H2O/OpenPose wrist-thumb-index-middle-ring-pinky", + "units": "meters", + }, + ) + bundle.save(args.output) + print(f"saved {count} frames to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase4_jitter_predictions.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase4_jitter_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..c638edc649e36a24ec91b04ad2594e22ffe09fcd --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase4_jitter_predictions.py @@ -0,0 +1,399 @@ +#!/usr/bin/env python3 +"""Cache hash-bound raw official-validation predictions for jitter evaluation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +CACHE_VERSION = 1 +FPS = 30.0 +FRAME_ARRAYS = ( + "clip_index", + "frame_id", + "frame_valid", + "K", + "pred_rotation_matrices", + "pred_shape", + "pred_wrist_translation", + "pred_joints_camera", + "pred_vertices_camera", + "pred_direct_2d_px", + "target_rotation_matrices", + "target_shape", + "target_wrist_translation", + "target_joints_camera", + "target_vertices_camera", + "target_2d_px", + "joint_annotation_valid", + "joint_element_valid", + "mano_annotation_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def take_slug(take: str) -> str: + parts = Path(take).parts + if len(parts) != 4 or parts[-1] != "cam4": + raise ValueError(f"unexpected H2O take: {take}") + return "__".join(parts) + + +def manifest_frame_count(path: Path) -> int: + identities: set[tuple[str, int]] = set() + rows = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + record = json.loads(line) + take = str(record["take"]) + for frame_id in record["frame_ids"]: + identity = (take, int(frame_id)) + if identity in identities: + raise ValueError(f"duplicate manifest frame: {take}/{int(frame_id)}") + identities.add(identity) + rows += 1 + if rows == 0: + raise ValueError("prediction cache manifest is empty") + return rows + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def apply_input_condition( + batch: dict[str, Any], condition: str, +) -> dict[str, Any]: + if condition == "complete": + return batch + model_batch = dict(batch) + if condition == "missing_depth": + model_batch["depth_available"] = torch.zeros_like(batch["depth_available"]) + model_batch["depth_m"] = torch.zeros_like(batch["depth_m"]) + model_batch["depth_pixel_valid"] = torch.zeros_like(batch["depth_pixel_valid"]) + return model_batch + if condition == "missing_k": + model_batch["K_available"] = torch.zeros_like(batch["K_available"]) + identity = torch.eye(3, dtype=batch["K"].dtype, device=batch["K"].device) + model_batch["K"] = identity.expand_as(batch["K"]).clone() + return model_batch + raise ValueError(f"unsupported input condition: {condition}") + + +def target_geometry( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for jitter cache targets") + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, joints = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + return rotations, vertices, joints + + +def validate_cache_arrays( + arrays: dict[str, np.ndarray], + *, + take: str, + expected_frame_ids: list[int], + checkpoint_sha256: str, + config_sha256: str, + manifest_sha256: str, + input_condition: str = "complete", +) -> None: + missing = sorted(set(FRAME_ARRAYS) - arrays.keys()) + if missing: + raise ValueError(f"raw jitter cache is missing arrays: {missing}") + if int(arrays["cache_version"]) != CACHE_VERSION: + raise ValueError("raw jitter cache version mismatch") + scalar_expectations = { + "take": take, + "checkpoint_sha256": checkpoint_sha256, + "config_sha256": config_sha256, + "manifest_sha256": manifest_sha256, + } + for key, expected in scalar_expectations.items(): + if str(arrays[key]) != expected: + raise ValueError(f"raw jitter cache {key} mismatch") + if input_condition != "complete" and str(arrays.get("input_condition", "")) != input_condition: + raise ValueError("raw jitter cache input condition mismatch") + frame_ids = arrays["frame_id"].astype(np.int64).tolist() + if frame_ids != expected_frame_ids or len(frame_ids) != len(set(frame_ids)): + raise ValueError(f"raw jitter cache frame sequence mismatch for {take}") + for key in FRAME_ARRAYS: + if arrays[key].shape[0] != len(frame_ids): + raise ValueError(f"raw jitter cache time dimension mismatch: {key}") + if np.issubdtype(arrays[key].dtype, np.floating): + finite = np.isfinite(arrays[key]) + if key.startswith("target_"): + # Invalid annotations are intentionally retained as NaN. + continue + if not finite.all(): + raise ValueError(f"raw jitter cache prediction is non-finite: {key}") + + +def load_valid_cache( + path: Path, + **expected: object, +) -> dict[str, np.ndarray] | None: + if not path.is_file(): + return None + try: + with np.load(path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + validate_cache_arrays(arrays, **expected) + except (OSError, KeyError, ValueError): + return None + return arrays + + +def build_model( + config: dict[str, Any], checkpoint: Path, device: torch.device, +) -> tuple[BimanualReconstructionModel, int]: + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(checkpoint, model, optimizer=None, map_location=device) + return model, int(state["step"]) + + +def infer_take( + *, + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + input_condition: str, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + subset = Subset(dataset, clip_indices) + loader = DataLoader( + subset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + for global_clip_index, batch_cpu in zip(clip_indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + target_rotations, target_vertices, _ = target_geometry(batch, model) + model_batch = apply_input_condition(batch, input_condition) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(model_batch) + valid_times = int(batch["frame_valid"][0].sum()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor( + (width, height), device=device, + ) + values: dict[str, torch.Tensor] = { + "clip_index": torch.full( + (valid_times,), global_clip_index, device=device, dtype=torch.int64, + ), + "frame_id": batch["frame_id"][0, :valid_times], + "frame_valid": batch["frame_valid"][0, :valid_times], + "K": batch["K"][0, :valid_times], + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0, :valid_times], + "pred_shape": prediction["mano_shape"][0, :valid_times], + "pred_wrist_translation": prediction["wrist_root_translation"][0, :valid_times], + "pred_joints_camera": prediction["joints_camera"][0, :valid_times], + "pred_vertices_camera": prediction["vertices_camera"][0, :valid_times], + "pred_direct_2d_px": direct_2d[0, :valid_times], + "target_rotation_matrices": target_rotations[0, :valid_times], + "target_shape": batch["mano_shape"][0, :valid_times], + "target_wrist_translation": batch["wrist_root_translation"][0, :valid_times], + "target_joints_camera": batch["joint3d_camera"][0, :valid_times], + "target_vertices_camera": target_vertices[0, :valid_times], + "target_2d_px": batch["joint2d"][0, :valid_times], + "joint_annotation_valid": batch["joint_annotation_valid"][0, :valid_times], + "joint_element_valid": batch["joint_element_valid"][0, :valid_times], + "mano_annotation_valid": batch["mano_annotation_valid"][0, :valid_times], + } + for key, value in values.items(): + array = value.detach().float().cpu().numpy() if value.is_floating_point() else value.cpu().numpy() + chunks[key].append(array) + return {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), default=0) + parser.add_argument("--max-clips", type=int) + parser.add_argument( + "--input-condition", choices=("complete", "missing_depth", "missing_k"), + default="complete", + ) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("jitter cache is hard-gated to official validation") + if args.max_clips is not None and args.max_clips < 1: + parser.error("--max-clips must be positive") + if not torch.cuda.is_available(): + parser.error("CUDA is required") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + config_hash = sha256(args.config) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (int(config["data"]["T"]),), (int(config["data"]["stride"]),), + max_clips=args.max_clips, + oracle_crop_enabled=config["model"].get("oracle_crop_mode", "none") != "none", + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + expected_frames = { + take: [ + frame_id + for index in indices + for frame_id in dataset.clips[index].frame_ids + ] + for take, indices in indices_by_take.items() + } + if any(len(values) != len(set(values)) for values in expected_frames.values()): + raise ValueError("jitter cache requires non-overlapping inference clips") + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model: BimanualReconstructionModel | None = None + checkpoint_step: int | None = None + records = [] + for take_index, (take, clip_indices) in enumerate(indices_by_take.items(), start=1): + output = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "manifest_sha256": manifest_hash, + "input_condition": args.input_condition, + } + arrays = load_valid_cache(output, **expected) + status = "reused" + if arrays is None: + if output.exists(): + raise ValueError(f"existing jitter cache failed validation: {output}") + if model is None: + model, checkpoint_step = build_model(config, args.checkpoint, device) + arrays = infer_take( + dataset=dataset, clip_indices=clip_indices, model=model, + device=device, dtype=dtype, input_condition=args.input_condition, + ) + arrays.update({ + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + "take": np.asarray(take), + "fps": np.asarray(FPS, dtype=np.float32), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "manifest_sha256": np.asarray(manifest_hash), + "input_condition": np.asarray(args.input_condition), + }) + validate_cache_arrays(arrays, **expected) + save_npz_atomic(output, arrays) + status = "written" + records.append({ + "take": take, "clips": len(clip_indices), + "frames": len(expected_frames[take]), "path": str(output), + "sha256": sha256(output), "status": status, + }) + print( + f"[{take_index}/{len(indices_by_take)}] {take}: " + f"{records[-1]['frames']} frames ({status})", + flush=True, + ) + if checkpoint_step is None: + # Read the step only when every cache was reused. + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + checkpoint_step = int(state["step"]) + total_frames = sum(record["frames"] for record in records) + full_validation = args.max_clips is None + expected_full_frames = manifest_frame_count(args.manifest) + if full_validation and total_frames != expected_full_frames: + raise ValueError( + "official-validation cache does not cover every manifest frame exactly once" + ) + report = { + "status": "complete", + "official_test_used": False, + "split_role": "official_validation", + "scope": "full" if full_validation else "smoke", + "fps": FPS, + "temporal_length": int(config["data"]["T"]), + "clip_boundary_filter_reset_required": True, + "input_condition": args.input_condition, + "missing_rgb_status": "unsupported_no_rgb_availability_or_training_dropout", + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": checkpoint_step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, + stdout=subprocess.PIPE, check=False, + ).stdout.strip(), + "clips": len(dataset), "frames": total_frames, + "expected_manifest_frames": expected_full_frames, "takes": records, + } + (args.output_dir / "cache_manifest.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "clips": report["clips"], + "frames": report["frames"], "takes": len(records), + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase6_sequence_predictions.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase6_sequence_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..5914ff7c6988c0f4da8b47b226fbbf1b7c0337e7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase6_sequence_predictions.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Cache bounded-window Phase 6 sequence predictions in the frozen raw schema.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from scripts.cache_phase4_jitter_predictions import ( + CACHE_VERSION, + FPS, + build_model, + load_valid_cache, + manifest_frame_count, + move_to_device, + save_npz_atomic, + sha256, + take_slug, + target_geometry, + validate_cache_arrays, +) + + +def validate_sequence_config(config: dict, mode: str) -> None: + """Validate model causality; frame iteration itself always supplies T=1.""" + + attention_mode = config["model"].get("temporal_attention_mode", "bidirectional") + expected_attention = "causal" if mode == "causal" else "bidirectional" + if attention_mode != expected_attention: + raise ValueError("sequence mode differs from config temporal attention mode") + + +def offline_stride(window: int, mode: str) -> int | None: + return max(window // 2, 1) if mode == "offline" else None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--max-takes", type=int) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("sequence cache is hard-gated to official validation") + if args.window < 1: + parser.error("window must be positive") + if args.max_takes is not None and args.max_takes < 1: + parser.error("max-takes must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + try: + validate_sequence_config(config, args.mode) + except ValueError as error: + parser.error(str(error)) + + config_hash = sha256(args.config) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (1,), (1,), + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + if args.max_takes is not None: + indices_by_take = dict(list(indices_by_take.items())[: args.max_takes]) + expected_frames = { + take: [dataset.clips[index].frame_ids[0] for index in indices] + for take, indices in indices_by_take.items() + } + if any(len(ids) != len(set(ids)) for ids in expected_frames.values()): + raise ValueError("sequence cache input contains duplicate take/frame identities") + + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model = None + checkpoint_step = None + records = [] + maximum_gpu_window = 0 + maximum_cpu_buffer = 0 + for take_index, (take, indices) in enumerate(indices_by_take.items(), start=1): + output_path = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "manifest_sha256": manifest_hash, + "input_condition": "complete", + } + arrays = load_valid_cache(output_path, **expected) + status = "reused" + if arrays is None: + if output_path.exists(): + raise ValueError(f"existing sequence cache failed validation: {output_path}") + if model is None: + model, checkpoint_step = build_model(config, args.checkpoint, device) + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.mode, window_size=args.window, + offline_stride=offline_stride(args.window, args.mode), + ), + device=device, autocast_dtype=dtype, + ) + target_chunks: dict[str, list[np.ndarray]] = defaultdict(list) + loader = DataLoader( + Subset(dataset, indices), batch_size=1, shuffle=False, + num_workers=0, collate_fn=collate_h2o_clips, pin_memory=True, + ) + + def frames(): + for global_index, batch_cpu in zip(indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + rotations, vertices, _ = target_geometry(batch, model) + values = { + # One output file is one continuous take. Frame gaps and + # frame_valid, not the source dataset index, delimit segments. + "clip_index": np.asarray([0], dtype=np.int64), + "frame_id": batch_cpu["frame_id"][0].numpy(), + "frame_valid": batch_cpu["frame_valid"][0].numpy(), + "K": batch_cpu["K"][0].numpy(), + "target_rotation_matrices": rotations[0].float().cpu().numpy(), + "target_shape": batch_cpu["mano_shape"][0].numpy(), + "target_wrist_translation": batch_cpu["wrist_root_translation"][0].numpy(), + "target_joints_camera": batch_cpu["joint3d_camera"][0].numpy(), + "target_vertices_camera": vertices[0].float().cpu().numpy(), + "target_2d_px": batch_cpu["joint2d"][0].numpy(), + "joint_annotation_valid": batch_cpu["joint_annotation_valid"][0].numpy(), + "joint_element_valid": batch_cpu["joint_element_valid"][0].numpy(), + "mano_annotation_valid": batch_cpu["mano_annotation_valid"][0].numpy(), + } + for key, value in values.items(): + target_chunks[key].append(value) + yield batch_cpu + + prediction = runner.infer(frames()) + height, width = config["data"]["resolution_hw"] + predicted = { + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0].float().numpy(), + "pred_shape": prediction["mano_shape"][0].float().numpy(), + "pred_wrist_translation": prediction["wrist_root_translation"][0].float().numpy(), + "pred_joints_camera": prediction["joints_camera"][0].float().numpy(), + "pred_vertices_camera": prediction["vertices_camera"][0].float().numpy(), + "pred_direct_2d_px": ( + prediction["joint2d_norm"][0].float() + * torch.tensor((width, height)) + ).numpy(), + } + arrays = { + **{key: np.concatenate(values, axis=0) for key, values in target_chunks.items()}, + **predicted, + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + "take": np.asarray(take), + "fps": np.asarray(FPS, dtype=np.float32), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "manifest_sha256": np.asarray(manifest_hash), + "input_condition": np.asarray("complete"), + "sequence_mode": np.asarray(args.mode), + "sequence_window": np.asarray(args.window, dtype=np.int32), + } + validate_cache_arrays(arrays, **expected) + save_npz_atomic(output_path, arrays) + maximum_gpu_window = max(maximum_gpu_window, runner.maximum_resident_frames) + maximum_cpu_buffer = max(maximum_cpu_buffer, runner.maximum_input_buffer_frames) + status = "written" + records.append({ + "take": take, "clips": len(indices), "frames": len(expected_frames[take]), + "path": str(output_path), "sha256": sha256(output_path), "status": status, + }) + print(f"[{take_index}/{len(indices_by_take)}] {take} ({status})", flush=True) + + if checkpoint_step is None: + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + checkpoint_step = int(state["step"]) + total_frames = sum(record["frames"] for record in records) + expected_total = ( + manifest_frame_count(args.manifest) if args.max_takes is None + else sum(len(frame_ids) for frame_ids in expected_frames.values()) + ) + if total_frames != expected_total: + raise ValueError("sequence cache does not cover the frozen manifest exactly") + report = { + "status": "complete", + "experiment": "P6_S5_length_generalized_inference", + "official_test_used": False, + "official_validation_used_for_selection": False, + "split_role": "official_validation", + "scope": "full" if args.max_takes is None else "smoke", + "fps": FPS, + "temporal_length": 1, + "sequence_mode": args.mode, + "sequence_window": args.window, + "offline_stride": offline_stride(args.window, args.mode), + "stitching": "center" if args.mode == "offline" else None, + "maximum_gpu_window_frames": maximum_gpu_window, + "maximum_cpu_input_buffer_frames": maximum_cpu_buffer, + "input_condition": "complete", + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": checkpoint_step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + "clips": len(dataset), "frames": total_frames, + "expected_manifest_frames": expected_total, "takes": records, + } + (args.output_dir / "cache_manifest.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "mode": args.mode, "window": args.window, + "frames": total_frames, "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase7_h2o_train.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase7_h2o_train.py new file mode 100644 index 0000000000000000000000000000000000000000..14a83bba28b96456e9238ece26d398545cc921eb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase7_h2o_train.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Build a bounded canonical cache from H2O official train only.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import math +from pathlib import Path +import time + +import numpy as np + +from foundation_hand.data import H2OCam4Dataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from scripts.cache_phase7_hot3d import ( + validate_cached_resolution, + validated_target_hw, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_train_manifest_path(path: Path) -> None: + if path.name != "official_train.jsonl": + raise ValueError("H2O adaptation cache requires canonical official_train.jsonl") + + +def center_out(values: list[int]) -> list[int]: + values = sorted(values) + center = (len(values) - 1) // 2 + order = [center] + distance = 1 + while len(order) < len(values): + if center + distance < len(values): + order.append(center + distance) + if center - distance >= 0: + order.append(center - distance) + distance += 1 + return [values[index] for index in order] + + +def balanced_clip_indices( + clips: list, count: int, max_recordings: int, +) -> list[int]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, clip in enumerate(clips): + parts = Path(clip.take).parts + groups[(parts[0], "/".join(parts[:-1]))].append(index) + strata: dict[str, list[tuple[str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[0]].append(key) + selected_groups: list[tuple[str, str]] = [] + cursor = 0 + while len(selected_groups) < min(max_recordings, len(groups)): + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected_groups.append(strata[subject][cursor]) + progress = True + if len(selected_groups) == max_recordings: + break + if not progress: + break + cursor += 1 + ordered = {key: center_out(groups[key]) for key in selected_groups} + selected = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in selected_groups: + if cursor < len(ordered[key]): + selected.append(ordered[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def rgb_uint8(rgb: np.ndarray) -> np.ndarray: + image = np.transpose(rgb, (0, 2, 3, 1)) + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int, required=True) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument("--resume", action="store_true") + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + validate_train_manifest_path(args.source_manifest) + if min(args.clips, args.max_recordings) <= 0: + parser.error("clip and recording counts must be positive") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + dataset = H2OCam4Dataset( + args.root, args.source_manifest, target_hw=target_hw, + clip_lengths=(8,), strides=(1,), + ) + candidate_count = min( + len(dataset), args.clips + max(32, math.ceil(args.clips * 0.1)), + ) + selected = balanced_clip_indices(dataset.clips, candidate_count, args.max_recordings) + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced H2O train clips are available") + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", "vertices_camera", + } + cached: dict[int, dict] = {} + skipped: list[int] = [] + started = time.monotonic() + for position, source_index in enumerate(selected, 1): + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise RuntimeError(f"invalid existing cache: {output}") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + else: + sample = dataset[(source_index, 0)] + has_supervision = bool(sample["translation_valid"].any()) + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + clip = dataset.clips[source_index] + parts = Path(clip.take).parts + if has_supervision: + cached[source_index] = { + "dataset_id": "H2O", + "subject_id": parts[0], + "sequence_id": "/".join(parts[1:-1]), + "physical_recording_id": "/".join(parts[:-1]), + "camera_id": "cam4", "stream_id": "cam4-rgb", + "headset_id": "H2O-ego", "source_clip_index": source_index, + "source_group_key": f"H2O/{'/'.join(parts[:-1])}", + "resolution_hw": list(target_hw), + "cache_path": str(output.resolve()), "cache_sha256": sha256(output), + } + else: + skipped.append(source_index) + if position % 10 == 0 or position == len(selected): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": position, "requested": len(selected), + "cached": len(cached), "skipped_no_supervision": len(skipped), + "clips_per_second": position / elapsed, + }), flush=True) + ordered_valid = [index for index in selected if index in cached][:args.clips] + if len(ordered_valid) == args.clips: + break + manifest = args.output_dir / "cache_manifest.jsonl" + temporary_manifest = manifest.with_suffix(".tmp") + temporary_manifest.write_text( + "".join(json.dumps(cached[index], sort_keys=True) + "\n" for index in ordered_valid), + encoding="utf-8", + ) + temporary_manifest.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": "complete" if len(ordered_valid) == args.clips else "insufficient_valid_clips", + "dataset": "H2O", "split_role": "official_train", + "source_manifest": { + "path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest), + }, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "requested_clips": args.clips, "candidate_clips_processed": position, + "resolution_hw": list(target_hw), + "cached_clips": len(ordered_valid), "valid_candidate_files": len(cached), + "recordings": len({cached[index]["physical_recording_id"] for index in ordered_valid}), + "skipped_no_supervision": skipped, + "wall_seconds": elapsed, "clips_per_second": position / elapsed, + "bytes": sum(Path(cached[index]["cache_path"]).stat().st_size for index in ordered_valid), + "resume_invocation": bool(args.resume), + "h2o_official_validation_used": False, "official_test_used": False, + } + (args.output_dir / "cache_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase7_hot3d.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase7_hot3d.py new file mode 100644 index 0000000000000000000000000000000000000000..7f6273de04231e6edb06c4fbfdacf1fe2547e592 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase7_hot3d.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Build a bounded, source-hash-bound HOT3D clip cache.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +import time + +import numpy as np + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def validated_target_hw(values: tuple[int, int] | list[int]) -> tuple[int, int]: + """Validate the full-frame cache resolution used by every source writer.""" + + if len(values) != 2: + raise ValueError("target resolution must contain height and width") + height, width = (int(value) for value in values) + if min(height, width) <= 0: + raise ValueError("target resolution dimensions must be positive") + return height, width + + +def validate_cached_resolution( + archive: np.lib.npyio.NpzFile, target_hw: tuple[int, int], +) -> None: + if "image_hw" not in archive.files: + raise ValueError("cached payload lacks image_hw") + image_hw = tuple(int(value) for value in np.asarray(archive["image_hw"]).reshape(-1)) + if image_hw != target_hw: + raise ValueError( + f"cached payload resolution {image_hw} does not match requested {target_hw}" + ) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def sha256_json(value: object) -> str: + payload = json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + return hashlib.sha256(payload).hexdigest() + + +def decode_position_slice( + decode_order: list[int], position_range: tuple[int, int] | None, +) -> tuple[list[int], tuple[int, int] | None]: + if position_range is None: + return decode_order, None + start, stop = position_range + if start < 0 or stop <= start or stop > len(decode_order): + raise ValueError( + f"invalid prefill position range [{start}, {stop}) for {len(decode_order)} candidates" + ) + return decode_order[start:stop], (start, stop) + + +def balanced_recording_keys( + groups: dict[tuple[str, str, str], list[int]], max_recordings: int, +) -> list[tuple[str, str, str]]: + strata: dict[tuple[str, str], list[tuple[str, str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[:2]].append(key) + selected: list[tuple[str, str, str]] = [] + cursor = 0 + while len(selected) < min(max_recordings, len(groups)): + progress = False + for stratum in sorted(strata): + if cursor < len(strata[stratum]): + selected.append(strata[stratum][cursor]) + progress = True + if len(selected) == max_recordings: + break + if not progress: + break + cursor += 1 + return selected + + +def balanced_indices( + rows: list[dict], count: int, max_recordings: int | None = None, +) -> list[int]: + groups: dict[tuple[str, str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + groups[(row["headset"], row["participant_id"], row["recording_id"])].append(index) + keys = sorted(groups) + if max_recordings is not None: + if max_recordings <= 0: + raise ValueError("max_recordings must be positive") + keys = balanced_recording_keys(groups, max_recordings) + selected: list[int] = [] + cursor = 0 + while len(selected) < min(count, len(rows)): + progress = False + for key in keys: + values = groups[key] + if cursor < len(values): + selected.append(values[cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def cache_candidate_count(requested: int, available: int) -> int: + return min(available, requested + max(64, int(np.ceil(requested * 0.1)))) + + +def first_valid_indices( + selected: list[int], cached: dict[int, dict], requested: int, +) -> list[int]: + return [index for index in selected if index in cached][:requested] + + +def should_stop_decoding( + selected: list[int], cached: dict[int, dict], requested: int, + decode_all_candidates: bool, +) -> bool: + """Stop early only when full candidate decoding was not requested.""" + + return ( + not decode_all_candidates + and len(first_valid_indices(selected, cached, requested)) == requested + ) + + +def rgb_uint8(rgb: np.ndarray) -> np.ndarray: + image = np.transpose(rgb, (0, 2, 3, 1)) + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument( + "--decode-all-candidates", action="store_true", + help="Decode the complete balanced overdraw pool before freezing the valid prefix.", + ) + parser.add_argument( + "--prefill-position-range", type=int, nargs=2, metavar=("START", "STOP"), + help=( + "Decode a zero-based half-open slice of the frozen candidate order into " + "a staging cache; no deployable cache manifest is produced." + ), + ) + parser.add_argument("--resume", action="store_true") + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + if args.clips < 1: + parser.error("--clips must be positive") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing output clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + dataset = HOT3DClipDataset( + args.root, args.source_manifest, args.toolkit_root, args.mano_root, + K_input_dropout=0.0, provider_cache_size=2, target_hw=target_hw, + ) + candidate_count = cache_candidate_count(args.clips, len(dataset.rows)) + selected = balanced_indices(dataset.rows, candidate_count, args.max_recordings) + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced candidates are available") + # Decode in recording order to avoid reopening VRS files for every clip. + full_decode_order = sorted( + selected, + key=lambda index: ( + dataset.rows[index]["recording_id"], + dataset.rows[index]["stream_id"], + dataset.rows[index]["timestamps_ns"][0], + ), + ) + prefill_range = ( + tuple(args.prefill_position_range) + if args.prefill_position_range is not None else None + ) + try: + decode_order, prefill_range = decode_position_slice( + full_decode_order, prefill_range, + ) + except ValueError as error: + parser.error(str(error)) + if prefill_range is not None and not args.decode_all_candidates: + parser.error("--prefill-position-range requires --decode-all-candidates") + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", + } + cache_rows: dict[int, dict] = {} + skipped_no_supervision: list[int] = [] + started = time.monotonic() + for position, source_index in enumerate(decode_order, 1): + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + try: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise ValueError("required cache arrays missing") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + if { + "source_hand_annotation_present", "geometry_convention_compatible", + }.issubset(archive.files): + masked_geometry = int(np.count_nonzero( + archive["source_hand_annotation_present"] + & ~archive["geometry_convention_compatible"] + )) + else: + # The previous strict writer raised before saving any + # clip containing a regeneration mismatch. + masked_geometry = 0 + except Exception as error: + raise RuntimeError(f"existing resume cache is invalid: {output}: {error}") from error + else: + sample = dataset[(source_index, 0)] + has_supervision = bool(sample["translation_valid"].any()) + masked_geometry = int(( + sample["source_hand_annotation_present"] + & ~sample["geometry_convention_compatible"] + ).sum()) + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + if has_supervision: + row = dataset.rows[source_index] + cache_rows[source_index] = { + "dataset_id": "HOT3D", + "subject_id": row["participant_id"], + "sequence_id": row["recording_id"], + "physical_recording_id": row["recording_id"], + "camera_id": row["stream_id"], + "stream_id": row["stream_id"], + "headset_id": row["headset"], + "source_clip_index": source_index, + "source_group_key": row["group_key"], + "resolution_hw": list(target_hw), + "geometry_masked_hand_frames": masked_geometry, + "cache_path": str(output.resolve()), + "cache_sha256": sha256(output), + } + else: + skipped_no_supervision.append(source_index) + if position % 10 == 0 or position == len(decode_order): + elapsed = time.monotonic() - started + print(json.dumps({ + "decoded": position, "total": len(decode_order), + "cached": len(cache_rows), + "skipped_no_supervision": len(skipped_no_supervision), + "clips_per_second": position / elapsed, + "eta_seconds": (len(decode_order) - position) / (position / elapsed), + }), flush=True) + if prefill_range is None and should_stop_decoding( + selected, cache_rows, args.clips, args.decode_all_candidates, + ): + break + if prefill_range is None: + ordered_cached = first_valid_indices(selected, cache_rows, args.clips) + manifest = args.output_dir / "cache_manifest.jsonl" + status = "complete" if len(ordered_cached) == args.clips else "insufficient_valid_clips" + mode = "deployable_cache" + else: + ordered_cached = [index for index in decode_order if index in cache_rows] + manifest = args.output_dir / "prefill_manifest.jsonl" + status = ( + "complete" + if len(ordered_cached) + len(skipped_no_supervision) == len(decode_order) + else "incomplete_prefill" + ) + mode = "staged_prefill" + temporary_manifest = manifest.with_suffix(".tmp") + temporary_manifest.write_text( + "".join(json.dumps(cache_rows[index], sort_keys=True) + "\n" for index in ordered_cached), + encoding="utf-8", + ) + temporary_manifest.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": status, + "mode": mode, + "official_test_used": False, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "clips": len(ordered_cached), + "candidate_clips_processed": position, + "full_candidate_clips": len(full_decode_order), + "requested_target_clips": args.clips, + "resolution_hw": list(target_hw), + "max_recordings": args.max_recordings, + "candidate_position_range": list(prefill_range) if prefill_range else None, + "candidate_source_indices_sha256": sha256_json(full_decode_order), + "recordings": len({cache_rows[index]["source_group_key"] for index in ordered_cached}), + "skipped_no_supervision": skipped_no_supervision, + "geometry_masked_hand_frames": sum( + cache_rows[index]["geometry_masked_hand_frames"] for index in ordered_cached + ), + "geometry_masked_source_indices": [ + index for index in ordered_cached + if cache_rows[index]["geometry_masked_hand_frames"] + ], + "decode_all_candidates": bool(args.decode_all_candidates), + "resume_invocation": bool(args.resume), + "wall_seconds": elapsed, + "clips_per_second": position / elapsed, + "bytes": sum(Path(cache_rows[index]["cache_path"]).stat().st_size for index in ordered_cached), + } + report_path = args.output_dir / "cache_report.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase7_unified_source.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase7_unified_source.py new file mode 100644 index 0000000000000000000000000000000000000000..72c1f102f49f8b1c31bd065469ea43d9f629b1cf --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/cache_phase7_unified_source.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Build resumable controlled caches for HOI4D or ARCTIC unified clips.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import math +from pathlib import Path +import time + +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset +from foundation_hand.data.schema import InvalidSourceSampleError +from scripts.cache_phase7_hot3d import ( + rgb_uint8, + validate_cached_resolution, + validated_target_hw, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def center_out(values: list[int]) -> list[int]: + values = sorted(values) + center = (len(values) - 1) // 2 + order = [center] + distance = 1 + while len(order) < len(values): + if center + distance < len(values): + order.append(center + distance) + if center - distance >= 0: + order.append(center - distance) + distance += 1 + return [values[index] for index in order] + + +def balanced_source_indices( + rows: list[dict], count: int, max_recordings: int, +) -> list[int]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + groups[(str(row["subject_id"]), str(row["physical_recording_id"]))].append(index) + strata: dict[str, list[tuple[str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[0]].append(key) + selected_groups: list[tuple[str, str]] = [] + cursor = 0 + while len(selected_groups) < min(max_recordings, len(groups)): + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected_groups.append(strata[subject][cursor]) + progress = True + if len(selected_groups) == max_recordings: + break + if not progress: + break + cursor += 1 + ordered = {key: center_out(groups[key]) for key in selected_groups} + selected: list[int] = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in selected_groups: + if cursor < len(ordered[key]): + selected.append(ordered[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def hand_side_source_indices(rows: list[dict], required_side: str) -> list[int]: + if required_side == "any": + return list(range(len(rows))) + if required_side not in {"left", "right"}: + raise ValueError("required hand side must be any, left or right") + return [ + index for index, row in enumerate(rows) + if any(required_side in sides for sides in row.get("hand_sides", [])) + ] + + +def cache_candidate_count(requested: int, available: int) -> int: + """Overdraw a deterministic candidate pool so invalid clips can be replaced.""" + return min(available, requested + max(32, math.ceil(requested * 0.1))) + + +def first_valid_indices( + selected: list[int], cached: dict[int, dict], requested: int, +) -> list[int]: + return [index for index in selected if index in cached][:requested] + + +def should_stop_decoding( + selected: list[int], cached: dict[int, dict], requested: int, + decode_all_candidates: bool, +) -> bool: + """Stop early only when full candidate decoding was not requested.""" + + return ( + not decode_all_candidates + and len(first_valid_indices(selected, cached, requested)) == requested + ) + + +def cache_completion_status( + requested: int, selected: list[int], cached: dict[int, dict], processed: int, + accept_all_valid: bool, +) -> str: + if accept_all_valid: + return "complete" if processed == len(selected) else "incomplete_source_scan" + return "complete" if len(first_valid_indices(selected, cached, requested)) == requested else "insufficient_valid_clips" + + +def recording_local_batches( + decode_order: list[int], rows: list[dict], batch_size: int = 2, +) -> list[list[int]]: + if batch_size < 1: + raise ValueError("prefetch batch size must be positive") + batches: list[list[int]] = [] + start = 0 + while start < len(decode_order): + recording = rows[decode_order[start]]["physical_recording_id"] + end = start + while ( + end < len(decode_order) + and rows[decode_order[end]]["physical_recording_id"] == recording + ): + end += 1 + group = decode_order[start:end] + batches.extend( + group[offset:offset + batch_size] + for offset in range(0, len(group), batch_size) + ) + start = end + return batches + + +def cache_row( + source_row: dict, source_index: int, output: Path, dataset: str, + target_hw: tuple[int, int], + right_geometry_masked_frames: int = 0, +) -> dict: + return { + "dataset_id": dataset, + "subject_id": str(source_row["subject_id"]), + "sequence_id": str(source_row["physical_recording_id"]), + "physical_recording_id": str(source_row["physical_recording_id"]), + "camera_id": str(source_row["camera_id"]), + "stream_id": str(source_row["camera_id"]), + "headset_id": str(source_row.get("serial_id", source_row["subject_id"])), + "source_clip_index": source_index, + "source_group_key": str(source_row["group_key"]), + "resolution_hw": list(target_hw), + "cache_path": str(output.resolve()), + "cache_sha256": sha256(output), + "right_geometry_masked_frames": int(right_geometry_masked_frames), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int, required=True) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument( + "--required-hand-side", choices=("any", "left", "right"), default="any", + help="Optional source-manifest hand-presence filter before balancing.", + ) + parser.add_argument( + "--prefetch-batch-size", type=int, default=0, + help="Optional exact recording-local prefetch batch; 0 keeps the original decoder.", + ) + parser.add_argument( + "--decode-all-candidates", action="store_true", + help="Decode the complete balanced overdraw pool before freezing the valid prefix.", + ) + parser.add_argument( + "--accept-all-valid", action="store_true", + help="For a full source manifest, cache every valid clip and report invalid clips explicitly.", + ) + parser.add_argument("--resume", action="store_true") + parser.add_argument("--torch-threads", type=int, default=0) + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + if min(args.clips, args.max_recordings) <= 0: + parser.error("clip and recording counts must be positive") + if args.torch_threads < 0: + parser.error("--torch-threads cannot be negative") + if args.torch_threads: + torch.set_num_threads(args.torch_threads) + torch.set_num_interop_threads(1) + if args.dataset == "HOI4D": + if args.root is None: + parser.error("HOI4D requires --root") + dataset = HOI4DClipDataset( + args.root, args.source_manifest, args.mano_root, target_hw=target_hw, + ) + else: + dataset = ARCTICClipDataset( + args.source_manifest, args.mano_root, target_hw=target_hw, + ) + eligible = hand_side_source_indices(dataset.rows, args.required_hand_side) + if args.accept_all_valid and args.clips != len(eligible): + parser.error("--accept-all-valid requires --clips to equal all eligible source clips") + eligible_rows = [dataset.rows[index] for index in eligible] + candidate_count = cache_candidate_count(args.clips, len(eligible_rows)) + selected = [ + eligible[index] + for index in balanced_source_indices( + eligible_rows, candidate_count, args.max_recordings, + ) + ] + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced candidates are available") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + # Group source reads to retain decoded sequence/provider state. + decode_order = sorted( + selected, + key=lambda index: ( + dataset.rows[index]["physical_recording_id"], + dataset.rows[index].get("frame_ids", dataset.rows[index].get("frame_ids_1based"))[0], + ), + ) + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", "geometry_convention_compatible", + } + cached: dict[int, dict] = {} + skipped_no_supervision: list[int] = [] + skipped_invalid_source: list[dict[str, str | int]] = [] + started = time.monotonic() + if args.prefetch_batch_size < 0: + parser.error("--prefetch-batch-size cannot be negative") + batches = ( + recording_local_batches(decode_order, dataset.rows, args.prefetch_batch_size) + if args.dataset == "HOI4D" and args.prefetch_batch_size + else [[index] for index in decode_order] + ) + position = 0 + for batch_indices in batches: + missing = [ + index for index in batch_indices + if not (clips_dir / f"clip_{index:07d}.npz").is_file() + ] + if args.dataset == "HOI4D" and args.prefetch_batch_size and missing: + dataset.prefetch_clip_indices(missing) + for source_index in batch_indices: + position += 1 + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise RuntimeError(f"invalid existing cache: {output}") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + right_geometry_masked_frames = int(np.count_nonzero( + archive["translation_valid"][..., 1] + & ~archive["mano_annotation_valid"][..., 1] + )) if args.dataset == "HOI4D" else 0 + else: + try: + sample = dataset[(source_index, 0)] + except InvalidSourceSampleError as error: + if not args.accept_all_valid: + raise + skipped_invalid_source.append({ + "source_clip_index": source_index, + "reason": str(error), + }) + has_supervision = False + else: + has_supervision = bool(sample["translation_valid"].any()) + right_geometry_masked_frames = int(( + sample["translation_valid"][..., 1] + & ~sample["mano_annotation_valid"][..., 1] + ).sum()) if args.dataset == "HOI4D" else 0 + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + if not has_supervision: + if not skipped_invalid_source or skipped_invalid_source[-1]["source_clip_index"] != source_index: + skipped_no_supervision.append(source_index) + else: + cached[source_index] = cache_row( + dataset.rows[source_index], source_index, output, args.dataset, + target_hw, + right_geometry_masked_frames, + ) + if position % 10 == 0 or position == len(decode_order): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": position, "requested": len(decode_order), + "cached": len(cached), "skipped_no_supervision": len(skipped_no_supervision), + "skipped_invalid_source": len(skipped_invalid_source), + "clips_per_second": position / elapsed, + "eta_seconds": (len(decode_order) - position) / (position / elapsed), + }), flush=True) + if args.dataset == "HOI4D" and args.prefetch_batch_size: + dataset.clear_prefetch() + if should_stop_decoding( + selected, cached, args.clips, + args.decode_all_candidates or args.accept_all_valid, + ): + break + ordered_cached = first_valid_indices(selected, cached, args.clips) + manifest = args.output_dir / "cache_manifest.jsonl" + manifest_temporary = manifest.with_suffix(".tmp") + manifest_temporary.write_text( + "".join(json.dumps(cached[index], sort_keys=True) + "\n" for index in ordered_cached), + encoding="utf-8", + ) + manifest_temporary.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": cache_completion_status( + args.clips, selected, cached, position, args.accept_all_valid, + ), + "dataset": args.dataset, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "requested_clips": args.clips, "candidate_clips_processed": position, + "resolution_hw": list(target_hw), + "cached_clips": len(ordered_cached), "valid_candidate_files": len(cached), + "recordings": len({cached[index]["source_group_key"] for index in ordered_cached}), + "required_hand_side": args.required_hand_side, + "eligible_source_clips": len(eligible), + "accept_all_valid": bool(args.accept_all_valid), + "all_eligible_processed": position == len(selected), + "cached_valid_clips": len(ordered_cached), + "decode_all_candidates": bool(args.decode_all_candidates), + "skipped_no_supervision": skipped_no_supervision, + "skipped_invalid_source": skipped_invalid_source, + "right_geometry_masked_frames": sum( + cached[index]["right_geometry_masked_frames"] for index in ordered_cached + ), + "right_geometry_masked_source_indices": [ + index for index in ordered_cached + if cached[index]["right_geometry_masked_frames"] + ], + "wall_seconds": elapsed, "clips_per_second": position / elapsed, + "bytes": sum(Path(cached[index]["cache_path"]).stat().st_size for index in ordered_cached), + "resume_invocation": bool(args.resume), "official_test_used": False, + "torch_threads": args.torch_threads or torch.get_num_threads(), + } + (args.output_dir / "cache_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/capture_environment.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/capture_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3d38bbd2ddfca1e23fdbc2eb2518240f885a2f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/capture_environment.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Capture phase-2 environment without exposing unrelated environment variables.""" + +from __future__ import annotations + +import json +import platform +import subprocess +from pathlib import Path + +import cv2 +import numpy as np +import torch + + +def command(args: list[str]) -> str: + return subprocess.run(args, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.strip() + + +def main() -> None: + output = Path("artifacts/phase2/environment") + output.mkdir(parents=True, exist_ok=True) + report = { + "captured_at": command(["date", "--iso-8601=seconds"]), + "platform": platform.platform(), "python": platform.python_version(), + "torch": torch.__version__, "torch_cuda": torch.version.cuda, "cuda_available": torch.cuda.is_available(), + "cuda_devices": [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())], + "bf16_supported": [torch.cuda.is_bf16_supported(index) for index in range(torch.cuda.device_count())], + "numpy": np.__version__, "opencv": cv2.__version__, + "nvidia_smi": command(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free,driver_version", "--format=csv,noheader"]), + "git_status": command(["git", "status", "--short"]), + "git_head": command(["git", "rev-parse", "HEAD"]), + "dinov3_commit": command(["git", "-C", "third_party/dinov3", "rev-parse", "HEAD"]), + "manopth_commit": command(["git", "-C", "third_party/manopth", "rev-parse", "HEAD"]), + "h2oplayer_commit": command(["git", "-C", "third_party/h2oplayer", "rev-parse", "HEAD"]), + } + (output / "environment.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/capture_phase4_provenance.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/capture_phase4_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..805db38ce73a5086e3677718bcaf2d864e418d7f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/capture_phase4_provenance.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Capture the Phase 4 entry state without reading the official test split.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import subprocess +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import cv2 +import numpy as np +import torch + + +def command(args: list[str], cwd: Path) -> str: + result = subprocess.run( + args, + cwd=cwd, + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + return result.stdout.strip() + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/freeze/entry")) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + output = (root / args.output_dir).resolve() if not args.output_dir.is_absolute() else args.output_dir + output.mkdir(parents=True, exist_ok=True) + + checkpoint_index = json.loads( + (root / "artifacts/phase3/reports/long_tail_checkpoints.json").read_text(encoding="utf-8") + ) + checkpoints = [] + for run in checkpoint_index["runs"].values(): + role = run["roles"]["tail_best_absolute"] + path = Path(role["path"]) + checkpoints.append({ + "seed": int(run["seed"]), + "step": int(role["step"]), + "path": str(path), + "registered_sha256": role["sha256"], + "observed_sha256": sha256(path), + "bytes": path.stat().st_size, + "evaluation": role["evaluation"], + }) + + protected_inputs = { + "official_train_manifest": root / "artifacts/phase2/data_audit/manifests/official_train.jsonl", + "official_val_manifest": root / "artifacts/phase2/data_audit/manifests/official_val.jsonl", + "fixed_validation_subset": root / "artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json", + } + report = { + "captured_at": datetime.now(ZoneInfo("Asia/Hong_Kong")).isoformat(), + "project_root": str(root), + "git_head": command(["git", "rev-parse", "HEAD"], root), + "git_status": command(["git", "status", "--short", "--branch"], root), + "git_diff_stat": command(["git", "diff", "--stat"], root), + "git_diff_sha256": hashlib.sha256(command(["git", "diff", "--binary"], root).encode()).hexdigest(), + "platform": platform.platform(), + "python": platform.python_version(), + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "cuda_devices": [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())], + "numpy": np.__version__, + "opencv": cv2.__version__, + "nvidia_smi": command([ + "nvidia-smi", + "--query-gpu=index,name,uuid,memory.total,memory.used,memory.free,utilization.gpu", + "--format=csv,noheader", + ], root), + "submodules": command(["git", "submodule", "status"], root), + "checkpoints": checkpoints, + "protected_inputs": { + name: {"path": str(path.resolve()), "sha256": sha256(path), "bytes": path.stat().st_size} + for name, path in protected_inputs.items() + }, + "official_test_used": False, + "official_test_note": "The official test manifest and files are intentionally not read or hashed.", + } + (output / "entry_provenance.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + (output / "git_status.txt").write_text(report["git_status"] + "\n", encoding="utf-8") + (output / "git_diff.patch").write_text(command(["git", "diff", "--binary"], root) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "captured", + "output": str(output), + "git_head": report["git_head"], + "checkpoint_hashes_match": all( + item["registered_sha256"] == item["observed_sha256"] for item in checkpoints + ), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/capture_phase5_provenance.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/capture_phase5_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..bb59cafe4facd03ad4fb3b51fc4bb96eea8d77da --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/capture_phase5_provenance.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Capture Phase 5 entry provenance without touching the official test split.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import subprocess +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import torch + + +def command(args: list[str], cwd: Path) -> str: + return subprocess.run( + args, cwd=cwd, check=False, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + ).stdout.strip() + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase5/freeze/entry")) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + output = args.output_dir if args.output_dir.is_absolute() else root / args.output_dir + output.mkdir(parents=True, exist_ok=True) + + baselines = [ + { + "name": f"p0_512_seed{seed}", + "checkpoint": root / f"artifacts/phase3/depth_dropout_runs_commit7583772/depth_dropout00_geometry_m3_l1_t1_s{seed}/best.pt", + "evaluation": root / f"artifacts/phase3/depth_dropout_full_validation/depth_dropout00_geometry_m3_l1_t1_s{seed}/best_absolute/evaluation.json", + } + for seed in (20260716, 20260717, 20260718) + ] + [{ + "name": "unified_640_tail_seed20260718", + "checkpoint": Path("/SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/best.pt"), + "evaluation": root / "artifacts/phase3/long_tail_full_validation/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/tail_best_absolute/evaluation.json", + }] + baseline_records = [] + for baseline in baselines: + evaluation = json.loads(baseline["evaluation"].read_text(encoding="utf-8")) + checkpoint = baseline["checkpoint"] + observed_hash = sha256(checkpoint) + baseline_records.append({ + "name": baseline["name"], + "checkpoint": str(checkpoint.resolve()), + "registered_sha256": evaluation["checkpoint"]["sha256"], + "observed_sha256": observed_hash, + "hash_matches": observed_hash == evaluation["checkpoint"]["sha256"], + "step": evaluation["checkpoint"]["step"], + "evaluation": str(baseline["evaluation"].resolve()), + "absolute_mpjpe_mm": evaluation["metrics"]["absolute_mpjpe_mm"]["mean"], + "official_test_used": evaluation["official_test_used"], + }) + + protected = { + "official_train": root / "artifacts/phase2/data_audit/manifests/official_train.jsonl", + "official_validation": root / "artifacts/phase2/data_audit/manifests/official_val.jsonl", + "fixed_validation_subset_640": root / "artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json", + "phase5_oof_folds": root / "artifacts/phase5/splits/subject_oof_v1/folds.json", + } + report = { + "captured_at": datetime.now(ZoneInfo("Asia/Hong_Kong")).isoformat(), + "status": "captured", + "project_root": str(root), + "git_head": command(["git", "rev-parse", "HEAD"], root), + "git_status": command(["git", "status", "--short", "--branch"], root), + "git_diff_sha256": hashlib.sha256( + command(["git", "diff", "--binary"], root).encode() + ).hexdigest(), + "platform": platform.platform(), + "python": platform.python_version(), + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "nvidia_smi": command([ + "nvidia-smi", "--query-gpu=index,name,uuid,memory.total,memory.used,memory.free,utilization.gpu", + "--format=csv,noheader", + ], root), + "disk": command(["df", "-h", str(root), "/SSD2", "/SSD3"], root), + "active_compute_processes": command([ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid,process_name,used_memory", + "--format=csv,noheader", + ], root), + "baselines": baseline_records, + "protected_inputs": { + name: {"path": str(path.resolve()), "sha256": sha256(path), "bytes": path.stat().st_size} + for name, path in protected.items() + }, + "official_test_used": False, + "official_test_note": "Official test manifests, files, predictions, and hashes were intentionally not accessed.", + } + (output / "entry_provenance.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + (output / "git_status.txt").write_text(report["git_status"] + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], + "output": str(output), + "baseline_hashes_match": all(row["hash_matches"] for row in baseline_records), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase3_resume.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase3_resume.py new file mode 100644 index 0000000000000000000000000000000000000000..82924e82bed187f735fe17acf6647623b4b1e206 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase3_resume.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Compare uninterrupted and resumed Phase 3 final states exactly.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +from pathlib import Path + + +def worker(reference_path: Path, resumed_path: Path) -> None: + import numpy as np + import torch + + reference = torch.load(reference_path, map_location="cpu", weights_only=False) + resumed = torch.load(resumed_path, map_location="cpu", weights_only=False) + + def equal(left, right) -> bool: + if torch.is_tensor(left) and torch.is_tensor(right): + return left.dtype == right.dtype and left.shape == right.shape and torch.equal(left, right) + if isinstance(left, np.ndarray) and isinstance(right, np.ndarray): + return left.dtype == right.dtype and left.shape == right.shape and np.array_equal(left, right) + if isinstance(left, dict) and isinstance(right, dict): + return left.keys() == right.keys() and all(equal(left[key], right[key]) for key in left) + if isinstance(left, (tuple, list)) and isinstance(right, type(left)): + return len(left) == len(right) and all(equal(a, b) for a, b in zip(left, right)) + return left == right + + result = { + "reference_step": int(reference["step"]), + "resumed_step": int(resumed["step"]), + "model_exact": equal(reference["model"], resumed["model"]), + "optimizer_exact": equal(reference["optimizer"], resumed["optimizer"]), + "python_rng_exact": equal(reference["python_rng"], resumed["python_rng"]), + "numpy_rng_exact": equal(reference["numpy_rng"], resumed["numpy_rng"]), + "torch_rng_exact": equal(reference["torch_rng"], resumed["torch_rng"]), + "cuda_rng_exact": equal(reference["cuda_rng"], resumed["cuda_rng"]), + } + print(json.dumps(result)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("reference_root", type=Path, nargs="?") + parser.add_argument("resumed_root", type=Path, nargs="?") + parser.add_argument("--expected-runs", type=int) + parser.add_argument("--checkpoint-name", default="step_0100000_final.pt") + parser.add_argument("--expected-step", type=int, default=100_000) + parser.add_argument("--worker", nargs=2, type=Path) + args = parser.parse_args() + if args.worker: + worker(*args.worker) + return + if args.reference_root is None or args.resumed_root is None: + parser.error("reference_root and resumed_root are required") + + # The resumed root defines the audited subset while a larger reference matrix + # may still be running. + run_names = sorted( + path.name for path in args.resumed_root.iterdir() + if path.is_dir() and not path.name.startswith("_") + ) + if args.expected_runs is not None and len(run_names) != args.expected_runs: + raise ValueError(f"expected {args.expected_runs} runs, found {len(run_names)}") + records = [] + for run_name in run_names: + reference_path = args.reference_root / run_name / args.checkpoint_name + resumed_path = args.resumed_root / run_name / args.checkpoint_name + if not reference_path.is_file() or not resumed_path.is_file(): + raise FileNotFoundError(f"missing final checkpoint for {run_name}") + process = subprocess.run( + [ + sys.executable, str(Path(__file__).resolve()), "--worker", + str(reference_path), str(resumed_path), + ], + check=True, capture_output=True, text=True, + ) + records.append({"run": run_name, **json.loads(process.stdout)}) + + passed = bool(records) and all( + row["reference_step"] == row["resumed_step"] == args.expected_step + and row["model_exact"] and row["optimizer_exact"] + and row["python_rng_exact"] and row["numpy_rng_exact"] + and row["torch_rng_exact"] and row["cuda_rng_exact"] + for row in records + ) + payload = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "reference_root": str(args.reference_root), + "resumed_root": str(args.resumed_root), + "runs": records, + } + output = args.resumed_root / "exact_resume_audit.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": payload["status"], "runs": len(records), "output": str(output)}, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase5_alignment_calibrators.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase5_alignment_calibrators.py new file mode 100644 index 0000000000000000000000000000000000000000..5921cddec59bf99669817ea5ddbe8fee1c4c6335 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase5_alignment_calibrators.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Compare shared multi-checkpoint and per-seed OOF calibrators.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + + +CONDITIONS = ( + "coarse", + "robust_alignment_unscaled", + "calibrated_always", + "calibrated_confidence", +) +METRICS = ("absolute_mpjpe_mm", "z_mae_mm", "z_p95_mm", "z_cvar95_mm") + + +def load_report(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "fitted" + or report.get("result_role") != "train_oof_cross_validated_threshold_selection" + or report.get("official_validation_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"comparison requires a train-OOF-only calibration report: {path}") + return report + + +def compare_reports( + shared: dict[str, Any], per_seed: list[dict[str, Any]], +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + if int(shared.get("expected_banks_per_fold", -1)) <= 1: + raise ValueError("shared report is not a multi-checkpoint calibration") + expected_seeds = {int(seed) for seed in shared.get("coarse_seeds", [])} + specific = {} + for report in per_seed: + seeds = [int(seed) for seed in report.get("coarse_seeds", [])] + if int(report.get("expected_banks_per_fold", -1)) != 1 or len(seeds) != 1: + raise ValueError("each per-seed report must contain one seed and one bank per fold") + if seeds[0] in specific: + raise ValueError(f"duplicate per-seed report: {seeds[0]}") + specific[seeds[0]] = report + if set(specific) != expected_seeds: + raise ValueError( + f"per-seed reports do not match shared seeds: {sorted(specific)} vs {sorted(expected_seeds)}" + ) + + rows = [] + for seed in sorted(expected_seeds): + shared_metrics = shared["metrics_by_seed"][str(seed)] + specific_metrics = specific[seed]["metrics"] + for metric in METRICS: + shared_coarse = float(shared_metrics["coarse"][metric]) + specific_coarse = float(specific_metrics["coarse"][metric]) + if abs(shared_coarse - specific_coarse) > 1e-9: + raise ValueError(f"seed {seed} coarse {metric} mismatch") + for condition in CONDITIONS: + row: dict[str, Any] = {"seed": seed, "condition": condition} + for metric in METRICS: + shared_value = float(shared_metrics[condition][metric]) + specific_value = float(specific_metrics[condition][metric]) + row[f"shared_{metric}"] = shared_value + row[f"per_seed_{metric}"] = specific_value + row[f"shared_minus_per_seed_{metric}"] = shared_value - specific_value + rows.append(row) + + calibrated = [row for row in rows if row["condition"] == "calibrated_always"] + summary = { + "status": "compared", + "experiment_class": "train_oof_shared_vs_per_seed_calibrator_ablation", + "seeds": sorted(expected_seeds), + "primary_condition": "calibrated_always", + "shared_absolute_better_seed_count": sum( + row["shared_minus_per_seed_absolute_mpjpe_mm"] < 0 for row in calibrated + ), + "mean_shared_minus_per_seed_absolute_mpjpe_mm": sum( + row["shared_minus_per_seed_absolute_mpjpe_mm"] for row in calibrated + ) / len(calibrated), + "mean_shared_minus_per_seed_z_p95_mm": sum( + row["shared_minus_per_seed_z_p95_mm"] for row in calibrated + ) / len(calibrated), + "official_validation_used": False, + "official_test_used": False, + } + return rows, summary + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--shared", type=Path, required=True) + parser.add_argument("--per-seed", type=Path, action="append", required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("comparison refuses to overwrite outputs") + shared = load_report(args.shared) + per_seed = [load_report(path) for path in args.per_seed] + rows, summary = compare_reports(shared, per_seed) + report = { + **summary, + "shared_report": str(args.shared.resolve()), + "per_seed_reports": [str(path.resolve()) for path in args.per_seed], + "rows": rows, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase6_paired_evaluations.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase6_paired_evaluations.py new file mode 100644 index 0000000000000000000000000000000000000000..6720f4f081aba86cf6a2f3152e427076a0f95dad --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase6_paired_evaluations.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Pair two frozen Phase 6 evaluation outputs by take/frame/side.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + + +METRIC_ALIASES = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm",), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm",), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm",), + "root_relative_mpvpe_mm": ("root_relative_mpvpe_mm",), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm",), + "translation_x_mae_mm": ("translation_x_mae_mm",), + "translation_y_mae_mm": ("translation_y_mae_mm",), + "translation_z_mae_mm": ("translation_z_mae_mm",), + "direct_2d_error_px": ("direct_2d_error_px",), + "projected_mano_2d_px": ("projected_mano_2d_px", "mano_projected_2d_error_px"), + "direct_mano_consistency_px": ( + "direct_mano_consistency_px", "direct_mano_2d_consistency_px", + ), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_rows(path: Path, condition: str | None) -> dict[tuple[str, int, str], dict[str, float]]: + output = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + if condition is not None and row.get("condition") != condition: + continue + if row.get("annotation_valid") not in (None, "1", "True", "true"): + continue + identity = (row["take"], int(row["frame_id"]), row["side"]) + if identity in output: + raise ValueError(f"duplicate paired identity: {identity}") + metrics = {} + for canonical, aliases in METRIC_ALIASES.items(): + source = next((alias for alias in aliases if row.get(alias, "") != ""), None) + if source is not None: + metrics[canonical] = float(row[source]) + output[identity] = metrics + if not output: + raise ValueError(f"no rows selected from {path}") + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--baseline-dir", type=Path, required=True) + parser.add_argument("--candidate-dir", type=Path, required=True) + parser.add_argument("--baseline-condition") + parser.add_argument("--candidate-condition") + parser.add_argument("--baseline-label", required=True) + parser.add_argument("--candidate-label", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + baseline_path = args.baseline_dir / "per_hand_frame_metrics.csv" + candidate_path = args.candidate_dir / "per_hand_frame_metrics.csv" + baseline = load_rows(baseline_path, args.baseline_condition) + candidate = load_rows(candidate_path, args.candidate_condition) + if set(baseline) != set(candidate): + raise ValueError("paired evaluations have different take/frame/side identities") + common_metrics = sorted( + set().union(*(set(row) for row in baseline.values())) + & set().union(*(set(row) for row in candidate.values())) + ) + if not common_metrics: + raise ValueError("paired evaluations have no common metrics") + frame_rows = [] + for identity in sorted(baseline): + take, frame_id, side = identity + row: dict[str, object] = {"take": take, "frame_id": frame_id, "side": side} + for metric in common_metrics: + if metric not in baseline[identity] or metric not in candidate[identity]: + continue + delta = candidate[identity][metric] - baseline[identity][metric] + row[f"baseline_{metric}"] = baseline[identity][metric] + row[f"candidate_{metric}"] = candidate[identity][metric] + row[f"delta_{metric}"] = delta + frame_rows.append(row) + rng = np.random.default_rng(20260717) + paired_rows = [] + for metric in common_metrics: + selected = [row for row in frame_rows if f"delta_{metric}" in row] + frame_delta = np.asarray([float(row[f"delta_{metric}"]) for row in selected]) + by_take: dict[str, list[float]] = defaultdict(list) + for row in selected: + by_take[str(row["take"])].append(float(row[f"delta_{metric}"])) + takes = sorted(by_take) + take_delta = np.asarray([ + np.mean(by_take[take]) for take in takes + ]) + indices = rng.integers(0, len(take_delta), size=(10_000, len(take_delta))) + bootstrap = take_delta[indices].mean(axis=1) + paired_rows.append({ + "candidate": args.candidate_label, "baseline": args.baseline_label, + "metric": metric, "hands": len(frame_delta), "takes": len(takes), + "frame_weighted_delta": float(frame_delta.mean()), + "take_equal_delta": float(take_delta.mean()), + "ci95_low": float(np.percentile(bootstrap, 2.5)), + "ci95_high": float(np.percentile(bootstrap, 97.5)), + "largest_sample_gain": float(frame_delta.min()), + "largest_sample_harm": float(frame_delta.max()), + "largest_take_gain": float(take_delta.min()), + "largest_take_harm": float(take_delta.max()), + }) + args.output_dir.mkdir(parents=True, exist_ok=True) + for filename, rows in ( + ("per_hand_frame_deltas.csv", frame_rows), + ("paired_take_bootstrap_ci.csv", paired_rows), + ): + with (args.output_dir / filename).open("x", newline="", encoding="utf-8") as handle: + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "paired", + "official_test_used": False, + "baseline": { + "label": args.baseline_label, "directory": str(args.baseline_dir.resolve()), + "condition": args.baseline_condition, "rows_sha256": sha256(baseline_path), + }, + "candidate": { + "label": args.candidate_label, "directory": str(args.candidate_dir.resolve()), + "condition": args.candidate_condition, "rows_sha256": sha256(candidate_path), + }, + "paired_identities": len(frame_rows), + "physical_takes": len({str(row["take"]) for row in frame_rows}), + "metrics": paired_rows, + } + (args.output_dir / "comparison.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_adaptation_forgetting.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_adaptation_forgetting.py new file mode 100644 index 0000000000000000000000000000000000000000..e1cb408e3922668217c70a3eddaf0c68cfd7748b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_adaptation_forgetting.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Paired external forgetting comparison for an H2O-adapted checkpoint.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.compare_phase8_specialist_curve import ( + MEAN_METRICS, + _load_rows, + _paired_bootstrap, +) + + +def _load_reference(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError("reference is not a strict external-heldout result") + return report + + +def _load_candidate(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_adaptation_external_heldout" + or report.get("evaluation_role") != "adaptation_external_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError("candidate is not an adaptation forgetting result") + return report + + +def compare( + reference_path: Path, + candidate_path: Path, + *, + seed: int = 20260717, + resamples: int = 2000, +) -> dict[str, Any]: + reference = _load_reference(reference_path) + candidate = _load_candidate(candidate_path) + for field in ("input_mode", "clips", "frames"): + if reference.get(field) != candidate.get(field): + raise ValueError(f"evaluation {field} differs") + if reference["cache_manifest"] != candidate["cache_manifest"]: + raise ValueError("evaluation cache manifest differs") + reference_rows = _load_rows(reference_path, reference) + candidate_rows = _load_rows(candidate_path, candidate) + if set(reference_rows) != set(candidate_rows): + raise ValueError("per-hand frame identities differ") + metrics: dict[str, Any] = {} + for metric in MEAN_METRICS: + metrics[metric] = { + "reference_global_mean": reference["metrics"][metric]["mean"], + "candidate_global_mean": candidate["metrics"][metric]["mean"], + **_paired_bootstrap( + reference_rows, candidate_rows, metric, "mean", seed, resamples, + ), + } + metrics["translation_z_recording_p95_mm"] = { + "reference_global_p95": reference["metrics"]["translation_z_mae_mm"]["p95"], + "candidate_global_p95": candidate["metrics"]["translation_z_mae_mm"]["p95"], + **_paired_bootstrap( + reference_rows, candidate_rows, "translation_z_mae_mm", "p95", + seed, resamples, + ), + } + return { + "schema_version": "phase8_adaptation_forgetting_comparison_v1", + "status": "complete", + "delta_definition": "adapted_candidate_minus_external_reference; positive is forgetting", + "reference": { + "evaluation": str(reference_path.resolve()), + "checkpoint": reference["checkpoint"], + }, + "candidate": { + "evaluation": str(candidate_path.resolve()), + "checkpoint": candidate["checkpoint"], + }, + "input_mode": reference["input_mode"], + "cache_manifest": reference["cache_manifest"], + "per_hand_identity_count": len(reference_rows), + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "metrics": metrics, + "selection_use": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-evaluation", type=Path, required=True) + parser.add_argument("--candidate-evaluation", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = compare( + args.reference_evaluation, args.candidate_evaluation, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_h2o_trainheldout.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_h2o_trainheldout.py new file mode 100644 index 0000000000000000000000000000000000000000..f823fbc57892f9bf3c1192807b564b7ad628c97a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_h2o_trainheldout.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Compare H2O train-heldout baselines separately by deployable input mode.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.select_phase7_h2o_adaptation import ( + METRIC_SPECS, + paired_recording_bootstrap, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def checked_artifact(report: dict[str, Any], name: str) -> Path: + record = report[name] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"{name} is missing or SHA256 differs: {path}") + return path + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("selection_split") != "h2o_train_group_heldout_only" + or manifest.get("h2o_official_validation_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("comparison manifest violates the train-heldout boundary") + by_mode: dict[str, list[dict[str, Any]]] = {} + cache_hashes: set[str] = set() + seen: set[tuple[str, str]] = set() + valid_status_roles = { + ("evaluated_h2o_train_group_heldout", "h2o_train_group_heldout"), + ("evaluated_h2o_train_group_heldout_control", "h2o_train_group_heldout_control"), + } + for item in manifest.get("candidates", []): + condition = str(item["condition"]) + report_path = Path(item["evaluation"]) + report = json.loads(report_path.read_text(encoding="utf-8")) + status_role = (report.get("status"), report.get("evaluation_role")) + mode = str(report.get("input_mode")) + if ( + status_role not in valid_status_roles + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or Path(report["cache_manifest"]["path"]).name != "train_group_heldout.jsonl" + ): + raise ValueError(f"invalid H2O train-heldout result: {report_path}") + if (condition, mode) in seen: + raise ValueError(f"duplicate condition/mode: {condition}/{mode}") + seen.add((condition, mode)) + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + cache = checked_artifact(report, "cache_manifest") + rows = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + cache_hashes.add(report["cache_manifest"]["sha256"]) + metrics = { + name: float(report["metrics"][row_metric][statistic]) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + by_mode.setdefault(mode, []).append({ + "condition": condition, "evaluation": str(report_path.resolve()), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config.resolve()), "cache_manifest": str(cache.resolve()), + "per_hand_rows": str(rows.resolve()), "metrics": metrics, + }) + if len(cache_hashes) != 1: + raise ValueError("candidates use different train-heldout manifests") + if not by_mode: + raise ValueError("comparison manifest has no candidates") + modes: dict[str, Any] = {} + for mode, candidates in sorted(by_mode.items()): + if len(candidates) < 2: + raise ValueError(f"input mode requires at least two candidates: {mode}") + order = sorted(candidates, key=lambda row: ( + row["metrics"]["absolute_mpjpe_mm"], + row["metrics"]["root_relative_mpjpe_mm"], + row["condition"], + )) + winner = order[0] + paired = {} + for candidate in order[1:]: + paired[candidate["condition"]] = { + name: paired_recording_bootstrap( + Path(winner["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + modes[mode] = { + "winner": winner["condition"], + "order": [candidate["condition"] for candidate in order], + "candidates": order, + "paired_recording_bootstrap_vs_winner": paired, + } + return { + "status": "compared_h2o_train_group_heldout_by_input_mode", + "selection_split": "h2o_train_group_heldout_only", + "selection_rule": "lowest Absolute MPJPE separately within each input mode", + "modes": modes, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_h2o_zero_shot.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c3efcc36b714f01f46834472c98a2b59014f8f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_h2o_zero_shot.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Compare already-frozen external checkpoints on H2O validation diagnostically.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import Any + +from scripts.compare_phase8_h2o_trainheldout import checked_artifact +from scripts.select_phase7_h2o_adaptation import METRIC_SPECS, paired_recording_bootstrap + + +BOUNDARY = "frozen_external_checkpoints_h2o_official_validation_diagnostic_only" + + +def _metrics(report: dict[str, Any]) -> dict[str, float]: + values = { + name: float(report["metrics"][row_metric][statistic]) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + if not all(math.isfinite(value) for value in values.values()): + raise ValueError("zero-shot report contains non-finite metrics") + return values + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("comparison_boundary") != BOUNDARY + or manifest.get("checkpoint_selection_frozen_before_h2o") is not True + or manifest.get("h2o_official_validation_used_for_external_selection") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("comparison manifest violates the frozen zero-shot boundary") + reference_condition = str(manifest.get("reference_condition", "")) + by_mode: dict[str, list[dict[str, Any]]] = {} + validation_hashes: set[str] = set() + seen: set[tuple[str, str]] = set() + for item in manifest.get("candidates", []): + condition = str(item["condition"]) + path = Path(item["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + mode = str(report.get("input_mode")) + if ( + report.get("status") != "evaluated_strict_h2o_zero_shot" + or report.get("evaluation_role") != "strict_external_zero_shot" + or report.get("h2o_training_data_used") is not False + or report.get("h2o_official_validation_used") is not True + or report.get("h2o_official_validation_used_for_external_selection") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid frozen H2O zero-shot result: {path}") + if (condition, mode) in seen: + raise ValueError(f"duplicate condition/mode: {condition}/{mode}") + seen.add((condition, mode)) + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + rows = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + validation = checked_artifact(report, "manifest") + validation_hashes.add(report["manifest"]["sha256"]) + by_mode.setdefault(mode, []).append({ + "condition": condition, + "evaluation": str(path.resolve()), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config), + "validation_manifest": str(validation), + "per_hand_rows": str(rows), + "metrics": _metrics(report), + }) + if len(validation_hashes) != 1 or not by_mode: + raise ValueError("zero-shot candidates must use one frozen validation manifest") + modes: dict[str, Any] = {} + for mode, candidates in sorted(by_mode.items()): + references = [row for row in candidates if row["condition"] == reference_condition] + if len(references) != 1 or len(candidates) < 2: + raise ValueError(f"mode lacks one reference and at least one candidate: {mode}") + reference = references[0] + comparisons = {} + for candidate in candidates: + if candidate is reference: + continue + comparisons[candidate["condition"]] = { + name: paired_recording_bootstrap( + Path(reference["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + modes[mode] = { + "reference": reference, + "candidates": [row for row in candidates if row is not reference], + "paired_candidate_minus_reference": comparisons, + } + return { + "status": "compared_frozen_h2o_zero_shot_diagnostic_only", + "comparison_boundary": BOUNDARY, + "selection_performed": False, + "reference_condition": reference_condition, + "modes": modes, + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_specialist_curve.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_specialist_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..92a78c396b10552bb60b3407b9e9686f7859ad84 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_specialist_curve.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Compare two frozen specialist checkpoints on identical external rows.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +MEAN_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", +) +IDENTITY_FIELDS = ( + "dataset", "physical_recording_id", "camera_id", "frame_id", "side", +) + + +def _load_report(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError(f"evaluation violates external curve contract: {path}") + return report + + +def _load_rows(report_path: Path, report: dict[str, Any]) -> dict[tuple[str, ...], dict[str, str]]: + specification = report["per_hand_rows"] + row_path = Path( + specification["path"] if isinstance(specification, dict) else specification, + ) + if not row_path.is_absolute(): + row_path = report_path.parent / row_path + if isinstance(specification, dict): + digest = hashlib.sha256(row_path.read_bytes()).hexdigest() + if digest != specification.get("sha256"): + raise ValueError(f"per-hand row SHA256 differs: {row_path}") + with row_path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + indexed: dict[tuple[str, ...], dict[str, str]] = {} + for row in rows: + identity = tuple(str(row[field]) for field in IDENTITY_FIELDS) + if identity in indexed: + raise ValueError(f"duplicate per-hand identity: {identity}") + indexed[identity] = row + if not indexed: + raise ValueError(f"evaluation has no per-hand rows: {row_path}") + return indexed + + +def _recording_statistic( + rows: dict[tuple[str, ...], dict[str, str]], metric: str, statistic: str, +) -> dict[tuple[str, str], float]: + grouped: dict[tuple[str, str], list[float]] = {} + for identity, row in rows.items(): + value = float(row[metric]) + if math.isfinite(value): + grouped.setdefault((identity[0], identity[1]), []).append(value) + if statistic == "mean": + reduce = np.mean + elif statistic == "p95": + reduce = lambda values: np.quantile(values, 0.95) + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + return {key: float(reduce(values)) for key, values in grouped.items()} + + +def _paired_bootstrap( + reference: dict[tuple[str, str], dict[str, str]], + candidate: dict[tuple[str, str], dict[str, str]], + metric: str, + statistic: str, + seed: int, + resamples: int, +) -> dict[str, Any]: + reference_values = _recording_statistic(reference, metric, statistic) + candidate_values = _recording_statistic(candidate, metric, statistic) + if set(reference_values) != set(candidate_values): + raise ValueError(f"finite recording coverage differs for {metric}/{statistic}") + keys = sorted(reference_values) + delta = np.asarray( + [candidate_values[key] - reference_values[key] for key in keys], + dtype=np.float64, + ) + rng = np.random.default_rng(seed) + sampled = delta[ + rng.integers(0, len(delta), size=(resamples, len(delta))) + ].mean(axis=1) + return { + "recording_statistic": statistic, + "recording_count": len(keys), + "mean_delta": float(delta.mean()), + "ci95_low": float(np.percentile(sampled, 2.5)), + "ci95_high": float(np.percentile(sampled, 97.5)), + } + + +def compare( + reference_path: Path, + candidate_path: Path, + *, + seed: int = 20260717, + resamples: int = 2000, +) -> dict[str, Any]: + reference_report = _load_report(reference_path) + candidate_report = _load_report(candidate_path) + for field in ("input_mode", "clips", "frames"): + if reference_report.get(field) != candidate_report.get(field): + raise ValueError(f"evaluation {field} differs") + if reference_report["cache_manifest"] != candidate_report["cache_manifest"]: + raise ValueError("evaluation cache manifest differs") + reference_rows = _load_rows(reference_path, reference_report) + candidate_rows = _load_rows(candidate_path, candidate_report) + if set(reference_rows) != set(candidate_rows): + raise ValueError("per-hand frame identities differ") + metrics: dict[str, Any] = {} + for metric in MEAN_METRICS: + reference_summary = reference_report["metrics"].get(metric) or {} + candidate_summary = candidate_report["metrics"].get(metric) or {} + metrics[metric] = { + "reference_global_mean": reference_summary.get("mean"), + "candidate_global_mean": candidate_summary.get("mean"), + **_paired_bootstrap( + reference_rows, candidate_rows, metric, "mean", seed, resamples, + ), + } + z_reference = reference_report["metrics"]["translation_z_mae_mm"] + z_candidate = candidate_report["metrics"]["translation_z_mae_mm"] + metrics["translation_z_recording_p95_mm"] = { + "reference_global_p95": z_reference.get("p95"), + "candidate_global_p95": z_candidate.get("p95"), + **_paired_bootstrap( + reference_rows, candidate_rows, "translation_z_mae_mm", "p95", + seed, resamples, + ), + } + absolute = metrics["absolute_mpjpe_mm"] + return { + "schema_version": "phase8_specialist_curve_comparison_v1", + "status": "complete", + "delta_definition": "candidate_minus_reference; negative favors candidate", + "reference": { + "evaluation": str(reference_path.resolve()), + "checkpoint_step": reference_report["checkpoint_step"], + "checkpoint": reference_report["checkpoint"], + }, + "candidate": { + "evaluation": str(candidate_path.resolve()), + "checkpoint_step": candidate_report["checkpoint_step"], + "checkpoint": candidate_report["checkpoint"], + }, + "input_mode": reference_report["input_mode"], + "cache_manifest": reference_report["cache_manifest"], + "per_hand_identity_count": len(reference_rows), + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "metrics": metrics, + "candidate_absolute_lower": ( + float(absolute["candidate_global_mean"]) + < float(absolute["reference_global_mean"]) + ), + "candidate_absolute_ci_excludes_zero": absolute["ci95_high"] < 0.0, + "h2o_training_data_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-evaluation", type=Path, required=True) + parser.add_argument("--candidate-evaluation", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + args.reference_evaluation, args.candidate_evaluation, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_stage7_left.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_stage7_left.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e522e3d109275545d58a7f4c7402d090b00fce --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/compare_phase8_stage7_left.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Compare matched Stage 7 left-supervision screens on external held-out data.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.select_phase7_h2o_adaptation import paired_recording_bootstrap + + +CONDITIONS = ("L0_sampler_only", "L1_left_root_relative") +DATASETS = ("HOT3D", "HOI4D", "ARCTIC") +METRICS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "source_root_relative_mpjpe_mm": ("source_root_relative_mpjpe_mm", "mean"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def checked(report: dict[str, Any], name: str) -> Path: + record = report[name] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"{name} is missing or SHA256 differs: {path}") + return path + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("evaluation_split") != "external_heldout_only" + or manifest.get("h2o_training_data_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("Stage 7 comparison boundary flags are invalid") + reports: dict[str, dict[str, dict[str, Any]]] = {condition: {} for condition in CONDITIONS} + for item in manifest.get("evaluations", []): + condition, dataset = str(item["condition"]), str(item["dataset"]) + if condition not in reports or dataset not in DATASETS: + raise ValueError(f"unexpected condition/dataset: {condition}/{dataset}") + if dataset in reports[condition]: + raise ValueError(f"duplicate condition/dataset: {condition}/{dataset}") + path = Path(item["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid external evaluation: {path}") + rows = checked(report, "per_hand_rows") + cache = checked(report, "cache_manifest") + checked(report, "checkpoint") + checked(report, "config") + reports[condition][dataset] = { + "path": str(path.resolve()), "report": report, + "rows": rows, "cache": cache, + } + for condition in CONDITIONS: + if set(reports[condition]) != set(DATASETS): + raise ValueError(f"{condition} does not contain all external domains") + datasets: dict[str, Any] = {} + for dataset in DATASETS: + reference = reports[CONDITIONS[0]][dataset] + candidate = reports[CONDITIONS[1]][dataset] + for key in ("sha256",): + if reference["report"]["cache_manifest"][key] != candidate["report"]["cache_manifest"][key]: + raise ValueError(f"{dataset} cache differs between L0 and L1") + if reference["report"]["input_mode"] != candidate["report"]["input_mode"]: + raise ValueError(f"{dataset} input mode differs between L0 and L1") + condition_metrics: dict[str, Any] = {} + for condition, record in ((CONDITIONS[0], reference), (CONDITIONS[1], candidate)): + report_metrics = record["report"]["metrics"] + condition_metrics[condition] = { + metric: ( + None if report_metrics.get(row_metric) is None + else float(report_metrics[row_metric][statistic]) + ) + for metric, (row_metric, statistic) in METRICS.items() + } + paired = { + metric: paired_recording_bootstrap( + reference["rows"], candidate["rows"], row_metric, statistic, + seed, resamples, + ) + for metric, (row_metric, statistic) in METRICS.items() + if condition_metrics[CONDITIONS[0]][metric] is not None + and condition_metrics[CONDITIONS[1]][metric] is not None + } + datasets[dataset] = { + "cache_manifest_sha256": reference["report"]["cache_manifest"]["sha256"], + "input_mode": reference["report"]["input_mode"], + "conditions": condition_metrics, + "paired_L1_minus_L0": paired, + } + macro: dict[str, Any] = {} + for metric in ("absolute_mpjpe_mm", "root_relative_mpjpe_mm"): + values = { + condition: [datasets[dataset]["conditions"][condition][metric] for dataset in DATASETS] + for condition in CONDITIONS + } + macro[metric] = { + **{condition: sum(rows) / len(rows) for condition, rows in values.items()}, + } + macro[metric]["L1_minus_L0"] = ( + macro[metric][CONDITIONS[1]] - macro[metric][CONDITIONS[0]] + ) + left_datasets = ("HOI4D", "ARCTIC") + source_values = { + condition: [ + datasets[dataset]["conditions"][condition]["source_root_relative_mpjpe_mm"] + for dataset in left_datasets + ] + for condition in CONDITIONS + } + if any(value is None for values in source_values.values() for value in values): + raise ValueError("left held-out source-root supervision is missing") + macro["source_root_relative_mpjpe_mm"] = { + condition: sum(values) / len(values) for condition, values in source_values.items() + } + macro["source_root_relative_mpjpe_mm"]["L1_minus_L0"] = ( + macro["source_root_relative_mpjpe_mm"][CONDITIONS[1]] + - macro["source_root_relative_mpjpe_mm"][CONDITIONS[0]] + ) + source_gain = -macro["source_root_relative_mpjpe_mm"]["L1_minus_L0"] + accepted = ( + source_gain >= 0.5 + and macro["absolute_mpjpe_mm"]["L1_minus_L0"] <= 1.0 + and macro["root_relative_mpjpe_mm"]["L1_minus_L0"] <= 1.0 + ) + return { + "schema_version": "phase8_stage7_left_comparison_v1", + "status": "complete", "datasets": datasets, "dataset_macro": macro, + "gate": { + "minimum_source_root_gain_mm": 0.5, + "maximum_absolute_regression_mm": 1.0, + "maximum_root_relative_regression_mm": 1.0, + "accepted": accepted, + }, + "h2o_training_data_used": False, "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/derive_phase9_hot_subset.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/derive_phase9_hot_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..abbd427229e098170eb3c8a45d4aef55ad057922 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/derive_phase9_hot_subset.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Derive a deterministic headset/recording-balanced HOT3D cache subset.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict, deque +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def balanced_subset(rows: list[dict[str, Any]], clips: int) -> list[dict[str, Any]]: + if clips <= 0 or clips > len(rows): + raise ValueError("subset size must be in [1, source rows]") + unique_indices = {int(row["source_clip_index"]) for row in rows} + if len(unique_indices) != len(rows): + raise ValueError("source cache contains duplicate source_clip_index values") + grouped: dict[str, dict[str, deque[dict[str, Any]]]] = defaultdict(dict) + by_recording: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for row in rows: + headset = str(row.get("headset_id", "unknown")) + recording = str(row["physical_recording_id"]) + by_recording[(headset, recording)].append(row) + for (headset, recording), recording_rows in by_recording.items(): + grouped[headset][recording] = deque(sorted( + recording_rows, key=lambda row: int(row["source_clip_index"]), + )) + + headsets = sorted(grouped) + recording_cursor = {headset: 0 for headset in headsets} + recording_ids = { + headset: sorted(grouped[headset]) for headset in headsets + } + selected: list[dict[str, Any]] = [] + while len(selected) < clips: + progress = False + for headset in headsets: + ids = recording_ids[headset] + for _ in range(len(ids)): + cursor = recording_cursor[headset] % len(ids) + recording_cursor[headset] += 1 + queue = grouped[headset][ids[cursor]] + if queue: + selected.append(queue.popleft()) + progress = True + break + if len(selected) == clips: + break + if not progress: + raise RuntimeError("balanced subset exhausted before requested size") + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--source-report", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + report = json.loads(args.source_report.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(args.source_manifest) + ): + parser.error("source cache report does not bind a complete manifest") + rows = load_jsonl(args.source_manifest) + selected = balanced_subset(rows, args.clips) + missing = [row["cache_path"] for row in selected if not Path(row["cache_path"]).is_file()] + if missing: + parser.error(f"selected cache payload is missing: {missing[0]}") + args.output_dir.mkdir(parents=True) + manifest = args.output_dir / "cache_manifest.jsonl" + temporary = manifest.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in selected), + encoding="utf-8", + ) + temporary.replace(manifest) + headset_counts = Counter(str(row.get("headset_id", "unknown")) for row in selected) + stream_counts = Counter(str(row.get("stream_id", "unknown")) for row in selected) + recording_counts = Counter(str(row["physical_recording_id"]) for row in selected) + output = { + "schema_version": "phase9_hot_balanced_subset_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "source_cache_manifest": { + "path": str(args.source_manifest.resolve()), + "sha256": sha256(args.source_manifest), + "rows": len(rows), + }, + "source_cache_report": { + "path": str(args.source_report.resolve()), + "sha256": sha256(args.source_report), + }, + "cache_manifest": { + "path": str(manifest.resolve()), + "sha256": sha256(manifest), + }, + "clips": len(selected), + "unique_source_clip_indices": len({int(row["source_clip_index"]) for row in selected}), + "recordings": len(recording_counts), + "headset_clip_counts": dict(sorted(headset_counts.items())), + "stream_clip_counts": dict(sorted(stream_counts.items())), + "recording_clip_count_min": min(recording_counts.values()), + "recording_clip_count_max": max(recording_counts.values()), + "payload_copy_bytes": 0, + "payloads_referenced_from_parent": True, + "official_test_used": False, + } + report_path = args.output_dir / "cache_report.json" + report_path.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8") + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase3.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase3.py new file mode 100644 index 0000000000000000000000000000000000000000..4acdc8f9c12791353d8d2fd3653421539f757245 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase3.py @@ -0,0 +1,1155 @@ +#!/usr/bin/env python3 +"""Audited Phase 3 validation with MANO meshes, tail metrics, and take CIs.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.phase4 import ( + action_name, + bimanual_asymmetry, + depth_validity_bucket, + find_failure_intervals, + load_action_label, + local_depth_statistics, + summarize_group_metrics, +) +from foundation_hand.evaluation.selection import select_visualization_frames +from foundation_hand.evaluation.visualization import ( + MeshLayer, + draw_skeleton, + project_mesh_layers, + render_mesh_layers, + save_attention_figure, + save_camera_views, +) +from foundation_hand.geometry.camera import project_points, unproject_depth +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +SIDES = ("left", "right") +PREDICTED_COLORS = ((32, 190, 105), (235, 112, 45)) +TARGET_COLORS = ((40, 160, 245), (215, 55, 190)) +FINGERTIP_INDICES = (4, 8, 12, 16, 20) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_clip_indices_manifest( + path: Path, + *, + source_manifest: Path, + data_config: dict[str, object], + dataset_length: int, +) -> tuple[list[int], dict[str, object]]: + record = json.loads(path.read_text(encoding="utf-8")) + contract = record.get("dataset_contract", {}) + resolution = [int(value) for value in data_config["resolution_hw"]] + if record.get("source_manifest_sha256") != sha256(source_manifest): + raise ValueError("clip subset source-manifest hash mismatch") + if int(record.get("source_clip_count", -1)) != dataset_length: + raise ValueError("clip subset source length mismatch") + if contract.get("resolution_hw") != resolution: + raise ValueError("clip subset resolution mismatch") + if int(contract.get("T", -1)) != int(data_config["T"]): + raise ValueError("clip subset temporal length mismatch") + if int(contract.get("stride", -1)) != int(data_config["stride"]): + raise ValueError("clip subset stride mismatch") + indices = [int(index) for index in record.get("clip_indices", [])] + if len(indices) != int(record.get("count", -1)) or len(indices) != len(set(indices)): + raise ValueError("clip subset count/uniqueness mismatch") + if not indices or min(indices) < 0 or max(indices) >= dataset_length: + raise ValueError("clip subset index out of bounds") + return indices, record + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def rgb_from_batch(batch: dict[str, Any], time_index: int) -> np.ndarray: + rgb = batch["rgb"][0, time_index].float().cpu().permute(1, 2, 0).numpy() + return np.clip((rgb * RGB_STD + RGB_MEAN) * 255.0, 0, 255).astype(np.uint8) + + +def hand_size_bucket(size: float | None) -> str | None: + if size is None: + return None + if size < 64: + return "small" + if size < 128: + return "medium" + return "large" + + +def wrist_depth_bucket(depth: float | None) -> str | None: + if depth is None: + return None + if depth < 0.5: + return "near" + if depth < 0.8: + return "middle" + return "far" + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + return + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def temporal_position_bias_report(model: BimanualReconstructionModel) -> dict[str, object]: + layers = [] + for layer_index, layer in enumerate(model.decoder.temporal): + bias = getattr(layer, "relative_position_bias", None) + if bias is None: + continue + values = bias.detach().float().cpu().numpy() + max_distance = int(layer.relative_bias_max_distance) + layers.append({ + "layer": layer_index, + "offsets_key_minus_query": list(range(-max_distance, max_distance + 1)), + "shape": list(values.shape), + "mean": float(values.mean()), + "std": float(values.std()), + "max_abs": float(np.abs(values).max()), + "per_head_bias": values.tolist(), + }) + return { + "mode": model.config.temporal_position_mode, + "sign_convention": "key_time_minus_query_time", + "layers": layers, + } + + +def add_label(image: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image.copy() + box_height = 8 + 18 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], box_height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (6, 17 + 18 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.38, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def attach_gt_geometry( + batch: dict[str, Any], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor]: + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + vertices, joints = model.mano_layer( + axis_angle_to_matrix(pose), + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + return vertices, joints + + +def run_model( + model: BimanualReconstructionModel, + batch: dict[str, Any], + dtype: torch.dtype, +) -> dict[str, Any]: + with torch.autocast("cuda", dtype=dtype): + return model(batch) + + +def save_depth_geometry( + output: Path, batch: dict[str, Any], time_index: int, title: str, +) -> None: + depth = batch["depth_m"][0, time_index, 0].float().cpu().numpy() + valid = batch["depth_pixel_valid"][0, time_index, 0].bool().cpu().numpy() + K = batch["K"][0, time_index].float().cpu().numpy() + xyz, xyz_valid = unproject_depth(depth, K) + fig, axes = plt.subplots(2, 3, figsize=(13, 7), constrained_layout=True) + values = ( + (depth, "depth (m)", "viridis"), + (valid, "depth validity", "gray"), + (xyz[..., 2], "Z (m)", "viridis"), + (np.where(xyz_valid, xyz[..., 0], np.nan), "X (m)", "coolwarm"), + (np.where(xyz_valid, xyz[..., 1], np.nan), "Y (m)", "coolwarm"), + (np.linalg.norm(xyz, axis=-1), "XYZ norm (m)", "viridis"), + ) + for axis, (value, name, cmap) in zip(axes.flat, values, strict=True): + artist = axis.imshow(value, cmap=cmap) + axis.set_title(name) + axis.axis("off") + fig.colorbar(artist, ax=axis, shrink=0.75) + fig.suptitle(title) + fig.savefig(output, dpi=150) + plt.close(fig) + + +def render_frame_bundle( + output_dir: Path, + image: np.ndarray, + K: np.ndarray, + predicted_vertices: np.ndarray, + target_vertices: np.ndarray, + predicted_joints: np.ndarray, + target_joints_2d: np.ndarray, + direct_joints_2d: np.ndarray, + mano_joints_2d: np.ndarray, + valid_hands: np.ndarray, + faces: tuple[np.ndarray, np.ndarray], + title_lines: tuple[str, ...], +) -> np.ndarray: + predicted_layers = [ + MeshLayer(predicted_vertices[hand], faces[hand], PREDICTED_COLORS[hand], 0.58) + for hand in range(2) + ] + target_layers = [ + MeshLayer(target_vertices[hand], faces[hand], TARGET_COLORS[hand], 0.50) + for hand in range(2) if valid_hands[hand] + ] + predicted_render = render_mesh_layers(image, project_mesh_layers(predicted_layers, K)) + target_render = render_mesh_layers(image, project_mesh_layers(target_layers, K)) + joint_render = render_mesh_layers( + image, project_mesh_layers(target_layers + predicted_layers, K), + ) + panels = [image, target_render, predicted_render, joint_render] + names = ("RGB", "GT MANO", "predicted MANO", "joint z-buffer overlay") + labeled_panels = [] + for panel, name in zip(panels, names, strict=True): + labeled_panels.append(add_label(panel, (name,))) + mosaic = np.concatenate(( + np.concatenate(labeled_panels[:2], axis=1), + np.concatenate(labeled_panels[2:], axis=1), + ), axis=0) + cv2.imwrite(str(output_dir / "mesh_rgb_overlay.png"), cv2.cvtColor(add_label(mosaic, title_lines), cv2.COLOR_RGB2BGR)) + + for hand, side in enumerate(SIDES): + layers = [predicted_layers[hand]] + if valid_hands[hand]: + layers.insert(0, MeshLayer(target_vertices[hand], faces[hand], TARGET_COLORS[hand], 0.50)) + rendered = render_mesh_layers(image, project_mesh_layers(layers, K)) + cv2.imwrite(str(output_dir / f"{side}_mesh_overlay.png"), cv2.cvtColor(add_label(rendered, title_lines), cv2.COLOR_RGB2BGR)) + + skeleton = image.copy() + for hand in range(2): + if valid_hands[hand]: + skeleton = draw_skeleton(skeleton, target_joints_2d[hand], (255, 255, 255), marker="cross") + skeleton = draw_skeleton(skeleton, direct_joints_2d[hand], PREDICTED_COLORS[hand], marker="circle", draw_edges=False) + skeleton = draw_skeleton(skeleton, mano_joints_2d[hand], TARGET_COLORS[hand], marker="ring") + skeleton = add_label(skeleton, title_lines + ("GT=white cross; direct-2D=dot; projected predicted MANO=ring",)) + cv2.imwrite(str(output_dir / "skeleton_consistency_overlay.png"), cv2.cvtColor(skeleton, cv2.COLOR_RGB2BGR)) + return add_label(joint_render, title_lines) + + +def visualize_selections( + selections: list[dict[str, object]], + dataset: H2OCam4Dataset, + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + config: dict[str, Any], + output_root: Path, +) -> None: + faces = tuple(layer.th_faces.cpu().numpy() for layer in model.mano_layer.layers) + modalities = "RGB" + ("+Depth" if config["model"].get("use_depth") else "") + ("+K" if config["model"].get("use_rays") else "") + for selection_index, selection in enumerate(selections): + clip_index = int(selection["clip_index"]) + requested_time = int(selection["time_index"]) + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(): + target_vertices, _ = attach_gt_geometry(batch, model) + prediction = run_model(model, batch, dtype) + valid_times = int(batch["frame_valid"][0].sum()) + time_index = min(requested_time, valid_times - 1) + sample_dir = output_root / f"{selection_index:02d}_{selection['subject']}_{str(selection['sequence']).replace('/', '_')}_{int(selection['frame_id']):06d}" + sample_dir.mkdir(parents=True, exist_ok=True) + valid_hands = batch["mano_annotation_valid"][0, time_index].bool().cpu().numpy() + K = batch["K"][0, time_index].float().cpu().numpy() + image = rgb_from_batch(batch, time_index) + predicted_vertices = prediction["vertices_camera"][0, time_index].float().cpu().numpy() + target_vertices_np = target_vertices[0, time_index].float().cpu().numpy() + predicted_joints = prediction["joints_camera"][0, time_index].float() + mano_2d, _ = project_points(predicted_joints, batch["K"][0, time_index].float()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"][0, time_index].float().cpu().numpy() * np.asarray((width, height)) + title_lines = ( + f"{selection['subject']}/{selection['sequence']}/{int(selection['frame_id'])} | L/R valid={int(valid_hands[0])}/{int(valid_hands[1])}", + f"config={config['name']} input={modalities} presence=unsupervised", + f"selection={','.join(str(reason) for reason in selection['reasons'])}", + ) + render_frame_bundle( + sample_dir, image, K, predicted_vertices, target_vertices_np, + predicted_joints.cpu().numpy(), batch["joint2d"][0, time_index].float().cpu().numpy(), + direct_2d, mano_2d.cpu().numpy(), valid_hands, faces, title_lines, + ) + save_camera_views( + sample_dir / "camera_3d_front_side.png", predicted_vertices, target_vertices_np, + valid_hands, " | ".join(title_lines[:2]), + ) + save_depth_geometry(sample_dir / "depth_xyz.png", batch, time_index, " | ".join(title_lines[:2])) + + attention = prediction["attention"] + grid_hw = (height // int(config["model"].get("patch_size", 16)), width // int(config["model"].get("patch_size", 16))) + rgb_attention = attention["rgb_cross_attention"][0, -1, time_index].float().cpu().numpy() + save_attention_figure( + sample_dir / "rgb_attention_raw_shared_scale.png", image, + rgb_attention[0], rgb_attention[1], grid_hw, "RGB | " + " | ".join(title_lines[:2]), + ) + if "depth_cross_attention" in attention: + depth_attention = attention["depth_cross_attention"][0, -1, time_index].float().cpu().numpy() + save_attention_figure( + sample_dir / "depth_attention_raw_shared_scale.png", image, + depth_attention[0], depth_attention[1], grid_hw, "Depth | " + " | ".join(title_lines[:2]), + ) + if "temporal_attention" in attention: + temporal = attention["temporal_attention"][0, -1].float().cpu().numpy() + shared_max = max(float(temporal.max()), 1e-8) + fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True) + artist = None + for hand, side in enumerate(SIDES): + artist = axes[hand].imshow(temporal[hand], vmin=0, vmax=shared_max, cmap="viridis") + axes[hand].set_title(side) + axes[hand].set_xlabel("key frame") + axes[hand].set_ylabel("query frame") + fig.colorbar(artist, ax=axes, label="raw head-averaged attention weight") + fig.suptitle("last-layer, head-averaged temporal attention; not calibrated probability") + fig.savefig(sample_dir / "temporal_attention_raw_shared_scale.png", dpi=160) + plt.close(fig) + + video_path = sample_dir / "clip_mesh_overlay.mp4" + writer = cv2.VideoWriter(str(video_path), cv2.VideoWriter_fourcc(*"mp4v"), 4.0, (width, height)) + for clip_time in range(valid_times): + clip_image = rgb_from_batch(batch, clip_time) + clip_K = batch["K"][0, clip_time].float().cpu().numpy() + clip_valid = batch["mano_annotation_valid"][0, clip_time].bool().cpu().numpy() + pred_layers = [ + MeshLayer(prediction["vertices_camera"][0, clip_time, hand].float().cpu().numpy(), faces[hand], PREDICTED_COLORS[hand], 0.58) + for hand in range(2) + ] + gt_layers = [ + MeshLayer(target_vertices[0, clip_time, hand].float().cpu().numpy(), faces[hand], TARGET_COLORS[hand], 0.50) + for hand in range(2) if clip_valid[hand] + ] + rendered = render_mesh_layers(clip_image, project_mesh_layers(gt_layers + pred_layers, clip_K)) + rendered = add_label(rendered, ( + f"{selection['subject']}/{selection['sequence']} frame={int(batch['frame_id'][0, clip_time])}", + f"L/R valid={int(clip_valid[0])}/{int(clip_valid[1])} config={config['name']} input={modalities}", + )) + writer.write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + writer.release() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + parser.add_argument("--clip-indices-manifest", type=Path) + parser.add_argument("--num-workers", type=int, default=0) + parser.add_argument("--seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--skip-visualizations", action="store_true") + parser.add_argument( + "--phase4-diagnostics", + action="store_true", + help=( + "Add signed translation, action, asymmetry, local-depth, group, " + "CVaR, and long-failure diagnostics without changing model inference." + ), + ) + parser.add_argument( + "--drop-depth", action="store_true", + help="Mark metric depth unavailable at inference while retaining the RGB-D-K checkpoint.", + ) + parser.add_argument( + "--drop-k", action="store_true", + help="Mark intrinsics/ray conditioning unavailable at inference while retaining the RGB-D-K checkpoint.", + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + max_clips=args.max_clips, + oracle_crop_enabled=( + config["model"].get("oracle_crop_mode", "none") != "none" + ), + ) + subset_record = None + evaluation_dataset = dataset + if args.clip_indices_manifest is not None: + if args.max_clips is not None: + parser.error("--max-clips and --clip-indices-manifest are mutually exclusive") + if not args.skip_visualizations: + parser.error("clip-index subset evaluation requires --skip-visualizations") + indices, subset_record = load_clip_indices_manifest( + args.clip_indices_manifest, + source_manifest=args.manifest, + data_config=data_config, + dataset_length=len(dataset), + ) + evaluation_dataset = Subset(dataset, indices) + loader = DataLoader( + evaluation_dataset, batch_size=1, shuffle=False, num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + values: dict[str, list[float]] = defaultdict(list) + per_joint: dict[str, list[float]] = defaultdict(list) + attention_values: dict[str, list[float]] = defaultdict(list) + temporal_by_distance: dict[int, list[float]] = defaultdict(list) + temporal_by_signed_distance: dict[int, list[float]] = defaultdict(list) + frame_rows: list[dict[str, object]] = [] + temporal_rows: list[dict[str, object]] = [] + oracle_refinement_values: dict[str, list[float]] = defaultdict(list) + selection_records: list[dict[str, object]] = [] + frame_count = 0 + + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = move_to_device(batch_cpu, device) + target_vertices, _ = attach_gt_geometry(batch, model) + if args.drop_depth: + batch["depth_input_available"] = torch.zeros_like(batch["frame_valid"], dtype=torch.bool) + batch["depth_available"] = batch["depth_input_available"] + if args.drop_k: + batch["K_input_available"] = torch.zeros_like(batch["frame_valid"], dtype=torch.bool) + batch["K_available"] = batch["K_input_available"] + prediction = run_model(model, batch, dtype) + frame_valid = batch["frame_valid"].bool() + if "mixed_projection_success" in prediction: + mixed_valid = frame_valid[..., None].expand_as( + prediction["mixed_projection_success"], + ) + mixed_diagnostics = { + "mixed_projection_success_fraction": prediction[ + "mixed_projection_success" + ].float(), + "mixed_projection_support_count": prediction[ + "mixed_projection_support_count" + ].float(), + "mixed_projection_conditioning": prediction[ + "mixed_projection_conditioning" + ].float(), + "mixed_projection_inlier_ratio": prediction[ + "mixed_projection_inlier_ratio" + ].float(), + "mixed_projection_residual_scale_px": prediction[ + "mixed_projection_residual_scale_px" + ].float(), + } + for key, diagnostic in mixed_diagnostics.items(): + values[key].extend(diagnostic[mixed_valid].cpu().tolist()) + joint_annotation = batch["joint_annotation_valid"].bool() & frame_valid[..., None] + mano_annotation = batch["mano_annotation_valid"].bool() & frame_valid[..., None] + joint_valid = batch["joint_element_valid"].bool() & joint_annotation[..., None] + frame_count += int(frame_valid.sum()) + + target_joints = torch.nan_to_num(batch["joint3d_camera"]) + predicted_joints = prediction["joints_camera"].float() + absolute_joint_error = torch.linalg.vector_norm(predicted_joints - target_joints, dim=-1) * 1000.0 + predicted_relative = predicted_joints - predicted_joints[..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + relative_joint_error = torch.linalg.vector_norm(predicted_relative - target_relative, dim=-1) * 1000.0 + translation_signed_error = ( + prediction["wrist_root_translation"].float() + - torch.nan_to_num(batch["wrist_root_translation"]) + ) * 1000.0 + translation_error = translation_signed_error.abs() + + oracle_refinement = "coarse_joints_camera" in prediction + if oracle_refinement: + coarse_joints = prediction["coarse_joints_camera"].float() + coarse_absolute_joint_error = torch.linalg.vector_norm( + coarse_joints - target_joints, dim=-1, + ) * 1000.0 + coarse_relative = coarse_joints - coarse_joints[..., :1, :] + coarse_relative_joint_error = torch.linalg.vector_norm( + coarse_relative - target_relative, dim=-1, + ) * 1000.0 + coarse_translation_error = ( + prediction["coarse_wrist_root_translation"].float() + - torch.nan_to_num(batch["wrist_root_translation"]) + ).abs() * 1000.0 + rotation_delta_degrees = torch.linalg.vector_norm( + prediction["oracle_crop_rotation_delta_axis_angle"].float(), + dim=-1, + ).mean(dim=-1) * (180.0 / np.pi) + shape_delta_l2 = torch.linalg.vector_norm( + prediction["oracle_crop_shape_delta"].float(), dim=-1, + ) + delta_z_mm = prediction["oracle_crop_delta_z"].float().squeeze(-1) * 1000.0 + + vertex_error = torch.linalg.vector_norm(prediction["vertices_camera"].float() - target_vertices, dim=-1) * 1000.0 + predicted_vertex_relative = prediction["vertices_camera"].float() - prediction["wrist_root_translation"].float()[..., None, :] + target_vertex_relative = target_vertices - torch.nan_to_num(batch["wrist_root_translation"])[..., None, :] + relative_vertex_error = torch.linalg.vector_norm(predicted_vertex_relative - target_vertex_relative, dim=-1) * 1000.0 + if oracle_refinement: + coarse_vertices = prediction["coarse_vertices_camera"].float() + coarse_vertex_error = torch.linalg.vector_norm( + coarse_vertices - target_vertices, dim=-1, + ) * 1000.0 + coarse_vertex_relative = ( + coarse_vertices + - prediction["coarse_wrist_root_translation"].float()[..., None, :] + ) + coarse_relative_vertex_error = torch.linalg.vector_norm( + coarse_vertex_relative - target_vertex_relative, dim=-1, + ) * 1000.0 + + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor((width, height), device=device) + legacy_direct_2d = prediction["joint2d_norm"] * torch.tensor((width, height), device=device) + mano_2d, mano_positive = project_points(predicted_joints, batch["K"].float()) + target_2d = torch.nan_to_num(batch["joint2d"]) + direct_2d_error = torch.linalg.vector_norm(direct_2d - target_2d, dim=-1) + legacy_direct_2d_error = torch.linalg.vector_norm(legacy_direct_2d - target_2d, dim=-1) + mano_2d_error = torch.linalg.vector_norm(mano_2d - target_2d, dim=-1) + direct_mano_consistency = torch.linalg.vector_norm(direct_2d - mano_2d, dim=-1) + + for hand, side in enumerate(SIDES): + mask = joint_valid[..., hand, :] + hand_mask = mano_annotation[..., hand] + values[f"{side}_absolute_mpjpe_mm"].extend( + absolute_joint_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_root_relative_mpjpe_mm"].extend( + relative_joint_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_direct_2d_error_px"].extend( + direct_2d_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_legacy_bf16_direct_2d_error_px"].extend( + legacy_direct_2d_error[..., hand, :][mask].float().cpu().tolist() + ) + projected_mask = mask & mano_positive[..., hand, :] + values[f"{side}_mano_projected_2d_error_px"].extend( + mano_2d_error[..., hand, :][projected_mask].cpu().tolist() + ) + values[f"{side}_direct_mano_2d_consistency_px"].extend( + direct_mano_consistency[..., hand, :][projected_mask].cpu().tolist() + ) + values[f"{side}_absolute_mpvpe_mm"].extend(vertex_error[..., hand, :].mean(-1)[hand_mask].cpu().tolist()) + values[f"{side}_root_relative_mpvpe_mm"].extend(relative_vertex_error[..., hand, :].mean(-1)[hand_mask].cpu().tolist()) + for axis_index, axis in enumerate("xyz"): + values[f"{side}_translation_{axis}_mae_mm"].extend(translation_error[..., hand, axis_index][joint_annotation[..., hand]].cpu().tolist()) + if args.phase4_diagnostics: + values[f"{side}_translation_{axis}_signed_error_mm"].extend( + translation_signed_error[..., hand, axis_index][ + joint_annotation[..., hand] + ].cpu().tolist() + ) + for joint_index in range(21): + joint_mask = mask[..., joint_index] + per_joint[f"{side}_{joint_index:02d}_absolute_mpjpe_mm"].extend( + absolute_joint_error[..., hand, joint_index][joint_mask].cpu().tolist() + ) + fingertip_mask = mask[..., list(FINGERTIP_INDICES)] + fingertip_count = fingertip_mask.sum(-1) + values[f"{side}_fingertip_mpjpe_mm"].extend( + ( + (absolute_joint_error[..., hand, list(FINGERTIP_INDICES)] * fingertip_mask).sum(-1) + / fingertip_count.clamp_min(1) + )[fingertip_count > 0].cpu().tolist() + ) + + if predicted_joints.shape[1] > 1: + pair_valid = joint_annotation[:, 1:] & joint_annotation[:, :-1] + predicted_wrist_velocity = prediction["wrist_root_translation"][:, 1:] - prediction["wrist_root_translation"][:, :-1] + target_wrist_velocity = torch.nan_to_num(batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1]) + wrist_velocity_error = torch.linalg.vector_norm(predicted_wrist_velocity - target_wrist_velocity, dim=-1) * 1000.0 + values["wrist_velocity_error_mm_per_frame"].extend(wrist_velocity_error[pair_valid].float().cpu().tolist()) + predicted_joint_velocity = predicted_joints[:, 1:] - predicted_joints[:, :-1] + target_joint_velocity = target_joints[:, 1:] - target_joints[:, :-1] + pair_joint_valid = joint_valid[:, 1:] & joint_valid[:, :-1] + joint_velocity_error = torch.linalg.vector_norm(predicted_joint_velocity - target_joint_velocity, dim=-1) * 1000.0 + values["joint_velocity_error_mm_per_frame"].extend(joint_velocity_error[pair_joint_valid].cpu().tolist()) + acceleration_valid = None + acceleration_error = None + if predicted_wrist_velocity.shape[1] > 1: + acceleration_valid = pair_valid[:, 1:] & pair_valid[:, :-1] + predicted_acceleration = predicted_wrist_velocity[:, 1:] - predicted_wrist_velocity[:, :-1] + target_acceleration = target_wrist_velocity[:, 1:] - target_wrist_velocity[:, :-1] + acceleration_error = torch.linalg.vector_norm(predicted_acceleration - target_acceleration, dim=-1) * 1000.0 + values["wrist_acceleration_error_mm_per_frame2"].extend(acceleration_error[acceleration_valid].float().cpu().tolist()) + + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + for transition_index in range(pair_valid.shape[1]): + for hand, side in enumerate(SIDES): + if not bool(pair_valid[0, transition_index, hand]): + continue + valid_joint_mask = pair_joint_valid[0, transition_index, hand] + joint_value = ( + float(joint_velocity_error[0, transition_index, hand][valid_joint_mask].mean()) + if bool(valid_joint_mask.any()) else None + ) + acceleration_value = None + if ( + transition_index > 0 + and acceleration_valid is not None + and bool(acceleration_valid[0, transition_index - 1, hand]) + ): + acceleration_value = float(acceleration_error[0, transition_index - 1, hand]) + temporal_rows.append({ + "clip_index": clip_index, + "transition_index": transition_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id_from": int(batch["frame_id"][0, transition_index]), + "frame_id_to": int(batch["frame_id"][0, transition_index + 1]), + "side": side, + "wrist_velocity_error_mm_per_frame": float(wrist_velocity_error[0, transition_index, hand]), + "joint_velocity_error_mm_per_frame": joint_value, + "wrist_acceleration_error_mm_per_frame2": acceleration_value, + "identity_switch_fraction": None, + }) + + wrong_sequence: list[bool | None] = [] + valid_length = int(frame_valid[0].sum()) + for time_index in range(valid_length): + annotation_state = "".join(str(int(value)) for value in joint_annotation[0, time_index].int().cpu().tolist()) + both_valid = bool(joint_annotation[0, time_index].all()) + wrong_side = None + if both_valid: + correct = 0.5 * ( + absolute_joint_error[0, time_index, 0].mean() + + absolute_joint_error[0, time_index, 1].mean() + ) + swapped = 0.5 * ( + torch.linalg.vector_norm(predicted_joints[0, time_index, 0] - target_joints[0, time_index, 1], dim=-1).mean() + + torch.linalg.vector_norm(predicted_joints[0, time_index, 1] - target_joints[0, time_index, 0], dim=-1).mean() + ) * 1000.0 + wrong_side = bool(swapped < correct) + values["wrong_side_preference"].append(float(wrong_side)) + wrong_sequence.append(wrong_side) + valid_hand_errors = [ + float(absolute_joint_error[0, time_index, hand].mean()) + for hand in range(2) if joint_annotation[0, time_index, hand] + ] + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + frame_id = int(batch["frame_id"][0, time_index]) + sizes: list[float | None] = [None, None] + depths: list[float | None] = [None, None] + for hand in range(2): + is_valid = bool(joint_annotation[0, time_index, hand]) + if is_valid: + extent = batch["joint2d"][0, time_index, hand].max(0).values - batch["joint2d"][0, time_index, hand].min(0).values + sizes[hand] = float(extent.max()) + depths[hand] = float(batch["wrist_root_translation"][0, time_index, hand, 2]) + valid_sizes = [value for value in sizes if value is not None] + valid_depths = [value for value in depths if value is not None] + asymmetry = bimanual_asymmetry(sizes, depths) + if args.phase4_diagnostics: + action_label = load_action_label(args.root, take, frame_id) + action = action_name(action_label) + action_family = str(batch["sequence_id"][0]).split("/", 1)[0] + depth_np = batch["depth_m"][0, time_index, 0].float().cpu().numpy() + depth_valid_np = ( + batch["depth_pixel_valid"][0, time_index, 0].bool().cpu().numpy() + ) + else: + action_label = None + action = None + action_family = None + depth_np = None + depth_valid_np = None + for hand in range(2): + is_valid = bool(joint_annotation[0, time_index, hand]) + size = sizes[hand] + depth = depths[hand] + local_depth: dict[str, float | int | None] = {} + if args.phase4_diagnostics and is_valid: + local_depth = local_depth_statistics( + depth_np, + depth_valid_np, + batch["joint2d"][0, time_index, hand].float().cpu().numpy(), + ) + local_median = local_depth.get("depth_median_m") + local_surface_minus_wrist = ( + float(local_median) - float(depth) + if local_median is not None and depth is not None + else None + ) + row = { + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "side": SIDES[hand], + "annotation_valid": int(is_valid), + "annotation_state": annotation_state, + "hand_size_px": size, + "hand_size_bucket": hand_size_bucket(size), + "wrist_depth_m": depth, + "depth_bucket": wrist_depth_bucket(depth), + "absolute_mpjpe_mm": float(absolute_joint_error[0, time_index, hand].mean()) if is_valid else None, + "root_relative_mpjpe_mm": float(relative_joint_error[0, time_index, hand].mean()) if is_valid else None, + "absolute_mpvpe_mm": float(vertex_error[0, time_index, hand].mean()) if bool(mano_annotation[0, time_index, hand]) else None, + "root_relative_mpvpe_mm": float(relative_vertex_error[0, time_index, hand].mean()) if bool(mano_annotation[0, time_index, hand]) else None, + "direct_2d_error_px": float(direct_2d_error[0, time_index, hand].mean()) if is_valid else None, + "legacy_bf16_direct_2d_error_px": float(legacy_direct_2d_error[0, time_index, hand].mean()) if is_valid else None, + "mano_projected_2d_error_px": float(mano_2d_error[0, time_index, hand].mean()) if is_valid else None, + "direct_mano_2d_consistency_px": float(direct_mano_consistency[0, time_index, hand].mean()) if is_valid else None, + "fingertip_mpjpe_mm": float(absolute_joint_error[0, time_index, hand, list(FINGERTIP_INDICES)].mean()) if is_valid else None, + "translation_x_mae_mm": float(translation_error[0, time_index, hand, 0]) if is_valid else None, + "translation_y_mae_mm": float(translation_error[0, time_index, hand, 1]) if is_valid else None, + "translation_z_mae_mm": float(translation_error[0, time_index, hand, 2]) if is_valid else None, + "wrong_side_preference": int(wrong_side) if wrong_side is not None else None, + } + if args.phase4_diagnostics: + predicted_translation = prediction["wrist_root_translation"][ + 0, time_index, hand + ].float() + target_translation = batch["wrist_root_translation"][ + 0, time_index, hand + ].float() + row.update({ + "action_family": action_family, + "action_label": action_label, + "action_name": action, + **asymmetry, + "local_depth_valid_fraction": local_depth.get("valid_fraction"), + "local_depth_validity_bucket": depth_validity_bucket( + local_depth.get("valid_fraction") + ), + "local_depth_median_m": local_median, + "local_depth_q10_m": local_depth.get("depth_q10_m"), + "local_depth_q90_m": local_depth.get("depth_q90_m"), + "local_depth_iqr_m": local_depth.get("depth_iqr_m"), + "local_depth_discontinuity_m": local_depth.get( + "depth_discontinuity_m" + ), + "local_surface_minus_wrist_z_m": local_surface_minus_wrist, + "predicted_wrist_x_m": ( + float(predicted_translation[0]) if is_valid else None + ), + "predicted_wrist_y_m": ( + float(predicted_translation[1]) if is_valid else None + ), + "predicted_wrist_z_m": ( + float(predicted_translation[2]) if is_valid else None + ), + "target_wrist_x_m": float(target_translation[0]) if is_valid else None, + "target_wrist_y_m": float(target_translation[1]) if is_valid else None, + "target_wrist_z_m": float(target_translation[2]) if is_valid else None, + "translation_x_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 0]) + if is_valid else None + ), + "translation_y_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 1]) + if is_valid else None + ), + "translation_z_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 2]) + if is_valid else None + ), + }) + if oracle_refinement: + mano_is_valid = bool(mano_annotation[0, time_index, hand]) + oracle_fields = { + "coarse_absolute_mpjpe_mm": ( + float(coarse_absolute_joint_error[0, time_index, hand].mean()) + if is_valid else None + ), + "coarse_root_relative_mpjpe_mm": ( + float(coarse_relative_joint_error[0, time_index, hand].mean()) + if is_valid else None + ), + "coarse_absolute_mpvpe_mm": ( + float(coarse_vertex_error[0, time_index, hand].mean()) + if mano_is_valid else None + ), + "coarse_root_relative_mpvpe_mm": ( + float(coarse_relative_vertex_error[0, time_index, hand].mean()) + if mano_is_valid else None + ), + "coarse_fingertip_mpjpe_mm": ( + float(coarse_absolute_joint_error[ + 0, time_index, hand, list(FINGERTIP_INDICES) + ].mean()) + if is_valid else None + ), + "coarse_translation_z_mae_mm": ( + float(coarse_translation_error[0, time_index, hand, 2]) + if is_valid else None + ), + "oracle_crop_delta_z_mm": ( + float(delta_z_mm[0, time_index, hand]) + if is_valid else None + ), + "oracle_crop_rotation_delta_geodesic_deg": ( + float(rotation_delta_degrees[0, time_index, hand]) + if is_valid else None + ), + "oracle_crop_shape_delta_l2": ( + float(shape_delta_l2[0, hand]) if is_valid else None + ), + "oracle_crop_rgb_available": int( + prediction["oracle_crop_rgb_available"][0, time_index, hand] + ), + "oracle_crop_depth_available": int( + prediction["oracle_crop_depth_available_effective"][ + 0, time_index, hand + ] + ), + } + row.update(oracle_fields) + if is_valid: + for key, value in oracle_fields.items(): + if key.startswith("oracle_crop_") and value is not None: + oracle_refinement_values[key].append(float(value)) + frame_rows.append(row) + selection_records.append({ + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "annotation_state": annotation_state, + "hand_size_bucket": hand_size_bucket(float(np.mean(valid_sizes))) if valid_sizes else None, + "depth_bucket": wrist_depth_bucket(float(np.mean(valid_depths))) if valid_depths else None, + "absolute_mpjpe_mm": float(np.mean(valid_hand_errors)) if valid_hand_errors else None, + }) + for transition_index, (previous, current) in enumerate( + zip(wrong_sequence[:-1], wrong_sequence[1:], strict=True) + ): + if previous is not None and current is not None: + identity_switch = float(previous != current) + values["identity_switch_fraction"].append(identity_switch) + temporal_rows.append({ + "clip_index": clip_index, + "transition_index": transition_index, + "take": f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4", + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id_from": int(batch["frame_id"][0, transition_index]), + "frame_id_to": int(batch["frame_id"][0, transition_index + 1]), + "side": "bimanual", + "wrist_velocity_error_mm_per_frame": None, + "joint_velocity_error_mm_per_frame": None, + "wrist_acceleration_error_mm_per_frame2": None, + "identity_switch_fraction": identity_switch, + }) + + attention = prediction["attention"] + rgb = attention["rgb_cross_attention"][:, -1] + left, right = rgb[..., 0, :], rgb[..., 1, :] + attention_values["rgb_same_peak"].extend((left.argmax(-1) == right.argmax(-1))[frame_valid].float().cpu().tolist()) + attention_values["rgb_left_right_cosine"].extend(torch.nn.functional.cosine_similarity(left, right, dim=-1)[frame_valid].float().cpu().tolist()) + attention_values["rgb_update_norm"].extend(attention["rgb_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + for key in ("depth_fusion_gate", "depth_fusion_gate_raw", "depth_update_norm", "gated_depth_update_norm"): + if key in attention: + attention_values[key].extend(attention[key][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + if "temporal_update_norm" in attention: + attention_values["temporal_update_norm"].extend( + attention["temporal_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist() + ) + if "temporal_attention" in attention: + temporal = attention["temporal_attention"][:, -1] + for hand in range(2): + valid_indices = torch.where(frame_valid[0])[0] + for query_index in valid_indices: + weights = temporal[0, hand, query_index, valid_indices].float() + normalized = weights / weights.sum().clamp_min(1e-8) + if normalized.numel() > 1: + entropy = -(normalized * normalized.clamp_min(1e-8).log()).sum() / np.log(normalized.numel()) + attention_values["temporal_normalized_entropy"].append(float(entropy)) + attention_values["temporal_diagonal"].append(float(temporal[0, hand, query_index, query_index])) + for key_index, key_frame in enumerate(valid_indices): + signed_distance = int(key_frame) - int(query_index) + temporal_by_distance[abs(signed_distance)].append(float(weights[key_index])) + temporal_by_signed_distance[signed_distance].append(float(weights[key_index])) + + selections = select_visualization_frames(selection_records, seed=args.seed) + strata_counts = { + field: { + str(value): sum(record.get(field) == value for record in selection_records) + for value in values_to_count + } + for field, values_to_count in ( + ("hand_size_bucket", ("small", "medium", "large")), + ("depth_bucket", ("near", "middle", "far")), + ("annotation_state", ("00", "01", "10", "11")), + ) + } + selection_manifest = { + "seed": args.seed, + "source_manifest": str(args.manifest.resolve()), + "clip_indices_manifest": ( + { + "path": str(args.clip_indices_manifest.resolve()), + "sha256": sha256(args.clip_indices_manifest), + "version": subset_record.get("version"), + "count": subset_record.get("count"), + } + if args.clip_indices_manifest is not None else None + ), + "checkpoint": str(args.checkpoint.resolve()), + "selection_policy": "random4 + error P50/P90/P95/worst + size/depth/valid-state medians", + "strata_counts": strata_counts, + "unavailable_requested_strata": [ + f"{field}={value}" + for field, counts in strata_counts.items() + for value, count in counts.items() if count == 0 + ], + "samples": selections, + } + (args.output_dir / "selection_manifest.json").write_text(json.dumps(selection_manifest, indent=2) + "\n", encoding="utf-8") + write_csv(args.output_dir / "per_hand_frame_metrics.csv", frame_rows) + write_csv(args.output_dir / "per_temporal_transition_metrics.csv", temporal_rows) + phase4_group_rows: list[dict[str, object]] = [] + phase4_failure_rows: list[dict[str, object]] = [] + if args.phase4_diagnostics: + phase4_metrics = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + ) + if oracle_refinement_values: + phase4_metrics += ( + "coarse_absolute_mpjpe_mm", + "coarse_root_relative_mpjpe_mm", + "coarse_absolute_mpvpe_mm", + "coarse_root_relative_mpvpe_mm", + "coarse_fingertip_mpjpe_mm", + "coarse_translation_z_mae_mm", + "oracle_crop_delta_z_mm", + "oracle_crop_rotation_delta_geodesic_deg", + "oracle_crop_shape_delta_l2", + ) + phase4_group_rows = summarize_group_metrics( + frame_rows, + phase4_metrics, + ( + "take", + "action_family", + "action_label", + "action_name", + "hand_size_bucket", + "depth_bucket", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", + ), + ) + phase4_failure_rows = find_failure_intervals( + frame_rows, + metric="translation_z_mae_mm", + threshold=40.0, + minimum_frames=3, + ) + find_failure_intervals( + frame_rows, + metric="absolute_mpjpe_mm", + threshold=50.0, + minimum_frames=3, + ) + write_csv(args.output_dir / "phase4_group_metrics.csv", phase4_group_rows) + write_csv(args.output_dir / "phase4_failure_intervals.csv", phase4_failure_rows) + + joint_rows = [] + for name, metric_values in sorted(per_joint.items()): + side, joint_index, _ = name.split("_", 2) + joint_rows.append({"side": side, "joint_index": int(joint_index), **distribution_summary(metric_values)}) + write_csv(args.output_dir / "per_joint_metrics.csv", joint_rows) + + bootstrap_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", "direct_2d_error_px", "mano_projected_2d_error_px", + "translation_z_mae_mm", "fingertip_mpjpe_mm", "wrong_side_preference", + ) + bootstrap_rows = bootstrap_take_means( + frame_rows, bootstrap_metrics, seed=args.seed, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "bootstrap_ci.csv", bootstrap_rows) + temporal_bootstrap_metrics = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", + ) + temporal_bootstrap_rows = bootstrap_take_means( + temporal_rows, temporal_bootstrap_metrics, + seed=args.seed, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "temporal_bootstrap_ci.csv", temporal_bootstrap_rows) + + distribution_metrics = {key: distribution_summary(metric_values) for key, metric_values in sorted(values.items())} + combined_keys = { + "absolute_mpjpe_mm": ("left_absolute_mpjpe_mm", "right_absolute_mpjpe_mm"), + "root_relative_mpjpe_mm": ("left_root_relative_mpjpe_mm", "right_root_relative_mpjpe_mm"), + "absolute_mpvpe_mm": ("left_absolute_mpvpe_mm", "right_absolute_mpvpe_mm"), + "root_relative_mpvpe_mm": ("left_root_relative_mpvpe_mm", "right_root_relative_mpvpe_mm"), + "direct_2d_error_px": ("left_direct_2d_error_px", "right_direct_2d_error_px"), + "legacy_bf16_direct_2d_error_px": ("left_legacy_bf16_direct_2d_error_px", "right_legacy_bf16_direct_2d_error_px"), + "mano_projected_2d_error_px": ("left_mano_projected_2d_error_px", "right_mano_projected_2d_error_px"), + "direct_mano_2d_consistency_px": ("left_direct_mano_2d_consistency_px", "right_direct_mano_2d_consistency_px"), + "fingertip_mpjpe_mm": ("left_fingertip_mpjpe_mm", "right_fingertip_mpjpe_mm"), + "translation_z_mae_mm": ("left_translation_z_mae_mm", "right_translation_z_mae_mm"), + } + for combined, components in combined_keys.items(): + distribution_metrics[combined] = distribution_summary(values[components[0]] + values[components[1]]) + + attention_report = { + key: distribution_summary(metric_values) for key, metric_values in sorted(attention_values.items()) + } + attention_report["temporal_attention_by_absolute_frame_distance"] = { + str(distance): distribution_summary(metric_values) + for distance, metric_values in sorted(temporal_by_distance.items()) + } + attention_report["temporal_attention_by_signed_frame_distance"] = { + str(distance): distribution_summary(metric_values) + for distance, metric_values in sorted(temporal_by_signed_distance.items()) + } + (args.output_dir / "attention_diagnostics.json").write_text(json.dumps(attention_report, indent=2) + "\n", encoding="utf-8") + position_bias_report = temporal_position_bias_report(model) + (args.output_dir / "temporal_position_bias.json").write_text( + json.dumps(position_bias_report, indent=2) + "\n", encoding="utf-8", + ) + + report = { + "status": "evaluated", + "split_role": "official_validation" if "val" in args.manifest.name else "non_test_evaluation", + "official_test_used": False, + "config": config, + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": sha256(args.checkpoint), + "step": int(checkpoint_state["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "inference_modality_override": { + "drop_depth": bool(args.drop_depth), + "drop_k": bool(args.drop_k), + "availability_contract": "input_and_legacy_flags_v2", + }, + "clips": len(evaluation_dataset), + "clip_indices_manifest": ( + { + "path": str(args.clip_indices_manifest.resolve()), + "sha256": sha256(args.clip_indices_manifest), + "version": subset_record.get("version"), + "count": subset_record.get("count"), + } + if args.clip_indices_manifest is not None else None + ), + "frames": frame_count, + "data_loader_workers": args.num_workers, + "metrics": distribution_metrics, + "attention": attention_report, + "temporal_position_bias": position_bias_report, + "bootstrap": bootstrap_rows, + "temporal_bootstrap": temporal_bootstrap_rows, + "phase4_diagnostics": { + "enabled": bool(args.phase4_diagnostics), + "group_rows": len(phase4_group_rows), + "failure_intervals": len(phase4_failure_rows), + "local_depth_contract": ( + "GT-joint region on aligned resized metric depth; surface statistics are " + "diagnostic and are not wrist-depth targets" + if args.phase4_diagnostics else None + ), + "failure_thresholds": ( + {"translation_z_mae_mm": 40.0, "absolute_mpjpe_mm": 50.0} + if args.phase4_diagnostics else None + ), + }, + "oracle_crop_refinement": { + "enabled": bool(oracle_refinement_values), + "gt_location_at_inference": bool(oracle_refinement_values), + "coarse_checkpoint_sha256": config.get("experiment", {}).get( + "coarse_checkpoint_sha256" + ), + "metrics": { + key: distribution_summary(metric_values) + for key, metric_values in sorted(oracle_refinement_values.items()) + }, + }, + "metric_definitions": { + "absolute_mpjpe_mm": "valid-joint-weighted Euclidean camera-space joint error", + "direct_2d_error_px": "valid-joint-weighted direct-head pixel error; frame means are used for take bootstrap", + "legacy_bf16_direct_2d_error_px": "Phase 2 compatibility metric that scales bf16 normalized coordinates before float conversion", + "absolute_mpvpe_mm": "mean Euclidean camera-space vertex error; MVE/MPVPE", + "root_relative_mpvpe_mm": "vertex error after subtracting each wrist/root", + "wrong_side_preference": "swapped L/R joint assignment has lower combined cost than semantic assignment", + "identity_switch_fraction": "adjacent both-valid frames change wrong-side assignment preference", + "translation_axis_signed_error_mm": "predicted camera-space wrist axis minus GT wrist axis", + "cvar95": "mean of observations at or above the empirical 95th percentile", + "attention": "last-layer, PyTorch head-averaged attention weights; not calibrated probability", + }, + "presence_note": "H2O annotation validity is not presence; no presence metric is reported.", + "device": torch.cuda.get_device_name(device), + "trainable_parameters": sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad), + "frozen_parameters": sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad), + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + + if not args.skip_visualizations: + visualize_selections( + selections, dataset, model, device, dtype, config, + args.output_dir / "visualization_audit", + ) + print(json.dumps({ + "status": report["status"], "clips": report["clips"], "frames": report["frames"], + "absolute_mpjpe_mm": distribution_metrics["absolute_mpjpe_mm"]["mean"], + "absolute_mpvpe_mm": distribution_metrics["absolute_mpvpe_mm"]["mean"], + "output_dir": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase4_jitter.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase4_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..01ef42bd758f0d15f63365ddcabec5115ffd2f99 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase4_jitter.py @@ -0,0 +1,767 @@ +#!/usr/bin/env python3 +"""Evaluate preregistered inference-only temporal filters from raw caches.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +import numpy as np +import torch + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.temporal_filter import ( + apply_by_segment, + butterworth_zero_phase, + derivative_norms, + ema, + ema_low_frequency_delay_frames, + filter_rotation_matrices, + high_frequency_energy_ratio, + rotation_geodesic_degrees, + valid_segments, +) +from foundation_hand.models.mano import ManoCameraLayer + + +FPS = 30.0 +FINGERTIPS = (4, 8, 12, 16, 20) + + +@dataclass(frozen=True) +class FilterCondition: + name: str + family: str + value: float | None + causal_status: str + latency_frames: float | None + + +def condition_grid() -> dict[str, FilterCondition]: + conditions = { + "F0_raw": FilterCondition("F0_raw", "F0", None, "raw", 0.0), + } + for alpha in (0.2, 0.4, 0.6): + name = f"F1_ema_alpha{alpha:g}" + conditions[name] = FilterCondition( + name, "F1", alpha, "causal", ema_low_frequency_delay_frames(alpha), + ) + for cutoff in (2.0, 4.0, 6.0): + name = f"F2_butterworth_{cutoff:g}hz" + conditions[name] = FilterCondition( + name, "F2", cutoff, "offline_zero_phase", None, + ) + return conditions + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty jitter report: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_take(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + if float(arrays["fps"]) != FPS: + raise ValueError(f"jitter cache fps mismatch: {path}") + return arrays + + +def filtered_parameters( + arrays: dict[str, np.ndarray], condition: FilterCondition, +) -> tuple[np.ndarray, np.ndarray, int]: + translation = arrays["pred_wrist_translation"].astype(np.float32) + rotations = arrays["pred_rotation_matrices"].astype(np.float32) + if condition.family == "F0": + return translation.copy(), rotations.copy(), 0 + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + if condition.family == "F1": + assert condition.value is not None + translation, fallback_translation = apply_by_segment( + translation, segments, + lambda values: ema(values, condition.value), minimum_frames=1, + ) + rotations, fallback_rotation = apply_by_segment( + rotations, segments, + lambda values: filter_rotation_matrices( + values, lambda quaternion: ema(quaternion, condition.value), + ), + minimum_frames=1, + ) + elif condition.family == "F2": + assert condition.value is not None + operation = lambda values: butterworth_zero_phase( + values, condition.value, FPS, order=2, + ) + translation, fallback_translation = apply_by_segment( + translation, segments, operation, minimum_frames=4, + ) + rotations, fallback_rotation = apply_by_segment( + rotations, segments, + lambda values: filter_rotation_matrices(values, operation), + minimum_frames=4, + ) + else: + raise ValueError(f"unsupported filter family: {condition.family}") + if fallback_translation != fallback_rotation: + raise AssertionError("translation/rotation filter fallback counts differ") + return translation, rotations, fallback_translation + + +def rebuild_geometry( + rotations: np.ndarray, + shape: np.ndarray, + translation: np.ndarray, + mano: ManoCameraLayer, + device: torch.device, + chunk_size: int = 256, +) -> tuple[np.ndarray, np.ndarray]: + vertices = [] + joints = [] + for start in range(0, len(rotations), chunk_size): + stop = min(start + chunk_size, len(rotations)) + with torch.inference_mode(): + chunk_vertices, chunk_joints = mano( + torch.from_numpy(rotations[start:stop]).to(device), + torch.from_numpy(shape[start:stop]).to(device), + torch.from_numpy(translation[start:stop]).to(device), + ) + vertices.append(chunk_vertices.cpu().numpy()) + joints.append(chunk_joints.cpu().numpy()) + return np.concatenate(vertices), np.concatenate(joints) + + +def project_points(points: np.ndarray, intrinsics: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + z = points[..., 2] + positive = np.isfinite(points).all(axis=-1) & (z > 1e-8) + safe_z = np.where(positive, z, 1.0) + x = intrinsics[:, None, None, 0, 0] * points[..., 0] / safe_z + x += intrinsics[:, None, None, 0, 2] + y = intrinsics[:, None, None, 1, 1] * points[..., 1] / safe_z + y += intrinsics[:, None, None, 1, 2] + projected = np.stack((x, y), axis=-1) + projected[~positive] = np.nan + return projected, positive + + +def append_finite(output: dict[str, list[float]], key: str, values: Iterable[float]) -> None: + output[key].extend(float(value) for value in values if np.isfinite(value)) + + +def per_frame_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + vertices: np.ndarray, + rotations: np.ndarray, + translation: np.ndarray, + frame_selected: np.ndarray, +) -> tuple[dict[str, list[float]], np.ndarray, np.ndarray]: + output: dict[str, list[float]] = defaultdict(list) + target_joints = arrays["target_joints_camera"] + target_vertices = arrays["target_vertices_camera"] + target_translation = arrays["target_wrist_translation"] + joint_valid = arrays["joint_element_valid"].astype(bool) + joint_valid &= frame_selected[:, None, None] + mano_valid = arrays["mano_annotation_valid"].astype(bool) + mano_valid &= frame_selected[:, None] + + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + joint_relative = joints - joints[..., :1, :] + target_joint_relative = target_joints - target_joints[..., :1, :] + root_joint_error = np.linalg.norm( + joint_relative - target_joint_relative, axis=-1, + ) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + vertex_relative = vertices - translation[..., None, :] + target_vertex_relative = target_vertices - target_translation[..., None, :] + root_vertex_error = np.linalg.norm( + vertex_relative - target_vertex_relative, axis=-1, + ) * 1000.0 + translation_signed = (translation - target_translation) * 1000.0 + + projected, projected_positive = project_points(joints, arrays["K"]) + projected_valid = joint_valid & projected_positive + target_2d = arrays["target_2d_px"] + projected_error = np.linalg.norm(projected - target_2d, axis=-1) + consistency = np.linalg.norm(projected - arrays["pred_direct_2d_px"], axis=-1) + direct_error = np.linalg.norm(arrays["pred_direct_2d_px"] - target_2d, axis=-1) + rotation_error = rotation_geodesic_degrees( + rotations, arrays["target_rotation_matrices"], + ).mean(axis=-1) + + for time_index in range(len(joints)): + for hand in range(2): + valid_joints = joint_valid[time_index, hand] + if valid_joints.any(): + append_finite(output, "absolute_mpjpe_mm", [ + joint_error[time_index, hand, valid_joints].mean() + ]) + append_finite(output, "root_relative_mpjpe_mm", [ + root_joint_error[time_index, hand, valid_joints].mean() + ]) + fingertip_valid = valid_joints[list(FINGERTIPS)] + if fingertip_valid.any(): + fingertip_values = joint_error[ + time_index, hand, list(FINGERTIPS) + ][fingertip_valid] + append_finite(output, "fingertip_mpjpe_mm", [fingertip_values.mean()]) + append_finite(output, "direct_2d_error_px", [ + direct_error[time_index, hand, valid_joints].mean() + ]) + valid_projected = projected_valid[time_index, hand] + if valid_projected.any(): + append_finite(output, "projected_mano_2d_error_px", [ + projected_error[time_index, hand, valid_projected].mean() + ]) + append_finite(output, "direct_mano_consistency_px", [ + consistency[time_index, hand, valid_projected].mean() + ]) + for axis, name in enumerate("xyz"): + append_finite(output, f"translation_{name}_signed_error_mm", [ + translation_signed[time_index, hand, axis] + ]) + append_finite(output, f"translation_{name}_mae_mm", [ + abs(translation_signed[time_index, hand, axis]) + ]) + if mano_valid[time_index, hand]: + append_finite(output, "absolute_mpvpe_mm", [ + vertex_error[time_index, hand].mean() + ]) + append_finite(output, "root_relative_mpvpe_mm", [ + root_vertex_error[time_index, hand].mean() + ]) + append_finite(output, "rotation_geodesic_error_deg", [ + rotation_error[time_index, hand] + ]) + return output, projected, joint_valid + + +def selected_segments( + arrays: dict[str, np.ndarray], frame_selected: np.ndarray, +) -> list[np.ndarray]: + return valid_segments( + arrays["clip_index"], arrays["frame_id"], + arrays["frame_valid"].astype(bool) & frame_selected, + ) + + +def temporal_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + projected: np.ndarray, + frame_selected: np.ndarray, +) -> dict[str, list[float]]: + output: dict[str, list[float]] = defaultdict(list) + segments = selected_segments(arrays, frame_selected) + target = arrays["target_joints_camera"] + annotation = arrays["joint_element_valid"].astype(bool) + for indices in segments: + for hand in range(2): + predicted_hand = joints[indices, hand] + target_hand = target[indices, hand] + valid_hand = annotation[indices, hand] + for order, error_name in ( + (1, "joint_velocity_error_mm_per_s"), + (2, "joint_acceleration_error_mm_per_s2"), + ): + if len(indices) <= order: + continue + predicted_derivative = np.diff(predicted_hand, n=order, axis=0) * FPS**order + target_derivative = np.diff(target_hand, n=order, axis=0) * FPS**order + derivative_valid = np.stack([ + valid_hand[start : len(valid_hand) - order + start] + for start in range(order + 1) + ]).all(axis=0) + errors = np.linalg.norm( + predicted_derivative - target_derivative, axis=-1, + ) * 1000.0 + for row, valid in zip(errors, derivative_valid, strict=True): + if valid.any(): + append_finite(output, error_name, [row[valid].mean()]) + translation_hand = joints[indices, hand, 0] + target_translation_hand = arrays["target_wrist_translation"][indices, hand] + translation_valid = arrays["joint_annotation_valid"][indices, hand].astype(bool) + for order, error_name in ( + (1, "wrist_velocity_error_mm_per_s"), + (2, "wrist_acceleration_error_mm_per_s2"), + ): + if len(indices) <= order: + continue + predicted_derivative = np.diff( + translation_hand, n=order, axis=0, + ) * FPS**order + target_derivative = np.diff( + target_translation_hand, n=order, axis=0, + ) * FPS**order + derivative_valid = np.stack([ + translation_valid[start : len(translation_valid) - order + start] + for start in range(order + 1) + ]).all(axis=0) + errors = np.linalg.norm( + predicted_derivative - target_derivative, axis=-1, + ) * 1000.0 + append_finite(output, error_name, errors[derivative_valid]) + if len(indices) >= 3: + acceleration = derivative_norms(predicted_hand, FPS, 2) * 1000.0 + append_finite( + output, "predicted_3d_joint_acceleration_mm_per_s2", + acceleration.mean(axis=-1), + ) + projected_acceleration = derivative_norms( + projected[indices, hand], FPS, 2, + ) + append_finite( + output, "predicted_2d_joint_acceleration_px_per_s2", + np.nanmean(projected_acceleration, axis=-1), + ) + if len(indices) >= 4: + jerk = derivative_norms(predicted_hand, FPS, 3) * 1000.0 + append_finite( + output, "predicted_3d_joint_jerk_mm_per_s3", + jerk.mean(axis=-1), + ) + projected_jerk = derivative_norms(projected[indices, hand], FPS, 3) + append_finite( + output, "predicted_2d_joint_jerk_px_per_s3", + np.nanmean(projected_jerk, axis=-1), + ) + append_finite(output, "high_frequency_energy_ratio", [ + high_frequency_energy_ratio(predicted_hand, FPS, 6.0) + ]) + if len(indices) >= 3: + velocity = derivative_norms(predicted_hand, FPS, 1).mean(axis=-1) + append_finite(output, "velocity_variation_m_per_s", [ + np.std(velocity) + ]) + + # Report jumps at clip boundaries without allowing the filter to cross them. + for index in range(1, len(joints)): + if ( + frame_selected[index - 1] + and frame_selected[index] + and arrays["frame_valid"][index - 1] + and arrays["frame_valid"][index] + and arrays["frame_id"][index] == arrays["frame_id"][index - 1] + 1 + and arrays["clip_index"][index] != arrays["clip_index"][index - 1] + ): + jump = np.linalg.norm(joints[index] - joints[index - 1], axis=-1) * 1000.0 + append_finite( + output, "clip_boundary_discontinuity_mm", jump.mean(axis=-1), + ) + return output + + +def identity_switch_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + frame_selected: np.ndarray, +) -> dict[str, list[float]]: + wrong: list[bool | None] = [] + target = arrays["target_joints_camera"] + annotation = arrays["joint_annotation_valid"].astype(bool) + for index in range(len(joints)): + if not frame_selected[index] or not annotation[index].all(): + wrong.append(None) + continue + semantic = ( + np.linalg.norm(joints[index, 0] - target[index, 0], axis=-1).mean() + + np.linalg.norm(joints[index, 1] - target[index, 1], axis=-1).mean() + ) + swapped = ( + np.linalg.norm(joints[index, 0] - target[index, 1], axis=-1).mean() + + np.linalg.norm(joints[index, 1] - target[index, 0], axis=-1).mean() + ) + wrong.append(bool(swapped < semantic)) + switches = [] + for indices in selected_segments(arrays, frame_selected): + for previous, current in zip(indices[:-1], indices[1:], strict=True): + if wrong[previous] is not None and wrong[current] is not None: + switches.append(float(wrong[previous] != wrong[current])) + return {"identity_switch_fraction": switches} + + +def summarize_condition( + values: dict[str, list[float]], + condition: FilterCondition, + scope: str, +) -> list[dict[str, object]]: + return [ + { + "scope": scope, "condition": condition.name, + "family": condition.family, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + "metric": metric, **distribution_summary(observations), + } + for metric, observations in sorted(values.items()) + ] + + +def metric_lookup(rows: list[dict[str, object]], condition: str, metric: str) -> dict[str, object]: + matches = [ + row for row in rows + if row["condition"] == condition and row["metric"] == metric + ] + if len(matches) != 1: + raise ValueError(f"expected one jitter metric row for {condition}/{metric}") + return matches[0] + + +def build_overview( + metric_rows: list[dict[str, object]], conditions: list[FilterCondition], + scope: str, +) -> list[dict[str, object]]: + raw_name = "F0_raw" + keys = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "z_p95_mm": ("translation_z_mae_mm", "p95"), + "velocity_error_mm_per_s": ("joint_velocity_error_mm_per_s", "mean"), + "acceleration_error_mm_per_s2": ("joint_acceleration_error_mm_per_s2", "mean"), + "jitter_3d_acceleration_mm_per_s2": ( + "predicted_3d_joint_acceleration_mm_per_s2", "mean", + ), + "jitter_3d_jerk_mm_per_s3": ("predicted_3d_joint_jerk_mm_per_s3", "mean"), + "jitter_2d_acceleration_px_per_s2": ( + "predicted_2d_joint_acceleration_px_per_s2", "mean", + ), + "jitter_2d_jerk_px_per_s3": ("predicted_2d_joint_jerk_px_per_s3", "mean"), + "high_frequency_energy_ratio": ("high_frequency_energy_ratio", "mean"), + } + raw = { + name: float(metric_lookup(metric_rows, raw_name, metric)[statistic]) + for name, (metric, statistic) in keys.items() + } + output = [] + for condition in conditions: + values = { + name: float(metric_lookup(metric_rows, condition.name, metric)[statistic]) + for name, (metric, statistic) in keys.items() + } + row: dict[str, object] = { + "scope": scope, "condition": condition.name, + "family": condition.family, "filter_value": condition.value, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + } + for name, value in values.items(): + row[name] = value + row[f"{name}_delta"] = value - raw[name] + guardrails = [ + 100.0 * (values[name] - raw[name]) / raw[name] + for name in ( + "absolute_mpjpe_mm", "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", "z_p95_mm", + ) + ] + reductions = [ + (raw[name] - values[name]) / raw[name] + for name in ( + "jitter_3d_acceleration_mm_per_s2", + "jitter_3d_jerk_mm_per_s3", + "jitter_2d_acceleration_px_per_s2", + "jitter_2d_jerk_px_per_s3", + ) + ] + row["maximum_accuracy_degradation_percent"] = max(guardrails) + row["accuracy_guardrail_passed"] = bool(max(guardrails) <= 1.0) + row["jitter_reduction_score"] = float(np.mean(reductions)) + row["accuracy_delta"] = row["absolute_mpjpe_mm_delta"] + row["jitter_delta"] = row["jitter_3d_acceleration_mm_per_s2_delta"] + row["velocity_error_delta"] = row["velocity_error_mm_per_s_delta"] + row["acceleration_error_delta"] = row[ + "acceleration_error_mm_per_s2_delta" + ] + row["selected_for_full_validation"] = False + output.append(row) + return output + + +def paired_take_bootstrap_rows( + take_rows: list[dict[str, object]], + conditions: list[FilterCondition], + *, + samples: int, + seed: int = 20260716, +) -> list[dict[str, object]]: + if samples < 1: + raise ValueError("bootstrap samples must be positive") + index = { + (str(row["take"]), str(row["condition"]), str(row["metric"])): row + for row in take_rows + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(conditions): + if condition.family == "F0": + continue + for metric_index, metric in enumerate(metrics): + for statistic_name in ("mean", "p95"): + paired = [] + raw_values = [] + filtered_values = [] + for take in takes: + raw = index.get((take, "F0_raw", metric)) + filtered = index.get((take, condition.name, metric)) + if raw is None or filtered is None: + continue + raw_value = raw.get(statistic_name) + filtered_value = filtered.get(statistic_name) + if raw_value is None or filtered_value is None: + continue + raw_float = float(raw_value) + filtered_float = float(filtered_value) + if not np.isfinite(raw_float) or not np.isfinite(filtered_float): + continue + raw_values.append(raw_float) + filtered_values.append(filtered_float) + paired.append(filtered_float - raw_float) + deltas = np.asarray(paired, dtype=np.float64) + if not len(deltas): + continue + rng = np.random.default_rng(np.random.SeedSequence([ + seed, condition_index, metric_index, + 0 if statistic_name == "mean" else 1, + ])) + indices = rng.integers(0, len(deltas), size=(samples, len(deltas))) + bootstrap = deltas[indices].mean(axis=1) + output.append({ + "scope": take_rows[0]["scope"], + "condition": condition.name, + "family": condition.family, + "metric": metric, + "take_statistic": statistic_name, + "takes": len(deltas), + "raw": float(np.mean(raw_values)), + "filtered": float(np.mean(filtered_values)), + "filtered_minus_raw": float(deltas.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def choose_filter_conditions(overview: list[dict[str, object]]) -> dict[str, str | None]: + selected: dict[str, str | None] = {"F1": None, "F2": None} + for family in selected: + candidates = [ + row for row in overview + if row["family"] == family and row["accuracy_guardrail_passed"] + ] + if not candidates: + continue + candidates.sort(key=lambda row: ( + -float(row["jitter_reduction_score"]), + float(row["acceleration_error_mm_per_s2"]), + float(row["absolute_mpjpe_mm"]), + -float(row["filter_value"]), + )) + selected[family] = str(candidates[0]["condition"]) + candidates[0]["selected_for_full_validation"] = True + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument( + "--scope", choices=("smoke", "subset", "full"), required=True, + ) + parser.add_argument("--subset-manifest", type=Path) + parser.add_argument("--selection-json", type=Path) + parser.add_argument("--conditions") + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise ValueError("jitter output directory must be new or empty") + cache_manifest = json.loads( + (args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8") + ) + expected_cache_scope = "smoke" if args.scope == "smoke" else "full" + if ( + cache_manifest.get("status") != "complete" + or cache_manifest.get("official_test_used") is not False + or float(cache_manifest.get("fps")) != FPS + or cache_manifest.get("scope") != expected_cache_scope + or ( + expected_cache_scope == "full" + and (cache_manifest.get("clips") != 1495 or cache_manifest.get("frames") != 11638) + ) + ): + raise ValueError("invalid raw jitter cache manifest") + grid = condition_grid() + if args.conditions: + requested = [value.strip() for value in args.conditions.split(",") if value.strip()] + else: + requested = list(grid) + if not requested or set(requested) - set(grid) or "F0_raw" not in requested: + raise ValueError("jitter conditions must be registered and include F0_raw") + if args.scope == "subset": + if args.subset_manifest is None or args.selection_json is not None: + raise ValueError("subset scope requires only --subset-manifest") + subset = json.loads(args.subset_manifest.read_text(encoding="utf-8")) + selected_clip_indices = {int(value) for value in subset["clip_indices"]} + if ( + len(selected_clip_indices) != 256 + or subset.get("source_manifest_sha256") + != cache_manifest["manifest"]["sha256"] + or subset.get("official_test_used", False) is not False + ): + raise ValueError("jitter tuning subset must be the frozen 256 clips") + elif args.scope == "full": + if args.selection_json is None or args.subset_manifest is not None: + raise ValueError("full scope requires only --selection-json") + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + selected_names = { + value for value in selection["selected_conditions"].values() + if value is not None + } + if set(requested) != {"F0_raw", *selected_names}: + raise ValueError("full evaluation conditions differ from frozen subset selection") + selected_clip_indices = None + else: + if args.selection_json is not None or args.subset_manifest is not None: + raise ValueError("smoke scope does not accept selection/subset inputs") + selected_clip_indices = None + + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + conditions = [grid[name] for name in requested] + global_values: dict[str, dict[str, list[float]]] = { + condition.name: defaultdict(list) for condition in conditions + } + take_rows = [] + fallback_rows = [] + for take_record in cache_manifest["takes"]: + arrays = load_take(Path(take_record["path"])) + frame_selected = ( + np.ones(len(arrays["frame_id"]), dtype=bool) + if selected_clip_indices is None else + np.isin(arrays["clip_index"], list(selected_clip_indices)) + ) + if not frame_selected.any(): + continue + take = str(arrays["take"]) + for condition in conditions: + translation, rotations, fallbacks = filtered_parameters(arrays, condition) + vertices, joints = rebuild_geometry( + rotations, arrays["pred_shape"].astype(np.float32), + translation, mano, device, + ) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, rotations, translation, frame_selected, + ) + for metric, values in temporal_metrics( + arrays, joints, projected, frame_selected, + ).items(): + metrics[metric].extend(values) + for metric, values in identity_switch_metrics( + arrays, joints, frame_selected, + ).items(): + metrics[metric].extend(values) + for metric, observations in metrics.items(): + global_values[condition.name][metric].extend(observations) + summary = distribution_summary(observations) + take_rows.append({ + "scope": args.scope, "take": take, + "condition": condition.name, "family": condition.family, + "metric": metric, **summary, + }) + fallback_rows.append({ + "scope": args.scope, "take": take, + "condition": condition.name, + "fallback_segments": fallbacks, + }) + metric_rows = [] + for condition in conditions: + metric_rows.extend(summarize_condition( + global_values[condition.name], condition, args.scope, + )) + overview = build_overview(metric_rows, conditions, args.scope) + if args.scope == "full": + for row in overview: + row["selected_for_full_validation"] = row["family"] != "F0" + paired_rows = paired_take_bootstrap_rows( + take_rows, conditions, samples=args.bootstrap_samples, + ) + selection_payload = None + if args.scope == "subset": + selected = choose_filter_conditions(overview) + selection_payload = { + "status": "selected", + "official_test_used": False, + "selection_scope": "frozen_official_validation_subset_256", + "subset_manifest": str(args.subset_manifest.resolve()), + "checkpoint": cache_manifest["checkpoint"], + "selected_conditions": selected, + "rule": ( + "<=1% maximum accuracy degradation; maximize mean relative " + "3D/2D acceleration/jerk reduction; then acceleration error, " + "absolute MPJPE, weaker smoothing" + ), + } + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "jitter_selection.json").write_text( + json.dumps(selection_payload, indent=2) + "\n", encoding="utf-8", + ) + write_csv(args.output_dir / "jitter_condition_metrics.csv", metric_rows) + write_csv(args.output_dir / "jitter_take_metrics.csv", take_rows) + write_csv(args.output_dir / "jitter_filter_fallbacks.csv", fallback_rows) + write_csv(args.output_dir / "jitter_raw_vs_filtered.csv", overview) + if paired_rows: + write_csv( + args.output_dir / "jitter_paired_take_bootstrap_ci.csv", paired_rows, + ) + report = { + "status": "evaluated", + "official_test_used": False, + "result_role": ( + "engineering_smoke" if args.scope == "smoke" + else "filtered_inference_secondary_results" + ), + "raw_model_results_remain_primary": True, + "scope": args.scope, + "fps": FPS, + "cache_manifest": str((args.cache_dir / "cache_manifest.json").resolve()), + "conditions": requested, + "selection": selection_payload, + "outputs": { + "overview": "jitter_raw_vs_filtered.csv", + "metrics": "jitter_condition_metrics.csv", + "take_metrics": "jitter_take_metrics.csv", + "fallbacks": "jitter_filter_fallbacks.csv", + "paired_take_bootstrap_ci": ( + "jitter_paired_take_bootstrap_ci.csv" if paired_rows else None + ), + }, + } + (args.output_dir / "jitter_evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "scope": args.scope, + "conditions": requested, "selection": selection_payload, + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase5_causal_state.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1f9b2876ea7a730a657e4ef9d6b15250842bed --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase5_causal_state.py @@ -0,0 +1,554 @@ +#!/usr/bin/env python3 +"""Evaluate OOF-frozen causal wrist-z state estimators on official validation.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +import numpy as np + +from foundation_hand.evaluation.causal_state import ( + causal_constant_velocity_kalman, + measurement_uncertainty_multiplier, +) +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.temporal_filter import ( + apply_by_segment, + butterworth_zero_phase, + ema, + valid_segments, +) +try: + from scripts.evaluate_phase4_jitter import ( + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, + ) +except ModuleNotFoundError: # Direct `python scripts/...` execution. + from evaluate_phase4_jitter import ( # type: ignore[no-redef] + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, + ) + + +FPS = 30.0 + + +@dataclass(frozen=True) +class Condition: + name: str + family: str + causal_status: str + latency_frames: float | None + + +CONDITIONS = ( + Condition("coarse", "coarse", "causal", 0.0), + Condition("calibrated_per_frame", "calibrated", "causal", 0.0), + Condition("ema_alpha0.6", "ema", "causal_fixed_lag", (1.0 - 0.6) / 0.6), + Condition("butterworth_2hz", "butterworth", "offline_zero_phase", None), + Condition("fixed_kalman", "fixed_kalman", "causal_state", 0.0), + Condition("uncertainty_kalman", "uncertainty_kalman", "causal_state", 0.0), +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def uncertainty_base(prediction: dict[str, np.ndarray]) -> np.ndarray: + available = prediction["alignment_applied"].astype(bool) + base = measurement_uncertainty_multiplier( + prediction["confidence"], + prediction["inlier_ratio"], + prediction["residual_scale_m"], + prediction["valid_fraction"], + prediction["quality"], + 1.0, + ) + return np.where(available, base, 5.0) + + +def condition_z( + arrays: dict[str, np.ndarray], + prediction: dict[str, np.ndarray], + condition: Condition, + selection: dict[str, object], +) -> tuple[np.ndarray, np.ndarray, int]: + coarse = arrays["pred_wrist_translation"][..., 2].astype(np.float64) + available = prediction["alignment_applied"].astype(bool) + correction = np.where(available, prediction["calibrated_delta_z_m"], 0.0) + measurement = coarse + correction + variance = np.full_like(measurement, np.nan) + if condition.family == "coarse": + return coarse.copy(), variance, 0 + if condition.family == "calibrated": + return measurement, variance, 0 + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + if condition.family == "ema": + filtered, fallback = apply_by_segment( + measurement, segments, lambda values: ema(values, 0.6), minimum_frames=1, + ) + return filtered, variance, fallback + if condition.family == "butterworth": + filtered, fallback = apply_by_segment( + measurement, + segments, + lambda values: butterworth_zero_phase(values, 2.0, FPS, order=2), + minimum_frames=4, + ) + return filtered, variance, fallback + parameters = selection["selected"][condition.family] + multiplier = np.ones_like(measurement) + if condition.family == "uncertainty_kalman": + strength = float(parameters["uncertainty_strength"]) + base = uncertainty_base(prediction) + multiplier = 1.0 + strength * (base - 1.0) + measurement_available = np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), measurement.shape, + ) + filtered, variance = causal_constant_velocity_kalman( + measurement, + frame_id=arrays["frame_id"], + segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], + measurement_available=measurement_available, + process_sigma_m_per_frame2=float(parameters["process_sigma_m_per_frame2"]), + measurement_sigma_m=float(parameters["measurement_sigma_m"]), + uncertainty_multiplier=multiplier, + ) + return filtered, variance, 0 + + +def translated_geometry( + arrays: dict[str, np.ndarray], z_m: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + coarse_z = arrays["pred_wrist_translation"][..., 2] + delta = z_m - coarse_z + translation = arrays["pred_wrist_translation"].astype(np.float64).copy() + joints = arrays["pred_joints_camera"].astype(np.float64).copy() + vertices = arrays["pred_vertices_camera"].astype(np.float64).copy() + translation[..., 2] = z_m + joints[..., 2] += delta[..., None] + vertices[..., 2] += delta[..., None] + return translation, joints, vertices + + +def append_metrics( + destination: dict[str, list[float]], source: dict[str, Iterable[float]], +) -> None: + for metric, values in source.items(): + destination[metric].extend(float(value) for value in values if np.isfinite(value)) + + +def response_diagnostics( + arrays: dict[str, np.ndarray], z_m: np.ndarray, +) -> dict[str, list[float]]: + output: dict[str, list[float]] = defaultdict(list) + target = arrays["target_wrist_translation"][..., 2] + hand_valid = arrays["joint_annotation_valid"].astype(bool) + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + for indices in segments: + for hand in range(2): + selected = indices[hand_valid[indices, hand]] + if len(selected) < 3 or np.any(np.diff(selected) != 1): + continue + pred_velocity = np.diff(z_m[selected, hand]) + target_velocity = np.diff(target[selected, hand]) + step = np.abs(target_velocity) >= 0.005 + if step.any(): + output["step_same_frame_absolute_error_mm"].extend( + (np.abs(pred_velocity[step] - target_velocity[step]) * 1000.0).tolist() + ) + output["step_same_frame_gain"].extend( + (pred_velocity[step] / target_velocity[step]).tolist() + ) + correlations = [] + for lag in range(4): + pred = pred_velocity[lag:] + truth = target_velocity[: len(target_velocity) - lag or None] + if len(pred) < 3 or np.std(pred) < 1e-10 or np.std(truth) < 1e-10: + correlations.append(float("-inf")) + else: + correlations.append(float(np.corrcoef(pred, truth)[0, 1])) + if np.isfinite(correlations).any(): + output["estimated_causal_lag_frames"].append(float(np.argmax(correlations))) + if len(selected) >= 8: + error = np.abs(z_m[selected, hand] - target[selected, hand]) * 1000.0 + output["segment_endpoint_drift_delta_mm"].append(float(error[-1] - error[0])) + output["segment_length_frames"].append(float(len(selected))) + starts = np.concatenate([indices[:1] for indices in segments]) if segments else np.empty(0, dtype=int) + if len(starts): + calibrated = arrays["_calibrated_measurement_z_m"] + output["boundary_reset_difference_mm"].extend( + (np.abs(z_m[starts] - calibrated[starts]) * 1000.0).reshape(-1).tolist() + ) + return output + + +def missing_transition_diagnostics( + arrays: dict[str, np.ndarray], + prediction: dict[str, np.ndarray], + selection: dict[str, object], + family: str, +) -> dict[str, list[float]]: + parameters = selection["selected"][family] + coarse = arrays["pred_wrist_translation"][..., 2].astype(np.float64) + available = prediction["alignment_applied"].astype(bool) + full_measurement = coarse + np.where( + available, prediction["calibrated_delta_z_m"], 0.0, + ) + missing_measurement = full_measurement.copy() + multiplier = np.ones_like(full_measurement) + missing_mask = np.zeros_like(available) + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + for indices in segments: + if len(indices) >= 6: + missing_mask[indices[3:5]] = True + missing_measurement[missing_mask] = coarse[missing_mask] + if family == "uncertainty_kalman": + strength = float(parameters["uncertainty_strength"]) + base = uncertainty_base(prediction) + base[missing_mask] = 5.0 + multiplier = 1.0 + strength * (base - 1.0) + measurement_available = np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), full_measurement.shape, + ) + filtered, _ = causal_constant_velocity_kalman( + missing_measurement, + frame_id=arrays["frame_id"], segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], measurement_available=measurement_available, + process_sigma_m_per_frame2=float(parameters["process_sigma_m_per_frame2"]), + measurement_sigma_m=float(parameters["measurement_sigma_m"]), + uncertainty_multiplier=multiplier, + ) + target = arrays["target_wrist_translation"][..., 2] + hand_valid = arrays["joint_annotation_valid"].astype(bool) + output: dict[str, list[float]] = defaultdict(list) + selected = missing_mask & hand_valid + output["simulated_missing_span_z_mae_mm"].extend( + (np.abs(filtered - target)[selected] * 1000.0).tolist() + ) + for indices in segments: + if len(indices) < 6: + continue + recovery = indices[5] + valid = hand_valid[recovery] + output["first_recovery_frame_z_mae_mm"].extend( + (np.abs(filtered[recovery] - target[recovery])[valid] * 1000.0).tolist() + ) + return output + + +def paired_bootstrap( + take_rows: list[dict[str, object]], *, samples: int, seed: int = 20260716, +) -> list[dict[str, object]]: + index = { + (str(row["take"]), str(row["condition"]), str(row["metric"]), statistic): + float(row[statistic]) + for row in take_rows + for statistic in ("mean", "p95") + if row.get(statistic) is not None and np.isfinite(float(row[statistic])) + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(CONDITIONS): + if condition.name == "calibrated_per_frame": + continue + for metric_index, metric in enumerate(metrics): + for statistic_index, statistic in enumerate(("mean", "p95")): + pairs = [ + ( + index[(take, condition.name, metric, statistic)], + index[(take, "calibrated_per_frame", metric, statistic)], + ) + for take in takes + if (take, condition.name, metric, statistic) in index + and (take, "calibrated_per_frame", metric, statistic) in index + ] + if not pairs: + continue + delta = np.asarray([filtered - raw for filtered, raw in pairs]) + rng = np.random.default_rng(np.random.SeedSequence( + (seed, condition_index, metric_index, statistic_index), + )) + bootstrap = delta[ + rng.integers(0, len(delta), size=(samples, len(delta))) + ].mean(axis=1) + output.append({ + "reference": "calibrated_per_frame", "condition": condition.name, + "metric": metric, "take_statistic": statistic, "takes": len(delta), + "condition_minus_reference": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def build_overview(metric_rows: list[dict[str, object]]) -> list[dict[str, object]]: + index = { + (str(row["condition"]), str(row["metric"])): row for row in metric_rows + } + fields = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "z_mae_mm": ("translation_z_mae_mm", "mean"), + "z_p95_mm": ("translation_z_mae_mm", "p95"), + "velocity_error_mm_per_s": ("joint_velocity_error_mm_per_s", "mean"), + "acceleration_error_mm_per_s2": ("joint_acceleration_error_mm_per_s2", "mean"), + "predicted_acceleration_mm_per_s2": ( + "predicted_3d_joint_acceleration_mm_per_s2", "mean", + ), + "predicted_jerk_mm_per_s3": ("predicted_3d_joint_jerk_mm_per_s3", "mean"), + "high_frequency_energy_ratio": ("high_frequency_energy_ratio", "mean"), + "estimated_causal_lag_frames": ("estimated_causal_lag_frames", "mean"), + } + reference = { + name: float(index[("calibrated_per_frame", metric)][statistic]) + for name, (metric, statistic) in fields.items() + } + output = [] + for condition in CONDITIONS: + values = { + name: float(index[(condition.name, metric)][statistic]) + for name, (metric, statistic) in fields.items() + } + row: dict[str, object] = { + "reference": "calibrated_per_frame", "condition": condition.name, + "family": condition.family, "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + } + for name, value in values.items(): + row[name] = value + row[f"{name}_delta"] = value - reference[name] + row["accuracy_delta"] = row["absolute_mpjpe_mm_delta"] + row["jitter_delta"] = row["predicted_acceleration_mm_per_s2_delta"] + row["velocity_error_delta"] = row["velocity_error_mm_per_s_delta"] + row["acceleration_error_delta"] = row["acceleration_error_mm_per_s2_delta"] + row["static_guardrail_passed"] = bool( + float(row["absolute_mpjpe_mm_delta"]) <= 0.2 + and float(row["z_mae_mm_delta"]) <= 0.2 + and float(row["z_p95_mm_delta"]) <= 0.2 + ) + row["retained_causal_candidate"] = bool( + condition.name == "uncertainty_kalman" + and row["static_guardrail_passed"] + and float(row["jitter_delta"]) < 0.0 + and float(row["velocity_error_delta"]) < 0.0 + and float(row["acceleration_error_delta"]) < 0.0 + ) + output.append(row) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-evaluation-dir", type=Path, required=True) + parser.add_argument("--selection-json", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument( + "--continuous-take-state", + action="store_true", + help="Keep state across model inference windows until a take/frame discontinuity.", + ) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("causal-state output directory must be new or empty") + cache_manifest_path = args.cache_dir / "cache_manifest.json" + alignment_report_path = args.alignment_evaluation_dir / "evaluation.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + alignment_report = json.loads(alignment_report_path.read_text(encoding="utf-8")) + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + or cache.get("frames") != 11638 + or float(cache.get("fps")) != FPS + ): + raise ValueError("invalid complete official-validation cache contract") + if ( + alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + or alignment_report.get("coarse_checkpoint", {}).get("sha256") + != cache.get("checkpoint", {}).get("sha256") + ): + raise ValueError("alignment evaluation does not match the raw cache") + if ( + selection.get("status") != "selected" + or selection.get("official_validation_used") is not False + or selection.get("official_test_used") is not False + or "coarse z is always" not in selection.get("measurement_contract", "") + ): + raise ValueError("causal-state parameters are not valid train-OOF selections") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + global_values = {condition.name: defaultdict(list) for condition in CONDITIONS} + take_rows = [] + response_rows = [] + missing_values = { + family: defaultdict(list) for family in ("fixed_kalman", "uncertainty_kalman") + } + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw-cache take hash mismatch: {take_path}") + arrays = load_npz(take_path) + if args.continuous_take_state: + arrays["clip_index"] = np.zeros_like(arrays["clip_index"]) + stem = "__".join(Path(str(arrays["take"])).parts) + prediction_path = args.alignment_evaluation_dir / "predictions" / f"{stem}.npz" + prediction = load_npz(prediction_path) + if not np.array_equal(arrays["frame_id"], prediction["frame_id"]): + raise ValueError(f"alignment frame mismatch: {arrays['take']}") + calibrated_measurement = arrays["pred_wrist_translation"][..., 2] + np.where( + prediction["alignment_applied"], prediction["calibrated_delta_z_m"], 0.0, + ) + arrays["_calibrated_measurement_z_m"] = calibrated_measurement + saved: dict[str, np.ndarray] = {"frame_id": arrays["frame_id"]} + for condition in CONDITIONS: + z_m, variance, fallbacks = condition_z(arrays, prediction, condition, selection) + translation, joints, vertices = translated_geometry(arrays, z_m) + selected = arrays["frame_valid"].astype(bool) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, arrays["pred_rotation_matrices"], translation, selected, + ) + append_metrics(metrics, temporal_metrics(arrays, joints, projected, selected)) + append_metrics(metrics, identity_switch_metrics(arrays, joints, selected)) + response = response_diagnostics(arrays, z_m) + append_metrics(metrics, response) + for metric, observations in metrics.items(): + global_values[condition.name][metric].extend(observations) + take_rows.append({ + "take": str(arrays["take"]), "condition": condition.name, + "family": condition.family, "metric": metric, + **distribution_summary(observations), + }) + for metric, observations in response.items(): + response_rows.append({ + "take": str(arrays["take"]), "condition": condition.name, + "metric": metric, **distribution_summary(observations), + }) + saved[f"{condition.name}_z_m"] = z_m + saved[f"{condition.name}_variance_m2"] = variance + saved[f"{condition.name}_fallback_segments"] = np.asarray(fallbacks) + for family in missing_values: + append_metrics( + missing_values[family], + missing_transition_diagnostics(arrays, prediction, selection, family), + ) + np.savez_compressed(prediction_root / f"{stem}.npz", **saved) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + metric_rows = [] + for condition in CONDITIONS: + for metric, observations in sorted(global_values[condition.name].items()): + metric_rows.append({ + "condition": condition.name, "family": condition.family, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, "metric": metric, + **distribution_summary(observations), + }) + missing_rows = [ + {"condition": family, "metric": metric, **distribution_summary(observations)} + for family, values in missing_values.items() + for metric, observations in sorted(values.items()) + ] + bootstrap_rows = paired_bootstrap( + take_rows, samples=args.bootstrap_samples, + ) + overview_rows = build_overview(metric_rows) + write_csv(args.output_dir / "metrics.csv", metric_rows) + write_csv(args.output_dir / "overview.csv", overview_rows) + write_csv(args.output_dir / "take_metrics.csv", take_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap_rows) + write_csv(args.output_dir / "response_diagnostics.csv", response_rows) + write_csv(args.output_dir / "missing_modality_transition.csv", missing_rows) + report = { + "status": "evaluated", + "experiment_class": "preregistered_confirmatory_causal_state", + "result_role": "deployable_causal_translation_z_state_ablation", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "alignment_evaluation": {"path": str(alignment_report_path.resolve()), "sha256": sha256(alignment_report_path)}, + "selection": {"path": str(args.selection_json.resolve()), "sha256": sha256(args.selection_json)}, + "checkpoint": cache["checkpoint"], + "conditions": [condition.__dict__ for condition in CONDITIONS], + "state_scope": "translation z only; pose/shape and translation x/y unchanged", + "measurement_contract": selection["measurement_contract"], + "boundary_contract": ( + "reset at invalid frame, frame discontinuity, and take boundary" + if args.continuous_take_state else + "reset at invalid frame, frame discontinuity, and frozen model clip boundary; never cross take" + ), + "continuous_take_state": args.continuous_take_state, + "long_sequence_limitation": ( + None if args.continuous_take_state else + "the inherited no-cross-clip rule limits a continuous state segment to the cache clip length" + ), + "missing_modality_diagnostic": "simulated local-alignment loss uses exact coarse-z fallback with high uncertainty; the unified coarse model's missing Depth/K static fallback was audited in Stage 3", + "outputs": { + "metrics": "metrics.csv", "take_metrics": "take_metrics.csv", + "overview": "overview.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "response": "response_diagnostics.csv", + "missing_transition": "missing_modality_transition.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "evaluated", "frames": cache["frames"], + "conditions": [condition.name for condition in CONDITIONS], + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase5_metric_alignment.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase5_metric_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f686d340bef0e1a05bb1555d8d89dcd10f1938 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase5_metric_alignment.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +"""Evaluate deployable predicted-location wrist-z alignment on frozen raw caches.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import cv2 +import joblib +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.alignment_calibration import ( + FEATURE_NAMES, + features_from_take, + projected_hand_scale_px, +) +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + + +FINGERTIPS = (4, 8, 12, 16, 20) +CALIBRATED_CONDITIONS = ( + "coarse", + "robust_alignment_unscaled", + "calibrated_always", + "calibrated_confidence", + "missing_depth_fallback", + "missing_k_fallback", +) +RAW_CONDITIONS = ("coarse", "robust_alignment_unscaled") +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + first_fields = list(rows[0]) + extra_fields = sorted({key for row in rows for key in row} - set(first_fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=first_fields + extra_fields, lineterminator="\n", + ) + writer.writeheader() + writer.writerows(rows) + + +def _velocity(translation: np.ndarray, frame_ids: np.ndarray) -> np.ndarray: + output = np.zeros_like(translation, dtype=np.float32) + contiguous = frame_ids[1:] == frame_ids[:-1] + 1 + output[1:][contiguous] = translation[1:][contiguous] - translation[:-1][contiguous] + return output + + +def alignment_arrays( + arrays: dict[str, np.ndarray], data_root: Path, +) -> dict[str, np.ndarray]: + take = str(arrays["take"]) + take_dir = data_root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + time = len(arrays["frame_id"]) + diagnostics: dict[str, list[np.ndarray]] = defaultdict(list) + overlap = [] + predicted_depth_order = [] + for time_index, frame_id in enumerate(arrays["frame_id"]): + depth_mm = cv2.imread( + str(take_dir / "depth" / f"{int(frame_id):06d}.png"), cv2.IMREAD_UNCHANGED, + ) + if depth_mm is None or depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{int(frame_id):06d}") + depth_m, depth_valid = depth_mm_to_m(depth_mm) + masks = [] + predicted_surface_medians = [] + for hand in range(2): + result, samples = align_wrist_z( + arrays["pred_vertices_camera"][time_index, hand], + K_raw, depth_m, depth_valid, + ) + if samples is None: + raise AssertionError("complete-modality evaluation has no depth samples") + for field, value in result.as_dict().items(): + diagnostics[f"alignment_{field}"].append(np.asarray(value)) + masks.append(np.unpackbits( + samples.silhouette_packed, bitorder="little", + count=samples.silhouette_hw[0] * samples.silhouette_hw[1], + ).astype(bool)) + predicted_surface_medians.append(float(np.median( + samples.predicted_depth_m[samples.visible_vertex], + ))) + intersection = np.logical_and(masks[0], masks[1]).sum() + union = np.logical_or(masks[0], masks[1]).sum() + overlap.append(intersection / max(union, 1)) + predicted_depth_order.append(np.sign( + predicted_surface_medians[1] - predicted_surface_medians[0] + )) + values = { + key: np.stack(items).reshape(time, 2) + for key, items in diagnostics.items() + } + pred_joints_raw, _ = project_points(arrays["pred_joints_camera"], K_raw) + resized_hw = arrays["K"].shape # Cache K is already aligned to model image. + del resized_hw + # Recover resized dimensions from principal-point scaling used by the 640x368 cache. + width, height = 640.0, 368.0 + raw_to_resized = np.asarray((width / raw_hw[1], height / raw_hw[0]), dtype=np.float32) + mano_resized = pred_joints_raw * raw_to_resized + values.update({ + "frame_id": arrays["frame_id"], + "pred_wrist_translation": arrays["pred_wrist_translation"], + "coarse_hand_scale_px": projected_hand_scale_px( + pred_joints_raw, source_hw=raw_hw, target_hw=(int(height), int(width)), + ), + "coarse_direct_mano_consistency_px": np.linalg.norm( + arrays["pred_direct_2d_px"] - mano_resized, axis=-1, + ).mean(axis=-1), + "silhouette_overlap_fraction": np.asarray(overlap, dtype=np.float32), + "predicted_depth_order": np.asarray(predicted_depth_order, dtype=np.int8), + "coarse_wrist_velocity_m_per_frame": _velocity( + arrays["pred_wrist_translation"], arrays["frame_id"], + ), + }) + return values + + +def correction_grid( + geometry: dict[str, np.ndarray], package: dict[str, object], +) -> tuple[dict[str, np.ndarray], np.ndarray, np.ndarray]: + features = features_from_take(geometry) + flat = features.reshape(-1, features.shape[-1]) + calibrated = np.clip(package["regressor"].predict(flat), -0.12, 0.12).reshape(features.shape[:2]) + confidence = package["confidence"].predict_proba(flat)[:, 1].reshape(features.shape[:2]) + available = geometry["alignment_applied"].astype(bool) + threshold = float(package["confidence_threshold"]) + raw = np.where(available, geometry["alignment_delta_z_m"], 0.0) + calibrated_available = np.where(available, calibrated, 0.0) + gated = np.where(available & (confidence >= threshold), calibrated, 0.0) + zero = np.zeros_like(raw) + return { + "coarse": zero, + "robust_alignment_unscaled": raw, + "calibrated_always": calibrated_available, + "calibrated_confidence": gated, + "missing_depth_fallback": zero, + "missing_k_fallback": zero, + }, calibrated, confidence + + +def hand_size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def take_rows( + arrays: dict[str, np.ndarray], + geometry: dict[str, np.ndarray], + corrections: dict[str, np.ndarray], + calibrated: np.ndarray, + confidence: np.ndarray, +) -> tuple[list[dict[str, object]], list[dict[str, object]]]: + frame_rows = [] + temporal_rows = [] + take = str(arrays["take"]) + for condition, correction in corrections.items(): + joints = arrays["pred_joints_camera"].astype(np.float64).copy() + vertices = arrays["pred_vertices_camera"].astype(np.float64).copy() + translation = arrays["pred_wrist_translation"].astype(np.float64).copy() + joints[..., 2] += correction[..., None] + vertices[..., 2] += correction[..., None] + translation[..., 2] += correction + projected, _ = project_points(joints, arrays["K"]) + frame_valid = arrays["frame_valid"].astype(bool) + valid = arrays["mano_annotation_valid"].astype(bool) & frame_valid[:, None] + for time_index, hand in zip(*np.where(valid), strict=True): + target_joints = arrays["target_joints_camera"][time_index, hand] + target_vertices = arrays["target_vertices_camera"][time_index, hand] + pred_joints = joints[time_index, hand] + pred_vertices = vertices[time_index, hand] + joint_error = np.linalg.norm(pred_joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(pred_vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (pred_joints - pred_joints[:1]) - (target_joints - target_joints[:1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (pred_vertices - pred_joints[:1]) - (target_vertices - target_joints[:1]), axis=-1, + ) * 1000.0 + z_signed = 1000.0 * ( + translation[time_index, hand, 2] + - arrays["target_wrist_translation"][time_index, hand, 2] + ) + translation_signed = 1000.0 * ( + translation[time_index, hand] + - arrays["target_wrist_translation"][time_index, hand] + ) + target_2d = arrays["target_2d_px"][time_index, hand] + direct_2d = arrays["pred_direct_2d_px"][time_index, hand] + scale = float(geometry["coarse_hand_scale_px"][time_index, hand]) + target_depth = float(arrays["target_wrist_translation"][time_index, hand, 2]) + frame_rows.append({ + "condition": condition, + "take": take, + "subject": take.split("/")[0], + "action_family": take.split("/")[1], + "frame_id": int(arrays["frame_id"][time_index]), + "side": "right" if hand else "left", + "hand_size_bucket": hand_size_bucket(scale), + "depth_bucket": depth_bucket(target_depth), + "absolute_mpjpe_mm": float(joint_error.mean()), + "root_relative_mpjpe_mm": float(root_joint_error.mean()), + "absolute_mpvpe_mm": float(vertex_error.mean()), + "root_relative_mpvpe_mm": float(root_vertex_error.mean()), + "fingertip_mpjpe_mm": float(joint_error[list(FINGERTIPS)].mean()), + "translation_x_mae_mm": abs(float(translation_signed[0])), + "translation_y_mae_mm": abs(float(translation_signed[1])), + "translation_z_mae_mm": abs(float(z_signed)), + "translation_x_signed_error_mm": float(translation_signed[0]), + "translation_y_signed_error_mm": float(translation_signed[1]), + "translation_z_signed_error_mm": float(z_signed), + "direct_2d_error_px": float(np.linalg.norm(direct_2d - target_2d, axis=-1).mean()), + "mano_projected_2d_error_px": float(np.linalg.norm(projected[time_index, hand] - target_2d, axis=-1).mean()), + "direct_mano_2d_consistency_px": float( + np.linalg.norm(direct_2d - projected[time_index, hand], axis=-1).mean() + ), + "raw_alignment_delta_z_mm": 1000.0 * float(geometry["alignment_delta_z_m"][time_index, hand]), + "calibrated_delta_z_mm": 1000.0 * float(calibrated[time_index, hand]), + "applied_delta_z_mm": 1000.0 * float(correction[time_index, hand]), + "alignment_confidence": float(confidence[time_index, hand]), + "alignment_support": int(geometry["alignment_valid_support_count"][time_index, hand]), + "alignment_quality": float(geometry["alignment_conditioning_quality"][time_index, hand]), + }) + + contiguous = arrays["frame_id"][1:] == arrays["frame_id"][:-1] + 1 + for hand in range(2): + transition_valid = contiguous & valid[1:, hand] & valid[:-1, hand] + indices = np.where(transition_valid)[0] + pred_velocity = joints[1:, hand] - joints[:-1, hand] + target_velocity = arrays["target_joints_camera"][1:, hand] - arrays["target_joints_camera"][:-1, hand] + for index in indices: + temporal_rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][index + 1]), + "side": "right" if hand else "left", + "joint_velocity_error_mm_per_frame": float( + np.linalg.norm(pred_velocity[index] - target_velocity[index], axis=-1).mean() * 1000.0 + ), + }) + acceleration_valid = transition_valid[1:] & transition_valid[:-1] + acceleration_indices = np.where(acceleration_valid)[0] + pred_acceleration = pred_velocity[1:] - pred_velocity[:-1] + target_acceleration = target_velocity[1:] - target_velocity[:-1] + for index in acceleration_indices: + temporal_rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][index + 2]), + "side": "right" if hand else "left", + "joint_acceleration_error_mm_per_frame2": float( + np.linalg.norm(pred_acceleration[index] - target_acceleration[index], axis=-1).mean() * 1000.0 + ), + "predicted_joint_acceleration_mm_per_frame2": float( + np.linalg.norm(pred_acceleration[index], axis=-1).mean() * 1000.0 + ), + }) + both_valid = valid.all(axis=1) + wrong_side: list[bool | None] = [] + for time_index in range(len(valid)): + if not both_valid[time_index]: + wrong_side.append(None) + continue + correct = 0.5 * ( + np.linalg.norm( + joints[time_index, 0] - arrays["target_joints_camera"][time_index, 0], + axis=-1, + ).mean() + + np.linalg.norm( + joints[time_index, 1] - arrays["target_joints_camera"][time_index, 1], + axis=-1, + ).mean() + ) + swapped = 0.5 * ( + np.linalg.norm( + joints[time_index, 0] - arrays["target_joints_camera"][time_index, 1], + axis=-1, + ).mean() + + np.linalg.norm( + joints[time_index, 1] - arrays["target_joints_camera"][time_index, 0], + axis=-1, + ).mean() + ) + wrong_side.append(bool(swapped < correct)) + for index, (previous, current) in enumerate( + zip(wrong_side[:-1], wrong_side[1:], strict=True) + ): + if contiguous[index] and previous is not None and current is not None: + temporal_rows.append({ + "condition": condition, + "take": take, + "frame_id": int(arrays["frame_id"][index + 1]), + "side": "bimanual", + "identity_switch_fraction": float(previous != current), + }) + return frame_rows, temporal_rows + + +def aggregate_rows( + frame_rows: list[dict[str, object]], + temporal_rows: list[dict[str, object]], + conditions: tuple[str, ...] = CALIBRATED_CONDITIONS, +) -> list[dict[str, object]]: + output = [] + for condition in conditions: + selected = [row for row in frame_rows if row["condition"] == condition] + for metric in METRICS: + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row[metric] for row in selected), + }) + temporal_selected = [row for row in temporal_rows if row["condition"] == condition] + for metric in ( + "joint_velocity_error_mm_per_frame", + "joint_acceleration_error_mm_per_frame2", + "predicted_joint_acceleration_mm_per_frame2", + "identity_switch_fraction", + ): + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row.get(metric) for row in temporal_selected), + }) + for group in ("side", "hand_size_bucket", "depth_bucket", "take", "action_family"): + values = sorted({str(row[group]) for row in selected}) + for value in values: + grouped = [row for row in selected if str(row[group]) == value] + for metric in METRICS: + output.append({ + "condition": condition, "group": group, "value": value, "metric": metric, + **distribution_summary(row[metric] for row in grouped), + }) + return output + + +def paired_take_bootstrap( + frame_rows: list[dict[str, object]], + *, + conditions: tuple[str, ...] = CALIBRATED_CONDITIONS, + samples: int = 10_000, + seed: int = 20260716, +) -> list[dict[str, object]]: + take_means: dict[tuple[str, str, str], float] = {} + takes = sorted({str(row["take"]) for row in frame_rows}) + for condition in conditions: + for take in takes: + rows = [row for row in frame_rows if row["condition"] == condition and row["take"] == take] + for metric in METRICS: + take_means[(condition, take, metric)] = float(np.mean([float(row[metric]) for row in rows])) + output = [] + rng = np.random.default_rng(seed) + for condition in conditions[1:]: + for metric in METRICS: + delta = np.asarray([ + take_means[(condition, take, metric)] - take_means[("coarse", take, metric)] + for take in takes + ]) + indices = rng.integers(0, len(delta), size=(samples, len(delta))) + boot = delta[indices].mean(axis=1) + output.append({ + "condition": condition, "metric": metric, "takes": len(takes), + "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--calibrator", type=Path) + parser.add_argument("--calibration-json", type=Path) + parser.add_argument("--raw-only", action="store_true") + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("metric-alignment output directory must be new or empty") + cache = json.loads((args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + ): + raise ValueError("official-validation cache contract is invalid") + if args.raw_only: + if args.calibrator is not None or args.calibration_json is not None: + parser.error("--raw-only cannot accept calibrator inputs") + calibration = None + package = None + conditions = RAW_CONDITIONS + else: + if args.calibrator is None or args.calibration_json is None: + parser.error("calibrated evaluation requires --calibrator and --calibration-json") + calibration = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration.get("status") != "fitted" + or calibration.get("official_validation_used") is not False + or calibration.get("official_test_used") is not False + or calibration.get("model", {}).get("sha256") != sha256(args.calibrator) + ): + raise ValueError("OOF calibration contract is invalid") + package = joblib.load(args.calibrator) + if tuple(package["feature_names"]) != FEATURE_NAMES: + raise ValueError("calibrator feature schema mismatch") + conditions = CALIBRATED_CONDITIONS + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + all_frame_rows = [] + all_temporal_rows = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw-cache take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + geometry = alignment_arrays(arrays, args.data_root) + if args.raw_only: + zero = np.zeros_like(geometry["alignment_delta_z_m"]) + available = geometry["alignment_applied"].astype(bool) + corrections = { + "coarse": zero, + "robust_alignment_unscaled": np.where( + available, geometry["alignment_delta_z_m"], 0.0, + ), + } + calibrated, confidence = zero, zero + else: + corrections, calibrated, confidence = correction_grid(geometry, package) + frame_rows, temporal_rows = take_rows( + arrays, geometry, corrections, calibrated, confidence, + ) + all_frame_rows.extend(frame_rows) + all_temporal_rows.extend(temporal_rows) + np.savez_compressed( + prediction_root / f"{'__'.join(Path(str(arrays['take'])).parts)}.npz", + frame_id=arrays["frame_id"], + raw_alignment_delta_z_m=geometry["alignment_delta_z_m"], + calibrated_delta_z_m=calibrated, + confidence=confidence, + gated_delta_z_m=( + zero if args.raw_only else corrections["calibrated_confidence"] + ), + support=geometry["alignment_valid_support_count"], + projected_support=geometry["alignment_projected_support_count"], + quality=geometry["alignment_conditioning_quality"], + alignment_applied=geometry["alignment_applied"], + inlier_ratio=geometry["alignment_inlier_ratio"], + residual_scale_m=geometry["alignment_residual_scale_m"], + valid_fraction=geometry["alignment_valid_fraction"], + foreground_fraction=geometry["alignment_foreground_fraction"], + background_fraction=geometry["alignment_background_fraction"], + depth_discontinuity_m=geometry["alignment_depth_discontinuity_m"], + silhouette_overlap_fraction=geometry["silhouette_overlap_fraction"], + coarse_hand_scale_px=geometry["coarse_hand_scale_px"], + coarse_direct_mano_consistency_px=geometry[ + "coarse_direct_mano_consistency_px" + ], + coarse_wrist_velocity_m_per_frame=geometry[ + "coarse_wrist_velocity_m_per_frame" + ], + predicted_depth_order=geometry["predicted_depth_order"], + ) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + aggregate = aggregate_rows(all_frame_rows, all_temporal_rows, conditions) + paired = paired_take_bootstrap(all_frame_rows, conditions=conditions) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_frame_rows) + write_csv(args.output_dir / "per_temporal_metrics.csv", all_temporal_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + missing_fallback_exact = None if args.raw_only else all( + next(row for row in aggregate if row["condition"] == condition and row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm")["mean"] + == next(row for row in aggregate if row["condition"] == "coarse" and row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm")["mean"] + for condition in ("missing_depth_fallback", "missing_k_fallback") + ) + report = { + "status": "evaluated", + "experiment_class": "ablation" if args.raw_only else "deployable_ablation", + "result_role": ( + "fixed_raw_predicted_location_alignment_without_learned_confidence" + if args.raw_only else "deployable_predicted_location_metric_alignment" + ), + "official_validation_used": True, + "official_validation_used_for_model_or_threshold_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str((args.cache_dir / "cache_manifest.json").resolve()), "sha256": sha256(args.cache_dir / "cache_manifest.json")}, + "coarse_checkpoint": cache["checkpoint"], + "calibration": ( + None if args.raw_only else + {"path": str(args.calibration_json.resolve()), "sha256": sha256(args.calibration_json)} + ), + "calibrator": ( + None if args.raw_only else + {"path": str(args.calibrator.resolve()), "sha256": sha256(args.calibrator)} + ), + "conditions": list(conditions), + "confidence_threshold": None if args.raw_only else float(package["confidence_threshold"]), + "location": "coarse predicted MANO projection; no GT location/bbox/crop", + "correction": "translation z only; pose/shape and coarse outputs retained", + "solver": { + "loss": "MAD-scaled Huber IRLS", + "minimum_support": 20, + "maximum_raw_residual_m": 0.15, + "maximum_delta_m": 0.12, + "surface_location": "frontmost predicted MANO vertices at coarse projection", + }, + "missing_depth_k_fallback_exact": missing_fallback_exact, + "missing_rgb_status": "not_supported_by_frozen_coarse_cache; no claim", + "added_temporal_latency_frames": 0, + "outputs": { + "per_hand": "per_hand_frame_metrics.csv", + "per_temporal": "per_temporal_metrics.csv", + "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "frames": cache["frames"], + "missing_fallback_exact": missing_fallback_exact, "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase5_missing_modality.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase5_missing_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0ac6c2f8b9d554603ecc696a9392e1f97bb9bf --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase5_missing_modality.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Evaluate true missing-Depth/K coarse-model caches against complete input.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import project_points +try: + from scripts.evaluate_phase4_jitter import identity_switch_metrics, temporal_metrics +except ModuleNotFoundError: # Direct `python scripts/...` execution. + from evaluate_phase4_jitter import identity_switch_metrics, temporal_metrics # type: ignore[no-redef] + + +CONDITIONS = ("complete", "missing_depth", "missing_k") +FINGERTIPS = (4, 8, 12, 16, 20) +STATIC_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "translation_x_signed_error_mm", "translation_y_signed_error_mm", + "translation_z_signed_error_mm", "direct_2d_error_px", + "mano_projected_2d_error_px", "direct_mano_2d_consistency_px", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def frame_rows(arrays: dict[str, np.ndarray], condition: str) -> list[dict[str, Any]]: + rows = [] + take = str(arrays["take"]) + projected, _ = project_points(arrays["pred_joints_camera"], arrays["K"][:, None]) + valid = arrays["frame_valid"].astype(bool)[:, None] & arrays["mano_annotation_valid"].astype(bool) + for time_index, hand in zip(*np.where(valid), strict=True): + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + vertices = arrays["pred_vertices_camera"][time_index, hand].astype(np.float64) + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_vertices = arrays["target_vertices_camera"][time_index, hand].astype(np.float64) + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (joints - joints[:1]) - (target_joints - target_joints[:1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (vertices - joints[:1]) - (target_vertices - target_joints[:1]), axis=-1, + ) * 1000.0 + translation_signed = 1000.0 * ( + arrays["pred_wrist_translation"][time_index, hand] + - arrays["target_wrist_translation"][time_index, hand] + ) + direct = arrays["pred_direct_2d_px"][time_index, hand] + target_2d = arrays["target_2d_px"][time_index, hand] + target_scale = float(np.max(np.ptp(target_2d, axis=0))) + rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][time_index]), + "side": "right" if hand else "left", + "hand_size_bucket": size_bucket(target_scale), + "wrist_depth_bucket": depth_bucket(float(arrays["target_wrist_translation"][time_index, hand, 2])), + "absolute_mpjpe_mm": float(joint_error.mean()), + "root_relative_mpjpe_mm": float(root_joint_error.mean()), + "absolute_mpvpe_mm": float(vertex_error.mean()), + "root_relative_mpvpe_mm": float(root_vertex_error.mean()), + "fingertip_mpjpe_mm": float(joint_error[list(FINGERTIPS)].mean()), + "translation_x_mae_mm": abs(float(translation_signed[0])), + "translation_y_mae_mm": abs(float(translation_signed[1])), + "translation_z_mae_mm": abs(float(translation_signed[2])), + "translation_x_signed_error_mm": float(translation_signed[0]), + "translation_y_signed_error_mm": float(translation_signed[1]), + "translation_z_signed_error_mm": float(translation_signed[2]), + "direct_2d_error_px": float(np.linalg.norm(direct - target_2d, axis=-1).mean()), + "mano_projected_2d_error_px": float( + np.linalg.norm(projected[time_index, hand] - target_2d, axis=-1).mean() + ), + "direct_mano_2d_consistency_px": float( + np.linalg.norm(direct - projected[time_index, hand], axis=-1).mean() + ), + }) + return rows + + +def matched_cache_arrays( + reference: dict[str, np.ndarray], candidate: dict[str, np.ndarray], +) -> bool: + keys = ( + "frame_id", "frame_valid", "K", "target_rotation_matrices", "target_shape", + "target_wrist_translation", "target_joints_camera", "target_vertices_camera", + "target_2d_px", "joint_annotation_valid", "joint_element_valid", + "mano_annotation_valid", + ) + return all(np.array_equal(reference[key], candidate[key], equal_nan=True) for key in keys) + + +def aggregate_static(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + output = [] + group_fields: dict[str, str | None] = { + "all": None, "side": "side", "hand_size": "hand_size_bucket", + "wrist_depth": "wrist_depth_bucket", + } + for condition in CONDITIONS: + condition_rows = [row for row in rows if row["condition"] == condition] + for group, field in group_fields.items(): + values = ["all"] if field is None else sorted({str(row[field]) for row in condition_rows}) + for value in values: + selected = condition_rows if field is None else [ + row for row in condition_rows if str(row[field]) == value + ] + for metric in STATIC_METRICS: + output.append({ + "condition": condition, "group": group, "value": value, + "metric": metric, + **distribution_summary([float(row[metric]) for row in selected]), + }) + return output + + +def take_metric_rows( + static_rows: list[dict[str, Any]], dynamic: dict[tuple[str, str], dict[str, list[float]]], +) -> list[dict[str, Any]]: + output = [] + takes = sorted({str(row["take"]) for row in static_rows}) + for condition in CONDITIONS: + for take in takes: + selected = [ + row for row in static_rows + if row["condition"] == condition and row["take"] == take + ] + for metric in STATIC_METRICS: + output.append({ + "condition": condition, "take": take, "metric": metric, + **distribution_summary([float(row[metric]) for row in selected]), + }) + for metric, observations in sorted(dynamic[(condition, take)].items()): + output.append({ + "condition": condition, "take": take, "metric": metric, + **distribution_summary(observations), + }) + return output + + +def paired_take_bootstrap( + take_rows: list[dict[str, Any]], samples: int = 10_000, seed: int = 20260716, +) -> list[dict[str, Any]]: + index = { + (row["condition"], row["take"], row["metric"]): float(row["mean"]) + for row in take_rows + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(CONDITIONS[1:]): + for metric_index, metric in enumerate(metrics): + pairs = [ + (index[(condition, take, metric)], index[("complete", take, metric)]) + for take in takes + if (condition, take, metric) in index and ("complete", take, metric) in index + ] + if not pairs: + continue + delta = np.asarray([missing - complete for missing, complete in pairs]) + rng = np.random.default_rng(np.random.SeedSequence((seed, condition_index, metric_index))) + bootstrap = delta[rng.integers(0, len(delta), size=(samples, len(delta)))].mean(axis=1) + output.append({ + "reference": "complete", "condition": condition, "metric": metric, + "takes": len(delta), "condition_minus_reference": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def load_manifest( + path: Path, expected_condition: str, expected_scope: str = "full", +) -> dict[str, Any]: + manifest = json.loads(path.read_text(encoding="utf-8")) + condition = manifest.get("input_condition", "complete") + if ( + manifest.get("status") != "complete" or manifest.get("scope") != expected_scope + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + or condition != expected_condition + ): + raise ValueError(f"invalid {expected_condition} cache manifest") + if expected_scope == "full" and ( + manifest.get("frames") != 11638 or manifest.get("clips") != 1495 + ): + raise ValueError(f"invalid {expected_condition} full-cache coverage") + return manifest + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--complete-cache", type=Path, required=True) + parser.add_argument("--missing-depth-cache", type=Path, required=True) + parser.add_argument("--missing-k-cache", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--scope", choices=("full", "smoke"), default="full") + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("missing-modality evaluation output must be new or empty") + cache_dirs = { + "complete": args.complete_cache, + "missing_depth": args.missing_depth_cache, + "missing_k": args.missing_k_cache, + } + manifests = { + condition: load_manifest(path / "cache_manifest.json", condition, args.scope) + for condition, path in cache_dirs.items() + } + coverage = {(manifest["clips"], manifest["frames"]) for manifest in manifests.values()} + if len(coverage) != 1: + raise ValueError("missing-modality cache coverage differs") + checkpoint_hashes = {manifest["checkpoint"]["sha256"] for manifest in manifests.values()} + manifest_hashes = {manifest["manifest"]["sha256"] for manifest in manifests.values()} + if len(checkpoint_hashes) != 1 or len(manifest_hashes) != 1: + raise ValueError("missing-modality caches do not share checkpoint/split") + takes_by_condition = { + condition: {record["take"]: record for record in manifest["takes"]} + for condition, manifest in manifests.items() + } + if any(set(records) != set(takes_by_condition["complete"]) for records in takes_by_condition.values()): + raise ValueError("missing-modality cache take grids differ") + static_rows: list[dict[str, Any]] = [] + dynamic: dict[tuple[str, str], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for take in sorted(takes_by_condition["complete"]): + arrays_by_condition = {} + for condition in CONDITIONS: + record = takes_by_condition[condition][take] + path = Path(record["path"]) + if sha256(path) != record["sha256"]: + raise ValueError(f"cache take hash mismatch: {path}") + arrays_by_condition[condition] = load_npz(path) + reference = arrays_by_condition["complete"] + for condition, arrays in arrays_by_condition.items(): + if condition != "complete" and not matched_cache_arrays(reference, arrays): + raise ValueError(f"cache frame/GT mismatch: {take}/{condition}") + static_rows.extend(frame_rows(arrays, condition)) + selected = arrays["frame_valid"].astype(bool) + temporal = temporal_metrics( + arrays, arrays["pred_joints_camera"], arrays["pred_direct_2d_px"], selected, + ) + identity = identity_switch_metrics(arrays, arrays["pred_joints_camera"], selected) + for metric, observations in {**temporal, **identity}.items(): + dynamic[(condition, take)][metric].extend( + float(value) for value in observations if np.isfinite(value) + ) + + group_rows = aggregate_static(static_rows) + take_rows = take_metric_rows(static_rows, dynamic) + bootstrap = paired_take_bootstrap(take_rows, samples=args.bootstrap_samples) + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", static_rows) + write_csv(args.output_dir / "group_metrics.csv", group_rows) + write_csv(args.output_dir / "take_metrics.csv", take_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap) + overview_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", "direct_2d_error_px", + "mano_projected_2d_error_px", + ) + overview = { + condition: { + metric: next( + row for row in group_rows + if row["condition"] == condition and row["group"] == "all" and row["metric"] == metric + ) + for metric in overview_metrics + } + for condition in CONDITIONS + } + report = { + "status": "evaluated", + "experiment_class": "preregistered_missing_modality_fallback_diagnostic", + "result_role": "true_coarse_model_input_ablation", + "reference": "complete", + "conditions": list(CONDITIONS), + "scope": args.scope, + "checkpoint_sha256": next(iter(checkpoint_hashes)), + "cache_manifests": { + condition: {"path": str((path / "cache_manifest.json").resolve()), "sha256": sha256(path / "cache_manifest.json")} + for condition, path in cache_dirs.items() + }, + "overview": overview, + "missing_rgb_status": "unsupported_no_rgb_availability_or_training_dropout", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "conditions": report["conditions"], + "frames": manifests["complete"]["frames"], "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_harm_risk.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..42c2af30c8069268484c386d654a282509505b07 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_harm_risk.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""Run the single frozen validation comparison for the OOF harm-risk gate.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import joblib +import numpy as np + +from foundation_hand.evaluation.harm_risk import ( + HARM_RISK_FEATURE_NAMES, + harm_risk_features, +) +from scripts.evaluate_phase6_mixed_projection import ( + METRICS, + aggregate_rows, + sha256, + take_rows, + write_csv, +) + + +ALWAYS = "coarse_wrist_ray__z_calibrated_always" +RISK = "coarse_wrist_ray__z_harm_risk" +SPECS = [ + {"id": "direct_xyz_coarse__z_coarse", "assembly": "direct_xyz_coarse", "z_mode": "coarse"}, + {"id": "direct_xyz_z_only__z_calibrated_always", "assembly": "direct_xyz_z_only", "z_mode": "calibrated_always"}, + {"id": ALWAYS, "assembly": "coarse_wrist_ray", "z_mode": "calibrated_always"}, + {"id": RISK, "assembly": "coarse_wrist_ray", "z_mode": "calibrated_confidence_0p6"}, +] + + +def paired_take_bootstrap( + rows: list[dict[str, object]], *, samples: int = 10_000, seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + output = [] + rng = np.random.default_rng(seed) + for metric in METRICS: + delta = [] + for take in takes: + candidate = [ + float(row[metric]) for row in rows + if row["condition"] == RISK and row["take"] == take + ] + reference = [ + float(row[metric]) for row in rows + if row["condition"] == ALWAYS and row["take"] == take + ] + delta.append(float(np.mean(candidate) - np.mean(reference))) + values = np.asarray(delta) + indices = rng.integers(0, len(values), size=(samples, len(values))) + boot = values[indices].mean(axis=1) + output.append({ + "condition": RISK, "reference": ALWAYS, "metric": metric, + "takes": len(takes), "delta_mean": float(values.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-dir", type=Path, required=True) + parser.add_argument("--risk-selection", type=Path, required=True) + parser.add_argument("--risk-package", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + cache_path = args.cache_dir / "cache_manifest.json" + alignment_path = args.alignment_dir / "evaluation.json" + cache = json.loads(cache_path.read_text(encoding="utf-8")) + alignment_report = json.loads(alignment_path.read_text(encoding="utf-8")) + risk_report = json.loads(args.risk_selection.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("scope") != "full" + or cache.get("official_test_used") is not False + or alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_path) + or risk_report.get("status") != "admitted_for_one_frozen_validation" + or risk_report.get("official_validation_used") is not False + or risk_report.get("official_test_used") is not False + or risk_report.get("package", {}).get("sha256") != sha256(args.risk_package) + ): + raise ValueError("cache/alignment/OOF-risk isolation contract failed") + package = joblib.load(args.risk_package) + if tuple(package["feature_names"]) != HARM_RISK_FEATURE_NAMES: + raise ValueError("risk package feature schema mismatch") + thresholds = package["selected_thresholds"] + if thresholds is None or thresholds != { + "expected_gain_threshold_mm": risk_report["selected"]["expected_gain_threshold_mm"], + "harm_probability_threshold": risk_report["selected"]["harm_probability_threshold"], + }: + raise ValueError("risk thresholds differ from frozen OOF selection") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + all_rows = [] + coverage_rows = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + raw_path = Path(take_record["path"]) + if sha256(raw_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {raw_path}") + with np.load(raw_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + diagnostic_path = args.alignment_dir / "predictions" / raw_path.name + with np.load(diagnostic_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + if not np.array_equal(arrays["frame_id"], alignment["frame_id"]): + raise ValueError(f"alignment frame mismatch: {raw_path}") + available = alignment["alignment_applied"].astype(bool) + calibrated = np.where(available, alignment["calibrated_delta_z_m"], 0.0) + raw = np.where(available, alignment["raw_alignment_delta_z_m"], 0.0) + features = harm_risk_features( + calibrated_delta_z_m=calibrated, + raw_delta_z_m=raw, + confidence=alignment["confidence"], + alignment_available=available, + raw_alignment_available=available, + valid_support_count=alignment["support"], + projected_support_count=alignment["projected_support"], + inlier_ratio=alignment["inlier_ratio"], + residual_scale_m=alignment["residual_scale_m"], + valid_fraction=alignment["valid_fraction"], + foreground_fraction=alignment["foreground_fraction"], + background_fraction=alignment["background_fraction"], + depth_discontinuity_m=alignment["depth_discontinuity_m"], + conditioning_quality=alignment["quality"], + silhouette_overlap_fraction=alignment["silhouette_overlap_fraction"], + coarse_hand_scale_px=alignment["coarse_hand_scale_px"], + coarse_direct_mano_consistency_px=alignment[ + "coarse_direct_mano_consistency_px" + ], + coarse_wrist_translation=arrays["pred_wrist_translation"], + coarse_wrist_velocity_m_per_frame=alignment[ + "coarse_wrist_velocity_m_per_frame" + ], + predicted_depth_order=alignment["predicted_depth_order"], + ) + flat = features.reshape(-1, features.shape[-1]) + expected_gain = package["regressor"].predict(flat).reshape(features.shape[:2]) + harm_probability = package["classifier"].predict_proba(flat)[:, 1].reshape( + features.shape[:2] + ) + gate = ( + available + & (expected_gain >= thresholds["expected_gain_threshold_mm"]) + & (harm_probability <= thresholds["harm_probability_threshold"]) + ) + risk_alignment = dict(alignment) + risk_alignment["gated_delta_z_m"] = np.where(gate, calibrated, 0.0) + rows, saved = take_rows(arrays, risk_alignment, SPECS) + all_rows.extend(rows) + coverage_rows.append({ + "take": str(arrays["take"]), "samples": int(gate.size), + "available": int(available.sum()), "applied": int(gate.sum()), + "coverage": float(gate.mean()), + "mean_expected_gain_mm": float(expected_gain.mean()), + "mean_harm_probability": float(harm_probability.mean()), + }) + output = prediction_root / raw_path.name + np.savez_compressed( + output, **saved, expected_gain_mm=expected_gain.astype(np.float32), + harm_probability=harm_probability.astype(np.float32), risk_gate=gate, + risk_delta_z_m=np.where(gate, calibrated, 0.0), + ) + take_records.append({ + "take": str(arrays["take"]), "frames": len(arrays["frame_id"]), + "path": str(output), "sha256": sha256(output), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + aggregate = aggregate_rows(all_rows, SPECS) + paired = paired_take_bootstrap(all_rows) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "coverage_by_take.csv", coverage_rows) + primary = { + row["condition"]: row for row in aggregate + if row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm" + } + report = { + "status": "evaluated_single_frozen_oof_risk_policy", + "experiment": "P6_S3_harm_aware_risk_gate", + "experiment_class": "exploratory_deployable_frozen_oof_policy", + "official_validation_used": True, + "official_validation_used_for_threshold_selection": False, + "official_test_used": False, + "oracle_information": False, + "conditions": SPECS, + "risk_thresholds": thresholds, + "coverage": float(sum(row["applied"] for row in coverage_rows) / sum( + row["samples"] for row in coverage_rows + )), + "always_absolute_mpjpe_mm": float(primary[ALWAYS]["mean"]), + "risk_absolute_mpjpe_mm": float(primary[RISK]["mean"]), + "absolute_delta_mm": float(primary[RISK]["mean"] - primary[ALWAYS]["mean"]), + "new_rank_one": float(primary[RISK]["mean"]) < 19.174950061401493, + "cache_manifest": {"path": str(cache_path.resolve()), "sha256": sha256(cache_path)}, + "alignment_evaluation": { + "path": str(alignment_path.resolve()), "sha256": sha256(alignment_path), + }, + "risk_selection": { + "path": str(args.risk_selection.resolve()), "sha256": sha256(args.risk_selection), + }, + "risk_package": {"path": str(args.risk_package.resolve()), "sha256": sha256(args.risk_package)}, + "checkpoint": cache["checkpoint"], "calibrator": alignment_report["calibrator"], + "takes": take_records, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_mixed_projection.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..cf5426ac585026170b1b28ff18476ce0d6656dcb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_mixed_projection.py @@ -0,0 +1,471 @@ +#!/usr/bin/env python3 +"""Evaluate frozen Phase 6 mixed-projection assemblies on validation caches.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.mixed_projection import ( + coarse_wrist_ray_translation, + direct_wrist_ray_translation, + solve_mixed_projection_batch, +) + + +FINGERTIPS = (4, 8, 12, 16, 20) +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + "direct_2d_error_px", + "projected_mano_2d_px", + "direct_mano_consistency_px", +) +REFERENCE = "direct_xyz_z_only__z_calibrated_always" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def condition_specs(selection: dict[str, Any]) -> list[dict[str, object]]: + winner = selection["winner"] + support = int(winner["minimum_support"]) + delta = float(winner["huber_delta_px"]) + output: list[dict[str, object]] = [ + {"id": "direct_xyz_coarse__z_coarse", "assembly": "direct_xyz_coarse", "z_mode": "coarse"}, + {"id": REFERENCE, "assembly": "direct_xyz_z_only", "z_mode": "calibrated_always"}, + {"id": "direct_xyz_z_only__z_raw_alignment", "assembly": "direct_xyz_z_only", "z_mode": "raw_alignment"}, + {"id": "direct_xyz_z_only__z_calibrated_confidence_0p6", "assembly": "direct_xyz_z_only", "z_mode": "calibrated_confidence_0p6"}, + ] + for z_mode in ( + "coarse", "raw_alignment", "calibrated_always", "calibrated_confidence_0p6", + ): + output.extend(( + {"id": f"coarse_wrist_ray__z_{z_mode}", "assembly": "coarse_wrist_ray", "z_mode": z_mode}, + {"id": f"direct_2d_wrist_ray__z_{z_mode}", "assembly": "direct_2d_wrist_ray", "z_mode": z_mode}, + { + "id": f"mixed_wls_s{support}__z_{z_mode}", + "assembly": "mixed_projection_21j_wls", "z_mode": z_mode, + "minimum_support": support, "huber_delta_px": None, + }, + { + "id": f"mixed_huber_d{delta:g}_s{support}__z_{z_mode}", + "assembly": "robust_mixed_projection", "z_mode": z_mode, + "minimum_support": support, "huber_delta_px": delta, + }, + )) + return output + + +def correction_grid(alignment: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + available = alignment["alignment_applied"].astype(bool) + raw = np.where(available, alignment["raw_alignment_delta_z_m"], 0.0) + calibrated = np.where(available, alignment["calibrated_delta_z_m"], 0.0) + confidence = np.where(available, alignment["gated_delta_z_m"], 0.0) + return { + "coarse": np.zeros_like(raw), + "raw_alignment": raw, + "calibrated_always": calibrated, + "calibrated_confidence_0p6": confidence, + } + + +def project(points: np.ndarray, K: np.ndarray) -> np.ndarray: + z = np.maximum(points[..., 2], 1e-8) + return np.stack(( + K[:, None, 0, 0] * points[..., 0] / z + K[:, None, 0, 2], + K[:, None, 1, 1] * points[..., 1] / z + K[:, None, 1, 2], + ), axis=-1) + + +def assemble( + spec: dict[str, object], + *, + coarse: np.ndarray, + root_relative_joints: np.ndarray, + anchors: np.ndarray, + K: np.ndarray, + z: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + direct = coarse.copy() + direct[:, 2] = z + ray = coarse_wrist_ray_translation(coarse, z) + assembly = spec["assembly"] + diagnostics: dict[str, np.ndarray] = {} + if assembly in {"direct_xyz_coarse", "direct_xyz_z_only"}: + return direct, diagnostics + if assembly == "coarse_wrist_ray": + return ray, diagnostics + if assembly == "direct_2d_wrist_ray": + translation, valid = direct_wrist_ray_translation(anchors, K, z, ray) + diagnostics.update({"success": valid, "failure_reason": np.where(valid, "ok", "invalid_k_or_anchor")}) + return translation, diagnostics + result = solve_mixed_projection_batch( + root_relative_joints, anchors, K, z, ray, + image_hw=(368, 640), minimum_support=int(spec["minimum_support"]), + robust_huber_delta_px=( + None if spec["huber_delta_px"] is None else float(spec["huber_delta_px"]) + ), + ) + diagnostics.update({ + "support_count": result.support_count, + "residual_scale_px": result.residual_scale_px, + "conditioning": result.conditioning, + "inlier_ratio": result.inlier_ratio, + "uncertainty_x_m": result.uncertainty_xy_m[:, 0], + "uncertainty_y_m": result.uncertainty_xy_m[:, 1], + "success": result.failure_reason == "ok", + "failure_reason": result.failure_reason, + }) + return result.translation_m, diagnostics + + +def hand_size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def take_rows( + arrays: dict[str, np.ndarray], + alignment: dict[str, np.ndarray], + specs: list[dict[str, object]], +) -> tuple[list[dict[str, object]], dict[str, np.ndarray]]: + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + time_index, hand = np.where(valid) + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + coarse_joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + coarse_vertices = arrays["pred_vertices_camera"][time_index, hand].astype(np.float64) + root_relative = coarse_joints - coarse_joints[:, :1] + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + K = arrays["K"][time_index].astype(np.float64) + corrections = correction_grid(alignment) + coarse_projected = project(coarse_joints, K) + scale = np.ptp(coarse_projected, axis=1).max(axis=-1) + frame_rows = [] + saved: dict[str, list[np.ndarray]] = defaultdict(list) + for spec in specs: + condition = str(spec["id"]) + z_mode = str(spec["z_mode"]) + z = coarse[:, 2] + corrections[z_mode][time_index, hand] + translation, diagnostics = assemble( + spec, coarse=coarse, root_relative_joints=root_relative, + anchors=anchors, K=K, z=z, + ) + shift = translation - coarse + joints = coarse_joints + shift[:, None] + vertices = coarse_vertices + shift[:, None] + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_vertices = arrays["target_vertices_camera"][time_index, hand].astype(np.float64) + target_translation = arrays["target_wrist_translation"][time_index, hand].astype(np.float64) + target_2d = arrays["target_2d_px"][time_index, hand].astype(np.float64) + projected = project(joints, K) + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (joints - joints[:, :1]) - (target_joints - target_joints[:, :1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (vertices - joints[:, :1]) - (target_vertices - target_joints[:, :1]), axis=-1, + ) * 1000.0 + signed_translation = (translation - target_translation) * 1000.0 + success = diagnostics.get("success", np.ones(len(translation), dtype=bool)) + failure = diagnostics.get("failure_reason", np.full(len(translation), "ok")) + support = diagnostics.get("support_count", np.full(len(translation), 21)) + residual_scale = diagnostics.get("residual_scale_px", np.zeros(len(translation))) + conditioning = diagnostics.get("conditioning", np.ones(len(translation))) + inlier_ratio = diagnostics.get("inlier_ratio", np.ones(len(translation))) + uncertainty_x = diagnostics.get("uncertainty_x_m", np.zeros(len(translation))) + uncertainty_y = diagnostics.get("uncertainty_y_m", np.zeros(len(translation))) + for index in range(len(translation)): + current_time, current_hand = int(time_index[index]), int(hand[index]) + direct_error = np.linalg.norm(anchors[index] - target_2d[index], axis=-1).mean() + projected_error = np.linalg.norm(projected[index] - target_2d[index], axis=-1).mean() + consistency = np.linalg.norm(projected[index] - anchors[index], axis=-1).mean() + frame_rows.append({ + "condition": condition, + "assembly": spec["assembly"], + "z_mode": z_mode, + "take": take, + "subject": take.split("/")[0], + "action_family": take.split("/")[1], + "frame_id": int(arrays["frame_id"][current_time]), + "side": "right" if current_hand else "left", + "hand_size_bucket": hand_size_bucket(float(scale[index])), + "depth_bucket": depth_bucket(float(target_translation[index, 2])), + "absolute_mpjpe_mm": float(joint_error[index].mean()), + "root_relative_mpjpe_mm": float(root_joint_error[index].mean()), + "absolute_mpvpe_mm": float(vertex_error[index].mean()), + "root_relative_mpvpe_mm": float(root_vertex_error[index].mean()), + "fingertip_mpjpe_mm": float(joint_error[index, FINGERTIPS].mean()), + "translation_x_mae_mm": abs(float(signed_translation[index, 0])), + "translation_y_mae_mm": abs(float(signed_translation[index, 1])), + "translation_z_mae_mm": abs(float(signed_translation[index, 2])), + "translation_x_signed_error_mm": float(signed_translation[index, 0]), + "translation_y_signed_error_mm": float(signed_translation[index, 1]), + "translation_z_signed_error_mm": float(signed_translation[index, 2]), + "direct_2d_error_px": float(direct_error), + "projected_mano_2d_px": float(projected_error), + "direct_mano_consistency_px": float(consistency), + "applied_delta_z_mm": float(1000.0 * corrections[z_mode][current_time, current_hand]), + "support_count": int(support[index]), + "residual_scale_px": float(residual_scale[index]), + "conditioning": float(conditioning[index]), + "inlier_ratio": float(inlier_ratio[index]), + "uncertainty_x_mm": float(1000.0 * uncertainty_x[index]), + "uncertainty_y_mm": float(1000.0 * uncertainty_y[index]), + "solve_success": bool(success[index]), + "failure_reason": str(failure[index]), + }) + saved[f"translation__{condition}"].append(translation.astype(np.float32)) + saved[f"success__{condition}"].append(success.astype(bool)) + saved_arrays: dict[str, np.ndarray] = { + "frame_id": arrays["frame_id"], + "valid_time_index": time_index.astype(np.int64), + "valid_hand_index": hand.astype(np.int64), + } + saved_arrays.update({key: value[0] for key, value in saved.items()}) + return frame_rows, saved_arrays + + +def aggregate_rows( + rows: list[dict[str, object]], specs: list[dict[str, object]], +) -> list[dict[str, object]]: + output = [] + for spec in specs: + condition = str(spec["id"]) + selected = [row for row in rows if row["condition"] == condition] + for metric in METRICS: + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row[metric] for row in selected), + }) + for group in ("side", "hand_size_bucket", "depth_bucket", "take", "action_family"): + for value in sorted({str(row[group]) for row in selected}): + grouped = [row for row in selected if str(row[group]) == value] + for metric in METRICS: + output.append({ + "condition": condition, "group": group, "value": value, + "metric": metric, + **distribution_summary(row[metric] for row in grouped), + }) + output.append({ + "condition": condition, "group": "all", "value": "all", + "metric": "solve_success_fraction", + **distribution_summary(float(row["solve_success"]) for row in selected), + }) + return output + + +def paired_take_bootstrap( + rows: list[dict[str, object]], specs: list[dict[str, object]], + *, samples: int = 10_000, seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + take_mean: dict[tuple[str, str, str], float] = {} + for spec in specs: + condition = str(spec["id"]) + for take in takes: + selected = [row for row in rows if row["condition"] == condition and row["take"] == take] + for metric in METRICS: + take_mean[(condition, take, metric)] = float(np.mean([row[metric] for row in selected])) + output = [] + rng = np.random.default_rng(seed) + for spec in specs: + condition = str(spec["id"]) + if condition == REFERENCE: + continue + for metric in METRICS: + delta = np.asarray([ + take_mean[(condition, take, metric)] - take_mean[(REFERENCE, take, metric)] + for take in takes + ]) + indices = rng.integers(0, len(delta), size=(samples, len(delta))) + boot = delta[indices].mean(axis=1) + output.append({ + "condition": condition, "reference": REFERENCE, "metric": metric, + "takes": len(takes), "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-dir", type=Path, required=True) + parser.add_argument("--oof-selection", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + cache_manifest_path = args.cache_dir / "cache_manifest.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + alignment_report_path = args.alignment_dir / "evaluation.json" + alignment_report = json.loads(alignment_report_path.read_text(encoding="utf-8")) + selection = json.loads(args.oof_selection.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("scope") != "full" + or cache.get("official_test_used") is not False + or alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + or selection.get("status") != "selected_oof_only" + or selection.get("official_validation_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("cache/alignment/OOF isolation contract failed") + specs = condition_specs(selection) + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_dir = args.output_dir / "predictions" + prediction_dir.mkdir() + all_rows = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + alignment_path = args.alignment_dir / "predictions" / take_path.name + with np.load(alignment_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + if not np.array_equal(arrays["frame_id"], alignment["frame_id"]): + raise ValueError(f"alignment frame mismatch: {take_path}") + rows, saved = take_rows(arrays, alignment, specs) + all_rows.extend(rows) + output_path = prediction_dir / take_path.name + np.savez_compressed(output_path, **saved) + take_records.append({ + "take": str(arrays["take"]), "frames": len(arrays["frame_id"]), + "path": str(output_path), "sha256": sha256(output_path), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + aggregate = aggregate_rows(all_rows, specs) + paired = paired_take_bootstrap(all_rows, specs) + reference_rows = { + (row["take"], row["frame_id"], row["side"]): row + for row in all_rows if row["condition"] == REFERENCE + } + case_rows = [] + for spec in specs: + condition = str(spec["id"]) + if condition == REFERENCE: + continue + selected = [row for row in all_rows if row["condition"] == condition] + deltas = np.asarray([ + float(row["absolute_mpjpe_mm"]) + - float(reference_rows[(row["take"], row["frame_id"], row["side"])]["absolute_mpjpe_mm"]) + for row in selected + ]) + for role, indices in ( + ("largest_gain", np.argsort(deltas)[:10]), + ("largest_harm", np.argsort(deltas)[-10:][::-1]), + ): + for rank, index in enumerate(indices, start=1): + row = selected[int(index)] + case_rows.append({ + "condition": condition, "role": role, "rank": rank, + "take": row["take"], "frame_id": row["frame_id"], "side": row["side"], + "absolute_delta_mm": float(deltas[index]), + "candidate_absolute_mpjpe_mm": row["absolute_mpjpe_mm"], + "reference_absolute_mpjpe_mm": reference_rows[ + (row["take"], row["frame_id"], row["side"]) + ]["absolute_mpjpe_mm"], + "support_count": row["support_count"], + "residual_scale_px": row["residual_scale_px"], + "conditioning": row["conditioning"], + "inlier_ratio": row["inlier_ratio"], + "failure_reason": row["failure_reason"], + }) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "largest_gain_harm.csv", case_rows) + primary_rows = [ + row for row in aggregate + if row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm" + ] + best = min(primary_rows, key=lambda row: float(row["mean"])) + reference = next(row for row in primary_rows if row["condition"] == REFERENCE) + guardrail = min(0.2, 0.01 * float(reference["mean"])) + report = { + "status": "evaluated_frozen_oof_selection", + "experiment": "P6_S1_cache_mixed_projection", + "experiment_class": "preregistered_cache_only_deployable_ablation", + "official_validation_used": True, + "official_validation_used_for_solver_constant_selection": False, + "official_test_used": False, + "oracle_information": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "alignment_evaluation": {"path": str(alignment_report_path.resolve()), "sha256": sha256(alignment_report_path)}, + "oof_selection": {"path": str(args.oof_selection.resolve()), "sha256": sha256(args.oof_selection)}, + "checkpoint": cache["checkpoint"], + "calibrator": alignment_report["calibrator"], + "conditions": specs, + "reference_condition": REFERENCE, + "reference_absolute_mpjpe_mm": float(reference["mean"]), + "best_condition": best["condition"], + "best_absolute_mpjpe_mm": float(best["mean"]), + "best_delta_mm": float(best["mean"] - reference["mean"]), + "new_rank_one": float(best["mean"]) < 19.45484110440441, + "geometry_secondary_guardrail_passed": float(best["mean"]) <= float(reference["mean"]) + guardrail, + "takes": take_records, + "outputs": { + "per_hand": "per_hand_frame_metrics.csv", "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "largest_gain_harm": "largest_gain_harm.csv", "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "reference": report["reference_absolute_mpjpe_mm"], + "best_condition": report["best_condition"], "best": report["best_absolute_mpjpe_mm"], + "new_rank_one": report["new_rank_one"], "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_pa_mpjpe.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_pa_mpjpe.py new file mode 100644 index 0000000000000000000000000000000000000000..59e3ad31371664ffe62f535f94ff288f2eaece36 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_pa_mpjpe.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Evaluate seed17 rigid and standard Procrustes-aligned MPJPE.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def summary(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": len(array), "mean": float(array.mean()), + "p50": float(np.percentile(array, 50)), + "p95": float(np.percentile(array, 95)), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + ): + raise ValueError("raw cache isolation contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + values: dict[str, list[float]] = defaultdict(list) + rows = [] + for take_record in manifest["takes"]: + path = Path(take_record["path"]) + if sha256(path) != take_record["sha256"]: + raise ValueError(f"cache take hash mismatch: {path}") + with np.load(path, allow_pickle=False) as archive: + predicted = archive["pred_joints_camera"] + target = archive["target_joints_camera"] + valid = archive["joint_annotation_valid"].astype(bool) & archive[ + "frame_valid" + ][:, None].astype(bool) + frame_ids = archive["frame_id"] + take = str(archive["take"]) + for hand, side in enumerate(("left", "right")): + indices = np.where(valid[:, hand])[0] + rigid = aligned_mpjpe_mm( + predicted[indices, hand], target[indices, hand], estimate_scale=False, + ) + similarity = aligned_mpjpe_mm( + predicted[indices, hand], target[indices, hand], estimate_scale=True, + ) + values["rigid_aligned_mpjpe_mm"].extend(rigid.tolist()) + values["pa_mpjpe_mm"].extend(similarity.tolist()) + values[f"{side}_rigid_aligned_mpjpe_mm"].extend(rigid.tolist()) + values[f"{side}_pa_mpjpe_mm"].extend(similarity.tolist()) + rows.extend({ + "take": take, "frame_id": int(frame_ids[index]), "side": side, + "rigid_aligned_mpjpe_mm": float(rigid[position]), + "pa_mpjpe_mm": float(similarity[position]), + } for position, index in enumerate(indices)) + with (args.output_dir / "per_hand_frame_metrics.csv").open( + "x", newline="", encoding="utf-8", + ) as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "evaluated", + "experiment": "P6_pose_alignment_metric_addendum", + "official_test_used": False, + "metric_definitions": { + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation, and scale", + "rigid_aligned_mpjpe_mm": "per-hand SE(3) Kabsch; removes translation and rotation only", + }, + "translation_only_system_invariance": True, + "metrics": {key: summary(items) for key, items in values.items()}, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_state_ray.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_state_ray.py new file mode 100644 index 0000000000000000000000000000000000000000..a44aac603af5f949a790d4f714314f029344abdf --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase6_state_ray.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Compose frozen causal-state z estimates with the coarse wrist camera ray.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.mixed_projection import coarse_wrist_ray_translation +from scripts.evaluate_phase4_jitter import ( + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, +) +from scripts.evaluate_phase5_causal_state import response_diagnostics +from scripts.evaluate_phase6_mixed_projection import METRICS, aggregate_rows, take_rows + + +STATE_CONDITIONS = ( + "coarse", + "calibrated_per_frame", + "ema_alpha0.6", + "butterworth_2hz", + "fixed_kalman", + "uncertainty_kalman", +) +REFERENCE = "calibrated_per_frame__coarse_wrist_ray" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def assemble_state_ray_geometry( + coarse_translation_m: np.ndarray, + coarse_joints_m: np.ndarray, + coarse_vertices_m: np.ndarray, + state_z_m: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Preserve each coarse wrist ray and rigidly translate its hand geometry.""" + + coarse_translation = np.asarray(coarse_translation_m, dtype=np.float64) + state_z = np.asarray(state_z_m, dtype=np.float64) + safe_z = np.where( + np.isfinite(state_z) & (state_z > 0.05), + state_z, + coarse_translation[..., 2], + ) + translation = coarse_wrist_ray_translation(coarse_translation, safe_z) + shift = translation - coarse_translation + joints = np.asarray(coarse_joints_m, dtype=np.float64) + shift[..., None, :] + vertices = np.asarray(coarse_vertices_m, dtype=np.float64) + shift[..., None, :] + return translation, joints, vertices + + +def paired_bootstrap( + rows: list[dict[str, object]], + conditions: list[str], + *, + samples: int, + seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + means: dict[tuple[str, str, str], float] = {} + for condition in conditions: + for take in takes: + selected = [ + row for row in rows + if row["condition"] == condition and row["take"] == take + ] + for metric in METRICS: + means[(condition, take, metric)] = float( + np.mean([float(row[metric]) for row in selected]) + ) + output = [] + for condition_index, condition in enumerate(conditions): + if condition == REFERENCE: + continue + for metric_index, metric in enumerate(METRICS): + delta = np.asarray([ + means[(condition, take, metric)] - means[(REFERENCE, take, metric)] + for take in takes + ]) + rng = np.random.default_rng( + np.random.SeedSequence((seed, condition_index, metric_index)) + ) + bootstrap = delta[ + rng.integers(0, len(delta), size=(samples, len(delta))) + ].mean(axis=1) + output.append({ + "condition": condition, + "reference": REFERENCE, + "metric": metric, + "takes": len(takes), + "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--state-evaluation-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + + cache_manifest_path = args.cache_dir / "cache_manifest.json" + state_report_path = args.state_evaluation_dir / "evaluation.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + state_report = json.loads(state_report_path.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("sequence_mode") != "causal" + or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + or state_report.get("status") != "evaluated" + or state_report.get("official_test_used") is not False + or state_report.get("official_validation_used_for_parameter_selection") is not False + or state_report.get("continuous_take_state") is not True + or state_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + ): + raise ValueError("causal cache/state isolation contract failed") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_dir = args.output_dir / "predictions" + prediction_dir.mkdir() + specs = [ + { + "id": f"{condition}__coarse_wrist_ray", + "assembly": "coarse_wrist_ray", + "z_mode": "calibrated_always", + } + for condition in STATE_CONDITIONS + ] + all_rows: list[dict[str, object]] = [] + temporal_values = { + str(spec["id"]): defaultdict(list) for spec in specs + } + temporal_take_rows: list[dict[str, object]] = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {take_path}") + arrays = load_npz(take_path) + arrays["clip_index"] = np.zeros_like(arrays["clip_index"]) + state_path = args.state_evaluation_dir / "predictions" / take_path.name + state = load_npz(state_path) + if not np.array_equal(arrays["frame_id"], state["frame_id"]): + raise ValueError(f"state frame mismatch: {take_path}") + arrays["_calibrated_measurement_z_m"] = state["calibrated_per_frame_z_m"] + saved: dict[str, np.ndarray] = {"frame_id": arrays["frame_id"]} + for spec, state_condition in zip(specs, STATE_CONDITIONS, strict=True): + condition = str(spec["id"]) + z_m = state[f"{state_condition}_z_m"].astype(np.float64) + correction = z_m - arrays["pred_wrist_translation"][..., 2] + alignment = { + "alignment_applied": np.isfinite(correction), + "raw_alignment_delta_z_m": correction, + "calibrated_delta_z_m": correction, + "gated_delta_z_m": correction, + } + rows, _ = take_rows(arrays, alignment, [spec]) + all_rows.extend(rows) + translation, joints, vertices = assemble_state_ray_geometry( + arrays["pred_wrist_translation"], + arrays["pred_joints_camera"], + arrays["pred_vertices_camera"], + z_m, + ) + selected = arrays["frame_valid"].astype(bool) + _, projected, _ = per_frame_metrics( + arrays, + joints, + vertices, + arrays["pred_rotation_matrices"], + translation, + selected, + ) + values = temporal_metrics(arrays, joints, projected, selected) + identity = identity_switch_metrics(arrays, joints, selected) + values.update(identity) + values.update(response_diagnostics(arrays, z_m)) + for metric, observations in values.items(): + finite = [float(value) for value in observations if np.isfinite(value)] + temporal_values[condition][metric].extend(finite) + temporal_take_rows.append({ + "take": str(arrays["take"]), + "condition": condition, + "metric": metric, + **distribution_summary(finite), + }) + saved[f"translation__{condition}"] = translation.astype(np.float32) + saved[f"z_variance_m2__{condition}"] = state[ + f"{state_condition}_variance_m2" + ].astype(np.float32) + output_path = prediction_dir / take_path.name + np.savez_compressed(output_path, **saved) + take_records.append({ + "take": str(arrays["take"]), + "frames": len(arrays["frame_id"]), + "path": str(output_path), + "sha256": sha256(output_path), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + aggregate = aggregate_rows(all_rows, specs) + conditions = [str(spec["id"]) for spec in specs] + paired = paired_bootstrap( + all_rows, conditions, samples=args.bootstrap_samples, + ) + temporal_rows = [ + {"condition": condition, "metric": metric, **distribution_summary(values)} + for condition in conditions + for metric, values in sorted(temporal_values[condition].items()) + ] + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "temporal_metrics.csv", temporal_rows) + write_csv(args.output_dir / "temporal_take_metrics.csv", temporal_take_rows) + + static_index = { + (str(row["condition"]), str(row["metric"])): row + for row in aggregate if row["group"] == "all" and row["value"] == "all" + } + temporal_index = { + (str(row["condition"]), str(row["metric"])): row for row in temporal_rows + } + overview = [] + for condition in conditions: + row: dict[str, object] = { + "condition": condition, + "absolute_mpjpe_mm": static_index[(condition, "absolute_mpjpe_mm")]["mean"], + "absolute_mpvpe_mm": static_index[(condition, "absolute_mpvpe_mm")]["mean"], + "fingertip_mpjpe_mm": static_index[(condition, "fingertip_mpjpe_mm")]["mean"], + "translation_x_mae_mm": static_index[(condition, "translation_x_mae_mm")]["mean"], + "translation_y_mae_mm": static_index[(condition, "translation_y_mae_mm")]["mean"], + "translation_z_mae_mm": static_index[(condition, "translation_z_mae_mm")]["mean"], + "translation_z_p95_mm": static_index[(condition, "translation_z_mae_mm")]["p95"], + "projected_mano_2d_px": static_index[(condition, "projected_mano_2d_px")]["mean"], + } + for metric in ( + "joint_velocity_error_mm_per_s", + "joint_acceleration_error_mm_per_s2", + "predicted_3d_joint_acceleration_mm_per_s2", + "predicted_3d_joint_jerk_mm_per_s3", + "high_frequency_energy_ratio", + "estimated_causal_lag_frames", + ): + if (condition, metric) in temporal_index: + row[metric] = temporal_index[(condition, metric)]["mean"] + overview.append(row) + reference = next(row for row in overview if row["condition"] == REFERENCE) + for row in overview: + row["absolute_delta_mm"] = float(row["absolute_mpjpe_mm"]) - float( + reference["absolute_mpjpe_mm"] + ) + row["static_guardrail_passed"] = bool( + float(row["absolute_delta_mm"]) <= 0.2 + and float(row["translation_z_mae_mm"]) + <= float(reference["translation_z_mae_mm"]) + 0.2 + and float(row["translation_z_p95_mm"]) + <= float(reference["translation_z_p95_mm"]) + 0.2 + ) + write_csv(args.output_dir / "overview.csv", overview) + report = { + "status": "evaluated_frozen_causal_state_coarse_ray", + "experiment_class": "preregistered_frozen_parameter_causal_state_composition", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + "oracle_information": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "state_evaluation": {"path": str(state_report_path.resolve()), "sha256": sha256(state_report_path)}, + "selection": state_report["selection"], + "assembly": "coarse wrist camera ray recomputed at each frozen state z", + "reference": REFERENCE, + "conditions": conditions, + "takes": take_records, + "outputs": { + "overview": "overview.csv", + "per_hand": "per_hand_frame_metrics.csv", + "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "temporal": "temporal_metrics.csv", + "temporal_takes": "temporal_take_metrics.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": report["status"], "overview": overview}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase7_egodexter_zero_shot.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase7_egodexter_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..d9afe80a0f18d42d100ec440bdaeeb35b14f9e7f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase7_egodexter_zero_shot.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Evaluate a fully frozen Phase 7 model on EgoDexter exactly once.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import time +from typing import Any, Iterator + +import numpy as np +import torch +import yaml + +from foundation_hand.data.egodexter_dataset import ( + EgoDexterSequenceDataset, FINGERTIP_JOINT_INDICES, SEQUENCES, +) +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.train_phase7_external import assert_physical_gpu_idle + + +FINGER_NAMES = ("thumb", "index", "middle", "ring", "little") +MODEL_INPUT_FIELDS = { + "rgb", "depth_m", "depth_pixel_valid", "K", "K_available", + "K_input_available", "depth_available", "depth_input_available", "frame_valid", +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_summary(values: list[float]) -> dict[str, float | int] | None: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if not len(array): + return None + return { + "count": int(len(array)), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + } + + +def validate_freeze_record( + record: dict[str, Any], model_id: str, checkpoint_sha: str, + config_path: Path, inference_mode: str, +) -> dict[str, Any]: + if ( + record.get("status") != "phase7_final_models_frozen" + or record.get("egodexter_used_for_training_or_selection") is not False + or record.get("official_test_used") is not False + ): + raise ValueError("Phase 7 final model set is not EgoDexter-eligible") + models = {item["id"]: item for item in record.get("models", [])} + if model_id not in models: + raise ValueError(f"model is absent from the final freeze: {model_id}") + model = models[model_id] + if model.get("checkpoint_sha256") != checkpoint_sha: + raise ValueError("checkpoint differs from final model freeze") + config_record = model.get("inference_configs", {}).get(inference_mode, {}) + if ( + Path(config_record.get("path", "")).resolve() != config_path.resolve() + or config_record.get("sha256") != sha256(config_path) + ): + raise ValueError("inference config differs from final model freeze") + mapping = record.get("egodexter_sequence_handedness", {}) + if set(mapping) != set(SEQUENCES) or any(side not in {"left", "right"} for side in mapping.values()): + raise ValueError("EgoDexter sequence handedness is not fully frozen") + return model + + +def model_frame(frame: dict[str, object]) -> dict[str, object]: + return {key: frame[key] for key in MODEL_INPUT_FIELDS} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--model-id", required=True) + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--input-mode", choices=("rgb_d_k", "rgb_k", "rgb_only"), required=True) + parser.add_argument("--inference-mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, default=8) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + checkpoint_sha = sha256(args.checkpoint) + freeze = json.loads(args.freeze_record.read_text(encoding="utf-8")) + validate_freeze_record( + freeze, args.model_id, checkpoint_sha, args.config, args.inference_mode, + ) + assert_physical_gpu_idle(args.physical_gpu_id) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + attention_mode = config["model"].get("temporal_attention_mode", "bidirectional") + required_attention = "causal" if args.inference_mode == "causal" else "bidirectional" + if attention_mode != required_attention: + parser.error("inference mode and temporal attention mode differ") + assets = config["assets"] + device = torch.device("cuda") + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + sequence_handedness = freeze["egodexter_sequence_handedness"] + rows: list[dict[str, Any]] = [] + raw_prediction, raw_target, raw_valid = [], [], [] + raw_sequence, raw_frame, raw_side = [], [], [] + maximum_gpu_window = 0 + maximum_cpu_buffer = 0 + total_frames = 0 + started = time.perf_counter() + torch.cuda.reset_peak_memory_stats() + for sequence_index, sequence in enumerate(SEQUENCES): + dataset = EgoDexterSequenceDataset( + args.root, sequence, hand_side=sequence_handedness[sequence], + target_hw=tuple(config["data"]["resolution_hw"]), + ) + targets: list[np.ndarray] = [] + target_valid: list[np.ndarray] = [] + frame_ids: list[int] = [] + + def frames() -> Iterator[dict[str, object]]: + for index in range(len(dataset)): + frame = dataset.frame(index, args.input_mode) + targets.append(frame["target_fingertips_camera_m"].numpy()) + target_valid.append(frame["target_fingertip_valid"].numpy()) + frame_ids.append(int(frame["frame_id"])) + yield model_frame(frame) + + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.inference_mode, window_size=args.window, + offline_stride=(args.window // 2 if args.inference_mode == "offline" else None), + ), + device=device, autocast_dtype=dtype, + ) + output = runner.infer(frames()) + predicted = output["joints_camera"][0, :, dataset.side_index][ + :, FINGERTIP_JOINT_INDICES + ].numpy() + target = np.stack(targets) + valid = np.stack(target_valid) & np.isfinite(predicted).all(axis=-1) + error = np.linalg.norm(predicted - target, axis=-1) * 1000.0 + for frame_index, frame_id in enumerate(frame_ids): + for finger, name in enumerate(FINGER_NAMES): + rows.append({ + "model_id": args.model_id, "sequence": sequence, + "frame_id": frame_id, "hand_side": dataset.hand_side, + "finger": name, "target_visible": bool(valid[frame_index, finger]), + "fingertip_error_mm": ( + float(error[frame_index, finger]) if valid[frame_index, finger] else math.nan + ), + }) + raw_prediction.append(predicted) + raw_target.append(target) + raw_valid.append(valid) + raw_sequence.append(np.full(len(dataset), sequence_index, dtype=np.int16)) + raw_frame.append(np.asarray(frame_ids, dtype=np.int32)) + raw_side.append(np.full(len(dataset), dataset.side_index, dtype=np.int8)) + total_frames += len(dataset) + maximum_gpu_window = max(maximum_gpu_window, runner.maximum_resident_frames) + maximum_cpu_buffer = max(maximum_cpu_buffer, runner.maximum_input_buffer_frames) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + args.output_dir.mkdir(parents=True) + row_path = args.output_dir / "per_fingertip_metrics.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed( + raw_path, predicted_fingertips_camera_m=np.concatenate(raw_prediction), + target_fingertips_camera_m=np.concatenate(raw_target), + target_visible=np.concatenate(raw_valid), sequence_index=np.concatenate(raw_sequence), + frame_id=np.concatenate(raw_frame), side_index=np.concatenate(raw_side), + ) + visible = [row["fingertip_error_mm"] for row in rows if row["target_visible"]] + report = { + "status": "evaluated_frozen_egodexter_zero_shot", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "model_id": args.model_id, "checkpoint_step": int(state["step"]), + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": checkpoint_sha}, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "freeze_record": {"path": str(args.freeze_record.resolve()), "sha256": sha256(args.freeze_record)}, + "input_mode": args.input_mode, "inference_mode": args.inference_mode, + "causal": args.inference_mode == "causal", "window": args.window, + "frames": total_frames, "visible_fingertips": len(visible), + "coverage_fraction": len(visible) / (total_frames * len(FINGER_NAMES)), + "fingertip_error_mm": finite_summary(visible), + "per_finger": { + finger: finite_summary([ + row["fingertip_error_mm"] for row in rows + if row["finger"] == finger and row["target_visible"] + ]) for finger in FINGER_NAMES + }, + "per_sequence": { + sequence: finite_summary([ + row["fingertip_error_mm"] for row in rows + if row["sequence"] == sequence and row["target_visible"] + ]) for sequence in SEQUENCES + }, + "sequence_handedness": sequence_handedness, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": total_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + "maximum_gpu_window_frames": maximum_gpu_window, + "maximum_cpu_input_buffer_frames": maximum_cpu_buffer, + }, + "per_fingertip_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "gt_passed_to_model": False, "per_frame_gt_slot_selection_used": False, + "egodexter_used_for_training_or_selection": False, "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase7_external.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..b067ba132f65bcdbd91712c730da0ff052e1e2f6 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase7_external.py @@ -0,0 +1,749 @@ +#!/usr/bin/env python3 +"""Unified held-out evaluation for Phase 7 external-only checkpoints.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import CachedUnifiedClipDataset, collate_h2o_clips +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from foundation_hand.geometry.camera import project_points +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.train_experiment import attach_gt_vertices, move_to_device +from scripts.train_phase7_external import assert_physical_gpu_idle + + +TIP_INDICES = (4, 8, 12, 16, 20) + + +def checkpoint_h2o_training_data_used(checkpoint_extra: dict[str, Any]) -> bool: + """Read H2O exposure without relabelling historical H2O checkpoints.""" + + explicit = checkpoint_extra.get("h2o_training_data_used") + if isinstance(explicit, bool): + return explicit + experiment = checkpoint_extra.get("config", {}).get("experiment", {}) + phase = experiment.get("phase") + # Phase 3-6 checkpoints predate the explicit provenance flag and were + # trained on the canonical H2O train split. + if isinstance(phase, int) and 3 <= phase <= 6: + return True + raise ValueError("checkpoint lacks auditable H2O-training provenance") + + +def validate_evaluation_role( + role: str, config: dict[str, Any], dataset_ids: set[str], + checkpoint_extra: dict[str, Any], cache_manifest: Path, +) -> None: + branch = config.get("experiment", {}).get("branch") + if role == "external_heldout": + if branch != "external_only": + raise ValueError("external evaluation config is not external-only") + if "H2O" in dataset_ids or checkpoint_extra.get("h2o_training_data_used") is not False: + raise ValueError("external evaluator refuses H2O data or training exposure") + elif role == "h2o_train_group_heldout": + if branch != "h2o_adaptation": + raise ValueError("H2O train-heldout evaluation requires an adaptation config") + if dataset_ids != {"H2O"}: + raise ValueError("H2O train-heldout evaluation requires a pure H2O cache") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("adaptation checkpoint lacks H2O-training provenance") + if cache_manifest.name != "train_group_heldout.jsonl": + raise ValueError("adaptation selection requires the frozen train-group-heldout manifest") + elif role == "h2o_train_group_heldout_control": + if dataset_ids != {"H2O"}: + raise ValueError("H2O train-heldout control requires a pure H2O cache") + checkpoint_h2o_training_data_used(checkpoint_extra) + if cache_manifest.name != "train_group_heldout.jsonl": + raise ValueError("H2O control requires the frozen train-group-heldout manifest") + elif role == "adaptation_external_heldout": + if branch != "h2o_adaptation": + raise ValueError("adaptation forgetting evaluation requires an adaptation config") + if not dataset_ids or not dataset_ids.issubset({"HOT3D", "HOI4D", "ARCTIC"}): + raise ValueError("adaptation forgetting evaluation requires pure external held-out data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("adaptation forgetting checkpoint lacks H2O-training provenance") + if "h2o" in str(cache_manifest).lower(): + raise ValueError("adaptation forgetting evaluation refuses H2O cache paths") + elif role == "phase9_external_heldout": + if branch != "phase9_unified": + raise ValueError("Phase 9 external evaluation requires a unified config") + if not dataset_ids or not dataset_ids.issubset({"HOT3D", "HOI4D", "ARCTIC"}): + raise ValueError("Phase 9 external evaluation requires pure external held-out data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("Phase 9 unified checkpoint lacks H2O-training provenance") + if "h2o" in str(cache_manifest).lower(): + raise ValueError("Phase 9 external evaluation refuses H2O cache paths") + elif role == "phase9_h2o_fold_heldout": + fold = str(config.get("experiment", {}).get("h2o_selection_fold", "")) + if branch != "phase9_unified" or not fold: + raise ValueError("Phase 9 fold evaluation requires a fold-specific unified config") + if dataset_ids != {"H2O"}: + raise ValueError("Phase 9 fold evaluation requires pure H2O train-heldout data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("Phase 9 fold checkpoint lacks H2O-training provenance") + expected = f"{fold}_heldout.jsonl" + if cache_manifest.name != expected: + raise ValueError(f"Phase 9 fold cache must be {expected}") + else: + raise ValueError(f"unsupported evaluation role: {role}") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_progress_heartbeat(path: Path | None, value: dict[str, Any]) -> None: + if path is None: + return + payload = { + "schema_version": "phase9_evaluation_progress_heartbeat_v1", + "updated_utc": datetime.now(timezone.utc).isoformat(), + "evaluator_pid": os.getpid(), + "h2o_official_validation_used": False, + "official_test_used": False, + **value, + } + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def direct_child_pids(pid: int) -> list[int]: + path = Path(f"/proc/{pid}/task/{pid}/children") + try: + return sorted(int(value) for value in path.read_text().split()) + except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError): + return [] + + +def finite_summary(values: list[float]) -> dict[str, float | int] | None: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if not len(array): + return None + p95 = float(np.quantile(array, .95)) + tail = array[array >= p95] + return { + "count": int(len(array)), "mean": float(array.mean()), + "median": float(np.median(array)), "p90": float(np.quantile(array, .90)), + "p95": p95, "p99": float(np.quantile(array, .99)), + "cvar95": float(tail.mean()), "max": float(array.max()), + } + + +def tensor_to_numpy(value: torch.Tensor) -> np.ndarray: + """Move persisted floating predictions to a NumPy-supported dtype.""" + value = value.detach().cpu() + if value.is_floating_point() and value.dtype == torch.bfloat16: + value = value.float() + return value.numpy() + + +def append_valid_frame_arrays( + raw: dict[str, list[np.ndarray]], values: dict[str, torch.Tensor], + frame_valid: torch.Tensor, +) -> None: + """Persist variable-length clips on one contiguous valid-frame axis.""" + + valid = tensor_to_numpy(frame_valid.bool()).reshape(-1) + batch, time = frame_valid.shape + for key, value in values.items(): + array = tensor_to_numpy(value) + if array.shape[:2] != (batch, time): + raise ValueError(f"raw temporal field shape differs from frame_valid: {key}") + flattened = array.reshape(batch * time, *array.shape[2:]) + raw.setdefault(key, []).append(flattened[valid]) + + +def hand_size_bucket(size_px: float) -> str: + if size_px < 64.0: + return "small_lt64" + if size_px < 128.0: + return "medium_64_128" + return "large_ge128" + + +def depth_bucket(depth_m: float) -> str: + return "far_gt0.8m" if depth_m > .8 else "near_le0.8m" + + +def apply_input_mode(batch: dict[str, Any], mode: str) -> None: + frame = batch["frame_valid"].bool() + if mode == "rgb_d_k": + batch["K_input_available"] = frame.clone() + elif mode == "rgb_k": + batch["K_input_available"] = frame.clone() + batch["depth_input_available"] = torch.zeros_like(frame) + elif mode == "rgb_only": + batch["K_input_available"] = torch.zeros_like(frame) + batch["depth_input_available"] = torch.zeros_like(frame) + else: + raise ValueError(f"unsupported input mode: {mode}") + batch["K_available"] = batch["K_input_available"] + batch["depth_available"] = batch["depth_input_available"] + + +def grouped_bootstrap( + rows: list[dict[str, Any]], metric: str, seed: int, resamples: int, +) -> dict[str, float | int] | None: + groups: dict[str, list[float]] = {} + for row in rows: + value = row.get(metric) + if value is not None and math.isfinite(float(value)): + groups.setdefault(str(row["physical_recording_id"]), []).append(float(value)) + if not groups: + return None + keys = sorted(groups) + generator = np.random.default_rng(seed) + estimates = [] + for _ in range(resamples): + sampled = generator.choice(keys, size=len(keys), replace=True) + values = [value for key in sampled for value in groups[str(key)]] + estimates.append(float(np.mean(values))) + return { + "groups": len(keys), "resamples": resamples, + "estimate": float(np.mean([value for values in groups.values() for value in values])), + "ci95_low": float(np.quantile(estimates, .025)), + "ci95_high": float(np.quantile(estimates, .975)), + } + + +def metric_fields() -> tuple[str, ...]: + return ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "source_root_relative_mpjpe_mm", + "rigid_se3_mpjpe_mm", "pa_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "direct_2d_error_px", + "projected_mano_2d_error_px", "direct_mano_consistency_px", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "translation_x_signed_mm", "translation_y_signed_mm", "translation_z_signed_mm", + ) + + +def ray_depth_diagnostic_row( + prediction: dict[str, torch.Tensor], batch: dict[str, Any], + batch_index: int, frame: int, side: int, translation_valid: bool, +) -> dict[str, float | bool]: + fields: dict[str, float | bool] = { + "ray_depth_confidence": math.nan, + "ray_depth_raw_delta_z_mm": math.nan, + "ray_depth_applied_delta_z_mm": math.nan, + "ray_depth_support_count": math.nan, + "ray_depth_local_valid_fraction": math.nan, + "ray_depth_correction_valid": False, + "ray_depth_base_z_error_mm": math.nan, + "ray_depth_final_z_error_mm": math.nan, + "ray_depth_harm_mm": math.nan, + } + if "ray_depth_confidence" not in prediction: + return fields + selector = (batch_index, frame, side) + support_count = int(prediction["ray_depth_support_count"][selector]) + fields.update({ + "ray_depth_confidence": float(prediction["ray_depth_confidence"][selector]), + "ray_depth_raw_delta_z_mm": float( + prediction["ray_depth_raw_delta_z_m"][selector] * 1000.0 + ), + "ray_depth_applied_delta_z_mm": float( + prediction["ray_depth_applied_delta_z_m"][selector] * 1000.0 + ), + "ray_depth_support_count": float(support_count), + "ray_depth_local_valid_fraction": support_count / 9.0, + "ray_depth_correction_valid": bool( + prediction["ray_depth_correction_valid"][selector] + ), + }) + if translation_valid: + target_z = batch["wrist_root_translation"][selector][2] + base_error = (prediction["ray_depth_base_z_m"][selector] - target_z).abs() * 1000.0 + final_error = ( + prediction["wrist_root_translation"][selector][2] - target_z + ).abs() * 1000.0 + fields.update({ + "ray_depth_base_z_error_mm": float(base_error), + "ray_depth_final_z_error_mm": float(final_error), + "ray_depth_harm_mm": float(final_error - base_error), + }) + return fields + + +def supervision_coverage(rows: list[dict[str, Any]]) -> dict[str, float | int]: + total = len(rows) + result: dict[str, float | int] = {"hand_rows": total} + for name, field in ( + ("joint3d", "joint3d_supervision"), + ("source_root_relative", "source_root_relative_supervision"), + ("translation", "translation_supervision"), + ("vertices", "vertices_supervision"), + ): + count = sum(bool(row.get(field, False)) for row in rows) + result[f"{name}_valid_hands"] = count + result[f"{name}_valid_fraction"] = count / total if total else 0.0 + return result + + +def make_row( + prediction: dict[str, torch.Tensor], batch: dict[str, Any], + batch_index: int, frame: int, side: int, +) -> dict[str, Any]: + side_name = ("left", "right")[side] + frame_valid = bool(batch["frame_valid"][batch_index, frame]) + translation_valid = frame_valid and bool(batch["translation_valid"][batch_index, frame, side]) + joint_mask = batch["joint3d_valid"][batch_index, frame, side].bool() & frame_valid + joint2d_mask = batch["joint2d_valid"][batch_index, frame, side].bool() & frame_valid + vertices_valid = frame_valid and bool(batch["vertices_valid"][batch_index, frame, side]) + source_relative_mask = torch.zeros_like(joint_mask) + if "joint3d_root_relative_valid" in batch: + source_relative_mask = ( + batch["joint3d_root_relative_valid"][batch_index, frame, side].bool() + & frame_valid + ) + row: dict[str, Any] = { + "dataset": str(batch["dataset_id"][batch_index]), + "subject_id": str(batch["subject_id"][batch_index]), + "physical_recording_id": str(batch["physical_recording_id"][batch_index]), + "camera_id": str(batch["camera_id"][batch_index]), + "headset_id": str(batch["headset_id"][batch_index]), + "frame_id": int(batch["frame_id"][batch_index, frame]), + "side": side_name, + "joint3d_supervision": bool(joint_mask.any()), + "source_root_relative_supervision": bool(source_relative_mask.any()), + "vertices_supervision": vertices_valid, + "translation_supervision": translation_valid, + } + row.update(ray_depth_diagnostic_row( + prediction, batch, batch_index, frame, side, translation_valid, + )) + for field in metric_fields(): + row[field] = math.nan + if translation_valid: + residual_mm = ( + prediction["wrist_root_translation"][batch_index, frame, side] + - batch["wrist_root_translation"][batch_index, frame, side] + ).float().cpu().numpy() * 1000.0 + for axis_index, axis in enumerate("xyz"): + row[f"translation_{axis}_signed_mm"] = float(residual_mm[axis_index]) + row[f"translation_{axis}_mae_mm"] = float(abs(residual_mm[axis_index])) + depth = float(batch["wrist_root_translation"][batch_index, frame, side, 2]) + row["wrist_depth_m"] = depth + row["depth_bucket"] = depth_bucket(depth) + else: + row["wrist_depth_m"] = math.nan + row["depth_bucket"] = "N/A" + if joint2d_mask.any(): + visible_joint_count = int(joint2d_mask.sum()) + row["visible_joint_count"] = visible_joint_count + row["occlusion_bucket"] = ( + "severe_le7" if visible_joint_count <= 7 + else ("partial_8_15" if visible_joint_count <= 15 else "visible_ge16") + ) + target_2d = batch["joint2d"][batch_index, frame, side].float() + height, width = batch["rgb"].shape[-2:] + direct = prediction["joint2d_norm"][batch_index, frame, side].float() * target_2d.new_tensor((width, height)) + predicted_3d = prediction["joints_camera"][batch_index, frame, side].float() + projected, positive = project_points( + predicted_3d, batch["K"][batch_index, frame].float(), + ) + valid_2d = joint2d_mask & torch.isfinite(target_2d).all(-1) + projected_valid = valid_2d & positive + row["direct_2d_error_px"] = float( + torch.linalg.vector_norm(direct - target_2d, dim=-1)[valid_2d].mean() + ) + if projected_valid.any(): + row["projected_mano_2d_error_px"] = float( + torch.linalg.vector_norm(projected - target_2d, dim=-1)[projected_valid].mean() + ) + row["direct_mano_consistency_px"] = float( + torch.linalg.vector_norm(direct - projected, dim=-1)[projected_valid].mean() + ) + valid_points = target_2d[valid_2d] + extent = valid_points.max(0).values - valid_points.min(0).values + size = float(extent.max()) + row["projected_hand_size_px"] = size + row["size_bucket"] = hand_size_bucket(size) + else: + row["visible_joint_count"] = 0 + row["occlusion_bucket"] = "unlabelled" + row["projected_hand_size_px"] = math.nan + row["size_bucket"] = "N/A" + if joint_mask.any(): + predicted_joints = prediction["joints_camera"][batch_index, frame, side].float() + target_joints = batch["joint3d_camera"][batch_index, frame, side].float() + errors = torch.linalg.vector_norm(predicted_joints - target_joints, dim=-1) * 1000.0 + row["absolute_mpjpe_mm"] = float(errors[joint_mask].mean()) + relative_prediction = predicted_joints - predicted_joints[:1] + relative_target = target_joints - target_joints[:1] + relative_error = torch.linalg.vector_norm(relative_prediction - relative_target, dim=-1) * 1000.0 + row["root_relative_mpjpe_mm"] = float(relative_error[joint_mask].mean()) + tips = torch.as_tensor(TIP_INDICES, device=joint_mask.device) + tip_mask = joint_mask[tips] + if tip_mask.any(): + row["fingertip_mpjpe_mm"] = float(errors[tips][tip_mask].mean()) + if bool(joint_mask.all()): + pred_np = predicted_joints.detach().cpu().numpy()[None] + target_np = target_joints.detach().cpu().numpy()[None] + row["rigid_se3_mpjpe_mm"] = float(aligned_mpjpe_mm( + pred_np, target_np, estimate_scale=False, + )[0]) + row["pa_mpjpe_mm"] = float(aligned_mpjpe_mm( + pred_np, target_np, estimate_scale=True, + )[0]) + if source_relative_mask.any(): + predicted_joints = prediction["joints_camera"][batch_index, frame, side].float() + predicted_relative = predicted_joints - predicted_joints[:1] + target_relative = batch["joint3d_root_relative"][batch_index, frame, side].float() + source_error = torch.linalg.vector_norm( + predicted_relative - target_relative, dim=-1, + ) * 1000.0 + row["source_root_relative_mpjpe_mm"] = float( + source_error[source_relative_mask].mean() + ) + if vertices_valid: + vertex_error = torch.linalg.vector_norm( + prediction["vertices_camera"][batch_index, frame, side].float() + - batch["vertices_camera"][batch_index, frame, side].float(), dim=-1, + ) * 1000.0 + row["mpvpe_mm"] = float(vertex_error.mean()) + return row + + +def aggregate(rows: list[dict[str, Any]]) -> dict[str, Any]: + result = {field: finite_summary([row[field] for row in rows]) for field in metric_fields()} + result["supervision_coverage"] = { + "overall": supervision_coverage(rows), + "left": supervision_coverage([row for row in rows if row["side"] == "left"]), + "right": supervision_coverage([row for row in rows if row["side"] == "right"]), + } + for split_name, selector in { + "left": lambda row: row["side"] == "left", + "right": lambda row: row["side"] == "right", + "near": lambda row: row["depth_bucket"] == "near_le0.8m", + "far": lambda row: row["depth_bucket"] == "far_gt0.8m", + "small": lambda row: row["size_bucket"] == "small_lt64", + "medium": lambda row: row["size_bucket"] == "medium_64_128", + "large": lambda row: row["size_bucket"] == "large_ge128", + }.items(): + selected = [row for row in rows if selector(row)] + result[f"bucket_{split_name}"] = { + "hands": len(selected), + "supervision_coverage": supervision_coverage(selected), + "absolute_mpjpe_mm": finite_summary([row["absolute_mpjpe_mm"] for row in selected]), + "translation_z_mae_mm": finite_summary([row["translation_z_mae_mm"] for row in selected]), + "fingertip_mpjpe_mm": finite_summary([row["fingertip_mpjpe_mm"] for row in selected]), + } + for field, prefix in (("headset_id", "headset"), ("occlusion_bucket", "occlusion")): + for value in sorted({str(row[field]) for row in rows}): + selected = [row for row in rows if str(row[field]) == value] + normalized = "".join(character.lower() if character.isalnum() else "_" for character in value) + result[f"bucket_{prefix}_{normalized}"] = { + "hands": len(selected), + "supervision_coverage": supervision_coverage(selected), + "absolute_mpjpe_mm": finite_summary([ + row["absolute_mpjpe_mm"] for row in selected + ]), + "root_relative_mpjpe_mm": finite_summary([ + row["root_relative_mpjpe_mm"] for row in selected + ]), + "translation_z_mae_mm": finite_summary([ + row["translation_z_mae_mm"] for row in selected + ]), + "fingertip_mpjpe_mm": finite_summary([ + row["fingertip_mpjpe_mm"] for row in selected + ]), + } + ray_rows = [row for row in rows if math.isfinite(float(row["ray_depth_confidence"]))] + result["ray_depth_diagnostics"] = None + if ray_rows: + correction_rows = [row for row in ray_rows if row["ray_depth_correction_valid"]] + result["ray_depth_diagnostics"] = { + "hands": len(ray_rows), + "correction_valid_hands": len(correction_rows), + "correction_valid_fraction": len(correction_rows) / len(ray_rows), + "confidence": finite_summary([row["ray_depth_confidence"] for row in ray_rows]), + "raw_delta_z_mm": finite_summary([row["ray_depth_raw_delta_z_mm"] for row in ray_rows]), + "applied_delta_z_mm": finite_summary([row["ray_depth_applied_delta_z_mm"] for row in ray_rows]), + "support_count": finite_summary([row["ray_depth_support_count"] for row in ray_rows]), + "local_valid_fraction": finite_summary([ + row["ray_depth_local_valid_fraction"] for row in ray_rows + ]), + "base_z_error_mm": finite_summary([row["ray_depth_base_z_error_mm"] for row in ray_rows]), + "final_z_error_mm": finite_summary([row["ray_depth_final_z_error_mm"] for row in ray_rows]), + "harm_mm": finite_summary([row["ray_depth_harm_mm"] for row in correction_rows]), + "harm_fraction": ( + float(np.mean([row["ray_depth_harm_mm"] > 0 for row in correction_rows])) + if correction_rows else None + ), + } + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--expected-cache-manifest-sha256") + parser.add_argument("--input-mode", choices=("rgb_d_k", "rgb_k", "rgb_only"), required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument( + "--allow-physical-gpus-4-5", action="store_true", + help="Explicit resource override; default preserves the historical GPU0-3 contract.", + ) + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--evaluation-id") + parser.add_argument("--heartbeat-path", type=Path) + parser.add_argument("--heartbeat-seconds", type=float, default=30.0) + parser.add_argument( + "--evaluation-role", + choices=( + "external_heldout", "h2o_train_group_heldout", + "h2o_train_group_heldout_control", "adaptation_external_heldout", + "phase9_external_heldout", "phase9_h2o_fold_heldout", + ), + default="external_heldout", + ) + args = parser.parse_args() + if args.heartbeat_seconds < 1: + parser.error("heartbeat interval must be at least one second") + if (args.heartbeat_path is None) != (args.evaluation_id is None): + parser.error("evaluation ID and heartbeat path must be provided together") + if sha256(args.checkpoint) != args.expected_checkpoint_sha256: + parser.error("checkpoint SHA256 differs from frozen expected value") + if ( + args.expected_cache_manifest_sha256 is not None + and sha256(args.cache_manifest) != args.expected_cache_manifest_sha256 + ): + parser.error("cache manifest SHA256 differs from frozen expected value") + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + allowed_physical_gpus = {0, 1, 2, 3} + if args.allow_physical_gpus_4_5: + allowed_physical_gpus.update((4, 5)) + if args.physical_gpu_id not in allowed_physical_gpus: + parser.error("physical GPU must be one of 0-3; GPU4-5 are reserved") + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + heartbeat_path = args.heartbeat_path + if heartbeat_path is not None: + if heartbeat_path.resolve().parent != args.output_dir.resolve(): + parser.error("evaluation heartbeat must be inside the output directory") + write_progress_heartbeat(heartbeat_path, { + "status": "initializing", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "processed_clips": 0, "processed_frames": 0, + "dataloader_worker_pids": [], + }) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + dataset = CachedUnifiedClipDataset(args.cache_manifest, K_input_dropout=0.0) + write_progress_heartbeat(heartbeat_path, { + "status": "data_ready", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": 0, + "processed_frames": 0, "dataloader_worker_pids": [], + }) + loader = DataLoader( + dataset, batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).cuda().eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location="cuda") + validate_evaluation_role( + args.evaluation_role, config, + {str(row["dataset_id"]).upper() for row in dataset.rows}, + state["extra"], args.cache_manifest, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + rows: list[dict[str, Any]] = [] + raw: dict[str, list[np.ndarray]] = {} + started = time.perf_counter() + last_heartbeat = started + processed_clips = 0 + processed_frames = 0 + torch.cuda.reset_peak_memory_stats() + with torch.inference_mode(): + for batch in loader: + processed_clips += len(batch["dataset_id"]) + apply_input_mode(batch, args.input_mode) + batch = move_to_device(batch, torch.device("cuda")) + if args.evaluation_role in { + "h2o_train_group_heldout", "h2o_train_group_heldout_control", + "phase9_h2o_fold_heldout", + }: + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + processed_frames += int(batch["frame_valid"].sum()) + now = time.perf_counter() + if now - last_heartbeat >= args.heartbeat_seconds: + write_progress_heartbeat(heartbeat_path, { + "status": "running", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), + "processed_clips": processed_clips, + "processed_frames": processed_frames, + "dataloader_worker_pids": direct_child_pids(os.getpid()), + }) + last_heartbeat = now + persisted = { + "predicted_joints_camera": prediction["joints_camera"], + "predicted_vertices_camera": prediction["vertices_camera"], + "predicted_wrist_root_translation": prediction["wrist_root_translation"], + "predicted_joint2d_norm": prediction["joint2d_norm"], + "predicted_mano_rotation_matrices": prediction["mano_rotation_matrices"], + "predicted_mano_shape": prediction["mano_shape"], + "target_mano_pose": batch["mano_pose"], + "mano_pose_valid": batch["mano_pose_valid"], + "target_joints_camera": batch["joint3d_camera"], + "target_vertices_camera": batch["vertices_camera"], + "target_wrist_root_translation": batch["wrist_root_translation"], + "target_joint2d": batch["joint2d"], + "joint3d_valid": batch["joint3d_valid"], + "vertices_valid": batch["vertices_valid"], + "translation_valid": batch["translation_valid"], + "joint2d_valid": batch["joint2d_valid"], + "frame_valid": batch["frame_valid"], + "K": batch["K"], + "frame_id": batch["frame_id"], + } + if "joint3d_root_relative" in batch: + persisted.update({ + "target_joint3d_root_relative": batch["joint3d_root_relative"], + "joint3d_root_relative_valid": batch["joint3d_root_relative_valid"], + }) + for key in ( + "ray_depth_wrist2d_norm", "ray_depth_log_base_z", + "ray_depth_base_z_m", "ray_depth_raw_delta_z_m", + "ray_depth_applied_delta_z_m", "ray_depth_confidence_logit", + "ray_depth_confidence", "ray_depth_local_statistics", + "ray_depth_support_count", "ray_depth_correction_valid", + "ray_depth_K_input_available", + ): + if key in prediction: + persisted[key] = prediction[key] + append_valid_frame_arrays(raw, persisted, batch["frame_valid"]) + batch_size, time_count = batch["frame_valid"].shape + for batch_index in range(batch_size): + for frame in range(time_count): + if not bool(batch["frame_valid"][batch_index, frame]): + continue + for side in range(2): + rows.append(make_row(prediction, batch, batch_index, frame, side)) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + write_progress_heartbeat(heartbeat_path, { + "status": "finalizing", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": processed_clips, + "processed_frames": processed_frames, + "dataloader_worker_pids": direct_child_pids(os.getpid()), + }) + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed(raw_path, **{ + key: np.concatenate(values, axis=0) for key, values in raw.items() + }) + row_path = args.output_dir / "per_hand_frame_metrics.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + take_rows = [] + for take in sorted({str(row["physical_recording_id"]) for row in rows}): + selected = [row for row in rows if row["physical_recording_id"] == take] + record: dict[str, Any] = {"physical_recording_id": take, "hands": len(selected)} + for field in metric_fields(): + summary = finite_summary([row[field] for row in selected]) + record[field] = summary["mean"] if summary is not None else math.nan + take_rows.append(record) + take_path = args.output_dir / "take_metrics.csv" + with take_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(take_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(take_rows) + bootstrap = { + field: grouped_bootstrap(rows, field, int(config["seed"]), args.bootstrap_resamples) + for field in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "source_root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + report = { + "status": { + "external_heldout": "evaluated", + "h2o_train_group_heldout": "evaluated_h2o_train_group_heldout", + "h2o_train_group_heldout_control": "evaluated_h2o_train_group_heldout_control", + "adaptation_external_heldout": "evaluated_adaptation_external_heldout", + "phase9_external_heldout": "evaluated_phase9_external_heldout", + "phase9_h2o_fold_heldout": "evaluated_phase9_h2o_fold_heldout", + }[args.evaluation_role], + "evaluation_role": args.evaluation_role, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "experiment": config["name"], "checkpoint_step": int(state["step"]), + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": args.expected_checkpoint_sha256}, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "cache_manifest": {"path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest)}, + "input_mode": args.input_mode, "clips": len(dataset), "frames": processed_frames, + "hands_rows": len(rows), "metrics": aggregate(rows), "grouped_bootstrap_ci": bootstrap, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": processed_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + }, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "raw_prediction_layout": "axis0 is the ordered sequence of frame_valid=true frames", + "per_hand_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "take_metrics": {"path": str(take_path.resolve()), "sha256": sha256(take_path)}, + "official_test_used": False, + "h2o_training_data_used": checkpoint_h2o_training_data_used(state["extra"]), + "h2o_official_validation_used": False, + "oracle_information_used": False, + "metric_definitions": { + "rigid_se3_mpjpe_mm": "per-hand Kabsch; removes translation and rotation", + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation and scale", + }, + } + output = args.output_dir / "evaluation.json" + output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + write_progress_heartbeat(heartbeat_path, { + "status": "complete", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": processed_clips, + "processed_frames": processed_frames, + "evaluation_report": str(output.resolve()), + "evaluation_report_sha256": sha256(output), + "dataloader_worker_pids": [], + }) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase7_h2o_zero_shot.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase7_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..dde27a07128671619a11c73262c329644068bc26 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase7_h2o_zero_shot.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Strict one-shot H2O validation evaluation of a frozen external generalist.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.evaluate_phase7_external import ( + aggregate, + apply_input_mode, + finite_summary, + grouped_bootstrap, + make_row, + metric_fields, + sha256, + tensor_to_numpy, +) +from scripts.train_experiment import attach_gt_vertices, move_to_device +from scripts.train_phase7_external import assert_physical_gpu_idle + + +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") +EVALUATION_ROLES = ( + "strict_external_zero_shot", "h2o_adapted_formal", + "phase9_unified_formal", +) + + +def validate_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + status = record.get("status") + if status not in { + "external_generalist_frozen", "external_architecture_candidate_frozen", + }: + raise ValueError("external checkpoint is not frozen") + if status == "external_architecture_candidate_frozen" and ( + record.get("selected_within_family") is not True + or record.get("overall_external_generalist_winner") is not False + ): + raise ValueError("external architecture candidate role is ambiguous") + if record.get("checkpoint_sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen external generalist") + if record.get("official_test_used") is not False: + raise ValueError("freeze record must explicitly exclude official test") + if record.get("h2o_official_validation_used_for_external_selection") is not False: + raise ValueError("external selection must precede H2O validation access") + if not record.get("external_selection_sha256"): + raise ValueError("freeze record lacks external selection SHA256") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from freeze record") + + +def validate_adaptation_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + if record.get("status") != "h2o_adaptation_candidate_frozen": + raise ValueError("H2O adaptation candidate is not frozen") + checkpoint = record.get("checkpoint", {}) + if checkpoint.get("sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen adaptation candidate") + if record.get("h2o_official_validation_used_for_selection") is not False: + raise ValueError("adaptation selection must use H2O train-heldout only") + if record.get("official_test_used") is not False: + raise ValueError("adaptation freeze record must explicitly exclude official test") + if not record.get("adaptation_selection_sha256"): + raise ValueError("adaptation freeze record lacks selection SHA256") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from adaptation freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from adaptation freeze record") + + +def validate_phase9_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + if record.get("status") != "phase9_final_unified_checkpoint_frozen": + raise ValueError("Phase 9 final unified checkpoint is not frozen") + if record.get("checkpoint", {}).get("sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen Phase 9 final checkpoint") + if ( + record.get("selection_complete") is not True + or record.get("stage9_final_decision_complete") is not True + or record.get("h2o_official_validation_used_for_selection") is not False + or record.get("official_test_used") is not False + or not record.get("selection_chain_sha256") + ): + raise ValueError("Phase 9 final selection provenance is incomplete") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from Phase 9 freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from Phase 9 freeze record") + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"cannot write empty metric rows: {path}") + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(rows) + + +def append_valid_frame_arrays( + raw: dict[str, list[np.ndarray]], values: dict[str, torch.Tensor], + frame_valid: torch.Tensor, +) -> None: + """Persist variable-length clips as one contiguous valid-frame axis.""" + + valid = tensor_to_numpy(frame_valid.bool()).reshape(-1) + batch, time = frame_valid.shape + for key, value in values.items(): + array = tensor_to_numpy(value) + if array.shape[:2] != (batch, time): + raise ValueError(f"raw temporal field shape differs from frame_valid: {key}") + flattened = array.reshape(batch * time, *array.shape[2:]) + raw.setdefault(key, []).append(flattened[valid]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--input-mode", choices=INPUT_MODES, required=True) + parser.add_argument( + "--evaluation-role", choices=EVALUATION_ROLES, + default="strict_external_zero_shot", + ) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--frame-stride", type=int, default=1) + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.physical_gpu_id not in {0, 1, 2, 3}: + parser.error("physical GPU must be one of 0-3; GPU4-5 are reserved") + import os + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + if sha256(args.checkpoint) != args.expected_checkpoint_sha256: + parser.error("checkpoint SHA256 differs from frozen expected value") + freeze_record = json.loads(args.freeze_record.read_text(encoding="utf-8")) + if args.evaluation_role == "strict_external_zero_shot": + validate_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + elif args.evaluation_role == "h2o_adapted_formal": + validate_adaptation_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + else: + validate_phase9_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + expected_branch = { + "strict_external_zero_shot": "external_only", + "h2o_adapted_formal": "h2o_adaptation", + "phase9_unified_formal": "phase9_unified", + }[args.evaluation_role] + if config.get("experiment", {}).get("branch") != expected_branch: + raise ValueError(f"checkpoint config branch is not {expected_branch}") + dataset = H2OCam4Dataset( + args.root, args.manifest, + target_hw=tuple(config["data"]["resolution_hw"]), + clip_lengths=(args.clip_length,), strides=(args.frame_stride,), + ) + loader = DataLoader( + dataset, batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).cuda().eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location="cuda") + expected_h2o_training = args.evaluation_role != "strict_external_zero_shot" + if state["extra"].get("h2o_training_data_used") is not expected_h2o_training: + raise ValueError("checkpoint H2O-training provenance differs from evaluation role") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + rows: list[dict[str, Any]] = [] + raw: dict[str, list[np.ndarray]] = {} + processed_frames = 0 + started = time.perf_counter() + torch.cuda.reset_peak_memory_stats() + with torch.inference_mode(): + for batch in loader: + apply_input_mode(batch, args.input_mode) + batch = move_to_device(batch, torch.device("cuda")) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + processed_frames += int(batch["frame_valid"].sum()) + persisted = { + "predicted_joints_camera": prediction["joints_camera"], + "predicted_vertices_camera": prediction["vertices_camera"], + "predicted_wrist_root_translation": prediction["wrist_root_translation"], + "predicted_joint2d_norm": prediction["joint2d_norm"], + "predicted_mano_rotation_matrices": prediction["mano_rotation_matrices"], + "predicted_mano_shape": prediction["mano_shape"], + "target_joints_camera": batch["joint3d_camera"], + "target_vertices_camera": batch["vertices_camera"], + "target_wrist_root_translation": batch["wrist_root_translation"], + "target_joint2d": batch["joint2d"], + "joint3d_valid": batch["joint3d_valid"], + "vertices_valid": batch["vertices_valid"], + "translation_valid": batch["translation_valid"], + "joint2d_valid": batch["joint2d_valid"], + "frame_valid": batch["frame_valid"], + "K": batch["K"], + "frame_id": batch["frame_id"], + } + append_valid_frame_arrays(raw, persisted, batch["frame_valid"]) + batch_size, time_count = batch["frame_valid"].shape + for batch_index in range(batch_size): + for frame in range(time_count): + if not bool(batch["frame_valid"][batch_index, frame]): + continue + for side in range(2): + rows.append(make_row(prediction, batch, batch_index, frame, side)) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed(raw_path, **{ + key: np.concatenate(values, axis=0) for key, values in raw.items() + }) + row_path = args.output_dir / "per_hand_frame_metrics.csv" + write_csv(row_path, rows) + take_rows = [] + for take in sorted({str(row["physical_recording_id"]) for row in rows}): + selected = [row for row in rows if row["physical_recording_id"] == take] + record: dict[str, Any] = {"physical_recording_id": take, "hands": len(selected)} + for field in metric_fields(): + summary = finite_summary([row[field] for row in selected]) + record[field] = summary["mean"] if summary is not None else math.nan + take_rows.append(record) + take_path = args.output_dir / "take_metrics.csv" + write_csv(take_path, take_rows) + bootstrap = { + field: grouped_bootstrap( + rows, field, int(config["seed"]), args.bootstrap_resamples, + ) + for field in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + report = { + "status": { + "strict_external_zero_shot": "evaluated_strict_h2o_zero_shot", + "h2o_adapted_formal": "evaluated_h2o_adapted_formal", + "phase9_unified_formal": "evaluated_phase9_unified_formal", + }[args.evaluation_role], + "evaluation_role": args.evaluation_role, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "experiment": config["name"], "checkpoint_step": int(state["step"]), + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": args.expected_checkpoint_sha256, + }, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "freeze_record": { + "path": str(args.freeze_record.resolve()), "sha256": sha256(args.freeze_record), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "input_mode": args.input_mode, "clips": len(dataset), "frames": processed_frames, + "hands_rows": len(rows), "metrics": aggregate(rows), + "grouped_bootstrap_ci": bootstrap, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": processed_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + }, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "raw_prediction_layout": "axis0 is the ordered sequence of frame_valid=true frames", + "per_hand_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "take_metrics": {"path": str(take_path.resolve()), "sha256": sha256(take_path)}, + "h2o_training_data_used": expected_h2o_training, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + "oracle_information_used": False, + "metric_definitions": { + "rigid_se3_mpjpe_mm": "per-hand Kabsch; removes translation and rotation", + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation and scale", + }, + } + output = args.output_dir / "evaluation.json" + output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase8_translation_oracles.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase8_translation_oracles.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3f03e6d4363d51d6d533cf00426e064d9d61b4 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_phase8_translation_oracles.py @@ -0,0 +1,355 @@ +#!/usr/bin/env python3 +"""Evaluation-only ray/z/root-relative decomposition from persisted predictions.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +CONDITIONS = ( + "raw", + "predicted_pose_shape_gt_translation", + "predicted_ray_gt_z", + "gt_ray_predicted_z", + "predicted_root_relative_gt_translation", + "predicted_translation_gt_root_relative", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def flatten_leading(array: np.ndarray, trailing_dimensions: int) -> np.ndarray: + trailing = array.shape[-trailing_dimensions:] + return array.reshape(-1, *trailing) + + +def axis_angle_to_matrix(axis_angle: np.ndarray) -> np.ndarray: + angle = np.linalg.norm(axis_angle, axis=-1) + safe = np.maximum(angle, 1e-12) + axis = axis_angle / safe[..., None] + x, y, z = np.moveaxis(axis, -1, 0) + zero = np.zeros_like(x) + skew = np.stack(( + zero, -z, y, z, zero, -x, -y, x, zero, + ), axis=-1).reshape(*axis.shape[:-1], 3, 3) + identity = np.broadcast_to(np.eye(3), skew.shape) + matrix = ( + identity + np.sin(angle)[..., None, None] * skew + + (1.0 - np.cos(angle))[..., None, None] * (skew @ skew) + ) + return np.where((angle < 1e-12)[..., None, None], identity, matrix) + + +def decompose(arrays: dict[str, np.ndarray]) -> dict[str, Any]: + pred_joints = flatten_leading(arrays["predicted_joints_camera"], 3) + target_joints = flatten_leading(arrays["target_joints_camera"], 3) + pred_translation = flatten_leading( + arrays["predicted_wrist_root_translation"], 2, + ) + target_translation = flatten_leading( + arrays["target_wrist_root_translation"], 2, + ) + joint_valid = flatten_leading(arrays["joint3d_valid"], 2).astype(bool) + translation_valid = flatten_leading( + arrays["translation_valid"], 1, + ).astype(bool) + if not ( + pred_joints.shape[:2] == target_joints.shape[:2] + == pred_translation.shape[:2] == target_translation.shape[:2] + == joint_valid.shape[:2] + ): + raise ValueError("raw prediction arrays do not share frame/hand axes") + pred_relative = pred_joints - pred_joints[..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + pred_z = pred_translation[..., 2] + target_z = target_translation[..., 2] + safe_pred_z = np.where(np.abs(pred_z) > 1e-6, pred_z, np.nan) + safe_target_z = np.where(np.abs(target_z) > 1e-6, target_z, np.nan) + pred_ray = pred_translation[..., :2] / safe_pred_z[..., None] + target_ray = target_translation[..., :2] / safe_target_z[..., None] + pred_ray_gt_z_translation = np.concatenate( + (pred_ray * target_z[..., None], target_z[..., None]), axis=-1, + ) + gt_ray_pred_z_translation = np.concatenate( + (target_ray * pred_z[..., None], pred_z[..., None]), axis=-1, + ) + condition_joints = { + "raw": pred_joints, + "predicted_pose_shape_gt_translation": ( + pred_relative + target_translation[..., None, :] + ), + "predicted_ray_gt_z": ( + pred_relative + pred_ray_gt_z_translation[..., None, :] + ), + "gt_ray_predicted_z": ( + pred_relative + gt_ray_pred_z_translation[..., None, :] + ), + "predicted_root_relative_gt_translation": ( + pred_relative + target_translation[..., None, :] + ), + "predicted_translation_gt_root_relative": ( + target_relative + pred_translation[..., None, :] + ), + } + condition_errors: dict[str, np.ndarray] = {} + annotation_valid = joint_valid.any(axis=-1) & translation_valid + positive_depth = ( + np.isfinite(pred_z) & np.isfinite(target_z) + & (pred_z > 0.05) & (target_z > 0.05) + ) + hand_valid = annotation_valid & positive_depth + for name, joints in condition_joints.items(): + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + numerator = np.where(joint_valid, joint_error, 0.0).sum(axis=-1) + denominator = joint_valid.sum(axis=-1) + error = numerator / np.maximum(denominator, 1) + condition_errors[name] = np.where(hand_valid, error, np.nan) + translation_residual = (pred_translation - target_translation) * 1000.0 + ray_residual = pred_ray - target_ray + result = { + "condition_errors_mm": condition_errors, + "translation_residual_mm": translation_residual, + "ray_residual": ray_residual, + "predicted_z_m": pred_z, + "target_z_m": target_z, + "valid": hand_valid, + "annotation_valid": annotation_valid, + "positive_depth": positive_depth, + } + if "K" in arrays: + K = flatten_leading(arrays["K"], 2) + if K.shape[0] != hand_valid.shape[0]: + raise ValueError("K frame axis differs from prediction frame axis") + result["K"] = np.broadcast_to(K[:, None], (*hand_valid.shape, 3, 3)) + if {"predicted_mano_rotation_matrices", "target_mano_pose", "mano_pose_valid"}.issubset(arrays): + predicted_rotation = flatten_leading( + arrays["predicted_mano_rotation_matrices"], 4, + )[..., 0, :, :] + target_pose = flatten_leading(arrays["target_mano_pose"], 2) + pose_valid = flatten_leading(arrays["mano_pose_valid"], 1).astype(bool) + target_rotation = axis_angle_to_matrix(target_pose[..., :3]) + relative = predicted_rotation @ np.swapaxes(target_rotation, -1, -2) + cosine = np.clip( + (np.trace(relative, axis1=-2, axis2=-1) - 1.0) / 2.0, + -1.0, 1.0, + ) + result["global_orientation_geodesic_deg"] = np.degrees(np.arccos(cosine)) + result["global_orientation_valid"] = pose_valid + return result + + +def finite_summary(values: np.ndarray) -> dict[str, float | int] | None: + values = np.asarray(values, dtype=np.float64) + values = values[np.isfinite(values)] + if not values.size: + return None + return { + "count": int(values.size), "mean": float(values.mean()), + "median": float(np.median(values)), + "p95": float(np.quantile(values, 0.95)), + } + + +def correlation(x: np.ndarray, y: np.ndarray, valid: np.ndarray) -> float | None: + mask = valid & np.isfinite(x) & np.isfinite(y) + if mask.sum() < 2 or np.std(x[mask]) == 0 or np.std(y[mask]) == 0: + return None + return float(np.corrcoef(x[mask], y[mask])[0, 1]) + + +def build_report(result: dict[str, Any]) -> dict[str, Any]: + errors = result["condition_errors_mm"] + raw_mean = float(np.nanmean(errors["raw"])) + conditions = {} + for name in CONDITIONS: + summary = finite_summary(errors[name]) + if summary is None: + conditions[name] = None + continue + gain = raw_mean - float(summary["mean"]) + conditions[name] = { + **summary, "gain_vs_raw_mm": gain, + "gain_vs_raw_percent": 100.0 * gain / raw_mean, + } + fix_z_gain = raw_mean - float(np.nanmean(errors["predicted_ray_gt_z"])) + fix_ray_gain = raw_mean - float(np.nanmean(errors["gt_ray_predicted_z"])) + fix_translation_gain = raw_mean - float(np.nanmean( + errors["predicted_root_relative_gt_translation"], + )) + interaction = fix_translation_gain - fix_z_gain - fix_ray_gain + residual = result["translation_residual_mm"] + valid = result["valid"] + axis = { + name: { + "signed_mm": finite_summary(residual[..., index][valid]), + "absolute_mm": finite_summary(np.abs(residual[..., index][valid])), + } + for index, name in enumerate("xyz") + } + axis["correlation"] = { + "x_y": correlation(residual[..., 0], residual[..., 1], valid), + "x_z": correlation(residual[..., 0], residual[..., 2], valid), + "y_z": correlation(residual[..., 1], residual[..., 2], valid), + } + orientation = result.get("global_orientation_geodesic_deg") + orientation_valid = result.get("global_orientation_valid") + return { + "status": "evaluated_oracle_diagnostic_only", + "deployable_claim": False, + "selection_use": False, + "official_test_used": False, + "validity_audit": { + "annotation_valid_hands": int(result["annotation_valid"].sum()), + "positive_depth_hands": int(result["valid"].sum()), + "excluded_nonpositive_or_near_depth": int( + (result["annotation_valid"] & ~result["positive_depth"]).sum() + ), + "minimum_ray_depth_m": 0.05, + }, + "conditions": conditions, + "translation_attribution": { + "fix_z_gain_mm": fix_z_gain, + "fix_ray_gain_mm": fix_ray_gain, + "fix_all_translation_gain_mm": fix_translation_gain, + "nonadditive_interaction_mm": interaction, + "note": "Counterfactual gains are not assumed additive; interaction is reported explicitly.", + }, + "translation_axis_error": axis, + "ray_residual_norm": finite_summary( + np.linalg.norm(result["ray_residual"], axis=-1)[valid], + ), + "global_orientation_geodesic_deg": ( + finite_summary(orientation[orientation_valid]) + if orientation is not None and orientation_valid is not None else None + ), + } + + +def bucket_report(result: dict[str, Any], rows: list[dict[str, Any]]) -> dict[str, Any]: + shape = result["valid"].shape + flat_rows = np.asarray(rows, dtype=object).reshape(shape) + target_z = result["target_z_m"] + selectors: dict[str, np.ndarray] = { + "side_left": np.vectorize(lambda row: row.get("side") == "left")(flat_rows), + "side_right": np.vectorize(lambda row: row.get("side") == "right")(flat_rows), + "depth_near_le0.5m": target_z <= 0.5, + "depth_mid_0.5_0.8m": (target_z > 0.5) & (target_z <= 0.8), + "depth_far_gt0.8m": target_z > 0.8, + } + for size in ("small_lt64", "medium_64_128", "large_ge128"): + selectors[f"size_{size}"] = np.vectorize( + lambda row, expected=size: row.get("size_bucket") == expected, + )(flat_rows) + K = result.get("K") + if K is not None: + focal = np.sqrt(K[..., 0, 0] * K[..., 1, 1]) + finite = focal[result["valid"] & np.isfinite(focal)] + if finite.size: + low, high = np.quantile(finite, (1.0 / 3.0, 2.0 / 3.0)) + selectors["focal_low"] = focal <= low + selectors["focal_mid"] = (focal > low) & (focal <= high) + selectors["focal_high"] = focal > high + errors = result["condition_errors_mm"] + output: dict[str, Any] = {} + for name, selector in selectors.items(): + mask = result["valid"] & selector + raw = finite_summary(errors["raw"][mask]) + if raw is None: + output[name] = None + continue + raw_mean = float(raw["mean"]) + output[name] = { + "raw_absolute_mpjpe_mm": raw, + "fix_z_gain_mm": raw_mean - float(np.nanmean(errors["predicted_ray_gt_z"][mask])), + "fix_ray_gain_mm": raw_mean - float(np.nanmean(errors["gt_ray_predicted_z"][mask])), + "fix_translation_gain_mm": raw_mean - float(np.nanmean( + errors["predicted_root_relative_gt_translation"][mask], + )), + } + output["occlusion"] = { + "status": "N/A" if not any("occlusion_bucket" in row for row in rows) else "available", + "reason": "Phase 7 per-hand rows do not persist a common occlusion bucket", + } + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--raw-predictions", type=Path, required=True) + parser.add_argument("--per-hand-rows", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + args.output_dir.mkdir(parents=True, exist_ok=True) + with np.load(args.raw_predictions) as loaded: + result = decompose({key: loaded[key] for key in loaded.files}) + rows = list(csv.DictReader(args.per_hand_rows.open(encoding="utf-8"))) + flat_count = result["valid"].size + if len(rows) != flat_count: + raise ValueError( + f"per-hand rows ({len(rows)}) differ from raw frame-hand count ({flat_count})" + ) + errors = result["condition_errors_mm"] + output_rows = [] + for index, row in enumerate(rows): + record = { + key: row.get(key, "") for key in ( + "dataset", "subject_id", "physical_recording_id", "camera_id", + "frame_id", "side", "depth_bucket", "size_bucket", + ) + } + flat_index = np.unravel_index(index, result["valid"].shape) + for condition in CONDITIONS: + record[f"{condition}_absolute_mpjpe_mm"] = float( + errors[condition][flat_index] + ) + for axis_index, axis in enumerate("xyz"): + record[f"translation_{axis}_signed_mm"] = float( + result["translation_residual_mm"][flat_index][axis_index] + ) + record["target_wrist_depth_m"] = float(result["target_z_m"][flat_index]) + record["predicted_wrist_depth_m"] = float(result["predicted_z_m"][flat_index]) + record["ray_residual_norm"] = float(np.linalg.norm(result["ray_residual"][flat_index])) + if "K" in result: + record["fx_px"] = float(result["K"][flat_index][0, 0]) + record["fy_px"] = float(result["K"][flat_index][1, 1]) + output_rows.append(record) + csv_path = args.output_dir / "per_hand_oracle_decomposition.csv" + with csv_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(output_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(output_rows) + report = build_report(result) + report["buckets"] = bucket_report(result, rows) + report.update({ + "raw_predictions": { + "path": str(args.raw_predictions.resolve()), + "sha256": sha256(args.raw_predictions), + }, + "per_hand_input": { + "path": str(args.per_hand_rows.resolve()), + "sha256": sha256(args.per_hand_rows), + }, + "per_hand_output": {"path": str(csv_path.resolve()), "sha256": sha256(csv_path)}, + }) + path = args.output_dir / "oracle_decomposition.json" + path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_sota_bundle.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_sota_bundle.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a226aebdf5591829184aa3e54525238a05d83a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_sota_bundle.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Evaluate one standardized external-model prediction bundle on H2O.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + evaluate_prediction_bundle, + write_csv_rows, +) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--prediction", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument( + "--pixel-scale", + type=float, + default=0.5, + help="Map raw H2O pixels to the Phase 3 640x368 evaluation scale.", + ) + parser.add_argument("--temporal-clip-length", type=int, default=8) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + prediction = PredictionBundle.load(args.prediction) + ground_truth = GroundTruthBundle.load(args.ground_truth) + report, frame_rows, temporal_rows = evaluate_prediction_bundle( + prediction, + ground_truth, + bootstrap_seed=args.bootstrap_seed, + bootstrap_samples=args.bootstrap_samples, + pixel_scale=args.pixel_scale, + temporal_clip_length=args.temporal_clip_length, + ) + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + write_csv_rows(args.output_dir / "per_hand_frame_metrics.csv", frame_rows) + write_csv_rows(args.output_dir / "per_temporal_transition_metrics.csv", temporal_rows) + print(json.dumps({ + "model": report["model_name"], + "coverage": report["coverage"]["hand_frame_fraction"], + "absolute_mpjpe_mm": report["metrics_success_conditioned"][ + "absolute_mpjpe_mm" + ]["mean"], + "root_relative_mpjpe_mm": report["metrics_success_conditioned"][ + "root_relative_mpjpe_mm" + ]["mean"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_tiny.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_tiny.py new file mode 100644 index 0000000000000000000000000000000000000000..d1416cb0dd5df06fc941ee11a654e30062cf3517 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/evaluate_tiny.py @@ -0,0 +1,426 @@ +#!/usr/bin/env python3 +"""Deterministic full tiny-set evaluation and visualization.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path + +import cv2 +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def draw_points(image: np.ndarray, points: np.ndarray, color: tuple[int, int, int], marker: bool) -> None: + for point in points: + if not np.isfinite(point).all(): + continue + xy = tuple(np.rint(point).astype(int)) + if marker: + cv2.drawMarker(image, xy, color, cv2.MARKER_CROSS, 8, 1) + else: + cv2.circle(image, xy, 3, color, -1) + + +def mean(values: list[float]) -> float | None: + return float(np.mean(values)) if values else None + + +def image_size_bucket(max_side_px: float) -> str: + if max_side_px < 64: + return "small_lt64px" + if max_side_px < 128: + return "medium_64_128px" + return "large_ge128px" + + +def depth_bucket(depth_m: float) -> str: + if depth_m < 0.5: + return "near_lt0.5m" + if depth_m < 0.8: + return "middle_0.5_0.8m" + return "far_ge0.8m" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--train-log", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args(); args.output_dir.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=args.max_clips, + oracle_crop_enabled=( + config["model"].get("oracle_crop_mode", "none") != "none" + ), + ) + loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_h2o_clips) + model_config = ModelConfig(**config["model"], dinov3_source=assets["dinov3_source"], dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"]) + device = torch.device(f"cuda:{args.gpu}") + model = BimanualReconstructionModel(model_config).to(device).eval() + load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + + values: dict[str, list[float]] = defaultdict(list) + loss_values: dict[str, list[float]] = defaultdict(list) + frame_rows: list[dict[str, object]] = [] + saved_overlays: list[Path] = [] + attention_same_peak = [] + attention_cosine = [] + depth_attention_same_peak = [] + temporal_attention_diagonal = [] + temporal_attention_entropy = [] + bimanual_cross_attention = [] + depth_gates = [] + raw_depth_gates = [] + rgb_update_norms = [] + depth_update_norms = [] + gated_depth_update_norms = [] + structured_diagnostics: dict[str, list[float]] = defaultdict(list) + visualization_index = 0 + saved_sequence_diagnostics = False + frame_count = 0 + bucket_values: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + + with torch.inference_mode(): + for batch in loader: + batch = {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + gt_vertices, _ = model.mano_layer( + axis_angle_to_matrix(pose), torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + mano_valid = (batch["mano_annotation_valid"].bool() & batch["frame_valid"].bool()[..., None])[..., None, None] + batch["vertices_camera"] = torch.where(mano_valid, gt_vertices, torch.full_like(gt_vertices, torch.nan)) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + for key, value in losses.items(): + loss_values[key].append(float(value)) + + frame_valid = batch["frame_valid"].bool() + frame_count += int(frame_valid.sum()) + ann = batch["joint_annotation_valid"].bool() & frame_valid[..., None] + joint_valid = batch["joint_element_valid"].bool() & ann[..., None] + target_joints = torch.nan_to_num(batch["joint3d_camera"]) + joint_error = torch.linalg.vector_norm(prediction["joints_camera"] - target_joints, dim=-1) * 1000 + pred_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + relative_error = torch.linalg.vector_norm(pred_relative - target_relative, dim=-1) * 1000 + translation_error = (prediction["wrist_root_translation"] - torch.nan_to_num(batch["wrist_root_translation"])).abs() * 1000 + height, width = map(int, batch["image_hw"][0].tolist()) + predicted_2d = prediction["joint2d_norm"] * torch.tensor((width, height), device=device) + target_2d = torch.nan_to_num(batch["joint2d"]) + error_2d = torch.linalg.vector_norm(predicted_2d - target_2d, dim=-1) + if "structured_translation_delta" in prediction: + valid_hands = frame_valid[..., None].expand(-1, -1, 2) + structured_diagnostics["translation_delta_norm_mm"].extend( + ( + torch.linalg.vector_norm( + prediction["structured_translation_delta"], dim=-1, + )[valid_hands] * 1000.0 + ).float().cpu().tolist() + ) + structured_diagnostics["rotation_delta_norm_deg"].extend( + ( + torch.linalg.vector_norm( + prediction["structured_rotation_delta_axis_angle"], dim=-1, + )[valid_hands[..., None].expand(-1, -1, -1, 16)] + * (180.0 / np.pi) + ).float().cpu().tolist() + ) + structured_diagnostics["shape_delta_abs"].extend( + prediction["structured_shape_delta"].abs().reshape(-1).float().cpu().tolist() + ) + pixel_scale = torch.tensor((width, height), device=device) + structured_diagnostics["joint2d_delta_px"].extend( + torch.linalg.vector_norm( + prediction["structured_joint2d_delta"] * pixel_scale, + dim=-1, + )[valid_hands[..., None].expand(-1, -1, -1, 21)].float().cpu().tolist() + ) + structured_diagnostics["sample_offset_norm_px"].extend( + torch.linalg.vector_norm( + prediction["structured_sample_offsets"] * pixel_scale, + dim=-1, + )[frame_valid[..., None, None, None].expand( + -1, -1, 2, 7, prediction["structured_sample_offsets"].shape[-2], + )].float().cpu().tolist() + ) + + if not saved_sequence_diagnostics: + subject = batch["subject_id"][0] + sequence = batch["sequence_id"][0] + title_prefix = f"{config['name']} | {subject}/{sequence}" + if "temporal_attention" in prediction["attention"]: + temporal_plot = prediction["attention"]["temporal_attention"][0, -1].float().cpu().numpy() + fig, axes = plt.subplots(1, 2, figsize=(9, 4)) + for hand, side in enumerate(("left", "right")): + axes[hand].imshow(temporal_plot[hand], vmin=0, vmax=max(float(temporal_plot.max()), 1e-8), cmap="viridis") + axes[hand].set_title(f"{side} temporal attention") + axes[hand].set_xlabel("key frame") + axes[hand].set_ylabel("query frame") + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_temporal_attention.png", dpi=160) + plt.close(fig) + valid_times = frame_valid[0].cpu().numpy() + time_axis = np.arange(int(valid_times.sum())) + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for hand, side in enumerate(("left", "right")): + hand_valid = ann[0, :, hand].cpu().numpy() & valid_times + pred_z = prediction["wrist_root_translation"][0, :, hand, 2].float().cpu().numpy()[valid_times] + gt_z = batch["wrist_root_translation"][0, :, hand, 2].float().cpu().numpy()[valid_times] + axes[0].plot(time_axis, pred_z, label=f"{side} pred") + axes[0].plot(time_axis[hand_valid[valid_times]], gt_z[hand_valid[valid_times]], "--", label=f"{side} GT") + per_frame = joint_error[0, :, hand].mean(-1).float().cpu().numpy()[valid_times] + axes[1].plot(time_axis[hand_valid[valid_times]], per_frame[hand_valid[valid_times]], label=side) + axes[0].set_title("Camera-space wrist z") + axes[0].set_ylabel("meters") + axes[1].set_title("Per-frame absolute MPJPE") + axes[1].set_ylabel("mm") + for axis in axes: + axis.set_xlabel("frame in clip") + axis.grid(alpha=0.25) + axis.legend() + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_translation_and_mpjpe.png", dpi=160) + plt.close(fig) + if "depth_fusion_gate" in prediction["attention"]: + gates = prediction["attention"]["depth_fusion_gate"][0, :, :, :, 0].float().cpu().numpy() + fig, axes = plt.subplots(1, 2, figsize=(10, 4)) + for hand, side in enumerate(("left", "right")): + for layer in range(gates.shape[0]): + axes[hand].plot(gates[layer, valid_times, hand], label=f"layer {layer}") + axes[hand].set_title(f"{side} depth gate") + axes[hand].set_xlabel("frame in clip") + axes[hand].set_ylim(0, 1) + axes[hand].grid(alpha=0.25) + axes[hand].legend() + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_depth_gate.png", dpi=160) + plt.close(fig) + saved_sequence_diagnostics = True + + for hand, side in enumerate(("left", "right")): + mask = joint_valid[..., hand, :] + values[f"{side}_absolute_mpjpe_mm"].extend(joint_error[..., hand, :][mask].float().cpu().tolist()) + values[f"{side}_root_relative_mpjpe_mm"].extend(relative_error[..., hand, :][mask].float().cpu().tolist()) + values[f"{side}_joint2d_error_px"].extend(error_2d[..., hand, :][mask].float().cpu().tolist()) + hand_mask = ann[..., hand] + for axis_index, axis in enumerate("xyz"): + values[f"{side}_translation_{axis}_mae_mm"].extend(translation_error[..., hand, axis_index][hand_mask].float().cpu().tolist()) + + rgb_attention = prediction["attention"]["rgb_cross_attention"][:, -1] + left_attention, right_attention = rgb_attention[..., 0, :], rgb_attention[..., 1, :] + valid_flat = frame_valid + attention_same_peak.extend((left_attention.argmax(-1) == right_attention.argmax(-1))[valid_flat].cpu().tolist()) + cosine = torch.nn.functional.cosine_similarity(left_attention, right_attention, dim=-1) + attention_cosine.extend(cosine[valid_flat].float().cpu().tolist()) + if "depth_fusion_gate" in prediction["attention"]: + depth_gates.extend(prediction["attention"]["depth_fusion_gate"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + raw_depth_gates.extend(prediction["attention"]["depth_fusion_gate_raw"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + depth_update_norms.extend(prediction["attention"]["depth_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + gated_depth_update_norms.extend(prediction["attention"]["gated_depth_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + depth_attention = prediction["attention"]["depth_cross_attention"][:, -1] + depth_attention_same_peak.extend( + (depth_attention[..., 0, :].argmax(-1) == depth_attention[..., 1, :].argmax(-1))[frame_valid].cpu().tolist() + ) + rgb_update_norms.extend(prediction["attention"]["rgb_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + + if "temporal_attention" in prediction["attention"]: + temporal = prediction["attention"]["temporal_attention"][:, -1] + for batch_index in range(temporal.shape[0]): + valid_indices = torch.where(frame_valid[batch_index])[0] + for hand_index in range(2): + for query_index in valid_indices: + weights = temporal[batch_index, hand_index, query_index, valid_indices].float() + weights = weights / weights.sum().clamp_min(1e-8) + temporal_attention_diagonal.append(float(temporal[batch_index, hand_index, query_index, query_index])) + if weights.numel() > 1: + entropy = -(weights * weights.clamp_min(1e-8).log()).sum() / np.log(weights.numel()) + temporal_attention_entropy.append(float(entropy)) + if "bimanual_attention" in prediction["attention"]: + bimanual = prediction["attention"]["bimanual_attention"][:, -1] + cross = 0.5 * (bimanual[..., 0, 1] + bimanual[..., 1, 0]) + bimanual_cross_attention.extend(cross[frame_valid].float().cpu().tolist()) + + if prediction["wrist_root_translation"].shape[1] > 1: + velocity_valid = ann[:, 1:] & ann[:, :-1] + predicted_velocity = prediction["wrist_root_translation"][:, 1:] - prediction["wrist_root_translation"][:, :-1] + target_velocity = torch.nan_to_num(batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1]) + velocity_error = torch.linalg.vector_norm(predicted_velocity - target_velocity, dim=-1) * 1000 + values["temporal_velocity_error_mm_per_frame"].extend(velocity_error[velocity_valid].float().cpu().tolist()) + if predicted_velocity.shape[1] > 1: + acceleration_valid = velocity_valid[:, 1:] & velocity_valid[:, :-1] + predicted_acceleration = predicted_velocity[:, 1:] - predicted_velocity[:, :-1] + target_acceleration = target_velocity[:, 1:] - target_velocity[:, :-1] + acceleration_error = torch.linalg.vector_norm(predicted_acceleration - target_acceleration, dim=-1) * 1000 + values["temporal_acceleration_error_mm_per_frame2"].extend( + acceleration_error[acceleration_valid].float().cpu().tolist() + ) + + for time_index in range(batch["rgb"].shape[1]): + if not frame_valid[0, time_index]: + continue + for hand, side in enumerate(("left", "right")): + is_valid = bool(ann[0, time_index, hand]) + annotation_state = "".join( + str(int(value)) for value in ann[0, time_index].int().cpu().tolist() + ) + max_side_px = None + wrist_depth_m = None + if is_valid: + points = batch["joint2d"][0, time_index, hand] + extent = points.max(dim=0).values - points.min(dim=0).values + max_side_px = float(extent.max()) + wrist_depth_m = float(batch["wrist_root_translation"][0, time_index, hand, 2]) + absolute_error = float(joint_error[0, time_index, hand].mean()) + root_error = float(relative_error[0, time_index, hand].mean()) + z_error = float(translation_error[0, time_index, hand, 2]) + for bucket in ( + f"image_size/{image_size_bucket(max_side_px)}", + f"wrist_depth/{depth_bucket(wrist_depth_m)}", + f"annotation_state/{annotation_state}", + ): + bucket_values[bucket]["absolute_mpjpe_mm"].append(absolute_error) + bucket_values[bucket]["root_relative_mpjpe_mm"].append(root_error) + bucket_values[bucket]["translation_z_mae_mm"].append(z_error) + frame_rows.append({ + "subject": batch["subject_id"][0], "sequence": batch["sequence_id"][0], + "frame_id": int(batch["frame_id"][0, time_index]), "side": side, + "annotation_valid": int(is_valid), + "annotation_state": annotation_state, + "hand_max_side_px": max_side_px, + "wrist_depth_m": wrist_depth_m, + "absolute_mpjpe_mm": float(joint_error[0, time_index, hand].mean()) if is_valid else None, + "root_relative_mpjpe_mm": float(relative_error[0, time_index, hand].mean()) if is_valid else None, + "joint2d_error_px": float(error_2d[0, time_index, hand].mean()) if is_valid else None, + **{f"pred_t_{axis}_m": float(prediction["wrist_root_translation"][0, time_index, hand, index]) for index, axis in enumerate("xyz")}, + **{f"gt_t_{axis}_m": float(batch["wrist_root_translation"][0, time_index, hand, index]) if is_valid else None for index, axis in enumerate("xyz")}, + }) + + if visualization_index < 16: + rgb = batch["rgb"][0, time_index].float().cpu().permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + for hand, color in enumerate(((50, 220, 50), (50, 80, 255))): + if ann[0, time_index, hand]: + draw_points(image, batch["joint2d"][0, time_index, hand].float().cpu().numpy(), (255, 255, 255), True) + draw_points(image, predicted_2d[0, time_index, hand].float().cpu().numpy(), color, False) + modalities = "RGB" + ("+Depth" if config["model"].get("use_depth") else "") + ("+K" if config["model"].get("use_rays") else "") + lines = ( + f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/{int(batch['frame_id'][0,time_index])} GT=x pred=dot", + f"config={config['name']} input={modalities}", + f"GT valid L={int(ann[0,time_index,0])} R={int(ann[0,time_index,1])} presence=unsupervised", + ) + cv2.rectangle(image, (0, 0), (width, 62), (0, 0, 0), -1) + for line_index, label in enumerate(lines): + cv2.putText(image, label, (6, 17 + 19 * line_index), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (255, 255, 255), 1) + overlay_path = args.output_dir / f"{visualization_index:02d}_prediction_overlay.jpg" + cv2.imwrite(str(overlay_path), image); saved_overlays.append(overlay_path) + grid_h, grid_w = height // 16, width // 16 + for hand, side in enumerate(("left", "right")): + heat = rgb_attention[0, time_index, hand].float().cpu().numpy().reshape(grid_h, grid_w) + heat = (heat - heat.min()) / max(float(heat.max() - heat.min()), 1e-8) + heat = cv2.resize(np.uint8(heat * 255), (width, height), interpolation=cv2.INTER_CUBIC) + heat = cv2.applyColorMap(heat, cv2.COLORMAP_TURBO) + cv2.imwrite(str(args.output_dir / f"{visualization_index:02d}_{side}_attention.jpg"), cv2.addWeighted(image, .55, heat, .45, 0)) + if "depth_cross_attention" in prediction["attention"]: + depth_attention = prediction["attention"]["depth_cross_attention"][:, -1] + depth_heat = depth_attention[0, time_index, hand].float().cpu().numpy().reshape(grid_h, grid_w) + depth_heat = (depth_heat - depth_heat.min()) / max(float(depth_heat.max() - depth_heat.min()), 1e-8) + depth_heat = cv2.resize(np.uint8(depth_heat * 255), (width, height), interpolation=cv2.INTER_CUBIC) + depth_heat = cv2.applyColorMap(depth_heat, cv2.COLORMAP_TURBO) + cv2.imwrite( + str(args.output_dir / f"{visualization_index:02d}_{side}_depth_attention.jpg"), + cv2.addWeighted(image, .55, depth_heat, .45, 0), + ) + visualization_index += 1 + + with (args.output_dir / "per_frame_metrics.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(frame_rows[0])); writer.writeheader(); writer.writerows(frame_rows) + + train_rows = [json.loads(line) for line in args.train_log.read_text(encoding="utf-8").splitlines() if line] + fig, axes = plt.subplots(1, 3, figsize=(15, 4)) + axes[0].plot([row["step"] for row in train_rows], [row["losses"]["total"] for row in train_rows]); axes[0].set_title("Total loss") + axes[1].plot([row["step"] for row in train_rows], [row["metrics"]["absolute_camera_mpjpe_mm"] for row in train_rows]); axes[1].set_title("Batch absolute MPJPE (mm)") + axes[2].plot([row["step"] for row in train_rows], [row["metrics"]["translation_z_mae_mm"] for row in train_rows]); axes[2].set_title("Batch z MAE (mm)") + for axis in axes: axis.set_xlabel("step"); axis.grid(alpha=.25) + fig.tight_layout(); fig.savefig(args.output_dir / "training_curves.png", dpi=160); plt.close(fig) + + metrics = {key: mean(item) for key, item in values.items()} + metrics.update({ + "all_absolute_mpjpe_mm": mean(values["left_absolute_mpjpe_mm"] + values["right_absolute_mpjpe_mm"]), + "all_root_relative_mpjpe_mm": mean(values["left_root_relative_mpjpe_mm"] + values["right_root_relative_mpjpe_mm"]), + "all_joint2d_error_px": mean(values["left_joint2d_error_px"] + values["right_joint2d_error_px"]), + "rgb_attention_same_peak_fraction": mean([float(value) for value in attention_same_peak]), + "rgb_attention_left_right_cosine": mean(attention_cosine), + "depth_attention_same_peak_fraction": mean([float(value) for value in depth_attention_same_peak]), + "temporal_attention_diagonal_mean": mean(temporal_attention_diagonal), + "temporal_attention_normalized_entropy": mean(temporal_attention_entropy), + "bimanual_cross_attention_mean": mean(bimanual_cross_attention), + "depth_gate_mean": mean(depth_gates), + "depth_gate_min": float(min(depth_gates)) if depth_gates else None, + "depth_gate_max": float(max(depth_gates)) if depth_gates else None, + "depth_gate_raw_mean": mean(raw_depth_gates), + "depth_gate_raw_min": float(min(raw_depth_gates)) if raw_depth_gates else None, + "depth_gate_raw_max": float(max(raw_depth_gates)) if raw_depth_gates else None, + "rgb_update_norm_mean": mean(rgb_update_norms), + "depth_update_norm_mean": mean(depth_update_norms), + "gated_depth_update_norm_mean": mean(gated_depth_update_norms), + }) + report = { + "status": "evaluated", "checkpoint": str(args.checkpoint.resolve()), + "split_role": "official_train_tiny_overfit" if "tiny" in args.manifest.name else "non_test_evaluation", + "official_test_used": False, + "clips": len(dataset), "frames": frame_count, + "metrics": metrics, "mean_weighted_losses": {key: mean(item) for key, item in loss_values.items()}, + "structured_residual_diagnostics": { + key: { + "mean": mean(items), + "p95": float(np.percentile(items, 95)) if items else None, + "maximum": float(max(items)) if items else None, + } + for key, items in sorted(structured_diagnostics.items()) + }, + "buckets": { + bucket: {"valid_hands": len(items["absolute_mpjpe_mm"]), **{key: mean(values) for key, values in items.items()}} + for bucket, items in sorted(bucket_values.items()) + }, + "occlusion_bucket": "UNAVAILABLE: H2O annotation_valid is not an occlusion or presence label.", + } + if "tiny" in args.manifest.name: + report["success_thresholds"] = {"absolute_mpjpe_mm": 15.0, "root_relative_mpjpe_mm": 8.0, "joint2d_error_px": 8.0} + report["tiny_overfit_passed"] = bool( + metrics["all_absolute_mpjpe_mm"] < 15 and metrics["all_root_relative_mpjpe_mm"] < 8 and metrics["all_joint2d_error_px"] < 8 + ) + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/extract_phase4_oracle_local_depth.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/extract_phase4_oracle_local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd7ff0e89f1308c39a663fd8afde461e7acc2f5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/extract_phase4_oracle_local_depth.py @@ -0,0 +1,324 @@ +#!/usr/bin/env python3 +"""Extract frozen-model A1 oracle local-depth features without test access.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import tempfile +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.local_depth import oracle_local_depth_features +from foundation_hand.evaluation.phase4 import ( + action_name, + bimanual_asymmetry, + load_action_label, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +SIDES = ("left", "right") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_save_npz(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{path.name}.", suffix=".npz", dir=path.parent, + ) + os.close(descriptor) + temporary = Path(temporary_name) + try: + np.savez_compressed(temporary, **arrays) + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError("A1 extraction produced no valid hand rows") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--split-role", choices=("official_train", "official_validation"), required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--expected-manifest-sha256", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--max-clips", type=int) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if "test" in args.manifest.name.lower() or "test" in args.split_role: + raise ValueError("Phase 4 A1 explicitly prohibits official-test access") + output_npz = args.output_dir / "features.npz" + output_csv = args.output_dir / "samples.csv" + output_json = args.output_dir / "extraction.json" + if any(path.exists() for path in (output_npz, output_csv, output_json)): + raise FileExistsError(f"refusing to overwrite existing A1 extraction in {args.output_dir}") + + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + if checkpoint_hash != args.expected_checkpoint_sha256: + raise ValueError("checkpoint hash differs from the registered Phase 3 reference") + if manifest_hash != args.expected_manifest_sha256: + raise ValueError("manifest hash differs from the registered Phase 4 protected input") + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), + (int(data_config["stride"]),), + max_clips=args.max_clips, + ) + loader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint_state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + chunks: dict[str, list[np.ndarray]] = { + "control": [], + "local": [], + "coarse_translation_m": [], + "target_translation_m": [], + "coarse_joints_m": [], + "target_joints_m": [], + "direct_joints_2d_px": [], + "target_joints_2d_px": [], + "K_resized": [], + } + rows: list[dict[str, object]] = [] + raw_intrinsics: dict[str, np.ndarray] = {} + control_names: tuple[str, ...] | None = None + local_names: tuple[str, ...] | None = None + + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = move_to_device(batch_cpu, device) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + frame_valid = batch["frame_valid"][0].bool() + annotation_valid = batch["joint_annotation_valid"][0].bool() & frame_valid[:, None] + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"][0].float().cpu().numpy() + direct_2d *= np.asarray((width, height), dtype=np.float32) + coarse_translation = prediction["wrist_root_translation"][0].float().cpu().numpy() + coarse_joints = prediction["joints_camera"][0].float().cpu().numpy() + target_translation = batch["wrist_root_translation"][0].float().cpu().numpy() + target_joints = batch["joint3d_camera"][0].float().cpu().numpy() + target_2d_resized = batch["joint2d"][0].float().cpu().numpy() + + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + take_dir = args.root / take + if take not in raw_intrinsics: + K_raw, raw_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + raw_intrinsics[take] = K_raw + else: + K_raw = raw_intrinsics[take] + raw_hw = None + + for time_index in torch.where(frame_valid)[0].cpu().tolist(): + frame_id = int(batch["frame_id"][0, time_index]) + stem = f"{frame_id:06d}" + raw_depth_mm = cv2.imread( + str(take_dir / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED, + ) + if raw_depth_mm is None: + raise RuntimeError(f"cannot read raw depth {take_dir}/depth/{stem}.png") + if raw_hw is not None and raw_depth_mm.shape != raw_hw: + raise ValueError(f"raw depth/K size mismatch at {take}/{stem}") + raw_depth_m, raw_depth_valid = depth_mm_to_m(raw_depth_mm) + target_2d_raw, positive = project_points(target_joints[time_index], K_raw) + + frame_sizes: list[float | None] = [None, None] + frame_depths: list[float | None] = [None, None] + for hand in range(2): + if bool(annotation_valid[time_index, hand]): + extent = ( + target_2d_resized[time_index, hand].max(axis=0) + - target_2d_resized[time_index, hand].min(axis=0) + ) + frame_sizes[hand] = float(extent.max()) + frame_depths[hand] = float(target_translation[time_index, hand, 2]) + asymmetry = bimanual_asymmetry(frame_sizes, frame_depths) + label = load_action_label(args.root, take, frame_id) + + clip_features: dict[str, list[np.ndarray]] = {key: [] for key in chunks} + clip_rows: list[dict[str, object]] = [] + for hand, side in enumerate(SIDES): + if not bool(annotation_valid[time_index, hand]): + continue + if not bool(positive[hand].all()): + raise ValueError(f"valid GT hand projects behind camera at {take}/{stem}/{side}") + features = oracle_local_depth_features( + raw_depth_m, + raw_depth_valid, + target_2d_raw[hand], + K_raw, + coarse_translation[time_index, hand], + hand, + ) + if control_names is None: + control_names, local_names = features.control_names, features.local_names + elif features.control_names != control_names or features.local_names != local_names: + raise AssertionError("A1 feature schema changed within one extraction") + clip_features["control"].append(features.control) + clip_features["local"].append(features.local) + clip_features["coarse_translation_m"].append(coarse_translation[time_index, hand]) + clip_features["target_translation_m"].append(target_translation[time_index, hand]) + clip_features["coarse_joints_m"].append(coarse_joints[time_index, hand]) + clip_features["target_joints_m"].append(target_joints[time_index, hand]) + clip_features["direct_joints_2d_px"].append(direct_2d[time_index, hand]) + clip_features["target_joints_2d_px"].append(target_2d_resized[time_index, hand]) + clip_features["K_resized"].append( + batch["K"][0, time_index].float().cpu().numpy() + ) + clip_rows.append({ + "sample_index": len(rows) + len(clip_rows), + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "side": side, + "side_index": hand, + "action_family": str(batch["sequence_id"][0]).split("/", 1)[0], + "action_label": label, + "action_name": action_name(label), + "hand_size_px": frame_sizes[hand], + "wrist_depth_m": frame_depths[hand], + "bimanual_size_ratio": asymmetry["bimanual_size_ratio"], + "bimanual_depth_gap_m": asymmetry["bimanual_depth_gap_m"], + "bimanual_asymmetry_bucket": asymmetry["bimanual_asymmetry_bucket"], + "local_depth_valid_fraction": features.local_valid_fraction, + "local_depth_discontinuity_m": features.local_depth_discontinuity_m, + }) + if clip_rows: + for key, values in clip_features.items(): + chunks[key].append(np.stack(values).astype(np.float32)) + rows.extend(clip_rows) + + if (clip_index + 1) % 250 == 0: + print( + f"clips={clip_index + 1}/{len(dataset)} valid_hands={len(rows)}", + flush=True, + ) + + if control_names is None or local_names is None: + raise ValueError("A1 extraction found no annotation-valid hands") + arrays = {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + sample_count = len(rows) + if any(value.shape[0] != sample_count for value in arrays.values()): + raise AssertionError("A1 array and metadata row counts differ") + arrays["target_residual_z_m"] = ( + arrays["target_translation_m"][:, 2] - arrays["coarse_translation_m"][:, 2] + ).astype(np.float32) + if not all(np.isfinite(value).all() for value in arrays.values()): + raise ValueError("A1 extraction contains non-finite values") + + args.output_dir.mkdir(parents=True, exist_ok=True) + atomic_save_npz(output_npz, arrays) + write_csv(output_csv, rows) + report = { + "status": "extracted", + "phase": 4, + "wave": "A1_oracle_local_depth", + "split_role": args.split_role, + "official_test_used": False, + "oracle_contract": ( + "GT 2D joints locate multiscale regions in original aligned metric depth only; " + "GT wrist depth is a target and is never an input feature." + ), + "control_contract": ( + "The control receives the same oracle location, K, side and coarse translation " + "but no local depth or XYZ statistics." + ), + "config": str(args.config.resolve()), + "data_root": str(args.root.resolve()), + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": checkpoint_hash, + "step": int(checkpoint_state["step"]), + }, + "dataset_clips": len(dataset), + "valid_hand_samples": sample_count, + "control_dim": len(control_names), + "local_dim": len(local_names), + "control_feature_names": list(control_names), + "local_feature_names": list(local_names), + "precision": config["precision"], + "device": torch.cuda.get_device_name(device), + "outputs": { + "features": str(output_npz.resolve()), + "samples": str(output_csv.resolve()), + }, + } + output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": "complete", "samples": sample_count, "output": str(args.output_dir)})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_fold_milestone_recovery.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_fold_milestone_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..146372c43331db29514bf7bbef1d96c7be0c0103 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_fold_milestone_recovery.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Validate recovered fold milestones and atomically complete canonical states.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.run_phase9_fold_milestone_eval import ( + atomic_json, + h2o_milestones, + milestone_checkpoint, + sha256, +) +from scripts.run_phase9_fold_shard import fold_evaluation_complete +from scripts.run_phase9_external_milestone_eval import stable_checkpoint_sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def expected_shard_evaluations( + registry: dict[str, Any], shard: int, output_root: Path, +) -> list[str]: + conditions = {item["condition"]: item for item in registry["conditions"]} + expected: list[str] = [] + for condition_id in registry["shards"][str(shard)]: + condition = conditions[condition_id] + config_path = Path(condition["config"]) + if sha256(config_path) != condition["config_sha256"]: + raise RuntimeError(f"fold config hash differs: {condition_id}") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + heldout = Path(config["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + run_dir = Path(condition["output_dir"]) + for milestone_id in h2o_milestones(config): + checkpoint = milestone_checkpoint(run_dir, milestone_id) + if checkpoint is None: + raise RuntimeError(f"missing checkpoint: {condition_id}:{milestone_id}") + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + evaluation_id = f"{condition_id}_{milestone_id}_{mode}" + output = output_root / condition_id / milestone_id / mode + if not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + raise RuntimeError(f"invalid recovered output: {evaluation_id}") + expected.append(evaluation_id) + return expected + + +def finalize(plan_path: Path) -> dict[str, Any]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + plan_hash = sha256(plan_path) + if plan.get("official_test_used") is not False: + raise RuntimeError("recovery plan must explicitly exclude official test") + registry_path = Path(plan["registry"]) + if sha256(registry_path) != plan["registry_sha256"]: + raise RuntimeError("registry SHA256 differs") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + worker_states: dict[str, str] = {} + recovered_ids: set[str] = set() + for worker in plan["workers"]: + state_path = Path(worker["state"]) + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or state.get("recovery_plan_sha256") != plan_hash + or state.get("recovery_worker_id") != worker["id"] + or set(state.get("assigned_evaluation_ids", [])) + != set(worker["evaluation_ids"]) + or not set(worker["evaluation_ids"]).issubset(state.get("completed_ids", [])) + ): + raise RuntimeError(f"incomplete recovery worker: {worker['id']}") + overlap = recovered_ids.intersection(worker["evaluation_ids"]) + if overlap: + raise RuntimeError(f"overlapping recovery IDs: {sorted(overlap)}") + recovered_ids.update(worker["evaluation_ids"]) + worker_states[worker["id"]] = sha256(state_path) + + completed_states: dict[str, Any] = {} + for shard_record in plan["canonical_states"]: + shard = int(shard_record["shard"]) + state_path = Path(shard_record["path"]) + if sha256(state_path) != shard_record["failed_state_sha256"]: + raise RuntimeError(f"canonical shard{shard} state changed during recovery") + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("registry_sha256") != plan["registry_sha256"] + or state.get("official_test_used") is not False + ): + raise RuntimeError(f"canonical shard{shard} binding differs") + expected = expected_shard_evaluations( + registry, shard, Path(plan["output_root"]), + ) + if len(expected) != 54 or len(set(expected)) != 54: + raise RuntimeError(f"shard{shard} expected evaluation count differs") + if not set(state.get("completed_ids", [])).union(recovered_ids).issuperset(expected): + raise RuntimeError(f"shard{shard} recovery coverage is incomplete") + state["recovered_failure"] = state.pop("failure", None) + state["status"] = "complete" + state["completed_ids"] = expected + state["allowed_physical_gpus"] = [0, 1, 2, 3, 4, 5] + state["resource_amendment"] = "gpu_4_5_evaluator_authorization_only_20260730" + state["recovery_plan"] = str(plan_path.resolve()) + state["recovery_plan_sha256"] = plan_hash + state["recovery_worker_state_sha256"] = worker_states + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state.pop("waiting_for", None) + atomic_json(state_path, state) + completed_states[str(shard)] = { + "path": str(state_path.resolve()), + "sha256": sha256(state_path), + "completed_ids": len(expected), + } + return { + "schema_version": "phase9_fold_milestone_recovery_merge_v1", + "status": "complete", + "recovery_plan": str(plan_path.resolve()), + "recovery_plan_sha256": plan_hash, + "canonical_states": completed_states, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + result = finalize(args.plan) + args.report.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.report, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_last2.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_last2.py new file mode 100644 index 0000000000000000000000000000000000000000..a32e407fc52390193f3f562b6d9ab92d00625032 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_last2.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Freeze the ordered Stage 9 decision after both candidate controllers finish.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +import time +from typing import Any + +from scripts.phase9_distributed_assignment import detect_machine, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if detect_machine(assignment, None) != "taku3": + raise ValueError("last-2 finalizer is owned only by Taku3") + if ( + plan.get("schema_version") != "phase9_last2_finalizer_plan_v1" + or plan.get("candidate_order") != ["5e7", "1e6"] + or plan.get("selection_rule") + != "retain_preceding_then_5e7_then_1e6_only_on_each_strict_gate" + or plan.get("dino_large_admitted") is not False + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("last-2 finalizer contract differs") + for candidate in plan["candidate_order"]: + spec = plan["candidates"][candidate] + plan_path = Path(spec["plan"]) + if not plan_path.is_file() or sha256(plan_path) != spec["plan_sha256"]: + raise ValueError(f"last-2 {candidate} plan binding differs") + controller_plan = read_json(plan_path) + if ( + controller_plan.get("candidate") != candidate + or Path(controller_plan["controller_state"]).resolve() + != Path(spec["state"]).resolve() + or Path(controller_plan["decision_report"]).resolve() + != Path(spec["report"]).resolve() + ): + raise ValueError(f"last-2 {candidate} paths differ") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"last-2 finalizer binding differs: {path}") + + +def candidate_result( + candidate: str, spec: dict[str, Any], +) -> tuple[str, dict[str, Any] | None, dict[str, Any] | None]: + state_path = Path(spec["state"]) + if not state_path.is_file(): + return "waiting", None, None + state = read_json(state_path) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed"): + return "failed", state, None + return "waiting", state, None + if ( + state.get("candidate") != candidate + or state.get("plan_sha256") != spec["plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + return "failed", state, None + report_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + not report_path.is_file() + or report_path.resolve() != Path(spec["report"]).resolve() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + ): + return "failed", state, None + report = read_json(report_path) + accepted = report.get("gate", {}).get("accepted") + if ( + report.get("schema_version") != "phase9_last2_candidate_decision_v1" + or report.get("status") != "complete" + or report.get("candidate") != candidate + or accepted not in {True, False} + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + return "failed", state, report + if accepted and ( + report.get("gate", {}).get("macro_strictly_improved") is not True + or report.get("gate", {}).get("worst_domain_strictly_improved") is not True + or state.get("admitted") is not True + ): + return "failed", state, report + return "complete", state, report + + +def build_final_report( + plan: dict[str, Any], results: dict[str, tuple[dict[str, Any], dict[str, Any]]], + *, created_utc: str | None = None, +) -> dict[str, Any]: + five_state, five = results["5e7"] + one_state, one = results["1e6"] + if one["gate"]["accepted"] and not five["gate"]["accepted"]: + raise ValueError("1e-6 cannot be accepted after a rejected 5e-7 candidate") + if one["gate"]["accepted"]: + selected = "last2_1e6" + selected_report = one + elif five["gate"]["accepted"]: + selected = "last2_5e7" + selected_report = five + else: + selected = "preceding_mechanism" + selected_report = None + reports = {} + for candidate, (state, report) in results.items(): + path = Path(plan["candidates"][candidate]["report"]) + reports[candidate] = { + "path": str(path.resolve()), + "sha256": sha256(path), + "admitted": state.get("admitted") is True, + "accepted": report["gate"]["accepted"], + "decision": report["decision"], + "candidate_training_gpu_hours": float( + report.get("candidate_training_gpu_hours", 0.0) + ), + } + total_gpu_hours = sum( + item["candidate_training_gpu_hours"] for item in reports.values() + ) + return { + "schema_version": "phase9_last2_final_decision_v1", + "status": "complete", + "created_utc": created_utc or utc_now(), + "candidate_order": list(plan["candidate_order"]), + "selection_rule": plan["selection_rule"], + "selected": selected, + "last2_accepted": selected_report is not None, + "selected_candidate_report": ( + reports["1e6"] if selected == "last2_1e6" + else reports["5e7"] if selected == "last2_5e7" + else None + ), + "selected_candidate_training_jobs": ( + selected_report.get("candidate_training_jobs") + if selected_report is not None else None + ), + "candidate_reports": reports, + "total_candidate_training_gpu_hours": total_gpu_hours, + "rejection_disclosure": { + candidate: report.get("not_admitted_reason") + or report.get("gate", {}).get("rejection_reason") + for candidate, (_, report) in results.items() + if report["gate"]["accepted"] is False + }, + "dino_large_admitted": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("last-2 finalizer state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_last2_finalizer_state_v1", + "status": "waiting_for_candidate_controllers", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing last-2 finalizer state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + statuses = {} + ready = {} + failed = None + for candidate in plan["candidate_order"]: + status, candidate_state, report = candidate_result( + candidate, plan["candidates"][candidate], + ) + statuses[candidate] = status + if status == "failed": + failed = candidate + elif status == "complete": + assert candidate_state is not None and report is not None + ready[candidate] = (candidate_state, report) + state["candidate_statuses"] = statuses + state["updated_utc"] = utc_now() + if failed is not None: + state["status"] = "failed_candidate_binding" + state["failure_candidate"] = failed + atomic_json(args.state, state) + raise SystemExit(1) + if len(ready) == len(plan["candidate_order"]): + break + state["status"] = "waiting_for_candidate_controllers" + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + report_path = Path(plan["report"]) + report_path.parent.mkdir(parents=True, exist_ok=True) + state.setdefault("decision_created_utc", utc_now()) + state["status"] = "publishing_decision" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + report = build_final_report( + plan, ready, created_utc=state["decision_created_utc"], + ) + if report_path.exists(): + if read_json(report_path) != report: + state["status"] = "failed_existing_report_differs" + atomic_json(args.state, state) + raise SystemExit(1) + else: + atomic_json(report_path, report) + state["status"] = "complete" + state["decision"] = report["selected"] + state["decision_report"] = { + "path": str(report_path.resolve()), "sha256": sha256(report_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_resolution_cache.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e6d32a6109f73a7c0dc2b0fdefe9cb8fa15bc6 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_resolution_cache.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Finalize Phase 9 resolution caches after every source worker completes.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +import time +from typing import Any + +from scripts.audit_phase9_resolution_cache import audit +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + sha256, + validate_plan_bindings, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_admission(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + path = Path(plan["admission_state"]) + if not path.is_file(): + raise ValueError("resolution admission state is missing") + state = json.loads(path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution admission state differs") + return state + + +def inspect_workers( + plan_path: Path, plan: dict[str, Any], admission: dict[str, Any] +) -> tuple[str, list[dict[str, Any]]]: + records = [] + overall = "complete" + for worker in plan["workers"]: + path = Path(worker["state"]) + if not path.is_file(): + overall = "waiting_for_workers" + records.append({"worker": worker["id"], "status": "missing"}) + continue + state = json.loads(path.read_text(encoding="utf-8")) + status = state.get("status") + if str(status).startswith("failed"): + overall = "failed_dependency" + elif status != "complete" and overall != "failed_dependency": + overall = "waiting_for_workers" + if ( + state.get("worker") != worker["id"] + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution worker state differs: {worker['id']}") + if status == "complete" and ( + state.get("winner") != admission.get("winner") + or state.get("winner_checkpoint") != admission.get("winner_checkpoint") + or state.get("winner_config") != admission.get("winner_config") + or state.get("admission_state_sha256") != sha256(plan["admission_state"]) + ): + raise ValueError(f"resolution worker winner binding differs: {worker['id']}") + records.append({ + "worker": worker["id"], + "status": status, + "state": str(path.resolve()), + "state_sha256": sha256(path), + }) + return overall, records + + +def validate_existing_completion( + plan_path: Path, plan: dict[str, Any], state: dict[str, Any] +) -> bool: + audit_path = Path(plan["audit_output"]) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == sha256(plan_path) + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and audit_path.is_file() + and state.get("audit", {}).get("sha256") == sha256(audit_path) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan_bindings(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["readiness_state"]).resolve(): + parser.error("readiness state path differs from plan") + + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.state.is_file(): + existing = json.loads(args.state.read_text(encoding="utf-8")) + if validate_existing_completion(args.plan, plan, existing): + print(json.dumps(existing, indent=2)) + return + if existing.get("plan_sha256") not in (None, sha256(args.plan)): + parser.error("existing readiness state belongs to another plan") + + state: dict[str, Any] = { + "schema_version": "phase9_resolution_cache_readiness_v1", + "status": "waiting_for_admission", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, + "official_test_used": False, + } + while True: + try: + admission = validate_admission(args.plan, plan) + worker_status, workers = inspect_workers(args.plan, plan, admission) + except ValueError as error: + if "admission state is missing" in str(error): + state["status"] = "waiting_for_admission" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_validation" + state["failure"] = str(error) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + state["workers"] = workers + state["status"] = worker_status + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if worker_status == "failed_dependency": + raise SystemExit(1) + if worker_status != "complete": + time.sleep(args.poll_seconds) + continue + break + + audit_path = Path(plan["audit_output"]) + if audit_path.exists(): + existing_audit = json.loads(audit_path.read_text(encoding="utf-8")) + if ( + existing_audit.get("status") != "complete" + or existing_audit.get("plan_sha256") != sha256(args.plan) + or existing_audit.get("official_test_used") is not False + or existing_audit.get("h2o_official_validation_used") is not False + ): + state["status"] = "failed_existing_audit" + atomic_json(args.state, state) + raise SystemExit(1) + else: + state["status"] = "auditing" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + try: + result = audit(plan) + except Exception as error: + state["status"] = "failed_audit" + state["failure"] = f"{type(error).__name__}: {error}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise + result.update({ + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "admission_state": str(Path(plan["admission_state"]).resolve()), + "admission_state_sha256": sha256(plan["admission_state"]), + "winner": admission["winner"], + "winner_checkpoint": admission["winner_checkpoint"], + "winner_config": admission["winner_config"], + "worker_states": workers, + }) + audit_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(audit_path, result) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["admission_state_sha256"] = sha256(plan["admission_state"]) + state["winner"] = admission["winner"] + state["winner_checkpoint"] = admission["winner_checkpoint"] + state["winner_config"] = admission["winner_config"] + state["audit"] = { + "path": str(audit_path.resolve()), + "sha256": sha256(audit_path), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_selection_binding_recovery.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d8d4a11430f20985ff8c87f96eb749783db882 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/finalize_phase9_selection_binding_recovery.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Publish one host's complete selection recovery as an immutable release.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +from typing import Any + +from scripts.run_phase9_selection_binding_recovery import ( + atomic_json, + validate_recovered_output, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def release_root(plan: dict[str, Any], owner: str) -> Path: + assignment = json.loads( + Path(plan["distributed_assignment"]["path"]).read_text(encoding="utf-8") + ) + return Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + + +def build_release( + *, plan_path: Path, owner: str, output: Path, +) -> dict[str, Any]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + plan_hash = sha256(plan_path) + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"selection recovery code binding differs: {path}") + root = release_root(plan, owner).resolve() + if output.parent.resolve() != root: + raise ValueError("selection recovery release must live at its frozen root") + owner_workers = [item for item in plan["workers"] if item["owner"] == owner] + owner_evaluations = [ + item for item in plan["evaluations"] if item["owner"] == owner + ] + expected_ids = {item["id"] for item in owner_evaluations} + completed_ids: set[str] = set() + worker_states = [] + for worker in owner_workers: + state_path = Path(worker["state"]) + if not state_path.is_file(): + raise ValueError(f"selection recovery worker state missing: {worker['id']}") + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("owner") != owner + or state.get("plan_sha256") != plan_hash + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or set(state.get("completed_ids", [])) + != set(worker["evaluation_ids"]) + ): + raise ValueError( + f"selection recovery worker state differs: {worker['id']}" + ) + completed_ids.update(state["completed_ids"]) + worker_states.append({ + "id": worker["id"], "path": str(state_path.resolve()), + "sha256": sha256(state_path), + }) + if completed_ids != expected_ids: + raise ValueError("selection recovery completed IDs differ") + evaluation_evidence = [] + files = [] + seen_relative_paths: set[str] = set() + for item in owner_evaluations: + evidence = validate_recovered_output(item) + directory = Path(item["output_dir"]).resolve() + try: + relative_output = directory.relative_to(root) + except ValueError as error: + raise ValueError("recovery output is outside owner root") from error + for path in sorted(directory.rglob("*")): + if path.is_symlink() or not path.is_file(): + if path.is_symlink(): + raise ValueError(f"recovery release refuses symlink: {path}") + continue + relative = str(path.resolve().relative_to(root)) + if relative in seen_relative_paths: + raise ValueError(f"duplicate recovery release path: {relative}") + seen_relative_paths.add(relative) + files.append({ + "path": relative, "sha256": sha256(path), + "bytes": path.stat().st_size, + }) + evaluation_evidence.append({ + "id": item["id"], "output_dir": str(relative_output), **evidence, + }) + return { + "schema_version": "phase9_selection_binding_recovery_release_v1", + "status": "complete_immutable_release", + "created_utc": datetime.now(timezone.utc).isoformat(), + "owner": owner, + "plan": {"path": str(plan_path.resolve()), "sha256": plan_hash}, + "distributed_assignment": plan["distributed_assignment"], + "root": str(root), + "worker_states": worker_states, + "evaluation_ids": sorted(expected_ids), + "evaluations": evaluation_evidence, + "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "read_only_after_publish": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--owner", choices=("taku3", "server_new"), required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = build_release(plan_path=args.plan, owner=args.owner, output=args.output) + if args.output.exists(): + existing = json.loads(args.output.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("owner") == args.owner + and existing.get("plan", {}).get("sha256") + == result["plan"]["sha256"] + and existing.get("files") == result["files"] + and existing.get("evaluations") == result["evaluations"] + ): + print(json.dumps(existing, indent=2)) + return + parser.error("existing recovery release differs") + atomic_json(args.output, result) + for item in result["files"]: + os.chmod(Path(result["root"]) / item["path"], 0o444) + os.chmod(args.output, 0o444) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase4_oracle_local_depth.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase4_oracle_local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..61cdc0efdd02dd690411a6cae7f8faf78c60a242 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase4_oracle_local_depth.py @@ -0,0 +1,605 @@ +#!/usr/bin/env python3 +"""Fit and evaluate the Phase 4 A1 bounded oracle wrist-z diagnostic.""" + +from __future__ import annotations + +import argparse +import copy +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.nn.functional as F + +from foundation_hand.evaluation.local_depth import BoundedZResidualRegressor +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import project_points + + +FINGERTIPS = (4, 8, 12, 16, 20) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV {path}") + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def stable_take_holdout(takes: list[str], modulus: int = 5) -> np.ndarray: + """Select a deterministic official-train-only holdout by complete take.""" + + if modulus < 2: + raise ValueError("holdout modulus must be at least two") + output = [] + for take in takes: + digest = hashlib.sha256(take.encode("utf-8")).digest() + output.append(int.from_bytes(digest[:8], "little") % modulus == 0) + return np.asarray(output, dtype=bool) + + +def padded_control(control: np.ndarray, local_dim: int) -> np.ndarray: + if control.ndim != 2 or control.shape[1] > local_dim: + raise ValueError("invalid control/local feature dimensions") + output = np.zeros((control.shape[0], local_dim), dtype=np.float32) + output[:, : control.shape[1]] = control + return output + + +def standardizer(features: np.ndarray, fit_mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + values = features[fit_mask].astype(np.float64) + mean = values.mean(axis=0).astype(np.float32) + std = values.std(axis=0).astype(np.float32) + std[std < 1e-6] = 1.0 + return mean, std + + +def fit_regressor( + features: np.ndarray, + target_m: np.ndarray, + train_mask: np.ndarray, + holdout_mask: np.ndarray, + *, + device: torch.device, + seed: int, + hidden_dim: int, + max_residual_m: float, + learning_rate: float, + weight_decay: float, + batch_size: int, + epochs: int, + patience: int, +) -> tuple[BoundedZResidualRegressor, np.ndarray, np.ndarray, list[dict[str, float | int]]]: + mean, std = standardizer(features, train_mask) + normalized = (features.astype(np.float32) - mean) / std + x = torch.from_numpy(normalized).to(device) + target = torch.from_numpy(target_m.astype(np.float32)).to(device) + train_indices = torch.from_numpy(np.where(train_mask)[0]).to(device) + holdout_indices = torch.from_numpy(np.where(holdout_mask)[0]).to(device) + if not train_indices.numel() or not holdout_indices.numel(): + raise ValueError("official-train fit/holdout split is empty") + + torch.manual_seed(seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(seed) + model = BoundedZResidualRegressor( + features.shape[1], hidden_dim=hidden_dim, max_residual_m=max_residual_m, + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=learning_rate, weight_decay=weight_decay, + ) + generator = torch.Generator(device=device).manual_seed(seed) + best_state = copy.deepcopy(model.state_dict()) + best_holdout = float("inf") + stale = 0 + history: list[dict[str, float | int]] = [] + for epoch in range(1, epochs + 1): + model.train() + shuffled = train_indices[torch.randperm(train_indices.numel(), generator=generator, device=device)] + losses = [] + for start in range(0, shuffled.numel(), batch_size): + indices = shuffled[start : start + batch_size] + optimizer.zero_grad(set_to_none=True) + prediction = model(x[indices]) + loss = F.smooth_l1_loss(prediction, target[indices], beta=0.01) + if not torch.isfinite(loss): + raise FloatingPointError("non-finite A1 training loss") + loss.backward() + optimizer.step() + losses.append(float(loss.detach())) + model.eval() + with torch.inference_mode(): + holdout_prediction = model(x[holdout_indices]) + holdout_mae = float((holdout_prediction - target[holdout_indices]).abs().mean()) + history.append({ + "epoch": epoch, + "train_smooth_l1": float(np.mean(losses)), + "holdout_residual_mae_m": holdout_mae, + }) + if holdout_mae < best_holdout - 1e-6: + best_holdout = holdout_mae + best_state = copy.deepcopy(model.state_dict()) + stale = 0 + else: + stale += 1 + if stale >= patience: + break + model.load_state_dict(best_state) + return model, mean, std, history + + +def infer_residual( + model: BoundedZResidualRegressor, + features: np.ndarray, + mean: np.ndarray, + std: np.ndarray, + device: torch.device, + batch_size: int = 8192, +) -> np.ndarray: + model.eval() + output = [] + with torch.inference_mode(): + for start in range(0, features.shape[0], batch_size): + values = (features[start : start + batch_size].astype(np.float32) - mean) / std + output.append(model(torch.from_numpy(values).to(device)).cpu().numpy()) + result = np.concatenate(output).astype(np.float32) + if not np.isfinite(result).all(): + raise FloatingPointError("A1 residual inference produced non-finite values") + return result + + +def variant_metrics( + arrays: dict[str, np.ndarray], residual_m: np.ndarray, +) -> dict[str, np.ndarray]: + coarse_translation = arrays["coarse_translation_m"] + target_translation = arrays["target_translation_m"] + coarse_joints = arrays["coarse_joints_m"] + target_joints = arrays["target_joints_m"] + refined_translation = coarse_translation.copy() + refined_translation[:, 2] += residual_m + refined_joints = coarse_joints.copy() + refined_joints[:, :, 2] += residual_m[:, None] + joint_error = np.linalg.norm(refined_joints - target_joints, axis=-1) * 1000.0 + relative_prediction = refined_joints - refined_joints[:, :1] + relative_target = target_joints - target_joints[:, :1] + relative_error = np.linalg.norm(relative_prediction - relative_target, axis=-1) * 1000.0 + translation_error = (refined_translation - target_translation) * 1000.0 + projected, positive = project_points(refined_joints, arrays["K_resized"]) + if not bool(positive.all()): + raise ValueError("A1 refined MANO joints project behind the camera") + target_2d = arrays["target_joints_2d_px"] + direct_2d = arrays["direct_joints_2d_px"] + return { + "absolute_mpjpe_mm": joint_error.mean(axis=1), + "root_relative_mpjpe_mm": relative_error.mean(axis=1), + "fingertip_mpjpe_mm": joint_error[:, FINGERTIPS].mean(axis=1), + "translation_z_signed_error_mm": translation_error[:, 2], + "translation_z_mae_mm": np.abs(translation_error[:, 2]), + "direct_2d_error_px": np.linalg.norm(direct_2d - target_2d, axis=-1).mean(axis=1), + "mano_projected_2d_error_px": np.linalg.norm(projected - target_2d, axis=-1).mean(axis=1), + "direct_mano_consistency_px": np.linalg.norm(direct_2d - projected, axis=-1).mean(axis=1), + "residual_magnitude_mm": np.abs(residual_m) * 1000.0, + "predicted_wrist_xyz_m": refined_translation, + "predicted_joints_m": refined_joints, + } + + +def temporal_metrics( + metadata: list[dict[str, str]], + target_translation: np.ndarray, + predictions: dict[str, dict[str, np.ndarray]], +) -> dict[str, dict[str, np.ndarray]]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(metadata): + groups[(row["take"], row["side"])].append(index) + output = { + variant: { + "wrist_velocity_error_mm_per_frame": [], + "wrist_acceleration_error_mm_per_frame2": [], + } + for variant in predictions + } + for indices in groups.values(): + ordered = sorted(indices, key=lambda index: int(metadata[index]["frame_id"])) + for position in range(1, len(ordered)): + previous, current = ordered[position - 1], ordered[position] + if int(metadata[current]["frame_id"]) != int(metadata[previous]["frame_id"]) + 1: + continue + target_velocity = target_translation[current] - target_translation[previous] + for variant, metrics in predictions.items(): + wrist = metrics["predicted_wrist_xyz_m"] + error = np.linalg.norm((wrist[current] - wrist[previous]) - target_velocity) * 1000.0 + output[variant]["wrist_velocity_error_mm_per_frame"].append(float(error)) + for position in range(2, len(ordered)): + first, second, third = ordered[position - 2 : position + 1] + frame_ids = [int(metadata[index]["frame_id"]) for index in (first, second, third)] + if frame_ids[1] != frame_ids[0] + 1 or frame_ids[2] != frame_ids[1] + 1: + continue + target_acceleration = target_translation[third] - 2 * target_translation[second] + target_translation[first] + for variant, metrics in predictions.items(): + wrist = metrics["predicted_wrist_xyz_m"] + acceleration = wrist[third] - 2 * wrist[second] + wrist[first] + error = np.linalg.norm(acceleration - target_acceleration) * 1000.0 + output[variant]["wrist_acceleration_error_mm_per_frame2"].append(float(error)) + return { + variant: {metric: np.asarray(values, dtype=np.float32) for metric, values in metrics.items()} + for variant, metrics in output.items() + } + + +def summarize_groups( + metadata: list[dict[str, str]], + variants: dict[str, dict[str, np.ndarray]], + temporal: dict[str, dict[str, np.ndarray]], + challenge: dict[str, Any], +) -> list[dict[str, object]]: + farthest = float(challenge["thresholds"]["farthest_observed_wrist_depth_p80_m"]) + challenge_clips = set(int(value) for value in challenge["clip_indices"]) + masks = { + "all": np.ones(len(metadata), dtype=bool), + "left": np.asarray([row["side"] == "left" for row in metadata]), + "right": np.asarray([row["side"] == "right" for row in metadata]), + "small": np.asarray([float(row["hand_size_px"]) < 64.0 for row in metadata]), + "farthest_observed": np.asarray([ + float(row["wrist_depth_m"]) >= farthest for row in metadata + ]), + "strong_asymmetry": np.asarray([ + row["bimanual_asymmetry_bucket"] == "strong" for row in metadata + ]), + "challenge": np.asarray([int(row["clip_index"]) in challenge_clips for row in metadata]), + } + rows: list[dict[str, object]] = [] + scalar_metrics = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", + ) + for group, mask in masks.items(): + for variant, metrics in variants.items(): + for metric in scalar_metrics: + rows.append({ + "group": group, + "variant": variant, + "metric": metric, + **distribution_summary(metrics[metric][mask]), + }) + for variant, metrics in temporal.items(): + for metric, values in metrics.items(): + rows.append({ + "group": "all_contiguous_transitions", + "variant": variant, + "metric": metric, + **distribution_summary(values), + }) + return rows + + +def paired_take_bootstrap( + metadata: list[dict[str, str]], + variants: dict[str, dict[str, np.ndarray]], + *, + seed: int, + samples: int, +) -> list[dict[str, object]]: + take_indices: dict[str, list[int]] = defaultdict(list) + for index, row in enumerate(metadata): + take_indices[row["take"]].append(index) + rng = np.random.default_rng(seed) + rows: list[dict[str, object]] = [] + comparisons = (("local", "coarse"), ("local", "control"), ("control", "coarse")) + metric_stats = ( + ("absolute_mpjpe_mm", "mean"), + ("translation_z_mae_mm", "mean"), + ("translation_z_mae_mm", "p95"), + ("fingertip_mpjpe_mm", "mean"), + ("mano_projected_2d_error_px", "mean"), + ) + take_names = sorted(take_indices) + for candidate, reference in comparisons: + for metric, statistic in metric_stats: + deltas = [] + for take in take_names: + indices = take_indices[take] + candidate_values = variants[candidate][metric][indices] + reference_values = variants[reference][metric][indices] + if statistic == "mean": + delta = float(candidate_values.mean() - reference_values.mean()) + else: + delta = float(np.percentile(candidate_values, 95) - np.percentile(reference_values, 95)) + deltas.append(delta) + deltas_array = np.asarray(deltas, dtype=np.float64) + bootstrap_indices = rng.integers(0, len(deltas_array), size=(samples, len(deltas_array))) + distribution = deltas_array[bootstrap_indices].mean(axis=1) + rows.append({ + "candidate": candidate, + "reference": reference, + "metric": metric, + "per_take_statistic": statistic, + "take_count": len(deltas_array), + "paired_delta_candidate_minus_reference": float(deltas_array.mean()), + "ci95_low": float(np.percentile(distribution, 2.5)), + "ci95_high": float(np.percentile(distribution, 97.5)), + "bootstrap_samples": samples, + "bootstrap_seed": seed, + }) + return rows + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--train-extraction", type=Path, required=True) + parser.add_argument("--validation-extraction", type=Path, required=True) + parser.add_argument("--challenge-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--fit-seed", type=int, default=4401) + parser.add_argument("--holdout-modulus", type=int, default=5) + parser.add_argument("--hidden-dim", type=int, default=128) + parser.add_argument("--max-residual-m", type=float, default=0.15) + parser.add_argument("--learning-rate", type=float, default=3e-3) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--batch-size", type=int, default=4096) + parser.add_argument("--epochs", type=int, default=80) + parser.add_argument("--patience", type=int, default=12) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + return parser.parse_args() + + +def load_extraction(path: Path) -> tuple[dict[str, np.ndarray], list[dict[str, str]], dict[str, Any]]: + report = json.loads((path / "extraction.json").read_text(encoding="utf-8")) + if report.get("official_test_used") is not False: + raise ValueError("A1 extraction does not explicitly preserve official-test isolation") + arrays = dict(np.load(path / "features.npz")) + rows = read_csv(path / "samples.csv") + if any(value.shape[0] != len(rows) for value in arrays.values()): + raise ValueError(f"array/CSV length mismatch in {path}") + return arrays, rows, report + + +def main() -> None: + args = parse_args() + output_files = ( + args.output_dir / "results.json", + args.output_dir / "group_metrics.csv", + args.output_dir / "validation_predictions.csv", + args.output_dir / "paired_take_bootstrap_ci.csv", + args.output_dir / "regressors.pt", + ) + if any(path.exists() for path in output_files): + raise FileExistsError(f"refusing to overwrite existing A1 result in {args.output_dir}") + train, train_rows, train_report = load_extraction(args.train_extraction) + validation, validation_rows, validation_report = load_extraction(args.validation_extraction) + if train_report["split_role"] != "official_train": + raise ValueError("A1 fitting requires official_train extraction") + if validation_report["split_role"] != "official_validation": + raise ValueError("A1 reporting requires official_validation extraction") + if train_report["checkpoint"]["sha256"] != validation_report["checkpoint"]["sha256"]: + raise ValueError("train/validation A1 extractions use different frozen checkpoints") + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + if challenge.get("checkpoint_selection_allowed") is not False: + raise ValueError("challenge subset is not registered as secondary-only") + + holdout_mask = stable_take_holdout( + [row["take"] for row in train_rows], modulus=args.holdout_modulus, + ) + train_mask = ~holdout_mask + local_dim = train["local"].shape[1] + train_features = { + "control": padded_control(train["control"], local_dim), + "local": train["local"], + } + validation_features = { + "control": padded_control(validation["control"], local_dim), + "local": validation["local"], + } + device = torch.device(f"cuda:{args.gpu}") + regressors: dict[str, BoundedZResidualRegressor] = {} + scalers: dict[str, tuple[np.ndarray, np.ndarray]] = {} + histories: dict[str, list[dict[str, float | int]]] = {} + for index, variant in enumerate(("control", "local")): + model, mean, std, history = fit_regressor( + train_features[variant], + train["target_residual_z_m"], + train_mask, + holdout_mask, + device=device, + seed=args.fit_seed + index, + hidden_dim=args.hidden_dim, + max_residual_m=args.max_residual_m, + learning_rate=args.learning_rate, + weight_decay=args.weight_decay, + batch_size=args.batch_size, + epochs=args.epochs, + patience=args.patience, + ) + regressors[variant] = model + scalers[variant] = (mean, std) + histories[variant] = history + + residuals = {"coarse": np.zeros(len(validation_rows), dtype=np.float32)} + for variant in ("control", "local"): + mean, std = scalers[variant] + residuals[variant] = infer_residual( + regressors[variant], validation_features[variant], mean, std, device, + ) + variants = { + variant: variant_metrics(validation, residual) + for variant, residual in residuals.items() + } + coarse_root = variants["coarse"]["root_relative_mpjpe_mm"] + coarse_direct = variants["coarse"]["direct_2d_error_px"] + for variant in ("control", "local"): + if not np.allclose(variants[variant]["root_relative_mpjpe_mm"], coarse_root, atol=1e-4): + raise AssertionError("uniform A1 z residual changed root-relative geometry") + if not np.array_equal(variants[variant]["direct_2d_error_px"], coarse_direct): + raise AssertionError("A1 residual changed the frozen direct-2D head") + + temporal = temporal_metrics( + validation_rows, validation["target_translation_m"], variants, + ) + group_rows = summarize_groups(validation_rows, variants, temporal, challenge) + bootstrap_rows = paired_take_bootstrap( + validation_rows, + variants, + seed=args.fit_seed, + samples=args.bootstrap_samples, + ) + prediction_rows: list[dict[str, object]] = [] + for index, metadata in enumerate(validation_rows): + row: dict[str, object] = dict(metadata) + for variant, metrics in variants.items(): + for metric in ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", + ): + row[f"{variant}_{metric}"] = float(metrics[metric][index]) + prediction_rows.append(row) + + def summary_value(group: str, variant: str, metric: str, statistic: str) -> float: + match = next( + row for row in group_rows + if row["group"] == group and row["variant"] == variant and row["metric"] == metric + ) + return float(match[statistic]) + + coarse_z_p95 = summary_value("all", "coarse", "translation_z_mae_mm", "p95") + local_z_p95 = summary_value("all", "local", "translation_z_mae_mm", "p95") + reductions = { + "full_validation_z_p95_percent": 100.0 * (coarse_z_p95 - local_z_p95) / coarse_z_p95, + } + for group in ("small", "farthest_observed", "right"): + coarse_value = summary_value(group, "coarse", "absolute_mpjpe_mm", "mean") + local_value = summary_value(group, "local", "absolute_mpjpe_mm", "mean") + reductions[f"{group}_absolute_mpjpe_percent"] = 100.0 * (coarse_value - local_value) / coarse_value + gate_metric = ( + reductions["full_validation_z_p95_percent"] >= 20.0 + or reductions["small_absolute_mpjpe_percent"] >= 15.0 + or reductions["farthest_observed_absolute_mpjpe_percent"] >= 15.0 + ) + gate_no_regression = True # Exact by construction and asserted above. + gate = { + "registered_condition": ( + "z P95 reduction >=20% OR small/farthest-observed absolute MPJPE reduction >=15%; " + "root-relative and direct-2D degradation <=2%" + ), + "metric_gate_pass": bool(gate_metric), + "no_regression_gate_pass": gate_no_regression, + "formal_A1_gate_pass": bool(gate_metric and gate_no_regression), + "depth_increment_condition": ( + "A2 additionally requires local-depth to retain meaningful improvement beyond the " + "same-capacity oracle-location control; reported but not silently assumed." + ), + "reductions_percent": reductions, + } + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "group_metrics.csv", group_rows) + write_csv(args.output_dir / "validation_predictions.csv", prediction_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap_rows) + torch.save({ + "wave": "A1_oracle_local_depth", + "fit_seed": args.fit_seed, + "input_dim": local_dim, + "hidden_dim": args.hidden_dim, + "max_residual_m": args.max_residual_m, + "models": { + variant: {key: value.detach().cpu() for key, value in model.state_dict().items()} + for variant, model in regressors.items() + }, + "scalers": { + variant: {"mean": mean, "std": std} + for variant, (mean, std) in scalers.items() + }, + }, args.output_dir / "regressors.pt") + report = { + "status": "evaluated", + "phase": 4, + "wave": "A1_oracle_local_depth", + "official_test_used": False, + "frozen_checkpoint": validation_report["checkpoint"], + "train_manifest": train_report["manifest"], + "validation_manifest": validation_report["manifest"], + "challenge_manifest": { + "path": str(args.challenge_manifest.resolve()), + "sha256": sha256(args.challenge_manifest), + "role": "secondary diagnostic only; never checkpoint selection", + }, + "protocol": { + "fit_data": "official_train only", + "fit_holdout": ( + f"whole-take SHA256 modulus-{args.holdout_modulus} holdout within official_train" + ), + "validation": "complete official validation, one independent report", + "control": "same input dimension and MLP parameter count; local-depth fields zeroed", + "hidden_dim": args.hidden_dim, + "max_residual_m": args.max_residual_m, + "learning_rate": args.learning_rate, + "weight_decay": args.weight_decay, + "batch_size": args.batch_size, + "maximum_epochs": args.epochs, + "early_stopping_patience": args.patience, + "fit_seed": args.fit_seed, + }, + "sample_counts": { + "official_train_fit": int(train_mask.sum()), + "official_train_holdout": int(holdout_mask.sum()), + "official_validation": len(validation_rows), + }, + "parameter_counts": { + variant: sum(parameter.numel() for parameter in model.parameters()) + for variant, model in regressors.items() + }, + "histories": histories, + "gate": gate, + "outputs": { + "group_metrics": str((args.output_dir / "group_metrics.csv").resolve()), + "validation_predictions": str((args.output_dir / "validation_predictions.csv").resolve()), + "paired_take_bootstrap_ci": str((args.output_dir / "paired_take_bootstrap_ci.csv").resolve()), + "regressors": str((args.output_dir / "regressors.pt").resolve()), + }, + } + (args.output_dir / "results.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": "complete", "gate": gate, "output": str(args.output_dir)})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase5_alignment_calibrator.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase5_alignment_calibrator.py new file mode 100644 index 0000000000000000000000000000000000000000..68eb72f652ec43cc343bed31e01e11a7f82287e7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase5_alignment_calibrator.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +"""Fit shared metric-alignment correction/confidence using OOF banks only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +import joblib +import numpy as np +from sklearn.linear_model import HuberRegressor, LogisticRegression +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler + +from foundation_hand.evaluation.alignment_calibration import FEATURE_NAMES, features_from_take + +THRESHOLD_GRID = (0.50, 0.60, 0.70, 0.80, 0.90, 0.95, 1.01) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_bank_layout( + manifests: list[dict[str, Any]], expected_banks_per_fold: int, +) -> dict[str, Any]: + if expected_banks_per_fold < 1: + raise ValueError("expected banks per fold must be positive") + observed_pairs: set[tuple[int, str]] = set() + observed_fold_seeds: set[tuple[int, int]] = set() + fold_counts: Counter[int] = Counter() + seed_folds: dict[int, set[int]] = defaultdict(set) + for manifest in manifests: + fold = int(manifest["fold"]) + checkpoint = str(manifest["checkpoint"]["sha256"]) + pair = (fold, checkpoint) + if pair in observed_pairs: + raise ValueError(f"duplicate OOF fold/checkpoint bank: {pair}") + observed_pairs.add(pair) + fold_counts[fold] += 1 + seed = manifest.get("seed") + if seed is None: + if expected_banks_per_fold > 1: + raise ValueError("expanded OOF banks require an explicit coarse seed") + continue + seed = int(seed) + fold_seed = (fold, seed) + if fold_seed in observed_fold_seeds: + raise ValueError(f"duplicate OOF fold/seed bank: {fold_seed}") + observed_fold_seeds.add(fold_seed) + seed_folds[seed].add(fold) + if set(fold_counts) != {0, 1, 2}: + raise ValueError(f"shared calibrator requires folds 0/1/2, got {set(fold_counts)}") + if any(fold_counts[fold] != expected_banks_per_fold for fold in range(3)): + raise ValueError( + "OOF bank count per fold differs from --expected-banks-per-fold: " + f"{dict(sorted(fold_counts.items()))}" + ) + if expected_banks_per_fold > 1: + if len(seed_folds) != expected_banks_per_fold: + raise ValueError( + f"expected {expected_banks_per_fold} coarse seeds, got {sorted(seed_folds)}" + ) + incomplete = {seed: sorted(folds) for seed, folds in seed_folds.items() if folds != {0, 1, 2}} + if incomplete: + raise ValueError(f"each coarse seed must cover folds 0/1/2: {incomplete}") + return { + "banks_per_fold": {str(fold): fold_counts[fold] for fold in range(3)}, + "coarse_seeds": sorted(seed_folds), + } + + +def load_bank( + bank_dirs: list[Path], expected_banks_per_fold: int = 1, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = { + key: [] for key in ( + "features", "target_residual_z_m", "raw_delta_z_m", "alignment_applied", + "pred_joints_m", "target_joints_m", "side", "hand_scale_px", + "frame_id", "subject", "take", "coarse_seed", "checkpoint", + ) + } + manifests = [] + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("bank_version") != 2 + or manifest.get("scope") != "full_fold" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("leakage_audit", {}).get("passed") is not True + or manifest.get("official_test_used") is not False + or manifest.get("official_validation_used_for_assignment") is not False + ): + raise ValueError(f"calibrator requires a complete leakage-free OOF bank: {bank_dir}") + manifests.append(manifest) + validate_bank_layout(manifests, expected_banks_per_fold) + for bank_dir, manifest in zip(bank_dirs, manifests, strict=True): + seed = int(manifest.get("seed", -1)) + checkpoint = str(manifest["checkpoint"]["sha256"]) + for take_record in manifest["takes"]: + with np.load(take_record["path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + time = len(arrays["frame_id"]) + features = features_from_take(arrays) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays[ + "frame_valid" + ][:, None].astype(bool) + hand_indices = np.broadcast_to(np.arange(2)[None], (time, 2)) + frame_ids = np.broadcast_to(arrays["frame_id"][:, None], (time, 2)) + chunks["features"].append(features[valid]) + chunks["target_residual_z_m"].append(arrays["translation_residual_m"][..., 2][valid]) + chunks["raw_delta_z_m"].append(arrays["alignment_delta_z_m"][valid]) + chunks["alignment_applied"].append(arrays["alignment_applied"][valid]) + chunks["pred_joints_m"].append(arrays["pred_joints_camera"][valid]) + chunks["target_joints_m"].append(arrays["target_joints_camera"][valid]) + chunks["side"].append(hand_indices[valid]) + chunks["hand_scale_px"].append(arrays["coarse_hand_scale_px"][valid]) + chunks["frame_id"].append(frame_ids[valid]) + chunks["subject"].append(np.full(valid.sum(), str(arrays["subject"]))) + chunks["take"].append(np.full(valid.sum(), str(arrays["take"]))) + chunks["coarse_seed"].append(np.full(valid.sum(), seed, dtype=np.int64)) + chunks["checkpoint"].append(np.full(valid.sum(), checkpoint)) + return {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + + +def correction_metrics(samples: dict[str, np.ndarray], correction_m: np.ndarray) -> dict[str, float]: + correction = np.asarray(correction_m, dtype=np.float64) + pred_joints = samples["pred_joints_m"].astype(np.float64).copy() + pred_joints[..., 2] += correction[:, None] + target_joints = samples["target_joints_m"].astype(np.float64) + joint_error_mm = np.linalg.norm(pred_joints - target_joints, axis=-1) * 1000.0 + z_error_mm = np.abs(samples["target_residual_z_m"] - correction) * 1000.0 + p95 = float(np.percentile(z_error_mm, 95)) + return { + "absolute_mpjpe_mm": float(joint_error_mm.mean()), + "z_mae_mm": float(z_error_mm.mean()), + "z_p95_mm": p95, + "z_cvar95_mm": float(z_error_mm[z_error_mm >= p95].mean()), + } + + +def fit_regressor(features: np.ndarray, target: np.ndarray): + return make_pipeline( + StandardScaler(), + HuberRegressor(epsilon=1.35, alpha=1e-4, max_iter=400, tol=1e-5), + ).fit(features, target) + + +def fit_confidence(features: np.ndarray, helpful: np.ndarray): + if np.unique(helpful).size < 2: + raise ValueError("alignment helpfulness target has only one class") + return make_pipeline( + StandardScaler(), + LogisticRegression(max_iter=1000, class_weight="balanced", C=1.0), + ).fit(features, helpful) + + +def select_confidence_threshold( + samples: dict[str, np.ndarray], + calibrated_correction_m: np.ndarray, + confidence: np.ndarray, +) -> tuple[float, list[dict[str, float | bool]]]: + coarse = correction_metrics(samples, np.zeros(len(confidence))) + guardrail_mm = min(0.2, 0.01 * coarse["absolute_mpjpe_mm"]) + available = samples["alignment_applied"].astype(bool) + rows = [] + for threshold in THRESHOLD_GRID: + applied = available & (confidence >= threshold) + correction = np.where(applied, calibrated_correction_m, 0.0) + metrics = correction_metrics(samples, correction) + rows.append({ + "threshold": threshold, + "available_fraction": float(available.mean()), + "applied_fraction": float(applied.mean()), + **metrics, + "absolute_guardrail_passed": bool( + metrics["absolute_mpjpe_mm"] <= coarse["absolute_mpjpe_mm"] + guardrail_mm + ), + }) + eligible = [row for row in rows if row["absolute_guardrail_passed"]] + if not eligible: + return 1.01, rows + eligible.sort(key=lambda row: ( + float(row["absolute_mpjpe_mm"]), + float(row["z_p95_mm"]), + float(row["applied_fraction"]), + )) + return float(eligible[0]["threshold"]), rows + + +def write_predictions( + path: Path, + samples: dict[str, np.ndarray], + calibrated: np.ndarray, + confidence: np.ndarray, + threshold: float, +) -> None: + with path.open("x", newline="", encoding="utf-8") as handle: + fields = ( + "sample_index", "coarse_seed", "checkpoint_sha256", "subject", "take", "frame_id", "side", + "target_residual_z_mm", "raw_alignment_delta_z_mm", + "calibrated_delta_z_mm", "confidence", "alignment_available", "applied", + ) + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for index in range(len(calibrated)): + writer.writerow({ + "sample_index": index, + "coarse_seed": int(samples.get("coarse_seed", np.full(len(calibrated), -1))[index]), + "checkpoint_sha256": str(samples.get("checkpoint", np.full(len(calibrated), ""))[index]), + "subject": samples["subject"][index], + "take": samples["take"][index], + "frame_id": int(samples["frame_id"][index]), + "side": "right" if int(samples["side"][index]) else "left", + "target_residual_z_mm": 1000.0 * samples["target_residual_z_m"][index], + "raw_alignment_delta_z_mm": 1000.0 * samples["raw_delta_z_m"][index], + "calibrated_delta_z_mm": 1000.0 * calibrated[index], + "confidence": confidence[index], + "alignment_available": bool(samples["alignment_applied"][index]), + "applied": bool( + samples["alignment_applied"][index] + and confidence[index] >= threshold + ), + }) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--expected-banks-per-fold", type=int, default=1) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("calibrator output directory must be new or empty") + samples = load_bank(args.bank_dir, args.expected_banks_per_fold) + features = samples["features"] + target = samples["target_residual_z_m"].astype(np.float64) + raw_delta = samples["raw_delta_z_m"].astype(np.float64) + available = samples["alignment_applied"].astype(bool) + subjects = samples["subject"] + cv_correction = np.zeros_like(target) + cv_confidence = np.zeros_like(target) + fold_records = [] + for heldout_subject in sorted(set(subjects.tolist())): + heldout = subjects == heldout_subject + train = ~heldout + regressor = fit_regressor(features[train], target[train]) + helpful = available[train] & ( + np.abs(target[train] - raw_delta[train]) < np.abs(target[train]) + ) + confidence_model = fit_confidence(features[train], helpful) + cv_correction[heldout] = np.clip(regressor.predict(features[heldout]), -0.12, 0.12) + cv_confidence[heldout] = confidence_model.predict_proba(features[heldout])[:, 1] + fold_records.append({ + "heldout_subject": heldout_subject, + "train_samples": int(train.sum()), + "heldout_samples": int(heldout.sum()), + "raw_helpful_fraction_train": float(helpful.mean()), + }) + threshold, threshold_rows = select_confidence_threshold( + samples, cv_correction, cv_confidence, + ) + raw_available = np.where(available, raw_delta, 0.0) + calibrated_available = np.where(available, cv_correction, 0.0) + selected_correction = np.where( + available & (cv_confidence >= threshold), cv_correction, 0.0, + ) + metrics = { + "coarse": correction_metrics(samples, np.zeros_like(target)), + "robust_alignment_unscaled": correction_metrics(samples, raw_available), + "calibrated_always": correction_metrics(samples, calibrated_available), + "calibrated_confidence": correction_metrics(samples, selected_correction), + } + corrections = { + "coarse": np.zeros_like(target), + "robust_alignment_unscaled": raw_available, + "calibrated_always": calibrated_available, + "calibrated_confidence": selected_correction, + } + metrics_by_seed = {} + for seed in sorted(set(samples["coarse_seed"].tolist())): + if int(seed) < 0: + continue + mask = samples["coarse_seed"] == seed + subset = { + key: value[mask] + for key, value in samples.items() + if key in ("target_residual_z_m", "pred_joints_m", "target_joints_m") + } + metrics_by_seed[str(int(seed))] = { + condition: correction_metrics(subset, correction[mask]) + for condition, correction in corrections.items() + } + + final_regressor = fit_regressor(features, target) + final_helpful = available & (np.abs(target - raw_delta) < np.abs(target)) + final_confidence = fit_confidence(features, final_helpful) + args.output_dir.mkdir(parents=True, exist_ok=True) + model_path = args.output_dir / "alignment_calibrator.joblib" + joblib.dump({ + "version": "phase5_oof_alignment_calibrator_v1", + "feature_names": FEATURE_NAMES, + "regressor": final_regressor, + "confidence": final_confidence, + "confidence_threshold": threshold, + "correction_bound_m": 0.12, + }, model_path) + predictions_path = args.output_dir / "oof_calibration_predictions.csv" + write_predictions( + predictions_path, samples, cv_correction, cv_confidence, threshold, + ) + report = { + "status": "fitted", + "experiment_class": "preregistered_oof_calibration", + "result_role": "train_oof_cross_validated_threshold_selection", + "official_validation_used": False, + "official_test_used": False, + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "expected_banks_per_fold": args.expected_banks_per_fold, + "coarse_seeds": sorted({int(seed) for seed in samples["coarse_seed"] if int(seed) >= 0}), + "samples": len(target), + "subjects": sorted(set(subjects.tolist())), + "features": list(FEATURE_NAMES), + "leave_one_subject_out": fold_records, + "confidence_target": "available raw robust delta reduces absolute wrist-z error", + "threshold_grid": list(THRESHOLD_GRID), + "selected_threshold": threshold, + "threshold_selection_rule": "minimize OOF absolute MPJPE among <=min(0.2mm,1%) guardrail candidates; tie-break z P95 then lower apply fraction", + "threshold_rows": threshold_rows, + "metrics": metrics, + "metrics_by_seed": metrics_by_seed, + "model": {"path": str(model_path.resolve()), "sha256": sha256(model_path)}, + "predictions": {"path": str(predictions_path.resolve()), "sha256": sha256(predictions_path)}, + } + (args.output_dir / "calibration.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "samples": report["samples"], + "selected_threshold": threshold, "metrics": metrics, + "official_validation_used": False, "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase5_causal_state.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bf8459c36303256261ef7ad38e7a1f322f501a9f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase5_causal_state.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Select causal translation-z state parameters using train OOF sequences only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.causal_state import ( + causal_constant_velocity_kalman, + measurement_uncertainty_multiplier, +) + + +PROCESS_SIGMAS = (0.002, 0.005, 0.01, 0.02, 0.05) +MEASUREMENT_SIGMAS = (0.0025, 0.005, 0.01, 0.02) +UNCERTAINTY_STRENGTHS = (0.5, 1.0, 2.0) +GUARDRAIL_MM = 0.2 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_calibration_predictions(path: Path) -> dict[tuple[str, int, str], dict[str, float | bool]]: + output = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + key = (row["take"], int(row["frame_id"]), row["side"]) + if key in output: + raise ValueError(f"duplicate OOF calibration prediction: {key}") + output[key] = { + "calibrated_delta_z_m": float(row["calibrated_delta_z_mm"]) / 1000.0, + "confidence": float(row["confidence"]), + "available": row["alignment_available"] == "True", + } + return output + + +def load_sequences( + bank_dirs: list[Path], prediction_csv: Path, +) -> tuple[list[dict[str, np.ndarray]], list[dict[str, Any]]]: + predictions = read_calibration_predictions(prediction_csv) + sequences = [] + manifests = [] + consumed: set[tuple[str, int, str]] = set() + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("bank_version") != 2 + or manifest.get("scope") != "full_fold" + or manifest.get("official_test_used") is not False + ): + raise ValueError(f"invalid OOF bank: {bank_dir}") + manifests.append(manifest) + for record in manifest["takes"]: + with np.load(record["path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + time = len(arrays["frame_id"]) + calibrated = np.zeros((time, 2), dtype=np.float32) + confidence = np.zeros((time, 2), dtype=np.float32) + available = np.zeros((time, 2), dtype=bool) + prediction_present = np.zeros((time, 2), dtype=bool) + for index, frame_id in enumerate(arrays["frame_id"]): + for hand, side in enumerate(("left", "right")): + key = (str(arrays["take"]), int(frame_id), side) + if key not in predictions: + continue + row = predictions[key] + calibrated[index, hand] = float(row["calibrated_delta_z_m"]) + confidence[index, hand] = float(row["confidence"]) + available[index, hand] = bool(row["available"]) + prediction_present[index, hand] = True + consumed.add(key) + expected = arrays["mano_annotation_valid"].astype(bool) & arrays[ + "frame_valid" + ][:, None].astype(bool) + if np.any(expected & ~prediction_present): + raise ValueError(f"missing OOF calibration rows for {arrays['take']}") + uncertainty_base = measurement_uncertainty_multiplier( + confidence, + arrays["alignment_inlier_ratio"], + arrays["alignment_residual_scale_m"], + arrays["alignment_valid_fraction"], + arrays["alignment_conditioning_quality"], + 1.0, + ) + uncertainty_base = np.where(available, uncertainty_base, 5.0) + sequences.append({ + "take": np.asarray(arrays["take"]), + "clip_index": arrays["clip_index"], + "frame_id": arrays["frame_id"], + "frame_valid": arrays["frame_valid"].astype(bool), + "hand_valid": expected, + "coarse_z_m": arrays["pred_wrist_translation"][..., 2], + "measurement_z_m": arrays["pred_wrist_translation"][..., 2] + np.where( + available, calibrated, 0.0, + ), + "target_z_m": arrays["target_wrist_translation"][..., 2], + "pred_joints_m": arrays["pred_joints_camera"], + "target_joints_m": arrays["target_joints_camera"], + # The deployable coarse model remains a measurement even when + # local Depth/K alignment is unavailable. In that case the + # correction falls back to zero and uncertainty is maximal. + "measurement_available": np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), (time, 2), + ).copy(), + "alignment_available": available, + "uncertainty_multiplier_base": uncertainty_base, + }) + if consumed != set(predictions): + raise ValueError("OOF calibration predictions do not exactly match bank samples") + return sequences, manifests + + +def summarize_filter( + sequences: list[dict[str, np.ndarray]], + *, + process_sigma: float | None, + measurement_sigma: float | None, + uncertainty_strength: float, +) -> dict[str, float]: + absolute = [] + z_error = [] + velocity_error = [] + acceleration_error = [] + predicted_acceleration = [] + predicted_jerk = [] + for arrays in sequences: + measurement = arrays["measurement_z_m"] + if process_sigma is None or measurement_sigma is None: + filtered = measurement + else: + base = arrays["uncertainty_multiplier_base"] + multiplier = 1.0 + uncertainty_strength * (base - 1.0) + filtered, _ = causal_constant_velocity_kalman( + measurement, + frame_id=arrays["frame_id"], + segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], + measurement_available=arrays["measurement_available"], + process_sigma_m_per_frame2=process_sigma, + measurement_sigma_m=measurement_sigma, + uncertainty_multiplier=multiplier, + ) + correction = filtered - arrays["coarse_z_m"] + joints = arrays["pred_joints_m"].astype(np.float64).copy() + joints[..., 2] += correction[..., None] + valid = arrays["hand_valid"] + joint_error = np.linalg.norm(joints - arrays["target_joints_m"], axis=-1).mean(axis=-1) + absolute.extend((joint_error[valid] * 1000.0).tolist()) + z_error.extend((np.abs(filtered - arrays["target_z_m"])[valid] * 1000.0).tolist()) + contiguous = ( + (arrays["frame_id"][1:] == arrays["frame_id"][:-1] + 1) + & (arrays["clip_index"][1:] == arrays["clip_index"][:-1]) + ) + for hand in range(2): + pair_valid = contiguous & valid[1:, hand] & valid[:-1, hand] + pred_velocity = np.diff(filtered[:, hand]) + target_velocity = np.diff(arrays["target_z_m"][:, hand]) + velocity_error.extend((np.abs(pred_velocity - target_velocity)[pair_valid] * 1000.0).tolist()) + if len(filtered) < 3: + continue + triple_valid = pair_valid[1:] & pair_valid[:-1] + pred_acceleration = np.diff(filtered[:, hand], n=2) + target_acceleration = np.diff(arrays["target_z_m"][:, hand], n=2) + acceleration_error.extend((np.abs(pred_acceleration - target_acceleration)[triple_valid] * 1000.0).tolist()) + predicted_acceleration.extend((np.abs(pred_acceleration)[triple_valid] * 1000.0).tolist()) + if len(filtered) >= 4: + quad_valid = triple_valid[1:] & triple_valid[:-1] + jerk = np.diff(filtered[:, hand], n=3) + predicted_jerk.extend((np.abs(jerk)[quad_valid] * 1000.0).tolist()) + absolute_array = np.asarray(absolute) + z_array = np.asarray(z_error) + return { + "absolute_mpjpe_mm": float(absolute_array.mean()), + "z_mae_mm": float(z_array.mean()), + "z_p95_mm": float(np.percentile(z_array, 95)), + "velocity_error_mm_per_frame": float(np.mean(velocity_error)), + "acceleration_error_mm_per_frame2": float(np.mean(acceleration_error)), + "predicted_acceleration_mm_per_frame2": float(np.mean(predicted_acceleration)), + "predicted_jerk_mm_per_frame3": float(np.mean(predicted_jerk)), + } + + +def select_candidate(rows: list[dict[str, Any]], baseline: dict[str, float]) -> dict[str, Any]: + eligible = [ + row for row in rows + if float(row["absolute_mpjpe_mm"]) <= baseline["absolute_mpjpe_mm"] + GUARDRAIL_MM + and float(row["z_mae_mm"]) <= baseline["z_mae_mm"] + GUARDRAIL_MM + and float(row["z_p95_mm"]) <= baseline["z_p95_mm"] + GUARDRAIL_MM + ] + if not eligible: + raise ValueError("no causal-state candidate passes the OOF static guardrails") + return min(eligible, key=lambda row: ( + float(row["predicted_acceleration_mm_per_frame2"]), + float(row["acceleration_error_mm_per_frame2"]), + float(row["velocity_error_mm_per_frame"]), + float(row["absolute_mpjpe_mm"]), + )) + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("causal-state output directory must be new or empty") + sequences, manifests = load_sequences(args.bank_dir, args.calibration_predictions) + baseline = summarize_filter( + sequences, process_sigma=None, measurement_sigma=None, uncertainty_strength=0.0, + ) + rows = [] + for process_sigma in PROCESS_SIGMAS: + for measurement_sigma in MEASUREMENT_SIGMAS: + for family, strengths in ( + ("fixed_kalman", (0.0,)), + ("uncertainty_kalman", UNCERTAINTY_STRENGTHS), + ): + for strength in strengths: + rows.append({ + "family": family, + "process_sigma_m_per_frame2": process_sigma, + "measurement_sigma_m": measurement_sigma, + "uncertainty_strength": strength, + **summarize_filter( + sequences, + process_sigma=process_sigma, + measurement_sigma=measurement_sigma, + uncertainty_strength=strength, + ), + }) + selected = { + family: select_candidate( + [row for row in rows if row["family"] == family], baseline, + ) + for family in ("fixed_kalman", "uncertainty_kalman") + } + args.output_dir.mkdir(parents=True, exist_ok=True) + grid_path = args.output_dir / "causal_state_oof_grid.csv" + write_csv(grid_path, rows) + report = { + "status": "selected", + "experiment_class": "train_oof_causal_state_selection", + "official_validation_used": False, + "official_test_used": False, + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "calibration_predictions": { + "path": str(args.calibration_predictions.resolve()), + "sha256": sha256(args.calibration_predictions), + }, + "sequences": len(sequences), + "baseline_calibrated_per_frame": baseline, + "guardrail_mm": GUARDRAIL_MM, + "selection_rule": "within +0.2 mm OOF Absolute/z-MAE/z-P95 guardrails, minimize predicted acceleration then acceleration error, velocity error, and Absolute MPJPE", + "measurement_contract": "coarse z is always the causal measurement on valid frames; unavailable local alignment applies zero correction with maximum uncertainty", + "selected": selected, + "grid": {"path": str(grid_path.resolve()), "sha256": sha256(grid_path), "rows": len(rows)}, + } + (args.output_dir / "causal_state_selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": report["status"], "selected": selected}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase6_harm_risk.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase6_harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..ebfa2bd15ba7b93b4781f9835dd9f649c8e8904c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/fit_phase6_harm_risk.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python3 +"""Fit the preregistered OOF-only Phase 6 harmful-correction risk model.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import joblib +import numpy as np +from sklearn.ensemble import HistGradientBoostingClassifier, HistGradientBoostingRegressor +from sklearn.metrics import brier_score_loss, roc_auc_score +from sklearn.model_selection import GroupKFold + +from foundation_hand.evaluation.mixed_projection import coarse_wrist_ray_translation + + +FEATURE_NAMES = ( + "calibrated_delta_z_m", "abs_calibrated_delta_z_m", + "raw_delta_z_m", "abs_raw_delta_z_m", "raw_calibrated_disagreement_m", + "existing_confidence", "alignment_available", "raw_alignment_available", + "valid_support_count", "projected_support_count", "inlier_ratio", + "residual_scale_m", "valid_fraction", "foreground_fraction", + "background_fraction", "depth_discontinuity_m", "conditioning_quality", + "silhouette_overlap_fraction", "coarse_hand_scale_px", + "coarse_direct_mano_consistency_px", "coarse_z_m", "coarse_ray_x", + "coarse_ray_y", "coarse_wrist_velocity_norm_m_per_frame", + "predicted_depth_order", "side_right", +) +GAIN_THRESHOLDS_MM = (-0.5, 0.0, 0.25, 0.5, 1.0, 2.0) +HARM_THRESHOLDS = (0.2, 0.3, 0.4, 0.5, 0.6) +SEED = 20260717 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_calibration_predictions( + path: Path, +) -> dict[tuple[int, str, int, int], tuple[float, float, bool]]: + lookup = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + hand = 1 if row["side"] == "right" else 0 + key = (int(row["coarse_seed"]), row["take"], int(row["frame_id"]), hand) + if key in lookup: + raise ValueError(f"duplicate calibration prediction: {key}") + lookup[key] = ( + float(row["calibrated_delta_z_mm"]) / 1000.0, + float(row["confidence"]), row["alignment_available"] == "True", + ) + if len(lookup) != 333_936: + raise ValueError(f"calibration prediction coverage changed: {len(lookup)}") + return lookup + + +def harm_cvar95( + coarse_absolute_mm: np.ndarray, + corrected_absolute_mm: np.ndarray, + applied: np.ndarray, +) -> float: + harm = np.where( + applied, np.maximum(corrected_absolute_mm - coarse_absolute_mm, 0.0), 0.0, + ) + threshold = np.percentile(harm, 95) + return float(harm[harm >= threshold].mean()) + + +def evaluate_policy( + *, + coarse_absolute_mm: np.ndarray, + corrected_absolute_mm: np.ndarray, + applied: np.ndarray, + seed_take_groups: np.ndarray, +) -> dict[str, float]: + final = np.where(applied, corrected_absolute_mm, coarse_absolute_mm) + by_group: dict[str, list[float]] = defaultdict(list) + coarse_by_group: dict[str, list[float]] = defaultdict(list) + for group, value, coarse in zip( + seed_take_groups, final, coarse_absolute_mm, strict=True, + ): + by_group[str(group)].append(float(value)) + coarse_by_group[str(group)].append(float(coarse)) + group_values = {key: float(np.mean(values)) for key, values in by_group.items()} + take_deltas = np.asarray([ + group_values[key] - float(np.mean(coarse_by_group[key])) for key in group_values + ]) + return { + "coverage": float(applied.mean()), + "absolute_frame_mean_mm": float(final.mean()), + "absolute_take_mean_mm": float(np.mean(list(group_values.values()))), + "harm_fraction_gt_0p5mm": float( + (applied & ((corrected_absolute_mm - coarse_absolute_mm) > 0.5)).mean() + ), + "harm_cvar95_mm": harm_cvar95( + coarse_absolute_mm, corrected_absolute_mm, applied, + ), + "worst_seed_take_harm_mm": float(take_deltas.max()), + } + + +def models() -> tuple[HistGradientBoostingRegressor, HistGradientBoostingClassifier]: + common = dict( + max_iter=150, learning_rate=0.05, max_depth=3, + min_samples_leaf=40, l2_regularization=1.0, + early_stopping=False, random_state=SEED, + ) + return HistGradientBoostingRegressor(**common), HistGradientBoostingClassifier(**common) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--calibration-json", type=Path, required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + calibration_report = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration_report.get("status") != "fitted" + or calibration_report.get("official_validation_used") is not False + or calibration_report.get("official_test_used") is not False + or calibration_report.get("samples") != 333_936 + or calibration_report.get("predictions", {}).get("sha256") + != sha256(args.calibration_predictions) + ): + raise ValueError("expanded OOF calibration contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + calibration = load_calibration_predictions(args.calibration_predictions) + + feature_chunks = [] + gain_chunks = [] + coarse_chunks = [] + corrected_chunks = [] + available_chunks = [] + physical_groups = [] + seed_take_groups = [] + sample_rows = [] + bank_records = [] + for bank_index, registered in enumerate(calibration_report["bank_manifests"], start=1): + manifest_path = Path(registered["path"]) + if sha256(manifest_path) != registered["sha256"]: + raise ValueError(f"bank manifest hash mismatch: {manifest_path}") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("official_test_used") is not False + or manifest.get("leakage_audit", {}).get("passed") is not True + ): + raise ValueError(f"bank isolation contract failed: {manifest_path}") + seed = int(manifest["seed"]) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + needed = ( + "frame_id", "frame_valid", "pred_wrist_translation", + "pred_joints_camera", "target_joints_camera", + "mano_annotation_valid", "alignment_delta_z_m", "alignment_applied", + "alignment_valid_support_count", "alignment_projected_support_count", + "alignment_inlier_ratio", "alignment_residual_scale_m", + "alignment_valid_fraction", "alignment_foreground_fraction", + "alignment_background_fraction", "alignment_depth_discontinuity_m", + "alignment_conditioning_quality", "silhouette_overlap_fraction", + "coarse_hand_scale_px", "coarse_direct_mano_consistency_px", + "coarse_wrist_velocity_m_per_frame", "predicted_depth_order", + ) + arrays = {key: archive[key] for key in needed} + take = str(archive["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + time_index, hand = np.where(valid) + count = len(time_index) + calibrated = np.zeros(count, dtype=np.float64) + confidence = np.zeros(count, dtype=np.float64) + available = np.zeros(count, dtype=bool) + for index, (time_value, hand_value) in enumerate( + zip(time_index, hand, strict=True), + ): + key = (seed, take, int(arrays["frame_id"][time_value]), int(hand_value)) + calibrated[index], confidence[index], available[index] = calibration[key] + raw = arrays["alignment_delta_z_m"][time_index, hand].astype(np.float64) + raw_available = arrays["alignment_applied"][time_index, hand].astype(bool) + calibrated = np.where(available, calibrated, 0.0) + raw = np.where(raw_available, raw, 0.0) + coarse_translation = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + coarse_joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + corrected_translation = coarse_wrist_ray_translation( + coarse_translation, coarse_translation[:, 2] + calibrated, + ) + corrected_joints = coarse_joints + ( + corrected_translation - coarse_translation + )[:, None] + coarse_absolute = np.linalg.norm(coarse_joints - target_joints, axis=-1).mean(axis=1) * 1000.0 + corrected_absolute = np.linalg.norm( + corrected_joints - target_joints, axis=-1, + ).mean(axis=1) * 1000.0 + gain = coarse_absolute - corrected_absolute + z = np.maximum(coarse_translation[:, 2], 1e-6) + overlap = arrays["silhouette_overlap_fraction"][time_index] + depth_order = arrays["predicted_depth_order"][time_index] + velocity = arrays["coarse_wrist_velocity_m_per_frame"][time_index, hand] + features = np.column_stack(( + calibrated, np.abs(calibrated), raw, np.abs(raw), np.abs(raw - calibrated), + confidence, available, raw_available, + arrays["alignment_valid_support_count"][time_index, hand], + arrays["alignment_projected_support_count"][time_index, hand], + arrays["alignment_inlier_ratio"][time_index, hand], + arrays["alignment_residual_scale_m"][time_index, hand], + arrays["alignment_valid_fraction"][time_index, hand], + arrays["alignment_foreground_fraction"][time_index, hand], + arrays["alignment_background_fraction"][time_index, hand], + arrays["alignment_depth_discontinuity_m"][time_index, hand], + arrays["alignment_conditioning_quality"][time_index, hand], overlap, + arrays["coarse_hand_scale_px"][time_index, hand], + arrays["coarse_direct_mano_consistency_px"][time_index, hand], + coarse_translation[:, 2], coarse_translation[:, 0] / z, + coarse_translation[:, 1] / z, np.linalg.norm(velocity, axis=1), + depth_order, hand.astype(np.float64), + )).astype(np.float32) + features = np.nan_to_num(features, nan=0.0, posinf=1e6, neginf=-1e6) + feature_chunks.append(features) + gain_chunks.append(gain.astype(np.float32)) + coarse_chunks.append(coarse_absolute.astype(np.float32)) + corrected_chunks.append(corrected_absolute.astype(np.float32)) + available_chunks.append(available) + physical_groups.extend([take] * count) + seed_take_groups.extend([f"{seed}:{take}"] * count) + sample_rows.extend({ + "coarse_seed": seed, "take": take, + "frame_id": int(arrays["frame_id"][time_value]), + "side": "right" if hand_value else "left", + } for time_value, hand_value in zip(time_index, hand, strict=True)) + bank_records.append({ + "path": str(manifest_path), "sha256": registered["sha256"], + "seed": seed, "fold": int(manifest["fold"]), + }) + print(f"[{bank_index}/9] fold{manifest['fold']} seed{seed} loaded", flush=True) + + X = np.concatenate(feature_chunks) + gain = np.concatenate(gain_chunks) + coarse_absolute = np.concatenate(coarse_chunks) + corrected_absolute = np.concatenate(corrected_chunks) + available = np.concatenate(available_chunks) + groups = np.asarray(physical_groups) + seed_take = np.asarray(seed_take_groups) + if X.shape != (333_936, len(FEATURE_NAMES)) or len(set(zip( + (row["coarse_seed"] for row in sample_rows), + (row["take"] for row in sample_rows), + (row["frame_id"] for row in sample_rows), + (row["side"] for row in sample_rows), + ))) != len(sample_rows): + raise ValueError("OOF feature coverage or uniqueness changed") + + harmful = gain < -0.5 + harm_magnitude = np.maximum(-gain, 0.0) + regression_weight = 1.0 + 4.0 * np.minimum(harm_magnitude / 10.0, 5.0) + classifier_weight = 1.0 + 8.0 * np.minimum(harm_magnitude / 10.0, 5.0) + predicted_gain = np.zeros_like(gain) + predicted_harm = np.zeros_like(gain) + fold_id = np.full(len(gain), -1, dtype=np.int8) + splitter = GroupKFold(n_splits=5) + for fold, (train, heldout) in enumerate(splitter.split(X, gain, groups), start=0): + regressor, classifier = models() + regressor.fit(X[train], gain[train], sample_weight=regression_weight[train]) + classifier.fit(X[train], harmful[train], sample_weight=classifier_weight[train]) + predicted_gain[heldout] = regressor.predict(X[heldout]) + predicted_harm[heldout] = classifier.predict_proba(X[heldout])[:, 1] + fold_id[heldout] = fold + print(f"cross-fit {fold + 1}/5: {len(heldout)} held-out samples", flush=True) + if np.any(fold_id < 0): + raise AssertionError("cross-fitting omitted samples") + + coarse_policy = evaluate_policy( + coarse_absolute_mm=coarse_absolute, corrected_absolute_mm=corrected_absolute, + applied=np.zeros_like(available), seed_take_groups=seed_take, + ) + always_policy = evaluate_policy( + coarse_absolute_mm=coarse_absolute, corrected_absolute_mm=corrected_absolute, + applied=available, seed_take_groups=seed_take, + ) + grid_rows = [] + for gain_threshold in GAIN_THRESHOLDS_MM: + for harm_threshold in HARM_THRESHOLDS: + applied = available & (predicted_gain >= gain_threshold) & ( + predicted_harm <= harm_threshold + ) + row = { + "expected_gain_threshold_mm": gain_threshold, + "harm_probability_threshold": harm_threshold, + **evaluate_policy( + coarse_absolute_mm=coarse_absolute, + corrected_absolute_mm=corrected_absolute, + applied=applied, seed_take_groups=seed_take, + ), + } + row["absolute_delta_vs_always_mm"] = ( + row["absolute_take_mean_mm"] - always_policy["absolute_take_mean_mm"] + ) + row["harm_cvar_reduction_fraction"] = 1.0 - ( + row["harm_cvar95_mm"] / max(always_policy["harm_cvar95_mm"], 1e-12) + ) + row["admission_passed"] = bool( + row["absolute_delta_vs_always_mm"] <= 0.1 + and row["coverage"] >= 0.2 + and row["harm_cvar_reduction_fraction"] >= 0.2 + ) + grid_rows.append(row) + eligible = [row for row in grid_rows if row["admission_passed"]] + eligible.sort(key=lambda row: ( + row["absolute_take_mean_mm"], row["harm_cvar95_mm"], + row["worst_seed_take_harm_mm"], row["coverage"], + )) + selected = eligible[0] if eligible else None + + final_regressor, final_classifier = models() + final_regressor.fit(X, gain, sample_weight=regression_weight) + final_classifier.fit(X, harmful, sample_weight=classifier_weight) + package_path = args.output_dir / "harm_risk_package.joblib" + joblib.dump({ + "version": "phase6_harm_risk_v1", + "feature_names": FEATURE_NAMES, + "regressor": final_regressor, + "classifier": final_classifier, + "selected_thresholds": None if selected is None else { + "expected_gain_threshold_mm": selected["expected_gain_threshold_mm"], + "harm_probability_threshold": selected["harm_probability_threshold"], + }, + "harm_definition_mm": 0.5, + "seed": SEED, + }, package_path) + + prediction_rows = [] + for index, identity in enumerate(sample_rows): + prediction_rows.append({ + "sample_index": index, **identity, "cv_fold": int(fold_id[index]), + "coarse_absolute_mpjpe_mm": float(coarse_absolute[index]), + "corrected_absolute_mpjpe_mm": float(corrected_absolute[index]), + "realized_gain_mm": float(gain[index]), + "predicted_gain_mm": float(predicted_gain[index]), + "harmful_gt_0p5mm": bool(harmful[index]), + "predicted_harm_probability": float(predicted_harm[index]), + "alignment_available": bool(available[index]), + }) + write_csv(args.output_dir / "cross_fitted_predictions.csv", prediction_rows) + write_csv(args.output_dir / "threshold_grid.csv", grid_rows) + report = { + "status": "admitted_for_one_frozen_validation" if selected is not None else "rejected_oof_gate", + "experiment": "P6_S3_harm_aware_risk_gate", + "experiment_class": "exploratory_oof_only_cross_fitted_risk_model", + "official_validation_used": False, + "official_test_used": False, + "oracle_information_at_inference": False, + "samples": len(X), "physical_takes": len(set(groups)), + "seed_take_groups": len(set(seed_take)), "features": list(FEATURE_NAMES), + "cross_validation": "5-fold GroupKFold by physical take across coarse seeds", + "cross_fitted_gain_mae_mm": float(np.mean(np.abs(predicted_gain - gain))), + "cross_fitted_harm_brier": float(brier_score_loss(harmful, predicted_harm)), + "cross_fitted_harm_roc_auc": float(roc_auc_score(harmful, predicted_harm)), + "coarse_policy": coarse_policy, "always_policy": always_policy, + "selected": selected, "eligible_conditions": len(eligible), + "package": {"path": str(package_path), "sha256": sha256(package_path)}, + "calibration": { + "json": str(args.calibration_json.resolve()), + "json_sha256": sha256(args.calibration_json), + "predictions": str(args.calibration_predictions.resolve()), + "predictions_sha256": sha256(args.calibration_predictions), + }, + "banks": bank_records, + "outputs": { + "threshold_grid": "threshold_grid.csv", + "cross_fitted_predictions": "cross_fitted_predictions.csv", + }, + } + (args.output_dir / "risk_selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "selected": selected, + "gain_mae_mm": report["cross_fitted_gain_mae_mm"], + "harm_auc": report["cross_fitted_harm_roc_auc"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/freeze_phase7_h2o_adaptation_validation.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/freeze_phase7_h2o_adaptation_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..2298467e46db7bcb7e74db4bb2211252cb82a353 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/freeze_phase7_h2o_adaptation_validation.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Freeze a train-heldout-selected adaptation candidate before H2O validation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_external import sha256 +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES + + +def build_freeze_record(selection_path: Path, validation_manifest: Path) -> dict[str, Any]: + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if ( + selection.get("status") != "selected_h2o_adaptation_train_group_heldout" + or selection.get("selection_split") != "h2o_train_group_heldout_only" + or selection.get("h2o_official_validation_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("adaptation selection is not eligible for validation freeze") + winner = selection.get("winner") + candidates = [item for item in selection.get("candidates", []) if item["candidate"] == winner] + if len(candidates) != 1: + raise ValueError("adaptation winner is missing or duplicated") + candidate = candidates[0] + checkpoint, config = Path(candidate["checkpoint"]), Path(candidate["config"]) + if sha256(checkpoint) != candidate["checkpoint_sha256"]: + raise ValueError("adaptation checkpoint SHA256 mismatch") + if sha256(config) != candidate["config_sha256"]: + raise ValueError("adaptation config SHA256 mismatch") + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only canonical H2O official validation may be frozen") + return { + "status": "h2o_adaptation_candidate_frozen", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "winner": winner, + "checkpoint": { + "path": str(checkpoint.resolve()), + "sha256": candidate["checkpoint_sha256"], + "step": candidate["checkpoint_step"], + }, + "config": { + "path": str(config.resolve()), + "sha256": candidate["config_sha256"], + }, + "adaptation_selection_path": str(selection_path.resolve()), + "adaptation_selection_sha256": sha256(selection_path), + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used_for_selection": False, + "h2o_validation_manifest": { + "path": str(validation_manifest.resolve()), + "sha256": sha256(validation_manifest), + }, + "frozen_h2o_input_modes": list(INPUT_MODES), + "h2o_training_data_used": True, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection", type=Path, required=True) + parser.add_argument("--validation-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = build_freeze_record(args.selection, args.validation_manifest) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/freeze_phase7_h2o_zero_shot.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/freeze_phase7_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..002866bbe6508fa9e5db8985698182f6eaab4657 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/freeze_phase7_h2o_zero_shot.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Freeze H2O zero-shot exposure only after external selection is immutable.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path + +from scripts.build_phase7_scale_eval_queue import sha256 + + +def build_freeze_record(selection_path: Path, manifest: Path) -> dict: + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if ( + selection.get("status") != "selected_external_generalist_no_h2o" + or selection.get("h2o_training_data_used") is not False + or selection.get("h2o_official_validation_used_for_external_selection") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("external generalist selection is not freeze-eligible") + checkpoint = Path(selection["checkpoint"]["path"]) + config = Path(selection["config"]["path"]) + if sha256(checkpoint) != selection["checkpoint"]["sha256"]: + raise ValueError("selected checkpoint hash mismatch") + if sha256(config) != selection["config"]["sha256"]: + raise ValueError("selected config hash mismatch") + if manifest.name != "official_val.jsonl": + raise ValueError("only canonical H2O official_val.jsonl can be frozen") + return { + "status": "external_generalist_frozen", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "checkpoint_path": str(checkpoint.resolve()), + "checkpoint_sha256": selection["checkpoint"]["sha256"], + "checkpoint_step": selection["checkpoint"]["step"], + "config_path": str(config.resolve()), "config_sha256": selection["config"]["sha256"], + "external_selection_path": str(selection_path.resolve()), + "external_selection_sha256": sha256(selection_path), + "frozen_h2o_input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "h2o_validation_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-selection", type=Path, required=True) + parser.add_argument("--h2o-validation-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + record = build_freeze_record(args.external_selection, args.h2o_validation_manifest) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/freeze_phase9_final_deployment.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/freeze_phase9_final_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..fab8e06ab8f566b0f721a6d89481379322349a41 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/freeze_phase9_final_deployment.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python3 +"""Freeze the unique final Phase 9 checkpoint for post-selection deployment audits.""" + +from __future__ import annotations + +import argparse +import hashlib +import fcntl +import json +from pathlib import Path +from typing import Any + +import torch +import yaml + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def complete_controller( + plan_path: Path, state_path: Path, *, decision_path: Path | None = None, +) -> tuple[dict[str, Any], Path]: + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not report_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or (decision_path is not None and report_path.resolve() != decision_path.resolve()) + ): + raise ValueError(f"controller decision is incomplete or unbound: {state_path}") + report = read_json(report_path) + if report.get("status") != "complete" or report.get("official_test_used") is not False: + raise ValueError(f"controller decision is not isolated: {report_path}") + return report, report_path + + +def normalized_job(job: dict[str, Any], source: str) -> dict[str, Any]: + checkpoint = Path(job.get("checkpoint", job.get("path", ""))) + checkpoint_sha = job.get("checkpoint_sha256", job.get("sha256")) + config = Path(job.get("config", "")) + config_sha = job.get("config_sha256") + if ( + not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha + or not config.is_file() or sha256(config) != config_sha + ): + raise ValueError(f"selected full job differs: {source}") + return { + "source": source, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha, + "config": str(config.resolve()), + "config_sha256": config_sha, + } + + +def preceding_full_job( + stage8: dict[str, Any], selection: dict[str, Any], +) -> tuple[dict[str, Any], str, bool, list[int]]: + resolution_hw = list(stage8["resolution_hw"]) + if stage8.get("shared_augmentation_accepted") is True: + job = normalized_job( + stage8["candidate_training_jobs"]["full"], + "stage8_shared_augmentation_full", + ) + return job, "shared_augmentation", True, resolution_hw + control = stage8["control"] + if control.get("kind") == "resolution_896x512_candidate": + path = Path(control["evaluation_plan"]["path"]) + if not path.is_file() or sha256(path) != control["evaluation_plan"]["sha256"]: + raise ValueError("selected resolution evaluation plan differs") + plan = read_json(path) + job = normalized_job(plan["training_jobs"]["full"], "stage7_resolution_full") + return job, "resolution", False, resolution_hw + if control.get("kind") == "frozen_640_winner": + record = control["selection_report"] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError("selected 640 selection report differs") + selected = read_json(path) + if selected.get("winner") != selection.get("winner"): + raise ValueError("selected 640 winner differs") + job = normalized_job({ + "checkpoint": selected["winner_checkpoint"]["path"], + "checkpoint_sha256": selected["winner_checkpoint"]["sha256"], + "config": selected["winner_config"]["path"], + "config_sha256": selected["winner_config"]["sha256"], + }, "phase9_frozen_640_winner") + return job, "frozen_640_winner", False, resolution_hw + raise ValueError("Stage 8 selected control kind differs") + + +def checkpoint_contract(job: dict[str, Any], resolution_hw: list[int]) -> int: + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + if ( + config.get("experiment", {}).get("branch") != "phase9_unified" + or config.get("experiment", {}).get("official_test_used") is not False + or list(config.get("data", {}).get("resolution_hw", [])) != resolution_hw + ): + raise ValueError("final deployment config contract differs") + state = torch.load(job["checkpoint"], map_location="cpu", weights_only=False) + extra = state.get("extra", {}) + if ( + extra.get("config") != config + or extra.get("h2o_training_data_used") is not True + or extra.get("official_test_used") is not False + or not isinstance(state.get("model"), dict) + ): + raise ValueError("final deployment checkpoint provenance differs") + return int(state["step"]) + + +def build_freeze( + *, selection_plan_path: Path, selection_state_path: Path, + stage8_plan_path: Path, stage8_state_path: Path, + last2_plan_path: Path, last2_state_path: Path, + validation_manifest: Path, validation_manifest_sha256: str, + training_manifest: Path, training_manifest_sha256: str, +) -> dict[str, Any]: + selection_plan = read_json(selection_plan_path) + selection_state = read_json(selection_state_path) + selection_path = Path(selection_plan["output_json"]) + if ( + selection_state.get("status") != "complete" + or selection_state.get("plan_sha256") != sha256(selection_plan_path) + or selection_state.get("official_test_used") is not False + or selection_state.get("h2o_official_validation_used") is not False + or not selection_path.is_file() + ): + raise ValueError("unified selection is incomplete or unbound") + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("winner") != selection_state.get("winner") + or selection.get("winner_checkpoint") != selection_state.get("winner_checkpoint") + or selection.get("winner_config") != selection_state.get("winner_config") + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("unified selection report differs") + required_plan = {item["id"]: item for item in selection_plan["required_states"]} + required_state = { + item["id"]: item for item in selection_state.get("required_states", []) + } + if len(required_plan) != 9 or set(required_state) != set(required_plan): + raise ValueError("unified selection required-state chain differs") + for identifier, item in required_state.items(): + path = Path(item["path"]) + expected_path = Path(required_plan[identifier]["path"]) + if ( + path.resolve() != expected_path.resolve() + or not path.is_file() or sha256(path) != item["sha256"] + ): + raise ValueError(f"unified selection required state differs: {identifier}") + payload = read_json(path) + if payload.get("status") != "complete" or payload.get("official_test_used") is not False: + raise ValueError(f"unified selection required state is incomplete: {identifier}") + + stage8_plan = read_json(stage8_plan_path) + stage8, stage8_path = complete_controller( + stage8_plan_path, stage8_state_path, + decision_path=Path(stage8_plan["decision_report"]), + ) + last2_plan = read_json(last2_plan_path) + last2, last2_path = complete_controller( + last2_plan_path, last2_state_path, + decision_path=Path(last2_plan["report"]), + ) + if stage8.get("winner") != selection.get("winner"): + raise ValueError("Stage 8 winner differs from unified selection") + + preceding, mechanism, shared_augmentation, resolution_hw = preceding_full_job( + stage8, selection, + ) + selected = str(last2["selected"]) + if selected in {"last2_5e7", "last2_1e6"}: + candidate = "5e7" if selected == "last2_5e7" else "1e6" + report_record = last2["selected_candidate_report"] + candidate_path = Path(report_record["path"]) + if not candidate_path.is_file() or sha256(candidate_path) != report_record["sha256"]: + raise ValueError("selected last-2 candidate report differs") + candidate_report = read_json(candidate_path) + if ( + candidate_report.get("candidate") != candidate + or candidate_report.get("gate", {}).get("accepted") is not True + ): + raise ValueError("selected last-2 gate differs") + job = normalized_job( + candidate_report["candidate_training_jobs"]["full"], selected, + ) + mechanism = selected + shared_augmentation = bool(candidate_report["shared_augmentation"]) + resolution_hw = list(candidate_report["resolution_hw"]) + elif selected == "preceding_mechanism": + job = preceding + else: + raise ValueError("last-2 final selection differs") + + step = checkpoint_contract(job, resolution_hw) + for path, expected, label in ( + (validation_manifest, validation_manifest_sha256, "official validation"), + (training_manifest, training_manifest_sha256, "official train"), + ): + if not path.is_file() or sha256(path) != expected: + raise ValueError(f"{label} manifest differs") + chain = { + "unified_selection_plan": sha256(selection_plan_path), + "unified_selection_state": sha256(selection_state_path), + "unified_selection": sha256(selection_path), + "stage8_controller_plan": sha256(stage8_plan_path), + "stage8_controller_state": sha256(stage8_state_path), + "stage8_decision": sha256(stage8_path), + "last2_finalizer_plan": sha256(last2_plan_path), + "last2_finalizer_state": sha256(last2_state_path), + "last2_final_decision": sha256(last2_path), + } + chain_hash = hashlib.sha256( + json.dumps(chain, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + return { + "schema_version": "phase9_final_deployment_freeze_v1", + "status": "phase9_final_unified_checkpoint_frozen", + "created_utc": last2["created_utc"], + "winner": selection["winner"], + "selected_mechanism": mechanism, + "resolution_hw": resolution_hw, + "shared_augmentation": shared_augmentation, + "checkpoint": { + "path": job["checkpoint"], "sha256": job["checkpoint_sha256"], + "step": step, + }, + "config": {"path": job["config"], "sha256": job["config_sha256"]}, + "selection_chain": chain, + "selection_chain_sha256": chain_hash, + "selection_complete": True, + "stage9_final_decision_complete": True, + "frozen_h2o_input_modes": list(INPUT_MODES), + "h2o_validation_manifest": { + "path": str(validation_manifest.resolve()), + "sha256": validation_manifest_sha256, + }, + "h2o_training_manifest": { + "path": str(training_manifest.resolve()), + "sha256": training_manifest_sha256, + }, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--selection-state", type=Path, required=True) + parser.add_argument("--stage8-plan", type=Path, required=True) + parser.add_argument("--stage8-state", type=Path, required=True) + parser.add_argument("--last2-plan", type=Path, required=True) + parser.add_argument("--last2-state", type=Path, required=True) + parser.add_argument("--validation-manifest", type=Path, required=True) + parser.add_argument("--validation-manifest-sha256", required=True) + parser.add_argument("--training-manifest", type=Path, required=True) + parser.add_argument("--training-manifest-sha256", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = build_freeze( + selection_plan_path=args.selection_plan, + selection_state_path=args.selection_state, + stage8_plan_path=args.stage8_plan, stage8_state_path=args.stage8_state, + last2_plan_path=args.last2_plan, last2_state_path=args.last2_state, + validation_manifest=args.validation_manifest, + validation_manifest_sha256=args.validation_manifest_sha256, + training_manifest=args.training_manifest, + training_manifest_sha256=args.training_manifest_sha256, + ) + if args.output.exists(): + if read_json(args.output) != result: + raise ValueError("existing final deployment freeze differs") + else: + atomic_json(args.output, result) + state = { + "schema_version": "phase9_final_deployment_freeze_state_v1", + "status": "complete", "freeze": str(args.output.resolve()), + "freeze_sha256": sha256(args.output), + "checkpoint_sha256": result["checkpoint"]["sha256"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_freeze_state_v1", + "status": "failed_resumable", + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used": False, + "official_test_used": False, + }) + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c27472cd14392687856490a5d6fd1c44ee7bc4d7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_configs.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Generate the pre-registered Phase 3 decoder/temporal core configs.""" + +from __future__ import annotations + +import argparse +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +LAYOUTS = { + "l0": "sequential", + "l1": "alternating", + "l2": "hybrid_reread", +} +MATRIX_ROWS = ( + ("l0", "t0"), + ("l0", "t1"), + ("l1", "t0"), + ("l1", "t1"), + ("l2", "t1"), +) +MODALITIES = { + "m0": {"use_depth": False, "use_rays": False}, + "m3": {"use_depth": True, "use_rays": True}, +} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + + rows = [] + for modality, modality_values in MODALITIES.items(): + for layout, temporal in MATRIX_ROWS: + for seed in SEEDS: + name = f"core_{modality}_{layout}_{temporal}_s{seed}" + config = { + "name": name, + "seed": seed, + "experiment": { + "phase": 3, + "matrix": "decoder_temporal_core", + "modality": modality.upper(), + "layout": layout.upper(), + "temporal": temporal.upper(), + "registered_axes": ["layout", "temporal_attention", "modality"], + }, + "data": { + "resolution_hw": [288, 512], + "T": 8, + "stride": 1, + "batch_size": 1, + }, + "model": { + "encoder": "dinov3", + "decoder_dim": 512, + "decoder_layers": 3, + "attention_heads": 8, + "decoder_mode": LAYOUTS[layout], + "use_temporal": temporal == "t1", + "use_depth": modality_values["use_depth"], + "depth_mode": "log_depth", + "depth_gate_mode": "fixed", + "depth_gate_fixed_value": 0.5, + "use_rays": modality_values["use_rays"], + "use_bimanual_interaction": True, + "predict_presence": True, + "require_mano": True, + }, + "loss": { + "joint2d": 1.0, + "joint3d_camera": 10.0, + "vertices_camera": 1.0, + "local_pose": 1.0, + "global_orientation": 1.0, + "shape": 0.1, + "translation": 10.0, + "reprojection": 1.0, + "temporal_velocity": 0.1, + "temporal_acceleration": 0.05, + "bimanual_relative_wrist": 1.0, + "presence": 0.0, + }, + "assets": { + "dinov3_source": "third_party/dinov3", + "dinov3_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "mano_root": "/SSD3/jiasen/foundation_hand/pretrained/mano", + }, + "precision": "bf16", + "protocol": { + "max_steps": 100000, + "num_workers": 4, + "checkpoint_interval": 25000, + "validation_interval": 5000, + "validation_batches": 256, + "learning_rate": 5e-5, + "min_learning_rate": 5e-6, + "warmup_steps": 500, + "early_stopping_patience": 0, + "validation_subset_manifest": "artifacts/phase3/validation_subset/validation_subset_256.json", + }, + } + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": modality.upper(), "layout": layout.upper(), + "decoder_mode": LAYOUTS[layout], "temporal": temporal.upper(), + "use_depth": int(modality_values["use_depth"]), + "use_rays": int(modality_values["use_rays"]), + "depth_gate": 0.5 if modality_values["use_depth"] else "not_used", + }) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} configs under {args.output_dir}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_depth_fusion_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_depth_fusion_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..a1436a0b91cc980e884999390c44c9a0fda0795f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_depth_fusion_configs.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Generate the first independent Phase 3 Depth fusion/representation controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = { + "gate025": { + "depth_mode": "log_depth", "depth_gate_mode": "fixed", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.25, + }, + "learned_gate": { + "depth_mode": "log_depth", "depth_gate_mode": "learned", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.5, + }, + "geometry": { + "depth_mode": "geometry", "depth_gate_mode": "fixed", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.5, + }, +} + + +def matrix_row(path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(path), "name": config["name"], "seed": config["seed"], + "modality": "M3", "layout": "L1", "temporal": "T1", + "variant": config["experiment"]["variant"], + "depth_mode": model["depth_mode"], + "depth_gate_mode": model["depth_gate_mode"], + "depth_gate_floor": model["depth_gate_floor"], + "depth_gate_fixed_value": model["depth_gate_fixed_value"], + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_fusion_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_fusion_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, changes in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / f"core_m3_l1_t1_s{seed}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, "matrix": "depth_fusion", "modality": "M3", + "layout": "L1", "temporal": "T1", "variant": variant, + "registered_axes": ["depth_fusion_or_representation"], + "reference": "P0_M3_L1_T1_fixed_gate_0.5", + } + config["model"].update(changes) + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append(matrix_row(path, config, "new_formal_run")) + rows.sort(key=lambda row: (str(row["variant"]), int(row["seed"]))) + write_matrix(args.runs_csv, rows) + write_matrix(args.matrix_csv, rows) + print(f"generated {len(rows)} Depth fusion configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_dropout_dose_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_dropout_dose_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..ff442de59dcd384b1d69070f92c29d57f47b2214 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_dropout_dose_configs.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Generate lower-dose Geometry modality-dropout Phase 3 controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = {"dropout005_geometry": 0.05, "dropout010_geometry": 0.10} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/dropout_dose_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/dropout_dose_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, probability in VARIANTS.items(): + for seed in SEEDS: + base_path = ( + args.base_config_dir + / f"depth_dropout00_geometry_m3_l1_t1_s{seed}.yaml" + ) + config = copy.deepcopy( + yaml.safe_load(base_path.read_text(encoding="utf-8")) + ) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "depth_modality_dropout_dose", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": variant, + "registered_axes": ["modality_dropout_dose"], + "reference": "D2_dropout00_and_dropout02_endpoints", + } + config["model"]["modality_dropout_prob"] = probability + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), + "name": name, + "seed": seed, + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "depth_mode": "geometry", + "variant": variant, + "modality_dropout_prob": probability, + "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(rows[0]), lineterminator="\n" + ) + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} dropout-dose configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_long_tail_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_long_tail_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..45500ef2d771d2f985343c04d4f262ebc1d0645a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_long_tail_configs.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Generate the preregistered E.3 low-learning-rate tail configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/photometric"), + ) + parser.add_argument( + "--checkpoint-root", type=Path, + default=Path("artifacts/phase3/photometric_runs_commit239b0bf"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/long_tail_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + source_name = f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + base_path = args.base_config_dir / f"{source_name}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "low_lr_tail", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": "photometric_on_r640x368_tail150k", + "registered_axes": ["training_duration"], + "reference": source_name, + } + config["protocol"]["max_steps"] = 150_000 + config["protocol"]["lr_schedule_steps"] = 100_000 + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + checkpoint = args.checkpoint_root / source_name / "step_0100000_final.pt" + rows.append({ + "config": str(path.resolve()), "name": name, "seed": seed, + "resume_checkpoint": str(checkpoint.resolve()), + "start_step": 100_000, "max_steps": 150_000, + "lr_schedule_steps": 100_000, "min_learning_rate": 5e-6, + "changed_variable": "training_duration_only", + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} E.3 low-LR-tail configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_modality_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_modality_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c89255f39b11007505204124621076e0d01704eb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_modality_configs.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Generate the new M1/M2 runs for the Phase 3 modality matrix.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +NEW_MODALITIES = { + "M1": {"use_depth": False, "use_rays": True}, + "M2": {"use_depth": True, "use_rays": False}, +} + + +def matrix_row(config_path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(config_path), + "name": config["name"], + "seed": config["seed"], + "modality": config["experiment"]["modality"], + "layout": config["experiment"]["layout"], + "temporal": config["experiment"]["temporal"], + "use_depth": int(model["use_depth"]), + "use_rays": int(model["use_rays"]), + "depth_gate": 0.5 if model["use_depth"] else "not_used", + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/modality")) + parser.add_argument("--new-runs-csv", type=Path, default=Path("artifacts/phase3/reports/modality_new_runs.csv")) + parser.add_argument("--full-matrix-csv", type=Path, default=Path("artifacts/phase3/reports/modality_config_matrix.csv")) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + new_rows = [] + full_rows = [] + for seed in SEEDS: + references = {} + for modality in ("M0", "M3"): + path = args.core_config_dir / f"core_{modality.lower()}_l1_t1_s{seed}.yaml" + config = yaml.safe_load(path.read_text(encoding="utf-8")) + references[modality] = config + full_rows.append(matrix_row(path, config, "reused_core_matrix")) + + for modality, flags in NEW_MODALITIES.items(): + config = copy.deepcopy(references["M3"]) + name = f"modality_{modality.lower()}_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "modality_causal", + "modality": modality, + "layout": "L1", + "temporal": "T1", + "registered_axes": ["modality"], + "decoder_promotion_source": "decoder_temporal_core_best_absolute_full_val", + } + config["model"]["use_depth"] = flags["use_depth"] + config["model"]["use_rays"] = flags["use_rays"] + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + row = matrix_row(path, config, "new_formal_run") + new_rows.append(row) + full_rows.append(row) + + new_rows.sort(key=lambda row: (str(row["modality"]), int(row["seed"]))) + full_rows.sort(key=lambda row: (str(row["modality"]), int(row["seed"]))) + write_matrix(args.new_runs_csv, new_rows) + write_matrix(args.full_matrix_csv, full_rows) + print(f"generated {len(new_rows)} new configs and {len(full_rows)} full-matrix rows") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_modality_dropout_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_modality_dropout_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c2841dce151e58be976b8e49d194d5faab3c2e69 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_modality_dropout_configs.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Generate same-commit geometry controls for M3 modality-dropout training.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +DROP_PROB = 0.2 +VARIANTS = {"dropout00_geometry": 0.0, "dropout02_geometry": DROP_PROB} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_dropout_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_dropout_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, probability in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / f"depth_geometry_m3_l1_t1_s{seed}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, "matrix": "depth_modality_dropout", "modality": "M3", + "layout": "L1", "temporal": "T1", "variant": variant, + "registered_axes": ["modality_dropout"], + "reference": "dropout00_geometry_same_commit", + } + config["model"]["modality_dropout_prob"] = probability + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "depth_mode": "geometry", "variant": variant, + "modality_dropout_prob": probability, "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} same-commit geometry modality-dropout configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_photometric_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_photometric_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..138bc89f81a2c18daf910344d7768488270af82f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_photometric_configs.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Generate same-code Phase 3 photometric augmentation off/on controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = {"off": False, "on": True} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/resolution"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/photometric"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/photometric_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/photometric_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, enabled in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"photometric_{variant}_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "photometric_augmentation", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": f"photometric_{variant}_r640x368", + "registered_axes": ["photometric_augmentation"], + "reference": "E1_promoted_r640x368", + } + config["data"]["photometric_augmentation"] = { + "enabled": enabled, + "probability": 0.8, + "brightness": 0.2, + "contrast": 0.2, + "saturation": 0.2, + "hue": 0.05, + } + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "variant": f"photometric_{variant}", + "photometric_enabled": enabled, + "resolution_h": 368, "resolution_w": 640, + "source": "new_same_commit_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} photometric off/on configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_resolution_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_resolution_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..4bc5c0e1550283a14452e8ffc4a36f9ed606302c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_resolution_configs.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Generate the 640x368 Phase 3 resolution controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VALIDATION_SUBSET = ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" +) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/resolution"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/resolution_640_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/resolution_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + base_path = ( + args.base_config_dir + / f"depth_dropout005_geometry_m3_l1_t1_s{seed}.yaml" + ) + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "resolution", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": "dropout005_geometry_r640x368", + "registered_axes": ["input_resolution"], + "reference": "dropout005_geometry_r512x288_D3", + } + config["data"]["resolution_hw"] = [368, 640] + config["protocol"]["validation_subset_manifest"] = VALIDATION_SUBSET + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "depth_mode": "geometry", "variant": "r640x368", + "resolution_h": 368, "resolution_w": 640, + "modality_dropout_prob": 0.05, "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} 640x368 resolution configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_temporal_position_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_temporal_position_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..12031161423294f686ba8f955d905e9de947f069 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase3_temporal_position_configs.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Generate the P0/P1 relative temporal-position experiment configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) + + +def matrix_row(config_path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(config_path), + "name": config["name"], + "seed": config["seed"], + "modality": config["experiment"]["modality"], + "layout": config["experiment"]["layout"], + "temporal": config["experiment"]["temporal"], + "position": config["experiment"].get("position", "P0"), + "temporal_position_mode": model.get("temporal_position_mode", "none"), + "relative_bias_max_distance": model.get("temporal_relative_bias_max_distance", "not_used"), + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/temporal_position")) + parser.add_argument( + "--new-runs-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_new_runs.csv"), + ) + parser.add_argument( + "--p0-runs-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_p0_reused_runs.csv"), + ) + parser.add_argument( + "--full-matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + new_rows = [] + p0_rows = [] + full_rows = [] + for seed in SEEDS: + p0_path = args.core_config_dir / f"core_m3_l1_t1_s{seed}.yaml" + p0 = yaml.safe_load(p0_path.read_text(encoding="utf-8")) + p0_row_config = copy.deepcopy(p0) + p0_row_config["experiment"]["position"] = "P0" + p0_row = matrix_row(p0_path, p0_row_config, "reused_core_matrix") + p0_rows.append(p0_row) + full_rows.append(p0_row) + + p1 = copy.deepcopy(p0) + name = f"temporal_p1_m3_l1_t1_s{seed}" + p1["name"] = name + p1["experiment"] = { + "phase": 3, + "matrix": "temporal_position", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "position": "P1", + "registered_axes": ["temporal_position"], + "reference": "P0_no_temporal_position_reused_core_m3_l1_t1", + } + p1["model"]["temporal_position_mode"] = "relative_bias" + p1["model"]["temporal_relative_bias_max_distance"] = 15 + p1_path = args.output_dir / f"{name}.yaml" + p1_path.write_text(yaml.safe_dump(p1, sort_keys=False), encoding="utf-8") + row = matrix_row(p1_path, p1, "new_formal_run") + new_rows.append(row) + full_rows.append(row) + + write_matrix(args.new_runs_csv, new_rows) + write_matrix(args.p0_runs_csv, p0_rows) + write_matrix(args.full_matrix_csv, full_rows) + print(f"generated {len(new_rows)} new configs and {len(full_rows)} P0/P1 rows") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase4_a3_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase4_a3_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..11d025bc0e7dd6e7f56fcad7fc54c12e8e9b509d --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase4_a3_configs.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Generate hash-bound A3 oracle-crop tiny/health/formal configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +import json +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +MODES = { + "rgb": "oracle_rgb", + "depth_k": "oracle_depth_k", + "rgb_depth_k": "oracle_rgb_depth_k", +} +STAGES = { + "tiny2k": { + "stage": "tiny", "max_steps": 2_000, "checkpoint_interval": 500, + "validation_interval": 500, "warmup_steps": 100, + "validation_subset_manifest": None, + }, + "health25k": { + "stage": "health", "max_steps": 25_000, + "checkpoint_interval": 5_000, "validation_interval": 5_000, + "warmup_steps": 500, + "validation_subset_manifest": ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" + ), + }, + "formal100k": { + "stage": "formal", "max_steps": 100_000, + "checkpoint_interval": 25_000, "validation_interval": 5_000, + "warmup_steps": 500, + "validation_subset_manifest": ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" + ), + }, +} + + +def protocol(stage: dict[str, object]) -> dict[str, object]: + output = { + "max_steps": stage["max_steps"], + "num_workers": 4, + "checkpoint_interval": stage["checkpoint_interval"], + "validation_interval": stage["validation_interval"], + "validation_batches": 256, + "learning_rate": 5e-5, + "min_learning_rate": 5e-6, + "warmup_steps": stage["warmup_steps"], + "early_stopping_patience": 0, + "lr_schedule_steps": stage["max_steps"], + } + if stage["validation_subset_manifest"] is not None: + output["validation_subset_manifest"] = stage["validation_subset_manifest"] + return output + + +def build_config( + base: dict, + mode_slug: str, + stage_slug: str, + checkpoint: dict, +) -> dict: + result = copy.deepcopy(base) + mode = MODES[mode_slug] + stage = STAGES[stage_slug] + seed = int(base["seed"]) + name = f"phase4_a3_{mode_slug}_r640x368_s{seed}_{stage_slug}" + result["name"] = name + result["experiment"] = { + "phase": 4, + "wave": "A", + "cell": "A3", + "stage": stage["stage"], + "oracle_crop_mode": mode, + "reference": base["name"], + "changed_variable": "oracle_raw_high_resolution_crop_residual_only", + "coarse_checkpoint_path": checkpoint["path"], + "coarse_checkpoint_sha256": checkpoint["sha256"], + "coarse_checkpoint_step": checkpoint["step"], + "gt_location_at_train_and_validation": True, + "deployable_inference": False, + "official_test_used": False, + } + result["model"].update({ + "oracle_crop_mode": mode, + "freeze_coarse_for_oracle_crop": True, + }) + result["sampling"] = {"mode": "uniform"} + result["protocol"] = protocol(stage) + return result + + +def write_config_matrices( + rows: list[dict[str, object]], + matrix_csv: Path, + formal_matrix_csv: Path, +) -> list[dict[str, object]]: + if not rows: + raise ValueError("at least one A3 configuration row is required") + matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + if not formal_rows: + raise ValueError("A3 configuration matrix has no formal rows") + formal_matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + return formal_rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--checkpoint-index", type=Path, + default=Path("artifacts/phase3/reports/long_tail_checkpoints.json"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase4/a3_oracle_crop"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/a3_oracle_crop_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/a3_oracle_crop_formal_config_matrix.csv"), + ) + args = parser.parse_args() + checkpoint_index = json.loads(args.checkpoint_index.read_text(encoding="utf-8")) + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + "longtail_photometric_on_geometry_m3_l1_t1_" + f"r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + run = checkpoint_index["runs"][base["name"]] + checkpoint = run["roles"]["tail_best_absolute"] + if int(run["seed"]) != seed or int(checkpoint["step"]) not in range(100_000, 150_001): + raise ValueError(f"invalid frozen checkpoint record for seed {seed}") + for mode_slug, mode in MODES.items(): + for stage_slug in STAGES: + if stage_slug != "formal100k" and seed != SEEDS[0]: + continue + generated = build_config(base, mode_slug, stage_slug, checkpoint) + output_path = args.output_dir / f"{generated['name']}.yaml" + output_path.write_text( + yaml.safe_dump(generated, sort_keys=False), encoding="utf-8", + ) + rows.append({ + "config": str(output_path.resolve()), + "name": generated["name"], + "seed": seed, + "mode": mode, + "stage": STAGES[stage_slug]["stage"], + "max_steps": STAGES[stage_slug]["max_steps"], + "initialization_checkpoint": checkpoint["path"], + "initialization_checkpoint_sha256": checkpoint["sha256"], + "initialization_checkpoint_step": checkpoint["step"], + "gt_location": True, + "official_test_used": False, + }) + formal_rows = write_config_matrices( + rows, args.matrix_csv, args.formal_matrix_csv, + ) + print(json.dumps({ + "status": "generated", "configs": len(rows), + "output_dir": str(args.output_dir), "matrix_csv": str(args.matrix_csv), + "formal_configs": len(formal_rows), + "formal_matrix_csv": str(args.formal_matrix_csv), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase4_b0_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase4_b0_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..374500c074dfdc0d588ae23fef22449cd82d1893 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase4_b0_configs.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Generate preregistered Phase 4 B0 axis-aware loss configurations.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +AXIS_WEIGHTS = (0.5, 0.5, 2.0) +HUBER_BETA_M = 0.01 + + +def b0_config(base: dict, seed: int, stage: str) -> dict: + config = copy.deepcopy(base) + config["seed"] = seed + suffix = { + "smoke": "smoke1", + "tiny": "tiny2k", + "health": "health25k", + "formal": "formal100k", + }[stage] + config["name"] = f"phase4_b0_axis_huber_r640x368_s{seed}_{suffix}" + config["experiment"] = { + "phase": 4, + "wave": "B", + "cell": "B0", + "stage": stage, + "reference": f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}", + "changed_variable": "translation_loss_only", + "frozen_model_recipe": True, + "official_test_used": False, + } + config["loss"]["translation_mode"] = "axis_huber" + config["loss"]["translation_axis_weights"] = list(AXIS_WEIGHTS) + config["loss"]["translation_huber_beta_m"] = HUBER_BETA_M + protocol = config["protocol"] + if stage == "smoke": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 1, + "lr_schedule_steps": 1, + "warmup_steps": 0, + "checkpoint_interval": 1, + "validation_interval": 1, + }) + elif stage == "tiny": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 2_000, + "lr_schedule_steps": 2_000, + "warmup_steps": 100, + "checkpoint_interval": 500, + "validation_interval": 500, + }) + elif stage == "health": + protocol.update({ + "max_steps": 25_000, + "lr_schedule_steps": 25_000, + "warmup_steps": 500, + "checkpoint_interval": 5_000, + "validation_interval": 5_000, + }) + elif stage == "formal": + protocol.update({ + "max_steps": 100_000, + "lr_schedule_steps": 100_000, + "warmup_steps": 500, + "checkpoint_interval": 25_000, + "validation_interval": 5_000, + }) + return config + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, default=Path("configs/phase3/long_tail"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase4/b0_axis_loss")) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b0_axis_loss_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b0_axis_loss_formal_config_matrix.csv"), + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + stages = ("smoke", "tiny", "health", "formal") if seed == SEEDS[0] else ("formal",) + for stage in stages: + config = b0_config(base, seed, stage) + path = args.output_dir / f"{config['name']}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), + "name": config["name"], + "seed": seed, + "stage": stage, + "run_name": f"{stage}_seed{seed}", + "max_steps": config["protocol"]["max_steps"], + "changed_variable": "translation loss L1 -> axis Huber", + "translation_axis_weights": "0.5,0.5,2.0", + "translation_huber_beta_m": HUBER_BETA_M, + "official_test_used": False, + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + with args.formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + print(f"generated {len(rows)} Phase 4 B0 configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase4_b2_configs.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase4_b2_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..fa886d4b37a143c5c5e844620f87afaea3cec7f1 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/generate_phase4_b2_configs.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Generate preregistered Phase 4 B2 balanced-sampling configurations.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +FULL_SAMPLER_MANIFEST = Path( + "/home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/" + "train_geometry_balanced_v1.json" +) +TINY_SAMPLER_MANIFEST = Path( + "/home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/" + "tiny_train_geometry_balanced_v1.json" +) + + +def b2_config(base: dict, seed: int, stage: str) -> dict: + config = copy.deepcopy(base) + config["seed"] = seed + suffix = { + "smoke": "smoke1", + "tiny": "tiny2k", + "health": "health25k", + "formal": "formal100k", + }[stage] + config["name"] = f"phase4_b2_balanced_sampler_r640x368_s{seed}_{suffix}" + config["experiment"] = { + "phase": 4, + "wave": "B", + "cell": "B2", + "stage": stage, + "reference": f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}", + "changed_variable": "training_sampler_only", + "frozen_model_recipe": True, + "official_test_used": False, + } + config["sampling"] = { + "mode": "balanced", + "manifest": str( + TINY_SAMPLER_MANIFEST if stage == "tiny" else FULL_SAMPLER_MANIFEST + ), + } + protocol = config["protocol"] + if stage == "smoke": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 1, + "lr_schedule_steps": 1, + "warmup_steps": 0, + "checkpoint_interval": 1, + "validation_interval": 1, + }) + elif stage == "tiny": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 2_000, + "lr_schedule_steps": 2_000, + "warmup_steps": 100, + "checkpoint_interval": 500, + "validation_interval": 500, + }) + elif stage == "health": + protocol.update({ + "max_steps": 25_000, + "lr_schedule_steps": 25_000, + "warmup_steps": 500, + "checkpoint_interval": 5_000, + "validation_interval": 5_000, + }) + elif stage == "formal": + protocol.update({ + "max_steps": 100_000, + "lr_schedule_steps": 100_000, + "warmup_steps": 500, + "checkpoint_interval": 25_000, + "validation_interval": 5_000, + }) + return config + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("configs/phase4/b2_balanced_sampling"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b2_balanced_sampling_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path( + "artifacts/phase4/reports/b2_balanced_sampling_formal_config_matrix.csv" + ), + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + stages = ("smoke", "tiny", "health", "formal") if seed == SEEDS[0] else ("formal",) + for stage in stages: + config = b2_config(base, seed, stage) + path = args.output_dir / f"{config['name']}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), + "name": config["name"], + "seed": seed, + "stage": stage, + "run_name": f"{stage}_seed{seed}", + "max_steps": config["protocol"]["max_steps"], + "changed_variable": "uniform -> train-only balanced sampling", + "sampling_manifest": config["sampling"]["manifest"], + "official_test_used": False, + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + with args.formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + print(f"generated {len(rows)} Phase 4 B2 configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/import_phase9_distributed_cache_worker_state.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/import_phase9_distributed_cache_worker_state.py new file mode 100644 index 0000000000000000000000000000000000000000..c41dc656030e78d58876c0bd9ad515c24f18ffac --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/import_phase9_distributed_cache_worker_state.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Normalize one external Stage 7 cache worker onto the central admission.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.phase9_distributed_assignment import load_assignment +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +HOST_LOCAL_ADMISSION_FIELDS = frozenset({"admitted_utc", "available_gib"}) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: Any) -> str: + payload = json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def scientific_admission(value: dict[str, Any]) -> dict[str, Any]: + return { + key: item for key, item in value.items() + if key not in HOST_LOCAL_ADMISSION_FIELDS + } + + +def validate_admission_pair( + source: dict[str, Any], central: dict[str, Any], expected_plan_sha256: str, +) -> dict[str, Any]: + for label, value in (("source", source), ("central", central)): + if ( + value.get("schema_version") != "phase9_resolution_admission_v1" + or value.get("status") != "complete" + or value.get("scientific_stage_admitted") is not True + or value.get("plan_sha256") != expected_plan_sha256 + or value.get("official_test_used") is not False + or value.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"{label} admission contract differs") + source_scientific = scientific_admission(source) + central_scientific = scientific_admission(central) + if source_scientific != central_scientific: + differing = sorted( + key for key in set(source_scientific) | set(central_scientific) + if source_scientific.get(key) != central_scientific.get(key) + ) + raise ValueError(f"distributed admission scientific binding differs: {differing}") + return { + "host_local_operational_fields": sorted(HOST_LOCAL_ADMISSION_FIELDS), + "source_operational_values": { + key: source[key] for key in sorted(HOST_LOCAL_ADMISSION_FIELDS) + }, + "central_operational_values": { + key: central[key] for key in sorted(HOST_LOCAL_ADMISSION_FIELDS) + }, + "normalized_scientific_binding_sha256": json_sha256(source_scientific), + } + + +def external_cache_worker_owner( + assignment: dict[str, Any], worker_id: str, +) -> str: + state_id = f"{worker_id}_cache_worker" + owners = { + item["id"]: item["owner"] + for item in assignment["stage7_cache_ownership"]["states"] + } + owner = owners.get(state_id) + if owner is None: + raise ValueError(f"distributed cache worker is undeclared: {worker_id}") + if owner == assignment["central_owner"]: + raise ValueError(f"cache worker is not external-owned: {worker_id}") + return owner + + +def validate_release_metadata( + release: dict[str, Any], receive: dict[str, Any], *, + source_owner: str, source_worker_sha256: str, bridge_plan_sha256: str, +) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != source_owner + or release.get("plan_sha256") != bridge_plan_sha256 + or release.get("producer_worker_state", {}).get("sha256") + != source_worker_sha256 + or release.get("live_reverse_sync_forbidden") is not True + or release.get("read_only_after_receive") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache release binding differs") + if ( + receive.get("status") != "complete" + or receive.get("plan_sha256") != bridge_plan_sha256 + or receive.get("release_file_count") != release.get("file_count") + or receive.get("release_total_bytes") != release.get("total_bytes") + or receive.get("live_reverse_sync_performed") is not False + or receive.get("official_test_used") is not False + or receive.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache receive binding differs") + released = { + item["id"]: (item["path"], item["file_count"], item["total_bytes"]) + for item in release.get("artifacts", []) + } + installed = { + item["id"]: (item["path"], item["file_count"], item["total_bytes"]) + for item in receive.get("installed", []) + } + if released != installed: + raise ValueError("external cache installed artifacts differ from release") + + +def validate_released_cache_files( + release: dict[str, Any], expected_files: list[dict[str, Any]], + resolution_hw: list[int], +) -> list[dict[str, Any]]: + root = Path(release["release_root"]) + inventory = {item["path"]: item for item in release["files"]} + results = [] + for expected in expected_files: + path = Path(expected["path"]) + relative = str(path.relative_to(root)) + record = inventory.get(relative) + if ( + record is None or record.get("sha256") != expected["sha256"] + or record.get("bytes") != path.stat().st_size + or not path.is_file() or sha256(path) != expected["sha256"] + ): + raise ValueError(f"external cache release file hash differs: {path}") + if path.name == "cache_report.json": + report = read_json(path) + if ( + report.get("status") != "complete" + or report.get("resolution_hw") != resolution_hw + or report.get("resume_invocation") is not True + or report.get("official_test_used") is not False + ): + raise ValueError(f"external cache report contract differs: {path}") + results.append({ + "path": str(path.resolve()), "sha256": expected["sha256"], + "release_relative_path": relative, "bytes": record["bytes"], + }) + return results + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("status") != "frozen" + or plan.get("central_owner") != "taku3" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("distributed admission import plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"distributed admission import binding differs: {path}") + assignment = load_assignment(plan) + if sha256(plan_path) == plan.get("superseded_plan_sha256"): + raise ValueError("distributed admission import plan identity differs") + return assignment + + +def build_imported_state(plan_path: Path, plan: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + assignment = validate_plan(plan_path, plan) + worker_id = plan["worker_id"] + source_owner = external_cache_worker_owner(assignment, worker_id) + if source_owner != plan["source_owner"]: + raise ValueError("distributed admission source owner differs") + source_admission_path = Path(plan["source_admission"]["evidence_path"]) + central_admission_path = Path(plan["central_admission"]["path"]) + source_worker_path = Path(plan["source_worker_state"]["evidence_path"]) + release_path = Path(plan["cache_release"]["evidence_path"]) + receive_path = Path(plan["cache_receive"]["path"]) + for path, expected in ( + (source_admission_path, plan["source_admission"]["sha256"]), + (central_admission_path, plan["central_admission"]["sha256"]), + (source_worker_path, plan["source_worker_state"]["sha256"]), + (release_path, plan["cache_release"]["sha256"]), + (receive_path, plan["cache_receive"]["sha256"]), + ): + if not path.is_file() or sha256(path) != expected: + raise ValueError(f"distributed admission evidence differs: {path}") + source_admission = read_json(source_admission_path) + central_admission = read_json(central_admission_path) + source_worker = read_json(source_worker_path) + release = read_json(release_path) + receive = read_json(receive_path) + admission = validate_admission_pair( + source_admission, central_admission, plan["cache_execution_plan_sha256"], + ) + if ( + source_worker.get("status") != "complete" + or source_worker.get("worker") != worker_id + or source_worker.get("plan_sha256") != plan["cache_execution_plan_sha256"] + or source_worker.get("admission_state_sha256") != plan["source_admission"]["sha256"] + or source_worker.get("winner") != central_admission["winner"] + or source_worker.get("winner_checkpoint") != central_admission["winner_checkpoint"] + or source_worker.get("winner_config") != central_admission["winner_config"] + or source_worker.get("official_test_used") is not False + or source_worker.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache worker scientific binding differs") + checkpoint = Path(source_worker["winner_checkpoint"]["path"]) + config = Path(source_worker["winner_config"]["path"]) + if ( + not checkpoint.is_file() + or sha256(checkpoint) != source_worker["winner_checkpoint"]["sha256"] + or not config.is_file() + or sha256(config) != source_worker["winner_config"]["sha256"] + ): + raise ValueError("external cache worker winner artifact differs") + validate_release_metadata( + release, receive, source_owner=source_owner, + source_worker_sha256=plan["source_worker_state"]["sha256"], + bridge_plan_sha256=plan["cache_release"]["plan_sha256"], + ) + if ( + release.get("file_count") != plan["cache_release"]["file_count"] + or release.get("total_bytes") != plan["cache_release"]["total_bytes"] + ): + raise ValueError("external cache release inventory totals differ") + if release["producer_worker_state"].get("value") != source_worker: + raise ValueError("external cache release worker value differs") + released_files = validate_released_cache_files( + release, plan["expected_cache_files"], plan["resolution_hw"], + ) + imported = deepcopy(source_worker) + imported["admission_state"] = str(central_admission_path.resolve()) + imported["admission_state_sha256"] = plan["central_admission"]["sha256"] + imported["distributed_admission_import"] = { + "schema_version": "phase9_distributed_admission_import_v1", + "status": "complete", "imported_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "worker": worker_id, "source_owner": source_owner, + "central_owner": assignment["central_owner"], + **admission, + "source_admission": { + "original_path": plan["source_admission"]["original_path"], + "evidence_path": str(source_admission_path.resolve()), + "sha256": plan["source_admission"]["sha256"], + }, + "central_admission": { + "path": str(central_admission_path.resolve()), + "sha256": plan["central_admission"]["sha256"], + }, + "source_worker_state": { + "original_path": plan["source_worker_state"]["original_path"], + "evidence_path": str(source_worker_path.resolve()), + "sha256": plan["source_worker_state"]["sha256"], + }, + "cache_release": { + "evidence_path": str(release_path.resolve()), + "sha256": plan["cache_release"]["sha256"], + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + }, + "cache_receive": { + "path": str(receive_path.resolve()), + "sha256": plan["cache_receive"]["sha256"], + }, + "released_cache_files": released_files, + "source_worker_state_preserved_unmodified": True, + "ordinary_single_host_binding_gate_changed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + audit = { + "schema_version": "phase9_distributed_admission_import_audit_v1", + "status": "complete", "created_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "worker": worker_id, "source_owner": source_owner, + "central_owner": assignment["central_owner"], + "source_admission_sha256": plan["source_admission"]["sha256"], + "central_admission_sha256": plan["central_admission"]["sha256"], + "host_local_operational_fields": admission["host_local_operational_fields"], + "normalized_scientific_binding_sha256": admission[ + "normalized_scientific_binding_sha256" + ], + "cache_release_sha256": plan["cache_release"]["sha256"], + "cache_receive_sha256": plan["cache_receive"]["sha256"], + "cache_release_file_count": release["file_count"], + "cache_release_total_bytes": release["total_bytes"], + "ordinary_single_host_binding_gate_changed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + return imported, audit + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output-state", type=Path, required=True) + parser.add_argument("--audit-output", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + if args.output_state.resolve() != Path(plan["output_state"]).resolve(): + parser.error("distributed admission output state differs") + if args.audit_output.resolve() != Path(plan["audit_output"]).resolve(): + parser.error("distributed admission audit output differs") + with Path(f"{args.output_state}.import.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + imported, audit = build_imported_state(args.plan, plan) + existing = read_json(args.output_state) if args.output_state.is_file() else None + if existing and existing.get("distributed_admission_import", {}).get( + "plan_sha256" + ) == sha256(args.plan): + if not args.audit_output.is_file(): + parser.error("imported worker exists without its audit") + print(json.dumps(existing, indent=2)) + return + atomic_json(args.output_state, imported) + audit["imported_worker_state"] = { + "path": str(args.output_state.resolve()), "sha256": sha256(args.output_state), + } + atomic_json(args.audit_output, audit) + print(json.dumps(imported, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/inspect_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/inspect_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..dad107db9c8f8406ee3a87089dcc0316a72f4fbb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/inspect_h2o.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +"""Inventory an extracted H2O egocentric dataset using only the standard library.""" + +from __future__ import annotations + +import argparse +import json +import struct +from collections import Counter, defaultdict +from pathlib import Path + + +CORE_FRAME_MODALITIES = { + "rgb", + "rgb256", + "depth", + "cam_pose", + "hand_pose", + "hand_pose_mano", + "obj_pose", + "obj_pose_rt", +} +TRAIN_LABEL_MODALITIES = {"action_label", "verb_label"} + + +def image_info(path: Path) -> dict[str, object]: + with path.open("rb") as handle: + header = handle.read(32) + if header.startswith(b"\x89PNG\r\n\x1a\n"): + width, height, bit_depth, color_type = struct.unpack(">IIBB", header[16:26]) + channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(color_type) + return { + "format": "PNG", + "width": width, + "height": height, + "bit_depth_per_channel": bit_depth, + "channels": channels, + "png_color_type": color_type, + } + + if header.startswith(b"\xff\xd8"): + handle.seek(2) + while True: + marker_start = handle.read(1) + if not marker_start: + break + if marker_start != b"\xff": + continue + marker = handle.read(1) + while marker == b"\xff": + marker = handle.read(1) + if marker in {b"\xd8", b"\xd9"}: + continue + size_raw = handle.read(2) + if len(size_raw) != 2: + break + size = struct.unpack(">H", size_raw)[0] + if marker and marker[0] in { + 0xC0, + 0xC1, + 0xC2, + 0xC3, + 0xC5, + 0xC6, + 0xC7, + 0xC9, + 0xCA, + 0xCB, + 0xCD, + 0xCE, + 0xCF, + }: + payload = handle.read(6) + bits, height, width, channels = struct.unpack(">BHHB", payload) + return { + "format": "JPEG", + "width": width, + "height": height, + "bit_depth_per_channel": bits, + "channels": channels, + } + handle.seek(size - 2, 1) + return {"format": "unknown"} + + +def numeric_frame_ids(files: list[Path]) -> set[int]: + return {int(path.stem) for path in files if path.stem.isdigit()} + + +def inspect_text(path: Path) -> dict[str, object]: + values = path.read_text(encoding="utf-8").split() + numeric = [] + for value in values[:8]: + try: + numeric.append(float(value)) + except ValueError: + numeric.append(value) + return {"value_count": len(values), "first_values": numeric} + + +def inspect_splits(root: Path) -> dict[str, object]: + result: dict[str, object] = {} + split_root = root / "label_split" + for split_path in sorted(split_root.glob("*.txt")): + lines = [line.strip() for line in split_path.read_text().splitlines() if line.strip()] + if split_path.name.startswith("pose_"): + missing = sum(not (root / line).is_file() for line in lines) + result[split_path.name] = { + "rows": len(lines), + "missing_paths": missing, + "first": lines[0] if lines else None, + "last": lines[-1] if lines else None, + } + else: + header = lines[0].split() if lines else [] + rows = [line.split() for line in lines[1:]] + path_index = header.index("path") if "path" in header else 1 + missing = sum(not (root / row[path_index]).is_dir() for row in rows) + class_counts: Counter[str] = Counter() + if "action_label" in header: + label_index = header.index("action_label") + class_counts.update(row[label_index] for row in rows) + result[split_path.name] = { + "rows": len(rows), + "columns": header, + "missing_paths": missing, + "class_counts": dict(sorted(class_counts.items(), key=lambda item: int(item[0]))), + } + return result + + +def inspect_dataset(root: Path) -> dict[str, object]: + modalities: dict[str, dict[str, object]] = defaultdict( + lambda: {"files": 0, "bytes": 0, "suffixes": set(), "sample": None} + ) + subject_take_counts: Counter[str] = Counter() + subject_rgb_frames: Counter[str] = Counter() + scene_take_counts: Counter[str] = Counter() + cameras: Counter[str] = Counter() + alignment_issue_counts: Counter[str] = Counter() + unexpected_alignment_issue_counts: Counter[str] = Counter() + alignment_examples: list[dict[str, object]] = [] + missing_modality_directory_takes: Counter[str] = Counter() + unexpected_modality_directory_takes: Counter[str] = Counter() + scalar_label_counts: dict[str, Counter[str]] = { + "action_label": Counter(), + "verb_label": Counter(), + "obj_pose": Counter(), + "obj_pose_rt": Counter(), + } + hand_presence: dict[str, Counter[str]] = { + "hand_pose": Counter(), + "hand_pose_mano": Counter(), + } + + take_dirs = sorted(root.glob("subject*/*/*/cam4")) + for cam4 in take_dirs: + subject, scene, take = cam4.parts[-4:-1] + subject_take_counts[subject] += 1 + scene_take_counts[f"{subject}/{scene}"] += 1 + for camera_dir in cam4.parent.glob("cam*"): + if camera_dir.is_dir(): + cameras[camera_dir.name] += 1 + + files_by_modality: dict[str, list[Path]] = {} + for child in sorted(cam4.iterdir()): + if child.is_dir(): + files = [entry for entry in child.iterdir() if entry.is_file()] + files_by_modality[child.name] = files + stats = modalities[child.name] + stats["files"] = int(stats["files"]) + len(files) + stats["bytes"] = int(stats["bytes"]) + sum(entry.stat().st_size for entry in files) + suffixes = stats["suffixes"] + assert isinstance(suffixes, set) + suffixes.update(entry.suffix.lower() for entry in files) + if stats["sample"] is None and files: + sample_path = sorted(files)[0] + sample: dict[str, object] = {"path": str(sample_path.relative_to(root))} + if sample_path.suffix.lower() in {".png", ".jpg", ".jpeg"}: + sample.update(image_info(sample_path)) + elif sample_path.suffix.lower() == ".txt": + sample.update(inspect_text(sample_path)) + stats["sample"] = sample + if child.name in scalar_label_counts: + for entry in files: + values = entry.read_text(encoding="utf-8").split() + if values: + scalar_label_counts[child.name][str(int(float(values[0])))] += 1 + if child.name in hand_presence: + right_flag_index = 64 if child.name == "hand_pose" else 62 + for entry in files: + values = entry.read_text(encoding="utf-8").split() + if len(values) <= right_flag_index: + hand_presence[child.name]["malformed"] += 1 + continue + left = int(float(values[0])) != 0 + right = int(float(values[right_flag_index])) != 0 + state = { + (True, True): "both", + (True, False): "left_only", + (False, True): "right_only", + (False, False): "neither", + }[(left, right)] + hand_presence[child.name][state] += 1 + elif child.is_file(): + stats = modalities[child.name] + stats["files"] = int(stats["files"]) + 1 + stats["bytes"] = int(stats["bytes"]) + child.stat().st_size + suffixes = stats["suffixes"] + assert isinstance(suffixes, set) + suffixes.add(child.suffix.lower()) + if stats["sample"] is None: + stats["sample"] = { + "path": str(child.relative_to(root)), + **inspect_text(child), + } + + expected_modalities = set(CORE_FRAME_MODALITIES) + if subject != "subject4": + expected_modalities.update(TRAIN_LABEL_MODALITIES) + actual_modalities = set(files_by_modality) + for modality in expected_modalities - actual_modalities: + missing_modality_directory_takes[modality] += 1 + for modality in actual_modalities - expected_modalities: + unexpected_modality_directory_takes[modality] += 1 + + rgb_ids = numeric_frame_ids(files_by_modality.get("rgb", [])) + subject_rgb_frames[subject] += len(rgb_ids) + for modality, files in files_by_modality.items(): + ids = numeric_frame_ids(files) + if ids and ids != rgb_ids: + missing = len(rgb_ids - ids) + extra = len(ids - rgb_ids) + if modality in expected_modalities: + alignment_issue_counts[modality] += 1 + alignment_scope = "expected" + else: + unexpected_alignment_issue_counts[modality] += 1 + alignment_scope = "unexpected" + if len(alignment_examples) < 20: + alignment_examples.append( + { + "take": f"{subject}/{scene}/{take}", + "modality": modality, + "scope": alignment_scope, + "missing_vs_rgb": missing, + "extra_vs_rgb": extra, + } + ) + + serializable_modalities = {} + for name, stats in sorted(modalities.items()): + serializable_modalities[name] = { + **stats, + "suffixes": sorted(stats["suffixes"]), + } + + object_stats = {} + for object_dir in sorted((root / "object").glob("*")): + if object_dir.is_dir(): + object_stats[object_dir.name] = sorted(path.name for path in object_dir.iterdir() if path.is_file()) + + return { + "root": str(root.resolve()), + "subjects": sorted(subject_take_counts), + "take_count": sum(subject_take_counts.values()), + "take_counts_by_subject": dict(sorted(subject_take_counts.items())), + "rgb_frames_by_subject": dict(sorted(subject_rgb_frames.items())), + "rgb_frames_total": sum(subject_rgb_frames.values()), + "take_counts_by_subject_scene": dict(sorted(scene_take_counts.items())), + "camera_directories": dict(sorted(cameras.items())), + "modalities": serializable_modalities, + "frame_alignment_issue_takes": dict(sorted(alignment_issue_counts.items())), + "unexpected_frame_alignment_issue_takes": dict(sorted(unexpected_alignment_issue_counts.items())), + "frame_alignment_examples": alignment_examples, + "missing_modality_directory_takes": dict(sorted(missing_modality_directory_takes.items())), + "unexpected_modality_directory_takes": dict(sorted(unexpected_modality_directory_takes.items())), + "per_frame_label_counts": { + name: dict(sorted(counts.items(), key=lambda item: int(item[0]))) + for name, counts in scalar_label_counts.items() + }, + "hand_presence_counts": { + name: dict(sorted(counts.items())) for name, counts in hand_presence.items() + }, + "objects": object_stats, + "splits": inspect_splits(root), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path, help="Extracted H2O root") + parser.add_argument("--output", type=Path, help="Write JSON to this path") + args = parser.parse_args() + report = inspect_dataset(args.root) + payload = json.dumps(report, indent=2, ensure_ascii=False) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(payload, encoding="utf-8") + print(payload, end="") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/merge_phase9_hot_prefill.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/merge_phase9_hot_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..a7db862b539b070f3f4174295d1c83bcbc7a2dfa --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/merge_phase9_hot_prefill.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Atomically hardlink completed HOT3D prefill shards into a live cache.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path + +from scripts.cache_phase7_hot3d import sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_prefill_reports(reports: list[dict]) -> None: + if not reports: + raise ValueError("at least one prefill report is required") + for report in reports: + if ( + report.get("status") != "complete" + or report.get("mode") != "staged_prefill" + or report.get("official_test_used") is not False + ): + raise ValueError("prefill report is incomplete or lacks test isolation") + stable_keys = ( + "full_candidate_clips", "requested_target_clips", "max_recordings", + "candidate_source_indices_sha256", + ) + for key in stable_keys: + if len({json.dumps(report.get(key), sort_keys=True) for report in reports}) != 1: + raise ValueError(f"prefill reports disagree on {key}") + source_hashes = {report["source_manifest"]["sha256"] for report in reports} + if len(source_hashes) != 1: + raise ValueError("prefill reports disagree on source manifest SHA256") + ranges = sorted(tuple(report["candidate_position_range"]) for report in reports) + if any(first[1] > second[0] for first, second in zip(ranges, ranges[1:])): + raise ValueError("prefill position ranges overlap") + + +def merge_prefills( + target_output_dir: Path, prefill_output_dirs: list[Path], report_path: Path, +) -> dict: + reports = [ + json.loads((path / "cache_report.json").read_text(encoding="utf-8")) + for path in prefill_output_dirs + ] + validate_prefill_reports(reports) + target_clips = target_output_dir / "clips" + if not target_clips.is_dir(): + raise ValueError("target cache clips directory does not exist") + if (target_output_dir / "cache_manifest.jsonl").exists(): + raise ValueError("target deployable manifest is already frozen") + linked = existing_identical = 0 + shard_records = [] + for output_dir, report in zip(prefill_output_dirs, reports, strict=True): + manifest = output_dir / "prefill_manifest.jsonl" + if sha256(manifest) != report["cache_manifest"]["sha256"]: + raise ValueError(f"prefill manifest SHA256 differs: {manifest}") + rows = [ + json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if len(rows) != int(report["clips"]): + raise ValueError(f"prefill manifest row count differs: {manifest}") + for row in rows: + source = Path(row["cache_path"]) + expected_name = f"clip_{int(row['source_clip_index']):07d}.npz" + if source.name != expected_name or not source.is_file(): + raise ValueError(f"invalid staged cache path: {source}") + if sha256(source) != row["cache_sha256"]: + raise ValueError(f"staged cache SHA256 differs: {source}") + target = target_clips / expected_name + try: + os.link(source, target) + linked += 1 + except FileExistsError: + if sha256(target) != row["cache_sha256"]: + raise ValueError(f"target cache collision differs: {target}") + existing_identical += 1 + shard_records.append({ + "output_dir": str(output_dir.resolve()), + "report_sha256": sha256(output_dir / "cache_report.json"), + "manifest_sha256": sha256(manifest), + "candidate_position_range": report["candidate_position_range"], + "clips": len(rows), + }) + result = { + "schema_version": "phase9_hot_prefill_merge_v1", + "status": "complete", "created_utc": utc_now(), + "target_output_dir": str(target_output_dir.resolve()), + "linked": linked, "existing_identical": existing_identical, + "shards": shard_records, "official_test_used": False, + } + report_path.parent.mkdir(parents=True, exist_ok=True) + temporary = report_path.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(report_path) + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--target-output-dir", type=Path, required=True) + parser.add_argument("--prefill-output-dir", type=Path, action="append", required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + result = merge_prefills( + args.target_output_dir, args.prefill_output_dir, args.report, + ) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/merge_phase9_selection_binding_recovery.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/merge_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..b71938506149e999f92a5aa6039455009504e185 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/merge_phase9_selection_binding_recovery.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""Dry-run, validate, and atomically merge Phase 9 selection recovery.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any, Callable + +from scripts.run_phase9_selection_binding_recovery import ( + atomic_json, + validate_recovered_output, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_release( + *, release_path: Path, plan_path: Path, plan: dict[str, Any], owner: str, +) -> dict[str, Any]: + if not release_path.is_file(): + raise ValueError(f"selection recovery release missing: {owner}") + release = json.loads(release_path.read_text(encoding="utf-8")) + root = release_path.parent.resolve() + expected_ids = { + item["id"] for item in plan["evaluations"] if item["owner"] == owner + } + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != owner + or release.get("plan", {}).get("sha256") != sha256(plan_path) + or Path(str(release.get("root", ""))).resolve() != root + or set(release.get("evaluation_ids", [])) != expected_ids + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or release.get("read_only_after_publish") is not True + ): + raise ValueError(f"selection recovery release contract differs: {owner}") + seen = set() + total_bytes = 0 + for item in release.get("files", []): + relative = Path(item["path"]) + if relative.is_absolute() or ".." in relative.parts or str(relative) in seen: + raise ValueError(f"invalid recovery release path: {relative}") + seen.add(str(relative)) + path = root / relative + if ( + not path.is_file() + or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"selection recovery release file differs: {path}") + total_bytes += item["bytes"] + if ( + len(seen) != release.get("file_count") + or total_bytes != release.get("total_bytes") + ): + raise ValueError(f"selection recovery release inventory differs: {owner}") + evidence = {item["id"]: item for item in release["evaluations"]} + if set(evidence) != expected_ids: + raise ValueError(f"selection recovery release evidence differs: {owner}") + for item in plan["evaluations"]: + if item["owner"] != owner: + continue + relative_output = Path(evidence[item["id"]]["output_dir"]) + if (root / relative_output).resolve() != Path(item["output_dir"]).resolve(): + raise ValueError(f"selection recovery output path differs: {item['id']}") + validate_recovered_output(item) + return release + + +def symlink_copy(source: str, destination: str) -> str: + os.symlink(str(Path(source).resolve()), destination) + return destination + + +def recovered_output_map( + plan: dict[str, Any], releases: dict[str, dict[str, Any]], + release_paths: dict[str, Path], +) -> dict[str, Path]: + result = {} + for owner, release in releases.items(): + root = release_paths[owner].parent.resolve() + by_id = {item["id"]: item for item in release["evaluations"]} + for item in plan["evaluations"]: + if item["owner"] == owner: + result[item["id"]] = root / by_id[item["id"]]["output_dir"] + return result + + +def run_dry_selection( + *, plan: dict[str, Any], recovered: dict[str, Path], +) -> dict[str, Any]: + selection_plan_path = Path(plan["selection_plan"]["path"]) + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + dry_root = Path(plan["dry_run_root"]) / sha256(selection_plan_path) + milestone_root = dry_root / "h2o_multifold_milestones" + output_json = dry_root / "unified_selection.json" + output_csv = dry_root / "unified_selection.csv" + if output_json.is_file() and output_csv.is_file(): + report = json.loads(output_json.read_text(encoding="utf-8")) + if ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + ): + return { + "root": str(dry_root.resolve()), + "json": {"path": str(output_json.resolve()), "sha256": sha256(output_json)}, + "csv": {"path": str(output_csv.resolve()), "sha256": sha256(output_csv)}, + "winner": report["winner"], + } + raise ValueError("existing selection dry-run output differs") + if dry_root.exists(): + shutil.rmtree(dry_root) + dry_root.mkdir(parents=True) + shutil.copytree( + Path(selection_plan["fold_milestone_root"]), milestone_root, + copy_function=symlink_copy, + ) + for item in plan["evaluations"]: + target = ( + milestone_root / item["condition"] / item["checkpoint_id"] + / item["input_mode"] + ) + if target.is_symlink() or target.is_file(): + target.unlink() + elif target.is_dir(): + shutil.rmtree(target) + os.symlink(str(recovered[item["id"]].resolve()), target, target_is_directory=True) + command = [ + sys.executable, "-m", "scripts.summarize_phase9_unified_selection", + "--external-root", selection_plan["external_root"], + "--fold-final-root", selection_plan["fold_final_root"], + "--fold-milestone-root", str(milestone_root.resolve()), + "--multifold-index", selection_plan["multifold_index"], + "--output-json", str(output_json.resolve()), + "--output-csv", str(output_csv.resolve()), + ] + log_path = dry_root / "summarizer.log" + with log_path.open("x", encoding="utf-8") as log: + result = subprocess.run( + command, cwd=Path.cwd(), stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + if result.returncode or not output_json.is_file() or not output_csv.is_file(): + raise ValueError(f"selection dry-run summarizer failed: {result.returncode}") + report = json.loads(output_json.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError("selection dry-run report isolation differs") + return { + "root": str(dry_root.resolve()), + "json": {"path": str(output_json.resolve()), "sha256": sha256(output_json)}, + "csv": {"path": str(output_csv.resolve()), "sha256": sha256(output_csv)}, + "log": {"path": str(log_path.resolve()), "sha256": sha256(log_path)}, + "winner": report["winner"], + } + + +def canonical_output(plan: dict[str, Any], item: dict[str, Any]) -> Path: + return ( + Path(plan["canonical_fold_milestone_root"]) + / item["condition"] / item["checkpoint_id"] / item["input_mode"] + ) + + +def prepare_outputs( + *, plan: dict[str, Any], recovered: dict[str, Path], +) -> dict[str, Path]: + prepared = {} + for item in plan["evaluations"]: + canonical = canonical_output(plan, item) + destination = canonical.parent / f".{canonical.name}.selection_recovery_v2_ready" + if destination.exists(): + shutil.rmtree(destination) + shutil.copytree(recovered[item["id"]], destination, copy_function=shutil.copy2) + candidate = {**item, "output_dir": str(destination.resolve())} + validate_recovered_output(candidate) + prepared[item["id"]] = destination + return prepared + + +def merge_outputs( + *, plan_path: Path, plan: dict[str, Any], prepared: dict[str, Path], + dry_run: dict[str, Any], releases: dict[str, dict[str, Any]], + release_paths: dict[str, Path], state_path: Path, +) -> dict[str, Any]: + backup_root = Path(plan["canonical_merge_backup_root"]) + backup_root.mkdir(parents=True, exist_ok=True) + lock_path = backup_root.parent / ".selection_binding_v2_merge.lock" + plan_hash = sha256(plan_path) + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if state_path.is_file(): + existing = json.loads(state_path.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == plan_hash + ): + return existing + if existing.get("plan_sha256") not in {None, plan_hash}: + raise ValueError("existing selection merge state differs") + replacements = [] + try: + for item in plan["evaluations"]: + canonical = canonical_output(plan, item) + backup = ( + backup_root / item["condition"] / item["checkpoint_id"] + / item["input_mode"] + ) + if backup.exists(): + raise ValueError(f"selection merge backup already exists: {backup}") + if not canonical.is_dir(): + raise ValueError(f"selection canonical output missing: {canonical}") + backup.parent.mkdir(parents=True, exist_ok=True) + os.replace(canonical, backup) + try: + os.replace(prepared[item["id"]], canonical) + except Exception: + os.replace(backup, canonical) + raise + replacements.append((item, canonical, backup)) + except Exception: + for item, canonical, backup in reversed(replacements): + staging = canonical.parent / f".{canonical.name}.rollback_recovered" + if staging.exists(): + shutil.rmtree(staging) + os.replace(canonical, staging) + os.replace(backup, canonical) + raise + merged = [] + for item, canonical, backup in replacements: + candidate = {**item, "output_dir": str(canonical.resolve())} + evidence = validate_recovered_output(candidate) + merged.append({ + "id": item["id"], "canonical_output": str(canonical.resolve()), + "backup_output": str(backup.resolve()), **evidence, + }) + state = { + "schema_version": "phase9_selection_binding_recovery_merge_state_v1", + "status": "complete", "completed_utc": datetime.now(timezone.utc).isoformat(), + "plan": str(plan_path.resolve()), "plan_sha256": plan_hash, + "dry_run": dry_run, + "releases": { + owner: { + "path": str(release_paths[owner].resolve()), + "sha256": sha256(release_paths[owner]), + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + } + for owner, release in releases.items() + }, + "merged": merged, + "failure_backup": plan["failure_backup"], + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(state_path, state) + return state + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--taku3-release", type=Path, required=True) + parser.add_argument("--server-new-release", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if ( + plan.get("official_test_used") is not False + or args.state.resolve() != Path(plan["canonical_merge_state"]).resolve() + ): + parser.error("selection merge plan/state contract differs") + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + parser.error(f"selection recovery code binding differs: {path}") + release_paths = { + "taku3": args.taku3_release, "server_new": args.server_new_release, + } + releases = { + owner: validate_release( + release_path=path, plan_path=args.plan, plan=plan, owner=owner, + ) + for owner, path in release_paths.items() + } + recovered = recovered_output_map(plan, releases, release_paths) + dry_run = run_dry_selection(plan=plan, recovered=recovered) + prepared = prepare_outputs(plan=plan, recovered=recovered) + state = merge_outputs( + plan_path=args.plan, plan=plan, prepared=prepared, dry_run=dry_run, + releases=releases, release_paths=release_paths, state_path=args.state, + ) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/merge_sota_bundles.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/merge_sota_bundles.py new file mode 100644 index 0000000000000000000000000000000000000000..584ee70fdf4d271fce83b8faeacf785e8d0e4324 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/merge_sota_bundles.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Merge disjoint inference shards and restore official-manifest frame order.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("inputs", nargs="+", type=Path) + args = parser.parse_args() + bundles = [PredictionBundle.load(path) for path in args.inputs] + names = {bundle.model_name for bundle in bundles} + if len(names) != 1: + raise ValueError(f"Shard model names differ: {names}") + has_vertices = {bundle.vertices_camera_m is not None for bundle in bundles} + if len(has_vertices) != 1: + raise ValueError("Shard vertex availability differs") + keys, _, _ = load_frame_index(args.manifest) + order_lookup = {str(key): index for index, key in enumerate(keys)} + concatenated_keys = np.concatenate([bundle.frame_keys for bundle in bundles]) + if set(map(str, concatenated_keys.tolist())) != set(map(str, keys.tolist())): + raise ValueError("Merged shards do not exactly cover the manifest") + order = np.argsort([order_lookup[str(key)] for key in concatenated_keys]) + metadata = dict(bundles[0].metadata) + metadata.pop("num_shards", None) + metadata.pop("shard_index", None) + for name in ( + "refined_windows", + "missing_detection_windows", + "tail_hand_frames_falling_back_to_wilor", + "root_iterations_total", + "smooth_iterations_total", + "run_count", + "new_initializations", + "new_optimizations", + ): + if all(name in bundle.metadata for bundle in bundles): + metadata[name] = sum(int(bundle.metadata[name]) for bundle in bundles) + delta_name = "initializer_mesh_reconstruction_delta_mm" + if all(delta_name in bundle.metadata for bundle in bundles): + weights = np.asarray( + [int(bundle.metadata.get("refined_windows", 0)) for bundle in bundles], + dtype=np.float64, + ) + values = np.asarray( + [float(bundle.metadata[delta_name]) for bundle in bundles], + dtype=np.float64, + ) + if weights.sum() > 0: + metadata[delta_name] = float(np.average(values, weights=weights)) + metadata.update({ + "merged_shards": len(bundles), + "shard_inputs": [str(path.resolve()) for path in args.inputs], + }) + PredictionBundle( + model_name=bundles[0].model_name, + frame_keys=concatenated_keys[order], + takes=np.concatenate([bundle.takes for bundle in bundles])[order], + frame_ids=np.concatenate([bundle.frame_ids for bundle in bundles])[order], + joints_camera_m=np.concatenate([ + bundle.joints_camera_m for bundle in bundles + ])[order], + detected=np.concatenate([bundle.detected for bundle in bundles])[order], + confidence=np.concatenate([bundle.confidence for bundle in bundles])[order], + vertices_camera_m=( + np.concatenate([bundle.vertices_camera_m for bundle in bundles])[order] + if True in has_vertices + else None + ), + metadata=metadata, + ).save(args.output) + print(f"merged {len(bundles)} shards into {args.output}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/phase9_distributed_assignment.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/phase9_distributed_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..a244226e86486c4dc547fe55431fa31f45e015c4 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/phase9_distributed_assignment.py @@ -0,0 +1,156 @@ +"""Shared ownership checks for distributed Phase 9 controllers.""" + +from __future__ import annotations + +import json +from pathlib import Path +import socket +from typing import Any + +from scripts.run_phase9_unified_train_queue import sha256 + + +MACHINES = ("taku3", "server_new") + + +def load_assignment(plan: dict[str, Any]) -> dict[str, Any]: + binding = plan.get("distributed_assignment", {}) + path = Path(str(binding.get("path", ""))) + if not path.is_file() or sha256(path) != binding.get("sha256"): + raise ValueError("distributed assignment binding differs") + assignment = json.loads(path.read_text(encoding="utf-8")) + if ( + assignment.get("schema_version") + != "foundation_phase9_distributed_assignment_v2" + or assignment.get("central_owner") != "taku3" + or assignment.get("selection_owner") != "taku3" + or assignment.get("report_owner") != "taku3" + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + or assignment.get("writer_contract", {}).get( + "single_writer_per_output" + ) is not True + or assignment.get("writer_contract", {}).get( + "live_reverse_sync_forbidden" + ) is not True + ): + raise ValueError("distributed assignment contract differs") + return assignment + + +def detect_machine(assignment: dict[str, Any], requested: str | None) -> str: + host = socket.gethostname() + matches = [ + machine for machine in MACHINES + if assignment["machines"][machine]["hostname"] == host + ] + if requested is not None: + if requested not in MACHINES or assignment["machines"][requested]["hostname"] != host: + raise ValueError("requested distributed machine differs from hostname") + return requested + if len(matches) != 1: + raise ValueError(f"hostname is not uniquely assigned: {host}") + return matches[0] + + +def gpu_allowlist(assignment: dict[str, Any], machine: str) -> list[int]: + allowed = assignment["machines"][machine]["physical_gpu_allowlist"] + if ( + not isinstance(allowed, list) + or not allowed + or len(allowed) != len(set(allowed)) + or any(not isinstance(gpu, int) for gpu in allowed) + ): + raise ValueError(f"distributed GPU allowlist differs: {machine}") + if machine == "server_new" and allowed != [0, 1, 2, 5]: + raise ValueError("server_new GPU allowlist must be exactly 0/1/2/5") + return allowed + + +def role_owners(assignment: dict[str, Any]) -> dict[str, str]: + records = assignment["stage_condition_ownership"]["roles"] + result = {item["role"]: item["owner"] for item in records} + expected = { + "full", "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + } + if set(result) != expected or len(records) != len(result): + raise ValueError("distributed role ownership differs") + if any(owner not in MACHINES for owner in result.values()): + raise ValueError("distributed role owner is unknown") + return result + + +def condition_owners( + registry: dict[str, Any], assignment: dict[str, Any], +) -> dict[str, str]: + owners = role_owners(assignment) + result = {} + for item in registry["conditions"]: + condition = item["condition"] + role = item.get("role") + if role not in owners or condition in result: + raise ValueError(f"distributed training role differs: {condition}") + result[condition] = owners[role] + if len(result) != 7: + raise ValueError("distributed training registry must contain seven jobs") + return result + + +def controller_state_path(plan: dict[str, Any], machine: str) -> Path: + states = plan.get("controller_states", {}) + if set(states) != set(MACHINES): + raise ValueError("distributed controller states differ") + paths = [str(Path(value).resolve()) for value in states.values()] + if len(paths) != len(set(paths)): + raise ValueError("distributed controller states are not unique") + return Path(states[machine]) + + +def distribute_evaluations( + *, evaluations: list[dict[str, Any]], assignment: dict[str, Any], + worker_state_root: Path, +) -> list[dict[str, Any]]: + owners = role_owners(assignment) + grouped: dict[str, list[dict[str, Any]]] = {machine: [] for machine in MACHINES} + for item in evaluations: + role = item.get("training_role") + if role not in owners: + raise ValueError(f"distributed evaluation role differs: {item.get('id')}") + owner = owners[role] + item["owner"] = owner + grouped[owner].append(item) + workers = [] + for owner in MACHINES: + gpus = gpu_allowlist(assignment, owner) + buckets: dict[int, list[str]] = {gpu: [] for gpu in gpus} + for index, item in enumerate(grouped[owner]): + buckets[gpus[index % len(gpus)]].append(item["id"]) + for gpu, identifiers in buckets.items(): + if not identifiers: + continue + workers.append({ + "id": f"{owner}_gpu{gpu}", "owner": owner, + "physical_gpu_id": gpu, + "state": str(( + worker_state_root / owner / f"gpu{gpu}_state.json" + ).resolve()), + "evaluation_ids": identifiers, + }) + ids = [item["id"] for item in evaluations] + assigned = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(ids) != len(set(ids)) + or len(assigned) != len(ids) + or len(set(assigned)) != len(ids) + or set(assigned) != set(ids) + ): + raise ValueError("distributed evaluation workers overlap or omit IDs") + return workers + + +def local_workers(workers: list[dict[str, Any]], machine: str) -> list[dict[str, Any]]: + result = [item for item in workers if item.get("owner") == machine] + if any(item.get("owner") not in MACHINES for item in workers): + raise ValueError("distributed evaluation worker owner differs") + return result diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/postprocess_video_jitter.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/postprocess_video_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..0b737af92d0fc6c2aa7713b0b03d209f6147eb86 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/postprocess_video_jitter.py @@ -0,0 +1,927 @@ +#!/usr/bin/env python3 +"""Cache raw long-sequence predictions and render jitter-smoothed MANO demos. + +This is an offline visualization postprocessor. It does not change the model, +checkpoint, evaluator, or reported metrics. Missing raw caches are reconstructed +with the exact checkpoint and non-overlapping temporal chunks recorded in the +source selection manifest. Later filter changes reuse those caches. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from scipy.signal import butter, sosfiltfilt +from scipy.spatial.transform import Rotation + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + MeshLayer, + project_mesh_layers, + render_mesh_layers, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.training.checkpoint import load_checkpoint + + +LEFT_COLOR_RGB = (40, 100, 235) +RIGHT_COLOR_RGB = (235, 55, 55) +MESH_ALPHA = 0.55 +CACHE_VERSION = 1 +RAW_CACHE_KEYS = ( + "mano_rotations_6d", + "mano_rotation_matrices", + "mano_shape", + "wrist_root_translation", + "vertices_camera", + "joints_camera", + "joint2d_norm", + "presence_logit", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_json_atomic(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + os.replace(temporary, path) + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def add_header(image_rgb: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image_rgb.copy() + height = 8 + 22 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, + line, + (8, 20 + 22 * index), + cv2.FONT_HERSHEY_SIMPLEX, + 0.55, + (255, 255, 255), + 1, + cv2.LINE_AA, + ) + return output + + +class FFmpegVideoWriter: + """Stream BGR frames to an atomic, Mac-compatible H.264 MP4.""" + + def __init__( + self, + path: Path, + fps: float, + frame_hw: tuple[int, int], + *, + crf: int, + preset: str, + ) -> None: + self.path = path + self.frame_hw = frame_hw + self.frames_written = 0 + path.parent.mkdir(parents=True, exist_ok=True) + self.temporary = path.with_name(f".{path.stem}.tmp-{os.getpid()}.mp4") + height, width = frame_hw + command = [ + "ffmpeg", + "-nostdin", + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "rawvideo", + "-pix_fmt", + "bgr24", + "-s:v", + f"{width}x{height}", + "-r", + f"{fps:.8g}", + "-i", + "pipe:0", + "-an", + "-c:v", + "libx264", + "-preset", + preset, + "-crf", + str(crf), + "-pix_fmt", + "yuv420p", + "-movflags", + "+faststart", + str(self.temporary), + ] + self.process = subprocess.Popen( + command, + stdin=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + def write(self, frame_bgr: np.ndarray) -> None: + height, width = self.frame_hw + if frame_bgr.shape != (height, width, 3) or frame_bgr.dtype != np.uint8: + raise ValueError( + f"invalid video frame {frame_bgr.shape}/{frame_bgr.dtype}; " + f"expected {(height, width, 3)}/uint8" + ) + if self.process.stdin is None: + raise RuntimeError("ffmpeg stdin is unavailable") + try: + self.process.stdin.write(np.ascontiguousarray(frame_bgr).tobytes()) + except BrokenPipeError as error: + stderr = self._read_stderr() + raise RuntimeError(f"ffmpeg stopped while writing {self.path}: {stderr}") from error + self.frames_written += 1 + + def _read_stderr(self) -> str: + if self.process.stderr is None: + return "" + return self.process.stderr.read().decode("utf-8", errors="replace").strip() + + def close(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + stderr = self._read_stderr() + return_code = self.process.wait() + if return_code != 0: + self.temporary.unlink(missing_ok=True) + raise RuntimeError(f"ffmpeg failed for {self.path}: {stderr}") + os.replace(self.temporary, self.path) + + def abort(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + if self.process.poll() is None: + self.process.terminate() + try: + self.process.wait(timeout=5) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + self.temporary.unlink(missing_ok=True) + + +def lowpass(values: np.ndarray, cutoff_hz: float, fps: float, order: int) -> np.ndarray: + if not 0.0 < cutoff_hz < fps / 2.0: + raise ValueError(f"cutoff must be in (0, {fps / 2.0}), got {cutoff_hz}") + if values.shape[0] < max(12, order * 6): + raise ValueError(f"sequence too short for zero-phase filtering: {values.shape[0]}") + sections = butter(order, cutoff_hz, btype="lowpass", fs=fps, output="sos") + return np.asarray(sosfiltfilt(sections, values, axis=0), dtype=np.float32) + + +def smooth_rotations( + matrices: np.ndarray, + cutoff_hz: float, + fps: float, + order: int, +) -> np.ndarray: + """Low-pass SO(3) trajectories through sign-continuous unit quaternions.""" + + if matrices.ndim != 5 or matrices.shape[1:] != (2, 16, 3, 3): + raise ValueError(f"unexpected rotation shape: {matrices.shape}") + frame_count = matrices.shape[0] + quaternions = Rotation.from_matrix(matrices.reshape(-1, 3, 3)).as_quat() + quaternions = quaternions.reshape(frame_count, 2, 16, 4) + for frame_index in range(1, frame_count): + dots = np.sum( + quaternions[frame_index - 1] * quaternions[frame_index], + axis=-1, + ) + quaternions[frame_index][dots < 0.0] *= -1.0 + filtered = lowpass(quaternions, cutoff_hz, fps, order) + norms = np.linalg.norm(filtered, axis=-1, keepdims=True) + if np.any(norms < 1e-6): + raise RuntimeError("quaternion low-pass produced a near-zero norm") + filtered /= norms + smoothed = Rotation.from_quat(filtered.reshape(-1, 4)).as_matrix() + return smoothed.reshape(matrices.shape).astype(np.float32) + + +def smooth_prediction( + raw: dict[str, np.ndarray], + *, + translation_cutoff_hz: float, + rotation_cutoff_hz: float, + fps: float, + order: int, +) -> dict[str, np.ndarray]: + shape = raw["mano_shape"] + stable_shape = np.median(shape, axis=0, keepdims=True).astype(np.float32) + return { + "frame_ids": raw["frame_ids"].copy(), + "mano_rotation_matrices": smooth_rotations( + raw["mano_rotation_matrices"], rotation_cutoff_hz, fps, order + ), + "mano_shape": np.repeat(stable_shape, shape.shape[0], axis=0), + "wrist_root_translation": lowpass( + raw["wrist_root_translation"], translation_cutoff_hz, fps, order + ), + } + + +def build_model( + config: dict[str, Any], + checkpoint_path: Path, + checkpoint_step: int, + device: torch.device, +) -> BimanualReconstructionModel: + assets = config["assets"] + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + state = load_checkpoint(checkpoint_path, model, optimizer=None, map_location=device) + if int(state["step"]) != checkpoint_step: + raise ValueError( + f"checkpoint step mismatch: expected {checkpoint_step}, got {state['step']}" + ) + return model + + +def infer_case( + *, + case: dict[str, Any], + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + checkpoint_sha256: str, +) -> dict[str, np.ndarray]: + values: dict[str, list[np.ndarray]] = defaultdict(list) + observed_frame_ids: list[int] = [] + for clip_number, clip_index in enumerate(clip_indices, start=1): + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + clip_frame_ids = sample["frame_id"].cpu().numpy().astype(np.int32) + observed_frame_ids.extend(int(value) for value in clip_frame_ids) + for key in RAW_CACHE_KEYS: + if key in prediction: + values[key].append(prediction[key][0].float().cpu().numpy()) + del prediction, batch + if clip_number % 25 == 0 or clip_number == len(clip_indices): + print( + f" inference {clip_number}/{len(clip_indices)} chunks " + f"({len(observed_frame_ids)}/{len(case['frame_ids'])} frames)", + flush=True, + ) + + expected_frame_ids = [int(value) for value in case["frame_ids"]] + if observed_frame_ids != expected_frame_ids: + raise RuntimeError( + f"inference frame mismatch for {case['take']}: " + f"{len(observed_frame_ids)} != {len(expected_frame_ids)}" + ) + arrays = { + key: np.concatenate(chunks, axis=0).astype(np.float32) + for key, chunks in values.items() + } + arrays.update({ + "frame_ids": np.asarray(observed_frame_ids, dtype=np.int32), + "take": np.asarray(str(case["take"])), + "checkpoint_sha256": np.asarray(checkpoint_sha256), + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + }) + required = { + "mano_rotation_matrices", + "mano_shape", + "wrist_root_translation", + "vertices_camera", + "joints_camera", + } + missing = sorted(required - arrays.keys()) + if missing: + raise RuntimeError(f"model output is missing cache fields: {missing}") + for key, value in arrays.items(): + if np.issubdtype(value.dtype, np.floating) and not np.isfinite(value).all(): + raise RuntimeError(f"non-finite values in raw output {key} for {case['take']}") + return arrays + + +def load_raw_cache( + path: Path, + *, + case: dict[str, Any], + checkpoint_sha256: str, +) -> dict[str, np.ndarray] | None: + if not path.is_file(): + return None + try: + with np.load(path, allow_pickle=False) as archive: + raw = {key: archive[key] for key in archive.files} + if int(raw["cache_version"]) != CACHE_VERSION: + return None + if str(raw["take"]) != str(case["take"]): + return None + if str(raw["checkpoint_sha256"]) != checkpoint_sha256: + return None + expected = np.asarray(case["frame_ids"], dtype=np.int32) + if not np.array_equal(raw["frame_ids"], expected): + return None + return raw + except (KeyError, OSError, ValueError): + return None + + +def rebuild_mano_geometry( + prediction: dict[str, np.ndarray], + mano_layer: ManoCameraLayer, + device: torch.device, + *, + batch_size: int = 128, +) -> None: + vertices: list[np.ndarray] = [] + joints: list[np.ndarray] = [] + frame_count = prediction["frame_ids"].shape[0] + for start in range(0, frame_count, batch_size): + stop = min(start + batch_size, frame_count) + rotations = torch.from_numpy( + prediction["mano_rotation_matrices"][start:stop] + ).to(device) + shape = torch.from_numpy(prediction["mano_shape"][start:stop]).to(device) + translation = torch.from_numpy( + prediction["wrist_root_translation"][start:stop] + ).to(device) + with torch.inference_mode(): + vertex_batch, joint_batch = mano_layer(rotations, shape, translation) + vertices.append(vertex_batch.float().cpu().numpy()) + joints.append(joint_batch.float().cpu().numpy()) + prediction["vertices_camera"] = np.concatenate(vertices, axis=0).astype(np.float32) + prediction["joints_camera"] = np.concatenate(joints, axis=0).astype(np.float32) + + +def acceleration_stats(points_m: np.ndarray) -> dict[str, float]: + acceleration_mm = np.linalg.norm(np.diff(points_m, n=2, axis=0), axis=-1) * 1000.0 + return { + "mean_mm_per_frame2": float(acceleration_mm.mean()), + "p50_mm_per_frame2": float(np.percentile(acceleration_mm, 50)), + "p95_mm_per_frame2": float(np.percentile(acceleration_mm, 95)), + } + + +def displacement_stats(raw_m: np.ndarray, smoothed_m: np.ndarray) -> dict[str, float]: + displacement_mm = np.linalg.norm(smoothed_m - raw_m, axis=-1) * 1000.0 + return { + "mean_mm": float(displacement_mm.mean()), + "p50_mm": float(np.percentile(displacement_mm, 50)), + "p95_mm": float(np.percentile(displacement_mm, 95)), + "max_mm": float(displacement_mm.max()), + } + + +def rotation_displacement_stats( + raw_matrices: np.ndarray, + smoothed_matrices: np.ndarray, +) -> dict[str, float]: + relative = np.swapaxes(raw_matrices, -1, -2) @ smoothed_matrices + radians = Rotation.from_matrix(relative.reshape(-1, 3, 3)).magnitude() + degrees = np.degrees(radians) + return { + "mean_degrees": float(degrees.mean()), + "p50_degrees": float(np.percentile(degrees, 50)), + "p95_degrees": float(np.percentile(degrees, 95)), + "max_degrees": float(degrees.max()), + } + + +def jitter_metrics( + raw: dict[str, np.ndarray], + smoothed: dict[str, np.ndarray], +) -> dict[str, Any]: + raw_wrist = acceleration_stats(raw["wrist_root_translation"]) + smooth_wrist = acceleration_stats(smoothed["wrist_root_translation"]) + raw_vertices = acceleration_stats(raw["vertices_camera"]) + smooth_vertices = acceleration_stats(smoothed["vertices_camera"]) + + def reduction(raw_value: float, smooth_value: float) -> float: + return float((1.0 - smooth_value / max(raw_value, 1e-12)) * 100.0) + + return { + "wrist_acceleration_raw": raw_wrist, + "wrist_acceleration_smoothed": smooth_wrist, + "wrist_acceleration_mean_reduction_percent": reduction( + raw_wrist["mean_mm_per_frame2"], smooth_wrist["mean_mm_per_frame2"] + ), + "vertex_acceleration_raw": raw_vertices, + "vertex_acceleration_smoothed": smooth_vertices, + "vertex_acceleration_mean_reduction_percent": reduction( + raw_vertices["mean_mm_per_frame2"], + smooth_vertices["mean_mm_per_frame2"], + ), + "wrist_filter_displacement": displacement_stats( + raw["wrist_root_translation"], smoothed["wrist_root_translation"] + ), + "vertex_filter_displacement": displacement_stats( + raw["vertices_camera"], smoothed["vertices_camera"] + ), + "rotation_filter_displacement": rotation_displacement_stats( + raw["mano_rotation_matrices"], smoothed["mano_rotation_matrices"] + ), + "raw_shape_temporal_std_mean": float(raw["mano_shape"].std(axis=0).mean()), + } + + +def probe_video(path: Path, expected_frames: int, frame_hw: tuple[int, int]) -> None: + command = [ + "ffprobe", + "-v", + "error", + "-select_streams", + "v:0", + "-count_frames", + "-show_entries", + "stream=codec_name,pix_fmt,width,height,nb_read_frames", + "-of", + "json", + str(path), + ] + report = json.loads(subprocess.check_output(command, text=True)) + streams = report.get("streams", []) + if len(streams) != 1: + raise RuntimeError(f"expected one video stream in {path}") + stream = streams[0] + height, width = frame_hw + observed = ( + stream.get("codec_name"), + stream.get("pix_fmt"), + int(stream.get("width", -1)), + int(stream.get("height", -1)), + int(stream.get("nb_read_frames", -1)), + ) + expected = ("h264", "yuv420p", width, height, expected_frames) + if observed != expected: + raise RuntimeError(f"video validation failed for {path}: {observed} != {expected}") + + +def render_case( + *, + case: dict[str, Any], + raw: dict[str, np.ndarray], + smoothed: dict[str, np.ndarray], + source_case_dir: Path, + output_case_dir: Path, + data_root: Path, + faces: tuple[np.ndarray, np.ndarray], + fps: float, + translation_cutoff_hz: float, + rotation_cutoff_hz: float, + filter_order: int, + crf: int, + preset: str, +) -> dict[str, Any]: + output_case_dir.mkdir(parents=True, exist_ok=True) + take_dir = data_root / str(case["take"]) + raw_K, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + height, width = source_hw + output_paths = { + "smoothed_overlay": output_case_dir / "predicted_mano_overlay_smoothed.mp4", + "smoothed_side_by_side": output_case_dir / "side_by_side_smoothed.mp4", + "raw_vs_smoothed": output_case_dir / "raw_vs_smoothed.mp4", + } + writers = [ + FFmpegVideoWriter(output_paths["smoothed_overlay"], fps, source_hw, crf=crf, preset=preset), + FFmpegVideoWriter( + output_paths["smoothed_side_by_side"], + fps, + (height, width * 2), + crf=crf, + preset=preset, + ), + FFmpegVideoWriter( + output_paths["raw_vs_smoothed"], + fps, + (height, width * 2), + crf=crf, + preset=preset, + ), + ] + raw_overlay_path = source_case_dir / "predicted_mano_overlay.mp4" + raw_capture = cv2.VideoCapture(str(raw_overlay_path)) + if not raw_capture.isOpened(): + for writer in writers: + writer.abort() + raise RuntimeError(f"failed to open source overlay: {raw_overlay_path}") + + frame_ids = [int(value) for value in case["frame_ids"]] + preview = None + comparison_preview = None + try: + for frame_index, frame_id in enumerate(frame_ids): + raw_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), + cv2.IMREAD_COLOR, + ) + if raw_bgr is None or raw_bgr.shape[:2] != source_hw: + raise RuntimeError(f"raw RGB decode/shape failure: {take_dir}/{frame_id}") + ok, source_overlay_bgr = raw_capture.read() + if not ok or source_overlay_bgr.shape[:2] != source_hw: + raise RuntimeError( + f"source overlay ended at frame {frame_index}: {raw_overlay_path}" + ) + raw_rgb = cv2.cvtColor(raw_bgr, cv2.COLOR_BGR2RGB) + layers = [ + MeshLayer( + smoothed["vertices_camera"][frame_index, hand], + faces[hand], + LEFT_COLOR_RGB if hand == 0 else RIGHT_COLOR_RGB, + MESH_ALPHA, + ) + for hand in range(2) + ] + rendered = render_mesh_layers(raw_rgb, project_mesh_layers(layers, raw_K)) + rendered = add_header(rendered, ( + f"Post-processed MANO | zero-phase low-pass | left=BLUE right=RED alpha={MESH_ALPHA:.2f}", + f"{case['subject']}/{case['sequence']} | frame={frame_id} " + f"({frame_index + 1}/{len(frame_ids)}) | translation={translation_cutoff_hz:g} Hz " + f"rotation={rotation_cutoff_hz:g} Hz order={filter_order}", + )) + original_panel = add_header(raw_rgb, ("Original cam4 RGB",)) + side_by_side = np.concatenate((original_panel, rendered), axis=1) + source_overlay_rgb = cv2.cvtColor(source_overlay_bgr, cv2.COLOR_BGR2RGB) + raw_vs_smoothed = np.concatenate((source_overlay_rgb, rendered), axis=1) + + writers[0].write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + writers[1].write(cv2.cvtColor(side_by_side, cv2.COLOR_RGB2BGR)) + writers[2].write(cv2.cvtColor(raw_vs_smoothed, cv2.COLOR_RGB2BGR)) + if frame_index == len(frame_ids) // 2: + preview = rendered.copy() + comparison_preview = raw_vs_smoothed.copy() + if (frame_index + 1) % 100 == 0 or frame_index + 1 == len(frame_ids): + print(f" render {frame_index + 1}/{len(frame_ids)} frames", flush=True) + + extra, _ = raw_capture.read() + if extra: + raise RuntimeError(f"source overlay has extra frames: {raw_overlay_path}") + for writer in writers: + writer.close() + except BaseException: + for writer in writers: + if writer.process.poll() is None or writer.temporary.exists(): + writer.abort() + raise + finally: + raw_capture.release() + + if preview is None or comparison_preview is None: + raise RuntimeError(f"no preview generated for {case['take']}") + preview_path = output_case_dir / "preview_smoothed.png" + comparison_preview_path = output_case_dir / "preview_raw_vs_smoothed.png" + cv2.imwrite(str(preview_path), cv2.cvtColor(preview, cv2.COLOR_RGB2BGR)) + cv2.imwrite( + str(comparison_preview_path), + cv2.cvtColor(comparison_preview, cv2.COLOR_RGB2BGR), + ) + probe_video(output_paths["smoothed_overlay"], len(frame_ids), source_hw) + probe_video( + output_paths["smoothed_side_by_side"], + len(frame_ids), + (height, width * 2), + ) + probe_video( + output_paths["raw_vs_smoothed"], + len(frame_ids), + (height, width * 2), + ) + metrics = jitter_metrics(raw, smoothed) + record = { + "take": case["take"], + "subject": case["subject"], + "sequence": case["sequence"], + "category": case["category"], + "rank": case["rank"], + "frame_count": len(frame_ids), + "source_case": str(source_case_dir.resolve()), + "raw_prediction_cache": str((output_case_dir / "raw_prediction.npz").resolve()), + "smoothed_prediction_cache": str( + (output_case_dir / "smoothed_prediction.npz").resolve() + ), + "videos": {key: str(path.resolve()) for key, path in output_paths.items()}, + "preview": str(preview_path.resolve()), + "raw_vs_smoothed_preview": str(comparison_preview_path.resolve()), + "jitter_metrics": metrics, + } + write_json_atomic(output_case_dir / "case_postprocess.json", record) + record["preview_rgb"] = preview + return record + + +def save_contact_sheet(path: Path, records: list[dict[str, Any]]) -> None: + if not records: + return + panels = [] + for record in records: + panel = cv2.resize(record["preview_rgb"], (384, 216), interpolation=cv2.INTER_AREA) + panel = add_header(panel, ( + f"{record['category']} #{record['rank']} | " + f"jitter -{record['jitter_metrics']['vertex_acceleration_mean_reduction_percent']:.1f}%", + )) + panels.append(panel) + while len(panels) % 5: + panels.append(np.zeros_like(panels[0])) + rows = [np.concatenate(panels[index : index + 5], axis=1) for index in range(0, len(panels), 5)] + sheet = np.concatenate(rows, axis=0) + cv2.imwrite(str(path), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR)) + + +def source_case_directory(source_dir: Path, case: dict[str, Any]) -> Path: + category_dir = "best_cases" if case["category"] == "best" else "failure_cases" + recorded = Path(case["videos"]["original"]).parent.name + path = source_dir / category_dir / recorded + if not path.is_dir(): + raise FileNotFoundError(f"source case directory missing: {path}") + return path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Re-infer missing raw MANO caches and render zero-phase jitter-smoothed demos." + ) + parser.add_argument( + "--source-dir", + type=Path, + default=Path("artifacts/phase3/video_cases_best_model_long_sequences"), + ) + parser.add_argument("--output-dir", type=Path) + parser.add_argument("--data-root", type=Path, default=Path("data/H2O/extracted")) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--category", choices=("all", "best", "failure"), default="all") + parser.add_argument("--max-cases", type=int) + parser.add_argument("--translation-cutoff-hz", type=float, default=3.0) + parser.add_argument("--rotation-cutoff-hz", type=float, default=4.0) + parser.add_argument("--filter-order", type=int, default=2) + parser.add_argument("--crf", type=int, default=18) + parser.add_argument( + "--ffmpeg-preset", + choices=("ultrafast", "superfast", "veryfast", "faster", "fast", "medium"), + default="fast", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + source_dir = args.source_dir.resolve() + if args.output_dir is None: + output_dir = source_dir.with_name(f"{source_dir.name}_smoothed") + else: + output_dir = args.output_dir.resolve() + data_root = args.data_root.resolve() + if source_dir == output_dir: + raise ValueError("source and output directories must differ") + if args.filter_order < 1: + raise ValueError("filter order must be positive") + if not 0 <= args.crf <= 51: + raise ValueError("CRF must be in [0, 51]") + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required to reconstruct missing raw prediction caches") + device = torch.device(f"cuda:{args.gpu}") + + selection_path = source_dir / "selection_manifest.json" + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if selection.get("status") != "complete" or selection.get("official_test_used") is not False: + raise ValueError("source selection manifest is incomplete or uses official test data") + config_path = Path(selection["config"]) + checkpoint = selection["checkpoint"] + checkpoint_path = Path(checkpoint["path"]) + expected_checkpoint_hash = str(checkpoint["sha256"]) + observed_checkpoint_hash = sha256(checkpoint_path) + if observed_checkpoint_hash != expected_checkpoint_hash: + raise ValueError("checkpoint hash differs from the source selection manifest") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + fps = float(selection["visualization_fps"]) + lowpass(np.zeros((32, 1), dtype=np.float32), args.translation_cutoff_hz, fps, args.filter_order) + lowpass(np.zeros((32, 1), dtype=np.float32), args.rotation_cutoff_hz, fps, args.filter_order) + + cases = [ + case + for case in selection["cases"] + if args.category == "all" or case["category"] == args.category + ] + if args.max_cases is not None: + if args.max_cases < 1: + raise ValueError("max cases must be positive") + cases = cases[: args.max_cases] + if not cases: + raise ValueError(f"no cases selected for category={args.category}") + output_dir.mkdir(parents=True, exist_ok=True) + + data_config = config["data"] + render_manifest_path = source_dir / "render_input_manifest.jsonl" + model_t = int(data_config["T"]) + dataset = H2OCam4Dataset( + data_root, + render_manifest_path, + tuple(data_config["resolution_hw"]), + (model_t,), + (int(data_config["stride"]),), + ) + clip_indices_by_take: dict[str, list[int]] = defaultdict(list) + for clip_index, clip in enumerate(dataset.clips): + clip_indices_by_take[clip.take].append(clip_index) + + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model: BimanualReconstructionModel | None = None + mano_layer: ManoCameraLayer | None = None + faces: tuple[np.ndarray, np.ndarray] | None = None + records: list[dict[str, Any]] = [] + for case_index, case in enumerate(cases, start=1): + source_case_dir = source_case_directory(source_dir, case) + category_dir = "best_cases" if case["category"] == "best" else "failure_cases" + output_case_dir = output_dir / category_dir / source_case_dir.name + output_case_dir.mkdir(parents=True, exist_ok=True) + raw_cache_path = output_case_dir / "raw_prediction.npz" + print( + f"[{case_index}/{len(cases)}] {case['category']} #{case['rank']} " + f"{case['take']} ({len(case['frame_ids'])} frames)", + flush=True, + ) + raw = load_raw_cache( + raw_cache_path, + case=case, + checkpoint_sha256=expected_checkpoint_hash, + ) + if raw is None: + if model is None: + print("loading frozen model checkpoint", flush=True) + model = build_model( + config, + checkpoint_path, + int(checkpoint["step"]), + device, + ) + mano_layer = model.mano_layer + if mano_layer is None: + raise RuntimeError("loaded model has no MANO layer") + faces = tuple(layer.th_faces.cpu().numpy() for layer in mano_layer.layers) + raw = infer_case( + case=case, + dataset=dataset, + clip_indices=clip_indices_by_take[str(case["take"])], + model=model, + device=device, + dtype=dtype, + checkpoint_sha256=expected_checkpoint_hash, + ) + save_npz_atomic(raw_cache_path, raw) + print(f" saved raw cache: {raw_cache_path}", flush=True) + else: + print(f" reusing raw cache: {raw_cache_path}", flush=True) + + if mano_layer is None: + mano_layer = ManoCameraLayer(config["assets"]["mano_root"]).to(device).eval() + if faces is None: + faces = tuple(layer.th_faces.cpu().numpy() for layer in mano_layer.layers) + smoothed = smooth_prediction( + raw, + translation_cutoff_hz=args.translation_cutoff_hz, + rotation_cutoff_hz=args.rotation_cutoff_hz, + fps=fps, + order=args.filter_order, + ) + rebuild_mano_geometry(smoothed, mano_layer, device) + save_npz_atomic(output_case_dir / "smoothed_prediction.npz", smoothed) + record = render_case( + case=case, + raw=raw, + smoothed=smoothed, + source_case_dir=source_case_dir, + output_case_dir=output_case_dir, + data_root=data_root, + faces=faces, + fps=fps, + translation_cutoff_hz=args.translation_cutoff_hz, + rotation_cutoff_hz=args.rotation_cutoff_hz, + filter_order=args.filter_order, + crf=args.crf, + preset=args.ffmpeg_preset, + ) + records.append(record) + print( + " mean vertex acceleration reduction: " + f"{record['jitter_metrics']['vertex_acceleration_mean_reduction_percent']:.1f}%", + flush=True, + ) + + save_contact_sheet(output_dir / "contact_sheet_smoothed.png", records) + serializable_records = [ + {key: value for key, value in record.items() if key != "preview_rgb"} + for record in records + ] + summary = { + "status": "complete", + "purpose": "offline visualization-only jitter postprocessing", + "source_dir": str(source_dir), + "source_selection_manifest": str(selection_path), + "checkpoint": checkpoint, + "model_inference_policy": ( + f"same frozen checkpoint and non-overlapping T={model_t} chunks as source render" + ), + "raw_cache_policy": ( + "render-relevant raw outputs are cached before filtering and reused on later runs" + ), + "postprocessing": { + "translation": "zero-phase Butterworth low-pass in camera XYZ", + "translation_cutoff_hz": args.translation_cutoff_hz, + "rotation": "zero-phase Butterworth low-pass on sign-continuous unit quaternions", + "rotation_cutoff_hz": args.rotation_cutoff_hz, + "filter_order": args.filter_order, + "shape": "per-take temporal median, held constant", + "fps": fps, + "phase_lag_frames": 0, + }, + "video_encoding": { + "codec": "H.264", + "pixel_format": "yuv420p", + "crf": args.crf, + "preset": args.ffmpeg_preset, + }, + "metrics_are_official_evaluation": False, + "cases": serializable_records, + } + write_json_atomic(output_dir / "postprocess_manifest.json", summary) + mean_reductions = [ + record["jitter_metrics"]["vertex_acceleration_mean_reduction_percent"] + for record in records + ] + readme = f"""# Jitter-Smoothed Long-Sequence Video Cases + +This directory is a visualization-only postprocessing of `{source_dir}`. The +model, checkpoint, official evaluation, and source artifacts are unchanged. + +Missing predictions were reconstructed with the same frozen checkpoint and +non-overlapping T={model_t} inference policy as the source demo. Each case keeps +`raw_prediction.npz` before filtering, so filter parameters can be adjusted and +videos regenerated without running the reconstruction model again. + +The offline filter is a zero-phase order-{args.filter_order} Butterworth low-pass: + +- wrist translation cutoff: {args.translation_cutoff_hz:g} Hz; +- MANO rotation cutoff: {args.rotation_cutoff_hz:g} Hz; +- MANO shape: temporal median held fixed within each take. + +Zero-phase filtering introduces no visual time shift but uses future frames, so +these videos do not represent a causal real-time system. H.264/yuv420p output is +used for macOS playback. `raw_vs_smoothed.mp4` is the clearest A/B view. + +Across the {len(records)} rendered cases, mean per-case vertex-acceleration +reduction is {float(np.mean(mean_reductions)):.1f}%. See +`postprocess_manifest.json` and each `case_postprocess.json` for details. +""" + (output_dir / "README.md").write_text(readme, encoding="utf-8") + print(json.dumps({ + "status": "complete", + "output_dir": str(output_dir), + "case_count": len(records), + "mean_vertex_acceleration_reduction_percent": float(np.mean(mean_reductions)), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/prepare_phase9_storage_overflow.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/prepare_phase9_storage_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..8e5f5a81b71ffeca38c3c4a0820da0a212058a66 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/prepare_phase9_storage_overflow.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Bind unopened Phase 9 fold outputs to a larger physical volume.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def bind_directory(logical: Path, physical: Path) -> str: + if logical.is_symlink(): + if logical.resolve() != physical.resolve(): + raise RuntimeError(f"existing symlink has wrong target: {logical}") + return "existing_identical" + if logical.exists(): + raise RuntimeError(f"logical output already exists: {logical}") + physical.mkdir(parents=True, exist_ok=True) + logical.parent.mkdir(parents=True, exist_ok=True) + os.symlink(physical, logical, target_is_directory=True) + if not logical.is_symlink() or logical.resolve() != physical.resolve(): + raise RuntimeError(f"failed to bind output: {logical}") + return "created" + + +def prepare(plan: dict[str, Any], plan_path: Path) -> dict[str, Any]: + if plan.get("official_test_used") is not False: + raise ValueError("plan must explicitly exclude official test") + registry_path = Path(plan["fold_training_registry"]) + if sha256(registry_path) != plan["fold_training_registry_sha256"]: + raise ValueError("fold registry hash mismatch") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + raise ValueError("fold registry must explicitly exclude official test") + conditions = {row["condition"]: row for row in registry["conditions"]} + logical_roots = { + key: Path(value) for key, value in plan["logical_evaluation_roots"].items() + } + physical_root = Path(plan["physical_root"]) + rows = [] + for condition_id in plan["conditions"]: + if condition_id not in conditions: + raise ValueError(f"condition is absent from registry: {condition_id}") + condition = conditions[condition_id] + bindings = { + "run": ( + Path(condition["output_dir"]), + physical_root / "runs" / "h2o_multifold" / condition_id.lower(), + ), + "final_evaluation": ( + logical_roots["final"] / condition_id, + physical_root / "evaluations" / "h2o_multifold" / condition_id, + ), + "milestone_evaluation": ( + logical_roots["milestone"] / condition_id, + physical_root / "evaluations" / "h2o_multifold_milestones" / condition_id, + ), + } + for kind, (logical, physical) in bindings.items(): + status = bind_directory(logical, physical) + rows.append({ + "condition": condition_id, "kind": kind, "status": status, + "logical": str(logical), "physical": str(physical), + }) + return { + "schema_version": "phase9_storage_overflow_report_v1", + "status": "complete", + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "bindings": rows, + "scientific_protocol_changed": False, + "official_test_used": False, + "completed_utc": utc_now(), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output report already exists") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + report = prepare(plan, args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/probe_memory.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/probe_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..c37fb1447ab5553ded97429d5473f5c2582a7123 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/probe_memory.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""4090 memory matrix using official random DINOv3 architecture (never training).""" + +from __future__ import annotations + +import argparse +import csv +import json +import platform +import time +from pathlib import Path + +import torch +from torch import nn + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.encoders import PatchFeatures + + +class ProbeDinoEncoder(nn.Module): + def __init__(self, backbone: nn.Module, output_dim: int = 512) -> None: + super().__init__() + self.backbone = backbone.requires_grad_(False).eval() + self.projection = nn.Linear(768, output_dim) + self.patch_size = 16 + + def train(self, mode: bool = True): + super().train(mode) + self.backbone.eval() + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + with torch.no_grad(): + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + return PatchFeatures(self.projection(raw), (images.shape[-2] // 16, images.shape[-1] // 16), 16) + + +def make_batch(batch_size: int, time_steps: int, height: int, width: int, device: torch.device) -> dict[str, torch.Tensor]: + K = torch.tensor([[width * 0.5, 0, width * 0.5], [0, width * 0.5, height * 0.5], [0, 0, 1]], device=device, dtype=torch.float32) + return { + "rgb": torch.randn(batch_size, time_steps, 3, height, width, device=device), + "depth_m": torch.rand(batch_size, time_steps, 1, height, width, device=device) + 0.3, + "depth_pixel_valid": torch.ones(batch_size, time_steps, 1, height, width, device=device, dtype=torch.bool), + "K": K[None, None].expand(batch_size, time_steps, -1, -1).clone(), + "K_available": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + "depth_available": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + "frame_valid": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + } + + +def run_case(backbone: nn.Module, case: dict[str, object], device: torch.device) -> dict[str, object]: + height, width = case["height"], case["width"] + dtype = torch.bfloat16 if case["precision"] == "bf16" else torch.float16 + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats(device) + config = ModelConfig( + encoder="tiny_debug", decoder_dim=512, decoder_layers=int(case["decoder_layers"]), attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, depth_mode="log_depth", use_rays=True, + use_bimanual_interaction=True, gradient_checkpointing=bool(case["gradient_checkpointing"]), + ) + model = BimanualReconstructionModel(config) + model.rgb_encoder = ProbeDinoEncoder(backbone, 512) + model.to(device).train() + batch = make_batch(int(case["batch_size"]), int(case["T"]), int(height), int(width), device) + start = time.perf_counter() + try: + with torch.autocast("cuda", dtype=dtype): + output = model(batch) + loss = ( + output["joint2d_norm"].square().mean() + + output["mano_rotations_6d"].square().mean() + + output["wrist_root_translation"].square().mean() + + output["mano_shape_sequence"].square().mean() + ) + forward_end = time.perf_counter() + loss.backward() + torch.cuda.synchronize(device) + end = time.perf_counter() + case.update({ + "status": "ok", "forward_s": forward_end - start, "forward_backward_s": end - start, + "frames_per_s": int(case["batch_size"]) * int(case["T"]) / (end - start), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30, + "loss_finite": bool(torch.isfinite(loss)), + }) + except torch.cuda.OutOfMemoryError as error: + case.update({"status": "oom", "error": str(error).splitlines()[0], "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30}) + finally: + del model, batch + torch.cuda.empty_cache() + return case + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--quick", action="store_true", help="Probe the core matrix; omit extra checkpoint/layer variants") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + torch.cuda.set_device(args.gpu) + device = torch.device("cuda") + from dinov3.hub.backbones import dinov3_vitb16 + torch.manual_seed(20260716) + backbone = dinov3_vitb16(pretrained=False).to(device) + cases = [] + for width, height in ((384, 224), (512, 288), (640, 368)): + for T in (1, 4, 8, 16): + for batch_size in (1, 2): + for precision in ("bf16", "fp16"): + cases.append({"width": width, "height": height, "T": T, "batch_size": batch_size, "precision": precision, "decoder_layers": 3, "gradient_checkpointing": False}) + if not args.quick: + for layers in (2, 3): + for checkpointing in (False, True): + for batch_size in (1, 2): + cases.append({"width": 512, "height": 288, "T": 8, "batch_size": batch_size, "precision": "bf16", "decoder_layers": layers, "gradient_checkpointing": checkpointing}) + + results = [] + for index, case in enumerate(cases): + case.update({"case": index, "gpu": torch.cuda.get_device_name(device), "random_architecture_only": True, "dinov3": "official dinov3_vitb16 pretrained=False", "seed": 20260716}) + result = run_case(backbone, case, device) + results.append(result) + print(json.dumps(result), flush=True) + fields = sorted({key for result in results for key in result}) + with (args.output_dir / "memory_probe.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader(); writer.writerows(results) + summary = { + "warning": "Architecture-only memory probe with official randomly initialized DINOv3 ViT-B/16. Not a training/quality result.", + "torch": torch.__version__, "python": platform.python_version(), "gpu": torch.cuda.get_device_name(device), + "case_count": len(results), "ok": sum(row["status"] == "ok" for row in results), "oom": sum(row["status"] == "oom" for row in results), + "results_csv": str((args.output_dir / "memory_probe.csv").resolve()), + } + (args.output_dir / "memory_probe_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/profile_phase5_alignment_solver.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/profile_phase5_alignment_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..842eb2831c09853c1731c7bd7a4e3d1276cad639 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/profile_phase5_alignment_solver.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Profile the deployable per-frame predicted-MANO/depth alignment solver.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import resource +import time +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def latency_summary(values_ms: list[float]) -> dict[str, float | int]: + values = np.asarray(values_ms, dtype=np.float64) + if not values.size or not np.isfinite(values).all(): + raise ValueError("latency samples must be non-empty and finite") + return { + "frames": int(len(values)), + "mean_ms": float(values.mean()), + "std_ms": float(values.std()), + "p50_ms": float(np.percentile(values, 50)), + "p90_ms": float(np.percentile(values, 90)), + "p95_ms": float(np.percentile(values, 95)), + "minimum_ms": float(values.min()), + "maximum_ms": float(values.max()), + "throughput_frames_per_second": float(1000.0 / values.mean()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--frames", type=int, default=128) + parser.add_argument("--warmup", type=int, default=8) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite profile: {args.output}") + if args.frames < 1 or args.warmup < 0: + parser.error("frames must be positive and warmup non-negative") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("scope") != "full" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + ): + raise ValueError("profile requires a complete official-validation raw cache") + take_record = manifest["takes"][0] + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError("profile take cache hash mismatch") + with np.load(take_path, allow_pickle=False) as archive: + frame_ids = archive["frame_id"][:args.frames].astype(np.int64) + vertices = archive["pred_vertices_camera"][:args.frames].astype(np.float32) + take = str(archive["take"]) + take_dir = args.data_root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + + depths = [] + for frame_id in frame_ids: + depth_mm = cv2.imread( + str(take_dir / "depth" / f"{int(frame_id):06d}.png"), cv2.IMREAD_UNCHANGED, + ) + if depth_mm is None or depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{int(frame_id):06d}") + depths.append(depth_mm_to_m(depth_mm)) + cv2.setNumThreads(1) + for index in range(min(args.warmup, len(frame_ids))): + for hand in range(2): + align_wrist_z(vertices[index, hand], K_raw, *depths[index]) + + elapsed_ms = [] + applied = [] + support = [] + for index in range(len(frame_ids)): + started = time.perf_counter_ns() + for hand in range(2): + diagnostics, _ = align_wrist_z( + vertices[index, hand], K_raw, *depths[index], + ) + applied.append(diagnostics.applied) + support.append(diagnostics.valid_support_count) + elapsed_ms.append((time.perf_counter_ns() - started) / 1_000_000.0) + + report = { + "status": "profiled", + "experiment_class": "engineering_profile_not_model_selection", + "official_validation_used": True, + "official_validation_used_for_model_or_threshold_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], + "take": take, + "frame_range": [int(frame_ids[0]), int(frame_ids[-1])], + "latency": { + **latency_summary(elapsed_ms), + "scope": "CPU per-frame two-hand projection/depth sampling/IRLS; raw depth predecoded; excludes coarse model and file I/O", + }, + "applied_hand_fraction": float(np.mean(applied)), + "support_count_mean": float(np.mean(support)), + "peak_process_rss_mib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0, + "cpu": platform.processor(), + "opencv_threads": cv2.getNumThreads(), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/profile_phase5_model.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/profile_phase5_model.py new file mode 100644 index 0000000000000000000000000000000000000000..08e09f54b448c025820f47f08d473f2dfbf8948b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/profile_phase5_model.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Profile a frozen candidate on one official-train clip without model selection.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader +from torch.utils.flop_counter import FlopCounterMode + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def move_to_device(batch: dict[str, object], device: torch.device) -> dict[str, object]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def parameter_counts(model: torch.nn.Module) -> dict[str, int]: + trainable = sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad) + frozen = sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad) + return {"trainable": trainable, "frozen": frozen, "total": trainable + frozen} + + +def percentile_summary(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + if not array.size or not np.isfinite(array).all(): + raise ValueError("latency measurements must be non-empty and finite") + return { + "iterations": int(len(array)), + "mean_ms": float(array.mean()), + "std_ms": float(array.std()), + "p50_ms": float(np.percentile(array, 50)), + "p90_ms": float(np.percentile(array, 90)), + "p95_ms": float(np.percentile(array, 95)), + "minimum_ms": float(array.min()), + "maximum_ms": float(array.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--warmup", type=int, default=20) + parser.add_argument("--iterations", type=int, default=100) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite profile: {args.output}") + if args.warmup < 1 or args.iterations < 1: + parser.error("warmup and iterations must be positive") + if "test" in args.manifest.name.lower() or "val" in args.manifest.name.lower(): + parser.error("profiling is restricted to official-train data") + checkpoint_hash = sha256(args.checkpoint) + if checkpoint_hash != args.expected_checkpoint_sha256: + parser.error("checkpoint hash mismatch") + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data = config["data"] + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data["resolution_hw"]), + (int(data["T"]),), + (int(data["stride"]),), + max_clips=1, + ) + loader = DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + batch = move_to_device(next(iter(loader)), device) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + if checkpoint.get("extra", {}).get("config") != config: + raise ValueError("profiling config differs from checkpoint embedded config") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + for _ in range(args.warmup): + model(batch) + torch.cuda.synchronize(device) + torch.cuda.reset_peak_memory_stats(device) + starts = [torch.cuda.Event(enable_timing=True) for _ in range(args.iterations)] + ends = [torch.cuda.Event(enable_timing=True) for _ in range(args.iterations)] + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + for start, end in zip(starts, ends, strict=True): + start.record() + model(batch) + end.record() + torch.cuda.synchronize(device) + latency = percentile_summary([start.elapsed_time(end) for start, end in zip(starts, ends, strict=True)]) + peak_vram_gib = torch.cuda.max_memory_allocated(device) / 2**30 + + flop_counter = FlopCounterMode(display=False) + # FlopCounterMode's module tracker requires an autograd graph in PyTorch 2.6. + # This single pass is excluded from the inference latency measurements above. + with torch.autocast("cuda", dtype=dtype), flop_counter: + model(batch) + supported_flops = int(flop_counter.get_total_flops()) + report = { + "status": "profiled", + "experiment_class": "engineering_profile_not_model_selection", + "official_validation_used": False, + "official_test_used": False, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], check=True, text=True, stdout=subprocess.PIPE, + ).stdout.strip(), + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": int(checkpoint["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "input": { + "batch_size": 1, + "clip_length": int(data["T"]), + "resolution_hw": list(data["resolution_hw"]), + "modalities": ["RGB", "Depth", "K"], + "precision": config["precision"], + }, + "parameters": parameter_counts(model), + "supported_operator_flops_per_clip": supported_flops, + "flops_scope": "PyTorch FlopCounterMode supported operators; forward only; unsupported custom operators are not estimated", + "latency": {**latency, "scope": "GPU model forward only; excludes data loading and host preprocessing"}, + "peak_allocated_vram_gib": peak_vram_gib, + "gpu": torch.cuda.get_device_name(device), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/rank_phase7_external.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/rank_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..0a13c2df62d7118453c90ff38151bfa4acf049f4 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/rank_phase7_external.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Rank Phase 7 external checkpoints without frame-count weighting or H2O.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_p95_mm", +) + + +def dense_ranks(values: dict[str, float]) -> dict[str, int]: + ordered = sorted(set(values.values())) + return {name: ordered.index(value) + 1 for name, value in values.items()} + + +def evaluation_metrics(report: dict[str, Any]) -> dict[str, float]: + metrics = report["metrics"] + values = { + "absolute_mpjpe_mm": metrics["absolute_mpjpe_mm"]["mean"], + "root_relative_mpjpe_mm": metrics["root_relative_mpjpe_mm"]["mean"], + "fingertip_mpjpe_mm": metrics["fingertip_mpjpe_mm"]["mean"], + "translation_z_p95_mm": metrics["translation_z_mae_mm"]["p95"], + } + if any(value is None or not math.isfinite(float(value)) for value in values.values()): + raise ValueError("selection metrics must all be finite") + return {key: float(value) for key, value in values.items()} + + +def load_entries(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if manifest.get("selection_split") != "external_heldout_only": + raise ValueError("selection manifest must be external_heldout_only") + expected = set(manifest["datasets"]) + if expected != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("selection requires exactly HOT3D, HOI4D and ARCTIC") + entries: list[dict[str, Any]] = [] + pairs: set[tuple[str, str]] = set() + steps: set[int] = set() + for item in manifest["evaluations"]: + condition = str(item["condition"]) + dataset = str(item["dataset"]) + pair = (condition, dataset) + if pair in pairs: + raise ValueError(f"duplicate condition/dataset pair: {pair}") + pairs.add(pair) + if dataset not in expected: + raise ValueError(f"unexpected dataset: {dataset}") + path = Path(item["path"]).resolve() + report = json.loads(path.read_text(encoding="utf-8")) + cache_path = str(report["cache_manifest"]["path"]).lower() + if "h2o" in cache_path or report.get("h2o_training_data_used") is not False: + raise ValueError("external ranking refuses H2O data or training exposure") + if report.get("official_test_used") is not False: + raise ValueError("external ranking refuses official-test evaluation") + step = int(report["checkpoint_step"]) + steps.add(step) + entries.append({ + "condition": condition, + "dataset": dataset, + "input_mode": report["input_mode"], + "checkpoint_step": step, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "evaluation_path": str(path), + **evaluation_metrics(report), + }) + conditions = {entry["condition"] for entry in entries} + missing = {(condition, dataset) for condition in conditions for dataset in expected} - pairs + if missing: + raise ValueError(f"incomplete condition/dataset grid: {sorted(missing)}") + if len(steps) != 1: + raise ValueError(f"checkpoint steps are not matched: {sorted(steps)}") + return entries + + +def pareto_frontier(vectors: dict[str, list[float]]) -> list[str]: + frontier = [] + for condition, vector in vectors.items(): + dominated = any( + other != condition + and all(left <= right for left, right in zip(other_vector, vector)) + and any(left < right for left, right in zip(other_vector, vector)) + for other, other_vector in vectors.items() + ) + if not dominated: + frontier.append(condition) + return sorted(frontier) + + +def rank_entries(entries: list[dict[str, Any]]) -> dict[str, Any]: + steps = {int(entry["checkpoint_step"]) for entry in entries} + if len(steps) != 1: + raise ValueError(f"checkpoint steps are not matched: {sorted(steps)}") + datasets = sorted({entry["dataset"] for entry in entries}) + conditions = sorted({entry["condition"] for entry in entries}) + lookup = {(entry["condition"], entry["dataset"]): entry for entry in entries} + dataset_ranks: dict[str, dict[str, float]] = {} + vectors = {condition: [] for condition in conditions} + for dataset in datasets: + metric_ranks = { + metric: dense_ranks({ + condition: lookup[(condition, dataset)][metric] + for condition in conditions + }) + for metric in METRICS + } + dataset_ranks[dataset] = {} + for condition in conditions: + score = sum(metric_ranks[metric][condition] for metric in METRICS) / len(METRICS) + dataset_ranks[dataset][condition] = score + vectors[condition].extend( + lookup[(condition, dataset)][metric] for metric in METRICS + ) + macro = { + condition: sum(dataset_ranks[dataset][condition] for dataset in datasets) / len(datasets) + for condition in conditions + } + order = sorted(conditions, key=lambda condition: ( + macro[condition], + sum(lookup[(condition, dataset)]["absolute_mpjpe_mm"] for dataset in datasets), + sum(lookup[(condition, dataset)]["root_relative_mpjpe_mm"] for dataset in datasets), + condition, + )) + return { + "matched_checkpoint_step": entries[0]["checkpoint_step"], + "dataset_ranks": dataset_ranks, + "macro_mean_rank": macro, + "pareto_frontier": pareto_frontier(vectors), + "order": order, + "winner": order[0], + "entries": entries, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + result = { + "status": "ranked_external_only", + "selection_rule": "dataset metric ranks -> macro mean rank -> Absolute/root-relative tie-break", + "frame_count_weighted": False, + "h2o_used": False, + "official_test_used": False, + **rank_entries(load_entries(manifest)), + } + args.output_dir.mkdir(parents=True, exist_ok=False) + (args.output_dir / "ranking.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + with (args.output_dir / "ranking.csv").open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, + fieldnames=( + "condition", "macro_mean_rank", "on_pareto_frontier", + ), + lineterminator="\n", + ) + writer.writeheader() + for condition in result["order"]: + writer.writerow({ + "condition": condition, + "macro_mean_rank": result["macro_mean_rank"][condition], + "on_pareto_frontier": condition in result["pareto_frontier"], + }) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/recover_phase9_arctic_resolution_cache.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/recover_phase9_arctic_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f62598bfecb94ccf2457dade735b0bca9d13fc --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/recover_phase9_arctic_resolution_cache.py @@ -0,0 +1,561 @@ +#!/usr/bin/env python3 +"""Restore the Stage 7 ARCTIC cache to the frozen 640 source-index set.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +from typing import Any + +import cv2 +import numpy as np + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + cache_step_complete, + sha256, + validate_plan_bindings, +) + + +IDENTITY_FIELDS = ( + "dataset_id", + "subject_id", + "physical_recording_id", + "source_group_key", + "camera_id", + "stream_id", + "headset_id", +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def load_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def indexed_rows( + rows: list[dict[str, Any]], label: str, +) -> tuple[list[int], dict[int, dict[str, Any]]]: + order = [int(row["source_clip_index"]) for row in rows] + if len(order) != len(set(order)): + duplicates = sorted({value for value in order if order.count(value) > 1}) + raise ValueError(f"{label} has duplicate source clip indices: {duplicates}") + return order, dict(zip(order, rows, strict=True)) + + +def compare_source_sets( + control_rows: list[dict[str, Any]], candidate_rows: list[dict[str, Any]], +) -> dict[str, Any]: + control_order, control = indexed_rows(control_rows, "control manifest") + candidate_order, candidate = indexed_rows(candidate_rows, "candidate manifest") + control_set, candidate_set = set(control), set(candidate) + missing = sorted(control_set - candidate_set) + extra = sorted(candidate_set - control_set) + drift = [] + for source_index in control_order: + if source_index not in candidate: + continue + differing = { + field: { + "control": control[source_index].get(field), + "candidate": candidate[source_index].get(field), + } + for field in IDENTITY_FIELDS + if control[source_index].get(field) != candidate[source_index].get(field) + } + if differing: + drift.append({"source_clip_index": source_index, "fields": differing}) + control_groups = {row["source_group_key"] for row in control_rows} + candidate_groups = { + candidate[index]["source_group_key"] + for index in control_order if index in candidate + } + return { + "control_count": len(control_order), + "candidate_count": len(candidate_order), + "control_unique_count": len(control_set), + "candidate_unique_count": len(candidate_set), + "missing_source_clip_indices": missing, + "extra_source_clip_indices": extra, + "identity_drift": drift, + "control_group_count": len(control_groups), + "candidate_accepted_group_count": len(candidate_groups), + "missing_groups": sorted(control_groups - candidate_groups), + "extra_groups": sorted(candidate_groups - control_groups), + } + + +def canonical_rows( + control_rows: list[dict[str, Any]], candidate_rows: list[dict[str, Any]], +) -> list[dict[str, Any]]: + comparison = compare_source_sets(control_rows, candidate_rows) + if ( + comparison["missing_source_clip_indices"] + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC source-index or group contract differs") + control_order, _ = indexed_rows(control_rows, "control manifest") + _, candidate = indexed_rows(candidate_rows, "candidate manifest") + return [candidate[index] for index in control_order] + + +def write_jsonl_atomic(path: Path, rows: list[dict[str, Any]]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + temporary.replace(path) + + +def preserve_file(source: Path, destination: Path) -> dict[str, Any]: + destination.parent.mkdir(parents=True, exist_ok=True) + source_hash = sha256(source) + if destination.exists(): + if not destination.is_file() or sha256(destination) != source_hash: + raise ValueError(f"preserved recovery evidence differs: {destination}") + else: + shutil.copy2(source, destination) + os.chmod(destination, 0o444) + return { + "path": str(destination.resolve()), + "sha256": source_hash, + "bytes": source.stat().st_size, + } + + +def quarantine_payload( + row: dict[str, Any], quarantine_root: Path, pass_id: str, +) -> dict[str, Any]: + source = Path(row["cache_path"]) + expected_hash = row["cache_sha256"] + if not source.is_file() or sha256(source) != expected_hash: + raise ValueError(f"extra ARCTIC payload differs: {source}") + destination = quarantine_root / pass_id / source.name + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + if not destination.is_file() or sha256(destination) != expected_hash: + raise ValueError(f"ARCTIC quarantine collision differs: {destination}") + source.unlink() + else: + source.replace(destination) + os.chmod(destination, 0o444) + return { + "source_clip_index": int(row["source_clip_index"]), + "path": str(destination.resolve()), + "sha256": expected_hash, + "bytes": destination.stat().st_size, + } + + +def payload_audit(rows: list[dict[str, Any]]) -> dict[str, Any]: + totals = { + "bytes": 0, + "clips_with_translation_supervision": 0, + "translation_valid_elements": 0, + "joint3d_valid_elements": 0, + "mano_annotation_valid_elements": 0, + } + probes: dict[int, dict[str, Any]] = {} + probe_positions = {0, len(rows) // 2, len(rows) - 1} + for position, row in enumerate(rows): + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"canonical ARCTIC payload differs: {path}") + with np.load(path, allow_pickle=False) as archive: + image_hw = [int(value) for value in archive["image_hw"].reshape(-1)] + if image_hw != [512, 896]: + raise ValueError(f"canonical ARCTIC resolution differs: {path}") + translation = np.asarray(archive["translation_valid"], dtype=bool) + joint3d = np.asarray(archive["joint3d_valid"], dtype=bool) + mano = np.asarray(archive["mano_annotation_valid"], dtype=bool) + if not translation.any(): + raise ValueError(f"canonical ARCTIC clip lacks supervision: {path}") + totals["bytes"] += path.stat().st_size + totals["clips_with_translation_supervision"] += 1 + totals["translation_valid_elements"] += int(translation.sum()) + totals["joint3d_valid_elements"] += int(joint3d.sum()) + totals["mano_annotation_valid_elements"] += int(mano.sum()) + if position in probe_positions: + probes[position] = { + "position": position, + "source_clip_index": int(row["source_clip_index"]), + "path": str(path.resolve()), + "sha256": row["cache_sha256"], + "image_hw": image_hw, + "frame_ids": archive["frame_id"].astype(int).tolist(), + "translation_valid_elements": int(translation.sum()), + "joint3d_valid_elements": int(joint3d.sum()), + } + return {**totals, "probes": [probes[key] for key in sorted(probes)]} + + +def source_extra_audit( + *, source_manifest: Path, control_report: dict[str, Any], + candidate_report: dict[str, Any], candidate_by_index: dict[int, dict[str, Any]], + extra_indices: list[int], mano_root: Path, +) -> list[dict[str, Any]]: + source_rows = [ + json.loads(line) + for line in source_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + control_skipped = {int(value) for value in control_report["skipped_no_supervision"]} + candidate_skipped = { + int(value) for value in candidate_report["skipped_no_supervision"] + } + low_dataset = ARCTICClipDataset( + source_manifest, mano_root, target_hw=(368, 640), + ) + high_dataset = ARCTICClipDataset( + source_manifest, mano_root, target_hw=(512, 896), + ) + results = [] + for source_index in extra_indices: + source = source_rows[source_index] + candidate = candidate_by_index[source_index] + images = [] + for value in source["image_paths"]: + path = Path(value) + image = cv2.imread(str(path), cv2.IMREAD_COLOR) + images.append({ + "path": str(path.resolve()), + "exists": path.is_file(), + "bytes": path.stat().st_size if path.is_file() else None, + "decoded_hw": list(image.shape[:2]) if image is not None else None, + }) + if any(not item["exists"] or item["decoded_hw"] != [600, 840] for item in images): + raise ValueError(f"ARCTIC extra source image differs: {source_index}") + mano_path, camera_path = Path(source["mano_path"]), Path(source["camera_path"]) + if not mano_path.is_file() or not camera_path.is_file(): + raise ValueError(f"ARCTIC extra annotation is missing: {source_index}") + mano_value = np.load(mano_path, allow_pickle=True).item() + camera_value = np.load(camera_path, allow_pickle=True).item() + if not {"left", "right"}.issubset(mano_value) or not { + "R_k_cam_np", "T_k_cam_np", "intrinsics", "dist8", + }.issubset(camera_value): + raise ValueError(f"ARCTIC extra annotation contract differs: {source_index}") + low = low_dataset[(source_index, 0)] + high = high_dataset[(source_index, 0)] + low_count = int(low["translation_valid"].sum()) + high_count = int(high["translation_valid"].sum()) + if ( + source_index not in control_skipped + or source_index in candidate_skipped + or low_count != 0 + or high_count <= 0 + or source["group_key"] != candidate["source_group_key"] + or source["physical_recording_id"] != candidate["physical_recording_id"] + ): + raise ValueError(f"ARCTIC extra acceptance reason differs: {source_index}") + results.append({ + "source_clip_index": source_index, + "classification": "resolution_dependent_supervision_boundary", + "control_640_reason": "skipped_no_supervision", + "control_640_translation_valid_elements": low_count, + "candidate_896_translation_valid_elements": high_count, + "subject_id": source["subject_id"], + "physical_recording_id": source["physical_recording_id"], + "source_group_key": source["group_key"], + "frame_ids_1based": source["frame_ids_1based"], + "images": images, + "mano_annotation": { + "path": str(mano_path.resolve()), "bytes": mano_path.stat().st_size, + "sides": sorted(mano_value), + }, + "camera_annotation": { + "path": str(camera_path.resolve()), "bytes": camera_path.stat().st_size, + "required_fields_present": True, + }, + }) + return results + + +def validate_recovery_plan(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("status") != "frozen" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("ARCTIC recovery plan isolation differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"ARCTIC recovery binding differs: {path}") + execution_path = Path(plan["execution_plan"]["path"]) + execution = json.loads(execution_path.read_text(encoding="utf-8")) + if sha256(execution_path) != plan["execution_plan"]["sha256"]: + raise ValueError("ARCTIC execution plan binding differs") + validate_plan_bindings(execution) + return execution + + +def canonicalize_pass( + *, plan_path: Path, plan: dict[str, Any], pass_id: str, +) -> dict[str, Any]: + manifest_path = Path(plan["candidate_manifest"]) + report_path = Path(plan["candidate_report"]) + control_manifest_path = Path(plan["control_manifest"]["path"]) + control_report_path = Path(plan["control_report"]["path"]) + evidence_root = Path(plan["evidence_root"]) / pass_id + raw_manifest = preserve_file(manifest_path, evidence_root / "raw_cache_manifest.jsonl") + raw_report = preserve_file(report_path, evidence_root / "raw_cache_report.json") + control_rows = load_jsonl(control_manifest_path) + candidate_rows = load_jsonl(manifest_path) + control_report = json.loads(control_report_path.read_text(encoding="utf-8")) + candidate_report = json.loads(report_path.read_text(encoding="utf-8")) + comparison = compare_source_sets(control_rows, candidate_rows) + expected_extra = plan["expected_extra_source_clip_indices"] + if ( + comparison["control_count"] != plan["expected_clips"] + or comparison["candidate_count"] != plan["raw_candidate_clips"] + or comparison["missing_source_clip_indices"] + or comparison["extra_source_clip_indices"] != expected_extra + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC cache mismatch is outside the frozen recovery scope") + _, candidate_by_index = indexed_rows(candidate_rows, "candidate manifest") + extras = source_extra_audit( + source_manifest=Path(plan["source_manifest"]["path"]), + control_report=control_report, + candidate_report=candidate_report, + candidate_by_index=candidate_by_index, + extra_indices=expected_extra, + mano_root=Path(plan["mano_root"]), + ) + quarantined = [ + quarantine_payload(candidate_by_index[index], Path(plan["quarantine_root"]), pass_id) + for index in expected_extra + ] + accepted = canonical_rows(control_rows, candidate_rows) + coverage = payload_audit(accepted) + if coverage["clips_with_translation_supervision"] != plan["expected_clips"]: + raise ValueError("ARCTIC canonical supervision coverage differs") + write_jsonl_atomic(manifest_path, accepted) + manifest_hash = sha256(manifest_path) + canonical_report = dict(candidate_report) + canonical_report.update({ + "status": "complete", + "cached_clips": plan["expected_clips"], + "cached_valid_clips": plan["expected_clips"], + "valid_candidate_files": plan["expected_clips"], + "recordings": comparison["control_group_count"], + "bytes": coverage["bytes"], + "cache_manifest": { + "path": str(manifest_path.resolve()), "sha256": manifest_hash, + }, + "canonical_filter": { + "schema_version": "phase9_arctic_resolution_canonical_filter_v1", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "control_manifest": plan["control_manifest"], + "raw_manifest": raw_manifest, + "raw_report": raw_report, + "excluded_resolution_dependent_source_indices": expected_extra, + "quarantined_payloads": quarantined, + "ordering": "frozen_640_control_source_index_order", + "logical_clip_set_changed_from_control": False, + }, + "supervision_coverage": coverage, + "h2o_official_validation_used": False, + "official_test_used": False, + }) + atomic_json(report_path, canonical_report) + return { + "pass_id": pass_id, + "raw_manifest": raw_manifest, + "raw_report": raw_report, + "comparison": comparison, + "extra_source_audit": extras, + "quarantined_payloads": quarantined, + "canonical_manifest": { + "path": str(manifest_path.resolve()), "sha256": manifest_hash, + "rows": len(accepted), + }, + "canonical_report": { + "path": str(report_path.resolve()), "sha256": sha256(report_path), + }, + "supervision_coverage": coverage, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--audit-only", action="store_true") + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + execution = validate_recovery_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + workers = {item["id"]: item for item in execution["workers"]} + worker = workers["arctic"] + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("ARCTIC recovery state path differs from execution plan") + initial_step, resume_step = worker["steps"][:2] + if args.audit_only: + control_rows = load_jsonl(Path(plan["control_manifest"]["path"])) + candidate_rows = load_jsonl(Path(plan["candidate_manifest"])) + comparison = compare_source_sets(control_rows, candidate_rows) + _, candidate_by_index = indexed_rows(candidate_rows, "candidate manifest") + control_report = json.loads( + Path(plan["control_report"]["path"]).read_text(encoding="utf-8") + ) + candidate_report = json.loads( + Path(plan["candidate_report"]).read_text(encoding="utf-8") + ) + expected_extra = plan["expected_extra_source_clip_indices"] + if ( + comparison["control_count"] != plan["expected_clips"] + or comparison["candidate_count"] != plan["raw_candidate_clips"] + or comparison["missing_source_clip_indices"] + or comparison["extra_source_clip_indices"] != expected_extra + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC preflight mismatch is outside recovery scope") + result = { + "schema_version": "phase9_arctic_resolution_mismatch_audit_v1", + "status": "complete", + "created_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "control_manifest": plan["control_manifest"], + "candidate_manifest": { + "path": str(Path(plan["candidate_manifest"]).resolve()), + "sha256": sha256(plan["candidate_manifest"]), + }, + "candidate_report": { + "path": str(Path(plan["candidate_report"]).resolve()), + "sha256": sha256(plan["candidate_report"]), + }, + "comparison": comparison, + "extra_source_audit": source_extra_audit( + source_manifest=Path(plan["source_manifest"]["path"]), + control_report=control_report, + candidate_report=candidate_report, + candidate_by_index=candidate_by_index, + extra_indices=expected_extra, + mano_root=Path(plan["mano_root"]), + ), + "mutation_performed": False, + "expected_clips_changed": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(Path(plan["preflight_audit_output"]), result) + print(json.dumps(result, indent=2)) + return + lock_path = Path(f"{args.state}.lock") + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state = json.loads(args.state.read_text(encoding="utf-8")) + if ( + state.get("worker") != "arctic" + or state.get("plan_sha256") != plan["execution_plan"]["sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + parser.error("ARCTIC failed state binding differs") + existing = state.get("canonical_set_recovery") + if existing and existing.get("status") == "complete": + if not cache_step_complete(initial_step, False) or not cache_step_complete( + resume_step, True + ): + parser.error("completed ARCTIC recovery outputs differ") + print(json.dumps(state, indent=2)) + return + if state.get("status") != "failed_resumable": + parser.error("ARCTIC recovery requires failed_resumable input state") + result: dict[str, Any] = { + "schema_version": "phase9_arctic_resolution_canonical_recovery_v1", + "status": "running", "started_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "failure_state_sha256": sha256(args.state), + "passes": [], "official_test_used": False, + "h2o_official_validation_used": False, + } + state["canonical_set_recovery"] = result + atomic_json(args.state, state) + initial = canonicalize_pass(plan_path=args.plan, plan=plan, pass_id="initial") + if not cache_step_complete(initial_step, False): + raise ValueError("initial ARCTIC canonical cache validation failed") + result["passes"].append(initial) + if initial_step["id"] not in state["completed_steps"]: + state["completed_steps"].append(initial_step["id"]) + command = list(resume_step["resume_command"]) + log_path = Path(plan["resume_log"]) + attempt = { + "step": resume_step["id"], "kind": "cache", + "recovery": "canonical_set_exact_resume_verify", + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_step"] = resume_step["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + completed = subprocess.run( + command, cwd=Path.cwd(), env=dict(os.environ, PYTHONPATH=str(Path.cwd())), + stdout=log, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = completed.returncode + if completed.returncode: + state["status"] = "failed_resumable" + result["status"] = "failed_resume_command" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(completed.returncode) + resumed = canonicalize_pass( + plan_path=args.plan, plan=plan, pass_id="resume_verify", + ) + result["passes"].append(resumed) + if not cache_step_complete(initial_step, False) or not cache_step_complete( + resume_step, True + ): + raise ValueError("resumed ARCTIC canonical cache validation failed") + if resume_step["id"] not in state["completed_steps"]: + state["completed_steps"].append(resume_step["id"]) + result["status"] = "complete" + result["completed_utc"] = utc_now() + result["canonical_manifest_sha256"] = sha256(plan["candidate_manifest"]) + result["canonical_report_sha256"] = sha256(plan["candidate_report"]) + atomic_json(Path(plan["audit_output"]), result) + result["audit_output"] = { + "path": str(Path(plan["audit_output"]).resolve()), + "sha256": sha256(plan["audit_output"]), + } + state["status"] = "waiting_for_remaining_steps" + state["updated_utc"] = utc_now() + state["failure_evidence_preserved"] = state.get("failure") + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_best_worst_video_cases.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_best_worst_video_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..04f5d1c2379da5af6f1d151193c5df89ce67d78b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_best_worst_video_cases.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +"""Render ranked full-take videos for the frozen Phase 3 candidate.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + MeshLayer, + project_mesh_layers, + render_mesh_layers, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +LEFT_COLOR_RGB = (40, 100, 235) +RIGHT_COLOR_RGB = (235, 55, 55) +MESH_ALPHA = 0.55 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def _mean(rows: list[dict[str, str]], field: str) -> float: + values = np.asarray([float(row[field]) for row in rows], dtype=np.float64) + if not np.isfinite(values).all(): + raise ValueError(f"non-finite {field} in sequence ranking rows") + return float(values.mean()) + + +def rank_video_sequences( + rows: list[dict[str, str]], *, count: int, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Rank validation takes by all annotation-valid hand-frame errors.""" + + grouped: dict[str, list[dict[str, str]]] = defaultdict(list) + for row in rows: + grouped[row["take"]].append(row) + + candidates = [] + for take, take_rows in grouped.items(): + valid_rows = [row for row in take_rows if int(row["annotation_valid"]) == 1] + if not valid_rows: + continue + observed = { + (int(row["frame_id"]), row["side"]) + for row in take_rows + } + if len(observed) != len(take_rows): + raise ValueError(f"duplicate evaluated hand-frame rows in {take}") + errors = np.asarray( + [float(row["absolute_mpjpe_mm"]) for row in valid_rows], + dtype=np.float64, + ) + if not np.isfinite(errors).all(): + raise ValueError(f"non-finite ranking errors in {take}") + first = valid_rows[0] + evaluated_frame_ids = sorted({int(row["frame_id"]) for row in take_rows}) + annotated_frame_ids = sorted({int(row["frame_id"]) for row in valid_rows}) + candidates.append({ + "take": take, + "subject": first["subject"], + "sequence": first["sequence"], + "evaluation_frame_ids": evaluated_frame_ids, + "evaluated_frame_count": len(evaluated_frame_ids), + "annotated_frame_count": len(annotated_frame_ids), + "annotated_hand_frames": len(valid_rows), + "absolute_mpjpe_mm_mean": float(errors.mean()), + "absolute_mpjpe_mm_p50": float(np.median(errors)), + "absolute_mpjpe_mm_max": float(errors.max()), + "root_relative_mpjpe_mm_mean": _mean(valid_rows, "root_relative_mpjpe_mm"), + "direct_2d_error_px_mean": _mean(valid_rows, "direct_2d_error_px"), + "translation_x_mae_mm_mean": _mean(valid_rows, "translation_x_mae_mm"), + "translation_y_mae_mm_mean": _mean(valid_rows, "translation_y_mae_mm"), + "translation_z_mae_mm_mean": _mean(valid_rows, "translation_z_mae_mm"), + }) + if len(candidates) < count * 2: + raise ValueError( + f"need at least {count * 2} validation takes, found {len(candidates)}" + ) + best = sorted( + candidates, + key=lambda row: (row["absolute_mpjpe_mm_mean"], row["take"]), + )[:count] + failure = sorted( + candidates, + key=lambda row: (-row["absolute_mpjpe_mm_mean"], row["take"]), + )[:count] + if {row["take"] for row in best} & {row["take"] for row in failure}: + raise AssertionError("best and failure sequence selections overlap") + return best, failure + + +def source_frame_ids(data_root: Path, take: str) -> list[int]: + frame_ids = sorted( + int(path.stem) for path in (data_root / take / "rgb").glob("*.png") + ) + if not frame_ids: + raise ValueError(f"no raw RGB frames in {data_root / take}") + expected = list(range(frame_ids[0], frame_ids[-1] + 1)) + if frame_ids != expected: + raise ValueError(f"raw RGB frames are not contiguous in {data_root / take}") + return frame_ids + + +def case_directory_name(rank: int, case: dict[str, Any]) -> str: + sequence = str(case["sequence"]).replace("/", "_") + first_frame, last_frame = case["frame_ids"][0], case["frame_ids"][-1] + return ( + f"{rank:02d}_{case['subject']}_{sequence}_" + f"frames_{first_frame:06d}_{last_frame:06d}" + ) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def add_header(image_rgb: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image_rgb.copy() + height = 8 + 22 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (8, 20 + 22 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.55, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def open_writer(path: Path, fps: float, frame_hw: tuple[int, int]) -> cv2.VideoWriter: + height, width = frame_hw + writer = cv2.VideoWriter( + str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height), + ) + if not writer.isOpened(): + raise RuntimeError(f"failed to open video writer: {path}") + return writer + + +def frame_error_lookup( + rows: list[dict[str, str]], take: str, +) -> dict[int, float]: + values: dict[int, list[float]] = defaultdict(list) + for row in rows: + if row["take"] != take or int(row["annotation_valid"]) != 1: + continue + values[int(row["frame_id"])].append(float(row["absolute_mpjpe_mm"])) + return {frame_id: float(np.mean(errors)) for frame_id, errors in values.items()} + + +def render_case( + *, + case: dict[str, Any], + rank: int, + category: str, + output_dir: Path, + dataset: H2OCam4Dataset, + clip_indices: list[int], + metric_rows: list[dict[str, str]], + data_root: Path, + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + faces: tuple[np.ndarray, np.ndarray], + fps: float, + model_t: int, +) -> dict[str, Any]: + output_dir.mkdir(parents=True, exist_ok=False) + take_dir = data_root / str(case["take"]) + raw_K, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + original_path = output_dir / "original_rgb.mp4" + overlay_path = output_dir / "predicted_mano_overlay.mp4" + comparison_path = output_dir / "side_by_side.mp4" + original_writer = open_writer(original_path, fps, source_hw) + overlay_writer = open_writer(overlay_path, fps, source_hw) + comparison_writer = open_writer( + comparison_path, fps, (source_hw[0], source_hw[1] * 2), + ) + errors = frame_error_lookup(metric_rows, str(case["take"])) + expected_frame_ids = list(case["frame_ids"]) + preview = None + rendered_frame_ids: list[int] = [] + try: + for clip_index in clip_indices: + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + clip_frame_ids = [int(value) for value in sample["frame_id"].tolist()] + for time_index, frame_id in enumerate(clip_frame_ids): + raw_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), + cv2.IMREAD_COLOR, + ) + if raw_bgr is None or raw_bgr.shape[:2] != source_hw: + raise RuntimeError( + f"raw RGB decode/shape failure: {take_dir}/{frame_id}" + ) + raw_rgb = cv2.cvtColor(raw_bgr, cv2.COLOR_BGR2RGB) + layers = [ + MeshLayer( + prediction["vertices_camera"][0, time_index, hand] + .float().cpu().numpy(), + faces[hand], + LEFT_COLOR_RGB if hand == 0 else RIGHT_COLOR_RGB, + MESH_ALPHA, + ) + for hand in range(2) + ] + rendered = render_mesh_layers( + raw_rgb, project_mesh_layers(layers, raw_K), + ) + frame_error = errors.get(frame_id) + error_label = ( + f"{frame_error:.2f} mm" + if frame_error is not None else "n/a (not evaluated)" + ) + global_index = len(rendered_frame_ids) + rendered = add_header(rendered, ( + f"{category} #{rank} | predicted MANO | left=BLUE right=RED alpha={MESH_ALPHA:.2f}", + f"{case['subject']}/{case['sequence']} | frame={frame_id} ({global_index + 1}/{len(expected_frame_ids)}) | take MPJPE={case['absolute_mpjpe_mm_mean']:.2f} mm | frame={error_label}", + )) + original_panel = add_header(raw_rgb, ("Original cam4 RGB",)) + comparison = np.concatenate((original_panel, rendered), axis=1) + + original_writer.write(raw_bgr) + overlay_writer.write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + comparison_writer.write(cv2.cvtColor(comparison, cv2.COLOR_RGB2BGR)) + rendered_frame_ids.append(frame_id) + if global_index == len(expected_frame_ids) // 2: + preview = comparison + del prediction, batch + finally: + original_writer.release() + overlay_writer.release() + comparison_writer.release() + + if rendered_frame_ids != expected_frame_ids: + raise RuntimeError( + f"rendered frame sequence mismatch for {case['take']}: " + f"{len(rendered_frame_ids)} != {len(expected_frame_ids)}" + ) + if preview is None: + raise RuntimeError(f"no preview generated for {case['take']}") + preview_path = output_dir / "preview.png" + cv2.imwrite(str(preview_path), cv2.cvtColor(preview, cv2.COLOR_RGB2BGR)) + record = { + **case, + "rank": rank, + "category": category, + "selection_requirement": "official-validation take with finite annotation-valid metrics", + "ranking_metric": "mean absolute MPJPE over all annotation-valid hand-frames in the take", + "inference_policy": f"contiguous full raw take, non-overlapping T={model_t} chunks with final partial chunk", + "colors_rgb": { + "left": list(LEFT_COLOR_RGB), "right": list(RIGHT_COLOR_RGB), + }, + "mesh_alpha": MESH_ALPHA, + "visualization_fps": fps, + "duration_seconds": len(expected_frame_ids) / fps, + "videos": { + "original": str(original_path.resolve()), + "predicted_mano_overlay": str(overlay_path.resolve()), + "side_by_side": str(comparison_path.resolve()), + }, + "preview": str(preview_path.resolve()), + } + (output_dir / "case.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + record["preview_rgb"] = preview + return record + + +def save_contact_sheet(output: Path, records: list[dict[str, Any]]) -> None: + panels = [] + for record in records: + preview = record["preview_rgb"] + panel = cv2.resize(preview, (384, 216), interpolation=cv2.INTER_AREA) + panel = add_header(panel, ( + f"{record['category']} #{record['rank']} | {record['absolute_mpjpe_mm_mean']:.2f} mm | {len(record['frame_ids'])} frames", + )) + panels.append(panel) + rows = [np.concatenate(panels[:5], axis=1), np.concatenate(panels[5:], axis=1)] + sheet = np.concatenate(rows, axis=0) + cv2.imwrite(str(output), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR)) + + +def save_case_summary(output: Path, records: list[dict[str, Any]]) -> None: + lines = [ + "# Ranked Long-Sequence Video Summary", + "", + "Takes are ranked by mean camera-space absolute MPJPE over every", + "annotation-valid official-validation hand-frame. Videos render each full raw", + "take continuously; frames outside the evaluated annotation runs do not affect", + "the ranking. All metric values below use only valid evaluation rows.", + "", + ] + for category, title in (("best", "Best Sequences"), ("failure", "Worst Sequences")): + lines.extend([ + f"## {title}", + "", + "| Rank | Take | Raw frames | Seconds | Evaluated frames | Abs MPJPE | Root-relative | Direct 2D | z MAE |", + "|---:|---|---:|---:|---:|---:|---:|---:|---:|", + ]) + for record in records: + if record["category"] != category: + continue + lines.append( + f"| {record['rank']} | `{record['take']}` | {len(record['frame_ids'])} | " + f"{record['duration_seconds']:.2f} | {record['evaluated_frame_count']} | " + f"{record['absolute_mpjpe_mm_mean']:.2f} mm | " + f"{record['root_relative_mpjpe_mm_mean']:.2f} mm | " + f"{record['direct_2d_error_px_mean']:.2f} px | " + f"{record['translation_z_mae_mm_mean']:.2f} mm |" + ) + lines.append("") + lines.extend([ + "Left MANO is blue, right MANO is red, and mesh alpha is 0.55. The", + "prediction-only overlay uses raw 1280x720 cam4 RGB and the original camera", + "intrinsics. GT meshes are not rendered. Official test was not used.", + "", + ]) + output.write_text("\n".join(lines), encoding="utf-8") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--evaluation-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--count", type=int, default=5) + parser.add_argument("--fps", type=float, default=30.0) + args = parser.parse_args() + if args.count != 5: + raise ValueError("the showcase requires exactly five best and five failure cases") + if args.fps <= 0: + raise ValueError("fps must be positive") + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError(f"refusing to overwrite non-empty output: {args.output_dir}") + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + metric_path = args.evaluation_dir / "per_hand_frame_metrics.csv" + report_path = args.evaluation_dir / "evaluation.json" + metric_rows = read_csv(metric_path) + report = json.loads(report_path.read_text(encoding="utf-8")) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + if ( + report.get("split_role") != "official_validation" + or report.get("official_test_used") is not False + or report.get("checkpoint", {}).get("sha256") != checkpoint_hash + or report.get("manifest", {}).get("sha256") != manifest_hash + ): + raise ValueError("evaluation/checkpoint/manifest provenance mismatch") + + best, failure = rank_video_sequences(metric_rows, count=args.count) + selected = best + failure + for case in selected: + case["frame_ids"] = source_frame_ids(args.data_root, str(case["take"])) + case["raw_frame_count"] = len(case["frame_ids"]) + + render_manifest_path = args.output_dir / "render_input_manifest.jsonl" + render_manifest_path.write_text( + "".join( + json.dumps({"take": case["take"], "frame_ids": case["frame_ids"]}) + "\n" + for case in selected + ), + encoding="utf-8", + ) + model_t = int(data_config["T"]) + dataset = H2OCam4Dataset( + args.data_root, render_manifest_path, tuple(data_config["resolution_hw"]), + (model_t,), (int(data_config["stride"]),), + ) + clip_indices_by_take: dict[str, list[int]] = defaultdict(list) + for clip_index, clip in enumerate(dataset.clips): + clip_indices_by_take[clip.take].append(clip_index) + + device = torch.device(f"cuda:{args.gpu}") + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint( + args.checkpoint, model, optimizer=None, map_location=device, + ) + if int(checkpoint_state["step"]) != int(report["checkpoint"]["step"]): + raise ValueError("checkpoint step differs from source evaluation") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + faces = tuple(layer.th_faces.cpu().numpy() for layer in model.mano_layer.layers) + + rendered_records = [] + for category, cases, parent_name in ( + ("best", best, "best_cases"), + ("failure", failure, "failure_cases"), + ): + parent = args.output_dir / parent_name + parent.mkdir(exist_ok=False) + for rank, case in enumerate(cases, start=1): + print( + f"rendering {category} #{rank}: {case['take']} " + f"({len(case['frame_ids'])} frames)", + flush=True, + ) + record = render_case( + case=case, rank=rank, category=category, + output_dir=parent / case_directory_name(rank, case), + dataset=dataset, + clip_indices=clip_indices_by_take[str(case["take"])], + metric_rows=metric_rows, data_root=args.data_root.resolve(), + model=model, device=device, dtype=dtype, faces=faces, + fps=args.fps, model_t=model_t, + ) + rendered_records.append(record) + + save_contact_sheet(args.output_dir / "contact_sheet.png", rendered_records) + save_case_summary(args.output_dir / "CASE_SUMMARY.md", rendered_records) + serializable_records = [ + {key: value for key, value in record.items() if key != "preview_rgb"} + for record in rendered_records + ] + manifest = { + "status": "complete", + "official_test_used": False, + "source_split": "official_validation", + "selection_policy": ( + "lowest/highest take mean absolute MPJPE over all annotation-valid " + "official-validation hand-frames" + ), + "render_policy": ( + "all contiguous raw frames in each selected take, including frames " + "outside evaluated annotation runs" + ), + "config": str(args.config.resolve()), + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": checkpoint_hash, + "step": int(checkpoint_state["step"]), + }, + "source_manifest": { + "path": str(args.manifest.resolve()), + "sha256": manifest_hash, + }, + "source_evaluation": str(args.evaluation_dir.resolve()), + "render_input_manifest": str(render_manifest_path.resolve()), + "model_input_resolution_hw": list(data_config["resolution_hw"]), + "model_temporal_window": model_t, + "render_space": "raw cam4 RGB resolution with original camera intrinsics", + "videos_are_prediction_only": True, + "visualization_fps": args.fps, + "cases": serializable_records, + } + (args.output_dir / "selection_manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8", + ) + readme = f"""# Best Model Long-Sequence Video Cases + +This directory uses the Phase 3 seed-20260718 step-140k tail-best checkpoint. +The five best and five worst cases are distinct official-validation takes, +ranked by mean camera-space absolute MPJPE across all annotation-valid +hand-frames in each take. + +Each case contains: + +- `original_rgb.mp4`: untouched full raw cam4 RGB sequence; +- `predicted_mano_overlay.mp4`: prediction-only MANO, left blue and right red; +- `side_by_side.mp4`: original and overlay comparison; +- `preview.png` and `case.json`. + +All raw frames from the selected take are rendered continuously, including +frames outside the evaluated annotation runs. Those frames display `n/a` for +the frame metric and do not affect ranking. Inference uses non-overlapping +T={model_t} chunks, matching the formal evaluator, with a final partial chunk. + +Playback is {args.fps:g} fps, matching the H2O capture rate. Mesh alpha is +0.55. Camera-space vertices are projected onto raw 1280x720 RGB with original +cam4 intrinsics. GT meshes are not rendered. Official test was not used. + +See `CASE_SUMMARY.md` for the ranking and metric breakdown, `contact_sheet.png` +for the visual index, and `selection_manifest.json` for full provenance. +""" + (args.output_dir / "README.md").write_text(readme, encoding="utf-8") + print(json.dumps({ + "status": "complete", + "output_dir": str(args.output_dir.resolve()), + "fps": args.fps, + "best_take_mpjpe_mm": [row["absolute_mpjpe_mm_mean"] for row in best], + "failure_take_mpjpe_mm": [ + row["absolute_mpjpe_mm_mean"] for row in failure + ], + "frame_counts": [len(row["frame_ids"]) for row in selected], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_phase4_filtered_cases.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_phase4_filtered_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea9f5f1022a50e8c55ff0fe3b30b1d019fb4375 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_phase4_filtered_cases.py @@ -0,0 +1,517 @@ +#!/usr/bin/env python3 +"""Render deterministic raw/filtered failure videos from audited jitter caches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + OPENPOSE_HAND_EDGES, + draw_skeleton, + project_camera_points, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models.mano import ManoCameraLayer +try: + from scripts.evaluate_phase4_jitter import ( + condition_grid, + filtered_parameters, + load_take, + rebuild_geometry, + ) +except ModuleNotFoundError: + from evaluate_phase4_jitter import ( # type: ignore[no-redef] + condition_grid, + filtered_parameters, + load_take, + rebuild_geometry, + ) + + +RAW_COLOR = (245, 145, 45) +FILTERED_COLOR = (35, 210, 235) +GT_COLOR = (70, 220, 105) +AXIS_COLORS = ((235, 80, 80), (70, 190, 90), (80, 130, 240)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +class FFmpegWriter: + def __init__(self, path: Path, fps: float, frame_hw: tuple[int, int]) -> None: + self.path = path + self.frame_hw = frame_hw + self.frames = 0 + path.parent.mkdir(parents=True, exist_ok=True) + self.temporary = path.with_name(f".{path.stem}.tmp-{os.getpid()}.mp4") + height, width = frame_hw + self.process = subprocess.Popen([ + "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-y", + "-f", "rawvideo", "-pix_fmt", "bgr24", "-s:v", f"{width}x{height}", + "-r", f"{fps:g}", "-i", "pipe:0", "-an", "-c:v", "libx264", + "-preset", "fast", "-crf", "18", "-pix_fmt", "yuv420p", + "-movflags", "+faststart", str(self.temporary), + ], stdin=subprocess.PIPE, stderr=subprocess.PIPE) + + def write(self, frame_bgr: np.ndarray) -> None: + if frame_bgr.shape != (*self.frame_hw, 3) or frame_bgr.dtype != np.uint8: + raise ValueError("video frame shape/dtype mismatch") + if self.process.stdin is None: + raise RuntimeError("ffmpeg stdin unavailable") + self.process.stdin.write(np.ascontiguousarray(frame_bgr).tobytes()) + self.frames += 1 + + def close(self) -> None: + assert self.process.stdin is not None + self.process.stdin.close() + stderr = self.process.stderr.read().decode("utf-8", errors="replace") if self.process.stderr else "" + return_code = self.process.wait() + if return_code: + self.temporary.unlink(missing_ok=True) + raise RuntimeError(f"ffmpeg failed: {stderr.strip()}") + os.replace(self.temporary, self.path) + + def abort(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + if self.process.poll() is None: + self.process.terminate() + self.process.wait(timeout=10) + self.temporary.unlink(missing_ok=True) + + +def add_header(image: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image.copy() + height = 8 + 24 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (9, 21 + 24 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.58, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def ranked_failure_takes( + cache_manifest: dict[str, Any], count: int, +) -> list[dict[str, object]]: + records = [] + for record in cache_manifest["takes"]: + arrays = load_take(Path(record["path"])) + error = np.linalg.norm( + arrays["pred_joints_camera"] - arrays["target_joints_camera"], axis=-1, + ) * 1000.0 + valid = arrays["joint_element_valid"].astype(bool) + values = error[valid] + if not len(values) or not np.isfinite(values).all(): + continue + records.append({ + "take": str(arrays["take"]), "path": record["path"], + "frames": len(arrays["frame_id"]), + "raw_absolute_mpjpe_mm": float(values.mean()), + }) + if len(records) < count: + raise ValueError("not enough annotated takes for filtered video cases") + return sorted( + records, key=lambda row: (-float(row["raw_absolute_mpjpe_mm"]), str(row["take"])), + )[:count] + + +def project_joints(joints: np.ndarray, K: np.ndarray) -> np.ndarray: + pixels, z = project_camera_points(joints, K) + pixels[z <= 1e-8] = np.nan + return pixels + + +def overlay_joints( + image_rgb: np.ndarray, + joints: np.ndarray, + K: np.ndarray, + color: tuple[int, int, int], + valid_hands: np.ndarray | None = None, +) -> np.ndarray: + output = image_rgb + for hand in range(2): + if valid_hands is not None and not bool(valid_hands[hand]): + continue + output = draw_skeleton( + output, project_joints(joints[hand], K), color, + marker="ring" if color == GT_COLOR else "circle", + ) + return output + + +def side_limits(*joint_sequences: np.ndarray) -> tuple[float, float, float, float]: + points = np.concatenate([values.reshape(-1, 3) for values in joint_sequences]) + finite = points[np.isfinite(points).all(axis=-1)] + if not len(finite): + return -0.4, 0.4, 0.2, 0.9 + x0, x1 = np.percentile(finite[:, 0], (1, 99)) + z0, z1 = np.percentile(finite[:, 2], (1, 99)) + x_margin = max(0.03, 0.1 * (x1 - x0)) + z_margin = max(0.03, 0.1 * (z1 - z0)) + return x0 - x_margin, x1 + x_margin, z0 - z_margin, z1 + z_margin + + +def camera_side_panel( + raw_joints: np.ndarray, + filtered_joints: np.ndarray, + target_joints: np.ndarray, + valid_hands: np.ndarray, + limits: tuple[float, float, float, float], + frame_id: int, + size: tuple[int, int] = (540, 960), +) -> np.ndarray: + height, width = size + panel = np.full((height, width, 3), 248, dtype=np.uint8) + x0, x1, z0, z1 = limits + + def point(value: np.ndarray) -> tuple[int, int]: + x = int(round(50 + (value[0] - x0) / max(x1 - x0, 1e-6) * (width - 100))) + y = int(round(height - 45 - (value[2] - z0) / max(z1 - z0, 1e-6) * (height - 100))) + return x, y + + cv2.rectangle(panel, (50, 45), (width - 50, height - 45), (50, 50, 50), 1) + for joints, color, valid_only in ( + (target_joints, GT_COLOR, True), + (raw_joints, RAW_COLOR, False), + (filtered_joints, FILTERED_COLOR, False), + ): + for hand in range(2): + if valid_only and not valid_hands[hand]: + continue + finite = np.isfinite(joints[hand]).all(axis=-1) + for start, end in OPENPOSE_HAND_EDGES: + if finite[start] and finite[end]: + cv2.line(panel, point(joints[hand, start]), point(joints[hand, end]), color, 2, cv2.LINE_AA) + for joint_index in np.flatnonzero(finite): + cv2.circle(panel, point(joints[hand, joint_index]), 2, color, -1, cv2.LINE_AA) + panel = add_header(panel, ( + f"Camera side view x/z | frame={frame_id}", + "GT=green raw=orange filtered=cyan", + )) + return panel + + +def trace_panel( + raw_error: np.ndarray, + filtered_error: np.ndarray, + valid: np.ndarray, + current: int, + side: str, + size: tuple[int, int] = (540, 1920), +) -> np.ndarray: + height, width = size + panel = np.full((height, width, 3), 250, dtype=np.uint8) + finite_values = np.concatenate((raw_error[valid], filtered_error[valid])) + limit = max(10.0, float(np.percentile(np.abs(finite_values), 99))) if finite_values.size else 10.0 + left, right = 70, width - 35 + band_height = (height - 70) // 3 + for axis, axis_name in enumerate("xyz"): + top = 48 + axis * band_height + bottom = top + band_height - 12 + middle = (top + bottom) // 2 + cv2.line(panel, (left, middle), (right, middle), (150, 150, 150), 1) + cv2.putText(panel, f"{axis_name} +/-{limit:.0f}mm", (8, top + 18), cv2.FONT_HERSHEY_SIMPLEX, 0.48, AXIS_COLORS[axis], 1, cv2.LINE_AA) + + def points(values: np.ndarray) -> list[np.ndarray]: + output = [] + segment = [] + for index, value in enumerate(values[:, axis]): + if valid[index] and np.isfinite(value): + x = int(round(left + index / max(len(values) - 1, 1) * (right - left))) + y = int(round(middle - np.clip(value / limit, -1, 1) * (bottom - top) / 2)) + segment.append((x, y)) + elif segment: + output.append(np.asarray(segment, dtype=np.int32)) + segment = [] + if segment: + output.append(np.asarray(segment, dtype=np.int32)) + return output + + for segment in points(raw_error): + if len(segment) >= 2: + cv2.polylines(panel, [segment], False, (115, 115, 115), 1, cv2.LINE_AA) + for segment in points(filtered_error): + if len(segment) >= 2: + cv2.polylines(panel, [segment], False, AXIS_COLORS[axis], 2, cv2.LINE_AA) + current_x = int(round(left + current / max(len(raw_error) - 1, 1) * (right - left))) + cv2.line(panel, (current_x, 42), (current_x, height - 20), (20, 20, 20), 1) + return add_header(panel, ( + f"Signed wrist xyz error | {side} hand | raw=gray filtered=color", + )) + + +def worst_side(arrays: dict[str, np.ndarray]) -> int: + valid = arrays["joint_annotation_valid"].astype(bool) + signed_z = ( + arrays["pred_wrist_translation"] - arrays["target_wrist_translation"] + )[..., 2] * 1000.0 + means = [ + float(np.mean(np.abs(signed_z[:, hand][valid[:, hand]]))) + if valid[:, hand].any() else -1.0 + for hand in range(2) + ] + return int(np.argmax(means)) + + +def render_case( + *, + arrays: dict[str, np.ndarray], + condition_name: str, + filtered_translation: np.ndarray, + filtered_joints: np.ndarray, + data_root: Path, + output_dir: Path, +) -> dict[str, object]: + take = str(arrays["take"]) + take_dir = data_root / take + raw_K, source_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + output_dir.mkdir(parents=True, exist_ok=False) + paths = { + "raw_vs_filtered_30fps": output_dir / "raw_vs_filtered_30fps.mp4", + "raw_vs_filtered_4fps": output_dir / "raw_vs_filtered_4fps.mp4", + "failure_diagnostic_30fps": output_dir / "failure_diagnostic_30fps.mp4", + } + writers = { + "raw_vs_filtered_30fps": FFmpegWriter( + paths["raw_vs_filtered_30fps"], 30.0, (source_hw[0], source_hw[1] * 2), + ), + "raw_vs_filtered_4fps": FFmpegWriter( + paths["raw_vs_filtered_4fps"], 4.0, (source_hw[0], source_hw[1] * 2), + ), + "failure_diagnostic_30fps": FFmpegWriter( + paths["failure_diagnostic_30fps"], 30.0, (1080, 1920), + ), + } + side = worst_side(arrays) + side_name = "left" if side == 0 else "right" + valid_side = arrays["joint_annotation_valid"][:, side].astype(bool) + raw_error = ( + arrays["pred_wrist_translation"][:, side] + - arrays["target_wrist_translation"][:, side] + ) * 1000.0 + filtered_error = ( + filtered_translation[:, side] - arrays["target_wrist_translation"][:, side] + ) * 1000.0 + limits = side_limits( + arrays["pred_joints_camera"], filtered_joints, + arrays["target_joints_camera"], + ) + frame_hashes: dict[str, list[str]] = {key: [] for key in writers} + try: + for index, frame_id in enumerate(arrays["frame_id"].astype(int)): + image_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), cv2.IMREAD_COLOR, + ) + if image_bgr is None or image_bgr.shape[:2] != source_hw: + raise RuntimeError(f"raw RGB failure for {take}/{frame_id}") + image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) + raw_panel = overlay_joints( + image_rgb, arrays["pred_joints_camera"][index], raw_K, RAW_COLOR, + ) + raw_panel = add_header(raw_panel, ( + f"RAW model | {take} | frame={frame_id}", + "MANO joints=orange | 30 fps physical time", + )) + filtered_panel = overlay_joints( + image_rgb, filtered_joints[index], raw_K, FILTERED_COLOR, + ) + filtered_panel = add_header(filtered_panel, ( + f"FILTERED {condition_name} | {take} | frame={frame_id}", + "MANO joints=cyan | inference-only secondary", + )) + comparison_rgb = np.concatenate((raw_panel, filtered_panel), axis=1) + comparison_bgr = cv2.cvtColor(comparison_rgb, cv2.COLOR_RGB2BGR) + for key in ("raw_vs_filtered_30fps", "raw_vs_filtered_4fps"): + writers[key].write(comparison_bgr) + frame_hashes[key].append(hashlib.sha256(comparison_bgr.tobytes()).hexdigest()) + + diagnostic_overlay = overlay_joints( + image_rgb, arrays["target_joints_camera"][index], raw_K, + GT_COLOR, arrays["joint_annotation_valid"][index], + ) + diagnostic_overlay = overlay_joints( + diagnostic_overlay, arrays["pred_joints_camera"][index], raw_K, + RAW_COLOR, + ) + diagnostic_overlay = overlay_joints( + diagnostic_overlay, filtered_joints[index], raw_K, FILTERED_COLOR, + ) + diagnostic_overlay = add_header(diagnostic_overlay, ( + f"GT/raw/filtered overlay | {take} | frame={frame_id}", + "GT=green raw=orange filtered=cyan", + )) + top_left = cv2.resize(diagnostic_overlay, (960, 540), interpolation=cv2.INTER_AREA) + top_right = camera_side_panel( + arrays["pred_joints_camera"][index], filtered_joints[index], + arrays["target_joints_camera"][index], + arrays["joint_annotation_valid"][index], limits, frame_id, + ) + trace = trace_panel( + raw_error, filtered_error, valid_side, index, side_name, + ) + diagnostic_rgb = np.concatenate(( + np.concatenate((top_left, top_right), axis=1), trace, + ), axis=0) + diagnostic_bgr = cv2.cvtColor(diagnostic_rgb, cv2.COLOR_RGB2BGR) + writers["failure_diagnostic_30fps"].write(diagnostic_bgr) + frame_hashes["failure_diagnostic_30fps"].append( + hashlib.sha256(diagnostic_bgr.tobytes()).hexdigest() + ) + except Exception: + for writer in writers.values(): + writer.abort() + raise + for writer in writers.values(): + writer.close() + videos = { + key: { + "path": str(path.resolve()), "sha256": sha256(path), + "frames": writers[key].frames, + "fps": 4.0 if key.endswith("4fps") else 30.0, + "frame_pixel_sha256": frame_hashes[key], + } + for key, path in paths.items() + } + record = { + "take": take, "condition": condition_name, + "frames": len(arrays["frame_id"]), "trace_side": side_name, + "official_test_used": False, "videos": videos, + } + (output_dir / "case.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + return record + + +def assert_deterministic( + records: list[dict[str, object]], reference_manifest: Path, +) -> None: + reference = json.loads(reference_manifest.read_text(encoding="utf-8")) + reference_index = { + (record["take"], record["condition"]): record for record in reference["cases"] + } + observed_keys = {(record["take"], record["condition"]) for record in records} + if observed_keys != set(reference_index): + raise ValueError("visualization audit case grid mismatch") + for record in records: + other = reference_index.get((record["take"], record["condition"])) + if other is None: + raise ValueError("visualization audit case grid mismatch") + for video_name, video in record["videos"].items(): + if video["frame_pixel_sha256"] != other["videos"][video_name]["frame_pixel_sha256"]: + raise ValueError(f"visualization pixels are non-deterministic: {video_name}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--selection-json", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--case-count", type=int, default=3) + parser.add_argument("--audit-against", type=Path) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("filtered video output must be new or empty") + cache_manifest = json.loads( + (args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8") + ) + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + if ( + cache_manifest.get("status") != "complete" + or cache_manifest.get("official_test_used") is not False + or cache_manifest.get("scope") != "full" + or cache_manifest.get("clips") != 1495 + or cache_manifest.get("frames") != 11638 + or selection.get("status") != "selected" + or selection.get("official_test_used") is not False + or selection.get("selection_scope") + != "frozen_official_validation_subset_256" + or selection.get("checkpoint", {}).get("sha256") + != cache_manifest.get("checkpoint", {}).get("sha256") + ): + raise ValueError("filtered video cache/selection provenance mismatch") + selected_conditions = [ + value for family, value in sorted(selection["selected_conditions"].items()) + if value is not None + ] + if not selected_conditions: + raise ValueError("no eligible filter condition was selected") + grid = condition_grid() + cases = ranked_failure_takes(cache_manifest, args.case_count) + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + records = [] + for condition_name in selected_conditions: + condition = grid[condition_name] + for rank, case in enumerate(cases, start=1): + arrays = load_take(Path(case["path"])) + filtered_translation, filtered_rotations, _ = filtered_parameters( + arrays, condition, + ) + _, filtered_joints = rebuild_geometry( + filtered_rotations, arrays["pred_shape"].astype(np.float32), + filtered_translation, mano, device, + ) + record = render_case( + arrays=arrays, condition_name=condition_name, + filtered_translation=filtered_translation, + filtered_joints=filtered_joints, + data_root=args.data_root, + output_dir=( + args.output_dir / condition_name + / f"{rank:02d}_{str(case['take']).replace('/', '__')}" + ), + ) + record["rank"] = rank + record["raw_absolute_mpjpe_mm"] = case["raw_absolute_mpjpe_mm"] + records.append(record) + if args.audit_against is not None: + assert_deterministic(records, args.audit_against) + manifest = { + "status": "complete", + "official_test_used": False, + "result_role": "filtered_inference_secondary_results", + "cache_checkpoint": cache_manifest["checkpoint"], + "selection_json": str(args.selection_json.resolve()), + "conditions": selected_conditions, + "case_selection": "highest raw take-level absolute MPJPE", + "deterministic_against": ( + str(args.audit_against.resolve()) if args.audit_against else None + ), + "deterministic_pixel_audit_passed": args.audit_against is not None, + "cases": records, + } + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "video_manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "conditions": selected_conditions, + "cases": len(records), "deterministic_audit": args.audit_against is not None, + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_phase5_alignment_failure_cases.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_phase5_alignment_failure_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..051fe5d245d148f74274f9d9d3dc2463f44468db --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_phase5_alignment_failure_cases.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +"""Render deterministic predicted-MANO/depth alignment failure diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import matplotlib +import numpy as np + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def select_cases( + rows: list[dict[str, str]], refined_condition: str, +) -> list[dict[str, Any]]: + keyed: dict[tuple[str, int, str], dict[str, dict[str, str]]] = {} + for row in rows: + if row["condition"] not in ("coarse", refined_condition): + continue + key = (row["take"], int(row["frame_id"]), row["side"]) + keyed.setdefault(key, {})[row["condition"]] = row + pairs = [ + (key, values["coarse"], values[refined_condition]) + for key, values in keyed.items() + if set(values) == {"coarse", refined_condition} + ] + if not pairs: + raise ValueError("no matched coarse/refined frame rows") + + def z(row: dict[str, str]) -> float: + return float(row["translation_z_mae_mm"]) + + role_candidates = { + "right_far_small_tail": sorted( + ( + item for item in pairs + if item[0][2] == "right" and ( + item[1]["depth_bucket"] == "far" + or item[1]["hand_size_bucket"] == "small" + ) + ), + key=lambda item: (-z(item[1]), item[0]), + ), + "largest_z_gain": sorted( + pairs, key=lambda item: (-(z(item[1]) - z(item[2])), item[0]), + ), + "largest_z_harm": sorted( + pairs, key=lambda item: (-(z(item[2]) - z(item[1])), item[0]), + ), + } + selected = [] + used: set[tuple[str, int, str]] = set() + for role, candidates in role_candidates.items(): + choice = next((item for item in candidates if item[0] not in used), None) + if choice is None: + raise ValueError(f"cannot select a unique case for {role}") + key, coarse, refined = choice + used.add(key) + selected.append({ + "role": role, + "take": key[0], + "frame_id": key[1], + "side": key[2], + "coarse_z_mae_mm": z(coarse), + "refined_z_mae_mm": z(refined), + "z_mae_delta_mm": z(refined) - z(coarse), + "coarse_absolute_mpjpe_mm": float(coarse["absolute_mpjpe_mm"]), + "refined_absolute_mpjpe_mm": float(refined["absolute_mpjpe_mm"]), + "applied_delta_z_mm": float(refined["applied_delta_z_mm"]), + "alignment_confidence": float(refined["alignment_confidence"]), + "alignment_support": int(refined["alignment_support"]), + "alignment_quality": float(refined["alignment_quality"]), + "depth_bucket": coarse["depth_bucket"], + "hand_size_bucket": coarse["hand_size_bucket"], + }) + return selected + + +def inlier_masks( + observed_depth_m: np.ndarray, + predicted_depth_m: np.ndarray, + sample_valid: np.ndarray, + delta_z_m: float, + residual_scale_m: float, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + residual = observed_depth_m - predicted_depth_m + eligible = sample_valid & np.isfinite(residual) & (np.abs(residual) <= 0.15) + scale = max(float(residual_scale_m), 0.003) + inlier = eligible & (np.abs(residual - float(delta_z_m)) <= 1.345 * scale) + return eligible, inlier, eligible & ~inlier + + +def crop_bounds( + points_px: np.ndarray, image_hw: tuple[int, int], minimum_size: int = 240, +) -> tuple[int, int, int, int]: + height, width = image_hw + points = np.asarray(points_px, dtype=np.float64).reshape(-1, 2) + points = points[np.isfinite(points).all(axis=1)] + if not len(points): + return 0, 0, width, height + low, high = points.min(axis=0), points.max(axis=0) + center = (low + high) / 2.0 + size = max(float(np.max(high - low) + 120.0), float(minimum_size)) + size = min(size, float(width), float(height)) + x0 = int(np.clip(round(center[0] - size / 2), 0, width - size)) + y0 = int(np.clip(round(center[1] - size / 2), 0, height - size)) + return x0, y0, int(x0 + size), int(y0 + size) + + +def draw_points( + axis: plt.Axes, points: np.ndarray, color: str, label: str, + *, marker: str = "o", size: float = 10.0, alpha: float = 0.9, +) -> None: + values = np.asarray(points) + finite = np.isfinite(values).all(axis=-1) + axis.scatter( + values[finite, 0], values[finite, 1], s=size, c=color, + marker=marker, alpha=alpha, label=label, linewidths=0.4, + ) + + +def render_case( + case: dict[str, Any], + *, + cache_arrays: dict[str, np.ndarray], + alignment_arrays: dict[str, np.ndarray], + data_root: Path, + output: Path, +) -> dict[str, Any]: + frame_ids = cache_arrays["frame_id"].astype(np.int64) + matches = np.where(frame_ids == int(case["frame_id"]))[0] + if len(matches) != 1: + raise ValueError(f"frame is not unique in raw cache: {case}") + index = int(matches[0]) + hand = 1 if case["side"] == "right" else 0 + take_dir = data_root / case["take"] + frame_name = f"{int(case['frame_id']):06d}.png" + rgb_bgr = cv2.imread(str(take_dir / "rgb" / frame_name), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(take_dir / "depth" / frame_name), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise FileNotFoundError(f"missing RGB/depth for {case['take']}/{frame_name}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + if tuple(rgb.shape[:2]) != raw_hw or tuple(depth_mm.shape) != raw_hw: + raise ValueError("raw RGB/depth/intrinsics dimensions disagree") + depth_m, depth_valid = depth_mm_to_m(depth_mm) + coarse_vertices = cache_arrays["pred_vertices_camera"][index, hand] + diagnostics, surface = align_wrist_z(coarse_vertices, K_raw, depth_m, depth_valid) + if surface is None: + raise AssertionError("complete-modality case has no surface samples") + stored_delta = float(alignment_arrays["raw_alignment_delta_z_m"][index, hand]) + if abs(diagnostics.delta_z_m - stored_delta) > 1e-8: + raise ValueError("rerender alignment delta differs from evaluated prediction") + correction = float(alignment_arrays["calibrated_delta_z_m"][index, hand]) + eligible, inlier, outlier = inlier_masks( + surface.observed_depth_m, surface.predicted_depth_m, + surface.sample_valid, diagnostics.delta_z_m, diagnostics.residual_scale_m, + ) + + coarse_joints = cache_arrays["pred_joints_camera"][index, hand].astype(np.float64) + target_joints = cache_arrays["target_joints_camera"][index, hand].astype(np.float64) + refined_joints = coarse_joints.copy() + refined_joints[:, 2] += correction + coarse_px, _ = project_points(coarse_joints, K_raw) + refined_px, _ = project_points(refined_joints, K_raw) + target_px, _ = project_points(target_joints, K_raw) + bounds = crop_bounds( + np.concatenate((coarse_px, target_px, surface.projected_vertices_px[surface.visible_vertex])), + raw_hw, + ) + x0, y0, x1, y1 = bounds + offset = np.asarray((x0, y0)) + + figure, axes = plt.subplots(2, 3, figsize=(16, 9), dpi=120) + rgb_axis = axes[0, 0] + rgb_axis.imshow(rgb[y0:y1, x0:x1]) + draw_points(rgb_axis, target_px - offset, "#2ca02c", "GT", marker="x", size=24) + draw_points(rgb_axis, coarse_px - offset, "#d6278b", "coarse", size=16) + draw_points(rgb_axis, refined_px - offset, "#00a6d6", "refined", marker="+", size=24) + rgb_axis.set_title(f"RGB projection | {case['side']}") + rgb_axis.legend(loc="upper right", fontsize=8) + rgb_axis.axis("off") + + depth_axis = axes[0, 1] + depth_display = np.where(depth_valid, depth_m, np.nan) + depth_axis.imshow(depth_display[y0:y1, x0:x1], cmap="turbo", vmin=0.25, vmax=1.25) + projected = surface.projected_vertices_px - offset + draw_points(depth_axis, projected[inlier], "#39d353", "IRLS inlier", size=13) + draw_points(depth_axis, projected[outlier], "#ff4d4f", "eligible outlier", marker="x", size=17) + invalid_visible = surface.visible_vertex & ~eligible + draw_points(depth_axis, projected[invalid_visible], "#dddddd", "invalid", size=5, alpha=0.45) + depth_axis.set_title("Observed metric depth + surface samples") + depth_axis.legend(loc="upper right", fontsize=7) + depth_axis.axis("off") + + scatter_axis = axes[0, 2] + predicted = surface.predicted_depth_m[eligible] + observed = surface.observed_depth_m[eligible] + scatter_axis.scatter(predicted[inlier[eligible]], observed[inlier[eligible]], s=9, c="#39d353", label="inlier") + scatter_axis.scatter(predicted[outlier[eligible]], observed[outlier[eligible]], s=12, c="#ff4d4f", marker="x", label="outlier") + if len(predicted): + low = float(min(predicted.min(), observed.min())) + high = float(max(predicted.max(), observed.max())) + grid = np.linspace(low, high, 100) + scatter_axis.plot(grid, grid, color="#666666", linewidth=1, label="surface identity") + scatter_axis.plot(grid, grid + diagnostics.delta_z_m, color="#d6278b", linewidth=1.3, label="raw IRLS shift") + scatter_axis.plot(grid, grid + correction, color="#00a6d6", linewidth=1.3, label="calibrated shift") + scatter_axis.set_xlabel("predicted MANO surface z (m)") + scatter_axis.set_ylabel("observed depth z (m)") + scatter_axis.set_title("Metric correspondence") + scatter_axis.grid(alpha=0.2) + scatter_axis.legend(fontsize=7) + + side_axis = axes[1, 0] + target_vertices = cache_arrays["target_vertices_camera"][index, hand] + refined_vertices = coarse_vertices.astype(np.float64).copy() + refined_vertices[:, 2] += correction + sample = np.arange(0, len(coarse_vertices), 6) + side_axis.scatter(coarse_vertices[sample, 2], coarse_vertices[sample, 0], s=3, c="#d6278b", alpha=0.35, label="coarse") + side_axis.scatter(refined_vertices[sample, 2], refined_vertices[sample, 0], s=3, c="#00a6d6", alpha=0.35, label="refined") + side_axis.scatter(target_vertices[sample, 2], target_vertices[sample, 0], s=3, c="#2ca02c", alpha=0.35, label="GT") + side_axis.set_xlabel("camera z (m)") + side_axis.set_ylabel("camera x (m)") + side_axis.set_title("Camera side view") + side_axis.grid(alpha=0.2) + side_axis.legend(fontsize=7) + side_axis.set_aspect("equal", adjustable="datalim") + + trace_axis = axes[1, 1] + start, stop = max(0, index - 20), min(len(frame_ids), index + 21) + trace_frames = frame_ids[start:stop] + coarse_signed = 1000.0 * ( + cache_arrays["pred_wrist_translation"][start:stop, hand, 2] + - cache_arrays["target_wrist_translation"][start:stop, hand, 2] + ) + refined_signed = coarse_signed + 1000.0 * alignment_arrays["calibrated_delta_z_m"][start:stop, hand] + trace_axis.plot(trace_frames, coarse_signed, color="#d6278b", label="coarse signed z") + trace_axis.plot(trace_frames, refined_signed, color="#00a6d6", label="refined signed z") + trace_axis.axhline(0.0, color="#555555", linewidth=0.8) + trace_axis.axvline(case["frame_id"], color="#111111", linestyle="--", linewidth=0.8) + trace_axis.set_xlabel("frame") + trace_axis.set_ylabel("pred - GT wrist z (mm)") + trace_axis.set_title("Local signed-z trace") + trace_axis.grid(alpha=0.2) + trace_axis.legend(fontsize=7) + + text_axis = axes[1, 2] + text_axis.axis("off") + text_axis.text(0.0, 1.0, "\n".join(( + f"role: {case['role']}", + f"take/frame: {case['take']} / {case['frame_id']}", + f"side, size, depth: {case['side']}, {case['hand_size_bucket']}, {case['depth_bucket']}", + f"coarse -> refined z MAE: {case['coarse_z_mae_mm']:.2f} -> {case['refined_z_mae_mm']:.2f} mm", + f"coarse -> refined MPJPE: {case['coarse_absolute_mpjpe_mm']:.2f} -> {case['refined_absolute_mpjpe_mm']:.2f} mm", + f"raw IRLS / calibrated delta-z: {1000.0 * diagnostics.delta_z_m:.2f} / {1000.0 * correction:.2f} mm", + f"support / inlier ratio: {diagnostics.valid_support_count} / {diagnostics.inlier_ratio:.3f}", + f"residual scale: {1000.0 * diagnostics.residual_scale_m:.2f} mm", + f"valid / foreground / background: {diagnostics.valid_fraction:.3f} / {diagnostics.foreground_fraction:.3f} / {diagnostics.background_fraction:.3f}", + f"depth discontinuity: {1000.0 * diagnostics.depth_discontinuity_m:.2f} mm", + f"conditioning / learned confidence: {diagnostics.conditioning_quality:.3f} / {case['alignment_confidence']:.3f}", + "selection: official-validation secondary diagnostic only", + )), va="top", family="monospace", fontsize=10) + figure.suptitle("Phase 5 predicted-location MANO-depth alignment diagnostic", fontsize=14) + figure.tight_layout() + output.parent.mkdir(parents=True, exist_ok=True) + figure.savefig(output) + plt.close(figure) + return { + **case, + "image": str(output.resolve()), + "image_sha256": sha256(output), + "eligible_surface_samples": int(eligible.sum()), + "inlier_surface_samples": int(inlier.sum()), + "outlier_surface_samples": int(outlier.sum()), + "rerender_raw_delta_z_mm": 1000.0 * diagnostics.delta_z_m, + "rerender_residual_scale_mm": 1000.0 * diagnostics.residual_scale_m, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-dir", type=Path, required=True) + parser.add_argument("--raw-cache-manifest", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--condition", default="calibrated_always") + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("visualization output directory must be new or empty") + evaluation = json.loads((args.evaluation_dir / "evaluation.json").read_text(encoding="utf-8")) + cache = json.loads(args.raw_cache_manifest.read_text(encoding="utf-8")) + if evaluation.get("official_test_used") is not False or cache.get("official_test_used") is not False: + raise ValueError("failure visualization requires test-free inputs") + if args.condition not in evaluation.get("conditions", []): + raise ValueError(f"condition is absent from evaluation: {args.condition}") + cases = select_cases( + load_csv(args.evaluation_dir / "per_hand_frame_metrics.csv"), args.condition, + ) + cache_by_take = {record["take"]: record for record in cache["takes"]} + records = [] + for case in cases: + cache_record = cache_by_take[case["take"]] + cache_path = Path(cache_record["path"]) + if sha256(cache_path) != cache_record["sha256"]: + raise ValueError(f"raw-cache hash mismatch: {cache_path}") + with np.load(cache_path, allow_pickle=False) as archive: + cache_arrays = {key: archive[key] for key in archive.files} + prediction_path = args.evaluation_dir / "predictions" / f"{'__'.join(Path(case['take']).parts)}.npz" + with np.load(prediction_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + filename = f"{case['role']}__{'__'.join(Path(case['take']).parts)}__f{case['frame_id']:06d}__{case['side']}.png" + records.append(render_case( + case, cache_arrays=cache_arrays, alignment_arrays=alignment, + data_root=args.data_root, output=args.output_dir / filename, + )) + report = { + "status": "complete", + "result_role": "official_validation_secondary_failure_diagnostic", + "selection_rule": ["right far/small maximum coarse z error", "largest refined z gain", "largest refined z harm"], + "condition": args.condition, + "evaluation": str(args.evaluation_dir.resolve()), + "raw_cache_manifest": str(args.raw_cache_manifest.resolve()), + "cases": records, + "used_for_model_or_threshold_selection": False, + "oracle_information_at_inference": False, + "official_test_used": False, + } + manifest_path = args.output_dir / "manifest.json" + manifest_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "cases": len(records), + "manifest": str(manifest_path), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_sota_projection_audit.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_sota_projection_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..212336420b5c6d1a025fd254f26dc10df78e55fa --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/render_sota_projection_audit.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Render deterministic GT/prediction projection checks for SOTA bundles.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + align_prediction, +) + + +EDGES = tuple( + edge + for finger_start in (1, 5, 9, 13, 17) + for edge in ( + (0, finger_start), + (finger_start, finger_start + 1), + (finger_start + 1, finger_start + 2), + (finger_start + 2, finger_start + 3), + ) +) +SIDE_COLORS = ((255, 200, 0), (0, 80, 255)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def project(points: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + normalized = points[..., :2] / points[..., 2:3] + return normalized @ intrinsics[:2, :2].T + intrinsics[:2, 2] + + +def draw_hand( + image: np.ndarray, + points: np.ndarray, + color: tuple[int, int, int], + *, + thickness: int, + radius: int, +) -> None: + rounded = np.rint(points).astype(np.int32) + for start, end in EDGES: + cv2.line( + image, + tuple(rounded[start]), + tuple(rounded[end]), + color, + thickness, + cv2.LINE_AA, + ) + for point in rounded: + cv2.circle(image, tuple(point), radius, color, -1, cv2.LINE_AA) + + +def make_panel( + image: np.ndarray, + label: str, + predicted: np.ndarray, + target: np.ndarray, + intrinsics: np.ndarray, + detected: np.ndarray, +) -> tuple[np.ndarray, float | None]: + panel = image.copy() + for hand in (0, 1): + draw_hand( + panel, + project(target[hand], intrinsics), + (245, 245, 245), + thickness=4, + radius=4, + ) + if detected[hand]: + draw_hand( + panel, + project(predicted[hand], intrinsics), + SIDE_COLORS[hand], + thickness=2, + radius=3, + ) + valid_hands = np.flatnonzero(detected) + error = None + if valid_hands.size: + error = float( + np.linalg.norm( + predicted[valid_hands] - target[valid_hands], axis=-1 + ).mean() + * 1000.0 + ) + cv2.rectangle(panel, (0, 0), (panel.shape[1], 46), (10, 10, 10), -1) + text = f"{label} Abs={error:.1f} mm" if error is not None else f"{label} missed" + cv2.putText( + panel, + text, + (12, 31), + cv2.FONT_HERSHEY_SIMPLEX, + 0.8, + (255, 255, 255), + 2, + cv2.LINE_AA, + ) + return panel, error + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--prediction", action="append", required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=6) + parser.add_argument("--panel-width", type=int, default=480) + args = parser.parse_args() + if args.samples <= 0 or args.panel_width <= 0: + raise ValueError("samples and panel width must be positive") + + ground_truth = GroundTruthBundle.load(args.ground_truth) + bundles: list[tuple[str, PredictionBundle, Path]] = [] + labels = set() + for spec in args.prediction: + label, separator, raw_path = spec.partition("=") + if not separator or not label or not raw_path or label in labels: + raise ValueError(f"Invalid or duplicate prediction spec: {spec}") + labels.add(label) + path = Path(raw_path).resolve() + bundles.append((label, align_prediction(PredictionBundle.load(path), ground_truth), path)) + + eligible = ground_truth.annotation_valid.all(axis=1) + for _, bundle, _ in bundles: + eligible &= bundle.detected.all(axis=1) + candidate_indices = np.flatnonzero(eligible) + if candidate_indices.size < args.samples: + raise ValueError("Not enough jointly valid/detected frames for projection audit") + positions = np.rint( + np.linspace(0, candidate_indices.size - 1, args.samples) + ).astype(np.int64) + selected = candidate_indices[positions] + + output_rows = [] + record_rows: list[dict[str, Any]] = [] + for frame_index in selected: + take = str(ground_truth.takes[frame_index]) + frame_id = int(ground_truth.frame_ids[frame_index]) + path = args.root / take / "rgb" / f"{frame_id:06d}.png" + image = cv2.imread(str(path)) + if image is None: + raise RuntimeError(f"Image decode failure: {path}") + panels = [] + for label, bundle, _ in bundles: + panel, error = make_panel( + image, + label, + bundle.joints_camera_m[frame_index], + ground_truth.joints_camera_m[frame_index], + ground_truth.intrinsics[frame_index], + bundle.detected[frame_index], + ) + height = round(panel.shape[0] * args.panel_width / panel.shape[1]) + panels.append(cv2.resize(panel, (args.panel_width, height))) + record_rows.append({ + "frame_key": str(ground_truth.frame_keys[frame_index]), + "model": label, + "absolute_mpjpe_mm": error, + }) + output_rows.append(np.concatenate(panels, axis=1)) + + audit_models = [] + height, width = image.shape[:2] + for label, bundle, path in bundles: + detected_points = bundle.joints_camera_m[bundle.detected] + K = np.repeat(ground_truth.intrinsics[:, None], 2, axis=1)[bundle.detected] + uv = np.einsum( + "nij,nkj->nki", + K[:, :2, :2], + detected_points[..., :2] / detected_points[..., 2:3], + ) + K[:, None, :2, 2] + in_frame = ( + (uv[..., 0] >= 0) + & (uv[..., 0] < width) + & (uv[..., 1] >= 0) + & (uv[..., 1] < height) + ) + audit_models.append({ + "label": label, + "prediction": str(path), + "prediction_sha256": sha256(path), + "detected_hand_frames": int(bundle.detected.sum()), + "finite_detected_fraction": float(np.isfinite(detected_points).all(axis=-1).mean()), + "positive_depth_fraction": float((detected_points[..., 2] > 0).mean()), + "projected_joint_in_frame_fraction": float(in_frame.mean()), + "wrist_z_m_percentiles": np.percentile( + detected_points[:, 0, 2], (1, 50, 99) + ).tolist(), + }) + + args.output_dir.mkdir(parents=True, exist_ok=True) + contact_sheet = np.concatenate(output_rows, axis=0) + contact_path = args.output_dir / "projection_contact_sheet.jpg" + if not cv2.imwrite(str(contact_path), contact_sheet, [cv2.IMWRITE_JPEG_QUALITY, 92]): + raise RuntimeError(f"Failed to write {contact_path}") + payload = { + "status": "pass", + "official_test_used": False, + "selection": "evenly spaced among frames valid and detected for every model", + "legend": "GT white; prediction left cyan and right red", + "selected_frame_keys": [ + str(ground_truth.frame_keys[index]) for index in selected + ], + "per_selected_frame": record_rows, + "models": audit_models, + "contact_sheet": str(contact_path.resolve()), + "contact_sheet_sha256": sha256(contact_path), + } + (args.output_dir / "visual_audit.json").write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(payload, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_dynhamr_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_dynhamr_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..84bdce419fb36846d43852afe76b93928b2290ea --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_dynhamr_h2o.py @@ -0,0 +1,627 @@ +#!/usr/bin/env python3 +"""Run the released Dyn-HaMR TTO pipeline zero-shot on H2O validation runs.""" + +from __future__ import annotations + +import argparse +import contextlib +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from scipy.interpolate import interp1d +from scipy.spatial.transform import Rotation, Slerp + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, frame_key +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--rescale-factor", type=float, default=1.3) + parser.add_argument("--max-runs", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + parser.add_argument( + "--run-indices", + nargs="*", + type=int, + help="Explicit global manifest-run order; overrides modulo sharding.", + ) + return parser.parse_args() + + +def _load_manifest_runs(path: Path) -> list[dict[str, Any]]: + runs = [json.loads(line) for line in path.read_text().splitlines() if line.strip()] + for run_index, run in enumerate(runs): + take = str(run["take"]) + if not take.endswith("/cam4"): + raise ValueError(f"Dyn-HaMR evaluation is cam4-only: {take}") + run["global_run_index"] = run_index + run["frame_ids"] = [int(value) for value in run["frame_ids"]] + return runs + + +def _import_hamer_runner(repo: Path) -> Any: + path = repo / "third-party" / "hamer" / "run.py" + spec = importlib.util.spec_from_file_location("dynhamr_released_hamer_runner", path) + if spec is None or spec.loader is None: + raise ImportError(f"Cannot import released HaMeR runner: {path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _to_numpy(value: Any) -> np.ndarray: + if torch.is_tensor(value): + return value.detach().float().cpu().numpy() + return np.asarray(value) + + +def _interpolate_rotvec(values: np.ndarray, visible: np.ndarray) -> np.ndarray: + output = values.copy() + indices = np.flatnonzero(visible) + if len(indices) < 2: + return output + times = np.arange(indices[0], indices[-1] + 1) + rotations = Rotation.from_rotvec(values[indices].reshape(len(indices), -1, 3)) + joint_count = rotations.as_rotvec().shape[1] + for joint in range(joint_count): + slerp = Slerp(indices, Rotation.from_rotvec(values[indices, joint])) + output[times, joint] = slerp(times).as_rotvec() + return output + + +def _interpolate_linear(values: np.ndarray, visible: np.ndarray) -> np.ndarray: + output = values.copy() + indices = np.flatnonzero(visible) + if len(indices) < 2: + return output + times = np.arange(indices[0], indices[-1] + 1) + function = interp1d(indices, values[indices], axis=0, kind="linear") + output[times] = function(times) + return output + + +def _extract_initialization( + frame_paths: list[Path], + raw_data: list[dict[str, Any]], + results: dict[str, Any], +) -> dict[str, np.ndarray]: + count = len(frame_paths) + pose = np.full((2, count, 15, 3), np.nan, dtype=np.float32) + orient = np.full((2, count, 1, 3), np.nan, dtype=np.float32) + shape = np.full((2, count, 10), np.nan, dtype=np.float32) + translation = np.full((2, count, 3), np.nan, dtype=np.float32) + keypoints = np.full((2, count, 21, 3), np.nan, dtype=np.float32) + confidence = np.full((2, count), np.nan, dtype=np.float32) + + for frame_index, (path, cleaned) in enumerate(zip(frame_paths, raw_data, strict=True)): + result = results[str(path)] + sides = np.asarray(result["tid"], dtype=np.int64) + for local, side in enumerate(sides): + mano = result["mano"][local] + hand_matrix = _to_numpy(mano["hand_pose"]).reshape(15, 3, 3) + root_matrix = _to_numpy(mano["global_orient"]).reshape(3, 3) + pose[side, frame_index] = Rotation.from_matrix(hand_matrix).as_rotvec() + orient[side, frame_index, 0] = Rotation.from_matrix(root_matrix).as_rotvec() + shape[side, frame_index] = _to_numpy(mano["betas"]).reshape(10) + translation[side, frame_index] = np.asarray( + result["cam_trans"][local], dtype=np.float32 + ) + keypoints[side, frame_index] = np.asarray( + result["extra_data"][local], dtype=np.float32 + ) + confidence[side, frame_index] = float( + cleaned["left_conf" if side == 0 else "right_conf"] + ) + + active = np.isfinite(pose).all(axis=(-1, -2)) + recovered = np.zeros_like(active) + vis_mask = np.full((2, count), -1.0, dtype=np.float32) + for side in (0, 1): + indices = np.flatnonzero(active[side]) + if len(indices) < 2: + continue + interval = slice(indices[0], indices[-1] + 1) + recovered[side, interval] = True + vis_mask[side, interval] = 0.0 + vis_mask[side, active[side]] = 1.0 + pose[side] = _interpolate_rotvec(pose[side], active[side]) + orient[side] = _interpolate_rotvec(orient[side], active[side]) + shape[side] = _interpolate_linear(shape[side], active[side]) + translation[side] = _interpolate_linear(translation[side], active[side]) + keypoints[side] = _interpolate_linear(keypoints[side], active[side]) + confidence[side] = _interpolate_linear(confidence[side], active[side]) + # The released file loader represents frames outside each recovered track + # with zeros and excludes them through the ternary visibility mask. + for values in (pose, orient, shape, translation, keypoints): + np.nan_to_num(values, copy=False) + return { + "pose": pose, + "orient": orient[:, :, 0], + "shape": shape, + "translation": translation, + "keypoints": keypoints, + "confidence": confidence, + "active": active, + "recovered": recovered, + "vis_mask": vis_mask, + } + + +def _run_official_initialization( + repo: Path, + frame_paths: list[Path], + detector: Any, + hamer_model: torch.nn.Module, + hamer_config: Any, + runner: Any, + rescale_factor: float, +) -> dict[str, np.ndarray]: + raw_data = runner.extract_raw_bboxes(frame_paths, detector, vis_dir=None) + cleaned_data = runner.clean_bbox_sequences(raw_data, vis_dir=None) + results = runner.run_hamer_on_cleaned_bboxes( + cleaned_data, + hamer_model, + hamer_config, + None, + SimpleNamespace( + rescale_factor=rescale_factor, + render=False, + res_folder=str(repo / "outputs" / "unused.pkl"), + ), + ) + return _extract_initialization(frame_paths, cleaned_data, results) + + +class _InactiveBMCLoss: + """Avoid loading unavailable BMC assets when all official bio weights are zero.""" + + def __init__(self, *_: Any, **__: Any) -> None: + pass + + def compute_loss(self, *_: Any, **__: Any) -> Any: + raise RuntimeError("BMC loss called although the released bio weight is zero") + + +def _run_optimizer_exact( + optimizer: Any, + observed: dict[str, Any], + iterations: int, +) -> int: + """Run the released outer-loop and early-stop logic without file checkpoints.""" + + optimizer.cur_step = 0 + optimizer.loss.cur_step = 0 + completed = 0 + for iteration in range(iterations): + optimizer.cur_step = iteration + optimizer.loss.cur_step = iteration + optimizer.optim_step(observed, iteration, writer=None) + completed = iteration + 1 + if np.isnan(optimizer.cur_loss): + raise FloatingPointError(f"{optimizer.name} produced NaN") + if optimizer.reached_max and optimizer.reached_max_iter < 0: + optimizer.reached_max_iter = iteration - 1 + if ( + optimizer.reached_max + and iteration - optimizer.reached_max_iter >= optimizer.max_chunk_steps + ): + break + loss_change = optimizer.prev_loss - optimizer.cur_loss + if optimizer.last_updated == iteration - 1 and loss_change == 0: + break + if ( + (optimizer.cur_loss < 0 and loss_change < 100) + or (iteration - optimizer.last_updated >= optimizer.max_chunk_steps) + or (loss_change < 20 and iteration - optimizer.last_updated > 5) + ): + optimizer.add_chunk += 1 + optimizer.last_updated = iteration + optimizer.prev_loss = optimizer.cur_loss + return completed + + +def _optimize_run( + repo: Path, + initialization: dict[str, np.ndarray], + intrinsics: np.ndarray, + device: torch.device, + log_path: Path, +) -> tuple[np.ndarray, np.ndarray, dict[str, int]]: + sys.path.insert(0, str(repo / "dyn-hamr")) + from body_model import MANO + from optim import losses as loss_module + from optim.base_scene import BaseSceneModel + from optim.optimizers import RootOptimizer, SmoothOptimizer + from util.logger import Logger + + active_sides = np.flatnonzero(initialization["recovered"].any(axis=1)) + count = initialization["pose"].shape[1] + output_joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + output_vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + if len(active_sides) == 0: + return output_joints, output_vertices, {"root_iterations": 0, "smooth_iterations": 0} + + loss_module.BMCLoss = _InactiveBMCLoss + config = yaml.safe_load((repo / "dyn-hamr" / "confs" / "optim.yaml").read_text())[ + "optim" + ] + all_weights = config["loss_weights"] + stage_weights = [ + {name: values[stage] for name, values in all_weights.items()} + for stage in range(3) + ] + options = dict(config["options"]) + options["vis_every"] = -1 + options["save_meshes"] = False + + batch = len(active_sides) + mano = MANO( + batch_size=batch * count, + pose2rot=True, + model_path=str(repo / "_DATA" / "data" / "mano"), + gender="neutral", + num_hand_joints=15, + mean_params=str(repo / "_DATA" / "data" / "mano_mean_params.npz"), + create_body_pose=False, + ).to(device) + scene = BaseSceneModel( + batch, + count, + mano, + None, + use_init=True, + opt_cams=False, + opt_scale=False, + async_tracks=True, + ) + observed: dict[str, Any] = { + "joints2d": torch.from_numpy(initialization["keypoints"][active_sides]).to(device), + "init_body_pose": torch.from_numpy(initialization["pose"][active_sides]).to(device), + "init_body_shape": torch.from_numpy(initialization["shape"][active_sides]).to(device), + "init_root_orient": torch.from_numpy(initialization["orient"][active_sides]).to(device), + "init_trans": torch.from_numpy(initialization["translation"][active_sides]).to(device), + "is_right": torch.from_numpy( + np.broadcast_to(active_sides[:, None], (batch, count)).astype(np.float32).copy() + ).to(device), + "vis_mask": torch.from_numpy(initialization["vis_mask"][active_sides]).to(device), + } + cam_data = { + "cam_R": torch.eye(3, device=device)[None].repeat(count, 1, 1), + "cam_t": torch.zeros(count, 3, device=device), + "intrins": torch.from_numpy( + np.stack( + [ + intrinsics[:, 0, 0], + intrinsics[:, 1, 1], + intrinsics[:, 0, 2], + intrinsics[:, 1, 2], + ], + axis=-1, + ).astype(np.float32) + ).to(device), + "static": True, + } + scene.initialize(observed, cam_data) + scene = scene.to(device) + Logger.init(str(log_path)) + + root_optimizer = RootOptimizer(scene, stage_weights, **options) + root_iterations = _run_optimizer_exact( + root_optimizer, observed, int(config["root"]["num_iters"]) + ) + smooth_options = dict(options) + smooth_options["opt_scale"] = bool(config["smooth"]["opt_scale"]) + smooth_optimizer = SmoothOptimizer(scene, stage_weights, **smooth_options) + smooth_iterations = _run_optimizer_exact( + smooth_optimizer, observed, int(config["smooth"]["num_iters"]) + ) + + with torch.inference_mode(): + prediction = scene.pred_params_mano(observed["is_right"]) + predicted_joints = prediction["joints3d"].float().cpu().numpy() + predicted_vertices = prediction["verts3d"].float().cpu().numpy() + for local, side in enumerate(active_sides): + valid = initialization["recovered"][side] + output_joints[valid, side] = predicted_joints[local, valid] + output_vertices[valid, side] = predicted_vertices[local, valid] + del root_optimizer, smooth_optimizer, scene, mano + torch.cuda.empty_cache() + plt.close("all") + return output_joints, output_vertices, { + "root_iterations": root_iterations, + "smooth_iterations": smooth_iterations, + } + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "detector", + "root", + "manifest", + "ground_truth", + "cache_dir", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + args.cache_dir.mkdir(parents=True, exist_ok=True) + args.output.parent.mkdir(parents=True, exist_ok=True) + + enable_legacy_mano_loading() + hamer_root = args.repo / "third-party" / "hamer" + sys.path.insert(0, str(hamer_root)) + sys.path.insert(0, str(args.repo / "dyn-hamr")) + os.chdir(args.repo) + from hamer.models import load_hamer + from ultralytics import YOLO + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + hamer_model, hamer_config = load_hamer(str(args.repo)) + hamer_model = hamer_model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + hamer_runner = _import_hamer_runner(args.repo) + + all_runs = _load_manifest_runs(args.manifest) + if args.run_indices is not None: + if len(set(args.run_indices)) != len(args.run_indices): + raise ValueError("Explicit run indices contain duplicates") + if any(index < 0 or index >= len(all_runs) for index in args.run_indices): + raise ValueError("Explicit run index is outside the manifest") + selected = [all_runs[index] for index in args.run_indices] + else: + selected = [ + run + for run in all_runs + if int(run["global_run_index"]) % args.num_shards == args.shard_index + ] + if args.max_runs is not None: + selected = selected[: args.max_runs] + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + + frame_keys: list[str] = [] + takes: list[str] = [] + frame_ids: list[int] = [] + run_outputs: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]] = [] + total_root_iterations = 0 + total_smooth_iterations = 0 + initialized_runs = 0 + optimized_runs = 0 + initialization_seconds = 0.0 + optimization_seconds = 0.0 + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for selected_index, run in enumerate(selected): + run_index = int(run["global_run_index"]) + take = str(run["take"]) + ids = np.asarray(run["frame_ids"], dtype=np.int64) + keys = np.asarray([frame_key(take, int(value)) for value in ids], dtype=np.str_) + frame_paths = [ + args.root / take / "rgb" / f"{int(value):06d}.png" for value in ids + ] + if not all(path.is_file() for path in frame_paths): + raise FileNotFoundError(f"Missing H2O RGB frame in run {run_index}") + run_dir = args.cache_dir / f"run_{run_index:03d}" + run_dir.mkdir(parents=True, exist_ok=True) + init_path = run_dir / "initialization.npz" + pred_path = run_dir / "prediction.npz" + log_path = run_dir / "optimizer.log" + if init_path.is_file(): + with np.load(init_path, allow_pickle=False) as data: + initialization = {name: data[name].copy() for name in data.files} + else: + if device.type == "cuda": + torch.cuda.synchronize(device) + stage_started = time.perf_counter() + with log_path.open("a", encoding="utf-8") as log, contextlib.redirect_stdout( + log + ), contextlib.redirect_stderr(log): + initialization = _run_official_initialization( + args.repo, + frame_paths, + detector, + hamer_model, + hamer_config, + hamer_runner, + args.rescale_factor, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + initialization_seconds += time.perf_counter() - stage_started + np.savez_compressed(init_path, **initialization) + initialized_runs += 1 + confidence = initialization["confidence"] + recovered = initialization["recovered"] + if pred_path.is_file(): + with np.load(pred_path, allow_pickle=False) as data: + run_joints = data["joints"].copy() + run_vertices = data["vertices"].copy() + iteration_counts = json.loads(str(data["iteration_counts_json"].item())) + else: + indices = np.asarray([gt_index[str(key)] for key in keys], dtype=np.int64) + # The released optimizer prints full pose tensors for every LBFGS + # closure. Logger still records scalar losses in optimizer.log. + if device.type == "cuda": + torch.cuda.synchronize(device) + stage_started = time.perf_counter() + with Path(os.devnull).open("w") as sink, contextlib.redirect_stdout( + sink + ), contextlib.redirect_stderr(sink): + run_joints, run_vertices, iteration_counts = _optimize_run( + args.repo, + initialization, + ground_truth.intrinsics[indices], + device, + log_path, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + optimization_seconds += time.perf_counter() - stage_started + np.savez_compressed( + pred_path, + joints=run_joints, + vertices=run_vertices, + iteration_counts_json=np.asarray(json.dumps(iteration_counts)), + ) + optimized_runs += 1 + total_root_iterations += int(iteration_counts["root_iterations"]) + total_smooth_iterations += int(iteration_counts["smooth_iterations"]) + frame_keys.extend(keys.tolist()) + takes.extend([take] * len(ids)) + frame_ids.extend(ids.tolist()) + run_outputs.append((run_joints, run_vertices, recovered.T, confidence.T)) + print( + f"Dyn-HaMR run {selected_index + 1}/{len(selected)} " + f"global={run_index} frames={len(ids)} " + f"iters={iteration_counts['root_iterations']}/{iteration_counts['smooth_iterations']}", + flush=True, + ) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "Dyn-HaMR", + "scope": "RGB detector/HaMeR initialization + per-run Root/Smooth test-time optimization", + "frames": int(sum(len(run["frame_ids"]) for run in selected)), + "runs": len(selected), + "processing_seconds": processing_seconds, + "frames_per_second": int(sum(len(run["frame_ids"]) for run in selected)) / processing_seconds, + "initialization_seconds": initialization_seconds, + "optimization_seconds": optimization_seconds, + "cache_and_host_overhead_seconds": processing_seconds - initialization_seconds - optimization_seconds, + "root_iterations": total_root_iterations, + "smooth_iterations": total_smooth_iterations, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + joints = np.concatenate([value[0] for value in run_outputs], axis=0) + vertices = np.concatenate([value[1] for value in run_outputs], axis=0) + detected = np.concatenate([value[2] for value in run_outputs], axis=0) + confidence = np.concatenate([value[3] for value in run_outputs], axis=0) + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + hamer_commit = subprocess.check_output( + ["git", "-C", str(hamer_root), "rev-parse", "HEAD"], text=True + ).strip() + hamer_checkpoint = args.repo / "_DATA" / "hamer_ckpts" / "checkpoints" / "hamer.ckpt" + reconstruction_parameters = sum( + parameter.numel() for parameter in hamer_model.parameters() + ) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/ZhengdiYu/Dyn-HaMR", + "repository_commit": commit, + "hamer_repository_commit": hamer_commit, + "hamer_checkpoint": str(hamer_checkpoint), + "hamer_checkpoint_sha256": sha256(hamer_checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": ( + "full RGB video, released enhanced YOLO/HaMeR tracker, known static H2O cam4 K, " + "per-contiguous-run Root and Smooth test-time optimization" + ), + "training_exposure": ( + "Dyn-HaMR is test-time optimization; released HaMeR initializer training includes " + "H2O3D but not H2O; no H2O fine-tuning" + ), + "fine_tuning": "not applicable: adaptation is per-video test-time optimization", + "camera_policy": "known static H2O cam4 extrinsics/intrinsics; no SLAM or GT pose", + "optimizer_config": str(args.repo / "dyn-hamr" / "confs" / "optim.yaml"), + "optimizer_config_sha256": sha256(args.repo / "dyn-hamr" / "confs" / "optim.yaml"), + "root_iterations_total": total_root_iterations, + "smooth_iterations_total": total_smooth_iterations, + "run_count": len(selected), + "new_initializations": initialized_runs, + "new_optimizations": optimized_runs, + "rescale_factor": args.rescale_factor, + "detector_confidence_threshold": 0.5, + "temporal": True, + "temporal_protocol": "each official validation manifest run optimized independently", + "optional_hmp_prior_used": False, + "inactive_bmc_asset_policy": ( + "BMC object initialization skipped because released bio weights are zero in all stages" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + "explicit_run_indices": args.run_indices, + } + bundle = PredictionBundle( + model_name="Dyn-HaMR-zero-shot-TTO", + frame_keys=np.asarray(frame_keys, dtype=np.str_), + takes=np.asarray(takes, dtype=np.str_), + frame_ids=np.asarray(frame_ids, dtype=np.int64), + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_foundation_hand_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_foundation_hand_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..52771dd5f05a9772cec1488dad3789b731bb9065 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_foundation_hand_h2o.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Export the promoted Phase 3 model into the common SOTA prediction schema.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.evaluation.sota import PredictionBundle, frame_key, load_frame_index +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--max-clips", type=int) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + keys, takes, frame_ids = load_frame_index(args.manifest) + key_to_index = {str(key): index for index, key in enumerate(keys)} + count = len(keys) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), + (int(data_config["stride"]),), + max_clips=args.max_clips, + ) + loader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint( + args.checkpoint, model, optimizer=None, map_location=device + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + exported = 0 + processed_clips = 0 + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = { + name: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for name, value in batch_cpu.items() + } + with torch.autocast("cuda", dtype=dtype): + output = model(batch) + valid_length = int(batch["frame_valid"][0].sum()) + output_joints = output["joints_camera"][0, :valid_length].float().cpu().numpy() + output_vertices = output["vertices_camera"][0, :valid_length].float().cpu().numpy() + for time_index in range(valid_length): + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + frame_id_value = int(batch["frame_id"][0, time_index]) + index = key_to_index[frame_key(take, frame_id_value)] + joints[index] = output_joints[time_index] + vertices[index] = output_vertices[time_index] + detected[index] = True + exported += 1 + processed_clips = clip_index + 1 + if (clip_index + 1) % 100 == 0 or clip_index + 1 == len(loader): + print(f"FoundationHand clips {clip_index + 1}/{len(loader)}", flush=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + processed_frames = int(detected.all(axis=1).sum()) + if args.timing_output is not None: + timing_output = args.timing_output.resolve() + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "FoundationHand-Phase3", + "scope": "RGB+Depth+K decode/preprocessing + BF16 T=8 model forward + host result transfer", + "frames": processed_frames, + "clips": processed_clips, + "processing_seconds": processing_seconds, + "frames_per_second": processed_frames / processing_seconds, + "clips_per_second": processed_clips / processing_seconds, + "amortized_ms_per_frame": 1000.0 * processing_seconds / processed_frames, + "clip_length": int(data_config["T"]), + "resolution_hw": data_config["resolution_hw"], + "batch_size_clips": 1, + "num_workers": args.num_workers, + "precision": config["precision"], + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + if args.max_clips is not None: + processed = detected.all(axis=1) + keys, takes, frame_ids = keys[processed], takes[processed], frame_ids[processed] + joints, vertices = joints[processed], vertices[processed] + detected, confidence = detected[processed], confidence[processed] + elif exported != count: + raise RuntimeError(f"Expected {count} exported frames, observed {exported}") + + repository_commit = subprocess.check_output( + ["git", "rev-parse", "HEAD"], text=True + ).strip() + parameter_count = sum(parameter.numel() for parameter in model.parameters()) + trainable_parameter_count = sum( + parameter.numel() for parameter in model.parameters() if parameter.requires_grad + ) + bundle = PredictionBundle( + model_name="FoundationHand-Phase3", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata={ + "repository_commit_at_export": repository_commit, + "training_commit": "d4019222835132fcbcc850ba49e6e0b53ab352b3", + "checkpoint": str(args.checkpoint.resolve()), + "checkpoint_sha256": sha256(args.checkpoint), + "checkpoint_step": int(checkpoint_state["step"]), + "parameter_count": parameter_count, + "trainable_parameter_count_at_export": trainable_parameter_count, + "input": "full RGB + aligned metric Depth + H2O K, T=8", + "temporal": True, + "temporal_window": int(data_config["T"]), + "detector": False, + "fixed_semantic_slots": True, + "official_test_used": False, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_hamba_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_hamba_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..80aca96be62d8cdd4d3d9c34afa69fc86f906300 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_hamba_h2o.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Run the released Hamba checkpoint on H2O with a common hand detector.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, load_frame_index +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--preprocess-repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256") + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=8) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "preprocess_repo", + "checkpoint", + "config", + "detector", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + if args.checkpoint_sha256 is not None and ( + len(args.checkpoint_sha256) != 64 + or any(character not in "0123456789abcdef" for character in args.checkpoint_sha256) + ): + raise ValueError("--checkpoint-sha256 must be 64 lowercase hexadecimal characters") + + sys.path.insert(0, str(args.preprocess_repo)) + sys.path.insert(0, str(args.repo)) + enable_legacy_mano_loading() + os.chdir(args.repo) + + from hamba.configs import get_config + from hamba.models import HAMBA + from ultralytics import YOLO + from wilor.datasets.vitdet_dataset import ViTDetDataset + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + config = get_config(str(args.config), update_cachedir=True) + config.defrost() + config.MODEL.BBOX_SHAPE = [192, 256] + config.MODEL.BACKBONE.pop("PRETRAINED_WEIGHTS", None) + config.MODEL.pop("PRETRAINED_WEIGHTS_INIT_REGRESSION", None) + config.freeze() + if not config.MODEL.USE_INIT_REGRESSION: + raise ValueError("This adapter requires the released initial-regressor configuration") + model = HAMBA(config, init_renderer=False) + checkpoint = torch.load( + args.checkpoint, + map_location="cpu", + weights_only=False, + mmap=True, + ) + model.load_state_dict(checkpoint["state_dict"], strict=True) + del checkpoint + model = model.to(device).eval() + + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch["keypoints_2d"] = torch.zeros((batch_size, 21, 3), dtype=torch.float32) + batch["is_valid"] = torch.ones(batch_size, dtype=torch.int64) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + record_indices = np.asarray([record[0] for record in records]) + intrinsic = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (intrinsic[:, 0, 0] + intrinsic[:, 1, 1]) + principal = intrinsic[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + camera = torch.stack(( + pred_cam[:, 1] + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), dim=-1).float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + batch_joints += camera[:, None] + batch_vertices += camera[:, None] + for local, (frame_index, side, score, _) in enumerate(records): + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + dataset = ViTDetDataset( + config, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"Hamba detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + kernel_path = Path(sys.modules["selective_scan_cuda_oflex"].__file__).resolve() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/humansensinglab/Hamba", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": args.checkpoint_sha256 or sha256(args.checkpoint), + "config": str(args.config), + "config_sha256": sha256(args.config), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector hand boxes, per-hand crops", + "training_exposure": "zero-shot H2O; release config includes H2O3D but not H2O", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "camera_policy": "cam_crop_to_full algebra with known H2O focal/principal point", + "preprocessing": "official HaMeR-compatible crop geometry shared with WiLoR", + "joint_source": "released Hamba initial regressor; no GT or external 2D joints", + "test_time_augmentation": False, + "selective_scan_kernel": str(kernel_path), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="Hamba-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_handdgp_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_handdgp_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..6a22aa27e858db7aa398de80e9399957e95d783b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_handdgp_h2o.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Run the released FreiHAND HandDGP checkpoint zero-shot on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import cv2 +import kornia +import numpy as np +import torch + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + load_frame_index, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=32) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--crop-scale", type=float, default=1.3) + parser.add_argument("--input-size", type=int, default=224) + parser.add_argument("--canonical-focal", type=float, default=1000.0) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def _prepare_crop( + image_rgb: np.ndarray, + box_xyxy: np.ndarray, + intrinsic: np.ndarray, + *, + is_left: bool, + input_size: int, + crop_scale: float, + canonical_focal: float, + generate_patch_image: Any, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Apply the released square crop and canonical-intrinsics rectification.""" + + image = image_rgb + box = np.asarray(box_xyxy, dtype=np.float32).copy() + K = np.asarray(intrinsic, dtype=np.float32).copy() + if is_left: + width = image.shape[1] + image = np.ascontiguousarray(image[:, ::-1]) + box[[0, 2]] = (width - 1) - box[[2, 0]] + K[0, 2] = (width - 1) - K[0, 2] + + width = float(box[2] - box[0]) + height = float(box[3] - box[1]) + side = max(width, height) + center = np.asarray( + [(box[0] + box[2]) * 0.5, (box[1] + box[3]) * 0.5], + dtype=np.float32, + ) + square_box = ( + float(center[0] - 0.5 * side), + float(center[1] - 0.5 * side), + side, + side, + ) + crop, _, _, _, _ = generate_patch_image( + cvimg=image, + bbox=square_box, + scale=crop_scale, + rot=0.0, + shift=(0.0, 0.0), + do_flip=False, + out_shape=(input_size, input_size), + shift_wh=None, + mask=None, + ) + crop_tensor = torch.from_numpy(np.ascontiguousarray(crop)).float() + crop_tensor = crop_tensor.permute(2, 0, 1) / 255.0 + + # FreiHAND hands are centered close to the optical axis. For arbitrary + # detector crops, use the equivalent box-centered virtual camera and map + # its ray back to the raw H2O camera after inference. + focal_scaled = K[[0, 1], [0, 1]] * input_size / (side * crop_scale) + crop_intrinsic = np.asarray( + [ + [focal_scaled[0], 0.0, input_size * 0.5], + [0.0, focal_scaled[1], input_size * 0.5], + [0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + canonical_intrinsic = np.asarray( + [ + [canonical_focal, 0.0, input_size * 0.5], + [0.0, canonical_focal, input_size * 0.5], + [0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + rectification = torch.from_numpy( + canonical_intrinsic @ np.linalg.inv(crop_intrinsic) + ) + crop_tensor = kornia.geometry.transform.warp_affine( + crop_tensor.unsqueeze(0), + rectification[:2, :3].unsqueeze(0), + dsize=(input_size, input_size), + mode="bilinear", + padding_mode="zeros", + align_corners=True, + ).squeeze(0) + ray_offset = (center - K[:2, 2]) / K[[0, 1], [0, 1]] + return ( + crop_tensor, + torch.from_numpy(canonical_intrinsic), + torch.from_numpy(ray_offset.astype(np.float32)), + ) + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "checkpoint", + "detector", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from src.models.handdgp import HandDGP + from third_party.HandMesh.utils.preprocessing import generate_patch_image + from ultralytics import YOLO + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], + takes[: args.max_frames], + frame_ids[: args.max_frames], + ) + count = len(keys) + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack( + [ground_truth.intrinsics[gt_index[str(key)]] for key in keys] + ) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + model = HandDGP( + batch_size=args.reconstruction_batch_size, + imagenet_pretrain=False, + input_size=args.input_size, + ) + checkpoint = torch.load( + args.checkpoint, + map_location="cpu", + weights_only=False, + mmap=True, + ) + state_dict = { + name.removeprefix("model."): value + for name, value in checkpoint["state_dict"].items() + } + model.load_state_dict(state_dict, strict=True) + del checkpoint, state_dict + model = model.to(device).eval() + + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + queue: list[ + tuple[int, int, float, torch.Tensor, torch.Tensor, torch.Tensor] + ] = [] + + def flush_queue(force: bool = False) -> None: + while len(queue) >= args.reconstruction_batch_size or (force and queue): + batch_size = min(args.reconstruction_batch_size, len(queue)) + records = queue[:batch_size] + del queue[:batch_size] + images = torch.stack([record[3] for record in records]).to(device) + camera = torch.stack([record[4] for record in records]).to(device) + with torch.inference_mode(): + output = model(images, camera, hand_scale=0.2) + batch_joints = output["keypoints3D_cs"].float().cpu().numpy() + batch_vertices = output["mesh_vertices3D_cs"].float().cpu().numpy() + ray_offsets = torch.stack([record[5] for record in records]).numpy() + batch_joints[..., :2] += ( + ray_offsets[:, None] * batch_joints[..., 2:3] + ) + batch_vertices[..., :2] += ( + ray_offsets[:, None] * batch_vertices[..., 2:3] + ) + for local, (frame_index, side, score, _, _, _) in enumerate(records): + if side == 0: + batch_joints[local, :, 0] *= -1.0 + batch_vertices[local, :, 0] *= -1.0 + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images_bgr = [ + cv2.imread( + str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png") + ) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images_bgr): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images_bgr, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + image_rgb = cv2.cvtColor(images_bgr[local], cv2.COLOR_BGR2RGB) + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop, crop_intrinsic, ray_offset = _prepare_crop( + image_rgb, + boxes[choice], + intrinsics[frame_index], + is_left=side == 0, + input_size=args.input_size, + crop_scale=args.crop_scale, + canonical_focal=args.canonical_focal, + generate_patch_image=generate_patch_image, + ) + queue.append( + ( + frame_index, + side, + float(scores[choice]), + crop, + crop_intrinsic, + ray_offset, + ) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"HandDGP detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + handmesh_commit = subprocess.check_output( + [ + "git", + "-C", + str((args.repo / "third_party" / "HandMesh").resolve()), + "rev-parse", + "HEAD", + ], + text=True, + ).strip() + # Decoder upsampling matrices are fixed and repeated along the configured + # batch dimension. Count one copy so the reported model size is invariant + # to inference batch size. + reconstruction_parameters = sum( + parameter[0].numel() + if name.startswith("decoder3d.up_transform.") + else parameter.numel() + for name, parameter in model.named_parameters() + ) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/nianticlabs/HandDGP", + "repository_commit": commit, + "handmesh_repository_commit": handmesh_commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector boxes, per-hand crops", + "training_exposure": "released checkpoint trained only on FreiHAND; no H2O or H2O3D", + "fine_tuning": "not available: official repository contains inference/evaluation only", + "confidence_threshold": args.confidence_threshold, + "crop_scale": args.crop_scale, + "input_size": args.input_size, + "canonical_focal": args.canonical_focal, + "preprocessing": ( + "official square crop and canonical-intrinsics rectification; " + "left hands reflected before the right-hand model and mapped back in camera x" + ), + "camera_policy": ( + "official DGP in a box-centered virtual crop camera; known H2O K " + "maps the crop ray back to raw cam4" + ), + "joint_conversion": "official MPII output already matches H2O/OpenPose convention", + "hand_scale_m": 0.2, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="HandDGP-FreiHAND-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_hawor_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_hawor_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..d65afad091f550bdebc7783b6a1acebccb125a46 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_hawor_h2o.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Run HaWoR's official tracked camera-space hand stage on H2O validation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-left", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--confidence-threshold", type=float, default=0.2) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def contiguous_runs(takes: np.ndarray, frame_ids: np.ndarray) -> list[np.ndarray]: + starts = [0] + for index in range(1, len(frame_ids)): + if takes[index] != takes[index - 1] or frame_ids[index] != frame_ids[index - 1] + 1: + starts.append(index) + starts.append(len(frame_ids)) + return [np.arange(starts[i], starts[i + 1]) for i in range(len(starts) - 1)] + + +def main() -> None: + args = parse_args() + for name in ( + "repo", "checkpoint", "detector", "mano_left", "mano_right", "root", + "manifest", "ground_truth", "output", + ): + setattr(args, name, Path(getattr(args, name)).resolve()) + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + targets = ( + (args.repo / "_DATA" / "data" / "mano" / "MANO_RIGHT.pkl", args.mano_right), + (args.repo / "_DATA" / "data_left" / "mano_left" / "MANO_LEFT.pkl", args.mano_left), + ) + for target, source in targets: + if not target.exists(): + target.symlink_to(source) + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from ultralytics import YOLO + from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + from hawor.utils.process import run_mano, run_mano_left + from hawor.configs import get_config + from hawor.utils.rotation import rotation_matrix_to_angle_axis + from lib.models.hawor import HAWOR + + from foundation_hand.evaluation.sota import GroundTruthBundle + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + all_runs = contiguous_runs(takes, frame_ids) + selected_runs = [ + run for index, run in enumerate(all_runs) + if index % args.num_shards == args.shard_index + ] + selected_mask = np.zeros(count, dtype=bool) + for run in selected_runs: + selected_mask[run] = True + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + enable_legacy_mano_loading() + model_config = args.checkpoint.parent.parent / "model_config.yaml" + config = get_config(str(model_config), update_cachedir=True) + if config.MODEL.BACKBONE.TYPE == "vit" and "BBOX_SHAPE" not in config.MODEL: + config.defrost() + config.MODEL.BBOX_SHAPE = [192, 256] + config.freeze() + model = HAWOR.load_from_checkpoint( + str(args.checkpoint), + strict=False, + cfg=config, + map_location=device, + weights_only=False, + ) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + boxes = np.full((count, 2, 4), np.nan, dtype=np.float32) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for run_number, run_indices in enumerate(selected_runs, start=1): + if getattr(detector, "predictor", None) is not None: + for tracker in getattr(detector.predictor, "trackers", []): + if hasattr(tracker, "reset"): + tracker.reset() + image_paths = [ + args.root / str(takes[index]) / "rgb" / f"{int(frame_ids[index]):06d}.png" + for index in run_indices + ] + for local, image_path in enumerate(image_paths): + image = cv2.imread(str(image_path)) + if image is None: + raise RuntimeError(f"Image decode failure: {image_path}") + with torch.no_grad(): + result = detector.track( + image, + conf=args.confidence_threshold, + persist=True, + verbose=False, + )[0] + result_boxes = result.boxes.xyxy.float().cpu().numpy() + result_classes = result.boxes.cls.long().cpu().numpy() + result_scores = result.boxes.conf.float().cpu().numpy() + frame_index = int(run_indices[local]) + for side in (0, 1): + choices = np.flatnonzero(result_classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(result_scores[choices])]) + boxes[frame_index, side] = result_boxes[choice] + confidence[frame_index, side] = result_scores[choice] + + for side in (0, 1): + available = run_indices[np.isfinite(boxes[run_indices, side]).all(axis=1)] + # The released video pipeline requires two detections, then linearly + # interpolates missing boxes between the first and last detection. + if available.size < 2: + continue + segment = np.arange(int(available[0]), int(available[-1]) + 1) + for coordinate in range(4): + boxes[segment, side, coordinate] = np.interp( + frame_ids[segment], + frame_ids[available], + boxes[available, side, coordinate], + ) + segment_paths = np.asarray([ + str(args.root / str(takes[index]) / "rgb" / f"{int(frame_ids[index]):06d}.png") + for index in segment + ]) + K = intrinsics[int(segment[0])] + focal = float(0.5 * (K[0, 0] + K[1, 1])) + center = np.asarray([K[0, 2], K[1, 2]], dtype=np.float32) + results = model.inference( + segment_paths, + boxes[segment, side], + img_focal=focal, + img_center=center, + device=str(device), + do_flip=(side == 0), + ) + root_rotation = rotation_matrix_to_angle_axis( + results["pred_rotmat"][None, :, 0] + ) + hand_pose = rotation_matrix_to_angle_axis( + results["pred_rotmat"][None, :, 1:] + ) + if side == 0: + root_rotation[..., 1:] *= -1 + hand_pose[..., 1:] *= -1 + # Keep the exact official left/right MANO conversion after canonical + # left-hand input flipping. + if side == 0: + mano_output = run_mano_left( + results["pred_trans"][None, :, 0], + root_rotation, + hand_pose, + betas=results["pred_shape"][None], + ) + else: + mano_output = run_mano( + results["pred_trans"][None, :, 0], + root_rotation, + hand_pose, + betas=results["pred_shape"][None], + ) + joints[segment, side] = mano_output["joints"][0].float().cpu().numpy() + vertices[segment, side] = mano_output["vertices"][0].float().cpu().numpy() + detected[segment, side] = True + print( + f"HaWoR run {run_number}: frames through {int(run_indices[-1]) + 1}/{count}", + flush=True, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + selected_frames = int(selected_mask.sum()) + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "HaWoR", + "scope": "RGB decode + tracked detector + bbox interpolation + temporal reconstruction + MANO conversion", + "frames": selected_frames, + "detected_hand_frames": int(detected[selected_mask].sum()), + "processing_seconds": processing_seconds, + "frames_per_second": selected_frames / processing_seconds, + "temporal_window": 16, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + keys = keys[selected_mask] + takes = takes[selected_mask] + frame_ids = frame_ids[selected_mask] + joints = joints[selected_mask] + vertices = vertices[selected_mask] + detected = detected[selected_mask] + confidence = confidence[selected_mask] + bundle = PredictionBundle( + model_name="HaWoR-camera", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata={ + "official_repository": "https://github.com/ThunderVVV/HaWoR", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "tracked per-hand RGB crops in contiguous 16-frame windows", + "confidence_threshold": args.confidence_threshold, + "temporal": True, + "temporal_window": 16, + "side_assignment": "official tracked detector handedness; highest confidence per side/frame", + "bbox_gap_policy": "official linear interpolation between first/last per-run detections", + "camera_conversion": "official get_trans with H2O fx/fy mean and principal point", + "excluded_for_camera_metrics": ["DROID-SLAM", "Metric3D", "world-space infiller"], + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_pad_hand_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_pad_hand_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb890442b99e6018c5aa3ca6ca6c2cc4d695ed5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_pad_hand_h2o.py @@ -0,0 +1,501 @@ +#!/usr/bin/env python3 +"""Run the released PAD-Hand WiLoR refinement pipeline on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import types +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + load_frame_index, +) +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +MANO_TO_OPENPOSE = np.asarray( + [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20], + dtype=np.int64, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def install_torch_scatter_compat() -> None: + """Provide the single torch-scatter operation used by the released model.""" + + if "torch_scatter" in sys.modules: + return + + def scatter_add( + source: torch.Tensor, + index: torch.Tensor, + dim: int = -1, + out: torch.Tensor | None = None, + dim_size: int | None = None, + ) -> torch.Tensor: + if out is None: + output_shape = list(source.shape) + output_shape[dim] = ( + dim_size if dim_size is not None else int(index.max().item()) + 1 + ) + out = source.new_zeros(output_shape) + index_shape = [1] * source.ndim + index_shape[dim] = index.numel() + expanded_index = index.reshape(index_shape).expand_as(source) + return out.scatter_add_(dim, expanded_index, source) + + module = types.ModuleType("torch_scatter") + module.scatter_add = scatter_add + sys.modules["torch_scatter"] = module + + +def enable_legacy_checkpoint_loading() -> None: + """Restore the pre-PyTorch-2.6 default for trusted official checkpoints.""" + + original_load = torch.load + + def load(*args: Any, **kwargs: Any) -> Any: + kwargs.setdefault("weights_only", False) + return original_load(*args, **kwargs) + + torch.load = load + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--pad-repo", type=Path, required=True) + parser.add_argument("--wilor-repo", type=Path, required=True) + parser.add_argument("--pad-checkpoint", type=Path, required=True) + parser.add_argument("--wilor-checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument("--diffusion-steps", type=int, default=4) + parser.add_argument("--kappa-degrees", type=float, default=15.0) + parser.add_argument("--seed", type=int, default=20260720) + parser.add_argument("--max-takes", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def stable_window_seed(base_seed: int, take: str, side: int, frame_id: int) -> int: + payload = f"{base_seed}|{take}|{side}|{frame_id}".encode("utf-8") + return int.from_bytes(hashlib.sha256(payload).digest()[:8], "little") % (2**31) + + +def contiguous_runs(frame_ids: np.ndarray) -> list[np.ndarray]: + if frame_ids.size == 0: + return [] + boundaries = np.flatnonzero(np.diff(frame_ids) != 1) + 1 + return [part for part in np.split(np.arange(frame_ids.size), boundaries) if part.size] + + +def main() -> None: + args = parse_args() + for name in ( + "pad_repo", + "wilor_repo", + "pad_checkpoint", + "wilor_checkpoint", + "detector", + "mano_right", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + if args.diffusion_steps <= 0: + raise ValueError("--diffusion-steps must be positive") + + required_pad_assets = ( + "processed_MANO_RIGHT.pkl", + "MeshConv_template.ply", + "MeshConv_transform.pkl", + ) + for filename in required_pad_assets: + asset = args.pad_repo / "assets" / filename + if not asset.is_file(): + raise FileNotFoundError(f"Missing released PAD-Hand asset: {asset}") + wilor_mano = args.wilor_repo / "mano_data" / "MANO_RIGHT.pkl" + if not wilor_mano.exists(): + wilor_mano.symlink_to(args.mano_right) + + keys, takes, frame_ids = load_frame_index(args.manifest) + unique_takes = list(dict.fromkeys(map(str, takes.tolist()))) + if args.max_takes is not None: + unique_takes = unique_takes[: args.max_takes] + selected_takes = { + take + for index, take in enumerate(unique_takes) + if index % args.num_shards == args.shard_index + } + selected = np.asarray([str(take) in selected_takes for take in takes], dtype=bool) + keys, takes, frame_ids = keys[selected], takes[selected], frame_ids[selected] + if not len(keys): + raise ValueError("Shard contains no frames") + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + enable_legacy_mano_loading() + enable_legacy_checkpoint_loading() + sys.path.insert(0, str(args.wilor_repo)) + os.chdir(args.wilor_repo) + from ultralytics import YOLO + from wilor.datasets.vitdet_dataset import ViTDetDataset + from wilor.models import load_wilor + + wilor_model, wilor_cfg = load_wilor( + checkpoint_path=str(args.wilor_checkpoint), + cfg_path=str(args.wilor_repo / "pretrained_models" / "model_config.yaml"), + ) + wilor_model = wilor_model.to(device).eval() + detector = YOLO(str(args.detector)).to(device) + + count = len(keys) + relative_joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + relative_vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + cameras = np.full((count, 2, 3), np.nan, dtype=np.float32) + global_orient = np.full((count, 2, 1, 3, 3), np.nan, dtype=np.float32) + hand_pose = np.full((count, 2, 15, 3, 3), np.nan, dtype=np.float32) + betas = np.full((count, 2, 10), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = wilor_model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + record_indices = np.asarray([record[0] for record in records]) + K = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (K[:, 0, 0] + K[:, 1, 1]) + principal = K[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + camera = torch.stack( + ( + pred_cam[:, 1] + + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), + dim=-1, + ).float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + batch_global = ( + output["pred_mano_params"]["global_orient"].float().cpu().numpy() + ) + batch_pose = output["pred_mano_params"]["hand_pose"].float().cpu().numpy() + batch_betas = output["pred_mano_params"]["betas"].float().cpu().numpy() + for local, (frame_index, side, score, _) in enumerate(records): + relative_joints[frame_index, side] = batch_joints[local] + relative_vertices[frame_index, side] = batch_vertices[local] + cameras[frame_index, side] = camera[local] + global_orient[frame_index, side] = batch_global[local] + hand_pose[frame_index, side] = batch_pose[local] + betas[frame_index, side] = batch_betas[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop_dataset = ViTDetDataset( + wilor_cfg, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), crop_dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"PAD-Hand WiLoR initialization {end}/{count}", flush=True) + flush_queue(force=True) + + install_torch_scatter_compat() + sys.path.insert(0, str(args.pad_repo)) + os.chdir(args.pad_repo) + from models.MANO import MANO + from models.difussionsampler import DiffusionSampler + from models.pad_hand import PAD_Hand + from models.utils import batch_euler2matzxy, rotmat2eulerzxy + + pad_model = PAD_Hand( + device=device, + seqlen=16, + decoder=True, + d_model=512, + nhead=8, + d_hid=512, + nlayers=4, + dropout=0.1, + ).to(device) + checkpoint = torch.load(args.pad_checkpoint, map_location=device, weights_only=False) + pad_model.load_state_dict(checkpoint["model"]) + pad_model.eval() + pad_model.mode = "test" + mano = MANO("RIGHT", device) + sampler = DiffusionSampler( + args.diffusion_steps, np.deg2rad(args.kappa_degrees), device + ) + + refined_joints = relative_joints.copy() + refined_vertices = relative_vertices.copy() + refined_windows = 0 + missing_detection_windows = 0 + tail_frames = 0 + initializer_mesh_delta_sum = 0.0 + initializer_mesh_delta_count = 0 + + for take in dict.fromkeys(map(str, takes.tolist())): + take_indices = np.flatnonzero(takes == take) + order = np.argsort(frame_ids[take_indices]) + take_indices = take_indices[order] + take_frame_ids = frame_ids[take_indices] + for run_positions in contiguous_runs(take_frame_ids): + run_indices = take_indices[run_positions] + tail_frames += len(run_indices) % 16 * 2 + for side in (0, 1): + for window_start in range(0, len(run_indices) - 15, 16): + window = run_indices[window_start : window_start + 16] + if not detected[window, side].all(): + missing_detection_windows += 1 + continue + rotmats = np.concatenate( + (global_orient[window, side], hand_pose[window, side]), axis=1 + ) + rotmats_t = torch.from_numpy(rotmats).to(device) + betas_t = torch.from_numpy(betas[window, side]).to(device) + y0_pose = rotmat2eulerzxy(rotmats_t.reshape(-1, 3, 3)).reshape( + 1, 16, 48 + ) + y0_shape = betas_t.unsqueeze(0) + y0_shape_t = y0_shape.reshape(-1, 10) + y0_rotmat = batch_euler2matzxy(y0_pose.reshape(-1, 3))[0].reshape( + -1, 16, 3, 3 + ) + y0_mano = mano.forward(betas=y0_shape_t, thetas_rotmat=y0_rotmat) + y0_vertices = y0_mano.vertices + comparison_vertices = y0_vertices.detach().cpu().numpy().copy() + if side == 0: + comparison_vertices[..., 0] *= -1 + initializer_mesh_delta_sum += float( + np.linalg.norm( + comparison_vertices - relative_vertices[window, side], axis=-1 + ).sum() + ) + initializer_mesh_delta_count += comparison_vertices.shape[0] * 778 + + src_mask = torch.ones((1, 16), dtype=torch.bool, device=device) + x0_pose_pred = y0_pose.clone() + window_seed = stable_window_seed( + args.seed, take, side, int(frame_ids[window[0]]) + ) + torch.manual_seed(window_seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(window_seed) + with torch.no_grad(): + for step in range(args.diffusion_steps, 0, -1): + if step == args.diffusion_steps: + step_batch = torch.full( + (1,), float(args.diffusion_steps), device=device + ) + noisy_pose = y0_pose + np.deg2rad( + args.kappa_degrees + ) * torch.randn_like(y0_pose) + else: + step_batch = torch.full( + (1,), step, device=device, dtype=torch.long + ) + noisy_pose = sampler.q_sample( + x0_pose_pred, y0_pose - x0_pose_pred, step_batch + ) + noisy_rotmat = batch_euler2matzxy( + noisy_pose.reshape(-1, 3) + )[0].reshape(-1, 16, 3, 3) + noisy_mano = mano.forward( + betas=y0_shape_t, thetas_rotmat=noisy_rotmat + ) + _, decoder_prediction = pad_model.forward( + y0_vertices.reshape(1, 16, 778, 3), + noisy_mano.vertices.reshape(1, 16, 778, 3), + step_batch.float(), + src_mask, + mano, + y0_shape_t, + ) + refined_rotmat = decoder_prediction[-2] + refined_mano = decoder_prediction[-1] + x0_pose_pred = rotmat2eulerzxy( + refined_rotmat.reshape(-1, 3, 3) + ).reshape(1, 16, 48) + vertices_out = refined_mano.vertices.detach().cpu().numpy() + joints_out = refined_mano.joints.detach().cpu().numpy()[ + :, MANO_TO_OPENPOSE + ] + if side == 0: + vertices_out[..., 0] *= -1 + joints_out[..., 0] *= -1 + refined_vertices[window, side] = vertices_out + refined_joints[window, side] = joints_out + refined_windows += 1 + + joints_camera = refined_joints + cameras[:, :, None] + vertices_camera = refined_vertices + cameras[:, :, None] + pad_commit = subprocess.check_output( + ["git", "-C", str(args.pad_repo), "rev-parse", "HEAD"], text=True + ).strip() + wilor_commit = subprocess.check_output( + ["git", "-C", str(args.wilor_repo), "rev-parse", "HEAD"], text=True + ).strip() + wilor_parameters = sum(parameter.numel() for parameter in wilor_model.parameters()) + detector_parameters = sum( + parameter.numel() for parameter in detector.model.parameters() + ) + pad_parameters = sum(parameter.numel() for parameter in pad_model.parameters()) + metadata = { + "official_repository": "https://github.com/DominoAI-Lab/PAD-Hand-CVPR-2026", + "repository_commit": pad_commit, + "base_wilor_repository_commit": wilor_commit, + "checkpoint": str(args.pad_checkpoint), + "checkpoint_sha256": sha256(args.pad_checkpoint), + "base_wilor_checkpoint": str(args.wilor_checkpoint), + "base_wilor_checkpoint_sha256": sha256(args.wilor_checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "pad_parameter_count": pad_parameters, + "reconstruction_parameter_count": wilor_parameters + pad_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": ( + wilor_parameters + pad_parameters + detector_parameters + ), + "input": ( + "full RGB detector, per-detection RGB crop WiLoR initialization, " + "per-side non-overlapping 16-frame PAD-Hand diffusion refinement" + ), + "temporal": True, + "temporal_window": 16, + "diffusion_steps": args.diffusion_steps, + "kappa_degrees": args.kappa_degrees, + "sampling_seed": args.seed, + "sampling_seed_policy": "SHA256(base seed, take, side, first frame)", + "refined_windows": refined_windows, + "missing_detection_windows": missing_detection_windows, + "tail_hand_frames_falling_back_to_wilor": tail_frames, + "initializer_mesh_reconstruction_delta_mm": ( + 1000.0 * initializer_mesh_delta_sum / initializer_mesh_delta_count + if initializer_mesh_delta_count + else None + ), + "camera_policy": "h2o_intrinsics", + "camera_conversion": ( + "WiLoR cam_crop_to_full algebra with known H2O focal/principal point; " + "PAD-Hand does not update camera translation" + ), + "side_assignment": "official WiLoR detector handedness; independent PAD-Hand refinement", + "training_exposure": ( + "paper trains on DexYCB/HO3D; released checkpoint does not label its " + "training split; no H2O fine-tuning" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="PAD-Hand-WiLoR-H2O-K", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints_camera, + vertices_camera_m=vertices_camera, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase3_full_validation.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase3_full_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..fd398945a306fb8176703ee7bb83eb8f92f6d408 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase3_full_validation.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python3 +"""Evaluate every registered Phase 3 core checkpoint on official validation.""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import queue +import shlex +import subprocess +import threading +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +VAL_MANIFEST = Path("artifacts/phase2/data_audit/manifests/official_val.jsonl") + + +@dataclass(frozen=True) +class EvaluationJob: + name: str + run_name: str + role: str + config: Path + checkpoint: Path + output: Path + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + output = {} + for line in result.stdout.splitlines(): + index, uuid = (part.strip() for part in line.split(",", 1)) + output[int(index)] = uuid + return output + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if not line.strip(): + continue + uuid, pid = (part.strip() for part in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +DEFAULT_CHECKPOINT_FILES = { + "step_025k": "step_0025000.pt", + "step_050k": "step_0050000.pt", + "step_075k": "step_0075000.pt", + "step_100k": "step_0100000.pt", + "best_absolute": "best.pt", + "best_z": "best_z.pt", + "final": "step_0100000_final.pt", +} + + +def checkpoint_roles( + run_dir: Path, checkpoint_files: dict[str, str] | None = None, +) -> tuple[tuple[str, Path], ...]: + definitions = DEFAULT_CHECKPOINT_FILES if checkpoint_files is None else checkpoint_files + return tuple((role, run_dir / filename) for role, filename in definitions.items()) + + +def load_checkpoint_files(path: Path | None) -> dict[str, str]: + if path is None: + return dict(DEFAULT_CHECKPOINT_FILES) + values = json.loads(path.read_text(encoding="utf-8")) + if ( + not isinstance(values, dict) + or not values + or any(not isinstance(role, str) or not role for role in values) + or any( + not isinstance(filename, str) or Path(filename).name != filename + for filename in values.values() + ) + ): + raise ValueError("checkpoint spec must be a non-empty role-to-filename JSON object") + return values + + +def validation_state_path(output_root: Path, filename: str) -> Path: + if Path(filename).name != filename or not filename.endswith(".json"): + raise ValueError("state filename must be a JSON basename") + return output_root / filename + + +def build_jobs( + matrix_csv: Path, + run_root: Path, + output_root: Path, + roles: tuple[str, ...] | None = None, + checkpoint_files: dict[str, str] | None = None, +) -> list[EvaluationJob]: + available_roles = checkpoint_roles(Path("unused"), checkpoint_files) + selected_roles = set(roles or (role for role, _ in available_roles)) + with matrix_csv.open(newline="", encoding="utf-8") as handle: + matrix_rows = list(csv.DictReader(handle)) + jobs = [] + for row in matrix_rows: + config = Path(row["config"]) + run_name = row.get("run_name") or config.stem + for role, checkpoint in checkpoint_roles(run_root / run_name, checkpoint_files): + if role not in selected_roles: + continue + jobs.append(EvaluationJob( + name=f"{run_name}__{role}", run_name=run_name, role=role, + config=config, checkpoint=checkpoint, + output=output_root / run_name / role, + )) + return jobs + + +def validate_job_grid(jobs: list[EvaluationJob], roles: tuple[str, ...]) -> int: + """Validate one evaluation per run and selected checkpoint role.""" + if not jobs: + raise ValueError("evaluation matrix produced no jobs") + selected_roles = set(roles) + run_names = {job.run_name for job in jobs} + job_keys = {(job.run_name, job.role) for job in jobs} + expected_jobs = len(run_names) * len(selected_roles) + if len(job_keys) != len(jobs): + raise ValueError("evaluation matrix contains duplicate run/checkpoint-role jobs") + if len(jobs) != expected_jobs: + raise ValueError( + f"expected {len(run_names)} runs x {len(selected_roles)} checkpoint roles " + f"= {expected_jobs} jobs, got {len(jobs)}" + ) + return len(run_names) + + +def command_for( + job: EvaluationJob, gpu: int, num_workers: int, + drop_depth: bool = False, drop_k: bool = False, + phase4_diagnostics: bool = False, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/evaluate_phase3.py", + "--config", str(job.config), + "--root", DATA_ROOT, + "--manifest", str(VAL_MANIFEST), + "--checkpoint", str(job.checkpoint), + "--output-dir", str(job.output), + "--gpu", "0", + "--num-workers", str(num_workers), + "--bootstrap-samples", "10000", + "--skip-visualizations", + ] + if drop_depth: + command.append("--drop-depth") + if drop_k: + command.append("--drop-k") + if phase4_diagnostics: + command.append("--phase4-diagnostics") + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def completed_evaluation(path: Path, job: EvaluationJob) -> bool: + report_path = path / "evaluation.json" + if not report_path.is_file(): + return False + try: + report = json.loads(report_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return False + return ( + report.get("status") == "evaluated" + and report.get("official_test_used") is False + and Path(report.get("checkpoint", {}).get("path", "")).resolve() == job.checkpoint.resolve() + and report.get("clips") == 1495 + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + parser.add_argument("--run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--output-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--gpus", default="0,1,2,3,5") + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument("--roles") + parser.add_argument("--checkpoint-spec", type=Path) + parser.add_argument("--drop-depth", action="store_true") + parser.add_argument("--drop-k", action="store_true") + parser.add_argument("--phase4-diagnostics", action="store_true") + parser.add_argument("--state-filename", default="validation_state.json") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + if VAL_MANIFEST.name != "official_val.jsonl": + parser.error("full validation launcher is hard-gated to official_val.jsonl") + if args.num_workers < 0: + parser.error("--num-workers must be non-negative") + try: + state_path = validation_state_path(args.output_root, args.state_filename) + except ValueError as error: + parser.error(str(error)) + + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + known_gpus = gpu_uuid_map() + unknown = sorted(set(gpus) - set(known_gpus)) + if unknown: + parser.error(f"unknown GPU indices: {unknown}") + + try: + checkpoint_files = load_checkpoint_files(args.checkpoint_spec) + except (OSError, json.JSONDecodeError, ValueError) as error: + parser.error(str(error)) + known_roles = tuple(checkpoint_files) + roles = ( + known_roles if args.roles is None + else tuple(value.strip() for value in args.roles.split(",") if value.strip()) + ) + unknown_roles = sorted(set(roles) - set(known_roles)) + if not roles or unknown_roles: + parser.error(f"invalid --roles; selected={roles}, unknown={unknown_roles}") + jobs = build_jobs( + args.matrix_csv, args.run_root, args.output_root, roles, checkpoint_files, + ) + try: + run_count = validate_job_grid(jobs, roles) + except ValueError as error: + parser.error(str(error)) + missing_configs = sorted({str(job.config) for job in jobs if not job.config.is_file()}) + missing_checkpoints = sorted({str(job.checkpoint) for job in jobs if not job.checkpoint.is_file()}) + if missing_configs or missing_checkpoints: + parser.error(json.dumps({ + "missing_configs": missing_configs, + "missing_checkpoints": missing_checkpoints, + }, indent=2)) + if args.dry_run: + print(json.dumps({ + "runs": run_count, "jobs": len(jobs), "gpus": gpus, "roles": roles, + "official_test_used": False, + "first_command": shlex.join(command_for( + jobs[0], gpus[0], args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + )[0]), + "last_command": shlex.join(command_for( + jobs[-1], gpus[-1], args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + )[0]), + "drop_depth": args.drop_depth, "drop_k": args.drop_k, + "phase4_diagnostics": args.phase4_diagnostics, + "state_file": str(state_path), + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + work: queue.Queue[EvaluationJob] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "manifest": str(VAL_MANIFEST), + "roles": roles, "official_test_used": False, "jobs": {}, + "checkpoint_spec": str(args.checkpoint_spec) if args.checkpoint_spec else None, + "drop_depth": args.drop_depth, "drop_k": args.drop_k, + "phase4_diagnostics": args.phase4_diagnostics, + "state_file": str(state_path), + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for job in jobs: + if completed_evaluation(job.output, job): + state["jobs"][job.name] = { + "status": "skipped_completed", "output": str(job.output), + "checkpoint": str(job.checkpoint), "role": job.role, + } + continue + if job.output.exists() and any(job.output.iterdir()): + state["jobs"][job.name] = { + "status": "blocked_existing_incomplete", "output": str(job.output), + "checkpoint": str(job.checkpoint), "role": job.role, + } + stop_launching.set() + continue + work.put(job) + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + job = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for( + job, gpu, args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + ) + log_path = log_root / f"{job.name}.log" + with state_lock: + state["jobs"][job.name] = { + "status": "running", "run": job.run_name, "role": job.role, + "config": str(job.config), "checkpoint": str(job.checkpoint), + "gpu": gpu, "gpu_uuid": gpu_uuid, "started_utc": utc_now(), + "output": str(job.output), "log": str(log_path), + "command": shlex.join(command), + } + persist() + job.output.mkdir(parents=True, exist_ok=False) + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][job.name]["pid"] = process.pid + persist() + return_code = process.wait() + valid_output = completed_evaluation(job.output, job) + with state_lock: + state["jobs"][job.name].update({ + "status": "completed" if return_code == 0 and valid_output else "failed", + "return_code": return_code, "output_validated": valid_output, + "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0 or not valid_output: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,), name=f"gpu-{gpu}") for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [ + name for name, record in state["jobs"].items() + if record["status"] in {"failed", "blocked_existing_incomplete"} + ] + state["status"] = "failed" if failed else "completed" + state["finished_utc"] = utc_now() + state["failed_jobs"] = failed + state["remaining_queue"] = work.qsize() + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase3_matrix.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase3_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..9e84d3da6831ce5604a00315099bb13709db6c57 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase3_matrix.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Run a pre-registered Phase 3 config queue on explicitly allowed idle GPUs.""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import queue +import shlex +import subprocess +import threading +import time +from datetime import datetime, timezone +from pathlib import Path + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +TRAIN_MANIFEST = "artifacts/phase2/data_audit/manifests/official_train.jsonl" +VAL_MANIFEST = "artifacts/phase2/data_audit/manifests/official_val.jsonl" +VAL_SUBSET = "artifacts/phase3/validation_subset/validation_subset_256.json" + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + output = {} + for line in result.stdout.splitlines(): + index, uuid = (part.strip() for part in line.split(",", 1)) + output[int(index)] = uuid + return output + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if not line.strip(): + continue + uuid, pid = (part.strip() for part in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +def command_for( + config: Path, + output_dir: Path, + gpu: int, + resume: Path | None = None, + validation_subset: Path | str = VAL_SUBSET, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/train_experiment.py", + "--config", str(config), + "--root", DATA_ROOT, + "--manifest", TRAIN_MANIFEST, + "--val-manifest", VAL_MANIFEST, + "--validation-subset-manifest", str(validation_subset), + "--output-dir", str(output_dir), + "--max-steps", "100000", + "--num-workers", "4", + "--checkpoint-interval", "25000", + "--validation-interval", "5000", + "--validation-batches", "256", + "--learning-rate", "5e-5", + "--min-learning-rate", "5e-6", + "--warmup-steps", "500", + "--early-stopping-patience", "0", + ] + if resume is not None: + command.extend(("--resume", str(resume))) + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + parser.add_argument("--output-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--gpus", default="0,1,2,3,5") + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--resume-root", type=Path) + parser.add_argument("--resume-step", type=int, default=75_000) + parser.add_argument( + "--validation-subset-manifest", type=Path, default=Path(VAL_SUBSET), + ) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + known_gpus = gpu_uuid_map() + unknown = sorted(set(gpus) - set(known_gpus)) + if unknown: + parser.error(f"unknown GPU indices: {unknown}") + + with args.matrix_csv.open(newline="", encoding="utf-8") as handle: + configs = [Path(row["config"]) for row in csv.DictReader(handle)] + missing = [str(path) for path in configs if not path.is_file()] + if missing: + parser.error(f"missing configs: {missing}") + jobs = [ + ( + config, + args.output_root / config.stem, + ( + args.resume_root / config.stem / f"step_{args.resume_step:07d}.pt" + if args.resume_root is not None else None + ), + ) + for config in configs + ] + missing_resume = [str(resume) for _, _, resume in jobs if resume and not resume.is_file()] + if missing_resume: + parser.error(f"missing resume checkpoints: {missing_resume}") + if args.dry_run: + print(json.dumps({ + "jobs": len(jobs), "gpus": gpus, + "commands": [ + shlex.join(command_for( + config, output, gpus[index % len(gpus)], resume, + args.validation_subset_manifest, + )[0]) + for index, (config, output, resume) in enumerate(jobs) + ], + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + state_path = args.output_root / "matrix_state.json" + work: queue.Queue[tuple[Path, Path, Path | None]] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "jobs": {}, + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for config, output, resume in jobs: + summary = output / "summary.json" + if summary.is_file() and json.loads(summary.read_text(encoding="utf-8")).get("status") == "completed": + state["jobs"][config.stem] = {"status": "skipped_completed", "output": str(output)} + continue + if output.exists() and any(output.iterdir()): + state["jobs"][config.stem] = { + "status": "blocked_existing_incomplete", "output": str(output), + } + stop_launching.set() + continue + work.put((config, output, resume)) + + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + config, output, resume = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for( + config, output, gpu, resume, args.validation_subset_manifest, + ) + log_path = log_root / f"{config.stem}.log" + with state_lock: + state["jobs"][config.stem] = { + "status": "running", "gpu": gpu, "gpu_uuid": gpu_uuid, + "started_utc": utc_now(), "output": str(output), + "log": str(log_path), "command": shlex.join(command), + "resume_checkpoint": str(resume) if resume is not None else None, + } + persist() + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][config.stem]["pid"] = process.pid + persist() + return_code = process.wait() + with state_lock: + state["jobs"][config.stem].update({ + "status": "completed" if return_code == 0 else "failed", + "return_code": return_code, "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,), name=f"gpu-{gpu}") for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [name for name, record in state["jobs"].items() if record["status"] in {"failed", "blocked_existing_incomplete"}] + state["status"] = "failed" if failed else "completed" + state["finished_utc"] = utc_now() + state["failed_jobs"] = failed + state["remaining_queue"] = work.qsize() + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase4_a3_matrix.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase4_a3_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..277b30257fd62aa997b6837b566ef7af2b34fe65 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase4_a3_matrix.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Run the preregistered Phase 4 A3 formal matrix on explicitly allowed GPUs.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import queue +import shlex +import subprocess +import threading +from datetime import datetime, timezone +from pathlib import Path + +import yaml + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +TRAIN_MANIFEST = "artifacts/phase2/data_audit/manifests/official_train.jsonl" +VAL_MANIFEST = "artifacts/phase2/data_audit/manifests/official_val.jsonl" +VAL_SUBSET = ( + "artifacts/phase3/validation_subset/resolution_640x368/" + "validation_subset_256.json" +) +EXPECTED_SEEDS = {20260716, 20260717, 20260718} +MODE_SLUGS = { + "oracle_rgb": "rgb", + "oracle_depth_k": "depth_k", + "oracle_rgb_depth_k": "rgb_depth_k", +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + return { + int(index.strip()): uuid.strip() + for line in result.stdout.splitlines() + for index, uuid in [line.split(",", 1)] + } + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + [ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid", + "--format=csv,noheader,nounits", + ], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if line.strip(): + uuid, pid = (value.strip() for value in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +def load_jobs( + matrix_csv: Path, + config_root: Path, + output_root: Path, +) -> list[dict[str, object]]: + with matrix_csv.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + observed = {(int(row["seed"]), row["mode"]) for row in rows} + expected = {(seed, mode) for seed in EXPECTED_SEEDS for mode in MODE_SLUGS} + if len(rows) != 9 or observed != expected: + raise ValueError("A3 formal matrix must contain exactly three modes x three seeds") + + jobs = [] + for row in rows: + seed = int(row["seed"]) + mode = row["mode"] + if row["stage"] != "formal" or int(row["max_steps"]) != 100_000: + raise ValueError("A3 matrix contains a non-formal or non-100k row") + if row["gt_location"] != "True" or row["official_test_used"] != "False": + raise ValueError("A3 formal matrix violates oracle/test-isolation contract") + config = config_root / Path(row["config"]).name + checkpoint = Path(row["initialization_checkpoint"]) + if not config.is_file() or not checkpoint.is_file(): + raise FileNotFoundError(f"missing A3 config/checkpoint: {config}, {checkpoint}") + if file_sha256(checkpoint) != row["initialization_checkpoint_sha256"]: + raise ValueError(f"initialization checkpoint hash mismatch for seed {seed}") + config_record = yaml.safe_load(config.read_text(encoding="utf-8")) + experiment = config_record.get("experiment", {}) + if ( + int(config_record["seed"]) != seed + or config_record["name"] != row["name"] + or experiment.get("oracle_crop_mode") != mode + or experiment.get("coarse_checkpoint_sha256") + != row["initialization_checkpoint_sha256"] + ): + raise ValueError(f"matrix/config mismatch for {config}") + jobs.append({ + "name": row["name"], + "seed": seed, + "mode": mode, + "config": config, + "checkpoint": checkpoint, + "output": output_root / row["name"], + }) + return jobs + + +def command_for( + job: dict[str, object], gpu: int, validation_subset: Path, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/train_experiment.py", + "--config", str(job["config"]), + "--root", DATA_ROOT, + "--manifest", TRAIN_MANIFEST, + "--val-manifest", VAL_MANIFEST, + "--validation-subset-manifest", str(validation_subset), + "--output-dir", str(job["output"]), + "--max-steps", "100000", + "--num-workers", "4", + "--checkpoint-interval", "25000", + "--validation-interval", "5000", + "--validation-batches", "256", + "--learning-rate", "5e-5", + "--min-learning-rate", "5e-6", + "--lr-schedule-steps", "100000", + "--warmup-steps", "500", + "--early-stopping-patience", "0", + "--init-checkpoint", str(job["checkpoint"]), + ] + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, required=True) + parser.add_argument( + "--config-root", type=Path, default=Path("configs/phase4/a3_oracle_crop"), + ) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--gpus", default="0,1,2,3,4,5") + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--validation-subset-manifest", type=Path, default=Path(VAL_SUBSET), + ) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + if not gpus or len(gpus) != len(set(gpus)): + parser.error("--gpus must contain unique GPU indices") + known_gpus = gpu_uuid_map() + if set(gpus) - set(known_gpus): + parser.error("--gpus contains an unknown GPU index") + if not args.validation_subset_manifest.is_file(): + parser.error("fixed validation subset is missing") + jobs = load_jobs(args.matrix_csv, args.config_root, args.output_root) + if args.dry_run: + print(json.dumps({ + "status": "dry_run", "jobs": len(jobs), "gpus": gpus, + "commands": [ + shlex.join(command_for(job, gpus[index % len(gpus)], args.validation_subset_manifest)[0]) + for index, job in enumerate(jobs) + ], + "official_test_used": False, + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + state_path = args.output_root / "matrix_state.json" + work: queue.Queue[dict[str, object]] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "official_test_used": False, "jobs": {}, + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for job in jobs: + output = job["output"] + summary = output / "summary.json" + if summary.is_file() and json.loads(summary.read_text(encoding="utf-8")).get("status") == "completed": + state["jobs"][job["name"]] = { + "status": "skipped_completed", "output": str(output), + } + elif output.exists() and any(output.iterdir()): + state["jobs"][job["name"]] = { + "status": "blocked_existing_incomplete", "output": str(output), + } + stop_launching.set() + else: + work.put(job) + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + job = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for(job, gpu, args.validation_subset_manifest) + log_path = log_root / f"{job['name']}.log" + with state_lock: + state["jobs"][job["name"]] = { + "status": "running", "gpu": gpu, "gpu_uuid": gpu_uuid, + "started_utc": utc_now(), "output": str(job["output"]), + "log": str(log_path), "command": shlex.join(command), + } + persist() + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][job["name"]]["pid"] = process.pid + persist() + return_code = process.wait() + with state_lock: + state["jobs"][job["name"]].update({ + "status": "completed" if return_code == 0 else "failed", + "return_code": return_code, "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,)) for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [ + name for name, record in state["jobs"].items() + if record["status"] in {"failed", "blocked_existing_incomplete"} + ] + state.update({ + "status": "failed" if failed else "completed", + "finished_utc": utc_now(), "failed_jobs": failed, + "remaining_queue": work.qsize(), + }) + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_adaptation_eval_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_adaptation_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c94ba7f43f0ea64e794d451c852510a306db20e6 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_adaptation_eval_queue.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Evaluate H2O adaptation checkpoints on frozen train-heldout groups.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_split") != "h2o_train_group_heldout_only" + ): + raise ValueError("adaptation evaluation queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("adaptation evaluation queue is empty") + for item in queue["evaluations"]: + if Path(item["cache_manifest"]).name != "train_group_heldout.jsonl": + raise ValueError("adaptation evaluation must use train_group_heldout.jsonl") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_train_group_heldout" + and report.get("evaluation_role") == "h2o_train_group_heldout" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("h2o_training_data_used") is True + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item.get("input_mode", "rgb_d_k"), + "--evaluation-role", "h2o_train_group_heldout", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty adaptation evaluation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_adaptation_forgetting_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_adaptation_forgetting_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa5b7a46bc6f95f83b75eb328abef01a86875a1 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_adaptation_forgetting_queue.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Evaluate H2O-adapted checkpoints on frozen external held-out caches.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_use") is not False + or queue.get("evaluation_split") != "external_heldout_forgetting_diagnostic_only" + ): + raise ValueError("adaptation forgetting queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("adaptation forgetting queue is empty") + for item in queue["evaluations"]: + if "h2o" in str(item["cache_manifest"]).lower(): + raise ValueError("adaptation forgetting queue refuses H2O cache paths") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_adaptation_external_heldout" + and report.get("evaluation_role") == "adaptation_external_heldout" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("h2o_training_data_used") is True + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--evaluation-role", "adaptation_external_heldout", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "selection_use": False, "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty forgetting evaluation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_adaptation_train_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_adaptation_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff2769a01a27e87301e9a37028692b23f43a562 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_adaptation_train_queue.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 7 H2O adaptation stages on idle GPUs 0-3.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_train_queue import ( + atomic_json, + cache_report_ready, + idle_gpu, + sha256, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def stage_marker(item: dict[str, Any]) -> Path: + return Path(item["output_dir"]) / ".phase7_queue" / f"{item['id']}.json" + + +def completed_matches(item: dict[str, Any]) -> bool: + marker_path = stage_marker(item) + if not marker_path.is_file(): + return False + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and int(marker.get("completed_step", -1)) == int(item["stop_after_step"]) + and marker.get("config_sha256") == item["config_sha256"] + and marker.get("h2o_training_data_used") is True + and marker.get("h2o_official_validation_used") is False + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", item["config"], "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(item["stop_after_step"]), + ] + if item.get("resume_checkpoint") is not None: + command.extend(("--resume", item["resume_checkpoint"])) + elif item.get("resume_from_step") is not None: + resume = Path(item["output_dir"]) / f"step_{int(item['resume_from_step']):07d}_final.pt" + command.extend(("--resume", str(resume))) + elif not item.get("neutral_start", False): + command.extend(("--init-checkpoint", item["init_checkpoint"])) + return command + + +def validate_stage_inputs(item: dict[str, Any]) -> None: + config = Path(item["config"]) + if not config.is_file() or sha256(config) != item["config_sha256"]: + raise RuntimeError(f"frozen config missing or SHA mismatch: {config}") + output = Path(item["output_dir"]) + resume_checkpoint = item.get("resume_checkpoint") + resume_step = item.get("resume_from_step") + if resume_checkpoint is not None: + resume = Path(resume_checkpoint) + if ( + not resume.is_file() + or sha256(resume) != item.get("resume_checkpoint_sha256") + ): + raise RuntimeError(f"explicit resume checkpoint is missing or has a SHA mismatch: {resume}") + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"explicit-resume adaptation output is not empty: {output}") + elif resume_step is None and item.get("neutral_start", False): + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new neutral-control output is not empty: {output}") + elif resume_step is None: + initialization = Path(item["init_checkpoint"]) + if ( + not initialization.is_file() + or sha256(initialization) != item["init_checkpoint_sha256"] + ): + raise RuntimeError(f"frozen initialization missing or SHA mismatch: {initialization}") + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new adaptation output is not empty: {output}") + else: + resume = output / f"step_{int(resume_step):07d}_final.pt" + if not resume.is_file(): + raise RuntimeError(f"resume checkpoint is missing: {resume}") + + +def write_stage_marker(item: dict[str, Any], gpu: int) -> dict[str, Any]: + output = Path(item["output_dir"]) + summary = json.loads((output / "summary.json").read_text(encoding="utf-8")) + step = int(item["stop_after_step"]) + checkpoint = output / f"step_{step:07d}_final.pt" + if ( + int(summary.get("completed_step", -1)) != step + or summary.get("h2o_training_data_used") is not True + or summary.get("official_test_used") is not False + or not checkpoint.is_file() + ): + raise RuntimeError(f"adaptation summary failed stage contract: {item['id']}") + marker = { + "status": "complete", "id": item["id"], "completed_utc": utc_now(), + "completed_step": step, "physical_gpu_id": gpu, + "config": str(Path(item["config"]).resolve()), + "config_sha256": item["config_sha256"], + "checkpoint": str(checkpoint.resolve()), "checkpoint_sha256": sha256(checkpoint), + "wall_seconds": summary.get("wall_seconds"), + "gpu_hours": summary.get("gpu_hours"), + "frames_per_second": summary.get("frames_per_second"), + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + marker_path = stage_marker(item) + marker_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(marker_path, marker) + return marker + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + ): + parser.error("adaptation queue exposure flags are not explicit and valid") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_caches", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": [0, 1, 2, 3], + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + while not all(cache_report_ready(item) for item in queue["required_caches"]): + state["status"] = "waiting_for_caches" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + for index, item in enumerate(queue["stages"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + validate_stage_inputs(item) + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + command = training_command(item, gpu) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0: + marker = write_stage_marker(item, gpu) + state["completed_ids"].append(item["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + break + state["status"] = "failed_non_resource" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["stages"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_external_eval_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_external_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..a41353ff9900a376e42d6fd5e72a03b55d48a27c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_external_eval_queue.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Wait for idle GPU0-3 slots and run a frozen Phase 7 evaluation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def completed_matches(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("official_test_used") is False + and report.get("h2o_training_data_used") is False + and ( + item.get("cache_manifest_sha256") is None + or report.get("cache_manifest", {}).get("sha256") == item["cache_manifest_sha256"] + ) + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], + "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 1000)), + ] + if item.get("cache_manifest_sha256") is not None: + command.extend(( + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + )) + return command + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + # A second observation narrows the race with non-FoundationHand users. + time.sleep(1.0) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if queue.get("official_test_used") is not False: + parser.error("queue must explicitly set official_test_used=false") + items = queue["evaluations"] + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + state["status"] = "running" + for index, item in enumerate(items): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["updated_utc"] = utc_now() + state["waiting_for_idle_gpu"] = True + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + state["waiting_for_idle_gpu"] = False + output_dir = Path(item["output_dir"]) + if output_dir.exists() and any(output_dir.iterdir()): + state["status"] = "failed_existing_output" + state["failure"] = { + "id": item["id"], "reason": f"nonempty output: {output_dir}", + } + atomic_json(args.state, state) + raise SystemExit(1) + command = evaluator_command(item, gpu) + attempt = { + "id": item["id"], "gpu": gpu, "start_utc": utc_now(), + "command": command, + } + state["attempts"].append(attempt) + atomic_json(args.state, state) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + attempt["log"] = str(log_path.resolve()) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + break + tail = log_path.read_text(encoding="utf-8", errors="replace")[-4096:] + if ( + "is not idle" in tail + and (not output_dir.exists() or not any(output_dir.iterdir())) + ): + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_non_resource" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(items) + state["updated_utc"] = utc_now() + state["waiting_for_idle_gpu"] = False + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_external_train_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_external_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..7d97cea3b8039b51ace8f9e31f76e944c5001e83 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_external_train_queue.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 7 external scale stages when caches and GPUs are ready.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def cache_report_ready(item: dict[str, Any]) -> bool: + report_path = Path(item["report"]) + manifest_path = Path(item["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + clip_count = report.get("clips", report.get("cached_clips")) + recorded_manifest = report.get("cache_manifest", {}) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(clip_count or -1) == int(item["expected_clips"]) + and Path(recorded_manifest.get("path", "")).resolve() == manifest_path.resolve() + and recorded_manifest.get("sha256") == sha256(manifest_path) + ) + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1.0) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def stage_marker(item: dict[str, Any]) -> Path: + return Path(item["output_dir"]) / ".phase7_queue" / f"{item['id']}.json" + + +def completed_matches(item: dict[str, Any]) -> bool: + marker_path = stage_marker(item) + if not marker_path.is_file(): + return False + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and int(marker.get("completed_step", -1)) == int(item["stop_after_step"]) + and marker.get("config_sha256") == item["config_sha256"] + and marker.get("h2o_training_data_used") is False + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", item["config"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(item["stop_after_step"]), + ] + resume_step = item.get("resume_from_step") + if resume_step is not None: + resume = Path(item["output_dir"]) / f"step_{int(resume_step):07d}_final.pt" + command.extend(("--resume", str(resume))) + if item.get("allow_schedule_tail") is True: + command.append("--allow-schedule-tail") + return command + + +def validate_stage_inputs(item: dict[str, Any]) -> None: + config = Path(item["config"]) + if not config.is_file() or sha256(config) != item["config_sha256"]: + raise RuntimeError(f"frozen config missing or SHA mismatch: {config}") + resume_step = item.get("resume_from_step") + output = Path(item["output_dir"]) + if resume_step is None: + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new-stage output is not empty: {output}") + else: + resume = output / f"step_{int(resume_step):07d}_final.pt" + if not resume.is_file(): + raise RuntimeError(f"resume checkpoint is missing: {resume}") + expected_resume_sha = item.get("resume_checkpoint_sha256") + if expected_resume_sha is not None and sha256(resume) != expected_resume_sha: + raise RuntimeError(f"resume checkpoint SHA256 mismatch: {resume}") + + +def write_stage_marker(item: dict[str, Any], gpu: int) -> dict[str, Any]: + output = Path(item["output_dir"]) + summary = json.loads((output / "summary.json").read_text(encoding="utf-8")) + step = int(item["stop_after_step"]) + checkpoint = output / f"step_{step:07d}_final.pt" + if ( + int(summary.get("completed_step", -1)) != step + or summary.get("h2o_training_data_used") is not False + or summary.get("official_test_used") is not False + or not checkpoint.is_file() + ): + raise RuntimeError(f"training summary did not satisfy stage contract: {item['id']}") + marker = { + "status": "complete", "id": item["id"], "completed_utc": utc_now(), + "completed_step": step, "physical_gpu_id": gpu, + "config": str(Path(item["config"]).resolve()), + "config_sha256": item["config_sha256"], + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": sha256(checkpoint), + "wall_seconds": summary.get("wall_seconds"), + "gpu_hours": summary.get("gpu_hours"), + "frames_per_second": summary.get("frames_per_second"), + "schedule_tail_enabled": summary.get("schedule_tail_enabled", False), + "schedule_tail_learning_rate": summary.get("schedule_tail_learning_rate"), + "h2o_training_data_used": False, "official_test_used": False, + } + marker_path = stage_marker(item) + marker_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(marker_path, marker) + return marker + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if queue.get("official_test_used") is not False: + parser.error("queue must explicitly set official_test_used=false") + if queue.get("h2o_training_data_used") is not False: + parser.error("queue must explicitly set h2o_training_data_used=false") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_caches", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), + "h2o_training_data_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + + while not all(cache_report_ready(item) for item in queue["required_caches"]): + state["status"] = "waiting_for_caches" + state["updated_utc"] = utc_now() + state["ready_caches"] = [ + item["id"] for item in queue["required_caches"] if cache_report_ready(item) + ] + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + for index, item in enumerate(queue["stages"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + try: + validate_stage_inputs(item) + except RuntimeError as error: + state["status"] = "failed_input_contract" + state["failure"] = {"id": item["id"], "reason": str(error)} + atomic_json(args.state, state) + raise SystemExit(str(error)) + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + command = training_command(item, gpu) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0: + marker = write_stage_marker(item, gpu) + state["completed_ids"].append(item["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + break + tail = log_path.read_text(encoding="utf-8", errors="replace")[-4096:] + output = Path(item["output_dir"]) + if "is not idle" in tail and (not output.exists() or not any(output.iterdir())): + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_non_resource_or_partial_output" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + + state["status"] = "complete" + state["current_index"] = len(queue["stages"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_h2o_adapted_validation_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_h2o_adapted_validation_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a3d4e4f667ade06aec102d29481ffdde764ac9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_h2o_adapted_validation_queue.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Run a frozen three-mode H2O validation package for an adapted checkpoint.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_split") != "h2o_train_group_heldout_only" + or queue.get("h2o_official_validation_used_for_selection") is not False + ): + raise ValueError("adapted validation exposure flags are invalid") + items = queue.get("evaluations", []) + if {item.get("input_mode") for item in items} != set(INPUT_MODES) or len(items) != 3: + raise ValueError("adapted validation queue requires exactly three unique input modes") + if len({item.get("checkpoint_sha256") for item in items}) != 1: + raise ValueError("adapted validation modes must use one frozen checkpoint") + if len({item.get("freeze_record") for item in items}) != 1: + raise ValueError("adapted validation modes must use one freeze record") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_adapted_formal" + and report.get("evaluation_role") == "h2o_adapted_formal" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is True + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--freeze-record", item["freeze_record"], "--root", item["root"], + "--manifest", item["manifest"], "--input-mode", item["input_mode"], + "--evaluation-role", "h2o_adapted_formal", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty adapted validation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_h2o_zero_shot_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_h2o_zero_shot_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9916057aef5704cf28f9a5084d7b3e2bc821cdc0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_h2o_zero_shot_queue.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Run the frozen three-mode strict H2O zero-shot evaluation package.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_training_data_used") is not False + or queue.get("h2o_official_validation_used_for_external_selection") is not False + ): + raise ValueError("strict zero-shot exposure flags are invalid") + items = queue.get("evaluations", []) + if {item.get("input_mode") for item in items} != set(INPUT_MODES) or len(items) != 3: + raise ValueError("strict zero-shot queue requires exactly three unique input modes") + if len({item.get("checkpoint_sha256") for item in items}) != 1: + raise ValueError("strict zero-shot modes must use one frozen checkpoint") + if len({item.get("manifest") for item in items}) != 1: + raise ValueError("strict zero-shot modes must use one frozen validation manifest") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_strict_h2o_zero_shot" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is False + and report.get("h2o_official_validation_used_for_external_selection") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--freeze-record", item["freeze_record"], "--root", item["root"], + "--manifest", item["manifest"], "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "official_test_used": False, "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty zero-shot output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_heldout_cache_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_heldout_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..2163297840a13304a2b53d0503dc025a689c1d1e --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase7_heldout_cache_queue.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Launch formal external held-out caches as their train caches complete.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import shlex +import subprocess +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def dependency_ready(item: dict[str, Any]) -> bool: + report_path = Path(item["dependency"]) + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + count = report.get("clips", report.get("cached_clips", 0)) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(count) >= 10000 + ) + + +def output_complete(item: dict[str, Any]) -> bool: + output = Path(item["output_dir"]) + report_path = output / "cache_report.json" + manifest_path = output / "cache_manifest.jsonl" + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + cache_manifest = report.get("cache_manifest", {}) + expected_recordings = item.get("physical_recordings") + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(report.get("clips", report.get("cached_clips", 0))) == 2048 + and report.get("source_manifest", {}).get("sha256") == item["source_manifest_sha256"] + and Path(cache_manifest.get("path", "")).resolve() == manifest_path.resolve() + and cache_manifest.get("sha256") == sha256(manifest_path) + and ( + expected_recordings is None + or int(report.get("recordings", -1)) == int(expected_recordings) + ) + ) + + +def command_tokens(command: str) -> tuple[list[str], dict[str, str]]: + tokens = shlex.split(command) + environment = dict(os.environ) + while tokens and "=" in tokens[0] and not tokens[0].startswith("-"): + key, value = tokens.pop(0).split("=", 1) + if key != "PYTHONPATH": + raise ValueError(f"unexpected command environment assignment: {key}") + environment[key] = str((Path.cwd() / value).resolve()) + if not tokens: + raise ValueError("cache command is empty") + return tokens, environment + + +def process_alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except (ProcessLookupError, PermissionError): + return False + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False or plan.get("h2o_used") is not False: + parser.error("held-out cache plan must be external-only and non-test") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_train_caches", "plan": str(args.plan.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), "completed_ids": [], + "active": {}, "attempts": [], "official_test_used": False, "h2o_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan") != str(args.plan.resolve()): + parser.error("existing state belongs to a different plan") + state = previous + pending = {item["dataset"]: item for item in plan["sources"]} + processes: dict[str, subprocess.Popen[str]] = {} + while len(state["completed_ids"]) < len(pending): + for dataset, item in pending.items(): + if dataset in state["completed_ids"]: + continue + if output_complete(item): + state["completed_ids"].append(dataset) + state["active"].pop(dataset, None) + atomic_json(args.state, state) + continue + active = state["active"].get(dataset) + if active and process_alive(int(active["pid"])): + continue + if not dependency_ready(item): + continue + output = Path(item["output_dir"]) + command_key = "resume_command" if output.exists() else "start_command" + command, environment = command_tokens(item[command_key]) + log_path = args.state.parent / f"heldout_cache_{dataset.lower()}.log" + attempt = { + "dataset": dataset, "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), "mode": command_key, + } + state["attempts"].append(attempt) + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, + ) + processes[dataset] = process + state["active"][dataset] = {"pid": process.pid, "log": str(log_path.resolve())} + state["status"] = "running" + atomic_json(args.state, state) + finished = [] + for dataset, active in list(state["active"].items()): + process = processes.get(dataset) + if process is not None: + returncode = process.poll() + if returncode is None: + continue + state["active"][dataset]["returncode"] = returncode + processes.pop(dataset) + elif process_alive(int(active["pid"])): + continue + # A completed report is validated on the next loop. A dead process + # without one is retained as a failure rather than silently retried. + item = pending[dataset] + if output_complete(item): + finished.append(dataset) + else: + state["status"] = "failed_incomplete_output" + state["failure"] = {"dataset": dataset, "log": active["log"]} + atomic_json(args.state, state) + raise SystemExit(1) + for dataset in finished: + if dataset not in state["completed_ids"]: + state["completed_ids"].append(dataset) + state["active"].pop(dataset, None) + state["updated_utc"] = utc_now() + state["ready_dependencies"] = [ + dataset for dataset, item in pending.items() if dependency_ready(item) + ] + atomic_json(args.state, state) + if len(state["completed_ids"]) < len(pending): + time.sleep(args.poll_seconds) + state["status"] = "complete" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase8_egodexter_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase8_egodexter_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9d96eeb623ad017721160ed288970aa05e10ae3a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase8_egodexter_queue.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Run a frozen EgoDexter queue on atomically claimed physical GPU0-3.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("egodexter_used_for_training_or_selection") is not False + or not queue.get("evaluations") + ): + raise ValueError("EgoDexter queue boundary flags are invalid") + expected = { + (mode, input_mode) + for mode in ("offline", "causal") + for input_mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + actual = { + (item.get("inference_mode"), item.get("input_mode")) + for item in queue["evaluations"] + } + if actual != expected or len(queue["evaluations"]) != len(expected): + raise ValueError("EgoDexter queue must contain the exact six-condition grid") + if {item.get("model_id") for item in queue["evaluations"]} != {queue.get("model_id")}: + raise ValueError("EgoDexter queue mixes model IDs") + + +def completed_matches(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_frozen_egodexter_zero_shot" + and report.get("model_id") == item["model_id"] + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("inference_mode") == item["inference_mode"] + and report.get("egodexter_used_for_training_or_selection") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_egodexter_zero_shot", + "--model-id", item["model_id"], + "--freeze-record", item["freeze_record"], + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--root", item["root"], "--input-mode", item["input_mode"], + "--inference-mode", item["inference_mode"], + "--window", str(item.get("window", 8)), + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists(): + raise RuntimeError(f"EgoDexter output already exists: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase8_h2o_control_eval_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase8_h2o_control_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..6106550a604d35b15aecabb34d29f911e7f8d1c9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase8_h2o_control_eval_queue.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Run hash-bound H2O train-heldout controls without changing their provenance.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("selection_split") != "h2o_train_group_heldout_only" + ): + raise ValueError("H2O control queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("H2O control queue is empty") + for item in queue["evaluations"]: + if Path(item["cache_manifest"]).name != "train_group_heldout.jsonl": + raise ValueError("H2O control must use train_group_heldout.jsonl") + if not isinstance(item.get("expected_h2o_training_data_used"), bool): + raise ValueError("control item must freeze expected H2O provenance") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_train_group_heldout_control" + and report.get("evaluation_role") == "h2o_train_group_heldout_control" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is item["expected_h2o_training_data_used"] + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--evaluation-role", "h2o_train_group_heldout_control", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty H2O control output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode != 0 or not completed_matches(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(item["id"]) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_data_finalize_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_data_finalize_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..8d1a4cd4bc05e33467e6e5aa5cf12294d155a053 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_data_finalize_queue.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Wait for Phase 9 base caches, then freeze subsets and left sidecars.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def base_cache_ready(item: dict[str, Any]) -> bool: + manifest = Path(item["manifest"]) + report_path = Path(item["report"]) + if not manifest.is_file() or not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(manifest) + ): + return False + if item["dataset"] == "HOT3D": + return int(report.get("clips", -1)) == int(item["expected_clips"]) + return ( + report.get("accept_all_valid") is True + and report.get("all_eligible_processed") is True + and int(report.get("cached_valid_clips", 0)) > 0 + ) + + +def artifact_complete(item: dict[str, Any]) -> bool: + report_path = Path(item["report"]) + manifest = Path(item["manifest"]) + if not report_path.is_file() or not manifest.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + key = "augmented_cache_manifest" if item["kind"] == "left_sidecar" else "cache_manifest" + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get(key, {}).get("sha256") == sha256(manifest) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("finalize plan must explicitly exclude official test") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_data_finalize_state_v1", + "status": "waiting_for_base_caches", + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "started_utc": utc_now(), + "updated_utc": utc_now(), + "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != sha256(args.plan): + parser.error("existing state is bound to a different plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + base_caches = {item["dataset"]: item for item in plan["base_caches"]} + for item in plan["artifacts"]: + if artifact_complete(item): + continue + prerequisite = base_caches[item["requires_base_cache"]] + while not base_cache_ready(prerequisite): + state["status"] = "waiting_for_base_cache" + state["current_artifact"] = item["id"] + state["waiting_for_dataset"] = item["requires_base_cache"] + state["ready_base_caches"] = [ + dataset for dataset, base in base_caches.items() + if base_cache_ready(base) + ] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = [str(value) for value in item["command"]] + if item["kind"] == "left_sidecar": + base_manifest = Path(item["base_cache_manifest"]) + command = [ + value.replace("{BASE_CACHE_SHA256}", sha256(base_manifest)) + for value in command + ] + if (Path(item["output_dir"]) / "sidecars").is_dir(): + command.append("--resume") + log_path = Path(item["log"]) + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "id": item["id"], "start_utc": utc_now(), + "command": command, "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_artifact"] = item["id"] + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode or not artifact_complete(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "returncode": result.returncode} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["artifacts"] = [{ + "id": item["id"], "manifest": item["manifest"], + "manifest_sha256": sha256(item["manifest"]), + "report": item["report"], "report_sha256": sha256(item["report"]), + } for item in plan["artifacts"]] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_distributed_resolution_cache_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_distributed_resolution_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9e349530aae1d53571708b4637ace42ed029b9e5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_distributed_resolution_cache_queue.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Enforce distributed cache ownership before entering the existing queue.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import sys + +from scripts.phase9_distributed_assignment import detect_machine, load_assignment + + +CACHE_OWNERS = { + "h2o": "taku3", + "hot3d": "server_new", + "hoi4d": "taku3", + "arctic": "taku3", +} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--assignment-sha256", required=True) + parser.add_argument("--worker", choices=tuple(CACHE_OWNERS), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + assignment = load_assignment({"distributed_assignment": { + "path": str(args.assignment.resolve()), + "sha256": args.assignment_sha256, + }}) + machine = detect_machine(assignment, None) + if CACHE_OWNERS[args.worker] != machine: + parser.error(f"cache worker {args.worker} is owned by {CACHE_OWNERS[args.worker]}") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + matches = [item for item in plan["workers"] if item["id"] == args.worker] + if ( + len(matches) != 1 + or Path(matches[0]["state"]).resolve() != args.state.resolve() + or plan.get("official_test_used") is not False + ): + parser.error("distributed cache worker plan/state differs") + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_cache_queue", + "--plan", str(args.plan.resolve()), "--worker", args.worker, + "--state", str(args.state.resolve()), + "--poll-seconds", str(args.poll_seconds), + ] + os.execv(sys.executable, command) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_expanded_coverage_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_expanded_coverage_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c69ac4d00155e8221d06fc56dc05c3fd3890b3 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_expanded_coverage_queue.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Run frozen source-coverage audits after Phase 9 data finalization.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import readiness_complete + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def audit_complete(item: dict[str, Any]) -> bool: + output = Path(item["output"]) + if not output.is_file(): + return False + report = json.loads(output.read_text(encoding="utf-8")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("cache_manifest", {}).get("sha256") == sha256(item["cache_manifest"]) + and report.get("source_manifest", {}).get("sha256") == sha256(item["source_manifest"]) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("coverage plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_expanded_coverage_state_v1", + "status": "waiting_for_data", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "updated_utc": utc_now(), "completed_ids": [], "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing coverage state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not readiness_complete(plan): + state["status"] = "waiting_for_data" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + for item in plan["audits"]: + if audit_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + continue + output = Path(item["output"]) + if output.exists(): + raise RuntimeError(f"incomplete coverage output already exists: {output}") + command = [ + sys.executable, "-m", "scripts.audit_phase9_source_coverage", + "--dataset", item["dataset"], + "--source-manifest", item["source_manifest"], + "--cache-manifest", item["cache_manifest"], + "--output", item["output"], + ] + log_path = args.state.parent / f"expanded_coverage_{item['dataset'].lower()}.log" + attempt = { + "id": item["id"], "start_utc": utc_now(), + "command": command, "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not audit_complete(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_external_milestone_eval.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_external_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..6b01ab8a3b01110cdfecc246e0022914527b06f1 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_external_milestone_eval.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Evaluate Phase 9 unified milestone checkpoints on native external held-outs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3, 4, 5) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def stable_checkpoint_sha256( + path: str | Path, + *, + stable_seconds: float = 2.0, + poll_seconds: float = 0.25, + timeout_seconds: float = 300.0, +) -> str: + """Hash a checkpoint only after a non-atomic torch.save has quiesced.""" + checkpoint = Path(path) + started = time.monotonic() + previous = (checkpoint.stat().st_size, checkpoint.stat().st_mtime_ns) + stable_since = time.monotonic() + while True: + if time.monotonic() - started > timeout_seconds: + raise TimeoutError(f"checkpoint did not stabilize: {checkpoint}") + time.sleep(poll_seconds) + before = checkpoint.stat() + signature = (before.st_size, before.st_mtime_ns) + if signature != previous: + previous = signature + stable_since = time.monotonic() + continue + if time.monotonic() - stable_since < stable_seconds: + continue + digest = sha256(checkpoint) + after = checkpoint.stat() + if (after.st_size, after.st_mtime_ns) == signature: + return digest + previous = (after.st_size, after.st_mtime_ns) + stable_since = time.monotonic() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def checkpoint_path(condition: dict[str, Any], checkpoint: dict[str, Any]) -> Path | None: + run = Path(condition["run_dir"]) + if checkpoint["kind"] == "final": + path = run / f"step_{int(checkpoint['step']):07d}_final.pt" + return path if path.is_file() else None + matches = sorted(run.glob(f"milestone_{checkpoint['milestone_id']}_step_*.pt")) + if len(matches) > 1: + raise RuntimeError(f"multiple checkpoint files for milestone {checkpoint['milestone_id']}") + return matches[0] if matches else None + + +def evaluation_complete( + output_dir: Path, checkpoint_hash: str, manifest_hash: str, input_mode: str, +) -> bool: + path = output_dir / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_phase9_external_heldout" + and report.get("evaluation_role") == "phase9_external_heldout" + and report.get("checkpoint", {}).get("sha256") == checkpoint_hash + and report.get("cache_manifest", {}).get("sha256") == manifest_hash + and report.get("input_mode") == input_mode + and report.get("h2o_training_data_used") is True + and report.get("official_test_used") is False + ) + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def evaluator_command( + condition: dict[str, Any], checkpoint: Path, checkpoint_hash: str, + source: dict[str, Any], gpu: int, output: Path, +) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", condition["config"], + "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", source["cache_manifest"], + "--expected-cache-manifest-sha256", source["cache_manifest_sha256"], + "--input-mode", source["input_mode"], + "--output-dir", str(output), + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(source.get("bootstrap_resamples", 2000)), + "--evaluation-role", "phase9_external_heldout", + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--condition", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + registry = json.loads(args.registry.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + parser.error("registry must explicitly exclude official test") + conditions = {item["condition"]: item for item in registry["conditions"]} + if args.condition not in conditions: + parser.error("unknown condition") + condition = conditions[args.condition] + config = Path(condition["config"]) + if not config.is_file() or sha256(config) != condition["config_sha256"]: + parser.error("frozen config is missing or changed") + for source in registry["sources"]: + manifest = Path(source["cache_manifest"]) + if not manifest.is_file() or sha256(manifest) != source["cache_manifest_sha256"]: + parser.error(f"held-out manifest is missing or changed: {source['id']}") + registry_hash = sha256(args.registry) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_external_milestone_eval_state_v1", + "status": "waiting_for_checkpoint", "condition": args.condition, + "registry": str(args.registry.resolve()), "registry_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("registry_sha256") != registry_hash: + parser.error("existing state is bound to another registry version") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for checkpoint_spec in condition["checkpoints"]: + while True: + checkpoint = checkpoint_path(condition, checkpoint_spec) + if checkpoint is not None: + break + state["status"] = "waiting_for_checkpoint" + state["waiting_for"] = checkpoint_spec["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for source in registry["sources"]: + evaluation_id = f"{args.condition}_{checkpoint_spec['id']}_{source['id']}" + output = Path(registry["evaluation_root"]) / args.condition / checkpoint_spec["id"] / source["id"] + if evaluation_complete( + output, checkpoint_hash, source["cache_manifest_sha256"], source["input_mode"], + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + continue + while True: + gpu = idle_gpu() + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + if output.exists() and any(output.iterdir()): + release_physical_gpu_claim(gpu) + state["status"] = "failed_existing_output" + state["failure"] = {"id": evaluation_id, "output": str(output)} + atomic_json(args.state, state) + raise SystemExit(1) + command = evaluator_command( + condition, checkpoint, checkpoint_hash, source, gpu, output, + ) + log_path = args.state.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not evaluation_complete( + output, checkpoint_hash, source["cache_manifest_sha256"], source["input_mode"], + ): + state["status"] = "failed" + state["failure"] = {"id": evaluation_id, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_final_deployment_controller.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_final_deployment_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..a64e86ece28d0bcd9b90218507b54ae5ab7ae529 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_final_deployment_controller.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +"""Wait for final selection, then supervise formal validation and deployment audits.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + if ( + plan.get("schema_version") != "phase9_final_deployment_controller_plan_v1" + or plan.get("job_count") != 11 or plan.get("worker_count") != 4 + or plan.get("allowed_physical_gpus") != [0, 1, 2, 3] + or plan.get("official_validation_checkpoint_count") != 1 + or plan.get("h2o_official_validation_used_for_selection") is not False + or plan.get("official_test_used") is not False + ): + raise ValueError("final deployment controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"final deployment binding differs: {path}") + + +def final_decision_ready(plan: dict[str, Any]) -> bool: + state_path = Path(plan["last2_finalizer_state"]) + if not state_path.is_file(): + return False + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["last2_finalizer_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and report_path.is_file() + and state.get("decision_report", {}).get("sha256") == sha256(report_path) + and report_path.resolve() == Path(plan["last2_final_decision"]).resolve() + ) + + +def worker_status(path: Path, plan_hash: str) -> str: + if not path.is_file(): + return "missing" + state = read_json(path) + if state.get("plan_sha256") != plan_hash: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def pid_matches(pid: int, worker: str, dynamic_plan: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_final_deployment_worker" in command + and f"--worker {worker}" in command + and str(dynamic_plan.resolve()) in command + ) + + +def launch_worker(dynamic_plan: Path, worker: dict[str, Any], log_path: Path) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_final_deployment_worker", + "--plan", str(dynamic_plan.resolve()), "--worker", worker["id"], + "--state", worker["state"], + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def run_command(command: list[str], state: dict[str, Any], state_path: Path, label: str) -> None: + state["status"] = label + state[f"{label}_command"] = command + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = f"failed_{label}" + state[f"{label}_returncode"] = result.returncode + atomic_json(state_path, state) + raise SystemExit(result.returncode) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["controller_state"]).resolve(): + parser.error("final deployment controller state differs") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_final_deployment_controller_state_v1", + "status": "waiting_for_final_selection", "started_utc": utc_now(), + "updated_utc": utc_now(), "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "workers": {}, + "h2o_official_validation_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing final deployment controller state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not final_decision_ready(plan): + state["status"] = "waiting_for_final_selection" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + freeze = Path(plan["freeze"]) + freeze_command = [ + sys.executable, "-m", "scripts.freeze_phase9_final_deployment", + "--selection-plan", plan["selection_plan"], + "--selection-state", plan["selection_state"], + "--stage8-plan", plan["stage8_plan"], + "--stage8-state", plan["stage8_state"], + "--last2-plan", plan["last2_finalizer_plan"], + "--last2-state", plan["last2_finalizer_state"], + "--validation-manifest", plan["validation_manifest"], + "--validation-manifest-sha256", plan["validation_manifest_sha256"], + "--training-manifest", plan["training_manifest"], + "--training-manifest-sha256", plan["training_manifest_sha256"], + "--output", str(freeze), "--state", plan["freeze_state"], + ] + run_command(freeze_command, state, args.state, "freezing_final_checkpoint") + freeze_state = read_json(plan["freeze_state"]) + if ( + freeze_state.get("status") != "complete" or not freeze.is_file() + or freeze_state.get("freeze_sha256") != sha256(freeze) + ): + state["status"] = "failed_freeze_binding" + atomic_json(args.state, state) + raise SystemExit(1) + + dynamic_plan = Path(plan["dynamic_plan"]) + dynamic_command = [ + sys.executable, "-m", "scripts.build_phase9_final_deployment_plan", + "--freeze", str(freeze), "--freeze-state", plan["freeze_state"], + "--output-root", plan["output_root"], + "--worker-state-root", plan["worker_state_root"], + "--causal-config", plan["causal_config"], + "--h2o-root", plan["h2o_root"], + "--output", str(dynamic_plan), "--state", plan["dynamic_plan_state"], + ] + run_command(dynamic_command, state, args.state, "building_deployment_plan") + dynamic_state = read_json(plan["dynamic_plan_state"]) + if ( + dynamic_state.get("status") != "complete" or not dynamic_plan.is_file() + or dynamic_state.get("plan_sha256") != sha256(dynamic_plan) + ): + state["status"] = "failed_dynamic_plan_binding" + atomic_json(args.state, state) + raise SystemExit(1) + dynamic_hash = sha256(dynamic_plan) + dynamic = read_json(dynamic_plan) + state["dynamic_plan_sha256"] = dynamic_hash + state.setdefault("workers", {}) + while True: + statuses = {} + for worker in dynamic["workers"]: + path = Path(worker["state"]) + status = worker_status(path, dynamic_hash) + statuses[worker["id"]] = status + if status == "complete" or status.startswith("failed"): + continue + previous_pid = int(state["workers"].get(worker["id"], {}).get("pid", -1)) + if not pid_matches(previous_pid, worker["id"], dynamic_plan): + pid = launch_worker( + dynamic_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(status.startswith("failed") for status in statuses.values()): + state["status"] = "failed_deployment_worker" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = "running_post_selection_audits" + state["h2o_official_validation_used"] = True + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + report = Path(plan["summary_report"]) + if not report.is_file(): + run_command([ + sys.executable, "-m", "scripts.summarize_phase9_final_deployment", + "--plan", str(dynamic_plan), "--output", str(report), + ], state, args.state, "summarizing_deployment") + summary = read_json(report) + if ( + summary.get("status") != "complete" + or summary.get("deployment_contract", {}).get("passed") is not True + or summary.get("h2o_official_validation_used_for_selection") is not False + or summary.get("official_test_used") is not False + ): + state["status"] = "failed_deployment_summary" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["summary_report"] = {"path": str(report.resolve()), "sha256": sha256(report)} + state["checkpoint"] = summary["checkpoint"] + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["h2o_official_validation_used"] = True + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_final_deployment_worker.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_final_deployment_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ad40a896ea1c75803d879094f935440c2aae9c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_final_deployment_worker.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Run one disjoint final deployment worker with resumable output validation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_artifact(record: dict[str, Any]) -> bool: + path = Path(record.get("path", "")) + return path.is_file() and record.get("sha256") == sha256(path) + + +def completed_matches(job: dict[str, Any]) -> bool: + kind = job["kind"] + path = ( + Path(job["output_dir"]) / "evaluation.json" + if kind == "formal_validation" else Path(job["output"]) + ) + if not path.is_file(): + return False + try: + report = read_json(path) + except (OSError, json.JSONDecodeError): + return False + common = ( + report.get("checkpoint", {}).get("sha256") == job["checkpoint_sha256"] + and report.get("config", {}).get("sha256") == job["config_sha256"] + and report.get("manifest", {}).get("sha256") == job["manifest_sha256"] + and report.get("official_test_used") is False + ) + if not common: + return False + report_step = report.get("checkpoint", {}).get( + "step", report.get("checkpoint_step") + ) + if int(report_step if report_step is not None else -1) != job["checkpoint_step"]: + return False + if kind == "formal_validation": + return ( + report.get("status") == "evaluated_phase9_unified_formal" + and report.get("evaluation_role") == "phase9_unified_formal" + and report.get("input_mode") == job["input_mode"] + and report.get("freeze_record", {}).get("sha256") + == job["freeze_record_sha256"] + and report.get("h2o_official_validation_used") is True + and report.get("h2o_official_validation_used_for_selection") is False + and report.get("h2o_training_data_used") is True + and all(validate_artifact(report[key]) for key in ( + "raw_predictions", "per_hand_rows", "take_metrics", + )) + ) + if kind == "variable_length": + results = report.get("forward_results", []) + return ( + report.get("status") == "completed" + and report.get("official_validation_used") is True + and [item.get("T") for item in results] == job["lengths"] + and all(item.get("all_finite") is True for item in results) + ) + if kind == "sequence": + bounded = ( + int(report.get("maximum_gpu_window_frames", 10**9)) <= job["window"] + and int(report.get("maximum_cpu_input_buffer_frames", 10**9)) + <= (job["window"] if job["mode"] == "causal" else 12) + ) + causal = report.get("invariance") + causal_ok = job["mode"] != "causal" or ( + isinstance(causal, dict) + and causal.get("future_perturbation_bitwise_zero") is True + and causal.get("prefix_passed") is True + ) + mode_ok = ( + report.get("causal") is (job["mode"] == "causal") + and report.get("offline_stride") + == (None if job["mode"] == "causal" else 4) + and report.get("stitching") + == (None if job["mode"] == "causal" else "center") + ) + return ( + report.get("status") == "passed" + and report.get("mode") == job["mode"] + and report.get("window") == job["window"] + and report.get("requested_frames") == job["frames"] + and report.get("output_frames") == job["frames"] + and report.get("frame_ids_strictly_increasing") is True + and report.get("finite") is True + and report.get("official_validation_used_for_selection") is False + and bounded and causal_ok and mode_ok + ) + if kind == "profile": + latency = report.get("latency", {}) + return ( + report.get("status") == "profiled" + and report.get("official_validation_used") is False + and report.get("input", {}).get("resolution_hw") == job["resolution_hw"] + and float(latency.get("p50_ms", 0)) > 0 + and float(latency.get("p95_ms", 0)) > 0 + and float(report.get("peak_allocated_vram_gib", 0)) > 0 + ) + return False + + +def command(job: dict[str, Any]) -> list[str]: + common = ["--config", job["config"], "--checkpoint", job["checkpoint"]] + if job["kind"] == "formal_validation": + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + *common, "--expected-checkpoint-sha256", job["checkpoint_sha256"], + "--freeze-record", job["freeze_record"], "--root", job["root"], + "--manifest", job["manifest"], "--input-mode", job["input_mode"], + "--evaluation-role", "phase9_unified_formal", + "--output-dir", job["output_dir"], "--physical-gpu-id", + str(job["physical_gpu_id"]), "--bootstrap-resamples", "2000", + ] + if job["kind"] == "variable_length": + return [ + sys.executable, "-m", "scripts.audit_phase6_variable_length", + *common, "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--gpu", str(job["physical_gpu_id"]), + "--repeats", "2", + ] + if job["kind"] == "sequence": + return [ + sys.executable, "-m", "scripts.audit_phase6_sequence_inference", + *common, "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--mode", job["mode"], + "--window", str(job["window"]), "--frames", str(job["frames"]), + "--gpu", str(job["physical_gpu_id"]), + ] + if job["kind"] == "profile": + return [ + sys.executable, "-m", "scripts.profile_phase5_model", + *common, "--expected-checkpoint-sha256", job["checkpoint_sha256"], + "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--gpu", str(job["physical_gpu_id"]), + "--warmup", "20", "--iterations", "100", + ] + raise ValueError(f"unknown final deployment job kind: {job['kind']}") + + +def output_target(job: dict[str, Any]) -> Path: + return Path(job.get("output", job.get("output_dir", ""))) + + +def archive_incomplete(job: dict[str, Any]) -> str | None: + target = output_target(job) + if not target.exists(): + return None + recovery = target.parent / "recovery" + recovery.mkdir(parents=True, exist_ok=True) + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + destination = recovery / f"{target.name}.{stamp}.incomplete" + suffix = 0 + while destination.exists(): + suffix += 1 + destination = recovery / f"{target.name}.{stamp}.{suffix}.incomplete" + shutil.move(str(target), str(destination)) + return str(destination.resolve()) + + +def validate_plan(plan: dict[str, Any], worker: dict[str, Any]) -> dict[str, dict[str, Any]]: + if ( + plan.get("status") != "frozen_ready_post_selection" + or plan.get("official_validation_checkpoint_count") != 1 + or plan.get("h2o_official_validation_used_for_selection") is not False + or plan.get("official_test_used") is not False + or worker.get("physical_gpu_id") not in {0, 1, 2, 3} + ): + raise ValueError("final deployment worker contract differs") + jobs = {job["id"]: job for job in plan["jobs"]} + if len(jobs) != 11 or any(identifier not in jobs for identifier in worker["job_ids"]): + raise ValueError("final deployment worker jobs differ") + if any(jobs[identifier]["physical_gpu_id"] != worker["physical_gpu_id"] for identifier in worker["job_ids"]): + raise ValueError("final deployment worker GPU assignment differs") + return jobs + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + worker = next((item for item in plan["workers"] if item["id"] == args.worker), None) + if worker is None: + parser.error("unknown final deployment worker") + try: + jobs = validate_plan(plan, worker) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("final deployment worker state differs") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_final_deployment_worker_state_v1", + "status": "running", "worker": args.worker, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing final deployment worker state differs") + if state.get("status") == "complete": + invalid = [ + identifier for identifier in worker["job_ids"] + if not completed_matches(jobs[identifier]) + ] + if invalid: + state["status"] = "failed_completed_output_binding" + state["failure"] = {"invalid_completed_ids": invalid} + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + print(json.dumps(state, indent=2)) + return + for identifier in worker["job_ids"]: + job = jobs[identifier] + target = output_target(job) + lock_path = Path(f"{target}.lock") + lock_path.parent.mkdir(parents=True, exist_ok=True) + with lock_path.open("a+", encoding="utf-8") as output_lock: + fcntl.flock(output_lock.fileno(), fcntl.LOCK_EX) + if completed_matches(job): + if identifier not in state["completed_ids"]: + state["completed_ids"].append(identifier) + atomic_json(args.state, state) + continue + archived = archive_incomplete(job) + attempt = { + "id": identifier, "kind": job["kind"], + "physical_gpu_id": job["physical_gpu_id"], + "start_utc": utc_now(), "command": command(job), + } + log_path = args.state.parent / f"{identifier}.log" + attempt["log"] = str(log_path.resolve()) + if archived: + attempt["archived_incomplete_output"] = archived + state["current_id"] = identifier + state["status"] = "running" + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ) + if job["kind"] == "formal_validation": + environment["CUDA_VISIBLE_DEVICES"] = str(job["physical_gpu_id"]) + else: + environment.pop("CUDA_VISIBLE_DEVICES", None) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + attempt["command"], cwd=Path.cwd(), env=environment, + stdout=log, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not completed_matches(job): + state["status"] = "failed_job" + state["failure"] = {"id": identifier, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(identifier) + atomic_json(args.state, state) + state["status"] = "complete" + state["current_id"] = None + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_fold_milestone_eval.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_fold_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..bae92c4c4151e059eb56207d37420d72fa6d3dbe --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_fold_milestone_eval.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +"""Evaluate H2O-bearing milestones for Phase 9 group-CV replicas.""" + +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any, Iterator + +import yaml + +from scripts.run_phase9_fold_shard import fold_evaluation_complete +from scripts.run_phase9_external_milestone_eval import stable_checkpoint_sha256 +from scripts.run_phase9_unified_train_queue import parse_physical_gpu_ids +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3, 4, 5) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def h2o_milestones(config: dict[str, Any]) -> list[str]: + return [ + str(milestone["id"]) + for milestone in config["protocol"].get("source_exposure_milestones", []) + if "H2O" in milestone.get("minimum_batches", {}) + ] + + +def milestone_checkpoint(run_dir: Path, milestone_id: str) -> Path | None: + matches = sorted(run_dir.glob(f"milestone_{milestone_id}_step_*.pt")) + if len(matches) > 1: + raise RuntimeError(f"multiple checkpoints found for milestone {milestone_id}") + return matches[0] if matches else None + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +@contextmanager +def exclusive_evaluation_output(output: Path) -> Iterator[None]: + output.parent.mkdir(parents=True, exist_ok=True) + lock_path = output.parent / f".{output.name}.phase9-evaluation.lock" + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(lock.fileno(), fcntl.LOCK_UN) + + +def recovery_assignment( + plan_path: Path, worker_id: str, registry_hash: str, +) -> tuple[dict[str, Any], str]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + raise ValueError("recovery plan must explicitly exclude official test") + if plan.get("registry_sha256") != registry_hash: + raise ValueError("recovery plan registry SHA256 differs") + matches = [item for item in plan["workers"] if item["id"] == worker_id] + if len(matches) != 1: + raise ValueError(f"recovery worker must be unique: {worker_id}") + return matches[0], sha256(plan_path) + + +def evaluation_command( + config_path: Path, checkpoint: Path, checkpoint_hash: str, + heldout: Path, heldout_hash: str, mode: str, output: Path, gpu: int, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", str(config_path), "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", str(heldout), + "--expected-cache-manifest-sha256", heldout_hash, + "--input-mode", mode, "--output-dir", str(output), + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", "phase9_h2o_fold_heldout", + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--shard", type=int, choices=(0, 1, 2), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--recovery-plan", type=Path) + parser.add_argument("--worker-id") + args = parser.parse_args() + registry = json.loads(args.registry.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + parser.error("fold registry must explicitly exclude official test") + conditions = {item["condition"]: item for item in registry["conditions"]} + assigned = registry["shards"][str(args.shard)] + registry_hash = sha256(args.registry) + selected_ids: set[str] | None = None + recovery_plan_hash: str | None = None + if (args.recovery_plan is None) != (args.worker_id is None): + parser.error("--recovery-plan and --worker-id must be provided together") + if args.recovery_plan is not None: + try: + worker, recovery_plan_hash = recovery_assignment( + args.recovery_plan, args.worker_id, registry_hash, + ) + except (KeyError, TypeError, ValueError) as error: + parser.error(str(error)) + if int(worker["shard"]) != args.shard: + parser.error("recovery worker shard differs") + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("recovery worker state path differs") + if tuple(worker["allowed_physical_gpus"]) != args.allowed_physical_gpus: + parser.error("recovery worker GPU assignment differs") + selected_ids = set(worker["evaluation_ids"]) + if len(selected_ids) != len(worker["evaluation_ids"]): + parser.error("recovery worker contains duplicate evaluation IDs") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_fold_milestone_eval_state_v1", + "status": "waiting_for_checkpoint", "shard": args.shard, + "registry": str(args.registry.resolve()), "registry_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(args.allowed_physical_gpus), + "official_test_used": False, + } + if recovery_plan_hash is not None: + state.update({ + "recovery_plan": str(args.recovery_plan.resolve()), + "recovery_plan_sha256": recovery_plan_hash, + "recovery_worker_id": args.worker_id, + "assigned_evaluation_ids": sorted(selected_ids), + "resource_amendment": "gpu_4_5_evaluator_authorization_only_20260730", + }) + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("registry_sha256") != registry_hash: + parser.error("existing state belongs to another registry") + if recovery_plan_hash is not None and ( + previous.get("recovery_plan_sha256") != recovery_plan_hash + or previous.get("recovery_worker_id") != args.worker_id + or set(previous.get("assigned_evaluation_ids", [])) != selected_ids + or tuple(previous.get("allowed_physical_gpus", ())) + != args.allowed_physical_gpus + ): + parser.error("existing recovery state belongs to another assignment") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for condition_id in assigned: + condition = conditions[condition_id] + config_path = Path(condition["config"]) + if sha256(config_path) != condition["config_sha256"]: + parser.error(f"fold config hash differs: {condition_id}") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + heldout = Path(config["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + run_dir = Path(condition["output_dir"]) + for milestone_id in h2o_milestones(config): + milestone_ids = { + f"{condition_id}_{milestone_id}_{mode}" + for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + if selected_ids is not None and not (milestone_ids & selected_ids): + continue + while True: + checkpoint = milestone_checkpoint(run_dir, milestone_id) + if checkpoint is not None: + break + state["status"] = "waiting_for_checkpoint" + state["waiting_for"] = f"{condition_id}:{milestone_id}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + evaluation_id = f"{condition_id}_{milestone_id}_{mode}" + if selected_ids is not None and evaluation_id not in selected_ids: + continue + output = args.output_root / condition_id / milestone_id / mode + if fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + continue + with exclusive_evaluation_output(output): + if fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + continue + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty incomplete output: {output}") + while True: + gpu = idle_gpu(args.allowed_physical_gpus) + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = evaluation_command( + config_path, checkpoint, checkpoint_hash, + heldout, heldout_hash, mode, output, gpu, + ) + log_path = args.state.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + state["status"] = "failed" + state["failure"] = { + "id": evaluation_id, "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + if selected_ids is not None and not selected_ids.issubset(state["completed_ids"]): + missing = sorted(selected_ids - set(state["completed_ids"])) + parser.error(f"recovery assignment contains unknown IDs: {missing}") + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_fold_overflow.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_fold_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..348d8b3162e8c54d6a313eb7961b75b243c63ab6 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_fold_overflow.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 9 fold conditions early on otherwise idle capacity.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def prerequisite_states_complete(plan: dict[str, Any]) -> bool: + for item in plan["prerequisite_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("overflow plan must explicitly exclude official test") + registry = Path(plan["fold_training_registry"]) + if sha256(registry) != plan["fold_training_registry_sha256"]: + parser.error("fold training registry SHA256 differs") + registry_payload = json.loads(registry.read_text(encoding="utf-8")) + registered = {item["condition"] for item in registry_payload["conditions"]} + if not plan["conditions"] or any(item not in registered for item in plan["conditions"]): + parser.error("overflow condition is not in the frozen fold registry") + + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + state: dict[str, Any] = { + "schema_version": "phase9_fold_overflow_state_v1", + "status": "waiting_for_prerequisites", + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "started_utc": utc_now(), + "updated_utc": utc_now(), + "completed_conditions": [], + "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing overflow state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + + while not prerequisite_states_complete(plan): + state["status"] = "waiting_for_prerequisites" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + child_root = Path(plan["child_state_root"]) + child_root.mkdir(parents=True, exist_ok=True) + for condition in plan["conditions"]: + if condition in state["completed_conditions"]: + continue + child_state = child_root / f"{condition.lower()}.json" + command = [ + sys.executable, + "-m", + "scripts.run_phase9_unified_train_queue", + "--queue", + str(registry), + "--condition", + condition, + "--state", + str(child_state), + "--poll-seconds", + str(args.poll_seconds), + "--allowed-physical-gpus", + str(plan["physical_gpu_id"]), + ] + log_path = args.state.parent / f"overflow_{condition.lower()}.log" + attempt = { + "condition": condition, + "start_utc": utc_now(), + "command": command, + "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "running_condition" + state["current_condition"] = condition + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, + stdout=log, + stderr=subprocess.STDOUT, + text=True, + check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode: + state["status"] = "failed_resumable" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_conditions"].append(condition) + atomic_json(args.state, state) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_fold_shard.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_fold_shard.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6b518537959a2149496efd6fae0f33badb5dc7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_fold_shard.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Run a shard of Phase 9 H2O group-CV replicas and formal fold evaluations.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) +from scripts.run_phase9_unified_train_queue import parse_physical_gpu_ids + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def main_training_complete(plan: dict[str, Any]) -> bool: + for item in plan["main_training_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def main_training_gate_satisfied( + plan: dict[str, Any], start_before_main_complete: bool, +) -> bool: + return start_before_main_complete or main_training_complete(plan) + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def fold_evaluation_complete( + output: Path, checkpoint_hash: str, manifest_hash: str, mode: str, +) -> bool: + report_path = output / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_phase9_h2o_fold_heldout" + and report.get("evaluation_role") == "phase9_h2o_fold_heldout" + and report.get("checkpoint", {}).get("sha256") == checkpoint_hash + and report.get("cache_manifest", {}).get("sha256") == manifest_hash + and report.get("input_mode") == mode + and report.get("official_test_used") is False + ) + + +def run_fold_evaluations( + condition: dict[str, Any], state: dict[str, Any], state_path: Path, + evaluation_root: Path, poll_seconds: float, + allowed_gpus: tuple[int, ...] = ALLOWED_GPUS, +) -> None: + step = int(condition["stages"][-1]["stop_after_step"]) + checkpoint = Path(condition["output_dir"]) / f"step_{step:07d}_final.pt" + checkpoint_hash = sha256(checkpoint) + config = Path(condition["config"]) + config_payload = __import__("yaml").safe_load(config.read_text(encoding="utf-8")) + heldout = Path(config_payload["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + output = evaluation_root / condition["condition"] / mode + evaluation_id = f"{condition['condition']}_{mode}" + if fold_evaluation_complete(output, checkpoint_hash, heldout_hash, mode): + if evaluation_id not in state["completed_evaluations"]: + state["completed_evaluations"].append(evaluation_id) + continue + while True: + gpu = idle_gpu(allowed_gpus) + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu_evaluation" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + time.sleep(poll_seconds) + if output.exists() and any(output.iterdir()): + release_physical_gpu_claim(gpu) + raise RuntimeError(f"nonempty incomplete fold evaluation output: {output}") + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", str(config), "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", str(heldout), + "--expected-cache-manifest-sha256", heldout_hash, + "--input-mode", mode, "--output-dir", str(output), + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", "phase9_h2o_fold_heldout", + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + log_path = state_path.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "type": "fold_evaluation", + "start_utc": utc_now(), "physical_gpu_id": gpu, + "command": command, "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "evaluating_fold" + atomic_json(state_path, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + raise RuntimeError(f"fold evaluation failed: {evaluation_id}") + state["completed_evaluations"].append(evaluation_id) + atomic_json(state_path, state) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--shard", type=int, choices=(0, 1, 2), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--start-before-main-complete", action="store_true") + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("fold shard plan must explicitly exclude official test") + registry_path = Path(plan["fold_training_registry"]) + if sha256(registry_path) != plan["fold_training_registry_sha256"]: + parser.error("fold training registry SHA256 differs") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + conditions = {item["condition"]: item for item in registry["conditions"]} + assigned = registry["shards"][str(args.shard)] + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_fold_shard_state_v1", + "status": "waiting_for_main_training", "shard": args.shard, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_conditions": [], "completed_evaluations": [], "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing shard state belongs to another plan") + state = previous + previous_gpus = tuple(state.get("allowed_physical_gpus", ALLOWED_GPUS)) + if state.get("attempts") and previous_gpus != args.allowed_physical_gpus: + parser.error("cannot change allowed GPUs after this shard has attempted work") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + state["allowed_physical_gpus"] = list(args.allowed_physical_gpus) + state["start_before_main_complete"] = bool(args.start_before_main_complete) + if args.start_before_main_complete: + state["resource_amendment"] = "user_authorized_all_idle_gpus_20260727" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + while not main_training_gate_satisfied(plan, args.start_before_main_complete): + state["status"] = "waiting_for_main_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_root = Path(plan["fold_evaluation_root"]) + for condition_id in assigned: + condition = conditions[condition_id] + if condition_id not in state["completed_conditions"]: + child_state = args.state.parent / "fold_jobs" / f"{condition_id.lower()}.json" + child_state.parent.mkdir(parents=True, exist_ok=True) + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry_path), "--condition", condition_id, + "--state", str(child_state), "--poll-seconds", str(args.poll_seconds), + "--allowed-physical-gpus", + ",".join(str(gpu) for gpu in args.allowed_physical_gpus), + ] + log_path = args.state.parent / f"{condition_id.lower()}_training.log" + attempt = { + "id": condition_id, "type": "fold_training", + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "training_fold" + state["current_condition"] = condition_id + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode: + state["status"] = "failed_fold_training" + state["failure"] = {"condition": condition_id, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_conditions"].append(condition_id) + atomic_json(args.state, state) + try: + run_fold_evaluations( + condition, state, args.state, evaluation_root, args.poll_seconds, + args.allowed_physical_gpus, + ) + except RuntimeError as error: + state["status"] = "failed_fold_evaluation" + state["failure"] = {"condition": condition_id, "reason": str(error)} + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_hot_cache_release_bridge.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_hot_cache_release_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f786874c313bcb438d540641b84f917de27431 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_hot_cache_release_bridge.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Publish and receive the immutable server_new Stage 7 HOT3D cache release.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + cache_step_complete, + sha256, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any] | None: + candidate = Path(path) + if not candidate.is_file(): + return None + return json.loads(candidate.read_text(encoding="utf-8")) + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("publisher_owner") != "server_new" + or plan.get("receiver_owner") != "taku3" + ): + raise ValueError("HOT cache release bridge plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"HOT cache bridge binding differs: {path}") + root = Path(plan["release_root"]) + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("HOT cache release root is not /SSD2") + for item in plan["artifacts"]: + path = Path(item["path"]) + if root not in path.parents or path == root: + raise ValueError("HOT cache release artifact is outside release root") + if Path(plan["staging_root"]).parts[:2] != ("/", "SSD2"): + raise ValueError("HOT cache staging root is not /SSD2") + + +def inventory_tree(root: Path, directory: Path) -> list[dict[str, Any]]: + if not directory.is_dir() or directory.is_symlink(): + raise ValueError(f"HOT release artifact directory differs: {directory}") + records = [] + for path in sorted(directory.rglob("*")): + if path.is_symlink(): + raise ValueError(f"HOT release refuses symlink: {path}") + if not path.is_file(): + continue + records.append({ + "path": str(path.relative_to(root)), "bytes": path.stat().st_size, + "sha256": sha256(path), + }) + return records + + +def validate_primary(plan: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]] | None: + queue_path = Path(plan["producer_queue_state"]["path"]) + primary_path = Path(plan["producer_worker_state"]) + queue = read_json(queue_path) + primary = read_json(primary_path) + if queue is None or primary is None: + return None + if queue.get("status") != "complete": + return None + if ( + queue.get("plan_sha256") != plan["producer_queue_state"]["plan_sha256"] + or queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + ): + raise ValueError("HOT producer queue completion binding differs") + execution_path = Path(plan["cache_execution_plan"]["path"]) + execution = json.loads(execution_path.read_text(encoding="utf-8")) + worker = next(item for item in execution["workers"] if item["id"] == "hot3d") + expected_steps = [item["id"] for item in worker["steps"]] + if ( + primary.get("status") != "complete" + or primary.get("worker") != "hot3d" + or primary.get("plan_sha256") != plan["cache_execution_plan"]["sha256"] + or primary.get("completed_steps") != expected_steps + or primary.get("official_test_used") is not False + or primary.get("h2o_official_validation_used") is not False + ): + raise ValueError("HOT primary worker completion differs") + for step in worker["steps"]: + if step["id"].endswith("resume_verify") and not cache_step_complete(step, True): + raise ValueError(f"HOT deployable resume output differs: {step['id']}") + return queue, primary + + +def publish(plan_path: Path, plan: dict[str, Any]) -> bool: + completion = validate_primary(plan) + if completion is None: + return False + queue, primary = completion + release_path = Path(plan["release_state"]) + if release_path.is_file(): + existing = json.loads(release_path.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return True + raise ValueError("existing HOT cache release differs") + root = Path(plan["release_root"]) + files: list[dict[str, Any]] = [] + artifact_records = [] + for item in plan["artifacts"]: + records = inventory_tree(root, Path(item["path"])) + files.extend(records) + artifact_records.append({ + "id": item["id"], "path": item["path"], + "relative_path": str(Path(item["path"]).relative_to(root)), + "file_count": len(records), + "total_bytes": sum(record["bytes"] for record in records), + }) + relative_paths = [item["path"] for item in files] + if len(relative_paths) != len(set(relative_paths)): + raise ValueError("HOT release inventory contains duplicate paths") + release = { + "schema_version": "phase9_hot_cache_immutable_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), "release_root": str(root.resolve()), + "producer_queue_state": { + "path": str(Path(plan["producer_queue_state"]["path"]).resolve()), + "sha256": sha256(plan["producer_queue_state"]["path"]), + "completed_utc": queue.get("completed_utc"), + }, + "producer_worker_state": { + "path": str(Path(plan["producer_worker_state"]).resolve()), + "sha256": sha256(plan["producer_worker_state"]), + "value": primary, + }, + "artifacts": artifact_records, "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "single_deployable_manifest_writer": "original_resolution_cache_runner", + "live_reverse_sync_forbidden": True, + "read_only_after_receive": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(release_path, release) + os.chmod(release_path, 0o444) + return True + + +def fetch_remote_json(host: str, path: str, timeout: float) -> dict[str, Any] | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if completed.returncode: + return None + try: + value = json.loads(completed.stdout) + except json.JSONDecodeError: + return None + return value if isinstance(value, dict) else None + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or release.get("live_reverse_sync_forbidden") is not True + or release.get("read_only_after_receive") is not True + ): + raise ValueError("HOT immutable release contract differs") + paths = [item["path"] for item in release.get("files", [])] + if ( + len(paths) != len(set(paths)) + or len(paths) != release.get("file_count") + or sum(item["bytes"] for item in release["files"]) != release.get("total_bytes") + ): + raise ValueError("HOT immutable release inventory differs") + for value in paths: + relative = Path(value) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError(f"HOT immutable release path is unsafe: {relative}") + + +def write_external_proxy(plan: dict[str, Any], queue: dict[str, Any] | None) -> None: + state_path = Path(plan["local_worker_state"]) + state = read_json(state_path) + if state is None or state.get("status") == "complete": + return + backup = Path(plan["local_state_backup"]) + if not backup.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(state_path, backup) + os.chmod(backup, 0o444) + if state.get("plan_sha256") != plan["cache_execution_plan"]["sha256"]: + raise ValueError("local HOT proxy state binding differs") + state.update({ + "status": "waiting_for_server_new_immutable_release", + "updated_utc": utc_now(), "external_owner": "server_new", + "external_queue_status": (queue or {}).get("status", "unavailable"), + "external_queue_updated_utc": (queue or {}).get("updated_utc"), + "live_reverse_sync_forbidden": True, + "h2o_official_validation_used": False, "official_test_used": False, + }) + atomic_json(state_path, state) + + +def verify_staging(staging: Path, release: dict[str, Any]) -> None: + for item in release["files"]: + path = staging / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] or sha256(path) != item["sha256"] + ): + raise ValueError(f"received HOT cache file differs: {path}") + + +def install_artifacts(plan: dict[str, Any], release: dict[str, Any], staging: Path) -> list[dict[str, Any]]: + installed = [] + backup_root = Path(plan["receive_backup_root"]) + for item in release["artifacts"]: + destination = Path(item["path"]) + source = staging / item["relative_path"] + backup = backup_root / item["relative_path"] + if destination.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + if backup.exists(): + raise ValueError(f"HOT receive backup already exists: {backup}") + os.replace(destination, backup) + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination) + for path in destination.rglob("*"): + os.chmod(path, 0o555 if path.is_dir() else 0o444) + os.chmod(destination, 0o555) + installed.append({ + "id": item["id"], "path": str(destination.resolve()), + "backup": str(backup.resolve()) if backup.exists() else None, + "file_count": item["file_count"], "total_bytes": item["total_bytes"], + }) + return installed + + +def receive(plan_path: Path, plan: dict[str, Any], state_path: Path) -> bool: + timeout = float(plan["ssh_timeout_seconds"]) + queue = fetch_remote_json( + plan["remote_host"], plan["producer_queue_state"]["path"], timeout, + ) + release = fetch_remote_json(plan["remote_host"], plan["release_state"], timeout) + if release is None: + write_external_proxy(plan, queue) + atomic_json(state_path, { + "schema_version": "phase9_hot_cache_receive_state_v1", + "status": "waiting_for_server_new_immutable_release", + "updated_utc": utc_now(), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "remote_queue_status": (queue or {}).get("status", "unavailable"), + "h2o_official_validation_used": False, "official_test_used": False, + }) + return False + validate_release(plan_path, plan, release) + if (read_json(state_path) or {}).get("status") == "complete": + return True + staging = Path(plan["staging_root"]) + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".release_files.txt" + file_list.write_text("".join(item["path"] + "\n" for item in release["files"]), encoding="utf-8") + command = [ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['remote_host']}:{Path(plan['release_root']).resolve()}/", + f"{staging.resolve()}/", + ] + completed = subprocess.run(command, check=False) + if completed.returncode: + raise RuntimeError(f"HOT immutable rsync failed: {completed.returncode}") + verify_staging(staging, release) + installed = install_artifacts(plan, release, staging) + remote_state = release["producer_worker_state"]["value"] + state_temporary = Path(plan["local_worker_state"]).with_suffix(".remote.tmp") + state_temporary.write_text(json.dumps(remote_state, indent=2) + "\n", encoding="utf-8") + if sha256(state_temporary) != release["producer_worker_state"]["sha256"]: + state_temporary.unlink() + raise ValueError("HOT received worker state differs") + os.replace(state_temporary, plan["local_worker_state"]) + result = { + "schema_version": "phase9_hot_cache_receive_state_v1", + "status": "complete", "completed_utc": utc_now(), + "updated_utc": utc_now(), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), "release_state": plan["release_state"], + "release_file_count": release["file_count"], + "release_total_bytes": release["total_bytes"], "installed": installed, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, result) + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--state", type=Path) + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1 and not args.once: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + state_path = Path(plan["release_state"] if args.role == "publish" else plan["receive_state"]) + if args.state and args.state.resolve() != state_path.resolve(): + parser.error("HOT cache bridge state path differs") + state_path.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{state_path}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + complete = publish(args.plan, plan) if args.role == "publish" else receive( + args.plan, plan, state_path, + ) + if complete or args.once: + print(json.dumps(read_json(state_path) or {"status": "waiting"}, indent=2)) + return + time.sleep(args.poll_seconds) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_hot_prefill_merge_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_hot_prefill_merge_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..0044df9b517929b1658514cfee1e03e7f397a52a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_hot_prefill_merge_queue.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Wait for frozen HOT prefill shards and merge them into the primary cache.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +import time + +from scripts.cache_phase7_hot3d import sha256 +from scripts.merge_phase9_hot_prefill import merge_prefills + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def prefill_complete(path: Path) -> bool: + report = path / "cache_report.json" + if not report.is_file(): + return False + value = json.loads(report.read_text(encoding="utf-8")) + return value.get("status") == "complete" and value.get("mode") == "staged_prefill" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("prefill plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + prefill_dirs = [Path(item["output_dir"]) for item in plan["shards"]] + state = { + "schema_version": "phase9_hot_prefill_merge_queue_v1", + "status": "waiting_for_prefill", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing state belongs to another prefill plan") + if previous.get("status") == "complete": + print(json.dumps(previous, indent=2)) + return + state = previous + while not all(prefill_complete(path) for path in prefill_dirs): + state["status"] = "waiting_for_prefill" + state["ready_shards"] = [str(path) for path in prefill_dirs if prefill_complete(path)] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "merging" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + result = merge_prefills( + Path(plan["target_output_dir"]), prefill_dirs, Path(plan["merge_report"]), + ) + state.update({ + "status": "complete", "updated_utc": utc_now(), + "merge_report": str(Path(plan["merge_report"]).resolve()), + "merge_report_sha256": sha256(Path(plan["merge_report"])), + "linked": result["linked"], + "existing_identical": result["existing_identical"], + }) + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_hot_prefill_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_hot_prefill_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..404aa2ad2ed1207d4650a0580a92722f4073d778 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_hot_prefill_queue.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +"""Run disjoint HOT3D cache prefills, merge them, and resume the canonical writer.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.cache_phase7_hot3d import sha256 +from scripts.merge_phase9_hot_prefill import merge_prefills + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def command_value(command: list[str], option: str) -> str: + try: + return command[command.index(option) + 1] + except (ValueError, IndexError) as error: + raise ValueError(f"prefill command lacks {option}") from error + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("resolution_hw") != [512, 896] + ): + raise ValueError("HOT prefill plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"HOT prefill binding differs: {path}") + source = Path(plan["source_manifest"]["path"]) + if not source.is_file() or sha256(source) != plan["source_manifest"]["sha256"]: + raise ValueError("HOT prefill source manifest differs") + target = Path(plan["target_output_dir"]) + if target.parts[:2] != ("/", "SSD2"): + raise ValueError("HOT prefill target is not on /SSD2") + shards = plan["shards"] + ranges = [tuple(item["candidate_position_range"]) for item in shards] + expected_start = 0 + outputs: set[Path] = set() + for shard, (start, stop) in zip(shards, ranges, strict=True): + if start != expected_start or stop <= start: + raise ValueError("HOT prefill ranges are not a contiguous partition") + expected_start = stop + output = Path(shard["output_dir"]) + if output.parts[:2] != ("/", "SSD2") or output == target or output in outputs: + raise ValueError("HOT prefill output ownership differs") + outputs.add(output) + command = shard["command"] + if ( + command_value(command, "--output-dir") != str(output) + or command_value(command, "--source-manifest") != str(source) + or command_value(command, "--prefill-position-range") != str(start) + or command[command.index("--prefill-position-range") + 2] != str(stop) + or command[command.index("--target-hw") + 1:command.index("--target-hw") + 3] + != ["512", "896"] + or "--decode-all-candidates" not in command + ): + raise ValueError(f"HOT prefill command differs: {shard['id']}") + if expected_start != int(plan["full_candidate_clips"]): + raise ValueError("HOT prefill ranges do not cover the candidate order") + if len({item["id"] for item in shards}) != len(shards): + raise ValueError("HOT prefill shard IDs are not unique") + if Path(plan["state"]).resolve() == plan_path.resolve(): + raise ValueError("HOT prefill state collides with its plan") + + +def prefill_complete(shard: dict[str, Any], plan: dict[str, Any]) -> bool: + output = Path(shard["output_dir"]) + report_path = output / "cache_report.json" + manifest_path = output / "prefill_manifest.jsonl" + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + start, stop = shard["candidate_position_range"] + processed = int(report.get("clips", -1)) + len( + report.get("skipped_no_supervision", []) + ) + return ( + report.get("status") == "complete" + and report.get("mode") == "staged_prefill" + and report.get("official_test_used") is False + and report.get("resolution_hw") == plan["resolution_hw"] + and report.get("candidate_position_range") == [start, stop] + and report.get("full_candidate_clips") == plan["full_candidate_clips"] + and report.get("requested_target_clips") == plan["requested_target_clips"] + and report.get("candidate_source_indices_sha256") + == plan["candidate_source_indices_sha256"] + and report.get("source_manifest", {}).get("sha256") + == plan["source_manifest"]["sha256"] + and report.get("cache_manifest", {}).get("sha256") == sha256(manifest_path) + and processed == stop - start + ) + + +def shard_pid_matches(pid: int, shard: dict[str, Any]) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + start, stop = shard["candidate_position_range"] + return ( + "scripts.cache_phase7_hot3d" in command + and f"--prefill-position-range {start} {stop}" in command + and f"--output-dir {Path(shard['output_dir']).resolve()}" in command + ) + + +def primary_pid_matches(pid: int, plan: dict[str, Any]) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_resolution_cache_queue" in command + and "--worker hot3d" in command + and f"--state {Path(plan['primary_state']).resolve()}" in command + ) + + +def launch(command: list[str], log_path: Path) -> int: + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def runtime_command(shard: dict[str, Any]) -> list[str]: + command = list(shard["command"]) + if Path(shard["output_dir"]).exists() and "--resume" not in command: + command.append("--resume") + return command + + +def primary_status(plan: dict[str, Any]) -> str: + path = Path(plan["primary_state"]) + if not path.is_file(): + return "missing" + state = json.loads(path.read_text(encoding="utf-8")) + if ( + state.get("plan_sha256") != plan["cache_execution_plan"]["sha256"] + or state.get("worker") != "hot3d" + or state.get("official_test_used") is not False + ): + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("HOT prefill state path differs from plan") + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_hot_prefill_queue_v1", + "status": "prefilling", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "shards": {}, "primary": {}, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing HOT prefill state belongs to another plan") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + statuses: dict[str, str] = {} + for shard in plan["shards"]: + identifier = shard["id"] + complete = prefill_complete(shard, plan) + statuses[identifier] = "complete" if complete else "running" + if complete: + continue + previous = state.setdefault("shards", {}).get(identifier, {}) + pid = int(previous.get("pid", -1)) + if not shard_pid_matches(pid, shard): + attempts = int(previous.get("attempts", 0)) + 1 + command = runtime_command(shard) + pid = launch(command, Path(shard["log"])) + state["shards"][identifier] = { + "pid": pid, "attempts": attempts, + "launched_utc": utc_now(), "command": command, + } + state["shard_statuses"] = statuses + state["updated_utc"] = utc_now() + if all(status == "complete" for status in statuses.values()): + break + state["status"] = "prefilling" + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + merge_path = Path(plan["merge_report"]) + if merge_path.is_file(): + merge = json.loads(merge_path.read_text(encoding="utf-8")) + if merge.get("status") != "complete": + parser.error("existing HOT prefill merge report differs") + else: + state["status"] = "merging" + atomic_json(args.state, state) + merge = merge_prefills( + Path(plan["target_output_dir"]), + [Path(item["output_dir"]) for item in plan["shards"]], + merge_path, + ) + state["merge_report"] = { + "path": str(merge_path.resolve()), "sha256": sha256(merge_path), + "linked": merge["linked"], + "existing_identical": merge["existing_identical"], + } + while True: + status = primary_status(plan) + state["primary_status"] = status + if status == "complete": + break + if status.startswith("failed") and status != "failed_resumable": + state["status"] = "failed_primary_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + pid = int(state.setdefault("primary", {}).get("pid", -1)) + if not primary_pid_matches(pid, plan): + command = list(plan["primary_resume_command"]) + pid = launch(command, Path(plan["primary_log"])) + state["primary"] = { + "pid": pid, "launched_utc": utc_now(), "command": command, + } + state["status"] = "merged_waiting_for_canonical_writer" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_last2_candidate_controller.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_last2_candidate_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8a1689c26bf3c9735e969e1bf77208b7844390 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_last2_candidate_controller.py @@ -0,0 +1,510 @@ +#!/usr/bin/env python3 +"""Run or formally reject one ordered DINO Base last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_resolution_evaluation_controller import ( + hard_failure as evaluation_hard_failure, + launch_worker as launch_evaluation_worker, + pid_matches as evaluation_pid_matches, + should_launch as should_launch_evaluation, + worker_status, +) +from scripts.run_phase9_resolution_training_controller import ( + condition_status, + hard_failure as training_hard_failure, + pid_matches as training_pid_matches, +) +from scripts.run_phase9_shared_augmentation_training_controller import ( + launch_worker as launch_training_worker, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("candidate") not in {"5e7", "1e6"} + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("training_job_count") != 7 + or plan.get("evaluation_count") != 25 + or plan.get("evaluation_worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + ): + raise ValueError("last-2 candidate controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"last-2 candidate binding differs: {path}") + + +def admission(plan: dict[str, Any]) -> tuple[str, str, dict[str, Any] | None]: + state_path = Path(plan["admission_controller_state"]) + if not state_path.is_file(): + return "waiting", "upstream_state_missing", None + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed"): + return "failed", "upstream_controller_failed", None + return "waiting", "upstream_controller_incomplete", None + if ( + state.get("plan_sha256") != plan["admission_controller_plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not report_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or report_path.resolve() + != Path(plan["admission_decision_report"]).resolve() + ): + return "failed", "upstream_decision_binding_differs", None + report = read_json(report_path) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + return "failed", "upstream_decision_isolation_differs", None + if plan["candidate"] == "5e7": + admitted = report.get("stage9_preceding_mechanism_gate", {}).get( + "stage9_last2_admitted" + ) is True + reason = ( + "preceding_mechanism_macro_and_worst_improved" + if admitted else "preceding_mechanism_gate_failed" + ) + else: + admitted = ( + report.get("candidate") == "5e7" + and report.get("gate", {}).get("macro_strictly_improved") is True + and report.get("gate", {}).get("worst_domain_strictly_improved") is True + and report.get("gate", {}).get("accepted") is True + ) + reason = "five_e7_strict_gate_passed" if admitted else "five_e7_gate_failed" + return ("admitted" if admitted else "rejected"), reason, report + + +def formal_rejection( + plan: dict[str, Any], reason: str, upstream: dict[str, Any], output: Path, +) -> dict[str, Any]: + return { + "schema_version": "phase9_last2_candidate_decision_v1", + "status": "complete", "candidate": plan["candidate"], + "created_utc": utc_now(), + "decision": f"not_admitted_last2_{plan['candidate']}", + "not_admitted_reason": reason, + "gate": { + "macro_strictly_improved": False, + "worst_domain_strictly_improved": False, + "accepted": False, + }, + "upstream_decision": { + "path": str(Path(plan["admission_decision_report"]).resolve()), + "sha256": sha256(plan["admission_decision_report"]), + }, + "training_started": False, + "evaluation_started": False, + "dino_large_admitted": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("last-2 controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + static_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_last2_candidate_controller_state_v1", + "status": "waiting_for_admission", "candidate": plan["candidate"], + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "machine": machine, + "controller_pid": os.getpid(), + "training_workers": {}, "evaluation_workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != static_hash: + parser.error("existing last-2 controller state differs") + if state.get("machine") != machine: + parser.error("existing last-2 state belongs to another machine") + if state.get("status") in {"complete", "complete_local"}: + print(json.dumps(state, indent=2)) + return + while True: + admission_status, reason, upstream = admission(plan) + if admission_status == "waiting": + state["status"] = "waiting_for_admission" + state["waiting_reason"] = reason + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + if admission_status == "failed": + state["status"] = "failed_admission_binding" + state["failure"] = reason + atomic_json(args.state, state) + raise SystemExit(1) + break + + decision_path = Path(plan["decision_report"]) + if admission_status == "rejected": + assert upstream is not None + if machine != "taku3": + while not decision_path.is_file(): + state["status"] = "waiting_for_central_rejection_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "complete_local" + state["admitted"] = False + state["decision_report"] = { + "path": str(decision_path.resolve()), + "sha256": sha256(decision_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + if not decision_path.exists(): + decision_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json( + decision_path, + formal_rejection(plan, reason, upstream, decision_path), + ) + report = read_json(decision_path) + if ( + report.get("status") != "complete" + or report.get("candidate") != plan["candidate"] + or report.get("decision") + != f"not_admitted_last2_{plan['candidate']}" + or report.get("not_admitted_reason") != reason + or report.get("training_started") is not False + or report.get("evaluation_started") is not False + or report.get("upstream_decision", {}).get("sha256") + != sha256(plan["admission_decision_report"]) + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + state["status"] = "failed_rejection_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["admitted"] = False + state["decision"] = report["decision"] + state["decision_report"] = { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + registry = Path(plan["training_registry"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_last2_training_registry", + "--candidate", plan["candidate"], + "--stage8-controller-plan", plan["stage8_controller_plan"], + "--stage8-controller-state", plan["stage8_controller_state"], + "--last2-plan", plan["last2_plan"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), + "--state", plan["training_registry_state"], + ] + if plan["candidate"] == "1e6": + builder_command.extend(("--five-e7-decision", plan["admission_decision_report"])) + if machine == "taku3": + state["status"] = "building_training_registry" + state["training_builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_training_registry_builder" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + registry_hash = sha256(registry) + registry_payload = read_json(registry) + conditions = [item["condition"] for item in registry_payload["conditions"]] + owners = condition_owners(registry_payload, assignment) + if ( + registry_payload.get("candidate") != plan["candidate"] + or len(conditions) != plan["training_job_count"] + or len(set(conditions)) != len(conditions) + or registry_payload.get("official_test_used") is not False + ): + state["status"] = "failed_training_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_hash + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("training_workers", {}) + training_state_root = Path(plan["training_state_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = training_state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_hash) + statuses[condition] = status + if training_hard_failure(status) or status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["training_workers"].get(condition, {}).get("pid", -1) + ) + if not training_pid_matches(previous_pid, condition, registry): + pid = launch_training_worker( + condition, registry, condition_state, + Path(plan["training_log_root"]) / f"{condition.lower()}.log", + allowed_gpus, + ) + state["training_workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["training_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(training_hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + training_completion = { + "schema_version": "phase9_last2_training_completion_state_v1", + "status": "complete", "candidate": plan["candidate"], + "completed_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "training_registry": str(registry.resolve()), + "training_registry_sha256": registry_hash, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if machine == "taku3": + atomic_json(Path(plan["training_completion_state"]), training_completion) + else: + while not Path(plan["training_completion_state"]).is_file(): + state["status"] = "waiting_for_central_training_aggregate_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + eval_builder = [ + sys.executable, "-m", "scripts.build_phase9_last2_evaluation_plan", + "--candidate", plan["candidate"], + "--training-controller-plan", str(args.plan), + "--training-controller-state", plan["training_completion_state"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["evaluation_worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["evaluation_builder_command"] = eval_builder + atomic_json(args.state, state) + result = subprocess.run(eval_builder, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_hash = sha256(evaluation_plan) + dynamic = read_json(evaluation_plan) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["evaluation_worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = evaluation_hash + state["owned_evaluation_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("evaluation_workers", {}) + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + worker_state = Path(worker["state"]) + status = worker_status(worker_state, evaluation_hash) + statuses[worker["id"]] = status + if not should_launch_evaluation(worker, machine, status): + continue + previous_pid = int( + state["evaluation_workers"].get(worker["id"], {}).get("pid", -1) + ) + if not evaluation_pid_matches( + previous_pid, worker["id"], evaluation_plan, + ): + pid = launch_evaluation_worker( + evaluation_plan, worker, + Path(plan["evaluation_worker_log_root"]) / f"{worker['id']}.log", + ) + state["evaluation_workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["evaluation_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "training_workers": state["training_workers"], + "evaluation_workers": state["evaluation_workers"], + } + if any(evaluation_hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["admitted"] = True + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + if not decision_path.exists(): + command = [ + sys.executable, "-m", "scripts.summarize_phase9_last2_decision", + "--plan", str(evaluation_plan), "--output", str(decision_path), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = read_json(decision_path) + if ( + report.get("status") != "complete" + or report.get("candidate") != plan["candidate"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != evaluation_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["admitted"] = True + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["decision_report"] = { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_last2_resume_training.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_last2_resume_training.py new file mode 100644 index 0000000000000000000000000000000000000000..b169e799e229b526fefbaa79729dba29e9466d86 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_last2_resume_training.py @@ -0,0 +1,859 @@ +#!/usr/bin/env python3 +"""Freeze and supervise the resource-only Stage 9 1e-6 training resume.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import getpass +import hashlib +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import time +from typing import Any + + +SCHEMA = "phase9_last2_1e6_resume_training_amendment_v1" +STATE_SCHEMA = "phase9_last2_1e6_resume_training_supervisor_v1" +CONTROL_SCHEMA = "phase9_last2_1e6_resume_control_v1" +EXTERNAL_ROLES = {"loso_subject2", "loso_subject3", "lofamily_k"} +EXPECTED_ROLES = { + "full", + "loso_subject1", + "loso_subject2", + "loso_subject3", + "lofamily_h", + "lofamily_k", + "lofamily_o", +} +RESUMABLE_STATUSES = { + "missing", + "waiting_for_data", + "waiting_for_prerequisites", + "waiting_for_idle_gpu", + "running", + "failed_resumable", +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: str | Path, value: dict[str, Any]) -> None: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name( + f".{destination.name}.tmp.{os.getpid()}.{time.time_ns()}" + ) + with temporary.open("w", encoding="utf-8") as handle: + json.dump(value, handle, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, destination) + + +def binding(path: str | Path) -> dict[str, str]: + resolved = Path(path).resolve() + if not resolved.is_file(): + raise ValueError(f"binding is missing: {resolved}") + return {"path": str(resolved), "sha256": sha256(resolved)} + + +def validate_binding(value: dict[str, Any], label: str) -> Path: + path = Path(str(value.get("path", ""))) + digest = value.get("sha256") + if not path.is_file() or not isinstance(digest, str) or sha256(path) != digest: + raise ValueError(f"{label} binding differs: {path}") + return path + + +def process_command(pid: int) -> str | None: + try: + return Path(f"/proc/{pid}/cmdline").read_bytes().replace( + b"\0", b" " + ).decode("utf-8", errors="replace") + except (FileNotFoundError, PermissionError, ProcessLookupError): + return None + + +def matching_pids(*needles: str) -> list[int]: + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + command = process_command(int(entry.name)) + if command and all(needle in command for needle in needles): + matches.append(int(entry.name)) + return sorted(matches) + + +def world_adapter_active_pids(formal_root: str) -> list[int]: + runners = ( + "scripts.run_world_adapter_formal_training_v1", + "scripts.control_world_adapter_formal_evaluation_v1", + "scripts.train_phase7_external", + "scripts.evaluate_phase7_external", + ) + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + command = process_command(int(entry.name)) + if command and formal_root in command and any(item in command for item in runners): + matches.append(int(entry.name)) + return sorted(matches) + + +def validate_world_adapter_terminal( + amendment: dict[str, Any], *, require_inactive: bool = True +) -> None: + evidence = amendment["world_adapter_isolation"] + training_path = validate_binding(evidence["training_controller"], "WA training") + evaluation_path = validate_binding( + evidence["evaluation_controller"], "WA evaluation" + ) + report_path = validate_binding(evidence["comparison_report"], "WA comparison") + training = read_json(training_path) + evaluation = read_json(evaluation_path) + report = read_json(report_path) + if ( + training.get("status") != "training_complete_evaluation_locked" + or training.get("training_job_count") != 42 + or training.get("current_stage_complete") != 42 + or training.get("workers") != {} + or training.get("official_test_used") is not False + or evaluation.get("status") != "complete_report_only_no_promotion" + or evaluation.get("evaluation_job_count") != 150 + or evaluation.get("completed_evaluation_jobs") != 150 + or evaluation.get("workers") != {} + or evaluation.get("official_test_used") is not False + or report.get("status") != "complete_report_only_no_promotion" + ): + raise ValueError("World Adapter formal run is not terminal and isolated") + active = world_adapter_active_pids(evidence["formal_root"]) + if require_inactive and active: + raise RuntimeError(f"World Adapter workers are active: {active}") + + +def validate_original_plan_bindings(plan: dict[str, Any]) -> None: + for item in plan.get("bindings", []): + validate_binding(item, "original plan") + + +def role_owners(assignment: dict[str, Any]) -> dict[str, str]: + records = assignment["stage_condition_ownership"]["roles"] + owners = {item["role"]: item["owner"] for item in records} + if set(owners) != EXPECTED_ROLES or len(records) != len(owners): + raise ValueError("original distributed role ownership differs") + return owners + + +def freeze(args: argparse.Namespace) -> None: + output = args.output.resolve() + if output.exists(): + raise ValueError(f"amendment output already exists: {output}") + original_plan_path = args.original_plan.resolve() + original_state_path = args.original_state.resolve() + registry_path = args.training_registry.resolve() + assignment_path = args.distributed_assignment.resolve() + original_plan = read_json(original_plan_path) + original_state = read_json(original_state_path) + registry = read_json(registry_path) + assignment = read_json(assignment_path) + validate_original_plan_bindings(original_plan) + owners = role_owners(assignment) + plan_hash = sha256(original_plan_path) + registry_hash = sha256(registry_path) + if ( + original_plan.get("candidate") != "1e6" + or original_plan.get("training_registry") != str(registry_path) + or original_plan.get("distributed_assignment", {}).get("path") + != str(assignment_path) + or original_plan.get("distributed_assignment", {}).get("sha256") + != sha256(assignment_path) + or original_state.get("plan_sha256") != plan_hash + or original_state.get("training_registry_sha256") != registry_hash + or original_state.get("official_test_used") is not False + or registry.get("status") != "frozen_ready" + or registry.get("candidate") != "1e6" + or registry.get("backbone_learning_rate") != 1e-6 + or registry.get("target_step") != 405000 + or registry.get("official_test_used") is not False + or len(registry.get("conditions", [])) != 7 + ): + raise ValueError("original 1e-6 plan, state, or registry differs") + state_root = Path(original_plan["training_state_root"]).resolve() + mappings = [] + observed_roles = set() + for item in registry["conditions"]: + condition = item["condition"] + role = item["role"] + observed_roles.add(role) + logical_owner = owners[role] + if (role in EXTERNAL_ROLES) != (logical_owner == "server_new"): + raise ValueError(f"unexpected original owner for {role}") + config_path = validate_binding( + {"path": item["config"], "sha256": item["config_sha256"]}, + f"config {condition}", + ) + initialization = validate_binding( + { + "path": item["initialization_checkpoint"], + "sha256": item["initialization_checkpoint_sha256"], + }, + f"initialization {condition}", + ) + mappings.append( + { + "condition": condition, + "role": role, + "logical_owner": logical_owner, + "execution_owner": "taku3", + "priority": 0 if logical_owner == "taku3" else 1, + "config": str(config_path), + "config_sha256": item["config_sha256"], + "initialization_checkpoint": str(initialization), + "initialization_checkpoint_sha256": item[ + "initialization_checkpoint_sha256" + ], + "output_dir": item["output_dir"], + "state": str(state_root / f"{condition.lower()}.json"), + } + ) + if observed_roles != EXPECTED_ROLES: + raise ValueError("1e-6 registry roles differ") + created = utc_now() + value = { + "schema_version": SCHEMA, + "status": "frozen_training_approved", + "created_utc": created, + "candidate": "1e6", + "authorization": { + "status": "approved", + "authorized_by": args.authorized_by, + "authorized_utc": created, + "request": args.authorization_note, + }, + "repository": str(args.repository.resolve()), + "python": str(args.python.resolve()), + "orchestrator": binding(Path(__file__).resolve()), + "original_controller_plan": binding(original_plan_path), + "original_controller_state_after_fail_closed_restart": binding( + original_state_path + ), + "training_registry": binding(registry_path), + "distributed_assignment": binding(assignment_path), + "training_runner": binding(args.training_runner.resolve()), + "model_training_runner": binding(args.model_training_runner.resolve()), + "training_mappings": mappings, + "supervisor_state": str(args.supervisor_state.resolve()), + "training_completion_report": str(args.completion_report.resolve()), + "control_file": str(args.control_file.resolve()), + "scheduling": { + "physical_gpu_allowlist": [0, 1, 2, 3, 4, 5], + "max_concurrent_training_workers": 4, + "minimum_gpu_slots_reserved_for_world_adapter": 2, + "cpu_nice": 10, + "io_class": "best-effort", + "io_priority": 7, + "existing_taku3_conditions_first": True, + }, + "world_adapter_isolation": { + "formal_root": args.world_adapter_formal_root, + "training_controller": binding(args.world_adapter_training_state), + "evaluation_controller": binding(args.world_adapter_evaluation_state), + "comparison_report": binding(args.world_adapter_comparison_report), + "training_jobs_complete": 42, + "evaluation_jobs_complete": 150, + "automatic_model_promotion": False, + }, + "external_owner_preflight": { + "host": "taku-g2", + "checked_utc": args.external_owner_checked_utc, + "matching_1e6_process_count": args.external_owner_process_count, + "canonical_training_states_present": sum( + Path(item["state"]).is_file() + for item in mappings + if item["logical_owner"] == "server_new" + ), + }, + "original_controller_restart_result": { + "status": original_state.get("status"), + "gpu_training_started": False, + "reason": "registry builder rejected existing runs before worker launch", + }, + "resource_schedule_amendment_only": True, + "external_process_preemption_forbidden": True, + "external_processes_preempted": False, + "scientific_fields_changed": [], + "model_changed": False, + "data_changed": False, + "seed_changed": False, + "optimizer_changed": False, + "learning_rate_changed": False, + "horizon_changed": False, + "metric_changed": False, + "selection_gate_changed": False, + "evaluation_started": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + validate_world_adapter_terminal(value) + atomic_json(output, value) + os.chmod(output, 0o444) + print(json.dumps({"path": str(output), "sha256": sha256(output)}, indent=2)) + + +def validate_amendment(path: Path) -> tuple[dict[str, Any], dict[str, Any]]: + amendment = read_json(path) + false_fields = ( + "external_processes_preempted", + "model_changed", + "data_changed", + "seed_changed", + "optimizer_changed", + "learning_rate_changed", + "horizon_changed", + "metric_changed", + "selection_gate_changed", + "evaluation_started", + "h2o_official_validation_used", + "official_test_used", + ) + if ( + amendment.get("schema_version") != SCHEMA + or amendment.get("status") != "frozen_training_approved" + or amendment.get("candidate") != "1e6" + or amendment.get("authorization", {}).get("status") != "approved" + or amendment.get("resource_schedule_amendment_only") is not True + or amendment.get("external_process_preemption_forbidden") is not True + or amendment.get("scientific_fields_changed") != [] + or any(amendment.get(key) is not False for key in false_fields) + ): + raise ValueError("1e-6 resume amendment contract differs") + orchestrator = validate_binding(amendment["orchestrator"], "orchestrator") + if orchestrator.resolve() != Path(__file__).resolve(): + raise ValueError("running orchestrator path differs from amendment") + original_plan_path = validate_binding( + amendment["original_controller_plan"], "original controller plan" + ) + original_state_path = validate_binding( + amendment["original_controller_state_after_fail_closed_restart"], + "original controller state", + ) + registry_path = validate_binding(amendment["training_registry"], "registry") + assignment_path = validate_binding( + amendment["distributed_assignment"], "distributed assignment" + ) + validate_binding(amendment["training_runner"], "training runner") + validate_binding(amendment["model_training_runner"], "model training runner") + original_plan = read_json(original_plan_path) + original_state = read_json(original_state_path) + registry = read_json(registry_path) + assignment = read_json(assignment_path) + validate_original_plan_bindings(original_plan) + owners = role_owners(assignment) + if ( + original_plan.get("candidate") != "1e6" + or original_plan.get("training_registry") != str(registry_path) + or original_state.get("plan_sha256") != sha256(original_plan_path) + or original_state.get("training_registry_sha256") != sha256(registry_path) + or registry.get("status") != "frozen_ready" + or registry.get("candidate") != "1e6" + or registry.get("backbone_learning_rate") != 1e-6 + or registry.get("target_step") != 405000 + or len(registry.get("conditions", [])) != 7 + ): + raise ValueError("bound original 1e-6 artifacts differ") + schedule = amendment.get("scheduling", {}) + if ( + schedule.get("physical_gpu_allowlist") != [0, 1, 2, 3, 4, 5] + or schedule.get("max_concurrent_training_workers") != 4 + or schedule.get("minimum_gpu_slots_reserved_for_world_adapter") != 2 + or schedule.get("cpu_nice") != 10 + or schedule.get("io_priority") != 7 + ): + raise ValueError("1e-6/World Adapter scheduling isolation differs") + preflight = amendment.get("external_owner_preflight", {}) + if ( + preflight.get("host") != "taku-g2" + or preflight.get("matching_1e6_process_count") != 0 + or preflight.get("canonical_training_states_present") != 0 + ): + raise ValueError("external owner preflight does not permit G3 execution") + jobs = {item["condition"]: item for item in registry["conditions"]} + mappings = amendment.get("training_mappings", []) + if len(mappings) != 7 or len({item.get("condition") for item in mappings}) != 7: + raise ValueError("resume mappings must contain seven unique conditions") + state_root = Path(original_plan["training_state_root"]).resolve() + for mapping in mappings: + condition = mapping.get("condition") + job = jobs.get(condition) + role = mapping.get("role") + if ( + job is None + or role != job.get("role") + or mapping.get("logical_owner") != owners.get(role) + or mapping.get("execution_owner") != "taku3" + or mapping.get("config") != job.get("config") + or mapping.get("config_sha256") != job.get("config_sha256") + or mapping.get("initialization_checkpoint") + != job.get("initialization_checkpoint") + or mapping.get("output_dir") != job.get("output_dir") + or Path(mapping.get("state", "")).resolve() + != state_root / f"{condition.lower()}.json" + ): + raise ValueError(f"resume mapping differs: {condition}") + validate_binding( + {"path": mapping["config"], "sha256": mapping["config_sha256"]}, + f"mapped config {condition}", + ) + validate_world_adapter_terminal(amendment, require_inactive=False) + return amendment, registry + + +def queue_pids(mapping: dict[str, Any], registry: Path) -> list[int]: + return matching_pids( + "scripts.run_phase9_unified_train_queue", + f"--condition {mapping['condition']}", + str(registry.resolve()), + str(Path(mapping["state"]).resolve()), + ) + + +def training_child_pids(mapping: dict[str, Any]) -> list[int]: + return matching_pids( + "scripts.train_phase7_external", + f"--output-dir {mapping['output_dir']}", + f"--config {mapping['config']}", + ) + + +def state_status(mapping: dict[str, Any], registry_hash: str) -> str: + path = Path(mapping["state"]) + if not path.is_file(): + return "missing" + try: + value = read_json(path) + except (OSError, json.JSONDecodeError): + return "unreadable" + if ( + value.get("queue_sha256") != registry_hash + or value.get("condition") != mapping["condition"] + or value.get("official_test_used") is not False + ): + return "failed_state_binding" + return str(value.get("status", "missing")) + + +def control_requested(amendment_path: Path, amendment: dict[str, Any]) -> bool: + path = Path(amendment["control_file"]) + if not path.is_file(): + return False + value = read_json(path) + return ( + value.get("schema_version") == CONTROL_SCHEMA + and value.get("amendment_sha256") == sha256(amendment_path) + and value.get("status") == "pause_requested" + ) + + +def terminate_queues( + amendment: dict[str, Any], registry: Path, grace_seconds: float = 30.0 +) -> dict[str, Any]: + matched = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + signals = [] + for condition, pids in matched.items(): + for pid in pids: + try: + os.killpg(pid, signal.SIGTERM) + signals.append({"condition": condition, "pid": pid, "signal": "SIGTERM"}) + except ProcessLookupError: + pass + deadline = time.monotonic() + grace_seconds + while time.monotonic() < deadline: + remaining = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + if not any(remaining.values()): + return {"matched": matched, "signals": signals, "remaining": remaining} + time.sleep(0.5) + remaining = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + return {"matched": matched, "signals": signals, "remaining": remaining} + + +def launch_worker(amendment: dict[str, Any], mapping: dict[str, Any]) -> tuple[int, list[str]]: + schedule = amendment["scheduling"] + command = [ + "ionice", + "-c", + "2", + "-n", + str(schedule["io_priority"]), + "nice", + "-n", + str(schedule["cpu_nice"]), + amendment["python"], + "-m", + "scripts.run_phase9_unified_train_queue", + "--queue", + amendment["training_registry"]["path"], + "--condition", + mapping["condition"], + "--state", + mapping["state"], + "--poll-seconds", + "30", + "--allowed-physical-gpus", + ",".join(str(item) for item in schedule["physical_gpu_allowlist"]), + ] + log_path = Path(amendment["supervisor_state"]).parent / "training_logs" / ( + f"{mapping['condition'].lower()}.log" + ) + log_path.parent.mkdir(parents=True, exist_ok=True) + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, + cwd=amendment["repository"], + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + text=True, + start_new_session=True, + ) + return process.pid, command + + +def ensure_workers( + amendment: dict[str, Any], registry: dict[str, Any], state: dict[str, Any] +) -> dict[str, str]: + registry_path = Path(amendment["training_registry"]["path"]) + registry_hash = amendment["training_registry"]["sha256"] + mappings = sorted( + amendment["training_mappings"], key=lambda item: (item["priority"], item["condition"]) + ) + statuses = { + mapping["condition"]: state_status(mapping, registry_hash) + for mapping in mappings + } + terminal = { + condition: status + for condition, status in statuses.items() + if status not in RESUMABLE_STATUSES and status != "complete" + } + if terminal: + raise RuntimeError(f"terminal training state: {terminal}") + active = [] + for mapping in mappings: + pids = queue_pids(mapping, registry_path) + if len(pids) > 1: + raise RuntimeError(f"multiple queue writers: {mapping['condition']}={pids}") + if pids: + active.append(mapping["condition"]) + record = state.setdefault("workers", {}).setdefault(mapping["condition"], {}) + record["pid"] = pids[0] + record["adopted_utc"] = utc_now() + maximum = amendment["scheduling"]["max_concurrent_training_workers"] + slots = maximum - len(active) + if slots < 0: + raise RuntimeError(f"1e-6 worker cap exceeded: {len(active)} > {maximum}") + jobs = {item["condition"]: item for item in registry["conditions"]} + for mapping in mappings: + if slots <= 0 or statuses[mapping["condition"]] == "complete": + continue + if mapping["condition"] in active: + continue + children = training_child_pids(mapping) + if children: + raise RuntimeError( + f"orphan training child blocks relaunch: {mapping['condition']}={children}" + ) + job = jobs[mapping["condition"]] + if mapping["config_sha256"] != job["config_sha256"]: + raise ValueError(f"config changed before launch: {mapping['condition']}") + record = state.setdefault("workers", {}).setdefault( + mapping["condition"], {"launches": 0} + ) + launches = int(record.get("launches", 0)) + if launches >= 3: + raise RuntimeError(f"relaunch limit reached: {mapping['condition']}") + pid, command = launch_worker(amendment, mapping) + record.update( + { + "pid": pid, + "launches": launches + 1, + "launched_utc": utc_now(), + "command": command, + } + ) + active.append(mapping["condition"]) + slots -= 1 + print(f"launched {mapping['condition']} pid={pid}", flush=True) + state["active_conditions"] = active + state["reserved_gpu_slots"] = 6 - len(active) + if state["reserved_gpu_slots"] < amendment["scheduling"][ + "minimum_gpu_slots_reserved_for_world_adapter" + ]: + raise RuntimeError("World Adapter GPU reservation was violated") + return statuses + + +def validate_completion( + amendment_path: Path, amendment: dict[str, Any], registry: dict[str, Any] +) -> dict[str, Any]: + registry_hash = amendment["training_registry"]["sha256"] + jobs = {item["condition"]: item for item in registry["conditions"]} + completed = [] + for mapping in amendment["training_mappings"]: + state_path = Path(mapping["state"]) + value = read_json(state_path) + job = jobs[mapping["condition"]] + marker = value.get("last_completed", {}) + checkpoint = Path(str(marker.get("checkpoint", ""))) + if ( + value.get("status") != "complete" + or value.get("queue_sha256") != registry_hash + or value.get("condition") != mapping["condition"] + or value.get("official_test_used") is not False + or marker.get("completed_step") != 405000 + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or queue_pids(mapping, Path(amendment["training_registry"]["path"])) + or training_child_pids(mapping) + ): + raise ValueError(f"terminal training output differs: {mapping['condition']}") + completed.append( + { + "condition": mapping["condition"], + "role": mapping["role"], + "logical_owner": mapping["logical_owner"], + "execution_owner": "taku3", + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": marker["checkpoint_sha256"], + "state": str(state_path.resolve()), + "state_sha256": sha256(state_path), + } + ) + return { + "schema_version": "phase9_last2_1e6_resume_training_completion_v1", + "status": "training_complete_evaluation_not_started", + "completed_utc": utc_now(), + "amendment": {"path": str(amendment_path), "sha256": sha256(amendment_path)}, + "training_registry": amendment["training_registry"], + "conditions": completed, + "condition_count": 7, + "evaluation_started": False, + "scientific_fields_changed": [], + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def run(args: argparse.Namespace) -> None: + amendment_path = args.amendment.resolve() + amendment, registry = validate_amendment(amendment_path) + state_path = args.state.resolve() + if state_path != Path(amendment["supervisor_state"]).resolve(): + raise ValueError("supervisor state path differs from amendment") + state_path.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{state_path}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state = { + "schema_version": STATE_SCHEMA, + "status": "starting", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "amendment": str(amendment_path), + "amendment_sha256": sha256(amendment_path), + "supervisor_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if state_path.is_file(): + previous = read_json(state_path) + if previous.get("amendment_sha256") != sha256(amendment_path): + raise ValueError("existing supervisor state belongs to another amendment") + if previous.get("status") == "complete": + print(json.dumps(previous, indent=2)) + return + state = previous + state["supervisor_pid"] = os.getpid() + state["resumed_utc"] = utc_now() + while True: + validate_world_adapter_terminal(amendment, require_inactive=False) + world_adapter_pids = world_adapter_active_pids( + amendment["world_adapter_isolation"]["formal_root"] + ) + if world_adapter_pids: + termination = terminate_queues( + amendment, Path(amendment["training_registry"]["path"]) + ) + state["status"] = "paused_for_world_adapter" + state["world_adapter_active_pids"] = world_adapter_pids + state["world_adapter_pause"] = termination + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if any(termination["remaining"].values()): + raise RuntimeError( + "some queue workers survived the World Adapter priority pause" + ) + return + if control_requested(amendment_path, amendment): + termination = terminate_queues( + amendment, Path(amendment["training_registry"]["path"]) + ) + state["status"] = "paused_by_manual_request" + state["pause"] = termination + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if any(termination["remaining"].values()): + raise RuntimeError("some queue workers survived the pause request") + return + statuses = ensure_workers(amendment, registry, state) + state["training_statuses"] = statuses + state["status"] = "training" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if all(status == "complete" for status in statuses.values()): + report = validate_completion(amendment_path, amendment, registry) + report_path = Path(amendment["training_completion_report"]) + if report_path.is_file(): + raise ValueError(f"completion report already exists: {report_path}") + atomic_json(report_path, report) + os.chmod(report_path, 0o444) + state["status"] = "complete" + state["training_completion_report"] = binding(report_path) + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + print(json.dumps(state, indent=2)) + return + time.sleep(args.poll_seconds) + + +def control(args: argparse.Namespace) -> None: + amendment_path = args.amendment.resolve() + amendment, _ = validate_amendment(amendment_path) + path = Path(amendment["control_file"]) + value = { + "schema_version": CONTROL_SCHEMA, + "status": "pause_requested" if args.action == "pause" else "cleared", + "created_utc": utc_now(), + "requested_by": f"{getpass.getuser()}@{socket.gethostname()}", + "amendment": str(amendment_path), + "amendment_sha256": sha256(amendment_path), + "note": args.note, + } + atomic_json(path, value) + print(json.dumps({"path": str(path), "sha256": sha256(path)}, indent=2)) + + +def status(args: argparse.Namespace) -> None: + amendment, registry = validate_amendment(args.amendment.resolve()) + registry_hash = amendment["training_registry"]["sha256"] + statuses = { + item["condition"]: state_status(item, registry_hash) + for item in amendment["training_mappings"] + } + active = { + item["condition"]: queue_pids( + item, Path(amendment["training_registry"]["path"]) + ) + for item in amendment["training_mappings"] + } + print( + json.dumps( + { + "amendment_sha256": sha256(args.amendment), + "training_statuses": statuses, + "active_queue_pids": active, + "world_adapter_active_pids": world_adapter_active_pids( + amendment["world_adapter_isolation"]["formal_root"] + ), + "target_step": registry["target_step"], + }, + indent=2, + ) + ) + + +def parser() -> argparse.ArgumentParser: + result = argparse.ArgumentParser() + subparsers = result.add_subparsers(dest="command", required=True) + freeze_parser = subparsers.add_parser("freeze") + freeze_parser.add_argument("--original-plan", type=Path, required=True) + freeze_parser.add_argument("--original-state", type=Path, required=True) + freeze_parser.add_argument("--training-registry", type=Path, required=True) + freeze_parser.add_argument("--distributed-assignment", type=Path, required=True) + freeze_parser.add_argument("--repository", type=Path, required=True) + freeze_parser.add_argument("--python", type=Path, required=True) + freeze_parser.add_argument("--training-runner", type=Path, required=True) + freeze_parser.add_argument("--model-training-runner", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-formal-root", required=True) + freeze_parser.add_argument("--world-adapter-training-state", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-evaluation-state", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-comparison-report", type=Path, required=True) + freeze_parser.add_argument("--external-owner-checked-utc", required=True) + freeze_parser.add_argument("--external-owner-process-count", type=int, required=True) + freeze_parser.add_argument("--authorized-by", required=True) + freeze_parser.add_argument("--authorization-note", required=True) + freeze_parser.add_argument("--supervisor-state", type=Path, required=True) + freeze_parser.add_argument("--completion-report", type=Path, required=True) + freeze_parser.add_argument("--control-file", type=Path, required=True) + freeze_parser.add_argument("--output", type=Path, required=True) + freeze_parser.set_defaults(function=freeze) + run_parser = subparsers.add_parser("run") + run_parser.add_argument("--amendment", type=Path, required=True) + run_parser.add_argument("--state", type=Path, required=True) + run_parser.add_argument("--poll-seconds", type=float, default=30.0) + run_parser.set_defaults(function=run) + status_parser = subparsers.add_parser("status") + status_parser.add_argument("--amendment", type=Path, required=True) + status_parser.set_defaults(function=status) + control_parser = subparsers.add_parser("control") + control_parser.add_argument("action", choices=("pause", "resume")) + control_parser.add_argument("--amendment", type=Path, required=True) + control_parser.add_argument("--note") + control_parser.set_defaults(function=control) + return result + + +def main() -> None: + args = parser().parse_args() + if getattr(args, "poll_seconds", 30.0) < 1: + raise ValueError("poll interval must be at least one second") + args.function(args) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_cache_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..880a58c8892f00aa6bfa02fb81d2bf8683a0808c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_cache_queue.py @@ -0,0 +1,372 @@ +#!/usr/bin/env python3 +"""Run one winner-gated, resumable Phase 9 resolution cache worker.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def validate_plan_bindings(plan: dict[str, Any]) -> None: + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution execution plan lacks official-data isolation") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution plan binding differs: {path}") + validate_execution_contract(plan) + + +def validate_execution_contract(plan: dict[str, Any]) -> None: + root = Path(plan["physical_root"]) + output_directories = [Path(path) for path in plan["output_directories"]] + if len(output_directories) != len(set(output_directories)): + raise ValueError("resolution output directories are not unique") + if any(path != root and root not in path.parents for path in output_directories): + raise ValueError("resolution output directory is outside the physical root") + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("resolution physical root is not on /SSD2") + + worker_ids: set[str] = set() + owned_outputs: dict[Path, str] = {} + cache_steps: list[dict[str, Any]] = [] + for worker in plan["workers"]: + worker_id = worker["id"] + if worker_id in worker_ids: + raise ValueError(f"duplicate resolution worker: {worker_id}") + worker_ids.add(worker_id) + if Path(worker["state"]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution worker state is not on /SSD2: {worker_id}") + step_ids: set[str] = set() + for step in worker["steps"]: + if step["id"] in step_ids: + raise ValueError(f"duplicate step in resolution worker: {worker_id}") + step_ids.add(step["id"]) + if step["kind"] in {"cache", "sidecar"}: + output = Path(step["output_dir"]) + owner = owned_outputs.setdefault(output, worker_id) + if owner != worker_id: + raise ValueError(f"resolution output has multiple writers: {output}") + if step["kind"] == "cache": + cache_steps.append(step) + for command_name in ("start_command", "resume_command"): + command = step[command_name] + if command and not any( + command[index:index + 3] == ["--target-hw", "512", "896"] + for index in range(len(command) - 2) + ): + raise ValueError( + f"resolution cache command lacks 512x896 target: " + f"{worker_id}/{step['id']}/{command_name}" + ) + + cache_contracts = { + (item["manifest"], item["report"], int(item["clips"])) + for item in plan["caches"] + } + step_contracts = { + (step["manifest"], step["report"], int(step["expected_clips"])) + for step in cache_steps + } + if not cache_contracts <= step_contracts: + raise ValueError("resolution audit cache lacks a matching writer step") + + +def selection_winner(plan: dict[str, Any]) -> dict[str, Any] | None: + state_path = Path(plan["selection_state"]) + report_path = Path(plan["selection_report"]) + if not state_path.is_file() or not report_path.is_file(): + return None + state = json.loads(state_path.read_text(encoding="utf-8")) + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or state.get("winner") != report.get("winner") + or state.get("winner_checkpoint") != report.get("winner_checkpoint") + ): + return None + checkpoint = Path(report["winner_checkpoint"]["path"]) + config = Path(report["winner_config"]["path"]) + if ( + not checkpoint.is_file() + or sha256(checkpoint) != report["winner_checkpoint"]["sha256"] + or not config.is_file() + or sha256(config) != report["winner_config"]["sha256"] + ): + return None + return { + "winner": report["winner"], + "winner_checkpoint": report["winner_checkpoint"], + "winner_config": report["winner_config"], + } + + +def ensure_admission(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any] | None: + admission_path = Path(plan["admission_state"]) + admission_path.parent.mkdir(parents=True, exist_ok=True) + lock_path = Path(f"{admission_path}.lock") + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if admission_path.is_file(): + admission = json.loads(admission_path.read_text(encoding="utf-8")) + if ( + admission.get("status") != "complete" + or admission.get("plan_sha256") != sha256(plan_path) + or admission.get("official_test_used") is not False + ): + raise ValueError("resolution admission state differs") + return admission + winner = selection_winner(plan) + if winner is None: + return None + root = Path(plan["physical_root"]) + if root.exists() or any(Path(path).exists() for path in plan["output_directories"]): + raise ValueError("resolution output exists before admission") + available_gib = shutil.disk_usage(root.parent).free / (1024 ** 3) + if available_gib < float(plan["minimum_available_gib"]): + raise ValueError("SSD2 free space is below the frozen admission minimum") + admission = { + "schema_version": "phase9_resolution_admission_v1", + "status": "complete", + "admitted_utc": utc_now(), + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "scientific_stage_admitted": True, + "trigger": "frozen_full_data_640_winner_complete", + "available_gib": available_gib, + **winner, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(admission_path, admission) + return admission + + +def cache_step_complete(step: dict[str, Any], require_resume: bool) -> bool: + report_path = Path(step["report"]) + manifest_path = Path(step["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + count = report.get("cached_clips", report.get("clips")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and tuple(report.get("resolution_hw", ())) == (512, 896) + and report.get("source_manifest", {}).get("sha256") + == step["source_manifest_sha256"] + and report.get("cache_manifest", {}).get("sha256") == sha256(manifest_path) + and int(count) == int(step["expected_clips"]) + and (not require_resume or report.get("resume_invocation") is True) + ) + + +def sidecar_step_complete(step: dict[str, Any]) -> bool: + report_path = Path(step["report"]) + manifest_path = Path(step["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("base_cache_manifest", {}).get("sha256") + == sha256(step["base_manifest"]) + and report.get("augmented_cache_manifest", {}).get("sha256") + == sha256(manifest_path) + and int(report.get("clips", -1)) == int(step["expected_clips"]) + and report.get("right_valid_joint_count") == 0 + and float(report.get("root_norm_max_mm", 1.0)) < 1e-4 + and ( + not step.get("require_resume") + or report.get("resume_invocation") is True + ) + ) + + +def multifold_step_complete(step: dict[str, Any]) -> bool: + path = Path(step["index"]) + if not path.is_file(): + return False + index = json.loads(path.read_text(encoding="utf-8")) + return ( + index.get("status") == "complete" + and index.get("official_test_used") is False + and index.get("h2o_official_validation_used") is False + and index.get("source_cache_manifest", {}).get("sha256") + == sha256(step["source_manifest"]) + and len(index.get("folds", [])) == 6 + ) + + +def step_complete(step: dict[str, Any]) -> bool: + if step["kind"] == "cache": + return cache_step_complete(step, bool(step.get("require_resume"))) + if step["kind"] == "sidecar": + return sidecar_step_complete(step) + if step["kind"] == "multifold": + return multifold_step_complete(step) + raise ValueError(f"unsupported resolution step kind: {step['kind']}") + + +def runtime_command(step: dict[str, Any]) -> list[str]: + if step["kind"] == "cache": + output = Path(step["output_dir"]) + command = step["resume_command"] if output.exists() else step["start_command"] + elif step["kind"] == "sidecar": + output = Path(step["output_dir"]) + command = step["resume_command"] if output.exists() else step["start_command"] + else: + command = step["command"] + base_hash = sha256(step["base_manifest"]) if step.get("base_manifest") else None + return [base_hash if token == "{BASE_CACHE_SHA256}" else token for token in command] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan_bindings(plan) + except ValueError as error: + parser.error(str(error)) + workers = {worker["id"]: worker for worker in plan["workers"]} + if args.worker not in workers: + parser.error(f"unknown resolution worker: {args.worker}") + worker = workers[args.worker] + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("worker state path differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + state_lock = Path(f"{args.state}.lock").open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + plan_hash = sha256(args.plan) + state = { + "schema_version": "phase9_resolution_cache_worker_state_v1", + "status": "waiting_for_640_winner", + "worker": args.worker, + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "started_utc": utc_now(), + "updated_utc": utc_now(), + "completed_steps": [], + "attempts": [], + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash or previous.get("worker") != args.worker: + parser.error("existing resolution state belongs to another plan/worker") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + try: + admission = ensure_admission(args.plan, plan) + except ValueError as error: + state["status"] = "failed_admission" + state["failure"] = str(error) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + if admission is not None: + break + state["status"] = "waiting_for_640_winner" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["admission_state"] = plan["admission_state"] + state["admission_state_sha256"] = sha256(plan["admission_state"]) + state["winner"] = admission["winner"] + state["winner_checkpoint"] = admission["winner_checkpoint"] + state["winner_config"] = admission["winner_config"] + atomic_json(args.state, state) + for step in worker["steps"]: + if step["id"] in state["completed_steps"] and step_complete(step): + continue + if step.get("always_run") is not True and step_complete(step): + state["completed_steps"].append(step["id"]) + atomic_json(args.state, state) + continue + command = runtime_command(step) + log_path = args.state.parent / f"{args.worker}_{step['id']}.log" + attempt = { + "step": step["id"], "kind": step["kind"], + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_step"] = step["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ, PYTHONPATH=str(Path.cwd())) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not step_complete(step): + state["status"] = "failed_resumable" + state["failure"] = { + "step": step["id"], "returncode": result.returncode, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + if step["id"] not in state["completed_steps"]: + state["completed_steps"].append(step["id"]) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_cache_supervisor.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_cache_supervisor.py new file mode 100644 index 0000000000000000000000000000000000000000..8eddded62d805d7d1f45f69aa0d13b3d7ad675e9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_cache_supervisor.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Supervise owner-bound Stage 7 cache workers and the readiness finalizer.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def process_matches(tokens: list[str]) -> list[int]: + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (OSError, UnicodeDecodeError): + continue + if all(token in command for token in tokens): + matches.append(int(entry.name)) + return sorted(matches) + + +def read_json(path: str | Path) -> dict[str, Any] | None: + candidate = Path(path) + if not candidate.is_file(): + return None + return json.loads(candidate.read_text(encoding="utf-8")) + + +def latest_progress(path: Path) -> dict[str, Any] | None: + if not path.is_file(): + return None + with path.open("rb") as handle: + handle.seek(0, os.SEEK_END) + size = handle.tell() + handle.seek(max(0, size - 256 * 1024)) + lines = handle.read().decode("utf-8", errors="replace").splitlines() + for line in reversed(lines): + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and any( + key in value for key in ("processed", "decoded", "cached", "clips") + ): + return value + return None + + +def classify_failure(state: dict[str, Any], transient_returncodes: set[int]) -> str: + status = str(state.get("status", "missing")) + if not status.startswith("failed"): + return "not_failed" + if status != "failed_resumable": + return "terminal_failure" + returncode = state.get("failure", {}).get("returncode") + if returncode == 0: + return "terminal_contract_mismatch" + if returncode in transient_returncodes: + return "known_transient_resumable" + return "terminal_unregistered_resumable" + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("owner") != "taku3" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution supervisor plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution supervisor binding differs: {path}") + execution = plan["cache_execution_plan"] + path = Path(execution["path"]) + if not path.is_file() or sha256(path) != execution["sha256"]: + raise ValueError("resolution supervisor cache execution plan differs") + ids = [worker["id"] for worker in plan["local_workers"]] + if len(ids) != len(set(ids)) or "hot3d" in ids: + raise ValueError("resolution supervisor local ownership differs") + if Path(plan["disk"]["path"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution supervisor disk is not /SSD2") + if Path(plan["state"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution supervisor state is not /SSD2") + + +def launch(command: list[str], log_path: Path) -> int: + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ, PYTHONPATH=str(Path.cwd())), + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def local_worker_snapshot( + worker: dict[str, Any], *, plan_hash: str, now: float, + transient_returncodes: set[int], +) -> dict[str, Any]: + state_path = Path(worker["state"]) + state = read_json(state_path) + controllers = process_matches(worker["process_tokens"]) + result: dict[str, Any] = { + "id": worker["id"], "owner": "taku3", + "state": str(state_path.resolve()), "controller_pids": controllers, + } + if state is None: + result.update(status="missing", classification="missing_state") + return result + if ( + state.get("worker") != worker["id"] + or state.get("plan_sha256") != plan_hash + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + result.update(status=state.get("status"), classification="terminal_binding_mismatch") + return result + attempt = state.get("attempts", [])[-1] if state.get("attempts") else {} + log_path = Path(attempt["log"]) if attempt.get("log") else None + state_mtime = state_path.stat().st_mtime + result.update({ + "status": state.get("status"), "current_step": state.get("current_step"), + "completed_steps": state.get("completed_steps", []), + "state_sha256": sha256(state_path), + "state_heartbeat_age_seconds": round(max(0.0, now - state_mtime), 3), + "classification": classify_failure(state, transient_returncodes), + "log": str(log_path.resolve()) if log_path else None, + "log_mtime_age_seconds": ( + round(max(0.0, now - log_path.stat().st_mtime), 3) + if log_path and log_path.is_file() else None + ), + "progress": latest_progress(log_path) if log_path else None, + }) + return result + + +def remote_json(host: str, path: str, timeout: float) -> dict[str, Any] | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if completed.returncode: + return None + try: + value = json.loads(completed.stdout) + except json.JSONDecodeError: + return None + return value if isinstance(value, dict) else None + + +def external_snapshot(external: dict[str, Any]) -> dict[str, Any]: + queue = remote_json( + external["host"], external["queue_state"], external["ssh_timeout_seconds"], + ) + release = remote_json( + external["host"], external["release_state"], external["ssh_timeout_seconds"], + ) + if queue is None: + return { + "id": external["id"], "owner": external["owner"], + "status": "remote_unreachable_or_state_missing", + "classification": "external_monitor_alert", + } + status = str(queue.get("status", "missing")) + if release and release.get("status") == "complete_immutable_release": + display_status = "immutable_release_ready" + elif status == "complete": + display_status = "waiting_for_immutable_release" + else: + display_status = "waiting_for_server_new_immutable_release" + return { + "id": external["id"], "owner": external["owner"], + "status": display_status, "queue_status": status, + "queue_updated_utc": queue.get("updated_utc"), + "shard_statuses": queue.get("shard_statuses", {}), + "release_status": release.get("status") if release else "missing", + "classification": "external_owned_monitor_only", + } + + +def alarms_for( + workers: list[dict[str, Any]], *, log_stale_seconds: float, +) -> list[dict[str, Any]]: + alarms = [] + for worker in workers: + classification = worker.get("classification") + if classification and classification.startswith("terminal"): + alarms.append({"worker": worker["id"], "reason": classification}) + if ( + worker.get("status") == "running" + and not worker.get("controller_pids") + ): + alarms.append({"worker": worker["id"], "reason": "running_state_without_controller"}) + age = worker.get("log_mtime_age_seconds") + if ( + worker.get("status") == "running" and age is not None + and age > log_stale_seconds + ): + alarms.append({"worker": worker["id"], "reason": "stale_progress_log", "age_seconds": age}) + return alarms + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1 and not args.once: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("resolution supervisor state path differs") + execution_hash = plan["cache_execution_plan"]["sha256"] + transient = {int(value) for value in plan["known_transient_returncodes"]} + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + existing = read_json(args.state) or {} + recovery_attempts = dict(existing.get("recovery_attempts", {})) + while True: + now = time.time() + local = [ + local_worker_snapshot( + worker, plan_hash=execution_hash, now=now, + transient_returncodes=transient, + ) + for worker in plan["local_workers"] + ] + recoveries = [] + for worker, snapshot in zip(plan["local_workers"], local, strict=True): + restartable = ( + snapshot["classification"] == "known_transient_resumable" + or snapshot["status"] in worker.get("restartable_statuses", []) + ) + attempts = int(recovery_attempts.get(worker["id"], 0)) + if ( + restartable and not snapshot["controller_pids"] + and attempts < int(plan["max_exact_resume_attempts"]) + ): + pid = launch(worker["resume_command"], Path(worker["supervisor_log"])) + attempts += 1 + recovery_attempts[worker["id"]] = attempts + recoveries.append({ + "worker": worker["id"], "pid": pid, "attempt": attempts, + "kind": "exact_frozen_queue_resume", "launched_utc": utc_now(), + }) + external = [external_snapshot(item) for item in plan["external_workers"]] + finalizer = plan["finalizer"] + finalizer_pids = process_matches(finalizer["process_tokens"]) + readiness = read_json(finalizer["state"]) + blocking_failure = any( + str(worker.get("status", "")).startswith("failed") for worker in local + ) + finalizer_recovery = None + if ( + not finalizer_pids + and (readiness or {}).get("status") != "complete" + and not blocking_failure + ): + pid = launch(finalizer["command"], Path(finalizer["log"])) + finalizer_pids = [pid] + finalizer_recovery = { + "pid": pid, "kind": "readiness_finalizer_restart", + "launched_utc": utc_now(), + } + disk = shutil.disk_usage(plan["disk"]["path"]) + disk_record = { + "path": plan["disk"]["path"], + "free_gib": round(disk.free / (1024 ** 3), 3), + "total_gib": round(disk.total / (1024 ** 3), 3), + } + alarms = alarms_for( + local, log_stale_seconds=float(plan["log_stale_seconds"]), + ) + if disk_record["free_gib"] < float(plan["disk"]["minimum_free_gib"]): + alarms.append({"worker": "disk", "reason": "minimum_free_space_breached"}) + state = { + "schema_version": "phase9_resolution_cache_supervisor_state_v1", + "status": "alert" if alarms else "monitoring", + "updated_utc": utc_now(), "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), "local_workers": local, + "external_workers": external, + "readiness": { + "status": (readiness or {}).get("status", "missing"), + "updated_utc": (readiness or {}).get("updated_utc"), + "finalizer_pids": finalizer_pids, + "recovery": finalizer_recovery, + }, + "disk": disk_record, "alarms": alarms, + "recoveries_this_poll": recoveries, + "recovery_attempts": recovery_attempts, + "max_exact_resume_attempts": plan["max_exact_resume_attempts"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + if args.once: + print(json.dumps(state, indent=2)) + return + time.sleep(args.poll_seconds) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_evaluation_controller.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..64ea48925512f43aa2084947f82545ea83ac8f44 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_evaluation_controller.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""Supervise Stage 7 evaluation workers and freeze the resolution decision.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or plan.get("evaluation_count") != 25 + or plan.get("worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + ): + raise ValueError("resolution evaluation controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution evaluation binding differs: {path}") + + +def training_complete(plan: dict[str, Any]) -> bool: + path = Path( + plan.get("training_controller_states", {}).get( + "taku3", plan["training_controller_state"] + ) + ) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + registry = Path(state.get("training_registry", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["training_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and registry.is_file() + and state.get("training_registry_sha256") == sha256(registry) + ) + + +def pid_matches(pid: int, worker: str, evaluation_plan: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_resolution_evaluation_worker" in command + and f"--worker {worker}" in command + and str(evaluation_plan.resolve()) in command + ) + + +def worker_status(path: Path, plan_sha256: str) -> str: + if not path.is_file(): + return "missing" + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_sha256: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def hard_failure(status: str) -> bool: + return status.startswith("failed") and status != "failed_resumable" + + +def should_launch(worker: dict[str, Any], machine: str, status: str) -> bool: + return ( + worker.get("owner") == machine + and status != "complete" + and not hard_failure(status) + ) + + +def launch_worker( + evaluation_plan: Path, worker: dict[str, Any], log_path: Path, +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_evaluation_worker", + "--plan", str(evaluation_plan.resolve()), "--worker", worker["id"], + "--state", worker["state"], "--poll-seconds", "30", + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("resolution evaluation controller state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + static_plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_evaluation_controller_state_v1", + "status": "waiting_for_resolution_training", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_plan_hash, + "machine": machine, + "controller_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != static_plan_hash: + parser.error("existing evaluation controller state differs") + if state.get("machine") != machine: + parser.error("existing evaluation state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not training_complete(plan): + state["status"] = "waiting_for_resolution_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_resolution_evaluation_plan", + "--training-controller-plan", plan["training_controller_plan"], + "--training-controller-state", plan["training_controller_state"], + "--cache-plan", plan["cache_execution_plan"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_plan_hash = sha256(evaluation_plan) + dynamic = json.loads(evaluation_plan.read_text(encoding="utf-8")) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = evaluation_plan_hash + state["owned_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("workers", {}) + + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + worker_state = Path(worker["state"]) + status = worker_status(worker_state, evaluation_plan_hash) + statuses[worker["id"]] = status + if not should_launch(worker, machine, status): + continue + previous_pid = int( + state["workers"].get(worker["id"], {}).get("pid", -1) + ) + if not pid_matches(previous_pid, worker["id"], evaluation_plan): + pid = launch_worker( + evaluation_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "worker_processes": state["workers"], + } + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + decision = Path(plan["decision_report"]) + if not decision.exists(): + command = [ + sys.executable, "-m", "scripts.summarize_phase9_resolution_decision", + "--plan", str(evaluation_plan), + "--control-external-root", plan["control_external_root"], + "--control-fold-final-root", plan["control_fold_final_root"], + "--control-fold-milestone-root", plan["control_fold_milestone_root"], + "--output", str(decision), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = json.loads(decision.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != evaluation_plan_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["accepted_resolution_hw"] = report["accepted_resolution_hw"] + state["decision_report"] = { + "path": str(decision.resolve()), "sha256": sha256(decision), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_evaluation_resource_recovery.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_evaluation_resource_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..2edf205a25ace56f727b1148bf1478dc02fbc5fa --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_evaluation_resource_recovery.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Rebind one unstarted logical evaluation worker to an idle allowed GPU.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.train_phase7_external import assert_physical_gpu_idle + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_amendment(path: Path, value: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + plan_path = Path(value.get("evaluation_plan", {}).get("path", "")) + controller_plan = Path(value.get("controller_plan", "")) + if ( + value.get("schema_version") != "phase9_resolution_evaluation_resource_amendment_v1" + or value.get("status") != "frozen" + or value.get("worker") != "server_new_gpu5" + or value.get("owner") != "server_new" + or value.get("planned_physical_gpu_id") != 5 + or value.get("replacement_physical_gpu_id") not in {0, 1, 2} + or value.get("evaluation_ids") + != ["loso_subject3_rgb_d_k", "lofamily_k_rgb_k"] + or value.get("requires_dynamic_idle_check") is not True + or value.get("external_process_preemption_forbidden") is not True + or value.get("scientific_fields_changed") != [] + or any(value.get(key) is not False for key in ( + "model_changed", "data_changed", "seed_changed", "metric_changed", + "selection_gate_changed", "official_test_used", + "h2o_official_validation_used", + )) + or not plan_path.is_file() + or sha256(plan_path) != value.get("evaluation_plan", {}).get("sha256") + or not controller_plan.is_file() + or sha256(controller_plan) != value.get("controller_plan_sha256") + ): + raise ValueError("resolution evaluation resource amendment differs") + plan = read_json(plan_path) + worker = next(item for item in plan["workers"] if item["id"] == value["worker"]) + if ( + worker.get("owner") != value["owner"] + or worker.get("physical_gpu_id") != value["planned_physical_gpu_id"] + or worker.get("evaluation_ids") != value["evaluation_ids"] + or worker.get("state") != value["original_state"] + or value["replacement_physical_gpu_id"] not in {0, 1, 2, 5} + or plan.get("official_test_used") is not False + ): + raise ValueError("resolution evaluation recovery worker binding differs") + if not path.is_file(): + raise ValueError("resolution evaluation resource amendment is unreadable") + return plan, worker + + +def imported_state( + recovery: dict[str, Any], amendment_path: Path, amendment: dict[str, Any], + original_plan_path: Path, +) -> dict[str, Any]: + if ( + recovery.get("status") != "complete" + or recovery.get("worker") != amendment["worker"] + or recovery.get("owner") != amendment["owner"] + or recovery.get("assigned_evaluation_ids") != amendment["evaluation_ids"] + or recovery.get("completed_ids") != amendment["evaluation_ids"] + or recovery.get("official_test_used") is not False + or recovery.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution evaluation recovery state differs") + return { + **recovery, + "schema_version": "phase9_resolution_evaluation_worker_state_v1", + "plan": str(original_plan_path.resolve()), + "plan_sha256": amendment["evaluation_plan"]["sha256"], + "physical_gpu_id": amendment["replacement_physical_gpu_id"], + "planned_physical_gpu_id": amendment["planned_physical_gpu_id"], + "resource_amendment": { + "path": str(amendment_path.resolve()), "sha256": sha256(amendment_path), + "reason": amendment["reason"], + }, + "source_recovery_state": { + "path": str(Path(amendment["recovery_state"]).resolve()), + "sha256": sha256(amendment["recovery_state"]), + }, + "imported_utc": utc_now(), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--amendment", type=Path, required=True) + args = parser.parse_args() + amendment = read_json(args.amendment) + try: + plan, worker = validate_amendment(args.amendment, amendment) + assert_physical_gpu_idle(amendment["replacement_physical_gpu_id"]) + except (ValueError, RuntimeError) as error: + parser.error(str(error)) + + original_state = Path(amendment["original_state"]) + backup = Path(amendment["original_state_backup"]) + if original_state.is_file(): + old = read_json(original_state) + if old.get("status") != "waiting_for_idle_gpu" or old.get("attempts") != []: + parser.error("logical GPU5 worker is not an unstarted waiter") + backup.parent.mkdir(parents=True, exist_ok=True) + if backup.exists() and sha256(backup) != sha256(original_state): + parser.error("logical GPU5 waiter backup differs") + if not backup.exists(): + shutil.copy2(original_state, backup) + os.chmod(backup, 0o444) + original_state.unlink() + + amended = deepcopy(plan) + amended_worker = next(item for item in amended["workers"] if item["id"] == amendment["worker"]) + amended_worker["physical_gpu_id"] = amendment["replacement_physical_gpu_id"] + amended_worker["state"] = amendment["recovery_state"] + amended["resource_schedule_amendment"] = { + "path": str(args.amendment.resolve()), "sha256": sha256(args.amendment), + } + recovery_plan = Path(amendment["recovery_plan"]) + if recovery_plan.exists() and read_json(recovery_plan) != amended: + parser.error("existing resolution evaluation recovery plan differs") + if not recovery_plan.exists(): + atomic_json(recovery_plan, amended) + os.chmod(recovery_plan, 0o444) + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_evaluation_worker", + "--plan", str(recovery_plan.resolve()), "--worker", amendment["worker"], + "--state", amendment["recovery_state"], "--poll-seconds", "30", + ] + result = subprocess.run(command, check=False) + if result.returncode: + raise SystemExit(result.returncode) + recovery = read_json(amendment["recovery_state"]) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if any(not evaluation_complete(evaluations[identifier]) for identifier in amendment["evaluation_ids"]): + raise ValueError("resolution evaluation recovery output differs") + imported = imported_state( + recovery, args.amendment, amendment, + Path(amendment["evaluation_plan"]["path"]), + ) + temporary = original_state.with_suffix(".importing") + atomic_json(temporary, imported) + os.replace(temporary, original_state) + controller_command = [ + sys.executable, "-u", "-m", "scripts.run_phase9_resolution_evaluation_controller", + "--plan", amendment["controller_plan"], "--state", amendment["controller_state"], + "--machine", "server_new", "--poll-seconds", "30", + ] + with Path(amendment["controller_log"]).open("a", encoding="utf-8") as log: + process = subprocess.Popen( + controller_command, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + print(json.dumps({ + "status": "complete", "imported_state": str(original_state.resolve()), + "imported_state_sha256": sha256(original_state), + "controller_pid": process.pid, "completed_utc": utc_now(), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_evaluation_worker.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_evaluation_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..71abe7979fd0b9d390223e80008f859de2a7200b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_evaluation_worker.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +"""Run one fixed-GPU shard of Stage 7 resolution evaluations.""" + +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time +from typing import Any, Iterator + +from scripts.phase9_distributed_assignment import ( + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +@contextmanager +def output_lock(output: Path) -> Iterator[None]: + output.parent.mkdir(parents=True, exist_ok=True) + path = output.parent / f".{output.name}.resolution-evaluation.lock" + with path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + yield + + +def evaluation_complete(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + bindings_match = ( + report.get("status") == f"evaluated_{item['evaluation_role']}" + and report.get("evaluation_role") == item["evaluation_role"] + and report.get("input_mode") == item["input_mode"] + and report.get("checkpoint", {}).get("path") == item["checkpoint"] + and report.get("checkpoint", {}).get("sha256") + == item["checkpoint_sha256"] + and report.get("config", {}).get("path") == item["config"] + and report.get("config", {}).get("sha256") == item["config_sha256"] + and report.get("cache_manifest", {}).get("path") + == item["cache_manifest"] + and report.get("cache_manifest", {}).get("sha256") + == item["cache_manifest_sha256"] + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + ) + if not bindings_match: + return False + for key in ("raw_predictions", "per_hand_rows", "take_metrics"): + artifact = report.get(key, {}) + path = Path(str(artifact.get("path", ""))) + if not path.is_file() or artifact.get("sha256") != sha256(path): + return False + return ( + isinstance(report.get("clips"), int) and report["clips"] > 0 + and isinstance(report.get("frames"), int) and report["frames"] > 0 + ) + + +def validate_inputs(items: list[dict[str, Any]]) -> None: + expected: dict[Path, str] = {} + for item in items: + for path_key, hash_key in ( + ("config", "config_sha256"), + ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256"), + ): + path = Path(item[path_key]) + digest = item[hash_key] + if path in expected and expected[path] != digest: + raise ValueError(f"evaluation input has conflicting hashes: {path}") + expected[path] = digest + for path, digest in expected.items(): + if not path.is_file() or sha256(path) != digest: + raise ValueError(f"resolution evaluation input differs: {path}") + + +def evaluation_command( + item: dict[str, Any], gpu: int, heartbeat_path: Path | None = None, + heartbeat_seconds: float = 30.0, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", item["evaluation_role"], + ] + if heartbeat_path is not None: + command.extend(( + "--evaluation-id", item["id"], + "--heartbeat-path", str(heartbeat_path.resolve()), + "--heartbeat-seconds", str(heartbeat_seconds), + )) + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def process_command(pid: int) -> str | None: + path = Path(f"/proc/{pid}/cmdline") + try: + return path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (FileNotFoundError, PermissionError, ProcessLookupError, UnicodeDecodeError): + return None + + +def evaluator_pid_matches(pid: int, item: dict[str, Any]) -> bool: + command = process_command(pid) + return bool( + command + and "scripts.evaluate_phase7_external" in command + and f"--evaluation-id {item['id']}" in command + and f"--output-dir {item['output_dir']}" in command + and f"--checkpoint {item['checkpoint']}" in command + ) + + +def process_descendants(pid: int) -> list[int]: + observed: set[int] = set() + pending = [pid] + while pending: + parent = pending.pop() + path = Path(f"/proc/{parent}/task/{parent}/children") + try: + children = [int(value) for value in path.read_text().split()] + except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError): + children = [] + for child in children: + if child not in observed: + observed.add(child) + pending.append(child) + return sorted(observed) + + +def validate_progress_heartbeat( + path: Path, item: dict[str, Any], evaluator_pid: int, +) -> dict[str, Any]: + value = json.loads(path.read_text(encoding="utf-8")) + if ( + value.get("schema_version") != "phase9_evaluation_progress_heartbeat_v1" + or value.get("evaluation_id") != item["id"] + or value.get("evaluator_pid") != evaluator_pid + or value.get("output_dir") != str(Path(item["output_dir"]).resolve()) + or value.get("official_test_used") is not False + or value.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution evaluator heartbeat differs: {item['id']}") + return value + + +def terminate_owned_process(process: subprocess.Popen[str]) -> None: + if process.poll() is not None: + return + try: + os.killpg(process.pid, 15) + except ProcessLookupError: + return + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, 9) + except ProcessLookupError: + pass + process.wait(timeout=15) + + +def run_evaluation_child( + *, command: list[str], environment: dict[str, str], log_path: Path, + heartbeat_path: Path, item: dict[str, Any], state: dict[str, Any], + state_path: Path, worker_heartbeat_seconds: float, + stall_timeout_seconds: float, +) -> tuple[int, str | None]: + started = time.monotonic() + last_progress = started + last_heartbeat_write = 0.0 + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + state["child"] = { + "pid": process.pid, "evaluation_id": item["id"], + "command": command, "started_utc": utc_now(), + } + atomic_json(state_path, state) + failure: str | None = None + try: + while process.poll() is None: + now = time.monotonic() + if not evaluator_pid_matches(process.pid, item): + failure = "evaluator_pid_or_cmdline_differs" + terminate_owned_process(process) + break + progress = None + if heartbeat_path.is_file(): + progress = validate_progress_heartbeat( + heartbeat_path, item, process.pid, + ) + age = time.time() - heartbeat_path.stat().st_mtime + last_progress = now - max(0.0, age) + if now - last_progress > stall_timeout_seconds: + failure = "evaluator_progress_stalled" + terminate_owned_process(process) + break + if now - last_heartbeat_write >= worker_heartbeat_seconds: + state["heartbeat"] = { + "updated_utc": utc_now(), "worker_pid": os.getpid(), + "evaluator_pid": process.pid, + "evaluator_cmdline_verified": True, + "descendant_pids": process_descendants(process.pid), + "log_mtime": log_path.stat().st_mtime, + "progress": progress, + "stall_timeout_seconds": stall_timeout_seconds, + } + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + last_heartbeat_write = now + time.sleep(min(5.0, worker_heartbeat_seconds)) + except Exception: + terminate_owned_process(process) + raise + returncode = process.wait() + return returncode, failure + + +def claim_when_idle(gpu: int, state: dict[str, Any], state_path: Path, poll: float) -> None: + while True: + try: + idle = assert_physical_gpu_idle(gpu) is None + except RuntimeError: + idle = False + if idle and claim_physical_gpu(gpu): + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + else: + return + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + time.sleep(poll) + + +def archive_incomplete_output( + item: dict[str, Any], state: dict[str, Any], state_path: Path, +) -> None: + output = Path(item["output_dir"]) + if not output.exists() or not any(output.iterdir()): + return + root = state_path.parent / "failed_outputs" / item["id"] + root.mkdir(parents=True, exist_ok=True) + destination = root / f"attempt_{len(state['attempts']):03d}" + if destination.exists(): + raise ValueError(f"incomplete evaluation archive already exists: {destination}") + shutil.move(str(output), str(destination)) + state.setdefault("archived_incomplete_outputs", []).append({ + "id": item["id"], "source": str(output.resolve()), + "archive": str(destination.resolve()), "archived_utc": utc_now(), + }) + atomic_json(state_path, state) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if ( + plan.get("status") != "frozen_ready" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + ): + parser.error("resolution evaluation plan is not frozen and isolated") + workers = {item["id"]: item for item in plan["workers"]} + if args.worker not in workers: + parser.error("unknown resolution evaluation worker") + worker = workers[args.worker] + try: + assignment = load_assignment(plan) + machine = detect_machine(assignment, None) + except ValueError as error: + parser.error(str(error)) + if worker.get("owner") != machine: + parser.error("evaluation worker is externally owned on this host") + if worker.get("physical_gpu_id") not in gpu_allowlist(assignment, machine): + parser.error("evaluation worker GPU is not allowed on this host") + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("resolution evaluation worker state differs from plan") + evaluations = {item["id"]: item for item in plan["evaluations"]} + items = [evaluations[identifier] for identifier in worker["evaluation_ids"]] + try: + validate_inputs(items) + except ValueError as error: + parser.error(str(error)) + + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_evaluation_worker_state_v1", + "status": "running", "worker": args.worker, + "physical_gpu_id": worker["physical_gpu_id"], + "owner": machine, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "assigned_evaluation_ids": worker["evaluation_ids"], + "completed_ids": [], "attempts": [], + "worker_pid": os.getpid(), + "started_utc": utc_now(), "updated_utc": utc_now(), + "resource_amendment": "user_authorized_idle_gpus_0_5_20260730", + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if ( + state.get("plan_sha256") != plan_hash + or state.get("worker") != args.worker + or state.get("owner") != machine + or state.get("assigned_evaluation_ids") != worker["evaluation_ids"] + ): + parser.error("existing evaluation worker state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + gpu = int(worker["physical_gpu_id"]) + for item in items: + if evaluation_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + with output_lock(Path(item["output_dir"])): + if evaluation_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + prior_attempts = sum( + attempt.get("id") == item["id"] + for attempt in state["attempts"] + ) + if prior_attempts >= plan["max_attempts_per_evaluation"]: + state["status"] = "failed_terminal_attempt_limit" + state["failure"] = { + "id": item["id"], "attempts": prior_attempts, + "reason": "maximum exact-resume attempts exhausted", + } + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + archive_incomplete_output(item, state, args.state) + claim_when_idle(gpu, state, args.state, args.poll_seconds) + heartbeat_path = Path(item["output_dir"]) / "evaluation_heartbeat.json" + command = evaluation_command( + item, gpu, heartbeat_path, + plan["evaluator_progress_heartbeat_seconds"], + ) + log_path = args.state.parent / "logs" / f"{item['id']}.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "id": item["id"], "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_evaluation"] = item["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + returncode, failure = run_evaluation_child( + command=command, environment=environment, + log_path=log_path, heartbeat_path=heartbeat_path, + item=item, state=state, state_path=args.state, + worker_heartbeat_seconds=plan["worker_heartbeat_seconds"], + stall_timeout_seconds=plan["stall_timeout_seconds"], + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = returncode + attempt["supervisor_failure"] = failure + state["updated_utc"] = utc_now() + if returncode or failure or not evaluation_complete(item): + attempt_count = sum( + value.get("id") == item["id"] + for value in state["attempts"] + ) + state["status"] = ( + "failed_terminal_attempt_limit" + if attempt_count >= plan["max_attempts_per_evaluation"] + else "failed_resumable" + ) + state["failure"] = { + "id": item["id"], "returncode": returncode, + "supervisor_failure": failure, + "attempts": attempt_count, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(returncode or 1) + state["completed_ids"].append(item["id"]) + state.pop("child", None) + state.pop("failure", None) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_training_controller.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..d6998ea02b27bfb0fc1d9a1c08cff8d426138ced --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_resolution_training_controller.py @@ -0,0 +1,268 @@ +#!/usr/bin/env python3 +"""Admit and supervise matched Phase 9 resolution training jobs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or float(plan.get("worst_domain_relative_regression_limit", -1)) != 0.01 + ): + raise ValueError("resolution training controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution training binding differs: {path}") + + +def readiness_complete(plan: dict[str, Any]) -> bool: + path = Path(plan["readiness_state"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + audit = Path(state.get("audit", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["cache_execution_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and audit.is_file() + and state.get("audit", {}).get("sha256") == sha256(audit) + ) + + +def pid_matches(pid: int, condition: str, registry: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_unified_train_queue" in command + and f"--condition {condition}" in command + and str(registry.resolve()) in command + ) + + +def condition_status(state_path: Path, registry_sha256: str) -> str: + if not state_path.is_file(): + return "missing" + state = json.loads(state_path.read_text(encoding="utf-8")) + if state.get("queue_sha256") != registry_sha256: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def hard_failure(status: str) -> bool: + return status.startswith("failed") and status != "failed_resumable" + + +def launch_worker( + condition: str, registry: Path, state_path: Path, log_path: Path, + allowed_gpus: list[int], +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry.resolve()), "--condition", condition, + "--state", str(state_path.resolve()), "--poll-seconds", "30", + "--allowed-physical-gpus", ",".join(str(gpu) for gpu in allowed_gpus), + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("resolution training controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_training_controller_state_v1", + "status": "waiting_for_cache_readiness", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "machine": machine, + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing controller state belongs to another plan") + if state.get("machine") != machine: + parser.error("existing controller state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not readiness_complete(plan): + state["status"] = "waiting_for_cache_readiness" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry = Path(plan["training_registry"]) + builder_state = Path(plan["registry_builder_state"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_resolution_training_registry", + "--selection-report", plan["selection_report"], + "--readiness-state", plan["readiness_state"], + "--cache-plan", plan["cache_execution_plan"], + "--unified-queue", plan["unified_training_queue"], + "--fold-queue", plan["fold_training_queue"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), "--state", str(builder_state), + ] + if machine == "taku3": + state["status"] = "building_registry" + state["builder_command"] = builder_command + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_registry_builder" + state["builder_returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry_sha256 = sha256(registry) + registry_payload = json.loads(registry.read_text(encoding="utf-8")) + conditions = [item["condition"] for item in registry_payload["conditions"]] + owners = condition_owners(registry_payload, assignment) + if ( + len(conditions) != 7 + or len(set(conditions)) != 7 + or registry_payload.get("gate", {}).get( + "worst_domain_relative_regression_limit" + ) != plan["worst_domain_relative_regression_limit"] + or registry_payload.get("official_test_used") is not False + ): + state["status"] = "failed_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_sha256 + state["conditions"] = conditions + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("workers", {}) + + state_root = Path(plan["training_state_root"]) + log_root = Path(plan["training_log_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_sha256) + statuses[condition] = status + if hard_failure(status): + continue + if status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["workers"].get(condition, {}).get("pid", -1) + ) + if not pid_matches(previous_pid, condition, registry): + pid = launch_worker( + condition, registry, condition_state, + log_root / f"{condition.lower()}.log", + allowed_gpus, + ) + state["workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["condition_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + state["status"] = "complete" if machine == "taku3" else "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_selection_binding_recovery.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..1de788859399ebc11c495022e81815866e615f7d --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_selection_binding_recovery.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python3 +"""Run one disjoint Phase 9 selection-binding recovery worker.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import socket +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def json_sha256(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def validate_input(path: str, expected_sha256: str, label: str) -> None: + candidate = Path(path) + if not candidate.is_file() or sha256(candidate) != expected_sha256: + raise ValueError(f"selection recovery {label} differs: {candidate}") + + +def validate_recovered_output(item: dict[str, Any]) -> dict[str, Any]: + output = Path(item["output_dir"]) + report_path = output / "evaluation.json" + if not report_path.is_file(): + raise ValueError(f"selection recovery report missing: {item['id']}") + report = json.loads(report_path.read_text(encoding="utf-8")) + expected_bindings = { + "config": (item["config"], item["config_sha256"]), + "checkpoint": (item["checkpoint"], item["checkpoint_sha256"]), + "cache_manifest": ( + item["cache_manifest"], item["cache_manifest_sha256"], + ), + } + for key, (path, digest) in expected_bindings.items(): + binding = report.get(key, {}) + if ( + Path(str(binding.get("path", ""))).resolve() != Path(path).resolve() + or binding.get("sha256") != digest + ): + raise ValueError( + f"selection recovery {key} binding differs: {item['id']}" + ) + if ( + report.get("status") != "evaluated_phase9_h2o_fold_heldout" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or { + key: report.get(key) + for key in ("clips", "frames", "hands_rows") + } != item["expected_sample_counts"] + ): + raise ValueError(f"selection recovery role/sample contract differs: {item['id']}") + expected = item["expected_determinism"] + artifacts = { + "raw_predictions": expected["raw_predictions_sha256"], + "per_hand_rows": expected["per_hand_rows_sha256"], + "take_metrics": expected["take_metrics_sha256"], + } + for key, expected_hash in artifacts.items(): + binding = report.get(key, {}) + path = Path(str(binding.get("path", ""))) + if ( + binding.get("sha256") != expected_hash + or not path.is_file() + or sha256(path) != expected_hash + ): + raise ValueError( + f"selection recovery deterministic artifact differs: " + f"{item['id']}:{key}" + ) + if ( + json_sha256(report.get("metrics")) != expected["metrics_sha256"] + or json_sha256(report.get("grouped_bootstrap_ci")) + != expected["grouped_bootstrap_ci_sha256"] + ): + raise ValueError(f"selection recovery deterministic metrics differ: {item['id']}") + return { + "report": str(report_path.resolve()), + "report_sha256": sha256(report_path), + "sample_counts": item["expected_sample_counts"], + "metrics_sha256": expected["metrics_sha256"], + "raw_predictions_sha256": expected["raw_predictions_sha256"], + } + + +def archive_incomplete_output(item: dict[str, Any]) -> str | None: + output = Path(item["output_dir"]) + if not output.exists() or not any(output.iterdir()): + return None + root = output.parents[3] / "incomplete_outputs" + root.mkdir(parents=True, exist_ok=True) + suffix = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") + destination = root / f"{item['id']}.{suffix}" + shutil.move(str(output), str(destination)) + return str(destination.resolve()) + + +def evaluation_command(item: dict[str, Any], gpu: int, bootstrap: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], + "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(bootstrap), + "--evaluation-role", item["evaluation_role"], + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--owner", choices=("taku3", "server_new"), required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + assignment_path = Path(plan["distributed_assignment"]["path"]) + if ( + plan.get("official_test_used") is not False + or not assignment_path.is_file() + or sha256(assignment_path) != plan["distributed_assignment"]["sha256"] + ): + parser.error("selection recovery plan/assignment binding differs") + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + parser.error(f"selection recovery code binding differs: {path}") + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + if socket.gethostname() != assignment["machines"][args.owner]["hostname"]: + parser.error("selection recovery owner does not match this host") + matches = [item for item in plan["workers"] if item["id"] == args.worker] + if len(matches) != 1 or matches[0]["owner"] != args.owner: + parser.error("selection recovery worker owner differs") + worker = matches[0] + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("selection recovery worker state differs") + gpu = int(worker["physical_gpu_id"]) + if gpu not in assignment["machines"][args.owner]["physical_gpu_allowlist"]: + parser.error("selection recovery GPU is not allowed on this host") + evaluations = {item["id"]: item for item in plan["evaluations"]} + assigned = [evaluations[identifier] for identifier in worker["evaluation_ids"]] + if any( + item["owner"] != args.owner or item["physical_gpu_id"] != gpu + for item in assigned + ): + parser.error("selection recovery evaluation assignment differs") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_selection_binding_recovery_worker_state_v1", + "status": "waiting_for_gpu", "owner": args.owner, + "worker": args.worker, "physical_gpu_id": gpu, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "assigned_evaluation_ids": worker["evaluation_ids"], + "completed_ids": [], "attempts": [], + "started_utc": utc_now(), "updated_utc": utc_now(), + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if ( + previous.get("plan_sha256") != plan_hash + or previous.get("owner") != args.owner + or previous.get("worker") != args.worker + or previous.get("assigned_evaluation_ids") + != worker["evaluation_ids"] + ): + parser.error("existing selection recovery state differs") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for item in assigned: + for key in ("config", "checkpoint", "cache_manifest"): + validate_input(item[key], item[f"{key}_sha256"], key) + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError): + evidence = None + if evidence is not None: + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + continue + output = Path(item["output_dir"]) + lock_path = output.parent / f".{output.name}.selection-recovery.lock" + output.parent.mkdir(parents=True, exist_ok=True) + with lock_path.open("a+", encoding="utf-8") as output_lock: + fcntl.flock(output_lock.fileno(), fcntl.LOCK_EX) + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError): + evidence = None + if evidence is not None: + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + atomic_json(args.state, state) + continue + archived = archive_incomplete_output(item) + while True: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + state["status"] = "waiting_for_gpu" + state["waiting_for"] = item["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + if claim_physical_gpu(gpu): + break + state["status"] = "waiting_for_gpu_claim" + state["waiting_for"] = item["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = evaluation_command( + item, gpu, int(plan["bootstrap_resamples"]) + ) + attempt = { + "evaluation_id": item["id"], "start_utc": utc_now(), + "command": command, + } + if archived is not None: + attempt["archived_incomplete_output"] = archived + state["status"] = "running" + state["current_evaluation"] = item["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + env = dict(os.environ) + env["CUDA_VISIBLE_DEVICES"] = str(gpu) + env["PYTHONUNBUFFERED"] = "1" + try: + result = subprocess.run( + command, cwd=Path.cwd(), env=env, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError) as error: + state["status"] = "failed_resumable" + state["failure"] = f"{type(error).__name__}: {error}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + if result.returncode: + state["status"] = "failed_resumable" + state["failure"] = f"evaluator exited {result.returncode}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + state.pop("failure", None) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if set(state["completed_ids"]) != set(worker["evaluation_ids"]): + state["status"] = "failed_state_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state.pop("waiting_for", None) + state.pop("current_evaluation", None) + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_selection_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_selection_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6bcd0a5ebe87d4b4d325dff8080e1954ad4aaa --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_selection_queue.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Wait for complete Phase 9 evidence and freeze unified candidate selection.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def evidence_complete(plan: dict[str, Any]) -> bool: + for item in plan["required_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def selection_complete(plan: dict[str, Any]) -> bool: + output = Path(plan["output_json"]) + if not output.is_file(): + return False + report = json.loads(output.read_text(encoding="utf-8")) + checkpoint = Path(report.get("winner_checkpoint", {}).get("path", "")) + config = Path(report.get("winner_config", {}).get("path", "")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + and checkpoint.is_file() + and report.get("winner_checkpoint", {}).get("sha256") == sha256(checkpoint) + and config.is_file() + and report.get("winner_config", {}).get("sha256") == sha256(config) + and Path(plan["output_csv"]).is_file() + ) + + +def archive_incomplete_outputs(plan: dict[str, Any], state_path: Path) -> list[str]: + outputs = [Path(plan["output_json"]), Path(plan["output_csv"])] + temporary_outputs = [ + path.with_suffix(path.suffix + ".tmp") for path in outputs + ] + existing = [path for path in outputs + temporary_outputs if path.exists()] + if not existing: + return [] + root = state_path.parent / "selection_incomplete_outputs" + root.mkdir(parents=True, exist_ok=True) + archived = [] + for path in existing: + destination = root / f"{path.name}.{len(list(root.iterdir())):03d}" + shutil.move(str(path), str(destination)) + archived.append(str(destination.resolve())) + return archived + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("selection plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state_lock = Path(f"{args.state}.lock").open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state = { + "schema_version": "phase9_selection_state_v1", + "status": "waiting_for_evidence", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "updated_utc": utc_now(), "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing selection state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not evidence_complete(plan): + state["status"] = "waiting_for_evidence" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + if not selection_complete(plan): + archived = archive_incomplete_outputs(plan, args.state) + if archived: + state.setdefault("archived_incomplete_outputs", []).extend(archived) + atomic_json(args.state, state) + command = [ + sys.executable, "-m", "scripts.summarize_phase9_unified_selection", + "--external-root", plan["external_root"], + "--fold-final-root", plan["fold_final_root"], + "--fold-milestone-root", plan["fold_milestone_root"], + "--multifold-index", plan["multifold_index"], + "--output-json", plan["output_json"], + "--output-csv", plan["output_csv"], + ] + log_path = args.state.parent / "unified_selection.log" + state["status"] = "running" + state["attempt"] = { + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + state["attempt"]["end_utc"] = utc_now() + state["attempt"]["returncode"] = result.returncode + if result.returncode or not selection_complete(plan): + state["status"] = "failed" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + report = json.loads(Path(plan["output_json"]).read_text(encoding="utf-8")) + state["status"] = "complete" + state["winner"] = report["winner"] + state["winner_checkpoint"] = report["winner_checkpoint"] + state["winner_config"] = report["winner_config"] + state["required_states"] = [ + { + "id": item["id"], "path": str(Path(item["path"]).resolve()), + "sha256": sha256(item["path"]), + } + for item in plan["required_states"] + ] + state["h2o_official_validation_used"] = False + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_shared_augmentation_evaluation_controller.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_shared_augmentation_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..1f0c887433e7319788e98fec0e732a102fc70c38 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_shared_augmentation_evaluation_controller.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""Supervise Stage 8 evaluations and freeze augmentation/Stage 9 gates.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_resolution_evaluation_controller import ( + hard_failure, + launch_worker, + pid_matches, + should_launch, + worker_status, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("evaluation_count") != 25 + or plan.get("worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + ): + raise ValueError("shared augmentation evaluation plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"shared augmentation evaluation binding differs: {path}") + + +def training_complete(plan: dict[str, Any]) -> bool: + path = Path( + plan.get("training_controller_states", {}).get( + "taku3", plan["training_controller_state"] + ) + ) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + registry = Path(state.get("training_registry", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["training_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and registry.is_file() + and state.get("training_registry_sha256") == sha256(registry) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("shared augmentation evaluation state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + static_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_shared_augmentation_evaluation_controller_state_v1", + "status": "waiting_for_augmentation_training", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "machine": machine, + "controller_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != static_hash: + parser.error("existing augmentation evaluation state differs") + if state.get("machine") != machine: + parser.error("existing augmentation evaluation machine differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not training_complete(plan): + state["status"] = "waiting_for_augmentation_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + builder_command = [ + sys.executable, "-m", + "scripts.build_phase9_shared_augmentation_evaluation_plan", + "--training-controller-plan", plan["training_controller_plan"], + "--training-controller-state", plan["training_controller_state"], + "--resolution-cache-plan", plan["resolution_cache_plan"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + dynamic_hash = sha256(evaluation_plan) + dynamic = json.loads(evaluation_plan.read_text(encoding="utf-8")) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = dynamic_hash + state["owned_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("workers", {}) + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + path = Path(worker["state"]) + status = worker_status(path, dynamic_hash) + statuses[worker["id"]] = status + if not should_launch(worker, machine, status): + continue + previous_pid = int( + state["workers"].get(worker["id"], {}).get("pid", -1) + ) + if not pid_matches(previous_pid, worker["id"], evaluation_plan): + pid = launch_worker( + evaluation_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "worker_processes": state["workers"], + } + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + decision = Path(plan["decision_report"]) + if not decision.exists(): + command = [ + sys.executable, "-m", + "scripts.summarize_phase9_shared_augmentation_decision", + "--plan", str(evaluation_plan), "--output", str(decision), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = json.loads(decision.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != dynamic_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["stage9_last2_admitted"] = report[ + "stage9_preceding_mechanism_gate" + ]["stage9_last2_admitted"] + state["decision_report"] = { + "path": str(decision.resolve()), "sha256": sha256(decision), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_shared_augmentation_training_controller.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_shared_augmentation_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..191670dce11e49ef1c417651529cdb49bca1cec2 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_shared_augmentation_training_controller.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Supervise Stage 8 shared-augmentation training after resolution freeze.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_resolution_training_controller import ( + condition_status, + hard_failure, + pid_matches, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or plan.get("job_count") != 7 + or float(plan.get("worst_domain_relative_regression_limit", -1)) != 0.01 + ): + raise ValueError("shared augmentation training plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"shared augmentation binding differs: {path}") + + +def resolution_decision_complete(plan: dict[str, Any]) -> bool: + state_path = Path(plan["resolution_controller_state"]) + if not state_path.is_file(): + return False + state = json.loads(state_path.read_text(encoding="utf-8")) + report = Path(state.get("decision_report", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["resolution_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and report.is_file() + and state.get("decision_report", {}).get("sha256") == sha256(report) + ) + + +def launch_worker( + condition: str, registry: Path, state_path: Path, log_path: Path, + allowed_gpus: list[int], +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry.resolve()), "--condition", condition, + "--state", str(state_path.resolve()), "--poll-seconds", "30", + "--allowed-physical-gpus", ",".join(str(gpu) for gpu in allowed_gpus), + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("shared augmentation controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_shared_augmentation_training_controller_state_v1", + "status": "waiting_for_resolution_decision", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "machine": machine, + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing shared augmentation controller state differs") + if state.get("machine") != machine: + parser.error("existing shared augmentation state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not resolution_decision_complete(plan): + state["status"] = "waiting_for_resolution_decision" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry = Path(plan["training_registry"]) + builder_command = [ + sys.executable, "-m", + "scripts.build_phase9_shared_augmentation_training_registry", + "--resolution-controller-plan", plan["resolution_controller_plan"], + "--resolution-controller-state", plan["resolution_controller_state"], + "--augmentation-plan", plan["shared_augmentation_plan"], + "--unified-queue", plan["unified_training_queue"], + "--fold-queue", plan["fold_training_queue"], + "--selection-report", plan["selection_report"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), + "--state", plan["registry_builder_state"], + ] + if machine == "taku3": + state["status"] = "building_registry" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_registry_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + registry_hash = sha256(registry) + payload = json.loads(registry.read_text(encoding="utf-8")) + conditions = [item["condition"] for item in payload["conditions"]] + owners = condition_owners(payload, assignment) + if ( + len(conditions) != plan["job_count"] + or len(set(conditions)) != plan["job_count"] + or payload.get("shared_augmentation_plan", {}).get("sha256") + != plan["shared_augmentation_plan_sha256"] + or payload.get("gate", {}).get("worst_domain_relative_regression_limit") + != plan["worst_domain_relative_regression_limit"] + or payload.get("official_test_used") is not False + ): + state["status"] = "failed_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_hash + state["resolution_hw"] = payload["resolution_hw"] + state["conditions"] = conditions + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("workers", {}) + + state_root = Path(plan["training_state_root"]) + log_root = Path(plan["training_log_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_hash) + statuses[condition] = status + if hard_failure(status) or status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["workers"].get(condition, {}).get("pid", -1) + ) + if not pid_matches(previous_pid, condition, registry): + pid = launch_worker( + condition, registry, condition_state, + log_root / f"{condition.lower()}.log", + allowed_gpus, + ) + state["workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["condition_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + state["status"] = "complete" if machine == "taku3" else "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_unified_train_queue.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_unified_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f904f748a1ecc505a0efe794951a67ddb4acb67b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_phase9_unified_train_queue.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python3 +"""Run one hash-bound Phase 9 unified mixture through smoke, health, and scale.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any +import re + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def parse_physical_gpu_ids(value: str) -> tuple[int, ...]: + try: + gpu_ids = tuple(int(item.strip()) for item in value.split(",") if item.strip()) + except ValueError as error: + raise argparse.ArgumentTypeError("GPU IDs must be comma-separated integers") from error + if not gpu_ids or len(set(gpu_ids)) != len(gpu_ids): + raise argparse.ArgumentTypeError("GPU IDs must be nonempty and unique") + if any(gpu < 0 or gpu > 5 for gpu in gpu_ids): + raise argparse.ArgumentTypeError("physical GPU IDs must be between 0 and 5") + return gpu_ids + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def attempt_gpu_hours(attempts: list[dict[str, Any]]) -> float: + seconds = 0.0 + for attempt in attempts: + if not attempt.get("start_utc") or not attempt.get("end_utc"): + continue + start = datetime.fromisoformat(attempt["start_utc"]) + end = datetime.fromisoformat(attempt["end_utc"]) + seconds += max(0.0, (end - start).total_seconds()) + return seconds / 3600.0 + + +def state_lock_path(state_path: Path) -> Path: + return Path(f"{state_path}.lock") + + +def readiness_complete(queue: dict[str, Any]) -> bool: + state_path = Path(queue["data_readiness_state"]) + if not state_path.is_file(): + return False + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or state.get("plan_sha256") != queue["data_finalize_plan_sha256"] + or ( + queue.get("data_readiness_state_sha256") is not None + and queue["data_readiness_state_sha256"] != sha256(state_path) + ) + ): + return False + for artifact in state.get("artifacts", []): + manifest = Path(artifact["manifest"]) + if not manifest.is_file() or sha256(manifest) != artifact["manifest_sha256"]: + return False + for artifact in queue.get("data_artifacts", []): + path = Path(artifact["path"]) + if not path.is_file() or sha256(path) != artifact["sha256"]: + return False + return True + + +def prerequisite_states_complete(registry: dict[str, Any]) -> bool: + for item in registry.get("prerequisite_states", []): + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def prerequisite_gate_satisfied( + registry: dict[str, Any], start_before_prerequisites: bool, +) -> bool: + return start_before_prerequisites or prerequisite_states_complete(registry) + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def marker_path(queue: dict[str, Any], stage: dict[str, Any]) -> Path: + return Path(queue["output_dir"]) / ".phase9_queue" / f"{stage['id']}.json" + + +def stage_complete(queue: dict[str, Any], stage: dict[str, Any]) -> bool: + path = marker_path(queue, stage) + if not path.is_file(): + return False + marker = json.loads(path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and marker.get("config_sha256") == queue["config_sha256"] + and int(marker.get("completed_step", -1)) == int(stage["stop_after_step"]) + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command( + queue: dict[str, Any], stage: dict[str, Any], gpu: int, + previous_checkpoint: Path | None, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", queue["config"], + "--output-dir", queue["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(stage["stop_after_step"]), + ] + if previous_checkpoint is None: + command.extend(("--init-checkpoint", queue["initialization_checkpoint"])) + else: + command.extend(("--resume", str(previous_checkpoint))) + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def latest_resumable_checkpoint( + queue: dict[str, Any], stage: dict[str, Any], previous_checkpoint: Path | None, +) -> Path | None: + target = int(stage["stop_after_step"]) + previous_step = -1 + if previous_checkpoint is not None: + match = re.search(r"step_(\d+)", previous_checkpoint.name) + previous_step = int(match.group(1)) if match else -1 + candidates = [] + for path in Path(queue["output_dir"]).glob("step_*.pt"): + match = re.fullmatch(r"step_(\d+)(?:_final)?\.pt", path.name) + if match is None: + continue + step = int(match.group(1)) + if previous_step < step < target and path.is_file(): + candidates.append((step, path)) + return max(candidates, default=(previous_step, previous_checkpoint))[1] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--condition", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--start-before-prerequisites", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + registry = json.loads(args.queue.read_text(encoding="utf-8")) + conditions = {item["condition"]: item for item in registry["conditions"]} + if args.condition not in conditions: + parser.error(f"condition not registered: {args.condition}") + queue = conditions[args.condition] + if registry.get("official_test_used") is not False: + parser.error("queue must explicitly exclude official test") + config = Path(queue["config"]) + initialization = Path(queue["initialization_checkpoint"]) + if not config.is_file() or sha256(config) != queue["config_sha256"]: + parser.error("frozen config is missing or has changed") + if not initialization.is_file() or sha256(initialization) != queue["initialization_checkpoint_sha256"]: + parser.error("frozen initialization checkpoint is missing or has changed") + args.state.parent.mkdir(parents=True, exist_ok=True) + lock_path = state_lock_path(args.state) + state_lock = lock_path.open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + registry_hash = sha256(args.queue) + state = { + "schema_version": "phase9_unified_train_state_v1", + "status": "waiting_for_data", + "condition": args.condition, + "queue": str(args.queue.resolve()), "queue_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "attempts": [], "completed_stages": [], + "allowed_physical_gpus": list(args.allowed_physical_gpus), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue_sha256") != registry_hash: + parser.error("existing state is bound to another queue version") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for attempt in state.get("attempts", []): + if attempt.get("start_utc") and not attempt.get("end_utc"): + attempt["end_utc"] = utc_now() + attempt["returncode"] = None + attempt["interrupted_before_queue_restart"] = True + previous_gpus = tuple(state.get("allowed_physical_gpus", ALLOWED_GPUS)) + if state.get("attempts") and previous_gpus != args.allowed_physical_gpus: + parser.error("cannot change allowed GPUs after this queue has attempted work") + previous_early_start = bool(state.get("start_before_prerequisites", False)) + if state.get("attempts") and previous_early_start != args.start_before_prerequisites: + parser.error("cannot change prerequisite scheduling after attempted work") + state["allowed_physical_gpus"] = list(args.allowed_physical_gpus) + state["start_before_prerequisites"] = bool(args.start_before_prerequisites) + if args.start_before_prerequisites: + state["resource_amendment"] = "user_authorized_all_idle_gpus_20260727" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + while not readiness_complete({**registry, **queue}): + state["status"] = "waiting_for_data" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + while not prerequisite_gate_satisfied(registry, args.start_before_prerequisites): + state["status"] = "waiting_for_prerequisites" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + previous_checkpoint: Path | None = None + for stage in queue["stages"]: + if stage_complete(queue, stage): + previous_checkpoint = Path( + json.loads(marker_path(queue, stage).read_text(encoding="utf-8"))["checkpoint"] + ) + if stage["id"] not in state["completed_stages"]: + state["completed_stages"].append(stage["id"]) + continue + previous_checkpoint = latest_resumable_checkpoint( + queue, stage, previous_checkpoint, + ) + while True: + gpu = idle_gpu(args.allowed_physical_gpus) + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + break + command = training_command(queue, stage, gpu, previous_checkpoint) + log_path = Path(queue["log_dir"]) / f"{stage['id']}.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "stage": stage["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_stage"] = stage["id"] + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode: + periodic = sorted(Path(queue["output_dir"]).glob("step_*.pt")) + latest = periodic[-1] if periodic else None + state["status"] = "failed_resumable" if periodic else "failed" + state["failure"] = { + "stage": stage["id"], "returncode": result.returncode, + "latest_checkpoint": str(latest.resolve()) if latest else None, + "latest_checkpoint_sha256": sha256(latest) if latest else None, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode) + checkpoint = Path(queue["output_dir"]) / f"step_{int(stage['stop_after_step']):07d}_final.pt" + summary = json.loads((Path(queue["output_dir"]) / "summary.json").read_text(encoding="utf-8")) + marker = { + "status": "complete", "condition": args.condition, + "stage": stage["id"], "completed_utc": utc_now(), + "completed_step": int(stage["stop_after_step"]), + "physical_gpu_id": gpu, "config": str(config.resolve()), + "config_sha256": queue["config_sha256"], + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": sha256(checkpoint), + "source_manifest_sha256": summary["source_manifest_sha256"], + "source_exposure_batches": summary["source_exposure_batches"], + "wall_seconds": summary["wall_seconds"], + "gpu_hours": summary["gpu_hours"], + "frames_per_second": summary["frames_per_second"], + "peak_vram_gib": summary["peak_vram_gib"], + "official_test_used": False, + } + path = marker_path(queue, stage) + path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(path, marker) + previous_checkpoint = checkpoint + state["completed_stages"].append(stage["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + + state["status"] = "complete" + state["gpu_hours_consumed"] = attempt_gpu_hours(state["attempts"]) + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_qort_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_qort_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..9c50b6afa211f8c32cd790f2fc21f36ea2055aa0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_qort_h2o.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Run the official QORT-Former H2O checkpoint on the common cam4 validation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +import torch +import torchvision.transforms as transforms +from PIL import Image + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + repo = args.repo.resolve() + sys.path.insert(0, str(repo)) + from lib.qort_former import QORT_Former + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys = keys[: args.max_frames] + takes = takes[: args.max_frames] + frame_ids = frame_ids[: args.max_frames] + count = len(keys) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = QORT_Former(num_classes=11).to(device).eval() + model.load_state_dict(checkpoint, strict=True) + transform = transforms.Compose([ + transforms.Resize((540, 960)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + + # QORT's released inference denormalizes u/v by the raw image size and z by + # 1000 mm. H2O K then deterministically maps released (u,v,z) to camera XYZ. + from foundation_hand.evaluation.sota import GroundTruthBundle + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + detected = np.ones((count, 2), dtype=bool) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for start in range(0, count, args.batch_size): + end = min(start + args.batch_size, count) + images = [] + image_sizes = [] + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True): + path = args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png" + with Image.open(path) as image: + rgb = image.convert("RGB") + image_sizes.append(rgb.size) + images.append(transform(rgb)) + batch = torch.stack(images).to(device) + with torch.no_grad(): + outputs = model(batch) + logits = outputs["pred_logits"] + predictions = outputs["pred_keypoints"] + batch_indices = torch.arange(end - start, device=device) + left_index = logits[:, :, 9].argmax(dim=1) + right_index = logits[:, :, 10].argmax(dim=1) + left = predictions[0, batch_indices, left_index].reshape(-1, 21, 3) + right = predictions[1, batch_indices, right_index].reshape(-1, 21, 3) + uvz = torch.stack((left, right), dim=1).float().cpu().numpy() + scores = torch.stack(( + logits[batch_indices, left_index, 9].sigmoid(), + logits[batch_indices, right_index, 10].sigmoid(), + ), dim=1).float().cpu().numpy() + confidence[start:end] = scores + for local_index, (width, height) in enumerate(image_sizes): + uvz[local_index, ..., 0] *= width + uvz[local_index, ..., 1] *= height + z = uvz[local_index, ..., 2] + K = intrinsics[start + local_index] + joints[start + local_index, ..., 0] = (uvz[local_index, ..., 0] - K[0, 2]) / K[0, 0] * z + joints[start + local_index, ..., 1] = (uvz[local_index, ..., 1] - K[1, 2]) / K[1, 1] * z + joints[start + local_index, ..., 2] = z + if end % 100 == 0 or end == count: + print(f"QORT-Former {end}/{count}", flush=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output.resolve() + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "QORT-Former", + "scope": "RGB decode + resize/normalize + model forward + camera conversion", + "frames": count, + "processing_seconds": processing_seconds, + "frames_per_second": count / processing_seconds, + "batch_size": args.batch_size, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(repo), "rev-parse", "HEAD"], text=True + ).strip() + parameter_count = sum(parameter.numel() for parameter in model.parameters()) + bundle = PredictionBundle( + model_name="QORT-Former", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + detected=detected, + confidence=confidence, + vertices_camera_m=None, + metadata={ + "official_repository": "https://github.com/kcsayem/QORT-Former", + "repository_commit": commit, + "checkpoint": str(args.checkpoint.resolve()), + "checkpoint_sha256": sha256(args.checkpoint), + "parameter_count": parameter_count, + "input": "full RGB, resized to 960x540", + "temporal": False, + "detector": False, + "output_conversion": "official normalized u,v,z; raw H2O K unprojection", + "original_paper_metric": "mean endpoint error over 21 joints", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_wildhands_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_wildhands_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e77900e883aa37cc0b9aee3c5e030263be10f9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_wildhands_h2o.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Run the released WildHands checkpoint on H2O with a common hand detector.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import types +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, load_frame_index +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix + + +MANO_TO_OPENPOSE = np.asarray( + [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20], + dtype=np.int64, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-dir", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=1.75) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def install_pytorch3d_rotation_compatibility() -> None: + """Provide the three pure-PyTorch transforms used by the official model.""" + + rotation_conversions = types.ModuleType("pytorch3d.transforms.rotation_conversions") + rotation_conversions.axis_angle_to_matrix = axis_angle_to_matrix + rotation_conversions.rotation_6d_to_matrix = rotation_6d_to_matrix + rotation_conversions.matrix_to_rotation_6d = ( + lambda matrix: matrix[..., :2, :].clone().reshape(matrix.shape[:-2] + (6,)) + ) + transforms = types.ModuleType("pytorch3d.transforms") + transforms.rotation_conversions = rotation_conversions + pytorch3d = types.ModuleType("pytorch3d") + pytorch3d.transforms = transforms + sys.modules.update({ + "pytorch3d": pytorch3d, + "pytorch3d.transforms": transforms, + "pytorch3d.transforms.rotation_conversions": rotation_conversions, + }) + + +def recursive_to(value: Any, device: torch.device) -> Any: + if torch.is_tensor(value): + return value.to(device) + if isinstance(value, dict): + return {name: recursive_to(item, device) for name, item in value.items()} + if isinstance(value, tuple): + return tuple(recursive_to(item, device) for item in value) + if isinstance(value, list): + return [recursive_to(item, device) for item in value] + return value + + +def main() -> None: + args = parse_args() + for name in ("repo", "checkpoint", "detector", "mano_dir", "root", "manifest", "ground_truth", "output"): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + + os.environ["WILDHANDS_MANO_DIR"] = str(args.mano_dir) + sys.path.insert(0, str(args.repo)) + enable_legacy_mano_loading() + install_pytorch3d_rotation_compatibility() + os.chdir(args.repo) + + from ultralytics import YOLO + from wildhands.configs.parser import construct_args + from wildhands.datasets.dataset import WildHandsDataset + from wildhands.models.wrapper import WildHandsWrapper + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + config = construct_args() + model = WildHandsWrapper(config) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + ignored = ("head_o", "arti_head", "grasp_classifier") + state = { + name: value + for name, value in checkpoint["state_dict"].items() + if not any(token in name for token in ignored) + } + model.load_state_dict(state) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, Any]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = recursive_to(default_collate([record[3] for record in records]), device) + with torch.no_grad(): + output = model(batch) + right_joints = output["pred.j3d.cam.r"].float().cpu().numpy() + left_joints = output["pred.j3d.cam.l"].float().cpu().numpy() + right_vertices = output["pred.v3d.cam.r"].float().cpu().numpy() + left_vertices = output["pred.v3d.cam.l"].float().cpu().numpy() + for local, (frame_index, side, score, _) in enumerate(records): + batch_joints = right_joints[local] if side else left_joints[local] + batch_vertices = right_vertices[local] if side else left_vertices[local] + joints[frame_index, side] = batch_joints[MANO_TO_OPENPOSE] + vertices[frame_index, side] = batch_vertices + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images_bgr = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images_bgr): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images_bgr, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + rgb = cv2.cvtColor(images_bgr[local], cv2.COLOR_BGR2RGB) + intrinsic = intrinsics[frame_index] + focal = float(0.5 * (intrinsic[0, 0] + intrinsic[1, 1])) + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + dataset = WildHandsDataset( + config, + rgb, + boxes[[choice]], + np.asarray([side], dtype=np.float32), + focal_length=focal, + rescale_factor=args.rescale_factor, + intrx=intrinsic, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"WildHands detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/ap229997/hands", + "repository_branch": "demo", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector hand boxes, per-hand crops", + "training_exposure": "zero-shot H2O; released model trained on ARCTIC, AssemblyHands, and EPIC", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "camera_policy": "official WildHands weak-perspective conversion with known H2O intrinsics", + "joint_conversion": "official MANO output reordered to H2O/OpenPose convention", + "pytorch3d_compatibility": "three official pure-torch rotation formulas supplied without renderer", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="WildHands-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_wilor_h2o.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_wilor_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..cabd7ffbda3772dd8a1d4c3d23a13f7eba864eb0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/run_wilor_h2o.py @@ -0,0 +1,346 @@ +#!/usr/bin/env python3 +"""Run the complete official WiLoR detector + reconstruction pipeline on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--official-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument( + "--camera-policy", + choices=("official", "h2o_intrinsics", "both"), + default="official", + ) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.repo = args.repo.resolve() + args.checkpoint = args.checkpoint.resolve() + args.detector = args.detector.resolve() + args.mano_right = args.mano_right.resolve() + args.root = args.root.resolve() + args.manifest = args.manifest.resolve() + if args.ground_truth is not None: + args.ground_truth = args.ground_truth.resolve() + args.output = args.output.resolve() + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + if args.official_output is not None: + args.official_output = args.official_output.resolve() + mano_target = args.repo / "mano_data" / "MANO_RIGHT.pkl" + if not mano_target.exists(): + mano_target.symlink_to(args.mano_right) + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from ultralytics import YOLO + from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + from wilor.datasets.vitdet_dataset import ViTDetDataset + from wilor.models import load_wilor + from wilor.utils.renderer import cam_crop_to_full + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + intrinsics = None + if args.camera_policy in ("h2o_intrinsics", "both"): + if args.ground_truth is None: + raise ValueError("--camera-policy h2o_intrinsics requires --ground-truth") + from foundation_hand.evaluation.sota import GroundTruthBundle + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ + ground_truth.intrinsics[gt_index[str(key)]] for key in keys + ]) + if args.camera_policy == "both" and args.official_output is None: + raise ValueError("--camera-policy both requires --official-output") + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + + enable_legacy_mano_loading() + model, model_cfg = load_wilor( + checkpoint_path=str(args.checkpoint), + cfg_path=str(args.repo / "pretrained_models" / "model_config.yaml"), + ) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + official_joints = ( + np.full_like(joints, np.nan) if args.camera_policy == "both" else None + ) + official_vertices = ( + np.full_like(vertices, np.nan) if args.camera_policy == "both" else None + ) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + img_size = batch["img_size"].float() + official_focal = ( + model_cfg.EXTRA.FOCAL_LENGTH + / model_cfg.MODEL.IMAGE_SIZE + * img_size.max() + ) + official_camera_tensor = cam_crop_to_full( + pred_cam, box_center, box_size, img_size, official_focal + ) + calibrated_camera_tensor = None + if args.camera_policy in ("h2o_intrinsics", "both"): + record_indices = np.asarray([record[0] for record in records]) + K = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (K[:, 0, 0] + K[:, 1, 1]) + principal = K[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + calibrated_camera_tensor = torch.stack(( + pred_cam[:, 1] + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), dim=-1) + camera_tensor = ( + calibrated_camera_tensor + if calibrated_camera_tensor is not None + else official_camera_tensor + ) + camera = camera_tensor.float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + relative_joints = batch_joints.copy() + relative_vertices = batch_vertices.copy() + batch_joints += camera[:, None] + batch_vertices += camera[:, None] + if args.camera_policy == "both": + official_camera = official_camera_tensor.float().cpu().numpy() + batch_official_joints = relative_joints + official_camera[:, None] + batch_official_vertices = relative_vertices + official_camera[:, None] + for local, (frame_index, side, score, _) in enumerate(records): + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + if args.camera_policy == "both": + official_joints[frame_index, side] = batch_official_joints[local] + official_vertices[frame_index, side] = batch_official_vertices[local] + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop_dataset = ViTDetDataset( + model_cfg, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append(( + frame_index, side, float(scores[choice]), crop_dataset[0] + )) + flush_queue() + if end % 100 == 0 or end == count: + print(f"WiLoR detector {end}/{count}", flush=True) + flush_queue(force=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "WiLoR", + "scope": "RGB decode + detector + crop preprocessing + reconstruction + camera conversion", + "frames": count, + "detected_hand_frames": int(detected.sum()), + "processing_seconds": processing_seconds, + "frames_per_second": count / processing_seconds, + "detector_batch_size": args.detector_batch_size, + "reconstruction_batch_size": args.reconstruction_batch_size, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + effective_policy = ( + "h2o_intrinsics" if args.camera_policy == "both" else args.camera_policy + ) + metadata = { + "official_repository": "https://github.com/rolpotamias/WiLoR", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB detector, per-detection RGB crop reconstruction", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "official detector handedness; highest-confidence detection per side", + "camera_policy": effective_policy, + "camera_conversion": ( + "official cam_crop_to_full with released assumed focal" + if effective_policy == "official" + else "cam_crop_to_full algebra with known H2O focal/principal point" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name=( + "WiLoR-official-camera" + if effective_policy == "official" + else "WiLoR-H2O-K-calibrated" + ), + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + if args.camera_policy == "both": + official_metadata = dict(metadata) + official_metadata.update({ + "camera_policy": "official", + "camera_conversion": "official cam_crop_to_full with released assumed focal", + }) + PredictionBundle( + model_name="WiLoR-official-camera", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=official_joints, + vertices_camera_m=official_vertices, + detected=detected, + confidence=confidence, + metadata=official_metadata, + ).save(args.official_output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/screen_phase6_mixed_projection_oof.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/screen_phase6_mixed_projection_oof.py new file mode 100644 index 0000000000000000000000000000000000000000..71c0f7f48655721114a3fab67f4c9847cfdf1a0e --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/screen_phase6_mixed_projection_oof.py @@ -0,0 +1,484 @@ +#!/usr/bin/env python3 +"""Select Phase 6 mixed-projection constants on train OOF predictions only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.mixed_projection import ( + coarse_wrist_ray_translation, + direct_wrist_ray_translation, + solve_mixed_projection_batch, +) + + +FINGERTIPS = (4, 8, 12, 16, 20) +Z_MODES = ( + "coarse", + "raw_alignment", + "calibrated_always", + "calibrated_confidence_0p6", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_cross_validated_calibration( + path: Path, +) -> dict[tuple[int, str, int, int], tuple[float, float, bool]]: + lookup: dict[tuple[int, str, int, int], tuple[float, float, bool]] = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + hand = 1 if row["side"] == "right" else 0 + key = ( + int(row["coarse_seed"]), row["take"], int(row["frame_id"]), hand, + ) + if key in lookup: + raise ValueError(f"duplicate calibration row: {key}") + lookup[key] = ( + float(row["calibrated_delta_z_mm"]) / 1000.0, + float(row["confidence"]), + row["alignment_available"] == "True", + ) + if len(lookup) != 333_936: + raise ValueError(f"expanded calibration row count changed: {len(lookup)}") + return lookup + + +def candidate_specs() -> list[dict[str, object]]: + output: list[dict[str, object]] = [] + for z_mode in Z_MODES: + output.extend(( + {"id": f"direct_xyz__z_{z_mode}", "assembly": "direct_xyz", "z_mode": z_mode}, + {"id": f"coarse_wrist_ray__z_{z_mode}", "assembly": "coarse_wrist_ray", "z_mode": z_mode}, + {"id": f"direct_2d_wrist_ray__z_{z_mode}", "assembly": "direct_2d_wrist_ray", "z_mode": z_mode}, + )) + for support in (4, 8, 12): + output.append({ + "id": f"mixed_wls_s{support}__z_{z_mode}", + "assembly": "mixed_projection_21j_wls", + "z_mode": z_mode, + "minimum_support": support, + "huber_delta_px": None, + }) + for delta in (2.0, 4.0, 8.0, 16.0): + output.append({ + "id": f"mixed_huber_d{delta:g}_s{support}__z_{z_mode}", + "assembly": "robust_mixed_projection", + "z_mode": z_mode, + "minimum_support": support, + "huber_delta_px": delta, + }) + return output + + +def corrections_for_take( + arrays: dict[str, np.ndarray], + *, + seed: int, + calibration: dict[tuple[int, str, int, int], tuple[float, float, bool]], +) -> tuple[dict[str, np.ndarray], np.ndarray, np.ndarray]: + time = len(arrays["frame_id"]) + calibrated = np.zeros((time, 2), dtype=np.float64) + confidence = np.zeros((time, 2), dtype=np.float64) + available = np.zeros((time, 2), dtype=bool) + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + for time_index, hand in zip(*np.where(valid), strict=True): + key = (seed, take, int(arrays["frame_id"][time_index]), int(hand)) + try: + calibrated[time_index, hand], confidence[time_index, hand], available[time_index, hand] = calibration[key] + except KeyError as error: + raise ValueError(f"missing cross-validated calibration row: {key}") from error + raw_available = arrays["alignment_applied"].astype(bool) + raw = np.where(raw_available, arrays["alignment_delta_z_m"], 0.0) + always = np.where(available, calibrated, 0.0) + gated = np.where(available & (confidence >= 0.6), calibrated, 0.0) + return { + "coarse": np.zeros((time, 2), dtype=np.float64), + "raw_alignment": raw, + "calibrated_always": always, + "calibrated_confidence_0p6": gated, + }, calibrated, confidence + + +def assemble( + spec: dict[str, object], + *, + coarse: np.ndarray, + root_relative_joints: np.ndarray, + anchors: np.ndarray, + K: np.ndarray, + z: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + direct = coarse.copy() + direct[:, 2] = z + ray = coarse_wrist_ray_translation(coarse, z) + assembly = spec["assembly"] + diagnostics: dict[str, np.ndarray] = {} + if assembly == "direct_xyz": + return direct, diagnostics + if assembly == "coarse_wrist_ray": + return ray, diagnostics + if assembly == "direct_2d_wrist_ray": + translation, valid = direct_wrist_ray_translation(anchors, K, z, ray) + diagnostics["success"] = valid + return translation, diagnostics + result = solve_mixed_projection_batch( + root_relative_joints, anchors, K, z, ray, + image_hw=(368, 640), + minimum_support=int(spec["minimum_support"]), + robust_huber_delta_px=( + None if spec["huber_delta_px"] is None else float(spec["huber_delta_px"]) + ), + ) + diagnostics.update({ + "support_count": result.support_count, + "residual_scale_px": result.residual_scale_px, + "conditioning": result.conditioning, + "inlier_ratio": result.inlier_ratio, + "uncertainty_x_m": result.uncertainty_xy_m[:, 0], + "uncertainty_y_m": result.uncertainty_xy_m[:, 1], + "success": result.failure_reason == "ok", + "failure_reason": result.failure_reason, + }) + return result.translation_m, diagnostics + + +def project(points: np.ndarray, K: np.ndarray) -> np.ndarray: + z = np.maximum(points[..., 2], 1e-8) + return np.stack(( + K[:, None, 0, 0] * points[..., 0] / z + K[:, None, 0, 2], + K[:, None, 1, 1] * points[..., 1] / z + K[:, None, 1, 2], + ), axis=-1) + + +def evaluate_translation( + arrays: dict[str, np.ndarray], + indices: tuple[np.ndarray, np.ndarray], + translation: np.ndarray, +) -> dict[str, np.ndarray]: + time_index, hand = indices + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + shift = translation - coarse + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + shift[:, None] + target = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_translation = arrays["target_wrist_translation"][time_index, hand].astype(np.float64) + joint_error = np.linalg.norm(joints - target, axis=-1) * 1000.0 + signed_translation = (translation - target_translation) * 1000.0 + K = arrays["K_resized"][time_index].astype(np.float64) + projected = project(joints, K) + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + target_2d = arrays["target_2d_px"][time_index, hand].astype(np.float64) + return { + "absolute_mpjpe_mm": joint_error.mean(axis=1), + "fingertip_mpjpe_mm": joint_error[:, FINGERTIPS].mean(axis=1), + "translation_x_mae_mm": np.abs(signed_translation[:, 0]), + "translation_y_mae_mm": np.abs(signed_translation[:, 1]), + "translation_z_mae_mm": np.abs(signed_translation[:, 2]), + "projected_mano_2d_px": np.linalg.norm(projected - target_2d, axis=-1).mean(axis=1), + "direct_mano_consistency_px": np.linalg.norm(projected - anchors, axis=-1).mean(axis=1), + } + + +def distribution(values: np.ndarray) -> dict[str, float]: + values = np.asarray(values, dtype=np.float64) + threshold = float(np.percentile(values, 95)) + return { + "mean": float(values.mean()), + "p95": threshold, + "cvar95": float(values[values >= threshold].mean()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--calibration-json", type=Path, required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + calibration_report = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration_report.get("status") != "fitted" + or calibration_report.get("official_validation_used") is not False + or calibration_report.get("official_test_used") is not False + or calibration_report.get("samples") != 333_936 + or calibration_report.get("predictions", {}).get("sha256") + != sha256(args.calibration_predictions) + ): + raise ValueError("expanded OOF calibration contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + calibration = load_cross_validated_calibration(args.calibration_predictions) + specs = candidate_specs() + spec_by_id = {str(spec["id"]): spec for spec in specs} + per_take: dict[tuple[str, int, str], dict[str, float]] = {} + values: dict[str, dict[str, list[np.ndarray]]] = { + str(spec["id"]): defaultdict(list) for spec in specs + } + bank_records = [] + sample_order: list[tuple[int, str, int, int]] = [] + + for bank_index, registered in enumerate(calibration_report["bank_manifests"], start=1): + manifest_path = Path(registered["path"]) + if sha256(manifest_path) != registered["sha256"]: + raise ValueError(f"bank manifest hash mismatch: {manifest_path}") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("official_test_used") is not False + or manifest.get("leakage_audit", {}).get("passed") is not True + ): + raise ValueError(f"bank isolation contract failed: {manifest_path}") + seed = int(manifest["seed"]) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + needed = ( + "frame_id", "frame_valid", "K_resized", "pred_wrist_translation", + "pred_joints_camera", "pred_direct_2d_px", "target_wrist_translation", + "target_joints_camera", "target_2d_px", "mano_annotation_valid", + "alignment_delta_z_m", "alignment_applied", + ) + arrays = {key: archive[key] for key in needed} + arrays["take"] = archive["take"] + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + indices = np.where(valid) + time_index, hand = indices + corrections, _, _ = corrections_for_take( + arrays, seed=seed, calibration=calibration, + ) + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + root_relative = joints - joints[:, :1] + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + K = arrays["K_resized"][time_index].astype(np.float64) + take_sample_keys = [ + (seed, take, int(arrays["frame_id"][t]), int(h)) + for t, h in zip(time_index, hand, strict=True) + ] + sample_order.extend(take_sample_keys) + for spec in specs: + candidate_id = str(spec["id"]) + z_mode = str(spec["z_mode"]) + refined_z = coarse[:, 2] + corrections[z_mode][time_index, hand] + translation, diagnostics = assemble( + spec, coarse=coarse, root_relative_joints=root_relative, + anchors=anchors, K=K, z=refined_z, + ) + metrics = evaluate_translation(arrays, indices, translation) + for metric, metric_values in metrics.items(): + values[candidate_id][metric].append(metric_values.astype(np.float32)) + success = diagnostics.get("success", np.ones(len(translation), dtype=bool)) + per_take[(candidate_id, seed, take)] = { + "absolute_mpjpe_mm": float(metrics["absolute_mpjpe_mm"].mean()), + "fingertip_mpjpe_mm": float(metrics["fingertip_mpjpe_mm"].mean()), + "translation_x_mae_mm": float(metrics["translation_x_mae_mm"].mean()), + "translation_y_mae_mm": float(metrics["translation_y_mae_mm"].mean()), + "translation_z_mae_mm": float(metrics["translation_z_mae_mm"].mean()), + "projected_mano_2d_px": float(metrics["projected_mano_2d_px"].mean()), + "success_fraction": float(success.mean()), + } + bank_records.append({ + "manifest": str(manifest_path), "sha256": registered["sha256"], + "seed": seed, "fold": int(manifest["fold"]), + "heldout_subject": manifest["heldout_subject"], + "takes": len(manifest["takes"]), "frames": int(manifest["frames"]), + }) + print(f"[{bank_index}/9] fold{manifest['fold']} seed{seed} complete", flush=True) + + if len(sample_order) != 333_936 or len(set(sample_order)) != len(sample_order): + raise ValueError("OOF sample coverage or uniqueness changed") + summary_rows = [] + concatenated: dict[str, dict[str, np.ndarray]] = {} + for spec in specs: + candidate_id = str(spec["id"]) + candidate_values = { + metric: np.concatenate(chunks) + for metric, chunks in values[candidate_id].items() + } + concatenated[candidate_id] = candidate_values + take_rows = [value for (name, _, _), value in per_take.items() if name == candidate_id] + z_mode = str(spec["z_mode"]) + baseline_id = f"direct_xyz__z_{z_mode}" + row: dict[str, object] = { + **spec, + "samples": len(candidate_values["absolute_mpjpe_mm"]), + "seed_take_groups": len(take_rows), + "absolute_frame_mean_mm": float(candidate_values["absolute_mpjpe_mm"].mean()), + "absolute_take_mean_mm": float(np.mean([item["absolute_mpjpe_mm"] for item in take_rows])), + "fingertip_frame_mean_mm": float(candidate_values["fingertip_mpjpe_mm"].mean()), + "translation_x_mae_mm": float(candidate_values["translation_x_mae_mm"].mean()), + "translation_x_p95_mm": float(np.percentile(candidate_values["translation_x_mae_mm"], 95)), + "translation_y_mae_mm": float(candidate_values["translation_y_mae_mm"].mean()), + "translation_y_p95_mm": float(np.percentile(candidate_values["translation_y_mae_mm"], 95)), + "translation_z_mae_mm": float(candidate_values["translation_z_mae_mm"].mean()), + "projected_mano_2d_px": float(candidate_values["projected_mano_2d_px"].mean()), + "direct_mano_consistency_px": float(candidate_values["direct_mano_consistency_px"].mean()), + "success_fraction": float(np.mean([item["success_fraction"] for item in take_rows])), + } + if candidate_id == baseline_id: + row.update({ + "absolute_frame_delta_vs_same_z_direct_mm": 0.0, + "absolute_take_delta_vs_same_z_direct_mm": 0.0, + "largest_take_harm_mm": 0.0, + "largest_sample_harm_mm": 0.0, + "absolute_guardrail_passed": True, + }) + summary_rows.append(row) + + row_by_id = {str(row["id"]): row for row in summary_rows} + for row in summary_rows: + candidate_id = str(row["id"]) + baseline_id = f"direct_xyz__z_{row['z_mode']}" + if candidate_id == baseline_id: + continue + baseline = row_by_id[baseline_id] + take_deltas = [] + for (name, seed, take), item in per_take.items(): + if name != candidate_id: + continue + take_deltas.append( + item["absolute_mpjpe_mm"] + - per_take[(baseline_id, seed, take)]["absolute_mpjpe_mm"] + ) + sample_delta = ( + concatenated[candidate_id]["absolute_mpjpe_mm"] + - concatenated[baseline_id]["absolute_mpjpe_mm"] + ) + frame_delta = float(row["absolute_frame_mean_mm"] - baseline["absolute_frame_mean_mm"]) + take_delta = float(row["absolute_take_mean_mm"] - baseline["absolute_take_mean_mm"]) + guardrail = min(0.2, 0.01 * float(baseline["absolute_frame_mean_mm"])) + row.update({ + "absolute_frame_delta_vs_same_z_direct_mm": frame_delta, + "absolute_take_delta_vs_same_z_direct_mm": take_delta, + "largest_take_harm_mm": float(np.max(take_deltas)), + "largest_sample_harm_mm": float(np.max(sample_delta)), + "absolute_guardrail_passed": frame_delta <= guardrail, + }) + + eligible = [ + row for row in summary_rows + if row["assembly"] != "direct_xyz" and row["absolute_guardrail_passed"] + ] + eligible.sort(key=lambda row: ( + float(row["absolute_take_mean_mm"]), + float(row["largest_take_harm_mm"]), + max(float(row["translation_x_p95_mm"]), float(row["translation_y_p95_mm"])), + float(row["projected_mano_2d_px"]), + distribution(concatenated[str(row["id"])]["absolute_mpjpe_mm"])["cvar95"], + 0 if row["assembly"] == "mixed_projection_21j_wls" else 1, + )) + if not eligible: + raise RuntimeError("no mixed-projection setting passes the preregistered guardrail") + best_take = float(eligible[0]["absolute_take_mean_mm"]) + tied = [row for row in eligible if float(row["absolute_take_mean_mm"]) <= best_take + 0.02] + tied.sort(key=lambda row: ( + float(row["largest_take_harm_mm"]), + max(float(row["translation_x_p95_mm"]), float(row["translation_y_p95_mm"])), + float(row["projected_mano_2d_px"]), + distribution(concatenated[str(row["id"])]["absolute_mpjpe_mm"])["cvar95"], + 0 if row["assembly"] == "mixed_projection_21j_wls" else 1, + )) + winner = tied[0] + winner_id = str(winner["id"]) + baseline_id = f"direct_xyz__z_{winner['z_mode']}" + winner_delta = ( + concatenated[winner_id]["absolute_mpjpe_mm"] + - concatenated[baseline_id]["absolute_mpjpe_mm"] + ) + order_gain = np.argsort(winner_delta)[:20] + order_harm = np.argsort(winner_delta)[-20:][::-1] + case_rows = [] + for role, order in (("largest_gain", order_gain), ("largest_harm", order_harm)): + for rank, index in enumerate(order, start=1): + seed, take, frame_id, hand = sample_order[int(index)] + case_rows.append({ + "role": role, "rank": rank, "sample_index": int(index), + "seed": seed, "take": take, "frame_id": frame_id, + "side": "right" if hand else "left", + "winner": winner_id, "baseline": baseline_id, + "absolute_delta_mm": float(winner_delta[index]), + "winner_absolute_mpjpe_mm": float(concatenated[winner_id]["absolute_mpjpe_mm"][index]), + "baseline_absolute_mpjpe_mm": float(concatenated[baseline_id]["absolute_mpjpe_mm"][index]), + }) + + write_csv(args.output_dir / "oof_grid.csv", summary_rows) + write_csv(args.output_dir / "largest_gain_harm.csv", case_rows) + report = { + "status": "selected_oof_only", + "experiment": "P6_S1_cache_mixed_projection", + "official_validation_used": False, + "official_test_used": False, + "oracle_information": False, + "samples": len(sample_order), + "seed_take_groups": len({(seed, take) for seed, take, _, _ in sample_order}), + "physical_takes": len({take for _, take, _, _ in sample_order}), + "seeds": sorted({seed for seed, _, _, _ in sample_order}), + "banks": bank_records, + "calibration": { + "json": str(args.calibration_json.resolve()), + "json_sha256": sha256(args.calibration_json), + "cross_validated_predictions": str(args.calibration_predictions.resolve()), + "predictions_sha256": sha256(args.calibration_predictions), + "confidence_threshold": 0.6, + }, + "grid": { + "conditions": len(specs), "minimum_support": [4, 8, 12], + "huber_delta_px": [2.0, 4.0, 8.0, 16.0], + "irls_iterations": 5, + "mask": "predicted finite + positive z>0.05m + in-frame anchor", + "fallback": "coarse wrist ray at same selected z; direct xyz if K invalid", + }, + "selection_rule": ( + "minimize seed-take-equal Absolute within same-z direct guardrail; " + "0.02mm tie band then largest-take harm, xy P95, projected 2D, CVaR95, WLS simplicity" + ), + "winner": winner, + "same_z_direct_baseline": row_by_id[baseline_id], + "outputs": {"grid": "oof_grid.csv", "largest_gain_harm": "largest_gain_harm.csv"}, + } + (args.output_dir / "selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "winner": winner_id, + "absolute_take_mean_mm": winner["absolute_take_mean_mm"], + "absolute_delta_mm": winner["absolute_take_delta_vs_same_z_direct_mm"], + "projected_mano_2d_px": winner["projected_mano_2d_px"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/seed_phase9_cache_hardlinks.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/seed_phase9_cache_hardlinks.py new file mode 100644 index 0000000000000000000000000000000000000000..24c63f0ecef2de0911cd4cb725ab7bafc274d7f5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/seed_phase9_cache_hardlinks.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Seed an expanded cache with hash-verified hardlinks from an older cache.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def seed_hardlinks( + manifest: Path, output_dir: Path, expected_dataset: str, +) -> dict[str, Any]: + rows = [ + json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not rows or {row.get("dataset_id") for row in rows} != {expected_dataset}: + raise ValueError("source cache manifest dataset differs from expectation") + clips_dir = output_dir / "clips" + clips_dir.mkdir(parents=True, exist_ok=True) + logical_bytes = 0 + reused = 0 + for row in rows: + source = Path(row["cache_path"]) + if not source.is_file() or sha256(source) != row["cache_sha256"]: + raise ValueError(f"source payload is missing or differs: {source}") + target = clips_dir / source.name + if target.exists(): + if not target.is_file() or sha256(target) != row["cache_sha256"]: + raise ValueError(f"existing target payload differs: {target}") + else: + os.link(source, target) + logical_bytes += source.stat().st_size + reused += 1 + return { + "schema_version": "phase9_cache_hardlink_seed_v1", + "status": "complete", + "dataset": expected_dataset, + "source_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "output_dir": str(output_dir.resolve()), + "hardlinked_clips": reused, + "logical_bytes": logical_bytes, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-cache-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--dataset", choices=("HOT3D", "HOI4D", "ARCTIC"), required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + if args.report.exists(): + parser.error("report already exists") + try: + result = seed_hardlinks(args.source_cache_manifest, args.output_dir, args.dataset) + except (OSError, ValueError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.report.parent.mkdir(parents=True, exist_ok=True) + temporary = args.report.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.report) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/select_phase7_external_continuation.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/select_phase7_external_continuation.py new file mode 100644 index 0000000000000000000000000000000000000000..b9332b63326456953ca11d008b1a0f69c2b42c24 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/select_phase7_external_continuation.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Select the final external checkpoint across frozen continuation steps.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.rank_phase7_external import METRICS, dense_ranks, evaluation_metrics, pareto_frontier +from scripts.build_phase7_scale_eval_queue import sha256 + + +DATASETS = ("ARCTIC", "HOI4D", "HOT3D") + + +def load_candidates(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if manifest.get("selection_split") != "external_heldout_only": + raise ValueError("continuation selection must be external-heldout only") + if set(manifest.get("datasets", [])) != set(DATASETS): + raise ValueError("continuation selection requires all three external datasets") + entries: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + for item in manifest.get("evaluations", []): + candidate, dataset = str(item["candidate"]), str(item["dataset"]) + if dataset not in DATASETS or (candidate, dataset) in seen: + raise ValueError(f"invalid or duplicate candidate/dataset pair: {(candidate, dataset)}") + seen.add((candidate, dataset)) + path = Path(item["path"]).resolve() + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or "h2o" in str(report["cache_manifest"]["path"]).lower() + ): + raise ValueError(f"non-external evaluation in continuation selection: {path}") + checkpoint = Path(report["checkpoint"]["path"]) + config = Path(report["config"]["path"]) + if sha256(checkpoint) != report["checkpoint"]["sha256"]: + raise ValueError(f"checkpoint hash mismatch: {checkpoint}") + if sha256(config) != report["config"]["sha256"]: + raise ValueError(f"config hash mismatch: {config}") + take_path = Path(report["take_metrics"]["path"]) + if sha256(take_path) != report["take_metrics"]["sha256"]: + raise ValueError(f"take metrics hash mismatch: {take_path}") + per_hand_path = Path(report["per_hand_rows"]["path"]) + if sha256(per_hand_path) != report["per_hand_rows"]["sha256"]: + raise ValueError(f"per-hand metrics hash mismatch: {per_hand_path}") + entries.append({ + "candidate": candidate, "dataset": dataset, + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint_path": str(checkpoint.resolve()), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config_path": str(config.resolve()), + "config_sha256": report["config"]["sha256"], + "evaluation_path": str(path), "take_metrics_path": str(take_path.resolve()), + "per_hand_metrics_path": str(per_hand_path.resolve()), + **evaluation_metrics(report), + }) + candidates = {entry["candidate"] for entry in entries} + missing = {(candidate, dataset) for candidate in candidates for dataset in DATASETS} - seen + if missing or len(candidates) < 2: + raise ValueError(f"incomplete continuation candidate grid: {sorted(missing)}") + for candidate in candidates: + selected = [entry for entry in entries if entry["candidate"] == candidate] + for field in ("checkpoint_step", "checkpoint_path", "checkpoint_sha256", "config_path", "config_sha256"): + if len({entry[field] for entry in selected}) != 1: + raise ValueError(f"candidate {candidate} has inconsistent {field}") + return entries + + +def rank_candidates(entries: list[dict[str, Any]]) -> dict[str, Any]: + candidates = sorted({entry["candidate"] for entry in entries}) + lookup = {(entry["candidate"], entry["dataset"]): entry for entry in entries} + dataset_ranks: dict[str, dict[str, float]] = {} + vectors = {candidate: [] for candidate in candidates} + for dataset in DATASETS: + ranks = { + metric: dense_ranks({candidate: lookup[(candidate, dataset)][metric] for candidate in candidates}) + for metric in METRICS + } + dataset_ranks[dataset] = {} + for candidate in candidates: + dataset_ranks[dataset][candidate] = sum(ranks[metric][candidate] for metric in METRICS) / len(METRICS) + vectors[candidate].extend(lookup[(candidate, dataset)][metric] for metric in METRICS) + macro = { + candidate: sum(dataset_ranks[dataset][candidate] for dataset in DATASETS) / len(DATASETS) + for candidate in candidates + } + order = sorted(candidates, key=lambda candidate: ( + macro[candidate], + sum(lookup[(candidate, dataset)]["absolute_mpjpe_mm"] for dataset in DATASETS), + sum(lookup[(candidate, dataset)]["root_relative_mpjpe_mm"] for dataset in DATASETS), + candidate, + )) + return { + "dataset_ranks": dataset_ranks, "macro_mean_rank": macro, + "pareto_frontier": pareto_frontier(vectors), "order": order, "winner": order[0], + } + + +def read_take_values( + path: Path, metric: str, statistic: str = "mean", +) -> dict[str, float]: + with path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + grouped: dict[str, list[float]] = {} + for row in rows: + value = float(row[metric]) + if math.isfinite(value): + grouped.setdefault(row["physical_recording_id"], []).append(value) + if statistic == "mean": + values = {key: float(np.mean(group)) for key, group in grouped.items()} + elif statistic == "p95": + values = {key: float(np.quantile(group, .95)) for key, group in grouped.items()} + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + if not values: + raise ValueError(f"no finite {metric} take values: {path}") + return values + + +def paired_take_bootstrap( + reference_path: Path, candidate_path: Path, metric: str, seed: int, resamples: int, + statistic: str = "mean", +) -> dict[str, Any]: + reference = read_take_values(reference_path, metric, statistic) + candidate = read_take_values(candidate_path, metric, statistic) + if set(reference) != set(candidate): + raise ValueError(f"paired take IDs differ for {metric}") + keys = sorted(reference) + delta = np.asarray([candidate[key] - reference[key] for key in keys], dtype=np.float64) + rng = np.random.default_rng(seed) + samples = delta[rng.integers(0, len(delta), size=(resamples, len(delta)))].mean(axis=1) + return { + "unit": "physical_recording", "recording_statistic": statistic, + "take_count": len(delta), + "delta_definition": "candidate_minus_reference; negative favors candidate", + "mean_delta": float(delta.mean()), + "ci95_low": float(np.percentile(samples, 2.5)), + "ci95_high": float(np.percentile(samples, 97.5)), + "resamples": resamples, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--funnel-selection", type=Path, required=True) + parser.add_argument("--expected-funnel-winner", required=True) + parser.add_argument("--reference-candidate", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--seed", type=int, default=20260717) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + funnel = json.loads(args.funnel_selection.read_text(encoding="utf-8")) + if ( + funnel.get("status") != "ranked_external_only" + or funnel.get("winner") != args.expected_funnel_winner + or funnel.get("h2o_used") is not False + or funnel.get("official_test_used") is not False + ): + parser.error("funnel selection does not match the frozen external-only decision") + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + entries = load_candidates(manifest) + ranking = rank_candidates(entries) + if args.reference_candidate not in ranking["order"]: + parser.error("reference candidate is absent") + lookup = {(entry["candidate"], entry["dataset"]): entry for entry in entries} + paired: dict[str, Any] = {} + paired_specs = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), + } + for candidate in ranking["order"]: + if candidate == args.reference_candidate: + continue + paired[candidate] = { + dataset: { + metric_name: paired_take_bootstrap( + Path(lookup[(args.reference_candidate, dataset)]["per_hand_metrics_path"]), + Path(lookup[(candidate, dataset)]["per_hand_metrics_path"]), + row_metric, args.seed, args.bootstrap_resamples, statistic, + ) + for metric_name, (row_metric, statistic) in paired_specs.items() + } + for dataset in DATASETS + } + winner = ranking["winner"] + winner_entries = [entry for entry in entries if entry["candidate"] == winner] + first = winner_entries[0] + result = { + "status": "selected_external_generalist_no_h2o", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "selection_rule": "dataset metric ranks -> macro mean rank -> Absolute/root-relative tie-break", + "selection_split": "external_heldout_only", "frame_count_weighted": False, + "funnel_selection": { + "path": str(args.funnel_selection.resolve()), "sha256": sha256(args.funnel_selection), + "winner": args.expected_funnel_winner, + }, + "candidate_manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "reference_candidate": args.reference_candidate, + **ranking, "entries": entries, "paired_take_bootstrap": paired, + "checkpoint": { + "path": first["checkpoint_path"], "sha256": first["checkpoint_sha256"], + "step": first["checkpoint_step"], + }, + "config": {"path": first["config_path"], "sha256": first["config_sha256"]}, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/select_phase7_h2o_adaptation.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/select_phase7_h2o_adaptation.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8d06a6082f25489ca5816a83149e0eba2424aa --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/select_phase7_h2o_adaptation.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Select a Phase 7 adaptation branch using H2O train-group-heldout only.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.build_phase7_scale_eval_queue import sha256 + + +PRIMARY_METRIC = "absolute_mpjpe_mm" +METRIC_SPECS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} +IDENTITY_FIELDS = ("physical_recording_id", "camera_id", "frame_id", "side") + + +def checked_artifact(record: dict[str, Any], name: str) -> Path: + artifact = record[name] + path = Path(artifact["path"]).resolve() + if not path.is_file() or sha256(path) != artifact["sha256"]: + raise ValueError(f"{name} is missing or has a SHA256 mismatch: {path}") + return path + + +def load_candidates(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if ( + manifest.get("selection_split") != "h2o_train_group_heldout_only" + or manifest.get("h2o_official_validation_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("selection manifest violates the H2O train-heldout boundary") + candidates: list[dict[str, Any]] = [] + names: set[str] = set() + cache_sha256: set[str] = set() + for item in manifest.get("candidates", []): + name = str(item["candidate"]) + if name in names: + raise ValueError(f"duplicate candidate: {name}") + names.add(name) + report_path = Path(item["evaluation"]).resolve() + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_h2o_train_group_heldout" + or report.get("evaluation_role") != "h2o_train_group_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or Path(report["cache_manifest"]["path"]).name != "train_group_heldout.jsonl" + ): + raise ValueError(f"candidate is not a valid train-heldout evaluation: {report_path}") + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + per_hand = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + cache = checked_artifact(report, "cache_manifest") + cache_sha256.add(report["cache_manifest"]["sha256"]) + metrics = { + metric: float(report["metrics"][row_metric]["mean"]) + for metric, (row_metric, statistic) in METRIC_SPECS.items() + if statistic == "mean" + } + metrics["translation_z_p95_mm"] = float( + report["metrics"]["translation_z_mae_mm"]["p95"] + ) + if not all(math.isfinite(value) for value in metrics.values()): + raise ValueError(f"candidate contains non-finite metrics: {name}") + candidates.append({ + "candidate": name, + "evaluation": str(report_path), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config), + "config_sha256": report["config"]["sha256"], + "cache_manifest": str(cache), + "cache_manifest_sha256": report["cache_manifest"]["sha256"], + "per_hand_rows": str(per_hand), + "metrics": metrics, + }) + if len(candidates) < 2: + raise ValueError("adaptation selection requires at least two candidates") + if len(cache_sha256) != 1: + raise ValueError("adaptation candidates use different train-heldout manifests") + return candidates + + +def read_paired_rows(path: Path, metric: str) -> dict[tuple[str, ...], float]: + result: dict[tuple[str, ...], float] = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + identity = tuple(str(row[field]) for field in IDENTITY_FIELDS) + if identity in result: + raise ValueError(f"duplicate per-hand identity: {identity}") + result[identity] = float(row[metric]) + return result + + +def paired_recording_bootstrap( + reference: Path, + candidate: Path, + metric: str, + statistic: str, + seed: int, + resamples: int, +) -> dict[str, Any]: + reference_rows = read_paired_rows(reference, metric) + candidate_rows = read_paired_rows(candidate, metric) + if set(reference_rows) != set(candidate_rows): + raise ValueError(f"paired per-hand identities differ for {metric}") + grouped: dict[str, list[tuple[float, float]]] = {} + for identity in sorted(reference_rows): + reference_value, candidate_value = reference_rows[identity], candidate_rows[identity] + if math.isfinite(reference_value) and math.isfinite(candidate_value): + grouped.setdefault(identity[0], []).append((reference_value, candidate_value)) + if not grouped: + raise ValueError(f"no finite paired values for {metric}") + deltas = [] + for recording in sorted(grouped): + values = np.asarray(grouped[recording], dtype=np.float64) + if statistic == "mean": + delta = values[:, 1].mean() - values[:, 0].mean() + elif statistic == "p95": + delta = np.quantile(values[:, 1], .95) - np.quantile(values[:, 0], .95) + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + deltas.append(float(delta)) + array = np.asarray(deltas, dtype=np.float64) + rng = np.random.default_rng(seed) + samples = array[rng.integers(0, len(array), size=(resamples, len(array)))].mean(1) + return { + "unit": "physical_recording", + "recording_statistic": statistic, + "recordings": len(array), + "delta_definition": "candidate_minus_reference; negative favors candidate", + "mean_delta": float(array.mean()), + "ci95_low": float(np.quantile(samples, .025)), + "ci95_high": float(np.quantile(samples, .975)), + "resamples": resamples, + } + + +def select( + manifest: dict[str, Any], seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + candidates = load_candidates(manifest) + order = sorted(candidates, key=lambda item: ( + item["metrics"][PRIMARY_METRIC], + item["metrics"]["root_relative_mpjpe_mm"], + item["metrics"]["fingertip_mpjpe_mm"], + item["candidate"], + )) + reference = order[0] + paired = {} + for candidate in order[1:]: + paired[candidate["candidate"]] = { + metric_name: paired_recording_bootstrap( + Path(reference["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for metric_name, (row_metric, statistic) in METRIC_SPECS.items() + } + return { + "status": "selected_h2o_adaptation_train_group_heldout", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "selection_rule": "lowest train-group-heldout Absolute MPJPE; root-relative then fingertip tie-break; no multi-seed or one-percent gate", + "selection_split": "h2o_train_group_heldout_only", + "primary_metric": PRIMARY_METRIC, + "winner": reference["candidate"], + "order": [item["candidate"] for item in order], + "candidates": candidates, + "paired_recording_bootstrap_vs_winner": paired, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + result = select( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, + resamples=args.bootstrap_resamples, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase4_a3.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase4_a3.py new file mode 100644 index 0000000000000000000000000000000000000000..d8de0510886c2ea270a8dc11eb799add21226b64 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase4_a3.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +"""Real-batch equality/backward smoke for the A3 oracle crop refiner.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def attach_gt_vertices( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> None: + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + with torch.no_grad(): + vertices, _ = model.mano_layer( + axis_angle_to_matrix(pose), + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = ( + batch["mano_annotation_valid"].bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where( + valid, vertices, torch.full_like(vertices, torch.nan), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--mode", choices=( + "oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k", + ), required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + actual_hash = file_sha256(args.checkpoint) + if actual_hash != args.expected_checkpoint_sha256: + parser.error( + f"checkpoint hash mismatch: {actual_hash} != {args.expected_checkpoint_sha256}" + ) + args.output_dir.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load(args.base_config.read_text(encoding="utf-8")) + seed = int(config["seed"]) + torch.manual_seed(seed) + data, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + photometric_augmentation=data.get("photometric_augmentation"), + augmentation_seed=seed, oracle_crop_enabled=True, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + device = torch.device(f"cuda:{args.gpu}") + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + common_model = { + **config["model"], + "dinov3_source": assets["dinov3_source"], + "dinov3_weights": assets["dinov3_weights"], + "mano_root": assets["mano_root"], + } + base = BimanualReconstructionModel(ModelConfig(**common_model)).to(device).eval() + load_checkpoint(args.checkpoint, base, optimizer=None, map_location=device) + refined_config = ModelConfig( + **common_model, oracle_crop_mode=args.mode, + freeze_coarse_for_oracle_crop=True, + ) + refined = BimanualReconstructionModel(refined_config).to(device).eval() + initialization = load_model_initialization( + args.checkpoint, refined, + allowed_missing_prefixes=("oracle_crop_",), map_location=device, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + base_output = base(batch) + refined_output = refined(batch) + comparisons = { + "joint2d": torch.equal( + base_output["joint2d_norm"], refined_output["joint2d_norm"], + ), + "rotations": torch.equal( + base_output["mano_rotation_matrices"], + refined_output["coarse_mano_rotation_matrices"], + ) and torch.equal( + refined_output["mano_rotation_matrices"], + refined_output["coarse_mano_rotation_matrices"], + ), + "shape": torch.equal( + base_output["mano_shape"], refined_output["coarse_mano_shape"], + ) and torch.equal( + refined_output["mano_shape"], refined_output["coarse_mano_shape"], + ), + "translation": torch.equal( + base_output["wrist_root_translation"], + refined_output["coarse_wrist_root_translation"], + ) and torch.equal( + refined_output["wrist_root_translation"], + refined_output["coarse_wrist_root_translation"], + ), + "joints": torch.equal( + base_output["joints_camera"], refined_output["coarse_joints_camera"], + ) and torch.equal( + refined_output["joints_camera"], refined_output["coarse_joints_camera"], + ), + "vertices": torch.equal( + base_output["vertices_camera"], refined_output["coarse_vertices_camera"], + ) and torch.equal( + refined_output["vertices_camera"], refined_output["coarse_vertices_camera"], + ), + } + if not all(comparisons.values()): + raise RuntimeError(f"zero-init coarse/refined equality failed: {comparisons}") + del base, base_output, refined_output + torch.cuda.empty_cache() + + refined.train() + attach_gt_vertices(batch, refined) + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + trainable = { + name: value for name, value in refined.named_parameters() + if value.requires_grad + } + if not trainable or any(not name.startswith("oracle_crop_") for name in trainable): + raise RuntimeError("A3 smoke found trainable non-oracle parameters") + optimizer = torch.optim.AdamW(trainable.values(), lr=5e-5, weight_decay=0.05) + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=dtype): + prediction = refined(batch) + losses = criterion(prediction, batch) + losses["total"].backward() + gradients_finite = all( + parameter.grad is None or bool(torch.isfinite(parameter.grad).all()) + for parameter in trainable.values() + ) + heads_with_gradient = sorted( + name for name, parameter in trainable.items() + if parameter.grad is not None and bool(torch.count_nonzero(parameter.grad)) + ) + if not gradients_finite or not heads_with_gradient: + raise RuntimeError("A3 smoke backward did not produce finite head gradients") + optimizer.step() + smoke_checkpoint = args.output_dir / "smoke_checkpoint.pt" + save_checkpoint( + smoke_checkpoint, refined, optimizer, 1, + extra={ + "phase": 4, "wave": "A3", "mode": args.mode, + "coarse_checkpoint_sha256": actual_hash, + "official_test_used": False, + }, + exclude_prefixes=("rgb_encoder.backbone.",), + ) + reloaded = BimanualReconstructionModel(refined_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + [value for value in reloaded.parameters() if value.requires_grad], + lr=5e-5, weight_decay=0.05, + ) + resume = load_checkpoint( + smoke_checkpoint, reloaded, reloaded_optimizer, map_location=device, + ) + reload_exact = all( + key.startswith("rgb_encoder.backbone.") + or torch.equal(value, reloaded.state_dict()[key]) + for key, value in refined.state_dict().items() + ) + payload = { + "status": "passed", + "official_test_used": False, + "mode": args.mode, + "seed": seed, + "coarse_checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": actual_hash, + "step": initialization["step"], + }, + "initialization_residual_missing_keys": initialization["residual_missing_keys"], + "checkpoint_excluded_prefixes": initialization[ + "checkpoint_excluded_prefixes" + ], + "zero_init_exact": comparisons, + "trainable_parameters": sum(value.numel() for value in trainable.values()), + "trainable_names_oracle_only": True, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "gradients_finite": gradients_finite, + "heads_with_gradient": heads_with_gradient, + "checkpoint_reload_exact": bool(reload_exact and resume["step"] == 1), + "oracle_crop_available_fraction": float( + batch["oracle_crop_available"].float().mean() + ), + "oracle_crop_depth_available_fraction": float( + batch["oracle_crop_depth_available"].float().mean() + ), + } + if not payload["checkpoint_reload_exact"]: + raise RuntimeError("A3 smoke checkpoint reload was not exact") + (args.output_dir / "smoke.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(payload, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase5_structured.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase5_structured.py new file mode 100644 index 0000000000000000000000000000000000000000..32656058c47b6e540b61932cf600b3a86860e640 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase5_structured.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Real-checkpoint forward/backward smoke for Phase 5 structured refinement.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("structured smoke output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if not config.get("model", {}).get("structured_hand_refinement", False): + raise ValueError("smoke requires a structured-hand config") + expected_hash = config.get("experiment", {}).get("coarse_checkpoint_sha256") + if sha256(args.checkpoint) != expected_hash: + raise ValueError("coarse checkpoint hash does not match the registered config") + seed = int(config["seed"]) + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("structured_",), + map_location=device, + ) + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-6, weight_decay=0.05) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + exact_zero_init = { + "joint2d": torch.equal(prediction["joint2d_norm"], prediction["coarse_joint2d_norm"]), + "rotation": torch.equal( + prediction["mano_rotation_matrices"], + prediction["coarse_mano_rotation_matrices"], + ), + "shape_sequence": torch.equal( + prediction["mano_shape_sequence"], + prediction["coarse_mano_shape_sequence"], + ), + "shape": torch.equal(prediction["mano_shape"], prediction["coarse_mano_shape"]), + "translation": torch.equal( + prediction["wrist_root_translation"], + prediction["coarse_wrist_root_translation"], + ), + } + losses["total"].backward() + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + residual_head_gradients = { + name: bool( + parameter.grad is not None and torch.isfinite(parameter.grad).all() + ) + for name, parameter in model.named_parameters() + if name.startswith("structured_") and name.endswith("weight") + } + required_head_gradients = { + name: finite for name, finite in residual_head_gradients.items() + if model_config.structured_refine_translation + or not name.startswith("structured_translation_head.") + } + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + args.output_dir.mkdir(parents=True, exist_ok=True) + checkpoint = args.output_dir / "structured_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, step=1, + extra={"kind": "phase5_structured_real_checkpoint_smoke"}, + exclude_prefixes=("rgb_encoder.backbone.",), + ) + expected_state = { + key: value.detach().cpu().clone() + for key, value in model.state_dict().items() + if not key.startswith("rgb_encoder.backbone.") + } + del prediction, losses, model, optimizer, criterion + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW(reloaded.parameters(), lr=5e-6, weight_decay=0.05) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected_state.items() + ) + shared_initialization_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("structured_", "rgb_encoder.backbone.")) + ] + passed = bool( + all(exact_zero_init.values()) + and all(required_head_gradients.values()) + and all(np.isfinite(value) for value in loss_values.values()) + and not shared_initialization_missing + and resume_exact + and resumed["step"] == 1 + ) + result = { + "status": "passed" if passed else "failed", + "experiment_class": "engineering_real_checkpoint_smoke", + "formal_training": False, + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "seed": seed, + "resolution_hw": data["resolution_hw"], + "T": data["T"], + "precision": config["precision"], + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_initialization_missing, + "exact_zero_initialization": exact_zero_init, + "losses": loss_values, + "losses_finite": all(np.isfinite(value) for value in loss_values.values()), + "gradient_norm": gradient_norm, + "residual_head_gradients_finite": residual_head_gradients, + "required_residual_head_gradients_finite": required_head_gradients, + "elapsed_s": elapsed, + "frames_per_s": int(data["T"]) / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "smoke_checkpoint": { + "path": str(checkpoint.resolve()), "sha256": sha256(checkpoint), + }, + "trainable_parameters": sum( + parameter.numel() for parameter in reloaded.parameters() + if parameter.requires_grad + ), + "frozen_parameters": sum( + parameter.numel() for parameter in reloaded.parameters() + if not parameter.requires_grad + ), + } + (args.output_dir / "smoke.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": result["status"], "exact_zero_initialization": exact_zero_init, + "resume_exact": resume_exact, "checkpoint": result["smoke_checkpoint"], + }, indent=2)) + if result["status"] != "passed": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase6_mixed_projection.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase6_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..e77188fd1466a88d3953ae576c22e44590e495bc --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase6_mixed_projection.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Real-checkpoint smoke for differentiable Phase 6 mixed projection.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def prefix(batch: dict[str, object], length: int) -> dict[str, object]: + output = {} + for key, value in batch.items(): + output[key] = ( + value[:, :length] if torch.is_tensor(value) and value.ndim >= 2 + and value.shape[1] == batch["frame_valid"].shape[1] + else value + ) + return output + + +def attach_gt_vertices( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> None: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for the real-batch smoke") + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, _ = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = ( + batch["mano_annotation_valid"].bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where( + valid, vertices, torch.full_like(vertices, torch.nan), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if config["model"].get("translation_parameterization") != "mixed_projection": + parser.error("smoke requires mixed_projection") + if sha256(args.checkpoint) != config["experiment"]["coarse_checkpoint_sha256"]: + parser.error("checkpoint hash differs from preregistration") + seed = int(config["seed"]) + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("mixed_log_tz_head",), + map_location=device, + ) + model.initialize_mixed_log_tz_from_direct_head() + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + learning_rate = float(config["protocol"]["learning_rate"]) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + attach_gt_vertices(batch, model) + args.output_dir.mkdir(parents=True, exist_ok=True) + excluded = checkpoint_excluded_prefixes(model) + initialized_checkpoint = args.output_dir / "mixed_projection_initialized_step0.pt" + save_checkpoint( + initialized_checkpoint, model, optimizer, 0, + extra={"kind": "phase6_mixed_projection_initialized_step0"}, + exclude_prefixes=excluded, + ) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + success_fraction = float(prediction["mixed_projection_success"].float().mean()) + teacher_z_difference_mm = float( + 1000.0 * ( + prediction["wrist_root_translation"][..., 2] + - prediction["mixed_projection_direct_teacher_translation"][..., 2] + ).abs().mean() + ) + losses["total"].backward() + gradient_groups = { + "log_tz": ["mixed_log_tz_head."], + "joint2d": ["joint2d_head."], + "pose": ["rotation_head."], + "shape": ["shape_head."], + "decoder": ["decoder."], + } + gradients = {} + for group, prefixes in gradient_groups.items(): + selected = [ + parameter.grad for name, parameter in model.named_parameters() + if parameter.requires_grad and name.startswith(tuple(prefixes)) + ] + gradients[group] = bool( + selected + and all(value is None or torch.isfinite(value).all() for value in selected) + and any(value.abs().sum() > 0 for value in selected if value is not None) + ) + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + model.eval() + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + t1 = model(prefix(batch, 1)) + t1_finite = bool( + torch.isfinite(t1["wrist_root_translation"]).all() + and torch.isfinite(t1["joints_camera"]).all() + ) + checkpoint = args.output_dir / "mixed_projection_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, 1, + extra={"kind": "phase6_mixed_projection_real_checkpoint_smoke"}, + exclude_prefixes=excluded, + ) + expected = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + if not key.startswith(excluded) + } + del model, optimizer, criterion, prediction, losses, t1 + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + reloaded, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected.items() + ) + shared_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("mixed_log_tz_head", "rgb_encoder.backbone.")) + ] + passed = bool( + all(np.isfinite(value) for value in loss_values.values()) + and success_fraction >= 0.99 + and all(gradients.values()) + and t1_finite + and resume_exact + and resumed["step"] == 1 + and not shared_missing + ) + report = { + "status": "passed" if passed else "failed", + "experiment": "P6_S2_differentiable_mixed_projection", + "experiment_class": "engineering_real_checkpoint_smoke", + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_missing, + "mixed_log_tz_initialization": "first-order log-softplus linearization", + "losses": loss_values, + "success_fraction": success_fraction, + "teacher_z_difference_mm": teacher_z_difference_mm, + "gradient_groups_finite_nonzero": gradients, + "gradient_norm": gradient_norm, + "T1_finite": t1_finite, + "T8_finite": all(np.isfinite(value) for value in loss_values.values()), + "elapsed_s": elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "initialized_checkpoint": { + "path": str(initialized_checkpoint.resolve()), + "sha256": sha256(initialized_checkpoint), + "step": 0, + }, + "checkpoint": {"path": str(checkpoint.resolve()), "sha256": sha256(checkpoint)}, + "trainable_parameters": sum(p.numel() for p in reloaded.parameters() if p.requires_grad), + "frozen_parameters": sum(p.numel() for p in reloaded.parameters() if not p.requires_grad), + } + (args.output_dir / "smoke.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "success_fraction": success_fraction, + "gradients": gradients, "resume_exact": resume_exact, + "output": str(args.output_dir), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase6_spatial_joint2d.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase6_spatial_joint2d.py new file mode 100644 index 0000000000000000000000000000000000000000..9c44a3f4073745881c46c5bdcea4843985a927ff --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_phase6_spatial_joint2d.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Real-checkpoint smoke for the Phase 6 spatial joint localizer.""" + +from __future__ import annotations + +import argparse +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, +) +from scripts.smoke_phase6_mixed_projection import attach_gt_vertices, prefix, sha256 + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if config["model"].get("joint2d_parameterization") != "spatial_heatmap": + parser.error("spatial smoke requires joint2d_parameterization=spatial_heatmap") + if sha256(args.checkpoint) != config["experiment"]["coarse_checkpoint_sha256"]: + parser.error("checkpoint hash differs from preregistration") + seed = int(config["seed"]) + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("joint_localization_",), + map_location=device, + ) + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + learning_rate = float(config["protocol"]["learning_rate"]) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + attach_gt_vertices(batch, model) + args.output_dir.mkdir(parents=True, exist_ok=True) + excluded = checkpoint_excluded_prefixes(model) + initialized_checkpoint = args.output_dir / "spatial_joint2d_initialized_step0.pt" + save_checkpoint( + initialized_checkpoint, model, optimizer, 0, + extra={"kind": "phase6_spatial_joint2d_initialized_step0"}, + exclude_prefixes=excluded, + ) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + height, width = map(int, batch["image_hw"][0].tolist()) + teacher_difference_px = float(( + (prediction["joint2d_norm"] - prediction["joint2d_linear_teacher_norm"]) + * prediction["joint2d_norm"].new_tensor((width, height)) + ).abs().mean()) + entropy = prediction["joint2d_heatmap_entropy"] + entropy_finite_bounded = bool( + torch.isfinite(entropy).all() and (entropy >= 0).all() and (entropy <= 1.0 + 1e-6).all() + ) + losses["total"].backward() + groups = { + "embedding": ("joint_localization_embedding",), + "query": ("joint_localization_query.",), + "feature": ("joint_localization_feature.",), + "offset": ("joint_localization_offset.",), + "decoder": ("decoder.",), + } + gradients = {} + for group, prefixes in groups.items(): + selected = [ + parameter.grad for name, parameter in model.named_parameters() + if parameter.requires_grad and name.startswith(prefixes) + ] + gradients[group] = bool( + selected + and all(value is None or torch.isfinite(value).all() for value in selected) + and any(value is not None and value.abs().sum() > 0 for value in selected) + ) + teacher_frozen = all(not parameter.requires_grad for parameter in model.joint2d_head.parameters()) + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + model.eval() + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + t1 = model(prefix(batch, 1)) + t1_finite = bool( + torch.isfinite(t1["joint2d_norm"]).all() + and torch.isfinite(t1["wrist_root_translation"]).all() + ) + checkpoint = args.output_dir / "spatial_joint2d_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, 1, + extra={"kind": "phase6_spatial_joint2d_real_checkpoint_smoke"}, + exclude_prefixes=excluded, + ) + expected = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + if not key.startswith(excluded) + } + del model, optimizer, criterion, prediction, losses, t1 + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + reloaded, learning_rate=learning_rate, backbone_learning_rate=None, + ), lr=learning_rate, weight_decay=0.05, + ) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected.items() + ) + shared_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("joint_localization_", "rgb_encoder.backbone.")) + ] + passed = bool( + all(np.isfinite(value) for value in loss_values.values()) + and all(gradients.values()) and teacher_frozen and entropy_finite_bounded + and t1_finite and resume_exact and resumed["step"] == 1 and not shared_missing + ) + report = { + "status": "passed" if passed else "failed", + "experiment": "P6_S3B_spatial_2d_anchors", + "experiment_class": "engineering_real_checkpoint_smoke", + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_missing, + "losses": loss_values, + "teacher_difference_px": teacher_difference_px, + "teacher_frozen": teacher_frozen, + "entropy_finite_bounded": entropy_finite_bounded, + "gradient_groups_finite_nonzero": gradients, + "gradient_norm": gradient_norm, + "T1_finite": t1_finite, + "T8_finite": all(np.isfinite(value) for value in loss_values.values()), + "elapsed_s": elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "initialized_checkpoint": { + "path": str(initialized_checkpoint.resolve()), + "sha256": sha256(initialized_checkpoint), "step": 0, + }, + "checkpoint": {"path": str(checkpoint.resolve()), "sha256": sha256(checkpoint)}, + } + (args.output_dir / "smoke.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "gradients": gradients, + "resume_exact": resume_exact, "output": str(args.output_dir), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_real_batch.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_real_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..7581b85b5a1e7d58affbf1c719ca10b12c981c1f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/smoke_real_batch.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Real H2O batch structural smoke test; uses debug RGB encoder when weights are absent.""" + +from __future__ import annotations + +import argparse +import json +import time +from pathlib import Path + +import cv2 +import numpy as np +import torch +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint, save_checkpoint + + +def parameter_counts(model: torch.nn.Module) -> tuple[int, int]: + trainable = sum(value.numel() for value in model.parameters() if value.requires_grad) + frozen = sum(value.numel() for value in model.parameters() if not value.requires_grad) + return trainable, frozen + + +def draw_overlay(batch: dict[str, torch.Tensor], output: dict[str, torch.Tensor], path: Path) -> None: + rgb = batch["rgb"][0, 0].detach().cpu().permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + height, width = image.shape[:2] + predicted = output["joint2d_norm"][0, 0].detach().float().cpu().numpy() * np.array((width, height)) + target = batch["joint2d"][0, 0].detach().float().cpu().numpy() + annotation_valid = batch["joint_annotation_valid"][0, 0].cpu().numpy() + for hand, color in enumerate(((50, 220, 50), (50, 80, 255))): + for point in predicted[hand]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, color, -1) + if annotation_valid[hand]: + for point in target[hand]: + cv2.drawMarker(image, tuple(np.rint(point).astype(int)), (255, 255, 255), cv2.MARKER_CROSS, 7, 1) + label = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/{int(batch['frame_id'][0,0])} debug_encoder RGB-D-K" + cv2.rectangle(image, (0, 0), (width, 32), (0, 0, 0), -1) + cv2.putText(image, label, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (255, 255, 255), 1) + cv2.imwrite(str(path), image) + + attention = output["attention"]["rgb_cross_attention"][0, -1, 0].detach().float().cpu().numpy() + grid_h, grid_w = height // 16, width // 16 + for hand, side in enumerate(("left", "right")): + heat = attention[hand].reshape(grid_h, grid_w) + heat = (heat - heat.min()) / max(float(heat.max() - heat.min()), 1e-8) + heat = cv2.resize(np.rint(heat * 255).astype(np.uint8), (width, height), interpolation=cv2.INTER_CUBIC) + heat = cv2.applyColorMap(heat, cv2.COLORMAP_TURBO) + mixed = cv2.addWeighted(image, 0.55, heat, 0.45, 0) + cv2.imwrite(str(path.with_name(path.stem + f"_{side}_rgb_attention.jpg")), mixed) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + torch.manual_seed(20260716); np.random.seed(20260716) + device = torch.device(f"cuda:{args.gpu}") + dataset = H2OCam4Dataset(args.root, args.manifest, (288, 512), (8,), (1,), max_clips=2) + loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_h2o_clips) + batch = next(iter(loader)) + batch = {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + config = ModelConfig( + encoder="tiny_debug", decoder_dim=256, decoder_layers=3, attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, depth_mode="log_depth", + use_rays=True, use_bimanual_interaction=True, require_mano=False, + ) + model = BimanualReconstructionModel(config).to(device).train() + loss_function = BimanualLoss(LossConfig()).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) + torch.cuda.reset_peak_memory_stats(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = loss_function(prediction, batch) + losses["total"].backward() + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000)) + optimizer.step(); torch.cuda.synchronize(device) + elapsed = time.perf_counter() - start + checkpoint = args.output_dir / "real_batch_smoke.pt" + save_checkpoint(checkpoint, model, optimizer, 1, {"kind": "structural_smoke_debug_encoder"}) + reloaded = BimanualReconstructionModel(config).to(device) + reloaded_optimizer = torch.optim.AdamW(reloaded.parameters(), lr=1e-4) + resume = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all(torch.equal(model.state_dict()[key], value) for key, value in reloaded.state_dict().items()) + trainable, frozen = parameter_counts(model) + result = { + "status": "passed_structural_smoke_only", "formal_training": False, + "limitation": "tiny_debug RGB encoder and no MANO assets; joint/vertex/reprojection losses are zero", + "seed": 20260716, "resolution_hw": [288, 512], "T": 8, "stride": 1, "batch_size": 1, "precision": "bf16", + "decoder": "alternating", "depth": "log_depth", "rays": True, + "trainable_parameters": trainable, "frozen_parameters": frozen, + "elapsed_s": elapsed, "frames_per_s": 8 / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30, + "gradient_norm": gradient_norm, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "losses_finite": all(bool(torch.isfinite(value)) for value in losses.values()), + "resume_success": bool(resume_exact and resume["step"] == 1), "checkpoint": str(checkpoint.resolve()), + "input_shapes": {key: list(value.shape) for key, value in batch.items() if torch.is_tensor(value)}, + "output_shapes": {key: list(value.shape) for key, value in prediction.items() if torch.is_tensor(value)}, + "attention_shapes": {key: list(value.shape) for key, value in prediction["attention"].items()}, + } + (args.output_dir / "real_batch_smoke.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + draw_overlay(batch, prediction, args.output_dir / "real_batch_prediction_overlay.jpg") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/split_phase7_h2o_train_cache.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/split_phase7_h2o_train_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..add4ccef194d122b76ef5d116d75a15fe37c347a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/split_phase7_h2o_train_cache.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Create deterministic recording-group H2O train-fit/heldout cache manifests.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def assign_group_folds(rows: list[dict[str, Any]], folds: int, seed: int) -> dict[str, int]: + if folds < 2: + raise ValueError("at least two folds are required") + subjects: dict[str, set[str]] = defaultdict(set) + group_subject: dict[str, str] = {} + for row in rows: + if str(row.get("dataset_id", "")).upper() != "H2O": + raise ValueError("H2O train cache split refuses non-H2O rows") + group = str(row["physical_recording_id"]) + subject = str(row["subject_id"]) + if group in group_subject and group_subject[group] != subject: + raise ValueError(f"physical recording spans subjects: {group}") + group_subject[group] = subject + subjects[subject].add(group) + assignments: dict[str, int] = {} + for subject, groups in sorted(subjects.items()): + ordered = sorted(groups, key=lambda group: hashlib.sha256( + f"{seed}|{subject}|{group}".encode("utf-8") + ).hexdigest()) + for index, group in enumerate(ordered): + assignments[group] = index % folds + return assignments + + +def split_rows( + rows: list[dict[str, Any]], assignments: dict[str, int], heldout_fold: int, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + fit, heldout = [], [] + for row in rows: + target = heldout if assignments[str(row["physical_recording_id"])] == heldout_fold else fit + target.append(row) + if not fit or not heldout: + raise ValueError("fit and heldout manifests must both be nonempty") + fit_groups = {row["physical_recording_id"] for row in fit} + heldout_groups = {row["physical_recording_id"] for row in heldout} + if fit_groups & heldout_groups: + raise AssertionError("physical recording leakage across H2O train split") + return fit, heldout + + +def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), encoding="utf-8", + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--cache-report", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--folds", type=int, default=5) + parser.add_argument("--heldout-fold", type=int, default=0) + parser.add_argument("--seed", type=int, default=20260717) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + if not 0 <= args.heldout_fold < args.folds: + parser.error("heldout fold is outside the fold range") + cache_report = json.loads(args.cache_report.read_text(encoding="utf-8")) + if ( + cache_report.get("status") != "complete" + or cache_report.get("dataset") != "H2O" + or cache_report.get("split_role") != "official_train" + or cache_report.get("h2o_official_validation_used") is not False + or cache_report.get("official_test_used") is not False + or cache_report["cache_manifest"]["sha256"] != sha256(args.cache_manifest) + ): + parser.error("cache report does not prove a complete official-train-only cache") + rows = [ + json.loads(line) for line in args.cache_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + assignments = assign_group_folds(rows, args.folds, args.seed) + fit, heldout = split_rows(rows, assignments, args.heldout_fold) + args.output_dir.mkdir(parents=True) + fit_path = args.output_dir / "train_fit.jsonl" + heldout_path = args.output_dir / "train_group_heldout.jsonl" + write_jsonl(fit_path, fit) + write_jsonl(heldout_path, heldout) + record = { + "status": "frozen_h2o_train_group_split", "schema_version": "phase7_h2o_train_group_cv_v1", + "source_cache_manifest": { + "path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest), + }, + "folds": args.folds, "heldout_fold": args.heldout_fold, "seed": args.seed, + "group_key": "(dataset_id, subject_id, physical_recording_id)", + "fit": { + "path": str(fit_path.resolve()), "sha256": sha256(fit_path), "clips": len(fit), + "recordings": len({row["physical_recording_id"] for row in fit}), + }, + "heldout": { + "path": str(heldout_path.resolve()), "sha256": sha256(heldout_path), + "clips": len(heldout), + "recordings": len({row["physical_recording_id"] for row in heldout}), + }, + "assignments": assignments, "recording_overlap": [], + "h2o_official_validation_used": False, "official_test_used": False, + } + (args.output_dir / "split.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_core.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_core.py new file mode 100644 index 0000000000000000000000000000000000000000..5e82cefcfac1b2f5833989ea3e5058a087bbd01f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_core.py @@ -0,0 +1,405 @@ +#!/usr/bin/env python3 +"""Summarize the pre-registered Phase 3 decoder/temporal core matrix.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import Iterable + +import numpy as np + + +CHECKPOINT_ROLES = ( + "step_025k", "step_050k", "step_075k", "step_100k", + "best_absolute", "best_z", "final", +) +FRAME_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "wrong_side_preference", +) +REPORT_METRICS = FRAME_METRICS + ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "identity_switch_fraction", +) +PAIR_DEFINITIONS = ( + ("l0_temporal", "L0", "T1", "L0", "T0"), + ("l1_temporal", "L1", "T1", "L1", "T0"), + ("alternating_without_temporal", "L1", "T0", "L0", "T0"), + ("alternating_with_temporal", "L1", "T1", "L0", "T1"), + ("hybrid_reread_vs_sequential", "L2", "T1", "L0", "T1"), + ("hybrid_reread_vs_alternating", "L2", "T1", "L1", "T1"), +) +OBSERVATION_KEY = ( + "clip_index", "time_index", "take", "subject", "sequence", + "frame_id", "side", "annotation_valid", "annotation_state", +) +TEMPORAL_OBSERVATION_KEY = ( + "clip_index", "transition_index", "take", "subject", "sequence", + "frame_id_from", "frame_id_to", "side", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: Iterable[dict[str, object]]) -> None: + rows = list(rows) + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fieldnames = list(rows[0]) + if any(list(row) != fieldnames for row in rows): + raise ValueError(f"inconsistent CSV fields for {path}") + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: str | None) -> float | None: + if value is None or value == "": + return None + result = float(value) + return result if math.isfinite(result) else None + + +def paired_take_differences( + candidate_rows: list[dict[str, str]], + reference_rows: list[dict[str, str]], + metric: str, + observation_key: tuple[str, ...] = OBSERVATION_KEY, +) -> dict[str, float]: + if len(candidate_rows) != len(reference_rows): + raise ValueError("paired evaluations have different observation counts") + take_values: dict[str, list[float]] = defaultdict(list) + frame_values = [] + for candidate, reference in zip(candidate_rows, reference_rows, strict=True): + if any(candidate[key] != reference[key] for key in observation_key): + raise ValueError("paired evaluations do not have identical observation order") + candidate_value = optional_float(candidate.get(metric)) + reference_value = optional_float(reference.get(metric)) + if candidate_value is None or reference_value is None: + continue + difference = candidate_value - reference_value + take_values[candidate["take"]].append(difference) + frame_values.append(difference) + if not take_values: + raise ValueError(f"no paired values for {metric}") + take_means = np.asarray([ + np.mean(values, dtype=np.float64) for _, values in sorted(take_values.items()) + ], dtype=np.float64) + return { + "take_equal_mean_delta": float(take_means.mean()), + "frame_weighted_mean_delta": float(np.mean(frame_values, dtype=np.float64)), + "take_count": int(take_means.size), + "observation_count": int(len(frame_values)), + "take_means": take_means, + } + + +def bootstrap_take_values( + take_values: np.ndarray, + seed: int = 20260716, + samples: int = 10_000, +) -> tuple[float, float]: + if take_values.ndim != 1 or take_values.size == 0: + raise ValueError("take_values must be a non-empty vector") + rng = np.random.default_rng(seed) + indices = rng.integers(0, take_values.size, size=(samples, take_values.size)) + means = take_values[indices].mean(axis=1) + return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5)) + + +def metric_mean(report: dict, name: str) -> float | None: + entry = report["metrics"].get(name) + if entry is not None: + return entry.get("mean") + if name in {"translation_x_mae_mm", "translation_y_mae_mm"}: + components = [ + report["metrics"][f"{side}_{name}"] for side in ("left", "right") + ] + count = sum(int(component["count"]) for component in components) + if count: + return sum( + float(component["mean"]) * int(component["count"]) + for component in components + ) / count + return None + + +def attention_mean(report: dict, name: str) -> float | None: + entry = report["attention"].get(name) + return None if entry is None else entry.get("mean") + + +def load_report(path: Path) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("official_test_used") is not False: + raise ValueError(f"invalid formal evaluation: {path}") + if report.get("split_role") != "official_validation" or report.get("clips") != 1495: + raise ValueError(f"incomplete or non-validation evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--temporal-evaluation-root", type=Path) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + report_paths = sorted(args.evaluation_root.glob("core_*/*/evaluation.json")) + if len(report_paths) != 210: + raise ValueError(f"expected 210 checkpoint evaluations, found {len(report_paths)}") + + all_rows = [] + best_rows = [] + reports_by_key: dict[tuple[str, str, str, int, str], tuple[Path, dict]] = {} + checkpoints: dict[str, dict[str, object]] = {} + collected_bootstrap = [] + for path in report_paths: + report = load_report(path) + config = report["config"] + experiment = config["experiment"] + run_name = path.parent.parent.name + role = path.parent.name + if role not in CHECKPOINT_ROLES: + raise ValueError(f"unregistered checkpoint role: {role}") + seed = int(config["seed"]) + training_summary = json.loads((args.run_root / run_name / "summary.json").read_text(encoding="utf-8")) + row: dict[str, object] = { + "run": run_name, + "modality": experiment["modality"], + "layout": experiment["layout"], + "temporal": experiment["temporal"], + "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "rgb_same_peak": attention_mean(report, "rgb_same_peak"), + "rgb_left_right_cosine": attention_mean(report, "rgb_left_right_cosine"), + "temporal_normalized_entropy": attention_mean(report, "temporal_normalized_entropy"), + "temporal_diagonal": attention_mean(report, "temporal_diagonal"), + "depth_fusion_gate": attention_mean(report, "depth_fusion_gate"), + "depth_fusion_gate_raw": attention_mean(report, "depth_fusion_gate_raw"), + "rgb_update_norm": attention_mean(report, "rgb_update_norm"), + "depth_update_norm": attention_mean(report, "depth_update_norm"), + "gated_depth_update_norm": attention_mean(report, "gated_depth_update_norm"), + "trainable_parameters": training_summary["trainable_parameters"], + "frozen_parameters": training_summary["frozen_parameters"], + "peak_vram_gib": training_summary["peak_vram_gib"], + "training_frames_per_s": training_summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + reports_by_key[(experiment["modality"], experiment["layout"], experiment["temporal"], seed, role)] = (path, report) + for bootstrap in report["bootstrap"]: + collected_bootstrap.append({ + "run": run_name, "modality": experiment["modality"], + "layout": experiment["layout"], "temporal": experiment["temporal"], + "seed": seed, "checkpoint_role": role, **bootstrap, + }) + checkpoint_record = checkpoints.setdefault(run_name, { + "config": config["name"], "modality": experiment["modality"], + "layout": experiment["layout"], "temporal": experiment["temporal"], + "seed": seed, "roles": {}, + }) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + write_csv(args.output_dir / "checkpoint_comparison.csv", all_rows) + write_csv(args.output_dir / "comparison.csv", best_rows) + write_csv(args.output_dir / "bootstrap_ci.csv", collected_bootstrap) + (args.output_dir / "checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for group_key in sorted({ + (row["modality"], row["layout"], row["temporal"]) for row in best_rows + }): + group = [row for row in best_rows if (row["modality"], row["layout"], row["temporal"]) == group_key] + if len(group) != 3: + raise ValueError(f"expected three seeds for {group_key}, got {len(group)}") + record: dict[str, object] = { + "modality": group_key[0], "layout": group_key[1], "temporal": group_key[2], + "seeds": [row["seed"] for row in group], + } + for metric in REPORT_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), + "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = {"mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1))} + aggregate.append(record) + + paired_rows = [] + for modality in ("M0", "M3"): + for comparison, candidate_layout, candidate_temporal, reference_layout, reference_temporal in PAIR_DEFINITIONS: + per_metric_by_seed: dict[str, list[dict[str, float]]] = defaultdict(list) + for seed in (20260716, 20260717, 20260718): + candidate_path, _ = reports_by_key[(modality, candidate_layout, candidate_temporal, seed, "best_absolute")] + reference_path, _ = reports_by_key[(modality, reference_layout, reference_temporal, seed, "best_absolute")] + candidate_rows = read_csv(candidate_path.parent / "per_hand_frame_metrics.csv") + reference_rows = read_csv(reference_path.parent / "per_hand_frame_metrics.csv") + for metric in FRAME_METRICS: + result = paired_take_differences(candidate_rows, reference_rows, metric) + per_metric_by_seed[metric].append({"seed": seed, **result}) + for metric in FRAME_METRICS: + results = per_metric_by_seed[metric] + stacked = np.stack([result["take_means"] for result in results], axis=0) + take_values = stacked.mean(axis=0) + ci_low, ci_high = bootstrap_take_values(take_values, args.seed, args.bootstrap_samples) + seed_deltas = [float(result["take_equal_mean_delta"]) for result in results] + paired_rows.append({ + "modality": modality, + "comparison": comparison, + "candidate": f"{candidate_layout}-{candidate_temporal}", + "reference": f"{reference_layout}-{reference_temporal}", + "metric": metric, + "delta_definition": "candidate_minus_reference_lower_is_better", + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "take_count": int(results[0]["take_count"]), + "observations_per_seed": int(results[0]["observation_count"]), + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + write_csv(args.output_dir / "paired_bootstrap_ci.csv", paired_rows) + + paired_temporal_rows = [] + if args.temporal_evaluation_root is not None: + temporal_metrics = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", + ) + for modality in ("M0", "M3"): + for comparison, candidate_layout, candidate_temporal, reference_layout, reference_temporal in PAIR_DEFINITIONS: + per_metric_by_seed: dict[str, list[dict[str, float]]] = defaultdict(list) + for seed in (20260716, 20260717, 20260718): + candidate_source, _ = reports_by_key[(modality, candidate_layout, candidate_temporal, seed, "best_absolute")] + reference_source, _ = reports_by_key[(modality, reference_layout, reference_temporal, seed, "best_absolute")] + candidate_path = ( + args.temporal_evaluation_root / candidate_source.parent.parent.name + / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + reference_path = ( + args.temporal_evaluation_root / reference_source.parent.parent.name + / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + candidate_rows = read_csv(candidate_path) + reference_rows = read_csv(reference_path) + for metric in temporal_metrics: + result = paired_take_differences( + candidate_rows, reference_rows, metric, + observation_key=TEMPORAL_OBSERVATION_KEY, + ) + per_metric_by_seed[metric].append({"seed": seed, **result}) + for metric in temporal_metrics: + results = per_metric_by_seed[metric] + stacked = np.stack([result["take_means"] for result in results], axis=0) + take_values = stacked.mean(axis=0) + ci_low, ci_high = bootstrap_take_values(take_values, args.seed, args.bootstrap_samples) + seed_deltas = [float(result["take_equal_mean_delta"]) for result in results] + paired_temporal_rows.append({ + "modality": modality, + "comparison": comparison, + "candidate": f"{candidate_layout}-{candidate_temporal}", + "reference": f"{reference_layout}-{reference_temporal}", + "metric": metric, + "delta_definition": "candidate_minus_reference_lower_is_better", + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "take_count": int(results[0]["take_count"]), + "observations_per_seed": int(results[0]["observation_count"]), + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + write_csv(args.output_dir / "paired_temporal_bootstrap_ci.csv", paired_temporal_rows) + + payload = { + "status": "complete", + "official_test_used": False, + "checkpoint_selection": "best_absolute selected only by the registered fixed 256-clip validation subset", + "evaluations": len(report_paths), + "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_bootstrap": { + "path": str((args.output_dir / "paired_bootstrap_ci.csv").resolve()), + "definition": "For each seed and take, compute paired per-observation candidate-reference deltas; average seeds within take; bootstrap the 24 take means.", + "temporal_path": ( + str((args.output_dir / "paired_temporal_bootstrap_ci.csv").resolve()) + if paired_temporal_rows else None + ), + "temporal_metric_limitation": ( + None if paired_temporal_rows + else "Provide --temporal-evaluation-root with transition exports to compute paired temporal take CIs." + ), + }, + "source_hashes": { + "full_validation_launcher_provenance": sha256(args.evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(report_paths), + "best_absolute_runs": len(best_rows), "paired_rows": len(paired_rows), + "paired_temporal_rows": len(paired_temporal_rows), + "output_dir": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_depth_fusion.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_depth_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2a737a31f0909731dfc210277fff9c0a27cda9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_depth_fusion.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +"""Summarize the registered Phase 3 Depth fusion/representation controls.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + write_csv, + ) + + +VARIANTS = ("P0_fixed05", "gate025", "learned_gate", "geometry") +NEW_VARIANTS = ("gate025", "learned_gate", "geometry") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def run_name(variant: str, seed: int) -> str: + if variant == "P0_fixed05": + return f"core_m3_l1_t1_s{seed}" + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_variant = None if variant == "P0_fixed05" else variant + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or (expected_variant is not None and experiment.get("variant") != expected_variant) + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal depth-fusion evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--new-run-root", type=Path, default=Path("artifacts/phase3/depth_fusion_runs")) + parser.add_argument("--core-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--new-evaluation-root", type=Path, default=Path("artifacts/phase3/depth_fusion_full_validation")) + parser.add_argument("--core-temporal-root", type=Path, default=Path("artifacts/phase3/temporal_position_p0_diagnostics")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + rows = [] + best_rows = [] + checkpoints: dict[str, dict] = {} + bootstrap_rows = [] + for variant in VARIANTS: + evaluation_root = args.core_evaluation_root if variant == "P0_fixed05" else args.new_evaluation_root + run_root = args.core_run_root if variant == "P0_fixed05" else args.new_run_root + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal run: {name}") + checkpoint_record = {"variant": variant, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + report_path = evaluation_root / name / role / "evaluation.json" + report = load_report(report_path, variant, seed) + reports[(variant, seed, role)] = (report_path, report) + row = { + "run": name, "variant": variant, "modality": "M3", + "layout": "L1", "temporal": "T1", "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in ( + "temporal_normalized_entropy", "temporal_diagonal", + "temporal_update_norm", "depth_fusion_gate", + "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ): + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, **item, + } for item in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(report_path.resolve()), + } + + expected_rows = len(VARIANTS) * len(SEEDS) * len(CHECKPOINT_ROLES) + if len(rows) != expected_rows or len(best_rows) != len(VARIANTS) * len(SEEDS): + raise ValueError(f"expected {expected_rows} rows, got {len(rows)}") + write_csv(args.output_dir / "depth_fusion_checkpoint_comparison.csv", rows) + write_csv(args.output_dir / "depth_fusion_comparison.csv", best_rows) + write_csv(args.output_dir / "depth_fusion_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "depth_fusion_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant, "modality": "M3", "layout": "L1", "temporal": "T1"} + for metric in FRAME_METRICS + TEMPORAL_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), + "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", "peak_vram_gib", + "training_frames_per_s", + ): + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + report_path, _ = reports[(variant, seed, "best_absolute")] + frame_cache[(variant, seed)] = read_csv(report_path.parent / "per_hand_frame_metrics.csv") + temporal_root = args.core_temporal_root if variant == "P0_fixed05" else args.new_evaluation_root + temporal_cache[(variant, seed)] = read_csv( + temporal_root / run_name(variant, seed) / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for variant in NEW_VARIANTS: + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {"candidate": frame_cache[(variant, seed)], "P0": frame_cache[("P0_fixed05", seed)]}, + metric, {"candidate": 1.0, "P0": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": f"{variant}-P0_fixed05", + "contrast": "+1*candidate -1*P0", + "metric": metric, + "delta_definition": "candidate minus fixed-gate-0.5 P0; lower is better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_fusion_bootstrap_ci.csv", paired_rows) + + temporal_rows = [] + for variant in NEW_VARIANTS: + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {"candidate": temporal_cache[(variant, seed)], "P0": temporal_cache[("P0_fixed05", seed)]}, + metric, {"candidate": 1.0, "P0": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": f"{variant}-P0_fixed05", + "contrast": "+1*candidate -1*P0", + "metric": metric, + "delta_definition": "candidate minus fixed-gate-0.5 P0; lower is better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_fusion_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", + "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "formal_validation_clips_per_run": 1495, + "evaluations": len(rows), + "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_depth_fusion_bootstrap_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_depth_fusion_temporal_ci.csv").resolve()), + "source_hashes": { + "new_validation_launcher": sha256(args.new_evaluation_root / "launcher_provenance.json"), + "core_validation_launcher": sha256(args.core_evaluation_root / "launcher_provenance.json"), + "matrix": sha256(Path("artifacts/phase3/reports/depth_fusion_new_runs.csv")), + }, + } + (args.output_dir / "depth_fusion_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "best_absolute_runs": len(best_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_dropout.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..f35a51389b1ce94b0b81b50bdffe572d73543924 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_dropout.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Summarize the same-commit Phase 3 geometry modality-dropout matrix.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) + + +VARIANTS = ("dropout00_geometry", "dropout02_geometry") + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown dropout variant: {variant}") + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "depth_modality_dropout" + or experiment.get("variant") != variant + or experiment.get("modality") != "M3" + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid complete-modality dropout evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row[metric] is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--run-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_runs_commit7583772"), + ) + parser.add_argument( + "--evaluation-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports = {} + checkpoint_rows = [] + best_rows = [] + checkpoints = {} + bootstrap_rows = [] + diagnostics = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((args.run_root / name / "summary.json").read_text(encoding="utf-8")) + provenance = json.loads( + (args.run_root / name / "run_provenance.json").read_text(encoding="utf-8") + ) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != "75837726f7eb8232b747932cbf536a834821e24d" + ): + raise ValueError(f"invalid formal dropout training run: {name}") + checkpoint_record = {"variant": variant, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = args.evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("dropout matrix is incomplete") + write_csv(args.output_dir / "depth_dropout_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "depth_dropout_comparison.csv", best_rows) + write_csv(args.output_dir / "depth_dropout_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "depth_dropout_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + diagnostics + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "dropout02": frame_cache[("dropout02_geometry", seed)], + "dropout00": frame_cache[("dropout00_geometry", seed)], + }, + metric, {"dropout02": 1.0, "dropout00": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": "dropout02_geometry-dropout00_geometry", + "metric": metric, "delta_definition": "dropout02 minus dropout00; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_bootstrap_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "dropout02": temporal_cache[("dropout02_geometry", seed)], + "dropout00": temporal_cache[("dropout00_geometry", seed)], + }, + metric, {"dropout02": 1.0, "dropout00": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": "dropout02_geometry-dropout00_geometry", + "metric": metric, "delta_definition": "dropout02 minus dropout00; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": "75837726f7eb8232b747932cbf536a834821e24d", + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str( + (args.output_dir / "paired_depth_dropout_bootstrap_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_depth_dropout_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "depth_dropout_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_dropout_dose.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_dropout_dose.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cbe8b0c7d099c4541ed67e9338ec4ffe15eac6 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_dropout_dose.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +"""Summarize D.2 endpoints together with the D.3 dropout-dose sweep.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) + + +TRAINING_COMMIT = "75837726f7eb8232b747932cbf536a834821e24d" +VARIANTS = ( + "dropout00_geometry", "dropout005_geometry", + "dropout010_geometry", "dropout02_geometry", +) +ENDPOINT_VARIANTS = {"dropout00_geometry", "dropout02_geometry"} +COMPARISONS = ( + ("dropout005_geometry", "dropout00_geometry"), + ("dropout010_geometry", "dropout00_geometry"), + ("dropout02_geometry", "dropout00_geometry"), + ("dropout010_geometry", "dropout005_geometry"), + ("dropout02_geometry", "dropout010_geometry"), + ("dropout02_geometry", "dropout005_geometry"), +) + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown dropout-dose variant: {variant}") + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def matrix_for(variant: str) -> str: + return ( + "depth_modality_dropout" + if variant in ENDPOINT_VARIANTS else "depth_modality_dropout_dose" + ) + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row[metric] is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != matrix_for(variant) + or experiment.get("variant") != variant + or experiment.get("modality") != "M3" + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid complete dropout-dose evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--endpoint-run-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_runs_commit7583772"), + ) + parser.add_argument( + "--dose-run-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_runs_commit7583772"), + ) + parser.add_argument( + "--endpoint-evaluation-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--dose-evaluation-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + diagnostics = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + reports = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + for variant in VARIANTS: + run_root = ( + args.endpoint_run_root if variant in ENDPOINT_VARIANTS else args.dose_run_root + ) + evaluation_root = ( + args.endpoint_evaluation_root + if variant in ENDPOINT_VARIANTS else args.dose_evaluation_root + ) + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text()) + provenance = json.loads((run_root / name / "run_provenance.json").read_text()) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid dropout-dose training run: {name}") + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 84 or len(best_rows) != 12: + raise ValueError("dropout-dose matrix is incomplete") + write_csv(args.output_dir / "dropout_dose_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "dropout_dose_comparison.csv", best_rows) + write_csv(args.output_dir / "dropout_dose_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "dropout_dose_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n" + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + diagnostics + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + temporal_rows = [] + for candidate, reference in COMPARISONS: + comparison = f"{candidate}-{reference}" + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(candidate, seed)], + "reference": frame_cache[(reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(candidate, seed)], + "reference": temporal_cache[(reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_dropout_dose_ci.csv", paired_rows) + write_csv(args.output_dir / "paired_dropout_dose_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_dropout_dose_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_dropout_dose_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "dropout_dose_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_dropout_dose_fallback.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_dropout_dose_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..2daef68597394f8412587333dcbf489ce2f188f0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_dropout_dose_fallback.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""Summarize complete and missing-modality behavior across four dropout doses.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_dropout_dose import ( + COMPARISONS as DOSE_COMPARISONS, ENDPOINT_VARIANTS, VARIANTS, + matrix_for, run_name, + ) + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_dropout_dose import ( + COMPARISONS as DOSE_COMPARISONS, ENDPOINT_VARIANTS, VARIANTS, + matrix_for, run_name, + ) + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_depth, expected_k = CONDITIONS[condition] + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != matrix_for(variant) + or experiment.get("variant") != variant + or int(report["config"]["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid dropout-dose fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--endpoint-complete-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--dose-complete-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument( + "--endpoint-fallback-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_fallback"), + ) + parser.add_argument( + "--dose-fallback-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_fallback"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + diagnostics = ( + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + for variant in VARIANTS: + if variant in ENDPOINT_VARIANTS: + root = ( + args.endpoint_complete_root if condition == "complete" + else args.endpoint_fallback_root / condition + ) + else: + root = ( + args.dose_complete_root if condition == "complete" + else args.dose_fallback_root / condition + ) + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 48: + raise ValueError(f"expected 48 dropout-dose fallback rows, got {len(rows)}") + write_csv(args.output_dir / "dropout_dose_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + diagnostics: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": ( + float(np.std(values, ddof=1)) if len(values) > 1 else None + ), + } + aggregate.append(record) + + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + for candidate, reference in DOSE_COMPARISONS: + contrasts.append(( + f"{condition}:{candidate}-{reference}", + (condition, candidate), (condition, reference), + )) + + paired_rows = [] + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_dropout_dose_fallback_ci.csv", paired_rows) + write_csv( + args.output_dir / "paired_dropout_dose_fallback_temporal_ci.csv", temporal_rows + ) + + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + equality.append({ + "variant": variant, + "seed": seed, + "frame_metrics_identical": ( + frame_cache[("drop_k", variant, seed)] + == frame_cache[("drop_both", variant, seed)] + ), + }) + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "paired_frame": str( + (args.output_dir / "paired_dropout_dose_fallback_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_dropout_dose_fallback_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "dropout_dose_fallback_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + all_equal = all(row["frame_metrics_identical"] for row in equality) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all_equal, + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + if not all_equal: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_fallback.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..5e26939c7294190d782e80c1a8713655ecf32cb7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_fallback.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""Summarize missing Depth/K inference behavior for the geometry dropout matrix.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from scripts.summarize_phase3_dropout import VARIANTS, run_name +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from summarize_phase3_dropout import VARIANTS, run_name + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_depth, expected_k = CONDITIONS[condition] + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("variant") != variant + or int(report["config"]["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--complete-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--fallback-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_fallback"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + diagnostics = ( + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + reports = {} + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + root = args.complete_root if condition == "complete" else args.fallback_root / condition + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + reports[(condition, variant, seed)] = path + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 24: + raise ValueError(f"expected 24 fallback rows, got {len(rows)}") + write_csv(args.output_dir / "depth_dropout_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + diagnostics: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + } + aggregate.append(record) + + paired_rows = [] + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + contrasts.append(( + f"{condition}:dropout02-dropout00", + (condition, "dropout02_geometry"), + (condition, "dropout00_geometry"), + )) + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_fallback_ci.csv", paired_rows) + + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_fallback_temporal_ci.csv", temporal_rows) + + # Geometry needs K for XYZ construction, so drop-K and drop-both should be identical. + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + k_rows = frame_cache[("drop_k", variant, seed)] + both_rows = frame_cache[("drop_both", variant, seed)] + equality.append({ + "variant": variant, "seed": seed, + "frame_metrics_identical": k_rows == both_rows, + }) + payload = { + "status": "complete", "official_test_used": False, + "geometry_k_dependency": ( + "When K is unavailable, XYZ/logZ geometry tokens and ray conditioning are both " + "disabled. Therefore drop_k and drop_both are expected to be identical." + ), + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "paired_frame": str( + (args.output_dir / "paired_depth_dropout_fallback_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_depth_dropout_fallback_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "depth_dropout_fallback_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all( + row["frame_metrics_identical"] for row in equality + ), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_long_tail.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_long_tail.py new file mode 100644 index 0000000000000000000000000000000000000000..d113631c873a7e249781efb84b821f65e074cebd --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_long_tail.py @@ -0,0 +1,337 @@ +#!/usr/bin/env python3 +"""Summarize the preregistered Phase 3 100k-to-150k low-LR tail.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, sha256, write_csv, + ) + from scripts.summarize_phase3_photometric import DIAGNOSTICS +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, sha256, write_csv, + ) + from summarize_phase3_photometric import DIAGNOSTICS + + +TRAINING_COMMIT = "d4019222835132fcbcc850ba49e6e0b53ab352b3" +REFERENCE_ROLE = "reference_best_absolute" +TAIL_ROLES = ( + "tail_step_125k", "tail_step_150k", "tail_best_absolute", + "tail_best_z", "tail_final", +) +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", "translation_z_mae_mm", +) + + +def reference_name(seed: int) -> str: + return f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + + +def tail_name(seed: int) -> str: + return f"longtail_{reference_name(seed)}" + + +def load_report(path: Path, seed: int, tail: bool) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + override = report.get("inference_modality_override", {}) + expected_matrix = "low_lr_tail" if tail else "photometric_augmentation" + expected_variant = ( + "photometric_on_r640x368_tail150k" if tail + else "photometric_on_r640x368" + ) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != expected_matrix + or experiment.get("variant") != expected_variant + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or int(config["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid long-tail evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def load_resume_audit(path: Path) -> dict: + audit = json.loads(path.read_text(encoding="utf-8")) + expected = {tail_name(seed) for seed in SEEDS} + rows = audit.get("runs", []) + if ( + audit.get("status") != "passed" + or audit.get("official_test_used") is not False + or {row.get("run") for row in rows} != expected + or any( + row.get("reference_step") != 150_000 + or row.get("resumed_step") != 150_000 + or not all(row.get(key) is True for key in ( + "model_exact", "optimizer_exact", "python_rng_exact", + "numpy_rng_exact", "torch_rng_exact", "cuda_rng_exact", + )) + for row in rows + ) + ): + raise ValueError(f"invalid long-tail exact-resume audit: {path}") + return {"status": "passed", "runs": len(rows), "path": str(path.resolve()), "sha256": sha256(path)} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--reference-evaluation-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--tail-run-root", type=Path, + default=Path("artifacts/phase3/long_tail_runs_commitd401922"), + ) + parser.add_argument( + "--tail-evaluation-root", type=Path, + default=Path("artifacts/phase3/long_tail_full_validation"), + ) + parser.add_argument( + "--resume-root", type=Path, + default=Path("artifacts/phase3/long_tail_resume_from125k"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports = {} + checkpoint_rows = [] + checkpoints = {} + training_audit = {} + for seed in SEEDS: + name = tail_name(seed) + run_dir = args.tail_run_root / name + summary = json.loads((run_dir / "summary.json").read_text(encoding="utf-8")) + provenance_path = Path(summary["run_provenance"]) + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + expected_resume = ( + Path("/SSD3/jiasen/foundation_hand/phase3_artifacts/photometric_runs_commit239b0bf") + / reference_name(seed) / "step_0100000_final.pt" + ) + schedule = summary.get("learning_rate_schedule", {}) + if ( + summary.get("status") != "completed" + or summary.get("start_step") != 100_000 + or summary.get("completed_step") != 150_000 + or schedule.get("total_steps") != 100_000 + or schedule.get("training_max_steps") != 150_000 + or schedule.get("min_lr") != 5e-6 + or provenance.get("git_commit") != TRAINING_COMMIT + or provenance.get("git_status") != "" + or Path(provenance.get("resume_checkpoint", "")).resolve() != expected_resume.resolve() + ): + raise ValueError(f"invalid long-tail training run: {name}") + training_audit[name] = { + "seed": seed, "start_step": 100_000, "completed_step": 150_000, + "lr_schedule_steps": 100_000, "min_lr": 5e-6, + "provenance": str(provenance_path), "provenance_sha256": sha256(provenance_path), + } + checkpoints[name] = {"seed": seed, "roles": {}} + paths = { + REFERENCE_ROLE: ( + args.reference_evaluation_root / reference_name(seed) + / "best_absolute" / "evaluation.json" + ), + **{ + role: args.tail_evaluation_root / name / role / "evaluation.json" + for role in TAIL_ROLES + }, + } + for role, path in paths.items(): + tail = role != REFERENCE_ROLE + report = load_report(path, seed, tail) + reports[(role, seed)] = path + row = { + "run": name, "seed": seed, "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "tail_training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + if len(checkpoint_rows) != 18: + raise ValueError(f"expected 18 reference/tail rows, got {len(checkpoint_rows)}") + write_csv(args.output_dir / "long_tail_checkpoint_comparison.csv", checkpoint_rows) + (args.output_dir / "long_tail_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + primary_roles = (REFERENCE_ROLE, "tail_best_absolute") + aggregate = [] + for role in primary_roles: + group = [row for row in checkpoint_rows if row["checkpoint_role"] == role] + record = {"role": role} + for metric in FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS: + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + joint_cache = {} + for role in primary_roles: + for seed in SEEDS: + parent = reports[(role, seed)].parent + frame_cache[(role, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(role, seed)] = read_csv(parent / "per_temporal_transition_metrics.csv") + joint_cache[(role, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in read_csv(parent / "per_joint_metrics.csv") + } + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + return contrast_take_differences( + { + "reference": cache[(REFERENCE_ROLE, seed)], + "tail": cache[("tail_best_absolute", seed)], + }, + metric, {"reference": -1.0, "tail": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in FRAME_METRICS: + paired_rows.append({ + "comparison": "tail_best-reference_best", "metric": metric, + "delta_definition": "tail minus reference; lower is better", + **aggregate_seed_contrasts( + [paired(metric, seed) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ), + }) + write_csv(args.output_dir / "paired_long_tail_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + temporal_rows.append({ + "comparison": "tail_best-reference_best", "metric": metric, + "delta_definition": "tail minus reference; lower is better", + **aggregate_seed_contrasts( + [paired(metric, seed, temporal=True) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ), + }) + write_csv(args.output_dir / "paired_long_tail_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": "tail_best-reference_best", + "subgroup_axis": subgroup[0], "subgroup_value": subgroup[1], + "metric": metric, + "delta_definition": "tail minus reference; lower is better", + } + try: + result = aggregate_seed_contrasts( + [paired(metric, seed, subgroup=subgroup) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ) + except ValueError as error: + if "no paired values" not in str(error): + raise + result = { + "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, + "seed_20260717_delta": None, + "seed_20260718_delta": None, + "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + } + available = False + else: + available = True + subgroup_rows.append({**prefix, "available": available, **result}) + write_csv(args.output_dir / "paired_long_tail_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + for side in ("left", "right"): + for joint_index in range(21): + reference = np.asarray([ + joint_cache[(REFERENCE_ROLE, seed)][(side, joint_index)] for seed in SEEDS + ]) + tail = np.asarray([ + joint_cache[("tail_best_absolute", seed)][(side, joint_index)] for seed in SEEDS + ]) + joint_rows.append({ + "side": side, "joint_index": joint_index, + "reference_seed_mean_mm": float(reference.mean()), + "tail_seed_mean_mm": float(tail.mean()), + "tail_minus_reference_seed_mean_mm": float((tail - reference).mean()), + "tail_minus_reference_seed_sample_std_mm": float((tail - reference).std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "long_tail_per_joint_comparison.csv", joint_rows) + + resume_audit = load_resume_audit(args.resume_root / "exact_resume_audit.json") + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(checkpoint_rows), "aggregate": aggregate, + "training_audit": training_audit, "exact_resume": resume_audit, + } + output = args.output_dir / "long_tail_comparison.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "output": str(output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_modality.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..086229a9170bafceb69ba11354aba9b9c2f33897 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_modality.py @@ -0,0 +1,445 @@ +#!/usr/bin/env python3 +"""Summarize the Phase 3 four-modality causal matrix.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import Iterable + +import numpy as np + + +SEEDS = (20260716, 20260717, 20260718) +MODALITIES = ("M0", "M1", "M2", "M3") +CHECKPOINT_ROLES = ( + "step_025k", "step_050k", "step_075k", "step_100k", + "best_absolute", "best_z", "final", +) +FRAME_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "wrong_side_preference", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", +) +REPORT_METRICS = FRAME_METRICS + TEMPORAL_METRICS +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", +) +FRAME_KEY = ( + "clip_index", "time_index", "take", "subject", "sequence", + "frame_id", "side", "annotation_valid", "annotation_state", +) +TEMPORAL_KEY = ( + "clip_index", "transition_index", "take", "subject", "sequence", + "frame_id_from", "frame_id_to", "side", +) +CONTRASTS = ( + ("K_without_depth", {"M1": 1.0, "M0": -1.0}), + ("K_with_depth", {"M3": 1.0, "M2": -1.0}), + ("Depth_without_K", {"M2": 1.0, "M0": -1.0}), + ("Depth_with_K", {"M3": 1.0, "M1": -1.0}), + ("Depth_K_interaction", {"M3": 1.0, "M2": -1.0, "M1": -1.0, "M0": 1.0}), +) +SUBGROUPS = ( + ("side", "left"), ("side", "right"), + ("hand_size_bucket", "small"), ("hand_size_bucket", "medium"), + ("hand_size_bucket", "large"), + ("depth_bucket", "near"), ("depth_bucket", "middle"), + ("depth_bucket", "far"), +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: Iterable[dict[str, object]]) -> None: + rows = list(rows) + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fieldnames = list(rows[0]) + if any(list(row) != fieldnames for row in rows): + raise ValueError(f"inconsistent CSV fields for {path}") + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: str | None) -> float | None: + if value is None or value == "": + return None + result = float(value) + return result if math.isfinite(result) else None + + +def run_name(modality: str, seed: int) -> str: + prefix = "core" if modality in {"M0", "M3"} else "modality" + return f"{prefix}_{modality.lower()}_l1_t1_s{seed}" + + +def load_report(path: Path, modality: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != modality + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal modality evaluation: {path}") + return report + + +def metric_mean(report: dict, name: str) -> float | None: + entry = report["metrics"].get(name) + if entry is not None: + return entry.get("mean") + if name in {"translation_x_mae_mm", "translation_y_mae_mm"}: + components = [report["metrics"][f"{side}_{name}"] for side in ("left", "right")] + count = sum(int(component["count"]) for component in components) + if count: + return sum( + float(component["mean"]) * int(component["count"]) + for component in components + ) / count + return None + + +def attention_mean(report: dict, name: str) -> float | None: + entry = report["attention"].get(name) + return None if entry is None else entry.get("mean") + + +def bootstrap(values: np.ndarray, seed: int, samples: int) -> tuple[float, float]: + if values.ndim != 1 or values.size == 0: + raise ValueError("bootstrap values must be a non-empty vector") + rng = np.random.default_rng(seed) + indices = rng.integers(0, values.size, size=(samples, values.size)) + means = values[indices].mean(axis=1) + return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5)) + + +def contrast_take_differences( + rows_by_modality: dict[str, list[dict[str, str]]], + metric: str, + coefficients: dict[str, float], + observation_key: tuple[str, ...], + subgroup: tuple[str, str] | None = None, +) -> dict[str, object]: + modalities = tuple(coefficients) + reference_rows = rows_by_modality[modalities[0]] + if any(len(rows_by_modality[modality]) != len(reference_rows) for modality in modalities[1:]): + raise ValueError("contrast evaluations have different observation counts") + take_values: dict[str, list[float]] = defaultdict(list) + observation_values = [] + for index, reference in enumerate(reference_rows): + aligned = [rows_by_modality[modality][index] for modality in modalities] + if any( + any(row[key] != reference[key] for key in observation_key) + for row in aligned[1:] + ): + raise ValueError("contrast evaluations do not have identical observation order") + if subgroup is not None and reference.get(subgroup[0]) != subgroup[1]: + continue + values = [optional_float(row.get(metric)) for row in aligned] + if any(value is None for value in values): + continue + difference = sum( + coefficients[modality] * float(value) + for modality, value in zip(modalities, values, strict=True) + ) + take_values[reference["take"]].append(difference) + observation_values.append(difference) + if not take_values: + raise ValueError(f"no paired values for metric={metric}, subgroup={subgroup}") + return { + "take_means": { + take: float(np.mean(values, dtype=np.float64)) + for take, values in sorted(take_values.items()) + }, + "observation_mean": float(np.mean(observation_values, dtype=np.float64)), + "observation_count": len(observation_values), + } + + +def aggregate_seed_contrasts( + seed_results: list[dict[str, object]], seed: int, samples: int, +) -> dict[str, object]: + common_takes = set(seed_results[0]["take_means"]) + for result in seed_results[1:]: + common_takes &= set(result["take_means"]) + if not common_takes: + raise ValueError("seed contrasts have no common takes") + take_values = np.asarray([ + np.mean([result["take_means"][take] for result in seed_results]) + for take in sorted(common_takes) + ], dtype=np.float64) + ci_low, ci_high = bootstrap(take_values, seed, samples) + seed_deltas = [float(np.mean(list(result["take_means"].values()))) for result in seed_results] + return { + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "frame_weighted_delta_mean": float(np.mean([ + result["observation_mean"] for result in seed_results + ])), + "take_count": len(common_takes), + "observations_per_seed": int(seed_results[0]["observation_count"]), + "bootstrap_samples": samples, + "bootstrap_seed": seed, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--modality-run-root", type=Path, default=Path("artifacts/phase3/modality_runs")) + parser.add_argument("--core-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--modality-evaluation-root", type=Path, default=Path("artifacts/phase3/modality_full_validation")) + parser.add_argument("--core-temporal-root", type=Path, default=Path("artifacts/phase3/core_temporal_validation_v2")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + all_rows = [] + best_rows = [] + checkpoints: dict[str, dict[str, object]] = {} + collected_bootstrap = [] + for modality in MODALITIES: + evaluation_root = args.core_evaluation_root if modality in {"M0", "M3"} else args.modality_evaluation_root + run_root = args.core_run_root if modality in {"M0", "M3"} else args.modality_run_root + for seed in SEEDS: + name = run_name(modality, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal training run: {name}") + checkpoint_record = { + "modality": modality, "layout": "L1", "temporal": "T1", + "seed": seed, "roles": {}, + } + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, modality, seed) + reports[(modality, seed, role)] = (path, report) + row: dict[str, object] = { + "run": name, "modality": modality, "layout": "L1", "temporal": "T1", + "seed": seed, "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "temporal_normalized_entropy": attention_mean(report, "temporal_normalized_entropy"), + "temporal_diagonal": attention_mean(report, "temporal_diagonal"), + "depth_fusion_gate": attention_mean(report, "depth_fusion_gate"), + "depth_fusion_gate_raw": attention_mean(report, "depth_fusion_gate_raw"), + "rgb_update_norm": attention_mean(report, "rgb_update_norm"), + "depth_update_norm": attention_mean(report, "depth_update_norm"), + "gated_depth_update_norm": attention_mean(report, "gated_depth_update_norm"), + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + collected_bootstrap.extend({ + "run": name, "modality": modality, "seed": seed, + "checkpoint_role": role, **bootstrap_row, + } for bootstrap_row in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(all_rows) != 84 or len(best_rows) != 12: + raise ValueError(f"expected 84 checkpoint rows and 12 best rows, got {len(all_rows)}, {len(best_rows)}") + write_csv(args.output_dir / "modality_checkpoint_comparison.csv", all_rows) + write_csv(args.output_dir / "modality_comparison.csv", best_rows) + write_csv(args.output_dir / "modality_bootstrap_ci.csv", collected_bootstrap) + (args.output_dir / "modality_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for modality in MODALITIES: + group = [row for row in best_rows if row["modality"] == modality] + if len(group) != 3: + raise ValueError(f"expected three seeds for {modality}, got {len(group)}") + record: dict[str, object] = {"modality": modality, "layout": "L1", "temporal": "T1"} + for metric in REPORT_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + } + aggregate.append(record) + + frame_cache: dict[tuple[str, int], list[dict[str, str]]] = {} + temporal_cache: dict[tuple[str, int], list[dict[str, str]]] = {} + for modality in MODALITIES: + for seed in SEEDS: + report_path, _ = reports[(modality, seed, "best_absolute")] + frame_cache[(modality, seed)] = read_csv(report_path.parent / "per_hand_frame_metrics.csv") + temporal_root = args.core_temporal_root if modality in {"M0", "M3"} else args.modality_evaluation_root + temporal_cache[(modality, seed)] = read_csv( + temporal_root / run_name(modality, seed) / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for contrast, coefficients in CONTRASTS: + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {modality: frame_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "metric": metric, + "delta_definition": "contrast_delta_lower_is_better_except_interaction_is_additivity_residual", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_bootstrap_ci.csv", paired_rows) + + subgroup_rows = [] + unavailable_subgroups: set[tuple[str, str]] = set() + for contrast, coefficients in CONTRASTS[:4]: + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "subgroup_axis": subgroup[0], "subgroup": subgroup[1], "metric": metric, + "delta_definition": "contrast_delta_lower_is_better", + } + try: + seed_results = [ + contrast_take_differences( + {modality: frame_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, FRAME_KEY, subgroup, + ) + for seed in SEEDS + ] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable_subgroups.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, + "take_equal_mean_delta": None, "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, "seed_20260717_delta": None, + "seed_20260718_delta": None, "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_subgroup_ci.csv", subgroup_rows) + + temporal_rows = [] + for contrast, coefficients in CONTRASTS: + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {modality: temporal_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "metric": metric, + "delta_definition": "contrast_delta_lower_is_better_except_interaction_is_additivity_residual", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "formal_validation_clips_per_run": 1495, + "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "causal_contrasts": { + "paired_frame": str((args.output_dir / "paired_modality_bootstrap_ci.csv").resolve()), + "paired_subgroups": str((args.output_dir / "paired_modality_subgroup_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_modality_temporal_ci.csv").resolve()), + "definition": "Within each seed and observation, apply the registered modality contrast; average within take, average seeds within take, then bootstrap equal-weight take means.", + "unavailable_subgroups": [ + {"axis": axis, "value": value} + for axis, value in sorted(unavailable_subgroups) + ], + }, + "source_hashes": { + "core_validation_launcher": sha256(args.core_evaluation_root / "launcher_provenance.json"), + "modality_validation_launcher": sha256(args.modality_evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "modality_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(all_rows), + "best_absolute_runs": len(best_rows), "paired_rows": len(paired_rows), + "subgroup_rows": len(subgroup_rows), "temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_photometric.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_photometric.py new file mode 100644 index 0000000000000000000000000000000000000000..a6cef761d482c983cc6ad19adc664c7f0754d534 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_photometric.py @@ -0,0 +1,467 @@ +#!/usr/bin/env python3 +"""Summarize the paired Phase 3 photometric augmentation experiment.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) + + +TRAINING_COMMIT = "239b0bf8850dd5533d3b3f4236cf856b4e826af6" +VARIANTS = ("off", "on") +DIAGNOSTICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", +) +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", "translation_z_mae_mm", +) +SCIENTIFIC_LOG_EXCLUSIONS = { + "timestamp", "frames_per_s", "peak_vram_gib", "photometric_augmentation", +} + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown photometric variant: {variant}") + return f"photometric_{variant}_geometry_m3_l1_t1_r640x368_s{seed}" + + +def reference_run_name(seed: int) -> str: + return f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + augmentation = config.get("data", {}).get("photometric_augmentation", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "photometric_augmentation" + or experiment.get("variant") != f"photometric_{variant}_r640x368" + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or bool(augmentation.get("enabled")) != (variant == "on") + or int(config["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid formal photometric evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def canonical_scientific_record(record: dict) -> bytes: + filtered = { + key: value for key, value in record.items() + if key not in SCIENTIFIC_LOG_EXCLUSIONS + } + return json.dumps( + filtered, sort_keys=True, separators=(",", ":"), allow_nan=False, + ).encode("utf-8") + + +def audit_off_reference(off_path: Path, reference_path: Path) -> dict: + digest = hashlib.sha256() + compared = 0 + with off_path.open(encoding="utf-8") as off_handle, reference_path.open( + encoding="utf-8" + ) as reference_handle: + for compared, (off_line, reference_line) in enumerate( + zip(off_handle, reference_handle, strict=True), start=1, + ): + off_record = canonical_scientific_record(json.loads(off_line)) + reference_record = canonical_scientific_record(json.loads(reference_line)) + if off_record != reference_record: + raise ValueError( + f"off/reference scientific trajectory differs at record {compared}" + ) + digest.update(off_record) + digest.update(b"\n") + if compared != 100_000: + raise ValueError(f"expected 100000 compared records, got {compared}") + return { + "records": compared, "scientific_fields_exact": True, + "canonical_sha256": digest.hexdigest(), + } + + +def augmentation_statistics(path: Path, variant: str) -> dict: + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + if len(rows) != 100_000: + raise ValueError(f"expected 100000 augmentation records: {path}") + diagnostics = [row.get("photometric_augmentation") for row in rows] + if any(item is None for item in diagnostics): + raise ValueError(f"missing photometric diagnostics: {path}") + applied = np.asarray([float(item["applied_fraction"]) for item in diagnostics]) + if np.any((applied < 0.0) | (applied > 1.0)): + raise ValueError(f"invalid applied fraction: {path}") + expected_identity = variant == "off" + factor_limits = { + "brightness_mean": (0.8, 1.2), + "contrast_mean": (0.8, 1.2), + "saturation_mean": (0.8, 1.2), + "hue_mean": (-0.05, 0.05), + } + factor_stats = {} + for key, (low, high) in factor_limits.items(): + values = np.asarray([float(item[key]) for item in diagnostics]) + if expected_identity: + identity = 0.0 if key == "hue_mean" else 1.0 + if not np.all(values == identity): + raise ValueError(f"off run has non-identity {key}: {path}") + if np.any((values < low - 1e-7) | (values > high + 1e-7)): + raise ValueError(f"{key} outside registered range: {path}") + factor_stats[key] = { + "mean": float(values.mean()), "min": float(values.min()), + "max": float(values.max()), + } + if expected_identity and np.any(applied != 0.0): + raise ValueError(f"off run reports applied augmentation: {path}") + return { + "records": len(rows), "applied_fraction_mean": float(applied.mean()), + "factors": factor_stats, + } + + +def load_resume_audit(path: Path, variant: str) -> dict: + audit = json.loads(path.read_text(encoding="utf-8")) + expected_names = {run_name(variant, seed) for seed in SEEDS} + records = audit.get("runs", []) + if ( + audit.get("status") != "passed" + or audit.get("official_test_used") is not False + or {record.get("run") for record in records} != expected_names + or any( + record.get("reference_step") != 100_000 + or record.get("resumed_step") != 100_000 + or not all( + record.get(key) is True for key in ( + "model_exact", "optimizer_exact", "python_rng_exact", + "numpy_rng_exact", "torch_rng_exact", "cuda_rng_exact", + ) + ) + for record in records + ) + ): + raise ValueError(f"invalid {variant} exact-resume audit: {path}") + return { + "status": "passed", "variant": variant, "runs": len(records), + "path": str(path.resolve()), "sha256": sha256(path), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--run-root", type=Path, + default=Path("artifacts/phase3/photometric_runs_commit239b0bf"), + ) + parser.add_argument( + "--evaluation-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--off-reference-root", type=Path, + default=Path("artifacts/phase3/resolution_640_runs_attempt2_commit7583772"), + ) + parser.add_argument( + "--off-resume-root", type=Path, + default=Path("artifacts/phase3/photometric_resume_from75k"), + ) + parser.add_argument( + "--on-resume-root", type=Path, + default=Path("artifacts/phase3/photometric_on_resume_from75k"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("artifacts/phase3/reports"), + ) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + resume_audits = { + variant: load_resume_audit( + ( + args.off_resume_root if variant == "off" + else args.on_resume_root + ) / "exact_resume_audit.json", + variant, + ) + for variant in VARIANTS + } + + reports: dict[tuple[str, int, str], Path] = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + training_audit = {} + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + run_dir = args.run_root / name + summary = json.loads((run_dir / "summary.json").read_text(encoding="utf-8")) + provenance = json.loads( + (run_dir / "run_provenance.json").read_text(encoding="utf-8") + ) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid photometric training run: {name}") + training_audit[name] = { + "variant": variant, "seed": seed, + "augmentation": augmentation_statistics( + run_dir / "train_metrics.jsonl", variant, + ), + } + if variant == "off": + training_audit[name]["e1_reference"] = audit_off_reference( + run_dir / "train_metrics.jsonl", + args.off_reference_root / reference_run_name(seed) / "train_metrics.jsonl", + ) + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = args.evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("photometric matrix is incomplete") + write_csv(args.output_dir / "photometric_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "photometric_comparison.csv", best_rows) + write_csv(args.output_dir / "photometric_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "photometric_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + (args.output_dir / "photometric_training_audit.json").write_text( + json.dumps({"status": "passed", "runs": training_audit}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + joint_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv( + parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + joint_cache[(variant, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in read_csv(parent / "per_joint_metrics.csv") + } + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + return contrast_take_differences( + {"off": cache[("off", seed)], "on": cache[("on", seed)]}, + metric, {"off": -1.0, "on": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in FRAME_METRICS: + results = [paired(metric, seed) for seed in SEEDS] + paired_rows.append({ + "comparison": "on-off", "metric": metric, + "delta_definition": "augmentation on minus off; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [paired(metric, seed, temporal=True) for seed in SEEDS] + temporal_rows.append({ + "comparison": "on-off", "metric": metric, + "delta_definition": "augmentation on minus off; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + unavailable = set() + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": "on-off", "subgroup_axis": subgroup[0], + "subgroup_value": subgroup[1], "metric": metric, + "bucket_source": "aligned augmentation-off reference rows", + "delta_definition": "augmentation on minus off; lower is better", + } + try: + results = [paired(metric, seed, subgroup=subgroup) for seed in SEEDS] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, "seed_delta_mean": None, + "seed_delta_sample_std": None, "seed_20260716_delta": None, + "seed_20260717_delta": None, "seed_20260718_delta": None, + "frame_weighted_delta_mean": None, "take_count": 0, + "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + for side in ("left", "right"): + for joint_index in range(21): + off = np.asarray([ + joint_cache[("off", seed)][(side, joint_index)] for seed in SEEDS + ]) + on = np.asarray([ + joint_cache[("on", seed)][(side, joint_index)] for seed in SEEDS + ]) + delta = on - off + joint_rows.append({ + "side": side, "joint_index": joint_index, + "off_seed_mean_mm": float(off.mean()), + "off_seed_sample_std_mm": float(off.std(ddof=1)), + "on_seed_mean_mm": float(on.mean()), + "on_seed_sample_std_mm": float(on.std(ddof=1)), + "on_minus_off_seed_mean_mm": float(delta.mean()), + "on_minus_off_seed_sample_std_mm": float(delta.std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "photometric_per_joint_comparison.csv", joint_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_photometric_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_photometric_temporal_ci.csv").resolve() + ), + "paired_subgroups": str( + (args.output_dir / "paired_photometric_subgroup_ci.csv").resolve() + ), + "per_joint": str( + (args.output_dir / "photometric_per_joint_comparison.csv").resolve() + ), + "training_audit": str( + (args.output_dir / "photometric_training_audit.json").resolve() + ), + "exact_resume": { + "status": "passed", "runs": sum( + audit["runs"] for audit in resume_audits.values() + ), + "variants": resume_audits, + }, + "unavailable_subgroups": [ + {"axis": axis, "value": value} for axis, value in sorted(unavailable) + ], + "source_hashes": { + "training_launcher": sha256(args.run_root / "launcher_provenance.json"), + "validation_launcher": sha256( + args.evaluation_root / "launcher_provenance.json" + ), + }, + } + (args.output_dir / "photometric_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "per_joint_rows": len(joint_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_photometric_fallback.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_photometric_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..e865911f92e2e957592fba42b7916a5421d6348b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_photometric_fallback.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Summarize missing-modality behavior for the final photometric candidate.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from scripts.summarize_phase3_photometric import DIAGNOSTICS, VARIANTS, run_name +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from summarize_phase3_photometric import DIAGNOSTICS, VARIANTS, run_name + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + augmentation = config.get("data", {}).get("photometric_augmentation", {}) + override = report.get("inference_modality_override", {}) + expected_depth, expected_k = CONDITIONS[condition] + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "photometric_augmentation" + or experiment.get("variant") != f"photometric_{variant}_r640x368" + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or bool(augmentation.get("enabled")) != (variant == "on") + or int(config["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid photometric fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--complete-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--fallback-root", type=Path, + default=Path("artifacts/phase3/photometric_fallback_validation"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("artifacts/phase3/reports"), + ) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + root = args.complete_root if condition == "complete" else args.fallback_root / condition + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 24: + raise ValueError(f"expected 24 complete/fallback rows, got {len(rows)}") + write_csv(args.output_dir / "photometric_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + } + aggregate.append(record) + + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + contrasts.append(( + f"{condition}:on-off", (condition, "on"), (condition, "off"), + )) + + paired_rows = [] + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_fallback_ci.csv", paired_rows) + write_csv( + args.output_dir / "paired_photometric_fallback_temporal_ci.csv", temporal_rows, + ) + + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + equality.append({ + "variant": variant, "seed": seed, + "frame_rows_identical": ( + frame_cache[("drop_k", variant, seed)] + == frame_cache[("drop_both", variant, seed)] + ), + "temporal_rows_identical": ( + temporal_cache[("drop_k", variant, seed)] + == temporal_cache[("drop_both", variant, seed)] + ), + }) + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "geometry_k_dependency": ( + "When K is unavailable, ray conditioning and XYZ/logZ geometry are disabled; " + "drop_k and drop_both are therefore expected to be identical." + ), + } + output = args.output_dir / "photometric_fallback_comparison.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all( + row["frame_rows_identical"] and row["temporal_rows_identical"] + for row in equality + ), + "output": str(output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_resolution.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..669c9bad9451479da904b1d35b1873d764686a56 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_resolution.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Summarize the paired Phase 3 512x288 versus 640x368 resolution study.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) + + +TRAINING_COMMIT = "75837726f7eb8232b747932cbf536a834821e24d" +VARIANTS = ("r512x288", "r640x368") +RESOLUTIONS = {"r512x288": (288, 512), "r640x368": (368, 640)} +NORMALIZED_2D_METRICS = ( + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", +) +PAIRED_FRAME_METRICS = FRAME_METRICS + tuple( + f"{metric}_at_512_width" for metric in NORMALIZED_2D_METRICS +) +DIAGNOSTICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", +) + + +def run_name(variant: str, seed: int) -> str: + if variant == "r512x288": + return f"depth_dropout005_geometry_m3_l1_t1_s{seed}" + if variant == "r640x368": + return f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + raise ValueError(f"unknown resolution variant: {variant}") + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + expected_matrix = ( + "depth_modality_dropout_dose" if variant == "r512x288" else "resolution" + ) + expected_variant = ( + "dropout005_geometry" + if variant == "r512x288" else "dropout005_geometry_r640x368" + ) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != expected_matrix + or experiment.get("variant") != expected_variant + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(report["config"]["data"]["resolution_hw"]) != RESOLUTIONS[variant] + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid formal resolution evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def add_normalized_2d_columns( + rows: list[dict[str, str]], variant: str, +) -> list[dict[str, str]]: + scale = 512.0 / RESOLUTIONS[variant][1] + output = [] + for row in rows: + adapted = dict(row) + for metric in NORMALIZED_2D_METRICS: + value = adapted.get(metric) + adapted[f"{metric}_at_512_width"] = ( + "" if value in {None, ""} else str(float(value) * scale) + ) + output.append(adapted) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--reference-run-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_runs_commit7583772"), + ) + parser.add_argument( + "--candidate-run-root", type=Path, + default=Path("artifacts/phase3/resolution_640_runs_attempt2_commit7583772"), + ) + parser.add_argument( + "--reference-evaluation-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument( + "--candidate-evaluation-root", type=Path, + default=Path("artifacts/phase3/resolution_640_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], Path] = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + for variant in VARIANTS: + run_root = ( + args.reference_run_root if variant == "r512x288" + else args.candidate_run_root + ) + evaluation_root = ( + args.reference_evaluation_root if variant == "r512x288" + else args.candidate_evaluation_root + ) + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text()) + provenance = json.loads((run_root / name / "run_provenance.json").read_text()) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid resolution training run: {name}") + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "resolution_h": RESOLUTIONS[variant][0], + "resolution_w": RESOLUTIONS[variant][1], + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in NORMALIZED_2D_METRICS: + value = row[metric] + row[f"{metric}_at_512_width"] = ( + None if value is None else value * 512.0 / RESOLUTIONS[variant][1] + ) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("resolution matrix is incomplete") + write_csv(args.output_dir / "resolution_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "resolution_comparison.csv", best_rows) + write_csv(args.output_dir / "resolution_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "resolution_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n" + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + PAIRED_FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = add_normalized_2d_columns( + read_csv(parent / "per_hand_frame_metrics.csv"), variant, + ) + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + # Reference is inserted first so subgroup membership always comes from + # the fixed 512x288 evaluation rather than changing with resolution. + return contrast_take_differences( + { + "reference": cache[("r512x288", seed)], + "candidate": cache[("r640x368", seed)], + }, + metric, {"reference": -1.0, "candidate": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in PAIRED_FRAME_METRICS: + results = [paired(metric, seed) for seed in SEEDS] + paired_rows.append({ + "comparison": "r640x368-r512x288", "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [paired(metric, seed, temporal=True) for seed in SEEDS] + temporal_rows.append({ + "comparison": "r640x368-r512x288", "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + unavailable = set() + subgroup_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px_at_512_width", "fingertip_mpjpe_mm", + "translation_z_mae_mm", + ) + for subgroup in SUBGROUPS: + for metric in subgroup_metrics: + prefix = { + "comparison": "r640x368-r512x288", + "subgroup_axis": subgroup[0], "subgroup_value": subgroup[1], + "metric": metric, + "bucket_source": "r512x288 reference rows", + "delta_definition": "candidate minus reference; lower is better", + } + try: + results = [paired(metric, seed, subgroup=subgroup) for seed in SEEDS] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, "seed_20260717_delta": None, + "seed_20260718_delta": None, "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + joint_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + rows = read_csv(parent / "per_joint_metrics.csv") + joint_cache[(variant, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in rows + } + for side in ("left", "right"): + for joint_index in range(21): + reference = np.array([ + joint_cache[("r512x288", seed)][(side, joint_index)] for seed in SEEDS + ]) + candidate = np.array([ + joint_cache[("r640x368", seed)][(side, joint_index)] for seed in SEEDS + ]) + delta = candidate - reference + joint_rows.append({ + "side": side, "joint_index": joint_index, + "r512x288_seed_mean_mm": float(reference.mean()), + "r512x288_seed_sample_std_mm": float(reference.std(ddof=1)), + "r640x368_seed_mean_mm": float(candidate.mean()), + "r640x368_seed_sample_std_mm": float(candidate.std(ddof=1)), + "candidate_minus_reference_seed_mean_mm": float(delta.mean()), + "candidate_minus_reference_seed_sample_std_mm": float(delta.std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "resolution_per_joint_comparison.csv", joint_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "evaluation_contract": { + "raw_2d": "processed-input pixels, retained for audit", + "normalized_2d": "640 metrics multiplied by 512/640; 512 unchanged", + "subgroup_membership": "always inherited from aligned r512x288 reference rows", + }, + "paired_frame": str((args.output_dir / "paired_resolution_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_resolution_temporal_ci.csv").resolve() + ), + "paired_subgroups": str( + (args.output_dir / "paired_resolution_subgroup_ci.csv").resolve() + ), + "per_joint": str( + (args.output_dir / "resolution_per_joint_comparison.csv").resolve() + ), + "unavailable_subgroups": [ + {"axis": axis, "value": value} for axis, value in sorted(unavailable) + ], + "source_hashes": { + "reference_validation_launcher": sha256( + args.reference_evaluation_root / "launcher_provenance_sixth.json" + ), + "candidate_training_launcher": sha256( + args.candidate_run_root / "launcher_provenance.json" + ), + }, + } + (args.output_dir / "resolution_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "per_joint_rows": len(joint_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_temporal_position.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_temporal_position.py new file mode 100644 index 0000000000000000000000000000000000000000..a85351446385b326384584b1928ed219e889d36c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase3_temporal_position.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python3 +"""Summarize the Phase 3 P0/P1 temporal-position experiment.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + REPORT_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + sha256, + write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + REPORT_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + sha256, + write_csv, + ) + + +POSITIONS = ("P0", "P1") +ATTENTION_METRICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", +) + + +def position_run_name(position: str, seed: int) -> str: + if position == "P0": + return f"core_m3_l1_t1_s{seed}" + if position == "P1": + return f"temporal_p1_m3_l1_t1_s{seed}" + raise ValueError(f"unknown temporal position: {position}") + + +def load_report(path: Path, position: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + observed_position = experiment.get("position", "P0") + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or observed_position != position + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal temporal-position evaluation: {path}") + return report + + +def flatten_bias_report(position: str, seed: int, report: dict) -> list[dict[str, object]]: + rows = [] + bias_report = report["temporal_position_bias"] + for layer in bias_report["layers"]: + offsets = layer["offsets_key_minus_query"] + for head, values in enumerate(layer["per_head_bias"]): + for offset, value in zip(offsets, values, strict=True): + rows.append({ + "position": position, "seed": seed, "layer": int(layer["layer"]), + "head": head, "offset_key_minus_query": int(offset), "bias": float(value), + }) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--p0-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--p1-run-root", type=Path, default=Path("artifacts/phase3/temporal_position_runs")) + parser.add_argument("--p0-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--p1-evaluation-root", type=Path, default=Path("artifacts/phase3/temporal_position_full_validation")) + parser.add_argument("--p0-diagnostic-root", type=Path, default=Path("artifacts/phase3/temporal_position_p0_diagnostics")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + diagnostics: dict[tuple[str, int], tuple[Path, dict]] = {} + all_rows = [] + best_rows = [] + checkpoints = {} + for position in POSITIONS: + run_root = args.p0_run_root if position == "P0" else args.p1_run_root + evaluation_root = args.p0_evaluation_root if position == "P0" else args.p1_evaluation_root + for seed in SEEDS: + name = position_run_name(position, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal training run: {name}") + checkpoint_record = {"position": position, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, position, seed) + reports[(position, seed, role)] = (path, report) + row: dict[str, object] = { + "run": name, "position": position, "seed": seed, + "checkpoint_role": role, "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), "evaluation": str(path.resolve()), + } + + diagnostic_path = ( + args.p0_diagnostic_root / name / "best_absolute" / "evaluation.json" + if position == "P0" + else args.p1_evaluation_root / name / "best_absolute" / "evaluation.json" + ) + diagnostic = load_report(diagnostic_path, position, seed) + formal_best = reports[(position, seed, "best_absolute")][1] + for metric in REPORT_METRICS: + if metric_mean(diagnostic, metric) != metric_mean(formal_best, metric): + raise ValueError(f"diagnostic metric drift for {name}: {metric}") + diagnostics[(position, seed)] = (diagnostic_path, diagnostic) + + if len(all_rows) != 42 or len(best_rows) != 6: + raise ValueError(f"expected 42 checkpoint rows and 6 best rows, got {len(all_rows)}, {len(best_rows)}") + write_csv(args.output_dir / "temporal_position_checkpoint_comparison.csv", all_rows) + + for row in best_rows: + diagnostic = diagnostics[(str(row["position"]), int(row["seed"]))][1] + for metric in ATTENTION_METRICS: + row[metric] = attention_mean(diagnostic, metric) + write_csv(args.output_dir / "temporal_position_comparison.csv", best_rows) + (args.output_dir / "temporal_position_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for position in POSITIONS: + group = [row for row in best_rows if row["position"] == position] + record: dict[str, object] = {"position": position, "seeds": list(SEEDS)} + for metric in REPORT_METRICS + ATTENTION_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("trainable_parameters", "peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + } + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + attention_distance_rows = [] + bias_rows = [] + for position in POSITIONS: + for seed in SEEDS: + path, report = diagnostics[(position, seed)] + frame_cache[(position, seed)] = read_csv(path.parent / "per_hand_frame_metrics.csv") + temporal_cache[(position, seed)] = read_csv(path.parent / "per_temporal_transition_metrics.csv") + for distance_mode, report_key in ( + ("absolute", "temporal_attention_by_absolute_frame_distance"), + ("signed_key_minus_query", "temporal_attention_by_signed_frame_distance"), + ): + for distance, distribution in report["attention"][report_key].items(): + attention_distance_rows.append({ + "position": position, "seed": seed, "distance_mode": distance_mode, + "distance": int(distance), **distribution, + }) + bias_rows.extend(flatten_bias_report(position, seed, report)) + write_csv(args.output_dir / "temporal_position_attention_by_distance.csv", attention_distance_rows) + if not bias_rows: + raise ValueError("P1 diagnostic evaluations did not export relative-position bias") + write_csv(args.output_dir / "temporal_position_bias.csv", bias_rows) + + grouped_bias: dict[tuple[int, int, int], list[float]] = {} + for row in bias_rows: + key = (int(row["layer"]), int(row["head"]), int(row["offset_key_minus_query"])) + grouped_bias.setdefault(key, []).append(float(row["bias"])) + bias_aggregate_rows = [{ + "position": "P1", "layer": layer, "head": head, "offset_key_minus_query": offset, + "seed_mean_bias": float(np.mean(values)), + "seed_sample_std_bias": float(np.std(values, ddof=1)), + "seed_20260716_bias": values[0], "seed_20260717_bias": values[1], + "seed_20260718_bias": values[2], + } for (layer, head, offset), values in sorted(grouped_bias.items())] + write_csv(args.output_dir / "temporal_position_bias_aggregate.csv", bias_aggregate_rows) + + paired_rows = [] + coefficients = {"P1": 1.0, "P0": -1.0} + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {position: frame_cache[(position, seed)] for position in POSITIONS}, + metric, coefficients, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": "P1_minus_P0", "metric": metric, + "delta_definition": "P1_minus_P0_lower_is_better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_temporal_position_bootstrap_ci.csv", paired_rows) + + paired_temporal_rows = [] + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {position: temporal_cache[(position, seed)] for position in POSITIONS}, + metric, coefficients, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + paired_temporal_rows.append({ + "comparison": "P1_minus_P0", "metric": metric, + "delta_definition": "P1_minus_P0_lower_is_better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_temporal_position_temporal_ci.csv", paired_temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_temporal_position_bootstrap_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_temporal_position_temporal_ci.csv").resolve()), + "attention_distance": str((args.output_dir / "temporal_position_attention_by_distance.csv").resolve()), + "bias_aggregate": str((args.output_dir / "temporal_position_bias_aggregate.csv").resolve()), + "source_hashes": { + "p0_diagnostic_launcher": sha256(args.p0_diagnostic_root / "launcher_provenance.json"), + "p1_validation_launcher": sha256(args.p1_evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "temporal_position_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "paired_rows": len(paired_rows), "paired_temporal_rows": len(paired_temporal_rows), + "bias_rows": len(bias_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_a1.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_a1.py new file mode 100644 index 0000000000000000000000000000000000000000..72611727f8c8853380b2b3d4d31e8389d70b79e3 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_a1.py @@ -0,0 +1,359 @@ +#!/usr/bin/env python3 +"""Aggregate the three frozen-checkpoint Phase 4 A1 oracle diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary + +if __package__: + from scripts.fit_phase4_oracle_local_depth import paired_take_bootstrap +else: + from fit_phase4_oracle_local_depth import paired_take_bootstrap + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = ("coarse", "control", "local") +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", +) +STABLE_FIELDS = ( + "sample_index", + "clip_index", + "time_index", + "take", + "subject", + "sequence", + "frame_id", + "side", + "side_index", + "action_family", + "action_label", + "action_name", + "hand_size_px", + "wrist_depth_m", + "bimanual_size_ratio", + "bimanual_depth_gap_m", + "bimanual_asymmetry_bucket", + "local_depth_valid_fraction", + "local_depth_discontinuity_m", +) + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV {path}") + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_seed_results(root: Path) -> tuple[ + dict[int, list[dict[str, str]]], dict[int, dict[str, Any]], list[dict[str, str]] +]: + rows_by_seed: dict[int, list[dict[str, str]]] = {} + reports: dict[int, dict[str, Any]] = {} + reference: list[dict[str, str]] | None = None + for seed in SEEDS: + fit = root / f"seed_{seed}" / "fit" + rows = read_csv(fit / "validation_predictions.csv") + report = json.loads((fit / "results.json").read_text(encoding="utf-8")) + if report.get("official_test_used") is not False: + raise ValueError(f"seed {seed} did not preserve official-test isolation") + if reference is None: + reference = rows + else: + if len(rows) != len(reference): + raise ValueError("A1 seed validation row counts differ") + for index, (candidate, expected) in enumerate(zip(rows, reference, strict=True)): + for field in STABLE_FIELDS: + if candidate[field] != expected[field]: + raise ValueError( + f"A1 seed metadata mismatch at row {index}, field {field}" + ) + rows_by_seed[seed] = rows + reports[seed] = report + if reference is None: + raise ValueError("no A1 seed results found") + return rows_by_seed, reports, reference + + +def aggregate_predictions( + rows_by_seed: dict[int, list[dict[str, str]]], +) -> dict[str, dict[str, np.ndarray]]: + output: dict[str, dict[str, np.ndarray]] = {} + for variant in VARIANTS: + output[variant] = {} + for metric in METRICS: + per_seed = np.asarray([ + [float(row[f"{variant}_{metric}"]) for row in rows_by_seed[seed]] + for seed in SEEDS + ], dtype=np.float64) + output[variant][metric] = per_seed.mean(axis=0) + return output + + +def group_masks( + rows: list[dict[str, str]], challenge: dict[str, Any], +) -> dict[str, np.ndarray]: + farthest = float(challenge["thresholds"]["farthest_observed_wrist_depth_p80_m"]) + challenge_clips = {int(value) for value in challenge["clip_indices"]} + return { + "all": np.ones(len(rows), dtype=bool), + "left": np.asarray([row["side"] == "left" for row in rows]), + "right": np.asarray([row["side"] == "right" for row in rows]), + "small": np.asarray([float(row["hand_size_px"]) < 64.0 for row in rows]), + "farthest_observed": np.asarray([ + float(row["wrist_depth_m"]) >= farthest for row in rows + ]), + "strong_asymmetry": np.asarray([ + row["bimanual_asymmetry_bucket"] == "strong" for row in rows + ]), + "challenge": np.asarray([ + int(row["clip_index"]) in challenge_clips for row in rows + ]), + } + + +def aggregate_group_rows( + predictions: dict[str, dict[str, np.ndarray]], masks: dict[str, np.ndarray], +) -> list[dict[str, object]]: + rows: list[dict[str, object]] = [] + for group, mask in masks.items(): + for variant in VARIANTS: + for metric in METRICS: + rows.append({ + "group": group, + "variant": variant, + "metric": metric, + "seed_scope": "per-frame mean over seeds 20260716/17/18", + **distribution_summary(predictions[variant][metric][mask]), + }) + return rows + + +def find_value( + rows: list[dict[str, object]], group: str, variant: str, metric: str, statistic: str, +) -> float: + record = next( + row for row in rows + if row["group"] == group and row["variant"] == variant and row["metric"] == metric + ) + return float(record[statistic]) + + +def seed_summary_rows(reports: dict[int, dict[str, Any]]) -> list[dict[str, object]]: + rows = [] + for seed in SEEDS: + report = reports[seed] + reductions = report["gate"]["reductions_percent"] + rows.append({ + "seed": seed, + "checkpoint_step": report["frozen_checkpoint"]["step"], + "checkpoint_sha256": report["frozen_checkpoint"]["sha256"], + "formal_A1_gate_pass": report["gate"]["formal_A1_gate_pass"], + **reductions, + "control_best_epoch": min( + report["histories"]["control"], + key=lambda row: row["holdout_residual_mae_m"], + )["epoch"], + "local_best_epoch": min( + report["histories"]["local"], + key=lambda row: row["holdout_residual_mae_m"], + )["epoch"], + }) + return rows + + +def markdown_report( + report: dict[str, Any], group_rows: list[dict[str, object]], seed_rows: list[dict[str, object]], +) -> str: + gate = report["gate"] + lines = [ + "# Phase 4 A1 Oracle Local-Depth Diagnostic", + "", + "## Decision", + "", + f"- Formal gate: **{'PASS' if gate['formal_A1_gate_pass'] else 'FAIL'}**.", + f"- Action: **{gate['decision']}**.", + "- Official test used: no.", + "- A2 predicted-location diagnostic is not admitted when A1 fails the preregistered gate.", + "", + "## Three-Seed Aggregate", + "", + "| Metric / group | Coarse | Oracle-location control | Oracle local depth | Reduction vs coarse |", + "|---|---:|---:|---:|---:|", + ] + table_specs = ( + ("z P95 / all", "all", "translation_z_mae_mm", "p95"), + ("absolute MPJPE / all", "all", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / small", "small", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / farthest-observed", "farthest_observed", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / right", "right", "absolute_mpjpe_mm", "mean"), + ("projected MANO 2D / all", "all", "mano_projected_2d_error_px", "mean"), + ) + for label, group, metric, statistic in table_specs: + values = { + variant: find_value(group_rows, group, variant, metric, statistic) + for variant in VARIANTS + } + reduction = 100.0 * (values["coarse"] - values["local"]) / values["coarse"] + lines.append( + f"| {label} | {values['coarse']:.2f} | {values['control']:.2f} | " + f"{values['local']:.2f} | {reduction:.2f}% |" + ) + lines.extend(( + "", + "The aggregate uses the per-frame mean error over the three frozen Phase 3 checkpoints, matching the Phase 4 Wave 0 aggregation convention. The local-depth regressor improves the tail beyond the same-capacity oracle-location control, but the registered full-validation/far-small thresholds are not reached.", + "", + "## Seed Stability", + "", + "| Seed | z P95 reduction | Small absolute reduction | Farthest-observed absolute reduction | Gate | Local best epoch |", + "|---:|---:|---:|---:|---|---:|", + )) + for row in seed_rows: + lines.append( + f"| {row['seed']} | {row['full_validation_z_p95_percent']:.2f}% | " + f"{row['small_absolute_mpjpe_percent']:.2f}% | " + f"{row['farthest_observed_absolute_mpjpe_percent']:.2f}% | " + f"{'pass' if row['formal_A1_gate_pass'] else 'fail'} | {row['local_best_epoch']} |" + ) + lines.extend(( + "", + "Seed 20260718 is the limiting case: its train-only holdout selected epoch 1 and its local-depth gain over the frozen coarse output is small. This prevents a robust three-seed claim even though seeds 20260716 and 20260717 individually pass.", + "", + "## Interpretation", + "", + "- Engineering correctness is established: data/hash isolation, raw depth/K alignment, feature schema, bounded residual, and exact root-relative/direct-2D invariance all passed.", + "- Local depth contains useful information beyond oracle location alone, but the gain is checkpoint-dependent and narrowly misses the preregistered aggregate threshold.", + "- Per the Phase 4 stop rule, do not implement the deployable local-depth branch or A2 at this point. Shift the next metric-z effort to matched axis-aware loss and train-only balanced-sampling controls; A3 remains an independent appearance upper-bound diagnostic.", + "", + "## Sources", + "", + f"- Input root: `{report['input_root']}`", + f"- Aggregate table: `{report['outputs']['comparison_csv']}`", + f"- Take bootstrap: `{report['outputs']['paired_take_bootstrap_ci']}`", + )) + return "\n".join(lines) + "\n" + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--input-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument( + "--challenge-manifest", type=Path, + default=Path("artifacts/phase4/challenge_subset/official_val_challenge_128.json"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + rows_by_seed, reports, metadata = load_seed_results(args.input_root) + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + predictions = aggregate_predictions(rows_by_seed) + group_rows = aggregate_group_rows(predictions, group_masks(metadata, challenge)) + bootstrap_rows = paired_take_bootstrap( + metadata, + predictions, + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + seed_rows = seed_summary_rows(reports) + + coarse_z_p95 = find_value(group_rows, "all", "coarse", "translation_z_mae_mm", "p95") + local_z_p95 = find_value(group_rows, "all", "local", "translation_z_mae_mm", "p95") + reductions = { + "full_validation_z_p95_percent": 100.0 * (coarse_z_p95 - local_z_p95) / coarse_z_p95, + } + for group in ("small", "farthest_observed", "right"): + coarse = find_value(group_rows, group, "coarse", "absolute_mpjpe_mm", "mean") + local = find_value(group_rows, group, "local", "absolute_mpjpe_mm", "mean") + reductions[f"{group}_absolute_mpjpe_percent"] = 100.0 * (coarse - local) / coarse + metric_pass = ( + reductions["full_validation_z_p95_percent"] >= 20.0 + or reductions["small_absolute_mpjpe_percent"] >= 15.0 + or reductions["farthest_observed_absolute_mpjpe_percent"] >= 15.0 + ) + invariance_pass = all( + abs(find_value(group_rows, "all", "local", metric, "mean") + - find_value(group_rows, "all", "coarse", metric, "mean")) <= 1e-4 + for metric in ("root_relative_mpjpe_mm", "direct_2d_error_px") + ) + formal_pass = bool(metric_pass and invariance_pass) + output_csv = args.output_dir / "a1_oracle_local_depth_comparison.csv" + output_bootstrap = args.output_dir / "paired_take_bootstrap_ci.csv" + output_seed = args.output_dir / "a1_oracle_local_depth_seed_stability.csv" + output_json = args.output_dir / "A1_ORACLE_LOCAL_DEPTH.json" + output_md = args.output_dir / "A1_ORACLE_LOCAL_DEPTH.md" + report = { + "status": "complete", + "phase": 4, + "wave": "A1_oracle_local_depth", + "official_test_used": False, + "input_root": str(args.input_root.resolve()), + "seed_scope": list(SEEDS), + "aggregation": "per-frame mean error over three seeds, then distribution summary", + "checkpoint_rule": "Phase 3 fixed-subset tail-best-absolute per seed", + "gate": { + "formal_A1_gate_pass": formal_pass, + "metric_gate_pass": bool(metric_pass), + "invariance_gate_pass": bool(invariance_pass), + "decision": ( + "ADMIT_A2" if formal_pass + else "STOP_LOCAL_DEPTH_BRANCH_AND_SHIFT_TO_LOSS_SAMPLING_OR_BACKBONE_CONTROLS" + ), + "thresholds": { + "full_validation_z_p95_reduction_percent": 20.0, + "small_or_farthest_absolute_mpjpe_reduction_percent": 15.0, + "root_relative_and_direct_2d_max_degradation_percent": 2.0, + }, + "observed_reductions_percent": reductions, + }, + "seed_results": seed_rows, + "outputs": { + "comparison_csv": str(output_csv.resolve()), + "paired_take_bootstrap_ci": str(output_bootstrap.resolve()), + "seed_stability_csv": str(output_seed.resolve()), + "markdown": str(output_md.resolve()), + }, + } + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(output_csv, group_rows) + write_csv(output_bootstrap, bootstrap_rows) + write_csv(output_seed, seed_rows) + output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + output_md.write_text(markdown_report(report, group_rows, seed_rows), encoding="utf-8") + print(json.dumps({"status": "complete", "gate": report["gate"]}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_a3.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_a3.py new file mode 100644 index 0000000000000000000000000000000000000000..d41d5683a4d4ffc98d31e2e3e2bd85c042d499e2 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_a3.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +"""Summarize A3 refined predictions against their exact frozen coarse outputs.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Mapping + +try: + from scripts.summarize_phase4_control import ( + RECONSTRUCTION_KEY, + RECONSTRUCTION_METADATA, + SEEDS, + aggregate_seed_rows, + assert_pair_alignment, + distribution_rows, + groups, + paired_take_bootstrap, + read_csv, + statistic, + write_csv, + ) +except ModuleNotFoundError: + from summarize_phase4_control import ( # type: ignore[no-redef] + RECONSTRUCTION_KEY, + RECONSTRUCTION_METADATA, + SEEDS, + aggregate_seed_rows, + assert_pair_alignment, + distribution_rows, + groups, + paired_take_bootstrap, + read_csv, + statistic, + write_csv, + ) + + +MODES = ("oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k") +METRIC_PAIRS = { + "absolute_mpjpe_mm": "coarse_absolute_mpjpe_mm", + "root_relative_mpjpe_mm": "coarse_root_relative_mpjpe_mm", + "absolute_mpvpe_mm": "coarse_absolute_mpvpe_mm", + "root_relative_mpvpe_mm": "coarse_root_relative_mpvpe_mm", + "fingertip_mpjpe_mm": "coarse_fingertip_mpjpe_mm", + "translation_z_mae_mm": "coarse_translation_z_mae_mm", +} +METRICS = tuple(METRIC_PAIRS) + + +def discover_evaluations(root: Path, role: str) -> dict[str, dict[int, Path]]: + output: dict[str, dict[int, Path]] = {mode: {} for mode in MODES} + for report_path in sorted(root.glob(f"*/{role}/evaluation.json")): + report = json.loads(report_path.read_text(encoding="utf-8")) + oracle = report.get("oracle_crop_refinement", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("clips") != 1495 + or report.get("phase4_diagnostics", {}).get("enabled") is not True + or oracle.get("enabled") is not True + or oracle.get("gt_location_at_inference") is not True + ): + raise ValueError(f"invalid complete A3 evaluation: {report_path}") + config = report["config"] + mode = config["experiment"]["oracle_crop_mode"] + seed = int(config["seed"]) + if mode not in output or seed in output[mode]: + raise ValueError(f"unexpected or duplicate A3 mode/seed: {mode}/{seed}") + if ( + oracle.get("coarse_checkpoint_sha256") + != config["experiment"]["coarse_checkpoint_sha256"] + ): + raise ValueError(f"coarse checkpoint identity missing: {report_path}") + output[mode][seed] = report_path.parent + for mode, records in output.items(): + if tuple(sorted(records)) != SEEDS: + raise ValueError( + f"expected seeds {SEEDS} for {mode}, found {tuple(sorted(records))}" + ) + return output + + +def coarse_rows(rows: list[dict[str, str]]) -> list[dict[str, object]]: + output = [] + for source in rows: + row: dict[str, object] = dict(source) + for metric, coarse_metric in METRIC_PAIRS.items(): + if coarse_metric not in source: + raise ValueError(f"missing A3 coarse metric {coarse_metric}") + row[metric] = source[coarse_metric] + output.append(row) + return output + + +def compute_gate( + coarse_absolute: float, + refined_absolute: float, + coarse_fingertip: float, + refined_fingertip: float, + coarse_root_mpvpe: float, + refined_root_mpvpe: float, +) -> dict[str, float | bool]: + fingertip_gain = 100.0 * (coarse_fingertip - refined_fingertip) / coarse_fingertip + root_mpvpe_gain = 100.0 * ( + coarse_root_mpvpe - refined_root_mpvpe + ) / coarse_root_mpvpe + absolute_degradation = 100.0 * ( + refined_absolute - coarse_absolute + ) / coarse_absolute + return { + "fingertip_improvement_percent": fingertip_gain, + "root_relative_mpvpe_improvement_percent": root_mpvpe_gain, + "absolute_mpjpe_degradation_percent": absolute_degradation, + "accuracy_gain_passed": bool( + fingertip_gain >= 10.0 or root_mpvpe_gain >= 10.0 + ), + "absolute_guardrail_passed": bool(absolute_degradation <= 2.0), + "promotion_gate_passed": bool( + (fingertip_gain >= 10.0 or root_mpvpe_gain >= 10.0) + and absolute_degradation <= 2.0 + ), + } + + +def rename_distribution_conditions( + rows: list[dict[str, object]], mode: str, scope: str, +) -> None: + for row in rows: + row["mode"] = mode + row["scope"] = scope + row["condition"] = { + "reference": "coarse", + "candidate": "refined", + "candidate_minus_reference": "refined_minus_coarse", + }[row["condition"]] + + +def gate_from_distributions( + rows: list[dict[str, object]], mode: str, +) -> dict[str, float | bool]: + def overall(metric: str, condition: str) -> float: + matches = [ + row for row in rows + if row["group_field"] == "all" and row["group_value"] == "all" + and row["metric"] == metric and row["condition"] == condition + ] + if len(matches) != 1: + raise ValueError(f"missing overall {mode}/{metric}/{condition}") + return float(matches[0]["mean"]) + + return compute_gate( + overall("absolute_mpjpe_mm", "coarse"), + overall("absolute_mpjpe_mm", "refined"), + overall("fingertip_mpjpe_mm", "coarse"), + overall("fingertip_mpjpe_mm", "refined"), + overall("root_relative_mpvpe_mm", "coarse"), + overall("root_relative_mpvpe_mm", "refined"), + ) + + +def assert_coarse_identical_across_modes( + raw_by_mode: Mapping[str, Mapping[int, list[dict[str, str]]]], +) -> None: + reference_mode = MODES[0] + for seed in SEEDS: + reference = { + tuple(row[field] for field in RECONSTRUCTION_KEY): tuple( + row[coarse_metric] for coarse_metric in METRIC_PAIRS.values() + ) + for row in raw_by_mode[reference_mode][seed] + } + for mode in MODES[1:]: + candidate = { + tuple(row[field] for field in RECONSTRUCTION_KEY): tuple( + row[coarse_metric] for coarse_metric in METRIC_PAIRS.values() + ) + for row in raw_by_mode[mode][seed] + } + if candidate != reference: + raise ValueError( + f"frozen coarse outputs differ across A3 modes for seed {seed}" + ) + + +def seed_deltas( + raw_by_seed: Mapping[int, list[dict[str, str]]], mode: str, +) -> list[dict[str, object]]: + output = [] + for seed in SEEDS: + rows = [ + row for row in raw_by_seed[seed] + if int(row["annotation_valid"]) == 1 + ] + for metric, coarse_metric in METRIC_PAIRS.items(): + coarse = statistic((row.get(coarse_metric) for row in rows), "mean") + refined = statistic((row.get(metric) for row in rows), "mean") + if coarse is None or refined is None: + continue + output.append({ + "mode": mode, "seed": seed, "metric": metric, + "coarse": coarse, "refined": refined, + "refined_minus_coarse": refined - coarse, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--role", default="best_absolute") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--challenge-manifest", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + evaluations = discover_evaluations(args.evaluation_root, args.role) + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + challenge_indices = {int(value) for value in challenge["clip_indices"]} + if ( + len(challenge_indices) != int(challenge["count"]) + or challenge.get("source_clip_count") != 1495 + or challenge.get("checkpoint_selection_allowed") is not False + or challenge.get("training_sampler_use_allowed") is not False + or challenge.get("official_test_used") is not False + ): + raise ValueError("invalid frozen official-validation challenge subset") + raw_by_mode = { + mode: { + seed: read_csv(evaluations[mode][seed] / "per_hand_frame_metrics.csv") + for seed in SEEDS + } + for mode in MODES + } + assert_coarse_identical_across_modes(raw_by_mode) + + comparison_output = [] + paired_output = [] + seed_output = [] + gates = {} + challenge_diagnostics = {} + for mode_index, mode in enumerate(MODES): + refined = aggregate_seed_rows( + raw_by_mode[mode], RECONSTRUCTION_KEY, METRICS, + ) + coarse = aggregate_seed_rows( + {seed: coarse_rows(raw_by_mode[mode][seed]) for seed in SEEDS}, + RECONSTRUCTION_KEY, METRICS, + ) + assert_pair_alignment( + coarse, refined, RECONSTRUCTION_KEY, RECONSTRUCTION_METADATA, + ) + distributions = distribution_rows( + coarse, refined, METRICS, require_annotation_valid=True, + ) + rename_distribution_conditions(distributions, mode, "full_validation") + comparison_output.extend(distributions) + + valid_coarse = [row for row in coarse if int(row["annotation_valid"]) == 1] + valid_refined = [row for row in refined if int(row["annotation_valid"]) == 1] + paired = paired_take_bootstrap( + valid_coarse, valid_refined, METRICS, groups(valid_coarse), + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + mode_index, + ) + paired.extend(paired_take_bootstrap( + valid_coarse, valid_refined, ("translation_z_mae_mm",), + groups(valid_coarse), statistics=("p95", "cvar95"), + bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 100 + mode_index, + )) + for row in paired: + row["mode"] = mode + row["scope"] = "full_validation" + row["coarse"] = row.pop("reference") + row["refined"] = row.pop("candidate") + row["refined_minus_coarse"] = row.pop("candidate_minus_reference") + paired_output.extend(paired) + seed_output.extend(seed_deltas(raw_by_mode[mode], mode)) + + gates[mode] = gate_from_distributions(distributions, mode) + + challenge_coarse = [ + row for row in coarse if int(row["clip_index"]) in challenge_indices + ] + challenge_refined = [ + row for row in refined if int(row["clip_index"]) in challenge_indices + ] + challenge_distributions = distribution_rows( + challenge_coarse, challenge_refined, METRICS, + require_annotation_valid=True, + ) + rename_distribution_conditions( + challenge_distributions, mode, "challenge_secondary", + ) + comparison_output.extend(challenge_distributions) + challenge_diagnostics[mode] = gate_from_distributions( + challenge_distributions, mode, + ) + challenge_paired = paired_take_bootstrap( + [row for row in challenge_coarse if int(row["annotation_valid"]) == 1], + [row for row in challenge_refined if int(row["annotation_valid"]) == 1], + METRICS, [("all", "all"), ("side", "left"), ("side", "right")], + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 200 + mode_index, + ) + for row in challenge_paired: + row["mode"] = mode + row["scope"] = "challenge_secondary" + row["coarse"] = row.pop("reference") + row["refined"] = row.pop("candidate") + row["refined_minus_coarse"] = row.pop("candidate_minus_reference") + paired_output.extend(challenge_paired) + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "a3_oracle_crop_comparison.csv", comparison_output) + write_csv( + args.output_dir / "a3_oracle_crop_paired_take_bootstrap_ci.csv", + paired_output, + ) + write_csv(args.output_dir / "a3_oracle_crop_seed_stability.csv", seed_output) + report = { + "status": "summarized", + "official_test_used": False, + "role": args.role, + "seeds": list(SEEDS), + "modes": list(MODES), + "aggregation": "aligned per-frame error averaged over three seeds", + "confidence_interval_unit": "paired official-validation take", + "coarse_consistency_across_modes": True, + "challenge_subset": { + "manifest": str(args.challenge_manifest.resolve()), + "clips": len(challenge_indices), + "role": "secondary_diagnostic_only", + "checkpoint_selection_allowed": False, + "diagnostics": challenge_diagnostics, + }, + "promotion_rule": ( + "fingertip MPJPE or root-relative MPVPE improves >=10%, and " + "absolute MPJPE degrades <=2%" + ), + "gates": gates, + } + (args.output_dir / "A3_ORACLE_CROP.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_control.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_control.py new file mode 100644 index 0000000000000000000000000000000000000000..786bf74861d7bf81eeee203f188c84966ad92b02 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_control.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +"""Compare a three-seed Phase 4 control with the matched 100k B-ref.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path +from typing import Iterable, Mapping + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary + + +SEEDS = (20260716, 20260717, 20260718) +RECONSTRUCTION_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "identity_switch_fraction", +) +RECONSTRUCTION_KEY = ("clip_index", "time_index", "side") +TEMPORAL_KEY = ("clip_index", "transition_index", "side") +RECONSTRUCTION_METADATA = ( + "take", + "frame_id", + "side", + "annotation_valid", + "hand_size_bucket", + "depth_bucket", + "action_family", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", +) +GROUP_FIELDS = ( + "side", + "hand_size_bucket", + "depth_bucket", + "action_family", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", +) + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report {path}") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: object) -> float | None: + if value in (None, ""): + return None + result = float(value) + return result if np.isfinite(result) else None + + +def discover_evaluations(root: Path, role: str) -> dict[int, Path]: + output = {} + for report_path in sorted(root.glob(f"*/{role}/evaluation.json")): + report = json.loads(report_path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("official_test_used") is not False: + raise ValueError(f"invalid evaluation report: {report_path}") + if report.get("phase4_diagnostics", {}).get("enabled") is not True: + raise ValueError(f"Phase 4 diagnostics missing: {report_path}") + seed = int(report["config"]["seed"]) + if seed in output: + raise ValueError(f"duplicate seed {seed} under {root}") + output[seed] = report_path.parent + if tuple(sorted(output)) != SEEDS: + raise ValueError(f"expected seeds {SEEDS}, found {tuple(sorted(output))} under {root}") + return output + + +def row_key(row: Mapping[str, object], fields: tuple[str, ...]) -> tuple[str, ...]: + return tuple(str(row[field]) for field in fields) + + +def aggregate_seed_rows( + rows_by_seed: Mapping[int, list[dict[str, str]]], + key_fields: tuple[str, ...], + metric_fields: tuple[str, ...], +) -> list[dict[str, object]]: + maps = { + seed: {row_key(row, key_fields): row for row in rows} + for seed, rows in rows_by_seed.items() + } + keys = set(maps[SEEDS[0]]) + if any(set(maps[seed]) != keys for seed in SEEDS[1:]): + raise ValueError("three-seed exported row keys do not align") + output = [] + for key in sorted(keys): + first = maps[SEEDS[0]][key] + row: dict[str, object] = dict(first) + for metric in metric_fields: + values = [ + optional_float(maps[seed][key].get(metric)) for seed in SEEDS + ] + finite = [value for value in values if value is not None] + row[metric] = float(np.mean(finite)) if finite else None + output.append(row) + return output + + +def assert_pair_alignment( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + key_fields: tuple[str, ...], + metadata_fields: tuple[str, ...], +) -> None: + reference_map = {row_key(row, key_fields): row for row in reference} + candidate_map = {row_key(row, key_fields): row for row in candidate} + if reference_map.keys() != candidate_map.keys(): + raise ValueError("candidate/reference exported row keys do not align") + for key, reference_row in reference_map.items(): + candidate_row = candidate_map[key] + for field in metadata_fields: + if str(reference_row.get(field, "")) != str(candidate_row.get(field, "")): + raise ValueError(f"candidate/reference metadata mismatch at {key}/{field}") + + +def groups(rows: list[dict[str, object]]) -> list[tuple[str, str]]: + output = [("all", "all")] + for field in GROUP_FIELDS: + values = sorted({str(row.get(field)) for row in rows if row.get(field) not in (None, "")}) + output.extend((field, value) for value in values) + return output + + +def selected_rows( + rows: list[dict[str, object]], group_field: str, group_value: str, +) -> list[dict[str, object]]: + if group_field == "all": + return rows + return [row for row in rows if str(row.get(group_field)) == group_value] + + +def distribution_rows( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + metrics: tuple[str, ...], + *, + require_annotation_valid: bool, +) -> list[dict[str, object]]: + if require_annotation_valid: + reference = [row for row in reference if int(row["annotation_valid"]) == 1] + candidate = [row for row in candidate if int(row["annotation_valid"]) == 1] + output = [] + for group_field, group_value in groups(reference): + reference_group = selected_rows(reference, group_field, group_value) + candidate_group = selected_rows(candidate, group_field, group_value) + for metric in metrics: + summaries = { + "reference": distribution_summary(row.get(metric) for row in reference_group), + "candidate": distribution_summary(row.get(metric) for row in candidate_group), + } + for condition, summary in summaries.items(): + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "condition": condition, + **summary, + "mean_relative_percent": None, + }) + delta = { + statistic: ( + summaries["candidate"][statistic] - summaries["reference"][statistic] + if summaries["candidate"][statistic] is not None + and summaries["reference"][statistic] is not None else None + ) + for statistic in ("mean", "p50", "p90", "p95", "p99", "cvar95") + } + reference_mean = summaries["reference"]["mean"] + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "condition": "candidate_minus_reference", + "count": summaries["candidate"]["count"], + "std": None, + **delta, + "mean_relative_percent": ( + 100.0 * delta["mean"] / reference_mean + if delta["mean"] is not None and reference_mean not in (None, 0) else None + ), + }) + return output + + +def statistic(values: Iterable[object], name: str) -> float | None: + array = np.asarray( + [value for item in values if (value := optional_float(item)) is not None], + dtype=np.float64, + ) + if not array.size: + return None + if name == "mean": + return float(array.mean()) + threshold = float(np.percentile(array, 95)) + if name == "p95": + return threshold + if name == "cvar95": + return float(array[array >= threshold].mean()) + raise ValueError(f"unknown statistic {name}") + + +def paired_take_bootstrap( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + metrics: tuple[str, ...], + group_specs: list[tuple[str, str]], + *, + statistics: tuple[str, ...], + bootstrap_samples: int, + seed: int, +) -> list[dict[str, object]]: + output = [] + for group_index, (group_field, group_value) in enumerate(group_specs): + reference_group = selected_rows(reference, group_field, group_value) + candidate_group = selected_rows(candidate, group_field, group_value) + reference_by_take: dict[str, list[dict[str, object]]] = defaultdict(list) + candidate_by_take: dict[str, list[dict[str, object]]] = defaultdict(list) + for row in reference_group: + reference_by_take[str(row["take"])].append(row) + for row in candidate_group: + candidate_by_take[str(row["take"])].append(row) + takes = sorted(set(reference_by_take) & set(candidate_by_take)) + for metric_index, metric in enumerate(metrics): + for statistic_index, statistic_name in enumerate(statistics): + paired = [] + reference_values = [] + candidate_values = [] + for take in takes: + reference_value = statistic( + (row.get(metric) for row in reference_by_take[take]), statistic_name, + ) + candidate_value = statistic( + (row.get(metric) for row in candidate_by_take[take]), statistic_name, + ) + if reference_value is None or candidate_value is None: + continue + reference_values.append(reference_value) + candidate_values.append(candidate_value) + paired.append(candidate_value - reference_value) + deltas = np.asarray(paired, dtype=np.float64) + if not deltas.size: + continue + rng = np.random.default_rng( + np.random.SeedSequence([seed, group_index, metric_index, statistic_index]) + ) + indices = rng.integers( + 0, deltas.size, size=(bootstrap_samples, deltas.size), + ) + distribution = deltas[indices].mean(axis=1) + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "statistic": f"take_{statistic_name}", + "takes": int(deltas.size), + "reference": float(np.mean(reference_values)), + "candidate": float(np.mean(candidate_values)), + "candidate_minus_reference": float(deltas.mean()), + "ci_low": float(np.percentile(distribution, 2.5)), + "ci_high": float(np.percentile(distribution, 97.5)), + "bootstrap_samples": bootstrap_samples, + }) + return output + + +def per_seed_deltas( + reference_dirs: Mapping[int, Path], + candidate_dirs: Mapping[int, Path], +) -> list[dict[str, object]]: + output = [] + for seed in SEEDS: + reference = [ + row for row in read_csv(reference_dirs[seed] / "per_hand_frame_metrics.csv") + if int(row["annotation_valid"]) == 1 + ] + candidate = [ + row for row in read_csv(candidate_dirs[seed] / "per_hand_frame_metrics.csv") + if int(row["annotation_valid"]) == 1 + ] + for metric in RECONSTRUCTION_METRICS: + reference_mean = statistic((row.get(metric) for row in reference), "mean") + candidate_mean = statistic((row.get(metric) for row in candidate), "mean") + if reference_mean is None or candidate_mean is None: + continue + output.append({ + "seed": seed, + "metric": metric, + "reference": reference_mean, + "candidate": candidate_mean, + "candidate_minus_reference": candidate_mean - reference_mean, + }) + return output + + +def lookup_distribution( + rows: list[dict[str, object]], group_field: str, group_value: str, + metric: str, condition: str, +) -> dict[str, object]: + matches = [ + row for row in rows + if row["group_field"] == group_field and row["group_value"] == group_value + and row["metric"] == metric and row["condition"] == condition + ] + if len(matches) != 1: + raise ValueError(f"expected one distribution row, found {len(matches)}") + return matches[0] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-root", type=Path, required=True) + parser.add_argument("--candidate-root", type=Path, required=True) + parser.add_argument("--role", default="best_absolute") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--prefix", required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + reference_dirs = discover_evaluations(args.reference_root, args.role) + candidate_dirs = discover_evaluations(args.candidate_root, args.role) + reconstruction = {} + temporal = {} + for name, directories in (("reference", reference_dirs), ("candidate", candidate_dirs)): + reconstruction[name] = aggregate_seed_rows({ + seed: read_csv(directory / "per_hand_frame_metrics.csv") + for seed, directory in directories.items() + }, RECONSTRUCTION_KEY, RECONSTRUCTION_METRICS) + temporal[name] = aggregate_seed_rows({ + seed: read_csv(directory / "per_temporal_transition_metrics.csv") + for seed, directory in directories.items() + }, TEMPORAL_KEY, TEMPORAL_METRICS) + assert_pair_alignment( + reconstruction["reference"], reconstruction["candidate"], + RECONSTRUCTION_KEY, RECONSTRUCTION_METADATA, + ) + assert_pair_alignment( + temporal["reference"], temporal["candidate"], + TEMPORAL_KEY, ("take", "frame_id_from", "frame_id_to", "side"), + ) + reconstruction_rows = distribution_rows( + reconstruction["reference"], reconstruction["candidate"], + RECONSTRUCTION_METRICS, require_annotation_valid=True, + ) + temporal_rows = distribution_rows( + temporal["reference"], temporal["candidate"], + TEMPORAL_METRICS, require_annotation_valid=False, + ) + valid_reference = [ + row for row in reconstruction["reference"] if int(row["annotation_valid"]) == 1 + ] + valid_candidate = [ + row for row in reconstruction["candidate"] if int(row["annotation_valid"]) == 1 + ] + group_specs = groups(valid_reference) + paired_rows = paired_take_bootstrap( + valid_reference, valid_candidate, RECONSTRUCTION_METRICS, + group_specs, statistics=("mean",), + bootstrap_samples=args.bootstrap_samples, seed=args.seed, + ) + paired_rows.extend(paired_take_bootstrap( + valid_reference, valid_candidate, ("translation_z_mae_mm",), + group_specs, statistics=("p95", "cvar95"), + bootstrap_samples=args.bootstrap_samples, seed=args.seed + 1, + )) + paired_rows.extend(paired_take_bootstrap( + temporal["reference"], temporal["candidate"], TEMPORAL_METRICS, + [("all", "all"), ("side", "left"), ("side", "right")], + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 2, + )) + seed_rows = per_seed_deltas(reference_dirs, candidate_dirs) + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / f"{args.prefix}_comparison.csv", reconstruction_rows + temporal_rows) + write_csv(args.output_dir / f"{args.prefix}_paired_take_bootstrap_ci.csv", paired_rows) + write_csv(args.output_dir / f"{args.prefix}_seed_stability.csv", seed_rows) + + def reduction(group_field: str, group_value: str, metric: str, statistic_name: str) -> float: + reference = lookup_distribution( + reconstruction_rows, group_field, group_value, metric, "reference", + )[statistic_name] + candidate = lookup_distribution( + reconstruction_rows, group_field, group_value, metric, "candidate", + )[statistic_name] + return 100.0 * (float(reference) - float(candidate)) / float(reference) + + gate = { + "z_p95_reduction_percent": reduction( + "all", "all", "translation_z_mae_mm", "p95", + ), + "small_absolute_reduction_percent": reduction( + "hand_size_bucket", "small", "absolute_mpjpe_mm", "mean", + ), + } + report = { + "status": "summarized", + "official_test_used": False, + "reference_root": str(args.reference_root.resolve()), + "candidate_root": str(args.candidate_root.resolve()), + "role": args.role, + "seeds": list(SEEDS), + "aggregation": "mean each aligned per-frame error over three seeds before distributions", + "confidence_interval_unit": "paired official-validation take", + "gate_diagnostics": gate, + "outputs": { + "comparison": f"{args.prefix}_comparison.csv", + "paired_take_bootstrap_ci": f"{args.prefix}_paired_take_bootstrap_ci.csv", + "seed_stability": f"{args.prefix}_seed_stability.csv", + }, + } + (args.output_dir / f"{args.prefix}.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_wave0.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_wave0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3340a99b19f9ae02a56d0a239a6f936d60ab8a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase4_wave0.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +"""Aggregate three frozen Phase 3 references into Phase 4 Wave 0 diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.phase4 import find_failure_intervals + + +SEEDS = (20260716, 20260717, 20260718) +MEAN_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", +) +STABLE_FIELDS = ( + "clip_index", + "time_index", + "take", + "subject", + "sequence", + "frame_id", + "side", + "annotation_valid", + "annotation_state", + "hand_size_px", + "hand_size_bucket", + "wrist_depth_m", + "depth_bucket", + "action_family", + "action_label", + "action_name", + "bimanual_size_ratio", + "bimanual_depth_gap_m", + "right_minus_left_depth_m", + "bimanual_asymmetry_bucket", + "local_depth_valid_fraction", + "local_depth_validity_bucket", + "local_depth_median_m", + "local_depth_q10_m", + "local_depth_q90_m", + "local_depth_iqr_m", + "local_depth_discontinuity_m", + "local_surface_minus_wrist_z_m", + "target_wrist_x_m", + "target_wrist_y_m", + "target_wrist_z_m", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + return + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: object) -> float | None: + if value in (None, ""): + return None + number = float(value) + return number if np.isfinite(number) else None + + +def classify_failure(row: dict[str, Any]) -> str: + if not int(row["annotation_valid"]): + return "annotation_invalid" + wrong_side = optional_float(row.get("wrong_side_preference_mean")) + z_error = float(row["translation_z_mae_mm_mean"]) + root_error = float(row["root_relative_mpjpe_mm_mean"]) + direct_2d = float(row["direct_2d_error_px_mean"]) + conditions = { + "identity": wrong_side is not None and wrong_side >= 0.5, + "z": z_error >= 40.0, + "articulation": root_error >= 30.0, + "localization_2d": direct_2d >= 20.0, + } + active = [name for name, enabled in conditions.items() if enabled] + if not active: + return "nominal" + if active == ["z"]: + return "z_translation_dominant" + if active == ["articulation"]: + return "articulation_dominant" + if active == ["localization_2d"]: + return "localization_2d_dominant" + if active == ["identity"]: + return "identity_assignment" + return "mixed_failure" + + +def aggregate_seed_rows(rows_by_seed: dict[int, list[dict[str, str]]]) -> list[dict[str, Any]]: + reference = rows_by_seed[SEEDS[0]] + for seed in SEEDS[1:]: + rows = rows_by_seed[seed] + if len(rows) != len(reference): + raise ValueError(f"seed {seed} row count differs: {len(rows)} != {len(reference)}") + output: list[dict[str, Any]] = [] + for index, reference_row in enumerate(reference): + row: dict[str, Any] = {field: reference_row.get(field, "") for field in STABLE_FIELDS} + for seed in SEEDS[1:]: + candidate = rows_by_seed[seed][index] + for field in STABLE_FIELDS: + if candidate.get(field, "") != reference_row.get(field, ""): + raise ValueError(f"target field mismatch at row {index}, seed {seed}, {field}") + row["annotation_valid"] = int(reference_row["annotation_valid"]) + row["clip_index"] = int(reference_row["clip_index"]) + row["time_index"] = int(reference_row["time_index"]) + row["frame_id"] = int(reference_row["frame_id"]) + for metric in MEAN_METRICS + ("wrong_side_preference",): + values = [optional_float(rows_by_seed[seed][index].get(metric)) for seed in SEEDS] + finite = np.asarray([value for value in values if value is not None], dtype=np.float64) + row[f"{metric}_mean"] = float(finite.mean()) if finite.size else None + row[f"{metric}_std"] = float(finite.std(ddof=1)) if finite.size > 1 else 0.0 if finite.size else None + row["failure_type"] = classify_failure(row) + output.append(row) + return output + + +def take_side_metrics(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for row in rows: + if int(row["annotation_valid"]): + grouped[(str(row["take"]), str(row["side"]))].append(row) + output = [] + for (take, side), items in sorted(grouped.items()): + record: dict[str, Any] = { + "take": take, + "side": side, + "valid_hand_frames": len(items), + "action_family": items[0]["action_family"], + "hand_size_px_mean": np.mean([float(row["hand_size_px"]) for row in items]), + "wrist_depth_m_mean": np.mean([float(row["wrist_depth_m"]) for row in items]), + "local_depth_valid_fraction_mean": np.mean([ + float(row["local_depth_valid_fraction"]) for row in items + if row["local_depth_valid_fraction"] not in (None, "") + ]), + "strong_asymmetry_fraction": np.mean([ + row["bimanual_asymmetry_bucket"] == "strong" for row in items + if row["bimanual_asymmetry_bucket"] not in (None, "") + ]), + } + for metric in ( + "absolute_mpjpe_mm_mean", + "root_relative_mpjpe_mm_mean", + "absolute_mpvpe_mm_mean", + "fingertip_mpjpe_mm_mean", + "direct_2d_error_px_mean", + "mano_projected_2d_error_px_mean", + "translation_x_mae_mm_mean", + "translation_y_mae_mm_mean", + "translation_z_mae_mm_mean", + "translation_z_signed_error_mm_mean", + ): + summary = distribution_summary(row[metric] for row in items) + base = metric.removesuffix("_mean") + record[f"{base}_mean"] = summary["mean"] + record[f"{base}_p95"] = summary["p95"] + record[f"{base}_cvar95"] = summary["cvar95"] + output.append(record) + return output + + +def select_challenge_subset( + rows: list[dict[str, Any]], + *, + seed: int, + target_clips: int = 128, +) -> tuple[list[int], list[dict[str, Any]], dict[str, float]]: + if target_clips < 112: + raise ValueError("challenge subset needs at least 112 clips for failure/control coverage") + valid = [row for row in rows if int(row["annotation_valid"])] + depths = np.asarray([float(row["wrist_depth_m"]) for row in valid], dtype=np.float64) + farthest_observed_threshold = float(np.percentile(depths, 80)) + z_median = float(np.median([row["translation_z_mae_mm_mean"] for row in valid])) + selected: dict[int, dict[str, Any]] = {} + failure_clips: set[int] = set() + + def sample_record(row: dict[str, Any], reason: str) -> dict[str, Any]: + return { + "clip_index": int(row["clip_index"]), + "time_index": int(row["time_index"]), + "take": row["take"], + "frame_id": int(row["frame_id"]), + "side": row["side"], + "action_label": int(row["action_label"]), + "action_name": row["action_name"], + "hand_size_px": float(row["hand_size_px"]), + "wrist_depth_m": float(row["wrist_depth_m"]), + "absolute_mpjpe_mm_mean": float(row["absolute_mpjpe_mm_mean"]), + "translation_z_mae_mm_mean": float(row["translation_z_mae_mm_mean"]), + "reasons": [reason], + } + + def add_failure( + candidates: list[dict[str, Any]], + count: int, + reason: str, + metric: str, + ) -> None: + if count <= 0: + return + ordered = sorted( + candidates, + key=lambda row: (-float(row[metric]), str(row["take"]), int(row["frame_id"]), str(row["side"])), + ) + added = 0 + for row in ordered: + clip_index = int(row["clip_index"]) + if clip_index in selected: + if reason not in selected[clip_index]["reasons"]: + selected[clip_index]["reasons"].append(reason) + continue + selected[clip_index] = sample_record(row, reason) + failure_clips.add(clip_index) + added += 1 + if added >= count: + break + + for side, right_count, left_count in (("right", 12, 0), ("left", 0, 8)): + add_failure( + [row for row in valid if row["side"] == side], + right_count + left_count, + "high_z_error", + "translation_z_mae_mm_mean", + ) + for side in ("left", "right"): + add_failure( + [row for row in valid if row["side"] == side], + 8, + "high_absolute_error", + "absolute_mpjpe_mm_mean", + ) + add_failure([ + row for row in valid + if row["side"] == side + and row["hand_size_bucket"] == "small" + and float(row["wrist_depth_m"]) >= farthest_observed_threshold + ], 6, "farthest_observed_small_hand", "translation_z_mae_mm_mean") + add_failure([ + row for row in valid + if row["side"] == side and row["bimanual_asymmetry_bucket"] == "strong" + ], 6, "strong_bimanual_asymmetry", "translation_z_mae_mm_mean") + add_failure([ + row for row in valid + if row["side"] == side and int(row["action_label"]) != 0 + ], 2, "object_interaction", "absolute_mpjpe_mm_mean") + + for side in ("left", "right"): + side_count = sum(selected[index]["side"] == side for index in failure_clips) + add_failure( + [row for row in valid if row["side"] == side], + max(0, 32 - side_count), + "failure_balance_fill", + "translation_z_mae_mm_mean", + ) + + # Add one ordinary low-z control for every take and side. These 48 clips + # prevent the diagnostic from collapsing onto a few known failure takes. + controls = [row for row in valid if float(row["translation_z_mae_mm_mean"]) <= z_median] + for take in sorted({str(row["take"]) for row in valid}): + for side in ("left", "right"): + candidates = [ + row for row in controls + if row["take"] == take + and row["side"] == side + and int(row["clip_index"]) not in selected + ] + candidates.sort(key=lambda row: ( + abs(float(row["translation_z_mae_mm_mean"]) - z_median), + int(row["frame_id"]), + )) + if candidates: + record = sample_record(candidates[0], "take_side_low_z_control") + selected[int(record["clip_index"])] = record + + challenge_samples = [selected[index] for index in sorted(failure_clips)] + rng = np.random.default_rng(seed) + challenge_order = rng.permutation(len(challenge_samples)) + for challenge_index in challenge_order: + if len(selected) >= target_clips: + break + challenge = challenge_samples[int(challenge_index)] + matches = [ + row for row in controls + if int(row["action_label"]) == int(challenge["action_label"]) + and row["side"] == challenge["side"] + and int(row["clip_index"]) not in selected + ] + if not matches: + continue + matches.sort(key=lambda row: ( + abs(float(row["hand_size_px"]) - float(challenge["hand_size_px"])) + / max(float(challenge["hand_size_px"]), 1.0) + + abs(float(row["wrist_depth_m"]) - float(challenge["wrist_depth_m"])) / 0.1, + str(row["take"]), + int(row["frame_id"]), + )) + match = matches[0] + record = sample_record(match, "same_action_low_z_matched_control") + record["matched_to_clip_index"] = int(challenge["clip_index"]) + selected[int(record["clip_index"])] = record + + if len(selected) < target_clips: + ordinary = sorted( + controls, + key=lambda row: ( + abs(float(row["translation_z_mae_mm_mean"]) - z_median), + int(row["action_label"]), + str(row["side"]), + int(row["clip_index"]), + ), + ) + for row in ordinary: + if len(selected) >= target_clips: + break + clip_index = int(row["clip_index"]) + if clip_index in selected: + continue + selected[clip_index] = sample_record(row, "ordinary_action_matched_fill") + samples = sorted(selected.values(), key=lambda row: int(row["clip_index"])) + return [int(row["clip_index"]) for row in samples], samples, { + "farthest_observed_wrist_depth_p80_m": farthest_observed_threshold, + "reference_z_error_median_mm": z_median, + } + + +def compare_legacy_outputs( + evaluation_root: Path, + checkpoint_index: dict[str, Any], +) -> list[dict[str, Any]]: + records = [] + for run in checkpoint_index["runs"].values(): + seed = int(run["seed"]) + original = Path(run["roles"]["tail_best_absolute"]["evaluation"]).parent + current = evaluation_root / f"seed_{seed}" + original_report = json.loads((original / "evaluation.json").read_text(encoding="utf-8")) + current_report = json.loads((current / "evaluation.json").read_text(encoding="utf-8")) + exact = True + for metric, summary in original_report["metrics"].items(): + for statistic, value in summary.items(): + exact &= current_report["metrics"][metric][statistic] == value + for filename in ("per_hand_frame_metrics.csv", "per_temporal_transition_metrics.csv"): + old_rows = read_csv(original / filename) + new_rows = read_csv(current / filename) + exact &= len(old_rows) == len(new_rows) + if exact: + for old_row, new_row in zip(old_rows, new_rows, strict=True): + exact &= all(new_row[key] == value for key, value in old_row.items()) + records.append({ + "seed": seed, + "checkpoint_sha256": current_report["checkpoint"]["sha256"], + "manifest_sha256": current_report["manifest"]["sha256"], + "clips": current_report["clips"], + "frames": current_report["frames"], + "legacy_outputs_exact": bool(exact), + "source_phase3_evaluation": str(original), + "phase4_evaluation": str(current.resolve()), + }) + if not all(record["legacy_outputs_exact"] for record in records): + raise ValueError("Phase 4 evaluator does not reproduce Phase 3 outputs exactly") + return sorted(records, key=lambda row: int(row["seed"])) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--evaluation-root", + type=Path, + default=Path("artifacts/phase4/wave0/reference_evaluations"), + ) + parser.add_argument( + "--checkpoint-index", + type=Path, + default=Path("artifacts/phase3/reports/long_tail_checkpoints.json"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/reports")) + parser.add_argument( + "--challenge-output", + type=Path, + default=Path("artifacts/phase4/challenge_subset/official_val_challenge_128.json"), + ) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + args.challenge_output.parent.mkdir(parents=True, exist_ok=True) + + checkpoint_index = json.loads(args.checkpoint_index.read_text(encoding="utf-8")) + consistency = compare_legacy_outputs(args.evaluation_root, checkpoint_index) + rows_by_seed = { + seed: read_csv(args.evaluation_root / f"seed_{seed}" / "per_hand_frame_metrics.csv") + for seed in SEEDS + } + aggregated = aggregate_seed_rows(rows_by_seed) + valid = [row for row in aggregated if int(row["annotation_valid"])] + take_rows = take_side_metrics(aggregated) + write_csv(args.output_dir / "take_side_metrics.csv", take_rows) + write_csv(args.output_dir / "failure_taxonomy.csv", aggregated) + + failure_intervals = find_failure_intervals( + [ + {**row, "translation_z_mae_mm": row["translation_z_mae_mm_mean"]} + for row in aggregated + ], + metric="translation_z_mae_mm", + threshold=40.0, + minimum_frames=3, + ) + find_failure_intervals( + [ + {**row, "absolute_mpjpe_mm": row["absolute_mpjpe_mm_mean"]} + for row in aggregated + ], + metric="absolute_mpjpe_mm", + threshold=50.0, + minimum_frames=3, + ) + write_csv(args.output_dir / "wave0_failure_intervals.csv", failure_intervals) + + bootstrap_metrics = tuple(f"{metric}_mean" for metric in MEAN_METRICS[:10]) + bootstrap_rows = bootstrap_take_means( + valid, + bootstrap_metrics, + seed=args.seed, + samples=10_000, + ) + write_csv(args.output_dir / "wave0_reference_take_bootstrap_ci.csv", bootstrap_rows) + + clip_indices, challenge_samples, thresholds = select_challenge_subset( + aggregated, + seed=args.seed, + target_clips=128, + ) + validation_manifest = Path( + json.loads( + (args.evaluation_root / f"seed_{SEEDS[0]}" / "evaluation.json").read_text( + encoding="utf-8" + ) + )["manifest"]["path"] + ) + challenge_manifest = { + "version": "phase4_official_val_challenge_v1", + "seed": args.seed, + "count": len(clip_indices), + "source_manifest": str(validation_manifest), + "source_manifest_sha256": sha256(validation_manifest), + "source_clip_count": 1495, + "dataset_contract": {"resolution_hw": [368, 640], "T": 8, "stride": 1}, + "source_checkpoints": [ + {"seed": record["seed"], "sha256": record["checkpoint_sha256"]} + for record in consistency + ], + "selection_policy": ( + "secondary diagnostic only: high z/absolute error, farthest-observed small hands, " + "strong bimanual asymmetry, object interaction, same-action low-z controls, and " + "ordinary matched fill" + ), + "thresholds": thresholds, + "far_note": ( + "Official validation has no valid wrist z >= 0.8 m. The challenge therefore uses " + "the observed validation wrist-depth P80 and labels it farthest-observed, not far." + ), + "checkpoint_selection_allowed": False, + "training_sampler_use_allowed": False, + "official_test_used": False, + "clip_indices": sorted(clip_indices), + "reason_counts": dict(Counter( + reason for sample in challenge_samples for reason in sample["reasons"] + )), + "samples": challenge_samples, + } + args.challenge_output.write_text( + json.dumps(challenge_manifest, indent=2) + "\n", encoding="utf-8" + ) + write_csv(args.challenge_output.with_suffix(".csv"), challenge_samples) + + taxonomy_counts = Counter(str(row["failure_type"]) for row in aggregated) + report = { + "status": "passed", + "official_test_used": False, + "evaluator_commit": "222b247cbf574faa9c9051832d0d51077df4573c", + "consistency": consistency, + "valid_hand_frames": len(valid), + "failure_taxonomy_counts": dict(taxonomy_counts), + "long_failure_intervals": len(failure_intervals), + "challenge_manifest": str(args.challenge_output.resolve()), + "challenge_manifest_sha256": sha256(args.challenge_output), + "challenge_clips": len(clip_indices), + } + (args.output_dir / "WAVE0_AUDIT.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase7_sequence_cache.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase7_sequence_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee2c43bea6622923c9cf4735cfd8610f5aeae19 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase7_sequence_cache.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Summarize frozen offline/causal sequence caches with static and dynamic metrics.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from foundation_hand.models.mano import ManoCameraLayer +from scripts.evaluate_phase4_jitter import ( + condition_grid, filtered_parameters, identity_switch_metrics, load_take, + per_frame_metrics, rebuild_geometry, temporal_metrics, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_manifest(manifest: dict[str, Any], path: Path) -> None: + if ( + manifest.get("status") != "complete" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_validation_used_for_selection") is not False + or manifest.get("official_test_used") is not False + or manifest.get("sequence_mode") not in {"offline", "causal"} + or int(manifest.get("sequence_window", -1)) < 1 + ): + raise ValueError(f"invalid frozen sequence cache manifest: {path}") + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"cannot write empty sequence summary: {path}") + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + + +def aligned_metrics(arrays: dict[str, np.ndarray], joints: np.ndarray) -> dict[str, list[float]]: + values: dict[str, list[float]] = defaultdict(list) + valid = arrays["joint_annotation_valid"].astype(bool) + valid &= arrays["frame_valid"][:, None].astype(bool) + for side in range(2): + indices = np.where(valid[:, side])[0] + if not len(indices): + continue + target = arrays["target_joints_camera"][indices, side] + predicted = joints[indices, side] + values["rigid_se3_mpjpe_mm"].extend(aligned_mpjpe_mm( + predicted, target, estimate_scale=False, + ).tolist()) + values["pa_mpjpe_mm"].extend(aligned_mpjpe_mm( + predicted, target, estimate_scale=True, + ).tolist()) + return values + + +def continuous_take_arrays(arrays: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + """Normalize legacy frame-iterator indices to one continuous take stream.""" + + if str(arrays.get("sequence_mode", "")) not in {"offline", "causal"}: + raise ValueError("take cache is not a bounded sequence-inference cache") + normalized = dict(arrays) + normalized["clip_index"] = np.zeros_like(arrays["frame_id"], dtype=np.int64) + return normalized + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--bootstrap-samples", type=int, default=2000) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + validate_manifest(manifest, manifest_path) + args.output_dir.mkdir(parents=True) + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + condition = condition_grid()["F0_raw"] + global_values: dict[str, list[float]] = defaultdict(list) + take_rows: list[dict[str, Any]] = [] + for take_record in manifest["takes"]: + path = Path(take_record["path"]) + if sha256(path) != take_record["sha256"]: + raise ValueError(f"take cache hash mismatch: {path}") + arrays = continuous_take_arrays(load_take(path)) + translation, rotations, _ = filtered_parameters(arrays, condition) + vertices, joints = rebuild_geometry( + rotations, arrays["pred_shape"].astype(np.float32), translation, + mano, device, + ) + selected = arrays["frame_valid"].astype(bool) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, rotations, translation, selected, + ) + for metric, observations in temporal_metrics( + arrays, joints, projected, selected, + ).items(): + metrics[metric].extend(observations) + for metric, observations in identity_switch_metrics( + arrays, joints, selected, + ).items(): + metrics[metric].extend(observations) + for metric, observations in aligned_metrics(arrays, joints).items(): + metrics[metric].extend(observations) + row: dict[str, Any] = {"take": str(arrays["take"]), "frames": len(joints)} + for metric, observations in metrics.items(): + global_values[metric].extend(observations) + summary = distribution_summary(observations) + row[metric] = summary["mean"] + row[f"{metric}_p95"] = summary["p95"] + take_rows.append(row) + all_fields = sorted({key for row in take_rows for key in row}) + normalized_rows = [{key: row.get(key) for key in all_fields} for row in take_rows] + write_csv(args.output_dir / "take_metrics.csv", normalized_rows) + metric_rows = [ + {"metric": metric, **distribution_summary(observations)} + for metric, observations in sorted(global_values.items()) + ] + write_csv(args.output_dir / "metrics.csv", metric_rows) + metric_names = sorted(global_values) + bootstrap = bootstrap_take_means( + take_rows, metric_names, seed=20260717, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "take_bootstrap_ci.csv", bootstrap) + report = { + "status": "evaluated_frozen_sequence_cache", + "sequence_mode": manifest["sequence_mode"], + "causal": manifest["sequence_mode"] == "causal", + "window": manifest["sequence_window"], + "offline_stride": manifest.get("offline_stride"), + "frames": manifest["frames"], "takes": len(manifest["takes"]), + "metrics": {row["metric"]: { + key: value for key, value in row.items() if key != "metric" + } for row in metric_rows}, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], "config": manifest["config"], + "bounded_memory": { + "maximum_gpu_window_frames": manifest["maximum_gpu_window_frames"], + "maximum_cpu_input_buffer_frames": manifest["maximum_cpu_input_buffer_frames"], + }, + "take_metrics": "take_metrics.csv", "take_bootstrap_ci": "take_bootstrap_ci.csv", + "official_validation_used_for_selection": False, "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "mode": report["sequence_mode"], + "absolute_mpjpe_mm": report["metrics"]["absolute_mpjpe_mm"]["mean"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase8_cross_domain_matrix.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase8_cross_domain_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec718b00fb86cb246600b0fafc8acaeb0e86941 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase8_cross_domain_matrix.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Summarize a frozen external cross-domain matrix without frame weighting.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "rigid_se3_mpjpe_mm", + "pa_mpjpe_mm", "mpvpe_mm", "fingertip_mpjpe_mm", + "projected_mano_2d_error_px", "translation_x_mae_mm", + "translation_y_mae_mm", "translation_z_mae_mm", +) + + +def metric_mean(report: dict[str, Any], metric: str) -> float: + value = report.get("metrics", {}).get(metric) + if not isinstance(value, dict) or value.get("mean") is None: + return math.nan + return float(value["mean"]) + + +def summarize(manifest: Path, output_dir: Path) -> dict[str, Any]: + specification = json.loads(manifest.read_text(encoding="utf-8")) + if specification.get("official_test_used") is not False: + raise ValueError("matrix manifest must set official_test_used=false") + entries = specification.get("entries", []) + if not entries: + raise ValueError("matrix manifest is empty") + if output_dir.exists() and any(output_dir.iterdir()): + raise ValueError("output directory must be new or empty") + output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, Any]] = [] + checkpoint_by_condition: dict[str, str] = {} + seen: set[tuple[str, str]] = set() + for entry in entries: + condition, dataset = str(entry["condition"]), str(entry["dataset"]) + key = (condition, dataset) + if key in seen: + raise ValueError(f"duplicate matrix cell: {condition}/{dataset}") + seen.add(key) + path = Path(entry["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"non-external or non-frozen matrix result: {path}") + checkpoint_sha = str(report["checkpoint"]["sha256"]) + prior = checkpoint_by_condition.setdefault(condition, checkpoint_sha) + if prior != checkpoint_sha: + raise ValueError(f"condition uses multiple checkpoints: {condition}") + row: dict[str, Any] = { + "condition": condition, "dataset": dataset, + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint_sha256": checkpoint_sha, + "input_mode": report["input_mode"], + "clips": int(report["clips"]), "frames": int(report["frames"]), + "evaluation": str(path.resolve()), + } + coverage = report.get("metrics", {}).get("supervision_coverage") + if not isinstance(coverage, dict): + raise ValueError(f"matrix result lacks supervision coverage: {path}") + for scope in ("overall", "left", "right"): + scoped = coverage.get(scope) + if not isinstance(scoped, dict): + raise ValueError(f"matrix result lacks {scope} supervision coverage: {path}") + for supervision in ("joint3d", "translation", "vertices"): + key = f"{supervision}_valid_fraction" + if scoped.get(key) is None: + raise ValueError(f"matrix result lacks {scope}/{key}: {path}") + row[f"{scope}_{key}"] = float(scoped[key]) + row.update({metric: metric_mean(report, metric) for metric in METRICS}) + z_summary = report.get("metrics", {}).get("translation_z_mae_mm") or {} + row["translation_z_p95_mm"] = float(z_summary.get("p95", math.nan)) + rows.append(row) + conditions = sorted({row["condition"] for row in rows}) + datasets = sorted({row["dataset"] for row in rows}) + expected = {(condition, dataset) for condition in conditions for dataset in datasets} + if seen != expected: + missing = sorted(expected - seen) + raise ValueError(f"cross-domain matrix is incomplete: {missing}") + + ranks: dict[str, dict[str, float]] = {condition: {} for condition in conditions} + for dataset in datasets: + selected = sorted( + (row for row in rows if row["dataset"] == dataset), + key=lambda row: row["absolute_mpjpe_mm"], + ) + for rank, row in enumerate(selected, 1): + ranks[row["condition"]][dataset] = float(rank) + mean_rank = { + condition: sum(ranks[condition].values()) / len(datasets) + for condition in conditions + } + absolute = { + condition: { + row["dataset"]: row["absolute_mpjpe_mm"] + for row in rows if row["condition"] == condition + } + for condition in conditions + } + pareto = [] + for condition in conditions: + dominated = any( + other != condition + and all(absolute[other][dataset] <= absolute[condition][dataset] for dataset in datasets) + and any(absolute[other][dataset] < absolute[condition][dataset] for dataset in datasets) + for other in conditions + ) + if not dominated: + pareto.append(condition) + + csv_path = output_dir / "cross_domain_matrix.csv" + with csv_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "complete", "selection": "dataset_macro_mean_rank", + "conditions": conditions, "datasets": datasets, + "dataset_ranks": ranks, "mean_rank": mean_rank, + "pareto_frontier": pareto, "rows": rows, + "official_test_used": False, + } + (output_dir / "summary.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + try: + result = summarize(args.manifest, args.output_dir) + except ValueError as error: + parser.error(str(error)) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase8_egodexter.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase8_egodexter.py new file mode 100644 index 0000000000000000000000000000000000000000..20bc81db0816cfd08d32c419fc3c157447dbb500 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase8_egodexter.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Summarize the complete frozen Phase 8 EgoDexter zero-shot grid.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_egodexter_zero_shot import sha256 + + +def summarize(queue_paths: list[Path]) -> dict[str, Any]: + rows = [] + model_ids: set[str] = set() + for queue_path in queue_paths: + queue = json.loads(queue_path.read_text(encoding="utf-8")) + if ( + queue.get("egodexter_used_for_training_or_selection") is not False + or queue.get("official_test_used") is not False + ): + raise ValueError("EgoDexter queue boundary flags are invalid") + model_ids.add(queue["model_id"]) + for item in queue["evaluations"]: + report_path = Path(item["output_dir"]) / "evaluation.json" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_frozen_egodexter_zero_shot" + or report.get("model_id") != item["model_id"] + or report.get("input_mode") != item["input_mode"] + or report.get("inference_mode") != item["inference_mode"] + or report.get("checkpoint", {}).get("sha256") != item["checkpoint_sha256"] + or report.get("egodexter_used_for_training_or_selection") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid EgoDexter report: {report_path}") + for artifact in ("per_fingertip_rows", "raw_predictions"): + record = report[artifact] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"EgoDexter {artifact} is missing or differs") + metric = report["fingertip_error_mm"] + rows.append({ + "model_id": item["model_id"], + "inference_mode": item["inference_mode"], + "input_mode": item["input_mode"], + "mean_fingertip_mm": metric["mean"], + "median_fingertip_mm": metric["median"], + "p95_fingertip_mm": metric["p95"], + "visible_fingertips": report["visible_fingertips"], + "coverage_fraction": report["coverage_fraction"], + "frames": report["frames"], + "fps": report["runtime"]["frames_per_second"], + "peak_vram_gib": report["runtime"]["peak_vram_gib"], + "maximum_gpu_window_frames": report["runtime"]["maximum_gpu_window_frames"], + "maximum_cpu_input_buffer_frames": report["runtime"]["maximum_cpu_input_buffer_frames"], + "per_finger": report["per_finger"], + "per_sequence": report["per_sequence"], + "evaluation": str(report_path.resolve()), + "evaluation_sha256": sha256(report_path), + }) + expected = len(model_ids) * 6 + identities = { + (row["model_id"], row["inference_mode"], row["input_mode"]) + for row in rows + } + if len(rows) != expected or len(identities) != expected: + raise ValueError("EgoDexter summary is not a complete unique grid") + return { + "schema_version": "phase8_egodexter_summary_v1", + "status": "complete_frozen_zero_shot", + "models": sorted(model_ids), + "conditions": rows, + "selection_use": False, + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", action="append", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("summary outputs must not exist") + try: + result = summarize(args.queue) + except (KeyError, OSError, ValueError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + csv_fields = [ + "model_id", "inference_mode", "input_mode", "mean_fingertip_mm", + "median_fingertip_mm", "p95_fingertip_mm", "visible_fingertips", + "coverage_fraction", "frames", "fps", "peak_vram_gib", + "maximum_gpu_window_frames", "maximum_cpu_input_buffer_frames", + "evaluation", "evaluation_sha256", + ] + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=csv_fields, lineterminator="\n") + writer.writeheader() + writer.writerows({key: row[key] for key in csv_fields} for row in result["conditions"]) + print(json.dumps({"status": result["status"], "conditions": len(result["conditions"])}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_final_deployment.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_final_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..8a16fb5023edce3600880e38c45f2309e30f30c8 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_final_deployment.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Summarize formal H2O disclosure and the final deployment contract.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.run_phase9_final_deployment_worker import completed_matches +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def mean_metric(report: dict[str, Any], name: str) -> float: + value = report["metrics"][name] + return float(value["mean"] if isinstance(value, dict) else value) + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + jobs = {job["id"]: job for job in plan["jobs"]} + if len(jobs) != 11 or any(not completed_matches(job) for job in jobs.values()): + raise ValueError("final deployment jobs are not complete and bound") + formal = {} + formal_gpu_hours = 0.0 + for mode in plan["formal_validation_modes"]: + job = jobs[f"formal_{mode}"] + path = Path(job["output_dir"]) / "evaluation.json" + report = read_json(path) + formal_gpu_hours += float(report["runtime"]["wall_seconds"]) / 3600.0 + formal[mode] = { + "report": {"path": str(path.resolve()), "sha256": sha256(path)}, + "absolute_mpjpe_mm": mean_metric(report, "absolute_mpjpe_mm"), + "root_relative_mpjpe_mm": mean_metric(report, "root_relative_mpjpe_mm"), + "fingertip_mpjpe_mm": mean_metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": float( + report["metrics"]["translation_z_mae_mm"]["p95"] + ), + "frames": int(report["frames"]), + "peak_vram_gib": float(report["runtime"]["peak_vram_gib"]), + } + variable_job = jobs["variable_length"] + variable_path = Path(variable_job["output"]) + variable = read_json(variable_path) + sequence = {} + for mode in ("offline", "causal"): + sequence[mode] = {} + for frames in plan["sequence_contract"]["ordering_lengths"]: + job = jobs[f"{mode}_w8_{frames}"] + path = Path(job["output"]) + report = read_json(path) + sequence[mode][str(frames)] = { + "report": {"path": str(path.resolve()), "sha256": sha256(path)}, + "throughput_fps": float(report["throughput_fps"]), + "peak_allocated_gib": float(report["peak_allocated_gib"]), + "maximum_gpu_window_frames": int(report["maximum_gpu_window_frames"]), + "maximum_cpu_input_buffer_frames": int( + report["maximum_cpu_input_buffer_frames"] + ), + "invariance": report.get("invariance"), + } + profile_path = Path(jobs["latency_vram"]["output"]) + profile = read_json(profile_path) + attempts = [] + total_gpu_seconds = 0.0 + for worker in plan["workers"]: + state_path = Path(worker["state"]) + state = read_json(state_path) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + ): + raise ValueError(f"final deployment worker state differs: {worker['id']}") + for attempt in state.get("attempts", []): + start = datetime.fromisoformat(attempt["start_utc"]) + end = datetime.fromisoformat(attempt["end_utc"]) + seconds = (end - start).total_seconds() + if seconds < 0: + raise ValueError("final deployment attempt duration is negative") + total_gpu_seconds += seconds + attempts.append({ + "worker": worker["id"], "id": attempt["id"], + "kind": attempt["kind"], "physical_gpu_id": attempt["physical_gpu_id"], + "start_utc": attempt["start_utc"], "end_utc": attempt["end_utc"], + "returncode": attempt["returncode"], + "gpu_hours": seconds / 3600.0, + "archived_incomplete_output": attempt.get("archived_incomplete_output"), + }) + return { + "schema_version": "phase9_final_deployment_summary_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "final_checkpoint_deployment_contract_passed", + "winner": plan["winner"], + "selected_mechanism": plan["selected_mechanism"], + "resolution_hw": plan["resolution_hw"], + "shared_augmentation": plan["shared_augmentation"], + "checkpoint": plan["checkpoint"], "config": plan["config"], + "formal_h2o_validation": formal, + "formal_h2o_validation_checkpoint_count": 1, + "formal_h2o_validation_gpu_hours": formal_gpu_hours, + "formal_h2o_validation_used_for_selection": False, + "variable_length": { + "report": {"path": str(variable_path.resolve()), "sha256": sha256(variable_path)}, + "lengths": [item["T"] for item in variable["forward_results"]], + "all_finite": all(item["all_finite"] for item in variable["forward_results"]), + }, + "sequence_inference": sequence, + "latency_vram": { + "report": {"path": str(profile_path.resolve()), "sha256": sha256(profile_path)}, + "latency": profile["latency"], + "peak_allocated_vram_gib": profile["peak_allocated_vram_gib"], + "supported_operator_flops_per_clip": profile[ + "supported_operator_flops_per_clip" + ], + }, + "deployment_attempts": attempts, + "deployment_total_gpu_hours": total_gpu_seconds / 3600.0, + "recovery_disclosure": [ + attempt for attempt in attempts + if attempt["returncode"] != 0 + or attempt["archived_incomplete_output"] is not None + ], + "deployment_contract": { + "t_1_2_4_8_16_32_64": True, + "offline_overlap_w8_31_64_257": True, + "causal_rolling_w8_31_64_257": True, + "future_prefix_invariance": True, + "bounded_memory": True, + "fresh_resolution_latency_vram": True, + "passed": True, + }, + "selection_mutated_after_formal_validation": False, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = summarize(args.plan) + if args.output.exists(): + existing = read_json(args.output) + for key in ("created_utc",): + existing.pop(key, None) + result.pop(key, None) + if existing != result: + raise ValueError("existing final deployment summary differs") + else: + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(read_json(args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_hot_scale.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_hot_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..ed40258b5b96d9a269aa993872a60e029faed81f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_hot_scale.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Summarize the matched Phase 9 HOT unique-coverage experiment.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + +from scripts.select_phase7_external_continuation import paired_take_bootstrap + + +METRICS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "pa_mpjpe_mm": ("pa_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_x_mae_mm": ("translation_x_mae_mm", "mean"), + "translation_y_mae_mm": ("translation_y_mae_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} + + +def load_evaluation(path: Path) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(path) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_phase9_external_heldout" + or report.get("evaluation_role") != "phase9_external_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("official_test_used") is not False + ): + raise ValueError(f"evaluation role/isolation mismatch: {path}") + return report + + +def scalar(report: dict[str, Any], metric: str, statistic: str) -> float: + value = float(report["metrics"][metric][statistic]) + if not math.isfinite(value): + raise ValueError(f"non-finite {metric}.{statistic}") + return value + + +def result_row( + condition: str, unique_clips: int, source_id: str, report: dict[str, Any], +) -> dict[str, Any]: + metrics = { + output: scalar(report, metric, statistic) + for output, (metric, statistic) in METRICS.items() + } + for name in ("aria", "quest3"): + bucket = report["metrics"].get(f"bucket_headset_{name}") + metrics[f"{name}_absolute_mpjpe_mm"] = ( + None if not bucket else float(bucket["absolute_mpjpe_mm"]["mean"]) + ) + return { + "condition": condition, + "hot_unique_clips": unique_clips, + "source_id": source_id, + "checkpoint": report["checkpoint"], + "metrics": metrics, + } + + +def summarize( + registry: dict[str, Any], evaluation_root: Path, control_root: Path, +) -> dict[str, Any]: + if registry.get("official_test_used") is not False: + raise ValueError("registry must explicitly exclude official test") + clip_counts = {"J40_HOT10K": 10_000, "J40_HOT50K": 50_000} + rows: list[dict[str, Any]] = [] + checkpoint_hashes: dict[str, str] = {} + for condition in registry["conditions"]: + condition_id = str(condition["condition"]) + if condition_id not in clip_counts: + continue + hashes = set() + for source in registry["sources"]: + source_id = str(source["id"]) + report = load_evaluation( + evaluation_root / condition_id / "final505k" / source_id + / "evaluation.json" + ) + if report["cache_manifest"]["sha256"] != source["cache_manifest_sha256"]: + raise ValueError(f"manifest hash mismatch: {condition_id}/{source_id}") + hashes.add(str(report["checkpoint"]["sha256"])) + rows.append(result_row( + condition_id, clip_counts[condition_id], source_id, report, + )) + if len(hashes) != 1: + raise ValueError(f"condition uses multiple checkpoints: {condition_id}") + checkpoint_hashes[condition_id] = hashes.pop() + + control_id = "J40_HOT100K" + hashes = set() + for source in registry["sources"]: + source_id = str(source["id"]) + report = load_evaluation(control_root / source_id / "evaluation.json") + if report["cache_manifest"]["sha256"] != source["cache_manifest_sha256"]: + raise ValueError(f"control manifest hash mismatch: {source_id}") + hashes.add(str(report["checkpoint"]["sha256"])) + rows.append(result_row(control_id, 100_000, source_id, report)) + if len(hashes) != 1: + raise ValueError("HOT100K control uses multiple checkpoints") + checkpoint_hashes[control_id] = hashes.pop() + + controls = { + row["source_id"]: row for row in rows if row["condition"] == control_id + } + for row in rows: + control = controls[row["source_id"]] + row["delta_vs_hot100k"] = { + metric: ( + None if value is None or control["metrics"][metric] is None + else value - control["metrics"][metric] + ) + for metric, value in row["metrics"].items() + } + paired: dict[str, dict[str, dict[str, Any]]] = {} + for condition_id in clip_counts: + paired[condition_id] = {} + for source in registry["sources"]: + source_id = str(source["id"]) + candidate_dir = evaluation_root / condition_id / "final505k" / source_id + reference_dir = control_root / source_id + paired[condition_id][source_id] = { + metric: paired_take_bootstrap( + reference_dir / "take_metrics.csv", + candidate_dir / "take_metrics.csv", + metric, seed=20260717, resamples=2000, + ) + for metric in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + paired[condition_id][source_id]["translation_z_p95_mm"] = ( + paired_take_bootstrap( + reference_dir / "per_hand_frame_metrics.csv", + candidate_dir / "per_hand_frame_metrics.csv", + "translation_z_mae_mm", seed=20260717, resamples=2000, + statistic="p95", + ) + ) + return { + "schema_version": "phase9_hot_unique_scale_summary_v1", + "status": "complete", + "comparison": "matched_J40_final505k_source_exposure", + "checkpoint_sha256": checkpoint_hashes, + "rows": rows, + "paired_recording_bootstrap_vs_hot100k": paired, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--control-root", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("summary outputs must be new") + result = summarize( + json.loads(args.registry.read_text(encoding="utf-8")), + args.evaluation_root, args.control_root, + ) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + fields = [ + "condition", "hot_unique_clips", "source_id", "checkpoint_sha256", + *METRICS, "aria_absolute_mpjpe_mm", "quest3_absolute_mpjpe_mm", + *[f"delta_{metric}" for metric in METRICS], + ] + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for row in result["rows"]: + writer.writerow({ + "condition": row["condition"], + "hot_unique_clips": row["hot_unique_clips"], + "source_id": row["source_id"], + "checkpoint_sha256": row["checkpoint"]["sha256"], + **row["metrics"], + **{ + f"delta_{metric}": row["delta_vs_hot100k"][metric] + for metric in METRICS + }, + }) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_last2_decision.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_last2_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..0c773ab0e98bd5e250e22c0e2fbd1ae392be8b95 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_last2_decision.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Apply the strict macro-and-worst gate to one last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.summarize_phase9_resolution_decision import ( + NATIVE_EXTERNAL, + checked_report, + h2o_guardrails, + metric, +) + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def strict_gate( + control_domains: dict[str, float], candidate_domains: dict[str, float], +) -> dict[str, Any]: + if set(control_domains) != {"h2o", "hot3d", "hoi4d", "arctic"}: + raise ValueError("last-2 control domains differ") + if set(candidate_domains) != set(control_domains): + raise ValueError("last-2 candidate domains differ") + control_macro = sum(control_domains.values()) / 4 + candidate_macro = sum(candidate_domains.values()) / 4 + control_worst = max(control_domains.values()) + candidate_worst = max(candidate_domains.values()) + macro = candidate_macro < control_macro + worst = candidate_worst < control_worst + return { + "control_macro_absolute_mm": control_macro, + "candidate_macro_absolute_mm": candidate_macro, + "macro_delta_mm": candidate_macro - control_macro, + "macro_strictly_improved": macro, + "control_worst_domain_absolute_mm": control_worst, + "candidate_worst_domain_absolute_mm": candidate_worst, + "worst_domain_delta_mm": candidate_worst - control_worst, + "worst_domain_strictly_improved": worst, + "accepted": macro and worst, + } + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if len(evaluations) != 25: + raise ValueError("last-2 evaluation count differs") + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"last-2 evaluation incomplete: {item['id']}") + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + control_reports = {} + for identifier, item in plan["control_reports"].items(): + path = Path(item["path"]) + if not path.is_file() or item["sha256"] != sha256(path): + raise ValueError(f"last-2 control report hash differs: {identifier}") + control_reports[identifier] = checked_report( + path, item["evaluation_role"], item["input_mode"], + ) + control_external = { + dataset: control_reports[f"full_{dataset}_{mode}"] + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = { + (fold, mode): control_reports[f"{fold}_{mode}"] + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + gate = strict_gate(control_domains, candidate_domains) + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + candidate = plan["candidate"] + return { + "schema_version": "phase9_last2_candidate_decision_v1", + "status": "complete", "candidate": candidate, + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": ( + f"accept_last2_{candidate}" if gate["accepted"] + else f"reject_last2_{candidate}" + ), + "backbone_learning_rate": plan["backbone_learning_rate"], + "resolution_hw": plan["resolution_hw"], + "shared_augmentation": plan["shared_augmentation"], + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "control_evaluation_plan": plan["control_evaluation_plan"], + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "dino_large_admitted": False, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("last-2 candidate decision output must be new") + result = summarize(args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_resolution_decision.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_resolution_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..0341ee8e004ae8b5d4fc699ded58fb19dfec1eab --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_resolution_decision.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Apply the frozen Stage 7 resolution gate and report all guardrails.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +FOLDS = ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", +) +NATIVE_EXTERNAL = { + "hot3d": "rgb_k", "hoi4d": "rgb_d_k", "arctic": "rgb_k", +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def checked_report(path: Path, role: str, mode: str) -> dict[str, Any]: + report = read_json(path) + if ( + report.get("status") != f"evaluated_{role}" + or report.get("evaluation_role") != role + or report.get("input_mode") != mode + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution decision input differs: {path}") + return report + + +def metric(report: dict[str, Any], name: str, statistic: str = "mean") -> float: + value = report.get("metrics", {}).get(name, {}).get(statistic) + if value is None or not math.isfinite(float(value)): + raise ValueError(f"missing finite metric {name}.{statistic}") + return float(value) + + +def h2o_guardrails(reports: dict[tuple[str, str], dict[str, Any]]) -> dict[str, Any]: + result = {} + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + selected = [reports[(fold, mode)] for fold in FOLDS] + absolute = [metric(report, "absolute_mpjpe_mm") for report in selected] + root = [metric(report, "root_relative_mpjpe_mm") for report in selected] + fingertip = [metric(report, "fingertip_mpjpe_mm") for report in selected] + z_tail = [ + metric(report, "translation_z_mae_mm", "p95") for report in selected + ] + result[mode] = { + "absolute_macro_mm": sum(absolute) / len(absolute), + "absolute_worst_fold_mm": max(absolute), + "root_relative_macro_mm": sum(root) / len(root), + "fingertip_macro_mm": sum(fingertip) / len(fingertip), + "translation_z_p95_macro_mm": sum(z_tail) / len(z_tail), + "translation_z_p95_worst_fold_mm": max(z_tail), + "fold_absolute_mm": dict(zip(FOLDS, absolute, strict=True)), + } + return result + + +def gate_decision( + control_domains: dict[str, float], candidate_domains: dict[str, float], + relative_limit: float, +) -> dict[str, Any]: + if set(control_domains) != {"h2o", "hot3d", "hoi4d", "arctic"}: + raise ValueError("resolution control domains differ") + if set(candidate_domains) != set(control_domains): + raise ValueError("resolution candidate domains differ") + control_macro = sum(control_domains.values()) / 4 + candidate_macro = sum(candidate_domains.values()) / 4 + control_worst = max(control_domains.values()) + candidate_worst = max(candidate_domains.values()) + worst_relative_regression = (candidate_worst - control_worst) / control_worst + macro_improved = candidate_macro < control_macro + worst_passed = worst_relative_regression <= relative_limit + return { + "control_macro_absolute_mm": control_macro, + "candidate_macro_absolute_mm": candidate_macro, + "macro_delta_mm": candidate_macro - control_macro, + "macro_strictly_improved": macro_improved, + "control_worst_domain_absolute_mm": control_worst, + "candidate_worst_domain_absolute_mm": candidate_worst, + "worst_domain_relative_regression": worst_relative_regression, + "worst_domain_relative_regression_limit": relative_limit, + "worst_domain_gate_passed": worst_passed, + "accepted": macro_improved and worst_passed, + } + + +def summarize( + plan_path: Path, control_external_root: Path, + control_fold_final_root: Path, control_fold_milestone_root: Path, +) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"resolution evaluation is incomplete: {item['id']}") + + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + + control = plan["control_evidence"] + mixture = control["mixture"] + external_id = control["external_checkpoint_id"] + fold_id = control["fold_checkpoint_id"] + control_external = { + dataset: checked_report( + control_external_root / mixture / external_id + / f"{dataset}_{mode}" / "evaluation.json", + "phase9_external_heldout", mode, + ) + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = {} + for fold in FOLDS: + condition = f"{mixture}_{fold}" + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + path = ( + control_fold_final_root / condition / mode / "evaluation.json" + if fold_id == "final" + else control_fold_milestone_root / condition / fold_id + / mode / "evaluation.json" + ) + control_h2o_reports[(fold, mode)] = checked_report( + path, "phase9_h2o_fold_heldout", mode, + ) + + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + for dataset, expected in control["absolute_mm"].items(): + if not math.isclose(control_domains[dataset], float(expected), abs_tol=1e-8): + raise ValueError(f"resolution control evidence differs: {dataset}") + gate = gate_decision( + control_domains, candidate_domains, + float(plan["gate"]["worst_domain_relative_regression_limit"]), + ) + + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + return { + "schema_version": "phase9_resolution_decision_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "accept_896x512" if gate["accepted"] else "retain_640x368", + "accepted_resolution_hw": [512, 896] if gate["accepted"] else [368, 640], + "control_resolution_hw": [368, 640], + "candidate_resolution_hw": [512, 896], + "winner": plan["winner"], + "control_checkpoint": plan["winner_checkpoint"], + "candidate_full_checkpoint": { + "path": plan["training_jobs"]["full"]["checkpoint"], + "sha256": plan["training_jobs"]["full"]["checkpoint_sha256"], + }, + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--control-external-root", type=Path, required=True) + parser.add_argument("--control-fold-final-root", type=Path, required=True) + parser.add_argument("--control-fold-milestone-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("resolution decision output must be new") + result = summarize( + args.plan, args.control_external_root, args.control_fold_final_root, + args.control_fold_milestone_root, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_resolution_evaluation_metrics.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_resolution_evaluation_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc33c1d7f19286e4dc4a9a36f79f012afae244c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_resolution_evaluation_metrics.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +"""Write the complete paired 640/896 Stage 7 metric inventory.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +FIELDS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "pa_mpjpe_mm": ("pa_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_x_mae_mm": ("translation_x_mae_mm", "mean"), + "translation_y_mae_mm": ("translation_y_mae_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def metric_values(report: dict[str, Any]) -> dict[str, float]: + result = {} + for label, (metric, statistic) in FIELDS.items(): + value = report.get("metrics", {}).get(metric, {}).get(statistic) + if not isinstance(value, (int, float)) or not math.isfinite(float(value)): + raise ValueError(f"resolution metric is missing or nonfinite: {label}") + result[label] = float(value) + return result + + +def control_path(plan: dict[str, Any], item: dict[str, Any], identifier: str) -> Path: + control = plan["control_evidence"] + mixture = control["mixture"] + if identifier.startswith("full_"): + name = identifier.removeprefix("full_") + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/external_milestones") + / mixture / control["external_checkpoint_id"] / name / "evaluation.json" + ) + fold = item["training_role"] + mode = item["input_mode"] + condition = f"{mixture}_{fold}" + if control["fold_checkpoint_id"] == "final": + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold") + / condition / mode / "evaluation.json" + ) + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold_milestones") + / condition / control["fold_checkpoint_id"] / mode / "evaluation.json" + ) + + +def checked_report(path: Path, item: dict[str, Any]) -> dict[str, Any]: + report = read_json(path) + if ( + report.get("status") != f"evaluated_{item['evaluation_role']}" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution paired report binding differs: {path}") + return report + + +def hot_headsets(report: dict[str, Any]) -> dict[str, Any]: + result = {} + for headset in ("aria", "quest3"): + metrics = report.get("metrics", {}).get(f"bucket_headset_{headset}", {}) + result[headset] = { + key: float(metrics[source][statistic]) + for key, (source, statistic) in FIELDS.items() + if source in metrics and statistic in metrics[source] + } + return result + + +def summarize(plan_path: Path, decision_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + decision = read_json(decision_path) + if ( + decision.get("status") != "complete" + or decision.get("evaluation_plan", {}).get("sha256") != sha256(plan_path) + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution decision binding differs") + owners = { + identifier: worker["owner"] + for worker in plan["workers"] for identifier in worker["evaluation_ids"] + } + rows = [] + for item in plan["evaluations"]: + if not evaluation_complete(item): + raise ValueError(f"resolution evaluation is incomplete: {item['id']}") + candidate_path = Path(item["output_dir"]) / "evaluation.json" + candidate = checked_report(candidate_path, item) + baseline_path = control_path(plan, item, item["id"]) + baseline = checked_report(baseline_path, item) + candidate_metrics = metric_values(candidate) + baseline_metrics = metric_values(baseline) + row = { + "evaluation_id": item["id"], "owner": owners[item["id"]], + "training_role": item["training_role"], "input_mode": item["input_mode"], + "evaluation_role": item["evaluation_role"], + "checkpoint_sha256": item["checkpoint_sha256"], + "config_sha256": item["config_sha256"], + "cache_manifest_sha256": item["cache_manifest_sha256"], + "clips": candidate["clips"], "frames": candidate["frames"], + "wall_seconds": candidate["runtime"]["wall_seconds"], + "gpu_hours": candidate["runtime"]["wall_seconds"] / 3600.0, + "candidate_report_sha256": sha256(candidate_path), + "control_report_sha256": sha256(baseline_path), + "candidate": candidate_metrics, "control": baseline_metrics, + "delta": { + key: candidate_metrics[key] - baseline_metrics[key] + for key in FIELDS + }, + "candidate_grouped_recording_ci": candidate["grouped_bootstrap_ci"], + "control_grouped_recording_ci": baseline["grouped_bootstrap_ci"], + } + if item["id"].startswith("full_hot3d_"): + row["hot3d_headset"] = { + "candidate": hot_headsets(candidate), "control": hot_headsets(baseline), + } + rows.append(row) + return { + "schema_version": "phase9_resolution_evaluation_metrics_v1", + "status": "complete", "created_utc": datetime.now(timezone.utc).isoformat(), + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "decision_report": {"path": str(decision_path.resolve()), "sha256": sha256(decision_path)}, + "evaluation_count": len(rows), "paired_control_count": len(rows), + "paired_by_evaluation_id_and_identical_heldout_contract": True, + "candidate_evaluation_gpu_hours": sum(row["gpu_hours"] for row in rows), + "candidate_training_gpu_hours": decision["candidate_training_gpu_hours"], + "control_domain_absolute_mm": decision["control_domain_absolute_mm"], + "candidate_domain_absolute_mm": decision["candidate_domain_absolute_mm"], + "gate": decision["gate"], "h2o_guardrails": decision["h2o_guardrails"], + "rows": rows, + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def write_csv(path: Path, report: dict[str, Any]) -> None: + fieldnames = [ + "evaluation_id", "owner", "training_role", "input_mode", "clips", "frames", + "wall_seconds", "gpu_hours", "checkpoint_sha256", "config_sha256", + "cache_manifest_sha256", "candidate_report_sha256", "control_report_sha256", + ] + [f"{prefix}_{field}" for prefix in ("candidate", "control", "delta") for field in FIELDS] + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + for source in report["rows"]: + row = {key: source[key] for key in fieldnames if key in source} + for prefix in ("candidate", "control", "delta"): + for field in FIELDS: + row[f"{prefix}_{field}"] = source[prefix][field] + writer.writerow(row) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--decision", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("resolution metric outputs must be new") + result = summarize(args.plan, args.decision) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output_json, result) + write_csv(args.output_csv, result) + print(json.dumps({ + "status": "complete", "json_sha256": sha256(args.output_json), + "csv_sha256": sha256(args.output_csv), "evaluation_count": 25, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_shared_augmentation_decision.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_shared_augmentation_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..161b1cb515462f41add17769350833b0a3a9cc3c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_shared_augmentation_decision.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Apply Stage 8 gate and freeze whether Stage 9 has a valid predecessor.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.summarize_phase9_resolution_decision import ( + NATIVE_EXTERNAL, + checked_report, + gate_decision, + h2o_guardrails, + metric, +) + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def stage9_preceding_gate( + augmentation_accepted: bool, augmentation_gate: dict[str, Any], + resolution_decision: dict[str, Any], +) -> dict[str, Any]: + augmentation_worst_improved = ( + augmentation_gate["candidate_worst_domain_absolute_mm"] + < augmentation_gate["control_worst_domain_absolute_mm"] + ) + if augmentation_accepted: + source = "shared_augmentation" + passed = ( + augmentation_gate["macro_strictly_improved"] + and augmentation_worst_improved + ) + else: + source = "resolution" + resolution_gate = resolution_decision["gate"] + passed = ( + resolution_decision["decision"] == "accept_896x512" + and resolution_gate["macro_strictly_improved"] + and resolution_gate["candidate_worst_domain_absolute_mm"] + < resolution_gate["control_worst_domain_absolute_mm"] + ) + return { + "source_mechanism": source, + "macro_and_worst_domain_strictly_improved": passed, + "stage9_last2_admitted": passed, + } + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if len(evaluations) != 25: + raise ValueError("shared augmentation evaluation count differs") + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"augmentation evaluation incomplete: {item['id']}") + + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + control_reports = {} + for identifier, item in plan["control_reports"].items(): + path = Path(item["path"]) + if not path.is_file() or item["sha256"] != sha256(path): + raise ValueError(f"augmentation control report hash differs: {identifier}") + control_reports[identifier] = checked_report( + path, item["evaluation_role"], item["input_mode"], + ) + control_external = { + dataset: control_reports[f"full_{dataset}_{mode}"] + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = { + (fold, mode): control_reports[f"{fold}_{mode}"] + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + resolution_path = Path(plan["resolution_decision"]["path"]) + if ( + not resolution_path.is_file() + or plan["resolution_decision"]["sha256"] != sha256(resolution_path) + ): + raise ValueError("augmentation resolution decision binding differs") + resolution = read_json(resolution_path) + expected_control_domains = ( + resolution["candidate_domain_absolute_mm"] + if resolution["decision"] == "accept_896x512" + else resolution["control_domain_absolute_mm"] + ) + for dataset, expected in expected_control_domains.items(): + if not math.isclose(control_domains[dataset], float(expected), abs_tol=1e-8): + raise ValueError(f"augmentation selected control differs: {dataset}") + gate = gate_decision( + control_domains, candidate_domains, + float(plan["gate"]["worst_domain_relative_regression_limit"]), + ) + preceding = stage9_preceding_gate(gate["accepted"], gate, resolution) + + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + accepted = bool(gate["accepted"]) + return { + "schema_version": "phase9_shared_augmentation_decision_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "accept_shared_augmentation" if accepted else "reject_shared_augmentation", + "shared_augmentation_accepted": accepted, + "selected_mechanism": "shared_augmentation" if accepted else "control", + "resolution_hw": plan["resolution_hw"], + "winner": plan["winner"], + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "stage9_preceding_mechanism_gate": preceding, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "control": plan["control"], + "resolution_decision": plan["resolution_decision"], + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("shared augmentation decision output must be new") + result = summarize(args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_unified_selection.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_unified_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..829747f7fdc5bbde018e1e0026d893dd7ea8fc8c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_phase9_unified_selection.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Select a Phase 9 unified candidate with dataset-equal group-CV evidence.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +CANDIDATES = { + "J25": [ + ("all20", "all_sources_20k"), + ("all50", "all_sources_50k"), + ("all100", "all_sources_100k"), + ("final405k", "final"), + ], + "J40": [ + ("nonhot20", "nonhot_20k"), + ("nonhot50_hot100", "nonhot_50k_hot_100k"), + ("nonhot100_hot200", "nonhot_100k_hot_200k"), + ("final505k", "final"), + ], + "J55": [ + ("nonhot20", "nonhot_20k"), + ("nonhot50", "nonhot_50k"), + ("nonhot100_hot367", "nonhot_100k_hot_367k"), + ("final675k", "final"), + ], +} +NATIVE_EXTERNAL = { + "hot3d": "hot3d_rgb_k", + "hoi4d": "hoi4d_rgb_d_k", + "arctic": "arctic_rgb_k", +} +METRICS = { + "absolute": "absolute_mpjpe_mm", + "root_relative": "root_relative_mpjpe_mm", + "fingertip": "fingertip_mpjpe_mm", +} + + +def evaluation(path: Path, expected_role: str) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(path) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("evaluation_role") != expected_role + or report.get("status") != f"evaluated_{expected_role}" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"evaluation role/isolation mismatch: {path}") + return report + + +def validate_multifold_index(index: dict[str, Any]) -> list[dict[str, Any]]: + expected_folds = { + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + } + folds = index.get("folds", []) + ids = [fold.get("id") for fold in folds] + if ( + index.get("status") != "complete" + or index.get("h2o_official_validation_used") is not False + or index.get("official_test_used") is not False + or index.get("selection_metrics") + != ["fold_macro_absolute_mpjpe", "worst_fold_absolute_mpjpe"] + or len(ids) != 6 + or set(ids) != expected_folds + or any( + not fold.get("heldout", {}).get("sha256") + or not fold.get("heldout", {}).get("path") + for fold in folds + ) + ): + raise ValueError("multifold index selection/isolation contract differs") + return folds + + +def mean_metric(report: dict[str, Any], metric: str) -> float: + value = report["metrics"][metric] + if value is None or not math.isfinite(float(value["mean"])): + raise ValueError(f"missing finite metric: {metric}") + return float(value["mean"]) + + +def rank_values(values: dict[str, float]) -> dict[str, float]: + ordered = sorted(values.items(), key=lambda item: (item[1], item[0])) + ranks: dict[str, float] = {} + position = 0 + while position < len(ordered): + end = position + 1 + while end < len(ordered) and ordered[end][1] == ordered[position][1]: + end += 1 + rank = (position + 1 + end) / 2.0 + for key, _ in ordered[position:end]: + ranks[key] = rank + position = end + return ranks + + +def pareto_frontier(rows: list[dict[str, Any]], datasets: tuple[str, ...]) -> set[str]: + frontier = set() + for row in rows: + dominated = any( + other["id"] != row["id"] + and all(other["absolute_mm"][dataset] <= row["absolute_mm"][dataset] for dataset in datasets) + and any(other["absolute_mm"][dataset] < row["absolute_mm"][dataset] for dataset in datasets) + for other in rows + ) + if not dominated: + frontier.add(row["id"]) + return frontier + + +def summarize( + external_root: Path, fold_final_root: Path, fold_milestone_root: Path, + folds: list[dict[str, Any]], +) -> dict[str, Any]: + rows: list[dict[str, Any]] = [] + for mixture, candidates in CANDIDATES.items(): + for external_id, fold_id in candidates: + candidate_id = f"{mixture}:{external_id}" + external_reports = { + dataset: evaluation( + external_root / mixture / external_id / source_id / "evaluation.json", + "phase9_external_heldout", + ) + for dataset, source_id in NATIVE_EXTERNAL.items() + } + if ( + len({json.dumps(report["checkpoint"], sort_keys=True) for report in external_reports.values()}) != 1 + or len({json.dumps(report["config"], sort_keys=True) for report in external_reports.values()}) != 1 + ): + raise ValueError(f"external checkpoint/config binding differs: {candidate_id}") + fold_reports = [] + for fold_record in folds: + fold = fold_record["id"] + condition = f"{mixture}_{fold}" + root = fold_final_root if fold_id == "final" else fold_milestone_root / condition / fold_id + path = ( + root / condition / "rgb_d_k" / "evaluation.json" + if fold_id == "final" + else root / "rgb_d_k" / "evaluation.json" + ) + report = evaluation(path, "phase9_h2o_fold_heldout") + if ( + report.get("input_mode") != "rgb_d_k" + or report.get("cache_manifest", {}).get("path") + != fold_record["heldout"]["path"] + or report.get("cache_manifest", {}).get("sha256") + != fold_record["heldout"]["sha256"] + ): + raise ValueError(f"fold heldout binding differs: {condition}") + fold_reports.append(report) + h2o_absolute = [mean_metric(report, METRICS["absolute"]) for report in fold_reports] + row = { + "id": candidate_id, "mixture": mixture, + "external_checkpoint_id": external_id, + "fold_checkpoint_id": fold_id, + "checkpoint": external_reports["hot3d"]["checkpoint"], + "config": external_reports["hot3d"]["config"], + "absolute_mm": { + "h2o": sum(h2o_absolute) / len(h2o_absolute), + **{ + dataset: mean_metric(report, METRICS["absolute"]) + for dataset, report in external_reports.items() + }, + }, + "h2o_worst_fold_absolute_mm": max(h2o_absolute), + "h2o_fold_absolute_mm": dict(zip( + [fold["id"] for fold in folds], h2o_absolute, strict=True, + )), + "h2o_fold_macro_root_relative_mm": sum( + mean_metric(report, METRICS["root_relative"]) for report in fold_reports + ) / len(fold_reports), + "h2o_fold_macro_fingertip_mm": sum( + mean_metric(report, METRICS["fingertip"]) for report in fold_reports + ) / len(fold_reports), + } + rows.append(row) + datasets = ("h2o", "hot3d", "hoi4d", "arctic") + for dataset in datasets: + ranks = rank_values({row["id"]: row["absolute_mm"][dataset] for row in rows}) + best = min(row["absolute_mm"][dataset] for row in rows) + for row in rows: + row.setdefault("dataset_rank", {})[dataset] = ranks[row["id"]] + row.setdefault("normalized_regression_from_best", {})[dataset] = ( + row["absolute_mm"][dataset] - best + ) / best + frontier = pareto_frontier(rows, datasets) + for row in rows: + row["dataset_equal_mean_rank"] = sum(row["dataset_rank"].values()) / len(datasets) + row["worst_dataset_normalized_regression"] = max( + row["normalized_regression_from_best"].values() + ) + row["pareto_frontier"] = row["id"] in frontier + ordered = sorted(rows, key=lambda row: ( + row["dataset_equal_mean_rank"], + row["worst_dataset_normalized_regression"], + sum(row["absolute_mm"].values()), + row["id"], + )) + return { + "schema_version": "phase9_unified_selection_v1", + "status": "complete", + "selection_rule": "dataset_equal_mean_rank_then_worst_normalized_regression_then_sum", + "normalization": "candidate_minus_per_dataset_best divided by per_dataset_best", + "winner": ordered[0]["id"], + "winner_checkpoint": ordered[0]["checkpoint"], + "winner_config": ordered[0]["config"], + "pareto_frontier": sorted(frontier), + "candidates": ordered, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-root", type=Path, required=True) + parser.add_argument("--fold-final-root", type=Path, required=True) + parser.add_argument("--fold-milestone-root", type=Path, required=True) + parser.add_argument("--multifold-index", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("selection outputs must be new") + index = json.loads(args.multifold_index.read_text(encoding="utf-8")) + result = summarize( + args.external_root, args.fold_final_root, args.fold_milestone_root, + validate_multifold_index(index), + ) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + csv_temporary = args.output_csv.with_suffix(args.output_csv.suffix + ".tmp") + json_temporary = args.output_json.with_suffix(args.output_json.suffix + ".tmp") + with csv_temporary.open("x", newline="", encoding="utf-8") as handle: + fields = [ + "id", "mixture", "external_checkpoint_id", "fold_checkpoint_id", + "h2o_absolute_mm", "hot3d_absolute_mm", "hoi4d_absolute_mm", + "arctic_absolute_mm", "h2o_worst_fold_absolute_mm", + "dataset_equal_mean_rank", "worst_dataset_normalized_regression", + "pareto_frontier", + ] + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for row in result["candidates"]: + writer.writerow({ + **{key: row[key] for key in fields if key in row}, + **{f"{dataset}_absolute_mm": row["absolute_mm"][dataset] for dataset in ("h2o", "hot3d", "hoi4d", "arctic")}, + }) + json_temporary.write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + csv_temporary.replace(args.output_csv) + json_temporary.replace(args.output_json) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_pilots.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_pilots.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3328105d986f49810eb62ccfe40cd8a9d5dd0e --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_pilots.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Create reproducible comparison tables and curves from completed pilots.""" + +from __future__ import annotations + +import argparse +import csv +import json +from datetime import datetime +from pathlib import Path + +import matplotlib.pyplot as plt + + +EXPERIMENTS_30MIN = { + "B Sequential RGB": "b_sequential_v1", + "C Alternating RGB": "c_alternating_v1", + "D Alternating RGB+K": "d_rgb_k_v1", + "E Alternating RGB+Depth": "e_rgb_depth_fixed_v1", + "F Alternating RGB+Depth+K": "f_rgb_depth_k_fixed_v1", +} + +EXPERIMENTS_2H = { + "C Alternating RGB": { + "result": "c_alternating_v3_resume_step50", + "segments": ["c_alternating_v1", "c_alternating_v2_resume_step25", "c_alternating_v3_resume_step50"], + }, + "D Alternating RGB+K": {"result": "d_rgb_k_v1", "segments": ["d_rgb_k_v1"]}, + "F Alternating RGB+Depth+K": {"result": "f_rgb_depth_k_fixed_v1", "segments": ["f_rgb_depth_k_fixed_v1"]}, +} + + +def load_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--pilot-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--suite", choices=("30min", "2h"), default="30min") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + rows = [] + bucket_rows = [] + curves = {} + if args.suite == "30min": + experiments = { + label: {"result": directory, "segments": [directory]} + for label, directory in EXPERIMENTS_30MIN.items() + } + else: + experiments = EXPERIMENTS_2H + for label, experiment in experiments.items(): + directory = experiment["result"] + root = args.pilot_root / directory + summary = load_json(root / "summary.json") + evaluation = load_json(root / "full_validation_best" / "evaluation.json") + validation = [] + training_records = [] + for segment in experiment["segments"]: + segment_root = args.pilot_root / segment + if (segment_root / "validation.jsonl").is_file(): + validation.extend(json.loads(line) for line in (segment_root / "validation.jsonl").read_text().splitlines()) + if (segment_root / "metrics.jsonl").is_file(): + training_records.extend(json.loads(line) for line in (segment_root / "metrics.jsonl").read_text().splitlines()) + validation.sort(key=lambda item: item["step"]) + training_records.sort(key=lambda item: item["step"]) + best_record = min(validation, key=lambda item: item["metrics"]["absolute_camera_mpjpe_mm"]) + metrics = evaluation["metrics"] + first_timestamp = datetime.fromisoformat(training_records[0]["timestamp"]) + last_timestamp = datetime.fromisoformat(training_records[-1]["timestamp"]) + wall_minutes = (last_timestamp - first_timestamp).total_seconds() / 60 + rows.append({ + "experiment": label, + "best_step": best_record["step"], + "trained_steps": summary["completed_step"], + "elapsed_minutes": wall_minutes, + "peak_vram_gib": summary["peak_vram_gib"], + "frames_per_s": summary["frames_per_s"], + "subset_best_absolute_mpjpe_mm": best_record["metrics"]["absolute_camera_mpjpe_mm"], + "full_absolute_mpjpe_mm": metrics["all_absolute_mpjpe_mm"], + "full_root_relative_mpjpe_mm": metrics["all_root_relative_mpjpe_mm"], + "full_joint2d_error_px": metrics["all_joint2d_error_px"], + "z_mae_mm": (metrics["left_translation_z_mae_mm"] + metrics["right_translation_z_mae_mm"]) / 2, + "velocity_error_mm_per_frame": metrics["temporal_velocity_error_mm_per_frame"], + "acceleration_error_mm_per_frame2": metrics["temporal_acceleration_error_mm_per_frame2"], + "rgb_attention_same_peak_fraction": metrics["rgb_attention_same_peak_fraction"], + "temporal_attention_entropy": metrics["temporal_attention_normalized_entropy"], + "depth_gate_mean": metrics["depth_gate_mean"], + "best_checkpoint": summary["best_checkpoint"], + }) + for bucket, values in evaluation["buckets"].items(): + bucket_rows.append({"experiment": label, "bucket": bucket, **values}) + curves[label] = validation + + with (args.output_dir / "comparison.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + with (args.output_dir / "bucket_comparison.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(bucket_rows[0])) + writer.writeheader() + writer.writerows(bucket_rows) + (args.output_dir / "comparison.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8") + + fig, axes = plt.subplots(1, 3, figsize=(16, 4.5)) + metric_names = ( + ("absolute_camera_mpjpe_mm", "Absolute MPJPE (mm)"), + ("root_relative_mpjpe_mm", "Root-relative MPJPE (mm)"), + ("translation_z_mae_mm", "Translation z MAE (mm)"), + ) + for label, records in curves.items(): + steps = [record["step"] for record in records] + for axis, (metric, title) in zip(axes, metric_names, strict=True): + axis.plot(steps, [record["metrics"][metric] for record in records], label=label) + axis.set_title(title) + axis.set_xlabel("step") + axis.grid(alpha=0.25) + axes[0].legend(fontsize=7) + fig.tight_layout() + fig.savefig(args.output_dir / "validation_curves.png", dpi=180) + plt.close(fig) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_sota_evaluation.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_sota_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..b46e9cca845bda5ca51a6087e12136c3f45da2b0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_sota_evaluation.py @@ -0,0 +1,813 @@ +#!/usr/bin/env python3 +"""Build the reproducible FoundationHand external-baseline comparison report.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +from foundation_hand.evaluation.sota import paired_take_bootstrap, write_csv_rows + + +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "joint_acceleration_error_mm_per_frame2", +) + +PROTOCOLS = { + "FoundationHand-Phase3": ( + "h2o_trained", + "H2O train;validation 子集选模", + ), + "QORT-Former": ("h2o_trained", "H2O train"), + "WiLoR-H2O-K": ("zero_shot", "无 H2O 微调;训练含 H2O3D"), + "HaWoR-camera": ("zero_shot", "发布权重无 H2O 微调"), + "WildHands-zero-shot": ( + "zero_shot", + "无 H2O;训练用 ARCTIC/AssemblyHands/EPIC", + ), + "Hamba-zero-shot": ( + "zero_shot", + "无 H2O;训练含 H2O3D", + ), + "PAD-Hand-WiLoR": ( + "zero_shot", + "无 H2O;论文训练用 DexYCB/HO3D,release checkpoint 未标具体版本", + ), + "HandDGP-zero-shot": ( + "zero_shot", + "无 H2O/H2O3D;发布权重仅用 FreiHAND 训练", + ), + "Dyn-HaMR-TTO": ( + "test_time_optimization", + "无 H2O;HaMeR initializer 含 H2O3D;每段视频独立 TTO", + ), + "WiLoR-native-camera": ("diagnostic", "同一 WiLoR 权重;原生 demo camera"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_rows(path: Path) -> list[dict[str, Any]]: + with path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + for row in rows: + for key, value in tuple(row.items()): + if value == "": + row[key] = None + return rows + + +def parameters(metadata: dict[str, Any]) -> tuple[int, int]: + if "end_to_end_parameter_count" in metadata: + return ( + int(metadata["reconstruction_parameter_count"]), + int(metadata["end_to_end_parameter_count"]), + ) + count = int(metadata["parameter_count"]) + return count, count + + +def metric_mean(report: dict[str, Any], metric: str) -> float | None: + summary = report["metrics_success_conditioned"].get(metric) + return None if summary is None else summary["mean"] + + +def temporal_mean(report: dict[str, Any], metric: str) -> float | None: + summary = report["temporal_metrics_success_conditioned"].get(metric) + return None if summary is None else summary["mean"] + + +def fmt(value: float | int | None, digits: int = 3) -> str: + if value is None: + return "N/A" + return f"{float(value):.{digits}f}" + + +def fmt_params(value: int) -> str: + return f"{value / 1_000_000:.1f}M" + + +def load_evaluation(label: str, directory: Path) -> dict[str, Any]: + report_path = directory / "evaluation.json" + frame_path = directory / "per_hand_frame_metrics.csv" + temporal_path = directory / "per_temporal_transition_metrics.csv" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("split_role") != "official_validation" + or report.get("official_test_used") is not False + ): + raise ValueError(f"Not a complete official-validation evaluation: {directory}") + model_parameters, end_to_end_parameters = parameters(report["prediction_metadata"]) + track, h2o_exposure = PROTOCOLS.get( + label, + ("uncategorized", report["prediction_metadata"].get("training_exposure", "Unknown")), + ) + row: dict[str, Any] = { + "label": label, + "model_name": report["model_name"], + "evaluation_track": track, + "h2o_exposure": h2o_exposure, + "input": report["prediction_metadata"].get("input"), + "temporal": report["prediction_metadata"].get("temporal"), + "model_parameter_count": model_parameters, + "end_to_end_parameter_count": end_to_end_parameters, + "frames": report["frames"], + "takes": report["takes"], + "annotation_valid_hand_frames": report["coverage"]["annotation_valid_hand_frames"], + "successful_hand_frames": report["coverage"]["successful_hand_frames"], + "coverage": report["coverage"]["hand_frame_fraction"], + "temporal_pair_coverage": report["coverage"]["temporal_pair_fraction"], + **{metric: metric_mean(report, metric) for metric in METRICS}, + **{metric: temporal_mean(report, metric) for metric in TEMPORAL_METRICS}, + **report["failure_aware"], + "evaluation_json": str(report_path.resolve()), + "evaluation_json_sha256": sha256(report_path), + "frame_metrics_csv": str(frame_path.resolve()), + "frame_metrics_csv_sha256": sha256(frame_path), + "temporal_metrics_csv": str(temporal_path.resolve()), + "temporal_metrics_csv_sha256": sha256(temporal_path), + } + for side in ("left", "right"): + row[f"{side}_coverage"] = report["per_side"][side]["coverage"] + row[f"{side}_absolute_mpjpe_mm"] = report["per_side"][side][ + "absolute_mpjpe_mm" + ]["mean"] + row[f"{side}_root_relative_mpjpe_mm"] = report["per_side"][side][ + "root_relative_mpjpe_mm" + ]["mean"] + return { + "label": label, + "directory": directory, + "report": report, + "frame_rows": read_rows(frame_path), + "summary": row, + } + + +def markdown_report( + evaluations: list[dict[str, Any]], + paired_rows: list[dict[str, Any]], + refinement_rows: list[dict[str, Any]], + dynhamr_hawor_rows: list[dict[str, Any]], + speed_report: dict[str, Any] | None, + *, + manifest: Path, + manifest_hash: str, + ground_truth: Path, + ground_truth_hash: str, + bootstrap_seed: int, + bootstrap_samples: int, +) -> str: + rows = [evaluation["summary"] for evaluation in evaluations] + foundation_evaluation = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "FoundationHand-Phase3" + ) + foundation_trainable = foundation_evaluation["report"]["prediction_metadata"].get( + "trainable_parameter_count_at_export" + ) + foundation_row = foundation_evaluation["summary"] + rows_by_label = {row["label"]: row for row in rows} + + comparative_note = "" + if "HaWoR-camera" in rows_by_label: + hawor_row = rows_by_label["HaWoR-camera"] + hawor_root = next( + row for row in paired_rows + if row["candidate"] == "HaWoR-camera" + and row["metric"] == "root_relative_mpjpe_mm" + ) + comparative_note = ( + "作为跨赛道描述性配对,FoundationHand 在 absolute joints/mesh、fingertip、z 和时间误差上更低;" + f"HaWoR 的逐帧 root-relative 均值虽低 " + f"{foundation_row['root_relative_mpjpe_mm'] - hawor_row['root_relative_mpjpe_mm']:.3f} mm," + f"但 take-equal paired delta 为 {hawor_root['candidate_minus_baseline']:+.3f} mm、" + f"95% CI [{hawor_root['ci95_low']:.3f}, {hawor_root['ci95_high']:.3f}]," + "只能判为等价,不能声称 HaWoR 显著更好。HaWoR 的 2D 优势有 paired CI 支持。" + ) + + qort_note = "" + if "QORT-Former" in rows_by_label: + qort_row = rows_by_label["QORT-Former"] + qort_note = ( + "具体到 QORT-Former:公开 checkpoint 在本 validation 上为 left/right " + f"{qort_row['left_absolute_mpjpe_mm']:.3f}/" + f"{qort_row['right_absolute_mpjpe_mm']:.3f} mm,没有达到论文 test 的 " + "20.1/19.9 mm 水平。它说明“公开权重在当前开发集未重现论文量级”," + "但 split 不同,所以不是论文数字错误的充分证据。" + ) + wildhands_note = "" + if "WildHands-zero-shot" in rows_by_label: + wildhands_row = rows_by_label["WildHands-zero-shot"] + wildhands_note = ( + "WildHands 发布权重在本协议的 root-relative MPJPE 为 " + f"{wildhands_row['root_relative_mpjpe_mm']:.3f} mm,与论文 H2O validation " + f"GT-box 结果 31.08 mm 相差 " + f"{wildhands_row['root_relative_mpjpe_mm'] - 31.08:.3f} mm," + "支持当前模型与关节适配的正确性。" + f"但 absolute MPJPE/z MAE 达 {wildhands_row['absolute_mpjpe_mm']:.3f}/" + f"{wildhands_row['translation_z_mae_mm']:.3f} mm,说明相对姿态接近论文量级不代表" + "绝对 camera-space 深度准确。" + ) + pad_note = "" + if "PAD-Hand-WiLoR" in rows_by_label and "WiLoR-H2O-K" in rows_by_label: + pad_row = rows_by_label["PAD-Hand-WiLoR"] + wilor_row = rows_by_label["WiLoR-H2O-K"] + pad_root = next( + row for row in refinement_rows + if row["metric"] == "root_relative_mpjpe_mm" + ) + pad_note = ( + "PAD-Hand 与 WiLoR 使用相同检测、初始化和 camera translation;其 16 帧扩散 refinement " + f"使 root-relative MPJPE 增加 " + f"{pad_row['root_relative_mpjpe_mm'] - wilor_row['root_relative_mpjpe_mm']:.3f} mm " + f"(take-equal paired delta {pad_root['candidate_minus_baseline']:+.3f} mm," + f"95% CI [{pad_root['ci95_low']:.3f}, {pad_root['ci95_high']:.3f}])," + f"但 joint velocity/acceleration error 从 " + f"{wilor_row['joint_velocity_error_mm_per_frame']:.3f}/" + f"{wilor_row['joint_acceleration_error_mm_per_frame2']:.3f} 降至 " + f"{pad_row['joint_velocity_error_mm_per_frame']:.3f}/" + f"{pad_row['joint_acceleration_error_mm_per_frame2']:.3f}。" + "因此它在 H2O 上是平滑性收益而非空间精度 SOTA。" + ) + dynhamr_note = "" + if "Dyn-HaMR-TTO" in rows_by_label: + dynhamr_row = rows_by_label["Dyn-HaMR-TTO"] + dynhamr_evaluation = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "Dyn-HaMR-TTO" + ) + dynhamr_metadata = dynhamr_evaluation["report"]["prediction_metadata"] + dynhamr_note = ( + "Dyn-HaMR 不是一次前向的重建网络:本表按每个 official-validation 连续 run " + "独立执行发布的 Root/Smooth test-time optimization,并使用已知静态 cam4 K。" + f"其 Coverage/absolute/root-relative MPJPE 为 {100 * dynhamr_row['coverage']:.2f}%/" + f"{dynhamr_row['absolute_mpjpe_mm']:.3f}/{dynhamr_row['root_relative_mpjpe_mm']:.3f} mm。" + f"94 个 run 共执行 {int(dynhamr_metadata['root_iterations_total']):,}/" + f"{int(dynhamr_metadata['smooth_iterations_total']):,} 次 Root/Smooth 外循环。" + "因此它属于高计算量 TTO 系统赛道,不能当作与 HaWoR/WiLoR 同成本的 feed-forward 模型。" + ) + if dynhamr_hawor_rows: + root_contrast = next( + row for row in dynhamr_hawor_rows + if row["metric"] == "root_relative_mpjpe_mm" + ) + dynhamr_note += ( + " 与 HaWoR 直接配对时,Dyn-HaMR 的 root-relative take-equal delta 为 " + f"{root_contrast['candidate_minus_baseline']:+.3f} mm,95% CI " + f"[{root_contrast['ci95_low']:.3f}, {root_contrast['ci95_high']:.3f}]," + "不能宣称任一方法显著更好。" + ) + h2o_trained = [row for row in rows if row["evaluation_track"] == "h2o_trained"] + zero_shot = [row for row in rows if row["evaluation_track"] == "zero_shot"] + test_time_optimization = [ + row for row in rows if row["evaluation_track"] == "test_time_optimization" + ] + diagnostics = [row for row in rows if row["evaluation_track"] == "diagnostic"] + uncategorized = [row for row in rows if row["evaluation_track"] == "uncategorized"] + h2o_absolute_winner = min( + (row for row in h2o_trained if row["absolute_mpjpe_mm"] is not None), + key=lambda row: row["absolute_mpjpe_mm"], + ) + h2o_root_winner = min( + (row for row in h2o_trained if row["root_relative_mpjpe_mm"] is not None), + key=lambda row: row["root_relative_mpjpe_mm"], + ) + zero_absolute_winner = min( + (row for row in zero_shot if row["absolute_mpjpe_mm"] is not None), + key=lambda row: row["absolute_mpjpe_mm"], + ) + zero_root_winner = min( + (row for row in zero_shot if row["root_relative_mpjpe_mm"] is not None), + key=lambda row: row["root_relative_mpjpe_mm"], + ) + zero_mesh_winner = min( + (row for row in zero_shot if row["absolute_mpvpe_mm"] is not None), + key=lambda row: row["absolute_mpvpe_mm"], + ) + zero_projected_winner = min( + (row for row in zero_shot if row["projected_2d_error_px"] is not None), + key=lambda row: row["projected_2d_error_px"], + ) + table_header = ( + "| 模型 | H2O 暴露 | 输入 | Params (模型/E2E) | Coverage | Abs MPJPE | " + "Root MPJPE | MPVPE | Root MPVPE | 2D | Fingertip | z MAE | PCK20 | AUC0-50 |" + ) + table_divider = ( + "|---|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|" + ) + speed_section: list[str] = [] + if speed_report is not None: + speed_by_label = { + row["setting_id"]: row for row in speed_report["rows"] + } + speed_section = [ + "", + "## 推理速度", + "", + ( + "同一 94 帧 H2O 连续片段、RTX 4090、包含 RGB 解码/预处理/所需 detector/" + "重建与 camera conversion 的本机实测中,批处理/时序摊销吞吐为:" + f"FoundationHand T8 {speed_by_label['FoundationHand-T8']['median_fps']:.2f} FPS," + f"QORT batch16 {speed_by_label['QORT-b16']['median_fps']:.2f} FPS," + f"WiLoR batch16 {speed_by_label['WiLoR-b16']['median_fps']:.2f} FPS," + f"HaWoR T16 {speed_by_label['HaWoR-T16']['median_fps']:.2f} FPS," + f"Dyn-HaMR TTO {speed_by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS。" + ), + "", + ( + "QORT/WiLoR 的 batch1 在线吞吐分别为 " + f"{speed_by_label['QORT-b1']['median_fps']:.2f}/" + f"{speed_by_label['WiLoR-b1']['median_fps']:.2f} FPS。" + "FoundationHand 的独立纯模型 profile 为 " + f"{speed_report['foundation_model_only_profile']['p50_ms_per_t8_clip']:.2f} ms/T8 clip," + f"即 {speed_report['foundation_model_only_profile']['amortized_frames_per_second']:.1f} frame/s;" + "完整数据路径为 T=8 RGB+Depth+K,因此二者不是同一计时口径。" + "HaWoR 与 Dyn-HaMR 是离线时序/TTO 方法,摊销 ms/frame 不是因果单帧延迟。" + "完整口径、重复范围与 Dyn-HaMR 开销拆分见 `INFERENCE_SPEED_REPORT.md`。" + ), + ] + + def result_line(row: dict[str, Any]) -> str: + return ( + f"| {row['label']} | {row['h2o_exposure']} | {row['input']} | " + f"{fmt_params(row['model_parameter_count'])}/{fmt_params(row['end_to_end_parameter_count'])} | " + f"{100 * row['coverage']:.2f}% | {fmt(row['absolute_mpjpe_mm'])} | " + f"{fmt(row['root_relative_mpjpe_mm'])} | {fmt(row['absolute_mpvpe_mm'])} | " + f"{fmt(row['root_relative_mpvpe_mm'])} | {fmt(row['projected_2d_error_px'])} | " + f"{fmt(row['fingertip_mpjpe_mm'])} | {fmt(row['translation_z_mae_mm'])} | " + f"{100 * row['absolute_pck_20mm']:.2f}% | {row['absolute_auc_0_50mm']:.4f} |" + ) + + lines = [ + "# FoundationHand 外部 SOTA 统一复评报告", + "", + "## 公平性结论", + "", + ( + "把 FoundationHand/QORT 与外部发布权重排成一个训练条件等价的 SOTA 总榜是不公平的。" + "前两者使用 H2O 训练,其余方法没有在 H2O 上微调;因此本报告改为域内训练与" + "零样本泛化两条前向赛道,并把逐视频优化方法单列为 TTO 赛道。" + "所有模型仍共享同一 validation、GT、坐标系和 evaluator。" + ), + "", + ( + f"H2O 域内训练赛道中,absolute/root-relative MPJPE 最低的分别是 " + f"**{h2o_absolute_winner['label']} ({fmt(h2o_absolute_winner['absolute_mpjpe_mm'])} mm)** " + f"和 **{h2o_root_winner['label']} ({fmt(h2o_root_winner['root_relative_mpjpe_mm'])} mm)**。" + "这仍是系统级比较:FoundationHand 使用 RGB+metric Depth+K、T=8,QORT 使用单帧 RGB。" + ), + "", + ( + f"H2O 零样本 RGB 赛道中,absolute/root-relative MPJPE 最低的分别是 " + f"**{zero_absolute_winner['label']} ({fmt(zero_absolute_winner['absolute_mpjpe_mm'])} mm)** " + f"和 **{zero_root_winner['label']} ({fmt(zero_root_winner['root_relative_mpjpe_mm'])} mm)**;" + f"absolute MPVPE 最低的是 **{zero_mesh_winner['label']} " + f"({fmt(zero_mesh_winner['absolute_mpvpe_mm'])} mm)**,投影 2D 最低的是 " + f"**{zero_projected_winner['label']} ({fmt(zero_projected_winner['projected_2d_error_px'])} px)**。" + ), + "", + comparative_note, + "", + ( + "这是一份同数据、同 GT、同坐标系、同评估器的开发集复评,不是可直接发表的官方-test " + "SOTA 声明。FoundationHand 的模型选择使用过该 validation split 的固定子集;各方法的输入模态和训练数据也不同。" + ), + "", + "## H2O 域内训练赛道", + "", + ( + "误差均为越低越好;Coverage、PCK、AUC 越高越好。MPJPE/MPVPE 是检测成功样本上的均值;" + "失败不会被静默删除,而是通过 Coverage 和 failure-aware PCK/AUC 计入。2D 误差按 Phase3 " + "约定缩放到 640x368 评估像素。" + ), + "", + table_header, + table_divider, + ] + lines.extend(result_line(row) for row in h2o_trained) + lines.extend([ + "", + "## H2O 零样本 RGB 赛道", + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in zero_shot) + if test_time_optimization: + lines.extend([ + "", + "## H2O 零样本 Test-Time Optimization 赛道", + "", + ( + "该表使用同一 H2O validation 和 evaluator,但方法在每段测试视频上优化模型变量," + "计算预算显著高于一次前向方法,因此不参与上方 zero-shot feed-forward winner 判定。" + ), + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in test_time_optimization) + if diagnostics or uncategorized: + lines.extend([ + "", + "## 诊断与未分类结果", + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in diagnostics + uncategorized) + lines.extend([ + "", + "### 左右手拆分", + "", + "| 模型 | Left coverage | Left Abs | Left Root | Right coverage | Right Abs | Right Root |", + "|---|---:|---:|---:|---:|---:|---:|", + ]) + for row in rows: + lines.append( + f"| {row['label']} | {100 * row['left_coverage']:.2f}% | " + f"{fmt(row['left_absolute_mpjpe_mm'])} | " + f"{fmt(row['left_root_relative_mpjpe_mm'])} | " + f"{100 * row['right_coverage']:.2f}% | " + f"{fmt(row['right_absolute_mpjpe_mm'])} | " + f"{fmt(row['right_root_relative_mpjpe_mm'])} |" + ) + lines.extend([ + "", + "WiLoR-H2O-K 使用已知 H2O 内参代入官方 `cam_crop_to_full` 代数,没有使用 GT pose 或拟合参数。" + "`WiLoR-native-camera` 保留发布 demo 的假设焦距,仅用于展示原样 camera translation 在 H2O 上的行为,不参与主结论。", + "", + ( + f"参数量由实际加载模块逐参数计数。FoundationHand 总参数 126.8M 中,export 时可训练参数为 " + f"{fmt_params(int(foundation_trainable)) if foundation_trainable is not None else 'N/A'}(DINO 冻结);" + "外部 RGB 方法的 E2E 数量包含实际使用的公开 detector。HaWoR 的 camera-space 表不加载与该任务无关的 " + "DROID-SLAM、Metric3D 和 world-space infiller。Dyn-HaMR 的参数数目是实际使用的 HaMeR initializer " + "与 detector;逐 run 优化变量随帧数变化,不计作网络参数。" + ), + "", + "QORT-Former 不输出 MANO mesh,因此 MPVPE 为 N/A。其 normalized `(u,v,z)` 反归一化和 K 反投影逐式复现了它所基于的官方 [H2OTR `pixel2cam`](https://github.com/chohoseong/H2OTR/blob/master/util/ops.py),不是用 GT pose 拟合得到的坐标。", + *speed_section, + "", + "## 时间指标", + "", + "| 模型 | Pair coverage | Wrist velocity | Joint velocity | Wrist acceleration | Joint acceleration |", + "|---|---:|---:|---:|---:|---:|", + ]) + for row in rows: + lines.append( + f"| {row['label']} | {100 * row['temporal_pair_coverage']:.2f}% | " + f"{fmt(row['wrist_velocity_error_mm_per_frame'])} | " + f"{fmt(row['joint_velocity_error_mm_per_frame'])} | " + f"{fmt(row['wrist_acceleration_error_mm_per_frame2'])} | " + f"{fmt(row['joint_acceleration_error_mm_per_frame2'])} |" + ) + lines.extend([ + "", + "时间差分只在同一连续 run、同一 Phase3 T=8 clip 内计算;检测失败的 pair 由 pair coverage 单独报告。", + "", + "### PAD-Hand refinement 诊断", + "", + pad_note, + "", + "### Dyn-HaMR TTO 诊断", + "", + dynhamr_note, + "", + "## 配对统计", + "", + ( + f"下表为候选模型减 FoundationHand 的 take-equal paired bootstrap;负值表示候选误差更低。" + f"每项只使用两模型都成功的精确交集,{bootstrap_samples:,} 次重采样,seed={bootstrap_seed}。" + ), + "", + "| 候选 | Metric | Paired hands | Takes | Delta | 95% CI |", + "|---|---|---:|---:|---:|---:|", + ]) + for row in paired_rows: + if row["metric"] not in ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", + ): + continue + lines.append( + f"| {row['candidate']} | {row['metric']} | {row['paired_hand_frames']} | " + f"{row['take_count']} | {fmt(row['candidate_minus_baseline'])} | " + f"[{fmt(row['ci95_low'])}, {fmt(row['ci95_high'])}] |" + ) + lines.extend([ + "", + "## 与论文原表的关系", + "", + "| 工作 | 论文报告 | 为什么不能与本表直接混排 |", + "|---|---|---|", + "| QORT-Former | H2O official test mean end-point error: left 20.1 mm, right 19.9 mm | 本报告是 official validation;论文未报告本 split 数字。指标形式接近,但 split 不同。 |", + "| WiLoR | FreiHAND PA-MPJPE/PA-MPVPE 5.5/5.1 mm;HO3D 7.5/7.7 mm | 数据集不同,且经过 Procrustes alignment;本表是 H2O 绝对 camera-space。 |", + "| HaWoR | DexYCB PA-MPJPE 4.76 mm、AUC 90.5 | 数据集不同,且 PA 对齐;本表只评 camera-space hand stage,不含 SLAM、Metric3D、world-space infiller。 |", + "| WildHands | H2O validation zero-shot root-relative MPJPE 31.08 mm、MRRPE 49.49 mm | 论文主要 ablation 使用 GT hand boxes;本表使用公开 detector,并额外报告 absolute camera-space、mesh、coverage。 |", + "| Hamba | FreiHAND PA-MPJPE/PA-MPVPE 5.8/5.5 mm(无 TTA) | 论文不报告 H2O;数据集不同且经 Procrustes alignment。本表发布配置含 H2O3D,但未含 H2O。 |", + "| PAD-Hand | DexYCB WiLoR→PAD-Hand: PA-MPJPE 4.88→4.63 mm、MPJPE 12.75→10.56 mm、ACCEL 6.70→3.34 | 本表是 H2O zero-shot,且保留 WiLoR camera translation;release checkpoint 未在 README 标明对应 DexYCB/HO3D 版本。 |", + "| HandDGP | FreiHAND camera-space MJE/MVE 46.3/46.3 mm | 发布权重仅用 FreiHAND;本表使用 H2O detector crop、已知 K 和同一 camera-space evaluator。 |", + "| Dyn-HaMR | 论文在动态相机视频上报告 global 4D hand-motion 指标 | 论文目标含相机运动与 world-space trajectory;本表因 H2O cam4 静止且 K 已知,只评每段 TTO 后的 camera-space hand 输出。 |", + "", + "因此,本复评能够检查公开 checkpoint 在同一 H2O validation 上的实际行为,但不能单独证实或否定论文 official-test 数字。", + "", + qort_note, + "", + wildhands_note, + "", + "原始来源:QORT-Former [paper](https://arxiv.org/abs/2502.19769) / [official repo](https://github.com/kcsayem/QORT-Former);WiLoR [paper](https://arxiv.org/abs/2409.12259) / [official repo](https://github.com/rolpotamias/WiLoR);HaWoR [paper](https://arxiv.org/abs/2501.02973) / [official repo](https://github.com/ThunderVVV/HaWoR);WildHands [ECCV page](https://eccv.ecva.net/virtual/2024/poster/2450) / [official repo](https://github.com/ap229997/hands);Hamba [NeurIPS paper](https://proceedings.neurips.cc/paper_files/paper/2024/hash/03e9a69e5b686c316a07d73f0cf5e225-Abstract-Conference.html) / [official repo](https://github.com/humansensinglab/Hamba);PAD-Hand [CVPR paper](https://openaccess.thecvf.com/content/CVPR2026/html/Ismayilzada_PAD-Hand_Physics-Aware_Diffusion_for_Hand_Motion_Recovery_CVPR_2026_paper.html) / [official repo](https://github.com/DominoAI-Lab/PAD-Hand-CVPR-2026);HandDGP [project](https://nianticlabs.github.io/handdgp/) / [official repo](https://github.com/nianticlabs/HandDGP);Dyn-HaMR [CVPR paper](https://openaccess.thecvf.com/content/CVPR2025/html/Yu_Dyn-HaMR_Recovering_4D_Interacting_Hand_Motion_from_a_Dynamic_Camera_CVPR_2025_paper.html) / [official repo](https://github.com/ZhengdiYu/Dyn-HaMR)。", + "", + "## 协议与公平性边界", + "", + f"- Manifest: `{manifest}`,SHA256 `{manifest_hash}`。", + f"- Ground truth bundle: `{ground_truth}`,SHA256 `{ground_truth_hash}`。", + f"- 样本:{rows[0]['frames']:,} 帧、{rows[0]['takes']} takes、{rows[0]['annotation_valid_hand_frames']:,} 个 annotation-valid hand-frames。", + "- Split:H2O official validation(subject3 held-out runs);official test(subject4)未使用。", + "- Camera:全部输出统一成 raw cam4 的 x-right/y-down/z-forward metric XYZ,再由同一 K 投影。", + "- 关节:H2O 左/右各 21 joints;mesh 统一为对应 MANO 778 vertices。", + "- FoundationHand 输入 RGB+metric Depth+K、T=8;QORT 输入单帧 RGB;WiLoR/WildHands/Hamba/HandDGP 输入 RGB detector/crop;HaWoR 与 PAD-Hand 输入 T=16 RGB track;Dyn-HaMR 对每个完整连续 run 做 TTO。协议一致不等于输入模态或计算预算一致。", + "- FoundationHand checkpoint 在 validation 固定子集上被选择;因此本报告用于开发期横向复评,最终无偏结论必须在冻结后一次性跑 official test。", + "- 直接运行 WiLoR/HaWoR/WildHands/Hamba/PAD-Hand/HandDGP 是有效的 H2O out-of-box 泛化测试,但不能解释为这些模型在 H2O 充分微调后的上限。Dyn-HaMR 已通过官方定义的 per-video TTO 适配测试序列。", + "- HandDGP 官方仓库只有 inference/evaluation;WiLoR/Hamba 只保留训练模块而缺少完整 runner/config;HaWoR 官方 README 仍写明训练代码将后续发布;PAD-Hand 仅发布 demo。自行编写微调器会形成新的派生训练配方,不能标成官方 fine-tuned baseline。", + "- 真正的 H2O fine-tuning 对照需要统一 H2O train、冻结 validation/test、同 detector/K、相同输入预算和选模规则,并同时报告 pretrained 与 fine-tuned;当前公开资产不足以严格完成这一实验。", + "- WiLoR/HaWoR 声明 CC BY-NC-ND 4.0,Hamba 声明 CC BY-NC 4.0;WildHands、QORT 与 PAD-Hand 在审计 commit 未见明确 LICENSE。MANO/Ultralytics 等依赖另有许可。当前下载与运行仅用于本地研究复评,不代表可重分发模型资产。", + "", + "## 已录用开源候选审计", + "", + "| 工作 | 状态 | 本报告处理 |", + "|---|---|---|", + "| PAD-Hand | CVPR 2026 Highlight;官方 demo 与 checkpoint | 纳入 zero-shot temporal 表;与相同 WiLoR initializer 成对报告。 |", + "| WildHands | ECCV 2024;官方代码与 checkpoint;论文明确 H2O zero-shot | 纳入零样本量化表。 |", + "| Hamba | NeurIPS 2024;官方推理代码与 checkpoint | 纳入零样本量化表;使用共同 detector 与官方 crop/initial-regressor。 |", + "| ViDiHand | 2026-06 arXiv;1.3B video diffusion + 37M decoder;metric two-hand camera-space 输出 | 方法与 H2O 高度匹配,但官方仓库仅 README,明确写明 code will be released soon;当前无 checkpoint/推理/训练代码。 |", + "| Dyn-HaMR | CVPR 2025 Highlight;官方代码、HaMeR 权重与 TTO 配置 | 已按每个连续 run、静态已知 H2O K 完整运行,单列 TTO 赛道;不是可微调 feed-forward baseline。 |", + "| HandDGP | ECCV 2024;官方 FreiHAND checkpoint 与 camera-space 推理 | 已用发布权重、官方 rectification/DGP 和共同 detector 纳入 zero-shot 表;仓库无训练入口。 |", + "| EgoHandICL | ICLR 2026;官方仓库 commit `16e5690` 含名义训练/推理文件 | 推理脚本引用未发布的 `handicl` 核心 package;Hugging Face 仅有数据/标注压缩包而无 checkpoint,README 还含 `` 与空权重路径,不能形成可审计推理或微调。 |", + "| MaskHand | ICCV 2025 | 项目页只有论文与演示;截至 2026-07-20,论文所指官方 GitHub 返回 404,无 checkpoint,无法同权重复评。 |", + "| Pose-Guided Temporal Enhancement | CVPR 2025 | 未找到作者公开的推理仓库或 checkpoint。 |", + "| OmniHands | ACM TOG 2026;官方代码与 image/video/multiview checkpoints | 任务核心是双手交互及 temporal/multiview,发布 demo 的相机输出/评估协议与本表单手 camera-space 协议不同,暂不混排。 |", + "| Enhancing Monocular 3D Hand Reconstruction with Learned Texture Priors | WACV 2026;公开 texture-supervised HaMeR 权重 | 仓库仍将完整 code release 标为未完成;待稳定发布后可按 HaMeR camera adapter 加入。 |", + "| HandOS | CVPR 2025 | 官方项目当前未提供可下载 checkpoint,无法做同权重复评。 |", + "| PS-HPME / Pseudo-Stereo-Hand | Knowledge-Based Systems 2026;目标为单目 camera-space mesh | 论文给出的官方 GitHub 地址在本次审计返回 404,无法下载代码或 checkpoint。 |", + "| SesaHand | ICLR 2026;生成数据增强重建 | 不是独立重建推理模型,官方仓库的 pretrained model 与 samples 仍标为 TBD。 |", + "| POEM-v2 | TPAMI 2025;代码/权重公开 | 多视图方法;当前冻结 H2O 产物只有 cam4,不能伪装成公平单目基线。 |", + "", + "## 公开实现与资产溯源", + "", + ]) + for evaluation in evaluations: + metadata = evaluation["report"]["prediction_metadata"] + lines.append(f"### {evaluation['label']}") + lines.append("") + if metadata.get("official_repository"): + lines.append(f"- Official repository: {metadata['official_repository']}") + lines.append(f"- Repository commit: `{metadata['repository_commit']}`") + elif metadata.get("training_commit"): + lines.append(f"- Training commit: `{metadata['training_commit']}`") + lines.append( + f"- Repository commit at export: `{metadata['repository_commit_at_export']}`" + ) + checkpoint = metadata.get("checkpoint", metadata.get("hamer_checkpoint")) + checkpoint_hash = metadata.get( + "checkpoint_sha256", metadata.get("hamer_checkpoint_sha256") + ) + lines.append(f"- Checkpoint: `{checkpoint}`") + lines.append(f"- Checkpoint SHA256: `{checkpoint_hash}`") + if metadata.get("detector_checkpoint"): + lines.append(f"- Detector: `{metadata['detector_checkpoint']}`") + lines.append( + f"- Detector SHA256: `{metadata['detector_checkpoint_sha256']}`" + ) + if metadata.get("base_wilor_checkpoint"): + lines.append( + f"- Base WiLoR commit: `{metadata['base_wilor_repository_commit']}`" + ) + lines.append(f"- Base WiLoR: `{metadata['base_wilor_checkpoint']}`") + lines.append( + f"- Base WiLoR SHA256: `{metadata['base_wilor_checkpoint_sha256']}`" + ) + lines.append(f"- Evaluation JSON SHA256: `{evaluation['summary']['evaluation_json_sha256']}`") + lines.append("") + lines.extend([ + "## 可复现产物", + "", + "- `comparison.csv`: 完整主表机器可读版本。", + "- `paired_take_bootstrap.csv`: 全指标配对差值与 CI。", + "- `pad_hand_vs_wilor_paired_take_bootstrap.csv`: PAD-Hand refinement 相对同一 WiLoR initializer 的配对差值。", + "- `dynhamr_vs_hawor_paired_take_bootstrap.csv`: Dyn-HaMR TTO 相对最强 zero-shot 前向 HaWoR 的直接配对差值。", + "- `INFERENCE_SPEED_REPORT.md`、`speed_comparison.csv` 与 `speed_report.json`: 同机统一推理速度、原始 timing 哈希和 Dyn-HaMR TTO 开销拆分。", + "- `report.json`: 汇总、论文协议旁注和所有输入文件 hash。", + "- `visual_audit/projection_contact_sheet.jpg` 与 `visual_audit/visual_audit.json`: 固定样本投影和全量正深度/画内统计。", + "- 各 evaluation 目录保留逐 hand-frame 与逐 temporal-transition CSV,可重算全部统计。", + "", + ]) + return "\n".join(lines) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--evaluation", + action="append", + required=True, + help="LABEL=directory containing evaluation.json and metric CSV files", + ) + parser.add_argument("--foundation-label", default="FoundationHand-Phase3") + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + + evaluations = [] + labels = set() + for spec in args.evaluation: + label, separator, raw_directory = spec.partition("=") + if not separator or not label or not raw_directory: + raise ValueError(f"Invalid --evaluation value: {spec}") + if label in labels: + raise ValueError(f"Duplicate evaluation label: {label}") + labels.add(label) + evaluations.append(load_evaluation(label, Path(raw_directory).resolve())) + if args.foundation_label not in labels: + raise ValueError(f"Missing foundation label: {args.foundation_label}") + baseline = next( + evaluation for evaluation in evaluations + if evaluation["label"] == args.foundation_label + ) + paired_rows: list[dict[str, Any]] = [] + for evaluation in evaluations: + if evaluation is baseline or evaluation["label"] == "WiLoR-native-camera": + continue + contrasts = paired_take_bootstrap( + baseline["frame_rows"], + evaluation["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + paired_rows.extend({ + "baseline": args.foundation_label, + "candidate": evaluation["label"], + **contrast, + } for contrast in contrasts) + + refinement_rows: list[dict[str, Any]] = [] + if "WiLoR-H2O-K" in labels and "PAD-Hand-WiLoR" in labels: + wilor = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "WiLoR-H2O-K" + ) + pad_hand = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "PAD-Hand-WiLoR" + ) + refinement_rows = [ + { + "baseline": "WiLoR-H2O-K", + "candidate": "PAD-Hand-WiLoR", + **contrast, + } + for contrast in paired_take_bootstrap( + wilor["frame_rows"], + pad_hand["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + ] + + dynhamr_hawor_rows: list[dict[str, Any]] = [] + if "HaWoR-camera" in labels and "Dyn-HaMR-TTO" in labels: + hawor = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "HaWoR-camera" + ) + dynhamr = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "Dyn-HaMR-TTO" + ) + dynhamr_hawor_rows = [ + { + "baseline": "HaWoR-camera", + "candidate": "Dyn-HaMR-TTO", + **contrast, + } + for contrast in paired_take_bootstrap( + hawor["frame_rows"], + dynhamr["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + ] + + args.output_dir.mkdir(parents=True, exist_ok=True) + comparison_rows = [evaluation["summary"] for evaluation in evaluations] + write_csv_rows(args.output_dir / "comparison.csv", comparison_rows) + write_csv_rows(args.output_dir / "paired_take_bootstrap.csv", paired_rows) + if refinement_rows: + write_csv_rows( + args.output_dir / "pad_hand_vs_wilor_paired_take_bootstrap.csv", + refinement_rows, + ) + if dynhamr_hawor_rows: + write_csv_rows( + args.output_dir / "dynhamr_vs_hawor_paired_take_bootstrap.csv", + dynhamr_hawor_rows, + ) + manifest = args.manifest.resolve() + ground_truth = args.ground_truth.resolve() + speed_report_path = args.output_dir / "speed_report.json" + speed_report = ( + json.loads(speed_report_path.read_text(encoding="utf-8")) + if speed_report_path.is_file() + else None + ) + payload = { + "status": "complete", + "official_test_used": False, + "split_role": "official_validation", + "manifest": str(manifest), + "manifest_sha256": sha256(manifest), + "ground_truth": str(ground_truth), + "ground_truth_sha256": sha256(ground_truth), + "bootstrap_seed": args.bootstrap_seed, + "bootstrap_samples": args.bootstrap_samples, + "comparison": comparison_rows, + "paired_take_bootstrap": paired_rows, + "pad_hand_vs_wilor_paired_take_bootstrap": refinement_rows, + "dynhamr_vs_hawor_paired_take_bootstrap": dynhamr_hawor_rows, + "paper_reported_context": { + "QORT-Former": "H2O test MEE left/right 20.1/19.9 mm", + "WiLoR": "FreiHAND PA-MPJPE/PA-MPVPE 5.5/5.1 mm; HO3D 7.5/7.7 mm", + "HaWoR": "DexYCB PA-MPJPE 4.76 mm, AUC 90.5", + "WildHands": "H2O validation zero-shot MPJPE/MRRPE 31.08/49.49 mm", + "Hamba": "FreiHAND no-TTA PA-MPJPE/PA-MPVPE 5.8/5.5 mm", + "PAD-Hand": ( + "DexYCB WiLoR->PAD-Hand PA-MPJPE 4.88->4.63 mm, " + "MPJPE 12.75->10.56 mm, ACCEL 6.70->3.34" + ), + "HandDGP": "FreiHAND camera-space MJE/MVE 46.3/46.3 mm", + "Dyn-HaMR": "global 4D hand-motion reconstruction on dynamic-camera videos", + }, + } + if speed_report is not None: + payload["speed_benchmark"] = { + "path": str(speed_report_path.resolve()), + "sha256": sha256(speed_report_path), + "status": speed_report.get("status"), + } + (args.output_dir / "report.json").write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + report_text = markdown_report( + evaluations, + paired_rows, + refinement_rows, + dynhamr_hawor_rows, + speed_report, + manifest=manifest, + manifest_hash=payload["manifest_sha256"], + ground_truth=ground_truth, + ground_truth_hash=payload["ground_truth_sha256"], + bootstrap_seed=args.bootstrap_seed, + bootstrap_samples=args.bootstrap_samples, + ) + (args.output_dir / "SOTA_EVALUATION_REPORT.md").write_text( + report_text, encoding="utf-8" + ) + print(json.dumps({ + "models": [evaluation["label"] for evaluation in evaluations], + "output_dir": str(args.output_dir.resolve()), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_sota_speed.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_sota_speed.py new file mode 100644 index 0000000000000000000000000000000000000000..11ebd0914d721320b8787f1e806411a282dab0cc --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/summarize_sota_speed.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Summarize synchronized external-baseline speed measurements.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +SETTINGS = { + "FoundationHand-T8": ("FoundationHand", "temporal_clip", "RGB+Depth+K, T=8, clip batch=1"), + "QORT-b1": ("QORT-Former", "framewise", "batch=1"), + "QORT-b16": ("QORT-Former", "batched", "batch=16"), + "WiLoR-b1": ("WiLoR", "framewise", "detector/reconstruction batch=1"), + "WiLoR-b16": ("WiLoR", "batched", "detector/reconstruction batch=16"), + "HaWoR-T16": ("HaWoR", "offline_temporal", "tracked temporal window=16"), + "Dyn-HaMR-TTO": ("Dyn-HaMR", "test_time_optimization", "one 94-frame run"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--timing", action="append", required=True, help="SETTING=timing.json") + parser.add_argument("--foundation-profile", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + + grouped: dict[str, list[tuple[Path, dict[str, Any]]]] = {} + for spec in args.timing: + label, separator, raw_path = spec.partition("=") + if not separator or label not in SETTINGS or not raw_path: + raise ValueError(f"Invalid timing specification: {spec}") + path = Path(raw_path).resolve() + payload = json.loads(path.read_text(encoding="utf-8")) + if payload.get("schema_version") != "foundation_hand_external_speed_v1": + raise ValueError(f"Unexpected timing schema: {path}") + if int(payload.get("frames", 0)) != 94: + raise ValueError(f"Benchmark must contain exactly 94 frames: {path}") + grouped.setdefault(label, []).append((path, payload)) + + missing = set(SETTINGS) - set(grouped) + if missing: + raise ValueError(f"Missing benchmark settings: {sorted(missing)}") + + rows: list[dict[str, Any]] = [] + raw_measurements: dict[str, list[dict[str, Any]]] = {} + for label, (model, mode, setting) in SETTINGS.items(): + measurements = grouped[label] + fps = np.asarray([item[1]["frames_per_second"] for item in measurements]) + seconds = np.asarray([item[1]["processing_seconds"] for item in measurements]) + row = { + "setting_id": label, + "model": model, + "mode": mode, + "setting": setting, + "repeats": len(measurements), + "frames_per_repeat": 94, + "median_processing_seconds": float(np.median(seconds)), + "median_fps": float(np.median(fps)), + "min_fps": float(fps.min()), + "max_fps": float(fps.max()), + "amortized_ms_per_frame": float(1000.0 / np.median(fps)), + } + rows.append(row) + raw_measurements[label] = [ + { + "path": str(path), + "sha256": sha256(path), + **payload, + } + for path, payload in measurements + ] + + by_label = {row["setting_id"]: row for row in rows} + dyn = raw_measurements["Dyn-HaMR-TTO"][0] + foundation_profile_path = args.foundation_profile.resolve() + foundation_profile = json.loads( + foundation_profile_path.read_text(encoding="utf-8") + ) + foundation_forward_ms = float(foundation_profile["latency"]["p50_ms"]) + foundation_model_fps = 8_000.0 / foundation_forward_ms + dyn_initializer_fps = dyn["frames"] / dyn["initialization_seconds"] + dyn_optimizer_fraction = dyn["optimization_seconds"] / dyn["processing_seconds"] + throughput_order = [ + "FoundationHand-T8", "QORT-b16", "WiLoR-b16", "HaWoR-T16", "Dyn-HaMR-TTO" + ] + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "speed_comparison.csv", rows) + report_payload = { + "status": "complete", + "schema_version": "foundation_hand_external_speed_report_v1", + "date": "2026-07-21", + "hardware": "NVIDIA GeForce RTX 4090", + "physical_gpu_policy": ( + "QORT/WiLoR/HaWoR repeats used idle physical GPU0; " + "Dyn-HaMR used idle physical GPU1; all GPUs are identical RTX 4090 cards" + ), + "workload": "first official H2O validation contiguous run (94 RGB frames)", + "timed_scope": ( + "RGB decode/preprocessing through final camera-space conversion; " + "model loading and prediction serialization excluded" + ), + "cuda_synchronized": True, + "rows": rows, + "raw_measurements": raw_measurements, + "foundation_model_only_profile": { + "path": str(foundation_profile_path), + "sha256": sha256(foundation_profile_path), + "p50_ms_per_t8_clip": foundation_forward_ms, + "amortized_frames_per_second": foundation_model_fps, + "scope": foundation_profile["latency"]["scope"], + }, + "dynhamr_diagnostics": { + "initializer_fps": dyn_initializer_fps, + "initializer_seconds": dyn["initialization_seconds"], + "optimization_seconds": dyn["optimization_seconds"], + "optimizer_fraction": dyn_optimizer_fraction, + "root_iterations": dyn["root_iterations"], + "smooth_iterations": dyn["smooth_iterations"], + }, + } + (args.output_dir / "speed_report.json").write_text( + json.dumps(report_payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + lines = [ + "# FoundationHand 外部方法推理速度复评", + "", + "## 结论", + "", + ( + f"在相同 94 帧 H2O RGB 连续片段和 RTX 4090 上,批处理吞吐排序为 " + f"**FoundationHand ({by_label['FoundationHand-T8']['median_fps']:.2f} FPS) > " + f"QORT-Former ({by_label['QORT-b16']['median_fps']:.2f} FPS) > " + f"WiLoR ({by_label['WiLoR-b16']['median_fps']:.2f} FPS) > " + f"HaWoR ({by_label['HaWoR-T16']['median_fps']:.2f} FPS) > " + f"Dyn-HaMR ({by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS)**。" + ), + "", + ( + "QORT/WiLoR 是逐帧前向方法;FoundationHand 使用 T=8 RGB+Depth+K clip;" + "HaWoR 必须看到时序窗口/连续 track;" + "Dyn-HaMR 对整段测试视频优化。因此 FPS 可比较系统计算成本,但 HaWoR/Dyn-HaMR 的" + "摊销 ms/frame 不是因果单帧响应延迟。" + ), + "", + "## 端到端摊销吞吐", + "", + "计时包含 RGB 解码、官方预处理、需要的 detector、重建和 camera-space 转换;不包含权重加载与 NPZ 写盘。", + "", + "| 方法 | 模式 | 设置 | 重复 | Median FPS | 范围 | 摊销 ms/frame |", + "|---|---|---|---:|---:|---:|---:|", + ] + for label in throughput_order: + row = by_label[label] + lines.append( + f"| {row['model']} | {row['mode']} | {row['setting']} | {row['repeats']} | " + f"{row['median_fps']:.3f} | {row['min_fps']:.3f}-{row['max_fps']:.3f} | " + f"{row['amortized_ms_per_frame']:.2f} |" + ) + lines.extend([ + "", + "## Batch-1 在线前向", + "", + "| 方法 | Median FPS | 范围 | ms/frame |", + "|---|---:|---:|---:|", + ]) + for label in ("QORT-b1", "WiLoR-b1"): + row = by_label[label] + lines.append( + f"| {row['model']} | {row['median_fps']:.3f} | " + f"{row['min_fps']:.3f}-{row['max_fps']:.3f} | " + f"{row['amortized_ms_per_frame']:.2f} |" + ) + lines.extend([ + "", + "HaWoR 和 Dyn-HaMR 不列入 batch-1 在线表:前者是非因果 tracked temporal inference,后者是整段 TTO。", + "", + "## FoundationHand 开销拆分", + "", + ( + f"FoundationHand 完整 RGB+Depth+K 数据路径的中位吞吐为 " + f"{by_label['FoundationHand-T8']['median_fps']:.2f} FPS(" + f"{by_label['FoundationHand-T8']['amortized_ms_per_frame']:.2f} ms/frame 摊销)。" + f"独立的 100 次 GPU forward 计时 P50 为 {foundation_forward_ms:.2f} ms/T=8 clip," + f"等价于 {foundation_model_fps:.1f} frame/s 的纯模型吞吐;两者差额主要来自 RGB/Depth 解码、" + "640x368 预处理、worker 启动和 host-device/host result transfer。" + ), + "", + ( + "FoundationHand 的 T=8 需要先获得一个 8 帧窗口,因此上述 14.2 ms/frame 是系统吞吐," + "不是零缓冲的单帧响应延迟。" + ), + "", + "## Dyn-HaMR 开销拆分", + "", + ( + f"Dyn-HaMR 的 detector+HaMeR 初始化耗时 {dyn['initialization_seconds']:.2f} s," + f"相当于 {dyn_initializer_fps:.2f} FPS;32 次 Root + 300 次 Smooth TTO 耗时 " + f"{dyn['optimization_seconds']:.2f} s,占完整推理时间 {100 * dyn_optimizer_fraction:.2f}%。" + f"完整 94 帧用时 {dyn['processing_seconds']:.2f} s,即 " + f"{by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS。" + ), + "", + "## 公平性边界", + "", + "- FoundationHand/QORT/WiLoR/HaWoR 各重复 3 次并报告中位数和范围;Dyn-HaMR 因完整 TTO 昂贵,报告一次无缓存的完整官方优化。", + "- QORT/WiLoR 的 batch=16 数字是吞吐,不是单请求延迟。", + "- HaWoR 速度只覆盖本 SOTA 报告使用的 camera-space hand stage,不包含 DROID-SLAM、Metric3D 或 world-space infiller。", + "- FoundationHand 使用 RGB+metric Depth+K 且不需要 detector;外部方法为 RGB,因此这是已部署系统吞吐比较,不是输入模态等价的 backbone benchmark。", + "- Dyn-HaMR 使用已知静态 H2O K,因此不包含 VIPE/DROID-SLAM;包含与量化结果完全相同的 Root/Smooth TTO。", + "- FoundationHand/QORT/WiLoR/HaWoR 重复测量使用空闲物理 GPU0;Dyn-HaMR 使用空闲物理 GPU1。六张卡均为 RTX 4090。", + "- 这些是本机 release-code 系统测速,不应与论文在其他 GPU、分辨率或只计 model-forward 的 FPS 直接混排。", + "", + "## 可复现产物", + "", + "- `speed_comparison.csv`: 汇总速度表。", + "- `speed_report.json`: 原始 timing 路径、SHA256、计时范围与 Dyn-HaMR 分段耗时。", + "- 原始同步 timing JSON 位于 `artifacts/sota/speed_benchmark_20260721/`。", + "", + ]) + (args.output_dir / "INFERENCE_SPEED_REPORT.md").write_text( + "\n".join(lines), encoding="utf-8" + ) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_last2_candidate_admission.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_last2_candidate_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..ab89a845500fc88174c957806b8b2318ca3e8e0a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_last2_candidate_admission.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Forward-sync one frozen last-2 admission to its remote owner controller.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def upstream_files(plan: dict[str, Any]) -> list[Path]: + state_path = Path(plan["admission_controller_state"]) + report_path = Path(plan["admission_decision_report"]) + if not state_path.is_file() or not report_path.is_file(): + raise NotReady("last-2 upstream decision is not complete") + state = read_json(state_path) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != plan["admission_controller_plan_sha256"] + or state.get("decision_report", {}).get("path") != str(report_path.resolve()) + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or state.get("official_test_used") is not False + ): + raise NotReady("last-2 upstream decision is not complete") + files = [report_path, state_path] + stage8_state = Path(plan["stage8_controller_state"]) + if stage8_state not in files: + stage8 = read_json(stage8_state) + stage8_report = Path(stage8["decision_report"]["path"]) + files.extend((stage8_report, stage8_state)) + return files + + +def admission_payload(plan: dict[str, Any]) -> tuple[str, list[Path], list[dict[str, str]]]: + files = upstream_files(plan) + central_path = Path(plan["controller_states"]["taku3"]) + if not central_path.is_file(): + raise NotReady("central last-2 candidate has not consumed admission") + central = read_json(central_path) + decision_path = Path(plan["decision_report"]) + if central.get("status") == "complete" and central.get("admitted") is False: + if not decision_path.is_file() or central.get("decision_report", {}).get("sha256") != sha256(decision_path): + raise ValueError("central last-2 rejection binding differs") + return "rejected", files + [decision_path, central_path], [] + registry_path = Path(plan["training_registry"]) + if not registry_path.is_file() or not central.get("training_registry_sha256"): + raise NotReady("central last-2 training registry is not frozen") + if ( + central.get("plan_sha256") != sha256(Path(central["plan"])) + or central.get("training_registry") != str(registry_path.resolve()) + or central.get("training_registry_sha256") != sha256(registry_path) + or central.get("official_test_used") is not False + ): + raise ValueError("central last-2 controller binding differs") + registry = read_json(registry_path) + owners = condition_owners(registry, load_assignment(plan)) + conditions = registry.get("conditions", []) + if ( + registry.get("status") != "frozen_ready" + or registry.get("candidate") != plan["candidate"] + or len(conditions) != 7 + or sum(owner == "server_new" for owner in owners.values()) != 3 + or registry.get("official_test_used") is not False + ): + raise ValueError("last-2 registry contract differs") + files.extend((Path(plan["training_registry_state"]), + *[Path(item["config"]) for item in conditions], registry_path)) + prerequisites, seen = [], set() + for item in conditions: + pair = (item["initialization_checkpoint"], item["initialization_checkpoint_sha256"]) + if pair not in seen: prerequisites.append({"path": pair[0], "sha256": pair[1]}); seen.add(pair) + for item in registry["data_artifacts"]: + pair = (item["path"], item["sha256"]) + if pair not in seen: prerequisites.append({"path": pair[0], "sha256": pair[1]}); seen.add(pair) + return "admitted", files, prerequisites + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = Path(state).parent.parent / "server_new.log" + command = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_last2_candidate_controller --plan " + str(plan_path.resolve()) + + " --state " + state + " --machine server_new --poll-seconds 30 >> " + + str(log) + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: raise RuntimeError("remote last-2 controller launch failed") + time.sleep(2) + probe = subprocess.run([ + "ssh", "server_new", "pgrep", "-fo", + f"scripts.run_phase9_last2_candidate_controller.*last2_v3/{plan['candidate']}.*server_new.json", + ], stdout=subprocess.PIPE, text=True, check=False) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote last-2 controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + admission, files, prerequisites = admission_payload(plan) + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"central last-2 prerequisite differs: {path}") + if remote_sha256("server_new", path) != item["sha256"]: + raise ValueError(f"remote last-2 prerequisite differs: {path}") + registry = Path(plan["training_registry"]) + ordered = [path for path in files if path != registry] + ([registry] if registry in files else []) + installed = [install_file("server_new", path) for path in ordered] + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_last2_candidate_admission_sync_v1", + "status": "complete", "candidate": plan["candidate"], "admission": admission, + "completed_utc": utc_now(), "plan_sha256": sha256(plan_path), + "installed": installed, "immutable_prerequisites": prerequisites, + "registry_installed_last": registry in files, "remote_controller_pid": pid, + "official_test_used": False, "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_last2_candidate_admission_sync_v1", + "status": "waiting_for_candidate_admission", "candidate": plan["candidate"], + "watcher_pid": os.getpid(), "updated_utc": utc_now(), "detail": str(error), + "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_last2_training_completion.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_last2_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..6c9fa4facf8e3fbbde000e22bcab8de5e9a983fc --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_last2_training_completion.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Completion-only remote training handoff for an admitted last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_resolution_training_completion import active_writer_pids +from scripts.sync_phase9_shared_augmentation_training_completion import ( + file_record, install, json_sha256, validate_terminal, +) + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(path: Path, plan: dict[str, Any]) -> None: + conditions = plan.get("conditions", []) + if ( + plan.get("schema_version") != "phase9_last2_training_completion_plan_v1" + or plan.get("status") != "frozen" + or plan.get("candidate") not in {"5e7", "1e6"} + or len(conditions) != 3 or len(set(conditions)) != 3 + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("target_step") != 405000 + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + ): + raise ValueError("last-2 training completion plan differs") + for binding in plan["bindings"]: + candidate = Path(binding["path"]) + if not candidate.is_file() or sha256(candidate) != binding["sha256"]: + raise ValueError(f"last-2 completion binding differs: {candidate}") + if not path.is_file(): raise ValueError("last-2 completion plan is unreadable") + + +def registry_jobs(plan: dict[str, Any]) -> tuple[Path, dict[str, Any], dict[str, Any]]: + path = Path(plan["training_registry"]["path"]) + if not path.is_file() or sha256(path) != plan["training_registry"]["sha256"]: + raise ValueError("last-2 training registry hash differs") + registry = read_json(path); jobs = {item["condition"]: item for item in registry["conditions"]} + owners = condition_owners(registry, load_assignment(plan)) + remote = [condition for condition in jobs if owners[condition] == "server_new"] + if ( + registry.get("status") != "frozen_ready" + or registry.get("candidate") != plan["candidate"] + or remote != plan["conditions"] + or registry.get("target_step") != 405000 + or registry.get("official_test_used") is not False + ): + raise ValueError("last-2 training registry contract differs") + return path, registry, jobs + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + registry_path, _, jobs = registry_jobs(plan) + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): raise NotReady("remote last-2 controller is missing") + controller = read_json(controller_path) + statuses = controller.get("training_statuses", {}) + if any(statuses.get(condition) != "complete" for condition in plan["conditions"]): + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("remote last-2 controller failed") + raise NotReady("remote last-2 training is still running") + if ( + controller.get("plan_sha256") != plan["controller_plan"]["sha256"] + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("official_test_used") is not False + ): + raise ValueError("remote last-2 controller binding differs") + root, state_root = Path(plan["release_root"]), Path(plan["training_state_root"]) + records, files = [], [] + for condition in plan["conditions"]: + job = jobs[condition]; state_path = state_root / f"{condition.lower()}.json" + state = read_json(state_path) + if state.get("queue_sha256") != sha256(registry_path): + raise ValueError(f"last-2 state registry binding differs: {condition}") + if active_writer_pids(job["output_dir"]): raise NotReady(f"last-2 writer exists: {condition}") + checkpoint, evidence = validate_terminal(job, state) + pair = [file_record(root, "checkpoint", checkpoint), + file_record(root, "training_state", state_path)] + files.extend(pair); records.append({ + "condition": condition, "role": job["role"], + "checkpoint_sha256": sha256(checkpoint), + "final_total_loss": float(evidence["metric"]["losses"]["total"]), + "metrics_sha256": evidence["metrics_sha256"], + "summary_sha256": evidence["summary_sha256"], "files": pair, + }) + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): return read_json(output) + records, files = source_records(plan) + value = { + "schema_version": "phase9_last2_training_completion_release_v1", + "status": "complete_immutable_release", "candidate": plan["candidate"], + "created_utc": utc_now(), "plan_sha256": sha256(plan_path), + "training_registry": plan["training_registry"], "release_root": plan["release_root"], + "conditions": records, "files": files, "file_count": 6, + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, "live_reverse_sync_performed": False, + "results_before_terminal_states": True, "official_test_used": False, + } + atomic_json(output, value); os.chmod(output, 0o444) + for item in files: os.chmod(item["absolute_path"], 0o444) + return value + + +def fetch(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run(["ssh", "server_new", "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, check=False) + if result.returncode: raise NotReady("remote last-2 release is unavailable") + return json.loads(result.stdout) + + +def validate_release(plan_path: Path, plan: dict[str, Any], value: dict[str, Any]) -> None: + files = value.get("files", []) + if ( + value.get("schema_version") != "phase9_last2_training_completion_release_v1" + or value.get("status") != "complete_immutable_release" + or value.get("candidate") != plan["candidate"] + or value.get("plan_sha256") != sha256(plan_path) + or value.get("training_registry") != plan["training_registry"] + or [item.get("condition") for item in value.get("conditions", [])] != plan["conditions"] + or len(files) != 6 or len({item.get("path") for item in files}) != 6 + or value.get("results_before_terminal_states") is not True + or value.get("official_test_used") is not False + ): + raise ValueError("last-2 immutable release differs") + + +def central_ready(plan: dict[str, Any]) -> bool: + path = Path(plan["training_completion_state"]) + if not path.is_file(): return False + value = read_json(path) + return (value.get("status") == "complete" and value.get("candidate") == plan["candidate"] + and value.get("training_registry_sha256") == plan["training_registry"]["sha256"] + and value.get("official_test_used") is False) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): return read_json(output) + release = fetch(plan); validate_release(plan_path, plan, release) + installed = install(plan, release) + deadline = time.monotonic() + 120 + while time.monotonic() < deadline and not central_ready(plan): time.sleep(2) + if not central_ready(plan): raise TimeoutError("central last-2 training did not converge") + value = { + "schema_version": "phase9_last2_training_completion_receive_v1", + "status": "complete", "candidate": plan["candidate"], "completed_utc": utc_now(), + "plan_sha256": sha256(plan_path), "release_sha256": json_sha256(release), + "installed": installed, "file_count": 6, "total_bytes": release["total_bytes"], + "results_before_terminal_states": True, "official_test_used": False, + } + atomic_json(output, value); return value + + +def main() -> None: + parser = argparse.ArgumentParser(); parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + try: validate_plan(args.plan, plan) + except ValueError as error: parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True); deadline = time.monotonic() + args.wait_timeout_seconds + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + value = publish(args.plan, plan) if args.role == "publish" else receive(args.plan, plan) + print(json.dumps(value, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(Path(f"{target}.watcher.json"), { + "schema_version": "phase9_last2_training_completion_watcher_v1", + "status": "waiting_for_terminal_source", "candidate": plan["candidate"], + "role": args.role, "watcher_pid": os.getpid(), "updated_utc": utc_now(), + "detail": str(error), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_resolution_evaluation_completion.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_resolution_evaluation_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..7213c888087d9e7daec2af464ac979afd0e504fa --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_resolution_evaluation_completion.py @@ -0,0 +1,450 @@ +#!/usr/bin/env python3 +"""Publish and import terminal server_new Stage 7 evaluation evidence.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +class NotReady(RuntimeError): + """A healthy source dependency has not reached its terminal state.""" + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: dict[str, Any]) -> str: + payload = (json.dumps(value, indent=2) + "\n").encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + if ( + plan.get("schema_version") + != "phase9_resolution_evaluation_completion_release_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or scientific.get("amendment_scope") + != "terminal_evaluation_state_and_result_handoff_only" + or any( + scientific.get(key) is not False + for key in ( + "model_changed", "data_changed", "seed_changed", + "metric_changed", "selection_gate_changed", + ) + ) + ): + raise ValueError("resolution evaluation completion plan contract differs") + for key in ( + "release_root", "staging_root", "release_state", "receive_state", + ): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution evaluation completion {key} is not /SSD2") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution evaluation completion binding differs: {path}") + if not plan_path.is_file(): + raise ValueError("resolution evaluation completion plan is unreadable") + + +def remote_inventory(plan: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]: + path = Path(plan["evaluation_plan"]["path"]) + if not path.is_file() or sha256(path) != plan["evaluation_plan"]["sha256"]: + raise ValueError("resolution evaluation plan hash differs") + dynamic = read_json(path) + workers = [item for item in dynamic["workers"] if item["owner"] == "server_new"] + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + assigned = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(dynamic["evaluations"]) != 25 + or len(dynamic["workers"]) != 10 + or len(workers) != 4 + or len(assigned) != 9 + or len(set(assigned)) != 9 + or any(evaluations[identifier]["training_role"] not in { + "loso_subject2", "loso_subject3", "lofamily_k", + } for identifier in assigned) + or dynamic.get("official_test_used") is not False + or dynamic.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new resolution evaluation ownership differs") + return dynamic, workers + + +def active_evaluator_pids(evaluation_id: str, proc_root: Path = Path("/proc")) -> list[int]: + result = [] + token = f"--evaluation-id {evaluation_id}" + for entry in proc_root.iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (FileNotFoundError, PermissionError, ProcessLookupError, UnicodeDecodeError): + continue + if "scripts.evaluate_phase7_external" in command and token in command: + result.append(int(entry.name)) + return sorted(result) + + +def release_file(root: Path, kind: str, path: Path) -> dict[str, Any]: + if not path.is_file() or path.is_symlink() or root not in path.resolve().parents: + raise ValueError(f"resolution evaluation release artifact differs: {path}") + return { + "kind": kind, + "path": str(path.resolve().relative_to(root.resolve())), + "absolute_path": str(path.resolve()), + "bytes": path.stat().st_size, + "sha256": sha256(path), + } + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + dynamic, workers = remote_inventory(plan) + dynamic_hash = plan["evaluation_plan"]["sha256"] + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): + raise NotReady("server_new evaluation controller state is missing") + controller = read_json(controller_path) + if controller.get("status") not in {"complete_local", "complete"}: + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("server_new evaluation controller failed") + raise NotReady("server_new evaluation controller is still running") + if ( + controller.get("machine") != "server_new" + or controller.get("evaluation_plan_sha256") != dynamic_hash + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new evaluation controller binding differs") + + root = Path(plan["release_root"]) + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + records = [] + files = [] + for worker in workers: + state_path = Path(worker["state"]) + if not state_path.is_file(): + raise NotReady(f"server_new evaluation worker is missing: {worker['id']}") + state = read_json(state_path) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed_terminal"): + raise ValueError(f"server_new evaluation worker failed: {worker['id']}") + raise NotReady(f"server_new evaluation worker is still running: {worker['id']}") + if ( + state.get("worker") != worker["id"] + or state.get("owner") != "server_new" + or state.get("plan_sha256") != dynamic_hash + or state.get("assigned_evaluation_ids") != worker["evaluation_ids"] + or state.get("completed_ids") != worker["evaluation_ids"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"server_new evaluation worker binding differs: {worker['id']}") + files.append(release_file(root, "worker_state", state_path)) + for identifier in worker["evaluation_ids"]: + if active_evaluator_pids(identifier): + raise NotReady(f"server_new evaluator still exists: {identifier}") + item = evaluations[identifier] + if not evaluation_complete(item): + raise ValueError(f"server_new evaluation result differs: {identifier}") + report_path = Path(item["output_dir"]) / "evaluation.json" + report = read_json(report_path) + result_files = [release_file(root, "evaluation_report", report_path)] + for key in ("raw_predictions", "per_hand_rows", "take_metrics"): + artifact = report[key] + path = Path(artifact["path"]) + record = release_file(root, key, path) + if record["sha256"] != artifact["sha256"]: + raise ValueError(f"server_new result artifact hash differs: {identifier}") + result_files.append(record) + files.extend(result_files) + records.append({ + "evaluation_id": identifier, + "worker": worker["id"], + "checkpoint_sha256": item["checkpoint_sha256"], + "config_sha256": item["config_sha256"], + "cache_manifest_sha256": item["cache_manifest_sha256"], + "clips": report["clips"], "frames": report["frames"], + "wall_seconds": report["runtime"]["wall_seconds"], + "gpu_hours": report["runtime"]["wall_seconds"] / 3600.0, + "evaluation_report_sha256": sha256(report_path), + "files": result_files, + }) + files.append(release_file(root, "controller_state", controller_path)) + paths = [item["path"] for item in files] + if len(records) != 9 or len(files) != 41 or len(paths) != len(set(paths)): + raise ValueError("server_new evaluation release inventory differs") + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + existing = read_json(output) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution evaluation release differs") + records, files = source_records(plan) + result = { + "schema_version": "phase9_resolution_evaluation_completion_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "destination_owner": "taku3", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_root": str(Path(plan["release_root"]).resolve()), + "evaluation_plan": plan["evaluation_plan"], + "evaluations": records, "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "results_before_terminal_states": True, + "single_writer_per_output": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, result) + os.chmod(output, 0o444) + for item in files: + os.chmod(item["absolute_path"], 0o444) + return result + + +def fetch_release(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", plan["source_host"], + "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + timeout=float(plan["ssh_timeout_seconds"]), + ) + if result.returncode: + raise NotReady("server_new evaluation completion release is unavailable") + try: + value = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise ValueError("server_new evaluation completion release is unreadable") from error + return value + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + files = release.get("files", []) + paths = [item.get("path") for item in files] + _, workers = remote_inventory(plan) + expected_ids = { + identifier for worker in workers for identifier in worker["evaluation_ids"] + } + records = release.get("evaluations", []) + record_ids = [item.get("evaluation_id") for item in records] + kind_counts = Counter(item.get("kind") for item in files) + if ( + release.get("schema_version") + != "phase9_resolution_evaluation_completion_release_v1" + or release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("destination_owner") != "taku3" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("evaluation_plan") != plan["evaluation_plan"] + or len(records) != 9 + or len(record_ids) != len(set(record_ids)) + or set(record_ids) != expected_ids + or len(files) != 41 or len(paths) != len(set(paths)) + or kind_counts != { + "evaluation_report": 9, "raw_predictions": 9, + "per_hand_rows": 9, "take_metrics": 9, + "worker_state": 4, "controller_state": 1, + } + or release.get("file_count") != 41 + or sum(item.get("bytes", -1) for item in files) != release.get("total_bytes") + or release.get("completion_only_reverse_release") is not True + or release.get("live_reverse_sync_performed") is not False + or release.get("results_before_terminal_states") is not True + or release.get("single_writer_per_output") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution evaluation immutable release differs") + for value in paths: + path = Path(str(value)) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"unsafe resolution evaluation release path: {path}") + file_hashes = {(item["path"], item["sha256"]) for item in files} + for record in records: + result_files = record.get("files", []) + if ( + len(result_files) != 4 + or record.get("evaluation_report_sha256") + != next( + (item["sha256"] for item in result_files + if item.get("kind") == "evaluation_report"), None, + ) + or any((item.get("path"), item.get("sha256")) not in file_hashes + for item in result_files) + ): + raise ValueError("resolution evaluation release result binding differs") + + +def verify_file(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"resolution evaluation completion file differs: {path}") + return path + + +def install_release(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root = Path(plan["release_root"]) + staging = Path(plan["staging_root"]) + pending = [] + installed = [] + for item in release["files"]: + destination = root / item["path"] + if destination.exists(): + verify_file(root, item) + installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".pending_evaluation_release_files.txt" + file_list.write_text( + "".join(item["path"] + "\n" for item in pending), encoding="utf-8", + ) + result = subprocess.run([ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['source_host']}:{root.resolve()}/", f"{staging.resolve()}/", + ], check=False) + if result.returncode: + raise RuntimeError(f"resolution evaluation rsync failed: {result.returncode}") + for item in pending: + verify_file(staging, item) + order = {"evaluation_report": 0, "raw_predictions": 0, "per_hand_rows": 0, + "take_metrics": 0, "controller_state": 1, "worker_state": 2} + for item in sorted(pending, key=lambda value: (order[value["kind"]], value["path"])): + source = staging / item["path"] + destination = root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + raise ValueError(f"resolution evaluation destination appeared: {destination}") + os.replace(source, destination) + os.chmod(destination, 0o444) + verify_file(root, item) + installed.append({**item, "resumed_existing": False}) + return sorted(installed, key=lambda item: item["path"]) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): + existing = read_json(output) + if existing.get("status") == "complete" and existing.get("plan_sha256") == sha256(plan_path): + return existing + raise ValueError("existing resolution evaluation receive state differs") + release = fetch_release(plan) + validate_release(plan_path, plan, release) + installed = install_release(plan, release) + result = { + "schema_version": "phase9_resolution_evaluation_completion_receive_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state": plan["release_state"], + "release_sha256": json_sha256(release), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "installed": installed, + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "results_before_terminal_states": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, result) + return result + + +def wait_for_result( + role: str, plan_path: Path, plan: dict[str, Any], timeout_seconds: float, +) -> dict[str, Any]: + deadline = time.monotonic() + timeout_seconds + watcher_path = Path( + f"{plan['release_state' if role == 'publish' else 'receive_state']}.watcher.json" + ) + while True: + try: + return publish(plan_path, plan) if role == "publish" else receive(plan_path, plan) + except NotReady as error: + if timeout_seconds <= 0 or time.monotonic() >= deadline: + raise + atomic_json(watcher_path, { + "schema_version": "phase9_resolution_evaluation_completion_watcher_v1", + "status": "waiting_for_terminal_source", "role": role, + "watcher_pid": os.getpid(), "updated_utc": utc_now(), + "detail": str(error), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "h2o_official_validation_used": False, "official_test_used": False, + }) + time.sleep(min(30.0, max(1.0, deadline - time.monotonic()))) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = wait_for_result( + args.role, args.plan, plan, args.wait_timeout_seconds, + ) + except Exception as error: + atomic_json(Path(f"{target}.failure.json"), { + "schema_version": "phase9_resolution_evaluation_completion_failure_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "role": args.role, "failure": f"{type(error).__name__}: {error}", + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, "official_test_used": False, + }) + raise + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_resolution_training_completion.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_resolution_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..34c74406bf5162cc0d980d780e5ef77133e4776c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_resolution_training_completion.py @@ -0,0 +1,569 @@ +#!/usr/bin/env python3 +"""Publish and import terminal server_new Stage 7 training evidence.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any +import zipfile + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +EXPECTED_CONDITIONS = ( + "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", + "S7R_J25_lofamily_k", +) +EXPECTED_STAGES = ("smoke2", "health2k", "matched_405000") + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + if ( + plan.get("schema_version") + != "phase9_resolution_training_completion_release_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("read_only_after_publish") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or scientific.get("amendment_scope") + != "terminal_state_and_final_checkpoint_handoff_only" + or any( + scientific.get(key) is not False + for key in ( + "model_changed", "data_changed", "seed_changed", + "optimizer_changed", "horizon_changed", + "selection_gate_changed", + ) + ) + ): + raise ValueError("resolution training completion plan contract differs") + if tuple(item["condition"] for item in plan.get("conditions", [])) != EXPECTED_CONDITIONS: + raise ValueError("resolution training completion conditions differ") + for key in ("release_root", "staging_root"): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution training completion {key} is not /SSD2") + if Path(plan["release_state"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution training completion release state is not /SSD2") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution completion binding differs: {path}") + if sha256(plan_path) == "": + raise ValueError("resolution completion plan is unreadable") + + +def last_json_record(path: Path, tail_bytes: int = 1 << 20) -> dict[str, Any]: + with path.open("rb") as handle: + handle.seek(0, os.SEEK_END) + size = handle.tell() + handle.seek(max(0, size - tail_bytes)) + lines = handle.read().splitlines() + for line in reversed(lines): + if line.strip(): + value = json.loads(line) + if not isinstance(value, dict): + break + return value + raise ValueError(f"terminal metric record is unavailable: {path}") + + +def validate_condition_payload( + expected: dict[str, Any], job: dict[str, Any], state: dict[str, Any], + metric: dict[str, Any], summary: dict[str, Any], +) -> None: + marker = state.get("last_completed", {}) + attempts = state.get("attempts", []) + losses = metric.get("losses", {}) + if ( + state.get("status") != "complete" + or state.get("condition") != expected["condition"] + or state.get("queue_sha256") != expected["training_registry_sha256"] + or state.get("official_test_used") is not False + or tuple(state.get("completed_stages", [])) != EXPECTED_STAGES + or tuple(item.get("stage") for item in attempts) != EXPECTED_STAGES + or any(item.get("returncode") != 0 for item in attempts) + or marker.get("status") != "complete" + or marker.get("stage") != "matched_405000" + or marker.get("completed_step") != 405000 + or marker.get("checkpoint") != expected["checkpoint"] + or marker.get("checkpoint_sha256") != expected["checkpoint_sha256"] + or marker.get("config") != job["config"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or metric.get("step") != 405000 + or not isinstance(losses, dict) + or not losses + or any( + not isinstance(value, (int, float)) or not math.isfinite(float(value)) + for value in losses.values() + ) + or summary.get("status") != "completed" + or summary.get("completed_step") != 405000 + or summary.get("protocol_max_steps") != 405000 + or summary.get("registered_run_end_step") != 405000 + or summary.get("final_checkpoint") != expected["checkpoint"] + or summary.get("final_checkpoint_sha256") != expected["checkpoint_sha256"] + or summary.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or summary.get("official_test_used") is not False + ): + raise ValueError( + f"resolution terminal training evidence differs: {expected['condition']}" + ) + + +def writer_matches(command: str, output_dir: str) -> bool: + return ( + "scripts.train_phase7_external" in command + and f"--output-dir {output_dir}" in command + ) + + +def active_writer_pids(output_dir: str, proc_root: Path = Path("/proc")) -> list[int]: + result = [] + for entry in proc_root.iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (FileNotFoundError, PermissionError, UnicodeDecodeError, ProcessLookupError): + continue + if writer_matches(command, output_dir): + result.append(int(entry.name)) + return sorted(result) + + +def verify_checkpoint_archive(path: Path) -> None: + if not zipfile.is_zipfile(path): + raise ValueError(f"resolution final checkpoint archive differs: {path}") + with zipfile.ZipFile(path) as archive: + if not archive.namelist() or archive.testzip() is not None: + raise ValueError(f"resolution final checkpoint is truncated: {path}") + + +def validate_source_completion(plan: dict[str, Any]) -> list[dict[str, Any]]: + assignment = load_assignment(plan) + registry_path = Path(plan["training_registry"]["path"]) + registry = read_json(registry_path) + if sha256(registry_path) != plan["training_registry"]["sha256"]: + raise ValueError("resolution completion registry hash differs") + jobs = {item["condition"]: item for item in registry["conditions"]} + owners = condition_owners(registry, assignment) + controller_path = Path(plan["source_controller_state"]["path"]) + controller = read_json(controller_path) + if ( + sha256(controller_path) != plan["source_controller_state"]["sha256"] + or controller.get("status") != "complete_local" + or controller.get("machine") != "server_new" + or controller.get("plan_sha256") + != plan["training_controller_plan"]["sha256"] + or controller.get("training_registry_sha256") + != plan["training_registry"]["sha256"] + or controller.get("condition_statuses") + != {condition: "complete" for condition in EXPECTED_CONDITIONS} + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new resolution controller completion differs") + + records = [] + root = Path(plan["release_root"]) + for expected in plan["conditions"]: + condition = expected["condition"] + if condition not in jobs or owners.get(condition) != "server_new": + raise ValueError(f"resolution completion ownership differs: {condition}") + job = jobs[condition] + config = Path(job["config"]) + state_path = Path(expected["state"]) + checkpoint = Path(expected["checkpoint"]) + metrics = Path(expected["metrics"]) + summary_path = Path(expected["summary"]) + for path in (state_path, checkpoint, metrics, summary_path, config): + if not path.is_file() or path.is_symlink(): + raise ValueError(f"resolution terminal artifact differs: {path}") + if ( + sha256(config) != job["config_sha256"] + or sha256(state_path) != expected["state_sha256"] + or checkpoint.stat().st_size != expected["checkpoint_bytes"] + or sha256(checkpoint) != expected["checkpoint_sha256"] + or sha256(metrics) != expected["metrics_sha256"] + or sha256(summary_path) != expected["summary_sha256"] + ): + raise ValueError(f"resolution terminal artifact hash differs: {condition}") + if active_writer_pids(job["output_dir"]): + raise ValueError(f"resolution output still has a writer: {condition}") + state = read_json(state_path) + metric = last_json_record(metrics) + summary = read_json(summary_path) + validate_condition_payload(expected, job, state, metric, summary) + verify_checkpoint_archive(checkpoint) + condition_files = [] + for kind, path in (("checkpoint", checkpoint), ("training_state", state_path)): + if root not in path.parents: + raise ValueError(f"resolution release file is outside root: {path}") + condition_files.append({ + "kind": kind, + "path": str(path.relative_to(root)), + "absolute_path": str(path.resolve()), + "bytes": path.stat().st_size, + "sha256": sha256(path), + }) + records.append({ + "condition": condition, + "role": job["role"], + "completed_utc": state["completed_utc"], + "gpu_hours": state["gpu_hours_consumed"], + "wall_seconds": marker_wall_seconds(state), + "final_total_loss": float(metric["losses"]["total"]), + "metrics_sha256": expected["metrics_sha256"], + "summary_sha256": expected["summary_sha256"], + "checkpoint_archive_crc_verified": True, + "active_writer_pids": [], + "files": condition_files, + }) + return records + + +def marker_wall_seconds(state: dict[str, Any]) -> float: + marker = state.get("last_completed", {}) + value = marker.get("wall_seconds") + if not isinstance(value, (int, float)) or not math.isfinite(float(value)): + raise ValueError("resolution terminal wall time differs") + return float(value) + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + existing = read_json(output) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution completion release differs") + conditions = validate_source_completion(plan) + files = [item for condition in conditions for item in condition["files"]] + paths = [item["path"] for item in files] + if len(paths) != 6 or len(set(paths)) != 6: + raise ValueError("resolution completion release inventory differs") + release = { + "schema_version": "phase9_resolution_training_completion_release_v1", + "status": "complete_immutable_release", + "created_utc": utc_now(), + "owner": "server_new", + "destination_owner": "taku3", + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "release_root": str(Path(plan["release_root"]).resolve()), + "source_controller_state": plan["source_controller_state"], + "conditions": conditions, + "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "read_only_after_publish": True, + "single_writer_per_output": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(output, release) + os.chmod(output, 0o444) + for item in files: + os.chmod(Path(item["absolute_path"]), 0o444) + return release + + +def fetch_remote_json(host: str, path: str, timeout: float) -> dict[str, Any]: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if result.returncode: + raise ValueError("resolution completion release is unavailable") + try: + value = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise ValueError("resolution completion release is unreadable") from error + if not isinstance(value, dict): + raise ValueError("resolution completion release is not an object") + return value + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + files = release.get("files", []) + paths = [item.get("path") for item in files] + if ( + release.get("schema_version") + != "phase9_resolution_training_completion_release_v1" + or release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("destination_owner") != "taku3" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("completion_only_reverse_release") is not True + or release.get("live_reverse_sync_performed") is not False + or release.get("read_only_after_publish") is not True + or release.get("single_writer_per_output") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or len(files) != 6 + or len(paths) != len(set(paths)) + or release.get("file_count") != 6 + or sum(item.get("bytes", -1) for item in files) != release.get("total_bytes") + ): + raise ValueError("resolution completion immutable release differs") + expected = { + (item["state_sha256"], item["checkpoint_sha256"]) + for item in plan["conditions"] + } + observed = { + ( + next(file["sha256"] for file in item["files"] if file["kind"] == "training_state"), + next(file["sha256"] for file in item["files"] if file["kind"] == "checkpoint"), + ) + for item in release.get("conditions", []) + } + if expected != observed: + raise ValueError("resolution completion condition hashes differ") + for value in paths: + path = Path(str(value)) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"unsafe resolution completion release path: {path}") + + +def verify_record(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"resolution completion file differs: {path}") + return path + + +def validate_global_completion_payload( + controller: dict[str, Any], registry_sha256: str, + conditions: dict[str, dict[str, Any]], +) -> None: + expected = { + "S7R_J25_full", "S7R_J25_loso_subject1", "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", "S7R_J25_lofamily_h", + "S7R_J25_lofamily_k", "S7R_J25_lofamily_o", + } + if ( + controller.get("status") != "complete" + or controller.get("machine") != "taku3" + or controller.get("training_registry_sha256") != registry_sha256 + or controller.get("condition_statuses") + != {condition: "complete" for condition in sorted(expected)} + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + or set(conditions) != expected + or any( + state.get("status") != "complete" + or state.get("queue_sha256") != registry_sha256 + or state.get("last_completed", {}).get("completed_step") != 405000 + or state.get("official_test_used") is not False + for state in conditions.values() + ) + ): + raise ValueError("global resolution training completion differs") + + +def install_release(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root = Path(plan["release_root"]) + staging = Path(plan["staging_root"]) + pending = [] + installed = [] + for item in release["files"]: + destination = root / item["path"] + if destination.exists(): + verify_record(root, item) + installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".pending_release_files.txt" + file_list.write_text( + "".join(item["path"] + "\n" for item in pending), encoding="utf-8", + ) + result = subprocess.run([ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['source_host']}:{root.resolve()}/", f"{staging.resolve()}/", + ], check=False) + if result.returncode: + raise RuntimeError(f"resolution completion rsync failed: {result.returncode}") + for item in pending: + verify_record(staging, item) + for kind in ("checkpoint", "training_state"): + for item in pending: + if item["kind"] != kind: + continue + source = staging / item["path"] + destination = root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + raise ValueError(f"resolution completion destination appeared: {destination}") + os.replace(source, destination) + os.chmod(destination, 0o444) + verify_record(root, item) + installed.append({**item, "resumed_existing": False}) + return sorted(installed, key=lambda item: item["path"]) + + +def backup_central_controller(plan: dict[str, Any]) -> dict[str, str]: + source = Path(plan["central_controller_state"]) + destination = Path(plan["central_controller_backup"]) + if destination.exists(): + return {"path": str(destination.resolve()), "sha256": sha256(destination)} + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + os.chmod(destination, 0o444) + return {"path": str(destination.resolve()), "sha256": sha256(destination)} + + +def wait_for_global_completion(plan: dict[str, Any]) -> dict[str, Any]: + deadline = time.monotonic() + float(plan["central_completion_timeout_seconds"]) + registry_hash = plan["training_registry"]["sha256"] + state_root = Path(plan["training_state_root"]) + while time.monotonic() < deadline: + controller = read_json(plan["central_controller_state"]) + registry = read_json(plan["training_registry"]["path"]) + states = { + item["condition"]: read_json( + state_root / f"{item['condition'].lower()}.json" + ) + for item in registry["conditions"] + } + try: + validate_global_completion_payload(controller, registry_hash, states) + except ValueError: + time.sleep(2) + continue + return controller + raise TimeoutError("central resolution training controller did not converge") + + +def receive(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + if state_path.is_file(): + existing = read_json(state_path) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution completion receive state differs") + release = fetch_remote_json( + plan["source_host"], plan["release_state"], + float(plan["ssh_timeout_seconds"]), + ) + validate_release(plan_path, plan, release) + backup = backup_central_controller(plan) + installed = install_release(plan, release) + controller = wait_for_global_completion(plan) + result = { + "schema_version": "phase9_resolution_training_completion_receive_v1", + "status": "complete", + "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "release_state": plan["release_state"], + "release_sha256": sha256_bytes(release), + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + "installed": installed, + "central_controller_backup": backup, + "central_controller_state": { + "path": str(Path(plan["central_controller_state"]).resolve()), + "sha256": sha256(plan["central_controller_state"]), + "status": controller["status"], + }, + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(state_path, result) + return result + + +def sha256_bytes(value: dict[str, Any]) -> str: + import hashlib + payload = (json.dumps(value, indent=2) + "\n").encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--state", type=Path) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + expected = Path( + plan["release_state"] if args.role == "publish" else plan["receive_state"] + ) + if args.state and args.state.resolve() != expected.resolve(): + parser.error("resolution completion state path differs") + expected.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{expected}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = publish(args.plan, plan) if args.role == "publish" else receive( + args.plan, plan, expected, + ) + except Exception as error: + failure = Path(f"{expected}.failure.json") + atomic_json(failure, { + "schema_version": "phase9_resolution_training_completion_failure_v1", + "status": "failed_resumable", + "updated_utc": utc_now(), + "role": args.role, + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used": False, + "official_test_used": False, + }) + raise + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_resolution_training_handoff.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_resolution_training_handoff.py new file mode 100644 index 0000000000000000000000000000000000000000..e55e92fce4239842ceb0765c72f32f3d506032e7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_resolution_training_handoff.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Publish central Stage 7 readiness and registry to server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +import subprocess +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + unchanged_fields = ( + "model_changed", + "data_changed", + "seed_changed", + "optimizer_changed", + "horizon_changed", + "selection_gate_changed", + ) + if ( + plan.get("schema_version") + != "phase9_resolution_distributed_training_handoff_amendment_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "taku3" + or plan.get("destination_owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("readiness_published_last") is not True + or plan.get("immutable_sync") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("server_new_physical_gpu_allowlist") != [0, 1, 2, 5] + or plan.get("external_owned_conditions") != [ + "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", + "S7R_J25_lofamily_k", + ] + or scientific.get("amendment_scope") + != "resource_scheduling_and_immutable_handoff_only" + or any(scientific.get(field) is not False for field in unchanged_fields) + ): + raise ValueError("resolution training handoff plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution training handoff binding differs: {path}") + + +def ordered_handoff_files(plan: dict[str, Any]) -> list[dict[str, Any]]: + records = list(plan["files"]) + if ( + not records or records[-1].get("role") != "readiness" + or any(item.get("role") == "readiness" for item in records[:-1]) + or len({item["path"] for item in records}) != len(records) + ): + raise ValueError("resolution readiness must be published uniquely and last") + return records + + +def remote_sha256(host: str, path: str) -> str | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "sha256sum", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode or not completed.stdout.strip(): + return None + return completed.stdout.split()[0] + + +def prepare_remote_parent(host: str, path: str) -> None: + parent = str(Path(path).parent) + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "mkdir", "-p", parent], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode: + detail = completed.stderr.strip() or f"returncode={completed.returncode}" + raise ValueError(f"cannot prepare resolution handoff parent {parent}: {detail}") + + +def validate_remote_cache_receive(plan: dict[str, Any]) -> None: + item = plan["remote_cache_receive_state"] + if remote_sha256(plan["destination_host"], item["path"]) != item["sha256"]: + raise ValueError("server_new cache receive state hash differs") + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", plan["destination_host"], "cat", item["path"]], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode: + raise ValueError("server_new cache receive state is unreadable") + try: + state = json.loads(completed.stdout) + except json.JSONDecodeError as error: + raise ValueError("server_new cache receive state is unreadable") from error + if ( + state.get("status") != "complete" + or state.get("file_count") != item["file_count"] + or state.get("total_bytes") != item["total_bytes"] + or state.get("read_only") is not True + or state.get("live_reverse_sync_performed") is not False + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new cache receive state contract differs") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(plan) + records = ordered_handoff_files(plan) + validate_remote_cache_receive(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("resolution training handoff state differs") + if args.state.is_file(): + existing = read_json(args.state) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == sha256(args.plan) + ): + print(json.dumps(existing, indent=2)) + return + parser.error("existing resolution training handoff state differs") + published = [] + for item in records: + source = Path(item["path"]) + if not source.is_file() or sha256(source) != item["sha256"]: + parser.error(f"resolution handoff source differs: {source}") + try: + prepare_remote_parent(plan["destination_host"], str(source.resolve())) + except ValueError as error: + parser.error(str(error)) + completed = subprocess.run([ + "rsync", "-a", "--chmod=F444", str(source.resolve()), + f"{plan['destination_host']}:{source.resolve()}", + ], check=False) + if completed.returncode: + raise SystemExit(completed.returncode) + if remote_sha256(plan["destination_host"], str(source.resolve())) != item["sha256"]: + parser.error(f"resolution handoff remote hash differs: {source}") + published.append(item) + state = { + "schema_version": "phase9_resolution_training_handoff_state_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "destination": plan["destination_host"], "published": published, + "readiness_published_last": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_shared_augmentation_admission.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_shared_augmentation_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c3d14120047c2df37a4932378ce275eb8da7e8 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_shared_augmentation_admission.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Forward-sync frozen Stage 8 admission and start the remote owner controller.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def admission_files(plan: dict[str, Any]) -> tuple[list[Path], list[dict[str, str]]]: + controller_path = Path(plan["controller_states"]["taku3"]) + if not controller_path.is_file(): + raise NotReady("central Stage 8 controller state is missing") + controller = read_json(controller_path) + registry_path = Path(plan["training_registry"]) + if not registry_path.is_file() or not controller.get("training_registry_sha256"): + raise NotReady("central Stage 8 registry is not frozen yet") + if ( + controller.get("plan_sha256") != sha256(plan_path_from_state(controller)) + or controller.get("training_registry") != str(registry_path.resolve()) + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("central Stage 8 controller binding differs") + registry = read_json(registry_path) + assignment = load_assignment(plan) + owners = condition_owners(registry, assignment) + conditions = registry.get("conditions", []) + if ( + registry.get("status") != "frozen_ready" + or len(conditions) != 7 + or len({item["condition"] for item in conditions}) != 7 + or sum(owner == "server_new" for owner in owners.values()) != 3 + or registry.get("official_test_used") is not False + or registry.get("h2o_official_validation_used_for_selection") is not False + ): + raise ValueError("Stage 8 training registry contract differs") + resolution_state = Path(plan["resolution_controller_state"]) + state = read_json(resolution_state) + decision = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != plan["resolution_controller_plan_sha256"] + or not decision.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(decision) + or state.get("official_test_used") is not False + ): + raise ValueError("Stage 8 resolution admission binding differs") + files = [ + decision, resolution_state, Path(plan["registry_builder_state"]), + *[Path(item["config"]) for item in conditions], registry_path, + ] + for path in files: + if not path.is_file(): + raise ValueError(f"Stage 8 admission file is missing: {path}") + prerequisites = [] + seen = set() + for item in conditions: + pair = (item["initialization_checkpoint"], item["initialization_checkpoint_sha256"]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + for item in registry["data_artifacts"]: + pair = (item["path"], item["sha256"]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + return files, prerequisites + + +def plan_path_from_state(state: dict[str, Any]) -> Path: + path = Path(state.get("plan", "")) + if not path.is_file(): + raise ValueError("Stage 8 controller plan is missing") + return path + + +def remote_sha256(host: str, path: Path) -> str | None: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "sha256sum", str(path)], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, check=False, + ) + return result.stdout.split()[0] if result.returncode == 0 else None + + +def install_file(host: str, path: Path) -> dict[str, Any]: + digest = sha256(path) + observed = remote_sha256(host, path) + if observed is not None: + if observed != digest: + raise ValueError(f"remote Stage 8 admission destination differs: {path}") + return {"path": str(path.resolve()), "sha256": digest, "resumed_existing": True} + temporary = Path(f"{path}.incoming-stage8-v3") + mkdir = subprocess.run( + ["ssh", host, "mkdir", "-p", str(path.parent)], check=False, + ) + if mkdir.returncode: + raise RuntimeError(f"remote Stage 8 admission mkdir failed: {path.parent}") + copied = subprocess.run( + ["rsync", "-a", str(path), f"{host}:{temporary}"], check=False, + ) + if copied.returncode or remote_sha256(host, temporary) != digest: + raise RuntimeError(f"remote Stage 8 admission staging differs: {path}") + installed = subprocess.run( + ["ssh", host, "mv", str(temporary), str(path)], check=False, + ) + if installed.returncode or remote_sha256(host, path) != digest: + raise RuntimeError(f"remote Stage 8 admission install differs: {path}") + return {"path": str(path.resolve()), "sha256": digest, "resumed_existing": False} + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/controller_logs/server_new_training.log" + command = ( + "cd /home/jiasen/foundation_hand && mkdir -p " + str(Path(log).parent) + + " && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_shared_augmentation_training_controller --plan " + + str(plan_path.resolve()) + " --state " + state + + " --machine server_new --poll-seconds 30 >> " + log + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", plan["source_host"], command], check=False) + if result.returncode: + raise RuntimeError("remote Stage 8 controller launch failed") + time.sleep(2) + probe = subprocess.run( + ["ssh", plan["source_host"], "pgrep", "-fo", + "scripts.run_phase9_shared_augmentation_training_controller.*shared_augmentation_v3.*server_new.json"], + stdout=subprocess.PIPE, text=True, check=False, + ) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote Stage 8 controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + files, prerequisites = admission_files(plan) + host = plan["source_host"] + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"local Stage 8 prerequisite differs: {path}") + if remote_sha256(host, path) != item["sha256"]: + raise ValueError(f"remote Stage 8 immutable prerequisite differs: {path}") + registry = Path(plan["training_registry"]) + installed = [] + for path in [item for item in files if item != registry] + [registry]: + installed.append(install_file(host, path)) + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_shared_augmentation_admission_sync_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "installed": installed, "immutable_prerequisites": prerequisites, + "remote_controller_pid": pid, + "registry_installed_last": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args() + plan = read_json(args.plan) + plan["source_host"] = "server_new" + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan) + atomic_json(args.state, result) + print(json.dumps(result, indent=2)) + return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: + raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_admission_sync_v1", + "status": "waiting_for_frozen_registry", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, "official_test_used": False, + }) + time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_shared_augmentation_evaluation_admission.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_shared_augmentation_evaluation_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..77f49003f8c121544b93407abc20a771830f37e0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_shared_augmentation_evaluation_admission.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Forward-sync the frozen Stage 8 evaluation plan to server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def frozen_payload(plan: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, str]]]: + dynamic_path = Path(plan["evaluation_plan"]) + central_state = Path(plan["controller_states"]["taku3"]) + if not dynamic_path.is_file() or not central_state.is_file(): + raise NotReady("central Stage 8 evaluation plan is not frozen yet") + state = read_json(central_state) + dynamic = read_json(dynamic_path) + if not state.get("evaluation_plan_sha256"): + raise NotReady("central Stage 8 evaluation controller has not admitted the plan") + if ( + state.get("plan_sha256") != sha256(Path(state["plan"])) + or state.get("evaluation_plan") != str(dynamic_path.resolve()) + or state.get("evaluation_plan_sha256") != sha256(dynamic_path) + or len(dynamic.get("evaluations", [])) != 25 + or len(dynamic.get("workers", [])) != 10 + or dynamic.get("worker_heartbeat_seconds") != 30 + or dynamic.get("stall_timeout_seconds") != 900 + or dynamic.get("official_test_used") is not False + ): + raise ValueError("Stage 8 evaluation admission binding differs") + remote_ids = { + identifier for worker in dynamic["workers"] if worker["owner"] == "server_new" + for identifier in worker["evaluation_ids"] + } + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + if len(remote_ids) != 9: + raise ValueError("Stage 8 remote evaluation ownership differs") + prerequisites = [] + seen = set() + for identifier in sorted(remote_ids): + item = evaluations[identifier] + for path_key, hash_key in ( + ("config", "config_sha256"), ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256"), + ): + pair = (item[path_key], item[hash_key]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + return dynamic, prerequisites + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/controller_logs/server_new_evaluation.log" + command = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_shared_augmentation_evaluation_controller --plan " + + str(plan_path.resolve()) + " --state " + state + + " --machine server_new --poll-seconds 30 >> " + log + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: + raise RuntimeError("remote Stage 8 evaluation controller launch failed") + time.sleep(2) + probe = subprocess.run([ + "ssh", "server_new", "pgrep", "-fo", + "scripts.run_phase9_shared_augmentation_evaluation_controller.*shared_augmentation_v3.*server_new.json", + ], stdout=subprocess.PIPE, text=True, check=False) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote Stage 8 evaluation controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + _, prerequisites = frozen_payload(plan) + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"central Stage 8 evaluation prerequisite differs: {path}") + if remote_sha256("server_new", path) != item["sha256"]: + raise ValueError(f"remote Stage 8 evaluation prerequisite differs: {path}") + dynamic = Path(plan["evaluation_plan"]) + files = [ + Path(plan["training_controller_state"]), Path(plan["evaluation_plan_state"]), + dynamic, + ] + installed = [install_file("server_new", path) for path in files[:-1]] + installed.append(install_file("server_new", dynamic)) + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_shared_augmentation_evaluation_admission_sync_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "evaluation_plan_sha256": sha256(dynamic), "installed": installed, + "immutable_prerequisites": prerequisites, "evaluation_plan_installed_last": True, + "remote_controller_pid": pid, "official_test_used": False, + "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_evaluation_admission_sync_v1", + "status": "waiting_for_frozen_evaluation_plan", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "plan_sha256": sha256(args.plan), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_shared_augmentation_training_completion.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_shared_augmentation_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..8c94bcfcd6549c3e5607171cb2a612bd1d6b3b3e --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_shared_augmentation_training_completion.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Completion-only server_new to taku3 handoff for Stage 8 training.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_resolution_training_completion import ( + active_writer_pids, + last_json_record, + verify_checkpoint_archive, +) + + +EXPECTED = ( + "S8A_J25_loso_subject2", "S8A_J25_loso_subject3", "S8A_J25_lofamily_k", +) + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: dict[str, Any]) -> str: + return hashlib.sha256((json.dumps(value, indent=2) + "\n").encode()).hexdigest() + + +def validate_plan(path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("schema_version") + != "phase9_shared_augmentation_training_completion_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or tuple(plan.get("conditions", [])) != EXPECTED + or plan.get("target_step") != 405000 + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("Stage 8 training completion plan contract differs") + for key in ("release_root", "staging_root", "release_state", "receive_state"): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"Stage 8 completion {key} is not /SSD2") + for binding in plan["bindings"]: + candidate = Path(binding["path"]) + if not candidate.is_file() or sha256(candidate) != binding["sha256"]: + raise ValueError(f"Stage 8 completion binding differs: {candidate}") + if not path.is_file(): + raise ValueError("Stage 8 completion plan is unreadable") + + +def registry_payload(plan: dict[str, Any]) -> tuple[Path, dict[str, Any], dict[str, Any]]: + path = Path(plan["training_registry"]["path"]) + if not path.is_file() or sha256(path) != plan["training_registry"]["sha256"]: + raise ValueError("Stage 8 training registry hash differs") + registry = read_json(path) + owners = condition_owners(registry, load_assignment(plan)) + jobs = {item["condition"]: item for item in registry["conditions"]} + if ( + registry.get("status") != "frozen_ready" + or registry.get("target_step") != 405000 + or tuple(condition for condition in jobs if owners[condition] == "server_new") + != EXPECTED + or registry.get("official_test_used") is not False + ): + raise ValueError("Stage 8 training registry contract differs") + return path, registry, jobs + + +def validate_terminal(job: dict[str, Any], state: dict[str, Any]) -> tuple[Path, dict[str, Any]]: + marker = state.get("last_completed", {}) + checkpoint = Path(marker.get("checkpoint", "")) + metrics = Path(job["output_dir"]) / "metrics.jsonl" + summary_path = Path(job["output_dir"]) / "summary.json" + if not checkpoint.is_file() or not metrics.is_file() or not summary_path.is_file(): + raise ValueError(f"Stage 8 terminal artifact is missing: {job['condition']}") + metric = last_json_record(metrics) + summary = read_json(summary_path) + losses = metric.get("losses", {}) + if ( + state.get("status") != "complete" + or state.get("condition") != job["condition"] + or marker.get("completed_step") != 405000 + or marker.get("config") != job["config"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") != job["expected_source_exposure_batches"] + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or metric.get("step") != 405000 + or not losses + or any(not isinstance(value, (int, float)) or not math.isfinite(float(value)) + for value in losses.values()) + or summary.get("status") != "completed" + or summary.get("completed_step") != 405000 + or summary.get("final_checkpoint_sha256") != marker["checkpoint_sha256"] + or summary.get("official_test_used") is not False + or state.get("official_test_used") is not False + ): + raise ValueError(f"Stage 8 terminal evidence differs: {job['condition']}") + verify_checkpoint_archive(checkpoint) + return checkpoint, {"metric": metric, "summary": summary, + "metrics_sha256": sha256(metrics), + "summary_sha256": sha256(summary_path)} + + +def file_record(root: Path, kind: str, path: Path) -> dict[str, Any]: + if not path.is_file() or path.is_symlink() or root not in path.resolve().parents: + raise ValueError(f"Stage 8 release file differs: {path}") + return {"kind": kind, "path": str(path.resolve().relative_to(root.resolve())), + "absolute_path": str(path.resolve()), "bytes": path.stat().st_size, + "sha256": sha256(path)} + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + registry_path, _, jobs = registry_payload(plan) + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): + raise NotReady("server_new Stage 8 controller state is missing") + controller = read_json(controller_path) + if controller.get("status") != "complete_local": + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("server_new Stage 8 controller failed") + raise NotReady("server_new Stage 8 training is still running") + if ( + controller.get("plan_sha256") != plan["training_controller_plan"]["sha256"] + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("condition_statuses") != {condition: "complete" for condition in EXPECTED} + or controller.get("official_test_used") is not False + ): + raise ValueError("server_new Stage 8 controller binding differs") + root = Path(plan["release_root"]) + state_root = Path(plan["training_state_root"]) + records, files = [], [] + for condition in EXPECTED: + job = jobs[condition] + state_path = state_root / f"{condition.lower()}.json" + state = read_json(state_path) + if state.get("queue_sha256") != sha256(registry_path): + raise ValueError(f"Stage 8 state registry binding differs: {condition}") + if active_writer_pids(job["output_dir"]): + raise NotReady(f"Stage 8 writer still exists: {condition}") + checkpoint, evidence = validate_terminal(job, state) + condition_files = [file_record(root, "checkpoint", checkpoint), + file_record(root, "training_state", state_path)] + files.extend(condition_files) + records.append({ + "condition": condition, "role": job["role"], + "checkpoint_sha256": sha256(checkpoint), + "final_total_loss": float(evidence["metric"]["losses"]["total"]), + "metrics_sha256": evidence["metrics_sha256"], + "summary_sha256": evidence["summary_sha256"], + "gpu_hours": state["gpu_hours_consumed"], "files": condition_files, + }) + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + value = read_json(output) + if value.get("status") == "complete_immutable_release" and value.get("plan_sha256") == sha256(plan_path): + return value + raise ValueError("existing Stage 8 release differs") + records, files = source_records(plan) + value = { + "schema_version": "phase9_shared_augmentation_training_completion_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "destination_owner": "taku3", + "plan_sha256": sha256(plan_path), "release_root": plan["release_root"], + "training_registry": plan["training_registry"], + "conditions": records, "files": files, "file_count": 6, + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, "live_reverse_sync_performed": False, + "results_before_terminal_states": True, "single_writer_per_output": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, value) + os.chmod(output, 0o444) + for item in files: + os.chmod(item["absolute_path"], 0o444) + return value + + +def fetch(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run(["ssh", plan["source_host"], "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, check=False) + if result.returncode: + raise NotReady("server_new Stage 8 release is unavailable") + return json.loads(result.stdout) + + +def validate_release(plan_path: Path, plan: dict[str, Any], value: dict[str, Any]) -> None: + files = value.get("files", []) + if ( + value.get("schema_version") != "phase9_shared_augmentation_training_completion_release_v1" + or value.get("status") != "complete_immutable_release" + or value.get("plan_sha256") != sha256(plan_path) + or value.get("training_registry") != plan["training_registry"] + or tuple(item.get("condition") for item in value.get("conditions", [])) != EXPECTED + or len(files) != 6 or len({item.get("path") for item in files}) != 6 + or sum(item.get("bytes", -1) for item in files) != value.get("total_bytes") + or value.get("results_before_terminal_states") is not True + or value.get("official_test_used") is not False + ): + raise ValueError("Stage 8 immutable release differs") + + +def verify(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if (not path.is_file() or path.is_symlink() or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"]): + raise ValueError(f"Stage 8 completion file differs: {path}") + return path + + +def install(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root, staging = Path(plan["release_root"]), Path(plan["staging_root"]) + pending, installed = [], [] + for item in release["files"]: + if (root / item["path"]).exists(): + verify(root, item); installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + listing = staging / ".pending_stage8_files.txt" + listing.write_text("".join(item["path"] + "\n" for item in pending), encoding="utf-8") + result = subprocess.run(["rsync", "-a", "--partial", f"--files-from={listing}", + f"{plan['source_host']}:{root}/", f"{staging}/"], check=False) + if result.returncode: + raise RuntimeError("Stage 8 completion rsync failed") + for item in pending: verify(staging, item) + for kind in ("checkpoint", "training_state"): + for item in pending: + if item["kind"] != kind: continue + source, destination = staging / item["path"], root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination); os.chmod(destination, 0o444) + verify(root, item); installed.append({**item, "resumed_existing": False}) + return installed + + +def central_complete(plan: dict[str, Any]) -> bool: + path = Path(plan["central_controller_state"]) + if not path.is_file(): return False + value = read_json(path) + return (value.get("status") == "complete" + and value.get("training_registry_sha256") == plan["training_registry"]["sha256"] + and value.get("official_test_used") is False) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): return read_json(output) + release = fetch(plan); validate_release(plan_path, plan, release) + backup = Path(plan["central_controller_backup"]) + if not backup.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(plan["central_controller_state"], backup); os.chmod(backup, 0o444) + installed = install(plan, release) + deadline = time.monotonic() + plan["central_completion_timeout_seconds"] + while time.monotonic() < deadline and not central_complete(plan): time.sleep(2) + if not central_complete(plan): raise TimeoutError("central Stage 8 controller did not converge") + value = { + "schema_version": "phase9_shared_augmentation_training_completion_receive_v1", + "status": "complete", "completed_utc": utc_now(), + "plan_sha256": sha256(plan_path), "release_sha256": json_sha256(release), + "file_count": 6, "total_bytes": release["total_bytes"], "installed": installed, + "results_before_terminal_states": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, value); return value + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + try: validate_plan(args.plan, plan) + except ValueError as error: parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True) + deadline = time.monotonic() + args.wait_timeout_seconds + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + value = publish(args.plan, plan) if args.role == "publish" else receive(args.plan, plan) + print(json.dumps(value, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(Path(f"{target}.watcher.json"), { + "schema_version": "phase9_shared_augmentation_training_completion_watcher_v1", + "status": "waiting_for_terminal_source", "role": args.role, + "watcher_pid": os.getpid(), "updated_utc": utc_now(), "detail": str(error), + "plan_sha256": sha256(args.plan), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_taku_resolution_caches.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_taku_resolution_caches.py new file mode 100644 index 0000000000000000000000000000000000000000..84cb358bfea905f09ef6978f46deff950973aab4 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/sync_phase9_taku_resolution_caches.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python3 +"""Publish and install Taku3-owned Stage 7 caches on server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("source_owner") != "taku3" + or plan.get("destination_owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("live_reverse_sync_forbidden") is not True + ): + raise ValueError("Taku3 cache sync plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"Taku3 cache sync binding differs: {path}") + root = Path(plan["release_root"]) + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("Taku3 cache sync root is not /SSD2") + for item in plan["artifacts"]: + path = Path(item["path"]) + if root not in path.parents: + raise ValueError(f"Taku3 cache artifact is outside release root: {path}") + + +def known_payload_hashes(manifests: list[str]) -> dict[Path, str]: + known: dict[Path, str] = {} + hash_fields = ( + ("cache_path", "cache_sha256"), + ("joint3d_root_relative_sidecar_path", "joint3d_root_relative_sidecar_sha256"), + ) + for value in manifests: + for line in Path(value).read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + row = json.loads(line) + for path_field, hash_field in hash_fields: + if row.get(path_field) and row.get(hash_field): + path = Path(row[path_field]).resolve() + digest = row[hash_field] + previous = known.setdefault(path, digest) + if previous != digest: + raise ValueError(f"conflicting manifest payload hash: {path}") + return known + + +def inventory_artifacts( + root: Path, artifacts: list[dict[str, Any]], known: dict[Path, str], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + files: list[dict[str, Any]] = [] + artifact_records = [] + seen: set[str] = set() + for item in artifacts: + artifact = Path(item["path"]) + if not artifact.exists() or artifact.is_symlink(): + raise ValueError(f"Taku3 cache artifact differs: {artifact}") + candidates = [artifact] if artifact.is_file() else sorted(artifact.rglob("*")) + start = len(files) + for path in candidates: + if path.is_symlink(): + raise ValueError(f"Taku3 cache release refuses symlink: {path}") + if not path.is_file(): + continue + relative = str(path.relative_to(root)) + if relative in seen: + raise ValueError(f"duplicate Taku3 cache release path: {relative}") + seen.add(relative) + digest = known.get(path.resolve()) + if digest is None: + digest = sha256(path) + files.append({ + "path": relative, "sha256": digest, "bytes": path.stat().st_size, + }) + selected = files[start:] + artifact_records.append({ + "id": item["id"], "path": str(artifact.resolve()), + "relative_path": str(artifact.relative_to(root)), + "kind": "file" if artifact.is_file() else "directory", + "file_count": len(selected), + "total_bytes": sum(record["bytes"] for record in selected), + }) + return files, artifact_records + + +def validate_readiness(plan: dict[str, Any]) -> dict[str, Any]: + path = Path(plan["readiness_state"]["path"]) + state = read_json(path) + audit = Path(state.get("audit", {}).get("path", "")) + if ( + state.get("status") != "complete" + or sha256(path) != plan["readiness_state"]["sha256"] + or state.get("plan_sha256") != plan["cache_execution_plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not audit.is_file() + or state.get("audit", {}).get("sha256") != sha256(audit) + ): + raise ValueError("Taku3 cache release readiness differs") + return state + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + readiness = validate_readiness(plan) + output = Path(plan["release_state"]) + if output.is_file(): + release = read_json(output) + if ( + release.get("status") == "complete_immutable_release" + and release.get("plan_sha256") == sha256(plan_path) + ): + return release + raise ValueError("existing Taku3 cache release differs") + root = Path(plan["release_root"]) + known = known_payload_hashes(plan["payload_manifests"]) + files, artifacts = inventory_artifacts(root, plan["artifacts"], known) + release = { + "schema_version": "phase9_taku_cache_immutable_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "taku3", "destination_owner": "server_new", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_root": str(root.resolve()), + "readiness_state": { + "path": str(Path(plan["readiness_state"]["path"]).resolve()), + "sha256": plan["readiness_state"]["sha256"], + "audit": readiness["audit"], + }, + "artifacts": artifacts, "files": files, "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "payload_hash_source": "globally_audited_cache_and_sidecar_manifests", + "read_only_after_publish": True, "live_reverse_sync_forbidden": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, release) + os.chmod(output, 0o444) + for item in plan["artifacts"]: + path = Path(item["path"]) + if path.is_file(): + os.chmod(path, 0o444) + continue + for candidate in path.rglob("*"): + os.chmod(candidate, 0o555 if candidate.is_dir() else 0o444) + os.chmod(path, 0o555) + return release + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != "taku3" + or release.get("destination_owner") != "server_new" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("read_only_after_publish") is not True + or release.get("live_reverse_sync_forbidden") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or len(release.get("files", [])) != release.get("file_count") + or sum(item["bytes"] for item in release["files"]) != release.get("total_bytes") + ): + raise ValueError("Taku3 cache immutable release differs") + paths = [item["path"] for item in release["files"]] + if len(paths) != len(set(paths)) or any( + Path(path).is_absolute() or ".." in Path(path).parts for path in paths + ): + raise ValueError("Taku3 cache release paths differ") + + +def push(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + release = read_json(plan["release_state"]) + validate_release(plan_path, plan, release) + file_list = Path(plan["push_file_list"]) + file_list.parent.mkdir(parents=True, exist_ok=True) + file_list.write_text( + "".join(item["path"] + "\n" for item in release["files"]), + encoding="utf-8", + ) + state = { + "schema_version": "phase9_taku_cache_push_state_v1", + "status": "syncing", "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state_sha256": sha256(plan["release_state"]), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "destination": plan["destination_host"], + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, state) + staging = Path(plan["destination_staging_root"]) + command = [ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{Path(plan['release_root']).resolve()}/", + f"{plan['destination_host']}:{staging.resolve()}/", + ] + completed = subprocess.run(command, check=False) + state["returncode"] = completed.returncode + state["updated_utc"] = utc_now() + state["status"] = "synced_waiting_for_remote_install" if not completed.returncode else "failed_resumable" + atomic_json(state_path, state) + if completed.returncode: + raise SystemExit(completed.returncode) + return state + + +def verify_files(root: Path, release: dict[str, Any]) -> None: + for item in release["files"]: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] or sha256(path) != item["sha256"] + ): + raise ValueError(f"received Taku3 cache file differs: {path}") + + +def install(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + release = read_json(plan["release_state"]) + validate_release(plan_path, plan, release) + staging = Path(plan["destination_staging_root"]) + verify_files(staging, release) + root = Path(plan["release_root"]) + installed = [] + for item in release["artifacts"]: + source = staging / item["relative_path"] + destination = root / item["relative_path"] + if destination.exists(): + raise ValueError(f"Taku3 cache destination already exists: {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination) + if destination.is_file(): + os.chmod(destination, 0o444) + else: + for path in destination.rglob("*"): + os.chmod(path, 0o555 if path.is_dir() else 0o444) + os.chmod(destination, 0o555) + installed.append(item) + state = { + "schema_version": "phase9_taku_cache_receive_state_v1", + "status": "complete", "completed_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state_sha256": sha256(plan["release_state"]), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "installed": installed, "read_only": True, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, state) + return state + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "push", "install"), required=True) + parser.add_argument("--state", type=Path) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + expected_state = { + "publish": Path(plan["release_state"]), + "push": Path(plan["push_state"]), + "install": Path(plan["destination_receive_state"]), + }[args.role] + if args.state and args.state.resolve() != expected_state.resolve(): + parser.error("Taku3 cache sync state differs") + expected_state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{expected_state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.role == "publish": + result = publish(args.plan, plan) + elif args.role == "push": + result = push(args.plan, plan, expected_state) + else: + result = install(args.plan, plan, expected_state) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/train_experiment.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/train_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..0773e54df5b6b201d2dd25e039341ea338b675c6 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/train_experiment.py @@ -0,0 +1,776 @@ +#!/usr/bin/env python3 +"""Formal H2O camera-space training entry point with hard asset/geometry gates.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import random +import shlex +import socket +import subprocess +import sys +import time +from dataclasses import asdict +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import ( + H2OCam4Dataset, + ResumableRandomBatchSampler, + ResumableWeightedBatchSampler, + collate_h2o_clips, + load_balanced_sampling_weights, +) +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.metrics import camera_metrics +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, + set_scheduled_learning_rate, +) +from foundation_hand.training.schedule import warmup_cosine_learning_rate + + +def git_state() -> str: + return subprocess.run(["git", "status", "--short"], text=True, stdout=subprocess.PIPE, check=False).stdout + + +def git_commit() -> str | None: + result = subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=False, + ) + return result.stdout.strip() or None + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def resolved_weight_path(value: str) -> Path: + path = Path(value) + return path / "model.safetensors" if path.is_dir() else path + + +def capture_run_provenance( + args: argparse.Namespace, + config: dict, + output_path: Path, +) -> Path: + assets = config["assets"] + tracked_files = { + "config": args.config, + "train_manifest": args.manifest, + "validation_manifest": args.val_manifest, + "validation_subset": args.validation_subset_manifest, + "sampling_manifest": Path(config.get("sampling", {}).get("manifest", "")), + "initialization_checkpoint": args.init_checkpoint, + "dinov3_weights": resolved_weight_path(assets["dinov3_weights"]), + "mano_left": Path(assets["mano_root"]) / "MANO_LEFT.pkl", + "mano_right": Path(assets["mano_root"]) / "MANO_RIGHT.pkl", + } + hashes = { + name: {"path": str(path.resolve()), "sha256": file_sha256(path)} + for name, path in tracked_files.items() if path is not None and path.is_file() + } + gpu_inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid,name,memory.total", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, + ).stdout.strip().splitlines() + provenance = { + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "hostname": socket.gethostname(), + "git_commit": git_commit(), + "git_status": git_state(), + "command_argv": [sys.executable, *sys.argv], + "command_shell": shlex.join([sys.executable, *sys.argv]), + "working_directory": str(Path.cwd()), + "config": config, + "seed": int(config["seed"]), + "cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "gpu_inventory": gpu_inventory, + "python": sys.version, + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "hashes": hashes, + "resume_checkpoint": str(args.resume.resolve()) if args.resume else None, + "initialization_checkpoint": ( + str(args.init_checkpoint.resolve()) if args.init_checkpoint else None + ), + } + output_path.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8") + return output_path + + +def load_validation_subset( + path: Path, + validation_manifest: Path, + data_config: dict, + dataset_size: int, +) -> tuple[list[int], dict]: + record = json.loads(path.read_text(encoding="utf-8")) + if record.get("source_manifest_sha256") != file_sha256(validation_manifest): + raise ValueError("validation subset source-manifest hash does not match --val-manifest") + contract = record.get("dataset_contract", {}) + expected = { + "resolution_hw": list(data_config["resolution_hw"]), + "T": int(data_config["T"]), + "stride": int(data_config["stride"]), + } + for key, value in expected.items(): + if contract.get(key) != value: + raise ValueError(f"validation subset contract mismatch for {key}: {contract.get(key)} != {value}") + indices = [int(index) for index in record["clip_indices"]] + if len(indices) != len(set(indices)) or not indices: + raise ValueError("validation subset indices must be non-empty and unique") + if min(indices) < 0 or max(indices) >= dataset_size: + raise ValueError("validation subset index is outside the validation dataset") + return indices, record + + +def preflight(config: dict, root: Path, manifest: Path) -> list[str]: + blockers = [] + if not root.is_dir(): blockers.append(f"dataset root missing: {root}") + if not manifest.is_file(): blockers.append(f"manifest missing: {manifest}") + assets = config.get("assets", {}) + source = Path(assets.get("dinov3_source") or "") + weights = Path(assets.get("dinov3_weights") or "") + mano_root = Path(assets.get("mano_root") or "") + if not (source / "hubconf.py").is_file(): blockers.append(f"official DINOv3 source missing: {source}") + valid_weight = weights.is_file() or (weights.is_dir() and (weights / "model.safetensors").is_file()) + if not valid_weight: blockers.append("DINOv3 pretrained weight missing; formal training forbids random DINO") + for side in ("LEFT", "RIGHT"): + if not (mano_root / f"MANO_{side}.pkl").is_file(): blockers.append(f"licensed MANO_{side}.pkl missing") + coordinate_report = Path("artifacts/phase2/coordinate_audit/mano_audit.json") + if not coordinate_report.is_file(): blockers.append("numerical MANO reconstruction/translation audit has not passed") + else: + audit = json.loads(coordinate_report.read_text(encoding="utf-8")) + if audit.get("status") != "passed": blockers.append("MANO coordinate audit exists but did not pass") + return blockers + + +def protocol_mismatches(config: dict, args: argparse.Namespace) -> list[str]: + """Reject formal runs whose CLI silently diverges from the registered config.""" + + protocol = config.get("protocol") + if protocol is None: + return [] + actual = { + "max_steps": args.max_steps, + "num_workers": args.num_workers, + "checkpoint_interval": args.checkpoint_interval, + "validation_interval": args.validation_interval, + "validation_batches": args.validation_batches, + "learning_rate": args.learning_rate, + "min_learning_rate": args.min_learning_rate, + "warmup_steps": args.warmup_steps, + "early_stopping_patience": args.early_stopping_patience, + } + mismatches = [ + f"protocol {key}={protocol.get(key)} but CLI resolved {value}" + for key, value in actual.items() if protocol.get(key) != value + ] + if "lr_schedule_steps" in protocol: + resolved_schedule_steps = ( + args.max_steps if args.lr_schedule_steps is None else args.lr_schedule_steps + ) + if protocol["lr_schedule_steps"] != resolved_schedule_steps: + mismatches.append( + "protocol lr_schedule_steps=" + f"{protocol['lr_schedule_steps']} but CLI resolved {resolved_schedule_steps}" + ) + registered_subset = protocol.get("validation_subset_manifest") + actual_subset = str(args.validation_subset_manifest) if args.validation_subset_manifest else None + if registered_subset != actual_subset: + mismatches.append( + f"protocol validation_subset_manifest={registered_subset} but CLI resolved {actual_subset}" + ) + return mismatches + + +def attach_gt_vertices(batch: dict[str, torch.Tensor], model: BimanualReconstructionModel) -> None: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for formal geometry supervision") + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, _ = model.mano_layer(rotations, torch.nan_to_num(batch["mano_shape"]), torch.nan_to_num(batch["wrist_root_translation"])) + valid = ( + batch.get("vertices_valid", batch["mano_annotation_valid"]).bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where(valid, vertices, torch.full_like(vertices, torch.nan)) + + +def move_to_device(batch: dict, device: torch.device) -> dict: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def photometric_diagnostics(batch: dict[str, torch.Tensor]) -> dict[str, float]: + parameters = batch.get("photometric_aug_params") + if parameters is None: + return {} + values = parameters[batch["frame_valid"].bool()] + if values.numel() == 0: + return {} + return { + "applied_fraction": float(values[:, 0].mean()), + "brightness_mean": float(values[:, 1].mean()), + "contrast_mean": float(values[:, 2].mean()), + "saturation_mean": float(values[:, 3].mean()), + "hue_mean": float(values[:, 4].mean()), + } + + +def run_validation( + model: BimanualReconstructionModel, + criterion: BimanualLoss, + loader: DataLoader, + device: torch.device, + dtype: torch.dtype, + max_batches: int, +) -> dict[str, dict[str, float]]: + """Run a bounded deterministic validation pass without changing train RNG.""" + + was_training = model.training + model.eval() + loss_values: dict[str, list[float]] = {} + metric_values: dict[str, list[float]] = {} + with torch.inference_mode(): + for batch_index, batch in enumerate(loader): + if batch_index >= max_batches: + break + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + for key, value in losses.items(): + scalar = float(value) + if math.isfinite(scalar): + loss_values.setdefault(key, []).append(scalar) + for key, value in camera_metrics(prediction, batch).items(): + if math.isfinite(value): + metric_values.setdefault(key, []).append(value) + model.train(was_training) + return { + "losses": {key: sum(values) / len(values) for key, values in loss_values.items()}, + "metrics": {key: sum(values) / len(values) for key, values in metric_values.items()}, + } + + +def validation_state_from_log(path: Path, metric: str) -> tuple[float, int]: + if not path.is_file(): + return float("inf"), 0 + best = float("inf") + no_improvement = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + record = json.loads(line) + value = record.get("metrics", {}).get(metric) + if value is not None and math.isfinite(value): + if float(value) < best: + best = float(value) + no_improvement = 0 + else: + no_improvement += 1 + return best, no_improvement + + +def attention_diagnostics(prediction: dict, batch: dict) -> dict[str, float | None]: + attention = prediction.get("attention", {}) + frame_valid = batch["frame_valid"].bool() + result: dict[str, float | None] = {} + if "rgb_cross_attention" in attention: + weights = attention["rgb_cross_attention"][:, -1] + left, right = weights[..., 0, :], weights[..., 1, :] + result["rgb_attention_same_peak_fraction"] = float( + (left.argmax(-1) == right.argmax(-1))[frame_valid].float().mean() + ) + result["rgb_attention_left_right_cosine"] = float( + torch.nn.functional.cosine_similarity(left, right, dim=-1)[frame_valid].mean() + ) + if "depth_fusion_gate" in attention: + result["depth_gate_mean"] = float(attention["depth_fusion_gate"][:, -1][frame_valid].float().mean()) + result["depth_gate_raw_mean"] = float(attention["depth_fusion_gate_raw"][:, -1][frame_valid].float().mean()) + result["gated_depth_update_norm_mean"] = float( + attention["gated_depth_update_norm"][:, -1][frame_valid].float().mean() + ) + if "temporal_attention" in attention: + weights = attention["temporal_attention"][:, -1] + entropy_values = [] + for batch_index in range(weights.shape[0]): + valid_indices = torch.where(frame_valid[batch_index])[0] + if valid_indices.numel() <= 1: + continue + selected = weights[batch_index, :, valid_indices][:, :, valid_indices].float() + selected = selected / selected.sum(dim=-1, keepdim=True).clamp_min(1e-8) + entropy = -(selected * selected.clamp_min(1e-8).log()).sum(dim=-1) / math.log(valid_indices.numel()) + entropy_values.append(entropy.mean()) + result["temporal_attention_normalized_entropy"] = ( + float(torch.stack(entropy_values).mean()) if entropy_values else None + ) + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--val-manifest", type=Path) + parser.add_argument("--validation-subset-manifest", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--max-steps", type=int, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--checkpoint-interval", type=int, default=100) + parser.add_argument("--learning-rate", type=float, default=1e-4) + parser.add_argument("--min-learning-rate", type=float) + parser.add_argument("--lr-schedule-steps", type=int) + parser.add_argument("--warmup-steps", type=int, default=0) + parser.add_argument("--depth-gate-warmup-steps", type=int, default=0) + parser.add_argument("--validation-interval", type=int, default=500) + parser.add_argument("--validation-batches", type=int, default=32) + parser.add_argument("--max-minutes", type=float) + parser.add_argument("--early-stopping-patience", type=int, default=0) + args = parser.parse_args() + if args.checkpoint_interval <= 0: + parser.error("--checkpoint-interval must be positive") + if args.validation_interval <= 0: + parser.error("--validation-interval must be positive") + if args.validation_batches <= 0: + parser.error("--validation-batches must be positive") + if args.max_minutes is not None and args.max_minutes <= 0: + parser.error("--max-minutes must be positive") + if args.early_stopping_patience < 0: + parser.error("--early-stopping-patience must be non-negative") + if args.resume is not None and args.init_checkpoint is not None: + parser.error("--resume and --init-checkpoint are mutually exclusive") + lr_schedule_steps = ( + args.max_steps if args.lr_schedule_steps is None else args.lr_schedule_steps + ) + if not 0 < lr_schedule_steps <= args.max_steps: + parser.error("--lr-schedule-steps must be in (0, max-steps]") + if not 0 <= args.warmup_steps < lr_schedule_steps: + parser.error("--warmup-steps must be in [0, lr-schedule-steps)") + min_learning_rate = args.learning_rate if args.min_learning_rate is None else args.min_learning_rate + if not 0 <= min_learning_rate <= args.learning_rate: + parser.error("--min-learning-rate must be in [0, learning-rate]") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + deterministic_training = bool( + config.get("protocol", {}).get("deterministic_training", False) + ) + if deterministic_training: + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.use_deterministic_algorithms(True) + torch.backends.cudnn.benchmark = False + oracle_crop_mode = config.get("model", {}).get("oracle_crop_mode", "none") + structured_refinement = bool( + config.get("model", {}).get("structured_hand_refinement", False) + ) + mixed_projection = ( + config.get("model", {}).get( + "translation_parameterization", "direct_xyz", + ) == "mixed_projection" + ) + spatial_joint2d = ( + config.get("model", {}).get( + "joint2d_parameterization", "hand_token_linear", + ) == "spatial_heatmap" + ) + matched_control_initialization = bool( + config.get("experiment", {}).get("matched_control_initialization", False) + ) + residual_initialization = ( + oracle_crop_mode != "none" or structured_refinement + or mixed_projection or spatial_joint2d + ) + if residual_initialization and args.resume is None and args.init_checkpoint is None: + parser.error("registered residual training requires --init-checkpoint on a new run") + if ( + not residual_initialization + and not matched_control_initialization + and args.init_checkpoint is not None + ): + parser.error( + "--init-checkpoint is restricted to registered residual or matched-control runs" + ) + if args.init_checkpoint is not None: + if not args.init_checkpoint.is_file(): + parser.error(f"initialization checkpoint missing: {args.init_checkpoint}") + expected_init_hash = config.get("experiment", {}).get("coarse_checkpoint_sha256") + actual_init_hash = file_sha256(args.init_checkpoint) + if expected_init_hash != actual_init_hash: + parser.error( + "initialization checkpoint hash mismatch: " + f"{actual_init_hash} != {expected_init_hash}" + ) + protocol_errors = protocol_mismatches(config, args) + if protocol_errors: + parser.error("; ".join(protocol_errors)) + if args.validation_subset_manifest is not None and args.val_manifest is None: + parser.error("--validation-subset-manifest requires --val-manifest") + if args.output_dir.exists() and any(args.output_dir.iterdir()) and args.resume is None: + parser.error("--output-dir must be new or empty unless --resume is provided") + args.output_dir.mkdir(parents=True, exist_ok=True) + blockers = preflight(config, args.root, args.manifest) + if args.val_manifest is not None and not args.val_manifest.is_file(): + blockers.append(f"validation manifest missing: {args.val_manifest}") + if args.validation_subset_manifest is not None and not args.validation_subset_manifest.is_file(): + blockers.append(f"validation subset manifest missing: {args.validation_subset_manifest}") + if blockers: + result = {"status": "blocked_preflight", "config": str(args.config), "blockers": blockers, "timestamp": datetime.now(timezone.utc).isoformat()} + (args.output_dir / "BLOCKED.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + raise SystemExit(2) + + provenance_name = "run_provenance.json" if args.resume is None else f"resume_provenance_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json" + provenance_path = capture_run_provenance(args, config, args.output_dir / provenance_name) + sampling_config = config.get("sampling", {"mode": "uniform"}) + sampling_mode = str(sampling_config.get("mode", "uniform")) + if sampling_mode not in {"uniform", "balanced"}: + parser.error(f"unsupported sampling mode: {sampling_mode}") + checkpoint_context = { + "config": config, + "external_frozen_backbone": config["assets"]["dinov3_weights"], + "sampler": ( + "global_step_weighted_v1" if sampling_mode == "balanced" + else "global_step_seeded_v1" + ), + "git_commit": git_commit(), + "run_provenance": str(provenance_path), + "run_provenance_sha256": file_sha256(provenance_path), + "initialization_checkpoint": ( + { + "path": str(args.init_checkpoint.resolve()), + "sha256": file_sha256(args.init_checkpoint), + } + if args.init_checkpoint is not None else None + ), + } + + seed = int(config["seed"]); random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + data_config, model_values, assets = config["data"], config["model"], config["assets"] + photometric_config = data_config.get("photometric_augmentation") + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + photometric_augmentation=photometric_config, + augmentation_seed=seed, + oracle_crop_enabled=oracle_crop_mode != "none", + ) + model_config = ModelConfig(**model_values, dinov3_source=assets["dinov3_source"], dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"]) + device = torch.device("cuda") + model = BimanualReconstructionModel(model_config).to(device) + initialization_record = None + if args.init_checkpoint is not None: + allowed_missing_prefixes = ( + (("oracle_crop_",) if oracle_crop_mode != "none" else ()) + + (("structured_",) if structured_refinement else ()) + + (("mixed_log_tz_head",) if mixed_projection else ()) + + (("joint_localization_",) if spatial_joint2d else ()) + ) + initialization_record = load_model_initialization( + args.init_checkpoint, model, + allowed_missing_prefixes=allowed_missing_prefixes, map_location=device, + require_residual=residual_initialization, + ) + checkpoint_context["initialization_checkpoint"].update({ + "source_step": initialization_record["step"], + "residual_missing_keys": initialization_record["residual_missing_keys"], + "checkpoint_excluded_prefixes": initialization_record[ + "checkpoint_excluded_prefixes" + ], + }) + if mixed_projection: + model.initialize_mixed_log_tz_from_direct_head() + checkpoint_context["initialization_checkpoint"].update({ + "mixed_log_tz_initialization": ( + "first-order log-softplus linearization of frozen direct-z head" + ), + "direct_xyz_teacher_frozen": True, + }) + loss_config = LossConfig(**config.get("loss", {})) + criterion = BimanualLoss(loss_config).to(device) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, + learning_rate=args.learning_rate, + backbone_learning_rate=config.get("protocol", {}).get( + "backbone_learning_rate" + ), + ), + lr=args.learning_rate, + weight_decay=0.05, + ) + excluded_checkpoint_prefixes = checkpoint_excluded_prefixes(model) + start_step = 0 + if args.resume: + start_step = int(load_checkpoint(args.resume, model, optimizer, device)["step"]) + set_scheduled_learning_rate(optimizer, args.learning_rate) + sampling_manifest_record = None + if sampling_mode == "balanced": + sampling_manifest = sampling_config.get("manifest") + if not sampling_manifest: + raise ValueError("balanced sampling requires sampling.manifest") + weights, sampling_manifest_record = load_balanced_sampling_weights( + sampling_manifest, args.manifest, data_config, len(dataset), + ) + batch_sampler = ResumableWeightedBatchSampler( + weights, int(data_config["batch_size"]), seed, start_step, args.max_steps, + include_epoch=photometric_config is not None, + ) + else: + batch_sampler = ResumableRandomBatchSampler( + len(dataset), int(data_config["batch_size"]), seed, start_step, args.max_steps, + include_epoch=photometric_config is not None, + ) + loader_generator = torch.Generator().manual_seed(seed + 10_000_000) + loader = DataLoader( + dataset, batch_sampler=batch_sampler, generator=loader_generator, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + val_loader = None + val_dataset_size = 0 + val_evaluated_samples = 0 + validation_subset_record = None + if args.val_manifest is not None: + val_dataset = H2OCam4Dataset( + args.root, args.val_manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + oracle_crop_enabled=oracle_crop_mode != "none", + ) + val_dataset_size = len(val_dataset) + if args.validation_subset_manifest is not None: + validation_indices, validation_subset_record = load_validation_subset( + args.validation_subset_manifest, args.val_manifest, data_config, len(val_dataset), + ) + expected_batches = math.ceil(len(validation_indices) / int(data_config["batch_size"])) + if args.validation_batches != expected_batches: + raise ValueError( + f"--validation-batches must be {expected_batches} to evaluate the complete fixed subset" + ) + val_evaluated_samples = len(validation_indices) + else: + val_evaluated_samples = min( + len(val_dataset), args.validation_batches * int(data_config["batch_size"]), + ) + validation_generator = torch.Generator().manual_seed(seed + 20_000_000) + validation_indices = torch.randperm( + len(val_dataset), generator=validation_generator, + )[:val_evaluated_samples].tolist() + validation_subset = Subset(val_dataset, validation_indices) + val_loader = DataLoader( + validation_subset, batch_size=int(data_config["batch_size"]), shuffle=False, + generator=torch.Generator().manual_seed(seed + 30_000_000), + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + log_path = args.output_dir / "train_metrics.jsonl" + validation_log_path = args.output_dir / "validation.jsonl" + best_metric_name = "absolute_camera_mpjpe_mm" + best_metric, no_improvement_validations = validation_state_from_log(validation_log_path, best_metric_name) + best_z_metric_name = "translation_z_mae_mm" + best_z_metric, _ = validation_state_from_log(validation_log_path, best_z_metric_name) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + completed_step = start_step + processed_frames = 0 + last_validation_step = -1 + stopped_for_time = False + stopped_for_early_stopping = False + for step, batch in zip(range(start_step, args.max_steps), loader, strict=True): + if args.max_minutes is not None and time.perf_counter() - started >= args.max_minutes * 60: + stopped_for_time = True + break + batch = move_to_device(batch, device) + processed_frames += int(batch["frame_valid"].sum()) + learning_rate = warmup_cosine_learning_rate( + step, lr_schedule_steps, args.learning_rate, min_learning_rate, + args.warmup_steps, + ) + set_scheduled_learning_rate(optimizer, learning_rate) + optimizer.zero_grad(set_to_none=True) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_diagnostics = criterion.translation_diagnostics(prediction, batch) + if not torch.isfinite(losses["total"]): + raise FloatingPointError(f"NaN/Inf loss at step {step}") + losses["total"].backward() + depth_gate_warmup_active = step < args.depth_gate_warmup_steps + if depth_gate_warmup_active: + for name, parameter in model.named_parameters(): + if ".depth_gate." in name: + parameter.grad = None + grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) + if not torch.isfinite(grad_norm): + raise FloatingPointError(f"NaN/Inf gradient at step {step}") + optimizer.step() + completed_step = step + 1 + record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": step + 1, "seed": seed, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "loss_diagnostics": { + key: float(value.detach()) for key, value in loss_diagnostics.items() + }, + "metrics": camera_metrics(prediction, batch), "gradient_norm": float(grad_norm), + "diagnostics": attention_diagnostics(prediction, batch), + "photometric_augmentation": photometric_diagnostics(batch), + "learning_rate": learning_rate, + "depth_gate_warmup_active": depth_gate_warmup_active, + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "frames_per_s": processed_frames / (time.perf_counter() - started), + } + with log_path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(record) + "\n") + if completed_step % args.checkpoint_interval == 0: + save_checkpoint( + args.output_dir / f"step_{completed_step:07d}.pt", model, optimizer, completed_step, + checkpoint_context, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if val_loader is not None and completed_step % args.validation_interval == 0: + validation = run_validation(model, criterion, val_loader, device, dtype, args.validation_batches) + validation_record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": completed_step, + "batches": args.validation_batches, **validation, + } + with validation_log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(validation_record) + "\n") + last_validation_step = completed_step + current_metric = validation["metrics"].get(best_metric_name, float("inf")) + current_z_metric = validation["metrics"].get(best_z_metric_name, float("inf")) + if current_metric < best_metric: + best_metric = current_metric + no_improvement_validations = 0 + save_checkpoint( + args.output_dir / "best.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_metric_name: best_metric}, "checkpoint_role": "best_absolute"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + else: + no_improvement_validations += 1 + if current_z_metric < best_z_metric: + best_z_metric = current_z_metric + save_checkpoint( + args.output_dir / "best_z.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_z_metric_name: best_z_metric}, "checkpoint_role": "best_z"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if args.early_stopping_patience and no_improvement_validations >= args.early_stopping_patience: + stopped_for_early_stopping = True + break + if val_loader is not None and completed_step > 0 and last_validation_step != completed_step: + validation = run_validation(model, criterion, val_loader, device, dtype, args.validation_batches) + validation_record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": completed_step, + "batches": args.validation_batches, **validation, + } + with validation_log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(validation_record) + "\n") + current_metric = validation["metrics"].get(best_metric_name, float("inf")) + current_z_metric = validation["metrics"].get(best_z_metric_name, float("inf")) + if current_metric < best_metric: + best_metric = current_metric + save_checkpoint( + args.output_dir / "best.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_metric_name: best_metric}, "checkpoint_role": "best_absolute"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if current_z_metric < best_z_metric: + best_z_metric = current_z_metric + save_checkpoint( + args.output_dir / "best_z.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_z_metric_name: best_z_metric}, "checkpoint_role": "best_z"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + final_checkpoint = args.output_dir / f"step_{completed_step:07d}_final.pt" + save_checkpoint( + final_checkpoint, model, optimizer, completed_step, + {**checkpoint_context, "checkpoint_role": "final"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + summary = { + "status": ( + "stopped_early_validation" if stopped_for_early_stopping else + "stopped_time_budget" if stopped_for_time else "completed" + ), + "config": config, "model_config": asdict(model_config), "loss_config": asdict(loss_config), + "seed": seed, "dataset_clips": len(dataset), "validation_manifest": str(args.val_manifest) if args.val_manifest else None, + "validation_dataset_clips": val_dataset_size, "validation_evaluated_samples": val_evaluated_samples, + "validation_sampling": ( + validation_subset_record.get("version") if validation_subset_record is not None else + "fixed_seed_uniform_random_subset_v1" if val_loader is not None else None + ), + "validation_subset_manifest": str(args.validation_subset_manifest.resolve()) if args.validation_subset_manifest else None, + "run_provenance": str(provenance_path), + "initialization": checkpoint_context["initialization_checkpoint"], + "start_step": start_step, "completed_step": completed_step, "requested_max_steps": args.max_steps, + "elapsed_minutes": (time.perf_counter() - started) / 60, + "sampler": checkpoint_context["sampler"], + "sampling_manifest": ( + str(Path(sampling_config["manifest"]).resolve()) + if sampling_manifest_record is not None else None + ), + "learning_rate_schedule": { + "name": "warmup_cosine_clamped", "base_lr": args.learning_rate, + "min_lr": min_learning_rate, "warmup_steps": args.warmup_steps, + "total_steps": lr_schedule_steps, + "training_max_steps": args.max_steps, + "backbone_lr_scale": next( + ( + float(group["lr_scale"]) + for group in optimizer.param_groups + if group.get("group_name") == "dinov3_backbone" + ), + None, + ), + "deterministic_training": deterministic_training, + }, + "best_validation": {best_metric_name: best_metric if math.isfinite(best_metric) else None}, + "best_z_validation": {best_z_metric_name: best_z_metric if math.isfinite(best_z_metric) else None}, + "best_z_checkpoint": str(args.output_dir / "best_z.pt") if (args.output_dir / "best_z.pt").is_file() else None, + "early_stopping_patience": args.early_stopping_patience, + "validation_checks_without_improvement": no_improvement_validations, + "best_checkpoint": str(args.output_dir / "best.pt") if (args.output_dir / "best.pt").is_file() else None, + "final_checkpoint": str(final_checkpoint), "git_status": git_state(), + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "frames_per_s": processed_frames / max(time.perf_counter() - started, 1e-6), + "precision": config["precision"], "gpu": torch.cuda.get_device_name(device), + "trainable_parameters": sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad), + "frozen_parameters": sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad), + } + (args.output_dir / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/scripts/train_phase7_external.py b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/train_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..fba61b4edae8c4636a2bb46343fa410e3885120a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/scripts/train_phase7_external.py @@ -0,0 +1,1316 @@ +#!/usr/bin/env python3 +"""External-only Phase 7 training over hash-bound unified clip caches.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import copy +from dataclasses import asdict +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import random +import shlex +import socket +import subprocess +import sys +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import ( + CachedUnifiedClipDataset, + ResumableMixtureBatchSampler, + UnifiedConcatDataset, + collate_h2o_clips, +) +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint, save_checkpoint +from foundation_hand.training.metrics import camera_metrics +from foundation_hand.training.optimizer import ( + clear_staged_later_gradients, + checkpoint_excluded_prefixes, + optimizer_parameter_groups, + set_scheduled_learning_rate, + set_staged_parameter_group_phase, + staged_optimizer_parameter_groups, +) +from foundation_hand.training.schedule import warmup_cosine_learning_rate +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +PHASE9_H2O_TRAIN_MANIFESTS = { + "full_data_640": Path( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "h2o_official_train7000_v1/cache_manifest.jsonl" + ), + "resolution_896x512": Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/h2o_train7000/cache_manifest.jsonl" + ), +} +PHASE9_H2O_TRAIN_MANIFESTS.update({ + "shared_augmentation_640": PHASE9_H2O_TRAIN_MANIFESTS["full_data_640"], + "shared_augmentation_896x512": PHASE9_H2O_TRAIN_MANIFESTS[ + "resolution_896x512" + ], +}) +PHASE9_H2O_FOLD_ROOTS = { + "full_data_640": Path("artifacts/phase9/manifests/h2o_multifold_v1"), + "resolution_896x512": Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "manifests/h2o_multifold_v1" + ), +} +PHASE9_H2O_FOLD_ROOTS.update({ + "shared_augmentation_640": PHASE9_H2O_FOLD_ROOTS["full_data_640"], + "shared_augmentation_896x512": PHASE9_H2O_FOLD_ROOTS[ + "resolution_896x512" + ], +}) +PHASE9_DATASETS = ("H2O", "HOT3D", "HOI4D", "ARCTIC") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def git_output(*arguments: str) -> str: + return subprocess.run( + ["git", *arguments], text=True, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=False, + ).stdout.strip() + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def assert_physical_gpu_idle(physical_gpu_id: int) -> None: + """Fail before CUDA allocation if another compute process owns the GPU.""" + + inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ).stdout.splitlines() + mapping = { + int(line.split(",", 1)[0].strip()): line.split(",", 1)[1].strip() + for line in inventory if line.strip() + } + if physical_gpu_id not in mapping: + raise RuntimeError(f"physical GPU {physical_gpu_id} is not present") + compute = subprocess.run( + [ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid,process_name", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ).stdout.splitlines() + owners = [line for line in compute if line.split(",", 1)[0].strip() == mapping[physical_gpu_id]] + if owners: + raise RuntimeError( + f"physical GPU {physical_gpu_id} is not idle: " + "; ".join(owners) + ) + + +def claim_physical_gpu(physical_gpu_id: int) -> bool: + """Atomically reserve an idle GPU across FoundationHand queue processes.""" + + path = Path(f"/tmp/foundation_hand_{os.getuid()}_gpu{physical_gpu_id}.claim") + owner = os.getpid() + while True: + try: + descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + try: + recorded = int(path.read_text(encoding="ascii").strip()) + except (OSError, ValueError): + recorded = -1 + if recorded == owner: + return True + try: + os.kill(recorded, 0) + except (OSError, ValueError): + try: + path.unlink() + except FileNotFoundError: + pass + continue + return False + else: + with os.fdopen(descriptor, "w", encoding="ascii") as handle: + handle.write(f"{owner}\n") + return True + + +def release_physical_gpu_claim(physical_gpu_id: int) -> None: + """Release a claim owned by this process after a failed stability check.""" + + path = Path(f"/tmp/foundation_hand_{os.getuid()}_gpu{physical_gpu_id}.claim") + try: + if int(path.read_text(encoding="ascii").strip()) == os.getpid(): + path.unlink() + except (FileNotFoundError, OSError, ValueError): + return + + +def contains_h2o(value: str) -> bool: + return any(part.lower() == "h2o" for part in Path(value).parts) + + +def load_cache_rows(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def validate_external_contract(config: dict[str, Any], config_path: Path) -> list[str]: + errors: list[str] = [] + experiment = config.get("experiment", {}) + if int(experiment.get("phase", -1)) not in {7, 8}: + errors.append("external-only experiment.phase must be 7 or 8") + if experiment.get("branch") != "external_only": + errors.append("experiment.branch must be external_only") + if experiment.get("uses_h2o_training_data") is not False: + errors.append("uses_h2o_training_data must be explicitly false") + if config.get("model", {}).get("dinov3_trainable_last_blocks", 0) != 0: + errors.append("Phase 7 external screen requires frozen DINO") + if float(config.get("model", {}).get("modality_dropout_prob", 0.0)) != 0.0: + errors.append("model modality dropout is frame-wise; use source clip dropout instead") + sources = config.get("data", {}).get("sources", []) + if not sources: + errors.append("at least one external source is required") + source_ids: set[str] = set() + for source in sources: + name = str(source.get("dataset", "")) + source_id = str(source.get("source_id", name)) + if source_id in source_ids: + errors.append(f"duplicate external source_id: {source_id}") + source_ids.add(source_id) + manifest = str(source.get("cache_manifest", "")) + if name.upper() not in {"HOT3D", "HOI4D", "ARCTIC"}: + errors.append(f"unsupported external source: {name}") + if contains_h2o(manifest) or name.upper() == "H2O": + errors.append(f"H2O source forbidden in external-only training: {manifest}") + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"source weight must be positive: {name}") + if name.upper() == "HOT3D" and float(source.get("K_input_dropout", -1)) != 0.3: + errors.append("HOT3D K_input_dropout must equal frozen clip-level 0.3") + if contains_h2o(str(config_path)): + errors.append("external-only config path must not be under an H2O directory") + if "initialization_checkpoint" in experiment: + errors.append("external-only configs may not define initialization_checkpoint") + return errors + + +def validate_adaptation_contract(config: dict[str, Any]) -> list[str]: + errors: list[str] = [] + experiment = config.get("experiment", {}) + if int(experiment.get("phase", -1)) not in {7, 8}: + errors.append("adaptation experiment.phase must be 7 or 8") + if experiment.get("branch") != "h2o_adaptation": + errors.append("experiment.branch must be h2o_adaptation") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("H2O adaptation must explicitly use H2O training data") + expected_init = str(experiment.get("initialization_checkpoint_sha256", "")) + if len(expected_init) != 64: + errors.append("adaptation requires a frozen initialization checkpoint SHA256") + if config.get("model", {}).get("dinov3_trainable_last_blocks", 0) != 0: + errors.append("adaptation requires frozen DINO") + if float(config.get("model", {}).get("modality_dropout_prob", 0.0)) != 0.0: + errors.append("use source clip dropout instead of frame-wise model dropout") + sources = config.get("data", {}).get("sources", []) + if not sources or not any(str(source.get("dataset", "")).upper() == "H2O" for source in sources): + errors.append("adaptation requires an H2O official-train source") + allowed = {"H2O", "HOT3D", "HOI4D", "ARCTIC"} + source_ids: set[str] = set() + for source in sources: + name = str(source.get("dataset", "")).upper() + source_id = str(source.get("source_id", name)) + if source_id in source_ids: + errors.append(f"duplicate adaptation source_id: {source_id}") + source_ids.add(source_id) + role = str(source.get("split_role", "")) + if name not in allowed: + errors.append(f"unsupported adaptation source: {name}") + if name == "H2O" and role != "official_train": + errors.append("H2O adaptation source must be official_train") + if name == "H2O" and Path(str(source.get("cache_manifest", ""))).name != "train_fit.jsonl": + errors.append("H2O adaptation training requires frozen train_fit.jsonl") + if name != "H2O" and role != "external_train": + errors.append(f"external replay source must be external_train: {name}") + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"source weight must be positive: {name}") + if name == "HOT3D" and float(source.get("K_input_dropout", -1)) != 0.3: + errors.append("HOT3D replay K_input_dropout must equal 0.3") + if sources and not math.isclose( + sum(float(source.get("weight", 0.0)) for source in sources), 1.0, + rel_tol=0.0, abs_tol=1e-8, + ): + errors.append("adaptation source weights must sum to one") + validation_sources = config.get("data", {}).get("validation_sources", []) + if len(validation_sources) != 1: + errors.append("adaptation requires exactly one H2O train-group-heldout source") + else: + validation = validation_sources[0] + if ( + str(validation.get("dataset", "")).upper() != "H2O" + or validation.get("split_role") != "train_group_heldout" + or Path(str(validation.get("cache_manifest", ""))).name + != "train_group_heldout.jsonl" + ): + errors.append("adaptation validation must be frozen H2O train_group_heldout.jsonl") + staged = config.get("protocol", {}).get("staged_adaptation") + if staged is not None: + prefixes = staged.get("initial_trainable_prefixes", []) + unfreeze_step = int(staged.get("unfreeze_step", -1)) + scale = float(staged.get("unfrozen_learning_rate_scale", -1.0)) + if not isinstance(prefixes, list) or not prefixes or not all( + isinstance(prefix, str) and prefix for prefix in prefixes + ): + errors.append("staged adaptation requires nonempty trainable prefixes") + if not 0 < unfreeze_step < int(config.get("protocol", {}).get("max_steps", 0)): + errors.append("staged adaptation unfreeze_step must be within training horizon") + if not 0.0 < scale <= 1.0: + errors.append("staged adaptation LR scale must be in (0, 1]") + return errors + + +def validate_h2o_neutral_control_contract(config: dict[str, Any]) -> list[str]: + """Validate the random-task-head H2O control without faking an init checkpoint.""" + + experiment = config.get("experiment", {}) + errors: list[str] = [] + if int(experiment.get("phase", -1)) != 8: + errors.append("neutral H2O control must be registered in Phase 8") + if experiment.get("branch") != "h2o_neutral_control": + errors.append("neutral H2O control branch is invalid") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("neutral H2O control must explicitly use H2O training data") + if experiment.get("neutral_task_heads") is not True: + errors.append("neutral H2O control must explicitly declare neutral_task_heads=true") + if any(key.startswith("initialization_checkpoint") for key in experiment): + errors.append("neutral H2O control forbids initialization checkpoint fields") + adaptation_view = copy.deepcopy(config) + adaptation_view["experiment"].update({ + "phase": 7, + "branch": "h2o_adaptation", + "initialization_checkpoint_sha256": "0" * 64, + }) + errors.extend(validate_adaptation_contract(adaptation_view)) + sources = config.get("data", {}).get("sources", []) + if len(sources) != 1 or str(sources[0].get("dataset", "")).upper() != "H2O": + errors.append("neutral H2O control must use only H2O official train") + return errors + + +def validate_phase9_unified_contract( + config: dict[str, Any], config_path: Path, +) -> list[str]: + """Validate the shared four-source Phase 9 direct-XYZ training contract.""" + + errors: list[str] = [] + experiment = config.get("experiment", {}) + specialization = experiment.get("data_only_amendment") == "arctic_h2o_s9_v2_20260917" + data = config.get("data", {}) + model = config.get("model", {}) + loss = config.get("loss", {}) + if int(experiment.get("phase", -1)) != 9: + errors.append("Phase 9 unified training requires experiment.phase=9") + if experiment.get("branch") != "phase9_unified": + errors.append("Phase 9 unified training requires branch=phase9_unified") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("Phase 9 unified training must declare H2O training use") + if experiment.get("h2o_official_validation_used_for_selection") is not False: + errors.append("H2O official validation must be excluded from selection") + if experiment.get("official_test_used") is not False: + errors.append("official test must be explicitly unused") + if len(str(experiment.get("initialization_checkpoint_sha256", ""))) != 64: + errors.append("Phase 9 requires a hash-bound external initialization") + if "phase9" not in {part.lower() for part in config_path.parts}: + errors.append("Phase 9 unified config must live under configs/phase9") + + phase9_stage = str(experiment.get("phase9_stage", "full_data_640")) + last2_stage = phase9_stage in {"last2_5e7", "last2_1e6"} + expected_model = { + "decoder_mode": "alternating", + "use_temporal": True, + "translation_parameterization": "direct_xyz", + "dinov3_trainable_last_blocks": 2 if last2_stage else 0, + "temporal_attention_mode": "bidirectional", + } + for key, expected in expected_model.items(): + if model.get(key) != expected: + errors.append(f"Phase 9 frozen model contract requires {key}={expected}") + if not math.isclose( + float(loss.get("joint3d_root_relative", 0.0)), + 10.0, + rel_tol=0.0, + abs_tol=1e-8, + ): + errors.append( + "Phase 9 frozen loss contract requires joint3d_root_relative=10.0" + ) + resolution = list(data.get("resolution_hw", [])) + if last2_stage: + expected_resolution = list(experiment.get("last2_resolution_hw", [])) + if expected_resolution not in ([368, 640], [512, 896]): + errors.append("Phase 9 last-2 requires a frozen 640 or 896 resolution") + h2o_contract_stage = ( + "resolution_896x512" + if expected_resolution == [512, 896] + else "full_data_640" + ) + else: + expected_resolution = { + "full_data_640": [368, 640], + "resolution_896x512": [512, 896], + "shared_augmentation_640": [368, 640], + "shared_augmentation_896x512": [512, 896], + }.get(phase9_stage) + h2o_contract_stage = phase9_stage + if expected_resolution is None: + errors.append(f"unsupported Phase 9 stage contract: {phase9_stage}") + elif resolution != expected_resolution or int(data.get("T", -1)) != 8: + errors.append( + f"Phase 9 {phase9_stage} contract requires " + f"{expected_resolution[1]}x{expected_resolution[0]} and T=8" + ) + shared_augmentation_stage = phase9_stage in { + "shared_augmentation_640", "shared_augmentation_896x512", + } or (last2_stage and experiment.get("last2_shared_augmentation") is True) + geometry = data.get("geometry_augmentation", {}) + expected_geometry = { + "enabled": True, "probability": 0.8, + "scale_min": 0.9, "scale_max": 1.1, + "translation_fraction": 0.05, + } + if shared_augmentation_stage: + if geometry != expected_geometry: + errors.append("Phase 9 shared geometry augmentation parameters differ") + elif bool(geometry.get("enabled", False)): + errors.append("Phase 9 shared geometry augmentation is not yet admitted") + if last2_stage: + if model.get("encoder") != "dinov3": + errors.append("Phase 9 last-2 requires the shared DINOv3 encoder") + if model.get("dinov3_model", "dinov3_vitb16") != "dinov3_vitb16": + errors.append("Phase 9 last-2 admits DINO Base only") + expected_backbone_lr = 5e-7 if phase9_stage == "last2_5e7" else 1e-6 + actual_backbone_lr = config.get("protocol", {}).get( + "backbone_learning_rate" + ) + if actual_backbone_lr is None or not math.isclose( + float(actual_backbone_lr), expected_backbone_lr, + rel_tol=0.0, abs_tol=1e-15, + ): + errors.append( + f"Phase 9 {phase9_stage} requires backbone learning rate " + f"{expected_backbone_lr}" + ) + elif config.get("protocol", {}).get("backbone_learning_rate") is not None: + errors.append("Phase 9 frozen-DINO stages forbid backbone learning rate") + if int(config.get("seed", -1)) != 20260717: + errors.append("Phase 9 primary seed must be 20260717") + + sources = data.get("sources", []) + names = [str(source.get("dataset", "")).upper() for source in sources] + if specialization: + if len(sources) != 2 or set(names) != {"H2O", "ARCTIC"}: + errors.append("Specialization requires exactly H2O and ARCTIC") + weights = {source["dataset"]: float(source["weight"]) for source in sources} + if not any(all(math.isclose(weights.get(k, -1), v, abs_tol=1e-10) + for k, v in pair.items()) + for pair in ({"H2O": 0.5, "ARCTIC": 0.5}, + {"H2O": 1 / 3, "ARCTIC": 2 / 3})): + errors.append("Unregistered specialization ratio") + if phase9_stage != "last2_1e6": + errors.append("Specialization must retain last2_1e6") + parent_config = Path(experiment["parent_config"]) + if sha256(parent_config) != experiment["parent_config_sha256"]: + errors.append("Parent configuration hash differs") + parent = yaml.safe_load(parent_config.read_text()) + for section in ("model", "loss", "precision"): + if config[section] != parent[section]: + errors.append(f"Specialization changed parent {section}") + expected_protocol = copy.deepcopy(parent["protocol"]) + for milestone in expected_protocol.get("source_exposure_milestones", []): + milestone["minimum_batches"] = { + k: v for k, v in milestone["minimum_batches"].items() + if k in {"H2O", "ARCTIC"} + } + if config["protocol"] != expected_protocol: + errors.append("Data-only experiment must preserve the complete Stage 9 protocol") + if {k: v for k, v in data.items() if k != "sources"} != { + k: v for k, v in parent["data"].items() if k != "sources" + }: + errors.append("Data-only experiment changed augmentation, batch size, or sequence settings") + if experiment["initialization_checkpoint_sha256"] != parent["experiment"]["initialization_checkpoint_sha256"]: + errors.append("Data-only experiment must use the same E40 initialization as Stage 9") + if config["seed"] != parent["seed"]: + errors.append("Data-only experiment changed the Stage 9 seed") + for source in sources: + original = next((s for s in parent["data"]["sources"] + if s["dataset"] == source["dataset"]), None) + if original is None: + errors.append("Unknown source in data-only experiment") + continue + if {k: v for k, v in source.items() if k != "weight"} != { + k: v for k, v in original.items() if k != "weight" + }: + errors.append(f"Specialization changed source contract: {source['dataset']}") + elif len(sources) != 4 or set(names) != set(PHASE9_DATASETS): + errors.append("Phase 9 unified training requires exactly H2O/HOT3D/HOI4D/ARCTIC") + source_ids = [str(source.get("source_id", source.get("dataset", ""))) for source in sources] + if len(set(source_ids)) != len(source_ids): + errors.append("Phase 9 sampling source IDs must be unique") + if sources and not math.isclose( + sum(float(source.get("weight", 0.0)) for source in sources), + 1.0, rel_tol=0.0, abs_tol=1e-8, + ): + errors.append("Phase 9 source weights must sum to one") + for source, name in zip(sources, names): + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"Phase 9 source weight must be positive: {name}") + expected_role = "official_train" if name == "H2O" else "external_train" + if source.get("split_role") != expected_role: + errors.append(f"Phase 9 {name} split role must be {expected_role}") + expected_k_dropout = 0.3 if name == "HOT3D" else 0.0 + if float(source.get("K_input_dropout", -1.0)) != expected_k_dropout: + errors.append(f"Phase 9 {name} K_input_dropout must equal {expected_k_dropout}") + corruption_probability = float( + source.get("depth_corruption_probability", 0.0) + ) + expected_corruption_probability = ( + 0.3 if shared_augmentation_stage and name in {"H2O", "HOI4D"} + else 0.0 + ) + if not math.isclose( + corruption_probability, expected_corruption_probability, + rel_tol=0.0, abs_tol=1e-12, + ): + errors.append( + f"Phase 9 {name} depth corruption probability must equal " + f"{expected_corruption_probability}" + ) + + selection_fold = experiment.get("h2o_selection_fold") + h2o_sources = [source for source, name in zip(sources, names) if name == "H2O"] + validation_sources = data.get("validation_sources", []) + if h2o_sources: + h2o_manifest = Path(str(h2o_sources[0].get("cache_manifest", ""))).resolve() + expected_h2o_manifest = PHASE9_H2O_TRAIN_MANIFESTS.get( + h2o_contract_stage + ) + fold_root = PHASE9_H2O_FOLD_ROOTS.get(h2o_contract_stage) + if selection_fold is None: + if ( + expected_h2o_manifest is None + or h2o_manifest != expected_h2o_manifest.resolve() + ): + errors.append( + "Phase 9 full run must use its stage-matched frozen H2O train cache" + ) + if validation_sources: + errors.append("Phase 9 full run cannot validate on leaked train subsets") + else: + if fold_root is None: + errors.append("Phase 9 fold stage has no admitted manifest root") + fold_root = Path("/__invalid_phase9_fold_root__") + expected_train = (fold_root.resolve() / f"{selection_fold}_train.jsonl") + expected_heldout = ( + fold_root.resolve() / f"{selection_fold}_heldout.jsonl" + ) + if h2o_manifest != expected_train: + errors.append("Phase 9 fold run H2O train manifest does not match its fold") + if len(validation_sources) != 1: + errors.append("Phase 9 fold run requires exactly its H2O heldout source") + elif ( + str(validation_sources[0].get("dataset", "")).upper() != "H2O" + or Path(str(validation_sources[0].get("cache_manifest", ""))).resolve() + != expected_heldout + ): + errors.append("Phase 9 fold validation manifest does not match its fold") + + valid_source_ids = set(source_ids) + milestone_ids: set[str] = set() + for milestone in config.get("protocol", {}).get("source_exposure_milestones", []): + milestone_id = str(milestone.get("id", "")) + minimum = milestone.get("minimum_batches", {}) + if not milestone_id or milestone_id in milestone_ids: + errors.append("Phase 9 exposure milestone IDs must be nonempty and unique") + milestone_ids.add(milestone_id) + if not minimum or not set(minimum).issubset(valid_source_ids): + errors.append(f"invalid source keys in exposure milestone: {milestone_id}") + if any(int(value) <= 0 for value in minimum.values()): + errors.append(f"exposure milestone counts must be positive: {milestone_id}") + return errors + + +def reached_source_exposure_milestones( + milestones: list[dict[str, Any]], + counts: Counter[str], + completed: set[str], +) -> list[str]: + reached = [] + for milestone in milestones: + milestone_id = str(milestone["id"]) + if milestone_id in completed: + continue + minimum = milestone["minimum_batches"] + if all(counts[source_id] >= int(target) for source_id, target in minimum.items()): + reached.append(milestone_id) + return reached + + +def checkpoint_context_with_exposure( + context: dict[str, Any], + source_batches: Counter[str], + source_frames: Counter[str], + depth_conditions: Counter[str], + completed_milestones: set[str], +) -> dict[str, Any]: + return { + **context, + "source_exposure_batches": dict(source_batches), + "source_exposure_frames": dict(source_frames), + "depth_input_condition_frames": dict(depth_conditions), + "completed_source_exposure_milestones": sorted(completed_milestones), + } + + +def validate_cache_manifest( + path: Path, expected_dataset: str, allow_h2o: bool = False, +) -> tuple[list[dict], list[str]]: + errors: list[str] = [] + if not path.is_file(): + return [], [f"cache manifest missing: {path}"] + rows = load_cache_rows(path) + if not rows: + errors.append(f"cache manifest is empty: {path}") + for index, row in enumerate(rows): + dataset = str(row.get("dataset_id", "")) + cache_path = Path(str(row.get("cache_path", ""))) + if dataset.upper() != expected_dataset.upper(): + errors.append(f"row {index} dataset mismatch: {dataset} != {expected_dataset}") + if not allow_h2o and ( + dataset.upper() == "H2O" or contains_h2o(str(cache_path)) + ): + errors.append(f"row {index} contains forbidden H2O data") + if not cache_path.is_file(): + errors.append(f"row {index} cache missing: {cache_path}") + if not row.get("cache_sha256"): + errors.append(f"row {index} lacks cache_sha256") + if len(errors) >= 20: + errors.append("additional cache errors omitted") + break + return rows, errors + + +def write_provenance( + output: Path, + config_path: Path, + config: dict[str, Any], + source_hashes: dict[str, str], + resume: Path | None, + initialization_checkpoint: Path | None = None, +) -> dict[str, Any]: + inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid,name,memory.total,memory.used", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, + ).stdout.strip().splitlines() + record = { + "timestamp_utc": utc_now(), + "hostname": socket.gethostname(), + "git_commit": git_output("rev-parse", "HEAD"), + "git_status": git_output("status", "--short"), + "command_argv": [sys.executable, *sys.argv], + "command_shell": shlex.join([sys.executable, *sys.argv]), + "working_directory": str(Path.cwd()), + "config_path": str(config_path.resolve()), + "config_sha256": sha256(config_path), + "config": config, + "source_manifest_sha256": source_hashes, + "resume_checkpoint": str(resume.resolve()) if resume else None, + "cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "gpu_inventory": inventory, + "python": sys.version, + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "external_only_neutral_heads": ( + config.get("experiment", {}).get("branch") == "external_only" + ), + "neutral_task_heads": ( + config.get("experiment", {}).get("branch") + in {"external_only", "h2o_neutral_control"} + ), + "initialization_checkpoint": ( + { + "path": str(initialization_checkpoint.resolve()), + "sha256": sha256(initialization_checkpoint), + } + if initialization_checkpoint is not None else None + ), + "h2o_initialization_used": False, + "h2o_training_data_used": bool( + config.get("experiment", {}).get("uses_h2o_training_data", False) + ), + "official_test_used": False, + } + name = "run_provenance.json" if resume is None else f"resume_provenance_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json" + (output / name).write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + return record + + +def source_batch_counts(batch: dict[str, Any]) -> dict[str, int]: + values = batch.get("sampling_source_id", batch.get("dataset_id", [])) + if isinstance(values, str): + values = [values] + return dict(Counter(str(value) for value in values)) + + +def source_frame_counts(batch: dict[str, Any]) -> dict[str, int]: + datasets = batch.get("sampling_source_id", batch.get("dataset_id", [])) + if isinstance(datasets, str): + datasets = [datasets] + valid = batch["frame_valid"].detach().cpu() + counts: Counter[str] = Counter() + for index, dataset in enumerate(datasets): + counts[str(dataset)] += int(valid[index].sum()) + return dict(counts) + + +def depth_input_condition_counts(batch: dict[str, Any]) -> dict[str, int]: + codes = batch.get("depth_input_condition_code") + if codes is None: + return {} + names = {0: "source_unavailable", 1: "rgb_k", 2: "clean_rgb_d_k"} + names.update({3 + index: f"corrupted_{name}" for index, name in enumerate(DEPTH_CORRUPTIONS)}) + values = codes.detach().cpu().reshape(-1).tolist() + return dict(Counter(names.get(int(value), f"unknown_{int(value)}") for value in values)) + + +def gpu_telemetry(physical_gpu_id: int) -> dict[str, float] | None: + result = subprocess.run( + [ + "nvidia-smi", f"--id={physical_gpu_id}", + "--query-gpu=utilization.gpu,memory.used", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + if result.returncode != 0 or not result.stdout.strip(): + return None + utilization, memory = result.stdout.strip().split(",")[:2] + return { + "gpu_utilization_percent": float(utilization.strip()), + "gpu_memory_used_mib": float(memory.strip()), + } + + +def run_validation( + model: BimanualReconstructionModel, + criterion: BimanualLoss, + loaders: dict[str, DataLoader], + device: torch.device, + dtype: torch.dtype, + max_batches: int, +) -> dict[str, Any]: + was_training = model.training + model.eval() + sources: dict[str, Any] = {} + with torch.inference_mode(): + for name, loader in loaders.items(): + metric_rows: list[dict[str, float]] = [] + loss_rows: list[dict[str, float]] = [] + for batch_index, batch in enumerate(loader): + if batch_index >= max_batches: + break + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + metric_rows.append(camera_metrics(prediction, batch)) + loss_rows.append({key: float(value) for key, value in losses.items()}) + sources[name] = { + "batches": len(metric_rows), + "metrics": { + key: float(np.mean([row[key] for row in metric_rows if math.isfinite(row.get(key, math.nan))])) + for key in sorted({key for row in metric_rows for key in row}) + if any(math.isfinite(row.get(key, math.nan)) for row in metric_rows) + }, + "losses": { + key: float(np.mean([row[key] for row in loss_rows if math.isfinite(row.get(key, math.nan))])) + for key in sorted({key for row in loss_rows for key in row}) + if any(math.isfinite(row.get(key, math.nan)) for row in loss_rows) + }, + } + model.train(was_training) + absolute = [ + record["metrics"]["absolute_camera_mpjpe_mm"] + for record in sources.values() + if "absolute_camera_mpjpe_mm" in record["metrics"] + ] + return { + "sources": sources, + "macro_absolute_camera_mpjpe_mm": float(np.mean(absolute)) if absolute else None, + } + + +def build_datasets( + config: dict[str, Any], seed: int, allow_h2o: bool = False, +) -> tuple[UnifiedConcatDataset, list[int], list[float], dict[str, str]]: + data = config["data"] + expected_resolution_hw = tuple(int(value) for value in data["resolution_hw"]) + datasets = [] + sizes: list[int] = [] + weights: list[float] = [] + hashes: dict[str, str] = {} + for source in data["sources"]: + manifest = Path(source["cache_manifest"]).resolve() + _, errors = validate_cache_manifest( + manifest, str(source["dataset"]), allow_h2o=allow_h2o, + ) + if errors: + raise ValueError("; ".join(errors)) + source_id = str(source.get("source_id", source["dataset"])) + if source_id in hashes: + raise ValueError(f"duplicate training source_id: {source_id}") + dataset = CachedUnifiedClipDataset( + manifest, + K_input_dropout=float(source.get("K_input_dropout", 0.0)), + dropout_seed=seed, + photometric_augmentation=data.get("photometric_augmentation"), + depth_input_dropout=float(source.get("depth_input_dropout", 0.0)), + depth_corruption_probability=float( + source.get("depth_corruption_probability", 0.0) + ), + joint3d_root_relative_scope=str( + source.get("joint3d_root_relative_scope", "auto") + ), + source_id=source_id, + expected_resolution_hw=expected_resolution_hw, + geometry_augmentation=data.get("geometry_augmentation"), + ) + datasets.append(dataset) + sizes.append(len(dataset)) + weights.append(float(source["weight"])) + hashes[source_id] = sha256(manifest) + return UnifiedConcatDataset(datasets), sizes, weights, hashes + + +def build_validation_loaders( + config: dict[str, Any], seed: int, batch_size: int, workers: int, + allow_h2o: bool = False, +) -> dict[str, DataLoader]: + loaders: dict[str, DataLoader] = {} + expected_resolution_hw = tuple( + int(value) for value in config["data"]["resolution_hw"] + ) + for source in config.get("data", {}).get("validation_sources", []): + name = str(source.get("source_id", source["dataset"])) + manifest = Path(source["cache_manifest"]).resolve() + _, errors = validate_cache_manifest( + manifest, str(source["dataset"]), allow_h2o=allow_h2o, + ) + if errors: + raise ValueError("; ".join(errors)) + dataset = CachedUnifiedClipDataset( + manifest, + K_input_dropout=float(source.get("K_input_dropout", 0.0)), + dropout_seed=seed, + joint3d_root_relative_scope=str( + source.get("joint3d_root_relative_scope", "auto") + ), + source_id=str(source.get("source_id", source["dataset"])), + expected_resolution_hw=expected_resolution_hw, + ) + loaders[name] = DataLoader( + dataset, batch_size=batch_size, shuffle=False, num_workers=workers, + persistent_workers=workers > 0, collate_fn=collate_h2o_clips, + pin_memory=True, + ) + return loaders + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument( + "--allow-physical-gpus-4-5", action="store_true", + help="Explicit resource override; default preserves the historical GPU0-3 contract.", + ) + parser.add_argument("--stop-after-step", type=int) + parser.add_argument( + "--allow-schedule-tail", action="store_true", + help="Allow external-only exact resume beyond max_steps at the clamped minimum LR.", + ) + args = parser.parse_args() + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + branch = str(config.get("experiment", {}).get("branch", "")) + if branch == "external_only": + errors = validate_external_contract(config, args.config) + if args.init_checkpoint is not None: + errors.append("external-only training forbids checkpoint initialization") + elif branch == "h2o_adaptation": + errors = validate_adaptation_contract(config) + if args.resume is None and args.init_checkpoint is None: + errors.append("new H2O adaptation requires --init-checkpoint") + if args.resume is not None and args.init_checkpoint is not None: + errors.append("--resume and --init-checkpoint are mutually exclusive") + elif branch == "h2o_neutral_control": + errors = validate_h2o_neutral_control_contract(config) + if args.init_checkpoint is not None: + errors.append("neutral H2O control forbids --init-checkpoint") + elif branch == "phase9_unified": + errors = validate_phase9_unified_contract(config, args.config) + if args.resume is None and args.init_checkpoint is None: + errors.append("new Phase 9 unified training requires --init-checkpoint") + if args.resume is not None and args.init_checkpoint is not None: + errors.append("--resume and --init-checkpoint are mutually exclusive") + else: + errors = [f"unsupported Phase 7 training branch: {branch}"] + if errors: + parser.error("; ".join(errors)) + if args.init_checkpoint is not None: + if not args.init_checkpoint.is_file(): + parser.error(f"initialization checkpoint missing: {args.init_checkpoint}") + expected = config["experiment"]["initialization_checkpoint_sha256"] + actual = sha256(args.init_checkpoint) + if actual != expected: + parser.error(f"initialization checkpoint SHA256 mismatch: {actual} != {expected}") + if args.output_dir.exists() and any(args.output_dir.iterdir()) and args.resume is None: + parser.error("--output-dir must be new or empty unless --resume is supplied") + visible = os.environ.get("CUDA_VISIBLE_DEVICES") + if visible != str(args.physical_gpu_id): + parser.error( + "CUDA_VISIBLE_DEVICES must name exactly --physical-gpu-id for auditable launch" + ) + allowed_physical_gpus = {0, 1, 2, 3} + if args.allow_physical_gpus_4_5: + allowed_physical_gpus.update((4, 5)) + if args.physical_gpu_id not in allowed_physical_gpus: + parser.error("Phase 7 may use only physical GPUs 0-3; GPU4-5 are reserved") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + protocol = config["protocol"] + max_steps = int(protocol["max_steps"]) + run_end_step = max_steps if args.stop_after_step is None else int(args.stop_after_step) + checkpoint_interval = int(protocol["checkpoint_interval"]) + validation_interval = int(protocol["validation_interval"]) + validation_batches = int(protocol["validation_batches"]) + telemetry_interval = int(protocol.get("telemetry_interval", 100)) + workers = int(protocol["num_workers"]) + batch_size = int(config["data"]["batch_size"]) + seed = int(config["seed"]) + if min(max_steps, checkpoint_interval, validation_interval, validation_batches, telemetry_interval) <= 0: + parser.error("step, checkpoint, and validation values must be positive") + if run_end_step <= 0: + parser.error("--stop-after-step must be positive") + if run_end_step > max_steps and not args.allow_schedule_tail: + parser.error("--stop-after-step exceeds protocol.max_steps without --allow-schedule-tail") + if args.allow_schedule_tail and branch != "external_only": + parser.error("--allow-schedule-tail is restricted to external-only training") + + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + allow_h2o = branch in { + "h2o_adaptation", "h2o_neutral_control", "phase9_unified", + } + train_dataset, source_sizes, source_weights, source_hashes = build_datasets( + config, seed, allow_h2o=allow_h2o, + ) + validation_loaders = build_validation_loaders( + config, seed, batch_size, workers, allow_h2o=allow_h2o, + ) + assets = config["assets"] + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + device = torch.device("cuda") + assert_physical_gpu_idle(args.physical_gpu_id) + provenance = write_provenance( + args.output_dir, args.config, config, source_hashes, args.resume, + args.init_checkpoint, + ) + model = BimanualReconstructionModel(model_config).to(device) + initialization_state = None + if args.init_checkpoint is not None: + specialization = config["experiment"].get("data_only_amendment") == "arctic_h2o_s9_v2_20260917" + if specialization: + payload = torch.load(args.init_checkpoint, map_location="cpu", weights_only=False) + if tuple(payload.get("excluded_model_prefixes", ())) != ("rgb_encoder.backbone.",): + raise RuntimeError("E40 exclusion contract differs from historical Stage 9") + missing = set(model.state_dict()) - set(payload["model"]) + if set(payload["model"]) - set(model.state_dict()): + raise RuntimeError("Unexpected E40 tensors") + if missing != {k for k in model.state_dict() if k.startswith("rgb_encoder.backbone.")}: + raise RuntimeError("E40 must supply every non-backbone tensor") + pretrained_backbone = {k: v.detach().cpu().clone() for k, v in model.state_dict().items() if k in missing} + initialization_state = load_checkpoint( + args.init_checkpoint, model, optimizer=None, map_location=device, + ) + if specialization: + if initialization_state["step"] != 200000: + raise RuntimeError("Data-only experiment must initialize from exact E40 200K") + if initialization_state["extra"].get("h2o_training_data_used") is not False: + raise RuntimeError("E40 initialization must retain no-H2O provenance") + if initialization_state["extra"].get("official_test_used") is not False: + raise RuntimeError("Parent official-test isolation is missing") + current = model.state_dict() + assert all(torch.equal(current[k].detach().cpu(), v) for k, v in payload["model"].items()) + assert all(torch.equal(current[k].detach().cpu(), v) for k, v in pretrained_backbone.items()) + composition = { + "initialization_checkpoint": str(args.init_checkpoint.resolve()), + "initialization_checkpoint_sha256": sha256(args.init_checkpoint), + "source_step": 200000, "new_stage_start_step": 0, + "loaded_non_backbone_tensors": len(payload["model"]), + "pretrained_backbone_tensors_preserved": len(pretrained_backbone), + "all_non_backbone_tensors_equal_E40": True, + "depth_and_K_reinitialized": False, + "matches_historical_stage9_initialization": True, + } + (args.output_dir / "initialization_composition.json").write_text(json.dumps(composition, indent=2) + "\n") + del payload, pretrained_backbone, current + elif initialization_state.get("extra", {}).get("h2o_training_data_used") is not False: + raise RuntimeError("adaptation initialization lacks strict no-H2O provenance") + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + learning_rate = float(protocol["learning_rate"]) + minimum_lr = float(protocol["min_learning_rate"]) + warmup_steps = int(protocol["warmup_steps"]) + staged_adaptation = protocol.get("staged_adaptation") + staged_prefixes: tuple[str, ...] = () + if staged_adaptation is not None: + staged_prefixes = tuple(staged_adaptation["initial_trainable_prefixes"]) + parameter_groups = staged_optimizer_parameter_groups( + model, + learning_rate=learning_rate, + initial_trainable_prefixes=staged_prefixes, + unfrozen_learning_rate_scale=float( + staged_adaptation["unfrozen_learning_rate_scale"] + ), + ) + else: + backbone_learning_rate = protocol.get("backbone_learning_rate") + parameter_groups = optimizer_parameter_groups( + model, + learning_rate=learning_rate, + backbone_learning_rate=( + float(backbone_learning_rate) + if backbone_learning_rate is not None else None + ), + ) + optimizer = torch.optim.AdamW( + parameter_groups, + lr=learning_rate, weight_decay=float(protocol.get("weight_decay", 0.05)), + ) + start_step = 0 + resume_extra: dict[str, Any] | None = None + if args.resume is not None: + if not args.resume.is_file(): + parser.error(f"resume checkpoint missing: {args.resume}") + state = load_checkpoint(args.resume, model, optimizer, device) + start_step = int(state["step"]) + resume_extra = state.get("extra", {}) + if resume_extra.get("config_sha256") != provenance["config_sha256"]: + raise RuntimeError("resume config hash differs from checkpoint") + if resume_extra.get("source_manifest_sha256") != source_hashes: + raise RuntimeError("resume source manifests differ from checkpoint") + set_scheduled_learning_rate(optimizer, learning_rate) + if start_step >= max_steps and not args.allow_schedule_tail: + parser.error(f"checkpoint step {start_step} is not below max_steps {max_steps}") + if start_step >= run_end_step: + parser.error( + f"checkpoint step {start_step} is not below this invocation's end step {run_end_step}" + ) + + batch_sampler = ResumableMixtureBatchSampler( + source_sizes, source_weights, batch_size, seed, start_step, run_end_step, + include_epoch=bool(config["data"].get("photometric_augmentation")), + ) + loader = DataLoader( + train_dataset, batch_sampler=batch_sampler, + generator=torch.Generator().manual_seed(seed + 10_000_000), + num_workers=workers, persistent_workers=workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + context = { + "phase": int(config.get("experiment", {}).get("phase", 7)), + "branch": branch, + "config": config, + "config_sha256": provenance["config_sha256"], + "source_manifest_sha256": source_hashes, + "h2o_training_data_used": allow_h2o, + "h2o_checkpoint_initialization_used": False, + "external_initialization_checkpoint": ( + { + "path": str(args.init_checkpoint.resolve()), + "sha256": sha256(args.init_checkpoint), + "source_step": int(initialization_state["step"]), + } + if args.init_checkpoint is not None + else ( + resume_extra.get("external_initialization_checkpoint") + if resume_extra is not None else None + ) + ), + "official_test_used": False, + "checkpoint_role": "periodic", + "schedule_tail": { + "enabled": bool(args.allow_schedule_tail), + "registered_max_steps": max_steps, + "run_end_step": run_end_step, + "learning_rate_after_horizon": minimum_lr, + }, + } + excluded = () if config["experiment"].get("data_only_amendment") else checkpoint_excluded_prefixes(model) + log_path = args.output_dir / "train_metrics.jsonl" + val_path = args.output_dir / "validation.jsonl" + started = time.perf_counter() + processed_frames = 0 + completed_step = start_step + iterator = iter(loader) + telemetry_samples: list[dict[str, float]] = [] + cumulative_source_batches: Counter[str] = Counter( + (resume_extra or {}).get("source_exposure_batches", {}) + ) + cumulative_source_frames: Counter[str] = Counter( + (resume_extra or {}).get("source_exposure_frames", {}) + ) + cumulative_depth_conditions: Counter[str] = Counter( + (resume_extra or {}).get("depth_input_condition_frames", {}) + ) + exposure_milestones = list(protocol.get("source_exposure_milestones", [])) + completed_exposure_milestones = set( + (resume_extra or {}).get("completed_source_exposure_milestones", []) + ) + torch.cuda.reset_peak_memory_stats(device) + for step in range(start_step, run_end_step): + fetch_started = time.perf_counter() + batch = next(iterator) + data_seconds = time.perf_counter() - fetch_started + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + step_source_batches = source_batch_counts(batch) + step_source_frames = source_frame_counts(batch) + step_depth_conditions = depth_input_condition_counts(batch) + cumulative_source_batches.update(step_source_batches) + cumulative_source_frames.update(step_source_frames) + cumulative_depth_conditions.update(step_depth_conditions) + processed_frames += int(batch["frame_valid"].sum()) + scheduled_lr = warmup_cosine_learning_rate( + step, max_steps, learning_rate, minimum_lr, warmup_steps, + ) + staged_later_active = bool( + staged_adaptation is not None + and step >= int(staged_adaptation["unfreeze_step"]) + ) + if staged_adaptation is not None: + set_staged_parameter_group_phase( + optimizer, active=staged_later_active, + ) + set_scheduled_learning_rate(optimizer, scheduled_lr) + optimizer.zero_grad(set_to_none=True) + forward_start = torch.cuda.Event(enable_timing=True) + forward_end = torch.cuda.Event(enable_timing=True) + backward_end = torch.cuda.Event(enable_timing=True) + forward_start.record() + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + forward_end.record() + if not torch.isfinite(losses["total"]): + raise FloatingPointError(f"non-finite loss at step {step + 1}") + losses["total"].backward() + if staged_adaptation is not None and not staged_later_active: + clear_staged_later_gradients(model, staged_prefixes) + group_norms = { + group["group_name"]: float(torch.linalg.vector_norm(torch.stack([ + p.grad.detach().float().norm() for p in group["params"] if p.grad is not None + ]))) for group in optimizer.param_groups + } + gradient_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) + if not torch.isfinite(gradient_norm): + raise FloatingPointError(f"non-finite gradient at step {step + 1}") + optimizer.step() + backward_end.record() + torch.cuda.synchronize(device) + completed_step = step + 1 + elapsed = time.perf_counter() - started + record = { + "timestamp_utc": utc_now(), + "step": completed_step, + "seed": seed, + "source_counts": step_source_batches, + "source_frame_counts": step_source_frames, + "depth_input_condition_counts": step_depth_conditions, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "metrics": camera_metrics(prediction, batch), + "gradient_norm": float(gradient_norm), + "gradient_group_norms_preclip": group_norms, + "clip_scale": min(1.0, 10.0 / (float(gradient_norm) + 1e-6)), + "optimizer_group_lrs": {g["group_name"]: g["lr"] for g in optimizer.param_groups}, + "learning_rate": scheduled_lr, + "staged_adaptation": ( + { + "later_group_active": staged_later_active, + "unfreeze_step": int(staged_adaptation["unfreeze_step"]), + "unfrozen_learning_rate_scale": float( + staged_adaptation["unfrozen_learning_rate_scale"] + ), + } + if staged_adaptation is not None else None + ), + "timing": { + "data_loading_seconds": data_seconds, + "forward_seconds": forward_start.elapsed_time(forward_end) / 1000.0, + "backward_optimizer_seconds": forward_end.elapsed_time(backward_end) / 1000.0, + "steps_per_second": (completed_step - start_step) / elapsed, + "frames_per_second": processed_frames / elapsed, + }, + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + } + if completed_step == start_step + 1 or completed_step % telemetry_interval == 0: + telemetry = gpu_telemetry(args.physical_gpu_id) + if telemetry is not None: + telemetry_samples.append(telemetry) + record["gpu_telemetry"] = telemetry + with log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + if completed_step % checkpoint_interval == 0: + save_checkpoint( + args.output_dir / f"step_{completed_step:07d}.pt", + model, optimizer, completed_step, + checkpoint_context_with_exposure( + context, cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + newly_reached = reached_source_exposure_milestones( + exposure_milestones, cumulative_source_batches, + completed_exposure_milestones, + ) + for milestone_id in newly_reached: + completed_exposure_milestones.add(milestone_id) + save_checkpoint( + args.output_dir + / f"milestone_{milestone_id}_step_{completed_step:07d}.pt", + model, optimizer, completed_step, + checkpoint_context_with_exposure( + context, cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + if validation_loaders and completed_step % validation_interval == 0: + result = run_validation( + model, criterion, validation_loaders, device, dtype, validation_batches, + ) + with val_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"timestamp_utc": utc_now(), "step": completed_step, **result}) + "\n") + + final_path = args.output_dir / f"step_{completed_step:07d}_final.pt" + save_checkpoint( + final_path, model, optimizer, completed_step, + checkpoint_context_with_exposure( + {**context, "checkpoint_role": "final"}, + cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + elapsed = time.perf_counter() - started + schedule_tail_argument = " --allow-schedule-tail" if args.allow_schedule_tail else "" + resource_override_argument = ( + " --allow-physical-gpus-4-5" if args.allow_physical_gpus_4_5 else "" + ) + resume_command = ( + f"CUDA_VISIBLE_DEVICES= {shlex.quote(sys.executable)} " + f"-m scripts.train_phase7_external --config {shlex.quote(str(args.config.resolve()))} " + f"--output-dir {shlex.quote(str(args.output_dir.resolve()))} " + f"--resume {shlex.quote(str(final_path.resolve()))} " + f"--physical-gpu-id {args.physical_gpu_id}{schedule_tail_argument}" + f"{resource_override_argument}" + ) + (args.output_dir / "resume_command.txt").write_text(resume_command + "\n", encoding="utf-8") + summary = { + "status": ( + "completed_schedule_tail" + if args.allow_schedule_tail and completed_step == run_end_step and completed_step > max_steps + else ("completed" if completed_step == max_steps else "paused_requested") + ), + "start_timestamp_utc": datetime.fromtimestamp( + time.time() - elapsed, timezone.utc, + ).isoformat(), + "end_timestamp_utc": utc_now(), + "start_step": start_step, + "completed_step": completed_step, + "protocol_max_steps": max_steps, + "registered_run_end_step": run_end_step, + "schedule_tail_enabled": bool(args.allow_schedule_tail), + "schedule_tail_learning_rate": minimum_lr if args.allow_schedule_tail else None, + "wall_seconds": elapsed, + "gpu_ids_visible": os.environ.get("CUDA_VISIBLE_DEVICES"), + "physical_gpu_id": args.physical_gpu_id, + "gpu_hours": elapsed / 3600.0, + "train_samples_per_second": ( + (completed_step - start_step) * batch_size / max(elapsed, 1e-9) + ), + "optimizer_steps_per_second": (completed_step - start_step) / max(elapsed, 1e-9), + "frames_per_second": processed_frames / max(elapsed, 1e-9), + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "gpu_utilization_percent_mean": ( + float(np.mean([value["gpu_utilization_percent"] for value in telemetry_samples])) + if telemetry_samples else None + ), + "gpu_telemetry_samples": len(telemetry_samples), + "final_checkpoint": str(final_path.resolve()), + "final_checkpoint_sha256": sha256(final_path), + "resume_command": resume_command, + "source_manifest_sha256": source_hashes, + "official_test_used": False, + "h2o_training_data_used": allow_h2o, + "model_config": asdict(model_config), + "source_exposure_batches": dict(cumulative_source_batches), + "source_exposure_frames": dict(cumulative_source_frames), + "depth_input_condition_frames": dict(cumulative_depth_conditions), + "completed_source_exposure_milestones": sorted( + completed_exposure_milestones + ), + "staged_adaptation": staged_adaptation, + } + (args.output_dir / "summary.json").write_text( + json.dumps(summary, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/smoke_adapters.py b/home/wuyifan/a7_rotation_fix_20260930_code/smoke_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..187e1e4a8016617c0eb87fb67f5d443d23898476 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/smoke_adapters.py @@ -0,0 +1,57 @@ +"""Decode one frozen filtered tile from each source without starting training.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import torch + +from filtered_dataset import FilteredClipDataset + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", type=Path, required=True) + parser.add_argument("--time", type=int, choices=(1, 8), required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--tile-id", help="Inspect a specific frozen tile") + args = parser.parse_args() + source = args.source + with torch.no_grad(): + dataset = FilteredClipDataset( + source, args.manifests / f"{source.lower()}_t{args.time}.jsonl", + args.time, (368, 640), + "/SSD3/jiasen/foundation_hand/pretrained/mano", + Path(__file__).parent / "third_party", + photometric_augmentation={"enabled": False}, + ) + mode = "rgb_depth_k" if source == "H2O" else "rgb_k" + spec = {"source": source, "tile_id": args.tile_id or dataset.rows[0]["filtered_tile_id"], + "epoch": 0, "source_ordinal": 0, "position": 0, "mode": mode} + sample = dataset[spec] + out = { + "source": source, "tile_id": spec["tile_id"], "frames": sample["frame_id"].tolist(), + "rgb_shape": list(sample["rgb"].shape), + "K_shape": list(sample["K"].shape), + "K_input": sample["K_input_available"].tolist(), + "K_supervision": sample["K_supervision_valid"].tolist(), + "depth_input": sample["depth_input_available"].tolist(), + "valid": {key: int(sample[key].sum()) for key in ( + "joint2d_valid", "joint3d_valid", "translation_valid", + "mano_pose_valid", "shape_valid", "vertices_valid", "reprojection_valid", + )}, + "finite_K": bool(torch.isfinite(sample["K"]).all()), + "valid_depth_pixels": int(sample["depth_pixel_valid"].sum()), + } + if "joint3d_root_relative_valid" in sample: + out["valid"]["joint3d_root_relative_valid"] = int(sample["joint3d_root_relative_valid"].sum()) + print(json.dumps(out, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/PKG-INFO b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..620eae1cf16816e8b6f85bc64184fc9d6654ac92 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/PKG-INFO @@ -0,0 +1,18 @@ +Metadata-Version: 2.4 +Name: foundation-hand +Version: 0.1.0 +Summary: Full-frame token-based bimanual reconstruction research code +Requires-Python: <3.12,>=3.11 +Requires-Dist: einops>=0.8 +Requires-Dist: numpy>=2.0 +Requires-Dist: opencv-python-headless>=4.10 +Requires-Dist: Pillow>=10 +Requires-Dist: PyYAML>=6 +Requires-Dist: scipy>=1.13 +Requires-Dist: torch>=2.6 +Requires-Dist: torchvision>=0.21 +Requires-Dist: tqdm>=4.66 +Provides-Extra: dev +Requires-Dist: pytest>=8; extra == "dev" +Provides-Extra: mano +Requires-Dist: smplx>=0.1.28; extra == "mano" diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/SOURCES.txt b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..41e91bffda7c0b0e844c367e275687fe7b4f6dc7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/SOURCES.txt @@ -0,0 +1,16 @@ +README.md +pyproject.toml +src/foundation_hand/__init__.py +src/foundation_hand.egg-info/PKG-INFO +src/foundation_hand.egg-info/SOURCES.txt +src/foundation_hand.egg-info/dependency_links.txt +src/foundation_hand.egg-info/requires.txt +src/foundation_hand.egg-info/top_level.txt +src/foundation_hand/data/__init__.py +src/foundation_hand/data/h2o_fields.py +src/foundation_hand/geometry/__init__.py +src/foundation_hand/geometry/camera.py +src/foundation_hand/geometry/mano_translation.py +tests/test_camera_geometry.py +tests/test_h2o_fields.py +tests/test_mano_translation.py \ No newline at end of file diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/dependency_links.txt b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/requires.txt b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..11a43ceccd64d950bbf022a5b8750dd7f449011f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/requires.txt @@ -0,0 +1,15 @@ +einops>=0.8 +numpy>=2.0 +opencv-python-headless>=4.10 +Pillow>=10 +PyYAML>=6 +scipy>=1.13 +torch>=2.6 +torchvision>=0.21 +tqdm>=4.66 + +[dev] +pytest>=8 + +[mano] +smplx>=0.1.28 diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/top_level.txt b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..6079d899260f4660e036318093285d2af7c1c176 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand.egg-info/top_level.txt @@ -0,0 +1 @@ +foundation_hand diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/__init__.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e2e8cc628c3ac4153bb9f660cad3e0083b5cb2 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/__init__.py @@ -0,0 +1,4 @@ +"""Unified full-frame bimanual reconstruction research package.""" + +__version__ = "0.1.0" + diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/__init__.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92b384d9e870d1f786ec2172145012828e61a7bb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/__init__.py @@ -0,0 +1,49 @@ +"""Dataset parsing and batching.""" + +from .h2o_fields import H2OJointRecord, H2OManoRecord, parse_joint_record, parse_mano_record + +__all__ = [ + "H2OJointRecord", + "H2OManoRecord", + "parse_joint_record", + "parse_mano_record", +] +from foundation_hand.data.h2o_dataset import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.cached_unified_dataset import CachedUnifiedClipDataset, UnifiedConcatDataset +from foundation_hand.data.egodexter_dataset import EgoDexterSequenceDataset +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.samplers import ( + ResumableMixtureBatchSampler, + ResumableRandomBatchSampler, + ResumableWeightedBatchSampler, + load_balanced_sampling_weights, +) +from foundation_hand.data.schema import ( + INPUT_AVAILABILITY_KEYS, + SUPERVISION_MASK_KEYS, + deterministic_clip_keep, + input_availability, + supervision_mask, +) + +__all__ = [ + "H2OCam4Dataset", + "HOT3DClipDataset", + "HOI4DClipDataset", + "ARCTICClipDataset", + "CachedUnifiedClipDataset", + "EgoDexterSequenceDataset", + "UnifiedConcatDataset", + "ResumableMixtureBatchSampler", + "ResumableRandomBatchSampler", + "ResumableWeightedBatchSampler", + "collate_h2o_clips", + "load_balanced_sampling_weights", + "INPUT_AVAILABILITY_KEYS", + "SUPERVISION_MASK_KEYS", + "deterministic_clip_keep", + "input_availability", + "supervision_mask", +] diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/arctic_dataset.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/arctic_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f22c15913e63b81fc8c79314d132d1f92d63d91a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/arctic_dataset.py @@ -0,0 +1,322 @@ +"""ARCTIC P2 rectified full-frame clips in the Phase 7 unified schema.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.h2o_dataset import ( + RGB_MEAN, + RGB_STD, + PhotometricAugmentation, + _resize_pad, + apply_photometric_augmentation, + sample_photometric_parameters, +) +from foundation_hand.geometry.camera import project_points, resize_and_pad_intrinsics +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import ( + axis_angle_to_matrix, + matrix_to_axis_angle, +) +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.data.schema import ( + InvalidSourceSampleError, + source_root_relative_joint_target, +) + + +def transform_points(points: torch.Tensor, world_to_camera: torch.Tensor) -> torch.Tensor: + if points.shape[-1] != 3 or world_to_camera.shape[-2:] != (4, 4): + raise ValueError("expected points [...,N,3] and transforms [...,4,4]") + return torch.einsum( + "...ij,...nj->...ni", world_to_camera[..., :3, :3], points, + ) + world_to_camera[..., None, :3, 3] + + +def geometry_compatibility_mask( + hand_valid: torch.Tensor, vertex_error_mm: torch.Tensor, +) -> torch.Tensor: + """Apply the frozen 1 mm MANO convention gate per frame and hand.""" + + return hand_valid & torch.isfinite(vertex_error_mm) & (vertex_error_mm < 1.0) + + +def compose_camera_global_orientation( + world_axis_angle: torch.Tensor, world_to_camera: torch.Tensor, +) -> torch.Tensor: + world_rotation = axis_angle_to_matrix(world_axis_angle) + camera_rotation = world_to_camera[..., :3, :3] @ world_rotation + return matrix_to_axis_angle(camera_rotation) + + +class ARCTICClipDataset(Dataset[dict[str, Any]]): + """Use P2 train or P2 val only; view 0 is rectified before model input.""" + + source_hw = (600, 840) + original_hw = (2000, 2800) + + def __init__( + self, + manifest: str | Path, + mano_root: str | Path, + target_hw: tuple[int, int] = (368, 640), + photometric_augmentation: Mapping[str, Any] | None = None, + augmentation_seed: int = 20260717, + hand_valid_policy: str = "legacy_wrist", + ) -> None: + self.manifest = Path(manifest).resolve() + self.target_hw = tuple(target_hw) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.augmentation_seed = int(augmentation_seed) + if hand_valid_policy not in {"legacy_wrist", "visible_mesh"}: + raise ValueError(f"unknown ARCTIC hand validity policy: {hand_valid_policy}") + self.hand_valid_policy = hand_valid_policy + self.rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not self.rows or any(row.get("dataset_id") != "ARCTIC" for row in self.rows): + raise ValueError("manifest must be non-empty and ARCTIC-only") + if any(row.get("protocol") != "P2" for row in self.rows): + raise ValueError("ARCTIC adapter accepts protocol P2 only") + if any(row.get("split_role") not in {"arctic_p2_train", "arctic_p2_val"} for row in self.rows): + raise ValueError("ARCTIC manifest may contain P2 train or val only") + if any(row.get("official_test_used") is not False for row in self.rows): + raise ValueError("ARCTIC manifest lacks test-isolation declaration") + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + self._source_mano = { + side: ManoLayer( + mano_root=str(mano_root), side=side, use_pca=False, + ncomps=45, flat_hand_mean=False, + ) + for side in ("left", "right") + } + self._target_mano = ManoCameraLayer(mano_root, fix_left_shapedirs=True) + self._cached_sequence: str | None = None + self._cached_mano: dict[str, Any] | None = None + self._cached_camera: dict[str, Any] | None = None + + def __len__(self) -> int: + return len(self.rows) + + def _sequence(self, row: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + sequence = str(row["physical_recording_id"]) + if self._cached_sequence != sequence: + self._cached_mano = np.load(row["mano_path"], allow_pickle=True).item() + self._cached_camera = np.load(row["camera_path"], allow_pickle=True).item() + self._cached_sequence = sequence + assert self._cached_mano is not None and self._cached_camera is not None + return self._cached_mano, self._cached_camera + + def source_root_relative_joint3d( + self, index: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Regenerate source-compatible camera-frame joints without images.""" + + row = self.rows[int(index)] + indices = [int(value) for value in row["array_indices_0based"]] + mano, camera = self._sequence(row) + rotation = torch.from_numpy(camera["R_k_cam_np"][indices].astype(np.float32)) + joints = torch.full((len(indices), 2, 21, 3), float("nan")) + hand_valid = torch.ones((len(indices), 2), dtype=torch.bool) + for side_index, side in enumerate(("left", "right")): + values = mano[side] + raw_pose = torch.from_numpy(np.concatenate(( + values["rot"][indices], values["pose"][indices], + ), axis=-1).astype(np.float32)) + beta = torch.from_numpy( + np.repeat( + np.asarray(values["shape"], dtype=np.float32)[None], + len(indices), axis=0, + ) + ) + with torch.no_grad(): + _, joints_mm = self._source_mano[side](raw_pose, beta) + relative_world = (joints_mm - joints_mm[:, :1]) / 1000.0 + joints[:, side_index] = torch.einsum( + "tij,tnj->tni", rotation, relative_world, + ) + return source_root_relative_joint_target(joints, hand_valid) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + indices = [int(value) for value in row["array_indices_0based"]] + frame_ids = [int(value) for value in row["frame_ids_1based"]] + mano, camera = self._sequence(row) + K_original = np.asarray(camera["intrinsics"], dtype=np.float32) + input_scale = self.source_hw[1] / self.original_hw[1] + if abs(input_scale - self.source_hw[0] / self.original_hw[0]) > 1e-9: + raise ValueError("ARCTIC ego speedup scale is anisotropic") + K_input = resize_and_pad_intrinsics( + K_original, self.original_hw, self.source_hw, + ) + distortion = np.asarray(camera["dist8"], dtype=np.float64) + parameters = sample_photometric_parameters( + self.photometric_augmentation, self.augmentation_seed, clip_index, epoch, + ) + rgb_rows = [] + resized_hw = pad_left_top = None + for path in row["image_paths"]: + bgr = cv2.imread(path, cv2.IMREAD_COLOR) + if bgr is None or bgr.shape[:2] != self.source_hw: + raise InvalidSourceSampleError(f"invalid ARCTIC ego image: {path}") + rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) + # Downloaded ego speedup images are scaled raw full frames. Rectify + # them to the undistorted camera frame used by ARCTIC P2 geometry. + rgb = cv2.undistort(rgb, K_input, distortion, None, K_input) + rgb = apply_photometric_augmentation(rgb, parameters) + rgb, resized_hw, pad_left_top = _resize_pad( + rgb, self.target_hw, cv2.INTER_LINEAR, + ) + rgb_rows.append( + np.transpose((rgb.astype(np.float32) / 255.0 - RGB_MEAN) / RGB_STD, (2, 0, 1)) + ) + assert resized_hw is not None and pad_left_top is not None + K = resize_and_pad_intrinsics( + K_input, self.source_hw, resized_hw, pad_left_top, + ) + time = len(indices) + source_vertices = torch.full((time, 2, 778, 3), float("nan")) + source_joints = torch.full((time, 2, 21, 3), float("nan")) + pose_camera = torch.full((time, 2, 48), float("nan")) + shape = torch.full((time, 2, 10), float("nan")) + wrist = torch.full((time, 2, 3), float("nan")) + world_to_camera = torch.eye(4)[None].repeat(time, 1, 1) + world_to_camera[:, :3, :3] = torch.from_numpy(camera["R_k_cam_np"][indices]) + world_to_camera[:, :3, 3] = torch.from_numpy(camera["T_k_cam_np"][indices, :, 0]) + for side_index, side in enumerate(("left", "right")): + values = mano[side] + raw_pose = torch.from_numpy(np.concatenate(( + values["rot"][indices], values["pose"][indices], + ), axis=-1).astype(np.float32)) + beta = torch.from_numpy( + np.repeat(np.asarray(values["shape"], dtype=np.float32)[None], time, axis=0) + ) + translation_world = torch.from_numpy(values["trans"][indices].astype(np.float32)) + with torch.no_grad(): + vertices_mm, joints_mm = self._source_mano[side](raw_pose, beta) + vertices_world = vertices_mm / 1000.0 + translation_world[:, None] + joints_world = joints_mm / 1000.0 + translation_world[:, None] + source_vertices[:, side_index] = transform_points(vertices_world, world_to_camera) + source_joints[:, side_index] = transform_points(joints_world, world_to_camera) + full_pose = raw_pose.clone() + full_pose[:, 3:] += self._source_mano[side].th_hands_mean + full_pose[:, :3] = compose_camera_global_orientation( + full_pose[:, :3], world_to_camera, + ) + pose_camera[:, side_index] = full_pose + shape[:, side_index] = beta + wrist[:, side_index] = source_joints[:, side_index, 0] + + K_tensor = torch.from_numpy(np.repeat(K[None], time, axis=0)) + source_joint2d, source_positive = project_points(source_joints, K_tensor) + height, width = self.target_hw + in_frame = ( + source_positive & torch.isfinite(source_joint2d).all(-1) + & (source_joint2d[..., 0] >= 0) & (source_joint2d[..., 0] < width) + & (source_joint2d[..., 1] >= 0) & (source_joint2d[..., 1] < height) + ) + if self.hand_valid_policy == "visible_mesh": + mesh_uv, mesh_positive = project_points(source_vertices, K_tensor) + mesh_in_frame = ( + mesh_positive & torch.isfinite(mesh_uv).all(-1) + & (mesh_uv[..., 0] >= 0) & (mesh_uv[..., 0] < width) + & (mesh_uv[..., 1] >= 0) & (mesh_uv[..., 1] < height) + ) + hand_valid = mesh_in_frame.any(-1) + else: + hand_valid = in_frame[..., 0] & (in_frame.sum(-1) >= 3) + rotations = axis_angle_to_matrix( + torch.nan_to_num(pose_camera).reshape(time, 2, 16, 3) + ) + with torch.no_grad(): + target_vertices, target_joints = self._target_mano( + rotations, torch.nan_to_num(shape), torch.nan_to_num(wrist), + ) + vertex_error_mm = torch.linalg.vector_norm( + target_vertices - source_vertices, dim=-1, + ).amax(dim=-1) * 1000.0 + geometry_valid = geometry_compatibility_mask(hand_valid, vertex_error_mm) + joint2d_valid = in_frame & hand_valid[..., None] + joint3d_valid = geometry_valid[..., None].expand(-1, -1, 21) + root_relative_joints, root_relative_valid = source_root_relative_joint_target( + source_joints, hand_valid, + ) + target_projected, _ = project_points(target_joints, K_tensor) + projection_error = torch.linalg.vector_norm( + target_projected - source_joint2d, dim=-1, + ) + for tensor, valid in ( + (target_vertices, geometry_valid), (target_joints, geometry_valid), + (source_joint2d, hand_valid), (pose_camera, hand_valid), + (shape, geometry_valid), (wrist, hand_valid), + ): + mask = valid + while mask.ndim < tensor.ndim: + mask = mask.unsqueeze(-1) + tensor.masked_fill_(~mask, float("nan")) + output: dict[str, Any] = { + "rgb": torch.from_numpy(np.stack(rgb_rows)), + "depth_m": torch.zeros((time, 1, *self.target_hw), dtype=torch.float32), + "depth_pixel_valid": torch.zeros((time, 1, *self.target_hw), dtype=torch.bool), + "K": K_tensor, + "camera_pose": world_to_camera, + "joint3d_camera": target_joints, + "joint3d_root_relative": root_relative_joints, + "joint2d": source_joint2d, + "joint_element_valid": joint3d_valid, + "mano_pose": pose_camera, + "mano_shape": shape, + "mano_translation_raw": torch.full_like(wrist, float("nan")), + "wrist_root_translation": wrist, + "joint_annotation_valid": geometry_valid, + "mano_annotation_valid": geometry_valid, + "joint2d_valid": joint2d_valid, + "joint3d_valid": joint3d_valid, + "joint3d_root_relative_valid": root_relative_valid, + "translation_valid": hand_valid, + "mano_pose_valid": hand_valid, + "shape_valid": geometry_valid, + "vertices_valid": geometry_valid, + "reprojection_valid": joint3d_valid, + "vertices_camera": target_vertices, + "presence_target": hand_valid.float(), + "presence_label_valid": torch.zeros((time, 2), dtype=torch.bool), + "presence_valid": torch.zeros((time, 2), dtype=torch.bool), + "depth_available": torch.zeros(time, dtype=torch.bool), + "K_available": torch.ones(time, dtype=torch.bool), + "depth_input_available": torch.zeros(time, dtype=torch.bool), + "K_input_available": torch.ones(time, dtype=torch.bool), + "K_supervision_valid": torch.ones(time, dtype=torch.bool), + "frame_valid": torch.ones(time, dtype=torch.bool), + "hand_side_id": torch.tensor((0, 1))[None].expand(time, -1).clone(), + "timestamp_ns": torch.tensor(indices, dtype=torch.long), + "frame_id": torch.tensor(frame_ids, dtype=torch.long), + "source_vertex_regen_error_mm": vertex_error_mm, + "geometry_convention_compatible": geometry_valid, + "projection_roundtrip_error_px": projection_error, + "photometric_aug_params": torch.from_numpy(np.repeat(parameters[None], time, axis=0)), + "image_hw": torch.tensor(self.target_hw, dtype=torch.long), + "dataset_id": "ARCTIC", + "subject_id": str(row["subject_id"]), + "sequence_id": str(row["physical_recording_id"]), + "physical_recording_id": str(row["physical_recording_id"]), + "camera_id": "ego_view_0_rectified", + "stream_id": "ego_rgb_rectified", + "headset_id": str(row["subject_id"]), + } + return output diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/cached_unified_dataset.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/cached_unified_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..616b65592175b6ec7b745ca8e448fe1292b5c713 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/cached_unified_dataset.py @@ -0,0 +1,465 @@ +"""Hash-bound controlled cache for unified external clips.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import ConcatDataset, Dataset + +from foundation_hand.data.h2o_dataset import ( + RGB_MEAN, + RGB_STD, + PhotometricAugmentation, + apply_photometric_augmentation, + sample_photometric_parameters, +) +from foundation_hand.data.schema import deterministic_clip_keep + + +DEPTH_CORRUPTIONS = ( + "quantization", "random_holes", "edge_erosion", "edge_dilation", + "local_invalid", "additive_noise", "multiplicative_noise", + "registration_shift", "sparse_outliers", "global_bias", +) + + +@dataclass(frozen=True) +class FullFrameGeometryAugmentation: + enabled: bool = False + probability: float = 0.0 + scale_min: float = 1.0 + scale_max: float = 1.0 + translation_fraction: float = 0.0 + + @classmethod + def from_mapping( + cls, value: Mapping[str, Any] | None, + ) -> "FullFrameGeometryAugmentation": + config = cls() if value is None else cls(**dict(value)) + if not 0.0 <= config.probability <= 1.0: + raise ValueError("geometry augmentation probability must be in [0, 1]") + if not 0.5 <= config.scale_min <= config.scale_max <= 2.0: + raise ValueError("geometry augmentation scale range must be within [0.5, 2.0]") + if not 0.0 <= config.translation_fraction <= 0.25: + raise ValueError("geometry translation fraction must be in [0, 0.25]") + if config.enabled and config.probability <= 0.0: + raise ValueError("enabled geometry augmentation requires positive probability") + return config + + +def sample_full_frame_affine( + config: FullFrameGeometryAugmentation, + seed: int, + source_clip_index: int, + epoch: int, + image_hw: tuple[int, int], +) -> tuple[np.ndarray, bool]: + """Sample one GT-independent affine shared by every frame and modality.""" + + matrix = np.eye(3, dtype=np.float32) + if not config.enabled: + return matrix, False + generator = np.random.default_rng( + int(seed) * 1_000_003 + int(source_clip_index) * 97_409 + int(epoch) * 65_537 + ) + if float(generator.random()) >= config.probability: + return matrix, False + height, width = image_hw + scale = float(generator.uniform(config.scale_min, config.scale_max)) + dx = float(generator.uniform(-1.0, 1.0) * config.translation_fraction * width) + dy = float(generator.uniform(-1.0, 1.0) * config.translation_fraction * height) + center_x, center_y = (width - 1.0) / 2.0, (height - 1.0) / 2.0 + matrix[0, 0] = scale + matrix[1, 1] = scale + matrix[0, 2] = (1.0 - scale) * center_x + dx + matrix[1, 2] = (1.0 - scale) * center_y + dy + return matrix, True + + +def apply_full_frame_affine( + rgb_u8: np.ndarray, + arrays: dict[str, np.ndarray], + matrix: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + """Warp full-frame inputs and update K/2D supervision with the same affine.""" + + rgb = np.asarray(rgb_u8) + if rgb.ndim != 4 or rgb.shape[-1] != 3: + raise ValueError(f"expected T,H,W,3 RGB cache, got {rgb.shape}") + time, height, width, _ = rgb.shape + if "image_hw" in arrays and tuple( + int(value) for value in np.asarray(arrays["image_hw"]).reshape(-1) + ) != (height, width): + raise ValueError("cached image_hw differs from RGB payload shape") + transform = np.asarray(matrix, dtype=np.float32) + if transform.shape != (3, 3) or not np.allclose(transform[2], (0.0, 0.0, 1.0)): + raise ValueError("full-frame geometry transform must be a 3x3 affine") + affine = transform[:2] + warped_rgb = np.stack([ + cv2.warpAffine( + frame, affine, (width, height), flags=cv2.INTER_LINEAR, + borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0), + ) + for frame in rgb + ]) + updated = dict(arrays) + if "depth_m" in updated and "depth_pixel_valid" in updated: + depth = np.asarray(updated["depth_m"], dtype=np.float32) + valid = np.asarray(updated["depth_pixel_valid"], dtype=bool) + if depth.shape != valid.shape or depth.shape != (time, 1, height, width): + raise ValueError("cached depth/valid geometry shape differs from RGB") + warped_depth = np.stack([ + cv2.warpAffine( + frame[0], affine, (width, height), flags=cv2.INTER_NEAREST, + borderMode=cv2.BORDER_CONSTANT, borderValue=0.0, + )[None] + for frame in depth + ]).astype(np.float32) + warped_valid = np.stack([ + cv2.warpAffine( + frame[0].astype(np.uint8), affine, (width, height), + flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, + borderValue=0, + )[None] + for frame in valid + ]).astype(bool) + updated["depth_m"] = np.where(warped_valid, warped_depth, 0.0).astype(np.float32) + updated["depth_pixel_valid"] = warped_valid + if "K" in updated: + intrinsics = np.asarray(updated["K"], dtype=np.float32) + if intrinsics.shape != (time, 3, 3): + raise ValueError("cached K shape differs from RGB time dimension") + updated["K"] = np.einsum("ij,tjk->tik", transform, intrinsics).astype(np.float32) + if "joint2d" in updated: + joints = np.asarray(updated["joint2d"], dtype=np.float32).copy() + joints_x = joints[..., 0].copy() + joints_y = joints[..., 1].copy() + joints[..., 0] = ( + transform[0, 0] * joints_x + + transform[0, 1] * joints_y + + transform[0, 2] + ) + joints[..., 1] = ( + transform[1, 0] * joints_x + + transform[1, 1] * joints_y + + transform[1, 2] + ) + updated["joint2d"] = joints + return warped_rgb, updated + + +def _shift(array: np.ndarray, dy: int, dx: int, fill: float | bool) -> np.ndarray: + result = np.full_like(array, fill) + source_y = slice(max(0, -dy), array.shape[-2] - max(0, dy)) + target_y = slice(max(0, dy), array.shape[-2] - max(0, -dy)) + source_x = slice(max(0, -dx), array.shape[-1] - max(0, dx)) + target_x = slice(max(0, dx), array.shape[-1] - max(0, -dx)) + result[..., target_y, target_x] = array[..., source_y, source_x] + return result + + +def corrupt_metric_depth( + depth_m: np.ndarray, + pixel_valid: np.ndarray, + corruption: str, + seed: int, +) -> tuple[np.ndarray, np.ndarray]: + """Apply one deterministic clip-level sensor corruption to model inputs.""" + + if corruption not in DEPTH_CORRUPTIONS: + raise ValueError(f"unsupported depth corruption: {corruption}") + depth = np.asarray(depth_m, dtype=np.float32).copy() + valid = np.asarray(pixel_valid, dtype=bool).copy() + generator = np.random.default_rng(seed) + if corruption == "quantization": + quantum = float(generator.choice((0.002, 0.005, 0.010))) + depth[valid] = np.round(depth[valid] / quantum) * quantum + elif corruption == "random_holes": + valid &= generator.random(valid.shape) >= 0.10 + elif corruption == "edge_erosion": + neighbors = [ + _shift(valid, dy, dx, False) + for dy in (-1, 0, 1) for dx in (-1, 0, 1) + ] + valid = np.logical_and.reduce(neighbors) + elif corruption == "edge_dilation": + offsets = [(dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)] + shifted_valid = [ + _shift(valid, dy, dx, False) + for dy, dx in offsets + ] + shifted_depth = [ + np.where(mask, _shift(depth, dy, dx, 0.0), np.inf) + for mask, (dy, dx) in zip(shifted_valid, offsets, strict=True) + ] + dilated = np.logical_or.reduce(shifted_valid) + nearest_foreground = np.minimum.reduce(shifted_depth) + depth = np.where(dilated, nearest_foreground, depth) + valid = dilated + elif corruption == "local_invalid": + height, width = valid.shape[-2:] + box_h, box_w = max(1, height // 5), max(1, width // 5) + top = int(generator.integers(0, max(1, height - box_h + 1))) + left = int(generator.integers(0, max(1, width - box_w + 1))) + valid[..., top : top + box_h, left : left + box_w] = False + elif corruption == "additive_noise": + noise = generator.normal(0.0, 0.0075, size=depth.shape).astype(np.float32) + depth[valid] += noise[valid] + elif corruption == "multiplicative_noise": + scale = generator.normal(1.0, 0.015, size=depth.shape).astype(np.float32) + depth[valid] *= scale[valid] + elif corruption == "registration_shift": + dy, dx = generator.integers(-3, 4, size=2) + depth = _shift(depth, int(dy), int(dx), 0.0) + valid = _shift(valid, int(dy), int(dx), False) + elif corruption == "sparse_outliers": + outliers = valid & (generator.random(valid.shape) < 0.02) + offsets = generator.uniform(-0.08, 0.08, size=depth.shape).astype(np.float32) + depth[outliers] += offsets[outliers] + elif corruption == "global_bias": + depth[valid] += float(generator.uniform(-0.04, 0.04)) + depth = np.where(valid, np.clip(depth, 0.02, 3.0), 0.0).astype(np.float32) + return depth, valid + + +class CachedUnifiedClipDataset(Dataset[dict[str, Any]]): + """Read bounded Phase 7 clip caches without source-format assumptions.""" + + def __init__( + self, + manifest: str | Path, + K_input_dropout: float = 0.0, + dropout_seed: int = 20260717, + photometric_augmentation: Mapping[str, Any] | None = None, + depth_input_dropout: float = 0.0, + depth_corruption_probability: float = 0.0, + joint3d_root_relative_scope: str = "auto", + source_id: str | None = None, + max_clips: int | None = None, + expected_resolution_hw: tuple[int, int] | None = None, + geometry_augmentation: Mapping[str, Any] | None = None, + ) -> None: + self.manifest = Path(manifest).resolve() + self.K_input_dropout = float(K_input_dropout) + self.dropout_seed = int(dropout_seed) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.geometry_augmentation = FullFrameGeometryAugmentation.from_mapping( + geometry_augmentation + ) + self.depth_input_dropout = float(depth_input_dropout) + self.depth_corruption_probability = float(depth_corruption_probability) + root_relative_scope = str(joint3d_root_relative_scope) + self.joint3d_root_relative_scope = { + "historical_left_only": "left_only", + }.get(root_relative_scope, root_relative_scope) + self.source_id = source_id + self.expected_resolution_hw = ( + tuple(int(value) for value in expected_resolution_hw) + if expected_resolution_hw is not None else None + ) + if not 0.0 <= self.K_input_dropout <= 1.0: + raise ValueError("K_input_dropout must be in [0, 1]") + if not 0.0 <= self.depth_input_dropout <= 1.0: + raise ValueError("depth_input_dropout must be in [0, 1]") + if not 0.0 <= self.depth_corruption_probability <= 1.0: + raise ValueError("depth_corruption_probability must be in [0, 1]") + if self.joint3d_root_relative_scope not in {"auto", "disabled", "left_only"}: + raise ValueError( + "joint3d_root_relative_scope must be auto, disabled, left_only " + "or historical_left_only" + ) + rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + self.rows = rows[:max_clips] + declared_resolutions = { + tuple(int(value) for value in row["resolution_hw"]) + for row in self.rows if "resolution_hw" in row + } + if len(declared_resolutions) > 1: + raise ValueError("cache manifest mixes multiple resolutions") + if self.expected_resolution_hw is not None: + if declared_resolutions and declared_resolutions != {self.expected_resolution_hw}: + raise ValueError( + f"cache resolution {sorted(declared_resolutions)} does not match " + f"configured {self.expected_resolution_hw}" + ) + if not declared_resolutions and self.expected_resolution_hw != (368, 640): + raise ValueError( + "legacy cache without resolution metadata is approved only for 640x368" + ) + for row in self.rows: + path = Path(row["cache_path"]) + if not path.is_file(): + raise FileNotFoundError(path) + if self.rows and self.expected_resolution_hw is not None and not declared_resolutions: + with np.load(self.rows[0]["cache_path"], allow_pickle=False) as archive: + if "image_hw" not in archive.files: + raise ValueError("legacy cache payload lacks image_hw") + actual = tuple(int(value) for value in archive["image_hw"].reshape(-1)) + if actual != self.expected_resolution_hw: + raise ValueError( + f"legacy cache resolution {actual} does not match configured " + f"{self.expected_resolution_hw}" + ) + + def __len__(self) -> int: + return len(self.rows) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + with np.load(row["cache_path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + rgb = arrays.pop("rgb_u8") + if self.geometry_augmentation.enabled: + image_hw = tuple(int(value) for value in arrays["image_hw"].reshape(-1)) + geometry_matrix, geometry_applied = sample_full_frame_affine( + self.geometry_augmentation, + self.dropout_seed + 307, + int(row["source_clip_index"]), + epoch, + image_hw, + ) + if geometry_applied: + rgb, arrays = apply_full_frame_affine(rgb, arrays, geometry_matrix) + arrays["geometry_aug_matrix"] = np.repeat( + geometry_matrix[None], len(arrays["frame_valid"]), axis=0, + ) + arrays["geometry_aug_applied"] = np.full( + len(arrays["frame_valid"]), geometry_applied, dtype=bool, + ) + parameters = sample_photometric_parameters( + self.photometric_augmentation, + self.dropout_seed, + int(row["source_clip_index"]), + epoch, + ) + rgb = np.stack([ + apply_photometric_augmentation(frame, parameters) for frame in rgb + ]) + rgb = rgb.astype(np.float32) / 255.0 + rgb = (rgb - RGB_MEAN) / RGB_STD + arrays["rgb"] = np.transpose(rgb, (0, 3, 1, 2)) + output = {key: torch.from_numpy(np.asarray(value)) for key, value in arrays.items()} + sidecar_path = row.get("joint3d_root_relative_sidecar_path") + if self.joint3d_root_relative_scope == "disabled": + output["joint3d_root_relative"] = torch.full_like( + output["joint3d_camera"], float("nan"), + ) + output["joint3d_root_relative_valid"] = torch.zeros_like( + output["joint3d_valid"], dtype=torch.bool, + ) + elif sidecar_path is not None: + with np.load(sidecar_path, allow_pickle=False) as sidecar: + relative = torch.from_numpy(sidecar["joint3d_root_relative"]) + relative_valid = torch.from_numpy( + sidecar["joint3d_root_relative_valid"] + ).bool() + if ( + relative.shape != output["joint3d_camera"].shape + or relative_valid.shape != output["joint3d_valid"].shape + or relative_valid[..., 1, :].any() + ): + raise RuntimeError("invalid historical-left root-relative sidecar") + output["joint3d_root_relative"] = relative.masked_fill( + ~relative_valid[..., None], float("nan"), + ) + output["joint3d_root_relative_valid"] = relative_valid + if self.joint3d_root_relative_scope == "left_only": + if ( + "joint3d_root_relative" not in output + or "joint3d_root_relative_valid" not in output + ): + raise RuntimeError("left-only scope requires cached root-relative targets") + relative_valid = output["joint3d_root_relative_valid"].bool().clone() + relative_valid[..., 1, :] = False + output["joint3d_root_relative_valid"] = relative_valid + output["joint3d_root_relative"] = output[ + "joint3d_root_relative" + ].masked_fill(~relative_valid[..., None], float("nan")) + keep_K = deterministic_clip_keep( + 1.0 - self.K_input_dropout, + self.dropout_seed, + int(row["source_clip_index"]), + epoch, + ) + output["K_input_available"] = torch.full( + output["frame_valid"].shape, keep_K, dtype=torch.bool, + ) + output["K_available"] = output["K_input_available"].clone() + source_depth_available = output["depth_input_available"].bool() + keep_depth = deterministic_clip_keep( + 1.0 - self.depth_input_dropout, + self.dropout_seed + 101, + int(row["source_clip_index"]), epoch, + ) + corrupt_depth = keep_depth and deterministic_clip_keep( + self.depth_corruption_probability, + self.dropout_seed + 211, + int(row["source_clip_index"]), epoch, + ) + condition_code = 0 + if bool(source_depth_available.any()) and not keep_depth: + output["depth_input_available"] = torch.zeros_like(source_depth_available) + condition_code = 1 + elif bool(source_depth_available.any()) and corrupt_depth: + corruption_index = ( + self.dropout_seed * 31 + int(row["source_clip_index"]) * 17 + epoch + ) % len(DEPTH_CORRUPTIONS) + corruption = DEPTH_CORRUPTIONS[corruption_index] + depth, valid = corrupt_metric_depth( + output["depth_m"].numpy(), output["depth_pixel_valid"].numpy(), + corruption, + seed=(self.dropout_seed * 1_000_003 + int(row["source_clip_index"]) * 97 + epoch), + ) + output["depth_m"] = torch.from_numpy(depth) + output["depth_pixel_valid"] = torch.from_numpy(valid) + condition_code = 3 + corruption_index + elif bool(source_depth_available.any()): + condition_code = 2 + output["depth_available"] = output["depth_input_available"].clone() + output["depth_input_condition_code"] = torch.full( + output["frame_valid"].shape, condition_code, dtype=torch.long, + ) + output["photometric_aug_params"] = torch.from_numpy( + np.repeat(parameters[None], len(output["frame_valid"]), axis=0) + ) + for key in ( + "dataset_id", "subject_id", "sequence_id", "physical_recording_id", + "camera_id", "stream_id", "headset_id", + ): + output[key] = row[key] + output["sampling_source_id"] = self.source_id or row["dataset_id"] + return output + + +class UnifiedConcatDataset(ConcatDataset): + """Concat dataset that preserves the sampler-provided augmentation epoch.""" + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + global_index, epoch = int(index[0]), int(index[1]) + else: + global_index, epoch = int(index), 0 + if global_index < 0: + global_index += len(self) + if global_index < 0 or global_index >= len(self): + raise IndexError("dataset index out of range") + dataset_index = int(np.searchsorted( + self.cumulative_sizes, global_index, side="right", + )) + previous = 0 if dataset_index == 0 else self.cumulative_sizes[dataset_index - 1] + return self.datasets[dataset_index][(global_index - previous, epoch)] diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/egodexter_dataset.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/egodexter_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..096ba3b2ab29316e3a92ab05dede9abf8ddbd85c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/egodexter_dataset.py @@ -0,0 +1,151 @@ +"""EgoDexter full-frame RGB-D sequence adapter for frozen zero-shot evaluation.""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Iterator + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD, _resize_pad +from foundation_hand.geometry.camera import depth_mm_to_m, resize_and_pad_intrinsics + + +SEQUENCES = ("Desk", "Fruits", "Kitchen", "Rotunda") +FINGERTIP_JOINT_INDICES = (4, 8, 12, 16, 20) + + +def parse_fingertip_line( + line: str, dimensions: int, *, missing_value: float = 0.0, +) -> np.ndarray: + groups = [group.strip() for group in line.split(";") if group.strip()] + if not 1 <= len(groups) <= 5: + raise ValueError(f"expected one to five fingertips, got {len(groups)}") + values = [[float(value.strip()) for value in group.split(",")] for group in groups] + present = np.asarray(values, dtype=np.float32) + if present.shape != (len(groups), dimensions): + raise ValueError(f"expected fingertip width {dimensions}, got {present.shape}") + array = np.full((5, dimensions), missing_value, dtype=np.float32) + array[: len(groups)] = present + return array + + +def load_depth_intrinsics(calibration_path: str | Path) -> np.ndarray: + text = Path(calibration_path).read_text(encoding="utf-8") + section = text.split("Depth Intrisics Matrix:", 1) + if len(section) != 2: + raise ValueError("depth intrinsics section missing") + rows = [] + for line in section[1].strip().splitlines()[:3]: + values = re.findall(r"[-+]?\d+(?:\.\d+)?", line) + if len(values) != 3: + raise ValueError(f"invalid depth intrinsics row: {line}") + rows.append([float(value) for value in values]) + K = np.asarray(rows, dtype=np.float32) + if K.shape != (3, 3) or not np.allclose(K[2], (0.0, 0.0, 1.0)): + raise ValueError("invalid depth intrinsics matrix") + return K + + +class EgoDexterSequenceDataset: + """Expose one sequence in order without using its annotations as model input.""" + + def __init__( + self, + root: str | Path, + sequence: str, + *, + hand_side: str, + target_hw: tuple[int, int] = (368, 640), + ) -> None: + if sequence not in SEQUENCES: + raise ValueError(f"unknown EgoDexter sequence: {sequence}") + if hand_side not in {"left", "right"}: + raise ValueError("hand_side must be frozen per sequence as left or right") + self.root = Path(root).resolve() + self.sequence = sequence + self.hand_side = hand_side + self.side_index = 0 if hand_side == "left" else 1 + self.target_hw = tuple(target_hw) + self.sequence_root = self.root / "data" / sequence + self.K_source = load_depth_intrinsics(self.root / "CameraCalibration_640x480.txt") + self.rgb_paths = sorted( + (self.sequence_root / "color_on_depth").glob("image_*_color_on_depth.png") + ) + self.depth_paths = sorted((self.sequence_root / "depth").glob("image_*_depth.png")) + lines_2d = (self.sequence_root / "annotation.txt").read_text( + encoding="utf-8", + ).splitlines() + lines_3d = (self.sequence_root / "annotation.txt_3D.txt").read_text( + encoding="utf-8", + ).splitlines() + lengths = {len(self.rgb_paths), len(self.depth_paths), len(lines_2d), len(lines_3d)} + if len(lengths) != 1 or not self.rgb_paths: + raise ValueError(f"EgoDexter sequence streams/annotations differ: {lengths}") + self.fingertips_2d = np.stack([ + parse_fingertip_line(line, 2, missing_value=-1.0) for line in lines_2d + ]) + self.fingertips_3d_m = np.stack([ + parse_fingertip_line(line, 3) for line in lines_3d + ]) / 1000.0 + + def __len__(self) -> int: + return len(self.rgb_paths) + + def _load(self, index: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + rgb_bgr = cv2.imread(str(self.rgb_paths[index]), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(self.depth_paths[index]), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise RuntimeError(f"EgoDexter decode failed: {self.sequence}/{index}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + if rgb.shape[:2] != (480, 640) or depth_mm.shape != (480, 640): + raise ValueError(f"unexpected EgoDexter resolution: {rgb.shape}/{depth_mm.shape}") + rgb, resized_hw, pad_left_top = _resize_pad(rgb, self.target_hw, cv2.INTER_AREA) + depth_mm, depth_hw, depth_pad = _resize_pad( + depth_mm, self.target_hw, cv2.INTER_NEAREST, + ) + if depth_hw != resized_hw or depth_pad != pad_left_top: + raise AssertionError("EgoDexter RGB/depth preprocessing diverged") + K = resize_and_pad_intrinsics( + self.K_source, (480, 640), resized_hw, pad_left_top, + ) + return rgb, depth_mm, K + + def frame(self, index: int, input_mode: str) -> dict[str, object]: + if input_mode not in {"rgb_d_k", "rgb_k", "rgb_only"}: + raise ValueError(f"unsupported input mode: {input_mode}") + rgb, depth_mm, K = self._load(index) + depth_m, depth_valid = depth_mm_to_m(depth_mm) + rgb = rgb.astype(np.float32) / 255.0 + rgb = (rgb - RGB_MEAN) / RGB_STD + K_available = input_mode != "rgb_only" + depth_available = input_mode == "rgb_d_k" + fingertips = self.fingertips_3d_m[index].copy() + fingertip_valid = np.linalg.norm(fingertips, axis=-1) > 0.0 + fingertips[~fingertip_valid] = np.nan + return { + "rgb": torch.from_numpy(np.transpose(rgb, (2, 0, 1))).float()[None, None], + "depth_m": torch.from_numpy(depth_m[None]).float()[None, None], + "depth_pixel_valid": torch.from_numpy(depth_valid[None])[None, None], + "K": torch.from_numpy(K).float()[None, None], + "K_available": torch.tensor([[K_available]], dtype=torch.bool), + "K_input_available": torch.tensor([[K_available]], dtype=torch.bool), + "depth_available": torch.tensor([[depth_available]], dtype=torch.bool), + "depth_input_available": torch.tensor([[depth_available]], dtype=torch.bool), + "frame_valid": torch.ones((1, 1), dtype=torch.bool), + "sequence_id": self.sequence, + "frame_id": index, + "hand_side": self.hand_side, + "hand_side_index": self.side_index, + "target_fingertips_camera_m": torch.from_numpy(fingertips), + "target_fingertip_valid": torch.from_numpy(fingertip_valid), + "target_fingertips_2d_source": torch.from_numpy(self.fingertips_2d[index]), + "K_supervision": torch.from_numpy(K).float(), + } + + def iter_frames(self, input_mode: str) -> Iterator[dict[str, object]]: + for index in range(len(self)): + yield self.frame(index, input_mode) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/h2o_dataset.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/h2o_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f771d19779fc8abbe5e010465f753057a4dd31 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/h2o_dataset.py @@ -0,0 +1,407 @@ +"""Cam4-only H2O RGB-D-K clip dataset with explicit annotation masks.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterable, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record, load_mano_record +from foundation_hand.data.oracle_crop import ( + crop_resize_intrinsics, + crop_resize_with_padding, + oracle_square_crop_spec, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points, resize_and_pad_intrinsics + +RGB_MEAN = np.asarray([0.485, 0.456, 0.406], dtype=np.float32) +RGB_STD = np.asarray([0.229, 0.224, 0.225], dtype=np.float32) + + +@dataclass(frozen=True) +class ClipRef: + take: str + frame_ids: tuple[int, ...] + + +@dataclass(frozen=True) +class PhotometricAugmentation: + enabled: bool = False + probability: float = 0.8 + brightness: float = 0.2 + contrast: float = 0.2 + saturation: float = 0.2 + hue: float = 0.05 + + @classmethod + def from_mapping( + cls, values: Mapping[str, Any] | None, + ) -> "PhotometricAugmentation": + config = cls(**dict(values or {})) + if not 0.0 <= config.probability <= 1.0: + raise ValueError("photometric probability must be in [0, 1]") + for name in ("brightness", "contrast", "saturation"): + if not 0.0 <= getattr(config, name) < 1.0: + raise ValueError(f"photometric {name} must be in [0, 1)") + if not 0.0 <= config.hue <= 0.5: + raise ValueError("photometric hue must be in [0, 0.5]") + return config + + +def sample_photometric_parameters( + config: PhotometricAugmentation, + seed: int, + clip_index: int, + epoch: int, +) -> np.ndarray: + """Return applied, brightness, contrast, saturation, and hue.""" + + identity = np.asarray([0.0, 1.0, 1.0, 1.0, 0.0], dtype=np.float32) + if not config.enabled: + return identity + rng = np.random.default_rng(np.random.SeedSequence([seed, clip_index, epoch])) + if rng.random() >= config.probability: + return identity + return np.asarray([ + 1.0, + rng.uniform(1.0 - config.brightness, 1.0 + config.brightness), + rng.uniform(1.0 - config.contrast, 1.0 + config.contrast), + rng.uniform(1.0 - config.saturation, 1.0 + config.saturation), + rng.uniform(-config.hue, config.hue), + ], dtype=np.float32) + + +def apply_photometric_augmentation( + rgb: np.ndarray, parameters: np.ndarray, +) -> np.ndarray: + """Apply a fixed-order color transform without changing image geometry.""" + + if float(parameters[0]) == 0.0: + return rgb + _, brightness, contrast, saturation, hue = parameters.astype(np.float32) + image = rgb.astype(np.float32) / 255.0 + image *= brightness + channel_mean = image.mean(axis=(0, 1), keepdims=True) + image = (image - channel_mean) * contrast + channel_mean + luminance = ( + image[..., 0:1] * 0.299 + + image[..., 1:2] * 0.587 + + image[..., 2:3] * 0.114 + ) + image = (image - luminance) * saturation + luminance + image = np.clip(image, 0.0, 1.0) + if float(hue) != 0.0: + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + hsv[..., 0] = np.mod(hsv[..., 0] + float(hue) * 360.0, 360.0) + image = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) + return np.rint(np.clip(image, 0.0, 1.0) * 255.0).astype(np.uint8) + + +def _load_jsonl(path: Path) -> list[dict[str, Any]]: + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + + +def _fit_resize(source_hw: tuple[int, int], target_hw: tuple[int, int]) -> tuple[tuple[int, int], tuple[int, int]]: + source_h, source_w = source_hw + target_h, target_w = target_hw + scale = min(target_w / source_w, target_h / source_h) + resized_h = max(1, round(source_h * scale)) + resized_w = max(1, round(source_w * scale)) + pad_top = (target_h - resized_h) // 2 + pad_left = (target_w - resized_w) // 2 + return (resized_h, resized_w), (pad_left, pad_top) + + +def _resize_pad(array: np.ndarray, target_hw: tuple[int, int], interpolation: int, fill: int | float = 0) -> tuple[np.ndarray, tuple[int, int], tuple[int, int]]: + resized_hw, pad_left_top = _fit_resize(array.shape[:2], target_hw) + resized = cv2.resize(array, (resized_hw[1], resized_hw[0]), interpolation=interpolation) + target_h, target_w = target_hw + pad_left, pad_top = pad_left_top + if array.ndim == 3: + output = np.full((target_h, target_w, array.shape[2]), fill, dtype=array.dtype) + else: + output = np.full((target_h, target_w), fill, dtype=array.dtype) + output[pad_top : pad_top + resized_hw[0], pad_left : pad_left + resized_hw[1]] = resized + return output, resized_hw, pad_left_top + + +class H2OCam4Dataset(Dataset[dict[str, Any]]): + """Read only cam4 clips; annotation-invalid numerical targets become NaN.""" + + def __init__( + self, + root: str | Path, + manifest: str | Path, + target_hw: tuple[int, int] = (288, 512), + clip_lengths: Iterable[int] = (8,), + strides: Iterable[int] = (1,), + window_step: int | None = None, + allow_partial: bool = True, + max_clips: int | None = None, + photometric_augmentation: Mapping[str, Any] | None = None, + augmentation_seed: int = 0, + oracle_crop_enabled: bool = False, + ) -> None: + self.root = Path(root).resolve() + self.manifest = Path(manifest).resolve() + self.target_hw = tuple(target_hw) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.augmentation_seed = int(augmentation_seed) + self.oracle_crop_enabled = bool(oracle_crop_enabled) + lengths = tuple(sorted(set(int(value) for value in clip_lengths))) + strides = tuple(sorted(set(int(value) for value in strides))) + if not lengths or not set(lengths).issubset({1, 2, 4, 8, 16}): + raise ValueError(f"Unsupported clip lengths: {lengths}") + if not strides or not set(strides).issubset({1, 2, 4}): + raise ValueError(f"Unsupported strides: {strides}") + self.clips: list[ClipRef] = [] + for record in _load_jsonl(self.manifest): + take = str(record["take"]) + if not take.endswith("cam4"): + raise ValueError(f"Manifest is not cam4-only: {take}") + available = tuple(int(value) for value in record["frame_ids"]) + for length in lengths: + for stride in strides: + span = (length - 1) * stride + 1 + step = window_step or span + for start in range(0, len(available), step): + ids = available[start : start + span : stride] + if len(ids) == length or (allow_partial and ids): + self.clips.append(ClipRef(take=take, frame_ids=ids)) + if max_clips is not None and len(self.clips) >= max_clips: + return + + def __len__(self) -> int: + return len(self.clips) + + def _load_frame( + self, + take: Path, + frame_id: int, + photometric_parameters: np.ndarray, + ) -> dict[str, np.ndarray | bool | int]: + stem = f"{frame_id:06d}" + rgb_bgr = cv2.imread(str(take / "rgb" / f"{stem}.png"), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(take / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise RuntimeError(f"Missing/decode failure at {take}/{stem}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + K, source_hw = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + if rgb.shape[:2] != source_hw or depth_mm.shape != source_hw: + raise ValueError(f"RGB/depth/K mismatch at {take}/{stem}") + joints = load_joint_record(take / "hand_pose" / f"{stem}.txt") + mano = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + if not np.array_equal(joints.annotation_valid, mano.annotation_valid): + raise ValueError(f"Joint/MANO valid disagreement at {take}/{stem}") + rgb = apply_photometric_augmentation(rgb, photometric_parameters) + oracle_crops = ( + self._extract_oracle_crops( + rgb, depth_mm, K, joints.joints_camera_m, + joints.annotation_valid, + ) + if self.oracle_crop_enabled else {} + ) + rgb, resized_hw, pad_left_top = _resize_pad(rgb, self.target_hw, cv2.INTER_AREA) + depth_mm, depth_resized_hw, depth_pad = _resize_pad(depth_mm, self.target_hw, cv2.INTER_NEAREST) + if depth_resized_hw != resized_hw or depth_pad != pad_left_top: + raise AssertionError("RGB/depth preprocessing diverged") + K_out = resize_and_pad_intrinsics(K, source_hw, resized_hw, pad_left_top) + depth_m, depth_valid = depth_mm_to_m(depth_mm) + + joint2d, positive_z = project_points(joints.joints_camera_m, K_out) + joint_valid = np.broadcast_to(joints.annotation_valid[:, None], (2, 21)).copy() & positive_z + + joint3d = joints.joints_camera_m.copy() + pose = mano.pose_axis_angle.copy() + shape = mano.shape.copy() + raw_translation = mano.translation_raw_m.copy() + wrist_translation = joints.joints_camera_m[:, 0].copy() + for hand in range(2): + if not joints.annotation_valid[hand]: + joint3d[hand] = np.nan + joint2d[hand] = np.nan + wrist_translation[hand] = np.nan + if not mano.annotation_valid[hand]: + pose[hand] = np.nan + shape[hand] = np.nan + raw_translation[hand] = np.nan + + rgb_float = rgb.astype(np.float32) / 255.0 + rgb_float = (rgb_float - RGB_MEAN) / RGB_STD + cam_pose = load_float_record(take / "cam_pose" / f"{stem}.txt").reshape(4, 4).astype(np.float32) + return { + "rgb": np.transpose(rgb_float, (2, 0, 1)), + "depth_m": depth_m[None], + "depth_pixel_valid": depth_valid[None], + "K": K_out, + "camera_pose": cam_pose, + "joint3d_camera": joint3d, + "joint2d": joint2d, + "joint_element_valid": joint_valid, + "mano_pose": pose, + "mano_shape": shape, + "mano_translation_raw": raw_translation, + "wrist_root_translation": wrist_translation, + "joint_annotation_valid": joints.annotation_valid, + "mano_annotation_valid": mano.annotation_valid, + "joint2d_valid": joint_valid, + "joint3d_valid": joint_valid, + "translation_valid": joints.annotation_valid.copy(), + "mano_pose_valid": mano.annotation_valid.copy(), + "shape_valid": mano.annotation_valid.copy(), + "vertices_valid": mano.annotation_valid.copy(), + "reprojection_valid": joint_valid.copy(), + # No reliable H2O field supplies on-screen presence. + "presence_target": np.full((2,), np.nan, dtype=np.float32), + "presence_label_valid": np.zeros((2,), dtype=bool), + "presence_valid": np.zeros((2,), dtype=bool), + "depth_available": True, + "K_available": True, + "depth_input_available": True, + "K_input_available": True, + "K_supervision_valid": True, + "hand_side_id": np.asarray((0, 1), dtype=np.int64), + "timestamp_ns": np.int64(round(frame_id * 1_000_000_000 / 30)), + "frame_id": frame_id, + **oracle_crops, + } + + @staticmethod + def _extract_oracle_crops( + rgb: np.ndarray, + depth_mm: np.ndarray, + K: np.ndarray, + joints_camera_m: np.ndarray, + annotation_valid: np.ndarray, + ) -> dict[str, np.ndarray]: + """Extract fixed A3 crops from raw aligned inputs and GT location.""" + + output_hw = (224, 224) + crops_rgb = np.zeros((2, 3, *output_hw), dtype=np.float32) + crops_depth = np.zeros((2, 1, *output_hw), dtype=np.float32) + crops_depth_valid = np.zeros((2, 1, *output_hw), dtype=bool) + crops_K = np.zeros((2, 3, 3), dtype=np.float32) + boxes = np.full((2, 4), -1, dtype=np.int32) + available = np.zeros(2, dtype=bool) + depth_available = np.zeros(2, dtype=bool) + joint2d_raw, positive_z = project_points(joints_camera_m, K) + for hand in range(2): + joint_valid = ( + np.full(21, bool(annotation_valid[hand]), dtype=bool) + & positive_z[hand] + & np.isfinite(joint2d_raw[hand]).all(axis=-1) + ) + spec = oracle_square_crop_spec( + joint2d_raw[hand], joint_valid, rgb.shape[:2], + ) + if spec is None: + continue + crop_rgb = crop_resize_with_padding( + rgb, spec, interpolation=cv2.INTER_LINEAR, + ) + crop_depth_mm = crop_resize_with_padding( + depth_mm, spec, interpolation=cv2.INTER_NEAREST, + ) + depth_m, valid = depth_mm_to_m(crop_depth_mm) + rgb_float = crop_rgb.astype(np.float32) / 255.0 + rgb_float = (rgb_float - RGB_MEAN) / RGB_STD + crops_rgb[hand] = np.transpose(rgb_float, (2, 0, 1)) + crops_depth[hand, 0] = depth_m + crops_depth_valid[hand, 0] = valid + crops_K[hand] = crop_resize_intrinsics(K, spec) + boxes[hand] = (spec.x0, spec.y0, spec.x1, spec.y1) + available[hand] = True + depth_available[hand] = bool(valid.any()) + return { + "oracle_crop_rgb": crops_rgb, + "oracle_crop_depth_m": crops_depth, + "oracle_crop_depth_pixel_valid": crops_depth_valid, + "oracle_crop_K": crops_K, + "oracle_crop_box_xyxy_raw": boxes, + "oracle_crop_available": available, + "oracle_crop_depth_available": depth_available, + } + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + clip = self.clips[clip_index] + take = self.root / clip.take + parts = Path(clip.take).parts + photometric_parameters = sample_photometric_parameters( + self.photometric_augmentation, + self.augmentation_seed, + clip_index, + epoch, + ) + frames = [ + self._load_frame(take, frame_id, photometric_parameters) + for frame_id in clip.frame_ids + ] + tensor_keys = set(frames[0]) - {"frame_id"} + output: dict[str, Any] = {} + for key in tensor_keys: + values = np.stack([np.asarray(frame[key]) for frame in frames]) + output[key] = torch.from_numpy(values) + output["frame_valid"] = torch.ones(len(frames), dtype=torch.bool) + output["dataset_id"] = "H2O" + output["subject_id"] = parts[0] + output["sequence_id"] = "/".join(parts[1:-1]) + output["physical_recording_id"] = "/".join(parts[:-1]) + output["camera_id"] = "cam4" + output["headset_id"] = "H2O-ego" + output["stream_id"] = "cam4-rgb" + output["frame_id"] = torch.tensor(clip.frame_ids, dtype=torch.long) + output["image_hw"] = torch.tensor(self.target_hw, dtype=torch.long) + output["photometric_aug_params"] = torch.from_numpy( + np.repeat(photometric_parameters[None], len(frames), axis=0) + ) + return output + + +def _pad_time(value: torch.Tensor, target_t: int, fill: float | int | bool) -> torch.Tensor: + if value.shape[0] == target_t: + return value + shape = (target_t - value.shape[0],) + value.shape[1:] + padding = torch.full(shape, fill, dtype=value.dtype) + return torch.cat((value, padding), dim=0) + + +def collate_h2o_clips(samples: list[dict[str, Any]]) -> dict[str, Any]: + """Pad variable length clips without repeating frames.""" + + max_t = max(int(sample["frame_valid"].shape[0]) for sample in samples) + metadata = { + "dataset_id", "subject_id", "sequence_id", "physical_recording_id", + "camera_id", "headset_id", "stream_id", "sampling_source_id", + "filtered_tile_id", "input_mode", + } + metadata &= set(samples[0]) + result: dict[str, Any] = {key: [sample[key] for sample in samples] for key in metadata} + nan_keys = { + "joint3d_camera", "joint3d_root_relative", "joint2d", "mano_pose", "mano_shape", + "mano_translation_raw", "wrist_root_translation", "presence_target", + "vertices_camera", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", + } + for key in samples[0]: + if key in metadata: + continue + values = [sample[key] for sample in samples] + if key == "image_hw": + result[key] = torch.stack(values) + continue + fill: float | int | bool = float("nan") if key in nan_keys else False if values[0].dtype == torch.bool else -1 if key == "frame_id" else 0 + result[key] = torch.stack([_pad_time(value, max_t, fill) for value in values]) + result["clip_length"] = torch.tensor([sample["frame_valid"].shape[0] for sample in samples], dtype=torch.long) + return result diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/h2o_fields.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/h2o_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..397172b7f7d4c4ac7f0040d4797d5b079e5264a3 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/h2o_fields.py @@ -0,0 +1,88 @@ +"""Strict parsers for the released H2O per-frame hand records.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +HAND_COUNT = 2 +JOINTS_PER_HAND = 21 +JOINT_RECORD_VALUES_PER_HAND = 64 +JOINT_RECORD_VALUES = 128 +MANO_RECORD_VALUES_PER_HAND = 62 +MANO_RECORD_VALUES = 124 +MANO_POSE_DIMS = 48 +MANO_SHAPE_DIMS = 10 + +LEFT = 0 +RIGHT = 1 + + +@dataclass(frozen=True) +class H2OJointRecord: + """Camera-space OpenPose-order hand joints and annotation validity.""" + + annotation_valid: np.ndarray # [2] bool + joints_camera_m: np.ndarray # [2, 21, 3] float32; invalid rows are not supervision + + +@dataclass(frozen=True) +class H2OManoRecord: + """Raw H2O MANO fit parameters and annotation validity.""" + + annotation_valid: np.ndarray # [2] bool + translation_raw_m: np.ndarray # [2, 3] + pose_axis_angle: np.ndarray # [2, 48], global first + shape: np.ndarray # [2, 10] + + +def load_float_record(path: str | Path) -> np.ndarray: + """Load one whitespace-separated H2O text record without accepting bad tokens.""" + + text = Path(path).read_text(encoding="utf-8") + values = np.fromstring(text, dtype=np.float64, sep=" ") + if values.size != len(text.split()): + raise ValueError(f"Non-numeric or malformed value in {path}") + return values + + +def parse_joint_record(values: np.ndarray) -> H2OJointRecord: + values = np.asarray(values, dtype=np.float64).reshape(-1) + if values.size != JOINT_RECORD_VALUES: + raise ValueError(f"Expected {JOINT_RECORD_VALUES} hand_pose values, got {values.size}") + + hands = values.reshape(HAND_COUNT, JOINT_RECORD_VALUES_PER_HAND) + valid = hands[:, 0] != 0 + joints = hands[:, 1:].reshape(HAND_COUNT, JOINTS_PER_HAND, 3).astype(np.float32) + return H2OJointRecord(annotation_valid=valid, joints_camera_m=joints) + + +def parse_mano_record(values: np.ndarray) -> H2OManoRecord: + values = np.asarray(values, dtype=np.float64).reshape(-1) + if values.size != MANO_RECORD_VALUES: + raise ValueError(f"Expected {MANO_RECORD_VALUES} hand_pose_mano values, got {values.size}") + + hands = values.reshape(HAND_COUNT, MANO_RECORD_VALUES_PER_HAND) + valid = hands[:, 0] != 0 + translation = hands[:, 1:4].astype(np.float32) + pose = hands[:, 4 : 4 + MANO_POSE_DIMS].astype(np.float32) + shape = hands[:, 4 + MANO_POSE_DIMS :].astype(np.float32) + if shape.shape != (HAND_COUNT, MANO_SHAPE_DIMS): + raise AssertionError(f"Unexpected MANO shape slice: {shape.shape}") + return H2OManoRecord( + annotation_valid=valid, + translation_raw_m=translation, + pose_axis_angle=pose, + shape=shape, + ) + + +def load_joint_record(path: str | Path) -> H2OJointRecord: + return parse_joint_record(load_float_record(path)) + + +def load_mano_record(path: str | Path) -> H2OManoRecord: + return parse_mano_record(load_float_record(path)) + diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/hoi4d_dataset.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/hoi4d_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..af4abbb4603ca6f7cf9396f9905a8b83137ff377 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/hoi4d_dataset.py @@ -0,0 +1,443 @@ +"""HOI4D RGB-D-K clips with explicit wrist-root and supervision semantics.""" + +from __future__ import annotations + +import json +import pickle +from pathlib import Path +import subprocess +from typing import Any, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.h2o_dataset import ( + RGB_MEAN, + RGB_STD, + PhotometricAugmentation, + _resize_pad, + apply_photometric_augmentation, + sample_photometric_parameters, +) +from foundation_hand.geometry.camera import ( + depth_mm_to_m, + project_points, + resize_and_pad_intrinsics, +) +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.data.schema import ( + InvalidSourceSampleError, + source_root_relative_joint_target, +) + + +def load_hoi4d_mano_annotation(path: str | Path) -> dict[str, np.ndarray]: + """Load one source annotation while classifying payload corruption narrowly.""" + + source = Path(path) + try: + with source.open("rb") as handle: + annotation = pickle.load(handle) + values = { + "poseCoeff": np.asarray(annotation["poseCoeff"], dtype=np.float32), + "beta": np.asarray(annotation["beta"], dtype=np.float32), + "trans": np.asarray(annotation["trans"], dtype=np.float32), + "kps2D": np.asarray(annotation["kps2D"], dtype=np.float32), + } + except (OSError, EOFError, pickle.UnpicklingError, KeyError, TypeError, ValueError) as error: + raise InvalidSourceSampleError( + f"invalid HOI4D MANO annotation payload: {source}: {error}" + ) from error + expected = { + "poseCoeff": (48,), "beta": (10,), "trans": (3,), "kps2D": (21, 2), + } + mismatches = [ + f"{key}={values[key].shape} expected={shape}" + for key, shape in expected.items() if values[key].shape != shape + ] + if mismatches: + raise InvalidSourceSampleError( + f"invalid HOI4D MANO annotation shapes: {source}: {'; '.join(mismatches)}" + ) + return values + + +def hoi4d_geometry_compatibility_mask( + hand_valid: torch.Tensor, vertex_error_mm: torch.Tensor, +) -> torch.Tensor: + """Keep historical-left mesh masked and apply the frozen 1 mm right gate.""" + + geometry_valid = ( + hand_valid & torch.isfinite(vertex_error_mm) & (vertex_error_mm < 1.0) + ) + geometry_valid[..., 0] = False + return geometry_valid + + +def decode_video_frames( + path: str | Path, + frame_ids: list[int], + source_hw: tuple[int, int], + pixel_format: str, + dtype: str, + channels: int, + fps: float | None = None, +) -> np.ndarray: + """Decode exact sorted frame indices while preserving 16-bit depth.""" + + if not frame_ids or frame_ids != sorted(set(frame_ids)): + raise ValueError("HOI4D decoded frame IDs must be non-empty, sorted and unique") + contiguous = frame_ids == list(range(frame_ids[0], frame_ids[-1] + 1)) + if fps is not None and contiguous: + if fps <= 0: + raise ValueError("HOI4D fps must be positive") + command = [ + "ffmpeg", "-v", "error", "-ss", f"{frame_ids[0] / fps:.9f}", + "-i", str(path), "-frames:v", str(len(frame_ids)), + "-f", "rawvideo", "-pix_fmt", pixel_format, "-", + ] + else: + expression = frame_select_expression(frame_ids) + command = [ + "ffmpeg", "-v", "error", "-i", str(path), "-vf", f"select={expression}", + "-vsync", "0", "-frames:v", str(len(frame_ids)), + "-f", "rawvideo", "-pix_fmt", pixel_format, "-", + ] + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) + if result.returncode != 0: + raise RuntimeError(f"ffmpeg decode failed for {path}: {result.stderr.decode(errors='replace')}") + height, width = source_hw + expected = len(frame_ids) * height * width * channels * np.dtype(dtype).itemsize + if len(result.stdout) != expected: + raise RuntimeError( + f"decoded byte count mismatch for {path}: {len(result.stdout)} != {expected}" + ) + shape = (len(frame_ids), height, width) if channels == 1 else ( + len(frame_ids), height, width, channels, + ) + return np.frombuffer(result.stdout, dtype=dtype).reshape(shape).copy() + + +def frame_select_expression(frame_ids: list[int]) -> str: + contiguous = frame_ids == list(range(frame_ids[0], frame_ids[-1] + 1)) + if contiguous: + return f"between(n\\,{frame_ids[0]}\\,{frame_ids[-1]})" + return "+".join(f"eq(n\\,{frame})" for frame in frame_ids) + + +class HOI4DClipDataset(Dataset[dict[str, Any]]): + """Load group-split HOI4D clips into the Phase 7 unified schema.""" + + source_hw = (1080, 1920) + + def __init__( + self, + root: str | Path, + manifest: str | Path, + mano_root: str | Path, + target_hw: tuple[int, int] = (368, 640), + photometric_augmentation: Mapping[str, Any] | None = None, + augmentation_seed: int = 20260717, + ) -> None: + self.root = Path(root).resolve() + self.manifest = Path(manifest).resolve() + self.target_hw = tuple(target_hw) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.augmentation_seed = int(augmentation_seed) + self.rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not self.rows or any(row.get("dataset_id") != "HOI4D" for row in self.rows): + raise ValueError("manifest must be non-empty and HOI4D-only") + if any(row.get("official_test_used") is not False for row in self.rows): + raise ValueError("HOI4D manifest lacks official-test isolation declaration") + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + self._source_mano = { + side: ManoLayer( + mano_root=str(mano_root), side=side, use_pca=False, + ncomps=45, flat_hand_mean=True, + ) + for side in ("left", "right") + } + self._target_mano = ManoCameraLayer(mano_root, fix_left_shapedirs=True) + self._prefetched_recording: str | None = None + self._prefetched_rgb: dict[int, np.ndarray] = {} + self._prefetched_depth: dict[int, np.ndarray] = {} + + def __len__(self) -> int: + return len(self.rows) + + def _annotation_path(self, row: dict[str, Any], frame: int, side: str) -> Path: + return ( + self.root / "Hand_pose" / f"handpose_{side}_hand" + / row["physical_recording_id"] / f"{frame}.pickle" + ) + + def prefetch_clip_indices(self, clip_indices: list[int]) -> None: + if not clip_indices: + self.clear_prefetch() + return + rows = [self.rows[index] for index in clip_indices] + recordings = {str(row["physical_recording_id"]) for row in rows} + rgb_paths = {str(row["rgb_video"]) for row in rows} + depth_paths = {str(row["depth_video"]) for row in rows} + frame_rates = {float(row["fps"]) for row in rows} + if ( + len(recordings) != 1 or len(rgb_paths) != 1 + or len(depth_paths) != 1 or len(frame_rates) != 1 + ): + raise ValueError("HOI4D prefetch batch must stay within one physical recording") + frame_ids = sorted({int(frame) for row in rows for frame in row["frame_ids"]}) + rgb = decode_video_frames( + next(iter(rgb_paths)), frame_ids, self.source_hw, "rgb24", "u1", 3, + fps=next(iter(frame_rates)), + ) + depth = decode_video_frames( + next(iter(depth_paths)), frame_ids, self.source_hw, "gray16le", " None: + self._prefetched_recording = None + self._prefetched_rgb = {} + self._prefetched_depth = {} + + def source_root_relative_joint3d( + self, index: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Regenerate source-compatible joints without decoding RGB-D video.""" + + row = self.rows[int(index)] + frame_ids = [int(value) for value in row["frame_ids"]] + joints = torch.full((len(frame_ids), 2, 21, 3), float("nan")) + hand_valid = torch.zeros((len(frame_ids), 2), dtype=torch.bool) + for side_index, side in enumerate(("left", "right")): + frame_indices = [] + poses = [] + shapes = [] + for frame_index, frame in enumerate(frame_ids): + path = self._annotation_path(row, frame, side) + if not path.is_file(): + continue + annotation = load_hoi4d_mano_annotation(path) + poses.append(annotation["poseCoeff"]) + shapes.append(annotation["beta"]) + frame_indices.append(frame_index) + if not frame_indices: + continue + with torch.no_grad(): + _, joints_mm = self._source_mano[side]( + torch.from_numpy(np.stack(poses)), + torch.from_numpy(np.stack(shapes)), + ) + relative = (joints_mm - joints_mm[:, :1]) / 1000.0 + joints[frame_indices, side_index] = relative + hand_valid[frame_indices, side_index] = True + return source_root_relative_joint_target(joints, hand_valid) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + frame_ids = [int(value) for value in row["frame_ids"]] + fps = float(row["fps"]) + use_prefetch = ( + self._prefetched_recording == str(row["physical_recording_id"]) + and all(frame in self._prefetched_rgb for frame in frame_ids) + and all(frame in self._prefetched_depth for frame in frame_ids) + ) + if use_prefetch: + rgb_raw = np.stack([self._prefetched_rgb[frame] for frame in frame_ids]) + depth_raw = np.stack([self._prefetched_depth[frame] for frame in frame_ids]) + else: + rgb_raw = decode_video_frames( + row["rgb_video"], frame_ids, self.source_hw, "rgb24", "u1", 3, + fps=fps, + ) + depth_raw = decode_video_frames( + row["depth_video"], frame_ids, self.source_hw, "gray16le", " None: + """Compatibility needed by the official SMPL-X loader on Python 3.11.""" + + if not hasattr(inspect, "getargspec"): + inspect.getargspec = inspect.getfullargspec # type: ignore[attr-defined] + aliases = { + "bool": np.bool_, "int": np.int64, "float": np.float64, + "complex": np.complex128, "object": np.object_, + "unicode": np.str_, "str": np.str_, + } + for name, value in aliases.items(): + if name not in np.__dict__: + setattr(np, name, value) + + +def load_hot3d_api(toolkit_root: str | Path) -> dict[str, Any]: + """Import the pinned official toolkit without copying or rewriting it.""" + + toolkit = Path(toolkit_root).resolve() + source = toolkit / "hot3d" + if not (source / "dataset_api.py").is_file(): + raise FileNotFoundError(f"official HOT3D toolkit missing: {source}") + source_text = str(source) + if source_text not in sys.path: + sys.path.insert(0, source_text) + enable_hot3d_runtime_compatibility() + from dataset_api import Hot3dDataProvider + from data_loaders.loader_hand_poses import Handedness, load_mano_shape_params + from data_loaders.loader_object_library import load_object_library + from data_loaders.mano_layer import MANOHandModel + from projectaria_tools.core.calibration import FISHEYE624, LINEAR + from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions + from projectaria_tools.core.stream_id import StreamId + return { + "Hot3dDataProvider": Hot3dDataProvider, + "Handedness": Handedness, + "load_mano_shape_params": load_mano_shape_params, + "load_object_library": load_object_library, + "MANOHandModel": MANOHandModel, + "LINEAR": LINEAR, + "FISHEYE624": FISHEYE624, + "TimeDomain": TimeDomain, + "TimeQueryOptions": TimeQueryOptions, + "StreamId": StreamId, + } + + +def transform_points(points: np.ndarray, transform: np.ndarray) -> np.ndarray: + points = np.asarray(points, dtype=np.float64) + transform = np.asarray(transform, dtype=np.float64) + if transform.shape != (4, 4): + raise ValueError("transform must be 4x4") + return (points @ transform[:3, :3].T + transform[:3, 3]).astype(np.float32) + + +def linear_camera_matrix(calibration: Any) -> np.ndarray: + focal = np.asarray(calibration.get_focal_lengths(), dtype=np.float64) + principal = np.asarray(calibration.get_principal_point(), dtype=np.float64) + if focal.size != 2 or principal.size != 2: + raise ValueError("HOT3D linear calibration is not pinhole fx/fy/cx/cy") + return np.asarray([ + [focal[0], 0.0, principal[0]], + [0.0, focal[1], principal[1]], + [0.0, 0.0, 1.0], + ], dtype=np.float32) + + +def pca_to_full_local_pose( + coefficients: np.ndarray, + source_layer: Any, +) -> torch.Tensor: + coefficients_t = torch.as_tensor(coefficients, dtype=torch.float32) + if coefficients_t.shape != (15,): + raise ValueError(f"HOT3D MANO PCA pose must have 15 values, got {coefficients_t.shape}") + return ( + coefficients_t @ source_layer.hand_components[:15].detach().cpu() + + source_layer.pose_mean[3:].detach().cpu() + ).reshape(15, 3) + + +def geometry_valid_mask( + annotation_present: torch.Tensor, + vertex_error_mm: torch.Tensor, + threshold_mm: float = 1.0, +) -> torch.Tensor: + """Enable geometry supervision only where MANO regeneration passes audit.""" + + return ( + annotation_present.bool() + & torch.isfinite(vertex_error_mm) + & (vertex_error_mm < threshold_mm) + ) + + +def hot3d_supervision_masks( + geometry_valid: torch.Tensor, + source_vertices: torch.Tensor, + joint2d: torch.Tensor, + positive_depth: torch.Tensor, + projection_error: torch.Tensor, + K: torch.Tensor, + image_hw: tuple[int, int], + max_projection_error_px: float = 2.0, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Keep full-hand 3D targets for visible hands, but only visible 2D joints.""" + + height, width = image_hw + mesh_uv, mesh_positive = project_points(source_vertices, K) + mesh_in_frame = ( + mesh_positive & torch.isfinite(mesh_uv).all(-1) + & (mesh_uv[..., 0] >= 0) & (mesh_uv[..., 0] < width) + & (mesh_uv[..., 1] >= 0) & (mesh_uv[..., 1] < height) + ) + hand_valid = geometry_valid & mesh_in_frame.any(-1) + joint_in_frame = ( + positive_depth & torch.isfinite(joint2d).all(-1) + & (joint2d[..., 0] >= 0) & (joint2d[..., 0] < width) + & (joint2d[..., 1] >= 0) & (joint2d[..., 1] < height) + ) + joint2d_valid = ( + hand_valid[..., None] & joint_in_frame + & torch.isfinite(projection_error) + & (projection_error <= max_projection_error_px) + ) + joint3d_valid = hand_valid[..., None].expand_as(joint2d_valid) + return hand_valid, joint2d_valid, joint3d_valid + + +def quest_linear_camera_calibration( + device: Any, stream_id: Any, linear_model: Any, native_model: Any, +) -> tuple[Any, Any]: + """Use Quest3's native device-to-camera transform with its rectified intrinsics.""" + + T_device_camera, _ = device.get_camera_calibration( + stream_id, camera_model=native_model, + ) + _, linear_calibration = device.get_camera_calibration( + stream_id, camera_model=linear_model, + ) + return T_device_camera, linear_calibration + + +class HOT3DClipDataset(Dataset[dict[str, Any]]): + """Decode rectilinear HOT3D clips through the official toolkit.""" + + def __init__( + self, + root: str | Path, + manifest: str | Path, + toolkit_root: str | Path, + mano_root: str | Path, + target_hw: tuple[int, int] = (368, 640), + K_input_dropout: float = 0.3, + dropout_seed: int = 20260717, + max_clips: int | None = None, + provider_cache_size: int = 2, + ) -> None: + self.root = Path(root).resolve() + self.manifest = Path(manifest).resolve() + self.toolkit_root = Path(toolkit_root).resolve() + self.mano_root = Path(mano_root).resolve() + self.target_hw = tuple(int(value) for value in target_hw) + self.K_input_dropout = float(K_input_dropout) + self.dropout_seed = int(dropout_seed) + self.provider_cache_size = int(provider_cache_size) + if not 0.0 <= self.K_input_dropout <= 1.0: + raise ValueError("K_input_dropout must be in [0, 1]") + if self.provider_cache_size < 1: + raise ValueError("provider_cache_size must be positive") + rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + for row in rows: + if row.get("dataset") != "HOT3D" or row.get("have_hand_object_pose_gt") is not True: + raise ValueError("HOT3D manifest contains a non-GT or foreign row") + if len(row.get("timestamps_ns", [])) == 0: + raise ValueError("HOT3D manifest contains an empty clip") + self.rows = rows[:max_clips] + self._api: dict[str, Any] | None = None + self._object_library: Any | None = None + self._source_mano: Any | None = None + self._target_mano: ManoCameraLayer | None = None + self._providers: OrderedDict[str, Any] = OrderedDict() + + def __len__(self) -> int: + return len(self.rows) + + def _initialize_runtime(self) -> None: + if self._api is not None: + return + self._api = load_hot3d_api(self.toolkit_root) + self._object_library = self._api["load_object_library"]( + str(self.root / "assets") + ) + self._source_mano = self._api["MANOHandModel"]( + str(self.mano_root), joint_mapper=None, + ) + self._target_mano = ManoCameraLayer( + self.mano_root, fix_left_shapedirs=True, + ).eval() + + def _provider(self, recording: str) -> Any: + self._initialize_runtime() + if recording in self._providers: + provider = self._providers.pop(recording) + self._providers[recording] = provider + return provider + assert self._api is not None + provider = self._api["Hot3dDataProvider"]( + sequence_folder=str(self.root / recording), + object_library=self._object_library, + mano_hand_model=self._source_mano, + ) + self._providers[recording] = provider + while len(self._providers) > self.provider_cache_size: + self._providers.popitem(last=False) + return provider + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + provider = self._provider(str(row["recording_id"])) + assert self._api is not None and self._target_mano is not None + hand_provider = provider.mano_hand_data_provider + if hand_provider is None: + raise RuntimeError("GT HOT3D row has no official MANO provider") + device = provider.device_data_provider + pose_provider = provider.device_pose_data_provider + stream_id = self._api["StreamId"](str(row["stream_id"])) + is_aria = str(row["headset"]) == "Aria" + keep_K = deterministic_clip_keep( + 1.0 - self.K_input_dropout, + self.dropout_seed, + clip_index, + epoch, + ) + shape_params = torch.as_tensor( + self._api["load_mano_shape_params"]( + str(self.root / row["recording_id"] / "mano_hand_pose_trajectory.jsonl") + ), + dtype=torch.float32, + ) + + frames: list[dict[str, Any]] = [] + source_vertices: list[np.ndarray] = [] + pose_targets: list[np.ndarray] = [] + shape_targets: list[np.ndarray] = [] + wrist_targets: list[np.ndarray] = [] + hand_valid_rows: list[np.ndarray] = [] + raw_calibrations: list[Any] = [] + resize_contracts: list[tuple[tuple[int, int], tuple[int, int], tuple[int, int]]] = [] + for timestamp_ns in row["timestamps_ns"]: + timestamp_ns = int(timestamp_ns) + hand_with_dt = hand_provider.get_pose_at_timestamp( + timestamp_ns, + self._api["TimeQueryOptions"].CLOSEST, + self._api["TimeDomain"].TIME_CODE, + 20_000_000, + ) + headset_with_dt = pose_provider.get_pose_at_timestamp( + timestamp_ns, + self._api["TimeQueryOptions"].CLOSEST, + self._api["TimeDomain"].TIME_CODE, + 20_000_000, + ) + if hand_with_dt is None or headset_with_dt is None: + raise RuntimeError( + f"HOT3D 20ms synchronization failure recording={row['recording_id']} " + f"stream={row['stream_id']} timestamp_ns={timestamp_ns} " + f"hand_missing={hand_with_dt is None} " + f"headset_missing={headset_with_dt is None}" + ) + if is_aria: + T_device_camera, calibration = device.get_online_camera_calibration( + stream_id, timestamp_ns, camera_model=self._api["LINEAR"], + ) + else: + T_device_camera, calibration = quest_linear_camera_calibration( + device, stream_id, self._api["LINEAR"], self._api["FISHEYE624"], + ) + image = device.get_undistorted_image(timestamp_ns, stream_id) + if image is None: + raise RuntimeError("official HOT3D provider returned no image") + if image.ndim == 2: + image = np.repeat(image[..., None], 3, axis=-1) + if image.ndim != 3 or image.shape[-1] != 3: + raise ValueError(f"unexpected HOT3D image shape: {image.shape}") + K_raw = linear_camera_matrix(calibration) + image, resized_hw, pad_left_top = _resize_pad( + image, self.target_hw, cv2.INTER_AREA, + ) + K = resize_and_pad_intrinsics( + K_raw, tuple(int(v) for v in calibration.get_image_size()[::-1]), + resized_hw, pad_left_top, + ) + source_hw = tuple(int(v) for v in calibration.get_image_size()[::-1]) + T_world_camera = ( + headset_with_dt.pose3d.T_world_device @ T_device_camera + ) + T_camera_world = np.asarray(T_world_camera.inverse().to_matrix()) + + poses = np.full((2, 48), np.nan, dtype=np.float32) + shapes = np.full((2, 10), np.nan, dtype=np.float32) + wrists = np.full((2, 3), np.nan, dtype=np.float32) + vertices = np.full((2, 778, 3), np.nan, dtype=np.float32) + valid = np.zeros(2, dtype=bool) + collection = hand_with_dt.pose3d_collection + for handedness, side in ( + (self._api["Handedness"].Left, 0), + (self._api["Handedness"].Right, 1), + ): + if handedness not in collection.poses: + continue + hand = collection.poses[handedness] + source_layer = ( + self._source_mano.mano_layer_left + if side == 0 else self._source_mano.mano_layer_right + ) + local_pose = pca_to_full_local_pose(hand.joint_angles, source_layer) + R_camera_world = torch.as_tensor( + T_camera_world[:3, :3], dtype=torch.float32, + ) + R_world_wrist = torch.as_tensor( + hand.wrist_pose.to_matrix()[:3, :3], dtype=torch.float32, + ) + global_pose = matrix_to_axis_angle( + (R_camera_world @ R_world_wrist)[None], + )[0] + source_vertex = hand_provider.get_hand_mesh_vertices(hand) + if source_vertex is None: + continue + # The official provider's mesh is authoritative. Wrist position + # is obtained from its native MANO root by undoing the global + # raw-translation convention through the source layer below. + native_output = source_layer( + betas=shape_params[None], + global_orient=matrix_to_axis_angle(R_world_wrist[None]), + hand_pose=torch.as_tensor(hand.joint_angles)[None], + transl=torch.as_tensor(hand.wrist_pose.to_matrix()[:3, 3])[None], + return_verts=True, + ) + wrist_world = native_output.joints[0, 0].detach().cpu().numpy() + poses[side] = torch.cat((global_pose, local_pose.reshape(-1))).numpy() + shapes[side] = shape_params.numpy() + wrists[side] = transform_points(wrist_world[None], T_camera_world)[0] + vertices[side] = transform_points( + source_vertex.detach().cpu().numpy(), T_camera_world, + ) + valid[side] = True + rgb = image.astype(np.float32) / 255.0 + rgb = (rgb - RGB_MEAN) / RGB_STD + frames.append({ + "rgb": np.transpose(rgb, (2, 0, 1)), + "K": K.astype(np.float32), + "camera_pose": np.asarray(T_world_camera.to_matrix(), dtype=np.float32), + "timestamp_ns": np.int64(timestamp_ns), + "frame_id": np.int64(timestamp_ns), + "hand_pose_time_delta_ns": np.int64(hand_with_dt.time_delta_ns), + "headset_time_delta_ns": np.int64(headset_with_dt.time_delta_ns), + }) + source_vertices.append(vertices) + pose_targets.append(poses) + shape_targets.append(shapes) + wrist_targets.append(wrists) + hand_valid_rows.append(valid) + raw_calibrations.append(calibration) + resize_contracts.append((source_hw, resized_hw, pad_left_top)) + + pose_tensor = torch.from_numpy(np.stack(pose_targets)) + shape_tensor = torch.from_numpy(np.stack(shape_targets)) + wrist_tensor = torch.from_numpy(np.stack(wrist_targets)) + valid_tensor = torch.from_numpy(np.stack(hand_valid_rows)) + rotations = axis_angle_to_matrix( + torch.nan_to_num(pose_tensor).reshape(len(frames), 2, 16, 3) + ) + with torch.no_grad(): + target_vertices, target_joints = self._target_mano( + rotations, torch.nan_to_num(shape_tensor), + torch.nan_to_num(wrist_tensor), + ) + source_vertex_tensor = torch.from_numpy(np.stack(source_vertices)) + vertex_error_mm = torch.linalg.vector_norm( + target_vertices - source_vertex_tensor, dim=-1, + ).amax(dim=-1) * 1000.0 + geometry_valid = geometry_valid_mask(valid_tensor, vertex_error_mm) + + K_tensor = torch.from_numpy(np.stack([frame["K"] for frame in frames])) + joint2d, positive = project_points(target_joints, K_tensor) + time = len(frames) + projection_error = torch.full((time, 2, 21), float("nan")) + for frame_index, calibration in enumerate(raw_calibrations): + source_hw, resized_hw, (pad_left, pad_top) = resize_contracts[frame_index] + scale_x = resized_hw[1] / source_hw[1] + scale_y = resized_hw[0] / source_hw[0] + for side in range(2): + if not geometry_valid[frame_index, side]: + continue + for joint_index, point in enumerate(target_joints[frame_index, side]): + source_uv = calibration.project(point.detach().cpu().numpy()) + if source_uv is None: + continue + resized_uv = torch.tensor( + ( + float(source_uv[0]) * scale_x + pad_left, + float(source_uv[1]) * scale_y + pad_top, + ), + dtype=joint2d.dtype, + ) + projection_error[frame_index, side, joint_index] = ( + torch.linalg.vector_norm( + resized_uv - joint2d[frame_index, side, joint_index] + ) + ) + geometry_valid, joint2d_valid, joint3d_valid = hot3d_supervision_masks( + geometry_valid, source_vertex_tensor, joint2d, positive, + projection_error, K_tensor, self.target_hw, + ) + for tensor in (target_vertices, target_joints, joint2d, pose_tensor, shape_tensor, wrist_tensor): + mask = geometry_valid + while mask.ndim < tensor.ndim: + mask = mask.unsqueeze(-1) + tensor.masked_fill_(~mask, float("nan")) + output: dict[str, Any] = { + "rgb": torch.from_numpy(np.stack([frame["rgb"] for frame in frames])), + "depth_m": torch.zeros((time, 1, *self.target_hw), dtype=torch.float32), + "depth_pixel_valid": torch.zeros((time, 1, *self.target_hw), dtype=torch.bool), + "K": K_tensor, + "camera_pose": torch.from_numpy(np.stack([frame["camera_pose"] for frame in frames])), + "joint3d_camera": target_joints, + "joint2d": joint2d, + "joint_element_valid": joint3d_valid, + "mano_pose": pose_tensor, + "mano_shape": shape_tensor, + "mano_translation_raw": torch.full_like(wrist_tensor, float("nan")), + "wrist_root_translation": wrist_tensor, + "joint_annotation_valid": geometry_valid, + "mano_annotation_valid": geometry_valid, + "joint2d_valid": joint2d_valid, + "joint3d_valid": joint3d_valid, + "translation_valid": geometry_valid, + "mano_pose_valid": geometry_valid, + "shape_valid": geometry_valid, + "vertices_valid": geometry_valid, + "reprojection_valid": joint2d_valid, + "vertices_camera": target_vertices, + "presence_target": torch.full((time, 2), float("nan")), + "presence_label_valid": torch.zeros((time, 2), dtype=torch.bool), + "presence_valid": torch.zeros((time, 2), dtype=torch.bool), + "depth_available": torch.zeros(time, dtype=torch.bool), + "K_available": torch.full((time,), keep_K, dtype=torch.bool), + "depth_input_available": torch.zeros(time, dtype=torch.bool), + "K_input_available": torch.full((time,), keep_K, dtype=torch.bool), + "K_supervision_valid": torch.ones(time, dtype=torch.bool), + "frame_valid": torch.ones(time, dtype=torch.bool), + "hand_side_id": torch.tensor((0, 1))[None].expand(time, -1).clone(), + "timestamp_ns": torch.tensor([frame["timestamp_ns"] for frame in frames]), + "frame_id": torch.tensor([frame["frame_id"] for frame in frames]), + "hand_pose_time_delta_ns": torch.tensor([frame["hand_pose_time_delta_ns"] for frame in frames]), + "headset_time_delta_ns": torch.tensor([frame["headset_time_delta_ns"] for frame in frames]), + "source_vertex_regen_error_mm": vertex_error_mm, + "source_hand_annotation_present": valid_tensor, + "geometry_convention_compatible": geometry_valid, + "projection_roundtrip_error_px": projection_error, + "image_hw": torch.tensor(self.target_hw, dtype=torch.long), + "dataset_id": "HOT3D", + "subject_id": str(row["participant_id"]), + "sequence_id": str(row["recording_id"]), + "physical_recording_id": str(row["recording_id"]), + "camera_id": str(row["stream_id"]), + "stream_id": str(row["stream_id"]), + "headset_id": str(row["headset"]), + } + return output diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/oracle_crop.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/oracle_crop.py new file mode 100644 index 0000000000000000000000000000000000000000..b615a58c3762a9ab88ed870acf5b6bc532d8ba6e --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/oracle_crop.py @@ -0,0 +1,105 @@ +"""Pre-registered raw-image crop geometry for the A3 oracle diagnostic.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import cv2 +import numpy as np + +from foundation_hand.geometry.camera import resize_and_pad_intrinsics + + +@dataclass(frozen=True) +class OracleCropSpec: + x0: int + y0: int + side: int + source_hw: tuple[int, int] + output_hw: tuple[int, int] = (224, 224) + + @property + def x1(self) -> int: + return self.x0 + self.side + + @property + def y1(self) -> int: + return self.y0 + self.side + + +def oracle_square_crop_spec( + joints_2d: np.ndarray, + joint_valid: np.ndarray, + source_hw: tuple[int, int], + *, + margin: float = 1.5, + min_side: int = 96, + min_points: int = 4, + output_hw: tuple[int, int] = (224, 224), +) -> OracleCropSpec | None: + """Build the fixed A3 square ROI from valid GT joint locations.""" + + points = np.asarray(joints_2d, dtype=np.float64) + valid = np.asarray(joint_valid, dtype=bool) + if points.shape != (21, 2) or valid.shape != (21,): + raise ValueError("expected joints [21,2] and validity [21]") + source_h, source_w = (int(value) for value in source_hw) + output_h, output_w = (int(value) for value in output_hw) + if min(source_h, source_w, output_h, output_w, min_side, min_points) <= 0: + raise ValueError("image sizes, minimum side, and minimum points must be positive") + if margin < 1.0: + raise ValueError("crop margin must be at least 1") + valid &= np.isfinite(points).all(axis=-1) + if int(valid.sum()) < min_points: + return None + selected = points[valid] + lower = selected.min(axis=0) + upper = selected.max(axis=0) + center = 0.5 * (lower + upper) + side = int(np.ceil(max(float(np.max(upper - lower)) * margin, float(min_side)))) + x0 = int(np.floor(float(center[0]) - side / 2.0)) + y0 = int(np.floor(float(center[1]) - side / 2.0)) + if x0 >= source_w or y0 >= source_h or x0 + side <= 0 or y0 + side <= 0: + return None + return OracleCropSpec(x0, y0, side, (source_h, source_w), (output_h, output_w)) + + +def crop_resize_with_padding( + array: np.ndarray, + spec: OracleCropSpec, + *, + interpolation: int, + fill: int | float = 0, +) -> np.ndarray: + """Apply an integer square crop, explicit padding, then one resize.""" + + value = np.asarray(array) + if value.shape[:2] != spec.source_hw: + raise ValueError(f"source shape {value.shape[:2]} does not match {spec.source_hw}") + crop_shape = (spec.side, spec.side) + value.shape[2:] + crop = np.full(crop_shape, fill, dtype=value.dtype) + source_h, source_w = spec.source_hw + source_x0, source_y0 = max(0, spec.x0), max(0, spec.y0) + source_x1, source_y1 = min(source_w, spec.x1), min(source_h, spec.y1) + if source_x1 > source_x0 and source_y1 > source_y0: + target_x0, target_y0 = source_x0 - spec.x0, source_y0 - spec.y0 + crop[ + target_y0 : target_y0 + source_y1 - source_y0, + target_x0 : target_x0 + source_x1 - source_x0, + ] = value[source_y0:source_y1, source_x0:source_x1] + output_h, output_w = spec.output_hw + return cv2.resize(crop, (output_w, output_h), interpolation=interpolation) + + +def crop_resize_intrinsics(K: np.ndarray, spec: OracleCropSpec) -> np.ndarray: + """Update raw intrinsics for the exact integer-crop/resize transform.""" + + matrix = np.asarray(K, dtype=np.float32) + if matrix.shape != (3, 3): + raise ValueError(f"expected K [3,3], got {matrix.shape}") + crop_K = matrix.copy() + crop_K[0, 2] -= spec.x0 + crop_K[1, 2] -= spec.y0 + return resize_and_pad_intrinsics( + crop_K, (spec.side, spec.side), spec.output_hw, (0, 0), + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/samplers.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..bf66124e4179cb7965c062132f17b2124003d6c8 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/samplers.py @@ -0,0 +1,240 @@ +"""Deterministic batch sampling that can resume exactly from a global step.""" + +from __future__ import annotations + +import math +import hashlib +import json +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import torch +from torch.utils.data import Sampler + + +SampleIndex = int | tuple[int, int] + + +class ResumableRandomBatchSampler(Sampler[list[SampleIndex]]): + """Generate an epoch permutation from ``seed + epoch``. + + The batch at a given global step is a pure function of the dataset size, + batch size, seed, and step. Reconstructing the sampler with ``start_step`` + therefore produces the same remaining batches after a checkpoint resume. + """ + + def __init__( + self, + dataset_size: int, + batch_size: int, + seed: int, + start_step: int, + end_step: int, + include_epoch: bool = False, + ) -> None: + if dataset_size <= 0: + raise ValueError("dataset_size must be positive") + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0 <= start_step <= end_step: + raise ValueError(f"Invalid step range: [{start_step}, {end_step})") + self.dataset_size = dataset_size + self.batch_size = batch_size + self.seed = seed + self.start_step = start_step + self.end_step = end_step + self.include_epoch = include_epoch + self.steps_per_epoch = math.ceil(dataset_size / batch_size) + + def __len__(self) -> int: + return self.end_step - self.start_step + + def __iter__(self) -> Iterator[list[SampleIndex]]: + cached_epoch = -1 + permutation: list[int] = [] + for step in range(self.start_step, self.end_step): + epoch, batch_in_epoch = divmod(step, self.steps_per_epoch) + if epoch != cached_epoch: + generator = torch.Generator().manual_seed(self.seed + epoch) + permutation = torch.randperm(self.dataset_size, generator=generator).tolist() + cached_epoch = epoch + start = batch_in_epoch * self.batch_size + indices = permutation[start : min(start + self.batch_size, self.dataset_size)] + if self.include_epoch: + yield [(index, epoch) for index in indices] + else: + yield indices + + +class ResumableWeightedBatchSampler(Sampler[list[SampleIndex]]): + """Draw a deterministic weighted epoch with replacement. + + Each epoch contains ``dataset_size`` draws. The draw sequence is a pure + function of the weights, seed, and epoch, so resuming at a global step + reproduces the uninterrupted batches exactly. + """ + + def __init__( + self, + weights: torch.Tensor | list[float], + batch_size: int, + seed: int, + start_step: int, + end_step: int, + include_epoch: bool = False, + ) -> None: + values = torch.as_tensor(weights, dtype=torch.float64, device="cpu") + if values.ndim != 1 or values.numel() == 0: + raise ValueError("weights must be a non-empty one-dimensional sequence") + if not torch.isfinite(values).all() or bool((values <= 0).any()): + raise ValueError("weights must be finite and strictly positive") + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0 <= start_step <= end_step: + raise ValueError(f"Invalid step range: [{start_step}, {end_step})") + self.weights = values + self.dataset_size = int(values.numel()) + self.batch_size = batch_size + self.seed = seed + self.start_step = start_step + self.end_step = end_step + self.include_epoch = include_epoch + self.steps_per_epoch = math.ceil(self.dataset_size / batch_size) + + def __len__(self) -> int: + return self.end_step - self.start_step + + def __iter__(self) -> Iterator[list[SampleIndex]]: + cached_epoch = -1 + draws: list[int] = [] + for step in range(self.start_step, self.end_step): + epoch, batch_in_epoch = divmod(step, self.steps_per_epoch) + if epoch != cached_epoch: + generator = torch.Generator().manual_seed(self.seed + epoch) + draws = torch.multinomial( + self.weights, + num_samples=self.dataset_size, + replacement=True, + generator=generator, + ).tolist() + cached_epoch = epoch + start = batch_in_epoch * self.batch_size + indices = draws[start : min(start + self.batch_size, self.dataset_size)] + if self.include_epoch: + yield [(index, epoch) for index in indices] + else: + yield indices + + +class ResumableMixtureBatchSampler(Sampler[list[SampleIndex]]): + """Draw an exact-resume batch from a registered dataset mixture. + + Source selection is independent of source length, so a large frame-count + dataset cannot silently dominate a registered mixture. Sampling within a + source is uniform with replacement and is a pure function of global step. + """ + + def __init__( + self, + source_sizes: list[int] | tuple[int, ...], + source_weights: list[float] | tuple[float, ...], + batch_size: int, + seed: int, + start_step: int, + end_step: int, + include_epoch: bool = False, + ) -> None: + sizes = torch.as_tensor(source_sizes, dtype=torch.int64) + weights = torch.as_tensor(source_weights, dtype=torch.float64) + if sizes.ndim != 1 or sizes.numel() == 0 or bool((sizes <= 0).any()): + raise ValueError("source_sizes must be a non-empty positive sequence") + if weights.shape != sizes.shape: + raise ValueError("source_weights must match source_sizes") + if not torch.isfinite(weights).all() or bool((weights <= 0).any()): + raise ValueError("source_weights must be finite and positive") + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0 <= start_step <= end_step: + raise ValueError(f"Invalid step range: [{start_step}, {end_step})") + self.source_sizes = sizes + self.source_weights = weights / weights.sum() + self.source_offsets = torch.cat((sizes.new_zeros(1), sizes.cumsum(0)[:-1])) + self.batch_size = int(batch_size) + self.seed = int(seed) + self.start_step = int(start_step) + self.end_step = int(end_step) + self.include_epoch = bool(include_epoch) + self.steps_per_epoch = math.ceil(int(sizes.sum()) / self.batch_size) + + def __len__(self) -> int: + return self.end_step - self.start_step + + def __iter__(self) -> Iterator[list[SampleIndex]]: + for step in range(self.start_step, self.end_step): + generator = torch.Generator().manual_seed(self.seed + step) + source_ids = torch.multinomial( + self.source_weights, + num_samples=self.batch_size, + replacement=True, + generator=generator, + ) + indices: list[SampleIndex] = [] + epoch = step // self.steps_per_epoch + for source_id in source_ids.tolist(): + local_index = int(torch.randint( + int(self.source_sizes[source_id]), + (1,), generator=generator, + )) + global_index = int(self.source_offsets[source_id]) + local_index + indices.append((global_index, epoch) if self.include_epoch else global_index) + yield indices + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_balanced_sampling_weights( + path: str | Path, + train_manifest: str | Path, + data_config: dict[str, Any], + dataset_size: int, +) -> tuple[list[float], dict[str, Any]]: + """Validate and load a train-only Phase 4 balanced-sampling manifest.""" + + manifest_path = Path(path) + train_manifest_path = Path(train_manifest) + record = json.loads(manifest_path.read_text(encoding="utf-8")) + if record.get("version") != "phase4_train_geometry_balanced_v1": + raise ValueError("unsupported balanced-sampling manifest version") + if record.get("split_role") != "official_train" or record.get("official_test_used") is not False: + raise ValueError("balanced sampling must be built from official train only") + if record.get("source_manifest_sha256") != _sha256(train_manifest_path): + raise ValueError("balanced-sampling source hash does not match --manifest") + contract = record.get("dataset_contract", {}) + expected_contract = { + "resolution_hw": list(data_config["resolution_hw"]), + "T": int(data_config["T"]), + "stride": int(data_config["stride"]), + } + for key, expected in expected_contract.items(): + if contract.get(key) != expected: + raise ValueError( + f"balanced-sampling contract mismatch for {key}: " + f"{contract.get(key)} != {expected}" + ) + rows = record.get("clips", []) + if len(rows) != dataset_size or record.get("clip_count") != dataset_size: + raise ValueError("balanced-sampling clip count does not match the training dataset") + indices = [row.get("clip_index") for row in rows] + if indices != list(range(dataset_size)): + raise ValueError("balanced-sampling clip indices must be ordered and complete") + weights = torch.as_tensor([row.get("weight") for row in rows], dtype=torch.float64) + if not torch.isfinite(weights).all() or bool((weights <= 0).any()): + raise ValueError("balanced-sampling weights must be finite and strictly positive") + return weights.tolist(), record diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/schema.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..15e3e8a1bdb388388060e4f27b01fbea4fa22104 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/data/schema.py @@ -0,0 +1,89 @@ +"""Unified multi-source sample supervision and modality contracts.""" + +from __future__ import annotations + +from typing import Mapping + +import torch + + +class InvalidSourceSampleError(RuntimeError): + """A manifest row points to missing, unreadable, or malformed source data.""" + + +SUPERVISION_MASK_KEYS = ( + "joint2d_valid", + "joint3d_valid", + "joint3d_root_relative_valid", + "translation_valid", + "mano_pose_valid", + "shape_valid", + "vertices_valid", + "reprojection_valid", + "presence_valid", + "K_supervision_valid", +) + + +def source_root_relative_joint_target( + joints_camera: torch.Tensor, + hand_valid: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Keep credible source-layer joint geometry separate from MANO compatibility.""" + + if joints_camera.shape[-2:] != (21, 3): + raise ValueError("source joints must end in [21,3]") + if hand_valid.shape != joints_camera.shape[:-2]: + raise ValueError("hand-valid mask differs from source joint prefix") + relative = joints_camera - joints_camera[..., :1, :] + valid = hand_valid[..., None] & torch.isfinite(relative).all(dim=-1) + relative = relative.masked_fill(~valid[..., None], float("nan")) + return relative, valid + +INPUT_AVAILABILITY_KEYS = ( + "depth_input_available", + "K_input_available", +) + + +def supervision_mask( + batch: Mapping[str, torch.Tensor], + key: str, + fallback: torch.Tensor, +) -> torch.Tensor: + """Resolve a Phase 7 mask while preserving historical batch behavior.""" + + value = batch.get(key) + return fallback.bool() if value is None else value.bool() + + +def input_availability( + batch: Mapping[str, torch.Tensor], + key: str, + legacy_key: str, + fallback: torch.Tensor, +) -> torch.Tensor: + """Keep model-input availability separate from geometry supervision.""" + + value = batch.get(key) + if value is None: + value = batch.get(legacy_key, fallback) + return value.bool() + + +def deterministic_clip_keep( + probability: float, + seed: int, + clip_index: int, + epoch: int, +) -> bool: + """Deterministic clip-level Bernoulli used by external input dropout.""" + + if not 0.0 <= probability <= 1.0: + raise ValueError("probability must be in [0, 1]") + generator = torch.Generator(device="cpu") + generator.manual_seed( + (int(seed) * 1_000_003 + int(clip_index) * 9_176 + int(epoch)) + % (2**63 - 1) + ) + return bool(torch.rand((), generator=generator).item() < probability) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/__init__.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..981c62ba4cc30967189bc146bb40d8fe3e3635f8 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/__init__.py @@ -0,0 +1,6 @@ +"""Evaluation and visualization utilities for camera-space reconstruction.""" + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.selection import select_visualization_frames + +__all__ = ["bootstrap_take_means", "distribution_summary", "select_visualization_frames"] diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/alignment_calibration.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/alignment_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..458feac1e2e30ca149ae69fd3fa91bdb346d0d02 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/alignment_calibration.py @@ -0,0 +1,70 @@ +"""Shared feature contract for OOF metric-alignment calibration and inference.""" + +from __future__ import annotations + +import numpy as np + + +FEATURE_NAMES = ( + "raw_alignment_delta_z_m", + "log_valid_support_count", + "inlier_ratio", + "residual_scale_m", + "valid_fraction", + "foreground_fraction", + "background_fraction", + "depth_discontinuity_m", + "conditioning_quality", + "coarse_wrist_z_m", + "log_hand_scale_px", + "direct_mano_consistency_px", + "silhouette_overlap_fraction", + "coarse_velocity_z_m_per_frame", + "side_right", +) + + +def projected_hand_scale_px( + projected_joints_px: np.ndarray, + *, + source_hw: tuple[int, int], + target_hw: tuple[int, int], +) -> np.ndarray: + """Measure projected hand extent after mapping source pixels to model pixels.""" + + source_height, source_width = source_hw + target_height, target_width = target_hw + if min(source_height, source_width, target_height, target_width) <= 0: + raise ValueError("source and target image dimensions must be positive") + scale = np.asarray( + (target_width / source_width, target_height / source_height), dtype=np.float32, + ) + resized = np.asarray(projected_joints_px, dtype=np.float32) * scale + return np.ptp(resized, axis=-2).max(axis=-1) + + +def features_from_take(arrays: dict[str, np.ndarray]) -> np.ndarray: + """Create `[time,left/right,feature]` geometry-only calibration inputs.""" + + time = len(arrays["frame_id"]) + side_right = np.broadcast_to(np.asarray((0.0, 1.0), dtype=np.float32), (time, 2)) + overlap = np.broadcast_to(arrays["silhouette_overlap_fraction"][:, None], (time, 2)) + values = ( + arrays["alignment_delta_z_m"], + np.log1p(arrays["alignment_valid_support_count"]), + arrays["alignment_inlier_ratio"], + arrays["alignment_residual_scale_m"], + arrays["alignment_valid_fraction"], + arrays["alignment_foreground_fraction"], + arrays["alignment_background_fraction"], + arrays["alignment_depth_discontinuity_m"], + arrays["alignment_conditioning_quality"], + arrays["pred_wrist_translation"][..., 2], + np.log1p(np.maximum(arrays["coarse_hand_scale_px"], 0.0)), + arrays["coarse_direct_mano_consistency_px"], + overlap, + arrays["coarse_wrist_velocity_m_per_frame"][..., 2], + side_right, + ) + features = np.stack(values, axis=-1).astype(np.float64) + return np.nan_to_num(features, nan=0.0, posinf=0.0, neginf=0.0) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/causal_state.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..66dea1ca7230f736d8ffb5f32f645ed7b862f4b7 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/causal_state.py @@ -0,0 +1,121 @@ +"""Causal translation-z state estimators for Phase 5 deployment.""" + +from __future__ import annotations + +import numpy as np + + +def measurement_uncertainty_multiplier( + confidence: np.ndarray, + inlier_ratio: np.ndarray, + residual_scale_m: np.ndarray, + valid_fraction: np.ndarray, + conditioning_quality: np.ndarray, + strength: float, +) -> np.ndarray: + """Map bounded geometry diagnostics to a deterministic measurement-noise scale.""" + + if strength < 0.0: + raise ValueError("uncertainty strength must be non-negative") + components = np.stack(( + 1.0 - np.clip(confidence, 0.0, 1.0), + 1.0 - np.clip(inlier_ratio, 0.0, 1.0), + np.clip(residual_scale_m / 0.02, 0.0, 2.0) / 2.0, + 1.0 - np.clip(valid_fraction, 0.0, 1.0), + 1.0 - np.clip(conditioning_quality, 0.0, 1.0), + ), axis=-1) + return np.clip(1.0 + strength * components.mean(axis=-1), 1.0, 5.0) + + +def causal_constant_velocity_kalman( + measurement_m: np.ndarray, + *, + frame_id: np.ndarray, + segment_id: np.ndarray | None = None, + valid: np.ndarray, + measurement_available: np.ndarray, + process_sigma_m_per_frame2: float, + measurement_sigma_m: float, + uncertainty_multiplier: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray]: + """Filter `[time,hand]` z measurements without crossing invalid/discontinuous frames.""" + + measurement = np.asarray(measurement_m, dtype=np.float64) + frame_id = np.asarray(frame_id, dtype=np.int64) + segment = ( + np.zeros(len(measurement), dtype=np.int64) + if segment_id is None else np.asarray(segment_id) + ) + valid = np.asarray(valid, dtype=bool) + available = np.asarray(measurement_available, dtype=bool) + if measurement.ndim != 2 or measurement.shape[1] != 2: + raise ValueError("measurement_m must have shape [time,2]") + if ( + frame_id.shape != (len(measurement),) + or segment.shape != (len(measurement),) + or valid.shape != (len(measurement),) + ): + raise ValueError("frame_id, segment_id, and valid must have shape [time]") + if available.shape != measurement.shape: + raise ValueError("measurement_available must match measurement_m") + if process_sigma_m_per_frame2 <= 0.0 or measurement_sigma_m <= 0.0: + raise ValueError("Kalman noise scales must be positive") + if uncertainty_multiplier is None: + multiplier = np.ones_like(measurement) + else: + multiplier = np.asarray(uncertainty_multiplier, dtype=np.float64) + if multiplier.shape != measurement.shape or np.any(multiplier < 1.0): + raise ValueError("uncertainty_multiplier must match measurements and be >=1") + + output = measurement.copy() + variance = np.full_like(measurement, np.nan) + transition = np.asarray(((1.0, 1.0), (0.0, 1.0)), dtype=np.float64) + observation = np.asarray((1.0, 0.0), dtype=np.float64) + q = process_sigma_m_per_frame2**2 * np.asarray( + ((0.25, 0.5), (0.5, 1.0)), dtype=np.float64, + ) + + for hand in range(2): + initialized = False + state = np.zeros(2, dtype=np.float64) + covariance = np.eye(2, dtype=np.float64) + previous_frame = -1 + previous_segment: object = None + for index in range(len(measurement)): + contiguous = ( + initialized + and frame_id[index] == previous_frame + 1 + and segment[index] == previous_segment + ) + if not valid[index] or not contiguous: + initialized = False + if not valid[index]: + output[index, hand] = measurement[index, hand] + previous_frame = int(frame_id[index]) + previous_segment = segment[index] + continue + if not initialized: + if not available[index, hand] or not np.isfinite(measurement[index, hand]): + output[index, hand] = measurement[index, hand] + previous_frame = int(frame_id[index]) + previous_segment = segment[index] + continue + state[:] = (measurement[index, hand], 0.0) + initial_variance = (measurement_sigma_m * multiplier[index, hand]) ** 2 + covariance = np.diag((initial_variance, 4.0 * initial_variance)) + initialized = True + else: + state = transition @ state + covariance = transition @ covariance @ transition.T + q + if available[index, hand] and np.isfinite(measurement[index, hand]): + r = (measurement_sigma_m * multiplier[index, hand]) ** 2 + innovation = measurement[index, hand] - observation @ state + innovation_variance = float(observation @ covariance @ observation + r) + gain = covariance @ observation / innovation_variance + state = state + gain * innovation + covariance = (np.eye(2) - np.outer(gain, observation)) @ covariance + output[index, hand] = state[0] + variance[index, hand] = covariance[0, 0] + previous_frame = int(frame_id[index]) + previous_segment = segment[index] + return output.astype(np.float32), variance.astype(np.float32) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/harm_risk.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc2a46bd4f7c4cdcee6de1fbb10dfb6b37add31 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/harm_risk.py @@ -0,0 +1,71 @@ +"""Predicted-only feature contract for Phase 6 harmful-correction risk.""" + +from __future__ import annotations + +import numpy as np + + +HARM_RISK_FEATURE_NAMES = ( + "calibrated_delta_z_m", "abs_calibrated_delta_z_m", + "raw_delta_z_m", "abs_raw_delta_z_m", "raw_calibrated_disagreement_m", + "existing_confidence", "alignment_available", "raw_alignment_available", + "valid_support_count", "projected_support_count", "inlier_ratio", + "residual_scale_m", "valid_fraction", "foreground_fraction", + "background_fraction", "depth_discontinuity_m", "conditioning_quality", + "silhouette_overlap_fraction", "coarse_hand_scale_px", + "coarse_direct_mano_consistency_px", "coarse_z_m", "coarse_ray_x", + "coarse_ray_y", "coarse_wrist_velocity_norm_m_per_frame", + "predicted_depth_order", "side_right", +) + + +def harm_risk_features( + *, + calibrated_delta_z_m: np.ndarray, + raw_delta_z_m: np.ndarray, + confidence: np.ndarray, + alignment_available: np.ndarray, + raw_alignment_available: np.ndarray, + valid_support_count: np.ndarray, + projected_support_count: np.ndarray, + inlier_ratio: np.ndarray, + residual_scale_m: np.ndarray, + valid_fraction: np.ndarray, + foreground_fraction: np.ndarray, + background_fraction: np.ndarray, + depth_discontinuity_m: np.ndarray, + conditioning_quality: np.ndarray, + silhouette_overlap_fraction: np.ndarray, + coarse_hand_scale_px: np.ndarray, + coarse_direct_mano_consistency_px: np.ndarray, + coarse_wrist_translation: np.ndarray, + coarse_wrist_velocity_m_per_frame: np.ndarray, + predicted_depth_order: np.ndarray, +) -> np.ndarray: + calibrated = np.asarray(calibrated_delta_z_m, dtype=np.float64) + raw = np.asarray(raw_delta_z_m, dtype=np.float64) + if calibrated.ndim != 2 or calibrated.shape[1] != 2 or raw.shape != calibrated.shape: + raise ValueError("risk delta-z arrays must have shape [time,2]") + time = len(calibrated) + overlap = np.broadcast_to( + np.asarray(silhouette_overlap_fraction)[:, None], (time, 2), + ) + depth_order = np.broadcast_to( + np.asarray(predicted_depth_order)[:, None], (time, 2), + ) + side = np.broadcast_to(np.asarray((0.0, 1.0)), (time, 2)) + translation = np.asarray(coarse_wrist_translation, dtype=np.float64) + z = np.maximum(translation[..., 2], 1e-6) + velocity_norm = np.linalg.norm(coarse_wrist_velocity_m_per_frame, axis=-1) + values = ( + calibrated, np.abs(calibrated), raw, np.abs(raw), np.abs(raw - calibrated), + confidence, alignment_available, raw_alignment_available, + valid_support_count, projected_support_count, inlier_ratio, + residual_scale_m, valid_fraction, foreground_fraction, + background_fraction, depth_discontinuity_m, conditioning_quality, + overlap, coarse_hand_scale_px, coarse_direct_mano_consistency_px, + translation[..., 2], translation[..., 0] / z, translation[..., 1] / z, + velocity_norm, depth_order, side, + ) + features = np.stack(values, axis=-1).astype(np.float32) + return np.nan_to_num(features, nan=0.0, posinf=1e6, neginf=-1e6) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/local_depth.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7ba9904db72607171a18a6c7415efd2a09ffdf --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/local_depth.py @@ -0,0 +1,231 @@ +"""Oracle local-depth feature extraction and bounded wrist-z residual models.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +import torch +from torch import nn + + +ANCHOR_JOINTS = (0, 4, 5, 8, 9, 12, 13, 16, 17, 20) +WINDOW_RADII = (3, 7, 15) +BBOX_MARGINS = (0.10, 0.30, 0.60) +DEPTH_STAT_NAMES = ( + "valid_fraction", + "q10_m", + "q25_m", + "q50_m", + "q75_m", + "q90_m", + "iqr_m", + "discontinuity_m", +) + + +def _depth_statistics(depth_m: np.ndarray, valid: np.ndarray) -> np.ndarray: + mask = np.asarray(valid, dtype=bool) & np.isfinite(depth_m) & (depth_m > 0.0) + valid_fraction = float(mask.mean()) if mask.size else 0.0 + values = np.asarray(depth_m, dtype=np.float64)[mask] + if not values.size: + return np.asarray([valid_fraction, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], dtype=np.float32) + q10, q25, q50, q75, q90 = np.percentile(values, (10, 25, 50, 75, 90)) + return np.asarray([ + valid_fraction, + q10, + q25, + q50, + q75, + q90, + q75 - q25, + q90 - q10, + ], dtype=np.float32) + + +def _clipped_region( + center_xy: np.ndarray, + half_size_xy: np.ndarray, + image_hw: tuple[int, int], +) -> tuple[slice, slice]: + height, width = image_hw + x0 = max(0, int(np.floor(float(center_xy[0] - half_size_xy[0])))) + y0 = max(0, int(np.floor(float(center_xy[1] - half_size_xy[1])))) + x1 = min(width, int(np.ceil(float(center_xy[0] + half_size_xy[0]))) + 1) + y1 = min(height, int(np.ceil(float(center_xy[1] + half_size_xy[1]))) + 1) + return slice(y0, max(y0, y1)), slice(x0, max(x0, x1)) + + +def _geometry_from_median( + center_xy: np.ndarray, + median_depth_m: float, + K: np.ndarray, +) -> np.ndarray: + if median_depth_m <= 0.0 or not np.isfinite(median_depth_m): + return np.zeros(5, dtype=np.float32) + x_ray = (float(center_xy[0]) - float(K[0, 2])) / float(K[0, 0]) + y_ray = (float(center_xy[1]) - float(K[1, 2])) / float(K[1, 1]) + return np.asarray([ + x_ray * median_depth_m, + y_ray * median_depth_m, + median_depth_m, + np.log(max(median_depth_m, 1e-6)), + 1.0, + ], dtype=np.float32) + + +@dataclass(frozen=True) +class OracleLocalDepthFeatures: + control: np.ndarray + local: np.ndarray + control_names: tuple[str, ...] + local_names: tuple[str, ...] + local_valid_fraction: float + local_depth_discontinuity_m: float + + +def oracle_local_depth_features( + depth_m: np.ndarray, + depth_valid: np.ndarray, + joints_2d_raw: np.ndarray, + K_raw: np.ndarray, + coarse_translation_m: np.ndarray, + side_index: int, +) -> OracleLocalDepthFeatures: + """Extract oracle-location features without using GT wrist depth as input.""" + + depth_m = np.asarray(depth_m, dtype=np.float32) + depth_valid = np.asarray(depth_valid, dtype=bool) + joints = np.asarray(joints_2d_raw, dtype=np.float32) + K = np.asarray(K_raw, dtype=np.float32) + coarse = np.asarray(coarse_translation_m, dtype=np.float32) + if depth_m.ndim != 2 or depth_valid.shape != depth_m.shape: + raise ValueError("raw metric depth and validity must be aligned HxW arrays") + if joints.shape != (21, 2) or K.shape != (3, 3) or coarse.shape != (3,): + raise ValueError("unexpected joint/K/coarse feature shape") + if side_index not in (0, 1): + raise ValueError("side_index must be 0 for left or 1 for right") + + height, width = depth_m.shape + finite = np.isfinite(joints).all(axis=-1) + if finite.any(): + minimum = joints[finite].min(axis=0) + maximum = joints[finite].max(axis=0) + center = 0.5 * (minimum + maximum) + extent = np.maximum(maximum - minimum, 1.0) + else: + center = np.asarray([width / 2.0, height / 2.0], dtype=np.float32) + extent = np.ones(2, dtype=np.float32) + + control_names = ( + "coarse_x_m", + "coarse_y_m", + "coarse_z_m", + "log_coarse_z", + "bbox_center_u_norm", + "bbox_center_v_norm", + "bbox_width_norm", + "bbox_height_norm", + "fx_norm", + "fy_norm", + "cx_norm", + "cy_norm", + "side_left", + "side_right", + ) + control = np.asarray([ + coarse[0], + coarse[1], + coarse[2], + np.log(max(float(coarse[2]), 1e-6)), + center[0] / width, + center[1] / height, + extent[0] / width, + extent[1] / height, + K[0, 0] / width, + K[1, 1] / height, + K[0, 2] / width, + K[1, 2] / height, + float(side_index == 0), + float(side_index == 1), + ], dtype=np.float32) + + local_values: list[float] = [] + local_names: list[str] = [] + anchor_validities: list[float] = [] + anchor_discontinuities: list[float] = [] + for joint_index in ANCHOR_JOINTS: + joint_center = joints[joint_index] if finite[joint_index] else center + for radius in WINDOW_RADII: + y_slice, x_slice = _clipped_region( + joint_center, + np.asarray([radius, radius], dtype=np.float32), + (height, width), + ) + statistics = _depth_statistics( + depth_m[y_slice, x_slice], depth_valid[y_slice, x_slice] + ) + geometry = _geometry_from_median(joint_center, float(statistics[3]), K) + prefix = f"joint{joint_index:02d}_r{radius}" + local_values.extend(statistics.tolist()) + local_names.extend(f"{prefix}_{name}" for name in DEPTH_STAT_NAMES) + local_values.extend(geometry.tolist()) + local_names.extend( + f"{prefix}_{name}" for name in ("median_x_m", "median_y_m", "median_z_m", "log_median_z", "median_valid") + ) + local_values.append(float(statistics[3] - coarse[2]) if statistics[0] > 0 else 0.0) + local_names.append(f"{prefix}_median_minus_coarse_z_m") + anchor_validities.append(float(statistics[0])) + anchor_discontinuities.append(float(statistics[7])) + + for margin in BBOX_MARGINS: + half_size = np.maximum(extent * (0.5 + margin), 4.0) + y_slice, x_slice = _clipped_region(center, half_size, (height, width)) + statistics = _depth_statistics(depth_m[y_slice, x_slice], depth_valid[y_slice, x_slice]) + geometry = _geometry_from_median(center, float(statistics[3]), K) + prefix = f"bbox_m{int(round(margin * 100)):02d}" + local_values.extend(statistics.tolist()) + local_names.extend(f"{prefix}_{name}" for name in DEPTH_STAT_NAMES) + local_values.extend(geometry.tolist()) + local_names.extend( + f"{prefix}_{name}" for name in ("median_x_m", "median_y_m", "median_z_m", "log_median_z", "median_valid") + ) + local_values.append(float(statistics[3] - coarse[2]) if statistics[0] > 0 else 0.0) + local_names.append(f"{prefix}_median_minus_coarse_z_m") + + local_array = np.asarray(local_values, dtype=np.float32) + if not np.isfinite(control).all() or not np.isfinite(local_array).all(): + raise ValueError("oracle local-depth feature extraction produced non-finite values") + return OracleLocalDepthFeatures( + control=control, + local=np.concatenate((control, local_array)).astype(np.float32), + control_names=control_names, + local_names=control_names + tuple(local_names), + local_valid_fraction=float(np.mean(anchor_validities)), + local_depth_discontinuity_m=float(np.mean(anchor_discontinuities)), + ) + + +class BoundedZResidualRegressor(nn.Module): + """Small zero-initialized residual MLP for an oracle diagnostic.""" + + def __init__( + self, + input_dim: int, + hidden_dim: int = 128, + max_residual_m: float = 0.15, + ) -> None: + super().__init__() + self.max_residual_m = float(max_residual_m) + self.network = nn.Sequential( + nn.Linear(input_dim, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, 1), + ) + nn.init.zeros_(self.network[-1].weight) + nn.init.zeros_(self.network[-1].bias) + + def forward(self, features: torch.Tensor) -> torch.Tensor: + return self.max_residual_m * torch.tanh(self.network(features).squeeze(-1)) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/metric_alignment.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/metric_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..918bb5bbce077ed9b0fdd77cdc2c0911ee799004 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/metric_alignment.py @@ -0,0 +1,333 @@ +"""Predicted-MANO to observed-depth alignment for deployable wrist-z correction.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass + +import cv2 +import numpy as np + +from foundation_hand.geometry.camera import project_points + + +@dataclass(frozen=True) +class AlignmentDiagnostics: + delta_z_m: float + applied: bool + valid_support_count: int + projected_support_count: int + inlier_ratio: float + residual_scale_m: float + valid_fraction: float + foreground_fraction: float + background_fraction: float + depth_discontinuity_m: float + conditioning_quality: float + + def as_dict(self) -> dict[str, float | int | bool]: + return asdict(self) + + +@dataclass(frozen=True) +class SurfaceSamples: + projected_vertices_px: np.ndarray + predicted_depth_m: np.ndarray + observed_depth_m: np.ndarray + visible_vertex: np.ndarray + sample_valid: np.ndarray + local_discontinuity_m: np.ndarray + silhouette_packed: np.ndarray + silhouette_hw: tuple[int, int] + + +def _empty_diagnostics(projected: int = 0) -> AlignmentDiagnostics: + return AlignmentDiagnostics( + delta_z_m=0.0, + applied=False, + valid_support_count=0, + projected_support_count=int(projected), + inlier_ratio=0.0, + residual_scale_m=0.0, + valid_fraction=0.0, + foreground_fraction=0.0, + background_fraction=0.0, + depth_discontinuity_m=0.0, + conditioning_quality=0.0, + ) + + +def robust_location_irls( + residuals_m: np.ndarray, + *, + base_weights: np.ndarray | None = None, + huber_k: float = 1.345, + iterations: int = 8, + minimum_scale_m: float = 0.003, + maximum_delta_m: float = 0.12, +) -> tuple[float, float, float]: + """Estimate a bounded common translation with MAD-scaled Huber IRLS.""" + + residuals = np.asarray(residuals_m, dtype=np.float64).reshape(-1) + finite = np.isfinite(residuals) + residuals = residuals[finite] + if not residuals.size: + return 0.0, 0.0, 0.0 + if base_weights is None: + weights = np.ones_like(residuals) + else: + input_weights = np.asarray(base_weights, dtype=np.float64).reshape(-1)[finite] + weights = np.clip(input_weights, 0.0, None) + if not np.any(weights > 0.0): + return 0.0, 0.0, 0.0 + + location = float(np.median(residuals)) + scale = max( + minimum_scale_m, + 1.4826 * float(np.median(np.abs(residuals - location))), + ) + for _ in range(iterations): + standardized = np.abs(residuals - location) / scale + robust = np.ones_like(standardized) + outside = standardized > huber_k + robust[outside] = huber_k / standardized[outside] + combined = weights * robust + if combined.sum() <= 1e-12: + return 0.0, scale, 0.0 + updated = float(np.sum(combined * residuals) / np.sum(combined)) + if abs(updated - location) < 1e-7: + location = updated + break + location = updated + location = float(np.clip(location, -maximum_delta_m, maximum_delta_m)) + inlier_ratio = float(np.mean(np.abs(residuals - location) <= huber_k * scale)) + return location, scale, inlier_ratio + + +def _visible_vertex_mask( + pixels: np.ndarray, + depth_m: np.ndarray, + image_hw: tuple[int, int], + cell_size: int, +) -> np.ndarray: + height, width = image_hw + finite = np.isfinite(pixels).all(axis=-1) & np.isfinite(depth_m) & (depth_m > 0.0) + inside = finite & (pixels[:, 0] >= 0) & (pixels[:, 0] < width) & ( + pixels[:, 1] >= 0 + ) & (pixels[:, 1] < height) + visible = np.zeros(len(pixels), dtype=bool) + indices = np.where(inside)[0] + if not len(indices): + return visible + cells_x = np.floor(pixels[indices, 0] / cell_size).astype(np.int64) + cells_y = np.floor(pixels[indices, 1] / cell_size).astype(np.int64) + cell_width = (width + cell_size - 1) // cell_size + cell_ids = cells_y * cell_width + cells_x + order = np.lexsort((depth_m[indices], cell_ids)) + sorted_ids = cell_ids[order] + first = np.r_[True, sorted_ids[1:] != sorted_ids[:-1]] + visible[indices[order[first]]] = True + return visible + + +def _sample_depth_regions( + depth_m: np.ndarray, + depth_valid: np.ndarray, + pixels: np.ndarray, + radius: int, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + height, width = depth_m.shape + count = len(pixels) + observed = np.full(count, np.nan, dtype=np.float32) + valid = np.zeros(count, dtype=bool) + discontinuity = np.full(count, np.nan, dtype=np.float32) + finite_pixels = np.isfinite(pixels).all(axis=-1) + centers = np.rint(np.where(finite_pixels[:, None], pixels, 0.0)).astype(np.int64) + offsets = np.arange(-radius, radius + 1, dtype=np.int64) + offset_y, offset_x = np.meshgrid(offsets, offsets, indexing="ij") + sample_x = centers[:, 0, None] + offset_x.reshape(1, -1) + sample_y = centers[:, 1, None] + offset_y.reshape(1, -1) + inside = finite_pixels[:, None] & (sample_x >= 0) & (sample_x < width) & ( + sample_y >= 0 + ) & (sample_y < height) + clipped_x = np.clip(sample_x, 0, width - 1) + clipped_y = np.clip(sample_y, 0, height - 1) + values = depth_m[clipped_y, clipped_x] + sample_valid = inside & depth_valid[clipped_y, clipped_x] & np.isfinite(values) & ( + values > 0.0 + ) + eligible = sample_valid.any(axis=1) + if np.any(eligible): + eligible_valid = sample_valid[eligible] + sorted_values = np.sort( + np.where(eligible_valid, values[eligible], np.inf), axis=1, + ) + counts = eligible_valid.sum(axis=1) + + def row_percentile(quantile: float) -> np.ndarray: + position = (counts - 1) * quantile + lower = np.floor(position).astype(np.int64) + upper = np.ceil(position).astype(np.int64) + fraction = position - lower + lower_value = np.take_along_axis(sorted_values, lower[:, None], axis=1)[:, 0] + upper_value = np.take_along_axis(sorted_values, upper[:, None], axis=1)[:, 0] + difference = upper_value - lower_value + interpolated = lower_value + difference * fraction + upper_stable = fraction >= 0.5 + interpolated[upper_stable] = ( + upper_value[upper_stable] + - difference[upper_stable] * (1.0 - fraction[upper_stable]) + ) + return interpolated + + q10, q50, q90 = (row_percentile(quantile) for quantile in (0.1, 0.5, 0.9)) + observed[eligible] = q50.astype(np.float32) + discontinuity[eligible] = (q90 - q10).astype(np.float32) + valid[eligible] = True + return observed, valid, discontinuity + + +def conservative_silhouette( + projected_vertices_px: np.ndarray, + visible_vertex: np.ndarray, + image_hw: tuple[int, int], + *, + downsample: int = 4, +) -> tuple[np.ndarray, tuple[int, int]]: + """Return a packed conservative projected-hull mask for bank/audit storage.""" + + height, width = image_hw + output_hw = ( + (height + downsample - 1) // downsample, + (width + downsample - 1) // downsample, + ) + mask = np.zeros(output_hw, dtype=np.uint8) + points = np.asarray(projected_vertices_px, dtype=np.float32)[visible_vertex] + points = points[np.isfinite(points).all(axis=-1)] / float(downsample) + if len(points) >= 3: + hull = cv2.convexHull(np.rint(points).astype(np.int32)) + cv2.fillConvexPoly(mask, hull, 1) + packed = np.packbits(mask.reshape(-1), bitorder="little") + return packed, output_hw + + +def sample_predicted_surface( + vertices_camera_m: np.ndarray, + K: np.ndarray, + depth_m: np.ndarray, + depth_valid: np.ndarray, + *, + cell_size: int = 4, + sample_radius: int = 2, + silhouette_downsample: int = 4, +) -> SurfaceSamples: + vertices = np.asarray(vertices_camera_m, dtype=np.float32) + depth = np.asarray(depth_m, dtype=np.float32) + valid = np.asarray(depth_valid, dtype=bool) + matrix = np.asarray(K, dtype=np.float32) + if vertices.ndim != 2 or vertices.shape[1] != 3: + raise ValueError("vertices must have shape [V,3]") + if depth.ndim != 2 or valid.shape != depth.shape or matrix.shape != (3, 3): + raise ValueError("depth, validity, or K shape mismatch") + pixels, positive = project_points(vertices, matrix) + visible = _visible_vertex_mask(pixels, vertices[:, 2], depth.shape, cell_size) + visible &= positive + observed, sample_valid, discontinuity = _sample_depth_regions( + depth, valid, pixels, sample_radius, + ) + sample_valid &= visible + packed, silhouette_hw = conservative_silhouette( + pixels, visible, depth.shape, downsample=silhouette_downsample, + ) + return SurfaceSamples( + projected_vertices_px=pixels.astype(np.float32), + predicted_depth_m=vertices[:, 2].astype(np.float32), + observed_depth_m=observed, + visible_vertex=visible, + sample_valid=sample_valid, + local_discontinuity_m=discontinuity, + silhouette_packed=packed, + silhouette_hw=silhouette_hw, + ) + + +def solve_wrist_delta_z( + samples: SurfaceSamples, + *, + minimum_support: int = 20, + maximum_raw_residual_m: float = 0.15, + discontinuity_scale_m: float = 0.04, + maximum_delta_m: float = 0.12, +) -> AlignmentDiagnostics: + residuals = samples.observed_depth_m - samples.predicted_depth_m + projected_count = int(samples.visible_vertex.sum()) + candidate = samples.sample_valid & np.isfinite(residuals) & ( + np.abs(residuals) <= maximum_raw_residual_m + ) + count = int(candidate.sum()) + if count < minimum_support: + return _empty_diagnostics(projected_count) + values = residuals[candidate].astype(np.float64) + discontinuity = samples.local_discontinuity_m[candidate].astype(np.float64) + weights = 1.0 / (1.0 + np.square(discontinuity / discontinuity_scale_m)) + delta, scale, inlier_ratio = robust_location_irls( + values, base_weights=weights, maximum_delta_m=maximum_delta_m, + ) + foreground_fraction = float(np.mean(values < delta - max(0.02, 2.5 * scale))) + background_fraction = float(np.mean(values > delta + max(0.03, 2.5 * scale))) + valid_fraction = count / max(projected_count, 1) + support_score = min(1.0, count / 80.0) + scale_score = float(np.exp(-scale / 0.025)) + contamination_score = max(0.0, 1.0 - foreground_fraction - background_fraction) + quality = float(np.clip( + support_score * inlier_ratio * scale_score * contamination_score, + 0.0, 1.0, + )) + return AlignmentDiagnostics( + delta_z_m=delta, + applied=True, + valid_support_count=count, + projected_support_count=projected_count, + inlier_ratio=inlier_ratio, + residual_scale_m=scale, + valid_fraction=valid_fraction, + foreground_fraction=foreground_fraction, + background_fraction=background_fraction, + depth_discontinuity_m=float(np.nanmedian(discontinuity)), + conditioning_quality=quality, + ) + + +def align_wrist_z( + vertices_camera_m: np.ndarray, + K: np.ndarray | None, + depth_m: np.ndarray | None, + depth_valid: np.ndarray | None, + *, + minimum_support: int = 20, +) -> tuple[AlignmentDiagnostics, SurfaceSamples | None]: + if K is None or depth_m is None or depth_valid is None: + return _empty_diagnostics(), None + matrix = np.asarray(K) + if matrix.shape != (3, 3) or not np.isfinite(matrix).all() or min( + float(matrix[0, 0]), float(matrix[1, 1]) + ) <= 0.0: + return _empty_diagnostics(), None + samples = sample_predicted_surface( + vertices_camera_m, matrix, depth_m, depth_valid, + ) + return solve_wrist_delta_z(samples, minimum_support=minimum_support), samples + + +def apply_translation_delta_z( + translation_m: np.ndarray, + joints_m: np.ndarray, + vertices_m: np.ndarray, + delta_z_m: float, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + translation = np.asarray(translation_m, dtype=np.float32).copy() + joints = np.asarray(joints_m, dtype=np.float32).copy() + vertices = np.asarray(vertices_m, dtype=np.float32).copy() + translation[..., 2] += float(delta_z_m) + joints[..., 2] += float(delta_z_m) + vertices[..., 2] += float(delta_z_m) + return translation, joints, vertices diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/metrics.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..2f904f95c1ee76ed1b12b0debaa6126225acc9c9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/metrics.py @@ -0,0 +1,100 @@ +"""Distribution summaries and take-level uncertainty estimates.""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence + +import numpy as np + + +PERCENTILES = (50, 90, 95, 99) + + +def finite_array(values: Iterable[float | int | None]) -> np.ndarray: + array = np.asarray([value for value in values if value is not None], dtype=np.float64) + return array[np.isfinite(array)] + + +def distribution_summary(values: Iterable[float | int | None]) -> dict[str, float | int | None]: + """Return central statistics, fixed tail percentiles, and upper-tail CVaR.""" + + array = finite_array(values) + if array.size == 0: + return { + "count": 0, + "mean": None, + "std": None, + **{f"p{percentile}": None for percentile in PERCENTILES}, + "cvar95": None, + } + p95 = float(np.percentile(array, 95)) + return { + "count": int(array.size), + "mean": float(array.mean()), + "std": float(array.std(ddof=0)), + **{ + f"p{percentile}": float(np.percentile(array, percentile)) + for percentile in PERCENTILES + }, + "cvar95": float(array[array >= p95].mean()), + } + + +def bootstrap_take_means( + rows: Sequence[Mapping[str, object]], + metric_names: Sequence[str], + *, + take_key: str = "take", + seed: int = 20260716, + samples: int = 10_000, +) -> list[dict[str, float | int | str | None]]: + """Bootstrap equally weighted take means and return percentile 95% CIs. + + Frame/hand observations are first averaged within each take. Resampling then + operates on takes, which avoids treating adjacent video frames as independent. + """ + + if samples <= 0: + raise ValueError("samples must be positive") + grouped: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for row in rows: + take = str(row[take_key]) + for metric in metric_names: + value = row.get(metric) + if value is None: + continue + number = float(value) + if np.isfinite(number): + grouped[take][metric].append(number) + + rng = np.random.default_rng(seed) + output: list[dict[str, float | int | str | None]] = [] + for metric in metric_names: + take_values = np.asarray( + [np.mean(items[metric]) for items in grouped.values() if items.get(metric)], + dtype=np.float64, + ) + if take_values.size == 0: + output.append({ + "metric": metric, + "take_count": 0, + "take_mean": None, + "ci95_low": None, + "ci95_high": None, + "bootstrap_samples": samples, + "seed": seed, + }) + continue + indices = rng.integers(0, take_values.size, size=(samples, take_values.size)) + bootstrap = take_values[indices].mean(axis=1) + output.append({ + "metric": metric, + "take_count": int(take_values.size), + "take_mean": float(take_values.mean()), + "ci95_low": float(np.percentile(bootstrap, 2.5)), + "ci95_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/mixed_projection.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..ce3762b44d153f24c7d08a7639fb51bb788602e9 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/mixed_projection.py @@ -0,0 +1,248 @@ +"""Predicted-anchor mixed-projection translation assembly.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + + +@dataclass(frozen=True) +class MixedProjectionBatchResult: + translation_m: np.ndarray + support_count: np.ndarray + residual_scale_px: np.ndarray + conditioning: np.ndarray + inlier_ratio: np.ndarray + uncertainty_xy_m: np.ndarray + failure_reason: np.ndarray + + +def coarse_wrist_ray_translation( + coarse_translation_m: np.ndarray, + refined_z_m: np.ndarray, + *, + minimum_depth_m: float = 0.05, +) -> np.ndarray: + """Change z while preserving the coarse camera ray.""" + + coarse = np.asarray(coarse_translation_m, dtype=np.float64) + z = np.asarray(refined_z_m, dtype=np.float64) + if coarse.shape[:-1] != z.shape or coarse.shape[-1] != 3: + raise ValueError("coarse translation and refined z shapes differ") + output = coarse.copy() + valid = ( + np.isfinite(coarse).all(axis=-1) + & np.isfinite(z) + & (coarse[..., 2] > minimum_depth_m) + & (z > minimum_depth_m) + ) + ratio = np.ones_like(z) + ratio[valid] = z[valid] / coarse[..., 2][valid] + output[..., :2] *= ratio[..., None] + output[..., 2] = np.where(np.isfinite(z), z, coarse[..., 2]) + return output + + +def direct_wrist_ray_translation( + anchors_px: np.ndarray, + intrinsics: np.ndarray, + refined_z_m: np.ndarray, + fallback_translation_m: np.ndarray, + *, + minimum_depth_m: float = 0.05, +) -> tuple[np.ndarray, np.ndarray]: + """Back-project the predicted direct-2D wrist at the selected depth.""" + + anchors = np.asarray(anchors_px, dtype=np.float64) + K = np.asarray(intrinsics, dtype=np.float64) + z = np.asarray(refined_z_m, dtype=np.float64) + fallback = np.asarray(fallback_translation_m, dtype=np.float64) + if anchors.shape[-2:] != (21, 2) or K.shape[-2:] != (3, 3): + raise ValueError("unexpected anchor or K shape") + output = fallback.copy() + wrist = anchors[..., 0, :] + fx, fy = K[..., 0, 0], K[..., 1, 1] + cx, cy = K[..., 0, 2], K[..., 1, 2] + valid = ( + np.isfinite(wrist).all(axis=-1) + & np.isfinite(K).all(axis=(-2, -1)) + & np.isfinite(z) + & (fx > 1e-8) + & (fy > 1e-8) + & (z > minimum_depth_m) + ) + output[..., 0] = np.where(valid, (wrist[..., 0] - cx) * z / fx, output[..., 0]) + output[..., 1] = np.where(valid, (wrist[..., 1] - cy) * z / fy, output[..., 1]) + output[..., 2] = np.where(np.isfinite(z), z, output[..., 2]) + return output, valid + + +def solve_mixed_projection_batch( + root_relative_joints_m: np.ndarray, + anchors_px: np.ndarray, + intrinsics: np.ndarray, + refined_z_m: np.ndarray, + fallback_translation_m: np.ndarray, + *, + image_hw: tuple[int, int], + minimum_support: int = 8, + robust_huber_delta_px: float | None = None, + irls_iterations: int = 5, + minimum_joint_depth_m: float = 0.05, + denominator_epsilon: float = 1e-10, +) -> MixedProjectionBatchResult: + """Solve tx/ty from predicted 2D anchors and MANO root-relative joints. + + Every solve mask is derived from predicted quantities. Failed solves keep + the supplied fallback x/y and the selected finite z. + """ + + joints = np.asarray(root_relative_joints_m, dtype=np.float64) + anchors = np.asarray(anchors_px, dtype=np.float64) + K = np.asarray(intrinsics, dtype=np.float64) + z = np.asarray(refined_z_m, dtype=np.float64) + fallback = np.asarray(fallback_translation_m, dtype=np.float64) + if joints.ndim != 3 or joints.shape[1:] != (21, 3): + raise ValueError(f"expected joints [N,21,3], got {joints.shape}") + count = joints.shape[0] + expected = { + "anchors": (count, 21, 2), + "intrinsics": (count, 3, 3), + "refined z": (count,), + "fallback": (count, 3), + } + for name, shape in expected.items(): + value = {"anchors": anchors, "intrinsics": K, "refined z": z, "fallback": fallback}[name] + if value.shape != shape: + raise ValueError(f"expected {name} {shape}, got {value.shape}") + if not 1 <= minimum_support <= 21: + raise ValueError("minimum_support must be in [1,21]") + if robust_huber_delta_px is not None and robust_huber_delta_px <= 0.0: + raise ValueError("Huber delta must be positive") + if irls_iterations < 1: + raise ValueError("IRLS iterations must be positive") + height, width = image_hw + if height <= 0 or width <= 0: + raise ValueError("image dimensions must be positive") + + fx, fy = K[:, 0, 0], K[:, 1, 1] + cx, cy = K[:, 0, 2], K[:, 1, 2] + joint_z = joints[..., 2] + z[:, None] + finite_k = np.isfinite(K).all(axis=(1, 2)) & (fx > 1e-8) & (fy > 1e-8) + finite_joint = np.isfinite(joints).all(axis=-1) + finite_anchor = np.isfinite(anchors).all(axis=-1) + in_frame = ( + (anchors[..., 0] >= 0.0) + & (anchors[..., 0] <= width - 1.0) + & (anchors[..., 1] >= 0.0) + & (anchors[..., 1] <= height - 1.0) + ) + mask = ( + finite_k[:, None] + & np.isfinite(z)[:, None] + & (joint_z > minimum_joint_depth_m) + & finite_joint + & finite_anchor + & in_frame + ) + support = mask.sum(axis=1).astype(np.int64) + + safe_joint_z = np.where(mask, joint_z, 1.0) + ax = fx[:, None] / safe_joint_z + ay = fy[:, None] / safe_joint_z + bx = anchors[..., 0] - cx[:, None] - fx[:, None] * joints[..., 0] / safe_joint_z + by = anchors[..., 1] - cy[:, None] - fy[:, None] * joints[..., 1] / safe_joint_z + ax = np.where(mask, ax, 0.0) + ay = np.where(mask, ay, 0.0) + bx = np.where(mask, bx, 0.0) + by = np.where(mask, by, 0.0) + + weights = mask.astype(np.float64) + + def solve(current_weights: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + denom_x = np.sum(current_weights * np.square(ax), axis=1) + denom_y = np.sum(current_weights * np.square(ay), axis=1) + tx = np.divide( + np.sum(current_weights * ax * bx, axis=1), denom_x, + out=np.full(count, np.nan), where=denom_x > denominator_epsilon, + ) + ty = np.divide( + np.sum(current_weights * ay * by, axis=1), denom_y, + out=np.full(count, np.nan), where=denom_y > denominator_epsilon, + ) + return tx, ty, denom_x, denom_y + + tx, ty, denom_x, denom_y = solve(weights) + if robust_huber_delta_px is not None: + for _ in range(irls_iterations): + residual = np.sqrt( + np.square(ax * tx[:, None] - bx) + + np.square(ay * ty[:, None] - by) + ) + robust = np.minimum( + 1.0, + robust_huber_delta_px / np.maximum(residual, 1e-12), + ) + weights = np.where(mask, robust, 0.0) + tx, ty, denom_x, denom_y = solve(weights) + + residual = np.sqrt( + np.square(ax * tx[:, None] - bx) + + np.square(ay * ty[:, None] - by) + ) + residual_masked = np.where(mask, residual, np.nan) + residual_scale = np.full(count, np.inf, dtype=np.float64) + has_support = support > 0 + if has_support.any(): + supported_residual = residual_masked[has_support] + median = np.nanmedian(supported_residual, axis=1) + mad = np.nanmedian( + np.abs(supported_residual - median[:, None]), axis=1, + ) + residual_scale[has_support] = 1.4826 * mad + if robust_huber_delta_px is None: + inlier = np.where(mask, True, False) + else: + inlier = mask & (residual <= robust_huber_delta_px) + inlier_ratio = np.divide( + inlier.sum(axis=1), support, + out=np.zeros(count, dtype=np.float64), where=support > 0, + ) + conditioning = np.divide( + np.minimum(denom_x, denom_y), np.maximum(denom_x, denom_y), + out=np.zeros(count, dtype=np.float64), where=np.maximum(denom_x, denom_y) > 0.0, + ) + uncertainty = np.stack(( + np.divide( + residual_scale, np.sqrt(denom_x), out=np.full(count, np.inf), + where=denom_x > denominator_epsilon, + ), + np.divide( + residual_scale, np.sqrt(denom_y), out=np.full(count, np.inf), + where=denom_y > denominator_epsilon, + ), + ), axis=-1) + + sufficient = support >= minimum_support + conditioned = (denom_x > denominator_epsilon) & (denom_y > denominator_epsilon) + finite_solution = np.isfinite(tx) & np.isfinite(ty) + success = finite_k & sufficient & conditioned & finite_solution + output = fallback.copy() + output[:, 0] = np.where(success, tx, output[:, 0]) + output[:, 1] = np.where(success, ty, output[:, 1]) + output[:, 2] = np.where(np.isfinite(z), z, output[:, 2]) + reason = np.full(count, "ok", dtype=" str: + return ACTION_NAMES.get(int(label), f"unknown_{int(label)}") + + +def load_action_label(data_root: str | Path, take: str, frame_id: int) -> int: + path = Path(data_root) / take / "action_label" / f"{int(frame_id):06d}.txt" + values = path.read_text(encoding="utf-8").split() + if len(values) != 1: + raise ValueError(f"expected one H2O action label in {path}, found {len(values)}") + label = int(values[0]) + if label not in ACTION_NAMES: + raise ValueError(f"unknown H2O action label {label} in {path}") + return label + + +def local_depth_statistics( + depth_m: np.ndarray, + depth_valid: np.ndarray, + joints_2d: np.ndarray, + *, + margin_fraction: float = 0.25, + minimum_size_px: int = 24, +) -> dict[str, float | int | None]: + """Summarize aligned metric depth in a conservative GT-joint region. + + This diagnostic intentionally describes visible surface geometry. It does + not equate the local depth median with the camera-space wrist center. + """ + + if depth_m.ndim != 2 or depth_valid.shape != depth_m.shape: + raise ValueError("depth and validity must be aligned HxW arrays") + points = np.asarray(joints_2d, dtype=np.float64) + finite = np.isfinite(points).all(axis=-1) + if not finite.any(): + return { + "roi_x0": None, + "roi_y0": None, + "roi_x1": None, + "roi_y1": None, + "pixel_count": 0, + "valid_fraction": None, + "depth_median_m": None, + "depth_q10_m": None, + "depth_q90_m": None, + "depth_iqr_m": None, + "depth_discontinuity_m": None, + } + points = points[finite] + minimum = points.min(axis=0) + maximum = points.max(axis=0) + center = 0.5 * (minimum + maximum) + extent = np.maximum(maximum - minimum, float(minimum_size_px)) + extent *= 1.0 + 2.0 * float(margin_fraction) + height, width = depth_m.shape + x0 = max(0, int(np.floor(center[0] - extent[0] / 2.0))) + y0 = max(0, int(np.floor(center[1] - extent[1] / 2.0))) + x1 = min(width, int(np.ceil(center[0] + extent[0] / 2.0)) + 1) + y1 = min(height, int(np.ceil(center[1] + extent[1] / 2.0)) + 1) + if x1 <= x0 or y1 <= y0: + return { + "roi_x0": x0, + "roi_y0": y0, + "roi_x1": x1, + "roi_y1": y1, + "pixel_count": 0, + "valid_fraction": None, + "depth_median_m": None, + "depth_q10_m": None, + "depth_q90_m": None, + "depth_iqr_m": None, + "depth_discontinuity_m": None, + } + region_valid = np.asarray(depth_valid[y0:y1, x0:x1], dtype=bool) + region_depth = np.asarray(depth_m[y0:y1, x0:x1], dtype=np.float64) + region_valid &= np.isfinite(region_depth) & (region_depth > 0.0) + values = region_depth[region_valid] + report: dict[str, float | int | None] = { + "roi_x0": x0, + "roi_y0": y0, + "roi_x1": x1, + "roi_y1": y1, + "pixel_count": int(region_valid.size), + "valid_fraction": float(region_valid.mean()), + "depth_median_m": None, + "depth_q10_m": None, + "depth_q90_m": None, + "depth_iqr_m": None, + "depth_discontinuity_m": None, + } + if values.size: + q10, q25, q50, q75, q90 = np.percentile(values, (10, 25, 50, 75, 90)) + report.update({ + "depth_median_m": float(q50), + "depth_q10_m": float(q10), + "depth_q90_m": float(q90), + "depth_iqr_m": float(q75 - q25), + "depth_discontinuity_m": float(q90 - q10), + }) + return report + + +def depth_validity_bucket(value: float | None) -> str | None: + if value is None or not np.isfinite(value): + return None + if value < 0.5: + return "low" + if value < 0.9: + return "partial" + return "high" + + +def bimanual_asymmetry( + hand_sizes_px: Sequence[float | None], + wrist_depths_m: Sequence[float | None], +) -> dict[str, float | str | None]: + if len(hand_sizes_px) != 2 or len(wrist_depths_m) != 2: + raise ValueError("bimanual asymmetry requires left/right pairs") + if any(value is None or not np.isfinite(value) for value in hand_sizes_px): + size_ratio = None + else: + small = max(min(float(hand_sizes_px[0]), float(hand_sizes_px[1])), 1e-6) + size_ratio = max(float(hand_sizes_px[0]), float(hand_sizes_px[1])) / small + if any(value is None or not np.isfinite(value) for value in wrist_depths_m): + depth_gap = None + signed_depth_gap = None + else: + signed_depth_gap = float(wrist_depths_m[1]) - float(wrist_depths_m[0]) + depth_gap = abs(signed_depth_gap) + + if size_ratio is None or depth_gap is None: + bucket = None + elif size_ratio >= 2.0 or depth_gap >= 0.20: + bucket = "strong" + elif size_ratio >= 1.5 or depth_gap >= 0.10: + bucket = "moderate" + else: + bucket = "balanced" + return { + "bimanual_size_ratio": size_ratio, + "bimanual_depth_gap_m": depth_gap, + "right_minus_left_depth_m": signed_depth_gap, + "bimanual_asymmetry_bucket": bucket, + } + + +def summarize_group_metrics( + rows: Sequence[Mapping[str, object]], + metrics: Sequence[str], + group_fields: Sequence[str], +) -> list[dict[str, object]]: + output: list[dict[str, object]] = [] + for group_field in group_fields: + groups: dict[str, list[Mapping[str, object]]] = defaultdict(list) + for row in rows: + value = row.get(group_field) + if value not in (None, ""): + groups[str(value)].append(row) + for group_value, group_rows in sorted(groups.items()): + for side in ("all", "left", "right"): + side_rows = ( + group_rows if side == "all" + else [row for row in group_rows if row.get("side") == side] + ) + for metric in metrics: + summary = distribution_summary(row.get(metric) for row in side_rows) + output.append({ + "group_field": group_field, + "group_value": group_value, + "side": side, + "metric": metric, + **summary, + }) + return output + + +def find_failure_intervals( + rows: Sequence[Mapping[str, object]], + *, + metric: str, + threshold: float, + minimum_frames: int = 3, +) -> list[dict[str, object]]: + """Find contiguous valid-frame intervals above a registered error threshold.""" + + grouped: dict[tuple[str, str], list[Mapping[str, object]]] = defaultdict(list) + for row in rows: + value = row.get(metric) + if row.get("annotation_valid") and value not in (None, ""): + grouped[(str(row["take"]), str(row["side"]))].append(row) + + intervals: list[dict[str, object]] = [] + for (take, side), group in sorted(grouped.items()): + ordered = sorted(group, key=lambda row: int(row["frame_id"])) + current: list[Mapping[str, object]] = [] + + def flush() -> None: + if len(current) < minimum_frames: + current.clear() + return + values = np.asarray([float(row[metric]) for row in current], dtype=np.float64) + intervals.append({ + "take": take, + "side": side, + "metric": metric, + "threshold": float(threshold), + "start_frame": int(current[0]["frame_id"]), + "end_frame": int(current[-1]["frame_id"]), + "frame_count": len(current), + "mean": float(values.mean()), + "maximum": float(values.max()), + "p95": float(np.percentile(values, 95)), + }) + current.clear() + + previous_frame: int | None = None + for row in ordered: + frame = int(row["frame_id"]) + above = float(row[metric]) >= threshold + if not above or (previous_frame is not None and frame != previous_frame + 1): + flush() + if above: + current.append(row) + previous_frame = frame + flush() + return sorted( + intervals, + key=lambda row: (-int(row["frame_count"]), -float(row["mean"]), str(row["take"])), + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/procrustes.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f5b53bcabf1384c6af810216589e897a459250 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/procrustes.py @@ -0,0 +1,46 @@ +"""Rigid and similarity-aligned 3D joint errors.""" + +from __future__ import annotations + +import numpy as np + + +def aligned_mpjpe_mm( + predicted_m: np.ndarray, + target_m: np.ndarray, + *, + estimate_scale: bool, +) -> np.ndarray: + """Return per-sample Kabsch/Umeyama MPJPE for arrays ending in [J,3].""" + + predicted = np.asarray(predicted_m, dtype=np.float64) + target = np.asarray(target_m, dtype=np.float64) + if predicted.shape != target.shape or predicted.ndim < 3 or predicted.shape[-1] != 3: + raise ValueError("predicted and target joints must share shape [...,J,3]") + prefix = predicted.shape[:-2] + joints = predicted.shape[-2] + source = predicted.reshape(-1, joints, 3) + destination = target.reshape(-1, joints, 3) + if not np.isfinite(source).all() or not np.isfinite(destination).all(): + raise ValueError("aligned MPJPE expects finite valid-hand joints") + source_mean = source.mean(axis=1, keepdims=True) + destination_mean = destination.mean(axis=1, keepdims=True) + source_centered = source - source_mean + destination_centered = destination - destination_mean + covariance = np.swapaxes(source_centered, 1, 2) @ destination_centered + left, singular, right_transposed = np.linalg.svd(covariance) + correction = np.ones((len(source), 3), dtype=np.float64) + correction[:, -1] = np.where( + np.linalg.det(left @ right_transposed) < 0.0, -1.0, 1.0, + ) + rotation = (left * correction[:, None, :]) @ right_transposed + aligned = source_centered @ rotation + if estimate_scale: + numerator = (singular * correction).sum(axis=1) + denominator = np.square(source_centered).sum(axis=(1, 2)) + scale = np.divide( + numerator, denominator, out=np.ones_like(numerator), where=denominator > 1e-12, + ) + aligned = aligned * scale[:, None, None] + error = np.linalg.norm(aligned - destination_centered, axis=-1).mean(axis=1) * 1000.0 + return error.reshape(prefix) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/selection.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/selection.py new file mode 100644 index 0000000000000000000000000000000000000000..0e01a5da365d139c657d71efd738c8b38b555d0c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/selection.py @@ -0,0 +1,69 @@ +"""Deterministic, auditable selection of qualitative validation examples.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence + +import numpy as np + + +def _nearest_rank(records: list[Mapping[str, object]], metric: str, percentile: float) -> Mapping[str, object] | None: + candidates = [record for record in records if record.get(metric) is not None] + if not candidates: + return None + values = np.asarray([float(record[metric]) for record in candidates], dtype=np.float64) + target = float(np.percentile(values, percentile)) + return candidates[int(np.argmin(np.abs(values - target)))] + + +def select_visualization_frames( + records: Sequence[Mapping[str, object]], + *, + seed: int = 20260716, + random_count: int = 4, + metric: str = "absolute_mpjpe_mm", +) -> list[dict[str, object]]: + """Select random, error-tail, scale, depth, and validity-state frames.""" + + if not records: + return [] + rng = np.random.default_rng(seed) + selected: dict[tuple[int, int], dict[str, object]] = {} + + def add(record: Mapping[str, object] | None, reason: str) -> None: + if record is None: + return + key = (int(record["clip_index"]), int(record["time_index"])) + if key not in selected: + selected[key] = { + "clip_index": key[0], + "time_index": key[1], + "subject": record["subject"], + "sequence": record["sequence"], + "take": record["take"], + "frame_id": int(record["frame_id"]), + "annotation_state": record["annotation_state"], + "hand_size_bucket": record.get("hand_size_bucket"), + "depth_bucket": record.get("depth_bucket"), + metric: record.get(metric), + "reasons": [], + } + selected[key]["reasons"].append(reason) + + random_count = min(random_count, len(records)) + for index in rng.choice(len(records), size=random_count, replace=False): + add(records[int(index)], "random") + + for percentile in (50, 90, 95, 100): + add(_nearest_rank(list(records), metric, percentile), f"error_p{percentile}") + + for field, values in ( + ("hand_size_bucket", ("small", "medium", "large")), + ("depth_bucket", ("near", "middle", "far")), + ("annotation_state", ("00", "01", "10", "11")), + ): + for value in values: + bucket = [record for record in records if record.get(field) == value] + add(_nearest_rank(bucket, metric, 50) if bucket else None, f"{field}={value}") + + return sorted(selected.values(), key=lambda item: (int(item["clip_index"]), int(item["time_index"]))) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/sota.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/sota.py new file mode 100644 index 0000000000000000000000000000000000000000..3eecabedfeca76d5b64506fb7b9aa9840c38c28f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/sota.py @@ -0,0 +1,630 @@ +"""Shared prediction format and fair H2O evaluation for external baselines.""" + +from __future__ import annotations + +import csv +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping, Sequence + +import numpy as np + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary + + +SCHEMA_VERSION = "foundation_hand_sota_prediction_v1" +SIDES = ("left", "right") +FINGERTIP_INDICES = (4, 8, 12, 16, 20) +PRIMARY_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", +) + + +def frame_key(take: str, frame_id: int) -> str: + return f"{take}/{frame_id:06d}" + + +def load_frame_index(manifest: str | Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Expand an official run manifest into its unique, deterministic frame order.""" + + takes: list[str] = [] + frame_ids: list[int] = [] + keys: list[str] = [] + seen: set[str] = set() + for line in Path(manifest).read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + record = json.loads(line) + take = str(record["take"]) + if not take.endswith("/cam4"): + raise ValueError(f"SOTA evaluation is cam4-only: {take}") + for value in record["frame_ids"]: + frame_id = int(value) + key = frame_key(take, frame_id) + if key in seen: + raise ValueError(f"Duplicate frame in manifest: {key}") + seen.add(key) + takes.append(take) + frame_ids.append(frame_id) + keys.append(key) + if not keys: + raise ValueError("Manifest contains no frames") + return ( + np.asarray(keys, dtype=np.str_), + np.asarray(takes, dtype=np.str_), + np.asarray(frame_ids, dtype=np.int64), + ) + + +@dataclass(frozen=True) +class PredictionBundle: + """Camera-space predictions aligned one-to-one with an official frame manifest.""" + + model_name: str + frame_keys: np.ndarray + takes: np.ndarray + frame_ids: np.ndarray + joints_camera_m: np.ndarray + detected: np.ndarray + confidence: np.ndarray + metadata: Mapping[str, Any] + vertices_camera_m: np.ndarray | None = None + + def validate(self) -> None: + count = len(self.frame_keys) + expected = { + "takes": (count,), + "frame_ids": (count,), + "joints_camera_m": (count, 2, 21, 3), + "detected": (count, 2), + "confidence": (count, 2), + } + for name, shape in expected.items(): + if np.asarray(getattr(self, name)).shape != shape: + raise ValueError( + f"{name} shape {np.asarray(getattr(self, name)).shape} != {shape}" + ) + if self.vertices_camera_m is not None: + vertices = np.asarray(self.vertices_camera_m) + if vertices.ndim != 4 or vertices.shape[:2] != (count, 2) or vertices.shape[-1] != 3: + raise ValueError(f"Unexpected vertices_camera_m shape: {vertices.shape}") + if len(set(map(str, self.frame_keys.tolist()))) != count: + raise ValueError("Prediction frame keys must be unique") + finite_joints = np.isfinite(self.joints_camera_m).all(axis=(-1, -2)) + if np.any(self.detected & ~finite_joints): + raise ValueError("Detected hands must have 21 finite camera-space joints") + if self.vertices_camera_m is not None: + finite_vertices = np.isfinite(self.vertices_camera_m).all(axis=(-1, -2)) + if np.any(self.detected & ~finite_vertices): + raise ValueError("Detected hands must have finite camera-space vertices") + + def save(self, path: str | Path) -> None: + self.validate() + payload: dict[str, np.ndarray] = { + "schema_version": np.asarray(SCHEMA_VERSION), + "model_name": np.asarray(self.model_name), + "frame_keys": np.asarray(self.frame_keys, dtype=np.str_), + "takes": np.asarray(self.takes, dtype=np.str_), + "frame_ids": np.asarray(self.frame_ids, dtype=np.int64), + "joints_camera_m": np.asarray(self.joints_camera_m, dtype=np.float32), + "detected": np.asarray(self.detected, dtype=np.bool_), + "confidence": np.asarray(self.confidence, dtype=np.float32), + "metadata_json": np.asarray(json.dumps(dict(self.metadata), sort_keys=True)), + } + if self.vertices_camera_m is not None: + payload["vertices_camera_m"] = np.asarray( + self.vertices_camera_m, dtype=np.float32 + ) + output = Path(path) + output.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(output, **payload) + + @classmethod + def load(cls, path: str | Path) -> "PredictionBundle": + with np.load(path, allow_pickle=False) as data: + version = str(data["schema_version"].item()) + if version != SCHEMA_VERSION: + raise ValueError(f"Unsupported prediction schema: {version}") + bundle = cls( + model_name=str(data["model_name"].item()), + frame_keys=data["frame_keys"].copy(), + takes=data["takes"].copy(), + frame_ids=data["frame_ids"].copy(), + joints_camera_m=data["joints_camera_m"].copy(), + detected=data["detected"].copy(), + confidence=data["confidence"].copy(), + metadata=json.loads(str(data["metadata_json"].item())), + vertices_camera_m=( + data["vertices_camera_m"].copy() + if "vertices_camera_m" in data.files + else None + ), + ) + bundle.validate() + return bundle + + +@dataclass(frozen=True) +class GroundTruthBundle: + frame_keys: np.ndarray + takes: np.ndarray + frame_ids: np.ndarray + joints_camera_m: np.ndarray + vertices_camera_m: np.ndarray + annotation_valid: np.ndarray + intrinsics: np.ndarray + metadata: Mapping[str, Any] + + def save(self, path: str | Path) -> None: + count = len(self.frame_keys) + if self.joints_camera_m.shape != (count, 2, 21, 3): + raise ValueError(f"Unexpected GT joints shape: {self.joints_camera_m.shape}") + if self.vertices_camera_m.shape[:2] != (count, 2): + raise ValueError(f"Unexpected GT vertices shape: {self.vertices_camera_m.shape}") + output = Path(path) + output.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + output, + schema_version=np.asarray("foundation_hand_sota_ground_truth_v1"), + frame_keys=np.asarray(self.frame_keys, dtype=np.str_), + takes=np.asarray(self.takes, dtype=np.str_), + frame_ids=np.asarray(self.frame_ids, dtype=np.int64), + joints_camera_m=np.asarray(self.joints_camera_m, dtype=np.float32), + vertices_camera_m=np.asarray(self.vertices_camera_m, dtype=np.float32), + annotation_valid=np.asarray(self.annotation_valid, dtype=np.bool_), + intrinsics=np.asarray(self.intrinsics, dtype=np.float32), + metadata_json=np.asarray(json.dumps(dict(self.metadata), sort_keys=True)), + ) + + @classmethod + def load(cls, path: str | Path) -> "GroundTruthBundle": + with np.load(path, allow_pickle=False) as data: + version = str(data["schema_version"].item()) + if version != "foundation_hand_sota_ground_truth_v1": + raise ValueError(f"Unsupported GT schema: {version}") + return cls( + frame_keys=data["frame_keys"].copy(), + takes=data["takes"].copy(), + frame_ids=data["frame_ids"].copy(), + joints_camera_m=data["joints_camera_m"].copy(), + vertices_camera_m=data["vertices_camera_m"].copy(), + annotation_valid=data["annotation_valid"].copy(), + intrinsics=data["intrinsics"].copy(), + metadata=json.loads(str(data["metadata_json"].item())), + ) + + +def align_prediction( + prediction: PredictionBundle, ground_truth: GroundTruthBundle +) -> PredictionBundle: + """Return predictions in GT order, rejecting missing or extra frame keys.""" + + gt_keys = list(map(str, ground_truth.frame_keys.tolist())) + pred_index = {str(key): index for index, key in enumerate(prediction.frame_keys.tolist())} + if set(pred_index) != set(gt_keys): + missing = sorted(set(gt_keys) - set(pred_index)) + extra = sorted(set(pred_index) - set(gt_keys)) + raise ValueError( + f"Prediction/GT frame mismatch: missing={missing[:3]} extra={extra[:3]}" + ) + order = np.asarray([pred_index[key] for key in gt_keys], dtype=np.int64) + return PredictionBundle( + model_name=prediction.model_name, + frame_keys=prediction.frame_keys[order], + takes=prediction.takes[order], + frame_ids=prediction.frame_ids[order], + joints_camera_m=prediction.joints_camera_m[order], + detected=prediction.detected[order], + confidence=prediction.confidence[order], + metadata=prediction.metadata, + vertices_camera_m=( + prediction.vertices_camera_m[order] + if prediction.vertices_camera_m is not None + else None + ), + ) + + +def _project(points: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + z = points[..., 2:3] + normalized = points[..., :2] / z + return np.einsum("nij,nhkj->nhki", intrinsics[:, :2, :2], normalized) + intrinsics[ + :, None, None, :2, 2 + ] + + +def _mean_or_none(value: np.ndarray) -> float | None: + finite = value[np.isfinite(value)] + return float(finite.mean()) if finite.size else None + + +def _auc_pck(errors_mm: np.ndarray, success: np.ndarray, maximum_mm: float = 50.0) -> float: + thresholds = np.linspace(0.0, maximum_mm, 101) + hits = success[..., None] & (errors_mm[..., None] <= thresholds) + pck = hits.reshape(-1, len(thresholds)).mean(axis=0) + return float(np.trapezoid(pck, thresholds) / maximum_mm) + + +def evaluate_prediction_bundle( + prediction: PredictionBundle, + ground_truth: GroundTruthBundle, + *, + bootstrap_seed: int = 20260716, + bootstrap_samples: int = 10_000, + pixel_scale: float = 1.0, + temporal_clip_length: int | None = 8, +) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]: + """Evaluate one model without silently dropping detector failures.""" + + prediction = align_prediction(prediction, ground_truth) + valid = ground_truth.annotation_valid.astype(bool) + finite = np.isfinite(prediction.joints_camera_m).all(axis=(-1, -2)) + success = valid & prediction.detected & finite + + joint_error = np.linalg.norm( + prediction.joints_camera_m - ground_truth.joints_camera_m, axis=-1 + ) * 1000.0 + pred_relative = prediction.joints_camera_m - prediction.joints_camera_m[:, :, :1] + gt_relative = ground_truth.joints_camera_m - ground_truth.joints_camera_m[:, :, :1] + relative_error = np.linalg.norm(pred_relative - gt_relative, axis=-1) * 1000.0 + projected = _project(prediction.joints_camera_m, ground_truth.intrinsics) + target_projected = _project(ground_truth.joints_camera_m, ground_truth.intrinsics) + if pixel_scale <= 0: + raise ValueError("pixel_scale must be positive") + projected_error = np.linalg.norm(projected - target_projected, axis=-1) * pixel_scale + translation_error = np.abs( + prediction.joints_camera_m[:, :, 0] - ground_truth.joints_camera_m[:, :, 0] + ) * 1000.0 + + vertex_error: np.ndarray | None = None + relative_vertex_error: np.ndarray | None = None + if prediction.vertices_camera_m is not None: + vertex_error = np.linalg.norm( + prediction.vertices_camera_m - ground_truth.vertices_camera_m, axis=-1 + ) * 1000.0 + pred_vertex_relative = ( + prediction.vertices_camera_m - prediction.joints_camera_m[:, :, None, 0] + ) + gt_vertex_relative = ( + ground_truth.vertices_camera_m - ground_truth.joints_camera_m[:, :, None, 0] + ) + relative_vertex_error = np.linalg.norm( + pred_vertex_relative - gt_vertex_relative, axis=-1 + ) * 1000.0 + + wrong_side: list[bool | None] = [] + for frame_index in range(len(ground_truth.frame_keys)): + if bool(valid[frame_index].all() and success[frame_index].all()): + correct = 0.5 * ( + joint_error[frame_index, 0].mean() + joint_error[frame_index, 1].mean() + ) + swapped = 500.0 * ( + np.linalg.norm( + prediction.joints_camera_m[frame_index, 0] + - ground_truth.joints_camera_m[frame_index, 1], + axis=-1, + ).mean() + + np.linalg.norm( + prediction.joints_camera_m[frame_index, 1] + - ground_truth.joints_camera_m[frame_index, 0], + axis=-1, + ).mean() + ) + wrong_side.append(bool(swapped < correct)) + else: + wrong_side.append(None) + + rows: list[dict[str, Any]] = [] + for frame_index in range(len(ground_truth.frame_keys)): + for hand, side in enumerate(SIDES): + is_valid = bool(valid[frame_index, hand]) + is_success = bool(success[frame_index, hand]) + row: dict[str, Any] = { + "frame_key": str(ground_truth.frame_keys[frame_index]), + "take": str(ground_truth.takes[frame_index]), + "frame_id": int(ground_truth.frame_ids[frame_index]), + "side": side, + "annotation_valid": int(is_valid), + "detected": int(prediction.detected[frame_index, hand]), + "evaluation_success": int(is_success), + "coverage_success": int(is_success) if is_valid else None, + "confidence": ( + float(prediction.confidence[frame_index, hand]) + if np.isfinite(prediction.confidence[frame_index, hand]) + else None + ), + "wrong_side_preference": ( + int(wrong_side[frame_index]) + if wrong_side[frame_index] is not None + else None + ), + } + metric_values = { + "absolute_mpjpe_mm": joint_error[frame_index, hand].mean(), + "root_relative_mpjpe_mm": relative_error[frame_index, hand].mean(), + "projected_2d_error_px": projected_error[frame_index, hand].mean(), + "fingertip_mpjpe_mm": joint_error[ + frame_index, hand, list(FINGERTIP_INDICES) + ].mean(), + "translation_x_mae_mm": translation_error[frame_index, hand, 0], + "translation_y_mae_mm": translation_error[frame_index, hand, 1], + "translation_z_mae_mm": translation_error[frame_index, hand, 2], + } + if vertex_error is not None and relative_vertex_error is not None: + metric_values.update({ + "absolute_mpvpe_mm": vertex_error[frame_index, hand].mean(), + "root_relative_mpvpe_mm": relative_vertex_error[ + frame_index, hand + ].mean(), + }) + for name in PRIMARY_METRICS: + row[name] = ( + float(metric_values[name]) + if is_success and name in metric_values + else None + ) + rows.append(row) + + temporal_rows: list[dict[str, Any]] = [] + run_positions = np.zeros(len(ground_truth.frame_keys), dtype=np.int64) + for index in range(1, len(run_positions)): + if ( + ground_truth.takes[index] == ground_truth.takes[index - 1] + and ground_truth.frame_ids[index] == ground_truth.frame_ids[index - 1] + 1 + ): + run_positions[index] = run_positions[index - 1] + 1 + for current in range(1, len(ground_truth.frame_keys)): + previous = current - 1 + consecutive = ( + ground_truth.takes[current] == ground_truth.takes[previous] + and ground_truth.frame_ids[current] == ground_truth.frame_ids[previous] + 1 + ) + clip_consecutive = ( + consecutive + and ( + temporal_clip_length is None + or run_positions[current] % temporal_clip_length != 0 + ) + ) + if not clip_consecutive: + continue + for hand, side in enumerate(SIDES): + gt_pair_valid = bool(valid[previous, hand] and valid[current, hand]) + pred_pair_valid = bool(success[previous, hand] and success[current, hand]) + wrist_velocity = None + joint_velocity = None + wrist_acceleration = None + joint_acceleration = None + gt_triplet_valid = False + pred_triplet_valid = False + if gt_pair_valid and pred_pair_valid: + predicted_delta = ( + prediction.joints_camera_m[current, hand] + - prediction.joints_camera_m[previous, hand] + ) + target_delta = ( + ground_truth.joints_camera_m[current, hand] + - ground_truth.joints_camera_m[previous, hand] + ) + velocity_error = np.linalg.norm(predicted_delta - target_delta, axis=-1) * 1000.0 + wrist_velocity = float(velocity_error[0]) + joint_velocity = float(velocity_error.mean()) + if previous >= 1: + before_previous = previous - 1 + triplet_consecutive = ( + ground_truth.takes[before_previous] == ground_truth.takes[current] + and ground_truth.frame_ids[before_previous] + 1 + == ground_truth.frame_ids[previous] + and ( + temporal_clip_length is None + or run_positions[current] % temporal_clip_length >= 2 + ) + ) + gt_triplet_valid = bool( + triplet_consecutive + and valid[before_previous, hand] + and valid[previous, hand] + and valid[current, hand] + ) + pred_triplet_valid = bool( + gt_triplet_valid + and success[before_previous, hand] + and success[previous, hand] + and success[current, hand] + ) + if pred_triplet_valid: + predicted_acceleration = ( + prediction.joints_camera_m[current, hand] + - 2 * prediction.joints_camera_m[previous, hand] + + prediction.joints_camera_m[before_previous, hand] + ) + target_acceleration = ( + ground_truth.joints_camera_m[current, hand] + - 2 * ground_truth.joints_camera_m[previous, hand] + + ground_truth.joints_camera_m[before_previous, hand] + ) + acceleration_error = np.linalg.norm( + predicted_acceleration - target_acceleration, axis=-1 + ) * 1000.0 + wrist_acceleration = float(acceleration_error[0]) + joint_acceleration = float(acceleration_error.mean()) + identity_switch = None + if wrong_side[previous] is not None and wrong_side[current] is not None: + identity_switch = int(wrong_side[previous] != wrong_side[current]) + temporal_rows.append({ + "take": str(ground_truth.takes[current]), + "side": side, + "frame_id_from": int(ground_truth.frame_ids[previous]), + "frame_id_to": int(ground_truth.frame_ids[current]), + "annotation_pair_valid": int(gt_pair_valid), + "evaluation_pair_success": int(gt_pair_valid and pred_pair_valid), + "annotation_triplet_valid": int(gt_triplet_valid), + "evaluation_triplet_success": int(pred_triplet_valid), + "wrist_velocity_error_mm_per_frame": wrist_velocity, + "joint_velocity_error_mm_per_frame": joint_velocity, + "wrist_acceleration_error_mm_per_frame2": wrist_acceleration, + "joint_acceleration_error_mm_per_frame2": joint_acceleration, + "identity_switch_fraction": identity_switch, + }) + + metric_summary = { + metric: distribution_summary(row[metric] for row in rows) + for metric in PRIMARY_METRICS + } + valid_joint = np.broadcast_to(valid[..., None], joint_error.shape) + success_joint = np.broadcast_to(success[..., None], joint_error.shape) + report: dict[str, Any] = { + "status": "evaluated", + "schema_version": SCHEMA_VERSION, + "model_name": prediction.model_name, + "frames": int(len(ground_truth.frame_keys)), + "takes": int(len(set(map(str, ground_truth.takes.tolist())))), + "official_test_used": False, + "split_role": "official_validation", + "prediction_metadata": dict(prediction.metadata), + "projected_2d_pixel_scale": pixel_scale, + "temporal_evaluation_clip_length": temporal_clip_length, + "coverage": { + "annotation_valid_hand_frames": int(valid.sum()), + "successful_hand_frames": int(success.sum()), + "hand_frame_fraction": float(success.sum() / valid.sum()), + "annotation_invalid_prediction_rate": float( + prediction.detected[~valid].mean() if np.any(~valid) else 0.0 + ), + "valid_temporal_pairs": int(sum(row["annotation_pair_valid"] for row in temporal_rows)), + "successful_temporal_pairs": int( + sum(row["evaluation_pair_success"] for row in temporal_rows) + ), + }, + "metrics_success_conditioned": metric_summary, + "failure_aware": { + "absolute_pck_20mm": float( + (success_joint & (joint_error <= 20.0))[valid_joint].mean() + ), + "absolute_pck_50mm": float( + (success_joint & (joint_error <= 50.0))[valid_joint].mean() + ), + "absolute_auc_0_50mm": _auc_pck( + joint_error[valid_joint], success_joint[valid_joint] + ), + "root_relative_pck_20mm": float( + (success_joint & (relative_error <= 20.0))[valid_joint].mean() + ), + "root_relative_pck_50mm": float( + (success_joint & (relative_error <= 50.0))[valid_joint].mean() + ), + "root_relative_auc_0_50mm": _auc_pck( + relative_error[valid_joint], success_joint[valid_joint] + ), + }, + "per_side": { + side: { + "coverage": float(success[:, hand].sum() / valid[:, hand].sum()), + **{ + metric: distribution_summary( + row[metric] for row in rows if row["side"] == side + ) + for metric in PRIMARY_METRICS + }, + } + for hand, side in enumerate(SIDES) + }, + "temporal_metrics_success_conditioned": { + name: distribution_summary(row[name] for row in temporal_rows) + for name in ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "joint_acceleration_error_mm_per_frame2", + "identity_switch_fraction", + ) + }, + "equal_take_bootstrap_ci": bootstrap_take_means( + rows, + ("coverage_success",) + PRIMARY_METRICS, + seed=bootstrap_seed, + samples=bootstrap_samples, + ), + } + valid_pairs = report["coverage"]["valid_temporal_pairs"] + report["coverage"]["temporal_pair_fraction"] = ( + float(report["coverage"]["successful_temporal_pairs"] / valid_pairs) + if valid_pairs + else None + ) + return report, rows, temporal_rows + + +def write_csv_rows(path: str | Path, rows: Sequence[Mapping[str, Any]]) -> None: + if not rows: + raise ValueError("Cannot write an empty metric table") + output = Path(path) + output.parent.mkdir(parents=True, exist_ok=True) + with output.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def paired_take_bootstrap( + baseline_rows: Sequence[Mapping[str, Any]], + candidate_rows: Sequence[Mapping[str, Any]], + metrics: Sequence[str] = PRIMARY_METRICS, + *, + seed: int = 20260716, + samples: int = 10_000, +) -> list[dict[str, Any]]: + """Bootstrap candidate-minus-baseline deltas on their exact success intersection.""" + + key_fields = ("frame_key", "side") + baseline = {tuple(row[field] for field in key_fields): row for row in baseline_rows} + candidate = {tuple(row[field] for field in key_fields): row for row in candidate_rows} + if set(baseline) != set(candidate): + raise ValueError("Paired metric tables do not contain identical hand-frame keys") + rng = np.random.default_rng(seed) + output: list[dict[str, Any]] = [] + for metric in metrics: + by_take: dict[str, list[float]] = defaultdict(list) + for key in baseline: + first = baseline[key].get(metric) + second = candidate[key].get(metric) + if first is None or second is None: + continue + if np.isfinite(float(first)) and np.isfinite(float(second)): + by_take[str(baseline[key]["take"])].append(float(second) - float(first)) + take_delta = np.asarray( + [np.mean(values) for values in by_take.values() if values], dtype=np.float64 + ) + if take_delta.size == 0: + output.append({ + "metric": metric, + "paired_hand_frames": 0, + "take_count": 0, + "candidate_minus_baseline": None, + "ci95_low": None, + "ci95_high": None, + }) + continue + indices = rng.integers(0, take_delta.size, size=(samples, take_delta.size)) + boot = take_delta[indices].mean(axis=1) + output.append({ + "metric": metric, + "paired_hand_frames": int(sum(len(values) for values in by_take.values())), + "take_count": int(take_delta.size), + "candidate_minus_baseline": float(take_delta.mean()), + "ci95_low": float(np.percentile(boot, 2.5)), + "ci95_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/subset.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/subset.py new file mode 100644 index 0000000000000000000000000000000000000000..250d37a0fa78a5caf231fa86d3948bce52f3f31d --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/subset.py @@ -0,0 +1,72 @@ +"""Deterministic take-balanced, within-take stratified subset construction.""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Mapping, Sequence + +import numpy as np + + +def balanced_stratified_indices( + records: Sequence[Mapping[str, object]], + count: int, + *, + seed: int, +) -> list[int]: + """Balance quotas over takes and round-robin available within-take strata.""" + + if count <= 0 or count > len(records): + raise ValueError("count must be positive and no larger than the record count") + by_take: dict[str, list[Mapping[str, object]]] = defaultdict(list) + for record in records: + by_take[str(record["take"])].append(record) + takes = sorted(by_take) + if not takes: + return [] + + rng = np.random.default_rng(seed) + shuffled_takes = list(np.asarray(takes)[rng.permutation(len(takes))]) + base, remainder = divmod(count, len(takes)) + quotas = {take: base + int(position < remainder) for position, take in enumerate(shuffled_takes)} + selected: list[int] = [] + + for take in takes: + groups: dict[tuple[str, str, str], list[Mapping[str, object]]] = defaultdict(list) + for record in by_take[take]: + stratum = ( + str(record["hand_size_bucket"]), + str(record["depth_bucket"]), + str(record["annotation_state"]), + ) + groups[stratum].append(record) + group_keys = sorted(groups) + group_keys = [group_keys[int(index)] for index in rng.permutation(len(group_keys))] + for key in group_keys: + order = rng.permutation(len(groups[key])) + groups[key] = [groups[key][int(index)] for index in order] + cursors = {key: 0 for key in group_keys} + take_selected = 0 + while take_selected < min(quotas[take], len(by_take[take])): + progressed = False + for key in group_keys: + cursor = cursors[key] + if cursor >= len(groups[key]): + continue + selected.append(int(groups[key][cursor]["clip_index"])) + cursors[key] += 1 + take_selected += 1 + progressed = True + if take_selected >= quotas[take]: + break + if not progressed: + break + + if len(selected) < count: + selected_set = set(selected) + remaining = [int(record["clip_index"]) for record in records if int(record["clip_index"]) not in selected_set] + order = rng.permutation(len(remaining)) + selected.extend(remaining[int(index)] for index in order[: count - len(selected)]) + if len(selected) != count or len(set(selected)) != count: + raise AssertionError("subset construction failed to return unique requested indices") + return sorted(selected) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/temporal_filter.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/temporal_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..44b73366b267f458273c51efb3583dc1b4778020 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/temporal_filter.py @@ -0,0 +1,183 @@ +"""Inference-only temporal filters and jitter metrics with hard segment resets.""" + +from __future__ import annotations + +from collections.abc import Callable + +import numpy as np +from scipy.signal import butter, sosfiltfilt +from scipy.spatial.transform import Rotation + + +def valid_segments( + clip_ids: np.ndarray, + frame_ids: np.ndarray, + frame_valid: np.ndarray, +) -> list[np.ndarray]: + """Return contiguous valid indices without crossing clip or frame gaps.""" + + clip_ids = np.asarray(clip_ids) + frame_ids = np.asarray(frame_ids) + frame_valid = np.asarray(frame_valid, dtype=bool) + if not (clip_ids.ndim == frame_ids.ndim == frame_valid.ndim == 1): + raise ValueError("segment metadata must be one-dimensional") + if not (len(clip_ids) == len(frame_ids) == len(frame_valid)): + raise ValueError("segment metadata lengths differ") + output: list[np.ndarray] = [] + start: int | None = None + for index in range(len(frame_ids)): + continues = ( + start is not None + and frame_valid[index] + and clip_ids[index] == clip_ids[index - 1] + and frame_ids[index] == frame_ids[index - 1] + 1 + ) + if not continues: + if start is not None: + output.append(np.arange(start, index, dtype=np.int64)) + start = index if frame_valid[index] else None + if start is not None: + output.append(np.arange(start, len(frame_ids), dtype=np.int64)) + return output + + +def ema(values: np.ndarray, alpha: float) -> np.ndarray: + if not 0.0 < alpha <= 1.0: + raise ValueError("EMA alpha must be in (0, 1]") + values = np.asarray(values) + if values.ndim < 1 or values.shape[0] == 0: + raise ValueError("EMA requires a non-empty time dimension") + output = values.astype(np.float64, copy=True) + for index in range(1, len(output)): + output[index] = alpha * values[index] + (1.0 - alpha) * output[index - 1] + return output.astype(values.dtype, copy=False) + + +def butterworth_zero_phase( + values: np.ndarray, + cutoff_hz: float, + fps: float, + order: int = 2, +) -> np.ndarray: + values = np.asarray(values) + if values.ndim < 1 or values.shape[0] < 4: + raise ValueError("zero-phase filtering requires at least four frames") + if fps <= 0.0 or not 0.0 < cutoff_hz < fps / 2.0: + raise ValueError("Butterworth cutoff must lie below Nyquist") + if order < 1: + raise ValueError("Butterworth order must be positive") + sections = butter(order, cutoff_hz, btype="lowpass", fs=fps, output="sos") + # H2O inference clips have T=8. Explicit n-1 padding preserves the hard + # clip boundary while allowing a verified zero-phase filter on full clips. + filtered = sosfiltfilt( + sections, values.astype(np.float64), axis=0, padlen=values.shape[0] - 1, + ) + if not np.isfinite(filtered).all(): + raise FloatingPointError("Butterworth filtering produced NaN/Inf") + return filtered.astype(values.dtype) + + +def apply_by_segment( + values: np.ndarray, + segments: list[np.ndarray], + operation: Callable[[np.ndarray], np.ndarray], + *, + minimum_frames: int, +) -> tuple[np.ndarray, int]: + values = np.asarray(values) + output = values.copy() + fallback_segments = 0 + for indices in segments: + if len(indices) < minimum_frames: + fallback_segments += 1 + continue + filtered = operation(values[indices]) + if filtered.shape != values[indices].shape: + raise ValueError("temporal operation changed the signal shape") + output[indices] = filtered + return output, fallback_segments + + +def unwrap_quaternion_signs(quaternions: np.ndarray) -> np.ndarray: + quaternions = np.asarray(quaternions) + if quaternions.ndim < 2 or quaternions.shape[-1] != 4: + raise ValueError("quaternions must have shape [time, ..., 4]") + output = quaternions.copy() + for index in range(1, len(output)): + dots = np.sum(output[index - 1] * output[index], axis=-1) + output[index][dots < 0.0] *= -1.0 + return output + + +def filter_rotation_matrices( + matrices: np.ndarray, + operation: Callable[[np.ndarray], np.ndarray], +) -> np.ndarray: + matrices = np.asarray(matrices) + if matrices.ndim < 3 or matrices.shape[-2:] != (3, 3): + raise ValueError("rotation matrices must have shape [time, ..., 3, 3]") + original_shape = matrices.shape + quaternions = Rotation.from_matrix(matrices.reshape(-1, 3, 3)).as_quat() + quaternions = quaternions.reshape(*original_shape[:-2], 4) + quaternions = unwrap_quaternion_signs(quaternions) + filtered = operation(quaternions) + norms = np.linalg.norm(filtered, axis=-1, keepdims=True) + if not np.isfinite(norms).all() or np.any(norms < 1e-8): + raise FloatingPointError("quaternion filter produced invalid norms") + filtered = filtered / norms + result = Rotation.from_quat(filtered.reshape(-1, 4)).as_matrix() + return result.reshape(original_shape).astype(matrices.dtype) + + +def finite_differences( + values: np.ndarray, fps: float, order: int, +) -> np.ndarray: + values = np.asarray(values) + if fps <= 0.0 or order < 1: + raise ValueError("finite difference fps/order is invalid") + output = values + for _ in range(order): + output = np.diff(output, axis=0) * fps + return output + + +def derivative_norms(values: np.ndarray, fps: float, order: int) -> np.ndarray: + differences = finite_differences(values, fps, order) + return np.linalg.vector_norm(differences, axis=-1) + + +def high_frequency_energy_ratio( + values: np.ndarray, fps: float, threshold_hz: float = 6.0, +) -> float: + values = np.asarray(values, dtype=np.float64) + if values.ndim < 1 or values.shape[0] < 4: + raise ValueError("spectral metric requires at least four frames") + if not 0.0 < threshold_hz < fps / 2.0: + raise ValueError("spectral threshold must lie below Nyquist") + centered = values - values.mean(axis=0, keepdims=True) + spectrum = np.fft.rfft(centered, axis=0) + power = np.abs(spectrum) ** 2 + frequencies = np.fft.rfftfreq(values.shape[0], d=1.0 / fps) + non_dc = frequencies > 0.0 + denominator = float(power[non_dc].sum()) + if denominator == 0.0: + return 0.0 + return float(power[frequencies >= threshold_hz].sum() / denominator) + + +def rotation_geodesic_degrees( + prediction: np.ndarray, target: np.ndarray, +) -> np.ndarray: + prediction = np.asarray(prediction) + target = np.asarray(target) + if prediction.shape != target.shape or prediction.shape[-2:] != (3, 3): + raise ValueError("rotation geodesic inputs must be aligned matrices") + relative = np.swapaxes(target, -1, -2) @ prediction + cosine = np.clip((np.trace(relative, axis1=-2, axis2=-1) - 1.0) / 2.0, -1.0, 1.0) + return np.rad2deg(np.arccos(cosine)) + + +def ema_low_frequency_delay_frames(alpha: float) -> float: + if not 0.0 < alpha <= 1.0: + raise ValueError("EMA alpha must be in (0, 1]") + return (1.0 - alpha) / alpha diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/visualization.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..fcec3681b699141bd51a7d3ad49cab5dcf905f6c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/evaluation/visualization.py @@ -0,0 +1,202 @@ +"""Camera-correct MANO, skeleton, attention, and 3D visualizations.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +import textwrap + +import cv2 +import matplotlib.pyplot as plt +import numpy as np + + +OPENPOSE_HAND_EDGES = tuple( + (start + offset, start + offset + 1) + for start in (1, 5, 9, 13, 17) + for offset in range(3) +) + ((0, 1), (0, 5), (0, 9), (0, 13), (0, 17)) + + +@dataclass(frozen=True) +class MeshLayer: + vertices_camera: np.ndarray + faces: np.ndarray + color_rgb: tuple[int, int, int] + alpha: float = 0.55 + + +def project_camera_points(points: np.ndarray, K: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + points = np.asarray(points, dtype=np.float32) + z = points[..., 2] + safe_z = np.where(z > 1e-8, z, 1.0) + u = K[0, 0] * points[..., 0] / safe_z + K[0, 2] + v = K[1, 1] * points[..., 1] / safe_z + K[1, 2] + return np.stack((u, v), axis=-1), z + + +def render_mesh_layers(image_rgb: np.ndarray, layers: Sequence[MeshLayer]) -> np.ndarray: + """Rasterize constant-color triangular meshes with perspective-correct z-order.""" + + image = np.asarray(image_rgb, dtype=np.uint8) + height, width = image.shape[:2] + depth_buffer = np.full((height, width), np.inf, dtype=np.float32) + color_buffer = np.zeros((height, width, 3), dtype=np.float32) + alpha_buffer = np.zeros((height, width), dtype=np.float32) + + for layer in layers: + vertices = np.asarray(layer.vertices_camera, dtype=np.float32) + faces = np.asarray(layer.faces, dtype=np.int64) + # The caller supplies already projected xy by temporarily storing pixel x/y + # in vertices_camera x/y when using this low-level rasterizer. + projected = vertices[:, :2] + z_values = vertices[:, 2] + for face in faces: + z = z_values[face] + if np.any(z <= 1e-6) or not np.isfinite(z).all(): + continue + triangle = projected[face] + if not np.isfinite(triangle).all(): + continue + x_min = max(int(np.floor(triangle[:, 0].min())), 0) + x_max = min(int(np.ceil(triangle[:, 0].max())), width - 1) + y_min = max(int(np.floor(triangle[:, 1].min())), 0) + y_max = min(int(np.ceil(triangle[:, 1].max())), height - 1) + if x_min > x_max or y_min > y_max: + continue + x0, y0 = triangle[0] + x1, y1 = triangle[1] + x2, y2 = triangle[2] + denominator = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2) + if abs(float(denominator)) < 1e-8: + continue + yy, xx = np.mgrid[y_min : y_max + 1, x_min : x_max + 1] + px = xx.astype(np.float32) + 0.5 + py = yy.astype(np.float32) + 0.5 + w0 = ((y1 - y2) * (px - x2) + (x2 - x1) * (py - y2)) / denominator + w1 = ((y2 - y0) * (px - x2) + (x0 - x2) * (py - y2)) / denominator + w2 = 1.0 - w0 - w1 + inside = (w0 >= -1e-5) & (w1 >= -1e-5) & (w2 >= -1e-5) + inverse_z = w0 / z[0] + w1 / z[1] + w2 / z[2] + pixel_z = np.where(inverse_z > 1e-8, 1.0 / inverse_z, np.inf) + local_depth = depth_buffer[y_min : y_max + 1, x_min : x_max + 1] + update = inside & (pixel_z < local_depth) + if not np.any(update): + continue + local_depth[update] = pixel_z[update] + local_color = color_buffer[y_min : y_max + 1, x_min : x_max + 1] + local_color[update] = np.asarray(layer.color_rgb, dtype=np.float32) + local_alpha = alpha_buffer[y_min : y_max + 1, x_min : x_max + 1] + local_alpha[update] = float(layer.alpha) + + alpha = alpha_buffer[..., None] + rendered = image.astype(np.float32) * (1.0 - alpha) + color_buffer * alpha + return np.clip(rendered, 0, 255).astype(np.uint8) + + +def project_mesh_layers(layers: Sequence[MeshLayer], K: np.ndarray) -> list[MeshLayer]: + """Convert camera-space vertices to pixel-x, pixel-y, camera-z vertices.""" + + projected_layers = [] + for layer in layers: + pixels, z = project_camera_points(layer.vertices_camera, K) + pixel_vertices = np.concatenate((pixels, z[:, None]), axis=-1) + projected_layers.append(MeshLayer(pixel_vertices, layer.faces, layer.color_rgb, layer.alpha)) + return projected_layers + + +def draw_skeleton( + image_rgb: np.ndarray, + points: np.ndarray, + color_rgb: tuple[int, int, int], + *, + marker: str = "circle", + draw_edges: bool = True, +) -> np.ndarray: + image = image_rgb.copy() + finite = np.isfinite(points).all(axis=-1) + integer = np.rint(np.where(finite[:, None], points, 0)).astype(np.int32) + if draw_edges: + for start, end in OPENPOSE_HAND_EDGES: + if finite[start] and finite[end]: + cv2.line(image, tuple(integer[start]), tuple(integer[end]), color_rgb, 1, cv2.LINE_AA) + for index, point in enumerate(integer): + if not finite[index]: + continue + if marker == "cross": + cv2.drawMarker(image, tuple(point), color_rgb, cv2.MARKER_CROSS, 8, 1) + elif marker == "ring": + cv2.circle(image, tuple(point), 4, color_rgb, 1, cv2.LINE_AA) + else: + cv2.circle(image, tuple(point), 2, color_rgb, -1, cv2.LINE_AA) + return image + + +def save_attention_figure( + output: Path, + image_rgb: np.ndarray, + left: np.ndarray, + right: np.ndarray, + grid_hw: tuple[int, int], + title: str, +) -> None: + """Save raw and image overlays using a shared left/right attention scale.""" + + height, width = image_rgb.shape[:2] + left_grid = np.asarray(left, dtype=np.float32).reshape(grid_hw) + right_grid = np.asarray(right, dtype=np.float32).reshape(grid_hw) + lower = float(min(left_grid.min(), right_grid.min())) + upper = float(max(left_grid.max(), right_grid.max())) + if upper <= lower: + upper = lower + 1e-8 + fig, axes = plt.subplots(2, 2, figsize=(11, 7), constrained_layout=True) + images = [] + for column, (side, grid) in enumerate((('left', left_grid), ('right', right_grid))): + raw = axes[0, column].imshow(grid, cmap="turbo", vmin=lower, vmax=upper) + images.append(raw) + axes[0, column].set_title(f"{side}: raw weights") + axes[0, column].set_xlabel("patch x") + axes[0, column].set_ylabel("patch y") + upsampled = cv2.resize(grid, (width, height), interpolation=cv2.INTER_CUBIC) + axes[1, column].imshow(image_rgb) + axes[1, column].imshow(upsampled, cmap="turbo", alpha=0.45, vmin=lower, vmax=upper) + axes[1, column].set_title(f"{side}: RGB overlay") + axes[1, column].axis("off") + fig.colorbar(images[0], ax=axes, shrink=0.82, label="raw head-averaged attention weight") + wrapped_title = textwrap.fill(title, width=95) + fig.suptitle(f"{wrapped_title}\nlast layer, head-averaged; visualization is not calibrated probability", fontsize=11) + fig.savefig(output, dpi=160) + plt.close(fig) + + +def save_camera_views( + output: Path, + predicted: np.ndarray, + target: np.ndarray, + valid_hands: np.ndarray, + title: str, +) -> None: + fig, axes = plt.subplots(1, 2, figsize=(12, 5), constrained_layout=True) + colors = ("#22a06b", "#e56b2f") + for axis, view_name, horizontal_index in zip(axes, ("front", "side"), (0, 2), strict=True): + for hand in range(2): + axis.scatter( + predicted[hand, :, horizontal_index], predicted[hand, :, 1], + s=4, alpha=0.35, c=colors[hand], label=f"{'LR'[hand]} pred", + ) + if valid_hands[hand]: + axis.scatter( + target[hand, :, horizontal_index], target[hand, :, 1], + s=4, alpha=0.22, c="black", label=f"{'LR'[hand]} GT", + ) + axis.set_xlabel("x (m)" if horizontal_index == 0 else "z (m)") + axis.set_ylabel("y (m)") + axis.set_title(f"{view_name}: {'x-y' if horizontal_index == 0 else 'z-y'}") + axis.legend(fontsize=7) + axis.set_aspect("equal", adjustable="datalim") + axis.invert_yaxis() + axis.grid(alpha=0.25) + fig.suptitle(textwrap.fill(title, width=105), fontsize=11) + fig.savefig(output, dpi=160) + plt.close(fig) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/__init__.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..202e66331920bb936a0aeacff8fc23a08071a85e --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/__init__.py @@ -0,0 +1,14 @@ +"""Camera and MANO geometry helpers.""" + +from .camera import depth_mm_to_m, intrinsics_from_h2o, project_points, unproject_depth +from .mano_translation import mano_raw_to_wrist, wrist_to_mano_raw + +__all__ = [ + "depth_mm_to_m", + "intrinsics_from_h2o", + "project_points", + "unproject_depth", + "mano_raw_to_wrist", + "wrist_to_mano_raw", +] + diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/camera.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..0f897cdebe7bd9cbd1a19c164a9b4909c72f6f4b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/camera.py @@ -0,0 +1,121 @@ +"""Camera-space geometry with explicit H2O units and image conventions.""" + +from __future__ import annotations + +from typing import overload + +import numpy as np +import torch + + +def intrinsics_from_h2o(values: np.ndarray) -> tuple[np.ndarray, tuple[int, int]]: + """Convert `fx fy cx cy width height` to K and `(height, width)`.""" + + values = np.asarray(values, dtype=np.float64).reshape(-1) + if values.size != 6: + raise ValueError(f"Expected 6 intrinsics values, got {values.size}") + fx, fy, cx, cy, width, height = values + if fx <= 0 or fy <= 0 or width <= 0 or height <= 0: + raise ValueError(f"Invalid intrinsics: {values.tolist()}") + K = np.array([[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]], dtype=np.float32) + return K, (int(round(height)), int(round(width))) + + +def depth_mm_to_m(depth_mm: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Convert released uint16 millimeter depth to metric depth plus validity.""" + + depth_m = np.asarray(depth_mm, dtype=np.float32) / 1000.0 + valid = np.isfinite(depth_m) & (depth_m > 0.0) + depth_m = np.where(valid, depth_m, 0.0).astype(np.float32) + return depth_m, valid + + +@overload +def project_points(points_camera: np.ndarray, K: np.ndarray) -> tuple[np.ndarray, np.ndarray]: ... + + +@overload +def project_points(points_camera: torch.Tensor, K: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: ... + + +def project_points(points_camera, K): + """Project x-right, y-down, z-forward camera points to image pixels.""" + + if isinstance(points_camera, torch.Tensor): + z = points_camera[..., 2] + safe_z = torch.where(z.abs() > 1e-8, z, torch.ones_like(z)) + fx, fy, cx, cy = K[..., 0, 0], K[..., 1, 1], K[..., 0, 2], K[..., 1, 2] + while fx.ndim < z.ndim: + fx, fy, cx, cy = (value.unsqueeze(-1) for value in (fx, fy, cx, cy)) + u = fx * points_camera[..., 0] / safe_z + cx + v = fy * points_camera[..., 1] / safe_z + cy + return torch.stack((u, v), dim=-1), z > 0 + + points = np.asarray(points_camera) + matrix = np.asarray(K) + z = points[..., 2] + safe_z = np.where(np.abs(z) > 1e-8, z, 1.0) + fx, fy, cx, cy = matrix[..., 0, 0], matrix[..., 1, 1], matrix[..., 0, 2], matrix[..., 1, 2] + while np.ndim(fx) < np.ndim(z): + fx, fy, cx, cy = (np.expand_dims(value, -1) for value in (fx, fy, cx, cy)) + u = fx * points[..., 0] / safe_z + cx + v = fy * points[..., 1] / safe_z + cy + return np.stack((u, v), axis=-1).astype(np.float32), z > 0 + + +def unproject_depth(depth_m: np.ndarray, K: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Unproject an HxW metric depth map to an HxWx3 camera-space point map.""" + + depth = np.asarray(depth_m, dtype=np.float32) + if depth.ndim != 2: + raise ValueError(f"Expected HxW depth, got {depth.shape}") + matrix = np.asarray(K, dtype=np.float32) + height, width = depth.shape + u, v = np.meshgrid(np.arange(width, dtype=np.float32), np.arange(height, dtype=np.float32)) + x = (u - matrix[0, 2]) * depth / matrix[0, 0] + y = (v - matrix[1, 2]) * depth / matrix[1, 1] + points = np.stack((x, y, depth), axis=-1) + valid = np.isfinite(depth) & (depth > 0.0) + points[~valid] = 0.0 + return points, valid + + +def resize_and_pad_intrinsics( + K: np.ndarray, + source_hw: tuple[int, int], + resized_hw: tuple[int, int], + pad_left_top: tuple[int, int] = (0, 0), +) -> np.ndarray: + """Update K for anisotropic resize followed by left/top pixel padding.""" + + source_h, source_w = source_hw + resized_h, resized_w = resized_hw + pad_left, pad_top = pad_left_top + if min(source_h, source_w, resized_h, resized_w) <= 0: + raise ValueError("Image sizes must be positive") + out = np.asarray(K, dtype=np.float32).copy() + sx = resized_w / source_w + sy = resized_h / source_h + out[0, 0] *= sx + out[0, 2] = out[0, 2] * sx + pad_left + out[1, 1] *= sy + out[1, 2] = out[1, 2] * sy + pad_top + return out + + +def patch_center_rays( + K: torch.Tensor, + grid_hw: tuple[int, int], + patch_size: int, +) -> torch.Tensor: + """Return unnormalized patch-center rays `[... , N, 3]`.""" + + grid_h, grid_w = grid_hw + dtype, device = K.dtype, K.device + u = (torch.arange(grid_w, dtype=dtype, device=device) + 0.5) * patch_size + v = (torch.arange(grid_h, dtype=dtype, device=device) + 0.5) * patch_size + vv, uu = torch.meshgrid(v, u, indexing="ij") + x = (uu.reshape(-1) - K[..., 0, 2].unsqueeze(-1)) / K[..., 0, 0].unsqueeze(-1) + y = (vv.reshape(-1) - K[..., 1, 2].unsqueeze(-1)) / K[..., 1, 1].unsqueeze(-1) + one = torch.ones_like(x) + return torch.stack((x, y, one), dim=-1) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/mano_compat.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/mano_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..92572790a447e15a1bed2ae8cfdec9473188276b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/mano_compat.py @@ -0,0 +1,26 @@ +"""Compatibility shim for the licensed MANO files and legacy chumpy loader.""" + +from __future__ import annotations + +import inspect + +import numpy as np + + +def enable_legacy_mano_loading() -> None: + """Restore names removed after the legacy MANO/chumpy release.""" + + if not hasattr(inspect, "getargspec"): + inspect.getargspec = inspect.getfullargspec # type: ignore[attr-defined] + aliases = { + "bool": bool, + "int": int, + "float": float, + "complex": complex, + "object": object, + "unicode": str, + "str": str, + } + for name, value in aliases.items(): + if name not in np.__dict__: + setattr(np, name, value) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/mano_translation.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/mano_translation.py new file mode 100644 index 0000000000000000000000000000000000000000..bd038e2956d172f29194b892244df021571b6ba5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/mano_translation.py @@ -0,0 +1,34 @@ +"""Conversion between H2O raw MANO translation and wrist/root translation.""" + +from __future__ import annotations + +import numpy as np +import torch + + +def mano_raw_to_wrist(raw_translation, mano_root_offset_m): + """Convert H2O raw MANO translation to camera-space MANO joint-0 position. + + H2OPlayer places native MANO joints using `joint_mm / 1000 + raw_translation`. + Therefore the wrist is the placed native joint 0, not the raw translation itself. + """ + + if isinstance(raw_translation, torch.Tensor): + return raw_translation + mano_root_offset_m + return np.asarray(raw_translation) + np.asarray(mano_root_offset_m) + + +def wrist_to_mano_raw(wrist_translation, mano_root_offset_m): + """Inverse of :func:`mano_raw_to_wrist`.""" + + if isinstance(wrist_translation, torch.Tensor): + return wrist_translation - mano_root_offset_m + return np.asarray(wrist_translation) - np.asarray(mano_root_offset_m) + + +def root_center_mano(vertices_m, joints_m): + """Root-center native MANO outputs while returning the removed root offset.""" + + root = joints_m[..., 0, :] + return vertices_m - root[..., None, :], joints_m - root[..., None, :], root + diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/mixed_projection.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..a80850e3c6eaa88fd7f1501e539f629638d881bb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/mixed_projection.py @@ -0,0 +1,167 @@ +"""Differentiable mixed-projection translation solve.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch + + +@dataclass(frozen=True) +class TorchMixedProjectionResult: + translation_m: torch.Tensor + support_count: torch.Tensor + residual_scale_px: torch.Tensor + conditioning: torch.Tensor + inlier_ratio: torch.Tensor + uncertainty_xy_m: torch.Tensor + success: torch.Tensor + + +def _masked_lower_median(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + """Return the deterministic lower median along the joint dimension.""" + + if values.ndim != 2 or mask.shape != values.shape: + raise ValueError("masked median expects equal [N,J] tensors") + counts = mask.sum(dim=1) + ordered = torch.sort( + torch.where(mask, values, torch.full_like(values, torch.inf)), dim=1, + ).values + indices = ((counts - 1).clamp_min(0) // 2)[:, None] + selected = ordered.gather(1, indices).squeeze(1) + return torch.where(counts > 0, selected, torch.full_like(selected, torch.inf)) + + +def solve_mixed_projection_translation( + root_relative_joints_m: torch.Tensor, + anchors_px: torch.Tensor, + K: torch.Tensor, + refined_z_m: torch.Tensor, + fallback_translation_m: torch.Tensor, + *, + image_hw: tuple[int, int], + K_available: torch.Tensor | None = None, + minimum_support: int = 4, + huber_delta_px: float = 16.0, + irls_iterations: int = 5, + minimum_joint_depth_m: float = 0.05, + denominator_epsilon: float = 1e-10, +) -> TorchMixedProjectionResult: + """Solve tx/ty while retaining gradients through geometry and robust weights.""" + + if root_relative_joints_m.shape[-2:] != (21, 3): + raise ValueError("root-relative joints must end in [21,3]") + if anchors_px.shape != (*root_relative_joints_m.shape[:-1], 2): + raise ValueError("anchor shape differs from joints") + if K.shape != (*root_relative_joints_m.shape[:-2], 3, 3): + raise ValueError("K shape differs from joints") + if refined_z_m.shape != root_relative_joints_m.shape[:-2]: + raise ValueError("z shape differs from joints") + if fallback_translation_m.shape != (*refined_z_m.shape, 3): + raise ValueError("fallback translation shape differs from z") + if not 1 <= minimum_support <= 21: + raise ValueError("minimum_support must be in [1,21]") + if huber_delta_px <= 0.0 or irls_iterations < 1: + raise ValueError("Huber delta and IRLS iterations must be positive") + height, width = image_hw + if height <= 0 or width <= 0: + raise ValueError("image dimensions must be positive") + + prefix = refined_z_m.shape + count = refined_z_m.numel() + joints = root_relative_joints_m.reshape(count, 21, 3) + anchors = anchors_px.reshape(count, 21, 2) + intrinsics = K.reshape(count, 3, 3) + z = refined_z_m.reshape(count) + fallback = fallback_translation_m.reshape(count, 3) + available = ( + torch.ones(count, dtype=torch.bool, device=z.device) + if K_available is None else K_available.reshape(count).bool() + ) + fx, fy = intrinsics[:, 0, 0], intrinsics[:, 1, 1] + cx, cy = intrinsics[:, 0, 2], intrinsics[:, 1, 2] + joint_z = joints[..., 2] + z[:, None] + finite_k = torch.isfinite(intrinsics).all(dim=-1).all(dim=-1) & (fx > 1e-8) & (fy > 1e-8) + mask = ( + available[:, None] + & finite_k[:, None] + & torch.isfinite(z)[:, None] + & torch.isfinite(joints).all(dim=-1) + & torch.isfinite(anchors).all(dim=-1) + & (joint_z > minimum_joint_depth_m) + & (anchors[..., 0] >= 0.0) + & (anchors[..., 0] <= width - 1.0) + & (anchors[..., 1] >= 0.0) + & (anchors[..., 1] <= height - 1.0) + ) + support = mask.sum(dim=1) + safe_depth = torch.where(mask, joint_z, torch.ones_like(joint_z)) + ax = torch.where(mask, fx[:, None] / safe_depth, torch.zeros_like(safe_depth)) + ay = torch.where(mask, fy[:, None] / safe_depth, torch.zeros_like(safe_depth)) + bx = anchors[..., 0] - cx[:, None] - fx[:, None] * joints[..., 0] / safe_depth + by = anchors[..., 1] - cy[:, None] - fy[:, None] * joints[..., 1] / safe_depth + bx = torch.where(mask, bx, torch.zeros_like(bx)) + by = torch.where(mask, by, torch.zeros_like(by)) + + def solve(weights: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + denom_x = (weights * ax.square()).sum(dim=1) + denom_y = (weights * ay.square()).sum(dim=1) + tx = (weights * ax * bx).sum(dim=1) / denom_x.clamp_min(denominator_epsilon) + ty = (weights * ay * by).sum(dim=1) / denom_y.clamp_min(denominator_epsilon) + return tx, ty, denom_x, denom_y + + weights = mask.to(joints.dtype) + tx, ty, denom_x, denom_y = solve(weights) + for _ in range(irls_iterations): + residual = torch.sqrt( + (ax * tx[:, None] - bx).square() + + (ay * ty[:, None] - by).square() + + 1e-12 + ) + robust = torch.clamp(huber_delta_px / residual, max=1.0) + weights = torch.where(mask, robust, torch.zeros_like(robust)) + tx, ty, denom_x, denom_y = solve(weights) + + residual = torch.sqrt( + (ax * tx[:, None] - bx).square() + + (ay * ty[:, None] - by).square() + + 1e-12 + ) + median = _masked_lower_median(residual, mask) + mad = _masked_lower_median(torch.abs(residual - median[:, None]), mask) + scale = torch.where(support > 0, 1.4826 * mad, torch.full_like(mad, torch.inf)) + inlier_ratio = torch.where( + support > 0, + (mask & (residual <= huber_delta_px)).sum(dim=1).to(joints.dtype) + / support.clamp_min(1).to(joints.dtype), + torch.zeros_like(z), + ) + conditioning = torch.minimum(denom_x, denom_y) / torch.maximum( + denom_x, denom_y, + ).clamp_min(denominator_epsilon) + uncertainty = torch.stack(( + scale / torch.sqrt(denom_x.clamp_min(denominator_epsilon)), + scale / torch.sqrt(denom_y.clamp_min(denominator_epsilon)), + ), dim=-1) + success = ( + available & finite_k & (support >= minimum_support) + & (denom_x > denominator_epsilon) & (denom_y > denominator_epsilon) + & torch.isfinite(tx) & torch.isfinite(ty) + ) + solved = torch.stack((tx, ty, z), dim=-1) + translation = torch.where(success[:, None], solved, fallback) + finite_z = torch.isfinite(z) + use_selected_z = available & finite_k & finite_z + translation = torch.cat(( + translation[:, :2], + torch.where(use_selected_z, z, fallback[:, 2])[:, None], + ), dim=-1) + return TorchMixedProjectionResult( + translation_m=translation.reshape(*prefix, 3), + support_count=support.reshape(prefix), + residual_scale_px=scale.reshape(prefix), + conditioning=conditioning.reshape(prefix), + inlier_ratio=inlier_ratio.reshape(prefix), + uncertainty_xy_m=uncertainty.reshape(*prefix, 2), + success=success.reshape(prefix), + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/rotations.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/rotations.py new file mode 100644 index 0000000000000000000000000000000000000000..ed7d554d59c60675461eab9e9b0cf9e7b1728b77 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/geometry/rotations.py @@ -0,0 +1,70 @@ +"""Differentiable rotation representations used by prediction and losses.""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F + + +def rotation_6d_to_matrix(value: torch.Tensor) -> torch.Tensor: + if value.shape[-1] != 6: + raise ValueError(f"Expected rotation 6D, got {value.shape}") + first = F.normalize(value[..., :3], dim=-1) + second_raw = value[..., 3:] + second = F.normalize(second_raw - (first * second_raw).sum(dim=-1, keepdim=True) * first, dim=-1) + third = torch.cross(first, second, dim=-1) + return torch.stack((first, second, third), dim=-2) + + +def axis_angle_to_matrix(axis_angle: torch.Tensor) -> torch.Tensor: + """Rodrigues formula with a stable small-angle branch.""" + + if axis_angle.shape[-1] != 3: + raise ValueError(f"Expected axis-angle [...,3], got {axis_angle.shape}") + theta2 = (axis_angle * axis_angle).sum(dim=-1, keepdim=True) + theta = torch.sqrt(theta2.clamp_min(1e-16)) + a = torch.where(theta2 > 1e-8, torch.sin(theta) / theta, 1 - theta2 / 6 + theta2 * theta2 / 120) + # torch.where evaluates both branches, so the large-angle expression must + # also remain finite at exact zero for zero-initialized residual heads. + b = torch.where( + theta2 > 1e-8, + (1 - torch.cos(theta)) / theta2.clamp_min(1e-16), + 0.5 - theta2 / 24 + theta2 * theta2 / 720, + ) + x, y, z = axis_angle.unbind(dim=-1) + zero = torch.zeros_like(x) + skew = torch.stack((zero, -z, y, z, zero, -x, -y, x, zero), dim=-1).reshape(axis_angle.shape[:-1] + (3, 3)) + eye = torch.eye(3, dtype=axis_angle.dtype, device=axis_angle.device).expand(axis_angle.shape[:-1] + (3, 3)) + return eye + a.unsqueeze(-1) * skew + b.unsqueeze(-1) * (skew @ skew) + + +def matrix_to_axis_angle(matrix: torch.Tensor) -> torch.Tensor: + """Convert rotation matrices to axis-angle, including rotations near pi.""" + + if matrix.shape[-2:] != (3, 3): + raise ValueError(f"Expected rotation matrices, got {matrix.shape}") + m00, m01, m02 = matrix[..., 0, 0], matrix[..., 0, 1], matrix[..., 0, 2] + m10, m11, m12 = matrix[..., 1, 0], matrix[..., 1, 1], matrix[..., 1, 2] + m20, m21, m22 = matrix[..., 2, 0], matrix[..., 2, 1], matrix[..., 2, 2] + one = torch.ones_like(m00) + magnitudes = torch.sqrt(torch.stack(( + one + m00 + m11 + m22, + one + m00 - m11 - m22, + one - m00 + m11 - m22, + one - m00 - m11 + m22, + ), dim=-1).clamp_min(1e-12)) + candidates = torch.stack(( + torch.stack((magnitudes[..., 0].square(), m21 - m12, m02 - m20, m10 - m01), dim=-1), + torch.stack((m21 - m12, magnitudes[..., 1].square(), m01 + m10, m02 + m20), dim=-1), + torch.stack((m02 - m20, m01 + m10, magnitudes[..., 2].square(), m12 + m21), dim=-1), + torch.stack((m10 - m01, m02 + m20, m12 + m21, magnitudes[..., 3].square()), dim=-1), + ), dim=-2) + largest = magnitudes.argmax(dim=-1) + selected = candidates.gather(-2, largest[..., None, None].expand(largest.shape + (1, 4))).squeeze(-2) + divisor = 2 * magnitudes.gather(-1, largest[..., None]) + quaternion = selected / divisor + quaternion = torch.where(quaternion[..., :1] < 0, -quaternion, quaternion) + xyz = quaternion[..., 1:] + half_sine = torch.linalg.vector_norm(xyz, dim=-1, keepdim=True).clamp_min(1e-12) + angle = 2 * torch.atan2(half_sine, quaternion[..., :1]) + return xyz * (angle / half_sine) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/inference/__init__.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4e4eaa20d7002f3d29890cb7af9c24a735a8bf --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/inference/__init__.py @@ -0,0 +1,5 @@ +"""Length-generalized inference utilities.""" + +from .sequence import LengthGeneralizedInference, SequenceInferenceConfig + +__all__ = ["LengthGeneralizedInference", "SequenceInferenceConfig"] diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/inference/sequence.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/inference/sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..288f7b6fd1e09d0af4e624ed4c62a1ac13fcc4cc --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/inference/sequence.py @@ -0,0 +1,212 @@ +"""Bounded-GPU-memory offline and causal sequence inference.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Iterable, Mapping + +import torch + + +@dataclass(frozen=True) +class SequenceInferenceConfig: + mode: str + window_size: int + offline_stride: int | None = None + stitching: str = "center" + + def __post_init__(self) -> None: + if self.mode not in {"offline", "causal"}: + raise ValueError(f"unknown sequence inference mode: {self.mode}") + if self.window_size < 1: + raise ValueError("window_size must be positive") + if self.offline_stride is not None and not 1 <= self.offline_stride <= self.window_size: + raise ValueError("offline_stride must be in [1, window_size]") + if self.stitching != "center": + raise ValueError("only fixed center stitching is registered") + + +class LengthGeneralizedInference: + """Run a model over a frame iterator without sequence-length GPU growth.""" + + _NON_TEMPORAL_OUTPUTS = { + "mano_shape_sequence", "coarse_mano_shape_sequence", "attention", + } + + def __init__( + self, + model: torch.nn.Module, + config: SequenceInferenceConfig, + *, + device: torch.device | str, + autocast_dtype: torch.dtype | None = None, + ) -> None: + self.model = model + self.config = config + self.device = torch.device(device) + self.autocast_dtype = autocast_dtype + model_config = getattr(model, "config", None) + attention_mode = getattr(model_config, "temporal_attention_mode", None) + if config.mode == "causal" and attention_mode != "causal": + raise ValueError( + "causal streaming requires temporal_attention_mode='causal'" + ) + self.maximum_resident_frames = 0 + self.maximum_input_buffer_frames = 0 + + @staticmethod + def _stack_frames(frames: list[Mapping[str, object]]) -> dict[str, object]: + if not frames: + raise ValueError("cannot stack an empty frame sequence") + output: dict[str, object] = {} + for key in frames[0]: + values = [frame[key] for frame in frames] + first = values[0] + if torch.is_tensor(first) and first.ndim >= 2 and first.shape[1] == 1: + if not all(torch.is_tensor(value) and value.shape[1] == 1 for value in values): + raise ValueError(f"inconsistent temporal field: {key}") + output[key] = torch.cat(values, dim=1) + else: + if torch.is_tensor(first) and not all( + torch.equal(first, value) for value in values[1:] + if torch.is_tensor(value) + ): + raise ValueError(f"non-temporal tensor changed within window: {key}") + output[key] = first + return output + + def _to_device(self, batch: Mapping[str, object]) -> dict[str, object]: + return { + key: value.to(self.device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + def _run_window(self, frames: list[Mapping[str, object]]) -> dict[str, object]: + self.maximum_resident_frames = max(self.maximum_resident_frames, len(frames)) + batch = self._to_device(self._stack_frames(frames)) + autocast_enabled = self.autocast_dtype is not None and self.device.type == "cuda" + with torch.inference_mode(), torch.autocast( + device_type=self.device.type, + dtype=self.autocast_dtype, + enabled=autocast_enabled, + ): + return self.model(batch) + + @classmethod + def _extract_frame( + cls, output: Mapping[str, object], index: int, time: int, + ) -> dict[str, torch.Tensor]: + frame: dict[str, torch.Tensor] = {} + for key, value in output.items(): + if ( + key not in cls._NON_TEMPORAL_OUTPUTS + and torch.is_tensor(value) + and value.ndim >= 2 + and value.shape[1] == time + ): + frame[key] = value[:, index : index + 1].detach().cpu() + if not frame: + raise ValueError("model output has no temporal tensors") + return frame + + @staticmethod + def _concatenate(frames: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]: + if not frames: + return {} + common = set.intersection(*(set(frame) for frame in frames)) + return { + key: torch.cat([frame[key] for frame in frames], dim=1) + for key in sorted(common) + } + + @staticmethod + def _window_starts(length: int, window: int, stride: int) -> list[int]: + if length <= window: + return [0] + starts = list(range(0, length - window + 1, stride)) + final = length - window + if starts[-1] != final: + starts.append(final) + return starts + + def infer_offline( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> dict[str, torch.Tensor]: + if self.config.mode != "offline": + raise ValueError("infer_offline requires mode='offline'") + window = self.config.window_size + stride = self.config.offline_stride or max(window // 2, 1) + buffer: list[Mapping[str, object]] = [] + buffer_start = 0 + total = 0 + next_start = 0 + last_start: int | None = None + selected: list[dict[str, torch.Tensor] | None] = [] + priority: list[int] = [] + + def run_window(start: int, local_frames: list[Mapping[str, object]]) -> None: + output = self._run_window(local_frames) + local_time = len(local_frames) + for local_index in range(local_time): + global_index = start + local_index + center_priority = min(local_index + 1, local_time - local_index) + if center_priority > priority[global_index]: + selected[global_index] = self._extract_frame( + output, local_index, local_time, + ) + priority[global_index] = center_priority + + for frame in frame_iterator: + buffer.append(frame) + selected.append(None) + priority.append(-1) + total += 1 + self.maximum_input_buffer_frames = max( + self.maximum_input_buffer_frames, len(buffer), + ) + while next_start + window <= total: + offset = next_start - buffer_start + run_window(next_start, buffer[offset : offset + window]) + last_start = next_start + next_start += stride + if last_start > buffer_start: + drop = last_start - buffer_start + del buffer[:drop] + buffer_start = last_start + if total == 0: + return {} + final_start = max(total - window, 0) + if last_start != final_start: + offset = final_start - buffer_start + run_window(final_start, buffer[offset:]) + if any(frame is None for frame in selected): + raise AssertionError("offline stitching omitted a frame") + return self._concatenate([frame for frame in selected if frame is not None]) + + def stream_causal( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> Iterable[dict[str, torch.Tensor]]: + if self.config.mode != "causal": + raise ValueError("stream_causal requires mode='causal'") + rolling: list[Mapping[str, object]] = [] + for frame in frame_iterator: + rolling.append(frame) + if len(rolling) > self.config.window_size: + rolling.pop(0) + self.maximum_input_buffer_frames = max( + self.maximum_input_buffer_frames, len(rolling), + ) + output = self._run_window(rolling) + yield self._extract_frame(output, len(rolling) - 1, len(rolling)) + + def infer_causal( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> dict[str, torch.Tensor]: + return self._concatenate(list(self.stream_causal(frame_iterator))) + + def infer( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> dict[str, torch.Tensor]: + if self.config.mode == "offline": + return self.infer_offline(frame_iterator) + return self.infer_causal(frame_iterator) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/__init__.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9cc5c23a03b9059a0eee77e5bb43735d2c70fcb3 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/__init__.py @@ -0,0 +1,3 @@ +from foundation_hand.models.bimanual import BimanualReconstructionModel, ModelConfig + +__all__ = ["BimanualReconstructionModel", "ModelConfig"] diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/bimanual.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/bimanual.py new file mode 100644 index 0000000000000000000000000000000000000000..25095078c7f76f3c1f0987ca37b233e351645093 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/bimanual.py @@ -0,0 +1,1021 @@ +"""Unified RGB-D-K video bimanual reconstruction model.""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from pathlib import Path +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from foundation_hand.data.schema import input_availability +from foundation_hand.geometry.camera import patch_center_rays +from foundation_hand.geometry.mixed_projection import solve_mixed_projection_translation +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix +from foundation_hand.models.decoder import HandQueryDecoder +from foundation_hand.models.encoders import DepthGeometryEncoder, DinoV3Encoder, TinyPatchEncoder +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.models.structured_hand import ( + FINGER_PARTS, + PALM_PART, + ROOT_PART, + StructuredHandRefinement, +) + + +@dataclass +class ModelConfig: + encoder: str = "dinov3" + dinov3_source: str | None = None + dinov3_weights: str | None = None + dinov3_model: str = "dinov3_vitb16" + dinov3_dim: int = 768 + dinov3_trainable_last_blocks: int = 0 + decoder_dim: int = 512 + decoder_layers: int = 3 + attention_heads: int = 8 + patch_size: int = 16 + decoder_mode: str = "alternating" + use_temporal: bool = True + use_depth: bool = True + depth_mode: str = "log_depth" + use_rays: bool = True + use_bimanual_interaction: bool = True + depth_gate_floor: float = 0.0 + depth_gate_mode: str = "learned" + depth_gate_fixed_value: float = 0.5 + modality_dropout_prob: float = 0.0 + temporal_position_mode: str = "none" + temporal_relative_bias_max_distance: int = 15 + temporal_attention_mode: str = "bidirectional" + predict_presence: bool = True + mano_root: str | None = None + require_mano: bool = False + mano_fix_left_shapedirs: bool = False + gradient_checkpointing: bool = False + oracle_crop_mode: str = "none" + freeze_coarse_for_oracle_crop: bool = False + structured_hand_refinement: bool = False + structured_refinement_detach_locations: bool = True + structured_refinement_deterministic_detached_sampling: bool = False + structured_deformable_samples: int = 4 + structured_refine_translation: bool = True + translation_parameterization: str = "direct_xyz" + mixed_projection_minimum_support: int = 4 + mixed_projection_huber_delta_px: float = 16.0 + mixed_projection_irls_iterations: int = 5 + ray_depth_residual_max_m: float = 0.20 + ray_depth_enable_residual: bool = True + ray_depth_confidence_initial_logit: float = -4.0 + ray_depth_sample_radius_px: float = 8.0 + ray_depth_minimum_support: int = 3 + joint2d_parameterization: str = "hand_token_linear" + heatmap_offset_enabled: bool = True + heatmap_use_depth: bool = True + + +class BimanualReconstructionModel(nn.Module): + def __init__(self, config: ModelConfig) -> None: + super().__init__() + self.config = config + if not 0.0 <= config.modality_dropout_prob < 1.0: + raise ValueError("modality_dropout_prob must be in [0, 1)") + if config.oracle_crop_mode not in { + "none", "oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k", + }: + raise ValueError(f"unknown oracle crop mode: {config.oracle_crop_mode}") + if config.freeze_coarse_for_oracle_crop and config.oracle_crop_mode == "none": + raise ValueError("coarse freezing requires an oracle crop mode") + if config.structured_hand_refinement and config.oracle_crop_mode != "none": + raise ValueError("structured and oracle crop refinement are mutually exclusive") + if config.translation_parameterization not in { + "direct_xyz", "mixed_projection", "ray_depth_residual", + }: + raise ValueError( + f"unknown translation parameterization: {config.translation_parameterization}" + ) + if config.joint2d_parameterization not in { + "hand_token_linear", "spatial_heatmap", + }: + raise ValueError( + f"unknown joint2d parameterization: {config.joint2d_parameterization}" + ) + if ( + config.translation_parameterization in { + "mixed_projection", "ray_depth_residual", + } + and (config.structured_hand_refinement or config.oracle_crop_mode != "none") + ): + raise ValueError( + "mixed projection cannot be combined with an existing refinement branch" + ) + if config.ray_depth_residual_max_m <= 0.0: + raise ValueError("ray-depth residual bound must be positive") + if config.ray_depth_sample_radius_px <= 0.0: + raise ValueError("ray-depth sample radius must be positive") + if config.ray_depth_minimum_support <= 0: + raise ValueError("ray-depth minimum support must be positive") + if config.encoder == "dinov3": + if config.dinov3_source is None or config.dinov3_weights is None: + raise ValueError("Formal DINOv3 encoder requires explicit official source and local pretrained weights") + self.rgb_encoder = DinoV3Encoder( + Path(config.dinov3_source), Path(config.dinov3_weights), config.dinov3_model, + config.decoder_dim, config.dinov3_dim, frozen=True, + trainable_last_blocks=config.dinov3_trainable_last_blocks, + ) + elif config.encoder == "tiny_debug": + self.rgb_encoder = TinyPatchEncoder(config.decoder_dim, config.patch_size) + else: + raise ValueError(f"Unknown encoder: {config.encoder}") + if config.use_depth: + self.depth_encoder = DepthGeometryEncoder(config.decoder_dim, config.patch_size, config.depth_mode) + if config.use_rays: + self.ray_encoder = nn.Sequential(nn.Linear(4, config.decoder_dim), nn.GELU(), nn.Linear(config.decoder_dim, config.decoder_dim)) + self.hand_queries = nn.Parameter(torch.randn(2, config.decoder_dim) * 0.02) + self.side_embedding = nn.Parameter(torch.randn(2, config.decoder_dim) * 0.02) + self.decoder = HandQueryDecoder( + config.decoder_dim, config.decoder_layers, config.attention_heads, + config.use_depth, config.use_temporal, config.use_bimanual_interaction, config.decoder_mode, + config.gradient_checkpointing, config.depth_gate_floor, + config.depth_gate_mode, config.depth_gate_fixed_value, + config.temporal_position_mode, config.temporal_relative_bias_max_distance, + config.temporal_attention_mode, + ) + self.joint2d_head = nn.Linear(config.decoder_dim, 42) + if config.joint2d_parameterization == "spatial_heatmap": + dim = config.decoder_dim + self.joint_localization_embedding = nn.Parameter( + torch.randn(2, 21, dim) * 0.02, + ) + self.joint_localization_query = nn.Linear(dim, dim) + self.joint_localization_feature = nn.Sequential( + nn.LayerNorm(dim), nn.Linear(dim, dim), + ) + self.joint_localization_offset = nn.Sequential( + nn.LayerNorm(dim * 2), nn.Linear(dim * 2, 2), + ) + nn.init.zeros_(self.joint_localization_offset[-1].weight) + nn.init.zeros_(self.joint_localization_offset[-1].bias) + self.rotation_head = nn.Linear(config.decoder_dim, 16 * 6) + self.translation_head = nn.Linear(config.decoder_dim, 3) + if config.translation_parameterization == "mixed_projection": + self.mixed_log_tz_head = nn.Linear(config.decoder_dim, 1) + if config.translation_parameterization == "ray_depth_residual": + self.ray_depth_log_z_head = nn.Linear(config.decoder_dim, 1) + ray_depth_feature_dim = config.decoder_dim * 2 + 8 + self.ray_depth_delta_head = nn.Sequential( + nn.LayerNorm(ray_depth_feature_dim), + nn.Linear(ray_depth_feature_dim, config.decoder_dim), nn.GELU(), + nn.Linear(config.decoder_dim, 1), + ) + self.ray_depth_confidence_head = nn.Sequential( + nn.LayerNorm(ray_depth_feature_dim), + nn.Linear(ray_depth_feature_dim, config.decoder_dim), nn.GELU(), + nn.Linear(config.decoder_dim, 1), + ) + nn.init.zeros_(self.ray_depth_delta_head[-1].weight) + nn.init.zeros_(self.ray_depth_delta_head[-1].bias) + nn.init.zeros_(self.ray_depth_confidence_head[-1].weight) + self.ray_depth_confidence_head[-1].bias.data.fill_( + config.ray_depth_confidence_initial_logit, + ) + self.presence_head = nn.Linear(config.decoder_dim, 1) if config.predict_presence else None + self.shape_score = nn.Linear(config.decoder_dim, 1) + self.shape_head = nn.Linear(config.decoder_dim, 10) + self.mano_layer = ( + ManoCameraLayer( + config.mano_root, + fix_left_shapedirs=config.mano_fix_left_shapedirs, + ) + if config.mano_root is not None else None + ) + if config.require_mano and self.mano_layer is None: + raise ValueError("Formal camera-space MANO training requires a licensed mano_root") + self._initialize_structured_refiner() + self._initialize_oracle_crop_refiner() + self._initialize_prediction_heads() + if config.translation_parameterization == "mixed_projection": + # Retained only as a frozen missing-K/invalid-solve teacher fallback. + for parameter in self.translation_head.parameters(): + parameter.requires_grad_(False) + if config.joint2d_parameterization == "spatial_heatmap": + for parameter in self.joint2d_head.parameters(): + parameter.requires_grad_(False) + if config.freeze_coarse_for_oracle_crop: + for name, parameter in self.named_parameters(): + if not name.startswith("oracle_crop_"): + parameter.requires_grad_(False) + + def _initialize_oracle_crop_refiner(self) -> None: + mode = self.config.oracle_crop_mode + if mode == "none": + return + use_rgb = mode in {"oracle_rgb", "oracle_rgb_depth_k"} + use_depth = mode in {"oracle_depth_k", "oracle_rgb_depth_k"} + if use_depth and not self.config.use_depth: + raise ValueError("oracle Depth+K refinement requires the coarse depth encoder") + feature_dim = self.config.decoder_dim * (1 + int(use_rgb) + int(use_depth)) + feature_dim += int(use_rgb) + int(use_depth) + if use_depth: + feature_dim += 4 + self.oracle_crop_fusion = nn.Sequential( + nn.LayerNorm(feature_dim), + nn.Linear(feature_dim, self.config.decoder_dim), + nn.GELU(), + nn.Linear(self.config.decoder_dim, self.config.decoder_dim), + nn.GELU(), + ) + if use_rgb: + self.oracle_crop_rotation_head = nn.Linear( + self.config.decoder_dim, 16 * 3, + ) + self.oracle_crop_shape_head = nn.Linear(self.config.decoder_dim, 10) + nn.init.zeros_(self.oracle_crop_rotation_head.weight) + nn.init.zeros_(self.oracle_crop_rotation_head.bias) + nn.init.zeros_(self.oracle_crop_shape_head.weight) + nn.init.zeros_(self.oracle_crop_shape_head.bias) + if use_depth: + self.oracle_crop_delta_z_head = nn.Linear(self.config.decoder_dim, 1) + nn.init.zeros_(self.oracle_crop_delta_z_head.weight) + nn.init.zeros_(self.oracle_crop_delta_z_head.bias) + + def _initialize_structured_refiner(self) -> None: + if not self.config.structured_hand_refinement: + return + dim = self.config.decoder_dim + self.structured_refiner = StructuredHandRefinement( + dim, self.config.attention_heads, use_depth=self.config.use_depth, + samples=self.config.structured_deformable_samples, + ) + self.structured_root_orientation_head = nn.Linear(dim, 3) + self.structured_finger_rotation_head = nn.Linear(dim, 3 * 3) + self.structured_translation_head = nn.Linear(dim, 3) + self.structured_shape_head = nn.Linear(dim, 10) + self.structured_root_2d_head = nn.Linear(dim, 2) + self.structured_finger_2d_head = nn.Linear(dim, 4 * 2) + for head in ( + self.structured_root_orientation_head, + self.structured_finger_rotation_head, + self.structured_translation_head, + self.structured_shape_head, + self.structured_root_2d_head, + self.structured_finger_2d_head, + ): + nn.init.zeros_(head.weight) + nn.init.zeros_(head.bias) + + def _initialize_prediction_heads(self) -> None: + """Start metric heads from finite, physically valid neutral predictions.""" + + identity_6d = torch.tensor((1.0, 0.0, 0.0, 0.0, 1.0, 0.0)) + with torch.no_grad(): + nn.init.zeros_(self.joint2d_head.weight) + nn.init.zeros_(self.joint2d_head.bias) + nn.init.zeros_(self.rotation_head.weight) + self.rotation_head.bias.copy_(identity_6d.repeat(16)) + nn.init.zeros_(self.translation_head.weight) + # softplus(inverse_softplus(0.6)) starts the wrist at z=0.6 m. + self.translation_head.bias.copy_(torch.tensor((0.0, 0.0, -0.19587037))) + if self.config.translation_parameterization == "mixed_projection": + nn.init.zeros_(self.mixed_log_tz_head.weight) + self.mixed_log_tz_head.bias.fill_(torch.log(torch.tensor(0.6))) + if self.config.translation_parameterization == "ray_depth_residual": + nn.init.zeros_(self.ray_depth_log_z_head.weight) + self.ray_depth_log_z_head.bias.fill_(torch.log(torch.tensor(0.6))) + nn.init.zeros_(self.shape_head.weight) + nn.init.zeros_(self.shape_head.bias) + if self.presence_head is not None: + nn.init.zeros_(self.presence_head.weight) + nn.init.zeros_(self.presence_head.bias) + + def forward(self, batch: dict[str, torch.Tensor]) -> dict[str, Any]: + rgb = batch["rgb"] + if rgb.ndim != 5: + raise ValueError(f"Expected RGB [B,T,3,H,W], got {rgb.shape}") + batch_size, time, _, height, width = rgb.shape + frame_valid = batch["frame_valid"].bool() + features = self.rgb_encoder(rgb.reshape(batch_size * time, 3, height, width)) + tokens = features.tokens + if "K" in batch: + K = batch["K"].reshape(batch_size * time, 3, 3).to(tokens.dtype) + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ).reshape(batch_size * time) + else: + K = torch.eye(3, dtype=tokens.dtype, device=tokens.device)[None].expand(batch_size * time, -1, -1) + K_available = torch.zeros(batch_size * time, dtype=torch.bool, device=tokens.device) + if self.training and self.config.modality_dropout_prob > 0.0 and self.config.use_rays: + keep_probability = 1.0 - self.config.modality_dropout_prob + K_available = K_available & ( + torch.rand(K_available.shape, device=K_available.device) < keep_probability + ) + if self.config.use_rays: + rays = patch_center_rays(K, features.grid_hw, features.patch_size) + availability = K_available.reshape(-1, 1, 1) + ray_inputs = torch.cat((rays, availability.expand(-1, rays.shape[1], 1).to(rays.dtype)), dim=-1) + tokens = tokens + self.ray_encoder(ray_inputs) * availability.to(tokens.dtype) + rgb_tokens = tokens.reshape(batch_size, time, tokens.shape[1], tokens.shape[2]) + + depth_tokens = None + depth_available = input_availability( + batch, + "depth_input_available", + "depth_available", + torch.zeros( + (batch_size, time), device=rgb.device, dtype=torch.bool, + ), + ) & frame_valid + # Training-only independent modality dropout tests fallback robustness without + # mutating the dataset availability contract or validation behavior. + if self.training and self.config.modality_dropout_prob > 0.0: + keep_probability = 1.0 - self.config.modality_dropout_prob + if self.config.use_depth: + depth_available = depth_available & ( + torch.rand(depth_available.shape, device=depth_available.device) < keep_probability + ) + if self.config.use_depth: + depth_m = batch.get("depth_m") + depth_pixel_valid = batch.get("depth_pixel_valid") + if depth_m is None or depth_pixel_valid is None: + depth_m = torch.zeros((batch_size, time, 1, height, width), dtype=rgb.dtype, device=rgb.device) + depth_pixel_valid = torch.zeros_like(depth_m, dtype=torch.bool) + depth_available = torch.zeros_like(frame_valid) + if self.config.depth_mode == "geometry": + depth_available = depth_available & K_available.reshape(batch_size, time) + depth_features = self.depth_encoder( + depth_m.reshape(batch_size * time, 1, height, width).to(tokens.dtype), + depth_pixel_valid.reshape(batch_size * time, 1, height, width), K, + ) + if depth_features.grid_hw != features.grid_hw: + raise ValueError(f"RGB/depth patch grids differ: {features.grid_hw} vs {depth_features.grid_hw}") + depth_tokens = depth_features.tokens.reshape(batch_size, time, depth_features.tokens.shape[1], depth_features.tokens.shape[2]) + + initial_query = ( + self.hand_queries + self.side_embedding + )[None, None].expand(batch_size, time, -1, -1) + rgb_only_query = None + rgb_only_attention = None + if self.config.translation_parameterization == "ray_depth_residual": + rgb_only_query, rgb_only_attention = self.decoder( + initial_query, rgb_tokens, None, frame_valid, + torch.zeros_like(depth_available), self.side_embedding[None], + ) + query, attention = self.decoder( + initial_query, rgb_tokens, depth_tokens, frame_valid, + depth_available, self.side_embedding[None], + ) + linear_joint2d_norm = torch.sigmoid( + self.joint2d_head(query).reshape(batch_size, time, 2, 21, 2) + ) + joint2d_output: dict[str, torch.Tensor] = {} + if self.config.joint2d_parameterization == "spatial_heatmap": + joint2d_norm, joint2d_output = self._spatial_joint2d( + query, rgb_tokens, depth_tokens, depth_available, + features.grid_hw, + ) + joint2d_output["joint2d_linear_teacher_norm"] = linear_joint2d_norm.detach() + else: + joint2d_norm = linear_joint2d_norm + rotations_6d = self.rotation_head(query).reshape(batch_size, time, 2, 16, 6) + translation_token = rgb_only_query if rgb_only_query is not None else query + translation_raw = self.translation_head(translation_token) + wrist_translation = torch.cat( + (translation_raw[..., :2], F.softplus(translation_raw[..., 2:3]) + 1e-4), dim=-1 + ) + + score = self.shape_score(query).squeeze(-1).masked_fill(~frame_valid[:, :, None], -torch.inf) + shape_weights = torch.softmax(score, dim=1) + pooled = (query * shape_weights[..., None]).sum(dim=1) + shape = self.shape_head(pooled) + rotation_matrices = rotation_6d_to_matrix(rotations_6d) + shape_sequence = shape + expanded_shape = shape[:, None].expand(-1, time, -1, -1) + refined_translation = wrist_translation + mixed_projection_output: dict[str, torch.Tensor] = {} + if self.config.translation_parameterization == "mixed_projection": + refined_translation, mixed_projection_output = self._apply_mixed_projection( + batch, query, joint2d_norm, rotation_matrices, expanded_shape, + wrist_translation, frame_valid, height=height, width=width, + ) + ray_depth_output: dict[str, torch.Tensor] = {} + if self.config.translation_parameterization == "ray_depth_residual": + if rgb_only_query is None: + raise RuntimeError("ray-depth translation requires an RGB-only query") + refined_translation, ray_depth_output = self._apply_ray_depth_translation( + batch, rgb_only_query, query, wrist_translation, frame_valid, + depth_available, height=height, width=width, + ) + ray_depth_output["rgb_only_translation_attention"] = rgb_only_attention + structured_output: dict[str, torch.Tensor] = {} + if self.config.structured_hand_refinement: + ( + joint2d_norm, rotation_matrices, shape_sequence, + expanded_shape, refined_translation, structured_output, + ) = self._apply_structured_refinement( + query, joint2d_norm, rgb_tokens, depth_tokens, features.grid_hw, + frame_valid, depth_available, rotation_matrices, shape, + expanded_shape, wrist_translation, shape_weights, + ) + oracle_output: dict[str, torch.Tensor] = {} + if self.config.oracle_crop_mode != "none": + rotation_matrices, shape_sequence, expanded_shape, refined_translation, oracle_output = ( + self._apply_oracle_crop_refinement( + batch, query, rotation_matrices, shape, expanded_shape, + wrist_translation, shape_weights, frame_valid, + depth_available, + ) + ) + output: dict[str, Any] = { + "hand_tokens": query, + "joint2d_norm": joint2d_norm, + "mano_rotations_6d": rotations_6d, + "mano_rotation_matrices": rotation_matrices, + "mano_shape_sequence": shape_sequence, + "mano_shape": expanded_shape, + "wrist_root_translation": refined_translation, + "shape_pool_weights": shape_weights, + "attention": attention, + "translation_parameterization": self.config.translation_parameterization, + "joint2d_parameterization": self.config.joint2d_parameterization, + **joint2d_output, + **mixed_projection_output, + **ray_depth_output, + **structured_output, + **oracle_output, + } + if self.presence_head is not None: + output["presence_logit"] = self.presence_head(query).squeeze(-1) + if self.mano_layer is not None: + if self.config.oracle_crop_mode != "none": + coarse_vertices, coarse_joints = self.mano_layer( + output["coarse_mano_rotation_matrices"], + output["coarse_mano_shape"], + output["coarse_wrist_root_translation"], + ) + output["coarse_vertices_camera"] = coarse_vertices + output["coarse_joints_camera"] = coarse_joints + vertices, joints = self.mano_layer( + output["mano_rotation_matrices"], output["mano_shape"], output["wrist_root_translation"] + ) + output["vertices_camera"] = vertices + output["joints_camera"] = joints + return output + + def _spatial_joint2d( + self, + hand_tokens: torch.Tensor, + rgb_tokens: torch.Tensor, + depth_tokens: torch.Tensor | None, + depth_available: torch.Tensor, + grid_hw: tuple[int, int], + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + spatial = rgb_tokens + if self.config.heatmap_use_depth and depth_tokens is not None: + spatial = spatial + 0.5 * depth_tokens * depth_available[ + :, :, None, None + ].to(depth_tokens.dtype) + spatial = self.joint_localization_feature(spatial) + joint_query = self.joint_localization_query(hand_tokens)[..., None, :] + joint_query = joint_query + self.joint_localization_embedding[None, None] + logits = torch.einsum( + "bthjd,btsd->bthjs", joint_query, spatial, + ) / (spatial.shape[-1] ** 0.5) + probability_float = torch.softmax(logits.float(), dim=-1) + probabilities = probability_float.to(spatial.dtype) + grid_height, grid_width = grid_hw + if grid_height * grid_width != spatial.shape[-2]: + raise ValueError("joint heatmap grid differs from encoded feature grid") + rows, columns = torch.meshgrid( + torch.arange(grid_height, device=spatial.device), + torch.arange(grid_width, device=spatial.device), indexing="ij", + ) + centers = torch.stack(( + (columns.reshape(-1) + 0.5) / grid_width, + (rows.reshape(-1) + 0.5) / grid_height, + ), dim=-1).to(dtype=probability_float.dtype) + coordinates = torch.einsum("bthjs,sd->bthjd", probability_float, centers) + pooled = torch.einsum("bthjs,btsd->bthjd", probabilities, spatial) + raw_offset = self.joint_localization_offset(torch.cat((joint_query, pooled), dim=-1)) + patch_scale = raw_offset.new_tensor((1.0 / grid_width, 1.0 / grid_height)) + offset = ( + torch.tanh(raw_offset) * patch_scale + if self.config.heatmap_offset_enabled else torch.zeros_like(raw_offset) + ) + coordinates = (coordinates + offset).clamp(0.0, 1.0) + probability_float = probability_float.clamp_min(1e-12) + entropy = -( + probability_float * probability_float.log() + ).sum(dim=-1) / math.log(float(spatial.shape[-2])) + return coordinates, { + "joint2d_heatmap_logits": logits, + "joint2d_heatmap_entropy": entropy, + "joint2d_heatmap_confidence": 1.0 - entropy, + "joint2d_heatmap_offset_norm": offset, + } + + def initialize_mixed_log_tz_from_direct_head( + self, reference_raw: float = -0.19587037, + ) -> None: + """Linearize log(softplus(x)) around the historical 0.6 m prior.""" + + if self.config.translation_parameterization != "mixed_projection": + raise RuntimeError("mixed log-tz initialization requires mixed projection") + reference = self.translation_head.bias.new_tensor(reference_raw) + reference_depth = F.softplus(reference) + 1e-4 + slope = torch.sigmoid(reference) / reference_depth + with torch.no_grad(): + self.mixed_log_tz_head.weight.copy_( + slope * self.translation_head.weight[2:3] + ) + self.mixed_log_tz_head.bias.copy_( + torch.log(reference_depth) + + slope * (self.translation_head.bias[2:3] - reference) + ) + + def initialize_ray_depth_from_direct_head( + self, reference_raw: float = -0.19587037, + ) -> None: + """Warm-start RGB base-z while retaining the direct no-K fallback.""" + + if self.config.translation_parameterization != "ray_depth_residual": + raise RuntimeError("ray-depth initialization requires ray_depth_residual") + reference = self.translation_head.bias.new_tensor(reference_raw) + reference_depth = F.softplus(reference) + 1e-4 + slope = torch.sigmoid(reference) / reference_depth + with torch.no_grad(): + self.ray_depth_log_z_head.weight.copy_( + slope * self.translation_head.weight[2:3] + ) + self.ray_depth_log_z_head.bias.copy_( + torch.log(reference_depth) + + slope * (self.translation_head.bias[2:3] - reference) + ) + + def _sample_local_depth_statistics( + self, + batch: dict[str, torch.Tensor], + wrist_norm: torch.Tensor, + base_z: torch.Tensor, + available: torch.Tensor, + *, + height: int, + width: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Sample a deterministic 3x3 metric-depth stencil at predicted wrists.""" + + batch_size, time, hands = wrist_norm.shape[:3] + depth = batch.get("depth_m") + valid_image = batch.get("depth_pixel_valid") + if depth is None or valid_image is None: + statistics = base_z.new_zeros(batch_size, time, hands, 8) + support = torch.zeros_like(base_z, dtype=torch.long) + return statistics, support + radius = float(self.config.ray_depth_sample_radius_px) + offsets = wrist_norm.new_tensor([ + (-radius, -radius), (0.0, -radius), (radius, -radius), + (-radius, 0.0), (0.0, 0.0), (radius, 0.0), + (-radius, radius), (0.0, radius), (radius, radius), + ]) + offset_norm = offsets * offsets.new_tensor((2.0 / width, 2.0 / height)) + grid = wrist_norm[..., None, :] * 2.0 - 1.0 + offset_norm + in_frame = (grid.abs() <= 1.0).all(dim=-1) + grid = grid.reshape(batch_size * time, hands * 9, 1, 2).float() + sampled_depth = F.grid_sample( + depth.reshape(batch_size * time, 1, height, width).float(), + grid, mode="nearest", padding_mode="zeros", align_corners=False, + ).reshape(batch_size, time, hands, 9) + sampled_valid = F.grid_sample( + valid_image.reshape(batch_size * time, 1, height, width).float(), + grid, mode="nearest", padding_mode="zeros", align_corners=False, + ).reshape(batch_size, time, hands, 9) > 0.5 + valid = ( + sampled_valid & in_frame & available[..., None, None] + & torch.isfinite(sampled_depth) & (sampled_depth > 0.02) + & (sampled_depth < 3.0) + ) + support = valid.sum(dim=-1) + safe = torch.where(valid, sampled_depth, torch.zeros_like(sampled_depth)) + denominator = support.clamp_min(1).to(base_z.dtype) + mean = safe.sum(dim=-1) / denominator + variance = ( + torch.where(valid, (sampled_depth - mean[..., None]).square(), + torch.zeros_like(sampled_depth)).sum(dim=-1) + / denominator + ) + nan_values = torch.where( + valid, sampled_depth, + torch.full_like(sampled_depth, float("nan")), + ) + median = torch.nanmedian(nan_values, dim=-1).values + minimum = torch.where( + valid, sampled_depth, torch.full_like(sampled_depth, float("inf")), + ).min(dim=-1).values + maximum = torch.where( + valid, sampled_depth, torch.full_like(sampled_depth, float("-inf")), + ).max(dim=-1).values + any_valid = support > 0 + median = torch.where(any_valid, median, torch.zeros_like(median)) + minimum = torch.where(any_valid, minimum, torch.zeros_like(minimum)) + maximum = torch.where(any_valid, maximum, torch.zeros_like(maximum)) + statistics = torch.stack(( + support.to(base_z.dtype) / 9.0, + median, median - base_z, minimum, maximum, + maximum - minimum, mean, variance.clamp_min(0.0).sqrt(), + ), dim=-1).to(base_z.dtype) + return statistics, support + + def _apply_ray_depth_translation( + self, + batch: dict[str, torch.Tensor], + rgb_query: torch.Tensor, + fused_query: torch.Tensor, + direct_fallback: torch.Tensor, + frame_valid: torch.Tensor, + depth_available: torch.Tensor, + *, + height: int, + width: int, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + wrist_norm = torch.sigmoid( + self.joint2d_head(rgb_query).reshape(*rgb_query.shape[:3], 21, 2) + )[..., 0, :] + log_base_z = self.ray_depth_log_z_head(rgb_query).squeeze(-1).clamp(-3.0, 1.0) + base_z = torch.exp(log_base_z) + if "K" in batch: + K = batch["K"].to(rgb_query.dtype) + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ) & frame_valid + else: + K = torch.eye( + 3, dtype=rgb_query.dtype, device=rgb_query.device, + )[None, None].expand(*frame_valid.shape, -1, -1) + K_available = torch.zeros_like(frame_valid) + usable_depth = depth_available & K_available + statistics, support = self._sample_local_depth_statistics( + batch, wrist_norm, base_z, usable_depth, + height=height, width=width, + ) + features = torch.cat((rgb_query, fused_query - rgb_query, statistics), dim=-1) + raw_delta = float(self.config.ray_depth_residual_max_m) * torch.tanh( + self.ray_depth_delta_head(features).squeeze(-1) + ) + confidence_logit = self.ray_depth_confidence_head(features).squeeze(-1) + correction_valid = ( + usable_depth[:, :, None] + & (support >= int(self.config.ray_depth_minimum_support)) + ) + if not self.config.ray_depth_enable_residual: + correction_valid = torch.zeros_like(correction_valid) + confidence = torch.where( + correction_valid, torch.sigmoid(confidence_logit), + torch.zeros_like(confidence_logit), + ) + delta = torch.where(correction_valid, raw_delta, torch.zeros_like(raw_delta)) + refined_z = (base_z + confidence * delta).clamp(0.05, 3.0) + u = wrist_norm[..., 0] * float(width) + v = wrist_norm[..., 1] * float(height) + fx = K[..., 0, 0][:, :, None].clamp_min(1e-6) + fy = K[..., 1, 1][:, :, None].clamp_min(1e-6) + cx = K[..., 0, 2][:, :, None] + cy = K[..., 1, 2][:, :, None] + ray_x = (u - cx) / fx + ray_y = (v - cy) / fy + assembled = torch.stack((ray_x * refined_z, ray_y * refined_z, refined_z), dim=-1) + use_ray = K_available[:, :, None, None] & frame_valid[:, :, None, None] + translation = torch.where(use_ray, assembled, direct_fallback) + translation = torch.where( + frame_valid[:, :, None, None], translation, + torch.zeros_like(translation), + ) + return translation, { + "ray_depth_wrist2d_norm": wrist_norm, + "ray_depth_log_base_z": log_base_z, + "ray_depth_base_z_m": base_z, + "ray_depth_raw_delta_z_m": delta, + "ray_depth_applied_delta_z_m": confidence * delta, + "ray_depth_confidence_logit": confidence_logit, + "ray_depth_confidence": confidence, + "ray_depth_local_statistics": statistics, + "ray_depth_support_count": support, + "ray_depth_correction_valid": correction_valid, + "ray_depth_K_input_available": K_available, + "ray_depth_direct_fallback_translation": direct_fallback, + } + + def _apply_mixed_projection( + self, + batch: dict[str, torch.Tensor], + hand_tokens: torch.Tensor, + joint2d_norm: torch.Tensor, + rotation_matrices: torch.Tensor, + expanded_shape: torch.Tensor, + direct_translation: torch.Tensor, + frame_valid: torch.Tensor, + *, + height: int, + width: int, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + if self.mano_layer is None: + raise RuntimeError("mixed projection requires the MANO camera layer") + log_tz = self.mixed_log_tz_head(hand_tokens).squeeze(-1).clamp(-3.0, 1.0) + tz = torch.exp(log_tz) + zero_translation = torch.zeros_like(direct_translation) + _, canonical_joints = self.mano_layer( + rotation_matrices, expanded_shape, zero_translation, + ) + root_relative_joints = canonical_joints - canonical_joints[..., :1, :] + anchors_px = joint2d_norm * joint2d_norm.new_tensor((width, height)) + if "K" in batch: + K = batch["K"].to(joint2d_norm.dtype) + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ) & frame_valid + else: + K = torch.eye( + 3, dtype=joint2d_norm.dtype, device=joint2d_norm.device, + )[None, None].expand(*frame_valid.shape, -1, -1) + K_available = torch.zeros_like(frame_valid) + K = K[:, :, None].expand(-1, -1, 2, -1, -1) + K_available = K_available[:, :, None].expand(-1, -1, 2) + result = solve_mixed_projection_translation( + root_relative_joints, anchors_px, K, tz, direct_translation, + image_hw=(height, width), K_available=K_available, + minimum_support=self.config.mixed_projection_minimum_support, + huber_delta_px=self.config.mixed_projection_huber_delta_px, + irls_iterations=self.config.mixed_projection_irls_iterations, + ) + translation = torch.where( + frame_valid[:, :, None, None], + result.translation_m, + torch.zeros_like(result.translation_m), + ) + return translation, { + "mixed_projection_log_tz": log_tz, + "mixed_projection_direct_teacher_translation": direct_translation.detach(), + "mixed_projection_support_count": result.support_count, + "mixed_projection_residual_scale_px": result.residual_scale_px, + "mixed_projection_conditioning": result.conditioning, + "mixed_projection_inlier_ratio": result.inlier_ratio, + "mixed_projection_uncertainty_xy_m": result.uncertainty_xy_m, + "mixed_projection_success": result.success, + } + + def _apply_structured_refinement( + self, + coarse_hand_tokens: torch.Tensor, + coarse_joint2d_norm: torch.Tensor, + rgb_tokens: torch.Tensor, + depth_tokens: torch.Tensor | None, + grid_hw: tuple[int, int], + frame_valid: torch.Tensor, + depth_available: torch.Tensor, + coarse_rotations: torch.Tensor, + coarse_shape_sequence: torch.Tensor, + coarse_shape: torch.Tensor, + coarse_translation: torch.Tensor, + shape_pool_weights: torch.Tensor, + ) -> tuple[ + torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, + dict[str, torch.Tensor], + ]: + part_tokens, diagnostics = self.structured_refiner( + coarse_hand_tokens, coarse_joint2d_norm, rgb_tokens, depth_tokens, + grid_hw, frame_valid, depth_available, + detach_locations=self.config.structured_refinement_detach_locations, + deterministic_detached_sampling=( + self.config.structured_refinement_deterministic_detached_sampling + ), + ) + root_token = part_tokens[..., ROOT_PART, :] + palm_token = part_tokens[..., PALM_PART, :] + finger_tokens = part_tokens[..., FINGER_PARTS, :] + + root_rotation_delta = self._bounded_axis_angle( + self.structured_root_orientation_head(root_token), + ) + finger_rotation_delta = self._bounded_axis_angle( + self.structured_finger_rotation_head(finger_tokens).reshape( + *finger_tokens.shape[:-1], 3, 3, + ) + ) + rotation_delta = torch.cat(( + root_rotation_delta[..., None, :], + finger_rotation_delta.reshape(*finger_rotation_delta.shape[:3], 15, 3), + ), dim=-2) + rotation_delta = rotation_delta * frame_valid[ + :, :, None, None, None + ].to(rotation_delta.dtype) + refined_rotations = self._compose_rotation_residual( + coarse_rotations, rotation_delta, + ) + + if self.config.structured_refine_translation: + translation_raw = self.structured_translation_head(root_token) + translation_scale = torch.tensor( + (0.05, 0.05, 0.12), dtype=translation_raw.dtype, + device=translation_raw.device, + ) + translation_delta = translation_scale * translation_raw / torch.sqrt( + 1.0 + translation_raw.square(), + ) + translation_delta = translation_delta * frame_valid[ + :, :, None, None + ].to(translation_delta.dtype) + else: + translation_delta = torch.zeros_like(coarse_translation) + refined_translation = coarse_translation + translation_delta + + raw_shape_delta = torch.tanh(self.structured_shape_head(palm_token)) + shape_delta = ( + raw_shape_delta * shape_pool_weights[..., None] + ).sum(dim=1) + refined_shape_sequence = coarse_shape_sequence + shape_delta + refined_shape = coarse_shape + shape_delta[:, None] + + joint2d_delta = torch.zeros_like(coarse_joint2d_norm) + joint2d_delta[..., 0, :] = self.structured_root_2d_head(root_token) + joint2d_delta[..., 1:, :] = self.structured_finger_2d_head( + finger_tokens, + ).reshape(*finger_tokens.shape[:3], 20, 2) + joint2d_delta = 0.1 * torch.tanh(joint2d_delta) + joint2d_delta = joint2d_delta * frame_valid[ + :, :, None, None, None + ].to(joint2d_delta.dtype) + refined_joint2d = (coarse_joint2d_norm + joint2d_delta).clamp(0.0, 1.0) + return ( + refined_joint2d, refined_rotations, refined_shape_sequence, + refined_shape, refined_translation, + { + "coarse_joint2d_norm": coarse_joint2d_norm, + "coarse_mano_rotation_matrices": coarse_rotations, + "coarse_mano_shape_sequence": coarse_shape_sequence, + "coarse_mano_shape": coarse_shape, + "coarse_wrist_root_translation": coarse_translation, + "structured_part_tokens": part_tokens, + "structured_rotation_delta_axis_angle": rotation_delta, + "structured_translation_delta": translation_delta, + "structured_shape_delta": shape_delta, + "structured_joint2d_delta": joint2d_delta, + **diagnostics, + }, + ) + + @staticmethod + def _bounded_axis_angle(raw: torch.Tensor, maximum_radians: float = 0.35) -> torch.Tensor: + denominator = torch.sqrt(1.0 + (raw * raw).sum(dim=-1, keepdim=True)) + return maximum_radians * raw / denominator + + @staticmethod + def _compose_rotation_residual( + coarse: torch.Tensor, delta_axis_angle: torch.Tensor, + ) -> torch.Tensor: + delta_matrix = axis_angle_to_matrix(delta_axis_angle) + identity = torch.eye( + 3, dtype=delta_matrix.dtype, device=delta_matrix.device, + ) + # This is algebraically coarse @ delta_matrix, but its zero-residual + # path is coarse + coarse @ 0. Direct BF16 coarse @ I can re-round the + # coarse matrix and violate the registered exact initialization gate. + return coarse + coarse @ (delta_matrix - identity) + + def _apply_oracle_crop_refinement( + self, + batch: dict[str, torch.Tensor], + coarse_hand_tokens: torch.Tensor, + coarse_rotations: torch.Tensor, + coarse_shape_sequence: torch.Tensor, + coarse_shape: torch.Tensor, + coarse_translation: torch.Tensor, + shape_pool_weights: torch.Tensor, + frame_valid: torch.Tensor, + coarse_depth_available: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]: + required = {"oracle_crop_available"} + mode = self.config.oracle_crop_mode + use_rgb = mode in {"oracle_rgb", "oracle_rgb_depth_k"} + use_depth = mode in {"oracle_depth_k", "oracle_rgb_depth_k"} + if use_rgb: + required.add("oracle_crop_rgb") + if use_depth: + required.update({ + "oracle_crop_depth_m", "oracle_crop_depth_pixel_valid", + "oracle_crop_depth_available", "oracle_crop_K", + }) + missing = sorted(required - batch.keys()) + if missing: + raise ValueError(f"oracle crop mode requires batch fields: {missing}") + + batch_size, time, hands, dim = coarse_hand_tokens.shape + if hands != 2: + raise ValueError("oracle crop refinement expects two hand tokens") + roi_available = batch["oracle_crop_available"].bool() & frame_valid[:, :, None] + parts = [coarse_hand_tokens] + availability_parts = [] + rgb_available = roi_available if use_rgb else torch.zeros_like(roi_available) + if use_rgb: + local_rgb = batch["oracle_crop_rgb"] + if local_rgb.shape[:3] != (batch_size, time, hands): + raise ValueError(f"unexpected oracle RGB crop shape: {local_rgb.shape}") + local_hw = local_rgb.shape[-2:] + rgb_features = self.rgb_encoder( + local_rgb.reshape(batch_size * time * hands, 3, *local_hw), + ) + rgb_token = rgb_features.tokens.mean(dim=1).reshape( + batch_size, time, hands, dim, + ) + parts.append(rgb_token * rgb_available[..., None].to(rgb_token.dtype)) + availability_parts.append(rgb_available[..., None].to(rgb_token.dtype)) + + depth_available = torch.zeros_like(roi_available) + if use_depth: + local_depth = batch["oracle_crop_depth_m"] + local_valid = batch["oracle_crop_depth_pixel_valid"].bool() + local_K = batch["oracle_crop_K"].to(coarse_hand_tokens.dtype) + local_hw = local_depth.shape[-2:] + expected_prefix = (batch_size, time, hands) + if local_depth.shape[:3] != expected_prefix or local_K.shape[:3] != expected_prefix: + raise ValueError("unexpected oracle depth/K crop shape") + depth_available = ( + batch["oracle_crop_depth_available"].bool() + & roi_available + & coarse_depth_available[:, :, None] + ) + identity_K = torch.eye( + 3, dtype=local_K.dtype, device=local_K.device, + ).expand_as(local_K) + safe_local_K = torch.where( + depth_available[..., None, None], local_K, identity_K, + ) + depth_features = self.depth_encoder( + local_depth.reshape(batch_size * time * hands, 1, *local_hw).to(coarse_hand_tokens.dtype), + local_valid.reshape(batch_size * time * hands, 1, *local_hw), + safe_local_K.reshape(batch_size * time * hands, 3, 3), + ) + depth_token = depth_features.tokens.mean(dim=1).reshape( + batch_size, time, hands, dim, + ) + parts.append(depth_token * depth_available[..., None].to(depth_token.dtype)) + normalized_K = torch.stack(( + safe_local_K[..., 0, 0] / local_hw[1], + safe_local_K[..., 1, 1] / local_hw[0], + safe_local_K[..., 0, 2] / local_hw[1], + safe_local_K[..., 1, 2] / local_hw[0], + ), dim=-1) + parts.append(normalized_K * depth_available[..., None].to(normalized_K.dtype)) + availability_parts.append(depth_available[..., None].to(depth_token.dtype)) + parts.extend(availability_parts) + fused = self.oracle_crop_fusion(torch.cat(parts, dim=-1)) + + refined_rotations = coarse_rotations + refined_shape_sequence = coarse_shape_sequence + refined_shape = coarse_shape + rotation_delta = torch.zeros( + (*coarse_rotations.shape[:-2], 3), + dtype=coarse_rotations.dtype, device=coarse_rotations.device, + ) + shape_delta = torch.zeros_like(coarse_shape_sequence) + if use_rgb: + raw_rotation = self.oracle_crop_rotation_head(fused).reshape( + batch_size, time, hands, 16, 3, + ) + rotation_delta = self._bounded_axis_angle(raw_rotation) + rotation_delta = rotation_delta * rgb_available[..., None, None].to(rotation_delta.dtype) + refined_rotations = self._compose_rotation_residual( + coarse_rotations, rotation_delta, + ) + raw_shape = torch.tanh(self.oracle_crop_shape_head(fused)) + weights = shape_pool_weights * rgb_available.to(shape_pool_weights.dtype) + weights = weights / weights.sum(dim=1, keepdim=True).clamp_min(1e-8) + shape_delta = (raw_shape * weights[..., None]).sum(dim=1) + shape_delta = shape_delta * rgb_available.any(dim=1)[..., None].to(shape_delta.dtype) + refined_shape_sequence = coarse_shape_sequence + shape_delta + refined_shape = refined_shape_sequence[:, None].expand(-1, time, -1, -1) + + delta_z = torch.zeros_like(coarse_translation[..., 2:3]) + if use_depth: + delta_z = 0.15 * torch.tanh(self.oracle_crop_delta_z_head(fused)) + delta_z = delta_z * depth_available[..., None].to(delta_z.dtype) + refined_translation = coarse_translation + torch.cat( + (torch.zeros_like(coarse_translation[..., :2]), delta_z), dim=-1, + ) + return ( + refined_rotations, + refined_shape_sequence, + refined_shape, + refined_translation, + { + "coarse_mano_rotation_matrices": coarse_rotations, + "coarse_mano_shape_sequence": coarse_shape_sequence, + "coarse_mano_shape": coarse_shape, + "coarse_wrist_root_translation": coarse_translation, + "oracle_crop_rotation_delta_axis_angle": rotation_delta, + "oracle_crop_shape_delta": shape_delta, + "oracle_crop_delta_z": delta_z, + "oracle_crop_rgb_available": rgb_available, + "oracle_crop_depth_available_effective": depth_available, + }, + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/decoder.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..2031cad4d2a5790f82da07dec1958f33f6153c71 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/decoder.py @@ -0,0 +1,267 @@ +"""Factorized spatial-temporal semantic hand-query decoder.""" + +from __future__ import annotations + +from typing import Any + +import torch +from torch import nn +from torch.utils.checkpoint import checkpoint + + +class SpatialUpdate(nn.Module): + def __init__( + self, + dim: int, + heads: int, + use_depth: bool, + use_bimanual: bool, + depth_gate_floor: float, + depth_gate_mode: str, + depth_gate_fixed_value: float, + ) -> None: + super().__init__() + self.query_norm = nn.LayerNorm(dim) + self.rgb_norm = nn.LayerNorm(dim) + self.rgb_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.use_bimanual = use_bimanual + if use_bimanual: + self.hand_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.use_depth = use_depth + if not 0.0 <= depth_gate_floor < 1.0: + raise ValueError(f"depth_gate_floor must be in [0,1), got {depth_gate_floor}") + if depth_gate_mode not in {"learned", "fixed"}: + raise ValueError(f"Unknown depth_gate_mode: {depth_gate_mode}") + if not 0.0 <= depth_gate_fixed_value <= 1.0: + raise ValueError(f"depth_gate_fixed_value must be in [0,1], got {depth_gate_fixed_value}") + self.depth_gate_floor = depth_gate_floor + self.depth_gate_mode = depth_gate_mode + self.depth_gate_fixed_value = depth_gate_fixed_value + if use_depth: + self.depth_norm = nn.LayerNorm(dim) + self.depth_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.depth_gate = nn.Sequential(nn.Linear(dim * 2, dim), nn.GELU(), nn.Linear(dim, 1)) + nn.init.zeros_(self.depth_gate[-1].weight) + nn.init.zeros_(self.depth_gate[-1].bias) + self.ffn = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim * 4), nn.GELU(), nn.Linear(dim * 4, dim)) + + def forward( + self, + queries: torch.Tensor, + rgb: torch.Tensor, + depth: torch.Tensor | None, + depth_available: torch.Tensor, + side_bias: torch.Tensor, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + q = self.query_norm(queries + side_bias) + if self.use_bimanual: + hand_delta, _ = self.hand_attention(q, q, q, need_weights=False) + queries = queries + hand_delta + q = self.query_norm(queries + side_bias) + rgb_delta, rgb_attention = self.rgb_attention(q, self.rgb_norm(rgb), self.rgb_norm(rgb), need_weights=True) + queries = queries + rgb_delta + aux: dict[str, torch.Tensor] = { + "rgb_cross_attention": rgb_attention, + "rgb_update_norm": torch.linalg.vector_norm(rgb_delta, dim=-1), + } + if self.use_depth and depth is not None: + q = self.query_norm(queries + side_bias) + depth_delta, depth_attention = self.depth_attention(q, self.depth_norm(depth), self.depth_norm(depth), need_weights=True) + if self.depth_gate_mode == "fixed": + raw_gate = torch.full_like(depth_delta[..., :1], self.depth_gate_fixed_value) + else: + raw_gate = torch.sigmoid(self.depth_gate(torch.cat((q, depth_delta), dim=-1))) + gate = self.depth_gate_floor + (1.0 - self.depth_gate_floor) * raw_gate + gate = gate * depth_available[:, None, None].to(gate.dtype) + queries = queries + gate * depth_delta + aux.update({ + "depth_cross_attention": depth_attention, + "depth_fusion_gate": gate, + "depth_fusion_gate_raw": raw_gate * depth_available[:, None, None].to(raw_gate.dtype), + "depth_update_norm": torch.linalg.vector_norm(depth_delta, dim=-1), + "gated_depth_update_norm": torch.linalg.vector_norm(gate * depth_delta, dim=-1), + }) + queries = queries + self.ffn(queries) + return queries, aux + + +class TemporalUpdate(nn.Module): + def __init__( + self, + dim: int, + heads: int, + use_temporal: bool, + use_bimanual: bool, + position_mode: str = "none", + relative_bias_max_distance: int = 15, + attention_mode: str = "bidirectional", + ) -> None: + super().__init__() + if position_mode not in {"none", "relative_bias"}: + raise ValueError(f"Unknown temporal position mode: {position_mode}") + if position_mode != "none" and not use_temporal: + raise ValueError("temporal position conditioning requires use_temporal=True") + if relative_bias_max_distance < 1: + raise ValueError("relative_bias_max_distance must be positive") + if attention_mode not in {"bidirectional", "causal"}: + raise ValueError(f"Unknown temporal attention mode: {attention_mode}") + self.use_temporal = use_temporal + self.use_bimanual = use_bimanual + self.position_mode = position_mode + self.heads = heads + self.relative_bias_max_distance = relative_bias_max_distance + self.attention_mode = attention_mode + if use_temporal: + self.temporal_norm = nn.LayerNorm(dim) + self.temporal_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + if position_mode == "relative_bias": + self.relative_position_bias = nn.Parameter( + torch.zeros(heads, 2 * relative_bias_max_distance + 1) + ) + if use_bimanual: + self.bimanual_norm = nn.LayerNorm(dim) + self.bimanual_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + + def _relative_attention_bias( + self, batch_hands: int, time: int, dtype: torch.dtype, device: torch.device, + ) -> torch.Tensor | None: + if self.position_mode == "none": + return None + positions = torch.arange(time, device=device) + # Signed key-query displacement preserves ordered offline-video direction. + relative = positions[None, :] - positions[:, None] + relative = relative.clamp( + -self.relative_bias_max_distance, self.relative_bias_max_distance, + ) + self.relative_bias_max_distance + per_head = self.relative_position_bias[:, relative].to(dtype=dtype) + return per_head[None].expand(batch_hands, -1, -1, -1).reshape( + batch_hands * self.heads, time, time, + ) + + def _attention_mask( + self, batch_hands: int, time: int, dtype: torch.dtype, + device: torch.device, + ) -> torch.Tensor | None: + attention_mask = self._relative_attention_bias( + batch_hands, time, dtype, device, + ) + if self.attention_mode == "bidirectional": + return attention_mask + future = torch.triu( + torch.ones(time, time, dtype=torch.bool, device=device), diagonal=1, + ) + if attention_mask is None: + return future + return attention_mask.masked_fill(future[None], float("-inf")) + + def forward(self, tokens: torch.Tensor, frame_valid: torch.Tensor) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + batch, time, hands, dim = tokens.shape + aux: dict[str, torch.Tensor] = {} + if self.use_temporal: + per_hand = tokens.permute(0, 2, 1, 3).reshape(batch * hands, time, dim) + normalized = self.temporal_norm(per_hand) + key_padding = (~frame_valid)[:, None].expand(batch, hands, time).reshape(batch * hands, time) + attention_mask = self._attention_mask( + batch * hands, time, normalized.dtype, normalized.device, + ) + if attention_mask is not None and attention_mask.dtype != torch.bool: + float_padding = torch.zeros_like(key_padding, dtype=normalized.dtype) + key_padding_mask: torch.Tensor = float_padding.masked_fill(key_padding, float("-inf")) + else: + key_padding_mask = key_padding + delta, weights = self.temporal_attention( + normalized, normalized, normalized, + key_padding_mask=key_padding_mask, attn_mask=attention_mask, + need_weights=True, + ) + per_hand = per_hand + delta + tokens = per_hand.reshape(batch, hands, time, dim).permute(0, 2, 1, 3) + aux["temporal_attention"] = weights.reshape(batch, hands, time, time) + aux["temporal_update_norm"] = torch.linalg.vector_norm(delta, dim=-1).reshape(batch, hands, time).permute(0, 2, 1) + if self.use_bimanual: + pairs = tokens.reshape(batch * time, hands, dim) + normalized = self.bimanual_norm(pairs) + delta, weights = self.bimanual_attention(normalized, normalized, normalized, need_weights=True) + tokens = (pairs + delta).reshape(batch, time, hands, dim) + aux["bimanual_attention"] = weights.reshape(batch, time, hands, hands) + return tokens * frame_valid[:, :, None, None].to(tokens.dtype), aux + + +class HandQueryDecoder(nn.Module): + def __init__( + self, + dim: int, + layers: int, + heads: int, + use_depth: bool, + use_temporal: bool, + use_bimanual: bool, + mode: str, + gradient_checkpointing: bool = False, + depth_gate_floor: float = 0.0, + depth_gate_mode: str = "learned", + depth_gate_fixed_value: float = 0.5, + temporal_position_mode: str = "none", + temporal_relative_bias_max_distance: int = 15, + temporal_attention_mode: str = "bidirectional", + ) -> None: + super().__init__() + if mode not in {"sequential", "alternating", "hybrid_reread"}: + raise ValueError(f"Unknown decoder mode: {mode}") + self.mode = mode + self.gradient_checkpointing = gradient_checkpointing + self.temporal_enabled = True + self.spatial = nn.ModuleList([ + SpatialUpdate( + dim, heads, use_depth, use_bimanual, depth_gate_floor, + depth_gate_mode, depth_gate_fixed_value, + ) + for _ in range(layers) + ]) + temporal_layers = layers if mode == "alternating" else 1 + self.temporal = nn.ModuleList([ + TemporalUpdate( + dim, heads, use_temporal, use_bimanual, + temporal_position_mode, temporal_relative_bias_max_distance, + temporal_attention_mode, + ) + for _ in range(temporal_layers) + ]) + # With three spatial blocks this is S-S-T-S. The single temporal block + # and all parameters exactly match the sequential S-S-S-T baseline. + self.hybrid_temporal_after = max(layers - 2, 0) + + def forward(self, queries: torch.Tensor, rgb: torch.Tensor, depth: torch.Tensor | None, frame_valid: torch.Tensor, depth_available: torch.Tensor, side_bias: torch.Tensor) -> tuple[torch.Tensor, dict[str, Any]]: + batch, time, hands, dim = queries.shape + rgb_flat = rgb.reshape(batch * time, rgb.shape[2], dim) + depth_flat = None if depth is None else depth.reshape(batch * time, depth.shape[2], dim) + available_flat = depth_available.reshape(batch * time) + aux: dict[str, list[torch.Tensor]] = {} + for layer_index, spatial in enumerate(self.spatial): + spatial_args = (queries.reshape(batch * time, hands, dim), rgb_flat, depth_flat, available_flat, side_bias) + if self.gradient_checkpointing and self.training: + flat, layer_aux = checkpoint(spatial, *spatial_args, use_reentrant=False) + else: + flat, layer_aux = spatial(*spatial_args) + queries = flat.reshape(batch, time, hands, dim) * frame_valid[:, :, None, None].to(flat.dtype) + for key, value in layer_aux.items(): + aux.setdefault(key, []).append(value.reshape(batch, time, *value.shape[1:])) + if self.mode == "alternating" and self.temporal_enabled: + if self.gradient_checkpointing and self.training: + queries, temporal_aux = checkpoint(self.temporal[layer_index], queries, frame_valid, use_reentrant=False) + else: + queries, temporal_aux = self.temporal[layer_index](queries, frame_valid) + for key, value in temporal_aux.items(): + aux.setdefault(key, []).append(value) + elif self.mode == "hybrid_reread" and self.temporal_enabled and layer_index == self.hybrid_temporal_after: + if self.gradient_checkpointing and self.training: + queries, temporal_aux = checkpoint(self.temporal[0], queries, frame_valid, use_reentrant=False) + else: + queries, temporal_aux = self.temporal[0](queries, frame_valid) + for key, value in temporal_aux.items(): + aux.setdefault(key, []).append(value) + if self.mode == "sequential" and self.temporal_enabled: + queries, temporal_aux = self.temporal[0](queries, frame_valid) + for key, value in temporal_aux.items(): + aux.setdefault(key, []).append(value) + return queries, {key: torch.stack(values, dim=1) for key, values in aux.items()} diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/encoders.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..1b7c243f1cc84457e794d5e045b543f93d344f93 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/encoders.py @@ -0,0 +1,180 @@ +"""RGB and metric depth/geometry patch encoders.""" + +from __future__ import annotations + +from pathlib import Path +from typing import NamedTuple + +import torch +from torch import nn + + +class PatchFeatures(NamedTuple): + tokens: torch.Tensor + grid_hw: tuple[int, int] + patch_size: int + + +class TinyPatchEncoder(nn.Module): + """Debug-only encoder; never a substitute for a pretrained DINOv3 result.""" + + def __init__(self, output_dim: int, patch_size: int = 16, width: int = 64) -> None: + super().__init__() + self.patch_size = patch_size + self.output_dim = output_dim + self.network = nn.Sequential( + nn.Conv2d(3, width, 7, stride=2, padding=3), nn.GELU(), + nn.Conv2d(width, output_dim, patch_size // 2, stride=patch_size // 2), + ) + + def forward(self, images: torch.Tensor) -> PatchFeatures: + features = self.network(images) + return PatchFeatures(features.flatten(2).transpose(1, 2), features.shape[-2:], self.patch_size) + + +class DinoV3Encoder(nn.Module): + """Frozen official DINOv3 dense patch-token wrapper.""" + + def __init__( + self, + source_repo: str | Path, + weights: str | Path, + model_name: str = "dinov3_vitb16", + output_dim: int = 512, + input_dim: int = 768, + frozen: bool = True, + trainable_last_blocks: int = 0, + ) -> None: + super().__init__() + source_repo, weights = Path(source_repo), Path(weights) + self.backend = "torch_hub" + self.num_prefix_tokens = 0 + if weights.is_dir() and (weights / "model.safetensors").is_file(): + try: + from transformers import AutoModel + except ImportError as error: + raise ImportError("Transformers >=4.56 is required for local DINOv3 safetensors") from error + self.backbone = AutoModel.from_pretrained(str(weights), local_files_only=True) + self.backend = "transformers" + self.patch_size = int(self.backbone.config.patch_size) + self.num_prefix_tokens = 1 + int(self.backbone.config.num_register_tokens) + input_dim = int(self.backbone.config.hidden_size) + else: + if not (source_repo / "hubconf.py").is_file(): + raise FileNotFoundError(f"Official DINOv3 source repo not found: {source_repo}") + if not weights.is_file(): + raise FileNotFoundError( + f"DINOv3 pretrained weight not found: {weights}. Random DINO is not accepted for formal experiments." + ) + self.backbone = torch.hub.load( + str(source_repo), model_name, source="local", pretrained=True, weights=str(weights) + ) + self.patch_size = int(self.backbone.patch_size) + self.output_dim = output_dim + self.projection = nn.Linear(input_dim, output_dim) + if trainable_last_blocks < 0: + raise ValueError("trainable_last_blocks must be non-negative") + blocks = self._backbone_blocks() + if trainable_last_blocks > len(blocks): + raise ValueError( + f"requested {trainable_last_blocks} trainable DINO blocks, " + f"but the backbone has {len(blocks)}" + ) + if not frozen and trainable_last_blocks: + raise ValueError("full-backbone training and last-block training are mutually exclusive") + self.trainable_last_blocks = trainable_last_blocks + self.frozen = frozen and trainable_last_blocks == 0 + if frozen: + self.backbone.requires_grad_(False) + if trainable_last_blocks: + for block in blocks[-trainable_last_blocks:]: + block.requires_grad_(True) + self._backbone_final_norm().requires_grad_(True) + self._set_backbone_mode(False) + + def _backbone_blocks(self) -> nn.ModuleList: + blocks = getattr(self.backbone, "layer", None) + if blocks is None: + blocks = getattr(self.backbone, "blocks", None) + if not isinstance(blocks, nn.ModuleList): + raise TypeError("unsupported DINOv3 backbone: transformer blocks are unavailable") + return blocks + + def _backbone_final_norm(self) -> nn.Module: + norm = getattr(self.backbone, "norm", None) + if not isinstance(norm, nn.Module): + raise TypeError("unsupported DINOv3 backbone: final norm is unavailable") + return norm + + def _set_backbone_mode(self, mode: bool) -> None: + self.backbone.eval() + if self.trainable_last_blocks: + for block in self._backbone_blocks()[-self.trainable_last_blocks:]: + block.train(mode) + self._backbone_final_norm().train(mode) + + def train(self, mode: bool = True): + super().train(mode) + if self.frozen or self.trainable_last_blocks: + self._set_backbone_mode(mode) + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + height, width = images.shape[-2:] + if height % self.patch_size or width % self.patch_size: + raise ValueError(f"DINO input {height}x{width} must be divisible by patch size {self.patch_size}") + if self.frozen: + with torch.no_grad(): + if self.backend == "transformers": + raw = self.backbone(pixel_values=images).last_hidden_state[:, self.num_prefix_tokens :] + else: + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + else: + if self.backend == "transformers": + raw = self.backbone(pixel_values=images).last_hidden_state[:, self.num_prefix_tokens :] + else: + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + tokens = self.projection(raw) + return PatchFeatures(tokens, (height // self.patch_size, width // self.patch_size), self.patch_size) + + +class DepthGeometryEncoder(nn.Module): + """Aligned metric log-depth or XYZ/logZ patch encoder.""" + + def __init__(self, output_dim: int, patch_size: int = 16, mode: str = "log_depth") -> None: + super().__init__() + if mode not in {"log_depth", "geometry"}: + raise ValueError(f"Unknown depth mode: {mode}") + self.mode = mode + self.patch_size = patch_size + channels = 2 if mode == "log_depth" else 5 + hidden = max(32, output_dim // 4) + self.encoder = nn.Sequential( + nn.Conv2d(channels, hidden, 3, padding=1), nn.GELU(), + nn.Conv2d(hidden, output_dim, patch_size, stride=patch_size), + ) + # Start as a zero residual so the gate need not suppress random depth noise. + nn.init.zeros_(self.encoder[-1].weight) + nn.init.zeros_(self.encoder[-1].bias) + + def forward(self, depth_m: torch.Tensor, valid: torch.Tensor, K: torch.Tensor) -> PatchFeatures: + if depth_m.ndim != 4 or depth_m.shape[1] != 1: + raise ValueError(f"Expected [BT,1,H,W] depth, got {depth_m.shape}") + valid_float = valid.to(depth_m.dtype) + log_z = torch.where(valid, depth_m.clamp_min(1e-4).log(), torch.zeros_like(depth_m)) + if self.mode == "log_depth": + inputs = torch.cat((log_z, valid_float), dim=1) + else: + _, _, height, width = depth_m.shape + u = torch.arange(width, device=depth_m.device, dtype=depth_m.dtype).view(1, 1, 1, width) + v = torch.arange(height, device=depth_m.device, dtype=depth_m.dtype).view(1, 1, height, 1) + cx = K[:, 0, 2].view(-1, 1, 1, 1) + cy = K[:, 1, 2].view(-1, 1, 1, 1) + fx = K[:, 0, 0].view(-1, 1, 1, 1) + fy = K[:, 1, 1].view(-1, 1, 1, 1) + x = (u - cx) * depth_m / fx + y = (v - cy) * depth_m / fy + x, y = x * valid_float, y * valid_float + inputs = torch.cat((x, y, depth_m * valid_float, log_z, valid_float), dim=1) + features = self.encoder(inputs) + return PatchFeatures(features.flatten(2).transpose(1, 2), features.shape[-2:], self.patch_size) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/mano.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/mano.py new file mode 100644 index 0000000000000000000000000000000000000000..aa23fb1a21aee64238a7ae6ce20b24c346643482 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/mano.py @@ -0,0 +1,61 @@ +"""Independent left/right MANO layers with wrist-root camera translation.""" + +from __future__ import annotations + +from pathlib import Path + +import torch +from torch import nn + +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import matrix_to_axis_angle + + +class ManoCameraLayer(nn.Module): + """Run official manopth in native mm, root-center, then place wrist in camera meters.""" + + def __init__( + self, + mano_root: str | Path, + fix_left_shapedirs: bool = False, + ) -> None: + super().__init__() + root = Path(mano_root) + required = [root / "MANO_LEFT.pkl", root / "MANO_RIGHT.pkl"] + missing = [str(path) for path in required if not path.is_file()] + if missing: + raise FileNotFoundError(f"Licensed MANO assets missing: {missing}") + enable_legacy_mano_loading() + try: + from manopth.manolayer import ManoLayer + except ImportError as error: + raise ImportError("Install the pinned official manopth source before enabling MANO") from error + self.layers = nn.ModuleList([ + ManoLayer(mano_root=str(root), side="left", use_pca=False, ncomps=45, flat_hand_mean=True), + ManoLayer(mano_root=str(root), side="right", use_pca=False, ncomps=45, flat_hand_mean=True), + ]) + if fix_left_shapedirs: + # Match the official HOT3D provider's corrected MANO-left + # convention. The historical default remains unchanged for old + # H2O checkpoints. + with torch.no_grad(): + self.layers[0].th_shapedirs[:, 0, :].mul_(-1) + + def forward(self, rotation_matrices: torch.Tensor, shape: torch.Tensor, wrist_translation_m: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + if rotation_matrices.shape[-3:] != (16, 3, 3): + raise ValueError(f"Expected [...,2,16,3,3], got {rotation_matrices.shape}") + leading = rotation_matrices.shape[:-4] + if rotation_matrices.shape[-4] != 2: + raise ValueError("MANO hand dimension must be fixed [left,right]") + vertices_out, joints_out = [], [] + for hand, layer in enumerate(self.layers): + pose = matrix_to_axis_angle(rotation_matrices[..., hand, :, :, :]).reshape(-1, 48) + betas = shape[..., hand, :].reshape(-1, 10) + vertices_mm, joints_mm = layer(pose, betas) + root_mm = joints_mm[:, :1] + wrist = wrist_translation_m[..., hand, :].reshape(-1, 1, 3) + vertices = (vertices_mm - root_mm) / 1000.0 + wrist + joints = (joints_mm - root_mm) / 1000.0 + wrist + vertices_out.append(vertices.reshape(*leading, vertices.shape[-2], 3)) + joints_out.append(joints.reshape(*leading, joints.shape[-2], 3)) + return torch.stack(vertices_out, dim=-3), torch.stack(joints_out, dim=-3) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/structured_hand.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/structured_hand.py new file mode 100644 index 0000000000000000000000000000000000000000..e5d3e8dd8fc760012d2622d61a13fef716ae1703 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/models/structured_hand.py @@ -0,0 +1,192 @@ +"""Predicted-location structured hand refinement for Phase 5.""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + + +PART_COUNT = 7 +ROOT_PART = 0 +PALM_PART = 1 +FINGER_PARTS = slice(2, 7) + + +def structured_part_locations(joints_2d_norm: torch.Tensor) -> torch.Tensor: + """Map 21 predicted joints to root, palm, and five finger centers.""" + + if joints_2d_norm.ndim != 5 or joints_2d_norm.shape[-2:] != (21, 2): + raise ValueError("joint locations must have shape [B,T,2,21,2]") + root = joints_2d_norm[..., :1, :] + palm = joints_2d_norm[..., (0, 1, 5, 9, 13, 17), :].mean( + dim=-2, keepdim=True, + ) + fingers = torch.stack([ + joints_2d_norm[..., start : start + 4, :].mean(dim=-2) + for start in (1, 5, 9, 13, 17) + ], dim=-2) + return torch.cat((root, palm, fingers), dim=-2) + + +def kinematic_attention_mask(device: torch.device) -> torch.Tensor: + """Return a symmetric root-palm-finger graph mask for self-attention.""" + + allowed = torch.eye(PART_COUNT, dtype=torch.bool, device=device) + allowed[ROOT_PART, PALM_PART] = True + allowed[PALM_PART, ROOT_PART] = True + allowed[PALM_PART, FINGER_PARTS] = True + allowed[FINGER_PARTS, PALM_PART] = True + return ~allowed + + +class StructuredHandRefinement(nn.Module): + """Fuse coarse hand tokens with deformably sampled full-frame features.""" + + def __init__( + self, dim: int, heads: int, *, use_depth: bool, samples: int = 4, + maximum_offset_norm: float = 0.08, + ) -> None: + super().__init__() + if samples < 1: + raise ValueError("deformable sample count must be positive") + if not 0.0 < maximum_offset_norm <= 0.25: + raise ValueError("maximum normalized offset must be in (0,0.25]") + self.samples = samples + self.maximum_offset_norm = maximum_offset_norm + self.use_depth = use_depth + self.part_embedding = nn.Parameter(torch.randn(PART_COUNT, dim) * 0.02) + self.offset_head = nn.Linear(dim, samples * 2) + nn.init.zeros_(self.offset_head.weight) + nn.init.zeros_(self.offset_head.bias) + self.rgb_projection = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim)) + if use_depth: + self.depth_projection = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim)) + self.fusion_norm = nn.LayerNorm(dim) + self.graph_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.ffn = nn.Sequential( + nn.LayerNorm(dim), nn.Linear(dim, dim * 4), nn.GELU(), + nn.Linear(dim * 4, dim), + ) + + @staticmethod + def _sample( + tokens: torch.Tensor, + grid_hw: tuple[int, int], + locations: torch.Tensor, + *, + deterministic_detached: bool = False, + ) -> torch.Tensor: + batch, time, patches, dim = tokens.shape + grid_height, grid_width = grid_hw + if patches != grid_height * grid_width: + raise ValueError("feature token count does not match patch grid") + if locations.shape[:2] != (batch, time) or locations.shape[-1] != 2: + raise ValueError("sample locations must align with [B,T] tokens") + if deterministic_detached: + features = tokens.detach().reshape(batch * time, patches, dim) + coordinates = locations.reshape(batch * time, -1, 2) + x = coordinates[..., 0] * grid_width - 0.5 + y = coordinates[..., 1] * grid_height - 0.5 + x0, y0 = torch.floor(x), torch.floor(y) + x1, y1 = x0 + 1.0, y0 + 1.0 + + def corner(x_index: torch.Tensor, y_index: torch.Tensor) -> torch.Tensor: + valid = ( + (x_index >= 0.0) & (x_index < grid_width) + & (y_index >= 0.0) & (y_index < grid_height) + ) + flat_index = ( + y_index.clamp(0, grid_height - 1).long() * grid_width + + x_index.clamp(0, grid_width - 1).long() + ) + value = torch.gather( + features, + 1, + flat_index[..., None].expand(-1, -1, dim), + ) + return value * valid[..., None].to(value.dtype) + + sampled = ( + corner(x0, y0) * ((x1 - x) * (y1 - y))[..., None] + + corner(x1, y0) * ((x - x0) * (y1 - y))[..., None] + + corner(x0, y1) * ((x1 - x) * (y - y0))[..., None] + + corner(x1, y1) * ((x - x0) * (y - y0))[..., None] + ) + sampled = sampled.reshape(*locations.shape[:-1], dim).mean(dim=-2) + return sampled + feature_map = tokens.reshape( + batch * time, grid_height, grid_width, dim, + ).permute(0, 3, 1, 2) + flat_locations = locations.reshape(batch * time, -1, locations.shape[-2], 2) + grid = flat_locations.mul(2.0).sub(1.0) + sampled = F.grid_sample( + feature_map, grid, mode="bilinear", padding_mode="zeros", + align_corners=False, + ) + sampled = sampled.mean(dim=-1).transpose(1, 2) + return sampled.reshape(*locations.shape[:-2], dim) + + def forward( + self, + coarse_hand_tokens: torch.Tensor, + joint2d_norm: torch.Tensor, + rgb_tokens: torch.Tensor, + depth_tokens: torch.Tensor | None, + grid_hw: tuple[int, int], + frame_valid: torch.Tensor, + depth_available: torch.Tensor, + *, + detach_locations: bool, + deterministic_detached_sampling: bool = False, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + batch, time, hands, dim = coarse_hand_tokens.shape + if hands != 2: + raise ValueError("structured refinement expects two hands") + locations = structured_part_locations(joint2d_norm) + if detach_locations: + locations = locations.detach() + seeds = coarse_hand_tokens[..., None, :] + self.part_embedding + offsets = self.maximum_offset_norm * torch.tanh( + self.offset_head(seeds).reshape( + batch, time, hands, PART_COUNT, self.samples, 2, + ) + ) + sample_locations = locations[..., None, :] + offsets + sampled_rgb = self._sample( + rgb_tokens, + grid_hw, + sample_locations, + deterministic_detached=deterministic_detached_sampling, + ) + tokens = seeds + self.rgb_projection(sampled_rgb) + if self.use_depth and depth_tokens is not None: + sampled_depth = self._sample( + depth_tokens, + grid_hw, + sample_locations, + deterministic_detached=deterministic_detached_sampling, + ) + depth_mask = depth_available[:, :, None, None, None].to(sampled_depth.dtype) + tokens = tokens + self.depth_projection(sampled_depth) * depth_mask + graph_input = self.fusion_norm(tokens).reshape( + batch * time * hands, PART_COUNT, dim, + ) + graph_delta, graph_weights = self.graph_attention( + graph_input, graph_input, graph_input, + attn_mask=kinematic_attention_mask(graph_input.device), + need_weights=True, + ) + tokens = (graph_input + graph_delta).reshape( + batch, time, hands, PART_COUNT, dim, + ) + tokens = tokens + self.ffn(tokens) + tokens = tokens * frame_valid[:, :, None, None, None].to(tokens.dtype) + return tokens, { + "structured_part_locations": locations, + "structured_sample_offsets": offsets, + "structured_sample_locations": sample_locations, + "structured_graph_attention": graph_weights.reshape( + batch, time, hands, PART_COUNT, PART_COUNT, + ), + } diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/__init__.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d718428f981b8ec69c68dee3978a07ce6689678 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/__init__.py @@ -0,0 +1,3 @@ +from foundation_hand.training.losses import BimanualLoss, LossConfig + +__all__ = ["BimanualLoss", "LossConfig"] diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/checkpoint.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..17d23ba069d588aaeee71af0d863dc35ca9002fb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/checkpoint.py @@ -0,0 +1,97 @@ +"""Exact model/optimizer/RNG checkpoint save and resume.""" + +from __future__ import annotations + +import random +from pathlib import Path +from typing import Any + +import numpy as np +import torch + + +def save_checkpoint( + path: str | Path, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + step: int, + extra: dict[str, Any] | None = None, + exclude_prefixes: tuple[str, ...] = (), +) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + model_state = { + key: value for key, value in model.state_dict().items() + if not key.startswith(exclude_prefixes) + } + state = { + "model": model_state, "optimizer": optimizer.state_dict(), "step": step, + "excluded_model_prefixes": exclude_prefixes, + "python_rng": random.getstate(), "numpy_rng": np.random.get_state(), + "torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None, + "extra": extra or {}, + } + torch.save(state, path) + + +def load_checkpoint(path: str | Path, model: torch.nn.Module, optimizer: torch.optim.Optimizer | None = None, map_location: str | torch.device = "cpu") -> dict[str, Any]: + state = torch.load(path, map_location=map_location, weights_only=False) + excluded_prefixes = tuple(state.get("excluded_model_prefixes", ())) + incompatible = model.load_state_dict(state["model"], strict=not excluded_prefixes) + if incompatible.unexpected_keys: + raise RuntimeError(f"Unexpected checkpoint keys: {incompatible.unexpected_keys}") + disallowed_missing = [ + key for key in incompatible.missing_keys + if not key.startswith(excluded_prefixes) + ] + if disallowed_missing: + raise RuntimeError(f"Missing non-excluded checkpoint keys: {disallowed_missing}") + if optimizer is not None: + optimizer.load_state_dict(state["optimizer"]) + random.setstate(state["python_rng"]) + np.random.set_state(state["numpy_rng"]) + torch.set_rng_state(state["torch_rng"].cpu()) + if torch.cuda.is_available() and state["cuda_rng"] is not None: + torch.cuda.set_rng_state_all([value.cpu() for value in state["cuda_rng"]]) + return {"step": state["step"], "extra": state["extra"]} + + +def load_model_initialization( + path: str | Path, + model: torch.nn.Module, + *, + allowed_missing_prefixes: tuple[str, ...], + map_location: str | torch.device = "cpu", + require_residual: bool = True, +) -> dict[str, Any]: + """Load an old model into a registered residual extension only.""" + + if require_residual and not allowed_missing_prefixes: + raise ValueError("initialization requires explicit allowed missing prefixes") + state = torch.load(path, map_location=map_location, weights_only=False) + incompatible = model.load_state_dict(state["model"], strict=False) + if incompatible.unexpected_keys: + raise RuntimeError(f"Unexpected initialization keys: {incompatible.unexpected_keys}") + checkpoint_excluded_prefixes = tuple(state.get("excluded_model_prefixes", ())) + accepted_missing_prefixes = allowed_missing_prefixes + checkpoint_excluded_prefixes + disallowed_missing = [ + key for key in incompatible.missing_keys + if not key.startswith(accepted_missing_prefixes) + ] + if disallowed_missing: + raise RuntimeError( + f"Missing non-residual initialization keys: {disallowed_missing}" + ) + residual_missing = [ + key for key in incompatible.missing_keys + if key.startswith(allowed_missing_prefixes) + ] + if require_residual and not residual_missing: + raise RuntimeError("initialization did not add any registered residual parameters") + return { + "step": int(state["step"]), + "extra": state.get("extra", {}), + "missing_keys": sorted(incompatible.missing_keys), + "residual_missing_keys": sorted(residual_missing), + "checkpoint_excluded_prefixes": checkpoint_excluded_prefixes, + } diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/losses.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..6e409461719f8b6fac7cee4689ec7e5870df36fd --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/losses.py @@ -0,0 +1,341 @@ +"""Mask-safe camera-space bimanual training losses.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch +import torch.nn.functional as F +from torch import nn + +from foundation_hand.data.schema import supervision_mask +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.geometry.camera import project_points + + +@dataclass +class LossConfig: + joint2d: float = 1.0 + joint2d_teacher: float = 0.0 + joint3d_camera: float = 10.0 + joint3d_root_relative: float = 0.0 + vertices_camera: float = 1.0 + local_pose: float = 1.0 + global_orientation: float = 1.0 + shape: float = 0.1 + translation: float = 10.0 + reprojection: float = 1.0 + temporal_velocity: float = 0.1 + temporal_acceleration: float = 0.05 + bimanual_relative_wrist: float = 1.0 + presence: float = 0.0 + translation_teacher: float = 0.0 + translation_mode: str = "l1" + translation_axis_weights: tuple[float, float, float] = (1.0, 1.0, 1.0) + translation_huber_beta_m: float = 0.01 + wrist_ray: float = 0.0 + robust_log_z: float = 0.0 + z_tail_cvar: float = 0.0 + depth_confidence_calibration: float = 0.0 + paired_modality_no_harm: float = 0.0 + + def __post_init__(self) -> None: + if self.translation_mode not in {"l1", "axis_huber"}: + raise ValueError(f"unsupported translation mode: {self.translation_mode}") + if len(self.translation_axis_weights) != 3: + raise ValueError("translation_axis_weights must contain x/y/z weights") + weights = tuple(float(value) for value in self.translation_axis_weights) + if any(value <= 0.0 for value in weights): + raise ValueError("translation axis weights must be positive") + if self.translation_huber_beta_m <= 0.0: + raise ValueError("translation_huber_beta_m must be positive") + self.translation_axis_weights = weights + + +def masked_mean(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + mask = torch.broadcast_to(mask, values.shape) + safe = torch.where(mask, values, torch.zeros_like(values)) + count = mask.sum() + return safe.sum() / count.clamp_min(1) + + +def masked_l1(prediction: torch.Tensor, target: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + safe_target = torch.where(torch.broadcast_to(mask, target.shape), target, torch.zeros_like(target)) + return masked_mean((prediction - safe_target).abs(), mask) + + +class BimanualLoss(nn.Module): + def __init__(self, config: LossConfig) -> None: + super().__init__() + self.config = config + + def _translation_loss( + self, + prediction: torch.Tensor, + target: torch.Tensor, + mask: torch.Tensor, + ) -> torch.Tensor: + if self.config.translation_mode == "l1": + return masked_l1(prediction, target, mask[..., None]) + safe_target = torch.where(mask[..., None], target, torch.zeros_like(target)) + elementwise = F.smooth_l1_loss( + prediction, + safe_target, + reduction="none", + beta=float(self.config.translation_huber_beta_m), + ) + weights = prediction.new_tensor(self.config.translation_axis_weights) + return masked_mean(elementwise * weights, mask[..., None]) + + def translation_diagnostics( + self, + prediction: dict[str, torch.Tensor], + batch: dict[str, torch.Tensor], + ) -> dict[str, torch.Tensor]: + """Return detached-loggable per-axis terms without changing total loss.""" + + frame = batch["frame_valid"].bool() + mask = supervision_mask( + batch, + "translation_valid", + batch["joint_annotation_valid"].bool(), + ) & frame[..., None] + target = torch.where( + mask[..., None], + batch["wrist_root_translation"], + torch.zeros_like(batch["wrist_root_translation"]), + ) + error = prediction["wrist_root_translation"] - target + if self.config.translation_mode == "axis_huber": + elementwise = F.smooth_l1_loss( + prediction["wrist_root_translation"], + target, + reduction="none", + beta=float(self.config.translation_huber_beta_m), + ) + weights = prediction["wrist_root_translation"].new_tensor( + self.config.translation_axis_weights + ) + else: + elementwise = error.abs() + weights = prediction["wrist_root_translation"].new_ones(3) + diagnostics: dict[str, torch.Tensor] = {} + for axis_index, axis in enumerate(("x", "y", "z")): + raw_mae = masked_mean(error[..., axis_index].abs(), mask) + axis_term = masked_mean(elementwise[..., axis_index], mask) + diagnostics[f"translation_{axis}_raw_mae_m"] = raw_mae + diagnostics[f"translation_{axis}_effective_loss_contribution"] = ( + axis_term * weights[axis_index] * float(self.config.translation) / 3.0 + ) + return diagnostics + + def forward(self, prediction: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: + frame = batch["frame_valid"].bool() + legacy_joint = batch["joint_annotation_valid"].bool() + legacy_mano = batch["mano_annotation_valid"].bool() + legacy_joint_elements = ( + batch["joint_element_valid"].bool() & legacy_joint[..., None] + ) + joint2d_valid = supervision_mask( + batch, "joint2d_valid", legacy_joint_elements, + ) & frame[..., None, None] + joint3d_valid = supervision_mask( + batch, "joint3d_valid", legacy_joint_elements, + ) & frame[..., None, None] + joint3d_root_relative_valid = supervision_mask( + batch, "joint3d_root_relative_valid", joint3d_valid, + ) & frame[..., None, None] + translation_valid = supervision_mask( + batch, "translation_valid", legacy_joint, + ) & frame[..., None] + pose_valid = supervision_mask( + batch, "mano_pose_valid", legacy_mano, + ) & frame[..., None] + shape_valid = supervision_mask( + batch, "shape_valid", legacy_mano, + ) & frame[..., None] + vertices_valid = supervision_mask( + batch, "vertices_valid", legacy_mano, + ) & frame[..., None] + image_hw = batch["image_hw"].to(prediction["joint2d_norm"].dtype) + wh = image_hw[:, None, None, None, [1, 0]] + target_2d_norm = batch["joint2d"].to(wh.dtype) / wh + joint_mask = joint2d_valid + + losses: dict[str, torch.Tensor] = {} + losses["joint2d"] = masked_l1(prediction["joint2d_norm"], target_2d_norm, joint_mask[..., None]) + if "joint2d_linear_teacher_norm" in prediction: + losses["joint2d_teacher"] = masked_l1( + prediction["joint2d_norm"], + prediction["joint2d_linear_teacher_norm"], + frame[..., None, None, None], + ) + else: + losses["joint2d_teacher"] = prediction["hand_tokens"].sum() * 0 + target_axis = batch["mano_pose"].reshape(*batch["mano_pose"].shape[:-1], 16, 3) + target_rot = axis_angle_to_matrix(torch.nan_to_num(target_axis)) + rotation_error = (prediction["mano_rotation_matrices"] - target_rot).abs() + losses["global_orientation"] = masked_mean( + rotation_error[..., :1, :, :], pose_valid[..., None, None, None], + ) + losses["local_pose"] = masked_mean( + rotation_error[..., 1:, :, :], pose_valid[..., None, None, None], + ) + losses["translation"] = self._translation_loss( + prediction["wrist_root_translation"], + batch["wrist_root_translation"], + translation_valid, + ) + if "mixed_projection_direct_teacher_translation" in prediction: + losses["translation_teacher"] = masked_l1( + prediction["wrist_root_translation"], + prediction["mixed_projection_direct_teacher_translation"], + translation_valid[..., None], + ) + else: + losses["translation_teacher"] = prediction["hand_tokens"].sum() * 0 + zero = prediction["hand_tokens"].sum() * 0 + if "ray_depth_wrist2d_norm" in prediction: + wrist_mask = joint2d_valid[..., 0] + losses["wrist_ray"] = masked_l1( + prediction["ray_depth_wrist2d_norm"], + target_2d_norm[..., 0, :], wrist_mask[..., None], + ) + target_z = batch["wrist_root_translation"][..., 2] + safe_target_z = torch.where( + translation_valid, target_z.clamp_min(1e-4), + torch.ones_like(target_z), + ) + losses["robust_log_z"] = masked_mean( + F.smooth_l1_loss( + prediction["ray_depth_log_base_z"], safe_target_z.log(), + reduction="none", beta=0.05, + ), + translation_valid, + ) + final_z_error = ( + prediction["wrist_root_translation"][..., 2] - target_z + ).abs() + valid_z_error = final_z_error[translation_valid] + if valid_z_error.numel(): + tail_count = max(1, int((valid_z_error.numel() + 19) // 20)) + losses["z_tail_cvar"] = torch.topk( + valid_z_error, k=tail_count, largest=True, + ).values.mean() + else: + losses["z_tail_cvar"] = zero + correction_valid = ( + prediction["ray_depth_correction_valid"].bool() + & translation_valid + ) + base_error = (prediction["ray_depth_base_z_m"] - target_z).abs() + corrected_error = final_z_error + helpful = (corrected_error < base_error).to( + prediction["ray_depth_confidence_logit"].dtype, + ) + confidence_bce = F.binary_cross_entropy_with_logits( + prediction["ray_depth_confidence_logit"], helpful, + reduction="none", + ) + losses["depth_confidence_calibration"] = masked_mean( + confidence_bce, correction_valid, + ) + losses["paired_modality_no_harm"] = masked_mean( + (corrected_error - base_error).clamp_min(0.0), + correction_valid, + ) + else: + losses["wrist_ray"] = zero + losses["robust_log_z"] = zero + losses["z_tail_cvar"] = zero + losses["depth_confidence_calibration"] = zero + losses["paired_modality_no_harm"] = zero + + shape_mask = shape_valid.any(dim=1) + safe_shape = torch.where( + shape_valid[..., None], batch["mano_shape"], + torch.zeros_like(batch["mano_shape"]), + ) + target_shape = ( + safe_shape.sum(dim=1) + / shape_valid.sum(dim=1).clamp_min(1)[..., None] + ) + losses["shape"] = masked_l1(prediction["mano_shape_sequence"], target_shape, shape_mask[..., None]) + + if "joints_camera" in prediction: + losses["joint3d_camera"] = masked_l1( + prediction["joints_camera"], batch["joint3d_camera"], + joint3d_valid[..., None], + ) + else: + losses["joint3d_camera"] = prediction["hand_tokens"].sum() * 0 + if "joints_camera" in prediction: + predicted_relative = ( + prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + ) + if "joint3d_root_relative" in batch: + target_relative = batch["joint3d_root_relative"] + else: + target_relative = ( + batch["joint3d_camera"] - batch["joint3d_camera"][..., :1, :] + ) + losses["joint3d_root_relative"] = masked_l1( + predicted_relative, target_relative, + joint3d_root_relative_valid[..., None], + ) + else: + losses["joint3d_root_relative"] = prediction["hand_tokens"].sum() * 0 + if "vertices_camera" in prediction and "vertices_camera" in batch: + losses["vertices_camera"] = masked_l1( + prediction["vertices_camera"], batch["vertices_camera"], + vertices_valid[..., None, None], + ) + else: + losses["vertices_camera"] = prediction["hand_tokens"].sum() * 0 + if "joints_camera" in prediction and "K" in batch: + projected, positive = project_points(prediction["joints_camera"], batch["K"]) + reprojection_norm = projected / wh + K_supervision_valid = supervision_mask( + batch, "K_supervision_valid", frame, + ) & frame + reprojection_valid = supervision_mask( + batch, "reprojection_valid", joint2d_valid, + ) + reprojection_mask = ( + reprojection_valid & positive & K_supervision_valid[..., None, None] + ) + losses["reprojection"] = masked_l1(reprojection_norm, target_2d_norm, reprojection_mask[..., None]) + else: + losses["reprojection"] = prediction["hand_tokens"].sum() * 0 + + wrists = prediction["wrist_root_translation"] + pair_valid = translation_valid.all(dim=-1) + target_relative = batch["wrist_root_translation"][:, :, 1] - batch["wrist_root_translation"][:, :, 0] + pred_relative = wrists[:, :, 1] - wrists[:, :, 0] + losses["bimanual_relative_wrist"] = masked_l1(pred_relative, target_relative, pair_valid[..., None]) + + velocity_valid = translation_valid[:, 1:] & translation_valid[:, :-1] + pred_velocity = wrists[:, 1:] - wrists[:, :-1] + target_velocity = batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1] + losses["temporal_velocity"] = masked_l1(pred_velocity, target_velocity, velocity_valid[..., None]) + acceleration_valid = velocity_valid[:, 1:] & velocity_valid[:, :-1] + pred_acceleration = pred_velocity[:, 1:] - pred_velocity[:, :-1] + target_acceleration = target_velocity[:, 1:] - target_velocity[:, :-1] + losses["temporal_acceleration"] = masked_l1(pred_acceleration, target_acceleration, acceleration_valid[..., None]) + + if "presence_logit" in prediction and self.config.presence > 0: + valid = supervision_mask( + batch, "presence_valid", batch["presence_label_valid"].bool(), + ) & frame[..., None] + target = torch.where(valid, batch["presence_target"], torch.zeros_like(batch["presence_target"])) + bce = F.binary_cross_entropy_with_logits(prediction["presence_logit"], target, reduction="none") + losses["presence"] = masked_mean(bce, valid) + else: + losses["presence"] = prediction["hand_tokens"].sum() * 0 + + weighted = { + name: value * float(getattr(self.config, name)) + for name, value in losses.items() + } + weighted["total"] = sum(weighted.values()) + return weighted diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/metrics.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..c3409994ee6d28374fbf42f8ccb1b191fee54eb2 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/metrics.py @@ -0,0 +1,34 @@ +"""Camera-space metrics reported separately from root-relative accuracy.""" + +from __future__ import annotations + +import torch + +from foundation_hand.data.schema import supervision_mask + + +def camera_metrics(prediction: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> dict[str, float]: + frame = batch["frame_valid"].bool() + legacy_joint = batch["joint_annotation_valid"].bool() + joint_valid = supervision_mask( + batch, + "joint3d_valid", + batch["joint_element_valid"].bool() & legacy_joint[..., None], + ) & frame[..., None, None] + metrics: dict[str, float] = {} + translation_error = (prediction["wrist_root_translation"] - torch.nan_to_num(batch["wrist_root_translation"])).abs() + trans_mask = supervision_mask( + batch, "translation_valid", legacy_joint, + ) & frame[..., None] + for index, axis in enumerate("xyz"): + values = translation_error[..., index][trans_mask] + metrics[f"translation_{axis}_mae_mm"] = float(values.mean() * 1000) if values.numel() else float("nan") + if "joints_camera" in prediction: + target = torch.nan_to_num(batch["joint3d_camera"]) + error = torch.linalg.vector_norm(prediction["joints_camera"] - target, dim=-1) + metrics["absolute_camera_mpjpe_mm"] = float(error[joint_valid].mean() * 1000) if joint_valid.any() else float("nan") + pred_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + target_relative = target - target[..., :1, :] + relative_error = torch.linalg.vector_norm(pred_relative - target_relative, dim=-1) + metrics["root_relative_mpjpe_mm"] = float(relative_error[joint_valid].mean() * 1000) if joint_valid.any() else float("nan") + return metrics diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/optimizer.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa76830ba81297de3971dc7a8f3e956608f8890 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/optimizer.py @@ -0,0 +1,135 @@ +"""Optimizer grouping for low-learning-rate backbone adaptation.""" + +from __future__ import annotations + +import torch + + +BACKBONE_PREFIX = "rgb_encoder.backbone." + + +def optimizer_parameter_groups( + model: torch.nn.Module, + *, + learning_rate: float, + backbone_learning_rate: float | None, +) -> list[dict[str, object]]: + if learning_rate <= 0: + raise ValueError("learning_rate must be positive") + main_parameters = [] + backbone_parameters = [] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + target = backbone_parameters if name.startswith(BACKBONE_PREFIX) else main_parameters + target.append(parameter) + if not main_parameters: + raise ValueError("optimizer has no non-backbone trainable parameters") + if backbone_parameters and backbone_learning_rate is None: + raise ValueError("trainable DINOv3 blocks require backbone_learning_rate") + if not backbone_parameters and backbone_learning_rate is not None: + raise ValueError("backbone_learning_rate was set but no backbone parameter is trainable") + groups: list[dict[str, object]] = [{ + "params": main_parameters, + "lr": learning_rate, + "lr_scale": 1.0, + "group_name": "main", + }] + if backbone_parameters: + assert backbone_learning_rate is not None + if not 0 < backbone_learning_rate <= learning_rate: + raise ValueError("backbone_learning_rate must be in (0, learning_rate]") + groups.append({ + "params": backbone_parameters, + "lr": backbone_learning_rate, + "lr_scale": backbone_learning_rate / learning_rate, + "group_name": "dinov3_backbone", + }) + return groups + + +def staged_optimizer_parameter_groups( + model: torch.nn.Module, + *, + learning_rate: float, + initial_trainable_prefixes: tuple[str, ...], + unfrozen_learning_rate_scale: float, +) -> list[dict[str, object]]: + """Build stable parameter groups for a freeze-then-unfreeze schedule.""" + + if learning_rate <= 0: + raise ValueError("learning_rate must be positive") + if not initial_trainable_prefixes: + raise ValueError("initial_trainable_prefixes must not be empty") + if not 0.0 < unfrozen_learning_rate_scale <= 1.0: + raise ValueError("unfrozen_learning_rate_scale must be in (0, 1]") + initial_parameters = [] + later_parameters = [] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad or name.startswith(BACKBONE_PREFIX): + continue + target = ( + initial_parameters + if name.startswith(initial_trainable_prefixes) + else later_parameters + ) + target.append(parameter) + if not initial_parameters: + raise ValueError("staged optimizer has no initially trainable parameters") + if not later_parameters: + raise ValueError("staged optimizer has no later-unfrozen parameters") + return [ + { + "params": initial_parameters, + "lr": learning_rate, + "lr_scale": 1.0, + "group_name": "staged_initial", + }, + { + "params": later_parameters, + "lr": 0.0, + "lr_scale": 0.0, + "unfrozen_lr_scale": unfrozen_learning_rate_scale, + "group_name": "staged_later", + }, + ] + + +def set_staged_parameter_group_phase( + optimizer: torch.optim.Optimizer, *, active: bool, +) -> None: + """Switch the later group without changing optimizer parameter identity.""" + + for group in optimizer.param_groups: + if group.get("group_name") == "staged_later": + group["lr_scale"] = float(group["unfrozen_lr_scale"]) if active else 0.0 + + +def clear_staged_later_gradients( + model: torch.nn.Module, initial_trainable_prefixes: tuple[str, ...], +) -> None: + """Make the initial phase a true freeze while retaining stable groups.""" + + for name, parameter in model.named_parameters(): + if ( + parameter.requires_grad + and not name.startswith(BACKBONE_PREFIX) + and not name.startswith(initial_trainable_prefixes) + ): + parameter.grad = None + + +def set_scheduled_learning_rate( + optimizer: torch.optim.Optimizer, learning_rate: float, +) -> None: + for parameter_group in optimizer.param_groups: + parameter_group["lr"] = learning_rate * float(parameter_group.get("lr_scale", 1.0)) + + +def checkpoint_excluded_prefixes(model: torch.nn.Module) -> tuple[str, ...]: + backbone_is_trainable = any( + parameter.requires_grad + for name, parameter in model.named_parameters() + if name.startswith(BACKBONE_PREFIX) + ) + return () if backbone_is_trainable else (BACKBONE_PREFIX,) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/schedule.py b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..f230d5239a3acd995eb21f897e0a238b56883104 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/src/foundation_hand/training/schedule.py @@ -0,0 +1,26 @@ +"""Step-deterministic learning-rate schedules.""" + +from __future__ import annotations + +import math + + +def warmup_cosine_learning_rate( + step: int, + total_steps: int, + base_lr: float, + min_lr: float, + warmup_steps: int, +) -> float: + if total_steps <= 0: + raise ValueError("total_steps must be positive") + if not 0 <= warmup_steps < total_steps: + raise ValueError("warmup_steps must be in [0, total_steps)") + if not 0 <= min_lr <= base_lr: + raise ValueError("Expected 0 <= min_lr <= base_lr") + if warmup_steps and step < warmup_steps: + return base_lr * (step + 1) / warmup_steps + progress = (step - warmup_steps) / max(total_steps - warmup_steps - 1, 1) + progress = min(max(progress, 0.0), 1.0) + cosine = 0.5 * (1.0 + math.cos(math.pi * progress)) + return min_lr + (base_lr - min_lr) * cosine diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/test_contract.py b/home/wuyifan/a7_rotation_fix_20260930_code/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..68b938b2aa050e510e544ed06105a08bb428ef15 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/test_contract.py @@ -0,0 +1,61 @@ +from collections import Counter +from pathlib import Path +import sqlite3 +import tempfile +import unittest + +from coverage_sampler import CoverageSampler, SOURCES +from preflight_index import tile_starts + + +class IndexTests(unittest.TestCase): + def test_tail_covers_every_frame_without_duplicates_at_start(self): + for length in range(8, 100): + starts = tile_starts(length) + self.assertEqual(starts[0], 0) + self.assertEqual(len(starts), (length + 7) // 8) + self.assertEqual(set().union(*(set(range(s, s + 8)) for s in starts)), set(range(length))) + + +class SamplerTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.index = Path(self.temp.name) / "index.sqlite" + with sqlite3.connect(self.index) as connection: + connection.execute("CREATE TABLE tiles(source TEXT, recording_id TEXT, tile_id TEXT)") + for source in SOURCES: + for recording in range(2): + for tile in range(5): + connection.execute( + "INSERT INTO tiles VALUES (?,?,?)", + (source, f"{source}-{recording}", f"{source}-{recording}-{tile}"), + ) + + def test_quota_resume_ddp_and_no_replacement(self): + sampler = CoverageSampler(self.index, "S1_S3") + first = [sampler.sample(pos) for pos in range(200)] + self.assertEqual(Counter(row["source"] for row in first), + Counter({"H2O": 80, "ARCTIC": 70, "HOT3D": 50})) + for source in SOURCES: + source_rows = [row for row in first if row["source"] == source] + self.assertEqual(len({row["tile_id"] for row in source_rows[:10]}), 10) + resumed = CoverageSampler(self.index, "S1_S3") + self.assertEqual(first[43:], [resumed.sample(pos) for pos in range(43, 200)]) + shards = [CoverageSampler(self.index, "S1_S3") for _ in range(6)] + merged = sorted((row for rank, item in enumerate(shards) + for row in item.shard(0, 200, rank, 6)), + key=lambda row: row["position"]) + self.assertEqual(first, merged) + + def test_s4_has_separate_ledger_and_modes(self): + sampler = CoverageSampler(self.index, "S4") + first = [sampler.sample(pos) for pos in range(200)] + self.assertEqual(Counter(row["source"] for row in first), + Counter({"H2O": 70, "ARCTIC": 50, "HOT3D": 80})) + self.assertTrue(all(row["mode"] != "rgb_depth_k" for row in first + if row["source"] != "H2O")) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/test_hot3d_rotation.py b/home/wuyifan/a7_rotation_fix_20260930_code/test_hot3d_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..70352220213018fe79a2540793fd9bfd46df2014 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/test_hot3d_rotation.py @@ -0,0 +1,24 @@ +import unittest + +import numpy as np +from scipy.spatial.transform import Rotation +import torch + +from third_party.hot3d.data_loaders.rotation_compat import matrix_to_axis_angle + + +class Hot3dRotationTests(unittest.TestCase): + def test_roundtrip_including_singular_angles(self): + values = np.array([ + [0.0, 0.0, 0.0], [1e-8, 0.0, 0.0], [0.4, -1.2, 2.1], + [np.pi - 1e-8, 0.0, 0.0], [0.0, np.pi, 0.0], + ]) + for value in values: + matrix = Rotation.from_rotvec(value).as_matrix() + recovered = matrix_to_axis_angle(torch.tensor(matrix, dtype=torch.float64)).numpy() + error = (Rotation.from_rotvec(recovered).inv() * Rotation.from_matrix(matrix)).magnitude() + self.assertLess(error, 1e-8) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/test_rotation_pi.py b/home/wuyifan/a7_rotation_fix_20260930_code/test_rotation_pi.py new file mode 100644 index 0000000000000000000000000000000000000000..32247982bb73ce1509133204f3474feff7bd9b88 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/test_rotation_pi.py @@ -0,0 +1,38 @@ +"""Regression checks for near-pi matrix-to-axis-angle conversion.""" + +import math + +import torch + +from foundation_hand.geometry.rotations import axis_angle_to_matrix, matrix_to_axis_angle + + +def test_matrix_axis_angle_roundtrip_random_and_near_pi(): + torch.manual_seed(20260930) + for dtype, tolerance in ((torch.float64, 1e-10), (torch.float32, 3e-6)): + axes = torch.nn.functional.normalize(torch.randn(10000, 3, dtype=dtype), dim=-1) + angles = torch.rand(10000, 1, dtype=dtype) * math.pi + angles[:100] = math.pi - 1e-6 + angles[100:200] = math.pi - 1e-4 + angles[200:300] = 0 + matrices = axis_angle_to_matrix(axes * angles) + restored = axis_angle_to_matrix(matrix_to_axis_angle(matrices)) + assert torch.isfinite(restored).all() + assert float((restored - matrices).abs().max()) < tolerance + + +def test_matrix_axis_angle_gradients_identity_and_near_pi(): + axes = torch.nn.functional.normalize(torch.tensor([[0.3, -0.7, 0.2]], dtype=torch.float64), dim=-1) + values = torch.cat((torch.zeros(1, 3, dtype=torch.float64), axes * (math.pi - 1e-5)), dim=0) + matrices = axis_angle_to_matrix(values).detach().requires_grad_() + vector = matrix_to_axis_angle(matrices) + vector.square().sum().backward() + assert torch.isfinite(vector).all() + assert torch.isfinite(matrices.grad).all() + + +def test_near_pi_arbitrary_axis(): + axis = torch.nn.functional.normalize(torch.tensor([0.37, 0.48, -0.79], dtype=torch.float64), dim=-1) + matrix = axis_angle_to_matrix(axis * (math.pi - 1e-5)) + recovered = matrix_to_axis_angle(matrix) + assert float((axis_angle_to_matrix(recovered) - matrix).abs().max()) < 1e-10 diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/tests/test_hot3d_supervision_masks.py b/home/wuyifan/a7_rotation_fix_20260930_code/tests/test_hot3d_supervision_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..78e1e20c79e447348dc12d5a5aea09852d83562f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/tests/test_hot3d_supervision_masks.py @@ -0,0 +1,89 @@ +import torch + +from foundation_hand.data.hot3d_dataset import ( + hot3d_supervision_masks, + quest_linear_camera_calibration, +) + + +def test_visible_mesh_keeps_full_3d_but_masks_offscreen_2d() -> None: + K = torch.tensor([[[100.0, 0.0, 50.0], [0.0, 100.0, 50.0], [0.0, 0.0, 1.0]]]) + source_vertices = torch.tensor([[ + [[0.0, 0.0, 1.0], [1.0, 0.0, 1.0]], + [[2.0, 0.0, 1.0], [3.0, 0.0, 1.0]], + ]]) + joint2d = torch.full((1, 2, 21, 2), 50.0) + joint2d[0, 0, 1] = torch.tensor([150.0, 50.0]) + joint2d[0, 0, 3] = torch.tensor([8_000_000.0, 50.0]) + errors = torch.zeros((1, 2, 21)) + errors[0, 0, 2] = 3.0 + errors[0, 0, 4] = float("nan") + + hand, joint2d_mask, joint3d_mask = hot3d_supervision_masks( + torch.ones((1, 2), dtype=torch.bool), source_vertices, joint2d, + torch.ones((1, 2, 21), dtype=torch.bool), errors, K, (100, 100), + ) + + assert hand.tolist() == [[True, False]] + assert joint2d_mask[0, 0, :5].tolist() == [True, False, False, False, False] + assert not joint2d_mask[0, 1].any() + assert joint3d_mask[0, 0].all() + assert not joint3d_mask[0, 1].any() + + +def test_missing_geometry_remains_invalid_even_when_mesh_projects_inside() -> None: + K = torch.eye(3).unsqueeze(0) + source_vertices = torch.tensor([[[[0.0, 0.0, 1.0]], [[0.0, 0.0, 1.0]]]]) + joint2d = torch.zeros((1, 2, 21, 2)) + errors = torch.zeros((1, 2, 21)) + + hand, joint2d_mask, joint3d_mask = hot3d_supervision_masks( + torch.tensor([[False, True]]), source_vertices, joint2d, + torch.ones((1, 2, 21), dtype=torch.bool), errors, K, (100, 100), + ) + + assert hand.tolist() == [[False, True]] + assert not joint2d_mask[0, 0].any() + assert not joint3d_mask[0, 0].any() + assert joint2d_mask[0, 1].all() + assert joint3d_mask[0, 1].all() + + +def test_temporal_masks_are_independent_per_frame_and_hand() -> None: + K = torch.eye(3).repeat(8, 1, 1) + source_vertices = torch.tensor([[[[0.0, 0.0, 1.0]], [[2.0, 0.0, 1.0]]]]).repeat(8, 1, 1, 1) + source_vertices[1, 0, 0, 0] = 2.0 + source_vertices[1, 1, 0, 0] = 0.0 + joint2d = torch.zeros((8, 2, 21, 2)) + errors = torch.zeros((8, 2, 21)) + + hand, joint2d_mask, joint3d_mask = hot3d_supervision_masks( + torch.ones((8, 2), dtype=torch.bool), source_vertices, joint2d, + torch.ones((8, 2, 21), dtype=torch.bool), errors, K, (1, 1), + ) + + assert hand[0].tolist() == [True, False] + assert hand[1].tolist() == [False, True] + assert hand[2:].tolist() == [[True, False]] * 6 + assert torch.equal(joint2d_mask, joint3d_mask) + + +def test_quest_rectification_preserves_native_camera_extrinsic() -> None: + linear_model, native_model = object(), object() + native_transform, identity_transform = object(), object() + linear_calibration, native_calibration = object(), object() + + class Device: + def get_camera_calibration(self, stream_id, camera_model): + assert stream_id == "camera" + if camera_model is native_model: + return native_transform, native_calibration + if camera_model is linear_model: + return identity_transform, linear_calibration + raise AssertionError("unexpected calibration model") + + transform, calibration = quest_linear_camera_calibration( + Device(), "camera", linear_model, native_model, + ) + assert transform is native_transform + assert calibration is linear_calibration diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/README.md b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/README.md new file mode 100644 index 0000000000000000000000000000000000000000..082f4c7ce9db928ac1089a0d8ea61ce5eef03a42 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/README.md @@ -0,0 +1,4 @@ +This run vendors the small HOT3D provider code from the read-only HaWoR checkout on G2. +Only its two `pytorch3d.transforms.matrix_to_axis_angle` calls are replaced with a +CPU-only SciPy rotvec conversion, which must pass near-identity and near-pi +round-trip tests. Source data and annotations are unchanged. diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/Hot3DVisualizer.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/Hot3DVisualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..0857105bdab063bf49095f980d0cfc32f6003d07 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/Hot3DVisualizer.py @@ -0,0 +1,656 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from typing import Dict, List, Optional + +import matplotlib.pyplot as plt + +import numpy as np +import rerun as rr # @manual + +from data_loaders.hand_common import LANDMARK_CONNECTIVITY +from data_loaders.headsets import Headset +from data_loaders.loader_object_library import ObjectLibrary +from projectaria_tools.core.stream_id import StreamId # @manual +from collections import defaultdict +import torch + +try: + from dataset_api import Hot3dDataProvider # @manual +except ImportError: + from hot3d.dataset_api import Hot3dDataProvider + +from data_loaders.HandDataProviderBase import ( # @manual + HandDataProviderBase, + HandPose3dCollectionWithDt, +) +from data_loaders.ObjectBox2dDataProvider import ( # @manual + ObjectBox2dCollectionWithDt, + ObjectBox2dProvider, +) + +from data_loaders.ObjectPose3dProvider import ( # @manual + ObjectPose3dCollectionWithDt, + ObjectPose3dProvider, +) + +from projectaria_tools.core.calibration import ( + CameraCalibration, + DeviceCalibration, + FISHEYE624, + LINEAR, +) +from projectaria_tools.core.mps import get_eyegaze_point_at_depth # @manual + +from projectaria_tools.core.mps.utils import ( # @manual + filter_points_from_confidence, + filter_points_from_count, +) + +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.sophus import SE3 # @manual +from projectaria_tools.utils.rerun_helpers import ( # @manual + AriaGlassesOutline, + ToTransform3D, +) + + +class Hot3DVisualizer: + + def __init__(self, hot3d_data_provider: Hot3dDataProvider) -> None: + + self._hot3d_data_provider = hot3d_data_provider + # Device calibration and Image stream data + self._device_data_provider = hot3d_data_provider.device_data_provider + # Data provider at time T (for device & objects & hand poses) + self._device_pose_provider = hot3d_data_provider.device_pose_data_provider + self._hand_data_provider = hot3d_data_provider.mano_hand_data_provider + self._object_pose_data_provider = hot3d_data_provider.object_pose_data_provider + self._object_box2d_data_provider = ( + hot3d_data_provider.object_box2d_data_provider + ) + # Object library + self._object_library = hot3d_data_provider.object_library + + # If required + # Retrieve a distinct color mapping for object bounding box to show consistent color across stream_ids + # - Use a Colormap for visualizing object bounding box + self._object_box2d_colors = None + if self._object_box2d_data_provider is not None: + color_map = plt.get_cmap("viridis") + self._object_box2d_colors = color_map( + np.linspace(0, 1, len(self._object_box2d_data_provider.object_uids)) + ) + + # Keep track of what 3D assets has been loaded/unloaded so we will load them only when needed + self._object_cache_status = {} + + # To be parametrized later + self._jpeg_quality = 75 + + def log_static_assets( + self, + image_stream_ids: List[StreamId], + disable_vis=False + ) -> None: + """ + Log all static assets (aka Timeless assets) + - assets that are immutable (but can still move if attached to a 3D Pose) + """ + + # Configure the world coordinate system to ease navigation + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + if not disable_vis: + rr.log("world", rr.ViewCoordinates.RIGHT_HAND_Z_UP, static=True) + else: + rr.log("world", rr.ViewCoordinates.RIGHT_HAND_Y_UP, static=True) + + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + ## for Aria devices, we use online calibration which is a dynamic asset + pass + elif self._hot3d_data_provider.get_device_type() is Headset.Quest3: + # For each of the stream ids we want to use, export the camera calibration (intrinsics and extrinsics) + for stream_id in image_stream_ids: + # + # Plot the camera configuration + [extrinsics, intrinsics] = ( + self._device_data_provider.get_camera_calibration(stream_id) + ) + Hot3DVisualizer.log_pose( + f"world/device/{stream_id}", extrinsics, static=True + ) + Hot3DVisualizer.log_calibration(f"world/device/{stream_id}", intrinsics) + + # Deal with Aria specifics + # - Glasses outline + # - Point cloud + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + if not disable_vis: + Hot3DVisualizer.log_aria_glasses( + "world/device/glasses_outline", + self._device_data_provider.get_device_calibration(), + ) + + # Point cloud (downsampled for visualization) + point_cloud = self._device_data_provider.get_point_cloud() + if point_cloud: + # Filter out low confidence points + threshold_invdep = 5e-4 + threshold_dep = 5e-4 + point_cloud = filter_points_from_confidence( + point_cloud, threshold_invdep, threshold_dep + ) + # Down sample points + points_data_down_sampled = filter_points_from_count( + point_cloud, 500_000 + ) + # Retrieve point position + point_positions = [it.position_world for it in points_data_down_sampled] + POINT_COLOR = [200, 200, 200] + if not disable_vis: + rr.log( + "world/points", + rr.Points3D(point_positions, colors=POINT_COLOR, radii=0.002), + static=True, + ) + + def log_dynamic_assets( + self, + stream_ids: List[StreamId], + timestamp_ns: int, + vertices_input = None, + disable_vis=False # to speed up exporting + ) -> None: + """ + Log dynamic assets: + I.e assets that are moving, such as: + - 3D assets + - Device pose + - Hands + - Object poses + - Image related specifics assets + - images (stream_ids) + - Object Bounding boxes + - Aria Eye Gaze + """ + dataset = defaultdict(list) + + # + ## Retrieve and log data that is not stream_id dependent (pure 3D data) + # + acceptable_time_delta = 0 + + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + # For each of the stream ids we want to use, export the camera calibration (intrinsics and extrinsics) + for stream_id in stream_ids: + # + # Plot the camera configuration + [extrinsics, intrinsics] = ( + self._device_data_provider.get_online_camera_calibration( + stream_id=stream_id, timestamp_ns=timestamp_ns + ) + ) + if str(stream_id) == '214-1': + ego_extrinsics = extrinsics.to_matrix() + # print(ego_extrinsics) + ego_focal = intrinsics.get_focal_lengths()[0] + if not disable_vis: + Hot3DVisualizer.log_pose(f"world/device/{stream_id}", extrinsics) + Hot3DVisualizer.log_calibration(f"world/device/{stream_id}", intrinsics) + + elif self._hot3d_data_provider.get_device_type() is Headset.Quest3: + ## for Quest devices we will use factory calibration which is a static asset + pass + + headset_pose3d_with_dt = None + if self._device_data_provider is not None: + headset_pose3d_with_dt = self._device_pose_provider.get_pose_at_timestamp( + timestamp_ns=timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + acceptable_time_delta=acceptable_time_delta, + ) + + hand_poses_with_dt = None + if self._hand_data_provider is not None: + hand_poses_with_dt = self._hand_data_provider.get_pose_at_timestamp( + timestamp_ns=timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + acceptable_time_delta=acceptable_time_delta, + ) + + if not disable_vis: + object_poses_with_dt = None + if self._object_pose_data_provider is not None: + object_poses_with_dt = ( + self._object_pose_data_provider.get_pose_at_timestamp( + timestamp_ns=timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + acceptable_time_delta=acceptable_time_delta, + ) + ) + + aria_eye_gaze_data = ( + self._device_data_provider.get_eye_gaze(timestamp_ns) + if self._hot3d_data_provider.get_device_type() is Headset.Aria + else None + ) + + # + ## Log Device pose + # + if headset_pose3d_with_dt is not None: + headset_pose3d = headset_pose3d_with_dt.pose3d + head_pose = headset_pose3d.T_world_device.to_matrix() + if not disable_vis: + Hot3DVisualizer.log_pose( + "world/device", headset_pose3d.T_world_device, static=False + ) + + # + ## Log Hand poses + # + rot_r, trans_r, pose_r, betas_r, rot_l, trans_l, pose_l, betas_l, vertices_r, vertices_l = Hot3DVisualizer.log_hands( + "world/hands", # /{handedness_label}/... will be added as necessary + self._hand_data_provider, + hand_poses_with_dt, + show_hand_mesh=True, + show_hand_vertices=False, + show_hand_landmarks=True, + vertices_inputs=vertices_input, + disable_vis=disable_vis + ) + + dataset['rot_r'].append(rot_r) + dataset['trans_r'].append(trans_r) # world-space translation + dataset['pose_r'].append(pose_r) + dataset['betas_r'].append(betas_r) + dataset['rot_l'].append(rot_l) + dataset['pose_l'].append(pose_l) + dataset['betas_l'].append(betas_l) + dataset['trans_l'].append(trans_l) # world-space translation + # dataset['vertices_r'].append(vertices_r) + # dataset['vertices_l'].append(vertices_l) + + + # + ## Log Object poses + # + if not disable_vis: + Hot3DVisualizer.log_object_poses( + "world/objects", + object_poses_with_dt, + self._object_pose_data_provider, + self._object_library, + self._object_cache_status, + ) + + # + ## Log stream dependent data + # + for stream_id in stream_ids: + # + ## Log Image data + # + + # Undistorted image (required if you want see reprojected 3D mesh on the images) + image_data = self._device_data_provider.get_undistorted_image( + timestamp_ns, stream_id + ) + if str(stream_id) == '214-1': + ego_image_cv2 = np.rot90(image_data[:, :, ::-1], -1) + # ego_image_cv2 = image_data[:, :, ::-1] + if not disable_vis: + if image_data is not None: + rr.log( + f"world/device/{stream_id}", + rr.Image(image_data).compress(jpeg_quality=self._jpeg_quality), + ) + + # Raw device images (required for object bounding box visualization) + image_data = self._device_data_provider.get_image(timestamp_ns, stream_id) + if image_data is not None: + rr.log( + f"world/device/{stream_id}_raw", + rr.Image(image_data).compress(jpeg_quality=self._jpeg_quality), + ) + + if ( + self._object_box2d_data_provider is not None + and stream_id in self._object_box2d_data_provider.stream_ids + ): + box2d_collection_with_dt = ( + self._object_box2d_data_provider.get_box2d_at_timestamp( + stream_id=stream_id, + timestamp_ns=timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + ) + ) + Hot3DVisualizer.log_object_bounding_boxes( + stream_id, + box2d_collection_with_dt, + self._object_box2d_data_provider, + self._object_library, + self._object_box2d_colors, + ) + + # + ## Eye Gaze image reprojection + # + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + + # We are showing EyeGaze reprojection only on the RGB image stream + if stream_id != StreamId("214-1"): + continue + + # Reproject EyeGaze for raw and pinhole images + camera_configurations = [FISHEYE624, LINEAR] + for camera_model in camera_configurations: + + eye_gaze_reprojection_data = ( + self._device_data_provider.get_eye_gaze_in_camera( + stream_id, timestamp_ns, camera_model=camera_model + ) + ) + if ( + eye_gaze_reprojection_data is None + or not eye_gaze_reprojection_data.any() + ): + continue + + label = ( + f"world/device/{stream_id}/eye-gaze_projection" + if camera_model == LINEAR + else f"world/device/{stream_id}_raw/eye-gaze_projection_raw" + ) + rr.log( + label, + rr.Points2D(eye_gaze_reprojection_data, radii=20), + # TODO consistent color and size depending of camera resolution + ) + # + ## Log device dependent remaining 3D data + # + + # Log 3D eye gaze + if not disable_vis: + if aria_eye_gaze_data is not None: + T_device_CPF = ( + self._device_data_provider.get_device_calibration().get_transform_device_cpf() + ) + # Compute eye_gaze vector at depth_m (30cm for a proxy 3D vector to display) + gaze_vector_in_cpf = get_eyegaze_point_at_depth( + aria_eye_gaze_data.yaw, aria_eye_gaze_data.pitch, depth_m=0.3 + ) + # Draw EyeGaze vector + rr.log( + "world/device/eye-gaze", + rr.Arrows3D( + origins=[T_device_CPF @ [0, 0, 0]], + vectors=[T_device_CPF @ gaze_vector_in_cpf], + ), + ) + if headset_pose3d_with_dt is None: + head_pose = None + return ego_image_cv2, head_pose, ego_extrinsics, ego_focal, dataset + + @staticmethod + def log_aria_glasses( + label: str, + device_calibration: DeviceCalibration, + use_cad_calibration: bool = True, + ) -> None: + ## Plot Project Aria Glasses outline (as lines) + aria_glasses_point_outline = AriaGlassesOutline( + device_calibration, use_cad_calibration + ) + rr.log(label, rr.LineStrips3D([aria_glasses_point_outline]), static=True) + + @staticmethod + def log_calibration( + label: str, + camera_calibration: CameraCalibration, + ) -> None: + rr.log( + label, + rr.Pinhole( + resolution=[ + camera_calibration.get_image_size()[0], + camera_calibration.get_image_size()[1], + ], + focal_length=float(camera_calibration.get_focal_lengths()[0]), + ), + static=True, + ) + + @staticmethod + def log_pose(label: str, pose: SE3, static=False) -> None: + rr.log(label, ToTransform3D(pose, False), static=static) + + @staticmethod + def log_hands( + label: str, + hand_data_provider: HandDataProviderBase, + hand_poses_with_dt: HandPose3dCollectionWithDt, + show_hand_mesh=True, + show_hand_vertices=True, + show_hand_landmarks=True, + vertices_inputs=None, + disable_vis=False + ): + logged_right_hand_data = False + logged_left_hand_data = False + rot_r, trans_r, pose_r, betas_r, rot_l, trans_l, pose_l, betas_l, vertices_r, vertices_l = torch.zeros([3]), torch.zeros([3]), torch.zeros([45]), torch.zeros([10]), torch.zeros([3]), torch.zeros([3]), torch.zeros([45]), torch.zeros([10]), torch.zeros([778, 3]), torch.zeros([778, 3]) + + if hand_poses_with_dt is None: + return rot_r, trans_r, pose_r, betas_r, rot_l, trans_l, pose_l, betas_l, vertices_r, vertices_l + hand_pose_collection = hand_poses_with_dt.pose3d_collection + + for hand_pose_data in hand_pose_collection.poses.values(): + + if hand_pose_data.is_left_hand(): + logged_left_hand_data = True + elif hand_pose_data.is_right_hand(): + logged_right_hand_data = True + + handedness_label = hand_pose_data.handedness_label() + + # Skeleton/Joints landmark representation + if show_hand_landmarks: + hand_landmarks, out_rot, out_trans, out_pose, out_betas = hand_data_provider.get_hand_landmarks(hand_pose_data) + # convert landmarks to connected lines for display + # (i.e retrieve points along the HAND LANDMARK_CONNECTIVITY as a list) + points = [ + connections + for connectivity in LANDMARK_CONNECTIVITY + for connections in [ + [hand_landmarks[it].numpy().tolist() for it in connectivity] + ] + ] + if handedness_label == 'right': + rot_r, trans_r, pose_r, betas_r = out_rot, out_trans, out_pose, out_betas + elif handedness_label == 'left': + rot_l, trans_l, pose_l, betas_l = out_rot, out_trans, out_pose, out_betas + else: + raise NotImplementedError + # rr.log( + # f"{label}/{handedness_label}/joints", + # rr.LineStrips3D(points, radii=0.002), + # ) + + # Update mesh vertices if required + hand_mesh_vertices = ( + hand_data_provider.get_hand_mesh_vertices(hand_pose_data) + if show_hand_vertices or show_hand_mesh + else None + ) + if not vertices_inputs is None: + if handedness_label == 'right': + hand_mesh_vertices = vertices_inputs[1] + else: + hand_mesh_vertices = vertices_inputs[0] + + if handedness_label == 'right': + vertices_r = hand_mesh_vertices + else: + vertices_l = hand_mesh_vertices + + if not disable_vis: + + # Vertices representation + if show_hand_vertices: + rr.log( + f"{label}/{handedness_label}/mesh", + rr.Points3D(hand_mesh_vertices), + ) + + # Triangular Mesh representation + if show_hand_mesh: + [hand_triangles, hand_vertex_normals] = ( + hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose_data) + ) + rr.log( + f"{label}/{handedness_label}/mesh_faces", + rr.Mesh3D( + vertex_positions=hand_mesh_vertices, + vertex_normals=hand_vertex_normals, + triangle_indices=hand_triangles, # TODO: we could avoid sending this list if we want to save memory + ), + ) + if not disable_vis: + # If some hand data has not been logged, do not show it in the visualizer + if logged_left_hand_data is False: + rr.log(f"{label}/left", rr.Clear.recursive()) + if logged_right_hand_data is False: + rr.log(f"{label}/right", rr.Clear.recursive()) + + return rot_r, trans_r, pose_r, betas_r, rot_l, trans_l, pose_l, betas_l, vertices_r, vertices_l + + @staticmethod + def log_object_poses( + label: str, # "world/objects", + object_poses_with_dt: ObjectPose3dCollectionWithDt, + object_pose_data_provider: ObjectPose3dProvider, + object_library: ObjectLibrary, + object_cache_status: Dict[int, bool], + ): + if object_poses_with_dt is None: + return + + objects_pose3d_collection = object_poses_with_dt.pose3d_collection + + # Keep a mapping to know what object has been seen, and which one has not + object_uids = object_pose_data_provider.object_uids_with_poses + logging_status = {x: False for x in object_uids} + + for ( + object_uid, + object_pose3d, + ) in objects_pose3d_collection.poses.items(): + + object_name = object_library.object_id_to_name_dict[object_uid] + object_name = object_name + "_" + str(object_uid) + object_cad_asset_filepath = ObjectLibrary.get_cad_asset_path( + object_library_folderpath=object_library.asset_folder_name, + object_id=object_uid, + ) + + Hot3DVisualizer.log_pose( + f"world/objects/{object_name}", + object_pose3d.T_world_object, + False, + ) + # Mark object has been seen + logging_status[object_uid] = True + + # Link the corresponding 3D object + if object_uid not in object_cache_status.keys(): + object_cache_status[object_uid] = True + rr.log( + f"world/objects/{object_name}", + rr.Asset3D( + path=object_cad_asset_filepath, + ), + ) + + # If some object are not visible, we clear the entity (last known mesh and pose will not be displayed) + for object_uid, displayed in logging_status.items(): + if not displayed: + object_name = object_library.object_id_to_name_dict[object_uid] + object_name = object_name + "_" + str(object_uid) + rr.log( + f"world/objects/{object_name}", + rr.Clear.recursive(), + ) + if object_uid in object_cache_status.keys(): + del object_cache_status[object_uid] # We will log the mesh again + + @staticmethod + def log_object_bounding_boxes( + stream_id: StreamId, + box2d_collection_with_dt: Optional[ObjectBox2dCollectionWithDt], + object_box2d_data_provider: ObjectBox2dProvider, + object_library: ObjectLibrary, + bbox_colors: np.ndarray, + ): + """ + Object bounding boxes (valid for native raw images). + - We assume that the image corresponding to the stream_id has been logged beforehand as 'world/device/{stream_id}_raw/' + """ + + # Keep a mapping to know what object has been seen, and which one has not + object_uids = list(object_box2d_data_provider.object_uids) + logging_status = {x: False for x in object_uids} + + if ( + box2d_collection_with_dt is None + or box2d_collection_with_dt.box2d_collection is None + ): + # No bounding box are retrieved, we clear all the bounding box visualization existing so far + rr.log(f"world/device/{stream_id}_raw/bbox", rr.Clear.recursive()) + return + + object_uids_at_query_timestamp = ( + box2d_collection_with_dt.box2d_collection.object_uid_list + ) + + for object_uid in object_uids_at_query_timestamp: + object_name = object_library.object_id_to_name_dict[object_uid] + axis_aligned_box2d = box2d_collection_with_dt.box2d_collection.box2ds[ + object_uid + ] + box = axis_aligned_box2d.box2d + if box is None: + continue + + logging_status[object_uid] = True + rr.log( + f"world/device/{stream_id}_raw/bbox/{object_name}", + rr.Boxes2D( + mins=[box.left, box.top], + sizes=[box.width, box.height], + colors=bbox_colors[object_uids.index(object_uid)], + ), + ) + # If some object are not visible, we clear the bounding box visualization + for key, value in logging_status.items(): + if not value: + object_name = object_library.object_id_to_name_dict[key] + rr.log( + f"world/device/{stream_id}_raw/bbox/{object_name}", + rr.Clear.flat(), + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/dataset_download_status_manager.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/dataset_download_status_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..03da5d69c43ee016dc847ef6ed1c45ca64536d2c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/dataset_download_status_manager.py @@ -0,0 +1,53 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import json +from typing import Final, List + +DOWNLOAD_STATUS_FILE: Final[str] = ".download_status.json" + + +class DatasetDownloadStatusManager: + def __init__(self, data_groups: List[str]): + self.status = {data_group: False for data_group in data_groups} + + # Read status file from json and assign to status + def from_json(self, json_path: str) -> None: + try: + with open(json_path, "r") as f: + data = json.load(f) + for expected_data_group in self.status: + if expected_data_group not in data: + error = f"{DOWNLOAD_STATUS_FILE} is missing data group {expected_data_group}.\n" + error += f"Your data may be out of date, try clearing {DOWNLOAD_STATUS_FILE} in your sequence path" + raise Exception(error) + self.status = data + except Exception as e: + print(f"[warning]: cannot read status json. {e}") + + def to_json(self, json_path: str): + try: + json_object = json.dumps(self.status, indent=4) + with open(json_path, "w") as outfile: + outfile.write(json_object) + except Exception as e: + print(f"[warning]: can not write status json. {e}") + + def set_download_status(self, data_type: str, value: bool): + if data_type not in self.status: + raise Exception(f"data type {data_type} is not supported") + self.status[data_type] = value + + def get_download_status(self, data_type: str) -> bool: + return self.status[data_type] diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/dataset_downloader_base.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/dataset_downloader_base.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a2eeea27aa6e1ee0cd55dd86d6c1e6dfd1417f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/dataset_downloader_base.py @@ -0,0 +1,283 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import hashlib +import json +import os +import shutil +import tempfile +from pathlib import Path +from typing import List, Optional, Tuple +from zipfile import is_zipfile, ZipFile + +import requests + +from dataset_download_status_manager import ( + DatasetDownloadStatusManager, + DOWNLOAD_STATUS_FILE, +) + +from requests.adapters import HTTPAdapter +from requests.packages.urllib3.util.retry import Retry +from tqdm import tqdm +from utils import load_data_groups_from_cdn + +CHUCK_SIZE_BYTE = 8192 +STATUS_CODE_DEFAULT = 404 + + +DATA_TYPE_TO_SAVE_PATH = { + "mps_eye_gaze": os.path.join("mps", "eye_gaze"), + "mps_slam_trajectories": os.path.join("mps", "slam"), + "mps_slam_points": os.path.join("mps", "slam"), + "mps_slam_calibration": os.path.join("mps", "slam"), + "mps_slam_summary": os.path.join("mps", "slam"), + "mps_hand_tracking": os.path.join("mps", "hand_tracking"), +} + + +def calculate_file_sha1(file_path: str) -> str: + sha1 = hashlib.sha1() + with open(file_path, "rb") as file: + chunk = file.read(4096) # Read the file in 4KB chunks + while chunk: + sha1.update(chunk) + chunk = file.read(4096) + + sha1_sum = sha1.hexdigest() + return sha1_sum + + +class DatasetDownloaderBase: + __KEY_URL: str = "download_url" + __KEY_FILENAME: str = "filename" + __KEY_CHECKSUM: str = "sha1sum" + + def __init__( + self, + cdn_file: str, + data_types: List[str], + sequences: Optional[List[str]] = None, + overwrite: bool = True, + ): + + # add slam summary if any slam data is requested + if "mps_slam_summary" not in data_types: + if ( + "mps_slam_trajectories" in data_types + or "mps_slam_calibration" in data_types + or "mps_slam_points" in data_types + ): + data_types.append("mps_slam_summary") + + self.data_types_selected = data_types + self.overwrite = overwrite + + # load cdn file + with open(cdn_file, "r") as f: + cdn_file_data = json.load(f) + if "sequences" not in cdn_file_data: + raise Exception("invalid cdn_file, missing key: sequences") + self.sequences_data = cdn_file_data["sequences"] + if "sequence_config" not in cdn_file_data: + raise Exception("invalid cdn_file, missing key: sequence_config") + self.sequence_config = cdn_file_data["sequence_config"] + + self.sequences = sequences + if sequences is None: + self.sequences = self.__get_all_sequences() + + self.data_types_all = load_data_groups_from_cdn(cdn_file) + + def download_data(self, output_folder: str): + if not os.path.exists(output_folder): + print(f"Creating local output folder {output_folder}") + os.makedirs(output_folder) + + # download sequences + responses = {} + for sequence in self.sequences: + responses[sequence] = self.__download_sequence( + sequence=sequence, + output_folder=output_folder, + ) + num_success_sequences = sum(1 for sequence in responses if responses[sequence]) + print( + f"{num_success_sequences} of {len(self.sequences)} sequences are successfully downloaded" + ) + + def __download_sequence( + self, + sequence: str, + output_folder: str, + ) -> bool: + output_folder_seq = os.path.join(output_folder, sequence) + print(f"downloading sequence {sequence} to {output_folder_seq}") + + if sequence not in self.sequences_data: + print(f"sequence {sequence} is not available in the selected data group") + return False + + if not os.path.exists(output_folder_seq): + os.makedirs(output_folder_seq) + + # check last download status + status_manager = DatasetDownloadStatusManager(self.data_types_all) + status_json = os.path.join(output_folder_seq, DOWNLOAD_STATUS_FILE) + if os.path.exists(status_json): + status_manager.from_json(status_json) + + final_success = True + for data_type in self.data_types_selected: + # skip the data which has already been downloaded if overwrite is not set + if not self.overwrite and status_manager.get_download_status(data_type): + if data_type == 'hand_data' and not os.path.exists('output_folder_seq/mano_hand_pose_trajectory.jsonl'): + pass + else: + print(f"skip downloading datatype {data_type} since already downloaded") + continue + data_type_download_is_success = True + is_success, status_code = self.__download_data_from_url( + sequence=sequence, + data_type=data_type, + output_folder=output_folder_seq, + ) + if not is_success: + data_type_download_is_success = False + final_success = False + print(f"{data_type} is NOT downloaded with error code {status_code}") + + # log download status for each data_type + status_manager.set_download_status(data_type, data_type_download_is_success) + + # write the download status to json + status_manager.to_json(status_json) + return final_success + + def __download_data_from_url( + self, + sequence: str, + data_type: str, + output_folder: str, + ) -> Tuple[bool, int]: + status_code = STATUS_CODE_DEFAULT + is_success = True + sequence_data = self.sequences_data[sequence] + + if data_type not in sequence_data: + print(f"Data type {data_type} is not available for sequence: {sequence}") + return is_success, status_code + + network_link = sequence_data[data_type][self.__KEY_URL] + if not network_link: + print( + f"Url for sequence '{sequence}', data type '{data_type}' is not available" + ) + return is_success, status_code + + try: + with tempfile.TemporaryDirectory() as local_tmp_path: + download_filename = sequence_data[data_type][self.__KEY_FILENAME] + download_file_path = os.path.join(local_tmp_path, download_filename) + sha1sum = sequence_data[data_type][self.__KEY_CHECKSUM] + session = requests.Session() + # allow retry on errors of too many requests (429), internal server error (500), + # bad gateway (502), service unavailable (503), or gateway timeout (504) + + retries = Retry( + total=5, + backoff_factor=2, # final try is 2*(2**5) = 64 seconds + status_forcelist=[429, 500, 502, 503, 504], + ) + + session.mount("https://", HTTPAdapter(max_retries=retries)) + + with session.get(network_link, stream=True, timeout=10) as r: + # r.raise_for_status() + total_size_in_bytes = int(r.headers.get("content-length", 0)) + + _, _, free_disk_in_bytes = shutil.disk_usage("/") + if free_disk_in_bytes < total_size_in_bytes: + raise Exception( + f"Insufficient disk space for sequence '{sequence}' data type '{data_type}'. Required \ + {total_size_in_bytes} bytes, available {free_disk_in_bytes} bytes" + ) + with open(download_file_path, "wb") as f: + print(f"Serializing to {download_file_path}") + progress_bar = tqdm( + total=total_size_in_bytes, unit="iB", unit_scale=True + ) + for chunk in r.iter_content(chunk_size=CHUCK_SIZE_BYTE): + # serialize chunk of 8KB + progress_bar.update(len(chunk)) + f.write(chunk) + progress_bar.close() + status_code = r.status_code + # raise exception if download fails and skip the unzip part below + r.raise_for_status() + + calculated_checksum = calculate_file_sha1(download_file_path) + if sha1sum != calculated_checksum: + error = f"different checksum value for sequence '{sequence}' and data type '{data_type}'\n" + error += f"Calculated checksum: {calculated_checksum}, expected checksum: {sha1sum}" + raise Exception(error) + + if is_zipfile(download_file_path): + # unzip and reorganize + with ZipFile(download_file_path) as zip_ref: + unzipped_top_dir_name = sequence + unzipped_dir = os.path.join( + local_tmp_path, unzipped_top_dir_name + ) + if not os.path.exists(unzipped_dir): + os.makedirs(unzipped_dir) + + # MOVE MPS FILES + if data_type in DATA_TYPE_TO_SAVE_PATH.keys(): + zip_ref.extractall(output_folder) + for local_path in zip_ref.namelist(): + abs_path = os.path.join(output_folder, local_path) + if os.path.isfile(abs_path): + move_filename = os.path.basename(abs_path) + move_path = os.path.join( + Path(abs_path).parent, + DATA_TYPE_TO_SAVE_PATH[data_type], + ) + os.makedirs(move_path, exist_ok=True) + shutil.move( + abs_path, os.path.join(move_path, move_filename) + ) + else: + zip_ref.extractall(output_folder) + else: + output_filename = os.path.join(output_folder, download_filename) + if data_type == "main_vrs": + basename_old = os.path.basename(output_filename) + basename_new = "recording.vrs" + output_filename = output_filename.replace( + basename_old, basename_new + ) + shutil.copyfile( + download_file_path, + output_filename, + ) + except Exception as e: + # Handle request exceptions (e.g., ConnectionError, TooManyRedirects, etc.) + print(f"An error occurred: {e}. Status code: {status_code}") + is_success = False + + return is_success, status_code + + def __get_all_sequences(self) -> List[str]: + return list(self.sequences_data.keys()) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/dataset_downloader_base_main.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/dataset_downloader_base_main.py new file mode 100644 index 0000000000000000000000000000000000000000..6d22dd308a74bf4aa7b4f62c9b2823b577c67cf0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/dataset_downloader_base_main.py @@ -0,0 +1,141 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import argparse + +from dataset_downloader_base import DatasetDownloaderBase + +from utils import load_data_groups_from_cdn, load_sequences_list_from_cdn + + +def parse_args(): + parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument( + "-c", + "--cdn_file", + dest="cdn_file", + type=str, + required=True, + default=None, + help="input file listing the CDN urls", + ) + + parser.add_argument( + "-o", + "--output_folder", + dest="output_folder", + type=str, + required=True, + help="output folder for storing the downloaded dataset locally", + ) + + parser.add_argument( + "-w", + "--overwrite", + dest="overwrite", + action="store_true", + required=False, + default=False, + help=""" + If set, re-download and overwrite sequences which have been downloaded before + """, + ) + + parser.add_argument( + "-d", + "--data_types", + dest="data_types", + nargs="+", + required=False, + default=[], + help=""" + List (space separated) of data types to download for each sequence. + To get a list of all data types available for this dataset, leave this blank and it will list all options. + If not set, and IFF single data type exists, it will will be downloaded automatically", + """, + ) + + parser.add_argument( + "-l", + "--sequence_names", + dest="sequence_names", + nargs="+", + required=False, + help="a list of sequence names (separated by space) to be downloaded. If not set, all sequences will be downloaded", + ) + + return parser.parse_args() + + +def main(): + args = parse_args() + + all_data_groups = load_data_groups_from_cdn(args.cdn_file) + all_data_groups_list = list(all_data_groups.keys()) + # remove slam summary since this gets downloaded automatically if any slam data is requested + if "mps_slam_summary" in all_data_groups_list: + all_data_groups_list.remove("mps_slam_summary") + + # If sequence_names is specified as "all", retrieve all sequences from the CDN file + if len(args.sequence_names) == 1 and "all" in args.sequence_names: + args.sequence_names = load_sequences_list_from_cdn(args.cdn_file) + + # If data_types are not specified, ask the user to specify one + # If only one data type is available, automatically download it + if len(args.data_types) == 0 and len(all_data_groups_list) > 1: + print("-d(, --data_types) must be specified") + print("Available data types include:") + for i in range(len(all_data_groups_list)): + print(f"{i}: {all_data_groups_list[i]}") + exit(1) + elif len(all_data_groups_list) == 1: + args.data_types = [0] # Download the only existing data type available + elif "all" in args.data_types: + args.data_types = [i for i in range(len(all_data_groups_list))] + + data_types = [] + for input_data_type in args.data_types: + data_types.append(all_data_groups_list[int(input_data_type)]) + + if args.sequence_names is None: + download_all = ( + input( + """ + -l(, --sequence_names) is not specified. + Do you want to download all sequences? [y/n] + """ + ).lower() + == "y" + ) + if not download_all: + print("Please rerun the command with -l(, --sequence_names) specified.") + print( + "Here is the list of available sequences:\n", + load_sequences_list_from_cdn(args.cdn_file), + ) + exit(1) + else: + print(f"Downloading the following sequences: {args.sequence_names}") + + downloader = DatasetDownloaderBase( + cdn_file=args.cdn_file, + data_types=data_types, + sequences=args.sequence_names, + overwrite=args.overwrite, + ) + downloader.download_data(output_folder=args.output_folder) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/utils.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8497d012ac3d5f31dd8f1aa001e958f3f403c0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_downloader/utils.py @@ -0,0 +1,120 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import json +import os +from typing import Dict, Final, List + + +########################################################################### + +# We require AT LEAST ONE of these files for eye_gaze +MPS_EYE_GAZE_FILES_REQUIRED: Final[List[str]] = [ + "general_eye_gaze.csv", + "generalized_eye_gaze.csv", + "personalized_eye_gaze.csv", + "calibrated_eye_gaze.csv", +] + +MPS_EYE_GAZE_FILES: Final[List[str]] = MPS_EYE_GAZE_FILES_REQUIRED + ["summary.json"] + +# We requires ALL of these SLAM files +MPS_SLAM_FILES_REQUIRED: Final[List[str]] = [ + "closed_loop_trajectory.csv", + "open_loop_trajectory.csv", + "online_calibration.jsonl", + "semidense_observations.csv.gz", +] + +MPS_SLAM_FILES: Final[List[str]] = MPS_SLAM_FILES_REQUIRED + [ + "semidense_points.csv.gz", + "global_points.csv.gz", + "summary.json", +] + +MPS_FOLDER: Final[str] = "mps" +MPS_SLAM_FOLDER: Final[str] = "slam" +MPS_EYE_GAZE_FOLDER: Final[str] = "eye_gaze" + +MPS_SLAM_GROUP_FILES: Final[Dict[str, List[str]]] = { + "mps_slam_trajectories": [MPS_SLAM_FILES[0], MPS_SLAM_FILES[1]], + "mps_slam_calibration": [MPS_SLAM_FILES[2]], + "mps_slam_points": [ + MPS_SLAM_FILES[3], + MPS_SLAM_FILES[4], + MPS_SLAM_FILES[5], + ], + "mps_slam_summary": [MPS_SLAM_FILES[6]], +} +MPS_DATA_GROUP_FILES: Final[Dict[str, List[str]]] = { + **MPS_SLAM_GROUP_FILES, + **{ + "mps_eye_gaze": MPS_EYE_GAZE_FILES, + }, +} +########################################################################### + + +# Load the list of sequences listed from the cdn file +def load_sequences_list_from_cdn(cdn_file: str) -> List[str]: + if not os.path.exists(cdn_file): + raise Exception("CDN file does not exist") + + # load sequences from cdn file + sequences_list = [] + with open(cdn_file, "r") as f: + cdn_file_data = json.load(f) + if "sequences" not in cdn_file_data: + raise Exception("invalid cdn_file, missing key: sequences") + sequences_list = cdn_file_data["sequences"].keys() + return sequences_list + + +# Load a list of data group name to all files included in that data group +def load_data_groups_from_cdn(cdn_file: str) -> Dict[str, List[str]]: + if not os.path.exists(cdn_file): + raise Exception("CDN file does not exist") + + # load sequence_config from cdn file + sequence_config = {} + with open(cdn_file, "r") as f: + cdn_file_data = json.load(f) + if "sequence_config" not in cdn_file_data: + raise Exception("invalid cdn_file, missing key: sequence_config") + sequence_config = cdn_file_data["sequence_config"] + + data_groups = {} + + # load main vrs data group + if "main" not in sequence_config: + raise Exception("invalid cdn_file, missing key: sequence_config/main") + main_data = sequence_config["main"] + if "recording" not in main_data: + raise Exception("invalid cdn_file, missing key: sequence_config/main/recording") + + # Only add "recording" and "mps" data if they are defined as different than None + if main_data["recording"] != "None": + data_groups["main_vrs"] = main_data["recording"] + if main_data["mps"] != "None": + # next add mps data groups which are predefined + data_groups.update(MPS_DATA_GROUP_FILES) + + # load custom data groups for this dataset + if "data_groups" not in sequence_config: + raise Exception("invalid cdn_file, missing key: sequence_config/data_groups") + + for data_group, files in sequence_config["data_groups"].items(): + data_groups[data_group] = files + + return data_groups diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/AlignedBox2d.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/AlignedBox2d.py new file mode 100644 index 0000000000000000000000000000000000000000..617a9eb36f78a748bd806412e4fe9bc25ebb3b6a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/AlignedBox2d.py @@ -0,0 +1,156 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from __future__ import annotations + +import numpy as np + + +class AlignedBox2d: + """ + An 2D axis aligned box in floating point. + + Assumptions: + * The origin is at top-left corner + * `right` and `bottom` are not inclusive in the region, i.e. the width and + height can be simply calculated by `right - left` and `bottom - top`. + """ + + def __init__(self, left: float, top: float, right: float, bottom: float): + """Initializes the bounding box given (left, top, right, bottom)""" + self._left: float = left + self._top: float = top + self._right: float = right + self._bottom: float = bottom + + def __repr__(self): + return f"AlignedBox2d(left: {self._left}, top: {self._top}, right: {self._right}, bottom: {self._bottom})" + + @property + def left(self) -> float: + """Left of the aligned box on x-axis.""" + return self._left + + @property + def top(self) -> float: + """Top of the aligned box on y-axis.""" + return self._top + + @property + def right(self) -> float: + """Right of the aligned box on x-axis.""" + return self._right + + @property + def bottom(self) -> float: + """Bottom of the aligned box on y-axis.""" + return self._bottom + + @property + def width(self) -> float: + """Width of the aligned box. + + Returns: + Width computed by right - left + """ + return self.right - self.left + + @property + def height(self) -> float: + """Height of the aligned box. + + Returns: + Height computed by bottom - top + """ + return self.bottom - self.top + + def pad(self, width: float, height: float) -> AlignedBox2d: + """Pads the region by extending `width` and `height` on four sides. + + Args: + width (float): length to pad on left and right sides + height (float): length to pad on top and bottom sides + Returns: + a new AlignedBox2d object with padded region + """ + return AlignedBox2d( + self.left - width, + self.top - height, + self.right + width, + self.bottom + height, + ) + + def array_ltrb(self) -> np.ndarray: + """Converts the box into a float np.ndarray of shape (4,): (left, top, right, bottom). + + Returns: + a float np.ndarray of shape (4,) representing (left, top, right, bottom) + """ + return np.array([self.left, self.top, self.right, self.bottom]) + + def array_ltwh(self) -> np.ndarray: + """Converts the box into a float np.ndarray of shape (4,): (left, top, width, height). + + Returns: + a float np.ndarray of shape (4,) representing (left, top, width, height) + """ + return np.array([self.left, self.top, self.width, self.height]) + + def int_array_ltrb(self) -> np.ndarray: + """Converts the box into an int np.ndarray of shape (4,): (left, top, width, height). + + Returns: + an int np.ndarray of shape (4,) representing (left, top, right, bottom) + """ + return self.array_ltrb().astype(int) + + def int_array_ltwh(self) -> np.ndarray: + """Converts the box into an int np.ndarray of shape (4,): (left, top, width, height). + + Returns: + an int np.ndarray of shape (4,) representing (left, top, width, height) + """ + return self.array_ltwh().astype(int) + + def round(self) -> AlignedBox2d: + """Rounds the float values to int. + + Returns: + a new AlignedBox2d object with rounded values (still float) + """ + return AlignedBox2d( + np.round(self.left), + np.round(self.top), + np.round(self.right), + np.round(self.bottom), + ) + + def clip(self, boundary: AlignedBox2d) -> AlignedBox2d: + """Clips the region by the boundary + + Args: + boundary (AlignedBox2d): boundary of box to be clipped + (boundary.left: minimum left / right value, + boundary.top: minimum top / bottom value, + boundary.right: maximum left / right value, + boundary.bottom: maximum top / bottom value) + Returns: + a new clipped AlignedBox2d object + """ + return AlignedBox2d( + min(max(self.left, boundary.left), boundary.right), + min(max(self.top, boundary.top), boundary.bottom), + min(max(self.right, boundary.left), boundary.right), + min(max(self.bottom, boundary.top), boundary.bottom), + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/AriaDataProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/AriaDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe3bd30a62796ec01fd6b8230ec97adf6503758 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/AriaDataProvider.py @@ -0,0 +1,337 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +from typing import List, Optional + +import numpy as np + +from projectaria_tools.core import data_provider # @manual +from projectaria_tools.core.calibration import ( # @manual + CameraCalibration, + DeviceCalibration, + distort_by_calibration, + FISHEYE624, + get_linear_camera_calibration, + LINEAR, +) +from projectaria_tools.core.mps import ( # @manual + EyeGaze, + get_eyegaze_point_at_depth, + MpsDataPathsProvider, + MpsDataProvider, +) +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.sophus import SE3 # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + + +class AriaDataProvider: + + def __init__( + self, vrs_filepath: str, mps_folder_path: Optional[str] = None + ) -> None: + self._vrs_data_provider = data_provider.create_vrs_data_provider(vrs_filepath) + + # MPS data provider + if mps_folder_path is not None and os.path.exists(mps_folder_path): + mps_data_paths_provider = MpsDataPathsProvider(mps_folder_path) + mps_data_paths = mps_data_paths_provider.get_data_paths() + self._mps_data_provider = MpsDataProvider(mps_data_paths) + print(mps_data_paths) + else: + self._mps_data_provider = None + + def get_image_stream_ids(self) -> List[StreamId]: + # retrieve all streams ids and filter the one that are image based + stream_ids = self._vrs_data_provider.get_all_streams() + image_stream_ids = [ + p + for p in stream_ids + if self._vrs_data_provider.get_label_from_stream_id(p).startswith("camera-") + ] + return image_stream_ids + + def get_sequence_timestamps( + self, + stream_id: StreamId = StreamId("214-1"), + time_domain: TimeDomain = TimeDomain.TIME_CODE, + ) -> List[int]: + """ + Returns the list of "time code" timestamp for the sequence + """ + return self._vrs_data_provider.get_timestamps_ns(stream_id, time_domain) + + def get_image_stream_label(self, stream_id: StreamId) -> str: + return self._vrs_data_provider.get_label_from_stream_id(stream_id) + + def get_image(self, timestamp_ns: int, stream_id: StreamId) -> np.ndarray: + image = self._vrs_data_provider.get_image_data_by_time_ns( + stream_id, + timestamp_ns, + TimeDomain.TIME_CODE, + TimeQueryOptions.CLOSEST, + ) + return image[0].to_numpy_array() + + def get_undistorted_image( + self, timestamp_ns: int, stream_id: StreamId + ) -> np.ndarray: + image = self.get_image(timestamp_ns, stream_id) + + [T_device_camera, native_camera_online_calibration] = ( + self.get_online_camera_calibration( + stream_id, timestamp_ns=timestamp_ns, camera_model=FISHEYE624 + ) + ) + [T_device_camera, pinhole_camera_online_calibration] = ( + self.get_online_camera_calibration( + stream_id, timestamp_ns=timestamp_ns, camera_model=LINEAR + ) + ) + + # Compute the actual undistorted image + undistorted_image = distort_by_calibration( + image, pinhole_camera_online_calibration, native_camera_online_calibration + ) + + return undistorted_image + + def get_device_calibration(self) -> DeviceCalibration: + """ + Return the device calibration (factory calibration of all sensors) + """ + return self._vrs_data_provider.get_device_calibration() + + def get_camera_calibration( + self, + stream_id: StreamId, + camera_model=FISHEYE624, + ) -> tuple[SE3, CameraCalibration]: + """ + Return the camera calibration of the device of the sequence as [Extrinsics, Intrinsics] + Note: + - A corresponding pinhole camera can be requested by using camera_model = LINEAR. + - This is the camera model used to generate the 'get_undistorted_image'. + """ + if not (camera_model is FISHEYE624 or camera_model is LINEAR): + raise ValueError( + "Invalid camera_model type, only FISHEYE624 and LINEAR are supported" + ) + + device_calibration = self.get_device_calibration() + stream_label = self._vrs_data_provider.get_label_from_stream_id(stream_id) + camera_calibration = device_calibration.get_camera_calib(stream_label) + + # If a corresponding pinhole camera is requested, we build one on the fly + if camera_model == LINEAR: + focal_lengths = camera_calibration.get_focal_lengths() + image_size = camera_calibration.get_image_size() + camera_calibration = get_linear_camera_calibration( + image_size[0], image_size[1], focal_lengths[0] + ) + # else return the native FISHEYE624 camera model + + T_device_camera = camera_calibration.get_transform_device_camera() + return [T_device_camera, camera_calibration] + + def get_online_camera_calibration( + self, + stream_id: StreamId, + timestamp_ns: Optional[int], + time_domain: TimeDomain = TimeDomain.TIME_CODE, + camera_model=FISHEYE624, + ) -> tuple[SE3, CameraCalibration]: + """ + Return the camera calibration of the device of the sequence as [Extrinsics, Intrinsics] + Note: + - A corresponding pinhole camera can be requested by using camera_model = LINEAR. + - This is the camera model used to generate the 'get_undistorted_image'. + """ + if not (camera_model is FISHEYE624 or camera_model is LINEAR): + raise ValueError( + "Invalid camera_model type, only FISHEYE624 and LINEAR are supported" + ) + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError( + f"{time_domain} is not supported. Only TIME_CODE is supported" + ) + + device_timestamp_ns = ( + self._vrs_data_provider.convert_from_timecode_to_device_time_ns( + timestamp_ns + ) + ) + online_calibration = self._mps_data_provider.get_online_calibration( + device_timestamp_ns=device_timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + ) + camera_calibs = online_calibration.camera_calibs + + stream_label = self._vrs_data_provider.get_label_from_stream_id(stream_id) + camera_calib = [c for c in camera_calibs if c.get_label() == stream_label] + if len(camera_calib) == 0: + raise ValueError( + f"camera_calib not found for stream_label: {stream_label} stream_id: {stream_id} at timestamp_ns: {timestamp_ns}" + ) + camera_calibration = camera_calib[0] + + ## Fix the image size to correspond to the image saved in the vrs. + ## The calibration returned by mps_data_provider has hardcoded image sizes which are incorrect. + [_, native_camera_calibration] = self.get_camera_calibration( + stream_id, camera_model=camera_model + ) + camera_calibration = CameraCalibration( + camera_calibration.get_label(), + camera_model, + camera_calibration.projection_params(), + camera_calibration.get_transform_device_camera(), + native_camera_calibration.get_image_size()[0], ## correct the image size + native_camera_calibration.get_image_size()[1], + camera_calibration.get_valid_radius(), + camera_calibration.get_max_solid_angle(), + camera_calibration.get_serial_number(), + ) + # Store the relative transform from device to camera + T_device_camera = camera_calibration.get_transform_device_camera() + + # If a corresponding pinhole camera is requested, we build one on the fly + if camera_model == LINEAR: + focal_lengths = camera_calibration.get_focal_lengths() + image_size = camera_calibration.get_image_size() + camera_calibration = get_linear_camera_calibration( + image_size[0], image_size[1], focal_lengths[0] + ) + # Info: transform_device_camera is set to ID in this path in the camera_calibration + # else return the native FISHEYE624 camera model + + return [T_device_camera, camera_calibration] + + def _timestamp_convert( + self, timestamp: int, time_domain_in: TimeDomain, time_domain_out: TimeDomain + ) -> int: + """ + Returns the converted timestamp between two domains (TimeCode <-> Aria DeviceTime) + """ + if ( + self._vrs_data_provider + and time_domain_in == TimeDomain.TIME_CODE + and time_domain_out == TimeDomain.DEVICE_TIME + ): + # Map to corresponding timestamp + device_timestamp_ns = ( + self._vrs_data_provider.convert_from_timecode_to_device_time_ns( + timestamp + ) + ) + return device_timestamp_ns + return None + + ### + # Add MPS data specifics + ### + + def get_point_cloud(self) -> Optional[np.ndarray]: + """ + Return the point cloud of the scene + """ + if self._mps_data_provider is None: + return None + if self._mps_data_provider.has_semidense_point_cloud(): + point_cloud_data = self._mps_data_provider.get_semidense_point_cloud() + # Point cloud filtering is left to the user + return point_cloud_data + + return None + + def _get_gaze_vector_reprojection( + self, + eye_gaze: EyeGaze, + stream_id_label: str, + device_calibration: DeviceCalibration, + camera_calibration: CameraCalibration, + ) -> np.ndarray: + """ + Helper function to project a eye gaze output onto a given image and its calibration, assuming specified fixed depth + """ + gaze_center_in_cpf = get_eyegaze_point_at_depth( + eye_gaze.yaw, eye_gaze.pitch, depth_m=eye_gaze.depth or 1.0 + ) + transform_device_cpf = device_calibration.get_transform_device_cpf() + transform_device_camera = device_calibration.get_transform_device_sensor( + stream_id_label, True + ) + # We use CAD value (this is the coordinate system used by the Eye Gaze model prediction) + # Using factory calibration (i.e CAD = False) would lead to less accurate EyeGaze reprojection. + transform_camera_cpf = transform_device_camera.inverse() @ transform_device_cpf + gaze_center_in_camera = transform_camera_cpf @ gaze_center_in_cpf + gaze_center_in_pixels = camera_calibration.project(gaze_center_in_camera) + return gaze_center_in_pixels + + def get_eye_gaze_in_camera( + self, + stream_id: StreamId, + timestamp_ns: int, + time_domain: TimeDomain = TimeDomain.TIME_CODE, + camera_model=FISHEYE624, + ): + """ + Return the eye_gaze at the given timestamp projected in the given stream for the given time_domain + """ + if not (camera_model is FISHEYE624 or camera_model is LINEAR): + raise ValueError( + "Invalid camera_model type, only FISHEYE624 and LINEAR are supported" + ) + + eye_gaze = self.get_eye_gaze(timestamp_ns, time_domain) + if eye_gaze: + [T_device_camera, camera_calibration] = self.get_camera_calibration( + stream_id, camera_model + ) + # Compute eye_gaze vector at depth_m and project it in the image + gaze_projection = self._get_gaze_vector_reprojection( + eye_gaze, + self.get_image_stream_label(stream_id), + self.get_device_calibration(), + camera_calibration, + ) + return gaze_projection + return None + + def get_eye_gaze( + self, + timestamp_ns: int, + time_domain: TimeDomain = TimeDomain.TIME_CODE, + ) -> Optional[EyeGaze]: + """ + Return the eye_gaze data at the given timestamp + """ + # Map to corresponding timestamp + if time_domain == TimeDomain.TIME_CODE: + device_timestamp_ns = self._timestamp_convert( + timestamp_ns, TimeDomain.TIME_CODE, TimeDomain.DEVICE_TIME + ) + elif time_domain == TimeDomain.DEVICE_TIME: + device_timestamp_ns = timestamp_ns + else: + raise ValueError("Unsupported time domain") + + if device_timestamp_ns: + if self._mps_data_provider.has_personalized_eyegaze(): + return self._mps_data_provider.get_personalized_eyegaze( + device_timestamp_ns + ) + elif self._mps_data_provider.has_general_eyegaze(): + return self._mps_data_provider.get_general_eyegaze(device_timestamp_ns) + return None diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HamerManoHandDataProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HamerManoHandDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..3aacacc12c74b5fffcd8d8fb29b2bd1aff698468 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HamerManoHandDataProvider.py @@ -0,0 +1,141 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from typing import List, Optional + +import numpy as np +import torch + +from data_loaders.HandDataProviderBase import HandDataProviderBase + +from data_loaders.loader_hand_poses import ( + Handedness, + HandPose, + load_hand_poses, + load_mano_shape_params, + load_hamer_hand_poses +) + +from data_loaders.rotation_compat import matrix_to_axis_angle + +from .hamer_mano_layer import HamerMANOHandModel + + +class HamerMANOHandDataProvider(HandDataProviderBase): + + def __init__( + self, + hand_pose_trajectory_filepath: str, + mano_layer: HamerMANOHandModel, + ) -> None: + + super().__init__() + self._hand_poses = load_hamer_hand_poses(hand_pose_trajectory_filepath) + self._sorted_timestamp_ns_list: List[int] = sorted(self._hand_poses.keys()) + + # Hand profile + self._mano_shape_params = load_mano_shape_params(hand_pose_trajectory_filepath) + if self._mano_shape_params is not None: + self._mano_shape_params = torch.from_numpy( + np.array(self._mano_shape_params) + ) + + self.mano_layer = mano_layer + + @property + def timestamp_ns_list(self) -> List[int]: + return self._sorted_timestamp_ns_list + + def get_hand_mesh_vertices( + self, hand_wrist_data: HandPose + ) -> Optional[torch.Tensor]: + """ + Return the hand mesh corresponding to given HandPose + """ + if ( + hand_wrist_data.wrist_pose is not None + and self._mano_shape_params is not None + and self.mano_layer is not None + ): + hand_wrist_pose_matrix = hand_wrist_data.wrist_pose.to_matrix() + hand_wrist_pose_tensor = torch.from_numpy(hand_wrist_pose_matrix) + + hand_wrist_rotation_axis_angle = matrix_to_axis_angle( + hand_wrist_pose_tensor[:3, :3] + ) + hand_wrist_pose_tensor = torch.cat( + [hand_wrist_rotation_axis_angle, hand_wrist_pose_tensor[:3, 3]] + ) + + mesh_vertices, landmarks = self.mano_layer.forward_kinematics( + self._mano_shape_params, + torch.from_numpy(np.array(hand_wrist_data.joint_angles)), + hand_wrist_pose_tensor, + torch.tensor([hand_wrist_data.handedness == Handedness.Right]), + ) + + return mesh_vertices + return None + + def get_hand_mesh_faces_and_normals( + self, hand_wrist_data: HandPose + ) -> Optional[List[np.ndarray]]: + """ + Return the hand mesh faces and normals + """ + if self.mano_layer is not None: + if hand_wrist_data.handedness == Handedness.Right: + hand_triangles = self.mano_layer.mano_layer_right.faces + else: + hand_triangles = self.mano_layer.mano_layer_left.faces + + vertices = self.get_hand_mesh_vertices(hand_wrist_data) + assert vertices is not None + normals = HandDataProviderBase.get_triangular_mesh_normals( + vertices.float().numpy(), hand_triangles + ) + return [hand_triangles, normals] + else: + return None + + def get_hand_landmarks(self, hand_wrist_data: HandPose) -> Optional[torch.Tensor]: + """ + Return the hand joint landmarks corresponding to given HandPose + See how to map the vertices together to represent a Hand as linked lines using LANDMARK_CONNECTIVITY + """ + if ( + hand_wrist_data.wrist_pose is not None + and self._mano_shape_params is not None + and self.mano_layer is not None + ): + hand_wrist_pose_matrix = hand_wrist_data.wrist_pose.to_matrix() + hand_wrist_pose_tensor = torch.from_numpy(hand_wrist_pose_matrix) + + hand_wrist_rotation_axis_angle = matrix_to_axis_angle( + hand_wrist_pose_tensor[:3, :3] + ) + hand_wrist_pose_tensor = torch.cat( + [hand_wrist_rotation_axis_angle, hand_wrist_pose_tensor[:3, 3]] + ) + + mesh_vertices, hand_landmarks = self.mano_layer.forward_kinematics( + self._mano_shape_params, + torch.from_numpy(np.array(hand_wrist_data.joint_angles)), + hand_wrist_pose_tensor, + torch.tensor([hand_wrist_data.handedness == Handedness.Right]), + ) + + return hand_landmarks, None, None, None, None + + return None diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HandBox2dDataProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HandBox2dDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..2405abccbc98db7a54530d787aa4918d25e4c15a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HandBox2dDataProvider.py @@ -0,0 +1,192 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +import logging +import os +from dataclasses import dataclass +from typing import Any, Dict, List, Optional + +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +from .AlignedBox2d import AlignedBox2d +from .constants import HAND_BOX2D_DATA_CSV_COLUMNS + +from .io_utils import float_or_none, is_float +from .loader_poses_utils import check_csv_columns +from .pose_utils import lookup_timestamp + +logger = logging.getLogger(__name__) +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(filename)s - %(lineno)d - %(levelname)s - %(message)s", +) + + +@dataclass +class HandBox2d: + box2d: AlignedBox2d + visibility_ratio: float + + +@dataclass +class HandBox2dCollection: + timestamp_ns: int + box2ds: Dict[int, HandBox2d] + + +HandBox2dTrajectory = Dict[int, HandBox2dCollection] # trajectory for a single stream +HandBox2dTrajectoryCollection = Dict[ + str, HandBox2dTrajectory +] # trajectories for multiple streams + + +@dataclass +class HandBox2dCollectionWithDt: + box2d_collection: HandBox2dCollection + time_delta_ns: int + + +class HandBox2dProvider: + + def __init__( + self, box2d_trajectory_collection: HandBox2dTrajectoryCollection + ) -> None: + + self._box2d_trajectory_collection = box2d_trajectory_collection + + self._sorted_timestamp_ns_list: Dict[str, List[int]] = {} + for stream_id in self._box2d_trajectory_collection.keys(): + self._sorted_timestamp_ns_list[stream_id] = sorted( + self._box2d_trajectory_collection[stream_id].keys() + ) + + def get_timestamp_ns_list(self, stream_id: StreamId) -> Optional[List[int]]: + return self._sorted_timestamp_ns_list.get(str(stream_id), None) + + @property + def stream_ids(self) -> List[StreamId]: + return [StreamId(x) for x in self._box2d_trajectory_collection.keys()] + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the trajectory + """ + stats = {} + stats["num_frames"] = { + k: sum(v) for k, v in self._sorted_timestamp_ns_list.items() + } + stats["stream_ids"] = [str(x) for x in self.stream_ids] + return stats + + def get_bbox_at_timestamp( + self, + stream_id: StreamId, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + ) -> Optional[HandBox2dCollectionWithDt]: + """ + Return the list of poses at the given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + if stream_id not in self.stream_ids: + raise ValueError(f"Box2d trajectory not available for stream {stream_id}.") + + box2d_collection, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._box2d_trajectory_collection[str(stream_id)], + sorted_timestamp_list=self.get_timestamp_ns_list(stream_id=stream_id), + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if box2d_collection is None or time_delta_ns is None: + return None + else: + return HandBox2dCollectionWithDt( + box2d_collection=box2d_collection, time_delta_ns=time_delta_ns + ) + + +def parse_box2ds_from_csv_reader(csv_reader) -> HandBox2dTrajectoryCollection: + + box2d_trajectory_collection: HandBox2dTrajectoryCollection = {} + + # Read the header row + header = next(csv_reader) + + # Ensure we have the desired columns + check_csv_columns(header, HAND_BOX2D_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in csv_reader: + + stream_id = str(StreamId(row[header.index("stream_id")])) + timestamp_ns = int(row[header.index("timestamp[ns]")]) + hand_index = int(row[header.index("hand_index")]) + visibility_ratio = float_or_none(row[header.index("visibility_ratio[%]")]) + + if is_float(row[header.index("x_min[pixel]")]): + x_min_px = float(row[header.index("x_min[pixel]")]) + x_max_px = float(row[header.index("x_max[pixel]")]) + y_min_px = float(row[header.index("y_min[pixel]")]) + y_max_px = float(row[header.index("y_max[pixel]")]) + + box2d = AlignedBox2d( + left=x_min_px, top=y_min_px, right=x_max_px, bottom=y_max_px + ) + else: + box2d = None + + object_box2d = HandBox2d( + box2d=box2d, + visibility_ratio=visibility_ratio, + ) + + if stream_id not in box2d_trajectory_collection: + box2d_trajectory_collection[stream_id] = {} + + if timestamp_ns not in box2d_trajectory_collection[stream_id]: + box2d_trajectory_collection[stream_id][timestamp_ns] = HandBox2dCollection( + timestamp_ns=timestamp_ns, box2ds={} + ) + + box2d_trajectory_collection[stream_id][timestamp_ns].box2ds[ + hand_index + ] = object_box2d + return box2d_trajectory_collection + + +def load_box2d_trajectory_from_csv(filename: str) -> Optional[HandBox2dProvider]: + """Load Dynamic Objects meta data from a CSV file. + + Keyword arguments: + filename -- the csv file i.e. sequence_folder + "/dynamic_objects.csv" + """ + if not os.path.exists(filename): + logger.warn(f"filename: {filename} does not exist.") + return None + + # Open the CSV file for reading + with open(filename, "r") as f: + csv_reader = csv.reader(f) + box2d_trajectory_collection = parse_box2ds_from_csv_reader( + csv_reader=csv_reader + ) + return HandBox2dProvider( + box2d_trajectory_collection=box2d_trajectory_collection + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HandDataProviderBase.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HandDataProviderBase.py new file mode 100644 index 0000000000000000000000000000000000000000..e9698fe7d8622ae73d26cc7faeefdafd73c47f73 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HandDataProviderBase.py @@ -0,0 +1,162 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from abc import abstractmethod +from dataclasses import dataclass +from typing import Any, Dict, List, Optional + +import numpy as np +import torch + +from data_loaders.loader_hand_poses import Handedness, HandPose, HandPose3dCollection +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual + +from .pose_utils import lookup_timestamp + + +@dataclass +class HandPose3dCollectionWithDt: + pose3d_collection: HandPose3dCollection + time_delta_ns: int + + +class HandDataProviderBase: + + def __init__( + self, + ) -> None: + + self._hand_poses = None + self._sorted_timestamp_ns_list: Optional[List[int]] = None + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the Hand data + """ + assert self._sorted_timestamp_ns_list is not None + assert self._hand_poses is not None + + stats = {} + stats["num_frames"] = len(self._sorted_timestamp_ns_list) + stats["num_right_hands"] = sum( + [ + 1 + for it in self._hand_poses.values() + if Handedness.Right in it.poses.keys() + ] + ) + stats["num_left_hands"] = sum( + [ + 1 + for it in self._hand_poses.values() + if Handedness.Left in it.poses.keys() + ] + ) + return stats + + def get_pose_at_timestamp( + self, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + acceptable_time_delta: Optional[int] = None, + ) -> Optional[HandPose3dCollectionWithDt]: + """ + Return the list of hands available at a given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + hand_pose_collection, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._hand_poses, + sorted_timestamp_list=self._sorted_timestamp_ns_list, + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if ( + hand_pose_collection is None + or time_delta_ns is None + or ( + acceptable_time_delta is not None + and abs(time_delta_ns) > acceptable_time_delta + ) + ): + return None + else: + return HandPose3dCollectionWithDt( + pose3d_collection=hand_pose_collection, time_delta_ns=time_delta_ns + ) + + @abstractmethod + def get_hand_mesh_vertices( + self, hand_wrist_data: HandPose + ) -> Optional[torch.Tensor]: + """ + Return the hand mesh corresponding to given HandPose + """ + + @abstractmethod + def get_hand_mesh_faces_and_normals( + self, hand_wrist_data: HandPose + ) -> Optional[List[np.ndarray]]: + """ + Return the hand mesh faces and normals + """ + + @abstractmethod + def get_hand_landmarks(self, hand_wrist_data: HandPose) -> Optional[torch.Tensor]: + """ + Return the hand joint landmarks corresponding to given HandPose + See how to map the vertices together to represent a Hand as linked lines using LANDMARK_CONNECTIVITY + """ + + @staticmethod + def normalized( + vecs: np.ndarray, axis: int = -1, add_const_to_denom: bool = True + ) -> np.ndarray: + """ + Normalize a set of vectors. + Args: + vecs: np.ndarray of shape (..., V). + axis: axis along which to normalize. + add_const_to_denom: if True, add a small constant to the denominator to prevent numerical issues. + Returns: + np.ndarray of the same shape as vecs. + """ + denom = np.linalg.norm(vecs, axis=axis, keepdims=True) + if add_const_to_denom: + denom += 1e-5 + return vecs / denom + + @staticmethod + def get_triangular_mesh_normals( + vertices: np.ndarray, triangles: np.ndarray + ) -> np.ndarray: + """ + Compute the normals of a triangular mesh. + Args: + vertices: np.ndarray of shape (..., V, 3). + triangles: np.ndarray of shape (..., F, 3). + Returns: + normals: np.ndarray of shape (..., F, 3). + """ + norm = np.zeros_like(vertices) + tris = vertices[triangles] + n = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0]) + n = HandDataProviderBase.normalized(n) + norm[triangles[:, 0]] += n + norm[triangles[:, 1]] += n + norm[triangles[:, 2]] += n + return HandDataProviderBase.normalized(norm) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HeadsetPose3dProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HeadsetPose3dProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..5aef12a0ac3c423e62dad1f21d9709d7e103c285 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/HeadsetPose3dProvider.py @@ -0,0 +1,171 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.sophus import SE3 # @manual + +from .constants import POSE_DATA_CSV_COLUMNS +from .loader_poses_utils import check_csv_columns +from .pose_utils import lookup_timestamp + + +@dataclass +class HeadsetPose3d: + """ + Class to store pose of a headset + """ + + T_world_device: Optional[SE3] = None + + +HeadsetPose3dTrajectory = Dict[int, HeadsetPose3d] + + +@dataclass +class HeadsetPose3dWithDt: + pose3d: HeadsetPose3d + time_delta_ns: int + + +class HeadsetPose3dProvider(object): + def __init__( + self, headset_pose3d_trajectory: HeadsetPose3dTrajectory, headset_uid: str + ): + self._pose3d_trajectory: HeadsetPose3dTrajectory = headset_pose3d_trajectory + self._sorted_timestamp_ns_list: List[int] = sorted( + self._pose3d_trajectory.keys() + ) + self._headset_uid: str = str(headset_uid) + + @property + def timestamp_ns_list(self) -> List[int]: + return self._sorted_timestamp_ns_list + + @property + def headset_uid(self) -> str: + return self._headset_uid + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the trajectory + """ + stats = {} + stats["num_frames"] = len(self._sorted_timestamp_ns_list) + stats["headset_uid"] = str(self._headset_uid) + return stats + + def get_pose_at_timestamp( + self, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + acceptable_time_delta: Optional[int] = None, + ) -> Optional[HeadsetPose3dWithDt]: + """ + Return the list of poses at the given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + headset_pose3d, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._pose3d_trajectory, + sorted_timestamp_list=self._sorted_timestamp_ns_list, + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if ( + headset_pose3d is None + or time_delta_ns is None + or ( + acceptable_time_delta is not None + and abs(time_delta_ns) > acceptable_time_delta + ) + ): + return None + else: + return HeadsetPose3dWithDt( + pose3d=headset_pose3d, time_delta_ns=time_delta_ns + ) + + +def load_headset_pose_trajectory_from_csv(filename: str) -> Tuple[Dict[int, SE3], str]: + """Load Device Poses meta data from a CSV file. + + Keyword arguments: + filename -- the csv file i.e. sequence_folder + "/headset_trajectory.csv" + """ + + pose3d_trajectory: HeadsetPose3dTrajectory = {} + headset_uids = set() + + # Open the CSV file for reading + with open(filename, "r") as f: + reader = csv.reader(f) + + # Read the header row + header = next(reader) + + # Ensure we have the desired columns + check_csv_columns(header, POSE_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in reader: + translation = [ + row[header.index("t_wo_x[m]")], + row[header.index("t_wo_y[m]")], + row[header.index("t_wo_z[m]")], + ] + quaternion_xyz = [ + row[header.index("q_wo_x")], + row[header.index("q_wo_y")], + row[header.index("q_wo_z")], + ] + quaternion_w = row[header.index("q_wo_w")] + timestamp_ns = int(row[header.index("timestamp[ns]")]) + headset_uids.add(str(row[header.index("object_uid")])) + + object_pose = SE3.from_quat_and_translation( + float(quaternion_w), + np.array([float(o) for o in quaternion_xyz]), + np.array([float(o) for o in translation]), + )[0] + + pose3d_trajectory[timestamp_ns] = HeadsetPose3d(T_world_device=object_pose) + + if len(headset_uids) != 1: + raise ValueError( + f"Expected 1 headset pose per timestamp, got {len(headset_uids)}. headset_uids: {headset_uids}" + ) + + return pose3d_trajectory, headset_uids.pop() + + +def load_headset_pose_provider_from_csv(filename: str) -> HeadsetPose3dProvider: + """ + Load pose_provider from csv + """ + + headset_pose3d_trajectory, headset_uid = load_headset_pose_trajectory_from_csv( + filename + ) + return HeadsetPose3dProvider( + headset_pose3d_trajectory=headset_pose3d_trajectory, + headset_uid=headset_uid, + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/ManoHandDataProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/ManoHandDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..25427dba074f9d75468879a9747ae915221958e5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/ManoHandDataProvider.py @@ -0,0 +1,140 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from typing import List, Optional + +import numpy as np +import torch + +from data_loaders.HandDataProviderBase import HandDataProviderBase + +from data_loaders.loader_hand_poses import ( + Handedness, + HandPose, + load_hand_poses, + load_mano_shape_params, +) + +from data_loaders.rotation_compat import matrix_to_axis_angle + +from .mano_layer import MANOHandModel + + +class MANOHandDataProvider(HandDataProviderBase): + + def __init__( + self, + hand_pose_trajectory_filepath: str, + mano_layer: MANOHandModel, + ) -> None: + + super().__init__() + self._hand_poses = load_hand_poses(hand_pose_trajectory_filepath) + self._sorted_timestamp_ns_list: List[int] = sorted(self._hand_poses.keys()) + + # Hand profile + self._mano_shape_params = load_mano_shape_params(hand_pose_trajectory_filepath) + if self._mano_shape_params is not None: + self._mano_shape_params = torch.from_numpy( + np.array(self._mano_shape_params) + ) + + self.mano_layer = mano_layer + + @property + def timestamp_ns_list(self) -> List[int]: + return self._sorted_timestamp_ns_list + + def get_hand_mesh_vertices( + self, hand_wrist_data: HandPose + ) -> Optional[torch.Tensor]: + """ + Return the hand mesh corresponding to given HandPose + """ + if ( + hand_wrist_data.wrist_pose is not None + and self._mano_shape_params is not None + and self.mano_layer is not None + ): + hand_wrist_pose_matrix = hand_wrist_data.wrist_pose.to_matrix() + hand_wrist_pose_tensor = torch.from_numpy(hand_wrist_pose_matrix) + + hand_wrist_rotation_axis_angle = matrix_to_axis_angle( + hand_wrist_pose_tensor[:3, :3] + ) + hand_wrist_pose_tensor = torch.cat( + [hand_wrist_rotation_axis_angle, hand_wrist_pose_tensor[:3, 3]] + ) + + mesh_vertices, landmarks, _, _, _, _ = self.mano_layer.forward_kinematics( + self._mano_shape_params, + torch.from_numpy(np.array(hand_wrist_data.joint_angles)), + hand_wrist_pose_tensor, + torch.tensor([hand_wrist_data.handedness == Handedness.Right]), + ) + + return mesh_vertices + return None + + def get_hand_mesh_faces_and_normals( + self, hand_wrist_data: HandPose + ) -> Optional[List[np.ndarray]]: + """ + Return the hand mesh faces and normals + """ + if self.mano_layer is not None: + if hand_wrist_data.handedness == Handedness.Right: + hand_triangles = self.mano_layer.mano_layer_right.faces + else: + hand_triangles = self.mano_layer.mano_layer_left.faces + + vertices = self.get_hand_mesh_vertices(hand_wrist_data) + assert vertices is not None + normals = HandDataProviderBase.get_triangular_mesh_normals( + vertices.float().numpy(), hand_triangles + ) + return [hand_triangles, normals] + else: + return None + + def get_hand_landmarks(self, hand_wrist_data: HandPose) -> Optional[torch.Tensor]: + """ + Return the hand joint landmarks corresponding to given HandPose + See how to map the vertices together to represent a Hand as linked lines using LANDMARK_CONNECTIVITY + """ + if ( + hand_wrist_data.wrist_pose is not None + and self._mano_shape_params is not None + and self.mano_layer is not None + ): + hand_wrist_pose_matrix = hand_wrist_data.wrist_pose.to_matrix() + hand_wrist_pose_tensor = torch.from_numpy(hand_wrist_pose_matrix) + + hand_wrist_rotation_axis_angle = matrix_to_axis_angle( + hand_wrist_pose_tensor[:3, :3] + ) + hand_wrist_pose_tensor = torch.cat( + [hand_wrist_rotation_axis_angle, hand_wrist_pose_tensor[:3, 3]] + ) + + mesh_vertices, hand_landmarks, out_rot, out_trans, out_pose, out_betas = self.mano_layer.forward_kinematics( + self._mano_shape_params, + torch.from_numpy(np.array(hand_wrist_data.joint_angles)), + hand_wrist_pose_tensor, + torch.tensor([hand_wrist_data.handedness == Handedness.Right]), + ) + + return hand_landmarks, out_rot, out_trans, out_pose, out_betas + + return None diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/ObjectBox2dDataProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/ObjectBox2dDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..c6328dec62733715731533c6674dc89b1827a81c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/ObjectBox2dDataProvider.py @@ -0,0 +1,219 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +import logging +import os +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Set + +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +from .AlignedBox2d import AlignedBox2d + +from .constants import BOX2D_DATA_CSV_COLUMNS +from .io_utils import float_or_none, is_float +from .loader_poses_utils import check_csv_columns +from .pose_utils import lookup_timestamp + +logger = logging.getLogger(__name__) +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(filename)s - %(lineno)d - %(levelname)s - %(message)s", +) + + +@dataclass +class ObjectBox2d: + box2d: Optional[AlignedBox2d] + visibility_ratio: float + + +@dataclass +class ObjectBox2dCollection: + timestamp_ns: int + box2ds: Dict[str, ObjectBox2d] + + @property + def object_uid_list(self) -> Set[str]: + return set(self.box2ds.keys()) + + +ObjectBox2dTrajectory = Dict[ + int, ObjectBox2dCollection +] # trajectory for a single stream +ObjectBox2dTrajectoryCollection = Dict[ + str, ObjectBox2dTrajectory +] # trajectories for multiple streams + + +@dataclass +class ObjectBox2dCollectionWithDt: + box2d_collection: ObjectBox2dCollection + time_delta_ns: int + + +class ObjectBox2dProvider: + + def __init__( + self, box2d_trajectory_collection: ObjectBox2dTrajectoryCollection + ) -> None: + + self._box2d_trajectory_collection = box2d_trajectory_collection + + self._sorted_timestamp_ns_list: Dict[str, List[int]] = {} + for stream_id in self._box2d_trajectory_collection.keys(): + self._sorted_timestamp_ns_list[stream_id] = sorted( + self._box2d_trajectory_collection[stream_id].keys() + ) + + self._object_uids_with_box2ds: Set = { + x + for box2d_trajectory in self._box2d_trajectory_collection.values() + for v in box2d_trajectory.values() + for x in v.object_uid_list + } + + def get_timestamp_ns_list(self, stream_id: StreamId) -> Optional[List[int]]: + return self._sorted_timestamp_ns_list.get(str(stream_id), None) + + @property + def stream_ids(self) -> List[StreamId]: + return [StreamId(x) for x in self._box2d_trajectory_collection.keys()] + + @property + def object_uids(self) -> Set[str]: + return set(self._object_uids_with_box2ds) + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the trajectory + """ + stats = {} + stats["num_frames"] = { + k: sum(v) for k, v in self._sorted_timestamp_ns_list.items() + } + stats["stream_ids"] = [str(x) for x in self.stream_ids] + stats["num_objects"] = len(self.object_uids) + stats["object_uids"] = [str(x) for x in self.object_uids] + return stats + + def get_box2d_at_timestamp( + self, + stream_id: StreamId, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + acceptable_time_delta: Optional[int] = None, + ) -> Optional[ObjectBox2dCollectionWithDt]: + """ + Return the list of boxes at the given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + if stream_id not in self.stream_ids: + raise ValueError(f"Box2d trajectory not available for stream {stream_id}.") + + box2d_collection, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._box2d_trajectory_collection[str(stream_id)], + sorted_timestamp_list=self.get_timestamp_ns_list(stream_id=stream_id), + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if ( + box2d_collection is None + or time_delta_ns is None + or ( + acceptable_time_delta is not None + and abs(time_delta_ns) > acceptable_time_delta + ) + ): + return None + else: + return ObjectBox2dCollectionWithDt( + box2d_collection=box2d_collection, time_delta_ns=time_delta_ns + ) + + +def parse_box2ds_from_csv_reader(csv_reader) -> ObjectBox2dTrajectoryCollection: + + box2d_trajectory_collection: ObjectBox2dTrajectoryCollection = {} + + # Read the header row + header = next(csv_reader) + + # Ensure we have the desired columns + check_csv_columns(header, BOX2D_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in csv_reader: + + stream_id = str(StreamId(row[header.index("stream_id")])) + timestamp_ns = int(row[header.index("timestamp[ns]")]) + object_uid = str(row[header.index("object_uid")]) + visibility_ratio = float_or_none(row[header.index("visibility_ratio[%]")]) + + if is_float(row[header.index("x_min[pixel]")]): + x_min_px = float(row[header.index("x_min[pixel]")]) + x_max_px = float(row[header.index("x_max[pixel]")]) + y_min_px = float(row[header.index("y_min[pixel]")]) + y_max_px = float(row[header.index("y_max[pixel]")]) + + box2d = AlignedBox2d( + left=x_min_px, top=y_min_px, right=x_max_px, bottom=y_max_px + ) + else: + box2d = None + + object_box2d = ObjectBox2d( + box2d=box2d, + visibility_ratio=visibility_ratio, + ) + + if stream_id not in box2d_trajectory_collection: + box2d_trajectory_collection[stream_id] = {} + + if timestamp_ns not in box2d_trajectory_collection[stream_id]: + box2d_trajectory_collection[stream_id][timestamp_ns] = ( + ObjectBox2dCollection(timestamp_ns=timestamp_ns, box2ds={}) + ) + + box2d_trajectory_collection[stream_id][timestamp_ns].box2ds[ + object_uid + ] = object_box2d + return box2d_trajectory_collection + + +def load_box2d_trajectory_from_csv(filename: str) -> Optional[ObjectBox2dProvider]: + """Load Dynamic Objects meta data from a CSV file. + + Keyword arguments: + filename -- the csv file i.e. sequence_folder + "/dynamic_objects.csv" + """ + if not os.path.exists(filename): + logger.warn(f"filename: {filename} does not exist.") + return None + + # Open the CSV file for reading + with open(filename, "r") as f: + csv_reader = csv.reader(f) + box2d_trajectory_collection = parse_box2ds_from_csv_reader( + csv_reader=csv_reader + ) + return ObjectBox2dProvider( + box2d_trajectory_collection=box2d_trajectory_collection + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/ObjectPose3dProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/ObjectPose3dProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..e0491636eabc661dba5d82456cbfcc1a7ac82279 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/ObjectPose3dProvider.py @@ -0,0 +1,182 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +from dataclasses import dataclass + +from typing import Any, Dict, List, Optional, Set + +import numpy as np +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.sophus import SE3 # @manual + +from .constants import POSE_DATA_CSV_COLUMNS +from .loader_poses_utils import check_csv_columns +from .pose_utils import lookup_timestamp + + +@dataclass +class ObjectPose3d: + """ + Class to store pose of a single entity (object/headset/hand) + """ + + T_world_object: Optional[SE3] = None + + +@dataclass +class ObjectPose3dCollection: + """ + Class to store the poses for a given timestamp + """ + + timestamp_ns: int + poses: Dict[str, ObjectPose3d] + + @property + def object_uid_list(self) -> Set[str]: + return set(self.poses.keys()) + + +ObjectPose3dTrajectory = Dict[int, ObjectPose3dCollection] + + +@dataclass +class ObjectPose3dCollectionWithDt: + pose3d_collection: ObjectPose3dCollection + time_delta_ns: int + + +class ObjectPose3dProvider(object): + def __init__(self, pose3d_trajectory: ObjectPose3dTrajectory): + self._pose3d_trajectory: ObjectPose3dTrajectory = pose3d_trajectory + self._sorted_timestamp_ns_list: List[int] = sorted( + self._pose3d_trajectory.keys() + ) + self._object_uids_with_poses: Set = { + x for v in self._pose3d_trajectory.values() for x in v.object_uid_list + } + + @property + def timestamp_ns_list(self) -> List[int]: + return self._sorted_timestamp_ns_list + + @property + def object_uids_with_poses(self) -> Set[str]: + return set(self._object_uids_with_poses) + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the trajectory + """ + stats = {} + stats["num_frames"] = len(self._sorted_timestamp_ns_list) + stats["num_objects"] = len(self._object_uids_with_poses) + stats["object_uids"] = [str(x) for x in self._object_uids_with_poses] + return stats + + def get_pose_at_timestamp( + self, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + acceptable_time_delta: Optional[int] = None, + ) -> Optional[ObjectPose3dCollectionWithDt]: + """ + Return the list of poses available at the given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + pose3d_collection, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._pose3d_trajectory, + sorted_timestamp_list=self._sorted_timestamp_ns_list, + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if ( + pose3d_collection is None + or time_delta_ns is None + or ( + acceptable_time_delta is not None + and abs(time_delta_ns) > acceptable_time_delta + ) + ): + return None + else: + return ObjectPose3dCollectionWithDt( + pose3d_collection=pose3d_collection, time_delta_ns=time_delta_ns + ) + + +def load_object_pose_trajectory_from_csv(filename: str) -> ObjectPose3dTrajectory: + """Load Dynamic Objects meta data from a CSV file. + + Keyword arguments: + filename -- the csv file i.e. sequence_folder + "/dynamic_objects.csv" + """ + + pose3d_trajectory: ObjectPose3dTrajectory = {} + # Open the CSV file for reading + with open(filename, "r") as f: + reader = csv.reader(f) + + # Read the header row + header = next(reader) + + # Ensure we have the desired columns + check_csv_columns(header, POSE_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in reader: + translation = [ + row[header.index("t_wo_x[m]")], + row[header.index("t_wo_y[m]")], + row[header.index("t_wo_z[m]")], + ] + quaternion_xyz = [ + row[header.index("q_wo_x")], + row[header.index("q_wo_y")], + row[header.index("q_wo_z")], + ] + quaternion_w = row[header.index("q_wo_w")] + timestamp_ns = int(row[header.index("timestamp[ns]")]) + object_uid = str(row[header.index("object_uid")]) + + T_world_object = SE3.from_quat_and_translation( + float(quaternion_w), + np.array([float(o) for o in quaternion_xyz]), + np.array([float(o) for o in translation]), + )[0] + + pose3d = ObjectPose3d(T_world_object=T_world_object) + + if timestamp_ns not in pose3d_trajectory: + pose3d_trajectory[timestamp_ns] = ObjectPose3dCollection( + timestamp_ns=timestamp_ns, poses={} + ) + + pose3d_trajectory[timestamp_ns].poses[object_uid] = pose3d + + return pose3d_trajectory + + +def load_pose_provider_from_csv(filename: str) -> ObjectPose3dProvider: + """ + Load the ObjectPose3dProvider from a csv file + """ + return ObjectPose3dProvider( + pose3d_trajectory=load_object_pose_trajectory_from_csv(filename) + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/PathProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/PathProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..62106f8b93b17ac9cd1848f6cedf3ef2c5b3d443 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/PathProvider.py @@ -0,0 +1,145 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os + +from .headsets import Headset +from .io_utils import load_json + + +class Hot3dDataPathProvider(object): + @staticmethod + def fromRecordingFolder(recording_instance_folderpath): + + metadata_filepath = os.path.join(recording_instance_folderpath, "metadata.json") + metadata_json = load_json(metadata_filepath) + headset = Headset[metadata_json["headset"]] + + if headset is Headset.Aria: + return AriaDatasetPaths( + recording_instance_folderpath=recording_instance_folderpath + ) + elif headset is Headset.Quest3: + return Quest3DatasetPaths( + recording_instance_folderpath=recording_instance_folderpath + ) + else: + raise NotImplementedError(f"{headset} not supported at the moment.") + + +class Quest3DatasetPaths(object): + def __init__(self, recording_instance_folderpath): + self._recording_instance_folderpath = recording_instance_folderpath + + @property + def recording_instance_folderpath(self): + return self._recording_instance_folderpath + + @property + def dynamic_objects_filepath(self): + return f"{self._recording_instance_folderpath}/dynamic_objects.csv" + + @property + def headset_trajectory_filepath(self): + return f"{self._recording_instance_folderpath}/headset_trajectory.csv" + + @property + def mano_hand_pose_trajectory_filepath(self): + return f"{self._recording_instance_folderpath}/mano_hand_pose_trajectory.jsonl" + + @property + def vrs_filepath(self): + return f"{self._recording_instance_folderpath}/recording.vrs" + + @property + def box2d_objects_filepath(self): + return f"{self._recording_instance_folderpath}/box2d_objects.csv" + + @property + def box2d_hands_filepath(self): + return f"{self._recording_instance_folderpath}/box2d_hands.csv" + + @property + def scene_metadata_filepath(self): + return f"{self._recording_instance_folderpath}/metadata.json" + + @property + def camera_models_filepath(self): + return f"{self._recording_instance_folderpath}/camera_models.json" + + @property + def required_filepaths(self): + return [ + self.vrs_filepath, + self.dynamic_objects_filepath, + self.headset_trajectory_filepath, + self.camera_models_filepath, + self.mano_hand_pose_trajectory_filepath, + ] + + def is_valid(self) -> bool: + return all(os.path.exists(filepath) for filepath in self.required_filepaths) + + +class AriaDatasetPaths(object): + def __init__(self, recording_instance_folderpath): + self._recording_instance_folderpath = recording_instance_folderpath + + @property + def recording_instance_folderpath(self): + return self._recording_instance_folderpath + + @property + def dynamic_objects_filepath(self): + return f"{self._recording_instance_folderpath}/dynamic_objects.csv" + + @property + def headset_trajectory_filepath(self): + return f"{self._recording_instance_folderpath}/headset_trajectory.csv" + + @property + def mano_hand_pose_trajectory_filepath(self): + return f"{self._recording_instance_folderpath}/mano_hand_pose_trajectory.jsonl" + + @property + def vrs_filepath(self): + return f"{self._recording_instance_folderpath}/recording.vrs" + + @property + def box2d_objects_filepath(self): + return f"{self._recording_instance_folderpath}/box2d_objects.csv" + + @property + def box2d_hands_filepath(self): + return f"{self._recording_instance_folderpath}/box2d_hands.csv" + + @property + def mps_folderpath(self): + return f"{self._recording_instance_folderpath}/mps" + + @property + def scene_metadata_filepath(self): + return f"{self._recording_instance_folderpath}/metadata.json" + + @property + def required_filepaths(self): + return [ + self.vrs_filepath, + self.dynamic_objects_filepath, + self.headset_trajectory_filepath, + self.mano_hand_pose_trajectory_filepath, + ] + + def is_valid(self) -> bool: + return all(os.path.exists(filepath) for filepath in self.required_filepaths) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/QuestDataProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/QuestDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..ce51c2b579dd7de478015f75836dec63c1d86b95 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/QuestDataProvider.py @@ -0,0 +1,207 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from typing import List, Optional + +import numpy as np +from data_loaders.io_utils import load_json +from PIL import Image + +from projectaria_tools.core.calibration import ( # @manual + CameraCalibration, + DeviceCadExtrinsics, + DeviceCalibration, + distort_by_calibration, + FISHEYE624, + get_linear_camera_calibration, + LINEAR, +) +from projectaria_tools.core.sophus import SE3 # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +try: + from pyvrs import ImageConversion, SyncVRSReader # @manual +except ImportError: + from pyvrs2 import SyncVRSReader # @manual + from vrsbindings import ImageConversion # @manual + + +class QuestDataProvider: + + def __init__(self, vrs_filepath: str, device_calibration_filepath: str) -> None: + self._vrs_reader = SyncVRSReader(vrs_filepath) + # Configure Image conversion + self._vrs_reader.set_image_conversion(ImageConversion.NORMALIZE) + self._vrs_reader.set_stream_type_image_conversion( + 8010, ImageConversion.NORMALIZE_GREY8 + ) + + # Keep the two last stream ids (the one with largest resolution) + image_stream_ids = [] + for stream_id in self._vrs_reader.stream_ids: + if self._vrs_reader.might_contain_images(stream_id): + image_stream_ids.append(stream_id) + image_stream_ids = sorted(image_stream_ids) + + # Filter the reader + filtered_reader = self._vrs_reader.filtered_by_fields( + stream_ids=image_stream_ids + ) + self._vrs_reader = filtered_reader + + # Loading camera calibration data + device_calibration_json = load_json(device_calibration_filepath) + camera_calibration = {} + for it in device_calibration_json: + quaternion = it["T_Device_Camera"]["quaternion_wxyz"] + translation = it["T_Device_Camera"]["translation_xyz"] + image_height = it["imageHeight"] + image_width = it["imageWidth"] + label = it["label"] + max_solid_angle = 1 # Limiting the fov to a constant value. + # projection_model_type = it["projectionModelType"] + projection_params = it["projectionParams"] + serial_number = it["serialNumber"] + + T_world_device = SE3.from_quat_and_translation( + quaternion[0], + quaternion[1:4], + translation, + ) + # Skip focal_y and rely on a single focal length for x,y + projection_params = projection_params[:1] + projection_params[2:] + + # Build the corresponding camera calibration object + camera_calibration[label] = CameraCalibration( + label, + FISHEYE624, + projection_params, + T_world_device, + image_width, + image_height, + None, + max_solid_angle, + serial_number, + ) + + self._device_calibration = DeviceCalibration( + camera_calibration, {}, {}, {}, {}, DeviceCadExtrinsics(), "", "" + ) + + def get_device_calibration(self) -> DeviceCalibration: + """ + Return the device calibration (factory calibration of all sensors) + """ + return self._device_calibration + + def get_camera_calibration( + self, + stream_id: StreamId, + camera_model=FISHEYE624, + ) -> tuple[SE3, CameraCalibration]: + """ + Return the camera calibration of the device of the sequence as [Extrinsics, Intrinsics] + Note: + - A corresponding pinhole camera can be requested by using camera_model = LINEAR. + - This is the camera model used to generate the 'get_undistorted_image'. + """ + if not (camera_model is FISHEYE624 or camera_model is LINEAR): + raise ValueError( + "Invalid camera_model type, only FISHEYE624 and LINEAR are supported" + ) + + device_calibration = self.get_device_calibration() + # Map the string to the right label + stream_label = self.get_image_stream_label(stream_id) + stream_labels_str = [ + self.get_image_stream_label(x) for x in self.get_image_stream_ids() + ] + idx_stream = stream_labels_str.index(stream_label) + corresponding_calibration_label = device_calibration.get_camera_labels()[ + idx_stream + ] + camera_calibration = device_calibration.get_camera_calib( + corresponding_calibration_label + ) + + # If a corresponding pinhole camera is requested, we build one on the fly + if camera_model == LINEAR: + focal_lengths = camera_calibration.get_focal_lengths() + image_size = camera_calibration.get_image_size() + camera_calibration = get_linear_camera_calibration( + image_size[0], image_size[1], focal_lengths[0] + ) + # else return the native FISHEYE624 camera model + + T_device_camera = camera_calibration.get_transform_device_camera() + return [T_device_camera, camera_calibration] + + def get_image_stream_ids(self) -> List[StreamId]: + # retrieve all streams ids and filter the one that are image based + image_stream_ids = [] + for stream_id in self._vrs_reader.stream_ids: + if self._vrs_reader.might_contain_images(stream_id): + image_stream_ids.append(stream_id) + image_stream_ids = sorted(image_stream_ids) + return [StreamId(x) for x in image_stream_ids] + + def get_sequence_timestamps(self) -> List[int]: + """ + Returns the list of "time code" timestamp for the sequence + """ + timestamps = self._vrs_reader.get_timestamp_list() + # convert timestamp from float to int in ns + return sorted({int(x * 1e9) for x in timestamps}) + + def get_image_stream_label(self, stream_id: StreamId) -> str: + return str(stream_id) + + def get_image(self, timestamp_ns: int, stream_id: StreamId) -> Optional[np.ndarray]: + try: + record = self._vrs_reader.read_record_by_time( + stream_id=self.get_image_stream_label(stream_id), + timestamp=timestamp_ns / 1e9, + ) + except ValueError as e: + print( + f"No record found for timestamp {timestamp_ns} and stream {stream_id}. Caught exception: {e}" + ) + record = None + + if record is not None and record.record_type == "data": + grey8 = Image.fromarray(record.image_blocks[0]) + return np.array(grey8) + else: + print(f"No image found for timestamp {timestamp_ns} and stream {stream_id}") + return None + + def get_undistorted_image( + self, timestamp_ns: int, stream_id: StreamId + ) -> Optional[np.ndarray]: + image = self.get_image(timestamp_ns, stream_id) + if image is None: + return None + + [T_device_camera, native_camera_calibration] = self.get_camera_calibration( + stream_id, camera_model=FISHEYE624 + ) + [T_device_camera, pinhole_camera_calibration] = self.get_camera_calibration( + stream_id, camera_model=LINEAR + ) + + # Compute the actual undistorted image + undistorted_image = distort_by_calibration( + image, pinhole_camera_calibration, native_camera_calibration + ) + return undistorted_image diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/constants.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd7aac8b7a70cd72eb3380b6d5c0c4fab5b8774 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/constants.py @@ -0,0 +1,53 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +POSE_DATA_CSV_COLUMNS = [ + "object_uid", + "timestamp[ns]", + "t_wo_x[m]", + "t_wo_y[m]", + "t_wo_z[m]", + "q_wo_w", + "q_wo_x", + "q_wo_y", + "q_wo_z", +] + +BOX2D_DATA_CSV_COLUMNS = [ + "stream_id", + "object_uid", + "timestamp[ns]", + "x_min[pixel]", + "x_max[pixel]", + "y_min[pixel]", + "y_max[pixel]", + "visibility_ratio[%]", +] + +HAND_BOX2D_DATA_CSV_COLUMNS = [ + "stream_id", + "hand_index", + "timestamp[ns]", + "x_min[pixel]", + "x_max[pixel]", + "y_min[pixel]", + "y_max[pixel]", + "visibility_ratio[%]", +] + +MASK_DATA_CSV_COLUMNS = [ + "timestamp[ns]", + "stream_id", + "mask", +] diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/hamer_mano_layer.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/hamer_mano_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..7edddb76be01b280c0dc4b145498f79336f4e34f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/hamer_mano_layer.py @@ -0,0 +1,284 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +from typing import List, Optional + +SMPLX_IMPORT_SUCCEEDED = False # default suppose we can't import SMPLX + +try: + import smplx + + SMPLX_IMPORT_SUCCEEDED = True +except ImportError: + print( + "INFO: HOT3D hands requires smplx (See our GitHub repository for more information on its installation)." + ) + +import torch + +mano_joint_mapping = [ + 16, + 17, + 18, + 19, + 20, + 0, + 14, + 15, + 1, + 2, + 3, + 4, + 5, + 6, + 10, + 11, + 12, + 7, + 8, + 9, +] + + +class HamerMANOHandModel: + N_VERT = 778 + N_LANDMARKS = 21 + MANO_FINGERTIP_VERT_INDICES = { + "thumb": 744, + "index": 320, + "middle": 443, + "ring": 554, + "pinky": 671, + } + + def __init__( + self, + mano_model_files_dir: str, + joint_mapper: Optional[List] = mano_joint_mapping, + ): + mano_left_filename = os.path.join(mano_model_files_dir, "MANO_LEFT.pkl") + mano_right_filename = os.path.join(mano_model_files_dir, "MANO_RIGHT.pkl") + + self.use_pose_pca = False + self.num_shape_params = 10 + self.device = "cpu" + self.dtype = torch.float32 + self.joint_mapper = joint_mapper + + self.mano_layer_left = smplx.create( + mano_left_filename, + "mano", + use_pca=self.use_pose_pca, + is_rhand=False, + flat_hand_mean=True + ) + self.mano_layer_left.to(self.device) + + self.mano_layer_right = smplx.create( + mano_right_filename, + "mano", + use_pca=self.use_pose_pca, + is_rhand=True, + flat_hand_mean=True + ) + self.mano_layer_right.to(self.device) + + # fix MANO shapedirs of the left hand bug (https://github.com/vchoutas/smplx/issues/48) + if ( + torch.sum( + torch.abs( + self.mano_layer_left.shapedirs[:, 0, :] + - self.mano_layer_right.shapedirs[:, 0, :] + ) + ) + < 1 + ): + self.mano_layer_left.shapedirs[:, 0, :] *= -1 + + def forward_kinematics( + self, + shape_params: torch.Tensor, + joint_angles: torch.Tensor, + global_xfrom: torch.Tensor, + is_right_hand: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + assert shape_params.shape[0] == self.num_shape_params + is_batched = len(joint_angles.shape) == 2 + if len(global_xfrom.shape) == 1: + global_xfrom = torch.unsqueeze(global_xfrom, 0) + assert global_xfrom.shape[1] == 6 + if len(joint_angles.shape) == 1: + joint_angles = torch.unsqueeze(joint_angles, 0) + assert is_right_hand.shape[0] == joint_angles.shape[0] + + num_frames = joint_angles.shape[0] + + # Left hand FK + if torch.any(torch.logical_not(is_right_hand)): + left_global_xform = global_xfrom[torch.logical_not(is_right_hand)] + left_joint_angles = joint_angles[torch.logical_not(is_right_hand)] + left_mano_output = self.mano_layer_left( + betas=shape_params[None] + .repeat(left_global_xform.shape[0], 1) + .to(self.dtype), + global_orient=left_global_xform[:, :3].to(self.dtype), + hand_pose=left_joint_angles.to(self.dtype), + transl=left_global_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + ) + + # Right hand FK + if torch.any(is_right_hand): + right_global_xform = global_xfrom[is_right_hand] + right_joint_angles = joint_angles[is_right_hand] + right_mano_output = self.mano_layer_right( + betas=shape_params[None] + .repeat(right_global_xform.shape[0], 1) + .to(self.dtype), + global_orient=right_global_xform[:, :3].to(self.dtype), + hand_pose=right_joint_angles.to(self.dtype), + transl=right_global_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + ) + + # Merge the left and right hand outputs + out_vertices = torch.zeros( + ( + num_frames, + self.N_VERT, + 3, + ) + ).to(self.device) + if torch.any(torch.logical_not(is_right_hand)): + out_vertices[torch.logical_not(is_right_hand)] = left_mano_output.vertices + if torch.sum(is_right_hand) > 0: + out_vertices[is_right_hand] = right_mano_output.vertices + + out_landmarks = torch.zeros( + ( + num_frames, + self.N_LANDMARKS, + 3, + ) + ).to(self.device) + if torch.any(torch.logical_not(is_right_hand)): + if left_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + left_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([left_mano_output.joints, extra_joints], dim=1) + else: + joints = left_mano_output.joints + out_landmarks[torch.logical_not(is_right_hand)] = joints + if torch.sum(is_right_hand) > 0: + if right_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + right_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([right_mano_output.joints, extra_joints], dim=1) + else: + joints = right_mano_output.joints + out_landmarks[is_right_hand] = joints + + assert out_landmarks.shape[1] == self.N_LANDMARKS + + if self.joint_mapper is not None: + out_landmarks = out_landmarks[:, self.joint_mapper] + + if not is_batched: + out_vertices = torch.squeeze(out_vertices, 0) + out_landmarks = torch.squeeze(out_landmarks, 0) + + return out_vertices, out_landmarks + + def shape_only_forward_kinematics( + self, + shape_params: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Method to get the vertices and landmarks of the hand using only the shape + parameters and passing 0s for pose params and global xform. + + Args: + shape_params: N x 6 (N is the number of frames) or 6, + """ + is_batched = len(shape_params.shape) == 2 + if is_batched: + assert shape_params.shape[1] == self.num_shape_params + num_frames = shape_params.shape[0] + else: + assert shape_params.shape[0] == self.num_shape_params + shape_params = shape_params.unsqueeze(0) + num_frames = 1 + + # create zero pose params + pose_params = torch.zeros((num_frames, 15)) + pose_xform = torch.zeros((num_frames, 6)) + + # FK + left_mano_output = self.mano_layer_left( + betas=shape_params.to(self.dtype), + global_orient=pose_xform[:, :3].to(self.dtype), + hand_pose=pose_params.to(self.dtype), + transl=pose_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + ) + + # Merge the left and right hand outputs + out_vertices = left_mano_output.vertices + + if left_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + left_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([left_mano_output.joints, extra_joints], dim=1) + else: + joints = left_mano_output.joints + out_landmarks = joints + + assert out_landmarks.shape[1] == self.N_LANDMARKS + + if self.joint_mapper is not None: + out_landmarks = out_landmarks[:, self.joint_mapper] + + if not is_batched: + out_vertices = torch.squeeze(out_vertices, 0) + out_landmarks = torch.squeeze(out_landmarks, 0) + + return out_vertices, out_landmarks + + +def loadHamerManoHandModel( + mano_model_files_dir: Optional[str], +) -> HamerMANOHandModel: + if not SMPLX_IMPORT_SUCCEEDED or mano_model_files_dir is None: + return None + + return HamerMANOHandModel(mano_model_files_dir) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/hand_common.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/hand_common.py new file mode 100644 index 0000000000000000000000000000000000000000..0051c15cf542e71353fcbac020ccc635f624707c --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/hand_common.py @@ -0,0 +1,169 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from enum import Enum + +# Define a HAND with 21 landmarks + + +class LANDMARK(Enum): + THUMB_FINGERTIP = "Thumb fingertip" + INDEX_FINGER_FINGERTIP = "Index finger fingertip" + MIDDLE_FINGER_FINGERTIP = "Middle finger fingertip" + RING_FINGER_FINGERTIP = "Ring finger fingertip" + PINKY_FINGER_FINGERTIP = "Pinky finger fingertip" + WRIST_JOINT = "Wrist joint" + THUMB_INTERMEDIATE_FRAME = "Thumb intermediate frame" + THUMB_DISTAL_FRAME = "Thumb distal frame" + INDEX_PROXIMAL_FRAME = "Index proximal frame" + INDEX_INTERMEDIATE_FRAME = "Index intermediate frame" + INDEX_DISTAL_FRAME = "Index distal frame" + MIDDLE_PROXIMAL_FRAME = "Middle proximal frame" + MIDDLE_INTERMEDIATE_FRAME = "Middle intermediate frame" + MIDDLE_DISTAL_FRAME = "Middle distal frame" + RING_PROXIMAL_FRAME = "Ring proximal frame" + RING_INTERMEDIATE_FRAME = "Ring intermediate frame" + RING_DISTAL_FRAME = "Ring distal frame" + PINKY_PROXIMAL_FRAME = "Pinky proximal frame" + PINKY_INTERMEDIATE_FRAME = "Pinky intermediate frame" + PINKY_DISTAL_FRAME = "Pinky distal frame" + PALM_CENTER = "Palm center" + + +LANDMARK_INDEX_TO_NAMING = [ + LANDMARK.THUMB_FINGERTIP, + LANDMARK.INDEX_FINGER_FINGERTIP, + LANDMARK.MIDDLE_FINGER_FINGERTIP, + LANDMARK.RING_FINGER_FINGERTIP, + LANDMARK.PINKY_FINGER_FINGERTIP, + LANDMARK.WRIST_JOINT, + LANDMARK.THUMB_INTERMEDIATE_FRAME, + LANDMARK.THUMB_DISTAL_FRAME, + LANDMARK.INDEX_PROXIMAL_FRAME, + LANDMARK.INDEX_INTERMEDIATE_FRAME, + LANDMARK.INDEX_DISTAL_FRAME, + LANDMARK.MIDDLE_PROXIMAL_FRAME, + LANDMARK.MIDDLE_INTERMEDIATE_FRAME, + LANDMARK.MIDDLE_DISTAL_FRAME, + LANDMARK.RING_PROXIMAL_FRAME, + LANDMARK.RING_INTERMEDIATE_FRAME, + LANDMARK.RING_DISTAL_FRAME, + LANDMARK.PINKY_PROXIMAL_FRAME, + LANDMARK.PINKY_INTERMEDIATE_FRAME, + LANDMARK.PINKY_DISTAL_FRAME, + LANDMARK.PALM_CENTER, +] + +LANDMARK_NAMING_TO_INDEX = {k: i for i, k in enumerate(LANDMARK_INDEX_TO_NAMING)} + +LANDMARK_CONNECTIVITY = [ + # pinky + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_FINGER_FINGERTIP], + ], + # ring + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_FINGER_FINGERTIP], + ], + # middle + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_FINGER_FINGERTIP], + ], + # index + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_FINGER_FINGERTIP], + ], + # thumb + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_FINGERTIP], + ], + # palm + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_PROXIMAL_FRAME], + ], +] diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/headsets.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/headsets.py new file mode 100644 index 0000000000000000000000000000000000000000..abae4d86c59362b8b72eb9a63d23c6a678061dbb --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/headsets.py @@ -0,0 +1,20 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from enum import auto, Enum + + +class Headset(Enum): + Aria = auto() + Quest3 = auto() diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/io_utils.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/io_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..049ec39b2470981786bbba9c3334923d1f6fb02a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/io_utils.py @@ -0,0 +1,48 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import json +from typing import Any, Optional + + +def load_json(json_filepath): + with open(json_filepath, "r") as fp: + return json.loads(fp.read()) + + +def write_json(payload, json_filepath): + with open(json_filepath, "w") as fp: + json.dump(payload, fp, indent=4, sort_keys=True) + + +def is_float(x: Any) -> bool: + """ + Function checks if the input is convertible to float + """ + if x is None: + return False + if len(x) == 0: + return False + try: + float(x) + return True + except ValueError: + return False + + +def float_or_none(x: Any) -> Optional[float]: + """ + Function returns a float if x is convertible to float, otherwise None + """ + return float(x) if is_float(x) else None diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_hand_poses.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_hand_poses.py new file mode 100644 index 0000000000000000000000000000000000000000..42d50df41166a8391165347c45be01c578af566a --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_hand_poses.py @@ -0,0 +1,201 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import json +from dataclasses import dataclass +from enum import Enum +from typing import Dict, List, Optional + +import numpy as np +from projectaria_tools.core.sophus import SE3 # @manual + +LEFT_HAND_INDEX = 0 +RIGHT_HAND_INDEX = 1 + + +class Handedness(Enum): + Left = int(LEFT_HAND_INDEX) + Right = int(RIGHT_HAND_INDEX) + + +@dataclass +class HandPose: + """Define a Hand pose as wrist_pose (SE3), and joint_angles.""" + + handedness: Handedness + wrist_pose: Optional[SE3] + joint_angles: List[float] + + def is_left_hand(self) -> bool: + return self.handedness == Handedness.Left + + def is_right_hand(self) -> bool: + return self.handedness == Handedness.Right + + def handedness_label(self) -> str: + return "left" if self.is_left_hand() else "right" + + +@dataclass +class HandPose3dCollection: + """ + Class to store the Hand poses for a given timestamp + """ + + timestamp_ns: int + poses: Dict[Handedness, HandPose] + + +TimestampHandPoses3d = Dict[int, HandPose3dCollection] + + +def _get_hand_pose(handedness: str, hand_poses_json: Dict) -> Optional[SE3]: + if handedness in hand_poses_json.keys(): + wrist = hand_poses_json[handedness]["wrist_xform"] + quaternion_w = wrist["q_wxyz"][0] + quaternion_xyz = wrist["q_wxyz"][1:4] + translation = wrist["t_xyz"] + hand_pose = SE3.from_quat_and_translation( + float(quaternion_w), + np.array([float(o) for o in quaternion_xyz]), + np.array([float(o) for o in translation]), + )[0] + return hand_pose + return None + + +def _get_mano_joint_angles( + handedness: str, hand_poses_json: Dict +) -> Optional[List[float]]: + if handedness in hand_poses_json.keys(): + pose_pca = hand_poses_json[handedness]["pose"] + return pose_pca + return None + + +def parse_hand_poses_from_fileobject(fileobject): + hand_poses_per_timestamp: TimestampHandPoses3d = {} + for line in fileobject: + # Parse the JSON file line + hand_pose_instance = json.loads(line) + timestamp_ns = hand_pose_instance["timestamp_ns"] + hand_poses_json = hand_pose_instance["hand_poses"] + + # Read hand pose data + left_hand_pose = _get_hand_pose(str(LEFT_HAND_INDEX), hand_poses_json) + right_hand_pose = _get_hand_pose(str(RIGHT_HAND_INDEX), hand_poses_json) + + left_joint_angles = _get_mano_joint_angles( + str(LEFT_HAND_INDEX), hand_poses_json + ) + right_joint_angles = _get_mano_joint_angles( + str(RIGHT_HAND_INDEX), hand_poses_json + ) + + # If hand pose data is available, add it to the dictionary + if ( + left_hand_pose is not None or right_hand_pose is not None + ) and timestamp_ns not in hand_poses_per_timestamp: + hand_poses_per_timestamp[timestamp_ns] = HandPose3dCollection( + timestamp_ns=timestamp_ns, poses={} + ) + + if left_hand_pose is not None: + hand_poses_per_timestamp[timestamp_ns].poses[Handedness.Left] = HandPose( + Handedness.Left, left_hand_pose, left_joint_angles + ) + + if right_hand_pose is not None: + hand_poses_per_timestamp[timestamp_ns].poses[Handedness.Right] = HandPose( + Handedness.Right, right_hand_pose, right_joint_angles + ) + return hand_poses_per_timestamp + +def parse_hamer_hand_poses_from_fileobject(fileobject): + hand_poses_per_timestamp: TimestampHandPoses3d = {} + for line in fileobject: + # Parse the JSON file line + hand_pose_instance = json.loads(line) + timestamp_ns = hand_pose_instance["timestamp_ns"] + hand_poses_json = hand_pose_instance["hand_poses"] + + # Read hand pose data + left_hand_pose = _get_hand_pose(str(LEFT_HAND_INDEX), hand_poses_json) + right_hand_pose = _get_hand_pose(str(RIGHT_HAND_INDEX), hand_poses_json) + + left_joint_angles = _get_mano_joint_angles( + str(LEFT_HAND_INDEX), hand_poses_json + ) + right_joint_angles = _get_mano_joint_angles( + str(RIGHT_HAND_INDEX), hand_poses_json + ) + + # If hand pose data is available, add it to the dictionary + if ( + left_hand_pose is not None or right_hand_pose is not None + ) and timestamp_ns not in hand_poses_per_timestamp: + hand_poses_per_timestamp[timestamp_ns] = HandPose3dCollection( + timestamp_ns=timestamp_ns, poses={} + ) + + if left_hand_pose is not None: + hand_poses_per_timestamp[timestamp_ns].poses[Handedness.Left] = HandPose( + Handedness.Left, left_hand_pose, left_joint_angles + ) + + if right_hand_pose is not None: + hand_poses_per_timestamp[timestamp_ns].poses[Handedness.Right] = HandPose( + Handedness.Right, right_hand_pose, right_joint_angles + ) + return hand_poses_per_timestamp + + +def load_hand_poses(filename: str) -> TimestampHandPoses3d: + """Load Hand Poses meta data from a JSONL file. + + Keyword arguments: + filename -- the jsonl file i.e. sequence_folder + "/hand_pose_trajectory.jsonl" + """ + with open(filename, "r") as fobj: + hand_poses_per_timestamp = parse_hand_poses_from_fileobject(fobj) + + return hand_poses_per_timestamp + +def load_hamer_hand_poses(filename: str) -> TimestampHandPoses3d: + """Load Hand Poses meta data from a JSONL file. + + Keyword arguments: + filename -- the jsonl file i.e. sequence_folder + "/hand_pose_trajectory.jsonl" + """ + with open(filename, "r") as fobj: + hand_poses_per_timestamp = parse_hamer_hand_poses_from_fileobject(fobj) + + return hand_poses_per_timestamp + + +def load_mano_shape_params(filename: str) -> Optional[List[float]]: + betas = None + with open(filename, "rb") as f: + for line in f: + hand_pose_instance = json.loads(line) + for handedness in ["0", "1"]: + if ( + handedness in hand_pose_instance["hand_poses"].keys() + and "betas" in hand_pose_instance["hand_poses"][handedness] + ): + betas = hand_pose_instance["hand_poses"][handedness]["betas"] + break + if betas is not None: + break + return betas diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_masks.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..356e016338fce9b4744bf281da153d139b8568ce --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_masks.py @@ -0,0 +1,157 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +from collections import Counter +from typing import Dict, List, Optional + +import numpy as np +from projectaria_tools.core.stream_id import StreamId # @manual + +from .constants import MASK_DATA_CSV_COLUMNS +from .loader_poses_utils import check_csv_columns + +TimestampedMask = Dict[int, bool] +StreamMask = Dict[str, TimestampedMask] + + +class MaskData(object): + def __init__(self, mask_data: Optional[StreamMask] = None): + self._mask = mask_data if mask_data is not None else Dict[str, bool] + + @property + def data(self): + return self._mask + + @property + def stream_ids(self): + return [StreamId(x) for x in self._mask.keys()] + + def stream_mask(self, stream_id: StreamId) -> Optional[TimestampedMask]: + return self._mask.get(str(stream_id), None) + + def length(self, stream_id: StreamId) -> int: + if str(stream_id) not in self._mask: + return 0 + return len(self._mask[str(stream_id)]) + + def num_true(self, stream_id: StreamId) -> int: + """Return the number of True values""" + if str(stream_id) not in self._mask: + return 0 + + return Counter(self._mask[str(stream_id)].values()).get(True, 0) + + def num_false(self, stream_id: StreamId) -> int: + """Return the number of False values""" + if str(stream_id) not in self._mask: + return 0 + return Counter(self._mask[str(stream_id)].values()).get(False, 0) + + def stats(self): + return { + sid: { + "length": self.length(sid), + "num_true": self.num_true(sid), + "num_false": self.num_false(sid), + } + for sid in sorted(self._mask.keys()) + } + + +def load_mask_data(mask_filename: str) -> MaskData: + """Load mask data from a HOT3D mask CSV file. + Data saved as CSV with three columns: + # timestamp[ns],stream_id,mask + # 67842008213302,214-1,True + # ... + """ + mask = {} + with open(mask_filename, "r") as f: + reader = csv.reader(f) + + # Read the header row + header = next(reader) + + # Ensure we have the desired columns + check_csv_columns(header, MASK_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in reader: + timestamp_int = row[header.index("timestamp[ns]")] + stream_id_str = row[header.index("stream_id")] + value = row[header.index("mask")] + + if stream_id_str not in mask: + mask[stream_id_str] = {} + + mask[stream_id_str][timestamp_int] = bool(value == "True") + + return MaskData(mask) + + +def combine_mask_data( + mask_list: List[MaskData], + operator: str = "and", # i.e 'and' or 'or' +) -> MaskData: + """ + Combine mask data from two or three sources given a logical operator. + """ + + stream_id_strs = {str(y) for x in mask_list for y in x.stream_ids} + stream_ids = [StreamId(x) for x in stream_id_strs] + + out_mask_dict = {} + for stream_id in stream_ids: + timestamped_mask_list = [x.stream_mask(stream_id=stream_id) for x in mask_list] + if any(x is None for x in timestamped_mask_list): + raise ValueError("mask data must be present for all streams") + out_mask_dict[str(stream_id)] = combine_timestamped_mask_data( + mask_list=timestamped_mask_list, operator=operator + ) + return MaskData(out_mask_dict) + + +def combine_timestamped_mask_data( + mask_list: List[TimestampedMask], + operator: str = "and", # i.e 'and' or 'or' +) -> TimestampedMask: + + if len(mask_list) > 0: + if not all(len(d) == len(mask_list[0]) for d in mask_list): + raise ValueError("Mask data must have the same length") + else: + raise ValueError("mask_list must not be empty") + + ## ensure the timestamps are identical across lists + reference_tsns_list = list(mask_list[0].keys()) + for it in mask_list[1:]: + if list(it.keys()) != reference_tsns_list: + raise ValueError("Mask data must have the same timestamps") + + resulting_array = np.array([mask_list[0][tsns] for tsns in reference_tsns_list]) + # resulting_array = np.array(list(mask_list[0].values())) + for it in mask_list[1:]: + if operator == "and": + resulting_array = resulting_array & np.array( + [it[tsns] for tsns in reference_tsns_list] + ) + elif operator == "or": + resulting_array = resulting_array | np.array( + [it[tsns] for tsns in reference_tsns_list] + ) + else: + raise ValueError("Invalid operator") + + return dict(zip(reference_tsns_list, resulting_array.tolist())) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_object_library.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_object_library.py new file mode 100644 index 0000000000000000000000000000000000000000..18c5b6935de8032bbc400277c479cf8420a2ff18 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_object_library.py @@ -0,0 +1,92 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + + +import os +from typing import Any, Dict, Set + +from .io_utils import load_json + + +class ObjectLibrary(object): + def __init__(self, object_library_json: Dict[str, Any], asset_folder: str): + self._object_library_json = object_library_json + ( + self._object_id_to_name_dict, + self._object_name_to_id_dict, + ) = self._get_object_id_name_mappings(object_library_json) + ( + self._headset_id_to_name_dict, + self._headset_name_to_id_dict, + ) = self._get_headset_id_name_mappings(object_library_json) + + self._asset_folder = asset_folder + + @property + def object_id_to_name_dict(self): + return self._object_id_to_name_dict + + @property + def object_name_to_id_dict(self): + return self._object_name_to_id_dict + + @property + def headset_id_to_name_dict(self): + return self._headset_id_to_name_dict + + @property + def headset_name_to_id_dict(self): + return self._headset_name_to_id_dict + + @property + def object_uids(self) -> Set[str]: + return set(self._object_name_to_id_dict.values()) + + @property + def headset_uids(self) -> Set[str]: + return set(self._headset_name_to_id_dict.values()) + + @property + def asset_folder_name(self) -> str: + return self._asset_folder + + def _get_object_id_name_mappings(self, object_info_json): + + object_id_to_name_dict = { + k: v["instance_name"] + for k, v in object_info_json.items() + if v["instance_type"] == "object" and v["motion_type"] == "dynamic" + } + object_name_to_id_dict = {v: k for k, v in object_id_to_name_dict.items()} + return object_id_to_name_dict, object_name_to_id_dict + + def _get_headset_id_name_mappings(self, object_info_json): + headset_id_to_name_dict = { + k: v["instance_name"] + for k, v in object_info_json.items() + if v["instance_type"] == "headset" + } + headset_name_to_id_dict = {v: k for k, v in headset_id_to_name_dict.items()} + return headset_id_to_name_dict, headset_name_to_id_dict + + @staticmethod + def get_cad_asset_path(object_library_folderpath: str, object_id: str) -> str: + return os.path.join(object_library_folderpath, f"{object_id}.glb") + + +def load_object_library(object_library_folderpath: str) -> ObjectLibrary: + instance_filepath = os.path.join(object_library_folderpath, "instance.json") + object_library_json = load_json(instance_filepath) + asset_folder = os.path.join(object_library_folderpath) + return ObjectLibrary(object_library_json, asset_folder) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_poses_utils.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_poses_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..58a266244547f4fd60541a802624b9c340c04356 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/loader_poses_utils.py @@ -0,0 +1,27 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + + +from typing import List + + +def check_csv_columns(csv_columns: List[str], expected_columns: List[str]) -> None: + """Ensure csv_columns is containing all value from expected_columns""" + for column in csv_columns: + if column not in expected_columns: + raise ValueError( + "Invalid Object CSV format. Expected columns are: {}".format( + ", ".join(expected_columns) + ) + ) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/mano_layer.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/mano_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..82e87e141668df5c1e0ea3153bd09840fb8734d5 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/mano_layer.py @@ -0,0 +1,301 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +from typing import List, Optional + +SMPLX_IMPORT_SUCCEEDED = False # default suppose we can't import SMPLX + +try: + import smplx + + SMPLX_IMPORT_SUCCEEDED = True +except ImportError: + print( + "INFO: HOT3D hands requires smplx (See our GitHub repository for more information on its installation)." + ) + +import torch + +mano_joint_mapping = [ + 16, + 17, + 18, + 19, + 20, + 0, + 14, + 15, + 1, + 2, + 3, + 4, + 5, + 6, + 10, + 11, + 12, + 7, + 8, + 9, +] + + +class MANOHandModel: + N_VERT = 778 + N_LANDMARKS = 21 + MANO_FINGERTIP_VERT_INDICES = { + "thumb": 744, + "index": 320, + "middle": 443, + "ring": 554, + "pinky": 671, + } + + def __init__( + self, + mano_model_files_dir: str, + joint_mapper: Optional[List] = mano_joint_mapping, + ): + mano_left_filename = os.path.join(mano_model_files_dir, "MANO_LEFT.pkl") + mano_right_filename = os.path.join(mano_model_files_dir, "MANO_RIGHT.pkl") + + self.use_pose_pca = True + self.num_pose_coeffs = 15 + self.num_shape_params = 10 + self.device = "cpu" + self.dtype = torch.float32 + self.joint_mapper = joint_mapper + + self.mano_layer_left = smplx.create( + mano_left_filename, + "mano", + use_pca=self.use_pose_pca, + is_rhand=False, + num_pca_comps=self.num_pose_coeffs, + ) + self.mano_layer_left.to(self.device) + + self.mano_layer_right = smplx.create( + mano_right_filename, + "mano", + use_pca=self.use_pose_pca, + is_rhand=True, + num_pca_comps=self.num_pose_coeffs, + ) + self.mano_layer_right.to(self.device) + + # fix MANO shapedirs of the left hand bug (https://github.com/vchoutas/smplx/issues/48) + if ( + torch.sum( + torch.abs( + self.mano_layer_left.shapedirs[:, 0, :] + - self.mano_layer_right.shapedirs[:, 0, :] + ) + ) + < 1 + ): + self.mano_layer_left.shapedirs[:, 0, :] *= -1 + + def forward_kinematics( + self, + shape_params: torch.Tensor, + joint_angles: torch.Tensor, + global_xfrom: torch.Tensor, + is_right_hand: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + assert shape_params.shape[0] == self.num_shape_params + is_batched = len(joint_angles.shape) == 2 + if len(global_xfrom.shape) == 1: + global_xfrom = torch.unsqueeze(global_xfrom, 0) + assert global_xfrom.shape[1] == 6 + if len(joint_angles.shape) == 1: + joint_angles = torch.unsqueeze(joint_angles, 0) + if self.use_pose_pca: + assert joint_angles.shape[1] == self.num_pose_coeffs + assert is_right_hand.shape[0] == joint_angles.shape[0] + + num_frames = joint_angles.shape[0] + + # Left hand FK + if torch.any(torch.logical_not(is_right_hand)): + left_global_xform = global_xfrom[torch.logical_not(is_right_hand)] + left_joint_angles = joint_angles[torch.logical_not(is_right_hand)] + left_mano_output = self.mano_layer_left( + betas=shape_params[None] + .repeat(left_global_xform.shape[0], 1) + .to(self.dtype), + global_orient=left_global_xform[:, :3].to(self.dtype), + hand_pose=left_joint_angles.to(self.dtype), + transl=left_global_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + return_full_pose=True, + ) + left_full_pose = left_mano_output.full_pose[0, 3:] + left_full_rot = left_mano_output.full_pose[0, :3] + + # Right hand FK + if torch.any(is_right_hand): + right_global_xform = global_xfrom[is_right_hand] + right_joint_angles = joint_angles[is_right_hand] + right_mano_output = self.mano_layer_right( + betas=shape_params[None] + .repeat(right_global_xform.shape[0], 1) + .to(self.dtype), + global_orient=right_global_xform[:, :3].to(self.dtype), + hand_pose=right_joint_angles.to(self.dtype), + transl=right_global_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + return_full_pose=True, + ) + right_full_pose = right_mano_output.full_pose[0, 3:] + right_full_rot = right_mano_output.full_pose[0, :3] + + # Merge the left and right hand outputs + out_vertices = torch.zeros( + ( + num_frames, + self.N_VERT, + 3, + ) + ).to(self.device) + if torch.any(torch.logical_not(is_right_hand)): + out_vertices[torch.logical_not(is_right_hand)] = left_mano_output.vertices + if torch.sum(is_right_hand) > 0: + out_vertices[is_right_hand] = right_mano_output.vertices + + out_landmarks = torch.zeros( + ( + num_frames, + self.N_LANDMARKS, + 3, + ) + ).to(self.device) + if torch.any(torch.logical_not(is_right_hand)): + out_pose = left_full_pose + out_rot = left_full_rot + out_trans = left_global_xform[:, 3:].to(self.dtype)[0] + out_betas = left_mano_output.betas[0] + if left_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + left_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([left_mano_output.joints, extra_joints], dim=1) + else: + joints = left_mano_output.joints + out_landmarks[torch.logical_not(is_right_hand)] = joints + if torch.sum(is_right_hand) > 0: + out_pose = right_full_pose + out_rot = right_full_rot + out_trans = right_global_xform[:, 3:].to(self.dtype)[0] + out_betas = right_mano_output.betas[0] + if right_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + right_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([right_mano_output.joints, extra_joints], dim=1) + else: + joints = right_mano_output.joints + out_landmarks[is_right_hand] = joints + + assert out_landmarks.shape[1] == self.N_LANDMARKS + + if self.joint_mapper is not None: + out_landmarks = out_landmarks[:, self.joint_mapper] + + if not is_batched: + out_vertices = torch.squeeze(out_vertices, 0) + out_landmarks = torch.squeeze(out_landmarks, 0) + + return out_vertices, out_landmarks, out_rot, out_trans, out_pose, out_betas + + def shape_only_forward_kinematics( + self, + shape_params: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Method to get the vertices and landmarks of the hand using only the shape + parameters and passing 0s for pose params and global xform. + + Args: + shape_params: N x 6 (N is the number of frames) or 6, + """ + is_batched = len(shape_params.shape) == 2 + if is_batched: + assert shape_params.shape[1] == self.num_shape_params + num_frames = shape_params.shape[0] + else: + assert shape_params.shape[0] == self.num_shape_params + shape_params = shape_params.unsqueeze(0) + num_frames = 1 + + # create zero pose params + pose_params = torch.zeros((num_frames, 15)) + pose_xform = torch.zeros((num_frames, 6)) + + # FK + left_mano_output = self.mano_layer_left( + betas=shape_params.to(self.dtype), + global_orient=pose_xform[:, :3].to(self.dtype), + hand_pose=pose_params.to(self.dtype), + transl=pose_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + ) + + # Merge the left and right hand outputs + out_vertices = left_mano_output.vertices + + if left_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + left_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([left_mano_output.joints, extra_joints], dim=1) + else: + joints = left_mano_output.joints + out_landmarks = joints + + assert out_landmarks.shape[1] == self.N_LANDMARKS + + if self.joint_mapper is not None: + out_landmarks = out_landmarks[:, self.joint_mapper] + + if not is_batched: + out_vertices = torch.squeeze(out_vertices, 0) + out_landmarks = torch.squeeze(out_landmarks, 0) + + return out_vertices, out_landmarks + + +def loadManoHandModel( + mano_model_files_dir: Optional[str], +) -> MANOHandModel: + if not SMPLX_IMPORT_SUCCEEDED or mano_model_files_dir is None: + return None + + return MANOHandModel(mano_model_files_dir) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/pose_utils.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/pose_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cb52f869a187e035857da89771a4b456c52639 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/pose_utils.py @@ -0,0 +1,101 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import bisect +from typing import Any, Dict, List, Optional, Tuple + +from projectaria_tools.core.sensor_data import TimeQueryOptions # @manual + + +def query_left_right(ordered_timestamps: List, query_timestamp: int): + """ + Return the left and right timestamp of the query timestamp by using bisection. + Assumption: timestamps are monotonically sorted in the ordered_timestamps List + """ + idx = bisect.bisect_left(ordered_timestamps, query_timestamp) + if idx == 0: + lower_timestamp = None + else: + lower_timestamp = ordered_timestamps[idx - 1] + + if idx == len(ordered_timestamps): + upper_timestamp = None + else: + upper_timestamp = ordered_timestamps[idx] + + if lower_timestamp is not None and upper_timestamp is not None: + alpha = (query_timestamp - lower_timestamp) / ( + upper_timestamp - lower_timestamp + ) + else: + alpha = None + return lower_timestamp, upper_timestamp, alpha + + +def lookup_timestamp( + time_indexed_dict: Dict[int, Any], + sorted_timestamp_list: Optional[List[int]], + query_timestamp: int, + time_query_options: TimeQueryOptions, +) -> Tuple[Any, int]: + """ + Lookup the object corresponding to query_timestamp based on the time_query_options. + time_indexed_dict: a dictionary of timestamp to object + sorted_timestamp_list: a precomputed list of sorted timestamps in time_indexed_dict. If None, it will be computed from time_indexed_dict. + query_timestamp: the timestamp to query + time_query_options: the time query options to use (CLOSEST, BEFORE, AFTER) + """ + + if sorted_timestamp_list is None: + sorted_timestamp_list = sorted(time_indexed_dict.keys()) + + obj = None + time_delta_ns = None + + if query_timestamp in time_indexed_dict: + obj = time_indexed_dict[query_timestamp] + time_delta_ns = 0 + else: + left_frame_tsns, right_frame_tsns, alpha = query_left_right( + ordered_timestamps=sorted_timestamp_list, + query_timestamp=query_timestamp, + ) + if time_query_options == TimeQueryOptions.BEFORE: + if left_frame_tsns is not None: + obj = time_indexed_dict[left_frame_tsns] + time_delta_ns = query_timestamp - left_frame_tsns + + elif time_query_options == TimeQueryOptions.AFTER: + if right_frame_tsns is not None: + obj = time_indexed_dict[right_frame_tsns] + time_delta_ns = query_timestamp - right_frame_tsns + + elif time_query_options == TimeQueryOptions.CLOSEST: + if left_frame_tsns is not None and right_frame_tsns is not None: + if abs(query_timestamp - left_frame_tsns) > abs( + query_timestamp - right_frame_tsns + ): + obj = time_indexed_dict[right_frame_tsns] + time_delta_ns = query_timestamp - right_frame_tsns + else: + obj = time_indexed_dict[left_frame_tsns] + time_delta_ns = query_timestamp - left_frame_tsns + elif left_frame_tsns is not None: + obj = time_indexed_dict[left_frame_tsns] + time_delta_ns = query_timestamp - left_frame_tsns + elif right_frame_tsns is not None: + obj = time_indexed_dict[right_frame_tsns] + time_delta_ns = query_timestamp - right_frame_tsns + + return obj, time_delta_ns diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/rotation_compat.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/rotation_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..80d0adc1690d7209d85971dc746b28952833767f --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/rotation_compat.py @@ -0,0 +1,12 @@ +"""CPU-only rotation conversion for the vendored HOT3D GT provider.""" + +import numpy as np +from scipy.spatial.transform import Rotation +import torch + + +def matrix_to_axis_angle(matrix: torch.Tensor) -> torch.Tensor: + if matrix.shape != (3, 3) or matrix.requires_grad or matrix.device.type != "cpu": + raise ValueError("HOT3D GT wrist rotation must be a detached CPU 3x3 matrix") + value = Rotation.from_matrix(matrix.detach().numpy().astype(np.float64)).as_rotvec() + return torch.as_tensor(np.array(value, copy=True), dtype=matrix.dtype) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_hands.csv b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_hands.csv new file mode 100644 index 0000000000000000000000000000000000000000..564ac4a9eeff0c85d762b3e2b4f7a41e8252ad78 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_hands.csv @@ -0,0 +1,19 @@ +stream_id,hand_index,timestamp[ns],x_min[pixel],x_max[pixel],y_min[pixel],y_max[pixel],visibility_ratio[%] +214-1,0,56773008264542,1135,1382,616,882,1.0 +214-1,1,56773008264542,1147,1383,444,606,1.0 +214-1,0,56823008196882,1047,1237,634,771,1.0 +214-1,1,56823008196882,1103,1271,312,499,1.0 +214-1,0,56873008205866,903,1180,705,868,1.0 +214-1,1,56873008205866,922,1183,389,620,1.0 +1201-1,0,56773008347142,510,578,82,188,1.0 +1201-1,1,56773008347142,525,604,34,81,1.0 +1201-1,0,56823008294232,478,541,82,140,1.0 +1201-1,1,56823008294232,514,564,0,42,1.0 +1201-1,0,56873008299754,421,513,88,164,1.0 +1201-1,1,56873008299754,439,539,0,56,1.0 +1201-2,0,56773008347130,509,586,398,466,1.0 +1201-2,1,56773008347130,508,585,311,392,1.0 +1201-2,0,56823008294220,479,542,396,440,1.0 +1201-2,1,56823008294220,487,533,279,342,1.0 +1201-2,0,56873008299742,422,525,453,479,1.0 +1201-2,1,56873008299742,426,517,329,419,1.0 diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_objects.csv b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_objects.csv new file mode 100644 index 0000000000000000000000000000000000000000..20f1997c2cd4bc791a5096114af147036724e9f0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_objects.csv @@ -0,0 +1,31 @@ +stream_id,object_uid,timestamp[ns],x_min[pixel],x_max[pixel],y_min[pixel],y_max[pixel],visibility_ratio[%] +214-1,225397651484143,56773008264542,1298,1368,839,1088,0.9550728949717346 +214-1,194930206998778,56773008264542,838,1059,486,726,1.0 +214-1,225397651484143,56823008196882,834,1063,865,913,1.0 +214-1,194930206998778,56823008196882,840,1169,386,719,0.9773508641516446 +214-1,253405647833885,56823008196882,1182,1300,1039,1110,1.0 +214-1,194930206998778,56873008205866,1044,1331,952,1241,1.0 +214-1,96945373046044,56873008205866,896,932,760,791,0.15743519781718962 +214-1,253405647833885,56873008205866,852,984,552,764,0.9002003352549164 +1201-1,225397651484143,56773008347142,519,567,183,273,1.0 +1201-1,194930206998778,56773008347142,403,491,5,97,1.0 +1201-1,96945373046044,56773008347142,564,594,253,289,1.0 +1201-1,253405647833885,56773008347142,590,626,282,325,1.0 +1201-1,225397651484143,56823008294232,389,468,144,169,1.0 +1201-1,194930206998778,56823008294232,405,532,0,99,0.9799943909507338 +1201-1,253405647833885,56823008294232,486,525,230,259,1.0 +1201-1,225397651484143,56873008299754,585,626,297,368,1.0 +1201-1,194930206998778,56873008299754,443,537,197,297,1.0 +1201-1,96945373046044,56873008299754,418,432,104,122,0.20871143375680581 +1201-1,253405647833885,56873008299754,401,463,20,108,0.97145822522055 +1201-2,225397651484143,56773008347130,580,586,417,433,0.6715328467153284 +1201-2,194930206998778,56773008347130,393,477,338,430,1.0 +1201-2,228358276546933,56773008347130,535,577,10,56,1.0 +1201-2,261746112525368,56773008347130,511,540,17,58,1.0 +1201-2,225397651484143,56823008294220,458,486,474,479,1.0 +1201-2,194930206998778,56823008294220,392,514,313,437,0.981008459114281 +1201-2,261746112525368,56823008294220,594,606,57,76,1.0 +1201-2,96945373046044,56823008294220,410,436,309,330,0.2748735244519393 +1201-2,194930206998778,56873008299742,536,550,476,479,1.0 +1201-2,228358276546933,56873008299742,441,480,102,142,1.0 +1201-2,253405647833885,56873008299742,401,450,401,479,0.967680608365019 diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/test_AriaDataProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/test_AriaDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..895820b205a3f1a34207f0bde5d900b2a6d056a0 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/test_AriaDataProvider.py @@ -0,0 +1,85 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +import unittest + +from data_loaders.AriaDataProvider import AriaDataProvider +from projectaria_tools.core.calibration import FISHEYE624, LINEAR +from projectaria_tools.core.stream_id import StreamId + +aria_vrs_resource = "aria_sample_recording/sequence.vrs" + +try: + from libfb.py import parutil + + vrs_file_filepath = parutil.get_file_path( + "test_data/" + aria_vrs_resource, pkg=__package__ + ) +except ImportError: + from pathlib import Path + + THIS_DIR = Path(__file__) + vrs_file_filepath = str(THIS_DIR.parent / aria_vrs_resource) + + +class TestAriaDataProvider(unittest.TestCase): + def setUp(self) -> None: + super().setUp() + + def test_provider_aria_recording(self) -> None: + self.assertTrue(os.path.exists(vrs_file_filepath)) + provider = AriaDataProvider(vrs_file_filepath, "") + + self.assertIsNotNone(provider) + self.assertIsNotNone(provider.get_device_calibration()) + + # Aria VRS files contains 3 Image streams (1 RGB, 2 SLAM) + stream_ids = provider.get_image_stream_ids() + self.assertEqual(len(stream_ids), 3) + self.assertTrue(StreamId("214-1") in stream_ids) + self.assertTrue(StreamId("1201-1") in stream_ids) + self.assertTrue(StreamId("1201-2") in stream_ids) + + timestamps = provider.get_sequence_timestamps() + self.assertTrue(len(timestamps) > 0) + + for stream_id in stream_ids: + img_array = provider.get_image(timestamps[0], stream_id) + self.assertIsNotNone(img_array) + if "rgb" in provider.get_image_stream_label(stream_id): + self.assertEqual(img_array.shape, (1408, 1408, 3)) + elif "slam" in provider.get_image_stream_label(stream_id): + self.assertEqual(img_array.shape, (480, 640)) + + undistorted_img_array = provider.get_image(timestamps[0], stream_id) + self.assertIsNotNone(undistorted_img_array) + + # Retrieve camera calibration + self.assertIsNotNone(provider.get_camera_calibration(stream_id)) + self.assertIsNotNone(provider.get_camera_calibration(stream_id, FISHEYE624)) + self.assertIsNotNone(provider.get_camera_calibration(stream_id, LINEAR)) + + # Assert we have the right camera type + self.assertEqual( + provider.get_camera_calibration(stream_id)[1].model_name(), + FISHEYE624, + ) + self.assertEqual( + provider.get_camera_calibration(stream_id, LINEAR)[1].model_name(), + LINEAR, + ) + + # MPS resources are empty since not initialized + self.assertIsNone(provider.get_point_cloud()) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/test_HandBox2dDataProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/test_HandBox2dDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..67107335d5687870e6e7cd011dbeecd67d8d76ac --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/test_HandBox2dDataProvider.py @@ -0,0 +1,67 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +import unittest + +from data_loaders.HandBox2dDataProvider import load_box2d_trajectory_from_csv +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +box2d_hands_resource = "aria_sample_recording/box2d_hands.csv" + +try: + from libfb.py import parutil + + box2d_hands_filepath = parutil.get_file_path( + "test_data/" + box2d_hands_resource, pkg=__package__ + ) +except ImportError: + from pathlib import Path + + THIS_DIR = Path(__file__) + box2d_hands_filepath = str(THIS_DIR.parent / box2d_hands_resource) + + +class TestHandBox2dDataProvider(unittest.TestCase): + def setUp(self) -> None: + super().setUp() + + def test_provider_aria_recording(self) -> None: + self.assertTrue(os.path.exists(box2d_hands_filepath)) + provider = load_box2d_trajectory_from_csv(filename=box2d_hands_filepath) + + stream_ids = provider.stream_ids + self.assertEqual(len(stream_ids), 3) + + self.assertTrue(StreamId("214-1") in stream_ids) + self.assertTrue(StreamId("1201-1") in stream_ids) + self.assertTrue(StreamId("1201-2") in stream_ids) + + for stream_id in stream_ids: + timestamp_ns_list = provider.get_timestamp_ns_list(stream_id=stream_id) + self.assertIsNotNone(timestamp_ns_list) + self.assertGreater(len(timestamp_ns_list), 0) + + query_timestamp_ns = timestamp_ns_list[len(timestamp_ns_list) // 2] + + box2d_collection_with_dt = provider.get_bbox_at_timestamp( + stream_id=stream_id, + timestamp_ns=query_timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + ) + + self.assertIsNotNone(box2d_collection_with_dt) + self.assertIsNotNone(box2d_collection_with_dt.box2d_collection) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/test_ObjectBox2dDataProvider.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/test_ObjectBox2dDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..1875ba371ad42bea016b4afe8865f34a33653a42 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/data_loaders/tests/test_ObjectBox2dDataProvider.py @@ -0,0 +1,73 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +import unittest + +from data_loaders.ObjectBox2dDataProvider import load_box2d_trajectory_from_csv +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +box2d_objects_resource = "aria_sample_recording/box2d_objects.csv" + +try: + from libfb.py import parutil + + box2d_objects_filepath = parutil.get_file_path( + "test_data/" + box2d_objects_resource, pkg=__package__ + ) +except ImportError: + from pathlib import Path + + THIS_DIR = Path(__file__) + box2d_objects_filepath = str(THIS_DIR.parent / box2d_objects_resource) + + +class TestObjectBox2dDataProvider(unittest.TestCase): + def setUp(self) -> None: + super().setUp() + + def test_provider_aria_recording(self) -> None: + self.assertTrue(os.path.exists(box2d_objects_filepath)) + provider = load_box2d_trajectory_from_csv(filename=box2d_objects_filepath) + object_uids = provider.object_uids + self.assertEqual(len(object_uids), 6) + + stream_ids = provider.stream_ids + self.assertEqual(len(stream_ids), 3) + + self.assertTrue(StreamId("214-1") in stream_ids) + self.assertTrue(StreamId("1201-1") in stream_ids) + self.assertTrue(StreamId("1201-2") in stream_ids) + + for stream_id in stream_ids: + timestamp_ns_list = provider.get_timestamp_ns_list(stream_id=stream_id) + self.assertIsNotNone(timestamp_ns_list) + self.assertGreater(len(timestamp_ns_list), 0) + + query_timestamp_ns = timestamp_ns_list[len(timestamp_ns_list) // 2] + + box2d_collection_with_dt = provider.get_box2d_at_timestamp( + stream_id=stream_id, + timestamp_ns=query_timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + ) + + self.assertIsNotNone(box2d_collection_with_dt) + self.assertIsNotNone(box2d_collection_with_dt.box2d_collection) + object_uids_at_query_timestamp = ( + box2d_collection_with_dt.box2d_collection.object_uid_list + ) + self.assertGreater(len(object_uids_at_query_timestamp), 0) diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/dataset_api.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/dataset_api.py new file mode 100644 index 0000000000000000000000000000000000000000..09eb2b03bdf11d3a69d54eeaf4b409cf445b9232 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/dataset_api.py @@ -0,0 +1,236 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +from typing import Any, Dict, Optional + +import data_loaders.HandBox2dDataProvider as HandBox2dDataProvider + +import data_loaders.ObjectBox2dDataProvider as ObjectBox2dDataProvider + +from data_loaders.AriaDataProvider import AriaDataProvider + +from data_loaders.HeadsetPose3dProvider import ( + HeadsetPose3dProvider, + load_headset_pose_provider_from_csv, +) + +from data_loaders.headsets import Headset +from data_loaders.io_utils import load_json +from data_loaders.loader_object_library import ObjectLibrary +from data_loaders.mano_layer import MANOHandModel +from data_loaders.ManoHandDataProvider import MANOHandDataProvider +from data_loaders.HamerManoHandDataProvider import HamerMANOHandDataProvider + +from data_loaders.ObjectPose3dProvider import ( + load_pose_provider_from_csv, + ObjectPose3dProvider, +) +from data_loaders.PathProvider import Hot3dDataPathProvider + +from data_loaders.QuestDataProvider import QuestDataProvider + +# 3D assets +# - object_uid + +# 3D transform +# Aria Device to Optitrack + +# Generic idea around the DataProvider is that is allow to initialize the data reading +# and offer a generic interface to retrieve timestamp data by TYPE (Image, Object, Hand, etc.) + + +class Hot3dDataProvider: + """ + High Level interface to retrieve and use data from the hot3d dataset + """ + + def __init__( + self, + sequence_folder: str, + object_library: ObjectLibrary, + mano_hand_model: Optional[MANOHandModel] = None, + fail_on_missing_data: bool = True, + use_slam_hamer: bool = False, + ) -> None: + """ + INIT_DOC_STRING + """ + # Will read all required metadata + # Hands + # Objects + # Device type, ... + self.path_provider = Hot3dDataPathProvider.fromRecordingFolder( + recording_instance_folderpath=sequence_folder + ) + if use_slam_hamer: + self.hamer_mano_hand_pose_trajectory_filepath = self.path_provider.mano_hand_pose_trajectory_filepath.replace("mano_hand_pose_trajectory.jsonl", "slam_hamer.jsonl") + else: + self.hamer_mano_hand_pose_trajectory_filepath = None + + if not self.path_provider.is_valid(): + missing_filepaths = [ + filepath + for filepath in self.path_provider.required_filepaths + if not os.path.exists(filepath) + ] + + if fail_on_missing_data: + raise RuntimeError( + f"Invalid hot3d path. Not all expected data are present. missing_filepaths: {missing_filepaths}" + ) + else: + print( + f"Not all expected data are present. missing_filepaths: {missing_filepaths}" + ) + + self._dynamic_objects_provider = load_pose_provider_from_csv( + self.path_provider.dynamic_objects_filepath + ) + + self._device_pose_provider = load_headset_pose_provider_from_csv( + self.path_provider.headset_trajectory_filepath + ) + + self._object_box2d_provider = ( + ObjectBox2dDataProvider.load_box2d_trajectory_from_csv( + self.path_provider.box2d_objects_filepath + ) + ) + + self._hand_box2d_provider = ( + HandBox2dDataProvider.load_box2d_trajectory_from_csv( + self.path_provider.box2d_hands_filepath + ) + ) + + self._object_library: ObjectLibrary = object_library + + self._mano_hand_data_provider = None + if os.path.isfile(self.path_provider.mano_hand_pose_trajectory_filepath): + if mano_hand_model is not None: + if self.hamer_mano_hand_pose_trajectory_filepath: + self._mano_hand_data_provider = HamerMANOHandDataProvider( + self.hamer_mano_hand_pose_trajectory_filepath, + mano_hand_model, + ) + else: + self._mano_hand_data_provider = MANOHandDataProvider( + self.path_provider.mano_hand_pose_trajectory_filepath, + mano_hand_model, + ) + else: + print("No MANO hand model provided, skipping MANO hand data provider") + else: + print( + f"WARN: Cannot find {self.path_provider.mano_hand_pose_trajectory_filepath}" + ) + + if self.get_device_type() == Headset.Aria: + self._device_data_provider = AriaDataProvider( + self.path_provider.vrs_filepath, + self.path_provider.mps_folderpath, + ) + elif self.get_device_type() == Headset.Quest3: + self._device_data_provider = QuestDataProvider( + self.path_provider.vrs_filepath, + self.path_provider.camera_models_filepath, + ) + else: + raise RuntimeError(f"Unsupported device type {self.get_device_type()}") + + def get_data_statistics(self) -> Dict[str, Any]: + statistics_dict = {} + statistics_dict["dynamic_objects"] = ( + self._dynamic_objects_provider.get_data_statistics() + ) + + if self._mano_hand_data_provider is not None: + statistics_dict["mano_hand_poses"] = ( + self._mano_hand_data_provider.get_data_statistics() + ) + + if self._object_box2d_provider is not None: + statistics_dict["object_box2ds"] = ( + self.object_box2d_data_provider.get_data_statistics() + ) + + if self._hand_box2d_provider is not None: + statistics_dict["hand_box2ds"] = ( + self.hand_box2d_data_provider.get_data_statistics() + ) + return statistics_dict + + @property + def object_library(self) -> ObjectLibrary: + """ + Return the object library used for initializing the Hot3dDataProvider + """ + return self._object_library + + @property + def device_data_provider(self): + """ + Return the device data provider (calibration and image stream data) + """ + return self._device_data_provider + + @property + def mano_hand_data_provider(self) -> Optional[MANOHandDataProvider]: + """ + Return the Mano hand data provider + """ + return self._mano_hand_data_provider + + @property + def object_box2d_data_provider(self): + """ + Return the object box2d data provider + """ + return self._object_box2d_provider + + @property + def hand_box2d_data_provider(self): + """ + Return the hand box2d data provider + """ + return self._hand_box2d_provider + + @property + def object_pose_data_provider(self) -> Optional[ObjectPose3dProvider]: + """ + Return the object pose provider + """ + return self._dynamic_objects_provider + + @property + def device_pose_data_provider(self) -> Optional[HeadsetPose3dProvider]: + """ + Return the device pose provider + """ + return self._device_pose_provider + + def get_device_type(self) -> Headset: + """ + Return the type of device used for recording (e.g. Quest3, Aria, etc.) + """ + return Headset[self.get_sequence_metadata()["headset"]] + + def get_sequence_metadata(self) -> Dict: + """ + Return the metadata associated with the sequence + """ + metadata_json = load_json(self.path_provider.scene_metadata_filepath) + + return metadata_json diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/export_gt.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/export_gt.py new file mode 100644 index 0000000000000000000000000000000000000000..aec9abc30f1f1fc9a749aebd1c2f4bfd3ff2fc1b --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/export_gt.py @@ -0,0 +1,25 @@ +import pickle +from viewer_export_gt import export_gt +import json +# import concurrent.futures + + +def load_set(set_file='train_set.pkl'): + try: + with open(set_file, 'rb') as f: + set = pickle.load(f) + return set + except FileNotFoundError: + return f"Error: The file {set_file} does not exist." + +if __name__ == "__main__": + + set = ['P0001_a68492d5', 'P0001_9b6feab7', 'P0014_8254f925', 'P0011_76ea6d47', 'P0014_84ea2dcc', 'P0001_8d136980', 'P0012_476bae57', 'P0012_130a66e1', 'P0014_24cb3bf0', 'P0010_1c9fe708', 'P0002_2ea9af5b', 'P0011_11475e24', 'P0010_0ecbf39f', 'P0010_160e551c', 'P0015_42b8b389', 'P0012_915e71c6', 'P0002_65085bfc', 'P0011_47878e48', 'P0011_cee8fe4f', 'P0002_016222d1', 'P0012_d85e10f6', 'P0012_119de519', 'P0010_41c4c626', 'P0012_f7e3880b', 'P0009_02511c2f', 'P0011_72efb935', 'P0010_924e574e'] + print(set) + cnt = 0 + for video_name in set: + export_gt("dataset/" + video_name, start_frame=20) + cnt += 1 + print(f"finished {cnt}/{len(set)} test videos") + with open('hot3d_dataset_export/val.json', 'w') as f: + json.dump(set, f) \ No newline at end of file diff --git a/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/viewer_export_gt.py b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/viewer_export_gt.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d8e02511953fefdbf90ff522c069ee51ee6e18 --- /dev/null +++ b/home/wuyifan/a7_rotation_fix_20260930_code/third_party/hot3d/viewer_export_gt.py @@ -0,0 +1,293 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import argparse +import os +import shutil +import subprocess +from typing import Optional, Type + +import rerun as rr # @manual +from data_loaders.loader_object_library import load_object_library +from data_loaders.mano_layer import loadManoHandModel +from data_loaders.hamer_mano_layer import loadHamerManoHandModel + +import sys +sys.path.append("..") +import pickle +import numpy as np +from collections import defaultdict +import torch +import joblib + +try: + from dataset_api import Hot3dDataProvider # @manual +except ImportError: + from hot3d.dataset_api import Hot3dDataProvider + +try: + from Hot3DVisualizer import Hot3DVisualizer +except ImportError: + from hot3d.Hot3DVisualizer import Hot3DVisualizer + +from tqdm import tqdm +import cv2 + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--sequence_folder", + type=str, + help="path to hot3d data sequence", + required=True, + ) + parser.add_argument( + "--object_library_folder", + type=str, + help="path to object library folder containing instance.json and *.glb cad files", + required=True, + ) + parser.add_argument( + "--mano_model_folder", + type=str, + default=None, + help="path to MANO models containing the MANO_RIGHT/LEFT.pkl files", + required=False, + ) + + parser.add_argument("--jpeg_quality", type=int, default=75, help=argparse.SUPPRESS) + + # If this path is set, we will save the rerun (.rrd) file to the given path + parser.add_argument( + "--rrd_output_path", type=str, default=None, help=argparse.SUPPRESS + ) + parser.add_argument( + "--use_slam_hamer", action="store_true" + ) + + return parser.parse_args() + + +def execute_rerun( + sequence_folder: str, + object_library_folder: str, + mano_model_folder: Optional[str], + rrd_output_path: Optional[str], + jpeg_quality: int, + timestamps_slice: Type[slice], + fail_on_missing_data: bool, + use_slam_hamer: bool, +): + export_gt_folder = sequence_folder.replace('dataset', 'hot3d_dataset_export') + if not os.path.exists(export_gt_folder): + os.makedirs(export_gt_folder) + # if os.path.exists(os.path.join(export_gt_folder, export_gt_folder.split('/')[-1] + '.mp4')): + # return + + if not os.path.exists(sequence_folder): + raise RuntimeError(f"Sequence folder {sequence_folder} does not exist") + if not os.path.exists(object_library_folder): + raise RuntimeError( + f"Object Library folder {object_library_folder} does not exist" + ) + + object_library = load_object_library( + object_library_folderpath=object_library_folder + ) + + if use_slam_hamer: + mano_hand_model = loadHamerManoHandModel(mano_model_folder) + else: + mano_hand_model = loadManoHandModel(mano_model_folder) + + # + # Initialize hot3d data provider + # + data_provider = Hot3dDataProvider( + sequence_folder=sequence_folder, + object_library=object_library, + mano_hand_model=mano_hand_model, + fail_on_missing_data=fail_on_missing_data, + use_slam_hamer=use_slam_hamer, + ) + print(f"data_provider statistics: {data_provider.get_data_statistics()}") + + # + # Prepare the rerun rerun log configuration + # + # rr.init("hot3d Data Viewer", spawn=(rrd_output_path is None)) + # if rrd_output_path is not None: + # print(f"Saving .rrd file to {rrd_output_path}") + # rr.save(rrd_output_path) + + # + # Initialize the rerun hot3d visualizer interface + # + rr_visualizer = Hot3DVisualizer(data_provider) + + # Define which image stream will be shown + image_stream_ids = data_provider.device_data_provider.get_image_stream_ids() + + # + # Log static assets (aka Timeless assets) + rr_visualizer.log_static_assets(image_stream_ids, disable_vis=True) + + timestamps = data_provider.device_data_provider.get_sequence_timestamps() + # + # Visualize the dataset sequence + # + # Loop over the timestamps of the sequence and visualize corresponding data + image_list = [] + tt_list = [] + ego_extrinsics_list = [] + head_pose_list = [] + data_video = defaultdict(list) + + for timestamp in tqdm(timestamps[timestamps_slice]): + + rr.set_time_nanos("synchronization_time", int(timestamp)) + rr.set_time_sequence("timestamp", timestamp) + + ego_image_cv2, head_pose, ego_extrinsics, ego_focal, data_img = rr_visualizer.log_dynamic_assets(image_stream_ids, timestamp, disable_vis=True) + if head_pose is None: + continue + for key in data_img.keys(): + data_video[key].extend(data_img[key]) + ego_extrinsics_list.append(ego_extrinsics) + head_pose_list.append(head_pose) + image_list.append(ego_image_cv2) + tt_list.append(timestamp) + data_video_all = {} + for key in data_video.keys(): + if torch.is_tensor(data_video[key][0]): + data_video_all[key] = torch.stack(data_video[key]) + save_pth = os.path.join(export_gt_folder, 'anno.pth') + joblib.dump(data_video_all, save_pth) + print("saved", save_pth) + head_pose_list = np.stack(head_pose_list) + ego_extrinsics_list = np.stack(ego_extrinsics_list) + with open(os.path.join(export_gt_folder, 'head_pose.pkl'), 'wb') as file: + pickle.dump(head_pose_list, file) + with open(os.path.join(export_gt_folder, 'ego_extrinsics.pkl'), 'wb') as file: + pickle.dump(ego_extrinsics_list, file) + with open(os.path.join(export_gt_folder, 'focal.txt'), 'w') as file: + file.write(str(ego_focal)) + + with open(os.path.join(export_gt_folder, 'tt_list.pkl'), 'wb') as file: + pickle.dump(tt_list, file) + create_video_from_list_fast(image_list, os.path.join(export_gt_folder, export_gt_folder.split('/')[-1] + '.mp4')) + + +def create_video_from_list_fast(image_list, output_path): + tmp_folder = os.path.join(os.path.dirname(output_path), 'extracted_images') + os.makedirs(tmp_folder, exist_ok=True) + for t, img in enumerate(tqdm(image_list)): + cv2.imwrite(os.path.join(tmp_folder, f"{t:04d}.jpg"), img) + create_video_from_images_ffmpeg(tmp_folder, output_path) + # shutil.rmtree(tmp_folder) + + +def create_video_from_images_ffmpeg(image_folder, output_video, frame_rate=30): + # 确保图片文件夹存在 + if not os.path.isdir(image_folder): + raise ValueError(f"Image folder {image_folder} does not exist.") + + # 构建 FFmpeg 命令 + ffmpeg_command = [ + 'ffmpeg', + '-framerate', str(frame_rate), + '-i', os.path.join(image_folder, '%04d.jpg'), # 假设图片文件名为 0001.png, 0002.png, 0003.png, ... + '-c:v', 'h264_nvenc', + '-preset', 'fast', + '-pix_fmt', 'yuv420p', + output_video + ] + + # 打印 FFmpeg 命令(可选) + print('Running FFmpeg command:', ' '.join(ffmpeg_command)) + + # 调用 FFmpeg 命令 + subprocess.run(ffmpeg_command, check=True) + +def create_video_from_list(image_list, output_path, fps=30): + # Check if the list is not empty + if not image_list: + print("The image list is empty.") + return + + # Get the width and height of the images + height, width, _ = image_list[0].shape + + # Define the codec and create VideoWriter object + fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Codec for mp4 + video_writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) + + # Write each frame to the video file + for image in tqdm(image_list): + video_writer.write(image) + + # Release the video writer + video_writer.release() + print(f"Video saved to {output_path}") + +def main(): + args = parse_args() + print(f"args provided: {args}") + + try: + execute_rerun( + sequence_folder=args.sequence_folder, + object_library_folder=args.object_library_folder, + mano_model_folder=args.mano_model_folder, + rrd_output_path=args.rrd_output_path, + jpeg_quality=args.jpeg_quality, + timestamps_slice=slice(None, 300, None), + fail_on_missing_data=False, + use_slam_hamer=args.use_slam_hamer, + ) + except Exception as error: + print(f"An exception occurred: {error}") + +def export_gt(sequence_folder, start_frame=20, debug=False): + print(sequence_folder) + # args = parse_args() + # print(f"args provided: {args}") + from easydict import EasyDict as edict + args = edict() + args.object_library_folder = "dataset/assets" + args.mano_model_folder = "mano_v1_2/models/" + args.rrd_output_path = None + args.jpeg_quality = 75 + args.use_slam_hamer = False + + if debug: + len = 300 + else: + len = None + + execute_rerun( + sequence_folder=sequence_folder, + object_library_folder=args.object_library_folder, + mano_model_folder=args.mano_model_folder, + rrd_output_path=args.rrd_output_path, + jpeg_quality=args.jpeg_quality, + timestamps_slice=slice(start_frame, len, None), + fail_on_missing_data=False, + use_slam_hamer=args.use_slam_hamer, + ) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/arctic_t8.jsonl b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/arctic_t8.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6055e14f7bc7480a154cde613b8268df017c3a3b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/arctic_t8.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35b61473010ae198b036d3c549ae1b922439e35711e5bc76f7f06c58fd82e7e6 +size 41251962 diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/h2o_t8.jsonl b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/h2o_t8.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..484710aa62cc9de3f049d12e1a2c0eaeeedde633 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/h2o_t8.jsonl @@ -0,0 +1,6406 @@ +{"filtered_tile_id":"00ee8ce028134272d95bd8c4:0","filtered_window_id":"00ee8ce028134272d95bd8c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/00ee8ce028134272d95bd8c4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[539,540,541,542,543,544,545,546],"take":"subject2/h2/3/cam4","frame_ids":[539,540,541,542,543,544,545,546]} +{"filtered_tile_id":"00ee8ce028134272d95bd8c4:8","filtered_window_id":"00ee8ce028134272d95bd8c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/00ee8ce028134272d95bd8c4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[547,548,549,550,551,552,553,554],"take":"subject2/h2/3/cam4","frame_ids":[547,548,549,550,551,552,553,554]} +{"filtered_tile_id":"00ee8ce028134272d95bd8c4:16","filtered_window_id":"00ee8ce028134272d95bd8c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/00ee8ce028134272d95bd8c4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[555,556,557,558,559,560,561,562],"take":"subject2/h2/3/cam4","frame_ids":[555,556,557,558,559,560,561,562]} +{"filtered_tile_id":"00ee8ce028134272d95bd8c4:24","filtered_window_id":"00ee8ce028134272d95bd8c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/00ee8ce028134272d95bd8c4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[563,564,565,566,567,568,569,570],"take":"subject2/h2/3/cam4","frame_ids":[563,564,565,566,567,568,569,570]} +{"filtered_tile_id":"00ee8ce028134272d95bd8c4:32","filtered_window_id":"00ee8ce028134272d95bd8c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/00ee8ce028134272d95bd8c4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[571,572,573,574,575,576,577,578],"take":"subject2/h2/3/cam4","frame_ids":[571,572,573,574,575,576,577,578]} +{"filtered_tile_id":"00ee8ce028134272d95bd8c4:40","filtered_window_id":"00ee8ce028134272d95bd8c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/00ee8ce028134272d95bd8c4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[579,580,581,582,583,584,585,586],"take":"subject2/h2/3/cam4","frame_ids":[579,580,581,582,583,584,585,586]} +{"filtered_tile_id":"00ee8ce028134272d95bd8c4:48","filtered_window_id":"00ee8ce028134272d95bd8c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/00ee8ce028134272d95bd8c4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[587,588,589,590,591,592,593,594],"take":"subject2/h2/3/cam4","frame_ids":[587,588,589,590,591,592,593,594]} +{"filtered_tile_id":"00ee8ce028134272d95bd8c4:52","filtered_window_id":"00ee8ce028134272d95bd8c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/00ee8ce028134272d95bd8c4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[591,592,593,594,595,596,597,598],"take":"subject2/h2/3/cam4","frame_ids":[591,592,593,594,595,596,597,598]} +{"filtered_tile_id":"0156ff6a7ce9466204fc5f3e:0","filtered_window_id":"0156ff6a7ce9466204fc5f3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0156ff6a7ce9466204fc5f3e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject2/o1/2/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"0156ff6a7ce9466204fc5f3e:8","filtered_window_id":"0156ff6a7ce9466204fc5f3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0156ff6a7ce9466204fc5f3e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject2/o1/2/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"0156ff6a7ce9466204fc5f3e:16","filtered_window_id":"0156ff6a7ce9466204fc5f3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0156ff6a7ce9466204fc5f3e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject2/o1/2/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"0156ff6a7ce9466204fc5f3e:24","filtered_window_id":"0156ff6a7ce9466204fc5f3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0156ff6a7ce9466204fc5f3e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject2/o1/2/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"0156ff6a7ce9466204fc5f3e:32","filtered_window_id":"0156ff6a7ce9466204fc5f3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0156ff6a7ce9466204fc5f3e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject2/o1/2/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"0156ff6a7ce9466204fc5f3e:40","filtered_window_id":"0156ff6a7ce9466204fc5f3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0156ff6a7ce9466204fc5f3e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[219,220,221,222,223,224,225,226],"take":"subject2/o1/2/cam4","frame_ids":[219,220,221,222,223,224,225,226]} +{"filtered_tile_id":"0156ff6a7ce9466204fc5f3e:48","filtered_window_id":"0156ff6a7ce9466204fc5f3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0156ff6a7ce9466204fc5f3e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[227,228,229,230,231,232,233,234],"take":"subject2/o1/2/cam4","frame_ids":[227,228,229,230,231,232,233,234]} +{"filtered_tile_id":"0156ff6a7ce9466204fc5f3e:52","filtered_window_id":"0156ff6a7ce9466204fc5f3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0156ff6a7ce9466204fc5f3e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject2/o1/2/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"017ca6c82b287b1b96a0a016:0","filtered_window_id":"017ca6c82b287b1b96a0a016","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/017ca6c82b287b1b96a0a016/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[109,110,111,112,113,114,115,116],"take":"subject2/k1/3/cam4","frame_ids":[109,110,111,112,113,114,115,116]} +{"filtered_tile_id":"017ca6c82b287b1b96a0a016:8","filtered_window_id":"017ca6c82b287b1b96a0a016","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/017ca6c82b287b1b96a0a016/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[117,118,119,120,121,122,123,124],"take":"subject2/k1/3/cam4","frame_ids":[117,118,119,120,121,122,123,124]} +{"filtered_tile_id":"017ca6c82b287b1b96a0a016:16","filtered_window_id":"017ca6c82b287b1b96a0a016","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/017ca6c82b287b1b96a0a016/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[125,126,127,128,129,130,131,132],"take":"subject2/k1/3/cam4","frame_ids":[125,126,127,128,129,130,131,132]} +{"filtered_tile_id":"017ca6c82b287b1b96a0a016:24","filtered_window_id":"017ca6c82b287b1b96a0a016","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/017ca6c82b287b1b96a0a016/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject2/k1/3/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"017ca6c82b287b1b96a0a016:32","filtered_window_id":"017ca6c82b287b1b96a0a016","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/017ca6c82b287b1b96a0a016/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject2/k1/3/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"017ca6c82b287b1b96a0a016:40","filtered_window_id":"017ca6c82b287b1b96a0a016","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/017ca6c82b287b1b96a0a016/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject2/k1/3/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"017ca6c82b287b1b96a0a016:48","filtered_window_id":"017ca6c82b287b1b96a0a016","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/017ca6c82b287b1b96a0a016/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject2/k1/3/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"017ca6c82b287b1b96a0a016:52","filtered_window_id":"017ca6c82b287b1b96a0a016","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/017ca6c82b287b1b96a0a016/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject2/k1/3/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"01ac2ab457e0a3c758cc6044:0","filtered_window_id":"01ac2ab457e0a3c758cc6044","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01ac2ab457e0a3c758cc6044/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[453,454,455,456,457,458,459,460],"take":"subject2/h1/6/cam4","frame_ids":[453,454,455,456,457,458,459,460]} +{"filtered_tile_id":"01ac2ab457e0a3c758cc6044:8","filtered_window_id":"01ac2ab457e0a3c758cc6044","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01ac2ab457e0a3c758cc6044/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject2/h1/6/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"01ac2ab457e0a3c758cc6044:16","filtered_window_id":"01ac2ab457e0a3c758cc6044","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01ac2ab457e0a3c758cc6044/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[469,470,471,472,473,474,475,476],"take":"subject2/h1/6/cam4","frame_ids":[469,470,471,472,473,474,475,476]} +{"filtered_tile_id":"01ac2ab457e0a3c758cc6044:24","filtered_window_id":"01ac2ab457e0a3c758cc6044","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01ac2ab457e0a3c758cc6044/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[477,478,479,480,481,482,483,484],"take":"subject2/h1/6/cam4","frame_ids":[477,478,479,480,481,482,483,484]} +{"filtered_tile_id":"01ac2ab457e0a3c758cc6044:32","filtered_window_id":"01ac2ab457e0a3c758cc6044","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01ac2ab457e0a3c758cc6044/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[485,486,487,488,489,490,491,492],"take":"subject2/h1/6/cam4","frame_ids":[485,486,487,488,489,490,491,492]} +{"filtered_tile_id":"01ac2ab457e0a3c758cc6044:40","filtered_window_id":"01ac2ab457e0a3c758cc6044","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01ac2ab457e0a3c758cc6044/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[493,494,495,496,497,498,499,500],"take":"subject2/h1/6/cam4","frame_ids":[493,494,495,496,497,498,499,500]} +{"filtered_tile_id":"01ac2ab457e0a3c758cc6044:48","filtered_window_id":"01ac2ab457e0a3c758cc6044","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01ac2ab457e0a3c758cc6044/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[501,502,503,504,505,506,507,508],"take":"subject2/h1/6/cam4","frame_ids":[501,502,503,504,505,506,507,508]} +{"filtered_tile_id":"01ac2ab457e0a3c758cc6044:52","filtered_window_id":"01ac2ab457e0a3c758cc6044","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01ac2ab457e0a3c758cc6044/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[505,506,507,508,509,510,511,512],"take":"subject2/h1/6/cam4","frame_ids":[505,506,507,508,509,510,511,512]} +{"filtered_tile_id":"01e18fcf17c3344722e81833:0","filtered_window_id":"01e18fcf17c3344722e81833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01e18fcf17c3344722e81833/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject2/o1/4/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"01e18fcf17c3344722e81833:8","filtered_window_id":"01e18fcf17c3344722e81833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01e18fcf17c3344722e81833/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject2/o1/4/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"01e18fcf17c3344722e81833:16","filtered_window_id":"01e18fcf17c3344722e81833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01e18fcf17c3344722e81833/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject2/o1/4/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"01e18fcf17c3344722e81833:24","filtered_window_id":"01e18fcf17c3344722e81833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01e18fcf17c3344722e81833/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[481,482,483,484,485,486,487,488],"take":"subject2/o1/4/cam4","frame_ids":[481,482,483,484,485,486,487,488]} +{"filtered_tile_id":"01e18fcf17c3344722e81833:32","filtered_window_id":"01e18fcf17c3344722e81833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01e18fcf17c3344722e81833/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[489,490,491,492,493,494,495,496],"take":"subject2/o1/4/cam4","frame_ids":[489,490,491,492,493,494,495,496]} +{"filtered_tile_id":"01e18fcf17c3344722e81833:40","filtered_window_id":"01e18fcf17c3344722e81833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01e18fcf17c3344722e81833/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[497,498,499,500,501,502,503,504],"take":"subject2/o1/4/cam4","frame_ids":[497,498,499,500,501,502,503,504]} +{"filtered_tile_id":"01e18fcf17c3344722e81833:48","filtered_window_id":"01e18fcf17c3344722e81833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01e18fcf17c3344722e81833/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[505,506,507,508,509,510,511,512],"take":"subject2/o1/4/cam4","frame_ids":[505,506,507,508,509,510,511,512]} +{"filtered_tile_id":"01e18fcf17c3344722e81833:52","filtered_window_id":"01e18fcf17c3344722e81833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01e18fcf17c3344722e81833/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[509,510,511,512,513,514,515,516],"take":"subject2/o1/4/cam4","frame_ids":[509,510,511,512,513,514,515,516]} +{"filtered_tile_id":"01fb72664453bbaf3e19281f:0","filtered_window_id":"01fb72664453bbaf3e19281f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01fb72664453bbaf3e19281f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[542,543,544,545,546,547,548,549],"take":"subject2/o1/3/cam4","frame_ids":[542,543,544,545,546,547,548,549]} +{"filtered_tile_id":"01fb72664453bbaf3e19281f:8","filtered_window_id":"01fb72664453bbaf3e19281f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01fb72664453bbaf3e19281f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[550,551,552,553,554,555,556,557],"take":"subject2/o1/3/cam4","frame_ids":[550,551,552,553,554,555,556,557]} +{"filtered_tile_id":"01fb72664453bbaf3e19281f:16","filtered_window_id":"01fb72664453bbaf3e19281f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01fb72664453bbaf3e19281f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[558,559,560,561,562,563,564,565],"take":"subject2/o1/3/cam4","frame_ids":[558,559,560,561,562,563,564,565]} +{"filtered_tile_id":"01fb72664453bbaf3e19281f:24","filtered_window_id":"01fb72664453bbaf3e19281f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01fb72664453bbaf3e19281f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[566,567,568,569,570,571,572,573],"take":"subject2/o1/3/cam4","frame_ids":[566,567,568,569,570,571,572,573]} +{"filtered_tile_id":"01fb72664453bbaf3e19281f:32","filtered_window_id":"01fb72664453bbaf3e19281f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01fb72664453bbaf3e19281f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[574,575,576,577,578,579,580,581],"take":"subject2/o1/3/cam4","frame_ids":[574,575,576,577,578,579,580,581]} +{"filtered_tile_id":"01fb72664453bbaf3e19281f:40","filtered_window_id":"01fb72664453bbaf3e19281f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01fb72664453bbaf3e19281f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[582,583,584,585,586,587,588,589],"take":"subject2/o1/3/cam4","frame_ids":[582,583,584,585,586,587,588,589]} +{"filtered_tile_id":"01fb72664453bbaf3e19281f:48","filtered_window_id":"01fb72664453bbaf3e19281f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01fb72664453bbaf3e19281f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[590,591,592,593,594,595,596,597],"take":"subject2/o1/3/cam4","frame_ids":[590,591,592,593,594,595,596,597]} +{"filtered_tile_id":"01fb72664453bbaf3e19281f:52","filtered_window_id":"01fb72664453bbaf3e19281f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/01fb72664453bbaf3e19281f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[594,595,596,597,598,599,600,601],"take":"subject2/o1/3/cam4","frame_ids":[594,595,596,597,598,599,600,601]} +{"filtered_tile_id":"0341e183e146c6ad8e67f969:0","filtered_window_id":"0341e183e146c6ad8e67f969","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0341e183e146c6ad8e67f969/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/h2/0/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"0341e183e146c6ad8e67f969:8","filtered_window_id":"0341e183e146c6ad8e67f969","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0341e183e146c6ad8e67f969/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject2/h2/0/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"0341e183e146c6ad8e67f969:16","filtered_window_id":"0341e183e146c6ad8e67f969","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0341e183e146c6ad8e67f969/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject2/h2/0/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"0341e183e146c6ad8e67f969:24","filtered_window_id":"0341e183e146c6ad8e67f969","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0341e183e146c6ad8e67f969/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject2/h2/0/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"0341e183e146c6ad8e67f969:32","filtered_window_id":"0341e183e146c6ad8e67f969","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0341e183e146c6ad8e67f969/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject2/h2/0/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"0341e183e146c6ad8e67f969:40","filtered_window_id":"0341e183e146c6ad8e67f969","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0341e183e146c6ad8e67f969/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject2/h2/0/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"0341e183e146c6ad8e67f969:48","filtered_window_id":"0341e183e146c6ad8e67f969","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0341e183e146c6ad8e67f969/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject2/h2/0/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"0341e183e146c6ad8e67f969:50","filtered_window_id":"0341e183e146c6ad8e67f969","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0341e183e146c6ad8e67f969/native_gt.npz","filtered_start_offset":50,"expected_frame_ids":[110,111,112,113,114,115,116,117],"take":"subject2/h2/0/cam4","frame_ids":[110,111,112,113,114,115,116,117]} +{"filtered_tile_id":"03a7c6f5f62f16e7799abcf4:0","filtered_window_id":"03a7c6f5f62f16e7799abcf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03a7c6f5f62f16e7799abcf4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[641,642,643,644,645,646,647,648],"take":"subject2/o1/1/cam4","frame_ids":[641,642,643,644,645,646,647,648]} +{"filtered_tile_id":"03a7c6f5f62f16e7799abcf4:8","filtered_window_id":"03a7c6f5f62f16e7799abcf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03a7c6f5f62f16e7799abcf4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[649,650,651,652,653,654,655,656],"take":"subject2/o1/1/cam4","frame_ids":[649,650,651,652,653,654,655,656]} +{"filtered_tile_id":"03a7c6f5f62f16e7799abcf4:16","filtered_window_id":"03a7c6f5f62f16e7799abcf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03a7c6f5f62f16e7799abcf4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[657,658,659,660,661,662,663,664],"take":"subject2/o1/1/cam4","frame_ids":[657,658,659,660,661,662,663,664]} +{"filtered_tile_id":"03a7c6f5f62f16e7799abcf4:24","filtered_window_id":"03a7c6f5f62f16e7799abcf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03a7c6f5f62f16e7799abcf4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[665,666,667,668,669,670,671,672],"take":"subject2/o1/1/cam4","frame_ids":[665,666,667,668,669,670,671,672]} +{"filtered_tile_id":"03a7c6f5f62f16e7799abcf4:32","filtered_window_id":"03a7c6f5f62f16e7799abcf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03a7c6f5f62f16e7799abcf4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[673,674,675,676,677,678,679,680],"take":"subject2/o1/1/cam4","frame_ids":[673,674,675,676,677,678,679,680]} +{"filtered_tile_id":"03a7c6f5f62f16e7799abcf4:40","filtered_window_id":"03a7c6f5f62f16e7799abcf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03a7c6f5f62f16e7799abcf4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[681,682,683,684,685,686,687,688],"take":"subject2/o1/1/cam4","frame_ids":[681,682,683,684,685,686,687,688]} +{"filtered_tile_id":"03a7c6f5f62f16e7799abcf4:48","filtered_window_id":"03a7c6f5f62f16e7799abcf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03a7c6f5f62f16e7799abcf4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[689,690,691,692,693,694,695,696],"take":"subject2/o1/1/cam4","frame_ids":[689,690,691,692,693,694,695,696]} +{"filtered_tile_id":"03a7c6f5f62f16e7799abcf4:52","filtered_window_id":"03a7c6f5f62f16e7799abcf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03a7c6f5f62f16e7799abcf4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[693,694,695,696,697,698,699,700],"take":"subject2/o1/1/cam4","frame_ids":[693,694,695,696,697,698,699,700]} +{"filtered_tile_id":"03da90c487cbc625da31d3b0:0","filtered_window_id":"03da90c487cbc625da31d3b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03da90c487cbc625da31d3b0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject2/h1/7/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"03da90c487cbc625da31d3b0:8","filtered_window_id":"03da90c487cbc625da31d3b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03da90c487cbc625da31d3b0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject2/h1/7/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"03da90c487cbc625da31d3b0:16","filtered_window_id":"03da90c487cbc625da31d3b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03da90c487cbc625da31d3b0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject2/h1/7/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"03da90c487cbc625da31d3b0:24","filtered_window_id":"03da90c487cbc625da31d3b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03da90c487cbc625da31d3b0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject2/h1/7/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"03da90c487cbc625da31d3b0:32","filtered_window_id":"03da90c487cbc625da31d3b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03da90c487cbc625da31d3b0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject2/h1/7/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"03da90c487cbc625da31d3b0:40","filtered_window_id":"03da90c487cbc625da31d3b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03da90c487cbc625da31d3b0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject2/h1/7/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"03da90c487cbc625da31d3b0:48","filtered_window_id":"03da90c487cbc625da31d3b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03da90c487cbc625da31d3b0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject2/h1/7/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"03da90c487cbc625da31d3b0:52","filtered_window_id":"03da90c487cbc625da31d3b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/03da90c487cbc625da31d3b0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject2/h1/7/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"04243af66fd5284e5e4b59b7:0","filtered_window_id":"04243af66fd5284e5e4b59b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04243af66fd5284e5e4b59b7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject3/k1/5/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"04243af66fd5284e5e4b59b7:8","filtered_window_id":"04243af66fd5284e5e4b59b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04243af66fd5284e5e4b59b7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject3/k1/5/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"04243af66fd5284e5e4b59b7:16","filtered_window_id":"04243af66fd5284e5e4b59b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04243af66fd5284e5e4b59b7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject3/k1/5/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"04243af66fd5284e5e4b59b7:24","filtered_window_id":"04243af66fd5284e5e4b59b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04243af66fd5284e5e4b59b7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject3/k1/5/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"04243af66fd5284e5e4b59b7:32","filtered_window_id":"04243af66fd5284e5e4b59b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04243af66fd5284e5e4b59b7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject3/k1/5/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"04243af66fd5284e5e4b59b7:40","filtered_window_id":"04243af66fd5284e5e4b59b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04243af66fd5284e5e4b59b7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject3/k1/5/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"04243af66fd5284e5e4b59b7:48","filtered_window_id":"04243af66fd5284e5e4b59b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04243af66fd5284e5e4b59b7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject3/k1/5/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"04243af66fd5284e5e4b59b7:52","filtered_window_id":"04243af66fd5284e5e4b59b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04243af66fd5284e5e4b59b7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[224,225,226,227,228,229,230,231],"take":"subject3/k1/5/cam4","frame_ids":[224,225,226,227,228,229,230,231]} +{"filtered_tile_id":"042d382d4ef815941577848b:0","filtered_window_id":"042d382d4ef815941577848b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/042d382d4ef815941577848b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject1/k1/7/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"042d382d4ef815941577848b:8","filtered_window_id":"042d382d4ef815941577848b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/042d382d4ef815941577848b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject1/k1/7/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"042d382d4ef815941577848b:16","filtered_window_id":"042d382d4ef815941577848b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/042d382d4ef815941577848b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[426,427,428,429,430,431,432,433],"take":"subject1/k1/7/cam4","frame_ids":[426,427,428,429,430,431,432,433]} +{"filtered_tile_id":"042d382d4ef815941577848b:24","filtered_window_id":"042d382d4ef815941577848b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/042d382d4ef815941577848b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[434,435,436,437,438,439,440,441],"take":"subject1/k1/7/cam4","frame_ids":[434,435,436,437,438,439,440,441]} +{"filtered_tile_id":"042d382d4ef815941577848b:32","filtered_window_id":"042d382d4ef815941577848b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/042d382d4ef815941577848b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject1/k1/7/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"042d382d4ef815941577848b:40","filtered_window_id":"042d382d4ef815941577848b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/042d382d4ef815941577848b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject1/k1/7/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"042d382d4ef815941577848b:48","filtered_window_id":"042d382d4ef815941577848b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/042d382d4ef815941577848b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject1/k1/7/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"042d382d4ef815941577848b:52","filtered_window_id":"042d382d4ef815941577848b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/042d382d4ef815941577848b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject1/k1/7/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"0461ac66d05344ea7ca3825e:0","filtered_window_id":"0461ac66d05344ea7ca3825e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0461ac66d05344ea7ca3825e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[291,292,293,294,295,296,297,298],"take":"subject1/o1/3/cam4","frame_ids":[291,292,293,294,295,296,297,298]} +{"filtered_tile_id":"0461ac66d05344ea7ca3825e:8","filtered_window_id":"0461ac66d05344ea7ca3825e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0461ac66d05344ea7ca3825e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[299,300,301,302,303,304,305,306],"take":"subject1/o1/3/cam4","frame_ids":[299,300,301,302,303,304,305,306]} +{"filtered_tile_id":"0461ac66d05344ea7ca3825e:16","filtered_window_id":"0461ac66d05344ea7ca3825e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0461ac66d05344ea7ca3825e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[307,308,309,310,311,312,313,314],"take":"subject1/o1/3/cam4","frame_ids":[307,308,309,310,311,312,313,314]} +{"filtered_tile_id":"0461ac66d05344ea7ca3825e:24","filtered_window_id":"0461ac66d05344ea7ca3825e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0461ac66d05344ea7ca3825e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[315,316,317,318,319,320,321,322],"take":"subject1/o1/3/cam4","frame_ids":[315,316,317,318,319,320,321,322]} +{"filtered_tile_id":"0461ac66d05344ea7ca3825e:32","filtered_window_id":"0461ac66d05344ea7ca3825e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0461ac66d05344ea7ca3825e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[323,324,325,326,327,328,329,330],"take":"subject1/o1/3/cam4","frame_ids":[323,324,325,326,327,328,329,330]} +{"filtered_tile_id":"0461ac66d05344ea7ca3825e:40","filtered_window_id":"0461ac66d05344ea7ca3825e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0461ac66d05344ea7ca3825e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[331,332,333,334,335,336,337,338],"take":"subject1/o1/3/cam4","frame_ids":[331,332,333,334,335,336,337,338]} +{"filtered_tile_id":"0461ac66d05344ea7ca3825e:48","filtered_window_id":"0461ac66d05344ea7ca3825e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0461ac66d05344ea7ca3825e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[339,340,341,342,343,344,345,346],"take":"subject1/o1/3/cam4","frame_ids":[339,340,341,342,343,344,345,346]} +{"filtered_tile_id":"0461ac66d05344ea7ca3825e:52","filtered_window_id":"0461ac66d05344ea7ca3825e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0461ac66d05344ea7ca3825e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[343,344,345,346,347,348,349,350],"take":"subject1/o1/3/cam4","frame_ids":[343,344,345,346,347,348,349,350]} +{"filtered_tile_id":"04d5fb9c5c3dae99371faa4d:0","filtered_window_id":"04d5fb9c5c3dae99371faa4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04d5fb9c5c3dae99371faa4d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject2/h2/3/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"04d5fb9c5c3dae99371faa4d:8","filtered_window_id":"04d5fb9c5c3dae99371faa4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04d5fb9c5c3dae99371faa4d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject2/h2/3/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"04d5fb9c5c3dae99371faa4d:16","filtered_window_id":"04d5fb9c5c3dae99371faa4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04d5fb9c5c3dae99371faa4d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject2/h2/3/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"04d5fb9c5c3dae99371faa4d:24","filtered_window_id":"04d5fb9c5c3dae99371faa4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04d5fb9c5c3dae99371faa4d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject2/h2/3/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"04d5fb9c5c3dae99371faa4d:32","filtered_window_id":"04d5fb9c5c3dae99371faa4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04d5fb9c5c3dae99371faa4d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject2/h2/3/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"04d5fb9c5c3dae99371faa4d:40","filtered_window_id":"04d5fb9c5c3dae99371faa4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04d5fb9c5c3dae99371faa4d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject2/h2/3/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"04d5fb9c5c3dae99371faa4d:48","filtered_window_id":"04d5fb9c5c3dae99371faa4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04d5fb9c5c3dae99371faa4d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject2/h2/3/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"04d5fb9c5c3dae99371faa4d:52","filtered_window_id":"04d5fb9c5c3dae99371faa4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04d5fb9c5c3dae99371faa4d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject2/h2/3/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"04e2cdd63331f344973dafd2:0","filtered_window_id":"04e2cdd63331f344973dafd2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04e2cdd63331f344973dafd2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject1/o1/2/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"04e2cdd63331f344973dafd2:8","filtered_window_id":"04e2cdd63331f344973dafd2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04e2cdd63331f344973dafd2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject1/o1/2/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"04e2cdd63331f344973dafd2:16","filtered_window_id":"04e2cdd63331f344973dafd2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04e2cdd63331f344973dafd2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[156,157,158,159,160,161,162,163],"take":"subject1/o1/2/cam4","frame_ids":[156,157,158,159,160,161,162,163]} +{"filtered_tile_id":"04e2cdd63331f344973dafd2:24","filtered_window_id":"04e2cdd63331f344973dafd2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04e2cdd63331f344973dafd2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[164,165,166,167,168,169,170,171],"take":"subject1/o1/2/cam4","frame_ids":[164,165,166,167,168,169,170,171]} +{"filtered_tile_id":"04e2cdd63331f344973dafd2:30","filtered_window_id":"04e2cdd63331f344973dafd2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/04e2cdd63331f344973dafd2/native_gt.npz","filtered_start_offset":30,"expected_frame_ids":[170,171,172,173,174,175,176,177],"take":"subject1/o1/2/cam4","frame_ids":[170,171,172,173,174,175,176,177]} +{"filtered_tile_id":"052cafa975e5194386b7f40f:0","filtered_window_id":"052cafa975e5194386b7f40f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/052cafa975e5194386b7f40f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject2/h1/0/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"052cafa975e5194386b7f40f:3","filtered_window_id":"052cafa975e5194386b7f40f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/052cafa975e5194386b7f40f/native_gt.npz","filtered_start_offset":3,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject2/h1/0/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"05394f5986d4d19d42604f5d:0","filtered_window_id":"05394f5986d4d19d42604f5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05394f5986d4d19d42604f5d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[72,73,74,75,76,77,78,79],"take":"subject2/h1/0/cam4","frame_ids":[72,73,74,75,76,77,78,79]} +{"filtered_tile_id":"05394f5986d4d19d42604f5d:8","filtered_window_id":"05394f5986d4d19d42604f5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05394f5986d4d19d42604f5d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[80,81,82,83,84,85,86,87],"take":"subject2/h1/0/cam4","frame_ids":[80,81,82,83,84,85,86,87]} +{"filtered_tile_id":"05394f5986d4d19d42604f5d:16","filtered_window_id":"05394f5986d4d19d42604f5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05394f5986d4d19d42604f5d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject2/h1/0/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"05394f5986d4d19d42604f5d:24","filtered_window_id":"05394f5986d4d19d42604f5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05394f5986d4d19d42604f5d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject2/h1/0/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"05394f5986d4d19d42604f5d:28","filtered_window_id":"05394f5986d4d19d42604f5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05394f5986d4d19d42604f5d/native_gt.npz","filtered_start_offset":28,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject2/h1/0/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"054cdc72ab14e0e767294b15:0","filtered_window_id":"054cdc72ab14e0e767294b15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/054cdc72ab14e0e767294b15/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[758,759,760,761,762,763,764,765],"take":"subject2/k2/6/cam4","frame_ids":[758,759,760,761,762,763,764,765]} +{"filtered_tile_id":"054cdc72ab14e0e767294b15:8","filtered_window_id":"054cdc72ab14e0e767294b15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/054cdc72ab14e0e767294b15/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[766,767,768,769,770,771,772,773],"take":"subject2/k2/6/cam4","frame_ids":[766,767,768,769,770,771,772,773]} +{"filtered_tile_id":"054cdc72ab14e0e767294b15:16","filtered_window_id":"054cdc72ab14e0e767294b15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/054cdc72ab14e0e767294b15/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[774,775,776,777,778,779,780,781],"take":"subject2/k2/6/cam4","frame_ids":[774,775,776,777,778,779,780,781]} +{"filtered_tile_id":"054cdc72ab14e0e767294b15:24","filtered_window_id":"054cdc72ab14e0e767294b15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/054cdc72ab14e0e767294b15/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[782,783,784,785,786,787,788,789],"take":"subject2/k2/6/cam4","frame_ids":[782,783,784,785,786,787,788,789]} +{"filtered_tile_id":"054cdc72ab14e0e767294b15:32","filtered_window_id":"054cdc72ab14e0e767294b15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/054cdc72ab14e0e767294b15/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[790,791,792,793,794,795,796,797],"take":"subject2/k2/6/cam4","frame_ids":[790,791,792,793,794,795,796,797]} +{"filtered_tile_id":"054cdc72ab14e0e767294b15:40","filtered_window_id":"054cdc72ab14e0e767294b15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/054cdc72ab14e0e767294b15/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[798,799,800,801,802,803,804,805],"take":"subject2/k2/6/cam4","frame_ids":[798,799,800,801,802,803,804,805]} +{"filtered_tile_id":"054cdc72ab14e0e767294b15:48","filtered_window_id":"054cdc72ab14e0e767294b15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/054cdc72ab14e0e767294b15/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[806,807,808,809,810,811,812,813],"take":"subject2/k2/6/cam4","frame_ids":[806,807,808,809,810,811,812,813]} +{"filtered_tile_id":"054cdc72ab14e0e767294b15:52","filtered_window_id":"054cdc72ab14e0e767294b15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/054cdc72ab14e0e767294b15/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[810,811,812,813,814,815,816,817],"take":"subject2/k2/6/cam4","frame_ids":[810,811,812,813,814,815,816,817]} +{"filtered_tile_id":"056278ad12e95b08340192eb:0","filtered_window_id":"056278ad12e95b08340192eb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/056278ad12e95b08340192eb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject1/h1/0/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"056278ad12e95b08340192eb:8","filtered_window_id":"056278ad12e95b08340192eb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/056278ad12e95b08340192eb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[72,73,74,75,76,77,78,79],"take":"subject1/h1/0/cam4","frame_ids":[72,73,74,75,76,77,78,79]} +{"filtered_tile_id":"056278ad12e95b08340192eb:16","filtered_window_id":"056278ad12e95b08340192eb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/056278ad12e95b08340192eb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[80,81,82,83,84,85,86,87],"take":"subject1/h1/0/cam4","frame_ids":[80,81,82,83,84,85,86,87]} +{"filtered_tile_id":"056278ad12e95b08340192eb:24","filtered_window_id":"056278ad12e95b08340192eb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/056278ad12e95b08340192eb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject1/h1/0/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"056278ad12e95b08340192eb:32","filtered_window_id":"056278ad12e95b08340192eb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/056278ad12e95b08340192eb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject1/h1/0/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"056278ad12e95b08340192eb:40","filtered_window_id":"056278ad12e95b08340192eb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/056278ad12e95b08340192eb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[104,105,106,107,108,109,110,111],"take":"subject1/h1/0/cam4","frame_ids":[104,105,106,107,108,109,110,111]} +{"filtered_tile_id":"056278ad12e95b08340192eb:48","filtered_window_id":"056278ad12e95b08340192eb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/056278ad12e95b08340192eb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[112,113,114,115,116,117,118,119],"take":"subject1/h1/0/cam4","frame_ids":[112,113,114,115,116,117,118,119]} +{"filtered_tile_id":"056278ad12e95b08340192eb:52","filtered_window_id":"056278ad12e95b08340192eb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/056278ad12e95b08340192eb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject1/h1/0/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"0564d6fac2a8fad7ea07e55b:0","filtered_window_id":"0564d6fac2a8fad7ea07e55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0564d6fac2a8fad7ea07e55b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[448,449,450,451,452,453,454,455],"take":"subject2/o1/6/cam4","frame_ids":[448,449,450,451,452,453,454,455]} +{"filtered_tile_id":"0564d6fac2a8fad7ea07e55b:8","filtered_window_id":"0564d6fac2a8fad7ea07e55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0564d6fac2a8fad7ea07e55b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[456,457,458,459,460,461,462,463],"take":"subject2/o1/6/cam4","frame_ids":[456,457,458,459,460,461,462,463]} +{"filtered_tile_id":"0564d6fac2a8fad7ea07e55b:16","filtered_window_id":"0564d6fac2a8fad7ea07e55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0564d6fac2a8fad7ea07e55b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[464,465,466,467,468,469,470,471],"take":"subject2/o1/6/cam4","frame_ids":[464,465,466,467,468,469,470,471]} +{"filtered_tile_id":"0564d6fac2a8fad7ea07e55b:24","filtered_window_id":"0564d6fac2a8fad7ea07e55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0564d6fac2a8fad7ea07e55b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject2/o1/6/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"0564d6fac2a8fad7ea07e55b:32","filtered_window_id":"0564d6fac2a8fad7ea07e55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0564d6fac2a8fad7ea07e55b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject2/o1/6/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"0564d6fac2a8fad7ea07e55b:40","filtered_window_id":"0564d6fac2a8fad7ea07e55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0564d6fac2a8fad7ea07e55b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject2/o1/6/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"0564d6fac2a8fad7ea07e55b:48","filtered_window_id":"0564d6fac2a8fad7ea07e55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0564d6fac2a8fad7ea07e55b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject2/o1/6/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"0564d6fac2a8fad7ea07e55b:52","filtered_window_id":"0564d6fac2a8fad7ea07e55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0564d6fac2a8fad7ea07e55b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[500,501,502,503,504,505,506,507],"take":"subject2/o1/6/cam4","frame_ids":[500,501,502,503,504,505,506,507]} +{"filtered_tile_id":"0572bd793370faca0ed68fe4:0","filtered_window_id":"0572bd793370faca0ed68fe4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0572bd793370faca0ed68fe4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject2/o2/4/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"0572bd793370faca0ed68fe4:8","filtered_window_id":"0572bd793370faca0ed68fe4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0572bd793370faca0ed68fe4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[471,472,473,474,475,476,477,478],"take":"subject2/o2/4/cam4","frame_ids":[471,472,473,474,475,476,477,478]} +{"filtered_tile_id":"0572bd793370faca0ed68fe4:16","filtered_window_id":"0572bd793370faca0ed68fe4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0572bd793370faca0ed68fe4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[479,480,481,482,483,484,485,486],"take":"subject2/o2/4/cam4","frame_ids":[479,480,481,482,483,484,485,486]} +{"filtered_tile_id":"0572bd793370faca0ed68fe4:24","filtered_window_id":"0572bd793370faca0ed68fe4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0572bd793370faca0ed68fe4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject2/o2/4/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"0572bd793370faca0ed68fe4:32","filtered_window_id":"0572bd793370faca0ed68fe4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0572bd793370faca0ed68fe4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[495,496,497,498,499,500,501,502],"take":"subject2/o2/4/cam4","frame_ids":[495,496,497,498,499,500,501,502]} +{"filtered_tile_id":"0572bd793370faca0ed68fe4:40","filtered_window_id":"0572bd793370faca0ed68fe4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0572bd793370faca0ed68fe4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[503,504,505,506,507,508,509,510],"take":"subject2/o2/4/cam4","frame_ids":[503,504,505,506,507,508,509,510]} +{"filtered_tile_id":"0572bd793370faca0ed68fe4:48","filtered_window_id":"0572bd793370faca0ed68fe4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0572bd793370faca0ed68fe4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[511,512,513,514,515,516,517,518],"take":"subject2/o2/4/cam4","frame_ids":[511,512,513,514,515,516,517,518]} +{"filtered_tile_id":"057fffb377c39b96add4e50d:0","filtered_window_id":"057fffb377c39b96add4e50d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/057fffb377c39b96add4e50d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject3/h2/7/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"057fffb377c39b96add4e50d:8","filtered_window_id":"057fffb377c39b96add4e50d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/057fffb377c39b96add4e50d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[361,362,363,364,365,366,367,368],"take":"subject3/h2/7/cam4","frame_ids":[361,362,363,364,365,366,367,368]} +{"filtered_tile_id":"057fffb377c39b96add4e50d:16","filtered_window_id":"057fffb377c39b96add4e50d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/057fffb377c39b96add4e50d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[369,370,371,372,373,374,375,376],"take":"subject3/h2/7/cam4","frame_ids":[369,370,371,372,373,374,375,376]} +{"filtered_tile_id":"057fffb377c39b96add4e50d:24","filtered_window_id":"057fffb377c39b96add4e50d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/057fffb377c39b96add4e50d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[377,378,379,380,381,382,383,384],"take":"subject3/h2/7/cam4","frame_ids":[377,378,379,380,381,382,383,384]} +{"filtered_tile_id":"057fffb377c39b96add4e50d:32","filtered_window_id":"057fffb377c39b96add4e50d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/057fffb377c39b96add4e50d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[385,386,387,388,389,390,391,392],"take":"subject3/h2/7/cam4","frame_ids":[385,386,387,388,389,390,391,392]} +{"filtered_tile_id":"057fffb377c39b96add4e50d:40","filtered_window_id":"057fffb377c39b96add4e50d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/057fffb377c39b96add4e50d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[393,394,395,396,397,398,399,400],"take":"subject3/h2/7/cam4","frame_ids":[393,394,395,396,397,398,399,400]} +{"filtered_tile_id":"057fffb377c39b96add4e50d:48","filtered_window_id":"057fffb377c39b96add4e50d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/057fffb377c39b96add4e50d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[401,402,403,404,405,406,407,408],"take":"subject3/h2/7/cam4","frame_ids":[401,402,403,404,405,406,407,408]} +{"filtered_tile_id":"057fffb377c39b96add4e50d:52","filtered_window_id":"057fffb377c39b96add4e50d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/057fffb377c39b96add4e50d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[405,406,407,408,409,410,411,412],"take":"subject3/h2/7/cam4","frame_ids":[405,406,407,408,409,410,411,412]} +{"filtered_tile_id":"05c739d6d9aaa4334a71c133:0","filtered_window_id":"05c739d6d9aaa4334a71c133","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05c739d6d9aaa4334a71c133/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject1/k2/1/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"05c739d6d9aaa4334a71c133:8","filtered_window_id":"05c739d6d9aaa4334a71c133","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05c739d6d9aaa4334a71c133/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject1/k2/1/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"05c739d6d9aaa4334a71c133:16","filtered_window_id":"05c739d6d9aaa4334a71c133","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05c739d6d9aaa4334a71c133/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject1/k2/1/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"05c739d6d9aaa4334a71c133:24","filtered_window_id":"05c739d6d9aaa4334a71c133","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05c739d6d9aaa4334a71c133/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject1/k2/1/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"05c739d6d9aaa4334a71c133:32","filtered_window_id":"05c739d6d9aaa4334a71c133","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05c739d6d9aaa4334a71c133/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[374,375,376,377,378,379,380,381],"take":"subject1/k2/1/cam4","frame_ids":[374,375,376,377,378,379,380,381]} +{"filtered_tile_id":"05c739d6d9aaa4334a71c133:40","filtered_window_id":"05c739d6d9aaa4334a71c133","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05c739d6d9aaa4334a71c133/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[382,383,384,385,386,387,388,389],"take":"subject1/k2/1/cam4","frame_ids":[382,383,384,385,386,387,388,389]} +{"filtered_tile_id":"05c739d6d9aaa4334a71c133:48","filtered_window_id":"05c739d6d9aaa4334a71c133","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05c739d6d9aaa4334a71c133/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject1/k2/1/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"05c739d6d9aaa4334a71c133:52","filtered_window_id":"05c739d6d9aaa4334a71c133","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/05c739d6d9aaa4334a71c133/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[394,395,396,397,398,399,400,401],"take":"subject1/k2/1/cam4","frame_ids":[394,395,396,397,398,399,400,401]} +{"filtered_tile_id":"06245c23cb04ae9555ce1c6a:0","filtered_window_id":"06245c23cb04ae9555ce1c6a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/06245c23cb04ae9555ce1c6a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject3/h1/0/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"06ca7062670711a85e58e950:0","filtered_window_id":"06ca7062670711a85e58e950","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/06ca7062670711a85e58e950/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[409,410,411,412,413,414,415,416],"take":"subject1/k2/5/cam4","frame_ids":[409,410,411,412,413,414,415,416]} +{"filtered_tile_id":"06ca7062670711a85e58e950:8","filtered_window_id":"06ca7062670711a85e58e950","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/06ca7062670711a85e58e950/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[417,418,419,420,421,422,423,424],"take":"subject1/k2/5/cam4","frame_ids":[417,418,419,420,421,422,423,424]} +{"filtered_tile_id":"06ca7062670711a85e58e950:16","filtered_window_id":"06ca7062670711a85e58e950","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/06ca7062670711a85e58e950/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject1/k2/5/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"06ca7062670711a85e58e950:24","filtered_window_id":"06ca7062670711a85e58e950","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/06ca7062670711a85e58e950/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[433,434,435,436,437,438,439,440],"take":"subject1/k2/5/cam4","frame_ids":[433,434,435,436,437,438,439,440]} +{"filtered_tile_id":"06ca7062670711a85e58e950:32","filtered_window_id":"06ca7062670711a85e58e950","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/06ca7062670711a85e58e950/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject1/k2/5/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"06ca7062670711a85e58e950:40","filtered_window_id":"06ca7062670711a85e58e950","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/06ca7062670711a85e58e950/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject1/k2/5/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"06ca7062670711a85e58e950:48","filtered_window_id":"06ca7062670711a85e58e950","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/06ca7062670711a85e58e950/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject1/k2/5/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"06ca7062670711a85e58e950:52","filtered_window_id":"06ca7062670711a85e58e950","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/06ca7062670711a85e58e950/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject1/k2/5/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"07210d069bee8f7e921d30f7:0","filtered_window_id":"07210d069bee8f7e921d30f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07210d069bee8f7e921d30f7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject1/k2/6/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"07210d069bee8f7e921d30f7:8","filtered_window_id":"07210d069bee8f7e921d30f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07210d069bee8f7e921d30f7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[290,291,292,293,294,295,296,297],"take":"subject1/k2/6/cam4","frame_ids":[290,291,292,293,294,295,296,297]} +{"filtered_tile_id":"07210d069bee8f7e921d30f7:16","filtered_window_id":"07210d069bee8f7e921d30f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07210d069bee8f7e921d30f7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject1/k2/6/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"07210d069bee8f7e921d30f7:24","filtered_window_id":"07210d069bee8f7e921d30f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07210d069bee8f7e921d30f7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[306,307,308,309,310,311,312,313],"take":"subject1/k2/6/cam4","frame_ids":[306,307,308,309,310,311,312,313]} +{"filtered_tile_id":"07210d069bee8f7e921d30f7:32","filtered_window_id":"07210d069bee8f7e921d30f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07210d069bee8f7e921d30f7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject1/k2/6/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"07210d069bee8f7e921d30f7:40","filtered_window_id":"07210d069bee8f7e921d30f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07210d069bee8f7e921d30f7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject1/k2/6/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"07210d069bee8f7e921d30f7:48","filtered_window_id":"07210d069bee8f7e921d30f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07210d069bee8f7e921d30f7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject1/k2/6/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"07210d069bee8f7e921d30f7:52","filtered_window_id":"07210d069bee8f7e921d30f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07210d069bee8f7e921d30f7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject1/k2/6/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"07a4c044b945abcdbc741552:0","filtered_window_id":"07a4c044b945abcdbc741552","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07a4c044b945abcdbc741552/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[74,75,76,77,78,79,80,81],"take":"subject1/o2/3/cam4","frame_ids":[74,75,76,77,78,79,80,81]} +{"filtered_tile_id":"07a4c044b945abcdbc741552:8","filtered_window_id":"07a4c044b945abcdbc741552","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07a4c044b945abcdbc741552/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[82,83,84,85,86,87,88,89],"take":"subject1/o2/3/cam4","frame_ids":[82,83,84,85,86,87,88,89]} +{"filtered_tile_id":"07a4c044b945abcdbc741552:16","filtered_window_id":"07a4c044b945abcdbc741552","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07a4c044b945abcdbc741552/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject1/o2/3/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"07a4c044b945abcdbc741552:24","filtered_window_id":"07a4c044b945abcdbc741552","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07a4c044b945abcdbc741552/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[98,99,100,101,102,103,104,105],"take":"subject1/o2/3/cam4","frame_ids":[98,99,100,101,102,103,104,105]} +{"filtered_tile_id":"07a4c044b945abcdbc741552:32","filtered_window_id":"07a4c044b945abcdbc741552","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07a4c044b945abcdbc741552/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[106,107,108,109,110,111,112,113],"take":"subject1/o2/3/cam4","frame_ids":[106,107,108,109,110,111,112,113]} +{"filtered_tile_id":"07a4c044b945abcdbc741552:40","filtered_window_id":"07a4c044b945abcdbc741552","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07a4c044b945abcdbc741552/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject1/o2/3/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"07a4c044b945abcdbc741552:46","filtered_window_id":"07a4c044b945abcdbc741552","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07a4c044b945abcdbc741552/native_gt.npz","filtered_start_offset":46,"expected_frame_ids":[120,121,122,123,124,125,126,127],"take":"subject1/o2/3/cam4","frame_ids":[120,121,122,123,124,125,126,127]} +{"filtered_tile_id":"07aa21499994581dff22b589:0","filtered_window_id":"07aa21499994581dff22b589","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07aa21499994581dff22b589/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[429,430,431,432,433,434,435,436],"take":"subject1/h2/5/cam4","frame_ids":[429,430,431,432,433,434,435,436]} +{"filtered_tile_id":"07aa21499994581dff22b589:8","filtered_window_id":"07aa21499994581dff22b589","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07aa21499994581dff22b589/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[437,438,439,440,441,442,443,444],"take":"subject1/h2/5/cam4","frame_ids":[437,438,439,440,441,442,443,444]} +{"filtered_tile_id":"07aa21499994581dff22b589:16","filtered_window_id":"07aa21499994581dff22b589","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07aa21499994581dff22b589/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[445,446,447,448,449,450,451,452],"take":"subject1/h2/5/cam4","frame_ids":[445,446,447,448,449,450,451,452]} +{"filtered_tile_id":"07aa21499994581dff22b589:24","filtered_window_id":"07aa21499994581dff22b589","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07aa21499994581dff22b589/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[453,454,455,456,457,458,459,460],"take":"subject1/h2/5/cam4","frame_ids":[453,454,455,456,457,458,459,460]} +{"filtered_tile_id":"07aa21499994581dff22b589:32","filtered_window_id":"07aa21499994581dff22b589","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07aa21499994581dff22b589/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject1/h2/5/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"07aa21499994581dff22b589:40","filtered_window_id":"07aa21499994581dff22b589","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07aa21499994581dff22b589/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[469,470,471,472,473,474,475,476],"take":"subject1/h2/5/cam4","frame_ids":[469,470,471,472,473,474,475,476]} +{"filtered_tile_id":"07aa21499994581dff22b589:42","filtered_window_id":"07aa21499994581dff22b589","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/07aa21499994581dff22b589/native_gt.npz","filtered_start_offset":42,"expected_frame_ids":[471,472,473,474,475,476,477,478],"take":"subject1/h2/5/cam4","frame_ids":[471,472,473,474,475,476,477,478]} +{"filtered_tile_id":"08a343d3123dc3938485c09d:0","filtered_window_id":"08a343d3123dc3938485c09d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/08a343d3123dc3938485c09d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject1/o2/2/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"08a343d3123dc3938485c09d:8","filtered_window_id":"08a343d3123dc3938485c09d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/08a343d3123dc3938485c09d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject1/o2/2/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"08a343d3123dc3938485c09d:11","filtered_window_id":"08a343d3123dc3938485c09d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/08a343d3123dc3938485c09d/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject1/o2/2/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"093cd9860d764ea7196b0978:0","filtered_window_id":"093cd9860d764ea7196b0978","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093cd9860d764ea7196b0978/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/k2/6/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"093cd9860d764ea7196b0978:8","filtered_window_id":"093cd9860d764ea7196b0978","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093cd9860d764ea7196b0978/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/k2/6/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"093cd9860d764ea7196b0978:16","filtered_window_id":"093cd9860d764ea7196b0978","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093cd9860d764ea7196b0978/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/k2/6/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"093cd9860d764ea7196b0978:24","filtered_window_id":"093cd9860d764ea7196b0978","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093cd9860d764ea7196b0978/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/k2/6/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"093cd9860d764ea7196b0978:32","filtered_window_id":"093cd9860d764ea7196b0978","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093cd9860d764ea7196b0978/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/k2/6/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"093cd9860d764ea7196b0978:40","filtered_window_id":"093cd9860d764ea7196b0978","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093cd9860d764ea7196b0978/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[56,57,58,59,60,61,62,63],"take":"subject2/k2/6/cam4","frame_ids":[56,57,58,59,60,61,62,63]} +{"filtered_tile_id":"093cd9860d764ea7196b0978:48","filtered_window_id":"093cd9860d764ea7196b0978","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093cd9860d764ea7196b0978/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject2/k2/6/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"093cd9860d764ea7196b0978:52","filtered_window_id":"093cd9860d764ea7196b0978","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093cd9860d764ea7196b0978/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject2/k2/6/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"093e2a4928868706da4377d0:0","filtered_window_id":"093e2a4928868706da4377d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093e2a4928868706da4377d0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/k2/1/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"093e2a4928868706da4377d0:8","filtered_window_id":"093e2a4928868706da4377d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093e2a4928868706da4377d0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject2/k2/1/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"093e2a4928868706da4377d0:16","filtered_window_id":"093e2a4928868706da4377d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093e2a4928868706da4377d0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject2/k2/1/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"093e2a4928868706da4377d0:22","filtered_window_id":"093e2a4928868706da4377d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/093e2a4928868706da4377d0/native_gt.npz","filtered_start_offset":22,"expected_frame_ids":[82,83,84,85,86,87,88,89],"take":"subject2/k2/1/cam4","frame_ids":[82,83,84,85,86,87,88,89]} +{"filtered_tile_id":"095955a56dce3148a7fb49bc:0","filtered_window_id":"095955a56dce3148a7fb49bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095955a56dce3148a7fb49bc/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject2/h2/5/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"095955a56dce3148a7fb49bc:8","filtered_window_id":"095955a56dce3148a7fb49bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095955a56dce3148a7fb49bc/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject2/h2/5/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"095955a56dce3148a7fb49bc:16","filtered_window_id":"095955a56dce3148a7fb49bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095955a56dce3148a7fb49bc/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject2/h2/5/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"095955a56dce3148a7fb49bc:24","filtered_window_id":"095955a56dce3148a7fb49bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095955a56dce3148a7fb49bc/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject2/h2/5/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"095955a56dce3148a7fb49bc:32","filtered_window_id":"095955a56dce3148a7fb49bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095955a56dce3148a7fb49bc/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[192,193,194,195,196,197,198,199],"take":"subject2/h2/5/cam4","frame_ids":[192,193,194,195,196,197,198,199]} +{"filtered_tile_id":"095955a56dce3148a7fb49bc:40","filtered_window_id":"095955a56dce3148a7fb49bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095955a56dce3148a7fb49bc/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[200,201,202,203,204,205,206,207],"take":"subject2/h2/5/cam4","frame_ids":[200,201,202,203,204,205,206,207]} +{"filtered_tile_id":"095955a56dce3148a7fb49bc:48","filtered_window_id":"095955a56dce3148a7fb49bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095955a56dce3148a7fb49bc/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[208,209,210,211,212,213,214,215],"take":"subject2/h2/5/cam4","frame_ids":[208,209,210,211,212,213,214,215]} +{"filtered_tile_id":"095955a56dce3148a7fb49bc:52","filtered_window_id":"095955a56dce3148a7fb49bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095955a56dce3148a7fb49bc/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject2/h2/5/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"095a306a20a17f151458b98d:0","filtered_window_id":"095a306a20a17f151458b98d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095a306a20a17f151458b98d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[207,208,209,210,211,212,213,214],"take":"subject3/h2/4/cam4","frame_ids":[207,208,209,210,211,212,213,214]} +{"filtered_tile_id":"095a306a20a17f151458b98d:8","filtered_window_id":"095a306a20a17f151458b98d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095a306a20a17f151458b98d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[215,216,217,218,219,220,221,222],"take":"subject3/h2/4/cam4","frame_ids":[215,216,217,218,219,220,221,222]} +{"filtered_tile_id":"095a306a20a17f151458b98d:16","filtered_window_id":"095a306a20a17f151458b98d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095a306a20a17f151458b98d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject3/h2/4/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"095a306a20a17f151458b98d:24","filtered_window_id":"095a306a20a17f151458b98d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095a306a20a17f151458b98d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject3/h2/4/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"095a306a20a17f151458b98d:32","filtered_window_id":"095a306a20a17f151458b98d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095a306a20a17f151458b98d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject3/h2/4/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"095a306a20a17f151458b98d:40","filtered_window_id":"095a306a20a17f151458b98d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095a306a20a17f151458b98d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject3/h2/4/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"095a306a20a17f151458b98d:48","filtered_window_id":"095a306a20a17f151458b98d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095a306a20a17f151458b98d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[255,256,257,258,259,260,261,262],"take":"subject3/h2/4/cam4","frame_ids":[255,256,257,258,259,260,261,262]} +{"filtered_tile_id":"095a306a20a17f151458b98d:52","filtered_window_id":"095a306a20a17f151458b98d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/095a306a20a17f151458b98d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[259,260,261,262,263,264,265,266],"take":"subject3/h2/4/cam4","frame_ids":[259,260,261,262,263,264,265,266]} +{"filtered_tile_id":"09789c81d0aef165f0153cff:0","filtered_window_id":"09789c81d0aef165f0153cff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09789c81d0aef165f0153cff/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[433,434,435,436,437,438,439,440],"take":"subject3/h2/1/cam4","frame_ids":[433,434,435,436,437,438,439,440]} +{"filtered_tile_id":"09789c81d0aef165f0153cff:8","filtered_window_id":"09789c81d0aef165f0153cff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09789c81d0aef165f0153cff/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject3/h2/1/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"09789c81d0aef165f0153cff:16","filtered_window_id":"09789c81d0aef165f0153cff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09789c81d0aef165f0153cff/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject3/h2/1/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"09789c81d0aef165f0153cff:24","filtered_window_id":"09789c81d0aef165f0153cff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09789c81d0aef165f0153cff/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject3/h2/1/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"09789c81d0aef165f0153cff:32","filtered_window_id":"09789c81d0aef165f0153cff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09789c81d0aef165f0153cff/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject3/h2/1/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"09789c81d0aef165f0153cff:40","filtered_window_id":"09789c81d0aef165f0153cff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09789c81d0aef165f0153cff/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject3/h2/1/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"09789c81d0aef165f0153cff:48","filtered_window_id":"09789c81d0aef165f0153cff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09789c81d0aef165f0153cff/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[481,482,483,484,485,486,487,488],"take":"subject3/h2/1/cam4","frame_ids":[481,482,483,484,485,486,487,488]} +{"filtered_tile_id":"09789c81d0aef165f0153cff:52","filtered_window_id":"09789c81d0aef165f0153cff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09789c81d0aef165f0153cff/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[485,486,487,488,489,490,491,492],"take":"subject3/h2/1/cam4","frame_ids":[485,486,487,488,489,490,491,492]} +{"filtered_tile_id":"09ca92c85ae225f7dd541341:0","filtered_window_id":"09ca92c85ae225f7dd541341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09ca92c85ae225f7dd541341/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject2/h1/2/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"09ca92c85ae225f7dd541341:8","filtered_window_id":"09ca92c85ae225f7dd541341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09ca92c85ae225f7dd541341/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[376,377,378,379,380,381,382,383],"take":"subject2/h1/2/cam4","frame_ids":[376,377,378,379,380,381,382,383]} +{"filtered_tile_id":"09ca92c85ae225f7dd541341:16","filtered_window_id":"09ca92c85ae225f7dd541341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09ca92c85ae225f7dd541341/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject2/h1/2/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"09ca92c85ae225f7dd541341:24","filtered_window_id":"09ca92c85ae225f7dd541341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09ca92c85ae225f7dd541341/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[392,393,394,395,396,397,398,399],"take":"subject2/h1/2/cam4","frame_ids":[392,393,394,395,396,397,398,399]} +{"filtered_tile_id":"09ca92c85ae225f7dd541341:32","filtered_window_id":"09ca92c85ae225f7dd541341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09ca92c85ae225f7dd541341/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[400,401,402,403,404,405,406,407],"take":"subject2/h1/2/cam4","frame_ids":[400,401,402,403,404,405,406,407]} +{"filtered_tile_id":"09ca92c85ae225f7dd541341:40","filtered_window_id":"09ca92c85ae225f7dd541341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09ca92c85ae225f7dd541341/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[408,409,410,411,412,413,414,415],"take":"subject2/h1/2/cam4","frame_ids":[408,409,410,411,412,413,414,415]} +{"filtered_tile_id":"09ca92c85ae225f7dd541341:48","filtered_window_id":"09ca92c85ae225f7dd541341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09ca92c85ae225f7dd541341/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[416,417,418,419,420,421,422,423],"take":"subject2/h1/2/cam4","frame_ids":[416,417,418,419,420,421,422,423]} +{"filtered_tile_id":"09ca92c85ae225f7dd541341:52","filtered_window_id":"09ca92c85ae225f7dd541341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09ca92c85ae225f7dd541341/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject2/h1/2/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"09eb565f0f3032e380c1118e:0","filtered_window_id":"09eb565f0f3032e380c1118e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09eb565f0f3032e380c1118e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[101,102,103,104,105,106,107,108],"take":"subject2/o2/3/cam4","frame_ids":[101,102,103,104,105,106,107,108]} +{"filtered_tile_id":"09eb565f0f3032e380c1118e:8","filtered_window_id":"09eb565f0f3032e380c1118e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09eb565f0f3032e380c1118e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[109,110,111,112,113,114,115,116],"take":"subject2/o2/3/cam4","frame_ids":[109,110,111,112,113,114,115,116]} +{"filtered_tile_id":"09eb565f0f3032e380c1118e:16","filtered_window_id":"09eb565f0f3032e380c1118e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09eb565f0f3032e380c1118e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[117,118,119,120,121,122,123,124],"take":"subject2/o2/3/cam4","frame_ids":[117,118,119,120,121,122,123,124]} +{"filtered_tile_id":"09eb565f0f3032e380c1118e:24","filtered_window_id":"09eb565f0f3032e380c1118e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09eb565f0f3032e380c1118e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[125,126,127,128,129,130,131,132],"take":"subject2/o2/3/cam4","frame_ids":[125,126,127,128,129,130,131,132]} +{"filtered_tile_id":"09eb565f0f3032e380c1118e:32","filtered_window_id":"09eb565f0f3032e380c1118e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09eb565f0f3032e380c1118e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject2/o2/3/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"09eb565f0f3032e380c1118e:40","filtered_window_id":"09eb565f0f3032e380c1118e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09eb565f0f3032e380c1118e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject2/o2/3/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"09eb565f0f3032e380c1118e:48","filtered_window_id":"09eb565f0f3032e380c1118e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09eb565f0f3032e380c1118e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject2/o2/3/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"09eb565f0f3032e380c1118e:52","filtered_window_id":"09eb565f0f3032e380c1118e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/09eb565f0f3032e380c1118e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject2/o2/3/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"0ad81de837b78b48b877efce:0","filtered_window_id":"0ad81de837b78b48b877efce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ad81de837b78b48b877efce/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[499,500,501,502,503,504,505,506],"take":"subject2/k2/6/cam4","frame_ids":[499,500,501,502,503,504,505,506]} +{"filtered_tile_id":"0ad81de837b78b48b877efce:8","filtered_window_id":"0ad81de837b78b48b877efce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ad81de837b78b48b877efce/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[507,508,509,510,511,512,513,514],"take":"subject2/k2/6/cam4","frame_ids":[507,508,509,510,511,512,513,514]} +{"filtered_tile_id":"0ad81de837b78b48b877efce:16","filtered_window_id":"0ad81de837b78b48b877efce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ad81de837b78b48b877efce/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[515,516,517,518,519,520,521,522],"take":"subject2/k2/6/cam4","frame_ids":[515,516,517,518,519,520,521,522]} +{"filtered_tile_id":"0ad81de837b78b48b877efce:24","filtered_window_id":"0ad81de837b78b48b877efce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ad81de837b78b48b877efce/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[523,524,525,526,527,528,529,530],"take":"subject2/k2/6/cam4","frame_ids":[523,524,525,526,527,528,529,530]} +{"filtered_tile_id":"0ad81de837b78b48b877efce:32","filtered_window_id":"0ad81de837b78b48b877efce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ad81de837b78b48b877efce/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[531,532,533,534,535,536,537,538],"take":"subject2/k2/6/cam4","frame_ids":[531,532,533,534,535,536,537,538]} +{"filtered_tile_id":"0ad81de837b78b48b877efce:40","filtered_window_id":"0ad81de837b78b48b877efce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ad81de837b78b48b877efce/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[539,540,541,542,543,544,545,546],"take":"subject2/k2/6/cam4","frame_ids":[539,540,541,542,543,544,545,546]} +{"filtered_tile_id":"0ad81de837b78b48b877efce:48","filtered_window_id":"0ad81de837b78b48b877efce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ad81de837b78b48b877efce/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[547,548,549,550,551,552,553,554],"take":"subject2/k2/6/cam4","frame_ids":[547,548,549,550,551,552,553,554]} +{"filtered_tile_id":"0ad81de837b78b48b877efce:52","filtered_window_id":"0ad81de837b78b48b877efce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ad81de837b78b48b877efce/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[551,552,553,554,555,556,557,558],"take":"subject2/k2/6/cam4","frame_ids":[551,552,553,554,555,556,557,558]} +{"filtered_tile_id":"0b50d046edad1f7ed396987d:0","filtered_window_id":"0b50d046edad1f7ed396987d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b50d046edad1f7ed396987d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject3/h2/7/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"0b50d046edad1f7ed396987d:8","filtered_window_id":"0b50d046edad1f7ed396987d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b50d046edad1f7ed396987d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject3/h2/7/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"0b50d046edad1f7ed396987d:16","filtered_window_id":"0b50d046edad1f7ed396987d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b50d046edad1f7ed396987d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject3/h2/7/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"0b50d046edad1f7ed396987d:24","filtered_window_id":"0b50d046edad1f7ed396987d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b50d046edad1f7ed396987d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[175,176,177,178,179,180,181,182],"take":"subject3/h2/7/cam4","frame_ids":[175,176,177,178,179,180,181,182]} +{"filtered_tile_id":"0b50d046edad1f7ed396987d:32","filtered_window_id":"0b50d046edad1f7ed396987d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b50d046edad1f7ed396987d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[183,184,185,186,187,188,189,190],"take":"subject3/h2/7/cam4","frame_ids":[183,184,185,186,187,188,189,190]} +{"filtered_tile_id":"0b50d046edad1f7ed396987d:40","filtered_window_id":"0b50d046edad1f7ed396987d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b50d046edad1f7ed396987d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[191,192,193,194,195,196,197,198],"take":"subject3/h2/7/cam4","frame_ids":[191,192,193,194,195,196,197,198]} +{"filtered_tile_id":"0b50d046edad1f7ed396987d:48","filtered_window_id":"0b50d046edad1f7ed396987d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b50d046edad1f7ed396987d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject3/h2/7/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"0b50d046edad1f7ed396987d:52","filtered_window_id":"0b50d046edad1f7ed396987d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b50d046edad1f7ed396987d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject3/h2/7/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"0b5b71444138a3d076284736:0","filtered_window_id":"0b5b71444138a3d076284736","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b5b71444138a3d076284736/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[89,90,91,92,93,94,95,96],"take":"subject1/o2/4/cam4","frame_ids":[89,90,91,92,93,94,95,96]} +{"filtered_tile_id":"0b5b71444138a3d076284736:8","filtered_window_id":"0b5b71444138a3d076284736","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b5b71444138a3d076284736/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[97,98,99,100,101,102,103,104],"take":"subject1/o2/4/cam4","frame_ids":[97,98,99,100,101,102,103,104]} +{"filtered_tile_id":"0b5b71444138a3d076284736:16","filtered_window_id":"0b5b71444138a3d076284736","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b5b71444138a3d076284736/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[105,106,107,108,109,110,111,112],"take":"subject1/o2/4/cam4","frame_ids":[105,106,107,108,109,110,111,112]} +{"filtered_tile_id":"0b5b71444138a3d076284736:24","filtered_window_id":"0b5b71444138a3d076284736","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b5b71444138a3d076284736/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[113,114,115,116,117,118,119,120],"take":"subject1/o2/4/cam4","frame_ids":[113,114,115,116,117,118,119,120]} +{"filtered_tile_id":"0b5b71444138a3d076284736:32","filtered_window_id":"0b5b71444138a3d076284736","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b5b71444138a3d076284736/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[121,122,123,124,125,126,127,128],"take":"subject1/o2/4/cam4","frame_ids":[121,122,123,124,125,126,127,128]} +{"filtered_tile_id":"0b5b71444138a3d076284736:40","filtered_window_id":"0b5b71444138a3d076284736","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b5b71444138a3d076284736/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject1/o2/4/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"0b5b71444138a3d076284736:48","filtered_window_id":"0b5b71444138a3d076284736","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b5b71444138a3d076284736/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject1/o2/4/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"0b5b71444138a3d076284736:52","filtered_window_id":"0b5b71444138a3d076284736","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0b5b71444138a3d076284736/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject1/o2/4/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"0bac42e2b103359925b79163:0","filtered_window_id":"0bac42e2b103359925b79163","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0bac42e2b103359925b79163/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[413,414,415,416,417,418,419,420],"take":"subject2/k2/3/cam4","frame_ids":[413,414,415,416,417,418,419,420]} +{"filtered_tile_id":"0bac42e2b103359925b79163:8","filtered_window_id":"0bac42e2b103359925b79163","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0bac42e2b103359925b79163/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[421,422,423,424,425,426,427,428],"take":"subject2/k2/3/cam4","frame_ids":[421,422,423,424,425,426,427,428]} +{"filtered_tile_id":"0bac42e2b103359925b79163:16","filtered_window_id":"0bac42e2b103359925b79163","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0bac42e2b103359925b79163/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[429,430,431,432,433,434,435,436],"take":"subject2/k2/3/cam4","frame_ids":[429,430,431,432,433,434,435,436]} +{"filtered_tile_id":"0bac42e2b103359925b79163:24","filtered_window_id":"0bac42e2b103359925b79163","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0bac42e2b103359925b79163/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[437,438,439,440,441,442,443,444],"take":"subject2/k2/3/cam4","frame_ids":[437,438,439,440,441,442,443,444]} +{"filtered_tile_id":"0bac42e2b103359925b79163:32","filtered_window_id":"0bac42e2b103359925b79163","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0bac42e2b103359925b79163/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[445,446,447,448,449,450,451,452],"take":"subject2/k2/3/cam4","frame_ids":[445,446,447,448,449,450,451,452]} +{"filtered_tile_id":"0bac42e2b103359925b79163:40","filtered_window_id":"0bac42e2b103359925b79163","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0bac42e2b103359925b79163/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[453,454,455,456,457,458,459,460],"take":"subject2/k2/3/cam4","frame_ids":[453,454,455,456,457,458,459,460]} +{"filtered_tile_id":"0bac42e2b103359925b79163:48","filtered_window_id":"0bac42e2b103359925b79163","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0bac42e2b103359925b79163/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject2/k2/3/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"0bac42e2b103359925b79163:52","filtered_window_id":"0bac42e2b103359925b79163","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0bac42e2b103359925b79163/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject2/k2/3/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"0c0a4df9f54863955711fff5:0","filtered_window_id":"0c0a4df9f54863955711fff5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c0a4df9f54863955711fff5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject3/h1/1/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"0c0a4df9f54863955711fff5:8","filtered_window_id":"0c0a4df9f54863955711fff5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c0a4df9f54863955711fff5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject3/h1/1/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"0c0a4df9f54863955711fff5:16","filtered_window_id":"0c0a4df9f54863955711fff5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c0a4df9f54863955711fff5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject3/h1/1/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"0c0a4df9f54863955711fff5:24","filtered_window_id":"0c0a4df9f54863955711fff5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c0a4df9f54863955711fff5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[274,275,276,277,278,279,280,281],"take":"subject3/h1/1/cam4","frame_ids":[274,275,276,277,278,279,280,281]} +{"filtered_tile_id":"0c0a4df9f54863955711fff5:32","filtered_window_id":"0c0a4df9f54863955711fff5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c0a4df9f54863955711fff5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject3/h1/1/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"0c0a4df9f54863955711fff5:40","filtered_window_id":"0c0a4df9f54863955711fff5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c0a4df9f54863955711fff5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[290,291,292,293,294,295,296,297],"take":"subject3/h1/1/cam4","frame_ids":[290,291,292,293,294,295,296,297]} +{"filtered_tile_id":"0c0a4df9f54863955711fff5:48","filtered_window_id":"0c0a4df9f54863955711fff5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c0a4df9f54863955711fff5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject3/h1/1/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"0c0a4df9f54863955711fff5:52","filtered_window_id":"0c0a4df9f54863955711fff5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c0a4df9f54863955711fff5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[302,303,304,305,306,307,308,309],"take":"subject3/h1/1/cam4","frame_ids":[302,303,304,305,306,307,308,309]} +{"filtered_tile_id":"0c2b5d7ade77028af0a992db:0","filtered_window_id":"0c2b5d7ade77028af0a992db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c2b5d7ade77028af0a992db/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[456,457,458,459,460,461,462,463],"take":"subject3/k1/5/cam4","frame_ids":[456,457,458,459,460,461,462,463]} +{"filtered_tile_id":"0c2b5d7ade77028af0a992db:8","filtered_window_id":"0c2b5d7ade77028af0a992db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c2b5d7ade77028af0a992db/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[464,465,466,467,468,469,470,471],"take":"subject3/k1/5/cam4","frame_ids":[464,465,466,467,468,469,470,471]} +{"filtered_tile_id":"0c2b5d7ade77028af0a992db:16","filtered_window_id":"0c2b5d7ade77028af0a992db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c2b5d7ade77028af0a992db/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject3/k1/5/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"0c2b5d7ade77028af0a992db:24","filtered_window_id":"0c2b5d7ade77028af0a992db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c2b5d7ade77028af0a992db/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject3/k1/5/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"0c2b5d7ade77028af0a992db:32","filtered_window_id":"0c2b5d7ade77028af0a992db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c2b5d7ade77028af0a992db/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject3/k1/5/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"0c2b5d7ade77028af0a992db:40","filtered_window_id":"0c2b5d7ade77028af0a992db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c2b5d7ade77028af0a992db/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject3/k1/5/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"0c2b5d7ade77028af0a992db:48","filtered_window_id":"0c2b5d7ade77028af0a992db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c2b5d7ade77028af0a992db/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject3/k1/5/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"0c2b5d7ade77028af0a992db:52","filtered_window_id":"0c2b5d7ade77028af0a992db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c2b5d7ade77028af0a992db/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[508,509,510,511,512,513,514,515],"take":"subject3/k1/5/cam4","frame_ids":[508,509,510,511,512,513,514,515]} +{"filtered_tile_id":"0c623c0433c996df88ea61af:0","filtered_window_id":"0c623c0433c996df88ea61af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c623c0433c996df88ea61af/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject2/o2/4/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"0c623c0433c996df88ea61af:8","filtered_window_id":"0c623c0433c996df88ea61af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c623c0433c996df88ea61af/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject2/o2/4/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"0c623c0433c996df88ea61af:16","filtered_window_id":"0c623c0433c996df88ea61af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c623c0433c996df88ea61af/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject2/o2/4/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"0c623c0433c996df88ea61af:24","filtered_window_id":"0c623c0433c996df88ea61af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c623c0433c996df88ea61af/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject2/o2/4/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"0c623c0433c996df88ea61af:32","filtered_window_id":"0c623c0433c996df88ea61af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c623c0433c996df88ea61af/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject2/o2/4/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"0c623c0433c996df88ea61af:40","filtered_window_id":"0c623c0433c996df88ea61af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c623c0433c996df88ea61af/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject2/o2/4/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"0c623c0433c996df88ea61af:48","filtered_window_id":"0c623c0433c996df88ea61af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c623c0433c996df88ea61af/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject2/o2/4/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"0c623c0433c996df88ea61af:52","filtered_window_id":"0c623c0433c996df88ea61af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0c623c0433c996df88ea61af/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject2/o2/4/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"0cb2cf5f920692fb70c2e2ed:0","filtered_window_id":"0cb2cf5f920692fb70c2e2ed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0cb2cf5f920692fb70c2e2ed/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[102,103,104,105,106,107,108,109],"take":"subject3/h1/2/cam4","frame_ids":[102,103,104,105,106,107,108,109]} +{"filtered_tile_id":"0cb2cf5f920692fb70c2e2ed:8","filtered_window_id":"0cb2cf5f920692fb70c2e2ed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0cb2cf5f920692fb70c2e2ed/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[110,111,112,113,114,115,116,117],"take":"subject3/h1/2/cam4","frame_ids":[110,111,112,113,114,115,116,117]} +{"filtered_tile_id":"0cb2cf5f920692fb70c2e2ed:16","filtered_window_id":"0cb2cf5f920692fb70c2e2ed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0cb2cf5f920692fb70c2e2ed/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[118,119,120,121,122,123,124,125],"take":"subject3/h1/2/cam4","frame_ids":[118,119,120,121,122,123,124,125]} +{"filtered_tile_id":"0cb2cf5f920692fb70c2e2ed:24","filtered_window_id":"0cb2cf5f920692fb70c2e2ed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0cb2cf5f920692fb70c2e2ed/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[126,127,128,129,130,131,132,133],"take":"subject3/h1/2/cam4","frame_ids":[126,127,128,129,130,131,132,133]} +{"filtered_tile_id":"0cb2cf5f920692fb70c2e2ed:32","filtered_window_id":"0cb2cf5f920692fb70c2e2ed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0cb2cf5f920692fb70c2e2ed/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[134,135,136,137,138,139,140,141],"take":"subject3/h1/2/cam4","frame_ids":[134,135,136,137,138,139,140,141]} +{"filtered_tile_id":"0cb2cf5f920692fb70c2e2ed:40","filtered_window_id":"0cb2cf5f920692fb70c2e2ed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0cb2cf5f920692fb70c2e2ed/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[142,143,144,145,146,147,148,149],"take":"subject3/h1/2/cam4","frame_ids":[142,143,144,145,146,147,148,149]} +{"filtered_tile_id":"0cb2cf5f920692fb70c2e2ed:48","filtered_window_id":"0cb2cf5f920692fb70c2e2ed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0cb2cf5f920692fb70c2e2ed/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[150,151,152,153,154,155,156,157],"take":"subject3/h1/2/cam4","frame_ids":[150,151,152,153,154,155,156,157]} +{"filtered_tile_id":"0cb2cf5f920692fb70c2e2ed:52","filtered_window_id":"0cb2cf5f920692fb70c2e2ed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0cb2cf5f920692fb70c2e2ed/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject3/h1/2/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"0ccc4451b0836a0c1c695560:0","filtered_window_id":"0ccc4451b0836a0c1c695560","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ccc4451b0836a0c1c695560/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[134,135,136,137,138,139,140,141],"take":"subject3/k1/7/cam4","frame_ids":[134,135,136,137,138,139,140,141]} +{"filtered_tile_id":"0ccc4451b0836a0c1c695560:8","filtered_window_id":"0ccc4451b0836a0c1c695560","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ccc4451b0836a0c1c695560/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[142,143,144,145,146,147,148,149],"take":"subject3/k1/7/cam4","frame_ids":[142,143,144,145,146,147,148,149]} +{"filtered_tile_id":"0ccc4451b0836a0c1c695560:16","filtered_window_id":"0ccc4451b0836a0c1c695560","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ccc4451b0836a0c1c695560/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[150,151,152,153,154,155,156,157],"take":"subject3/k1/7/cam4","frame_ids":[150,151,152,153,154,155,156,157]} +{"filtered_tile_id":"0ccc4451b0836a0c1c695560:24","filtered_window_id":"0ccc4451b0836a0c1c695560","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ccc4451b0836a0c1c695560/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[158,159,160,161,162,163,164,165],"take":"subject3/k1/7/cam4","frame_ids":[158,159,160,161,162,163,164,165]} +{"filtered_tile_id":"0ccc4451b0836a0c1c695560:32","filtered_window_id":"0ccc4451b0836a0c1c695560","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ccc4451b0836a0c1c695560/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject3/k1/7/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"0ccc4451b0836a0c1c695560:40","filtered_window_id":"0ccc4451b0836a0c1c695560","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ccc4451b0836a0c1c695560/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject3/k1/7/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"0ccc4451b0836a0c1c695560:48","filtered_window_id":"0ccc4451b0836a0c1c695560","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ccc4451b0836a0c1c695560/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject3/k1/7/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"0ccc4451b0836a0c1c695560:52","filtered_window_id":"0ccc4451b0836a0c1c695560","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ccc4451b0836a0c1c695560/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[186,187,188,189,190,191,192,193],"take":"subject3/k1/7/cam4","frame_ids":[186,187,188,189,190,191,192,193]} +{"filtered_tile_id":"0d1cd97b8f79f940c16db83f:0","filtered_window_id":"0d1cd97b8f79f940c16db83f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d1cd97b8f79f940c16db83f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject3/h1/6/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"0d1cd97b8f79f940c16db83f:8","filtered_window_id":"0d1cd97b8f79f940c16db83f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d1cd97b8f79f940c16db83f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject3/h1/6/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"0d1cd97b8f79f940c16db83f:16","filtered_window_id":"0d1cd97b8f79f940c16db83f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d1cd97b8f79f940c16db83f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject3/h1/6/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"0d1cd97b8f79f940c16db83f:24","filtered_window_id":"0d1cd97b8f79f940c16db83f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d1cd97b8f79f940c16db83f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject3/h1/6/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"0d1cd97b8f79f940c16db83f:32","filtered_window_id":"0d1cd97b8f79f940c16db83f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d1cd97b8f79f940c16db83f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject3/h1/6/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"0d1cd97b8f79f940c16db83f:40","filtered_window_id":"0d1cd97b8f79f940c16db83f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d1cd97b8f79f940c16db83f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject3/h1/6/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"0d1cd97b8f79f940c16db83f:46","filtered_window_id":"0d1cd97b8f79f940c16db83f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d1cd97b8f79f940c16db83f/native_gt.npz","filtered_start_offset":46,"expected_frame_ids":[526,527,528,529,530,531,532,533],"take":"subject3/h1/6/cam4","frame_ids":[526,527,528,529,530,531,532,533]} +{"filtered_tile_id":"0d24958a4a3f8b81980d3854:0","filtered_window_id":"0d24958a4a3f8b81980d3854","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d24958a4a3f8b81980d3854/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject3/k1/4/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"0d24958a4a3f8b81980d3854:8","filtered_window_id":"0d24958a4a3f8b81980d3854","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d24958a4a3f8b81980d3854/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject3/k1/4/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"0d24958a4a3f8b81980d3854:16","filtered_window_id":"0d24958a4a3f8b81980d3854","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d24958a4a3f8b81980d3854/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject3/k1/4/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"0d24958a4a3f8b81980d3854:24","filtered_window_id":"0d24958a4a3f8b81980d3854","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d24958a4a3f8b81980d3854/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject3/k1/4/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"0d24958a4a3f8b81980d3854:32","filtered_window_id":"0d24958a4a3f8b81980d3854","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d24958a4a3f8b81980d3854/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject3/k1/4/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"0d24958a4a3f8b81980d3854:40","filtered_window_id":"0d24958a4a3f8b81980d3854","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d24958a4a3f8b81980d3854/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject3/k1/4/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"0d24958a4a3f8b81980d3854:48","filtered_window_id":"0d24958a4a3f8b81980d3854","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d24958a4a3f8b81980d3854/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject3/k1/4/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"0d24958a4a3f8b81980d3854:52","filtered_window_id":"0d24958a4a3f8b81980d3854","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d24958a4a3f8b81980d3854/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject3/k1/4/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"0d3112711e36c29b7d8a6606:0","filtered_window_id":"0d3112711e36c29b7d8a6606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d3112711e36c29b7d8a6606/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[6,7,8,9,10,11,12,13],"take":"subject2/k2/3/cam4","frame_ids":[6,7,8,9,10,11,12,13]} +{"filtered_tile_id":"0d3112711e36c29b7d8a6606:8","filtered_window_id":"0d3112711e36c29b7d8a6606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d3112711e36c29b7d8a6606/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[14,15,16,17,18,19,20,21],"take":"subject2/k2/3/cam4","frame_ids":[14,15,16,17,18,19,20,21]} +{"filtered_tile_id":"0d3112711e36c29b7d8a6606:16","filtered_window_id":"0d3112711e36c29b7d8a6606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d3112711e36c29b7d8a6606/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[22,23,24,25,26,27,28,29],"take":"subject2/k2/3/cam4","frame_ids":[22,23,24,25,26,27,28,29]} +{"filtered_tile_id":"0d3112711e36c29b7d8a6606:24","filtered_window_id":"0d3112711e36c29b7d8a6606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d3112711e36c29b7d8a6606/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[30,31,32,33,34,35,36,37],"take":"subject2/k2/3/cam4","frame_ids":[30,31,32,33,34,35,36,37]} +{"filtered_tile_id":"0d3112711e36c29b7d8a6606:32","filtered_window_id":"0d3112711e36c29b7d8a6606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d3112711e36c29b7d8a6606/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[38,39,40,41,42,43,44,45],"take":"subject2/k2/3/cam4","frame_ids":[38,39,40,41,42,43,44,45]} +{"filtered_tile_id":"0d3112711e36c29b7d8a6606:40","filtered_window_id":"0d3112711e36c29b7d8a6606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d3112711e36c29b7d8a6606/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[46,47,48,49,50,51,52,53],"take":"subject2/k2/3/cam4","frame_ids":[46,47,48,49,50,51,52,53]} +{"filtered_tile_id":"0d3112711e36c29b7d8a6606:48","filtered_window_id":"0d3112711e36c29b7d8a6606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d3112711e36c29b7d8a6606/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[54,55,56,57,58,59,60,61],"take":"subject2/k2/3/cam4","frame_ids":[54,55,56,57,58,59,60,61]} +{"filtered_tile_id":"0d3112711e36c29b7d8a6606:49","filtered_window_id":"0d3112711e36c29b7d8a6606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0d3112711e36c29b7d8a6606/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[55,56,57,58,59,60,61,62],"take":"subject2/k2/3/cam4","frame_ids":[55,56,57,58,59,60,61,62]} +{"filtered_tile_id":"0dacc7c2c00e7e85d672edae:0","filtered_window_id":"0dacc7c2c00e7e85d672edae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dacc7c2c00e7e85d672edae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[320,321,322,323,324,325,326,327],"take":"subject2/h2/5/cam4","frame_ids":[320,321,322,323,324,325,326,327]} +{"filtered_tile_id":"0dacc7c2c00e7e85d672edae:8","filtered_window_id":"0dacc7c2c00e7e85d672edae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dacc7c2c00e7e85d672edae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[328,329,330,331,332,333,334,335],"take":"subject2/h2/5/cam4","frame_ids":[328,329,330,331,332,333,334,335]} +{"filtered_tile_id":"0dacc7c2c00e7e85d672edae:16","filtered_window_id":"0dacc7c2c00e7e85d672edae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dacc7c2c00e7e85d672edae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[336,337,338,339,340,341,342,343],"take":"subject2/h2/5/cam4","frame_ids":[336,337,338,339,340,341,342,343]} +{"filtered_tile_id":"0dacc7c2c00e7e85d672edae:24","filtered_window_id":"0dacc7c2c00e7e85d672edae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dacc7c2c00e7e85d672edae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[344,345,346,347,348,349,350,351],"take":"subject2/h2/5/cam4","frame_ids":[344,345,346,347,348,349,350,351]} +{"filtered_tile_id":"0dacc7c2c00e7e85d672edae:32","filtered_window_id":"0dacc7c2c00e7e85d672edae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dacc7c2c00e7e85d672edae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject2/h2/5/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"0dacc7c2c00e7e85d672edae:40","filtered_window_id":"0dacc7c2c00e7e85d672edae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dacc7c2c00e7e85d672edae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject2/h2/5/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"0dacc7c2c00e7e85d672edae:48","filtered_window_id":"0dacc7c2c00e7e85d672edae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dacc7c2c00e7e85d672edae/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject2/h2/5/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"0dacc7c2c00e7e85d672edae:52","filtered_window_id":"0dacc7c2c00e7e85d672edae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dacc7c2c00e7e85d672edae/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject2/h2/5/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"0dd10a46e52cb2ae83b8cf8c:0","filtered_window_id":"0dd10a46e52cb2ae83b8cf8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dd10a46e52cb2ae83b8cf8c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[38,39,40,41,42,43,44,45],"take":"subject2/o1/6/cam4","frame_ids":[38,39,40,41,42,43,44,45]} +{"filtered_tile_id":"0dd10a46e52cb2ae83b8cf8c:8","filtered_window_id":"0dd10a46e52cb2ae83b8cf8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dd10a46e52cb2ae83b8cf8c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[46,47,48,49,50,51,52,53],"take":"subject2/o1/6/cam4","frame_ids":[46,47,48,49,50,51,52,53]} +{"filtered_tile_id":"0dd10a46e52cb2ae83b8cf8c:16","filtered_window_id":"0dd10a46e52cb2ae83b8cf8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dd10a46e52cb2ae83b8cf8c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[54,55,56,57,58,59,60,61],"take":"subject2/o1/6/cam4","frame_ids":[54,55,56,57,58,59,60,61]} +{"filtered_tile_id":"0dd10a46e52cb2ae83b8cf8c:24","filtered_window_id":"0dd10a46e52cb2ae83b8cf8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dd10a46e52cb2ae83b8cf8c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[62,63,64,65,66,67,68,69],"take":"subject2/o1/6/cam4","frame_ids":[62,63,64,65,66,67,68,69]} +{"filtered_tile_id":"0dd10a46e52cb2ae83b8cf8c:32","filtered_window_id":"0dd10a46e52cb2ae83b8cf8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dd10a46e52cb2ae83b8cf8c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[70,71,72,73,74,75,76,77],"take":"subject2/o1/6/cam4","frame_ids":[70,71,72,73,74,75,76,77]} +{"filtered_tile_id":"0dd10a46e52cb2ae83b8cf8c:40","filtered_window_id":"0dd10a46e52cb2ae83b8cf8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dd10a46e52cb2ae83b8cf8c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject2/o1/6/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"0dd10a46e52cb2ae83b8cf8c:48","filtered_window_id":"0dd10a46e52cb2ae83b8cf8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dd10a46e52cb2ae83b8cf8c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[86,87,88,89,90,91,92,93],"take":"subject2/o1/6/cam4","frame_ids":[86,87,88,89,90,91,92,93]} +{"filtered_tile_id":"0dd10a46e52cb2ae83b8cf8c:52","filtered_window_id":"0dd10a46e52cb2ae83b8cf8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dd10a46e52cb2ae83b8cf8c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject2/o1/6/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"0dfb144a521d5a70247d408c:0","filtered_window_id":"0dfb144a521d5a70247d408c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dfb144a521d5a70247d408c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject1/o1/1/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"0dfb144a521d5a70247d408c:8","filtered_window_id":"0dfb144a521d5a70247d408c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dfb144a521d5a70247d408c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[495,496,497,498,499,500,501,502],"take":"subject1/o1/1/cam4","frame_ids":[495,496,497,498,499,500,501,502]} +{"filtered_tile_id":"0dfb144a521d5a70247d408c:16","filtered_window_id":"0dfb144a521d5a70247d408c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dfb144a521d5a70247d408c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[503,504,505,506,507,508,509,510],"take":"subject1/o1/1/cam4","frame_ids":[503,504,505,506,507,508,509,510]} +{"filtered_tile_id":"0dfb144a521d5a70247d408c:24","filtered_window_id":"0dfb144a521d5a70247d408c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dfb144a521d5a70247d408c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[511,512,513,514,515,516,517,518],"take":"subject1/o1/1/cam4","frame_ids":[511,512,513,514,515,516,517,518]} +{"filtered_tile_id":"0dfb144a521d5a70247d408c:32","filtered_window_id":"0dfb144a521d5a70247d408c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dfb144a521d5a70247d408c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[519,520,521,522,523,524,525,526],"take":"subject1/o1/1/cam4","frame_ids":[519,520,521,522,523,524,525,526]} +{"filtered_tile_id":"0dfb144a521d5a70247d408c:40","filtered_window_id":"0dfb144a521d5a70247d408c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dfb144a521d5a70247d408c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[527,528,529,530,531,532,533,534],"take":"subject1/o1/1/cam4","frame_ids":[527,528,529,530,531,532,533,534]} +{"filtered_tile_id":"0dfb144a521d5a70247d408c:43","filtered_window_id":"0dfb144a521d5a70247d408c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0dfb144a521d5a70247d408c/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[530,531,532,533,534,535,536,537],"take":"subject1/o1/1/cam4","frame_ids":[530,531,532,533,534,535,536,537]} +{"filtered_tile_id":"0e618c73368de9fd4956d774:0","filtered_window_id":"0e618c73368de9fd4956d774","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e618c73368de9fd4956d774/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[517,518,519,520,521,522,523,524],"take":"subject2/o1/4/cam4","frame_ids":[517,518,519,520,521,522,523,524]} +{"filtered_tile_id":"0e618c73368de9fd4956d774:8","filtered_window_id":"0e618c73368de9fd4956d774","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e618c73368de9fd4956d774/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[525,526,527,528,529,530,531,532],"take":"subject2/o1/4/cam4","frame_ids":[525,526,527,528,529,530,531,532]} +{"filtered_tile_id":"0e618c73368de9fd4956d774:16","filtered_window_id":"0e618c73368de9fd4956d774","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e618c73368de9fd4956d774/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[533,534,535,536,537,538,539,540],"take":"subject2/o1/4/cam4","frame_ids":[533,534,535,536,537,538,539,540]} +{"filtered_tile_id":"0e618c73368de9fd4956d774:24","filtered_window_id":"0e618c73368de9fd4956d774","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e618c73368de9fd4956d774/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject2/o1/4/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"0e618c73368de9fd4956d774:32","filtered_window_id":"0e618c73368de9fd4956d774","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e618c73368de9fd4956d774/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[549,550,551,552,553,554,555,556],"take":"subject2/o1/4/cam4","frame_ids":[549,550,551,552,553,554,555,556]} +{"filtered_tile_id":"0e618c73368de9fd4956d774:40","filtered_window_id":"0e618c73368de9fd4956d774","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e618c73368de9fd4956d774/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[557,558,559,560,561,562,563,564],"take":"subject2/o1/4/cam4","frame_ids":[557,558,559,560,561,562,563,564]} +{"filtered_tile_id":"0e618c73368de9fd4956d774:48","filtered_window_id":"0e618c73368de9fd4956d774","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e618c73368de9fd4956d774/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[565,566,567,568,569,570,571,572],"take":"subject2/o1/4/cam4","frame_ids":[565,566,567,568,569,570,571,572]} +{"filtered_tile_id":"0e618c73368de9fd4956d774:52","filtered_window_id":"0e618c73368de9fd4956d774","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e618c73368de9fd4956d774/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[569,570,571,572,573,574,575,576],"take":"subject2/o1/4/cam4","frame_ids":[569,570,571,572,573,574,575,576]} +{"filtered_tile_id":"0e6715c571cac12f36722394:0","filtered_window_id":"0e6715c571cac12f36722394","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e6715c571cac12f36722394/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[720,721,722,723,724,725,726,727],"take":"subject2/o1/2/cam4","frame_ids":[720,721,722,723,724,725,726,727]} +{"filtered_tile_id":"0e6715c571cac12f36722394:8","filtered_window_id":"0e6715c571cac12f36722394","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e6715c571cac12f36722394/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[728,729,730,731,732,733,734,735],"take":"subject2/o1/2/cam4","frame_ids":[728,729,730,731,732,733,734,735]} +{"filtered_tile_id":"0e6715c571cac12f36722394:16","filtered_window_id":"0e6715c571cac12f36722394","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e6715c571cac12f36722394/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[736,737,738,739,740,741,742,743],"take":"subject2/o1/2/cam4","frame_ids":[736,737,738,739,740,741,742,743]} +{"filtered_tile_id":"0e6715c571cac12f36722394:24","filtered_window_id":"0e6715c571cac12f36722394","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e6715c571cac12f36722394/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[744,745,746,747,748,749,750,751],"take":"subject2/o1/2/cam4","frame_ids":[744,745,746,747,748,749,750,751]} +{"filtered_tile_id":"0e6715c571cac12f36722394:32","filtered_window_id":"0e6715c571cac12f36722394","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e6715c571cac12f36722394/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[752,753,754,755,756,757,758,759],"take":"subject2/o1/2/cam4","frame_ids":[752,753,754,755,756,757,758,759]} +{"filtered_tile_id":"0e6715c571cac12f36722394:40","filtered_window_id":"0e6715c571cac12f36722394","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e6715c571cac12f36722394/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[760,761,762,763,764,765,766,767],"take":"subject2/o1/2/cam4","frame_ids":[760,761,762,763,764,765,766,767]} +{"filtered_tile_id":"0e6715c571cac12f36722394:48","filtered_window_id":"0e6715c571cac12f36722394","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e6715c571cac12f36722394/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[768,769,770,771,772,773,774,775],"take":"subject2/o1/2/cam4","frame_ids":[768,769,770,771,772,773,774,775]} +{"filtered_tile_id":"0e6715c571cac12f36722394:52","filtered_window_id":"0e6715c571cac12f36722394","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e6715c571cac12f36722394/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[772,773,774,775,776,777,778,779],"take":"subject2/o1/2/cam4","frame_ids":[772,773,774,775,776,777,778,779]} +{"filtered_tile_id":"0e7658573ca2383fd2acbba3:0","filtered_window_id":"0e7658573ca2383fd2acbba3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e7658573ca2383fd2acbba3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[79,80,81,82,83,84,85,86],"take":"subject2/h1/5/cam4","frame_ids":[79,80,81,82,83,84,85,86]} +{"filtered_tile_id":"0e7658573ca2383fd2acbba3:8","filtered_window_id":"0e7658573ca2383fd2acbba3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e7658573ca2383fd2acbba3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[87,88,89,90,91,92,93,94],"take":"subject2/h1/5/cam4","frame_ids":[87,88,89,90,91,92,93,94]} +{"filtered_tile_id":"0e7658573ca2383fd2acbba3:16","filtered_window_id":"0e7658573ca2383fd2acbba3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e7658573ca2383fd2acbba3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[95,96,97,98,99,100,101,102],"take":"subject2/h1/5/cam4","frame_ids":[95,96,97,98,99,100,101,102]} +{"filtered_tile_id":"0e7658573ca2383fd2acbba3:24","filtered_window_id":"0e7658573ca2383fd2acbba3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e7658573ca2383fd2acbba3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[103,104,105,106,107,108,109,110],"take":"subject2/h1/5/cam4","frame_ids":[103,104,105,106,107,108,109,110]} +{"filtered_tile_id":"0e7658573ca2383fd2acbba3:32","filtered_window_id":"0e7658573ca2383fd2acbba3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e7658573ca2383fd2acbba3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject2/h1/5/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"0e7658573ca2383fd2acbba3:40","filtered_window_id":"0e7658573ca2383fd2acbba3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e7658573ca2383fd2acbba3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject2/h1/5/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"0e7658573ca2383fd2acbba3:48","filtered_window_id":"0e7658573ca2383fd2acbba3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e7658573ca2383fd2acbba3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject2/h1/5/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"0e7658573ca2383fd2acbba3:52","filtered_window_id":"0e7658573ca2383fd2acbba3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e7658573ca2383fd2acbba3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject2/h1/5/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"0e992e9f917de641d4012e97:0","filtered_window_id":"0e992e9f917de641d4012e97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e992e9f917de641d4012e97/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject1/h2/3/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"0e992e9f917de641d4012e97:8","filtered_window_id":"0e992e9f917de641d4012e97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e992e9f917de641d4012e97/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject1/h2/3/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"0e992e9f917de641d4012e97:16","filtered_window_id":"0e992e9f917de641d4012e97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e992e9f917de641d4012e97/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject1/h2/3/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"0e992e9f917de641d4012e97:24","filtered_window_id":"0e992e9f917de641d4012e97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e992e9f917de641d4012e97/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject1/h2/3/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"0e992e9f917de641d4012e97:32","filtered_window_id":"0e992e9f917de641d4012e97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e992e9f917de641d4012e97/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject1/h2/3/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"0e992e9f917de641d4012e97:40","filtered_window_id":"0e992e9f917de641d4012e97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e992e9f917de641d4012e97/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject1/h2/3/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"0e992e9f917de641d4012e97:48","filtered_window_id":"0e992e9f917de641d4012e97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e992e9f917de641d4012e97/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject1/h2/3/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"0e992e9f917de641d4012e97:52","filtered_window_id":"0e992e9f917de641d4012e97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0e992e9f917de641d4012e97/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject1/h2/3/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"0ea41970694a714029427b2b:0","filtered_window_id":"0ea41970694a714029427b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ea41970694a714029427b2b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[505,506,507,508,509,510,511,512],"take":"subject1/o2/6/cam4","frame_ids":[505,506,507,508,509,510,511,512]} +{"filtered_tile_id":"0ea41970694a714029427b2b:8","filtered_window_id":"0ea41970694a714029427b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ea41970694a714029427b2b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[513,514,515,516,517,518,519,520],"take":"subject1/o2/6/cam4","frame_ids":[513,514,515,516,517,518,519,520]} +{"filtered_tile_id":"0ea41970694a714029427b2b:16","filtered_window_id":"0ea41970694a714029427b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ea41970694a714029427b2b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[521,522,523,524,525,526,527,528],"take":"subject1/o2/6/cam4","frame_ids":[521,522,523,524,525,526,527,528]} +{"filtered_tile_id":"0ea41970694a714029427b2b:24","filtered_window_id":"0ea41970694a714029427b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ea41970694a714029427b2b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[529,530,531,532,533,534,535,536],"take":"subject1/o2/6/cam4","frame_ids":[529,530,531,532,533,534,535,536]} +{"filtered_tile_id":"0ea41970694a714029427b2b:32","filtered_window_id":"0ea41970694a714029427b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ea41970694a714029427b2b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[537,538,539,540,541,542,543,544],"take":"subject1/o2/6/cam4","frame_ids":[537,538,539,540,541,542,543,544]} +{"filtered_tile_id":"0ea41970694a714029427b2b:40","filtered_window_id":"0ea41970694a714029427b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ea41970694a714029427b2b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[545,546,547,548,549,550,551,552],"take":"subject1/o2/6/cam4","frame_ids":[545,546,547,548,549,550,551,552]} +{"filtered_tile_id":"0ea41970694a714029427b2b:48","filtered_window_id":"0ea41970694a714029427b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ea41970694a714029427b2b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[553,554,555,556,557,558,559,560],"take":"subject1/o2/6/cam4","frame_ids":[553,554,555,556,557,558,559,560]} +{"filtered_tile_id":"0ea41970694a714029427b2b:52","filtered_window_id":"0ea41970694a714029427b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ea41970694a714029427b2b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[557,558,559,560,561,562,563,564],"take":"subject1/o2/6/cam4","frame_ids":[557,558,559,560,561,562,563,564]} +{"filtered_tile_id":"0ed7dd72a375d9f1ed81a420:0","filtered_window_id":"0ed7dd72a375d9f1ed81a420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ed7dd72a375d9f1ed81a420/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject2/o1/2/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"0ed7dd72a375d9f1ed81a420:8","filtered_window_id":"0ed7dd72a375d9f1ed81a420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ed7dd72a375d9f1ed81a420/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject2/o1/2/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"0ed7dd72a375d9f1ed81a420:16","filtered_window_id":"0ed7dd72a375d9f1ed81a420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ed7dd72a375d9f1ed81a420/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[104,105,106,107,108,109,110,111],"take":"subject2/o1/2/cam4","frame_ids":[104,105,106,107,108,109,110,111]} +{"filtered_tile_id":"0ed7dd72a375d9f1ed81a420:24","filtered_window_id":"0ed7dd72a375d9f1ed81a420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ed7dd72a375d9f1ed81a420/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[112,113,114,115,116,117,118,119],"take":"subject2/o1/2/cam4","frame_ids":[112,113,114,115,116,117,118,119]} +{"filtered_tile_id":"0ed7dd72a375d9f1ed81a420:32","filtered_window_id":"0ed7dd72a375d9f1ed81a420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ed7dd72a375d9f1ed81a420/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[120,121,122,123,124,125,126,127],"take":"subject2/o1/2/cam4","frame_ids":[120,121,122,123,124,125,126,127]} +{"filtered_tile_id":"0ed7dd72a375d9f1ed81a420:40","filtered_window_id":"0ed7dd72a375d9f1ed81a420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ed7dd72a375d9f1ed81a420/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[128,129,130,131,132,133,134,135],"take":"subject2/o1/2/cam4","frame_ids":[128,129,130,131,132,133,134,135]} +{"filtered_tile_id":"0ed7dd72a375d9f1ed81a420:48","filtered_window_id":"0ed7dd72a375d9f1ed81a420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ed7dd72a375d9f1ed81a420/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[136,137,138,139,140,141,142,143],"take":"subject2/o1/2/cam4","frame_ids":[136,137,138,139,140,141,142,143]} +{"filtered_tile_id":"0ed7dd72a375d9f1ed81a420:52","filtered_window_id":"0ed7dd72a375d9f1ed81a420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ed7dd72a375d9f1ed81a420/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject2/o1/2/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"0ee46387c1c08f95ca343c46:0","filtered_window_id":"0ee46387c1c08f95ca343c46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ee46387c1c08f95ca343c46/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[572,573,574,575,576,577,578,579],"take":"subject2/k1/6/cam4","frame_ids":[572,573,574,575,576,577,578,579]} +{"filtered_tile_id":"0ee46387c1c08f95ca343c46:8","filtered_window_id":"0ee46387c1c08f95ca343c46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ee46387c1c08f95ca343c46/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[580,581,582,583,584,585,586,587],"take":"subject2/k1/6/cam4","frame_ids":[580,581,582,583,584,585,586,587]} +{"filtered_tile_id":"0ee46387c1c08f95ca343c46:16","filtered_window_id":"0ee46387c1c08f95ca343c46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ee46387c1c08f95ca343c46/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[588,589,590,591,592,593,594,595],"take":"subject2/k1/6/cam4","frame_ids":[588,589,590,591,592,593,594,595]} +{"filtered_tile_id":"0ee46387c1c08f95ca343c46:24","filtered_window_id":"0ee46387c1c08f95ca343c46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ee46387c1c08f95ca343c46/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[596,597,598,599,600,601,602,603],"take":"subject2/k1/6/cam4","frame_ids":[596,597,598,599,600,601,602,603]} +{"filtered_tile_id":"0ee46387c1c08f95ca343c46:32","filtered_window_id":"0ee46387c1c08f95ca343c46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ee46387c1c08f95ca343c46/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[604,605,606,607,608,609,610,611],"take":"subject2/k1/6/cam4","frame_ids":[604,605,606,607,608,609,610,611]} +{"filtered_tile_id":"0ee46387c1c08f95ca343c46:40","filtered_window_id":"0ee46387c1c08f95ca343c46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ee46387c1c08f95ca343c46/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[612,613,614,615,616,617,618,619],"take":"subject2/k1/6/cam4","frame_ids":[612,613,614,615,616,617,618,619]} +{"filtered_tile_id":"0ee46387c1c08f95ca343c46:48","filtered_window_id":"0ee46387c1c08f95ca343c46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ee46387c1c08f95ca343c46/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[620,621,622,623,624,625,626,627],"take":"subject2/k1/6/cam4","frame_ids":[620,621,622,623,624,625,626,627]} +{"filtered_tile_id":"0ee46387c1c08f95ca343c46:52","filtered_window_id":"0ee46387c1c08f95ca343c46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0ee46387c1c08f95ca343c46/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[624,625,626,627,628,629,630,631],"take":"subject2/k1/6/cam4","frame_ids":[624,625,626,627,628,629,630,631]} +{"filtered_tile_id":"0f3cca37b7b4fe2311cf512e:0","filtered_window_id":"0f3cca37b7b4fe2311cf512e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f3cca37b7b4fe2311cf512e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[680,681,682,683,684,685,686,687],"take":"subject2/h1/7/cam4","frame_ids":[680,681,682,683,684,685,686,687]} +{"filtered_tile_id":"0f3cca37b7b4fe2311cf512e:8","filtered_window_id":"0f3cca37b7b4fe2311cf512e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f3cca37b7b4fe2311cf512e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[688,689,690,691,692,693,694,695],"take":"subject2/h1/7/cam4","frame_ids":[688,689,690,691,692,693,694,695]} +{"filtered_tile_id":"0f3cca37b7b4fe2311cf512e:16","filtered_window_id":"0f3cca37b7b4fe2311cf512e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f3cca37b7b4fe2311cf512e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[696,697,698,699,700,701,702,703],"take":"subject2/h1/7/cam4","frame_ids":[696,697,698,699,700,701,702,703]} +{"filtered_tile_id":"0f3cca37b7b4fe2311cf512e:24","filtered_window_id":"0f3cca37b7b4fe2311cf512e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f3cca37b7b4fe2311cf512e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[704,705,706,707,708,709,710,711],"take":"subject2/h1/7/cam4","frame_ids":[704,705,706,707,708,709,710,711]} +{"filtered_tile_id":"0f3cca37b7b4fe2311cf512e:32","filtered_window_id":"0f3cca37b7b4fe2311cf512e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f3cca37b7b4fe2311cf512e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[712,713,714,715,716,717,718,719],"take":"subject2/h1/7/cam4","frame_ids":[712,713,714,715,716,717,718,719]} +{"filtered_tile_id":"0f3cca37b7b4fe2311cf512e:40","filtered_window_id":"0f3cca37b7b4fe2311cf512e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f3cca37b7b4fe2311cf512e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[720,721,722,723,724,725,726,727],"take":"subject2/h1/7/cam4","frame_ids":[720,721,722,723,724,725,726,727]} +{"filtered_tile_id":"0f3cca37b7b4fe2311cf512e:48","filtered_window_id":"0f3cca37b7b4fe2311cf512e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f3cca37b7b4fe2311cf512e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[728,729,730,731,732,733,734,735],"take":"subject2/h1/7/cam4","frame_ids":[728,729,730,731,732,733,734,735]} +{"filtered_tile_id":"0f3cca37b7b4fe2311cf512e:52","filtered_window_id":"0f3cca37b7b4fe2311cf512e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f3cca37b7b4fe2311cf512e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[732,733,734,735,736,737,738,739],"take":"subject2/h1/7/cam4","frame_ids":[732,733,734,735,736,737,738,739]} +{"filtered_tile_id":"0f420f50871ebf917a453d5f:0","filtered_window_id":"0f420f50871ebf917a453d5f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f420f50871ebf917a453d5f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject3/h2/0/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"0f420f50871ebf917a453d5f:8","filtered_window_id":"0f420f50871ebf917a453d5f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f420f50871ebf917a453d5f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject3/h2/0/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"0f420f50871ebf917a453d5f:16","filtered_window_id":"0f420f50871ebf917a453d5f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f420f50871ebf917a453d5f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject3/h2/0/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"0f420f50871ebf917a453d5f:24","filtered_window_id":"0f420f50871ebf917a453d5f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f420f50871ebf917a453d5f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject3/h2/0/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"0f420f50871ebf917a453d5f:32","filtered_window_id":"0f420f50871ebf917a453d5f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f420f50871ebf917a453d5f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject3/h2/0/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"0f420f50871ebf917a453d5f:40","filtered_window_id":"0f420f50871ebf917a453d5f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f420f50871ebf917a453d5f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject3/h2/0/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"0f420f50871ebf917a453d5f:48","filtered_window_id":"0f420f50871ebf917a453d5f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f420f50871ebf917a453d5f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject3/h2/0/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"0f420f50871ebf917a453d5f:52","filtered_window_id":"0f420f50871ebf917a453d5f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f420f50871ebf917a453d5f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject3/h2/0/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"0f8aacabbfc698a168ba4aa4:0","filtered_window_id":"0f8aacabbfc698a168ba4aa4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f8aacabbfc698a168ba4aa4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[626,627,628,629,630,631,632,633],"take":"subject2/h1/5/cam4","frame_ids":[626,627,628,629,630,631,632,633]} +{"filtered_tile_id":"0f8aacabbfc698a168ba4aa4:8","filtered_window_id":"0f8aacabbfc698a168ba4aa4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f8aacabbfc698a168ba4aa4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[634,635,636,637,638,639,640,641],"take":"subject2/h1/5/cam4","frame_ids":[634,635,636,637,638,639,640,641]} +{"filtered_tile_id":"0f8aacabbfc698a168ba4aa4:16","filtered_window_id":"0f8aacabbfc698a168ba4aa4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f8aacabbfc698a168ba4aa4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[642,643,644,645,646,647,648,649],"take":"subject2/h1/5/cam4","frame_ids":[642,643,644,645,646,647,648,649]} +{"filtered_tile_id":"0f8aacabbfc698a168ba4aa4:24","filtered_window_id":"0f8aacabbfc698a168ba4aa4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f8aacabbfc698a168ba4aa4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[650,651,652,653,654,655,656,657],"take":"subject2/h1/5/cam4","frame_ids":[650,651,652,653,654,655,656,657]} +{"filtered_tile_id":"0f8aacabbfc698a168ba4aa4:32","filtered_window_id":"0f8aacabbfc698a168ba4aa4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f8aacabbfc698a168ba4aa4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[658,659,660,661,662,663,664,665],"take":"subject2/h1/5/cam4","frame_ids":[658,659,660,661,662,663,664,665]} +{"filtered_tile_id":"0f8aacabbfc698a168ba4aa4:40","filtered_window_id":"0f8aacabbfc698a168ba4aa4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f8aacabbfc698a168ba4aa4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[666,667,668,669,670,671,672,673],"take":"subject2/h1/5/cam4","frame_ids":[666,667,668,669,670,671,672,673]} +{"filtered_tile_id":"0f8aacabbfc698a168ba4aa4:43","filtered_window_id":"0f8aacabbfc698a168ba4aa4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f8aacabbfc698a168ba4aa4/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[669,670,671,672,673,674,675,676],"take":"subject2/h1/5/cam4","frame_ids":[669,670,671,672,673,674,675,676]} +{"filtered_tile_id":"0f972377f902c4530b13f5aa:0","filtered_window_id":"0f972377f902c4530b13f5aa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f972377f902c4530b13f5aa/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject1/o2/0/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"0f972377f902c4530b13f5aa:8","filtered_window_id":"0f972377f902c4530b13f5aa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f972377f902c4530b13f5aa/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/o2/0/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"0f972377f902c4530b13f5aa:16","filtered_window_id":"0f972377f902c4530b13f5aa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f972377f902c4530b13f5aa/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject1/o2/0/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"0f972377f902c4530b13f5aa:24","filtered_window_id":"0f972377f902c4530b13f5aa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f972377f902c4530b13f5aa/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject1/o2/0/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"0f972377f902c4530b13f5aa:32","filtered_window_id":"0f972377f902c4530b13f5aa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f972377f902c4530b13f5aa/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject1/o2/0/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"0f972377f902c4530b13f5aa:40","filtered_window_id":"0f972377f902c4530b13f5aa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f972377f902c4530b13f5aa/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject1/o2/0/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"0f972377f902c4530b13f5aa:42","filtered_window_id":"0f972377f902c4530b13f5aa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0f972377f902c4530b13f5aa/native_gt.npz","filtered_start_offset":42,"expected_frame_ids":[142,143,144,145,146,147,148,149],"take":"subject1/o2/0/cam4","frame_ids":[142,143,144,145,146,147,148,149]} +{"filtered_tile_id":"0fe664bf995c18c8e631f1f0:0","filtered_window_id":"0fe664bf995c18c8e631f1f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0fe664bf995c18c8e631f1f0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[559,560,561,562,563,564,565,566],"take":"subject3/h1/5/cam4","frame_ids":[559,560,561,562,563,564,565,566]} +{"filtered_tile_id":"0fe664bf995c18c8e631f1f0:8","filtered_window_id":"0fe664bf995c18c8e631f1f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0fe664bf995c18c8e631f1f0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[567,568,569,570,571,572,573,574],"take":"subject3/h1/5/cam4","frame_ids":[567,568,569,570,571,572,573,574]} +{"filtered_tile_id":"0fe664bf995c18c8e631f1f0:10","filtered_window_id":"0fe664bf995c18c8e631f1f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0fe664bf995c18c8e631f1f0/native_gt.npz","filtered_start_offset":10,"expected_frame_ids":[569,570,571,572,573,574,575,576],"take":"subject3/h1/5/cam4","frame_ids":[569,570,571,572,573,574,575,576]} +{"filtered_tile_id":"0fff7518b96f2ece8c967870:0","filtered_window_id":"0fff7518b96f2ece8c967870","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/0fff7518b96f2ece8c967870/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[98,99,100,101,102,103,104,105],"take":"subject2/o1/1/cam4","frame_ids":[98,99,100,101,102,103,104,105]} +{"filtered_tile_id":"101f8a63be6475891428571d:0","filtered_window_id":"101f8a63be6475891428571d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/101f8a63be6475891428571d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject2/o2/0/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"101f8a63be6475891428571d:8","filtered_window_id":"101f8a63be6475891428571d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/101f8a63be6475891428571d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject2/o2/0/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"101f8a63be6475891428571d:16","filtered_window_id":"101f8a63be6475891428571d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/101f8a63be6475891428571d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[341,342,343,344,345,346,347,348],"take":"subject2/o2/0/cam4","frame_ids":[341,342,343,344,345,346,347,348]} +{"filtered_tile_id":"101f8a63be6475891428571d:24","filtered_window_id":"101f8a63be6475891428571d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/101f8a63be6475891428571d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[349,350,351,352,353,354,355,356],"take":"subject2/o2/0/cam4","frame_ids":[349,350,351,352,353,354,355,356]} +{"filtered_tile_id":"101f8a63be6475891428571d:32","filtered_window_id":"101f8a63be6475891428571d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/101f8a63be6475891428571d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject2/o2/0/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"101f8a63be6475891428571d:40","filtered_window_id":"101f8a63be6475891428571d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/101f8a63be6475891428571d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject2/o2/0/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"101f8a63be6475891428571d:48","filtered_window_id":"101f8a63be6475891428571d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/101f8a63be6475891428571d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[373,374,375,376,377,378,379,380],"take":"subject2/o2/0/cam4","frame_ids":[373,374,375,376,377,378,379,380]} +{"filtered_tile_id":"101f8a63be6475891428571d:52","filtered_window_id":"101f8a63be6475891428571d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/101f8a63be6475891428571d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[377,378,379,380,381,382,383,384],"take":"subject2/o2/0/cam4","frame_ids":[377,378,379,380,381,382,383,384]} +{"filtered_tile_id":"106fbc93b5ea663ac2b4c8a5:0","filtered_window_id":"106fbc93b5ea663ac2b4c8a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/106fbc93b5ea663ac2b4c8a5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[575,576,577,578,579,580,581,582],"take":"subject1/k2/6/cam4","frame_ids":[575,576,577,578,579,580,581,582]} +{"filtered_tile_id":"106fbc93b5ea663ac2b4c8a5:8","filtered_window_id":"106fbc93b5ea663ac2b4c8a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/106fbc93b5ea663ac2b4c8a5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[583,584,585,586,587,588,589,590],"take":"subject1/k2/6/cam4","frame_ids":[583,584,585,586,587,588,589,590]} +{"filtered_tile_id":"106fbc93b5ea663ac2b4c8a5:16","filtered_window_id":"106fbc93b5ea663ac2b4c8a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/106fbc93b5ea663ac2b4c8a5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[591,592,593,594,595,596,597,598],"take":"subject1/k2/6/cam4","frame_ids":[591,592,593,594,595,596,597,598]} +{"filtered_tile_id":"106fbc93b5ea663ac2b4c8a5:24","filtered_window_id":"106fbc93b5ea663ac2b4c8a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/106fbc93b5ea663ac2b4c8a5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[599,600,601,602,603,604,605,606],"take":"subject1/k2/6/cam4","frame_ids":[599,600,601,602,603,604,605,606]} +{"filtered_tile_id":"106fbc93b5ea663ac2b4c8a5:32","filtered_window_id":"106fbc93b5ea663ac2b4c8a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/106fbc93b5ea663ac2b4c8a5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[607,608,609,610,611,612,613,614],"take":"subject1/k2/6/cam4","frame_ids":[607,608,609,610,611,612,613,614]} +{"filtered_tile_id":"106fbc93b5ea663ac2b4c8a5:40","filtered_window_id":"106fbc93b5ea663ac2b4c8a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/106fbc93b5ea663ac2b4c8a5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[615,616,617,618,619,620,621,622],"take":"subject1/k2/6/cam4","frame_ids":[615,616,617,618,619,620,621,622]} +{"filtered_tile_id":"106fbc93b5ea663ac2b4c8a5:48","filtered_window_id":"106fbc93b5ea663ac2b4c8a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/106fbc93b5ea663ac2b4c8a5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[623,624,625,626,627,628,629,630],"take":"subject1/k2/6/cam4","frame_ids":[623,624,625,626,627,628,629,630]} +{"filtered_tile_id":"106fbc93b5ea663ac2b4c8a5:52","filtered_window_id":"106fbc93b5ea663ac2b4c8a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/106fbc93b5ea663ac2b4c8a5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[627,628,629,630,631,632,633,634],"take":"subject1/k2/6/cam4","frame_ids":[627,628,629,630,631,632,633,634]} +{"filtered_tile_id":"10f871665defe74ea4ea4653:0","filtered_window_id":"10f871665defe74ea4ea4653","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/10f871665defe74ea4ea4653/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject2/h2/5/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"10f871665defe74ea4ea4653:8","filtered_window_id":"10f871665defe74ea4ea4653","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/10f871665defe74ea4ea4653/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject2/h2/5/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"10f871665defe74ea4ea4653:16","filtered_window_id":"10f871665defe74ea4ea4653","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/10f871665defe74ea4ea4653/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject2/h2/5/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"10f871665defe74ea4ea4653:24","filtered_window_id":"10f871665defe74ea4ea4653","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/10f871665defe74ea4ea4653/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject2/h2/5/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"10f871665defe74ea4ea4653:32","filtered_window_id":"10f871665defe74ea4ea4653","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/10f871665defe74ea4ea4653/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject2/h2/5/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"10f871665defe74ea4ea4653:40","filtered_window_id":"10f871665defe74ea4ea4653","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/10f871665defe74ea4ea4653/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject2/h2/5/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"10f871665defe74ea4ea4653:48","filtered_window_id":"10f871665defe74ea4ea4653","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/10f871665defe74ea4ea4653/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject2/h2/5/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"10f871665defe74ea4ea4653:52","filtered_window_id":"10f871665defe74ea4ea4653","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/10f871665defe74ea4ea4653/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[432,433,434,435,436,437,438,439],"take":"subject2/h2/5/cam4","frame_ids":[432,433,434,435,436,437,438,439]} +{"filtered_tile_id":"112e0b43720d78d4a228a76b:0","filtered_window_id":"112e0b43720d78d4a228a76b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/112e0b43720d78d4a228a76b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject2/h2/2/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"112e0b43720d78d4a228a76b:8","filtered_window_id":"112e0b43720d78d4a228a76b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/112e0b43720d78d4a228a76b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[156,157,158,159,160,161,162,163],"take":"subject2/h2/2/cam4","frame_ids":[156,157,158,159,160,161,162,163]} +{"filtered_tile_id":"112e0b43720d78d4a228a76b:16","filtered_window_id":"112e0b43720d78d4a228a76b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/112e0b43720d78d4a228a76b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[164,165,166,167,168,169,170,171],"take":"subject2/h2/2/cam4","frame_ids":[164,165,166,167,168,169,170,171]} +{"filtered_tile_id":"112e0b43720d78d4a228a76b:24","filtered_window_id":"112e0b43720d78d4a228a76b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/112e0b43720d78d4a228a76b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject2/h2/2/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"112e0b43720d78d4a228a76b:32","filtered_window_id":"112e0b43720d78d4a228a76b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/112e0b43720d78d4a228a76b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject2/h2/2/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"112e0b43720d78d4a228a76b:40","filtered_window_id":"112e0b43720d78d4a228a76b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/112e0b43720d78d4a228a76b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject2/h2/2/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"112e0b43720d78d4a228a76b:48","filtered_window_id":"112e0b43720d78d4a228a76b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/112e0b43720d78d4a228a76b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject2/h2/2/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"112e0b43720d78d4a228a76b:52","filtered_window_id":"112e0b43720d78d4a228a76b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/112e0b43720d78d4a228a76b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[200,201,202,203,204,205,206,207],"take":"subject2/h2/2/cam4","frame_ids":[200,201,202,203,204,205,206,207]} +{"filtered_tile_id":"11be2e5260424f43a6e8650e:0","filtered_window_id":"11be2e5260424f43a6e8650e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/11be2e5260424f43a6e8650e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[634,635,636,637,638,639,640,641],"take":"subject1/k1/2/cam4","frame_ids":[634,635,636,637,638,639,640,641]} +{"filtered_tile_id":"11be2e5260424f43a6e8650e:8","filtered_window_id":"11be2e5260424f43a6e8650e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/11be2e5260424f43a6e8650e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[642,643,644,645,646,647,648,649],"take":"subject1/k1/2/cam4","frame_ids":[642,643,644,645,646,647,648,649]} +{"filtered_tile_id":"11be2e5260424f43a6e8650e:16","filtered_window_id":"11be2e5260424f43a6e8650e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/11be2e5260424f43a6e8650e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[650,651,652,653,654,655,656,657],"take":"subject1/k1/2/cam4","frame_ids":[650,651,652,653,654,655,656,657]} +{"filtered_tile_id":"11be2e5260424f43a6e8650e:24","filtered_window_id":"11be2e5260424f43a6e8650e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/11be2e5260424f43a6e8650e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[658,659,660,661,662,663,664,665],"take":"subject1/k1/2/cam4","frame_ids":[658,659,660,661,662,663,664,665]} +{"filtered_tile_id":"11be2e5260424f43a6e8650e:32","filtered_window_id":"11be2e5260424f43a6e8650e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/11be2e5260424f43a6e8650e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[666,667,668,669,670,671,672,673],"take":"subject1/k1/2/cam4","frame_ids":[666,667,668,669,670,671,672,673]} +{"filtered_tile_id":"11be2e5260424f43a6e8650e:40","filtered_window_id":"11be2e5260424f43a6e8650e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/11be2e5260424f43a6e8650e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[674,675,676,677,678,679,680,681],"take":"subject1/k1/2/cam4","frame_ids":[674,675,676,677,678,679,680,681]} +{"filtered_tile_id":"11be2e5260424f43a6e8650e:48","filtered_window_id":"11be2e5260424f43a6e8650e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/11be2e5260424f43a6e8650e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[682,683,684,685,686,687,688,689],"take":"subject1/k1/2/cam4","frame_ids":[682,683,684,685,686,687,688,689]} +{"filtered_tile_id":"11be2e5260424f43a6e8650e:52","filtered_window_id":"11be2e5260424f43a6e8650e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/11be2e5260424f43a6e8650e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[686,687,688,689,690,691,692,693],"take":"subject1/k1/2/cam4","frame_ids":[686,687,688,689,690,691,692,693]} +{"filtered_tile_id":"123f99f5394637cd0c4ecbf4:0","filtered_window_id":"123f99f5394637cd0c4ecbf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/123f99f5394637cd0c4ecbf4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[156,157,158,159,160,161,162,163],"take":"subject3/h2/3/cam4","frame_ids":[156,157,158,159,160,161,162,163]} +{"filtered_tile_id":"123f99f5394637cd0c4ecbf4:8","filtered_window_id":"123f99f5394637cd0c4ecbf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/123f99f5394637cd0c4ecbf4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[164,165,166,167,168,169,170,171],"take":"subject3/h2/3/cam4","frame_ids":[164,165,166,167,168,169,170,171]} +{"filtered_tile_id":"123f99f5394637cd0c4ecbf4:16","filtered_window_id":"123f99f5394637cd0c4ecbf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/123f99f5394637cd0c4ecbf4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject3/h2/3/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"123f99f5394637cd0c4ecbf4:24","filtered_window_id":"123f99f5394637cd0c4ecbf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/123f99f5394637cd0c4ecbf4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject3/h2/3/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"123f99f5394637cd0c4ecbf4:32","filtered_window_id":"123f99f5394637cd0c4ecbf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/123f99f5394637cd0c4ecbf4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject3/h2/3/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"123f99f5394637cd0c4ecbf4:40","filtered_window_id":"123f99f5394637cd0c4ecbf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/123f99f5394637cd0c4ecbf4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject3/h2/3/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"123f99f5394637cd0c4ecbf4:48","filtered_window_id":"123f99f5394637cd0c4ecbf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/123f99f5394637cd0c4ecbf4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject3/h2/3/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"123f99f5394637cd0c4ecbf4:52","filtered_window_id":"123f99f5394637cd0c4ecbf4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/123f99f5394637cd0c4ecbf4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[208,209,210,211,212,213,214,215],"take":"subject3/h2/3/cam4","frame_ids":[208,209,210,211,212,213,214,215]} +{"filtered_tile_id":"12673f536c78d5626a1c3277:0","filtered_window_id":"12673f536c78d5626a1c3277","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/12673f536c78d5626a1c3277/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[359,360,361,362,363,364,365,366],"take":"subject2/h2/3/cam4","frame_ids":[359,360,361,362,363,364,365,366]} +{"filtered_tile_id":"12673f536c78d5626a1c3277:8","filtered_window_id":"12673f536c78d5626a1c3277","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/12673f536c78d5626a1c3277/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[367,368,369,370,371,372,373,374],"take":"subject2/h2/3/cam4","frame_ids":[367,368,369,370,371,372,373,374]} +{"filtered_tile_id":"12673f536c78d5626a1c3277:16","filtered_window_id":"12673f536c78d5626a1c3277","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/12673f536c78d5626a1c3277/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[375,376,377,378,379,380,381,382],"take":"subject2/h2/3/cam4","frame_ids":[375,376,377,378,379,380,381,382]} +{"filtered_tile_id":"12673f536c78d5626a1c3277:24","filtered_window_id":"12673f536c78d5626a1c3277","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/12673f536c78d5626a1c3277/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject2/h2/3/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"12673f536c78d5626a1c3277:32","filtered_window_id":"12673f536c78d5626a1c3277","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/12673f536c78d5626a1c3277/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject2/h2/3/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"12673f536c78d5626a1c3277:40","filtered_window_id":"12673f536c78d5626a1c3277","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/12673f536c78d5626a1c3277/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject2/h2/3/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"12673f536c78d5626a1c3277:48","filtered_window_id":"12673f536c78d5626a1c3277","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/12673f536c78d5626a1c3277/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject2/h2/3/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"12673f536c78d5626a1c3277:52","filtered_window_id":"12673f536c78d5626a1c3277","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/12673f536c78d5626a1c3277/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[411,412,413,414,415,416,417,418],"take":"subject2/h2/3/cam4","frame_ids":[411,412,413,414,415,416,417,418]} +{"filtered_tile_id":"1291bfed6d3f67c1420379d9:0","filtered_window_id":"1291bfed6d3f67c1420379d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1291bfed6d3f67c1420379d9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[303,304,305,306,307,308,309,310],"take":"subject2/h1/4/cam4","frame_ids":[303,304,305,306,307,308,309,310]} +{"filtered_tile_id":"1291bfed6d3f67c1420379d9:8","filtered_window_id":"1291bfed6d3f67c1420379d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1291bfed6d3f67c1420379d9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[311,312,313,314,315,316,317,318],"take":"subject2/h1/4/cam4","frame_ids":[311,312,313,314,315,316,317,318]} +{"filtered_tile_id":"1291bfed6d3f67c1420379d9:16","filtered_window_id":"1291bfed6d3f67c1420379d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1291bfed6d3f67c1420379d9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[319,320,321,322,323,324,325,326],"take":"subject2/h1/4/cam4","frame_ids":[319,320,321,322,323,324,325,326]} +{"filtered_tile_id":"1291bfed6d3f67c1420379d9:24","filtered_window_id":"1291bfed6d3f67c1420379d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1291bfed6d3f67c1420379d9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[327,328,329,330,331,332,333,334],"take":"subject2/h1/4/cam4","frame_ids":[327,328,329,330,331,332,333,334]} +{"filtered_tile_id":"1291bfed6d3f67c1420379d9:32","filtered_window_id":"1291bfed6d3f67c1420379d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1291bfed6d3f67c1420379d9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[335,336,337,338,339,340,341,342],"take":"subject2/h1/4/cam4","frame_ids":[335,336,337,338,339,340,341,342]} +{"filtered_tile_id":"1291bfed6d3f67c1420379d9:40","filtered_window_id":"1291bfed6d3f67c1420379d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1291bfed6d3f67c1420379d9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[343,344,345,346,347,348,349,350],"take":"subject2/h1/4/cam4","frame_ids":[343,344,345,346,347,348,349,350]} +{"filtered_tile_id":"1291bfed6d3f67c1420379d9:48","filtered_window_id":"1291bfed6d3f67c1420379d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1291bfed6d3f67c1420379d9/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[351,352,353,354,355,356,357,358],"take":"subject2/h1/4/cam4","frame_ids":[351,352,353,354,355,356,357,358]} +{"filtered_tile_id":"1291bfed6d3f67c1420379d9:50","filtered_window_id":"1291bfed6d3f67c1420379d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1291bfed6d3f67c1420379d9/native_gt.npz","filtered_start_offset":50,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject2/h1/4/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"130a7acf2ee238304d8ef529:0","filtered_window_id":"130a7acf2ee238304d8ef529","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130a7acf2ee238304d8ef529/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject3/h2/6/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"130a7acf2ee238304d8ef529:8","filtered_window_id":"130a7acf2ee238304d8ef529","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130a7acf2ee238304d8ef529/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject3/h2/6/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"130a7acf2ee238304d8ef529:16","filtered_window_id":"130a7acf2ee238304d8ef529","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130a7acf2ee238304d8ef529/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject3/h2/6/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"130a7acf2ee238304d8ef529:24","filtered_window_id":"130a7acf2ee238304d8ef529","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130a7acf2ee238304d8ef529/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject3/h2/6/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"130a7acf2ee238304d8ef529:32","filtered_window_id":"130a7acf2ee238304d8ef529","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130a7acf2ee238304d8ef529/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject3/h2/6/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"130a7acf2ee238304d8ef529:40","filtered_window_id":"130a7acf2ee238304d8ef529","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130a7acf2ee238304d8ef529/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject3/h2/6/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"130a7acf2ee238304d8ef529:48","filtered_window_id":"130a7acf2ee238304d8ef529","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130a7acf2ee238304d8ef529/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject3/h2/6/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"130a7acf2ee238304d8ef529:52","filtered_window_id":"130a7acf2ee238304d8ef529","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130a7acf2ee238304d8ef529/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject3/h2/6/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"130b0eeece472bf16473b3f6:0","filtered_window_id":"130b0eeece472bf16473b3f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130b0eeece472bf16473b3f6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject1/k2/1/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"130b0eeece472bf16473b3f6:8","filtered_window_id":"130b0eeece472bf16473b3f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130b0eeece472bf16473b3f6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[290,291,292,293,294,295,296,297],"take":"subject1/k2/1/cam4","frame_ids":[290,291,292,293,294,295,296,297]} +{"filtered_tile_id":"130b0eeece472bf16473b3f6:16","filtered_window_id":"130b0eeece472bf16473b3f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130b0eeece472bf16473b3f6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject1/k2/1/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"130b0eeece472bf16473b3f6:24","filtered_window_id":"130b0eeece472bf16473b3f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130b0eeece472bf16473b3f6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[306,307,308,309,310,311,312,313],"take":"subject1/k2/1/cam4","frame_ids":[306,307,308,309,310,311,312,313]} +{"filtered_tile_id":"130b0eeece472bf16473b3f6:32","filtered_window_id":"130b0eeece472bf16473b3f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130b0eeece472bf16473b3f6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject1/k2/1/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"130b0eeece472bf16473b3f6:40","filtered_window_id":"130b0eeece472bf16473b3f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130b0eeece472bf16473b3f6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject1/k2/1/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"130b0eeece472bf16473b3f6:48","filtered_window_id":"130b0eeece472bf16473b3f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130b0eeece472bf16473b3f6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject1/k2/1/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"130b0eeece472bf16473b3f6:52","filtered_window_id":"130b0eeece472bf16473b3f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/130b0eeece472bf16473b3f6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject1/k2/1/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"135a0076ea45eb3a301d65fd:0","filtered_window_id":"135a0076ea45eb3a301d65fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a0076ea45eb3a301d65fd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[70,71,72,73,74,75,76,77],"take":"subject1/k1/7/cam4","frame_ids":[70,71,72,73,74,75,76,77]} +{"filtered_tile_id":"135a0076ea45eb3a301d65fd:8","filtered_window_id":"135a0076ea45eb3a301d65fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a0076ea45eb3a301d65fd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject1/k1/7/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"135a0076ea45eb3a301d65fd:16","filtered_window_id":"135a0076ea45eb3a301d65fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a0076ea45eb3a301d65fd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[86,87,88,89,90,91,92,93],"take":"subject1/k1/7/cam4","frame_ids":[86,87,88,89,90,91,92,93]} +{"filtered_tile_id":"135a0076ea45eb3a301d65fd:24","filtered_window_id":"135a0076ea45eb3a301d65fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a0076ea45eb3a301d65fd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[94,95,96,97,98,99,100,101],"take":"subject1/k1/7/cam4","frame_ids":[94,95,96,97,98,99,100,101]} +{"filtered_tile_id":"135a0076ea45eb3a301d65fd:32","filtered_window_id":"135a0076ea45eb3a301d65fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a0076ea45eb3a301d65fd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[102,103,104,105,106,107,108,109],"take":"subject1/k1/7/cam4","frame_ids":[102,103,104,105,106,107,108,109]} +{"filtered_tile_id":"135a0076ea45eb3a301d65fd:40","filtered_window_id":"135a0076ea45eb3a301d65fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a0076ea45eb3a301d65fd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[110,111,112,113,114,115,116,117],"take":"subject1/k1/7/cam4","frame_ids":[110,111,112,113,114,115,116,117]} +{"filtered_tile_id":"135a0076ea45eb3a301d65fd:48","filtered_window_id":"135a0076ea45eb3a301d65fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a0076ea45eb3a301d65fd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[118,119,120,121,122,123,124,125],"take":"subject1/k1/7/cam4","frame_ids":[118,119,120,121,122,123,124,125]} +{"filtered_tile_id":"135a0076ea45eb3a301d65fd:52","filtered_window_id":"135a0076ea45eb3a301d65fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a0076ea45eb3a301d65fd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject1/k1/7/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"135a8adcb467f5cccd1f4e84:0","filtered_window_id":"135a8adcb467f5cccd1f4e84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a8adcb467f5cccd1f4e84/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[215,216,217,218,219,220,221,222],"take":"subject1/o2/0/cam4","frame_ids":[215,216,217,218,219,220,221,222]} +{"filtered_tile_id":"135a8adcb467f5cccd1f4e84:8","filtered_window_id":"135a8adcb467f5cccd1f4e84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a8adcb467f5cccd1f4e84/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject1/o2/0/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"135a8adcb467f5cccd1f4e84:16","filtered_window_id":"135a8adcb467f5cccd1f4e84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a8adcb467f5cccd1f4e84/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject1/o2/0/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"135a8adcb467f5cccd1f4e84:24","filtered_window_id":"135a8adcb467f5cccd1f4e84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a8adcb467f5cccd1f4e84/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject1/o2/0/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"135a8adcb467f5cccd1f4e84:28","filtered_window_id":"135a8adcb467f5cccd1f4e84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/135a8adcb467f5cccd1f4e84/native_gt.npz","filtered_start_offset":28,"expected_frame_ids":[243,244,245,246,247,248,249,250],"take":"subject1/o2/0/cam4","frame_ids":[243,244,245,246,247,248,249,250]} +{"filtered_tile_id":"138dfc66313c782aa8adc392:0","filtered_window_id":"138dfc66313c782aa8adc392","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/138dfc66313c782aa8adc392/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[439,440,441,442,443,444,445,446],"take":"subject3/k1/3/cam4","frame_ids":[439,440,441,442,443,444,445,446]} +{"filtered_tile_id":"138dfc66313c782aa8adc392:8","filtered_window_id":"138dfc66313c782aa8adc392","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/138dfc66313c782aa8adc392/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[447,448,449,450,451,452,453,454],"take":"subject3/k1/3/cam4","frame_ids":[447,448,449,450,451,452,453,454]} +{"filtered_tile_id":"138dfc66313c782aa8adc392:16","filtered_window_id":"138dfc66313c782aa8adc392","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/138dfc66313c782aa8adc392/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[455,456,457,458,459,460,461,462],"take":"subject3/k1/3/cam4","frame_ids":[455,456,457,458,459,460,461,462]} +{"filtered_tile_id":"138dfc66313c782aa8adc392:24","filtered_window_id":"138dfc66313c782aa8adc392","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/138dfc66313c782aa8adc392/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject3/k1/3/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"138dfc66313c782aa8adc392:32","filtered_window_id":"138dfc66313c782aa8adc392","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/138dfc66313c782aa8adc392/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[471,472,473,474,475,476,477,478],"take":"subject3/k1/3/cam4","frame_ids":[471,472,473,474,475,476,477,478]} +{"filtered_tile_id":"138dfc66313c782aa8adc392:40","filtered_window_id":"138dfc66313c782aa8adc392","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/138dfc66313c782aa8adc392/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[479,480,481,482,483,484,485,486],"take":"subject3/k1/3/cam4","frame_ids":[479,480,481,482,483,484,485,486]} +{"filtered_tile_id":"138dfc66313c782aa8adc392:48","filtered_window_id":"138dfc66313c782aa8adc392","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/138dfc66313c782aa8adc392/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject3/k1/3/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"138dfc66313c782aa8adc392:52","filtered_window_id":"138dfc66313c782aa8adc392","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/138dfc66313c782aa8adc392/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[491,492,493,494,495,496,497,498],"take":"subject3/k1/3/cam4","frame_ids":[491,492,493,494,495,496,497,498]} +{"filtered_tile_id":"13a9fe1c8b6f695eed882b91:0","filtered_window_id":"13a9fe1c8b6f695eed882b91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13a9fe1c8b6f695eed882b91/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject1/k2/5/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"13a9fe1c8b6f695eed882b91:8","filtered_window_id":"13a9fe1c8b6f695eed882b91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13a9fe1c8b6f695eed882b91/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject1/k2/5/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"13a9fe1c8b6f695eed882b91:16","filtered_window_id":"13a9fe1c8b6f695eed882b91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13a9fe1c8b6f695eed882b91/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject1/k2/5/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"13a9fe1c8b6f695eed882b91:24","filtered_window_id":"13a9fe1c8b6f695eed882b91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13a9fe1c8b6f695eed882b91/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject1/k2/5/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"13a9fe1c8b6f695eed882b91:32","filtered_window_id":"13a9fe1c8b6f695eed882b91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13a9fe1c8b6f695eed882b91/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject1/k2/5/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"13a9fe1c8b6f695eed882b91:40","filtered_window_id":"13a9fe1c8b6f695eed882b91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13a9fe1c8b6f695eed882b91/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[246,247,248,249,250,251,252,253],"take":"subject1/k2/5/cam4","frame_ids":[246,247,248,249,250,251,252,253]} +{"filtered_tile_id":"13a9fe1c8b6f695eed882b91:48","filtered_window_id":"13a9fe1c8b6f695eed882b91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13a9fe1c8b6f695eed882b91/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject1/k2/5/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"13a9fe1c8b6f695eed882b91:52","filtered_window_id":"13a9fe1c8b6f695eed882b91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13a9fe1c8b6f695eed882b91/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject1/k2/5/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"13c6fe636565bae56ecf3dfc:0","filtered_window_id":"13c6fe636565bae56ecf3dfc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13c6fe636565bae56ecf3dfc/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject1/k1/3/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"13c6fe636565bae56ecf3dfc:8","filtered_window_id":"13c6fe636565bae56ecf3dfc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13c6fe636565bae56ecf3dfc/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject1/k1/3/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"13c6fe636565bae56ecf3dfc:16","filtered_window_id":"13c6fe636565bae56ecf3dfc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13c6fe636565bae56ecf3dfc/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject1/k1/3/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"13c6fe636565bae56ecf3dfc:24","filtered_window_id":"13c6fe636565bae56ecf3dfc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13c6fe636565bae56ecf3dfc/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject1/k1/3/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"13c6fe636565bae56ecf3dfc:32","filtered_window_id":"13c6fe636565bae56ecf3dfc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13c6fe636565bae56ecf3dfc/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject1/k1/3/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"13c6fe636565bae56ecf3dfc:40","filtered_window_id":"13c6fe636565bae56ecf3dfc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13c6fe636565bae56ecf3dfc/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject1/k1/3/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"13c6fe636565bae56ecf3dfc:48","filtered_window_id":"13c6fe636565bae56ecf3dfc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13c6fe636565bae56ecf3dfc/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[175,176,177,178,179,180,181,182],"take":"subject1/k1/3/cam4","frame_ids":[175,176,177,178,179,180,181,182]} +{"filtered_tile_id":"13c6fe636565bae56ecf3dfc:52","filtered_window_id":"13c6fe636565bae56ecf3dfc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13c6fe636565bae56ecf3dfc/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject1/k1/3/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"13fc63ea3a9459aa00a122bf:0","filtered_window_id":"13fc63ea3a9459aa00a122bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13fc63ea3a9459aa00a122bf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[423,424,425,426,427,428,429,430],"take":"subject2/h2/0/cam4","frame_ids":[423,424,425,426,427,428,429,430]} +{"filtered_tile_id":"13fc63ea3a9459aa00a122bf:8","filtered_window_id":"13fc63ea3a9459aa00a122bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13fc63ea3a9459aa00a122bf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[431,432,433,434,435,436,437,438],"take":"subject2/h2/0/cam4","frame_ids":[431,432,433,434,435,436,437,438]} +{"filtered_tile_id":"13fc63ea3a9459aa00a122bf:16","filtered_window_id":"13fc63ea3a9459aa00a122bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13fc63ea3a9459aa00a122bf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[439,440,441,442,443,444,445,446],"take":"subject2/h2/0/cam4","frame_ids":[439,440,441,442,443,444,445,446]} +{"filtered_tile_id":"13fc63ea3a9459aa00a122bf:24","filtered_window_id":"13fc63ea3a9459aa00a122bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13fc63ea3a9459aa00a122bf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[447,448,449,450,451,452,453,454],"take":"subject2/h2/0/cam4","frame_ids":[447,448,449,450,451,452,453,454]} +{"filtered_tile_id":"13fc63ea3a9459aa00a122bf:32","filtered_window_id":"13fc63ea3a9459aa00a122bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13fc63ea3a9459aa00a122bf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[455,456,457,458,459,460,461,462],"take":"subject2/h2/0/cam4","frame_ids":[455,456,457,458,459,460,461,462]} +{"filtered_tile_id":"13fc63ea3a9459aa00a122bf:40","filtered_window_id":"13fc63ea3a9459aa00a122bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13fc63ea3a9459aa00a122bf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject2/h2/0/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"13fc63ea3a9459aa00a122bf:48","filtered_window_id":"13fc63ea3a9459aa00a122bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13fc63ea3a9459aa00a122bf/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[471,472,473,474,475,476,477,478],"take":"subject2/h2/0/cam4","frame_ids":[471,472,473,474,475,476,477,478]} +{"filtered_tile_id":"13fc63ea3a9459aa00a122bf:49","filtered_window_id":"13fc63ea3a9459aa00a122bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/13fc63ea3a9459aa00a122bf/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject2/h2/0/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"1430f728948cef17e2980d2c:0","filtered_window_id":"1430f728948cef17e2980d2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1430f728948cef17e2980d2c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[777,778,779,780,781,782,783,784],"take":"subject3/k1/5/cam4","frame_ids":[777,778,779,780,781,782,783,784]} +{"filtered_tile_id":"1430f728948cef17e2980d2c:8","filtered_window_id":"1430f728948cef17e2980d2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1430f728948cef17e2980d2c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[785,786,787,788,789,790,791,792],"take":"subject3/k1/5/cam4","frame_ids":[785,786,787,788,789,790,791,792]} +{"filtered_tile_id":"145bbfc057c86adae82654f1:0","filtered_window_id":"145bbfc057c86adae82654f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/145bbfc057c86adae82654f1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[578,579,580,581,582,583,584,585],"take":"subject2/h2/2/cam4","frame_ids":[578,579,580,581,582,583,584,585]} +{"filtered_tile_id":"145bbfc057c86adae82654f1:8","filtered_window_id":"145bbfc057c86adae82654f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/145bbfc057c86adae82654f1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[586,587,588,589,590,591,592,593],"take":"subject2/h2/2/cam4","frame_ids":[586,587,588,589,590,591,592,593]} +{"filtered_tile_id":"145bbfc057c86adae82654f1:16","filtered_window_id":"145bbfc057c86adae82654f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/145bbfc057c86adae82654f1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[594,595,596,597,598,599,600,601],"take":"subject2/h2/2/cam4","frame_ids":[594,595,596,597,598,599,600,601]} +{"filtered_tile_id":"145bbfc057c86adae82654f1:24","filtered_window_id":"145bbfc057c86adae82654f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/145bbfc057c86adae82654f1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[602,603,604,605,606,607,608,609],"take":"subject2/h2/2/cam4","frame_ids":[602,603,604,605,606,607,608,609]} +{"filtered_tile_id":"145bbfc057c86adae82654f1:25","filtered_window_id":"145bbfc057c86adae82654f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/145bbfc057c86adae82654f1/native_gt.npz","filtered_start_offset":25,"expected_frame_ids":[603,604,605,606,607,608,609,610],"take":"subject2/h2/2/cam4","frame_ids":[603,604,605,606,607,608,609,610]} +{"filtered_tile_id":"14bb7fa33da7388e18c85db6:0","filtered_window_id":"14bb7fa33da7388e18c85db6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/14bb7fa33da7388e18c85db6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[731,732,733,734,735,736,737,738],"take":"subject1/h1/3/cam4","frame_ids":[731,732,733,734,735,736,737,738]} +{"filtered_tile_id":"14bb7fa33da7388e18c85db6:8","filtered_window_id":"14bb7fa33da7388e18c85db6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/14bb7fa33da7388e18c85db6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[739,740,741,742,743,744,745,746],"take":"subject1/h1/3/cam4","frame_ids":[739,740,741,742,743,744,745,746]} +{"filtered_tile_id":"14bb7fa33da7388e18c85db6:16","filtered_window_id":"14bb7fa33da7388e18c85db6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/14bb7fa33da7388e18c85db6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[747,748,749,750,751,752,753,754],"take":"subject1/h1/3/cam4","frame_ids":[747,748,749,750,751,752,753,754]} +{"filtered_tile_id":"14bb7fa33da7388e18c85db6:24","filtered_window_id":"14bb7fa33da7388e18c85db6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/14bb7fa33da7388e18c85db6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[755,756,757,758,759,760,761,762],"take":"subject1/h1/3/cam4","frame_ids":[755,756,757,758,759,760,761,762]} +{"filtered_tile_id":"14bb7fa33da7388e18c85db6:32","filtered_window_id":"14bb7fa33da7388e18c85db6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/14bb7fa33da7388e18c85db6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[763,764,765,766,767,768,769,770],"take":"subject1/h1/3/cam4","frame_ids":[763,764,765,766,767,768,769,770]} +{"filtered_tile_id":"14bb7fa33da7388e18c85db6:40","filtered_window_id":"14bb7fa33da7388e18c85db6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/14bb7fa33da7388e18c85db6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[771,772,773,774,775,776,777,778],"take":"subject1/h1/3/cam4","frame_ids":[771,772,773,774,775,776,777,778]} +{"filtered_tile_id":"14bb7fa33da7388e18c85db6:42","filtered_window_id":"14bb7fa33da7388e18c85db6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/14bb7fa33da7388e18c85db6/native_gt.npz","filtered_start_offset":42,"expected_frame_ids":[773,774,775,776,777,778,779,780],"take":"subject1/h1/3/cam4","frame_ids":[773,774,775,776,777,778,779,780]} +{"filtered_tile_id":"156a1cc59c8c43b75f40bec8:0","filtered_window_id":"156a1cc59c8c43b75f40bec8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/156a1cc59c8c43b75f40bec8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject3/h1/3/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"156a1cc59c8c43b75f40bec8:8","filtered_window_id":"156a1cc59c8c43b75f40bec8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/156a1cc59c8c43b75f40bec8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject3/h1/3/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"156a1cc59c8c43b75f40bec8:16","filtered_window_id":"156a1cc59c8c43b75f40bec8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/156a1cc59c8c43b75f40bec8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject3/h1/3/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"156a1cc59c8c43b75f40bec8:24","filtered_window_id":"156a1cc59c8c43b75f40bec8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/156a1cc59c8c43b75f40bec8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject3/h1/3/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"156a1cc59c8c43b75f40bec8:32","filtered_window_id":"156a1cc59c8c43b75f40bec8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/156a1cc59c8c43b75f40bec8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject3/h1/3/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"156a1cc59c8c43b75f40bec8:40","filtered_window_id":"156a1cc59c8c43b75f40bec8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/156a1cc59c8c43b75f40bec8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[536,537,538,539,540,541,542,543],"take":"subject3/h1/3/cam4","frame_ids":[536,537,538,539,540,541,542,543]} +{"filtered_tile_id":"156a1cc59c8c43b75f40bec8:48","filtered_window_id":"156a1cc59c8c43b75f40bec8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/156a1cc59c8c43b75f40bec8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[544,545,546,547,548,549,550,551],"take":"subject3/h1/3/cam4","frame_ids":[544,545,546,547,548,549,550,551]} +{"filtered_tile_id":"156a1cc59c8c43b75f40bec8:52","filtered_window_id":"156a1cc59c8c43b75f40bec8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/156a1cc59c8c43b75f40bec8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject3/h1/3/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"158ca3b756550025a6b9c0ae:0","filtered_window_id":"158ca3b756550025a6b9c0ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/158ca3b756550025a6b9c0ae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject2/k1/5/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"158ca3b756550025a6b9c0ae:8","filtered_window_id":"158ca3b756550025a6b9c0ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/158ca3b756550025a6b9c0ae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[296,297,298,299,300,301,302,303],"take":"subject2/k1/5/cam4","frame_ids":[296,297,298,299,300,301,302,303]} +{"filtered_tile_id":"158ca3b756550025a6b9c0ae:16","filtered_window_id":"158ca3b756550025a6b9c0ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/158ca3b756550025a6b9c0ae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[304,305,306,307,308,309,310,311],"take":"subject2/k1/5/cam4","frame_ids":[304,305,306,307,308,309,310,311]} +{"filtered_tile_id":"158ca3b756550025a6b9c0ae:24","filtered_window_id":"158ca3b756550025a6b9c0ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/158ca3b756550025a6b9c0ae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[312,313,314,315,316,317,318,319],"take":"subject2/k1/5/cam4","frame_ids":[312,313,314,315,316,317,318,319]} +{"filtered_tile_id":"158ca3b756550025a6b9c0ae:32","filtered_window_id":"158ca3b756550025a6b9c0ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/158ca3b756550025a6b9c0ae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[320,321,322,323,324,325,326,327],"take":"subject2/k1/5/cam4","frame_ids":[320,321,322,323,324,325,326,327]} +{"filtered_tile_id":"158ca3b756550025a6b9c0ae:40","filtered_window_id":"158ca3b756550025a6b9c0ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/158ca3b756550025a6b9c0ae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[328,329,330,331,332,333,334,335],"take":"subject2/k1/5/cam4","frame_ids":[328,329,330,331,332,333,334,335]} +{"filtered_tile_id":"158ca3b756550025a6b9c0ae:48","filtered_window_id":"158ca3b756550025a6b9c0ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/158ca3b756550025a6b9c0ae/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[336,337,338,339,340,341,342,343],"take":"subject2/k1/5/cam4","frame_ids":[336,337,338,339,340,341,342,343]} +{"filtered_tile_id":"158ca3b756550025a6b9c0ae:52","filtered_window_id":"158ca3b756550025a6b9c0ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/158ca3b756550025a6b9c0ae/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[340,341,342,343,344,345,346,347],"take":"subject2/k1/5/cam4","frame_ids":[340,341,342,343,344,345,346,347]} +{"filtered_tile_id":"160da9dd3b8cedc875a28aee:0","filtered_window_id":"160da9dd3b8cedc875a28aee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/160da9dd3b8cedc875a28aee/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[244,245,246,247,248,249,250,251],"take":"subject2/k2/5/cam4","frame_ids":[244,245,246,247,248,249,250,251]} +{"filtered_tile_id":"160da9dd3b8cedc875a28aee:8","filtered_window_id":"160da9dd3b8cedc875a28aee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/160da9dd3b8cedc875a28aee/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[252,253,254,255,256,257,258,259],"take":"subject2/k2/5/cam4","frame_ids":[252,253,254,255,256,257,258,259]} +{"filtered_tile_id":"160da9dd3b8cedc875a28aee:16","filtered_window_id":"160da9dd3b8cedc875a28aee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/160da9dd3b8cedc875a28aee/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[260,261,262,263,264,265,266,267],"take":"subject2/k2/5/cam4","frame_ids":[260,261,262,263,264,265,266,267]} +{"filtered_tile_id":"160da9dd3b8cedc875a28aee:24","filtered_window_id":"160da9dd3b8cedc875a28aee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/160da9dd3b8cedc875a28aee/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[268,269,270,271,272,273,274,275],"take":"subject2/k2/5/cam4","frame_ids":[268,269,270,271,272,273,274,275]} +{"filtered_tile_id":"160da9dd3b8cedc875a28aee:29","filtered_window_id":"160da9dd3b8cedc875a28aee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/160da9dd3b8cedc875a28aee/native_gt.npz","filtered_start_offset":29,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject2/k2/5/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"162484cd74287c59483b9fb0:0","filtered_window_id":"162484cd74287c59483b9fb0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/162484cd74287c59483b9fb0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject3/h2/7/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"162484cd74287c59483b9fb0:8","filtered_window_id":"162484cd74287c59483b9fb0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/162484cd74287c59483b9fb0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[219,220,221,222,223,224,225,226],"take":"subject3/h2/7/cam4","frame_ids":[219,220,221,222,223,224,225,226]} +{"filtered_tile_id":"162484cd74287c59483b9fb0:16","filtered_window_id":"162484cd74287c59483b9fb0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/162484cd74287c59483b9fb0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[227,228,229,230,231,232,233,234],"take":"subject3/h2/7/cam4","frame_ids":[227,228,229,230,231,232,233,234]} +{"filtered_tile_id":"162484cd74287c59483b9fb0:24","filtered_window_id":"162484cd74287c59483b9fb0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/162484cd74287c59483b9fb0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[235,236,237,238,239,240,241,242],"take":"subject3/h2/7/cam4","frame_ids":[235,236,237,238,239,240,241,242]} +{"filtered_tile_id":"162484cd74287c59483b9fb0:32","filtered_window_id":"162484cd74287c59483b9fb0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/162484cd74287c59483b9fb0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[243,244,245,246,247,248,249,250],"take":"subject3/h2/7/cam4","frame_ids":[243,244,245,246,247,248,249,250]} +{"filtered_tile_id":"162484cd74287c59483b9fb0:40","filtered_window_id":"162484cd74287c59483b9fb0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/162484cd74287c59483b9fb0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[251,252,253,254,255,256,257,258],"take":"subject3/h2/7/cam4","frame_ids":[251,252,253,254,255,256,257,258]} +{"filtered_tile_id":"162484cd74287c59483b9fb0:48","filtered_window_id":"162484cd74287c59483b9fb0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/162484cd74287c59483b9fb0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[259,260,261,262,263,264,265,266],"take":"subject3/h2/7/cam4","frame_ids":[259,260,261,262,263,264,265,266]} +{"filtered_tile_id":"162484cd74287c59483b9fb0:52","filtered_window_id":"162484cd74287c59483b9fb0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/162484cd74287c59483b9fb0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject3/h2/7/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"1630829ccfd0591f559bc74a:0","filtered_window_id":"1630829ccfd0591f559bc74a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1630829ccfd0591f559bc74a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[601,602,603,604,605,606,607,608],"take":"subject2/k2/2/cam4","frame_ids":[601,602,603,604,605,606,607,608]} +{"filtered_tile_id":"1630829ccfd0591f559bc74a:8","filtered_window_id":"1630829ccfd0591f559bc74a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1630829ccfd0591f559bc74a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[609,610,611,612,613,614,615,616],"take":"subject2/k2/2/cam4","frame_ids":[609,610,611,612,613,614,615,616]} +{"filtered_tile_id":"1630829ccfd0591f559bc74a:12","filtered_window_id":"1630829ccfd0591f559bc74a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1630829ccfd0591f559bc74a/native_gt.npz","filtered_start_offset":12,"expected_frame_ids":[613,614,615,616,617,618,619,620],"take":"subject2/k2/2/cam4","frame_ids":[613,614,615,616,617,618,619,620]} +{"filtered_tile_id":"167355c53ba7dd0fc8c0555e:0","filtered_window_id":"167355c53ba7dd0fc8c0555e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/167355c53ba7dd0fc8c0555e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject3/h1/3/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"167355c53ba7dd0fc8c0555e:8","filtered_window_id":"167355c53ba7dd0fc8c0555e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/167355c53ba7dd0fc8c0555e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject3/h1/3/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"167355c53ba7dd0fc8c0555e:16","filtered_window_id":"167355c53ba7dd0fc8c0555e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/167355c53ba7dd0fc8c0555e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject3/h1/3/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"167355c53ba7dd0fc8c0555e:24","filtered_window_id":"167355c53ba7dd0fc8c0555e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/167355c53ba7dd0fc8c0555e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject3/h1/3/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"167355c53ba7dd0fc8c0555e:32","filtered_window_id":"167355c53ba7dd0fc8c0555e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/167355c53ba7dd0fc8c0555e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject3/h1/3/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"167355c53ba7dd0fc8c0555e:40","filtered_window_id":"167355c53ba7dd0fc8c0555e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/167355c53ba7dd0fc8c0555e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[236,237,238,239,240,241,242,243],"take":"subject3/h1/3/cam4","frame_ids":[236,237,238,239,240,241,242,243]} +{"filtered_tile_id":"167355c53ba7dd0fc8c0555e:48","filtered_window_id":"167355c53ba7dd0fc8c0555e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/167355c53ba7dd0fc8c0555e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[244,245,246,247,248,249,250,251],"take":"subject3/h1/3/cam4","frame_ids":[244,245,246,247,248,249,250,251]} +{"filtered_tile_id":"167355c53ba7dd0fc8c0555e:52","filtered_window_id":"167355c53ba7dd0fc8c0555e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/167355c53ba7dd0fc8c0555e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject3/h1/3/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"179236d729c3f165291f4d58:0","filtered_window_id":"179236d729c3f165291f4d58","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/179236d729c3f165291f4d58/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject2/h2/4/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"179236d729c3f165291f4d58:8","filtered_window_id":"179236d729c3f165291f4d58","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/179236d729c3f165291f4d58/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[77,78,79,80,81,82,83,84],"take":"subject2/h2/4/cam4","frame_ids":[77,78,79,80,81,82,83,84]} +{"filtered_tile_id":"179236d729c3f165291f4d58:16","filtered_window_id":"179236d729c3f165291f4d58","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/179236d729c3f165291f4d58/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject2/h2/4/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"179236d729c3f165291f4d58:24","filtered_window_id":"179236d729c3f165291f4d58","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/179236d729c3f165291f4d58/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[93,94,95,96,97,98,99,100],"take":"subject2/h2/4/cam4","frame_ids":[93,94,95,96,97,98,99,100]} +{"filtered_tile_id":"179236d729c3f165291f4d58:25","filtered_window_id":"179236d729c3f165291f4d58","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/179236d729c3f165291f4d58/native_gt.npz","filtered_start_offset":25,"expected_frame_ids":[94,95,96,97,98,99,100,101],"take":"subject2/h2/4/cam4","frame_ids":[94,95,96,97,98,99,100,101]} +{"filtered_tile_id":"18149eb332f012f04951224b:0","filtered_window_id":"18149eb332f012f04951224b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18149eb332f012f04951224b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject3/h2/1/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"18149eb332f012f04951224b:8","filtered_window_id":"18149eb332f012f04951224b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18149eb332f012f04951224b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject3/h2/1/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"18149eb332f012f04951224b:16","filtered_window_id":"18149eb332f012f04951224b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18149eb332f012f04951224b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject3/h2/1/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"18149eb332f012f04951224b:24","filtered_window_id":"18149eb332f012f04951224b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18149eb332f012f04951224b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject3/h2/1/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"18149eb332f012f04951224b:32","filtered_window_id":"18149eb332f012f04951224b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18149eb332f012f04951224b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject3/h2/1/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"18149eb332f012f04951224b:40","filtered_window_id":"18149eb332f012f04951224b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18149eb332f012f04951224b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject3/h2/1/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"18149eb332f012f04951224b:48","filtered_window_id":"18149eb332f012f04951224b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18149eb332f012f04951224b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject3/h2/1/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"18149eb332f012f04951224b:52","filtered_window_id":"18149eb332f012f04951224b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18149eb332f012f04951224b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject3/h2/1/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"1836c5074272fd45a5ce2e96:0","filtered_window_id":"1836c5074272fd45a5ce2e96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1836c5074272fd45a5ce2e96/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[355,356,357,358,359,360,361,362],"take":"subject2/o2/3/cam4","frame_ids":[355,356,357,358,359,360,361,362]} +{"filtered_tile_id":"1836c5074272fd45a5ce2e96:8","filtered_window_id":"1836c5074272fd45a5ce2e96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1836c5074272fd45a5ce2e96/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[363,364,365,366,367,368,369,370],"take":"subject2/o2/3/cam4","frame_ids":[363,364,365,366,367,368,369,370]} +{"filtered_tile_id":"1836c5074272fd45a5ce2e96:16","filtered_window_id":"1836c5074272fd45a5ce2e96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1836c5074272fd45a5ce2e96/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[371,372,373,374,375,376,377,378],"take":"subject2/o2/3/cam4","frame_ids":[371,372,373,374,375,376,377,378]} +{"filtered_tile_id":"1836c5074272fd45a5ce2e96:24","filtered_window_id":"1836c5074272fd45a5ce2e96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1836c5074272fd45a5ce2e96/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[379,380,381,382,383,384,385,386],"take":"subject2/o2/3/cam4","frame_ids":[379,380,381,382,383,384,385,386]} +{"filtered_tile_id":"1836c5074272fd45a5ce2e96:32","filtered_window_id":"1836c5074272fd45a5ce2e96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1836c5074272fd45a5ce2e96/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[387,388,389,390,391,392,393,394],"take":"subject2/o2/3/cam4","frame_ids":[387,388,389,390,391,392,393,394]} +{"filtered_tile_id":"1836c5074272fd45a5ce2e96:40","filtered_window_id":"1836c5074272fd45a5ce2e96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1836c5074272fd45a5ce2e96/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject2/o2/3/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"1836c5074272fd45a5ce2e96:48","filtered_window_id":"1836c5074272fd45a5ce2e96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1836c5074272fd45a5ce2e96/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject2/o2/3/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"1836c5074272fd45a5ce2e96:52","filtered_window_id":"1836c5074272fd45a5ce2e96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1836c5074272fd45a5ce2e96/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject2/o2/3/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"1845eeb65cc2ae2dfc77f4b2:0","filtered_window_id":"1845eeb65cc2ae2dfc77f4b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1845eeb65cc2ae2dfc77f4b2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject2/o2/4/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"1845eeb65cc2ae2dfc77f4b2:8","filtered_window_id":"1845eeb65cc2ae2dfc77f4b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1845eeb65cc2ae2dfc77f4b2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject2/o2/4/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"1845eeb65cc2ae2dfc77f4b2:16","filtered_window_id":"1845eeb65cc2ae2dfc77f4b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1845eeb65cc2ae2dfc77f4b2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject2/o2/4/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"1845eeb65cc2ae2dfc77f4b2:24","filtered_window_id":"1845eeb65cc2ae2dfc77f4b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1845eeb65cc2ae2dfc77f4b2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject2/o2/4/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"1845eeb65cc2ae2dfc77f4b2:32","filtered_window_id":"1845eeb65cc2ae2dfc77f4b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1845eeb65cc2ae2dfc77f4b2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject2/o2/4/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"1845eeb65cc2ae2dfc77f4b2:40","filtered_window_id":"1845eeb65cc2ae2dfc77f4b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1845eeb65cc2ae2dfc77f4b2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[274,275,276,277,278,279,280,281],"take":"subject2/o2/4/cam4","frame_ids":[274,275,276,277,278,279,280,281]} +{"filtered_tile_id":"1845eeb65cc2ae2dfc77f4b2:48","filtered_window_id":"1845eeb65cc2ae2dfc77f4b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1845eeb65cc2ae2dfc77f4b2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject2/o2/4/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"1845eeb65cc2ae2dfc77f4b2:52","filtered_window_id":"1845eeb65cc2ae2dfc77f4b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1845eeb65cc2ae2dfc77f4b2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[286,287,288,289,290,291,292,293],"take":"subject2/o2/4/cam4","frame_ids":[286,287,288,289,290,291,292,293]} +{"filtered_tile_id":"1869837511bc880bdace85ca:0","filtered_window_id":"1869837511bc880bdace85ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1869837511bc880bdace85ca/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject3/h1/6/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"1869837511bc880bdace85ca:8","filtered_window_id":"1869837511bc880bdace85ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1869837511bc880bdace85ca/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject3/h1/6/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"1869837511bc880bdace85ca:16","filtered_window_id":"1869837511bc880bdace85ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1869837511bc880bdace85ca/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject3/h1/6/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"1869837511bc880bdace85ca:24","filtered_window_id":"1869837511bc880bdace85ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1869837511bc880bdace85ca/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject3/h1/6/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"1869837511bc880bdace85ca:32","filtered_window_id":"1869837511bc880bdace85ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1869837511bc880bdace85ca/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject3/h1/6/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"1869837511bc880bdace85ca:40","filtered_window_id":"1869837511bc880bdace85ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1869837511bc880bdace85ca/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject3/h1/6/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"1869837511bc880bdace85ca:48","filtered_window_id":"1869837511bc880bdace85ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1869837511bc880bdace85ca/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject3/h1/6/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"1869837511bc880bdace85ca:52","filtered_window_id":"1869837511bc880bdace85ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1869837511bc880bdace85ca/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject3/h1/6/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"18b5567e8abb526f45c8a9f1:0","filtered_window_id":"18b5567e8abb526f45c8a9f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18b5567e8abb526f45c8a9f1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject2/o1/6/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"18b5567e8abb526f45c8a9f1:8","filtered_window_id":"18b5567e8abb526f45c8a9f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18b5567e8abb526f45c8a9f1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject2/o1/6/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"18b5567e8abb526f45c8a9f1:16","filtered_window_id":"18b5567e8abb526f45c8a9f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18b5567e8abb526f45c8a9f1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject2/o1/6/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"18b5567e8abb526f45c8a9f1:24","filtered_window_id":"18b5567e8abb526f45c8a9f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18b5567e8abb526f45c8a9f1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject2/o1/6/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"18b5567e8abb526f45c8a9f1:32","filtered_window_id":"18b5567e8abb526f45c8a9f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18b5567e8abb526f45c8a9f1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject2/o1/6/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"18b5567e8abb526f45c8a9f1:40","filtered_window_id":"18b5567e8abb526f45c8a9f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18b5567e8abb526f45c8a9f1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject2/o1/6/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"18b5567e8abb526f45c8a9f1:48","filtered_window_id":"18b5567e8abb526f45c8a9f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18b5567e8abb526f45c8a9f1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject2/o1/6/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"18b5567e8abb526f45c8a9f1:52","filtered_window_id":"18b5567e8abb526f45c8a9f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/18b5567e8abb526f45c8a9f1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[440,441,442,443,444,445,446,447],"take":"subject2/o1/6/cam4","frame_ids":[440,441,442,443,444,445,446,447]} +{"filtered_tile_id":"190fd760cb4cb156d76ce231:0","filtered_window_id":"190fd760cb4cb156d76ce231","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/190fd760cb4cb156d76ce231/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[323,324,325,326,327,328,329,330],"take":"subject3/h2/2/cam4","frame_ids":[323,324,325,326,327,328,329,330]} +{"filtered_tile_id":"190fd760cb4cb156d76ce231:8","filtered_window_id":"190fd760cb4cb156d76ce231","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/190fd760cb4cb156d76ce231/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[331,332,333,334,335,336,337,338],"take":"subject3/h2/2/cam4","frame_ids":[331,332,333,334,335,336,337,338]} +{"filtered_tile_id":"190fd760cb4cb156d76ce231:16","filtered_window_id":"190fd760cb4cb156d76ce231","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/190fd760cb4cb156d76ce231/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[339,340,341,342,343,344,345,346],"take":"subject3/h2/2/cam4","frame_ids":[339,340,341,342,343,344,345,346]} +{"filtered_tile_id":"190fd760cb4cb156d76ce231:24","filtered_window_id":"190fd760cb4cb156d76ce231","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/190fd760cb4cb156d76ce231/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[347,348,349,350,351,352,353,354],"take":"subject3/h2/2/cam4","frame_ids":[347,348,349,350,351,352,353,354]} +{"filtered_tile_id":"190fd760cb4cb156d76ce231:32","filtered_window_id":"190fd760cb4cb156d76ce231","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/190fd760cb4cb156d76ce231/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[355,356,357,358,359,360,361,362],"take":"subject3/h2/2/cam4","frame_ids":[355,356,357,358,359,360,361,362]} +{"filtered_tile_id":"190fd760cb4cb156d76ce231:40","filtered_window_id":"190fd760cb4cb156d76ce231","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/190fd760cb4cb156d76ce231/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[363,364,365,366,367,368,369,370],"take":"subject3/h2/2/cam4","frame_ids":[363,364,365,366,367,368,369,370]} +{"filtered_tile_id":"190fd760cb4cb156d76ce231:48","filtered_window_id":"190fd760cb4cb156d76ce231","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/190fd760cb4cb156d76ce231/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[371,372,373,374,375,376,377,378],"take":"subject3/h2/2/cam4","frame_ids":[371,372,373,374,375,376,377,378]} +{"filtered_tile_id":"190fd760cb4cb156d76ce231:52","filtered_window_id":"190fd760cb4cb156d76ce231","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/190fd760cb4cb156d76ce231/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[375,376,377,378,379,380,381,382],"take":"subject3/h2/2/cam4","frame_ids":[375,376,377,378,379,380,381,382]} +{"filtered_tile_id":"1928a18908e43b6e298bf1e9:0","filtered_window_id":"1928a18908e43b6e298bf1e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1928a18908e43b6e298bf1e9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[27,28,29,30,31,32,33,34],"take":"subject2/o1/3/cam4","frame_ids":[27,28,29,30,31,32,33,34]} +{"filtered_tile_id":"1928a18908e43b6e298bf1e9:8","filtered_window_id":"1928a18908e43b6e298bf1e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1928a18908e43b6e298bf1e9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[35,36,37,38,39,40,41,42],"take":"subject2/o1/3/cam4","frame_ids":[35,36,37,38,39,40,41,42]} +{"filtered_tile_id":"1928a18908e43b6e298bf1e9:16","filtered_window_id":"1928a18908e43b6e298bf1e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1928a18908e43b6e298bf1e9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[43,44,45,46,47,48,49,50],"take":"subject2/o1/3/cam4","frame_ids":[43,44,45,46,47,48,49,50]} +{"filtered_tile_id":"1928a18908e43b6e298bf1e9:24","filtered_window_id":"1928a18908e43b6e298bf1e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1928a18908e43b6e298bf1e9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject2/o1/3/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"1928a18908e43b6e298bf1e9:32","filtered_window_id":"1928a18908e43b6e298bf1e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1928a18908e43b6e298bf1e9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[59,60,61,62,63,64,65,66],"take":"subject2/o1/3/cam4","frame_ids":[59,60,61,62,63,64,65,66]} +{"filtered_tile_id":"1928a18908e43b6e298bf1e9:40","filtered_window_id":"1928a18908e43b6e298bf1e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1928a18908e43b6e298bf1e9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject2/o1/3/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"1928a18908e43b6e298bf1e9:48","filtered_window_id":"1928a18908e43b6e298bf1e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1928a18908e43b6e298bf1e9/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject2/o1/3/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"1928a18908e43b6e298bf1e9:49","filtered_window_id":"1928a18908e43b6e298bf1e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1928a18908e43b6e298bf1e9/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject2/o1/3/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"19423e07c98f372d1c057f72:0","filtered_window_id":"19423e07c98f372d1c057f72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19423e07c98f372d1c057f72/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[546,547,548,549,550,551,552,553],"take":"subject1/h2/7/cam4","frame_ids":[546,547,548,549,550,551,552,553]} +{"filtered_tile_id":"19423e07c98f372d1c057f72:8","filtered_window_id":"19423e07c98f372d1c057f72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19423e07c98f372d1c057f72/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[554,555,556,557,558,559,560,561],"take":"subject1/h2/7/cam4","frame_ids":[554,555,556,557,558,559,560,561]} +{"filtered_tile_id":"19423e07c98f372d1c057f72:16","filtered_window_id":"19423e07c98f372d1c057f72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19423e07c98f372d1c057f72/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[562,563,564,565,566,567,568,569],"take":"subject1/h2/7/cam4","frame_ids":[562,563,564,565,566,567,568,569]} +{"filtered_tile_id":"19423e07c98f372d1c057f72:24","filtered_window_id":"19423e07c98f372d1c057f72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19423e07c98f372d1c057f72/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[570,571,572,573,574,575,576,577],"take":"subject1/h2/7/cam4","frame_ids":[570,571,572,573,574,575,576,577]} +{"filtered_tile_id":"19423e07c98f372d1c057f72:32","filtered_window_id":"19423e07c98f372d1c057f72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19423e07c98f372d1c057f72/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[578,579,580,581,582,583,584,585],"take":"subject1/h2/7/cam4","frame_ids":[578,579,580,581,582,583,584,585]} +{"filtered_tile_id":"19423e07c98f372d1c057f72:40","filtered_window_id":"19423e07c98f372d1c057f72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19423e07c98f372d1c057f72/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[586,587,588,589,590,591,592,593],"take":"subject1/h2/7/cam4","frame_ids":[586,587,588,589,590,591,592,593]} +{"filtered_tile_id":"19423e07c98f372d1c057f72:48","filtered_window_id":"19423e07c98f372d1c057f72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19423e07c98f372d1c057f72/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[594,595,596,597,598,599,600,601],"take":"subject1/h2/7/cam4","frame_ids":[594,595,596,597,598,599,600,601]} +{"filtered_tile_id":"19423e07c98f372d1c057f72:52","filtered_window_id":"19423e07c98f372d1c057f72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19423e07c98f372d1c057f72/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[598,599,600,601,602,603,604,605],"take":"subject1/h2/7/cam4","frame_ids":[598,599,600,601,602,603,604,605]} +{"filtered_tile_id":"19df160247d7f6957b012bf3:0","filtered_window_id":"19df160247d7f6957b012bf3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19df160247d7f6957b012bf3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject2/k2/1/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"19df160247d7f6957b012bf3:4","filtered_window_id":"19df160247d7f6957b012bf3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/19df160247d7f6957b012bf3/native_gt.npz","filtered_start_offset":4,"expected_frame_ids":[284,285,286,287,288,289,290,291],"take":"subject2/k2/1/cam4","frame_ids":[284,285,286,287,288,289,290,291]} +{"filtered_tile_id":"1a0411b79c50842e39d45b42:0","filtered_window_id":"1a0411b79c50842e39d45b42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a0411b79c50842e39d45b42/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject3/h2/3/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"1a0411b79c50842e39d45b42:8","filtered_window_id":"1a0411b79c50842e39d45b42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a0411b79c50842e39d45b42/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject3/h2/3/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"1a0411b79c50842e39d45b42:16","filtered_window_id":"1a0411b79c50842e39d45b42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a0411b79c50842e39d45b42/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject3/h2/3/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"1a0411b79c50842e39d45b42:24","filtered_window_id":"1a0411b79c50842e39d45b42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a0411b79c50842e39d45b42/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject3/h2/3/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"1a0411b79c50842e39d45b42:32","filtered_window_id":"1a0411b79c50842e39d45b42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a0411b79c50842e39d45b42/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject3/h2/3/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"1a0411b79c50842e39d45b42:40","filtered_window_id":"1a0411b79c50842e39d45b42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a0411b79c50842e39d45b42/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject3/h2/3/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"1a0411b79c50842e39d45b42:48","filtered_window_id":"1a0411b79c50842e39d45b42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a0411b79c50842e39d45b42/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject3/h2/3/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"1a0411b79c50842e39d45b42:52","filtered_window_id":"1a0411b79c50842e39d45b42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a0411b79c50842e39d45b42/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[448,449,450,451,452,453,454,455],"take":"subject3/h2/3/cam4","frame_ids":[448,449,450,451,452,453,454,455]} +{"filtered_tile_id":"1a23d612b29e5f0966091a86:0","filtered_window_id":"1a23d612b29e5f0966091a86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a23d612b29e5f0966091a86/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[200,201,202,203,204,205,206,207],"take":"subject3/k1/1/cam4","frame_ids":[200,201,202,203,204,205,206,207]} +{"filtered_tile_id":"1a23d612b29e5f0966091a86:2","filtered_window_id":"1a23d612b29e5f0966091a86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a23d612b29e5f0966091a86/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[202,203,204,205,206,207,208,209],"take":"subject3/k1/1/cam4","frame_ids":[202,203,204,205,206,207,208,209]} +{"filtered_tile_id":"1a479fff1899b4781426c761:0","filtered_window_id":"1a479fff1899b4781426c761","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a479fff1899b4781426c761/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject3/h2/0/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"1a479fff1899b4781426c761:8","filtered_window_id":"1a479fff1899b4781426c761","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a479fff1899b4781426c761/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject3/h2/0/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"1a479fff1899b4781426c761:16","filtered_window_id":"1a479fff1899b4781426c761","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a479fff1899b4781426c761/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject3/h2/0/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"1a479fff1899b4781426c761:24","filtered_window_id":"1a479fff1899b4781426c761","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a479fff1899b4781426c761/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject3/h2/0/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"1a479fff1899b4781426c761:32","filtered_window_id":"1a479fff1899b4781426c761","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a479fff1899b4781426c761/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject3/h2/0/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"1a479fff1899b4781426c761:40","filtered_window_id":"1a479fff1899b4781426c761","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a479fff1899b4781426c761/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[274,275,276,277,278,279,280,281],"take":"subject3/h2/0/cam4","frame_ids":[274,275,276,277,278,279,280,281]} +{"filtered_tile_id":"1a479fff1899b4781426c761:48","filtered_window_id":"1a479fff1899b4781426c761","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a479fff1899b4781426c761/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject3/h2/0/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"1a479fff1899b4781426c761:52","filtered_window_id":"1a479fff1899b4781426c761","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a479fff1899b4781426c761/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[286,287,288,289,290,291,292,293],"take":"subject3/h2/0/cam4","frame_ids":[286,287,288,289,290,291,292,293]} +{"filtered_tile_id":"1a59a56e57b47879349724e0:0","filtered_window_id":"1a59a56e57b47879349724e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a59a56e57b47879349724e0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[65,66,67,68,69,70,71,72],"take":"subject1/h2/0/cam4","frame_ids":[65,66,67,68,69,70,71,72]} +{"filtered_tile_id":"1a59a56e57b47879349724e0:8","filtered_window_id":"1a59a56e57b47879349724e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a59a56e57b47879349724e0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[73,74,75,76,77,78,79,80],"take":"subject1/h2/0/cam4","frame_ids":[73,74,75,76,77,78,79,80]} +{"filtered_tile_id":"1a59a56e57b47879349724e0:16","filtered_window_id":"1a59a56e57b47879349724e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a59a56e57b47879349724e0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[81,82,83,84,85,86,87,88],"take":"subject1/h2/0/cam4","frame_ids":[81,82,83,84,85,86,87,88]} +{"filtered_tile_id":"1a59a56e57b47879349724e0:24","filtered_window_id":"1a59a56e57b47879349724e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a59a56e57b47879349724e0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[89,90,91,92,93,94,95,96],"take":"subject1/h2/0/cam4","frame_ids":[89,90,91,92,93,94,95,96]} +{"filtered_tile_id":"1a59a56e57b47879349724e0:32","filtered_window_id":"1a59a56e57b47879349724e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a59a56e57b47879349724e0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[97,98,99,100,101,102,103,104],"take":"subject1/h2/0/cam4","frame_ids":[97,98,99,100,101,102,103,104]} +{"filtered_tile_id":"1a59a56e57b47879349724e0:40","filtered_window_id":"1a59a56e57b47879349724e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a59a56e57b47879349724e0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[105,106,107,108,109,110,111,112],"take":"subject1/h2/0/cam4","frame_ids":[105,106,107,108,109,110,111,112]} +{"filtered_tile_id":"1a59a56e57b47879349724e0:48","filtered_window_id":"1a59a56e57b47879349724e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a59a56e57b47879349724e0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[113,114,115,116,117,118,119,120],"take":"subject1/h2/0/cam4","frame_ids":[113,114,115,116,117,118,119,120]} +{"filtered_tile_id":"1a59a56e57b47879349724e0:52","filtered_window_id":"1a59a56e57b47879349724e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1a59a56e57b47879349724e0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[117,118,119,120,121,122,123,124],"take":"subject1/h2/0/cam4","frame_ids":[117,118,119,120,121,122,123,124]} +{"filtered_tile_id":"1b2330c2948d5bfeda108f33:0","filtered_window_id":"1b2330c2948d5bfeda108f33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b2330c2948d5bfeda108f33/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[232,233,234,235,236,237,238,239],"take":"subject2/k1/3/cam4","frame_ids":[232,233,234,235,236,237,238,239]} +{"filtered_tile_id":"1b2330c2948d5bfeda108f33:8","filtered_window_id":"1b2330c2948d5bfeda108f33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b2330c2948d5bfeda108f33/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[240,241,242,243,244,245,246,247],"take":"subject2/k1/3/cam4","frame_ids":[240,241,242,243,244,245,246,247]} +{"filtered_tile_id":"1b2330c2948d5bfeda108f33:16","filtered_window_id":"1b2330c2948d5bfeda108f33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b2330c2948d5bfeda108f33/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject2/k1/3/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"1b2330c2948d5bfeda108f33:24","filtered_window_id":"1b2330c2948d5bfeda108f33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b2330c2948d5bfeda108f33/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject2/k1/3/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"1b2330c2948d5bfeda108f33:32","filtered_window_id":"1b2330c2948d5bfeda108f33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b2330c2948d5bfeda108f33/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject2/k1/3/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"1b2330c2948d5bfeda108f33:40","filtered_window_id":"1b2330c2948d5bfeda108f33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b2330c2948d5bfeda108f33/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject2/k1/3/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"1b2330c2948d5bfeda108f33:48","filtered_window_id":"1b2330c2948d5bfeda108f33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b2330c2948d5bfeda108f33/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject2/k1/3/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"1b2330c2948d5bfeda108f33:52","filtered_window_id":"1b2330c2948d5bfeda108f33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b2330c2948d5bfeda108f33/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[284,285,286,287,288,289,290,291],"take":"subject2/k1/3/cam4","frame_ids":[284,285,286,287,288,289,290,291]} +{"filtered_tile_id":"1b3230dc69a42ed393bcaedc:0","filtered_window_id":"1b3230dc69a42ed393bcaedc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b3230dc69a42ed393bcaedc/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[538,539,540,541,542,543,544,545],"take":"subject1/k2/1/cam4","frame_ids":[538,539,540,541,542,543,544,545]} +{"filtered_tile_id":"1b3230dc69a42ed393bcaedc:8","filtered_window_id":"1b3230dc69a42ed393bcaedc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b3230dc69a42ed393bcaedc/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[546,547,548,549,550,551,552,553],"take":"subject1/k2/1/cam4","frame_ids":[546,547,548,549,550,551,552,553]} +{"filtered_tile_id":"1b3230dc69a42ed393bcaedc:16","filtered_window_id":"1b3230dc69a42ed393bcaedc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b3230dc69a42ed393bcaedc/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[554,555,556,557,558,559,560,561],"take":"subject1/k2/1/cam4","frame_ids":[554,555,556,557,558,559,560,561]} +{"filtered_tile_id":"1b3230dc69a42ed393bcaedc:24","filtered_window_id":"1b3230dc69a42ed393bcaedc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b3230dc69a42ed393bcaedc/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[562,563,564,565,566,567,568,569],"take":"subject1/k2/1/cam4","frame_ids":[562,563,564,565,566,567,568,569]} +{"filtered_tile_id":"1b3230dc69a42ed393bcaedc:32","filtered_window_id":"1b3230dc69a42ed393bcaedc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b3230dc69a42ed393bcaedc/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[570,571,572,573,574,575,576,577],"take":"subject1/k2/1/cam4","frame_ids":[570,571,572,573,574,575,576,577]} +{"filtered_tile_id":"1b3230dc69a42ed393bcaedc:40","filtered_window_id":"1b3230dc69a42ed393bcaedc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b3230dc69a42ed393bcaedc/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[578,579,580,581,582,583,584,585],"take":"subject1/k2/1/cam4","frame_ids":[578,579,580,581,582,583,584,585]} +{"filtered_tile_id":"1b3230dc69a42ed393bcaedc:48","filtered_window_id":"1b3230dc69a42ed393bcaedc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b3230dc69a42ed393bcaedc/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[586,587,588,589,590,591,592,593],"take":"subject1/k2/1/cam4","frame_ids":[586,587,588,589,590,591,592,593]} +{"filtered_tile_id":"1b3230dc69a42ed393bcaedc:52","filtered_window_id":"1b3230dc69a42ed393bcaedc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b3230dc69a42ed393bcaedc/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[590,591,592,593,594,595,596,597],"take":"subject1/k2/1/cam4","frame_ids":[590,591,592,593,594,595,596,597]} +{"filtered_tile_id":"1b47ac1062c34b87adb14188:0","filtered_window_id":"1b47ac1062c34b87adb14188","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b47ac1062c34b87adb14188/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[295,296,297,298,299,300,301,302],"take":"subject2/o2/3/cam4","frame_ids":[295,296,297,298,299,300,301,302]} +{"filtered_tile_id":"1b47ac1062c34b87adb14188:8","filtered_window_id":"1b47ac1062c34b87adb14188","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b47ac1062c34b87adb14188/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[303,304,305,306,307,308,309,310],"take":"subject2/o2/3/cam4","frame_ids":[303,304,305,306,307,308,309,310]} +{"filtered_tile_id":"1b47ac1062c34b87adb14188:16","filtered_window_id":"1b47ac1062c34b87adb14188","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b47ac1062c34b87adb14188/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[311,312,313,314,315,316,317,318],"take":"subject2/o2/3/cam4","frame_ids":[311,312,313,314,315,316,317,318]} +{"filtered_tile_id":"1b47ac1062c34b87adb14188:24","filtered_window_id":"1b47ac1062c34b87adb14188","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b47ac1062c34b87adb14188/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[319,320,321,322,323,324,325,326],"take":"subject2/o2/3/cam4","frame_ids":[319,320,321,322,323,324,325,326]} +{"filtered_tile_id":"1b47ac1062c34b87adb14188:32","filtered_window_id":"1b47ac1062c34b87adb14188","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b47ac1062c34b87adb14188/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[327,328,329,330,331,332,333,334],"take":"subject2/o2/3/cam4","frame_ids":[327,328,329,330,331,332,333,334]} +{"filtered_tile_id":"1b47ac1062c34b87adb14188:40","filtered_window_id":"1b47ac1062c34b87adb14188","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b47ac1062c34b87adb14188/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[335,336,337,338,339,340,341,342],"take":"subject2/o2/3/cam4","frame_ids":[335,336,337,338,339,340,341,342]} +{"filtered_tile_id":"1b47ac1062c34b87adb14188:48","filtered_window_id":"1b47ac1062c34b87adb14188","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b47ac1062c34b87adb14188/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[343,344,345,346,347,348,349,350],"take":"subject2/o2/3/cam4","frame_ids":[343,344,345,346,347,348,349,350]} +{"filtered_tile_id":"1b47ac1062c34b87adb14188:52","filtered_window_id":"1b47ac1062c34b87adb14188","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b47ac1062c34b87adb14188/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[347,348,349,350,351,352,353,354],"take":"subject2/o2/3/cam4","frame_ids":[347,348,349,350,351,352,353,354]} +{"filtered_tile_id":"1b4dceb468ecfc4e91609520:0","filtered_window_id":"1b4dceb468ecfc4e91609520","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b4dceb468ecfc4e91609520/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[1189,1190,1191,1192,1193,1194,1195,1196],"take":"subject2/o1/2/cam4","frame_ids":[1189,1190,1191,1192,1193,1194,1195,1196]} +{"filtered_tile_id":"1b4dceb468ecfc4e91609520:8","filtered_window_id":"1b4dceb468ecfc4e91609520","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b4dceb468ecfc4e91609520/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[1197,1198,1199,1200,1201,1202,1203,1204],"take":"subject2/o1/2/cam4","frame_ids":[1197,1198,1199,1200,1201,1202,1203,1204]} +{"filtered_tile_id":"1b4dceb468ecfc4e91609520:16","filtered_window_id":"1b4dceb468ecfc4e91609520","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b4dceb468ecfc4e91609520/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[1205,1206,1207,1208,1209,1210,1211,1212],"take":"subject2/o1/2/cam4","frame_ids":[1205,1206,1207,1208,1209,1210,1211,1212]} +{"filtered_tile_id":"1b4dceb468ecfc4e91609520:24","filtered_window_id":"1b4dceb468ecfc4e91609520","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b4dceb468ecfc4e91609520/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[1213,1214,1215,1216,1217,1218,1219,1220],"take":"subject2/o1/2/cam4","frame_ids":[1213,1214,1215,1216,1217,1218,1219,1220]} +{"filtered_tile_id":"1b4dceb468ecfc4e91609520:32","filtered_window_id":"1b4dceb468ecfc4e91609520","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b4dceb468ecfc4e91609520/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[1221,1222,1223,1224,1225,1226,1227,1228],"take":"subject2/o1/2/cam4","frame_ids":[1221,1222,1223,1224,1225,1226,1227,1228]} +{"filtered_tile_id":"1b4dceb468ecfc4e91609520:40","filtered_window_id":"1b4dceb468ecfc4e91609520","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b4dceb468ecfc4e91609520/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[1229,1230,1231,1232,1233,1234,1235,1236],"take":"subject2/o1/2/cam4","frame_ids":[1229,1230,1231,1232,1233,1234,1235,1236]} +{"filtered_tile_id":"1b4dceb468ecfc4e91609520:41","filtered_window_id":"1b4dceb468ecfc4e91609520","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b4dceb468ecfc4e91609520/native_gt.npz","filtered_start_offset":41,"expected_frame_ids":[1230,1231,1232,1233,1234,1235,1236,1237],"take":"subject2/o1/2/cam4","frame_ids":[1230,1231,1232,1233,1234,1235,1236,1237]} +{"filtered_tile_id":"1b51cc8f9725d3eb00768228:0","filtered_window_id":"1b51cc8f9725d3eb00768228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b51cc8f9725d3eb00768228/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[392,393,394,395,396,397,398,399],"take":"subject3/h2/5/cam4","frame_ids":[392,393,394,395,396,397,398,399]} +{"filtered_tile_id":"1b51cc8f9725d3eb00768228:8","filtered_window_id":"1b51cc8f9725d3eb00768228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b51cc8f9725d3eb00768228/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[400,401,402,403,404,405,406,407],"take":"subject3/h2/5/cam4","frame_ids":[400,401,402,403,404,405,406,407]} +{"filtered_tile_id":"1b51cc8f9725d3eb00768228:16","filtered_window_id":"1b51cc8f9725d3eb00768228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b51cc8f9725d3eb00768228/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[408,409,410,411,412,413,414,415],"take":"subject3/h2/5/cam4","frame_ids":[408,409,410,411,412,413,414,415]} +{"filtered_tile_id":"1b51cc8f9725d3eb00768228:24","filtered_window_id":"1b51cc8f9725d3eb00768228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b51cc8f9725d3eb00768228/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[416,417,418,419,420,421,422,423],"take":"subject3/h2/5/cam4","frame_ids":[416,417,418,419,420,421,422,423]} +{"filtered_tile_id":"1b51cc8f9725d3eb00768228:32","filtered_window_id":"1b51cc8f9725d3eb00768228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b51cc8f9725d3eb00768228/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[424,425,426,427,428,429,430,431],"take":"subject3/h2/5/cam4","frame_ids":[424,425,426,427,428,429,430,431]} +{"filtered_tile_id":"1b51cc8f9725d3eb00768228:40","filtered_window_id":"1b51cc8f9725d3eb00768228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b51cc8f9725d3eb00768228/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[432,433,434,435,436,437,438,439],"take":"subject3/h2/5/cam4","frame_ids":[432,433,434,435,436,437,438,439]} +{"filtered_tile_id":"1b51cc8f9725d3eb00768228:48","filtered_window_id":"1b51cc8f9725d3eb00768228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b51cc8f9725d3eb00768228/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[440,441,442,443,444,445,446,447],"take":"subject3/h2/5/cam4","frame_ids":[440,441,442,443,444,445,446,447]} +{"filtered_tile_id":"1b51cc8f9725d3eb00768228:52","filtered_window_id":"1b51cc8f9725d3eb00768228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1b51cc8f9725d3eb00768228/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject3/h2/5/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"1bf7dc0d845a5d3f5f8187f6:0","filtered_window_id":"1bf7dc0d845a5d3f5f8187f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1bf7dc0d845a5d3f5f8187f6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject2/k2/0/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"1bf7dc0d845a5d3f5f8187f6:8","filtered_window_id":"1bf7dc0d845a5d3f5f8187f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1bf7dc0d845a5d3f5f8187f6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[536,537,538,539,540,541,542,543],"take":"subject2/k2/0/cam4","frame_ids":[536,537,538,539,540,541,542,543]} +{"filtered_tile_id":"1bf7dc0d845a5d3f5f8187f6:16","filtered_window_id":"1bf7dc0d845a5d3f5f8187f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1bf7dc0d845a5d3f5f8187f6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[544,545,546,547,548,549,550,551],"take":"subject2/k2/0/cam4","frame_ids":[544,545,546,547,548,549,550,551]} +{"filtered_tile_id":"1bf7dc0d845a5d3f5f8187f6:24","filtered_window_id":"1bf7dc0d845a5d3f5f8187f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1bf7dc0d845a5d3f5f8187f6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[552,553,554,555,556,557,558,559],"take":"subject2/k2/0/cam4","frame_ids":[552,553,554,555,556,557,558,559]} +{"filtered_tile_id":"1bf7dc0d845a5d3f5f8187f6:32","filtered_window_id":"1bf7dc0d845a5d3f5f8187f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1bf7dc0d845a5d3f5f8187f6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[560,561,562,563,564,565,566,567],"take":"subject2/k2/0/cam4","frame_ids":[560,561,562,563,564,565,566,567]} +{"filtered_tile_id":"1bf7dc0d845a5d3f5f8187f6:40","filtered_window_id":"1bf7dc0d845a5d3f5f8187f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1bf7dc0d845a5d3f5f8187f6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[568,569,570,571,572,573,574,575],"take":"subject2/k2/0/cam4","frame_ids":[568,569,570,571,572,573,574,575]} +{"filtered_tile_id":"1bf7dc0d845a5d3f5f8187f6:48","filtered_window_id":"1bf7dc0d845a5d3f5f8187f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1bf7dc0d845a5d3f5f8187f6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[576,577,578,579,580,581,582,583],"take":"subject2/k2/0/cam4","frame_ids":[576,577,578,579,580,581,582,583]} +{"filtered_tile_id":"1bf7dc0d845a5d3f5f8187f6:52","filtered_window_id":"1bf7dc0d845a5d3f5f8187f6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1bf7dc0d845a5d3f5f8187f6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[580,581,582,583,584,585,586,587],"take":"subject2/k2/0/cam4","frame_ids":[580,581,582,583,584,585,586,587]} +{"filtered_tile_id":"1c119ebc98d9343b8297b04e:0","filtered_window_id":"1c119ebc98d9343b8297b04e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1c119ebc98d9343b8297b04e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject1/h1/1/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"1c119ebc98d9343b8297b04e:8","filtered_window_id":"1c119ebc98d9343b8297b04e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1c119ebc98d9343b8297b04e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject1/h1/1/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"1c119ebc98d9343b8297b04e:16","filtered_window_id":"1c119ebc98d9343b8297b04e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1c119ebc98d9343b8297b04e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject1/h1/1/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"1c119ebc98d9343b8297b04e:24","filtered_window_id":"1c119ebc98d9343b8297b04e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1c119ebc98d9343b8297b04e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject1/h1/1/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"1c119ebc98d9343b8297b04e:32","filtered_window_id":"1c119ebc98d9343b8297b04e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1c119ebc98d9343b8297b04e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject1/h1/1/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"1c119ebc98d9343b8297b04e:40","filtered_window_id":"1c119ebc98d9343b8297b04e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1c119ebc98d9343b8297b04e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject1/h1/1/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"1c119ebc98d9343b8297b04e:48","filtered_window_id":"1c119ebc98d9343b8297b04e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1c119ebc98d9343b8297b04e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject1/h1/1/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"1c119ebc98d9343b8297b04e:52","filtered_window_id":"1c119ebc98d9343b8297b04e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1c119ebc98d9343b8297b04e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject1/h1/1/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"1d05034c4532b887ef3a55be:0","filtered_window_id":"1d05034c4532b887ef3a55be","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d05034c4532b887ef3a55be/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[483,484,485,486,487,488,489,490],"take":"subject1/o1/5/cam4","frame_ids":[483,484,485,486,487,488,489,490]} +{"filtered_tile_id":"1d05034c4532b887ef3a55be:8","filtered_window_id":"1d05034c4532b887ef3a55be","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d05034c4532b887ef3a55be/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[491,492,493,494,495,496,497,498],"take":"subject1/o1/5/cam4","frame_ids":[491,492,493,494,495,496,497,498]} +{"filtered_tile_id":"1d05034c4532b887ef3a55be:16","filtered_window_id":"1d05034c4532b887ef3a55be","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d05034c4532b887ef3a55be/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[499,500,501,502,503,504,505,506],"take":"subject1/o1/5/cam4","frame_ids":[499,500,501,502,503,504,505,506]} +{"filtered_tile_id":"1d05034c4532b887ef3a55be:24","filtered_window_id":"1d05034c4532b887ef3a55be","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d05034c4532b887ef3a55be/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[507,508,509,510,511,512,513,514],"take":"subject1/o1/5/cam4","frame_ids":[507,508,509,510,511,512,513,514]} +{"filtered_tile_id":"1d05034c4532b887ef3a55be:32","filtered_window_id":"1d05034c4532b887ef3a55be","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d05034c4532b887ef3a55be/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[515,516,517,518,519,520,521,522],"take":"subject1/o1/5/cam4","frame_ids":[515,516,517,518,519,520,521,522]} +{"filtered_tile_id":"1d05034c4532b887ef3a55be:40","filtered_window_id":"1d05034c4532b887ef3a55be","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d05034c4532b887ef3a55be/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[523,524,525,526,527,528,529,530],"take":"subject1/o1/5/cam4","frame_ids":[523,524,525,526,527,528,529,530]} +{"filtered_tile_id":"1d05034c4532b887ef3a55be:48","filtered_window_id":"1d05034c4532b887ef3a55be","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d05034c4532b887ef3a55be/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[531,532,533,534,535,536,537,538],"take":"subject1/o1/5/cam4","frame_ids":[531,532,533,534,535,536,537,538]} +{"filtered_tile_id":"1d05034c4532b887ef3a55be:52","filtered_window_id":"1d05034c4532b887ef3a55be","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d05034c4532b887ef3a55be/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[535,536,537,538,539,540,541,542],"take":"subject1/o1/5/cam4","frame_ids":[535,536,537,538,539,540,541,542]} +{"filtered_tile_id":"1d079b9f47e262118a6ae882:0","filtered_window_id":"1d079b9f47e262118a6ae882","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d079b9f47e262118a6ae882/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[103,104,105,106,107,108,109,110],"take":"subject2/h1/6/cam4","frame_ids":[103,104,105,106,107,108,109,110]} +{"filtered_tile_id":"1d079b9f47e262118a6ae882:6","filtered_window_id":"1d079b9f47e262118a6ae882","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1d079b9f47e262118a6ae882/native_gt.npz","filtered_start_offset":6,"expected_frame_ids":[109,110,111,112,113,114,115,116],"take":"subject2/h1/6/cam4","frame_ids":[109,110,111,112,113,114,115,116]} +{"filtered_tile_id":"1e0f957ce7bbdbe1574b9a28:0","filtered_window_id":"1e0f957ce7bbdbe1574b9a28","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e0f957ce7bbdbe1574b9a28/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject2/o1/3/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"1e0f957ce7bbdbe1574b9a28:1","filtered_window_id":"1e0f957ce7bbdbe1574b9a28","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e0f957ce7bbdbe1574b9a28/native_gt.npz","filtered_start_offset":1,"expected_frame_ids":[347,348,349,350,351,352,353,354],"take":"subject2/o1/3/cam4","frame_ids":[347,348,349,350,351,352,353,354]} +{"filtered_tile_id":"1e19a10428684f4f2be23d70:0","filtered_window_id":"1e19a10428684f4f2be23d70","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e19a10428684f4f2be23d70/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject2/h1/7/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"1e19a10428684f4f2be23d70:7","filtered_window_id":"1e19a10428684f4f2be23d70","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e19a10428684f4f2be23d70/native_gt.npz","filtered_start_offset":7,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject2/h1/7/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"1e4b025afba6e86a261222b5:0","filtered_window_id":"1e4b025afba6e86a261222b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e4b025afba6e86a261222b5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[232,233,234,235,236,237,238,239],"take":"subject2/h1/6/cam4","frame_ids":[232,233,234,235,236,237,238,239]} +{"filtered_tile_id":"1e4b025afba6e86a261222b5:8","filtered_window_id":"1e4b025afba6e86a261222b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e4b025afba6e86a261222b5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[240,241,242,243,244,245,246,247],"take":"subject2/h1/6/cam4","frame_ids":[240,241,242,243,244,245,246,247]} +{"filtered_tile_id":"1e4b025afba6e86a261222b5:16","filtered_window_id":"1e4b025afba6e86a261222b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e4b025afba6e86a261222b5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject2/h1/6/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"1e4b025afba6e86a261222b5:24","filtered_window_id":"1e4b025afba6e86a261222b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e4b025afba6e86a261222b5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject2/h1/6/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"1e4b025afba6e86a261222b5:32","filtered_window_id":"1e4b025afba6e86a261222b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e4b025afba6e86a261222b5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject2/h1/6/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"1e4b025afba6e86a261222b5:40","filtered_window_id":"1e4b025afba6e86a261222b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e4b025afba6e86a261222b5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject2/h1/6/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"1e4b025afba6e86a261222b5:48","filtered_window_id":"1e4b025afba6e86a261222b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e4b025afba6e86a261222b5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject2/h1/6/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"1e4b025afba6e86a261222b5:52","filtered_window_id":"1e4b025afba6e86a261222b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e4b025afba6e86a261222b5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[284,285,286,287,288,289,290,291],"take":"subject2/h1/6/cam4","frame_ids":[284,285,286,287,288,289,290,291]} +{"filtered_tile_id":"1e5e3c8907e431d086b43f25:0","filtered_window_id":"1e5e3c8907e431d086b43f25","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e5e3c8907e431d086b43f25/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[733,734,735,736,737,738,739,740],"take":"subject1/k1/3/cam4","frame_ids":[733,734,735,736,737,738,739,740]} +{"filtered_tile_id":"1e5e3c8907e431d086b43f25:8","filtered_window_id":"1e5e3c8907e431d086b43f25","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e5e3c8907e431d086b43f25/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[741,742,743,744,745,746,747,748],"take":"subject1/k1/3/cam4","frame_ids":[741,742,743,744,745,746,747,748]} +{"filtered_tile_id":"1e5e3c8907e431d086b43f25:16","filtered_window_id":"1e5e3c8907e431d086b43f25","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e5e3c8907e431d086b43f25/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[749,750,751,752,753,754,755,756],"take":"subject1/k1/3/cam4","frame_ids":[749,750,751,752,753,754,755,756]} +{"filtered_tile_id":"1e5e3c8907e431d086b43f25:24","filtered_window_id":"1e5e3c8907e431d086b43f25","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e5e3c8907e431d086b43f25/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[757,758,759,760,761,762,763,764],"take":"subject1/k1/3/cam4","frame_ids":[757,758,759,760,761,762,763,764]} +{"filtered_tile_id":"1e5e3c8907e431d086b43f25:32","filtered_window_id":"1e5e3c8907e431d086b43f25","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e5e3c8907e431d086b43f25/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[765,766,767,768,769,770,771,772],"take":"subject1/k1/3/cam4","frame_ids":[765,766,767,768,769,770,771,772]} +{"filtered_tile_id":"1e5e3c8907e431d086b43f25:35","filtered_window_id":"1e5e3c8907e431d086b43f25","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1e5e3c8907e431d086b43f25/native_gt.npz","filtered_start_offset":35,"expected_frame_ids":[768,769,770,771,772,773,774,775],"take":"subject1/k1/3/cam4","frame_ids":[768,769,770,771,772,773,774,775]} +{"filtered_tile_id":"1eda9554e92311bcf7fa0626:0","filtered_window_id":"1eda9554e92311bcf7fa0626","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eda9554e92311bcf7fa0626/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject3/h2/5/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"1eda9554e92311bcf7fa0626:8","filtered_window_id":"1eda9554e92311bcf7fa0626","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eda9554e92311bcf7fa0626/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject3/h2/5/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"1eda9554e92311bcf7fa0626:16","filtered_window_id":"1eda9554e92311bcf7fa0626","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eda9554e92311bcf7fa0626/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject3/h2/5/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"1eda9554e92311bcf7fa0626:24","filtered_window_id":"1eda9554e92311bcf7fa0626","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eda9554e92311bcf7fa0626/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject3/h2/5/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"1eda9554e92311bcf7fa0626:32","filtered_window_id":"1eda9554e92311bcf7fa0626","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eda9554e92311bcf7fa0626/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[175,176,177,178,179,180,181,182],"take":"subject3/h2/5/cam4","frame_ids":[175,176,177,178,179,180,181,182]} +{"filtered_tile_id":"1eda9554e92311bcf7fa0626:40","filtered_window_id":"1eda9554e92311bcf7fa0626","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eda9554e92311bcf7fa0626/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[183,184,185,186,187,188,189,190],"take":"subject3/h2/5/cam4","frame_ids":[183,184,185,186,187,188,189,190]} +{"filtered_tile_id":"1eda9554e92311bcf7fa0626:48","filtered_window_id":"1eda9554e92311bcf7fa0626","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eda9554e92311bcf7fa0626/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[191,192,193,194,195,196,197,198],"take":"subject3/h2/5/cam4","frame_ids":[191,192,193,194,195,196,197,198]} +{"filtered_tile_id":"1eda9554e92311bcf7fa0626:52","filtered_window_id":"1eda9554e92311bcf7fa0626","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eda9554e92311bcf7fa0626/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject3/h2/5/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"1eec23b9e8be7fefbcf2261a:0","filtered_window_id":"1eec23b9e8be7fefbcf2261a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eec23b9e8be7fefbcf2261a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[377,378,379,380,381,382,383,384],"take":"subject1/h1/0/cam4","frame_ids":[377,378,379,380,381,382,383,384]} +{"filtered_tile_id":"1eec23b9e8be7fefbcf2261a:8","filtered_window_id":"1eec23b9e8be7fefbcf2261a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eec23b9e8be7fefbcf2261a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[385,386,387,388,389,390,391,392],"take":"subject1/h1/0/cam4","frame_ids":[385,386,387,388,389,390,391,392]} +{"filtered_tile_id":"1eec23b9e8be7fefbcf2261a:16","filtered_window_id":"1eec23b9e8be7fefbcf2261a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eec23b9e8be7fefbcf2261a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[393,394,395,396,397,398,399,400],"take":"subject1/h1/0/cam4","frame_ids":[393,394,395,396,397,398,399,400]} +{"filtered_tile_id":"1eec23b9e8be7fefbcf2261a:24","filtered_window_id":"1eec23b9e8be7fefbcf2261a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eec23b9e8be7fefbcf2261a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[401,402,403,404,405,406,407,408],"take":"subject1/h1/0/cam4","frame_ids":[401,402,403,404,405,406,407,408]} +{"filtered_tile_id":"1eec23b9e8be7fefbcf2261a:32","filtered_window_id":"1eec23b9e8be7fefbcf2261a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eec23b9e8be7fefbcf2261a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[409,410,411,412,413,414,415,416],"take":"subject1/h1/0/cam4","frame_ids":[409,410,411,412,413,414,415,416]} +{"filtered_tile_id":"1eec23b9e8be7fefbcf2261a:33","filtered_window_id":"1eec23b9e8be7fefbcf2261a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1eec23b9e8be7fefbcf2261a/native_gt.npz","filtered_start_offset":33,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject1/h1/0/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"1f418977a1967b5158e55522:0","filtered_window_id":"1f418977a1967b5158e55522","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f418977a1967b5158e55522/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject3/h1/6/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"1f418977a1967b5158e55522:8","filtered_window_id":"1f418977a1967b5158e55522","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f418977a1967b5158e55522/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject3/h1/6/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"1f418977a1967b5158e55522:16","filtered_window_id":"1f418977a1967b5158e55522","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f418977a1967b5158e55522/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject3/h1/6/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"1f418977a1967b5158e55522:24","filtered_window_id":"1f418977a1967b5158e55522","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f418977a1967b5158e55522/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject3/h1/6/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"1f418977a1967b5158e55522:32","filtered_window_id":"1f418977a1967b5158e55522","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f418977a1967b5158e55522/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject3/h1/6/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"1f418977a1967b5158e55522:40","filtered_window_id":"1f418977a1967b5158e55522","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f418977a1967b5158e55522/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject3/h1/6/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"1f418977a1967b5158e55522:48","filtered_window_id":"1f418977a1967b5158e55522","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f418977a1967b5158e55522/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[468,469,470,471,472,473,474,475],"take":"subject3/h1/6/cam4","frame_ids":[468,469,470,471,472,473,474,475]} +{"filtered_tile_id":"1f418977a1967b5158e55522:52","filtered_window_id":"1f418977a1967b5158e55522","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f418977a1967b5158e55522/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject3/h1/6/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"1f58444d0b64c7d11a7ebbbf:0","filtered_window_id":"1f58444d0b64c7d11a7ebbbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f58444d0b64c7d11a7ebbbf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[125,126,127,128,129,130,131,132],"take":"subject3/h1/5/cam4","frame_ids":[125,126,127,128,129,130,131,132]} +{"filtered_tile_id":"1f58444d0b64c7d11a7ebbbf:8","filtered_window_id":"1f58444d0b64c7d11a7ebbbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f58444d0b64c7d11a7ebbbf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject3/h1/5/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"1f58444d0b64c7d11a7ebbbf:16","filtered_window_id":"1f58444d0b64c7d11a7ebbbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f58444d0b64c7d11a7ebbbf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject3/h1/5/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"1f58444d0b64c7d11a7ebbbf:24","filtered_window_id":"1f58444d0b64c7d11a7ebbbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f58444d0b64c7d11a7ebbbf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject3/h1/5/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"1f58444d0b64c7d11a7ebbbf:32","filtered_window_id":"1f58444d0b64c7d11a7ebbbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f58444d0b64c7d11a7ebbbf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject3/h1/5/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"1f58444d0b64c7d11a7ebbbf:40","filtered_window_id":"1f58444d0b64c7d11a7ebbbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f58444d0b64c7d11a7ebbbf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject3/h1/5/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"1f58444d0b64c7d11a7ebbbf:48","filtered_window_id":"1f58444d0b64c7d11a7ebbbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f58444d0b64c7d11a7ebbbf/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject3/h1/5/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"1f58444d0b64c7d11a7ebbbf:52","filtered_window_id":"1f58444d0b64c7d11a7ebbbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f58444d0b64c7d11a7ebbbf/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject3/h1/5/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"1f6aba94209019a3d4903c93:0","filtered_window_id":"1f6aba94209019a3d4903c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6aba94209019a3d4903c93/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/h2/6/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"1f6aba94209019a3d4903c93:8","filtered_window_id":"1f6aba94209019a3d4903c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6aba94209019a3d4903c93/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject2/h2/6/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"1f6aba94209019a3d4903c93:16","filtered_window_id":"1f6aba94209019a3d4903c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6aba94209019a3d4903c93/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject2/h2/6/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"1f6aba94209019a3d4903c93:24","filtered_window_id":"1f6aba94209019a3d4903c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6aba94209019a3d4903c93/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject2/h2/6/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"1f6aba94209019a3d4903c93:32","filtered_window_id":"1f6aba94209019a3d4903c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6aba94209019a3d4903c93/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject2/h2/6/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"1f6aba94209019a3d4903c93:39","filtered_window_id":"1f6aba94209019a3d4903c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6aba94209019a3d4903c93/native_gt.npz","filtered_start_offset":39,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject2/h2/6/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"1f6d82b00b84bb172f87eaa2:0","filtered_window_id":"1f6d82b00b84bb172f87eaa2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6d82b00b84bb172f87eaa2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject1/h2/5/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"1f6d82b00b84bb172f87eaa2:8","filtered_window_id":"1f6d82b00b84bb172f87eaa2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6d82b00b84bb172f87eaa2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[207,208,209,210,211,212,213,214],"take":"subject1/h2/5/cam4","frame_ids":[207,208,209,210,211,212,213,214]} +{"filtered_tile_id":"1f6d82b00b84bb172f87eaa2:16","filtered_window_id":"1f6d82b00b84bb172f87eaa2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6d82b00b84bb172f87eaa2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[215,216,217,218,219,220,221,222],"take":"subject1/h2/5/cam4","frame_ids":[215,216,217,218,219,220,221,222]} +{"filtered_tile_id":"1f6d82b00b84bb172f87eaa2:24","filtered_window_id":"1f6d82b00b84bb172f87eaa2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6d82b00b84bb172f87eaa2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject1/h2/5/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"1f6d82b00b84bb172f87eaa2:32","filtered_window_id":"1f6d82b00b84bb172f87eaa2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6d82b00b84bb172f87eaa2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject1/h2/5/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"1f6d82b00b84bb172f87eaa2:40","filtered_window_id":"1f6d82b00b84bb172f87eaa2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6d82b00b84bb172f87eaa2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject1/h2/5/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"1f6d82b00b84bb172f87eaa2:48","filtered_window_id":"1f6d82b00b84bb172f87eaa2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6d82b00b84bb172f87eaa2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject1/h2/5/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"1f6d82b00b84bb172f87eaa2:52","filtered_window_id":"1f6d82b00b84bb172f87eaa2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f6d82b00b84bb172f87eaa2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[251,252,253,254,255,256,257,258],"take":"subject1/h2/5/cam4","frame_ids":[251,252,253,254,255,256,257,258]} +{"filtered_tile_id":"1f784267c3a25a8396441340:0","filtered_window_id":"1f784267c3a25a8396441340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f784267c3a25a8396441340/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[439,440,441,442,443,444,445,446],"take":"subject2/k2/6/cam4","frame_ids":[439,440,441,442,443,444,445,446]} +{"filtered_tile_id":"1f784267c3a25a8396441340:8","filtered_window_id":"1f784267c3a25a8396441340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f784267c3a25a8396441340/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[447,448,449,450,451,452,453,454],"take":"subject2/k2/6/cam4","frame_ids":[447,448,449,450,451,452,453,454]} +{"filtered_tile_id":"1f784267c3a25a8396441340:16","filtered_window_id":"1f784267c3a25a8396441340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f784267c3a25a8396441340/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[455,456,457,458,459,460,461,462],"take":"subject2/k2/6/cam4","frame_ids":[455,456,457,458,459,460,461,462]} +{"filtered_tile_id":"1f784267c3a25a8396441340:24","filtered_window_id":"1f784267c3a25a8396441340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f784267c3a25a8396441340/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject2/k2/6/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"1f784267c3a25a8396441340:32","filtered_window_id":"1f784267c3a25a8396441340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f784267c3a25a8396441340/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[471,472,473,474,475,476,477,478],"take":"subject2/k2/6/cam4","frame_ids":[471,472,473,474,475,476,477,478]} +{"filtered_tile_id":"1f784267c3a25a8396441340:40","filtered_window_id":"1f784267c3a25a8396441340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f784267c3a25a8396441340/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[479,480,481,482,483,484,485,486],"take":"subject2/k2/6/cam4","frame_ids":[479,480,481,482,483,484,485,486]} +{"filtered_tile_id":"1f784267c3a25a8396441340:48","filtered_window_id":"1f784267c3a25a8396441340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f784267c3a25a8396441340/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject2/k2/6/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"1f784267c3a25a8396441340:52","filtered_window_id":"1f784267c3a25a8396441340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1f784267c3a25a8396441340/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[491,492,493,494,495,496,497,498],"take":"subject2/k2/6/cam4","frame_ids":[491,492,493,494,495,496,497,498]} +{"filtered_tile_id":"1fb58a169f16645294ba375d:0","filtered_window_id":"1fb58a169f16645294ba375d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fb58a169f16645294ba375d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[635,636,637,638,639,640,641,642],"take":"subject1/k2/6/cam4","frame_ids":[635,636,637,638,639,640,641,642]} +{"filtered_tile_id":"1fb58a169f16645294ba375d:8","filtered_window_id":"1fb58a169f16645294ba375d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fb58a169f16645294ba375d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[643,644,645,646,647,648,649,650],"take":"subject1/k2/6/cam4","frame_ids":[643,644,645,646,647,648,649,650]} +{"filtered_tile_id":"1fb58a169f16645294ba375d:9","filtered_window_id":"1fb58a169f16645294ba375d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fb58a169f16645294ba375d/native_gt.npz","filtered_start_offset":9,"expected_frame_ids":[644,645,646,647,648,649,650,651],"take":"subject1/k2/6/cam4","frame_ids":[644,645,646,647,648,649,650,651]} +{"filtered_tile_id":"1fc15745f6d7ff9de8a313fe:0","filtered_window_id":"1fc15745f6d7ff9de8a313fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fc15745f6d7ff9de8a313fe/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o1/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"1fc15745f6d7ff9de8a313fe:8","filtered_window_id":"1fc15745f6d7ff9de8a313fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fc15745f6d7ff9de8a313fe/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o1/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"1fc15745f6d7ff9de8a313fe:16","filtered_window_id":"1fc15745f6d7ff9de8a313fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fc15745f6d7ff9de8a313fe/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o1/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"1fc15745f6d7ff9de8a313fe:24","filtered_window_id":"1fc15745f6d7ff9de8a313fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fc15745f6d7ff9de8a313fe/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o1/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"1fc15745f6d7ff9de8a313fe:32","filtered_window_id":"1fc15745f6d7ff9de8a313fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fc15745f6d7ff9de8a313fe/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o1/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"1fc15745f6d7ff9de8a313fe:40","filtered_window_id":"1fc15745f6d7ff9de8a313fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fc15745f6d7ff9de8a313fe/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/o1/1/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"1fc15745f6d7ff9de8a313fe:48","filtered_window_id":"1fc15745f6d7ff9de8a313fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fc15745f6d7ff9de8a313fe/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/o1/1/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"1fc15745f6d7ff9de8a313fe:49","filtered_window_id":"1fc15745f6d7ff9de8a313fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fc15745f6d7ff9de8a313fe/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[49,50,51,52,53,54,55,56],"take":"subject1/o1/1/cam4","frame_ids":[49,50,51,52,53,54,55,56]} +{"filtered_tile_id":"1fd111a34989df7bb11bc915:0","filtered_window_id":"1fd111a34989df7bb11bc915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fd111a34989df7bb11bc915/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject2/h1/2/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"1fd111a34989df7bb11bc915:8","filtered_window_id":"1fd111a34989df7bb11bc915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fd111a34989df7bb11bc915/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject2/h1/2/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"1fd111a34989df7bb11bc915:16","filtered_window_id":"1fd111a34989df7bb11bc915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fd111a34989df7bb11bc915/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject2/h1/2/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"1fd111a34989df7bb11bc915:24","filtered_window_id":"1fd111a34989df7bb11bc915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fd111a34989df7bb11bc915/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject2/h1/2/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"1fd111a34989df7bb11bc915:32","filtered_window_id":"1fd111a34989df7bb11bc915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fd111a34989df7bb11bc915/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject2/h1/2/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"1fd111a34989df7bb11bc915:40","filtered_window_id":"1fd111a34989df7bb11bc915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fd111a34989df7bb11bc915/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject2/h1/2/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"1fd111a34989df7bb11bc915:48","filtered_window_id":"1fd111a34989df7bb11bc915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fd111a34989df7bb11bc915/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[536,537,538,539,540,541,542,543],"take":"subject2/h1/2/cam4","frame_ids":[536,537,538,539,540,541,542,543]} +{"filtered_tile_id":"1fd111a34989df7bb11bc915:52","filtered_window_id":"1fd111a34989df7bb11bc915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/1fd111a34989df7bb11bc915/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[540,541,542,543,544,545,546,547],"take":"subject2/h1/2/cam4","frame_ids":[540,541,542,543,544,545,546,547]} +{"filtered_tile_id":"2070114bc654e99ac7dd7c53:0","filtered_window_id":"2070114bc654e99ac7dd7c53","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2070114bc654e99ac7dd7c53/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject2/o1/6/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"2070114bc654e99ac7dd7c53:8","filtered_window_id":"2070114bc654e99ac7dd7c53","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2070114bc654e99ac7dd7c53/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject2/o1/6/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"2070114bc654e99ac7dd7c53:16","filtered_window_id":"2070114bc654e99ac7dd7c53","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2070114bc654e99ac7dd7c53/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject2/o1/6/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"2070114bc654e99ac7dd7c53:24","filtered_window_id":"2070114bc654e99ac7dd7c53","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2070114bc654e99ac7dd7c53/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject2/o1/6/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"2070114bc654e99ac7dd7c53:32","filtered_window_id":"2070114bc654e99ac7dd7c53","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2070114bc654e99ac7dd7c53/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject2/o1/6/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"2070114bc654e99ac7dd7c53:40","filtered_window_id":"2070114bc654e99ac7dd7c53","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2070114bc654e99ac7dd7c53/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject2/o1/6/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"2070114bc654e99ac7dd7c53:48","filtered_window_id":"2070114bc654e99ac7dd7c53","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2070114bc654e99ac7dd7c53/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject2/o1/6/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"2070114bc654e99ac7dd7c53:52","filtered_window_id":"2070114bc654e99ac7dd7c53","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2070114bc654e99ac7dd7c53/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject2/o1/6/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"20763fb237fa80b77c70489b:0","filtered_window_id":"20763fb237fa80b77c70489b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20763fb237fa80b77c70489b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject1/o1/5/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"20a90ce32d3bab3d7e170e4b:0","filtered_window_id":"20a90ce32d3bab3d7e170e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20a90ce32d3bab3d7e170e4b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject3/h1/3/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"20a90ce32d3bab3d7e170e4b:8","filtered_window_id":"20a90ce32d3bab3d7e170e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20a90ce32d3bab3d7e170e4b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject3/h1/3/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"20a90ce32d3bab3d7e170e4b:16","filtered_window_id":"20a90ce32d3bab3d7e170e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20a90ce32d3bab3d7e170e4b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject3/h1/3/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"20a90ce32d3bab3d7e170e4b:24","filtered_window_id":"20a90ce32d3bab3d7e170e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20a90ce32d3bab3d7e170e4b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject3/h1/3/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"20a90ce32d3bab3d7e170e4b:32","filtered_window_id":"20a90ce32d3bab3d7e170e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20a90ce32d3bab3d7e170e4b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject3/h1/3/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"20a90ce32d3bab3d7e170e4b:40","filtered_window_id":"20a90ce32d3bab3d7e170e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20a90ce32d3bab3d7e170e4b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[296,297,298,299,300,301,302,303],"take":"subject3/h1/3/cam4","frame_ids":[296,297,298,299,300,301,302,303]} +{"filtered_tile_id":"20a90ce32d3bab3d7e170e4b:48","filtered_window_id":"20a90ce32d3bab3d7e170e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20a90ce32d3bab3d7e170e4b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[304,305,306,307,308,309,310,311],"take":"subject3/h1/3/cam4","frame_ids":[304,305,306,307,308,309,310,311]} +{"filtered_tile_id":"20a90ce32d3bab3d7e170e4b:52","filtered_window_id":"20a90ce32d3bab3d7e170e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20a90ce32d3bab3d7e170e4b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject3/h1/3/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"20cc1257560a1c0000cc28db:0","filtered_window_id":"20cc1257560a1c0000cc28db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20cc1257560a1c0000cc28db/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject3/k1/2/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"20cc1257560a1c0000cc28db:8","filtered_window_id":"20cc1257560a1c0000cc28db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20cc1257560a1c0000cc28db/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject3/k1/2/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"20cc1257560a1c0000cc28db:16","filtered_window_id":"20cc1257560a1c0000cc28db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20cc1257560a1c0000cc28db/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject3/k1/2/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"20cc1257560a1c0000cc28db:24","filtered_window_id":"20cc1257560a1c0000cc28db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20cc1257560a1c0000cc28db/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject3/k1/2/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"20cc1257560a1c0000cc28db:32","filtered_window_id":"20cc1257560a1c0000cc28db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20cc1257560a1c0000cc28db/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[192,193,194,195,196,197,198,199],"take":"subject3/k1/2/cam4","frame_ids":[192,193,194,195,196,197,198,199]} +{"filtered_tile_id":"20cc1257560a1c0000cc28db:40","filtered_window_id":"20cc1257560a1c0000cc28db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20cc1257560a1c0000cc28db/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[200,201,202,203,204,205,206,207],"take":"subject3/k1/2/cam4","frame_ids":[200,201,202,203,204,205,206,207]} +{"filtered_tile_id":"20cc1257560a1c0000cc28db:48","filtered_window_id":"20cc1257560a1c0000cc28db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20cc1257560a1c0000cc28db/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[208,209,210,211,212,213,214,215],"take":"subject3/k1/2/cam4","frame_ids":[208,209,210,211,212,213,214,215]} +{"filtered_tile_id":"20cc1257560a1c0000cc28db:52","filtered_window_id":"20cc1257560a1c0000cc28db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/20cc1257560a1c0000cc28db/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject3/k1/2/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"21613389c58f989e5d7a3eb4:0","filtered_window_id":"21613389c58f989e5d7a3eb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21613389c58f989e5d7a3eb4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[540,541,542,543,544,545,546,547],"take":"subject1/k1/3/cam4","frame_ids":[540,541,542,543,544,545,546,547]} +{"filtered_tile_id":"21613389c58f989e5d7a3eb4:8","filtered_window_id":"21613389c58f989e5d7a3eb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21613389c58f989e5d7a3eb4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject1/k1/3/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"21613389c58f989e5d7a3eb4:16","filtered_window_id":"21613389c58f989e5d7a3eb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21613389c58f989e5d7a3eb4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject1/k1/3/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"21613389c58f989e5d7a3eb4:24","filtered_window_id":"21613389c58f989e5d7a3eb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21613389c58f989e5d7a3eb4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject1/k1/3/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"21613389c58f989e5d7a3eb4:32","filtered_window_id":"21613389c58f989e5d7a3eb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21613389c58f989e5d7a3eb4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[572,573,574,575,576,577,578,579],"take":"subject1/k1/3/cam4","frame_ids":[572,573,574,575,576,577,578,579]} +{"filtered_tile_id":"21613389c58f989e5d7a3eb4:40","filtered_window_id":"21613389c58f989e5d7a3eb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21613389c58f989e5d7a3eb4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[580,581,582,583,584,585,586,587],"take":"subject1/k1/3/cam4","frame_ids":[580,581,582,583,584,585,586,587]} +{"filtered_tile_id":"21613389c58f989e5d7a3eb4:48","filtered_window_id":"21613389c58f989e5d7a3eb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21613389c58f989e5d7a3eb4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[588,589,590,591,592,593,594,595],"take":"subject1/k1/3/cam4","frame_ids":[588,589,590,591,592,593,594,595]} +{"filtered_tile_id":"21613389c58f989e5d7a3eb4:52","filtered_window_id":"21613389c58f989e5d7a3eb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21613389c58f989e5d7a3eb4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[592,593,594,595,596,597,598,599],"take":"subject1/k1/3/cam4","frame_ids":[592,593,594,595,596,597,598,599]} +{"filtered_tile_id":"2165ae07dec3fec7d917d255:0","filtered_window_id":"2165ae07dec3fec7d917d255","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2165ae07dec3fec7d917d255/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[136,137,138,139,140,141,142,143],"take":"subject1/k1/0/cam4","frame_ids":[136,137,138,139,140,141,142,143]} +{"filtered_tile_id":"2165ae07dec3fec7d917d255:8","filtered_window_id":"2165ae07dec3fec7d917d255","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2165ae07dec3fec7d917d255/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[144,145,146,147,148,149,150,151],"take":"subject1/k1/0/cam4","frame_ids":[144,145,146,147,148,149,150,151]} +{"filtered_tile_id":"2165ae07dec3fec7d917d255:16","filtered_window_id":"2165ae07dec3fec7d917d255","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2165ae07dec3fec7d917d255/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject1/k1/0/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"2165ae07dec3fec7d917d255:24","filtered_window_id":"2165ae07dec3fec7d917d255","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2165ae07dec3fec7d917d255/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject1/k1/0/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"2165ae07dec3fec7d917d255:32","filtered_window_id":"2165ae07dec3fec7d917d255","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2165ae07dec3fec7d917d255/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject1/k1/0/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"2165ae07dec3fec7d917d255:40","filtered_window_id":"2165ae07dec3fec7d917d255","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2165ae07dec3fec7d917d255/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject1/k1/0/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"2165ae07dec3fec7d917d255:48","filtered_window_id":"2165ae07dec3fec7d917d255","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2165ae07dec3fec7d917d255/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject1/k1/0/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"2165ae07dec3fec7d917d255:52","filtered_window_id":"2165ae07dec3fec7d917d255","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2165ae07dec3fec7d917d255/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject1/k1/0/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"219d4fe050db6520377293a5:0","filtered_window_id":"219d4fe050db6520377293a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/219d4fe050db6520377293a5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject1/k2/5/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"219d4fe050db6520377293a5:8","filtered_window_id":"219d4fe050db6520377293a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/219d4fe050db6520377293a5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject1/k2/5/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"219d4fe050db6520377293a5:16","filtered_window_id":"219d4fe050db6520377293a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/219d4fe050db6520377293a5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject1/k2/5/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"219d4fe050db6520377293a5:24","filtered_window_id":"219d4fe050db6520377293a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/219d4fe050db6520377293a5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject1/k2/5/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"219d4fe050db6520377293a5:32","filtered_window_id":"219d4fe050db6520377293a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/219d4fe050db6520377293a5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject1/k2/5/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"219d4fe050db6520377293a5:40","filtered_window_id":"219d4fe050db6520377293a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/219d4fe050db6520377293a5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject1/k2/5/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"219d4fe050db6520377293a5:48","filtered_window_id":"219d4fe050db6520377293a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/219d4fe050db6520377293a5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject1/k2/5/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"219d4fe050db6520377293a5:50","filtered_window_id":"219d4fe050db6520377293a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/219d4fe050db6520377293a5/native_gt.npz","filtered_start_offset":50,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject1/k2/5/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"21e4a88169875fa885addf4a:0","filtered_window_id":"21e4a88169875fa885addf4a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21e4a88169875fa885addf4a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject1/k2/1/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"21e4a88169875fa885addf4a:8","filtered_window_id":"21e4a88169875fa885addf4a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21e4a88169875fa885addf4a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject1/k2/1/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"21e4a88169875fa885addf4a:16","filtered_window_id":"21e4a88169875fa885addf4a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21e4a88169875fa885addf4a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject1/k2/1/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"21e4a88169875fa885addf4a:24","filtered_window_id":"21e4a88169875fa885addf4a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21e4a88169875fa885addf4a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject1/k2/1/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"21e4a88169875fa885addf4a:32","filtered_window_id":"21e4a88169875fa885addf4a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21e4a88169875fa885addf4a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject1/k2/1/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"21e4a88169875fa885addf4a:40","filtered_window_id":"21e4a88169875fa885addf4a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21e4a88169875fa885addf4a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject1/k2/1/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"21e4a88169875fa885addf4a:48","filtered_window_id":"21e4a88169875fa885addf4a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21e4a88169875fa885addf4a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[526,527,528,529,530,531,532,533],"take":"subject1/k2/1/cam4","frame_ids":[526,527,528,529,530,531,532,533]} +{"filtered_tile_id":"21e4a88169875fa885addf4a:52","filtered_window_id":"21e4a88169875fa885addf4a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/21e4a88169875fa885addf4a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[530,531,532,533,534,535,536,537],"take":"subject1/k2/1/cam4","frame_ids":[530,531,532,533,534,535,536,537]} +{"filtered_tile_id":"2262d01d837cddbb932108db:0","filtered_window_id":"2262d01d837cddbb932108db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2262d01d837cddbb932108db/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[126,127,128,129,130,131,132,133],"take":"subject2/o1/1/cam4","frame_ids":[126,127,128,129,130,131,132,133]} +{"filtered_tile_id":"2262d01d837cddbb932108db:8","filtered_window_id":"2262d01d837cddbb932108db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2262d01d837cddbb932108db/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[134,135,136,137,138,139,140,141],"take":"subject2/o1/1/cam4","frame_ids":[134,135,136,137,138,139,140,141]} +{"filtered_tile_id":"2262d01d837cddbb932108db:16","filtered_window_id":"2262d01d837cddbb932108db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2262d01d837cddbb932108db/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[142,143,144,145,146,147,148,149],"take":"subject2/o1/1/cam4","frame_ids":[142,143,144,145,146,147,148,149]} +{"filtered_tile_id":"2262d01d837cddbb932108db:24","filtered_window_id":"2262d01d837cddbb932108db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2262d01d837cddbb932108db/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[150,151,152,153,154,155,156,157],"take":"subject2/o1/1/cam4","frame_ids":[150,151,152,153,154,155,156,157]} +{"filtered_tile_id":"2262d01d837cddbb932108db:32","filtered_window_id":"2262d01d837cddbb932108db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2262d01d837cddbb932108db/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[158,159,160,161,162,163,164,165],"take":"subject2/o1/1/cam4","frame_ids":[158,159,160,161,162,163,164,165]} +{"filtered_tile_id":"2262d01d837cddbb932108db:40","filtered_window_id":"2262d01d837cddbb932108db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2262d01d837cddbb932108db/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject2/o1/1/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"2262d01d837cddbb932108db:48","filtered_window_id":"2262d01d837cddbb932108db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2262d01d837cddbb932108db/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject2/o1/1/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"2262d01d837cddbb932108db:52","filtered_window_id":"2262d01d837cddbb932108db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2262d01d837cddbb932108db/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[178,179,180,181,182,183,184,185],"take":"subject2/o1/1/cam4","frame_ids":[178,179,180,181,182,183,184,185]} +{"filtered_tile_id":"2272cc5590d45320d8b311fd:0","filtered_window_id":"2272cc5590d45320d8b311fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2272cc5590d45320d8b311fd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[6,7,8,9,10,11,12,13],"take":"subject3/k1/7/cam4","frame_ids":[6,7,8,9,10,11,12,13]} +{"filtered_tile_id":"2272cc5590d45320d8b311fd:8","filtered_window_id":"2272cc5590d45320d8b311fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2272cc5590d45320d8b311fd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[14,15,16,17,18,19,20,21],"take":"subject3/k1/7/cam4","frame_ids":[14,15,16,17,18,19,20,21]} +{"filtered_tile_id":"2272cc5590d45320d8b311fd:16","filtered_window_id":"2272cc5590d45320d8b311fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2272cc5590d45320d8b311fd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[22,23,24,25,26,27,28,29],"take":"subject3/k1/7/cam4","frame_ids":[22,23,24,25,26,27,28,29]} +{"filtered_tile_id":"2272cc5590d45320d8b311fd:24","filtered_window_id":"2272cc5590d45320d8b311fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2272cc5590d45320d8b311fd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[30,31,32,33,34,35,36,37],"take":"subject3/k1/7/cam4","frame_ids":[30,31,32,33,34,35,36,37]} +{"filtered_tile_id":"2272cc5590d45320d8b311fd:32","filtered_window_id":"2272cc5590d45320d8b311fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2272cc5590d45320d8b311fd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[38,39,40,41,42,43,44,45],"take":"subject3/k1/7/cam4","frame_ids":[38,39,40,41,42,43,44,45]} +{"filtered_tile_id":"2272cc5590d45320d8b311fd:40","filtered_window_id":"2272cc5590d45320d8b311fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2272cc5590d45320d8b311fd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[46,47,48,49,50,51,52,53],"take":"subject3/k1/7/cam4","frame_ids":[46,47,48,49,50,51,52,53]} +{"filtered_tile_id":"2272cc5590d45320d8b311fd:43","filtered_window_id":"2272cc5590d45320d8b311fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2272cc5590d45320d8b311fd/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[49,50,51,52,53,54,55,56],"take":"subject3/k1/7/cam4","frame_ids":[49,50,51,52,53,54,55,56]} +{"filtered_tile_id":"2287beec5f8e53e9a7b27532:0","filtered_window_id":"2287beec5f8e53e9a7b27532","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2287beec5f8e53e9a7b27532/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[526,527,528,529,530,531,532,533],"take":"subject1/o1/7/cam4","frame_ids":[526,527,528,529,530,531,532,533]} +{"filtered_tile_id":"2287beec5f8e53e9a7b27532:8","filtered_window_id":"2287beec5f8e53e9a7b27532","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2287beec5f8e53e9a7b27532/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[534,535,536,537,538,539,540,541],"take":"subject1/o1/7/cam4","frame_ids":[534,535,536,537,538,539,540,541]} +{"filtered_tile_id":"2287beec5f8e53e9a7b27532:16","filtered_window_id":"2287beec5f8e53e9a7b27532","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2287beec5f8e53e9a7b27532/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[542,543,544,545,546,547,548,549],"take":"subject1/o1/7/cam4","frame_ids":[542,543,544,545,546,547,548,549]} +{"filtered_tile_id":"2287beec5f8e53e9a7b27532:24","filtered_window_id":"2287beec5f8e53e9a7b27532","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2287beec5f8e53e9a7b27532/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[550,551,552,553,554,555,556,557],"take":"subject1/o1/7/cam4","frame_ids":[550,551,552,553,554,555,556,557]} +{"filtered_tile_id":"2287beec5f8e53e9a7b27532:32","filtered_window_id":"2287beec5f8e53e9a7b27532","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2287beec5f8e53e9a7b27532/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[558,559,560,561,562,563,564,565],"take":"subject1/o1/7/cam4","frame_ids":[558,559,560,561,562,563,564,565]} +{"filtered_tile_id":"2287beec5f8e53e9a7b27532:40","filtered_window_id":"2287beec5f8e53e9a7b27532","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2287beec5f8e53e9a7b27532/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[566,567,568,569,570,571,572,573],"take":"subject1/o1/7/cam4","frame_ids":[566,567,568,569,570,571,572,573]} +{"filtered_tile_id":"2287beec5f8e53e9a7b27532:48","filtered_window_id":"2287beec5f8e53e9a7b27532","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2287beec5f8e53e9a7b27532/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[574,575,576,577,578,579,580,581],"take":"subject1/o1/7/cam4","frame_ids":[574,575,576,577,578,579,580,581]} +{"filtered_tile_id":"2287beec5f8e53e9a7b27532:52","filtered_window_id":"2287beec5f8e53e9a7b27532","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2287beec5f8e53e9a7b27532/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[578,579,580,581,582,583,584,585],"take":"subject1/o1/7/cam4","frame_ids":[578,579,580,581,582,583,584,585]} +{"filtered_tile_id":"22af7ad212e3e3ba4e519d5e:0","filtered_window_id":"22af7ad212e3e3ba4e519d5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/22af7ad212e3e3ba4e519d5e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[688,689,690,691,692,693,694,695],"take":"subject2/h2/4/cam4","frame_ids":[688,689,690,691,692,693,694,695]} +{"filtered_tile_id":"22af7ad212e3e3ba4e519d5e:8","filtered_window_id":"22af7ad212e3e3ba4e519d5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/22af7ad212e3e3ba4e519d5e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[696,697,698,699,700,701,702,703],"take":"subject2/h2/4/cam4","frame_ids":[696,697,698,699,700,701,702,703]} +{"filtered_tile_id":"22af7ad212e3e3ba4e519d5e:16","filtered_window_id":"22af7ad212e3e3ba4e519d5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/22af7ad212e3e3ba4e519d5e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[704,705,706,707,708,709,710,711],"take":"subject2/h2/4/cam4","frame_ids":[704,705,706,707,708,709,710,711]} +{"filtered_tile_id":"22af7ad212e3e3ba4e519d5e:24","filtered_window_id":"22af7ad212e3e3ba4e519d5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/22af7ad212e3e3ba4e519d5e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[712,713,714,715,716,717,718,719],"take":"subject2/h2/4/cam4","frame_ids":[712,713,714,715,716,717,718,719]} +{"filtered_tile_id":"22af7ad212e3e3ba4e519d5e:32","filtered_window_id":"22af7ad212e3e3ba4e519d5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/22af7ad212e3e3ba4e519d5e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[720,721,722,723,724,725,726,727],"take":"subject2/h2/4/cam4","frame_ids":[720,721,722,723,724,725,726,727]} +{"filtered_tile_id":"22af7ad212e3e3ba4e519d5e:40","filtered_window_id":"22af7ad212e3e3ba4e519d5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/22af7ad212e3e3ba4e519d5e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[728,729,730,731,732,733,734,735],"take":"subject2/h2/4/cam4","frame_ids":[728,729,730,731,732,733,734,735]} +{"filtered_tile_id":"22af7ad212e3e3ba4e519d5e:48","filtered_window_id":"22af7ad212e3e3ba4e519d5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/22af7ad212e3e3ba4e519d5e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[736,737,738,739,740,741,742,743],"take":"subject2/h2/4/cam4","frame_ids":[736,737,738,739,740,741,742,743]} +{"filtered_tile_id":"22af7ad212e3e3ba4e519d5e:52","filtered_window_id":"22af7ad212e3e3ba4e519d5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/22af7ad212e3e3ba4e519d5e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[740,741,742,743,744,745,746,747],"take":"subject2/h2/4/cam4","frame_ids":[740,741,742,743,744,745,746,747]} +{"filtered_tile_id":"23138660dc42486b9033a4ce:0","filtered_window_id":"23138660dc42486b9033a4ce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23138660dc42486b9033a4ce/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[80,81,82,83,84,85,86,87],"take":"subject1/o1/2/cam4","frame_ids":[80,81,82,83,84,85,86,87]} +{"filtered_tile_id":"23138660dc42486b9033a4ce:8","filtered_window_id":"23138660dc42486b9033a4ce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23138660dc42486b9033a4ce/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject1/o1/2/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"23138660dc42486b9033a4ce:16","filtered_window_id":"23138660dc42486b9033a4ce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23138660dc42486b9033a4ce/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject1/o1/2/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"23138660dc42486b9033a4ce:24","filtered_window_id":"23138660dc42486b9033a4ce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23138660dc42486b9033a4ce/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[104,105,106,107,108,109,110,111],"take":"subject1/o1/2/cam4","frame_ids":[104,105,106,107,108,109,110,111]} +{"filtered_tile_id":"23138660dc42486b9033a4ce:32","filtered_window_id":"23138660dc42486b9033a4ce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23138660dc42486b9033a4ce/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[112,113,114,115,116,117,118,119],"take":"subject1/o1/2/cam4","frame_ids":[112,113,114,115,116,117,118,119]} +{"filtered_tile_id":"23138660dc42486b9033a4ce:40","filtered_window_id":"23138660dc42486b9033a4ce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23138660dc42486b9033a4ce/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[120,121,122,123,124,125,126,127],"take":"subject1/o1/2/cam4","frame_ids":[120,121,122,123,124,125,126,127]} +{"filtered_tile_id":"23138660dc42486b9033a4ce:48","filtered_window_id":"23138660dc42486b9033a4ce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23138660dc42486b9033a4ce/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[128,129,130,131,132,133,134,135],"take":"subject1/o1/2/cam4","frame_ids":[128,129,130,131,132,133,134,135]} +{"filtered_tile_id":"23138660dc42486b9033a4ce:52","filtered_window_id":"23138660dc42486b9033a4ce","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23138660dc42486b9033a4ce/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject1/o1/2/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"238e2cadcd29dd4cb5f2e20c:0","filtered_window_id":"238e2cadcd29dd4cb5f2e20c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/238e2cadcd29dd4cb5f2e20c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[294,295,296,297,298,299,300,301],"take":"subject1/h2/3/cam4","frame_ids":[294,295,296,297,298,299,300,301]} +{"filtered_tile_id":"238e2cadcd29dd4cb5f2e20c:8","filtered_window_id":"238e2cadcd29dd4cb5f2e20c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/238e2cadcd29dd4cb5f2e20c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[302,303,304,305,306,307,308,309],"take":"subject1/h2/3/cam4","frame_ids":[302,303,304,305,306,307,308,309]} +{"filtered_tile_id":"238e2cadcd29dd4cb5f2e20c:16","filtered_window_id":"238e2cadcd29dd4cb5f2e20c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/238e2cadcd29dd4cb5f2e20c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject1/h2/3/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"238e2cadcd29dd4cb5f2e20c:24","filtered_window_id":"238e2cadcd29dd4cb5f2e20c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/238e2cadcd29dd4cb5f2e20c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject1/h2/3/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"238e2cadcd29dd4cb5f2e20c:32","filtered_window_id":"238e2cadcd29dd4cb5f2e20c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/238e2cadcd29dd4cb5f2e20c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject1/h2/3/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"238e2cadcd29dd4cb5f2e20c:40","filtered_window_id":"238e2cadcd29dd4cb5f2e20c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/238e2cadcd29dd4cb5f2e20c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject1/h2/3/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"238e2cadcd29dd4cb5f2e20c:48","filtered_window_id":"238e2cadcd29dd4cb5f2e20c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/238e2cadcd29dd4cb5f2e20c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject1/h2/3/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"238e2cadcd29dd4cb5f2e20c:52","filtered_window_id":"238e2cadcd29dd4cb5f2e20c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/238e2cadcd29dd4cb5f2e20c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject1/h2/3/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"23d86083ae001d99a74b059a:0","filtered_window_id":"23d86083ae001d99a74b059a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23d86083ae001d99a74b059a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[21,22,23,24,25,26,27,28],"take":"subject2/k1/2/cam4","frame_ids":[21,22,23,24,25,26,27,28]} +{"filtered_tile_id":"23d86083ae001d99a74b059a:8","filtered_window_id":"23d86083ae001d99a74b059a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23d86083ae001d99a74b059a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[29,30,31,32,33,34,35,36],"take":"subject2/k1/2/cam4","frame_ids":[29,30,31,32,33,34,35,36]} +{"filtered_tile_id":"23d86083ae001d99a74b059a:16","filtered_window_id":"23d86083ae001d99a74b059a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23d86083ae001d99a74b059a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject2/k1/2/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"23d86083ae001d99a74b059a:24","filtered_window_id":"23d86083ae001d99a74b059a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23d86083ae001d99a74b059a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject2/k1/2/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"23d86083ae001d99a74b059a:32","filtered_window_id":"23d86083ae001d99a74b059a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23d86083ae001d99a74b059a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[53,54,55,56,57,58,59,60],"take":"subject2/k1/2/cam4","frame_ids":[53,54,55,56,57,58,59,60]} +{"filtered_tile_id":"23d86083ae001d99a74b059a:40","filtered_window_id":"23d86083ae001d99a74b059a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23d86083ae001d99a74b059a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[61,62,63,64,65,66,67,68],"take":"subject2/k1/2/cam4","frame_ids":[61,62,63,64,65,66,67,68]} +{"filtered_tile_id":"23d86083ae001d99a74b059a:48","filtered_window_id":"23d86083ae001d99a74b059a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23d86083ae001d99a74b059a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject2/k1/2/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"23d86083ae001d99a74b059a:52","filtered_window_id":"23d86083ae001d99a74b059a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23d86083ae001d99a74b059a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[73,74,75,76,77,78,79,80],"take":"subject2/k1/2/cam4","frame_ids":[73,74,75,76,77,78,79,80]} +{"filtered_tile_id":"23fd1c7b12d20d00f2881ea1:0","filtered_window_id":"23fd1c7b12d20d00f2881ea1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23fd1c7b12d20d00f2881ea1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[438,439,440,441,442,443,444,445],"take":"subject3/k1/2/cam4","frame_ids":[438,439,440,441,442,443,444,445]} +{"filtered_tile_id":"23fd1c7b12d20d00f2881ea1:8","filtered_window_id":"23fd1c7b12d20d00f2881ea1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23fd1c7b12d20d00f2881ea1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[446,447,448,449,450,451,452,453],"take":"subject3/k1/2/cam4","frame_ids":[446,447,448,449,450,451,452,453]} +{"filtered_tile_id":"23fd1c7b12d20d00f2881ea1:16","filtered_window_id":"23fd1c7b12d20d00f2881ea1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23fd1c7b12d20d00f2881ea1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[454,455,456,457,458,459,460,461],"take":"subject3/k1/2/cam4","frame_ids":[454,455,456,457,458,459,460,461]} +{"filtered_tile_id":"23fd1c7b12d20d00f2881ea1:24","filtered_window_id":"23fd1c7b12d20d00f2881ea1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23fd1c7b12d20d00f2881ea1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject3/k1/2/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"23fd1c7b12d20d00f2881ea1:32","filtered_window_id":"23fd1c7b12d20d00f2881ea1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23fd1c7b12d20d00f2881ea1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject3/k1/2/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"23fd1c7b12d20d00f2881ea1:40","filtered_window_id":"23fd1c7b12d20d00f2881ea1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23fd1c7b12d20d00f2881ea1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject3/k1/2/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"23fd1c7b12d20d00f2881ea1:48","filtered_window_id":"23fd1c7b12d20d00f2881ea1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23fd1c7b12d20d00f2881ea1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject3/k1/2/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"23fd1c7b12d20d00f2881ea1:52","filtered_window_id":"23fd1c7b12d20d00f2881ea1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/23fd1c7b12d20d00f2881ea1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[490,491,492,493,494,495,496,497],"take":"subject3/k1/2/cam4","frame_ids":[490,491,492,493,494,495,496,497]} +{"filtered_tile_id":"241c4789ab208d8d58b9b30c:0","filtered_window_id":"241c4789ab208d8d58b9b30c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/241c4789ab208d8d58b9b30c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[73,74,75,76,77,78,79,80],"take":"subject2/k1/0/cam4","frame_ids":[73,74,75,76,77,78,79,80]} +{"filtered_tile_id":"241ec367e677298677fa8c09:0","filtered_window_id":"241ec367e677298677fa8c09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/241ec367e677298677fa8c09/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject3/h1/5/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"241ec367e677298677fa8c09:8","filtered_window_id":"241ec367e677298677fa8c09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/241ec367e677298677fa8c09/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject3/h1/5/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"241ec367e677298677fa8c09:16","filtered_window_id":"241ec367e677298677fa8c09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/241ec367e677298677fa8c09/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject3/h1/5/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"241ec367e677298677fa8c09:24","filtered_window_id":"241ec367e677298677fa8c09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/241ec367e677298677fa8c09/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject3/h1/5/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"241ec367e677298677fa8c09:32","filtered_window_id":"241ec367e677298677fa8c09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/241ec367e677298677fa8c09/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject3/h1/5/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"241ec367e677298677fa8c09:40","filtered_window_id":"241ec367e677298677fa8c09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/241ec367e677298677fa8c09/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject3/h1/5/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"241ec367e677298677fa8c09:48","filtered_window_id":"241ec367e677298677fa8c09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/241ec367e677298677fa8c09/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject3/h1/5/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"241ec367e677298677fa8c09:52","filtered_window_id":"241ec367e677298677fa8c09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/241ec367e677298677fa8c09/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject3/h1/5/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"24653ac78582c0dd34bdd53b:0","filtered_window_id":"24653ac78582c0dd34bdd53b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24653ac78582c0dd34bdd53b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject3/h1/7/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"24653ac78582c0dd34bdd53b:8","filtered_window_id":"24653ac78582c0dd34bdd53b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24653ac78582c0dd34bdd53b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject3/h1/7/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"24653ac78582c0dd34bdd53b:16","filtered_window_id":"24653ac78582c0dd34bdd53b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24653ac78582c0dd34bdd53b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject3/h1/7/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"24653ac78582c0dd34bdd53b:24","filtered_window_id":"24653ac78582c0dd34bdd53b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24653ac78582c0dd34bdd53b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject3/h1/7/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"24653ac78582c0dd34bdd53b:32","filtered_window_id":"24653ac78582c0dd34bdd53b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24653ac78582c0dd34bdd53b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject3/h1/7/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"24653ac78582c0dd34bdd53b:40","filtered_window_id":"24653ac78582c0dd34bdd53b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24653ac78582c0dd34bdd53b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject3/h1/7/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"24653ac78582c0dd34bdd53b:48","filtered_window_id":"24653ac78582c0dd34bdd53b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24653ac78582c0dd34bdd53b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject3/h1/7/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"24653ac78582c0dd34bdd53b:52","filtered_window_id":"24653ac78582c0dd34bdd53b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24653ac78582c0dd34bdd53b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject3/h1/7/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"248dc1fd08c32553202e6f5b:0","filtered_window_id":"248dc1fd08c32553202e6f5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/248dc1fd08c32553202e6f5b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[711,712,713,714,715,716,717,718],"take":"subject3/k1/3/cam4","frame_ids":[711,712,713,714,715,716,717,718]} +{"filtered_tile_id":"248dc1fd08c32553202e6f5b:8","filtered_window_id":"248dc1fd08c32553202e6f5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/248dc1fd08c32553202e6f5b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[719,720,721,722,723,724,725,726],"take":"subject3/k1/3/cam4","frame_ids":[719,720,721,722,723,724,725,726]} +{"filtered_tile_id":"248dc1fd08c32553202e6f5b:16","filtered_window_id":"248dc1fd08c32553202e6f5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/248dc1fd08c32553202e6f5b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[727,728,729,730,731,732,733,734],"take":"subject3/k1/3/cam4","frame_ids":[727,728,729,730,731,732,733,734]} +{"filtered_tile_id":"248dc1fd08c32553202e6f5b:24","filtered_window_id":"248dc1fd08c32553202e6f5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/248dc1fd08c32553202e6f5b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[735,736,737,738,739,740,741,742],"take":"subject3/k1/3/cam4","frame_ids":[735,736,737,738,739,740,741,742]} +{"filtered_tile_id":"248dc1fd08c32553202e6f5b:32","filtered_window_id":"248dc1fd08c32553202e6f5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/248dc1fd08c32553202e6f5b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[743,744,745,746,747,748,749,750],"take":"subject3/k1/3/cam4","frame_ids":[743,744,745,746,747,748,749,750]} +{"filtered_tile_id":"248dc1fd08c32553202e6f5b:40","filtered_window_id":"248dc1fd08c32553202e6f5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/248dc1fd08c32553202e6f5b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[751,752,753,754,755,756,757,758],"take":"subject3/k1/3/cam4","frame_ids":[751,752,753,754,755,756,757,758]} +{"filtered_tile_id":"248dc1fd08c32553202e6f5b:48","filtered_window_id":"248dc1fd08c32553202e6f5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/248dc1fd08c32553202e6f5b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[759,760,761,762,763,764,765,766],"take":"subject3/k1/3/cam4","frame_ids":[759,760,761,762,763,764,765,766]} +{"filtered_tile_id":"248dc1fd08c32553202e6f5b:52","filtered_window_id":"248dc1fd08c32553202e6f5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/248dc1fd08c32553202e6f5b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[763,764,765,766,767,768,769,770],"take":"subject3/k1/3/cam4","frame_ids":[763,764,765,766,767,768,769,770]} +{"filtered_tile_id":"2498f863a116dc5b34fd0236:0","filtered_window_id":"2498f863a116dc5b34fd0236","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2498f863a116dc5b34fd0236/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[292,293,294,295,296,297,298,299],"take":"subject2/h1/6/cam4","frame_ids":[292,293,294,295,296,297,298,299]} +{"filtered_tile_id":"2498f863a116dc5b34fd0236:8","filtered_window_id":"2498f863a116dc5b34fd0236","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2498f863a116dc5b34fd0236/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[300,301,302,303,304,305,306,307],"take":"subject2/h1/6/cam4","frame_ids":[300,301,302,303,304,305,306,307]} +{"filtered_tile_id":"2498f863a116dc5b34fd0236:16","filtered_window_id":"2498f863a116dc5b34fd0236","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2498f863a116dc5b34fd0236/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject2/h1/6/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"2498f863a116dc5b34fd0236:24","filtered_window_id":"2498f863a116dc5b34fd0236","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2498f863a116dc5b34fd0236/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[316,317,318,319,320,321,322,323],"take":"subject2/h1/6/cam4","frame_ids":[316,317,318,319,320,321,322,323]} +{"filtered_tile_id":"2498f863a116dc5b34fd0236:32","filtered_window_id":"2498f863a116dc5b34fd0236","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2498f863a116dc5b34fd0236/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject2/h1/6/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"2498f863a116dc5b34fd0236:40","filtered_window_id":"2498f863a116dc5b34fd0236","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2498f863a116dc5b34fd0236/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject2/h1/6/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"2498f863a116dc5b34fd0236:48","filtered_window_id":"2498f863a116dc5b34fd0236","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2498f863a116dc5b34fd0236/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[340,341,342,343,344,345,346,347],"take":"subject2/h1/6/cam4","frame_ids":[340,341,342,343,344,345,346,347]} +{"filtered_tile_id":"2498f863a116dc5b34fd0236:52","filtered_window_id":"2498f863a116dc5b34fd0236","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2498f863a116dc5b34fd0236/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[344,345,346,347,348,349,350,351],"take":"subject2/h1/6/cam4","frame_ids":[344,345,346,347,348,349,350,351]} +{"filtered_tile_id":"24f1a5fb97a24516c10810a5:0","filtered_window_id":"24f1a5fb97a24516c10810a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24f1a5fb97a24516c10810a5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/h2/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"24f1a5fb97a24516c10810a5:8","filtered_window_id":"24f1a5fb97a24516c10810a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24f1a5fb97a24516c10810a5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/h2/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"24f1a5fb97a24516c10810a5:16","filtered_window_id":"24f1a5fb97a24516c10810a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24f1a5fb97a24516c10810a5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/h2/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"24f1a5fb97a24516c10810a5:24","filtered_window_id":"24f1a5fb97a24516c10810a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24f1a5fb97a24516c10810a5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/h2/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"24f1a5fb97a24516c10810a5:32","filtered_window_id":"24f1a5fb97a24516c10810a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24f1a5fb97a24516c10810a5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/h2/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"24f1a5fb97a24516c10810a5:40","filtered_window_id":"24f1a5fb97a24516c10810a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24f1a5fb97a24516c10810a5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/h2/1/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"24f1a5fb97a24516c10810a5:48","filtered_window_id":"24f1a5fb97a24516c10810a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24f1a5fb97a24516c10810a5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/h2/1/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"24f1a5fb97a24516c10810a5:52","filtered_window_id":"24f1a5fb97a24516c10810a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/24f1a5fb97a24516c10810a5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/h2/1/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"2571a3ec1fffcb68addeb374:0","filtered_window_id":"2571a3ec1fffcb68addeb374","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2571a3ec1fffcb68addeb374/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject1/k1/3/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"2571a3ec1fffcb68addeb374:8","filtered_window_id":"2571a3ec1fffcb68addeb374","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2571a3ec1fffcb68addeb374/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject1/k1/3/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"2571a3ec1fffcb68addeb374:16","filtered_window_id":"2571a3ec1fffcb68addeb374","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2571a3ec1fffcb68addeb374/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject1/k1/3/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"2571a3ec1fffcb68addeb374:24","filtered_window_id":"2571a3ec1fffcb68addeb374","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2571a3ec1fffcb68addeb374/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject1/k1/3/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"2571a3ec1fffcb68addeb374:32","filtered_window_id":"2571a3ec1fffcb68addeb374","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2571a3ec1fffcb68addeb374/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject1/k1/3/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"2571a3ec1fffcb68addeb374:40","filtered_window_id":"2571a3ec1fffcb68addeb374","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2571a3ec1fffcb68addeb374/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject1/k1/3/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"2571a3ec1fffcb68addeb374:48","filtered_window_id":"2571a3ec1fffcb68addeb374","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2571a3ec1fffcb68addeb374/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject1/k1/3/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"2571a3ec1fffcb68addeb374:52","filtered_window_id":"2571a3ec1fffcb68addeb374","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2571a3ec1fffcb68addeb374/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject1/k1/3/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"25e4fe8bb32835ba033c6595:0","filtered_window_id":"25e4fe8bb32835ba033c6595","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25e4fe8bb32835ba033c6595/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject3/h1/7/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"25e4fe8bb32835ba033c6595:1","filtered_window_id":"25e4fe8bb32835ba033c6595","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25e4fe8bb32835ba033c6595/native_gt.npz","filtered_start_offset":1,"expected_frame_ids":[381,382,383,384,385,386,387,388],"take":"subject3/h1/7/cam4","frame_ids":[381,382,383,384,385,386,387,388]} +{"filtered_tile_id":"25f3df1c46fea69099f9bfcb:0","filtered_window_id":"25f3df1c46fea69099f9bfcb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25f3df1c46fea69099f9bfcb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/o1/4/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"25f3df1c46fea69099f9bfcb:8","filtered_window_id":"25f3df1c46fea69099f9bfcb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25f3df1c46fea69099f9bfcb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject1/o1/4/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"25f3df1c46fea69099f9bfcb:16","filtered_window_id":"25f3df1c46fea69099f9bfcb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25f3df1c46fea69099f9bfcb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject1/o1/4/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"25f3df1c46fea69099f9bfcb:24","filtered_window_id":"25f3df1c46fea69099f9bfcb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25f3df1c46fea69099f9bfcb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject1/o1/4/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"25f3df1c46fea69099f9bfcb:32","filtered_window_id":"25f3df1c46fea69099f9bfcb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25f3df1c46fea69099f9bfcb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject1/o1/4/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"25f3df1c46fea69099f9bfcb:40","filtered_window_id":"25f3df1c46fea69099f9bfcb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25f3df1c46fea69099f9bfcb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject1/o1/4/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"25f3df1c46fea69099f9bfcb:48","filtered_window_id":"25f3df1c46fea69099f9bfcb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25f3df1c46fea69099f9bfcb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[156,157,158,159,160,161,162,163],"take":"subject1/o1/4/cam4","frame_ids":[156,157,158,159,160,161,162,163]} +{"filtered_tile_id":"25f3df1c46fea69099f9bfcb:52","filtered_window_id":"25f3df1c46fea69099f9bfcb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/25f3df1c46fea69099f9bfcb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject1/o1/4/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"273f70397ab53562730ed538:0","filtered_window_id":"273f70397ab53562730ed538","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/273f70397ab53562730ed538/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[389,390,391,392,393,394,395,396],"take":"subject1/k1/6/cam4","frame_ids":[389,390,391,392,393,394,395,396]} +{"filtered_tile_id":"273f70397ab53562730ed538:8","filtered_window_id":"273f70397ab53562730ed538","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/273f70397ab53562730ed538/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[397,398,399,400,401,402,403,404],"take":"subject1/k1/6/cam4","frame_ids":[397,398,399,400,401,402,403,404]} +{"filtered_tile_id":"273f70397ab53562730ed538:16","filtered_window_id":"273f70397ab53562730ed538","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/273f70397ab53562730ed538/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[405,406,407,408,409,410,411,412],"take":"subject1/k1/6/cam4","frame_ids":[405,406,407,408,409,410,411,412]} +{"filtered_tile_id":"273f70397ab53562730ed538:24","filtered_window_id":"273f70397ab53562730ed538","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/273f70397ab53562730ed538/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[413,414,415,416,417,418,419,420],"take":"subject1/k1/6/cam4","frame_ids":[413,414,415,416,417,418,419,420]} +{"filtered_tile_id":"273f70397ab53562730ed538:32","filtered_window_id":"273f70397ab53562730ed538","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/273f70397ab53562730ed538/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[421,422,423,424,425,426,427,428],"take":"subject1/k1/6/cam4","frame_ids":[421,422,423,424,425,426,427,428]} +{"filtered_tile_id":"273f70397ab53562730ed538:40","filtered_window_id":"273f70397ab53562730ed538","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/273f70397ab53562730ed538/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[429,430,431,432,433,434,435,436],"take":"subject1/k1/6/cam4","frame_ids":[429,430,431,432,433,434,435,436]} +{"filtered_tile_id":"273f70397ab53562730ed538:48","filtered_window_id":"273f70397ab53562730ed538","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/273f70397ab53562730ed538/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[437,438,439,440,441,442,443,444],"take":"subject1/k1/6/cam4","frame_ids":[437,438,439,440,441,442,443,444]} +{"filtered_tile_id":"273f70397ab53562730ed538:52","filtered_window_id":"273f70397ab53562730ed538","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/273f70397ab53562730ed538/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject1/k1/6/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"280fbb30c30d1ecbaed333ef:0","filtered_window_id":"280fbb30c30d1ecbaed333ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/280fbb30c30d1ecbaed333ef/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject2/h1/1/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"280fbb30c30d1ecbaed333ef:8","filtered_window_id":"280fbb30c30d1ecbaed333ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/280fbb30c30d1ecbaed333ef/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject2/h1/1/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"280fbb30c30d1ecbaed333ef:16","filtered_window_id":"280fbb30c30d1ecbaed333ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/280fbb30c30d1ecbaed333ef/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject2/h1/1/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"280fbb30c30d1ecbaed333ef:24","filtered_window_id":"280fbb30c30d1ecbaed333ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/280fbb30c30d1ecbaed333ef/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject2/h1/1/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"280fbb30c30d1ecbaed333ef:32","filtered_window_id":"280fbb30c30d1ecbaed333ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/280fbb30c30d1ecbaed333ef/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject2/h1/1/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"280fbb30c30d1ecbaed333ef:40","filtered_window_id":"280fbb30c30d1ecbaed333ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/280fbb30c30d1ecbaed333ef/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject2/h1/1/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"280fbb30c30d1ecbaed333ef:48","filtered_window_id":"280fbb30c30d1ecbaed333ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/280fbb30c30d1ecbaed333ef/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject2/h1/1/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"280fbb30c30d1ecbaed333ef:52","filtered_window_id":"280fbb30c30d1ecbaed333ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/280fbb30c30d1ecbaed333ef/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject2/h1/1/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"283cdd640378b33d33f77f17:0","filtered_window_id":"283cdd640378b33d33f77f17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/283cdd640378b33d33f77f17/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject1/o1/4/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"283cdd640378b33d33f77f17:8","filtered_window_id":"283cdd640378b33d33f77f17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/283cdd640378b33d33f77f17/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject1/o1/4/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"283cdd640378b33d33f77f17:15","filtered_window_id":"283cdd640378b33d33f77f17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/283cdd640378b33d33f77f17/native_gt.npz","filtered_start_offset":15,"expected_frame_ids":[320,321,322,323,324,325,326,327],"take":"subject1/o1/4/cam4","frame_ids":[320,321,322,323,324,325,326,327]} +{"filtered_tile_id":"286752d567885f79e2082b9d:0","filtered_window_id":"286752d567885f79e2082b9d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/286752d567885f79e2082b9d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h2/6/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"286752d567885f79e2082b9d:8","filtered_window_id":"286752d567885f79e2082b9d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/286752d567885f79e2082b9d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h2/6/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"286752d567885f79e2082b9d:16","filtered_window_id":"286752d567885f79e2082b9d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/286752d567885f79e2082b9d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h2/6/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"286752d567885f79e2082b9d:24","filtered_window_id":"286752d567885f79e2082b9d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/286752d567885f79e2082b9d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h2/6/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"286752d567885f79e2082b9d:32","filtered_window_id":"286752d567885f79e2082b9d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/286752d567885f79e2082b9d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h2/6/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"286752d567885f79e2082b9d:40","filtered_window_id":"286752d567885f79e2082b9d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/286752d567885f79e2082b9d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/h2/6/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"286752d567885f79e2082b9d:46","filtered_window_id":"286752d567885f79e2082b9d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/286752d567885f79e2082b9d/native_gt.npz","filtered_start_offset":46,"expected_frame_ids":[46,47,48,49,50,51,52,53],"take":"subject1/h2/6/cam4","frame_ids":[46,47,48,49,50,51,52,53]} +{"filtered_tile_id":"28909304cf90d74e2feee5b4:0","filtered_window_id":"28909304cf90d74e2feee5b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28909304cf90d74e2feee5b4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[315,316,317,318,319,320,321,322],"take":"subject1/h1/3/cam4","frame_ids":[315,316,317,318,319,320,321,322]} +{"filtered_tile_id":"28909304cf90d74e2feee5b4:8","filtered_window_id":"28909304cf90d74e2feee5b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28909304cf90d74e2feee5b4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[323,324,325,326,327,328,329,330],"take":"subject1/h1/3/cam4","frame_ids":[323,324,325,326,327,328,329,330]} +{"filtered_tile_id":"28909304cf90d74e2feee5b4:16","filtered_window_id":"28909304cf90d74e2feee5b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28909304cf90d74e2feee5b4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[331,332,333,334,335,336,337,338],"take":"subject1/h1/3/cam4","frame_ids":[331,332,333,334,335,336,337,338]} +{"filtered_tile_id":"28909304cf90d74e2feee5b4:24","filtered_window_id":"28909304cf90d74e2feee5b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28909304cf90d74e2feee5b4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[339,340,341,342,343,344,345,346],"take":"subject1/h1/3/cam4","frame_ids":[339,340,341,342,343,344,345,346]} +{"filtered_tile_id":"28909304cf90d74e2feee5b4:32","filtered_window_id":"28909304cf90d74e2feee5b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28909304cf90d74e2feee5b4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[347,348,349,350,351,352,353,354],"take":"subject1/h1/3/cam4","frame_ids":[347,348,349,350,351,352,353,354]} +{"filtered_tile_id":"28909304cf90d74e2feee5b4:40","filtered_window_id":"28909304cf90d74e2feee5b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28909304cf90d74e2feee5b4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[355,356,357,358,359,360,361,362],"take":"subject1/h1/3/cam4","frame_ids":[355,356,357,358,359,360,361,362]} +{"filtered_tile_id":"28909304cf90d74e2feee5b4:48","filtered_window_id":"28909304cf90d74e2feee5b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28909304cf90d74e2feee5b4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[363,364,365,366,367,368,369,370],"take":"subject1/h1/3/cam4","frame_ids":[363,364,365,366,367,368,369,370]} +{"filtered_tile_id":"28909304cf90d74e2feee5b4:52","filtered_window_id":"28909304cf90d74e2feee5b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28909304cf90d74e2feee5b4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[367,368,369,370,371,372,373,374],"take":"subject1/h1/3/cam4","frame_ids":[367,368,369,370,371,372,373,374]} +{"filtered_tile_id":"28b9fdeb67a1d3ee5b1eec96:0","filtered_window_id":"28b9fdeb67a1d3ee5b1eec96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28b9fdeb67a1d3ee5b1eec96/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[603,604,605,606,607,608,609,610],"take":"subject1/k1/1/cam4","frame_ids":[603,604,605,606,607,608,609,610]} +{"filtered_tile_id":"28b9fdeb67a1d3ee5b1eec96:8","filtered_window_id":"28b9fdeb67a1d3ee5b1eec96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28b9fdeb67a1d3ee5b1eec96/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[611,612,613,614,615,616,617,618],"take":"subject1/k1/1/cam4","frame_ids":[611,612,613,614,615,616,617,618]} +{"filtered_tile_id":"28b9fdeb67a1d3ee5b1eec96:16","filtered_window_id":"28b9fdeb67a1d3ee5b1eec96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28b9fdeb67a1d3ee5b1eec96/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[619,620,621,622,623,624,625,626],"take":"subject1/k1/1/cam4","frame_ids":[619,620,621,622,623,624,625,626]} +{"filtered_tile_id":"28b9fdeb67a1d3ee5b1eec96:24","filtered_window_id":"28b9fdeb67a1d3ee5b1eec96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28b9fdeb67a1d3ee5b1eec96/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[627,628,629,630,631,632,633,634],"take":"subject1/k1/1/cam4","frame_ids":[627,628,629,630,631,632,633,634]} +{"filtered_tile_id":"28b9fdeb67a1d3ee5b1eec96:32","filtered_window_id":"28b9fdeb67a1d3ee5b1eec96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28b9fdeb67a1d3ee5b1eec96/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[635,636,637,638,639,640,641,642],"take":"subject1/k1/1/cam4","frame_ids":[635,636,637,638,639,640,641,642]} +{"filtered_tile_id":"28b9fdeb67a1d3ee5b1eec96:40","filtered_window_id":"28b9fdeb67a1d3ee5b1eec96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28b9fdeb67a1d3ee5b1eec96/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[643,644,645,646,647,648,649,650],"take":"subject1/k1/1/cam4","frame_ids":[643,644,645,646,647,648,649,650]} +{"filtered_tile_id":"28b9fdeb67a1d3ee5b1eec96:48","filtered_window_id":"28b9fdeb67a1d3ee5b1eec96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28b9fdeb67a1d3ee5b1eec96/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[651,652,653,654,655,656,657,658],"take":"subject1/k1/1/cam4","frame_ids":[651,652,653,654,655,656,657,658]} +{"filtered_tile_id":"28b9fdeb67a1d3ee5b1eec96:52","filtered_window_id":"28b9fdeb67a1d3ee5b1eec96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28b9fdeb67a1d3ee5b1eec96/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[655,656,657,658,659,660,661,662],"take":"subject1/k1/1/cam4","frame_ids":[655,656,657,658,659,660,661,662]} +{"filtered_tile_id":"28cf62b328f06b383ecd4686:0","filtered_window_id":"28cf62b328f06b383ecd4686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28cf62b328f06b383ecd4686/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject2/o1/2/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"28cf62b328f06b383ecd4686:8","filtered_window_id":"28cf62b328f06b383ecd4686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28cf62b328f06b383ecd4686/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject2/o1/2/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"28cf62b328f06b383ecd4686:16","filtered_window_id":"28cf62b328f06b383ecd4686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28cf62b328f06b383ecd4686/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject2/o1/2/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"28cf62b328f06b383ecd4686:24","filtered_window_id":"28cf62b328f06b383ecd4686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28cf62b328f06b383ecd4686/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject2/o1/2/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"28cf62b328f06b383ecd4686:32","filtered_window_id":"28cf62b328f06b383ecd4686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28cf62b328f06b383ecd4686/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject2/o1/2/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"28cf62b328f06b383ecd4686:40","filtered_window_id":"28cf62b328f06b383ecd4686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28cf62b328f06b383ecd4686/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject2/o1/2/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"28cf62b328f06b383ecd4686:48","filtered_window_id":"28cf62b328f06b383ecd4686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28cf62b328f06b383ecd4686/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject2/o1/2/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"28cf62b328f06b383ecd4686:52","filtered_window_id":"28cf62b328f06b383ecd4686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28cf62b328f06b383ecd4686/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[532,533,534,535,536,537,538,539],"take":"subject2/o1/2/cam4","frame_ids":[532,533,534,535,536,537,538,539]} +{"filtered_tile_id":"28ec608fa161cd47d7b97d9c:0","filtered_window_id":"28ec608fa161cd47d7b97d9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28ec608fa161cd47d7b97d9c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject1/o1/0/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"28ec608fa161cd47d7b97d9c:8","filtered_window_id":"28ec608fa161cd47d7b97d9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28ec608fa161cd47d7b97d9c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[386,387,388,389,390,391,392,393],"take":"subject1/o1/0/cam4","frame_ids":[386,387,388,389,390,391,392,393]} +{"filtered_tile_id":"28ec608fa161cd47d7b97d9c:16","filtered_window_id":"28ec608fa161cd47d7b97d9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28ec608fa161cd47d7b97d9c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[394,395,396,397,398,399,400,401],"take":"subject1/o1/0/cam4","frame_ids":[394,395,396,397,398,399,400,401]} +{"filtered_tile_id":"28ec608fa161cd47d7b97d9c:24","filtered_window_id":"28ec608fa161cd47d7b97d9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28ec608fa161cd47d7b97d9c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[402,403,404,405,406,407,408,409],"take":"subject1/o1/0/cam4","frame_ids":[402,403,404,405,406,407,408,409]} +{"filtered_tile_id":"28ec608fa161cd47d7b97d9c:28","filtered_window_id":"28ec608fa161cd47d7b97d9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28ec608fa161cd47d7b97d9c/native_gt.npz","filtered_start_offset":28,"expected_frame_ids":[406,407,408,409,410,411,412,413],"take":"subject1/o1/0/cam4","frame_ids":[406,407,408,409,410,411,412,413]} +{"filtered_tile_id":"28fc5a0335d0cfa78cb40c7b:0","filtered_window_id":"28fc5a0335d0cfa78cb40c7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28fc5a0335d0cfa78cb40c7b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[413,414,415,416,417,418,419,420],"take":"subject3/h2/7/cam4","frame_ids":[413,414,415,416,417,418,419,420]} +{"filtered_tile_id":"28fc5a0335d0cfa78cb40c7b:8","filtered_window_id":"28fc5a0335d0cfa78cb40c7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28fc5a0335d0cfa78cb40c7b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[421,422,423,424,425,426,427,428],"take":"subject3/h2/7/cam4","frame_ids":[421,422,423,424,425,426,427,428]} +{"filtered_tile_id":"28fc5a0335d0cfa78cb40c7b:16","filtered_window_id":"28fc5a0335d0cfa78cb40c7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28fc5a0335d0cfa78cb40c7b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[429,430,431,432,433,434,435,436],"take":"subject3/h2/7/cam4","frame_ids":[429,430,431,432,433,434,435,436]} +{"filtered_tile_id":"28fc5a0335d0cfa78cb40c7b:24","filtered_window_id":"28fc5a0335d0cfa78cb40c7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28fc5a0335d0cfa78cb40c7b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[437,438,439,440,441,442,443,444],"take":"subject3/h2/7/cam4","frame_ids":[437,438,439,440,441,442,443,444]} +{"filtered_tile_id":"28fc5a0335d0cfa78cb40c7b:32","filtered_window_id":"28fc5a0335d0cfa78cb40c7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28fc5a0335d0cfa78cb40c7b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[445,446,447,448,449,450,451,452],"take":"subject3/h2/7/cam4","frame_ids":[445,446,447,448,449,450,451,452]} +{"filtered_tile_id":"28fc5a0335d0cfa78cb40c7b:40","filtered_window_id":"28fc5a0335d0cfa78cb40c7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28fc5a0335d0cfa78cb40c7b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[453,454,455,456,457,458,459,460],"take":"subject3/h2/7/cam4","frame_ids":[453,454,455,456,457,458,459,460]} +{"filtered_tile_id":"28fc5a0335d0cfa78cb40c7b:48","filtered_window_id":"28fc5a0335d0cfa78cb40c7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28fc5a0335d0cfa78cb40c7b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject3/h2/7/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"28fc5a0335d0cfa78cb40c7b:50","filtered_window_id":"28fc5a0335d0cfa78cb40c7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/28fc5a0335d0cfa78cb40c7b/native_gt.npz","filtered_start_offset":50,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject3/h2/7/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"2927c002c1b14cf9cfc14a92:0","filtered_window_id":"2927c002c1b14cf9cfc14a92","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2927c002c1b14cf9cfc14a92/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[259,260,261,262,263,264,265,266],"take":"subject3/k1/3/cam4","frame_ids":[259,260,261,262,263,264,265,266]} +{"filtered_tile_id":"2927c002c1b14cf9cfc14a92:8","filtered_window_id":"2927c002c1b14cf9cfc14a92","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2927c002c1b14cf9cfc14a92/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[267,268,269,270,271,272,273,274],"take":"subject3/k1/3/cam4","frame_ids":[267,268,269,270,271,272,273,274]} +{"filtered_tile_id":"2927c002c1b14cf9cfc14a92:16","filtered_window_id":"2927c002c1b14cf9cfc14a92","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2927c002c1b14cf9cfc14a92/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[275,276,277,278,279,280,281,282],"take":"subject3/k1/3/cam4","frame_ids":[275,276,277,278,279,280,281,282]} +{"filtered_tile_id":"2927c002c1b14cf9cfc14a92:24","filtered_window_id":"2927c002c1b14cf9cfc14a92","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2927c002c1b14cf9cfc14a92/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[283,284,285,286,287,288,289,290],"take":"subject3/k1/3/cam4","frame_ids":[283,284,285,286,287,288,289,290]} +{"filtered_tile_id":"2927c002c1b14cf9cfc14a92:32","filtered_window_id":"2927c002c1b14cf9cfc14a92","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2927c002c1b14cf9cfc14a92/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[291,292,293,294,295,296,297,298],"take":"subject3/k1/3/cam4","frame_ids":[291,292,293,294,295,296,297,298]} +{"filtered_tile_id":"2927c002c1b14cf9cfc14a92:40","filtered_window_id":"2927c002c1b14cf9cfc14a92","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2927c002c1b14cf9cfc14a92/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[299,300,301,302,303,304,305,306],"take":"subject3/k1/3/cam4","frame_ids":[299,300,301,302,303,304,305,306]} +{"filtered_tile_id":"2927c002c1b14cf9cfc14a92:48","filtered_window_id":"2927c002c1b14cf9cfc14a92","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2927c002c1b14cf9cfc14a92/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[307,308,309,310,311,312,313,314],"take":"subject3/k1/3/cam4","frame_ids":[307,308,309,310,311,312,313,314]} +{"filtered_tile_id":"2927c002c1b14cf9cfc14a92:52","filtered_window_id":"2927c002c1b14cf9cfc14a92","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2927c002c1b14cf9cfc14a92/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[311,312,313,314,315,316,317,318],"take":"subject3/k1/3/cam4","frame_ids":[311,312,313,314,315,316,317,318]} +{"filtered_tile_id":"29417480cd32ea2d94858f42:0","filtered_window_id":"29417480cd32ea2d94858f42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29417480cd32ea2d94858f42/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[702,703,704,705,706,707,708,709],"take":"subject1/o1/1/cam4","frame_ids":[702,703,704,705,706,707,708,709]} +{"filtered_tile_id":"29417480cd32ea2d94858f42:8","filtered_window_id":"29417480cd32ea2d94858f42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29417480cd32ea2d94858f42/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[710,711,712,713,714,715,716,717],"take":"subject1/o1/1/cam4","frame_ids":[710,711,712,713,714,715,716,717]} +{"filtered_tile_id":"29417480cd32ea2d94858f42:16","filtered_window_id":"29417480cd32ea2d94858f42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29417480cd32ea2d94858f42/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[718,719,720,721,722,723,724,725],"take":"subject1/o1/1/cam4","frame_ids":[718,719,720,721,722,723,724,725]} +{"filtered_tile_id":"29417480cd32ea2d94858f42:24","filtered_window_id":"29417480cd32ea2d94858f42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29417480cd32ea2d94858f42/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[726,727,728,729,730,731,732,733],"take":"subject1/o1/1/cam4","frame_ids":[726,727,728,729,730,731,732,733]} +{"filtered_tile_id":"29417480cd32ea2d94858f42:32","filtered_window_id":"29417480cd32ea2d94858f42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29417480cd32ea2d94858f42/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[734,735,736,737,738,739,740,741],"take":"subject1/o1/1/cam4","frame_ids":[734,735,736,737,738,739,740,741]} +{"filtered_tile_id":"29417480cd32ea2d94858f42:34","filtered_window_id":"29417480cd32ea2d94858f42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29417480cd32ea2d94858f42/native_gt.npz","filtered_start_offset":34,"expected_frame_ids":[736,737,738,739,740,741,742,743],"take":"subject1/o1/1/cam4","frame_ids":[736,737,738,739,740,741,742,743]} +{"filtered_tile_id":"29aa2eb0edbf2666cfe8f746:0","filtered_window_id":"29aa2eb0edbf2666cfe8f746","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29aa2eb0edbf2666cfe8f746/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject2/k2/6/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"29aa2eb0edbf2666cfe8f746:8","filtered_window_id":"29aa2eb0edbf2666cfe8f746","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29aa2eb0edbf2666cfe8f746/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject2/k2/6/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"29aa2eb0edbf2666cfe8f746:16","filtered_window_id":"29aa2eb0edbf2666cfe8f746","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29aa2eb0edbf2666cfe8f746/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject2/k2/6/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"29aa2eb0edbf2666cfe8f746:24","filtered_window_id":"29aa2eb0edbf2666cfe8f746","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29aa2eb0edbf2666cfe8f746/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject2/k2/6/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"29aa2eb0edbf2666cfe8f746:32","filtered_window_id":"29aa2eb0edbf2666cfe8f746","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29aa2eb0edbf2666cfe8f746/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject2/k2/6/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"29aa2eb0edbf2666cfe8f746:40","filtered_window_id":"29aa2eb0edbf2666cfe8f746","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29aa2eb0edbf2666cfe8f746/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject2/k2/6/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"29aa2eb0edbf2666cfe8f746:48","filtered_window_id":"29aa2eb0edbf2666cfe8f746","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29aa2eb0edbf2666cfe8f746/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject2/k2/6/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"29aa2eb0edbf2666cfe8f746:52","filtered_window_id":"29aa2eb0edbf2666cfe8f746","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29aa2eb0edbf2666cfe8f746/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject2/k2/6/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"29b6d512e641fdf84d5825a8:0","filtered_window_id":"29b6d512e641fdf84d5825a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29b6d512e641fdf84d5825a8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject3/h1/5/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"29b6d512e641fdf84d5825a8:8","filtered_window_id":"29b6d512e641fdf84d5825a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29b6d512e641fdf84d5825a8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject3/h1/5/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"29b6d512e641fdf84d5825a8:16","filtered_window_id":"29b6d512e641fdf84d5825a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29b6d512e641fdf84d5825a8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject3/h1/5/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"29b6d512e641fdf84d5825a8:24","filtered_window_id":"29b6d512e641fdf84d5825a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29b6d512e641fdf84d5825a8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject3/h1/5/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"29b6d512e641fdf84d5825a8:32","filtered_window_id":"29b6d512e641fdf84d5825a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29b6d512e641fdf84d5825a8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject3/h1/5/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"29b6d512e641fdf84d5825a8:40","filtered_window_id":"29b6d512e641fdf84d5825a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29b6d512e641fdf84d5825a8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject3/h1/5/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"29b6d512e641fdf84d5825a8:48","filtered_window_id":"29b6d512e641fdf84d5825a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29b6d512e641fdf84d5825a8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject3/h1/5/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"29b6d512e641fdf84d5825a8:52","filtered_window_id":"29b6d512e641fdf84d5825a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29b6d512e641fdf84d5825a8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject3/h1/5/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"29bc25b76d24f12e7476d4ae:0","filtered_window_id":"29bc25b76d24f12e7476d4ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29bc25b76d24f12e7476d4ae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject2/k1/6/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"29bc25b76d24f12e7476d4ae:7","filtered_window_id":"29bc25b76d24f12e7476d4ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/29bc25b76d24f12e7476d4ae/native_gt.npz","filtered_start_offset":7,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject2/k1/6/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"2a66d8d92767685f2102f1a8:0","filtered_window_id":"2a66d8d92767685f2102f1a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a66d8d92767685f2102f1a8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[35,36,37,38,39,40,41,42],"take":"subject3/k1/5/cam4","frame_ids":[35,36,37,38,39,40,41,42]} +{"filtered_tile_id":"2a66d8d92767685f2102f1a8:8","filtered_window_id":"2a66d8d92767685f2102f1a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a66d8d92767685f2102f1a8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[43,44,45,46,47,48,49,50],"take":"subject3/k1/5/cam4","frame_ids":[43,44,45,46,47,48,49,50]} +{"filtered_tile_id":"2a66d8d92767685f2102f1a8:16","filtered_window_id":"2a66d8d92767685f2102f1a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a66d8d92767685f2102f1a8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject3/k1/5/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"2a66d8d92767685f2102f1a8:24","filtered_window_id":"2a66d8d92767685f2102f1a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a66d8d92767685f2102f1a8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[59,60,61,62,63,64,65,66],"take":"subject3/k1/5/cam4","frame_ids":[59,60,61,62,63,64,65,66]} +{"filtered_tile_id":"2a66d8d92767685f2102f1a8:32","filtered_window_id":"2a66d8d92767685f2102f1a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a66d8d92767685f2102f1a8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject3/k1/5/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"2a66d8d92767685f2102f1a8:40","filtered_window_id":"2a66d8d92767685f2102f1a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a66d8d92767685f2102f1a8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject3/k1/5/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"2a66d8d92767685f2102f1a8:48","filtered_window_id":"2a66d8d92767685f2102f1a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a66d8d92767685f2102f1a8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject3/k1/5/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"2a66d8d92767685f2102f1a8:52","filtered_window_id":"2a66d8d92767685f2102f1a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a66d8d92767685f2102f1a8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[87,88,89,90,91,92,93,94],"take":"subject3/k1/5/cam4","frame_ids":[87,88,89,90,91,92,93,94]} +{"filtered_tile_id":"2a70eb568925204312daf44c:0","filtered_window_id":"2a70eb568925204312daf44c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a70eb568925204312daf44c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject3/h1/6/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"2a70eb568925204312daf44c:4","filtered_window_id":"2a70eb568925204312daf44c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a70eb568925204312daf44c/native_gt.npz","filtered_start_offset":4,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject3/h1/6/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"2a9322bb672d3e552e4c11a6:0","filtered_window_id":"2a9322bb672d3e552e4c11a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a9322bb672d3e552e4c11a6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject3/h2/1/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"2a9322bb672d3e552e4c11a6:8","filtered_window_id":"2a9322bb672d3e552e4c11a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a9322bb672d3e552e4c11a6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject3/h2/1/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"2a9322bb672d3e552e4c11a6:16","filtered_window_id":"2a9322bb672d3e552e4c11a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a9322bb672d3e552e4c11a6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject3/h2/1/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"2a9322bb672d3e552e4c11a6:24","filtered_window_id":"2a9322bb672d3e552e4c11a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a9322bb672d3e552e4c11a6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject3/h2/1/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"2a9322bb672d3e552e4c11a6:32","filtered_window_id":"2a9322bb672d3e552e4c11a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a9322bb672d3e552e4c11a6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject3/h2/1/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"2a9322bb672d3e552e4c11a6:40","filtered_window_id":"2a9322bb672d3e552e4c11a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a9322bb672d3e552e4c11a6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject3/h2/1/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"2a9322bb672d3e552e4c11a6:48","filtered_window_id":"2a9322bb672d3e552e4c11a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a9322bb672d3e552e4c11a6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject3/h2/1/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"2a9322bb672d3e552e4c11a6:52","filtered_window_id":"2a9322bb672d3e552e4c11a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2a9322bb672d3e552e4c11a6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject3/h2/1/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"2ab7272c90c73bb59a775564:0","filtered_window_id":"2ab7272c90c73bb59a775564","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ab7272c90c73bb59a775564/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[260,261,262,263,264,265,266,267],"take":"subject3/k1/4/cam4","frame_ids":[260,261,262,263,264,265,266,267]} +{"filtered_tile_id":"2ab7272c90c73bb59a775564:8","filtered_window_id":"2ab7272c90c73bb59a775564","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ab7272c90c73bb59a775564/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[268,269,270,271,272,273,274,275],"take":"subject3/k1/4/cam4","frame_ids":[268,269,270,271,272,273,274,275]} +{"filtered_tile_id":"2ab7272c90c73bb59a775564:16","filtered_window_id":"2ab7272c90c73bb59a775564","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ab7272c90c73bb59a775564/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[276,277,278,279,280,281,282,283],"take":"subject3/k1/4/cam4","frame_ids":[276,277,278,279,280,281,282,283]} +{"filtered_tile_id":"2ab7272c90c73bb59a775564:24","filtered_window_id":"2ab7272c90c73bb59a775564","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ab7272c90c73bb59a775564/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[284,285,286,287,288,289,290,291],"take":"subject3/k1/4/cam4","frame_ids":[284,285,286,287,288,289,290,291]} +{"filtered_tile_id":"2ab7272c90c73bb59a775564:32","filtered_window_id":"2ab7272c90c73bb59a775564","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ab7272c90c73bb59a775564/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[292,293,294,295,296,297,298,299],"take":"subject3/k1/4/cam4","frame_ids":[292,293,294,295,296,297,298,299]} +{"filtered_tile_id":"2ab7272c90c73bb59a775564:40","filtered_window_id":"2ab7272c90c73bb59a775564","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ab7272c90c73bb59a775564/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[300,301,302,303,304,305,306,307],"take":"subject3/k1/4/cam4","frame_ids":[300,301,302,303,304,305,306,307]} +{"filtered_tile_id":"2ab7272c90c73bb59a775564:48","filtered_window_id":"2ab7272c90c73bb59a775564","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ab7272c90c73bb59a775564/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject3/k1/4/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"2ab7272c90c73bb59a775564:51","filtered_window_id":"2ab7272c90c73bb59a775564","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ab7272c90c73bb59a775564/native_gt.npz","filtered_start_offset":51,"expected_frame_ids":[311,312,313,314,315,316,317,318],"take":"subject3/k1/4/cam4","frame_ids":[311,312,313,314,315,316,317,318]} +{"filtered_tile_id":"2ac35712a69ac07efe24ea80:0","filtered_window_id":"2ac35712a69ac07efe24ea80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ac35712a69ac07efe24ea80/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[515,516,517,518,519,520,521,522],"take":"subject1/o1/4/cam4","frame_ids":[515,516,517,518,519,520,521,522]} +{"filtered_tile_id":"2ac35712a69ac07efe24ea80:8","filtered_window_id":"2ac35712a69ac07efe24ea80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ac35712a69ac07efe24ea80/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[523,524,525,526,527,528,529,530],"take":"subject1/o1/4/cam4","frame_ids":[523,524,525,526,527,528,529,530]} +{"filtered_tile_id":"2ac35712a69ac07efe24ea80:16","filtered_window_id":"2ac35712a69ac07efe24ea80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ac35712a69ac07efe24ea80/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[531,532,533,534,535,536,537,538],"take":"subject1/o1/4/cam4","frame_ids":[531,532,533,534,535,536,537,538]} +{"filtered_tile_id":"2ac35712a69ac07efe24ea80:20","filtered_window_id":"2ac35712a69ac07efe24ea80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ac35712a69ac07efe24ea80/native_gt.npz","filtered_start_offset":20,"expected_frame_ids":[535,536,537,538,539,540,541,542],"take":"subject1/o1/4/cam4","frame_ids":[535,536,537,538,539,540,541,542]} +{"filtered_tile_id":"2b383116e8be5539f9a0a45f:0","filtered_window_id":"2b383116e8be5539f9a0a45f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b383116e8be5539f9a0a45f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h1/5/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"2b383116e8be5539f9a0a45f:8","filtered_window_id":"2b383116e8be5539f9a0a45f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b383116e8be5539f9a0a45f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h1/5/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"2b383116e8be5539f9a0a45f:16","filtered_window_id":"2b383116e8be5539f9a0a45f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b383116e8be5539f9a0a45f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h1/5/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"2b383116e8be5539f9a0a45f:24","filtered_window_id":"2b383116e8be5539f9a0a45f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b383116e8be5539f9a0a45f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h1/5/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"2b383116e8be5539f9a0a45f:32","filtered_window_id":"2b383116e8be5539f9a0a45f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b383116e8be5539f9a0a45f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h1/5/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"2b383116e8be5539f9a0a45f:40","filtered_window_id":"2b383116e8be5539f9a0a45f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b383116e8be5539f9a0a45f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/h1/5/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"2b383116e8be5539f9a0a45f:45","filtered_window_id":"2b383116e8be5539f9a0a45f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b383116e8be5539f9a0a45f/native_gt.npz","filtered_start_offset":45,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject1/h1/5/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"2b3e0dc8962d23d88f126344:0","filtered_window_id":"2b3e0dc8962d23d88f126344","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b3e0dc8962d23d88f126344/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject3/h1/2/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"2b3e0dc8962d23d88f126344:8","filtered_window_id":"2b3e0dc8962d23d88f126344","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b3e0dc8962d23d88f126344/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[170,171,172,173,174,175,176,177],"take":"subject3/h1/2/cam4","frame_ids":[170,171,172,173,174,175,176,177]} +{"filtered_tile_id":"2b3e0dc8962d23d88f126344:9","filtered_window_id":"2b3e0dc8962d23d88f126344","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b3e0dc8962d23d88f126344/native_gt.npz","filtered_start_offset":9,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject3/h1/2/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"2b686a4ce838118d38158356:0","filtered_window_id":"2b686a4ce838118d38158356","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b686a4ce838118d38158356/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[354,355,356,357,358,359,360,361],"take":"subject3/k1/6/cam4","frame_ids":[354,355,356,357,358,359,360,361]} +{"filtered_tile_id":"2b686a4ce838118d38158356:8","filtered_window_id":"2b686a4ce838118d38158356","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b686a4ce838118d38158356/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject3/k1/6/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"2b9e330afa2f33ff2fd43b10:0","filtered_window_id":"2b9e330afa2f33ff2fd43b10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b9e330afa2f33ff2fd43b10/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[13,14,15,16,17,18,19,20],"take":"subject2/k1/0/cam4","frame_ids":[13,14,15,16,17,18,19,20]} +{"filtered_tile_id":"2b9e330afa2f33ff2fd43b10:8","filtered_window_id":"2b9e330afa2f33ff2fd43b10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b9e330afa2f33ff2fd43b10/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[21,22,23,24,25,26,27,28],"take":"subject2/k1/0/cam4","frame_ids":[21,22,23,24,25,26,27,28]} +{"filtered_tile_id":"2b9e330afa2f33ff2fd43b10:16","filtered_window_id":"2b9e330afa2f33ff2fd43b10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b9e330afa2f33ff2fd43b10/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[29,30,31,32,33,34,35,36],"take":"subject2/k1/0/cam4","frame_ids":[29,30,31,32,33,34,35,36]} +{"filtered_tile_id":"2b9e330afa2f33ff2fd43b10:24","filtered_window_id":"2b9e330afa2f33ff2fd43b10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b9e330afa2f33ff2fd43b10/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject2/k1/0/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"2b9e330afa2f33ff2fd43b10:32","filtered_window_id":"2b9e330afa2f33ff2fd43b10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b9e330afa2f33ff2fd43b10/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject2/k1/0/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"2b9e330afa2f33ff2fd43b10:40","filtered_window_id":"2b9e330afa2f33ff2fd43b10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b9e330afa2f33ff2fd43b10/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[53,54,55,56,57,58,59,60],"take":"subject2/k1/0/cam4","frame_ids":[53,54,55,56,57,58,59,60]} +{"filtered_tile_id":"2b9e330afa2f33ff2fd43b10:48","filtered_window_id":"2b9e330afa2f33ff2fd43b10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b9e330afa2f33ff2fd43b10/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[61,62,63,64,65,66,67,68],"take":"subject2/k1/0/cam4","frame_ids":[61,62,63,64,65,66,67,68]} +{"filtered_tile_id":"2b9e330afa2f33ff2fd43b10:52","filtered_window_id":"2b9e330afa2f33ff2fd43b10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2b9e330afa2f33ff2fd43b10/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[65,66,67,68,69,70,71,72],"take":"subject2/k1/0/cam4","frame_ids":[65,66,67,68,69,70,71,72]} +{"filtered_tile_id":"2bda6d068f5be8562a9dbc91:0","filtered_window_id":"2bda6d068f5be8562a9dbc91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2bda6d068f5be8562a9dbc91/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[336,337,338,339,340,341,342,343],"take":"subject3/k1/5/cam4","frame_ids":[336,337,338,339,340,341,342,343]} +{"filtered_tile_id":"2bda6d068f5be8562a9dbc91:8","filtered_window_id":"2bda6d068f5be8562a9dbc91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2bda6d068f5be8562a9dbc91/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[344,345,346,347,348,349,350,351],"take":"subject3/k1/5/cam4","frame_ids":[344,345,346,347,348,349,350,351]} +{"filtered_tile_id":"2bda6d068f5be8562a9dbc91:16","filtered_window_id":"2bda6d068f5be8562a9dbc91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2bda6d068f5be8562a9dbc91/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject3/k1/5/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"2bda6d068f5be8562a9dbc91:24","filtered_window_id":"2bda6d068f5be8562a9dbc91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2bda6d068f5be8562a9dbc91/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject3/k1/5/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"2bda6d068f5be8562a9dbc91:32","filtered_window_id":"2bda6d068f5be8562a9dbc91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2bda6d068f5be8562a9dbc91/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject3/k1/5/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"2bda6d068f5be8562a9dbc91:40","filtered_window_id":"2bda6d068f5be8562a9dbc91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2bda6d068f5be8562a9dbc91/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[376,377,378,379,380,381,382,383],"take":"subject3/k1/5/cam4","frame_ids":[376,377,378,379,380,381,382,383]} +{"filtered_tile_id":"2bda6d068f5be8562a9dbc91:48","filtered_window_id":"2bda6d068f5be8562a9dbc91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2bda6d068f5be8562a9dbc91/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject3/k1/5/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"2bda6d068f5be8562a9dbc91:52","filtered_window_id":"2bda6d068f5be8562a9dbc91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2bda6d068f5be8562a9dbc91/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject3/k1/5/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"2c3d6eb4aa272bde517cefb9:0","filtered_window_id":"2c3d6eb4aa272bde517cefb9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c3d6eb4aa272bde517cefb9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject1/o1/0/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"2c3d6eb4aa272bde517cefb9:8","filtered_window_id":"2c3d6eb4aa272bde517cefb9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c3d6eb4aa272bde517cefb9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject1/o1/0/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"2c3d6eb4aa272bde517cefb9:16","filtered_window_id":"2c3d6eb4aa272bde517cefb9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c3d6eb4aa272bde517cefb9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject1/o1/0/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"2c3d6eb4aa272bde517cefb9:24","filtered_window_id":"2c3d6eb4aa272bde517cefb9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c3d6eb4aa272bde517cefb9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject1/o1/0/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"2c6b851c9eaf256158174f54:0","filtered_window_id":"2c6b851c9eaf256158174f54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c6b851c9eaf256158174f54/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject1/k2/3/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"2c6b851c9eaf256158174f54:8","filtered_window_id":"2c6b851c9eaf256158174f54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c6b851c9eaf256158174f54/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject1/k2/3/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"2c6b851c9eaf256158174f54:16","filtered_window_id":"2c6b851c9eaf256158174f54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c6b851c9eaf256158174f54/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[411,412,413,414,415,416,417,418],"take":"subject1/k2/3/cam4","frame_ids":[411,412,413,414,415,416,417,418]} +{"filtered_tile_id":"2c6b851c9eaf256158174f54:24","filtered_window_id":"2c6b851c9eaf256158174f54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c6b851c9eaf256158174f54/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[419,420,421,422,423,424,425,426],"take":"subject1/k2/3/cam4","frame_ids":[419,420,421,422,423,424,425,426]} +{"filtered_tile_id":"2c6b851c9eaf256158174f54:32","filtered_window_id":"2c6b851c9eaf256158174f54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c6b851c9eaf256158174f54/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject1/k2/3/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"2c6b851c9eaf256158174f54:40","filtered_window_id":"2c6b851c9eaf256158174f54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c6b851c9eaf256158174f54/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/k2/3/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"2c6b851c9eaf256158174f54:48","filtered_window_id":"2c6b851c9eaf256158174f54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c6b851c9eaf256158174f54/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject1/k2/3/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"2c6b851c9eaf256158174f54:52","filtered_window_id":"2c6b851c9eaf256158174f54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c6b851c9eaf256158174f54/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[447,448,449,450,451,452,453,454],"take":"subject1/k2/3/cam4","frame_ids":[447,448,449,450,451,452,453,454]} +{"filtered_tile_id":"2c7b4095c8cf07ba029a3979:0","filtered_window_id":"2c7b4095c8cf07ba029a3979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c7b4095c8cf07ba029a3979/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[780,781,782,783,784,785,786,787],"take":"subject2/o1/2/cam4","frame_ids":[780,781,782,783,784,785,786,787]} +{"filtered_tile_id":"2c7b4095c8cf07ba029a3979:8","filtered_window_id":"2c7b4095c8cf07ba029a3979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c7b4095c8cf07ba029a3979/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[788,789,790,791,792,793,794,795],"take":"subject2/o1/2/cam4","frame_ids":[788,789,790,791,792,793,794,795]} +{"filtered_tile_id":"2c7b4095c8cf07ba029a3979:16","filtered_window_id":"2c7b4095c8cf07ba029a3979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c7b4095c8cf07ba029a3979/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[796,797,798,799,800,801,802,803],"take":"subject2/o1/2/cam4","frame_ids":[796,797,798,799,800,801,802,803]} +{"filtered_tile_id":"2c7b4095c8cf07ba029a3979:24","filtered_window_id":"2c7b4095c8cf07ba029a3979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c7b4095c8cf07ba029a3979/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[804,805,806,807,808,809,810,811],"take":"subject2/o1/2/cam4","frame_ids":[804,805,806,807,808,809,810,811]} +{"filtered_tile_id":"2c7b4095c8cf07ba029a3979:32","filtered_window_id":"2c7b4095c8cf07ba029a3979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c7b4095c8cf07ba029a3979/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[812,813,814,815,816,817,818,819],"take":"subject2/o1/2/cam4","frame_ids":[812,813,814,815,816,817,818,819]} +{"filtered_tile_id":"2c7b4095c8cf07ba029a3979:40","filtered_window_id":"2c7b4095c8cf07ba029a3979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c7b4095c8cf07ba029a3979/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[820,821,822,823,824,825,826,827],"take":"subject2/o1/2/cam4","frame_ids":[820,821,822,823,824,825,826,827]} +{"filtered_tile_id":"2c7b4095c8cf07ba029a3979:48","filtered_window_id":"2c7b4095c8cf07ba029a3979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c7b4095c8cf07ba029a3979/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[828,829,830,831,832,833,834,835],"take":"subject2/o1/2/cam4","frame_ids":[828,829,830,831,832,833,834,835]} +{"filtered_tile_id":"2c7b4095c8cf07ba029a3979:52","filtered_window_id":"2c7b4095c8cf07ba029a3979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c7b4095c8cf07ba029a3979/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[832,833,834,835,836,837,838,839],"take":"subject2/o1/2/cam4","frame_ids":[832,833,834,835,836,837,838,839]} +{"filtered_tile_id":"2c99ffe11bfce2c0d1a34e32:0","filtered_window_id":"2c99ffe11bfce2c0d1a34e32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c99ffe11bfce2c0d1a34e32/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[804,805,806,807,808,809,810,811],"take":"subject1/h2/3/cam4","frame_ids":[804,805,806,807,808,809,810,811]} +{"filtered_tile_id":"2c99ffe11bfce2c0d1a34e32:8","filtered_window_id":"2c99ffe11bfce2c0d1a34e32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c99ffe11bfce2c0d1a34e32/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[812,813,814,815,816,817,818,819],"take":"subject1/h2/3/cam4","frame_ids":[812,813,814,815,816,817,818,819]} +{"filtered_tile_id":"2c99ffe11bfce2c0d1a34e32:16","filtered_window_id":"2c99ffe11bfce2c0d1a34e32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c99ffe11bfce2c0d1a34e32/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[820,821,822,823,824,825,826,827],"take":"subject1/h2/3/cam4","frame_ids":[820,821,822,823,824,825,826,827]} +{"filtered_tile_id":"2c99ffe11bfce2c0d1a34e32:24","filtered_window_id":"2c99ffe11bfce2c0d1a34e32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c99ffe11bfce2c0d1a34e32/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[828,829,830,831,832,833,834,835],"take":"subject1/h2/3/cam4","frame_ids":[828,829,830,831,832,833,834,835]} +{"filtered_tile_id":"2c99ffe11bfce2c0d1a34e32:32","filtered_window_id":"2c99ffe11bfce2c0d1a34e32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c99ffe11bfce2c0d1a34e32/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[836,837,838,839,840,841,842,843],"take":"subject1/h2/3/cam4","frame_ids":[836,837,838,839,840,841,842,843]} +{"filtered_tile_id":"2c99ffe11bfce2c0d1a34e32:40","filtered_window_id":"2c99ffe11bfce2c0d1a34e32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c99ffe11bfce2c0d1a34e32/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[844,845,846,847,848,849,850,851],"take":"subject1/h2/3/cam4","frame_ids":[844,845,846,847,848,849,850,851]} +{"filtered_tile_id":"2c99ffe11bfce2c0d1a34e32:48","filtered_window_id":"2c99ffe11bfce2c0d1a34e32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c99ffe11bfce2c0d1a34e32/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[852,853,854,855,856,857,858,859],"take":"subject1/h2/3/cam4","frame_ids":[852,853,854,855,856,857,858,859]} +{"filtered_tile_id":"2c99ffe11bfce2c0d1a34e32:52","filtered_window_id":"2c99ffe11bfce2c0d1a34e32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2c99ffe11bfce2c0d1a34e32/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[856,857,858,859,860,861,862,863],"take":"subject1/h2/3/cam4","frame_ids":[856,857,858,859,860,861,862,863]} +{"filtered_tile_id":"2cb70ceaf1746dba20997359:0","filtered_window_id":"2cb70ceaf1746dba20997359","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2cb70ceaf1746dba20997359/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject1/o2/0/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"2cb70ceaf1746dba20997359:8","filtered_window_id":"2cb70ceaf1746dba20997359","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2cb70ceaf1746dba20997359/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject1/o2/0/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"2cb70ceaf1746dba20997359:10","filtered_window_id":"2cb70ceaf1746dba20997359","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2cb70ceaf1746dba20997359/native_gt.npz","filtered_start_offset":10,"expected_frame_ids":[70,71,72,73,74,75,76,77],"take":"subject1/o2/0/cam4","frame_ids":[70,71,72,73,74,75,76,77]} +{"filtered_tile_id":"2d0580d8cd4d2d45f0dc764e:0","filtered_window_id":"2d0580d8cd4d2d45f0dc764e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d0580d8cd4d2d45f0dc764e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject3/h2/2/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"2d0580d8cd4d2d45f0dc764e:8","filtered_window_id":"2d0580d8cd4d2d45f0dc764e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d0580d8cd4d2d45f0dc764e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject3/h2/2/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"2d0580d8cd4d2d45f0dc764e:16","filtered_window_id":"2d0580d8cd4d2d45f0dc764e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d0580d8cd4d2d45f0dc764e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject3/h2/2/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"2d0580d8cd4d2d45f0dc764e:24","filtered_window_id":"2d0580d8cd4d2d45f0dc764e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d0580d8cd4d2d45f0dc764e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject3/h2/2/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"2d0580d8cd4d2d45f0dc764e:32","filtered_window_id":"2d0580d8cd4d2d45f0dc764e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d0580d8cd4d2d45f0dc764e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject3/h2/2/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"2d0580d8cd4d2d45f0dc764e:40","filtered_window_id":"2d0580d8cd4d2d45f0dc764e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d0580d8cd4d2d45f0dc764e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject3/h2/2/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"2d0580d8cd4d2d45f0dc764e:48","filtered_window_id":"2d0580d8cd4d2d45f0dc764e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d0580d8cd4d2d45f0dc764e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject3/h2/2/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"2d0580d8cd4d2d45f0dc764e:52","filtered_window_id":"2d0580d8cd4d2d45f0dc764e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d0580d8cd4d2d45f0dc764e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject3/h2/2/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"2d48106f28593bdd00783fde:0","filtered_window_id":"2d48106f28593bdd00783fde","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d48106f28593bdd00783fde/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject1/o2/0/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"2d48106f28593bdd00783fde:8","filtered_window_id":"2d48106f28593bdd00783fde","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d48106f28593bdd00783fde/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject1/o2/0/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"2d48106f28593bdd00783fde:16","filtered_window_id":"2d48106f28593bdd00783fde","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d48106f28593bdd00783fde/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject1/o2/0/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"2d48106f28593bdd00783fde:24","filtered_window_id":"2d48106f28593bdd00783fde","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d48106f28593bdd00783fde/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject1/o2/0/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"2d48106f28593bdd00783fde:32","filtered_window_id":"2d48106f28593bdd00783fde","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d48106f28593bdd00783fde/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject1/o2/0/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"2d48106f28593bdd00783fde:40","filtered_window_id":"2d48106f28593bdd00783fde","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d48106f28593bdd00783fde/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject1/o2/0/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"2d48106f28593bdd00783fde:48","filtered_window_id":"2d48106f28593bdd00783fde","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d48106f28593bdd00783fde/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject1/o2/0/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"2d48106f28593bdd00783fde:52","filtered_window_id":"2d48106f28593bdd00783fde","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d48106f28593bdd00783fde/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[207,208,209,210,211,212,213,214],"take":"subject1/o2/0/cam4","frame_ids":[207,208,209,210,211,212,213,214]} +{"filtered_tile_id":"2d621c722477ed2687d67adb:0","filtered_window_id":"2d621c722477ed2687d67adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d621c722477ed2687d67adb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[292,293,294,295,296,297,298,299],"take":"subject2/k2/0/cam4","frame_ids":[292,293,294,295,296,297,298,299]} +{"filtered_tile_id":"2d621c722477ed2687d67adb:8","filtered_window_id":"2d621c722477ed2687d67adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d621c722477ed2687d67adb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[300,301,302,303,304,305,306,307],"take":"subject2/k2/0/cam4","frame_ids":[300,301,302,303,304,305,306,307]} +{"filtered_tile_id":"2d621c722477ed2687d67adb:16","filtered_window_id":"2d621c722477ed2687d67adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d621c722477ed2687d67adb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject2/k2/0/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"2d621c722477ed2687d67adb:24","filtered_window_id":"2d621c722477ed2687d67adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d621c722477ed2687d67adb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[316,317,318,319,320,321,322,323],"take":"subject2/k2/0/cam4","frame_ids":[316,317,318,319,320,321,322,323]} +{"filtered_tile_id":"2d621c722477ed2687d67adb:32","filtered_window_id":"2d621c722477ed2687d67adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d621c722477ed2687d67adb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject2/k2/0/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"2d621c722477ed2687d67adb:40","filtered_window_id":"2d621c722477ed2687d67adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d621c722477ed2687d67adb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject2/k2/0/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"2d621c722477ed2687d67adb:48","filtered_window_id":"2d621c722477ed2687d67adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d621c722477ed2687d67adb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[340,341,342,343,344,345,346,347],"take":"subject2/k2/0/cam4","frame_ids":[340,341,342,343,344,345,346,347]} +{"filtered_tile_id":"2d621c722477ed2687d67adb:52","filtered_window_id":"2d621c722477ed2687d67adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d621c722477ed2687d67adb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[344,345,346,347,348,349,350,351],"take":"subject2/k2/0/cam4","frame_ids":[344,345,346,347,348,349,350,351]} +{"filtered_tile_id":"2d668b813708b7f9ec6daa79:0","filtered_window_id":"2d668b813708b7f9ec6daa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d668b813708b7f9ec6daa79/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[530,531,532,533,534,535,536,537],"take":"subject3/k1/1/cam4","frame_ids":[530,531,532,533,534,535,536,537]} +{"filtered_tile_id":"2d668b813708b7f9ec6daa79:8","filtered_window_id":"2d668b813708b7f9ec6daa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d668b813708b7f9ec6daa79/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[538,539,540,541,542,543,544,545],"take":"subject3/k1/1/cam4","frame_ids":[538,539,540,541,542,543,544,545]} +{"filtered_tile_id":"2d668b813708b7f9ec6daa79:16","filtered_window_id":"2d668b813708b7f9ec6daa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d668b813708b7f9ec6daa79/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[546,547,548,549,550,551,552,553],"take":"subject3/k1/1/cam4","frame_ids":[546,547,548,549,550,551,552,553]} +{"filtered_tile_id":"2d668b813708b7f9ec6daa79:24","filtered_window_id":"2d668b813708b7f9ec6daa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d668b813708b7f9ec6daa79/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[554,555,556,557,558,559,560,561],"take":"subject3/k1/1/cam4","frame_ids":[554,555,556,557,558,559,560,561]} +{"filtered_tile_id":"2d668b813708b7f9ec6daa79:32","filtered_window_id":"2d668b813708b7f9ec6daa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d668b813708b7f9ec6daa79/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[562,563,564,565,566,567,568,569],"take":"subject3/k1/1/cam4","frame_ids":[562,563,564,565,566,567,568,569]} +{"filtered_tile_id":"2d668b813708b7f9ec6daa79:40","filtered_window_id":"2d668b813708b7f9ec6daa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d668b813708b7f9ec6daa79/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[570,571,572,573,574,575,576,577],"take":"subject3/k1/1/cam4","frame_ids":[570,571,572,573,574,575,576,577]} +{"filtered_tile_id":"2d668b813708b7f9ec6daa79:45","filtered_window_id":"2d668b813708b7f9ec6daa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2d668b813708b7f9ec6daa79/native_gt.npz","filtered_start_offset":45,"expected_frame_ids":[575,576,577,578,579,580,581,582],"take":"subject3/k1/1/cam4","frame_ids":[575,576,577,578,579,580,581,582]} +{"filtered_tile_id":"2e5c9dc4eff43d7135011dae:0","filtered_window_id":"2e5c9dc4eff43d7135011dae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2e5c9dc4eff43d7135011dae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject2/o1/6/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"2e5c9dc4eff43d7135011dae:8","filtered_window_id":"2e5c9dc4eff43d7135011dae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2e5c9dc4eff43d7135011dae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject2/o1/6/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"2e5c9dc4eff43d7135011dae:16","filtered_window_id":"2e5c9dc4eff43d7135011dae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2e5c9dc4eff43d7135011dae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject2/o1/6/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"2e5c9dc4eff43d7135011dae:24","filtered_window_id":"2e5c9dc4eff43d7135011dae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2e5c9dc4eff43d7135011dae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject2/o1/6/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"2e5c9dc4eff43d7135011dae:32","filtered_window_id":"2e5c9dc4eff43d7135011dae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2e5c9dc4eff43d7135011dae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject2/o1/6/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"2e5c9dc4eff43d7135011dae:40","filtered_window_id":"2e5c9dc4eff43d7135011dae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2e5c9dc4eff43d7135011dae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject2/o1/6/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"2e5c9dc4eff43d7135011dae:48","filtered_window_id":"2e5c9dc4eff43d7135011dae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2e5c9dc4eff43d7135011dae/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject2/o1/6/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"2e5c9dc4eff43d7135011dae:52","filtered_window_id":"2e5c9dc4eff43d7135011dae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2e5c9dc4eff43d7135011dae/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject2/o1/6/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"2eab53df8bb7942ac07ec62b:0","filtered_window_id":"2eab53df8bb7942ac07ec62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2eab53df8bb7942ac07ec62b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject2/h1/0/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"2eab53df8bb7942ac07ec62b:8","filtered_window_id":"2eab53df8bb7942ac07ec62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2eab53df8bb7942ac07ec62b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject2/h1/0/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"2eab53df8bb7942ac07ec62b:16","filtered_window_id":"2eab53df8bb7942ac07ec62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2eab53df8bb7942ac07ec62b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject2/h1/0/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"2eab53df8bb7942ac07ec62b:24","filtered_window_id":"2eab53df8bb7942ac07ec62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2eab53df8bb7942ac07ec62b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject2/h1/0/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"2eab53df8bb7942ac07ec62b:32","filtered_window_id":"2eab53df8bb7942ac07ec62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2eab53df8bb7942ac07ec62b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject2/h1/0/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"2eab53df8bb7942ac07ec62b:40","filtered_window_id":"2eab53df8bb7942ac07ec62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2eab53df8bb7942ac07ec62b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject2/h1/0/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"2eab53df8bb7942ac07ec62b:48","filtered_window_id":"2eab53df8bb7942ac07ec62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2eab53df8bb7942ac07ec62b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject2/h1/0/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"2eab53df8bb7942ac07ec62b:52","filtered_window_id":"2eab53df8bb7942ac07ec62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2eab53df8bb7942ac07ec62b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject2/h1/0/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"2ec03e2cd44d417ddf8c0ff7:0","filtered_window_id":"2ec03e2cd44d417ddf8c0ff7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ec03e2cd44d417ddf8c0ff7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[618,619,620,621,622,623,624,625],"take":"subject3/k1/2/cam4","frame_ids":[618,619,620,621,622,623,624,625]} +{"filtered_tile_id":"2ec03e2cd44d417ddf8c0ff7:8","filtered_window_id":"2ec03e2cd44d417ddf8c0ff7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ec03e2cd44d417ddf8c0ff7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[626,627,628,629,630,631,632,633],"take":"subject3/k1/2/cam4","frame_ids":[626,627,628,629,630,631,632,633]} +{"filtered_tile_id":"2ec03e2cd44d417ddf8c0ff7:16","filtered_window_id":"2ec03e2cd44d417ddf8c0ff7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ec03e2cd44d417ddf8c0ff7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[634,635,636,637,638,639,640,641],"take":"subject3/k1/2/cam4","frame_ids":[634,635,636,637,638,639,640,641]} +{"filtered_tile_id":"2ec03e2cd44d417ddf8c0ff7:24","filtered_window_id":"2ec03e2cd44d417ddf8c0ff7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ec03e2cd44d417ddf8c0ff7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[642,643,644,645,646,647,648,649],"take":"subject3/k1/2/cam4","frame_ids":[642,643,644,645,646,647,648,649]} +{"filtered_tile_id":"2ec03e2cd44d417ddf8c0ff7:32","filtered_window_id":"2ec03e2cd44d417ddf8c0ff7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ec03e2cd44d417ddf8c0ff7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[650,651,652,653,654,655,656,657],"take":"subject3/k1/2/cam4","frame_ids":[650,651,652,653,654,655,656,657]} +{"filtered_tile_id":"2ec03e2cd44d417ddf8c0ff7:40","filtered_window_id":"2ec03e2cd44d417ddf8c0ff7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ec03e2cd44d417ddf8c0ff7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[658,659,660,661,662,663,664,665],"take":"subject3/k1/2/cam4","frame_ids":[658,659,660,661,662,663,664,665]} +{"filtered_tile_id":"2ec03e2cd44d417ddf8c0ff7:48","filtered_window_id":"2ec03e2cd44d417ddf8c0ff7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ec03e2cd44d417ddf8c0ff7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[666,667,668,669,670,671,672,673],"take":"subject3/k1/2/cam4","frame_ids":[666,667,668,669,670,671,672,673]} +{"filtered_tile_id":"2ec03e2cd44d417ddf8c0ff7:52","filtered_window_id":"2ec03e2cd44d417ddf8c0ff7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ec03e2cd44d417ddf8c0ff7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[670,671,672,673,674,675,676,677],"take":"subject3/k1/2/cam4","frame_ids":[670,671,672,673,674,675,676,677]} +{"filtered_tile_id":"2edd5c92b4132c9df626aeb4:0","filtered_window_id":"2edd5c92b4132c9df626aeb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2edd5c92b4132c9df626aeb4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject2/h2/5/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"2edd5c92b4132c9df626aeb4:5","filtered_window_id":"2edd5c92b4132c9df626aeb4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2edd5c92b4132c9df626aeb4/native_gt.npz","filtered_start_offset":5,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject2/h2/5/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"2ee78203140834e965fbfd84:0","filtered_window_id":"2ee78203140834e965fbfd84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ee78203140834e965fbfd84/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject1/h2/6/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"2ee78203140834e965fbfd84:8","filtered_window_id":"2ee78203140834e965fbfd84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ee78203140834e965fbfd84/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject1/h2/6/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"2ee78203140834e965fbfd84:16","filtered_window_id":"2ee78203140834e965fbfd84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ee78203140834e965fbfd84/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject1/h2/6/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"2ee78203140834e965fbfd84:24","filtered_window_id":"2ee78203140834e965fbfd84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ee78203140834e965fbfd84/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject1/h2/6/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"2ee78203140834e965fbfd84:32","filtered_window_id":"2ee78203140834e965fbfd84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ee78203140834e965fbfd84/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject1/h2/6/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"2ee78203140834e965fbfd84:40","filtered_window_id":"2ee78203140834e965fbfd84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ee78203140834e965fbfd84/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject1/h2/6/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"2ee78203140834e965fbfd84:48","filtered_window_id":"2ee78203140834e965fbfd84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ee78203140834e965fbfd84/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject1/h2/6/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"2ee78203140834e965fbfd84:52","filtered_window_id":"2ee78203140834e965fbfd84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2ee78203140834e965fbfd84/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject1/h2/6/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"2f40acf82d91c5ba47a47e60:0","filtered_window_id":"2f40acf82d91c5ba47a47e60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2f40acf82d91c5ba47a47e60/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[581,582,583,584,585,586,587,588],"take":"subject2/o1/1/cam4","frame_ids":[581,582,583,584,585,586,587,588]} +{"filtered_tile_id":"2f40acf82d91c5ba47a47e60:8","filtered_window_id":"2f40acf82d91c5ba47a47e60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2f40acf82d91c5ba47a47e60/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[589,590,591,592,593,594,595,596],"take":"subject2/o1/1/cam4","frame_ids":[589,590,591,592,593,594,595,596]} +{"filtered_tile_id":"2f40acf82d91c5ba47a47e60:16","filtered_window_id":"2f40acf82d91c5ba47a47e60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2f40acf82d91c5ba47a47e60/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[597,598,599,600,601,602,603,604],"take":"subject2/o1/1/cam4","frame_ids":[597,598,599,600,601,602,603,604]} +{"filtered_tile_id":"2f40acf82d91c5ba47a47e60:24","filtered_window_id":"2f40acf82d91c5ba47a47e60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2f40acf82d91c5ba47a47e60/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[605,606,607,608,609,610,611,612],"take":"subject2/o1/1/cam4","frame_ids":[605,606,607,608,609,610,611,612]} +{"filtered_tile_id":"2f40acf82d91c5ba47a47e60:32","filtered_window_id":"2f40acf82d91c5ba47a47e60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2f40acf82d91c5ba47a47e60/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[613,614,615,616,617,618,619,620],"take":"subject2/o1/1/cam4","frame_ids":[613,614,615,616,617,618,619,620]} +{"filtered_tile_id":"2f40acf82d91c5ba47a47e60:40","filtered_window_id":"2f40acf82d91c5ba47a47e60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2f40acf82d91c5ba47a47e60/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[621,622,623,624,625,626,627,628],"take":"subject2/o1/1/cam4","frame_ids":[621,622,623,624,625,626,627,628]} +{"filtered_tile_id":"2f40acf82d91c5ba47a47e60:48","filtered_window_id":"2f40acf82d91c5ba47a47e60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2f40acf82d91c5ba47a47e60/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[629,630,631,632,633,634,635,636],"take":"subject2/o1/1/cam4","frame_ids":[629,630,631,632,633,634,635,636]} +{"filtered_tile_id":"2f40acf82d91c5ba47a47e60:52","filtered_window_id":"2f40acf82d91c5ba47a47e60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2f40acf82d91c5ba47a47e60/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[633,634,635,636,637,638,639,640],"take":"subject2/o1/1/cam4","frame_ids":[633,634,635,636,637,638,639,640]} +{"filtered_tile_id":"2fa7e81c9608ce3b84b9ac9b:0","filtered_window_id":"2fa7e81c9608ce3b84b9ac9b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fa7e81c9608ce3b84b9ac9b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject2/h1/1/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"2fa7e81c9608ce3b84b9ac9b:8","filtered_window_id":"2fa7e81c9608ce3b84b9ac9b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fa7e81c9608ce3b84b9ac9b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject2/h1/1/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"2fa7e81c9608ce3b84b9ac9b:16","filtered_window_id":"2fa7e81c9608ce3b84b9ac9b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fa7e81c9608ce3b84b9ac9b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject2/h1/1/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"2fa7e81c9608ce3b84b9ac9b:24","filtered_window_id":"2fa7e81c9608ce3b84b9ac9b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fa7e81c9608ce3b84b9ac9b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[572,573,574,575,576,577,578,579],"take":"subject2/h1/1/cam4","frame_ids":[572,573,574,575,576,577,578,579]} +{"filtered_tile_id":"2fa7e81c9608ce3b84b9ac9b:32","filtered_window_id":"2fa7e81c9608ce3b84b9ac9b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fa7e81c9608ce3b84b9ac9b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[580,581,582,583,584,585,586,587],"take":"subject2/h1/1/cam4","frame_ids":[580,581,582,583,584,585,586,587]} +{"filtered_tile_id":"2fa7e81c9608ce3b84b9ac9b:40","filtered_window_id":"2fa7e81c9608ce3b84b9ac9b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fa7e81c9608ce3b84b9ac9b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[588,589,590,591,592,593,594,595],"take":"subject2/h1/1/cam4","frame_ids":[588,589,590,591,592,593,594,595]} +{"filtered_tile_id":"2fa7e81c9608ce3b84b9ac9b:48","filtered_window_id":"2fa7e81c9608ce3b84b9ac9b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fa7e81c9608ce3b84b9ac9b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[596,597,598,599,600,601,602,603],"take":"subject2/h1/1/cam4","frame_ids":[596,597,598,599,600,601,602,603]} +{"filtered_tile_id":"2fa7e81c9608ce3b84b9ac9b:52","filtered_window_id":"2fa7e81c9608ce3b84b9ac9b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fa7e81c9608ce3b84b9ac9b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[600,601,602,603,604,605,606,607],"take":"subject2/h1/1/cam4","frame_ids":[600,601,602,603,604,605,606,607]} +{"filtered_tile_id":"2fc697874b6409ca44e7ea81:0","filtered_window_id":"2fc697874b6409ca44e7ea81","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fc697874b6409ca44e7ea81/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[74,75,76,77,78,79,80,81],"take":"subject2/k2/5/cam4","frame_ids":[74,75,76,77,78,79,80,81]} +{"filtered_tile_id":"2fc697874b6409ca44e7ea81:4","filtered_window_id":"2fc697874b6409ca44e7ea81","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fc697874b6409ca44e7ea81/native_gt.npz","filtered_start_offset":4,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject2/k2/5/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"2fee5db92eb2a0db16da8340:0","filtered_window_id":"2fee5db92eb2a0db16da8340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fee5db92eb2a0db16da8340/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[302,303,304,305,306,307,308,309],"take":"subject1/o2/3/cam4","frame_ids":[302,303,304,305,306,307,308,309]} +{"filtered_tile_id":"2fee5db92eb2a0db16da8340:8","filtered_window_id":"2fee5db92eb2a0db16da8340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fee5db92eb2a0db16da8340/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject1/o2/3/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"2fee5db92eb2a0db16da8340:16","filtered_window_id":"2fee5db92eb2a0db16da8340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fee5db92eb2a0db16da8340/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject1/o2/3/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"2fee5db92eb2a0db16da8340:24","filtered_window_id":"2fee5db92eb2a0db16da8340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fee5db92eb2a0db16da8340/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject1/o2/3/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"2fee5db92eb2a0db16da8340:32","filtered_window_id":"2fee5db92eb2a0db16da8340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fee5db92eb2a0db16da8340/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject1/o2/3/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"2fee5db92eb2a0db16da8340:40","filtered_window_id":"2fee5db92eb2a0db16da8340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fee5db92eb2a0db16da8340/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject1/o2/3/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"2fee5db92eb2a0db16da8340:48","filtered_window_id":"2fee5db92eb2a0db16da8340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fee5db92eb2a0db16da8340/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject1/o2/3/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"2fee5db92eb2a0db16da8340:52","filtered_window_id":"2fee5db92eb2a0db16da8340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/2fee5db92eb2a0db16da8340/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[354,355,356,357,358,359,360,361],"take":"subject1/o2/3/cam4","frame_ids":[354,355,356,357,358,359,360,361]} +{"filtered_tile_id":"3034abdddf6e72cfd39bf47b:0","filtered_window_id":"3034abdddf6e72cfd39bf47b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3034abdddf6e72cfd39bf47b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject2/o2/5/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"3034abdddf6e72cfd39bf47b:8","filtered_window_id":"3034abdddf6e72cfd39bf47b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3034abdddf6e72cfd39bf47b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject2/o2/5/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"3034abdddf6e72cfd39bf47b:16","filtered_window_id":"3034abdddf6e72cfd39bf47b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3034abdddf6e72cfd39bf47b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject2/o2/5/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"3034abdddf6e72cfd39bf47b:24","filtered_window_id":"3034abdddf6e72cfd39bf47b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3034abdddf6e72cfd39bf47b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[296,297,298,299,300,301,302,303],"take":"subject2/o2/5/cam4","frame_ids":[296,297,298,299,300,301,302,303]} +{"filtered_tile_id":"3034abdddf6e72cfd39bf47b:32","filtered_window_id":"3034abdddf6e72cfd39bf47b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3034abdddf6e72cfd39bf47b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[304,305,306,307,308,309,310,311],"take":"subject2/o2/5/cam4","frame_ids":[304,305,306,307,308,309,310,311]} +{"filtered_tile_id":"3034abdddf6e72cfd39bf47b:40","filtered_window_id":"3034abdddf6e72cfd39bf47b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3034abdddf6e72cfd39bf47b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[312,313,314,315,316,317,318,319],"take":"subject2/o2/5/cam4","frame_ids":[312,313,314,315,316,317,318,319]} +{"filtered_tile_id":"3034abdddf6e72cfd39bf47b:48","filtered_window_id":"3034abdddf6e72cfd39bf47b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3034abdddf6e72cfd39bf47b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[320,321,322,323,324,325,326,327],"take":"subject2/o2/5/cam4","frame_ids":[320,321,322,323,324,325,326,327]} +{"filtered_tile_id":"3034abdddf6e72cfd39bf47b:52","filtered_window_id":"3034abdddf6e72cfd39bf47b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3034abdddf6e72cfd39bf47b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject2/o2/5/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"30d65c0a7ccf938ae269c8e9:0","filtered_window_id":"30d65c0a7ccf938ae269c8e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30d65c0a7ccf938ae269c8e9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject1/k2/1/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"30d65c0a7ccf938ae269c8e9:8","filtered_window_id":"30d65c0a7ccf938ae269c8e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30d65c0a7ccf938ae269c8e9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject1/k2/1/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"30d65c0a7ccf938ae269c8e9:16","filtered_window_id":"30d65c0a7ccf938ae269c8e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30d65c0a7ccf938ae269c8e9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject1/k2/1/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"30d65c0a7ccf938ae269c8e9:24","filtered_window_id":"30d65c0a7ccf938ae269c8e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30d65c0a7ccf938ae269c8e9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject1/k2/1/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"30d65c0a7ccf938ae269c8e9:32","filtered_window_id":"30d65c0a7ccf938ae269c8e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30d65c0a7ccf938ae269c8e9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject1/k2/1/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"30d65c0a7ccf938ae269c8e9:40","filtered_window_id":"30d65c0a7ccf938ae269c8e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30d65c0a7ccf938ae269c8e9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject1/k2/1/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"30d65c0a7ccf938ae269c8e9:44","filtered_window_id":"30d65c0a7ccf938ae269c8e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30d65c0a7ccf938ae269c8e9/native_gt.npz","filtered_start_offset":44,"expected_frame_ids":[218,219,220,221,222,223,224,225],"take":"subject1/k2/1/cam4","frame_ids":[218,219,220,221,222,223,224,225]} +{"filtered_tile_id":"30e4d83c2e844491bee76d2f:0","filtered_window_id":"30e4d83c2e844491bee76d2f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30e4d83c2e844491bee76d2f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[54,55,56,57,58,59,60,61],"take":"subject1/h2/1/cam4","frame_ids":[54,55,56,57,58,59,60,61]} +{"filtered_tile_id":"30e4d83c2e844491bee76d2f:8","filtered_window_id":"30e4d83c2e844491bee76d2f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30e4d83c2e844491bee76d2f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[62,63,64,65,66,67,68,69],"take":"subject1/h2/1/cam4","frame_ids":[62,63,64,65,66,67,68,69]} +{"filtered_tile_id":"30e4d83c2e844491bee76d2f:16","filtered_window_id":"30e4d83c2e844491bee76d2f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30e4d83c2e844491bee76d2f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[70,71,72,73,74,75,76,77],"take":"subject1/h2/1/cam4","frame_ids":[70,71,72,73,74,75,76,77]} +{"filtered_tile_id":"30e4d83c2e844491bee76d2f:24","filtered_window_id":"30e4d83c2e844491bee76d2f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30e4d83c2e844491bee76d2f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject1/h2/1/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"30e4d83c2e844491bee76d2f:32","filtered_window_id":"30e4d83c2e844491bee76d2f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30e4d83c2e844491bee76d2f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[86,87,88,89,90,91,92,93],"take":"subject1/h2/1/cam4","frame_ids":[86,87,88,89,90,91,92,93]} +{"filtered_tile_id":"30e4d83c2e844491bee76d2f:40","filtered_window_id":"30e4d83c2e844491bee76d2f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30e4d83c2e844491bee76d2f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[94,95,96,97,98,99,100,101],"take":"subject1/h2/1/cam4","frame_ids":[94,95,96,97,98,99,100,101]} +{"filtered_tile_id":"30e4d83c2e844491bee76d2f:48","filtered_window_id":"30e4d83c2e844491bee76d2f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30e4d83c2e844491bee76d2f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[102,103,104,105,106,107,108,109],"take":"subject1/h2/1/cam4","frame_ids":[102,103,104,105,106,107,108,109]} +{"filtered_tile_id":"30e4d83c2e844491bee76d2f:50","filtered_window_id":"30e4d83c2e844491bee76d2f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/30e4d83c2e844491bee76d2f/native_gt.npz","filtered_start_offset":50,"expected_frame_ids":[104,105,106,107,108,109,110,111],"take":"subject1/h2/1/cam4","frame_ids":[104,105,106,107,108,109,110,111]} +{"filtered_tile_id":"314febca3f817374f02e50a1:0","filtered_window_id":"314febca3f817374f02e50a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/314febca3f817374f02e50a1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[194,195,196,197,198,199,200,201],"take":"subject3/k1/7/cam4","frame_ids":[194,195,196,197,198,199,200,201]} +{"filtered_tile_id":"314febca3f817374f02e50a1:8","filtered_window_id":"314febca3f817374f02e50a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/314febca3f817374f02e50a1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[202,203,204,205,206,207,208,209],"take":"subject3/k1/7/cam4","frame_ids":[202,203,204,205,206,207,208,209]} +{"filtered_tile_id":"314febca3f817374f02e50a1:16","filtered_window_id":"314febca3f817374f02e50a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/314febca3f817374f02e50a1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[210,211,212,213,214,215,216,217],"take":"subject3/k1/7/cam4","frame_ids":[210,211,212,213,214,215,216,217]} +{"filtered_tile_id":"314febca3f817374f02e50a1:24","filtered_window_id":"314febca3f817374f02e50a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/314febca3f817374f02e50a1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[218,219,220,221,222,223,224,225],"take":"subject3/k1/7/cam4","frame_ids":[218,219,220,221,222,223,224,225]} +{"filtered_tile_id":"314febca3f817374f02e50a1:32","filtered_window_id":"314febca3f817374f02e50a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/314febca3f817374f02e50a1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject3/k1/7/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"314febca3f817374f02e50a1:40","filtered_window_id":"314febca3f817374f02e50a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/314febca3f817374f02e50a1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject3/k1/7/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"314febca3f817374f02e50a1:48","filtered_window_id":"314febca3f817374f02e50a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/314febca3f817374f02e50a1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject3/k1/7/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"314febca3f817374f02e50a1:52","filtered_window_id":"314febca3f817374f02e50a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/314febca3f817374f02e50a1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[246,247,248,249,250,251,252,253],"take":"subject3/k1/7/cam4","frame_ids":[246,247,248,249,250,251,252,253]} +{"filtered_tile_id":"315ed08e19141da60d03100e:0","filtered_window_id":"315ed08e19141da60d03100e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/315ed08e19141da60d03100e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[215,216,217,218,219,220,221,222],"take":"subject1/k1/4/cam4","frame_ids":[215,216,217,218,219,220,221,222]} +{"filtered_tile_id":"315ed08e19141da60d03100e:8","filtered_window_id":"315ed08e19141da60d03100e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/315ed08e19141da60d03100e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject1/k1/4/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"315ed08e19141da60d03100e:16","filtered_window_id":"315ed08e19141da60d03100e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/315ed08e19141da60d03100e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject1/k1/4/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"315ed08e19141da60d03100e:24","filtered_window_id":"315ed08e19141da60d03100e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/315ed08e19141da60d03100e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject1/k1/4/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"315ed08e19141da60d03100e:32","filtered_window_id":"315ed08e19141da60d03100e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/315ed08e19141da60d03100e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject1/k1/4/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"315ed08e19141da60d03100e:40","filtered_window_id":"315ed08e19141da60d03100e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/315ed08e19141da60d03100e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[255,256,257,258,259,260,261,262],"take":"subject1/k1/4/cam4","frame_ids":[255,256,257,258,259,260,261,262]} +{"filtered_tile_id":"315ed08e19141da60d03100e:48","filtered_window_id":"315ed08e19141da60d03100e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/315ed08e19141da60d03100e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject1/k1/4/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"315ed08e19141da60d03100e:52","filtered_window_id":"315ed08e19141da60d03100e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/315ed08e19141da60d03100e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[267,268,269,270,271,272,273,274],"take":"subject1/k1/4/cam4","frame_ids":[267,268,269,270,271,272,273,274]} +{"filtered_tile_id":"31b907b872dc457a42d79d76:0","filtered_window_id":"31b907b872dc457a42d79d76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/31b907b872dc457a42d79d76/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject1/h2/3/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"31b907b872dc457a42d79d76:8","filtered_window_id":"31b907b872dc457a42d79d76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/31b907b872dc457a42d79d76/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[93,94,95,96,97,98,99,100],"take":"subject1/h2/3/cam4","frame_ids":[93,94,95,96,97,98,99,100]} +{"filtered_tile_id":"31b907b872dc457a42d79d76:16","filtered_window_id":"31b907b872dc457a42d79d76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/31b907b872dc457a42d79d76/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[101,102,103,104,105,106,107,108],"take":"subject1/h2/3/cam4","frame_ids":[101,102,103,104,105,106,107,108]} +{"filtered_tile_id":"31b907b872dc457a42d79d76:24","filtered_window_id":"31b907b872dc457a42d79d76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/31b907b872dc457a42d79d76/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[109,110,111,112,113,114,115,116],"take":"subject1/h2/3/cam4","frame_ids":[109,110,111,112,113,114,115,116]} +{"filtered_tile_id":"31b907b872dc457a42d79d76:32","filtered_window_id":"31b907b872dc457a42d79d76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/31b907b872dc457a42d79d76/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[117,118,119,120,121,122,123,124],"take":"subject1/h2/3/cam4","frame_ids":[117,118,119,120,121,122,123,124]} +{"filtered_tile_id":"31b907b872dc457a42d79d76:39","filtered_window_id":"31b907b872dc457a42d79d76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/31b907b872dc457a42d79d76/native_gt.npz","filtered_start_offset":39,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject1/h2/3/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"3245342febb70ce12175d1c8:0","filtered_window_id":"3245342febb70ce12175d1c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3245342febb70ce12175d1c8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject2/k1/6/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"3245342febb70ce12175d1c8:8","filtered_window_id":"3245342febb70ce12175d1c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3245342febb70ce12175d1c8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[53,54,55,56,57,58,59,60],"take":"subject2/k1/6/cam4","frame_ids":[53,54,55,56,57,58,59,60]} +{"filtered_tile_id":"3245342febb70ce12175d1c8:16","filtered_window_id":"3245342febb70ce12175d1c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3245342febb70ce12175d1c8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[61,62,63,64,65,66,67,68],"take":"subject2/k1/6/cam4","frame_ids":[61,62,63,64,65,66,67,68]} +{"filtered_tile_id":"3245342febb70ce12175d1c8:24","filtered_window_id":"3245342febb70ce12175d1c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3245342febb70ce12175d1c8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject2/k1/6/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"3245342febb70ce12175d1c8:32","filtered_window_id":"3245342febb70ce12175d1c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3245342febb70ce12175d1c8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[77,78,79,80,81,82,83,84],"take":"subject2/k1/6/cam4","frame_ids":[77,78,79,80,81,82,83,84]} +{"filtered_tile_id":"3245342febb70ce12175d1c8:40","filtered_window_id":"3245342febb70ce12175d1c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3245342febb70ce12175d1c8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject2/k1/6/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"3245342febb70ce12175d1c8:48","filtered_window_id":"3245342febb70ce12175d1c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3245342febb70ce12175d1c8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[93,94,95,96,97,98,99,100],"take":"subject2/k1/6/cam4","frame_ids":[93,94,95,96,97,98,99,100]} +{"filtered_tile_id":"3245342febb70ce12175d1c8:52","filtered_window_id":"3245342febb70ce12175d1c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3245342febb70ce12175d1c8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[97,98,99,100,101,102,103,104],"take":"subject2/k1/6/cam4","frame_ids":[97,98,99,100,101,102,103,104]} +{"filtered_tile_id":"324673aebf5d7dd9a6b2e64e:0","filtered_window_id":"324673aebf5d7dd9a6b2e64e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/324673aebf5d7dd9a6b2e64e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[647,648,649,650,651,652,653,654],"take":"subject1/o2/1/cam4","frame_ids":[647,648,649,650,651,652,653,654]} +{"filtered_tile_id":"324673aebf5d7dd9a6b2e64e:8","filtered_window_id":"324673aebf5d7dd9a6b2e64e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/324673aebf5d7dd9a6b2e64e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[655,656,657,658,659,660,661,662],"take":"subject1/o2/1/cam4","frame_ids":[655,656,657,658,659,660,661,662]} +{"filtered_tile_id":"324673aebf5d7dd9a6b2e64e:13","filtered_window_id":"324673aebf5d7dd9a6b2e64e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/324673aebf5d7dd9a6b2e64e/native_gt.npz","filtered_start_offset":13,"expected_frame_ids":[660,661,662,663,664,665,666,667],"take":"subject1/o2/1/cam4","frame_ids":[660,661,662,663,664,665,666,667]} +{"filtered_tile_id":"326fcd1efdf0e1c082fa2610:0","filtered_window_id":"326fcd1efdf0e1c082fa2610","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/326fcd1efdf0e1c082fa2610/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject3/k1/1/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"326fcd1efdf0e1c082fa2610:8","filtered_window_id":"326fcd1efdf0e1c082fa2610","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/326fcd1efdf0e1c082fa2610/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject3/k1/1/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"326fcd1efdf0e1c082fa2610:16","filtered_window_id":"326fcd1efdf0e1c082fa2610","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/326fcd1efdf0e1c082fa2610/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject3/k1/1/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"326fcd1efdf0e1c082fa2610:24","filtered_window_id":"326fcd1efdf0e1c082fa2610","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/326fcd1efdf0e1c082fa2610/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[374,375,376,377,378,379,380,381],"take":"subject3/k1/1/cam4","frame_ids":[374,375,376,377,378,379,380,381]} +{"filtered_tile_id":"326fcd1efdf0e1c082fa2610:32","filtered_window_id":"326fcd1efdf0e1c082fa2610","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/326fcd1efdf0e1c082fa2610/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[382,383,384,385,386,387,388,389],"take":"subject3/k1/1/cam4","frame_ids":[382,383,384,385,386,387,388,389]} +{"filtered_tile_id":"326fcd1efdf0e1c082fa2610:40","filtered_window_id":"326fcd1efdf0e1c082fa2610","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/326fcd1efdf0e1c082fa2610/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject3/k1/1/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"326fcd1efdf0e1c082fa2610:48","filtered_window_id":"326fcd1efdf0e1c082fa2610","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/326fcd1efdf0e1c082fa2610/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[398,399,400,401,402,403,404,405],"take":"subject3/k1/1/cam4","frame_ids":[398,399,400,401,402,403,404,405]} +{"filtered_tile_id":"326fcd1efdf0e1c082fa2610:52","filtered_window_id":"326fcd1efdf0e1c082fa2610","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/326fcd1efdf0e1c082fa2610/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[402,403,404,405,406,407,408,409],"take":"subject3/k1/1/cam4","frame_ids":[402,403,404,405,406,407,408,409]} +{"filtered_tile_id":"331b07c9e64d5aeb68f6ad6e:0","filtered_window_id":"331b07c9e64d5aeb68f6ad6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/331b07c9e64d5aeb68f6ad6e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[960,961,962,963,964,965,966,967],"take":"subject2/o1/2/cam4","frame_ids":[960,961,962,963,964,965,966,967]} +{"filtered_tile_id":"331b07c9e64d5aeb68f6ad6e:8","filtered_window_id":"331b07c9e64d5aeb68f6ad6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/331b07c9e64d5aeb68f6ad6e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[968,969,970,971,972,973,974,975],"take":"subject2/o1/2/cam4","frame_ids":[968,969,970,971,972,973,974,975]} +{"filtered_tile_id":"331b07c9e64d5aeb68f6ad6e:16","filtered_window_id":"331b07c9e64d5aeb68f6ad6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/331b07c9e64d5aeb68f6ad6e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[976,977,978,979,980,981,982,983],"take":"subject2/o1/2/cam4","frame_ids":[976,977,978,979,980,981,982,983]} +{"filtered_tile_id":"331b07c9e64d5aeb68f6ad6e:24","filtered_window_id":"331b07c9e64d5aeb68f6ad6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/331b07c9e64d5aeb68f6ad6e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[984,985,986,987,988,989,990,991],"take":"subject2/o1/2/cam4","frame_ids":[984,985,986,987,988,989,990,991]} +{"filtered_tile_id":"331b07c9e64d5aeb68f6ad6e:32","filtered_window_id":"331b07c9e64d5aeb68f6ad6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/331b07c9e64d5aeb68f6ad6e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[992,993,994,995,996,997,998,999],"take":"subject2/o1/2/cam4","frame_ids":[992,993,994,995,996,997,998,999]} +{"filtered_tile_id":"331b07c9e64d5aeb68f6ad6e:40","filtered_window_id":"331b07c9e64d5aeb68f6ad6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/331b07c9e64d5aeb68f6ad6e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[1000,1001,1002,1003,1004,1005,1006,1007],"take":"subject2/o1/2/cam4","frame_ids":[1000,1001,1002,1003,1004,1005,1006,1007]} +{"filtered_tile_id":"331b07c9e64d5aeb68f6ad6e:48","filtered_window_id":"331b07c9e64d5aeb68f6ad6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/331b07c9e64d5aeb68f6ad6e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[1008,1009,1010,1011,1012,1013,1014,1015],"take":"subject2/o1/2/cam4","frame_ids":[1008,1009,1010,1011,1012,1013,1014,1015]} +{"filtered_tile_id":"331b07c9e64d5aeb68f6ad6e:52","filtered_window_id":"331b07c9e64d5aeb68f6ad6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/331b07c9e64d5aeb68f6ad6e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[1012,1013,1014,1015,1016,1017,1018,1019],"take":"subject2/o1/2/cam4","frame_ids":[1012,1013,1014,1015,1016,1017,1018,1019]} +{"filtered_tile_id":"33584ce199a15a812c107d4b:0","filtered_window_id":"33584ce199a15a812c107d4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33584ce199a15a812c107d4b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[587,588,589,590,591,592,593,594],"take":"subject1/o1/3/cam4","frame_ids":[587,588,589,590,591,592,593,594]} +{"filtered_tile_id":"33584ce199a15a812c107d4b:3","filtered_window_id":"33584ce199a15a812c107d4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33584ce199a15a812c107d4b/native_gt.npz","filtered_start_offset":3,"expected_frame_ids":[590,591,592,593,594,595,596,597],"take":"subject1/o1/3/cam4","frame_ids":[590,591,592,593,594,595,596,597]} +{"filtered_tile_id":"33fb64f34e35c6448e024602:0","filtered_window_id":"33fb64f34e35c6448e024602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb64f34e35c6448e024602/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[347,348,349,350,351,352,353,354],"take":"subject2/k1/1/cam4","frame_ids":[347,348,349,350,351,352,353,354]} +{"filtered_tile_id":"33fb64f34e35c6448e024602:8","filtered_window_id":"33fb64f34e35c6448e024602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb64f34e35c6448e024602/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[355,356,357,358,359,360,361,362],"take":"subject2/k1/1/cam4","frame_ids":[355,356,357,358,359,360,361,362]} +{"filtered_tile_id":"33fb64f34e35c6448e024602:16","filtered_window_id":"33fb64f34e35c6448e024602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb64f34e35c6448e024602/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[363,364,365,366,367,368,369,370],"take":"subject2/k1/1/cam4","frame_ids":[363,364,365,366,367,368,369,370]} +{"filtered_tile_id":"33fb64f34e35c6448e024602:24","filtered_window_id":"33fb64f34e35c6448e024602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb64f34e35c6448e024602/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[371,372,373,374,375,376,377,378],"take":"subject2/k1/1/cam4","frame_ids":[371,372,373,374,375,376,377,378]} +{"filtered_tile_id":"33fb64f34e35c6448e024602:32","filtered_window_id":"33fb64f34e35c6448e024602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb64f34e35c6448e024602/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[379,380,381,382,383,384,385,386],"take":"subject2/k1/1/cam4","frame_ids":[379,380,381,382,383,384,385,386]} +{"filtered_tile_id":"33fb64f34e35c6448e024602:40","filtered_window_id":"33fb64f34e35c6448e024602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb64f34e35c6448e024602/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[387,388,389,390,391,392,393,394],"take":"subject2/k1/1/cam4","frame_ids":[387,388,389,390,391,392,393,394]} +{"filtered_tile_id":"33fb64f34e35c6448e024602:48","filtered_window_id":"33fb64f34e35c6448e024602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb64f34e35c6448e024602/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject2/k1/1/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"33fb64f34e35c6448e024602:52","filtered_window_id":"33fb64f34e35c6448e024602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb64f34e35c6448e024602/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject2/k1/1/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"33fb9f6cefd2ffbe3fabc261:0","filtered_window_id":"33fb9f6cefd2ffbe3fabc261","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb9f6cefd2ffbe3fabc261/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject2/k2/6/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"33fb9f6cefd2ffbe3fabc261:8","filtered_window_id":"33fb9f6cefd2ffbe3fabc261","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb9f6cefd2ffbe3fabc261/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject2/k2/6/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"33fb9f6cefd2ffbe3fabc261:16","filtered_window_id":"33fb9f6cefd2ffbe3fabc261","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb9f6cefd2ffbe3fabc261/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject2/k2/6/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"33fb9f6cefd2ffbe3fabc261:24","filtered_window_id":"33fb9f6cefd2ffbe3fabc261","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb9f6cefd2ffbe3fabc261/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject2/k2/6/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"33fb9f6cefd2ffbe3fabc261:32","filtered_window_id":"33fb9f6cefd2ffbe3fabc261","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb9f6cefd2ffbe3fabc261/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject2/k2/6/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"33fb9f6cefd2ffbe3fabc261:40","filtered_window_id":"33fb9f6cefd2ffbe3fabc261","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb9f6cefd2ffbe3fabc261/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject2/k2/6/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"33fb9f6cefd2ffbe3fabc261:48","filtered_window_id":"33fb9f6cefd2ffbe3fabc261","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb9f6cefd2ffbe3fabc261/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[361,362,363,364,365,366,367,368],"take":"subject2/k2/6/cam4","frame_ids":[361,362,363,364,365,366,367,368]} +{"filtered_tile_id":"33fb9f6cefd2ffbe3fabc261:52","filtered_window_id":"33fb9f6cefd2ffbe3fabc261","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/33fb9f6cefd2ffbe3fabc261/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject2/k2/6/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"342e60f49ebbe86431722341:0","filtered_window_id":"342e60f49ebbe86431722341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/342e60f49ebbe86431722341/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject2/k1/1/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"342e60f49ebbe86431722341:8","filtered_window_id":"342e60f49ebbe86431722341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/342e60f49ebbe86431722341/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject2/k1/1/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"342e60f49ebbe86431722341:16","filtered_window_id":"342e60f49ebbe86431722341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/342e60f49ebbe86431722341/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[481,482,483,484,485,486,487,488],"take":"subject2/k1/1/cam4","frame_ids":[481,482,483,484,485,486,487,488]} +{"filtered_tile_id":"342e60f49ebbe86431722341:24","filtered_window_id":"342e60f49ebbe86431722341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/342e60f49ebbe86431722341/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[489,490,491,492,493,494,495,496],"take":"subject2/k1/1/cam4","frame_ids":[489,490,491,492,493,494,495,496]} +{"filtered_tile_id":"342e60f49ebbe86431722341:32","filtered_window_id":"342e60f49ebbe86431722341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/342e60f49ebbe86431722341/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[497,498,499,500,501,502,503,504],"take":"subject2/k1/1/cam4","frame_ids":[497,498,499,500,501,502,503,504]} +{"filtered_tile_id":"342e60f49ebbe86431722341:40","filtered_window_id":"342e60f49ebbe86431722341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/342e60f49ebbe86431722341/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[505,506,507,508,509,510,511,512],"take":"subject2/k1/1/cam4","frame_ids":[505,506,507,508,509,510,511,512]} +{"filtered_tile_id":"342e60f49ebbe86431722341:48","filtered_window_id":"342e60f49ebbe86431722341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/342e60f49ebbe86431722341/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[513,514,515,516,517,518,519,520],"take":"subject2/k1/1/cam4","frame_ids":[513,514,515,516,517,518,519,520]} +{"filtered_tile_id":"342e60f49ebbe86431722341:52","filtered_window_id":"342e60f49ebbe86431722341","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/342e60f49ebbe86431722341/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[517,518,519,520,521,522,523,524],"take":"subject2/k1/1/cam4","frame_ids":[517,518,519,520,521,522,523,524]} +{"filtered_tile_id":"346a0a1f7fc1a94e7a9270d6:0","filtered_window_id":"346a0a1f7fc1a94e7a9270d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/346a0a1f7fc1a94e7a9270d6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject2/o2/6/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"346a0a1f7fc1a94e7a9270d6:8","filtered_window_id":"346a0a1f7fc1a94e7a9270d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/346a0a1f7fc1a94e7a9270d6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject2/o2/6/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"346a0a1f7fc1a94e7a9270d6:16","filtered_window_id":"346a0a1f7fc1a94e7a9270d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/346a0a1f7fc1a94e7a9270d6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject2/o2/6/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"346a0a1f7fc1a94e7a9270d6:24","filtered_window_id":"346a0a1f7fc1a94e7a9270d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/346a0a1f7fc1a94e7a9270d6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject2/o2/6/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"346a0a1f7fc1a94e7a9270d6:27","filtered_window_id":"346a0a1f7fc1a94e7a9270d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/346a0a1f7fc1a94e7a9270d6/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[356,357,358,359,360,361,362,363],"take":"subject2/o2/6/cam4","frame_ids":[356,357,358,359,360,361,362,363]} +{"filtered_tile_id":"34f20256004d418ad23058a8:0","filtered_window_id":"34f20256004d418ad23058a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/34f20256004d418ad23058a8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[79,80,81,82,83,84,85,86],"take":"subject1/h1/2/cam4","frame_ids":[79,80,81,82,83,84,85,86]} +{"filtered_tile_id":"34f20256004d418ad23058a8:8","filtered_window_id":"34f20256004d418ad23058a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/34f20256004d418ad23058a8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[87,88,89,90,91,92,93,94],"take":"subject1/h1/2/cam4","frame_ids":[87,88,89,90,91,92,93,94]} +{"filtered_tile_id":"34f20256004d418ad23058a8:16","filtered_window_id":"34f20256004d418ad23058a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/34f20256004d418ad23058a8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[95,96,97,98,99,100,101,102],"take":"subject1/h1/2/cam4","frame_ids":[95,96,97,98,99,100,101,102]} +{"filtered_tile_id":"34f20256004d418ad23058a8:24","filtered_window_id":"34f20256004d418ad23058a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/34f20256004d418ad23058a8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[103,104,105,106,107,108,109,110],"take":"subject1/h1/2/cam4","frame_ids":[103,104,105,106,107,108,109,110]} +{"filtered_tile_id":"34f20256004d418ad23058a8:32","filtered_window_id":"34f20256004d418ad23058a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/34f20256004d418ad23058a8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject1/h1/2/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"34f20256004d418ad23058a8:40","filtered_window_id":"34f20256004d418ad23058a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/34f20256004d418ad23058a8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject1/h1/2/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"34f20256004d418ad23058a8:48","filtered_window_id":"34f20256004d418ad23058a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/34f20256004d418ad23058a8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject1/h1/2/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"34f20256004d418ad23058a8:52","filtered_window_id":"34f20256004d418ad23058a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/34f20256004d418ad23058a8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject1/h1/2/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"355d767032c7422d045b7a8c:0","filtered_window_id":"355d767032c7422d045b7a8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/355d767032c7422d045b7a8c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[294,295,296,297,298,299,300,301],"take":"subject3/k1/6/cam4","frame_ids":[294,295,296,297,298,299,300,301]} +{"filtered_tile_id":"355d767032c7422d045b7a8c:8","filtered_window_id":"355d767032c7422d045b7a8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/355d767032c7422d045b7a8c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[302,303,304,305,306,307,308,309],"take":"subject3/k1/6/cam4","frame_ids":[302,303,304,305,306,307,308,309]} +{"filtered_tile_id":"355d767032c7422d045b7a8c:16","filtered_window_id":"355d767032c7422d045b7a8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/355d767032c7422d045b7a8c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject3/k1/6/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"355d767032c7422d045b7a8c:24","filtered_window_id":"355d767032c7422d045b7a8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/355d767032c7422d045b7a8c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject3/k1/6/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"355d767032c7422d045b7a8c:32","filtered_window_id":"355d767032c7422d045b7a8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/355d767032c7422d045b7a8c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject3/k1/6/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"355d767032c7422d045b7a8c:40","filtered_window_id":"355d767032c7422d045b7a8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/355d767032c7422d045b7a8c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject3/k1/6/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"355d767032c7422d045b7a8c:48","filtered_window_id":"355d767032c7422d045b7a8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/355d767032c7422d045b7a8c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject3/k1/6/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"355d767032c7422d045b7a8c:52","filtered_window_id":"355d767032c7422d045b7a8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/355d767032c7422d045b7a8c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject3/k1/6/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"356481718c7008a2493521fa:0","filtered_window_id":"356481718c7008a2493521fa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/356481718c7008a2493521fa/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject1/h1/4/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"356481718c7008a2493521fa:8","filtered_window_id":"356481718c7008a2493521fa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/356481718c7008a2493521fa/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject1/h1/4/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"356481718c7008a2493521fa:16","filtered_window_id":"356481718c7008a2493521fa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/356481718c7008a2493521fa/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject1/h1/4/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"356481718c7008a2493521fa:24","filtered_window_id":"356481718c7008a2493521fa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/356481718c7008a2493521fa/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject1/h1/4/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"356481718c7008a2493521fa:32","filtered_window_id":"356481718c7008a2493521fa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/356481718c7008a2493521fa/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject1/h1/4/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"356481718c7008a2493521fa:40","filtered_window_id":"356481718c7008a2493521fa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/356481718c7008a2493521fa/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject1/h1/4/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"356481718c7008a2493521fa:48","filtered_window_id":"356481718c7008a2493521fa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/356481718c7008a2493521fa/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[526,527,528,529,530,531,532,533],"take":"subject1/h1/4/cam4","frame_ids":[526,527,528,529,530,531,532,533]} +{"filtered_tile_id":"356481718c7008a2493521fa:52","filtered_window_id":"356481718c7008a2493521fa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/356481718c7008a2493521fa/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[530,531,532,533,534,535,536,537],"take":"subject1/h1/4/cam4","frame_ids":[530,531,532,533,534,535,536,537]} +{"filtered_tile_id":"3586593ed31d748c68de468b:0","filtered_window_id":"3586593ed31d748c68de468b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3586593ed31d748c68de468b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject2/k1/0/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"3586593ed31d748c68de468b:8","filtered_window_id":"3586593ed31d748c68de468b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3586593ed31d748c68de468b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject2/k1/0/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"3586593ed31d748c68de468b:16","filtered_window_id":"3586593ed31d748c68de468b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3586593ed31d748c68de468b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject2/k1/0/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"3586593ed31d748c68de468b:24","filtered_window_id":"3586593ed31d748c68de468b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3586593ed31d748c68de468b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject2/k1/0/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"3586593ed31d748c68de468b:32","filtered_window_id":"3586593ed31d748c68de468b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3586593ed31d748c68de468b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject2/k1/0/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"3586593ed31d748c68de468b:40","filtered_window_id":"3586593ed31d748c68de468b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3586593ed31d748c68de468b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject2/k1/0/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"3586593ed31d748c68de468b:48","filtered_window_id":"3586593ed31d748c68de468b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3586593ed31d748c68de468b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject2/k1/0/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"3586593ed31d748c68de468b:52","filtered_window_id":"3586593ed31d748c68de468b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3586593ed31d748c68de468b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject2/k1/0/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"35bd2939856b7e689671cfcd:0","filtered_window_id":"35bd2939856b7e689671cfcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/35bd2939856b7e689671cfcd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[475,476,477,478,479,480,481,482],"take":"subject2/o2/1/cam4","frame_ids":[475,476,477,478,479,480,481,482]} +{"filtered_tile_id":"35bd2939856b7e689671cfcd:8","filtered_window_id":"35bd2939856b7e689671cfcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/35bd2939856b7e689671cfcd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[483,484,485,486,487,488,489,490],"take":"subject2/o2/1/cam4","frame_ids":[483,484,485,486,487,488,489,490]} +{"filtered_tile_id":"35bd2939856b7e689671cfcd:16","filtered_window_id":"35bd2939856b7e689671cfcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/35bd2939856b7e689671cfcd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[491,492,493,494,495,496,497,498],"take":"subject2/o2/1/cam4","frame_ids":[491,492,493,494,495,496,497,498]} +{"filtered_tile_id":"35bd2939856b7e689671cfcd:24","filtered_window_id":"35bd2939856b7e689671cfcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/35bd2939856b7e689671cfcd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[499,500,501,502,503,504,505,506],"take":"subject2/o2/1/cam4","frame_ids":[499,500,501,502,503,504,505,506]} +{"filtered_tile_id":"35bd2939856b7e689671cfcd:32","filtered_window_id":"35bd2939856b7e689671cfcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/35bd2939856b7e689671cfcd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[507,508,509,510,511,512,513,514],"take":"subject2/o2/1/cam4","frame_ids":[507,508,509,510,511,512,513,514]} +{"filtered_tile_id":"35bd2939856b7e689671cfcd:40","filtered_window_id":"35bd2939856b7e689671cfcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/35bd2939856b7e689671cfcd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[515,516,517,518,519,520,521,522],"take":"subject2/o2/1/cam4","frame_ids":[515,516,517,518,519,520,521,522]} +{"filtered_tile_id":"35bd2939856b7e689671cfcd:48","filtered_window_id":"35bd2939856b7e689671cfcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/35bd2939856b7e689671cfcd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[523,524,525,526,527,528,529,530],"take":"subject2/o2/1/cam4","frame_ids":[523,524,525,526,527,528,529,530]} +{"filtered_tile_id":"35bd2939856b7e689671cfcd:52","filtered_window_id":"35bd2939856b7e689671cfcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/35bd2939856b7e689671cfcd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[527,528,529,530,531,532,533,534],"take":"subject2/o2/1/cam4","frame_ids":[527,528,529,530,531,532,533,534]} +{"filtered_tile_id":"3635260efb13dc09d12ff4e0:0","filtered_window_id":"3635260efb13dc09d12ff4e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3635260efb13dc09d12ff4e0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject1/k1/0/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"3635260efb13dc09d12ff4e0:8","filtered_window_id":"3635260efb13dc09d12ff4e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3635260efb13dc09d12ff4e0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject1/k1/0/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"3635260efb13dc09d12ff4e0:16","filtered_window_id":"3635260efb13dc09d12ff4e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3635260efb13dc09d12ff4e0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject1/k1/0/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"3635260efb13dc09d12ff4e0:24","filtered_window_id":"3635260efb13dc09d12ff4e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3635260efb13dc09d12ff4e0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject1/k1/0/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"3635260efb13dc09d12ff4e0:32","filtered_window_id":"3635260efb13dc09d12ff4e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3635260efb13dc09d12ff4e0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject1/k1/0/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"3635260efb13dc09d12ff4e0:40","filtered_window_id":"3635260efb13dc09d12ff4e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3635260efb13dc09d12ff4e0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[296,297,298,299,300,301,302,303],"take":"subject1/k1/0/cam4","frame_ids":[296,297,298,299,300,301,302,303]} +{"filtered_tile_id":"3635260efb13dc09d12ff4e0:48","filtered_window_id":"3635260efb13dc09d12ff4e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3635260efb13dc09d12ff4e0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[304,305,306,307,308,309,310,311],"take":"subject1/k1/0/cam4","frame_ids":[304,305,306,307,308,309,310,311]} +{"filtered_tile_id":"3635260efb13dc09d12ff4e0:52","filtered_window_id":"3635260efb13dc09d12ff4e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3635260efb13dc09d12ff4e0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject1/k1/0/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"364caac7ee777b34e7815b24:0","filtered_window_id":"364caac7ee777b34e7815b24","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/364caac7ee777b34e7815b24/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[311,312,313,314,315,316,317,318],"take":"subject2/o1/2/cam4","frame_ids":[311,312,313,314,315,316,317,318]} +{"filtered_tile_id":"364caac7ee777b34e7815b24:8","filtered_window_id":"364caac7ee777b34e7815b24","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/364caac7ee777b34e7815b24/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[319,320,321,322,323,324,325,326],"take":"subject2/o1/2/cam4","frame_ids":[319,320,321,322,323,324,325,326]} +{"filtered_tile_id":"364caac7ee777b34e7815b24:16","filtered_window_id":"364caac7ee777b34e7815b24","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/364caac7ee777b34e7815b24/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[327,328,329,330,331,332,333,334],"take":"subject2/o1/2/cam4","frame_ids":[327,328,329,330,331,332,333,334]} +{"filtered_tile_id":"364caac7ee777b34e7815b24:24","filtered_window_id":"364caac7ee777b34e7815b24","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/364caac7ee777b34e7815b24/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[335,336,337,338,339,340,341,342],"take":"subject2/o1/2/cam4","frame_ids":[335,336,337,338,339,340,341,342]} +{"filtered_tile_id":"364caac7ee777b34e7815b24:32","filtered_window_id":"364caac7ee777b34e7815b24","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/364caac7ee777b34e7815b24/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[343,344,345,346,347,348,349,350],"take":"subject2/o1/2/cam4","frame_ids":[343,344,345,346,347,348,349,350]} +{"filtered_tile_id":"364caac7ee777b34e7815b24:40","filtered_window_id":"364caac7ee777b34e7815b24","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/364caac7ee777b34e7815b24/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[351,352,353,354,355,356,357,358],"take":"subject2/o1/2/cam4","frame_ids":[351,352,353,354,355,356,357,358]} +{"filtered_tile_id":"364caac7ee777b34e7815b24:48","filtered_window_id":"364caac7ee777b34e7815b24","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/364caac7ee777b34e7815b24/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[359,360,361,362,363,364,365,366],"take":"subject2/o1/2/cam4","frame_ids":[359,360,361,362,363,364,365,366]} +{"filtered_tile_id":"364caac7ee777b34e7815b24:52","filtered_window_id":"364caac7ee777b34e7815b24","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/364caac7ee777b34e7815b24/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[363,364,365,366,367,368,369,370],"take":"subject2/o1/2/cam4","frame_ids":[363,364,365,366,367,368,369,370]} +{"filtered_tile_id":"366c073f2ee8ceee3227e6ae:0","filtered_window_id":"366c073f2ee8ceee3227e6ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/366c073f2ee8ceee3227e6ae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject2/h1/3/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"366c073f2ee8ceee3227e6ae:8","filtered_window_id":"366c073f2ee8ceee3227e6ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/366c073f2ee8ceee3227e6ae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject2/h1/3/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"366c073f2ee8ceee3227e6ae:16","filtered_window_id":"366c073f2ee8ceee3227e6ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/366c073f2ee8ceee3227e6ae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject2/h1/3/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"366c073f2ee8ceee3227e6ae:24","filtered_window_id":"366c073f2ee8ceee3227e6ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/366c073f2ee8ceee3227e6ae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[468,469,470,471,472,473,474,475],"take":"subject2/h1/3/cam4","frame_ids":[468,469,470,471,472,473,474,475]} +{"filtered_tile_id":"366c073f2ee8ceee3227e6ae:32","filtered_window_id":"366c073f2ee8ceee3227e6ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/366c073f2ee8ceee3227e6ae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[476,477,478,479,480,481,482,483],"take":"subject2/h1/3/cam4","frame_ids":[476,477,478,479,480,481,482,483]} +{"filtered_tile_id":"366c073f2ee8ceee3227e6ae:40","filtered_window_id":"366c073f2ee8ceee3227e6ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/366c073f2ee8ceee3227e6ae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[484,485,486,487,488,489,490,491],"take":"subject2/h1/3/cam4","frame_ids":[484,485,486,487,488,489,490,491]} +{"filtered_tile_id":"366c073f2ee8ceee3227e6ae:47","filtered_window_id":"366c073f2ee8ceee3227e6ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/366c073f2ee8ceee3227e6ae/native_gt.npz","filtered_start_offset":47,"expected_frame_ids":[491,492,493,494,495,496,497,498],"take":"subject2/h1/3/cam4","frame_ids":[491,492,493,494,495,496,497,498]} +{"filtered_tile_id":"369adeeeb169746ebb2c6d03:0","filtered_window_id":"369adeeeb169746ebb2c6d03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/369adeeeb169746ebb2c6d03/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject3/k1/3/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"369adeeeb169746ebb2c6d03:8","filtered_window_id":"369adeeeb169746ebb2c6d03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/369adeeeb169746ebb2c6d03/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject3/k1/3/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"369adeeeb169746ebb2c6d03:16","filtered_window_id":"369adeeeb169746ebb2c6d03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/369adeeeb169746ebb2c6d03/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject3/k1/3/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"369adeeeb169746ebb2c6d03:24","filtered_window_id":"369adeeeb169746ebb2c6d03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/369adeeeb169746ebb2c6d03/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject3/k1/3/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"369adeeeb169746ebb2c6d03:32","filtered_window_id":"369adeeeb169746ebb2c6d03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/369adeeeb169746ebb2c6d03/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject3/k1/3/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"369adeeeb169746ebb2c6d03:40","filtered_window_id":"369adeeeb169746ebb2c6d03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/369adeeeb169746ebb2c6d03/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject3/k1/3/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"369adeeeb169746ebb2c6d03:48","filtered_window_id":"369adeeeb169746ebb2c6d03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/369adeeeb169746ebb2c6d03/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject3/k1/3/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"369adeeeb169746ebb2c6d03:52","filtered_window_id":"369adeeeb169746ebb2c6d03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/369adeeeb169746ebb2c6d03/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[191,192,193,194,195,196,197,198],"take":"subject3/k1/3/cam4","frame_ids":[191,192,193,194,195,196,197,198]} +{"filtered_tile_id":"36bf6490c99e2453cc3beb99:0","filtered_window_id":"36bf6490c99e2453cc3beb99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/36bf6490c99e2453cc3beb99/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject2/h1/4/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"36bf6490c99e2453cc3beb99:8","filtered_window_id":"36bf6490c99e2453cc3beb99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/36bf6490c99e2453cc3beb99/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[469,470,471,472,473,474,475,476],"take":"subject2/h1/4/cam4","frame_ids":[469,470,471,472,473,474,475,476]} +{"filtered_tile_id":"36bf6490c99e2453cc3beb99:16","filtered_window_id":"36bf6490c99e2453cc3beb99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/36bf6490c99e2453cc3beb99/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[477,478,479,480,481,482,483,484],"take":"subject2/h1/4/cam4","frame_ids":[477,478,479,480,481,482,483,484]} +{"filtered_tile_id":"36bf6490c99e2453cc3beb99:24","filtered_window_id":"36bf6490c99e2453cc3beb99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/36bf6490c99e2453cc3beb99/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[485,486,487,488,489,490,491,492],"take":"subject2/h1/4/cam4","frame_ids":[485,486,487,488,489,490,491,492]} +{"filtered_tile_id":"36bf6490c99e2453cc3beb99:32","filtered_window_id":"36bf6490c99e2453cc3beb99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/36bf6490c99e2453cc3beb99/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[493,494,495,496,497,498,499,500],"take":"subject2/h1/4/cam4","frame_ids":[493,494,495,496,497,498,499,500]} +{"filtered_tile_id":"36bf6490c99e2453cc3beb99:40","filtered_window_id":"36bf6490c99e2453cc3beb99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/36bf6490c99e2453cc3beb99/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[501,502,503,504,505,506,507,508],"take":"subject2/h1/4/cam4","frame_ids":[501,502,503,504,505,506,507,508]} +{"filtered_tile_id":"36bf6490c99e2453cc3beb99:48","filtered_window_id":"36bf6490c99e2453cc3beb99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/36bf6490c99e2453cc3beb99/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[509,510,511,512,513,514,515,516],"take":"subject2/h1/4/cam4","frame_ids":[509,510,511,512,513,514,515,516]} +{"filtered_tile_id":"36bf6490c99e2453cc3beb99:52","filtered_window_id":"36bf6490c99e2453cc3beb99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/36bf6490c99e2453cc3beb99/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[513,514,515,516,517,518,519,520],"take":"subject2/h1/4/cam4","frame_ids":[513,514,515,516,517,518,519,520]} +{"filtered_tile_id":"3740b0e08b093fc187524411:0","filtered_window_id":"3740b0e08b093fc187524411","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3740b0e08b093fc187524411/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[125,126,127,128,129,130,131,132],"take":"subject1/k2/3/cam4","frame_ids":[125,126,127,128,129,130,131,132]} +{"filtered_tile_id":"3740b0e08b093fc187524411:8","filtered_window_id":"3740b0e08b093fc187524411","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3740b0e08b093fc187524411/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject1/k2/3/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"3740b0e08b093fc187524411:16","filtered_window_id":"3740b0e08b093fc187524411","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3740b0e08b093fc187524411/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject1/k2/3/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"3740b0e08b093fc187524411:24","filtered_window_id":"3740b0e08b093fc187524411","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3740b0e08b093fc187524411/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject1/k2/3/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"3740b0e08b093fc187524411:32","filtered_window_id":"3740b0e08b093fc187524411","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3740b0e08b093fc187524411/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject1/k2/3/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"3740b0e08b093fc187524411:40","filtered_window_id":"3740b0e08b093fc187524411","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3740b0e08b093fc187524411/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject1/k2/3/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"3740b0e08b093fc187524411:48","filtered_window_id":"3740b0e08b093fc187524411","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3740b0e08b093fc187524411/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject1/k2/3/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"3740b0e08b093fc187524411:52","filtered_window_id":"3740b0e08b093fc187524411","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3740b0e08b093fc187524411/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject1/k2/3/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"377235c738b5a937d0d81f0d:0","filtered_window_id":"377235c738b5a937d0d81f0d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/377235c738b5a937d0d81f0d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[86,87,88,89,90,91,92,93],"take":"subject2/k2/2/cam4","frame_ids":[86,87,88,89,90,91,92,93]} +{"filtered_tile_id":"377235c738b5a937d0d81f0d:8","filtered_window_id":"377235c738b5a937d0d81f0d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/377235c738b5a937d0d81f0d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[94,95,96,97,98,99,100,101],"take":"subject2/k2/2/cam4","frame_ids":[94,95,96,97,98,99,100,101]} +{"filtered_tile_id":"377235c738b5a937d0d81f0d:16","filtered_window_id":"377235c738b5a937d0d81f0d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/377235c738b5a937d0d81f0d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[102,103,104,105,106,107,108,109],"take":"subject2/k2/2/cam4","frame_ids":[102,103,104,105,106,107,108,109]} +{"filtered_tile_id":"377235c738b5a937d0d81f0d:24","filtered_window_id":"377235c738b5a937d0d81f0d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/377235c738b5a937d0d81f0d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[110,111,112,113,114,115,116,117],"take":"subject2/k2/2/cam4","frame_ids":[110,111,112,113,114,115,116,117]} +{"filtered_tile_id":"377235c738b5a937d0d81f0d:32","filtered_window_id":"377235c738b5a937d0d81f0d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/377235c738b5a937d0d81f0d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[118,119,120,121,122,123,124,125],"take":"subject2/k2/2/cam4","frame_ids":[118,119,120,121,122,123,124,125]} +{"filtered_tile_id":"377235c738b5a937d0d81f0d:40","filtered_window_id":"377235c738b5a937d0d81f0d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/377235c738b5a937d0d81f0d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[126,127,128,129,130,131,132,133],"take":"subject2/k2/2/cam4","frame_ids":[126,127,128,129,130,131,132,133]} +{"filtered_tile_id":"377235c738b5a937d0d81f0d:43","filtered_window_id":"377235c738b5a937d0d81f0d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/377235c738b5a937d0d81f0d/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject2/k2/2/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"379095c0911d97decd5e7ba6:0","filtered_window_id":"379095c0911d97decd5e7ba6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/379095c0911d97decd5e7ba6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[94,95,96,97,98,99,100,101],"take":"subject3/h2/3/cam4","frame_ids":[94,95,96,97,98,99,100,101]} +{"filtered_tile_id":"379095c0911d97decd5e7ba6:8","filtered_window_id":"379095c0911d97decd5e7ba6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/379095c0911d97decd5e7ba6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[102,103,104,105,106,107,108,109],"take":"subject3/h2/3/cam4","frame_ids":[102,103,104,105,106,107,108,109]} +{"filtered_tile_id":"379095c0911d97decd5e7ba6:16","filtered_window_id":"379095c0911d97decd5e7ba6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/379095c0911d97decd5e7ba6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[110,111,112,113,114,115,116,117],"take":"subject3/h2/3/cam4","frame_ids":[110,111,112,113,114,115,116,117]} +{"filtered_tile_id":"379095c0911d97decd5e7ba6:24","filtered_window_id":"379095c0911d97decd5e7ba6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/379095c0911d97decd5e7ba6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[118,119,120,121,122,123,124,125],"take":"subject3/h2/3/cam4","frame_ids":[118,119,120,121,122,123,124,125]} +{"filtered_tile_id":"379095c0911d97decd5e7ba6:32","filtered_window_id":"379095c0911d97decd5e7ba6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/379095c0911d97decd5e7ba6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[126,127,128,129,130,131,132,133],"take":"subject3/h2/3/cam4","frame_ids":[126,127,128,129,130,131,132,133]} +{"filtered_tile_id":"379095c0911d97decd5e7ba6:40","filtered_window_id":"379095c0911d97decd5e7ba6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/379095c0911d97decd5e7ba6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[134,135,136,137,138,139,140,141],"take":"subject3/h2/3/cam4","frame_ids":[134,135,136,137,138,139,140,141]} +{"filtered_tile_id":"379095c0911d97decd5e7ba6:48","filtered_window_id":"379095c0911d97decd5e7ba6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/379095c0911d97decd5e7ba6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[142,143,144,145,146,147,148,149],"take":"subject3/h2/3/cam4","frame_ids":[142,143,144,145,146,147,148,149]} +{"filtered_tile_id":"379095c0911d97decd5e7ba6:49","filtered_window_id":"379095c0911d97decd5e7ba6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/379095c0911d97decd5e7ba6/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject3/h2/3/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"37acc0f92e2e4bde6e5b399c:0","filtered_window_id":"37acc0f92e2e4bde6e5b399c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37acc0f92e2e4bde6e5b399c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[600,601,602,603,604,605,606,607],"take":"subject2/o1/2/cam4","frame_ids":[600,601,602,603,604,605,606,607]} +{"filtered_tile_id":"37acc0f92e2e4bde6e5b399c:8","filtered_window_id":"37acc0f92e2e4bde6e5b399c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37acc0f92e2e4bde6e5b399c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[608,609,610,611,612,613,614,615],"take":"subject2/o1/2/cam4","frame_ids":[608,609,610,611,612,613,614,615]} +{"filtered_tile_id":"37acc0f92e2e4bde6e5b399c:16","filtered_window_id":"37acc0f92e2e4bde6e5b399c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37acc0f92e2e4bde6e5b399c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[616,617,618,619,620,621,622,623],"take":"subject2/o1/2/cam4","frame_ids":[616,617,618,619,620,621,622,623]} +{"filtered_tile_id":"37acc0f92e2e4bde6e5b399c:24","filtered_window_id":"37acc0f92e2e4bde6e5b399c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37acc0f92e2e4bde6e5b399c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[624,625,626,627,628,629,630,631],"take":"subject2/o1/2/cam4","frame_ids":[624,625,626,627,628,629,630,631]} +{"filtered_tile_id":"37acc0f92e2e4bde6e5b399c:32","filtered_window_id":"37acc0f92e2e4bde6e5b399c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37acc0f92e2e4bde6e5b399c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[632,633,634,635,636,637,638,639],"take":"subject2/o1/2/cam4","frame_ids":[632,633,634,635,636,637,638,639]} +{"filtered_tile_id":"37acc0f92e2e4bde6e5b399c:40","filtered_window_id":"37acc0f92e2e4bde6e5b399c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37acc0f92e2e4bde6e5b399c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[640,641,642,643,644,645,646,647],"take":"subject2/o1/2/cam4","frame_ids":[640,641,642,643,644,645,646,647]} +{"filtered_tile_id":"37acc0f92e2e4bde6e5b399c:48","filtered_window_id":"37acc0f92e2e4bde6e5b399c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37acc0f92e2e4bde6e5b399c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[648,649,650,651,652,653,654,655],"take":"subject2/o1/2/cam4","frame_ids":[648,649,650,651,652,653,654,655]} +{"filtered_tile_id":"37acc0f92e2e4bde6e5b399c:52","filtered_window_id":"37acc0f92e2e4bde6e5b399c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37acc0f92e2e4bde6e5b399c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[652,653,654,655,656,657,658,659],"take":"subject2/o1/2/cam4","frame_ids":[652,653,654,655,656,657,658,659]} +{"filtered_tile_id":"37b35e47a5edfa6056acf868:0","filtered_window_id":"37b35e47a5edfa6056acf868","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37b35e47a5edfa6056acf868/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[456,457,458,459,460,461,462,463],"take":"subject3/h2/3/cam4","frame_ids":[456,457,458,459,460,461,462,463]} +{"filtered_tile_id":"37b35e47a5edfa6056acf868:8","filtered_window_id":"37b35e47a5edfa6056acf868","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37b35e47a5edfa6056acf868/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[464,465,466,467,468,469,470,471],"take":"subject3/h2/3/cam4","frame_ids":[464,465,466,467,468,469,470,471]} +{"filtered_tile_id":"37b35e47a5edfa6056acf868:16","filtered_window_id":"37b35e47a5edfa6056acf868","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37b35e47a5edfa6056acf868/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject3/h2/3/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"37b35e47a5edfa6056acf868:24","filtered_window_id":"37b35e47a5edfa6056acf868","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37b35e47a5edfa6056acf868/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject3/h2/3/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"37b35e47a5edfa6056acf868:32","filtered_window_id":"37b35e47a5edfa6056acf868","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37b35e47a5edfa6056acf868/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject3/h2/3/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"37b35e47a5edfa6056acf868:40","filtered_window_id":"37b35e47a5edfa6056acf868","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37b35e47a5edfa6056acf868/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject3/h2/3/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"37b35e47a5edfa6056acf868:48","filtered_window_id":"37b35e47a5edfa6056acf868","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37b35e47a5edfa6056acf868/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject3/h2/3/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"37b35e47a5edfa6056acf868:52","filtered_window_id":"37b35e47a5edfa6056acf868","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37b35e47a5edfa6056acf868/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[508,509,510,511,512,513,514,515],"take":"subject3/h2/3/cam4","frame_ids":[508,509,510,511,512,513,514,515]} +{"filtered_tile_id":"37dea9d966a5e307ce115fec:0","filtered_window_id":"37dea9d966a5e307ce115fec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37dea9d966a5e307ce115fec/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[14,15,16,17,18,19,20,21],"take":"subject2/k2/5/cam4","frame_ids":[14,15,16,17,18,19,20,21]} +{"filtered_tile_id":"37dea9d966a5e307ce115fec:8","filtered_window_id":"37dea9d966a5e307ce115fec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37dea9d966a5e307ce115fec/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[22,23,24,25,26,27,28,29],"take":"subject2/k2/5/cam4","frame_ids":[22,23,24,25,26,27,28,29]} +{"filtered_tile_id":"37dea9d966a5e307ce115fec:16","filtered_window_id":"37dea9d966a5e307ce115fec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37dea9d966a5e307ce115fec/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[30,31,32,33,34,35,36,37],"take":"subject2/k2/5/cam4","frame_ids":[30,31,32,33,34,35,36,37]} +{"filtered_tile_id":"37dea9d966a5e307ce115fec:24","filtered_window_id":"37dea9d966a5e307ce115fec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37dea9d966a5e307ce115fec/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[38,39,40,41,42,43,44,45],"take":"subject2/k2/5/cam4","frame_ids":[38,39,40,41,42,43,44,45]} +{"filtered_tile_id":"37dea9d966a5e307ce115fec:32","filtered_window_id":"37dea9d966a5e307ce115fec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37dea9d966a5e307ce115fec/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[46,47,48,49,50,51,52,53],"take":"subject2/k2/5/cam4","frame_ids":[46,47,48,49,50,51,52,53]} +{"filtered_tile_id":"37dea9d966a5e307ce115fec:40","filtered_window_id":"37dea9d966a5e307ce115fec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37dea9d966a5e307ce115fec/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[54,55,56,57,58,59,60,61],"take":"subject2/k2/5/cam4","frame_ids":[54,55,56,57,58,59,60,61]} +{"filtered_tile_id":"37dea9d966a5e307ce115fec:48","filtered_window_id":"37dea9d966a5e307ce115fec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37dea9d966a5e307ce115fec/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[62,63,64,65,66,67,68,69],"take":"subject2/k2/5/cam4","frame_ids":[62,63,64,65,66,67,68,69]} +{"filtered_tile_id":"37dea9d966a5e307ce115fec:52","filtered_window_id":"37dea9d966a5e307ce115fec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/37dea9d966a5e307ce115fec/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[66,67,68,69,70,71,72,73],"take":"subject2/k2/5/cam4","frame_ids":[66,67,68,69,70,71,72,73]} +{"filtered_tile_id":"381472f62de436da46a0c897:0","filtered_window_id":"381472f62de436da46a0c897","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/381472f62de436da46a0c897/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/k1/6/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"381472f62de436da46a0c897:8","filtered_window_id":"381472f62de436da46a0c897","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/381472f62de436da46a0c897/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/k1/6/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"381472f62de436da46a0c897:16","filtered_window_id":"381472f62de436da46a0c897","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/381472f62de436da46a0c897/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k1/6/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"381472f62de436da46a0c897:24","filtered_window_id":"381472f62de436da46a0c897","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/381472f62de436da46a0c897/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k1/6/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"381472f62de436da46a0c897:32","filtered_window_id":"381472f62de436da46a0c897","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/381472f62de436da46a0c897/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k1/6/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"381472f62de436da46a0c897:40","filtered_window_id":"381472f62de436da46a0c897","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/381472f62de436da46a0c897/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/k1/6/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"381472f62de436da46a0c897:48","filtered_window_id":"381472f62de436da46a0c897","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/381472f62de436da46a0c897/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/k1/6/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"381472f62de436da46a0c897:52","filtered_window_id":"381472f62de436da46a0c897","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/381472f62de436da46a0c897/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/k1/6/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"38274cdb2c59308072a1cb61:0","filtered_window_id":"38274cdb2c59308072a1cb61","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/38274cdb2c59308072a1cb61/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/h1/4/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"38274cdb2c59308072a1cb61:8","filtered_window_id":"38274cdb2c59308072a1cb61","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/38274cdb2c59308072a1cb61/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/h1/4/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"38274cdb2c59308072a1cb61:16","filtered_window_id":"38274cdb2c59308072a1cb61","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/38274cdb2c59308072a1cb61/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/h1/4/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"38274cdb2c59308072a1cb61:24","filtered_window_id":"38274cdb2c59308072a1cb61","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/38274cdb2c59308072a1cb61/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/h1/4/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"38274cdb2c59308072a1cb61:32","filtered_window_id":"38274cdb2c59308072a1cb61","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/38274cdb2c59308072a1cb61/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/h1/4/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"38274cdb2c59308072a1cb61:40","filtered_window_id":"38274cdb2c59308072a1cb61","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/38274cdb2c59308072a1cb61/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/h1/4/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"38274cdb2c59308072a1cb61:48","filtered_window_id":"38274cdb2c59308072a1cb61","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/38274cdb2c59308072a1cb61/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/h1/4/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"38274cdb2c59308072a1cb61:52","filtered_window_id":"38274cdb2c59308072a1cb61","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/38274cdb2c59308072a1cb61/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/h1/4/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"382b4454540deeaa86c8dae0:0","filtered_window_id":"382b4454540deeaa86c8dae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/382b4454540deeaa86c8dae0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject1/h2/2/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"382b4454540deeaa86c8dae0:8","filtered_window_id":"382b4454540deeaa86c8dae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/382b4454540deeaa86c8dae0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject1/h2/2/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"382b4454540deeaa86c8dae0:16","filtered_window_id":"382b4454540deeaa86c8dae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/382b4454540deeaa86c8dae0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject1/h2/2/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"382b4454540deeaa86c8dae0:24","filtered_window_id":"382b4454540deeaa86c8dae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/382b4454540deeaa86c8dae0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject1/h2/2/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"382b4454540deeaa86c8dae0:32","filtered_window_id":"382b4454540deeaa86c8dae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/382b4454540deeaa86c8dae0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject1/h2/2/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"382b4454540deeaa86c8dae0:40","filtered_window_id":"382b4454540deeaa86c8dae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/382b4454540deeaa86c8dae0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[423,424,425,426,427,428,429,430],"take":"subject1/h2/2/cam4","frame_ids":[423,424,425,426,427,428,429,430]} +{"filtered_tile_id":"382b4454540deeaa86c8dae0:48","filtered_window_id":"382b4454540deeaa86c8dae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/382b4454540deeaa86c8dae0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[431,432,433,434,435,436,437,438],"take":"subject1/h2/2/cam4","frame_ids":[431,432,433,434,435,436,437,438]} +{"filtered_tile_id":"382b4454540deeaa86c8dae0:52","filtered_window_id":"382b4454540deeaa86c8dae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/382b4454540deeaa86c8dae0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/h2/2/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"3886939f47413673e3d8d95b:0","filtered_window_id":"3886939f47413673e3d8d95b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3886939f47413673e3d8d95b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o1/0/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"3886939f47413673e3d8d95b:8","filtered_window_id":"3886939f47413673e3d8d95b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3886939f47413673e3d8d95b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o1/0/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"3886939f47413673e3d8d95b:16","filtered_window_id":"3886939f47413673e3d8d95b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3886939f47413673e3d8d95b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o1/0/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"3886939f47413673e3d8d95b:24","filtered_window_id":"3886939f47413673e3d8d95b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3886939f47413673e3d8d95b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o1/0/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"3886939f47413673e3d8d95b:27","filtered_window_id":"3886939f47413673e3d8d95b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3886939f47413673e3d8d95b/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[27,28,29,30,31,32,33,34],"take":"subject1/o1/0/cam4","frame_ids":[27,28,29,30,31,32,33,34]} +{"filtered_tile_id":"3893352a0ffdf1a4e7b75f7b:0","filtered_window_id":"3893352a0ffdf1a4e7b75f7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3893352a0ffdf1a4e7b75f7b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject1/o2/4/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"3893352a0ffdf1a4e7b75f7b:8","filtered_window_id":"3893352a0ffdf1a4e7b75f7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3893352a0ffdf1a4e7b75f7b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject1/o2/4/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"3893352a0ffdf1a4e7b75f7b:16","filtered_window_id":"3893352a0ffdf1a4e7b75f7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3893352a0ffdf1a4e7b75f7b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject1/o2/4/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"3893352a0ffdf1a4e7b75f7b:24","filtered_window_id":"3893352a0ffdf1a4e7b75f7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3893352a0ffdf1a4e7b75f7b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject1/o2/4/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"3893352a0ffdf1a4e7b75f7b:32","filtered_window_id":"3893352a0ffdf1a4e7b75f7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3893352a0ffdf1a4e7b75f7b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject1/o2/4/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"3893352a0ffdf1a4e7b75f7b:40","filtered_window_id":"3893352a0ffdf1a4e7b75f7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3893352a0ffdf1a4e7b75f7b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject1/o2/4/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"3893352a0ffdf1a4e7b75f7b:48","filtered_window_id":"3893352a0ffdf1a4e7b75f7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3893352a0ffdf1a4e7b75f7b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject1/o2/4/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"3893352a0ffdf1a4e7b75f7b:52","filtered_window_id":"3893352a0ffdf1a4e7b75f7b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3893352a0ffdf1a4e7b75f7b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject1/o2/4/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"393a0aeb97e7412bfe6e039e:0","filtered_window_id":"393a0aeb97e7412bfe6e039e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393a0aeb97e7412bfe6e039e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/h2/5/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"393a0aeb97e7412bfe6e039e:1","filtered_window_id":"393a0aeb97e7412bfe6e039e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393a0aeb97e7412bfe6e039e/native_gt.npz","filtered_start_offset":1,"expected_frame_ids":[61,62,63,64,65,66,67,68],"take":"subject2/h2/5/cam4","frame_ids":[61,62,63,64,65,66,67,68]} +{"filtered_tile_id":"393c6794e972291ed5aac0fb:0","filtered_window_id":"393c6794e972291ed5aac0fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393c6794e972291ed5aac0fb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[86,87,88,89,90,91,92,93],"take":"subject1/o1/1/cam4","frame_ids":[86,87,88,89,90,91,92,93]} +{"filtered_tile_id":"393c6794e972291ed5aac0fb:8","filtered_window_id":"393c6794e972291ed5aac0fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393c6794e972291ed5aac0fb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[94,95,96,97,98,99,100,101],"take":"subject1/o1/1/cam4","frame_ids":[94,95,96,97,98,99,100,101]} +{"filtered_tile_id":"393c6794e972291ed5aac0fb:16","filtered_window_id":"393c6794e972291ed5aac0fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393c6794e972291ed5aac0fb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[102,103,104,105,106,107,108,109],"take":"subject1/o1/1/cam4","frame_ids":[102,103,104,105,106,107,108,109]} +{"filtered_tile_id":"393c6794e972291ed5aac0fb:24","filtered_window_id":"393c6794e972291ed5aac0fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393c6794e972291ed5aac0fb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[110,111,112,113,114,115,116,117],"take":"subject1/o1/1/cam4","frame_ids":[110,111,112,113,114,115,116,117]} +{"filtered_tile_id":"393c6794e972291ed5aac0fb:32","filtered_window_id":"393c6794e972291ed5aac0fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393c6794e972291ed5aac0fb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[118,119,120,121,122,123,124,125],"take":"subject1/o1/1/cam4","frame_ids":[118,119,120,121,122,123,124,125]} +{"filtered_tile_id":"393c6794e972291ed5aac0fb:40","filtered_window_id":"393c6794e972291ed5aac0fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393c6794e972291ed5aac0fb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[126,127,128,129,130,131,132,133],"take":"subject1/o1/1/cam4","frame_ids":[126,127,128,129,130,131,132,133]} +{"filtered_tile_id":"393c6794e972291ed5aac0fb:48","filtered_window_id":"393c6794e972291ed5aac0fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393c6794e972291ed5aac0fb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[134,135,136,137,138,139,140,141],"take":"subject1/o1/1/cam4","frame_ids":[134,135,136,137,138,139,140,141]} +{"filtered_tile_id":"393c6794e972291ed5aac0fb:52","filtered_window_id":"393c6794e972291ed5aac0fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/393c6794e972291ed5aac0fb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject1/o1/1/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"398b1a182d34316a2e70f8de:0","filtered_window_id":"398b1a182d34316a2e70f8de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/398b1a182d34316a2e70f8de/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[601,602,603,604,605,606,607,608],"take":"subject3/h1/7/cam4","frame_ids":[601,602,603,604,605,606,607,608]} +{"filtered_tile_id":"398b1a182d34316a2e70f8de:8","filtered_window_id":"398b1a182d34316a2e70f8de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/398b1a182d34316a2e70f8de/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[609,610,611,612,613,614,615,616],"take":"subject3/h1/7/cam4","frame_ids":[609,610,611,612,613,614,615,616]} +{"filtered_tile_id":"398b1a182d34316a2e70f8de:16","filtered_window_id":"398b1a182d34316a2e70f8de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/398b1a182d34316a2e70f8de/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[617,618,619,620,621,622,623,624],"take":"subject3/h1/7/cam4","frame_ids":[617,618,619,620,621,622,623,624]} +{"filtered_tile_id":"398b1a182d34316a2e70f8de:24","filtered_window_id":"398b1a182d34316a2e70f8de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/398b1a182d34316a2e70f8de/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[625,626,627,628,629,630,631,632],"take":"subject3/h1/7/cam4","frame_ids":[625,626,627,628,629,630,631,632]} +{"filtered_tile_id":"398b1a182d34316a2e70f8de:32","filtered_window_id":"398b1a182d34316a2e70f8de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/398b1a182d34316a2e70f8de/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[633,634,635,636,637,638,639,640],"take":"subject3/h1/7/cam4","frame_ids":[633,634,635,636,637,638,639,640]} +{"filtered_tile_id":"398b1a182d34316a2e70f8de:40","filtered_window_id":"398b1a182d34316a2e70f8de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/398b1a182d34316a2e70f8de/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[641,642,643,644,645,646,647,648],"take":"subject3/h1/7/cam4","frame_ids":[641,642,643,644,645,646,647,648]} +{"filtered_tile_id":"398b1a182d34316a2e70f8de:48","filtered_window_id":"398b1a182d34316a2e70f8de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/398b1a182d34316a2e70f8de/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[649,650,651,652,653,654,655,656],"take":"subject3/h1/7/cam4","frame_ids":[649,650,651,652,653,654,655,656]} +{"filtered_tile_id":"398b1a182d34316a2e70f8de:52","filtered_window_id":"398b1a182d34316a2e70f8de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/398b1a182d34316a2e70f8de/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[653,654,655,656,657,658,659,660],"take":"subject3/h1/7/cam4","frame_ids":[653,654,655,656,657,658,659,660]} +{"filtered_tile_id":"399c16b442245be465928780:0","filtered_window_id":"399c16b442245be465928780","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/399c16b442245be465928780/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[121,122,123,124,125,126,127,128],"take":"subject1/h1/5/cam4","frame_ids":[121,122,123,124,125,126,127,128]} +{"filtered_tile_id":"399c16b442245be465928780:8","filtered_window_id":"399c16b442245be465928780","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/399c16b442245be465928780/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject1/h1/5/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"399c16b442245be465928780:16","filtered_window_id":"399c16b442245be465928780","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/399c16b442245be465928780/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject1/h1/5/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"399c16b442245be465928780:24","filtered_window_id":"399c16b442245be465928780","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/399c16b442245be465928780/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject1/h1/5/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"399c16b442245be465928780:32","filtered_window_id":"399c16b442245be465928780","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/399c16b442245be465928780/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject1/h1/5/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"399c16b442245be465928780:40","filtered_window_id":"399c16b442245be465928780","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/399c16b442245be465928780/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject1/h1/5/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"399c16b442245be465928780:48","filtered_window_id":"399c16b442245be465928780","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/399c16b442245be465928780/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject1/h1/5/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"399c16b442245be465928780:52","filtered_window_id":"399c16b442245be465928780","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/399c16b442245be465928780/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject1/h1/5/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"39ad323780c944ad9c89f2a4:0","filtered_window_id":"39ad323780c944ad9c89f2a4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39ad323780c944ad9c89f2a4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject1/k1/3/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"39ad323780c944ad9c89f2a4:8","filtered_window_id":"39ad323780c944ad9c89f2a4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39ad323780c944ad9c89f2a4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject1/k1/3/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"39ad323780c944ad9c89f2a4:16","filtered_window_id":"39ad323780c944ad9c89f2a4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39ad323780c944ad9c89f2a4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject1/k1/3/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"39ad323780c944ad9c89f2a4:24","filtered_window_id":"39ad323780c944ad9c89f2a4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39ad323780c944ad9c89f2a4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject1/k1/3/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"39ad323780c944ad9c89f2a4:32","filtered_window_id":"39ad323780c944ad9c89f2a4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39ad323780c944ad9c89f2a4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject1/k1/3/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"39ad323780c944ad9c89f2a4:40","filtered_window_id":"39ad323780c944ad9c89f2a4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39ad323780c944ad9c89f2a4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject1/k1/3/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"39ad323780c944ad9c89f2a4:48","filtered_window_id":"39ad323780c944ad9c89f2a4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39ad323780c944ad9c89f2a4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject1/k1/3/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"39ad323780c944ad9c89f2a4:52","filtered_window_id":"39ad323780c944ad9c89f2a4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39ad323780c944ad9c89f2a4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject1/k1/3/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"39f9c5efdc3ca5cb689b2320:0","filtered_window_id":"39f9c5efdc3ca5cb689b2320","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39f9c5efdc3ca5cb689b2320/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject3/k1/4/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"39f9c5efdc3ca5cb689b2320:8","filtered_window_id":"39f9c5efdc3ca5cb689b2320","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39f9c5efdc3ca5cb689b2320/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject3/k1/4/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"39f9c5efdc3ca5cb689b2320:16","filtered_window_id":"39f9c5efdc3ca5cb689b2320","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39f9c5efdc3ca5cb689b2320/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[526,527,528,529,530,531,532,533],"take":"subject3/k1/4/cam4","frame_ids":[526,527,528,529,530,531,532,533]} +{"filtered_tile_id":"39f9c5efdc3ca5cb689b2320:24","filtered_window_id":"39f9c5efdc3ca5cb689b2320","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39f9c5efdc3ca5cb689b2320/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[534,535,536,537,538,539,540,541],"take":"subject3/k1/4/cam4","frame_ids":[534,535,536,537,538,539,540,541]} +{"filtered_tile_id":"39f9c5efdc3ca5cb689b2320:31","filtered_window_id":"39f9c5efdc3ca5cb689b2320","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/39f9c5efdc3ca5cb689b2320/native_gt.npz","filtered_start_offset":31,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject3/k1/4/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"3acc711fb06c2b1276402755:0","filtered_window_id":"3acc711fb06c2b1276402755","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3acc711fb06c2b1276402755/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[175,176,177,178,179,180,181,182],"take":"subject2/o2/6/cam4","frame_ids":[175,176,177,178,179,180,181,182]} +{"filtered_tile_id":"3acc711fb06c2b1276402755:5","filtered_window_id":"3acc711fb06c2b1276402755","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3acc711fb06c2b1276402755/native_gt.npz","filtered_start_offset":5,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject2/o2/6/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"3ad77ce4e7b9d28e6f400f63:0","filtered_window_id":"3ad77ce4e7b9d28e6f400f63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3ad77ce4e7b9d28e6f400f63/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject2/h1/3/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"3ad77ce4e7b9d28e6f400f63:8","filtered_window_id":"3ad77ce4e7b9d28e6f400f63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3ad77ce4e7b9d28e6f400f63/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[392,393,394,395,396,397,398,399],"take":"subject2/h1/3/cam4","frame_ids":[392,393,394,395,396,397,398,399]} +{"filtered_tile_id":"3ad77ce4e7b9d28e6f400f63:16","filtered_window_id":"3ad77ce4e7b9d28e6f400f63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3ad77ce4e7b9d28e6f400f63/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[400,401,402,403,404,405,406,407],"take":"subject2/h1/3/cam4","frame_ids":[400,401,402,403,404,405,406,407]} +{"filtered_tile_id":"3ad77ce4e7b9d28e6f400f63:24","filtered_window_id":"3ad77ce4e7b9d28e6f400f63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3ad77ce4e7b9d28e6f400f63/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[408,409,410,411,412,413,414,415],"take":"subject2/h1/3/cam4","frame_ids":[408,409,410,411,412,413,414,415]} +{"filtered_tile_id":"3ad77ce4e7b9d28e6f400f63:32","filtered_window_id":"3ad77ce4e7b9d28e6f400f63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3ad77ce4e7b9d28e6f400f63/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[416,417,418,419,420,421,422,423],"take":"subject2/h1/3/cam4","frame_ids":[416,417,418,419,420,421,422,423]} +{"filtered_tile_id":"3ad77ce4e7b9d28e6f400f63:40","filtered_window_id":"3ad77ce4e7b9d28e6f400f63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3ad77ce4e7b9d28e6f400f63/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[424,425,426,427,428,429,430,431],"take":"subject2/h1/3/cam4","frame_ids":[424,425,426,427,428,429,430,431]} +{"filtered_tile_id":"3ad77ce4e7b9d28e6f400f63:48","filtered_window_id":"3ad77ce4e7b9d28e6f400f63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3ad77ce4e7b9d28e6f400f63/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[432,433,434,435,436,437,438,439],"take":"subject2/h1/3/cam4","frame_ids":[432,433,434,435,436,437,438,439]} +{"filtered_tile_id":"3ad77ce4e7b9d28e6f400f63:52","filtered_window_id":"3ad77ce4e7b9d28e6f400f63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3ad77ce4e7b9d28e6f400f63/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject2/h1/3/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"3b0ca0d9d50730dffea69228:0","filtered_window_id":"3b0ca0d9d50730dffea69228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b0ca0d9d50730dffea69228/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject1/o2/6/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"3b0ca0d9d50730dffea69228:2","filtered_window_id":"3b0ca0d9d50730dffea69228","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b0ca0d9d50730dffea69228/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject1/o2/6/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"3b8615536a09653a6adef41a:0","filtered_window_id":"3b8615536a09653a6adef41a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b8615536a09653a6adef41a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[401,402,403,404,405,406,407,408],"take":"subject1/o2/5/cam4","frame_ids":[401,402,403,404,405,406,407,408]} +{"filtered_tile_id":"3b8615536a09653a6adef41a:8","filtered_window_id":"3b8615536a09653a6adef41a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b8615536a09653a6adef41a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[409,410,411,412,413,414,415,416],"take":"subject1/o2/5/cam4","frame_ids":[409,410,411,412,413,414,415,416]} +{"filtered_tile_id":"3b8615536a09653a6adef41a:16","filtered_window_id":"3b8615536a09653a6adef41a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b8615536a09653a6adef41a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[417,418,419,420,421,422,423,424],"take":"subject1/o2/5/cam4","frame_ids":[417,418,419,420,421,422,423,424]} +{"filtered_tile_id":"3b8615536a09653a6adef41a:24","filtered_window_id":"3b8615536a09653a6adef41a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b8615536a09653a6adef41a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject1/o2/5/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"3b8615536a09653a6adef41a:32","filtered_window_id":"3b8615536a09653a6adef41a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b8615536a09653a6adef41a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[433,434,435,436,437,438,439,440],"take":"subject1/o2/5/cam4","frame_ids":[433,434,435,436,437,438,439,440]} +{"filtered_tile_id":"3b8615536a09653a6adef41a:40","filtered_window_id":"3b8615536a09653a6adef41a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b8615536a09653a6adef41a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject1/o2/5/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"3b8615536a09653a6adef41a:48","filtered_window_id":"3b8615536a09653a6adef41a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b8615536a09653a6adef41a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject1/o2/5/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"3b8615536a09653a6adef41a:52","filtered_window_id":"3b8615536a09653a6adef41a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3b8615536a09653a6adef41a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[453,454,455,456,457,458,459,460],"take":"subject1/o2/5/cam4","frame_ids":[453,454,455,456,457,458,459,460]} +{"filtered_tile_id":"3c0440ee7966dc890c153a1d:0","filtered_window_id":"3c0440ee7966dc890c153a1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c0440ee7966dc890c153a1d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[120,121,122,123,124,125,126,127],"take":"subject1/k1/5/cam4","frame_ids":[120,121,122,123,124,125,126,127]} +{"filtered_tile_id":"3c0440ee7966dc890c153a1d:8","filtered_window_id":"3c0440ee7966dc890c153a1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c0440ee7966dc890c153a1d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[128,129,130,131,132,133,134,135],"take":"subject1/k1/5/cam4","frame_ids":[128,129,130,131,132,133,134,135]} +{"filtered_tile_id":"3c0440ee7966dc890c153a1d:16","filtered_window_id":"3c0440ee7966dc890c153a1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c0440ee7966dc890c153a1d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[136,137,138,139,140,141,142,143],"take":"subject1/k1/5/cam4","frame_ids":[136,137,138,139,140,141,142,143]} +{"filtered_tile_id":"3c0440ee7966dc890c153a1d:24","filtered_window_id":"3c0440ee7966dc890c153a1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c0440ee7966dc890c153a1d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[144,145,146,147,148,149,150,151],"take":"subject1/k1/5/cam4","frame_ids":[144,145,146,147,148,149,150,151]} +{"filtered_tile_id":"3c0440ee7966dc890c153a1d:32","filtered_window_id":"3c0440ee7966dc890c153a1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c0440ee7966dc890c153a1d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject1/k1/5/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"3c0440ee7966dc890c153a1d:40","filtered_window_id":"3c0440ee7966dc890c153a1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c0440ee7966dc890c153a1d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject1/k1/5/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"3c0440ee7966dc890c153a1d:48","filtered_window_id":"3c0440ee7966dc890c153a1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c0440ee7966dc890c153a1d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject1/k1/5/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"3c0440ee7966dc890c153a1d:52","filtered_window_id":"3c0440ee7966dc890c153a1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c0440ee7966dc890c153a1d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject1/k1/5/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"3c4d0a820cd7701f42631887:0","filtered_window_id":"3c4d0a820cd7701f42631887","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c4d0a820cd7701f42631887/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[619,620,621,622,623,624,625,626],"take":"subject2/k2/6/cam4","frame_ids":[619,620,621,622,623,624,625,626]} +{"filtered_tile_id":"3c4d0a820cd7701f42631887:8","filtered_window_id":"3c4d0a820cd7701f42631887","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c4d0a820cd7701f42631887/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[627,628,629,630,631,632,633,634],"take":"subject2/k2/6/cam4","frame_ids":[627,628,629,630,631,632,633,634]} +{"filtered_tile_id":"3c4d0a820cd7701f42631887:16","filtered_window_id":"3c4d0a820cd7701f42631887","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c4d0a820cd7701f42631887/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[635,636,637,638,639,640,641,642],"take":"subject2/k2/6/cam4","frame_ids":[635,636,637,638,639,640,641,642]} +{"filtered_tile_id":"3c4d0a820cd7701f42631887:24","filtered_window_id":"3c4d0a820cd7701f42631887","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c4d0a820cd7701f42631887/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[643,644,645,646,647,648,649,650],"take":"subject2/k2/6/cam4","frame_ids":[643,644,645,646,647,648,649,650]} +{"filtered_tile_id":"3c4d0a820cd7701f42631887:32","filtered_window_id":"3c4d0a820cd7701f42631887","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c4d0a820cd7701f42631887/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[651,652,653,654,655,656,657,658],"take":"subject2/k2/6/cam4","frame_ids":[651,652,653,654,655,656,657,658]} +{"filtered_tile_id":"3c4d0a820cd7701f42631887:40","filtered_window_id":"3c4d0a820cd7701f42631887","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c4d0a820cd7701f42631887/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[659,660,661,662,663,664,665,666],"take":"subject2/k2/6/cam4","frame_ids":[659,660,661,662,663,664,665,666]} +{"filtered_tile_id":"3c4d0a820cd7701f42631887:48","filtered_window_id":"3c4d0a820cd7701f42631887","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c4d0a820cd7701f42631887/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[667,668,669,670,671,672,673,674],"take":"subject2/k2/6/cam4","frame_ids":[667,668,669,670,671,672,673,674]} +{"filtered_tile_id":"3c4d0a820cd7701f42631887:52","filtered_window_id":"3c4d0a820cd7701f42631887","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3c4d0a820cd7701f42631887/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[671,672,673,674,675,676,677,678],"take":"subject2/k2/6/cam4","frame_ids":[671,672,673,674,675,676,677,678]} +{"filtered_tile_id":"3cc60728ecaa5337aab4be88:0","filtered_window_id":"3cc60728ecaa5337aab4be88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cc60728ecaa5337aab4be88/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[660,661,662,663,664,665,666,667],"take":"subject2/o1/2/cam4","frame_ids":[660,661,662,663,664,665,666,667]} +{"filtered_tile_id":"3cc60728ecaa5337aab4be88:8","filtered_window_id":"3cc60728ecaa5337aab4be88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cc60728ecaa5337aab4be88/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[668,669,670,671,672,673,674,675],"take":"subject2/o1/2/cam4","frame_ids":[668,669,670,671,672,673,674,675]} +{"filtered_tile_id":"3cc60728ecaa5337aab4be88:16","filtered_window_id":"3cc60728ecaa5337aab4be88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cc60728ecaa5337aab4be88/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[676,677,678,679,680,681,682,683],"take":"subject2/o1/2/cam4","frame_ids":[676,677,678,679,680,681,682,683]} +{"filtered_tile_id":"3cc60728ecaa5337aab4be88:24","filtered_window_id":"3cc60728ecaa5337aab4be88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cc60728ecaa5337aab4be88/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[684,685,686,687,688,689,690,691],"take":"subject2/o1/2/cam4","frame_ids":[684,685,686,687,688,689,690,691]} +{"filtered_tile_id":"3cc60728ecaa5337aab4be88:32","filtered_window_id":"3cc60728ecaa5337aab4be88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cc60728ecaa5337aab4be88/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[692,693,694,695,696,697,698,699],"take":"subject2/o1/2/cam4","frame_ids":[692,693,694,695,696,697,698,699]} +{"filtered_tile_id":"3cc60728ecaa5337aab4be88:40","filtered_window_id":"3cc60728ecaa5337aab4be88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cc60728ecaa5337aab4be88/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[700,701,702,703,704,705,706,707],"take":"subject2/o1/2/cam4","frame_ids":[700,701,702,703,704,705,706,707]} +{"filtered_tile_id":"3cc60728ecaa5337aab4be88:48","filtered_window_id":"3cc60728ecaa5337aab4be88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cc60728ecaa5337aab4be88/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[708,709,710,711,712,713,714,715],"take":"subject2/o1/2/cam4","frame_ids":[708,709,710,711,712,713,714,715]} +{"filtered_tile_id":"3cc60728ecaa5337aab4be88:52","filtered_window_id":"3cc60728ecaa5337aab4be88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cc60728ecaa5337aab4be88/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[712,713,714,715,716,717,718,719],"take":"subject2/o1/2/cam4","frame_ids":[712,713,714,715,716,717,718,719]} +{"filtered_tile_id":"3cdcd858d8bbb8e37e9476bf:0","filtered_window_id":"3cdcd858d8bbb8e37e9476bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cdcd858d8bbb8e37e9476bf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h1/3/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"3cdcd858d8bbb8e37e9476bf:8","filtered_window_id":"3cdcd858d8bbb8e37e9476bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cdcd858d8bbb8e37e9476bf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h1/3/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"3cdcd858d8bbb8e37e9476bf:16","filtered_window_id":"3cdcd858d8bbb8e37e9476bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cdcd858d8bbb8e37e9476bf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h1/3/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"3cdcd858d8bbb8e37e9476bf:24","filtered_window_id":"3cdcd858d8bbb8e37e9476bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cdcd858d8bbb8e37e9476bf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h1/3/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"3cdcd858d8bbb8e37e9476bf:32","filtered_window_id":"3cdcd858d8bbb8e37e9476bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cdcd858d8bbb8e37e9476bf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h1/3/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"3cdcd858d8bbb8e37e9476bf:40","filtered_window_id":"3cdcd858d8bbb8e37e9476bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cdcd858d8bbb8e37e9476bf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/h1/3/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"3cdcd858d8bbb8e37e9476bf:42","filtered_window_id":"3cdcd858d8bbb8e37e9476bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3cdcd858d8bbb8e37e9476bf/native_gt.npz","filtered_start_offset":42,"expected_frame_ids":[42,43,44,45,46,47,48,49],"take":"subject1/h1/3/cam4","frame_ids":[42,43,44,45,46,47,48,49]} +{"filtered_tile_id":"3d4975f5dd89bcc2900e02bf:0","filtered_window_id":"3d4975f5dd89bcc2900e02bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3d4975f5dd89bcc2900e02bf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[599,600,601,602,603,604,605,606],"take":"subject2/h2/3/cam4","frame_ids":[599,600,601,602,603,604,605,606]} +{"filtered_tile_id":"3d4975f5dd89bcc2900e02bf:8","filtered_window_id":"3d4975f5dd89bcc2900e02bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3d4975f5dd89bcc2900e02bf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[607,608,609,610,611,612,613,614],"take":"subject2/h2/3/cam4","frame_ids":[607,608,609,610,611,612,613,614]} +{"filtered_tile_id":"3d4975f5dd89bcc2900e02bf:16","filtered_window_id":"3d4975f5dd89bcc2900e02bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3d4975f5dd89bcc2900e02bf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[615,616,617,618,619,620,621,622],"take":"subject2/h2/3/cam4","frame_ids":[615,616,617,618,619,620,621,622]} +{"filtered_tile_id":"3d4975f5dd89bcc2900e02bf:24","filtered_window_id":"3d4975f5dd89bcc2900e02bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3d4975f5dd89bcc2900e02bf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[623,624,625,626,627,628,629,630],"take":"subject2/h2/3/cam4","frame_ids":[623,624,625,626,627,628,629,630]} +{"filtered_tile_id":"3d4975f5dd89bcc2900e02bf:32","filtered_window_id":"3d4975f5dd89bcc2900e02bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3d4975f5dd89bcc2900e02bf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[631,632,633,634,635,636,637,638],"take":"subject2/h2/3/cam4","frame_ids":[631,632,633,634,635,636,637,638]} +{"filtered_tile_id":"3d4975f5dd89bcc2900e02bf:40","filtered_window_id":"3d4975f5dd89bcc2900e02bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3d4975f5dd89bcc2900e02bf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[639,640,641,642,643,644,645,646],"take":"subject2/h2/3/cam4","frame_ids":[639,640,641,642,643,644,645,646]} +{"filtered_tile_id":"3d4975f5dd89bcc2900e02bf:48","filtered_window_id":"3d4975f5dd89bcc2900e02bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3d4975f5dd89bcc2900e02bf/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[647,648,649,650,651,652,653,654],"take":"subject2/h2/3/cam4","frame_ids":[647,648,649,650,651,652,653,654]} +{"filtered_tile_id":"3d4975f5dd89bcc2900e02bf:52","filtered_window_id":"3d4975f5dd89bcc2900e02bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3d4975f5dd89bcc2900e02bf/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[651,652,653,654,655,656,657,658],"take":"subject2/h2/3/cam4","frame_ids":[651,652,653,654,655,656,657,658]} +{"filtered_tile_id":"3db8c826ab5c9b4f843ca915:0","filtered_window_id":"3db8c826ab5c9b4f843ca915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3db8c826ab5c9b4f843ca915/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[20,21,22,23,24,25,26,27],"take":"subject3/h2/5/cam4","frame_ids":[20,21,22,23,24,25,26,27]} +{"filtered_tile_id":"3db8c826ab5c9b4f843ca915:8","filtered_window_id":"3db8c826ab5c9b4f843ca915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3db8c826ab5c9b4f843ca915/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[28,29,30,31,32,33,34,35],"take":"subject3/h2/5/cam4","frame_ids":[28,29,30,31,32,33,34,35]} +{"filtered_tile_id":"3db8c826ab5c9b4f843ca915:16","filtered_window_id":"3db8c826ab5c9b4f843ca915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3db8c826ab5c9b4f843ca915/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[36,37,38,39,40,41,42,43],"take":"subject3/h2/5/cam4","frame_ids":[36,37,38,39,40,41,42,43]} +{"filtered_tile_id":"3db8c826ab5c9b4f843ca915:24","filtered_window_id":"3db8c826ab5c9b4f843ca915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3db8c826ab5c9b4f843ca915/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[44,45,46,47,48,49,50,51],"take":"subject3/h2/5/cam4","frame_ids":[44,45,46,47,48,49,50,51]} +{"filtered_tile_id":"3db8c826ab5c9b4f843ca915:32","filtered_window_id":"3db8c826ab5c9b4f843ca915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3db8c826ab5c9b4f843ca915/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject3/h2/5/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"3db8c826ab5c9b4f843ca915:40","filtered_window_id":"3db8c826ab5c9b4f843ca915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3db8c826ab5c9b4f843ca915/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject3/h2/5/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"3db8c826ab5c9b4f843ca915:48","filtered_window_id":"3db8c826ab5c9b4f843ca915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3db8c826ab5c9b4f843ca915/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject3/h2/5/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"3db8c826ab5c9b4f843ca915:52","filtered_window_id":"3db8c826ab5c9b4f843ca915","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3db8c826ab5c9b4f843ca915/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[72,73,74,75,76,77,78,79],"take":"subject3/h2/5/cam4","frame_ids":[72,73,74,75,76,77,78,79]} +{"filtered_tile_id":"3e18e4967bee8bbbf8f780ae:0","filtered_window_id":"3e18e4967bee8bbbf8f780ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3e18e4967bee8bbbf8f780ae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject2/o2/4/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"3e18e4967bee8bbbf8f780ae:8","filtered_window_id":"3e18e4967bee8bbbf8f780ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3e18e4967bee8bbbf8f780ae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject2/o2/4/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"3e18e4967bee8bbbf8f780ae:16","filtered_window_id":"3e18e4967bee8bbbf8f780ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3e18e4967bee8bbbf8f780ae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject2/o2/4/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"3e18e4967bee8bbbf8f780ae:24","filtered_window_id":"3e18e4967bee8bbbf8f780ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3e18e4967bee8bbbf8f780ae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject2/o2/4/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"3e18e4967bee8bbbf8f780ae:32","filtered_window_id":"3e18e4967bee8bbbf8f780ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3e18e4967bee8bbbf8f780ae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject2/o2/4/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"3e18e4967bee8bbbf8f780ae:40","filtered_window_id":"3e18e4967bee8bbbf8f780ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3e18e4967bee8bbbf8f780ae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject2/o2/4/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"3e18e4967bee8bbbf8f780ae:48","filtered_window_id":"3e18e4967bee8bbbf8f780ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3e18e4967bee8bbbf8f780ae/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject2/o2/4/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"3e18e4967bee8bbbf8f780ae:52","filtered_window_id":"3e18e4967bee8bbbf8f780ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3e18e4967bee8bbbf8f780ae/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject2/o2/4/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"3eb4f0b79b20742a5db2c154:0","filtered_window_id":"3eb4f0b79b20742a5db2c154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3eb4f0b79b20742a5db2c154/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[405,406,407,408,409,410,411,412],"take":"subject1/k2/4/cam4","frame_ids":[405,406,407,408,409,410,411,412]} +{"filtered_tile_id":"3eb4f0b79b20742a5db2c154:8","filtered_window_id":"3eb4f0b79b20742a5db2c154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3eb4f0b79b20742a5db2c154/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[413,414,415,416,417,418,419,420],"take":"subject1/k2/4/cam4","frame_ids":[413,414,415,416,417,418,419,420]} +{"filtered_tile_id":"3eb4f0b79b20742a5db2c154:16","filtered_window_id":"3eb4f0b79b20742a5db2c154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3eb4f0b79b20742a5db2c154/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[421,422,423,424,425,426,427,428],"take":"subject1/k2/4/cam4","frame_ids":[421,422,423,424,425,426,427,428]} +{"filtered_tile_id":"3eb4f0b79b20742a5db2c154:24","filtered_window_id":"3eb4f0b79b20742a5db2c154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3eb4f0b79b20742a5db2c154/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[429,430,431,432,433,434,435,436],"take":"subject1/k2/4/cam4","frame_ids":[429,430,431,432,433,434,435,436]} +{"filtered_tile_id":"3eb4f0b79b20742a5db2c154:32","filtered_window_id":"3eb4f0b79b20742a5db2c154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3eb4f0b79b20742a5db2c154/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[437,438,439,440,441,442,443,444],"take":"subject1/k2/4/cam4","frame_ids":[437,438,439,440,441,442,443,444]} +{"filtered_tile_id":"3eb4f0b79b20742a5db2c154:40","filtered_window_id":"3eb4f0b79b20742a5db2c154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3eb4f0b79b20742a5db2c154/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[445,446,447,448,449,450,451,452],"take":"subject1/k2/4/cam4","frame_ids":[445,446,447,448,449,450,451,452]} +{"filtered_tile_id":"3f2c6601d76ae42963a079dd:0","filtered_window_id":"3f2c6601d76ae42963a079dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f2c6601d76ae42963a079dd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[294,295,296,297,298,299,300,301],"take":"subject2/h2/0/cam4","frame_ids":[294,295,296,297,298,299,300,301]} +{"filtered_tile_id":"3f2c6601d76ae42963a079dd:8","filtered_window_id":"3f2c6601d76ae42963a079dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f2c6601d76ae42963a079dd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[302,303,304,305,306,307,308,309],"take":"subject2/h2/0/cam4","frame_ids":[302,303,304,305,306,307,308,309]} +{"filtered_tile_id":"3f2c6601d76ae42963a079dd:16","filtered_window_id":"3f2c6601d76ae42963a079dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f2c6601d76ae42963a079dd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject2/h2/0/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"3f2c6601d76ae42963a079dd:24","filtered_window_id":"3f2c6601d76ae42963a079dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f2c6601d76ae42963a079dd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject2/h2/0/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"3f2c6601d76ae42963a079dd:32","filtered_window_id":"3f2c6601d76ae42963a079dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f2c6601d76ae42963a079dd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject2/h2/0/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"3f2c6601d76ae42963a079dd:38","filtered_window_id":"3f2c6601d76ae42963a079dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f2c6601d76ae42963a079dd/native_gt.npz","filtered_start_offset":38,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject2/h2/0/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"3f31abaaab70acee125ca17b:0","filtered_window_id":"3f31abaaab70acee125ca17b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f31abaaab70acee125ca17b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject3/k1/5/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"3f31abaaab70acee125ca17b:8","filtered_window_id":"3f31abaaab70acee125ca17b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f31abaaab70acee125ca17b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject3/k1/5/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"3f31abaaab70acee125ca17b:16","filtered_window_id":"3f31abaaab70acee125ca17b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f31abaaab70acee125ca17b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject3/k1/5/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"3f31abaaab70acee125ca17b:24","filtered_window_id":"3f31abaaab70acee125ca17b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f31abaaab70acee125ca17b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject3/k1/5/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"3f31abaaab70acee125ca17b:32","filtered_window_id":"3f31abaaab70acee125ca17b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f31abaaab70acee125ca17b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject3/k1/5/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"3f31abaaab70acee125ca17b:40","filtered_window_id":"3f31abaaab70acee125ca17b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f31abaaab70acee125ca17b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject3/k1/5/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"3f31abaaab70acee125ca17b:48","filtered_window_id":"3f31abaaab70acee125ca17b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f31abaaab70acee125ca17b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject3/k1/5/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"3f31abaaab70acee125ca17b:52","filtered_window_id":"3f31abaaab70acee125ca17b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f31abaaab70acee125ca17b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[448,449,450,451,452,453,454,455],"take":"subject3/k1/5/cam4","frame_ids":[448,449,450,451,452,453,454,455]} +{"filtered_tile_id":"3f58141f062fc23354ed74cf:0","filtered_window_id":"3f58141f062fc23354ed74cf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f58141f062fc23354ed74cf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject3/k1/1/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"3f58141f062fc23354ed74cf:8","filtered_window_id":"3f58141f062fc23354ed74cf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f58141f062fc23354ed74cf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject3/k1/1/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"3f58141f062fc23354ed74cf:16","filtered_window_id":"3f58141f062fc23354ed74cf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f58141f062fc23354ed74cf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[426,427,428,429,430,431,432,433],"take":"subject3/k1/1/cam4","frame_ids":[426,427,428,429,430,431,432,433]} +{"filtered_tile_id":"3f58141f062fc23354ed74cf:24","filtered_window_id":"3f58141f062fc23354ed74cf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f58141f062fc23354ed74cf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[434,435,436,437,438,439,440,441],"take":"subject3/k1/1/cam4","frame_ids":[434,435,436,437,438,439,440,441]} +{"filtered_tile_id":"3f58141f062fc23354ed74cf:32","filtered_window_id":"3f58141f062fc23354ed74cf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f58141f062fc23354ed74cf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject3/k1/1/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"3f58141f062fc23354ed74cf:40","filtered_window_id":"3f58141f062fc23354ed74cf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f58141f062fc23354ed74cf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject3/k1/1/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"3f58141f062fc23354ed74cf:48","filtered_window_id":"3f58141f062fc23354ed74cf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f58141f062fc23354ed74cf/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject3/k1/1/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"3f58141f062fc23354ed74cf:52","filtered_window_id":"3f58141f062fc23354ed74cf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/3f58141f062fc23354ed74cf/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject3/k1/1/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"411bc9346cd24a02b74f03e2:0","filtered_window_id":"411bc9346cd24a02b74f03e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411bc9346cd24a02b74f03e2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[295,296,297,298,299,300,301,302],"take":"subject2/o2/1/cam4","frame_ids":[295,296,297,298,299,300,301,302]} +{"filtered_tile_id":"411bc9346cd24a02b74f03e2:8","filtered_window_id":"411bc9346cd24a02b74f03e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411bc9346cd24a02b74f03e2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[303,304,305,306,307,308,309,310],"take":"subject2/o2/1/cam4","frame_ids":[303,304,305,306,307,308,309,310]} +{"filtered_tile_id":"411bc9346cd24a02b74f03e2:16","filtered_window_id":"411bc9346cd24a02b74f03e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411bc9346cd24a02b74f03e2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[311,312,313,314,315,316,317,318],"take":"subject2/o2/1/cam4","frame_ids":[311,312,313,314,315,316,317,318]} +{"filtered_tile_id":"411bc9346cd24a02b74f03e2:24","filtered_window_id":"411bc9346cd24a02b74f03e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411bc9346cd24a02b74f03e2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[319,320,321,322,323,324,325,326],"take":"subject2/o2/1/cam4","frame_ids":[319,320,321,322,323,324,325,326]} +{"filtered_tile_id":"411bc9346cd24a02b74f03e2:32","filtered_window_id":"411bc9346cd24a02b74f03e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411bc9346cd24a02b74f03e2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[327,328,329,330,331,332,333,334],"take":"subject2/o2/1/cam4","frame_ids":[327,328,329,330,331,332,333,334]} +{"filtered_tile_id":"411bc9346cd24a02b74f03e2:40","filtered_window_id":"411bc9346cd24a02b74f03e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411bc9346cd24a02b74f03e2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[335,336,337,338,339,340,341,342],"take":"subject2/o2/1/cam4","frame_ids":[335,336,337,338,339,340,341,342]} +{"filtered_tile_id":"411bc9346cd24a02b74f03e2:48","filtered_window_id":"411bc9346cd24a02b74f03e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411bc9346cd24a02b74f03e2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[343,344,345,346,347,348,349,350],"take":"subject2/o2/1/cam4","frame_ids":[343,344,345,346,347,348,349,350]} +{"filtered_tile_id":"411bc9346cd24a02b74f03e2:52","filtered_window_id":"411bc9346cd24a02b74f03e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411bc9346cd24a02b74f03e2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[347,348,349,350,351,352,353,354],"take":"subject2/o2/1/cam4","frame_ids":[347,348,349,350,351,352,353,354]} +{"filtered_tile_id":"411d0a1eb006479362e60e22:0","filtered_window_id":"411d0a1eb006479362e60e22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411d0a1eb006479362e60e22/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject1/o2/2/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"411d0a1eb006479362e60e22:8","filtered_window_id":"411d0a1eb006479362e60e22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411d0a1eb006479362e60e22/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[86,87,88,89,90,91,92,93],"take":"subject1/o2/2/cam4","frame_ids":[86,87,88,89,90,91,92,93]} +{"filtered_tile_id":"411d0a1eb006479362e60e22:16","filtered_window_id":"411d0a1eb006479362e60e22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411d0a1eb006479362e60e22/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[94,95,96,97,98,99,100,101],"take":"subject1/o2/2/cam4","frame_ids":[94,95,96,97,98,99,100,101]} +{"filtered_tile_id":"411d0a1eb006479362e60e22:24","filtered_window_id":"411d0a1eb006479362e60e22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411d0a1eb006479362e60e22/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[102,103,104,105,106,107,108,109],"take":"subject1/o2/2/cam4","frame_ids":[102,103,104,105,106,107,108,109]} +{"filtered_tile_id":"411d0a1eb006479362e60e22:32","filtered_window_id":"411d0a1eb006479362e60e22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411d0a1eb006479362e60e22/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[110,111,112,113,114,115,116,117],"take":"subject1/o2/2/cam4","frame_ids":[110,111,112,113,114,115,116,117]} +{"filtered_tile_id":"411d0a1eb006479362e60e22:40","filtered_window_id":"411d0a1eb006479362e60e22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411d0a1eb006479362e60e22/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[118,119,120,121,122,123,124,125],"take":"subject1/o2/2/cam4","frame_ids":[118,119,120,121,122,123,124,125]} +{"filtered_tile_id":"411d0a1eb006479362e60e22:48","filtered_window_id":"411d0a1eb006479362e60e22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411d0a1eb006479362e60e22/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[126,127,128,129,130,131,132,133],"take":"subject1/o2/2/cam4","frame_ids":[126,127,128,129,130,131,132,133]} +{"filtered_tile_id":"411d0a1eb006479362e60e22:52","filtered_window_id":"411d0a1eb006479362e60e22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/411d0a1eb006479362e60e22/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject1/o2/2/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"41cdd2a0c8d852c3b1e5ce18:0","filtered_window_id":"41cdd2a0c8d852c3b1e5ce18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/41cdd2a0c8d852c3b1e5ce18/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/k1/4/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"41cdd2a0c8d852c3b1e5ce18:8","filtered_window_id":"41cdd2a0c8d852c3b1e5ce18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/41cdd2a0c8d852c3b1e5ce18/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/k1/4/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"41cdd2a0c8d852c3b1e5ce18:16","filtered_window_id":"41cdd2a0c8d852c3b1e5ce18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/41cdd2a0c8d852c3b1e5ce18/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k1/4/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"41cdd2a0c8d852c3b1e5ce18:24","filtered_window_id":"41cdd2a0c8d852c3b1e5ce18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/41cdd2a0c8d852c3b1e5ce18/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k1/4/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"41cdd2a0c8d852c3b1e5ce18:32","filtered_window_id":"41cdd2a0c8d852c3b1e5ce18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/41cdd2a0c8d852c3b1e5ce18/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k1/4/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"41cdd2a0c8d852c3b1e5ce18:40","filtered_window_id":"41cdd2a0c8d852c3b1e5ce18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/41cdd2a0c8d852c3b1e5ce18/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/k1/4/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"41cdd2a0c8d852c3b1e5ce18:48","filtered_window_id":"41cdd2a0c8d852c3b1e5ce18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/41cdd2a0c8d852c3b1e5ce18/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/k1/4/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"41cdd2a0c8d852c3b1e5ce18:49","filtered_window_id":"41cdd2a0c8d852c3b1e5ce18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/41cdd2a0c8d852c3b1e5ce18/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[49,50,51,52,53,54,55,56],"take":"subject1/k1/4/cam4","frame_ids":[49,50,51,52,53,54,55,56]} +{"filtered_tile_id":"422adb075b7087c15ab5693a:0","filtered_window_id":"422adb075b7087c15ab5693a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/422adb075b7087c15ab5693a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[121,122,123,124,125,126,127,128],"take":"subject1/h2/1/cam4","frame_ids":[121,122,123,124,125,126,127,128]} +{"filtered_tile_id":"422adb075b7087c15ab5693a:8","filtered_window_id":"422adb075b7087c15ab5693a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/422adb075b7087c15ab5693a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject1/h2/1/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"422adb075b7087c15ab5693a:16","filtered_window_id":"422adb075b7087c15ab5693a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/422adb075b7087c15ab5693a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject1/h2/1/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"422adb075b7087c15ab5693a:24","filtered_window_id":"422adb075b7087c15ab5693a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/422adb075b7087c15ab5693a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject1/h2/1/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"422adb075b7087c15ab5693a:32","filtered_window_id":"422adb075b7087c15ab5693a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/422adb075b7087c15ab5693a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject1/h2/1/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"422adb075b7087c15ab5693a:40","filtered_window_id":"422adb075b7087c15ab5693a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/422adb075b7087c15ab5693a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject1/h2/1/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"422adb075b7087c15ab5693a:48","filtered_window_id":"422adb075b7087c15ab5693a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/422adb075b7087c15ab5693a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject1/h2/1/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"422adb075b7087c15ab5693a:52","filtered_window_id":"422adb075b7087c15ab5693a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/422adb075b7087c15ab5693a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject1/h2/1/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"426ed69f70291fa123cd0417:0","filtered_window_id":"426ed69f70291fa123cd0417","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/426ed69f70291fa123cd0417/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject2/h1/2/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"426ed69f70291fa123cd0417:8","filtered_window_id":"426ed69f70291fa123cd0417","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/426ed69f70291fa123cd0417/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject2/h1/2/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"426ed69f70291fa123cd0417:16","filtered_window_id":"426ed69f70291fa123cd0417","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/426ed69f70291fa123cd0417/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject2/h1/2/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"426ed69f70291fa123cd0417:24","filtered_window_id":"426ed69f70291fa123cd0417","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/426ed69f70291fa123cd0417/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[572,573,574,575,576,577,578,579],"take":"subject2/h1/2/cam4","frame_ids":[572,573,574,575,576,577,578,579]} +{"filtered_tile_id":"426ed69f70291fa123cd0417:32","filtered_window_id":"426ed69f70291fa123cd0417","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/426ed69f70291fa123cd0417/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[580,581,582,583,584,585,586,587],"take":"subject2/h1/2/cam4","frame_ids":[580,581,582,583,584,585,586,587]} +{"filtered_tile_id":"426ed69f70291fa123cd0417:40","filtered_window_id":"426ed69f70291fa123cd0417","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/426ed69f70291fa123cd0417/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[588,589,590,591,592,593,594,595],"take":"subject2/h1/2/cam4","frame_ids":[588,589,590,591,592,593,594,595]} +{"filtered_tile_id":"426ed69f70291fa123cd0417:48","filtered_window_id":"426ed69f70291fa123cd0417","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/426ed69f70291fa123cd0417/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[596,597,598,599,600,601,602,603],"take":"subject2/h1/2/cam4","frame_ids":[596,597,598,599,600,601,602,603]} +{"filtered_tile_id":"426ed69f70291fa123cd0417:52","filtered_window_id":"426ed69f70291fa123cd0417","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/426ed69f70291fa123cd0417/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[600,601,602,603,604,605,606,607],"take":"subject2/h1/2/cam4","frame_ids":[600,601,602,603,604,605,606,607]} +{"filtered_tile_id":"4453f5c30cf077909efa6df5:0","filtered_window_id":"4453f5c30cf077909efa6df5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4453f5c30cf077909efa6df5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject3/h1/4/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"4453f5c30cf077909efa6df5:6","filtered_window_id":"4453f5c30cf077909efa6df5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4453f5c30cf077909efa6df5/native_gt.npz","filtered_start_offset":6,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject3/h1/4/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"446d5568ec06ff1493ac6174:0","filtered_window_id":"446d5568ec06ff1493ac6174","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/446d5568ec06ff1493ac6174/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[433,434,435,436,437,438,439,440],"take":"subject2/k1/3/cam4","frame_ids":[433,434,435,436,437,438,439,440]} +{"filtered_tile_id":"446d5568ec06ff1493ac6174:8","filtered_window_id":"446d5568ec06ff1493ac6174","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/446d5568ec06ff1493ac6174/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject2/k1/3/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"446d5568ec06ff1493ac6174:16","filtered_window_id":"446d5568ec06ff1493ac6174","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/446d5568ec06ff1493ac6174/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject2/k1/3/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"446d5568ec06ff1493ac6174:24","filtered_window_id":"446d5568ec06ff1493ac6174","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/446d5568ec06ff1493ac6174/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject2/k1/3/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"446d5568ec06ff1493ac6174:28","filtered_window_id":"446d5568ec06ff1493ac6174","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/446d5568ec06ff1493ac6174/native_gt.npz","filtered_start_offset":28,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject2/k1/3/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"448badcd2b1d641278fbbe80:0","filtered_window_id":"448badcd2b1d641278fbbe80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/448badcd2b1d641278fbbe80/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h2/4/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"448badcd2b1d641278fbbe80:8","filtered_window_id":"448badcd2b1d641278fbbe80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/448badcd2b1d641278fbbe80/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h2/4/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"448badcd2b1d641278fbbe80:16","filtered_window_id":"448badcd2b1d641278fbbe80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/448badcd2b1d641278fbbe80/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h2/4/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"448badcd2b1d641278fbbe80:24","filtered_window_id":"448badcd2b1d641278fbbe80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/448badcd2b1d641278fbbe80/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h2/4/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"448badcd2b1d641278fbbe80:32","filtered_window_id":"448badcd2b1d641278fbbe80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/448badcd2b1d641278fbbe80/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h2/4/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"448badcd2b1d641278fbbe80:40","filtered_window_id":"448badcd2b1d641278fbbe80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/448badcd2b1d641278fbbe80/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/h2/4/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"448badcd2b1d641278fbbe80:47","filtered_window_id":"448badcd2b1d641278fbbe80","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/448badcd2b1d641278fbbe80/native_gt.npz","filtered_start_offset":47,"expected_frame_ids":[47,48,49,50,51,52,53,54],"take":"subject1/h2/4/cam4","frame_ids":[47,48,49,50,51,52,53,54]} +{"filtered_tile_id":"44b990f87a0ece372a495ddb:0","filtered_window_id":"44b990f87a0ece372a495ddb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/44b990f87a0ece372a495ddb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[679,680,681,682,683,684,685,686],"take":"subject3/k1/3/cam4","frame_ids":[679,680,681,682,683,684,685,686]} +{"filtered_tile_id":"44b990f87a0ece372a495ddb:8","filtered_window_id":"44b990f87a0ece372a495ddb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/44b990f87a0ece372a495ddb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[687,688,689,690,691,692,693,694],"take":"subject3/k1/3/cam4","frame_ids":[687,688,689,690,691,692,693,694]} +{"filtered_tile_id":"44b990f87a0ece372a495ddb:13","filtered_window_id":"44b990f87a0ece372a495ddb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/44b990f87a0ece372a495ddb/native_gt.npz","filtered_start_offset":13,"expected_frame_ids":[692,693,694,695,696,697,698,699],"take":"subject3/k1/3/cam4","frame_ids":[692,693,694,695,696,697,698,699]} +{"filtered_tile_id":"451436cc6b62a3d4a6724f5c:0","filtered_window_id":"451436cc6b62a3d4a6724f5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/451436cc6b62a3d4a6724f5c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject1/k1/4/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"451436cc6b62a3d4a6724f5c:8","filtered_window_id":"451436cc6b62a3d4a6724f5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/451436cc6b62a3d4a6724f5c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject1/k1/4/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"451436cc6b62a3d4a6724f5c:16","filtered_window_id":"451436cc6b62a3d4a6724f5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/451436cc6b62a3d4a6724f5c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject1/k1/4/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"451436cc6b62a3d4a6724f5c:24","filtered_window_id":"451436cc6b62a3d4a6724f5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/451436cc6b62a3d4a6724f5c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject1/k1/4/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"451436cc6b62a3d4a6724f5c:32","filtered_window_id":"451436cc6b62a3d4a6724f5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/451436cc6b62a3d4a6724f5c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject1/k1/4/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"451436cc6b62a3d4a6724f5c:40","filtered_window_id":"451436cc6b62a3d4a6724f5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/451436cc6b62a3d4a6724f5c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject1/k1/4/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"451436cc6b62a3d4a6724f5c:48","filtered_window_id":"451436cc6b62a3d4a6724f5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/451436cc6b62a3d4a6724f5c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject1/k1/4/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"451436cc6b62a3d4a6724f5c:52","filtered_window_id":"451436cc6b62a3d4a6724f5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/451436cc6b62a3d4a6724f5c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[522,523,524,525,526,527,528,529],"take":"subject1/k1/4/cam4","frame_ids":[522,523,524,525,526,527,528,529]} +{"filtered_tile_id":"456632a2c10bf91fe4cc8ef3:0","filtered_window_id":"456632a2c10bf91fe4cc8ef3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/456632a2c10bf91fe4cc8ef3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[613,614,615,616,617,618,619,620],"take":"subject3/h2/1/cam4","frame_ids":[613,614,615,616,617,618,619,620]} +{"filtered_tile_id":"456632a2c10bf91fe4cc8ef3:8","filtered_window_id":"456632a2c10bf91fe4cc8ef3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/456632a2c10bf91fe4cc8ef3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[621,622,623,624,625,626,627,628],"take":"subject3/h2/1/cam4","frame_ids":[621,622,623,624,625,626,627,628]} +{"filtered_tile_id":"456632a2c10bf91fe4cc8ef3:16","filtered_window_id":"456632a2c10bf91fe4cc8ef3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/456632a2c10bf91fe4cc8ef3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[629,630,631,632,633,634,635,636],"take":"subject3/h2/1/cam4","frame_ids":[629,630,631,632,633,634,635,636]} +{"filtered_tile_id":"456632a2c10bf91fe4cc8ef3:24","filtered_window_id":"456632a2c10bf91fe4cc8ef3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/456632a2c10bf91fe4cc8ef3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[637,638,639,640,641,642,643,644],"take":"subject3/h2/1/cam4","frame_ids":[637,638,639,640,641,642,643,644]} +{"filtered_tile_id":"456632a2c10bf91fe4cc8ef3:32","filtered_window_id":"456632a2c10bf91fe4cc8ef3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/456632a2c10bf91fe4cc8ef3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[645,646,647,648,649,650,651,652],"take":"subject3/h2/1/cam4","frame_ids":[645,646,647,648,649,650,651,652]} +{"filtered_tile_id":"456632a2c10bf91fe4cc8ef3:40","filtered_window_id":"456632a2c10bf91fe4cc8ef3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/456632a2c10bf91fe4cc8ef3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[653,654,655,656,657,658,659,660],"take":"subject3/h2/1/cam4","frame_ids":[653,654,655,656,657,658,659,660]} +{"filtered_tile_id":"456632a2c10bf91fe4cc8ef3:48","filtered_window_id":"456632a2c10bf91fe4cc8ef3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/456632a2c10bf91fe4cc8ef3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[661,662,663,664,665,666,667,668],"take":"subject3/h2/1/cam4","frame_ids":[661,662,663,664,665,666,667,668]} +{"filtered_tile_id":"456632a2c10bf91fe4cc8ef3:52","filtered_window_id":"456632a2c10bf91fe4cc8ef3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/456632a2c10bf91fe4cc8ef3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[665,666,667,668,669,670,671,672],"take":"subject3/h2/1/cam4","frame_ids":[665,666,667,668,669,670,671,672]} +{"filtered_tile_id":"462a9d738579132f8c0653cd:0","filtered_window_id":"462a9d738579132f8c0653cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/462a9d738579132f8c0653cd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject2/h2/4/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"462a9d738579132f8c0653cd:8","filtered_window_id":"462a9d738579132f8c0653cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/462a9d738579132f8c0653cd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject2/h2/4/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"462a9d738579132f8c0653cd:16","filtered_window_id":"462a9d738579132f8c0653cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/462a9d738579132f8c0653cd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[373,374,375,376,377,378,379,380],"take":"subject2/h2/4/cam4","frame_ids":[373,374,375,376,377,378,379,380]} +{"filtered_tile_id":"462a9d738579132f8c0653cd:24","filtered_window_id":"462a9d738579132f8c0653cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/462a9d738579132f8c0653cd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[381,382,383,384,385,386,387,388],"take":"subject2/h2/4/cam4","frame_ids":[381,382,383,384,385,386,387,388]} +{"filtered_tile_id":"462a9d738579132f8c0653cd:32","filtered_window_id":"462a9d738579132f8c0653cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/462a9d738579132f8c0653cd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[389,390,391,392,393,394,395,396],"take":"subject2/h2/4/cam4","frame_ids":[389,390,391,392,393,394,395,396]} +{"filtered_tile_id":"462a9d738579132f8c0653cd:40","filtered_window_id":"462a9d738579132f8c0653cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/462a9d738579132f8c0653cd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[397,398,399,400,401,402,403,404],"take":"subject2/h2/4/cam4","frame_ids":[397,398,399,400,401,402,403,404]} +{"filtered_tile_id":"462a9d738579132f8c0653cd:48","filtered_window_id":"462a9d738579132f8c0653cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/462a9d738579132f8c0653cd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[405,406,407,408,409,410,411,412],"take":"subject2/h2/4/cam4","frame_ids":[405,406,407,408,409,410,411,412]} +{"filtered_tile_id":"462a9d738579132f8c0653cd:52","filtered_window_id":"462a9d738579132f8c0653cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/462a9d738579132f8c0653cd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[409,410,411,412,413,414,415,416],"take":"subject2/h2/4/cam4","frame_ids":[409,410,411,412,413,414,415,416]} +{"filtered_tile_id":"4638589d93af44c851727def:0","filtered_window_id":"4638589d93af44c851727def","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4638589d93af44c851727def/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[424,425,426,427,428,429,430,431],"take":"subject1/h1/1/cam4","frame_ids":[424,425,426,427,428,429,430,431]} +{"filtered_tile_id":"4638589d93af44c851727def:8","filtered_window_id":"4638589d93af44c851727def","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4638589d93af44c851727def/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[432,433,434,435,436,437,438,439],"take":"subject1/h1/1/cam4","frame_ids":[432,433,434,435,436,437,438,439]} +{"filtered_tile_id":"4638589d93af44c851727def:11","filtered_window_id":"4638589d93af44c851727def","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4638589d93af44c851727def/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/h1/1/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"463f2b0444b025dd7cf95f1a:0","filtered_window_id":"463f2b0444b025dd7cf95f1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/463f2b0444b025dd7cf95f1a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject2/h1/1/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"463f2b0444b025dd7cf95f1a:8","filtered_window_id":"463f2b0444b025dd7cf95f1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/463f2b0444b025dd7cf95f1a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[426,427,428,429,430,431,432,433],"take":"subject2/h1/1/cam4","frame_ids":[426,427,428,429,430,431,432,433]} +{"filtered_tile_id":"463f2b0444b025dd7cf95f1a:16","filtered_window_id":"463f2b0444b025dd7cf95f1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/463f2b0444b025dd7cf95f1a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[434,435,436,437,438,439,440,441],"take":"subject2/h1/1/cam4","frame_ids":[434,435,436,437,438,439,440,441]} +{"filtered_tile_id":"463f2b0444b025dd7cf95f1a:19","filtered_window_id":"463f2b0444b025dd7cf95f1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/463f2b0444b025dd7cf95f1a/native_gt.npz","filtered_start_offset":19,"expected_frame_ids":[437,438,439,440,441,442,443,444],"take":"subject2/h1/1/cam4","frame_ids":[437,438,439,440,441,442,443,444]} +{"filtered_tile_id":"4668f6315a400b5319aeb32d:0","filtered_window_id":"4668f6315a400b5319aeb32d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4668f6315a400b5319aeb32d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject3/h2/5/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"4668f6315a400b5319aeb32d:8","filtered_window_id":"4668f6315a400b5319aeb32d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4668f6315a400b5319aeb32d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject3/h2/5/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"4668f6315a400b5319aeb32d:16","filtered_window_id":"4668f6315a400b5319aeb32d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4668f6315a400b5319aeb32d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject3/h2/5/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"4668f6315a400b5319aeb32d:24","filtered_window_id":"4668f6315a400b5319aeb32d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4668f6315a400b5319aeb32d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[536,537,538,539,540,541,542,543],"take":"subject3/h2/5/cam4","frame_ids":[536,537,538,539,540,541,542,543]} +{"filtered_tile_id":"4668f6315a400b5319aeb32d:32","filtered_window_id":"4668f6315a400b5319aeb32d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4668f6315a400b5319aeb32d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[544,545,546,547,548,549,550,551],"take":"subject3/h2/5/cam4","frame_ids":[544,545,546,547,548,549,550,551]} +{"filtered_tile_id":"4668f6315a400b5319aeb32d:40","filtered_window_id":"4668f6315a400b5319aeb32d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4668f6315a400b5319aeb32d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[552,553,554,555,556,557,558,559],"take":"subject3/h2/5/cam4","frame_ids":[552,553,554,555,556,557,558,559]} +{"filtered_tile_id":"4668f6315a400b5319aeb32d:44","filtered_window_id":"4668f6315a400b5319aeb32d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4668f6315a400b5319aeb32d/native_gt.npz","filtered_start_offset":44,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject3/h2/5/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"4679032cafc8fe186292c8ee:0","filtered_window_id":"4679032cafc8fe186292c8ee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4679032cafc8fe186292c8ee/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[12,13,14,15,16,17,18,19],"take":"subject2/h1/0/cam4","frame_ids":[12,13,14,15,16,17,18,19]} +{"filtered_tile_id":"4679032cafc8fe186292c8ee:8","filtered_window_id":"4679032cafc8fe186292c8ee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4679032cafc8fe186292c8ee/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[20,21,22,23,24,25,26,27],"take":"subject2/h1/0/cam4","frame_ids":[20,21,22,23,24,25,26,27]} +{"filtered_tile_id":"4679032cafc8fe186292c8ee:16","filtered_window_id":"4679032cafc8fe186292c8ee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4679032cafc8fe186292c8ee/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[28,29,30,31,32,33,34,35],"take":"subject2/h1/0/cam4","frame_ids":[28,29,30,31,32,33,34,35]} +{"filtered_tile_id":"4679032cafc8fe186292c8ee:24","filtered_window_id":"4679032cafc8fe186292c8ee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4679032cafc8fe186292c8ee/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[36,37,38,39,40,41,42,43],"take":"subject2/h1/0/cam4","frame_ids":[36,37,38,39,40,41,42,43]} +{"filtered_tile_id":"4679032cafc8fe186292c8ee:32","filtered_window_id":"4679032cafc8fe186292c8ee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4679032cafc8fe186292c8ee/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[44,45,46,47,48,49,50,51],"take":"subject2/h1/0/cam4","frame_ids":[44,45,46,47,48,49,50,51]} +{"filtered_tile_id":"4679032cafc8fe186292c8ee:40","filtered_window_id":"4679032cafc8fe186292c8ee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4679032cafc8fe186292c8ee/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/h1/0/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"4679032cafc8fe186292c8ee:48","filtered_window_id":"4679032cafc8fe186292c8ee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4679032cafc8fe186292c8ee/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/h1/0/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"4679032cafc8fe186292c8ee:52","filtered_window_id":"4679032cafc8fe186292c8ee","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4679032cafc8fe186292c8ee/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject2/h1/0/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"4697690edf59815e3dc120cb:0","filtered_window_id":"4697690edf59815e3dc120cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4697690edf59815e3dc120cb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject2/h2/0/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"4697690edf59815e3dc120cb:8","filtered_window_id":"4697690edf59815e3dc120cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4697690edf59815e3dc120cb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject2/h2/0/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"4697690edf59815e3dc120cb:16","filtered_window_id":"4697690edf59815e3dc120cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4697690edf59815e3dc120cb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject2/h2/0/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"4697690edf59815e3dc120cb:24","filtered_window_id":"4697690edf59815e3dc120cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4697690edf59815e3dc120cb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject2/h2/0/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"4697690edf59815e3dc120cb:32","filtered_window_id":"4697690edf59815e3dc120cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4697690edf59815e3dc120cb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject2/h2/0/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"4697690edf59815e3dc120cb:40","filtered_window_id":"4697690edf59815e3dc120cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4697690edf59815e3dc120cb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[274,275,276,277,278,279,280,281],"take":"subject2/h2/0/cam4","frame_ids":[274,275,276,277,278,279,280,281]} +{"filtered_tile_id":"4697690edf59815e3dc120cb:48","filtered_window_id":"4697690edf59815e3dc120cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4697690edf59815e3dc120cb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject2/h2/0/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"4697690edf59815e3dc120cb:52","filtered_window_id":"4697690edf59815e3dc120cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4697690edf59815e3dc120cb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[286,287,288,289,290,291,292,293],"take":"subject2/h2/0/cam4","frame_ids":[286,287,288,289,290,291,292,293]} +{"filtered_tile_id":"46daa9774594223ec4ab2f8a:0","filtered_window_id":"46daa9774594223ec4ab2f8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/46daa9774594223ec4ab2f8a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[729,730,731,732,733,734,735,736],"take":"subject2/o1/1/cam4","frame_ids":[729,730,731,732,733,734,735,736]} +{"filtered_tile_id":"46daa9774594223ec4ab2f8a:8","filtered_window_id":"46daa9774594223ec4ab2f8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/46daa9774594223ec4ab2f8a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[737,738,739,740,741,742,743,744],"take":"subject2/o1/1/cam4","frame_ids":[737,738,739,740,741,742,743,744]} +{"filtered_tile_id":"46daa9774594223ec4ab2f8a:16","filtered_window_id":"46daa9774594223ec4ab2f8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/46daa9774594223ec4ab2f8a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[745,746,747,748,749,750,751,752],"take":"subject2/o1/1/cam4","frame_ids":[745,746,747,748,749,750,751,752]} +{"filtered_tile_id":"46daa9774594223ec4ab2f8a:24","filtered_window_id":"46daa9774594223ec4ab2f8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/46daa9774594223ec4ab2f8a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[753,754,755,756,757,758,759,760],"take":"subject2/o1/1/cam4","frame_ids":[753,754,755,756,757,758,759,760]} +{"filtered_tile_id":"46daa9774594223ec4ab2f8a:32","filtered_window_id":"46daa9774594223ec4ab2f8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/46daa9774594223ec4ab2f8a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[761,762,763,764,765,766,767,768],"take":"subject2/o1/1/cam4","frame_ids":[761,762,763,764,765,766,767,768]} +{"filtered_tile_id":"46daa9774594223ec4ab2f8a:40","filtered_window_id":"46daa9774594223ec4ab2f8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/46daa9774594223ec4ab2f8a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[769,770,771,772,773,774,775,776],"take":"subject2/o1/1/cam4","frame_ids":[769,770,771,772,773,774,775,776]} +{"filtered_tile_id":"46daa9774594223ec4ab2f8a:48","filtered_window_id":"46daa9774594223ec4ab2f8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/46daa9774594223ec4ab2f8a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[777,778,779,780,781,782,783,784],"take":"subject2/o1/1/cam4","frame_ids":[777,778,779,780,781,782,783,784]} +{"filtered_tile_id":"46daa9774594223ec4ab2f8a:52","filtered_window_id":"46daa9774594223ec4ab2f8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/46daa9774594223ec4ab2f8a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[781,782,783,784,785,786,787,788],"take":"subject2/o1/1/cam4","frame_ids":[781,782,783,784,785,786,787,788]} +{"filtered_tile_id":"474f08f84a87aa9ab5e2c40e:0","filtered_window_id":"474f08f84a87aa9ab5e2c40e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/474f08f84a87aa9ab5e2c40e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject1/h1/6/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"474f08f84a87aa9ab5e2c40e:7","filtered_window_id":"474f08f84a87aa9ab5e2c40e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/474f08f84a87aa9ab5e2c40e/native_gt.npz","filtered_start_offset":7,"expected_frame_ids":[244,245,246,247,248,249,250,251],"take":"subject1/h1/6/cam4","frame_ids":[244,245,246,247,248,249,250,251]} +{"filtered_tile_id":"4758f1bcc27c21ae12739902:0","filtered_window_id":"4758f1bcc27c21ae12739902","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4758f1bcc27c21ae12739902/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject2/h1/3/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"4758f1bcc27c21ae12739902:8","filtered_window_id":"4758f1bcc27c21ae12739902","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4758f1bcc27c21ae12739902/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[306,307,308,309,310,311,312,313],"take":"subject2/h1/3/cam4","frame_ids":[306,307,308,309,310,311,312,313]} +{"filtered_tile_id":"4758f1bcc27c21ae12739902:16","filtered_window_id":"4758f1bcc27c21ae12739902","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4758f1bcc27c21ae12739902/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject2/h1/3/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"4758f1bcc27c21ae12739902:24","filtered_window_id":"4758f1bcc27c21ae12739902","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4758f1bcc27c21ae12739902/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject2/h1/3/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"4758f1bcc27c21ae12739902:32","filtered_window_id":"4758f1bcc27c21ae12739902","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4758f1bcc27c21ae12739902/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject2/h1/3/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"4758f1bcc27c21ae12739902:40","filtered_window_id":"4758f1bcc27c21ae12739902","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4758f1bcc27c21ae12739902/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject2/h1/3/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"4758f1bcc27c21ae12739902:48","filtered_window_id":"4758f1bcc27c21ae12739902","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4758f1bcc27c21ae12739902/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject2/h1/3/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"4758f1bcc27c21ae12739902:52","filtered_window_id":"4758f1bcc27c21ae12739902","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4758f1bcc27c21ae12739902/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject2/h1/3/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"47927ef70d89cb194dbbfc85:0","filtered_window_id":"47927ef70d89cb194dbbfc85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47927ef70d89cb194dbbfc85/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject1/o1/3/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"47927ef70d89cb194dbbfc85:8","filtered_window_id":"47927ef70d89cb194dbbfc85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47927ef70d89cb194dbbfc85/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject1/o1/3/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"47927ef70d89cb194dbbfc85:16","filtered_window_id":"47927ef70d89cb194dbbfc85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47927ef70d89cb194dbbfc85/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject1/o1/3/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"47927ef70d89cb194dbbfc85:24","filtered_window_id":"47927ef70d89cb194dbbfc85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47927ef70d89cb194dbbfc85/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[255,256,257,258,259,260,261,262],"take":"subject1/o1/3/cam4","frame_ids":[255,256,257,258,259,260,261,262]} +{"filtered_tile_id":"47927ef70d89cb194dbbfc85:32","filtered_window_id":"47927ef70d89cb194dbbfc85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47927ef70d89cb194dbbfc85/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject1/o1/3/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"47927ef70d89cb194dbbfc85:40","filtered_window_id":"47927ef70d89cb194dbbfc85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47927ef70d89cb194dbbfc85/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[271,272,273,274,275,276,277,278],"take":"subject1/o1/3/cam4","frame_ids":[271,272,273,274,275,276,277,278]} +{"filtered_tile_id":"47927ef70d89cb194dbbfc85:48","filtered_window_id":"47927ef70d89cb194dbbfc85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47927ef70d89cb194dbbfc85/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[279,280,281,282,283,284,285,286],"take":"subject1/o1/3/cam4","frame_ids":[279,280,281,282,283,284,285,286]} +{"filtered_tile_id":"47927ef70d89cb194dbbfc85:52","filtered_window_id":"47927ef70d89cb194dbbfc85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47927ef70d89cb194dbbfc85/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[283,284,285,286,287,288,289,290],"take":"subject1/o1/3/cam4","frame_ids":[283,284,285,286,287,288,289,290]} +{"filtered_tile_id":"4794b8a5bc02f009518e7606:0","filtered_window_id":"4794b8a5bc02f009518e7606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4794b8a5bc02f009518e7606/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[210,211,212,213,214,215,216,217],"take":"subject2/k1/5/cam4","frame_ids":[210,211,212,213,214,215,216,217]} +{"filtered_tile_id":"4794b8a5bc02f009518e7606:8","filtered_window_id":"4794b8a5bc02f009518e7606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4794b8a5bc02f009518e7606/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[218,219,220,221,222,223,224,225],"take":"subject2/k1/5/cam4","frame_ids":[218,219,220,221,222,223,224,225]} +{"filtered_tile_id":"4794b8a5bc02f009518e7606:16","filtered_window_id":"4794b8a5bc02f009518e7606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4794b8a5bc02f009518e7606/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject2/k1/5/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"4794b8a5bc02f009518e7606:24","filtered_window_id":"4794b8a5bc02f009518e7606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4794b8a5bc02f009518e7606/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject2/k1/5/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"4794b8a5bc02f009518e7606:27","filtered_window_id":"4794b8a5bc02f009518e7606","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4794b8a5bc02f009518e7606/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject2/k1/5/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"47e18d883edd8f4c82f062ea:0","filtered_window_id":"47e18d883edd8f4c82f062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47e18d883edd8f4c82f062ea/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject2/o2/0/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"47e18d883edd8f4c82f062ea:8","filtered_window_id":"47e18d883edd8f4c82f062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47e18d883edd8f4c82f062ea/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject2/o2/0/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"47e18d883edd8f4c82f062ea:16","filtered_window_id":"47e18d883edd8f4c82f062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47e18d883edd8f4c82f062ea/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject2/o2/0/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"47e18d883edd8f4c82f062ea:24","filtered_window_id":"47e18d883edd8f4c82f062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47e18d883edd8f4c82f062ea/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject2/o2/0/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"47e18d883edd8f4c82f062ea:32","filtered_window_id":"47e18d883edd8f4c82f062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47e18d883edd8f4c82f062ea/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject2/o2/0/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"47e18d883edd8f4c82f062ea:40","filtered_window_id":"47e18d883edd8f4c82f062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47e18d883edd8f4c82f062ea/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject2/o2/0/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"47e18d883edd8f4c82f062ea:48","filtered_window_id":"47e18d883edd8f4c82f062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47e18d883edd8f4c82f062ea/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject2/o2/0/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"47e18d883edd8f4c82f062ea:52","filtered_window_id":"47e18d883edd8f4c82f062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/47e18d883edd8f4c82f062ea/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject2/o2/0/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"488649bee00bacadafd23a29:0","filtered_window_id":"488649bee00bacadafd23a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/488649bee00bacadafd23a29/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject2/k2/4/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"488649bee00bacadafd23a29:8","filtered_window_id":"488649bee00bacadafd23a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/488649bee00bacadafd23a29/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject2/k2/4/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"488649bee00bacadafd23a29:16","filtered_window_id":"488649bee00bacadafd23a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/488649bee00bacadafd23a29/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject2/k2/4/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"488649bee00bacadafd23a29:24","filtered_window_id":"488649bee00bacadafd23a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/488649bee00bacadafd23a29/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject2/k2/4/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"488649bee00bacadafd23a29:32","filtered_window_id":"488649bee00bacadafd23a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/488649bee00bacadafd23a29/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject2/k2/4/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"488649bee00bacadafd23a29:40","filtered_window_id":"488649bee00bacadafd23a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/488649bee00bacadafd23a29/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject2/k2/4/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"488649bee00bacadafd23a29:48","filtered_window_id":"488649bee00bacadafd23a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/488649bee00bacadafd23a29/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject2/k2/4/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"488649bee00bacadafd23a29:52","filtered_window_id":"488649bee00bacadafd23a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/488649bee00bacadafd23a29/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject2/k2/4/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"48a05c8d7a4174d7d5dc5631:0","filtered_window_id":"48a05c8d7a4174d7d5dc5631","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48a05c8d7a4174d7d5dc5631/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject3/h1/7/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"48a05c8d7a4174d7d5dc5631:8","filtered_window_id":"48a05c8d7a4174d7d5dc5631","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48a05c8d7a4174d7d5dc5631/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject3/h1/7/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"48a05c8d7a4174d7d5dc5631:16","filtered_window_id":"48a05c8d7a4174d7d5dc5631","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48a05c8d7a4174d7d5dc5631/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject3/h1/7/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"48a05c8d7a4174d7d5dc5631:24","filtered_window_id":"48a05c8d7a4174d7d5dc5631","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48a05c8d7a4174d7d5dc5631/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject3/h1/7/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"48eaf244061683387ef53200:0","filtered_window_id":"48eaf244061683387ef53200","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48eaf244061683387ef53200/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject2/k1/2/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"48eaf244061683387ef53200:8","filtered_window_id":"48eaf244061683387ef53200","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48eaf244061683387ef53200/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject2/k1/2/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"48eaf244061683387ef53200:16","filtered_window_id":"48eaf244061683387ef53200","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48eaf244061683387ef53200/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject2/k1/2/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"48eaf244061683387ef53200:24","filtered_window_id":"48eaf244061683387ef53200","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48eaf244061683387ef53200/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject2/k1/2/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"48eaf244061683387ef53200:32","filtered_window_id":"48eaf244061683387ef53200","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48eaf244061683387ef53200/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject2/k1/2/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"48eaf244061683387ef53200:40","filtered_window_id":"48eaf244061683387ef53200","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48eaf244061683387ef53200/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[341,342,343,344,345,346,347,348],"take":"subject2/k1/2/cam4","frame_ids":[341,342,343,344,345,346,347,348]} +{"filtered_tile_id":"48eaf244061683387ef53200:48","filtered_window_id":"48eaf244061683387ef53200","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48eaf244061683387ef53200/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[349,350,351,352,353,354,355,356],"take":"subject2/k1/2/cam4","frame_ids":[349,350,351,352,353,354,355,356]} +{"filtered_tile_id":"48eaf244061683387ef53200:52","filtered_window_id":"48eaf244061683387ef53200","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48eaf244061683387ef53200/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject2/k1/2/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"48fdd6deca6d48efd77df351:0","filtered_window_id":"48fdd6deca6d48efd77df351","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48fdd6deca6d48efd77df351/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[120,121,122,123,124,125,126,127],"take":"subject2/h2/1/cam4","frame_ids":[120,121,122,123,124,125,126,127]} +{"filtered_tile_id":"48fdd6deca6d48efd77df351:8","filtered_window_id":"48fdd6deca6d48efd77df351","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48fdd6deca6d48efd77df351/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[128,129,130,131,132,133,134,135],"take":"subject2/h2/1/cam4","frame_ids":[128,129,130,131,132,133,134,135]} +{"filtered_tile_id":"48fdd6deca6d48efd77df351:16","filtered_window_id":"48fdd6deca6d48efd77df351","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48fdd6deca6d48efd77df351/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[136,137,138,139,140,141,142,143],"take":"subject2/h2/1/cam4","frame_ids":[136,137,138,139,140,141,142,143]} +{"filtered_tile_id":"48fdd6deca6d48efd77df351:24","filtered_window_id":"48fdd6deca6d48efd77df351","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48fdd6deca6d48efd77df351/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[144,145,146,147,148,149,150,151],"take":"subject2/h2/1/cam4","frame_ids":[144,145,146,147,148,149,150,151]} +{"filtered_tile_id":"48fdd6deca6d48efd77df351:32","filtered_window_id":"48fdd6deca6d48efd77df351","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48fdd6deca6d48efd77df351/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject2/h2/1/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"48fdd6deca6d48efd77df351:40","filtered_window_id":"48fdd6deca6d48efd77df351","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48fdd6deca6d48efd77df351/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject2/h2/1/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"48fdd6deca6d48efd77df351:48","filtered_window_id":"48fdd6deca6d48efd77df351","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48fdd6deca6d48efd77df351/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject2/h2/1/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"48fdd6deca6d48efd77df351:52","filtered_window_id":"48fdd6deca6d48efd77df351","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/48fdd6deca6d48efd77df351/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject2/h2/1/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"490b9acdc656eb9887907590:0","filtered_window_id":"490b9acdc656eb9887907590","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/490b9acdc656eb9887907590/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject3/h1/5/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"490b9acdc656eb9887907590:8","filtered_window_id":"490b9acdc656eb9887907590","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/490b9acdc656eb9887907590/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[433,434,435,436,437,438,439,440],"take":"subject3/h1/5/cam4","frame_ids":[433,434,435,436,437,438,439,440]} +{"filtered_tile_id":"490b9acdc656eb9887907590:16","filtered_window_id":"490b9acdc656eb9887907590","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/490b9acdc656eb9887907590/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject3/h1/5/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"490b9acdc656eb9887907590:24","filtered_window_id":"490b9acdc656eb9887907590","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/490b9acdc656eb9887907590/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject3/h1/5/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"490b9acdc656eb9887907590:32","filtered_window_id":"490b9acdc656eb9887907590","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/490b9acdc656eb9887907590/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject3/h1/5/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"490b9acdc656eb9887907590:40","filtered_window_id":"490b9acdc656eb9887907590","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/490b9acdc656eb9887907590/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject3/h1/5/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"490b9acdc656eb9887907590:48","filtered_window_id":"490b9acdc656eb9887907590","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/490b9acdc656eb9887907590/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject3/h1/5/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"490b9acdc656eb9887907590:52","filtered_window_id":"490b9acdc656eb9887907590","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/490b9acdc656eb9887907590/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[477,478,479,480,481,482,483,484],"take":"subject3/h1/5/cam4","frame_ids":[477,478,479,480,481,482,483,484]} +{"filtered_tile_id":"4919a8bebe590a91084a11e9:0","filtered_window_id":"4919a8bebe590a91084a11e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4919a8bebe590a91084a11e9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[419,420,421,422,423,424,425,426],"take":"subject1/o1/2/cam4","frame_ids":[419,420,421,422,423,424,425,426]} +{"filtered_tile_id":"4919a8bebe590a91084a11e9:8","filtered_window_id":"4919a8bebe590a91084a11e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4919a8bebe590a91084a11e9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject1/o1/2/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"4919a8bebe590a91084a11e9:16","filtered_window_id":"4919a8bebe590a91084a11e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4919a8bebe590a91084a11e9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/o1/2/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"4919a8bebe590a91084a11e9:24","filtered_window_id":"4919a8bebe590a91084a11e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4919a8bebe590a91084a11e9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject1/o1/2/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"4919a8bebe590a91084a11e9:32","filtered_window_id":"4919a8bebe590a91084a11e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4919a8bebe590a91084a11e9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject1/o1/2/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"4919a8bebe590a91084a11e9:38","filtered_window_id":"4919a8bebe590a91084a11e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4919a8bebe590a91084a11e9/native_gt.npz","filtered_start_offset":38,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject1/o1/2/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"4975137e32041adadf1e08b6:0","filtered_window_id":"4975137e32041adadf1e08b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4975137e32041adadf1e08b6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[5,6,7,8,9,10,11,12],"take":"subject2/k1/3/cam4","frame_ids":[5,6,7,8,9,10,11,12]} +{"filtered_tile_id":"4975137e32041adadf1e08b6:8","filtered_window_id":"4975137e32041adadf1e08b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4975137e32041adadf1e08b6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[13,14,15,16,17,18,19,20],"take":"subject2/k1/3/cam4","frame_ids":[13,14,15,16,17,18,19,20]} +{"filtered_tile_id":"4975137e32041adadf1e08b6:16","filtered_window_id":"4975137e32041adadf1e08b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4975137e32041adadf1e08b6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[21,22,23,24,25,26,27,28],"take":"subject2/k1/3/cam4","frame_ids":[21,22,23,24,25,26,27,28]} +{"filtered_tile_id":"4975137e32041adadf1e08b6:24","filtered_window_id":"4975137e32041adadf1e08b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4975137e32041adadf1e08b6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[29,30,31,32,33,34,35,36],"take":"subject2/k1/3/cam4","frame_ids":[29,30,31,32,33,34,35,36]} +{"filtered_tile_id":"4975137e32041adadf1e08b6:32","filtered_window_id":"4975137e32041adadf1e08b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4975137e32041adadf1e08b6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject2/k1/3/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"4975137e32041adadf1e08b6:40","filtered_window_id":"4975137e32041adadf1e08b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4975137e32041adadf1e08b6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject2/k1/3/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"4975137e32041adadf1e08b6:48","filtered_window_id":"4975137e32041adadf1e08b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4975137e32041adadf1e08b6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[53,54,55,56,57,58,59,60],"take":"subject2/k1/3/cam4","frame_ids":[53,54,55,56,57,58,59,60]} +{"filtered_tile_id":"4975137e32041adadf1e08b6:52","filtered_window_id":"4975137e32041adadf1e08b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4975137e32041adadf1e08b6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[57,58,59,60,61,62,63,64],"take":"subject2/k1/3/cam4","frame_ids":[57,58,59,60,61,62,63,64]} +{"filtered_tile_id":"498f9e693fb2c79cfb47d55b:0","filtered_window_id":"498f9e693fb2c79cfb47d55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/498f9e693fb2c79cfb47d55b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject1/o1/1/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"498f9e693fb2c79cfb47d55b:8","filtered_window_id":"498f9e693fb2c79cfb47d55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/498f9e693fb2c79cfb47d55b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject1/o1/1/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"498f9e693fb2c79cfb47d55b:16","filtered_window_id":"498f9e693fb2c79cfb47d55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/498f9e693fb2c79cfb47d55b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject1/o1/1/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"498f9e693fb2c79cfb47d55b:24","filtered_window_id":"498f9e693fb2c79cfb47d55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/498f9e693fb2c79cfb47d55b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject1/o1/1/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"498f9e693fb2c79cfb47d55b:32","filtered_window_id":"498f9e693fb2c79cfb47d55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/498f9e693fb2c79cfb47d55b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[255,256,257,258,259,260,261,262],"take":"subject1/o1/1/cam4","frame_ids":[255,256,257,258,259,260,261,262]} +{"filtered_tile_id":"498f9e693fb2c79cfb47d55b:40","filtered_window_id":"498f9e693fb2c79cfb47d55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/498f9e693fb2c79cfb47d55b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject1/o1/1/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"498f9e693fb2c79cfb47d55b:48","filtered_window_id":"498f9e693fb2c79cfb47d55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/498f9e693fb2c79cfb47d55b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[271,272,273,274,275,276,277,278],"take":"subject1/o1/1/cam4","frame_ids":[271,272,273,274,275,276,277,278]} +{"filtered_tile_id":"498f9e693fb2c79cfb47d55b:52","filtered_window_id":"498f9e693fb2c79cfb47d55b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/498f9e693fb2c79cfb47d55b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[275,276,277,278,279,280,281,282],"take":"subject1/o1/1/cam4","frame_ids":[275,276,277,278,279,280,281,282]} +{"filtered_tile_id":"4a5ff36c4eecf8f331f33739:0","filtered_window_id":"4a5ff36c4eecf8f331f33739","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a5ff36c4eecf8f331f33739/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[532,533,534,535,536,537,538,539],"take":"subject2/k2/1/cam4","frame_ids":[532,533,534,535,536,537,538,539]} +{"filtered_tile_id":"4a5ff36c4eecf8f331f33739:8","filtered_window_id":"4a5ff36c4eecf8f331f33739","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a5ff36c4eecf8f331f33739/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[540,541,542,543,544,545,546,547],"take":"subject2/k2/1/cam4","frame_ids":[540,541,542,543,544,545,546,547]} +{"filtered_tile_id":"4a5ff36c4eecf8f331f33739:16","filtered_window_id":"4a5ff36c4eecf8f331f33739","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a5ff36c4eecf8f331f33739/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject2/k2/1/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"4a5ff36c4eecf8f331f33739:24","filtered_window_id":"4a5ff36c4eecf8f331f33739","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a5ff36c4eecf8f331f33739/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject2/k2/1/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"4a5ff36c4eecf8f331f33739:32","filtered_window_id":"4a5ff36c4eecf8f331f33739","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a5ff36c4eecf8f331f33739/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject2/k2/1/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"4a5ff36c4eecf8f331f33739:40","filtered_window_id":"4a5ff36c4eecf8f331f33739","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a5ff36c4eecf8f331f33739/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[572,573,574,575,576,577,578,579],"take":"subject2/k2/1/cam4","frame_ids":[572,573,574,575,576,577,578,579]} +{"filtered_tile_id":"4a5ff36c4eecf8f331f33739:48","filtered_window_id":"4a5ff36c4eecf8f331f33739","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a5ff36c4eecf8f331f33739/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[580,581,582,583,584,585,586,587],"take":"subject2/k2/1/cam4","frame_ids":[580,581,582,583,584,585,586,587]} +{"filtered_tile_id":"4a5ff36c4eecf8f331f33739:52","filtered_window_id":"4a5ff36c4eecf8f331f33739","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a5ff36c4eecf8f331f33739/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[584,585,586,587,588,589,590,591],"take":"subject2/k2/1/cam4","frame_ids":[584,585,586,587,588,589,590,591]} +{"filtered_tile_id":"4a8c91fa28e25c7a5dbe16ab:0","filtered_window_id":"4a8c91fa28e25c7a5dbe16ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a8c91fa28e25c7a5dbe16ab/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[717,718,719,720,721,722,723,724],"take":"subject3/k1/5/cam4","frame_ids":[717,718,719,720,721,722,723,724]} +{"filtered_tile_id":"4a8c91fa28e25c7a5dbe16ab:8","filtered_window_id":"4a8c91fa28e25c7a5dbe16ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a8c91fa28e25c7a5dbe16ab/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[725,726,727,728,729,730,731,732],"take":"subject3/k1/5/cam4","frame_ids":[725,726,727,728,729,730,731,732]} +{"filtered_tile_id":"4a8c91fa28e25c7a5dbe16ab:16","filtered_window_id":"4a8c91fa28e25c7a5dbe16ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a8c91fa28e25c7a5dbe16ab/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[733,734,735,736,737,738,739,740],"take":"subject3/k1/5/cam4","frame_ids":[733,734,735,736,737,738,739,740]} +{"filtered_tile_id":"4a8c91fa28e25c7a5dbe16ab:24","filtered_window_id":"4a8c91fa28e25c7a5dbe16ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a8c91fa28e25c7a5dbe16ab/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[741,742,743,744,745,746,747,748],"take":"subject3/k1/5/cam4","frame_ids":[741,742,743,744,745,746,747,748]} +{"filtered_tile_id":"4a8c91fa28e25c7a5dbe16ab:32","filtered_window_id":"4a8c91fa28e25c7a5dbe16ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a8c91fa28e25c7a5dbe16ab/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[749,750,751,752,753,754,755,756],"take":"subject3/k1/5/cam4","frame_ids":[749,750,751,752,753,754,755,756]} +{"filtered_tile_id":"4a8c91fa28e25c7a5dbe16ab:40","filtered_window_id":"4a8c91fa28e25c7a5dbe16ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a8c91fa28e25c7a5dbe16ab/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[757,758,759,760,761,762,763,764],"take":"subject3/k1/5/cam4","frame_ids":[757,758,759,760,761,762,763,764]} +{"filtered_tile_id":"4a8c91fa28e25c7a5dbe16ab:48","filtered_window_id":"4a8c91fa28e25c7a5dbe16ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a8c91fa28e25c7a5dbe16ab/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[765,766,767,768,769,770,771,772],"take":"subject3/k1/5/cam4","frame_ids":[765,766,767,768,769,770,771,772]} +{"filtered_tile_id":"4a8c91fa28e25c7a5dbe16ab:52","filtered_window_id":"4a8c91fa28e25c7a5dbe16ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4a8c91fa28e25c7a5dbe16ab/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[769,770,771,772,773,774,775,776],"take":"subject3/k1/5/cam4","frame_ids":[769,770,771,772,773,774,775,776]} +{"filtered_tile_id":"4ab2da265d1190f53cbd2e46:0","filtered_window_id":"4ab2da265d1190f53cbd2e46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ab2da265d1190f53cbd2e46/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject1/h2/7/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"4ab2da265d1190f53cbd2e46:8","filtered_window_id":"4ab2da265d1190f53cbd2e46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ab2da265d1190f53cbd2e46/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject1/h2/7/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"4ab2da265d1190f53cbd2e46:16","filtered_window_id":"4ab2da265d1190f53cbd2e46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ab2da265d1190f53cbd2e46/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject1/h2/7/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"4ab2da265d1190f53cbd2e46:24","filtered_window_id":"4ab2da265d1190f53cbd2e46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ab2da265d1190f53cbd2e46/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject1/h2/7/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"4ab2da265d1190f53cbd2e46:32","filtered_window_id":"4ab2da265d1190f53cbd2e46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ab2da265d1190f53cbd2e46/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject1/h2/7/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"4ab2da265d1190f53cbd2e46:40","filtered_window_id":"4ab2da265d1190f53cbd2e46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ab2da265d1190f53cbd2e46/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[526,527,528,529,530,531,532,533],"take":"subject1/h2/7/cam4","frame_ids":[526,527,528,529,530,531,532,533]} +{"filtered_tile_id":"4ab2da265d1190f53cbd2e46:48","filtered_window_id":"4ab2da265d1190f53cbd2e46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ab2da265d1190f53cbd2e46/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[534,535,536,537,538,539,540,541],"take":"subject1/h2/7/cam4","frame_ids":[534,535,536,537,538,539,540,541]} +{"filtered_tile_id":"4ab2da265d1190f53cbd2e46:52","filtered_window_id":"4ab2da265d1190f53cbd2e46","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ab2da265d1190f53cbd2e46/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[538,539,540,541,542,543,544,545],"take":"subject1/h2/7/cam4","frame_ids":[538,539,540,541,542,543,544,545]} +{"filtered_tile_id":"4ace6bafbc01b6cbe9aadb2d:0","filtered_window_id":"4ace6bafbc01b6cbe9aadb2d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ace6bafbc01b6cbe9aadb2d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[606,607,608,609,610,611,612,613],"take":"subject1/h2/7/cam4","frame_ids":[606,607,608,609,610,611,612,613]} +{"filtered_tile_id":"4ace6bafbc01b6cbe9aadb2d:8","filtered_window_id":"4ace6bafbc01b6cbe9aadb2d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ace6bafbc01b6cbe9aadb2d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[614,615,616,617,618,619,620,621],"take":"subject1/h2/7/cam4","frame_ids":[614,615,616,617,618,619,620,621]} +{"filtered_tile_id":"4ace6bafbc01b6cbe9aadb2d:16","filtered_window_id":"4ace6bafbc01b6cbe9aadb2d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ace6bafbc01b6cbe9aadb2d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[622,623,624,625,626,627,628,629],"take":"subject1/h2/7/cam4","frame_ids":[622,623,624,625,626,627,628,629]} +{"filtered_tile_id":"4ace6bafbc01b6cbe9aadb2d:24","filtered_window_id":"4ace6bafbc01b6cbe9aadb2d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ace6bafbc01b6cbe9aadb2d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[630,631,632,633,634,635,636,637],"take":"subject1/h2/7/cam4","frame_ids":[630,631,632,633,634,635,636,637]} +{"filtered_tile_id":"4ace6bafbc01b6cbe9aadb2d:32","filtered_window_id":"4ace6bafbc01b6cbe9aadb2d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ace6bafbc01b6cbe9aadb2d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[638,639,640,641,642,643,644,645],"take":"subject1/h2/7/cam4","frame_ids":[638,639,640,641,642,643,644,645]} +{"filtered_tile_id":"4ace6bafbc01b6cbe9aadb2d:40","filtered_window_id":"4ace6bafbc01b6cbe9aadb2d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ace6bafbc01b6cbe9aadb2d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[646,647,648,649,650,651,652,653],"take":"subject1/h2/7/cam4","frame_ids":[646,647,648,649,650,651,652,653]} +{"filtered_tile_id":"4ace6bafbc01b6cbe9aadb2d:48","filtered_window_id":"4ace6bafbc01b6cbe9aadb2d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ace6bafbc01b6cbe9aadb2d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[654,655,656,657,658,659,660,661],"take":"subject1/h2/7/cam4","frame_ids":[654,655,656,657,658,659,660,661]} +{"filtered_tile_id":"4ace6bafbc01b6cbe9aadb2d:52","filtered_window_id":"4ace6bafbc01b6cbe9aadb2d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ace6bafbc01b6cbe9aadb2d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[658,659,660,661,662,663,664,665],"take":"subject1/h2/7/cam4","frame_ids":[658,659,660,661,662,663,664,665]} +{"filtered_tile_id":"4b532dbc0dd5c7febbfbbe0c:0","filtered_window_id":"4b532dbc0dd5c7febbfbbe0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4b532dbc0dd5c7febbfbbe0c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[659,660,661,662,663,664,665,666],"take":"subject2/h2/3/cam4","frame_ids":[659,660,661,662,663,664,665,666]} +{"filtered_tile_id":"4b532dbc0dd5c7febbfbbe0c:8","filtered_window_id":"4b532dbc0dd5c7febbfbbe0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4b532dbc0dd5c7febbfbbe0c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[667,668,669,670,671,672,673,674],"take":"subject2/h2/3/cam4","frame_ids":[667,668,669,670,671,672,673,674]} +{"filtered_tile_id":"4b532dbc0dd5c7febbfbbe0c:16","filtered_window_id":"4b532dbc0dd5c7febbfbbe0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4b532dbc0dd5c7febbfbbe0c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[675,676,677,678,679,680,681,682],"take":"subject2/h2/3/cam4","frame_ids":[675,676,677,678,679,680,681,682]} +{"filtered_tile_id":"4b532dbc0dd5c7febbfbbe0c:24","filtered_window_id":"4b532dbc0dd5c7febbfbbe0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4b532dbc0dd5c7febbfbbe0c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[683,684,685,686,687,688,689,690],"take":"subject2/h2/3/cam4","frame_ids":[683,684,685,686,687,688,689,690]} +{"filtered_tile_id":"4b532dbc0dd5c7febbfbbe0c:32","filtered_window_id":"4b532dbc0dd5c7febbfbbe0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4b532dbc0dd5c7febbfbbe0c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[691,692,693,694,695,696,697,698],"take":"subject2/h2/3/cam4","frame_ids":[691,692,693,694,695,696,697,698]} +{"filtered_tile_id":"4b532dbc0dd5c7febbfbbe0c:40","filtered_window_id":"4b532dbc0dd5c7febbfbbe0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4b532dbc0dd5c7febbfbbe0c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[699,700,701,702,703,704,705,706],"take":"subject2/h2/3/cam4","frame_ids":[699,700,701,702,703,704,705,706]} +{"filtered_tile_id":"4b532dbc0dd5c7febbfbbe0c:48","filtered_window_id":"4b532dbc0dd5c7febbfbbe0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4b532dbc0dd5c7febbfbbe0c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[707,708,709,710,711,712,713,714],"take":"subject2/h2/3/cam4","frame_ids":[707,708,709,710,711,712,713,714]} +{"filtered_tile_id":"4b532dbc0dd5c7febbfbbe0c:52","filtered_window_id":"4b532dbc0dd5c7febbfbbe0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4b532dbc0dd5c7febbfbbe0c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[711,712,713,714,715,716,717,718],"take":"subject2/h2/3/cam4","frame_ids":[711,712,713,714,715,716,717,718]} +{"filtered_tile_id":"4baee1bfb04c557293898c2c:0","filtered_window_id":"4baee1bfb04c557293898c2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4baee1bfb04c557293898c2c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[105,106,107,108,109,110,111,112],"take":"subject3/h2/1/cam4","frame_ids":[105,106,107,108,109,110,111,112]} +{"filtered_tile_id":"4baee1bfb04c557293898c2c:8","filtered_window_id":"4baee1bfb04c557293898c2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4baee1bfb04c557293898c2c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[113,114,115,116,117,118,119,120],"take":"subject3/h2/1/cam4","frame_ids":[113,114,115,116,117,118,119,120]} +{"filtered_tile_id":"4baee1bfb04c557293898c2c:16","filtered_window_id":"4baee1bfb04c557293898c2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4baee1bfb04c557293898c2c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[121,122,123,124,125,126,127,128],"take":"subject3/h2/1/cam4","frame_ids":[121,122,123,124,125,126,127,128]} +{"filtered_tile_id":"4baee1bfb04c557293898c2c:24","filtered_window_id":"4baee1bfb04c557293898c2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4baee1bfb04c557293898c2c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject3/h2/1/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"4baee1bfb04c557293898c2c:32","filtered_window_id":"4baee1bfb04c557293898c2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4baee1bfb04c557293898c2c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject3/h2/1/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"4baee1bfb04c557293898c2c:40","filtered_window_id":"4baee1bfb04c557293898c2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4baee1bfb04c557293898c2c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject3/h2/1/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"4baee1bfb04c557293898c2c:48","filtered_window_id":"4baee1bfb04c557293898c2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4baee1bfb04c557293898c2c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject3/h2/1/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"4baee1bfb04c557293898c2c:52","filtered_window_id":"4baee1bfb04c557293898c2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4baee1bfb04c557293898c2c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject3/h2/1/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"4be054112e69ccad87fa616c:0","filtered_window_id":"4be054112e69ccad87fa616c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4be054112e69ccad87fa616c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[82,83,84,85,86,87,88,89],"take":"subject2/k1/1/cam4","frame_ids":[82,83,84,85,86,87,88,89]} +{"filtered_tile_id":"4be054112e69ccad87fa616c:8","filtered_window_id":"4be054112e69ccad87fa616c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4be054112e69ccad87fa616c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject2/k1/1/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"4be054112e69ccad87fa616c:16","filtered_window_id":"4be054112e69ccad87fa616c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4be054112e69ccad87fa616c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[98,99,100,101,102,103,104,105],"take":"subject2/k1/1/cam4","frame_ids":[98,99,100,101,102,103,104,105]} +{"filtered_tile_id":"4be054112e69ccad87fa616c:24","filtered_window_id":"4be054112e69ccad87fa616c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4be054112e69ccad87fa616c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[106,107,108,109,110,111,112,113],"take":"subject2/k1/1/cam4","frame_ids":[106,107,108,109,110,111,112,113]} +{"filtered_tile_id":"4be054112e69ccad87fa616c:32","filtered_window_id":"4be054112e69ccad87fa616c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4be054112e69ccad87fa616c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject2/k1/1/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"4be054112e69ccad87fa616c:40","filtered_window_id":"4be054112e69ccad87fa616c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4be054112e69ccad87fa616c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject2/k1/1/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"4be054112e69ccad87fa616c:48","filtered_window_id":"4be054112e69ccad87fa616c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4be054112e69ccad87fa616c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject2/k1/1/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"4be054112e69ccad87fa616c:52","filtered_window_id":"4be054112e69ccad87fa616c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4be054112e69ccad87fa616c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[134,135,136,137,138,139,140,141],"take":"subject2/k1/1/cam4","frame_ids":[134,135,136,137,138,139,140,141]} +{"filtered_tile_id":"4c6e4af41f949e83881fa3b6:0","filtered_window_id":"4c6e4af41f949e83881fa3b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4c6e4af41f949e83881fa3b6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[609,610,611,612,613,614,615,616],"take":"subject1/k1/7/cam4","frame_ids":[609,610,611,612,613,614,615,616]} +{"filtered_tile_id":"4c6e4af41f949e83881fa3b6:8","filtered_window_id":"4c6e4af41f949e83881fa3b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4c6e4af41f949e83881fa3b6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[617,618,619,620,621,622,623,624],"take":"subject1/k1/7/cam4","frame_ids":[617,618,619,620,621,622,623,624]} +{"filtered_tile_id":"4c6e4af41f949e83881fa3b6:16","filtered_window_id":"4c6e4af41f949e83881fa3b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4c6e4af41f949e83881fa3b6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[625,626,627,628,629,630,631,632],"take":"subject1/k1/7/cam4","frame_ids":[625,626,627,628,629,630,631,632]} +{"filtered_tile_id":"4c6e4af41f949e83881fa3b6:19","filtered_window_id":"4c6e4af41f949e83881fa3b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4c6e4af41f949e83881fa3b6/native_gt.npz","filtered_start_offset":19,"expected_frame_ids":[628,629,630,631,632,633,634,635],"take":"subject1/k1/7/cam4","frame_ids":[628,629,630,631,632,633,634,635]} +{"filtered_tile_id":"4cc9429a514b4095e24afaba:0","filtered_window_id":"4cc9429a514b4095e24afaba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4cc9429a514b4095e24afaba/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject2/o2/0/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"4cc9429a514b4095e24afaba:8","filtered_window_id":"4cc9429a514b4095e24afaba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4cc9429a514b4095e24afaba/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject2/o2/0/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"4cc9429a514b4095e24afaba:16","filtered_window_id":"4cc9429a514b4095e24afaba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4cc9429a514b4095e24afaba/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject2/o2/0/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"4cc9429a514b4095e24afaba:24","filtered_window_id":"4cc9429a514b4095e24afaba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4cc9429a514b4095e24afaba/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject2/o2/0/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"4cc9429a514b4095e24afaba:32","filtered_window_id":"4cc9429a514b4095e24afaba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4cc9429a514b4095e24afaba/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject2/o2/0/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"4cc9429a514b4095e24afaba:40","filtered_window_id":"4cc9429a514b4095e24afaba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4cc9429a514b4095e24afaba/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject2/o2/0/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"4cc9429a514b4095e24afaba:48","filtered_window_id":"4cc9429a514b4095e24afaba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4cc9429a514b4095e24afaba/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject2/o2/0/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"4cc9429a514b4095e24afaba:52","filtered_window_id":"4cc9429a514b4095e24afaba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4cc9429a514b4095e24afaba/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject2/o2/0/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"4ce8e8df2f6a85b91b56debd:0","filtered_window_id":"4ce8e8df2f6a85b91b56debd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ce8e8df2f6a85b91b56debd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/k2/5/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"4ce8e8df2f6a85b91b56debd:8","filtered_window_id":"4ce8e8df2f6a85b91b56debd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ce8e8df2f6a85b91b56debd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/k2/5/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"4ce8e8df2f6a85b91b56debd:16","filtered_window_id":"4ce8e8df2f6a85b91b56debd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ce8e8df2f6a85b91b56debd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k2/5/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"4ce8e8df2f6a85b91b56debd:24","filtered_window_id":"4ce8e8df2f6a85b91b56debd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ce8e8df2f6a85b91b56debd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k2/5/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"4ce8e8df2f6a85b91b56debd:32","filtered_window_id":"4ce8e8df2f6a85b91b56debd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ce8e8df2f6a85b91b56debd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k2/5/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"4ce8e8df2f6a85b91b56debd:40","filtered_window_id":"4ce8e8df2f6a85b91b56debd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ce8e8df2f6a85b91b56debd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/k2/5/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"4ce8e8df2f6a85b91b56debd:48","filtered_window_id":"4ce8e8df2f6a85b91b56debd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ce8e8df2f6a85b91b56debd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/k2/5/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"4ce8e8df2f6a85b91b56debd:52","filtered_window_id":"4ce8e8df2f6a85b91b56debd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ce8e8df2f6a85b91b56debd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/k2/5/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"4d03335d48ae750cc2d0cd5c:0","filtered_window_id":"4d03335d48ae750cc2d0cd5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d03335d48ae750cc2d0cd5c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject3/h2/6/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"4d03335d48ae750cc2d0cd5c:8","filtered_window_id":"4d03335d48ae750cc2d0cd5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d03335d48ae750cc2d0cd5c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject3/h2/6/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"4d03335d48ae750cc2d0cd5c:16","filtered_window_id":"4d03335d48ae750cc2d0cd5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d03335d48ae750cc2d0cd5c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject3/h2/6/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"4d03335d48ae750cc2d0cd5c:24","filtered_window_id":"4d03335d48ae750cc2d0cd5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d03335d48ae750cc2d0cd5c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject3/h2/6/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"4d03335d48ae750cc2d0cd5c:32","filtered_window_id":"4d03335d48ae750cc2d0cd5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d03335d48ae750cc2d0cd5c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject3/h2/6/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"4d03335d48ae750cc2d0cd5c:40","filtered_window_id":"4d03335d48ae750cc2d0cd5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d03335d48ae750cc2d0cd5c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject3/h2/6/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"4d03335d48ae750cc2d0cd5c:48","filtered_window_id":"4d03335d48ae750cc2d0cd5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d03335d48ae750cc2d0cd5c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject3/h2/6/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"4d03335d48ae750cc2d0cd5c:52","filtered_window_id":"4d03335d48ae750cc2d0cd5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d03335d48ae750cc2d0cd5c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject3/h2/6/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"4d200c296a6177a0ffff6652:0","filtered_window_id":"4d200c296a6177a0ffff6652","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d200c296a6177a0ffff6652/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject3/h1/4/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"4d200c296a6177a0ffff6652:8","filtered_window_id":"4d200c296a6177a0ffff6652","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d200c296a6177a0ffff6652/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject3/h1/4/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"4d200c296a6177a0ffff6652:16","filtered_window_id":"4d200c296a6177a0ffff6652","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d200c296a6177a0ffff6652/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[373,374,375,376,377,378,379,380],"take":"subject3/h1/4/cam4","frame_ids":[373,374,375,376,377,378,379,380]} +{"filtered_tile_id":"4d200c296a6177a0ffff6652:24","filtered_window_id":"4d200c296a6177a0ffff6652","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d200c296a6177a0ffff6652/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[381,382,383,384,385,386,387,388],"take":"subject3/h1/4/cam4","frame_ids":[381,382,383,384,385,386,387,388]} +{"filtered_tile_id":"4d200c296a6177a0ffff6652:32","filtered_window_id":"4d200c296a6177a0ffff6652","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d200c296a6177a0ffff6652/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[389,390,391,392,393,394,395,396],"take":"subject3/h1/4/cam4","frame_ids":[389,390,391,392,393,394,395,396]} +{"filtered_tile_id":"4d200c296a6177a0ffff6652:40","filtered_window_id":"4d200c296a6177a0ffff6652","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d200c296a6177a0ffff6652/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[397,398,399,400,401,402,403,404],"take":"subject3/h1/4/cam4","frame_ids":[397,398,399,400,401,402,403,404]} +{"filtered_tile_id":"4d200c296a6177a0ffff6652:48","filtered_window_id":"4d200c296a6177a0ffff6652","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d200c296a6177a0ffff6652/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[405,406,407,408,409,410,411,412],"take":"subject3/h1/4/cam4","frame_ids":[405,406,407,408,409,410,411,412]} +{"filtered_tile_id":"4d200c296a6177a0ffff6652:52","filtered_window_id":"4d200c296a6177a0ffff6652","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4d200c296a6177a0ffff6652/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[409,410,411,412,413,414,415,416],"take":"subject3/h1/4/cam4","frame_ids":[409,410,411,412,413,414,415,416]} +{"filtered_tile_id":"4e7adb4a987c05d9a5b0e75f:0","filtered_window_id":"4e7adb4a987c05d9a5b0e75f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e7adb4a987c05d9a5b0e75f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject3/h1/0/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"4e7adb4a987c05d9a5b0e75f:8","filtered_window_id":"4e7adb4a987c05d9a5b0e75f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e7adb4a987c05d9a5b0e75f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject3/h1/0/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"4e7adb4a987c05d9a5b0e75f:16","filtered_window_id":"4e7adb4a987c05d9a5b0e75f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e7adb4a987c05d9a5b0e75f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject3/h1/0/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"4e7adb4a987c05d9a5b0e75f:24","filtered_window_id":"4e7adb4a987c05d9a5b0e75f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e7adb4a987c05d9a5b0e75f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject3/h1/0/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"4e7adb4a987c05d9a5b0e75f:32","filtered_window_id":"4e7adb4a987c05d9a5b0e75f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e7adb4a987c05d9a5b0e75f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject3/h1/0/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"4e7adb4a987c05d9a5b0e75f:40","filtered_window_id":"4e7adb4a987c05d9a5b0e75f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e7adb4a987c05d9a5b0e75f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject3/h1/0/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"4e7adb4a987c05d9a5b0e75f:48","filtered_window_id":"4e7adb4a987c05d9a5b0e75f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e7adb4a987c05d9a5b0e75f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject3/h1/0/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"4e7adb4a987c05d9a5b0e75f:52","filtered_window_id":"4e7adb4a987c05d9a5b0e75f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e7adb4a987c05d9a5b0e75f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[218,219,220,221,222,223,224,225],"take":"subject3/h1/0/cam4","frame_ids":[218,219,220,221,222,223,224,225]} +{"filtered_tile_id":"4e88f98d4c8cecc1d1ba4725:0","filtered_window_id":"4e88f98d4c8cecc1d1ba4725","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e88f98d4c8cecc1d1ba4725/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[375,376,377,378,379,380,381,382],"take":"subject1/h1/3/cam4","frame_ids":[375,376,377,378,379,380,381,382]} +{"filtered_tile_id":"4e88f98d4c8cecc1d1ba4725:8","filtered_window_id":"4e88f98d4c8cecc1d1ba4725","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e88f98d4c8cecc1d1ba4725/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject1/h1/3/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"4e88f98d4c8cecc1d1ba4725:16","filtered_window_id":"4e88f98d4c8cecc1d1ba4725","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e88f98d4c8cecc1d1ba4725/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject1/h1/3/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"4e88f98d4c8cecc1d1ba4725:24","filtered_window_id":"4e88f98d4c8cecc1d1ba4725","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e88f98d4c8cecc1d1ba4725/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject1/h1/3/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"4e88f98d4c8cecc1d1ba4725:32","filtered_window_id":"4e88f98d4c8cecc1d1ba4725","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e88f98d4c8cecc1d1ba4725/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject1/h1/3/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"4e88f98d4c8cecc1d1ba4725:40","filtered_window_id":"4e88f98d4c8cecc1d1ba4725","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e88f98d4c8cecc1d1ba4725/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject1/h1/3/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"4e88f98d4c8cecc1d1ba4725:48","filtered_window_id":"4e88f98d4c8cecc1d1ba4725","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e88f98d4c8cecc1d1ba4725/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[423,424,425,426,427,428,429,430],"take":"subject1/h1/3/cam4","frame_ids":[423,424,425,426,427,428,429,430]} +{"filtered_tile_id":"4e88f98d4c8cecc1d1ba4725:52","filtered_window_id":"4e88f98d4c8cecc1d1ba4725","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4e88f98d4c8cecc1d1ba4725/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject1/h1/3/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"4ea03f6582e95f4a3bb21674:0","filtered_window_id":"4ea03f6582e95f4a3bb21674","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ea03f6582e95f4a3bb21674/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject2/h2/2/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"4ea03f6582e95f4a3bb21674:8","filtered_window_id":"4ea03f6582e95f4a3bb21674","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ea03f6582e95f4a3bb21674/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject2/h2/2/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"4ea03f6582e95f4a3bb21674:16","filtered_window_id":"4ea03f6582e95f4a3bb21674","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ea03f6582e95f4a3bb21674/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[354,355,356,357,358,359,360,361],"take":"subject2/h2/2/cam4","frame_ids":[354,355,356,357,358,359,360,361]} +{"filtered_tile_id":"4ea03f6582e95f4a3bb21674:24","filtered_window_id":"4ea03f6582e95f4a3bb21674","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ea03f6582e95f4a3bb21674/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject2/h2/2/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"4ea03f6582e95f4a3bb21674:32","filtered_window_id":"4ea03f6582e95f4a3bb21674","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ea03f6582e95f4a3bb21674/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject2/h2/2/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"4ea03f6582e95f4a3bb21674:40","filtered_window_id":"4ea03f6582e95f4a3bb21674","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ea03f6582e95f4a3bb21674/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject2/h2/2/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"4ea03f6582e95f4a3bb21674:48","filtered_window_id":"4ea03f6582e95f4a3bb21674","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ea03f6582e95f4a3bb21674/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[386,387,388,389,390,391,392,393],"take":"subject2/h2/2/cam4","frame_ids":[386,387,388,389,390,391,392,393]} +{"filtered_tile_id":"4ea03f6582e95f4a3bb21674:52","filtered_window_id":"4ea03f6582e95f4a3bb21674","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4ea03f6582e95f4a3bb21674/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject2/h2/2/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"4fb69ea57fba75f760e7bd9e:0","filtered_window_id":"4fb69ea57fba75f760e7bd9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fb69ea57fba75f760e7bd9e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject3/k1/4/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"4fb69ea57fba75f760e7bd9e:8","filtered_window_id":"4fb69ea57fba75f760e7bd9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fb69ea57fba75f760e7bd9e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject3/k1/4/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"4fb69ea57fba75f760e7bd9e:16","filtered_window_id":"4fb69ea57fba75f760e7bd9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fb69ea57fba75f760e7bd9e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[466,467,468,469,470,471,472,473],"take":"subject3/k1/4/cam4","frame_ids":[466,467,468,469,470,471,472,473]} +{"filtered_tile_id":"4fb69ea57fba75f760e7bd9e:24","filtered_window_id":"4fb69ea57fba75f760e7bd9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fb69ea57fba75f760e7bd9e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[474,475,476,477,478,479,480,481],"take":"subject3/k1/4/cam4","frame_ids":[474,475,476,477,478,479,480,481]} +{"filtered_tile_id":"4fb69ea57fba75f760e7bd9e:32","filtered_window_id":"4fb69ea57fba75f760e7bd9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fb69ea57fba75f760e7bd9e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[482,483,484,485,486,487,488,489],"take":"subject3/k1/4/cam4","frame_ids":[482,483,484,485,486,487,488,489]} +{"filtered_tile_id":"4fb69ea57fba75f760e7bd9e:40","filtered_window_id":"4fb69ea57fba75f760e7bd9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fb69ea57fba75f760e7bd9e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[490,491,492,493,494,495,496,497],"take":"subject3/k1/4/cam4","frame_ids":[490,491,492,493,494,495,496,497]} +{"filtered_tile_id":"4fb69ea57fba75f760e7bd9e:48","filtered_window_id":"4fb69ea57fba75f760e7bd9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fb69ea57fba75f760e7bd9e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[498,499,500,501,502,503,504,505],"take":"subject3/k1/4/cam4","frame_ids":[498,499,500,501,502,503,504,505]} +{"filtered_tile_id":"4fb69ea57fba75f760e7bd9e:52","filtered_window_id":"4fb69ea57fba75f760e7bd9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fb69ea57fba75f760e7bd9e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject3/k1/4/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"4fc7906458a13fed53f45fca:0","filtered_window_id":"4fc7906458a13fed53f45fca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fc7906458a13fed53f45fca/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[276,277,278,279,280,281,282,283],"take":"subject3/h2/3/cam4","frame_ids":[276,277,278,279,280,281,282,283]} +{"filtered_tile_id":"4fc7906458a13fed53f45fca:8","filtered_window_id":"4fc7906458a13fed53f45fca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fc7906458a13fed53f45fca/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[284,285,286,287,288,289,290,291],"take":"subject3/h2/3/cam4","frame_ids":[284,285,286,287,288,289,290,291]} +{"filtered_tile_id":"4fc7906458a13fed53f45fca:16","filtered_window_id":"4fc7906458a13fed53f45fca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fc7906458a13fed53f45fca/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[292,293,294,295,296,297,298,299],"take":"subject3/h2/3/cam4","frame_ids":[292,293,294,295,296,297,298,299]} +{"filtered_tile_id":"4fc7906458a13fed53f45fca:24","filtered_window_id":"4fc7906458a13fed53f45fca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fc7906458a13fed53f45fca/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[300,301,302,303,304,305,306,307],"take":"subject3/h2/3/cam4","frame_ids":[300,301,302,303,304,305,306,307]} +{"filtered_tile_id":"4fc7906458a13fed53f45fca:32","filtered_window_id":"4fc7906458a13fed53f45fca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fc7906458a13fed53f45fca/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject3/h2/3/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"4fc7906458a13fed53f45fca:40","filtered_window_id":"4fc7906458a13fed53f45fca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fc7906458a13fed53f45fca/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[316,317,318,319,320,321,322,323],"take":"subject3/h2/3/cam4","frame_ids":[316,317,318,319,320,321,322,323]} +{"filtered_tile_id":"4fc7906458a13fed53f45fca:48","filtered_window_id":"4fc7906458a13fed53f45fca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fc7906458a13fed53f45fca/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject3/h2/3/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"4fc7906458a13fed53f45fca:52","filtered_window_id":"4fc7906458a13fed53f45fca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/4fc7906458a13fed53f45fca/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[328,329,330,331,332,333,334,335],"take":"subject3/h2/3/cam4","frame_ids":[328,329,330,331,332,333,334,335]} +{"filtered_tile_id":"50a6134c8414b1f561cfbdc7:0","filtered_window_id":"50a6134c8414b1f561cfbdc7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50a6134c8414b1f561cfbdc7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[553,554,555,556,557,558,559,560],"take":"subject3/h2/1/cam4","frame_ids":[553,554,555,556,557,558,559,560]} +{"filtered_tile_id":"50a6134c8414b1f561cfbdc7:8","filtered_window_id":"50a6134c8414b1f561cfbdc7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50a6134c8414b1f561cfbdc7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[561,562,563,564,565,566,567,568],"take":"subject3/h2/1/cam4","frame_ids":[561,562,563,564,565,566,567,568]} +{"filtered_tile_id":"50a6134c8414b1f561cfbdc7:16","filtered_window_id":"50a6134c8414b1f561cfbdc7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50a6134c8414b1f561cfbdc7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[569,570,571,572,573,574,575,576],"take":"subject3/h2/1/cam4","frame_ids":[569,570,571,572,573,574,575,576]} +{"filtered_tile_id":"50a6134c8414b1f561cfbdc7:24","filtered_window_id":"50a6134c8414b1f561cfbdc7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50a6134c8414b1f561cfbdc7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[577,578,579,580,581,582,583,584],"take":"subject3/h2/1/cam4","frame_ids":[577,578,579,580,581,582,583,584]} +{"filtered_tile_id":"50a6134c8414b1f561cfbdc7:32","filtered_window_id":"50a6134c8414b1f561cfbdc7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50a6134c8414b1f561cfbdc7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[585,586,587,588,589,590,591,592],"take":"subject3/h2/1/cam4","frame_ids":[585,586,587,588,589,590,591,592]} +{"filtered_tile_id":"50a6134c8414b1f561cfbdc7:40","filtered_window_id":"50a6134c8414b1f561cfbdc7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50a6134c8414b1f561cfbdc7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[593,594,595,596,597,598,599,600],"take":"subject3/h2/1/cam4","frame_ids":[593,594,595,596,597,598,599,600]} +{"filtered_tile_id":"50a6134c8414b1f561cfbdc7:48","filtered_window_id":"50a6134c8414b1f561cfbdc7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50a6134c8414b1f561cfbdc7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[601,602,603,604,605,606,607,608],"take":"subject3/h2/1/cam4","frame_ids":[601,602,603,604,605,606,607,608]} +{"filtered_tile_id":"50a6134c8414b1f561cfbdc7:52","filtered_window_id":"50a6134c8414b1f561cfbdc7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50a6134c8414b1f561cfbdc7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[605,606,607,608,609,610,611,612],"take":"subject3/h2/1/cam4","frame_ids":[605,606,607,608,609,610,611,612]} +{"filtered_tile_id":"50f8d0ad95c60830a86c8154:0","filtered_window_id":"50f8d0ad95c60830a86c8154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50f8d0ad95c60830a86c8154/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[537,538,539,540,541,542,543,544],"take":"subject3/k1/5/cam4","frame_ids":[537,538,539,540,541,542,543,544]} +{"filtered_tile_id":"50f8d0ad95c60830a86c8154:8","filtered_window_id":"50f8d0ad95c60830a86c8154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50f8d0ad95c60830a86c8154/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[545,546,547,548,549,550,551,552],"take":"subject3/k1/5/cam4","frame_ids":[545,546,547,548,549,550,551,552]} +{"filtered_tile_id":"50f8d0ad95c60830a86c8154:16","filtered_window_id":"50f8d0ad95c60830a86c8154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50f8d0ad95c60830a86c8154/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[553,554,555,556,557,558,559,560],"take":"subject3/k1/5/cam4","frame_ids":[553,554,555,556,557,558,559,560]} +{"filtered_tile_id":"50f8d0ad95c60830a86c8154:24","filtered_window_id":"50f8d0ad95c60830a86c8154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50f8d0ad95c60830a86c8154/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[561,562,563,564,565,566,567,568],"take":"subject3/k1/5/cam4","frame_ids":[561,562,563,564,565,566,567,568]} +{"filtered_tile_id":"50f8d0ad95c60830a86c8154:32","filtered_window_id":"50f8d0ad95c60830a86c8154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50f8d0ad95c60830a86c8154/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[569,570,571,572,573,574,575,576],"take":"subject3/k1/5/cam4","frame_ids":[569,570,571,572,573,574,575,576]} +{"filtered_tile_id":"50f8d0ad95c60830a86c8154:40","filtered_window_id":"50f8d0ad95c60830a86c8154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50f8d0ad95c60830a86c8154/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[577,578,579,580,581,582,583,584],"take":"subject3/k1/5/cam4","frame_ids":[577,578,579,580,581,582,583,584]} +{"filtered_tile_id":"50f8d0ad95c60830a86c8154:42","filtered_window_id":"50f8d0ad95c60830a86c8154","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/50f8d0ad95c60830a86c8154/native_gt.npz","filtered_start_offset":42,"expected_frame_ids":[579,580,581,582,583,584,585,586],"take":"subject3/k1/5/cam4","frame_ids":[579,580,581,582,583,584,585,586]} +{"filtered_tile_id":"511e49bcaa07c78d75759f27:0","filtered_window_id":"511e49bcaa07c78d75759f27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/511e49bcaa07c78d75759f27/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject3/k1/2/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"511e49bcaa07c78d75759f27:8","filtered_window_id":"511e49bcaa07c78d75759f27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/511e49bcaa07c78d75759f27/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject3/k1/2/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"511e49bcaa07c78d75759f27:16","filtered_window_id":"511e49bcaa07c78d75759f27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/511e49bcaa07c78d75759f27/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject3/k1/2/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"511e49bcaa07c78d75759f27:24","filtered_window_id":"511e49bcaa07c78d75759f27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/511e49bcaa07c78d75759f27/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject3/k1/2/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"511e49bcaa07c78d75759f27:29","filtered_window_id":"511e49bcaa07c78d75759f27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/511e49bcaa07c78d75759f27/native_gt.npz","filtered_start_offset":29,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject3/k1/2/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"51adccc98c7a30d67dda67dd:0","filtered_window_id":"51adccc98c7a30d67dda67dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51adccc98c7a30d67dda67dd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[216,217,218,219,220,221,222,223],"take":"subject1/h1/3/cam4","frame_ids":[216,217,218,219,220,221,222,223]} +{"filtered_tile_id":"51adccc98c7a30d67dda67dd:8","filtered_window_id":"51adccc98c7a30d67dda67dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51adccc98c7a30d67dda67dd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[224,225,226,227,228,229,230,231],"take":"subject1/h1/3/cam4","frame_ids":[224,225,226,227,228,229,230,231]} +{"filtered_tile_id":"51adccc98c7a30d67dda67dd:16","filtered_window_id":"51adccc98c7a30d67dda67dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51adccc98c7a30d67dda67dd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[232,233,234,235,236,237,238,239],"take":"subject1/h1/3/cam4","frame_ids":[232,233,234,235,236,237,238,239]} +{"filtered_tile_id":"51adccc98c7a30d67dda67dd:18","filtered_window_id":"51adccc98c7a30d67dda67dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51adccc98c7a30d67dda67dd/native_gt.npz","filtered_start_offset":18,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject1/h1/3/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"51e89a51190ac2491dab5d01:0","filtered_window_id":"51e89a51190ac2491dab5d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51e89a51190ac2491dab5d01/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[295,296,297,298,299,300,301,302],"take":"subject2/k1/4/cam4","frame_ids":[295,296,297,298,299,300,301,302]} +{"filtered_tile_id":"51e89a51190ac2491dab5d01:8","filtered_window_id":"51e89a51190ac2491dab5d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51e89a51190ac2491dab5d01/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[303,304,305,306,307,308,309,310],"take":"subject2/k1/4/cam4","frame_ids":[303,304,305,306,307,308,309,310]} +{"filtered_tile_id":"51e89a51190ac2491dab5d01:16","filtered_window_id":"51e89a51190ac2491dab5d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51e89a51190ac2491dab5d01/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[311,312,313,314,315,316,317,318],"take":"subject2/k1/4/cam4","frame_ids":[311,312,313,314,315,316,317,318]} +{"filtered_tile_id":"51e89a51190ac2491dab5d01:24","filtered_window_id":"51e89a51190ac2491dab5d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51e89a51190ac2491dab5d01/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[319,320,321,322,323,324,325,326],"take":"subject2/k1/4/cam4","frame_ids":[319,320,321,322,323,324,325,326]} +{"filtered_tile_id":"51e89a51190ac2491dab5d01:32","filtered_window_id":"51e89a51190ac2491dab5d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51e89a51190ac2491dab5d01/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[327,328,329,330,331,332,333,334],"take":"subject2/k1/4/cam4","frame_ids":[327,328,329,330,331,332,333,334]} +{"filtered_tile_id":"51e89a51190ac2491dab5d01:40","filtered_window_id":"51e89a51190ac2491dab5d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51e89a51190ac2491dab5d01/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[335,336,337,338,339,340,341,342],"take":"subject2/k1/4/cam4","frame_ids":[335,336,337,338,339,340,341,342]} +{"filtered_tile_id":"51e89a51190ac2491dab5d01:48","filtered_window_id":"51e89a51190ac2491dab5d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51e89a51190ac2491dab5d01/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[343,344,345,346,347,348,349,350],"take":"subject2/k1/4/cam4","frame_ids":[343,344,345,346,347,348,349,350]} +{"filtered_tile_id":"51e89a51190ac2491dab5d01:52","filtered_window_id":"51e89a51190ac2491dab5d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51e89a51190ac2491dab5d01/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[347,348,349,350,351,352,353,354],"take":"subject2/k1/4/cam4","frame_ids":[347,348,349,350,351,352,353,354]} +{"filtered_tile_id":"51f73c7bed8fecc8a92dbdd1:0","filtered_window_id":"51f73c7bed8fecc8a92dbdd1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51f73c7bed8fecc8a92dbdd1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject3/h1/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"51f73c7bed8fecc8a92dbdd1:8","filtered_window_id":"51f73c7bed8fecc8a92dbdd1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51f73c7bed8fecc8a92dbdd1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject3/h1/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"51f73c7bed8fecc8a92dbdd1:16","filtered_window_id":"51f73c7bed8fecc8a92dbdd1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51f73c7bed8fecc8a92dbdd1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject3/h1/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"51f73c7bed8fecc8a92dbdd1:24","filtered_window_id":"51f73c7bed8fecc8a92dbdd1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51f73c7bed8fecc8a92dbdd1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject3/h1/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"51f73c7bed8fecc8a92dbdd1:32","filtered_window_id":"51f73c7bed8fecc8a92dbdd1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51f73c7bed8fecc8a92dbdd1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject3/h1/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"51f73c7bed8fecc8a92dbdd1:40","filtered_window_id":"51f73c7bed8fecc8a92dbdd1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51f73c7bed8fecc8a92dbdd1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject3/h1/1/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"51f73c7bed8fecc8a92dbdd1:48","filtered_window_id":"51f73c7bed8fecc8a92dbdd1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51f73c7bed8fecc8a92dbdd1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject3/h1/1/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"51f73c7bed8fecc8a92dbdd1:52","filtered_window_id":"51f73c7bed8fecc8a92dbdd1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/51f73c7bed8fecc8a92dbdd1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject3/h1/1/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"5239bd1fff4f62f57e5444ae:0","filtered_window_id":"5239bd1fff4f62f57e5444ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5239bd1fff4f62f57e5444ae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[744,745,746,747,748,749,750,751],"take":"subject1/h2/3/cam4","frame_ids":[744,745,746,747,748,749,750,751]} +{"filtered_tile_id":"5239bd1fff4f62f57e5444ae:8","filtered_window_id":"5239bd1fff4f62f57e5444ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5239bd1fff4f62f57e5444ae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[752,753,754,755,756,757,758,759],"take":"subject1/h2/3/cam4","frame_ids":[752,753,754,755,756,757,758,759]} +{"filtered_tile_id":"5239bd1fff4f62f57e5444ae:16","filtered_window_id":"5239bd1fff4f62f57e5444ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5239bd1fff4f62f57e5444ae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[760,761,762,763,764,765,766,767],"take":"subject1/h2/3/cam4","frame_ids":[760,761,762,763,764,765,766,767]} +{"filtered_tile_id":"5239bd1fff4f62f57e5444ae:24","filtered_window_id":"5239bd1fff4f62f57e5444ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5239bd1fff4f62f57e5444ae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[768,769,770,771,772,773,774,775],"take":"subject1/h2/3/cam4","frame_ids":[768,769,770,771,772,773,774,775]} +{"filtered_tile_id":"5239bd1fff4f62f57e5444ae:32","filtered_window_id":"5239bd1fff4f62f57e5444ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5239bd1fff4f62f57e5444ae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[776,777,778,779,780,781,782,783],"take":"subject1/h2/3/cam4","frame_ids":[776,777,778,779,780,781,782,783]} +{"filtered_tile_id":"5239bd1fff4f62f57e5444ae:40","filtered_window_id":"5239bd1fff4f62f57e5444ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5239bd1fff4f62f57e5444ae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[784,785,786,787,788,789,790,791],"take":"subject1/h2/3/cam4","frame_ids":[784,785,786,787,788,789,790,791]} +{"filtered_tile_id":"5239bd1fff4f62f57e5444ae:48","filtered_window_id":"5239bd1fff4f62f57e5444ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5239bd1fff4f62f57e5444ae/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[792,793,794,795,796,797,798,799],"take":"subject1/h2/3/cam4","frame_ids":[792,793,794,795,796,797,798,799]} +{"filtered_tile_id":"5239bd1fff4f62f57e5444ae:52","filtered_window_id":"5239bd1fff4f62f57e5444ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5239bd1fff4f62f57e5444ae/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[796,797,798,799,800,801,802,803],"take":"subject1/h2/3/cam4","frame_ids":[796,797,798,799,800,801,802,803]} +{"filtered_tile_id":"524b582fc05dc94a7d5d5021:0","filtered_window_id":"524b582fc05dc94a7d5d5021","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/524b582fc05dc94a7d5d5021/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject3/h2/6/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"524b582fc05dc94a7d5d5021:8","filtered_window_id":"524b582fc05dc94a7d5d5021","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/524b582fc05dc94a7d5d5021/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[481,482,483,484,485,486,487,488],"take":"subject3/h2/6/cam4","frame_ids":[481,482,483,484,485,486,487,488]} +{"filtered_tile_id":"524b582fc05dc94a7d5d5021:16","filtered_window_id":"524b582fc05dc94a7d5d5021","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/524b582fc05dc94a7d5d5021/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[489,490,491,492,493,494,495,496],"take":"subject3/h2/6/cam4","frame_ids":[489,490,491,492,493,494,495,496]} +{"filtered_tile_id":"524b582fc05dc94a7d5d5021:24","filtered_window_id":"524b582fc05dc94a7d5d5021","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/524b582fc05dc94a7d5d5021/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[497,498,499,500,501,502,503,504],"take":"subject3/h2/6/cam4","frame_ids":[497,498,499,500,501,502,503,504]} +{"filtered_tile_id":"524b582fc05dc94a7d5d5021:32","filtered_window_id":"524b582fc05dc94a7d5d5021","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/524b582fc05dc94a7d5d5021/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[505,506,507,508,509,510,511,512],"take":"subject3/h2/6/cam4","frame_ids":[505,506,507,508,509,510,511,512]} +{"filtered_tile_id":"524b582fc05dc94a7d5d5021:40","filtered_window_id":"524b582fc05dc94a7d5d5021","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/524b582fc05dc94a7d5d5021/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[513,514,515,516,517,518,519,520],"take":"subject3/h2/6/cam4","frame_ids":[513,514,515,516,517,518,519,520]} +{"filtered_tile_id":"524b582fc05dc94a7d5d5021:48","filtered_window_id":"524b582fc05dc94a7d5d5021","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/524b582fc05dc94a7d5d5021/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[521,522,523,524,525,526,527,528],"take":"subject3/h2/6/cam4","frame_ids":[521,522,523,524,525,526,527,528]} +{"filtered_tile_id":"524b582fc05dc94a7d5d5021:52","filtered_window_id":"524b582fc05dc94a7d5d5021","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/524b582fc05dc94a7d5d5021/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[525,526,527,528,529,530,531,532],"take":"subject3/h2/6/cam4","frame_ids":[525,526,527,528,529,530,531,532]} +{"filtered_tile_id":"52a5aca94e7c4f8e4659cdb5:0","filtered_window_id":"52a5aca94e7c4f8e4659cdb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52a5aca94e7c4f8e4659cdb5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[251,252,253,254,255,256,257,258],"take":"subject2/o1/5/cam4","frame_ids":[251,252,253,254,255,256,257,258]} +{"filtered_tile_id":"52a5aca94e7c4f8e4659cdb5:8","filtered_window_id":"52a5aca94e7c4f8e4659cdb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52a5aca94e7c4f8e4659cdb5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[259,260,261,262,263,264,265,266],"take":"subject2/o1/5/cam4","frame_ids":[259,260,261,262,263,264,265,266]} +{"filtered_tile_id":"52a5aca94e7c4f8e4659cdb5:16","filtered_window_id":"52a5aca94e7c4f8e4659cdb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52a5aca94e7c4f8e4659cdb5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[267,268,269,270,271,272,273,274],"take":"subject2/o1/5/cam4","frame_ids":[267,268,269,270,271,272,273,274]} +{"filtered_tile_id":"52a5aca94e7c4f8e4659cdb5:19","filtered_window_id":"52a5aca94e7c4f8e4659cdb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52a5aca94e7c4f8e4659cdb5/native_gt.npz","filtered_start_offset":19,"expected_frame_ids":[270,271,272,273,274,275,276,277],"take":"subject2/o1/5/cam4","frame_ids":[270,271,272,273,274,275,276,277]} +{"filtered_tile_id":"52c782f6c58167664b6e6d50:0","filtered_window_id":"52c782f6c58167664b6e6d50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52c782f6c58167664b6e6d50/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject3/h2/6/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"52c782f6c58167664b6e6d50:8","filtered_window_id":"52c782f6c58167664b6e6d50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52c782f6c58167664b6e6d50/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject3/h2/6/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"52c782f6c58167664b6e6d50:16","filtered_window_id":"52c782f6c58167664b6e6d50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52c782f6c58167664b6e6d50/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject3/h2/6/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"52c782f6c58167664b6e6d50:24","filtered_window_id":"52c782f6c58167664b6e6d50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52c782f6c58167664b6e6d50/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject3/h2/6/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"52c782f6c58167664b6e6d50:32","filtered_window_id":"52c782f6c58167664b6e6d50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52c782f6c58167664b6e6d50/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject3/h2/6/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"52c782f6c58167664b6e6d50:40","filtered_window_id":"52c782f6c58167664b6e6d50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52c782f6c58167664b6e6d50/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject3/h2/6/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"52c782f6c58167664b6e6d50:48","filtered_window_id":"52c782f6c58167664b6e6d50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52c782f6c58167664b6e6d50/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject3/h2/6/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"52c782f6c58167664b6e6d50:52","filtered_window_id":"52c782f6c58167664b6e6d50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/52c782f6c58167664b6e6d50/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject3/h2/6/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"5301a55f655bda11f0e205ff:0","filtered_window_id":"5301a55f655bda11f0e205ff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5301a55f655bda11f0e205ff/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[61,62,63,64,65,66,67,68],"take":"subject1/h2/2/cam4","frame_ids":[61,62,63,64,65,66,67,68]} +{"filtered_tile_id":"5301a55f655bda11f0e205ff:8","filtered_window_id":"5301a55f655bda11f0e205ff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5301a55f655bda11f0e205ff/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject1/h2/2/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"5301a55f655bda11f0e205ff:16","filtered_window_id":"5301a55f655bda11f0e205ff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5301a55f655bda11f0e205ff/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[77,78,79,80,81,82,83,84],"take":"subject1/h2/2/cam4","frame_ids":[77,78,79,80,81,82,83,84]} +{"filtered_tile_id":"5301a55f655bda11f0e205ff:24","filtered_window_id":"5301a55f655bda11f0e205ff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5301a55f655bda11f0e205ff/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject1/h2/2/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"5301a55f655bda11f0e205ff:32","filtered_window_id":"5301a55f655bda11f0e205ff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5301a55f655bda11f0e205ff/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[93,94,95,96,97,98,99,100],"take":"subject1/h2/2/cam4","frame_ids":[93,94,95,96,97,98,99,100]} +{"filtered_tile_id":"5301a55f655bda11f0e205ff:40","filtered_window_id":"5301a55f655bda11f0e205ff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5301a55f655bda11f0e205ff/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[101,102,103,104,105,106,107,108],"take":"subject1/h2/2/cam4","frame_ids":[101,102,103,104,105,106,107,108]} +{"filtered_tile_id":"543640be6fe87377011523d4:0","filtered_window_id":"543640be6fe87377011523d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/543640be6fe87377011523d4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[533,534,535,536,537,538,539,540],"take":"subject3/h2/6/cam4","frame_ids":[533,534,535,536,537,538,539,540]} +{"filtered_tile_id":"543640be6fe87377011523d4:8","filtered_window_id":"543640be6fe87377011523d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/543640be6fe87377011523d4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject3/h2/6/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"543640be6fe87377011523d4:16","filtered_window_id":"543640be6fe87377011523d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/543640be6fe87377011523d4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[549,550,551,552,553,554,555,556],"take":"subject3/h2/6/cam4","frame_ids":[549,550,551,552,553,554,555,556]} +{"filtered_tile_id":"543640be6fe87377011523d4:24","filtered_window_id":"543640be6fe87377011523d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/543640be6fe87377011523d4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[557,558,559,560,561,562,563,564],"take":"subject3/h2/6/cam4","frame_ids":[557,558,559,560,561,562,563,564]} +{"filtered_tile_id":"543640be6fe87377011523d4:32","filtered_window_id":"543640be6fe87377011523d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/543640be6fe87377011523d4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[565,566,567,568,569,570,571,572],"take":"subject3/h2/6/cam4","frame_ids":[565,566,567,568,569,570,571,572]} +{"filtered_tile_id":"543640be6fe87377011523d4:40","filtered_window_id":"543640be6fe87377011523d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/543640be6fe87377011523d4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[573,574,575,576,577,578,579,580],"take":"subject3/h2/6/cam4","frame_ids":[573,574,575,576,577,578,579,580]} +{"filtered_tile_id":"543640be6fe87377011523d4:43","filtered_window_id":"543640be6fe87377011523d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/543640be6fe87377011523d4/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[576,577,578,579,580,581,582,583],"take":"subject3/h2/6/cam4","frame_ids":[576,577,578,579,580,581,582,583]} +{"filtered_tile_id":"55603f2c5078c5fffd8e14da:0","filtered_window_id":"55603f2c5078c5fffd8e14da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55603f2c5078c5fffd8e14da/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject1/o1/7/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"55603f2c5078c5fffd8e14da:8","filtered_window_id":"55603f2c5078c5fffd8e14da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55603f2c5078c5fffd8e14da/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject1/o1/7/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"55603f2c5078c5fffd8e14da:16","filtered_window_id":"55603f2c5078c5fffd8e14da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55603f2c5078c5fffd8e14da/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject1/o1/7/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"55603f2c5078c5fffd8e14da:24","filtered_window_id":"55603f2c5078c5fffd8e14da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55603f2c5078c5fffd8e14da/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject1/o1/7/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"55603f2c5078c5fffd8e14da:32","filtered_window_id":"55603f2c5078c5fffd8e14da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55603f2c5078c5fffd8e14da/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject1/o1/7/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"55603f2c5078c5fffd8e14da:40","filtered_window_id":"55603f2c5078c5fffd8e14da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55603f2c5078c5fffd8e14da/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject1/o1/7/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"55603f2c5078c5fffd8e14da:48","filtered_window_id":"55603f2c5078c5fffd8e14da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55603f2c5078c5fffd8e14da/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject1/o1/7/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"55603f2c5078c5fffd8e14da:52","filtered_window_id":"55603f2c5078c5fffd8e14da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55603f2c5078c5fffd8e14da/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject1/o1/7/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"55e3df9135928407240a3a75:0","filtered_window_id":"55e3df9135928407240a3a75","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55e3df9135928407240a3a75/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[398,399,400,401,402,403,404,405],"take":"subject2/k1/0/cam4","frame_ids":[398,399,400,401,402,403,404,405]} +{"filtered_tile_id":"55e3df9135928407240a3a75:8","filtered_window_id":"55e3df9135928407240a3a75","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55e3df9135928407240a3a75/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[406,407,408,409,410,411,412,413],"take":"subject2/k1/0/cam4","frame_ids":[406,407,408,409,410,411,412,413]} +{"filtered_tile_id":"55e3df9135928407240a3a75:16","filtered_window_id":"55e3df9135928407240a3a75","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55e3df9135928407240a3a75/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[414,415,416,417,418,419,420,421],"take":"subject2/k1/0/cam4","frame_ids":[414,415,416,417,418,419,420,421]} +{"filtered_tile_id":"55e3df9135928407240a3a75:24","filtered_window_id":"55e3df9135928407240a3a75","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55e3df9135928407240a3a75/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[422,423,424,425,426,427,428,429],"take":"subject2/k1/0/cam4","frame_ids":[422,423,424,425,426,427,428,429]} +{"filtered_tile_id":"55e3df9135928407240a3a75:32","filtered_window_id":"55e3df9135928407240a3a75","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55e3df9135928407240a3a75/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[430,431,432,433,434,435,436,437],"take":"subject2/k1/0/cam4","frame_ids":[430,431,432,433,434,435,436,437]} +{"filtered_tile_id":"55e3df9135928407240a3a75:40","filtered_window_id":"55e3df9135928407240a3a75","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55e3df9135928407240a3a75/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[438,439,440,441,442,443,444,445],"take":"subject2/k1/0/cam4","frame_ids":[438,439,440,441,442,443,444,445]} +{"filtered_tile_id":"55e3df9135928407240a3a75:48","filtered_window_id":"55e3df9135928407240a3a75","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55e3df9135928407240a3a75/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[446,447,448,449,450,451,452,453],"take":"subject2/k1/0/cam4","frame_ids":[446,447,448,449,450,451,452,453]} +{"filtered_tile_id":"55e3df9135928407240a3a75:52","filtered_window_id":"55e3df9135928407240a3a75","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/55e3df9135928407240a3a75/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject2/k1/0/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"5603db8c95b8928f0c608fef:0","filtered_window_id":"5603db8c95b8928f0c608fef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5603db8c95b8928f0c608fef/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject3/h1/7/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"5603db8c95b8928f0c608fef:8","filtered_window_id":"5603db8c95b8928f0c608fef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5603db8c95b8928f0c608fef/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[98,99,100,101,102,103,104,105],"take":"subject3/h1/7/cam4","frame_ids":[98,99,100,101,102,103,104,105]} +{"filtered_tile_id":"5603db8c95b8928f0c608fef:16","filtered_window_id":"5603db8c95b8928f0c608fef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5603db8c95b8928f0c608fef/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[106,107,108,109,110,111,112,113],"take":"subject3/h1/7/cam4","frame_ids":[106,107,108,109,110,111,112,113]} +{"filtered_tile_id":"5603db8c95b8928f0c608fef:24","filtered_window_id":"5603db8c95b8928f0c608fef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5603db8c95b8928f0c608fef/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject3/h1/7/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"5603db8c95b8928f0c608fef:32","filtered_window_id":"5603db8c95b8928f0c608fef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5603db8c95b8928f0c608fef/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject3/h1/7/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"5603db8c95b8928f0c608fef:40","filtered_window_id":"5603db8c95b8928f0c608fef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5603db8c95b8928f0c608fef/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject3/h1/7/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"5603db8c95b8928f0c608fef:43","filtered_window_id":"5603db8c95b8928f0c608fef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5603db8c95b8928f0c608fef/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject3/h1/7/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"566f354d0255b3058c582914:0","filtered_window_id":"566f354d0255b3058c582914","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/566f354d0255b3058c582914/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[18,19,20,21,22,23,24,25],"take":"subject2/o2/0/cam4","frame_ids":[18,19,20,21,22,23,24,25]} +{"filtered_tile_id":"566f354d0255b3058c582914:8","filtered_window_id":"566f354d0255b3058c582914","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/566f354d0255b3058c582914/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[26,27,28,29,30,31,32,33],"take":"subject2/o2/0/cam4","frame_ids":[26,27,28,29,30,31,32,33]} +{"filtered_tile_id":"566f354d0255b3058c582914:16","filtered_window_id":"566f354d0255b3058c582914","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/566f354d0255b3058c582914/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[34,35,36,37,38,39,40,41],"take":"subject2/o2/0/cam4","frame_ids":[34,35,36,37,38,39,40,41]} +{"filtered_tile_id":"566f354d0255b3058c582914:24","filtered_window_id":"566f354d0255b3058c582914","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/566f354d0255b3058c582914/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[42,43,44,45,46,47,48,49],"take":"subject2/o2/0/cam4","frame_ids":[42,43,44,45,46,47,48,49]} +{"filtered_tile_id":"566f354d0255b3058c582914:32","filtered_window_id":"566f354d0255b3058c582914","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/566f354d0255b3058c582914/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[50,51,52,53,54,55,56,57],"take":"subject2/o2/0/cam4","frame_ids":[50,51,52,53,54,55,56,57]} +{"filtered_tile_id":"566f354d0255b3058c582914:40","filtered_window_id":"566f354d0255b3058c582914","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/566f354d0255b3058c582914/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[58,59,60,61,62,63,64,65],"take":"subject2/o2/0/cam4","frame_ids":[58,59,60,61,62,63,64,65]} +{"filtered_tile_id":"566f354d0255b3058c582914:47","filtered_window_id":"566f354d0255b3058c582914","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/566f354d0255b3058c582914/native_gt.npz","filtered_start_offset":47,"expected_frame_ids":[65,66,67,68,69,70,71,72],"take":"subject2/o2/0/cam4","frame_ids":[65,66,67,68,69,70,71,72]} +{"filtered_tile_id":"56cfc80d0f80d85b24395e0e:0","filtered_window_id":"56cfc80d0f80d85b24395e0e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/56cfc80d0f80d85b24395e0e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[80,81,82,83,84,85,86,87],"take":"subject1/k1/2/cam4","frame_ids":[80,81,82,83,84,85,86,87]} +{"filtered_tile_id":"56cfc80d0f80d85b24395e0e:8","filtered_window_id":"56cfc80d0f80d85b24395e0e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/56cfc80d0f80d85b24395e0e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject1/k1/2/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"56cfc80d0f80d85b24395e0e:11","filtered_window_id":"56cfc80d0f80d85b24395e0e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/56cfc80d0f80d85b24395e0e/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject1/k1/2/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"5725836f2ca41a20be4e579d:0","filtered_window_id":"5725836f2ca41a20be4e579d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5725836f2ca41a20be4e579d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[316,317,318,319,320,321,322,323],"take":"subject2/h1/5/cam4","frame_ids":[316,317,318,319,320,321,322,323]} +{"filtered_tile_id":"5725836f2ca41a20be4e579d:8","filtered_window_id":"5725836f2ca41a20be4e579d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5725836f2ca41a20be4e579d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject2/h1/5/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"5725836f2ca41a20be4e579d:16","filtered_window_id":"5725836f2ca41a20be4e579d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5725836f2ca41a20be4e579d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject2/h1/5/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"5725836f2ca41a20be4e579d:24","filtered_window_id":"5725836f2ca41a20be4e579d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5725836f2ca41a20be4e579d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[340,341,342,343,344,345,346,347],"take":"subject2/h1/5/cam4","frame_ids":[340,341,342,343,344,345,346,347]} +{"filtered_tile_id":"5725836f2ca41a20be4e579d:32","filtered_window_id":"5725836f2ca41a20be4e579d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5725836f2ca41a20be4e579d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[348,349,350,351,352,353,354,355],"take":"subject2/h1/5/cam4","frame_ids":[348,349,350,351,352,353,354,355]} +{"filtered_tile_id":"5725836f2ca41a20be4e579d:40","filtered_window_id":"5725836f2ca41a20be4e579d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5725836f2ca41a20be4e579d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[356,357,358,359,360,361,362,363],"take":"subject2/h1/5/cam4","frame_ids":[356,357,358,359,360,361,362,363]} +{"filtered_tile_id":"5725836f2ca41a20be4e579d:48","filtered_window_id":"5725836f2ca41a20be4e579d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5725836f2ca41a20be4e579d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject2/h1/5/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"5725836f2ca41a20be4e579d:49","filtered_window_id":"5725836f2ca41a20be4e579d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5725836f2ca41a20be4e579d/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject2/h1/5/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"5732054fe823cec03fc7302f:0","filtered_window_id":"5732054fe823cec03fc7302f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5732054fe823cec03fc7302f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject1/o1/7/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"5732054fe823cec03fc7302f:8","filtered_window_id":"5732054fe823cec03fc7302f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5732054fe823cec03fc7302f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject1/o1/7/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"5732054fe823cec03fc7302f:16","filtered_window_id":"5732054fe823cec03fc7302f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5732054fe823cec03fc7302f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject1/o1/7/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"5732054fe823cec03fc7302f:24","filtered_window_id":"5732054fe823cec03fc7302f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5732054fe823cec03fc7302f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject1/o1/7/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"5732054fe823cec03fc7302f:32","filtered_window_id":"5732054fe823cec03fc7302f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5732054fe823cec03fc7302f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject1/o1/7/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"5732054fe823cec03fc7302f:40","filtered_window_id":"5732054fe823cec03fc7302f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5732054fe823cec03fc7302f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject1/o1/7/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"5732054fe823cec03fc7302f:48","filtered_window_id":"5732054fe823cec03fc7302f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5732054fe823cec03fc7302f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject1/o1/7/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"5732054fe823cec03fc7302f:52","filtered_window_id":"5732054fe823cec03fc7302f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5732054fe823cec03fc7302f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject1/o1/7/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"5812d3baa9ea1339a31746ea:0","filtered_window_id":"5812d3baa9ea1339a31746ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5812d3baa9ea1339a31746ea/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject2/o2/2/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"5812d3baa9ea1339a31746ea:2","filtered_window_id":"5812d3baa9ea1339a31746ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5812d3baa9ea1339a31746ea/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject2/o2/2/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"59797e3e9c6b1424123d3815:0","filtered_window_id":"59797e3e9c6b1424123d3815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/59797e3e9c6b1424123d3815/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[235,236,237,238,239,240,241,242],"take":"subject1/h1/1/cam4","frame_ids":[235,236,237,238,239,240,241,242]} +{"filtered_tile_id":"59797e3e9c6b1424123d3815:8","filtered_window_id":"59797e3e9c6b1424123d3815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/59797e3e9c6b1424123d3815/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[243,244,245,246,247,248,249,250],"take":"subject1/h1/1/cam4","frame_ids":[243,244,245,246,247,248,249,250]} +{"filtered_tile_id":"59797e3e9c6b1424123d3815:16","filtered_window_id":"59797e3e9c6b1424123d3815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/59797e3e9c6b1424123d3815/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[251,252,253,254,255,256,257,258],"take":"subject1/h1/1/cam4","frame_ids":[251,252,253,254,255,256,257,258]} +{"filtered_tile_id":"59797e3e9c6b1424123d3815:24","filtered_window_id":"59797e3e9c6b1424123d3815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/59797e3e9c6b1424123d3815/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[259,260,261,262,263,264,265,266],"take":"subject1/h1/1/cam4","frame_ids":[259,260,261,262,263,264,265,266]} +{"filtered_tile_id":"59797e3e9c6b1424123d3815:26","filtered_window_id":"59797e3e9c6b1424123d3815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/59797e3e9c6b1424123d3815/native_gt.npz","filtered_start_offset":26,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject1/h1/1/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"597d0549c0725b083f398ce4:0","filtered_window_id":"597d0549c0725b083f398ce4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/597d0549c0725b083f398ce4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject1/o1/6/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"597d0549c0725b083f398ce4:8","filtered_window_id":"597d0549c0725b083f398ce4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/597d0549c0725b083f398ce4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject1/o1/6/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"597d0549c0725b083f398ce4:16","filtered_window_id":"597d0549c0725b083f398ce4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/597d0549c0725b083f398ce4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject1/o1/6/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"597d0549c0725b083f398ce4:24","filtered_window_id":"597d0549c0725b083f398ce4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/597d0549c0725b083f398ce4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject1/o1/6/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"597d0549c0725b083f398ce4:32","filtered_window_id":"597d0549c0725b083f398ce4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/597d0549c0725b083f398ce4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[236,237,238,239,240,241,242,243],"take":"subject1/o1/6/cam4","frame_ids":[236,237,238,239,240,241,242,243]} +{"filtered_tile_id":"597d0549c0725b083f398ce4:40","filtered_window_id":"597d0549c0725b083f398ce4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/597d0549c0725b083f398ce4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[244,245,246,247,248,249,250,251],"take":"subject1/o1/6/cam4","frame_ids":[244,245,246,247,248,249,250,251]} +{"filtered_tile_id":"597d0549c0725b083f398ce4:48","filtered_window_id":"597d0549c0725b083f398ce4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/597d0549c0725b083f398ce4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[252,253,254,255,256,257,258,259],"take":"subject1/o1/6/cam4","frame_ids":[252,253,254,255,256,257,258,259]} +{"filtered_tile_id":"597d0549c0725b083f398ce4:52","filtered_window_id":"597d0549c0725b083f398ce4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/597d0549c0725b083f398ce4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject1/o1/6/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"599d067e5bd4b99fe5ec5cbd:0","filtered_window_id":"599d067e5bd4b99fe5ec5cbd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/599d067e5bd4b99fe5ec5cbd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[300,301,302,303,304,305,306,307],"take":"subject2/h2/1/cam4","frame_ids":[300,301,302,303,304,305,306,307]} +{"filtered_tile_id":"599d067e5bd4b99fe5ec5cbd:8","filtered_window_id":"599d067e5bd4b99fe5ec5cbd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/599d067e5bd4b99fe5ec5cbd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject2/h2/1/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"599d067e5bd4b99fe5ec5cbd:16","filtered_window_id":"599d067e5bd4b99fe5ec5cbd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/599d067e5bd4b99fe5ec5cbd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[316,317,318,319,320,321,322,323],"take":"subject2/h2/1/cam4","frame_ids":[316,317,318,319,320,321,322,323]} +{"filtered_tile_id":"599d067e5bd4b99fe5ec5cbd:24","filtered_window_id":"599d067e5bd4b99fe5ec5cbd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/599d067e5bd4b99fe5ec5cbd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject2/h2/1/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"599d067e5bd4b99fe5ec5cbd:32","filtered_window_id":"599d067e5bd4b99fe5ec5cbd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/599d067e5bd4b99fe5ec5cbd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject2/h2/1/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"599d067e5bd4b99fe5ec5cbd:40","filtered_window_id":"599d067e5bd4b99fe5ec5cbd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/599d067e5bd4b99fe5ec5cbd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[340,341,342,343,344,345,346,347],"take":"subject2/h2/1/cam4","frame_ids":[340,341,342,343,344,345,346,347]} +{"filtered_tile_id":"5a12d6cc2c3f5fb17c9ed87b:0","filtered_window_id":"5a12d6cc2c3f5fb17c9ed87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a12d6cc2c3f5fb17c9ed87b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[521,522,523,524,525,526,527,528],"take":"subject2/h1/4/cam4","frame_ids":[521,522,523,524,525,526,527,528]} +{"filtered_tile_id":"5a12d6cc2c3f5fb17c9ed87b:8","filtered_window_id":"5a12d6cc2c3f5fb17c9ed87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a12d6cc2c3f5fb17c9ed87b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[529,530,531,532,533,534,535,536],"take":"subject2/h1/4/cam4","frame_ids":[529,530,531,532,533,534,535,536]} +{"filtered_tile_id":"5a12d6cc2c3f5fb17c9ed87b:16","filtered_window_id":"5a12d6cc2c3f5fb17c9ed87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a12d6cc2c3f5fb17c9ed87b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[537,538,539,540,541,542,543,544],"take":"subject2/h1/4/cam4","frame_ids":[537,538,539,540,541,542,543,544]} +{"filtered_tile_id":"5a12d6cc2c3f5fb17c9ed87b:24","filtered_window_id":"5a12d6cc2c3f5fb17c9ed87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a12d6cc2c3f5fb17c9ed87b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[545,546,547,548,549,550,551,552],"take":"subject2/h1/4/cam4","frame_ids":[545,546,547,548,549,550,551,552]} +{"filtered_tile_id":"5a12d6cc2c3f5fb17c9ed87b:28","filtered_window_id":"5a12d6cc2c3f5fb17c9ed87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a12d6cc2c3f5fb17c9ed87b/native_gt.npz","filtered_start_offset":28,"expected_frame_ids":[549,550,551,552,553,554,555,556],"take":"subject2/h1/4/cam4","frame_ids":[549,550,551,552,553,554,555,556]} +{"filtered_tile_id":"5a448ec06ffe2cfcbffead85:0","filtered_window_id":"5a448ec06ffe2cfcbffead85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a448ec06ffe2cfcbffead85/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o1/4/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"5a448ec06ffe2cfcbffead85:8","filtered_window_id":"5a448ec06ffe2cfcbffead85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a448ec06ffe2cfcbffead85/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o1/4/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"5a448ec06ffe2cfcbffead85:16","filtered_window_id":"5a448ec06ffe2cfcbffead85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a448ec06ffe2cfcbffead85/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o1/4/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"5a448ec06ffe2cfcbffead85:24","filtered_window_id":"5a448ec06ffe2cfcbffead85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a448ec06ffe2cfcbffead85/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o1/4/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"5a448ec06ffe2cfcbffead85:32","filtered_window_id":"5a448ec06ffe2cfcbffead85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a448ec06ffe2cfcbffead85/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o1/4/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"5a448ec06ffe2cfcbffead85:40","filtered_window_id":"5a448ec06ffe2cfcbffead85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a448ec06ffe2cfcbffead85/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/o1/4/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"5a448ec06ffe2cfcbffead85:43","filtered_window_id":"5a448ec06ffe2cfcbffead85","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a448ec06ffe2cfcbffead85/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[43,44,45,46,47,48,49,50],"take":"subject1/o1/4/cam4","frame_ids":[43,44,45,46,47,48,49,50]} +{"filtered_tile_id":"5a816e1dd819c9e08050842f:0","filtered_window_id":"5a816e1dd819c9e08050842f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a816e1dd819c9e08050842f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/h2/5/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"5a816e1dd819c9e08050842f:8","filtered_window_id":"5a816e1dd819c9e08050842f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a816e1dd819c9e08050842f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/h2/5/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"5a816e1dd819c9e08050842f:16","filtered_window_id":"5a816e1dd819c9e08050842f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a816e1dd819c9e08050842f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/h2/5/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"5a816e1dd819c9e08050842f:24","filtered_window_id":"5a816e1dd819c9e08050842f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a816e1dd819c9e08050842f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/h2/5/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"5a816e1dd819c9e08050842f:32","filtered_window_id":"5a816e1dd819c9e08050842f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a816e1dd819c9e08050842f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/h2/5/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"5a816e1dd819c9e08050842f:40","filtered_window_id":"5a816e1dd819c9e08050842f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a816e1dd819c9e08050842f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/h2/5/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"5a816e1dd819c9e08050842f:48","filtered_window_id":"5a816e1dd819c9e08050842f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a816e1dd819c9e08050842f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/h2/5/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"5a816e1dd819c9e08050842f:52","filtered_window_id":"5a816e1dd819c9e08050842f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5a816e1dd819c9e08050842f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/h2/5/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"5aaaec5449cc031b9dbbf62b:0","filtered_window_id":"5aaaec5449cc031b9dbbf62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5aaaec5449cc031b9dbbf62b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[398,399,400,401,402,403,404,405],"take":"subject3/h2/4/cam4","frame_ids":[398,399,400,401,402,403,404,405]} +{"filtered_tile_id":"5aaaec5449cc031b9dbbf62b:8","filtered_window_id":"5aaaec5449cc031b9dbbf62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5aaaec5449cc031b9dbbf62b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[406,407,408,409,410,411,412,413],"take":"subject3/h2/4/cam4","frame_ids":[406,407,408,409,410,411,412,413]} +{"filtered_tile_id":"5aaaec5449cc031b9dbbf62b:16","filtered_window_id":"5aaaec5449cc031b9dbbf62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5aaaec5449cc031b9dbbf62b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[414,415,416,417,418,419,420,421],"take":"subject3/h2/4/cam4","frame_ids":[414,415,416,417,418,419,420,421]} +{"filtered_tile_id":"5aaaec5449cc031b9dbbf62b:24","filtered_window_id":"5aaaec5449cc031b9dbbf62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5aaaec5449cc031b9dbbf62b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[422,423,424,425,426,427,428,429],"take":"subject3/h2/4/cam4","frame_ids":[422,423,424,425,426,427,428,429]} +{"filtered_tile_id":"5aaaec5449cc031b9dbbf62b:32","filtered_window_id":"5aaaec5449cc031b9dbbf62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5aaaec5449cc031b9dbbf62b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[430,431,432,433,434,435,436,437],"take":"subject3/h2/4/cam4","frame_ids":[430,431,432,433,434,435,436,437]} +{"filtered_tile_id":"5aaaec5449cc031b9dbbf62b:40","filtered_window_id":"5aaaec5449cc031b9dbbf62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5aaaec5449cc031b9dbbf62b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[438,439,440,441,442,443,444,445],"take":"subject3/h2/4/cam4","frame_ids":[438,439,440,441,442,443,444,445]} +{"filtered_tile_id":"5aaaec5449cc031b9dbbf62b:48","filtered_window_id":"5aaaec5449cc031b9dbbf62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5aaaec5449cc031b9dbbf62b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[446,447,448,449,450,451,452,453],"take":"subject3/h2/4/cam4","frame_ids":[446,447,448,449,450,451,452,453]} +{"filtered_tile_id":"5aaaec5449cc031b9dbbf62b:52","filtered_window_id":"5aaaec5449cc031b9dbbf62b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5aaaec5449cc031b9dbbf62b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject3/h2/4/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"5ac53d40cc6757477ad9d36f:0","filtered_window_id":"5ac53d40cc6757477ad9d36f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ac53d40cc6757477ad9d36f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject1/o2/3/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"5ac53d40cc6757477ad9d36f:8","filtered_window_id":"5ac53d40cc6757477ad9d36f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ac53d40cc6757477ad9d36f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject1/o2/3/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"5ac53d40cc6757477ad9d36f:16","filtered_window_id":"5ac53d40cc6757477ad9d36f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ac53d40cc6757477ad9d36f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject1/o2/3/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"5ac53d40cc6757477ad9d36f:24","filtered_window_id":"5ac53d40cc6757477ad9d36f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ac53d40cc6757477ad9d36f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[386,387,388,389,390,391,392,393],"take":"subject1/o2/3/cam4","frame_ids":[386,387,388,389,390,391,392,393]} +{"filtered_tile_id":"5ac53d40cc6757477ad9d36f:27","filtered_window_id":"5ac53d40cc6757477ad9d36f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ac53d40cc6757477ad9d36f/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[389,390,391,392,393,394,395,396],"take":"subject1/o2/3/cam4","frame_ids":[389,390,391,392,393,394,395,396]} +{"filtered_tile_id":"5b21acc004567bdb537ad82b:0","filtered_window_id":"5b21acc004567bdb537ad82b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b21acc004567bdb537ad82b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[592,593,594,595,596,597,598,599],"take":"subject2/k2/1/cam4","frame_ids":[592,593,594,595,596,597,598,599]} +{"filtered_tile_id":"5b21acc004567bdb537ad82b:8","filtered_window_id":"5b21acc004567bdb537ad82b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b21acc004567bdb537ad82b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[600,601,602,603,604,605,606,607],"take":"subject2/k2/1/cam4","frame_ids":[600,601,602,603,604,605,606,607]} +{"filtered_tile_id":"5b21acc004567bdb537ad82b:16","filtered_window_id":"5b21acc004567bdb537ad82b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b21acc004567bdb537ad82b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[608,609,610,611,612,613,614,615],"take":"subject2/k2/1/cam4","frame_ids":[608,609,610,611,612,613,614,615]} +{"filtered_tile_id":"5b21acc004567bdb537ad82b:24","filtered_window_id":"5b21acc004567bdb537ad82b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b21acc004567bdb537ad82b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[616,617,618,619,620,621,622,623],"take":"subject2/k2/1/cam4","frame_ids":[616,617,618,619,620,621,622,623]} +{"filtered_tile_id":"5b21acc004567bdb537ad82b:32","filtered_window_id":"5b21acc004567bdb537ad82b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b21acc004567bdb537ad82b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[624,625,626,627,628,629,630,631],"take":"subject2/k2/1/cam4","frame_ids":[624,625,626,627,628,629,630,631]} +{"filtered_tile_id":"5b21acc004567bdb537ad82b:40","filtered_window_id":"5b21acc004567bdb537ad82b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b21acc004567bdb537ad82b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[632,633,634,635,636,637,638,639],"take":"subject2/k2/1/cam4","frame_ids":[632,633,634,635,636,637,638,639]} +{"filtered_tile_id":"5b21acc004567bdb537ad82b:48","filtered_window_id":"5b21acc004567bdb537ad82b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b21acc004567bdb537ad82b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[640,641,642,643,644,645,646,647],"take":"subject2/k2/1/cam4","frame_ids":[640,641,642,643,644,645,646,647]} +{"filtered_tile_id":"5b21acc004567bdb537ad82b:52","filtered_window_id":"5b21acc004567bdb537ad82b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b21acc004567bdb537ad82b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[644,645,646,647,648,649,650,651],"take":"subject2/k2/1/cam4","frame_ids":[644,645,646,647,648,649,650,651]} +{"filtered_tile_id":"5b92268d88dcc1eaf2223979:0","filtered_window_id":"5b92268d88dcc1eaf2223979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b92268d88dcc1eaf2223979/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject1/k1/3/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"5b92268d88dcc1eaf2223979:8","filtered_window_id":"5b92268d88dcc1eaf2223979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b92268d88dcc1eaf2223979/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject1/k1/3/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"5b92268d88dcc1eaf2223979:16","filtered_window_id":"5b92268d88dcc1eaf2223979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b92268d88dcc1eaf2223979/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject1/k1/3/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"5b92268d88dcc1eaf2223979:24","filtered_window_id":"5b92268d88dcc1eaf2223979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b92268d88dcc1eaf2223979/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject1/k1/3/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"5b92268d88dcc1eaf2223979:32","filtered_window_id":"5b92268d88dcc1eaf2223979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b92268d88dcc1eaf2223979/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject1/k1/3/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"5b92268d88dcc1eaf2223979:40","filtered_window_id":"5b92268d88dcc1eaf2223979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b92268d88dcc1eaf2223979/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[423,424,425,426,427,428,429,430],"take":"subject1/k1/3/cam4","frame_ids":[423,424,425,426,427,428,429,430]} +{"filtered_tile_id":"5b92268d88dcc1eaf2223979:48","filtered_window_id":"5b92268d88dcc1eaf2223979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b92268d88dcc1eaf2223979/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[431,432,433,434,435,436,437,438],"take":"subject1/k1/3/cam4","frame_ids":[431,432,433,434,435,436,437,438]} +{"filtered_tile_id":"5b92268d88dcc1eaf2223979:52","filtered_window_id":"5b92268d88dcc1eaf2223979","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5b92268d88dcc1eaf2223979/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/k1/3/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"5bb95ab42f31ddc9a326857e:0","filtered_window_id":"5bb95ab42f31ddc9a326857e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bb95ab42f31ddc9a326857e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[351,352,353,354,355,356,357,358],"take":"subject1/o1/5/cam4","frame_ids":[351,352,353,354,355,356,357,358]} +{"filtered_tile_id":"5bb95ab42f31ddc9a326857e:8","filtered_window_id":"5bb95ab42f31ddc9a326857e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bb95ab42f31ddc9a326857e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[359,360,361,362,363,364,365,366],"take":"subject1/o1/5/cam4","frame_ids":[359,360,361,362,363,364,365,366]} +{"filtered_tile_id":"5bb95ab42f31ddc9a326857e:16","filtered_window_id":"5bb95ab42f31ddc9a326857e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bb95ab42f31ddc9a326857e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[367,368,369,370,371,372,373,374],"take":"subject1/o1/5/cam4","frame_ids":[367,368,369,370,371,372,373,374]} +{"filtered_tile_id":"5bb95ab42f31ddc9a326857e:24","filtered_window_id":"5bb95ab42f31ddc9a326857e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bb95ab42f31ddc9a326857e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[375,376,377,378,379,380,381,382],"take":"subject1/o1/5/cam4","frame_ids":[375,376,377,378,379,380,381,382]} +{"filtered_tile_id":"5bb95ab42f31ddc9a326857e:32","filtered_window_id":"5bb95ab42f31ddc9a326857e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bb95ab42f31ddc9a326857e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject1/o1/5/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"5bb95ab42f31ddc9a326857e:40","filtered_window_id":"5bb95ab42f31ddc9a326857e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bb95ab42f31ddc9a326857e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject1/o1/5/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"5bb95ab42f31ddc9a326857e:48","filtered_window_id":"5bb95ab42f31ddc9a326857e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bb95ab42f31ddc9a326857e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject1/o1/5/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"5bb95ab42f31ddc9a326857e:52","filtered_window_id":"5bb95ab42f31ddc9a326857e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bb95ab42f31ddc9a326857e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject1/o1/5/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"5bdd93373543a3bfd967f26e:0","filtered_window_id":"5bdd93373543a3bfd967f26e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bdd93373543a3bfd967f26e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[702,703,704,705,706,707,708,709],"take":"subject1/h1/7/cam4","frame_ids":[702,703,704,705,706,707,708,709]} +{"filtered_tile_id":"5bdd93373543a3bfd967f26e:8","filtered_window_id":"5bdd93373543a3bfd967f26e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bdd93373543a3bfd967f26e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[710,711,712,713,714,715,716,717],"take":"subject1/h1/7/cam4","frame_ids":[710,711,712,713,714,715,716,717]} +{"filtered_tile_id":"5bdd93373543a3bfd967f26e:16","filtered_window_id":"5bdd93373543a3bfd967f26e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bdd93373543a3bfd967f26e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[718,719,720,721,722,723,724,725],"take":"subject1/h1/7/cam4","frame_ids":[718,719,720,721,722,723,724,725]} +{"filtered_tile_id":"5bdd93373543a3bfd967f26e:24","filtered_window_id":"5bdd93373543a3bfd967f26e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bdd93373543a3bfd967f26e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[726,727,728,729,730,731,732,733],"take":"subject1/h1/7/cam4","frame_ids":[726,727,728,729,730,731,732,733]} +{"filtered_tile_id":"5bdd93373543a3bfd967f26e:32","filtered_window_id":"5bdd93373543a3bfd967f26e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bdd93373543a3bfd967f26e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[734,735,736,737,738,739,740,741],"take":"subject1/h1/7/cam4","frame_ids":[734,735,736,737,738,739,740,741]} +{"filtered_tile_id":"5bdd93373543a3bfd967f26e:40","filtered_window_id":"5bdd93373543a3bfd967f26e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bdd93373543a3bfd967f26e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[742,743,744,745,746,747,748,749],"take":"subject1/h1/7/cam4","frame_ids":[742,743,744,745,746,747,748,749]} +{"filtered_tile_id":"5bdd93373543a3bfd967f26e:48","filtered_window_id":"5bdd93373543a3bfd967f26e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bdd93373543a3bfd967f26e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[750,751,752,753,754,755,756,757],"take":"subject1/h1/7/cam4","frame_ids":[750,751,752,753,754,755,756,757]} +{"filtered_tile_id":"5bdd93373543a3bfd967f26e:52","filtered_window_id":"5bdd93373543a3bfd967f26e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bdd93373543a3bfd967f26e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[754,755,756,757,758,759,760,761],"take":"subject1/h1/7/cam4","frame_ids":[754,755,756,757,758,759,760,761]} +{"filtered_tile_id":"5be4044d97fbb8ffcbef9380:0","filtered_window_id":"5be4044d97fbb8ffcbef9380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be4044d97fbb8ffcbef9380/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject1/h1/5/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"5be4044d97fbb8ffcbef9380:8","filtered_window_id":"5be4044d97fbb8ffcbef9380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be4044d97fbb8ffcbef9380/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject1/h1/5/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"5be4044d97fbb8ffcbef9380:16","filtered_window_id":"5be4044d97fbb8ffcbef9380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be4044d97fbb8ffcbef9380/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject1/h1/5/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"5be4044d97fbb8ffcbef9380:17","filtered_window_id":"5be4044d97fbb8ffcbef9380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be4044d97fbb8ffcbef9380/native_gt.npz","filtered_start_offset":17,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject1/h1/5/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"5be40b2e1da79fa454731380:0","filtered_window_id":"5be40b2e1da79fa454731380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be40b2e1da79fa454731380/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[587,588,589,590,591,592,593,594],"take":"subject1/o2/1/cam4","frame_ids":[587,588,589,590,591,592,593,594]} +{"filtered_tile_id":"5be40b2e1da79fa454731380:8","filtered_window_id":"5be40b2e1da79fa454731380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be40b2e1da79fa454731380/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[595,596,597,598,599,600,601,602],"take":"subject1/o2/1/cam4","frame_ids":[595,596,597,598,599,600,601,602]} +{"filtered_tile_id":"5be40b2e1da79fa454731380:16","filtered_window_id":"5be40b2e1da79fa454731380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be40b2e1da79fa454731380/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[603,604,605,606,607,608,609,610],"take":"subject1/o2/1/cam4","frame_ids":[603,604,605,606,607,608,609,610]} +{"filtered_tile_id":"5be40b2e1da79fa454731380:24","filtered_window_id":"5be40b2e1da79fa454731380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be40b2e1da79fa454731380/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[611,612,613,614,615,616,617,618],"take":"subject1/o2/1/cam4","frame_ids":[611,612,613,614,615,616,617,618]} +{"filtered_tile_id":"5be40b2e1da79fa454731380:32","filtered_window_id":"5be40b2e1da79fa454731380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be40b2e1da79fa454731380/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[619,620,621,622,623,624,625,626],"take":"subject1/o2/1/cam4","frame_ids":[619,620,621,622,623,624,625,626]} +{"filtered_tile_id":"5be40b2e1da79fa454731380:40","filtered_window_id":"5be40b2e1da79fa454731380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be40b2e1da79fa454731380/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[627,628,629,630,631,632,633,634],"take":"subject1/o2/1/cam4","frame_ids":[627,628,629,630,631,632,633,634]} +{"filtered_tile_id":"5be40b2e1da79fa454731380:48","filtered_window_id":"5be40b2e1da79fa454731380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be40b2e1da79fa454731380/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[635,636,637,638,639,640,641,642],"take":"subject1/o2/1/cam4","frame_ids":[635,636,637,638,639,640,641,642]} +{"filtered_tile_id":"5be40b2e1da79fa454731380:52","filtered_window_id":"5be40b2e1da79fa454731380","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5be40b2e1da79fa454731380/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[639,640,641,642,643,644,645,646],"take":"subject1/o2/1/cam4","frame_ids":[639,640,641,642,643,644,645,646]} +{"filtered_tile_id":"5bf396082e3bb071bf3b1299:0","filtered_window_id":"5bf396082e3bb071bf3b1299","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bf396082e3bb071bf3b1299/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject1/o2/3/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"5bf396082e3bb071bf3b1299:8","filtered_window_id":"5bf396082e3bb071bf3b1299","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bf396082e3bb071bf3b1299/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject1/o2/3/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"5bf396082e3bb071bf3b1299:16","filtered_window_id":"5bf396082e3bb071bf3b1299","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bf396082e3bb071bf3b1299/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject1/o2/3/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"5bf396082e3bb071bf3b1299:23","filtered_window_id":"5bf396082e3bb071bf3b1299","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5bf396082e3bb071bf3b1299/native_gt.npz","filtered_start_offset":23,"expected_frame_ids":[271,272,273,274,275,276,277,278],"take":"subject1/o2/3/cam4","frame_ids":[271,272,273,274,275,276,277,278]} +{"filtered_tile_id":"5ca4484b29a3fa1cd1b96598:0","filtered_window_id":"5ca4484b29a3fa1cd1b96598","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ca4484b29a3fa1cd1b96598/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[348,349,350,351,352,353,354,355],"take":"subject2/k1/5/cam4","frame_ids":[348,349,350,351,352,353,354,355]} +{"filtered_tile_id":"5ca4484b29a3fa1cd1b96598:8","filtered_window_id":"5ca4484b29a3fa1cd1b96598","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ca4484b29a3fa1cd1b96598/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[356,357,358,359,360,361,362,363],"take":"subject2/k1/5/cam4","frame_ids":[356,357,358,359,360,361,362,363]} +{"filtered_tile_id":"5ca4484b29a3fa1cd1b96598:16","filtered_window_id":"5ca4484b29a3fa1cd1b96598","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ca4484b29a3fa1cd1b96598/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject2/k1/5/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"5ca4484b29a3fa1cd1b96598:22","filtered_window_id":"5ca4484b29a3fa1cd1b96598","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ca4484b29a3fa1cd1b96598/native_gt.npz","filtered_start_offset":22,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject2/k1/5/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"5ccc509914841740262a0ef4:0","filtered_window_id":"5ccc509914841740262a0ef4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ccc509914841740262a0ef4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject1/o2/3/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"5ccc509914841740262a0ef4:8","filtered_window_id":"5ccc509914841740262a0ef4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ccc509914841740262a0ef4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject1/o2/3/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"5ccc509914841740262a0ef4:16","filtered_window_id":"5ccc509914841740262a0ef4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ccc509914841740262a0ef4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject1/o2/3/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"5ccc509914841740262a0ef4:24","filtered_window_id":"5ccc509914841740262a0ef4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ccc509914841740262a0ef4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject1/o2/3/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"5ccc509914841740262a0ef4:32","filtered_window_id":"5ccc509914841740262a0ef4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ccc509914841740262a0ef4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject1/o2/3/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"5ccc509914841740262a0ef4:40","filtered_window_id":"5ccc509914841740262a0ef4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ccc509914841740262a0ef4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject1/o2/3/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"5ccc509914841740262a0ef4:42","filtered_window_id":"5ccc509914841740262a0ef4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ccc509914841740262a0ef4/native_gt.npz","filtered_start_offset":42,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject1/o2/3/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"5d0533fd83b366df21eab8a7:0","filtered_window_id":"5d0533fd83b366df21eab8a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d0533fd83b366df21eab8a7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject3/k1/4/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"5d0533fd83b366df21eab8a7:8","filtered_window_id":"5d0533fd83b366df21eab8a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d0533fd83b366df21eab8a7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[175,176,177,178,179,180,181,182],"take":"subject3/k1/4/cam4","frame_ids":[175,176,177,178,179,180,181,182]} +{"filtered_tile_id":"5d0533fd83b366df21eab8a7:16","filtered_window_id":"5d0533fd83b366df21eab8a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d0533fd83b366df21eab8a7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[183,184,185,186,187,188,189,190],"take":"subject3/k1/4/cam4","frame_ids":[183,184,185,186,187,188,189,190]} +{"filtered_tile_id":"5d0533fd83b366df21eab8a7:24","filtered_window_id":"5d0533fd83b366df21eab8a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d0533fd83b366df21eab8a7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[191,192,193,194,195,196,197,198],"take":"subject3/k1/4/cam4","frame_ids":[191,192,193,194,195,196,197,198]} +{"filtered_tile_id":"5d0533fd83b366df21eab8a7:32","filtered_window_id":"5d0533fd83b366df21eab8a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d0533fd83b366df21eab8a7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject3/k1/4/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"5d0533fd83b366df21eab8a7:40","filtered_window_id":"5d0533fd83b366df21eab8a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d0533fd83b366df21eab8a7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[207,208,209,210,211,212,213,214],"take":"subject3/k1/4/cam4","frame_ids":[207,208,209,210,211,212,213,214]} +{"filtered_tile_id":"5d7c1d7c3b7e4f2abe4ee70d:0","filtered_window_id":"5d7c1d7c3b7e4f2abe4ee70d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d7c1d7c3b7e4f2abe4ee70d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject3/k1/0/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"5d7c1d7c3b7e4f2abe4ee70d:8","filtered_window_id":"5d7c1d7c3b7e4f2abe4ee70d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d7c1d7c3b7e4f2abe4ee70d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject3/k1/0/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"5d7c1d7c3b7e4f2abe4ee70d:16","filtered_window_id":"5d7c1d7c3b7e4f2abe4ee70d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d7c1d7c3b7e4f2abe4ee70d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject3/k1/0/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"5d7c1d7c3b7e4f2abe4ee70d:24","filtered_window_id":"5d7c1d7c3b7e4f2abe4ee70d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d7c1d7c3b7e4f2abe4ee70d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[170,171,172,173,174,175,176,177],"take":"subject3/k1/0/cam4","frame_ids":[170,171,172,173,174,175,176,177]} +{"filtered_tile_id":"5d7c1d7c3b7e4f2abe4ee70d:32","filtered_window_id":"5d7c1d7c3b7e4f2abe4ee70d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d7c1d7c3b7e4f2abe4ee70d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[178,179,180,181,182,183,184,185],"take":"subject3/k1/0/cam4","frame_ids":[178,179,180,181,182,183,184,185]} +{"filtered_tile_id":"5d7c1d7c3b7e4f2abe4ee70d:40","filtered_window_id":"5d7c1d7c3b7e4f2abe4ee70d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d7c1d7c3b7e4f2abe4ee70d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[186,187,188,189,190,191,192,193],"take":"subject3/k1/0/cam4","frame_ids":[186,187,188,189,190,191,192,193]} +{"filtered_tile_id":"5d7c1d7c3b7e4f2abe4ee70d:48","filtered_window_id":"5d7c1d7c3b7e4f2abe4ee70d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d7c1d7c3b7e4f2abe4ee70d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[194,195,196,197,198,199,200,201],"take":"subject3/k1/0/cam4","frame_ids":[194,195,196,197,198,199,200,201]} +{"filtered_tile_id":"5d7c1d7c3b7e4f2abe4ee70d:52","filtered_window_id":"5d7c1d7c3b7e4f2abe4ee70d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d7c1d7c3b7e4f2abe4ee70d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject3/k1/0/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"5d86d09f0ff75d4803cdd6f8:0","filtered_window_id":"5d86d09f0ff75d4803cdd6f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d86d09f0ff75d4803cdd6f8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject1/h1/7/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"5d86d09f0ff75d4803cdd6f8:8","filtered_window_id":"5d86d09f0ff75d4803cdd6f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d86d09f0ff75d4803cdd6f8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject1/h1/7/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"5d86d09f0ff75d4803cdd6f8:16","filtered_window_id":"5d86d09f0ff75d4803cdd6f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d86d09f0ff75d4803cdd6f8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject1/h1/7/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"5d86d09f0ff75d4803cdd6f8:24","filtered_window_id":"5d86d09f0ff75d4803cdd6f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d86d09f0ff75d4803cdd6f8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject1/h1/7/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"5d86d09f0ff75d4803cdd6f8:32","filtered_window_id":"5d86d09f0ff75d4803cdd6f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d86d09f0ff75d4803cdd6f8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject1/h1/7/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"5d86d09f0ff75d4803cdd6f8:40","filtered_window_id":"5d86d09f0ff75d4803cdd6f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d86d09f0ff75d4803cdd6f8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject1/h1/7/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"5d86d09f0ff75d4803cdd6f8:48","filtered_window_id":"5d86d09f0ff75d4803cdd6f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d86d09f0ff75d4803cdd6f8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject1/h1/7/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"5d86d09f0ff75d4803cdd6f8:52","filtered_window_id":"5d86d09f0ff75d4803cdd6f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d86d09f0ff75d4803cdd6f8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject1/h1/7/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"5d87732e10bc3e899cfb0425:0","filtered_window_id":"5d87732e10bc3e899cfb0425","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d87732e10bc3e899cfb0425/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[142,143,144,145,146,147,148,149],"take":"subject2/k1/1/cam4","frame_ids":[142,143,144,145,146,147,148,149]} +{"filtered_tile_id":"5d87732e10bc3e899cfb0425:8","filtered_window_id":"5d87732e10bc3e899cfb0425","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d87732e10bc3e899cfb0425/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[150,151,152,153,154,155,156,157],"take":"subject2/k1/1/cam4","frame_ids":[150,151,152,153,154,155,156,157]} +{"filtered_tile_id":"5d87732e10bc3e899cfb0425:16","filtered_window_id":"5d87732e10bc3e899cfb0425","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d87732e10bc3e899cfb0425/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[158,159,160,161,162,163,164,165],"take":"subject2/k1/1/cam4","frame_ids":[158,159,160,161,162,163,164,165]} +{"filtered_tile_id":"5d87732e10bc3e899cfb0425:24","filtered_window_id":"5d87732e10bc3e899cfb0425","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d87732e10bc3e899cfb0425/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject2/k1/1/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"5d87732e10bc3e899cfb0425:32","filtered_window_id":"5d87732e10bc3e899cfb0425","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d87732e10bc3e899cfb0425/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject2/k1/1/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"5d87732e10bc3e899cfb0425:40","filtered_window_id":"5d87732e10bc3e899cfb0425","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d87732e10bc3e899cfb0425/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject2/k1/1/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"5d87732e10bc3e899cfb0425:48","filtered_window_id":"5d87732e10bc3e899cfb0425","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d87732e10bc3e899cfb0425/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject2/k1/1/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"5d87732e10bc3e899cfb0425:52","filtered_window_id":"5d87732e10bc3e899cfb0425","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5d87732e10bc3e899cfb0425/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[194,195,196,197,198,199,200,201],"take":"subject2/k1/1/cam4","frame_ids":[194,195,196,197,198,199,200,201]} +{"filtered_tile_id":"5ddc637135960f7dfad5b340:0","filtered_window_id":"5ddc637135960f7dfad5b340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ddc637135960f7dfad5b340/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject1/k2/1/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"5ddc637135960f7dfad5b340:8","filtered_window_id":"5ddc637135960f7dfad5b340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ddc637135960f7dfad5b340/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject1/k2/1/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"5ddc637135960f7dfad5b340:16","filtered_window_id":"5ddc637135960f7dfad5b340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ddc637135960f7dfad5b340/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject1/k2/1/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"5ddc637135960f7dfad5b340:24","filtered_window_id":"5ddc637135960f7dfad5b340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ddc637135960f7dfad5b340/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject1/k2/1/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"5ddc637135960f7dfad5b340:32","filtered_window_id":"5ddc637135960f7dfad5b340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ddc637135960f7dfad5b340/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject1/k2/1/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"5ddc637135960f7dfad5b340:40","filtered_window_id":"5ddc637135960f7dfad5b340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ddc637135960f7dfad5b340/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject1/k2/1/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"5ddc637135960f7dfad5b340:48","filtered_window_id":"5ddc637135960f7dfad5b340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ddc637135960f7dfad5b340/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject1/k2/1/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"5ddc637135960f7dfad5b340:52","filtered_window_id":"5ddc637135960f7dfad5b340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ddc637135960f7dfad5b340/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject1/k2/1/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"5e008820e694d3842687674b:0","filtered_window_id":"5e008820e694d3842687674b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e008820e694d3842687674b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[336,337,338,339,340,341,342,343],"take":"subject1/o2/0/cam4","frame_ids":[336,337,338,339,340,341,342,343]} +{"filtered_tile_id":"5e008820e694d3842687674b:8","filtered_window_id":"5e008820e694d3842687674b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e008820e694d3842687674b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[344,345,346,347,348,349,350,351],"take":"subject1/o2/0/cam4","frame_ids":[344,345,346,347,348,349,350,351]} +{"filtered_tile_id":"5e008820e694d3842687674b:16","filtered_window_id":"5e008820e694d3842687674b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e008820e694d3842687674b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject1/o2/0/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"5e008820e694d3842687674b:24","filtered_window_id":"5e008820e694d3842687674b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e008820e694d3842687674b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject1/o2/0/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"5e008820e694d3842687674b:32","filtered_window_id":"5e008820e694d3842687674b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e008820e694d3842687674b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject1/o2/0/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"5e008820e694d3842687674b:40","filtered_window_id":"5e008820e694d3842687674b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e008820e694d3842687674b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[376,377,378,379,380,381,382,383],"take":"subject1/o2/0/cam4","frame_ids":[376,377,378,379,380,381,382,383]} +{"filtered_tile_id":"5e008820e694d3842687674b:48","filtered_window_id":"5e008820e694d3842687674b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e008820e694d3842687674b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject1/o2/0/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"5e008820e694d3842687674b:52","filtered_window_id":"5e008820e694d3842687674b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e008820e694d3842687674b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject1/o2/0/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"5e7780f38a270bef921736f8:0","filtered_window_id":"5e7780f38a270bef921736f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e7780f38a270bef921736f8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h1/6/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"5e7780f38a270bef921736f8:8","filtered_window_id":"5e7780f38a270bef921736f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e7780f38a270bef921736f8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h1/6/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"5e7780f38a270bef921736f8:14","filtered_window_id":"5e7780f38a270bef921736f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e7780f38a270bef921736f8/native_gt.npz","filtered_start_offset":14,"expected_frame_ids":[14,15,16,17,18,19,20,21],"take":"subject1/h1/6/cam4","frame_ids":[14,15,16,17,18,19,20,21]} +{"filtered_tile_id":"5e9220acb66759aa10973dda:0","filtered_window_id":"5e9220acb66759aa10973dda","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e9220acb66759aa10973dda/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[637,638,639,640,641,642,643,644],"take":"subject2/o1/4/cam4","frame_ids":[637,638,639,640,641,642,643,644]} +{"filtered_tile_id":"5e9220acb66759aa10973dda:8","filtered_window_id":"5e9220acb66759aa10973dda","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e9220acb66759aa10973dda/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[645,646,647,648,649,650,651,652],"take":"subject2/o1/4/cam4","frame_ids":[645,646,647,648,649,650,651,652]} +{"filtered_tile_id":"5e9220acb66759aa10973dda:16","filtered_window_id":"5e9220acb66759aa10973dda","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e9220acb66759aa10973dda/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[653,654,655,656,657,658,659,660],"take":"subject2/o1/4/cam4","frame_ids":[653,654,655,656,657,658,659,660]} +{"filtered_tile_id":"5e9220acb66759aa10973dda:24","filtered_window_id":"5e9220acb66759aa10973dda","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e9220acb66759aa10973dda/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[661,662,663,664,665,666,667,668],"take":"subject2/o1/4/cam4","frame_ids":[661,662,663,664,665,666,667,668]} +{"filtered_tile_id":"5e9220acb66759aa10973dda:32","filtered_window_id":"5e9220acb66759aa10973dda","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e9220acb66759aa10973dda/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[669,670,671,672,673,674,675,676],"take":"subject2/o1/4/cam4","frame_ids":[669,670,671,672,673,674,675,676]} +{"filtered_tile_id":"5e9220acb66759aa10973dda:40","filtered_window_id":"5e9220acb66759aa10973dda","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e9220acb66759aa10973dda/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[677,678,679,680,681,682,683,684],"take":"subject2/o1/4/cam4","frame_ids":[677,678,679,680,681,682,683,684]} +{"filtered_tile_id":"5e9220acb66759aa10973dda:48","filtered_window_id":"5e9220acb66759aa10973dda","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e9220acb66759aa10973dda/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[685,686,687,688,689,690,691,692],"take":"subject2/o1/4/cam4","frame_ids":[685,686,687,688,689,690,691,692]} +{"filtered_tile_id":"5e9220acb66759aa10973dda:52","filtered_window_id":"5e9220acb66759aa10973dda","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5e9220acb66759aa10973dda/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[689,690,691,692,693,694,695,696],"take":"subject2/o1/4/cam4","frame_ids":[689,690,691,692,693,694,695,696]} +{"filtered_tile_id":"5ecf9497b33537ffe309de22:0","filtered_window_id":"5ecf9497b33537ffe309de22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ecf9497b33537ffe309de22/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject1/h1/5/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"5ecf9497b33537ffe309de22:8","filtered_window_id":"5ecf9497b33537ffe309de22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ecf9497b33537ffe309de22/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject1/h1/5/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"5ecf9497b33537ffe309de22:10","filtered_window_id":"5ecf9497b33537ffe309de22","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ecf9497b33537ffe309de22/native_gt.npz","filtered_start_offset":10,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject1/h1/5/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"5f04bc17101aa921c531d598:0","filtered_window_id":"5f04bc17101aa921c531d598","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5f04bc17101aa921c531d598/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject3/h2/0/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"5f04bc17101aa921c531d598:8","filtered_window_id":"5f04bc17101aa921c531d598","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5f04bc17101aa921c531d598/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject3/h2/0/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"5f04bc17101aa921c531d598:16","filtered_window_id":"5f04bc17101aa921c531d598","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5f04bc17101aa921c531d598/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject3/h2/0/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"5f04bc17101aa921c531d598:22","filtered_window_id":"5f04bc17101aa921c531d598","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5f04bc17101aa921c531d598/native_gt.npz","filtered_start_offset":22,"expected_frame_ids":[570,571,572,573,574,575,576,577],"take":"subject3/h2/0/cam4","frame_ids":[570,571,572,573,574,575,576,577]} +{"filtered_tile_id":"5fac7542ee9e2615f388fba5:0","filtered_window_id":"5fac7542ee9e2615f388fba5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fac7542ee9e2615f388fba5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[65,66,67,68,69,70,71,72],"take":"subject2/k1/3/cam4","frame_ids":[65,66,67,68,69,70,71,72]} +{"filtered_tile_id":"5fb92cf073880bf5e200df11:0","filtered_window_id":"5fb92cf073880bf5e200df11","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fb92cf073880bf5e200df11/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject3/h1/5/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"5fb92cf073880bf5e200df11:8","filtered_window_id":"5fb92cf073880bf5e200df11","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fb92cf073880bf5e200df11/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject3/h1/5/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"5fb92cf073880bf5e200df11:16","filtered_window_id":"5fb92cf073880bf5e200df11","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fb92cf073880bf5e200df11/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[53,54,55,56,57,58,59,60],"take":"subject3/h1/5/cam4","frame_ids":[53,54,55,56,57,58,59,60]} +{"filtered_tile_id":"5fb92cf073880bf5e200df11:24","filtered_window_id":"5fb92cf073880bf5e200df11","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fb92cf073880bf5e200df11/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[61,62,63,64,65,66,67,68],"take":"subject3/h1/5/cam4","frame_ids":[61,62,63,64,65,66,67,68]} +{"filtered_tile_id":"5fb92cf073880bf5e200df11:32","filtered_window_id":"5fb92cf073880bf5e200df11","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fb92cf073880bf5e200df11/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject3/h1/5/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"5fb92cf073880bf5e200df11:40","filtered_window_id":"5fb92cf073880bf5e200df11","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fb92cf073880bf5e200df11/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[77,78,79,80,81,82,83,84],"take":"subject3/h1/5/cam4","frame_ids":[77,78,79,80,81,82,83,84]} +{"filtered_tile_id":"5fb92cf073880bf5e200df11:48","filtered_window_id":"5fb92cf073880bf5e200df11","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fb92cf073880bf5e200df11/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject3/h1/5/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"5fb92cf073880bf5e200df11:52","filtered_window_id":"5fb92cf073880bf5e200df11","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fb92cf073880bf5e200df11/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[89,90,91,92,93,94,95,96],"take":"subject3/h1/5/cam4","frame_ids":[89,90,91,92,93,94,95,96]} +{"filtered_tile_id":"5fcd2eb7c66408a5888cea5e:0","filtered_window_id":"5fcd2eb7c66408a5888cea5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fcd2eb7c66408a5888cea5e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject2/h1/6/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"5fcd2eb7c66408a5888cea5e:8","filtered_window_id":"5fcd2eb7c66408a5888cea5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fcd2eb7c66408a5888cea5e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject2/h1/6/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"5fcd2eb7c66408a5888cea5e:16","filtered_window_id":"5fcd2eb7c66408a5888cea5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fcd2eb7c66408a5888cea5e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject2/h1/6/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"5fcd2eb7c66408a5888cea5e:24","filtered_window_id":"5fcd2eb7c66408a5888cea5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fcd2eb7c66408a5888cea5e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject2/h1/6/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"5fcd2eb7c66408a5888cea5e:32","filtered_window_id":"5fcd2eb7c66408a5888cea5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fcd2eb7c66408a5888cea5e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject2/h1/6/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"5fcd2eb7c66408a5888cea5e:40","filtered_window_id":"5fcd2eb7c66408a5888cea5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fcd2eb7c66408a5888cea5e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject2/h1/6/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"5fcd2eb7c66408a5888cea5e:48","filtered_window_id":"5fcd2eb7c66408a5888cea5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fcd2eb7c66408a5888cea5e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject2/h1/6/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"5fcd2eb7c66408a5888cea5e:52","filtered_window_id":"5fcd2eb7c66408a5888cea5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fcd2eb7c66408a5888cea5e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[224,225,226,227,228,229,230,231],"take":"subject2/h1/6/cam4","frame_ids":[224,225,226,227,228,229,230,231]} +{"filtered_tile_id":"5fd4a944ea78dc0d54397d97:0","filtered_window_id":"5fd4a944ea78dc0d54397d97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fd4a944ea78dc0d54397d97/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject3/h2/6/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"5fd4a944ea78dc0d54397d97:8","filtered_window_id":"5fd4a944ea78dc0d54397d97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fd4a944ea78dc0d54397d97/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject3/h2/6/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"5fd4a944ea78dc0d54397d97:16","filtered_window_id":"5fd4a944ea78dc0d54397d97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fd4a944ea78dc0d54397d97/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject3/h2/6/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"5fd4a944ea78dc0d54397d97:24","filtered_window_id":"5fd4a944ea78dc0d54397d97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fd4a944ea78dc0d54397d97/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject3/h2/6/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"5fd4a944ea78dc0d54397d97:26","filtered_window_id":"5fd4a944ea78dc0d54397d97","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5fd4a944ea78dc0d54397d97/native_gt.npz","filtered_start_offset":26,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject3/h2/6/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"5ffa408be756368d3e92aa05:0","filtered_window_id":"5ffa408be756368d3e92aa05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ffa408be756368d3e92aa05/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject2/k2/2/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"5ffa408be756368d3e92aa05:8","filtered_window_id":"5ffa408be756368d3e92aa05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ffa408be756368d3e92aa05/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject2/k2/2/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"5ffa408be756368d3e92aa05:16","filtered_window_id":"5ffa408be756368d3e92aa05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ffa408be756368d3e92aa05/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[255,256,257,258,259,260,261,262],"take":"subject2/k2/2/cam4","frame_ids":[255,256,257,258,259,260,261,262]} +{"filtered_tile_id":"5ffa408be756368d3e92aa05:24","filtered_window_id":"5ffa408be756368d3e92aa05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ffa408be756368d3e92aa05/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject2/k2/2/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"5ffa408be756368d3e92aa05:30","filtered_window_id":"5ffa408be756368d3e92aa05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/5ffa408be756368d3e92aa05/native_gt.npz","filtered_start_offset":30,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject2/k2/2/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"60360cd152746f9d1246d923:0","filtered_window_id":"60360cd152746f9d1246d923","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60360cd152746f9d1246d923/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject1/o1/6/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"60360cd152746f9d1246d923:8","filtered_window_id":"60360cd152746f9d1246d923","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60360cd152746f9d1246d923/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject1/o1/6/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"60360cd152746f9d1246d923:16","filtered_window_id":"60360cd152746f9d1246d923","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60360cd152746f9d1246d923/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/o1/6/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"60360cd152746f9d1246d923:24","filtered_window_id":"60360cd152746f9d1246d923","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60360cd152746f9d1246d923/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject1/o1/6/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"60360cd152746f9d1246d923:32","filtered_window_id":"60360cd152746f9d1246d923","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60360cd152746f9d1246d923/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject1/o1/6/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"60360cd152746f9d1246d923:34","filtered_window_id":"60360cd152746f9d1246d923","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60360cd152746f9d1246d923/native_gt.npz","filtered_start_offset":34,"expected_frame_ids":[126,127,128,129,130,131,132,133],"take":"subject1/o1/6/cam4","frame_ids":[126,127,128,129,130,131,132,133]} +{"filtered_tile_id":"6048b3817b6b1e01f504f717:0","filtered_window_id":"6048b3817b6b1e01f504f717","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6048b3817b6b1e01f504f717/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[71,72,73,74,75,76,77,78],"take":"subject2/o1/5/cam4","frame_ids":[71,72,73,74,75,76,77,78]} +{"filtered_tile_id":"6048b3817b6b1e01f504f717:8","filtered_window_id":"6048b3817b6b1e01f504f717","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6048b3817b6b1e01f504f717/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[79,80,81,82,83,84,85,86],"take":"subject2/o1/5/cam4","frame_ids":[79,80,81,82,83,84,85,86]} +{"filtered_tile_id":"6048b3817b6b1e01f504f717:16","filtered_window_id":"6048b3817b6b1e01f504f717","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6048b3817b6b1e01f504f717/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[87,88,89,90,91,92,93,94],"take":"subject2/o1/5/cam4","frame_ids":[87,88,89,90,91,92,93,94]} +{"filtered_tile_id":"6048b3817b6b1e01f504f717:24","filtered_window_id":"6048b3817b6b1e01f504f717","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6048b3817b6b1e01f504f717/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[95,96,97,98,99,100,101,102],"take":"subject2/o1/5/cam4","frame_ids":[95,96,97,98,99,100,101,102]} +{"filtered_tile_id":"6048b3817b6b1e01f504f717:32","filtered_window_id":"6048b3817b6b1e01f504f717","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6048b3817b6b1e01f504f717/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[103,104,105,106,107,108,109,110],"take":"subject2/o1/5/cam4","frame_ids":[103,104,105,106,107,108,109,110]} +{"filtered_tile_id":"6048b3817b6b1e01f504f717:40","filtered_window_id":"6048b3817b6b1e01f504f717","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6048b3817b6b1e01f504f717/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject2/o1/5/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"6048b3817b6b1e01f504f717:48","filtered_window_id":"6048b3817b6b1e01f504f717","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6048b3817b6b1e01f504f717/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject2/o1/5/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"6048b3817b6b1e01f504f717:52","filtered_window_id":"6048b3817b6b1e01f504f717","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6048b3817b6b1e01f504f717/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject2/o1/5/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"606ca5f5ee54e34da08c7a51:0","filtered_window_id":"606ca5f5ee54e34da08c7a51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/606ca5f5ee54e34da08c7a51/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[26,27,28,29,30,31,32,33],"take":"subject2/k2/2/cam4","frame_ids":[26,27,28,29,30,31,32,33]} +{"filtered_tile_id":"606ca5f5ee54e34da08c7a51:8","filtered_window_id":"606ca5f5ee54e34da08c7a51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/606ca5f5ee54e34da08c7a51/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[34,35,36,37,38,39,40,41],"take":"subject2/k2/2/cam4","frame_ids":[34,35,36,37,38,39,40,41]} +{"filtered_tile_id":"606ca5f5ee54e34da08c7a51:16","filtered_window_id":"606ca5f5ee54e34da08c7a51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/606ca5f5ee54e34da08c7a51/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[42,43,44,45,46,47,48,49],"take":"subject2/k2/2/cam4","frame_ids":[42,43,44,45,46,47,48,49]} +{"filtered_tile_id":"606ca5f5ee54e34da08c7a51:24","filtered_window_id":"606ca5f5ee54e34da08c7a51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/606ca5f5ee54e34da08c7a51/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[50,51,52,53,54,55,56,57],"take":"subject2/k2/2/cam4","frame_ids":[50,51,52,53,54,55,56,57]} +{"filtered_tile_id":"606ca5f5ee54e34da08c7a51:32","filtered_window_id":"606ca5f5ee54e34da08c7a51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/606ca5f5ee54e34da08c7a51/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[58,59,60,61,62,63,64,65],"take":"subject2/k2/2/cam4","frame_ids":[58,59,60,61,62,63,64,65]} +{"filtered_tile_id":"606ca5f5ee54e34da08c7a51:40","filtered_window_id":"606ca5f5ee54e34da08c7a51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/606ca5f5ee54e34da08c7a51/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[66,67,68,69,70,71,72,73],"take":"subject2/k2/2/cam4","frame_ids":[66,67,68,69,70,71,72,73]} +{"filtered_tile_id":"606ca5f5ee54e34da08c7a51:48","filtered_window_id":"606ca5f5ee54e34da08c7a51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/606ca5f5ee54e34da08c7a51/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[74,75,76,77,78,79,80,81],"take":"subject2/k2/2/cam4","frame_ids":[74,75,76,77,78,79,80,81]} +{"filtered_tile_id":"606ca5f5ee54e34da08c7a51:52","filtered_window_id":"606ca5f5ee54e34da08c7a51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/606ca5f5ee54e34da08c7a51/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject2/k2/2/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"609c3e4a77d0d2147e711ab3:0","filtered_window_id":"609c3e4a77d0d2147e711ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/609c3e4a77d0d2147e711ab3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[448,449,450,451,452,453,454,455],"take":"subject2/h2/4/cam4","frame_ids":[448,449,450,451,452,453,454,455]} +{"filtered_tile_id":"609c3e4a77d0d2147e711ab3:8","filtered_window_id":"609c3e4a77d0d2147e711ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/609c3e4a77d0d2147e711ab3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[456,457,458,459,460,461,462,463],"take":"subject2/h2/4/cam4","frame_ids":[456,457,458,459,460,461,462,463]} +{"filtered_tile_id":"609c3e4a77d0d2147e711ab3:16","filtered_window_id":"609c3e4a77d0d2147e711ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/609c3e4a77d0d2147e711ab3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[464,465,466,467,468,469,470,471],"take":"subject2/h2/4/cam4","frame_ids":[464,465,466,467,468,469,470,471]} +{"filtered_tile_id":"609c3e4a77d0d2147e711ab3:24","filtered_window_id":"609c3e4a77d0d2147e711ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/609c3e4a77d0d2147e711ab3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject2/h2/4/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"609c3e4a77d0d2147e711ab3:32","filtered_window_id":"609c3e4a77d0d2147e711ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/609c3e4a77d0d2147e711ab3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject2/h2/4/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"609c3e4a77d0d2147e711ab3:40","filtered_window_id":"609c3e4a77d0d2147e711ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/609c3e4a77d0d2147e711ab3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject2/h2/4/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"609c3e4a77d0d2147e711ab3:48","filtered_window_id":"609c3e4a77d0d2147e711ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/609c3e4a77d0d2147e711ab3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject2/h2/4/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"609c3e4a77d0d2147e711ab3:52","filtered_window_id":"609c3e4a77d0d2147e711ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/609c3e4a77d0d2147e711ab3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[500,501,502,503,504,505,506,507],"take":"subject2/h2/4/cam4","frame_ids":[500,501,502,503,504,505,506,507]} +{"filtered_tile_id":"60a93b9911200a3b00cd4de8:0","filtered_window_id":"60a93b9911200a3b00cd4de8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60a93b9911200a3b00cd4de8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[202,203,204,205,206,207,208,209],"take":"subject1/o2/6/cam4","frame_ids":[202,203,204,205,206,207,208,209]} +{"filtered_tile_id":"60a93b9911200a3b00cd4de8:8","filtered_window_id":"60a93b9911200a3b00cd4de8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60a93b9911200a3b00cd4de8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[210,211,212,213,214,215,216,217],"take":"subject1/o2/6/cam4","frame_ids":[210,211,212,213,214,215,216,217]} +{"filtered_tile_id":"60a93b9911200a3b00cd4de8:16","filtered_window_id":"60a93b9911200a3b00cd4de8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60a93b9911200a3b00cd4de8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[218,219,220,221,222,223,224,225],"take":"subject1/o2/6/cam4","frame_ids":[218,219,220,221,222,223,224,225]} +{"filtered_tile_id":"60a93b9911200a3b00cd4de8:24","filtered_window_id":"60a93b9911200a3b00cd4de8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60a93b9911200a3b00cd4de8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject1/o2/6/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"60a93b9911200a3b00cd4de8:32","filtered_window_id":"60a93b9911200a3b00cd4de8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60a93b9911200a3b00cd4de8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject1/o2/6/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"60a93b9911200a3b00cd4de8:40","filtered_window_id":"60a93b9911200a3b00cd4de8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60a93b9911200a3b00cd4de8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject1/o2/6/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"60a93b9911200a3b00cd4de8:48","filtered_window_id":"60a93b9911200a3b00cd4de8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60a93b9911200a3b00cd4de8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject1/o2/6/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"60a93b9911200a3b00cd4de8:52","filtered_window_id":"60a93b9911200a3b00cd4de8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60a93b9911200a3b00cd4de8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject1/o2/6/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"60ad8362e9bcf33dc2c9f30b:0","filtered_window_id":"60ad8362e9bcf33dc2c9f30b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60ad8362e9bcf33dc2c9f30b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject1/k2/4/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"60ad8362e9bcf33dc2c9f30b:8","filtered_window_id":"60ad8362e9bcf33dc2c9f30b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60ad8362e9bcf33dc2c9f30b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject1/k2/4/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"60ad8362e9bcf33dc2c9f30b:16","filtered_window_id":"60ad8362e9bcf33dc2c9f30b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60ad8362e9bcf33dc2c9f30b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[376,377,378,379,380,381,382,383],"take":"subject1/k2/4/cam4","frame_ids":[376,377,378,379,380,381,382,383]} +{"filtered_tile_id":"60ad8362e9bcf33dc2c9f30b:24","filtered_window_id":"60ad8362e9bcf33dc2c9f30b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60ad8362e9bcf33dc2c9f30b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject1/k2/4/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"60ad8362e9bcf33dc2c9f30b:32","filtered_window_id":"60ad8362e9bcf33dc2c9f30b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60ad8362e9bcf33dc2c9f30b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[392,393,394,395,396,397,398,399],"take":"subject1/k2/4/cam4","frame_ids":[392,393,394,395,396,397,398,399]} +{"filtered_tile_id":"60f53f546e29779f40d502db:0","filtered_window_id":"60f53f546e29779f40d502db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60f53f546e29779f40d502db/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[118,119,120,121,122,123,124,125],"take":"subject2/h1/3/cam4","frame_ids":[118,119,120,121,122,123,124,125]} +{"filtered_tile_id":"60f53f546e29779f40d502db:8","filtered_window_id":"60f53f546e29779f40d502db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60f53f546e29779f40d502db/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[126,127,128,129,130,131,132,133],"take":"subject2/h1/3/cam4","frame_ids":[126,127,128,129,130,131,132,133]} +{"filtered_tile_id":"60f53f546e29779f40d502db:16","filtered_window_id":"60f53f546e29779f40d502db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60f53f546e29779f40d502db/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[134,135,136,137,138,139,140,141],"take":"subject2/h1/3/cam4","frame_ids":[134,135,136,137,138,139,140,141]} +{"filtered_tile_id":"60f53f546e29779f40d502db:24","filtered_window_id":"60f53f546e29779f40d502db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60f53f546e29779f40d502db/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[142,143,144,145,146,147,148,149],"take":"subject2/h1/3/cam4","frame_ids":[142,143,144,145,146,147,148,149]} +{"filtered_tile_id":"60f53f546e29779f40d502db:32","filtered_window_id":"60f53f546e29779f40d502db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60f53f546e29779f40d502db/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[150,151,152,153,154,155,156,157],"take":"subject2/h1/3/cam4","frame_ids":[150,151,152,153,154,155,156,157]} +{"filtered_tile_id":"60f53f546e29779f40d502db:40","filtered_window_id":"60f53f546e29779f40d502db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60f53f546e29779f40d502db/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[158,159,160,161,162,163,164,165],"take":"subject2/h1/3/cam4","frame_ids":[158,159,160,161,162,163,164,165]} +{"filtered_tile_id":"60f53f546e29779f40d502db:48","filtered_window_id":"60f53f546e29779f40d502db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60f53f546e29779f40d502db/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject2/h1/3/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"60f53f546e29779f40d502db:52","filtered_window_id":"60f53f546e29779f40d502db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/60f53f546e29779f40d502db/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[170,171,172,173,174,175,176,177],"take":"subject2/h1/3/cam4","frame_ids":[170,171,172,173,174,175,176,177]} +{"filtered_tile_id":"611957d9b592250560b844db:0","filtered_window_id":"611957d9b592250560b844db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/611957d9b592250560b844db/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject2/o2/1/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"611957d9b592250560b844db:8","filtered_window_id":"611957d9b592250560b844db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/611957d9b592250560b844db/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[423,424,425,426,427,428,429,430],"take":"subject2/o2/1/cam4","frame_ids":[423,424,425,426,427,428,429,430]} +{"filtered_tile_id":"611957d9b592250560b844db:16","filtered_window_id":"611957d9b592250560b844db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/611957d9b592250560b844db/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[431,432,433,434,435,436,437,438],"take":"subject2/o2/1/cam4","frame_ids":[431,432,433,434,435,436,437,438]} +{"filtered_tile_id":"611957d9b592250560b844db:24","filtered_window_id":"611957d9b592250560b844db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/611957d9b592250560b844db/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[439,440,441,442,443,444,445,446],"take":"subject2/o2/1/cam4","frame_ids":[439,440,441,442,443,444,445,446]} +{"filtered_tile_id":"611957d9b592250560b844db:32","filtered_window_id":"611957d9b592250560b844db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/611957d9b592250560b844db/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[447,448,449,450,451,452,453,454],"take":"subject2/o2/1/cam4","frame_ids":[447,448,449,450,451,452,453,454]} +{"filtered_tile_id":"611957d9b592250560b844db:40","filtered_window_id":"611957d9b592250560b844db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/611957d9b592250560b844db/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[455,456,457,458,459,460,461,462],"take":"subject2/o2/1/cam4","frame_ids":[455,456,457,458,459,460,461,462]} +{"filtered_tile_id":"611957d9b592250560b844db:48","filtered_window_id":"611957d9b592250560b844db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/611957d9b592250560b844db/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject2/o2/1/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"611957d9b592250560b844db:52","filtered_window_id":"611957d9b592250560b844db","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/611957d9b592250560b844db/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[467,468,469,470,471,472,473,474],"take":"subject2/o2/1/cam4","frame_ids":[467,468,469,470,471,472,473,474]} +{"filtered_tile_id":"61c8dfe584023f6647a74dcd:0","filtered_window_id":"61c8dfe584023f6647a74dcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/61c8dfe584023f6647a74dcd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[340,341,342,343,344,345,346,347],"take":"subject1/h2/1/cam4","frame_ids":[340,341,342,343,344,345,346,347]} +{"filtered_tile_id":"61c8dfe584023f6647a74dcd:8","filtered_window_id":"61c8dfe584023f6647a74dcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/61c8dfe584023f6647a74dcd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[348,349,350,351,352,353,354,355],"take":"subject1/h2/1/cam4","frame_ids":[348,349,350,351,352,353,354,355]} +{"filtered_tile_id":"61c8dfe584023f6647a74dcd:16","filtered_window_id":"61c8dfe584023f6647a74dcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/61c8dfe584023f6647a74dcd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[356,357,358,359,360,361,362,363],"take":"subject1/h2/1/cam4","frame_ids":[356,357,358,359,360,361,362,363]} +{"filtered_tile_id":"61c8dfe584023f6647a74dcd:24","filtered_window_id":"61c8dfe584023f6647a74dcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/61c8dfe584023f6647a74dcd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject1/h2/1/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"61c8dfe584023f6647a74dcd:32","filtered_window_id":"61c8dfe584023f6647a74dcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/61c8dfe584023f6647a74dcd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject1/h2/1/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"61c8dfe584023f6647a74dcd:40","filtered_window_id":"61c8dfe584023f6647a74dcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/61c8dfe584023f6647a74dcd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject1/h2/1/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"61c8dfe584023f6647a74dcd:48","filtered_window_id":"61c8dfe584023f6647a74dcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/61c8dfe584023f6647a74dcd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject1/h2/1/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"61c8dfe584023f6647a74dcd:52","filtered_window_id":"61c8dfe584023f6647a74dcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/61c8dfe584023f6647a74dcd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[392,393,394,395,396,397,398,399],"take":"subject1/h2/1/cam4","frame_ids":[392,393,394,395,396,397,398,399]} +{"filtered_tile_id":"621995fdcc9522b93d35c442:0","filtered_window_id":"621995fdcc9522b93d35c442","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/621995fdcc9522b93d35c442/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[636,637,638,639,640,641,642,643],"take":"subject3/h2/3/cam4","frame_ids":[636,637,638,639,640,641,642,643]} +{"filtered_tile_id":"621995fdcc9522b93d35c442:8","filtered_window_id":"621995fdcc9522b93d35c442","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/621995fdcc9522b93d35c442/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[644,645,646,647,648,649,650,651],"take":"subject3/h2/3/cam4","frame_ids":[644,645,646,647,648,649,650,651]} +{"filtered_tile_id":"621995fdcc9522b93d35c442:16","filtered_window_id":"621995fdcc9522b93d35c442","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/621995fdcc9522b93d35c442/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[652,653,654,655,656,657,658,659],"take":"subject3/h2/3/cam4","frame_ids":[652,653,654,655,656,657,658,659]} +{"filtered_tile_id":"621995fdcc9522b93d35c442:24","filtered_window_id":"621995fdcc9522b93d35c442","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/621995fdcc9522b93d35c442/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[660,661,662,663,664,665,666,667],"take":"subject3/h2/3/cam4","frame_ids":[660,661,662,663,664,665,666,667]} +{"filtered_tile_id":"621995fdcc9522b93d35c442:32","filtered_window_id":"621995fdcc9522b93d35c442","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/621995fdcc9522b93d35c442/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[668,669,670,671,672,673,674,675],"take":"subject3/h2/3/cam4","frame_ids":[668,669,670,671,672,673,674,675]} +{"filtered_tile_id":"621995fdcc9522b93d35c442:40","filtered_window_id":"621995fdcc9522b93d35c442","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/621995fdcc9522b93d35c442/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[676,677,678,679,680,681,682,683],"take":"subject3/h2/3/cam4","frame_ids":[676,677,678,679,680,681,682,683]} +{"filtered_tile_id":"621995fdcc9522b93d35c442:48","filtered_window_id":"621995fdcc9522b93d35c442","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/621995fdcc9522b93d35c442/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[684,685,686,687,688,689,690,691],"take":"subject3/h2/3/cam4","frame_ids":[684,685,686,687,688,689,690,691]} +{"filtered_tile_id":"6230a1c22763043300eadf67:0","filtered_window_id":"6230a1c22763043300eadf67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6230a1c22763043300eadf67/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject1/k1/7/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"6230a1c22763043300eadf67:8","filtered_window_id":"6230a1c22763043300eadf67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6230a1c22763043300eadf67/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject1/k1/7/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"6230a1c22763043300eadf67:16","filtered_window_id":"6230a1c22763043300eadf67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6230a1c22763043300eadf67/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject1/k1/7/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"6230a1c22763043300eadf67:24","filtered_window_id":"6230a1c22763043300eadf67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6230a1c22763043300eadf67/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject1/k1/7/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"6230a1c22763043300eadf67:32","filtered_window_id":"6230a1c22763043300eadf67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6230a1c22763043300eadf67/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject1/k1/7/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"6230a1c22763043300eadf67:40","filtered_window_id":"6230a1c22763043300eadf67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6230a1c22763043300eadf67/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject1/k1/7/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"6230a1c22763043300eadf67:48","filtered_window_id":"6230a1c22763043300eadf67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6230a1c22763043300eadf67/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject1/k1/7/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"6230a1c22763043300eadf67:52","filtered_window_id":"6230a1c22763043300eadf67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6230a1c22763043300eadf67/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject1/k1/7/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"627049be64a23b6e5ef2a953:0","filtered_window_id":"627049be64a23b6e5ef2a953","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627049be64a23b6e5ef2a953/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject2/h2/5/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"627049be64a23b6e5ef2a953:8","filtered_window_id":"627049be64a23b6e5ef2a953","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627049be64a23b6e5ef2a953/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject2/h2/5/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"627049be64a23b6e5ef2a953:16","filtered_window_id":"627049be64a23b6e5ef2a953","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627049be64a23b6e5ef2a953/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[236,237,238,239,240,241,242,243],"take":"subject2/h2/5/cam4","frame_ids":[236,237,238,239,240,241,242,243]} +{"filtered_tile_id":"627049be64a23b6e5ef2a953:24","filtered_window_id":"627049be64a23b6e5ef2a953","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627049be64a23b6e5ef2a953/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[244,245,246,247,248,249,250,251],"take":"subject2/h2/5/cam4","frame_ids":[244,245,246,247,248,249,250,251]} +{"filtered_tile_id":"627049be64a23b6e5ef2a953:32","filtered_window_id":"627049be64a23b6e5ef2a953","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627049be64a23b6e5ef2a953/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[252,253,254,255,256,257,258,259],"take":"subject2/h2/5/cam4","frame_ids":[252,253,254,255,256,257,258,259]} +{"filtered_tile_id":"627049be64a23b6e5ef2a953:40","filtered_window_id":"627049be64a23b6e5ef2a953","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627049be64a23b6e5ef2a953/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[260,261,262,263,264,265,266,267],"take":"subject2/h2/5/cam4","frame_ids":[260,261,262,263,264,265,266,267]} +{"filtered_tile_id":"627049be64a23b6e5ef2a953:48","filtered_window_id":"627049be64a23b6e5ef2a953","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627049be64a23b6e5ef2a953/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[268,269,270,271,272,273,274,275],"take":"subject2/h2/5/cam4","frame_ids":[268,269,270,271,272,273,274,275]} +{"filtered_tile_id":"627049be64a23b6e5ef2a953:52","filtered_window_id":"627049be64a23b6e5ef2a953","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627049be64a23b6e5ef2a953/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject2/h2/5/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"627f4b018e28d80997f5a3f7:0","filtered_window_id":"627f4b018e28d80997f5a3f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627f4b018e28d80997f5a3f7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[1020,1021,1022,1023,1024,1025,1026,1027],"take":"subject2/o1/2/cam4","frame_ids":[1020,1021,1022,1023,1024,1025,1026,1027]} +{"filtered_tile_id":"627f4b018e28d80997f5a3f7:8","filtered_window_id":"627f4b018e28d80997f5a3f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627f4b018e28d80997f5a3f7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[1028,1029,1030,1031,1032,1033,1034,1035],"take":"subject2/o1/2/cam4","frame_ids":[1028,1029,1030,1031,1032,1033,1034,1035]} +{"filtered_tile_id":"627f4b018e28d80997f5a3f7:16","filtered_window_id":"627f4b018e28d80997f5a3f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627f4b018e28d80997f5a3f7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[1036,1037,1038,1039,1040,1041,1042,1043],"take":"subject2/o1/2/cam4","frame_ids":[1036,1037,1038,1039,1040,1041,1042,1043]} +{"filtered_tile_id":"627f4b018e28d80997f5a3f7:24","filtered_window_id":"627f4b018e28d80997f5a3f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627f4b018e28d80997f5a3f7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[1044,1045,1046,1047,1048,1049,1050,1051],"take":"subject2/o1/2/cam4","frame_ids":[1044,1045,1046,1047,1048,1049,1050,1051]} +{"filtered_tile_id":"627f4b018e28d80997f5a3f7:32","filtered_window_id":"627f4b018e28d80997f5a3f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627f4b018e28d80997f5a3f7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[1052,1053,1054,1055,1056,1057,1058,1059],"take":"subject2/o1/2/cam4","frame_ids":[1052,1053,1054,1055,1056,1057,1058,1059]} +{"filtered_tile_id":"627f4b018e28d80997f5a3f7:40","filtered_window_id":"627f4b018e28d80997f5a3f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627f4b018e28d80997f5a3f7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[1060,1061,1062,1063,1064,1065,1066,1067],"take":"subject2/o1/2/cam4","frame_ids":[1060,1061,1062,1063,1064,1065,1066,1067]} +{"filtered_tile_id":"627f4b018e28d80997f5a3f7:48","filtered_window_id":"627f4b018e28d80997f5a3f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627f4b018e28d80997f5a3f7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[1068,1069,1070,1071,1072,1073,1074,1075],"take":"subject2/o1/2/cam4","frame_ids":[1068,1069,1070,1071,1072,1073,1074,1075]} +{"filtered_tile_id":"627f4b018e28d80997f5a3f7:52","filtered_window_id":"627f4b018e28d80997f5a3f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/627f4b018e28d80997f5a3f7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[1072,1073,1074,1075,1076,1077,1078,1079],"take":"subject2/o1/2/cam4","frame_ids":[1072,1073,1074,1075,1076,1077,1078,1079]} +{"filtered_tile_id":"62bb30497cbcf227c3d3942c:0","filtered_window_id":"62bb30497cbcf227c3d3942c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62bb30497cbcf227c3d3942c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o2/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"62bb30497cbcf227c3d3942c:8","filtered_window_id":"62bb30497cbcf227c3d3942c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62bb30497cbcf227c3d3942c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o2/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"62bb30497cbcf227c3d3942c:16","filtered_window_id":"62bb30497cbcf227c3d3942c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62bb30497cbcf227c3d3942c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o2/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"62bb30497cbcf227c3d3942c:24","filtered_window_id":"62bb30497cbcf227c3d3942c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62bb30497cbcf227c3d3942c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o2/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"62bb30497cbcf227c3d3942c:32","filtered_window_id":"62bb30497cbcf227c3d3942c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62bb30497cbcf227c3d3942c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o2/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"62bb30497cbcf227c3d3942c:40","filtered_window_id":"62bb30497cbcf227c3d3942c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62bb30497cbcf227c3d3942c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/o2/1/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"62bb30497cbcf227c3d3942c:48","filtered_window_id":"62bb30497cbcf227c3d3942c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62bb30497cbcf227c3d3942c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/o2/1/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"62bb30497cbcf227c3d3942c:52","filtered_window_id":"62bb30497cbcf227c3d3942c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62bb30497cbcf227c3d3942c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/o2/1/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"62f9da03a3bd9958bbb78fe7:0","filtered_window_id":"62f9da03a3bd9958bbb78fe7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62f9da03a3bd9958bbb78fe7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject2/k2/2/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"62f9da03a3bd9958bbb78fe7:8","filtered_window_id":"62f9da03a3bd9958bbb78fe7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62f9da03a3bd9958bbb78fe7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject2/k2/2/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"62f9da03a3bd9958bbb78fe7:16","filtered_window_id":"62f9da03a3bd9958bbb78fe7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62f9da03a3bd9958bbb78fe7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject2/k2/2/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"62f9da03a3bd9958bbb78fe7:24","filtered_window_id":"62f9da03a3bd9958bbb78fe7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62f9da03a3bd9958bbb78fe7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject2/k2/2/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"62f9da03a3bd9958bbb78fe7:32","filtered_window_id":"62f9da03a3bd9958bbb78fe7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62f9da03a3bd9958bbb78fe7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject2/k2/2/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"62f9da03a3bd9958bbb78fe7:40","filtered_window_id":"62f9da03a3bd9958bbb78fe7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62f9da03a3bd9958bbb78fe7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[219,220,221,222,223,224,225,226],"take":"subject2/k2/2/cam4","frame_ids":[219,220,221,222,223,224,225,226]} +{"filtered_tile_id":"62f9da03a3bd9958bbb78fe7:48","filtered_window_id":"62f9da03a3bd9958bbb78fe7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62f9da03a3bd9958bbb78fe7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[227,228,229,230,231,232,233,234],"take":"subject2/k2/2/cam4","frame_ids":[227,228,229,230,231,232,233,234]} +{"filtered_tile_id":"62f9da03a3bd9958bbb78fe7:52","filtered_window_id":"62f9da03a3bd9958bbb78fe7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/62f9da03a3bd9958bbb78fe7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject2/k2/2/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"63020ea45618f6fab8f8c705:0","filtered_window_id":"63020ea45618f6fab8f8c705","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63020ea45618f6fab8f8c705/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[430,431,432,433,434,435,436,437],"take":"subject3/h1/1/cam4","frame_ids":[430,431,432,433,434,435,436,437]} +{"filtered_tile_id":"63020ea45618f6fab8f8c705:8","filtered_window_id":"63020ea45618f6fab8f8c705","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63020ea45618f6fab8f8c705/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[438,439,440,441,442,443,444,445],"take":"subject3/h1/1/cam4","frame_ids":[438,439,440,441,442,443,444,445]} +{"filtered_tile_id":"63020ea45618f6fab8f8c705:16","filtered_window_id":"63020ea45618f6fab8f8c705","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63020ea45618f6fab8f8c705/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[446,447,448,449,450,451,452,453],"take":"subject3/h1/1/cam4","frame_ids":[446,447,448,449,450,451,452,453]} +{"filtered_tile_id":"63020ea45618f6fab8f8c705:24","filtered_window_id":"63020ea45618f6fab8f8c705","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63020ea45618f6fab8f8c705/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[454,455,456,457,458,459,460,461],"take":"subject3/h1/1/cam4","frame_ids":[454,455,456,457,458,459,460,461]} +{"filtered_tile_id":"63020ea45618f6fab8f8c705:32","filtered_window_id":"63020ea45618f6fab8f8c705","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63020ea45618f6fab8f8c705/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject3/h1/1/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"63020ea45618f6fab8f8c705:40","filtered_window_id":"63020ea45618f6fab8f8c705","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63020ea45618f6fab8f8c705/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject3/h1/1/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"63020ea45618f6fab8f8c705:48","filtered_window_id":"63020ea45618f6fab8f8c705","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63020ea45618f6fab8f8c705/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject3/h1/1/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"63020ea45618f6fab8f8c705:52","filtered_window_id":"63020ea45618f6fab8f8c705","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63020ea45618f6fab8f8c705/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[482,483,484,485,486,487,488,489],"take":"subject3/h1/1/cam4","frame_ids":[482,483,484,485,486,487,488,489]} +{"filtered_tile_id":"637b6233b47b67c8837db78b:0","filtered_window_id":"637b6233b47b67c8837db78b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/637b6233b47b67c8837db78b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o1/5/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"637b6233b47b67c8837db78b:8","filtered_window_id":"637b6233b47b67c8837db78b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/637b6233b47b67c8837db78b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o1/5/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"637b6233b47b67c8837db78b:16","filtered_window_id":"637b6233b47b67c8837db78b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/637b6233b47b67c8837db78b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o1/5/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"637b6233b47b67c8837db78b:24","filtered_window_id":"637b6233b47b67c8837db78b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/637b6233b47b67c8837db78b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o1/5/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"637b6233b47b67c8837db78b:30","filtered_window_id":"637b6233b47b67c8837db78b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/637b6233b47b67c8837db78b/native_gt.npz","filtered_start_offset":30,"expected_frame_ids":[30,31,32,33,34,35,36,37],"take":"subject1/o1/5/cam4","frame_ids":[30,31,32,33,34,35,36,37]} +{"filtered_tile_id":"63fcf39b4ca313fa1cfac797:0","filtered_window_id":"63fcf39b4ca313fa1cfac797","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63fcf39b4ca313fa1cfac797/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[756,757,758,759,760,761,762,763],"take":"subject3/h2/3/cam4","frame_ids":[756,757,758,759,760,761,762,763]} +{"filtered_tile_id":"63fcf39b4ca313fa1cfac797:8","filtered_window_id":"63fcf39b4ca313fa1cfac797","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63fcf39b4ca313fa1cfac797/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[764,765,766,767,768,769,770,771],"take":"subject3/h2/3/cam4","frame_ids":[764,765,766,767,768,769,770,771]} +{"filtered_tile_id":"63fcf39b4ca313fa1cfac797:16","filtered_window_id":"63fcf39b4ca313fa1cfac797","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63fcf39b4ca313fa1cfac797/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[772,773,774,775,776,777,778,779],"take":"subject3/h2/3/cam4","frame_ids":[772,773,774,775,776,777,778,779]} +{"filtered_tile_id":"63fcf39b4ca313fa1cfac797:18","filtered_window_id":"63fcf39b4ca313fa1cfac797","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/63fcf39b4ca313fa1cfac797/native_gt.npz","filtered_start_offset":18,"expected_frame_ids":[774,775,776,777,778,779,780,781],"take":"subject3/h2/3/cam4","frame_ids":[774,775,776,777,778,779,780,781]} +{"filtered_tile_id":"641b4398f20a9e5491489d3f:0","filtered_window_id":"641b4398f20a9e5491489d3f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/641b4398f20a9e5491489d3f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[367,368,369,370,371,372,373,374],"take":"subject1/o1/1/cam4","frame_ids":[367,368,369,370,371,372,373,374]} +{"filtered_tile_id":"641b4398f20a9e5491489d3f:8","filtered_window_id":"641b4398f20a9e5491489d3f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/641b4398f20a9e5491489d3f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[375,376,377,378,379,380,381,382],"take":"subject1/o1/1/cam4","frame_ids":[375,376,377,378,379,380,381,382]} +{"filtered_tile_id":"641b4398f20a9e5491489d3f:16","filtered_window_id":"641b4398f20a9e5491489d3f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/641b4398f20a9e5491489d3f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject1/o1/1/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"641b4398f20a9e5491489d3f:24","filtered_window_id":"641b4398f20a9e5491489d3f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/641b4398f20a9e5491489d3f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject1/o1/1/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"641b4398f20a9e5491489d3f:32","filtered_window_id":"641b4398f20a9e5491489d3f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/641b4398f20a9e5491489d3f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject1/o1/1/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"641b4398f20a9e5491489d3f:40","filtered_window_id":"641b4398f20a9e5491489d3f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/641b4398f20a9e5491489d3f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject1/o1/1/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"641b4398f20a9e5491489d3f:48","filtered_window_id":"641b4398f20a9e5491489d3f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/641b4398f20a9e5491489d3f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject1/o1/1/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"641b4398f20a9e5491489d3f:52","filtered_window_id":"641b4398f20a9e5491489d3f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/641b4398f20a9e5491489d3f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[419,420,421,422,423,424,425,426],"take":"subject1/o1/1/cam4","frame_ids":[419,420,421,422,423,424,425,426]} +{"filtered_tile_id":"646ff2d1781b126745fe9af3:0","filtered_window_id":"646ff2d1781b126745fe9af3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/646ff2d1781b126745fe9af3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject3/h2/5/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"646ff2d1781b126745fe9af3:8","filtered_window_id":"646ff2d1781b126745fe9af3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/646ff2d1781b126745fe9af3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[340,341,342,343,344,345,346,347],"take":"subject3/h2/5/cam4","frame_ids":[340,341,342,343,344,345,346,347]} +{"filtered_tile_id":"646ff2d1781b126745fe9af3:16","filtered_window_id":"646ff2d1781b126745fe9af3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/646ff2d1781b126745fe9af3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[348,349,350,351,352,353,354,355],"take":"subject3/h2/5/cam4","frame_ids":[348,349,350,351,352,353,354,355]} +{"filtered_tile_id":"646ff2d1781b126745fe9af3:24","filtered_window_id":"646ff2d1781b126745fe9af3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/646ff2d1781b126745fe9af3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[356,357,358,359,360,361,362,363],"take":"subject3/h2/5/cam4","frame_ids":[356,357,358,359,360,361,362,363]} +{"filtered_tile_id":"646ff2d1781b126745fe9af3:32","filtered_window_id":"646ff2d1781b126745fe9af3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/646ff2d1781b126745fe9af3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject3/h2/5/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"646ff2d1781b126745fe9af3:40","filtered_window_id":"646ff2d1781b126745fe9af3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/646ff2d1781b126745fe9af3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject3/h2/5/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"646ff2d1781b126745fe9af3:48","filtered_window_id":"646ff2d1781b126745fe9af3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/646ff2d1781b126745fe9af3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject3/h2/5/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"646ff2d1781b126745fe9af3:52","filtered_window_id":"646ff2d1781b126745fe9af3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/646ff2d1781b126745fe9af3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject3/h2/5/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"6470987c693ddb78fb7452c6:0","filtered_window_id":"6470987c693ddb78fb7452c6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6470987c693ddb78fb7452c6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[632,633,634,635,636,637,638,639],"take":"subject2/k1/6/cam4","frame_ids":[632,633,634,635,636,637,638,639]} +{"filtered_tile_id":"6470987c693ddb78fb7452c6:8","filtered_window_id":"6470987c693ddb78fb7452c6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6470987c693ddb78fb7452c6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[640,641,642,643,644,645,646,647],"take":"subject2/k1/6/cam4","frame_ids":[640,641,642,643,644,645,646,647]} +{"filtered_tile_id":"6470987c693ddb78fb7452c6:16","filtered_window_id":"6470987c693ddb78fb7452c6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6470987c693ddb78fb7452c6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[648,649,650,651,652,653,654,655],"take":"subject2/k1/6/cam4","frame_ids":[648,649,650,651,652,653,654,655]} +{"filtered_tile_id":"6470987c693ddb78fb7452c6:24","filtered_window_id":"6470987c693ddb78fb7452c6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6470987c693ddb78fb7452c6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[656,657,658,659,660,661,662,663],"take":"subject2/k1/6/cam4","frame_ids":[656,657,658,659,660,661,662,663]} +{"filtered_tile_id":"6470987c693ddb78fb7452c6:32","filtered_window_id":"6470987c693ddb78fb7452c6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6470987c693ddb78fb7452c6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[664,665,666,667,668,669,670,671],"take":"subject2/k1/6/cam4","frame_ids":[664,665,666,667,668,669,670,671]} +{"filtered_tile_id":"6470987c693ddb78fb7452c6:40","filtered_window_id":"6470987c693ddb78fb7452c6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6470987c693ddb78fb7452c6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[672,673,674,675,676,677,678,679],"take":"subject2/k1/6/cam4","frame_ids":[672,673,674,675,676,677,678,679]} +{"filtered_tile_id":"6470987c693ddb78fb7452c6:48","filtered_window_id":"6470987c693ddb78fb7452c6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6470987c693ddb78fb7452c6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[680,681,682,683,684,685,686,687],"take":"subject2/k1/6/cam4","frame_ids":[680,681,682,683,684,685,686,687]} +{"filtered_tile_id":"6470987c693ddb78fb7452c6:52","filtered_window_id":"6470987c693ddb78fb7452c6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6470987c693ddb78fb7452c6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[684,685,686,687,688,689,690,691],"take":"subject2/k1/6/cam4","frame_ids":[684,685,686,687,688,689,690,691]} +{"filtered_tile_id":"648ab0b9ea116103fc628cd3:0","filtered_window_id":"648ab0b9ea116103fc628cd3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/648ab0b9ea116103fc628cd3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/k2/4/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"648ab0b9ea116103fc628cd3:8","filtered_window_id":"648ab0b9ea116103fc628cd3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/648ab0b9ea116103fc628cd3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/k2/4/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"648ab0b9ea116103fc628cd3:16","filtered_window_id":"648ab0b9ea116103fc628cd3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/648ab0b9ea116103fc628cd3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/k2/4/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"648ab0b9ea116103fc628cd3:24","filtered_window_id":"648ab0b9ea116103fc628cd3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/648ab0b9ea116103fc628cd3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/k2/4/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"648ab0b9ea116103fc628cd3:32","filtered_window_id":"648ab0b9ea116103fc628cd3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/648ab0b9ea116103fc628cd3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/k2/4/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"648ab0b9ea116103fc628cd3:40","filtered_window_id":"648ab0b9ea116103fc628cd3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/648ab0b9ea116103fc628cd3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/k2/4/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"648ab0b9ea116103fc628cd3:48","filtered_window_id":"648ab0b9ea116103fc628cd3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/648ab0b9ea116103fc628cd3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/k2/4/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"648ab0b9ea116103fc628cd3:52","filtered_window_id":"648ab0b9ea116103fc628cd3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/648ab0b9ea116103fc628cd3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/k2/4/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"64983daec24eac24aa5e9d87:0","filtered_window_id":"64983daec24eac24aa5e9d87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64983daec24eac24aa5e9d87/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[336,337,338,339,340,341,342,343],"take":"subject3/h2/3/cam4","frame_ids":[336,337,338,339,340,341,342,343]} +{"filtered_tile_id":"64983daec24eac24aa5e9d87:8","filtered_window_id":"64983daec24eac24aa5e9d87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64983daec24eac24aa5e9d87/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[344,345,346,347,348,349,350,351],"take":"subject3/h2/3/cam4","frame_ids":[344,345,346,347,348,349,350,351]} +{"filtered_tile_id":"64983daec24eac24aa5e9d87:16","filtered_window_id":"64983daec24eac24aa5e9d87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64983daec24eac24aa5e9d87/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject3/h2/3/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"64983daec24eac24aa5e9d87:24","filtered_window_id":"64983daec24eac24aa5e9d87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64983daec24eac24aa5e9d87/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject3/h2/3/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"64983daec24eac24aa5e9d87:32","filtered_window_id":"64983daec24eac24aa5e9d87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64983daec24eac24aa5e9d87/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject3/h2/3/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"64983daec24eac24aa5e9d87:40","filtered_window_id":"64983daec24eac24aa5e9d87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64983daec24eac24aa5e9d87/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[376,377,378,379,380,381,382,383],"take":"subject3/h2/3/cam4","frame_ids":[376,377,378,379,380,381,382,383]} +{"filtered_tile_id":"64983daec24eac24aa5e9d87:48","filtered_window_id":"64983daec24eac24aa5e9d87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64983daec24eac24aa5e9d87/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject3/h2/3/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"64983daec24eac24aa5e9d87:52","filtered_window_id":"64983daec24eac24aa5e9d87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64983daec24eac24aa5e9d87/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject3/h2/3/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"64a9ae6659d662653405c0df:0","filtered_window_id":"64a9ae6659d662653405c0df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64a9ae6659d662653405c0df/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[936,937,938,939,940,941,942,943],"take":"subject2/o1/1/cam4","frame_ids":[936,937,938,939,940,941,942,943]} +{"filtered_tile_id":"64a9ae6659d662653405c0df:8","filtered_window_id":"64a9ae6659d662653405c0df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64a9ae6659d662653405c0df/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[944,945,946,947,948,949,950,951],"take":"subject2/o1/1/cam4","frame_ids":[944,945,946,947,948,949,950,951]} +{"filtered_tile_id":"64a9ae6659d662653405c0df:16","filtered_window_id":"64a9ae6659d662653405c0df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64a9ae6659d662653405c0df/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[952,953,954,955,956,957,958,959],"take":"subject2/o1/1/cam4","frame_ids":[952,953,954,955,956,957,958,959]} +{"filtered_tile_id":"64a9ae6659d662653405c0df:24","filtered_window_id":"64a9ae6659d662653405c0df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64a9ae6659d662653405c0df/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[960,961,962,963,964,965,966,967],"take":"subject2/o1/1/cam4","frame_ids":[960,961,962,963,964,965,966,967]} +{"filtered_tile_id":"64a9ae6659d662653405c0df:32","filtered_window_id":"64a9ae6659d662653405c0df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64a9ae6659d662653405c0df/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[968,969,970,971,972,973,974,975],"take":"subject2/o1/1/cam4","frame_ids":[968,969,970,971,972,973,974,975]} +{"filtered_tile_id":"64a9ae6659d662653405c0df:40","filtered_window_id":"64a9ae6659d662653405c0df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64a9ae6659d662653405c0df/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[976,977,978,979,980,981,982,983],"take":"subject2/o1/1/cam4","frame_ids":[976,977,978,979,980,981,982,983]} +{"filtered_tile_id":"64a9ae6659d662653405c0df:41","filtered_window_id":"64a9ae6659d662653405c0df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/64a9ae6659d662653405c0df/native_gt.npz","filtered_start_offset":41,"expected_frame_ids":[977,978,979,980,981,982,983,984],"take":"subject2/o1/1/cam4","frame_ids":[977,978,979,980,981,982,983,984]} +{"filtered_tile_id":"651b2a7a468754e108765e69:0","filtered_window_id":"651b2a7a468754e108765e69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/651b2a7a468754e108765e69/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[275,276,277,278,279,280,281,282],"take":"subject1/k1/4/cam4","frame_ids":[275,276,277,278,279,280,281,282]} +{"filtered_tile_id":"651b2a7a468754e108765e69:8","filtered_window_id":"651b2a7a468754e108765e69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/651b2a7a468754e108765e69/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[283,284,285,286,287,288,289,290],"take":"subject1/k1/4/cam4","frame_ids":[283,284,285,286,287,288,289,290]} +{"filtered_tile_id":"651b2a7a468754e108765e69:16","filtered_window_id":"651b2a7a468754e108765e69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/651b2a7a468754e108765e69/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[291,292,293,294,295,296,297,298],"take":"subject1/k1/4/cam4","frame_ids":[291,292,293,294,295,296,297,298]} +{"filtered_tile_id":"651b2a7a468754e108765e69:24","filtered_window_id":"651b2a7a468754e108765e69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/651b2a7a468754e108765e69/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[299,300,301,302,303,304,305,306],"take":"subject1/k1/4/cam4","frame_ids":[299,300,301,302,303,304,305,306]} +{"filtered_tile_id":"651b2a7a468754e108765e69:32","filtered_window_id":"651b2a7a468754e108765e69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/651b2a7a468754e108765e69/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[307,308,309,310,311,312,313,314],"take":"subject1/k1/4/cam4","frame_ids":[307,308,309,310,311,312,313,314]} +{"filtered_tile_id":"651b2a7a468754e108765e69:40","filtered_window_id":"651b2a7a468754e108765e69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/651b2a7a468754e108765e69/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[315,316,317,318,319,320,321,322],"take":"subject1/k1/4/cam4","frame_ids":[315,316,317,318,319,320,321,322]} +{"filtered_tile_id":"651b2a7a468754e108765e69:48","filtered_window_id":"651b2a7a468754e108765e69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/651b2a7a468754e108765e69/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[323,324,325,326,327,328,329,330],"take":"subject1/k1/4/cam4","frame_ids":[323,324,325,326,327,328,329,330]} +{"filtered_tile_id":"651b2a7a468754e108765e69:52","filtered_window_id":"651b2a7a468754e108765e69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/651b2a7a468754e108765e69/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[327,328,329,330,331,332,333,334],"take":"subject1/k1/4/cam4","frame_ids":[327,328,329,330,331,332,333,334]} +{"filtered_tile_id":"6538d84f721b276557020fb5:0","filtered_window_id":"6538d84f721b276557020fb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6538d84f721b276557020fb5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/h1/3/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"6538d84f721b276557020fb5:8","filtered_window_id":"6538d84f721b276557020fb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6538d84f721b276557020fb5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/h1/3/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"6538d84f721b276557020fb5:16","filtered_window_id":"6538d84f721b276557020fb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6538d84f721b276557020fb5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/h1/3/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"6538d84f721b276557020fb5:24","filtered_window_id":"6538d84f721b276557020fb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6538d84f721b276557020fb5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/h1/3/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"6538d84f721b276557020fb5:32","filtered_window_id":"6538d84f721b276557020fb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6538d84f721b276557020fb5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[56,57,58,59,60,61,62,63],"take":"subject2/h1/3/cam4","frame_ids":[56,57,58,59,60,61,62,63]} +{"filtered_tile_id":"6538d84f721b276557020fb5:40","filtered_window_id":"6538d84f721b276557020fb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6538d84f721b276557020fb5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject2/h1/3/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"6538d84f721b276557020fb5:48","filtered_window_id":"6538d84f721b276557020fb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6538d84f721b276557020fb5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[72,73,74,75,76,77,78,79],"take":"subject2/h1/3/cam4","frame_ids":[72,73,74,75,76,77,78,79]} +{"filtered_tile_id":"6538d84f721b276557020fb5:52","filtered_window_id":"6538d84f721b276557020fb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6538d84f721b276557020fb5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject2/h1/3/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"65e77106be070859cbad212d:0","filtered_window_id":"65e77106be070859cbad212d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/65e77106be070859cbad212d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[31,32,33,34,35,36,37,38],"take":"subject1/o2/5/cam4","frame_ids":[31,32,33,34,35,36,37,38]} +{"filtered_tile_id":"65e77106be070859cbad212d:8","filtered_window_id":"65e77106be070859cbad212d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/65e77106be070859cbad212d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[39,40,41,42,43,44,45,46],"take":"subject1/o2/5/cam4","frame_ids":[39,40,41,42,43,44,45,46]} +{"filtered_tile_id":"65e77106be070859cbad212d:16","filtered_window_id":"65e77106be070859cbad212d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/65e77106be070859cbad212d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[47,48,49,50,51,52,53,54],"take":"subject1/o2/5/cam4","frame_ids":[47,48,49,50,51,52,53,54]} +{"filtered_tile_id":"65e77106be070859cbad212d:24","filtered_window_id":"65e77106be070859cbad212d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/65e77106be070859cbad212d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[55,56,57,58,59,60,61,62],"take":"subject1/o2/5/cam4","frame_ids":[55,56,57,58,59,60,61,62]} +{"filtered_tile_id":"65e77106be070859cbad212d:32","filtered_window_id":"65e77106be070859cbad212d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/65e77106be070859cbad212d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[63,64,65,66,67,68,69,70],"take":"subject1/o2/5/cam4","frame_ids":[63,64,65,66,67,68,69,70]} +{"filtered_tile_id":"65e77106be070859cbad212d:40","filtered_window_id":"65e77106be070859cbad212d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/65e77106be070859cbad212d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[71,72,73,74,75,76,77,78],"take":"subject1/o2/5/cam4","frame_ids":[71,72,73,74,75,76,77,78]} +{"filtered_tile_id":"65e77106be070859cbad212d:45","filtered_window_id":"65e77106be070859cbad212d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/65e77106be070859cbad212d/native_gt.npz","filtered_start_offset":45,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject1/o2/5/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"66c5a2014bc587ecc26f1c8f:0","filtered_window_id":"66c5a2014bc587ecc26f1c8f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66c5a2014bc587ecc26f1c8f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject2/o1/0/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"66c5a2014bc587ecc26f1c8f:8","filtered_window_id":"66c5a2014bc587ecc26f1c8f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66c5a2014bc587ecc26f1c8f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject2/o1/0/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"66c5a2014bc587ecc26f1c8f:16","filtered_window_id":"66c5a2014bc587ecc26f1c8f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66c5a2014bc587ecc26f1c8f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject2/o1/0/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"66c5a2014bc587ecc26f1c8f:24","filtered_window_id":"66c5a2014bc587ecc26f1c8f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66c5a2014bc587ecc26f1c8f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject2/o1/0/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"66c5a2014bc587ecc26f1c8f:32","filtered_window_id":"66c5a2014bc587ecc26f1c8f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66c5a2014bc587ecc26f1c8f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[192,193,194,195,196,197,198,199],"take":"subject2/o1/0/cam4","frame_ids":[192,193,194,195,196,197,198,199]} +{"filtered_tile_id":"66c5a2014bc587ecc26f1c8f:40","filtered_window_id":"66c5a2014bc587ecc26f1c8f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66c5a2014bc587ecc26f1c8f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[200,201,202,203,204,205,206,207],"take":"subject2/o1/0/cam4","frame_ids":[200,201,202,203,204,205,206,207]} +{"filtered_tile_id":"66c5a2014bc587ecc26f1c8f:48","filtered_window_id":"66c5a2014bc587ecc26f1c8f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66c5a2014bc587ecc26f1c8f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[208,209,210,211,212,213,214,215],"take":"subject2/o1/0/cam4","frame_ids":[208,209,210,211,212,213,214,215]} +{"filtered_tile_id":"66c5a2014bc587ecc26f1c8f:52","filtered_window_id":"66c5a2014bc587ecc26f1c8f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66c5a2014bc587ecc26f1c8f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject2/o1/0/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"66d78de3cbc4b248834cdf41:0","filtered_window_id":"66d78de3cbc4b248834cdf41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66d78de3cbc4b248834cdf41/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject2/k1/6/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"66d78de3cbc4b248834cdf41:8","filtered_window_id":"66d78de3cbc4b248834cdf41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66d78de3cbc4b248834cdf41/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject2/k1/6/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"66d78de3cbc4b248834cdf41:16","filtered_window_id":"66d78de3cbc4b248834cdf41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66d78de3cbc4b248834cdf41/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject2/k1/6/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"66d78de3cbc4b248834cdf41:24","filtered_window_id":"66d78de3cbc4b248834cdf41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66d78de3cbc4b248834cdf41/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[536,537,538,539,540,541,542,543],"take":"subject2/k1/6/cam4","frame_ids":[536,537,538,539,540,541,542,543]} +{"filtered_tile_id":"66d78de3cbc4b248834cdf41:32","filtered_window_id":"66d78de3cbc4b248834cdf41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66d78de3cbc4b248834cdf41/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[544,545,546,547,548,549,550,551],"take":"subject2/k1/6/cam4","frame_ids":[544,545,546,547,548,549,550,551]} +{"filtered_tile_id":"66d78de3cbc4b248834cdf41:40","filtered_window_id":"66d78de3cbc4b248834cdf41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66d78de3cbc4b248834cdf41/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[552,553,554,555,556,557,558,559],"take":"subject2/k1/6/cam4","frame_ids":[552,553,554,555,556,557,558,559]} +{"filtered_tile_id":"66d78de3cbc4b248834cdf41:48","filtered_window_id":"66d78de3cbc4b248834cdf41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66d78de3cbc4b248834cdf41/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[560,561,562,563,564,565,566,567],"take":"subject2/k1/6/cam4","frame_ids":[560,561,562,563,564,565,566,567]} +{"filtered_tile_id":"66d78de3cbc4b248834cdf41:52","filtered_window_id":"66d78de3cbc4b248834cdf41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66d78de3cbc4b248834cdf41/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject2/k1/6/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"66facf654e440eb3c53f7ce7:0","filtered_window_id":"66facf654e440eb3c53f7ce7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66facf654e440eb3c53f7ce7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject1/k1/7/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"66facf654e440eb3c53f7ce7:8","filtered_window_id":"66facf654e440eb3c53f7ce7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66facf654e440eb3c53f7ce7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject1/k1/7/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"66facf654e440eb3c53f7ce7:16","filtered_window_id":"66facf654e440eb3c53f7ce7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66facf654e440eb3c53f7ce7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject1/k1/7/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"66facf654e440eb3c53f7ce7:24","filtered_window_id":"66facf654e440eb3c53f7ce7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66facf654e440eb3c53f7ce7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject1/k1/7/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"66facf654e440eb3c53f7ce7:32","filtered_window_id":"66facf654e440eb3c53f7ce7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66facf654e440eb3c53f7ce7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject1/k1/7/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"66facf654e440eb3c53f7ce7:40","filtered_window_id":"66facf654e440eb3c53f7ce7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66facf654e440eb3c53f7ce7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject1/k1/7/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"66facf654e440eb3c53f7ce7:48","filtered_window_id":"66facf654e440eb3c53f7ce7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66facf654e440eb3c53f7ce7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject1/k1/7/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"66facf654e440eb3c53f7ce7:52","filtered_window_id":"66facf654e440eb3c53f7ce7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/66facf654e440eb3c53f7ce7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject1/k1/7/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"672a2c942d0883425923a052:0","filtered_window_id":"672a2c942d0883425923a052","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/672a2c942d0883425923a052/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[251,252,253,254,255,256,257,258],"take":"subject2/o1/2/cam4","frame_ids":[251,252,253,254,255,256,257,258]} +{"filtered_tile_id":"672a2c942d0883425923a052:8","filtered_window_id":"672a2c942d0883425923a052","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/672a2c942d0883425923a052/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[259,260,261,262,263,264,265,266],"take":"subject2/o1/2/cam4","frame_ids":[259,260,261,262,263,264,265,266]} +{"filtered_tile_id":"672a2c942d0883425923a052:16","filtered_window_id":"672a2c942d0883425923a052","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/672a2c942d0883425923a052/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[267,268,269,270,271,272,273,274],"take":"subject2/o1/2/cam4","frame_ids":[267,268,269,270,271,272,273,274]} +{"filtered_tile_id":"672a2c942d0883425923a052:24","filtered_window_id":"672a2c942d0883425923a052","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/672a2c942d0883425923a052/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[275,276,277,278,279,280,281,282],"take":"subject2/o1/2/cam4","frame_ids":[275,276,277,278,279,280,281,282]} +{"filtered_tile_id":"672a2c942d0883425923a052:32","filtered_window_id":"672a2c942d0883425923a052","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/672a2c942d0883425923a052/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[283,284,285,286,287,288,289,290],"take":"subject2/o1/2/cam4","frame_ids":[283,284,285,286,287,288,289,290]} +{"filtered_tile_id":"672a2c942d0883425923a052:40","filtered_window_id":"672a2c942d0883425923a052","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/672a2c942d0883425923a052/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[291,292,293,294,295,296,297,298],"take":"subject2/o1/2/cam4","frame_ids":[291,292,293,294,295,296,297,298]} +{"filtered_tile_id":"672a2c942d0883425923a052:48","filtered_window_id":"672a2c942d0883425923a052","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/672a2c942d0883425923a052/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[299,300,301,302,303,304,305,306],"take":"subject2/o1/2/cam4","frame_ids":[299,300,301,302,303,304,305,306]} +{"filtered_tile_id":"672a2c942d0883425923a052:52","filtered_window_id":"672a2c942d0883425923a052","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/672a2c942d0883425923a052/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[303,304,305,306,307,308,309,310],"take":"subject2/o1/2/cam4","frame_ids":[303,304,305,306,307,308,309,310]} +{"filtered_tile_id":"674fac0216fe2497339e2b5e:0","filtered_window_id":"674fac0216fe2497339e2b5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/674fac0216fe2497339e2b5e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[525,526,527,528,529,530,531,532],"take":"subject2/k1/1/cam4","frame_ids":[525,526,527,528,529,530,531,532]} +{"filtered_tile_id":"674fac0216fe2497339e2b5e:8","filtered_window_id":"674fac0216fe2497339e2b5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/674fac0216fe2497339e2b5e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[533,534,535,536,537,538,539,540],"take":"subject2/k1/1/cam4","frame_ids":[533,534,535,536,537,538,539,540]} +{"filtered_tile_id":"674fac0216fe2497339e2b5e:16","filtered_window_id":"674fac0216fe2497339e2b5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/674fac0216fe2497339e2b5e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject2/k1/1/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"674fac0216fe2497339e2b5e:24","filtered_window_id":"674fac0216fe2497339e2b5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/674fac0216fe2497339e2b5e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[549,550,551,552,553,554,555,556],"take":"subject2/k1/1/cam4","frame_ids":[549,550,551,552,553,554,555,556]} +{"filtered_tile_id":"674fac0216fe2497339e2b5e:32","filtered_window_id":"674fac0216fe2497339e2b5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/674fac0216fe2497339e2b5e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[557,558,559,560,561,562,563,564],"take":"subject2/k1/1/cam4","frame_ids":[557,558,559,560,561,562,563,564]} +{"filtered_tile_id":"674fac0216fe2497339e2b5e:40","filtered_window_id":"674fac0216fe2497339e2b5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/674fac0216fe2497339e2b5e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[565,566,567,568,569,570,571,572],"take":"subject2/k1/1/cam4","frame_ids":[565,566,567,568,569,570,571,572]} +{"filtered_tile_id":"674fac0216fe2497339e2b5e:48","filtered_window_id":"674fac0216fe2497339e2b5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/674fac0216fe2497339e2b5e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[573,574,575,576,577,578,579,580],"take":"subject2/k1/1/cam4","frame_ids":[573,574,575,576,577,578,579,580]} +{"filtered_tile_id":"674fac0216fe2497339e2b5e:52","filtered_window_id":"674fac0216fe2497339e2b5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/674fac0216fe2497339e2b5e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[577,578,579,580,581,582,583,584],"take":"subject2/k1/1/cam4","frame_ids":[577,578,579,580,581,582,583,584]} +{"filtered_tile_id":"6754bbb8045b84051d8ef509:0","filtered_window_id":"6754bbb8045b84051d8ef509","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6754bbb8045b84051d8ef509/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/h1/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"6754bbb8045b84051d8ef509:8","filtered_window_id":"6754bbb8045b84051d8ef509","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6754bbb8045b84051d8ef509/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/h1/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"6754bbb8045b84051d8ef509:16","filtered_window_id":"6754bbb8045b84051d8ef509","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6754bbb8045b84051d8ef509/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/h1/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"6754bbb8045b84051d8ef509:24","filtered_window_id":"6754bbb8045b84051d8ef509","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6754bbb8045b84051d8ef509/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/h1/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"6754bbb8045b84051d8ef509:32","filtered_window_id":"6754bbb8045b84051d8ef509","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6754bbb8045b84051d8ef509/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/h1/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"6754bbb8045b84051d8ef509:40","filtered_window_id":"6754bbb8045b84051d8ef509","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6754bbb8045b84051d8ef509/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/h1/1/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"6754bbb8045b84051d8ef509:48","filtered_window_id":"6754bbb8045b84051d8ef509","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6754bbb8045b84051d8ef509/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/h1/1/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"6754bbb8045b84051d8ef509:52","filtered_window_id":"6754bbb8045b84051d8ef509","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6754bbb8045b84051d8ef509/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/h1/1/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"679f26b1e89b33ad929a0819:0","filtered_window_id":"679f26b1e89b33ad929a0819","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/679f26b1e89b33ad929a0819/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[376,377,378,379,380,381,382,383],"take":"subject3/h1/3/cam4","frame_ids":[376,377,378,379,380,381,382,383]} +{"filtered_tile_id":"679f26b1e89b33ad929a0819:8","filtered_window_id":"679f26b1e89b33ad929a0819","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/679f26b1e89b33ad929a0819/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject3/h1/3/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"679f26b1e89b33ad929a0819:16","filtered_window_id":"679f26b1e89b33ad929a0819","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/679f26b1e89b33ad929a0819/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[392,393,394,395,396,397,398,399],"take":"subject3/h1/3/cam4","frame_ids":[392,393,394,395,396,397,398,399]} +{"filtered_tile_id":"679f26b1e89b33ad929a0819:24","filtered_window_id":"679f26b1e89b33ad929a0819","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/679f26b1e89b33ad929a0819/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[400,401,402,403,404,405,406,407],"take":"subject3/h1/3/cam4","frame_ids":[400,401,402,403,404,405,406,407]} +{"filtered_tile_id":"679f26b1e89b33ad929a0819:32","filtered_window_id":"679f26b1e89b33ad929a0819","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/679f26b1e89b33ad929a0819/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[408,409,410,411,412,413,414,415],"take":"subject3/h1/3/cam4","frame_ids":[408,409,410,411,412,413,414,415]} +{"filtered_tile_id":"679f26b1e89b33ad929a0819:40","filtered_window_id":"679f26b1e89b33ad929a0819","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/679f26b1e89b33ad929a0819/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[416,417,418,419,420,421,422,423],"take":"subject3/h1/3/cam4","frame_ids":[416,417,418,419,420,421,422,423]} +{"filtered_tile_id":"679f26b1e89b33ad929a0819:48","filtered_window_id":"679f26b1e89b33ad929a0819","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/679f26b1e89b33ad929a0819/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[424,425,426,427,428,429,430,431],"take":"subject3/h1/3/cam4","frame_ids":[424,425,426,427,428,429,430,431]} +{"filtered_tile_id":"679f26b1e89b33ad929a0819:52","filtered_window_id":"679f26b1e89b33ad929a0819","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/679f26b1e89b33ad929a0819/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject3/h1/3/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"68452dc3fc54e8fca4625b2b:0","filtered_window_id":"68452dc3fc54e8fca4625b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68452dc3fc54e8fca4625b2b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject2/h1/2/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"68452dc3fc54e8fca4625b2b:8","filtered_window_id":"68452dc3fc54e8fca4625b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68452dc3fc54e8fca4625b2b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject2/h1/2/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"68452dc3fc54e8fca4625b2b:16","filtered_window_id":"68452dc3fc54e8fca4625b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68452dc3fc54e8fca4625b2b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject2/h1/2/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"68452dc3fc54e8fca4625b2b:24","filtered_window_id":"68452dc3fc54e8fca4625b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68452dc3fc54e8fca4625b2b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject2/h1/2/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"68452dc3fc54e8fca4625b2b:32","filtered_window_id":"68452dc3fc54e8fca4625b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68452dc3fc54e8fca4625b2b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject2/h1/2/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"68452dc3fc54e8fca4625b2b:40","filtered_window_id":"68452dc3fc54e8fca4625b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68452dc3fc54e8fca4625b2b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject2/h1/2/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"68452dc3fc54e8fca4625b2b:48","filtered_window_id":"68452dc3fc54e8fca4625b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68452dc3fc54e8fca4625b2b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[296,297,298,299,300,301,302,303],"take":"subject2/h1/2/cam4","frame_ids":[296,297,298,299,300,301,302,303]} +{"filtered_tile_id":"68452dc3fc54e8fca4625b2b:52","filtered_window_id":"68452dc3fc54e8fca4625b2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68452dc3fc54e8fca4625b2b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[300,301,302,303,304,305,306,307],"take":"subject2/h1/2/cam4","frame_ids":[300,301,302,303,304,305,306,307]} +{"filtered_tile_id":"685de8b9ad11c0594192bea8:0","filtered_window_id":"685de8b9ad11c0594192bea8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/685de8b9ad11c0594192bea8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject1/o1/3/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"685de8b9ad11c0594192bea8:8","filtered_window_id":"685de8b9ad11c0594192bea8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/685de8b9ad11c0594192bea8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject1/o1/3/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"685de8b9ad11c0594192bea8:16","filtered_window_id":"685de8b9ad11c0594192bea8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/685de8b9ad11c0594192bea8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject1/o1/3/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"685de8b9ad11c0594192bea8:24","filtered_window_id":"685de8b9ad11c0594192bea8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/685de8b9ad11c0594192bea8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject1/o1/3/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"685de8b9ad11c0594192bea8:32","filtered_window_id":"685de8b9ad11c0594192bea8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/685de8b9ad11c0594192bea8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject1/o1/3/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"685de8b9ad11c0594192bea8:40","filtered_window_id":"685de8b9ad11c0594192bea8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/685de8b9ad11c0594192bea8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject1/o1/3/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"685de8b9ad11c0594192bea8:48","filtered_window_id":"685de8b9ad11c0594192bea8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/685de8b9ad11c0594192bea8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject1/o1/3/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"685de8b9ad11c0594192bea8:52","filtered_window_id":"685de8b9ad11c0594192bea8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/685de8b9ad11c0594192bea8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject1/o1/3/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"68b60079e2273f110d8e43e1:0","filtered_window_id":"68b60079e2273f110d8e43e1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68b60079e2273f110d8e43e1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject1/h1/6/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"68b60079e2273f110d8e43e1:8","filtered_window_id":"68b60079e2273f110d8e43e1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68b60079e2273f110d8e43e1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject1/h1/6/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"68b60079e2273f110d8e43e1:16","filtered_window_id":"68b60079e2273f110d8e43e1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68b60079e2273f110d8e43e1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject1/h1/6/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"68b60079e2273f110d8e43e1:24","filtered_window_id":"68b60079e2273f110d8e43e1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68b60079e2273f110d8e43e1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject1/h1/6/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"68b60079e2273f110d8e43e1:32","filtered_window_id":"68b60079e2273f110d8e43e1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68b60079e2273f110d8e43e1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject1/h1/6/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"68b60079e2273f110d8e43e1:40","filtered_window_id":"68b60079e2273f110d8e43e1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68b60079e2273f110d8e43e1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject1/h1/6/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"68b60079e2273f110d8e43e1:48","filtered_window_id":"68b60079e2273f110d8e43e1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68b60079e2273f110d8e43e1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject1/h1/6/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"68b60079e2273f110d8e43e1:52","filtered_window_id":"68b60079e2273f110d8e43e1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68b60079e2273f110d8e43e1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject1/h1/6/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"68f982733be6e476cc582f91:0","filtered_window_id":"68f982733be6e476cc582f91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68f982733be6e476cc582f91/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject1/o2/7/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"68f982733be6e476cc582f91:8","filtered_window_id":"68f982733be6e476cc582f91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68f982733be6e476cc582f91/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject1/o2/7/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"68f982733be6e476cc582f91:16","filtered_window_id":"68f982733be6e476cc582f91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68f982733be6e476cc582f91/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject1/o2/7/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"68f982733be6e476cc582f91:18","filtered_window_id":"68f982733be6e476cc582f91","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/68f982733be6e476cc582f91/native_gt.npz","filtered_start_offset":18,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject1/o2/7/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"69b55c7287e583fc264b003c:0","filtered_window_id":"69b55c7287e583fc264b003c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b55c7287e583fc264b003c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[300,301,302,303,304,305,306,307],"take":"subject1/k2/4/cam4","frame_ids":[300,301,302,303,304,305,306,307]} +{"filtered_tile_id":"69b55c7287e583fc264b003c:8","filtered_window_id":"69b55c7287e583fc264b003c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b55c7287e583fc264b003c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject1/k2/4/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"69b55c7287e583fc264b003c:16","filtered_window_id":"69b55c7287e583fc264b003c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b55c7287e583fc264b003c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[316,317,318,319,320,321,322,323],"take":"subject1/k2/4/cam4","frame_ids":[316,317,318,319,320,321,322,323]} +{"filtered_tile_id":"69b55c7287e583fc264b003c:24","filtered_window_id":"69b55c7287e583fc264b003c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b55c7287e583fc264b003c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject1/k2/4/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"69b55c7287e583fc264b003c:32","filtered_window_id":"69b55c7287e583fc264b003c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b55c7287e583fc264b003c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject1/k2/4/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"69b55c7287e583fc264b003c:40","filtered_window_id":"69b55c7287e583fc264b003c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b55c7287e583fc264b003c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[340,341,342,343,344,345,346,347],"take":"subject1/k2/4/cam4","frame_ids":[340,341,342,343,344,345,346,347]} +{"filtered_tile_id":"69b55c7287e583fc264b003c:48","filtered_window_id":"69b55c7287e583fc264b003c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b55c7287e583fc264b003c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[348,349,350,351,352,353,354,355],"take":"subject1/k2/4/cam4","frame_ids":[348,349,350,351,352,353,354,355]} +{"filtered_tile_id":"69b55c7287e583fc264b003c:52","filtered_window_id":"69b55c7287e583fc264b003c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b55c7287e583fc264b003c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject1/k2/4/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"69b7a2e8bffabaab115d4913:0","filtered_window_id":"69b7a2e8bffabaab115d4913","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b7a2e8bffabaab115d4913/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[508,509,510,511,512,513,514,515],"take":"subject2/h1/7/cam4","frame_ids":[508,509,510,511,512,513,514,515]} +{"filtered_tile_id":"69b7a2e8bffabaab115d4913:8","filtered_window_id":"69b7a2e8bffabaab115d4913","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b7a2e8bffabaab115d4913/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[516,517,518,519,520,521,522,523],"take":"subject2/h1/7/cam4","frame_ids":[516,517,518,519,520,521,522,523]} +{"filtered_tile_id":"69b7a2e8bffabaab115d4913:16","filtered_window_id":"69b7a2e8bffabaab115d4913","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b7a2e8bffabaab115d4913/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[524,525,526,527,528,529,530,531],"take":"subject2/h1/7/cam4","frame_ids":[524,525,526,527,528,529,530,531]} +{"filtered_tile_id":"69b7a2e8bffabaab115d4913:24","filtered_window_id":"69b7a2e8bffabaab115d4913","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b7a2e8bffabaab115d4913/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[532,533,534,535,536,537,538,539],"take":"subject2/h1/7/cam4","frame_ids":[532,533,534,535,536,537,538,539]} +{"filtered_tile_id":"69b7a2e8bffabaab115d4913:32","filtered_window_id":"69b7a2e8bffabaab115d4913","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b7a2e8bffabaab115d4913/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[540,541,542,543,544,545,546,547],"take":"subject2/h1/7/cam4","frame_ids":[540,541,542,543,544,545,546,547]} +{"filtered_tile_id":"69b7a2e8bffabaab115d4913:40","filtered_window_id":"69b7a2e8bffabaab115d4913","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b7a2e8bffabaab115d4913/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject2/h1/7/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"69b7a2e8bffabaab115d4913:48","filtered_window_id":"69b7a2e8bffabaab115d4913","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b7a2e8bffabaab115d4913/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject2/h1/7/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"69b7a2e8bffabaab115d4913:52","filtered_window_id":"69b7a2e8bffabaab115d4913","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69b7a2e8bffabaab115d4913/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[560,561,562,563,564,565,566,567],"take":"subject2/h1/7/cam4","frame_ids":[560,561,562,563,564,565,566,567]} +{"filtered_tile_id":"69d291b992cb3ba43fb4fef8:0","filtered_window_id":"69d291b992cb3ba43fb4fef8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69d291b992cb3ba43fb4fef8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject3/h2/5/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"69d291b992cb3ba43fb4fef8:8","filtered_window_id":"69d291b992cb3ba43fb4fef8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69d291b992cb3ba43fb4fef8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject3/h2/5/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"69d291b992cb3ba43fb4fef8:16","filtered_window_id":"69d291b992cb3ba43fb4fef8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69d291b992cb3ba43fb4fef8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject3/h2/5/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"69d291b992cb3ba43fb4fef8:24","filtered_window_id":"69d291b992cb3ba43fb4fef8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69d291b992cb3ba43fb4fef8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[296,297,298,299,300,301,302,303],"take":"subject3/h2/5/cam4","frame_ids":[296,297,298,299,300,301,302,303]} +{"filtered_tile_id":"69d291b992cb3ba43fb4fef8:32","filtered_window_id":"69d291b992cb3ba43fb4fef8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69d291b992cb3ba43fb4fef8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[304,305,306,307,308,309,310,311],"take":"subject3/h2/5/cam4","frame_ids":[304,305,306,307,308,309,310,311]} +{"filtered_tile_id":"69d291b992cb3ba43fb4fef8:40","filtered_window_id":"69d291b992cb3ba43fb4fef8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69d291b992cb3ba43fb4fef8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[312,313,314,315,316,317,318,319],"take":"subject3/h2/5/cam4","frame_ids":[312,313,314,315,316,317,318,319]} +{"filtered_tile_id":"69d291b992cb3ba43fb4fef8:48","filtered_window_id":"69d291b992cb3ba43fb4fef8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69d291b992cb3ba43fb4fef8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[320,321,322,323,324,325,326,327],"take":"subject3/h2/5/cam4","frame_ids":[320,321,322,323,324,325,326,327]} +{"filtered_tile_id":"69d291b992cb3ba43fb4fef8:52","filtered_window_id":"69d291b992cb3ba43fb4fef8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69d291b992cb3ba43fb4fef8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject3/h2/5/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"69fc843a4fb2ec2665c9bb10:0","filtered_window_id":"69fc843a4fb2ec2665c9bb10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69fc843a4fb2ec2665c9bb10/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[5,6,7,8,9,10,11,12],"take":"subject1/o2/4/cam4","frame_ids":[5,6,7,8,9,10,11,12]} +{"filtered_tile_id":"69fc843a4fb2ec2665c9bb10:8","filtered_window_id":"69fc843a4fb2ec2665c9bb10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69fc843a4fb2ec2665c9bb10/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[13,14,15,16,17,18,19,20],"take":"subject1/o2/4/cam4","frame_ids":[13,14,15,16,17,18,19,20]} +{"filtered_tile_id":"69fc843a4fb2ec2665c9bb10:16","filtered_window_id":"69fc843a4fb2ec2665c9bb10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69fc843a4fb2ec2665c9bb10/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[21,22,23,24,25,26,27,28],"take":"subject1/o2/4/cam4","frame_ids":[21,22,23,24,25,26,27,28]} +{"filtered_tile_id":"69fc843a4fb2ec2665c9bb10:24","filtered_window_id":"69fc843a4fb2ec2665c9bb10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69fc843a4fb2ec2665c9bb10/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[29,30,31,32,33,34,35,36],"take":"subject1/o2/4/cam4","frame_ids":[29,30,31,32,33,34,35,36]} +{"filtered_tile_id":"69fc843a4fb2ec2665c9bb10:32","filtered_window_id":"69fc843a4fb2ec2665c9bb10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69fc843a4fb2ec2665c9bb10/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject1/o2/4/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"69fc843a4fb2ec2665c9bb10:40","filtered_window_id":"69fc843a4fb2ec2665c9bb10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69fc843a4fb2ec2665c9bb10/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject1/o2/4/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"69fc843a4fb2ec2665c9bb10:48","filtered_window_id":"69fc843a4fb2ec2665c9bb10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69fc843a4fb2ec2665c9bb10/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[53,54,55,56,57,58,59,60],"take":"subject1/o2/4/cam4","frame_ids":[53,54,55,56,57,58,59,60]} +{"filtered_tile_id":"69fc843a4fb2ec2665c9bb10:52","filtered_window_id":"69fc843a4fb2ec2665c9bb10","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/69fc843a4fb2ec2665c9bb10/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[57,58,59,60,61,62,63,64],"take":"subject1/o2/4/cam4","frame_ids":[57,58,59,60,61,62,63,64]} +{"filtered_tile_id":"6a202000d175991656a8699c:0","filtered_window_id":"6a202000d175991656a8699c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a202000d175991656a8699c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[343,344,345,346,347,348,349,350],"take":"subject1/k2/0/cam4","frame_ids":[343,344,345,346,347,348,349,350]} +{"filtered_tile_id":"6a202000d175991656a8699c:8","filtered_window_id":"6a202000d175991656a8699c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a202000d175991656a8699c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[351,352,353,354,355,356,357,358],"take":"subject1/k2/0/cam4","frame_ids":[351,352,353,354,355,356,357,358]} +{"filtered_tile_id":"6a202000d175991656a8699c:16","filtered_window_id":"6a202000d175991656a8699c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a202000d175991656a8699c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[359,360,361,362,363,364,365,366],"take":"subject1/k2/0/cam4","frame_ids":[359,360,361,362,363,364,365,366]} +{"filtered_tile_id":"6a202000d175991656a8699c:24","filtered_window_id":"6a202000d175991656a8699c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a202000d175991656a8699c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[367,368,369,370,371,372,373,374],"take":"subject1/k2/0/cam4","frame_ids":[367,368,369,370,371,372,373,374]} +{"filtered_tile_id":"6a202000d175991656a8699c:32","filtered_window_id":"6a202000d175991656a8699c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a202000d175991656a8699c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[375,376,377,378,379,380,381,382],"take":"subject1/k2/0/cam4","frame_ids":[375,376,377,378,379,380,381,382]} +{"filtered_tile_id":"6a202000d175991656a8699c:40","filtered_window_id":"6a202000d175991656a8699c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a202000d175991656a8699c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject1/k2/0/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"6a202000d175991656a8699c:48","filtered_window_id":"6a202000d175991656a8699c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a202000d175991656a8699c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject1/k2/0/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"6a202000d175991656a8699c:52","filtered_window_id":"6a202000d175991656a8699c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a202000d175991656a8699c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject1/k2/0/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"6a2c9b561472b6770b6f0443:0","filtered_window_id":"6a2c9b561472b6770b6f0443","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a2c9b561472b6770b6f0443/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject1/o1/6/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"6a2c9b561472b6770b6f0443:8","filtered_window_id":"6a2c9b561472b6770b6f0443","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a2c9b561472b6770b6f0443/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[398,399,400,401,402,403,404,405],"take":"subject1/o1/6/cam4","frame_ids":[398,399,400,401,402,403,404,405]} +{"filtered_tile_id":"6a2c9b561472b6770b6f0443:16","filtered_window_id":"6a2c9b561472b6770b6f0443","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a2c9b561472b6770b6f0443/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[406,407,408,409,410,411,412,413],"take":"subject1/o1/6/cam4","frame_ids":[406,407,408,409,410,411,412,413]} +{"filtered_tile_id":"6a2c9b561472b6770b6f0443:24","filtered_window_id":"6a2c9b561472b6770b6f0443","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a2c9b561472b6770b6f0443/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[414,415,416,417,418,419,420,421],"take":"subject1/o1/6/cam4","frame_ids":[414,415,416,417,418,419,420,421]} +{"filtered_tile_id":"6a2c9b561472b6770b6f0443:31","filtered_window_id":"6a2c9b561472b6770b6f0443","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a2c9b561472b6770b6f0443/native_gt.npz","filtered_start_offset":31,"expected_frame_ids":[421,422,423,424,425,426,427,428],"take":"subject1/o1/6/cam4","frame_ids":[421,422,423,424,425,426,427,428]} +{"filtered_tile_id":"6a6a475a7faffd975915a645:0","filtered_window_id":"6a6a475a7faffd975915a645","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a6a475a7faffd975915a645/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject1/k1/1/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"6a6a475a7faffd975915a645:2","filtered_window_id":"6a6a475a7faffd975915a645","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a6a475a7faffd975915a645/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[474,475,476,477,478,479,480,481],"take":"subject1/k1/1/cam4","frame_ids":[474,475,476,477,478,479,480,481]} +{"filtered_tile_id":"6a94ca0e32cbd3d52592ea57:0","filtered_window_id":"6a94ca0e32cbd3d52592ea57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a94ca0e32cbd3d52592ea57/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[479,480,481,482,483,484,485,486],"take":"subject2/h2/3/cam4","frame_ids":[479,480,481,482,483,484,485,486]} +{"filtered_tile_id":"6a94ca0e32cbd3d52592ea57:8","filtered_window_id":"6a94ca0e32cbd3d52592ea57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a94ca0e32cbd3d52592ea57/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject2/h2/3/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"6a94ca0e32cbd3d52592ea57:16","filtered_window_id":"6a94ca0e32cbd3d52592ea57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a94ca0e32cbd3d52592ea57/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[495,496,497,498,499,500,501,502],"take":"subject2/h2/3/cam4","frame_ids":[495,496,497,498,499,500,501,502]} +{"filtered_tile_id":"6a94ca0e32cbd3d52592ea57:24","filtered_window_id":"6a94ca0e32cbd3d52592ea57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a94ca0e32cbd3d52592ea57/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[503,504,505,506,507,508,509,510],"take":"subject2/h2/3/cam4","frame_ids":[503,504,505,506,507,508,509,510]} +{"filtered_tile_id":"6a94ca0e32cbd3d52592ea57:32","filtered_window_id":"6a94ca0e32cbd3d52592ea57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a94ca0e32cbd3d52592ea57/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[511,512,513,514,515,516,517,518],"take":"subject2/h2/3/cam4","frame_ids":[511,512,513,514,515,516,517,518]} +{"filtered_tile_id":"6a94ca0e32cbd3d52592ea57:40","filtered_window_id":"6a94ca0e32cbd3d52592ea57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a94ca0e32cbd3d52592ea57/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[519,520,521,522,523,524,525,526],"take":"subject2/h2/3/cam4","frame_ids":[519,520,521,522,523,524,525,526]} +{"filtered_tile_id":"6a94ca0e32cbd3d52592ea57:48","filtered_window_id":"6a94ca0e32cbd3d52592ea57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a94ca0e32cbd3d52592ea57/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[527,528,529,530,531,532,533,534],"take":"subject2/h2/3/cam4","frame_ids":[527,528,529,530,531,532,533,534]} +{"filtered_tile_id":"6a94ca0e32cbd3d52592ea57:52","filtered_window_id":"6a94ca0e32cbd3d52592ea57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6a94ca0e32cbd3d52592ea57/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[531,532,533,534,535,536,537,538],"take":"subject2/h2/3/cam4","frame_ids":[531,532,533,534,535,536,537,538]} +{"filtered_tile_id":"6ad636775cbf73f3eecfea29:0","filtered_window_id":"6ad636775cbf73f3eecfea29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ad636775cbf73f3eecfea29/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[988,989,990,991,992,993,994,995],"take":"subject2/h1/3/cam4","frame_ids":[988,989,990,991,992,993,994,995]} +{"filtered_tile_id":"6ad636775cbf73f3eecfea29:8","filtered_window_id":"6ad636775cbf73f3eecfea29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ad636775cbf73f3eecfea29/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[996,997,998,999,1000,1001,1002,1003],"take":"subject2/h1/3/cam4","frame_ids":[996,997,998,999,1000,1001,1002,1003]} +{"filtered_tile_id":"6bde544078c57b4e3ab7bb35:0","filtered_window_id":"6bde544078c57b4e3ab7bb35","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6bde544078c57b4e3ab7bb35/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[888,889,890,891,892,893,894,895],"take":"subject3/k1/3/cam4","frame_ids":[888,889,890,891,892,893,894,895]} +{"filtered_tile_id":"6bde544078c57b4e3ab7bb35:8","filtered_window_id":"6bde544078c57b4e3ab7bb35","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6bde544078c57b4e3ab7bb35/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[896,897,898,899,900,901,902,903],"take":"subject3/k1/3/cam4","frame_ids":[896,897,898,899,900,901,902,903]} +{"filtered_tile_id":"6bde544078c57b4e3ab7bb35:16","filtered_window_id":"6bde544078c57b4e3ab7bb35","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6bde544078c57b4e3ab7bb35/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[904,905,906,907,908,909,910,911],"take":"subject3/k1/3/cam4","frame_ids":[904,905,906,907,908,909,910,911]} +{"filtered_tile_id":"6bde544078c57b4e3ab7bb35:24","filtered_window_id":"6bde544078c57b4e3ab7bb35","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6bde544078c57b4e3ab7bb35/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[912,913,914,915,916,917,918,919],"take":"subject3/k1/3/cam4","frame_ids":[912,913,914,915,916,917,918,919]} +{"filtered_tile_id":"6bde544078c57b4e3ab7bb35:32","filtered_window_id":"6bde544078c57b4e3ab7bb35","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6bde544078c57b4e3ab7bb35/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[920,921,922,923,924,925,926,927],"take":"subject3/k1/3/cam4","frame_ids":[920,921,922,923,924,925,926,927]} +{"filtered_tile_id":"6bde544078c57b4e3ab7bb35:40","filtered_window_id":"6bde544078c57b4e3ab7bb35","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6bde544078c57b4e3ab7bb35/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[928,929,930,931,932,933,934,935],"take":"subject3/k1/3/cam4","frame_ids":[928,929,930,931,932,933,934,935]} +{"filtered_tile_id":"6bde544078c57b4e3ab7bb35:48","filtered_window_id":"6bde544078c57b4e3ab7bb35","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6bde544078c57b4e3ab7bb35/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[936,937,938,939,940,941,942,943],"take":"subject3/k1/3/cam4","frame_ids":[936,937,938,939,940,941,942,943]} +{"filtered_tile_id":"6bde544078c57b4e3ab7bb35:52","filtered_window_id":"6bde544078c57b4e3ab7bb35","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6bde544078c57b4e3ab7bb35/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[940,941,942,943,944,945,946,947],"take":"subject3/k1/3/cam4","frame_ids":[940,941,942,943,944,945,946,947]} +{"filtered_tile_id":"6becd7f7f3bf89b93feea9b2:0","filtered_window_id":"6becd7f7f3bf89b93feea9b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6becd7f7f3bf89b93feea9b2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[7,8,9,10,11,12,13,14],"take":"subject3/k1/2/cam4","frame_ids":[7,8,9,10,11,12,13,14]} +{"filtered_tile_id":"6becd7f7f3bf89b93feea9b2:8","filtered_window_id":"6becd7f7f3bf89b93feea9b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6becd7f7f3bf89b93feea9b2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[15,16,17,18,19,20,21,22],"take":"subject3/k1/2/cam4","frame_ids":[15,16,17,18,19,20,21,22]} +{"filtered_tile_id":"6becd7f7f3bf89b93feea9b2:16","filtered_window_id":"6becd7f7f3bf89b93feea9b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6becd7f7f3bf89b93feea9b2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[23,24,25,26,27,28,29,30],"take":"subject3/k1/2/cam4","frame_ids":[23,24,25,26,27,28,29,30]} +{"filtered_tile_id":"6becd7f7f3bf89b93feea9b2:24","filtered_window_id":"6becd7f7f3bf89b93feea9b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6becd7f7f3bf89b93feea9b2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[31,32,33,34,35,36,37,38],"take":"subject3/k1/2/cam4","frame_ids":[31,32,33,34,35,36,37,38]} +{"filtered_tile_id":"6becd7f7f3bf89b93feea9b2:32","filtered_window_id":"6becd7f7f3bf89b93feea9b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6becd7f7f3bf89b93feea9b2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[39,40,41,42,43,44,45,46],"take":"subject3/k1/2/cam4","frame_ids":[39,40,41,42,43,44,45,46]} +{"filtered_tile_id":"6becd7f7f3bf89b93feea9b2:40","filtered_window_id":"6becd7f7f3bf89b93feea9b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6becd7f7f3bf89b93feea9b2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[47,48,49,50,51,52,53,54],"take":"subject3/k1/2/cam4","frame_ids":[47,48,49,50,51,52,53,54]} +{"filtered_tile_id":"6becd7f7f3bf89b93feea9b2:48","filtered_window_id":"6becd7f7f3bf89b93feea9b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6becd7f7f3bf89b93feea9b2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[55,56,57,58,59,60,61,62],"take":"subject3/k1/2/cam4","frame_ids":[55,56,57,58,59,60,61,62]} +{"filtered_tile_id":"6becd7f7f3bf89b93feea9b2:52","filtered_window_id":"6becd7f7f3bf89b93feea9b2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6becd7f7f3bf89b93feea9b2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[59,60,61,62,63,64,65,66],"take":"subject3/k1/2/cam4","frame_ids":[59,60,61,62,63,64,65,66]} +{"filtered_tile_id":"6c0e87b6241571416db0bf01:0","filtered_window_id":"6c0e87b6241571416db0bf01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c0e87b6241571416db0bf01/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject2/o1/2/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"6c0e87b6241571416db0bf01:8","filtered_window_id":"6c0e87b6241571416db0bf01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c0e87b6241571416db0bf01/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject2/o1/2/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"6c0e87b6241571416db0bf01:16","filtered_window_id":"6c0e87b6241571416db0bf01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c0e87b6241571416db0bf01/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject2/o1/2/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"6c0e87b6241571416db0bf01:24","filtered_window_id":"6c0e87b6241571416db0bf01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c0e87b6241571416db0bf01/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject2/o1/2/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"6c0e87b6241571416db0bf01:32","filtered_window_id":"6c0e87b6241571416db0bf01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c0e87b6241571416db0bf01/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject2/o1/2/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"6c0e87b6241571416db0bf01:40","filtered_window_id":"6c0e87b6241571416db0bf01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c0e87b6241571416db0bf01/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject2/o1/2/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"6c0e87b6241571416db0bf01:48","filtered_window_id":"6c0e87b6241571416db0bf01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c0e87b6241571416db0bf01/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[468,469,470,471,472,473,474,475],"take":"subject2/o1/2/cam4","frame_ids":[468,469,470,471,472,473,474,475]} +{"filtered_tile_id":"6c0e87b6241571416db0bf01:52","filtered_window_id":"6c0e87b6241571416db0bf01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c0e87b6241571416db0bf01/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject2/o1/2/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"6c30f085a1a17c3d6a1b5c33:0","filtered_window_id":"6c30f085a1a17c3d6a1b5c33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c30f085a1a17c3d6a1b5c33/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject1/o1/1/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"6c30f085a1a17c3d6a1b5c33:8","filtered_window_id":"6c30f085a1a17c3d6a1b5c33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c30f085a1a17c3d6a1b5c33/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject1/o1/1/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"6c30f085a1a17c3d6a1b5c33:16","filtered_window_id":"6c30f085a1a17c3d6a1b5c33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c30f085a1a17c3d6a1b5c33/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject1/o1/1/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"6c30f085a1a17c3d6a1b5c33:24","filtered_window_id":"6c30f085a1a17c3d6a1b5c33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c30f085a1a17c3d6a1b5c33/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject1/o1/1/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"6c30f085a1a17c3d6a1b5c33:32","filtered_window_id":"6c30f085a1a17c3d6a1b5c33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c30f085a1a17c3d6a1b5c33/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject1/o1/1/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"6c30f085a1a17c3d6a1b5c33:40","filtered_window_id":"6c30f085a1a17c3d6a1b5c33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c30f085a1a17c3d6a1b5c33/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject1/o1/1/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"6c30f085a1a17c3d6a1b5c33:48","filtered_window_id":"6c30f085a1a17c3d6a1b5c33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c30f085a1a17c3d6a1b5c33/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject1/o1/1/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"6c30f085a1a17c3d6a1b5c33:52","filtered_window_id":"6c30f085a1a17c3d6a1b5c33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c30f085a1a17c3d6a1b5c33/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[215,216,217,218,219,220,221,222],"take":"subject1/o1/1/cam4","frame_ids":[215,216,217,218,219,220,221,222]} +{"filtered_tile_id":"6c39fdcbb8c67d5d565bc253:0","filtered_window_id":"6c39fdcbb8c67d5d565bc253","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c39fdcbb8c67d5d565bc253/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[533,534,535,536,537,538,539,540],"take":"subject2/k2/3/cam4","frame_ids":[533,534,535,536,537,538,539,540]} +{"filtered_tile_id":"6c39fdcbb8c67d5d565bc253:8","filtered_window_id":"6c39fdcbb8c67d5d565bc253","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c39fdcbb8c67d5d565bc253/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject2/k2/3/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"6c39fdcbb8c67d5d565bc253:16","filtered_window_id":"6c39fdcbb8c67d5d565bc253","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c39fdcbb8c67d5d565bc253/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[549,550,551,552,553,554,555,556],"take":"subject2/k2/3/cam4","frame_ids":[549,550,551,552,553,554,555,556]} +{"filtered_tile_id":"6c39fdcbb8c67d5d565bc253:24","filtered_window_id":"6c39fdcbb8c67d5d565bc253","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c39fdcbb8c67d5d565bc253/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[557,558,559,560,561,562,563,564],"take":"subject2/k2/3/cam4","frame_ids":[557,558,559,560,561,562,563,564]} +{"filtered_tile_id":"6c39fdcbb8c67d5d565bc253:32","filtered_window_id":"6c39fdcbb8c67d5d565bc253","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c39fdcbb8c67d5d565bc253/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[565,566,567,568,569,570,571,572],"take":"subject2/k2/3/cam4","frame_ids":[565,566,567,568,569,570,571,572]} +{"filtered_tile_id":"6c39fdcbb8c67d5d565bc253:40","filtered_window_id":"6c39fdcbb8c67d5d565bc253","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c39fdcbb8c67d5d565bc253/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[573,574,575,576,577,578,579,580],"take":"subject2/k2/3/cam4","frame_ids":[573,574,575,576,577,578,579,580]} +{"filtered_tile_id":"6c39fdcbb8c67d5d565bc253:48","filtered_window_id":"6c39fdcbb8c67d5d565bc253","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c39fdcbb8c67d5d565bc253/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[581,582,583,584,585,586,587,588],"take":"subject2/k2/3/cam4","frame_ids":[581,582,583,584,585,586,587,588]} +{"filtered_tile_id":"6c39fdcbb8c67d5d565bc253:52","filtered_window_id":"6c39fdcbb8c67d5d565bc253","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c39fdcbb8c67d5d565bc253/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[585,586,587,588,589,590,591,592],"take":"subject2/k2/3/cam4","frame_ids":[585,586,587,588,589,590,591,592]} +{"filtered_tile_id":"6c8d0317c22c8e2efb655547:0","filtered_window_id":"6c8d0317c22c8e2efb655547","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c8d0317c22c8e2efb655547/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[642,643,644,645,646,647,648,649],"take":"subject1/o1/1/cam4","frame_ids":[642,643,644,645,646,647,648,649]} +{"filtered_tile_id":"6c8d0317c22c8e2efb655547:8","filtered_window_id":"6c8d0317c22c8e2efb655547","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c8d0317c22c8e2efb655547/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[650,651,652,653,654,655,656,657],"take":"subject1/o1/1/cam4","frame_ids":[650,651,652,653,654,655,656,657]} +{"filtered_tile_id":"6c8d0317c22c8e2efb655547:16","filtered_window_id":"6c8d0317c22c8e2efb655547","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c8d0317c22c8e2efb655547/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[658,659,660,661,662,663,664,665],"take":"subject1/o1/1/cam4","frame_ids":[658,659,660,661,662,663,664,665]} +{"filtered_tile_id":"6c8d0317c22c8e2efb655547:24","filtered_window_id":"6c8d0317c22c8e2efb655547","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c8d0317c22c8e2efb655547/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[666,667,668,669,670,671,672,673],"take":"subject1/o1/1/cam4","frame_ids":[666,667,668,669,670,671,672,673]} +{"filtered_tile_id":"6c8d0317c22c8e2efb655547:32","filtered_window_id":"6c8d0317c22c8e2efb655547","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c8d0317c22c8e2efb655547/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[674,675,676,677,678,679,680,681],"take":"subject1/o1/1/cam4","frame_ids":[674,675,676,677,678,679,680,681]} +{"filtered_tile_id":"6c8d0317c22c8e2efb655547:40","filtered_window_id":"6c8d0317c22c8e2efb655547","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c8d0317c22c8e2efb655547/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[682,683,684,685,686,687,688,689],"take":"subject1/o1/1/cam4","frame_ids":[682,683,684,685,686,687,688,689]} +{"filtered_tile_id":"6c8d0317c22c8e2efb655547:48","filtered_window_id":"6c8d0317c22c8e2efb655547","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c8d0317c22c8e2efb655547/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[690,691,692,693,694,695,696,697],"take":"subject1/o1/1/cam4","frame_ids":[690,691,692,693,694,695,696,697]} +{"filtered_tile_id":"6c8d0317c22c8e2efb655547:52","filtered_window_id":"6c8d0317c22c8e2efb655547","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6c8d0317c22c8e2efb655547/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[694,695,696,697,698,699,700,701],"take":"subject1/o1/1/cam4","frame_ids":[694,695,696,697,698,699,700,701]} +{"filtered_tile_id":"6d81b963bc830460ff487d6a:0","filtered_window_id":"6d81b963bc830460ff487d6a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6d81b963bc830460ff487d6a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject1/h1/4/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"6d81b963bc830460ff487d6a:8","filtered_window_id":"6d81b963bc830460ff487d6a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6d81b963bc830460ff487d6a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject1/h1/4/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"6d81b963bc830460ff487d6a:16","filtered_window_id":"6d81b963bc830460ff487d6a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6d81b963bc830460ff487d6a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject1/h1/4/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"6d81b963bc830460ff487d6a:24","filtered_window_id":"6d81b963bc830460ff487d6a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6d81b963bc830460ff487d6a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject1/h1/4/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"6d81b963bc830460ff487d6a:32","filtered_window_id":"6d81b963bc830460ff487d6a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6d81b963bc830460ff487d6a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject1/h1/4/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"6d81b963bc830460ff487d6a:40","filtered_window_id":"6d81b963bc830460ff487d6a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6d81b963bc830460ff487d6a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject1/h1/4/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"6d81b963bc830460ff487d6a:48","filtered_window_id":"6d81b963bc830460ff487d6a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6d81b963bc830460ff487d6a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject1/h1/4/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"6d81b963bc830460ff487d6a:52","filtered_window_id":"6d81b963bc830460ff487d6a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6d81b963bc830460ff487d6a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject1/h1/4/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"6db651428b48eb66b9ef9642:0","filtered_window_id":"6db651428b48eb66b9ef9642","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6db651428b48eb66b9ef9642/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject2/h1/1/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"6db651428b48eb66b9ef9642:8","filtered_window_id":"6db651428b48eb66b9ef9642","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6db651428b48eb66b9ef9642/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject2/h1/1/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"6db651428b48eb66b9ef9642:16","filtered_window_id":"6db651428b48eb66b9ef9642","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6db651428b48eb66b9ef9642/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[374,375,376,377,378,379,380,381],"take":"subject2/h1/1/cam4","frame_ids":[374,375,376,377,378,379,380,381]} +{"filtered_tile_id":"6db651428b48eb66b9ef9642:24","filtered_window_id":"6db651428b48eb66b9ef9642","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6db651428b48eb66b9ef9642/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[382,383,384,385,386,387,388,389],"take":"subject2/h1/1/cam4","frame_ids":[382,383,384,385,386,387,388,389]} +{"filtered_tile_id":"6db651428b48eb66b9ef9642:32","filtered_window_id":"6db651428b48eb66b9ef9642","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6db651428b48eb66b9ef9642/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject2/h1/1/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"6db651428b48eb66b9ef9642:40","filtered_window_id":"6db651428b48eb66b9ef9642","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6db651428b48eb66b9ef9642/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[398,399,400,401,402,403,404,405],"take":"subject2/h1/1/cam4","frame_ids":[398,399,400,401,402,403,404,405]} +{"filtered_tile_id":"6db651428b48eb66b9ef9642:48","filtered_window_id":"6db651428b48eb66b9ef9642","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6db651428b48eb66b9ef9642/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[406,407,408,409,410,411,412,413],"take":"subject2/h1/1/cam4","frame_ids":[406,407,408,409,410,411,412,413]} +{"filtered_tile_id":"6db651428b48eb66b9ef9642:52","filtered_window_id":"6db651428b48eb66b9ef9642","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6db651428b48eb66b9ef9642/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject2/h1/1/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"6e33c5e57af97bd83bec833c:0","filtered_window_id":"6e33c5e57af97bd83bec833c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6e33c5e57af97bd83bec833c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o1/3/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"6e33c5e57af97bd83bec833c:8","filtered_window_id":"6e33c5e57af97bd83bec833c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6e33c5e57af97bd83bec833c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o1/3/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"6e33c5e57af97bd83bec833c:16","filtered_window_id":"6e33c5e57af97bd83bec833c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6e33c5e57af97bd83bec833c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o1/3/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"6e33c5e57af97bd83bec833c:24","filtered_window_id":"6e33c5e57af97bd83bec833c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6e33c5e57af97bd83bec833c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o1/3/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"6e33c5e57af97bd83bec833c:32","filtered_window_id":"6e33c5e57af97bd83bec833c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6e33c5e57af97bd83bec833c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o1/3/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"6e33c5e57af97bd83bec833c:37","filtered_window_id":"6e33c5e57af97bd83bec833c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6e33c5e57af97bd83bec833c/native_gt.npz","filtered_start_offset":37,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject1/o1/3/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"6e6df413d660979fa58b04ae:0","filtered_window_id":"6e6df413d660979fa58b04ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6e6df413d660979fa58b04ae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[892,893,894,895,896,897,898,899],"take":"subject2/h1/3/cam4","frame_ids":[892,893,894,895,896,897,898,899]} +{"filtered_tile_id":"6e6df413d660979fa58b04ae:8","filtered_window_id":"6e6df413d660979fa58b04ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6e6df413d660979fa58b04ae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[900,901,902,903,904,905,906,907],"take":"subject2/h1/3/cam4","frame_ids":[900,901,902,903,904,905,906,907]} +{"filtered_tile_id":"6e6df413d660979fa58b04ae:11","filtered_window_id":"6e6df413d660979fa58b04ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6e6df413d660979fa58b04ae/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[903,904,905,906,907,908,909,910],"take":"subject2/h1/3/cam4","frame_ids":[903,904,905,906,907,908,909,910]} +{"filtered_tile_id":"6eaae202eed79a0345b81a66:0","filtered_window_id":"6eaae202eed79a0345b81a66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eaae202eed79a0345b81a66/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject2/k2/0/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"6eaae202eed79a0345b81a66:8","filtered_window_id":"6eaae202eed79a0345b81a66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eaae202eed79a0345b81a66/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject2/k2/0/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"6eaae202eed79a0345b81a66:16","filtered_window_id":"6eaae202eed79a0345b81a66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eaae202eed79a0345b81a66/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject2/k2/0/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"6eaae202eed79a0345b81a66:24","filtered_window_id":"6eaae202eed79a0345b81a66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eaae202eed79a0345b81a66/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject2/k2/0/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"6eaae202eed79a0345b81a66:32","filtered_window_id":"6eaae202eed79a0345b81a66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eaae202eed79a0345b81a66/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject2/k2/0/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"6eaae202eed79a0345b81a66:40","filtered_window_id":"6eaae202eed79a0345b81a66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eaae202eed79a0345b81a66/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject2/k2/0/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"6eaae202eed79a0345b81a66:48","filtered_window_id":"6eaae202eed79a0345b81a66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eaae202eed79a0345b81a66/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject2/k2/0/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"6eaae202eed79a0345b81a66:52","filtered_window_id":"6eaae202eed79a0345b81a66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eaae202eed79a0345b81a66/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[224,225,226,227,228,229,230,231],"take":"subject2/k2/0/cam4","frame_ids":[224,225,226,227,228,229,230,231]} +{"filtered_tile_id":"6ecf98eef9951ddd74c347a5:0","filtered_window_id":"6ecf98eef9951ddd74c347a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ecf98eef9951ddd74c347a5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/o2/3/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"6ecf98eef9951ddd74c347a5:8","filtered_window_id":"6ecf98eef9951ddd74c347a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ecf98eef9951ddd74c347a5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/o2/3/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"6ecf98eef9951ddd74c347a5:16","filtered_window_id":"6ecf98eef9951ddd74c347a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ecf98eef9951ddd74c347a5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/o2/3/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"6ecf98eef9951ddd74c347a5:24","filtered_window_id":"6ecf98eef9951ddd74c347a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ecf98eef9951ddd74c347a5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/o2/3/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"6ecf98eef9951ddd74c347a5:32","filtered_window_id":"6ecf98eef9951ddd74c347a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ecf98eef9951ddd74c347a5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/o2/3/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"6ecf98eef9951ddd74c347a5:40","filtered_window_id":"6ecf98eef9951ddd74c347a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ecf98eef9951ddd74c347a5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[56,57,58,59,60,61,62,63],"take":"subject2/o2/3/cam4","frame_ids":[56,57,58,59,60,61,62,63]} +{"filtered_tile_id":"6ecf98eef9951ddd74c347a5:48","filtered_window_id":"6ecf98eef9951ddd74c347a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ecf98eef9951ddd74c347a5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject2/o2/3/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"6ecf98eef9951ddd74c347a5:52","filtered_window_id":"6ecf98eef9951ddd74c347a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ecf98eef9951ddd74c347a5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject2/o2/3/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"6eda9c6961c03dc022716a15:0","filtered_window_id":"6eda9c6961c03dc022716a15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eda9c6961c03dc022716a15/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[58,59,60,61,62,63,64,65],"take":"subject1/o1/3/cam4","frame_ids":[58,59,60,61,62,63,64,65]} +{"filtered_tile_id":"6eda9c6961c03dc022716a15:8","filtered_window_id":"6eda9c6961c03dc022716a15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eda9c6961c03dc022716a15/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[66,67,68,69,70,71,72,73],"take":"subject1/o1/3/cam4","frame_ids":[66,67,68,69,70,71,72,73]} +{"filtered_tile_id":"6eda9c6961c03dc022716a15:16","filtered_window_id":"6eda9c6961c03dc022716a15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eda9c6961c03dc022716a15/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[74,75,76,77,78,79,80,81],"take":"subject1/o1/3/cam4","frame_ids":[74,75,76,77,78,79,80,81]} +{"filtered_tile_id":"6eda9c6961c03dc022716a15:24","filtered_window_id":"6eda9c6961c03dc022716a15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eda9c6961c03dc022716a15/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[82,83,84,85,86,87,88,89],"take":"subject1/o1/3/cam4","frame_ids":[82,83,84,85,86,87,88,89]} +{"filtered_tile_id":"6eda9c6961c03dc022716a15:32","filtered_window_id":"6eda9c6961c03dc022716a15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eda9c6961c03dc022716a15/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject1/o1/3/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"6eda9c6961c03dc022716a15:38","filtered_window_id":"6eda9c6961c03dc022716a15","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6eda9c6961c03dc022716a15/native_gt.npz","filtered_start_offset":38,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject1/o1/3/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"6ef8eff2c8efc5e3288c17ae:0","filtered_window_id":"6ef8eff2c8efc5e3288c17ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ef8eff2c8efc5e3288c17ae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[723,724,725,726,727,728,729,730],"take":"subject1/k1/1/cam4","frame_ids":[723,724,725,726,727,728,729,730]} +{"filtered_tile_id":"6ef8eff2c8efc5e3288c17ae:2","filtered_window_id":"6ef8eff2c8efc5e3288c17ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6ef8eff2c8efc5e3288c17ae/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[725,726,727,728,729,730,731,732],"take":"subject1/k1/1/cam4","frame_ids":[725,726,727,728,729,730,731,732]} +{"filtered_tile_id":"6f3edf9076984b1ea370c35b:0","filtered_window_id":"6f3edf9076984b1ea370c35b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f3edf9076984b1ea370c35b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject2/h1/3/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"6f3edf9076984b1ea370c35b:2","filtered_window_id":"6f3edf9076984b1ea370c35b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f3edf9076984b1ea370c35b/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[86,87,88,89,90,91,92,93],"take":"subject2/h1/3/cam4","frame_ids":[86,87,88,89,90,91,92,93]} +{"filtered_tile_id":"6f46096b59050a5eef903719:0","filtered_window_id":"6f46096b59050a5eef903719","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f46096b59050a5eef903719/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject2/k1/5/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"6f46096b59050a5eef903719:8","filtered_window_id":"6f46096b59050a5eef903719","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f46096b59050a5eef903719/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[98,99,100,101,102,103,104,105],"take":"subject2/k1/5/cam4","frame_ids":[98,99,100,101,102,103,104,105]} +{"filtered_tile_id":"6f46096b59050a5eef903719:16","filtered_window_id":"6f46096b59050a5eef903719","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f46096b59050a5eef903719/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[106,107,108,109,110,111,112,113],"take":"subject2/k1/5/cam4","frame_ids":[106,107,108,109,110,111,112,113]} +{"filtered_tile_id":"6f46096b59050a5eef903719:24","filtered_window_id":"6f46096b59050a5eef903719","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f46096b59050a5eef903719/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject2/k1/5/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"6f46096b59050a5eef903719:32","filtered_window_id":"6f46096b59050a5eef903719","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f46096b59050a5eef903719/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject2/k1/5/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"6f46096b59050a5eef903719:40","filtered_window_id":"6f46096b59050a5eef903719","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f46096b59050a5eef903719/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject2/k1/5/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"6f46096b59050a5eef903719:48","filtered_window_id":"6f46096b59050a5eef903719","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f46096b59050a5eef903719/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject2/k1/5/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"6f46096b59050a5eef903719:52","filtered_window_id":"6f46096b59050a5eef903719","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f46096b59050a5eef903719/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[142,143,144,145,146,147,148,149],"take":"subject2/k1/5/cam4","frame_ids":[142,143,144,145,146,147,148,149]} +{"filtered_tile_id":"6f4bc5379086e979edd3a516:0","filtered_window_id":"6f4bc5379086e979edd3a516","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f4bc5379086e979edd3a516/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject1/o1/7/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"6f4bc5379086e979edd3a516:8","filtered_window_id":"6f4bc5379086e979edd3a516","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f4bc5379086e979edd3a516/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[77,78,79,80,81,82,83,84],"take":"subject1/o1/7/cam4","frame_ids":[77,78,79,80,81,82,83,84]} +{"filtered_tile_id":"6f4bc5379086e979edd3a516:16","filtered_window_id":"6f4bc5379086e979edd3a516","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f4bc5379086e979edd3a516/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject1/o1/7/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"6f4bc5379086e979edd3a516:24","filtered_window_id":"6f4bc5379086e979edd3a516","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f4bc5379086e979edd3a516/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[93,94,95,96,97,98,99,100],"take":"subject1/o1/7/cam4","frame_ids":[93,94,95,96,97,98,99,100]} +{"filtered_tile_id":"6f4bc5379086e979edd3a516:32","filtered_window_id":"6f4bc5379086e979edd3a516","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f4bc5379086e979edd3a516/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[101,102,103,104,105,106,107,108],"take":"subject1/o1/7/cam4","frame_ids":[101,102,103,104,105,106,107,108]} +{"filtered_tile_id":"6f4bc5379086e979edd3a516:40","filtered_window_id":"6f4bc5379086e979edd3a516","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f4bc5379086e979edd3a516/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[109,110,111,112,113,114,115,116],"take":"subject1/o1/7/cam4","frame_ids":[109,110,111,112,113,114,115,116]} +{"filtered_tile_id":"6f4bc5379086e979edd3a516:44","filtered_window_id":"6f4bc5379086e979edd3a516","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f4bc5379086e979edd3a516/native_gt.npz","filtered_start_offset":44,"expected_frame_ids":[113,114,115,116,117,118,119,120],"take":"subject1/o1/7/cam4","frame_ids":[113,114,115,116,117,118,119,120]} +{"filtered_tile_id":"6f58d1f9eafb6cfea1f9ab59:0","filtered_window_id":"6f58d1f9eafb6cfea1f9ab59","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f58d1f9eafb6cfea1f9ab59/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[585,586,587,588,589,590,591,592],"take":"subject2/k1/1/cam4","frame_ids":[585,586,587,588,589,590,591,592]} +{"filtered_tile_id":"6f58d1f9eafb6cfea1f9ab59:8","filtered_window_id":"6f58d1f9eafb6cfea1f9ab59","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f58d1f9eafb6cfea1f9ab59/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[593,594,595,596,597,598,599,600],"take":"subject2/k1/1/cam4","frame_ids":[593,594,595,596,597,598,599,600]} +{"filtered_tile_id":"6f58d1f9eafb6cfea1f9ab59:16","filtered_window_id":"6f58d1f9eafb6cfea1f9ab59","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f58d1f9eafb6cfea1f9ab59/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[601,602,603,604,605,606,607,608],"take":"subject2/k1/1/cam4","frame_ids":[601,602,603,604,605,606,607,608]} +{"filtered_tile_id":"6f58d1f9eafb6cfea1f9ab59:24","filtered_window_id":"6f58d1f9eafb6cfea1f9ab59","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f58d1f9eafb6cfea1f9ab59/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[609,610,611,612,613,614,615,616],"take":"subject2/k1/1/cam4","frame_ids":[609,610,611,612,613,614,615,616]} +{"filtered_tile_id":"6f58d1f9eafb6cfea1f9ab59:32","filtered_window_id":"6f58d1f9eafb6cfea1f9ab59","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f58d1f9eafb6cfea1f9ab59/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[617,618,619,620,621,622,623,624],"take":"subject2/k1/1/cam4","frame_ids":[617,618,619,620,621,622,623,624]} +{"filtered_tile_id":"6f58d1f9eafb6cfea1f9ab59:40","filtered_window_id":"6f58d1f9eafb6cfea1f9ab59","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f58d1f9eafb6cfea1f9ab59/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[625,626,627,628,629,630,631,632],"take":"subject2/k1/1/cam4","frame_ids":[625,626,627,628,629,630,631,632]} +{"filtered_tile_id":"6f58d1f9eafb6cfea1f9ab59:48","filtered_window_id":"6f58d1f9eafb6cfea1f9ab59","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f58d1f9eafb6cfea1f9ab59/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[633,634,635,636,637,638,639,640],"take":"subject2/k1/1/cam4","frame_ids":[633,634,635,636,637,638,639,640]} +{"filtered_tile_id":"6f58d1f9eafb6cfea1f9ab59:49","filtered_window_id":"6f58d1f9eafb6cfea1f9ab59","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6f58d1f9eafb6cfea1f9ab59/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[634,635,636,637,638,639,640,641],"take":"subject2/k1/1/cam4","frame_ids":[634,635,636,637,638,639,640,641]} +{"filtered_tile_id":"6fefe25498cabbdf4760602b:0","filtered_window_id":"6fefe25498cabbdf4760602b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6fefe25498cabbdf4760602b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject2/h2/6/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"6fefe25498cabbdf4760602b:8","filtered_window_id":"6fefe25498cabbdf4760602b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6fefe25498cabbdf4760602b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject2/h2/6/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"6fefe25498cabbdf4760602b:16","filtered_window_id":"6fefe25498cabbdf4760602b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6fefe25498cabbdf4760602b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject2/h2/6/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"6fefe25498cabbdf4760602b:24","filtered_window_id":"6fefe25498cabbdf4760602b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6fefe25498cabbdf4760602b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject2/h2/6/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"6fefe25498cabbdf4760602b:32","filtered_window_id":"6fefe25498cabbdf4760602b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6fefe25498cabbdf4760602b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject2/h2/6/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"6fefe25498cabbdf4760602b:40","filtered_window_id":"6fefe25498cabbdf4760602b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/6fefe25498cabbdf4760602b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject2/h2/6/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"7008ff257f6bb5f56a855535:0","filtered_window_id":"7008ff257f6bb5f56a855535","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7008ff257f6bb5f56a855535/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject1/k1/1/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"7008ff257f6bb5f56a855535:8","filtered_window_id":"7008ff257f6bb5f56a855535","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7008ff257f6bb5f56a855535/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject1/k1/1/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"7008ff257f6bb5f56a855535:16","filtered_window_id":"7008ff257f6bb5f56a855535","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7008ff257f6bb5f56a855535/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject1/k1/1/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"7008ff257f6bb5f56a855535:24","filtered_window_id":"7008ff257f6bb5f56a855535","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7008ff257f6bb5f56a855535/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject1/k1/1/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"7008ff257f6bb5f56a855535:32","filtered_window_id":"7008ff257f6bb5f56a855535","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7008ff257f6bb5f56a855535/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject1/k1/1/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"7008ff257f6bb5f56a855535:40","filtered_window_id":"7008ff257f6bb5f56a855535","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7008ff257f6bb5f56a855535/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject1/k1/1/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"7008ff257f6bb5f56a855535:48","filtered_window_id":"7008ff257f6bb5f56a855535","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7008ff257f6bb5f56a855535/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject1/k1/1/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"7008ff257f6bb5f56a855535:52","filtered_window_id":"7008ff257f6bb5f56a855535","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7008ff257f6bb5f56a855535/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[232,233,234,235,236,237,238,239],"take":"subject1/k1/1/cam4","frame_ids":[232,233,234,235,236,237,238,239]} +{"filtered_tile_id":"7074b4d1a9b5afe18fff411a:0","filtered_window_id":"7074b4d1a9b5afe18fff411a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7074b4d1a9b5afe18fff411a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject2/h1/5/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"7074b4d1a9b5afe18fff411a:8","filtered_window_id":"7074b4d1a9b5afe18fff411a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7074b4d1a9b5afe18fff411a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[386,387,388,389,390,391,392,393],"take":"subject2/h1/5/cam4","frame_ids":[386,387,388,389,390,391,392,393]} +{"filtered_tile_id":"7074b4d1a9b5afe18fff411a:16","filtered_window_id":"7074b4d1a9b5afe18fff411a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7074b4d1a9b5afe18fff411a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[394,395,396,397,398,399,400,401],"take":"subject2/h1/5/cam4","frame_ids":[394,395,396,397,398,399,400,401]} +{"filtered_tile_id":"7074b4d1a9b5afe18fff411a:24","filtered_window_id":"7074b4d1a9b5afe18fff411a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7074b4d1a9b5afe18fff411a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[402,403,404,405,406,407,408,409],"take":"subject2/h1/5/cam4","frame_ids":[402,403,404,405,406,407,408,409]} +{"filtered_tile_id":"7074b4d1a9b5afe18fff411a:32","filtered_window_id":"7074b4d1a9b5afe18fff411a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7074b4d1a9b5afe18fff411a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject2/h1/5/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"7074b4d1a9b5afe18fff411a:40","filtered_window_id":"7074b4d1a9b5afe18fff411a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7074b4d1a9b5afe18fff411a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject2/h1/5/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"7074b4d1a9b5afe18fff411a:48","filtered_window_id":"7074b4d1a9b5afe18fff411a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7074b4d1a9b5afe18fff411a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[426,427,428,429,430,431,432,433],"take":"subject2/h1/5/cam4","frame_ids":[426,427,428,429,430,431,432,433]} +{"filtered_tile_id":"7074b4d1a9b5afe18fff411a:52","filtered_window_id":"7074b4d1a9b5afe18fff411a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7074b4d1a9b5afe18fff411a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[430,431,432,433,434,435,436,437],"take":"subject2/h1/5/cam4","frame_ids":[430,431,432,433,434,435,436,437]} +{"filtered_tile_id":"707f3269435397881f557ae3:0","filtered_window_id":"707f3269435397881f557ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/707f3269435397881f557ae3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject2/h1/0/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"707f3269435397881f557ae3:8","filtered_window_id":"707f3269435397881f557ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/707f3269435397881f557ae3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject2/h1/0/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"707f3269435397881f557ae3:16","filtered_window_id":"707f3269435397881f557ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/707f3269435397881f557ae3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject2/h1/0/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"707f3269435397881f557ae3:24","filtered_window_id":"707f3269435397881f557ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/707f3269435397881f557ae3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject2/h1/0/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"707f3269435397881f557ae3:32","filtered_window_id":"707f3269435397881f557ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/707f3269435397881f557ae3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject2/h1/0/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"707f3269435397881f557ae3:40","filtered_window_id":"707f3269435397881f557ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/707f3269435397881f557ae3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject2/h1/0/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"707f3269435397881f557ae3:48","filtered_window_id":"707f3269435397881f557ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/707f3269435397881f557ae3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[170,171,172,173,174,175,176,177],"take":"subject2/h1/0/cam4","frame_ids":[170,171,172,173,174,175,176,177]} +{"filtered_tile_id":"707f3269435397881f557ae3:52","filtered_window_id":"707f3269435397881f557ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/707f3269435397881f557ae3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject2/h1/0/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"70f7aa90b8d25cdee5390798:0","filtered_window_id":"70f7aa90b8d25cdee5390798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/70f7aa90b8d25cdee5390798/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[621,622,623,624,625,626,627,628],"take":"subject3/h2/7/cam4","frame_ids":[621,622,623,624,625,626,627,628]} +{"filtered_tile_id":"70f7aa90b8d25cdee5390798:8","filtered_window_id":"70f7aa90b8d25cdee5390798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/70f7aa90b8d25cdee5390798/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[629,630,631,632,633,634,635,636],"take":"subject3/h2/7/cam4","frame_ids":[629,630,631,632,633,634,635,636]} +{"filtered_tile_id":"70f7aa90b8d25cdee5390798:16","filtered_window_id":"70f7aa90b8d25cdee5390798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/70f7aa90b8d25cdee5390798/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[637,638,639,640,641,642,643,644],"take":"subject3/h2/7/cam4","frame_ids":[637,638,639,640,641,642,643,644]} +{"filtered_tile_id":"70f7aa90b8d25cdee5390798:24","filtered_window_id":"70f7aa90b8d25cdee5390798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/70f7aa90b8d25cdee5390798/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[645,646,647,648,649,650,651,652],"take":"subject3/h2/7/cam4","frame_ids":[645,646,647,648,649,650,651,652]} +{"filtered_tile_id":"70f7aa90b8d25cdee5390798:32","filtered_window_id":"70f7aa90b8d25cdee5390798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/70f7aa90b8d25cdee5390798/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[653,654,655,656,657,658,659,660],"take":"subject3/h2/7/cam4","frame_ids":[653,654,655,656,657,658,659,660]} +{"filtered_tile_id":"70f7aa90b8d25cdee5390798:40","filtered_window_id":"70f7aa90b8d25cdee5390798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/70f7aa90b8d25cdee5390798/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[661,662,663,664,665,666,667,668],"take":"subject3/h2/7/cam4","frame_ids":[661,662,663,664,665,666,667,668]} +{"filtered_tile_id":"70f7aa90b8d25cdee5390798:43","filtered_window_id":"70f7aa90b8d25cdee5390798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/70f7aa90b8d25cdee5390798/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[664,665,666,667,668,669,670,671],"take":"subject3/h2/7/cam4","frame_ids":[664,665,666,667,668,669,670,671]} +{"filtered_tile_id":"717f610e5ef7195ac02aa5f3:0","filtered_window_id":"717f610e5ef7195ac02aa5f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/717f610e5ef7195ac02aa5f3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[501,502,503,504,505,506,507,508],"take":"subject2/h2/6/cam4","frame_ids":[501,502,503,504,505,506,507,508]} +{"filtered_tile_id":"717f610e5ef7195ac02aa5f3:8","filtered_window_id":"717f610e5ef7195ac02aa5f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/717f610e5ef7195ac02aa5f3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[509,510,511,512,513,514,515,516],"take":"subject2/h2/6/cam4","frame_ids":[509,510,511,512,513,514,515,516]} +{"filtered_tile_id":"717f610e5ef7195ac02aa5f3:16","filtered_window_id":"717f610e5ef7195ac02aa5f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/717f610e5ef7195ac02aa5f3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[517,518,519,520,521,522,523,524],"take":"subject2/h2/6/cam4","frame_ids":[517,518,519,520,521,522,523,524]} +{"filtered_tile_id":"717f610e5ef7195ac02aa5f3:24","filtered_window_id":"717f610e5ef7195ac02aa5f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/717f610e5ef7195ac02aa5f3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[525,526,527,528,529,530,531,532],"take":"subject2/h2/6/cam4","frame_ids":[525,526,527,528,529,530,531,532]} +{"filtered_tile_id":"717f610e5ef7195ac02aa5f3:32","filtered_window_id":"717f610e5ef7195ac02aa5f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/717f610e5ef7195ac02aa5f3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[533,534,535,536,537,538,539,540],"take":"subject2/h2/6/cam4","frame_ids":[533,534,535,536,537,538,539,540]} +{"filtered_tile_id":"717f610e5ef7195ac02aa5f3:40","filtered_window_id":"717f610e5ef7195ac02aa5f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/717f610e5ef7195ac02aa5f3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject2/h2/6/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"717f610e5ef7195ac02aa5f3:48","filtered_window_id":"717f610e5ef7195ac02aa5f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/717f610e5ef7195ac02aa5f3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[549,550,551,552,553,554,555,556],"take":"subject2/h2/6/cam4","frame_ids":[549,550,551,552,553,554,555,556]} +{"filtered_tile_id":"717f610e5ef7195ac02aa5f3:52","filtered_window_id":"717f610e5ef7195ac02aa5f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/717f610e5ef7195ac02aa5f3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[553,554,555,556,557,558,559,560],"take":"subject2/h2/6/cam4","frame_ids":[553,554,555,556,557,558,559,560]} +{"filtered_tile_id":"71a1ae4f46bfc560432c5b0c:0","filtered_window_id":"71a1ae4f46bfc560432c5b0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a1ae4f46bfc560432c5b0c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject3/k1/1/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"71a1ae4f46bfc560432c5b0c:8","filtered_window_id":"71a1ae4f46bfc560432c5b0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a1ae4f46bfc560432c5b0c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject3/k1/1/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"71a1ae4f46bfc560432c5b0c:16","filtered_window_id":"71a1ae4f46bfc560432c5b0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a1ae4f46bfc560432c5b0c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject3/k1/1/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"71a1ae4f46bfc560432c5b0c:24","filtered_window_id":"71a1ae4f46bfc560432c5b0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a1ae4f46bfc560432c5b0c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject3/k1/1/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"71a1ae4f46bfc560432c5b0c:32","filtered_window_id":"71a1ae4f46bfc560432c5b0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a1ae4f46bfc560432c5b0c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject3/k1/1/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"71a1ae4f46bfc560432c5b0c:40","filtered_window_id":"71a1ae4f46bfc560432c5b0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a1ae4f46bfc560432c5b0c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject3/k1/1/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"71a1ae4f46bfc560432c5b0c:48","filtered_window_id":"71a1ae4f46bfc560432c5b0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a1ae4f46bfc560432c5b0c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject3/k1/1/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"71a1ae4f46bfc560432c5b0c:52","filtered_window_id":"71a1ae4f46bfc560432c5b0c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a1ae4f46bfc560432c5b0c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[522,523,524,525,526,527,528,529],"take":"subject3/k1/1/cam4","frame_ids":[522,523,524,525,526,527,528,529]} +{"filtered_tile_id":"71a446a84bc2fe9914d042a1:0","filtered_window_id":"71a446a84bc2fe9914d042a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a446a84bc2fe9914d042a1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/o1/4/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"71a446a84bc2fe9914d042a1:8","filtered_window_id":"71a446a84bc2fe9914d042a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a446a84bc2fe9914d042a1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[56,57,58,59,60,61,62,63],"take":"subject2/o1/4/cam4","frame_ids":[56,57,58,59,60,61,62,63]} +{"filtered_tile_id":"71a446a84bc2fe9914d042a1:16","filtered_window_id":"71a446a84bc2fe9914d042a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a446a84bc2fe9914d042a1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject2/o1/4/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"71a446a84bc2fe9914d042a1:24","filtered_window_id":"71a446a84bc2fe9914d042a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a446a84bc2fe9914d042a1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[72,73,74,75,76,77,78,79],"take":"subject2/o1/4/cam4","frame_ids":[72,73,74,75,76,77,78,79]} +{"filtered_tile_id":"71a446a84bc2fe9914d042a1:32","filtered_window_id":"71a446a84bc2fe9914d042a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a446a84bc2fe9914d042a1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[80,81,82,83,84,85,86,87],"take":"subject2/o1/4/cam4","frame_ids":[80,81,82,83,84,85,86,87]} +{"filtered_tile_id":"71a446a84bc2fe9914d042a1:40","filtered_window_id":"71a446a84bc2fe9914d042a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a446a84bc2fe9914d042a1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject2/o1/4/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"71a446a84bc2fe9914d042a1:48","filtered_window_id":"71a446a84bc2fe9914d042a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a446a84bc2fe9914d042a1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject2/o1/4/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"71a446a84bc2fe9914d042a1:52","filtered_window_id":"71a446a84bc2fe9914d042a1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71a446a84bc2fe9914d042a1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject2/o1/4/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"71f7bedcee002b70dbddf16b:0","filtered_window_id":"71f7bedcee002b70dbddf16b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71f7bedcee002b70dbddf16b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[586,587,588,589,590,591,592,593],"take":"subject1/o1/7/cam4","frame_ids":[586,587,588,589,590,591,592,593]} +{"filtered_tile_id":"71f7bedcee002b70dbddf16b:2","filtered_window_id":"71f7bedcee002b70dbddf16b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/71f7bedcee002b70dbddf16b/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[588,589,590,591,592,593,594,595],"take":"subject1/o1/7/cam4","frame_ids":[588,589,590,591,592,593,594,595]} +{"filtered_tile_id":"72adb5c3c9539f1d5e51c4d0:0","filtered_window_id":"72adb5c3c9539f1d5e51c4d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72adb5c3c9539f1d5e51c4d0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject2/h2/1/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"72adb5c3c9539f1d5e51c4d0:8","filtered_window_id":"72adb5c3c9539f1d5e51c4d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72adb5c3c9539f1d5e51c4d0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject2/h2/1/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"72adb5c3c9539f1d5e51c4d0:16","filtered_window_id":"72adb5c3c9539f1d5e51c4d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72adb5c3c9539f1d5e51c4d0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject2/h2/1/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"72adb5c3c9539f1d5e51c4d0:24","filtered_window_id":"72adb5c3c9539f1d5e51c4d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72adb5c3c9539f1d5e51c4d0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject2/h2/1/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"72adb5c3c9539f1d5e51c4d0:32","filtered_window_id":"72adb5c3c9539f1d5e51c4d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72adb5c3c9539f1d5e51c4d0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject2/h2/1/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"72adb5c3c9539f1d5e51c4d0:40","filtered_window_id":"72adb5c3c9539f1d5e51c4d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72adb5c3c9539f1d5e51c4d0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject2/h2/1/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"72adb5c3c9539f1d5e51c4d0:48","filtered_window_id":"72adb5c3c9539f1d5e51c4d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72adb5c3c9539f1d5e51c4d0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject2/h2/1/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"72adb5c3c9539f1d5e51c4d0:52","filtered_window_id":"72adb5c3c9539f1d5e51c4d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72adb5c3c9539f1d5e51c4d0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[232,233,234,235,236,237,238,239],"take":"subject2/h2/1/cam4","frame_ids":[232,233,234,235,236,237,238,239]} +{"filtered_tile_id":"72fc848af73297df2e6d0120:0","filtered_window_id":"72fc848af73297df2e6d0120","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72fc848af73297df2e6d0120/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[499,500,501,502,503,504,505,506],"take":"subject3/k1/3/cam4","frame_ids":[499,500,501,502,503,504,505,506]} +{"filtered_tile_id":"72fc848af73297df2e6d0120:8","filtered_window_id":"72fc848af73297df2e6d0120","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72fc848af73297df2e6d0120/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[507,508,509,510,511,512,513,514],"take":"subject3/k1/3/cam4","frame_ids":[507,508,509,510,511,512,513,514]} +{"filtered_tile_id":"72fc848af73297df2e6d0120:16","filtered_window_id":"72fc848af73297df2e6d0120","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72fc848af73297df2e6d0120/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[515,516,517,518,519,520,521,522],"take":"subject3/k1/3/cam4","frame_ids":[515,516,517,518,519,520,521,522]} +{"filtered_tile_id":"72fc848af73297df2e6d0120:24","filtered_window_id":"72fc848af73297df2e6d0120","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72fc848af73297df2e6d0120/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[523,524,525,526,527,528,529,530],"take":"subject3/k1/3/cam4","frame_ids":[523,524,525,526,527,528,529,530]} +{"filtered_tile_id":"72fc848af73297df2e6d0120:32","filtered_window_id":"72fc848af73297df2e6d0120","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72fc848af73297df2e6d0120/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[531,532,533,534,535,536,537,538],"take":"subject3/k1/3/cam4","frame_ids":[531,532,533,534,535,536,537,538]} +{"filtered_tile_id":"72fc848af73297df2e6d0120:40","filtered_window_id":"72fc848af73297df2e6d0120","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72fc848af73297df2e6d0120/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[539,540,541,542,543,544,545,546],"take":"subject3/k1/3/cam4","frame_ids":[539,540,541,542,543,544,545,546]} +{"filtered_tile_id":"72fc848af73297df2e6d0120:48","filtered_window_id":"72fc848af73297df2e6d0120","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72fc848af73297df2e6d0120/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[547,548,549,550,551,552,553,554],"take":"subject3/k1/3/cam4","frame_ids":[547,548,549,550,551,552,553,554]} +{"filtered_tile_id":"72fc848af73297df2e6d0120:52","filtered_window_id":"72fc848af73297df2e6d0120","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/72fc848af73297df2e6d0120/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[551,552,553,554,555,556,557,558],"take":"subject3/k1/3/cam4","frame_ids":[551,552,553,554,555,556,557,558]} +{"filtered_tile_id":"73133d921f9dad5653c919a5:0","filtered_window_id":"73133d921f9dad5653c919a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73133d921f9dad5653c919a5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject2/h2/1/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"73133d921f9dad5653c919a5:8","filtered_window_id":"73133d921f9dad5653c919a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73133d921f9dad5653c919a5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject2/h2/1/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"73133d921f9dad5653c919a5:16","filtered_window_id":"73133d921f9dad5653c919a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73133d921f9dad5653c919a5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject2/h2/1/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"73133d921f9dad5653c919a5:24","filtered_window_id":"73133d921f9dad5653c919a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73133d921f9dad5653c919a5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[466,467,468,469,470,471,472,473],"take":"subject2/h2/1/cam4","frame_ids":[466,467,468,469,470,471,472,473]} +{"filtered_tile_id":"73133d921f9dad5653c919a5:32","filtered_window_id":"73133d921f9dad5653c919a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73133d921f9dad5653c919a5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[474,475,476,477,478,479,480,481],"take":"subject2/h2/1/cam4","frame_ids":[474,475,476,477,478,479,480,481]} +{"filtered_tile_id":"73133d921f9dad5653c919a5:40","filtered_window_id":"73133d921f9dad5653c919a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73133d921f9dad5653c919a5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[482,483,484,485,486,487,488,489],"take":"subject2/h2/1/cam4","frame_ids":[482,483,484,485,486,487,488,489]} +{"filtered_tile_id":"73133d921f9dad5653c919a5:48","filtered_window_id":"73133d921f9dad5653c919a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73133d921f9dad5653c919a5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[490,491,492,493,494,495,496,497],"take":"subject2/h2/1/cam4","frame_ids":[490,491,492,493,494,495,496,497]} +{"filtered_tile_id":"73133d921f9dad5653c919a5:52","filtered_window_id":"73133d921f9dad5653c919a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73133d921f9dad5653c919a5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject2/h2/1/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"73377fddad2a4b8a569b49de:0","filtered_window_id":"73377fddad2a4b8a569b49de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73377fddad2a4b8a569b49de/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[577,578,579,580,581,582,583,584],"take":"subject2/o1/4/cam4","frame_ids":[577,578,579,580,581,582,583,584]} +{"filtered_tile_id":"73377fddad2a4b8a569b49de:8","filtered_window_id":"73377fddad2a4b8a569b49de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73377fddad2a4b8a569b49de/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[585,586,587,588,589,590,591,592],"take":"subject2/o1/4/cam4","frame_ids":[585,586,587,588,589,590,591,592]} +{"filtered_tile_id":"73377fddad2a4b8a569b49de:16","filtered_window_id":"73377fddad2a4b8a569b49de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73377fddad2a4b8a569b49de/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[593,594,595,596,597,598,599,600],"take":"subject2/o1/4/cam4","frame_ids":[593,594,595,596,597,598,599,600]} +{"filtered_tile_id":"73377fddad2a4b8a569b49de:24","filtered_window_id":"73377fddad2a4b8a569b49de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73377fddad2a4b8a569b49de/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[601,602,603,604,605,606,607,608],"take":"subject2/o1/4/cam4","frame_ids":[601,602,603,604,605,606,607,608]} +{"filtered_tile_id":"73377fddad2a4b8a569b49de:32","filtered_window_id":"73377fddad2a4b8a569b49de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73377fddad2a4b8a569b49de/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[609,610,611,612,613,614,615,616],"take":"subject2/o1/4/cam4","frame_ids":[609,610,611,612,613,614,615,616]} +{"filtered_tile_id":"73377fddad2a4b8a569b49de:40","filtered_window_id":"73377fddad2a4b8a569b49de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73377fddad2a4b8a569b49de/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[617,618,619,620,621,622,623,624],"take":"subject2/o1/4/cam4","frame_ids":[617,618,619,620,621,622,623,624]} +{"filtered_tile_id":"73377fddad2a4b8a569b49de:48","filtered_window_id":"73377fddad2a4b8a569b49de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73377fddad2a4b8a569b49de/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[625,626,627,628,629,630,631,632],"take":"subject2/o1/4/cam4","frame_ids":[625,626,627,628,629,630,631,632]} +{"filtered_tile_id":"73377fddad2a4b8a569b49de:52","filtered_window_id":"73377fddad2a4b8a569b49de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73377fddad2a4b8a569b49de/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[629,630,631,632,633,634,635,636],"take":"subject2/o1/4/cam4","frame_ids":[629,630,631,632,633,634,635,636]} +{"filtered_tile_id":"73a2f265a01ac022ec273685:0","filtered_window_id":"73a2f265a01ac022ec273685","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73a2f265a01ac022ec273685/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject1/o1/4/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"73a2f265a01ac022ec273685:8","filtered_window_id":"73a2f265a01ac022ec273685","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73a2f265a01ac022ec273685/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject1/o1/4/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"73a2f265a01ac022ec273685:16","filtered_window_id":"73a2f265a01ac022ec273685","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73a2f265a01ac022ec273685/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[411,412,413,414,415,416,417,418],"take":"subject1/o1/4/cam4","frame_ids":[411,412,413,414,415,416,417,418]} +{"filtered_tile_id":"73a2f265a01ac022ec273685:24","filtered_window_id":"73a2f265a01ac022ec273685","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73a2f265a01ac022ec273685/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[419,420,421,422,423,424,425,426],"take":"subject1/o1/4/cam4","frame_ids":[419,420,421,422,423,424,425,426]} +{"filtered_tile_id":"73a2f265a01ac022ec273685:32","filtered_window_id":"73a2f265a01ac022ec273685","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73a2f265a01ac022ec273685/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject1/o1/4/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"73a2f265a01ac022ec273685:40","filtered_window_id":"73a2f265a01ac022ec273685","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73a2f265a01ac022ec273685/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/o1/4/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"73a2f265a01ac022ec273685:48","filtered_window_id":"73a2f265a01ac022ec273685","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73a2f265a01ac022ec273685/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject1/o1/4/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"73a2f265a01ac022ec273685:52","filtered_window_id":"73a2f265a01ac022ec273685","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73a2f265a01ac022ec273685/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[447,448,449,450,451,452,453,454],"take":"subject1/o1/4/cam4","frame_ids":[447,448,449,450,451,452,453,454]} +{"filtered_tile_id":"73cdb250ef1fea9e21d171f2:0","filtered_window_id":"73cdb250ef1fea9e21d171f2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73cdb250ef1fea9e21d171f2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[4,5,6,7,8,9,10,11],"take":"subject2/o2/2/cam4","frame_ids":[4,5,6,7,8,9,10,11]} +{"filtered_tile_id":"73cdb250ef1fea9e21d171f2:8","filtered_window_id":"73cdb250ef1fea9e21d171f2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73cdb250ef1fea9e21d171f2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[12,13,14,15,16,17,18,19],"take":"subject2/o2/2/cam4","frame_ids":[12,13,14,15,16,17,18,19]} +{"filtered_tile_id":"73cdb250ef1fea9e21d171f2:16","filtered_window_id":"73cdb250ef1fea9e21d171f2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73cdb250ef1fea9e21d171f2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[20,21,22,23,24,25,26,27],"take":"subject2/o2/2/cam4","frame_ids":[20,21,22,23,24,25,26,27]} +{"filtered_tile_id":"73cdb250ef1fea9e21d171f2:24","filtered_window_id":"73cdb250ef1fea9e21d171f2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73cdb250ef1fea9e21d171f2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[28,29,30,31,32,33,34,35],"take":"subject2/o2/2/cam4","frame_ids":[28,29,30,31,32,33,34,35]} +{"filtered_tile_id":"73cdb250ef1fea9e21d171f2:32","filtered_window_id":"73cdb250ef1fea9e21d171f2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73cdb250ef1fea9e21d171f2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[36,37,38,39,40,41,42,43],"take":"subject2/o2/2/cam4","frame_ids":[36,37,38,39,40,41,42,43]} +{"filtered_tile_id":"73cdb250ef1fea9e21d171f2:40","filtered_window_id":"73cdb250ef1fea9e21d171f2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73cdb250ef1fea9e21d171f2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[44,45,46,47,48,49,50,51],"take":"subject2/o2/2/cam4","frame_ids":[44,45,46,47,48,49,50,51]} +{"filtered_tile_id":"73cdb250ef1fea9e21d171f2:48","filtered_window_id":"73cdb250ef1fea9e21d171f2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73cdb250ef1fea9e21d171f2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/o2/2/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"73cdb250ef1fea9e21d171f2:52","filtered_window_id":"73cdb250ef1fea9e21d171f2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73cdb250ef1fea9e21d171f2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[56,57,58,59,60,61,62,63],"take":"subject2/o2/2/cam4","frame_ids":[56,57,58,59,60,61,62,63]} +{"filtered_tile_id":"73ce7194921b7bb77550ba2c:0","filtered_window_id":"73ce7194921b7bb77550ba2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73ce7194921b7bb77550ba2c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[438,439,440,441,442,443,444,445],"take":"subject1/h2/3/cam4","frame_ids":[438,439,440,441,442,443,444,445]} +{"filtered_tile_id":"73ce7194921b7bb77550ba2c:8","filtered_window_id":"73ce7194921b7bb77550ba2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73ce7194921b7bb77550ba2c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[446,447,448,449,450,451,452,453],"take":"subject1/h2/3/cam4","frame_ids":[446,447,448,449,450,451,452,453]} +{"filtered_tile_id":"73ce7194921b7bb77550ba2c:16","filtered_window_id":"73ce7194921b7bb77550ba2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73ce7194921b7bb77550ba2c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[454,455,456,457,458,459,460,461],"take":"subject1/h2/3/cam4","frame_ids":[454,455,456,457,458,459,460,461]} +{"filtered_tile_id":"73ce7194921b7bb77550ba2c:24","filtered_window_id":"73ce7194921b7bb77550ba2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73ce7194921b7bb77550ba2c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject1/h2/3/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"73ce7194921b7bb77550ba2c:32","filtered_window_id":"73ce7194921b7bb77550ba2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73ce7194921b7bb77550ba2c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject1/h2/3/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"73ce7194921b7bb77550ba2c:40","filtered_window_id":"73ce7194921b7bb77550ba2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73ce7194921b7bb77550ba2c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject1/h2/3/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"73ce7194921b7bb77550ba2c:48","filtered_window_id":"73ce7194921b7bb77550ba2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73ce7194921b7bb77550ba2c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject1/h2/3/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"73ce7194921b7bb77550ba2c:52","filtered_window_id":"73ce7194921b7bb77550ba2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/73ce7194921b7bb77550ba2c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[490,491,492,493,494,495,496,497],"take":"subject1/h2/3/cam4","frame_ids":[490,491,492,493,494,495,496,497]} +{"filtered_tile_id":"74f39b369b5d25627f90a4cd:0","filtered_window_id":"74f39b369b5d25627f90a4cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/74f39b369b5d25627f90a4cd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject3/h1/1/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"74f39b369b5d25627f90a4cd:8","filtered_window_id":"74f39b369b5d25627f90a4cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/74f39b369b5d25627f90a4cd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject3/h1/1/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"74f39b369b5d25627f90a4cd:16","filtered_window_id":"74f39b369b5d25627f90a4cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/74f39b369b5d25627f90a4cd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[386,387,388,389,390,391,392,393],"take":"subject3/h1/1/cam4","frame_ids":[386,387,388,389,390,391,392,393]} +{"filtered_tile_id":"74f39b369b5d25627f90a4cd:24","filtered_window_id":"74f39b369b5d25627f90a4cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/74f39b369b5d25627f90a4cd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[394,395,396,397,398,399,400,401],"take":"subject3/h1/1/cam4","frame_ids":[394,395,396,397,398,399,400,401]} +{"filtered_tile_id":"74f39b369b5d25627f90a4cd:32","filtered_window_id":"74f39b369b5d25627f90a4cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/74f39b369b5d25627f90a4cd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[402,403,404,405,406,407,408,409],"take":"subject3/h1/1/cam4","frame_ids":[402,403,404,405,406,407,408,409]} +{"filtered_tile_id":"74f39b369b5d25627f90a4cd:40","filtered_window_id":"74f39b369b5d25627f90a4cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/74f39b369b5d25627f90a4cd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject3/h1/1/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"74f39b369b5d25627f90a4cd:48","filtered_window_id":"74f39b369b5d25627f90a4cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/74f39b369b5d25627f90a4cd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject3/h1/1/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"74f39b369b5d25627f90a4cd:52","filtered_window_id":"74f39b369b5d25627f90a4cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/74f39b369b5d25627f90a4cd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[422,423,424,425,426,427,428,429],"take":"subject3/h1/1/cam4","frame_ids":[422,423,424,425,426,427,428,429]} +{"filtered_tile_id":"755e630bc6c5b42a516557f5:0","filtered_window_id":"755e630bc6c5b42a516557f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/755e630bc6c5b42a516557f5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject1/h1/5/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"755e630bc6c5b42a516557f5:8","filtered_window_id":"755e630bc6c5b42a516557f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/755e630bc6c5b42a516557f5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject1/h1/5/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"755e630bc6c5b42a516557f5:16","filtered_window_id":"755e630bc6c5b42a516557f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/755e630bc6c5b42a516557f5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject1/h1/5/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"755e630bc6c5b42a516557f5:24","filtered_window_id":"755e630bc6c5b42a516557f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/755e630bc6c5b42a516557f5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[466,467,468,469,470,471,472,473],"take":"subject1/h1/5/cam4","frame_ids":[466,467,468,469,470,471,472,473]} +{"filtered_tile_id":"755e630bc6c5b42a516557f5:32","filtered_window_id":"755e630bc6c5b42a516557f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/755e630bc6c5b42a516557f5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[474,475,476,477,478,479,480,481],"take":"subject1/h1/5/cam4","frame_ids":[474,475,476,477,478,479,480,481]} +{"filtered_tile_id":"755e630bc6c5b42a516557f5:35","filtered_window_id":"755e630bc6c5b42a516557f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/755e630bc6c5b42a516557f5/native_gt.npz","filtered_start_offset":35,"expected_frame_ids":[477,478,479,480,481,482,483,484],"take":"subject1/h1/5/cam4","frame_ids":[477,478,479,480,481,482,483,484]} +{"filtered_tile_id":"75a172a9e11c6f7768721de7:0","filtered_window_id":"75a172a9e11c6f7768721de7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/75a172a9e11c6f7768721de7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[20,21,22,23,24,25,26,27],"take":"subject1/k1/2/cam4","frame_ids":[20,21,22,23,24,25,26,27]} +{"filtered_tile_id":"75a172a9e11c6f7768721de7:8","filtered_window_id":"75a172a9e11c6f7768721de7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/75a172a9e11c6f7768721de7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[28,29,30,31,32,33,34,35],"take":"subject1/k1/2/cam4","frame_ids":[28,29,30,31,32,33,34,35]} +{"filtered_tile_id":"75a172a9e11c6f7768721de7:16","filtered_window_id":"75a172a9e11c6f7768721de7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/75a172a9e11c6f7768721de7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[36,37,38,39,40,41,42,43],"take":"subject1/k1/2/cam4","frame_ids":[36,37,38,39,40,41,42,43]} +{"filtered_tile_id":"75a172a9e11c6f7768721de7:24","filtered_window_id":"75a172a9e11c6f7768721de7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/75a172a9e11c6f7768721de7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[44,45,46,47,48,49,50,51],"take":"subject1/k1/2/cam4","frame_ids":[44,45,46,47,48,49,50,51]} +{"filtered_tile_id":"75a172a9e11c6f7768721de7:32","filtered_window_id":"75a172a9e11c6f7768721de7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/75a172a9e11c6f7768721de7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/k1/2/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"75a172a9e11c6f7768721de7:40","filtered_window_id":"75a172a9e11c6f7768721de7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/75a172a9e11c6f7768721de7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject1/k1/2/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"75a172a9e11c6f7768721de7:48","filtered_window_id":"75a172a9e11c6f7768721de7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/75a172a9e11c6f7768721de7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject1/k1/2/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"75a172a9e11c6f7768721de7:52","filtered_window_id":"75a172a9e11c6f7768721de7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/75a172a9e11c6f7768721de7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[72,73,74,75,76,77,78,79],"take":"subject1/k1/2/cam4","frame_ids":[72,73,74,75,76,77,78,79]} +{"filtered_tile_id":"76c4ce408d887098c71634b4:0","filtered_window_id":"76c4ce408d887098c71634b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76c4ce408d887098c71634b4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject2/o2/2/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"76c4ce408d887098c71634b4:8","filtered_window_id":"76c4ce408d887098c71634b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76c4ce408d887098c71634b4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[93,94,95,96,97,98,99,100],"take":"subject2/o2/2/cam4","frame_ids":[93,94,95,96,97,98,99,100]} +{"filtered_tile_id":"76c4ce408d887098c71634b4:16","filtered_window_id":"76c4ce408d887098c71634b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76c4ce408d887098c71634b4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[101,102,103,104,105,106,107,108],"take":"subject2/o2/2/cam4","frame_ids":[101,102,103,104,105,106,107,108]} +{"filtered_tile_id":"76c4ce408d887098c71634b4:24","filtered_window_id":"76c4ce408d887098c71634b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76c4ce408d887098c71634b4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[109,110,111,112,113,114,115,116],"take":"subject2/o2/2/cam4","frame_ids":[109,110,111,112,113,114,115,116]} +{"filtered_tile_id":"76c4ce408d887098c71634b4:32","filtered_window_id":"76c4ce408d887098c71634b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76c4ce408d887098c71634b4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[117,118,119,120,121,122,123,124],"take":"subject2/o2/2/cam4","frame_ids":[117,118,119,120,121,122,123,124]} +{"filtered_tile_id":"76c4ce408d887098c71634b4:40","filtered_window_id":"76c4ce408d887098c71634b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76c4ce408d887098c71634b4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[125,126,127,128,129,130,131,132],"take":"subject2/o2/2/cam4","frame_ids":[125,126,127,128,129,130,131,132]} +{"filtered_tile_id":"76c4ce408d887098c71634b4:48","filtered_window_id":"76c4ce408d887098c71634b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76c4ce408d887098c71634b4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject2/o2/2/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"76c4ce408d887098c71634b4:52","filtered_window_id":"76c4ce408d887098c71634b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76c4ce408d887098c71634b4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject2/o2/2/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"76f8ea39f697f6817958ec89:0","filtered_window_id":"76f8ea39f697f6817958ec89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76f8ea39f697f6817958ec89/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[246,247,248,249,250,251,252,253],"take":"subject2/o1/1/cam4","frame_ids":[246,247,248,249,250,251,252,253]} +{"filtered_tile_id":"76f8ea39f697f6817958ec89:8","filtered_window_id":"76f8ea39f697f6817958ec89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76f8ea39f697f6817958ec89/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject2/o1/1/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"76f8ea39f697f6817958ec89:16","filtered_window_id":"76f8ea39f697f6817958ec89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76f8ea39f697f6817958ec89/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[262,263,264,265,266,267,268,269],"take":"subject2/o1/1/cam4","frame_ids":[262,263,264,265,266,267,268,269]} +{"filtered_tile_id":"76f8ea39f697f6817958ec89:24","filtered_window_id":"76f8ea39f697f6817958ec89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76f8ea39f697f6817958ec89/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[270,271,272,273,274,275,276,277],"take":"subject2/o1/1/cam4","frame_ids":[270,271,272,273,274,275,276,277]} +{"filtered_tile_id":"76f8ea39f697f6817958ec89:32","filtered_window_id":"76f8ea39f697f6817958ec89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76f8ea39f697f6817958ec89/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[278,279,280,281,282,283,284,285],"take":"subject2/o1/1/cam4","frame_ids":[278,279,280,281,282,283,284,285]} +{"filtered_tile_id":"76f8ea39f697f6817958ec89:40","filtered_window_id":"76f8ea39f697f6817958ec89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76f8ea39f697f6817958ec89/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[286,287,288,289,290,291,292,293],"take":"subject2/o1/1/cam4","frame_ids":[286,287,288,289,290,291,292,293]} +{"filtered_tile_id":"76f8ea39f697f6817958ec89:48","filtered_window_id":"76f8ea39f697f6817958ec89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76f8ea39f697f6817958ec89/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[294,295,296,297,298,299,300,301],"take":"subject2/o1/1/cam4","frame_ids":[294,295,296,297,298,299,300,301]} +{"filtered_tile_id":"76f8ea39f697f6817958ec89:52","filtered_window_id":"76f8ea39f697f6817958ec89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/76f8ea39f697f6817958ec89/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject2/o1/1/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"770e8e91ad57d5cb139f30fb:0","filtered_window_id":"770e8e91ad57d5cb139f30fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/770e8e91ad57d5cb139f30fb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject2/o1/1/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"770e8e91ad57d5cb139f30fb:8","filtered_window_id":"770e8e91ad57d5cb139f30fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/770e8e91ad57d5cb139f30fb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[469,470,471,472,473,474,475,476],"take":"subject2/o1/1/cam4","frame_ids":[469,470,471,472,473,474,475,476]} +{"filtered_tile_id":"770e8e91ad57d5cb139f30fb:16","filtered_window_id":"770e8e91ad57d5cb139f30fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/770e8e91ad57d5cb139f30fb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[477,478,479,480,481,482,483,484],"take":"subject2/o1/1/cam4","frame_ids":[477,478,479,480,481,482,483,484]} +{"filtered_tile_id":"770e8e91ad57d5cb139f30fb:24","filtered_window_id":"770e8e91ad57d5cb139f30fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/770e8e91ad57d5cb139f30fb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[485,486,487,488,489,490,491,492],"take":"subject2/o1/1/cam4","frame_ids":[485,486,487,488,489,490,491,492]} +{"filtered_tile_id":"770e8e91ad57d5cb139f30fb:32","filtered_window_id":"770e8e91ad57d5cb139f30fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/770e8e91ad57d5cb139f30fb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[493,494,495,496,497,498,499,500],"take":"subject2/o1/1/cam4","frame_ids":[493,494,495,496,497,498,499,500]} +{"filtered_tile_id":"770e8e91ad57d5cb139f30fb:40","filtered_window_id":"770e8e91ad57d5cb139f30fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/770e8e91ad57d5cb139f30fb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[501,502,503,504,505,506,507,508],"take":"subject2/o1/1/cam4","frame_ids":[501,502,503,504,505,506,507,508]} +{"filtered_tile_id":"770e8e91ad57d5cb139f30fb:48","filtered_window_id":"770e8e91ad57d5cb139f30fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/770e8e91ad57d5cb139f30fb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[509,510,511,512,513,514,515,516],"take":"subject2/o1/1/cam4","frame_ids":[509,510,511,512,513,514,515,516]} +{"filtered_tile_id":"770e8e91ad57d5cb139f30fb:52","filtered_window_id":"770e8e91ad57d5cb139f30fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/770e8e91ad57d5cb139f30fb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[513,514,515,516,517,518,519,520],"take":"subject2/o1/1/cam4","frame_ids":[513,514,515,516,517,518,519,520]} +{"filtered_tile_id":"771b2822a61bc526b45ca686:0","filtered_window_id":"771b2822a61bc526b45ca686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/771b2822a61bc526b45ca686/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject1/o2/3/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"771b2822a61bc526b45ca686:8","filtered_window_id":"771b2822a61bc526b45ca686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/771b2822a61bc526b45ca686/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject1/o2/3/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"771b2822a61bc526b45ca686:16","filtered_window_id":"771b2822a61bc526b45ca686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/771b2822a61bc526b45ca686/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject1/o2/3/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"771b2822a61bc526b45ca686:24","filtered_window_id":"771b2822a61bc526b45ca686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/771b2822a61bc526b45ca686/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject1/o2/3/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"771b2822a61bc526b45ca686:32","filtered_window_id":"771b2822a61bc526b45ca686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/771b2822a61bc526b45ca686/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject1/o2/3/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"771b2822a61bc526b45ca686:40","filtered_window_id":"771b2822a61bc526b45ca686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/771b2822a61bc526b45ca686/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject1/o2/3/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"771b2822a61bc526b45ca686:48","filtered_window_id":"771b2822a61bc526b45ca686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/771b2822a61bc526b45ca686/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject1/o2/3/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"771b2822a61bc526b45ca686:52","filtered_window_id":"771b2822a61bc526b45ca686","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/771b2822a61bc526b45ca686/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[524,525,526,527,528,529,530,531],"take":"subject1/o2/3/cam4","frame_ids":[524,525,526,527,528,529,530,531]} +{"filtered_tile_id":"7760e68e4ed363fafe40c587:0","filtered_window_id":"7760e68e4ed363fafe40c587","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7760e68e4ed363fafe40c587/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject1/k2/6/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"7760e68e4ed363fafe40c587:8","filtered_window_id":"7760e68e4ed363fafe40c587","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7760e68e4ed363fafe40c587/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject1/k2/6/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"7760e68e4ed363fafe40c587:16","filtered_window_id":"7760e68e4ed363fafe40c587","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7760e68e4ed363fafe40c587/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject1/k2/6/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"7760e68e4ed363fafe40c587:24","filtered_window_id":"7760e68e4ed363fafe40c587","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7760e68e4ed363fafe40c587/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject1/k2/6/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"7760e68e4ed363fafe40c587:32","filtered_window_id":"7760e68e4ed363fafe40c587","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7760e68e4ed363fafe40c587/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject1/k2/6/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"7760e68e4ed363fafe40c587:40","filtered_window_id":"7760e68e4ed363fafe40c587","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7760e68e4ed363fafe40c587/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject1/k2/6/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"7760e68e4ed363fafe40c587:48","filtered_window_id":"7760e68e4ed363fafe40c587","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7760e68e4ed363fafe40c587/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject1/k2/6/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"7760e68e4ed363fafe40c587:52","filtered_window_id":"7760e68e4ed363fafe40c587","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7760e68e4ed363fafe40c587/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[456,457,458,459,460,461,462,463],"take":"subject1/k2/6/cam4","frame_ids":[456,457,458,459,460,461,462,463]} +{"filtered_tile_id":"7797fcb082d070375c689495:0","filtered_window_id":"7797fcb082d070375c689495","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7797fcb082d070375c689495/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject1/o2/5/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"7797fcb082d070375c689495:8","filtered_window_id":"7797fcb082d070375c689495","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7797fcb082d070375c689495/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject1/o2/5/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"7797fcb082d070375c689495:16","filtered_window_id":"7797fcb082d070375c689495","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7797fcb082d070375c689495/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject1/o2/5/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"7797fcb082d070375c689495:24","filtered_window_id":"7797fcb082d070375c689495","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7797fcb082d070375c689495/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject1/o2/5/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"7797fcb082d070375c689495:32","filtered_window_id":"7797fcb082d070375c689495","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7797fcb082d070375c689495/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject1/o2/5/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"7797fcb082d070375c689495:40","filtered_window_id":"7797fcb082d070375c689495","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7797fcb082d070375c689495/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject1/o2/5/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"7797fcb082d070375c689495:48","filtered_window_id":"7797fcb082d070375c689495","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7797fcb082d070375c689495/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject1/o2/5/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"7797fcb082d070375c689495:52","filtered_window_id":"7797fcb082d070375c689495","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7797fcb082d070375c689495/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject1/o2/5/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"783fa4143aa98d1c71b93c17:0","filtered_window_id":"783fa4143aa98d1c71b93c17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/783fa4143aa98d1c71b93c17/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[191,192,193,194,195,196,197,198],"take":"subject2/o1/5/cam4","frame_ids":[191,192,193,194,195,196,197,198]} +{"filtered_tile_id":"783fa4143aa98d1c71b93c17:8","filtered_window_id":"783fa4143aa98d1c71b93c17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/783fa4143aa98d1c71b93c17/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject2/o1/5/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"783fa4143aa98d1c71b93c17:16","filtered_window_id":"783fa4143aa98d1c71b93c17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/783fa4143aa98d1c71b93c17/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[207,208,209,210,211,212,213,214],"take":"subject2/o1/5/cam4","frame_ids":[207,208,209,210,211,212,213,214]} +{"filtered_tile_id":"783fa4143aa98d1c71b93c17:24","filtered_window_id":"783fa4143aa98d1c71b93c17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/783fa4143aa98d1c71b93c17/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[215,216,217,218,219,220,221,222],"take":"subject2/o1/5/cam4","frame_ids":[215,216,217,218,219,220,221,222]} +{"filtered_tile_id":"783fa4143aa98d1c71b93c17:32","filtered_window_id":"783fa4143aa98d1c71b93c17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/783fa4143aa98d1c71b93c17/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject2/o1/5/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"783fa4143aa98d1c71b93c17:40","filtered_window_id":"783fa4143aa98d1c71b93c17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/783fa4143aa98d1c71b93c17/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject2/o1/5/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"783fa4143aa98d1c71b93c17:48","filtered_window_id":"783fa4143aa98d1c71b93c17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/783fa4143aa98d1c71b93c17/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject2/o1/5/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"783fa4143aa98d1c71b93c17:52","filtered_window_id":"783fa4143aa98d1c71b93c17","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/783fa4143aa98d1c71b93c17/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[243,244,245,246,247,248,249,250],"take":"subject2/o1/5/cam4","frame_ids":[243,244,245,246,247,248,249,250]} +{"filtered_tile_id":"78908ed2da6874dd42ce66d7:0","filtered_window_id":"78908ed2da6874dd42ce66d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78908ed2da6874dd42ce66d7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[89,90,91,92,93,94,95,96],"take":"subject2/k2/4/cam4","frame_ids":[89,90,91,92,93,94,95,96]} +{"filtered_tile_id":"78908ed2da6874dd42ce66d7:8","filtered_window_id":"78908ed2da6874dd42ce66d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78908ed2da6874dd42ce66d7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[97,98,99,100,101,102,103,104],"take":"subject2/k2/4/cam4","frame_ids":[97,98,99,100,101,102,103,104]} +{"filtered_tile_id":"78908ed2da6874dd42ce66d7:16","filtered_window_id":"78908ed2da6874dd42ce66d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78908ed2da6874dd42ce66d7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[105,106,107,108,109,110,111,112],"take":"subject2/k2/4/cam4","frame_ids":[105,106,107,108,109,110,111,112]} +{"filtered_tile_id":"78908ed2da6874dd42ce66d7:24","filtered_window_id":"78908ed2da6874dd42ce66d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78908ed2da6874dd42ce66d7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[113,114,115,116,117,118,119,120],"take":"subject2/k2/4/cam4","frame_ids":[113,114,115,116,117,118,119,120]} +{"filtered_tile_id":"78908ed2da6874dd42ce66d7:32","filtered_window_id":"78908ed2da6874dd42ce66d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78908ed2da6874dd42ce66d7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[121,122,123,124,125,126,127,128],"take":"subject2/k2/4/cam4","frame_ids":[121,122,123,124,125,126,127,128]} +{"filtered_tile_id":"78908ed2da6874dd42ce66d7:40","filtered_window_id":"78908ed2da6874dd42ce66d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78908ed2da6874dd42ce66d7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject2/k2/4/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"78908ed2da6874dd42ce66d7:48","filtered_window_id":"78908ed2da6874dd42ce66d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78908ed2da6874dd42ce66d7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject2/k2/4/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"78908ed2da6874dd42ce66d7:52","filtered_window_id":"78908ed2da6874dd42ce66d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78908ed2da6874dd42ce66d7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject2/k2/4/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"78a0d536ca84a6bac57ec327:0","filtered_window_id":"78a0d536ca84a6bac57ec327","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a0d536ca84a6bac57ec327/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[616,617,618,619,620,621,622,623],"take":"subject3/h1/3/cam4","frame_ids":[616,617,618,619,620,621,622,623]} +{"filtered_tile_id":"78a0d536ca84a6bac57ec327:8","filtered_window_id":"78a0d536ca84a6bac57ec327","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a0d536ca84a6bac57ec327/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[624,625,626,627,628,629,630,631],"take":"subject3/h1/3/cam4","frame_ids":[624,625,626,627,628,629,630,631]} +{"filtered_tile_id":"78a0d536ca84a6bac57ec327:16","filtered_window_id":"78a0d536ca84a6bac57ec327","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a0d536ca84a6bac57ec327/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[632,633,634,635,636,637,638,639],"take":"subject3/h1/3/cam4","frame_ids":[632,633,634,635,636,637,638,639]} +{"filtered_tile_id":"78a0d536ca84a6bac57ec327:24","filtered_window_id":"78a0d536ca84a6bac57ec327","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a0d536ca84a6bac57ec327/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[640,641,642,643,644,645,646,647],"take":"subject3/h1/3/cam4","frame_ids":[640,641,642,643,644,645,646,647]} +{"filtered_tile_id":"78a0d536ca84a6bac57ec327:32","filtered_window_id":"78a0d536ca84a6bac57ec327","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a0d536ca84a6bac57ec327/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[648,649,650,651,652,653,654,655],"take":"subject3/h1/3/cam4","frame_ids":[648,649,650,651,652,653,654,655]} +{"filtered_tile_id":"78a0d536ca84a6bac57ec327:40","filtered_window_id":"78a0d536ca84a6bac57ec327","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a0d536ca84a6bac57ec327/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[656,657,658,659,660,661,662,663],"take":"subject3/h1/3/cam4","frame_ids":[656,657,658,659,660,661,662,663]} +{"filtered_tile_id":"78a0d536ca84a6bac57ec327:48","filtered_window_id":"78a0d536ca84a6bac57ec327","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a0d536ca84a6bac57ec327/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[664,665,666,667,668,669,670,671],"take":"subject3/h1/3/cam4","frame_ids":[664,665,666,667,668,669,670,671]} +{"filtered_tile_id":"78a0d536ca84a6bac57ec327:52","filtered_window_id":"78a0d536ca84a6bac57ec327","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a0d536ca84a6bac57ec327/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[668,669,670,671,672,673,674,675],"take":"subject3/h1/3/cam4","frame_ids":[668,669,670,671,672,673,674,675]} +{"filtered_tile_id":"78a49e43bb67fd72f1d406c3:0","filtered_window_id":"78a49e43bb67fd72f1d406c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a49e43bb67fd72f1d406c3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[377,378,379,380,381,382,383,384],"take":"subject3/k1/0/cam4","frame_ids":[377,378,379,380,381,382,383,384]} +{"filtered_tile_id":"78a49e43bb67fd72f1d406c3:3","filtered_window_id":"78a49e43bb67fd72f1d406c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/78a49e43bb67fd72f1d406c3/native_gt.npz","filtered_start_offset":3,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject3/k1/0/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"7910c931a21ee11e8f1a8834:0","filtered_window_id":"7910c931a21ee11e8f1a8834","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7910c931a21ee11e8f1a8834/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[175,176,177,178,179,180,181,182],"take":"subject1/k1/6/cam4","frame_ids":[175,176,177,178,179,180,181,182]} +{"filtered_tile_id":"7910c931a21ee11e8f1a8834:8","filtered_window_id":"7910c931a21ee11e8f1a8834","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7910c931a21ee11e8f1a8834/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[183,184,185,186,187,188,189,190],"take":"subject1/k1/6/cam4","frame_ids":[183,184,185,186,187,188,189,190]} +{"filtered_tile_id":"7910c931a21ee11e8f1a8834:16","filtered_window_id":"7910c931a21ee11e8f1a8834","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7910c931a21ee11e8f1a8834/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[191,192,193,194,195,196,197,198],"take":"subject1/k1/6/cam4","frame_ids":[191,192,193,194,195,196,197,198]} +{"filtered_tile_id":"7910c931a21ee11e8f1a8834:24","filtered_window_id":"7910c931a21ee11e8f1a8834","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7910c931a21ee11e8f1a8834/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject1/k1/6/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"7910c931a21ee11e8f1a8834:32","filtered_window_id":"7910c931a21ee11e8f1a8834","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7910c931a21ee11e8f1a8834/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[207,208,209,210,211,212,213,214],"take":"subject1/k1/6/cam4","frame_ids":[207,208,209,210,211,212,213,214]} +{"filtered_tile_id":"7910c931a21ee11e8f1a8834:40","filtered_window_id":"7910c931a21ee11e8f1a8834","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7910c931a21ee11e8f1a8834/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[215,216,217,218,219,220,221,222],"take":"subject1/k1/6/cam4","frame_ids":[215,216,217,218,219,220,221,222]} +{"filtered_tile_id":"7910c931a21ee11e8f1a8834:48","filtered_window_id":"7910c931a21ee11e8f1a8834","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7910c931a21ee11e8f1a8834/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject1/k1/6/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"7910c931a21ee11e8f1a8834:52","filtered_window_id":"7910c931a21ee11e8f1a8834","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7910c931a21ee11e8f1a8834/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[227,228,229,230,231,232,233,234],"take":"subject1/k1/6/cam4","frame_ids":[227,228,229,230,231,232,233,234]} +{"filtered_tile_id":"794e1bc41df3f6b71f3a3737:0","filtered_window_id":"794e1bc41df3f6b71f3a3737","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/794e1bc41df3f6b71f3a3737/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject2/h2/4/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"794e1bc41df3f6b71f3a3737:8","filtered_window_id":"794e1bc41df3f6b71f3a3737","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/794e1bc41df3f6b71f3a3737/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject2/h2/4/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"794e1bc41df3f6b71f3a3737:16","filtered_window_id":"794e1bc41df3f6b71f3a3737","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/794e1bc41df3f6b71f3a3737/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject2/h2/4/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"794e1bc41df3f6b71f3a3737:24","filtered_window_id":"794e1bc41df3f6b71f3a3737","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/794e1bc41df3f6b71f3a3737/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject2/h2/4/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"794e1bc41df3f6b71f3a3737:32","filtered_window_id":"794e1bc41df3f6b71f3a3737","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/794e1bc41df3f6b71f3a3737/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject2/h2/4/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"794e1bc41df3f6b71f3a3737:40","filtered_window_id":"794e1bc41df3f6b71f3a3737","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/794e1bc41df3f6b71f3a3737/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject2/h2/4/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"794e1bc41df3f6b71f3a3737:48","filtered_window_id":"794e1bc41df3f6b71f3a3737","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/794e1bc41df3f6b71f3a3737/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject2/h2/4/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"794e1bc41df3f6b71f3a3737:52","filtered_window_id":"794e1bc41df3f6b71f3a3737","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/794e1bc41df3f6b71f3a3737/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject2/h2/4/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"795757113519f88510611dd6:0","filtered_window_id":"795757113519f88510611dd6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/795757113519f88510611dd6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[455,456,457,458,459,460,461,462],"take":"subject1/o1/4/cam4","frame_ids":[455,456,457,458,459,460,461,462]} +{"filtered_tile_id":"795757113519f88510611dd6:8","filtered_window_id":"795757113519f88510611dd6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/795757113519f88510611dd6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject1/o1/4/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"795757113519f88510611dd6:16","filtered_window_id":"795757113519f88510611dd6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/795757113519f88510611dd6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[471,472,473,474,475,476,477,478],"take":"subject1/o1/4/cam4","frame_ids":[471,472,473,474,475,476,477,478]} +{"filtered_tile_id":"795757113519f88510611dd6:24","filtered_window_id":"795757113519f88510611dd6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/795757113519f88510611dd6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[479,480,481,482,483,484,485,486],"take":"subject1/o1/4/cam4","frame_ids":[479,480,481,482,483,484,485,486]} +{"filtered_tile_id":"795757113519f88510611dd6:32","filtered_window_id":"795757113519f88510611dd6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/795757113519f88510611dd6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject1/o1/4/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"795757113519f88510611dd6:40","filtered_window_id":"795757113519f88510611dd6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/795757113519f88510611dd6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[495,496,497,498,499,500,501,502],"take":"subject1/o1/4/cam4","frame_ids":[495,496,497,498,499,500,501,502]} +{"filtered_tile_id":"795757113519f88510611dd6:48","filtered_window_id":"795757113519f88510611dd6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/795757113519f88510611dd6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[503,504,505,506,507,508,509,510],"take":"subject1/o1/4/cam4","frame_ids":[503,504,505,506,507,508,509,510]} +{"filtered_tile_id":"795757113519f88510611dd6:52","filtered_window_id":"795757113519f88510611dd6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/795757113519f88510611dd6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[507,508,509,510,511,512,513,514],"take":"subject1/o1/4/cam4","frame_ids":[507,508,509,510,511,512,513,514]} +{"filtered_tile_id":"799553205418c6716e5cc00d:0","filtered_window_id":"799553205418c6716e5cc00d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/799553205418c6716e5cc00d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject2/h2/6/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"799553205418c6716e5cc00d:8","filtered_window_id":"799553205418c6716e5cc00d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/799553205418c6716e5cc00d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject2/h2/6/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"799553205418c6716e5cc00d:16","filtered_window_id":"799553205418c6716e5cc00d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/799553205418c6716e5cc00d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[386,387,388,389,390,391,392,393],"take":"subject2/h2/6/cam4","frame_ids":[386,387,388,389,390,391,392,393]} +{"filtered_tile_id":"799553205418c6716e5cc00d:24","filtered_window_id":"799553205418c6716e5cc00d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/799553205418c6716e5cc00d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[394,395,396,397,398,399,400,401],"take":"subject2/h2/6/cam4","frame_ids":[394,395,396,397,398,399,400,401]} +{"filtered_tile_id":"799553205418c6716e5cc00d:32","filtered_window_id":"799553205418c6716e5cc00d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/799553205418c6716e5cc00d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[402,403,404,405,406,407,408,409],"take":"subject2/h2/6/cam4","frame_ids":[402,403,404,405,406,407,408,409]} +{"filtered_tile_id":"799553205418c6716e5cc00d:40","filtered_window_id":"799553205418c6716e5cc00d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/799553205418c6716e5cc00d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject2/h2/6/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"799553205418c6716e5cc00d:48","filtered_window_id":"799553205418c6716e5cc00d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/799553205418c6716e5cc00d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject2/h2/6/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"799553205418c6716e5cc00d:52","filtered_window_id":"799553205418c6716e5cc00d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/799553205418c6716e5cc00d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[422,423,424,425,426,427,428,429],"take":"subject2/h2/6/cam4","frame_ids":[422,423,424,425,426,427,428,429]} +{"filtered_tile_id":"7a497aab3749a0724827d27e:0","filtered_window_id":"7a497aab3749a0724827d27e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a497aab3749a0724827d27e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[535,536,537,538,539,540,541,542],"take":"subject2/o2/1/cam4","frame_ids":[535,536,537,538,539,540,541,542]} +{"filtered_tile_id":"7a497aab3749a0724827d27e:8","filtered_window_id":"7a497aab3749a0724827d27e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a497aab3749a0724827d27e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[543,544,545,546,547,548,549,550],"take":"subject2/o2/1/cam4","frame_ids":[543,544,545,546,547,548,549,550]} +{"filtered_tile_id":"7a497aab3749a0724827d27e:16","filtered_window_id":"7a497aab3749a0724827d27e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a497aab3749a0724827d27e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[551,552,553,554,555,556,557,558],"take":"subject2/o2/1/cam4","frame_ids":[551,552,553,554,555,556,557,558]} +{"filtered_tile_id":"7a497aab3749a0724827d27e:24","filtered_window_id":"7a497aab3749a0724827d27e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a497aab3749a0724827d27e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[559,560,561,562,563,564,565,566],"take":"subject2/o2/1/cam4","frame_ids":[559,560,561,562,563,564,565,566]} +{"filtered_tile_id":"7a497aab3749a0724827d27e:32","filtered_window_id":"7a497aab3749a0724827d27e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a497aab3749a0724827d27e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[567,568,569,570,571,572,573,574],"take":"subject2/o2/1/cam4","frame_ids":[567,568,569,570,571,572,573,574]} +{"filtered_tile_id":"7a497aab3749a0724827d27e:40","filtered_window_id":"7a497aab3749a0724827d27e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a497aab3749a0724827d27e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[575,576,577,578,579,580,581,582],"take":"subject2/o2/1/cam4","frame_ids":[575,576,577,578,579,580,581,582]} +{"filtered_tile_id":"7a497aab3749a0724827d27e:48","filtered_window_id":"7a497aab3749a0724827d27e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a497aab3749a0724827d27e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[583,584,585,586,587,588,589,590],"take":"subject2/o2/1/cam4","frame_ids":[583,584,585,586,587,588,589,590]} +{"filtered_tile_id":"7a497aab3749a0724827d27e:52","filtered_window_id":"7a497aab3749a0724827d27e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a497aab3749a0724827d27e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[587,588,589,590,591,592,593,594],"take":"subject2/o2/1/cam4","frame_ids":[587,588,589,590,591,592,593,594]} +{"filtered_tile_id":"7a6010e176a01e81604f74ab:0","filtered_window_id":"7a6010e176a01e81604f74ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a6010e176a01e81604f74ab/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject2/k1/0/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"7a6010e176a01e81604f74ab:8","filtered_window_id":"7a6010e176a01e81604f74ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a6010e176a01e81604f74ab/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[466,467,468,469,470,471,472,473],"take":"subject2/k1/0/cam4","frame_ids":[466,467,468,469,470,471,472,473]} +{"filtered_tile_id":"7a6010e176a01e81604f74ab:16","filtered_window_id":"7a6010e176a01e81604f74ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a6010e176a01e81604f74ab/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[474,475,476,477,478,479,480,481],"take":"subject2/k1/0/cam4","frame_ids":[474,475,476,477,478,479,480,481]} +{"filtered_tile_id":"7a6010e176a01e81604f74ab:24","filtered_window_id":"7a6010e176a01e81604f74ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a6010e176a01e81604f74ab/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[482,483,484,485,486,487,488,489],"take":"subject2/k1/0/cam4","frame_ids":[482,483,484,485,486,487,488,489]} +{"filtered_tile_id":"7a6a061a3f85509273c1fc98:0","filtered_window_id":"7a6a061a3f85509273c1fc98","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a6a061a3f85509273c1fc98/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[267,268,269,270,271,272,273,274],"take":"subject3/h2/4/cam4","frame_ids":[267,268,269,270,271,272,273,274]} +{"filtered_tile_id":"7a6a061a3f85509273c1fc98:8","filtered_window_id":"7a6a061a3f85509273c1fc98","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a6a061a3f85509273c1fc98/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[275,276,277,278,279,280,281,282],"take":"subject3/h2/4/cam4","frame_ids":[275,276,277,278,279,280,281,282]} +{"filtered_tile_id":"7a6a061a3f85509273c1fc98:16","filtered_window_id":"7a6a061a3f85509273c1fc98","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a6a061a3f85509273c1fc98/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[283,284,285,286,287,288,289,290],"take":"subject3/h2/4/cam4","frame_ids":[283,284,285,286,287,288,289,290]} +{"filtered_tile_id":"7a6a061a3f85509273c1fc98:24","filtered_window_id":"7a6a061a3f85509273c1fc98","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a6a061a3f85509273c1fc98/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[291,292,293,294,295,296,297,298],"take":"subject3/h2/4/cam4","frame_ids":[291,292,293,294,295,296,297,298]} +{"filtered_tile_id":"7a6a061a3f85509273c1fc98:26","filtered_window_id":"7a6a061a3f85509273c1fc98","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7a6a061a3f85509273c1fc98/native_gt.npz","filtered_start_offset":26,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject3/h2/4/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"7bd80888fb98f4065a09a702:0","filtered_window_id":"7bd80888fb98f4065a09a702","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7bd80888fb98f4065a09a702/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[719,720,721,722,723,724,725,726],"take":"subject2/h2/3/cam4","frame_ids":[719,720,721,722,723,724,725,726]} +{"filtered_tile_id":"7be1c3b72f382cc485bfe51a:0","filtered_window_id":"7be1c3b72f382cc485bfe51a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7be1c3b72f382cc485bfe51a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[697,698,699,700,701,702,703,704],"take":"subject2/o1/4/cam4","frame_ids":[697,698,699,700,701,702,703,704]} +{"filtered_tile_id":"7be1c3b72f382cc485bfe51a:8","filtered_window_id":"7be1c3b72f382cc485bfe51a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7be1c3b72f382cc485bfe51a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[705,706,707,708,709,710,711,712],"take":"subject2/o1/4/cam4","frame_ids":[705,706,707,708,709,710,711,712]} +{"filtered_tile_id":"7be1c3b72f382cc485bfe51a:16","filtered_window_id":"7be1c3b72f382cc485bfe51a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7be1c3b72f382cc485bfe51a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[713,714,715,716,717,718,719,720],"take":"subject2/o1/4/cam4","frame_ids":[713,714,715,716,717,718,719,720]} +{"filtered_tile_id":"7be1c3b72f382cc485bfe51a:24","filtered_window_id":"7be1c3b72f382cc485bfe51a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7be1c3b72f382cc485bfe51a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[721,722,723,724,725,726,727,728],"take":"subject2/o1/4/cam4","frame_ids":[721,722,723,724,725,726,727,728]} +{"filtered_tile_id":"7be1c3b72f382cc485bfe51a:32","filtered_window_id":"7be1c3b72f382cc485bfe51a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7be1c3b72f382cc485bfe51a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[729,730,731,732,733,734,735,736],"take":"subject2/o1/4/cam4","frame_ids":[729,730,731,732,733,734,735,736]} +{"filtered_tile_id":"7be1c3b72f382cc485bfe51a:40","filtered_window_id":"7be1c3b72f382cc485bfe51a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7be1c3b72f382cc485bfe51a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[737,738,739,740,741,742,743,744],"take":"subject2/o1/4/cam4","frame_ids":[737,738,739,740,741,742,743,744]} +{"filtered_tile_id":"7be1c3b72f382cc485bfe51a:48","filtered_window_id":"7be1c3b72f382cc485bfe51a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7be1c3b72f382cc485bfe51a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[745,746,747,748,749,750,751,752],"take":"subject2/o1/4/cam4","frame_ids":[745,746,747,748,749,750,751,752]} +{"filtered_tile_id":"7be1c3b72f382cc485bfe51a:52","filtered_window_id":"7be1c3b72f382cc485bfe51a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7be1c3b72f382cc485bfe51a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[749,750,751,752,753,754,755,756],"take":"subject2/o1/4/cam4","frame_ids":[749,750,751,752,753,754,755,756]} +{"filtered_tile_id":"7c2318f9e909c18fee557942:0","filtered_window_id":"7c2318f9e909c18fee557942","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c2318f9e909c18fee557942/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject3/k1/7/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"7c2318f9e909c18fee557942:8","filtered_window_id":"7c2318f9e909c18fee557942","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c2318f9e909c18fee557942/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[262,263,264,265,266,267,268,269],"take":"subject3/k1/7/cam4","frame_ids":[262,263,264,265,266,267,268,269]} +{"filtered_tile_id":"7c2318f9e909c18fee557942:16","filtered_window_id":"7c2318f9e909c18fee557942","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c2318f9e909c18fee557942/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[270,271,272,273,274,275,276,277],"take":"subject3/k1/7/cam4","frame_ids":[270,271,272,273,274,275,276,277]} +{"filtered_tile_id":"7c2318f9e909c18fee557942:19","filtered_window_id":"7c2318f9e909c18fee557942","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c2318f9e909c18fee557942/native_gt.npz","filtered_start_offset":19,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject3/k1/7/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"7c818b243946d7ee4d027602:0","filtered_window_id":"7c818b243946d7ee4d027602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c818b243946d7ee4d027602/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[499,500,501,502,503,504,505,506],"take":"subject3/h1/5/cam4","frame_ids":[499,500,501,502,503,504,505,506]} +{"filtered_tile_id":"7c818b243946d7ee4d027602:8","filtered_window_id":"7c818b243946d7ee4d027602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c818b243946d7ee4d027602/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[507,508,509,510,511,512,513,514],"take":"subject3/h1/5/cam4","frame_ids":[507,508,509,510,511,512,513,514]} +{"filtered_tile_id":"7c818b243946d7ee4d027602:16","filtered_window_id":"7c818b243946d7ee4d027602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c818b243946d7ee4d027602/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[515,516,517,518,519,520,521,522],"take":"subject3/h1/5/cam4","frame_ids":[515,516,517,518,519,520,521,522]} +{"filtered_tile_id":"7c818b243946d7ee4d027602:24","filtered_window_id":"7c818b243946d7ee4d027602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c818b243946d7ee4d027602/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[523,524,525,526,527,528,529,530],"take":"subject3/h1/5/cam4","frame_ids":[523,524,525,526,527,528,529,530]} +{"filtered_tile_id":"7c818b243946d7ee4d027602:32","filtered_window_id":"7c818b243946d7ee4d027602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c818b243946d7ee4d027602/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[531,532,533,534,535,536,537,538],"take":"subject3/h1/5/cam4","frame_ids":[531,532,533,534,535,536,537,538]} +{"filtered_tile_id":"7c818b243946d7ee4d027602:40","filtered_window_id":"7c818b243946d7ee4d027602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c818b243946d7ee4d027602/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[539,540,541,542,543,544,545,546],"take":"subject3/h1/5/cam4","frame_ids":[539,540,541,542,543,544,545,546]} +{"filtered_tile_id":"7c818b243946d7ee4d027602:48","filtered_window_id":"7c818b243946d7ee4d027602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c818b243946d7ee4d027602/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[547,548,549,550,551,552,553,554],"take":"subject3/h1/5/cam4","frame_ids":[547,548,549,550,551,552,553,554]} +{"filtered_tile_id":"7c818b243946d7ee4d027602:52","filtered_window_id":"7c818b243946d7ee4d027602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c818b243946d7ee4d027602/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[551,552,553,554,555,556,557,558],"take":"subject3/h1/5/cam4","frame_ids":[551,552,553,554,555,556,557,558]} +{"filtered_tile_id":"7c8854cb40dd390643185ab3:0","filtered_window_id":"7c8854cb40dd390643185ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c8854cb40dd390643185ab3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject3/h1/3/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"7c8854cb40dd390643185ab3:8","filtered_window_id":"7c8854cb40dd390643185ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c8854cb40dd390643185ab3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject3/h1/3/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"7c8854cb40dd390643185ab3:16","filtered_window_id":"7c8854cb40dd390643185ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c8854cb40dd390643185ab3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[572,573,574,575,576,577,578,579],"take":"subject3/h1/3/cam4","frame_ids":[572,573,574,575,576,577,578,579]} +{"filtered_tile_id":"7c8854cb40dd390643185ab3:24","filtered_window_id":"7c8854cb40dd390643185ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c8854cb40dd390643185ab3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[580,581,582,583,584,585,586,587],"take":"subject3/h1/3/cam4","frame_ids":[580,581,582,583,584,585,586,587]} +{"filtered_tile_id":"7c8854cb40dd390643185ab3:32","filtered_window_id":"7c8854cb40dd390643185ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c8854cb40dd390643185ab3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[588,589,590,591,592,593,594,595],"take":"subject3/h1/3/cam4","frame_ids":[588,589,590,591,592,593,594,595]} +{"filtered_tile_id":"7c8854cb40dd390643185ab3:40","filtered_window_id":"7c8854cb40dd390643185ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c8854cb40dd390643185ab3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[596,597,598,599,600,601,602,603],"take":"subject3/h1/3/cam4","frame_ids":[596,597,598,599,600,601,602,603]} +{"filtered_tile_id":"7c8854cb40dd390643185ab3:48","filtered_window_id":"7c8854cb40dd390643185ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c8854cb40dd390643185ab3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[604,605,606,607,608,609,610,611],"take":"subject3/h1/3/cam4","frame_ids":[604,605,606,607,608,609,610,611]} +{"filtered_tile_id":"7c8854cb40dd390643185ab3:52","filtered_window_id":"7c8854cb40dd390643185ab3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7c8854cb40dd390643185ab3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[608,609,610,611,612,613,614,615],"take":"subject3/h1/3/cam4","frame_ids":[608,609,610,611,612,613,614,615]} +{"filtered_tile_id":"7cd604baf75eb359feaa8798:0","filtered_window_id":"7cd604baf75eb359feaa8798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7cd604baf75eb359feaa8798/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o1/7/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"7cd604baf75eb359feaa8798:8","filtered_window_id":"7cd604baf75eb359feaa8798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7cd604baf75eb359feaa8798/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o1/7/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"7cd604baf75eb359feaa8798:16","filtered_window_id":"7cd604baf75eb359feaa8798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7cd604baf75eb359feaa8798/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o1/7/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"7cd604baf75eb359feaa8798:24","filtered_window_id":"7cd604baf75eb359feaa8798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7cd604baf75eb359feaa8798/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o1/7/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"7cd604baf75eb359feaa8798:32","filtered_window_id":"7cd604baf75eb359feaa8798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7cd604baf75eb359feaa8798/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o1/7/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"7cd604baf75eb359feaa8798:36","filtered_window_id":"7cd604baf75eb359feaa8798","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7cd604baf75eb359feaa8798/native_gt.npz","filtered_start_offset":36,"expected_frame_ids":[36,37,38,39,40,41,42,43],"take":"subject1/o1/7/cam4","frame_ids":[36,37,38,39,40,41,42,43]} +{"filtered_tile_id":"7d12852eaad8a5e9a84b254c:0","filtered_window_id":"7d12852eaad8a5e9a84b254c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7d12852eaad8a5e9a84b254c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject1/k1/4/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"7d12852eaad8a5e9a84b254c:8","filtered_window_id":"7d12852eaad8a5e9a84b254c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7d12852eaad8a5e9a84b254c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject1/k1/4/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"7d12852eaad8a5e9a84b254c:16","filtered_window_id":"7d12852eaad8a5e9a84b254c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7d12852eaad8a5e9a84b254c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[426,427,428,429,430,431,432,433],"take":"subject1/k1/4/cam4","frame_ids":[426,427,428,429,430,431,432,433]} +{"filtered_tile_id":"7d12852eaad8a5e9a84b254c:24","filtered_window_id":"7d12852eaad8a5e9a84b254c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7d12852eaad8a5e9a84b254c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[434,435,436,437,438,439,440,441],"take":"subject1/k1/4/cam4","frame_ids":[434,435,436,437,438,439,440,441]} +{"filtered_tile_id":"7d12852eaad8a5e9a84b254c:32","filtered_window_id":"7d12852eaad8a5e9a84b254c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7d12852eaad8a5e9a84b254c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject1/k1/4/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"7d12852eaad8a5e9a84b254c:40","filtered_window_id":"7d12852eaad8a5e9a84b254c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7d12852eaad8a5e9a84b254c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject1/k1/4/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"7d12852eaad8a5e9a84b254c:48","filtered_window_id":"7d12852eaad8a5e9a84b254c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7d12852eaad8a5e9a84b254c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject1/k1/4/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"7d12852eaad8a5e9a84b254c:52","filtered_window_id":"7d12852eaad8a5e9a84b254c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7d12852eaad8a5e9a84b254c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject1/k1/4/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"7db06120b58d414d6f626c05:0","filtered_window_id":"7db06120b58d414d6f626c05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db06120b58d414d6f626c05/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[232,233,234,235,236,237,238,239],"take":"subject2/k2/0/cam4","frame_ids":[232,233,234,235,236,237,238,239]} +{"filtered_tile_id":"7db06120b58d414d6f626c05:8","filtered_window_id":"7db06120b58d414d6f626c05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db06120b58d414d6f626c05/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[240,241,242,243,244,245,246,247],"take":"subject2/k2/0/cam4","frame_ids":[240,241,242,243,244,245,246,247]} +{"filtered_tile_id":"7db06120b58d414d6f626c05:16","filtered_window_id":"7db06120b58d414d6f626c05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db06120b58d414d6f626c05/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject2/k2/0/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"7db06120b58d414d6f626c05:24","filtered_window_id":"7db06120b58d414d6f626c05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db06120b58d414d6f626c05/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject2/k2/0/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"7db06120b58d414d6f626c05:32","filtered_window_id":"7db06120b58d414d6f626c05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db06120b58d414d6f626c05/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject2/k2/0/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"7db06120b58d414d6f626c05:40","filtered_window_id":"7db06120b58d414d6f626c05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db06120b58d414d6f626c05/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject2/k2/0/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"7db06120b58d414d6f626c05:48","filtered_window_id":"7db06120b58d414d6f626c05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db06120b58d414d6f626c05/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject2/k2/0/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"7db06120b58d414d6f626c05:52","filtered_window_id":"7db06120b58d414d6f626c05","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db06120b58d414d6f626c05/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[284,285,286,287,288,289,290,291],"take":"subject2/k2/0/cam4","frame_ids":[284,285,286,287,288,289,290,291]} +{"filtered_tile_id":"7db09075ef2ecc97de26d8c5:0","filtered_window_id":"7db09075ef2ecc97de26d8c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db09075ef2ecc97de26d8c5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject2/o1/5/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"7db09075ef2ecc97de26d8c5:8","filtered_window_id":"7db09075ef2ecc97de26d8c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db09075ef2ecc97de26d8c5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[459,460,461,462,463,464,465,466],"take":"subject2/o1/5/cam4","frame_ids":[459,460,461,462,463,464,465,466]} +{"filtered_tile_id":"7db09075ef2ecc97de26d8c5:16","filtered_window_id":"7db09075ef2ecc97de26d8c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db09075ef2ecc97de26d8c5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[467,468,469,470,471,472,473,474],"take":"subject2/o1/5/cam4","frame_ids":[467,468,469,470,471,472,473,474]} +{"filtered_tile_id":"7db09075ef2ecc97de26d8c5:24","filtered_window_id":"7db09075ef2ecc97de26d8c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db09075ef2ecc97de26d8c5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[475,476,477,478,479,480,481,482],"take":"subject2/o1/5/cam4","frame_ids":[475,476,477,478,479,480,481,482]} +{"filtered_tile_id":"7db09075ef2ecc97de26d8c5:32","filtered_window_id":"7db09075ef2ecc97de26d8c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db09075ef2ecc97de26d8c5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[483,484,485,486,487,488,489,490],"take":"subject2/o1/5/cam4","frame_ids":[483,484,485,486,487,488,489,490]} +{"filtered_tile_id":"7db09075ef2ecc97de26d8c5:40","filtered_window_id":"7db09075ef2ecc97de26d8c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db09075ef2ecc97de26d8c5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[491,492,493,494,495,496,497,498],"take":"subject2/o1/5/cam4","frame_ids":[491,492,493,494,495,496,497,498]} +{"filtered_tile_id":"7db09075ef2ecc97de26d8c5:48","filtered_window_id":"7db09075ef2ecc97de26d8c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7db09075ef2ecc97de26d8c5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[499,500,501,502,503,504,505,506],"take":"subject2/o1/5/cam4","frame_ids":[499,500,501,502,503,504,505,506]} +{"filtered_tile_id":"7f0ef63680338d58bba06faa:0","filtered_window_id":"7f0ef63680338d58bba06faa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f0ef63680338d58bba06faa/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject1/h1/7/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"7f0ef63680338d58bba06faa:8","filtered_window_id":"7f0ef63680338d58bba06faa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f0ef63680338d58bba06faa/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[469,470,471,472,473,474,475,476],"take":"subject1/h1/7/cam4","frame_ids":[469,470,471,472,473,474,475,476]} +{"filtered_tile_id":"7f0ef63680338d58bba06faa:16","filtered_window_id":"7f0ef63680338d58bba06faa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f0ef63680338d58bba06faa/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[477,478,479,480,481,482,483,484],"take":"subject1/h1/7/cam4","frame_ids":[477,478,479,480,481,482,483,484]} +{"filtered_tile_id":"7f0ef63680338d58bba06faa:24","filtered_window_id":"7f0ef63680338d58bba06faa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f0ef63680338d58bba06faa/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[485,486,487,488,489,490,491,492],"take":"subject1/h1/7/cam4","frame_ids":[485,486,487,488,489,490,491,492]} +{"filtered_tile_id":"7f0ef63680338d58bba06faa:32","filtered_window_id":"7f0ef63680338d58bba06faa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f0ef63680338d58bba06faa/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[493,494,495,496,497,498,499,500],"take":"subject1/h1/7/cam4","frame_ids":[493,494,495,496,497,498,499,500]} +{"filtered_tile_id":"7f0ef63680338d58bba06faa:40","filtered_window_id":"7f0ef63680338d58bba06faa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f0ef63680338d58bba06faa/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[501,502,503,504,505,506,507,508],"take":"subject1/h1/7/cam4","frame_ids":[501,502,503,504,505,506,507,508]} +{"filtered_tile_id":"7f0ef63680338d58bba06faa:48","filtered_window_id":"7f0ef63680338d58bba06faa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f0ef63680338d58bba06faa/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[509,510,511,512,513,514,515,516],"take":"subject1/h1/7/cam4","frame_ids":[509,510,511,512,513,514,515,516]} +{"filtered_tile_id":"7f0ef63680338d58bba06faa:52","filtered_window_id":"7f0ef63680338d58bba06faa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f0ef63680338d58bba06faa/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[513,514,515,516,517,518,519,520],"take":"subject1/h1/7/cam4","frame_ids":[513,514,515,516,517,518,519,520]} +{"filtered_tile_id":"7f7fcd6cdcc3f93944c4eef1:0","filtered_window_id":"7f7fcd6cdcc3f93944c4eef1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f7fcd6cdcc3f93944c4eef1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/k1/4/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"7f7fcd6cdcc3f93944c4eef1:8","filtered_window_id":"7f7fcd6cdcc3f93944c4eef1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f7fcd6cdcc3f93944c4eef1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/k1/4/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"7f7fcd6cdcc3f93944c4eef1:16","filtered_window_id":"7f7fcd6cdcc3f93944c4eef1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f7fcd6cdcc3f93944c4eef1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/k1/4/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"7f7fcd6cdcc3f93944c4eef1:24","filtered_window_id":"7f7fcd6cdcc3f93944c4eef1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f7fcd6cdcc3f93944c4eef1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/k1/4/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"7f7fcd6cdcc3f93944c4eef1:32","filtered_window_id":"7f7fcd6cdcc3f93944c4eef1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f7fcd6cdcc3f93944c4eef1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/k1/4/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"7f7fcd6cdcc3f93944c4eef1:40","filtered_window_id":"7f7fcd6cdcc3f93944c4eef1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f7fcd6cdcc3f93944c4eef1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/k1/4/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"7f7fcd6cdcc3f93944c4eef1:48","filtered_window_id":"7f7fcd6cdcc3f93944c4eef1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f7fcd6cdcc3f93944c4eef1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/k1/4/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"7f7fcd6cdcc3f93944c4eef1:52","filtered_window_id":"7f7fcd6cdcc3f93944c4eef1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f7fcd6cdcc3f93944c4eef1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/k1/4/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"7f830925b9b929db946b5229:0","filtered_window_id":"7f830925b9b929db946b5229","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f830925b9b929db946b5229/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/o1/5/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"7f830925b9b929db946b5229:8","filtered_window_id":"7f830925b9b929db946b5229","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f830925b9b929db946b5229/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/o1/5/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"7f830925b9b929db946b5229:16","filtered_window_id":"7f830925b9b929db946b5229","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f830925b9b929db946b5229/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/o1/5/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"7f830925b9b929db946b5229:24","filtered_window_id":"7f830925b9b929db946b5229","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f830925b9b929db946b5229/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/o1/5/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"7f830925b9b929db946b5229:32","filtered_window_id":"7f830925b9b929db946b5229","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f830925b9b929db946b5229/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/o1/5/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"7f830925b9b929db946b5229:40","filtered_window_id":"7f830925b9b929db946b5229","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f830925b9b929db946b5229/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/o1/5/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"7f830925b9b929db946b5229:48","filtered_window_id":"7f830925b9b929db946b5229","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f830925b9b929db946b5229/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/o1/5/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"7f830925b9b929db946b5229:52","filtered_window_id":"7f830925b9b929db946b5229","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7f830925b9b929db946b5229/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/o1/5/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"7fc48615c4ea3cff44bbaf38:0","filtered_window_id":"7fc48615c4ea3cff44bbaf38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc48615c4ea3cff44bbaf38/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[909,910,911,912,913,914,915,916],"take":"subject1/h1/3/cam4","frame_ids":[909,910,911,912,913,914,915,916]} +{"filtered_tile_id":"7fc48615c4ea3cff44bbaf38:8","filtered_window_id":"7fc48615c4ea3cff44bbaf38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc48615c4ea3cff44bbaf38/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[917,918,919,920,921,922,923,924],"take":"subject1/h1/3/cam4","frame_ids":[917,918,919,920,921,922,923,924]} +{"filtered_tile_id":"7fc48615c4ea3cff44bbaf38:12","filtered_window_id":"7fc48615c4ea3cff44bbaf38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc48615c4ea3cff44bbaf38/native_gt.npz","filtered_start_offset":12,"expected_frame_ids":[921,922,923,924,925,926,927,928],"take":"subject1/h1/3/cam4","frame_ids":[921,922,923,924,925,926,927,928]} +{"filtered_tile_id":"7fc6f80c3d85ebfab8f228d4:0","filtered_window_id":"7fc6f80c3d85ebfab8f228d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc6f80c3d85ebfab8f228d4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[558,559,560,561,562,563,564,565],"take":"subject1/h2/3/cam4","frame_ids":[558,559,560,561,562,563,564,565]} +{"filtered_tile_id":"7fc6f80c3d85ebfab8f228d4:8","filtered_window_id":"7fc6f80c3d85ebfab8f228d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc6f80c3d85ebfab8f228d4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[566,567,568,569,570,571,572,573],"take":"subject1/h2/3/cam4","frame_ids":[566,567,568,569,570,571,572,573]} +{"filtered_tile_id":"7fc6f80c3d85ebfab8f228d4:16","filtered_window_id":"7fc6f80c3d85ebfab8f228d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc6f80c3d85ebfab8f228d4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[574,575,576,577,578,579,580,581],"take":"subject1/h2/3/cam4","frame_ids":[574,575,576,577,578,579,580,581]} +{"filtered_tile_id":"7fc6f80c3d85ebfab8f228d4:24","filtered_window_id":"7fc6f80c3d85ebfab8f228d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc6f80c3d85ebfab8f228d4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[582,583,584,585,586,587,588,589],"take":"subject1/h2/3/cam4","frame_ids":[582,583,584,585,586,587,588,589]} +{"filtered_tile_id":"7fc6f80c3d85ebfab8f228d4:32","filtered_window_id":"7fc6f80c3d85ebfab8f228d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc6f80c3d85ebfab8f228d4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[590,591,592,593,594,595,596,597],"take":"subject1/h2/3/cam4","frame_ids":[590,591,592,593,594,595,596,597]} +{"filtered_tile_id":"7fc6f80c3d85ebfab8f228d4:40","filtered_window_id":"7fc6f80c3d85ebfab8f228d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc6f80c3d85ebfab8f228d4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[598,599,600,601,602,603,604,605],"take":"subject1/h2/3/cam4","frame_ids":[598,599,600,601,602,603,604,605]} +{"filtered_tile_id":"7fc6f80c3d85ebfab8f228d4:48","filtered_window_id":"7fc6f80c3d85ebfab8f228d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc6f80c3d85ebfab8f228d4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[606,607,608,609,610,611,612,613],"take":"subject1/h2/3/cam4","frame_ids":[606,607,608,609,610,611,612,613]} +{"filtered_tile_id":"7fc6f80c3d85ebfab8f228d4:52","filtered_window_id":"7fc6f80c3d85ebfab8f228d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/7fc6f80c3d85ebfab8f228d4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[610,611,612,613,614,615,616,617],"take":"subject1/h2/3/cam4","frame_ids":[610,611,612,613,614,615,616,617]} +{"filtered_tile_id":"804688f08f03e522fd3e82b6:0","filtered_window_id":"804688f08f03e522fd3e82b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/804688f08f03e522fd3e82b6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject3/h1/7/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"804688f08f03e522fd3e82b6:8","filtered_window_id":"804688f08f03e522fd3e82b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/804688f08f03e522fd3e82b6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject3/h1/7/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"804688f08f03e522fd3e82b6:16","filtered_window_id":"804688f08f03e522fd3e82b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/804688f08f03e522fd3e82b6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject3/h1/7/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"804688f08f03e522fd3e82b6:24","filtered_window_id":"804688f08f03e522fd3e82b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/804688f08f03e522fd3e82b6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject3/h1/7/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"804688f08f03e522fd3e82b6:32","filtered_window_id":"804688f08f03e522fd3e82b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/804688f08f03e522fd3e82b6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject3/h1/7/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"804688f08f03e522fd3e82b6:40","filtered_window_id":"804688f08f03e522fd3e82b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/804688f08f03e522fd3e82b6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject3/h1/7/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"804688f08f03e522fd3e82b6:48","filtered_window_id":"804688f08f03e522fd3e82b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/804688f08f03e522fd3e82b6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject3/h1/7/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"804688f08f03e522fd3e82b6:52","filtered_window_id":"804688f08f03e522fd3e82b6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/804688f08f03e522fd3e82b6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject3/h1/7/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"809a408cbed47aa509f42976:0","filtered_window_id":"809a408cbed47aa509f42976","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/809a408cbed47aa509f42976/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[416,417,418,419,420,421,422,423],"take":"subject1/h2/3/cam4","frame_ids":[416,417,418,419,420,421,422,423]} +{"filtered_tile_id":"809a408cbed47aa509f42976:4","filtered_window_id":"809a408cbed47aa509f42976","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/809a408cbed47aa509f42976/native_gt.npz","filtered_start_offset":4,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject1/h2/3/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"80d6fdb8ba0cf2d157a56ad3:0","filtered_window_id":"80d6fdb8ba0cf2d157a56ad3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/80d6fdb8ba0cf2d157a56ad3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject3/h1/1/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"80d6fdb8ba0cf2d157a56ad3:8","filtered_window_id":"80d6fdb8ba0cf2d157a56ad3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/80d6fdb8ba0cf2d157a56ad3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject3/h1/1/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"80d6fdb8ba0cf2d157a56ad3:16","filtered_window_id":"80d6fdb8ba0cf2d157a56ad3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/80d6fdb8ba0cf2d157a56ad3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject3/h1/1/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"80d6fdb8ba0cf2d157a56ad3:24","filtered_window_id":"80d6fdb8ba0cf2d157a56ad3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/80d6fdb8ba0cf2d157a56ad3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject3/h1/1/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"80d6fdb8ba0cf2d157a56ad3:32","filtered_window_id":"80d6fdb8ba0cf2d157a56ad3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/80d6fdb8ba0cf2d157a56ad3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject3/h1/1/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"80d6fdb8ba0cf2d157a56ad3:40","filtered_window_id":"80d6fdb8ba0cf2d157a56ad3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/80d6fdb8ba0cf2d157a56ad3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject3/h1/1/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"80d6fdb8ba0cf2d157a56ad3:44","filtered_window_id":"80d6fdb8ba0cf2d157a56ad3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/80d6fdb8ba0cf2d157a56ad3/native_gt.npz","filtered_start_offset":44,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject3/h1/1/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"811097c3455469029b3641c5:0","filtered_window_id":"811097c3455469029b3641c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/811097c3455469029b3641c5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[10,11,12,13,14,15,16,17],"take":"subject2/h2/3/cam4","frame_ids":[10,11,12,13,14,15,16,17]} +{"filtered_tile_id":"811097c3455469029b3641c5:8","filtered_window_id":"811097c3455469029b3641c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/811097c3455469029b3641c5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[18,19,20,21,22,23,24,25],"take":"subject2/h2/3/cam4","frame_ids":[18,19,20,21,22,23,24,25]} +{"filtered_tile_id":"811097c3455469029b3641c5:16","filtered_window_id":"811097c3455469029b3641c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/811097c3455469029b3641c5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[26,27,28,29,30,31,32,33],"take":"subject2/h2/3/cam4","frame_ids":[26,27,28,29,30,31,32,33]} +{"filtered_tile_id":"811097c3455469029b3641c5:24","filtered_window_id":"811097c3455469029b3641c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/811097c3455469029b3641c5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[34,35,36,37,38,39,40,41],"take":"subject2/h2/3/cam4","frame_ids":[34,35,36,37,38,39,40,41]} +{"filtered_tile_id":"811097c3455469029b3641c5:32","filtered_window_id":"811097c3455469029b3641c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/811097c3455469029b3641c5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[42,43,44,45,46,47,48,49],"take":"subject2/h2/3/cam4","frame_ids":[42,43,44,45,46,47,48,49]} +{"filtered_tile_id":"811097c3455469029b3641c5:40","filtered_window_id":"811097c3455469029b3641c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/811097c3455469029b3641c5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[50,51,52,53,54,55,56,57],"take":"subject2/h2/3/cam4","frame_ids":[50,51,52,53,54,55,56,57]} +{"filtered_tile_id":"811097c3455469029b3641c5:48","filtered_window_id":"811097c3455469029b3641c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/811097c3455469029b3641c5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[58,59,60,61,62,63,64,65],"take":"subject2/h2/3/cam4","frame_ids":[58,59,60,61,62,63,64,65]} +{"filtered_tile_id":"811097c3455469029b3641c5:52","filtered_window_id":"811097c3455469029b3641c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/811097c3455469029b3641c5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[62,63,64,65,66,67,68,69],"take":"subject2/h2/3/cam4","frame_ids":[62,63,64,65,66,67,68,69]} +{"filtered_tile_id":"81a0355340c375e24f674d01:0","filtered_window_id":"81a0355340c375e24f674d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81a0355340c375e24f674d01/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject3/k1/0/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"81a0355340c375e24f674d01:8","filtered_window_id":"81a0355340c375e24f674d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81a0355340c375e24f674d01/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject3/k1/0/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"81a0355340c375e24f674d01:16","filtered_window_id":"81a0355340c375e24f674d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81a0355340c375e24f674d01/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject3/k1/0/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"81a0355340c375e24f674d01:24","filtered_window_id":"81a0355340c375e24f674d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81a0355340c375e24f674d01/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[341,342,343,344,345,346,347,348],"take":"subject3/k1/0/cam4","frame_ids":[341,342,343,344,345,346,347,348]} +{"filtered_tile_id":"81a0355340c375e24f674d01:32","filtered_window_id":"81a0355340c375e24f674d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81a0355340c375e24f674d01/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[349,350,351,352,353,354,355,356],"take":"subject3/k1/0/cam4","frame_ids":[349,350,351,352,353,354,355,356]} +{"filtered_tile_id":"81a0355340c375e24f674d01:40","filtered_window_id":"81a0355340c375e24f674d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81a0355340c375e24f674d01/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject3/k1/0/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"81a0355340c375e24f674d01:48","filtered_window_id":"81a0355340c375e24f674d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81a0355340c375e24f674d01/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject3/k1/0/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"81a0355340c375e24f674d01:52","filtered_window_id":"81a0355340c375e24f674d01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81a0355340c375e24f674d01/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[369,370,371,372,373,374,375,376],"take":"subject3/k1/0/cam4","frame_ids":[369,370,371,372,373,374,375,376]} +{"filtered_tile_id":"81c86892016a89ab176134fe:0","filtered_window_id":"81c86892016a89ab176134fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81c86892016a89ab176134fe/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[9,10,11,12,13,14,15,16],"take":"subject2/o2/5/cam4","frame_ids":[9,10,11,12,13,14,15,16]} +{"filtered_tile_id":"81c86892016a89ab176134fe:8","filtered_window_id":"81c86892016a89ab176134fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81c86892016a89ab176134fe/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[17,18,19,20,21,22,23,24],"take":"subject2/o2/5/cam4","frame_ids":[17,18,19,20,21,22,23,24]} +{"filtered_tile_id":"81c86892016a89ab176134fe:16","filtered_window_id":"81c86892016a89ab176134fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81c86892016a89ab176134fe/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[25,26,27,28,29,30,31,32],"take":"subject2/o2/5/cam4","frame_ids":[25,26,27,28,29,30,31,32]} +{"filtered_tile_id":"81c86892016a89ab176134fe:24","filtered_window_id":"81c86892016a89ab176134fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81c86892016a89ab176134fe/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[33,34,35,36,37,38,39,40],"take":"subject2/o2/5/cam4","frame_ids":[33,34,35,36,37,38,39,40]} +{"filtered_tile_id":"81c86892016a89ab176134fe:32","filtered_window_id":"81c86892016a89ab176134fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81c86892016a89ab176134fe/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[41,42,43,44,45,46,47,48],"take":"subject2/o2/5/cam4","frame_ids":[41,42,43,44,45,46,47,48]} +{"filtered_tile_id":"81c86892016a89ab176134fe:39","filtered_window_id":"81c86892016a89ab176134fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81c86892016a89ab176134fe/native_gt.npz","filtered_start_offset":39,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/o2/5/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"81d165c599126d664544430b:0","filtered_window_id":"81d165c599126d664544430b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81d165c599126d664544430b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject2/o2/1/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"81d165c599126d664544430b:8","filtered_window_id":"81d165c599126d664544430b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81d165c599126d664544430b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[93,94,95,96,97,98,99,100],"take":"subject2/o2/1/cam4","frame_ids":[93,94,95,96,97,98,99,100]} +{"filtered_tile_id":"81d165c599126d664544430b:16","filtered_window_id":"81d165c599126d664544430b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81d165c599126d664544430b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[101,102,103,104,105,106,107,108],"take":"subject2/o2/1/cam4","frame_ids":[101,102,103,104,105,106,107,108]} +{"filtered_tile_id":"81d165c599126d664544430b:24","filtered_window_id":"81d165c599126d664544430b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81d165c599126d664544430b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[109,110,111,112,113,114,115,116],"take":"subject2/o2/1/cam4","frame_ids":[109,110,111,112,113,114,115,116]} +{"filtered_tile_id":"81d165c599126d664544430b:32","filtered_window_id":"81d165c599126d664544430b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81d165c599126d664544430b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[117,118,119,120,121,122,123,124],"take":"subject2/o2/1/cam4","frame_ids":[117,118,119,120,121,122,123,124]} +{"filtered_tile_id":"81d165c599126d664544430b:40","filtered_window_id":"81d165c599126d664544430b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81d165c599126d664544430b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[125,126,127,128,129,130,131,132],"take":"subject2/o2/1/cam4","frame_ids":[125,126,127,128,129,130,131,132]} +{"filtered_tile_id":"81d165c599126d664544430b:48","filtered_window_id":"81d165c599126d664544430b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81d165c599126d664544430b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject2/o2/1/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"81d165c599126d664544430b:52","filtered_window_id":"81d165c599126d664544430b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/81d165c599126d664544430b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject2/o2/1/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"8215eee7ed4bbf0b8692382e:0","filtered_window_id":"8215eee7ed4bbf0b8692382e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8215eee7ed4bbf0b8692382e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject3/k1/0/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"8215eee7ed4bbf0b8692382e:8","filtered_window_id":"8215eee7ed4bbf0b8692382e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8215eee7ed4bbf0b8692382e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject3/k1/0/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"8215eee7ed4bbf0b8692382e:16","filtered_window_id":"8215eee7ed4bbf0b8692382e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8215eee7ed4bbf0b8692382e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject3/k1/0/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"8215eee7ed4bbf0b8692382e:24","filtered_window_id":"8215eee7ed4bbf0b8692382e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8215eee7ed4bbf0b8692382e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject3/k1/0/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"8215eee7ed4bbf0b8692382e:32","filtered_window_id":"8215eee7ed4bbf0b8692382e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8215eee7ed4bbf0b8692382e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject3/k1/0/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"8215eee7ed4bbf0b8692382e:40","filtered_window_id":"8215eee7ed4bbf0b8692382e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8215eee7ed4bbf0b8692382e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[246,247,248,249,250,251,252,253],"take":"subject3/k1/0/cam4","frame_ids":[246,247,248,249,250,251,252,253]} +{"filtered_tile_id":"8215eee7ed4bbf0b8692382e:48","filtered_window_id":"8215eee7ed4bbf0b8692382e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8215eee7ed4bbf0b8692382e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject3/k1/0/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"8215eee7ed4bbf0b8692382e:52","filtered_window_id":"8215eee7ed4bbf0b8692382e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8215eee7ed4bbf0b8692382e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject3/k1/0/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"82381e846164447f16fba004:0","filtered_window_id":"82381e846164447f16fba004","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/82381e846164447f16fba004/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject2/k1/6/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"82381e846164447f16fba004:8","filtered_window_id":"82381e846164447f16fba004","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/82381e846164447f16fba004/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject2/k1/6/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"82381e846164447f16fba004:16","filtered_window_id":"82381e846164447f16fba004","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/82381e846164447f16fba004/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject2/k1/6/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"82381e846164447f16fba004:24","filtered_window_id":"82381e846164447f16fba004","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/82381e846164447f16fba004/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject2/k1/6/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"82381e846164447f16fba004:32","filtered_window_id":"82381e846164447f16fba004","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/82381e846164447f16fba004/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject2/k1/6/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"82381e846164447f16fba004:40","filtered_window_id":"82381e846164447f16fba004","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/82381e846164447f16fba004/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject2/k1/6/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"82381e846164447f16fba004:48","filtered_window_id":"82381e846164447f16fba004","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/82381e846164447f16fba004/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject2/k1/6/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"82381e846164447f16fba004:52","filtered_window_id":"82381e846164447f16fba004","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/82381e846164447f16fba004/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject2/k1/6/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"8241ff6d13edeef468b3f30e:0","filtered_window_id":"8241ff6d13edeef468b3f30e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8241ff6d13edeef468b3f30e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[319,320,321,322,323,324,325,326],"take":"subject3/k1/3/cam4","frame_ids":[319,320,321,322,323,324,325,326]} +{"filtered_tile_id":"8241ff6d13edeef468b3f30e:8","filtered_window_id":"8241ff6d13edeef468b3f30e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8241ff6d13edeef468b3f30e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[327,328,329,330,331,332,333,334],"take":"subject3/k1/3/cam4","frame_ids":[327,328,329,330,331,332,333,334]} +{"filtered_tile_id":"8241ff6d13edeef468b3f30e:16","filtered_window_id":"8241ff6d13edeef468b3f30e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8241ff6d13edeef468b3f30e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[335,336,337,338,339,340,341,342],"take":"subject3/k1/3/cam4","frame_ids":[335,336,337,338,339,340,341,342]} +{"filtered_tile_id":"8241ff6d13edeef468b3f30e:24","filtered_window_id":"8241ff6d13edeef468b3f30e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8241ff6d13edeef468b3f30e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[343,344,345,346,347,348,349,350],"take":"subject3/k1/3/cam4","frame_ids":[343,344,345,346,347,348,349,350]} +{"filtered_tile_id":"8241ff6d13edeef468b3f30e:32","filtered_window_id":"8241ff6d13edeef468b3f30e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8241ff6d13edeef468b3f30e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[351,352,353,354,355,356,357,358],"take":"subject3/k1/3/cam4","frame_ids":[351,352,353,354,355,356,357,358]} +{"filtered_tile_id":"8241ff6d13edeef468b3f30e:40","filtered_window_id":"8241ff6d13edeef468b3f30e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8241ff6d13edeef468b3f30e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[359,360,361,362,363,364,365,366],"take":"subject3/k1/3/cam4","frame_ids":[359,360,361,362,363,364,365,366]} +{"filtered_tile_id":"8241ff6d13edeef468b3f30e:48","filtered_window_id":"8241ff6d13edeef468b3f30e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8241ff6d13edeef468b3f30e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[367,368,369,370,371,372,373,374],"take":"subject3/k1/3/cam4","frame_ids":[367,368,369,370,371,372,373,374]} +{"filtered_tile_id":"8241ff6d13edeef468b3f30e:52","filtered_window_id":"8241ff6d13edeef468b3f30e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8241ff6d13edeef468b3f30e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[371,372,373,374,375,376,377,378],"take":"subject3/k1/3/cam4","frame_ids":[371,372,373,374,375,376,377,378]} +{"filtered_tile_id":"8251ceeaf81bc24f60e768ea:0","filtered_window_id":"8251ceeaf81bc24f60e768ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8251ceeaf81bc24f60e768ea/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[304,305,306,307,308,309,310,311],"take":"subject1/h1/1/cam4","frame_ids":[304,305,306,307,308,309,310,311]} +{"filtered_tile_id":"8251ceeaf81bc24f60e768ea:8","filtered_window_id":"8251ceeaf81bc24f60e768ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8251ceeaf81bc24f60e768ea/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[312,313,314,315,316,317,318,319],"take":"subject1/h1/1/cam4","frame_ids":[312,313,314,315,316,317,318,319]} +{"filtered_tile_id":"8251ceeaf81bc24f60e768ea:16","filtered_window_id":"8251ceeaf81bc24f60e768ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8251ceeaf81bc24f60e768ea/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[320,321,322,323,324,325,326,327],"take":"subject1/h1/1/cam4","frame_ids":[320,321,322,323,324,325,326,327]} +{"filtered_tile_id":"8251ceeaf81bc24f60e768ea:24","filtered_window_id":"8251ceeaf81bc24f60e768ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8251ceeaf81bc24f60e768ea/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[328,329,330,331,332,333,334,335],"take":"subject1/h1/1/cam4","frame_ids":[328,329,330,331,332,333,334,335]} +{"filtered_tile_id":"8251ceeaf81bc24f60e768ea:32","filtered_window_id":"8251ceeaf81bc24f60e768ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8251ceeaf81bc24f60e768ea/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[336,337,338,339,340,341,342,343],"take":"subject1/h1/1/cam4","frame_ids":[336,337,338,339,340,341,342,343]} +{"filtered_tile_id":"8251ceeaf81bc24f60e768ea:40","filtered_window_id":"8251ceeaf81bc24f60e768ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8251ceeaf81bc24f60e768ea/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[344,345,346,347,348,349,350,351],"take":"subject1/h1/1/cam4","frame_ids":[344,345,346,347,348,349,350,351]} +{"filtered_tile_id":"8251ceeaf81bc24f60e768ea:48","filtered_window_id":"8251ceeaf81bc24f60e768ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8251ceeaf81bc24f60e768ea/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject1/h1/1/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"8251ceeaf81bc24f60e768ea:52","filtered_window_id":"8251ceeaf81bc24f60e768ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8251ceeaf81bc24f60e768ea/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[356,357,358,359,360,361,362,363],"take":"subject1/h1/1/cam4","frame_ids":[356,357,358,359,360,361,362,363]} +{"filtered_tile_id":"8277cce2528709902344f799:0","filtered_window_id":"8277cce2528709902344f799","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8277cce2528709902344f799/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[490,491,492,493,494,495,496,497],"take":"subject3/h1/1/cam4","frame_ids":[490,491,492,493,494,495,496,497]} +{"filtered_tile_id":"8277cce2528709902344f799:8","filtered_window_id":"8277cce2528709902344f799","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8277cce2528709902344f799/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[498,499,500,501,502,503,504,505],"take":"subject3/h1/1/cam4","frame_ids":[498,499,500,501,502,503,504,505]} +{"filtered_tile_id":"8277cce2528709902344f799:16","filtered_window_id":"8277cce2528709902344f799","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8277cce2528709902344f799/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[506,507,508,509,510,511,512,513],"take":"subject3/h1/1/cam4","frame_ids":[506,507,508,509,510,511,512,513]} +{"filtered_tile_id":"8277cce2528709902344f799:24","filtered_window_id":"8277cce2528709902344f799","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8277cce2528709902344f799/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[514,515,516,517,518,519,520,521],"take":"subject3/h1/1/cam4","frame_ids":[514,515,516,517,518,519,520,521]} +{"filtered_tile_id":"8277cce2528709902344f799:32","filtered_window_id":"8277cce2528709902344f799","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8277cce2528709902344f799/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[522,523,524,525,526,527,528,529],"take":"subject3/h1/1/cam4","frame_ids":[522,523,524,525,526,527,528,529]} +{"filtered_tile_id":"8277cce2528709902344f799:40","filtered_window_id":"8277cce2528709902344f799","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8277cce2528709902344f799/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[530,531,532,533,534,535,536,537],"take":"subject3/h1/1/cam4","frame_ids":[530,531,532,533,534,535,536,537]} +{"filtered_tile_id":"8277cce2528709902344f799:48","filtered_window_id":"8277cce2528709902344f799","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8277cce2528709902344f799/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[538,539,540,541,542,543,544,545],"take":"subject3/h1/1/cam4","frame_ids":[538,539,540,541,542,543,544,545]} +{"filtered_tile_id":"8277cce2528709902344f799:52","filtered_window_id":"8277cce2528709902344f799","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8277cce2528709902344f799/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[542,543,544,545,546,547,548,549],"take":"subject3/h1/1/cam4","frame_ids":[542,543,544,545,546,547,548,549]} +{"filtered_tile_id":"83238972947659b36acb6802:0","filtered_window_id":"83238972947659b36acb6802","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83238972947659b36acb6802/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[455,456,457,458,459,460,461,462],"take":"subject1/k2/3/cam4","frame_ids":[455,456,457,458,459,460,461,462]} +{"filtered_tile_id":"83238972947659b36acb6802:8","filtered_window_id":"83238972947659b36acb6802","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83238972947659b36acb6802/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject1/k2/3/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"83238972947659b36acb6802:16","filtered_window_id":"83238972947659b36acb6802","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83238972947659b36acb6802/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[471,472,473,474,475,476,477,478],"take":"subject1/k2/3/cam4","frame_ids":[471,472,473,474,475,476,477,478]} +{"filtered_tile_id":"83238972947659b36acb6802:24","filtered_window_id":"83238972947659b36acb6802","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83238972947659b36acb6802/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[479,480,481,482,483,484,485,486],"take":"subject1/k2/3/cam4","frame_ids":[479,480,481,482,483,484,485,486]} +{"filtered_tile_id":"83238972947659b36acb6802:32","filtered_window_id":"83238972947659b36acb6802","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83238972947659b36acb6802/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject1/k2/3/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"83238972947659b36acb6802:40","filtered_window_id":"83238972947659b36acb6802","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83238972947659b36acb6802/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[495,496,497,498,499,500,501,502],"take":"subject1/k2/3/cam4","frame_ids":[495,496,497,498,499,500,501,502]} +{"filtered_tile_id":"83238972947659b36acb6802:45","filtered_window_id":"83238972947659b36acb6802","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83238972947659b36acb6802/native_gt.npz","filtered_start_offset":45,"expected_frame_ids":[500,501,502,503,504,505,506,507],"take":"subject1/k2/3/cam4","frame_ids":[500,501,502,503,504,505,506,507]} +{"filtered_tile_id":"83485253f02dc05722ccae92:0","filtered_window_id":"83485253f02dc05722ccae92","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83485253f02dc05722ccae92/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject1/o2/4/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"83fdf9de7931a760ef696f4c:0","filtered_window_id":"83fdf9de7931a760ef696f4c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83fdf9de7931a760ef696f4c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o1/6/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"83fdf9de7931a760ef696f4c:8","filtered_window_id":"83fdf9de7931a760ef696f4c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83fdf9de7931a760ef696f4c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o1/6/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"83fdf9de7931a760ef696f4c:16","filtered_window_id":"83fdf9de7931a760ef696f4c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83fdf9de7931a760ef696f4c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o1/6/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"83fdf9de7931a760ef696f4c:24","filtered_window_id":"83fdf9de7931a760ef696f4c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83fdf9de7931a760ef696f4c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o1/6/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"83fdf9de7931a760ef696f4c:32","filtered_window_id":"83fdf9de7931a760ef696f4c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83fdf9de7931a760ef696f4c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o1/6/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"83fdf9de7931a760ef696f4c:40","filtered_window_id":"83fdf9de7931a760ef696f4c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83fdf9de7931a760ef696f4c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/o1/6/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"83fdf9de7931a760ef696f4c:48","filtered_window_id":"83fdf9de7931a760ef696f4c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83fdf9de7931a760ef696f4c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/o1/6/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"83fdf9de7931a760ef696f4c:52","filtered_window_id":"83fdf9de7931a760ef696f4c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/83fdf9de7931a760ef696f4c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/o1/6/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"844d114d034a57745b81617a:0","filtered_window_id":"844d114d034a57745b81617a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/844d114d034a57745b81617a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject2/o2/5/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"844d114d034a57745b81617a:8","filtered_window_id":"844d114d034a57745b81617a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/844d114d034a57745b81617a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject2/o2/5/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"844d114d034a57745b81617a:16","filtered_window_id":"844d114d034a57745b81617a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/844d114d034a57745b81617a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject2/o2/5/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"844d114d034a57745b81617a:24","filtered_window_id":"844d114d034a57745b81617a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/844d114d034a57745b81617a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject2/o2/5/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"844d114d034a57745b81617a:32","filtered_window_id":"844d114d034a57745b81617a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/844d114d034a57745b81617a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject2/o2/5/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"844d114d034a57745b81617a:40","filtered_window_id":"844d114d034a57745b81617a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/844d114d034a57745b81617a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject2/o2/5/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"844d114d034a57745b81617a:48","filtered_window_id":"844d114d034a57745b81617a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/844d114d034a57745b81617a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject2/o2/5/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"844d114d034a57745b81617a:52","filtered_window_id":"844d114d034a57745b81617a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/844d114d034a57745b81617a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[144,145,146,147,148,149,150,151],"take":"subject2/o2/5/cam4","frame_ids":[144,145,146,147,148,149,150,151]} +{"filtered_tile_id":"848e56ab9b627e485b5bcdd9:0","filtered_window_id":"848e56ab9b627e485b5bcdd9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/848e56ab9b627e485b5bcdd9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[735,736,737,738,739,740,741,742],"take":"subject2/h2/3/cam4","frame_ids":[735,736,737,738,739,740,741,742]} +{"filtered_tile_id":"848e56ab9b627e485b5bcdd9:8","filtered_window_id":"848e56ab9b627e485b5bcdd9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/848e56ab9b627e485b5bcdd9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[743,744,745,746,747,748,749,750],"take":"subject2/h2/3/cam4","frame_ids":[743,744,745,746,747,748,749,750]} +{"filtered_tile_id":"848e56ab9b627e485b5bcdd9:16","filtered_window_id":"848e56ab9b627e485b5bcdd9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/848e56ab9b627e485b5bcdd9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[751,752,753,754,755,756,757,758],"take":"subject2/h2/3/cam4","frame_ids":[751,752,753,754,755,756,757,758]} +{"filtered_tile_id":"848e56ab9b627e485b5bcdd9:24","filtered_window_id":"848e56ab9b627e485b5bcdd9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/848e56ab9b627e485b5bcdd9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[759,760,761,762,763,764,765,766],"take":"subject2/h2/3/cam4","frame_ids":[759,760,761,762,763,764,765,766]} +{"filtered_tile_id":"848e56ab9b627e485b5bcdd9:32","filtered_window_id":"848e56ab9b627e485b5bcdd9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/848e56ab9b627e485b5bcdd9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[767,768,769,770,771,772,773,774],"take":"subject2/h2/3/cam4","frame_ids":[767,768,769,770,771,772,773,774]} +{"filtered_tile_id":"848e56ab9b627e485b5bcdd9:40","filtered_window_id":"848e56ab9b627e485b5bcdd9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/848e56ab9b627e485b5bcdd9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[775,776,777,778,779,780,781,782],"take":"subject2/h2/3/cam4","frame_ids":[775,776,777,778,779,780,781,782]} +{"filtered_tile_id":"848e56ab9b627e485b5bcdd9:48","filtered_window_id":"848e56ab9b627e485b5bcdd9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/848e56ab9b627e485b5bcdd9/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[783,784,785,786,787,788,789,790],"take":"subject2/h2/3/cam4","frame_ids":[783,784,785,786,787,788,789,790]} +{"filtered_tile_id":"848e56ab9b627e485b5bcdd9:51","filtered_window_id":"848e56ab9b627e485b5bcdd9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/848e56ab9b627e485b5bcdd9/native_gt.npz","filtered_start_offset":51,"expected_frame_ids":[786,787,788,789,790,791,792,793],"take":"subject2/h2/3/cam4","frame_ids":[786,787,788,789,790,791,792,793]} +{"filtered_tile_id":"849a2700d41c77a95b799b27:0","filtered_window_id":"849a2700d41c77a95b799b27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/849a2700d41c77a95b799b27/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject3/k1/0/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"849a2700d41c77a95b799b27:5","filtered_window_id":"849a2700d41c77a95b799b27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/849a2700d41c77a95b799b27/native_gt.npz","filtered_start_offset":5,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject3/k1/0/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"84e328841ba3f7eaa2629763:0","filtered_window_id":"84e328841ba3f7eaa2629763","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/84e328841ba3f7eaa2629763/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[402,403,404,405,406,407,408,409],"take":"subject2/h1/0/cam4","frame_ids":[402,403,404,405,406,407,408,409]} +{"filtered_tile_id":"84e328841ba3f7eaa2629763:8","filtered_window_id":"84e328841ba3f7eaa2629763","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/84e328841ba3f7eaa2629763/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject2/h1/0/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"84e328841ba3f7eaa2629763:16","filtered_window_id":"84e328841ba3f7eaa2629763","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/84e328841ba3f7eaa2629763/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject2/h1/0/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"84e328841ba3f7eaa2629763:24","filtered_window_id":"84e328841ba3f7eaa2629763","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/84e328841ba3f7eaa2629763/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[426,427,428,429,430,431,432,433],"take":"subject2/h1/0/cam4","frame_ids":[426,427,428,429,430,431,432,433]} +{"filtered_tile_id":"84e328841ba3f7eaa2629763:32","filtered_window_id":"84e328841ba3f7eaa2629763","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/84e328841ba3f7eaa2629763/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[434,435,436,437,438,439,440,441],"take":"subject2/h1/0/cam4","frame_ids":[434,435,436,437,438,439,440,441]} +{"filtered_tile_id":"84e328841ba3f7eaa2629763:40","filtered_window_id":"84e328841ba3f7eaa2629763","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/84e328841ba3f7eaa2629763/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject2/h1/0/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"84e328841ba3f7eaa2629763:48","filtered_window_id":"84e328841ba3f7eaa2629763","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/84e328841ba3f7eaa2629763/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject2/h1/0/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"84e328841ba3f7eaa2629763:52","filtered_window_id":"84e328841ba3f7eaa2629763","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/84e328841ba3f7eaa2629763/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[454,455,456,457,458,459,460,461],"take":"subject2/h1/0/cam4","frame_ids":[454,455,456,457,458,459,460,461]} +{"filtered_tile_id":"8518bb59326e5202316815de:0","filtered_window_id":"8518bb59326e5202316815de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8518bb59326e5202316815de/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject2/o2/5/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"8518bb59326e5202316815de:8","filtered_window_id":"8518bb59326e5202316815de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8518bb59326e5202316815de/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject2/o2/5/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"8518bb59326e5202316815de:16","filtered_window_id":"8518bb59326e5202316815de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8518bb59326e5202316815de/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject2/o2/5/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"8518bb59326e5202316815de:24","filtered_window_id":"8518bb59326e5202316815de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8518bb59326e5202316815de/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject2/o2/5/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"8518bb59326e5202316815de:32","filtered_window_id":"8518bb59326e5202316815de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8518bb59326e5202316815de/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject2/o2/5/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"8518bb59326e5202316815de:40","filtered_window_id":"8518bb59326e5202316815de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8518bb59326e5202316815de/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[192,193,194,195,196,197,198,199],"take":"subject2/o2/5/cam4","frame_ids":[192,193,194,195,196,197,198,199]} +{"filtered_tile_id":"8518bb59326e5202316815de:48","filtered_window_id":"8518bb59326e5202316815de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8518bb59326e5202316815de/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[200,201,202,203,204,205,206,207],"take":"subject2/o2/5/cam4","frame_ids":[200,201,202,203,204,205,206,207]} +{"filtered_tile_id":"8518bb59326e5202316815de:52","filtered_window_id":"8518bb59326e5202316815de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8518bb59326e5202316815de/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject2/o2/5/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"855ebd980d821b6362973c00:0","filtered_window_id":"855ebd980d821b6362973c00","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/855ebd980d821b6362973c00/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[809,810,811,812,813,814,815,816],"take":"subject2/h1/3/cam4","frame_ids":[809,810,811,812,813,814,815,816]} +{"filtered_tile_id":"855ebd980d821b6362973c00:8","filtered_window_id":"855ebd980d821b6362973c00","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/855ebd980d821b6362973c00/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[817,818,819,820,821,822,823,824],"take":"subject2/h1/3/cam4","frame_ids":[817,818,819,820,821,822,823,824]} +{"filtered_tile_id":"855ebd980d821b6362973c00:16","filtered_window_id":"855ebd980d821b6362973c00","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/855ebd980d821b6362973c00/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[825,826,827,828,829,830,831,832],"take":"subject2/h1/3/cam4","frame_ids":[825,826,827,828,829,830,831,832]} +{"filtered_tile_id":"855ebd980d821b6362973c00:19","filtered_window_id":"855ebd980d821b6362973c00","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/855ebd980d821b6362973c00/native_gt.npz","filtered_start_offset":19,"expected_frame_ids":[828,829,830,831,832,833,834,835],"take":"subject2/h1/3/cam4","frame_ids":[828,829,830,831,832,833,834,835]} +{"filtered_tile_id":"858e6e6cfb15178afc2f9eac:0","filtered_window_id":"858e6e6cfb15178afc2f9eac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/858e6e6cfb15178afc2f9eac/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject3/h1/6/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"858e6e6cfb15178afc2f9eac:8","filtered_window_id":"858e6e6cfb15178afc2f9eac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/858e6e6cfb15178afc2f9eac/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject3/h1/6/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"858e6e6cfb15178afc2f9eac:16","filtered_window_id":"858e6e6cfb15178afc2f9eac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/858e6e6cfb15178afc2f9eac/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject3/h1/6/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"858e6e6cfb15178afc2f9eac:24","filtered_window_id":"858e6e6cfb15178afc2f9eac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/858e6e6cfb15178afc2f9eac/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject3/h1/6/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"858e6e6cfb15178afc2f9eac:32","filtered_window_id":"858e6e6cfb15178afc2f9eac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/858e6e6cfb15178afc2f9eac/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject3/h1/6/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"858e6e6cfb15178afc2f9eac:40","filtered_window_id":"858e6e6cfb15178afc2f9eac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/858e6e6cfb15178afc2f9eac/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject3/h1/6/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"858e6e6cfb15178afc2f9eac:48","filtered_window_id":"858e6e6cfb15178afc2f9eac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/858e6e6cfb15178afc2f9eac/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject3/h1/6/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"858e6e6cfb15178afc2f9eac:52","filtered_window_id":"858e6e6cfb15178afc2f9eac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/858e6e6cfb15178afc2f9eac/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject3/h1/6/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"85ac1c760cbcb94be0dffd57:0","filtered_window_id":"85ac1c760cbcb94be0dffd57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/85ac1c760cbcb94be0dffd57/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject1/k1/3/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"85ac1c760cbcb94be0dffd57:8","filtered_window_id":"85ac1c760cbcb94be0dffd57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/85ac1c760cbcb94be0dffd57/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject1/k1/3/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"85ac1c760cbcb94be0dffd57:16","filtered_window_id":"85ac1c760cbcb94be0dffd57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/85ac1c760cbcb94be0dffd57/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject1/k1/3/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"85ac1c760cbcb94be0dffd57:24","filtered_window_id":"85ac1c760cbcb94be0dffd57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/85ac1c760cbcb94be0dffd57/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject1/k1/3/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"85ac1c760cbcb94be0dffd57:32","filtered_window_id":"85ac1c760cbcb94be0dffd57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/85ac1c760cbcb94be0dffd57/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject1/k1/3/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"85ac1c760cbcb94be0dffd57:40","filtered_window_id":"85ac1c760cbcb94be0dffd57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/85ac1c760cbcb94be0dffd57/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject1/k1/3/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"85ac1c760cbcb94be0dffd57:48","filtered_window_id":"85ac1c760cbcb94be0dffd57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/85ac1c760cbcb94be0dffd57/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/k1/3/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"85ac1c760cbcb94be0dffd57:52","filtered_window_id":"85ac1c760cbcb94be0dffd57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/85ac1c760cbcb94be0dffd57/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[112,113,114,115,116,117,118,119],"take":"subject1/k1/3/cam4","frame_ids":[112,113,114,115,116,117,118,119]} +{"filtered_tile_id":"8631c4f485f234108c441117:0","filtered_window_id":"8631c4f485f234108c441117","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8631c4f485f234108c441117/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[484,485,486,487,488,489,490,491],"take":"subject1/h1/2/cam4","frame_ids":[484,485,486,487,488,489,490,491]} +{"filtered_tile_id":"8662cad1ca1c99b3b7c75b01:0","filtered_window_id":"8662cad1ca1c99b3b7c75b01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8662cad1ca1c99b3b7c75b01/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject1/o2/3/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"8662cad1ca1c99b3b7c75b01:8","filtered_window_id":"8662cad1ca1c99b3b7c75b01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8662cad1ca1c99b3b7c75b01/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject1/o2/3/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"8662cad1ca1c99b3b7c75b01:16","filtered_window_id":"8662cad1ca1c99b3b7c75b01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8662cad1ca1c99b3b7c75b01/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject1/o2/3/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"8662cad1ca1c99b3b7c75b01:24","filtered_window_id":"8662cad1ca1c99b3b7c75b01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8662cad1ca1c99b3b7c75b01/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject1/o2/3/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"8662cad1ca1c99b3b7c75b01:32","filtered_window_id":"8662cad1ca1c99b3b7c75b01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8662cad1ca1c99b3b7c75b01/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject1/o2/3/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"8662cad1ca1c99b3b7c75b01:40","filtered_window_id":"8662cad1ca1c99b3b7c75b01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8662cad1ca1c99b3b7c75b01/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject1/o2/3/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"8662cad1ca1c99b3b7c75b01:48","filtered_window_id":"8662cad1ca1c99b3b7c75b01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8662cad1ca1c99b3b7c75b01/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[236,237,238,239,240,241,242,243],"take":"subject1/o2/3/cam4","frame_ids":[236,237,238,239,240,241,242,243]} +{"filtered_tile_id":"8662cad1ca1c99b3b7c75b01:52","filtered_window_id":"8662cad1ca1c99b3b7c75b01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8662cad1ca1c99b3b7c75b01/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[240,241,242,243,244,245,246,247],"take":"subject1/o2/3/cam4","frame_ids":[240,241,242,243,244,245,246,247]} +{"filtered_tile_id":"86723a405340e359784e1a50:0","filtered_window_id":"86723a405340e359784e1a50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86723a405340e359784e1a50/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject2/h1/0/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"86723a405340e359784e1a50:8","filtered_window_id":"86723a405340e359784e1a50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86723a405340e359784e1a50/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject2/h1/0/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"86723a405340e359784e1a50:16","filtered_window_id":"86723a405340e359784e1a50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86723a405340e359784e1a50/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject2/h1/0/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"86723a405340e359784e1a50:24","filtered_window_id":"86723a405340e359784e1a50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86723a405340e359784e1a50/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject2/h1/0/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"86723a405340e359784e1a50:32","filtered_window_id":"86723a405340e359784e1a50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86723a405340e359784e1a50/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[374,375,376,377,378,379,380,381],"take":"subject2/h1/0/cam4","frame_ids":[374,375,376,377,378,379,380,381]} +{"filtered_tile_id":"86723a405340e359784e1a50:40","filtered_window_id":"86723a405340e359784e1a50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86723a405340e359784e1a50/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[382,383,384,385,386,387,388,389],"take":"subject2/h1/0/cam4","frame_ids":[382,383,384,385,386,387,388,389]} +{"filtered_tile_id":"86723a405340e359784e1a50:48","filtered_window_id":"86723a405340e359784e1a50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86723a405340e359784e1a50/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject2/h1/0/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"86723a405340e359784e1a50:52","filtered_window_id":"86723a405340e359784e1a50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86723a405340e359784e1a50/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[394,395,396,397,398,399,400,401],"take":"subject2/h1/0/cam4","frame_ids":[394,395,396,397,398,399,400,401]} +{"filtered_tile_id":"86bb1ae1fe818146b724bbc5:0","filtered_window_id":"86bb1ae1fe818146b724bbc5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86bb1ae1fe818146b724bbc5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject2/o2/1/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"86bb1ae1fe818146b724bbc5:8","filtered_window_id":"86bb1ae1fe818146b724bbc5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86bb1ae1fe818146b724bbc5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject2/o2/1/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"86bb1ae1fe818146b724bbc5:16","filtered_window_id":"86bb1ae1fe818146b724bbc5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86bb1ae1fe818146b724bbc5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject2/o2/1/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"86bb1ae1fe818146b724bbc5:24","filtered_window_id":"86bb1ae1fe818146b724bbc5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86bb1ae1fe818146b724bbc5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject2/o2/1/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"86bb1ae1fe818146b724bbc5:32","filtered_window_id":"86bb1ae1fe818146b724bbc5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86bb1ae1fe818146b724bbc5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject2/o2/1/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"86bb1ae1fe818146b724bbc5:40","filtered_window_id":"86bb1ae1fe818146b724bbc5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86bb1ae1fe818146b724bbc5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject2/o2/1/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"86bb1ae1fe818146b724bbc5:48","filtered_window_id":"86bb1ae1fe818146b724bbc5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86bb1ae1fe818146b724bbc5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject2/o2/1/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"86bb1ae1fe818146b724bbc5:52","filtered_window_id":"86bb1ae1fe818146b724bbc5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86bb1ae1fe818146b724bbc5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject2/o2/1/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"86d1005604de0f845b6cfee8:0","filtered_window_id":"86d1005604de0f845b6cfee8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86d1005604de0f845b6cfee8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject1/h1/1/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"86d1005604de0f845b6cfee8:8","filtered_window_id":"86d1005604de0f845b6cfee8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86d1005604de0f845b6cfee8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject1/h1/1/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"86d1005604de0f845b6cfee8:16","filtered_window_id":"86d1005604de0f845b6cfee8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86d1005604de0f845b6cfee8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject1/h1/1/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"86d1005604de0f845b6cfee8:24","filtered_window_id":"86d1005604de0f845b6cfee8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86d1005604de0f845b6cfee8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject1/h1/1/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"86d1005604de0f845b6cfee8:32","filtered_window_id":"86d1005604de0f845b6cfee8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86d1005604de0f845b6cfee8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject1/h1/1/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"86d1005604de0f845b6cfee8:40","filtered_window_id":"86d1005604de0f845b6cfee8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86d1005604de0f845b6cfee8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject1/h1/1/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"86d1005604de0f845b6cfee8:48","filtered_window_id":"86d1005604de0f845b6cfee8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86d1005604de0f845b6cfee8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject1/h1/1/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"86d1005604de0f845b6cfee8:52","filtered_window_id":"86d1005604de0f845b6cfee8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/86d1005604de0f845b6cfee8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[416,417,418,419,420,421,422,423],"take":"subject1/h1/1/cam4","frame_ids":[416,417,418,419,420,421,422,423]} +{"filtered_tile_id":"8736b4af0657b90c18f18e99:0","filtered_window_id":"8736b4af0657b90c18f18e99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8736b4af0657b90c18f18e99/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject3/h2/4/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"8736b4af0657b90c18f18e99:8","filtered_window_id":"8736b4af0657b90c18f18e99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8736b4af0657b90c18f18e99/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject3/h2/4/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"8736b4af0657b90c18f18e99:16","filtered_window_id":"8736b4af0657b90c18f18e99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8736b4af0657b90c18f18e99/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject3/h2/4/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"8736b4af0657b90c18f18e99:24","filtered_window_id":"8736b4af0657b90c18f18e99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8736b4af0657b90c18f18e99/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject3/h2/4/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"8736b4af0657b90c18f18e99:32","filtered_window_id":"8736b4af0657b90c18f18e99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8736b4af0657b90c18f18e99/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject3/h2/4/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"8736b4af0657b90c18f18e99:40","filtered_window_id":"8736b4af0657b90c18f18e99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8736b4af0657b90c18f18e99/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject3/h2/4/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"8736b4af0657b90c18f18e99:48","filtered_window_id":"8736b4af0657b90c18f18e99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8736b4af0657b90c18f18e99/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject3/h2/4/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"8736b4af0657b90c18f18e99:51","filtered_window_id":"8736b4af0657b90c18f18e99","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8736b4af0657b90c18f18e99/native_gt.npz","filtered_start_offset":51,"expected_frame_ids":[118,119,120,121,122,123,124,125],"take":"subject3/h2/4/cam4","frame_ids":[118,119,120,121,122,123,124,125]} +{"filtered_tile_id":"87802b1df370f0f1484452fb:0","filtered_window_id":"87802b1df370f0f1484452fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87802b1df370f0f1484452fb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[565,566,567,568,569,570,571,572],"take":"subject1/o2/6/cam4","frame_ids":[565,566,567,568,569,570,571,572]} +{"filtered_tile_id":"87802b1df370f0f1484452fb:8","filtered_window_id":"87802b1df370f0f1484452fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87802b1df370f0f1484452fb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[573,574,575,576,577,578,579,580],"take":"subject1/o2/6/cam4","frame_ids":[573,574,575,576,577,578,579,580]} +{"filtered_tile_id":"87802b1df370f0f1484452fb:16","filtered_window_id":"87802b1df370f0f1484452fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87802b1df370f0f1484452fb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[581,582,583,584,585,586,587,588],"take":"subject1/o2/6/cam4","frame_ids":[581,582,583,584,585,586,587,588]} +{"filtered_tile_id":"87802b1df370f0f1484452fb:24","filtered_window_id":"87802b1df370f0f1484452fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87802b1df370f0f1484452fb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[589,590,591,592,593,594,595,596],"take":"subject1/o2/6/cam4","frame_ids":[589,590,591,592,593,594,595,596]} +{"filtered_tile_id":"87802b1df370f0f1484452fb:32","filtered_window_id":"87802b1df370f0f1484452fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87802b1df370f0f1484452fb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[597,598,599,600,601,602,603,604],"take":"subject1/o2/6/cam4","frame_ids":[597,598,599,600,601,602,603,604]} +{"filtered_tile_id":"87802b1df370f0f1484452fb:33","filtered_window_id":"87802b1df370f0f1484452fb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87802b1df370f0f1484452fb/native_gt.npz","filtered_start_offset":33,"expected_frame_ids":[598,599,600,601,602,603,604,605],"take":"subject1/o2/6/cam4","frame_ids":[598,599,600,601,602,603,604,605]} +{"filtered_tile_id":"87a804ca1f5f8a02727a5acc:0","filtered_window_id":"87a804ca1f5f8a02727a5acc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87a804ca1f5f8a02727a5acc/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject3/h1/5/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"87a804ca1f5f8a02727a5acc:8","filtered_window_id":"87a804ca1f5f8a02727a5acc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87a804ca1f5f8a02727a5acc/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject3/h1/5/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"87a804ca1f5f8a02727a5acc:16","filtered_window_id":"87a804ca1f5f8a02727a5acc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87a804ca1f5f8a02727a5acc/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject3/h1/5/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"87a804ca1f5f8a02727a5acc:24","filtered_window_id":"87a804ca1f5f8a02727a5acc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87a804ca1f5f8a02727a5acc/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject3/h1/5/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"87a804ca1f5f8a02727a5acc:32","filtered_window_id":"87a804ca1f5f8a02727a5acc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87a804ca1f5f8a02727a5acc/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject3/h1/5/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"87a804ca1f5f8a02727a5acc:40","filtered_window_id":"87a804ca1f5f8a02727a5acc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87a804ca1f5f8a02727a5acc/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject3/h1/5/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"87a804ca1f5f8a02727a5acc:48","filtered_window_id":"87a804ca1f5f8a02727a5acc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87a804ca1f5f8a02727a5acc/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject3/h1/5/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"87a804ca1f5f8a02727a5acc:52","filtered_window_id":"87a804ca1f5f8a02727a5acc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/87a804ca1f5f8a02727a5acc/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject3/h1/5/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"8835baa06d212bf0432d06b1:0","filtered_window_id":"8835baa06d212bf0432d06b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8835baa06d212bf0432d06b1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject2/h2/5/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"8835baa06d212bf0432d06b1:8","filtered_window_id":"8835baa06d212bf0432d06b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8835baa06d212bf0432d06b1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject2/h2/5/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"8835baa06d212bf0432d06b1:16","filtered_window_id":"8835baa06d212bf0432d06b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8835baa06d212bf0432d06b1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject2/h2/5/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"8835baa06d212bf0432d06b1:24","filtered_window_id":"8835baa06d212bf0432d06b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8835baa06d212bf0432d06b1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject2/h2/5/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"8835baa06d212bf0432d06b1:32","filtered_window_id":"8835baa06d212bf0432d06b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8835baa06d212bf0432d06b1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject2/h2/5/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"8835baa06d212bf0432d06b1:40","filtered_window_id":"8835baa06d212bf0432d06b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8835baa06d212bf0432d06b1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject2/h2/5/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"8835baa06d212bf0432d06b1:48","filtered_window_id":"8835baa06d212bf0432d06b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8835baa06d212bf0432d06b1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject2/h2/5/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"8835baa06d212bf0432d06b1:52","filtered_window_id":"8835baa06d212bf0432d06b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8835baa06d212bf0432d06b1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject2/h2/5/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"88b280581343200334b02b71:0","filtered_window_id":"88b280581343200334b02b71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88b280581343200334b02b71/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[77,78,79,80,81,82,83,84],"take":"subject3/h1/2/cam4","frame_ids":[77,78,79,80,81,82,83,84]} +{"filtered_tile_id":"88b280581343200334b02b71:4","filtered_window_id":"88b280581343200334b02b71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88b280581343200334b02b71/native_gt.npz","filtered_start_offset":4,"expected_frame_ids":[81,82,83,84,85,86,87,88],"take":"subject3/h1/2/cam4","frame_ids":[81,82,83,84,85,86,87,88]} +{"filtered_tile_id":"88f1183e932b7ee11fdb8c5d:0","filtered_window_id":"88f1183e932b7ee11fdb8c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88f1183e932b7ee11fdb8c5d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[411,412,413,414,415,416,417,418],"take":"subject1/o1/5/cam4","frame_ids":[411,412,413,414,415,416,417,418]} +{"filtered_tile_id":"88f1183e932b7ee11fdb8c5d:8","filtered_window_id":"88f1183e932b7ee11fdb8c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88f1183e932b7ee11fdb8c5d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[419,420,421,422,423,424,425,426],"take":"subject1/o1/5/cam4","frame_ids":[419,420,421,422,423,424,425,426]} +{"filtered_tile_id":"88f1183e932b7ee11fdb8c5d:16","filtered_window_id":"88f1183e932b7ee11fdb8c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88f1183e932b7ee11fdb8c5d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject1/o1/5/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"88f1183e932b7ee11fdb8c5d:24","filtered_window_id":"88f1183e932b7ee11fdb8c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88f1183e932b7ee11fdb8c5d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/o1/5/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"88f1183e932b7ee11fdb8c5d:32","filtered_window_id":"88f1183e932b7ee11fdb8c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88f1183e932b7ee11fdb8c5d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject1/o1/5/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"88f1183e932b7ee11fdb8c5d:40","filtered_window_id":"88f1183e932b7ee11fdb8c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88f1183e932b7ee11fdb8c5d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject1/o1/5/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"88f1183e932b7ee11fdb8c5d:48","filtered_window_id":"88f1183e932b7ee11fdb8c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88f1183e932b7ee11fdb8c5d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[459,460,461,462,463,464,465,466],"take":"subject1/o1/5/cam4","frame_ids":[459,460,461,462,463,464,465,466]} +{"filtered_tile_id":"88f1183e932b7ee11fdb8c5d:52","filtered_window_id":"88f1183e932b7ee11fdb8c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/88f1183e932b7ee11fdb8c5d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject1/o1/5/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"8900fcc6aac390409170ac7c:0","filtered_window_id":"8900fcc6aac390409170ac7c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8900fcc6aac390409170ac7c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[696,697,698,699,700,701,702,703],"take":"subject3/h2/3/cam4","frame_ids":[696,697,698,699,700,701,702,703]} +{"filtered_tile_id":"8900fcc6aac390409170ac7c:8","filtered_window_id":"8900fcc6aac390409170ac7c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8900fcc6aac390409170ac7c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[704,705,706,707,708,709,710,711],"take":"subject3/h2/3/cam4","frame_ids":[704,705,706,707,708,709,710,711]} +{"filtered_tile_id":"8900fcc6aac390409170ac7c:16","filtered_window_id":"8900fcc6aac390409170ac7c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8900fcc6aac390409170ac7c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[712,713,714,715,716,717,718,719],"take":"subject3/h2/3/cam4","frame_ids":[712,713,714,715,716,717,718,719]} +{"filtered_tile_id":"8900fcc6aac390409170ac7c:24","filtered_window_id":"8900fcc6aac390409170ac7c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8900fcc6aac390409170ac7c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[720,721,722,723,724,725,726,727],"take":"subject3/h2/3/cam4","frame_ids":[720,721,722,723,724,725,726,727]} +{"filtered_tile_id":"8900fcc6aac390409170ac7c:32","filtered_window_id":"8900fcc6aac390409170ac7c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8900fcc6aac390409170ac7c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[728,729,730,731,732,733,734,735],"take":"subject3/h2/3/cam4","frame_ids":[728,729,730,731,732,733,734,735]} +{"filtered_tile_id":"8900fcc6aac390409170ac7c:40","filtered_window_id":"8900fcc6aac390409170ac7c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8900fcc6aac390409170ac7c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[736,737,738,739,740,741,742,743],"take":"subject3/h2/3/cam4","frame_ids":[736,737,738,739,740,741,742,743]} +{"filtered_tile_id":"8900fcc6aac390409170ac7c:48","filtered_window_id":"8900fcc6aac390409170ac7c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8900fcc6aac390409170ac7c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[744,745,746,747,748,749,750,751],"take":"subject3/h2/3/cam4","frame_ids":[744,745,746,747,748,749,750,751]} +{"filtered_tile_id":"8900fcc6aac390409170ac7c:52","filtered_window_id":"8900fcc6aac390409170ac7c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8900fcc6aac390409170ac7c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[748,749,750,751,752,753,754,755],"take":"subject3/h2/3/cam4","frame_ids":[748,749,750,751,752,753,754,755]} +{"filtered_tile_id":"891dfe1717f0bdf0fff28a18:0","filtered_window_id":"891dfe1717f0bdf0fff28a18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/891dfe1717f0bdf0fff28a18/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject1/h2/3/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"891dfe1717f0bdf0fff28a18:8","filtered_window_id":"891dfe1717f0bdf0fff28a18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/891dfe1717f0bdf0fff28a18/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject1/h2/3/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"891dfe1717f0bdf0fff28a18:14","filtered_window_id":"891dfe1717f0bdf0fff28a18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/891dfe1717f0bdf0fff28a18/native_gt.npz","filtered_start_offset":14,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject1/h2/3/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"8a89c52469075e1c172df271:0","filtered_window_id":"8a89c52469075e1c172df271","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8a89c52469075e1c172df271/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[900,901,902,903,904,905,906,907],"take":"subject2/o1/2/cam4","frame_ids":[900,901,902,903,904,905,906,907]} +{"filtered_tile_id":"8a89c52469075e1c172df271:8","filtered_window_id":"8a89c52469075e1c172df271","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8a89c52469075e1c172df271/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[908,909,910,911,912,913,914,915],"take":"subject2/o1/2/cam4","frame_ids":[908,909,910,911,912,913,914,915]} +{"filtered_tile_id":"8a89c52469075e1c172df271:16","filtered_window_id":"8a89c52469075e1c172df271","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8a89c52469075e1c172df271/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[916,917,918,919,920,921,922,923],"take":"subject2/o1/2/cam4","frame_ids":[916,917,918,919,920,921,922,923]} +{"filtered_tile_id":"8a89c52469075e1c172df271:24","filtered_window_id":"8a89c52469075e1c172df271","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8a89c52469075e1c172df271/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[924,925,926,927,928,929,930,931],"take":"subject2/o1/2/cam4","frame_ids":[924,925,926,927,928,929,930,931]} +{"filtered_tile_id":"8a89c52469075e1c172df271:32","filtered_window_id":"8a89c52469075e1c172df271","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8a89c52469075e1c172df271/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[932,933,934,935,936,937,938,939],"take":"subject2/o1/2/cam4","frame_ids":[932,933,934,935,936,937,938,939]} +{"filtered_tile_id":"8a89c52469075e1c172df271:40","filtered_window_id":"8a89c52469075e1c172df271","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8a89c52469075e1c172df271/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[940,941,942,943,944,945,946,947],"take":"subject2/o1/2/cam4","frame_ids":[940,941,942,943,944,945,946,947]} +{"filtered_tile_id":"8a89c52469075e1c172df271:48","filtered_window_id":"8a89c52469075e1c172df271","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8a89c52469075e1c172df271/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[948,949,950,951,952,953,954,955],"take":"subject2/o1/2/cam4","frame_ids":[948,949,950,951,952,953,954,955]} +{"filtered_tile_id":"8a89c52469075e1c172df271:52","filtered_window_id":"8a89c52469075e1c172df271","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8a89c52469075e1c172df271/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[952,953,954,955,956,957,958,959],"take":"subject2/o1/2/cam4","frame_ids":[952,953,954,955,956,957,958,959]} +{"filtered_tile_id":"8b6eaaa48ca785474e92f21e:0","filtered_window_id":"8b6eaaa48ca785474e92f21e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b6eaaa48ca785474e92f21e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[351,352,353,354,355,356,357,358],"take":"subject1/o1/3/cam4","frame_ids":[351,352,353,354,355,356,357,358]} +{"filtered_tile_id":"8b6eaaa48ca785474e92f21e:8","filtered_window_id":"8b6eaaa48ca785474e92f21e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b6eaaa48ca785474e92f21e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[359,360,361,362,363,364,365,366],"take":"subject1/o1/3/cam4","frame_ids":[359,360,361,362,363,364,365,366]} +{"filtered_tile_id":"8b6eaaa48ca785474e92f21e:16","filtered_window_id":"8b6eaaa48ca785474e92f21e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b6eaaa48ca785474e92f21e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[367,368,369,370,371,372,373,374],"take":"subject1/o1/3/cam4","frame_ids":[367,368,369,370,371,372,373,374]} +{"filtered_tile_id":"8b6eaaa48ca785474e92f21e:24","filtered_window_id":"8b6eaaa48ca785474e92f21e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b6eaaa48ca785474e92f21e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[375,376,377,378,379,380,381,382],"take":"subject1/o1/3/cam4","frame_ids":[375,376,377,378,379,380,381,382]} +{"filtered_tile_id":"8b6eaaa48ca785474e92f21e:32","filtered_window_id":"8b6eaaa48ca785474e92f21e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b6eaaa48ca785474e92f21e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject1/o1/3/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"8b6eaaa48ca785474e92f21e:40","filtered_window_id":"8b6eaaa48ca785474e92f21e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b6eaaa48ca785474e92f21e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject1/o1/3/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"8b6eaaa48ca785474e92f21e:48","filtered_window_id":"8b6eaaa48ca785474e92f21e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b6eaaa48ca785474e92f21e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject1/o1/3/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"8b6eaaa48ca785474e92f21e:52","filtered_window_id":"8b6eaaa48ca785474e92f21e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b6eaaa48ca785474e92f21e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject1/o1/3/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"8b7bc2bf258c13de0c0ad326:0","filtered_window_id":"8b7bc2bf258c13de0c0ad326","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b7bc2bf258c13de0c0ad326/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject1/h1/0/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"8b7bc2bf258c13de0c0ad326:8","filtered_window_id":"8b7bc2bf258c13de0c0ad326","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b7bc2bf258c13de0c0ad326/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject1/h1/0/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"8b7bc2bf258c13de0c0ad326:16","filtered_window_id":"8b7bc2bf258c13de0c0ad326","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b7bc2bf258c13de0c0ad326/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject1/h1/0/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"8b7bc2bf258c13de0c0ad326:24","filtered_window_id":"8b7bc2bf258c13de0c0ad326","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b7bc2bf258c13de0c0ad326/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[341,342,343,344,345,346,347,348],"take":"subject1/h1/0/cam4","frame_ids":[341,342,343,344,345,346,347,348]} +{"filtered_tile_id":"8b7bc2bf258c13de0c0ad326:32","filtered_window_id":"8b7bc2bf258c13de0c0ad326","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b7bc2bf258c13de0c0ad326/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[349,350,351,352,353,354,355,356],"take":"subject1/h1/0/cam4","frame_ids":[349,350,351,352,353,354,355,356]} +{"filtered_tile_id":"8b7bc2bf258c13de0c0ad326:40","filtered_window_id":"8b7bc2bf258c13de0c0ad326","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b7bc2bf258c13de0c0ad326/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject1/h1/0/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"8b7bc2bf258c13de0c0ad326:48","filtered_window_id":"8b7bc2bf258c13de0c0ad326","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b7bc2bf258c13de0c0ad326/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject1/h1/0/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"8b7bc2bf258c13de0c0ad326:52","filtered_window_id":"8b7bc2bf258c13de0c0ad326","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b7bc2bf258c13de0c0ad326/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[369,370,371,372,373,374,375,376],"take":"subject1/h1/0/cam4","frame_ids":[369,370,371,372,373,374,375,376]} +{"filtered_tile_id":"8b82a2e4364ce6822955c3b7:0","filtered_window_id":"8b82a2e4364ce6822955c3b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b82a2e4364ce6822955c3b7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[125,126,127,128,129,130,131,132],"take":"subject1/h2/0/cam4","frame_ids":[125,126,127,128,129,130,131,132]} +{"filtered_tile_id":"8b82a2e4364ce6822955c3b7:8","filtered_window_id":"8b82a2e4364ce6822955c3b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b82a2e4364ce6822955c3b7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject1/h2/0/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"8b82a2e4364ce6822955c3b7:16","filtered_window_id":"8b82a2e4364ce6822955c3b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b82a2e4364ce6822955c3b7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject1/h2/0/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"8b82a2e4364ce6822955c3b7:24","filtered_window_id":"8b82a2e4364ce6822955c3b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b82a2e4364ce6822955c3b7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject1/h2/0/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"8b82a2e4364ce6822955c3b7:32","filtered_window_id":"8b82a2e4364ce6822955c3b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b82a2e4364ce6822955c3b7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject1/h2/0/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"8b82a2e4364ce6822955c3b7:40","filtered_window_id":"8b82a2e4364ce6822955c3b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b82a2e4364ce6822955c3b7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject1/h2/0/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"8b82a2e4364ce6822955c3b7:48","filtered_window_id":"8b82a2e4364ce6822955c3b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b82a2e4364ce6822955c3b7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject1/h2/0/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"8b82a2e4364ce6822955c3b7:52","filtered_window_id":"8b82a2e4364ce6822955c3b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8b82a2e4364ce6822955c3b7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject1/h2/0/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"8ba9ba272324bd57178f46c0:0","filtered_window_id":"8ba9ba272324bd57178f46c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ba9ba272324bd57178f46c0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[592,593,594,595,596,597,598,599],"take":"subject1/o2/3/cam4","frame_ids":[592,593,594,595,596,597,598,599]} +{"filtered_tile_id":"8ba9ba272324bd57178f46c0:8","filtered_window_id":"8ba9ba272324bd57178f46c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ba9ba272324bd57178f46c0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[600,601,602,603,604,605,606,607],"take":"subject1/o2/3/cam4","frame_ids":[600,601,602,603,604,605,606,607]} +{"filtered_tile_id":"8ba9ba272324bd57178f46c0:16","filtered_window_id":"8ba9ba272324bd57178f46c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ba9ba272324bd57178f46c0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[608,609,610,611,612,613,614,615],"take":"subject1/o2/3/cam4","frame_ids":[608,609,610,611,612,613,614,615]} +{"filtered_tile_id":"8ba9ba272324bd57178f46c0:24","filtered_window_id":"8ba9ba272324bd57178f46c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ba9ba272324bd57178f46c0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[616,617,618,619,620,621,622,623],"take":"subject1/o2/3/cam4","frame_ids":[616,617,618,619,620,621,622,623]} +{"filtered_tile_id":"8ba9ba272324bd57178f46c0:32","filtered_window_id":"8ba9ba272324bd57178f46c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ba9ba272324bd57178f46c0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[624,625,626,627,628,629,630,631],"take":"subject1/o2/3/cam4","frame_ids":[624,625,626,627,628,629,630,631]} +{"filtered_tile_id":"8ba9ba272324bd57178f46c0:40","filtered_window_id":"8ba9ba272324bd57178f46c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ba9ba272324bd57178f46c0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[632,633,634,635,636,637,638,639],"take":"subject1/o2/3/cam4","frame_ids":[632,633,634,635,636,637,638,639]} +{"filtered_tile_id":"8ba9ba272324bd57178f46c0:48","filtered_window_id":"8ba9ba272324bd57178f46c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ba9ba272324bd57178f46c0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[640,641,642,643,644,645,646,647],"take":"subject1/o2/3/cam4","frame_ids":[640,641,642,643,644,645,646,647]} +{"filtered_tile_id":"8ba9ba272324bd57178f46c0:52","filtered_window_id":"8ba9ba272324bd57178f46c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ba9ba272324bd57178f46c0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[644,645,646,647,648,649,650,651],"take":"subject1/o2/3/cam4","frame_ids":[644,645,646,647,648,649,650,651]} +{"filtered_tile_id":"8c2572b1e3601da259f20e54:0","filtered_window_id":"8c2572b1e3601da259f20e54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c2572b1e3601da259f20e54/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[513,514,515,516,517,518,519,520],"take":"subject2/h1/6/cam4","frame_ids":[513,514,515,516,517,518,519,520]} +{"filtered_tile_id":"8c2572b1e3601da259f20e54:8","filtered_window_id":"8c2572b1e3601da259f20e54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c2572b1e3601da259f20e54/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[521,522,523,524,525,526,527,528],"take":"subject2/h1/6/cam4","frame_ids":[521,522,523,524,525,526,527,528]} +{"filtered_tile_id":"8c2572b1e3601da259f20e54:16","filtered_window_id":"8c2572b1e3601da259f20e54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c2572b1e3601da259f20e54/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[529,530,531,532,533,534,535,536],"take":"subject2/h1/6/cam4","frame_ids":[529,530,531,532,533,534,535,536]} +{"filtered_tile_id":"8c2572b1e3601da259f20e54:24","filtered_window_id":"8c2572b1e3601da259f20e54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c2572b1e3601da259f20e54/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[537,538,539,540,541,542,543,544],"take":"subject2/h1/6/cam4","frame_ids":[537,538,539,540,541,542,543,544]} +{"filtered_tile_id":"8c2572b1e3601da259f20e54:32","filtered_window_id":"8c2572b1e3601da259f20e54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c2572b1e3601da259f20e54/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[545,546,547,548,549,550,551,552],"take":"subject2/h1/6/cam4","frame_ids":[545,546,547,548,549,550,551,552]} +{"filtered_tile_id":"8c2572b1e3601da259f20e54:35","filtered_window_id":"8c2572b1e3601da259f20e54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c2572b1e3601da259f20e54/native_gt.npz","filtered_start_offset":35,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject2/h1/6/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"8c3a4cbfe15a6a04ef7dcf21:0","filtered_window_id":"8c3a4cbfe15a6a04ef7dcf21","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c3a4cbfe15a6a04ef7dcf21/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject2/o1/4/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"8c3a4cbfe15a6a04ef7dcf21:8","filtered_window_id":"8c3a4cbfe15a6a04ef7dcf21","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c3a4cbfe15a6a04ef7dcf21/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject2/o1/4/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"8c3a4cbfe15a6a04ef7dcf21:16","filtered_window_id":"8c3a4cbfe15a6a04ef7dcf21","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c3a4cbfe15a6a04ef7dcf21/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[411,412,413,414,415,416,417,418],"take":"subject2/o1/4/cam4","frame_ids":[411,412,413,414,415,416,417,418]} +{"filtered_tile_id":"8c3a4cbfe15a6a04ef7dcf21:24","filtered_window_id":"8c3a4cbfe15a6a04ef7dcf21","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c3a4cbfe15a6a04ef7dcf21/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[419,420,421,422,423,424,425,426],"take":"subject2/o1/4/cam4","frame_ids":[419,420,421,422,423,424,425,426]} +{"filtered_tile_id":"8c3a4cbfe15a6a04ef7dcf21:32","filtered_window_id":"8c3a4cbfe15a6a04ef7dcf21","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c3a4cbfe15a6a04ef7dcf21/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject2/o1/4/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"8c3a4cbfe15a6a04ef7dcf21:40","filtered_window_id":"8c3a4cbfe15a6a04ef7dcf21","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c3a4cbfe15a6a04ef7dcf21/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject2/o1/4/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"8c3a4cbfe15a6a04ef7dcf21:48","filtered_window_id":"8c3a4cbfe15a6a04ef7dcf21","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c3a4cbfe15a6a04ef7dcf21/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject2/o1/4/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"8c3a4cbfe15a6a04ef7dcf21:51","filtered_window_id":"8c3a4cbfe15a6a04ef7dcf21","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8c3a4cbfe15a6a04ef7dcf21/native_gt.npz","filtered_start_offset":51,"expected_frame_ids":[446,447,448,449,450,451,452,453],"take":"subject2/o1/4/cam4","frame_ids":[446,447,448,449,450,451,452,453]} +{"filtered_tile_id":"8cd91296b3704b8771421884:0","filtered_window_id":"8cd91296b3704b8771421884","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8cd91296b3704b8771421884/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject2/h2/2/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"8cd91296b3704b8771421884:8","filtered_window_id":"8cd91296b3704b8771421884","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8cd91296b3704b8771421884/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[526,527,528,529,530,531,532,533],"take":"subject2/h2/2/cam4","frame_ids":[526,527,528,529,530,531,532,533]} +{"filtered_tile_id":"8cd91296b3704b8771421884:16","filtered_window_id":"8cd91296b3704b8771421884","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8cd91296b3704b8771421884/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[534,535,536,537,538,539,540,541],"take":"subject2/h2/2/cam4","frame_ids":[534,535,536,537,538,539,540,541]} +{"filtered_tile_id":"8cd91296b3704b8771421884:24","filtered_window_id":"8cd91296b3704b8771421884","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8cd91296b3704b8771421884/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[542,543,544,545,546,547,548,549],"take":"subject2/h2/2/cam4","frame_ids":[542,543,544,545,546,547,548,549]} +{"filtered_tile_id":"8cd91296b3704b8771421884:32","filtered_window_id":"8cd91296b3704b8771421884","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8cd91296b3704b8771421884/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[550,551,552,553,554,555,556,557],"take":"subject2/h2/2/cam4","frame_ids":[550,551,552,553,554,555,556,557]} +{"filtered_tile_id":"8cd91296b3704b8771421884:40","filtered_window_id":"8cd91296b3704b8771421884","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8cd91296b3704b8771421884/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[558,559,560,561,562,563,564,565],"take":"subject2/h2/2/cam4","frame_ids":[558,559,560,561,562,563,564,565]} +{"filtered_tile_id":"8cd91296b3704b8771421884:48","filtered_window_id":"8cd91296b3704b8771421884","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8cd91296b3704b8771421884/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[566,567,568,569,570,571,572,573],"take":"subject2/h2/2/cam4","frame_ids":[566,567,568,569,570,571,572,573]} +{"filtered_tile_id":"8cd91296b3704b8771421884:52","filtered_window_id":"8cd91296b3704b8771421884","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8cd91296b3704b8771421884/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[570,571,572,573,574,575,576,577],"take":"subject2/h2/2/cam4","frame_ids":[570,571,572,573,574,575,576,577]} +{"filtered_tile_id":"8d995b0e71f0e0d82a069c90:0","filtered_window_id":"8d995b0e71f0e0d82a069c90","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d995b0e71f0e0d82a069c90/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[582,583,584,585,586,587,588,589],"take":"subject1/o1/1/cam4","frame_ids":[582,583,584,585,586,587,588,589]} +{"filtered_tile_id":"8d995b0e71f0e0d82a069c90:8","filtered_window_id":"8d995b0e71f0e0d82a069c90","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d995b0e71f0e0d82a069c90/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[590,591,592,593,594,595,596,597],"take":"subject1/o1/1/cam4","frame_ids":[590,591,592,593,594,595,596,597]} +{"filtered_tile_id":"8d995b0e71f0e0d82a069c90:16","filtered_window_id":"8d995b0e71f0e0d82a069c90","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d995b0e71f0e0d82a069c90/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[598,599,600,601,602,603,604,605],"take":"subject1/o1/1/cam4","frame_ids":[598,599,600,601,602,603,604,605]} +{"filtered_tile_id":"8d995b0e71f0e0d82a069c90:24","filtered_window_id":"8d995b0e71f0e0d82a069c90","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d995b0e71f0e0d82a069c90/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[606,607,608,609,610,611,612,613],"take":"subject1/o1/1/cam4","frame_ids":[606,607,608,609,610,611,612,613]} +{"filtered_tile_id":"8d995b0e71f0e0d82a069c90:32","filtered_window_id":"8d995b0e71f0e0d82a069c90","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d995b0e71f0e0d82a069c90/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[614,615,616,617,618,619,620,621],"take":"subject1/o1/1/cam4","frame_ids":[614,615,616,617,618,619,620,621]} +{"filtered_tile_id":"8d995b0e71f0e0d82a069c90:40","filtered_window_id":"8d995b0e71f0e0d82a069c90","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d995b0e71f0e0d82a069c90/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[622,623,624,625,626,627,628,629],"take":"subject1/o1/1/cam4","frame_ids":[622,623,624,625,626,627,628,629]} +{"filtered_tile_id":"8d995b0e71f0e0d82a069c90:48","filtered_window_id":"8d995b0e71f0e0d82a069c90","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d995b0e71f0e0d82a069c90/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[630,631,632,633,634,635,636,637],"take":"subject1/o1/1/cam4","frame_ids":[630,631,632,633,634,635,636,637]} +{"filtered_tile_id":"8d995b0e71f0e0d82a069c90:52","filtered_window_id":"8d995b0e71f0e0d82a069c90","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d995b0e71f0e0d82a069c90/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[634,635,636,637,638,639,640,641],"take":"subject1/o1/1/cam4","frame_ids":[634,635,636,637,638,639,640,641]} +{"filtered_tile_id":"8d9f05a597f581e20d1687c9:0","filtered_window_id":"8d9f05a597f581e20d1687c9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d9f05a597f581e20d1687c9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[419,420,421,422,423,424,425,426],"take":"subject2/h2/3/cam4","frame_ids":[419,420,421,422,423,424,425,426]} +{"filtered_tile_id":"8d9f05a597f581e20d1687c9:8","filtered_window_id":"8d9f05a597f581e20d1687c9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d9f05a597f581e20d1687c9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject2/h2/3/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"8d9f05a597f581e20d1687c9:16","filtered_window_id":"8d9f05a597f581e20d1687c9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d9f05a597f581e20d1687c9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject2/h2/3/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"8d9f05a597f581e20d1687c9:24","filtered_window_id":"8d9f05a597f581e20d1687c9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d9f05a597f581e20d1687c9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject2/h2/3/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"8d9f05a597f581e20d1687c9:32","filtered_window_id":"8d9f05a597f581e20d1687c9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d9f05a597f581e20d1687c9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject2/h2/3/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"8d9f05a597f581e20d1687c9:40","filtered_window_id":"8d9f05a597f581e20d1687c9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d9f05a597f581e20d1687c9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[459,460,461,462,463,464,465,466],"take":"subject2/h2/3/cam4","frame_ids":[459,460,461,462,463,464,465,466]} +{"filtered_tile_id":"8d9f05a597f581e20d1687c9:48","filtered_window_id":"8d9f05a597f581e20d1687c9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d9f05a597f581e20d1687c9/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[467,468,469,470,471,472,473,474],"take":"subject2/h2/3/cam4","frame_ids":[467,468,469,470,471,472,473,474]} +{"filtered_tile_id":"8d9f05a597f581e20d1687c9:52","filtered_window_id":"8d9f05a597f581e20d1687c9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8d9f05a597f581e20d1687c9/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[471,472,473,474,475,476,477,478],"take":"subject2/h2/3/cam4","frame_ids":[471,472,473,474,475,476,477,478]} +{"filtered_tile_id":"8dee26649c04b2dfdc1374cc:0","filtered_window_id":"8dee26649c04b2dfdc1374cc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8dee26649c04b2dfdc1374cc/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[678,679,680,681,682,683,684,685],"take":"subject3/k1/2/cam4","frame_ids":[678,679,680,681,682,683,684,685]} +{"filtered_tile_id":"8dee26649c04b2dfdc1374cc:8","filtered_window_id":"8dee26649c04b2dfdc1374cc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8dee26649c04b2dfdc1374cc/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[686,687,688,689,690,691,692,693],"take":"subject3/k1/2/cam4","frame_ids":[686,687,688,689,690,691,692,693]} +{"filtered_tile_id":"8dee26649c04b2dfdc1374cc:16","filtered_window_id":"8dee26649c04b2dfdc1374cc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8dee26649c04b2dfdc1374cc/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[694,695,696,697,698,699,700,701],"take":"subject3/k1/2/cam4","frame_ids":[694,695,696,697,698,699,700,701]} +{"filtered_tile_id":"8dee26649c04b2dfdc1374cc:24","filtered_window_id":"8dee26649c04b2dfdc1374cc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8dee26649c04b2dfdc1374cc/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[702,703,704,705,706,707,708,709],"take":"subject3/k1/2/cam4","frame_ids":[702,703,704,705,706,707,708,709]} +{"filtered_tile_id":"8dee26649c04b2dfdc1374cc:32","filtered_window_id":"8dee26649c04b2dfdc1374cc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8dee26649c04b2dfdc1374cc/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[710,711,712,713,714,715,716,717],"take":"subject3/k1/2/cam4","frame_ids":[710,711,712,713,714,715,716,717]} +{"filtered_tile_id":"8dee26649c04b2dfdc1374cc:40","filtered_window_id":"8dee26649c04b2dfdc1374cc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8dee26649c04b2dfdc1374cc/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[718,719,720,721,722,723,724,725],"take":"subject3/k1/2/cam4","frame_ids":[718,719,720,721,722,723,724,725]} +{"filtered_tile_id":"8dee26649c04b2dfdc1374cc:48","filtered_window_id":"8dee26649c04b2dfdc1374cc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8dee26649c04b2dfdc1374cc/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[726,727,728,729,730,731,732,733],"take":"subject3/k1/2/cam4","frame_ids":[726,727,728,729,730,731,732,733]} +{"filtered_tile_id":"8dee26649c04b2dfdc1374cc:52","filtered_window_id":"8dee26649c04b2dfdc1374cc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8dee26649c04b2dfdc1374cc/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[730,731,732,733,734,735,736,737],"take":"subject3/k1/2/cam4","frame_ids":[730,731,732,733,734,735,736,737]} +{"filtered_tile_id":"8df0d5162d663ae839be4b5c:0","filtered_window_id":"8df0d5162d663ae839be4b5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8df0d5162d663ae839be4b5c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject3/k1/6/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"8df0d5162d663ae839be4b5c:8","filtered_window_id":"8df0d5162d663ae839be4b5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8df0d5162d663ae839be4b5c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject3/k1/6/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"8df0d5162d663ae839be4b5c:16","filtered_window_id":"8df0d5162d663ae839be4b5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8df0d5162d663ae839be4b5c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject3/k1/6/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"8df0d5162d663ae839be4b5c:24","filtered_window_id":"8df0d5162d663ae839be4b5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8df0d5162d663ae839be4b5c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject3/k1/6/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"8df0d5162d663ae839be4b5c:32","filtered_window_id":"8df0d5162d663ae839be4b5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8df0d5162d663ae839be4b5c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject3/k1/6/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"8df0d5162d663ae839be4b5c:40","filtered_window_id":"8df0d5162d663ae839be4b5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8df0d5162d663ae839be4b5c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject3/k1/6/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"8df0d5162d663ae839be4b5c:48","filtered_window_id":"8df0d5162d663ae839be4b5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8df0d5162d663ae839be4b5c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject3/k1/6/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"8df0d5162d663ae839be4b5c:52","filtered_window_id":"8df0d5162d663ae839be4b5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8df0d5162d663ae839be4b5c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject3/k1/6/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"8e5bc755828b0baa9f912b03:0","filtered_window_id":"8e5bc755828b0baa9f912b03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8e5bc755828b0baa9f912b03/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject1/o2/6/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"8e5bc755828b0baa9f912b03:8","filtered_window_id":"8e5bc755828b0baa9f912b03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8e5bc755828b0baa9f912b03/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject1/o2/6/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"8e5bc755828b0baa9f912b03:16","filtered_window_id":"8e5bc755828b0baa9f912b03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8e5bc755828b0baa9f912b03/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject1/o2/6/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"8e5bc755828b0baa9f912b03:24","filtered_window_id":"8e5bc755828b0baa9f912b03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8e5bc755828b0baa9f912b03/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject1/o2/6/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"8e5bc755828b0baa9f912b03:32","filtered_window_id":"8e5bc755828b0baa9f912b03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8e5bc755828b0baa9f912b03/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject1/o2/6/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"8e5bc755828b0baa9f912b03:40","filtered_window_id":"8e5bc755828b0baa9f912b03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8e5bc755828b0baa9f912b03/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject1/o2/6/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"8e5bc755828b0baa9f912b03:48","filtered_window_id":"8e5bc755828b0baa9f912b03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8e5bc755828b0baa9f912b03/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject1/o2/6/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"8e5bc755828b0baa9f912b03:52","filtered_window_id":"8e5bc755828b0baa9f912b03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8e5bc755828b0baa9f912b03/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject1/o2/6/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"8ebb745f6e0342c3dcc16ba8:0","filtered_window_id":"8ebb745f6e0342c3dcc16ba8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ebb745f6e0342c3dcc16ba8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[385,386,387,388,389,390,391,392],"take":"subject2/o2/0/cam4","frame_ids":[385,386,387,388,389,390,391,392]} +{"filtered_tile_id":"8ebb745f6e0342c3dcc16ba8:8","filtered_window_id":"8ebb745f6e0342c3dcc16ba8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ebb745f6e0342c3dcc16ba8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[393,394,395,396,397,398,399,400],"take":"subject2/o2/0/cam4","frame_ids":[393,394,395,396,397,398,399,400]} +{"filtered_tile_id":"8ebb745f6e0342c3dcc16ba8:10","filtered_window_id":"8ebb745f6e0342c3dcc16ba8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ebb745f6e0342c3dcc16ba8/native_gt.npz","filtered_start_offset":10,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject2/o2/0/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"8ec3310e734b17c4facd2279:0","filtered_window_id":"8ec3310e734b17c4facd2279","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ec3310e734b17c4facd2279/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[485,486,487,488,489,490,491,492],"take":"subject3/h1/5/cam4","frame_ids":[485,486,487,488,489,490,491,492]} +{"filtered_tile_id":"8ec3310e734b17c4facd2279:2","filtered_window_id":"8ec3310e734b17c4facd2279","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8ec3310e734b17c4facd2279/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject3/h1/5/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"8f924847cc1b68c95060349f:0","filtered_window_id":"8f924847cc1b68c95060349f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8f924847cc1b68c95060349f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject2/h1/5/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"8f924847cc1b68c95060349f:8","filtered_window_id":"8f924847cc1b68c95060349f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8f924847cc1b68c95060349f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject2/h1/5/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"8f924847cc1b68c95060349f:16","filtered_window_id":"8f924847cc1b68c95060349f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8f924847cc1b68c95060349f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject2/h1/5/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"8f924847cc1b68c95060349f:24","filtered_window_id":"8f924847cc1b68c95060349f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8f924847cc1b68c95060349f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject2/h1/5/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"8f924847cc1b68c95060349f:32","filtered_window_id":"8f924847cc1b68c95060349f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8f924847cc1b68c95060349f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject2/h1/5/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"8f924847cc1b68c95060349f:40","filtered_window_id":"8f924847cc1b68c95060349f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8f924847cc1b68c95060349f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject2/h1/5/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"8f924847cc1b68c95060349f:48","filtered_window_id":"8f924847cc1b68c95060349f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8f924847cc1b68c95060349f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject2/h1/5/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"8f924847cc1b68c95060349f:52","filtered_window_id":"8f924847cc1b68c95060349f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8f924847cc1b68c95060349f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject2/h1/5/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"8fe680b9a57574606fc60c5d:0","filtered_window_id":"8fe680b9a57574606fc60c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8fe680b9a57574606fc60c5d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject3/h2/2/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"8fe680b9a57574606fc60c5d:8","filtered_window_id":"8fe680b9a57574606fc60c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8fe680b9a57574606fc60c5d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject3/h2/2/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"8fe680b9a57574606fc60c5d:16","filtered_window_id":"8fe680b9a57574606fc60c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8fe680b9a57574606fc60c5d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[459,460,461,462,463,464,465,466],"take":"subject3/h2/2/cam4","frame_ids":[459,460,461,462,463,464,465,466]} +{"filtered_tile_id":"8fe680b9a57574606fc60c5d:24","filtered_window_id":"8fe680b9a57574606fc60c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8fe680b9a57574606fc60c5d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[467,468,469,470,471,472,473,474],"take":"subject3/h2/2/cam4","frame_ids":[467,468,469,470,471,472,473,474]} +{"filtered_tile_id":"8fe680b9a57574606fc60c5d:27","filtered_window_id":"8fe680b9a57574606fc60c5d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/8fe680b9a57574606fc60c5d/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject3/h2/2/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"90123558fad41ac5b188790f:0","filtered_window_id":"90123558fad41ac5b188790f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90123558fad41ac5b188790f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[411,412,413,414,415,416,417,418],"take":"subject1/o1/3/cam4","frame_ids":[411,412,413,414,415,416,417,418]} +{"filtered_tile_id":"90123558fad41ac5b188790f:8","filtered_window_id":"90123558fad41ac5b188790f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90123558fad41ac5b188790f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[419,420,421,422,423,424,425,426],"take":"subject1/o1/3/cam4","frame_ids":[419,420,421,422,423,424,425,426]} +{"filtered_tile_id":"90123558fad41ac5b188790f:16","filtered_window_id":"90123558fad41ac5b188790f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90123558fad41ac5b188790f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject1/o1/3/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"90123558fad41ac5b188790f:24","filtered_window_id":"90123558fad41ac5b188790f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90123558fad41ac5b188790f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/o1/3/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"90123558fad41ac5b188790f:32","filtered_window_id":"90123558fad41ac5b188790f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90123558fad41ac5b188790f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject1/o1/3/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"90123558fad41ac5b188790f:40","filtered_window_id":"90123558fad41ac5b188790f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90123558fad41ac5b188790f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject1/o1/3/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"90123558fad41ac5b188790f:48","filtered_window_id":"90123558fad41ac5b188790f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90123558fad41ac5b188790f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[459,460,461,462,463,464,465,466],"take":"subject1/o1/3/cam4","frame_ids":[459,460,461,462,463,464,465,466]} +{"filtered_tile_id":"90123558fad41ac5b188790f:52","filtered_window_id":"90123558fad41ac5b188790f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90123558fad41ac5b188790f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[463,464,465,466,467,468,469,470],"take":"subject1/o1/3/cam4","frame_ids":[463,464,465,466,467,468,469,470]} +{"filtered_tile_id":"902e490eeae3f0c7bf575823:0","filtered_window_id":"902e490eeae3f0c7bf575823","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/902e490eeae3f0c7bf575823/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[35,36,37,38,39,40,41,42],"take":"subject1/h1/6/cam4","frame_ids":[35,36,37,38,39,40,41,42]} +{"filtered_tile_id":"902e490eeae3f0c7bf575823:8","filtered_window_id":"902e490eeae3f0c7bf575823","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/902e490eeae3f0c7bf575823/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[43,44,45,46,47,48,49,50],"take":"subject1/h1/6/cam4","frame_ids":[43,44,45,46,47,48,49,50]} +{"filtered_tile_id":"902e490eeae3f0c7bf575823:16","filtered_window_id":"902e490eeae3f0c7bf575823","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/902e490eeae3f0c7bf575823/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject1/h1/6/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"902e490eeae3f0c7bf575823:24","filtered_window_id":"902e490eeae3f0c7bf575823","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/902e490eeae3f0c7bf575823/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[59,60,61,62,63,64,65,66],"take":"subject1/h1/6/cam4","frame_ids":[59,60,61,62,63,64,65,66]} +{"filtered_tile_id":"902e490eeae3f0c7bf575823:32","filtered_window_id":"902e490eeae3f0c7bf575823","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/902e490eeae3f0c7bf575823/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject1/h1/6/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"902e490eeae3f0c7bf575823:40","filtered_window_id":"902e490eeae3f0c7bf575823","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/902e490eeae3f0c7bf575823/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject1/h1/6/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"902e490eeae3f0c7bf575823:48","filtered_window_id":"902e490eeae3f0c7bf575823","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/902e490eeae3f0c7bf575823/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject1/h1/6/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"902e490eeae3f0c7bf575823:52","filtered_window_id":"902e490eeae3f0c7bf575823","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/902e490eeae3f0c7bf575823/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[87,88,89,90,91,92,93,94],"take":"subject1/h1/6/cam4","frame_ids":[87,88,89,90,91,92,93,94]} +{"filtered_tile_id":"90350911df62e94afee302b1:0","filtered_window_id":"90350911df62e94afee302b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90350911df62e94afee302b1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject3/k1/5/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"90350911df62e94afee302b1:8","filtered_window_id":"90350911df62e94afee302b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90350911df62e94afee302b1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[526,527,528,529,530,531,532,533],"take":"subject3/k1/5/cam4","frame_ids":[526,527,528,529,530,531,532,533]} +{"filtered_tile_id":"90350911df62e94afee302b1:11","filtered_window_id":"90350911df62e94afee302b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90350911df62e94afee302b1/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[529,530,531,532,533,534,535,536],"take":"subject3/k1/5/cam4","frame_ids":[529,530,531,532,533,534,535,536]} +{"filtered_tile_id":"9049526e52cede60d4325566:0","filtered_window_id":"9049526e52cede60d4325566","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9049526e52cede60d4325566/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[490,491,492,493,494,495,496,497],"take":"subject2/o2/5/cam4","frame_ids":[490,491,492,493,494,495,496,497]} +{"filtered_tile_id":"9049526e52cede60d4325566:8","filtered_window_id":"9049526e52cede60d4325566","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9049526e52cede60d4325566/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[498,499,500,501,502,503,504,505],"take":"subject2/o2/5/cam4","frame_ids":[498,499,500,501,502,503,504,505]} +{"filtered_tile_id":"9049526e52cede60d4325566:16","filtered_window_id":"9049526e52cede60d4325566","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9049526e52cede60d4325566/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[506,507,508,509,510,511,512,513],"take":"subject2/o2/5/cam4","frame_ids":[506,507,508,509,510,511,512,513]} +{"filtered_tile_id":"9049526e52cede60d4325566:24","filtered_window_id":"9049526e52cede60d4325566","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9049526e52cede60d4325566/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[514,515,516,517,518,519,520,521],"take":"subject2/o2/5/cam4","frame_ids":[514,515,516,517,518,519,520,521]} +{"filtered_tile_id":"9049526e52cede60d4325566:25","filtered_window_id":"9049526e52cede60d4325566","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9049526e52cede60d4325566/native_gt.npz","filtered_start_offset":25,"expected_frame_ids":[515,516,517,518,519,520,521,522],"take":"subject2/o2/5/cam4","frame_ids":[515,516,517,518,519,520,521,522]} +{"filtered_tile_id":"90ab1724165ba29d5bb6ceb5:0","filtered_window_id":"90ab1724165ba29d5bb6ceb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90ab1724165ba29d5bb6ceb5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject3/h2/2/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"90ab1724165ba29d5bb6ceb5:8","filtered_window_id":"90ab1724165ba29d5bb6ceb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90ab1724165ba29d5bb6ceb5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[175,176,177,178,179,180,181,182],"take":"subject3/h2/2/cam4","frame_ids":[175,176,177,178,179,180,181,182]} +{"filtered_tile_id":"90ab1724165ba29d5bb6ceb5:16","filtered_window_id":"90ab1724165ba29d5bb6ceb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90ab1724165ba29d5bb6ceb5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[183,184,185,186,187,188,189,190],"take":"subject3/h2/2/cam4","frame_ids":[183,184,185,186,187,188,189,190]} +{"filtered_tile_id":"90ab1724165ba29d5bb6ceb5:24","filtered_window_id":"90ab1724165ba29d5bb6ceb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90ab1724165ba29d5bb6ceb5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[191,192,193,194,195,196,197,198],"take":"subject3/h2/2/cam4","frame_ids":[191,192,193,194,195,196,197,198]} +{"filtered_tile_id":"90ab1724165ba29d5bb6ceb5:32","filtered_window_id":"90ab1724165ba29d5bb6ceb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90ab1724165ba29d5bb6ceb5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject3/h2/2/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"90ab1724165ba29d5bb6ceb5:40","filtered_window_id":"90ab1724165ba29d5bb6ceb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90ab1724165ba29d5bb6ceb5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[207,208,209,210,211,212,213,214],"take":"subject3/h2/2/cam4","frame_ids":[207,208,209,210,211,212,213,214]} +{"filtered_tile_id":"90ab1724165ba29d5bb6ceb5:45","filtered_window_id":"90ab1724165ba29d5bb6ceb5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/90ab1724165ba29d5bb6ceb5/native_gt.npz","filtered_start_offset":45,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject3/h2/2/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"91940e4c36df6d3cb583c8a2:0","filtered_window_id":"91940e4c36df6d3cb583c8a2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91940e4c36df6d3cb583c8a2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[757,758,759,760,761,762,763,764],"take":"subject2/o1/4/cam4","frame_ids":[757,758,759,760,761,762,763,764]} +{"filtered_tile_id":"91940e4c36df6d3cb583c8a2:8","filtered_window_id":"91940e4c36df6d3cb583c8a2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91940e4c36df6d3cb583c8a2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[765,766,767,768,769,770,771,772],"take":"subject2/o1/4/cam4","frame_ids":[765,766,767,768,769,770,771,772]} +{"filtered_tile_id":"91940e4c36df6d3cb583c8a2:16","filtered_window_id":"91940e4c36df6d3cb583c8a2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91940e4c36df6d3cb583c8a2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[773,774,775,776,777,778,779,780],"take":"subject2/o1/4/cam4","frame_ids":[773,774,775,776,777,778,779,780]} +{"filtered_tile_id":"91940e4c36df6d3cb583c8a2:19","filtered_window_id":"91940e4c36df6d3cb583c8a2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91940e4c36df6d3cb583c8a2/native_gt.npz","filtered_start_offset":19,"expected_frame_ids":[776,777,778,779,780,781,782,783],"take":"subject2/o1/4/cam4","frame_ids":[776,777,778,779,780,781,782,783]} +{"filtered_tile_id":"91ce15b51107fcd4451b4e8b:0","filtered_window_id":"91ce15b51107fcd4451b4e8b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91ce15b51107fcd4451b4e8b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject1/o2/4/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"91ce15b51107fcd4451b4e8b:8","filtered_window_id":"91ce15b51107fcd4451b4e8b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91ce15b51107fcd4451b4e8b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject1/o2/4/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"91ce15b51107fcd4451b4e8b:16","filtered_window_id":"91ce15b51107fcd4451b4e8b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91ce15b51107fcd4451b4e8b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject1/o2/4/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"91ce15b51107fcd4451b4e8b:24","filtered_window_id":"91ce15b51107fcd4451b4e8b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91ce15b51107fcd4451b4e8b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[466,467,468,469,470,471,472,473],"take":"subject1/o2/4/cam4","frame_ids":[466,467,468,469,470,471,472,473]} +{"filtered_tile_id":"91ce15b51107fcd4451b4e8b:32","filtered_window_id":"91ce15b51107fcd4451b4e8b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91ce15b51107fcd4451b4e8b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[474,475,476,477,478,479,480,481],"take":"subject1/o2/4/cam4","frame_ids":[474,475,476,477,478,479,480,481]} +{"filtered_tile_id":"91ce15b51107fcd4451b4e8b:40","filtered_window_id":"91ce15b51107fcd4451b4e8b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91ce15b51107fcd4451b4e8b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[482,483,484,485,486,487,488,489],"take":"subject1/o2/4/cam4","frame_ids":[482,483,484,485,486,487,488,489]} +{"filtered_tile_id":"91ce15b51107fcd4451b4e8b:48","filtered_window_id":"91ce15b51107fcd4451b4e8b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91ce15b51107fcd4451b4e8b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[490,491,492,493,494,495,496,497],"take":"subject1/o2/4/cam4","frame_ids":[490,491,492,493,494,495,496,497]} +{"filtered_tile_id":"91ce15b51107fcd4451b4e8b:52","filtered_window_id":"91ce15b51107fcd4451b4e8b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91ce15b51107fcd4451b4e8b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject1/o2/4/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"91e9efc63e9c850e77cf93da:0","filtered_window_id":"91e9efc63e9c850e77cf93da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91e9efc63e9c850e77cf93da/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject3/k1/4/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"91e9efc63e9c850e77cf93da:8","filtered_window_id":"91e9efc63e9c850e77cf93da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91e9efc63e9c850e77cf93da/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[398,399,400,401,402,403,404,405],"take":"subject3/k1/4/cam4","frame_ids":[398,399,400,401,402,403,404,405]} +{"filtered_tile_id":"91e9efc63e9c850e77cf93da:16","filtered_window_id":"91e9efc63e9c850e77cf93da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91e9efc63e9c850e77cf93da/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[406,407,408,409,410,411,412,413],"take":"subject3/k1/4/cam4","frame_ids":[406,407,408,409,410,411,412,413]} +{"filtered_tile_id":"91e9efc63e9c850e77cf93da:24","filtered_window_id":"91e9efc63e9c850e77cf93da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91e9efc63e9c850e77cf93da/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[414,415,416,417,418,419,420,421],"take":"subject3/k1/4/cam4","frame_ids":[414,415,416,417,418,419,420,421]} +{"filtered_tile_id":"91e9efc63e9c850e77cf93da:32","filtered_window_id":"91e9efc63e9c850e77cf93da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91e9efc63e9c850e77cf93da/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[422,423,424,425,426,427,428,429],"take":"subject3/k1/4/cam4","frame_ids":[422,423,424,425,426,427,428,429]} +{"filtered_tile_id":"91e9efc63e9c850e77cf93da:40","filtered_window_id":"91e9efc63e9c850e77cf93da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91e9efc63e9c850e77cf93da/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[430,431,432,433,434,435,436,437],"take":"subject3/k1/4/cam4","frame_ids":[430,431,432,433,434,435,436,437]} +{"filtered_tile_id":"91e9efc63e9c850e77cf93da:48","filtered_window_id":"91e9efc63e9c850e77cf93da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91e9efc63e9c850e77cf93da/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[438,439,440,441,442,443,444,445],"take":"subject3/k1/4/cam4","frame_ids":[438,439,440,441,442,443,444,445]} +{"filtered_tile_id":"91e9efc63e9c850e77cf93da:52","filtered_window_id":"91e9efc63e9c850e77cf93da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/91e9efc63e9c850e77cf93da/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject3/k1/4/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"929b7fb496f2840b95d5d04a:0","filtered_window_id":"929b7fb496f2840b95d5d04a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/929b7fb496f2840b95d5d04a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[818,819,820,821,822,823,824,825],"take":"subject2/k2/6/cam4","frame_ids":[818,819,820,821,822,823,824,825]} +{"filtered_tile_id":"929b7fb496f2840b95d5d04a:8","filtered_window_id":"929b7fb496f2840b95d5d04a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/929b7fb496f2840b95d5d04a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[826,827,828,829,830,831,832,833],"take":"subject2/k2/6/cam4","frame_ids":[826,827,828,829,830,831,832,833]} +{"filtered_tile_id":"929b7fb496f2840b95d5d04a:12","filtered_window_id":"929b7fb496f2840b95d5d04a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/929b7fb496f2840b95d5d04a/native_gt.npz","filtered_start_offset":12,"expected_frame_ids":[830,831,832,833,834,835,836,837],"take":"subject2/k2/6/cam4","frame_ids":[830,831,832,833,834,835,836,837]} +{"filtered_tile_id":"92d1638c752f6dc62e15ae71:0","filtered_window_id":"92d1638c752f6dc62e15ae71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/92d1638c752f6dc62e15ae71/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[393,394,395,396,397,398,399,400],"take":"subject2/h1/6/cam4","frame_ids":[393,394,395,396,397,398,399,400]} +{"filtered_tile_id":"92d1638c752f6dc62e15ae71:8","filtered_window_id":"92d1638c752f6dc62e15ae71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/92d1638c752f6dc62e15ae71/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[401,402,403,404,405,406,407,408],"take":"subject2/h1/6/cam4","frame_ids":[401,402,403,404,405,406,407,408]} +{"filtered_tile_id":"92d1638c752f6dc62e15ae71:16","filtered_window_id":"92d1638c752f6dc62e15ae71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/92d1638c752f6dc62e15ae71/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[409,410,411,412,413,414,415,416],"take":"subject2/h1/6/cam4","frame_ids":[409,410,411,412,413,414,415,416]} +{"filtered_tile_id":"92d1638c752f6dc62e15ae71:24","filtered_window_id":"92d1638c752f6dc62e15ae71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/92d1638c752f6dc62e15ae71/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[417,418,419,420,421,422,423,424],"take":"subject2/h1/6/cam4","frame_ids":[417,418,419,420,421,422,423,424]} +{"filtered_tile_id":"92d1638c752f6dc62e15ae71:32","filtered_window_id":"92d1638c752f6dc62e15ae71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/92d1638c752f6dc62e15ae71/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject2/h1/6/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"92d1638c752f6dc62e15ae71:40","filtered_window_id":"92d1638c752f6dc62e15ae71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/92d1638c752f6dc62e15ae71/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[433,434,435,436,437,438,439,440],"take":"subject2/h1/6/cam4","frame_ids":[433,434,435,436,437,438,439,440]} +{"filtered_tile_id":"92d1638c752f6dc62e15ae71:48","filtered_window_id":"92d1638c752f6dc62e15ae71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/92d1638c752f6dc62e15ae71/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject2/h1/6/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"92d1638c752f6dc62e15ae71:52","filtered_window_id":"92d1638c752f6dc62e15ae71","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/92d1638c752f6dc62e15ae71/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[445,446,447,448,449,450,451,452],"take":"subject2/h1/6/cam4","frame_ids":[445,446,447,448,449,450,451,452]} +{"filtered_tile_id":"93681db1823fab777d57d002:0","filtered_window_id":"93681db1823fab777d57d002","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93681db1823fab777d57d002/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[663,664,665,666,667,668,669,670],"take":"subject1/k1/1/cam4","frame_ids":[663,664,665,666,667,668,669,670]} +{"filtered_tile_id":"93681db1823fab777d57d002:8","filtered_window_id":"93681db1823fab777d57d002","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93681db1823fab777d57d002/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[671,672,673,674,675,676,677,678],"take":"subject1/k1/1/cam4","frame_ids":[671,672,673,674,675,676,677,678]} +{"filtered_tile_id":"93681db1823fab777d57d002:16","filtered_window_id":"93681db1823fab777d57d002","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93681db1823fab777d57d002/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[679,680,681,682,683,684,685,686],"take":"subject1/k1/1/cam4","frame_ids":[679,680,681,682,683,684,685,686]} +{"filtered_tile_id":"93681db1823fab777d57d002:24","filtered_window_id":"93681db1823fab777d57d002","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93681db1823fab777d57d002/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[687,688,689,690,691,692,693,694],"take":"subject1/k1/1/cam4","frame_ids":[687,688,689,690,691,692,693,694]} +{"filtered_tile_id":"93681db1823fab777d57d002:32","filtered_window_id":"93681db1823fab777d57d002","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93681db1823fab777d57d002/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[695,696,697,698,699,700,701,702],"take":"subject1/k1/1/cam4","frame_ids":[695,696,697,698,699,700,701,702]} +{"filtered_tile_id":"93681db1823fab777d57d002:40","filtered_window_id":"93681db1823fab777d57d002","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93681db1823fab777d57d002/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[703,704,705,706,707,708,709,710],"take":"subject1/k1/1/cam4","frame_ids":[703,704,705,706,707,708,709,710]} +{"filtered_tile_id":"93681db1823fab777d57d002:48","filtered_window_id":"93681db1823fab777d57d002","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93681db1823fab777d57d002/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[711,712,713,714,715,716,717,718],"take":"subject1/k1/1/cam4","frame_ids":[711,712,713,714,715,716,717,718]} +{"filtered_tile_id":"93681db1823fab777d57d002:52","filtered_window_id":"93681db1823fab777d57d002","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93681db1823fab777d57d002/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[715,716,717,718,719,720,721,722],"take":"subject1/k1/1/cam4","frame_ids":[715,716,717,718,719,720,721,722]} +{"filtered_tile_id":"939f0540a2d4bbbbd2d65ffa:0","filtered_window_id":"939f0540a2d4bbbbd2d65ffa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/939f0540a2d4bbbbd2d65ffa/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject1/k1/4/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"939f0540a2d4bbbbd2d65ffa:8","filtered_window_id":"939f0540a2d4bbbbd2d65ffa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/939f0540a2d4bbbbd2d65ffa/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject1/k1/4/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"939f0540a2d4bbbbd2d65ffa:16","filtered_window_id":"939f0540a2d4bbbbd2d65ffa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/939f0540a2d4bbbbd2d65ffa/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject1/k1/4/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"939f0540a2d4bbbbd2d65ffa:24","filtered_window_id":"939f0540a2d4bbbbd2d65ffa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/939f0540a2d4bbbbd2d65ffa/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject1/k1/4/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"939f0540a2d4bbbbd2d65ffa:32","filtered_window_id":"939f0540a2d4bbbbd2d65ffa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/939f0540a2d4bbbbd2d65ffa/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject1/k1/4/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"939f0540a2d4bbbbd2d65ffa:40","filtered_window_id":"939f0540a2d4bbbbd2d65ffa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/939f0540a2d4bbbbd2d65ffa/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject1/k1/4/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"939f0540a2d4bbbbd2d65ffa:48","filtered_window_id":"939f0540a2d4bbbbd2d65ffa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/939f0540a2d4bbbbd2d65ffa/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject1/k1/4/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"939f0540a2d4bbbbd2d65ffa:52","filtered_window_id":"939f0540a2d4bbbbd2d65ffa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/939f0540a2d4bbbbd2d65ffa/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject1/k1/4/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"93d1c3808110351c97d36fbf:0","filtered_window_id":"93d1c3808110351c97d36fbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93d1c3808110351c97d36fbf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[611,612,613,614,615,616,617,618],"take":"subject1/h1/3/cam4","frame_ids":[611,612,613,614,615,616,617,618]} +{"filtered_tile_id":"93d1c3808110351c97d36fbf:8","filtered_window_id":"93d1c3808110351c97d36fbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93d1c3808110351c97d36fbf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[619,620,621,622,623,624,625,626],"take":"subject1/h1/3/cam4","frame_ids":[619,620,621,622,623,624,625,626]} +{"filtered_tile_id":"93d1c3808110351c97d36fbf:16","filtered_window_id":"93d1c3808110351c97d36fbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93d1c3808110351c97d36fbf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[627,628,629,630,631,632,633,634],"take":"subject1/h1/3/cam4","frame_ids":[627,628,629,630,631,632,633,634]} +{"filtered_tile_id":"93d1c3808110351c97d36fbf:24","filtered_window_id":"93d1c3808110351c97d36fbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93d1c3808110351c97d36fbf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[635,636,637,638,639,640,641,642],"take":"subject1/h1/3/cam4","frame_ids":[635,636,637,638,639,640,641,642]} +{"filtered_tile_id":"93d1c3808110351c97d36fbf:32","filtered_window_id":"93d1c3808110351c97d36fbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93d1c3808110351c97d36fbf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[643,644,645,646,647,648,649,650],"take":"subject1/h1/3/cam4","frame_ids":[643,644,645,646,647,648,649,650]} +{"filtered_tile_id":"93d1c3808110351c97d36fbf:40","filtered_window_id":"93d1c3808110351c97d36fbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93d1c3808110351c97d36fbf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[651,652,653,654,655,656,657,658],"take":"subject1/h1/3/cam4","frame_ids":[651,652,653,654,655,656,657,658]} +{"filtered_tile_id":"93d1c3808110351c97d36fbf:48","filtered_window_id":"93d1c3808110351c97d36fbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93d1c3808110351c97d36fbf/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[659,660,661,662,663,664,665,666],"take":"subject1/h1/3/cam4","frame_ids":[659,660,661,662,663,664,665,666]} +{"filtered_tile_id":"93d1c3808110351c97d36fbf:52","filtered_window_id":"93d1c3808110351c97d36fbf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93d1c3808110351c97d36fbf/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[663,664,665,666,667,668,669,670],"take":"subject1/h1/3/cam4","frame_ids":[663,664,665,666,667,668,669,670]} +{"filtered_tile_id":"93ebf9635cda36f146c7cecc:0","filtered_window_id":"93ebf9635cda36f146c7cecc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93ebf9635cda36f146c7cecc/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[43,44,45,46,47,48,49,50],"take":"subject2/h1/6/cam4","frame_ids":[43,44,45,46,47,48,49,50]} +{"filtered_tile_id":"93ebf9635cda36f146c7cecc:8","filtered_window_id":"93ebf9635cda36f146c7cecc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93ebf9635cda36f146c7cecc/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject2/h1/6/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"93ebf9635cda36f146c7cecc:16","filtered_window_id":"93ebf9635cda36f146c7cecc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93ebf9635cda36f146c7cecc/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[59,60,61,62,63,64,65,66],"take":"subject2/h1/6/cam4","frame_ids":[59,60,61,62,63,64,65,66]} +{"filtered_tile_id":"93ebf9635cda36f146c7cecc:24","filtered_window_id":"93ebf9635cda36f146c7cecc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93ebf9635cda36f146c7cecc/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject2/h1/6/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"93ebf9635cda36f146c7cecc:32","filtered_window_id":"93ebf9635cda36f146c7cecc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93ebf9635cda36f146c7cecc/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject2/h1/6/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"93ebf9635cda36f146c7cecc:40","filtered_window_id":"93ebf9635cda36f146c7cecc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93ebf9635cda36f146c7cecc/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject2/h1/6/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"93ebf9635cda36f146c7cecc:48","filtered_window_id":"93ebf9635cda36f146c7cecc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93ebf9635cda36f146c7cecc/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject2/h1/6/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"93ebf9635cda36f146c7cecc:52","filtered_window_id":"93ebf9635cda36f146c7cecc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/93ebf9635cda36f146c7cecc/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[95,96,97,98,99,100,101,102],"take":"subject2/h1/6/cam4","frame_ids":[95,96,97,98,99,100,101,102]} +{"filtered_tile_id":"9462647090c7713defc8223f:0","filtered_window_id":"9462647090c7713defc8223f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9462647090c7713defc8223f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[356,357,358,359,360,361,362,363],"take":"subject1/h2/3/cam4","frame_ids":[356,357,358,359,360,361,362,363]} +{"filtered_tile_id":"9462647090c7713defc8223f:8","filtered_window_id":"9462647090c7713defc8223f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9462647090c7713defc8223f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject1/h2/3/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"9462647090c7713defc8223f:16","filtered_window_id":"9462647090c7713defc8223f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9462647090c7713defc8223f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject1/h2/3/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"9462647090c7713defc8223f:24","filtered_window_id":"9462647090c7713defc8223f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9462647090c7713defc8223f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject1/h2/3/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"9462647090c7713defc8223f:32","filtered_window_id":"9462647090c7713defc8223f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9462647090c7713defc8223f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject1/h2/3/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"9462647090c7713defc8223f:40","filtered_window_id":"9462647090c7713defc8223f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9462647090c7713defc8223f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject1/h2/3/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"9462647090c7713defc8223f:48","filtered_window_id":"9462647090c7713defc8223f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9462647090c7713defc8223f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject1/h2/3/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"9462647090c7713defc8223f:52","filtered_window_id":"9462647090c7713defc8223f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9462647090c7713defc8223f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[408,409,410,411,412,413,414,415],"take":"subject1/h2/3/cam4","frame_ids":[408,409,410,411,412,413,414,415]} +{"filtered_tile_id":"948d813abc10545d936604b5:0","filtered_window_id":"948d813abc10545d936604b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/948d813abc10545d936604b5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[271,272,273,274,275,276,277,278],"take":"subject1/h2/4/cam4","frame_ids":[271,272,273,274,275,276,277,278]} +{"filtered_tile_id":"948d813abc10545d936604b5:8","filtered_window_id":"948d813abc10545d936604b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/948d813abc10545d936604b5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[279,280,281,282,283,284,285,286],"take":"subject1/h2/4/cam4","frame_ids":[279,280,281,282,283,284,285,286]} +{"filtered_tile_id":"948d813abc10545d936604b5:16","filtered_window_id":"948d813abc10545d936604b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/948d813abc10545d936604b5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[287,288,289,290,291,292,293,294],"take":"subject1/h2/4/cam4","frame_ids":[287,288,289,290,291,292,293,294]} +{"filtered_tile_id":"94e7e07b9f57b086a4bd80a5:0","filtered_window_id":"94e7e07b9f57b086a4bd80a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94e7e07b9f57b086a4bd80a5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[666,667,668,669,670,671,672,673],"take":"subject1/h2/7/cam4","frame_ids":[666,667,668,669,670,671,672,673]} +{"filtered_tile_id":"94e7e07b9f57b086a4bd80a5:8","filtered_window_id":"94e7e07b9f57b086a4bd80a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94e7e07b9f57b086a4bd80a5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[674,675,676,677,678,679,680,681],"take":"subject1/h2/7/cam4","frame_ids":[674,675,676,677,678,679,680,681]} +{"filtered_tile_id":"94e7e07b9f57b086a4bd80a5:16","filtered_window_id":"94e7e07b9f57b086a4bd80a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94e7e07b9f57b086a4bd80a5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[682,683,684,685,686,687,688,689],"take":"subject1/h2/7/cam4","frame_ids":[682,683,684,685,686,687,688,689]} +{"filtered_tile_id":"94e7e07b9f57b086a4bd80a5:24","filtered_window_id":"94e7e07b9f57b086a4bd80a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94e7e07b9f57b086a4bd80a5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[690,691,692,693,694,695,696,697],"take":"subject1/h2/7/cam4","frame_ids":[690,691,692,693,694,695,696,697]} +{"filtered_tile_id":"94e7e07b9f57b086a4bd80a5:32","filtered_window_id":"94e7e07b9f57b086a4bd80a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94e7e07b9f57b086a4bd80a5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[698,699,700,701,702,703,704,705],"take":"subject1/h2/7/cam4","frame_ids":[698,699,700,701,702,703,704,705]} +{"filtered_tile_id":"94e7e07b9f57b086a4bd80a5:40","filtered_window_id":"94e7e07b9f57b086a4bd80a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94e7e07b9f57b086a4bd80a5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[706,707,708,709,710,711,712,713],"take":"subject1/h2/7/cam4","frame_ids":[706,707,708,709,710,711,712,713]} +{"filtered_tile_id":"94e7e07b9f57b086a4bd80a5:41","filtered_window_id":"94e7e07b9f57b086a4bd80a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94e7e07b9f57b086a4bd80a5/native_gt.npz","filtered_start_offset":41,"expected_frame_ids":[707,708,709,710,711,712,713,714],"take":"subject1/h2/7/cam4","frame_ids":[707,708,709,710,711,712,713,714]} +{"filtered_tile_id":"94f42caa32fc3b70dd288a29:0","filtered_window_id":"94f42caa32fc3b70dd288a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f42caa32fc3b70dd288a29/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject3/h1/4/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"94f42caa32fc3b70dd288a29:8","filtered_window_id":"94f42caa32fc3b70dd288a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f42caa32fc3b70dd288a29/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject3/h1/4/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"94f42caa32fc3b70dd288a29:16","filtered_window_id":"94f42caa32fc3b70dd288a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f42caa32fc3b70dd288a29/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject3/h1/4/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"94f42caa32fc3b70dd288a29:24","filtered_window_id":"94f42caa32fc3b70dd288a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f42caa32fc3b70dd288a29/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject3/h1/4/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"94f42caa32fc3b70dd288a29:32","filtered_window_id":"94f42caa32fc3b70dd288a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f42caa32fc3b70dd288a29/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject3/h1/4/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"94f42caa32fc3b70dd288a29:40","filtered_window_id":"94f42caa32fc3b70dd288a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f42caa32fc3b70dd288a29/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject3/h1/4/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"94f42caa32fc3b70dd288a29:48","filtered_window_id":"94f42caa32fc3b70dd288a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f42caa32fc3b70dd288a29/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject3/h1/4/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"94f42caa32fc3b70dd288a29:51","filtered_window_id":"94f42caa32fc3b70dd288a29","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f42caa32fc3b70dd288a29/native_gt.npz","filtered_start_offset":51,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject3/h1/4/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"94f775b7c104e7bd4e93cb5c:0","filtered_window_id":"94f775b7c104e7bd4e93cb5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f775b7c104e7bd4e93cb5c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject1/h2/6/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"94f775b7c104e7bd4e93cb5c:8","filtered_window_id":"94f775b7c104e7bd4e93cb5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f775b7c104e7bd4e93cb5c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[426,427,428,429,430,431,432,433],"take":"subject1/h2/6/cam4","frame_ids":[426,427,428,429,430,431,432,433]} +{"filtered_tile_id":"94f775b7c104e7bd4e93cb5c:16","filtered_window_id":"94f775b7c104e7bd4e93cb5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f775b7c104e7bd4e93cb5c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[434,435,436,437,438,439,440,441],"take":"subject1/h2/6/cam4","frame_ids":[434,435,436,437,438,439,440,441]} +{"filtered_tile_id":"94f775b7c104e7bd4e93cb5c:24","filtered_window_id":"94f775b7c104e7bd4e93cb5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f775b7c104e7bd4e93cb5c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject1/h2/6/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"94f775b7c104e7bd4e93cb5c:32","filtered_window_id":"94f775b7c104e7bd4e93cb5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f775b7c104e7bd4e93cb5c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject1/h2/6/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"94f775b7c104e7bd4e93cb5c:40","filtered_window_id":"94f775b7c104e7bd4e93cb5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f775b7c104e7bd4e93cb5c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject1/h2/6/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"94f775b7c104e7bd4e93cb5c:48","filtered_window_id":"94f775b7c104e7bd4e93cb5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f775b7c104e7bd4e93cb5c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[466,467,468,469,470,471,472,473],"take":"subject1/h2/6/cam4","frame_ids":[466,467,468,469,470,471,472,473]} +{"filtered_tile_id":"94f775b7c104e7bd4e93cb5c:52","filtered_window_id":"94f775b7c104e7bd4e93cb5c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/94f775b7c104e7bd4e93cb5c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject1/h2/6/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"95167290921db6bbb60df483:0","filtered_window_id":"95167290921db6bbb60df483","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/95167290921db6bbb60df483/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[290,291,292,293,294,295,296,297],"take":"subject1/h1/5/cam4","frame_ids":[290,291,292,293,294,295,296,297]} +{"filtered_tile_id":"95167290921db6bbb60df483:8","filtered_window_id":"95167290921db6bbb60df483","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/95167290921db6bbb60df483/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject1/h1/5/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"95167290921db6bbb60df483:16","filtered_window_id":"95167290921db6bbb60df483","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/95167290921db6bbb60df483/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[306,307,308,309,310,311,312,313],"take":"subject1/h1/5/cam4","frame_ids":[306,307,308,309,310,311,312,313]} +{"filtered_tile_id":"95167290921db6bbb60df483:24","filtered_window_id":"95167290921db6bbb60df483","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/95167290921db6bbb60df483/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject1/h1/5/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"95167290921db6bbb60df483:32","filtered_window_id":"95167290921db6bbb60df483","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/95167290921db6bbb60df483/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject1/h1/5/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"95167290921db6bbb60df483:40","filtered_window_id":"95167290921db6bbb60df483","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/95167290921db6bbb60df483/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject1/h1/5/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"95167290921db6bbb60df483:48","filtered_window_id":"95167290921db6bbb60df483","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/95167290921db6bbb60df483/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject1/h1/5/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"95167290921db6bbb60df483:52","filtered_window_id":"95167290921db6bbb60df483","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/95167290921db6bbb60df483/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject1/h1/5/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"955c26c147c7262b81007123:0","filtered_window_id":"955c26c147c7262b81007123","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/955c26c147c7262b81007123/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject2/o2/5/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"955c26c147c7262b81007123:8","filtered_window_id":"955c26c147c7262b81007123","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/955c26c147c7262b81007123/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject2/o2/5/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"955c26c147c7262b81007123:16","filtered_window_id":"955c26c147c7262b81007123","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/955c26c147c7262b81007123/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[386,387,388,389,390,391,392,393],"take":"subject2/o2/5/cam4","frame_ids":[386,387,388,389,390,391,392,393]} +{"filtered_tile_id":"955c26c147c7262b81007123:24","filtered_window_id":"955c26c147c7262b81007123","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/955c26c147c7262b81007123/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[394,395,396,397,398,399,400,401],"take":"subject2/o2/5/cam4","frame_ids":[394,395,396,397,398,399,400,401]} +{"filtered_tile_id":"955c26c147c7262b81007123:32","filtered_window_id":"955c26c147c7262b81007123","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/955c26c147c7262b81007123/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[402,403,404,405,406,407,408,409],"take":"subject2/o2/5/cam4","frame_ids":[402,403,404,405,406,407,408,409]} +{"filtered_tile_id":"955c26c147c7262b81007123:40","filtered_window_id":"955c26c147c7262b81007123","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/955c26c147c7262b81007123/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[410,411,412,413,414,415,416,417],"take":"subject2/o2/5/cam4","frame_ids":[410,411,412,413,414,415,416,417]} +{"filtered_tile_id":"955c26c147c7262b81007123:48","filtered_window_id":"955c26c147c7262b81007123","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/955c26c147c7262b81007123/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject2/o2/5/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"955c26c147c7262b81007123:52","filtered_window_id":"955c26c147c7262b81007123","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/955c26c147c7262b81007123/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[422,423,424,425,426,427,428,429],"take":"subject2/o2/5/cam4","frame_ids":[422,423,424,425,426,427,428,429]} +{"filtered_tile_id":"966dbcbc51d35fc557f24ba2:0","filtered_window_id":"966dbcbc51d35fc557f24ba2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dbcbc51d35fc557f24ba2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[243,244,245,246,247,248,249,250],"take":"subject2/h1/4/cam4","frame_ids":[243,244,245,246,247,248,249,250]} +{"filtered_tile_id":"966dbcbc51d35fc557f24ba2:8","filtered_window_id":"966dbcbc51d35fc557f24ba2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dbcbc51d35fc557f24ba2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[251,252,253,254,255,256,257,258],"take":"subject2/h1/4/cam4","frame_ids":[251,252,253,254,255,256,257,258]} +{"filtered_tile_id":"966dbcbc51d35fc557f24ba2:16","filtered_window_id":"966dbcbc51d35fc557f24ba2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dbcbc51d35fc557f24ba2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[259,260,261,262,263,264,265,266],"take":"subject2/h1/4/cam4","frame_ids":[259,260,261,262,263,264,265,266]} +{"filtered_tile_id":"966dbcbc51d35fc557f24ba2:24","filtered_window_id":"966dbcbc51d35fc557f24ba2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dbcbc51d35fc557f24ba2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[267,268,269,270,271,272,273,274],"take":"subject2/h1/4/cam4","frame_ids":[267,268,269,270,271,272,273,274]} +{"filtered_tile_id":"966dbcbc51d35fc557f24ba2:32","filtered_window_id":"966dbcbc51d35fc557f24ba2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dbcbc51d35fc557f24ba2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[275,276,277,278,279,280,281,282],"take":"subject2/h1/4/cam4","frame_ids":[275,276,277,278,279,280,281,282]} +{"filtered_tile_id":"966dbcbc51d35fc557f24ba2:40","filtered_window_id":"966dbcbc51d35fc557f24ba2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dbcbc51d35fc557f24ba2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[283,284,285,286,287,288,289,290],"take":"subject2/h1/4/cam4","frame_ids":[283,284,285,286,287,288,289,290]} +{"filtered_tile_id":"966dbcbc51d35fc557f24ba2:48","filtered_window_id":"966dbcbc51d35fc557f24ba2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dbcbc51d35fc557f24ba2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[291,292,293,294,295,296,297,298],"take":"subject2/h1/4/cam4","frame_ids":[291,292,293,294,295,296,297,298]} +{"filtered_tile_id":"966dbcbc51d35fc557f24ba2:52","filtered_window_id":"966dbcbc51d35fc557f24ba2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dbcbc51d35fc557f24ba2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[295,296,297,298,299,300,301,302],"take":"subject2/h1/4/cam4","frame_ids":[295,296,297,298,299,300,301,302]} +{"filtered_tile_id":"966dddbb6914cccfbf2e89ba:0","filtered_window_id":"966dddbb6914cccfbf2e89ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dddbb6914cccfbf2e89ba/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[629,630,631,632,633,634,635,636],"take":"subject2/h1/3/cam4","frame_ids":[629,630,631,632,633,634,635,636]} +{"filtered_tile_id":"966dddbb6914cccfbf2e89ba:8","filtered_window_id":"966dddbb6914cccfbf2e89ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dddbb6914cccfbf2e89ba/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[637,638,639,640,641,642,643,644],"take":"subject2/h1/3/cam4","frame_ids":[637,638,639,640,641,642,643,644]} +{"filtered_tile_id":"966dddbb6914cccfbf2e89ba:16","filtered_window_id":"966dddbb6914cccfbf2e89ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dddbb6914cccfbf2e89ba/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[645,646,647,648,649,650,651,652],"take":"subject2/h1/3/cam4","frame_ids":[645,646,647,648,649,650,651,652]} +{"filtered_tile_id":"966dddbb6914cccfbf2e89ba:24","filtered_window_id":"966dddbb6914cccfbf2e89ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dddbb6914cccfbf2e89ba/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[653,654,655,656,657,658,659,660],"take":"subject2/h1/3/cam4","frame_ids":[653,654,655,656,657,658,659,660]} +{"filtered_tile_id":"966dddbb6914cccfbf2e89ba:32","filtered_window_id":"966dddbb6914cccfbf2e89ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dddbb6914cccfbf2e89ba/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[661,662,663,664,665,666,667,668],"take":"subject2/h1/3/cam4","frame_ids":[661,662,663,664,665,666,667,668]} +{"filtered_tile_id":"966dddbb6914cccfbf2e89ba:40","filtered_window_id":"966dddbb6914cccfbf2e89ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dddbb6914cccfbf2e89ba/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[669,670,671,672,673,674,675,676],"take":"subject2/h1/3/cam4","frame_ids":[669,670,671,672,673,674,675,676]} +{"filtered_tile_id":"966dddbb6914cccfbf2e89ba:48","filtered_window_id":"966dddbb6914cccfbf2e89ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dddbb6914cccfbf2e89ba/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[677,678,679,680,681,682,683,684],"take":"subject2/h1/3/cam4","frame_ids":[677,678,679,680,681,682,683,684]} +{"filtered_tile_id":"966dddbb6914cccfbf2e89ba:52","filtered_window_id":"966dddbb6914cccfbf2e89ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/966dddbb6914cccfbf2e89ba/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[681,682,683,684,685,686,687,688],"take":"subject2/h1/3/cam4","frame_ids":[681,682,683,684,685,686,687,688]} +{"filtered_tile_id":"96dff1eb4d2b1655262e1b2c:0","filtered_window_id":"96dff1eb4d2b1655262e1b2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/96dff1eb4d2b1655262e1b2c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject1/k1/3/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"96dff1eb4d2b1655262e1b2c:8","filtered_window_id":"96dff1eb4d2b1655262e1b2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/96dff1eb4d2b1655262e1b2c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject1/k1/3/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"96dff1eb4d2b1655262e1b2c:16","filtered_window_id":"96dff1eb4d2b1655262e1b2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/96dff1eb4d2b1655262e1b2c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject1/k1/3/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"96dff1eb4d2b1655262e1b2c:24","filtered_window_id":"96dff1eb4d2b1655262e1b2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/96dff1eb4d2b1655262e1b2c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject1/k1/3/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"96dff1eb4d2b1655262e1b2c:32","filtered_window_id":"96dff1eb4d2b1655262e1b2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/96dff1eb4d2b1655262e1b2c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject1/k1/3/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"96dff1eb4d2b1655262e1b2c:40","filtered_window_id":"96dff1eb4d2b1655262e1b2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/96dff1eb4d2b1655262e1b2c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject1/k1/3/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"96dff1eb4d2b1655262e1b2c:48","filtered_window_id":"96dff1eb4d2b1655262e1b2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/96dff1eb4d2b1655262e1b2c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject1/k1/3/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"96dff1eb4d2b1655262e1b2c:52","filtered_window_id":"96dff1eb4d2b1655262e1b2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/96dff1eb4d2b1655262e1b2c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[532,533,534,535,536,537,538,539],"take":"subject1/k1/3/cam4","frame_ids":[532,533,534,535,536,537,538,539]} +{"filtered_tile_id":"971e40b26b316bcec16463c4:0","filtered_window_id":"971e40b26b316bcec16463c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/971e40b26b316bcec16463c4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/k2/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"971e40b26b316bcec16463c4:8","filtered_window_id":"971e40b26b316bcec16463c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/971e40b26b316bcec16463c4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/k2/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"971e40b26b316bcec16463c4:16","filtered_window_id":"971e40b26b316bcec16463c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/971e40b26b316bcec16463c4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/k2/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"971e40b26b316bcec16463c4:24","filtered_window_id":"971e40b26b316bcec16463c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/971e40b26b316bcec16463c4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/k2/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"971e40b26b316bcec16463c4:32","filtered_window_id":"971e40b26b316bcec16463c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/971e40b26b316bcec16463c4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/k2/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"971e40b26b316bcec16463c4:40","filtered_window_id":"971e40b26b316bcec16463c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/971e40b26b316bcec16463c4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/k2/1/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"971e40b26b316bcec16463c4:48","filtered_window_id":"971e40b26b316bcec16463c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/971e40b26b316bcec16463c4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/k2/1/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"971e40b26b316bcec16463c4:52","filtered_window_id":"971e40b26b316bcec16463c4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/971e40b26b316bcec16463c4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/k2/1/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"9721d40073daa73a9624f06c:0","filtered_window_id":"9721d40073daa73a9624f06c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9721d40073daa73a9624f06c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject2/o1/0/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"9721d40073daa73a9624f06c:6","filtered_window_id":"9721d40073daa73a9624f06c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9721d40073daa73a9624f06c/native_gt.npz","filtered_start_offset":6,"expected_frame_ids":[74,75,76,77,78,79,80,81],"take":"subject2/o1/0/cam4","frame_ids":[74,75,76,77,78,79,80,81]} +{"filtered_tile_id":"973ea7c60151fbf3ce479e14:0","filtered_window_id":"973ea7c60151fbf3ce479e14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/973ea7c60151fbf3ce479e14/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/k1/7/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"973ea7c60151fbf3ce479e14:8","filtered_window_id":"973ea7c60151fbf3ce479e14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/973ea7c60151fbf3ce479e14/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/k1/7/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"973ea7c60151fbf3ce479e14:16","filtered_window_id":"973ea7c60151fbf3ce479e14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/973ea7c60151fbf3ce479e14/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k1/7/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"973ea7c60151fbf3ce479e14:24","filtered_window_id":"973ea7c60151fbf3ce479e14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/973ea7c60151fbf3ce479e14/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k1/7/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"973ea7c60151fbf3ce479e14:32","filtered_window_id":"973ea7c60151fbf3ce479e14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/973ea7c60151fbf3ce479e14/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k1/7/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"973ea7c60151fbf3ce479e14:38","filtered_window_id":"973ea7c60151fbf3ce479e14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/973ea7c60151fbf3ce479e14/native_gt.npz","filtered_start_offset":38,"expected_frame_ids":[38,39,40,41,42,43,44,45],"take":"subject1/k1/7/cam4","frame_ids":[38,39,40,41,42,43,44,45]} +{"filtered_tile_id":"977380d20f72460229bf80c0:0","filtered_window_id":"977380d20f72460229bf80c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/977380d20f72460229bf80c0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[6,7,8,9,10,11,12,13],"take":"subject1/k2/2/cam4","frame_ids":[6,7,8,9,10,11,12,13]} +{"filtered_tile_id":"977380d20f72460229bf80c0:8","filtered_window_id":"977380d20f72460229bf80c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/977380d20f72460229bf80c0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[14,15,16,17,18,19,20,21],"take":"subject1/k2/2/cam4","frame_ids":[14,15,16,17,18,19,20,21]} +{"filtered_tile_id":"977380d20f72460229bf80c0:16","filtered_window_id":"977380d20f72460229bf80c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/977380d20f72460229bf80c0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[22,23,24,25,26,27,28,29],"take":"subject1/k2/2/cam4","frame_ids":[22,23,24,25,26,27,28,29]} +{"filtered_tile_id":"977380d20f72460229bf80c0:24","filtered_window_id":"977380d20f72460229bf80c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/977380d20f72460229bf80c0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[30,31,32,33,34,35,36,37],"take":"subject1/k2/2/cam4","frame_ids":[30,31,32,33,34,35,36,37]} +{"filtered_tile_id":"977380d20f72460229bf80c0:32","filtered_window_id":"977380d20f72460229bf80c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/977380d20f72460229bf80c0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[38,39,40,41,42,43,44,45],"take":"subject1/k2/2/cam4","frame_ids":[38,39,40,41,42,43,44,45]} +{"filtered_tile_id":"977380d20f72460229bf80c0:40","filtered_window_id":"977380d20f72460229bf80c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/977380d20f72460229bf80c0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[46,47,48,49,50,51,52,53],"take":"subject1/k2/2/cam4","frame_ids":[46,47,48,49,50,51,52,53]} +{"filtered_tile_id":"977380d20f72460229bf80c0:48","filtered_window_id":"977380d20f72460229bf80c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/977380d20f72460229bf80c0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[54,55,56,57,58,59,60,61],"take":"subject1/k2/2/cam4","frame_ids":[54,55,56,57,58,59,60,61]} +{"filtered_tile_id":"977380d20f72460229bf80c0:52","filtered_window_id":"977380d20f72460229bf80c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/977380d20f72460229bf80c0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[58,59,60,61,62,63,64,65],"take":"subject1/k2/2/cam4","frame_ids":[58,59,60,61,62,63,64,65]} +{"filtered_tile_id":"978c1707e828f3c2f2737aec:0","filtered_window_id":"978c1707e828f3c2f2737aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/978c1707e828f3c2f2737aec/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject1/k1/7/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"978c1707e828f3c2f2737aec:8","filtered_window_id":"978c1707e828f3c2f2737aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/978c1707e828f3c2f2737aec/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject1/k1/7/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"978c1707e828f3c2f2737aec:16","filtered_window_id":"978c1707e828f3c2f2737aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/978c1707e828f3c2f2737aec/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject1/k1/7/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"978c1707e828f3c2f2737aec:24","filtered_window_id":"978c1707e828f3c2f2737aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/978c1707e828f3c2f2737aec/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject1/k1/7/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"978c1707e828f3c2f2737aec:32","filtered_window_id":"978c1707e828f3c2f2737aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/978c1707e828f3c2f2737aec/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject1/k1/7/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"978c1707e828f3c2f2737aec:40","filtered_window_id":"978c1707e828f3c2f2737aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/978c1707e828f3c2f2737aec/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject1/k1/7/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"978c1707e828f3c2f2737aec:48","filtered_window_id":"978c1707e828f3c2f2737aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/978c1707e828f3c2f2737aec/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[341,342,343,344,345,346,347,348],"take":"subject1/k1/7/cam4","frame_ids":[341,342,343,344,345,346,347,348]} +{"filtered_tile_id":"978c1707e828f3c2f2737aec:52","filtered_window_id":"978c1707e828f3c2f2737aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/978c1707e828f3c2f2737aec/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject1/k1/7/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"9793cded61e376b6350820cb:0","filtered_window_id":"9793cded61e376b6350820cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9793cded61e376b6350820cb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h1/7/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"9793cded61e376b6350820cb:8","filtered_window_id":"9793cded61e376b6350820cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9793cded61e376b6350820cb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h1/7/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"9793cded61e376b6350820cb:16","filtered_window_id":"9793cded61e376b6350820cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9793cded61e376b6350820cb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h1/7/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"9793cded61e376b6350820cb:24","filtered_window_id":"9793cded61e376b6350820cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9793cded61e376b6350820cb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h1/7/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"9793cded61e376b6350820cb:32","filtered_window_id":"9793cded61e376b6350820cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9793cded61e376b6350820cb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h1/7/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"9793cded61e376b6350820cb:40","filtered_window_id":"9793cded61e376b6350820cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9793cded61e376b6350820cb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/h1/7/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"9793cded61e376b6350820cb:48","filtered_window_id":"9793cded61e376b6350820cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9793cded61e376b6350820cb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/h1/7/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"9793cded61e376b6350820cb:52","filtered_window_id":"9793cded61e376b6350820cb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9793cded61e376b6350820cb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/h1/7/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"97ed99528be9655ce7c1504b:0","filtered_window_id":"97ed99528be9655ce7c1504b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/97ed99528be9655ce7c1504b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[448,449,450,451,452,453,454,455],"take":"subject2/h1/7/cam4","frame_ids":[448,449,450,451,452,453,454,455]} +{"filtered_tile_id":"97ed99528be9655ce7c1504b:8","filtered_window_id":"97ed99528be9655ce7c1504b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/97ed99528be9655ce7c1504b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[456,457,458,459,460,461,462,463],"take":"subject2/h1/7/cam4","frame_ids":[456,457,458,459,460,461,462,463]} +{"filtered_tile_id":"97ed99528be9655ce7c1504b:16","filtered_window_id":"97ed99528be9655ce7c1504b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/97ed99528be9655ce7c1504b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[464,465,466,467,468,469,470,471],"take":"subject2/h1/7/cam4","frame_ids":[464,465,466,467,468,469,470,471]} +{"filtered_tile_id":"97ed99528be9655ce7c1504b:24","filtered_window_id":"97ed99528be9655ce7c1504b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/97ed99528be9655ce7c1504b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject2/h1/7/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"97ed99528be9655ce7c1504b:32","filtered_window_id":"97ed99528be9655ce7c1504b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/97ed99528be9655ce7c1504b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject2/h1/7/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"97ed99528be9655ce7c1504b:40","filtered_window_id":"97ed99528be9655ce7c1504b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/97ed99528be9655ce7c1504b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject2/h1/7/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"97ed99528be9655ce7c1504b:48","filtered_window_id":"97ed99528be9655ce7c1504b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/97ed99528be9655ce7c1504b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject2/h1/7/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"97ed99528be9655ce7c1504b:52","filtered_window_id":"97ed99528be9655ce7c1504b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/97ed99528be9655ce7c1504b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[500,501,502,503,504,505,506,507],"take":"subject2/h1/7/cam4","frame_ids":[500,501,502,503,504,505,506,507]} +{"filtered_tile_id":"980e915e631e94ecdab4cb1d:0","filtered_window_id":"980e915e631e94ecdab4cb1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/980e915e631e94ecdab4cb1d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[602,603,604,605,606,607,608,609],"take":"subject2/o1/3/cam4","frame_ids":[602,603,604,605,606,607,608,609]} +{"filtered_tile_id":"980e915e631e94ecdab4cb1d:8","filtered_window_id":"980e915e631e94ecdab4cb1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/980e915e631e94ecdab4cb1d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[610,611,612,613,614,615,616,617],"take":"subject2/o1/3/cam4","frame_ids":[610,611,612,613,614,615,616,617]} +{"filtered_tile_id":"980e915e631e94ecdab4cb1d:16","filtered_window_id":"980e915e631e94ecdab4cb1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/980e915e631e94ecdab4cb1d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[618,619,620,621,622,623,624,625],"take":"subject2/o1/3/cam4","frame_ids":[618,619,620,621,622,623,624,625]} +{"filtered_tile_id":"980e915e631e94ecdab4cb1d:24","filtered_window_id":"980e915e631e94ecdab4cb1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/980e915e631e94ecdab4cb1d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[626,627,628,629,630,631,632,633],"take":"subject2/o1/3/cam4","frame_ids":[626,627,628,629,630,631,632,633]} +{"filtered_tile_id":"980e915e631e94ecdab4cb1d:32","filtered_window_id":"980e915e631e94ecdab4cb1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/980e915e631e94ecdab4cb1d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[634,635,636,637,638,639,640,641],"take":"subject2/o1/3/cam4","frame_ids":[634,635,636,637,638,639,640,641]} +{"filtered_tile_id":"980e915e631e94ecdab4cb1d:40","filtered_window_id":"980e915e631e94ecdab4cb1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/980e915e631e94ecdab4cb1d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[642,643,644,645,646,647,648,649],"take":"subject2/o1/3/cam4","frame_ids":[642,643,644,645,646,647,648,649]} +{"filtered_tile_id":"980e915e631e94ecdab4cb1d:48","filtered_window_id":"980e915e631e94ecdab4cb1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/980e915e631e94ecdab4cb1d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[650,651,652,653,654,655,656,657],"take":"subject2/o1/3/cam4","frame_ids":[650,651,652,653,654,655,656,657]} +{"filtered_tile_id":"980e915e631e94ecdab4cb1d:52","filtered_window_id":"980e915e631e94ecdab4cb1d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/980e915e631e94ecdab4cb1d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[654,655,656,657,658,659,660,661],"take":"subject2/o1/3/cam4","frame_ids":[654,655,656,657,658,659,660,661]} +{"filtered_tile_id":"981f4615ed51c672b830f70a:0","filtered_window_id":"981f4615ed51c672b830f70a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/981f4615ed51c672b830f70a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject2/o1/4/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"981f4615ed51c672b830f70a:8","filtered_window_id":"981f4615ed51c672b830f70a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/981f4615ed51c672b830f70a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject2/o1/4/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"981f4615ed51c672b830f70a:16","filtered_window_id":"981f4615ed51c672b830f70a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/981f4615ed51c672b830f70a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject2/o1/4/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"981f4615ed51c672b830f70a:24","filtered_window_id":"981f4615ed51c672b830f70a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/981f4615ed51c672b830f70a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject2/o1/4/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"981f4615ed51c672b830f70a:26","filtered_window_id":"981f4615ed51c672b830f70a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/981f4615ed51c672b830f70a/native_gt.npz","filtered_start_offset":26,"expected_frame_ids":[331,332,333,334,335,336,337,338],"take":"subject2/o1/4/cam4","frame_ids":[331,332,333,334,335,336,337,338]} +{"filtered_tile_id":"982d76dc2d17e3fb0fa2d03c:0","filtered_window_id":"982d76dc2d17e3fb0fa2d03c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/982d76dc2d17e3fb0fa2d03c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject3/k1/3/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"982d76dc2d17e3fb0fa2d03c:8","filtered_window_id":"982d76dc2d17e3fb0fa2d03c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/982d76dc2d17e3fb0fa2d03c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[207,208,209,210,211,212,213,214],"take":"subject3/k1/3/cam4","frame_ids":[207,208,209,210,211,212,213,214]} +{"filtered_tile_id":"982d76dc2d17e3fb0fa2d03c:16","filtered_window_id":"982d76dc2d17e3fb0fa2d03c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/982d76dc2d17e3fb0fa2d03c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[215,216,217,218,219,220,221,222],"take":"subject3/k1/3/cam4","frame_ids":[215,216,217,218,219,220,221,222]} +{"filtered_tile_id":"982d76dc2d17e3fb0fa2d03c:24","filtered_window_id":"982d76dc2d17e3fb0fa2d03c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/982d76dc2d17e3fb0fa2d03c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject3/k1/3/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"982d76dc2d17e3fb0fa2d03c:32","filtered_window_id":"982d76dc2d17e3fb0fa2d03c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/982d76dc2d17e3fb0fa2d03c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject3/k1/3/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"982d76dc2d17e3fb0fa2d03c:40","filtered_window_id":"982d76dc2d17e3fb0fa2d03c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/982d76dc2d17e3fb0fa2d03c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject3/k1/3/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"982d76dc2d17e3fb0fa2d03c:48","filtered_window_id":"982d76dc2d17e3fb0fa2d03c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/982d76dc2d17e3fb0fa2d03c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject3/k1/3/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"982d76dc2d17e3fb0fa2d03c:52","filtered_window_id":"982d76dc2d17e3fb0fa2d03c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/982d76dc2d17e3fb0fa2d03c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[251,252,253,254,255,256,257,258],"take":"subject3/k1/3/cam4","frame_ids":[251,252,253,254,255,256,257,258]} +{"filtered_tile_id":"986bf60baa2a10f678b94a27:0","filtered_window_id":"986bf60baa2a10f678b94a27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/986bf60baa2a10f678b94a27/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[186,187,188,189,190,191,192,193],"take":"subject2/o1/1/cam4","frame_ids":[186,187,188,189,190,191,192,193]} +{"filtered_tile_id":"986bf60baa2a10f678b94a27:8","filtered_window_id":"986bf60baa2a10f678b94a27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/986bf60baa2a10f678b94a27/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[194,195,196,197,198,199,200,201],"take":"subject2/o1/1/cam4","frame_ids":[194,195,196,197,198,199,200,201]} +{"filtered_tile_id":"986bf60baa2a10f678b94a27:16","filtered_window_id":"986bf60baa2a10f678b94a27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/986bf60baa2a10f678b94a27/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[202,203,204,205,206,207,208,209],"take":"subject2/o1/1/cam4","frame_ids":[202,203,204,205,206,207,208,209]} +{"filtered_tile_id":"986bf60baa2a10f678b94a27:24","filtered_window_id":"986bf60baa2a10f678b94a27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/986bf60baa2a10f678b94a27/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[210,211,212,213,214,215,216,217],"take":"subject2/o1/1/cam4","frame_ids":[210,211,212,213,214,215,216,217]} +{"filtered_tile_id":"986bf60baa2a10f678b94a27:32","filtered_window_id":"986bf60baa2a10f678b94a27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/986bf60baa2a10f678b94a27/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[218,219,220,221,222,223,224,225],"take":"subject2/o1/1/cam4","frame_ids":[218,219,220,221,222,223,224,225]} +{"filtered_tile_id":"986bf60baa2a10f678b94a27:40","filtered_window_id":"986bf60baa2a10f678b94a27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/986bf60baa2a10f678b94a27/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject2/o1/1/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"986bf60baa2a10f678b94a27:48","filtered_window_id":"986bf60baa2a10f678b94a27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/986bf60baa2a10f678b94a27/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject2/o1/1/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"986bf60baa2a10f678b94a27:52","filtered_window_id":"986bf60baa2a10f678b94a27","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/986bf60baa2a10f678b94a27/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject2/o1/1/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"988abc8e5ccceb6cbdf5a1e2:0","filtered_window_id":"988abc8e5ccceb6cbdf5a1e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988abc8e5ccceb6cbdf5a1e2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject2/k2/1/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"988abc8e5ccceb6cbdf5a1e2:8","filtered_window_id":"988abc8e5ccceb6cbdf5a1e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988abc8e5ccceb6cbdf5a1e2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject2/k2/1/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"988abc8e5ccceb6cbdf5a1e2:16","filtered_window_id":"988abc8e5ccceb6cbdf5a1e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988abc8e5ccceb6cbdf5a1e2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[236,237,238,239,240,241,242,243],"take":"subject2/k2/1/cam4","frame_ids":[236,237,238,239,240,241,242,243]} +{"filtered_tile_id":"988abc8e5ccceb6cbdf5a1e2:24","filtered_window_id":"988abc8e5ccceb6cbdf5a1e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988abc8e5ccceb6cbdf5a1e2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[244,245,246,247,248,249,250,251],"take":"subject2/k2/1/cam4","frame_ids":[244,245,246,247,248,249,250,251]} +{"filtered_tile_id":"988abc8e5ccceb6cbdf5a1e2:32","filtered_window_id":"988abc8e5ccceb6cbdf5a1e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988abc8e5ccceb6cbdf5a1e2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[252,253,254,255,256,257,258,259],"take":"subject2/k2/1/cam4","frame_ids":[252,253,254,255,256,257,258,259]} +{"filtered_tile_id":"988abc8e5ccceb6cbdf5a1e2:40","filtered_window_id":"988abc8e5ccceb6cbdf5a1e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988abc8e5ccceb6cbdf5a1e2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[260,261,262,263,264,265,266,267],"take":"subject2/k2/1/cam4","frame_ids":[260,261,262,263,264,265,266,267]} +{"filtered_tile_id":"988abc8e5ccceb6cbdf5a1e2:48","filtered_window_id":"988abc8e5ccceb6cbdf5a1e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988abc8e5ccceb6cbdf5a1e2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[268,269,270,271,272,273,274,275],"take":"subject2/k2/1/cam4","frame_ids":[268,269,270,271,272,273,274,275]} +{"filtered_tile_id":"988abc8e5ccceb6cbdf5a1e2:52","filtered_window_id":"988abc8e5ccceb6cbdf5a1e2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988abc8e5ccceb6cbdf5a1e2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject2/k2/1/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"988bcdab36e40dfe3a6948fe:0","filtered_window_id":"988bcdab36e40dfe3a6948fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988bcdab36e40dfe3a6948fe/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/k2/4/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"988bcdab36e40dfe3a6948fe:8","filtered_window_id":"988bcdab36e40dfe3a6948fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988bcdab36e40dfe3a6948fe/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/k2/4/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"988bcdab36e40dfe3a6948fe:16","filtered_window_id":"988bcdab36e40dfe3a6948fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988bcdab36e40dfe3a6948fe/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k2/4/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"988bcdab36e40dfe3a6948fe:24","filtered_window_id":"988bcdab36e40dfe3a6948fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988bcdab36e40dfe3a6948fe/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k2/4/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"988bcdab36e40dfe3a6948fe:32","filtered_window_id":"988bcdab36e40dfe3a6948fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988bcdab36e40dfe3a6948fe/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k2/4/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"988bcdab36e40dfe3a6948fe:40","filtered_window_id":"988bcdab36e40dfe3a6948fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988bcdab36e40dfe3a6948fe/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/k2/4/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"988bcdab36e40dfe3a6948fe:48","filtered_window_id":"988bcdab36e40dfe3a6948fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988bcdab36e40dfe3a6948fe/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/k2/4/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"988bcdab36e40dfe3a6948fe:52","filtered_window_id":"988bcdab36e40dfe3a6948fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/988bcdab36e40dfe3a6948fe/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/k2/4/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"98debe4c8b709e3f1514013e:0","filtered_window_id":"98debe4c8b709e3f1514013e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98debe4c8b709e3f1514013e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[74,75,76,77,78,79,80,81],"take":"subject1/o1/0/cam4","frame_ids":[74,75,76,77,78,79,80,81]} +{"filtered_tile_id":"98debe4c8b709e3f1514013e:8","filtered_window_id":"98debe4c8b709e3f1514013e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98debe4c8b709e3f1514013e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[82,83,84,85,86,87,88,89],"take":"subject1/o1/0/cam4","frame_ids":[82,83,84,85,86,87,88,89]} +{"filtered_tile_id":"98debe4c8b709e3f1514013e:16","filtered_window_id":"98debe4c8b709e3f1514013e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98debe4c8b709e3f1514013e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject1/o1/0/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"98debe4c8b709e3f1514013e:24","filtered_window_id":"98debe4c8b709e3f1514013e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98debe4c8b709e3f1514013e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[98,99,100,101,102,103,104,105],"take":"subject1/o1/0/cam4","frame_ids":[98,99,100,101,102,103,104,105]} +{"filtered_tile_id":"98debe4c8b709e3f1514013e:32","filtered_window_id":"98debe4c8b709e3f1514013e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98debe4c8b709e3f1514013e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[106,107,108,109,110,111,112,113],"take":"subject1/o1/0/cam4","frame_ids":[106,107,108,109,110,111,112,113]} +{"filtered_tile_id":"98debe4c8b709e3f1514013e:40","filtered_window_id":"98debe4c8b709e3f1514013e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98debe4c8b709e3f1514013e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject1/o1/0/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"98debe4c8b709e3f1514013e:47","filtered_window_id":"98debe4c8b709e3f1514013e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98debe4c8b709e3f1514013e/native_gt.npz","filtered_start_offset":47,"expected_frame_ids":[121,122,123,124,125,126,127,128],"take":"subject1/o1/0/cam4","frame_ids":[121,122,123,124,125,126,127,128]} +{"filtered_tile_id":"98ebb68348cbf8a35a025a64:0","filtered_window_id":"98ebb68348cbf8a35a025a64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98ebb68348cbf8a35a025a64/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[9,10,11,12,13,14,15,16],"take":"subject2/h2/4/cam4","frame_ids":[9,10,11,12,13,14,15,16]} +{"filtered_tile_id":"98ebb68348cbf8a35a025a64:8","filtered_window_id":"98ebb68348cbf8a35a025a64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98ebb68348cbf8a35a025a64/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[17,18,19,20,21,22,23,24],"take":"subject2/h2/4/cam4","frame_ids":[17,18,19,20,21,22,23,24]} +{"filtered_tile_id":"98ebb68348cbf8a35a025a64:16","filtered_window_id":"98ebb68348cbf8a35a025a64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98ebb68348cbf8a35a025a64/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[25,26,27,28,29,30,31,32],"take":"subject2/h2/4/cam4","frame_ids":[25,26,27,28,29,30,31,32]} +{"filtered_tile_id":"98ebb68348cbf8a35a025a64:24","filtered_window_id":"98ebb68348cbf8a35a025a64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98ebb68348cbf8a35a025a64/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[33,34,35,36,37,38,39,40],"take":"subject2/h2/4/cam4","frame_ids":[33,34,35,36,37,38,39,40]} +{"filtered_tile_id":"98ebb68348cbf8a35a025a64:32","filtered_window_id":"98ebb68348cbf8a35a025a64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98ebb68348cbf8a35a025a64/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[41,42,43,44,45,46,47,48],"take":"subject2/h2/4/cam4","frame_ids":[41,42,43,44,45,46,47,48]} +{"filtered_tile_id":"98ebb68348cbf8a35a025a64:40","filtered_window_id":"98ebb68348cbf8a35a025a64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98ebb68348cbf8a35a025a64/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[49,50,51,52,53,54,55,56],"take":"subject2/h2/4/cam4","frame_ids":[49,50,51,52,53,54,55,56]} +{"filtered_tile_id":"98ebb68348cbf8a35a025a64:48","filtered_window_id":"98ebb68348cbf8a35a025a64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98ebb68348cbf8a35a025a64/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[57,58,59,60,61,62,63,64],"take":"subject2/h2/4/cam4","frame_ids":[57,58,59,60,61,62,63,64]} +{"filtered_tile_id":"98ebb68348cbf8a35a025a64:52","filtered_window_id":"98ebb68348cbf8a35a025a64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/98ebb68348cbf8a35a025a64/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[61,62,63,64,65,66,67,68],"take":"subject2/h2/4/cam4","frame_ids":[61,62,63,64,65,66,67,68]} +{"filtered_tile_id":"993fdd045dcba770a8bbd07b:0","filtered_window_id":"993fdd045dcba770a8bbd07b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/993fdd045dcba770a8bbd07b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject2/o1/3/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"993fdd045dcba770a8bbd07b:8","filtered_window_id":"993fdd045dcba770a8bbd07b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/993fdd045dcba770a8bbd07b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject2/o1/3/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"993fdd045dcba770a8bbd07b:16","filtered_window_id":"993fdd045dcba770a8bbd07b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/993fdd045dcba770a8bbd07b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject2/o1/3/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"993fdd045dcba770a8bbd07b:24","filtered_window_id":"993fdd045dcba770a8bbd07b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/993fdd045dcba770a8bbd07b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject2/o1/3/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"993fdd045dcba770a8bbd07b:32","filtered_window_id":"993fdd045dcba770a8bbd07b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/993fdd045dcba770a8bbd07b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject2/o1/3/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"993fdd045dcba770a8bbd07b:40","filtered_window_id":"993fdd045dcba770a8bbd07b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/993fdd045dcba770a8bbd07b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject2/o1/3/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"993fdd045dcba770a8bbd07b:48","filtered_window_id":"993fdd045dcba770a8bbd07b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/993fdd045dcba770a8bbd07b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[219,220,221,222,223,224,225,226],"take":"subject2/o1/3/cam4","frame_ids":[219,220,221,222,223,224,225,226]} +{"filtered_tile_id":"993fdd045dcba770a8bbd07b:52","filtered_window_id":"993fdd045dcba770a8bbd07b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/993fdd045dcba770a8bbd07b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject2/o1/3/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"9943658efdc70ffaf31146f8:0","filtered_window_id":"9943658efdc70ffaf31146f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9943658efdc70ffaf31146f8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[262,263,264,265,266,267,268,269],"take":"subject3/h1/2/cam4","frame_ids":[262,263,264,265,266,267,268,269]} +{"filtered_tile_id":"9943658efdc70ffaf31146f8:8","filtered_window_id":"9943658efdc70ffaf31146f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9943658efdc70ffaf31146f8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[270,271,272,273,274,275,276,277],"take":"subject3/h1/2/cam4","frame_ids":[270,271,272,273,274,275,276,277]} +{"filtered_tile_id":"9943658efdc70ffaf31146f8:16","filtered_window_id":"9943658efdc70ffaf31146f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9943658efdc70ffaf31146f8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[278,279,280,281,282,283,284,285],"take":"subject3/h1/2/cam4","frame_ids":[278,279,280,281,282,283,284,285]} +{"filtered_tile_id":"9943658efdc70ffaf31146f8:24","filtered_window_id":"9943658efdc70ffaf31146f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9943658efdc70ffaf31146f8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[286,287,288,289,290,291,292,293],"take":"subject3/h1/2/cam4","frame_ids":[286,287,288,289,290,291,292,293]} +{"filtered_tile_id":"9943658efdc70ffaf31146f8:32","filtered_window_id":"9943658efdc70ffaf31146f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9943658efdc70ffaf31146f8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[294,295,296,297,298,299,300,301],"take":"subject3/h1/2/cam4","frame_ids":[294,295,296,297,298,299,300,301]} +{"filtered_tile_id":"9943658efdc70ffaf31146f8:40","filtered_window_id":"9943658efdc70ffaf31146f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9943658efdc70ffaf31146f8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[302,303,304,305,306,307,308,309],"take":"subject3/h1/2/cam4","frame_ids":[302,303,304,305,306,307,308,309]} +{"filtered_tile_id":"9943658efdc70ffaf31146f8:48","filtered_window_id":"9943658efdc70ffaf31146f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9943658efdc70ffaf31146f8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject3/h1/2/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"9943658efdc70ffaf31146f8:52","filtered_window_id":"9943658efdc70ffaf31146f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9943658efdc70ffaf31146f8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject3/h1/2/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"9978933e1bc58b64c7f8ac4e:0","filtered_window_id":"9978933e1bc58b64c7f8ac4e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9978933e1bc58b64c7f8ac4e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[749,750,751,752,753,754,755,756],"take":"subject2/h1/3/cam4","frame_ids":[749,750,751,752,753,754,755,756]} +{"filtered_tile_id":"9978933e1bc58b64c7f8ac4e:8","filtered_window_id":"9978933e1bc58b64c7f8ac4e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9978933e1bc58b64c7f8ac4e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[757,758,759,760,761,762,763,764],"take":"subject2/h1/3/cam4","frame_ids":[757,758,759,760,761,762,763,764]} +{"filtered_tile_id":"9978933e1bc58b64c7f8ac4e:16","filtered_window_id":"9978933e1bc58b64c7f8ac4e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9978933e1bc58b64c7f8ac4e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[765,766,767,768,769,770,771,772],"take":"subject2/h1/3/cam4","frame_ids":[765,766,767,768,769,770,771,772]} +{"filtered_tile_id":"9978933e1bc58b64c7f8ac4e:24","filtered_window_id":"9978933e1bc58b64c7f8ac4e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9978933e1bc58b64c7f8ac4e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[773,774,775,776,777,778,779,780],"take":"subject2/h1/3/cam4","frame_ids":[773,774,775,776,777,778,779,780]} +{"filtered_tile_id":"9978933e1bc58b64c7f8ac4e:32","filtered_window_id":"9978933e1bc58b64c7f8ac4e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9978933e1bc58b64c7f8ac4e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[781,782,783,784,785,786,787,788],"take":"subject2/h1/3/cam4","frame_ids":[781,782,783,784,785,786,787,788]} +{"filtered_tile_id":"9978933e1bc58b64c7f8ac4e:40","filtered_window_id":"9978933e1bc58b64c7f8ac4e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9978933e1bc58b64c7f8ac4e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[789,790,791,792,793,794,795,796],"take":"subject2/h1/3/cam4","frame_ids":[789,790,791,792,793,794,795,796]} +{"filtered_tile_id":"9978933e1bc58b64c7f8ac4e:48","filtered_window_id":"9978933e1bc58b64c7f8ac4e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9978933e1bc58b64c7f8ac4e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[797,798,799,800,801,802,803,804],"take":"subject2/h1/3/cam4","frame_ids":[797,798,799,800,801,802,803,804]} +{"filtered_tile_id":"9978933e1bc58b64c7f8ac4e:52","filtered_window_id":"9978933e1bc58b64c7f8ac4e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9978933e1bc58b64c7f8ac4e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[801,802,803,804,805,806,807,808],"take":"subject2/h1/3/cam4","frame_ids":[801,802,803,804,805,806,807,808]} +{"filtered_tile_id":"99dad260d07a8a25fb87e55e:0","filtered_window_id":"99dad260d07a8a25fb87e55e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/99dad260d07a8a25fb87e55e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject3/h2/0/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"99dad260d07a8a25fb87e55e:8","filtered_window_id":"99dad260d07a8a25fb87e55e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/99dad260d07a8a25fb87e55e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject3/h2/0/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"99dad260d07a8a25fb87e55e:16","filtered_window_id":"99dad260d07a8a25fb87e55e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/99dad260d07a8a25fb87e55e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject3/h2/0/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"99dad260d07a8a25fb87e55e:24","filtered_window_id":"99dad260d07a8a25fb87e55e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/99dad260d07a8a25fb87e55e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject3/h2/0/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"99dad260d07a8a25fb87e55e:32","filtered_window_id":"99dad260d07a8a25fb87e55e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/99dad260d07a8a25fb87e55e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject3/h2/0/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"99dad260d07a8a25fb87e55e:40","filtered_window_id":"99dad260d07a8a25fb87e55e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/99dad260d07a8a25fb87e55e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject3/h2/0/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"99dad260d07a8a25fb87e55e:48","filtered_window_id":"99dad260d07a8a25fb87e55e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/99dad260d07a8a25fb87e55e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject3/h2/0/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"99dad260d07a8a25fb87e55e:52","filtered_window_id":"99dad260d07a8a25fb87e55e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/99dad260d07a8a25fb87e55e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject3/h2/0/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"9a85d85142a6dd8289796274:0","filtered_window_id":"9a85d85142a6dd8289796274","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9a85d85142a6dd8289796274/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[608,609,610,611,612,613,614,615],"take":"subject2/h1/1/cam4","frame_ids":[608,609,610,611,612,613,614,615]} +{"filtered_tile_id":"9a85d85142a6dd8289796274:8","filtered_window_id":"9a85d85142a6dd8289796274","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9a85d85142a6dd8289796274/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[616,617,618,619,620,621,622,623],"take":"subject2/h1/1/cam4","frame_ids":[616,617,618,619,620,621,622,623]} +{"filtered_tile_id":"9a85d85142a6dd8289796274:16","filtered_window_id":"9a85d85142a6dd8289796274","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9a85d85142a6dd8289796274/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[624,625,626,627,628,629,630,631],"take":"subject2/h1/1/cam4","frame_ids":[624,625,626,627,628,629,630,631]} +{"filtered_tile_id":"9a85d85142a6dd8289796274:24","filtered_window_id":"9a85d85142a6dd8289796274","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9a85d85142a6dd8289796274/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[632,633,634,635,636,637,638,639],"take":"subject2/h1/1/cam4","frame_ids":[632,633,634,635,636,637,638,639]} +{"filtered_tile_id":"9a85d85142a6dd8289796274:32","filtered_window_id":"9a85d85142a6dd8289796274","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9a85d85142a6dd8289796274/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[640,641,642,643,644,645,646,647],"take":"subject2/h1/1/cam4","frame_ids":[640,641,642,643,644,645,646,647]} +{"filtered_tile_id":"9a85d85142a6dd8289796274:40","filtered_window_id":"9a85d85142a6dd8289796274","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9a85d85142a6dd8289796274/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[648,649,650,651,652,653,654,655],"take":"subject2/h1/1/cam4","frame_ids":[648,649,650,651,652,653,654,655]} +{"filtered_tile_id":"9a85d85142a6dd8289796274:48","filtered_window_id":"9a85d85142a6dd8289796274","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9a85d85142a6dd8289796274/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[656,657,658,659,660,661,662,663],"take":"subject2/h1/1/cam4","frame_ids":[656,657,658,659,660,661,662,663]} +{"filtered_tile_id":"9ace43868b51405a8a39b0b4:0","filtered_window_id":"9ace43868b51405a8a39b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ace43868b51405a8a39b0b4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject1/o1/1/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"9ace43868b51405a8a39b0b4:8","filtered_window_id":"9ace43868b51405a8a39b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ace43868b51405a8a39b0b4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/o1/1/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"9ace43868b51405a8a39b0b4:16","filtered_window_id":"9ace43868b51405a8a39b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ace43868b51405a8a39b0b4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject1/o1/1/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"9ace43868b51405a8a39b0b4:24","filtered_window_id":"9ace43868b51405a8a39b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ace43868b51405a8a39b0b4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject1/o1/1/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"9ace43868b51405a8a39b0b4:32","filtered_window_id":"9ace43868b51405a8a39b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ace43868b51405a8a39b0b4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[459,460,461,462,463,464,465,466],"take":"subject1/o1/1/cam4","frame_ids":[459,460,461,462,463,464,465,466]} +{"filtered_tile_id":"9ace43868b51405a8a39b0b4:40","filtered_window_id":"9ace43868b51405a8a39b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ace43868b51405a8a39b0b4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[467,468,469,470,471,472,473,474],"take":"subject1/o1/1/cam4","frame_ids":[467,468,469,470,471,472,473,474]} +{"filtered_tile_id":"9ace43868b51405a8a39b0b4:48","filtered_window_id":"9ace43868b51405a8a39b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ace43868b51405a8a39b0b4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[475,476,477,478,479,480,481,482],"take":"subject1/o1/1/cam4","frame_ids":[475,476,477,478,479,480,481,482]} +{"filtered_tile_id":"9ace43868b51405a8a39b0b4:52","filtered_window_id":"9ace43868b51405a8a39b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ace43868b51405a8a39b0b4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[479,480,481,482,483,484,485,486],"take":"subject1/o1/1/cam4","frame_ids":[479,480,481,482,483,484,485,486]} +{"filtered_tile_id":"9b7ceadecc0f77785cf33d0f:0","filtered_window_id":"9b7ceadecc0f77785cf33d0f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9b7ceadecc0f77785cf33d0f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[652,653,654,655,656,657,658,659],"take":"subject1/o2/3/cam4","frame_ids":[652,653,654,655,656,657,658,659]} +{"filtered_tile_id":"9b7ceadecc0f77785cf33d0f:8","filtered_window_id":"9b7ceadecc0f77785cf33d0f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9b7ceadecc0f77785cf33d0f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[660,661,662,663,664,665,666,667],"take":"subject1/o2/3/cam4","frame_ids":[660,661,662,663,664,665,666,667]} +{"filtered_tile_id":"9b7ceadecc0f77785cf33d0f:16","filtered_window_id":"9b7ceadecc0f77785cf33d0f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9b7ceadecc0f77785cf33d0f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[668,669,670,671,672,673,674,675],"take":"subject1/o2/3/cam4","frame_ids":[668,669,670,671,672,673,674,675]} +{"filtered_tile_id":"9b7ceadecc0f77785cf33d0f:24","filtered_window_id":"9b7ceadecc0f77785cf33d0f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9b7ceadecc0f77785cf33d0f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[676,677,678,679,680,681,682,683],"take":"subject1/o2/3/cam4","frame_ids":[676,677,678,679,680,681,682,683]} +{"filtered_tile_id":"9b7ceadecc0f77785cf33d0f:32","filtered_window_id":"9b7ceadecc0f77785cf33d0f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9b7ceadecc0f77785cf33d0f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[684,685,686,687,688,689,690,691],"take":"subject1/o2/3/cam4","frame_ids":[684,685,686,687,688,689,690,691]} +{"filtered_tile_id":"9b7ceadecc0f77785cf33d0f:40","filtered_window_id":"9b7ceadecc0f77785cf33d0f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9b7ceadecc0f77785cf33d0f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[692,693,694,695,696,697,698,699],"take":"subject1/o2/3/cam4","frame_ids":[692,693,694,695,696,697,698,699]} +{"filtered_tile_id":"9b7ceadecc0f77785cf33d0f:48","filtered_window_id":"9b7ceadecc0f77785cf33d0f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9b7ceadecc0f77785cf33d0f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[700,701,702,703,704,705,706,707],"take":"subject1/o2/3/cam4","frame_ids":[700,701,702,703,704,705,706,707]} +{"filtered_tile_id":"9b7ceadecc0f77785cf33d0f:52","filtered_window_id":"9b7ceadecc0f77785cf33d0f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9b7ceadecc0f77785cf33d0f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[704,705,706,707,708,709,710,711],"take":"subject1/o2/3/cam4","frame_ids":[704,705,706,707,708,709,710,711]} +{"filtered_tile_id":"9bac732e64dee98ad6714e6e:0","filtered_window_id":"9bac732e64dee98ad6714e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9bac732e64dee98ad6714e6e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject2/k1/1/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"9bac732e64dee98ad6714e6e:8","filtered_window_id":"9bac732e64dee98ad6714e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9bac732e64dee98ad6714e6e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject2/k1/1/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"9bac732e64dee98ad6714e6e:16","filtered_window_id":"9bac732e64dee98ad6714e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9bac732e64dee98ad6714e6e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[423,424,425,426,427,428,429,430],"take":"subject2/k1/1/cam4","frame_ids":[423,424,425,426,427,428,429,430]} +{"filtered_tile_id":"9bac732e64dee98ad6714e6e:18","filtered_window_id":"9bac732e64dee98ad6714e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9bac732e64dee98ad6714e6e/native_gt.npz","filtered_start_offset":18,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject2/k1/1/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"9cd7393ebe4ce131b2e8e1ea:0","filtered_window_id":"9cd7393ebe4ce131b2e8e1ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cd7393ebe4ce131b2e8e1ea/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject1/o2/2/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"9cd7393ebe4ce131b2e8e1ea:8","filtered_window_id":"9cd7393ebe4ce131b2e8e1ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cd7393ebe4ce131b2e8e1ea/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject1/o2/2/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"9cd7393ebe4ce131b2e8e1ea:16","filtered_window_id":"9cd7393ebe4ce131b2e8e1ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cd7393ebe4ce131b2e8e1ea/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject1/o2/2/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"9cd7393ebe4ce131b2e8e1ea:24","filtered_window_id":"9cd7393ebe4ce131b2e8e1ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cd7393ebe4ce131b2e8e1ea/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject1/o2/2/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"9cd7393ebe4ce131b2e8e1ea:32","filtered_window_id":"9cd7393ebe4ce131b2e8e1ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cd7393ebe4ce131b2e8e1ea/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject1/o2/2/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"9cd7393ebe4ce131b2e8e1ea:40","filtered_window_id":"9cd7393ebe4ce131b2e8e1ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cd7393ebe4ce131b2e8e1ea/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject1/o2/2/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"9cd7393ebe4ce131b2e8e1ea:48","filtered_window_id":"9cd7393ebe4ce131b2e8e1ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cd7393ebe4ce131b2e8e1ea/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject1/o2/2/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"9cd7393ebe4ce131b2e8e1ea:52","filtered_window_id":"9cd7393ebe4ce131b2e8e1ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cd7393ebe4ce131b2e8e1ea/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject1/o2/2/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"9ce724425809d75f39ff9a13:0","filtered_window_id":"9ce724425809d75f39ff9a13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ce724425809d75f39ff9a13/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject1/h2/4/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"9ce724425809d75f39ff9a13:8","filtered_window_id":"9ce724425809d75f39ff9a13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ce724425809d75f39ff9a13/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[219,220,221,222,223,224,225,226],"take":"subject1/h2/4/cam4","frame_ids":[219,220,221,222,223,224,225,226]} +{"filtered_tile_id":"9ce724425809d75f39ff9a13:16","filtered_window_id":"9ce724425809d75f39ff9a13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ce724425809d75f39ff9a13/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[227,228,229,230,231,232,233,234],"take":"subject1/h2/4/cam4","frame_ids":[227,228,229,230,231,232,233,234]} +{"filtered_tile_id":"9ce724425809d75f39ff9a13:24","filtered_window_id":"9ce724425809d75f39ff9a13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ce724425809d75f39ff9a13/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[235,236,237,238,239,240,241,242],"take":"subject1/h2/4/cam4","frame_ids":[235,236,237,238,239,240,241,242]} +{"filtered_tile_id":"9ce724425809d75f39ff9a13:32","filtered_window_id":"9ce724425809d75f39ff9a13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ce724425809d75f39ff9a13/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[243,244,245,246,247,248,249,250],"take":"subject1/h2/4/cam4","frame_ids":[243,244,245,246,247,248,249,250]} +{"filtered_tile_id":"9ce724425809d75f39ff9a13:40","filtered_window_id":"9ce724425809d75f39ff9a13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ce724425809d75f39ff9a13/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[251,252,253,254,255,256,257,258],"take":"subject1/h2/4/cam4","frame_ids":[251,252,253,254,255,256,257,258]} +{"filtered_tile_id":"9ce724425809d75f39ff9a13:48","filtered_window_id":"9ce724425809d75f39ff9a13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ce724425809d75f39ff9a13/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[259,260,261,262,263,264,265,266],"take":"subject1/h2/4/cam4","frame_ids":[259,260,261,262,263,264,265,266]} +{"filtered_tile_id":"9ce724425809d75f39ff9a13:52","filtered_window_id":"9ce724425809d75f39ff9a13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9ce724425809d75f39ff9a13/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject1/h2/4/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"9cfc5592c2d0a9c5e1ec8e26:0","filtered_window_id":"9cfc5592c2d0a9c5e1ec8e26","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cfc5592c2d0a9c5e1ec8e26/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject1/k1/3/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"9cfc5592c2d0a9c5e1ec8e26:8","filtered_window_id":"9cfc5592c2d0a9c5e1ec8e26","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cfc5592c2d0a9c5e1ec8e26/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject1/k1/3/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"9cfc5592c2d0a9c5e1ec8e26:16","filtered_window_id":"9cfc5592c2d0a9c5e1ec8e26","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cfc5592c2d0a9c5e1ec8e26/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[459,460,461,462,463,464,465,466],"take":"subject1/k1/3/cam4","frame_ids":[459,460,461,462,463,464,465,466]} +{"filtered_tile_id":"9cfc5592c2d0a9c5e1ec8e26:24","filtered_window_id":"9cfc5592c2d0a9c5e1ec8e26","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9cfc5592c2d0a9c5e1ec8e26/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[467,468,469,470,471,472,473,474],"take":"subject1/k1/3/cam4","frame_ids":[467,468,469,470,471,472,473,474]} +{"filtered_tile_id":"9d64beb70dd3b4220e471986:0","filtered_window_id":"9d64beb70dd3b4220e471986","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d64beb70dd3b4220e471986/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[79,80,81,82,83,84,85,86],"take":"subject1/h2/4/cam4","frame_ids":[79,80,81,82,83,84,85,86]} +{"filtered_tile_id":"9d64beb70dd3b4220e471986:8","filtered_window_id":"9d64beb70dd3b4220e471986","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d64beb70dd3b4220e471986/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[87,88,89,90,91,92,93,94],"take":"subject1/h2/4/cam4","frame_ids":[87,88,89,90,91,92,93,94]} +{"filtered_tile_id":"9d64beb70dd3b4220e471986:16","filtered_window_id":"9d64beb70dd3b4220e471986","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d64beb70dd3b4220e471986/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[95,96,97,98,99,100,101,102],"take":"subject1/h2/4/cam4","frame_ids":[95,96,97,98,99,100,101,102]} +{"filtered_tile_id":"9d64beb70dd3b4220e471986:24","filtered_window_id":"9d64beb70dd3b4220e471986","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d64beb70dd3b4220e471986/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[103,104,105,106,107,108,109,110],"take":"subject1/h2/4/cam4","frame_ids":[103,104,105,106,107,108,109,110]} +{"filtered_tile_id":"9d64beb70dd3b4220e471986:32","filtered_window_id":"9d64beb70dd3b4220e471986","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d64beb70dd3b4220e471986/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject1/h2/4/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"9d64beb70dd3b4220e471986:36","filtered_window_id":"9d64beb70dd3b4220e471986","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d64beb70dd3b4220e471986/native_gt.npz","filtered_start_offset":36,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject1/h2/4/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"9d65f82ad608abfa1966759d:0","filtered_window_id":"9d65f82ad608abfa1966759d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d65f82ad608abfa1966759d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject1/k1/5/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"9d65f82ad608abfa1966759d:8","filtered_window_id":"9d65f82ad608abfa1966759d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d65f82ad608abfa1966759d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject1/k1/5/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"9d65f82ad608abfa1966759d:16","filtered_window_id":"9d65f82ad608abfa1966759d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d65f82ad608abfa1966759d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject1/k1/5/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"9d65f82ad608abfa1966759d:24","filtered_window_id":"9d65f82ad608abfa1966759d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d65f82ad608abfa1966759d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject1/k1/5/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"9d65f82ad608abfa1966759d:32","filtered_window_id":"9d65f82ad608abfa1966759d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d65f82ad608abfa1966759d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject1/k1/5/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"9d65f82ad608abfa1966759d:40","filtered_window_id":"9d65f82ad608abfa1966759d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d65f82ad608abfa1966759d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject1/k1/5/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"9d65f82ad608abfa1966759d:48","filtered_window_id":"9d65f82ad608abfa1966759d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d65f82ad608abfa1966759d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject1/k1/5/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"9d65f82ad608abfa1966759d:52","filtered_window_id":"9d65f82ad608abfa1966759d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d65f82ad608abfa1966759d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[232,233,234,235,236,237,238,239],"take":"subject1/k1/5/cam4","frame_ids":[232,233,234,235,236,237,238,239]} +{"filtered_tile_id":"9d7f2329857b748ae9c2acff:0","filtered_window_id":"9d7f2329857b748ae9c2acff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d7f2329857b748ae9c2acff/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject3/h1/2/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"9d7f2329857b748ae9c2acff:8","filtered_window_id":"9d7f2329857b748ae9c2acff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d7f2329857b748ae9c2acff/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject3/h1/2/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"9d7f2329857b748ae9c2acff:16","filtered_window_id":"9d7f2329857b748ae9c2acff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d7f2329857b748ae9c2acff/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject3/h1/2/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"9d7f2329857b748ae9c2acff:24","filtered_window_id":"9d7f2329857b748ae9c2acff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d7f2329857b748ae9c2acff/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject3/h1/2/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"9d7f2329857b748ae9c2acff:32","filtered_window_id":"9d7f2329857b748ae9c2acff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d7f2329857b748ae9c2acff/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[354,355,356,357,358,359,360,361],"take":"subject3/h1/2/cam4","frame_ids":[354,355,356,357,358,359,360,361]} +{"filtered_tile_id":"9d7f2329857b748ae9c2acff:40","filtered_window_id":"9d7f2329857b748ae9c2acff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d7f2329857b748ae9c2acff/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject3/h1/2/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"9d7f2329857b748ae9c2acff:42","filtered_window_id":"9d7f2329857b748ae9c2acff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d7f2329857b748ae9c2acff/native_gt.npz","filtered_start_offset":42,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject3/h1/2/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"9d94f7e060bf35f66851c7b7:0","filtered_window_id":"9d94f7e060bf35f66851c7b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d94f7e060bf35f66851c7b7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/k2/6/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"9d94f7e060bf35f66851c7b7:8","filtered_window_id":"9d94f7e060bf35f66851c7b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d94f7e060bf35f66851c7b7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/k2/6/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"9d94f7e060bf35f66851c7b7:16","filtered_window_id":"9d94f7e060bf35f66851c7b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d94f7e060bf35f66851c7b7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k2/6/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"9d94f7e060bf35f66851c7b7:24","filtered_window_id":"9d94f7e060bf35f66851c7b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d94f7e060bf35f66851c7b7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k2/6/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"9d94f7e060bf35f66851c7b7:32","filtered_window_id":"9d94f7e060bf35f66851c7b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d94f7e060bf35f66851c7b7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k2/6/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"9d94f7e060bf35f66851c7b7:35","filtered_window_id":"9d94f7e060bf35f66851c7b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9d94f7e060bf35f66851c7b7/native_gt.npz","filtered_start_offset":35,"expected_frame_ids":[35,36,37,38,39,40,41,42],"take":"subject1/k2/6/cam4","frame_ids":[35,36,37,38,39,40,41,42]} +{"filtered_tile_id":"9e389f1a47567879db7c0173:0","filtered_window_id":"9e389f1a47567879db7c0173","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e389f1a47567879db7c0173/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[501,502,503,504,505,506,507,508],"take":"subject3/h2/7/cam4","frame_ids":[501,502,503,504,505,506,507,508]} +{"filtered_tile_id":"9e389f1a47567879db7c0173:8","filtered_window_id":"9e389f1a47567879db7c0173","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e389f1a47567879db7c0173/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[509,510,511,512,513,514,515,516],"take":"subject3/h2/7/cam4","frame_ids":[509,510,511,512,513,514,515,516]} +{"filtered_tile_id":"9e389f1a47567879db7c0173:16","filtered_window_id":"9e389f1a47567879db7c0173","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e389f1a47567879db7c0173/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[517,518,519,520,521,522,523,524],"take":"subject3/h2/7/cam4","frame_ids":[517,518,519,520,521,522,523,524]} +{"filtered_tile_id":"9e389f1a47567879db7c0173:24","filtered_window_id":"9e389f1a47567879db7c0173","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e389f1a47567879db7c0173/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[525,526,527,528,529,530,531,532],"take":"subject3/h2/7/cam4","frame_ids":[525,526,527,528,529,530,531,532]} +{"filtered_tile_id":"9e389f1a47567879db7c0173:32","filtered_window_id":"9e389f1a47567879db7c0173","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e389f1a47567879db7c0173/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[533,534,535,536,537,538,539,540],"take":"subject3/h2/7/cam4","frame_ids":[533,534,535,536,537,538,539,540]} +{"filtered_tile_id":"9e389f1a47567879db7c0173:40","filtered_window_id":"9e389f1a47567879db7c0173","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e389f1a47567879db7c0173/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject3/h2/7/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"9e389f1a47567879db7c0173:48","filtered_window_id":"9e389f1a47567879db7c0173","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e389f1a47567879db7c0173/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[549,550,551,552,553,554,555,556],"take":"subject3/h2/7/cam4","frame_ids":[549,550,551,552,553,554,555,556]} +{"filtered_tile_id":"9e389f1a47567879db7c0173:52","filtered_window_id":"9e389f1a47567879db7c0173","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e389f1a47567879db7c0173/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[553,554,555,556,557,558,559,560],"take":"subject3/h2/7/cam4","frame_ids":[553,554,555,556,557,558,559,560]} +{"filtered_tile_id":"9e4c058417be555f0646cefb:0","filtered_window_id":"9e4c058417be555f0646cefb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e4c058417be555f0646cefb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[65,66,67,68,69,70,71,72],"take":"subject1/k2/3/cam4","frame_ids":[65,66,67,68,69,70,71,72]} +{"filtered_tile_id":"9e4c058417be555f0646cefb:8","filtered_window_id":"9e4c058417be555f0646cefb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e4c058417be555f0646cefb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[73,74,75,76,77,78,79,80],"take":"subject1/k2/3/cam4","frame_ids":[73,74,75,76,77,78,79,80]} +{"filtered_tile_id":"9e4c058417be555f0646cefb:16","filtered_window_id":"9e4c058417be555f0646cefb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e4c058417be555f0646cefb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[81,82,83,84,85,86,87,88],"take":"subject1/k2/3/cam4","frame_ids":[81,82,83,84,85,86,87,88]} +{"filtered_tile_id":"9e4c058417be555f0646cefb:24","filtered_window_id":"9e4c058417be555f0646cefb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e4c058417be555f0646cefb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[89,90,91,92,93,94,95,96],"take":"subject1/k2/3/cam4","frame_ids":[89,90,91,92,93,94,95,96]} +{"filtered_tile_id":"9e4c058417be555f0646cefb:32","filtered_window_id":"9e4c058417be555f0646cefb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e4c058417be555f0646cefb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[97,98,99,100,101,102,103,104],"take":"subject1/k2/3/cam4","frame_ids":[97,98,99,100,101,102,103,104]} +{"filtered_tile_id":"9e4c058417be555f0646cefb:40","filtered_window_id":"9e4c058417be555f0646cefb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e4c058417be555f0646cefb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[105,106,107,108,109,110,111,112],"take":"subject1/k2/3/cam4","frame_ids":[105,106,107,108,109,110,111,112]} +{"filtered_tile_id":"9e4c058417be555f0646cefb:48","filtered_window_id":"9e4c058417be555f0646cefb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e4c058417be555f0646cefb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[113,114,115,116,117,118,119,120],"take":"subject1/k2/3/cam4","frame_ids":[113,114,115,116,117,118,119,120]} +{"filtered_tile_id":"9e4c058417be555f0646cefb:52","filtered_window_id":"9e4c058417be555f0646cefb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9e4c058417be555f0646cefb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[117,118,119,120,121,122,123,124],"take":"subject1/k2/3/cam4","frame_ids":[117,118,119,120,121,122,123,124]} +{"filtered_tile_id":"9eee876bee084164b71d0a4d:0","filtered_window_id":"9eee876bee084164b71d0a4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9eee876bee084164b71d0a4d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[290,291,292,293,294,295,296,297],"take":"subject3/k1/1/cam4","frame_ids":[290,291,292,293,294,295,296,297]} +{"filtered_tile_id":"9eee876bee084164b71d0a4d:8","filtered_window_id":"9eee876bee084164b71d0a4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9eee876bee084164b71d0a4d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject3/k1/1/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"9eee876bee084164b71d0a4d:16","filtered_window_id":"9eee876bee084164b71d0a4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9eee876bee084164b71d0a4d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[306,307,308,309,310,311,312,313],"take":"subject3/k1/1/cam4","frame_ids":[306,307,308,309,310,311,312,313]} +{"filtered_tile_id":"9eee876bee084164b71d0a4d:24","filtered_window_id":"9eee876bee084164b71d0a4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9eee876bee084164b71d0a4d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject3/k1/1/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"9eee876bee084164b71d0a4d:32","filtered_window_id":"9eee876bee084164b71d0a4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9eee876bee084164b71d0a4d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject3/k1/1/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"9eee876bee084164b71d0a4d:40","filtered_window_id":"9eee876bee084164b71d0a4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9eee876bee084164b71d0a4d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject3/k1/1/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"9eee876bee084164b71d0a4d:48","filtered_window_id":"9eee876bee084164b71d0a4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9eee876bee084164b71d0a4d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject3/k1/1/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"9eee876bee084164b71d0a4d:52","filtered_window_id":"9eee876bee084164b71d0a4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9eee876bee084164b71d0a4d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject3/k1/1/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"9f13c55015a34cf86264767f:0","filtered_window_id":"9f13c55015a34cf86264767f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f13c55015a34cf86264767f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[618,619,620,621,622,623,624,625],"take":"subject1/h2/3/cam4","frame_ids":[618,619,620,621,622,623,624,625]} +{"filtered_tile_id":"9f13c55015a34cf86264767f:8","filtered_window_id":"9f13c55015a34cf86264767f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f13c55015a34cf86264767f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[626,627,628,629,630,631,632,633],"take":"subject1/h2/3/cam4","frame_ids":[626,627,628,629,630,631,632,633]} +{"filtered_tile_id":"9f13c55015a34cf86264767f:16","filtered_window_id":"9f13c55015a34cf86264767f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f13c55015a34cf86264767f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[634,635,636,637,638,639,640,641],"take":"subject1/h2/3/cam4","frame_ids":[634,635,636,637,638,639,640,641]} +{"filtered_tile_id":"9f13c55015a34cf86264767f:24","filtered_window_id":"9f13c55015a34cf86264767f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f13c55015a34cf86264767f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[642,643,644,645,646,647,648,649],"take":"subject1/h2/3/cam4","frame_ids":[642,643,644,645,646,647,648,649]} +{"filtered_tile_id":"9f13c55015a34cf86264767f:32","filtered_window_id":"9f13c55015a34cf86264767f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f13c55015a34cf86264767f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[650,651,652,653,654,655,656,657],"take":"subject1/h2/3/cam4","frame_ids":[650,651,652,653,654,655,656,657]} +{"filtered_tile_id":"9f13c55015a34cf86264767f:40","filtered_window_id":"9f13c55015a34cf86264767f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f13c55015a34cf86264767f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[658,659,660,661,662,663,664,665],"take":"subject1/h2/3/cam4","frame_ids":[658,659,660,661,662,663,664,665]} +{"filtered_tile_id":"9f13c55015a34cf86264767f:48","filtered_window_id":"9f13c55015a34cf86264767f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f13c55015a34cf86264767f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[666,667,668,669,670,671,672,673],"take":"subject1/h2/3/cam4","frame_ids":[666,667,668,669,670,671,672,673]} +{"filtered_tile_id":"9f13c55015a34cf86264767f:52","filtered_window_id":"9f13c55015a34cf86264767f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f13c55015a34cf86264767f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[670,671,672,673,674,675,676,677],"take":"subject1/h2/3/cam4","frame_ids":[670,671,672,673,674,675,676,677]} +{"filtered_tile_id":"9f298c496c46ccf4e4e08493:0","filtered_window_id":"9f298c496c46ccf4e4e08493","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f298c496c46ccf4e4e08493/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[240,241,242,243,244,245,246,247],"take":"subject1/k1/5/cam4","frame_ids":[240,241,242,243,244,245,246,247]} +{"filtered_tile_id":"9f298c496c46ccf4e4e08493:8","filtered_window_id":"9f298c496c46ccf4e4e08493","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f298c496c46ccf4e4e08493/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject1/k1/5/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"9f298c496c46ccf4e4e08493:16","filtered_window_id":"9f298c496c46ccf4e4e08493","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f298c496c46ccf4e4e08493/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject1/k1/5/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"9f298c496c46ccf4e4e08493:24","filtered_window_id":"9f298c496c46ccf4e4e08493","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f298c496c46ccf4e4e08493/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject1/k1/5/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"9f298c496c46ccf4e4e08493:32","filtered_window_id":"9f298c496c46ccf4e4e08493","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f298c496c46ccf4e4e08493/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject1/k1/5/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"9f298c496c46ccf4e4e08493:40","filtered_window_id":"9f298c496c46ccf4e4e08493","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f298c496c46ccf4e4e08493/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject1/k1/5/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"9f298c496c46ccf4e4e08493:48","filtered_window_id":"9f298c496c46ccf4e4e08493","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f298c496c46ccf4e4e08493/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject1/k1/5/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"9f298c496c46ccf4e4e08493:52","filtered_window_id":"9f298c496c46ccf4e4e08493","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f298c496c46ccf4e4e08493/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[292,293,294,295,296,297,298,299],"take":"subject1/k1/5/cam4","frame_ids":[292,293,294,295,296,297,298,299]} +{"filtered_tile_id":"9f497a9ae2b3a265a1bc6594:0","filtered_window_id":"9f497a9ae2b3a265a1bc6594","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f497a9ae2b3a265a1bc6594/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[454,455,456,457,458,459,460,461],"take":"subject1/k1/2/cam4","frame_ids":[454,455,456,457,458,459,460,461]} +{"filtered_tile_id":"9f497a9ae2b3a265a1bc6594:8","filtered_window_id":"9f497a9ae2b3a265a1bc6594","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f497a9ae2b3a265a1bc6594/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject1/k1/2/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"9f497a9ae2b3a265a1bc6594:16","filtered_window_id":"9f497a9ae2b3a265a1bc6594","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f497a9ae2b3a265a1bc6594/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject1/k1/2/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"9f497a9ae2b3a265a1bc6594:24","filtered_window_id":"9f497a9ae2b3a265a1bc6594","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f497a9ae2b3a265a1bc6594/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject1/k1/2/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"9f497a9ae2b3a265a1bc6594:32","filtered_window_id":"9f497a9ae2b3a265a1bc6594","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f497a9ae2b3a265a1bc6594/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject1/k1/2/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"9f497a9ae2b3a265a1bc6594:40","filtered_window_id":"9f497a9ae2b3a265a1bc6594","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f497a9ae2b3a265a1bc6594/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject1/k1/2/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"9f497a9ae2b3a265a1bc6594:48","filtered_window_id":"9f497a9ae2b3a265a1bc6594","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f497a9ae2b3a265a1bc6594/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject1/k1/2/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"9f497a9ae2b3a265a1bc6594:52","filtered_window_id":"9f497a9ae2b3a265a1bc6594","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f497a9ae2b3a265a1bc6594/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[506,507,508,509,510,511,512,513],"take":"subject1/k1/2/cam4","frame_ids":[506,507,508,509,510,511,512,513]} +{"filtered_tile_id":"9f584b15ba2d3ea0a182a5bf:0","filtered_window_id":"9f584b15ba2d3ea0a182a5bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f584b15ba2d3ea0a182a5bf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[361,362,363,364,365,366,367,368],"take":"subject2/k2/2/cam4","frame_ids":[361,362,363,364,365,366,367,368]} +{"filtered_tile_id":"9f584b15ba2d3ea0a182a5bf:8","filtered_window_id":"9f584b15ba2d3ea0a182a5bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f584b15ba2d3ea0a182a5bf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[369,370,371,372,373,374,375,376],"take":"subject2/k2/2/cam4","frame_ids":[369,370,371,372,373,374,375,376]} +{"filtered_tile_id":"9f584b15ba2d3ea0a182a5bf:16","filtered_window_id":"9f584b15ba2d3ea0a182a5bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f584b15ba2d3ea0a182a5bf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[377,378,379,380,381,382,383,384],"take":"subject2/k2/2/cam4","frame_ids":[377,378,379,380,381,382,383,384]} +{"filtered_tile_id":"9f584b15ba2d3ea0a182a5bf:24","filtered_window_id":"9f584b15ba2d3ea0a182a5bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f584b15ba2d3ea0a182a5bf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[385,386,387,388,389,390,391,392],"take":"subject2/k2/2/cam4","frame_ids":[385,386,387,388,389,390,391,392]} +{"filtered_tile_id":"9f584b15ba2d3ea0a182a5bf:32","filtered_window_id":"9f584b15ba2d3ea0a182a5bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f584b15ba2d3ea0a182a5bf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[393,394,395,396,397,398,399,400],"take":"subject2/k2/2/cam4","frame_ids":[393,394,395,396,397,398,399,400]} +{"filtered_tile_id":"9f584b15ba2d3ea0a182a5bf:40","filtered_window_id":"9f584b15ba2d3ea0a182a5bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f584b15ba2d3ea0a182a5bf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[401,402,403,404,405,406,407,408],"take":"subject2/k2/2/cam4","frame_ids":[401,402,403,404,405,406,407,408]} +{"filtered_tile_id":"9f584b15ba2d3ea0a182a5bf:48","filtered_window_id":"9f584b15ba2d3ea0a182a5bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f584b15ba2d3ea0a182a5bf/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[409,410,411,412,413,414,415,416],"take":"subject2/k2/2/cam4","frame_ids":[409,410,411,412,413,414,415,416]} +{"filtered_tile_id":"9f584b15ba2d3ea0a182a5bf:52","filtered_window_id":"9f584b15ba2d3ea0a182a5bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/9f584b15ba2d3ea0a182a5bf/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[413,414,415,416,417,418,419,420],"take":"subject2/k2/2/cam4","frame_ids":[413,414,415,416,417,418,419,420]} +{"filtered_tile_id":"a00fafdff1d91390abb59ec5:0","filtered_window_id":"a00fafdff1d91390abb59ec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a00fafdff1d91390abb59ec5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[595,596,597,598,599,600,601,602],"take":"subject2/o2/1/cam4","frame_ids":[595,596,597,598,599,600,601,602]} +{"filtered_tile_id":"a00fafdff1d91390abb59ec5:8","filtered_window_id":"a00fafdff1d91390abb59ec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a00fafdff1d91390abb59ec5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[603,604,605,606,607,608,609,610],"take":"subject2/o2/1/cam4","frame_ids":[603,604,605,606,607,608,609,610]} +{"filtered_tile_id":"a00fafdff1d91390abb59ec5:16","filtered_window_id":"a00fafdff1d91390abb59ec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a00fafdff1d91390abb59ec5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[611,612,613,614,615,616,617,618],"take":"subject2/o2/1/cam4","frame_ids":[611,612,613,614,615,616,617,618]} +{"filtered_tile_id":"a00fafdff1d91390abb59ec5:19","filtered_window_id":"a00fafdff1d91390abb59ec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a00fafdff1d91390abb59ec5/native_gt.npz","filtered_start_offset":19,"expected_frame_ids":[614,615,616,617,618,619,620,621],"take":"subject2/o2/1/cam4","frame_ids":[614,615,616,617,618,619,620,621]} +{"filtered_tile_id":"a01b60a19f97f5f35b2510a3:0","filtered_window_id":"a01b60a19f97f5f35b2510a3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a01b60a19f97f5f35b2510a3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[599,600,601,602,603,604,605,606],"take":"subject3/k1/5/cam4","frame_ids":[599,600,601,602,603,604,605,606]} +{"filtered_tile_id":"a01b60a19f97f5f35b2510a3:8","filtered_window_id":"a01b60a19f97f5f35b2510a3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a01b60a19f97f5f35b2510a3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[607,608,609,610,611,612,613,614],"take":"subject3/k1/5/cam4","frame_ids":[607,608,609,610,611,612,613,614]} +{"filtered_tile_id":"a01b60a19f97f5f35b2510a3:16","filtered_window_id":"a01b60a19f97f5f35b2510a3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a01b60a19f97f5f35b2510a3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[615,616,617,618,619,620,621,622],"take":"subject3/k1/5/cam4","frame_ids":[615,616,617,618,619,620,621,622]} +{"filtered_tile_id":"a01b60a19f97f5f35b2510a3:24","filtered_window_id":"a01b60a19f97f5f35b2510a3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a01b60a19f97f5f35b2510a3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[623,624,625,626,627,628,629,630],"take":"subject3/k1/5/cam4","frame_ids":[623,624,625,626,627,628,629,630]} +{"filtered_tile_id":"a01b60a19f97f5f35b2510a3:32","filtered_window_id":"a01b60a19f97f5f35b2510a3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a01b60a19f97f5f35b2510a3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[631,632,633,634,635,636,637,638],"take":"subject3/k1/5/cam4","frame_ids":[631,632,633,634,635,636,637,638]} +{"filtered_tile_id":"a01b60a19f97f5f35b2510a3:40","filtered_window_id":"a01b60a19f97f5f35b2510a3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a01b60a19f97f5f35b2510a3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[639,640,641,642,643,644,645,646],"take":"subject3/k1/5/cam4","frame_ids":[639,640,641,642,643,644,645,646]} +{"filtered_tile_id":"a01b60a19f97f5f35b2510a3:42","filtered_window_id":"a01b60a19f97f5f35b2510a3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a01b60a19f97f5f35b2510a3/native_gt.npz","filtered_start_offset":42,"expected_frame_ids":[641,642,643,644,645,646,647,648],"take":"subject3/k1/5/cam4","frame_ids":[641,642,643,644,645,646,647,648]} +{"filtered_tile_id":"a0ec8d54ec74c3869984e3d6:0","filtered_window_id":"a0ec8d54ec74c3869984e3d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a0ec8d54ec74c3869984e3d6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject1/h2/1/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"a0ec8d54ec74c3869984e3d6:8","filtered_window_id":"a0ec8d54ec74c3869984e3d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a0ec8d54ec74c3869984e3d6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject1/h2/1/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"a0ec8d54ec74c3869984e3d6:16","filtered_window_id":"a0ec8d54ec74c3869984e3d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a0ec8d54ec74c3869984e3d6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject1/h2/1/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"a0ec8d54ec74c3869984e3d6:24","filtered_window_id":"a0ec8d54ec74c3869984e3d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a0ec8d54ec74c3869984e3d6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject1/h2/1/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"a0ec8d54ec74c3869984e3d6:32","filtered_window_id":"a0ec8d54ec74c3869984e3d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a0ec8d54ec74c3869984e3d6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject1/h2/1/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"a0ec8d54ec74c3869984e3d6:40","filtered_window_id":"a0ec8d54ec74c3869984e3d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a0ec8d54ec74c3869984e3d6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject1/h2/1/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"a0ec8d54ec74c3869984e3d6:48","filtered_window_id":"a0ec8d54ec74c3869984e3d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a0ec8d54ec74c3869984e3d6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject1/h2/1/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"a0ec8d54ec74c3869984e3d6:49","filtered_window_id":"a0ec8d54ec74c3869984e3d6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a0ec8d54ec74c3869984e3d6/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject1/h2/1/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"a1e5ae87fddd5a177b6f576b:0","filtered_window_id":"a1e5ae87fddd5a177b6f576b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e5ae87fddd5a177b6f576b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[240,241,242,243,244,245,246,247],"take":"subject1/k1/1/cam4","frame_ids":[240,241,242,243,244,245,246,247]} +{"filtered_tile_id":"a1e5ae87fddd5a177b6f576b:8","filtered_window_id":"a1e5ae87fddd5a177b6f576b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e5ae87fddd5a177b6f576b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject1/k1/1/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"a1e5ae87fddd5a177b6f576b:16","filtered_window_id":"a1e5ae87fddd5a177b6f576b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e5ae87fddd5a177b6f576b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject1/k1/1/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"a1e5ae87fddd5a177b6f576b:24","filtered_window_id":"a1e5ae87fddd5a177b6f576b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e5ae87fddd5a177b6f576b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject1/k1/1/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"a1e5ae87fddd5a177b6f576b:32","filtered_window_id":"a1e5ae87fddd5a177b6f576b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e5ae87fddd5a177b6f576b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject1/k1/1/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"a1e5ae87fddd5a177b6f576b:33","filtered_window_id":"a1e5ae87fddd5a177b6f576b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e5ae87fddd5a177b6f576b/native_gt.npz","filtered_start_offset":33,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject1/k1/1/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"a1e7eeb156810d03d59410ef:0","filtered_window_id":"a1e7eeb156810d03d59410ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e7eeb156810d03d59410ef/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject1/h1/1/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"a1e7eeb156810d03d59410ef:8","filtered_window_id":"a1e7eeb156810d03d59410ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e7eeb156810d03d59410ef/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject1/h1/1/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"a1e7eeb156810d03d59410ef:16","filtered_window_id":"a1e7eeb156810d03d59410ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e7eeb156810d03d59410ef/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject1/h1/1/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"a1e7eeb156810d03d59410ef:24","filtered_window_id":"a1e7eeb156810d03d59410ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e7eeb156810d03d59410ef/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject1/h1/1/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"a1e7eeb156810d03d59410ef:32","filtered_window_id":"a1e7eeb156810d03d59410ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e7eeb156810d03d59410ef/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject1/h1/1/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"a1e7eeb156810d03d59410ef:40","filtered_window_id":"a1e7eeb156810d03d59410ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e7eeb156810d03d59410ef/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[536,537,538,539,540,541,542,543],"take":"subject1/h1/1/cam4","frame_ids":[536,537,538,539,540,541,542,543]} +{"filtered_tile_id":"a1e7eeb156810d03d59410ef:48","filtered_window_id":"a1e7eeb156810d03d59410ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e7eeb156810d03d59410ef/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[544,545,546,547,548,549,550,551],"take":"subject1/h1/1/cam4","frame_ids":[544,545,546,547,548,549,550,551]} +{"filtered_tile_id":"a1e7eeb156810d03d59410ef:52","filtered_window_id":"a1e7eeb156810d03d59410ef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a1e7eeb156810d03d59410ef/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject1/h1/1/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"a23b081a3f481be658555f42:0","filtered_window_id":"a23b081a3f481be658555f42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a23b081a3f481be658555f42/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject1/k1/6/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"a23b081a3f481be658555f42:2","filtered_window_id":"a23b081a3f481be658555f42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a23b081a3f481be658555f42/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject1/k1/6/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"a2754e4b2ae22fb33f8f0a5a:0","filtered_window_id":"a2754e4b2ae22fb33f8f0a5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2754e4b2ae22fb33f8f0a5a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[47,48,49,50,51,52,53,54],"take":"subject3/h2/7/cam4","frame_ids":[47,48,49,50,51,52,53,54]} +{"filtered_tile_id":"a2754e4b2ae22fb33f8f0a5a:8","filtered_window_id":"a2754e4b2ae22fb33f8f0a5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2754e4b2ae22fb33f8f0a5a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[55,56,57,58,59,60,61,62],"take":"subject3/h2/7/cam4","frame_ids":[55,56,57,58,59,60,61,62]} +{"filtered_tile_id":"a2754e4b2ae22fb33f8f0a5a:16","filtered_window_id":"a2754e4b2ae22fb33f8f0a5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2754e4b2ae22fb33f8f0a5a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[63,64,65,66,67,68,69,70],"take":"subject3/h2/7/cam4","frame_ids":[63,64,65,66,67,68,69,70]} +{"filtered_tile_id":"a2754e4b2ae22fb33f8f0a5a:24","filtered_window_id":"a2754e4b2ae22fb33f8f0a5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2754e4b2ae22fb33f8f0a5a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[71,72,73,74,75,76,77,78],"take":"subject3/h2/7/cam4","frame_ids":[71,72,73,74,75,76,77,78]} +{"filtered_tile_id":"a2754e4b2ae22fb33f8f0a5a:32","filtered_window_id":"a2754e4b2ae22fb33f8f0a5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2754e4b2ae22fb33f8f0a5a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[79,80,81,82,83,84,85,86],"take":"subject3/h2/7/cam4","frame_ids":[79,80,81,82,83,84,85,86]} +{"filtered_tile_id":"a2754e4b2ae22fb33f8f0a5a:40","filtered_window_id":"a2754e4b2ae22fb33f8f0a5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2754e4b2ae22fb33f8f0a5a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[87,88,89,90,91,92,93,94],"take":"subject3/h2/7/cam4","frame_ids":[87,88,89,90,91,92,93,94]} +{"filtered_tile_id":"a2754e4b2ae22fb33f8f0a5a:48","filtered_window_id":"a2754e4b2ae22fb33f8f0a5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2754e4b2ae22fb33f8f0a5a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[95,96,97,98,99,100,101,102],"take":"subject3/h2/7/cam4","frame_ids":[95,96,97,98,99,100,101,102]} +{"filtered_tile_id":"a2754e4b2ae22fb33f8f0a5a:52","filtered_window_id":"a2754e4b2ae22fb33f8f0a5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2754e4b2ae22fb33f8f0a5a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject3/h2/7/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"a2d39b041a3e5d168eee1550:0","filtered_window_id":"a2d39b041a3e5d168eee1550","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2d39b041a3e5d168eee1550/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject1/k2/0/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"a2d39b041a3e5d168eee1550:8","filtered_window_id":"a2d39b041a3e5d168eee1550","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2d39b041a3e5d168eee1550/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject1/k2/0/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"a2d39b041a3e5d168eee1550:16","filtered_window_id":"a2d39b041a3e5d168eee1550","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2d39b041a3e5d168eee1550/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject1/k2/0/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"a2d39b041a3e5d168eee1550:24","filtered_window_id":"a2d39b041a3e5d168eee1550","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2d39b041a3e5d168eee1550/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject1/k2/0/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"a2d39b041a3e5d168eee1550:32","filtered_window_id":"a2d39b041a3e5d168eee1550","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2d39b041a3e5d168eee1550/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject1/k2/0/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"a2d39b041a3e5d168eee1550:40","filtered_window_id":"a2d39b041a3e5d168eee1550","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2d39b041a3e5d168eee1550/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject1/k2/0/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"a2d39b041a3e5d168eee1550:48","filtered_window_id":"a2d39b041a3e5d168eee1550","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2d39b041a3e5d168eee1550/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject1/k2/0/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"a2d39b041a3e5d168eee1550:52","filtered_window_id":"a2d39b041a3e5d168eee1550","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2d39b041a3e5d168eee1550/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject1/k2/0/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"a2f6e7e4fb617734f6e0d2e4:0","filtered_window_id":"a2f6e7e4fb617734f6e0d2e4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2f6e7e4fb617734f6e0d2e4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[482,483,484,485,486,487,488,489],"take":"subject2/o1/3/cam4","frame_ids":[482,483,484,485,486,487,488,489]} +{"filtered_tile_id":"a2f6e7e4fb617734f6e0d2e4:8","filtered_window_id":"a2f6e7e4fb617734f6e0d2e4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2f6e7e4fb617734f6e0d2e4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[490,491,492,493,494,495,496,497],"take":"subject2/o1/3/cam4","frame_ids":[490,491,492,493,494,495,496,497]} +{"filtered_tile_id":"a2f6e7e4fb617734f6e0d2e4:16","filtered_window_id":"a2f6e7e4fb617734f6e0d2e4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2f6e7e4fb617734f6e0d2e4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[498,499,500,501,502,503,504,505],"take":"subject2/o1/3/cam4","frame_ids":[498,499,500,501,502,503,504,505]} +{"filtered_tile_id":"a2f6e7e4fb617734f6e0d2e4:24","filtered_window_id":"a2f6e7e4fb617734f6e0d2e4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2f6e7e4fb617734f6e0d2e4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[506,507,508,509,510,511,512,513],"take":"subject2/o1/3/cam4","frame_ids":[506,507,508,509,510,511,512,513]} +{"filtered_tile_id":"a2f6e7e4fb617734f6e0d2e4:32","filtered_window_id":"a2f6e7e4fb617734f6e0d2e4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2f6e7e4fb617734f6e0d2e4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[514,515,516,517,518,519,520,521],"take":"subject2/o1/3/cam4","frame_ids":[514,515,516,517,518,519,520,521]} +{"filtered_tile_id":"a2f6e7e4fb617734f6e0d2e4:40","filtered_window_id":"a2f6e7e4fb617734f6e0d2e4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2f6e7e4fb617734f6e0d2e4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[522,523,524,525,526,527,528,529],"take":"subject2/o1/3/cam4","frame_ids":[522,523,524,525,526,527,528,529]} +{"filtered_tile_id":"a2f6e7e4fb617734f6e0d2e4:48","filtered_window_id":"a2f6e7e4fb617734f6e0d2e4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2f6e7e4fb617734f6e0d2e4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[530,531,532,533,534,535,536,537],"take":"subject2/o1/3/cam4","frame_ids":[530,531,532,533,534,535,536,537]} +{"filtered_tile_id":"a2f6e7e4fb617734f6e0d2e4:52","filtered_window_id":"a2f6e7e4fb617734f6e0d2e4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a2f6e7e4fb617734f6e0d2e4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[534,535,536,537,538,539,540,541],"take":"subject2/o1/3/cam4","frame_ids":[534,535,536,537,538,539,540,541]} +{"filtered_tile_id":"a367ffc45ced773ba8f8e4d8:0","filtered_window_id":"a367ffc45ced773ba8f8e4d8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a367ffc45ced773ba8f8e4d8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject1/o1/5/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"a367ffc45ced773ba8f8e4d8:8","filtered_window_id":"a367ffc45ced773ba8f8e4d8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a367ffc45ced773ba8f8e4d8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject1/o1/5/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"a367ffc45ced773ba8f8e4d8:16","filtered_window_id":"a367ffc45ced773ba8f8e4d8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a367ffc45ced773ba8f8e4d8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject1/o1/5/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"a367ffc45ced773ba8f8e4d8:24","filtered_window_id":"a367ffc45ced773ba8f8e4d8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a367ffc45ced773ba8f8e4d8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject1/o1/5/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"a367ffc45ced773ba8f8e4d8:32","filtered_window_id":"a367ffc45ced773ba8f8e4d8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a367ffc45ced773ba8f8e4d8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject1/o1/5/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"a367ffc45ced773ba8f8e4d8:40","filtered_window_id":"a367ffc45ced773ba8f8e4d8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a367ffc45ced773ba8f8e4d8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject1/o1/5/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"a39379ae7f10d52a4a3dc100:0","filtered_window_id":"a39379ae7f10d52a4a3dc100","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39379ae7f10d52a4a3dc100/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject2/h1/1/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"a39379ae7f10d52a4a3dc100:8","filtered_window_id":"a39379ae7f10d52a4a3dc100","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39379ae7f10d52a4a3dc100/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject2/h1/1/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"a39379ae7f10d52a4a3dc100:16","filtered_window_id":"a39379ae7f10d52a4a3dc100","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39379ae7f10d52a4a3dc100/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject2/h1/1/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"a39379ae7f10d52a4a3dc100:24","filtered_window_id":"a39379ae7f10d52a4a3dc100","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39379ae7f10d52a4a3dc100/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject2/h1/1/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"a39379ae7f10d52a4a3dc100:32","filtered_window_id":"a39379ae7f10d52a4a3dc100","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39379ae7f10d52a4a3dc100/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject2/h1/1/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"a39379ae7f10d52a4a3dc100:40","filtered_window_id":"a39379ae7f10d52a4a3dc100","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39379ae7f10d52a4a3dc100/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject2/h1/1/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"a39379ae7f10d52a4a3dc100:48","filtered_window_id":"a39379ae7f10d52a4a3dc100","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39379ae7f10d52a4a3dc100/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[536,537,538,539,540,541,542,543],"take":"subject2/h1/1/cam4","frame_ids":[536,537,538,539,540,541,542,543]} +{"filtered_tile_id":"a39379ae7f10d52a4a3dc100:52","filtered_window_id":"a39379ae7f10d52a4a3dc100","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39379ae7f10d52a4a3dc100/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[540,541,542,543,544,545,546,547],"take":"subject2/h1/1/cam4","frame_ids":[540,541,542,543,544,545,546,547]} +{"filtered_tile_id":"a39d4468548ce2f6980fe7df:0","filtered_window_id":"a39d4468548ce2f6980fe7df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39d4468548ce2f6980fe7df/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject1/k1/0/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"a39d4468548ce2f6980fe7df:8","filtered_window_id":"a39d4468548ce2f6980fe7df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39d4468548ce2f6980fe7df/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject1/k1/0/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"a39d4468548ce2f6980fe7df:16","filtered_window_id":"a39d4468548ce2f6980fe7df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39d4468548ce2f6980fe7df/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject1/k1/0/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"a39d4468548ce2f6980fe7df:24","filtered_window_id":"a39d4468548ce2f6980fe7df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39d4468548ce2f6980fe7df/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject1/k1/0/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"a39d4468548ce2f6980fe7df:32","filtered_window_id":"a39d4468548ce2f6980fe7df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39d4468548ce2f6980fe7df/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/k1/0/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"a39d4468548ce2f6980fe7df:40","filtered_window_id":"a39d4468548ce2f6980fe7df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39d4468548ce2f6980fe7df/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject1/k1/0/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"a39d4468548ce2f6980fe7df:48","filtered_window_id":"a39d4468548ce2f6980fe7df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39d4468548ce2f6980fe7df/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject1/k1/0/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"a39d4468548ce2f6980fe7df:52","filtered_window_id":"a39d4468548ce2f6980fe7df","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a39d4468548ce2f6980fe7df/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[128,129,130,131,132,133,134,135],"take":"subject1/k1/0/cam4","frame_ids":[128,129,130,131,132,133,134,135]} +{"filtered_tile_id":"a3ce1cd582f583126c4b541b:0","filtered_window_id":"a3ce1cd582f583126c4b541b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a3ce1cd582f583126c4b541b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[642,643,644,645,646,647,648,649],"take":"subject1/h1/7/cam4","frame_ids":[642,643,644,645,646,647,648,649]} +{"filtered_tile_id":"a3ce1cd582f583126c4b541b:8","filtered_window_id":"a3ce1cd582f583126c4b541b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a3ce1cd582f583126c4b541b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[650,651,652,653,654,655,656,657],"take":"subject1/h1/7/cam4","frame_ids":[650,651,652,653,654,655,656,657]} +{"filtered_tile_id":"a3ce1cd582f583126c4b541b:16","filtered_window_id":"a3ce1cd582f583126c4b541b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a3ce1cd582f583126c4b541b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[658,659,660,661,662,663,664,665],"take":"subject1/h1/7/cam4","frame_ids":[658,659,660,661,662,663,664,665]} +{"filtered_tile_id":"a3ce1cd582f583126c4b541b:24","filtered_window_id":"a3ce1cd582f583126c4b541b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a3ce1cd582f583126c4b541b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[666,667,668,669,670,671,672,673],"take":"subject1/h1/7/cam4","frame_ids":[666,667,668,669,670,671,672,673]} +{"filtered_tile_id":"a3ce1cd582f583126c4b541b:32","filtered_window_id":"a3ce1cd582f583126c4b541b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a3ce1cd582f583126c4b541b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[674,675,676,677,678,679,680,681],"take":"subject1/h1/7/cam4","frame_ids":[674,675,676,677,678,679,680,681]} +{"filtered_tile_id":"a3ce1cd582f583126c4b541b:40","filtered_window_id":"a3ce1cd582f583126c4b541b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a3ce1cd582f583126c4b541b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[682,683,684,685,686,687,688,689],"take":"subject1/h1/7/cam4","frame_ids":[682,683,684,685,686,687,688,689]} +{"filtered_tile_id":"a3ce1cd582f583126c4b541b:48","filtered_window_id":"a3ce1cd582f583126c4b541b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a3ce1cd582f583126c4b541b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[690,691,692,693,694,695,696,697],"take":"subject1/h1/7/cam4","frame_ids":[690,691,692,693,694,695,696,697]} +{"filtered_tile_id":"a3ce1cd582f583126c4b541b:52","filtered_window_id":"a3ce1cd582f583126c4b541b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a3ce1cd582f583126c4b541b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[694,695,696,697,698,699,700,701],"take":"subject1/h1/7/cam4","frame_ids":[694,695,696,697,698,699,700,701]} +{"filtered_tile_id":"a535035f832ce4d033204a63:0","filtered_window_id":"a535035f832ce4d033204a63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a535035f832ce4d033204a63/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[836,837,838,839,840,841,842,843],"take":"subject2/h1/3/cam4","frame_ids":[836,837,838,839,840,841,842,843]} +{"filtered_tile_id":"a535035f832ce4d033204a63:8","filtered_window_id":"a535035f832ce4d033204a63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a535035f832ce4d033204a63/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[844,845,846,847,848,849,850,851],"take":"subject2/h1/3/cam4","frame_ids":[844,845,846,847,848,849,850,851]} +{"filtered_tile_id":"a535035f832ce4d033204a63:16","filtered_window_id":"a535035f832ce4d033204a63","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a535035f832ce4d033204a63/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[852,853,854,855,856,857,858,859],"take":"subject2/h1/3/cam4","frame_ids":[852,853,854,855,856,857,858,859]} +{"filtered_tile_id":"a5500f888095b73504fb5bcf:0","filtered_window_id":"a5500f888095b73504fb5bcf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5500f888095b73504fb5bcf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[469,470,471,472,473,474,475,476],"take":"subject1/k2/5/cam4","frame_ids":[469,470,471,472,473,474,475,476]} +{"filtered_tile_id":"a5500f888095b73504fb5bcf:8","filtered_window_id":"a5500f888095b73504fb5bcf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5500f888095b73504fb5bcf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[477,478,479,480,481,482,483,484],"take":"subject1/k2/5/cam4","frame_ids":[477,478,479,480,481,482,483,484]} +{"filtered_tile_id":"a5500f888095b73504fb5bcf:16","filtered_window_id":"a5500f888095b73504fb5bcf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5500f888095b73504fb5bcf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[485,486,487,488,489,490,491,492],"take":"subject1/k2/5/cam4","frame_ids":[485,486,487,488,489,490,491,492]} +{"filtered_tile_id":"a5500f888095b73504fb5bcf:24","filtered_window_id":"a5500f888095b73504fb5bcf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5500f888095b73504fb5bcf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[493,494,495,496,497,498,499,500],"take":"subject1/k2/5/cam4","frame_ids":[493,494,495,496,497,498,499,500]} +{"filtered_tile_id":"a5500f888095b73504fb5bcf:32","filtered_window_id":"a5500f888095b73504fb5bcf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5500f888095b73504fb5bcf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[501,502,503,504,505,506,507,508],"take":"subject1/k2/5/cam4","frame_ids":[501,502,503,504,505,506,507,508]} +{"filtered_tile_id":"a5500f888095b73504fb5bcf:40","filtered_window_id":"a5500f888095b73504fb5bcf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5500f888095b73504fb5bcf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[509,510,511,512,513,514,515,516],"take":"subject1/k2/5/cam4","frame_ids":[509,510,511,512,513,514,515,516]} +{"filtered_tile_id":"a5500f888095b73504fb5bcf:48","filtered_window_id":"a5500f888095b73504fb5bcf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5500f888095b73504fb5bcf/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[517,518,519,520,521,522,523,524],"take":"subject1/k2/5/cam4","frame_ids":[517,518,519,520,521,522,523,524]} +{"filtered_tile_id":"a5500f888095b73504fb5bcf:52","filtered_window_id":"a5500f888095b73504fb5bcf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5500f888095b73504fb5bcf/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[521,522,523,524,525,526,527,528],"take":"subject1/k2/5/cam4","frame_ids":[521,522,523,524,525,526,527,528]} +{"filtered_tile_id":"a58ec282b2a8318f778b6feb:0","filtered_window_id":"a58ec282b2a8318f778b6feb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a58ec282b2a8318f778b6feb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/o1/0/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"a58ec282b2a8318f778b6feb:8","filtered_window_id":"a58ec282b2a8318f778b6feb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a58ec282b2a8318f778b6feb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/o1/0/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"a58ec282b2a8318f778b6feb:16","filtered_window_id":"a58ec282b2a8318f778b6feb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a58ec282b2a8318f778b6feb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/o1/0/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"a58ec282b2a8318f778b6feb:24","filtered_window_id":"a58ec282b2a8318f778b6feb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a58ec282b2a8318f778b6feb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/o1/0/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"a58ec282b2a8318f778b6feb:32","filtered_window_id":"a58ec282b2a8318f778b6feb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a58ec282b2a8318f778b6feb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/o1/0/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"a58ec282b2a8318f778b6feb:40","filtered_window_id":"a58ec282b2a8318f778b6feb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a58ec282b2a8318f778b6feb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/o1/0/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"a58ec282b2a8318f778b6feb:48","filtered_window_id":"a58ec282b2a8318f778b6feb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a58ec282b2a8318f778b6feb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[56,57,58,59,60,61,62,63],"take":"subject2/o1/0/cam4","frame_ids":[56,57,58,59,60,61,62,63]} +{"filtered_tile_id":"a58ec282b2a8318f778b6feb:52","filtered_window_id":"a58ec282b2a8318f778b6feb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a58ec282b2a8318f778b6feb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/o1/0/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"a5ab53cc92cfefe4fdefbb8c:0","filtered_window_id":"a5ab53cc92cfefe4fdefbb8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5ab53cc92cfefe4fdefbb8c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject2/k1/0/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"a5ab53cc92cfefe4fdefbb8c:8","filtered_window_id":"a5ab53cc92cfefe4fdefbb8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5ab53cc92cfefe4fdefbb8c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject2/k1/0/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"a5ab53cc92cfefe4fdefbb8c:16","filtered_window_id":"a5ab53cc92cfefe4fdefbb8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5ab53cc92cfefe4fdefbb8c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[354,355,356,357,358,359,360,361],"take":"subject2/k1/0/cam4","frame_ids":[354,355,356,357,358,359,360,361]} +{"filtered_tile_id":"a5ab53cc92cfefe4fdefbb8c:24","filtered_window_id":"a5ab53cc92cfefe4fdefbb8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5ab53cc92cfefe4fdefbb8c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject2/k1/0/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"a5ab53cc92cfefe4fdefbb8c:32","filtered_window_id":"a5ab53cc92cfefe4fdefbb8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5ab53cc92cfefe4fdefbb8c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject2/k1/0/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"a5ab53cc92cfefe4fdefbb8c:40","filtered_window_id":"a5ab53cc92cfefe4fdefbb8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5ab53cc92cfefe4fdefbb8c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject2/k1/0/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"a5ab53cc92cfefe4fdefbb8c:48","filtered_window_id":"a5ab53cc92cfefe4fdefbb8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5ab53cc92cfefe4fdefbb8c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[386,387,388,389,390,391,392,393],"take":"subject2/k1/0/cam4","frame_ids":[386,387,388,389,390,391,392,393]} +{"filtered_tile_id":"a5ab53cc92cfefe4fdefbb8c:52","filtered_window_id":"a5ab53cc92cfefe4fdefbb8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5ab53cc92cfefe4fdefbb8c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject2/k1/0/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"a5d28127c037c4c78fe63e13:0","filtered_window_id":"a5d28127c037c4c78fe63e13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5d28127c037c4c78fe63e13/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject1/h2/6/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"a5d28127c037c4c78fe63e13:8","filtered_window_id":"a5d28127c037c4c78fe63e13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5d28127c037c4c78fe63e13/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject1/h2/6/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"a5d28127c037c4c78fe63e13:16","filtered_window_id":"a5d28127c037c4c78fe63e13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5d28127c037c4c78fe63e13/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject1/h2/6/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"a5d28127c037c4c78fe63e13:24","filtered_window_id":"a5d28127c037c4c78fe63e13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5d28127c037c4c78fe63e13/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject1/h2/6/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"a5d28127c037c4c78fe63e13:32","filtered_window_id":"a5d28127c037c4c78fe63e13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5d28127c037c4c78fe63e13/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject1/h2/6/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"a5d28127c037c4c78fe63e13:40","filtered_window_id":"a5d28127c037c4c78fe63e13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5d28127c037c4c78fe63e13/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject1/h2/6/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"a5d28127c037c4c78fe63e13:48","filtered_window_id":"a5d28127c037c4c78fe63e13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5d28127c037c4c78fe63e13/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject1/h2/6/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"a5d28127c037c4c78fe63e13:52","filtered_window_id":"a5d28127c037c4c78fe63e13","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5d28127c037c4c78fe63e13/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject1/h2/6/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"a5f8a45465cd0ef63efc509a:0","filtered_window_id":"a5f8a45465cd0ef63efc509a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5f8a45465cd0ef63efc509a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject1/k1/4/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"a5f8a45465cd0ef63efc509a:8","filtered_window_id":"a5f8a45465cd0ef63efc509a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5f8a45465cd0ef63efc509a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject1/k1/4/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"a5f8a45465cd0ef63efc509a:16","filtered_window_id":"a5f8a45465cd0ef63efc509a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5f8a45465cd0ef63efc509a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject1/k1/4/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"a5f8a45465cd0ef63efc509a:24","filtered_window_id":"a5f8a45465cd0ef63efc509a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5f8a45465cd0ef63efc509a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject1/k1/4/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"a5f8a45465cd0ef63efc509a:32","filtered_window_id":"a5f8a45465cd0ef63efc509a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5f8a45465cd0ef63efc509a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject1/k1/4/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"a5f8a45465cd0ef63efc509a:40","filtered_window_id":"a5f8a45465cd0ef63efc509a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5f8a45465cd0ef63efc509a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject1/k1/4/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"a5f8a45465cd0ef63efc509a:48","filtered_window_id":"a5f8a45465cd0ef63efc509a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5f8a45465cd0ef63efc509a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[175,176,177,178,179,180,181,182],"take":"subject1/k1/4/cam4","frame_ids":[175,176,177,178,179,180,181,182]} +{"filtered_tile_id":"a5f8a45465cd0ef63efc509a:52","filtered_window_id":"a5f8a45465cd0ef63efc509a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5f8a45465cd0ef63efc509a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject1/k1/4/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"a5fbe163a2906a39390a51f3:0","filtered_window_id":"a5fbe163a2906a39390a51f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5fbe163a2906a39390a51f3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[446,447,448,449,450,451,452,453],"take":"subject1/h2/4/cam4","frame_ids":[446,447,448,449,450,451,452,453]} +{"filtered_tile_id":"a5fbe163a2906a39390a51f3:8","filtered_window_id":"a5fbe163a2906a39390a51f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5fbe163a2906a39390a51f3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[454,455,456,457,458,459,460,461],"take":"subject1/h2/4/cam4","frame_ids":[454,455,456,457,458,459,460,461]} +{"filtered_tile_id":"a5fbe163a2906a39390a51f3:16","filtered_window_id":"a5fbe163a2906a39390a51f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5fbe163a2906a39390a51f3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject1/h2/4/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"a5fbe163a2906a39390a51f3:24","filtered_window_id":"a5fbe163a2906a39390a51f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5fbe163a2906a39390a51f3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject1/h2/4/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"a5fbe163a2906a39390a51f3:32","filtered_window_id":"a5fbe163a2906a39390a51f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5fbe163a2906a39390a51f3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject1/h2/4/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"a5fbe163a2906a39390a51f3:40","filtered_window_id":"a5fbe163a2906a39390a51f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5fbe163a2906a39390a51f3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject1/h2/4/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"a5fbe163a2906a39390a51f3:48","filtered_window_id":"a5fbe163a2906a39390a51f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5fbe163a2906a39390a51f3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject1/h2/4/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"a5fbe163a2906a39390a51f3:52","filtered_window_id":"a5fbe163a2906a39390a51f3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a5fbe163a2906a39390a51f3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[498,499,500,501,502,503,504,505],"take":"subject1/h2/4/cam4","frame_ids":[498,499,500,501,502,503,504,505]} +{"filtered_tile_id":"a605828ef13e9f021569f1c7:0","filtered_window_id":"a605828ef13e9f021569f1c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a605828ef13e9f021569f1c7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o2/0/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"a605828ef13e9f021569f1c7:8","filtered_window_id":"a605828ef13e9f021569f1c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a605828ef13e9f021569f1c7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o2/0/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"a605828ef13e9f021569f1c7:16","filtered_window_id":"a605828ef13e9f021569f1c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a605828ef13e9f021569f1c7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o2/0/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"a605828ef13e9f021569f1c7:24","filtered_window_id":"a605828ef13e9f021569f1c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a605828ef13e9f021569f1c7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o2/0/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"a605828ef13e9f021569f1c7:32","filtered_window_id":"a605828ef13e9f021569f1c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a605828ef13e9f021569f1c7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o2/0/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"a605828ef13e9f021569f1c7:40","filtered_window_id":"a605828ef13e9f021569f1c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a605828ef13e9f021569f1c7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/o2/0/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"a605828ef13e9f021569f1c7:48","filtered_window_id":"a605828ef13e9f021569f1c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a605828ef13e9f021569f1c7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/o2/0/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"a605828ef13e9f021569f1c7:52","filtered_window_id":"a605828ef13e9f021569f1c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a605828ef13e9f021569f1c7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/o2/0/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"a64cf16ec74b833add9119ba:0","filtered_window_id":"a64cf16ec74b833add9119ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a64cf16ec74b833add9119ba/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject2/o1/5/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"a64cf16ec74b833add9119ba:8","filtered_window_id":"a64cf16ec74b833add9119ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a64cf16ec74b833add9119ba/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject2/o1/5/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"a64cf16ec74b833add9119ba:16","filtered_window_id":"a64cf16ec74b833add9119ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a64cf16ec74b833add9119ba/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject2/o1/5/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"a64cf16ec74b833add9119ba:24","filtered_window_id":"a64cf16ec74b833add9119ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a64cf16ec74b833add9119ba/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject2/o1/5/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"a64cf16ec74b833add9119ba:32","filtered_window_id":"a64cf16ec74b833add9119ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a64cf16ec74b833add9119ba/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[423,424,425,426,427,428,429,430],"take":"subject2/o1/5/cam4","frame_ids":[423,424,425,426,427,428,429,430]} +{"filtered_tile_id":"a64cf16ec74b833add9119ba:40","filtered_window_id":"a64cf16ec74b833add9119ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a64cf16ec74b833add9119ba/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[431,432,433,434,435,436,437,438],"take":"subject2/o1/5/cam4","frame_ids":[431,432,433,434,435,436,437,438]} +{"filtered_tile_id":"a64cf16ec74b833add9119ba:48","filtered_window_id":"a64cf16ec74b833add9119ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a64cf16ec74b833add9119ba/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[439,440,441,442,443,444,445,446],"take":"subject2/o1/5/cam4","frame_ids":[439,440,441,442,443,444,445,446]} +{"filtered_tile_id":"a64cf16ec74b833add9119ba:52","filtered_window_id":"a64cf16ec74b833add9119ba","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a64cf16ec74b833add9119ba/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject2/o1/5/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"a69616d254066102048c16f0:0","filtered_window_id":"a69616d254066102048c16f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a69616d254066102048c16f0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject3/h1/4/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"a69616d254066102048c16f0:8","filtered_window_id":"a69616d254066102048c16f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a69616d254066102048c16f0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject3/h1/4/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"a69616d254066102048c16f0:16","filtered_window_id":"a69616d254066102048c16f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a69616d254066102048c16f0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject3/h1/4/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"a69616d254066102048c16f0:24","filtered_window_id":"a69616d254066102048c16f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a69616d254066102048c16f0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject3/h1/4/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"a69616d254066102048c16f0:32","filtered_window_id":"a69616d254066102048c16f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a69616d254066102048c16f0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject3/h1/4/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"a69616d254066102048c16f0:40","filtered_window_id":"a69616d254066102048c16f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a69616d254066102048c16f0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject3/h1/4/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"a69616d254066102048c16f0:48","filtered_window_id":"a69616d254066102048c16f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a69616d254066102048c16f0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject3/h1/4/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"a69616d254066102048c16f0:52","filtered_window_id":"a69616d254066102048c16f0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a69616d254066102048c16f0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject3/h1/4/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"a701c9ff271f1604550c3a1a:0","filtered_window_id":"a701c9ff271f1604550c3a1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a701c9ff271f1604550c3a1a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[909,910,911,912,913,914,915,916],"take":"subject2/o1/1/cam4","frame_ids":[909,910,911,912,913,914,915,916]} +{"filtered_tile_id":"a701c9ff271f1604550c3a1a:8","filtered_window_id":"a701c9ff271f1604550c3a1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a701c9ff271f1604550c3a1a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[917,918,919,920,921,922,923,924],"take":"subject2/o1/1/cam4","frame_ids":[917,918,919,920,921,922,923,924]} +{"filtered_tile_id":"a701c9ff271f1604550c3a1a:14","filtered_window_id":"a701c9ff271f1604550c3a1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a701c9ff271f1604550c3a1a/native_gt.npz","filtered_start_offset":14,"expected_frame_ids":[923,924,925,926,927,928,929,930],"take":"subject2/o1/1/cam4","frame_ids":[923,924,925,926,927,928,929,930]} +{"filtered_tile_id":"a796b28dbdd6e35570cdaa79:0","filtered_window_id":"a796b28dbdd6e35570cdaa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a796b28dbdd6e35570cdaa79/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[3,4,5,6,7,8,9,10],"take":"subject3/k1/6/cam4","frame_ids":[3,4,5,6,7,8,9,10]} +{"filtered_tile_id":"a796b28dbdd6e35570cdaa79:8","filtered_window_id":"a796b28dbdd6e35570cdaa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a796b28dbdd6e35570cdaa79/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[11,12,13,14,15,16,17,18],"take":"subject3/k1/6/cam4","frame_ids":[11,12,13,14,15,16,17,18]} +{"filtered_tile_id":"a796b28dbdd6e35570cdaa79:16","filtered_window_id":"a796b28dbdd6e35570cdaa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a796b28dbdd6e35570cdaa79/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[19,20,21,22,23,24,25,26],"take":"subject3/k1/6/cam4","frame_ids":[19,20,21,22,23,24,25,26]} +{"filtered_tile_id":"a796b28dbdd6e35570cdaa79:24","filtered_window_id":"a796b28dbdd6e35570cdaa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a796b28dbdd6e35570cdaa79/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[27,28,29,30,31,32,33,34],"take":"subject3/k1/6/cam4","frame_ids":[27,28,29,30,31,32,33,34]} +{"filtered_tile_id":"a796b28dbdd6e35570cdaa79:32","filtered_window_id":"a796b28dbdd6e35570cdaa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a796b28dbdd6e35570cdaa79/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[35,36,37,38,39,40,41,42],"take":"subject3/k1/6/cam4","frame_ids":[35,36,37,38,39,40,41,42]} +{"filtered_tile_id":"a796b28dbdd6e35570cdaa79:40","filtered_window_id":"a796b28dbdd6e35570cdaa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a796b28dbdd6e35570cdaa79/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[43,44,45,46,47,48,49,50],"take":"subject3/k1/6/cam4","frame_ids":[43,44,45,46,47,48,49,50]} +{"filtered_tile_id":"a796b28dbdd6e35570cdaa79:48","filtered_window_id":"a796b28dbdd6e35570cdaa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a796b28dbdd6e35570cdaa79/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject3/k1/6/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"a796b28dbdd6e35570cdaa79:52","filtered_window_id":"a796b28dbdd6e35570cdaa79","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a796b28dbdd6e35570cdaa79/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[55,56,57,58,59,60,61,62],"take":"subject3/k1/6/cam4","frame_ids":[55,56,57,58,59,60,61,62]} +{"filtered_tile_id":"a799fdbab89cd77e2645c07a:0","filtered_window_id":"a799fdbab89cd77e2645c07a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a799fdbab89cd77e2645c07a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[527,528,529,530,531,532,533,534],"take":"subject1/o2/1/cam4","frame_ids":[527,528,529,530,531,532,533,534]} +{"filtered_tile_id":"a799fdbab89cd77e2645c07a:8","filtered_window_id":"a799fdbab89cd77e2645c07a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a799fdbab89cd77e2645c07a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[535,536,537,538,539,540,541,542],"take":"subject1/o2/1/cam4","frame_ids":[535,536,537,538,539,540,541,542]} +{"filtered_tile_id":"a799fdbab89cd77e2645c07a:16","filtered_window_id":"a799fdbab89cd77e2645c07a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a799fdbab89cd77e2645c07a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[543,544,545,546,547,548,549,550],"take":"subject1/o2/1/cam4","frame_ids":[543,544,545,546,547,548,549,550]} +{"filtered_tile_id":"a799fdbab89cd77e2645c07a:24","filtered_window_id":"a799fdbab89cd77e2645c07a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a799fdbab89cd77e2645c07a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[551,552,553,554,555,556,557,558],"take":"subject1/o2/1/cam4","frame_ids":[551,552,553,554,555,556,557,558]} +{"filtered_tile_id":"a799fdbab89cd77e2645c07a:32","filtered_window_id":"a799fdbab89cd77e2645c07a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a799fdbab89cd77e2645c07a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[559,560,561,562,563,564,565,566],"take":"subject1/o2/1/cam4","frame_ids":[559,560,561,562,563,564,565,566]} +{"filtered_tile_id":"a799fdbab89cd77e2645c07a:40","filtered_window_id":"a799fdbab89cd77e2645c07a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a799fdbab89cd77e2645c07a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[567,568,569,570,571,572,573,574],"take":"subject1/o2/1/cam4","frame_ids":[567,568,569,570,571,572,573,574]} +{"filtered_tile_id":"a799fdbab89cd77e2645c07a:48","filtered_window_id":"a799fdbab89cd77e2645c07a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a799fdbab89cd77e2645c07a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[575,576,577,578,579,580,581,582],"take":"subject1/o2/1/cam4","frame_ids":[575,576,577,578,579,580,581,582]} +{"filtered_tile_id":"a799fdbab89cd77e2645c07a:52","filtered_window_id":"a799fdbab89cd77e2645c07a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a799fdbab89cd77e2645c07a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[579,580,581,582,583,584,585,586],"take":"subject1/o2/1/cam4","frame_ids":[579,580,581,582,583,584,585,586]} +{"filtered_tile_id":"a7ace75b9f66e23785a90b32:0","filtered_window_id":"a7ace75b9f66e23785a90b32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a7ace75b9f66e23785a90b32/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[678,679,680,681,682,683,684,685],"take":"subject1/h2/3/cam4","frame_ids":[678,679,680,681,682,683,684,685]} +{"filtered_tile_id":"a7ace75b9f66e23785a90b32:8","filtered_window_id":"a7ace75b9f66e23785a90b32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a7ace75b9f66e23785a90b32/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[686,687,688,689,690,691,692,693],"take":"subject1/h2/3/cam4","frame_ids":[686,687,688,689,690,691,692,693]} +{"filtered_tile_id":"a7ace75b9f66e23785a90b32:16","filtered_window_id":"a7ace75b9f66e23785a90b32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a7ace75b9f66e23785a90b32/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[694,695,696,697,698,699,700,701],"take":"subject1/h2/3/cam4","frame_ids":[694,695,696,697,698,699,700,701]} +{"filtered_tile_id":"a7ace75b9f66e23785a90b32:24","filtered_window_id":"a7ace75b9f66e23785a90b32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a7ace75b9f66e23785a90b32/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[702,703,704,705,706,707,708,709],"take":"subject1/h2/3/cam4","frame_ids":[702,703,704,705,706,707,708,709]} +{"filtered_tile_id":"a7ace75b9f66e23785a90b32:32","filtered_window_id":"a7ace75b9f66e23785a90b32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a7ace75b9f66e23785a90b32/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[710,711,712,713,714,715,716,717],"take":"subject1/h2/3/cam4","frame_ids":[710,711,712,713,714,715,716,717]} +{"filtered_tile_id":"a7ace75b9f66e23785a90b32:40","filtered_window_id":"a7ace75b9f66e23785a90b32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a7ace75b9f66e23785a90b32/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[718,719,720,721,722,723,724,725],"take":"subject1/h2/3/cam4","frame_ids":[718,719,720,721,722,723,724,725]} +{"filtered_tile_id":"a7ace75b9f66e23785a90b32:48","filtered_window_id":"a7ace75b9f66e23785a90b32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a7ace75b9f66e23785a90b32/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[726,727,728,729,730,731,732,733],"take":"subject1/h2/3/cam4","frame_ids":[726,727,728,729,730,731,732,733]} +{"filtered_tile_id":"a7ace75b9f66e23785a90b32:52","filtered_window_id":"a7ace75b9f66e23785a90b32","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a7ace75b9f66e23785a90b32/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[730,731,732,733,734,735,736,737],"take":"subject1/h2/3/cam4","frame_ids":[730,731,732,733,734,735,736,737]} +{"filtered_tile_id":"a863d6d00254d8f164dd5815:0","filtered_window_id":"a863d6d00254d8f164dd5815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a863d6d00254d8f164dd5815/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[23,24,25,26,27,28,29,30],"take":"subject2/h1/7/cam4","frame_ids":[23,24,25,26,27,28,29,30]} +{"filtered_tile_id":"a863d6d00254d8f164dd5815:8","filtered_window_id":"a863d6d00254d8f164dd5815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a863d6d00254d8f164dd5815/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[31,32,33,34,35,36,37,38],"take":"subject2/h1/7/cam4","frame_ids":[31,32,33,34,35,36,37,38]} +{"filtered_tile_id":"a863d6d00254d8f164dd5815:16","filtered_window_id":"a863d6d00254d8f164dd5815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a863d6d00254d8f164dd5815/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[39,40,41,42,43,44,45,46],"take":"subject2/h1/7/cam4","frame_ids":[39,40,41,42,43,44,45,46]} +{"filtered_tile_id":"a863d6d00254d8f164dd5815:24","filtered_window_id":"a863d6d00254d8f164dd5815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a863d6d00254d8f164dd5815/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[47,48,49,50,51,52,53,54],"take":"subject2/h1/7/cam4","frame_ids":[47,48,49,50,51,52,53,54]} +{"filtered_tile_id":"a863d6d00254d8f164dd5815:32","filtered_window_id":"a863d6d00254d8f164dd5815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a863d6d00254d8f164dd5815/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[55,56,57,58,59,60,61,62],"take":"subject2/h1/7/cam4","frame_ids":[55,56,57,58,59,60,61,62]} +{"filtered_tile_id":"a863d6d00254d8f164dd5815:40","filtered_window_id":"a863d6d00254d8f164dd5815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a863d6d00254d8f164dd5815/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[63,64,65,66,67,68,69,70],"take":"subject2/h1/7/cam4","frame_ids":[63,64,65,66,67,68,69,70]} +{"filtered_tile_id":"a863d6d00254d8f164dd5815:48","filtered_window_id":"a863d6d00254d8f164dd5815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a863d6d00254d8f164dd5815/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[71,72,73,74,75,76,77,78],"take":"subject2/h1/7/cam4","frame_ids":[71,72,73,74,75,76,77,78]} +{"filtered_tile_id":"a863d6d00254d8f164dd5815:52","filtered_window_id":"a863d6d00254d8f164dd5815","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a863d6d00254d8f164dd5815/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject2/h1/7/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"a876202033e6925b9e49e001:0","filtered_window_id":"a876202033e6925b9e49e001","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a876202033e6925b9e49e001/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject2/h2/3/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"a876202033e6925b9e49e001:8","filtered_window_id":"a876202033e6925b9e49e001","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a876202033e6925b9e49e001/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject2/h2/3/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"a876202033e6925b9e49e001:16","filtered_window_id":"a876202033e6925b9e49e001","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a876202033e6925b9e49e001/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[255,256,257,258,259,260,261,262],"take":"subject2/h2/3/cam4","frame_ids":[255,256,257,258,259,260,261,262]} +{"filtered_tile_id":"a876202033e6925b9e49e001:24","filtered_window_id":"a876202033e6925b9e49e001","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a876202033e6925b9e49e001/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject2/h2/3/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"a876202033e6925b9e49e001:32","filtered_window_id":"a876202033e6925b9e49e001","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a876202033e6925b9e49e001/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[271,272,273,274,275,276,277,278],"take":"subject2/h2/3/cam4","frame_ids":[271,272,273,274,275,276,277,278]} +{"filtered_tile_id":"a876202033e6925b9e49e001:40","filtered_window_id":"a876202033e6925b9e49e001","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a876202033e6925b9e49e001/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[279,280,281,282,283,284,285,286],"take":"subject2/h2/3/cam4","frame_ids":[279,280,281,282,283,284,285,286]} +{"filtered_tile_id":"a876202033e6925b9e49e001:48","filtered_window_id":"a876202033e6925b9e49e001","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a876202033e6925b9e49e001/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[287,288,289,290,291,292,293,294],"take":"subject2/h2/3/cam4","frame_ids":[287,288,289,290,291,292,293,294]} +{"filtered_tile_id":"a876202033e6925b9e49e001:52","filtered_window_id":"a876202033e6925b9e49e001","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a876202033e6925b9e49e001/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[291,292,293,294,295,296,297,298],"take":"subject2/h2/3/cam4","frame_ids":[291,292,293,294,295,296,297,298]} +{"filtered_tile_id":"a8d66f4b0ea22d09468da3b3:0","filtered_window_id":"a8d66f4b0ea22d09468da3b3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8d66f4b0ea22d09468da3b3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[617,618,619,620,621,622,623,624],"take":"subject2/o1/6/cam4","frame_ids":[617,618,619,620,621,622,623,624]} +{"filtered_tile_id":"a8d66f4b0ea22d09468da3b3:8","filtered_window_id":"a8d66f4b0ea22d09468da3b3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8d66f4b0ea22d09468da3b3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[625,626,627,628,629,630,631,632],"take":"subject2/o1/6/cam4","frame_ids":[625,626,627,628,629,630,631,632]} +{"filtered_tile_id":"a8d66f4b0ea22d09468da3b3:9","filtered_window_id":"a8d66f4b0ea22d09468da3b3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8d66f4b0ea22d09468da3b3/native_gt.npz","filtered_start_offset":9,"expected_frame_ids":[626,627,628,629,630,631,632,633],"take":"subject2/o1/6/cam4","frame_ids":[626,627,628,629,630,631,632,633]} +{"filtered_tile_id":"a8dd46f5846eafbef83a9ac1:0","filtered_window_id":"a8dd46f5846eafbef83a9ac1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8dd46f5846eafbef83a9ac1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[113,114,115,116,117,118,119,120],"take":"subject2/h1/1/cam4","frame_ids":[113,114,115,116,117,118,119,120]} +{"filtered_tile_id":"a8dd46f5846eafbef83a9ac1:8","filtered_window_id":"a8dd46f5846eafbef83a9ac1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8dd46f5846eafbef83a9ac1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[121,122,123,124,125,126,127,128],"take":"subject2/h1/1/cam4","frame_ids":[121,122,123,124,125,126,127,128]} +{"filtered_tile_id":"a8dd46f5846eafbef83a9ac1:16","filtered_window_id":"a8dd46f5846eafbef83a9ac1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8dd46f5846eafbef83a9ac1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject2/h1/1/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"a8dd46f5846eafbef83a9ac1:24","filtered_window_id":"a8dd46f5846eafbef83a9ac1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8dd46f5846eafbef83a9ac1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject2/h1/1/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"a8dd46f5846eafbef83a9ac1:32","filtered_window_id":"a8dd46f5846eafbef83a9ac1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8dd46f5846eafbef83a9ac1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject2/h1/1/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"a8dd46f5846eafbef83a9ac1:40","filtered_window_id":"a8dd46f5846eafbef83a9ac1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8dd46f5846eafbef83a9ac1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject2/h1/1/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"a8dd46f5846eafbef83a9ac1:48","filtered_window_id":"a8dd46f5846eafbef83a9ac1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8dd46f5846eafbef83a9ac1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject2/h1/1/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"a8dd46f5846eafbef83a9ac1:52","filtered_window_id":"a8dd46f5846eafbef83a9ac1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a8dd46f5846eafbef83a9ac1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject2/h1/1/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"a9ea80d849a51cf9ca0df2e0:0","filtered_window_id":"a9ea80d849a51cf9ca0df2e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a9ea80d849a51cf9ca0df2e0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject2/h1/6/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"a9ea80d849a51cf9ca0df2e0:8","filtered_window_id":"a9ea80d849a51cf9ca0df2e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a9ea80d849a51cf9ca0df2e0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject2/h1/6/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"a9ea80d849a51cf9ca0df2e0:16","filtered_window_id":"a9ea80d849a51cf9ca0df2e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a9ea80d849a51cf9ca0df2e0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject2/h1/6/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"a9ea80d849a51cf9ca0df2e0:24","filtered_window_id":"a9ea80d849a51cf9ca0df2e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a9ea80d849a51cf9ca0df2e0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject2/h1/6/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"a9ea80d849a51cf9ca0df2e0:29","filtered_window_id":"a9ea80d849a51cf9ca0df2e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/a9ea80d849a51cf9ca0df2e0/native_gt.npz","filtered_start_offset":29,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject2/h1/6/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"aa11dc9d7b07b603d290114e:0","filtered_window_id":"aa11dc9d7b07b603d290114e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa11dc9d7b07b603d290114e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[348,349,350,351,352,353,354,355],"take":"subject1/h1/6/cam4","frame_ids":[348,349,350,351,352,353,354,355]} +{"filtered_tile_id":"aa11dc9d7b07b603d290114e:8","filtered_window_id":"aa11dc9d7b07b603d290114e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa11dc9d7b07b603d290114e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[356,357,358,359,360,361,362,363],"take":"subject1/h1/6/cam4","frame_ids":[356,357,358,359,360,361,362,363]} +{"filtered_tile_id":"aa11dc9d7b07b603d290114e:16","filtered_window_id":"aa11dc9d7b07b603d290114e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa11dc9d7b07b603d290114e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject1/h1/6/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"aa11dc9d7b07b603d290114e:24","filtered_window_id":"aa11dc9d7b07b603d290114e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa11dc9d7b07b603d290114e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject1/h1/6/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"aa11dc9d7b07b603d290114e:32","filtered_window_id":"aa11dc9d7b07b603d290114e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa11dc9d7b07b603d290114e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject1/h1/6/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"aa11dc9d7b07b603d290114e:40","filtered_window_id":"aa11dc9d7b07b603d290114e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa11dc9d7b07b603d290114e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject1/h1/6/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"aa11dc9d7b07b603d290114e:48","filtered_window_id":"aa11dc9d7b07b603d290114e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa11dc9d7b07b603d290114e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject1/h1/6/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"aa11dc9d7b07b603d290114e:52","filtered_window_id":"aa11dc9d7b07b603d290114e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa11dc9d7b07b603d290114e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[400,401,402,403,404,405,406,407],"take":"subject1/h1/6/cam4","frame_ids":[400,401,402,403,404,405,406,407]} +{"filtered_tile_id":"aa3099ec12c0904747691be7:0","filtered_window_id":"aa3099ec12c0904747691be7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa3099ec12c0904747691be7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject2/o2/6/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"aa3099ec12c0904747691be7:8","filtered_window_id":"aa3099ec12c0904747691be7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa3099ec12c0904747691be7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject2/o2/6/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"aa3099ec12c0904747691be7:16","filtered_window_id":"aa3099ec12c0904747691be7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa3099ec12c0904747691be7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject2/o2/6/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"aa3099ec12c0904747691be7:24","filtered_window_id":"aa3099ec12c0904747691be7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa3099ec12c0904747691be7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject2/o2/6/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"aa3099ec12c0904747691be7:32","filtered_window_id":"aa3099ec12c0904747691be7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa3099ec12c0904747691be7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject2/o2/6/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"aa3099ec12c0904747691be7:40","filtered_window_id":"aa3099ec12c0904747691be7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa3099ec12c0904747691be7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject2/o2/6/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"aa3099ec12c0904747691be7:48","filtered_window_id":"aa3099ec12c0904747691be7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa3099ec12c0904747691be7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject2/o2/6/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"aa3099ec12c0904747691be7:52","filtered_window_id":"aa3099ec12c0904747691be7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa3099ec12c0904747691be7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject2/o2/6/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"aa725519b135f1b846dea1f8:0","filtered_window_id":"aa725519b135f1b846dea1f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa725519b135f1b846dea1f8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[789,790,791,792,793,794,795,796],"take":"subject2/o1/1/cam4","frame_ids":[789,790,791,792,793,794,795,796]} +{"filtered_tile_id":"aa725519b135f1b846dea1f8:8","filtered_window_id":"aa725519b135f1b846dea1f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa725519b135f1b846dea1f8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[797,798,799,800,801,802,803,804],"take":"subject2/o1/1/cam4","frame_ids":[797,798,799,800,801,802,803,804]} +{"filtered_tile_id":"aa725519b135f1b846dea1f8:16","filtered_window_id":"aa725519b135f1b846dea1f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa725519b135f1b846dea1f8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[805,806,807,808,809,810,811,812],"take":"subject2/o1/1/cam4","frame_ids":[805,806,807,808,809,810,811,812]} +{"filtered_tile_id":"aa725519b135f1b846dea1f8:24","filtered_window_id":"aa725519b135f1b846dea1f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa725519b135f1b846dea1f8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[813,814,815,816,817,818,819,820],"take":"subject2/o1/1/cam4","frame_ids":[813,814,815,816,817,818,819,820]} +{"filtered_tile_id":"aa725519b135f1b846dea1f8:32","filtered_window_id":"aa725519b135f1b846dea1f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa725519b135f1b846dea1f8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[821,822,823,824,825,826,827,828],"take":"subject2/o1/1/cam4","frame_ids":[821,822,823,824,825,826,827,828]} +{"filtered_tile_id":"aa725519b135f1b846dea1f8:40","filtered_window_id":"aa725519b135f1b846dea1f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa725519b135f1b846dea1f8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[829,830,831,832,833,834,835,836],"take":"subject2/o1/1/cam4","frame_ids":[829,830,831,832,833,834,835,836]} +{"filtered_tile_id":"aa725519b135f1b846dea1f8:48","filtered_window_id":"aa725519b135f1b846dea1f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa725519b135f1b846dea1f8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[837,838,839,840,841,842,843,844],"take":"subject2/o1/1/cam4","frame_ids":[837,838,839,840,841,842,843,844]} +{"filtered_tile_id":"aa725519b135f1b846dea1f8:52","filtered_window_id":"aa725519b135f1b846dea1f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa725519b135f1b846dea1f8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[841,842,843,844,845,846,847,848],"take":"subject2/o1/1/cam4","frame_ids":[841,842,843,844,845,846,847,848]} +{"filtered_tile_id":"aa9bfa8cfb94abd7a5d510fe:0","filtered_window_id":"aa9bfa8cfb94abd7a5d510fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa9bfa8cfb94abd7a5d510fe/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[286,287,288,289,290,291,292,293],"take":"subject2/o1/3/cam4","frame_ids":[286,287,288,289,290,291,292,293]} +{"filtered_tile_id":"aa9bfa8cfb94abd7a5d510fe:8","filtered_window_id":"aa9bfa8cfb94abd7a5d510fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa9bfa8cfb94abd7a5d510fe/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[294,295,296,297,298,299,300,301],"take":"subject2/o1/3/cam4","frame_ids":[294,295,296,297,298,299,300,301]} +{"filtered_tile_id":"aa9bfa8cfb94abd7a5d510fe:16","filtered_window_id":"aa9bfa8cfb94abd7a5d510fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa9bfa8cfb94abd7a5d510fe/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[302,303,304,305,306,307,308,309],"take":"subject2/o1/3/cam4","frame_ids":[302,303,304,305,306,307,308,309]} +{"filtered_tile_id":"aa9bfa8cfb94abd7a5d510fe:24","filtered_window_id":"aa9bfa8cfb94abd7a5d510fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa9bfa8cfb94abd7a5d510fe/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject2/o1/3/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"aa9bfa8cfb94abd7a5d510fe:32","filtered_window_id":"aa9bfa8cfb94abd7a5d510fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa9bfa8cfb94abd7a5d510fe/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject2/o1/3/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"aa9bfa8cfb94abd7a5d510fe:40","filtered_window_id":"aa9bfa8cfb94abd7a5d510fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa9bfa8cfb94abd7a5d510fe/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject2/o1/3/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"aa9bfa8cfb94abd7a5d510fe:48","filtered_window_id":"aa9bfa8cfb94abd7a5d510fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa9bfa8cfb94abd7a5d510fe/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject2/o1/3/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"aa9bfa8cfb94abd7a5d510fe:52","filtered_window_id":"aa9bfa8cfb94abd7a5d510fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aa9bfa8cfb94abd7a5d510fe/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject2/o1/3/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"ab1e7df63fa215d843736a41:0","filtered_window_id":"ab1e7df63fa215d843736a41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab1e7df63fa215d843736a41/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[521,522,523,524,525,526,527,528],"take":"subject2/o1/1/cam4","frame_ids":[521,522,523,524,525,526,527,528]} +{"filtered_tile_id":"ab1e7df63fa215d843736a41:8","filtered_window_id":"ab1e7df63fa215d843736a41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab1e7df63fa215d843736a41/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[529,530,531,532,533,534,535,536],"take":"subject2/o1/1/cam4","frame_ids":[529,530,531,532,533,534,535,536]} +{"filtered_tile_id":"ab1e7df63fa215d843736a41:16","filtered_window_id":"ab1e7df63fa215d843736a41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab1e7df63fa215d843736a41/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[537,538,539,540,541,542,543,544],"take":"subject2/o1/1/cam4","frame_ids":[537,538,539,540,541,542,543,544]} +{"filtered_tile_id":"ab1e7df63fa215d843736a41:24","filtered_window_id":"ab1e7df63fa215d843736a41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab1e7df63fa215d843736a41/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[545,546,547,548,549,550,551,552],"take":"subject2/o1/1/cam4","frame_ids":[545,546,547,548,549,550,551,552]} +{"filtered_tile_id":"ab1e7df63fa215d843736a41:32","filtered_window_id":"ab1e7df63fa215d843736a41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab1e7df63fa215d843736a41/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[553,554,555,556,557,558,559,560],"take":"subject2/o1/1/cam4","frame_ids":[553,554,555,556,557,558,559,560]} +{"filtered_tile_id":"ab1e7df63fa215d843736a41:40","filtered_window_id":"ab1e7df63fa215d843736a41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab1e7df63fa215d843736a41/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[561,562,563,564,565,566,567,568],"take":"subject2/o1/1/cam4","frame_ids":[561,562,563,564,565,566,567,568]} +{"filtered_tile_id":"ab1e7df63fa215d843736a41:48","filtered_window_id":"ab1e7df63fa215d843736a41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab1e7df63fa215d843736a41/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[569,570,571,572,573,574,575,576],"take":"subject2/o1/1/cam4","frame_ids":[569,570,571,572,573,574,575,576]} +{"filtered_tile_id":"ab1e7df63fa215d843736a41:52","filtered_window_id":"ab1e7df63fa215d843736a41","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab1e7df63fa215d843736a41/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[573,574,575,576,577,578,579,580],"take":"subject2/o1/1/cam4","frame_ids":[573,574,575,576,577,578,579,580]} +{"filtered_tile_id":"ab89aeae768dc0566ece8851:0","filtered_window_id":"ab89aeae768dc0566ece8851","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab89aeae768dc0566ece8851/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[95,96,97,98,99,100,101,102],"take":"subject1/h1/6/cam4","frame_ids":[95,96,97,98,99,100,101,102]} +{"filtered_tile_id":"ab89aeae768dc0566ece8851:5","filtered_window_id":"ab89aeae768dc0566ece8851","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ab89aeae768dc0566ece8851/native_gt.npz","filtered_start_offset":5,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject1/h1/6/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"abca9b79c2645784c973c4dd:0","filtered_window_id":"abca9b79c2645784c973c4dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abca9b79c2645784c973c4dd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject1/h1/1/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"abca9b79c2645784c973c4dd:8","filtered_window_id":"abca9b79c2645784c973c4dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abca9b79c2645784c973c4dd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject1/h1/1/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"abca9b79c2645784c973c4dd:16","filtered_window_id":"abca9b79c2645784c973c4dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abca9b79c2645784c973c4dd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[572,573,574,575,576,577,578,579],"take":"subject1/h1/1/cam4","frame_ids":[572,573,574,575,576,577,578,579]} +{"filtered_tile_id":"abca9b79c2645784c973c4dd:24","filtered_window_id":"abca9b79c2645784c973c4dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abca9b79c2645784c973c4dd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[580,581,582,583,584,585,586,587],"take":"subject1/h1/1/cam4","frame_ids":[580,581,582,583,584,585,586,587]} +{"filtered_tile_id":"abca9b79c2645784c973c4dd:32","filtered_window_id":"abca9b79c2645784c973c4dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abca9b79c2645784c973c4dd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[588,589,590,591,592,593,594,595],"take":"subject1/h1/1/cam4","frame_ids":[588,589,590,591,592,593,594,595]} +{"filtered_tile_id":"abca9b79c2645784c973c4dd:40","filtered_window_id":"abca9b79c2645784c973c4dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abca9b79c2645784c973c4dd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[596,597,598,599,600,601,602,603],"take":"subject1/h1/1/cam4","frame_ids":[596,597,598,599,600,601,602,603]} +{"filtered_tile_id":"abca9b79c2645784c973c4dd:48","filtered_window_id":"abca9b79c2645784c973c4dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abca9b79c2645784c973c4dd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[604,605,606,607,608,609,610,611],"take":"subject1/h1/1/cam4","frame_ids":[604,605,606,607,608,609,610,611]} +{"filtered_tile_id":"abca9b79c2645784c973c4dd:52","filtered_window_id":"abca9b79c2645784c973c4dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abca9b79c2645784c973c4dd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[608,609,610,611,612,613,614,615],"take":"subject1/h1/1/cam4","frame_ids":[608,609,610,611,612,613,614,615]} +{"filtered_tile_id":"abde1f0669b8d8a4edef940f:0","filtered_window_id":"abde1f0669b8d8a4edef940f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abde1f0669b8d8a4edef940f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject1/k2/6/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"abde1f0669b8d8a4edef940f:8","filtered_window_id":"abde1f0669b8d8a4edef940f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abde1f0669b8d8a4edef940f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[170,171,172,173,174,175,176,177],"take":"subject1/k2/6/cam4","frame_ids":[170,171,172,173,174,175,176,177]} +{"filtered_tile_id":"abde1f0669b8d8a4edef940f:16","filtered_window_id":"abde1f0669b8d8a4edef940f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abde1f0669b8d8a4edef940f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[178,179,180,181,182,183,184,185],"take":"subject1/k2/6/cam4","frame_ids":[178,179,180,181,182,183,184,185]} +{"filtered_tile_id":"abde1f0669b8d8a4edef940f:24","filtered_window_id":"abde1f0669b8d8a4edef940f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abde1f0669b8d8a4edef940f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[186,187,188,189,190,191,192,193],"take":"subject1/k2/6/cam4","frame_ids":[186,187,188,189,190,191,192,193]} +{"filtered_tile_id":"abde1f0669b8d8a4edef940f:32","filtered_window_id":"abde1f0669b8d8a4edef940f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abde1f0669b8d8a4edef940f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[194,195,196,197,198,199,200,201],"take":"subject1/k2/6/cam4","frame_ids":[194,195,196,197,198,199,200,201]} +{"filtered_tile_id":"abde1f0669b8d8a4edef940f:40","filtered_window_id":"abde1f0669b8d8a4edef940f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abde1f0669b8d8a4edef940f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[202,203,204,205,206,207,208,209],"take":"subject1/k2/6/cam4","frame_ids":[202,203,204,205,206,207,208,209]} +{"filtered_tile_id":"abde1f0669b8d8a4edef940f:48","filtered_window_id":"abde1f0669b8d8a4edef940f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abde1f0669b8d8a4edef940f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[210,211,212,213,214,215,216,217],"take":"subject1/k2/6/cam4","frame_ids":[210,211,212,213,214,215,216,217]} +{"filtered_tile_id":"abde1f0669b8d8a4edef940f:52","filtered_window_id":"abde1f0669b8d8a4edef940f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abde1f0669b8d8a4edef940f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject1/k2/6/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"abdebc2066f587f1dcd8fbed:0","filtered_window_id":"abdebc2066f587f1dcd8fbed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abdebc2066f587f1dcd8fbed/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[559,560,561,562,563,564,565,566],"take":"subject2/k2/6/cam4","frame_ids":[559,560,561,562,563,564,565,566]} +{"filtered_tile_id":"abdebc2066f587f1dcd8fbed:8","filtered_window_id":"abdebc2066f587f1dcd8fbed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abdebc2066f587f1dcd8fbed/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[567,568,569,570,571,572,573,574],"take":"subject2/k2/6/cam4","frame_ids":[567,568,569,570,571,572,573,574]} +{"filtered_tile_id":"abdebc2066f587f1dcd8fbed:16","filtered_window_id":"abdebc2066f587f1dcd8fbed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abdebc2066f587f1dcd8fbed/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[575,576,577,578,579,580,581,582],"take":"subject2/k2/6/cam4","frame_ids":[575,576,577,578,579,580,581,582]} +{"filtered_tile_id":"abdebc2066f587f1dcd8fbed:24","filtered_window_id":"abdebc2066f587f1dcd8fbed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abdebc2066f587f1dcd8fbed/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[583,584,585,586,587,588,589,590],"take":"subject2/k2/6/cam4","frame_ids":[583,584,585,586,587,588,589,590]} +{"filtered_tile_id":"abdebc2066f587f1dcd8fbed:32","filtered_window_id":"abdebc2066f587f1dcd8fbed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abdebc2066f587f1dcd8fbed/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[591,592,593,594,595,596,597,598],"take":"subject2/k2/6/cam4","frame_ids":[591,592,593,594,595,596,597,598]} +{"filtered_tile_id":"abdebc2066f587f1dcd8fbed:40","filtered_window_id":"abdebc2066f587f1dcd8fbed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abdebc2066f587f1dcd8fbed/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[599,600,601,602,603,604,605,606],"take":"subject2/k2/6/cam4","frame_ids":[599,600,601,602,603,604,605,606]} +{"filtered_tile_id":"abdebc2066f587f1dcd8fbed:48","filtered_window_id":"abdebc2066f587f1dcd8fbed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abdebc2066f587f1dcd8fbed/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[607,608,609,610,611,612,613,614],"take":"subject2/k2/6/cam4","frame_ids":[607,608,609,610,611,612,613,614]} +{"filtered_tile_id":"abdebc2066f587f1dcd8fbed:52","filtered_window_id":"abdebc2066f587f1dcd8fbed","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abdebc2066f587f1dcd8fbed/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[611,612,613,614,615,616,617,618],"take":"subject2/k2/6/cam4","frame_ids":[611,612,613,614,615,616,617,618]} +{"filtered_tile_id":"abfbcd168119708c0326c92d:0","filtered_window_id":"abfbcd168119708c0326c92d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abfbcd168119708c0326c92d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[619,620,621,622,623,624,625,626],"take":"subject3/k1/3/cam4","frame_ids":[619,620,621,622,623,624,625,626]} +{"filtered_tile_id":"abfbcd168119708c0326c92d:8","filtered_window_id":"abfbcd168119708c0326c92d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abfbcd168119708c0326c92d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[627,628,629,630,631,632,633,634],"take":"subject3/k1/3/cam4","frame_ids":[627,628,629,630,631,632,633,634]} +{"filtered_tile_id":"abfbcd168119708c0326c92d:16","filtered_window_id":"abfbcd168119708c0326c92d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abfbcd168119708c0326c92d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[635,636,637,638,639,640,641,642],"take":"subject3/k1/3/cam4","frame_ids":[635,636,637,638,639,640,641,642]} +{"filtered_tile_id":"abfbcd168119708c0326c92d:24","filtered_window_id":"abfbcd168119708c0326c92d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abfbcd168119708c0326c92d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[643,644,645,646,647,648,649,650],"take":"subject3/k1/3/cam4","frame_ids":[643,644,645,646,647,648,649,650]} +{"filtered_tile_id":"abfbcd168119708c0326c92d:32","filtered_window_id":"abfbcd168119708c0326c92d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abfbcd168119708c0326c92d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[651,652,653,654,655,656,657,658],"take":"subject3/k1/3/cam4","frame_ids":[651,652,653,654,655,656,657,658]} +{"filtered_tile_id":"abfbcd168119708c0326c92d:40","filtered_window_id":"abfbcd168119708c0326c92d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abfbcd168119708c0326c92d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[659,660,661,662,663,664,665,666],"take":"subject3/k1/3/cam4","frame_ids":[659,660,661,662,663,664,665,666]} +{"filtered_tile_id":"abfbcd168119708c0326c92d:48","filtered_window_id":"abfbcd168119708c0326c92d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abfbcd168119708c0326c92d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[667,668,669,670,671,672,673,674],"take":"subject3/k1/3/cam4","frame_ids":[667,668,669,670,671,672,673,674]} +{"filtered_tile_id":"abfbcd168119708c0326c92d:52","filtered_window_id":"abfbcd168119708c0326c92d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/abfbcd168119708c0326c92d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[671,672,673,674,675,676,677,678],"take":"subject3/k1/3/cam4","frame_ids":[671,672,673,674,675,676,677,678]} +{"filtered_tile_id":"ac11ed26496fb5c6d33685c2:0","filtered_window_id":"ac11ed26496fb5c6d33685c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac11ed26496fb5c6d33685c2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[72,73,74,75,76,77,78,79],"take":"subject3/h2/2/cam4","frame_ids":[72,73,74,75,76,77,78,79]} +{"filtered_tile_id":"ac11ed26496fb5c6d33685c2:4","filtered_window_id":"ac11ed26496fb5c6d33685c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac11ed26496fb5c6d33685c2/native_gt.npz","filtered_start_offset":4,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject3/h2/2/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"ac53a1b0a8d62d8f26590828:0","filtered_window_id":"ac53a1b0a8d62d8f26590828","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac53a1b0a8d62d8f26590828/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject1/o2/1/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"ac53a1b0a8d62d8f26590828:8","filtered_window_id":"ac53a1b0a8d62d8f26590828","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac53a1b0a8d62d8f26590828/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject1/o2/1/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"ac53a1b0a8d62d8f26590828:16","filtered_window_id":"ac53a1b0a8d62d8f26590828","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac53a1b0a8d62d8f26590828/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject1/o2/1/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"ac53a1b0a8d62d8f26590828:24","filtered_window_id":"ac53a1b0a8d62d8f26590828","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac53a1b0a8d62d8f26590828/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject1/o2/1/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"ac53a1b0a8d62d8f26590828:32","filtered_window_id":"ac53a1b0a8d62d8f26590828","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac53a1b0a8d62d8f26590828/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject1/o2/1/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"ac53a1b0a8d62d8f26590828:40","filtered_window_id":"ac53a1b0a8d62d8f26590828","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac53a1b0a8d62d8f26590828/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject1/o2/1/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"ac53a1b0a8d62d8f26590828:44","filtered_window_id":"ac53a1b0a8d62d8f26590828","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac53a1b0a8d62d8f26590828/native_gt.npz","filtered_start_offset":44,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject1/o2/1/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"ac7c9ff49bd677e92dcea604:0","filtered_window_id":"ac7c9ff49bd677e92dcea604","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac7c9ff49bd677e92dcea604/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject3/h1/6/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"ac7c9ff49bd677e92dcea604:8","filtered_window_id":"ac7c9ff49bd677e92dcea604","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac7c9ff49bd677e92dcea604/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject3/h1/6/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"ac7c9ff49bd677e92dcea604:16","filtered_window_id":"ac7c9ff49bd677e92dcea604","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac7c9ff49bd677e92dcea604/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject3/h1/6/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"ac7c9ff49bd677e92dcea604:24","filtered_window_id":"ac7c9ff49bd677e92dcea604","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac7c9ff49bd677e92dcea604/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject3/h1/6/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"ac7c9ff49bd677e92dcea604:32","filtered_window_id":"ac7c9ff49bd677e92dcea604","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac7c9ff49bd677e92dcea604/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject3/h1/6/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"ac7c9ff49bd677e92dcea604:40","filtered_window_id":"ac7c9ff49bd677e92dcea604","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac7c9ff49bd677e92dcea604/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject3/h1/6/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"ac7c9ff49bd677e92dcea604:48","filtered_window_id":"ac7c9ff49bd677e92dcea604","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac7c9ff49bd677e92dcea604/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject3/h1/6/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"ac7c9ff49bd677e92dcea604:52","filtered_window_id":"ac7c9ff49bd677e92dcea604","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ac7c9ff49bd677e92dcea604/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject3/h1/6/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"ad02146a1c4673eb7577f418:0","filtered_window_id":"ad02146a1c4673eb7577f418","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ad02146a1c4673eb7577f418/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject3/h1/3/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"ad02146a1c4673eb7577f418:8","filtered_window_id":"ad02146a1c4673eb7577f418","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ad02146a1c4673eb7577f418/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject3/h1/3/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"ad02146a1c4673eb7577f418:16","filtered_window_id":"ad02146a1c4673eb7577f418","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ad02146a1c4673eb7577f418/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject3/h1/3/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"ad02146a1c4673eb7577f418:24","filtered_window_id":"ad02146a1c4673eb7577f418","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ad02146a1c4673eb7577f418/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject3/h1/3/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"ad02146a1c4673eb7577f418:32","filtered_window_id":"ad02146a1c4673eb7577f418","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ad02146a1c4673eb7577f418/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[468,469,470,471,472,473,474,475],"take":"subject3/h1/3/cam4","frame_ids":[468,469,470,471,472,473,474,475]} +{"filtered_tile_id":"ad02146a1c4673eb7577f418:40","filtered_window_id":"ad02146a1c4673eb7577f418","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ad02146a1c4673eb7577f418/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[476,477,478,479,480,481,482,483],"take":"subject3/h1/3/cam4","frame_ids":[476,477,478,479,480,481,482,483]} +{"filtered_tile_id":"ad02146a1c4673eb7577f418:48","filtered_window_id":"ad02146a1c4673eb7577f418","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ad02146a1c4673eb7577f418/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[484,485,486,487,488,489,490,491],"take":"subject3/h1/3/cam4","frame_ids":[484,485,486,487,488,489,490,491]} +{"filtered_tile_id":"ad02146a1c4673eb7577f418:52","filtered_window_id":"ad02146a1c4673eb7577f418","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ad02146a1c4673eb7577f418/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject3/h1/3/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"ade708970d835f46926939ad:0","filtered_window_id":"ade708970d835f46926939ad","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ade708970d835f46926939ad/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/k2/3/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"ade708970d835f46926939ad:8","filtered_window_id":"ade708970d835f46926939ad","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ade708970d835f46926939ad/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/k2/3/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"ade708970d835f46926939ad:16","filtered_window_id":"ade708970d835f46926939ad","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ade708970d835f46926939ad/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k2/3/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"ade708970d835f46926939ad:24","filtered_window_id":"ade708970d835f46926939ad","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ade708970d835f46926939ad/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k2/3/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"ade708970d835f46926939ad:32","filtered_window_id":"ade708970d835f46926939ad","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ade708970d835f46926939ad/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k2/3/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"ade708970d835f46926939ad:40","filtered_window_id":"ade708970d835f46926939ad","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ade708970d835f46926939ad/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/k2/3/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"ade708970d835f46926939ad:48","filtered_window_id":"ade708970d835f46926939ad","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ade708970d835f46926939ad/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/k2/3/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"ade708970d835f46926939ad:49","filtered_window_id":"ade708970d835f46926939ad","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ade708970d835f46926939ad/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[49,50,51,52,53,54,55,56],"take":"subject1/k2/3/cam4","frame_ids":[49,50,51,52,53,54,55,56]} +{"filtered_tile_id":"adf778f0c4ef637204623d65:0","filtered_window_id":"adf778f0c4ef637204623d65","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adf778f0c4ef637204623d65/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[421,422,423,424,425,426,427,428],"take":"subject2/k2/2/cam4","frame_ids":[421,422,423,424,425,426,427,428]} +{"filtered_tile_id":"adf778f0c4ef637204623d65:8","filtered_window_id":"adf778f0c4ef637204623d65","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adf778f0c4ef637204623d65/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[429,430,431,432,433,434,435,436],"take":"subject2/k2/2/cam4","frame_ids":[429,430,431,432,433,434,435,436]} +{"filtered_tile_id":"adf778f0c4ef637204623d65:16","filtered_window_id":"adf778f0c4ef637204623d65","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adf778f0c4ef637204623d65/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[437,438,439,440,441,442,443,444],"take":"subject2/k2/2/cam4","frame_ids":[437,438,439,440,441,442,443,444]} +{"filtered_tile_id":"adf778f0c4ef637204623d65:24","filtered_window_id":"adf778f0c4ef637204623d65","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adf778f0c4ef637204623d65/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[445,446,447,448,449,450,451,452],"take":"subject2/k2/2/cam4","frame_ids":[445,446,447,448,449,450,451,452]} +{"filtered_tile_id":"adf778f0c4ef637204623d65:32","filtered_window_id":"adf778f0c4ef637204623d65","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adf778f0c4ef637204623d65/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[453,454,455,456,457,458,459,460],"take":"subject2/k2/2/cam4","frame_ids":[453,454,455,456,457,458,459,460]} +{"filtered_tile_id":"adf778f0c4ef637204623d65:40","filtered_window_id":"adf778f0c4ef637204623d65","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adf778f0c4ef637204623d65/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[461,462,463,464,465,466,467,468],"take":"subject2/k2/2/cam4","frame_ids":[461,462,463,464,465,466,467,468]} +{"filtered_tile_id":"adf778f0c4ef637204623d65:48","filtered_window_id":"adf778f0c4ef637204623d65","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adf778f0c4ef637204623d65/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[469,470,471,472,473,474,475,476],"take":"subject2/k2/2/cam4","frame_ids":[469,470,471,472,473,474,475,476]} +{"filtered_tile_id":"adf778f0c4ef637204623d65:52","filtered_window_id":"adf778f0c4ef637204623d65","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adf778f0c4ef637204623d65/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject2/k2/2/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"adfa6fa7f23ce3a73c4f6e2b:0","filtered_window_id":"adfa6fa7f23ce3a73c4f6e2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adfa6fa7f23ce3a73c4f6e2b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject1/o2/6/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"adfa6fa7f23ce3a73c4f6e2b:8","filtered_window_id":"adfa6fa7f23ce3a73c4f6e2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adfa6fa7f23ce3a73c4f6e2b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject1/o2/6/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"adfa6fa7f23ce3a73c4f6e2b:16","filtered_window_id":"adfa6fa7f23ce3a73c4f6e2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adfa6fa7f23ce3a73c4f6e2b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject1/o2/6/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"adfa6fa7f23ce3a73c4f6e2b:24","filtered_window_id":"adfa6fa7f23ce3a73c4f6e2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adfa6fa7f23ce3a73c4f6e2b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject1/o2/6/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"adfa6fa7f23ce3a73c4f6e2b:31","filtered_window_id":"adfa6fa7f23ce3a73c4f6e2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/adfa6fa7f23ce3a73c4f6e2b/native_gt.npz","filtered_start_offset":31,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject1/o2/6/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"ae6cff85f651f99a7cd76666:0","filtered_window_id":"ae6cff85f651f99a7cd76666","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae6cff85f651f99a7cd76666/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[658,659,660,661,662,663,664,665],"take":"subject1/o1/7/cam4","frame_ids":[658,659,660,661,662,663,664,665]} +{"filtered_tile_id":"ae6cff85f651f99a7cd76666:8","filtered_window_id":"ae6cff85f651f99a7cd76666","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae6cff85f651f99a7cd76666/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[666,667,668,669,670,671,672,673],"take":"subject1/o1/7/cam4","frame_ids":[666,667,668,669,670,671,672,673]} +{"filtered_tile_id":"ae6cff85f651f99a7cd76666:16","filtered_window_id":"ae6cff85f651f99a7cd76666","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae6cff85f651f99a7cd76666/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[674,675,676,677,678,679,680,681],"take":"subject1/o1/7/cam4","frame_ids":[674,675,676,677,678,679,680,681]} +{"filtered_tile_id":"ae6cff85f651f99a7cd76666:24","filtered_window_id":"ae6cff85f651f99a7cd76666","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae6cff85f651f99a7cd76666/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[682,683,684,685,686,687,688,689],"take":"subject1/o1/7/cam4","frame_ids":[682,683,684,685,686,687,688,689]} +{"filtered_tile_id":"ae6cff85f651f99a7cd76666:32","filtered_window_id":"ae6cff85f651f99a7cd76666","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae6cff85f651f99a7cd76666/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[690,691,692,693,694,695,696,697],"take":"subject1/o1/7/cam4","frame_ids":[690,691,692,693,694,695,696,697]} +{"filtered_tile_id":"ae6cff85f651f99a7cd76666:40","filtered_window_id":"ae6cff85f651f99a7cd76666","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae6cff85f651f99a7cd76666/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[698,699,700,701,702,703,704,705],"take":"subject1/o1/7/cam4","frame_ids":[698,699,700,701,702,703,704,705]} +{"filtered_tile_id":"ae6cff85f651f99a7cd76666:48","filtered_window_id":"ae6cff85f651f99a7cd76666","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae6cff85f651f99a7cd76666/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[706,707,708,709,710,711,712,713],"take":"subject1/o1/7/cam4","frame_ids":[706,707,708,709,710,711,712,713]} +{"filtered_tile_id":"ae6cff85f651f99a7cd76666:52","filtered_window_id":"ae6cff85f651f99a7cd76666","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae6cff85f651f99a7cd76666/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[710,711,712,713,714,715,716,717],"take":"subject1/o1/7/cam4","frame_ids":[710,711,712,713,714,715,716,717]} +{"filtered_tile_id":"ae798988e9e4b71aca7a9f03:0","filtered_window_id":"ae798988e9e4b71aca7a9f03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae798988e9e4b71aca7a9f03/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[70,71,72,73,74,75,76,77],"take":"subject2/h2/3/cam4","frame_ids":[70,71,72,73,74,75,76,77]} +{"filtered_tile_id":"ae798988e9e4b71aca7a9f03:8","filtered_window_id":"ae798988e9e4b71aca7a9f03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae798988e9e4b71aca7a9f03/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject2/h2/3/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"ae798988e9e4b71aca7a9f03:11","filtered_window_id":"ae798988e9e4b71aca7a9f03","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae798988e9e4b71aca7a9f03/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[81,82,83,84,85,86,87,88],"take":"subject2/h2/3/cam4","frame_ids":[81,82,83,84,85,86,87,88]} +{"filtered_tile_id":"ae8d9a23e2202ab7be2b44d5:0","filtered_window_id":"ae8d9a23e2202ab7be2b44d5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae8d9a23e2202ab7be2b44d5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[192,193,194,195,196,197,198,199],"take":"subject1/h2/2/cam4","frame_ids":[192,193,194,195,196,197,198,199]} +{"filtered_tile_id":"ae8d9a23e2202ab7be2b44d5:8","filtered_window_id":"ae8d9a23e2202ab7be2b44d5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae8d9a23e2202ab7be2b44d5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[200,201,202,203,204,205,206,207],"take":"subject1/h2/2/cam4","frame_ids":[200,201,202,203,204,205,206,207]} +{"filtered_tile_id":"ae8d9a23e2202ab7be2b44d5:16","filtered_window_id":"ae8d9a23e2202ab7be2b44d5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae8d9a23e2202ab7be2b44d5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[208,209,210,211,212,213,214,215],"take":"subject1/h2/2/cam4","frame_ids":[208,209,210,211,212,213,214,215]} +{"filtered_tile_id":"ae8d9a23e2202ab7be2b44d5:24","filtered_window_id":"ae8d9a23e2202ab7be2b44d5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae8d9a23e2202ab7be2b44d5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[216,217,218,219,220,221,222,223],"take":"subject1/h2/2/cam4","frame_ids":[216,217,218,219,220,221,222,223]} +{"filtered_tile_id":"ae8d9a23e2202ab7be2b44d5:26","filtered_window_id":"ae8d9a23e2202ab7be2b44d5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ae8d9a23e2202ab7be2b44d5/native_gt.npz","filtered_start_offset":26,"expected_frame_ids":[218,219,220,221,222,223,224,225],"take":"subject1/h2/2/cam4","frame_ids":[218,219,220,221,222,223,224,225]} +{"filtered_tile_id":"aeb46d06b8daf58ceac590ea:0","filtered_window_id":"aeb46d06b8daf58ceac590ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aeb46d06b8daf58ceac590ea/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[700,701,702,703,704,705,706,707],"take":"subject3/k1/3/cam4","frame_ids":[700,701,702,703,704,705,706,707]} +{"filtered_tile_id":"aeb46d06b8daf58ceac590ea:3","filtered_window_id":"aeb46d06b8daf58ceac590ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aeb46d06b8daf58ceac590ea/native_gt.npz","filtered_start_offset":3,"expected_frame_ids":[703,704,705,706,707,708,709,710],"take":"subject3/k1/3/cam4","frame_ids":[703,704,705,706,707,708,709,710]} +{"filtered_tile_id":"aed3bc9abc808be128ef025d:0","filtered_window_id":"aed3bc9abc808be128ef025d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aed3bc9abc808be128ef025d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[678,679,680,681,682,683,684,685],"take":"subject2/h2/6/cam4","frame_ids":[678,679,680,681,682,683,684,685]} +{"filtered_tile_id":"aed3bc9abc808be128ef025d:8","filtered_window_id":"aed3bc9abc808be128ef025d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aed3bc9abc808be128ef025d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[686,687,688,689,690,691,692,693],"take":"subject2/h2/6/cam4","frame_ids":[686,687,688,689,690,691,692,693]} +{"filtered_tile_id":"aed3bc9abc808be128ef025d:16","filtered_window_id":"aed3bc9abc808be128ef025d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aed3bc9abc808be128ef025d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[694,695,696,697,698,699,700,701],"take":"subject2/h2/6/cam4","frame_ids":[694,695,696,697,698,699,700,701]} +{"filtered_tile_id":"aed3bc9abc808be128ef025d:24","filtered_window_id":"aed3bc9abc808be128ef025d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aed3bc9abc808be128ef025d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[702,703,704,705,706,707,708,709],"take":"subject2/h2/6/cam4","frame_ids":[702,703,704,705,706,707,708,709]} +{"filtered_tile_id":"aed3bc9abc808be128ef025d:32","filtered_window_id":"aed3bc9abc808be128ef025d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aed3bc9abc808be128ef025d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[710,711,712,713,714,715,716,717],"take":"subject2/h2/6/cam4","frame_ids":[710,711,712,713,714,715,716,717]} +{"filtered_tile_id":"aed3bc9abc808be128ef025d:40","filtered_window_id":"aed3bc9abc808be128ef025d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aed3bc9abc808be128ef025d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[718,719,720,721,722,723,724,725],"take":"subject2/h2/6/cam4","frame_ids":[718,719,720,721,722,723,724,725]} +{"filtered_tile_id":"aed3bc9abc808be128ef025d:48","filtered_window_id":"aed3bc9abc808be128ef025d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aed3bc9abc808be128ef025d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[726,727,728,729,730,731,732,733],"take":"subject2/h2/6/cam4","frame_ids":[726,727,728,729,730,731,732,733]} +{"filtered_tile_id":"aed3bc9abc808be128ef025d:52","filtered_window_id":"aed3bc9abc808be128ef025d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aed3bc9abc808be128ef025d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[730,731,732,733,734,735,736,737],"take":"subject2/h2/6/cam4","frame_ids":[730,731,732,733,734,735,736,737]} +{"filtered_tile_id":"aeea82dd7fa506e61d94ac9e:0","filtered_window_id":"aeea82dd7fa506e61d94ac9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aeea82dd7fa506e61d94ac9e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[616,617,618,619,620,621,622,623],"take":"subject1/h1/1/cam4","frame_ids":[616,617,618,619,620,621,622,623]} +{"filtered_tile_id":"aeea82dd7fa506e61d94ac9e:2","filtered_window_id":"aeea82dd7fa506e61d94ac9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/aeea82dd7fa506e61d94ac9e/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[618,619,620,621,622,623,624,625],"take":"subject1/h1/1/cam4","frame_ids":[618,619,620,621,622,623,624,625]} +{"filtered_tile_id":"af137e7912f743f1960123fd:0","filtered_window_id":"af137e7912f743f1960123fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af137e7912f743f1960123fd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject1/h2/3/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"af137e7912f743f1960123fd:8","filtered_window_id":"af137e7912f743f1960123fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af137e7912f743f1960123fd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject1/h2/3/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"af137e7912f743f1960123fd:16","filtered_window_id":"af137e7912f743f1960123fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af137e7912f743f1960123fd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject1/h2/3/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"af137e7912f743f1960123fd:24","filtered_window_id":"af137e7912f743f1960123fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af137e7912f743f1960123fd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject1/h2/3/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"af137e7912f743f1960123fd:32","filtered_window_id":"af137e7912f743f1960123fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af137e7912f743f1960123fd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject1/h2/3/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"af137e7912f743f1960123fd:40","filtered_window_id":"af137e7912f743f1960123fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af137e7912f743f1960123fd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[274,275,276,277,278,279,280,281],"take":"subject1/h2/3/cam4","frame_ids":[274,275,276,277,278,279,280,281]} +{"filtered_tile_id":"af137e7912f743f1960123fd:48","filtered_window_id":"af137e7912f743f1960123fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af137e7912f743f1960123fd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject1/h2/3/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"af137e7912f743f1960123fd:52","filtered_window_id":"af137e7912f743f1960123fd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af137e7912f743f1960123fd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[286,287,288,289,290,291,292,293],"take":"subject1/h2/3/cam4","frame_ids":[286,287,288,289,290,291,292,293]} +{"filtered_tile_id":"af19e9ebbaaba08b3ea7ebae:0","filtered_window_id":"af19e9ebbaaba08b3ea7ebae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af19e9ebbaaba08b3ea7ebae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject2/k2/0/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"af19e9ebbaaba08b3ea7ebae:8","filtered_window_id":"af19e9ebbaaba08b3ea7ebae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af19e9ebbaaba08b3ea7ebae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject2/k2/0/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"af19e9ebbaaba08b3ea7ebae:16","filtered_window_id":"af19e9ebbaaba08b3ea7ebae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af19e9ebbaaba08b3ea7ebae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject2/k2/0/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"af19e9ebbaaba08b3ea7ebae:24","filtered_window_id":"af19e9ebbaaba08b3ea7ebae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af19e9ebbaaba08b3ea7ebae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject2/k2/0/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"af19e9ebbaaba08b3ea7ebae:32","filtered_window_id":"af19e9ebbaaba08b3ea7ebae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af19e9ebbaaba08b3ea7ebae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject2/k2/0/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"af19e9ebbaaba08b3ea7ebae:40","filtered_window_id":"af19e9ebbaaba08b3ea7ebae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af19e9ebbaaba08b3ea7ebae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject2/k2/0/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"af19e9ebbaaba08b3ea7ebae:48","filtered_window_id":"af19e9ebbaaba08b3ea7ebae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af19e9ebbaaba08b3ea7ebae/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject2/k2/0/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"af19e9ebbaaba08b3ea7ebae:52","filtered_window_id":"af19e9ebbaaba08b3ea7ebae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/af19e9ebbaaba08b3ea7ebae/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[464,465,466,467,468,469,470,471],"take":"subject2/k2/0/cam4","frame_ids":[464,465,466,467,468,469,470,471]} +{"filtered_tile_id":"b0340ab75803883dda7290b9:0","filtered_window_id":"b0340ab75803883dda7290b9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0340ab75803883dda7290b9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject1/h1/4/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"b0340ab75803883dda7290b9:8","filtered_window_id":"b0340ab75803883dda7290b9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0340ab75803883dda7290b9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject1/h1/4/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"b0340ab75803883dda7290b9:16","filtered_window_id":"b0340ab75803883dda7290b9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0340ab75803883dda7290b9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject1/h1/4/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"b0340ab75803883dda7290b9:21","filtered_window_id":"b0340ab75803883dda7290b9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0340ab75803883dda7290b9/native_gt.npz","filtered_start_offset":21,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject1/h1/4/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"b04da484b673692fbb8b406b:0","filtered_window_id":"b04da484b673692fbb8b406b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b04da484b673692fbb8b406b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[21,22,23,24,25,26,27,28],"take":"subject3/k1/3/cam4","frame_ids":[21,22,23,24,25,26,27,28]} +{"filtered_tile_id":"b04da484b673692fbb8b406b:8","filtered_window_id":"b04da484b673692fbb8b406b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b04da484b673692fbb8b406b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[29,30,31,32,33,34,35,36],"take":"subject3/k1/3/cam4","frame_ids":[29,30,31,32,33,34,35,36]} +{"filtered_tile_id":"b04da484b673692fbb8b406b:16","filtered_window_id":"b04da484b673692fbb8b406b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b04da484b673692fbb8b406b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject3/k1/3/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"b04da484b673692fbb8b406b:24","filtered_window_id":"b04da484b673692fbb8b406b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b04da484b673692fbb8b406b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject3/k1/3/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"b04da484b673692fbb8b406b:32","filtered_window_id":"b04da484b673692fbb8b406b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b04da484b673692fbb8b406b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[53,54,55,56,57,58,59,60],"take":"subject3/k1/3/cam4","frame_ids":[53,54,55,56,57,58,59,60]} +{"filtered_tile_id":"b04da484b673692fbb8b406b:40","filtered_window_id":"b04da484b673692fbb8b406b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b04da484b673692fbb8b406b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[61,62,63,64,65,66,67,68],"take":"subject3/k1/3/cam4","frame_ids":[61,62,63,64,65,66,67,68]} +{"filtered_tile_id":"b04da484b673692fbb8b406b:48","filtered_window_id":"b04da484b673692fbb8b406b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b04da484b673692fbb8b406b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject3/k1/3/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"b04da484b673692fbb8b406b:52","filtered_window_id":"b04da484b673692fbb8b406b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b04da484b673692fbb8b406b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[73,74,75,76,77,78,79,80],"take":"subject3/k1/3/cam4","frame_ids":[73,74,75,76,77,78,79,80]} +{"filtered_tile_id":"b0c0ebd8a471be6f04d74b1a:0","filtered_window_id":"b0c0ebd8a471be6f04d74b1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0c0ebd8a471be6f04d74b1a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[740,741,742,743,744,745,746,747],"take":"subject2/h1/7/cam4","frame_ids":[740,741,742,743,744,745,746,747]} +{"filtered_tile_id":"b0c0ebd8a471be6f04d74b1a:8","filtered_window_id":"b0c0ebd8a471be6f04d74b1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0c0ebd8a471be6f04d74b1a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[748,749,750,751,752,753,754,755],"take":"subject2/h1/7/cam4","frame_ids":[748,749,750,751,752,753,754,755]} +{"filtered_tile_id":"b0c0ebd8a471be6f04d74b1a:16","filtered_window_id":"b0c0ebd8a471be6f04d74b1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0c0ebd8a471be6f04d74b1a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[756,757,758,759,760,761,762,763],"take":"subject2/h1/7/cam4","frame_ids":[756,757,758,759,760,761,762,763]} +{"filtered_tile_id":"b0c0ebd8a471be6f04d74b1a:24","filtered_window_id":"b0c0ebd8a471be6f04d74b1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0c0ebd8a471be6f04d74b1a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[764,765,766,767,768,769,770,771],"take":"subject2/h1/7/cam4","frame_ids":[764,765,766,767,768,769,770,771]} +{"filtered_tile_id":"b0c0ebd8a471be6f04d74b1a:32","filtered_window_id":"b0c0ebd8a471be6f04d74b1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0c0ebd8a471be6f04d74b1a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[772,773,774,775,776,777,778,779],"take":"subject2/h1/7/cam4","frame_ids":[772,773,774,775,776,777,778,779]} +{"filtered_tile_id":"b0c0ebd8a471be6f04d74b1a:40","filtered_window_id":"b0c0ebd8a471be6f04d74b1a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b0c0ebd8a471be6f04d74b1a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[780,781,782,783,784,785,786,787],"take":"subject2/h1/7/cam4","frame_ids":[780,781,782,783,784,785,786,787]} +{"filtered_tile_id":"b14e892c8a9428d4d11c0ee7:0","filtered_window_id":"b14e892c8a9428d4d11c0ee7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b14e892c8a9428d4d11c0ee7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[373,374,375,376,377,378,379,380],"take":"subject2/k1/3/cam4","frame_ids":[373,374,375,376,377,378,379,380]} +{"filtered_tile_id":"b14e892c8a9428d4d11c0ee7:8","filtered_window_id":"b14e892c8a9428d4d11c0ee7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b14e892c8a9428d4d11c0ee7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[381,382,383,384,385,386,387,388],"take":"subject2/k1/3/cam4","frame_ids":[381,382,383,384,385,386,387,388]} +{"filtered_tile_id":"b14e892c8a9428d4d11c0ee7:16","filtered_window_id":"b14e892c8a9428d4d11c0ee7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b14e892c8a9428d4d11c0ee7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[389,390,391,392,393,394,395,396],"take":"subject2/k1/3/cam4","frame_ids":[389,390,391,392,393,394,395,396]} +{"filtered_tile_id":"b14e892c8a9428d4d11c0ee7:24","filtered_window_id":"b14e892c8a9428d4d11c0ee7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b14e892c8a9428d4d11c0ee7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[397,398,399,400,401,402,403,404],"take":"subject2/k1/3/cam4","frame_ids":[397,398,399,400,401,402,403,404]} +{"filtered_tile_id":"b14e892c8a9428d4d11c0ee7:32","filtered_window_id":"b14e892c8a9428d4d11c0ee7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b14e892c8a9428d4d11c0ee7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[405,406,407,408,409,410,411,412],"take":"subject2/k1/3/cam4","frame_ids":[405,406,407,408,409,410,411,412]} +{"filtered_tile_id":"b14e892c8a9428d4d11c0ee7:40","filtered_window_id":"b14e892c8a9428d4d11c0ee7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b14e892c8a9428d4d11c0ee7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[413,414,415,416,417,418,419,420],"take":"subject2/k1/3/cam4","frame_ids":[413,414,415,416,417,418,419,420]} +{"filtered_tile_id":"b14e892c8a9428d4d11c0ee7:48","filtered_window_id":"b14e892c8a9428d4d11c0ee7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b14e892c8a9428d4d11c0ee7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[421,422,423,424,425,426,427,428],"take":"subject2/k1/3/cam4","frame_ids":[421,422,423,424,425,426,427,428]} +{"filtered_tile_id":"b14e892c8a9428d4d11c0ee7:52","filtered_window_id":"b14e892c8a9428d4d11c0ee7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b14e892c8a9428d4d11c0ee7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject2/k1/3/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"b1556980e5fcefd7b946476c:0","filtered_window_id":"b1556980e5fcefd7b946476c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1556980e5fcefd7b946476c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject3/h2/4/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"b1556980e5fcefd7b946476c:8","filtered_window_id":"b1556980e5fcefd7b946476c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1556980e5fcefd7b946476c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject3/h2/4/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"b1556980e5fcefd7b946476c:16","filtered_window_id":"b1556980e5fcefd7b946476c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1556980e5fcefd7b946476c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject3/h2/4/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"b1556980e5fcefd7b946476c:24","filtered_window_id":"b1556980e5fcefd7b946476c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1556980e5fcefd7b946476c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject3/h2/4/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"b1556980e5fcefd7b946476c:32","filtered_window_id":"b1556980e5fcefd7b946476c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1556980e5fcefd7b946476c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject3/h2/4/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"b1556980e5fcefd7b946476c:40","filtered_window_id":"b1556980e5fcefd7b946476c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1556980e5fcefd7b946476c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject3/h2/4/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"b1556980e5fcefd7b946476c:48","filtered_window_id":"b1556980e5fcefd7b946476c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1556980e5fcefd7b946476c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject3/h2/4/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"b1556980e5fcefd7b946476c:52","filtered_window_id":"b1556980e5fcefd7b946476c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1556980e5fcefd7b946476c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject3/h2/4/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"b17c37db0d7ae5549737e87b:0","filtered_window_id":"b17c37db0d7ae5549737e87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b17c37db0d7ae5549737e87b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[639,640,641,642,643,644,645,646],"take":"subject1/h2/1/cam4","frame_ids":[639,640,641,642,643,644,645,646]} +{"filtered_tile_id":"b17c37db0d7ae5549737e87b:8","filtered_window_id":"b17c37db0d7ae5549737e87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b17c37db0d7ae5549737e87b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[647,648,649,650,651,652,653,654],"take":"subject1/h2/1/cam4","frame_ids":[647,648,649,650,651,652,653,654]} +{"filtered_tile_id":"b17c37db0d7ae5549737e87b:16","filtered_window_id":"b17c37db0d7ae5549737e87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b17c37db0d7ae5549737e87b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[655,656,657,658,659,660,661,662],"take":"subject1/h2/1/cam4","frame_ids":[655,656,657,658,659,660,661,662]} +{"filtered_tile_id":"b17c37db0d7ae5549737e87b:24","filtered_window_id":"b17c37db0d7ae5549737e87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b17c37db0d7ae5549737e87b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[663,664,665,666,667,668,669,670],"take":"subject1/h2/1/cam4","frame_ids":[663,664,665,666,667,668,669,670]} +{"filtered_tile_id":"b17c37db0d7ae5549737e87b:26","filtered_window_id":"b17c37db0d7ae5549737e87b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b17c37db0d7ae5549737e87b/native_gt.npz","filtered_start_offset":26,"expected_frame_ids":[665,666,667,668,669,670,671,672],"take":"subject1/h2/1/cam4","frame_ids":[665,666,667,668,669,670,671,672]} +{"filtered_tile_id":"b190719fb7a37baec6e36a2c:0","filtered_window_id":"b190719fb7a37baec6e36a2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b190719fb7a37baec6e36a2c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject2/k2/5/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"b190719fb7a37baec6e36a2c:8","filtered_window_id":"b190719fb7a37baec6e36a2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b190719fb7a37baec6e36a2c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject2/k2/5/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"b190719fb7a37baec6e36a2c:16","filtered_window_id":"b190719fb7a37baec6e36a2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b190719fb7a37baec6e36a2c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject2/k2/5/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"b190719fb7a37baec6e36a2c:24","filtered_window_id":"b190719fb7a37baec6e36a2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b190719fb7a37baec6e36a2c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject2/k2/5/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"b190719fb7a37baec6e36a2c:32","filtered_window_id":"b190719fb7a37baec6e36a2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b190719fb7a37baec6e36a2c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[156,157,158,159,160,161,162,163],"take":"subject2/k2/5/cam4","frame_ids":[156,157,158,159,160,161,162,163]} +{"filtered_tile_id":"b190719fb7a37baec6e36a2c:40","filtered_window_id":"b190719fb7a37baec6e36a2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b190719fb7a37baec6e36a2c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[164,165,166,167,168,169,170,171],"take":"subject2/k2/5/cam4","frame_ids":[164,165,166,167,168,169,170,171]} +{"filtered_tile_id":"b190719fb7a37baec6e36a2c:48","filtered_window_id":"b190719fb7a37baec6e36a2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b190719fb7a37baec6e36a2c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject2/k2/5/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"b190719fb7a37baec6e36a2c:52","filtered_window_id":"b190719fb7a37baec6e36a2c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b190719fb7a37baec6e36a2c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject2/k2/5/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"b1ffdeccce3f9bd0b2c19688:0","filtered_window_id":"b1ffdeccce3f9bd0b2c19688","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1ffdeccce3f9bd0b2c19688/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject3/h2/3/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"b1ffdeccce3f9bd0b2c19688:8","filtered_window_id":"b1ffdeccce3f9bd0b2c19688","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1ffdeccce3f9bd0b2c19688/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject3/h2/3/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"b1ffdeccce3f9bd0b2c19688:16","filtered_window_id":"b1ffdeccce3f9bd0b2c19688","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1ffdeccce3f9bd0b2c19688/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject3/h2/3/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"b1ffdeccce3f9bd0b2c19688:24","filtered_window_id":"b1ffdeccce3f9bd0b2c19688","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1ffdeccce3f9bd0b2c19688/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject3/h2/3/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"b1ffdeccce3f9bd0b2c19688:32","filtered_window_id":"b1ffdeccce3f9bd0b2c19688","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1ffdeccce3f9bd0b2c19688/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject3/h2/3/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"b1ffdeccce3f9bd0b2c19688:40","filtered_window_id":"b1ffdeccce3f9bd0b2c19688","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1ffdeccce3f9bd0b2c19688/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject3/h2/3/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"b1ffdeccce3f9bd0b2c19688:48","filtered_window_id":"b1ffdeccce3f9bd0b2c19688","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1ffdeccce3f9bd0b2c19688/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject3/h2/3/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"b1ffdeccce3f9bd0b2c19688:52","filtered_window_id":"b1ffdeccce3f9bd0b2c19688","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b1ffdeccce3f9bd0b2c19688/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject3/h2/3/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"b24c620b776dc0c26d98dd96:0","filtered_window_id":"b24c620b776dc0c26d98dd96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b24c620b776dc0c26d98dd96/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[79,80,81,82,83,84,85,86],"take":"subject1/h1/7/cam4","frame_ids":[79,80,81,82,83,84,85,86]} +{"filtered_tile_id":"b24c620b776dc0c26d98dd96:8","filtered_window_id":"b24c620b776dc0c26d98dd96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b24c620b776dc0c26d98dd96/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[87,88,89,90,91,92,93,94],"take":"subject1/h1/7/cam4","frame_ids":[87,88,89,90,91,92,93,94]} +{"filtered_tile_id":"b24c620b776dc0c26d98dd96:16","filtered_window_id":"b24c620b776dc0c26d98dd96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b24c620b776dc0c26d98dd96/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[95,96,97,98,99,100,101,102],"take":"subject1/h1/7/cam4","frame_ids":[95,96,97,98,99,100,101,102]} +{"filtered_tile_id":"b24c620b776dc0c26d98dd96:24","filtered_window_id":"b24c620b776dc0c26d98dd96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b24c620b776dc0c26d98dd96/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[103,104,105,106,107,108,109,110],"take":"subject1/h1/7/cam4","frame_ids":[103,104,105,106,107,108,109,110]} +{"filtered_tile_id":"b24c620b776dc0c26d98dd96:32","filtered_window_id":"b24c620b776dc0c26d98dd96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b24c620b776dc0c26d98dd96/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject1/h1/7/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"b24c620b776dc0c26d98dd96:40","filtered_window_id":"b24c620b776dc0c26d98dd96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b24c620b776dc0c26d98dd96/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject1/h1/7/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"b24c620b776dc0c26d98dd96:43","filtered_window_id":"b24c620b776dc0c26d98dd96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b24c620b776dc0c26d98dd96/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject1/h1/7/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"b25f34aef13f6e480ae7c5a5:0","filtered_window_id":"b25f34aef13f6e480ae7c5a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b25f34aef13f6e480ae7c5a5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o2/7/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"b25f34aef13f6e480ae7c5a5:8","filtered_window_id":"b25f34aef13f6e480ae7c5a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b25f34aef13f6e480ae7c5a5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o2/7/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"b25f34aef13f6e480ae7c5a5:16","filtered_window_id":"b25f34aef13f6e480ae7c5a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b25f34aef13f6e480ae7c5a5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o2/7/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"b25f34aef13f6e480ae7c5a5:24","filtered_window_id":"b25f34aef13f6e480ae7c5a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b25f34aef13f6e480ae7c5a5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o2/7/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"b25f34aef13f6e480ae7c5a5:32","filtered_window_id":"b25f34aef13f6e480ae7c5a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b25f34aef13f6e480ae7c5a5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o2/7/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"b25f34aef13f6e480ae7c5a5:40","filtered_window_id":"b25f34aef13f6e480ae7c5a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b25f34aef13f6e480ae7c5a5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/o2/7/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"b25f34aef13f6e480ae7c5a5:48","filtered_window_id":"b25f34aef13f6e480ae7c5a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b25f34aef13f6e480ae7c5a5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/o2/7/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"b25f34aef13f6e480ae7c5a5:52","filtered_window_id":"b25f34aef13f6e480ae7c5a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b25f34aef13f6e480ae7c5a5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/o2/7/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"b27deb097b4b2de57992455f:0","filtered_window_id":"b27deb097b4b2de57992455f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b27deb097b4b2de57992455f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject1/h1/5/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"b27deb097b4b2de57992455f:8","filtered_window_id":"b27deb097b4b2de57992455f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b27deb097b4b2de57992455f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject1/h1/5/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"b27deb097b4b2de57992455f:16","filtered_window_id":"b27deb097b4b2de57992455f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b27deb097b4b2de57992455f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject1/h1/5/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"b27deb097b4b2de57992455f:24","filtered_window_id":"b27deb097b4b2de57992455f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b27deb097b4b2de57992455f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject1/h1/5/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"b27deb097b4b2de57992455f:32","filtered_window_id":"b27deb097b4b2de57992455f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b27deb097b4b2de57992455f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject1/h1/5/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"b27deb097b4b2de57992455f:40","filtered_window_id":"b27deb097b4b2de57992455f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b27deb097b4b2de57992455f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject1/h1/5/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"b27deb097b4b2de57992455f:48","filtered_window_id":"b27deb097b4b2de57992455f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b27deb097b4b2de57992455f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject1/h1/5/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"b27deb097b4b2de57992455f:51","filtered_window_id":"b27deb097b4b2de57992455f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b27deb097b4b2de57992455f/native_gt.npz","filtered_start_offset":51,"expected_frame_ids":[276,277,278,279,280,281,282,283],"take":"subject1/h1/5/cam4","frame_ids":[276,277,278,279,280,281,282,283]} +{"filtered_tile_id":"b2c9e53f4872d567e6368733:0","filtered_window_id":"b2c9e53f4872d567e6368733","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b2c9e53f4872d567e6368733/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[129,130,131,132,133,134,135,136],"take":"subject1/h2/7/cam4","frame_ids":[129,130,131,132,133,134,135,136]} +{"filtered_tile_id":"b2c9e53f4872d567e6368733:8","filtered_window_id":"b2c9e53f4872d567e6368733","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b2c9e53f4872d567e6368733/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[137,138,139,140,141,142,143,144],"take":"subject1/h2/7/cam4","frame_ids":[137,138,139,140,141,142,143,144]} +{"filtered_tile_id":"b2c9e53f4872d567e6368733:16","filtered_window_id":"b2c9e53f4872d567e6368733","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b2c9e53f4872d567e6368733/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject1/h2/7/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"b2c9e53f4872d567e6368733:24","filtered_window_id":"b2c9e53f4872d567e6368733","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b2c9e53f4872d567e6368733/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject1/h2/7/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"b2c9e53f4872d567e6368733:32","filtered_window_id":"b2c9e53f4872d567e6368733","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b2c9e53f4872d567e6368733/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[161,162,163,164,165,166,167,168],"take":"subject1/h2/7/cam4","frame_ids":[161,162,163,164,165,166,167,168]} +{"filtered_tile_id":"b2c9e53f4872d567e6368733:40","filtered_window_id":"b2c9e53f4872d567e6368733","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b2c9e53f4872d567e6368733/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject1/h2/7/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"b2c9e53f4872d567e6368733:48","filtered_window_id":"b2c9e53f4872d567e6368733","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b2c9e53f4872d567e6368733/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject1/h2/7/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"b2c9e53f4872d567e6368733:52","filtered_window_id":"b2c9e53f4872d567e6368733","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b2c9e53f4872d567e6368733/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject1/h2/7/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"b39717589368d9c70a89fca4:0","filtered_window_id":"b39717589368d9c70a89fca4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b39717589368d9c70a89fca4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[240,241,242,243,244,245,246,247],"take":"subject1/k2/4/cam4","frame_ids":[240,241,242,243,244,245,246,247]} +{"filtered_tile_id":"b39717589368d9c70a89fca4:8","filtered_window_id":"b39717589368d9c70a89fca4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b39717589368d9c70a89fca4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject1/k2/4/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"b39717589368d9c70a89fca4:16","filtered_window_id":"b39717589368d9c70a89fca4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b39717589368d9c70a89fca4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject1/k2/4/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"b39717589368d9c70a89fca4:24","filtered_window_id":"b39717589368d9c70a89fca4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b39717589368d9c70a89fca4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject1/k2/4/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"b39717589368d9c70a89fca4:32","filtered_window_id":"b39717589368d9c70a89fca4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b39717589368d9c70a89fca4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject1/k2/4/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"b39717589368d9c70a89fca4:40","filtered_window_id":"b39717589368d9c70a89fca4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b39717589368d9c70a89fca4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject1/k2/4/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"b39717589368d9c70a89fca4:48","filtered_window_id":"b39717589368d9c70a89fca4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b39717589368d9c70a89fca4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject1/k2/4/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"b39717589368d9c70a89fca4:52","filtered_window_id":"b39717589368d9c70a89fca4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b39717589368d9c70a89fca4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[292,293,294,295,296,297,298,299],"take":"subject1/k2/4/cam4","frame_ids":[292,293,294,295,296,297,298,299]} +{"filtered_tile_id":"b3d15df78a41f94ca7f1108f:0","filtered_window_id":"b3d15df78a41f94ca7f1108f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3d15df78a41f94ca7f1108f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject2/o1/0/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"b3d15df78a41f94ca7f1108f:8","filtered_window_id":"b3d15df78a41f94ca7f1108f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3d15df78a41f94ca7f1108f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject2/o1/0/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"b3d15df78a41f94ca7f1108f:16","filtered_window_id":"b3d15df78a41f94ca7f1108f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3d15df78a41f94ca7f1108f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject2/o1/0/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"b3d15df78a41f94ca7f1108f:24","filtered_window_id":"b3d15df78a41f94ca7f1108f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3d15df78a41f94ca7f1108f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject2/o1/0/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"b3d15df78a41f94ca7f1108f:32","filtered_window_id":"b3d15df78a41f94ca7f1108f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3d15df78a41f94ca7f1108f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject2/o1/0/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"b3d15df78a41f94ca7f1108f:40","filtered_window_id":"b3d15df78a41f94ca7f1108f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3d15df78a41f94ca7f1108f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject2/o1/0/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"b3d15df78a41f94ca7f1108f:48","filtered_window_id":"b3d15df78a41f94ca7f1108f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3d15df78a41f94ca7f1108f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject2/o1/0/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"b3d15df78a41f94ca7f1108f:52","filtered_window_id":"b3d15df78a41f94ca7f1108f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3d15df78a41f94ca7f1108f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject2/o1/0/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"b3dbcc22210e7d54856ee151:0","filtered_window_id":"b3dbcc22210e7d54856ee151","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3dbcc22210e7d54856ee151/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[373,374,375,376,377,378,379,380],"take":"subject3/h2/1/cam4","frame_ids":[373,374,375,376,377,378,379,380]} +{"filtered_tile_id":"b3dbcc22210e7d54856ee151:8","filtered_window_id":"b3dbcc22210e7d54856ee151","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3dbcc22210e7d54856ee151/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[381,382,383,384,385,386,387,388],"take":"subject3/h2/1/cam4","frame_ids":[381,382,383,384,385,386,387,388]} +{"filtered_tile_id":"b3dbcc22210e7d54856ee151:16","filtered_window_id":"b3dbcc22210e7d54856ee151","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3dbcc22210e7d54856ee151/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[389,390,391,392,393,394,395,396],"take":"subject3/h2/1/cam4","frame_ids":[389,390,391,392,393,394,395,396]} +{"filtered_tile_id":"b3dbcc22210e7d54856ee151:24","filtered_window_id":"b3dbcc22210e7d54856ee151","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3dbcc22210e7d54856ee151/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[397,398,399,400,401,402,403,404],"take":"subject3/h2/1/cam4","frame_ids":[397,398,399,400,401,402,403,404]} +{"filtered_tile_id":"b3dbcc22210e7d54856ee151:32","filtered_window_id":"b3dbcc22210e7d54856ee151","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3dbcc22210e7d54856ee151/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[405,406,407,408,409,410,411,412],"take":"subject3/h2/1/cam4","frame_ids":[405,406,407,408,409,410,411,412]} +{"filtered_tile_id":"b3dbcc22210e7d54856ee151:40","filtered_window_id":"b3dbcc22210e7d54856ee151","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3dbcc22210e7d54856ee151/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[413,414,415,416,417,418,419,420],"take":"subject3/h2/1/cam4","frame_ids":[413,414,415,416,417,418,419,420]} +{"filtered_tile_id":"b3dbcc22210e7d54856ee151:48","filtered_window_id":"b3dbcc22210e7d54856ee151","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3dbcc22210e7d54856ee151/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[421,422,423,424,425,426,427,428],"take":"subject3/h2/1/cam4","frame_ids":[421,422,423,424,425,426,427,428]} +{"filtered_tile_id":"b3dbcc22210e7d54856ee151:52","filtered_window_id":"b3dbcc22210e7d54856ee151","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b3dbcc22210e7d54856ee151/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject3/h2/1/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"b40be9f101ccb225ba343366:0","filtered_window_id":"b40be9f101ccb225ba343366","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b40be9f101ccb225ba343366/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject1/o1/0/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"b40be9f101ccb225ba343366:8","filtered_window_id":"b40be9f101ccb225ba343366","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b40be9f101ccb225ba343366/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject1/o1/0/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"b40be9f101ccb225ba343366:16","filtered_window_id":"b40be9f101ccb225ba343366","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b40be9f101ccb225ba343366/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject1/o1/0/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"b40be9f101ccb225ba343366:24","filtered_window_id":"b40be9f101ccb225ba343366","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b40be9f101ccb225ba343366/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject1/o1/0/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"b40be9f101ccb225ba343366:32","filtered_window_id":"b40be9f101ccb225ba343366","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b40be9f101ccb225ba343366/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject1/o1/0/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"b40be9f101ccb225ba343366:40","filtered_window_id":"b40be9f101ccb225ba343366","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b40be9f101ccb225ba343366/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject1/o1/0/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"b40be9f101ccb225ba343366:48","filtered_window_id":"b40be9f101ccb225ba343366","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b40be9f101ccb225ba343366/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject1/o1/0/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"b40be9f101ccb225ba343366:52","filtered_window_id":"b40be9f101ccb225ba343366","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b40be9f101ccb225ba343366/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject1/o1/0/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"b42336af0fd6c8b4e079567f:0","filtered_window_id":"b42336af0fd6c8b4e079567f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b42336af0fd6c8b4e079567f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject1/k2/6/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"b42336af0fd6c8b4e079567f:8","filtered_window_id":"b42336af0fd6c8b4e079567f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b42336af0fd6c8b4e079567f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject1/k2/6/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"b42336af0fd6c8b4e079567f:16","filtered_window_id":"b42336af0fd6c8b4e079567f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b42336af0fd6c8b4e079567f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject1/k2/6/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"b42336af0fd6c8b4e079567f:24","filtered_window_id":"b42336af0fd6c8b4e079567f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b42336af0fd6c8b4e079567f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[246,247,248,249,250,251,252,253],"take":"subject1/k2/6/cam4","frame_ids":[246,247,248,249,250,251,252,253]} +{"filtered_tile_id":"b42336af0fd6c8b4e079567f:32","filtered_window_id":"b42336af0fd6c8b4e079567f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b42336af0fd6c8b4e079567f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject1/k2/6/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"b42336af0fd6c8b4e079567f:40","filtered_window_id":"b42336af0fd6c8b4e079567f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b42336af0fd6c8b4e079567f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[262,263,264,265,266,267,268,269],"take":"subject1/k2/6/cam4","frame_ids":[262,263,264,265,266,267,268,269]} +{"filtered_tile_id":"b42336af0fd6c8b4e079567f:48","filtered_window_id":"b42336af0fd6c8b4e079567f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b42336af0fd6c8b4e079567f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[270,271,272,273,274,275,276,277],"take":"subject1/k2/6/cam4","frame_ids":[270,271,272,273,274,275,276,277]} +{"filtered_tile_id":"b42336af0fd6c8b4e079567f:52","filtered_window_id":"b42336af0fd6c8b4e079567f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b42336af0fd6c8b4e079567f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[274,275,276,277,278,279,280,281],"take":"subject1/k2/6/cam4","frame_ids":[274,275,276,277,278,279,280,281]} +{"filtered_tile_id":"b446dccddb02a42f101efc42:0","filtered_window_id":"b446dccddb02a42f101efc42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b446dccddb02a42f101efc42/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject2/k2/4/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"b446dccddb02a42f101efc42:8","filtered_window_id":"b446dccddb02a42f101efc42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b446dccddb02a42f101efc42/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject2/k2/4/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"b446dccddb02a42f101efc42:16","filtered_window_id":"b446dccddb02a42f101efc42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b446dccddb02a42f101efc42/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject2/k2/4/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"b446dccddb02a42f101efc42:24","filtered_window_id":"b446dccddb02a42f101efc42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b446dccddb02a42f101efc42/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject2/k2/4/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"b446dccddb02a42f101efc42:27","filtered_window_id":"b446dccddb02a42f101efc42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b446dccddb02a42f101efc42/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject2/k2/4/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"b4a34d95cfd69172a88e59a9:0","filtered_window_id":"b4a34d95cfd69172a88e59a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a34d95cfd69172a88e59a9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[434,435,436,437,438,439,440,441],"take":"subject2/o1/0/cam4","frame_ids":[434,435,436,437,438,439,440,441]} +{"filtered_tile_id":"b4a34d95cfd69172a88e59a9:8","filtered_window_id":"b4a34d95cfd69172a88e59a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a34d95cfd69172a88e59a9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[442,443,444,445,446,447,448,449],"take":"subject2/o1/0/cam4","frame_ids":[442,443,444,445,446,447,448,449]} +{"filtered_tile_id":"b4a34d95cfd69172a88e59a9:16","filtered_window_id":"b4a34d95cfd69172a88e59a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a34d95cfd69172a88e59a9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[450,451,452,453,454,455,456,457],"take":"subject2/o1/0/cam4","frame_ids":[450,451,452,453,454,455,456,457]} +{"filtered_tile_id":"b4a34d95cfd69172a88e59a9:24","filtered_window_id":"b4a34d95cfd69172a88e59a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a34d95cfd69172a88e59a9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject2/o1/0/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"b4a34d95cfd69172a88e59a9:32","filtered_window_id":"b4a34d95cfd69172a88e59a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a34d95cfd69172a88e59a9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[466,467,468,469,470,471,472,473],"take":"subject2/o1/0/cam4","frame_ids":[466,467,468,469,470,471,472,473]} +{"filtered_tile_id":"b4a34d95cfd69172a88e59a9:40","filtered_window_id":"b4a34d95cfd69172a88e59a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a34d95cfd69172a88e59a9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[474,475,476,477,478,479,480,481],"take":"subject2/o1/0/cam4","frame_ids":[474,475,476,477,478,479,480,481]} +{"filtered_tile_id":"b4a34d95cfd69172a88e59a9:48","filtered_window_id":"b4a34d95cfd69172a88e59a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a34d95cfd69172a88e59a9/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[482,483,484,485,486,487,488,489],"take":"subject2/o1/0/cam4","frame_ids":[482,483,484,485,486,487,488,489]} +{"filtered_tile_id":"b4a34d95cfd69172a88e59a9:52","filtered_window_id":"b4a34d95cfd69172a88e59a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a34d95cfd69172a88e59a9/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject2/o1/0/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"b4a7a5df9ec48e844f011f55:0","filtered_window_id":"b4a7a5df9ec48e844f011f55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7a5df9ec48e844f011f55/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[574,575,576,577,578,579,580,581],"take":"subject1/k1/2/cam4","frame_ids":[574,575,576,577,578,579,580,581]} +{"filtered_tile_id":"b4a7a5df9ec48e844f011f55:8","filtered_window_id":"b4a7a5df9ec48e844f011f55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7a5df9ec48e844f011f55/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[582,583,584,585,586,587,588,589],"take":"subject1/k1/2/cam4","frame_ids":[582,583,584,585,586,587,588,589]} +{"filtered_tile_id":"b4a7a5df9ec48e844f011f55:16","filtered_window_id":"b4a7a5df9ec48e844f011f55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7a5df9ec48e844f011f55/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[590,591,592,593,594,595,596,597],"take":"subject1/k1/2/cam4","frame_ids":[590,591,592,593,594,595,596,597]} +{"filtered_tile_id":"b4a7a5df9ec48e844f011f55:24","filtered_window_id":"b4a7a5df9ec48e844f011f55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7a5df9ec48e844f011f55/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[598,599,600,601,602,603,604,605],"take":"subject1/k1/2/cam4","frame_ids":[598,599,600,601,602,603,604,605]} +{"filtered_tile_id":"b4a7a5df9ec48e844f011f55:32","filtered_window_id":"b4a7a5df9ec48e844f011f55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7a5df9ec48e844f011f55/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[606,607,608,609,610,611,612,613],"take":"subject1/k1/2/cam4","frame_ids":[606,607,608,609,610,611,612,613]} +{"filtered_tile_id":"b4a7a5df9ec48e844f011f55:40","filtered_window_id":"b4a7a5df9ec48e844f011f55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7a5df9ec48e844f011f55/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[614,615,616,617,618,619,620,621],"take":"subject1/k1/2/cam4","frame_ids":[614,615,616,617,618,619,620,621]} +{"filtered_tile_id":"b4a7a5df9ec48e844f011f55:48","filtered_window_id":"b4a7a5df9ec48e844f011f55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7a5df9ec48e844f011f55/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[622,623,624,625,626,627,628,629],"take":"subject1/k1/2/cam4","frame_ids":[622,623,624,625,626,627,628,629]} +{"filtered_tile_id":"b4a7a5df9ec48e844f011f55:52","filtered_window_id":"b4a7a5df9ec48e844f011f55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7a5df9ec48e844f011f55/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[626,627,628,629,630,631,632,633],"take":"subject1/k1/2/cam4","frame_ids":[626,627,628,629,630,631,632,633]} +{"filtered_tile_id":"b4a7c5a83aba9dc70d274875:0","filtered_window_id":"b4a7c5a83aba9dc70d274875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7c5a83aba9dc70d274875/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject2/o2/5/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"b4a7c5a83aba9dc70d274875:8","filtered_window_id":"b4a7c5a83aba9dc70d274875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7c5a83aba9dc70d274875/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject2/o2/5/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"b4a7c5a83aba9dc70d274875:16","filtered_window_id":"b4a7c5a83aba9dc70d274875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7c5a83aba9dc70d274875/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject2/o2/5/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"b4a7c5a83aba9dc70d274875:24","filtered_window_id":"b4a7c5a83aba9dc70d274875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7c5a83aba9dc70d274875/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[236,237,238,239,240,241,242,243],"take":"subject2/o2/5/cam4","frame_ids":[236,237,238,239,240,241,242,243]} +{"filtered_tile_id":"b4a7c5a83aba9dc70d274875:32","filtered_window_id":"b4a7c5a83aba9dc70d274875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7c5a83aba9dc70d274875/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[244,245,246,247,248,249,250,251],"take":"subject2/o2/5/cam4","frame_ids":[244,245,246,247,248,249,250,251]} +{"filtered_tile_id":"b4a7c5a83aba9dc70d274875:40","filtered_window_id":"b4a7c5a83aba9dc70d274875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7c5a83aba9dc70d274875/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[252,253,254,255,256,257,258,259],"take":"subject2/o2/5/cam4","frame_ids":[252,253,254,255,256,257,258,259]} +{"filtered_tile_id":"b4a7c5a83aba9dc70d274875:48","filtered_window_id":"b4a7c5a83aba9dc70d274875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7c5a83aba9dc70d274875/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[260,261,262,263,264,265,266,267],"take":"subject2/o2/5/cam4","frame_ids":[260,261,262,263,264,265,266,267]} +{"filtered_tile_id":"b4a7c5a83aba9dc70d274875:52","filtered_window_id":"b4a7c5a83aba9dc70d274875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b4a7c5a83aba9dc70d274875/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject2/o2/5/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"b52439f41c84627b869318d9:0","filtered_window_id":"b52439f41c84627b869318d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b52439f41c84627b869318d9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject1/k2/6/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"b52439f41c84627b869318d9:8","filtered_window_id":"b52439f41c84627b869318d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b52439f41c84627b869318d9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject1/k2/6/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"b52439f41c84627b869318d9:16","filtered_window_id":"b52439f41c84627b869318d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b52439f41c84627b869318d9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject1/k2/6/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"b52439f41c84627b869318d9:24","filtered_window_id":"b52439f41c84627b869318d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b52439f41c84627b869318d9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject1/k2/6/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"b52439f41c84627b869318d9:26","filtered_window_id":"b52439f41c84627b869318d9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b52439f41c84627b869318d9/native_gt.npz","filtered_start_offset":26,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject1/k2/6/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"b627998384cb138b912bd850:0","filtered_window_id":"b627998384cb138b912bd850","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b627998384cb138b912bd850/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject2/o1/0/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"b627998384cb138b912bd850:8","filtered_window_id":"b627998384cb138b912bd850","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b627998384cb138b912bd850/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject2/o1/0/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"b627998384cb138b912bd850:16","filtered_window_id":"b627998384cb138b912bd850","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b627998384cb138b912bd850/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject2/o1/0/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"b627998384cb138b912bd850:24","filtered_window_id":"b627998384cb138b912bd850","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b627998384cb138b912bd850/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject2/o1/0/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"b627998384cb138b912bd850:32","filtered_window_id":"b627998384cb138b912bd850","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b627998384cb138b912bd850/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject2/o1/0/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"b627998384cb138b912bd850:40","filtered_window_id":"b627998384cb138b912bd850","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b627998384cb138b912bd850/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[354,355,356,357,358,359,360,361],"take":"subject2/o1/0/cam4","frame_ids":[354,355,356,357,358,359,360,361]} +{"filtered_tile_id":"b627998384cb138b912bd850:48","filtered_window_id":"b627998384cb138b912bd850","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b627998384cb138b912bd850/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject2/o1/0/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"b627998384cb138b912bd850:52","filtered_window_id":"b627998384cb138b912bd850","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b627998384cb138b912bd850/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject2/o1/0/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"b759ff9e6527c5707f65bfae:0","filtered_window_id":"b759ff9e6527c5707f65bfae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b759ff9e6527c5707f65bfae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h2/3/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"b759ff9e6527c5707f65bfae:8","filtered_window_id":"b759ff9e6527c5707f65bfae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b759ff9e6527c5707f65bfae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h2/3/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"b759ff9e6527c5707f65bfae:16","filtered_window_id":"b759ff9e6527c5707f65bfae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b759ff9e6527c5707f65bfae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h2/3/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"b759ff9e6527c5707f65bfae:24","filtered_window_id":"b759ff9e6527c5707f65bfae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b759ff9e6527c5707f65bfae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h2/3/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"b759ff9e6527c5707f65bfae:32","filtered_window_id":"b759ff9e6527c5707f65bfae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b759ff9e6527c5707f65bfae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h2/3/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"b759ff9e6527c5707f65bfae:40","filtered_window_id":"b759ff9e6527c5707f65bfae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b759ff9e6527c5707f65bfae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/h2/3/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"b759ff9e6527c5707f65bfae:45","filtered_window_id":"b759ff9e6527c5707f65bfae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b759ff9e6527c5707f65bfae/native_gt.npz","filtered_start_offset":45,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject1/h2/3/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"b77630e1293d47a7a8af894d:0","filtered_window_id":"b77630e1293d47a7a8af894d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b77630e1293d47a7a8af894d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject2/h1/7/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"b77630e1293d47a7a8af894d:8","filtered_window_id":"b77630e1293d47a7a8af894d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b77630e1293d47a7a8af894d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject2/h1/7/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"b77630e1293d47a7a8af894d:16","filtered_window_id":"b77630e1293d47a7a8af894d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b77630e1293d47a7a8af894d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject2/h1/7/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"b77630e1293d47a7a8af894d:24","filtered_window_id":"b77630e1293d47a7a8af894d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b77630e1293d47a7a8af894d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject2/h1/7/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"b77630e1293d47a7a8af894d:32","filtered_window_id":"b77630e1293d47a7a8af894d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b77630e1293d47a7a8af894d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject2/h1/7/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"b77630e1293d47a7a8af894d:40","filtered_window_id":"b77630e1293d47a7a8af894d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b77630e1293d47a7a8af894d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject2/h1/7/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"b77630e1293d47a7a8af894d:48","filtered_window_id":"b77630e1293d47a7a8af894d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b77630e1293d47a7a8af894d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject2/h1/7/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"b77630e1293d47a7a8af894d:52","filtered_window_id":"b77630e1293d47a7a8af894d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b77630e1293d47a7a8af894d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject2/h1/7/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"b795b05f461be0955842765d:0","filtered_window_id":"b795b05f461be0955842765d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b795b05f461be0955842765d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[928,929,930,931,932,933,934,935],"take":"subject2/h1/3/cam4","frame_ids":[928,929,930,931,932,933,934,935]} +{"filtered_tile_id":"b795b05f461be0955842765d:8","filtered_window_id":"b795b05f461be0955842765d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b795b05f461be0955842765d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[936,937,938,939,940,941,942,943],"take":"subject2/h1/3/cam4","frame_ids":[936,937,938,939,940,941,942,943]} +{"filtered_tile_id":"b795b05f461be0955842765d:16","filtered_window_id":"b795b05f461be0955842765d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b795b05f461be0955842765d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[944,945,946,947,948,949,950,951],"take":"subject2/h1/3/cam4","frame_ids":[944,945,946,947,948,949,950,951]} +{"filtered_tile_id":"b795b05f461be0955842765d:24","filtered_window_id":"b795b05f461be0955842765d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b795b05f461be0955842765d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[952,953,954,955,956,957,958,959],"take":"subject2/h1/3/cam4","frame_ids":[952,953,954,955,956,957,958,959]} +{"filtered_tile_id":"b795b05f461be0955842765d:32","filtered_window_id":"b795b05f461be0955842765d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b795b05f461be0955842765d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[960,961,962,963,964,965,966,967],"take":"subject2/h1/3/cam4","frame_ids":[960,961,962,963,964,965,966,967]} +{"filtered_tile_id":"b795b05f461be0955842765d:40","filtered_window_id":"b795b05f461be0955842765d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b795b05f461be0955842765d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[968,969,970,971,972,973,974,975],"take":"subject2/h1/3/cam4","frame_ids":[968,969,970,971,972,973,974,975]} +{"filtered_tile_id":"b795b05f461be0955842765d:48","filtered_window_id":"b795b05f461be0955842765d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b795b05f461be0955842765d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[976,977,978,979,980,981,982,983],"take":"subject2/h1/3/cam4","frame_ids":[976,977,978,979,980,981,982,983]} +{"filtered_tile_id":"b795b05f461be0955842765d:52","filtered_window_id":"b795b05f461be0955842765d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b795b05f461be0955842765d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[980,981,982,983,984,985,986,987],"take":"subject2/h1/3/cam4","frame_ids":[980,981,982,983,984,985,986,987]} +{"filtered_tile_id":"b7f9e36ce3eccbe2ca536998:0","filtered_window_id":"b7f9e36ce3eccbe2ca536998","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b7f9e36ce3eccbe2ca536998/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject1/h2/2/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"b7f9e36ce3eccbe2ca536998:8","filtered_window_id":"b7f9e36ce3eccbe2ca536998","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b7f9e36ce3eccbe2ca536998/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject1/h2/2/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"b7f9e36ce3eccbe2ca536998:16","filtered_window_id":"b7f9e36ce3eccbe2ca536998","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b7f9e36ce3eccbe2ca536998/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject1/h2/2/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"b7f9e36ce3eccbe2ca536998:24","filtered_window_id":"b7f9e36ce3eccbe2ca536998","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b7f9e36ce3eccbe2ca536998/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[156,157,158,159,160,161,162,163],"take":"subject1/h2/2/cam4","frame_ids":[156,157,158,159,160,161,162,163]} +{"filtered_tile_id":"b7f9e36ce3eccbe2ca536998:32","filtered_window_id":"b7f9e36ce3eccbe2ca536998","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b7f9e36ce3eccbe2ca536998/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[164,165,166,167,168,169,170,171],"take":"subject1/h2/2/cam4","frame_ids":[164,165,166,167,168,169,170,171]} +{"filtered_tile_id":"b7f9e36ce3eccbe2ca536998:40","filtered_window_id":"b7f9e36ce3eccbe2ca536998","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b7f9e36ce3eccbe2ca536998/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject1/h2/2/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"b7f9e36ce3eccbe2ca536998:48","filtered_window_id":"b7f9e36ce3eccbe2ca536998","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b7f9e36ce3eccbe2ca536998/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject1/h2/2/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"b7f9e36ce3eccbe2ca536998:52","filtered_window_id":"b7f9e36ce3eccbe2ca536998","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b7f9e36ce3eccbe2ca536998/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject1/h2/2/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"b84310382e73a25494eff530:0","filtered_window_id":"b84310382e73a25494eff530","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b84310382e73a25494eff530/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[514,515,516,517,518,519,520,521],"take":"subject1/k1/2/cam4","frame_ids":[514,515,516,517,518,519,520,521]} +{"filtered_tile_id":"b84310382e73a25494eff530:8","filtered_window_id":"b84310382e73a25494eff530","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b84310382e73a25494eff530/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[522,523,524,525,526,527,528,529],"take":"subject1/k1/2/cam4","frame_ids":[522,523,524,525,526,527,528,529]} +{"filtered_tile_id":"b84310382e73a25494eff530:16","filtered_window_id":"b84310382e73a25494eff530","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b84310382e73a25494eff530/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[530,531,532,533,534,535,536,537],"take":"subject1/k1/2/cam4","frame_ids":[530,531,532,533,534,535,536,537]} +{"filtered_tile_id":"b84310382e73a25494eff530:24","filtered_window_id":"b84310382e73a25494eff530","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b84310382e73a25494eff530/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[538,539,540,541,542,543,544,545],"take":"subject1/k1/2/cam4","frame_ids":[538,539,540,541,542,543,544,545]} +{"filtered_tile_id":"b84310382e73a25494eff530:32","filtered_window_id":"b84310382e73a25494eff530","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b84310382e73a25494eff530/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[546,547,548,549,550,551,552,553],"take":"subject1/k1/2/cam4","frame_ids":[546,547,548,549,550,551,552,553]} +{"filtered_tile_id":"b84310382e73a25494eff530:40","filtered_window_id":"b84310382e73a25494eff530","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b84310382e73a25494eff530/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[554,555,556,557,558,559,560,561],"take":"subject1/k1/2/cam4","frame_ids":[554,555,556,557,558,559,560,561]} +{"filtered_tile_id":"b84310382e73a25494eff530:48","filtered_window_id":"b84310382e73a25494eff530","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b84310382e73a25494eff530/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[562,563,564,565,566,567,568,569],"take":"subject1/k1/2/cam4","frame_ids":[562,563,564,565,566,567,568,569]} +{"filtered_tile_id":"b84310382e73a25494eff530:52","filtered_window_id":"b84310382e73a25494eff530","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b84310382e73a25494eff530/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[566,567,568,569,570,571,572,573],"take":"subject1/k1/2/cam4","frame_ids":[566,567,568,569,570,571,572,573]} +{"filtered_tile_id":"b88641000e9bd8e79b4ed608:0","filtered_window_id":"b88641000e9bd8e79b4ed608","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b88641000e9bd8e79b4ed608/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject1/o2/7/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"b88641000e9bd8e79b4ed608:8","filtered_window_id":"b88641000e9bd8e79b4ed608","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b88641000e9bd8e79b4ed608/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject1/o2/7/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"b88641000e9bd8e79b4ed608:16","filtered_window_id":"b88641000e9bd8e79b4ed608","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b88641000e9bd8e79b4ed608/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject1/o2/7/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"b88641000e9bd8e79b4ed608:24","filtered_window_id":"b88641000e9bd8e79b4ed608","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b88641000e9bd8e79b4ed608/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject1/o2/7/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"b88641000e9bd8e79b4ed608:32","filtered_window_id":"b88641000e9bd8e79b4ed608","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b88641000e9bd8e79b4ed608/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject1/o2/7/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"b88641000e9bd8e79b4ed608:40","filtered_window_id":"b88641000e9bd8e79b4ed608","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b88641000e9bd8e79b4ed608/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject1/o2/7/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"b88641000e9bd8e79b4ed608:48","filtered_window_id":"b88641000e9bd8e79b4ed608","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b88641000e9bd8e79b4ed608/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject1/o2/7/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"b88641000e9bd8e79b4ed608:52","filtered_window_id":"b88641000e9bd8e79b4ed608","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b88641000e9bd8e79b4ed608/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject1/o2/7/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"b89fa5bb48f90680585c3904:0","filtered_window_id":"b89fa5bb48f90680585c3904","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b89fa5bb48f90680585c3904/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject1/h1/3/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"b89fa5bb48f90680585c3904:8","filtered_window_id":"b89fa5bb48f90680585c3904","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b89fa5bb48f90680585c3904/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject1/h1/3/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"b8d1f712b75af9c554062ffe:0","filtered_window_id":"b8d1f712b75af9c554062ffe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d1f712b75af9c554062ffe/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[224,225,226,227,228,229,230,231],"take":"subject1/k2/3/cam4","frame_ids":[224,225,226,227,228,229,230,231]} +{"filtered_tile_id":"b8d1f712b75af9c554062ffe:8","filtered_window_id":"b8d1f712b75af9c554062ffe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d1f712b75af9c554062ffe/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[232,233,234,235,236,237,238,239],"take":"subject1/k2/3/cam4","frame_ids":[232,233,234,235,236,237,238,239]} +{"filtered_tile_id":"b8d1f712b75af9c554062ffe:16","filtered_window_id":"b8d1f712b75af9c554062ffe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d1f712b75af9c554062ffe/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[240,241,242,243,244,245,246,247],"take":"subject1/k2/3/cam4","frame_ids":[240,241,242,243,244,245,246,247]} +{"filtered_tile_id":"b8d1f712b75af9c554062ffe:24","filtered_window_id":"b8d1f712b75af9c554062ffe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d1f712b75af9c554062ffe/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject1/k2/3/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"b8d1f712b75af9c554062ffe:32","filtered_window_id":"b8d1f712b75af9c554062ffe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d1f712b75af9c554062ffe/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject1/k2/3/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"b8d1f712b75af9c554062ffe:40","filtered_window_id":"b8d1f712b75af9c554062ffe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d1f712b75af9c554062ffe/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject1/k2/3/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"b8d1f712b75af9c554062ffe:48","filtered_window_id":"b8d1f712b75af9c554062ffe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d1f712b75af9c554062ffe/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject1/k2/3/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"b8d1f712b75af9c554062ffe:52","filtered_window_id":"b8d1f712b75af9c554062ffe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d1f712b75af9c554062ffe/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[276,277,278,279,280,281,282,283],"take":"subject1/k2/3/cam4","frame_ids":[276,277,278,279,280,281,282,283]} +{"filtered_tile_id":"b8d77a5c80072a04bc028692:0","filtered_window_id":"b8d77a5c80072a04bc028692","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d77a5c80072a04bc028692/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[18,19,20,21,22,23,24,25],"take":"subject1/k2/0/cam4","frame_ids":[18,19,20,21,22,23,24,25]} +{"filtered_tile_id":"b8d77a5c80072a04bc028692:8","filtered_window_id":"b8d77a5c80072a04bc028692","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d77a5c80072a04bc028692/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[26,27,28,29,30,31,32,33],"take":"subject1/k2/0/cam4","frame_ids":[26,27,28,29,30,31,32,33]} +{"filtered_tile_id":"b8d77a5c80072a04bc028692:16","filtered_window_id":"b8d77a5c80072a04bc028692","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d77a5c80072a04bc028692/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[34,35,36,37,38,39,40,41],"take":"subject1/k2/0/cam4","frame_ids":[34,35,36,37,38,39,40,41]} +{"filtered_tile_id":"b8d77a5c80072a04bc028692:24","filtered_window_id":"b8d77a5c80072a04bc028692","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d77a5c80072a04bc028692/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[42,43,44,45,46,47,48,49],"take":"subject1/k2/0/cam4","frame_ids":[42,43,44,45,46,47,48,49]} +{"filtered_tile_id":"b8d77a5c80072a04bc028692:32","filtered_window_id":"b8d77a5c80072a04bc028692","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d77a5c80072a04bc028692/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[50,51,52,53,54,55,56,57],"take":"subject1/k2/0/cam4","frame_ids":[50,51,52,53,54,55,56,57]} +{"filtered_tile_id":"b8d77a5c80072a04bc028692:40","filtered_window_id":"b8d77a5c80072a04bc028692","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d77a5c80072a04bc028692/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[58,59,60,61,62,63,64,65],"take":"subject1/k2/0/cam4","frame_ids":[58,59,60,61,62,63,64,65]} +{"filtered_tile_id":"b8d77a5c80072a04bc028692:48","filtered_window_id":"b8d77a5c80072a04bc028692","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d77a5c80072a04bc028692/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[66,67,68,69,70,71,72,73],"take":"subject1/k2/0/cam4","frame_ids":[66,67,68,69,70,71,72,73]} +{"filtered_tile_id":"b8d77a5c80072a04bc028692:52","filtered_window_id":"b8d77a5c80072a04bc028692","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8d77a5c80072a04bc028692/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[70,71,72,73,74,75,76,77],"take":"subject1/k2/0/cam4","frame_ids":[70,71,72,73,74,75,76,77]} +{"filtered_tile_id":"b8e585eaa1e457a218776ab9:0","filtered_window_id":"b8e585eaa1e457a218776ab9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8e585eaa1e457a218776ab9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject2/k1/0/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"b8e585eaa1e457a218776ab9:8","filtered_window_id":"b8e585eaa1e457a218776ab9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8e585eaa1e457a218776ab9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject2/k1/0/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"b8e585eaa1e457a218776ab9:16","filtered_window_id":"b8e585eaa1e457a218776ab9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8e585eaa1e457a218776ab9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject2/k1/0/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"b8e585eaa1e457a218776ab9:24","filtered_window_id":"b8e585eaa1e457a218776ab9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8e585eaa1e457a218776ab9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject2/k1/0/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"b8e585eaa1e457a218776ab9:32","filtered_window_id":"b8e585eaa1e457a218776ab9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8e585eaa1e457a218776ab9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject2/k1/0/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"b8e585eaa1e457a218776ab9:40","filtered_window_id":"b8e585eaa1e457a218776ab9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8e585eaa1e457a218776ab9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject2/k1/0/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"b8e585eaa1e457a218776ab9:48","filtered_window_id":"b8e585eaa1e457a218776ab9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8e585eaa1e457a218776ab9/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject2/k1/0/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"b8e585eaa1e457a218776ab9:52","filtered_window_id":"b8e585eaa1e457a218776ab9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b8e585eaa1e457a218776ab9/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject2/k1/0/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"b929b728b0eeecd1e25fcf33:0","filtered_window_id":"b929b728b0eeecd1e25fcf33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b929b728b0eeecd1e25fcf33/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject2/o1/3/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"b929b728b0eeecd1e25fcf33:8","filtered_window_id":"b929b728b0eeecd1e25fcf33","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b929b728b0eeecd1e25fcf33/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject2/o1/3/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"b9687d8fe4c271bfa0315b18:0","filtered_window_id":"b9687d8fe4c271bfa0315b18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9687d8fe4c271bfa0315b18/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject2/h2/4/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"b9687d8fe4c271bfa0315b18:8","filtered_window_id":"b9687d8fe4c271bfa0315b18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9687d8fe4c271bfa0315b18/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject2/h2/4/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"b9687d8fe4c271bfa0315b18:16","filtered_window_id":"b9687d8fe4c271bfa0315b18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9687d8fe4c271bfa0315b18/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject2/h2/4/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"b9687d8fe4c271bfa0315b18:24","filtered_window_id":"b9687d8fe4c271bfa0315b18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9687d8fe4c271bfa0315b18/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject2/h2/4/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"b9687d8fe4c271bfa0315b18:32","filtered_window_id":"b9687d8fe4c271bfa0315b18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9687d8fe4c271bfa0315b18/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject2/h2/4/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"b9687d8fe4c271bfa0315b18:40","filtered_window_id":"b9687d8fe4c271bfa0315b18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9687d8fe4c271bfa0315b18/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject2/h2/4/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"b9687d8fe4c271bfa0315b18:48","filtered_window_id":"b9687d8fe4c271bfa0315b18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9687d8fe4c271bfa0315b18/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject2/h2/4/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"b9687d8fe4c271bfa0315b18:51","filtered_window_id":"b9687d8fe4c271bfa0315b18","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9687d8fe4c271bfa0315b18/native_gt.npz","filtered_start_offset":51,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject2/h2/4/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"b988d230642e2be149209ac8:0","filtered_window_id":"b988d230642e2be149209ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b988d230642e2be149209ac8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[144,145,146,147,148,149,150,151],"take":"subject1/o1/6/cam4","frame_ids":[144,145,146,147,148,149,150,151]} +{"filtered_tile_id":"b988d230642e2be149209ac8:8","filtered_window_id":"b988d230642e2be149209ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b988d230642e2be149209ac8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject1/o1/6/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"b988d230642e2be149209ac8:16","filtered_window_id":"b988d230642e2be149209ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b988d230642e2be149209ac8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject1/o1/6/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"b988d230642e2be149209ac8:24","filtered_window_id":"b988d230642e2be149209ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b988d230642e2be149209ac8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject1/o1/6/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"b988d230642e2be149209ac8:32","filtered_window_id":"b988d230642e2be149209ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b988d230642e2be149209ac8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject1/o1/6/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"b988d230642e2be149209ac8:40","filtered_window_id":"b988d230642e2be149209ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b988d230642e2be149209ac8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject1/o1/6/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"b988d230642e2be149209ac8:48","filtered_window_id":"b988d230642e2be149209ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b988d230642e2be149209ac8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[192,193,194,195,196,197,198,199],"take":"subject1/o1/6/cam4","frame_ids":[192,193,194,195,196,197,198,199]} +{"filtered_tile_id":"b988d230642e2be149209ac8:52","filtered_window_id":"b988d230642e2be149209ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b988d230642e2be149209ac8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject1/o1/6/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"b9d500773c4cfb0fe7986ae3:0","filtered_window_id":"b9d500773c4cfb0fe7986ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d500773c4cfb0fe7986ae3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[400,401,402,403,404,405,406,407],"take":"subject1/h2/1/cam4","frame_ids":[400,401,402,403,404,405,406,407]} +{"filtered_tile_id":"b9d500773c4cfb0fe7986ae3:8","filtered_window_id":"b9d500773c4cfb0fe7986ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d500773c4cfb0fe7986ae3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[408,409,410,411,412,413,414,415],"take":"subject1/h2/1/cam4","frame_ids":[408,409,410,411,412,413,414,415]} +{"filtered_tile_id":"b9d500773c4cfb0fe7986ae3:16","filtered_window_id":"b9d500773c4cfb0fe7986ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d500773c4cfb0fe7986ae3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[416,417,418,419,420,421,422,423],"take":"subject1/h2/1/cam4","frame_ids":[416,417,418,419,420,421,422,423]} +{"filtered_tile_id":"b9d500773c4cfb0fe7986ae3:24","filtered_window_id":"b9d500773c4cfb0fe7986ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d500773c4cfb0fe7986ae3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[424,425,426,427,428,429,430,431],"take":"subject1/h2/1/cam4","frame_ids":[424,425,426,427,428,429,430,431]} +{"filtered_tile_id":"b9d500773c4cfb0fe7986ae3:32","filtered_window_id":"b9d500773c4cfb0fe7986ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d500773c4cfb0fe7986ae3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[432,433,434,435,436,437,438,439],"take":"subject1/h2/1/cam4","frame_ids":[432,433,434,435,436,437,438,439]} +{"filtered_tile_id":"b9d500773c4cfb0fe7986ae3:40","filtered_window_id":"b9d500773c4cfb0fe7986ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d500773c4cfb0fe7986ae3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[440,441,442,443,444,445,446,447],"take":"subject1/h2/1/cam4","frame_ids":[440,441,442,443,444,445,446,447]} +{"filtered_tile_id":"b9d500773c4cfb0fe7986ae3:41","filtered_window_id":"b9d500773c4cfb0fe7986ae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d500773c4cfb0fe7986ae3/native_gt.npz","filtered_start_offset":41,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject1/h2/1/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"b9d52a70309d11b244fd0dfe:0","filtered_window_id":"b9d52a70309d11b244fd0dfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d52a70309d11b244fd0dfe/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject2/h2/3/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"b9d52a70309d11b244fd0dfe:8","filtered_window_id":"b9d52a70309d11b244fd0dfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d52a70309d11b244fd0dfe/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject2/h2/3/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"b9d52a70309d11b244fd0dfe:16","filtered_window_id":"b9d52a70309d11b244fd0dfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d52a70309d11b244fd0dfe/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject2/h2/3/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"b9d52a70309d11b244fd0dfe:24","filtered_window_id":"b9d52a70309d11b244fd0dfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d52a70309d11b244fd0dfe/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject2/h2/3/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"b9d52a70309d11b244fd0dfe:32","filtered_window_id":"b9d52a70309d11b244fd0dfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d52a70309d11b244fd0dfe/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject2/h2/3/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"b9d52a70309d11b244fd0dfe:40","filtered_window_id":"b9d52a70309d11b244fd0dfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d52a70309d11b244fd0dfe/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[219,220,221,222,223,224,225,226],"take":"subject2/h2/3/cam4","frame_ids":[219,220,221,222,223,224,225,226]} +{"filtered_tile_id":"b9d52a70309d11b244fd0dfe:48","filtered_window_id":"b9d52a70309d11b244fd0dfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d52a70309d11b244fd0dfe/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[227,228,229,230,231,232,233,234],"take":"subject2/h2/3/cam4","frame_ids":[227,228,229,230,231,232,233,234]} +{"filtered_tile_id":"b9d52a70309d11b244fd0dfe:52","filtered_window_id":"b9d52a70309d11b244fd0dfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/b9d52a70309d11b244fd0dfe/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject2/h2/3/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"ba01377a570eb2fef9642454:0","filtered_window_id":"ba01377a570eb2fef9642454","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba01377a570eb2fef9642454/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject2/k1/4/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"ba01377a570eb2fef9642454:8","filtered_window_id":"ba01377a570eb2fef9642454","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba01377a570eb2fef9642454/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject2/k1/4/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"ba01377a570eb2fef9642454:15","filtered_window_id":"ba01377a570eb2fef9642454","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba01377a570eb2fef9642454/native_gt.npz","filtered_start_offset":15,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject2/k1/4/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"ba1cb6b30e7ce4ba4f1bc402:0","filtered_window_id":"ba1cb6b30e7ce4ba4f1bc402","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba1cb6b30e7ce4ba4f1bc402/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[7,8,9,10,11,12,13,14],"take":"subject2/h2/2/cam4","frame_ids":[7,8,9,10,11,12,13,14]} +{"filtered_tile_id":"ba1cb6b30e7ce4ba4f1bc402:8","filtered_window_id":"ba1cb6b30e7ce4ba4f1bc402","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba1cb6b30e7ce4ba4f1bc402/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[15,16,17,18,19,20,21,22],"take":"subject2/h2/2/cam4","frame_ids":[15,16,17,18,19,20,21,22]} +{"filtered_tile_id":"ba1cb6b30e7ce4ba4f1bc402:16","filtered_window_id":"ba1cb6b30e7ce4ba4f1bc402","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba1cb6b30e7ce4ba4f1bc402/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[23,24,25,26,27,28,29,30],"take":"subject2/h2/2/cam4","frame_ids":[23,24,25,26,27,28,29,30]} +{"filtered_tile_id":"ba1cb6b30e7ce4ba4f1bc402:24","filtered_window_id":"ba1cb6b30e7ce4ba4f1bc402","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba1cb6b30e7ce4ba4f1bc402/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[31,32,33,34,35,36,37,38],"take":"subject2/h2/2/cam4","frame_ids":[31,32,33,34,35,36,37,38]} +{"filtered_tile_id":"ba1cb6b30e7ce4ba4f1bc402:32","filtered_window_id":"ba1cb6b30e7ce4ba4f1bc402","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba1cb6b30e7ce4ba4f1bc402/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[39,40,41,42,43,44,45,46],"take":"subject2/h2/2/cam4","frame_ids":[39,40,41,42,43,44,45,46]} +{"filtered_tile_id":"ba1cb6b30e7ce4ba4f1bc402:40","filtered_window_id":"ba1cb6b30e7ce4ba4f1bc402","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba1cb6b30e7ce4ba4f1bc402/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[47,48,49,50,51,52,53,54],"take":"subject2/h2/2/cam4","frame_ids":[47,48,49,50,51,52,53,54]} +{"filtered_tile_id":"ba1cb6b30e7ce4ba4f1bc402:48","filtered_window_id":"ba1cb6b30e7ce4ba4f1bc402","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba1cb6b30e7ce4ba4f1bc402/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[55,56,57,58,59,60,61,62],"take":"subject2/h2/2/cam4","frame_ids":[55,56,57,58,59,60,61,62]} +{"filtered_tile_id":"ba1cb6b30e7ce4ba4f1bc402:52","filtered_window_id":"ba1cb6b30e7ce4ba4f1bc402","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba1cb6b30e7ce4ba4f1bc402/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[59,60,61,62,63,64,65,66],"take":"subject2/h2/2/cam4","frame_ids":[59,60,61,62,63,64,65,66]} +{"filtered_tile_id":"ba2224b5ab55adb50c6f7b76:0","filtered_window_id":"ba2224b5ab55adb50c6f7b76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba2224b5ab55adb50c6f7b76/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[458,459,460,461,462,463,464,465],"take":"subject2/h2/2/cam4","frame_ids":[458,459,460,461,462,463,464,465]} +{"filtered_tile_id":"ba2224b5ab55adb50c6f7b76:8","filtered_window_id":"ba2224b5ab55adb50c6f7b76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba2224b5ab55adb50c6f7b76/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[466,467,468,469,470,471,472,473],"take":"subject2/h2/2/cam4","frame_ids":[466,467,468,469,470,471,472,473]} +{"filtered_tile_id":"ba2224b5ab55adb50c6f7b76:16","filtered_window_id":"ba2224b5ab55adb50c6f7b76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba2224b5ab55adb50c6f7b76/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[474,475,476,477,478,479,480,481],"take":"subject2/h2/2/cam4","frame_ids":[474,475,476,477,478,479,480,481]} +{"filtered_tile_id":"ba2224b5ab55adb50c6f7b76:24","filtered_window_id":"ba2224b5ab55adb50c6f7b76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba2224b5ab55adb50c6f7b76/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[482,483,484,485,486,487,488,489],"take":"subject2/h2/2/cam4","frame_ids":[482,483,484,485,486,487,488,489]} +{"filtered_tile_id":"ba2224b5ab55adb50c6f7b76:32","filtered_window_id":"ba2224b5ab55adb50c6f7b76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba2224b5ab55adb50c6f7b76/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[490,491,492,493,494,495,496,497],"take":"subject2/h2/2/cam4","frame_ids":[490,491,492,493,494,495,496,497]} +{"filtered_tile_id":"ba2224b5ab55adb50c6f7b76:40","filtered_window_id":"ba2224b5ab55adb50c6f7b76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba2224b5ab55adb50c6f7b76/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[498,499,500,501,502,503,504,505],"take":"subject2/h2/2/cam4","frame_ids":[498,499,500,501,502,503,504,505]} +{"filtered_tile_id":"ba2224b5ab55adb50c6f7b76:48","filtered_window_id":"ba2224b5ab55adb50c6f7b76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba2224b5ab55adb50c6f7b76/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[506,507,508,509,510,511,512,513],"take":"subject2/h2/2/cam4","frame_ids":[506,507,508,509,510,511,512,513]} +{"filtered_tile_id":"ba2224b5ab55adb50c6f7b76:52","filtered_window_id":"ba2224b5ab55adb50c6f7b76","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba2224b5ab55adb50c6f7b76/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject2/h2/2/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"ba3b82f6afe316bfdb23e655:0","filtered_window_id":"ba3b82f6afe316bfdb23e655","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba3b82f6afe316bfdb23e655/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject2/k2/3/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"ba3b82f6afe316bfdb23e655:8","filtered_window_id":"ba3b82f6afe316bfdb23e655","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba3b82f6afe316bfdb23e655/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject2/k2/3/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"ba3b82f6afe316bfdb23e655:16","filtered_window_id":"ba3b82f6afe316bfdb23e655","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba3b82f6afe316bfdb23e655/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject2/k2/3/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"ba3b82f6afe316bfdb23e655:24","filtered_window_id":"ba3b82f6afe316bfdb23e655","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba3b82f6afe316bfdb23e655/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject2/k2/3/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"ba3b82f6afe316bfdb23e655:32","filtered_window_id":"ba3b82f6afe316bfdb23e655","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba3b82f6afe316bfdb23e655/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject2/k2/3/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"ba3b82f6afe316bfdb23e655:40","filtered_window_id":"ba3b82f6afe316bfdb23e655","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba3b82f6afe316bfdb23e655/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject2/k2/3/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"ba3b82f6afe316bfdb23e655:48","filtered_window_id":"ba3b82f6afe316bfdb23e655","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba3b82f6afe316bfdb23e655/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[341,342,343,344,345,346,347,348],"take":"subject2/k2/3/cam4","frame_ids":[341,342,343,344,345,346,347,348]} +{"filtered_tile_id":"ba3b82f6afe316bfdb23e655:52","filtered_window_id":"ba3b82f6afe316bfdb23e655","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba3b82f6afe316bfdb23e655/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject2/k2/3/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"ba5145b72ddaab13a7e05a5b:0","filtered_window_id":"ba5145b72ddaab13a7e05a5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba5145b72ddaab13a7e05a5b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject1/h2/0/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"ba5145b72ddaab13a7e05a5b:8","filtered_window_id":"ba5145b72ddaab13a7e05a5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba5145b72ddaab13a7e05a5b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject1/h2/0/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"ba5145b72ddaab13a7e05a5b:16","filtered_window_id":"ba5145b72ddaab13a7e05a5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba5145b72ddaab13a7e05a5b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject1/h2/0/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"ba5145b72ddaab13a7e05a5b:24","filtered_window_id":"ba5145b72ddaab13a7e05a5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba5145b72ddaab13a7e05a5b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject1/h2/0/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"ba5145b72ddaab13a7e05a5b:32","filtered_window_id":"ba5145b72ddaab13a7e05a5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba5145b72ddaab13a7e05a5b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject1/h2/0/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"ba5145b72ddaab13a7e05a5b:40","filtered_window_id":"ba5145b72ddaab13a7e05a5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba5145b72ddaab13a7e05a5b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject1/h2/0/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"ba5145b72ddaab13a7e05a5b:48","filtered_window_id":"ba5145b72ddaab13a7e05a5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba5145b72ddaab13a7e05a5b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject1/h2/0/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"ba5145b72ddaab13a7e05a5b:52","filtered_window_id":"ba5145b72ddaab13a7e05a5b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba5145b72ddaab13a7e05a5b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject1/h2/0/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"ba53767e2c320adb6ac4ddfe:0","filtered_window_id":"ba53767e2c320adb6ac4ddfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba53767e2c320adb6ac4ddfe/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject1/k1/1/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"ba53767e2c320adb6ac4ddfe:8","filtered_window_id":"ba53767e2c320adb6ac4ddfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba53767e2c320adb6ac4ddfe/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject1/k1/1/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"ba53767e2c320adb6ac4ddfe:16","filtered_window_id":"ba53767e2c320adb6ac4ddfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba53767e2c320adb6ac4ddfe/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject1/k1/1/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"ba53767e2c320adb6ac4ddfe:24","filtered_window_id":"ba53767e2c320adb6ac4ddfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba53767e2c320adb6ac4ddfe/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[376,377,378,379,380,381,382,383],"take":"subject1/k1/1/cam4","frame_ids":[376,377,378,379,380,381,382,383]} +{"filtered_tile_id":"ba53767e2c320adb6ac4ddfe:32","filtered_window_id":"ba53767e2c320adb6ac4ddfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba53767e2c320adb6ac4ddfe/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject1/k1/1/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"ba53767e2c320adb6ac4ddfe:40","filtered_window_id":"ba53767e2c320adb6ac4ddfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba53767e2c320adb6ac4ddfe/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[392,393,394,395,396,397,398,399],"take":"subject1/k1/1/cam4","frame_ids":[392,393,394,395,396,397,398,399]} +{"filtered_tile_id":"ba53767e2c320adb6ac4ddfe:48","filtered_window_id":"ba53767e2c320adb6ac4ddfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba53767e2c320adb6ac4ddfe/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[400,401,402,403,404,405,406,407],"take":"subject1/k1/1/cam4","frame_ids":[400,401,402,403,404,405,406,407]} +{"filtered_tile_id":"ba53767e2c320adb6ac4ddfe:52","filtered_window_id":"ba53767e2c320adb6ac4ddfe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba53767e2c320adb6ac4ddfe/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject1/k1/1/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"ba6500e4a35786d2b08b2b67:0","filtered_window_id":"ba6500e4a35786d2b08b2b67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba6500e4a35786d2b08b2b67/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[379,380,381,382,383,384,385,386],"take":"subject3/k1/3/cam4","frame_ids":[379,380,381,382,383,384,385,386]} +{"filtered_tile_id":"ba6500e4a35786d2b08b2b67:8","filtered_window_id":"ba6500e4a35786d2b08b2b67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba6500e4a35786d2b08b2b67/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[387,388,389,390,391,392,393,394],"take":"subject3/k1/3/cam4","frame_ids":[387,388,389,390,391,392,393,394]} +{"filtered_tile_id":"ba6500e4a35786d2b08b2b67:16","filtered_window_id":"ba6500e4a35786d2b08b2b67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba6500e4a35786d2b08b2b67/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject3/k1/3/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"ba6500e4a35786d2b08b2b67:24","filtered_window_id":"ba6500e4a35786d2b08b2b67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba6500e4a35786d2b08b2b67/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject3/k1/3/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"ba6500e4a35786d2b08b2b67:32","filtered_window_id":"ba6500e4a35786d2b08b2b67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba6500e4a35786d2b08b2b67/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[411,412,413,414,415,416,417,418],"take":"subject3/k1/3/cam4","frame_ids":[411,412,413,414,415,416,417,418]} +{"filtered_tile_id":"ba6500e4a35786d2b08b2b67:40","filtered_window_id":"ba6500e4a35786d2b08b2b67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba6500e4a35786d2b08b2b67/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[419,420,421,422,423,424,425,426],"take":"subject3/k1/3/cam4","frame_ids":[419,420,421,422,423,424,425,426]} +{"filtered_tile_id":"ba6500e4a35786d2b08b2b67:48","filtered_window_id":"ba6500e4a35786d2b08b2b67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba6500e4a35786d2b08b2b67/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[427,428,429,430,431,432,433,434],"take":"subject3/k1/3/cam4","frame_ids":[427,428,429,430,431,432,433,434]} +{"filtered_tile_id":"ba6500e4a35786d2b08b2b67:52","filtered_window_id":"ba6500e4a35786d2b08b2b67","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba6500e4a35786d2b08b2b67/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[431,432,433,434,435,436,437,438],"take":"subject3/k1/3/cam4","frame_ids":[431,432,433,434,435,436,437,438]} +{"filtered_tile_id":"ba989eaeeed27d013aec6769:0","filtered_window_id":"ba989eaeeed27d013aec6769","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba989eaeeed27d013aec6769/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject2/k1/6/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"ba989eaeeed27d013aec6769:8","filtered_window_id":"ba989eaeeed27d013aec6769","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba989eaeeed27d013aec6769/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject2/k1/6/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"ba989eaeeed27d013aec6769:16","filtered_window_id":"ba989eaeeed27d013aec6769","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba989eaeeed27d013aec6769/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject2/k1/6/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"ba989eaeeed27d013aec6769:24","filtered_window_id":"ba989eaeeed27d013aec6769","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba989eaeeed27d013aec6769/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject2/k1/6/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"ba989eaeeed27d013aec6769:32","filtered_window_id":"ba989eaeeed27d013aec6769","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba989eaeeed27d013aec6769/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject2/k1/6/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"ba989eaeeed27d013aec6769:40","filtered_window_id":"ba989eaeeed27d013aec6769","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba989eaeeed27d013aec6769/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject2/k1/6/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"ba989eaeeed27d013aec6769:48","filtered_window_id":"ba989eaeeed27d013aec6769","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba989eaeeed27d013aec6769/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject2/k1/6/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"ba989eaeeed27d013aec6769:52","filtered_window_id":"ba989eaeeed27d013aec6769","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ba989eaeeed27d013aec6769/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[191,192,193,194,195,196,197,198],"take":"subject2/k1/6/cam4","frame_ids":[191,192,193,194,195,196,197,198]} +{"filtered_tile_id":"bb3214bdca04101fc3e17893:0","filtered_window_id":"bb3214bdca04101fc3e17893","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb3214bdca04101fc3e17893/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[312,313,314,315,316,317,318,319],"take":"subject2/k2/1/cam4","frame_ids":[312,313,314,315,316,317,318,319]} +{"filtered_tile_id":"bb3214bdca04101fc3e17893:8","filtered_window_id":"bb3214bdca04101fc3e17893","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb3214bdca04101fc3e17893/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[320,321,322,323,324,325,326,327],"take":"subject2/k2/1/cam4","frame_ids":[320,321,322,323,324,325,326,327]} +{"filtered_tile_id":"bb3214bdca04101fc3e17893:16","filtered_window_id":"bb3214bdca04101fc3e17893","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb3214bdca04101fc3e17893/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[328,329,330,331,332,333,334,335],"take":"subject2/k2/1/cam4","frame_ids":[328,329,330,331,332,333,334,335]} +{"filtered_tile_id":"bb3214bdca04101fc3e17893:24","filtered_window_id":"bb3214bdca04101fc3e17893","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb3214bdca04101fc3e17893/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[336,337,338,339,340,341,342,343],"take":"subject2/k2/1/cam4","frame_ids":[336,337,338,339,340,341,342,343]} +{"filtered_tile_id":"bb3214bdca04101fc3e17893:32","filtered_window_id":"bb3214bdca04101fc3e17893","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb3214bdca04101fc3e17893/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[344,345,346,347,348,349,350,351],"take":"subject2/k2/1/cam4","frame_ids":[344,345,346,347,348,349,350,351]} +{"filtered_tile_id":"bb3214bdca04101fc3e17893:40","filtered_window_id":"bb3214bdca04101fc3e17893","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb3214bdca04101fc3e17893/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject2/k2/1/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"bb3214bdca04101fc3e17893:48","filtered_window_id":"bb3214bdca04101fc3e17893","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb3214bdca04101fc3e17893/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject2/k2/1/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"bb3214bdca04101fc3e17893:52","filtered_window_id":"bb3214bdca04101fc3e17893","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb3214bdca04101fc3e17893/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject2/k2/1/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"bb9175b82b2d3d2f459b956f:0","filtered_window_id":"bb9175b82b2d3d2f459b956f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb9175b82b2d3d2f459b956f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject3/h1/0/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"bb9175b82b2d3d2f459b956f:8","filtered_window_id":"bb9175b82b2d3d2f459b956f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb9175b82b2d3d2f459b956f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject3/h1/0/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"bb9175b82b2d3d2f459b956f:16","filtered_window_id":"bb9175b82b2d3d2f459b956f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb9175b82b2d3d2f459b956f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject3/h1/0/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"bb9175b82b2d3d2f459b956f:24","filtered_window_id":"bb9175b82b2d3d2f459b956f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb9175b82b2d3d2f459b956f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject3/h1/0/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"bb9175b82b2d3d2f459b956f:32","filtered_window_id":"bb9175b82b2d3d2f459b956f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb9175b82b2d3d2f459b956f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject3/h1/0/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"bb9175b82b2d3d2f459b956f:40","filtered_window_id":"bb9175b82b2d3d2f459b956f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb9175b82b2d3d2f459b956f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject3/h1/0/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"bb9175b82b2d3d2f459b956f:48","filtered_window_id":"bb9175b82b2d3d2f459b956f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb9175b82b2d3d2f459b956f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject3/h1/0/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"bb9175b82b2d3d2f459b956f:52","filtered_window_id":"bb9175b82b2d3d2f459b956f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bb9175b82b2d3d2f459b956f/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject3/h1/0/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"bd04cc70ea8658957b8227a7:0","filtered_window_id":"bd04cc70ea8658957b8227a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd04cc70ea8658957b8227a7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[255,256,257,258,259,260,261,262],"take":"subject1/h1/3/cam4","frame_ids":[255,256,257,258,259,260,261,262]} +{"filtered_tile_id":"bd04cc70ea8658957b8227a7:8","filtered_window_id":"bd04cc70ea8658957b8227a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd04cc70ea8658957b8227a7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject1/h1/3/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"bd04cc70ea8658957b8227a7:16","filtered_window_id":"bd04cc70ea8658957b8227a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd04cc70ea8658957b8227a7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[271,272,273,274,275,276,277,278],"take":"subject1/h1/3/cam4","frame_ids":[271,272,273,274,275,276,277,278]} +{"filtered_tile_id":"bd04cc70ea8658957b8227a7:24","filtered_window_id":"bd04cc70ea8658957b8227a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd04cc70ea8658957b8227a7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[279,280,281,282,283,284,285,286],"take":"subject1/h1/3/cam4","frame_ids":[279,280,281,282,283,284,285,286]} +{"filtered_tile_id":"bd04cc70ea8658957b8227a7:32","filtered_window_id":"bd04cc70ea8658957b8227a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd04cc70ea8658957b8227a7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[287,288,289,290,291,292,293,294],"take":"subject1/h1/3/cam4","frame_ids":[287,288,289,290,291,292,293,294]} +{"filtered_tile_id":"bd04cc70ea8658957b8227a7:40","filtered_window_id":"bd04cc70ea8658957b8227a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd04cc70ea8658957b8227a7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[295,296,297,298,299,300,301,302],"take":"subject1/h1/3/cam4","frame_ids":[295,296,297,298,299,300,301,302]} +{"filtered_tile_id":"bd04cc70ea8658957b8227a7:48","filtered_window_id":"bd04cc70ea8658957b8227a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd04cc70ea8658957b8227a7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[303,304,305,306,307,308,309,310],"take":"subject1/h1/3/cam4","frame_ids":[303,304,305,306,307,308,309,310]} +{"filtered_tile_id":"bd04cc70ea8658957b8227a7:52","filtered_window_id":"bd04cc70ea8658957b8227a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd04cc70ea8658957b8227a7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[307,308,309,310,311,312,313,314],"take":"subject1/h1/3/cam4","frame_ids":[307,308,309,310,311,312,313,314]} +{"filtered_tile_id":"bd6ca933b2ec33cd7ee1df55:0","filtered_window_id":"bd6ca933b2ec33cd7ee1df55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd6ca933b2ec33cd7ee1df55/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject3/k1/7/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"bd6ca933b2ec33cd7ee1df55:8","filtered_window_id":"bd6ca933b2ec33cd7ee1df55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd6ca933b2ec33cd7ee1df55/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject3/k1/7/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"bd6ca933b2ec33cd7ee1df55:16","filtered_window_id":"bd6ca933b2ec33cd7ee1df55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd6ca933b2ec33cd7ee1df55/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject3/k1/7/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"bd6ca933b2ec33cd7ee1df55:24","filtered_window_id":"bd6ca933b2ec33cd7ee1df55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd6ca933b2ec33cd7ee1df55/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject3/k1/7/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"bd6ca933b2ec33cd7ee1df55:32","filtered_window_id":"bd6ca933b2ec33cd7ee1df55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd6ca933b2ec33cd7ee1df55/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[341,342,343,344,345,346,347,348],"take":"subject3/k1/7/cam4","frame_ids":[341,342,343,344,345,346,347,348]} +{"filtered_tile_id":"bd6ca933b2ec33cd7ee1df55:40","filtered_window_id":"bd6ca933b2ec33cd7ee1df55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd6ca933b2ec33cd7ee1df55/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[349,350,351,352,353,354,355,356],"take":"subject3/k1/7/cam4","frame_ids":[349,350,351,352,353,354,355,356]} +{"filtered_tile_id":"bd6ca933b2ec33cd7ee1df55:48","filtered_window_id":"bd6ca933b2ec33cd7ee1df55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd6ca933b2ec33cd7ee1df55/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject3/k1/7/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"bd6ca933b2ec33cd7ee1df55:52","filtered_window_id":"bd6ca933b2ec33cd7ee1df55","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bd6ca933b2ec33cd7ee1df55/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[361,362,363,364,365,366,367,368],"take":"subject3/k1/7/cam4","frame_ids":[361,362,363,364,365,366,367,368]} +{"filtered_tile_id":"be6d520070492271f6d362e8:0","filtered_window_id":"be6d520070492271f6d362e8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be6d520070492271f6d362e8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[970,971,972,973,974,975,976,977],"take":"subject1/o2/2/cam4","frame_ids":[970,971,972,973,974,975,976,977]} +{"filtered_tile_id":"be6d520070492271f6d362e8:8","filtered_window_id":"be6d520070492271f6d362e8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be6d520070492271f6d362e8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[978,979,980,981,982,983,984,985],"take":"subject1/o2/2/cam4","frame_ids":[978,979,980,981,982,983,984,985]} +{"filtered_tile_id":"be6d520070492271f6d362e8:15","filtered_window_id":"be6d520070492271f6d362e8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be6d520070492271f6d362e8/native_gt.npz","filtered_start_offset":15,"expected_frame_ids":[985,986,987,988,989,990,991,992],"take":"subject1/o2/2/cam4","frame_ids":[985,986,987,988,989,990,991,992]} +{"filtered_tile_id":"be8c7e4c6ba4ccfbfcd54f52:0","filtered_window_id":"be8c7e4c6ba4ccfbfcd54f52","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c7e4c6ba4ccfbfcd54f52/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/k2/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"be8c7e4c6ba4ccfbfcd54f52:8","filtered_window_id":"be8c7e4c6ba4ccfbfcd54f52","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c7e4c6ba4ccfbfcd54f52/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/k2/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"be8c7e4c6ba4ccfbfcd54f52:16","filtered_window_id":"be8c7e4c6ba4ccfbfcd54f52","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c7e4c6ba4ccfbfcd54f52/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k2/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"be8c7e4c6ba4ccfbfcd54f52:24","filtered_window_id":"be8c7e4c6ba4ccfbfcd54f52","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c7e4c6ba4ccfbfcd54f52/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k2/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"be8c7e4c6ba4ccfbfcd54f52:32","filtered_window_id":"be8c7e4c6ba4ccfbfcd54f52","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c7e4c6ba4ccfbfcd54f52/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k2/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"be8c7e4c6ba4ccfbfcd54f52:39","filtered_window_id":"be8c7e4c6ba4ccfbfcd54f52","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c7e4c6ba4ccfbfcd54f52/native_gt.npz","filtered_start_offset":39,"expected_frame_ids":[39,40,41,42,43,44,45,46],"take":"subject1/k2/1/cam4","frame_ids":[39,40,41,42,43,44,45,46]} +{"filtered_tile_id":"be8c884f303bdc85e98d4095:0","filtered_window_id":"be8c884f303bdc85e98d4095","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c884f303bdc85e98d4095/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject3/h2/6/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"be8c884f303bdc85e98d4095:8","filtered_window_id":"be8c884f303bdc85e98d4095","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c884f303bdc85e98d4095/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[59,60,61,62,63,64,65,66],"take":"subject3/h2/6/cam4","frame_ids":[59,60,61,62,63,64,65,66]} +{"filtered_tile_id":"be8c884f303bdc85e98d4095:16","filtered_window_id":"be8c884f303bdc85e98d4095","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c884f303bdc85e98d4095/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject3/h2/6/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"be8c884f303bdc85e98d4095:24","filtered_window_id":"be8c884f303bdc85e98d4095","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c884f303bdc85e98d4095/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject3/h2/6/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"be8c884f303bdc85e98d4095:32","filtered_window_id":"be8c884f303bdc85e98d4095","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c884f303bdc85e98d4095/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject3/h2/6/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"be8c884f303bdc85e98d4095:40","filtered_window_id":"be8c884f303bdc85e98d4095","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c884f303bdc85e98d4095/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject3/h2/6/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"be8c884f303bdc85e98d4095:48","filtered_window_id":"be8c884f303bdc85e98d4095","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c884f303bdc85e98d4095/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject3/h2/6/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"be8c884f303bdc85e98d4095:52","filtered_window_id":"be8c884f303bdc85e98d4095","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/be8c884f303bdc85e98d4095/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[103,104,105,106,107,108,109,110],"take":"subject3/h2/6/cam4","frame_ids":[103,104,105,106,107,108,109,110]} +{"filtered_tile_id":"bedd27dac893ecdf869be528:0","filtered_window_id":"bedd27dac893ecdf869be528","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bedd27dac893ecdf869be528/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject2/h2/6/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"bedd27dac893ecdf869be528:8","filtered_window_id":"bedd27dac893ecdf869be528","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bedd27dac893ecdf869be528/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject2/h2/6/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"bedd27dac893ecdf869be528:16","filtered_window_id":"bedd27dac893ecdf869be528","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bedd27dac893ecdf869be528/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject2/h2/6/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"bedd27dac893ecdf869be528:24","filtered_window_id":"bedd27dac893ecdf869be528","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bedd27dac893ecdf869be528/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject2/h2/6/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"bedd27dac893ecdf869be528:32","filtered_window_id":"bedd27dac893ecdf869be528","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bedd27dac893ecdf869be528/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject2/h2/6/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"bedd27dac893ecdf869be528:40","filtered_window_id":"bedd27dac893ecdf869be528","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bedd27dac893ecdf869be528/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject2/h2/6/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"bedd27dac893ecdf869be528:48","filtered_window_id":"bedd27dac893ecdf869be528","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bedd27dac893ecdf869be528/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject2/h2/6/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"bedd27dac893ecdf869be528:52","filtered_window_id":"bedd27dac893ecdf869be528","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bedd27dac893ecdf869be528/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject2/h2/6/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"bef88e56da493cc1462a4053:0","filtered_window_id":"bef88e56da493cc1462a4053","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bef88e56da493cc1462a4053/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h1/0/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"bef88e56da493cc1462a4053:8","filtered_window_id":"bef88e56da493cc1462a4053","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bef88e56da493cc1462a4053/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h1/0/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"bef88e56da493cc1462a4053:16","filtered_window_id":"bef88e56da493cc1462a4053","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bef88e56da493cc1462a4053/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h1/0/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"bef88e56da493cc1462a4053:24","filtered_window_id":"bef88e56da493cc1462a4053","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bef88e56da493cc1462a4053/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h1/0/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"bef88e56da493cc1462a4053:32","filtered_window_id":"bef88e56da493cc1462a4053","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bef88e56da493cc1462a4053/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h1/0/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"bef88e56da493cc1462a4053:40","filtered_window_id":"bef88e56da493cc1462a4053","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bef88e56da493cc1462a4053/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/h1/0/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"bef88e56da493cc1462a4053:48","filtered_window_id":"bef88e56da493cc1462a4053","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bef88e56da493cc1462a4053/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/h1/0/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"bef88e56da493cc1462a4053:52","filtered_window_id":"bef88e56da493cc1462a4053","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bef88e56da493cc1462a4053/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/h1/0/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"bfa5ef6b078fbc28aabf6c3b:0","filtered_window_id":"bfa5ef6b078fbc28aabf6c3b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfa5ef6b078fbc28aabf6c3b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject3/h2/0/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"bfa5ef6b078fbc28aabf6c3b:8","filtered_window_id":"bfa5ef6b078fbc28aabf6c3b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfa5ef6b078fbc28aabf6c3b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject3/h2/0/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"bfa5ef6b078fbc28aabf6c3b:16","filtered_window_id":"bfa5ef6b078fbc28aabf6c3b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfa5ef6b078fbc28aabf6c3b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject3/h2/0/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"bfa5ef6b078fbc28aabf6c3b:24","filtered_window_id":"bfa5ef6b078fbc28aabf6c3b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfa5ef6b078fbc28aabf6c3b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject3/h2/0/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"bfa5ef6b078fbc28aabf6c3b:32","filtered_window_id":"bfa5ef6b078fbc28aabf6c3b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfa5ef6b078fbc28aabf6c3b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject3/h2/0/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"bfa5ef6b078fbc28aabf6c3b:40","filtered_window_id":"bfa5ef6b078fbc28aabf6c3b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfa5ef6b078fbc28aabf6c3b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject3/h2/0/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"bfa5ef6b078fbc28aabf6c3b:48","filtered_window_id":"bfa5ef6b078fbc28aabf6c3b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfa5ef6b078fbc28aabf6c3b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject3/h2/0/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"bfa5ef6b078fbc28aabf6c3b:52","filtered_window_id":"bfa5ef6b078fbc28aabf6c3b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfa5ef6b078fbc28aabf6c3b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject3/h2/0/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"bfe81bf68a23035ff95a504d:0","filtered_window_id":"bfe81bf68a23035ff95a504d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe81bf68a23035ff95a504d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[600,601,602,603,604,605,606,607],"take":"subject1/k1/3/cam4","frame_ids":[600,601,602,603,604,605,606,607]} +{"filtered_tile_id":"bfe81bf68a23035ff95a504d:8","filtered_window_id":"bfe81bf68a23035ff95a504d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe81bf68a23035ff95a504d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[608,609,610,611,612,613,614,615],"take":"subject1/k1/3/cam4","frame_ids":[608,609,610,611,612,613,614,615]} +{"filtered_tile_id":"bfe81bf68a23035ff95a504d:16","filtered_window_id":"bfe81bf68a23035ff95a504d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe81bf68a23035ff95a504d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[616,617,618,619,620,621,622,623],"take":"subject1/k1/3/cam4","frame_ids":[616,617,618,619,620,621,622,623]} +{"filtered_tile_id":"bfe81bf68a23035ff95a504d:24","filtered_window_id":"bfe81bf68a23035ff95a504d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe81bf68a23035ff95a504d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[624,625,626,627,628,629,630,631],"take":"subject1/k1/3/cam4","frame_ids":[624,625,626,627,628,629,630,631]} +{"filtered_tile_id":"bfe81bf68a23035ff95a504d:32","filtered_window_id":"bfe81bf68a23035ff95a504d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe81bf68a23035ff95a504d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[632,633,634,635,636,637,638,639],"take":"subject1/k1/3/cam4","frame_ids":[632,633,634,635,636,637,638,639]} +{"filtered_tile_id":"bfe81bf68a23035ff95a504d:40","filtered_window_id":"bfe81bf68a23035ff95a504d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe81bf68a23035ff95a504d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[640,641,642,643,644,645,646,647],"take":"subject1/k1/3/cam4","frame_ids":[640,641,642,643,644,645,646,647]} +{"filtered_tile_id":"bfe81bf68a23035ff95a504d:48","filtered_window_id":"bfe81bf68a23035ff95a504d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe81bf68a23035ff95a504d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[648,649,650,651,652,653,654,655],"take":"subject1/k1/3/cam4","frame_ids":[648,649,650,651,652,653,654,655]} +{"filtered_tile_id":"bfe81bf68a23035ff95a504d:52","filtered_window_id":"bfe81bf68a23035ff95a504d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe81bf68a23035ff95a504d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[652,653,654,655,656,657,658,659],"take":"subject1/k1/3/cam4","frame_ids":[652,653,654,655,656,657,658,659]} +{"filtered_tile_id":"bfe9182c24c0fc50819568bd:0","filtered_window_id":"bfe9182c24c0fc50819568bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe9182c24c0fc50819568bd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject2/o2/6/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"bfe9182c24c0fc50819568bd:8","filtered_window_id":"bfe9182c24c0fc50819568bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe9182c24c0fc50819568bd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject2/o2/6/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"bfe9182c24c0fc50819568bd:16","filtered_window_id":"bfe9182c24c0fc50819568bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe9182c24c0fc50819568bd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject2/o2/6/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"bfe9182c24c0fc50819568bd:24","filtered_window_id":"bfe9182c24c0fc50819568bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe9182c24c0fc50819568bd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject2/o2/6/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"bfe9182c24c0fc50819568bd:32","filtered_window_id":"bfe9182c24c0fc50819568bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe9182c24c0fc50819568bd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject2/o2/6/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"bfe9182c24c0fc50819568bd:40","filtered_window_id":"bfe9182c24c0fc50819568bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe9182c24c0fc50819568bd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject2/o2/6/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"bfe9182c24c0fc50819568bd:48","filtered_window_id":"bfe9182c24c0fc50819568bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe9182c24c0fc50819568bd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject2/o2/6/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"bfe9182c24c0fc50819568bd:52","filtered_window_id":"bfe9182c24c0fc50819568bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bfe9182c24c0fc50819568bd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject2/o2/6/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"bff546638d5bc002bac8b9b0:0","filtered_window_id":"bff546638d5bc002bac8b9b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bff546638d5bc002bac8b9b0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[156,157,158,159,160,161,162,163],"take":"subject1/h1/3/cam4","frame_ids":[156,157,158,159,160,161,162,163]} +{"filtered_tile_id":"bff546638d5bc002bac8b9b0:8","filtered_window_id":"bff546638d5bc002bac8b9b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bff546638d5bc002bac8b9b0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[164,165,166,167,168,169,170,171],"take":"subject1/h1/3/cam4","frame_ids":[164,165,166,167,168,169,170,171]} +{"filtered_tile_id":"bff546638d5bc002bac8b9b0:16","filtered_window_id":"bff546638d5bc002bac8b9b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bff546638d5bc002bac8b9b0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject1/h1/3/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"bff546638d5bc002bac8b9b0:24","filtered_window_id":"bff546638d5bc002bac8b9b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bff546638d5bc002bac8b9b0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject1/h1/3/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"bff546638d5bc002bac8b9b0:32","filtered_window_id":"bff546638d5bc002bac8b9b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bff546638d5bc002bac8b9b0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject1/h1/3/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"bff546638d5bc002bac8b9b0:40","filtered_window_id":"bff546638d5bc002bac8b9b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bff546638d5bc002bac8b9b0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[196,197,198,199,200,201,202,203],"take":"subject1/h1/3/cam4","frame_ids":[196,197,198,199,200,201,202,203]} +{"filtered_tile_id":"bff546638d5bc002bac8b9b0:48","filtered_window_id":"bff546638d5bc002bac8b9b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bff546638d5bc002bac8b9b0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[204,205,206,207,208,209,210,211],"take":"subject1/h1/3/cam4","frame_ids":[204,205,206,207,208,209,210,211]} +{"filtered_tile_id":"bff546638d5bc002bac8b9b0:52","filtered_window_id":"bff546638d5bc002bac8b9b0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/bff546638d5bc002bac8b9b0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[208,209,210,211,212,213,214,215],"take":"subject1/h1/3/cam4","frame_ids":[208,209,210,211,212,213,214,215]} +{"filtered_tile_id":"c0727aed8635c05facc87a37:0","filtered_window_id":"c0727aed8635c05facc87a37","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c0727aed8635c05facc87a37/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject2/k1/6/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"c0727aed8635c05facc87a37:8","filtered_window_id":"c0727aed8635c05facc87a37","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c0727aed8635c05facc87a37/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject2/k1/6/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"c0727aed8635c05facc87a37:16","filtered_window_id":"c0727aed8635c05facc87a37","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c0727aed8635c05facc87a37/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[373,374,375,376,377,378,379,380],"take":"subject2/k1/6/cam4","frame_ids":[373,374,375,376,377,378,379,380]} +{"filtered_tile_id":"c0727aed8635c05facc87a37:24","filtered_window_id":"c0727aed8635c05facc87a37","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c0727aed8635c05facc87a37/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[381,382,383,384,385,386,387,388],"take":"subject2/k1/6/cam4","frame_ids":[381,382,383,384,385,386,387,388]} +{"filtered_tile_id":"c0727aed8635c05facc87a37:32","filtered_window_id":"c0727aed8635c05facc87a37","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c0727aed8635c05facc87a37/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[389,390,391,392,393,394,395,396],"take":"subject2/k1/6/cam4","frame_ids":[389,390,391,392,393,394,395,396]} +{"filtered_tile_id":"c0727aed8635c05facc87a37:38","filtered_window_id":"c0727aed8635c05facc87a37","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c0727aed8635c05facc87a37/native_gt.npz","filtered_start_offset":38,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject2/k1/6/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"c0e28f81e115b2c10986fc6e:0","filtered_window_id":"c0e28f81e115b2c10986fc6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c0e28f81e115b2c10986fc6e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[558,559,560,561,562,563,564,565],"take":"subject2/h1/5/cam4","frame_ids":[558,559,560,561,562,563,564,565]} +{"filtered_tile_id":"c0e28f81e115b2c10986fc6e:8","filtered_window_id":"c0e28f81e115b2c10986fc6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c0e28f81e115b2c10986fc6e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[566,567,568,569,570,571,572,573],"take":"subject2/h1/5/cam4","frame_ids":[566,567,568,569,570,571,572,573]} +{"filtered_tile_id":"c10493c92733290d5bd8005a:0","filtered_window_id":"c10493c92733290d5bd8005a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c10493c92733290d5bd8005a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject2/k1/6/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"c10493c92733290d5bd8005a:8","filtered_window_id":"c10493c92733290d5bd8005a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c10493c92733290d5bd8005a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject2/k1/6/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"c10493c92733290d5bd8005a:16","filtered_window_id":"c10493c92733290d5bd8005a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c10493c92733290d5bd8005a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[468,469,470,471,472,473,474,475],"take":"subject2/k1/6/cam4","frame_ids":[468,469,470,471,472,473,474,475]} +{"filtered_tile_id":"c10493c92733290d5bd8005a:24","filtered_window_id":"c10493c92733290d5bd8005a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c10493c92733290d5bd8005a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[476,477,478,479,480,481,482,483],"take":"subject2/k1/6/cam4","frame_ids":[476,477,478,479,480,481,482,483]} +{"filtered_tile_id":"c10493c92733290d5bd8005a:32","filtered_window_id":"c10493c92733290d5bd8005a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c10493c92733290d5bd8005a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[484,485,486,487,488,489,490,491],"take":"subject2/k1/6/cam4","frame_ids":[484,485,486,487,488,489,490,491]} +{"filtered_tile_id":"c10493c92733290d5bd8005a:40","filtered_window_id":"c10493c92733290d5bd8005a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c10493c92733290d5bd8005a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[492,493,494,495,496,497,498,499],"take":"subject2/k1/6/cam4","frame_ids":[492,493,494,495,496,497,498,499]} +{"filtered_tile_id":"c10493c92733290d5bd8005a:48","filtered_window_id":"c10493c92733290d5bd8005a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c10493c92733290d5bd8005a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[500,501,502,503,504,505,506,507],"take":"subject2/k1/6/cam4","frame_ids":[500,501,502,503,504,505,506,507]} +{"filtered_tile_id":"c10493c92733290d5bd8005a:52","filtered_window_id":"c10493c92733290d5bd8005a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c10493c92733290d5bd8005a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject2/k1/6/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"c1152dbfe286aa4103e9a875:0","filtered_window_id":"c1152dbfe286aa4103e9a875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c1152dbfe286aa4103e9a875/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[692,693,694,695,696,697,698,699],"take":"subject2/k1/6/cam4","frame_ids":[692,693,694,695,696,697,698,699]} +{"filtered_tile_id":"c1152dbfe286aa4103e9a875:8","filtered_window_id":"c1152dbfe286aa4103e9a875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c1152dbfe286aa4103e9a875/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[700,701,702,703,704,705,706,707],"take":"subject2/k1/6/cam4","frame_ids":[700,701,702,703,704,705,706,707]} +{"filtered_tile_id":"c1152dbfe286aa4103e9a875:16","filtered_window_id":"c1152dbfe286aa4103e9a875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c1152dbfe286aa4103e9a875/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[708,709,710,711,712,713,714,715],"take":"subject2/k1/6/cam4","frame_ids":[708,709,710,711,712,713,714,715]} +{"filtered_tile_id":"c1152dbfe286aa4103e9a875:24","filtered_window_id":"c1152dbfe286aa4103e9a875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c1152dbfe286aa4103e9a875/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[716,717,718,719,720,721,722,723],"take":"subject2/k1/6/cam4","frame_ids":[716,717,718,719,720,721,722,723]} +{"filtered_tile_id":"c1152dbfe286aa4103e9a875:32","filtered_window_id":"c1152dbfe286aa4103e9a875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c1152dbfe286aa4103e9a875/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[724,725,726,727,728,729,730,731],"take":"subject2/k1/6/cam4","frame_ids":[724,725,726,727,728,729,730,731]} +{"filtered_tile_id":"c1152dbfe286aa4103e9a875:40","filtered_window_id":"c1152dbfe286aa4103e9a875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c1152dbfe286aa4103e9a875/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[732,733,734,735,736,737,738,739],"take":"subject2/k1/6/cam4","frame_ids":[732,733,734,735,736,737,738,739]} +{"filtered_tile_id":"c1152dbfe286aa4103e9a875:48","filtered_window_id":"c1152dbfe286aa4103e9a875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c1152dbfe286aa4103e9a875/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[740,741,742,743,744,745,746,747],"take":"subject2/k1/6/cam4","frame_ids":[740,741,742,743,744,745,746,747]} +{"filtered_tile_id":"c1152dbfe286aa4103e9a875:52","filtered_window_id":"c1152dbfe286aa4103e9a875","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c1152dbfe286aa4103e9a875/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[744,745,746,747,748,749,750,751],"take":"subject2/k1/6/cam4","frame_ids":[744,745,746,747,748,749,750,751]} +{"filtered_tile_id":"c30308beaaa8b32b52c21203:0","filtered_window_id":"c30308beaaa8b32b52c21203","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c30308beaaa8b32b52c21203/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject3/h1/1/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"c30308beaaa8b32b52c21203:8","filtered_window_id":"c30308beaaa8b32b52c21203","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c30308beaaa8b32b52c21203/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject3/h1/1/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"c30308beaaa8b32b52c21203:16","filtered_window_id":"c30308beaaa8b32b52c21203","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c30308beaaa8b32b52c21203/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject3/h1/1/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"c30308beaaa8b32b52c21203:24","filtered_window_id":"c30308beaaa8b32b52c21203","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c30308beaaa8b32b52c21203/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject3/h1/1/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"c30308beaaa8b32b52c21203:32","filtered_window_id":"c30308beaaa8b32b52c21203","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c30308beaaa8b32b52c21203/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject3/h1/1/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"c30308beaaa8b32b52c21203:40","filtered_window_id":"c30308beaaa8b32b52c21203","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c30308beaaa8b32b52c21203/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject3/h1/1/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"c30308beaaa8b32b52c21203:48","filtered_window_id":"c30308beaaa8b32b52c21203","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c30308beaaa8b32b52c21203/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject3/h1/1/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"c30308beaaa8b32b52c21203:52","filtered_window_id":"c30308beaaa8b32b52c21203","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c30308beaaa8b32b52c21203/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject3/h1/1/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"c3040d6462594e73a3405007:0","filtered_window_id":"c3040d6462594e73a3405007","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3040d6462594e73a3405007/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[543,544,545,546,547,548,549,550],"take":"subject1/k1/1/cam4","frame_ids":[543,544,545,546,547,548,549,550]} +{"filtered_tile_id":"c3040d6462594e73a3405007:8","filtered_window_id":"c3040d6462594e73a3405007","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3040d6462594e73a3405007/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[551,552,553,554,555,556,557,558],"take":"subject1/k1/1/cam4","frame_ids":[551,552,553,554,555,556,557,558]} +{"filtered_tile_id":"c3040d6462594e73a3405007:16","filtered_window_id":"c3040d6462594e73a3405007","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3040d6462594e73a3405007/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[559,560,561,562,563,564,565,566],"take":"subject1/k1/1/cam4","frame_ids":[559,560,561,562,563,564,565,566]} +{"filtered_tile_id":"c3040d6462594e73a3405007:24","filtered_window_id":"c3040d6462594e73a3405007","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3040d6462594e73a3405007/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[567,568,569,570,571,572,573,574],"take":"subject1/k1/1/cam4","frame_ids":[567,568,569,570,571,572,573,574]} +{"filtered_tile_id":"c3040d6462594e73a3405007:32","filtered_window_id":"c3040d6462594e73a3405007","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3040d6462594e73a3405007/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[575,576,577,578,579,580,581,582],"take":"subject1/k1/1/cam4","frame_ids":[575,576,577,578,579,580,581,582]} +{"filtered_tile_id":"c3040d6462594e73a3405007:40","filtered_window_id":"c3040d6462594e73a3405007","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3040d6462594e73a3405007/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[583,584,585,586,587,588,589,590],"take":"subject1/k1/1/cam4","frame_ids":[583,584,585,586,587,588,589,590]} +{"filtered_tile_id":"c3040d6462594e73a3405007:48","filtered_window_id":"c3040d6462594e73a3405007","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3040d6462594e73a3405007/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[591,592,593,594,595,596,597,598],"take":"subject1/k1/1/cam4","frame_ids":[591,592,593,594,595,596,597,598]} +{"filtered_tile_id":"c3040d6462594e73a3405007:52","filtered_window_id":"c3040d6462594e73a3405007","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3040d6462594e73a3405007/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[595,596,597,598,599,600,601,602],"take":"subject1/k1/1/cam4","frame_ids":[595,596,597,598,599,600,601,602]} +{"filtered_tile_id":"c314a650d057855356f17acb:0","filtered_window_id":"c314a650d057855356f17acb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c314a650d057855356f17acb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject2/k2/4/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"c314a650d057855356f17acb:8","filtered_window_id":"c314a650d057855356f17acb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c314a650d057855356f17acb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[374,375,376,377,378,379,380,381],"take":"subject2/k2/4/cam4","frame_ids":[374,375,376,377,378,379,380,381]} +{"filtered_tile_id":"c314a650d057855356f17acb:16","filtered_window_id":"c314a650d057855356f17acb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c314a650d057855356f17acb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[382,383,384,385,386,387,388,389],"take":"subject2/k2/4/cam4","frame_ids":[382,383,384,385,386,387,388,389]} +{"filtered_tile_id":"c314a650d057855356f17acb:22","filtered_window_id":"c314a650d057855356f17acb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c314a650d057855356f17acb/native_gt.npz","filtered_start_offset":22,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject2/k2/4/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"c3a947cc518d23fb6a48e8cd:0","filtered_window_id":"c3a947cc518d23fb6a48e8cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3a947cc518d23fb6a48e8cd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject3/k1/7/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"c3a947cc518d23fb6a48e8cd:8","filtered_window_id":"c3a947cc518d23fb6a48e8cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3a947cc518d23fb6a48e8cd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[433,434,435,436,437,438,439,440],"take":"subject3/k1/7/cam4","frame_ids":[433,434,435,436,437,438,439,440]} +{"filtered_tile_id":"c3a947cc518d23fb6a48e8cd:16","filtered_window_id":"c3a947cc518d23fb6a48e8cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3a947cc518d23fb6a48e8cd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject3/k1/7/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"c3a947cc518d23fb6a48e8cd:24","filtered_window_id":"c3a947cc518d23fb6a48e8cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3a947cc518d23fb6a48e8cd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject3/k1/7/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"c3a947cc518d23fb6a48e8cd:32","filtered_window_id":"c3a947cc518d23fb6a48e8cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3a947cc518d23fb6a48e8cd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject3/k1/7/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"c3a947cc518d23fb6a48e8cd:40","filtered_window_id":"c3a947cc518d23fb6a48e8cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3a947cc518d23fb6a48e8cd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject3/k1/7/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"c3a947cc518d23fb6a48e8cd:48","filtered_window_id":"c3a947cc518d23fb6a48e8cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3a947cc518d23fb6a48e8cd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject3/k1/7/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"c3a947cc518d23fb6a48e8cd:52","filtered_window_id":"c3a947cc518d23fb6a48e8cd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3a947cc518d23fb6a48e8cd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[477,478,479,480,481,482,483,484],"take":"subject3/k1/7/cam4","frame_ids":[477,478,479,480,481,482,483,484]} +{"filtered_tile_id":"c3f32a3c7d6851aa88f95e06:0","filtered_window_id":"c3f32a3c7d6851aa88f95e06","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3f32a3c7d6851aa88f95e06/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[355,356,357,358,359,360,361,362],"take":"subject2/o2/1/cam4","frame_ids":[355,356,357,358,359,360,361,362]} +{"filtered_tile_id":"c3f32a3c7d6851aa88f95e06:8","filtered_window_id":"c3f32a3c7d6851aa88f95e06","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3f32a3c7d6851aa88f95e06/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[363,364,365,366,367,368,369,370],"take":"subject2/o2/1/cam4","frame_ids":[363,364,365,366,367,368,369,370]} +{"filtered_tile_id":"c3f32a3c7d6851aa88f95e06:16","filtered_window_id":"c3f32a3c7d6851aa88f95e06","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3f32a3c7d6851aa88f95e06/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[371,372,373,374,375,376,377,378],"take":"subject2/o2/1/cam4","frame_ids":[371,372,373,374,375,376,377,378]} +{"filtered_tile_id":"c3f32a3c7d6851aa88f95e06:24","filtered_window_id":"c3f32a3c7d6851aa88f95e06","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3f32a3c7d6851aa88f95e06/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[379,380,381,382,383,384,385,386],"take":"subject2/o2/1/cam4","frame_ids":[379,380,381,382,383,384,385,386]} +{"filtered_tile_id":"c3f32a3c7d6851aa88f95e06:32","filtered_window_id":"c3f32a3c7d6851aa88f95e06","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3f32a3c7d6851aa88f95e06/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[387,388,389,390,391,392,393,394],"take":"subject2/o2/1/cam4","frame_ids":[387,388,389,390,391,392,393,394]} +{"filtered_tile_id":"c3f32a3c7d6851aa88f95e06:40","filtered_window_id":"c3f32a3c7d6851aa88f95e06","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3f32a3c7d6851aa88f95e06/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject2/o2/1/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"c3f32a3c7d6851aa88f95e06:48","filtered_window_id":"c3f32a3c7d6851aa88f95e06","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3f32a3c7d6851aa88f95e06/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject2/o2/1/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"c3f32a3c7d6851aa88f95e06:52","filtered_window_id":"c3f32a3c7d6851aa88f95e06","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c3f32a3c7d6851aa88f95e06/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject2/o2/1/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"c425bb85b5a560046c23c170:0","filtered_window_id":"c425bb85b5a560046c23c170","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c425bb85b5a560046c23c170/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject1/k2/5/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"c425bb85b5a560046c23c170:6","filtered_window_id":"c425bb85b5a560046c23c170","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c425bb85b5a560046c23c170/native_gt.npz","filtered_start_offset":6,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject1/k2/5/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"c475a51364b038ba512ed6dd:0","filtered_window_id":"c475a51364b038ba512ed6dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c475a51364b038ba512ed6dd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject3/h1/7/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"c475a51364b038ba512ed6dd:6","filtered_window_id":"c475a51364b038ba512ed6dd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c475a51364b038ba512ed6dd/native_gt.npz","filtered_start_offset":6,"expected_frame_ids":[66,67,68,69,70,71,72,73],"take":"subject3/h1/7/cam4","frame_ids":[66,67,68,69,70,71,72,73]} +{"filtered_tile_id":"c5027d6ada742f56c70745c5:0","filtered_window_id":"c5027d6ada742f56c70745c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5027d6ada742f56c70745c5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject2/h2/2/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"c5027d6ada742f56c70745c5:8","filtered_window_id":"c5027d6ada742f56c70745c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5027d6ada742f56c70745c5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject2/h2/2/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"c5027d6ada742f56c70745c5:16","filtered_window_id":"c5027d6ada742f56c70745c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5027d6ada742f56c70745c5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject2/h2/2/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"c5027d6ada742f56c70745c5:24","filtered_window_id":"c5027d6ada742f56c70745c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5027d6ada742f56c70745c5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject2/h2/2/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"c5027d6ada742f56c70745c5:32","filtered_window_id":"c5027d6ada742f56c70745c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5027d6ada742f56c70745c5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject2/h2/2/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"c5027d6ada742f56c70745c5:40","filtered_window_id":"c5027d6ada742f56c70745c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5027d6ada742f56c70745c5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject2/h2/2/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"c5027d6ada742f56c70745c5:48","filtered_window_id":"c5027d6ada742f56c70745c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5027d6ada742f56c70745c5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject2/h2/2/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"c513ea8fa2595e84b3ba53b8:0","filtered_window_id":"c513ea8fa2595e84b3ba53b8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c513ea8fa2595e84b3ba53b8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[73,74,75,76,77,78,79,80],"take":"subject3/k1/1/cam4","frame_ids":[73,74,75,76,77,78,79,80]} +{"filtered_tile_id":"c513ea8fa2595e84b3ba53b8:8","filtered_window_id":"c513ea8fa2595e84b3ba53b8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c513ea8fa2595e84b3ba53b8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[81,82,83,84,85,86,87,88],"take":"subject3/k1/1/cam4","frame_ids":[81,82,83,84,85,86,87,88]} +{"filtered_tile_id":"c513ea8fa2595e84b3ba53b8:11","filtered_window_id":"c513ea8fa2595e84b3ba53b8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c513ea8fa2595e84b3ba53b8/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject3/k1/1/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"c55c052beef395cd0e37c010:0","filtered_window_id":"c55c052beef395cd0e37c010","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c55c052beef395cd0e37c010/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[652,653,654,655,656,657,658,659],"take":"subject2/k2/1/cam4","frame_ids":[652,653,654,655,656,657,658,659]} +{"filtered_tile_id":"c55c052beef395cd0e37c010:8","filtered_window_id":"c55c052beef395cd0e37c010","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c55c052beef395cd0e37c010/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[660,661,662,663,664,665,666,667],"take":"subject2/k2/1/cam4","frame_ids":[660,661,662,663,664,665,666,667]} +{"filtered_tile_id":"c55c052beef395cd0e37c010:16","filtered_window_id":"c55c052beef395cd0e37c010","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c55c052beef395cd0e37c010/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[668,669,670,671,672,673,674,675],"take":"subject2/k2/1/cam4","frame_ids":[668,669,670,671,672,673,674,675]} +{"filtered_tile_id":"c55c052beef395cd0e37c010:24","filtered_window_id":"c55c052beef395cd0e37c010","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c55c052beef395cd0e37c010/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[676,677,678,679,680,681,682,683],"take":"subject2/k2/1/cam4","frame_ids":[676,677,678,679,680,681,682,683]} +{"filtered_tile_id":"c55c052beef395cd0e37c010:32","filtered_window_id":"c55c052beef395cd0e37c010","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c55c052beef395cd0e37c010/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[684,685,686,687,688,689,690,691],"take":"subject2/k2/1/cam4","frame_ids":[684,685,686,687,688,689,690,691]} +{"filtered_tile_id":"c55c052beef395cd0e37c010:40","filtered_window_id":"c55c052beef395cd0e37c010","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c55c052beef395cd0e37c010/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[692,693,694,695,696,697,698,699],"take":"subject2/k2/1/cam4","frame_ids":[692,693,694,695,696,697,698,699]} +{"filtered_tile_id":"c55c052beef395cd0e37c010:48","filtered_window_id":"c55c052beef395cd0e37c010","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c55c052beef395cd0e37c010/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[700,701,702,703,704,705,706,707],"take":"subject2/k2/1/cam4","frame_ids":[700,701,702,703,704,705,706,707]} +{"filtered_tile_id":"c55c052beef395cd0e37c010:52","filtered_window_id":"c55c052beef395cd0e37c010","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c55c052beef395cd0e37c010/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[704,705,706,707,708,709,710,711],"take":"subject2/k2/1/cam4","frame_ids":[704,705,706,707,708,709,710,711]} +{"filtered_tile_id":"c565c8f3bb36511505137250:0","filtered_window_id":"c565c8f3bb36511505137250","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c565c8f3bb36511505137250/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject3/h1/1/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"c565c8f3bb36511505137250:8","filtered_window_id":"c565c8f3bb36511505137250","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c565c8f3bb36511505137250/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject3/h1/1/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"c565c8f3bb36511505137250:16","filtered_window_id":"c565c8f3bb36511505137250","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c565c8f3bb36511505137250/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject3/h1/1/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"c565c8f3bb36511505137250:24","filtered_window_id":"c565c8f3bb36511505137250","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c565c8f3bb36511505137250/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject3/h1/1/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"c565c8f3bb36511505137250:32","filtered_window_id":"c565c8f3bb36511505137250","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c565c8f3bb36511505137250/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject3/h1/1/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"c565c8f3bb36511505137250:37","filtered_window_id":"c565c8f3bb36511505137250","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c565c8f3bb36511505137250/native_gt.npz","filtered_start_offset":37,"expected_frame_ids":[97,98,99,100,101,102,103,104],"take":"subject3/h1/1/cam4","frame_ids":[97,98,99,100,101,102,103,104]} +{"filtered_tile_id":"c5690b268c6af759b21504c0:0","filtered_window_id":"c5690b268c6af759b21504c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5690b268c6af759b21504c0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject1/k1/6/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"c5690b268c6af759b21504c0:8","filtered_window_id":"c5690b268c6af759b21504c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5690b268c6af759b21504c0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject1/k1/6/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"c5690b268c6af759b21504c0:16","filtered_window_id":"c5690b268c6af759b21504c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5690b268c6af759b21504c0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject1/k1/6/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"c5690b268c6af759b21504c0:24","filtered_window_id":"c5690b268c6af759b21504c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5690b268c6af759b21504c0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject1/k1/6/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"c5690b268c6af759b21504c0:32","filtered_window_id":"c5690b268c6af759b21504c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5690b268c6af759b21504c0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject1/k1/6/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"c5690b268c6af759b21504c0:40","filtered_window_id":"c5690b268c6af759b21504c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5690b268c6af759b21504c0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject1/k1/6/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"c5690b268c6af759b21504c0:48","filtered_window_id":"c5690b268c6af759b21504c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5690b268c6af759b21504c0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject1/k1/6/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"c5690b268c6af759b21504c0:52","filtered_window_id":"c5690b268c6af759b21504c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5690b268c6af759b21504c0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject1/k1/6/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"c59eb495c11dfd518e03cefa:0","filtered_window_id":"c59eb495c11dfd518e03cefa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c59eb495c11dfd518e03cefa/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/k1/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"c59eb495c11dfd518e03cefa:8","filtered_window_id":"c59eb495c11dfd518e03cefa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c59eb495c11dfd518e03cefa/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/k1/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"c59eb495c11dfd518e03cefa:16","filtered_window_id":"c59eb495c11dfd518e03cefa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c59eb495c11dfd518e03cefa/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/k1/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"c59eb495c11dfd518e03cefa:24","filtered_window_id":"c59eb495c11dfd518e03cefa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c59eb495c11dfd518e03cefa/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/k1/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"c59eb495c11dfd518e03cefa:32","filtered_window_id":"c59eb495c11dfd518e03cefa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c59eb495c11dfd518e03cefa/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/k1/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"c59eb495c11dfd518e03cefa:40","filtered_window_id":"c59eb495c11dfd518e03cefa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c59eb495c11dfd518e03cefa/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/k1/1/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"c59eb495c11dfd518e03cefa:48","filtered_window_id":"c59eb495c11dfd518e03cefa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c59eb495c11dfd518e03cefa/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/k1/1/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"c59eb495c11dfd518e03cefa:52","filtered_window_id":"c59eb495c11dfd518e03cefa","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c59eb495c11dfd518e03cefa/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/k1/1/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"c5dfa6dd28349fe4b544dd54:0","filtered_window_id":"c5dfa6dd28349fe4b544dd54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5dfa6dd28349fe4b544dd54/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[55,56,57,58,59,60,61,62],"take":"subject1/o1/4/cam4","frame_ids":[55,56,57,58,59,60,61,62]} +{"filtered_tile_id":"c5dfa6dd28349fe4b544dd54:8","filtered_window_id":"c5dfa6dd28349fe4b544dd54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5dfa6dd28349fe4b544dd54/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[63,64,65,66,67,68,69,70],"take":"subject1/o1/4/cam4","frame_ids":[63,64,65,66,67,68,69,70]} +{"filtered_tile_id":"c5dfa6dd28349fe4b544dd54:16","filtered_window_id":"c5dfa6dd28349fe4b544dd54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5dfa6dd28349fe4b544dd54/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[71,72,73,74,75,76,77,78],"take":"subject1/o1/4/cam4","frame_ids":[71,72,73,74,75,76,77,78]} +{"filtered_tile_id":"c5dfa6dd28349fe4b544dd54:24","filtered_window_id":"c5dfa6dd28349fe4b544dd54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5dfa6dd28349fe4b544dd54/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[79,80,81,82,83,84,85,86],"take":"subject1/o1/4/cam4","frame_ids":[79,80,81,82,83,84,85,86]} +{"filtered_tile_id":"c5dfa6dd28349fe4b544dd54:32","filtered_window_id":"c5dfa6dd28349fe4b544dd54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5dfa6dd28349fe4b544dd54/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[87,88,89,90,91,92,93,94],"take":"subject1/o1/4/cam4","frame_ids":[87,88,89,90,91,92,93,94]} +{"filtered_tile_id":"c5dfa6dd28349fe4b544dd54:34","filtered_window_id":"c5dfa6dd28349fe4b544dd54","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5dfa6dd28349fe4b544dd54/native_gt.npz","filtered_start_offset":34,"expected_frame_ids":[89,90,91,92,93,94,95,96],"take":"subject1/o1/4/cam4","frame_ids":[89,90,91,92,93,94,95,96]} +{"filtered_tile_id":"c5e7cfcf9902ddcfa04958e9:0","filtered_window_id":"c5e7cfcf9902ddcfa04958e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5e7cfcf9902ddcfa04958e9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject3/h2/5/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"c5e7cfcf9902ddcfa04958e9:8","filtered_window_id":"c5e7cfcf9902ddcfa04958e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5e7cfcf9902ddcfa04958e9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject3/h2/5/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"c5e7cfcf9902ddcfa04958e9:16","filtered_window_id":"c5e7cfcf9902ddcfa04958e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5e7cfcf9902ddcfa04958e9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[468,469,470,471,472,473,474,475],"take":"subject3/h2/5/cam4","frame_ids":[468,469,470,471,472,473,474,475]} +{"filtered_tile_id":"c5e7cfcf9902ddcfa04958e9:24","filtered_window_id":"c5e7cfcf9902ddcfa04958e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5e7cfcf9902ddcfa04958e9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[476,477,478,479,480,481,482,483],"take":"subject3/h2/5/cam4","frame_ids":[476,477,478,479,480,481,482,483]} +{"filtered_tile_id":"c5e7cfcf9902ddcfa04958e9:32","filtered_window_id":"c5e7cfcf9902ddcfa04958e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5e7cfcf9902ddcfa04958e9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[484,485,486,487,488,489,490,491],"take":"subject3/h2/5/cam4","frame_ids":[484,485,486,487,488,489,490,491]} +{"filtered_tile_id":"c5e7cfcf9902ddcfa04958e9:40","filtered_window_id":"c5e7cfcf9902ddcfa04958e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5e7cfcf9902ddcfa04958e9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[492,493,494,495,496,497,498,499],"take":"subject3/h2/5/cam4","frame_ids":[492,493,494,495,496,497,498,499]} +{"filtered_tile_id":"c5e7cfcf9902ddcfa04958e9:48","filtered_window_id":"c5e7cfcf9902ddcfa04958e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5e7cfcf9902ddcfa04958e9/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[500,501,502,503,504,505,506,507],"take":"subject3/h2/5/cam4","frame_ids":[500,501,502,503,504,505,506,507]} +{"filtered_tile_id":"c5e7cfcf9902ddcfa04958e9:52","filtered_window_id":"c5e7cfcf9902ddcfa04958e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c5e7cfcf9902ddcfa04958e9/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject3/h2/5/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"c653cbd3f73e5565d2bb89a7:0","filtered_window_id":"c653cbd3f73e5565d2bb89a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c653cbd3f73e5565d2bb89a7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[306,307,308,309,310,311,312,313],"take":"subject2/o1/1/cam4","frame_ids":[306,307,308,309,310,311,312,313]} +{"filtered_tile_id":"c653cbd3f73e5565d2bb89a7:8","filtered_window_id":"c653cbd3f73e5565d2bb89a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c653cbd3f73e5565d2bb89a7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject2/o1/1/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"c653cbd3f73e5565d2bb89a7:11","filtered_window_id":"c653cbd3f73e5565d2bb89a7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c653cbd3f73e5565d2bb89a7/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject2/o1/1/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"c674d0e7f5590a2bfee76d8a:0","filtered_window_id":"c674d0e7f5590a2bfee76d8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c674d0e7f5590a2bfee76d8a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[306,307,308,309,310,311,312,313],"take":"subject2/k2/4/cam4","frame_ids":[306,307,308,309,310,311,312,313]} +{"filtered_tile_id":"c674d0e7f5590a2bfee76d8a:8","filtered_window_id":"c674d0e7f5590a2bfee76d8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c674d0e7f5590a2bfee76d8a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject2/k2/4/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"c674d0e7f5590a2bfee76d8a:16","filtered_window_id":"c674d0e7f5590a2bfee76d8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c674d0e7f5590a2bfee76d8a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject2/k2/4/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"c674d0e7f5590a2bfee76d8a:24","filtered_window_id":"c674d0e7f5590a2bfee76d8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c674d0e7f5590a2bfee76d8a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject2/k2/4/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"c674d0e7f5590a2bfee76d8a:32","filtered_window_id":"c674d0e7f5590a2bfee76d8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c674d0e7f5590a2bfee76d8a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject2/k2/4/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"c674d0e7f5590a2bfee76d8a:40","filtered_window_id":"c674d0e7f5590a2bfee76d8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c674d0e7f5590a2bfee76d8a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject2/k2/4/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"c674d0e7f5590a2bfee76d8a:48","filtered_window_id":"c674d0e7f5590a2bfee76d8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c674d0e7f5590a2bfee76d8a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[354,355,356,357,358,359,360,361],"take":"subject2/k2/4/cam4","frame_ids":[354,355,356,357,358,359,360,361]} +{"filtered_tile_id":"c674d0e7f5590a2bfee76d8a:52","filtered_window_id":"c674d0e7f5590a2bfee76d8a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c674d0e7f5590a2bfee76d8a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject2/k2/4/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"c675722714bcf50195490b8d:0","filtered_window_id":"c675722714bcf50195490b8d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c675722714bcf50195490b8d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[2,3,4,5,6,7,8,9],"take":"subject1/o1/2/cam4","frame_ids":[2,3,4,5,6,7,8,9]} +{"filtered_tile_id":"c675722714bcf50195490b8d:8","filtered_window_id":"c675722714bcf50195490b8d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c675722714bcf50195490b8d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[10,11,12,13,14,15,16,17],"take":"subject1/o1/2/cam4","frame_ids":[10,11,12,13,14,15,16,17]} +{"filtered_tile_id":"c675722714bcf50195490b8d:16","filtered_window_id":"c675722714bcf50195490b8d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c675722714bcf50195490b8d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[18,19,20,21,22,23,24,25],"take":"subject1/o1/2/cam4","frame_ids":[18,19,20,21,22,23,24,25]} +{"filtered_tile_id":"c675722714bcf50195490b8d:24","filtered_window_id":"c675722714bcf50195490b8d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c675722714bcf50195490b8d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[26,27,28,29,30,31,32,33],"take":"subject1/o1/2/cam4","frame_ids":[26,27,28,29,30,31,32,33]} +{"filtered_tile_id":"c675722714bcf50195490b8d:32","filtered_window_id":"c675722714bcf50195490b8d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c675722714bcf50195490b8d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[34,35,36,37,38,39,40,41],"take":"subject1/o1/2/cam4","frame_ids":[34,35,36,37,38,39,40,41]} +{"filtered_tile_id":"c675722714bcf50195490b8d:40","filtered_window_id":"c675722714bcf50195490b8d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c675722714bcf50195490b8d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[42,43,44,45,46,47,48,49],"take":"subject1/o1/2/cam4","frame_ids":[42,43,44,45,46,47,48,49]} +{"filtered_tile_id":"c675722714bcf50195490b8d:48","filtered_window_id":"c675722714bcf50195490b8d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c675722714bcf50195490b8d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[50,51,52,53,54,55,56,57],"take":"subject1/o1/2/cam4","frame_ids":[50,51,52,53,54,55,56,57]} +{"filtered_tile_id":"c675722714bcf50195490b8d:52","filtered_window_id":"c675722714bcf50195490b8d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c675722714bcf50195490b8d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[54,55,56,57,58,59,60,61],"take":"subject1/o1/2/cam4","frame_ids":[54,55,56,57,58,59,60,61]} +{"filtered_tile_id":"c68e7e9667b305d434b5600c:0","filtered_window_id":"c68e7e9667b305d434b5600c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c68e7e9667b305d434b5600c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject2/k2/0/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"c68e7e9667b305d434b5600c:8","filtered_window_id":"c68e7e9667b305d434b5600c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c68e7e9667b305d434b5600c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject2/k2/0/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"c68e7e9667b305d434b5600c:16","filtered_window_id":"c68e7e9667b305d434b5600c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c68e7e9667b305d434b5600c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject2/k2/0/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"c68e7e9667b305d434b5600c:24","filtered_window_id":"c68e7e9667b305d434b5600c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c68e7e9667b305d434b5600c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[376,377,378,379,380,381,382,383],"take":"subject2/k2/0/cam4","frame_ids":[376,377,378,379,380,381,382,383]} +{"filtered_tile_id":"c68e7e9667b305d434b5600c:32","filtered_window_id":"c68e7e9667b305d434b5600c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c68e7e9667b305d434b5600c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject2/k2/0/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"c68e7e9667b305d434b5600c:40","filtered_window_id":"c68e7e9667b305d434b5600c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c68e7e9667b305d434b5600c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[392,393,394,395,396,397,398,399],"take":"subject2/k2/0/cam4","frame_ids":[392,393,394,395,396,397,398,399]} +{"filtered_tile_id":"c68e7e9667b305d434b5600c:48","filtered_window_id":"c68e7e9667b305d434b5600c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c68e7e9667b305d434b5600c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[400,401,402,403,404,405,406,407],"take":"subject2/k2/0/cam4","frame_ids":[400,401,402,403,404,405,406,407]} +{"filtered_tile_id":"c68e7e9667b305d434b5600c:52","filtered_window_id":"c68e7e9667b305d434b5600c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c68e7e9667b305d434b5600c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject2/k2/0/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"c6bf1984a980840c4f55d519:0","filtered_window_id":"c6bf1984a980840c4f55d519","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6bf1984a980840c4f55d519/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[374,375,376,377,378,379,380,381],"take":"subject2/o1/0/cam4","frame_ids":[374,375,376,377,378,379,380,381]} +{"filtered_tile_id":"c6bf1984a980840c4f55d519:8","filtered_window_id":"c6bf1984a980840c4f55d519","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6bf1984a980840c4f55d519/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[382,383,384,385,386,387,388,389],"take":"subject2/o1/0/cam4","frame_ids":[382,383,384,385,386,387,388,389]} +{"filtered_tile_id":"c6bf1984a980840c4f55d519:16","filtered_window_id":"c6bf1984a980840c4f55d519","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6bf1984a980840c4f55d519/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject2/o1/0/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"c6bf1984a980840c4f55d519:24","filtered_window_id":"c6bf1984a980840c4f55d519","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6bf1984a980840c4f55d519/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[398,399,400,401,402,403,404,405],"take":"subject2/o1/0/cam4","frame_ids":[398,399,400,401,402,403,404,405]} +{"filtered_tile_id":"c6bf1984a980840c4f55d519:32","filtered_window_id":"c6bf1984a980840c4f55d519","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6bf1984a980840c4f55d519/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[406,407,408,409,410,411,412,413],"take":"subject2/o1/0/cam4","frame_ids":[406,407,408,409,410,411,412,413]} +{"filtered_tile_id":"c6bf1984a980840c4f55d519:40","filtered_window_id":"c6bf1984a980840c4f55d519","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6bf1984a980840c4f55d519/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[414,415,416,417,418,419,420,421],"take":"subject2/o1/0/cam4","frame_ids":[414,415,416,417,418,419,420,421]} +{"filtered_tile_id":"c6bf1984a980840c4f55d519:48","filtered_window_id":"c6bf1984a980840c4f55d519","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6bf1984a980840c4f55d519/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[422,423,424,425,426,427,428,429],"take":"subject2/o1/0/cam4","frame_ids":[422,423,424,425,426,427,428,429]} +{"filtered_tile_id":"c6bf1984a980840c4f55d519:52","filtered_window_id":"c6bf1984a980840c4f55d519","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6bf1984a980840c4f55d519/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[426,427,428,429,430,431,432,433],"take":"subject2/o1/0/cam4","frame_ids":[426,427,428,429,430,431,432,433]} +{"filtered_tile_id":"c6dace87fbd681a34b88c379:0","filtered_window_id":"c6dace87fbd681a34b88c379","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6dace87fbd681a34b88c379/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject2/o2/3/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"c6dace87fbd681a34b88c379:8","filtered_window_id":"c6dace87fbd681a34b88c379","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6dace87fbd681a34b88c379/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject2/o2/3/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"c6dace87fbd681a34b88c379:16","filtered_window_id":"c6dace87fbd681a34b88c379","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6dace87fbd681a34b88c379/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject2/o2/3/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"c6dace87fbd681a34b88c379:18","filtered_window_id":"c6dace87fbd681a34b88c379","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c6dace87fbd681a34b88c379/native_gt.npz","filtered_start_offset":18,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject2/o2/3/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"c700819451ce0e3cfee35d2a:0","filtered_window_id":"c700819451ce0e3cfee35d2a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c700819451ce0e3cfee35d2a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[357,358,359,360,361,362,363,364],"take":"subject1/o1/7/cam4","frame_ids":[357,358,359,360,361,362,363,364]} +{"filtered_tile_id":"c700819451ce0e3cfee35d2a:8","filtered_window_id":"c700819451ce0e3cfee35d2a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c700819451ce0e3cfee35d2a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject1/o1/7/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"c700819451ce0e3cfee35d2a:16","filtered_window_id":"c700819451ce0e3cfee35d2a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c700819451ce0e3cfee35d2a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[373,374,375,376,377,378,379,380],"take":"subject1/o1/7/cam4","frame_ids":[373,374,375,376,377,378,379,380]} +{"filtered_tile_id":"c700819451ce0e3cfee35d2a:24","filtered_window_id":"c700819451ce0e3cfee35d2a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c700819451ce0e3cfee35d2a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[381,382,383,384,385,386,387,388],"take":"subject1/o1/7/cam4","frame_ids":[381,382,383,384,385,386,387,388]} +{"filtered_tile_id":"c700819451ce0e3cfee35d2a:32","filtered_window_id":"c700819451ce0e3cfee35d2a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c700819451ce0e3cfee35d2a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[389,390,391,392,393,394,395,396],"take":"subject1/o1/7/cam4","frame_ids":[389,390,391,392,393,394,395,396]} +{"filtered_tile_id":"c700819451ce0e3cfee35d2a:40","filtered_window_id":"c700819451ce0e3cfee35d2a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c700819451ce0e3cfee35d2a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[397,398,399,400,401,402,403,404],"take":"subject1/o1/7/cam4","frame_ids":[397,398,399,400,401,402,403,404]} +{"filtered_tile_id":"c700819451ce0e3cfee35d2a:46","filtered_window_id":"c700819451ce0e3cfee35d2a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c700819451ce0e3cfee35d2a/native_gt.npz","filtered_start_offset":46,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject1/o1/7/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"c7400fd7d54bbb293c45584b:0","filtered_window_id":"c7400fd7d54bbb293c45584b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7400fd7d54bbb293c45584b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/h1/1/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"c7400fd7d54bbb293c45584b:8","filtered_window_id":"c7400fd7d54bbb293c45584b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7400fd7d54bbb293c45584b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject2/h1/1/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"c7400fd7d54bbb293c45584b:16","filtered_window_id":"c7400fd7d54bbb293c45584b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7400fd7d54bbb293c45584b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject2/h1/1/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"c7400fd7d54bbb293c45584b:24","filtered_window_id":"c7400fd7d54bbb293c45584b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7400fd7d54bbb293c45584b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject2/h1/1/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"c7400fd7d54bbb293c45584b:28","filtered_window_id":"c7400fd7d54bbb293c45584b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7400fd7d54bbb293c45584b/native_gt.npz","filtered_start_offset":28,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject2/h1/1/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"c749d201874145014aa2ec01:0","filtered_window_id":"c749d201874145014aa2ec01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c749d201874145014aa2ec01/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject2/h1/7/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"c749d201874145014aa2ec01:8","filtered_window_id":"c749d201874145014aa2ec01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c749d201874145014aa2ec01/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject2/h1/7/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"c749d201874145014aa2ec01:16","filtered_window_id":"c749d201874145014aa2ec01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c749d201874145014aa2ec01/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[386,387,388,389,390,391,392,393],"take":"subject2/h1/7/cam4","frame_ids":[386,387,388,389,390,391,392,393]} +{"filtered_tile_id":"c749d201874145014aa2ec01:24","filtered_window_id":"c749d201874145014aa2ec01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c749d201874145014aa2ec01/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[394,395,396,397,398,399,400,401],"take":"subject2/h1/7/cam4","frame_ids":[394,395,396,397,398,399,400,401]} +{"filtered_tile_id":"c749d201874145014aa2ec01:27","filtered_window_id":"c749d201874145014aa2ec01","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c749d201874145014aa2ec01/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[397,398,399,400,401,402,403,404],"take":"subject2/h1/7/cam4","frame_ids":[397,398,399,400,401,402,403,404]} +{"filtered_tile_id":"c76853c5ec6c224323da54f8:0","filtered_window_id":"c76853c5ec6c224323da54f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c76853c5ec6c224323da54f8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject1/o1/0/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"c76853c5ec6c224323da54f8:8","filtered_window_id":"c76853c5ec6c224323da54f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c76853c5ec6c224323da54f8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject1/o1/0/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"c76853c5ec6c224323da54f8:16","filtered_window_id":"c76853c5ec6c224323da54f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c76853c5ec6c224323da54f8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject1/o1/0/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"c76853c5ec6c224323da54f8:24","filtered_window_id":"c76853c5ec6c224323da54f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c76853c5ec6c224323da54f8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject1/o1/0/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"c76853c5ec6c224323da54f8:32","filtered_window_id":"c76853c5ec6c224323da54f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c76853c5ec6c224323da54f8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject1/o1/0/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"c76853c5ec6c224323da54f8:40","filtered_window_id":"c76853c5ec6c224323da54f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c76853c5ec6c224323da54f8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject1/o1/0/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"c76853c5ec6c224323da54f8:48","filtered_window_id":"c76853c5ec6c224323da54f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c76853c5ec6c224323da54f8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject1/o1/0/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"c76853c5ec6c224323da54f8:52","filtered_window_id":"c76853c5ec6c224323da54f8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c76853c5ec6c224323da54f8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject1/o1/0/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"c778e7bdfb88667a4b6ac301:0","filtered_window_id":"c778e7bdfb88667a4b6ac301","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c778e7bdfb88667a4b6ac301/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject2/k2/1/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"c778e7bdfb88667a4b6ac301:8","filtered_window_id":"c778e7bdfb88667a4b6ac301","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c778e7bdfb88667a4b6ac301/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject2/k2/1/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"c778e7bdfb88667a4b6ac301:16","filtered_window_id":"c778e7bdfb88667a4b6ac301","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c778e7bdfb88667a4b6ac301/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject2/k2/1/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"c778e7bdfb88667a4b6ac301:24","filtered_window_id":"c778e7bdfb88667a4b6ac301","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c778e7bdfb88667a4b6ac301/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject2/k2/1/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"c778e7bdfb88667a4b6ac301:32","filtered_window_id":"c778e7bdfb88667a4b6ac301","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c778e7bdfb88667a4b6ac301/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject2/k2/1/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"c778e7bdfb88667a4b6ac301:40","filtered_window_id":"c778e7bdfb88667a4b6ac301","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c778e7bdfb88667a4b6ac301/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject2/k2/1/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"c778e7bdfb88667a4b6ac301:48","filtered_window_id":"c778e7bdfb88667a4b6ac301","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c778e7bdfb88667a4b6ac301/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject2/k2/1/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"c778e7bdfb88667a4b6ac301:52","filtered_window_id":"c778e7bdfb88667a4b6ac301","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c778e7bdfb88667a4b6ac301/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject2/k2/1/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"c7836d75e13934d7d6a889c5:0","filtered_window_id":"c7836d75e13934d7d6a889c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7836d75e13934d7d6a889c5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject2/h1/7/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"c7836d75e13934d7d6a889c5:8","filtered_window_id":"c7836d75e13934d7d6a889c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7836d75e13934d7d6a889c5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject2/h1/7/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"c7836d75e13934d7d6a889c5:16","filtered_window_id":"c7836d75e13934d7d6a889c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7836d75e13934d7d6a889c5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject2/h1/7/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"c7836d75e13934d7d6a889c5:24","filtered_window_id":"c7836d75e13934d7d6a889c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7836d75e13934d7d6a889c5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject2/h1/7/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"c7836d75e13934d7d6a889c5:32","filtered_window_id":"c7836d75e13934d7d6a889c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7836d75e13934d7d6a889c5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject2/h1/7/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"c7836d75e13934d7d6a889c5:40","filtered_window_id":"c7836d75e13934d7d6a889c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7836d75e13934d7d6a889c5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject2/h1/7/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"c7836d75e13934d7d6a889c5:41","filtered_window_id":"c7836d75e13934d7d6a889c5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7836d75e13934d7d6a889c5/native_gt.npz","filtered_start_offset":41,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject2/h1/7/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"c7b0ce2b630618b2b48dd602:0","filtered_window_id":"c7b0ce2b630618b2b48dd602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7b0ce2b630618b2b48dd602/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o2/6/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"c7b0ce2b630618b2b48dd602:8","filtered_window_id":"c7b0ce2b630618b2b48dd602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7b0ce2b630618b2b48dd602/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o2/6/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"c7b0ce2b630618b2b48dd602:16","filtered_window_id":"c7b0ce2b630618b2b48dd602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7b0ce2b630618b2b48dd602/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o2/6/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"c7b0ce2b630618b2b48dd602:24","filtered_window_id":"c7b0ce2b630618b2b48dd602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7b0ce2b630618b2b48dd602/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o2/6/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"c7b0ce2b630618b2b48dd602:32","filtered_window_id":"c7b0ce2b630618b2b48dd602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7b0ce2b630618b2b48dd602/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o2/6/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"c7b0ce2b630618b2b48dd602:40","filtered_window_id":"c7b0ce2b630618b2b48dd602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7b0ce2b630618b2b48dd602/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/o2/6/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"c7b0ce2b630618b2b48dd602:48","filtered_window_id":"c7b0ce2b630618b2b48dd602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7b0ce2b630618b2b48dd602/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/o2/6/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"c7b0ce2b630618b2b48dd602:52","filtered_window_id":"c7b0ce2b630618b2b48dd602","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c7b0ce2b630618b2b48dd602/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/o2/6/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"c822b3e679c5944e20fe8559:0","filtered_window_id":"c822b3e679c5944e20fe8559","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c822b3e679c5944e20fe8559/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[752,753,754,755,756,757,758,759],"take":"subject2/k1/6/cam4","frame_ids":[752,753,754,755,756,757,758,759]} +{"filtered_tile_id":"c822b3e679c5944e20fe8559:8","filtered_window_id":"c822b3e679c5944e20fe8559","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c822b3e679c5944e20fe8559/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[760,761,762,763,764,765,766,767],"take":"subject2/k1/6/cam4","frame_ids":[760,761,762,763,764,765,766,767]} +{"filtered_tile_id":"c822b3e679c5944e20fe8559:16","filtered_window_id":"c822b3e679c5944e20fe8559","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c822b3e679c5944e20fe8559/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[768,769,770,771,772,773,774,775],"take":"subject2/k1/6/cam4","frame_ids":[768,769,770,771,772,773,774,775]} +{"filtered_tile_id":"c822b3e679c5944e20fe8559:24","filtered_window_id":"c822b3e679c5944e20fe8559","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c822b3e679c5944e20fe8559/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[776,777,778,779,780,781,782,783],"take":"subject2/k1/6/cam4","frame_ids":[776,777,778,779,780,781,782,783]} +{"filtered_tile_id":"c822b3e679c5944e20fe8559:32","filtered_window_id":"c822b3e679c5944e20fe8559","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c822b3e679c5944e20fe8559/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[784,785,786,787,788,789,790,791],"take":"subject2/k1/6/cam4","frame_ids":[784,785,786,787,788,789,790,791]} +{"filtered_tile_id":"c822b3e679c5944e20fe8559:40","filtered_window_id":"c822b3e679c5944e20fe8559","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c822b3e679c5944e20fe8559/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[792,793,794,795,796,797,798,799],"take":"subject2/k1/6/cam4","frame_ids":[792,793,794,795,796,797,798,799]} +{"filtered_tile_id":"c822b3e679c5944e20fe8559:48","filtered_window_id":"c822b3e679c5944e20fe8559","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c822b3e679c5944e20fe8559/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[800,801,802,803,804,805,806,807],"take":"subject2/k1/6/cam4","frame_ids":[800,801,802,803,804,805,806,807]} +{"filtered_tile_id":"c822b3e679c5944e20fe8559:52","filtered_window_id":"c822b3e679c5944e20fe8559","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c822b3e679c5944e20fe8559/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[804,805,806,807,808,809,810,811],"take":"subject2/k1/6/cam4","frame_ids":[804,805,806,807,808,809,810,811]} +{"filtered_tile_id":"c87c15edeb79470c5bd049ec:0","filtered_window_id":"c87c15edeb79470c5bd049ec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c87c15edeb79470c5bd049ec/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[550,551,552,553,554,555,556,557],"take":"subject3/h1/1/cam4","frame_ids":[550,551,552,553,554,555,556,557]} +{"filtered_tile_id":"c87c15edeb79470c5bd049ec:8","filtered_window_id":"c87c15edeb79470c5bd049ec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c87c15edeb79470c5bd049ec/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[558,559,560,561,562,563,564,565],"take":"subject3/h1/1/cam4","frame_ids":[558,559,560,561,562,563,564,565]} +{"filtered_tile_id":"c87c15edeb79470c5bd049ec:16","filtered_window_id":"c87c15edeb79470c5bd049ec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c87c15edeb79470c5bd049ec/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[566,567,568,569,570,571,572,573],"take":"subject3/h1/1/cam4","frame_ids":[566,567,568,569,570,571,572,573]} +{"filtered_tile_id":"c87c15edeb79470c5bd049ec:23","filtered_window_id":"c87c15edeb79470c5bd049ec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c87c15edeb79470c5bd049ec/native_gt.npz","filtered_start_offset":23,"expected_frame_ids":[573,574,575,576,577,578,579,580],"take":"subject3/h1/1/cam4","frame_ids":[573,574,575,576,577,578,579,580]} +{"filtered_tile_id":"c8d758246f50cd7fc21319c2:0","filtered_window_id":"c8d758246f50cd7fc21319c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c8d758246f50cd7fc21319c2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[579,580,581,582,583,584,585,586],"take":"subject1/h2/1/cam4","frame_ids":[579,580,581,582,583,584,585,586]} +{"filtered_tile_id":"c8d758246f50cd7fc21319c2:8","filtered_window_id":"c8d758246f50cd7fc21319c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c8d758246f50cd7fc21319c2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[587,588,589,590,591,592,593,594],"take":"subject1/h2/1/cam4","frame_ids":[587,588,589,590,591,592,593,594]} +{"filtered_tile_id":"c8d758246f50cd7fc21319c2:16","filtered_window_id":"c8d758246f50cd7fc21319c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c8d758246f50cd7fc21319c2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[595,596,597,598,599,600,601,602],"take":"subject1/h2/1/cam4","frame_ids":[595,596,597,598,599,600,601,602]} +{"filtered_tile_id":"c8d758246f50cd7fc21319c2:24","filtered_window_id":"c8d758246f50cd7fc21319c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c8d758246f50cd7fc21319c2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[603,604,605,606,607,608,609,610],"take":"subject1/h2/1/cam4","frame_ids":[603,604,605,606,607,608,609,610]} +{"filtered_tile_id":"c8d758246f50cd7fc21319c2:32","filtered_window_id":"c8d758246f50cd7fc21319c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c8d758246f50cd7fc21319c2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[611,612,613,614,615,616,617,618],"take":"subject1/h2/1/cam4","frame_ids":[611,612,613,614,615,616,617,618]} +{"filtered_tile_id":"c8d758246f50cd7fc21319c2:40","filtered_window_id":"c8d758246f50cd7fc21319c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c8d758246f50cd7fc21319c2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[619,620,621,622,623,624,625,626],"take":"subject1/h2/1/cam4","frame_ids":[619,620,621,622,623,624,625,626]} +{"filtered_tile_id":"c8d758246f50cd7fc21319c2:48","filtered_window_id":"c8d758246f50cd7fc21319c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c8d758246f50cd7fc21319c2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[627,628,629,630,631,632,633,634],"take":"subject1/h2/1/cam4","frame_ids":[627,628,629,630,631,632,633,634]} +{"filtered_tile_id":"c8d758246f50cd7fc21319c2:52","filtered_window_id":"c8d758246f50cd7fc21319c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c8d758246f50cd7fc21319c2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[631,632,633,634,635,636,637,638],"take":"subject1/h2/1/cam4","frame_ids":[631,632,633,634,635,636,637,638]} +{"filtered_tile_id":"c92509389a81bd7fc5487e5a:0","filtered_window_id":"c92509389a81bd7fc5487e5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c92509389a81bd7fc5487e5a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject1/o1/3/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"c92509389a81bd7fc5487e5a:8","filtered_window_id":"c92509389a81bd7fc5487e5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c92509389a81bd7fc5487e5a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject1/o1/3/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"c92509389a81bd7fc5487e5a:11","filtered_window_id":"c92509389a81bd7fc5487e5a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c92509389a81bd7fc5487e5a/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject1/o1/3/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"c97cb596a6cec4c92e288f4f:0","filtered_window_id":"c97cb596a6cec4c92e288f4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c97cb596a6cec4c92e288f4f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject2/h2/4/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"c97cb596a6cec4c92e288f4f:8","filtered_window_id":"c97cb596a6cec4c92e288f4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c97cb596a6cec4c92e288f4f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject2/h2/4/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"c97cb596a6cec4c92e288f4f:16","filtered_window_id":"c97cb596a6cec4c92e288f4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c97cb596a6cec4c92e288f4f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject2/h2/4/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"c97cb596a6cec4c92e288f4f:24","filtered_window_id":"c97cb596a6cec4c92e288f4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c97cb596a6cec4c92e288f4f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject2/h2/4/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"c97cb596a6cec4c92e288f4f:32","filtered_window_id":"c97cb596a6cec4c92e288f4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c97cb596a6cec4c92e288f4f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[341,342,343,344,345,346,347,348],"take":"subject2/h2/4/cam4","frame_ids":[341,342,343,344,345,346,347,348]} +{"filtered_tile_id":"c998c7d9e0ea7723aa22d2c7:0","filtered_window_id":"c998c7d9e0ea7723aa22d2c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c998c7d9e0ea7723aa22d2c7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject2/k1/3/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"c998c7d9e0ea7723aa22d2c7:8","filtered_window_id":"c998c7d9e0ea7723aa22d2c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c998c7d9e0ea7723aa22d2c7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject2/k1/3/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"c998c7d9e0ea7723aa22d2c7:16","filtered_window_id":"c998c7d9e0ea7723aa22d2c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c998c7d9e0ea7723aa22d2c7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject2/k1/3/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"c998c7d9e0ea7723aa22d2c7:24","filtered_window_id":"c998c7d9e0ea7723aa22d2c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c998c7d9e0ea7723aa22d2c7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject2/k1/3/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"c998c7d9e0ea7723aa22d2c7:32","filtered_window_id":"c998c7d9e0ea7723aa22d2c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c998c7d9e0ea7723aa22d2c7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject2/k1/3/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"c998c7d9e0ea7723aa22d2c7:36","filtered_window_id":"c998c7d9e0ea7723aa22d2c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c998c7d9e0ea7723aa22d2c7/native_gt.npz","filtered_start_offset":36,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject2/k1/3/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"c9a0cbf92f86d22197868e4b:0","filtered_window_id":"c9a0cbf92f86d22197868e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9a0cbf92f86d22197868e4b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject2/h1/2/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"c9a0cbf92f86d22197868e4b:8","filtered_window_id":"c9a0cbf92f86d22197868e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9a0cbf92f86d22197868e4b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject2/h1/2/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"c9a0cbf92f86d22197868e4b:9","filtered_window_id":"c9a0cbf92f86d22197868e4b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9a0cbf92f86d22197868e4b/native_gt.npz","filtered_start_offset":9,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject2/h1/2/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"c9b406e86296d9b675755e64:0","filtered_window_id":"c9b406e86296d9b675755e64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9b406e86296d9b675755e64/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[550,551,552,553,554,555,556,557],"take":"subject1/o2/2/cam4","frame_ids":[550,551,552,553,554,555,556,557]} +{"filtered_tile_id":"c9b406e86296d9b675755e64:8","filtered_window_id":"c9b406e86296d9b675755e64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9b406e86296d9b675755e64/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[558,559,560,561,562,563,564,565],"take":"subject1/o2/2/cam4","frame_ids":[558,559,560,561,562,563,564,565]} +{"filtered_tile_id":"c9b406e86296d9b675755e64:16","filtered_window_id":"c9b406e86296d9b675755e64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9b406e86296d9b675755e64/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[566,567,568,569,570,571,572,573],"take":"subject1/o2/2/cam4","frame_ids":[566,567,568,569,570,571,572,573]} +{"filtered_tile_id":"c9b406e86296d9b675755e64:24","filtered_window_id":"c9b406e86296d9b675755e64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9b406e86296d9b675755e64/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[574,575,576,577,578,579,580,581],"take":"subject1/o2/2/cam4","frame_ids":[574,575,576,577,578,579,580,581]} +{"filtered_tile_id":"c9b406e86296d9b675755e64:32","filtered_window_id":"c9b406e86296d9b675755e64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9b406e86296d9b675755e64/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[582,583,584,585,586,587,588,589],"take":"subject1/o2/2/cam4","frame_ids":[582,583,584,585,586,587,588,589]} +{"filtered_tile_id":"c9b406e86296d9b675755e64:40","filtered_window_id":"c9b406e86296d9b675755e64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9b406e86296d9b675755e64/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[590,591,592,593,594,595,596,597],"take":"subject1/o2/2/cam4","frame_ids":[590,591,592,593,594,595,596,597]} +{"filtered_tile_id":"c9b406e86296d9b675755e64:48","filtered_window_id":"c9b406e86296d9b675755e64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9b406e86296d9b675755e64/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[598,599,600,601,602,603,604,605],"take":"subject1/o2/2/cam4","frame_ids":[598,599,600,601,602,603,604,605]} +{"filtered_tile_id":"c9b406e86296d9b675755e64:52","filtered_window_id":"c9b406e86296d9b675755e64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/c9b406e86296d9b675755e64/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[602,603,604,605,606,607,608,609],"take":"subject1/o2/2/cam4","frame_ids":[602,603,604,605,606,607,608,609]} +{"filtered_tile_id":"ca1ea56a6e3a16b676db8b95:0","filtered_window_id":"ca1ea56a6e3a16b676db8b95","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca1ea56a6e3a16b676db8b95/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[509,510,511,512,513,514,515,516],"take":"subject2/h1/3/cam4","frame_ids":[509,510,511,512,513,514,515,516]} +{"filtered_tile_id":"ca1ea56a6e3a16b676db8b95:8","filtered_window_id":"ca1ea56a6e3a16b676db8b95","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca1ea56a6e3a16b676db8b95/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[517,518,519,520,521,522,523,524],"take":"subject2/h1/3/cam4","frame_ids":[517,518,519,520,521,522,523,524]} +{"filtered_tile_id":"ca1ea56a6e3a16b676db8b95:16","filtered_window_id":"ca1ea56a6e3a16b676db8b95","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca1ea56a6e3a16b676db8b95/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[525,526,527,528,529,530,531,532],"take":"subject2/h1/3/cam4","frame_ids":[525,526,527,528,529,530,531,532]} +{"filtered_tile_id":"ca1ea56a6e3a16b676db8b95:24","filtered_window_id":"ca1ea56a6e3a16b676db8b95","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca1ea56a6e3a16b676db8b95/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[533,534,535,536,537,538,539,540],"take":"subject2/h1/3/cam4","frame_ids":[533,534,535,536,537,538,539,540]} +{"filtered_tile_id":"ca1ea56a6e3a16b676db8b95:32","filtered_window_id":"ca1ea56a6e3a16b676db8b95","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca1ea56a6e3a16b676db8b95/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject2/h1/3/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"ca1ea56a6e3a16b676db8b95:40","filtered_window_id":"ca1ea56a6e3a16b676db8b95","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca1ea56a6e3a16b676db8b95/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[549,550,551,552,553,554,555,556],"take":"subject2/h1/3/cam4","frame_ids":[549,550,551,552,553,554,555,556]} +{"filtered_tile_id":"ca1ea56a6e3a16b676db8b95:48","filtered_window_id":"ca1ea56a6e3a16b676db8b95","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca1ea56a6e3a16b676db8b95/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[557,558,559,560,561,562,563,564],"take":"subject2/h1/3/cam4","frame_ids":[557,558,559,560,561,562,563,564]} +{"filtered_tile_id":"ca1ea56a6e3a16b676db8b95:52","filtered_window_id":"ca1ea56a6e3a16b676db8b95","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca1ea56a6e3a16b676db8b95/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[561,562,563,564,565,566,567,568],"take":"subject2/h1/3/cam4","frame_ids":[561,562,563,564,565,566,567,568]} +{"filtered_tile_id":"ca21300e1392c83f167f9da5:0","filtered_window_id":"ca21300e1392c83f167f9da5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca21300e1392c83f167f9da5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject3/h1/3/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"ca21300e1392c83f167f9da5:8","filtered_window_id":"ca21300e1392c83f167f9da5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca21300e1392c83f167f9da5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject3/h1/3/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"ca21300e1392c83f167f9da5:16","filtered_window_id":"ca21300e1392c83f167f9da5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca21300e1392c83f167f9da5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject3/h1/3/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"ca21300e1392c83f167f9da5:22","filtered_window_id":"ca21300e1392c83f167f9da5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca21300e1392c83f167f9da5/native_gt.npz","filtered_start_offset":22,"expected_frame_ids":[82,83,84,85,86,87,88,89],"take":"subject3/h1/3/cam4","frame_ids":[82,83,84,85,86,87,88,89]} +{"filtered_tile_id":"ca4ff0fb422e52471e6bf0a8:0","filtered_window_id":"ca4ff0fb422e52471e6bf0a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca4ff0fb422e52471e6bf0a8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h2/5/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"ca4ff0fb422e52471e6bf0a8:8","filtered_window_id":"ca4ff0fb422e52471e6bf0a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca4ff0fb422e52471e6bf0a8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h2/5/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"ca4ff0fb422e52471e6bf0a8:16","filtered_window_id":"ca4ff0fb422e52471e6bf0a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca4ff0fb422e52471e6bf0a8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h2/5/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"ca4ff0fb422e52471e6bf0a8:24","filtered_window_id":"ca4ff0fb422e52471e6bf0a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca4ff0fb422e52471e6bf0a8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h2/5/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"ca4ff0fb422e52471e6bf0a8:32","filtered_window_id":"ca4ff0fb422e52471e6bf0a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca4ff0fb422e52471e6bf0a8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h2/5/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"ca4ff0fb422e52471e6bf0a8:38","filtered_window_id":"ca4ff0fb422e52471e6bf0a8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca4ff0fb422e52471e6bf0a8/native_gt.npz","filtered_start_offset":38,"expected_frame_ids":[38,39,40,41,42,43,44,45],"take":"subject1/h2/5/cam4","frame_ids":[38,39,40,41,42,43,44,45]} +{"filtered_tile_id":"ca7b955d40efb34a8079aec5:0","filtered_window_id":"ca7b955d40efb34a8079aec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca7b955d40efb34a8079aec5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject3/h1/1/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"ca7b955d40efb34a8079aec5:8","filtered_window_id":"ca7b955d40efb34a8079aec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca7b955d40efb34a8079aec5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject3/h1/1/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"ca7b955d40efb34a8079aec5:16","filtered_window_id":"ca7b955d40efb34a8079aec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca7b955d40efb34a8079aec5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject3/h1/1/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"ca7b955d40efb34a8079aec5:24","filtered_window_id":"ca7b955d40efb34a8079aec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca7b955d40efb34a8079aec5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject3/h1/1/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"ca7b955d40efb34a8079aec5:32","filtered_window_id":"ca7b955d40efb34a8079aec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca7b955d40efb34a8079aec5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject3/h1/1/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"ca7b955d40efb34a8079aec5:40","filtered_window_id":"ca7b955d40efb34a8079aec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca7b955d40efb34a8079aec5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject3/h1/1/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"ca7b955d40efb34a8079aec5:48","filtered_window_id":"ca7b955d40efb34a8079aec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca7b955d40efb34a8079aec5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject3/h1/1/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"ca7b955d40efb34a8079aec5:52","filtered_window_id":"ca7b955d40efb34a8079aec5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ca7b955d40efb34a8079aec5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject3/h1/1/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"cb0fa800a1655cafce2b0ac8:0","filtered_window_id":"cb0fa800a1655cafce2b0ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb0fa800a1655cafce2b0ac8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject3/k1/1/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"cb0fa800a1655cafce2b0ac8:8","filtered_window_id":"cb0fa800a1655cafce2b0ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb0fa800a1655cafce2b0ac8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject3/k1/1/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"cb0fa800a1655cafce2b0ac8:16","filtered_window_id":"cb0fa800a1655cafce2b0ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb0fa800a1655cafce2b0ac8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[246,247,248,249,250,251,252,253],"take":"subject3/k1/1/cam4","frame_ids":[246,247,248,249,250,251,252,253]} +{"filtered_tile_id":"cb0fa800a1655cafce2b0ac8:24","filtered_window_id":"cb0fa800a1655cafce2b0ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb0fa800a1655cafce2b0ac8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject3/k1/1/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"cb0fa800a1655cafce2b0ac8:32","filtered_window_id":"cb0fa800a1655cafce2b0ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb0fa800a1655cafce2b0ac8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[262,263,264,265,266,267,268,269],"take":"subject3/k1/1/cam4","frame_ids":[262,263,264,265,266,267,268,269]} +{"filtered_tile_id":"cb0fa800a1655cafce2b0ac8:40","filtered_window_id":"cb0fa800a1655cafce2b0ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb0fa800a1655cafce2b0ac8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[270,271,272,273,274,275,276,277],"take":"subject3/k1/1/cam4","frame_ids":[270,271,272,273,274,275,276,277]} +{"filtered_tile_id":"cb0fa800a1655cafce2b0ac8:48","filtered_window_id":"cb0fa800a1655cafce2b0ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb0fa800a1655cafce2b0ac8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[278,279,280,281,282,283,284,285],"take":"subject3/k1/1/cam4","frame_ids":[278,279,280,281,282,283,284,285]} +{"filtered_tile_id":"cb0fa800a1655cafce2b0ac8:52","filtered_window_id":"cb0fa800a1655cafce2b0ac8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb0fa800a1655cafce2b0ac8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject3/k1/1/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"cb5008ef92839a52d95dd527:0","filtered_window_id":"cb5008ef92839a52d95dd527","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb5008ef92839a52d95dd527/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject2/k1/6/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"cb5008ef92839a52d95dd527:8","filtered_window_id":"cb5008ef92839a52d95dd527","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb5008ef92839a52d95dd527/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject2/k1/6/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"cb5008ef92839a52d95dd527:16","filtered_window_id":"cb5008ef92839a52d95dd527","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb5008ef92839a52d95dd527/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject2/k1/6/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"cb5008ef92839a52d95dd527:24","filtered_window_id":"cb5008ef92839a52d95dd527","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb5008ef92839a52d95dd527/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject2/k1/6/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"cb5008ef92839a52d95dd527:32","filtered_window_id":"cb5008ef92839a52d95dd527","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb5008ef92839a52d95dd527/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject2/k1/6/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"cb5008ef92839a52d95dd527:40","filtered_window_id":"cb5008ef92839a52d95dd527","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb5008ef92839a52d95dd527/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject2/k1/6/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"cb5008ef92839a52d95dd527:48","filtered_window_id":"cb5008ef92839a52d95dd527","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb5008ef92839a52d95dd527/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject2/k1/6/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"cb5008ef92839a52d95dd527:52","filtered_window_id":"cb5008ef92839a52d95dd527","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb5008ef92839a52d95dd527/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[349,350,351,352,353,354,355,356],"take":"subject2/k1/6/cam4","frame_ids":[349,350,351,352,353,354,355,356]} +{"filtered_tile_id":"cb64741f2af07c98bb989d34:0","filtered_window_id":"cb64741f2af07c98bb989d34","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb64741f2af07c98bb989d34/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[136,137,138,139,140,141,142,143],"take":"subject3/h1/3/cam4","frame_ids":[136,137,138,139,140,141,142,143]} +{"filtered_tile_id":"cb64741f2af07c98bb989d34:8","filtered_window_id":"cb64741f2af07c98bb989d34","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb64741f2af07c98bb989d34/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[144,145,146,147,148,149,150,151],"take":"subject3/h1/3/cam4","frame_ids":[144,145,146,147,148,149,150,151]} +{"filtered_tile_id":"cb64741f2af07c98bb989d34:16","filtered_window_id":"cb64741f2af07c98bb989d34","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb64741f2af07c98bb989d34/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject3/h1/3/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"cb64741f2af07c98bb989d34:24","filtered_window_id":"cb64741f2af07c98bb989d34","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb64741f2af07c98bb989d34/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject3/h1/3/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"cb64741f2af07c98bb989d34:32","filtered_window_id":"cb64741f2af07c98bb989d34","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb64741f2af07c98bb989d34/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject3/h1/3/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"cb64741f2af07c98bb989d34:40","filtered_window_id":"cb64741f2af07c98bb989d34","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb64741f2af07c98bb989d34/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject3/h1/3/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"cb64741f2af07c98bb989d34:48","filtered_window_id":"cb64741f2af07c98bb989d34","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb64741f2af07c98bb989d34/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject3/h1/3/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"cb64741f2af07c98bb989d34:52","filtered_window_id":"cb64741f2af07c98bb989d34","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb64741f2af07c98bb989d34/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject3/h1/3/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"cb6e78b225353411fc80f833:0","filtered_window_id":"cb6e78b225353411fc80f833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb6e78b225353411fc80f833/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[364,365,366,367,368,369,370,371],"take":"subject1/h1/2/cam4","frame_ids":[364,365,366,367,368,369,370,371]} +{"filtered_tile_id":"cb6e78b225353411fc80f833:8","filtered_window_id":"cb6e78b225353411fc80f833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb6e78b225353411fc80f833/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject1/h1/2/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"cb6e78b225353411fc80f833:16","filtered_window_id":"cb6e78b225353411fc80f833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb6e78b225353411fc80f833/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject1/h1/2/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"cb6e78b225353411fc80f833:24","filtered_window_id":"cb6e78b225353411fc80f833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb6e78b225353411fc80f833/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject1/h1/2/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"cb6e78b225353411fc80f833:32","filtered_window_id":"cb6e78b225353411fc80f833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb6e78b225353411fc80f833/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject1/h1/2/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"cb6e78b225353411fc80f833:40","filtered_window_id":"cb6e78b225353411fc80f833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb6e78b225353411fc80f833/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject1/h1/2/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"cb6e78b225353411fc80f833:48","filtered_window_id":"cb6e78b225353411fc80f833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb6e78b225353411fc80f833/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject1/h1/2/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"cb6e78b225353411fc80f833:52","filtered_window_id":"cb6e78b225353411fc80f833","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb6e78b225353411fc80f833/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[416,417,418,419,420,421,422,423],"take":"subject1/h1/2/cam4","frame_ids":[416,417,418,419,420,421,422,423]} +{"filtered_tile_id":"cb70b9604d1934b69c95e8f7:0","filtered_window_id":"cb70b9604d1934b69c95e8f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb70b9604d1934b69c95e8f7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[498,499,500,501,502,503,504,505],"take":"subject1/h2/3/cam4","frame_ids":[498,499,500,501,502,503,504,505]} +{"filtered_tile_id":"cb70b9604d1934b69c95e8f7:8","filtered_window_id":"cb70b9604d1934b69c95e8f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb70b9604d1934b69c95e8f7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[506,507,508,509,510,511,512,513],"take":"subject1/h2/3/cam4","frame_ids":[506,507,508,509,510,511,512,513]} +{"filtered_tile_id":"cb70b9604d1934b69c95e8f7:16","filtered_window_id":"cb70b9604d1934b69c95e8f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb70b9604d1934b69c95e8f7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[514,515,516,517,518,519,520,521],"take":"subject1/h2/3/cam4","frame_ids":[514,515,516,517,518,519,520,521]} +{"filtered_tile_id":"cb70b9604d1934b69c95e8f7:24","filtered_window_id":"cb70b9604d1934b69c95e8f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb70b9604d1934b69c95e8f7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[522,523,524,525,526,527,528,529],"take":"subject1/h2/3/cam4","frame_ids":[522,523,524,525,526,527,528,529]} +{"filtered_tile_id":"cb70b9604d1934b69c95e8f7:32","filtered_window_id":"cb70b9604d1934b69c95e8f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb70b9604d1934b69c95e8f7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[530,531,532,533,534,535,536,537],"take":"subject1/h2/3/cam4","frame_ids":[530,531,532,533,534,535,536,537]} +{"filtered_tile_id":"cb70b9604d1934b69c95e8f7:40","filtered_window_id":"cb70b9604d1934b69c95e8f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb70b9604d1934b69c95e8f7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[538,539,540,541,542,543,544,545],"take":"subject1/h2/3/cam4","frame_ids":[538,539,540,541,542,543,544,545]} +{"filtered_tile_id":"cb70b9604d1934b69c95e8f7:48","filtered_window_id":"cb70b9604d1934b69c95e8f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb70b9604d1934b69c95e8f7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[546,547,548,549,550,551,552,553],"take":"subject1/h2/3/cam4","frame_ids":[546,547,548,549,550,551,552,553]} +{"filtered_tile_id":"cb70b9604d1934b69c95e8f7:52","filtered_window_id":"cb70b9604d1934b69c95e8f7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cb70b9604d1934b69c95e8f7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[550,551,552,553,554,555,556,557],"take":"subject1/h2/3/cam4","frame_ids":[550,551,552,553,554,555,556,557]} +{"filtered_tile_id":"cbfa99dfd9b2846c9b2ec5a2:0","filtered_window_id":"cbfa99dfd9b2846c9b2ec5a2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cbfa99dfd9b2846c9b2ec5a2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject1/k1/7/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"cbfa99dfd9b2846c9b2ec5a2:8","filtered_window_id":"cbfa99dfd9b2846c9b2ec5a2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cbfa99dfd9b2846c9b2ec5a2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[361,362,363,364,365,366,367,368],"take":"subject1/k1/7/cam4","frame_ids":[361,362,363,364,365,366,367,368]} +{"filtered_tile_id":"cbfa99dfd9b2846c9b2ec5a2:16","filtered_window_id":"cbfa99dfd9b2846c9b2ec5a2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cbfa99dfd9b2846c9b2ec5a2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[369,370,371,372,373,374,375,376],"take":"subject1/k1/7/cam4","frame_ids":[369,370,371,372,373,374,375,376]} +{"filtered_tile_id":"cbfa99dfd9b2846c9b2ec5a2:24","filtered_window_id":"cbfa99dfd9b2846c9b2ec5a2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cbfa99dfd9b2846c9b2ec5a2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[377,378,379,380,381,382,383,384],"take":"subject1/k1/7/cam4","frame_ids":[377,378,379,380,381,382,383,384]} +{"filtered_tile_id":"cbfa99dfd9b2846c9b2ec5a2:30","filtered_window_id":"cbfa99dfd9b2846c9b2ec5a2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cbfa99dfd9b2846c9b2ec5a2/native_gt.npz","filtered_start_offset":30,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject1/k1/7/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"cc074290fb22cb288cbd8f60:0","filtered_window_id":"cc074290fb22cb288cbd8f60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc074290fb22cb288cbd8f60/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject1/k1/5/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"cc074290fb22cb288cbd8f60:8","filtered_window_id":"cc074290fb22cb288cbd8f60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc074290fb22cb288cbd8f60/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject1/k1/5/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"cc074290fb22cb288cbd8f60:16","filtered_window_id":"cc074290fb22cb288cbd8f60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc074290fb22cb288cbd8f60/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject1/k1/5/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"cc074290fb22cb288cbd8f60:24","filtered_window_id":"cc074290fb22cb288cbd8f60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc074290fb22cb288cbd8f60/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject1/k1/5/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"cc074290fb22cb288cbd8f60:32","filtered_window_id":"cc074290fb22cb288cbd8f60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc074290fb22cb288cbd8f60/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject1/k1/5/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"cc074290fb22cb288cbd8f60:40","filtered_window_id":"cc074290fb22cb288cbd8f60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc074290fb22cb288cbd8f60/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[481,482,483,484,485,486,487,488],"take":"subject1/k1/5/cam4","frame_ids":[481,482,483,484,485,486,487,488]} +{"filtered_tile_id":"cc074290fb22cb288cbd8f60:46","filtered_window_id":"cc074290fb22cb288cbd8f60","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc074290fb22cb288cbd8f60/native_gt.npz","filtered_start_offset":46,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject1/k1/5/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"cc244969eebc7f125be98d4f:0","filtered_window_id":"cc244969eebc7f125be98d4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc244969eebc7f125be98d4f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject3/k1/6/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"cc244969eebc7f125be98d4f:8","filtered_window_id":"cc244969eebc7f125be98d4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc244969eebc7f125be98d4f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject3/k1/6/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"cc244969eebc7f125be98d4f:16","filtered_window_id":"cc244969eebc7f125be98d4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc244969eebc7f125be98d4f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject3/k1/6/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"cc244969eebc7f125be98d4f:24","filtered_window_id":"cc244969eebc7f125be98d4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc244969eebc7f125be98d4f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject3/k1/6/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"cc244969eebc7f125be98d4f:32","filtered_window_id":"cc244969eebc7f125be98d4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc244969eebc7f125be98d4f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject3/k1/6/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"cc244969eebc7f125be98d4f:40","filtered_window_id":"cc244969eebc7f125be98d4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc244969eebc7f125be98d4f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject3/k1/6/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"cc244969eebc7f125be98d4f:43","filtered_window_id":"cc244969eebc7f125be98d4f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc244969eebc7f125be98d4f/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject3/k1/6/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"cc9124918d1d7214f891ff5e:0","filtered_window_id":"cc9124918d1d7214f891ff5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc9124918d1d7214f891ff5e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[1,2,3,4,5,6,7,8],"take":"subject1/h2/2/cam4","frame_ids":[1,2,3,4,5,6,7,8]} +{"filtered_tile_id":"cc9124918d1d7214f891ff5e:8","filtered_window_id":"cc9124918d1d7214f891ff5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc9124918d1d7214f891ff5e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[9,10,11,12,13,14,15,16],"take":"subject1/h2/2/cam4","frame_ids":[9,10,11,12,13,14,15,16]} +{"filtered_tile_id":"cc9124918d1d7214f891ff5e:16","filtered_window_id":"cc9124918d1d7214f891ff5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc9124918d1d7214f891ff5e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[17,18,19,20,21,22,23,24],"take":"subject1/h2/2/cam4","frame_ids":[17,18,19,20,21,22,23,24]} +{"filtered_tile_id":"cc9124918d1d7214f891ff5e:24","filtered_window_id":"cc9124918d1d7214f891ff5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc9124918d1d7214f891ff5e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[25,26,27,28,29,30,31,32],"take":"subject1/h2/2/cam4","frame_ids":[25,26,27,28,29,30,31,32]} +{"filtered_tile_id":"cc9124918d1d7214f891ff5e:32","filtered_window_id":"cc9124918d1d7214f891ff5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc9124918d1d7214f891ff5e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[33,34,35,36,37,38,39,40],"take":"subject1/h2/2/cam4","frame_ids":[33,34,35,36,37,38,39,40]} +{"filtered_tile_id":"cc9124918d1d7214f891ff5e:40","filtered_window_id":"cc9124918d1d7214f891ff5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc9124918d1d7214f891ff5e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[41,42,43,44,45,46,47,48],"take":"subject1/h2/2/cam4","frame_ids":[41,42,43,44,45,46,47,48]} +{"filtered_tile_id":"cc9124918d1d7214f891ff5e:48","filtered_window_id":"cc9124918d1d7214f891ff5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc9124918d1d7214f891ff5e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[49,50,51,52,53,54,55,56],"take":"subject1/h2/2/cam4","frame_ids":[49,50,51,52,53,54,55,56]} +{"filtered_tile_id":"cc9124918d1d7214f891ff5e:52","filtered_window_id":"cc9124918d1d7214f891ff5e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cc9124918d1d7214f891ff5e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[53,54,55,56,57,58,59,60],"take":"subject1/h2/2/cam4","frame_ids":[53,54,55,56,57,58,59,60]} +{"filtered_tile_id":"cca59c2b96026597d4e2581c:0","filtered_window_id":"cca59c2b96026597d4e2581c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cca59c2b96026597d4e2581c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject1/h2/5/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"cca59c2b96026597d4e2581c:8","filtered_window_id":"cca59c2b96026597d4e2581c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cca59c2b96026597d4e2581c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[72,73,74,75,76,77,78,79],"take":"subject1/h2/5/cam4","frame_ids":[72,73,74,75,76,77,78,79]} +{"filtered_tile_id":"cca59c2b96026597d4e2581c:16","filtered_window_id":"cca59c2b96026597d4e2581c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cca59c2b96026597d4e2581c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[80,81,82,83,84,85,86,87],"take":"subject1/h2/5/cam4","frame_ids":[80,81,82,83,84,85,86,87]} +{"filtered_tile_id":"cca59c2b96026597d4e2581c:24","filtered_window_id":"cca59c2b96026597d4e2581c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cca59c2b96026597d4e2581c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject1/h2/5/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"cca59c2b96026597d4e2581c:32","filtered_window_id":"cca59c2b96026597d4e2581c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cca59c2b96026597d4e2581c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject1/h2/5/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"cca59c2b96026597d4e2581c:40","filtered_window_id":"cca59c2b96026597d4e2581c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cca59c2b96026597d4e2581c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[104,105,106,107,108,109,110,111],"take":"subject1/h2/5/cam4","frame_ids":[104,105,106,107,108,109,110,111]} +{"filtered_tile_id":"cca59c2b96026597d4e2581c:44","filtered_window_id":"cca59c2b96026597d4e2581c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cca59c2b96026597d4e2581c/native_gt.npz","filtered_start_offset":44,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/h2/5/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"cce5f7b2c29661255f3117a9:0","filtered_window_id":"cce5f7b2c29661255f3117a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cce5f7b2c29661255f3117a9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[657,658,659,660,661,662,663,664],"take":"subject3/k1/5/cam4","frame_ids":[657,658,659,660,661,662,663,664]} +{"filtered_tile_id":"cce5f7b2c29661255f3117a9:8","filtered_window_id":"cce5f7b2c29661255f3117a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cce5f7b2c29661255f3117a9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[665,666,667,668,669,670,671,672],"take":"subject3/k1/5/cam4","frame_ids":[665,666,667,668,669,670,671,672]} +{"filtered_tile_id":"cce5f7b2c29661255f3117a9:16","filtered_window_id":"cce5f7b2c29661255f3117a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cce5f7b2c29661255f3117a9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[673,674,675,676,677,678,679,680],"take":"subject3/k1/5/cam4","frame_ids":[673,674,675,676,677,678,679,680]} +{"filtered_tile_id":"cce5f7b2c29661255f3117a9:24","filtered_window_id":"cce5f7b2c29661255f3117a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cce5f7b2c29661255f3117a9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[681,682,683,684,685,686,687,688],"take":"subject3/k1/5/cam4","frame_ids":[681,682,683,684,685,686,687,688]} +{"filtered_tile_id":"cce5f7b2c29661255f3117a9:32","filtered_window_id":"cce5f7b2c29661255f3117a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cce5f7b2c29661255f3117a9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[689,690,691,692,693,694,695,696],"take":"subject3/k1/5/cam4","frame_ids":[689,690,691,692,693,694,695,696]} +{"filtered_tile_id":"cce5f7b2c29661255f3117a9:40","filtered_window_id":"cce5f7b2c29661255f3117a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cce5f7b2c29661255f3117a9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[697,698,699,700,701,702,703,704],"take":"subject3/k1/5/cam4","frame_ids":[697,698,699,700,701,702,703,704]} +{"filtered_tile_id":"cce5f7b2c29661255f3117a9:48","filtered_window_id":"cce5f7b2c29661255f3117a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cce5f7b2c29661255f3117a9/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[705,706,707,708,709,710,711,712],"take":"subject3/k1/5/cam4","frame_ids":[705,706,707,708,709,710,711,712]} +{"filtered_tile_id":"cce5f7b2c29661255f3117a9:52","filtered_window_id":"cce5f7b2c29661255f3117a9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cce5f7b2c29661255f3117a9/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[709,710,711,712,713,714,715,716],"take":"subject3/k1/5/cam4","frame_ids":[709,710,711,712,713,714,715,716]} +{"filtered_tile_id":"cd4b8ad3e7d35c97cde8e59e:0","filtered_window_id":"cd4b8ad3e7d35c97cde8e59e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cd4b8ad3e7d35c97cde8e59e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject2/h2/6/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"cd4b8ad3e7d35c97cde8e59e:8","filtered_window_id":"cd4b8ad3e7d35c97cde8e59e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cd4b8ad3e7d35c97cde8e59e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject2/h2/6/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"cd4b8ad3e7d35c97cde8e59e:16","filtered_window_id":"cd4b8ad3e7d35c97cde8e59e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cd4b8ad3e7d35c97cde8e59e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject2/h2/6/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"cd4b8ad3e7d35c97cde8e59e:24","filtered_window_id":"cd4b8ad3e7d35c97cde8e59e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cd4b8ad3e7d35c97cde8e59e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[274,275,276,277,278,279,280,281],"take":"subject2/h2/6/cam4","frame_ids":[274,275,276,277,278,279,280,281]} +{"filtered_tile_id":"cd4b8ad3e7d35c97cde8e59e:32","filtered_window_id":"cd4b8ad3e7d35c97cde8e59e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cd4b8ad3e7d35c97cde8e59e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject2/h2/6/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"cd4b8ad3e7d35c97cde8e59e:40","filtered_window_id":"cd4b8ad3e7d35c97cde8e59e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cd4b8ad3e7d35c97cde8e59e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[290,291,292,293,294,295,296,297],"take":"subject2/h2/6/cam4","frame_ids":[290,291,292,293,294,295,296,297]} +{"filtered_tile_id":"cd4b8ad3e7d35c97cde8e59e:48","filtered_window_id":"cd4b8ad3e7d35c97cde8e59e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cd4b8ad3e7d35c97cde8e59e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject2/h2/6/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"cd4b8ad3e7d35c97cde8e59e:52","filtered_window_id":"cd4b8ad3e7d35c97cde8e59e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cd4b8ad3e7d35c97cde8e59e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[302,303,304,305,306,307,308,309],"take":"subject2/h2/6/cam4","frame_ids":[302,303,304,305,306,307,308,309]} +{"filtered_tile_id":"cd863069fde495cbe6522b58:0","filtered_window_id":"cd863069fde495cbe6522b58","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cd863069fde495cbe6522b58/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[649,650,651,652,653,654,655,656],"take":"subject3/k1/5/cam4","frame_ids":[649,650,651,652,653,654,655,656]} +{"filtered_tile_id":"cdb82fbe363b806a9bbcea04:0","filtered_window_id":"cdb82fbe363b806a9bbcea04","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdb82fbe363b806a9bbcea04/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[38,39,40,41,42,43,44,45],"take":"subject2/o1/1/cam4","frame_ids":[38,39,40,41,42,43,44,45]} +{"filtered_tile_id":"cdb82fbe363b806a9bbcea04:8","filtered_window_id":"cdb82fbe363b806a9bbcea04","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdb82fbe363b806a9bbcea04/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[46,47,48,49,50,51,52,53],"take":"subject2/o1/1/cam4","frame_ids":[46,47,48,49,50,51,52,53]} +{"filtered_tile_id":"cdb82fbe363b806a9bbcea04:16","filtered_window_id":"cdb82fbe363b806a9bbcea04","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdb82fbe363b806a9bbcea04/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[54,55,56,57,58,59,60,61],"take":"subject2/o1/1/cam4","frame_ids":[54,55,56,57,58,59,60,61]} +{"filtered_tile_id":"cdb82fbe363b806a9bbcea04:24","filtered_window_id":"cdb82fbe363b806a9bbcea04","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdb82fbe363b806a9bbcea04/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[62,63,64,65,66,67,68,69],"take":"subject2/o1/1/cam4","frame_ids":[62,63,64,65,66,67,68,69]} +{"filtered_tile_id":"cdb82fbe363b806a9bbcea04:32","filtered_window_id":"cdb82fbe363b806a9bbcea04","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdb82fbe363b806a9bbcea04/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[70,71,72,73,74,75,76,77],"take":"subject2/o1/1/cam4","frame_ids":[70,71,72,73,74,75,76,77]} +{"filtered_tile_id":"cdb82fbe363b806a9bbcea04:40","filtered_window_id":"cdb82fbe363b806a9bbcea04","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdb82fbe363b806a9bbcea04/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject2/o1/1/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"cdb82fbe363b806a9bbcea04:48","filtered_window_id":"cdb82fbe363b806a9bbcea04","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdb82fbe363b806a9bbcea04/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[86,87,88,89,90,91,92,93],"take":"subject2/o1/1/cam4","frame_ids":[86,87,88,89,90,91,92,93]} +{"filtered_tile_id":"cdb82fbe363b806a9bbcea04:52","filtered_window_id":"cdb82fbe363b806a9bbcea04","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdb82fbe363b806a9bbcea04/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject2/o1/1/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"cdf931a235b1af54b9de2ad5:0","filtered_window_id":"cdf931a235b1af54b9de2ad5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdf931a235b1af54b9de2ad5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[849,850,851,852,853,854,855,856],"take":"subject1/h1/3/cam4","frame_ids":[849,850,851,852,853,854,855,856]} +{"filtered_tile_id":"cdf931a235b1af54b9de2ad5:8","filtered_window_id":"cdf931a235b1af54b9de2ad5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdf931a235b1af54b9de2ad5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[857,858,859,860,861,862,863,864],"take":"subject1/h1/3/cam4","frame_ids":[857,858,859,860,861,862,863,864]} +{"filtered_tile_id":"cdf931a235b1af54b9de2ad5:16","filtered_window_id":"cdf931a235b1af54b9de2ad5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdf931a235b1af54b9de2ad5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[865,866,867,868,869,870,871,872],"take":"subject1/h1/3/cam4","frame_ids":[865,866,867,868,869,870,871,872]} +{"filtered_tile_id":"cdf931a235b1af54b9de2ad5:24","filtered_window_id":"cdf931a235b1af54b9de2ad5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdf931a235b1af54b9de2ad5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[873,874,875,876,877,878,879,880],"take":"subject1/h1/3/cam4","frame_ids":[873,874,875,876,877,878,879,880]} +{"filtered_tile_id":"cdf931a235b1af54b9de2ad5:32","filtered_window_id":"cdf931a235b1af54b9de2ad5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdf931a235b1af54b9de2ad5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[881,882,883,884,885,886,887,888],"take":"subject1/h1/3/cam4","frame_ids":[881,882,883,884,885,886,887,888]} +{"filtered_tile_id":"cdf931a235b1af54b9de2ad5:40","filtered_window_id":"cdf931a235b1af54b9de2ad5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdf931a235b1af54b9de2ad5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[889,890,891,892,893,894,895,896],"take":"subject1/h1/3/cam4","frame_ids":[889,890,891,892,893,894,895,896]} +{"filtered_tile_id":"cdf931a235b1af54b9de2ad5:48","filtered_window_id":"cdf931a235b1af54b9de2ad5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdf931a235b1af54b9de2ad5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[897,898,899,900,901,902,903,904],"take":"subject1/h1/3/cam4","frame_ids":[897,898,899,900,901,902,903,904]} +{"filtered_tile_id":"cdf931a235b1af54b9de2ad5:52","filtered_window_id":"cdf931a235b1af54b9de2ad5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cdf931a235b1af54b9de2ad5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[901,902,903,904,905,906,907,908],"take":"subject1/h1/3/cam4","frame_ids":[901,902,903,904,905,906,907,908]} +{"filtered_tile_id":"ce093cc3e5b4cf5897cd3583:0","filtered_window_id":"ce093cc3e5b4cf5897cd3583","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ce093cc3e5b4cf5897cd3583/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject3/h1/7/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"ce093cc3e5b4cf5897cd3583:8","filtered_window_id":"ce093cc3e5b4cf5897cd3583","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ce093cc3e5b4cf5897cd3583/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject3/h1/7/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"ce093cc3e5b4cf5897cd3583:16","filtered_window_id":"ce093cc3e5b4cf5897cd3583","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ce093cc3e5b4cf5897cd3583/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject3/h1/7/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"ce093cc3e5b4cf5897cd3583:24","filtered_window_id":"ce093cc3e5b4cf5897cd3583","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ce093cc3e5b4cf5897cd3583/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject3/h1/7/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"ce093cc3e5b4cf5897cd3583:32","filtered_window_id":"ce093cc3e5b4cf5897cd3583","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ce093cc3e5b4cf5897cd3583/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject3/h1/7/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"ce093cc3e5b4cf5897cd3583:40","filtered_window_id":"ce093cc3e5b4cf5897cd3583","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ce093cc3e5b4cf5897cd3583/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject3/h1/7/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"ce093cc3e5b4cf5897cd3583:48","filtered_window_id":"ce093cc3e5b4cf5897cd3583","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ce093cc3e5b4cf5897cd3583/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject3/h1/7/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"ce093cc3e5b4cf5897cd3583:52","filtered_window_id":"ce093cc3e5b4cf5897cd3583","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ce093cc3e5b4cf5897cd3583/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject3/h1/7/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"cecc84271dff23f5c930b93c:0","filtered_window_id":"cecc84271dff23f5c930b93c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cecc84271dff23f5c930b93c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject1/h2/7/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"cecc84271dff23f5c930b93c:8","filtered_window_id":"cecc84271dff23f5c930b93c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cecc84271dff23f5c930b93c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject1/h2/7/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"cecc84271dff23f5c930b93c:16","filtered_window_id":"cecc84271dff23f5c930b93c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cecc84271dff23f5c930b93c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject1/h2/7/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"cecc84271dff23f5c930b93c:24","filtered_window_id":"cecc84271dff23f5c930b93c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cecc84271dff23f5c930b93c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject1/h2/7/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"cecc84271dff23f5c930b93c:32","filtered_window_id":"cecc84271dff23f5c930b93c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cecc84271dff23f5c930b93c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject1/h2/7/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"cecc84271dff23f5c930b93c:35","filtered_window_id":"cecc84271dff23f5c930b93c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cecc84271dff23f5c930b93c/native_gt.npz","filtered_start_offset":35,"expected_frame_ids":[284,285,286,287,288,289,290,291],"take":"subject1/h2/7/cam4","frame_ids":[284,285,286,287,288,289,290,291]} +{"filtered_tile_id":"ceec2c4d20d2196e49880e1c:0","filtered_window_id":"ceec2c4d20d2196e49880e1c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ceec2c4d20d2196e49880e1c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[150,151,152,153,154,155,156,157],"take":"subject2/k1/5/cam4","frame_ids":[150,151,152,153,154,155,156,157]} +{"filtered_tile_id":"ceec2c4d20d2196e49880e1c:8","filtered_window_id":"ceec2c4d20d2196e49880e1c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ceec2c4d20d2196e49880e1c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[158,159,160,161,162,163,164,165],"take":"subject2/k1/5/cam4","frame_ids":[158,159,160,161,162,163,164,165]} +{"filtered_tile_id":"ceec2c4d20d2196e49880e1c:16","filtered_window_id":"ceec2c4d20d2196e49880e1c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ceec2c4d20d2196e49880e1c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject2/k1/5/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"ceec2c4d20d2196e49880e1c:24","filtered_window_id":"ceec2c4d20d2196e49880e1c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ceec2c4d20d2196e49880e1c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject2/k1/5/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"ceec2c4d20d2196e49880e1c:32","filtered_window_id":"ceec2c4d20d2196e49880e1c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ceec2c4d20d2196e49880e1c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject2/k1/5/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"ceec2c4d20d2196e49880e1c:40","filtered_window_id":"ceec2c4d20d2196e49880e1c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ceec2c4d20d2196e49880e1c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject2/k1/5/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"ceec2c4d20d2196e49880e1c:48","filtered_window_id":"ceec2c4d20d2196e49880e1c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ceec2c4d20d2196e49880e1c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject2/k1/5/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"ceec2c4d20d2196e49880e1c:52","filtered_window_id":"ceec2c4d20d2196e49880e1c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ceec2c4d20d2196e49880e1c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[202,203,204,205,206,207,208,209],"take":"subject2/k1/5/cam4","frame_ids":[202,203,204,205,206,207,208,209]} +{"filtered_tile_id":"cefeee38b4438b012d0e3243:0","filtered_window_id":"cefeee38b4438b012d0e3243","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cefeee38b4438b012d0e3243/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject2/o2/6/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"cefeee38b4438b012d0e3243:8","filtered_window_id":"cefeee38b4438b012d0e3243","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cefeee38b4438b012d0e3243/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject2/o2/6/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"cefeee38b4438b012d0e3243:16","filtered_window_id":"cefeee38b4438b012d0e3243","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cefeee38b4438b012d0e3243/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject2/o2/6/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"cefeee38b4438b012d0e3243:24","filtered_window_id":"cefeee38b4438b012d0e3243","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cefeee38b4438b012d0e3243/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject2/o2/6/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"cefeee38b4438b012d0e3243:32","filtered_window_id":"cefeee38b4438b012d0e3243","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cefeee38b4438b012d0e3243/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject2/o2/6/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"cefeee38b4438b012d0e3243:40","filtered_window_id":"cefeee38b4438b012d0e3243","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cefeee38b4438b012d0e3243/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject2/o2/6/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"cefeee38b4438b012d0e3243:48","filtered_window_id":"cefeee38b4438b012d0e3243","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cefeee38b4438b012d0e3243/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject2/o2/6/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"cefeee38b4438b012d0e3243:52","filtered_window_id":"cefeee38b4438b012d0e3243","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cefeee38b4438b012d0e3243/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject2/o2/6/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"cf11e37b8610b90c0e75a2a6:0","filtered_window_id":"cf11e37b8610b90c0e75a2a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf11e37b8610b90c0e75a2a6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject2/k2/6/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"cf11e37b8610b90c0e75a2a6:8","filtered_window_id":"cf11e37b8610b90c0e75a2a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf11e37b8610b90c0e75a2a6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject2/k2/6/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"cf11e37b8610b90c0e75a2a6:16","filtered_window_id":"cf11e37b8610b90c0e75a2a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf11e37b8610b90c0e75a2a6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject2/k2/6/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"cf11e37b8610b90c0e75a2a6:24","filtered_window_id":"cf11e37b8610b90c0e75a2a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf11e37b8610b90c0e75a2a6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject2/k2/6/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"cf11e37b8610b90c0e75a2a6:32","filtered_window_id":"cf11e37b8610b90c0e75a2a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf11e37b8610b90c0e75a2a6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject2/k2/6/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"cf11e37b8610b90c0e75a2a6:40","filtered_window_id":"cf11e37b8610b90c0e75a2a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf11e37b8610b90c0e75a2a6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject2/k2/6/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"cf11e37b8610b90c0e75a2a6:48","filtered_window_id":"cf11e37b8610b90c0e75a2a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf11e37b8610b90c0e75a2a6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject2/k2/6/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"cf11e37b8610b90c0e75a2a6:52","filtered_window_id":"cf11e37b8610b90c0e75a2a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf11e37b8610b90c0e75a2a6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject2/k2/6/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"cf257af259cf649905b55d86:0","filtered_window_id":"cf257af259cf649905b55d86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf257af259cf649905b55d86/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject1/o2/1/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"cf257af259cf649905b55d86:8","filtered_window_id":"cf257af259cf649905b55d86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf257af259cf649905b55d86/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject1/o2/1/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"cf257af259cf649905b55d86:16","filtered_window_id":"cf257af259cf649905b55d86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf257af259cf649905b55d86/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject1/o2/1/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"cf257af259cf649905b55d86:24","filtered_window_id":"cf257af259cf649905b55d86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf257af259cf649905b55d86/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject1/o2/1/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"cf257af259cf649905b55d86:32","filtered_window_id":"cf257af259cf649905b55d86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf257af259cf649905b55d86/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject1/o2/1/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"cf257af259cf649905b55d86:40","filtered_window_id":"cf257af259cf649905b55d86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf257af259cf649905b55d86/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[361,362,363,364,365,366,367,368],"take":"subject1/o2/1/cam4","frame_ids":[361,362,363,364,365,366,367,368]} +{"filtered_tile_id":"cf257af259cf649905b55d86:48","filtered_window_id":"cf257af259cf649905b55d86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf257af259cf649905b55d86/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[369,370,371,372,373,374,375,376],"take":"subject1/o2/1/cam4","frame_ids":[369,370,371,372,373,374,375,376]} +{"filtered_tile_id":"cf257af259cf649905b55d86:52","filtered_window_id":"cf257af259cf649905b55d86","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf257af259cf649905b55d86/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[373,374,375,376,377,378,379,380],"take":"subject1/o2/1/cam4","frame_ids":[373,374,375,376,377,378,379,380]} +{"filtered_tile_id":"cf4180a03cc8b7e240687bca:0","filtered_window_id":"cf4180a03cc8b7e240687bca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf4180a03cc8b7e240687bca/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[220,221,222,223,224,225,226,227],"take":"subject2/o1/0/cam4","frame_ids":[220,221,222,223,224,225,226,227]} +{"filtered_tile_id":"cf4180a03cc8b7e240687bca:8","filtered_window_id":"cf4180a03cc8b7e240687bca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf4180a03cc8b7e240687bca/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[228,229,230,231,232,233,234,235],"take":"subject2/o1/0/cam4","frame_ids":[228,229,230,231,232,233,234,235]} +{"filtered_tile_id":"cf4180a03cc8b7e240687bca:16","filtered_window_id":"cf4180a03cc8b7e240687bca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf4180a03cc8b7e240687bca/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[236,237,238,239,240,241,242,243],"take":"subject2/o1/0/cam4","frame_ids":[236,237,238,239,240,241,242,243]} +{"filtered_tile_id":"cf4180a03cc8b7e240687bca:24","filtered_window_id":"cf4180a03cc8b7e240687bca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf4180a03cc8b7e240687bca/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[244,245,246,247,248,249,250,251],"take":"subject2/o1/0/cam4","frame_ids":[244,245,246,247,248,249,250,251]} +{"filtered_tile_id":"cf4180a03cc8b7e240687bca:32","filtered_window_id":"cf4180a03cc8b7e240687bca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf4180a03cc8b7e240687bca/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[252,253,254,255,256,257,258,259],"take":"subject2/o1/0/cam4","frame_ids":[252,253,254,255,256,257,258,259]} +{"filtered_tile_id":"cf4180a03cc8b7e240687bca:40","filtered_window_id":"cf4180a03cc8b7e240687bca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf4180a03cc8b7e240687bca/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[260,261,262,263,264,265,266,267],"take":"subject2/o1/0/cam4","frame_ids":[260,261,262,263,264,265,266,267]} +{"filtered_tile_id":"cf4180a03cc8b7e240687bca:43","filtered_window_id":"cf4180a03cc8b7e240687bca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf4180a03cc8b7e240687bca/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject2/o1/0/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"cf5e28fb5765c0757d332772:0","filtered_window_id":"cf5e28fb5765c0757d332772","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf5e28fb5765c0757d332772/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[557,558,559,560,561,562,563,564],"take":"subject2/o1/6/cam4","frame_ids":[557,558,559,560,561,562,563,564]} +{"filtered_tile_id":"cf5e28fb5765c0757d332772:8","filtered_window_id":"cf5e28fb5765c0757d332772","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf5e28fb5765c0757d332772/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[565,566,567,568,569,570,571,572],"take":"subject2/o1/6/cam4","frame_ids":[565,566,567,568,569,570,571,572]} +{"filtered_tile_id":"cf5e28fb5765c0757d332772:16","filtered_window_id":"cf5e28fb5765c0757d332772","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf5e28fb5765c0757d332772/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[573,574,575,576,577,578,579,580],"take":"subject2/o1/6/cam4","frame_ids":[573,574,575,576,577,578,579,580]} +{"filtered_tile_id":"cf5e28fb5765c0757d332772:24","filtered_window_id":"cf5e28fb5765c0757d332772","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf5e28fb5765c0757d332772/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[581,582,583,584,585,586,587,588],"take":"subject2/o1/6/cam4","frame_ids":[581,582,583,584,585,586,587,588]} +{"filtered_tile_id":"cf5e28fb5765c0757d332772:32","filtered_window_id":"cf5e28fb5765c0757d332772","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf5e28fb5765c0757d332772/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[589,590,591,592,593,594,595,596],"take":"subject2/o1/6/cam4","frame_ids":[589,590,591,592,593,594,595,596]} +{"filtered_tile_id":"cf5e28fb5765c0757d332772:40","filtered_window_id":"cf5e28fb5765c0757d332772","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf5e28fb5765c0757d332772/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[597,598,599,600,601,602,603,604],"take":"subject2/o1/6/cam4","frame_ids":[597,598,599,600,601,602,603,604]} +{"filtered_tile_id":"cf5e28fb5765c0757d332772:48","filtered_window_id":"cf5e28fb5765c0757d332772","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf5e28fb5765c0757d332772/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[605,606,607,608,609,610,611,612],"take":"subject2/o1/6/cam4","frame_ids":[605,606,607,608,609,610,611,612]} +{"filtered_tile_id":"cf5e28fb5765c0757d332772:52","filtered_window_id":"cf5e28fb5765c0757d332772","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cf5e28fb5765c0757d332772/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[609,610,611,612,613,614,615,616],"take":"subject2/o1/6/cam4","frame_ids":[609,610,611,612,613,614,615,616]} +{"filtered_tile_id":"cfe70615e2504c26287673bf:0","filtered_window_id":"cfe70615e2504c26287673bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cfe70615e2504c26287673bf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[618,619,620,621,622,623,624,625],"take":"subject2/h2/6/cam4","frame_ids":[618,619,620,621,622,623,624,625]} +{"filtered_tile_id":"cfe70615e2504c26287673bf:8","filtered_window_id":"cfe70615e2504c26287673bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cfe70615e2504c26287673bf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[626,627,628,629,630,631,632,633],"take":"subject2/h2/6/cam4","frame_ids":[626,627,628,629,630,631,632,633]} +{"filtered_tile_id":"cfe70615e2504c26287673bf:16","filtered_window_id":"cfe70615e2504c26287673bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cfe70615e2504c26287673bf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[634,635,636,637,638,639,640,641],"take":"subject2/h2/6/cam4","frame_ids":[634,635,636,637,638,639,640,641]} +{"filtered_tile_id":"cfe70615e2504c26287673bf:24","filtered_window_id":"cfe70615e2504c26287673bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cfe70615e2504c26287673bf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[642,643,644,645,646,647,648,649],"take":"subject2/h2/6/cam4","frame_ids":[642,643,644,645,646,647,648,649]} +{"filtered_tile_id":"cfe70615e2504c26287673bf:32","filtered_window_id":"cfe70615e2504c26287673bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cfe70615e2504c26287673bf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[650,651,652,653,654,655,656,657],"take":"subject2/h2/6/cam4","frame_ids":[650,651,652,653,654,655,656,657]} +{"filtered_tile_id":"cfe70615e2504c26287673bf:40","filtered_window_id":"cfe70615e2504c26287673bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cfe70615e2504c26287673bf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[658,659,660,661,662,663,664,665],"take":"subject2/h2/6/cam4","frame_ids":[658,659,660,661,662,663,664,665]} +{"filtered_tile_id":"cfe70615e2504c26287673bf:48","filtered_window_id":"cfe70615e2504c26287673bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cfe70615e2504c26287673bf/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[666,667,668,669,670,671,672,673],"take":"subject2/h2/6/cam4","frame_ids":[666,667,668,669,670,671,672,673]} +{"filtered_tile_id":"cfe70615e2504c26287673bf:52","filtered_window_id":"cfe70615e2504c26287673bf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/cfe70615e2504c26287673bf/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[670,671,672,673,674,675,676,677],"take":"subject2/h2/6/cam4","frame_ids":[670,671,672,673,674,675,676,677]} +{"filtered_tile_id":"d00ac116200028bbacceb581:0","filtered_window_id":"d00ac116200028bbacceb581","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d00ac116200028bbacceb581/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[561,562,563,564,565,566,567,568],"take":"subject2/h2/6/cam4","frame_ids":[561,562,563,564,565,566,567,568]} +{"filtered_tile_id":"d00ac116200028bbacceb581:1","filtered_window_id":"d00ac116200028bbacceb581","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d00ac116200028bbacceb581/native_gt.npz","filtered_start_offset":1,"expected_frame_ids":[562,563,564,565,566,567,568,569],"take":"subject2/h2/6/cam4","frame_ids":[562,563,564,565,566,567,568,569]} +{"filtered_tile_id":"d08e3a0e41e56d4d1f50c067:0","filtered_window_id":"d08e3a0e41e56d4d1f50c067","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d08e3a0e41e56d4d1f50c067/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[101,102,103,104,105,106,107,108],"take":"subject2/o2/0/cam4","frame_ids":[101,102,103,104,105,106,107,108]} +{"filtered_tile_id":"d08e3a0e41e56d4d1f50c067:8","filtered_window_id":"d08e3a0e41e56d4d1f50c067","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d08e3a0e41e56d4d1f50c067/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[109,110,111,112,113,114,115,116],"take":"subject2/o2/0/cam4","frame_ids":[109,110,111,112,113,114,115,116]} +{"filtered_tile_id":"d08e3a0e41e56d4d1f50c067:16","filtered_window_id":"d08e3a0e41e56d4d1f50c067","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d08e3a0e41e56d4d1f50c067/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[117,118,119,120,121,122,123,124],"take":"subject2/o2/0/cam4","frame_ids":[117,118,119,120,121,122,123,124]} +{"filtered_tile_id":"d08e3a0e41e56d4d1f50c067:24","filtered_window_id":"d08e3a0e41e56d4d1f50c067","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d08e3a0e41e56d4d1f50c067/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[125,126,127,128,129,130,131,132],"take":"subject2/o2/0/cam4","frame_ids":[125,126,127,128,129,130,131,132]} +{"filtered_tile_id":"d08e3a0e41e56d4d1f50c067:32","filtered_window_id":"d08e3a0e41e56d4d1f50c067","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d08e3a0e41e56d4d1f50c067/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject2/o2/0/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"d08e3a0e41e56d4d1f50c067:40","filtered_window_id":"d08e3a0e41e56d4d1f50c067","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d08e3a0e41e56d4d1f50c067/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject2/o2/0/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"d08e3a0e41e56d4d1f50c067:48","filtered_window_id":"d08e3a0e41e56d4d1f50c067","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d08e3a0e41e56d4d1f50c067/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject2/o2/0/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"d08e3a0e41e56d4d1f50c067:52","filtered_window_id":"d08e3a0e41e56d4d1f50c067","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d08e3a0e41e56d4d1f50c067/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[153,154,155,156,157,158,159,160],"take":"subject2/o2/0/cam4","frame_ids":[153,154,155,156,157,158,159,160]} +{"filtered_tile_id":"d110b57d230f719f9db35f0b:0","filtered_window_id":"d110b57d230f719f9db35f0b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d110b57d230f719f9db35f0b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[177,178,179,180,181,182,183,184],"take":"subject1/o1/5/cam4","frame_ids":[177,178,179,180,181,182,183,184]} +{"filtered_tile_id":"d110b57d230f719f9db35f0b:8","filtered_window_id":"d110b57d230f719f9db35f0b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d110b57d230f719f9db35f0b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[185,186,187,188,189,190,191,192],"take":"subject1/o1/5/cam4","frame_ids":[185,186,187,188,189,190,191,192]} +{"filtered_tile_id":"d110b57d230f719f9db35f0b:16","filtered_window_id":"d110b57d230f719f9db35f0b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d110b57d230f719f9db35f0b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject1/o1/5/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"d110b57d230f719f9db35f0b:24","filtered_window_id":"d110b57d230f719f9db35f0b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d110b57d230f719f9db35f0b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject1/o1/5/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"d110b57d230f719f9db35f0b:32","filtered_window_id":"d110b57d230f719f9db35f0b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d110b57d230f719f9db35f0b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject1/o1/5/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"d110b57d230f719f9db35f0b:40","filtered_window_id":"d110b57d230f719f9db35f0b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d110b57d230f719f9db35f0b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject1/o1/5/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"d110b57d230f719f9db35f0b:48","filtered_window_id":"d110b57d230f719f9db35f0b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d110b57d230f719f9db35f0b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject1/o1/5/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"d110b57d230f719f9db35f0b:52","filtered_window_id":"d110b57d230f719f9db35f0b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d110b57d230f719f9db35f0b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject1/o1/5/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"d13460ab3a79092bedeebe14:0","filtered_window_id":"d13460ab3a79092bedeebe14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d13460ab3a79092bedeebe14/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[628,629,630,631,632,633,634,635],"take":"subject2/h2/4/cam4","frame_ids":[628,629,630,631,632,633,634,635]} +{"filtered_tile_id":"d13460ab3a79092bedeebe14:8","filtered_window_id":"d13460ab3a79092bedeebe14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d13460ab3a79092bedeebe14/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[636,637,638,639,640,641,642,643],"take":"subject2/h2/4/cam4","frame_ids":[636,637,638,639,640,641,642,643]} +{"filtered_tile_id":"d13460ab3a79092bedeebe14:16","filtered_window_id":"d13460ab3a79092bedeebe14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d13460ab3a79092bedeebe14/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[644,645,646,647,648,649,650,651],"take":"subject2/h2/4/cam4","frame_ids":[644,645,646,647,648,649,650,651]} +{"filtered_tile_id":"d13460ab3a79092bedeebe14:24","filtered_window_id":"d13460ab3a79092bedeebe14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d13460ab3a79092bedeebe14/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[652,653,654,655,656,657,658,659],"take":"subject2/h2/4/cam4","frame_ids":[652,653,654,655,656,657,658,659]} +{"filtered_tile_id":"d13460ab3a79092bedeebe14:32","filtered_window_id":"d13460ab3a79092bedeebe14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d13460ab3a79092bedeebe14/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[660,661,662,663,664,665,666,667],"take":"subject2/h2/4/cam4","frame_ids":[660,661,662,663,664,665,666,667]} +{"filtered_tile_id":"d13460ab3a79092bedeebe14:40","filtered_window_id":"d13460ab3a79092bedeebe14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d13460ab3a79092bedeebe14/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[668,669,670,671,672,673,674,675],"take":"subject2/h2/4/cam4","frame_ids":[668,669,670,671,672,673,674,675]} +{"filtered_tile_id":"d13460ab3a79092bedeebe14:48","filtered_window_id":"d13460ab3a79092bedeebe14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d13460ab3a79092bedeebe14/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[676,677,678,679,680,681,682,683],"take":"subject2/h2/4/cam4","frame_ids":[676,677,678,679,680,681,682,683]} +{"filtered_tile_id":"d13460ab3a79092bedeebe14:52","filtered_window_id":"d13460ab3a79092bedeebe14","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d13460ab3a79092bedeebe14/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[680,681,682,683,684,685,686,687],"take":"subject2/h2/4/cam4","frame_ids":[680,681,682,683,684,685,686,687]} +{"filtered_tile_id":"d14ef6c0fa52f5b4f530e643:0","filtered_window_id":"d14ef6c0fa52f5b4f530e643","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d14ef6c0fa52f5b4f530e643/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject2/h1/1/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"d14ef6c0fa52f5b4f530e643:8","filtered_window_id":"d14ef6c0fa52f5b4f530e643","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d14ef6c0fa52f5b4f530e643/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[306,307,308,309,310,311,312,313],"take":"subject2/h1/1/cam4","frame_ids":[306,307,308,309,310,311,312,313]} +{"filtered_tile_id":"d14ef6c0fa52f5b4f530e643:16","filtered_window_id":"d14ef6c0fa52f5b4f530e643","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d14ef6c0fa52f5b4f530e643/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject2/h1/1/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"d14ef6c0fa52f5b4f530e643:24","filtered_window_id":"d14ef6c0fa52f5b4f530e643","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d14ef6c0fa52f5b4f530e643/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[322,323,324,325,326,327,328,329],"take":"subject2/h1/1/cam4","frame_ids":[322,323,324,325,326,327,328,329]} +{"filtered_tile_id":"d14ef6c0fa52f5b4f530e643:32","filtered_window_id":"d14ef6c0fa52f5b4f530e643","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d14ef6c0fa52f5b4f530e643/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject2/h1/1/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"d14ef6c0fa52f5b4f530e643:40","filtered_window_id":"d14ef6c0fa52f5b4f530e643","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d14ef6c0fa52f5b4f530e643/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject2/h1/1/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"d14ef6c0fa52f5b4f530e643:48","filtered_window_id":"d14ef6c0fa52f5b4f530e643","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d14ef6c0fa52f5b4f530e643/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject2/h1/1/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"d14ef6c0fa52f5b4f530e643:52","filtered_window_id":"d14ef6c0fa52f5b4f530e643","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d14ef6c0fa52f5b4f530e643/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject2/h1/1/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"d1f1c457757ae664ec16bf87:0","filtered_window_id":"d1f1c457757ae664ec16bf87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d1f1c457757ae664ec16bf87/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[393,394,395,396,397,398,399,400],"take":"subject1/h1/7/cam4","frame_ids":[393,394,395,396,397,398,399,400]} +{"filtered_tile_id":"d1f1c457757ae664ec16bf87:8","filtered_window_id":"d1f1c457757ae664ec16bf87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d1f1c457757ae664ec16bf87/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[401,402,403,404,405,406,407,408],"take":"subject1/h1/7/cam4","frame_ids":[401,402,403,404,405,406,407,408]} +{"filtered_tile_id":"d1f1c457757ae664ec16bf87:16","filtered_window_id":"d1f1c457757ae664ec16bf87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d1f1c457757ae664ec16bf87/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[409,410,411,412,413,414,415,416],"take":"subject1/h1/7/cam4","frame_ids":[409,410,411,412,413,414,415,416]} +{"filtered_tile_id":"d1f1c457757ae664ec16bf87:24","filtered_window_id":"d1f1c457757ae664ec16bf87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d1f1c457757ae664ec16bf87/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[417,418,419,420,421,422,423,424],"take":"subject1/h1/7/cam4","frame_ids":[417,418,419,420,421,422,423,424]} +{"filtered_tile_id":"d1f1c457757ae664ec16bf87:32","filtered_window_id":"d1f1c457757ae664ec16bf87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d1f1c457757ae664ec16bf87/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject1/h1/7/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"d1f1c457757ae664ec16bf87:39","filtered_window_id":"d1f1c457757ae664ec16bf87","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d1f1c457757ae664ec16bf87/native_gt.npz","filtered_start_offset":39,"expected_frame_ids":[432,433,434,435,436,437,438,439],"take":"subject1/h1/7/cam4","frame_ids":[432,433,434,435,436,437,438,439]} +{"filtered_tile_id":"d2587cab8cbfeffdd16873f4:0","filtered_window_id":"d2587cab8cbfeffdd16873f4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2587cab8cbfeffdd16873f4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[112,113,114,115,116,117,118,119],"take":"subject2/k2/0/cam4","frame_ids":[112,113,114,115,116,117,118,119]} +{"filtered_tile_id":"d2587cab8cbfeffdd16873f4:8","filtered_window_id":"d2587cab8cbfeffdd16873f4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2587cab8cbfeffdd16873f4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[120,121,122,123,124,125,126,127],"take":"subject2/k2/0/cam4","frame_ids":[120,121,122,123,124,125,126,127]} +{"filtered_tile_id":"d2587cab8cbfeffdd16873f4:16","filtered_window_id":"d2587cab8cbfeffdd16873f4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2587cab8cbfeffdd16873f4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[128,129,130,131,132,133,134,135],"take":"subject2/k2/0/cam4","frame_ids":[128,129,130,131,132,133,134,135]} +{"filtered_tile_id":"d2587cab8cbfeffdd16873f4:24","filtered_window_id":"d2587cab8cbfeffdd16873f4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2587cab8cbfeffdd16873f4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[136,137,138,139,140,141,142,143],"take":"subject2/k2/0/cam4","frame_ids":[136,137,138,139,140,141,142,143]} +{"filtered_tile_id":"d2587cab8cbfeffdd16873f4:32","filtered_window_id":"d2587cab8cbfeffdd16873f4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2587cab8cbfeffdd16873f4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[144,145,146,147,148,149,150,151],"take":"subject2/k2/0/cam4","frame_ids":[144,145,146,147,148,149,150,151]} +{"filtered_tile_id":"d2587cab8cbfeffdd16873f4:40","filtered_window_id":"d2587cab8cbfeffdd16873f4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2587cab8cbfeffdd16873f4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject2/k2/0/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"d2587cab8cbfeffdd16873f4:48","filtered_window_id":"d2587cab8cbfeffdd16873f4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2587cab8cbfeffdd16873f4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject2/k2/0/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"d2587cab8cbfeffdd16873f4:52","filtered_window_id":"d2587cab8cbfeffdd16873f4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2587cab8cbfeffdd16873f4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[164,165,166,167,168,169,170,171],"take":"subject2/k2/0/cam4","frame_ids":[164,165,166,167,168,169,170,171]} +{"filtered_tile_id":"d2847a131003e8643ac5834c:0","filtered_window_id":"d2847a131003e8643ac5834c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2847a131003e8643ac5834c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[74,75,76,77,78,79,80,81],"take":"subject3/k1/7/cam4","frame_ids":[74,75,76,77,78,79,80,81]} +{"filtered_tile_id":"d2847a131003e8643ac5834c:8","filtered_window_id":"d2847a131003e8643ac5834c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2847a131003e8643ac5834c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[82,83,84,85,86,87,88,89],"take":"subject3/k1/7/cam4","frame_ids":[82,83,84,85,86,87,88,89]} +{"filtered_tile_id":"d2847a131003e8643ac5834c:16","filtered_window_id":"d2847a131003e8643ac5834c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2847a131003e8643ac5834c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[90,91,92,93,94,95,96,97],"take":"subject3/k1/7/cam4","frame_ids":[90,91,92,93,94,95,96,97]} +{"filtered_tile_id":"d2847a131003e8643ac5834c:24","filtered_window_id":"d2847a131003e8643ac5834c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2847a131003e8643ac5834c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[98,99,100,101,102,103,104,105],"take":"subject3/k1/7/cam4","frame_ids":[98,99,100,101,102,103,104,105]} +{"filtered_tile_id":"d2847a131003e8643ac5834c:32","filtered_window_id":"d2847a131003e8643ac5834c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2847a131003e8643ac5834c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[106,107,108,109,110,111,112,113],"take":"subject3/k1/7/cam4","frame_ids":[106,107,108,109,110,111,112,113]} +{"filtered_tile_id":"d2847a131003e8643ac5834c:40","filtered_window_id":"d2847a131003e8643ac5834c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2847a131003e8643ac5834c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject3/k1/7/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"d2847a131003e8643ac5834c:48","filtered_window_id":"d2847a131003e8643ac5834c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2847a131003e8643ac5834c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject3/k1/7/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"d2847a131003e8643ac5834c:52","filtered_window_id":"d2847a131003e8643ac5834c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2847a131003e8643ac5834c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[126,127,128,129,130,131,132,133],"take":"subject3/k1/7/cam4","frame_ids":[126,127,128,129,130,131,132,133]} +{"filtered_tile_id":"d2c846173288184dce780319:0","filtered_window_id":"d2c846173288184dce780319","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2c846173288184dce780319/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[240,241,242,243,244,245,246,247],"take":"subject2/h2/1/cam4","frame_ids":[240,241,242,243,244,245,246,247]} +{"filtered_tile_id":"d2c846173288184dce780319:8","filtered_window_id":"d2c846173288184dce780319","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2c846173288184dce780319/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[248,249,250,251,252,253,254,255],"take":"subject2/h2/1/cam4","frame_ids":[248,249,250,251,252,253,254,255]} +{"filtered_tile_id":"d2c846173288184dce780319:16","filtered_window_id":"d2c846173288184dce780319","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2c846173288184dce780319/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[256,257,258,259,260,261,262,263],"take":"subject2/h2/1/cam4","frame_ids":[256,257,258,259,260,261,262,263]} +{"filtered_tile_id":"d2c846173288184dce780319:24","filtered_window_id":"d2c846173288184dce780319","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2c846173288184dce780319/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[264,265,266,267,268,269,270,271],"take":"subject2/h2/1/cam4","frame_ids":[264,265,266,267,268,269,270,271]} +{"filtered_tile_id":"d2c846173288184dce780319:32","filtered_window_id":"d2c846173288184dce780319","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2c846173288184dce780319/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[272,273,274,275,276,277,278,279],"take":"subject2/h2/1/cam4","frame_ids":[272,273,274,275,276,277,278,279]} +{"filtered_tile_id":"d2c846173288184dce780319:40","filtered_window_id":"d2c846173288184dce780319","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2c846173288184dce780319/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject2/h2/1/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"d2c846173288184dce780319:48","filtered_window_id":"d2c846173288184dce780319","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2c846173288184dce780319/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject2/h2/1/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"d2c846173288184dce780319:52","filtered_window_id":"d2c846173288184dce780319","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d2c846173288184dce780319/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[292,293,294,295,296,297,298,299],"take":"subject2/h2/1/cam4","frame_ids":[292,293,294,295,296,297,298,299]} +{"filtered_tile_id":"d309be084775a3e4fc2761d7:0","filtered_window_id":"d309be084775a3e4fc2761d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d309be084775a3e4fc2761d7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/h1/5/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"d309be084775a3e4fc2761d7:8","filtered_window_id":"d309be084775a3e4fc2761d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d309be084775a3e4fc2761d7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/h1/5/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"d309be084775a3e4fc2761d7:16","filtered_window_id":"d309be084775a3e4fc2761d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d309be084775a3e4fc2761d7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/h1/5/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"d309be084775a3e4fc2761d7:24","filtered_window_id":"d309be084775a3e4fc2761d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d309be084775a3e4fc2761d7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/h1/5/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"d309be084775a3e4fc2761d7:32","filtered_window_id":"d309be084775a3e4fc2761d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d309be084775a3e4fc2761d7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/h1/5/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"d309be084775a3e4fc2761d7:39","filtered_window_id":"d309be084775a3e4fc2761d7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d309be084775a3e4fc2761d7/native_gt.npz","filtered_start_offset":39,"expected_frame_ids":[39,40,41,42,43,44,45,46],"take":"subject2/h1/5/cam4","frame_ids":[39,40,41,42,43,44,45,46]} +{"filtered_tile_id":"d387bfe207dfb77956dc7edf:0","filtered_window_id":"d387bfe207dfb77956dc7edf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d387bfe207dfb77956dc7edf/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[430,431,432,433,434,435,436,437],"take":"subject2/o2/5/cam4","frame_ids":[430,431,432,433,434,435,436,437]} +{"filtered_tile_id":"d387bfe207dfb77956dc7edf:8","filtered_window_id":"d387bfe207dfb77956dc7edf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d387bfe207dfb77956dc7edf/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[438,439,440,441,442,443,444,445],"take":"subject2/o2/5/cam4","frame_ids":[438,439,440,441,442,443,444,445]} +{"filtered_tile_id":"d387bfe207dfb77956dc7edf:16","filtered_window_id":"d387bfe207dfb77956dc7edf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d387bfe207dfb77956dc7edf/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[446,447,448,449,450,451,452,453],"take":"subject2/o2/5/cam4","frame_ids":[446,447,448,449,450,451,452,453]} +{"filtered_tile_id":"d387bfe207dfb77956dc7edf:24","filtered_window_id":"d387bfe207dfb77956dc7edf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d387bfe207dfb77956dc7edf/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[454,455,456,457,458,459,460,461],"take":"subject2/o2/5/cam4","frame_ids":[454,455,456,457,458,459,460,461]} +{"filtered_tile_id":"d387bfe207dfb77956dc7edf:32","filtered_window_id":"d387bfe207dfb77956dc7edf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d387bfe207dfb77956dc7edf/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[462,463,464,465,466,467,468,469],"take":"subject2/o2/5/cam4","frame_ids":[462,463,464,465,466,467,468,469]} +{"filtered_tile_id":"d387bfe207dfb77956dc7edf:40","filtered_window_id":"d387bfe207dfb77956dc7edf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d387bfe207dfb77956dc7edf/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject2/o2/5/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"d387bfe207dfb77956dc7edf:48","filtered_window_id":"d387bfe207dfb77956dc7edf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d387bfe207dfb77956dc7edf/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject2/o2/5/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"d387bfe207dfb77956dc7edf:52","filtered_window_id":"d387bfe207dfb77956dc7edf","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d387bfe207dfb77956dc7edf/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[482,483,484,485,486,487,488,489],"take":"subject2/o2/5/cam4","frame_ids":[482,483,484,485,486,487,488,489]} +{"filtered_tile_id":"d3d421e1486cd8007daaab49:0","filtered_window_id":"d3d421e1486cd8007daaab49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3d421e1486cd8007daaab49/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[23,24,25,26,27,28,29,30],"take":"subject2/o2/4/cam4","frame_ids":[23,24,25,26,27,28,29,30]} +{"filtered_tile_id":"d3d421e1486cd8007daaab49:8","filtered_window_id":"d3d421e1486cd8007daaab49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3d421e1486cd8007daaab49/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[31,32,33,34,35,36,37,38],"take":"subject2/o2/4/cam4","frame_ids":[31,32,33,34,35,36,37,38]} +{"filtered_tile_id":"d3d421e1486cd8007daaab49:16","filtered_window_id":"d3d421e1486cd8007daaab49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3d421e1486cd8007daaab49/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[39,40,41,42,43,44,45,46],"take":"subject2/o2/4/cam4","frame_ids":[39,40,41,42,43,44,45,46]} +{"filtered_tile_id":"d3d421e1486cd8007daaab49:24","filtered_window_id":"d3d421e1486cd8007daaab49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3d421e1486cd8007daaab49/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[47,48,49,50,51,52,53,54],"take":"subject2/o2/4/cam4","frame_ids":[47,48,49,50,51,52,53,54]} +{"filtered_tile_id":"d3d421e1486cd8007daaab49:32","filtered_window_id":"d3d421e1486cd8007daaab49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3d421e1486cd8007daaab49/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[55,56,57,58,59,60,61,62],"take":"subject2/o2/4/cam4","frame_ids":[55,56,57,58,59,60,61,62]} +{"filtered_tile_id":"d3d421e1486cd8007daaab49:40","filtered_window_id":"d3d421e1486cd8007daaab49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3d421e1486cd8007daaab49/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[63,64,65,66,67,68,69,70],"take":"subject2/o2/4/cam4","frame_ids":[63,64,65,66,67,68,69,70]} +{"filtered_tile_id":"d3d421e1486cd8007daaab49:48","filtered_window_id":"d3d421e1486cd8007daaab49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3d421e1486cd8007daaab49/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[71,72,73,74,75,76,77,78],"take":"subject2/o2/4/cam4","frame_ids":[71,72,73,74,75,76,77,78]} +{"filtered_tile_id":"d3d421e1486cd8007daaab49:52","filtered_window_id":"d3d421e1486cd8007daaab49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3d421e1486cd8007daaab49/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject2/o2/4/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"d3fe58abfd674d1bdd74c134:0","filtered_window_id":"d3fe58abfd674d1bdd74c134","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3fe58abfd674d1bdd74c134/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject2/h2/4/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"d3fe58abfd674d1bdd74c134:8","filtered_window_id":"d3fe58abfd674d1bdd74c134","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3fe58abfd674d1bdd74c134/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject2/h2/4/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"d3fe58abfd674d1bdd74c134:16","filtered_window_id":"d3fe58abfd674d1bdd74c134","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3fe58abfd674d1bdd74c134/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject2/h2/4/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"d3fe58abfd674d1bdd74c134:24","filtered_window_id":"d3fe58abfd674d1bdd74c134","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3fe58abfd674d1bdd74c134/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject2/h2/4/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"d3fe58abfd674d1bdd74c134:32","filtered_window_id":"d3fe58abfd674d1bdd74c134","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3fe58abfd674d1bdd74c134/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject2/h2/4/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"d3fe58abfd674d1bdd74c134:40","filtered_window_id":"d3fe58abfd674d1bdd74c134","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3fe58abfd674d1bdd74c134/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject2/h2/4/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"d3fe58abfd674d1bdd74c134:48","filtered_window_id":"d3fe58abfd674d1bdd74c134","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3fe58abfd674d1bdd74c134/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject2/h2/4/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"d3fe58abfd674d1bdd74c134:52","filtered_window_id":"d3fe58abfd674d1bdd74c134","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d3fe58abfd674d1bdd74c134/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject2/h2/4/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"d421b65e9a231d0873c5f22e:0","filtered_window_id":"d421b65e9a231d0873c5f22e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d421b65e9a231d0873c5f22e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject1/o1/7/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"d421b65e9a231d0873c5f22e:8","filtered_window_id":"d421b65e9a231d0873c5f22e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d421b65e9a231d0873c5f22e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject1/o1/7/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"d421b65e9a231d0873c5f22e:16","filtered_window_id":"d421b65e9a231d0873c5f22e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d421b65e9a231d0873c5f22e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject1/o1/7/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"d421b65e9a231d0873c5f22e:24","filtered_window_id":"d421b65e9a231d0873c5f22e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d421b65e9a231d0873c5f22e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject1/o1/7/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"d421b65e9a231d0873c5f22e:32","filtered_window_id":"d421b65e9a231d0873c5f22e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d421b65e9a231d0873c5f22e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject1/o1/7/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"d421b65e9a231d0873c5f22e:40","filtered_window_id":"d421b65e9a231d0873c5f22e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d421b65e9a231d0873c5f22e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject1/o1/7/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"d421b65e9a231d0873c5f22e:48","filtered_window_id":"d421b65e9a231d0873c5f22e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d421b65e9a231d0873c5f22e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject1/o1/7/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"d421b65e9a231d0873c5f22e:52","filtered_window_id":"d421b65e9a231d0873c5f22e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d421b65e9a231d0873c5f22e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[349,350,351,352,353,354,355,356],"take":"subject1/o1/7/cam4","frame_ids":[349,350,351,352,353,354,355,356]} +{"filtered_tile_id":"d44a0e856751103bfae05c42:0","filtered_window_id":"d44a0e856751103bfae05c42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d44a0e856751103bfae05c42/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject3/h1/0/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"d44a0e856751103bfae05c42:8","filtered_window_id":"d44a0e856751103bfae05c42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d44a0e856751103bfae05c42/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject3/h1/0/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"d44a0e856751103bfae05c42:16","filtered_window_id":"d44a0e856751103bfae05c42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d44a0e856751103bfae05c42/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject3/h1/0/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"d44a0e856751103bfae05c42:24","filtered_window_id":"d44a0e856751103bfae05c42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d44a0e856751103bfae05c42/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject3/h1/0/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"d44a0e856751103bfae05c42:32","filtered_window_id":"d44a0e856751103bfae05c42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d44a0e856751103bfae05c42/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject3/h1/0/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"d44a0e856751103bfae05c42:40","filtered_window_id":"d44a0e856751103bfae05c42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d44a0e856751103bfae05c42/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject3/h1/0/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"d44a0e856751103bfae05c42:48","filtered_window_id":"d44a0e856751103bfae05c42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d44a0e856751103bfae05c42/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[374,375,376,377,378,379,380,381],"take":"subject3/h1/0/cam4","frame_ids":[374,375,376,377,378,379,380,381]} +{"filtered_tile_id":"d44a0e856751103bfae05c42:52","filtered_window_id":"d44a0e856751103bfae05c42","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d44a0e856751103bfae05c42/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject3/h1/0/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"d469ed40e05665eb0fce1af6:0","filtered_window_id":"d469ed40e05665eb0fce1af6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d469ed40e05665eb0fce1af6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[330,331,332,333,334,335,336,337],"take":"subject1/o1/6/cam4","frame_ids":[330,331,332,333,334,335,336,337]} +{"filtered_tile_id":"d469ed40e05665eb0fce1af6:8","filtered_window_id":"d469ed40e05665eb0fce1af6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d469ed40e05665eb0fce1af6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject1/o1/6/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"d469ed40e05665eb0fce1af6:16","filtered_window_id":"d469ed40e05665eb0fce1af6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d469ed40e05665eb0fce1af6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[346,347,348,349,350,351,352,353],"take":"subject1/o1/6/cam4","frame_ids":[346,347,348,349,350,351,352,353]} +{"filtered_tile_id":"d469ed40e05665eb0fce1af6:24","filtered_window_id":"d469ed40e05665eb0fce1af6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d469ed40e05665eb0fce1af6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[354,355,356,357,358,359,360,361],"take":"subject1/o1/6/cam4","frame_ids":[354,355,356,357,358,359,360,361]} +{"filtered_tile_id":"d469ed40e05665eb0fce1af6:32","filtered_window_id":"d469ed40e05665eb0fce1af6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d469ed40e05665eb0fce1af6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject1/o1/6/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"d469ed40e05665eb0fce1af6:40","filtered_window_id":"d469ed40e05665eb0fce1af6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d469ed40e05665eb0fce1af6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[370,371,372,373,374,375,376,377],"take":"subject1/o1/6/cam4","frame_ids":[370,371,372,373,374,375,376,377]} +{"filtered_tile_id":"d469ed40e05665eb0fce1af6:48","filtered_window_id":"d469ed40e05665eb0fce1af6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d469ed40e05665eb0fce1af6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[378,379,380,381,382,383,384,385],"take":"subject1/o1/6/cam4","frame_ids":[378,379,380,381,382,383,384,385]} +{"filtered_tile_id":"d469ed40e05665eb0fce1af6:52","filtered_window_id":"d469ed40e05665eb0fce1af6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d469ed40e05665eb0fce1af6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[382,383,384,385,386,387,388,389],"take":"subject1/o1/6/cam4","frame_ids":[382,383,384,385,386,387,388,389]} +{"filtered_tile_id":"d47f9666e248ca08432c2f84:0","filtered_window_id":"d47f9666e248ca08432c2f84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d47f9666e248ca08432c2f84/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[718,719,720,721,722,723,724,725],"take":"subject1/o1/7/cam4","frame_ids":[718,719,720,721,722,723,724,725]} +{"filtered_tile_id":"d47f9666e248ca08432c2f84:8","filtered_window_id":"d47f9666e248ca08432c2f84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d47f9666e248ca08432c2f84/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[726,727,728,729,730,731,732,733],"take":"subject1/o1/7/cam4","frame_ids":[726,727,728,729,730,731,732,733]} +{"filtered_tile_id":"d47f9666e248ca08432c2f84:16","filtered_window_id":"d47f9666e248ca08432c2f84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d47f9666e248ca08432c2f84/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[734,735,736,737,738,739,740,741],"take":"subject1/o1/7/cam4","frame_ids":[734,735,736,737,738,739,740,741]} +{"filtered_tile_id":"d47f9666e248ca08432c2f84:17","filtered_window_id":"d47f9666e248ca08432c2f84","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d47f9666e248ca08432c2f84/native_gt.npz","filtered_start_offset":17,"expected_frame_ids":[735,736,737,738,739,740,741,742],"take":"subject1/o1/7/cam4","frame_ids":[735,736,737,738,739,740,741,742]} +{"filtered_tile_id":"d4c36c82c99bc8220017295a:0","filtered_window_id":"d4c36c82c99bc8220017295a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4c36c82c99bc8220017295a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[689,690,691,692,693,694,695,696],"take":"subject2/h1/3/cam4","frame_ids":[689,690,691,692,693,694,695,696]} +{"filtered_tile_id":"d4c36c82c99bc8220017295a:8","filtered_window_id":"d4c36c82c99bc8220017295a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4c36c82c99bc8220017295a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[697,698,699,700,701,702,703,704],"take":"subject2/h1/3/cam4","frame_ids":[697,698,699,700,701,702,703,704]} +{"filtered_tile_id":"d4c36c82c99bc8220017295a:16","filtered_window_id":"d4c36c82c99bc8220017295a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4c36c82c99bc8220017295a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[705,706,707,708,709,710,711,712],"take":"subject2/h1/3/cam4","frame_ids":[705,706,707,708,709,710,711,712]} +{"filtered_tile_id":"d4c36c82c99bc8220017295a:24","filtered_window_id":"d4c36c82c99bc8220017295a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4c36c82c99bc8220017295a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[713,714,715,716,717,718,719,720],"take":"subject2/h1/3/cam4","frame_ids":[713,714,715,716,717,718,719,720]} +{"filtered_tile_id":"d4c36c82c99bc8220017295a:32","filtered_window_id":"d4c36c82c99bc8220017295a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4c36c82c99bc8220017295a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[721,722,723,724,725,726,727,728],"take":"subject2/h1/3/cam4","frame_ids":[721,722,723,724,725,726,727,728]} +{"filtered_tile_id":"d4c36c82c99bc8220017295a:40","filtered_window_id":"d4c36c82c99bc8220017295a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4c36c82c99bc8220017295a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[729,730,731,732,733,734,735,736],"take":"subject2/h1/3/cam4","frame_ids":[729,730,731,732,733,734,735,736]} +{"filtered_tile_id":"d4c36c82c99bc8220017295a:48","filtered_window_id":"d4c36c82c99bc8220017295a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4c36c82c99bc8220017295a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[737,738,739,740,741,742,743,744],"take":"subject2/h1/3/cam4","frame_ids":[737,738,739,740,741,742,743,744]} +{"filtered_tile_id":"d4c36c82c99bc8220017295a:52","filtered_window_id":"d4c36c82c99bc8220017295a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4c36c82c99bc8220017295a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[741,742,743,744,745,746,747,748],"take":"subject2/h1/3/cam4","frame_ids":[741,742,743,744,745,746,747,748]} +{"filtered_tile_id":"d4fc1e9aefbe0b14d66be395:0","filtered_window_id":"d4fc1e9aefbe0b14d66be395","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4fc1e9aefbe0b14d66be395/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[175,176,177,178,179,180,181,182],"take":"subject1/h1/1/cam4","frame_ids":[175,176,177,178,179,180,181,182]} +{"filtered_tile_id":"d4fc1e9aefbe0b14d66be395:8","filtered_window_id":"d4fc1e9aefbe0b14d66be395","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4fc1e9aefbe0b14d66be395/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[183,184,185,186,187,188,189,190],"take":"subject1/h1/1/cam4","frame_ids":[183,184,185,186,187,188,189,190]} +{"filtered_tile_id":"d4fc1e9aefbe0b14d66be395:16","filtered_window_id":"d4fc1e9aefbe0b14d66be395","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4fc1e9aefbe0b14d66be395/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[191,192,193,194,195,196,197,198],"take":"subject1/h1/1/cam4","frame_ids":[191,192,193,194,195,196,197,198]} +{"filtered_tile_id":"d4fc1e9aefbe0b14d66be395:24","filtered_window_id":"d4fc1e9aefbe0b14d66be395","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4fc1e9aefbe0b14d66be395/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[199,200,201,202,203,204,205,206],"take":"subject1/h1/1/cam4","frame_ids":[199,200,201,202,203,204,205,206]} +{"filtered_tile_id":"d4fc1e9aefbe0b14d66be395:32","filtered_window_id":"d4fc1e9aefbe0b14d66be395","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4fc1e9aefbe0b14d66be395/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[207,208,209,210,211,212,213,214],"take":"subject1/h1/1/cam4","frame_ids":[207,208,209,210,211,212,213,214]} +{"filtered_tile_id":"d4fc1e9aefbe0b14d66be395:40","filtered_window_id":"d4fc1e9aefbe0b14d66be395","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4fc1e9aefbe0b14d66be395/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[215,216,217,218,219,220,221,222],"take":"subject1/h1/1/cam4","frame_ids":[215,216,217,218,219,220,221,222]} +{"filtered_tile_id":"d4fc1e9aefbe0b14d66be395:48","filtered_window_id":"d4fc1e9aefbe0b14d66be395","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4fc1e9aefbe0b14d66be395/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[223,224,225,226,227,228,229,230],"take":"subject1/h1/1/cam4","frame_ids":[223,224,225,226,227,228,229,230]} +{"filtered_tile_id":"d4fc1e9aefbe0b14d66be395:52","filtered_window_id":"d4fc1e9aefbe0b14d66be395","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d4fc1e9aefbe0b14d66be395/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[227,228,229,230,231,232,233,234],"take":"subject1/h1/1/cam4","frame_ids":[227,228,229,230,231,232,233,234]} +{"filtered_tile_id":"d577d5cb7489fa86bd5d5218:0","filtered_window_id":"d577d5cb7489fa86bd5d5218","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d577d5cb7489fa86bd5d5218/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject2/o1/3/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"d577d5cb7489fa86bd5d5218:8","filtered_window_id":"d577d5cb7489fa86bd5d5218","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d577d5cb7489fa86bd5d5218/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject2/o1/3/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"d577d5cb7489fa86bd5d5218:16","filtered_window_id":"d577d5cb7489fa86bd5d5218","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d577d5cb7489fa86bd5d5218/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject2/o1/3/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"d577d5cb7489fa86bd5d5218:24","filtered_window_id":"d577d5cb7489fa86bd5d5218","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d577d5cb7489fa86bd5d5218/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject2/o1/3/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"d577d5cb7489fa86bd5d5218:32","filtered_window_id":"d577d5cb7489fa86bd5d5218","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d577d5cb7489fa86bd5d5218/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject2/o1/3/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"d577d5cb7489fa86bd5d5218:40","filtered_window_id":"d577d5cb7489fa86bd5d5218","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d577d5cb7489fa86bd5d5218/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject2/o1/3/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"d577d5cb7489fa86bd5d5218:48","filtered_window_id":"d577d5cb7489fa86bd5d5218","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d577d5cb7489fa86bd5d5218/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[159,160,161,162,163,164,165,166],"take":"subject2/o1/3/cam4","frame_ids":[159,160,161,162,163,164,165,166]} +{"filtered_tile_id":"d577d5cb7489fa86bd5d5218:52","filtered_window_id":"d577d5cb7489fa86bd5d5218","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d577d5cb7489fa86bd5d5218/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject2/o1/3/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"d5b40a2effe0a2b622536c96:0","filtered_window_id":"d5b40a2effe0a2b622536c96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d5b40a2effe0a2b622536c96/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[840,841,842,843,844,845,846,847],"take":"subject2/o1/2/cam4","frame_ids":[840,841,842,843,844,845,846,847]} +{"filtered_tile_id":"d5b40a2effe0a2b622536c96:8","filtered_window_id":"d5b40a2effe0a2b622536c96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d5b40a2effe0a2b622536c96/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[848,849,850,851,852,853,854,855],"take":"subject2/o1/2/cam4","frame_ids":[848,849,850,851,852,853,854,855]} +{"filtered_tile_id":"d5b40a2effe0a2b622536c96:16","filtered_window_id":"d5b40a2effe0a2b622536c96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d5b40a2effe0a2b622536c96/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[856,857,858,859,860,861,862,863],"take":"subject2/o1/2/cam4","frame_ids":[856,857,858,859,860,861,862,863]} +{"filtered_tile_id":"d5b40a2effe0a2b622536c96:24","filtered_window_id":"d5b40a2effe0a2b622536c96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d5b40a2effe0a2b622536c96/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[864,865,866,867,868,869,870,871],"take":"subject2/o1/2/cam4","frame_ids":[864,865,866,867,868,869,870,871]} +{"filtered_tile_id":"d5b40a2effe0a2b622536c96:32","filtered_window_id":"d5b40a2effe0a2b622536c96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d5b40a2effe0a2b622536c96/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[872,873,874,875,876,877,878,879],"take":"subject2/o1/2/cam4","frame_ids":[872,873,874,875,876,877,878,879]} +{"filtered_tile_id":"d5b40a2effe0a2b622536c96:40","filtered_window_id":"d5b40a2effe0a2b622536c96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d5b40a2effe0a2b622536c96/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[880,881,882,883,884,885,886,887],"take":"subject2/o1/2/cam4","frame_ids":[880,881,882,883,884,885,886,887]} +{"filtered_tile_id":"d5b40a2effe0a2b622536c96:48","filtered_window_id":"d5b40a2effe0a2b622536c96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d5b40a2effe0a2b622536c96/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[888,889,890,891,892,893,894,895],"take":"subject2/o1/2/cam4","frame_ids":[888,889,890,891,892,893,894,895]} +{"filtered_tile_id":"d5b40a2effe0a2b622536c96:52","filtered_window_id":"d5b40a2effe0a2b622536c96","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d5b40a2effe0a2b622536c96/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[892,893,894,895,896,897,898,899],"take":"subject2/o1/2/cam4","frame_ids":[892,893,894,895,896,897,898,899]} +{"filtered_tile_id":"d66091deb0aaf0d37ffdd063:0","filtered_window_id":"d66091deb0aaf0d37ffdd063","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d66091deb0aaf0d37ffdd063/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject2/o1/4/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"d66091deb0aaf0d37ffdd063:8","filtered_window_id":"d66091deb0aaf0d37ffdd063","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d66091deb0aaf0d37ffdd063/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject2/o1/4/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"d66091deb0aaf0d37ffdd063:16","filtered_window_id":"d66091deb0aaf0d37ffdd063","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d66091deb0aaf0d37ffdd063/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject2/o1/4/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"d66091deb0aaf0d37ffdd063:24","filtered_window_id":"d66091deb0aaf0d37ffdd063","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d66091deb0aaf0d37ffdd063/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject2/o1/4/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"d66091deb0aaf0d37ffdd063:32","filtered_window_id":"d66091deb0aaf0d37ffdd063","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d66091deb0aaf0d37ffdd063/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject2/o1/4/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"d66091deb0aaf0d37ffdd063:40","filtered_window_id":"d66091deb0aaf0d37ffdd063","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d66091deb0aaf0d37ffdd063/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject2/o1/4/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"d66091deb0aaf0d37ffdd063:48","filtered_window_id":"d66091deb0aaf0d37ffdd063","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d66091deb0aaf0d37ffdd063/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject2/o1/4/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"d66091deb0aaf0d37ffdd063:52","filtered_window_id":"d66091deb0aaf0d37ffdd063","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d66091deb0aaf0d37ffdd063/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject2/o1/4/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"d69ff7eaf24f9edd840b631c:0","filtered_window_id":"d69ff7eaf24f9edd840b631c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d69ff7eaf24f9edd840b631c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[11,12,13,14,15,16,17,18],"take":"subject1/h1/2/cam4","frame_ids":[11,12,13,14,15,16,17,18]} +{"filtered_tile_id":"d69ff7eaf24f9edd840b631c:8","filtered_window_id":"d69ff7eaf24f9edd840b631c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d69ff7eaf24f9edd840b631c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[19,20,21,22,23,24,25,26],"take":"subject1/h1/2/cam4","frame_ids":[19,20,21,22,23,24,25,26]} +{"filtered_tile_id":"d69ff7eaf24f9edd840b631c:16","filtered_window_id":"d69ff7eaf24f9edd840b631c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d69ff7eaf24f9edd840b631c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[27,28,29,30,31,32,33,34],"take":"subject1/h1/2/cam4","frame_ids":[27,28,29,30,31,32,33,34]} +{"filtered_tile_id":"d69ff7eaf24f9edd840b631c:24","filtered_window_id":"d69ff7eaf24f9edd840b631c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d69ff7eaf24f9edd840b631c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[35,36,37,38,39,40,41,42],"take":"subject1/h1/2/cam4","frame_ids":[35,36,37,38,39,40,41,42]} +{"filtered_tile_id":"d69ff7eaf24f9edd840b631c:32","filtered_window_id":"d69ff7eaf24f9edd840b631c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d69ff7eaf24f9edd840b631c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[43,44,45,46,47,48,49,50],"take":"subject1/h1/2/cam4","frame_ids":[43,44,45,46,47,48,49,50]} +{"filtered_tile_id":"d69ff7eaf24f9edd840b631c:40","filtered_window_id":"d69ff7eaf24f9edd840b631c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d69ff7eaf24f9edd840b631c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject1/h1/2/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"d69ff7eaf24f9edd840b631c:48","filtered_window_id":"d69ff7eaf24f9edd840b631c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d69ff7eaf24f9edd840b631c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[59,60,61,62,63,64,65,66],"take":"subject1/h1/2/cam4","frame_ids":[59,60,61,62,63,64,65,66]} +{"filtered_tile_id":"d69ff7eaf24f9edd840b631c:52","filtered_window_id":"d69ff7eaf24f9edd840b631c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d69ff7eaf24f9edd840b631c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[63,64,65,66,67,68,69,70],"take":"subject1/h1/2/cam4","frame_ids":[63,64,65,66,67,68,69,70]} +{"filtered_tile_id":"d6c6a136ac1126e081143b9c:0","filtered_window_id":"d6c6a136ac1126e081143b9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6c6a136ac1126e081143b9c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[551,552,553,554,555,556,557,558],"take":"subject1/h1/3/cam4","frame_ids":[551,552,553,554,555,556,557,558]} +{"filtered_tile_id":"d6c6a136ac1126e081143b9c:8","filtered_window_id":"d6c6a136ac1126e081143b9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6c6a136ac1126e081143b9c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[559,560,561,562,563,564,565,566],"take":"subject1/h1/3/cam4","frame_ids":[559,560,561,562,563,564,565,566]} +{"filtered_tile_id":"d6c6a136ac1126e081143b9c:16","filtered_window_id":"d6c6a136ac1126e081143b9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6c6a136ac1126e081143b9c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[567,568,569,570,571,572,573,574],"take":"subject1/h1/3/cam4","frame_ids":[567,568,569,570,571,572,573,574]} +{"filtered_tile_id":"d6c6a136ac1126e081143b9c:24","filtered_window_id":"d6c6a136ac1126e081143b9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6c6a136ac1126e081143b9c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[575,576,577,578,579,580,581,582],"take":"subject1/h1/3/cam4","frame_ids":[575,576,577,578,579,580,581,582]} +{"filtered_tile_id":"d6c6a136ac1126e081143b9c:32","filtered_window_id":"d6c6a136ac1126e081143b9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6c6a136ac1126e081143b9c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[583,584,585,586,587,588,589,590],"take":"subject1/h1/3/cam4","frame_ids":[583,584,585,586,587,588,589,590]} +{"filtered_tile_id":"d6c6a136ac1126e081143b9c:40","filtered_window_id":"d6c6a136ac1126e081143b9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6c6a136ac1126e081143b9c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[591,592,593,594,595,596,597,598],"take":"subject1/h1/3/cam4","frame_ids":[591,592,593,594,595,596,597,598]} +{"filtered_tile_id":"d6c6a136ac1126e081143b9c:48","filtered_window_id":"d6c6a136ac1126e081143b9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6c6a136ac1126e081143b9c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[599,600,601,602,603,604,605,606],"take":"subject1/h1/3/cam4","frame_ids":[599,600,601,602,603,604,605,606]} +{"filtered_tile_id":"d6c6a136ac1126e081143b9c:52","filtered_window_id":"d6c6a136ac1126e081143b9c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6c6a136ac1126e081143b9c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[603,604,605,606,607,608,609,610],"take":"subject1/h1/3/cam4","frame_ids":[603,604,605,606,607,608,609,610]} +{"filtered_tile_id":"d6cf727c9329b3333dccfe38:0","filtered_window_id":"d6cf727c9329b3333dccfe38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6cf727c9329b3333dccfe38/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[120,121,122,123,124,125,126,127],"take":"subject1/k1/1/cam4","frame_ids":[120,121,122,123,124,125,126,127]} +{"filtered_tile_id":"d6cf727c9329b3333dccfe38:8","filtered_window_id":"d6cf727c9329b3333dccfe38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6cf727c9329b3333dccfe38/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[128,129,130,131,132,133,134,135],"take":"subject1/k1/1/cam4","frame_ids":[128,129,130,131,132,133,134,135]} +{"filtered_tile_id":"d6cf727c9329b3333dccfe38:16","filtered_window_id":"d6cf727c9329b3333dccfe38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6cf727c9329b3333dccfe38/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[136,137,138,139,140,141,142,143],"take":"subject1/k1/1/cam4","frame_ids":[136,137,138,139,140,141,142,143]} +{"filtered_tile_id":"d6cf727c9329b3333dccfe38:24","filtered_window_id":"d6cf727c9329b3333dccfe38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6cf727c9329b3333dccfe38/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[144,145,146,147,148,149,150,151],"take":"subject1/k1/1/cam4","frame_ids":[144,145,146,147,148,149,150,151]} +{"filtered_tile_id":"d6cf727c9329b3333dccfe38:32","filtered_window_id":"d6cf727c9329b3333dccfe38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6cf727c9329b3333dccfe38/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject1/k1/1/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"d6cf727c9329b3333dccfe38:40","filtered_window_id":"d6cf727c9329b3333dccfe38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6cf727c9329b3333dccfe38/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject1/k1/1/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"d6cf727c9329b3333dccfe38:48","filtered_window_id":"d6cf727c9329b3333dccfe38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6cf727c9329b3333dccfe38/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject1/k1/1/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"d6cf727c9329b3333dccfe38:52","filtered_window_id":"d6cf727c9329b3333dccfe38","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d6cf727c9329b3333dccfe38/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject1/k1/1/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"d73866ea52145cc5c83772b9:0","filtered_window_id":"d73866ea52145cc5c83772b9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d73866ea52145cc5c83772b9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject2/o2/2/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"d73866ea52145cc5c83772b9:8","filtered_window_id":"d73866ea52145cc5c83772b9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d73866ea52145cc5c83772b9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject2/o2/2/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"d73866ea52145cc5c83772b9:16","filtered_window_id":"d73866ea52145cc5c83772b9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d73866ea52145cc5c83772b9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[361,362,363,364,365,366,367,368],"take":"subject2/o2/2/cam4","frame_ids":[361,362,363,364,365,366,367,368]} +{"filtered_tile_id":"d73866ea52145cc5c83772b9:24","filtered_window_id":"d73866ea52145cc5c83772b9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d73866ea52145cc5c83772b9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[369,370,371,372,373,374,375,376],"take":"subject2/o2/2/cam4","frame_ids":[369,370,371,372,373,374,375,376]} +{"filtered_tile_id":"d73866ea52145cc5c83772b9:27","filtered_window_id":"d73866ea52145cc5c83772b9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d73866ea52145cc5c83772b9/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject2/o2/2/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"d7e4857b1cae7b6e3243cd9f:0","filtered_window_id":"d7e4857b1cae7b6e3243cd9f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d7e4857b1cae7b6e3243cd9f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[530,531,532,533,534,535,536,537],"take":"subject1/k1/4/cam4","frame_ids":[530,531,532,533,534,535,536,537]} +{"filtered_tile_id":"d7e4857b1cae7b6e3243cd9f:8","filtered_window_id":"d7e4857b1cae7b6e3243cd9f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d7e4857b1cae7b6e3243cd9f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[538,539,540,541,542,543,544,545],"take":"subject1/k1/4/cam4","frame_ids":[538,539,540,541,542,543,544,545]} +{"filtered_tile_id":"d801efc053f21037037f944c:0","filtered_window_id":"d801efc053f21037037f944c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d801efc053f21037037f944c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject2/k2/1/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"d801efc053f21037037f944c:8","filtered_window_id":"d801efc053f21037037f944c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d801efc053f21037037f944c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[380,381,382,383,384,385,386,387],"take":"subject2/k2/1/cam4","frame_ids":[380,381,382,383,384,385,386,387]} +{"filtered_tile_id":"d801efc053f21037037f944c:16","filtered_window_id":"d801efc053f21037037f944c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d801efc053f21037037f944c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[388,389,390,391,392,393,394,395],"take":"subject2/k2/1/cam4","frame_ids":[388,389,390,391,392,393,394,395]} +{"filtered_tile_id":"d801efc053f21037037f944c:24","filtered_window_id":"d801efc053f21037037f944c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d801efc053f21037037f944c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject2/k2/1/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"d801efc053f21037037f944c:32","filtered_window_id":"d801efc053f21037037f944c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d801efc053f21037037f944c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject2/k2/1/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"d801efc053f21037037f944c:40","filtered_window_id":"d801efc053f21037037f944c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d801efc053f21037037f944c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject2/k2/1/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"d801efc053f21037037f944c:48","filtered_window_id":"d801efc053f21037037f944c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d801efc053f21037037f944c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject2/k2/1/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"d801efc053f21037037f944c:52","filtered_window_id":"d801efc053f21037037f944c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d801efc053f21037037f944c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[424,425,426,427,428,429,430,431],"take":"subject2/k2/1/cam4","frame_ids":[424,425,426,427,428,429,430,431]} +{"filtered_tile_id":"d8168dca4cd8576742dc9975:0","filtered_window_id":"d8168dca4cd8576742dc9975","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8168dca4cd8576742dc9975/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject1/h2/5/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"d8168dca4cd8576742dc9975:8","filtered_window_id":"d8168dca4cd8576742dc9975","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8168dca4cd8576742dc9975/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject1/h2/5/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"d8168dca4cd8576742dc9975:16","filtered_window_id":"d8168dca4cd8576742dc9975","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8168dca4cd8576742dc9975/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[170,171,172,173,174,175,176,177],"take":"subject1/h2/5/cam4","frame_ids":[170,171,172,173,174,175,176,177]} +{"filtered_tile_id":"d8168dca4cd8576742dc9975:24","filtered_window_id":"d8168dca4cd8576742dc9975","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8168dca4cd8576742dc9975/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[178,179,180,181,182,183,184,185],"take":"subject1/h2/5/cam4","frame_ids":[178,179,180,181,182,183,184,185]} +{"filtered_tile_id":"d8168dca4cd8576742dc9975:29","filtered_window_id":"d8168dca4cd8576742dc9975","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8168dca4cd8576742dc9975/native_gt.npz","filtered_start_offset":29,"expected_frame_ids":[183,184,185,186,187,188,189,190],"take":"subject1/h2/5/cam4","frame_ids":[183,184,185,186,187,188,189,190]} +{"filtered_tile_id":"d8268fca7bb675318198fd73:0","filtered_window_id":"d8268fca7bb675318198fd73","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8268fca7bb675318198fd73/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject1/k2/5/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"d8268fca7bb675318198fd73:8","filtered_window_id":"d8268fca7bb675318198fd73","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8268fca7bb675318198fd73/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject1/k2/5/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"d8268fca7bb675318198fd73:9","filtered_window_id":"d8268fca7bb675318198fd73","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8268fca7bb675318198fd73/native_gt.npz","filtered_start_offset":9,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject1/k2/5/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"d8ff742d5e18a062186f3d72:0","filtered_window_id":"d8ff742d5e18a062186f3d72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8ff742d5e18a062186f3d72/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject3/h2/2/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"d8ff742d5e18a062186f3d72:8","filtered_window_id":"d8ff742d5e18a062186f3d72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8ff742d5e18a062186f3d72/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject3/h2/2/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"d8ff742d5e18a062186f3d72:16","filtered_window_id":"d8ff742d5e18a062186f3d72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8ff742d5e18a062186f3d72/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject3/h2/2/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"d8ff742d5e18a062186f3d72:24","filtered_window_id":"d8ff742d5e18a062186f3d72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8ff742d5e18a062186f3d72/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject3/h2/2/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"d8ff742d5e18a062186f3d72:32","filtered_window_id":"d8ff742d5e18a062186f3d72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8ff742d5e18a062186f3d72/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject3/h2/2/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"d8ff742d5e18a062186f3d72:40","filtered_window_id":"d8ff742d5e18a062186f3d72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8ff742d5e18a062186f3d72/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[423,424,425,426,427,428,429,430],"take":"subject3/h2/2/cam4","frame_ids":[423,424,425,426,427,428,429,430]} +{"filtered_tile_id":"d8ff742d5e18a062186f3d72:48","filtered_window_id":"d8ff742d5e18a062186f3d72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8ff742d5e18a062186f3d72/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[431,432,433,434,435,436,437,438],"take":"subject3/h2/2/cam4","frame_ids":[431,432,433,434,435,436,437,438]} +{"filtered_tile_id":"d8ff742d5e18a062186f3d72:52","filtered_window_id":"d8ff742d5e18a062186f3d72","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/d8ff742d5e18a062186f3d72/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject3/h2/2/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"da2e48f5325f91ee049157bc:0","filtered_window_id":"da2e48f5325f91ee049157bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da2e48f5325f91ee049157bc/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject2/k2/6/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"da2e48f5325f91ee049157bc:8","filtered_window_id":"da2e48f5325f91ee049157bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da2e48f5325f91ee049157bc/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject2/k2/6/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"da2e48f5325f91ee049157bc:16","filtered_window_id":"da2e48f5325f91ee049157bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da2e48f5325f91ee049157bc/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject2/k2/6/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"da2e48f5325f91ee049157bc:24","filtered_window_id":"da2e48f5325f91ee049157bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da2e48f5325f91ee049157bc/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject2/k2/6/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"da2e48f5325f91ee049157bc:32","filtered_window_id":"da2e48f5325f91ee049157bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da2e48f5325f91ee049157bc/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject2/k2/6/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"da2e48f5325f91ee049157bc:40","filtered_window_id":"da2e48f5325f91ee049157bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da2e48f5325f91ee049157bc/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject2/k2/6/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"da2e48f5325f91ee049157bc:48","filtered_window_id":"da2e48f5325f91ee049157bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da2e48f5325f91ee049157bc/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject2/k2/6/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"da2e48f5325f91ee049157bc:52","filtered_window_id":"da2e48f5325f91ee049157bc","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da2e48f5325f91ee049157bc/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[167,168,169,170,171,172,173,174],"take":"subject2/k2/6/cam4","frame_ids":[167,168,169,170,171,172,173,174]} +{"filtered_tile_id":"da8635f07346102d6e359c49:0","filtered_window_id":"da8635f07346102d6e359c49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da8635f07346102d6e359c49/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject1/k2/0/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"da8635f07346102d6e359c49:8","filtered_window_id":"da8635f07346102d6e359c49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da8635f07346102d6e359c49/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/k2/0/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"da8635f07346102d6e359c49:16","filtered_window_id":"da8635f07346102d6e359c49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da8635f07346102d6e359c49/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[116,117,118,119,120,121,122,123],"take":"subject1/k2/0/cam4","frame_ids":[116,117,118,119,120,121,122,123]} +{"filtered_tile_id":"da8635f07346102d6e359c49:24","filtered_window_id":"da8635f07346102d6e359c49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da8635f07346102d6e359c49/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[124,125,126,127,128,129,130,131],"take":"subject1/k2/0/cam4","frame_ids":[124,125,126,127,128,129,130,131]} +{"filtered_tile_id":"da8635f07346102d6e359c49:32","filtered_window_id":"da8635f07346102d6e359c49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da8635f07346102d6e359c49/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[132,133,134,135,136,137,138,139],"take":"subject1/k2/0/cam4","frame_ids":[132,133,134,135,136,137,138,139]} +{"filtered_tile_id":"da8635f07346102d6e359c49:40","filtered_window_id":"da8635f07346102d6e359c49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da8635f07346102d6e359c49/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject1/k2/0/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"da8635f07346102d6e359c49:48","filtered_window_id":"da8635f07346102d6e359c49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da8635f07346102d6e359c49/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject1/k2/0/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"da8635f07346102d6e359c49:52","filtered_window_id":"da8635f07346102d6e359c49","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/da8635f07346102d6e359c49/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[152,153,154,155,156,157,158,159],"take":"subject1/k2/0/cam4","frame_ids":[152,153,154,155,156,157,158,159]} +{"filtered_tile_id":"dae9da51f8de4a5d07ba67de:0","filtered_window_id":"dae9da51f8de4a5d07ba67de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dae9da51f8de4a5d07ba67de/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[860,861,862,863,864,865,866,867],"take":"subject2/h1/3/cam4","frame_ids":[860,861,862,863,864,865,866,867]} +{"filtered_tile_id":"dae9da51f8de4a5d07ba67de:8","filtered_window_id":"dae9da51f8de4a5d07ba67de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dae9da51f8de4a5d07ba67de/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[868,869,870,871,872,873,874,875],"take":"subject2/h1/3/cam4","frame_ids":[868,869,870,871,872,873,874,875]} +{"filtered_tile_id":"dae9da51f8de4a5d07ba67de:16","filtered_window_id":"dae9da51f8de4a5d07ba67de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dae9da51f8de4a5d07ba67de/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[876,877,878,879,880,881,882,883],"take":"subject2/h1/3/cam4","frame_ids":[876,877,878,879,880,881,882,883]} +{"filtered_tile_id":"dae9da51f8de4a5d07ba67de:24","filtered_window_id":"dae9da51f8de4a5d07ba67de","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dae9da51f8de4a5d07ba67de/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[884,885,886,887,888,889,890,891],"take":"subject2/h1/3/cam4","frame_ids":[884,885,886,887,888,889,890,891]} +{"filtered_tile_id":"db0fb1c8064984ae815fa0bd:0","filtered_window_id":"db0fb1c8064984ae815fa0bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db0fb1c8064984ae815fa0bd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject1/k1/2/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"db0fb1c8064984ae815fa0bd:8","filtered_window_id":"db0fb1c8064984ae815fa0bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db0fb1c8064984ae815fa0bd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject1/k1/2/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"db0fb1c8064984ae815fa0bd:16","filtered_window_id":"db0fb1c8064984ae815fa0bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db0fb1c8064984ae815fa0bd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject1/k1/2/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"db0fb1c8064984ae815fa0bd:24","filtered_window_id":"db0fb1c8064984ae815fa0bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db0fb1c8064984ae815fa0bd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject1/k1/2/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"db0fb1c8064984ae815fa0bd:32","filtered_window_id":"db0fb1c8064984ae815fa0bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db0fb1c8064984ae815fa0bd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[246,247,248,249,250,251,252,253],"take":"subject1/k1/2/cam4","frame_ids":[246,247,248,249,250,251,252,253]} +{"filtered_tile_id":"db0fb1c8064984ae815fa0bd:40","filtered_window_id":"db0fb1c8064984ae815fa0bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db0fb1c8064984ae815fa0bd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject1/k1/2/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"db0fb1c8064984ae815fa0bd:48","filtered_window_id":"db0fb1c8064984ae815fa0bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db0fb1c8064984ae815fa0bd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[262,263,264,265,266,267,268,269],"take":"subject1/k1/2/cam4","frame_ids":[262,263,264,265,266,267,268,269]} +{"filtered_tile_id":"db0fb1c8064984ae815fa0bd:52","filtered_window_id":"db0fb1c8064984ae815fa0bd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db0fb1c8064984ae815fa0bd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject1/k1/2/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"db808807a6ff6066d3cc344b:0","filtered_window_id":"db808807a6ff6066d3cc344b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db808807a6ff6066d3cc344b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[791,792,793,794,795,796,797,798],"take":"subject2/h2/4/cam4","frame_ids":[791,792,793,794,795,796,797,798]} +{"filtered_tile_id":"db808807a6ff6066d3cc344b:8","filtered_window_id":"db808807a6ff6066d3cc344b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db808807a6ff6066d3cc344b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[799,800,801,802,803,804,805,806],"take":"subject2/h2/4/cam4","frame_ids":[799,800,801,802,803,804,805,806]} +{"filtered_tile_id":"db808807a6ff6066d3cc344b:16","filtered_window_id":"db808807a6ff6066d3cc344b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db808807a6ff6066d3cc344b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[807,808,809,810,811,812,813,814],"take":"subject2/h2/4/cam4","frame_ids":[807,808,809,810,811,812,813,814]} +{"filtered_tile_id":"db808807a6ff6066d3cc344b:24","filtered_window_id":"db808807a6ff6066d3cc344b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db808807a6ff6066d3cc344b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[815,816,817,818,819,820,821,822],"take":"subject2/h2/4/cam4","frame_ids":[815,816,817,818,819,820,821,822]} +{"filtered_tile_id":"db808807a6ff6066d3cc344b:32","filtered_window_id":"db808807a6ff6066d3cc344b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db808807a6ff6066d3cc344b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[823,824,825,826,827,828,829,830],"take":"subject2/h2/4/cam4","frame_ids":[823,824,825,826,827,828,829,830]} +{"filtered_tile_id":"db808807a6ff6066d3cc344b:40","filtered_window_id":"db808807a6ff6066d3cc344b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db808807a6ff6066d3cc344b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[831,832,833,834,835,836,837,838],"take":"subject2/h2/4/cam4","frame_ids":[831,832,833,834,835,836,837,838]} +{"filtered_tile_id":"db808807a6ff6066d3cc344b:48","filtered_window_id":"db808807a6ff6066d3cc344b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db808807a6ff6066d3cc344b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[839,840,841,842,843,844,845,846],"take":"subject2/h2/4/cam4","frame_ids":[839,840,841,842,843,844,845,846]} +{"filtered_tile_id":"db808807a6ff6066d3cc344b:52","filtered_window_id":"db808807a6ff6066d3cc344b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/db808807a6ff6066d3cc344b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[843,844,845,846,847,848,849,850],"take":"subject2/h2/4/cam4","frame_ids":[843,844,845,846,847,848,849,850]} +{"filtered_tile_id":"dc4f2facb689614fc34f26e9:0","filtered_window_id":"dc4f2facb689614fc34f26e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc4f2facb689614fc34f26e9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject1/h2/6/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"dc4f2facb689614fc34f26e9:8","filtered_window_id":"dc4f2facb689614fc34f26e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc4f2facb689614fc34f26e9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject1/h2/6/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"dc4f2facb689614fc34f26e9:16","filtered_window_id":"dc4f2facb689614fc34f26e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc4f2facb689614fc34f26e9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject1/h2/6/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"dc4f2facb689614fc34f26e9:24","filtered_window_id":"dc4f2facb689614fc34f26e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc4f2facb689614fc34f26e9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[333,334,335,336,337,338,339,340],"take":"subject1/h2/6/cam4","frame_ids":[333,334,335,336,337,338,339,340]} +{"filtered_tile_id":"dc4f2facb689614fc34f26e9:30","filtered_window_id":"dc4f2facb689614fc34f26e9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc4f2facb689614fc34f26e9/native_gt.npz","filtered_start_offset":30,"expected_frame_ids":[339,340,341,342,343,344,345,346],"take":"subject1/h2/6/cam4","frame_ids":[339,340,341,342,343,344,345,346]} +{"filtered_tile_id":"dc9b8d24db5f307c8fd158a0:0","filtered_window_id":"dc9b8d24db5f307c8fd158a0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc9b8d24db5f307c8fd158a0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[363,364,365,366,367,368,369,370],"take":"subject2/h2/0/cam4","frame_ids":[363,364,365,366,367,368,369,370]} +{"filtered_tile_id":"dc9b8d24db5f307c8fd158a0:8","filtered_window_id":"dc9b8d24db5f307c8fd158a0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc9b8d24db5f307c8fd158a0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[371,372,373,374,375,376,377,378],"take":"subject2/h2/0/cam4","frame_ids":[371,372,373,374,375,376,377,378]} +{"filtered_tile_id":"dc9b8d24db5f307c8fd158a0:16","filtered_window_id":"dc9b8d24db5f307c8fd158a0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc9b8d24db5f307c8fd158a0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[379,380,381,382,383,384,385,386],"take":"subject2/h2/0/cam4","frame_ids":[379,380,381,382,383,384,385,386]} +{"filtered_tile_id":"dc9b8d24db5f307c8fd158a0:24","filtered_window_id":"dc9b8d24db5f307c8fd158a0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc9b8d24db5f307c8fd158a0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[387,388,389,390,391,392,393,394],"take":"subject2/h2/0/cam4","frame_ids":[387,388,389,390,391,392,393,394]} +{"filtered_tile_id":"dc9b8d24db5f307c8fd158a0:32","filtered_window_id":"dc9b8d24db5f307c8fd158a0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc9b8d24db5f307c8fd158a0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[395,396,397,398,399,400,401,402],"take":"subject2/h2/0/cam4","frame_ids":[395,396,397,398,399,400,401,402]} +{"filtered_tile_id":"dc9b8d24db5f307c8fd158a0:40","filtered_window_id":"dc9b8d24db5f307c8fd158a0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc9b8d24db5f307c8fd158a0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[403,404,405,406,407,408,409,410],"take":"subject2/h2/0/cam4","frame_ids":[403,404,405,406,407,408,409,410]} +{"filtered_tile_id":"dc9b8d24db5f307c8fd158a0:48","filtered_window_id":"dc9b8d24db5f307c8fd158a0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc9b8d24db5f307c8fd158a0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[411,412,413,414,415,416,417,418],"take":"subject2/h2/0/cam4","frame_ids":[411,412,413,414,415,416,417,418]} +{"filtered_tile_id":"dc9b8d24db5f307c8fd158a0:52","filtered_window_id":"dc9b8d24db5f307c8fd158a0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dc9b8d24db5f307c8fd158a0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject2/h2/0/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"dce7edd31c83022cedde3aec:0","filtered_window_id":"dce7edd31c83022cedde3aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dce7edd31c83022cedde3aec/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[559,560,561,562,563,564,565,566],"take":"subject3/k1/3/cam4","frame_ids":[559,560,561,562,563,564,565,566]} +{"filtered_tile_id":"dce7edd31c83022cedde3aec:8","filtered_window_id":"dce7edd31c83022cedde3aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dce7edd31c83022cedde3aec/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[567,568,569,570,571,572,573,574],"take":"subject3/k1/3/cam4","frame_ids":[567,568,569,570,571,572,573,574]} +{"filtered_tile_id":"dce7edd31c83022cedde3aec:16","filtered_window_id":"dce7edd31c83022cedde3aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dce7edd31c83022cedde3aec/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[575,576,577,578,579,580,581,582],"take":"subject3/k1/3/cam4","frame_ids":[575,576,577,578,579,580,581,582]} +{"filtered_tile_id":"dce7edd31c83022cedde3aec:24","filtered_window_id":"dce7edd31c83022cedde3aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dce7edd31c83022cedde3aec/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[583,584,585,586,587,588,589,590],"take":"subject3/k1/3/cam4","frame_ids":[583,584,585,586,587,588,589,590]} +{"filtered_tile_id":"dce7edd31c83022cedde3aec:32","filtered_window_id":"dce7edd31c83022cedde3aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dce7edd31c83022cedde3aec/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[591,592,593,594,595,596,597,598],"take":"subject3/k1/3/cam4","frame_ids":[591,592,593,594,595,596,597,598]} +{"filtered_tile_id":"dce7edd31c83022cedde3aec:40","filtered_window_id":"dce7edd31c83022cedde3aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dce7edd31c83022cedde3aec/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[599,600,601,602,603,604,605,606],"take":"subject3/k1/3/cam4","frame_ids":[599,600,601,602,603,604,605,606]} +{"filtered_tile_id":"dce7edd31c83022cedde3aec:48","filtered_window_id":"dce7edd31c83022cedde3aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dce7edd31c83022cedde3aec/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[607,608,609,610,611,612,613,614],"take":"subject3/k1/3/cam4","frame_ids":[607,608,609,610,611,612,613,614]} +{"filtered_tile_id":"dce7edd31c83022cedde3aec:52","filtered_window_id":"dce7edd31c83022cedde3aec","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dce7edd31c83022cedde3aec/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[611,612,613,614,615,616,617,618],"take":"subject3/k1/3/cam4","frame_ids":[611,612,613,614,615,616,617,618]} +{"filtered_tile_id":"dd2413afbdf252acc12d906a:0","filtered_window_id":"dd2413afbdf252acc12d906a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd2413afbdf252acc12d906a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject1/k1/5/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"dd2413afbdf252acc12d906a:8","filtered_window_id":"dd2413afbdf252acc12d906a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd2413afbdf252acc12d906a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject1/k1/5/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"dd2413afbdf252acc12d906a:16","filtered_window_id":"dd2413afbdf252acc12d906a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd2413afbdf252acc12d906a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[376,377,378,379,380,381,382,383],"take":"subject1/k1/5/cam4","frame_ids":[376,377,378,379,380,381,382,383]} +{"filtered_tile_id":"dd2413afbdf252acc12d906a:24","filtered_window_id":"dd2413afbdf252acc12d906a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd2413afbdf252acc12d906a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[384,385,386,387,388,389,390,391],"take":"subject1/k1/5/cam4","frame_ids":[384,385,386,387,388,389,390,391]} +{"filtered_tile_id":"dd2413afbdf252acc12d906a:32","filtered_window_id":"dd2413afbdf252acc12d906a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd2413afbdf252acc12d906a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[392,393,394,395,396,397,398,399],"take":"subject1/k1/5/cam4","frame_ids":[392,393,394,395,396,397,398,399]} +{"filtered_tile_id":"dd2413afbdf252acc12d906a:40","filtered_window_id":"dd2413afbdf252acc12d906a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd2413afbdf252acc12d906a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[400,401,402,403,404,405,406,407],"take":"subject1/k1/5/cam4","frame_ids":[400,401,402,403,404,405,406,407]} +{"filtered_tile_id":"dd2413afbdf252acc12d906a:48","filtered_window_id":"dd2413afbdf252acc12d906a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd2413afbdf252acc12d906a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[408,409,410,411,412,413,414,415],"take":"subject1/k1/5/cam4","frame_ids":[408,409,410,411,412,413,414,415]} +{"filtered_tile_id":"dd2413afbdf252acc12d906a:52","filtered_window_id":"dd2413afbdf252acc12d906a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd2413afbdf252acc12d906a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject1/k1/5/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"dd86b841f0dcc57ebace2ec3:0","filtered_window_id":"dd86b841f0dcc57ebace2ec3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd86b841f0dcc57ebace2ec3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[307,308,309,310,311,312,313,314],"take":"subject1/o2/4/cam4","frame_ids":[307,308,309,310,311,312,313,314]} +{"filtered_tile_id":"dd86b841f0dcc57ebace2ec3:2","filtered_window_id":"dd86b841f0dcc57ebace2ec3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/dd86b841f0dcc57ebace2ec3/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject1/o2/4/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"ddc9f9af85ba6453032b2d3e:0","filtered_window_id":"ddc9f9af85ba6453032b2d3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ddc9f9af85ba6453032b2d3e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject2/k1/2/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"ddc9f9af85ba6453032b2d3e:8","filtered_window_id":"ddc9f9af85ba6453032b2d3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ddc9f9af85ba6453032b2d3e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject2/k1/2/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"ddc9f9af85ba6453032b2d3e:16","filtered_window_id":"ddc9f9af85ba6453032b2d3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ddc9f9af85ba6453032b2d3e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject2/k1/2/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"ddc9f9af85ba6453032b2d3e:24","filtered_window_id":"ddc9f9af85ba6453032b2d3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ddc9f9af85ba6453032b2d3e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject2/k1/2/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"ddc9f9af85ba6453032b2d3e:32","filtered_window_id":"ddc9f9af85ba6453032b2d3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ddc9f9af85ba6453032b2d3e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[173,174,175,176,177,178,179,180],"take":"subject2/k1/2/cam4","frame_ids":[173,174,175,176,177,178,179,180]} +{"filtered_tile_id":"ddc9f9af85ba6453032b2d3e:40","filtered_window_id":"ddc9f9af85ba6453032b2d3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ddc9f9af85ba6453032b2d3e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[181,182,183,184,185,186,187,188],"take":"subject2/k1/2/cam4","frame_ids":[181,182,183,184,185,186,187,188]} +{"filtered_tile_id":"ddc9f9af85ba6453032b2d3e:48","filtered_window_id":"ddc9f9af85ba6453032b2d3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ddc9f9af85ba6453032b2d3e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[189,190,191,192,193,194,195,196],"take":"subject2/k1/2/cam4","frame_ids":[189,190,191,192,193,194,195,196]} +{"filtered_tile_id":"ddc9f9af85ba6453032b2d3e:52","filtered_window_id":"ddc9f9af85ba6453032b2d3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ddc9f9af85ba6453032b2d3e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject2/k1/2/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"de0073dbf81b5d645631e935:0","filtered_window_id":"de0073dbf81b5d645631e935","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de0073dbf81b5d645631e935/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[359,360,361,362,363,364,365,366],"take":"subject1/o1/2/cam4","frame_ids":[359,360,361,362,363,364,365,366]} +{"filtered_tile_id":"de0073dbf81b5d645631e935:8","filtered_window_id":"de0073dbf81b5d645631e935","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de0073dbf81b5d645631e935/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[367,368,369,370,371,372,373,374],"take":"subject1/o1/2/cam4","frame_ids":[367,368,369,370,371,372,373,374]} +{"filtered_tile_id":"de0073dbf81b5d645631e935:16","filtered_window_id":"de0073dbf81b5d645631e935","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de0073dbf81b5d645631e935/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[375,376,377,378,379,380,381,382],"take":"subject1/o1/2/cam4","frame_ids":[375,376,377,378,379,380,381,382]} +{"filtered_tile_id":"de0073dbf81b5d645631e935:24","filtered_window_id":"de0073dbf81b5d645631e935","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de0073dbf81b5d645631e935/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject1/o1/2/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"de0073dbf81b5d645631e935:32","filtered_window_id":"de0073dbf81b5d645631e935","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de0073dbf81b5d645631e935/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[391,392,393,394,395,396,397,398],"take":"subject1/o1/2/cam4","frame_ids":[391,392,393,394,395,396,397,398]} +{"filtered_tile_id":"de0073dbf81b5d645631e935:40","filtered_window_id":"de0073dbf81b5d645631e935","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de0073dbf81b5d645631e935/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[399,400,401,402,403,404,405,406],"take":"subject1/o1/2/cam4","frame_ids":[399,400,401,402,403,404,405,406]} +{"filtered_tile_id":"de0073dbf81b5d645631e935:48","filtered_window_id":"de0073dbf81b5d645631e935","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de0073dbf81b5d645631e935/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[407,408,409,410,411,412,413,414],"take":"subject1/o1/2/cam4","frame_ids":[407,408,409,410,411,412,413,414]} +{"filtered_tile_id":"de0073dbf81b5d645631e935:52","filtered_window_id":"de0073dbf81b5d645631e935","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de0073dbf81b5d645631e935/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[411,412,413,414,415,416,417,418],"take":"subject1/o1/2/cam4","frame_ids":[411,412,413,414,415,416,417,418]} +{"filtered_tile_id":"de2d2116117b83584a52bfa9:0","filtered_window_id":"de2d2116117b83584a52bfa9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de2d2116117b83584a52bfa9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject1/k1/6/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"de2d2116117b83584a52bfa9:8","filtered_window_id":"de2d2116117b83584a52bfa9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de2d2116117b83584a52bfa9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject1/k1/6/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"de2d2116117b83584a52bfa9:16","filtered_window_id":"de2d2116117b83584a52bfa9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de2d2116117b83584a52bfa9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject1/k1/6/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"de2d2116117b83584a52bfa9:24","filtered_window_id":"de2d2116117b83584a52bfa9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de2d2116117b83584a52bfa9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject1/k1/6/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"de2d2116117b83584a52bfa9:32","filtered_window_id":"de2d2116117b83584a52bfa9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de2d2116117b83584a52bfa9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[361,362,363,364,365,366,367,368],"take":"subject1/k1/6/cam4","frame_ids":[361,362,363,364,365,366,367,368]} +{"filtered_tile_id":"de2d2116117b83584a52bfa9:40","filtered_window_id":"de2d2116117b83584a52bfa9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de2d2116117b83584a52bfa9/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[369,370,371,372,373,374,375,376],"take":"subject1/k1/6/cam4","frame_ids":[369,370,371,372,373,374,375,376]} +{"filtered_tile_id":"de2d2116117b83584a52bfa9:48","filtered_window_id":"de2d2116117b83584a52bfa9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de2d2116117b83584a52bfa9/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[377,378,379,380,381,382,383,384],"take":"subject1/k1/6/cam4","frame_ids":[377,378,379,380,381,382,383,384]} +{"filtered_tile_id":"de2d2116117b83584a52bfa9:52","filtered_window_id":"de2d2116117b83584a52bfa9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de2d2116117b83584a52bfa9/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[381,382,383,384,385,386,387,388],"take":"subject1/k1/6/cam4","frame_ids":[381,382,383,384,385,386,387,388]} +{"filtered_tile_id":"de53cfc47d160e6475bf208f:0","filtered_window_id":"de53cfc47d160e6475bf208f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de53cfc47d160e6475bf208f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject2/o1/6/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"de53cfc47d160e6475bf208f:8","filtered_window_id":"de53cfc47d160e6475bf208f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de53cfc47d160e6475bf208f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject2/o1/6/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"de53cfc47d160e6475bf208f:16","filtered_window_id":"de53cfc47d160e6475bf208f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de53cfc47d160e6475bf208f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject2/o1/6/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"de53cfc47d160e6475bf208f:24","filtered_window_id":"de53cfc47d160e6475bf208f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de53cfc47d160e6475bf208f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject2/o1/6/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"de53cfc47d160e6475bf208f:32","filtered_window_id":"de53cfc47d160e6475bf208f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de53cfc47d160e6475bf208f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject2/o1/6/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"de53cfc47d160e6475bf208f:40","filtered_window_id":"de53cfc47d160e6475bf208f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de53cfc47d160e6475bf208f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject2/o1/6/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"de53cfc47d160e6475bf208f:46","filtered_window_id":"de53cfc47d160e6475bf208f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/de53cfc47d160e6475bf208f/native_gt.npz","filtered_start_offset":46,"expected_frame_ids":[359,360,361,362,363,364,365,366],"take":"subject2/o1/6/cam4","frame_ids":[359,360,361,362,363,364,365,366]} +{"filtered_tile_id":"df06e72da9a729d242f8aeb6:0","filtered_window_id":"df06e72da9a729d242f8aeb6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df06e72da9a729d242f8aeb6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[470,471,472,473,474,475,476,477],"take":"subject1/k1/7/cam4","frame_ids":[470,471,472,473,474,475,476,477]} +{"filtered_tile_id":"df06e72da9a729d242f8aeb6:8","filtered_window_id":"df06e72da9a729d242f8aeb6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df06e72da9a729d242f8aeb6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject1/k1/7/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"df06e72da9a729d242f8aeb6:16","filtered_window_id":"df06e72da9a729d242f8aeb6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df06e72da9a729d242f8aeb6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject1/k1/7/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"df06e72da9a729d242f8aeb6:17","filtered_window_id":"df06e72da9a729d242f8aeb6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df06e72da9a729d242f8aeb6/native_gt.npz","filtered_start_offset":17,"expected_frame_ids":[487,488,489,490,491,492,493,494],"take":"subject1/k1/7/cam4","frame_ids":[487,488,489,490,491,492,493,494]} +{"filtered_tile_id":"df21fa75bc8518a2fe156420:0","filtered_window_id":"df21fa75bc8518a2fe156420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df21fa75bc8518a2fe156420/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[488,489,490,491,492,493,494,495],"take":"subject3/h2/0/cam4","frame_ids":[488,489,490,491,492,493,494,495]} +{"filtered_tile_id":"df21fa75bc8518a2fe156420:8","filtered_window_id":"df21fa75bc8518a2fe156420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df21fa75bc8518a2fe156420/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[496,497,498,499,500,501,502,503],"take":"subject3/h2/0/cam4","frame_ids":[496,497,498,499,500,501,502,503]} +{"filtered_tile_id":"df21fa75bc8518a2fe156420:16","filtered_window_id":"df21fa75bc8518a2fe156420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df21fa75bc8518a2fe156420/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[504,505,506,507,508,509,510,511],"take":"subject3/h2/0/cam4","frame_ids":[504,505,506,507,508,509,510,511]} +{"filtered_tile_id":"df21fa75bc8518a2fe156420:24","filtered_window_id":"df21fa75bc8518a2fe156420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df21fa75bc8518a2fe156420/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[512,513,514,515,516,517,518,519],"take":"subject3/h2/0/cam4","frame_ids":[512,513,514,515,516,517,518,519]} +{"filtered_tile_id":"df21fa75bc8518a2fe156420:32","filtered_window_id":"df21fa75bc8518a2fe156420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df21fa75bc8518a2fe156420/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[520,521,522,523,524,525,526,527],"take":"subject3/h2/0/cam4","frame_ids":[520,521,522,523,524,525,526,527]} +{"filtered_tile_id":"df21fa75bc8518a2fe156420:40","filtered_window_id":"df21fa75bc8518a2fe156420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df21fa75bc8518a2fe156420/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[528,529,530,531,532,533,534,535],"take":"subject3/h2/0/cam4","frame_ids":[528,529,530,531,532,533,534,535]} +{"filtered_tile_id":"df21fa75bc8518a2fe156420:48","filtered_window_id":"df21fa75bc8518a2fe156420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df21fa75bc8518a2fe156420/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[536,537,538,539,540,541,542,543],"take":"subject3/h2/0/cam4","frame_ids":[536,537,538,539,540,541,542,543]} +{"filtered_tile_id":"df21fa75bc8518a2fe156420:52","filtered_window_id":"df21fa75bc8518a2fe156420","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df21fa75bc8518a2fe156420/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[540,541,542,543,544,545,546,547],"take":"subject3/h2/0/cam4","frame_ids":[540,541,542,543,544,545,546,547]} +{"filtered_tile_id":"df31dd4eeecc613ea73dfd02:0","filtered_window_id":"df31dd4eeecc613ea73dfd02","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df31dd4eeecc613ea73dfd02/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[588,589,590,591,592,593,594,595],"take":"subject2/k2/0/cam4","frame_ids":[588,589,590,591,592,593,594,595]} +{"filtered_tile_id":"df31dd4eeecc613ea73dfd02:8","filtered_window_id":"df31dd4eeecc613ea73dfd02","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df31dd4eeecc613ea73dfd02/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[596,597,598,599,600,601,602,603],"take":"subject2/k2/0/cam4","frame_ids":[596,597,598,599,600,601,602,603]} +{"filtered_tile_id":"df31dd4eeecc613ea73dfd02:16","filtered_window_id":"df31dd4eeecc613ea73dfd02","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df31dd4eeecc613ea73dfd02/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[604,605,606,607,608,609,610,611],"take":"subject2/k2/0/cam4","frame_ids":[604,605,606,607,608,609,610,611]} +{"filtered_tile_id":"df31dd4eeecc613ea73dfd02:24","filtered_window_id":"df31dd4eeecc613ea73dfd02","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df31dd4eeecc613ea73dfd02/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[612,613,614,615,616,617,618,619],"take":"subject2/k2/0/cam4","frame_ids":[612,613,614,615,616,617,618,619]} +{"filtered_tile_id":"df31dd4eeecc613ea73dfd02:32","filtered_window_id":"df31dd4eeecc613ea73dfd02","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df31dd4eeecc613ea73dfd02/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[620,621,622,623,624,625,626,627],"take":"subject2/k2/0/cam4","frame_ids":[620,621,622,623,624,625,626,627]} +{"filtered_tile_id":"df86600a22879c9b2597d382:0","filtered_window_id":"df86600a22879c9b2597d382","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df86600a22879c9b2597d382/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject1/o2/4/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"df86600a22879c9b2597d382:8","filtered_window_id":"df86600a22879c9b2597d382","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df86600a22879c9b2597d382/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject1/o2/4/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"df86600a22879c9b2597d382:16","filtered_window_id":"df86600a22879c9b2597d382","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df86600a22879c9b2597d382/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject1/o2/4/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"df86600a22879c9b2597d382:24","filtered_window_id":"df86600a22879c9b2597d382","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df86600a22879c9b2597d382/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[526,527,528,529,530,531,532,533],"take":"subject1/o2/4/cam4","frame_ids":[526,527,528,529,530,531,532,533]} +{"filtered_tile_id":"df86600a22879c9b2597d382:32","filtered_window_id":"df86600a22879c9b2597d382","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df86600a22879c9b2597d382/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[534,535,536,537,538,539,540,541],"take":"subject1/o2/4/cam4","frame_ids":[534,535,536,537,538,539,540,541]} +{"filtered_tile_id":"df86600a22879c9b2597d382:40","filtered_window_id":"df86600a22879c9b2597d382","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df86600a22879c9b2597d382/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[542,543,544,545,546,547,548,549],"take":"subject1/o2/4/cam4","frame_ids":[542,543,544,545,546,547,548,549]} +{"filtered_tile_id":"df86600a22879c9b2597d382:48","filtered_window_id":"df86600a22879c9b2597d382","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df86600a22879c9b2597d382/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[550,551,552,553,554,555,556,557],"take":"subject1/o2/4/cam4","frame_ids":[550,551,552,553,554,555,556,557]} +{"filtered_tile_id":"df86600a22879c9b2597d382:52","filtered_window_id":"df86600a22879c9b2597d382","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/df86600a22879c9b2597d382/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[554,555,556,557,558,559,560,561],"take":"subject1/o2/4/cam4","frame_ids":[554,555,556,557,558,559,560,561]} +{"filtered_tile_id":"e0038a0510d1dc9d56f26162:0","filtered_window_id":"e0038a0510d1dc9d56f26162","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e0038a0510d1dc9d56f26162/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[309,310,311,312,313,314,315,316],"take":"subject1/h1/4/cam4","frame_ids":[309,310,311,312,313,314,315,316]} +{"filtered_tile_id":"e0038a0510d1dc9d56f26162:8","filtered_window_id":"e0038a0510d1dc9d56f26162","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e0038a0510d1dc9d56f26162/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[317,318,319,320,321,322,323,324],"take":"subject1/h1/4/cam4","frame_ids":[317,318,319,320,321,322,323,324]} +{"filtered_tile_id":"e0038a0510d1dc9d56f26162:16","filtered_window_id":"e0038a0510d1dc9d56f26162","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e0038a0510d1dc9d56f26162/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject1/h1/4/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"e0038a0510d1dc9d56f26162:19","filtered_window_id":"e0038a0510d1dc9d56f26162","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e0038a0510d1dc9d56f26162/native_gt.npz","filtered_start_offset":19,"expected_frame_ids":[328,329,330,331,332,333,334,335],"take":"subject1/h1/4/cam4","frame_ids":[328,329,330,331,332,333,334,335]} +{"filtered_tile_id":"e095d566e0f4e367ccfdacc2:0","filtered_window_id":"e095d566e0f4e367ccfdacc2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e095d566e0f4e367ccfdacc2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[160,161,162,163,164,165,166,167],"take":"subject2/k2/1/cam4","frame_ids":[160,161,162,163,164,165,166,167]} +{"filtered_tile_id":"e095d566e0f4e367ccfdacc2:8","filtered_window_id":"e095d566e0f4e367ccfdacc2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e095d566e0f4e367ccfdacc2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject2/k2/1/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"e095d566e0f4e367ccfdacc2:16","filtered_window_id":"e095d566e0f4e367ccfdacc2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e095d566e0f4e367ccfdacc2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject2/k2/1/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"e095d566e0f4e367ccfdacc2:24","filtered_window_id":"e095d566e0f4e367ccfdacc2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e095d566e0f4e367ccfdacc2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject2/k2/1/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"e095d566e0f4e367ccfdacc2:32","filtered_window_id":"e095d566e0f4e367ccfdacc2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e095d566e0f4e367ccfdacc2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[192,193,194,195,196,197,198,199],"take":"subject2/k2/1/cam4","frame_ids":[192,193,194,195,196,197,198,199]} +{"filtered_tile_id":"e095d566e0f4e367ccfdacc2:40","filtered_window_id":"e095d566e0f4e367ccfdacc2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e095d566e0f4e367ccfdacc2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[200,201,202,203,204,205,206,207],"take":"subject2/k2/1/cam4","frame_ids":[200,201,202,203,204,205,206,207]} +{"filtered_tile_id":"e095d566e0f4e367ccfdacc2:48","filtered_window_id":"e095d566e0f4e367ccfdacc2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e095d566e0f4e367ccfdacc2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[208,209,210,211,212,213,214,215],"take":"subject2/k2/1/cam4","frame_ids":[208,209,210,211,212,213,214,215]} +{"filtered_tile_id":"e095d566e0f4e367ccfdacc2:52","filtered_window_id":"e095d566e0f4e367ccfdacc2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e095d566e0f4e367ccfdacc2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[212,213,214,215,216,217,218,219],"take":"subject2/k2/1/cam4","frame_ids":[212,213,214,215,216,217,218,219]} +{"filtered_tile_id":"e0fd7ecf4ffb265be19f9c1e:0","filtered_window_id":"e0fd7ecf4ffb265be19f9c1e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e0fd7ecf4ffb265be19f9c1e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject2/k2/6/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"e0fd7ecf4ffb265be19f9c1e:8","filtered_window_id":"e0fd7ecf4ffb265be19f9c1e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e0fd7ecf4ffb265be19f9c1e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject2/k2/6/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"e0fd7ecf4ffb265be19f9c1e:9","filtered_window_id":"e0fd7ecf4ffb265be19f9c1e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e0fd7ecf4ffb265be19f9c1e/native_gt.npz","filtered_start_offset":9,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject2/k2/6/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"e13fa71b3b1429fe9fac4e6e:0","filtered_window_id":"e13fa71b3b1429fe9fac4e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e13fa71b3b1429fe9fac4e6e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[408,409,410,411,412,413,414,415],"take":"subject1/h1/6/cam4","frame_ids":[408,409,410,411,412,413,414,415]} +{"filtered_tile_id":"e13fa71b3b1429fe9fac4e6e:8","filtered_window_id":"e13fa71b3b1429fe9fac4e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e13fa71b3b1429fe9fac4e6e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[416,417,418,419,420,421,422,423],"take":"subject1/h1/6/cam4","frame_ids":[416,417,418,419,420,421,422,423]} +{"filtered_tile_id":"e13fa71b3b1429fe9fac4e6e:16","filtered_window_id":"e13fa71b3b1429fe9fac4e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e13fa71b3b1429fe9fac4e6e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[424,425,426,427,428,429,430,431],"take":"subject1/h1/6/cam4","frame_ids":[424,425,426,427,428,429,430,431]} +{"filtered_tile_id":"e13fa71b3b1429fe9fac4e6e:24","filtered_window_id":"e13fa71b3b1429fe9fac4e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e13fa71b3b1429fe9fac4e6e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[432,433,434,435,436,437,438,439],"take":"subject1/h1/6/cam4","frame_ids":[432,433,434,435,436,437,438,439]} +{"filtered_tile_id":"e13fa71b3b1429fe9fac4e6e:32","filtered_window_id":"e13fa71b3b1429fe9fac4e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e13fa71b3b1429fe9fac4e6e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[440,441,442,443,444,445,446,447],"take":"subject1/h1/6/cam4","frame_ids":[440,441,442,443,444,445,446,447]} +{"filtered_tile_id":"e13fa71b3b1429fe9fac4e6e:40","filtered_window_id":"e13fa71b3b1429fe9fac4e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e13fa71b3b1429fe9fac4e6e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[448,449,450,451,452,453,454,455],"take":"subject1/h1/6/cam4","frame_ids":[448,449,450,451,452,453,454,455]} +{"filtered_tile_id":"e13fa71b3b1429fe9fac4e6e:44","filtered_window_id":"e13fa71b3b1429fe9fac4e6e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e13fa71b3b1429fe9fac4e6e/native_gt.npz","filtered_start_offset":44,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject1/h1/6/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"e20fe10f70cd4a12ca5aa238:0","filtered_window_id":"e20fe10f70cd4a12ca5aa238","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e20fe10f70cd4a12ca5aa238/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject2/h1/3/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"e20fe10f70cd4a12ca5aa238:8","filtered_window_id":"e20fe10f70cd4a12ca5aa238","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e20fe10f70cd4a12ca5aa238/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[366,367,368,369,370,371,372,373],"take":"subject2/h1/3/cam4","frame_ids":[366,367,368,369,370,371,372,373]} +{"filtered_tile_id":"e20fe10f70cd4a12ca5aa238:11","filtered_window_id":"e20fe10f70cd4a12ca5aa238","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e20fe10f70cd4a12ca5aa238/native_gt.npz","filtered_start_offset":11,"expected_frame_ids":[369,370,371,372,373,374,375,376],"take":"subject2/h1/3/cam4","frame_ids":[369,370,371,372,373,374,375,376]} +{"filtered_tile_id":"e21b529f263ac2ed0203db16:0","filtered_window_id":"e21b529f263ac2ed0203db16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e21b529f263ac2ed0203db16/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject3/h2/5/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"e21b529f263ac2ed0203db16:5","filtered_window_id":"e21b529f263ac2ed0203db16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e21b529f263ac2ed0203db16/native_gt.npz","filtered_start_offset":5,"expected_frame_ids":[208,209,210,211,212,213,214,215],"take":"subject3/h2/5/cam4","frame_ids":[208,209,210,211,212,213,214,215]} +{"filtered_tile_id":"e22107a05ce3cb93a1513d89:0","filtered_window_id":"e22107a05ce3cb93a1513d89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22107a05ce3cb93a1513d89/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject1/o2/1/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"e22107a05ce3cb93a1513d89:8","filtered_window_id":"e22107a05ce3cb93a1513d89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22107a05ce3cb93a1513d89/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject1/o2/1/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"e22107a05ce3cb93a1513d89:16","filtered_window_id":"e22107a05ce3cb93a1513d89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22107a05ce3cb93a1513d89/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject1/o2/1/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"e22107a05ce3cb93a1513d89:24","filtered_window_id":"e22107a05ce3cb93a1513d89","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22107a05ce3cb93a1513d89/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject1/o2/1/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"e22e0e912270032d773aa881:0","filtered_window_id":"e22e0e912270032d773aa881","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22e0e912270032d773aa881/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject3/h1/4/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"e22e0e912270032d773aa881:8","filtered_window_id":"e22e0e912270032d773aa881","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22e0e912270032d773aa881/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[187,188,189,190,191,192,193,194],"take":"subject3/h1/4/cam4","frame_ids":[187,188,189,190,191,192,193,194]} +{"filtered_tile_id":"e22e0e912270032d773aa881:16","filtered_window_id":"e22e0e912270032d773aa881","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22e0e912270032d773aa881/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[195,196,197,198,199,200,201,202],"take":"subject3/h1/4/cam4","frame_ids":[195,196,197,198,199,200,201,202]} +{"filtered_tile_id":"e22e0e912270032d773aa881:24","filtered_window_id":"e22e0e912270032d773aa881","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22e0e912270032d773aa881/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[203,204,205,206,207,208,209,210],"take":"subject3/h1/4/cam4","frame_ids":[203,204,205,206,207,208,209,210]} +{"filtered_tile_id":"e22e0e912270032d773aa881:32","filtered_window_id":"e22e0e912270032d773aa881","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22e0e912270032d773aa881/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[211,212,213,214,215,216,217,218],"take":"subject3/h1/4/cam4","frame_ids":[211,212,213,214,215,216,217,218]} +{"filtered_tile_id":"e22e0e912270032d773aa881:40","filtered_window_id":"e22e0e912270032d773aa881","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22e0e912270032d773aa881/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[219,220,221,222,223,224,225,226],"take":"subject3/h1/4/cam4","frame_ids":[219,220,221,222,223,224,225,226]} +{"filtered_tile_id":"e22e0e912270032d773aa881:48","filtered_window_id":"e22e0e912270032d773aa881","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22e0e912270032d773aa881/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[227,228,229,230,231,232,233,234],"take":"subject3/h1/4/cam4","frame_ids":[227,228,229,230,231,232,233,234]} +{"filtered_tile_id":"e22e0e912270032d773aa881:52","filtered_window_id":"e22e0e912270032d773aa881","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e22e0e912270032d773aa881/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[231,232,233,234,235,236,237,238],"take":"subject3/h1/4/cam4","frame_ids":[231,232,233,234,235,236,237,238]} +{"filtered_tile_id":"e24874da7c4d0442c84edbcd:0","filtered_window_id":"e24874da7c4d0442c84edbcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e24874da7c4d0442c84edbcd/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[516,517,518,519,520,521,522,523],"take":"subject3/h2/3/cam4","frame_ids":[516,517,518,519,520,521,522,523]} +{"filtered_tile_id":"e24874da7c4d0442c84edbcd:8","filtered_window_id":"e24874da7c4d0442c84edbcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e24874da7c4d0442c84edbcd/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[524,525,526,527,528,529,530,531],"take":"subject3/h2/3/cam4","frame_ids":[524,525,526,527,528,529,530,531]} +{"filtered_tile_id":"e24874da7c4d0442c84edbcd:16","filtered_window_id":"e24874da7c4d0442c84edbcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e24874da7c4d0442c84edbcd/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[532,533,534,535,536,537,538,539],"take":"subject3/h2/3/cam4","frame_ids":[532,533,534,535,536,537,538,539]} +{"filtered_tile_id":"e24874da7c4d0442c84edbcd:24","filtered_window_id":"e24874da7c4d0442c84edbcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e24874da7c4d0442c84edbcd/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[540,541,542,543,544,545,546,547],"take":"subject3/h2/3/cam4","frame_ids":[540,541,542,543,544,545,546,547]} +{"filtered_tile_id":"e24874da7c4d0442c84edbcd:32","filtered_window_id":"e24874da7c4d0442c84edbcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e24874da7c4d0442c84edbcd/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject3/h2/3/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"e24874da7c4d0442c84edbcd:40","filtered_window_id":"e24874da7c4d0442c84edbcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e24874da7c4d0442c84edbcd/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject3/h2/3/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"e24874da7c4d0442c84edbcd:48","filtered_window_id":"e24874da7c4d0442c84edbcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e24874da7c4d0442c84edbcd/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject3/h2/3/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"e24874da7c4d0442c84edbcd:52","filtered_window_id":"e24874da7c4d0442c84edbcd","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e24874da7c4d0442c84edbcd/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[568,569,570,571,572,573,574,575],"take":"subject3/h2/3/cam4","frame_ids":[568,569,570,571,572,573,574,575]} +{"filtered_tile_id":"e253ccaafab726253c2e77c2:0","filtered_window_id":"e253ccaafab726253c2e77c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e253ccaafab726253c2e77c2/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[202,203,204,205,206,207,208,209],"take":"subject3/h1/2/cam4","frame_ids":[202,203,204,205,206,207,208,209]} +{"filtered_tile_id":"e253ccaafab726253c2e77c2:8","filtered_window_id":"e253ccaafab726253c2e77c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e253ccaafab726253c2e77c2/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[210,211,212,213,214,215,216,217],"take":"subject3/h1/2/cam4","frame_ids":[210,211,212,213,214,215,216,217]} +{"filtered_tile_id":"e253ccaafab726253c2e77c2:16","filtered_window_id":"e253ccaafab726253c2e77c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e253ccaafab726253c2e77c2/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[218,219,220,221,222,223,224,225],"take":"subject3/h1/2/cam4","frame_ids":[218,219,220,221,222,223,224,225]} +{"filtered_tile_id":"e253ccaafab726253c2e77c2:24","filtered_window_id":"e253ccaafab726253c2e77c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e253ccaafab726253c2e77c2/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject3/h1/2/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"e253ccaafab726253c2e77c2:32","filtered_window_id":"e253ccaafab726253c2e77c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e253ccaafab726253c2e77c2/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[234,235,236,237,238,239,240,241],"take":"subject3/h1/2/cam4","frame_ids":[234,235,236,237,238,239,240,241]} +{"filtered_tile_id":"e253ccaafab726253c2e77c2:40","filtered_window_id":"e253ccaafab726253c2e77c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e253ccaafab726253c2e77c2/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject3/h1/2/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"e253ccaafab726253c2e77c2:48","filtered_window_id":"e253ccaafab726253c2e77c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e253ccaafab726253c2e77c2/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject3/h1/2/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"e253ccaafab726253c2e77c2:52","filtered_window_id":"e253ccaafab726253c2e77c2","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e253ccaafab726253c2e77c2/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject3/h1/2/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"e2b2039a1a1f070761032a68:0","filtered_window_id":"e2b2039a1a1f070761032a68","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b2039a1a1f070761032a68/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[432,433,434,435,436,437,438,439],"take":"subject2/k2/1/cam4","frame_ids":[432,433,434,435,436,437,438,439]} +{"filtered_tile_id":"e2b2039a1a1f070761032a68:8","filtered_window_id":"e2b2039a1a1f070761032a68","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b2039a1a1f070761032a68/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[440,441,442,443,444,445,446,447],"take":"subject2/k2/1/cam4","frame_ids":[440,441,442,443,444,445,446,447]} +{"filtered_tile_id":"e2b2039a1a1f070761032a68:16","filtered_window_id":"e2b2039a1a1f070761032a68","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b2039a1a1f070761032a68/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[448,449,450,451,452,453,454,455],"take":"subject2/k2/1/cam4","frame_ids":[448,449,450,451,452,453,454,455]} +{"filtered_tile_id":"e2b2039a1a1f070761032a68:24","filtered_window_id":"e2b2039a1a1f070761032a68","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b2039a1a1f070761032a68/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[456,457,458,459,460,461,462,463],"take":"subject2/k2/1/cam4","frame_ids":[456,457,458,459,460,461,462,463]} +{"filtered_tile_id":"e2b2039a1a1f070761032a68:32","filtered_window_id":"e2b2039a1a1f070761032a68","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b2039a1a1f070761032a68/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[464,465,466,467,468,469,470,471],"take":"subject2/k2/1/cam4","frame_ids":[464,465,466,467,468,469,470,471]} +{"filtered_tile_id":"e2b2039a1a1f070761032a68:40","filtered_window_id":"e2b2039a1a1f070761032a68","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b2039a1a1f070761032a68/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[472,473,474,475,476,477,478,479],"take":"subject2/k2/1/cam4","frame_ids":[472,473,474,475,476,477,478,479]} +{"filtered_tile_id":"e2b2039a1a1f070761032a68:48","filtered_window_id":"e2b2039a1a1f070761032a68","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b2039a1a1f070761032a68/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject2/k2/1/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"e2b2039a1a1f070761032a68:52","filtered_window_id":"e2b2039a1a1f070761032a68","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b2039a1a1f070761032a68/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[484,485,486,487,488,489,490,491],"take":"subject2/k2/1/cam4","frame_ids":[484,485,486,487,488,489,490,491]} +{"filtered_tile_id":"e2b68b42b0c4127500fd9e8c:0","filtered_window_id":"e2b68b42b0c4127500fd9e8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b68b42b0c4127500fd9e8c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[568,569,570,571,572,573,574,575],"take":"subject2/h2/4/cam4","frame_ids":[568,569,570,571,572,573,574,575]} +{"filtered_tile_id":"e2b68b42b0c4127500fd9e8c:8","filtered_window_id":"e2b68b42b0c4127500fd9e8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b68b42b0c4127500fd9e8c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[576,577,578,579,580,581,582,583],"take":"subject2/h2/4/cam4","frame_ids":[576,577,578,579,580,581,582,583]} +{"filtered_tile_id":"e2b68b42b0c4127500fd9e8c:16","filtered_window_id":"e2b68b42b0c4127500fd9e8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b68b42b0c4127500fd9e8c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[584,585,586,587,588,589,590,591],"take":"subject2/h2/4/cam4","frame_ids":[584,585,586,587,588,589,590,591]} +{"filtered_tile_id":"e2b68b42b0c4127500fd9e8c:24","filtered_window_id":"e2b68b42b0c4127500fd9e8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b68b42b0c4127500fd9e8c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[592,593,594,595,596,597,598,599],"take":"subject2/h2/4/cam4","frame_ids":[592,593,594,595,596,597,598,599]} +{"filtered_tile_id":"e2b68b42b0c4127500fd9e8c:32","filtered_window_id":"e2b68b42b0c4127500fd9e8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b68b42b0c4127500fd9e8c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[600,601,602,603,604,605,606,607],"take":"subject2/h2/4/cam4","frame_ids":[600,601,602,603,604,605,606,607]} +{"filtered_tile_id":"e2b68b42b0c4127500fd9e8c:40","filtered_window_id":"e2b68b42b0c4127500fd9e8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b68b42b0c4127500fd9e8c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[608,609,610,611,612,613,614,615],"take":"subject2/h2/4/cam4","frame_ids":[608,609,610,611,612,613,614,615]} +{"filtered_tile_id":"e2b68b42b0c4127500fd9e8c:48","filtered_window_id":"e2b68b42b0c4127500fd9e8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b68b42b0c4127500fd9e8c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[616,617,618,619,620,621,622,623],"take":"subject2/h2/4/cam4","frame_ids":[616,617,618,619,620,621,622,623]} +{"filtered_tile_id":"e2b68b42b0c4127500fd9e8c:52","filtered_window_id":"e2b68b42b0c4127500fd9e8c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2b68b42b0c4127500fd9e8c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[620,621,622,623,624,625,626,627],"take":"subject2/h2/4/cam4","frame_ids":[620,621,622,623,624,625,626,627]} +{"filtered_tile_id":"e2c62afea799c6ec187e63ab:0","filtered_window_id":"e2c62afea799c6ec187e63ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2c62afea799c6ec187e63ab/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[508,509,510,511,512,513,514,515],"take":"subject2/o1/6/cam4","frame_ids":[508,509,510,511,512,513,514,515]} +{"filtered_tile_id":"e2c62afea799c6ec187e63ab:5","filtered_window_id":"e2c62afea799c6ec187e63ab","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e2c62afea799c6ec187e63ab/native_gt.npz","filtered_start_offset":5,"expected_frame_ids":[513,514,515,516,517,518,519,520],"take":"subject2/o1/6/cam4","frame_ids":[513,514,515,516,517,518,519,520]} +{"filtered_tile_id":"e3618902893b5df8e78d8a3e:0","filtered_window_id":"e3618902893b5df8e78d8a3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3618902893b5df8e78d8a3e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k1/0/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"e3618902893b5df8e78d8a3e:8","filtered_window_id":"e3618902893b5df8e78d8a3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3618902893b5df8e78d8a3e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k1/0/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"e3618902893b5df8e78d8a3e:16","filtered_window_id":"e3618902893b5df8e78d8a3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3618902893b5df8e78d8a3e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k1/0/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"e3618902893b5df8e78d8a3e:24","filtered_window_id":"e3618902893b5df8e78d8a3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3618902893b5df8e78d8a3e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/k1/0/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"e3618902893b5df8e78d8a3e:32","filtered_window_id":"e3618902893b5df8e78d8a3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3618902893b5df8e78d8a3e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/k1/0/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"e3618902893b5df8e78d8a3e:40","filtered_window_id":"e3618902893b5df8e78d8a3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3618902893b5df8e78d8a3e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[56,57,58,59,60,61,62,63],"take":"subject1/k1/0/cam4","frame_ids":[56,57,58,59,60,61,62,63]} +{"filtered_tile_id":"e3618902893b5df8e78d8a3e:48","filtered_window_id":"e3618902893b5df8e78d8a3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3618902893b5df8e78d8a3e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject1/k1/0/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"e3618902893b5df8e78d8a3e:52","filtered_window_id":"e3618902893b5df8e78d8a3e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3618902893b5df8e78d8a3e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject1/k1/0/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"e36c149485df8b849f9c6336:0","filtered_window_id":"e36c149485df8b849f9c6336","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e36c149485df8b849f9c6336/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[287,288,289,290,291,292,293,294],"take":"subject2/k1/1/cam4","frame_ids":[287,288,289,290,291,292,293,294]} +{"filtered_tile_id":"e36c149485df8b849f9c6336:8","filtered_window_id":"e36c149485df8b849f9c6336","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e36c149485df8b849f9c6336/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[295,296,297,298,299,300,301,302],"take":"subject2/k1/1/cam4","frame_ids":[295,296,297,298,299,300,301,302]} +{"filtered_tile_id":"e36c149485df8b849f9c6336:16","filtered_window_id":"e36c149485df8b849f9c6336","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e36c149485df8b849f9c6336/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[303,304,305,306,307,308,309,310],"take":"subject2/k1/1/cam4","frame_ids":[303,304,305,306,307,308,309,310]} +{"filtered_tile_id":"e36c149485df8b849f9c6336:24","filtered_window_id":"e36c149485df8b849f9c6336","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e36c149485df8b849f9c6336/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[311,312,313,314,315,316,317,318],"take":"subject2/k1/1/cam4","frame_ids":[311,312,313,314,315,316,317,318]} +{"filtered_tile_id":"e36c149485df8b849f9c6336:32","filtered_window_id":"e36c149485df8b849f9c6336","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e36c149485df8b849f9c6336/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[319,320,321,322,323,324,325,326],"take":"subject2/k1/1/cam4","frame_ids":[319,320,321,322,323,324,325,326]} +{"filtered_tile_id":"e36c149485df8b849f9c6336:40","filtered_window_id":"e36c149485df8b849f9c6336","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e36c149485df8b849f9c6336/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[327,328,329,330,331,332,333,334],"take":"subject2/k1/1/cam4","frame_ids":[327,328,329,330,331,332,333,334]} +{"filtered_tile_id":"e36c149485df8b849f9c6336:48","filtered_window_id":"e36c149485df8b849f9c6336","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e36c149485df8b849f9c6336/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[335,336,337,338,339,340,341,342],"take":"subject2/k1/1/cam4","frame_ids":[335,336,337,338,339,340,341,342]} +{"filtered_tile_id":"e36c149485df8b849f9c6336:52","filtered_window_id":"e36c149485df8b849f9c6336","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e36c149485df8b849f9c6336/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[339,340,341,342,343,344,345,346],"take":"subject2/k1/1/cam4","frame_ids":[339,340,341,342,343,344,345,346]} +{"filtered_tile_id":"e3a74c7fa0aafcc8c7c9fc6c:0","filtered_window_id":"e3a74c7fa0aafcc8c7c9fc6c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3a74c7fa0aafcc8c7c9fc6c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[117,118,119,120,121,122,123,124],"take":"subject1/o1/5/cam4","frame_ids":[117,118,119,120,121,122,123,124]} +{"filtered_tile_id":"e3a74c7fa0aafcc8c7c9fc6c:8","filtered_window_id":"e3a74c7fa0aafcc8c7c9fc6c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3a74c7fa0aafcc8c7c9fc6c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[125,126,127,128,129,130,131,132],"take":"subject1/o1/5/cam4","frame_ids":[125,126,127,128,129,130,131,132]} +{"filtered_tile_id":"e3a74c7fa0aafcc8c7c9fc6c:16","filtered_window_id":"e3a74c7fa0aafcc8c7c9fc6c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3a74c7fa0aafcc8c7c9fc6c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[133,134,135,136,137,138,139,140],"take":"subject1/o1/5/cam4","frame_ids":[133,134,135,136,137,138,139,140]} +{"filtered_tile_id":"e3a74c7fa0aafcc8c7c9fc6c:24","filtered_window_id":"e3a74c7fa0aafcc8c7c9fc6c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3a74c7fa0aafcc8c7c9fc6c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[141,142,143,144,145,146,147,148],"take":"subject1/o1/5/cam4","frame_ids":[141,142,143,144,145,146,147,148]} +{"filtered_tile_id":"e3a74c7fa0aafcc8c7c9fc6c:32","filtered_window_id":"e3a74c7fa0aafcc8c7c9fc6c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3a74c7fa0aafcc8c7c9fc6c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[149,150,151,152,153,154,155,156],"take":"subject1/o1/5/cam4","frame_ids":[149,150,151,152,153,154,155,156]} +{"filtered_tile_id":"e3a74c7fa0aafcc8c7c9fc6c:40","filtered_window_id":"e3a74c7fa0aafcc8c7c9fc6c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3a74c7fa0aafcc8c7c9fc6c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[157,158,159,160,161,162,163,164],"take":"subject1/o1/5/cam4","frame_ids":[157,158,159,160,161,162,163,164]} +{"filtered_tile_id":"e3a74c7fa0aafcc8c7c9fc6c:48","filtered_window_id":"e3a74c7fa0aafcc8c7c9fc6c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3a74c7fa0aafcc8c7c9fc6c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[165,166,167,168,169,170,171,172],"take":"subject1/o1/5/cam4","frame_ids":[165,166,167,168,169,170,171,172]} +{"filtered_tile_id":"e3a74c7fa0aafcc8c7c9fc6c:52","filtered_window_id":"e3a74c7fa0aafcc8c7c9fc6c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3a74c7fa0aafcc8c7c9fc6c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[169,170,171,172,173,174,175,176],"take":"subject1/o1/5/cam4","frame_ids":[169,170,171,172,173,174,175,176]} +{"filtered_tile_id":"e3f19c76819f059571ab06f5:0","filtered_window_id":"e3f19c76819f059571ab06f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3f19c76819f059571ab06f5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[748,749,750,751,752,753,754,755],"take":"subject2/h2/4/cam4","frame_ids":[748,749,750,751,752,753,754,755]} +{"filtered_tile_id":"e3f19c76819f059571ab06f5:8","filtered_window_id":"e3f19c76819f059571ab06f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3f19c76819f059571ab06f5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[756,757,758,759,760,761,762,763],"take":"subject2/h2/4/cam4","frame_ids":[756,757,758,759,760,761,762,763]} +{"filtered_tile_id":"e3f19c76819f059571ab06f5:16","filtered_window_id":"e3f19c76819f059571ab06f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3f19c76819f059571ab06f5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[764,765,766,767,768,769,770,771],"take":"subject2/h2/4/cam4","frame_ids":[764,765,766,767,768,769,770,771]} +{"filtered_tile_id":"e3f19c76819f059571ab06f5:24","filtered_window_id":"e3f19c76819f059571ab06f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3f19c76819f059571ab06f5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[772,773,774,775,776,777,778,779],"take":"subject2/h2/4/cam4","frame_ids":[772,773,774,775,776,777,778,779]} +{"filtered_tile_id":"e3f19c76819f059571ab06f5:27","filtered_window_id":"e3f19c76819f059571ab06f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e3f19c76819f059571ab06f5/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[775,776,777,778,779,780,781,782],"take":"subject2/h2/4/cam4","frame_ids":[775,776,777,778,779,780,781,782]} +{"filtered_tile_id":"e421cbe14676e5ccc550474d:0","filtered_window_id":"e421cbe14676e5ccc550474d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e421cbe14676e5ccc550474d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject1/h1/7/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"e421cbe14676e5ccc550474d:8","filtered_window_id":"e421cbe14676e5ccc550474d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e421cbe14676e5ccc550474d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject1/h1/7/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"e421cbe14676e5ccc550474d:16","filtered_window_id":"e421cbe14676e5ccc550474d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e421cbe14676e5ccc550474d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject1/h1/7/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"e421cbe14676e5ccc550474d:24","filtered_window_id":"e421cbe14676e5ccc550474d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e421cbe14676e5ccc550474d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject1/h1/7/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"e421cbe14676e5ccc550474d:32","filtered_window_id":"e421cbe14676e5ccc550474d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e421cbe14676e5ccc550474d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[305,306,307,308,309,310,311,312],"take":"subject1/h1/7/cam4","frame_ids":[305,306,307,308,309,310,311,312]} +{"filtered_tile_id":"e421cbe14676e5ccc550474d:40","filtered_window_id":"e421cbe14676e5ccc550474d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e421cbe14676e5ccc550474d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject1/h1/7/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"e421cbe14676e5ccc550474d:48","filtered_window_id":"e421cbe14676e5ccc550474d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e421cbe14676e5ccc550474d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject1/h1/7/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"e421cbe14676e5ccc550474d:52","filtered_window_id":"e421cbe14676e5ccc550474d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e421cbe14676e5ccc550474d/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[325,326,327,328,329,330,331,332],"take":"subject1/h1/7/cam4","frame_ids":[325,326,327,328,329,330,331,332]} +{"filtered_tile_id":"e49fcf9fdf4f463c73f2f24c:0","filtered_window_id":"e49fcf9fdf4f463c73f2f24c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e49fcf9fdf4f463c73f2f24c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject1/k1/1/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"e49fcf9fdf4f463c73f2f24c:8","filtered_window_id":"e49fcf9fdf4f463c73f2f24c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e49fcf9fdf4f463c73f2f24c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject1/k1/1/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"e49fcf9fdf4f463c73f2f24c:16","filtered_window_id":"e49fcf9fdf4f463c73f2f24c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e49fcf9fdf4f463c73f2f24c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject1/k1/1/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"e49fcf9fdf4f463c73f2f24c:24","filtered_window_id":"e49fcf9fdf4f463c73f2f24c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e49fcf9fdf4f463c73f2f24c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject1/k1/1/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"e49fcf9fdf4f463c73f2f24c:32","filtered_window_id":"e49fcf9fdf4f463c73f2f24c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e49fcf9fdf4f463c73f2f24c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject1/k1/1/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"e49fcf9fdf4f463c73f2f24c:40","filtered_window_id":"e49fcf9fdf4f463c73f2f24c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e49fcf9fdf4f463c73f2f24c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject1/k1/1/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"e49fcf9fdf4f463c73f2f24c:48","filtered_window_id":"e49fcf9fdf4f463c73f2f24c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e49fcf9fdf4f463c73f2f24c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject1/k1/1/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"e49fcf9fdf4f463c73f2f24c:52","filtered_window_id":"e49fcf9fdf4f463c73f2f24c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e49fcf9fdf4f463c73f2f24c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[464,465,466,467,468,469,470,471],"take":"subject1/k1/1/cam4","frame_ids":[464,465,466,467,468,469,470,471]} +{"filtered_tile_id":"e4b2886b4a54c8432ceb197a:0","filtered_window_id":"e4b2886b4a54c8432ceb197a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e4b2886b4a54c8432ceb197a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[712,713,714,715,716,717,718,719],"take":"subject1/o2/3/cam4","frame_ids":[712,713,714,715,716,717,718,719]} +{"filtered_tile_id":"e4b2886b4a54c8432ceb197a:8","filtered_window_id":"e4b2886b4a54c8432ceb197a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e4b2886b4a54c8432ceb197a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[720,721,722,723,724,725,726,727],"take":"subject1/o2/3/cam4","frame_ids":[720,721,722,723,724,725,726,727]} +{"filtered_tile_id":"e4b2886b4a54c8432ceb197a:16","filtered_window_id":"e4b2886b4a54c8432ceb197a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e4b2886b4a54c8432ceb197a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[728,729,730,731,732,733,734,735],"take":"subject1/o2/3/cam4","frame_ids":[728,729,730,731,732,733,734,735]} +{"filtered_tile_id":"e4b2886b4a54c8432ceb197a:24","filtered_window_id":"e4b2886b4a54c8432ceb197a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e4b2886b4a54c8432ceb197a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[736,737,738,739,740,741,742,743],"take":"subject1/o2/3/cam4","frame_ids":[736,737,738,739,740,741,742,743]} +{"filtered_tile_id":"e4b2886b4a54c8432ceb197a:32","filtered_window_id":"e4b2886b4a54c8432ceb197a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e4b2886b4a54c8432ceb197a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[744,745,746,747,748,749,750,751],"take":"subject1/o2/3/cam4","frame_ids":[744,745,746,747,748,749,750,751]} +{"filtered_tile_id":"e4b2886b4a54c8432ceb197a:33","filtered_window_id":"e4b2886b4a54c8432ceb197a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e4b2886b4a54c8432ceb197a/native_gt.npz","filtered_start_offset":33,"expected_frame_ids":[745,746,747,748,749,750,751,752],"take":"subject1/o2/3/cam4","frame_ids":[745,746,747,748,749,750,751,752]} +{"filtered_tile_id":"e549f8fd65a8b0a21bbe454e:0","filtered_window_id":"e549f8fd65a8b0a21bbe454e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e549f8fd65a8b0a21bbe454e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject1/h2/0/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"e549f8fd65a8b0a21bbe454e:1","filtered_window_id":"e549f8fd65a8b0a21bbe454e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e549f8fd65a8b0a21bbe454e/native_gt.npz","filtered_start_offset":1,"expected_frame_ids":[338,339,340,341,342,343,344,345],"take":"subject1/h2/0/cam4","frame_ids":[338,339,340,341,342,343,344,345]} +{"filtered_tile_id":"e54e447f3568e9359b45ac57:0","filtered_window_id":"e54e447f3568e9359b45ac57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e54e447f3568e9359b45ac57/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[508,509,510,511,512,513,514,515],"take":"subject2/h2/4/cam4","frame_ids":[508,509,510,511,512,513,514,515]} +{"filtered_tile_id":"e54e447f3568e9359b45ac57:8","filtered_window_id":"e54e447f3568e9359b45ac57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e54e447f3568e9359b45ac57/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[516,517,518,519,520,521,522,523],"take":"subject2/h2/4/cam4","frame_ids":[516,517,518,519,520,521,522,523]} +{"filtered_tile_id":"e54e447f3568e9359b45ac57:16","filtered_window_id":"e54e447f3568e9359b45ac57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e54e447f3568e9359b45ac57/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[524,525,526,527,528,529,530,531],"take":"subject2/h2/4/cam4","frame_ids":[524,525,526,527,528,529,530,531]} +{"filtered_tile_id":"e54e447f3568e9359b45ac57:24","filtered_window_id":"e54e447f3568e9359b45ac57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e54e447f3568e9359b45ac57/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[532,533,534,535,536,537,538,539],"take":"subject2/h2/4/cam4","frame_ids":[532,533,534,535,536,537,538,539]} +{"filtered_tile_id":"e54e447f3568e9359b45ac57:32","filtered_window_id":"e54e447f3568e9359b45ac57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e54e447f3568e9359b45ac57/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[540,541,542,543,544,545,546,547],"take":"subject2/h2/4/cam4","frame_ids":[540,541,542,543,544,545,546,547]} +{"filtered_tile_id":"e54e447f3568e9359b45ac57:40","filtered_window_id":"e54e447f3568e9359b45ac57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e54e447f3568e9359b45ac57/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject2/h2/4/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"e54e447f3568e9359b45ac57:48","filtered_window_id":"e54e447f3568e9359b45ac57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e54e447f3568e9359b45ac57/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject2/h2/4/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"e54e447f3568e9359b45ac57:52","filtered_window_id":"e54e447f3568e9359b45ac57","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e54e447f3568e9359b45ac57/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[560,561,562,563,564,565,566,567],"take":"subject2/h2/4/cam4","frame_ids":[560,561,562,563,564,565,566,567]} +{"filtered_tile_id":"e56bd5750704e81a6c498e51:0","filtered_window_id":"e56bd5750704e81a6c498e51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e56bd5750704e81a6c498e51/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject1/h2/6/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"e56bd5750704e81a6c498e51:8","filtered_window_id":"e56bd5750704e81a6c498e51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e56bd5750704e81a6c498e51/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[486,487,488,489,490,491,492,493],"take":"subject1/h2/6/cam4","frame_ids":[486,487,488,489,490,491,492,493]} +{"filtered_tile_id":"e56bd5750704e81a6c498e51:16","filtered_window_id":"e56bd5750704e81a6c498e51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e56bd5750704e81a6c498e51/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[494,495,496,497,498,499,500,501],"take":"subject1/h2/6/cam4","frame_ids":[494,495,496,497,498,499,500,501]} +{"filtered_tile_id":"e56bd5750704e81a6c498e51:24","filtered_window_id":"e56bd5750704e81a6c498e51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e56bd5750704e81a6c498e51/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject1/h2/6/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"e56bd5750704e81a6c498e51:32","filtered_window_id":"e56bd5750704e81a6c498e51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e56bd5750704e81a6c498e51/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject1/h2/6/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"e56bd5750704e81a6c498e51:40","filtered_window_id":"e56bd5750704e81a6c498e51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e56bd5750704e81a6c498e51/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject1/h2/6/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"e56bd5750704e81a6c498e51:45","filtered_window_id":"e56bd5750704e81a6c498e51","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e56bd5750704e81a6c498e51/native_gt.npz","filtered_start_offset":45,"expected_frame_ids":[523,524,525,526,527,528,529,530],"take":"subject1/h2/6/cam4","frame_ids":[523,524,525,526,527,528,529,530]} +{"filtered_tile_id":"e59061cdbbc2f5e5f98fb1b5:0","filtered_window_id":"e59061cdbbc2f5e5f98fb1b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59061cdbbc2f5e5f98fb1b5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[106,107,108,109,110,111,112,113],"take":"subject3/h1/0/cam4","frame_ids":[106,107,108,109,110,111,112,113]} +{"filtered_tile_id":"e59061cdbbc2f5e5f98fb1b5:8","filtered_window_id":"e59061cdbbc2f5e5f98fb1b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59061cdbbc2f5e5f98fb1b5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject3/h1/0/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"e59061cdbbc2f5e5f98fb1b5:16","filtered_window_id":"e59061cdbbc2f5e5f98fb1b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59061cdbbc2f5e5f98fb1b5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject3/h1/0/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"e59061cdbbc2f5e5f98fb1b5:24","filtered_window_id":"e59061cdbbc2f5e5f98fb1b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59061cdbbc2f5e5f98fb1b5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject3/h1/0/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"e59061cdbbc2f5e5f98fb1b5:32","filtered_window_id":"e59061cdbbc2f5e5f98fb1b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59061cdbbc2f5e5f98fb1b5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject3/h1/0/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"e59061cdbbc2f5e5f98fb1b5:40","filtered_window_id":"e59061cdbbc2f5e5f98fb1b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59061cdbbc2f5e5f98fb1b5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject3/h1/0/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"e59061cdbbc2f5e5f98fb1b5:48","filtered_window_id":"e59061cdbbc2f5e5f98fb1b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59061cdbbc2f5e5f98fb1b5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject3/h1/0/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"e59061cdbbc2f5e5f98fb1b5:52","filtered_window_id":"e59061cdbbc2f5e5f98fb1b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59061cdbbc2f5e5f98fb1b5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[158,159,160,161,162,163,164,165],"take":"subject3/h1/0/cam4","frame_ids":[158,159,160,161,162,163,164,165]} +{"filtered_tile_id":"e59732e793139f0a34aedbc6:0","filtered_window_id":"e59732e793139f0a34aedbc6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59732e793139f0a34aedbc6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[178,179,180,181,182,183,184,185],"take":"subject2/h1/3/cam4","frame_ids":[178,179,180,181,182,183,184,185]} +{"filtered_tile_id":"e59732e793139f0a34aedbc6:8","filtered_window_id":"e59732e793139f0a34aedbc6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59732e793139f0a34aedbc6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[186,187,188,189,190,191,192,193],"take":"subject2/h1/3/cam4","frame_ids":[186,187,188,189,190,191,192,193]} +{"filtered_tile_id":"e59732e793139f0a34aedbc6:16","filtered_window_id":"e59732e793139f0a34aedbc6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59732e793139f0a34aedbc6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[194,195,196,197,198,199,200,201],"take":"subject2/h1/3/cam4","frame_ids":[194,195,196,197,198,199,200,201]} +{"filtered_tile_id":"e59732e793139f0a34aedbc6:24","filtered_window_id":"e59732e793139f0a34aedbc6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59732e793139f0a34aedbc6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[202,203,204,205,206,207,208,209],"take":"subject2/h1/3/cam4","frame_ids":[202,203,204,205,206,207,208,209]} +{"filtered_tile_id":"e59732e793139f0a34aedbc6:32","filtered_window_id":"e59732e793139f0a34aedbc6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59732e793139f0a34aedbc6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[210,211,212,213,214,215,216,217],"take":"subject2/h1/3/cam4","frame_ids":[210,211,212,213,214,215,216,217]} +{"filtered_tile_id":"e59732e793139f0a34aedbc6:40","filtered_window_id":"e59732e793139f0a34aedbc6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59732e793139f0a34aedbc6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[218,219,220,221,222,223,224,225],"take":"subject2/h1/3/cam4","frame_ids":[218,219,220,221,222,223,224,225]} +{"filtered_tile_id":"e59732e793139f0a34aedbc6:48","filtered_window_id":"e59732e793139f0a34aedbc6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59732e793139f0a34aedbc6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject2/h1/3/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"e59732e793139f0a34aedbc6:52","filtered_window_id":"e59732e793139f0a34aedbc6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e59732e793139f0a34aedbc6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[230,231,232,233,234,235,236,237],"take":"subject2/h1/3/cam4","frame_ids":[230,231,232,233,234,235,236,237]} +{"filtered_tile_id":"e5b5fa4ab691474f9fe4c084:0","filtered_window_id":"e5b5fa4ab691474f9fe4c084","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e5b5fa4ab691474f9fe4c084/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject1/k1/6/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"e5b5fa4ab691474f9fe4c084:8","filtered_window_id":"e5b5fa4ab691474f9fe4c084","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e5b5fa4ab691474f9fe4c084/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[77,78,79,80,81,82,83,84],"take":"subject1/k1/6/cam4","frame_ids":[77,78,79,80,81,82,83,84]} +{"filtered_tile_id":"e5b5fa4ab691474f9fe4c084:16","filtered_window_id":"e5b5fa4ab691474f9fe4c084","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e5b5fa4ab691474f9fe4c084/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[85,86,87,88,89,90,91,92],"take":"subject1/k1/6/cam4","frame_ids":[85,86,87,88,89,90,91,92]} +{"filtered_tile_id":"e5b5fa4ab691474f9fe4c084:24","filtered_window_id":"e5b5fa4ab691474f9fe4c084","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e5b5fa4ab691474f9fe4c084/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[93,94,95,96,97,98,99,100],"take":"subject1/k1/6/cam4","frame_ids":[93,94,95,96,97,98,99,100]} +{"filtered_tile_id":"e5b5fa4ab691474f9fe4c084:32","filtered_window_id":"e5b5fa4ab691474f9fe4c084","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e5b5fa4ab691474f9fe4c084/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[101,102,103,104,105,106,107,108],"take":"subject1/k1/6/cam4","frame_ids":[101,102,103,104,105,106,107,108]} +{"filtered_tile_id":"e5b5fa4ab691474f9fe4c084:33","filtered_window_id":"e5b5fa4ab691474f9fe4c084","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e5b5fa4ab691474f9fe4c084/native_gt.npz","filtered_start_offset":33,"expected_frame_ids":[102,103,104,105,106,107,108,109],"take":"subject1/k1/6/cam4","frame_ids":[102,103,104,105,106,107,108,109]} +{"filtered_tile_id":"e60d01ecb09fbcb3f48e33a6:0","filtered_window_id":"e60d01ecb09fbcb3f48e33a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d01ecb09fbcb3f48e33a6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject1/h2/6/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"e60d01ecb09fbcb3f48e33a6:8","filtered_window_id":"e60d01ecb09fbcb3f48e33a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d01ecb09fbcb3f48e33a6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject1/h2/6/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"e60d01ecb09fbcb3f48e33a6:16","filtered_window_id":"e60d01ecb09fbcb3f48e33a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d01ecb09fbcb3f48e33a6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject1/h2/6/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"e60d01ecb09fbcb3f48e33a6:24","filtered_window_id":"e60d01ecb09fbcb3f48e33a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d01ecb09fbcb3f48e33a6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject1/h2/6/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"e60d01ecb09fbcb3f48e33a6:32","filtered_window_id":"e60d01ecb09fbcb3f48e33a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d01ecb09fbcb3f48e33a6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject1/h2/6/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"e60d01ecb09fbcb3f48e33a6:40","filtered_window_id":"e60d01ecb09fbcb3f48e33a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d01ecb09fbcb3f48e33a6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[289,290,291,292,293,294,295,296],"take":"subject1/h2/6/cam4","frame_ids":[289,290,291,292,293,294,295,296]} +{"filtered_tile_id":"e60d01ecb09fbcb3f48e33a6:48","filtered_window_id":"e60d01ecb09fbcb3f48e33a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d01ecb09fbcb3f48e33a6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject1/h2/6/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"e60d01ecb09fbcb3f48e33a6:52","filtered_window_id":"e60d01ecb09fbcb3f48e33a6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d01ecb09fbcb3f48e33a6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[301,302,303,304,305,306,307,308],"take":"subject1/h2/6/cam4","frame_ids":[301,302,303,304,305,306,307,308]} +{"filtered_tile_id":"e60d780ff35b86a82e4b816e:0","filtered_window_id":"e60d780ff35b86a82e4b816e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d780ff35b86a82e4b816e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[119,120,121,122,123,124,125,126],"take":"subject1/h2/5/cam4","frame_ids":[119,120,121,122,123,124,125,126]} +{"filtered_tile_id":"e60d780ff35b86a82e4b816e:8","filtered_window_id":"e60d780ff35b86a82e4b816e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d780ff35b86a82e4b816e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject1/h2/5/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"e60d780ff35b86a82e4b816e:16","filtered_window_id":"e60d780ff35b86a82e4b816e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d780ff35b86a82e4b816e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[135,136,137,138,139,140,141,142],"take":"subject1/h2/5/cam4","frame_ids":[135,136,137,138,139,140,141,142]} +{"filtered_tile_id":"e60d780ff35b86a82e4b816e:24","filtered_window_id":"e60d780ff35b86a82e4b816e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d780ff35b86a82e4b816e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[143,144,145,146,147,148,149,150],"take":"subject1/h2/5/cam4","frame_ids":[143,144,145,146,147,148,149,150]} +{"filtered_tile_id":"e60d780ff35b86a82e4b816e:26","filtered_window_id":"e60d780ff35b86a82e4b816e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e60d780ff35b86a82e4b816e/native_gt.npz","filtered_start_offset":26,"expected_frame_ids":[145,146,147,148,149,150,151,152],"take":"subject1/h2/5/cam4","frame_ids":[145,146,147,148,149,150,151,152]} +{"filtered_tile_id":"e6ef407a6396117ffdabd549:0","filtered_window_id":"e6ef407a6396117ffdabd549","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e6ef407a6396117ffdabd549/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[283,284,285,286,287,288,289,290],"take":"subject1/o1/1/cam4","frame_ids":[283,284,285,286,287,288,289,290]} +{"filtered_tile_id":"e6ef407a6396117ffdabd549:8","filtered_window_id":"e6ef407a6396117ffdabd549","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e6ef407a6396117ffdabd549/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[291,292,293,294,295,296,297,298],"take":"subject1/o1/1/cam4","frame_ids":[291,292,293,294,295,296,297,298]} +{"filtered_tile_id":"e6ef407a6396117ffdabd549:10","filtered_window_id":"e6ef407a6396117ffdabd549","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e6ef407a6396117ffdabd549/native_gt.npz","filtered_start_offset":10,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject1/o1/1/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"e71ebc58833d55c4f42df700:0","filtered_window_id":"e71ebc58833d55c4f42df700","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e71ebc58833d55c4f42df700/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[17,18,19,20,21,22,23,24],"take":"subject3/h1/2/cam4","frame_ids":[17,18,19,20,21,22,23,24]} +{"filtered_tile_id":"e71ebc58833d55c4f42df700:8","filtered_window_id":"e71ebc58833d55c4f42df700","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e71ebc58833d55c4f42df700/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[25,26,27,28,29,30,31,32],"take":"subject3/h1/2/cam4","frame_ids":[25,26,27,28,29,30,31,32]} +{"filtered_tile_id":"e71ebc58833d55c4f42df700:16","filtered_window_id":"e71ebc58833d55c4f42df700","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e71ebc58833d55c4f42df700/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[33,34,35,36,37,38,39,40],"take":"subject3/h1/2/cam4","frame_ids":[33,34,35,36,37,38,39,40]} +{"filtered_tile_id":"e71ebc58833d55c4f42df700:24","filtered_window_id":"e71ebc58833d55c4f42df700","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e71ebc58833d55c4f42df700/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[41,42,43,44,45,46,47,48],"take":"subject3/h1/2/cam4","frame_ids":[41,42,43,44,45,46,47,48]} +{"filtered_tile_id":"e71ebc58833d55c4f42df700:32","filtered_window_id":"e71ebc58833d55c4f42df700","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e71ebc58833d55c4f42df700/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[49,50,51,52,53,54,55,56],"take":"subject3/h1/2/cam4","frame_ids":[49,50,51,52,53,54,55,56]} +{"filtered_tile_id":"e71ebc58833d55c4f42df700:40","filtered_window_id":"e71ebc58833d55c4f42df700","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e71ebc58833d55c4f42df700/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[57,58,59,60,61,62,63,64],"take":"subject3/h1/2/cam4","frame_ids":[57,58,59,60,61,62,63,64]} +{"filtered_tile_id":"e71ebc58833d55c4f42df700:48","filtered_window_id":"e71ebc58833d55c4f42df700","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e71ebc58833d55c4f42df700/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[65,66,67,68,69,70,71,72],"take":"subject3/h1/2/cam4","frame_ids":[65,66,67,68,69,70,71,72]} +{"filtered_tile_id":"e71ebc58833d55c4f42df700:52","filtered_window_id":"e71ebc58833d55c4f42df700","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e71ebc58833d55c4f42df700/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject3/h1/2/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"e73a5838ce5d8e778a25d6f1:0","filtered_window_id":"e73a5838ce5d8e778a25d6f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e73a5838ce5d8e778a25d6f1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject3/k1/1/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"e73a5838ce5d8e778a25d6f1:8","filtered_window_id":"e73a5838ce5d8e778a25d6f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e73a5838ce5d8e778a25d6f1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject3/k1/1/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"e73a5838ce5d8e778a25d6f1:16","filtered_window_id":"e73a5838ce5d8e778a25d6f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e73a5838ce5d8e778a25d6f1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[156,157,158,159,160,161,162,163],"take":"subject3/k1/1/cam4","frame_ids":[156,157,158,159,160,161,162,163]} +{"filtered_tile_id":"e73a5838ce5d8e778a25d6f1:24","filtered_window_id":"e73a5838ce5d8e778a25d6f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e73a5838ce5d8e778a25d6f1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[164,165,166,167,168,169,170,171],"take":"subject3/k1/1/cam4","frame_ids":[164,165,166,167,168,169,170,171]} +{"filtered_tile_id":"e73a5838ce5d8e778a25d6f1:32","filtered_window_id":"e73a5838ce5d8e778a25d6f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e73a5838ce5d8e778a25d6f1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject3/k1/1/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"e73a5838ce5d8e778a25d6f1:40","filtered_window_id":"e73a5838ce5d8e778a25d6f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e73a5838ce5d8e778a25d6f1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject3/k1/1/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"e73a5838ce5d8e778a25d6f1:48","filtered_window_id":"e73a5838ce5d8e778a25d6f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e73a5838ce5d8e778a25d6f1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[188,189,190,191,192,193,194,195],"take":"subject3/k1/1/cam4","frame_ids":[188,189,190,191,192,193,194,195]} +{"filtered_tile_id":"e73a5838ce5d8e778a25d6f1:52","filtered_window_id":"e73a5838ce5d8e778a25d6f1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e73a5838ce5d8e778a25d6f1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[192,193,194,195,196,197,198,199],"take":"subject3/k1/1/cam4","frame_ids":[192,193,194,195,196,197,198,199]} +{"filtered_tile_id":"e773db014e629b9180524e88:0","filtered_window_id":"e773db014e629b9180524e88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e773db014e629b9180524e88/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject1/o1/5/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"e773db014e629b9180524e88:8","filtered_window_id":"e773db014e629b9180524e88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e773db014e629b9180524e88/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject1/o1/5/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"e773db014e629b9180524e88:16","filtered_window_id":"e773db014e629b9180524e88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e773db014e629b9180524e88/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject1/o1/5/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"e773db014e629b9180524e88:24","filtered_window_id":"e773db014e629b9180524e88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e773db014e629b9180524e88/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject1/o1/5/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"e773db014e629b9180524e88:32","filtered_window_id":"e773db014e629b9180524e88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e773db014e629b9180524e88/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject1/o1/5/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"e773db014e629b9180524e88:36","filtered_window_id":"e773db014e629b9180524e88","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e773db014e629b9180524e88/native_gt.npz","filtered_start_offset":36,"expected_frame_ids":[103,104,105,106,107,108,109,110],"take":"subject1/o1/5/cam4","frame_ids":[103,104,105,106,107,108,109,110]} +{"filtered_tile_id":"e7a5e4a2b11fc17631ebfae3:0","filtered_window_id":"e7a5e4a2b11fc17631ebfae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7a5e4a2b11fc17631ebfae3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject1/o2/4/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"e7a5e4a2b11fc17631ebfae3:8","filtered_window_id":"e7a5e4a2b11fc17631ebfae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7a5e4a2b11fc17631ebfae3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[255,256,257,258,259,260,261,262],"take":"subject1/o2/4/cam4","frame_ids":[255,256,257,258,259,260,261,262]} +{"filtered_tile_id":"e7a5e4a2b11fc17631ebfae3:16","filtered_window_id":"e7a5e4a2b11fc17631ebfae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7a5e4a2b11fc17631ebfae3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[263,264,265,266,267,268,269,270],"take":"subject1/o2/4/cam4","frame_ids":[263,264,265,266,267,268,269,270]} +{"filtered_tile_id":"e7a5e4a2b11fc17631ebfae3:24","filtered_window_id":"e7a5e4a2b11fc17631ebfae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7a5e4a2b11fc17631ebfae3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[271,272,273,274,275,276,277,278],"take":"subject1/o2/4/cam4","frame_ids":[271,272,273,274,275,276,277,278]} +{"filtered_tile_id":"e7a5e4a2b11fc17631ebfae3:32","filtered_window_id":"e7a5e4a2b11fc17631ebfae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7a5e4a2b11fc17631ebfae3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[279,280,281,282,283,284,285,286],"take":"subject1/o2/4/cam4","frame_ids":[279,280,281,282,283,284,285,286]} +{"filtered_tile_id":"e7a5e4a2b11fc17631ebfae3:40","filtered_window_id":"e7a5e4a2b11fc17631ebfae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7a5e4a2b11fc17631ebfae3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[287,288,289,290,291,292,293,294],"take":"subject1/o2/4/cam4","frame_ids":[287,288,289,290,291,292,293,294]} +{"filtered_tile_id":"e7a5e4a2b11fc17631ebfae3:48","filtered_window_id":"e7a5e4a2b11fc17631ebfae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7a5e4a2b11fc17631ebfae3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[295,296,297,298,299,300,301,302],"take":"subject1/o2/4/cam4","frame_ids":[295,296,297,298,299,300,301,302]} +{"filtered_tile_id":"e7a5e4a2b11fc17631ebfae3:52","filtered_window_id":"e7a5e4a2b11fc17631ebfae3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7a5e4a2b11fc17631ebfae3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[299,300,301,302,303,304,305,306],"take":"subject1/o2/4/cam4","frame_ids":[299,300,301,302,303,304,305,306]} +{"filtered_tile_id":"e7f2a0973e090b447aa1a77d:0","filtered_window_id":"e7f2a0973e090b447aa1a77d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7f2a0973e090b447aa1a77d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[239,240,241,242,243,244,245,246],"take":"subject1/o2/2/cam4","frame_ids":[239,240,241,242,243,244,245,246]} +{"filtered_tile_id":"e7f2a0973e090b447aa1a77d:8","filtered_window_id":"e7f2a0973e090b447aa1a77d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7f2a0973e090b447aa1a77d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[247,248,249,250,251,252,253,254],"take":"subject1/o2/2/cam4","frame_ids":[247,248,249,250,251,252,253,254]} +{"filtered_tile_id":"e7f2a0973e090b447aa1a77d:16","filtered_window_id":"e7f2a0973e090b447aa1a77d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7f2a0973e090b447aa1a77d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[255,256,257,258,259,260,261,262],"take":"subject1/o2/2/cam4","frame_ids":[255,256,257,258,259,260,261,262]} +{"filtered_tile_id":"e7f2a0973e090b447aa1a77d:21","filtered_window_id":"e7f2a0973e090b447aa1a77d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e7f2a0973e090b447aa1a77d/native_gt.npz","filtered_start_offset":21,"expected_frame_ids":[260,261,262,263,264,265,266,267],"take":"subject1/o2/2/cam4","frame_ids":[260,261,262,263,264,265,266,267]} +{"filtered_tile_id":"e85b1e03ebc52debaffd8a16:0","filtered_window_id":"e85b1e03ebc52debaffd8a16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e85b1e03ebc52debaffd8a16/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[576,577,578,579,580,581,582,583],"take":"subject3/h2/3/cam4","frame_ids":[576,577,578,579,580,581,582,583]} +{"filtered_tile_id":"e85b1e03ebc52debaffd8a16:8","filtered_window_id":"e85b1e03ebc52debaffd8a16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e85b1e03ebc52debaffd8a16/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[584,585,586,587,588,589,590,591],"take":"subject3/h2/3/cam4","frame_ids":[584,585,586,587,588,589,590,591]} +{"filtered_tile_id":"e85b1e03ebc52debaffd8a16:16","filtered_window_id":"e85b1e03ebc52debaffd8a16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e85b1e03ebc52debaffd8a16/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[592,593,594,595,596,597,598,599],"take":"subject3/h2/3/cam4","frame_ids":[592,593,594,595,596,597,598,599]} +{"filtered_tile_id":"e85b1e03ebc52debaffd8a16:24","filtered_window_id":"e85b1e03ebc52debaffd8a16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e85b1e03ebc52debaffd8a16/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[600,601,602,603,604,605,606,607],"take":"subject3/h2/3/cam4","frame_ids":[600,601,602,603,604,605,606,607]} +{"filtered_tile_id":"e85b1e03ebc52debaffd8a16:32","filtered_window_id":"e85b1e03ebc52debaffd8a16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e85b1e03ebc52debaffd8a16/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[608,609,610,611,612,613,614,615],"take":"subject3/h2/3/cam4","frame_ids":[608,609,610,611,612,613,614,615]} +{"filtered_tile_id":"e85b1e03ebc52debaffd8a16:40","filtered_window_id":"e85b1e03ebc52debaffd8a16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e85b1e03ebc52debaffd8a16/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[616,617,618,619,620,621,622,623],"take":"subject3/h2/3/cam4","frame_ids":[616,617,618,619,620,621,622,623]} +{"filtered_tile_id":"e85b1e03ebc52debaffd8a16:48","filtered_window_id":"e85b1e03ebc52debaffd8a16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e85b1e03ebc52debaffd8a16/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[624,625,626,627,628,629,630,631],"take":"subject3/h2/3/cam4","frame_ids":[624,625,626,627,628,629,630,631]} +{"filtered_tile_id":"e85b1e03ebc52debaffd8a16:52","filtered_window_id":"e85b1e03ebc52debaffd8a16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e85b1e03ebc52debaffd8a16/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[628,629,630,631,632,633,634,635],"take":"subject3/h2/3/cam4","frame_ids":[628,629,630,631,632,633,634,635]} +{"filtered_tile_id":"e873ccb12bfb9642b3886839:0","filtered_window_id":"e873ccb12bfb9642b3886839","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e873ccb12bfb9642b3886839/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[849,850,851,852,853,854,855,856],"take":"subject2/o1/1/cam4","frame_ids":[849,850,851,852,853,854,855,856]} +{"filtered_tile_id":"e873ccb12bfb9642b3886839:8","filtered_window_id":"e873ccb12bfb9642b3886839","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e873ccb12bfb9642b3886839/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[857,858,859,860,861,862,863,864],"take":"subject2/o1/1/cam4","frame_ids":[857,858,859,860,861,862,863,864]} +{"filtered_tile_id":"e873ccb12bfb9642b3886839:16","filtered_window_id":"e873ccb12bfb9642b3886839","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e873ccb12bfb9642b3886839/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[865,866,867,868,869,870,871,872],"take":"subject2/o1/1/cam4","frame_ids":[865,866,867,868,869,870,871,872]} +{"filtered_tile_id":"e873ccb12bfb9642b3886839:24","filtered_window_id":"e873ccb12bfb9642b3886839","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e873ccb12bfb9642b3886839/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[873,874,875,876,877,878,879,880],"take":"subject2/o1/1/cam4","frame_ids":[873,874,875,876,877,878,879,880]} +{"filtered_tile_id":"e873ccb12bfb9642b3886839:32","filtered_window_id":"e873ccb12bfb9642b3886839","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e873ccb12bfb9642b3886839/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[881,882,883,884,885,886,887,888],"take":"subject2/o1/1/cam4","frame_ids":[881,882,883,884,885,886,887,888]} +{"filtered_tile_id":"e873ccb12bfb9642b3886839:40","filtered_window_id":"e873ccb12bfb9642b3886839","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e873ccb12bfb9642b3886839/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[889,890,891,892,893,894,895,896],"take":"subject2/o1/1/cam4","frame_ids":[889,890,891,892,893,894,895,896]} +{"filtered_tile_id":"e873ccb12bfb9642b3886839:48","filtered_window_id":"e873ccb12bfb9642b3886839","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e873ccb12bfb9642b3886839/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[897,898,899,900,901,902,903,904],"take":"subject2/o1/1/cam4","frame_ids":[897,898,899,900,901,902,903,904]} +{"filtered_tile_id":"e873ccb12bfb9642b3886839:52","filtered_window_id":"e873ccb12bfb9642b3886839","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e873ccb12bfb9642b3886839/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[901,902,903,904,905,906,907,908],"take":"subject2/o1/1/cam4","frame_ids":[901,902,903,904,905,906,907,908]} +{"filtered_tile_id":"e8f0e94f2420f14ceac5f4c8:0","filtered_window_id":"e8f0e94f2420f14ceac5f4c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e8f0e94f2420f14ceac5f4c8/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject1/o2/5/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"e8f0e94f2420f14ceac5f4c8:8","filtered_window_id":"e8f0e94f2420f14ceac5f4c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e8f0e94f2420f14ceac5f4c8/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject1/o2/5/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"e8f0e94f2420f14ceac5f4c8:16","filtered_window_id":"e8f0e94f2420f14ceac5f4c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e8f0e94f2420f14ceac5f4c8/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject1/o2/5/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"e8f0e94f2420f14ceac5f4c8:24","filtered_window_id":"e8f0e94f2420f14ceac5f4c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e8f0e94f2420f14ceac5f4c8/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject1/o2/5/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"e8f0e94f2420f14ceac5f4c8:32","filtered_window_id":"e8f0e94f2420f14ceac5f4c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e8f0e94f2420f14ceac5f4c8/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject1/o2/5/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"e8f0e94f2420f14ceac5f4c8:40","filtered_window_id":"e8f0e94f2420f14ceac5f4c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e8f0e94f2420f14ceac5f4c8/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject1/o2/5/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"e8f0e94f2420f14ceac5f4c8:48","filtered_window_id":"e8f0e94f2420f14ceac5f4c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e8f0e94f2420f14ceac5f4c8/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject1/o2/5/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"e8f0e94f2420f14ceac5f4c8:52","filtered_window_id":"e8f0e94f2420f14ceac5f4c8","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e8f0e94f2420f14ceac5f4c8/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[151,152,153,154,155,156,157,158],"take":"subject1/o2/5/cam4","frame_ids":[151,152,153,154,155,156,157,158]} +{"filtered_tile_id":"e93dbc2240c40d1f4725b0b7:0","filtered_window_id":"e93dbc2240c40d1f4725b0b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e93dbc2240c40d1f4725b0b7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[197,198,199,200,201,202,203,204],"take":"subject2/h1/4/cam4","frame_ids":[197,198,199,200,201,202,203,204]} +{"filtered_tile_id":"e93dbc2240c40d1f4725b0b7:8","filtered_window_id":"e93dbc2240c40d1f4725b0b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e93dbc2240c40d1f4725b0b7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[205,206,207,208,209,210,211,212],"take":"subject2/h1/4/cam4","frame_ids":[205,206,207,208,209,210,211,212]} +{"filtered_tile_id":"e93dbc2240c40d1f4725b0b7:16","filtered_window_id":"e93dbc2240c40d1f4725b0b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e93dbc2240c40d1f4725b0b7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[213,214,215,216,217,218,219,220],"take":"subject2/h1/4/cam4","frame_ids":[213,214,215,216,217,218,219,220]} +{"filtered_tile_id":"e93dbc2240c40d1f4725b0b7:24","filtered_window_id":"e93dbc2240c40d1f4725b0b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e93dbc2240c40d1f4725b0b7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject2/h1/4/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"e93dbc2240c40d1f4725b0b7:29","filtered_window_id":"e93dbc2240c40d1f4725b0b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e93dbc2240c40d1f4725b0b7/native_gt.npz","filtered_start_offset":29,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject2/h1/4/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"e96e6ea146389eac798cdbef:0","filtered_window_id":"e96e6ea146389eac798cdbef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e96e6ea146389eac798cdbef/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/h2/1/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"e96e6ea146389eac798cdbef:8","filtered_window_id":"e96e6ea146389eac798cdbef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e96e6ea146389eac798cdbef/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject2/h2/1/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"e96e6ea146389eac798cdbef:16","filtered_window_id":"e96e6ea146389eac798cdbef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e96e6ea146389eac798cdbef/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject2/h2/1/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"e96e6ea146389eac798cdbef:24","filtered_window_id":"e96e6ea146389eac798cdbef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e96e6ea146389eac798cdbef/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject2/h2/1/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"e96e6ea146389eac798cdbef:32","filtered_window_id":"e96e6ea146389eac798cdbef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e96e6ea146389eac798cdbef/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject2/h2/1/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"e96e6ea146389eac798cdbef:40","filtered_window_id":"e96e6ea146389eac798cdbef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e96e6ea146389eac798cdbef/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject2/h2/1/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"e96e6ea146389eac798cdbef:48","filtered_window_id":"e96e6ea146389eac798cdbef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e96e6ea146389eac798cdbef/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject2/h2/1/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"e96e6ea146389eac798cdbef:52","filtered_window_id":"e96e6ea146389eac798cdbef","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e96e6ea146389eac798cdbef/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[112,113,114,115,116,117,118,119],"take":"subject2/h2/1/cam4","frame_ids":[112,113,114,115,116,117,118,119]} +{"filtered_tile_id":"e9d571b1f1abb92a14f2b6a5:0","filtered_window_id":"e9d571b1f1abb92a14f2b6a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e9d571b1f1abb92a14f2b6a5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[320,321,322,323,324,325,326,327],"take":"subject3/h1/7/cam4","frame_ids":[320,321,322,323,324,325,326,327]} +{"filtered_tile_id":"e9d571b1f1abb92a14f2b6a5:8","filtered_window_id":"e9d571b1f1abb92a14f2b6a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e9d571b1f1abb92a14f2b6a5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[328,329,330,331,332,333,334,335],"take":"subject3/h1/7/cam4","frame_ids":[328,329,330,331,332,333,334,335]} +{"filtered_tile_id":"e9d571b1f1abb92a14f2b6a5:16","filtered_window_id":"e9d571b1f1abb92a14f2b6a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e9d571b1f1abb92a14f2b6a5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[336,337,338,339,340,341,342,343],"take":"subject3/h1/7/cam4","frame_ids":[336,337,338,339,340,341,342,343]} +{"filtered_tile_id":"e9d571b1f1abb92a14f2b6a5:24","filtered_window_id":"e9d571b1f1abb92a14f2b6a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e9d571b1f1abb92a14f2b6a5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[344,345,346,347,348,349,350,351],"take":"subject3/h1/7/cam4","frame_ids":[344,345,346,347,348,349,350,351]} +{"filtered_tile_id":"e9d571b1f1abb92a14f2b6a5:32","filtered_window_id":"e9d571b1f1abb92a14f2b6a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e9d571b1f1abb92a14f2b6a5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject3/h1/7/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"e9d571b1f1abb92a14f2b6a5:40","filtered_window_id":"e9d571b1f1abb92a14f2b6a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e9d571b1f1abb92a14f2b6a5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[360,361,362,363,364,365,366,367],"take":"subject3/h1/7/cam4","frame_ids":[360,361,362,363,364,365,366,367]} +{"filtered_tile_id":"e9d571b1f1abb92a14f2b6a5:48","filtered_window_id":"e9d571b1f1abb92a14f2b6a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e9d571b1f1abb92a14f2b6a5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[368,369,370,371,372,373,374,375],"take":"subject3/h1/7/cam4","frame_ids":[368,369,370,371,372,373,374,375]} +{"filtered_tile_id":"e9d571b1f1abb92a14f2b6a5:52","filtered_window_id":"e9d571b1f1abb92a14f2b6a5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/e9d571b1f1abb92a14f2b6a5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[372,373,374,375,376,377,378,379],"take":"subject3/h1/7/cam4","frame_ids":[372,373,374,375,376,377,378,379]} +{"filtered_tile_id":"ea3a247f0afebe96a1a5830c:0","filtered_window_id":"ea3a247f0afebe96a1a5830c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ea3a247f0afebe96a1a5830c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject2/h1/7/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"ea3a247f0afebe96a1a5830c:8","filtered_window_id":"ea3a247f0afebe96a1a5830c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ea3a247f0afebe96a1a5830c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject2/h1/7/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"ea3a247f0afebe96a1a5830c:16","filtered_window_id":"ea3a247f0afebe96a1a5830c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ea3a247f0afebe96a1a5830c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject2/h1/7/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"ea3a247f0afebe96a1a5830c:24","filtered_window_id":"ea3a247f0afebe96a1a5830c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ea3a247f0afebe96a1a5830c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[274,275,276,277,278,279,280,281],"take":"subject2/h1/7/cam4","frame_ids":[274,275,276,277,278,279,280,281]} +{"filtered_tile_id":"ea3a247f0afebe96a1a5830c:32","filtered_window_id":"ea3a247f0afebe96a1a5830c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ea3a247f0afebe96a1a5830c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject2/h1/7/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"ea3a247f0afebe96a1a5830c:40","filtered_window_id":"ea3a247f0afebe96a1a5830c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ea3a247f0afebe96a1a5830c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[290,291,292,293,294,295,296,297],"take":"subject2/h1/7/cam4","frame_ids":[290,291,292,293,294,295,296,297]} +{"filtered_tile_id":"ea3a247f0afebe96a1a5830c:48","filtered_window_id":"ea3a247f0afebe96a1a5830c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ea3a247f0afebe96a1a5830c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject2/h1/7/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"ea3a247f0afebe96a1a5830c:52","filtered_window_id":"ea3a247f0afebe96a1a5830c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ea3a247f0afebe96a1a5830c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[302,303,304,305,306,307,308,309],"take":"subject2/h1/7/cam4","frame_ids":[302,303,304,305,306,307,308,309]} +{"filtered_tile_id":"eaa4c2337049613a631783e6:0","filtered_window_id":"eaa4c2337049613a631783e6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eaa4c2337049613a631783e6/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[300,301,302,303,304,305,306,307],"take":"subject1/k1/5/cam4","frame_ids":[300,301,302,303,304,305,306,307]} +{"filtered_tile_id":"eaa4c2337049613a631783e6:8","filtered_window_id":"eaa4c2337049613a631783e6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eaa4c2337049613a631783e6/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject1/k1/5/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"eaa4c2337049613a631783e6:16","filtered_window_id":"eaa4c2337049613a631783e6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eaa4c2337049613a631783e6/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[316,317,318,319,320,321,322,323],"take":"subject1/k1/5/cam4","frame_ids":[316,317,318,319,320,321,322,323]} +{"filtered_tile_id":"eaa4c2337049613a631783e6:24","filtered_window_id":"eaa4c2337049613a631783e6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eaa4c2337049613a631783e6/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject1/k1/5/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"eaa4c2337049613a631783e6:32","filtered_window_id":"eaa4c2337049613a631783e6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eaa4c2337049613a631783e6/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject1/k1/5/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"eaa4c2337049613a631783e6:40","filtered_window_id":"eaa4c2337049613a631783e6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eaa4c2337049613a631783e6/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[340,341,342,343,344,345,346,347],"take":"subject1/k1/5/cam4","frame_ids":[340,341,342,343,344,345,346,347]} +{"filtered_tile_id":"eaa4c2337049613a631783e6:48","filtered_window_id":"eaa4c2337049613a631783e6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eaa4c2337049613a631783e6/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[348,349,350,351,352,353,354,355],"take":"subject1/k1/5/cam4","frame_ids":[348,349,350,351,352,353,354,355]} +{"filtered_tile_id":"eaa4c2337049613a631783e6:52","filtered_window_id":"eaa4c2337049613a631783e6","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eaa4c2337049613a631783e6/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[352,353,354,355,356,357,358,359],"take":"subject1/k1/5/cam4","frame_ids":[352,353,354,355,356,357,358,359]} +{"filtered_tile_id":"eab7f2a32e15a7431f8882ca:0","filtered_window_id":"eab7f2a32e15a7431f8882ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eab7f2a32e15a7431f8882ca/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/h1/4/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"eab7f2a32e15a7431f8882ca:7","filtered_window_id":"eab7f2a32e15a7431f8882ca","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eab7f2a32e15a7431f8882ca/native_gt.npz","filtered_start_offset":7,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject2/h1/4/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"eb5b0d8e9652b7cd73786cae:0","filtered_window_id":"eb5b0d8e9652b7cd73786cae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eb5b0d8e9652b7cd73786cae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[18,19,20,21,22,23,24,25],"take":"subject3/k1/0/cam4","frame_ids":[18,19,20,21,22,23,24,25]} +{"filtered_tile_id":"eb5b0d8e9652b7cd73786cae:8","filtered_window_id":"eb5b0d8e9652b7cd73786cae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eb5b0d8e9652b7cd73786cae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[26,27,28,29,30,31,32,33],"take":"subject3/k1/0/cam4","frame_ids":[26,27,28,29,30,31,32,33]} +{"filtered_tile_id":"eb5b0d8e9652b7cd73786cae:16","filtered_window_id":"eb5b0d8e9652b7cd73786cae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eb5b0d8e9652b7cd73786cae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[34,35,36,37,38,39,40,41],"take":"subject3/k1/0/cam4","frame_ids":[34,35,36,37,38,39,40,41]} +{"filtered_tile_id":"eb5b0d8e9652b7cd73786cae:24","filtered_window_id":"eb5b0d8e9652b7cd73786cae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eb5b0d8e9652b7cd73786cae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[42,43,44,45,46,47,48,49],"take":"subject3/k1/0/cam4","frame_ids":[42,43,44,45,46,47,48,49]} +{"filtered_tile_id":"eb5b0d8e9652b7cd73786cae:32","filtered_window_id":"eb5b0d8e9652b7cd73786cae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eb5b0d8e9652b7cd73786cae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[50,51,52,53,54,55,56,57],"take":"subject3/k1/0/cam4","frame_ids":[50,51,52,53,54,55,56,57]} +{"filtered_tile_id":"eb5b0d8e9652b7cd73786cae:40","filtered_window_id":"eb5b0d8e9652b7cd73786cae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eb5b0d8e9652b7cd73786cae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[58,59,60,61,62,63,64,65],"take":"subject3/k1/0/cam4","frame_ids":[58,59,60,61,62,63,64,65]} +{"filtered_tile_id":"eb5b0d8e9652b7cd73786cae:48","filtered_window_id":"eb5b0d8e9652b7cd73786cae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eb5b0d8e9652b7cd73786cae/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[66,67,68,69,70,71,72,73],"take":"subject3/k1/0/cam4","frame_ids":[66,67,68,69,70,71,72,73]} +{"filtered_tile_id":"eb5b0d8e9652b7cd73786cae:52","filtered_window_id":"eb5b0d8e9652b7cd73786cae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eb5b0d8e9652b7cd73786cae/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[70,71,72,73,74,75,76,77],"take":"subject3/k1/0/cam4","frame_ids":[70,71,72,73,74,75,76,77]} +{"filtered_tile_id":"ebe4342a5e53e8106e834d69:0","filtered_window_id":"ebe4342a5e53e8106e834d69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebe4342a5e53e8106e834d69/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject2/o2/6/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"ebe4342a5e53e8106e834d69:8","filtered_window_id":"ebe4342a5e53e8106e834d69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebe4342a5e53e8106e834d69/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject2/o2/6/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"ebe4342a5e53e8106e834d69:16","filtered_window_id":"ebe4342a5e53e8106e834d69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebe4342a5e53e8106e834d69/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject2/o2/6/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"ebe4342a5e53e8106e834d69:24","filtered_window_id":"ebe4342a5e53e8106e834d69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebe4342a5e53e8106e834d69/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject2/o2/6/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"ebe4342a5e53e8106e834d69:27","filtered_window_id":"ebe4342a5e53e8106e834d69","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebe4342a5e53e8106e834d69/native_gt.npz","filtered_start_offset":27,"expected_frame_ids":[95,96,97,98,99,100,101,102],"take":"subject2/o2/6/cam4","frame_ids":[95,96,97,98,99,100,101,102]} +{"filtered_tile_id":"ebf1ba1702c3d62182b08e66:0","filtered_window_id":"ebf1ba1702c3d62182b08e66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebf1ba1702c3d62182b08e66/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h2/0/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"ebf1ba1702c3d62182b08e66:8","filtered_window_id":"ebf1ba1702c3d62182b08e66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebf1ba1702c3d62182b08e66/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h2/0/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"ebf1ba1702c3d62182b08e66:16","filtered_window_id":"ebf1ba1702c3d62182b08e66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebf1ba1702c3d62182b08e66/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h2/0/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"ebf1ba1702c3d62182b08e66:24","filtered_window_id":"ebf1ba1702c3d62182b08e66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebf1ba1702c3d62182b08e66/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h2/0/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"ebf1ba1702c3d62182b08e66:32","filtered_window_id":"ebf1ba1702c3d62182b08e66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebf1ba1702c3d62182b08e66/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h2/0/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"ebf1ba1702c3d62182b08e66:40","filtered_window_id":"ebf1ba1702c3d62182b08e66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebf1ba1702c3d62182b08e66/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/h2/0/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"ebf1ba1702c3d62182b08e66:48","filtered_window_id":"ebf1ba1702c3d62182b08e66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebf1ba1702c3d62182b08e66/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/h2/0/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"ebf1ba1702c3d62182b08e66:51","filtered_window_id":"ebf1ba1702c3d62182b08e66","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ebf1ba1702c3d62182b08e66/native_gt.npz","filtered_start_offset":51,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject1/h2/0/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"ec806d7d8c9235c6f438bf19:0","filtered_window_id":"ec806d7d8c9235c6f438bf19","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ec806d7d8c9235c6f438bf19/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject1/o1/4/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"ec806d7d8c9235c6f438bf19:8","filtered_window_id":"ec806d7d8c9235c6f438bf19","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ec806d7d8c9235c6f438bf19/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject1/o1/4/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"ec806d7d8c9235c6f438bf19:16","filtered_window_id":"ec806d7d8c9235c6f438bf19","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ec806d7d8c9235c6f438bf19/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject1/o1/4/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"ec806d7d8c9235c6f438bf19:24","filtered_window_id":"ec806d7d8c9235c6f438bf19","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ec806d7d8c9235c6f438bf19/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject1/o1/4/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"ec806d7d8c9235c6f438bf19:32","filtered_window_id":"ec806d7d8c9235c6f438bf19","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ec806d7d8c9235c6f438bf19/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[277,278,279,280,281,282,283,284],"take":"subject1/o1/4/cam4","frame_ids":[277,278,279,280,281,282,283,284]} +{"filtered_tile_id":"ec806d7d8c9235c6f438bf19:40","filtered_window_id":"ec806d7d8c9235c6f438bf19","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ec806d7d8c9235c6f438bf19/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject1/o1/4/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"ec806d7d8c9235c6f438bf19:48","filtered_window_id":"ec806d7d8c9235c6f438bf19","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ec806d7d8c9235c6f438bf19/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[293,294,295,296,297,298,299,300],"take":"subject1/o1/4/cam4","frame_ids":[293,294,295,296,297,298,299,300]} +{"filtered_tile_id":"ec806d7d8c9235c6f438bf19:52","filtered_window_id":"ec806d7d8c9235c6f438bf19","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ec806d7d8c9235c6f438bf19/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[297,298,299,300,301,302,303,304],"take":"subject1/o1/4/cam4","frame_ids":[297,298,299,300,301,302,303,304]} +{"filtered_tile_id":"ecfad91ee2d5b1a7bede7444:0","filtered_window_id":"ecfad91ee2d5b1a7bede7444","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ecfad91ee2d5b1a7bede7444/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[521,522,523,524,525,526,527,528],"take":"subject1/h1/7/cam4","frame_ids":[521,522,523,524,525,526,527,528]} +{"filtered_tile_id":"ecfad91ee2d5b1a7bede7444:8","filtered_window_id":"ecfad91ee2d5b1a7bede7444","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ecfad91ee2d5b1a7bede7444/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[529,530,531,532,533,534,535,536],"take":"subject1/h1/7/cam4","frame_ids":[529,530,531,532,533,534,535,536]} +{"filtered_tile_id":"ecfad91ee2d5b1a7bede7444:14","filtered_window_id":"ecfad91ee2d5b1a7bede7444","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ecfad91ee2d5b1a7bede7444/native_gt.npz","filtered_start_offset":14,"expected_frame_ids":[535,536,537,538,539,540,541,542],"take":"subject1/h1/7/cam4","frame_ids":[535,536,537,538,539,540,541,542]} +{"filtered_tile_id":"ed09be09a557c15d4023a77f:0","filtered_window_id":"ed09be09a557c15d4023a77f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed09be09a557c15d4023a77f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/o2/3/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"ed09be09a557c15d4023a77f:8","filtered_window_id":"ed09be09a557c15d4023a77f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed09be09a557c15d4023a77f/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/o2/3/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"ed09be09a557c15d4023a77f:16","filtered_window_id":"ed09be09a557c15d4023a77f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed09be09a557c15d4023a77f/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/o2/3/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"ed09be09a557c15d4023a77f:24","filtered_window_id":"ed09be09a557c15d4023a77f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed09be09a557c15d4023a77f/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/o2/3/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"ed09be09a557c15d4023a77f:32","filtered_window_id":"ed09be09a557c15d4023a77f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed09be09a557c15d4023a77f/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/o2/3/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"ed09be09a557c15d4023a77f:40","filtered_window_id":"ed09be09a557c15d4023a77f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed09be09a557c15d4023a77f/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/o2/3/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"ed09be09a557c15d4023a77f:48","filtered_window_id":"ed09be09a557c15d4023a77f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed09be09a557c15d4023a77f/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/o2/3/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"ed09be09a557c15d4023a77f:49","filtered_window_id":"ed09be09a557c15d4023a77f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed09be09a557c15d4023a77f/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[49,50,51,52,53,54,55,56],"take":"subject1/o2/3/cam4","frame_ids":[49,50,51,52,53,54,55,56]} +{"filtered_tile_id":"ed198ab1a11450d81df71288:0","filtered_window_id":"ed198ab1a11450d81df71288","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed198ab1a11450d81df71288/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[502,503,504,505,506,507,508,509],"take":"subject2/h2/1/cam4","frame_ids":[502,503,504,505,506,507,508,509]} +{"filtered_tile_id":"ed198ab1a11450d81df71288:8","filtered_window_id":"ed198ab1a11450d81df71288","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed198ab1a11450d81df71288/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[510,511,512,513,514,515,516,517],"take":"subject2/h2/1/cam4","frame_ids":[510,511,512,513,514,515,516,517]} +{"filtered_tile_id":"ed198ab1a11450d81df71288:16","filtered_window_id":"ed198ab1a11450d81df71288","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed198ab1a11450d81df71288/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[518,519,520,521,522,523,524,525],"take":"subject2/h2/1/cam4","frame_ids":[518,519,520,521,522,523,524,525]} +{"filtered_tile_id":"ed198ab1a11450d81df71288:20","filtered_window_id":"ed198ab1a11450d81df71288","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ed198ab1a11450d81df71288/native_gt.npz","filtered_start_offset":20,"expected_frame_ids":[522,523,524,525,526,527,528,529],"take":"subject2/h2/1/cam4","frame_ids":[522,523,524,525,526,527,528,529]} +{"filtered_tile_id":"ee19ec60c44b46d358d4394a:0","filtered_window_id":"ee19ec60c44b46d358d4394a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee19ec60c44b46d358d4394a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[56,57,58,59,60,61,62,63],"take":"subject1/h2/7/cam4","frame_ids":[56,57,58,59,60,61,62,63]} +{"filtered_tile_id":"ee19ec60c44b46d358d4394a:8","filtered_window_id":"ee19ec60c44b46d358d4394a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee19ec60c44b46d358d4394a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[64,65,66,67,68,69,70,71],"take":"subject1/h2/7/cam4","frame_ids":[64,65,66,67,68,69,70,71]} +{"filtered_tile_id":"ee19ec60c44b46d358d4394a:16","filtered_window_id":"ee19ec60c44b46d358d4394a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee19ec60c44b46d358d4394a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[72,73,74,75,76,77,78,79],"take":"subject1/h2/7/cam4","frame_ids":[72,73,74,75,76,77,78,79]} +{"filtered_tile_id":"ee19ec60c44b46d358d4394a:24","filtered_window_id":"ee19ec60c44b46d358d4394a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee19ec60c44b46d358d4394a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[80,81,82,83,84,85,86,87],"take":"subject1/h2/7/cam4","frame_ids":[80,81,82,83,84,85,86,87]} +{"filtered_tile_id":"ee19ec60c44b46d358d4394a:32","filtered_window_id":"ee19ec60c44b46d358d4394a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee19ec60c44b46d358d4394a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject1/h2/7/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"ee19ec60c44b46d358d4394a:40","filtered_window_id":"ee19ec60c44b46d358d4394a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee19ec60c44b46d358d4394a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject1/h2/7/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"ee19ec60c44b46d358d4394a:48","filtered_window_id":"ee19ec60c44b46d358d4394a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee19ec60c44b46d358d4394a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[104,105,106,107,108,109,110,111],"take":"subject1/h2/7/cam4","frame_ids":[104,105,106,107,108,109,110,111]} +{"filtered_tile_id":"ee19ec60c44b46d358d4394a:52","filtered_window_id":"ee19ec60c44b46d358d4394a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee19ec60c44b46d358d4394a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/h2/7/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"ee1a038f502d62cad6854679:0","filtered_window_id":"ee1a038f502d62cad6854679","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee1a038f502d62cad6854679/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[381,382,383,384,385,386,387,388],"take":"subject1/o2/1/cam4","frame_ids":[381,382,383,384,385,386,387,388]} +{"filtered_tile_id":"ee1a038f502d62cad6854679:8","filtered_window_id":"ee1a038f502d62cad6854679","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee1a038f502d62cad6854679/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[389,390,391,392,393,394,395,396],"take":"subject1/o2/1/cam4","frame_ids":[389,390,391,392,393,394,395,396]} +{"filtered_tile_id":"ee1a038f502d62cad6854679:16","filtered_window_id":"ee1a038f502d62cad6854679","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee1a038f502d62cad6854679/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[397,398,399,400,401,402,403,404],"take":"subject1/o2/1/cam4","frame_ids":[397,398,399,400,401,402,403,404]} +{"filtered_tile_id":"ee1a038f502d62cad6854679:24","filtered_window_id":"ee1a038f502d62cad6854679","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee1a038f502d62cad6854679/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[405,406,407,408,409,410,411,412],"take":"subject1/o2/1/cam4","frame_ids":[405,406,407,408,409,410,411,412]} +{"filtered_tile_id":"ee1a038f502d62cad6854679:32","filtered_window_id":"ee1a038f502d62cad6854679","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee1a038f502d62cad6854679/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[413,414,415,416,417,418,419,420],"take":"subject1/o2/1/cam4","frame_ids":[413,414,415,416,417,418,419,420]} +{"filtered_tile_id":"ee1a038f502d62cad6854679:40","filtered_window_id":"ee1a038f502d62cad6854679","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee1a038f502d62cad6854679/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[421,422,423,424,425,426,427,428],"take":"subject1/o2/1/cam4","frame_ids":[421,422,423,424,425,426,427,428]} +{"filtered_tile_id":"ee1a038f502d62cad6854679:48","filtered_window_id":"ee1a038f502d62cad6854679","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee1a038f502d62cad6854679/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[429,430,431,432,433,434,435,436],"take":"subject1/o2/1/cam4","frame_ids":[429,430,431,432,433,434,435,436]} +{"filtered_tile_id":"ee1a038f502d62cad6854679:52","filtered_window_id":"ee1a038f502d62cad6854679","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee1a038f502d62cad6854679/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[433,434,435,436,437,438,439,440],"take":"subject1/o2/1/cam4","frame_ids":[433,434,435,436,437,438,439,440]} +{"filtered_tile_id":"ee3b119b181039604f9c51b1:0","filtered_window_id":"ee3b119b181039604f9c51b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee3b119b181039604f9c51b1/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/k1/5/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"ee3b119b181039604f9c51b1:8","filtered_window_id":"ee3b119b181039604f9c51b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee3b119b181039604f9c51b1/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/k1/5/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"ee3b119b181039604f9c51b1:16","filtered_window_id":"ee3b119b181039604f9c51b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee3b119b181039604f9c51b1/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/k1/5/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"ee3b119b181039604f9c51b1:24","filtered_window_id":"ee3b119b181039604f9c51b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee3b119b181039604f9c51b1/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/k1/5/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"ee3b119b181039604f9c51b1:32","filtered_window_id":"ee3b119b181039604f9c51b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee3b119b181039604f9c51b1/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/k1/5/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"ee3b119b181039604f9c51b1:40","filtered_window_id":"ee3b119b181039604f9c51b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee3b119b181039604f9c51b1/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject1/k1/5/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"ee3b119b181039604f9c51b1:48","filtered_window_id":"ee3b119b181039604f9c51b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee3b119b181039604f9c51b1/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject1/k1/5/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"ee3b119b181039604f9c51b1:52","filtered_window_id":"ee3b119b181039604f9c51b1","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ee3b119b181039604f9c51b1/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject1/k1/5/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"eecf98a37c86b83aace062ea:0","filtered_window_id":"eecf98a37c86b83aace062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eecf98a37c86b83aace062ea/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[97,98,99,100,101,102,103,104],"take":"subject3/h1/5/cam4","frame_ids":[97,98,99,100,101,102,103,104]} +{"filtered_tile_id":"eecf98a37c86b83aace062ea:8","filtered_window_id":"eecf98a37c86b83aace062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eecf98a37c86b83aace062ea/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[105,106,107,108,109,110,111,112],"take":"subject3/h1/5/cam4","frame_ids":[105,106,107,108,109,110,111,112]} +{"filtered_tile_id":"eecf98a37c86b83aace062ea:14","filtered_window_id":"eecf98a37c86b83aace062ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eecf98a37c86b83aace062ea/native_gt.npz","filtered_start_offset":14,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject3/h1/5/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"eed0f342d9c7224fbee4d4f5:0","filtered_window_id":"eed0f342d9c7224fbee4d4f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eed0f342d9c7224fbee4d4f5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject1/k1/5/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"eed0f342d9c7224fbee4d4f5:8","filtered_window_id":"eed0f342d9c7224fbee4d4f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eed0f342d9c7224fbee4d4f5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject1/k1/5/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"eed0f342d9c7224fbee4d4f5:16","filtered_window_id":"eed0f342d9c7224fbee4d4f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eed0f342d9c7224fbee4d4f5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject1/k1/5/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"eed0f342d9c7224fbee4d4f5:24","filtered_window_id":"eed0f342d9c7224fbee4d4f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eed0f342d9c7224fbee4d4f5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject1/k1/5/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"eed0f342d9c7224fbee4d4f5:32","filtered_window_id":"eed0f342d9c7224fbee4d4f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eed0f342d9c7224fbee4d4f5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject1/k1/5/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"eed0f342d9c7224fbee4d4f5:40","filtered_window_id":"eed0f342d9c7224fbee4d4f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eed0f342d9c7224fbee4d4f5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject1/k1/5/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"eed0f342d9c7224fbee4d4f5:48","filtered_window_id":"eed0f342d9c7224fbee4d4f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eed0f342d9c7224fbee4d4f5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/k1/5/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"eed0f342d9c7224fbee4d4f5:52","filtered_window_id":"eed0f342d9c7224fbee4d4f5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eed0f342d9c7224fbee4d4f5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[112,113,114,115,116,117,118,119],"take":"subject1/k1/5/cam4","frame_ids":[112,113,114,115,116,117,118,119]} +{"filtered_tile_id":"eee61920d61477eded7626c3:0","filtered_window_id":"eee61920d61477eded7626c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eee61920d61477eded7626c3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject2/k2/3/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"eee61920d61477eded7626c3:8","filtered_window_id":"eee61920d61477eded7626c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eee61920d61477eded7626c3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject2/k2/3/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"eee61920d61477eded7626c3:16","filtered_window_id":"eee61920d61477eded7626c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eee61920d61477eded7626c3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject2/k2/3/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"eee61920d61477eded7626c3:24","filtered_window_id":"eee61920d61477eded7626c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eee61920d61477eded7626c3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject2/k2/3/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"eee61920d61477eded7626c3:32","filtered_window_id":"eee61920d61477eded7626c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eee61920d61477eded7626c3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[265,266,267,268,269,270,271,272],"take":"subject2/k2/3/cam4","frame_ids":[265,266,267,268,269,270,271,272]} +{"filtered_tile_id":"eee61920d61477eded7626c3:40","filtered_window_id":"eee61920d61477eded7626c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eee61920d61477eded7626c3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[273,274,275,276,277,278,279,280],"take":"subject2/k2/3/cam4","frame_ids":[273,274,275,276,277,278,279,280]} +{"filtered_tile_id":"eee61920d61477eded7626c3:48","filtered_window_id":"eee61920d61477eded7626c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eee61920d61477eded7626c3/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[281,282,283,284,285,286,287,288],"take":"subject2/k2/3/cam4","frame_ids":[281,282,283,284,285,286,287,288]} +{"filtered_tile_id":"eee61920d61477eded7626c3:52","filtered_window_id":"eee61920d61477eded7626c3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eee61920d61477eded7626c3/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[285,286,287,288,289,290,291,292],"take":"subject2/k2/3/cam4","frame_ids":[285,286,287,288,289,290,291,292]} +{"filtered_tile_id":"eeff8f6c6cb35ac0aff69022:0","filtered_window_id":"eeff8f6c6cb35ac0aff69022","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eeff8f6c6cb35ac0aff69022/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[673,674,675,676,677,678,679,680],"take":"subject3/h2/1/cam4","frame_ids":[673,674,675,676,677,678,679,680]} +{"filtered_tile_id":"eeff8f6c6cb35ac0aff69022:8","filtered_window_id":"eeff8f6c6cb35ac0aff69022","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eeff8f6c6cb35ac0aff69022/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[681,682,683,684,685,686,687,688],"take":"subject3/h2/1/cam4","frame_ids":[681,682,683,684,685,686,687,688]} +{"filtered_tile_id":"eeff8f6c6cb35ac0aff69022:16","filtered_window_id":"eeff8f6c6cb35ac0aff69022","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eeff8f6c6cb35ac0aff69022/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[689,690,691,692,693,694,695,696],"take":"subject3/h2/1/cam4","frame_ids":[689,690,691,692,693,694,695,696]} +{"filtered_tile_id":"eeff8f6c6cb35ac0aff69022:24","filtered_window_id":"eeff8f6c6cb35ac0aff69022","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eeff8f6c6cb35ac0aff69022/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[697,698,699,700,701,702,703,704],"take":"subject3/h2/1/cam4","frame_ids":[697,698,699,700,701,702,703,704]} +{"filtered_tile_id":"eeff8f6c6cb35ac0aff69022:32","filtered_window_id":"eeff8f6c6cb35ac0aff69022","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eeff8f6c6cb35ac0aff69022/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[705,706,707,708,709,710,711,712],"take":"subject3/h2/1/cam4","frame_ids":[705,706,707,708,709,710,711,712]} +{"filtered_tile_id":"eeff8f6c6cb35ac0aff69022:33","filtered_window_id":"eeff8f6c6cb35ac0aff69022","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/eeff8f6c6cb35ac0aff69022/native_gt.npz","filtered_start_offset":33,"expected_frame_ids":[706,707,708,709,710,711,712,713],"take":"subject3/h2/1/cam4","frame_ids":[706,707,708,709,710,711,712,713]} +{"filtered_tile_id":"ef2c6c2d8730b3698487df50:0","filtered_window_id":"ef2c6c2d8730b3698487df50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef2c6c2d8730b3698487df50/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[396,397,398,399,400,401,402,403],"take":"subject1/o2/0/cam4","frame_ids":[396,397,398,399,400,401,402,403]} +{"filtered_tile_id":"ef2c6c2d8730b3698487df50:8","filtered_window_id":"ef2c6c2d8730b3698487df50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef2c6c2d8730b3698487df50/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[404,405,406,407,408,409,410,411],"take":"subject1/o2/0/cam4","frame_ids":[404,405,406,407,408,409,410,411]} +{"filtered_tile_id":"ef2c6c2d8730b3698487df50:16","filtered_window_id":"ef2c6c2d8730b3698487df50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef2c6c2d8730b3698487df50/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[412,413,414,415,416,417,418,419],"take":"subject1/o2/0/cam4","frame_ids":[412,413,414,415,416,417,418,419]} +{"filtered_tile_id":"ef2c6c2d8730b3698487df50:24","filtered_window_id":"ef2c6c2d8730b3698487df50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef2c6c2d8730b3698487df50/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[420,421,422,423,424,425,426,427],"take":"subject1/o2/0/cam4","frame_ids":[420,421,422,423,424,425,426,427]} +{"filtered_tile_id":"ef2c6c2d8730b3698487df50:32","filtered_window_id":"ef2c6c2d8730b3698487df50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef2c6c2d8730b3698487df50/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject1/o2/0/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"ef2c6c2d8730b3698487df50:40","filtered_window_id":"ef2c6c2d8730b3698487df50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef2c6c2d8730b3698487df50/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject1/o2/0/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"ef2c6c2d8730b3698487df50:43","filtered_window_id":"ef2c6c2d8730b3698487df50","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef2c6c2d8730b3698487df50/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[439,440,441,442,443,444,445,446],"take":"subject1/o2/0/cam4","frame_ids":[439,440,441,442,443,444,445,446]} +{"filtered_tile_id":"ef4584a3b7889bc286798b09:0","filtered_window_id":"ef4584a3b7889bc286798b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef4584a3b7889bc286798b09/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[519,520,521,522,523,524,525,526],"take":"subject1/h2/1/cam4","frame_ids":[519,520,521,522,523,524,525,526]} +{"filtered_tile_id":"ef4584a3b7889bc286798b09:8","filtered_window_id":"ef4584a3b7889bc286798b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef4584a3b7889bc286798b09/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[527,528,529,530,531,532,533,534],"take":"subject1/h2/1/cam4","frame_ids":[527,528,529,530,531,532,533,534]} +{"filtered_tile_id":"ef4584a3b7889bc286798b09:16","filtered_window_id":"ef4584a3b7889bc286798b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef4584a3b7889bc286798b09/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[535,536,537,538,539,540,541,542],"take":"subject1/h2/1/cam4","frame_ids":[535,536,537,538,539,540,541,542]} +{"filtered_tile_id":"ef4584a3b7889bc286798b09:24","filtered_window_id":"ef4584a3b7889bc286798b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef4584a3b7889bc286798b09/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[543,544,545,546,547,548,549,550],"take":"subject1/h2/1/cam4","frame_ids":[543,544,545,546,547,548,549,550]} +{"filtered_tile_id":"ef4584a3b7889bc286798b09:32","filtered_window_id":"ef4584a3b7889bc286798b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef4584a3b7889bc286798b09/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[551,552,553,554,555,556,557,558],"take":"subject1/h2/1/cam4","frame_ids":[551,552,553,554,555,556,557,558]} +{"filtered_tile_id":"ef4584a3b7889bc286798b09:40","filtered_window_id":"ef4584a3b7889bc286798b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef4584a3b7889bc286798b09/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[559,560,561,562,563,564,565,566],"take":"subject1/h2/1/cam4","frame_ids":[559,560,561,562,563,564,565,566]} +{"filtered_tile_id":"ef4584a3b7889bc286798b09:48","filtered_window_id":"ef4584a3b7889bc286798b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef4584a3b7889bc286798b09/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[567,568,569,570,571,572,573,574],"take":"subject1/h2/1/cam4","frame_ids":[567,568,569,570,571,572,573,574]} +{"filtered_tile_id":"ef4584a3b7889bc286798b09:52","filtered_window_id":"ef4584a3b7889bc286798b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef4584a3b7889bc286798b09/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[571,572,573,574,575,576,577,578],"take":"subject1/h2/1/cam4","frame_ids":[571,572,573,574,575,576,577,578]} +{"filtered_tile_id":"ef5ec63a03f6170d71db9da9:0","filtered_window_id":"ef5ec63a03f6170d71db9da9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef5ec63a03f6170d71db9da9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[415,416,417,418,419,420,421,422],"take":"subject2/o2/3/cam4","frame_ids":[415,416,417,418,419,420,421,422]} +{"filtered_tile_id":"ef5ec63a03f6170d71db9da9:3","filtered_window_id":"ef5ec63a03f6170d71db9da9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ef5ec63a03f6170d71db9da9/native_gt.npz","filtered_start_offset":3,"expected_frame_ids":[418,419,420,421,422,423,424,425],"take":"subject2/o2/3/cam4","frame_ids":[418,419,420,421,422,423,424,425]} +{"filtered_tile_id":"efedd51d300c2bfcc12f7263:0","filtered_window_id":"efedd51d300c2bfcc12f7263","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/efedd51d300c2bfcc12f7263/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[140,141,142,143,144,145,146,147],"take":"subject2/o1/4/cam4","frame_ids":[140,141,142,143,144,145,146,147]} +{"filtered_tile_id":"efedd51d300c2bfcc12f7263:8","filtered_window_id":"efedd51d300c2bfcc12f7263","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/efedd51d300c2bfcc12f7263/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[148,149,150,151,152,153,154,155],"take":"subject2/o1/4/cam4","frame_ids":[148,149,150,151,152,153,154,155]} +{"filtered_tile_id":"efedd51d300c2bfcc12f7263:16","filtered_window_id":"efedd51d300c2bfcc12f7263","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/efedd51d300c2bfcc12f7263/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[156,157,158,159,160,161,162,163],"take":"subject2/o1/4/cam4","frame_ids":[156,157,158,159,160,161,162,163]} +{"filtered_tile_id":"efedd51d300c2bfcc12f7263:24","filtered_window_id":"efedd51d300c2bfcc12f7263","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/efedd51d300c2bfcc12f7263/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[164,165,166,167,168,169,170,171],"take":"subject2/o1/4/cam4","frame_ids":[164,165,166,167,168,169,170,171]} +{"filtered_tile_id":"efedd51d300c2bfcc12f7263:32","filtered_window_id":"efedd51d300c2bfcc12f7263","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/efedd51d300c2bfcc12f7263/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[172,173,174,175,176,177,178,179],"take":"subject2/o1/4/cam4","frame_ids":[172,173,174,175,176,177,178,179]} +{"filtered_tile_id":"efedd51d300c2bfcc12f7263:40","filtered_window_id":"efedd51d300c2bfcc12f7263","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/efedd51d300c2bfcc12f7263/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[180,181,182,183,184,185,186,187],"take":"subject2/o1/4/cam4","frame_ids":[180,181,182,183,184,185,186,187]} +{"filtered_tile_id":"efedd51d300c2bfcc12f7263:42","filtered_window_id":"efedd51d300c2bfcc12f7263","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/efedd51d300c2bfcc12f7263/native_gt.npz","filtered_start_offset":42,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject2/o1/4/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"effe75dbbb0fbffdc47634b7:0","filtered_window_id":"effe75dbbb0fbffdc47634b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/effe75dbbb0fbffdc47634b7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[131,132,133,134,135,136,137,138],"take":"subject2/o1/5/cam4","frame_ids":[131,132,133,134,135,136,137,138]} +{"filtered_tile_id":"effe75dbbb0fbffdc47634b7:8","filtered_window_id":"effe75dbbb0fbffdc47634b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/effe75dbbb0fbffdc47634b7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject2/o1/5/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"effe75dbbb0fbffdc47634b7:16","filtered_window_id":"effe75dbbb0fbffdc47634b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/effe75dbbb0fbffdc47634b7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject2/o1/5/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"effe75dbbb0fbffdc47634b7:24","filtered_window_id":"effe75dbbb0fbffdc47634b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/effe75dbbb0fbffdc47634b7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject2/o1/5/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"effe75dbbb0fbffdc47634b7:32","filtered_window_id":"effe75dbbb0fbffdc47634b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/effe75dbbb0fbffdc47634b7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[163,164,165,166,167,168,169,170],"take":"subject2/o1/5/cam4","frame_ids":[163,164,165,166,167,168,169,170]} +{"filtered_tile_id":"effe75dbbb0fbffdc47634b7:40","filtered_window_id":"effe75dbbb0fbffdc47634b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/effe75dbbb0fbffdc47634b7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[171,172,173,174,175,176,177,178],"take":"subject2/o1/5/cam4","frame_ids":[171,172,173,174,175,176,177,178]} +{"filtered_tile_id":"effe75dbbb0fbffdc47634b7:48","filtered_window_id":"effe75dbbb0fbffdc47634b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/effe75dbbb0fbffdc47634b7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[179,180,181,182,183,184,185,186],"take":"subject2/o1/5/cam4","frame_ids":[179,180,181,182,183,184,185,186]} +{"filtered_tile_id":"effe75dbbb0fbffdc47634b7:52","filtered_window_id":"effe75dbbb0fbffdc47634b7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/effe75dbbb0fbffdc47634b7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[183,184,185,186,187,188,189,190],"take":"subject2/o1/5/cam4","frame_ids":[183,184,185,186,187,188,189,190]} +{"filtered_tile_id":"f00772a73a3f05ec98fc6ee5:0","filtered_window_id":"f00772a73a3f05ec98fc6ee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f00772a73a3f05ec98fc6ee5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[435,436,437,438,439,440,441,442],"take":"subject1/h1/3/cam4","frame_ids":[435,436,437,438,439,440,441,442]} +{"filtered_tile_id":"f00772a73a3f05ec98fc6ee5:8","filtered_window_id":"f00772a73a3f05ec98fc6ee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f00772a73a3f05ec98fc6ee5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[443,444,445,446,447,448,449,450],"take":"subject1/h1/3/cam4","frame_ids":[443,444,445,446,447,448,449,450]} +{"filtered_tile_id":"f00772a73a3f05ec98fc6ee5:16","filtered_window_id":"f00772a73a3f05ec98fc6ee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f00772a73a3f05ec98fc6ee5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[451,452,453,454,455,456,457,458],"take":"subject1/h1/3/cam4","frame_ids":[451,452,453,454,455,456,457,458]} +{"filtered_tile_id":"f00772a73a3f05ec98fc6ee5:24","filtered_window_id":"f00772a73a3f05ec98fc6ee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f00772a73a3f05ec98fc6ee5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[459,460,461,462,463,464,465,466],"take":"subject1/h1/3/cam4","frame_ids":[459,460,461,462,463,464,465,466]} +{"filtered_tile_id":"f00772a73a3f05ec98fc6ee5:32","filtered_window_id":"f00772a73a3f05ec98fc6ee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f00772a73a3f05ec98fc6ee5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[467,468,469,470,471,472,473,474],"take":"subject1/h1/3/cam4","frame_ids":[467,468,469,470,471,472,473,474]} +{"filtered_tile_id":"f00772a73a3f05ec98fc6ee5:40","filtered_window_id":"f00772a73a3f05ec98fc6ee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f00772a73a3f05ec98fc6ee5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[475,476,477,478,479,480,481,482],"take":"subject1/h1/3/cam4","frame_ids":[475,476,477,478,479,480,481,482]} +{"filtered_tile_id":"f00772a73a3f05ec98fc6ee5:43","filtered_window_id":"f00772a73a3f05ec98fc6ee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f00772a73a3f05ec98fc6ee5/native_gt.npz","filtered_start_offset":43,"expected_frame_ids":[478,479,480,481,482,483,484,485],"take":"subject1/h1/3/cam4","frame_ids":[478,479,480,481,482,483,484,485]} +{"filtered_tile_id":"f05fad6180669a1376bd0d16:0","filtered_window_id":"f05fad6180669a1376bd0d16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f05fad6180669a1376bd0d16/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[310,311,312,313,314,315,316,317],"take":"subject2/h2/6/cam4","frame_ids":[310,311,312,313,314,315,316,317]} +{"filtered_tile_id":"f05fad6180669a1376bd0d16:8","filtered_window_id":"f05fad6180669a1376bd0d16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f05fad6180669a1376bd0d16/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject2/h2/6/cam4","frame_ids":[318,319,320,321,322,323,324,325]} +{"filtered_tile_id":"f05fad6180669a1376bd0d16:16","filtered_window_id":"f05fad6180669a1376bd0d16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f05fad6180669a1376bd0d16/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[326,327,328,329,330,331,332,333],"take":"subject2/h2/6/cam4","frame_ids":[326,327,328,329,330,331,332,333]} +{"filtered_tile_id":"f05fad6180669a1376bd0d16:24","filtered_window_id":"f05fad6180669a1376bd0d16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f05fad6180669a1376bd0d16/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[334,335,336,337,338,339,340,341],"take":"subject2/h2/6/cam4","frame_ids":[334,335,336,337,338,339,340,341]} +{"filtered_tile_id":"f05fad6180669a1376bd0d16:32","filtered_window_id":"f05fad6180669a1376bd0d16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f05fad6180669a1376bd0d16/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[342,343,344,345,346,347,348,349],"take":"subject2/h2/6/cam4","frame_ids":[342,343,344,345,346,347,348,349]} +{"filtered_tile_id":"f05fad6180669a1376bd0d16:40","filtered_window_id":"f05fad6180669a1376bd0d16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f05fad6180669a1376bd0d16/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[350,351,352,353,354,355,356,357],"take":"subject2/h2/6/cam4","frame_ids":[350,351,352,353,354,355,356,357]} +{"filtered_tile_id":"f05fad6180669a1376bd0d16:48","filtered_window_id":"f05fad6180669a1376bd0d16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f05fad6180669a1376bd0d16/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[358,359,360,361,362,363,364,365],"take":"subject2/h2/6/cam4","frame_ids":[358,359,360,361,362,363,364,365]} +{"filtered_tile_id":"f05fad6180669a1376bd0d16:52","filtered_window_id":"f05fad6180669a1376bd0d16","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f05fad6180669a1376bd0d16/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[362,363,364,365,366,367,368,369],"take":"subject2/h2/6/cam4","frame_ids":[362,363,364,365,366,367,368,369]} +{"filtered_tile_id":"f08c81b14e2f7883a52e48e0:0","filtered_window_id":"f08c81b14e2f7883a52e48e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f08c81b14e2f7883a52e48e0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject2/k2/3/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"f08c81b14e2f7883a52e48e0:8","filtered_window_id":"f08c81b14e2f7883a52e48e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f08c81b14e2f7883a52e48e0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[481,482,483,484,485,486,487,488],"take":"subject2/k2/3/cam4","frame_ids":[481,482,483,484,485,486,487,488]} +{"filtered_tile_id":"f08c81b14e2f7883a52e48e0:16","filtered_window_id":"f08c81b14e2f7883a52e48e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f08c81b14e2f7883a52e48e0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[489,490,491,492,493,494,495,496],"take":"subject2/k2/3/cam4","frame_ids":[489,490,491,492,493,494,495,496]} +{"filtered_tile_id":"f08c81b14e2f7883a52e48e0:24","filtered_window_id":"f08c81b14e2f7883a52e48e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f08c81b14e2f7883a52e48e0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[497,498,499,500,501,502,503,504],"take":"subject2/k2/3/cam4","frame_ids":[497,498,499,500,501,502,503,504]} +{"filtered_tile_id":"f08c81b14e2f7883a52e48e0:32","filtered_window_id":"f08c81b14e2f7883a52e48e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f08c81b14e2f7883a52e48e0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[505,506,507,508,509,510,511,512],"take":"subject2/k2/3/cam4","frame_ids":[505,506,507,508,509,510,511,512]} +{"filtered_tile_id":"f08c81b14e2f7883a52e48e0:40","filtered_window_id":"f08c81b14e2f7883a52e48e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f08c81b14e2f7883a52e48e0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[513,514,515,516,517,518,519,520],"take":"subject2/k2/3/cam4","frame_ids":[513,514,515,516,517,518,519,520]} +{"filtered_tile_id":"f08c81b14e2f7883a52e48e0:48","filtered_window_id":"f08c81b14e2f7883a52e48e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f08c81b14e2f7883a52e48e0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[521,522,523,524,525,526,527,528],"take":"subject2/k2/3/cam4","frame_ids":[521,522,523,524,525,526,527,528]} +{"filtered_tile_id":"f08c81b14e2f7883a52e48e0:52","filtered_window_id":"f08c81b14e2f7883a52e48e0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f08c81b14e2f7883a52e48e0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[525,526,527,528,529,530,531,532],"take":"subject2/k2/3/cam4","frame_ids":[525,526,527,528,529,530,531,532]} +{"filtered_tile_id":"f0acbf6672bb3c8151ceb32a:0","filtered_window_id":"f0acbf6672bb3c8151ceb32a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0acbf6672bb3c8151ceb32a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[587,588,589,590,591,592,593,594],"take":"subject3/k1/5/cam4","frame_ids":[587,588,589,590,591,592,593,594]} +{"filtered_tile_id":"f0acbf6672bb3c8151ceb32a:4","filtered_window_id":"f0acbf6672bb3c8151ceb32a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0acbf6672bb3c8151ceb32a/native_gt.npz","filtered_start_offset":4,"expected_frame_ids":[591,592,593,594,595,596,597,598],"take":"subject3/k1/5/cam4","frame_ids":[591,592,593,594,595,596,597,598]} +{"filtered_tile_id":"f0f58c96ba5791ecc7181331:0","filtered_window_id":"f0f58c96ba5791ecc7181331","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f58c96ba5791ecc7181331/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[331,332,333,334,335,336,337,338],"take":"subject2/o1/5/cam4","frame_ids":[331,332,333,334,335,336,337,338]} +{"filtered_tile_id":"f0f58c96ba5791ecc7181331:8","filtered_window_id":"f0f58c96ba5791ecc7181331","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f58c96ba5791ecc7181331/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[339,340,341,342,343,344,345,346],"take":"subject2/o1/5/cam4","frame_ids":[339,340,341,342,343,344,345,346]} +{"filtered_tile_id":"f0f58c96ba5791ecc7181331:16","filtered_window_id":"f0f58c96ba5791ecc7181331","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f58c96ba5791ecc7181331/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[347,348,349,350,351,352,353,354],"take":"subject2/o1/5/cam4","frame_ids":[347,348,349,350,351,352,353,354]} +{"filtered_tile_id":"f0f58c96ba5791ecc7181331:24","filtered_window_id":"f0f58c96ba5791ecc7181331","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f58c96ba5791ecc7181331/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[355,356,357,358,359,360,361,362],"take":"subject2/o1/5/cam4","frame_ids":[355,356,357,358,359,360,361,362]} +{"filtered_tile_id":"f0f58c96ba5791ecc7181331:32","filtered_window_id":"f0f58c96ba5791ecc7181331","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f58c96ba5791ecc7181331/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[363,364,365,366,367,368,369,370],"take":"subject2/o1/5/cam4","frame_ids":[363,364,365,366,367,368,369,370]} +{"filtered_tile_id":"f0f58c96ba5791ecc7181331:40","filtered_window_id":"f0f58c96ba5791ecc7181331","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f58c96ba5791ecc7181331/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[371,372,373,374,375,376,377,378],"take":"subject2/o1/5/cam4","frame_ids":[371,372,373,374,375,376,377,378]} +{"filtered_tile_id":"f0f58c96ba5791ecc7181331:48","filtered_window_id":"f0f58c96ba5791ecc7181331","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f58c96ba5791ecc7181331/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[379,380,381,382,383,384,385,386],"take":"subject2/o1/5/cam4","frame_ids":[379,380,381,382,383,384,385,386]} +{"filtered_tile_id":"f0f58c96ba5791ecc7181331:52","filtered_window_id":"f0f58c96ba5791ecc7181331","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f58c96ba5791ecc7181331/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[383,384,385,386,387,388,389,390],"take":"subject2/o1/5/cam4","frame_ids":[383,384,385,386,387,388,389,390]} +{"filtered_tile_id":"f0f5e63005b6d8b712033a1f:0","filtered_window_id":"f0f5e63005b6d8b712033a1f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f5e63005b6d8b712033a1f/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[62,63,64,65,66,67,68,69],"take":"subject1/o1/2/cam4","frame_ids":[62,63,64,65,66,67,68,69]} +{"filtered_tile_id":"f0f5e63005b6d8b712033a1f:3","filtered_window_id":"f0f5e63005b6d8b712033a1f","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f0f5e63005b6d8b712033a1f/native_gt.npz","filtered_start_offset":3,"expected_frame_ids":[65,66,67,68,69,70,71,72],"take":"subject1/o1/2/cam4","frame_ids":[65,66,67,68,69,70,71,72]} +{"filtered_tile_id":"f155d747747cd02ed32cce8e:0","filtered_window_id":"f155d747747cd02ed32cce8e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f155d747747cd02ed32cce8e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/h2/0/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"f155d747747cd02ed32cce8e:8","filtered_window_id":"f155d747747cd02ed32cce8e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f155d747747cd02ed32cce8e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/h2/0/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"f155d747747cd02ed32cce8e:16","filtered_window_id":"f155d747747cd02ed32cce8e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f155d747747cd02ed32cce8e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/h2/0/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"f155d747747cd02ed32cce8e:24","filtered_window_id":"f155d747747cd02ed32cce8e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f155d747747cd02ed32cce8e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/h2/0/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"f155d747747cd02ed32cce8e:32","filtered_window_id":"f155d747747cd02ed32cce8e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f155d747747cd02ed32cce8e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/h2/0/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"f155d747747cd02ed32cce8e:40","filtered_window_id":"f155d747747cd02ed32cce8e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f155d747747cd02ed32cce8e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/h2/0/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"f155d747747cd02ed32cce8e:48","filtered_window_id":"f155d747747cd02ed32cce8e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f155d747747cd02ed32cce8e/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/h2/0/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"f155d747747cd02ed32cce8e:52","filtered_window_id":"f155d747747cd02ed32cce8e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f155d747747cd02ed32cce8e/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/h2/0/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"f1a4c1851bfcc01e3eb04a2b:0","filtered_window_id":"f1a4c1851bfcc01e3eb04a2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1a4c1851bfcc01e3eb04a2b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[569,570,571,572,573,574,575,576],"take":"subject2/h1/3/cam4","frame_ids":[569,570,571,572,573,574,575,576]} +{"filtered_tile_id":"f1a4c1851bfcc01e3eb04a2b:8","filtered_window_id":"f1a4c1851bfcc01e3eb04a2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1a4c1851bfcc01e3eb04a2b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[577,578,579,580,581,582,583,584],"take":"subject2/h1/3/cam4","frame_ids":[577,578,579,580,581,582,583,584]} +{"filtered_tile_id":"f1a4c1851bfcc01e3eb04a2b:16","filtered_window_id":"f1a4c1851bfcc01e3eb04a2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1a4c1851bfcc01e3eb04a2b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[585,586,587,588,589,590,591,592],"take":"subject2/h1/3/cam4","frame_ids":[585,586,587,588,589,590,591,592]} +{"filtered_tile_id":"f1a4c1851bfcc01e3eb04a2b:24","filtered_window_id":"f1a4c1851bfcc01e3eb04a2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1a4c1851bfcc01e3eb04a2b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[593,594,595,596,597,598,599,600],"take":"subject2/h1/3/cam4","frame_ids":[593,594,595,596,597,598,599,600]} +{"filtered_tile_id":"f1a4c1851bfcc01e3eb04a2b:32","filtered_window_id":"f1a4c1851bfcc01e3eb04a2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1a4c1851bfcc01e3eb04a2b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[601,602,603,604,605,606,607,608],"take":"subject2/h1/3/cam4","frame_ids":[601,602,603,604,605,606,607,608]} +{"filtered_tile_id":"f1a4c1851bfcc01e3eb04a2b:40","filtered_window_id":"f1a4c1851bfcc01e3eb04a2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1a4c1851bfcc01e3eb04a2b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[609,610,611,612,613,614,615,616],"take":"subject2/h1/3/cam4","frame_ids":[609,610,611,612,613,614,615,616]} +{"filtered_tile_id":"f1a4c1851bfcc01e3eb04a2b:48","filtered_window_id":"f1a4c1851bfcc01e3eb04a2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1a4c1851bfcc01e3eb04a2b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[617,618,619,620,621,622,623,624],"take":"subject2/h1/3/cam4","frame_ids":[617,618,619,620,621,622,623,624]} +{"filtered_tile_id":"f1a4c1851bfcc01e3eb04a2b:52","filtered_window_id":"f1a4c1851bfcc01e3eb04a2b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1a4c1851bfcc01e3eb04a2b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[621,622,623,624,625,626,627,628],"take":"subject2/h1/3/cam4","frame_ids":[621,622,623,624,625,626,627,628]} +{"filtered_tile_id":"f1ad9ba5d7f11db8c0606aff:0","filtered_window_id":"f1ad9ba5d7f11db8c0606aff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1ad9ba5d7f11db8c0606aff/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[238,239,240,241,242,243,244,245],"take":"subject2/h1/3/cam4","frame_ids":[238,239,240,241,242,243,244,245]} +{"filtered_tile_id":"f1ad9ba5d7f11db8c0606aff:8","filtered_window_id":"f1ad9ba5d7f11db8c0606aff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1ad9ba5d7f11db8c0606aff/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[246,247,248,249,250,251,252,253],"take":"subject2/h1/3/cam4","frame_ids":[246,247,248,249,250,251,252,253]} +{"filtered_tile_id":"f1ad9ba5d7f11db8c0606aff:16","filtered_window_id":"f1ad9ba5d7f11db8c0606aff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1ad9ba5d7f11db8c0606aff/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[254,255,256,257,258,259,260,261],"take":"subject2/h1/3/cam4","frame_ids":[254,255,256,257,258,259,260,261]} +{"filtered_tile_id":"f1ad9ba5d7f11db8c0606aff:24","filtered_window_id":"f1ad9ba5d7f11db8c0606aff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1ad9ba5d7f11db8c0606aff/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[262,263,264,265,266,267,268,269],"take":"subject2/h1/3/cam4","frame_ids":[262,263,264,265,266,267,268,269]} +{"filtered_tile_id":"f1ad9ba5d7f11db8c0606aff:32","filtered_window_id":"f1ad9ba5d7f11db8c0606aff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1ad9ba5d7f11db8c0606aff/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[270,271,272,273,274,275,276,277],"take":"subject2/h1/3/cam4","frame_ids":[270,271,272,273,274,275,276,277]} +{"filtered_tile_id":"f1ad9ba5d7f11db8c0606aff:40","filtered_window_id":"f1ad9ba5d7f11db8c0606aff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1ad9ba5d7f11db8c0606aff/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[278,279,280,281,282,283,284,285],"take":"subject2/h1/3/cam4","frame_ids":[278,279,280,281,282,283,284,285]} +{"filtered_tile_id":"f1ad9ba5d7f11db8c0606aff:48","filtered_window_id":"f1ad9ba5d7f11db8c0606aff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1ad9ba5d7f11db8c0606aff/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[286,287,288,289,290,291,292,293],"take":"subject2/h1/3/cam4","frame_ids":[286,287,288,289,290,291,292,293]} +{"filtered_tile_id":"f1ad9ba5d7f11db8c0606aff:52","filtered_window_id":"f1ad9ba5d7f11db8c0606aff","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1ad9ba5d7f11db8c0606aff/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[290,291,292,293,294,295,296,297],"take":"subject2/h1/3/cam4","frame_ids":[290,291,292,293,294,295,296,297]} +{"filtered_tile_id":"f1df6d21a4d59dbf6316c6c0:0","filtered_window_id":"f1df6d21a4d59dbf6316c6c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1df6d21a4d59dbf6316c6c0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[313,314,315,316,317,318,319,320],"take":"subject3/h2/1/cam4","frame_ids":[313,314,315,316,317,318,319,320]} +{"filtered_tile_id":"f1df6d21a4d59dbf6316c6c0:8","filtered_window_id":"f1df6d21a4d59dbf6316c6c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1df6d21a4d59dbf6316c6c0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[321,322,323,324,325,326,327,328],"take":"subject3/h2/1/cam4","frame_ids":[321,322,323,324,325,326,327,328]} +{"filtered_tile_id":"f1df6d21a4d59dbf6316c6c0:16","filtered_window_id":"f1df6d21a4d59dbf6316c6c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1df6d21a4d59dbf6316c6c0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[329,330,331,332,333,334,335,336],"take":"subject3/h2/1/cam4","frame_ids":[329,330,331,332,333,334,335,336]} +{"filtered_tile_id":"f1df6d21a4d59dbf6316c6c0:24","filtered_window_id":"f1df6d21a4d59dbf6316c6c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1df6d21a4d59dbf6316c6c0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[337,338,339,340,341,342,343,344],"take":"subject3/h2/1/cam4","frame_ids":[337,338,339,340,341,342,343,344]} +{"filtered_tile_id":"f1df6d21a4d59dbf6316c6c0:32","filtered_window_id":"f1df6d21a4d59dbf6316c6c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1df6d21a4d59dbf6316c6c0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[345,346,347,348,349,350,351,352],"take":"subject3/h2/1/cam4","frame_ids":[345,346,347,348,349,350,351,352]} +{"filtered_tile_id":"f1df6d21a4d59dbf6316c6c0:40","filtered_window_id":"f1df6d21a4d59dbf6316c6c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1df6d21a4d59dbf6316c6c0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[353,354,355,356,357,358,359,360],"take":"subject3/h2/1/cam4","frame_ids":[353,354,355,356,357,358,359,360]} +{"filtered_tile_id":"f1df6d21a4d59dbf6316c6c0:48","filtered_window_id":"f1df6d21a4d59dbf6316c6c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1df6d21a4d59dbf6316c6c0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[361,362,363,364,365,366,367,368],"take":"subject3/h2/1/cam4","frame_ids":[361,362,363,364,365,366,367,368]} +{"filtered_tile_id":"f1df6d21a4d59dbf6316c6c0:52","filtered_window_id":"f1df6d21a4d59dbf6316c6c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f1df6d21a4d59dbf6316c6c0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[365,366,367,368,369,370,371,372],"take":"subject3/h2/1/cam4","frame_ids":[365,366,367,368,369,370,371,372]} +{"filtered_tile_id":"f2381d80df5c77bf2e545de5:0","filtered_window_id":"f2381d80df5c77bf2e545de5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2381d80df5c77bf2e545de5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[193,194,195,196,197,198,199,200],"take":"subject1/h1/0/cam4","frame_ids":[193,194,195,196,197,198,199,200]} +{"filtered_tile_id":"f2381d80df5c77bf2e545de5:8","filtered_window_id":"f2381d80df5c77bf2e545de5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2381d80df5c77bf2e545de5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[201,202,203,204,205,206,207,208],"take":"subject1/h1/0/cam4","frame_ids":[201,202,203,204,205,206,207,208]} +{"filtered_tile_id":"f2381d80df5c77bf2e545de5:16","filtered_window_id":"f2381d80df5c77bf2e545de5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2381d80df5c77bf2e545de5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[209,210,211,212,213,214,215,216],"take":"subject1/h1/0/cam4","frame_ids":[209,210,211,212,213,214,215,216]} +{"filtered_tile_id":"f2381d80df5c77bf2e545de5:24","filtered_window_id":"f2381d80df5c77bf2e545de5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2381d80df5c77bf2e545de5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[217,218,219,220,221,222,223,224],"take":"subject1/h1/0/cam4","frame_ids":[217,218,219,220,221,222,223,224]} +{"filtered_tile_id":"f2381d80df5c77bf2e545de5:32","filtered_window_id":"f2381d80df5c77bf2e545de5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2381d80df5c77bf2e545de5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[225,226,227,228,229,230,231,232],"take":"subject1/h1/0/cam4","frame_ids":[225,226,227,228,229,230,231,232]} +{"filtered_tile_id":"f2381d80df5c77bf2e545de5:40","filtered_window_id":"f2381d80df5c77bf2e545de5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2381d80df5c77bf2e545de5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject1/h1/0/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"f2381d80df5c77bf2e545de5:48","filtered_window_id":"f2381d80df5c77bf2e545de5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2381d80df5c77bf2e545de5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject1/h1/0/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"f2381d80df5c77bf2e545de5:52","filtered_window_id":"f2381d80df5c77bf2e545de5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2381d80df5c77bf2e545de5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject1/h1/0/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"f2a12cd21abc725fc100ddc3:0","filtered_window_id":"f2a12cd21abc725fc100ddc3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2a12cd21abc725fc100ddc3/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/o2/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"f2a12cd21abc725fc100ddc3:8","filtered_window_id":"f2a12cd21abc725fc100ddc3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2a12cd21abc725fc100ddc3/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/o2/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"f2a12cd21abc725fc100ddc3:16","filtered_window_id":"f2a12cd21abc725fc100ddc3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2a12cd21abc725fc100ddc3/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/o2/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"f2a12cd21abc725fc100ddc3:24","filtered_window_id":"f2a12cd21abc725fc100ddc3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2a12cd21abc725fc100ddc3/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/o2/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"f2a12cd21abc725fc100ddc3:32","filtered_window_id":"f2a12cd21abc725fc100ddc3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2a12cd21abc725fc100ddc3/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/o2/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"f2a12cd21abc725fc100ddc3:40","filtered_window_id":"f2a12cd21abc725fc100ddc3","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f2a12cd21abc725fc100ddc3/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/o2/1/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"f30fdc1e0456a4209a329e44:0","filtered_window_id":"f30fdc1e0456a4209a329e44","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f30fdc1e0456a4209a329e44/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[493,494,495,496,497,498,499,500],"take":"subject3/h2/1/cam4","frame_ids":[493,494,495,496,497,498,499,500]} +{"filtered_tile_id":"f30fdc1e0456a4209a329e44:8","filtered_window_id":"f30fdc1e0456a4209a329e44","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f30fdc1e0456a4209a329e44/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[501,502,503,504,505,506,507,508],"take":"subject3/h2/1/cam4","frame_ids":[501,502,503,504,505,506,507,508]} +{"filtered_tile_id":"f30fdc1e0456a4209a329e44:16","filtered_window_id":"f30fdc1e0456a4209a329e44","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f30fdc1e0456a4209a329e44/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[509,510,511,512,513,514,515,516],"take":"subject3/h2/1/cam4","frame_ids":[509,510,511,512,513,514,515,516]} +{"filtered_tile_id":"f30fdc1e0456a4209a329e44:24","filtered_window_id":"f30fdc1e0456a4209a329e44","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f30fdc1e0456a4209a329e44/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[517,518,519,520,521,522,523,524],"take":"subject3/h2/1/cam4","frame_ids":[517,518,519,520,521,522,523,524]} +{"filtered_tile_id":"f30fdc1e0456a4209a329e44:32","filtered_window_id":"f30fdc1e0456a4209a329e44","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f30fdc1e0456a4209a329e44/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[525,526,527,528,529,530,531,532],"take":"subject3/h2/1/cam4","frame_ids":[525,526,527,528,529,530,531,532]} +{"filtered_tile_id":"f30fdc1e0456a4209a329e44:40","filtered_window_id":"f30fdc1e0456a4209a329e44","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f30fdc1e0456a4209a329e44/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[533,534,535,536,537,538,539,540],"take":"subject3/h2/1/cam4","frame_ids":[533,534,535,536,537,538,539,540]} +{"filtered_tile_id":"f30fdc1e0456a4209a329e44:48","filtered_window_id":"f30fdc1e0456a4209a329e44","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f30fdc1e0456a4209a329e44/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject3/h2/1/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"f30fdc1e0456a4209a329e44:52","filtered_window_id":"f30fdc1e0456a4209a329e44","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f30fdc1e0456a4209a329e44/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[545,546,547,548,549,550,551,552],"take":"subject3/h2/1/cam4","frame_ids":[545,546,547,548,549,550,551,552]} +{"filtered_tile_id":"f40e8334badb8a6390940125:0","filtered_window_id":"f40e8334badb8a6390940125","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f40e8334badb8a6390940125/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[417,418,419,420,421,422,423,424],"take":"subject2/h2/4/cam4","frame_ids":[417,418,419,420,421,422,423,424]} +{"filtered_tile_id":"f40e8334badb8a6390940125:8","filtered_window_id":"f40e8334badb8a6390940125","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f40e8334badb8a6390940125/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[425,426,427,428,429,430,431,432],"take":"subject2/h2/4/cam4","frame_ids":[425,426,427,428,429,430,431,432]} +{"filtered_tile_id":"f40e8334badb8a6390940125:12","filtered_window_id":"f40e8334badb8a6390940125","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f40e8334badb8a6390940125/native_gt.npz","filtered_start_offset":12,"expected_frame_ids":[429,430,431,432,433,434,435,436],"take":"subject2/h2/4/cam4","frame_ids":[429,430,431,432,433,434,435,436]} +{"filtered_tile_id":"f430e7157ceec9d50aeab695:0","filtered_window_id":"f430e7157ceec9d50aeab695","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f430e7157ceec9d50aeab695/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/o2/6/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"f430e7157ceec9d50aeab695:8","filtered_window_id":"f430e7157ceec9d50aeab695","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f430e7157ceec9d50aeab695/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/o2/6/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"f430e7157ceec9d50aeab695:16","filtered_window_id":"f430e7157ceec9d50aeab695","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f430e7157ceec9d50aeab695/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/o2/6/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"f430e7157ceec9d50aeab695:24","filtered_window_id":"f430e7157ceec9d50aeab695","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f430e7157ceec9d50aeab695/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/o2/6/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"f430e7157ceec9d50aeab695:32","filtered_window_id":"f430e7157ceec9d50aeab695","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f430e7157ceec9d50aeab695/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/o2/6/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"f430e7157ceec9d50aeab695:40","filtered_window_id":"f430e7157ceec9d50aeab695","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f430e7157ceec9d50aeab695/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/o2/6/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"f430e7157ceec9d50aeab695:48","filtered_window_id":"f430e7157ceec9d50aeab695","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f430e7157ceec9d50aeab695/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[56,57,58,59,60,61,62,63],"take":"subject2/o2/6/cam4","frame_ids":[56,57,58,59,60,61,62,63]} +{"filtered_tile_id":"f430e7157ceec9d50aeab695:52","filtered_window_id":"f430e7157ceec9d50aeab695","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f430e7157ceec9d50aeab695/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject2/o2/6/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"f4a70b8c9337397780dae0b5:0","filtered_window_id":"f4a70b8c9337397780dae0b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4a70b8c9337397780dae0b5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject2/h2/0/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"f4a70b8c9337397780dae0b5:8","filtered_window_id":"f4a70b8c9337397780dae0b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4a70b8c9337397780dae0b5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject2/h2/0/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"f4a70b8c9337397780dae0b5:16","filtered_window_id":"f4a70b8c9337397780dae0b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4a70b8c9337397780dae0b5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject2/h2/0/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"f4a70b8c9337397780dae0b5:24","filtered_window_id":"f4a70b8c9337397780dae0b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4a70b8c9337397780dae0b5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[198,199,200,201,202,203,204,205],"take":"subject2/h2/0/cam4","frame_ids":[198,199,200,201,202,203,204,205]} +{"filtered_tile_id":"f4a70b8c9337397780dae0b5:32","filtered_window_id":"f4a70b8c9337397780dae0b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4a70b8c9337397780dae0b5/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[206,207,208,209,210,211,212,213],"take":"subject2/h2/0/cam4","frame_ids":[206,207,208,209,210,211,212,213]} +{"filtered_tile_id":"f4a70b8c9337397780dae0b5:40","filtered_window_id":"f4a70b8c9337397780dae0b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4a70b8c9337397780dae0b5/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[214,215,216,217,218,219,220,221],"take":"subject2/h2/0/cam4","frame_ids":[214,215,216,217,218,219,220,221]} +{"filtered_tile_id":"f4a70b8c9337397780dae0b5:48","filtered_window_id":"f4a70b8c9337397780dae0b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4a70b8c9337397780dae0b5/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[222,223,224,225,226,227,228,229],"take":"subject2/h2/0/cam4","frame_ids":[222,223,224,225,226,227,228,229]} +{"filtered_tile_id":"f4a70b8c9337397780dae0b5:52","filtered_window_id":"f4a70b8c9337397780dae0b5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4a70b8c9337397780dae0b5/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[226,227,228,229,230,231,232,233],"take":"subject2/h2/0/cam4","frame_ids":[226,227,228,229,230,231,232,233]} +{"filtered_tile_id":"f4ecd5accef72503bdf9b2ea:0","filtered_window_id":"f4ecd5accef72503bdf9b2ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4ecd5accef72503bdf9b2ea/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[541,542,543,544,545,546,547,548],"take":"subject3/h1/7/cam4","frame_ids":[541,542,543,544,545,546,547,548]} +{"filtered_tile_id":"f4ecd5accef72503bdf9b2ea:8","filtered_window_id":"f4ecd5accef72503bdf9b2ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4ecd5accef72503bdf9b2ea/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[549,550,551,552,553,554,555,556],"take":"subject3/h1/7/cam4","frame_ids":[549,550,551,552,553,554,555,556]} +{"filtered_tile_id":"f4ecd5accef72503bdf9b2ea:16","filtered_window_id":"f4ecd5accef72503bdf9b2ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4ecd5accef72503bdf9b2ea/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[557,558,559,560,561,562,563,564],"take":"subject3/h1/7/cam4","frame_ids":[557,558,559,560,561,562,563,564]} +{"filtered_tile_id":"f4ecd5accef72503bdf9b2ea:24","filtered_window_id":"f4ecd5accef72503bdf9b2ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4ecd5accef72503bdf9b2ea/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[565,566,567,568,569,570,571,572],"take":"subject3/h1/7/cam4","frame_ids":[565,566,567,568,569,570,571,572]} +{"filtered_tile_id":"f4ecd5accef72503bdf9b2ea:32","filtered_window_id":"f4ecd5accef72503bdf9b2ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4ecd5accef72503bdf9b2ea/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[573,574,575,576,577,578,579,580],"take":"subject3/h1/7/cam4","frame_ids":[573,574,575,576,577,578,579,580]} +{"filtered_tile_id":"f4ecd5accef72503bdf9b2ea:40","filtered_window_id":"f4ecd5accef72503bdf9b2ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4ecd5accef72503bdf9b2ea/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[581,582,583,584,585,586,587,588],"take":"subject3/h1/7/cam4","frame_ids":[581,582,583,584,585,586,587,588]} +{"filtered_tile_id":"f4ecd5accef72503bdf9b2ea:48","filtered_window_id":"f4ecd5accef72503bdf9b2ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4ecd5accef72503bdf9b2ea/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[589,590,591,592,593,594,595,596],"take":"subject3/h1/7/cam4","frame_ids":[589,590,591,592,593,594,595,596]} +{"filtered_tile_id":"f4ecd5accef72503bdf9b2ea:52","filtered_window_id":"f4ecd5accef72503bdf9b2ea","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f4ecd5accef72503bdf9b2ea/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[593,594,595,596,597,598,599,600],"take":"subject3/h1/7/cam4","frame_ids":[593,594,595,596,597,598,599,600]} +{"filtered_tile_id":"f51929bcf7cb18b88fa94a43:0","filtered_window_id":"f51929bcf7cb18b88fa94a43","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f51929bcf7cb18b88fa94a43/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[417,418,419,420,421,422,423,424],"take":"subject3/h1/4/cam4","frame_ids":[417,418,419,420,421,422,423,424]} +{"filtered_tile_id":"f51929bcf7cb18b88fa94a43:5","filtered_window_id":"f51929bcf7cb18b88fa94a43","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f51929bcf7cb18b88fa94a43/native_gt.npz","filtered_start_offset":5,"expected_frame_ids":[422,423,424,425,426,427,428,429],"take":"subject3/h1/4/cam4","frame_ids":[422,423,424,425,426,427,428,429]} +{"filtered_tile_id":"f537e4631f0428d2db58c368:0","filtered_window_id":"f537e4631f0428d2db58c368","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f537e4631f0428d2db58c368/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/h2/6/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"f537e4631f0428d2db58c368:8","filtered_window_id":"f537e4631f0428d2db58c368","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f537e4631f0428d2db58c368/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject2/h2/6/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"f537e4631f0428d2db58c368:16","filtered_window_id":"f537e4631f0428d2db58c368","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f537e4631f0428d2db58c368/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject2/h2/6/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"f537e4631f0428d2db58c368:24","filtered_window_id":"f537e4631f0428d2db58c368","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f537e4631f0428d2db58c368/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject2/h2/6/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"f537e4631f0428d2db58c368:32","filtered_window_id":"f537e4631f0428d2db58c368","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f537e4631f0428d2db58c368/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject2/h2/6/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"f537e4631f0428d2db58c368:40","filtered_window_id":"f537e4631f0428d2db58c368","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f537e4631f0428d2db58c368/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject2/h2/6/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"f537e4631f0428d2db58c368:48","filtered_window_id":"f537e4631f0428d2db58c368","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f537e4631f0428d2db58c368/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject2/h2/6/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"f537e4631f0428d2db58c368:52","filtered_window_id":"f537e4631f0428d2db58c368","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f537e4631f0428d2db58c368/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject2/h2/6/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"f545d880efbfda41071c585d:0","filtered_window_id":"f545d880efbfda41071c585d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f545d880efbfda41071c585d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[221,222,223,224,225,226,227,228],"take":"subject2/h1/5/cam4","frame_ids":[221,222,223,224,225,226,227,228]} +{"filtered_tile_id":"f545d880efbfda41071c585d:8","filtered_window_id":"f545d880efbfda41071c585d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f545d880efbfda41071c585d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[229,230,231,232,233,234,235,236],"take":"subject2/h1/5/cam4","frame_ids":[229,230,231,232,233,234,235,236]} +{"filtered_tile_id":"f545d880efbfda41071c585d:16","filtered_window_id":"f545d880efbfda41071c585d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f545d880efbfda41071c585d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[237,238,239,240,241,242,243,244],"take":"subject2/h1/5/cam4","frame_ids":[237,238,239,240,241,242,243,244]} +{"filtered_tile_id":"f545d880efbfda41071c585d:24","filtered_window_id":"f545d880efbfda41071c585d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f545d880efbfda41071c585d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[245,246,247,248,249,250,251,252],"take":"subject2/h1/5/cam4","frame_ids":[245,246,247,248,249,250,251,252]} +{"filtered_tile_id":"f545d880efbfda41071c585d:32","filtered_window_id":"f545d880efbfda41071c585d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f545d880efbfda41071c585d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[253,254,255,256,257,258,259,260],"take":"subject2/h1/5/cam4","frame_ids":[253,254,255,256,257,258,259,260]} +{"filtered_tile_id":"f545d880efbfda41071c585d:40","filtered_window_id":"f545d880efbfda41071c585d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f545d880efbfda41071c585d/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject2/h1/5/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"f545d880efbfda41071c585d:48","filtered_window_id":"f545d880efbfda41071c585d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f545d880efbfda41071c585d/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[269,270,271,272,273,274,275,276],"take":"subject2/h1/5/cam4","frame_ids":[269,270,271,272,273,274,275,276]} +{"filtered_tile_id":"f545d880efbfda41071c585d:49","filtered_window_id":"f545d880efbfda41071c585d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f545d880efbfda41071c585d/native_gt.npz","filtered_start_offset":49,"expected_frame_ids":[270,271,272,273,274,275,276,277],"take":"subject2/h1/5/cam4","frame_ids":[270,271,272,273,274,275,276,277]} +{"filtered_tile_id":"f555377fa6ebb3e641321cc9:0","filtered_window_id":"f555377fa6ebb3e641321cc9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f555377fa6ebb3e641321cc9/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[568,569,570,571,572,573,574,575],"take":"subject2/h1/7/cam4","frame_ids":[568,569,570,571,572,573,574,575]} +{"filtered_tile_id":"f555377fa6ebb3e641321cc9:8","filtered_window_id":"f555377fa6ebb3e641321cc9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f555377fa6ebb3e641321cc9/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[576,577,578,579,580,581,582,583],"take":"subject2/h1/7/cam4","frame_ids":[576,577,578,579,580,581,582,583]} +{"filtered_tile_id":"f555377fa6ebb3e641321cc9:16","filtered_window_id":"f555377fa6ebb3e641321cc9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f555377fa6ebb3e641321cc9/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[584,585,586,587,588,589,590,591],"take":"subject2/h1/7/cam4","frame_ids":[584,585,586,587,588,589,590,591]} +{"filtered_tile_id":"f555377fa6ebb3e641321cc9:24","filtered_window_id":"f555377fa6ebb3e641321cc9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f555377fa6ebb3e641321cc9/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[592,593,594,595,596,597,598,599],"take":"subject2/h1/7/cam4","frame_ids":[592,593,594,595,596,597,598,599]} +{"filtered_tile_id":"f555377fa6ebb3e641321cc9:32","filtered_window_id":"f555377fa6ebb3e641321cc9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f555377fa6ebb3e641321cc9/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[600,601,602,603,604,605,606,607],"take":"subject2/h1/7/cam4","frame_ids":[600,601,602,603,604,605,606,607]} +{"filtered_tile_id":"f555377fa6ebb3e641321cc9:39","filtered_window_id":"f555377fa6ebb3e641321cc9","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f555377fa6ebb3e641321cc9/native_gt.npz","filtered_start_offset":39,"expected_frame_ids":[607,608,609,610,611,612,613,614],"take":"subject2/h1/7/cam4","frame_ids":[607,608,609,610,611,612,613,614]} +{"filtered_tile_id":"f590c12f8e00d687926d5aac:0","filtered_window_id":"f590c12f8e00d687926d5aac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f590c12f8e00d687926d5aac/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[280,281,282,283,284,285,286,287],"take":"subject3/k1/2/cam4","frame_ids":[280,281,282,283,284,285,286,287]} +{"filtered_tile_id":"f590c12f8e00d687926d5aac:8","filtered_window_id":"f590c12f8e00d687926d5aac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f590c12f8e00d687926d5aac/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[288,289,290,291,292,293,294,295],"take":"subject3/k1/2/cam4","frame_ids":[288,289,290,291,292,293,294,295]} +{"filtered_tile_id":"f590c12f8e00d687926d5aac:16","filtered_window_id":"f590c12f8e00d687926d5aac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f590c12f8e00d687926d5aac/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[296,297,298,299,300,301,302,303],"take":"subject3/k1/2/cam4","frame_ids":[296,297,298,299,300,301,302,303]} +{"filtered_tile_id":"f590c12f8e00d687926d5aac:24","filtered_window_id":"f590c12f8e00d687926d5aac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f590c12f8e00d687926d5aac/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[304,305,306,307,308,309,310,311],"take":"subject3/k1/2/cam4","frame_ids":[304,305,306,307,308,309,310,311]} +{"filtered_tile_id":"f590c12f8e00d687926d5aac:32","filtered_window_id":"f590c12f8e00d687926d5aac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f590c12f8e00d687926d5aac/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[312,313,314,315,316,317,318,319],"take":"subject3/k1/2/cam4","frame_ids":[312,313,314,315,316,317,318,319]} +{"filtered_tile_id":"f590c12f8e00d687926d5aac:40","filtered_window_id":"f590c12f8e00d687926d5aac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f590c12f8e00d687926d5aac/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[320,321,322,323,324,325,326,327],"take":"subject3/k1/2/cam4","frame_ids":[320,321,322,323,324,325,326,327]} +{"filtered_tile_id":"f590c12f8e00d687926d5aac:47","filtered_window_id":"f590c12f8e00d687926d5aac","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f590c12f8e00d687926d5aac/native_gt.npz","filtered_start_offset":47,"expected_frame_ids":[327,328,329,330,331,332,333,334],"take":"subject3/k1/2/cam4","frame_ids":[327,328,329,330,331,332,333,334]} +{"filtered_tile_id":"f59288c5b101148c44f5054b:0","filtered_window_id":"f59288c5b101148c44f5054b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f59288c5b101148c44f5054b/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[441,442,443,444,445,446,447,448],"take":"subject2/h2/6/cam4","frame_ids":[441,442,443,444,445,446,447,448]} +{"filtered_tile_id":"f59288c5b101148c44f5054b:8","filtered_window_id":"f59288c5b101148c44f5054b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f59288c5b101148c44f5054b/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[449,450,451,452,453,454,455,456],"take":"subject2/h2/6/cam4","frame_ids":[449,450,451,452,453,454,455,456]} +{"filtered_tile_id":"f59288c5b101148c44f5054b:16","filtered_window_id":"f59288c5b101148c44f5054b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f59288c5b101148c44f5054b/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[457,458,459,460,461,462,463,464],"take":"subject2/h2/6/cam4","frame_ids":[457,458,459,460,461,462,463,464]} +{"filtered_tile_id":"f59288c5b101148c44f5054b:24","filtered_window_id":"f59288c5b101148c44f5054b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f59288c5b101148c44f5054b/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[465,466,467,468,469,470,471,472],"take":"subject2/h2/6/cam4","frame_ids":[465,466,467,468,469,470,471,472]} +{"filtered_tile_id":"f59288c5b101148c44f5054b:32","filtered_window_id":"f59288c5b101148c44f5054b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f59288c5b101148c44f5054b/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[473,474,475,476,477,478,479,480],"take":"subject2/h2/6/cam4","frame_ids":[473,474,475,476,477,478,479,480]} +{"filtered_tile_id":"f59288c5b101148c44f5054b:40","filtered_window_id":"f59288c5b101148c44f5054b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f59288c5b101148c44f5054b/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[481,482,483,484,485,486,487,488],"take":"subject2/h2/6/cam4","frame_ids":[481,482,483,484,485,486,487,488]} +{"filtered_tile_id":"f59288c5b101148c44f5054b:48","filtered_window_id":"f59288c5b101148c44f5054b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f59288c5b101148c44f5054b/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[489,490,491,492,493,494,495,496],"take":"subject2/h2/6/cam4","frame_ids":[489,490,491,492,493,494,495,496]} +{"filtered_tile_id":"f59288c5b101148c44f5054b:52","filtered_window_id":"f59288c5b101148c44f5054b","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f59288c5b101148c44f5054b/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[493,494,495,496,497,498,499,500],"take":"subject2/h2/6/cam4","frame_ids":[493,494,495,496,497,498,499,500]} +{"filtered_tile_id":"f60190d54987d6cbc29852ae:0","filtered_window_id":"f60190d54987d6cbc29852ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f60190d54987d6cbc29852ae/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[59,60,61,62,63,64,65,66],"take":"subject1/h1/4/cam4","frame_ids":[59,60,61,62,63,64,65,66]} +{"filtered_tile_id":"f60190d54987d6cbc29852ae:8","filtered_window_id":"f60190d54987d6cbc29852ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f60190d54987d6cbc29852ae/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject1/h1/4/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"f60190d54987d6cbc29852ae:16","filtered_window_id":"f60190d54987d6cbc29852ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f60190d54987d6cbc29852ae/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject1/h1/4/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"f60190d54987d6cbc29852ae:24","filtered_window_id":"f60190d54987d6cbc29852ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f60190d54987d6cbc29852ae/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject1/h1/4/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"f60190d54987d6cbc29852ae:32","filtered_window_id":"f60190d54987d6cbc29852ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f60190d54987d6cbc29852ae/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject1/h1/4/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"f60190d54987d6cbc29852ae:40","filtered_window_id":"f60190d54987d6cbc29852ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f60190d54987d6cbc29852ae/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject1/h1/4/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"f60190d54987d6cbc29852ae:48","filtered_window_id":"f60190d54987d6cbc29852ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f60190d54987d6cbc29852ae/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject1/h1/4/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"f60190d54987d6cbc29852ae:52","filtered_window_id":"f60190d54987d6cbc29852ae","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f60190d54987d6cbc29852ae/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[111,112,113,114,115,116,117,118],"take":"subject1/h1/4/cam4","frame_ids":[111,112,113,114,115,116,117,118]} +{"filtered_tile_id":"f6877eecc52747271a8b546c:0","filtered_window_id":"f6877eecc52747271a8b546c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6877eecc52747271a8b546c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[538,539,540,541,542,543,544,545],"take":"subject1/h1/4/cam4","frame_ids":[538,539,540,541,542,543,544,545]} +{"filtered_tile_id":"f6877eecc52747271a8b546c:8","filtered_window_id":"f6877eecc52747271a8b546c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6877eecc52747271a8b546c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[546,547,548,549,550,551,552,553],"take":"subject1/h1/4/cam4","frame_ids":[546,547,548,549,550,551,552,553]} +{"filtered_tile_id":"f6877eecc52747271a8b546c:16","filtered_window_id":"f6877eecc52747271a8b546c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6877eecc52747271a8b546c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[554,555,556,557,558,559,560,561],"take":"subject1/h1/4/cam4","frame_ids":[554,555,556,557,558,559,560,561]} +{"filtered_tile_id":"f6877eecc52747271a8b546c:24","filtered_window_id":"f6877eecc52747271a8b546c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6877eecc52747271a8b546c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[562,563,564,565,566,567,568,569],"take":"subject1/h1/4/cam4","frame_ids":[562,563,564,565,566,567,568,569]} +{"filtered_tile_id":"f6877eecc52747271a8b546c:32","filtered_window_id":"f6877eecc52747271a8b546c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6877eecc52747271a8b546c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[570,571,572,573,574,575,576,577],"take":"subject1/h1/4/cam4","frame_ids":[570,571,572,573,574,575,576,577]} +{"filtered_tile_id":"f6877eecc52747271a8b546c:40","filtered_window_id":"f6877eecc52747271a8b546c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6877eecc52747271a8b546c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[578,579,580,581,582,583,584,585],"take":"subject1/h1/4/cam4","frame_ids":[578,579,580,581,582,583,584,585]} +{"filtered_tile_id":"f6877eecc52747271a8b546c:41","filtered_window_id":"f6877eecc52747271a8b546c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6877eecc52747271a8b546c/native_gt.npz","filtered_start_offset":41,"expected_frame_ids":[579,580,581,582,583,584,585,586],"take":"subject1/h1/4/cam4","frame_ids":[579,580,581,582,583,584,585,586]} +{"filtered_tile_id":"f6bb47143450b8e103744762:0","filtered_window_id":"f6bb47143450b8e103744762","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6bb47143450b8e103744762/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[233,234,235,236,237,238,239,240],"take":"subject2/h1/1/cam4","frame_ids":[233,234,235,236,237,238,239,240]} +{"filtered_tile_id":"f6bb47143450b8e103744762:8","filtered_window_id":"f6bb47143450b8e103744762","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6bb47143450b8e103744762/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[241,242,243,244,245,246,247,248],"take":"subject2/h1/1/cam4","frame_ids":[241,242,243,244,245,246,247,248]} +{"filtered_tile_id":"f6bb47143450b8e103744762:16","filtered_window_id":"f6bb47143450b8e103744762","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6bb47143450b8e103744762/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[249,250,251,252,253,254,255,256],"take":"subject2/h1/1/cam4","frame_ids":[249,250,251,252,253,254,255,256]} +{"filtered_tile_id":"f6bb47143450b8e103744762:24","filtered_window_id":"f6bb47143450b8e103744762","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6bb47143450b8e103744762/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[257,258,259,260,261,262,263,264],"take":"subject2/h1/1/cam4","frame_ids":[257,258,259,260,261,262,263,264]} +{"filtered_tile_id":"f6bb47143450b8e103744762:28","filtered_window_id":"f6bb47143450b8e103744762","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f6bb47143450b8e103744762/native_gt.npz","filtered_start_offset":28,"expected_frame_ids":[261,262,263,264,265,266,267,268],"take":"subject2/h1/1/cam4","frame_ids":[261,262,263,264,265,266,267,268]} +{"filtered_tile_id":"f73a04eb182dc1ea0114738c:0","filtered_window_id":"f73a04eb182dc1ea0114738c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f73a04eb182dc1ea0114738c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[168,169,170,171,172,173,174,175],"take":"subject1/o1/4/cam4","frame_ids":[168,169,170,171,172,173,174,175]} +{"filtered_tile_id":"f73a04eb182dc1ea0114738c:8","filtered_window_id":"f73a04eb182dc1ea0114738c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f73a04eb182dc1ea0114738c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[176,177,178,179,180,181,182,183],"take":"subject1/o1/4/cam4","frame_ids":[176,177,178,179,180,181,182,183]} +{"filtered_tile_id":"f73a04eb182dc1ea0114738c:16","filtered_window_id":"f73a04eb182dc1ea0114738c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f73a04eb182dc1ea0114738c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[184,185,186,187,188,189,190,191],"take":"subject1/o1/4/cam4","frame_ids":[184,185,186,187,188,189,190,191]} +{"filtered_tile_id":"f73a04eb182dc1ea0114738c:24","filtered_window_id":"f73a04eb182dc1ea0114738c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f73a04eb182dc1ea0114738c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[192,193,194,195,196,197,198,199],"take":"subject1/o1/4/cam4","frame_ids":[192,193,194,195,196,197,198,199]} +{"filtered_tile_id":"f7ff0c6c270906d00dcfe3bb:0","filtered_window_id":"f7ff0c6c270906d00dcfe3bb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f7ff0c6c270906d00dcfe3bb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[676,677,678,679,680,681,682,683],"take":"subject3/h1/3/cam4","frame_ids":[676,677,678,679,680,681,682,683]} +{"filtered_tile_id":"f7ff0c6c270906d00dcfe3bb:8","filtered_window_id":"f7ff0c6c270906d00dcfe3bb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f7ff0c6c270906d00dcfe3bb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[684,685,686,687,688,689,690,691],"take":"subject3/h1/3/cam4","frame_ids":[684,685,686,687,688,689,690,691]} +{"filtered_tile_id":"f7ff0c6c270906d00dcfe3bb:10","filtered_window_id":"f7ff0c6c270906d00dcfe3bb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f7ff0c6c270906d00dcfe3bb/native_gt.npz","filtered_start_offset":10,"expected_frame_ids":[686,687,688,689,690,691,692,693],"take":"subject3/h1/3/cam4","frame_ids":[686,687,688,689,690,691,692,693]} +{"filtered_tile_id":"f88add63376e29f24cf3b0b4:0","filtered_window_id":"f88add63376e29f24cf3b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f88add63376e29f24cf3b0b4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h2/7/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"f88add63376e29f24cf3b0b4:8","filtered_window_id":"f88add63376e29f24cf3b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f88add63376e29f24cf3b0b4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h2/7/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"f88add63376e29f24cf3b0b4:16","filtered_window_id":"f88add63376e29f24cf3b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f88add63376e29f24cf3b0b4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h2/7/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"f88add63376e29f24cf3b0b4:24","filtered_window_id":"f88add63376e29f24cf3b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f88add63376e29f24cf3b0b4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h2/7/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"f88add63376e29f24cf3b0b4:32","filtered_window_id":"f88add63376e29f24cf3b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f88add63376e29f24cf3b0b4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h2/7/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"f88add63376e29f24cf3b0b4:37","filtered_window_id":"f88add63376e29f24cf3b0b4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f88add63376e29f24cf3b0b4/native_gt.npz","filtered_start_offset":37,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject1/h2/7/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"f8a2c8f3c0eb87864a5861d0:0","filtered_window_id":"f8a2c8f3c0eb87864a5861d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f8a2c8f3c0eb87864a5861d0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[242,243,244,245,246,247,248,249],"take":"subject2/h1/0/cam4","frame_ids":[242,243,244,245,246,247,248,249]} +{"filtered_tile_id":"f8a2c8f3c0eb87864a5861d0:8","filtered_window_id":"f8a2c8f3c0eb87864a5861d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f8a2c8f3c0eb87864a5861d0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[250,251,252,253,254,255,256,257],"take":"subject2/h1/0/cam4","frame_ids":[250,251,252,253,254,255,256,257]} +{"filtered_tile_id":"f8a2c8f3c0eb87864a5861d0:16","filtered_window_id":"f8a2c8f3c0eb87864a5861d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f8a2c8f3c0eb87864a5861d0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[258,259,260,261,262,263,264,265],"take":"subject2/h1/0/cam4","frame_ids":[258,259,260,261,262,263,264,265]} +{"filtered_tile_id":"f8a2c8f3c0eb87864a5861d0:24","filtered_window_id":"f8a2c8f3c0eb87864a5861d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f8a2c8f3c0eb87864a5861d0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject2/h1/0/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"f8a2c8f3c0eb87864a5861d0:28","filtered_window_id":"f8a2c8f3c0eb87864a5861d0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f8a2c8f3c0eb87864a5861d0/native_gt.npz","filtered_start_offset":28,"expected_frame_ids":[270,271,272,273,274,275,276,277],"take":"subject2/h1/0/cam4","frame_ids":[270,271,272,273,274,275,276,277]} +{"filtered_tile_id":"f8c3f23509073077988c1b09:0","filtered_window_id":"f8c3f23509073077988c1b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f8c3f23509073077988c1b09/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[271,272,273,274,275,276,277,278],"take":"subject3/h2/7/cam4","frame_ids":[271,272,273,274,275,276,277,278]} +{"filtered_tile_id":"f8c3f23509073077988c1b09:5","filtered_window_id":"f8c3f23509073077988c1b09","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f8c3f23509073077988c1b09/native_gt.npz","filtered_start_offset":5,"expected_frame_ids":[276,277,278,279,280,281,282,283],"take":"subject3/h2/7/cam4","frame_ids":[276,277,278,279,280,281,282,283]} +{"filtered_tile_id":"f92951f01827355fc67d6d23:0","filtered_window_id":"f92951f01827355fc67d6d23","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f92951f01827355fc67d6d23/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[284,285,286,287,288,289,290,291],"take":"subject1/k2/3/cam4","frame_ids":[284,285,286,287,288,289,290,291]} +{"filtered_tile_id":"f92951f01827355fc67d6d23:8","filtered_window_id":"f92951f01827355fc67d6d23","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f92951f01827355fc67d6d23/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[292,293,294,295,296,297,298,299],"take":"subject1/k2/3/cam4","frame_ids":[292,293,294,295,296,297,298,299]} +{"filtered_tile_id":"f92951f01827355fc67d6d23:16","filtered_window_id":"f92951f01827355fc67d6d23","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f92951f01827355fc67d6d23/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[300,301,302,303,304,305,306,307],"take":"subject1/k2/3/cam4","frame_ids":[300,301,302,303,304,305,306,307]} +{"filtered_tile_id":"f92951f01827355fc67d6d23:24","filtered_window_id":"f92951f01827355fc67d6d23","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f92951f01827355fc67d6d23/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[308,309,310,311,312,313,314,315],"take":"subject1/k2/3/cam4","frame_ids":[308,309,310,311,312,313,314,315]} +{"filtered_tile_id":"f92951f01827355fc67d6d23:32","filtered_window_id":"f92951f01827355fc67d6d23","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f92951f01827355fc67d6d23/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[316,317,318,319,320,321,322,323],"take":"subject1/k2/3/cam4","frame_ids":[316,317,318,319,320,321,322,323]} +{"filtered_tile_id":"f92951f01827355fc67d6d23:40","filtered_window_id":"f92951f01827355fc67d6d23","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f92951f01827355fc67d6d23/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[324,325,326,327,328,329,330,331],"take":"subject1/k2/3/cam4","frame_ids":[324,325,326,327,328,329,330,331]} +{"filtered_tile_id":"f92951f01827355fc67d6d23:48","filtered_window_id":"f92951f01827355fc67d6d23","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f92951f01827355fc67d6d23/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[332,333,334,335,336,337,338,339],"take":"subject1/k2/3/cam4","frame_ids":[332,333,334,335,336,337,338,339]} +{"filtered_tile_id":"f92951f01827355fc67d6d23:52","filtered_window_id":"f92951f01827355fc67d6d23","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f92951f01827355fc67d6d23/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[336,337,338,339,340,341,342,343],"take":"subject1/k2/3/cam4","frame_ids":[336,337,338,339,340,341,342,343]} +{"filtered_tile_id":"f97dffb16f6684db8cfa2340:0","filtered_window_id":"f97dffb16f6684db8cfa2340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f97dffb16f6684db8cfa2340/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[60,61,62,63,64,65,66,67],"take":"subject1/k2/4/cam4","frame_ids":[60,61,62,63,64,65,66,67]} +{"filtered_tile_id":"f97dffb16f6684db8cfa2340:8","filtered_window_id":"f97dffb16f6684db8cfa2340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f97dffb16f6684db8cfa2340/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[68,69,70,71,72,73,74,75],"take":"subject1/k2/4/cam4","frame_ids":[68,69,70,71,72,73,74,75]} +{"filtered_tile_id":"f97dffb16f6684db8cfa2340:16","filtered_window_id":"f97dffb16f6684db8cfa2340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f97dffb16f6684db8cfa2340/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[76,77,78,79,80,81,82,83],"take":"subject1/k2/4/cam4","frame_ids":[76,77,78,79,80,81,82,83]} +{"filtered_tile_id":"f97dffb16f6684db8cfa2340:24","filtered_window_id":"f97dffb16f6684db8cfa2340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f97dffb16f6684db8cfa2340/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[84,85,86,87,88,89,90,91],"take":"subject1/k2/4/cam4","frame_ids":[84,85,86,87,88,89,90,91]} +{"filtered_tile_id":"f97dffb16f6684db8cfa2340:32","filtered_window_id":"f97dffb16f6684db8cfa2340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f97dffb16f6684db8cfa2340/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[92,93,94,95,96,97,98,99],"take":"subject1/k2/4/cam4","frame_ids":[92,93,94,95,96,97,98,99]} +{"filtered_tile_id":"f97dffb16f6684db8cfa2340:40","filtered_window_id":"f97dffb16f6684db8cfa2340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f97dffb16f6684db8cfa2340/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[100,101,102,103,104,105,106,107],"take":"subject1/k2/4/cam4","frame_ids":[100,101,102,103,104,105,106,107]} +{"filtered_tile_id":"f97dffb16f6684db8cfa2340:48","filtered_window_id":"f97dffb16f6684db8cfa2340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f97dffb16f6684db8cfa2340/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[108,109,110,111,112,113,114,115],"take":"subject1/k2/4/cam4","frame_ids":[108,109,110,111,112,113,114,115]} +{"filtered_tile_id":"f97dffb16f6684db8cfa2340:52","filtered_window_id":"f97dffb16f6684db8cfa2340","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/f97dffb16f6684db8cfa2340/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[112,113,114,115,116,117,118,119],"take":"subject1/k2/4/cam4","frame_ids":[112,113,114,115,116,117,118,119]} +{"filtered_tile_id":"fa06c8686d54183377689ffb:0","filtered_window_id":"fa06c8686d54183377689ffb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa06c8686d54183377689ffb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[13,14,15,16,17,18,19,20],"take":"subject3/k1/1/cam4","frame_ids":[13,14,15,16,17,18,19,20]} +{"filtered_tile_id":"fa06c8686d54183377689ffb:8","filtered_window_id":"fa06c8686d54183377689ffb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa06c8686d54183377689ffb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[21,22,23,24,25,26,27,28],"take":"subject3/k1/1/cam4","frame_ids":[21,22,23,24,25,26,27,28]} +{"filtered_tile_id":"fa06c8686d54183377689ffb:16","filtered_window_id":"fa06c8686d54183377689ffb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa06c8686d54183377689ffb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[29,30,31,32,33,34,35,36],"take":"subject3/k1/1/cam4","frame_ids":[29,30,31,32,33,34,35,36]} +{"filtered_tile_id":"fa06c8686d54183377689ffb:24","filtered_window_id":"fa06c8686d54183377689ffb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa06c8686d54183377689ffb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject3/k1/1/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"fa06c8686d54183377689ffb:32","filtered_window_id":"fa06c8686d54183377689ffb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa06c8686d54183377689ffb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject3/k1/1/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"fa06c8686d54183377689ffb:40","filtered_window_id":"fa06c8686d54183377689ffb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa06c8686d54183377689ffb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[53,54,55,56,57,58,59,60],"take":"subject3/k1/1/cam4","frame_ids":[53,54,55,56,57,58,59,60]} +{"filtered_tile_id":"fa06c8686d54183377689ffb:48","filtered_window_id":"fa06c8686d54183377689ffb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa06c8686d54183377689ffb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[61,62,63,64,65,66,67,68],"take":"subject3/k1/1/cam4","frame_ids":[61,62,63,64,65,66,67,68]} +{"filtered_tile_id":"fa06c8686d54183377689ffb:52","filtered_window_id":"fa06c8686d54183377689ffb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa06c8686d54183377689ffb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[65,66,67,68,69,70,71,72],"take":"subject3/k1/1/cam4","frame_ids":[65,66,67,68,69,70,71,72]} +{"filtered_tile_id":"fa44601f2dee4d1517d13348:0","filtered_window_id":"fa44601f2dee4d1517d13348","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa44601f2dee4d1517d13348/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[69,70,71,72,73,74,75,76],"take":"subject2/k2/0/cam4","frame_ids":[69,70,71,72,73,74,75,76]} +{"filtered_tile_id":"fa44601f2dee4d1517d13348:5","filtered_window_id":"fa44601f2dee4d1517d13348","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa44601f2dee4d1517d13348/native_gt.npz","filtered_start_offset":5,"expected_frame_ids":[74,75,76,77,78,79,80,81],"take":"subject2/k2/0/cam4","frame_ids":[74,75,76,77,78,79,80,81]} +{"filtered_tile_id":"fa4948cee2db7d3e50615668:0","filtered_window_id":"fa4948cee2db7d3e50615668","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa4948cee2db7d3e50615668/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[80,81,82,83,84,85,86,87],"take":"subject2/h1/2/cam4","frame_ids":[80,81,82,83,84,85,86,87]} +{"filtered_tile_id":"fa4948cee2db7d3e50615668:8","filtered_window_id":"fa4948cee2db7d3e50615668","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa4948cee2db7d3e50615668/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[88,89,90,91,92,93,94,95],"take":"subject2/h1/2/cam4","frame_ids":[88,89,90,91,92,93,94,95]} +{"filtered_tile_id":"fa4948cee2db7d3e50615668:16","filtered_window_id":"fa4948cee2db7d3e50615668","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa4948cee2db7d3e50615668/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[96,97,98,99,100,101,102,103],"take":"subject2/h1/2/cam4","frame_ids":[96,97,98,99,100,101,102,103]} +{"filtered_tile_id":"fa4948cee2db7d3e50615668:24","filtered_window_id":"fa4948cee2db7d3e50615668","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa4948cee2db7d3e50615668/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[104,105,106,107,108,109,110,111],"take":"subject2/h1/2/cam4","frame_ids":[104,105,106,107,108,109,110,111]} +{"filtered_tile_id":"fa4948cee2db7d3e50615668:29","filtered_window_id":"fa4948cee2db7d3e50615668","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fa4948cee2db7d3e50615668/native_gt.npz","filtered_start_offset":29,"expected_frame_ids":[109,110,111,112,113,114,115,116],"take":"subject2/h1/2/cam4","frame_ids":[109,110,111,112,113,114,115,116]} +{"filtered_tile_id":"fac0bad5b6c391b024a1d2d4:0","filtered_window_id":"fac0bad5b6c391b024a1d2d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fac0bad5b6c391b024a1d2d4/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[142,143,144,145,146,147,148,149],"take":"subject1/o2/6/cam4","frame_ids":[142,143,144,145,146,147,148,149]} +{"filtered_tile_id":"fac0bad5b6c391b024a1d2d4:8","filtered_window_id":"fac0bad5b6c391b024a1d2d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fac0bad5b6c391b024a1d2d4/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[150,151,152,153,154,155,156,157],"take":"subject1/o2/6/cam4","frame_ids":[150,151,152,153,154,155,156,157]} +{"filtered_tile_id":"fac0bad5b6c391b024a1d2d4:16","filtered_window_id":"fac0bad5b6c391b024a1d2d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fac0bad5b6c391b024a1d2d4/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[158,159,160,161,162,163,164,165],"take":"subject1/o2/6/cam4","frame_ids":[158,159,160,161,162,163,164,165]} +{"filtered_tile_id":"fac0bad5b6c391b024a1d2d4:24","filtered_window_id":"fac0bad5b6c391b024a1d2d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fac0bad5b6c391b024a1d2d4/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[166,167,168,169,170,171,172,173],"take":"subject1/o2/6/cam4","frame_ids":[166,167,168,169,170,171,172,173]} +{"filtered_tile_id":"fac0bad5b6c391b024a1d2d4:32","filtered_window_id":"fac0bad5b6c391b024a1d2d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fac0bad5b6c391b024a1d2d4/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject1/o2/6/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"fac0bad5b6c391b024a1d2d4:40","filtered_window_id":"fac0bad5b6c391b024a1d2d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fac0bad5b6c391b024a1d2d4/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[182,183,184,185,186,187,188,189],"take":"subject1/o2/6/cam4","frame_ids":[182,183,184,185,186,187,188,189]} +{"filtered_tile_id":"fac0bad5b6c391b024a1d2d4:48","filtered_window_id":"fac0bad5b6c391b024a1d2d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fac0bad5b6c391b024a1d2d4/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[190,191,192,193,194,195,196,197],"take":"subject1/o2/6/cam4","frame_ids":[190,191,192,193,194,195,196,197]} +{"filtered_tile_id":"fac0bad5b6c391b024a1d2d4:52","filtered_window_id":"fac0bad5b6c391b024a1d2d4","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fac0bad5b6c391b024a1d2d4/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[194,195,196,197,198,199,200,201],"take":"subject1/o2/6/cam4","frame_ids":[194,195,196,197,198,199,200,201]} +{"filtered_tile_id":"fb26372f202e334074fdd64d:0","filtered_window_id":"fb26372f202e334074fdd64d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fb26372f202e334074fdd64d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[208,209,210,211,212,213,214,215],"take":"subject2/h2/2/cam4","frame_ids":[208,209,210,211,212,213,214,215]} +{"filtered_tile_id":"fb77fbe2ddf439a073b02adb:0","filtered_window_id":"fb77fbe2ddf439a073b02adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fb77fbe2ddf439a073b02adb/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[106,107,108,109,110,111,112,113],"take":"subject2/k1/4/cam4","frame_ids":[106,107,108,109,110,111,112,113]} +{"filtered_tile_id":"fb77fbe2ddf439a073b02adb:8","filtered_window_id":"fb77fbe2ddf439a073b02adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fb77fbe2ddf439a073b02adb/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[114,115,116,117,118,119,120,121],"take":"subject2/k1/4/cam4","frame_ids":[114,115,116,117,118,119,120,121]} +{"filtered_tile_id":"fb77fbe2ddf439a073b02adb:16","filtered_window_id":"fb77fbe2ddf439a073b02adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fb77fbe2ddf439a073b02adb/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject2/k1/4/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"fb77fbe2ddf439a073b02adb:24","filtered_window_id":"fb77fbe2ddf439a073b02adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fb77fbe2ddf439a073b02adb/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject2/k1/4/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"fb77fbe2ddf439a073b02adb:32","filtered_window_id":"fb77fbe2ddf439a073b02adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fb77fbe2ddf439a073b02adb/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject2/k1/4/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"fb77fbe2ddf439a073b02adb:40","filtered_window_id":"fb77fbe2ddf439a073b02adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fb77fbe2ddf439a073b02adb/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject2/k1/4/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"fb77fbe2ddf439a073b02adb:48","filtered_window_id":"fb77fbe2ddf439a073b02adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fb77fbe2ddf439a073b02adb/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject2/k1/4/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"fb77fbe2ddf439a073b02adb:52","filtered_window_id":"fb77fbe2ddf439a073b02adb","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fb77fbe2ddf439a073b02adb/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[158,159,160,161,162,163,164,165],"take":"subject2/k1/4/cam4","frame_ids":[158,159,160,161,162,163,164,165]} +{"filtered_tile_id":"fbc2491162de2a122f52f7c0:0","filtered_window_id":"fbc2491162de2a122f52f7c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fbc2491162de2a122f52f7c0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject3/h1/3/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"fbc2491162de2a122f52f7c0:8","filtered_window_id":"fbc2491162de2a122f52f7c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fbc2491162de2a122f52f7c0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject3/h1/3/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"fbc2491162de2a122f52f7c0:16","filtered_window_id":"fbc2491162de2a122f52f7c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fbc2491162de2a122f52f7c0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject3/h1/3/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"fbc2491162de2a122f52f7c0:24","filtered_window_id":"fbc2491162de2a122f52f7c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fbc2491162de2a122f52f7c0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject3/h1/3/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"fbc2491162de2a122f52f7c0:32","filtered_window_id":"fbc2491162de2a122f52f7c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fbc2491162de2a122f52f7c0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject3/h1/3/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"fbc2491162de2a122f52f7c0:40","filtered_window_id":"fbc2491162de2a122f52f7c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fbc2491162de2a122f52f7c0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[40,41,42,43,44,45,46,47],"take":"subject3/h1/3/cam4","frame_ids":[40,41,42,43,44,45,46,47]} +{"filtered_tile_id":"fbc2491162de2a122f52f7c0:48","filtered_window_id":"fbc2491162de2a122f52f7c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fbc2491162de2a122f52f7c0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[48,49,50,51,52,53,54,55],"take":"subject3/h1/3/cam4","frame_ids":[48,49,50,51,52,53,54,55]} +{"filtered_tile_id":"fbc2491162de2a122f52f7c0:52","filtered_window_id":"fbc2491162de2a122f52f7c0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fbc2491162de2a122f52f7c0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[52,53,54,55,56,57,58,59],"take":"subject3/h1/3/cam4","frame_ids":[52,53,54,55,56,57,58,59]} +{"filtered_tile_id":"fc3facd1a7ad8d2579be1c93:0","filtered_window_id":"fc3facd1a7ad8d2579be1c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc3facd1a7ad8d2579be1c93/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[299,300,301,302,303,304,305,306],"take":"subject2/h2/3/cam4","frame_ids":[299,300,301,302,303,304,305,306]} +{"filtered_tile_id":"fc3facd1a7ad8d2579be1c93:8","filtered_window_id":"fc3facd1a7ad8d2579be1c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc3facd1a7ad8d2579be1c93/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[307,308,309,310,311,312,313,314],"take":"subject2/h2/3/cam4","frame_ids":[307,308,309,310,311,312,313,314]} +{"filtered_tile_id":"fc3facd1a7ad8d2579be1c93:16","filtered_window_id":"fc3facd1a7ad8d2579be1c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc3facd1a7ad8d2579be1c93/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[315,316,317,318,319,320,321,322],"take":"subject2/h2/3/cam4","frame_ids":[315,316,317,318,319,320,321,322]} +{"filtered_tile_id":"fc3facd1a7ad8d2579be1c93:24","filtered_window_id":"fc3facd1a7ad8d2579be1c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc3facd1a7ad8d2579be1c93/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[323,324,325,326,327,328,329,330],"take":"subject2/h2/3/cam4","frame_ids":[323,324,325,326,327,328,329,330]} +{"filtered_tile_id":"fc3facd1a7ad8d2579be1c93:32","filtered_window_id":"fc3facd1a7ad8d2579be1c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc3facd1a7ad8d2579be1c93/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[331,332,333,334,335,336,337,338],"take":"subject2/h2/3/cam4","frame_ids":[331,332,333,334,335,336,337,338]} +{"filtered_tile_id":"fc3facd1a7ad8d2579be1c93:40","filtered_window_id":"fc3facd1a7ad8d2579be1c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc3facd1a7ad8d2579be1c93/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[339,340,341,342,343,344,345,346],"take":"subject2/h2/3/cam4","frame_ids":[339,340,341,342,343,344,345,346]} +{"filtered_tile_id":"fc3facd1a7ad8d2579be1c93:48","filtered_window_id":"fc3facd1a7ad8d2579be1c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc3facd1a7ad8d2579be1c93/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[347,348,349,350,351,352,353,354],"take":"subject2/h2/3/cam4","frame_ids":[347,348,349,350,351,352,353,354]} +{"filtered_tile_id":"fc3facd1a7ad8d2579be1c93:52","filtered_window_id":"fc3facd1a7ad8d2579be1c93","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc3facd1a7ad8d2579be1c93/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[351,352,353,354,355,356,357,358],"take":"subject2/h2/3/cam4","frame_ids":[351,352,353,354,355,356,357,358]} +{"filtered_tile_id":"fc90ea94deb8e00984a4bee5:0","filtered_window_id":"fc90ea94deb8e00984a4bee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc90ea94deb8e00984a4bee5/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[762,763,764,765,766,767,768,769],"take":"subject1/h1/7/cam4","frame_ids":[762,763,764,765,766,767,768,769]} +{"filtered_tile_id":"fc90ea94deb8e00984a4bee5:8","filtered_window_id":"fc90ea94deb8e00984a4bee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc90ea94deb8e00984a4bee5/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[770,771,772,773,774,775,776,777],"take":"subject1/h1/7/cam4","frame_ids":[770,771,772,773,774,775,776,777]} +{"filtered_tile_id":"fc90ea94deb8e00984a4bee5:16","filtered_window_id":"fc90ea94deb8e00984a4bee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc90ea94deb8e00984a4bee5/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[778,779,780,781,782,783,784,785],"take":"subject1/h1/7/cam4","frame_ids":[778,779,780,781,782,783,784,785]} +{"filtered_tile_id":"fc90ea94deb8e00984a4bee5:24","filtered_window_id":"fc90ea94deb8e00984a4bee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc90ea94deb8e00984a4bee5/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[786,787,788,789,790,791,792,793],"take":"subject1/h1/7/cam4","frame_ids":[786,787,788,789,790,791,792,793]} +{"filtered_tile_id":"fc90ea94deb8e00984a4bee5:28","filtered_window_id":"fc90ea94deb8e00984a4bee5","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fc90ea94deb8e00984a4bee5/native_gt.npz","filtered_start_offset":28,"expected_frame_ids":[790,791,792,793,794,795,796,797],"take":"subject1/h1/7/cam4","frame_ids":[790,791,792,793,794,795,796,797]} +{"filtered_tile_id":"fca82bd05994b299ab1b873a:0","filtered_window_id":"fca82bd05994b299ab1b873a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca82bd05994b299ab1b873a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[382,383,384,385,386,387,388,389],"take":"subject2/h2/1/cam4","frame_ids":[382,383,384,385,386,387,388,389]} +{"filtered_tile_id":"fca82bd05994b299ab1b873a:8","filtered_window_id":"fca82bd05994b299ab1b873a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca82bd05994b299ab1b873a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[390,391,392,393,394,395,396,397],"take":"subject2/h2/1/cam4","frame_ids":[390,391,392,393,394,395,396,397]} +{"filtered_tile_id":"fca82bd05994b299ab1b873a:16","filtered_window_id":"fca82bd05994b299ab1b873a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca82bd05994b299ab1b873a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[398,399,400,401,402,403,404,405],"take":"subject2/h2/1/cam4","frame_ids":[398,399,400,401,402,403,404,405]} +{"filtered_tile_id":"fca82bd05994b299ab1b873a:24","filtered_window_id":"fca82bd05994b299ab1b873a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca82bd05994b299ab1b873a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[406,407,408,409,410,411,412,413],"take":"subject2/h2/1/cam4","frame_ids":[406,407,408,409,410,411,412,413]} +{"filtered_tile_id":"fca82bd05994b299ab1b873a:32","filtered_window_id":"fca82bd05994b299ab1b873a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca82bd05994b299ab1b873a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[414,415,416,417,418,419,420,421],"take":"subject2/h2/1/cam4","frame_ids":[414,415,416,417,418,419,420,421]} +{"filtered_tile_id":"fca82bd05994b299ab1b873a:40","filtered_window_id":"fca82bd05994b299ab1b873a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca82bd05994b299ab1b873a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[422,423,424,425,426,427,428,429],"take":"subject2/h2/1/cam4","frame_ids":[422,423,424,425,426,427,428,429]} +{"filtered_tile_id":"fca82bd05994b299ab1b873a:48","filtered_window_id":"fca82bd05994b299ab1b873a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca82bd05994b299ab1b873a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[430,431,432,433,434,435,436,437],"take":"subject2/h2/1/cam4","frame_ids":[430,431,432,433,434,435,436,437]} +{"filtered_tile_id":"fca82bd05994b299ab1b873a:52","filtered_window_id":"fca82bd05994b299ab1b873a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca82bd05994b299ab1b873a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[434,435,436,437,438,439,440,441],"take":"subject2/h2/1/cam4","frame_ids":[434,435,436,437,438,439,440,441]} +{"filtered_tile_id":"fca9dafa3a112c49ed82ad64:0","filtered_window_id":"fca9dafa3a112c49ed82ad64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca9dafa3a112c49ed82ad64/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject2/h2/3/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"fca9dafa3a112c49ed82ad64:2","filtered_window_id":"fca9dafa3a112c49ed82ad64","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fca9dafa3a112c49ed82ad64/native_gt.npz","filtered_start_offset":2,"expected_frame_ids":[2,3,4,5,6,7,8,9],"take":"subject2/h2/3/cam4","frame_ids":[2,3,4,5,6,7,8,9]} +{"filtered_tile_id":"fcc96c3bd82c8eb794b59071:0","filtered_window_id":"fcc96c3bd82c8eb794b59071","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcc96c3bd82c8eb794b59071/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[139,140,141,142,143,144,145,146],"take":"subject1/h1/2/cam4","frame_ids":[139,140,141,142,143,144,145,146]} +{"filtered_tile_id":"fcc96c3bd82c8eb794b59071:8","filtered_window_id":"fcc96c3bd82c8eb794b59071","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcc96c3bd82c8eb794b59071/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[147,148,149,150,151,152,153,154],"take":"subject1/h1/2/cam4","frame_ids":[147,148,149,150,151,152,153,154]} +{"filtered_tile_id":"fcc96c3bd82c8eb794b59071:16","filtered_window_id":"fcc96c3bd82c8eb794b59071","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcc96c3bd82c8eb794b59071/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[155,156,157,158,159,160,161,162],"take":"subject1/h1/2/cam4","frame_ids":[155,156,157,158,159,160,161,162]} +{"filtered_tile_id":"fcc96c3bd82c8eb794b59071:23","filtered_window_id":"fcc96c3bd82c8eb794b59071","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcc96c3bd82c8eb794b59071/native_gt.npz","filtered_start_offset":23,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject1/h1/2/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"fcf05683e1af4f29f8c11ae0:0","filtered_window_id":"fcf05683e1af4f29f8c11ae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcf05683e1af4f29f8c11ae0/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[54,55,56,57,58,59,60,61],"take":"subject1/k2/1/cam4","frame_ids":[54,55,56,57,58,59,60,61]} +{"filtered_tile_id":"fcf05683e1af4f29f8c11ae0:8","filtered_window_id":"fcf05683e1af4f29f8c11ae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcf05683e1af4f29f8c11ae0/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[62,63,64,65,66,67,68,69],"take":"subject1/k2/1/cam4","frame_ids":[62,63,64,65,66,67,68,69]} +{"filtered_tile_id":"fcf05683e1af4f29f8c11ae0:16","filtered_window_id":"fcf05683e1af4f29f8c11ae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcf05683e1af4f29f8c11ae0/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[70,71,72,73,74,75,76,77],"take":"subject1/k2/1/cam4","frame_ids":[70,71,72,73,74,75,76,77]} +{"filtered_tile_id":"fcf05683e1af4f29f8c11ae0:24","filtered_window_id":"fcf05683e1af4f29f8c11ae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcf05683e1af4f29f8c11ae0/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[78,79,80,81,82,83,84,85],"take":"subject1/k2/1/cam4","frame_ids":[78,79,80,81,82,83,84,85]} +{"filtered_tile_id":"fcf05683e1af4f29f8c11ae0:32","filtered_window_id":"fcf05683e1af4f29f8c11ae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcf05683e1af4f29f8c11ae0/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[86,87,88,89,90,91,92,93],"take":"subject1/k2/1/cam4","frame_ids":[86,87,88,89,90,91,92,93]} +{"filtered_tile_id":"fcf05683e1af4f29f8c11ae0:40","filtered_window_id":"fcf05683e1af4f29f8c11ae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcf05683e1af4f29f8c11ae0/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[94,95,96,97,98,99,100,101],"take":"subject1/k2/1/cam4","frame_ids":[94,95,96,97,98,99,100,101]} +{"filtered_tile_id":"fcf05683e1af4f29f8c11ae0:48","filtered_window_id":"fcf05683e1af4f29f8c11ae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcf05683e1af4f29f8c11ae0/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[102,103,104,105,106,107,108,109],"take":"subject1/k2/1/cam4","frame_ids":[102,103,104,105,106,107,108,109]} +{"filtered_tile_id":"fcf05683e1af4f29f8c11ae0:52","filtered_window_id":"fcf05683e1af4f29f8c11ae0","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fcf05683e1af4f29f8c11ae0/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[106,107,108,109,110,111,112,113],"take":"subject1/k2/1/cam4","frame_ids":[106,107,108,109,110,111,112,113]} +{"filtered_tile_id":"fd16408ceab550699dd475c7:0","filtered_window_id":"fd16408ceab550699dd475c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd16408ceab550699dd475c7/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject1/h1/3/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"fd16408ceab550699dd475c7:8","filtered_window_id":"fd16408ceab550699dd475c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd16408ceab550699dd475c7/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject1/h1/3/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"fd16408ceab550699dd475c7:16","filtered_window_id":"fd16408ceab550699dd475c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd16408ceab550699dd475c7/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject1/h1/3/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"fd16408ceab550699dd475c7:24","filtered_window_id":"fd16408ceab550699dd475c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd16408ceab550699dd475c7/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject1/h1/3/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"fd16408ceab550699dd475c7:32","filtered_window_id":"fd16408ceab550699dd475c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd16408ceab550699dd475c7/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[107,108,109,110,111,112,113,114],"take":"subject1/h1/3/cam4","frame_ids":[107,108,109,110,111,112,113,114]} +{"filtered_tile_id":"fd16408ceab550699dd475c7:40","filtered_window_id":"fd16408ceab550699dd475c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd16408ceab550699dd475c7/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[115,116,117,118,119,120,121,122],"take":"subject1/h1/3/cam4","frame_ids":[115,116,117,118,119,120,121,122]} +{"filtered_tile_id":"fd16408ceab550699dd475c7:48","filtered_window_id":"fd16408ceab550699dd475c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd16408ceab550699dd475c7/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[123,124,125,126,127,128,129,130],"take":"subject1/h1/3/cam4","frame_ids":[123,124,125,126,127,128,129,130]} +{"filtered_tile_id":"fd16408ceab550699dd475c7:52","filtered_window_id":"fd16408ceab550699dd475c7","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd16408ceab550699dd475c7/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[127,128,129,130,131,132,133,134],"take":"subject1/h1/3/cam4","frame_ids":[127,128,129,130,131,132,133,134]} +{"filtered_tile_id":"fd5b890d08145599446665af:0","filtered_window_id":"fd5b890d08145599446665af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd5b890d08145599446665af/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[0,1,2,3,4,5,6,7],"take":"subject1/h2/1/cam4","frame_ids":[0,1,2,3,4,5,6,7]} +{"filtered_tile_id":"fd5b890d08145599446665af:8","filtered_window_id":"fd5b890d08145599446665af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd5b890d08145599446665af/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[8,9,10,11,12,13,14,15],"take":"subject1/h2/1/cam4","frame_ids":[8,9,10,11,12,13,14,15]} +{"filtered_tile_id":"fd5b890d08145599446665af:16","filtered_window_id":"fd5b890d08145599446665af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd5b890d08145599446665af/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[16,17,18,19,20,21,22,23],"take":"subject1/h2/1/cam4","frame_ids":[16,17,18,19,20,21,22,23]} +{"filtered_tile_id":"fd5b890d08145599446665af:24","filtered_window_id":"fd5b890d08145599446665af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd5b890d08145599446665af/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[24,25,26,27,28,29,30,31],"take":"subject1/h2/1/cam4","frame_ids":[24,25,26,27,28,29,30,31]} +{"filtered_tile_id":"fd5b890d08145599446665af:32","filtered_window_id":"fd5b890d08145599446665af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd5b890d08145599446665af/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[32,33,34,35,36,37,38,39],"take":"subject1/h2/1/cam4","frame_ids":[32,33,34,35,36,37,38,39]} +{"filtered_tile_id":"fd5b890d08145599446665af:34","filtered_window_id":"fd5b890d08145599446665af","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fd5b890d08145599446665af/native_gt.npz","filtered_start_offset":34,"expected_frame_ids":[34,35,36,37,38,39,40,41],"take":"subject1/h2/1/cam4","frame_ids":[34,35,36,37,38,39,40,41]} +{"filtered_tile_id":"fdc070c7e56cf3890d07576a:0","filtered_window_id":"fdc070c7e56cf3890d07576a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdc070c7e56cf3890d07576a/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[122,123,124,125,126,127,128,129],"take":"subject1/h1/4/cam4","frame_ids":[122,123,124,125,126,127,128,129]} +{"filtered_tile_id":"fdc070c7e56cf3890d07576a:8","filtered_window_id":"fdc070c7e56cf3890d07576a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdc070c7e56cf3890d07576a/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[130,131,132,133,134,135,136,137],"take":"subject1/h1/4/cam4","frame_ids":[130,131,132,133,134,135,136,137]} +{"filtered_tile_id":"fdc070c7e56cf3890d07576a:16","filtered_window_id":"fdc070c7e56cf3890d07576a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdc070c7e56cf3890d07576a/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[138,139,140,141,142,143,144,145],"take":"subject1/h1/4/cam4","frame_ids":[138,139,140,141,142,143,144,145]} +{"filtered_tile_id":"fdc070c7e56cf3890d07576a:24","filtered_window_id":"fdc070c7e56cf3890d07576a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdc070c7e56cf3890d07576a/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[146,147,148,149,150,151,152,153],"take":"subject1/h1/4/cam4","frame_ids":[146,147,148,149,150,151,152,153]} +{"filtered_tile_id":"fdc070c7e56cf3890d07576a:32","filtered_window_id":"fdc070c7e56cf3890d07576a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdc070c7e56cf3890d07576a/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[154,155,156,157,158,159,160,161],"take":"subject1/h1/4/cam4","frame_ids":[154,155,156,157,158,159,160,161]} +{"filtered_tile_id":"fdc070c7e56cf3890d07576a:40","filtered_window_id":"fdc070c7e56cf3890d07576a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdc070c7e56cf3890d07576a/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[162,163,164,165,166,167,168,169],"take":"subject1/h1/4/cam4","frame_ids":[162,163,164,165,166,167,168,169]} +{"filtered_tile_id":"fdc070c7e56cf3890d07576a:48","filtered_window_id":"fdc070c7e56cf3890d07576a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdc070c7e56cf3890d07576a/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[170,171,172,173,174,175,176,177],"take":"subject1/h1/4/cam4","frame_ids":[170,171,172,173,174,175,176,177]} +{"filtered_tile_id":"fdc070c7e56cf3890d07576a:52","filtered_window_id":"fdc070c7e56cf3890d07576a","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdc070c7e56cf3890d07576a/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[174,175,176,177,178,179,180,181],"take":"subject1/h1/4/cam4","frame_ids":[174,175,176,177,178,179,180,181]} +{"filtered_tile_id":"fdcca920068547ab06bd61fe:0","filtered_window_id":"fdcca920068547ab06bd61fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdcca920068547ab06bd61fe/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[540,541,542,543,544,545,546,547],"take":"subject2/o1/2/cam4","frame_ids":[540,541,542,543,544,545,546,547]} +{"filtered_tile_id":"fdcca920068547ab06bd61fe:8","filtered_window_id":"fdcca920068547ab06bd61fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdcca920068547ab06bd61fe/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[548,549,550,551,552,553,554,555],"take":"subject2/o1/2/cam4","frame_ids":[548,549,550,551,552,553,554,555]} +{"filtered_tile_id":"fdcca920068547ab06bd61fe:16","filtered_window_id":"fdcca920068547ab06bd61fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdcca920068547ab06bd61fe/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[556,557,558,559,560,561,562,563],"take":"subject2/o1/2/cam4","frame_ids":[556,557,558,559,560,561,562,563]} +{"filtered_tile_id":"fdcca920068547ab06bd61fe:24","filtered_window_id":"fdcca920068547ab06bd61fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdcca920068547ab06bd61fe/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[564,565,566,567,568,569,570,571],"take":"subject2/o1/2/cam4","frame_ids":[564,565,566,567,568,569,570,571]} +{"filtered_tile_id":"fdcca920068547ab06bd61fe:32","filtered_window_id":"fdcca920068547ab06bd61fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdcca920068547ab06bd61fe/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[572,573,574,575,576,577,578,579],"take":"subject2/o1/2/cam4","frame_ids":[572,573,574,575,576,577,578,579]} +{"filtered_tile_id":"fdcca920068547ab06bd61fe:40","filtered_window_id":"fdcca920068547ab06bd61fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdcca920068547ab06bd61fe/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[580,581,582,583,584,585,586,587],"take":"subject2/o1/2/cam4","frame_ids":[580,581,582,583,584,585,586,587]} +{"filtered_tile_id":"fdcca920068547ab06bd61fe:48","filtered_window_id":"fdcca920068547ab06bd61fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdcca920068547ab06bd61fe/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[588,589,590,591,592,593,594,595],"take":"subject2/o1/2/cam4","frame_ids":[588,589,590,591,592,593,594,595]} +{"filtered_tile_id":"fdcca920068547ab06bd61fe:52","filtered_window_id":"fdcca920068547ab06bd61fe","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fdcca920068547ab06bd61fe/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[592,593,594,595,596,597,598,599],"take":"subject2/o1/2/cam4","frame_ids":[592,593,594,595,596,597,598,599]} +{"filtered_tile_id":"fde5e07ab429a63d0014d91c:0","filtered_window_id":"fde5e07ab429a63d0014d91c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fde5e07ab429a63d0014d91c/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[428,429,430,431,432,433,434,435],"take":"subject2/h1/2/cam4","frame_ids":[428,429,430,431,432,433,434,435]} +{"filtered_tile_id":"fde5e07ab429a63d0014d91c:8","filtered_window_id":"fde5e07ab429a63d0014d91c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fde5e07ab429a63d0014d91c/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[436,437,438,439,440,441,442,443],"take":"subject2/h1/2/cam4","frame_ids":[436,437,438,439,440,441,442,443]} +{"filtered_tile_id":"fde5e07ab429a63d0014d91c:16","filtered_window_id":"fde5e07ab429a63d0014d91c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fde5e07ab429a63d0014d91c/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[444,445,446,447,448,449,450,451],"take":"subject2/h1/2/cam4","frame_ids":[444,445,446,447,448,449,450,451]} +{"filtered_tile_id":"fde5e07ab429a63d0014d91c:24","filtered_window_id":"fde5e07ab429a63d0014d91c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fde5e07ab429a63d0014d91c/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[452,453,454,455,456,457,458,459],"take":"subject2/h1/2/cam4","frame_ids":[452,453,454,455,456,457,458,459]} +{"filtered_tile_id":"fde5e07ab429a63d0014d91c:32","filtered_window_id":"fde5e07ab429a63d0014d91c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fde5e07ab429a63d0014d91c/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[460,461,462,463,464,465,466,467],"take":"subject2/h1/2/cam4","frame_ids":[460,461,462,463,464,465,466,467]} +{"filtered_tile_id":"fde5e07ab429a63d0014d91c:40","filtered_window_id":"fde5e07ab429a63d0014d91c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fde5e07ab429a63d0014d91c/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[468,469,470,471,472,473,474,475],"take":"subject2/h1/2/cam4","frame_ids":[468,469,470,471,472,473,474,475]} +{"filtered_tile_id":"fde5e07ab429a63d0014d91c:48","filtered_window_id":"fde5e07ab429a63d0014d91c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fde5e07ab429a63d0014d91c/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[476,477,478,479,480,481,482,483],"take":"subject2/h1/2/cam4","frame_ids":[476,477,478,479,480,481,482,483]} +{"filtered_tile_id":"fde5e07ab429a63d0014d91c:52","filtered_window_id":"fde5e07ab429a63d0014d91c","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fde5e07ab429a63d0014d91c/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[480,481,482,483,484,485,486,487],"take":"subject2/h1/2/cam4","frame_ids":[480,481,482,483,484,485,486,487]} +{"filtered_tile_id":"fe158b491d544ac25b565281:0","filtered_window_id":"fe158b491d544ac25b565281","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fe158b491d544ac25b565281/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[1080,1081,1082,1083,1084,1085,1086,1087],"take":"subject2/o1/2/cam4","frame_ids":[1080,1081,1082,1083,1084,1085,1086,1087]} +{"filtered_tile_id":"fe158b491d544ac25b565281:8","filtered_window_id":"fe158b491d544ac25b565281","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fe158b491d544ac25b565281/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[1088,1089,1090,1091,1092,1093,1094,1095],"take":"subject2/o1/2/cam4","frame_ids":[1088,1089,1090,1091,1092,1093,1094,1095]} +{"filtered_tile_id":"fe158b491d544ac25b565281:16","filtered_window_id":"fe158b491d544ac25b565281","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fe158b491d544ac25b565281/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[1096,1097,1098,1099,1100,1101,1102,1103],"take":"subject2/o1/2/cam4","frame_ids":[1096,1097,1098,1099,1100,1101,1102,1103]} +{"filtered_tile_id":"fe158b491d544ac25b565281:24","filtered_window_id":"fe158b491d544ac25b565281","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fe158b491d544ac25b565281/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[1104,1105,1106,1107,1108,1109,1110,1111],"take":"subject2/o1/2/cam4","frame_ids":[1104,1105,1106,1107,1108,1109,1110,1111]} +{"filtered_tile_id":"fe158b491d544ac25b565281:32","filtered_window_id":"fe158b491d544ac25b565281","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fe158b491d544ac25b565281/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[1112,1113,1114,1115,1116,1117,1118,1119],"take":"subject2/o1/2/cam4","frame_ids":[1112,1113,1114,1115,1116,1117,1118,1119]} +{"filtered_tile_id":"fe158b491d544ac25b565281:40","filtered_window_id":"fe158b491d544ac25b565281","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fe158b491d544ac25b565281/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[1120,1121,1122,1123,1124,1125,1126,1127],"take":"subject2/o1/2/cam4","frame_ids":[1120,1121,1122,1123,1124,1125,1126,1127]} +{"filtered_tile_id":"fe158b491d544ac25b565281:48","filtered_window_id":"fe158b491d544ac25b565281","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fe158b491d544ac25b565281/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[1128,1129,1130,1131,1132,1133,1134,1135],"take":"subject2/o1/2/cam4","frame_ids":[1128,1129,1130,1131,1132,1133,1134,1135]} +{"filtered_tile_id":"fe158b491d544ac25b565281:52","filtered_window_id":"fe158b491d544ac25b565281","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/fe158b491d544ac25b565281/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[1132,1133,1134,1135,1136,1137,1138,1139],"take":"subject2/o1/2/cam4","frame_ids":[1132,1133,1134,1135,1136,1137,1138,1139]} +{"filtered_tile_id":"feff45214f7f52c98c099f4d:0","filtered_window_id":"feff45214f7f52c98c099f4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/feff45214f7f52c98c099f4d/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[67,68,69,70,71,72,73,74],"take":"subject1/h1/5/cam4","frame_ids":[67,68,69,70,71,72,73,74]} +{"filtered_tile_id":"feff45214f7f52c98c099f4d:8","filtered_window_id":"feff45214f7f52c98c099f4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/feff45214f7f52c98c099f4d/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[75,76,77,78,79,80,81,82],"take":"subject1/h1/5/cam4","frame_ids":[75,76,77,78,79,80,81,82]} +{"filtered_tile_id":"feff45214f7f52c98c099f4d:16","filtered_window_id":"feff45214f7f52c98c099f4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/feff45214f7f52c98c099f4d/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[83,84,85,86,87,88,89,90],"take":"subject1/h1/5/cam4","frame_ids":[83,84,85,86,87,88,89,90]} +{"filtered_tile_id":"feff45214f7f52c98c099f4d:24","filtered_window_id":"feff45214f7f52c98c099f4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/feff45214f7f52c98c099f4d/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[91,92,93,94,95,96,97,98],"take":"subject1/h1/5/cam4","frame_ids":[91,92,93,94,95,96,97,98]} +{"filtered_tile_id":"feff45214f7f52c98c099f4d:32","filtered_window_id":"feff45214f7f52c98c099f4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/feff45214f7f52c98c099f4d/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[99,100,101,102,103,104,105,106],"take":"subject1/h1/5/cam4","frame_ids":[99,100,101,102,103,104,105,106]} +{"filtered_tile_id":"feff45214f7f52c98c099f4d:37","filtered_window_id":"feff45214f7f52c98c099f4d","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/feff45214f7f52c98c099f4d/native_gt.npz","filtered_start_offset":37,"expected_frame_ids":[104,105,106,107,108,109,110,111],"take":"subject1/h1/5/cam4","frame_ids":[104,105,106,107,108,109,110,111]} +{"filtered_tile_id":"ff6929a89d0d53881fb43e9e:0","filtered_window_id":"ff6929a89d0d53881fb43e9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff6929a89d0d53881fb43e9e/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[5,6,7,8,9,10,11,12],"take":"subject2/k1/5/cam4","frame_ids":[5,6,7,8,9,10,11,12]} +{"filtered_tile_id":"ff6929a89d0d53881fb43e9e:8","filtered_window_id":"ff6929a89d0d53881fb43e9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff6929a89d0d53881fb43e9e/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[13,14,15,16,17,18,19,20],"take":"subject2/k1/5/cam4","frame_ids":[13,14,15,16,17,18,19,20]} +{"filtered_tile_id":"ff6929a89d0d53881fb43e9e:16","filtered_window_id":"ff6929a89d0d53881fb43e9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff6929a89d0d53881fb43e9e/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[21,22,23,24,25,26,27,28],"take":"subject2/k1/5/cam4","frame_ids":[21,22,23,24,25,26,27,28]} +{"filtered_tile_id":"ff6929a89d0d53881fb43e9e:24","filtered_window_id":"ff6929a89d0d53881fb43e9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff6929a89d0d53881fb43e9e/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[29,30,31,32,33,34,35,36],"take":"subject2/k1/5/cam4","frame_ids":[29,30,31,32,33,34,35,36]} +{"filtered_tile_id":"ff6929a89d0d53881fb43e9e:32","filtered_window_id":"ff6929a89d0d53881fb43e9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff6929a89d0d53881fb43e9e/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[37,38,39,40,41,42,43,44],"take":"subject2/k1/5/cam4","frame_ids":[37,38,39,40,41,42,43,44]} +{"filtered_tile_id":"ff6929a89d0d53881fb43e9e:40","filtered_window_id":"ff6929a89d0d53881fb43e9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff6929a89d0d53881fb43e9e/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[45,46,47,48,49,50,51,52],"take":"subject2/k1/5/cam4","frame_ids":[45,46,47,48,49,50,51,52]} +{"filtered_tile_id":"ff6929a89d0d53881fb43e9e:46","filtered_window_id":"ff6929a89d0d53881fb43e9e","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff6929a89d0d53881fb43e9e/native_gt.npz","filtered_start_offset":46,"expected_frame_ids":[51,52,53,54,55,56,57,58],"take":"subject2/k1/5/cam4","frame_ids":[51,52,53,54,55,56,57,58]} +{"filtered_tile_id":"ff86274b1e48817b716533da:0","filtered_window_id":"ff86274b1e48817b716533da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff86274b1e48817b716533da/native_gt.npz","filtered_start_offset":0,"expected_frame_ids":[266,267,268,269,270,271,272,273],"take":"subject1/k2/5/cam4","frame_ids":[266,267,268,269,270,271,272,273]} +{"filtered_tile_id":"ff86274b1e48817b716533da:8","filtered_window_id":"ff86274b1e48817b716533da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff86274b1e48817b716533da/native_gt.npz","filtered_start_offset":8,"expected_frame_ids":[274,275,276,277,278,279,280,281],"take":"subject1/k2/5/cam4","frame_ids":[274,275,276,277,278,279,280,281]} +{"filtered_tile_id":"ff86274b1e48817b716533da:16","filtered_window_id":"ff86274b1e48817b716533da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff86274b1e48817b716533da/native_gt.npz","filtered_start_offset":16,"expected_frame_ids":[282,283,284,285,286,287,288,289],"take":"subject1/k2/5/cam4","frame_ids":[282,283,284,285,286,287,288,289]} +{"filtered_tile_id":"ff86274b1e48817b716533da:24","filtered_window_id":"ff86274b1e48817b716533da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff86274b1e48817b716533da/native_gt.npz","filtered_start_offset":24,"expected_frame_ids":[290,291,292,293,294,295,296,297],"take":"subject1/k2/5/cam4","frame_ids":[290,291,292,293,294,295,296,297]} +{"filtered_tile_id":"ff86274b1e48817b716533da:32","filtered_window_id":"ff86274b1e48817b716533da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff86274b1e48817b716533da/native_gt.npz","filtered_start_offset":32,"expected_frame_ids":[298,299,300,301,302,303,304,305],"take":"subject1/k2/5/cam4","frame_ids":[298,299,300,301,302,303,304,305]} +{"filtered_tile_id":"ff86274b1e48817b716533da:40","filtered_window_id":"ff86274b1e48817b716533da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff86274b1e48817b716533da/native_gt.npz","filtered_start_offset":40,"expected_frame_ids":[306,307,308,309,310,311,312,313],"take":"subject1/k2/5/cam4","frame_ids":[306,307,308,309,310,311,312,313]} +{"filtered_tile_id":"ff86274b1e48817b716533da:48","filtered_window_id":"ff86274b1e48817b716533da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff86274b1e48817b716533da/native_gt.npz","filtered_start_offset":48,"expected_frame_ids":[314,315,316,317,318,319,320,321],"take":"subject1/k2/5/cam4","frame_ids":[314,315,316,317,318,319,320,321]} +{"filtered_tile_id":"ff86274b1e48817b716533da:52","filtered_window_id":"ff86274b1e48817b716533da","filtered_gt_path":"/SSD3/yangzijing/ego_full_training_filter_20260925/filtered/H2O/ff86274b1e48817b716533da/native_gt.npz","filtered_start_offset":52,"expected_frame_ids":[318,319,320,321,322,323,324,325],"take":"subject1/k2/5/cam4","frame_ids":[318,319,320,321,322,323,324,325]} diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/hot3d_t8.jsonl b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/hot3d_t8.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..10a40217fd7cba821525a8876663a3a20a44b6e3 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/adapter_trainable_t8/hot3d_t8.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8630298efbce16764a0c1d7bc108f46675c26a9fc290553b7920420b74f877b7 +size 85616024 diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..caf8b38ba60830be5dcd17052fe80b3c1ec5b8e4 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/cache/trainable_t8_index.sqlite @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462 +size 132706304 diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/.gitignore b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bc1a1f6167d09c909aad37280b760bb715d0f1da --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/.gitignore @@ -0,0 +1,2 @@ +# Created by pytest automatically. +* diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/CACHEDIR.TAG b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/CACHEDIR.TAG new file mode 100644 index 0000000000000000000000000000000000000000..fce15ad7eaa74e5682b644c84efb75334c112f95 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/CACHEDIR.TAG @@ -0,0 +1,4 @@ +Signature: 8a477f597d28d172789f06886806bc55 +# This file is a cache directory tag created by pytest. +# For information about cache directory tags, see: +# https://bford.info/cachedir/spec.html diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/README.md b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b89018ced91c0a8af7f3f23ce8901870da89f3a0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/README.md @@ -0,0 +1,8 @@ +# pytest cache directory # + +This directory contains data from the pytest's cache plugin, +which provides the `--lf` and `--ff` options, as well as the `cache` fixture. + +**Do not** commit this to version control. + +See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information. diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/v/cache/lastfailed b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/v/cache/lastfailed new file mode 100644 index 0000000000000000000000000000000000000000..9e26dfeeb6e641a33dae4961196235bdb965b21b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/v/cache/lastfailed @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/v/cache/nodeids b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/v/cache/nodeids new file mode 100644 index 0000000000000000000000000000000000000000..8766fb872f2a8b76c32b03a2724a90ea9d0df027 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/.pytest_cache/v/cache/nodeids @@ -0,0 +1,6 @@ +[ + "tests/test_hot3d_supervision_masks.py::test_missing_geometry_remains_invalid_even_when_mesh_projects_inside", + "tests/test_hot3d_supervision_masks.py::test_quest_rectification_preserves_native_camera_extrinsic", + "tests/test_hot3d_supervision_masks.py::test_temporal_masks_are_independent_per_frame_and_hand", + "tests/test_hot3d_supervision_masks.py::test_visible_mesh_keeps_full_3d_but_masks_offscreen_2d" +] \ No newline at end of file diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_formal_stage.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_formal_stage.py new file mode 100644 index 0000000000000000000000000000000000000000..68ad0c1c90c60fc8329518db2ec8956b0a6c137e --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_formal_stage.py @@ -0,0 +1,133 @@ +"""Audit a completed formal stage endpoint without modifying training state.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +import math +from pathlib import Path +import statistics + +import torch + +from clean_train import INDEX, STAGES, sha, training_code_hashes + + +EXTREME_LOSS_THRESHOLD = 100.0 + + +def run(checkpoint: Path, metrics: Path, stage: str, update: int) -> dict: + state = torch.load(checkpoint, map_location="cpu", weights_only=False) + rows = [json.loads(line) for line in metrics.open()] + errors = [] + if not rows or len(rows) != update or [row["update"] for row in rows] != list(range(1, update + 1)): + errors.append("metrics do not contain every update through the requested endpoint") + if state["stage"] != stage or state["update"] != update: + errors.append("checkpoint stage or update differs from requested endpoint") + if state.get("smoke") or not state.get("complete_backbone"): + errors.append("checkpoint is smoke or lacks the complete backbone") + if state["world_size"] != 6 or len(state["rank_rng_states"]) != 6: + errors.append("checkpoint is not a complete six-rank state") + if state["next_global_sample_position"] != STAGES[stage]["offset"] + 6 * update: + errors.append("sampler cursor differs from the registered stage schedule") + if state["index_sha256"] != sha(INDEX) or state["code_sha256"] != training_code_hashes(): + errors.append("checkpoint data index or training code identity differs from current files") + if state.get("grad_clip") != 100.0: + errors.append("gradient clipping threshold differs from the frozen recipe") + exposure = Counter(state["exposures"]) + if sum(exposure.values()) != 6 * update: + errors.append("source/mode exposure ledger does not sum to global batch times updates") + if stage in ("S1", "S2", "S3"): + expected = {"H2O": 0.40, "ARCTIC": 0.35, "HOT3D": 0.25} + else: + expected = {"H2O": 0.35, "ARCTIC": 0.25, "HOT3D": 0.40} + source_exposure = { + source: sum(count for key, count in exposure.items() if key.startswith(source + ":")) + for source in expected + } + for source, fraction in expected.items(): + if abs(source_exposure[source] - 6 * update * fraction) > 6: + errors.append(f"{source} exposure differs from the registered quota") + expected_modes = { + "H2O:rgb", "H2O:rgb_k", "H2O:rgb_depth_k", + "ARCTIC:rgb", "ARCTIC:rgb_k", "HOT3D:rgb", "HOT3D:rgb_k", + } + if set(exposure) != expected_modes: + errors.append("one or more registered source/input modes are absent") + supervision = state.get("supervision_exposures") + if (not isinstance(supervision, dict) or not supervision + or sum(supervision.values()) <= 0 or min(supervision.values()) < 0): + errors.append("supervision ledger is empty or contains invalid counts") + if rows: + last = rows[-1] + if last["exposures"] != state["exposures"] or last.get("supervision_exposures") != supervision: + errors.append("final metrics row and checkpoint exposure ledgers differ") + if not all(math.isfinite(row["loss"]) and math.isfinite(row["grad_norm_max"]) for row in rows): + errors.append("nonfinite loss or gradient norm in the training history") + extreme_loss_updates = [row["update"] for row in rows + if math.isfinite(row["loss"]) + and row["loss"] > EXTREME_LOSS_THRESHOLD] + if extreme_loss_updates: + errors.append(f"extreme finite loss at updates {extreme_loss_updates[:20]}") + detailed = [row for row in rows if "grad_parameter_groups" in row] + required_groups = { + "rgb_encoder.projection", "depth_encoder", "ray_encoder", + "decoder.spatial", "joint2d_head", "rotation_head", + "translation_head", "shape_head", + } + if stage != "S1": + required_groups.update(("decoder.temporal", "shape_score")) + if stage == "S4": + required_groups.add("rgb_encoder.backbone") + if not all(any(row["grad_parameter_groups"].get(group, 0) > 0 for row in detailed) + for group in required_groups): + errors.append("a required trainable parameter group never received a nonzero gradient") + else: + detailed = [] + extreme_loss_updates = [] + window = min(100, len(rows)) + report = { + "status": "pass" if not errors else "fail", + "errors": errors, + "checkpoint": str(checkpoint), + "checkpoint_sha256": sha(checkpoint), + "stage": stage, + "update": update, + "training_code_sha256": state["code_sha256"]["clean_train.py"], + "source_exposure": source_exposure, + "source_mode_exposure": dict(exposure), + "supervision_ledger_keys": len(supervision or {}), + "supervision_elements": sum((supervision or {}).values()), + "first_window_loss_mean": statistics.mean(row["loss"] for row in rows[:window]) if rows else None, + "last_window_loss_mean": statistics.mean(row["loss"] for row in rows[-window:]) if rows else None, + "last_window_grad_norm_median": statistics.median(row["grad_norm_max"] for row in rows[-window:]) if rows else None, + "clipped_updates": sum(bool(row["clipped"]) for row in rows), + "max_batch_loss": max((row["loss"] for row in rows), default=None), + "extreme_loss_threshold": EXTREME_LOSS_THRESHOLD, + "extreme_loss_updates": extreme_loss_updates, + "detailed_rows": len(detailed), + } + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--metrics", type=Path, required=True) + parser.add_argument("--stage", choices=tuple(STAGES), required=True) + parser.add_argument("--update", type=int, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + report = run(args.checkpoint, args.metrics, args.stage, args.update) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2)) + if report["errors"]: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_gt_projection.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_gt_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..3a92d42d3cad354945b06e3c8d86d25dae30e4d0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_gt_projection.py @@ -0,0 +1,108 @@ +"""Freeze a 100-frame RGB/GT/K alignment gallery from trainable native clips.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from clean_train import ASSETS, MANIFESTS +from filtered_dataset import FilteredClipDataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.geometry.camera import project_points + + +QUOTAS = {"H2O": 40, "ARCTIC": 30, "HOT3D": 30} +CELL_HW = (200, 356) + + +def thumbnail(sample: dict, source: str, tile_id: str) -> tuple[np.ndarray, list[float], int]: + frame = len(sample["rgb"]) // 2 + rgb = sample["rgb"][frame].permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + points = sample["joint3d_camera"][frame] + K = sample["K"][frame] + projected, positive = project_points(points, K) + target = sample["joint2d"][frame] + valid = (sample["joint2d_valid"][frame] & sample["joint3d_valid"][frame] + & positive & torch.isfinite(target).all(-1)) + errors = torch.linalg.vector_norm(projected - target, dim=-1)[valid].tolist() + height, width = image.shape[:2] + for hand in range(2): + for joint in range(21): + if not bool(valid[hand, joint]): + continue + x, y = target[hand, joint].tolist() + px, py = projected[hand, joint].tolist() + if 0 <= x < width and 0 <= y < height: + cv2.circle(image, (round(x), round(y)), 3, (0, 255, 255), -1) + if 0 <= px < width and 0 <= py < height: + cv2.circle(image, (round(px), round(py)), 2, (255, 0, 255), -1) + cell_height, cell_width = CELL_HW + image = cv2.resize(image, (cell_width, cell_height - 28), interpolation=cv2.INTER_AREA) + cell = np.zeros((cell_height, cell_width, 3), dtype=np.uint8) + cell[:cell_height - 28] = image + label = f"{source} {tile_id[-22:]} valid={int(valid.sum())}" + cv2.putText(cell, label, (5, cell_height - 9), cv2.FONT_HERSHEY_SIMPLEX, + .38, (255, 255, 255), 1, cv2.LINE_AA) + return cell, errors, int(valid.sum()) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + args.output.mkdir(parents=True) + cells = [] + report = {"schema": "clean_gt_projection_audit_v1", "selection": "linspace over frozen trainable T8 manifests", + "total_frames": sum(QUOTAS.values()), "sources": {}} + for source, count in QUOTAS.items(): + manifest = MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl" + dataset = FilteredClipDataset( + source, manifest, 8, (368, 640), ASSETS["mano_root"], + Path(__file__).parent / "third_party", {"enabled": False}, + ) + indices = np.linspace(0, len(dataset) - 1, count, dtype=int) + errors = [] + valid_counts = [] + tiles = [] + for index in indices: + row = dataset.rows[int(index)] + tile_id = str(row["filtered_tile_id"]) + sample = dataset[{"source": source, "tile_id": tile_id, "epoch": 0, + "mode": "rgb_depth_k" if source == "H2O" else "rgb_k", + "position": 0, "source_ordinal": int(index)}] + cell, joint_errors, valid_count = thumbnail(sample, source, tile_id) + cells.append(cell) + errors.extend(joint_errors) + valid_counts.append(valid_count) + tiles.append(tile_id) + values = np.asarray(errors) + report["sources"][source] = { + "frames": count, "frames_with_valid_3d_and_2d": sum(x > 0 for x in valid_counts), + "valid_joints": len(errors), "mean_reprojection_px": float(values.mean()) if len(values) else None, + "p95_reprojection_px": float(np.quantile(values, .95)) if len(values) else None, + "max_reprojection_px": float(values.max()) if len(values) else None, + "tile_ids": tiles, + } + height, width = CELL_HW + gallery = np.zeros((10 * height, 10 * width, 3), dtype=np.uint8) + for number, cell in enumerate(cells): + row, col = divmod(number, 10) + gallery[row * height:(row + 1) * height, col * width:(col + 1) * width] = cell + if not cv2.imwrite(str(args.output / "gt_projection_100.jpg"), gallery): + raise RuntimeError("gallery write failed") + (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({name: {key: value for key, value in row.items() if key != "tile_ids"} + for name, row in report["sources"].items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_headset_sync.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_headset_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..679b0c33f13bd968d67a8980223428165da61a61 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_headset_sync.py @@ -0,0 +1,104 @@ +"""Audit HOT3D camera-frame GT construction against native headset pose time.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import csv +from functools import lru_cache +import json +from pathlib import Path + +import numpy as np + +from preflight_index import tile_starts + + +MAX_DELTA_NS = 20_000_000 + + +@lru_cache(maxsize=256) +def trajectory(root: str) -> np.ndarray: + path = Path(root) / "headset_trajectory.csv" + with path.open(newline="") as stream: + stamps = np.asarray( + [int(row["timestamp[ns]"]) for row in csv.DictReader(stream)], dtype=np.int64, + ) + if len(stamps) == 0 or np.any(np.diff(stamps) <= 0): + raise ValueError(f"empty or nonmonotone headset trajectory: {path}") + return stamps + + +@lru_cache(maxsize=256) +def timeline(path: str, stream: str) -> np.ndarray: + return np.asarray(json.loads(Path(path).read_text())[stream], dtype=np.int64) + + +def deltas(target: np.ndarray, reference: np.ndarray) -> np.ndarray: + upper = np.searchsorted(reference, target).clip(0, len(reference) - 1) + lower = (upper - 1).clip(0, len(reference) - 1) + return np.minimum(np.abs(reference[upper] - target), np.abs(reference[lower] - target)) + + +def audit(manifest: Path) -> tuple[dict, list[dict]]: + counts = Counter() + recording_bad = Counter() + bad: list[dict] = [] + max_deltas = [] + for line in manifest.open(): + if not line.strip(): + continue + row = json.loads(line) + if row["dataset"] != "HOT3D": + continue + source = row["source"] + stamps = timeline(source["timestamps_path"], row["stream_id"])[ + int(row["start"]):int(row["end"]) + ] + if len(stamps) != row["frame_count"]: + raise ValueError(f"timeline length mismatch: {row['id']}") + delta = deltas(stamps, trajectory(source["root"])) + bad_frames = delta > MAX_DELTA_NS + bad_tiles = [start for start in tile_starts(len(stamps)) + if bool(bad_frames[start:start + 8].any())] + counts["windows"] += 1 + counts["frames"] += len(stamps) + counts["tiles"] += len(tile_starts(len(stamps))) + counts["bad_frames"] += int(bad_frames.sum()) + counts["bad_tiles"] += len(bad_tiles) + if bad_frames.any(): + counts["bad_windows"] += 1 + recording_bad[row["recording_id"]] += 1 + max_deltas.append(float(delta.max() / 1e6)) + bad.append({"window_id": row["id"], "recording_id": row["recording_id"], + "stream_id": row["stream_id"], "bad_frame_offsets": np.flatnonzero(bad_frames).tolist(), + "bad_tile_offsets": bad_tiles, "maximum_nearest_headset_delta_ms": float(delta.max() / 1e6)}) + report = { + "threshold_ms": 20, "counts": dict(counts), + "affected_recordings": len(recording_bad), + "worst_recordings_by_window_count": recording_bad.most_common(20), + "bad_window_delta_ms_median": float(np.median(max_deltas)) if max_deltas else 0, + "bad_window_delta_ms_max": max(max_deltas, default=0), + } + return report, bad + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--report", type=Path, required=True) + parser.add_argument("--bad-windows", type=Path, required=True) + args = parser.parse_args() + for path in (args.report, args.bad_windows): + if path.exists(): + raise FileExistsError(path) + report, bad = audit(args.manifest) + args.report.write_text(json.dumps(report, indent=2) + "\n") + with args.bad_windows.open("w") as stream: + for row in bad: + stream.write(json.dumps(row) + "\n") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_input_modes.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_input_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c4c2ab8786bbffe21be79e147165f59b008111 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_input_modes.py @@ -0,0 +1,58 @@ +"""Assert modality input dropout never changes camera or GT supervision.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import torch + +from clean_train import ASSETS, MANIFESTS +from filtered_dataset import FilteredClipDataset + + +SUPERVISION = ( + "K", "K_supervision_valid", "joint2d", "joint2d_valid", + "joint3d_camera", "joint3d_valid", "wrist_root_translation", + "translation_valid", "mano_pose", "mano_pose_valid", "mano_shape", + "shape_valid", "vertices_valid", "reprojection_valid", +) + + +def main() -> None: + result = {} + for source in ("H2O", "ARCTIC", "HOT3D"): + manifest = MANIFESTS / "adapter_trainable_t8" / f"{source.lower()}_t8.jsonl" + dataset = FilteredClipDataset( + source, manifest, 8, (368, 640), ASSETS["mano_root"], + Path(__file__).parent / "third_party", {"enabled": False}, + ) + row = dataset.rows[0] + spec = {"source": source, "tile_id": row["filtered_tile_id"], + "position": 0, "source_ordinal": 0, "epoch": 0} + modes = ("rgb", "rgb_k", "rgb_depth_k") if source == "H2O" else ("rgb", "rgb_k") + samples = {mode: dataset[{**spec, "mode": mode}] for mode in modes} + reference = samples["rgb"] + frame = reference["frame_valid"].bool() + if not bool(reference["K_supervision_valid"].any()): + raise AssertionError(f"{source} selected clip lacks K supervision") + for mode, sample in samples.items(): + torch.testing.assert_close(sample["rgb"], reference["rgb"]) + for name in SUPERVISION: + torch.testing.assert_close(sample[name], reference[name], equal_nan=True) + expected_K = frame if mode != "rgb" else torch.zeros_like(frame) + expected_depth = frame if mode == "rgb_depth_k" else torch.zeros_like(frame) + for canonical, alias, expected in ( + ("K_input_available", "K_available", expected_K), + ("depth_input_available", "depth_available", expected_depth), + ): + if not torch.equal(sample[canonical], expected) or not torch.equal(sample[alias], expected): + raise AssertionError(f"{source}:{mode} availability flags diverge") + result[source] = {"tile_id": spec["tile_id"], "modes": modes, + "K_supervised_frames": int(reference["K_supervision_valid"].sum()), + "GT_and_real_K_unchanged": True} + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_schedule.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..d564389690154f78b10e1e20fca34b32a428afae --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/audit_schedule.py @@ -0,0 +1,50 @@ +"""Verify every registered T=8 tile is exposed before source-local reuse.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +from pathlib import Path + +from coverage_sampler import CoverageSampler, SOURCES + + +def audit(index: Path, stage: str, samples: int) -> dict: + sampler = CoverageSampler(index, stage) + seen = {source: set() for source in SOURCES} + exposures = Counter() + modes = Counter() + first_coverage = {} + for position in range(samples): + row = sampler.sample(position) + source = str(row["source"]) + ordinal = int(row["source_ordinal"]) + if ordinal < sampler.sizes[source] and row["tile_id"] in seen[source]: + raise AssertionError(f"tile repeated before coverage: {source} {row['tile_id']}") + seen[source].add(row["tile_id"]) + exposures[source] += 1 + modes[f"{source}:{row['mode']}"] += 1 + if source not in first_coverage and len(seen[source]) == sampler.sizes[source]: + first_coverage[source] = position + 1 + if any(len(seen[source]) != sampler.sizes[source] for source in SOURCES): + raise AssertionError("registered T=8 stage did not cover all source tiles") + return { + "stage": stage, "samples": samples, "status": "pass", + "tiles": sampler.sizes, "unique_tiles": {source: len(seen[source]) for source in SOURCES}, + "exposures": dict(exposures), "input_modes": dict(modes), + "first_complete_global_position": first_coverage, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--index", type=Path, required=True) + parser.add_argument("--stage", choices=("S1_S3", "S4"), required=True) + parser.add_argument("--samples", type=int, required=True) + args = parser.parse_args() + print(json.dumps(audit(args.index, args.stage, args.samples), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/benchmark_decode.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/benchmark_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a2146c5035daa63e01ea7574caf358c84a6363 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/benchmark_decode.py @@ -0,0 +1,56 @@ +"""Measure uncached native clip decoding across spaced recordings.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys +import time + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import numpy as np +import torch + +from filtered_dataset import FilteredClipDataset + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--count", type=int, default=8) + parser.add_argument("--grouped", action="store_true", help="Read consecutive tiles in one recording") + args = parser.parse_args() + start = time.perf_counter() + dataset = FilteredClipDataset( + args.source, args.manifests / f"{args.source.lower()}_t8.jsonl", 8, + (368, 640), "/SSD3/jiasen/foundation_hand/pretrained/mano", + Path(__file__).parent / "third_party", {"enabled": False}, + ) + init_seconds = time.perf_counter() - start + indices = list(range(args.count)) if args.grouped else np.linspace( + 0, len(dataset) - 1, args.count, dtype=int, + ).tolist() + times = [] + recordings = [] + with torch.no_grad(): + for sequence, index in enumerate(indices): + row = dataset.rows[index] + spec = {"source": args.source, "tile_id": row["filtered_tile_id"], + "epoch": 0, "source_ordinal": sequence, "position": sequence, + "mode": "rgb_depth_k" if args.source == "H2O" else "rgb_k"} + mark = time.perf_counter() + sample = dataset[spec] + times.append(time.perf_counter() - mark) + recordings.append(sample["physical_recording_id"]) + print(json.dumps({"source": args.source, "count": len(times), + "recordings": len(set(recordings)), "init_seconds": init_seconds, + "decode_seconds": times, "median_seconds": float(np.median(times)), + "p95_seconds": float(np.quantile(times, .95)), + "clips_per_second_single_worker": len(times) / sum(times)}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/build_trainable_index.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/build_trainable_index.py new file mode 100644 index 0000000000000000000000000000000000000000..03f9619e1b4a6beca9a51c0da26ab28d09d4d898 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/build_trainable_index.py @@ -0,0 +1,126 @@ +"""Apply audited HOT3D headset-pose eligibility without changing source GT.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import json +import os +from pathlib import Path +import sqlite3 + +from preflight_index import digest, tile_starts + + +def valid_runs(length: int, invalid: set[int]): + start = None + for position in range(length + 1): + good = position < length and position not in invalid + if good and start is None: + start = position + elif not good and start is not None: + yield start, position + start = None + + +def build(original: Path, audit: Path, bad_windows: Path, output: Path) -> dict: + if output.exists(): + raise FileExistsError(output) + report = json.loads(audit.read_text()) + if report["threshold_ms"] != 20 or report["counts"]["windows"] != 18962: + raise ValueError("headset synchronization audit is not the frozen full-data audit") + bad_rows = [json.loads(line) for line in bad_windows.open() if line.strip()] + if len(bad_rows) != report["counts"]["bad_windows"]: + raise ValueError("bad-window list differs from summary") + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_suffix(output.suffix + ".tmp") + if temporary.exists(): + raise FileExistsError(temporary) + source = sqlite3.connect(f"file:{original}?mode=ro", uri=True) + target = sqlite3.connect(temporary) + try: + source.backup(target) + target.execute("CREATE TABLE sync_exclusions (window_id TEXT PRIMARY KEY, bad_frame_offsets_json TEXT NOT NULL)") + lost_valid_frames = 0 + recovered_valid_frames = 0 + windows_without_t8 = 0 + for record in bad_rows: + window_id = record["window_id"] + row = target.execute( + "SELECT source,recording_id,frame_ids_json FROM windows WHERE window_id=?", + (window_id,), + ).fetchone() + if row is None or row[0] != "HOT3D": + raise ValueError(f"unknown HOT3D window {window_id}") + _, recording, frame_ids_json = row + frame_ids = json.loads(frame_ids_json) + invalid = set(record["bad_frame_offsets"]) + if not invalid or min(invalid) < 0 or max(invalid) >= len(frame_ids): + raise ValueError(f"bad frame offsets outside window {window_id}") + original_bad_tiles = [offset for (offset,) in target.execute( + "SELECT start_offset FROM tiles WHERE window_id=?", (window_id,), + ) if invalid.intersection(range(offset, offset + 8))] + if sorted(original_bad_tiles) != sorted(record["bad_tile_offsets"]): + raise ValueError(f"headset audit tile mapping differs: {window_id}") + target.execute("DELETE FROM tiles WHERE window_id=?", (window_id,)) + target.execute("INSERT INTO sync_exclusions VALUES (?,?)", + (window_id, json.dumps(sorted(invalid)))) + covered = set() + tile_count = 0 + for first, last in valid_runs(len(frame_ids), invalid): + if last - first < 8: + continue + for local_start in tile_starts(last - first): + offset = first + local_start + selected = frame_ids[offset:offset + 8] + if len(selected) != 8 or invalid.intersection(range(offset, offset + 8)): + raise AssertionError("trainable tile contains an invalid headset frame") + target.execute( + "INSERT INTO tiles VALUES (?,?,?,?,?,?)", + (f"{window_id}:{offset}", window_id, "HOT3D", recording, + offset, json.dumps(selected)), + ) + covered.update(range(offset, offset + 8)) + tile_count += 1 + if tile_count == 0: + windows_without_t8 += 1 + recovered_valid_frames += len(covered) + lost_valid_frames += (len(frame_ids) - len(invalid) - len(covered)) + counts = Counter(dict(target.execute("SELECT source, COUNT(*) FROM tiles GROUP BY source"))) + bad_tile_check = target.execute( + "SELECT COUNT(*) FROM tiles t JOIN sync_exclusions e ON t.window_id=e.window_id" + ).fetchone()[0] + target.commit() + except BaseException: + target.close() + source.close() + temporary.unlink(missing_ok=True) + raise + target.close() + source.close() + os.replace(temporary, output) + return { + "status": "pass", "original_index_sha256": digest(original), + "headset_sync_report_sha256": digest(audit), + "headset_bad_windows_sha256": digest(bad_windows), + "trainable_index_sha256": digest(output), "tiles_by_source": dict(counts), + "audited_windows_with_bad_headset_pose": len(bad_rows), + "windows_without_any_t8": windows_without_t8, + "valid_frames_covered_inside_affected_windows": recovered_valid_frames, + "valid_frames_not_packable_into_t8": lost_valid_frames, + "tiles_in_affected_windows": bad_tile_check, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--original", type=Path, required=True) + parser.add_argument("--audit", type=Path, required=True) + parser.add_argument("--bad-windows", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(build(args.original, args.audit, args.bad_windows, args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/clean_eval.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/clean_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..888132d52b7c6e468fab8ecb62bac9627b82caf8 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/clean_eval.py @@ -0,0 +1,139 @@ +"""Evaluate a complete clean-GT checkpoint on frozen native-GT panels.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import ASSETS, INDEX, ROOT, model_for, sha, training_code_hashes +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.h2o_dataset import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +FOUR_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "projected_mano_2d_error_px", +) + + +def dataset_for(source: str, manifest: Path): + hw = (512, 896) + if source == "H2O": + return H2OCam4Dataset( + "/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, hw, + clip_lengths=(8,), strides=(1,), window_step=8, + allow_partial=False, + ) + if source == "ARCTIC": + return ARCTICClipDataset(manifest, ASSETS["mano_root"], hw) + if source == "HOT3D": + return HOT3DClipDataset( + "/SSD3/jiasen/foundation_hand/HOT3D/dataset", manifest, + Path(__file__).parent / "third_party", ASSETS["mano_root"], + hw, K_input_dropout=0.0, + ) + raise ValueError(source) + + +def apply_mode(batch: dict, mode: str) -> None: + frame = batch["frame_valid"].bool() + K = frame.clone() if mode != "rgb" else torch.zeros_like(frame) + depth = frame.clone() if mode == "rgb_depth_k" else torch.zeros_like(frame) + batch["K_input_available"] = K + batch["depth_input_available"] = depth + batch["K_available"] = K.clone() + batch["depth_available"] = depth.clone() + if not (torch.equal(batch["K_input_available"], K) + and torch.equal(batch["depth_input_available"], depth)): + raise RuntimeError("input availability override failed") + + +def run(args: argparse.Namespace) -> dict: + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + if panel_report["train_manifest_sha256"] != "b4b0ac4bc4a771c9bc7626a9eec7f5f541ef96908a9a64d219192efd7b8f7f89": + raise RuntimeError("frozen training allowlist identity differs") + if args.role == "confirmation" and not args.final_checkpoint: + raise ValueError("confirmation is reserved for a frozen final checkpoint") + if args.source != "H2O" and args.mode == "rgb_depth_k": + raise ValueError("only H2O has real metric depth") + manifest = panels / f"{args.source.lower()}_{args.role}_t8.jsonl" + expected = panel_report["sources"][args.source][args.role]["manifest_sha256"] + if sha(manifest) != expected: + raise RuntimeError("validation panel SHA256 changed") + if args.output.exists(): + raise FileExistsError(args.output) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if not state.get("complete_backbone") or state["index_sha256"] != sha(INDEX): + raise RuntimeError("checkpoint lacks complete DINO or filtered-index identity") + if state.get("smoke", False) and not args.allow_smoke: + raise RuntimeError("smoke checkpoint is not valid for formal evaluation") + code_match = state["code_sha256"] == training_code_hashes() + if not code_match and not args.allow_smoke: + raise RuntimeError("evaluation code differs from checkpoint training code") + if args.role == "confirmation" and ( + state.get("smoke", False) or state["stage"] != "S4" + or state["update"] != 66667 + ): + raise RuntimeError("confirmation requires the frozen S4 endpoint") + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + dataset = dataset_for(args.source, manifest) + if args.limit is not None and not args.allow_smoke: + raise ValueError("subset evaluation must be marked as smoke") + limit = min(len(dataset), args.limit) if args.limit is not None else len(dataset) + rows = [] + with torch.inference_mode(): + for index in range(limit): + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast(device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"): + prediction = model(batch) + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows.append(make_row(prediction, batch, 0, frame, side)) + summary = aggregate(rows) + report = { + "role": args.role, "source": args.source, "input_mode": args.mode, + "checkpoint": str(args.checkpoint), "checkpoint_sha256": sha(args.checkpoint), + "checkpoint_stage": state["stage"], "checkpoint_update": state["update"], + "panel_sha256": expected, "clips": limit, "hands": len(rows), + "smoke": bool(args.allow_smoke), + "checkpoint_code_match": code_match, + "evaluator_sha256": sha(Path(__file__)), + "metric_impl_sha256": sha(Path(__file__).parent / "scripts/evaluate_phase7_external.py"), + "four_metrics": {name: summary[name] for name in FOUR_METRICS}, + "supervision_coverage": summary["supervision_coverage"], + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--role", choices=("development", "confirmation"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--final-checkpoint", action="store_true") + parser.add_argument("--allow-smoke", action="store_true") + parser.add_argument("--limit", type=int) + args = parser.parse_args() + print(json.dumps(run(args), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/clean_train.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/clean_train.py new file mode 100644 index 0000000000000000000000000000000000000000..3887eb28769f77ab87cea0c5fa960955b78dcf80 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/clean_train.py @@ -0,0 +1,558 @@ +"""Fresh-DINO staged Foundation Hand training on the frozen filtered-GT index. + +Use torchrun for DDP. This entry never loads a learned Foundation Hand parent. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from contextlib import nullcontext +from datetime import timedelta +import hashlib +import json +import math +import os +from pathlib import Path +import random +import resource +import shutil +import sys +import time + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import numpy as np +import torch +import torch.distributed as dist +from torch import nn +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader, Dataset, Sampler +from safetensors import safe_open + +from coverage_sampler import CoverageSampler, SOURCES +from filtered_dataset import FilteredClipDataset +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.losses import BimanualLoss, LossConfig +from foundation_hand.training.optimizer import optimizer_parameter_groups, set_scheduled_learning_rate +from foundation_hand.training.schedule import warmup_cosine_learning_rate +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925") +INDEX = ROOT / "cache/trainable_t8_index.sqlite" +MANIFESTS = ROOT / "cache" +EXPECTED_INDEX_SHA256 = "5e59c448dc6ecd46dcfc58aaa5b35721d8e96ac726eeb6c497c593230aee6462" +EXPECTED_MANIFEST_SHA256 = { + 1: {"ARCTIC": "489315448fef1a2adcb50d7ba162d3d376810d0fa652905330d5e3db77620c62", + "H2O": "7bca84c00e66e9680704d5c54b1001af637cda620ef4f31037626407dcd8dc88", + "HOT3D": "391c837142e5985bf45c505bc9c3f3daa7f220c3a4144bad51635ca1f632e15f"}, + 8: {"ARCTIC": "35b61473010ae198b036d3c549ae1b922439e35711e5bc76f7f06c58fd82e7e6", + "H2O": "74e20172e321b363523f05497b891834d88edd0f349acb58288a4e6f37e01a8a", + "HOT3D": "8630298efbce16764a0c1d7bc108f46675c26a9fc290553b7920420b74f877b7"}, +} +ASSETS = { + "dinov3_source": "/home/jiasen/foundation_hand/third_party/dinov3", + "dinov3_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "mano_root": "/SSD3/jiasen/foundation_hand/pretrained/mano", +} +STAGES = { + "S1": {"time": 1, "hw": (368, 640), "updates": 16667, + "coverage": "S1_S3", "offset": 0, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S2": {"time": 8, "hw": (368, 640), "updates": 50000, + "coverage": "S1_S3", "offset": 0, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S3": {"time": 8, "hw": (512, 896), "updates": 83334, + "coverage": "S1_S3", "offset": 300000, "max_lr": 5e-5, "min_lr": 5e-6, "last2": 0}, + "S4": {"time": 8, "hw": (512, 896), "updates": 66667, + "coverage": "S4", "offset": 0, "max_lr": 1e-5, "min_lr": 1e-6, "last2": 2}, +} +LOSS = LossConfig( + joint2d=1.0, joint3d_camera=10.0, joint3d_root_relative=10.0, + vertices_camera=1.0, local_pose=1.0, global_orientation=1.0, + shape=.1, translation=10.0, reprojection=1.0, + temporal_velocity=.1, temporal_acceleration=.05, + bimanual_relative_wrist=1.0, presence=0.0, +) +FRESH_HEAD_WEIGHT_STD = 0.001 +FRESH_DEPTH_WEIGHT_STD = 0.001 +MONITORED_LOSSES = ( + "joint2d", "joint3d_camera", "joint3d_root_relative", "vertices_camera", + "local_pose", "global_orientation", "shape", "translation", + "reprojection", "temporal_velocity", "temporal_acceleration", + "bimanual_relative_wrist", +) +TRANSLATION_DIAGNOSTICS = tuple( + f"translation_{axis}_{suffix}" + for axis in ("x", "y", "z") + for suffix in ("raw_mae_m", "effective_loss_contribution") +) +MASK_FIELDS = ( + "joint2d_valid", "joint3d_valid", "joint3d_root_relative_valid", + "translation_valid", "mano_pose_valid", "shape_valid", + "vertices_valid", "reprojection_valid", +) + + +def sha(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def training_code_hashes() -> dict[str, str]: + code_root = Path(__file__).parent + paths = [code_root / name for name in ( + "clean_train.py", "filtered_dataset.py", "coverage_sampler.py", + "export_adapter_manifests.py", "build_trainable_index.py", + )] + list((code_root / "src/foundation_hand").rglob("*.py")) + list( + (code_root / "third_party/hot3d").rglob("*.py") + ) + return {str(path.relative_to(code_root)): sha(path) for path in sorted(paths)} + + +class MixedDataset(Dataset): + def __init__(self, time: int, hw: tuple[int, int]): + manifests = MANIFESTS / f"adapter_trainable_t{time}" + self.sources = { + source: FilteredClipDataset( + source, manifests / f"{source.lower()}_t{time}.jsonl", time, + hw, ASSETS["mano_root"], Path(__file__).parent / "third_party", + {"enabled": source != "HOT3D", "probability": .8}, + ) + for source in SOURCES + } + + def __len__(self) -> int: + return sum(map(len, self.sources.values())) + + def __getitem__(self, spec: dict): + return self.sources[str(spec["source"])][spec] + + +class PositionSampler(Sampler[dict]): + def __init__(self, coverage: CoverageSampler, first: int, last: int, rank: int, world: int): + self.coverage, self.first, self.last = coverage, first, last + self.rank, self.world = rank, world + + def __iter__(self): + yield from self.coverage.shard(self.first, self.last, self.rank, self.world) + + def __len__(self): + return (self.last - self.first) // self.world + + +class Objective(nn.Module): + def __init__(self, model: BimanualReconstructionModel): + super().__init__() + self.model = model + self.criterion = BimanualLoss(LOSS) + + def forward(self, batch: dict): + prediction = self.model(batch) + losses = self.criterion(prediction, batch) + with torch.no_grad(): + losses.update(self.criterion.translation_diagnostics(prediction, batch)) + return losses + + +def model_for(stage: str) -> BimanualReconstructionModel: + options = STAGES[stage] + config = ModelConfig( + encoder="dinov3", decoder_dim=512, decoder_layers=3, attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, + depth_mode="geometry", depth_gate_mode="fixed", depth_gate_fixed_value=.5, + use_rays=True, use_bimanual_interaction=True, predict_presence=True, + require_mano=True, mano_fix_left_shapedirs=True, + modality_dropout_prob=0.0, temporal_position_mode="none", + temporal_attention_mode="bidirectional", dinov3_trainable_last_blocks=options["last2"], + translation_parameterization="direct_xyz", **ASSETS, + ) + model = BimanualReconstructionModel(config) + if stage == "S1": + with torch.no_grad(): + for head in ( + model.joint2d_head, model.rotation_head, + model.translation_head, model.shape_head, + ): + nn.init.normal_(head.weight, std=FRESH_HEAD_WEIGHT_STD) + nn.init.normal_( + model.depth_encoder.encoder[-1].weight, + std=FRESH_DEPTH_WEIGHT_STD, + ) + model.presence_head.requires_grad_(False) + if stage == "S1": + model.decoder.temporal_enabled = False + model.decoder.temporal.requires_grad_(False) + return model + + +def verify_official_dino(model: BimanualReconstructionModel) -> dict: + weight_file = Path(ASSETS["dinov3_weights"]) / "model.safetensors" + backbone = model.rgb_encoder.backbone.state_dict() + with safe_open(str(weight_file), framework="pt", device="cpu") as weights: + if set(backbone) != set(weights.keys()): + raise RuntimeError("pretrained DINO tensor names differ from model backbone") + for name, value in backbone.items(): + if not torch.equal(value.cpu(), weights.get_tensor(name)): + raise RuntimeError(f"DINO differs from official weight: {name}") + return {"tensors_equal": len(backbone), "official_safetensors_sha256": sha(weight_file), + "projection_is_new": "projection.weight" not in backbone} + + +def rng_state(device: torch.device) -> dict: + return {"python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state(device)} + + +def restore_rng(state: dict, device: torch.device) -> None: + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"].cpu()) + torch.cuda.set_rng_state(state["cuda"].cpu(), device) + + +def gradient_group_norms(model: nn.Module) -> dict[str, float]: + squared: dict[str, torch.Tensor] = {} + for name, parameter in model.named_parameters(): + if parameter.grad is None: + continue + parts = name.split(".") + group = ".".join(parts[:2]) if parts[0] in ("rgb_encoder", "decoder") else parts[0] + squared[group] = squared.get(group, parameter.grad.new_zeros(())) + parameter.grad.float().square().sum() + return {name: float(value.sqrt()) for name, value in squared.items()} + + +def storage_guard(start: bool) -> None: + devices = {path.stat().st_dev for path in (ROOT, ROOT / "cache", ROOT / "checkpoints", ROOT / "logs", ROOT / "eval")} + if len(devices) != 1: + raise RuntimeError("run directories are not on the same filesystem") + free = shutil.disk_usage(ROOT).free + threshold = (300 if start else 200) * 1024**3 + if free < threshold: + raise RuntimeError(f"root disk free {free / 1024**3:.1f} GiB below stage guard") + checkpoint_bytes = sum( + path.stat().st_size for path in (ROOT / "checkpoints").rglob("*.pt") + if not any("smoke" in component for component in path.relative_to(ROOT).parts) + ) + if not start and checkpoint_bytes + 2 * 1024**3 > 40 * 1024**3: + raise RuntimeError("checkpoint budget cannot fit another full checkpoint") + + +def checkpoint( + path: Path, stage: str, update: int, model: nn.Module, + optimizer: torch.optim.Optimizer, counts: Counter, supervision_counts: Counter, + device: torch.device, + rank: int, world: int, code_hashes: dict, data_hashes: dict, smoke: bool, + grad_clip: float, +) -> None: + local_rng = rng_state(device) + all_rng = [None] * world if rank == 0 else None + if world > 1: + dist.gather_object(local_rng, all_rng, dst=0) + else: + all_rng = [local_rng] + if rank == 0: + storage_guard(False) + if path.exists() or path.with_suffix(".tmp").exists(): + raise FileExistsError(f"checkpoint path is occupied: {path}") + state = { + "model": model.state_dict(), "optimizer": optimizer.state_dict(), + "stage": stage, "update": update, "world_size": world, + "next_global_sample_position": STAGES[stage]["offset"] + update * 6, + "index_sha256": sha(INDEX), "code_sha256": code_hashes, + "data_sha256": data_hashes, + "rank_rng_states": all_rng, "exposures": dict(counts), + "supervision_exposures": dict(supervision_counts), + "scheduler": {"stage_local_update": update, "total_updates": STAGES[stage]["updates"]}, + "complete_backbone": True, + "smoke": smoke, + "grad_clip": grad_clip, + } + temporary = path.with_suffix(".tmp") + torch.save(state, temporary) + temporary.replace(path) + loaded = torch.load(path, map_location="cpu", weights_only=False) + if loaded["update"] != update or set(loaded["model"]) != set(model.state_dict()): + raise RuntimeError("checkpoint load-back failed") + print(f"checkpoint {path} sha256={sha(path)}", flush=True) + if world > 1: + dist.barrier(device_ids=[device.index]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--stage", choices=tuple(STAGES), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--updates", type=int, required=True, help="Stage-local endpoint") + parser.add_argument("--workers", type=int, default=2) + parser.add_argument("--resume", type=Path) + parser.add_argument("--parent", type=Path) + parser.add_argument("--save", action="store_true") + parser.add_argument("--smoke", action="store_true", + help="Allow an incomplete prior-stage checkpoint for isolated preflight only") + parser.add_argument("--grad-clip", type=float, default=100.0) + args = parser.parse_args() + stage = args.stage + options = STAGES[stage] + if not 0 < args.updates <= options["updates"]: + raise ValueError("updates outside registered stage budget") + if not math.isfinite(args.grad_clip) or args.grad_clip <= 0: + raise ValueError("grad clip threshold must be finite and positive") + if not args.resume and (stage == "S1") == bool(args.parent): + raise ValueError("S1 requires no parent; S2/S3/S4 require a complete prior-stage parent") + if args.resume and args.parent: + raise ValueError("resume and stage parent are mutually exclusive") + rank = int(os.environ.get("RANK", 0)) + world = int(os.environ.get("WORLD_SIZE", 1)) + local_rank = int(os.environ.get("LOCAL_RANK", 0)) + if world not in (1, 2, 3, 6) or 6 % world: + raise ValueError("world size must divide global batch 6") + accumulation = 6 // world + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + resource.setrlimit(resource.RLIMIT_NOFILE, (min(max(8192, soft), hard), hard)) + torch.set_num_threads(2) + torch.cuda.set_device(local_rank) + device = torch.device("cuda", local_rank) + if world > 1: + dist.init_process_group("nccl", timeout=timedelta(minutes=15), device_id=device) + try: + storage_guard(True) + if rank == 0: + args.output.mkdir(parents=True, exist_ok=True) + if (args.output / "metrics.jsonl").exists() and not args.resume: + raise FileExistsError("fresh run output already contains training metrics") + if world > 1: + dist.barrier(device_ids=[local_rank]) + code_hashes = training_code_hashes() + selected_manifests = MANIFESTS / f"adapter_trainable_t{options['time']}" + data_hashes = {name: sha(selected_manifests / f"{name.lower()}_t{options['time']}.jsonl") + for name in SOURCES} + if sha(INDEX) != EXPECTED_INDEX_SHA256 or data_hashes != EXPECTED_MANIFEST_SHA256[options["time"]]: + raise RuntimeError("frozen filtered index or native adapter manifest changed") + seed = 20260925 + rank + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed(seed) + model = model_for(stage) + dino_audit = verify_official_dino(model) if rank == 0 and stage == "S1" else None + model = model.to(device) + start = 0 + counts: Counter = Counter() + supervision_counts: Counter = Counter() + previous = args.resume or args.parent + state = None + if previous: + state = torch.load(previous, map_location="cpu", weights_only=False) + if not state.get("complete_backbone") or state["index_sha256"] != sha(INDEX): + raise RuntimeError("parent/resume checkpoint lacks full DINO or filtered-index identity") + if args.resume: + if (state["stage"] != stage or state["world_size"] != world + or state["code_sha256"] != code_hashes or state["data_sha256"] != data_hashes): + raise RuntimeError("exact resume contract mismatch") + if bool(state.get("smoke", False)) != args.smoke: + raise RuntimeError("smoke and formal checkpoints cannot be interchanged") + if float(state.get("grad_clip", 10.0)) != args.grad_clip: + raise RuntimeError("resume changed the gradient clipping threshold") + start = int(state["update"]) + counts.update(state["exposures"]) + supervision_counts.update(state["supervision_exposures"]) + else: + previous_stage = {"S2": "S1", "S3": "S2", "S4": "S3"}[stage] + if state["stage"] != previous_stage: + raise RuntimeError("stage parent is not the immediately preceding stage") + if not args.smoke and ( + state["update"] != STAGES[previous_stage]["updates"] + or state.get("smoke", False) + ): + raise RuntimeError("formal training requires a complete non-smoke prior stage") + if not args.smoke and state["code_sha256"] != code_hashes: + raise RuntimeError("formal stage parent was built with different training code") + if not args.smoke and STAGES[previous_stage]["time"] == options["time"]: + if state["data_sha256"] != data_hashes: + raise RuntimeError("T8 adapter manifests changed across formal stages") + model.load_state_dict(state["model"], strict=True) + model.train() + params = [parameter for parameter in model.parameters() if parameter.requires_grad] + backbone_lr = 5e-7 if stage == "S4" else None + optimizer = torch.optim.AdamW( + optimizer_parameter_groups(model, learning_rate=options["max_lr"], + backbone_learning_rate=backbone_lr), weight_decay=.05, + ) + if args.resume: + optimizer.load_state_dict(state["optimizer"]) + restore_rng(state["rank_rng_states"][rank], device) + del state + if not start < args.updates: + raise ValueError("resume checkpoint is already at or beyond requested endpoint") + dataset = MixedDataset(options["time"], options["hw"]) + coverage = CoverageSampler(INDEX, options["coverage"]) + first = options["offset"] + start * 6 + last = options["offset"] + args.updates * 6 + sampler = PositionSampler(coverage, first, last, rank, world) + loader = DataLoader(dataset, batch_size=1, sampler=sampler, + num_workers=args.workers, collate_fn=collate_h2o_clips, + pin_memory=True, persistent_workers=args.workers > 0, + generator=torch.Generator().manual_seed(seed + 1000000)) + iterator = iter(loader) + objective = Objective(model).to(device) + if world > 1: + objective = DDP(objective, device_ids=[local_rank], output_device=local_rank, + broadcast_buffers=False, find_unused_parameters=True) + if rank == 0: + log = (args.output / "metrics.jsonl").open("a", buffering=1) + if dino_audit: + print(json.dumps({"official_dino_audit": dino_audit}), flush=True) + start_clock = time.monotonic() + torch.cuda.reset_peak_memory_stats(device) + for update in range(start, args.updates): + lr = warmup_cosine_learning_rate(update, options["updates"], + options["max_lr"], options["min_lr"], 1000) + set_scheduled_learning_rate(optimizer, lr) + optimizer.zero_grad(set_to_none=True) + losses_total = torch.zeros((), device=device) + local_modes = Counter() + local_supervision = Counter() + detailed = update < 10 or (update + 1) % 100 == 0 or update + 1 == args.updates + local_details: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + for micro in range(accumulation): + cpu = next(iterator) + source_name = cpu["sampling_source_id"][0] + local_modes[f"{source_name}:{cpu['input_mode'][0]}"] += 1 + batch = move_to_device(cpu, device) + mode_key = f"{source_name}:{cpu['input_mode'][0]}" + for name in MASK_FIELDS: + if name in cpu: + for side in range(2): + local_supervision[f"{mode_key}:{side}:{name}"] += int( + cpu[name][:, :, side].sum() + ) + attach_gt_vertices(batch, model) + sync = objective.no_sync() if world > 1 and micro + 1 < accumulation else nullcontext() + with sync, torch.autocast("cuda", dtype=torch.bfloat16): + losses = objective(batch) + if not torch.isfinite(losses["total"]): + raise RuntimeError(f"nonfinite loss at {stage} update {update}") + (losses["total"] / accumulation).backward() + losses_total += losses["total"].detach() / accumulation + if detailed: + detail = local_details[mode_key] + detail["samples"] += 1 + detail["loss_sums"].update({name: float(losses[name].detach()) + for name in MONITORED_LOSSES + TRANSLATION_DIAGNOSTICS}) + detail["valid_elements"].update({name: int(cpu[name].sum()) + for name in MASK_FIELDS if name in cpu}) + grad_groups = gradient_group_norms(model) if detailed and rank == 0 else None + grad_norm = torch.nn.utils.clip_grad_norm_(params, args.grad_clip) + if not torch.isfinite(grad_norm): + raise RuntimeError(f"nonfinite gradient norm at {stage} update {update}") + norm_min, norm_max = grad_norm.detach().clone(), grad_norm.detach().clone() + if world > 1: + dist.all_reduce(norm_min, op=dist.ReduceOp.MIN) + dist.all_reduce(norm_max, op=dist.ReduceOp.MAX) + optimizer.step() + if world > 1: + dist.all_reduce(losses_total) + gathered = [None] * world + dist.all_gather_object(gathered, { + "modes": dict(local_modes), "supervision": dict(local_supervision), + "details": dict(local_details) if detailed else {}, + }) + else: + gathered = [{"modes": dict(local_modes), + "supervision": dict(local_supervision), + "details": dict(local_details) if detailed else {}}] + for value in gathered: + counts.update(value["modes"]) + supervision_counts.update(value["supervision"]) + if rank == 0: + row = {"stage": stage, "update": update + 1, + "loss": float(losses_total / world), + "grad_norm_min": float(norm_min), "grad_norm_max": float(norm_max), + "clipped": float(norm_max) > args.grad_clip, + "grad_clip_threshold": args.grad_clip, "lr": lr, + "exposures": dict(counts)} + if detailed: + source_sums: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + mode_sums: dict[str, dict] = defaultdict(lambda: { + "samples": 0, "loss_sums": Counter(), "valid_elements": Counter(), + }) + for value in gathered: + for source_mode, detail in value["details"].items(): + source_name = source_mode.split(":", 1)[0] + for target in (source_sums[source_name], mode_sums[source_mode]): + target["samples"] += detail["samples"] + target["loss_sums"].update(detail["loss_sums"]) + target["valid_elements"].update(detail["valid_elements"]) + row["loss_terms"] = { + name: sum(detail["loss_sums"][name] for detail in source_sums.values()) / 6 + for name in MONITORED_LOSSES + } + row["source_loss_terms"] = { + source_name: {name: detail["loss_sums"][name] / detail["samples"] + for name in MONITORED_LOSSES} + for source_name, detail in source_sums.items() + } + row["source_valid_elements"] = { + source_name: dict(detail["valid_elements"]) + for source_name, detail in source_sums.items() + } + row["source_mode_loss_terms"] = { + source_mode: {name: detail["loss_sums"][name] / detail["samples"] + for name in MONITORED_LOSSES} + for source_mode, detail in mode_sums.items() + } + row["source_mode_translation_axes"] = { + source_mode: {name: detail["loss_sums"][name] / detail["samples"] + for name in TRANSLATION_DIAGNOSTICS} + for source_mode, detail in mode_sums.items() + } + row["source_mode_valid_elements"] = { + source_mode: dict(detail["valid_elements"]) + for source_mode, detail in mode_sums.items() + } + row["supervision_exposures"] = dict(supervision_counts) + row["grad_parameter_groups"] = grad_groups + log.write(json.dumps(row) + "\n") + if args.updates <= 10 or (update + 1) % 500 == 0 or update + 1 == args.updates: + print(json.dumps(row), flush=True) + milestone = update + 1 + registered = options["updates"] + if milestone < args.updates and ( + milestone % 10000 == 0 or milestone in { + round(registered * .25), round(registered * .50), round(registered * .75), + } + ): + checkpoint(args.output / f"{stage.lower()}_update_{milestone:07d}.pt", + stage, milestone, model, optimizer, counts, supervision_counts, + device, rank, world, code_hashes, data_hashes, + args.smoke, args.grad_clip) + torch.cuda.synchronize(device) + elapsed = time.monotonic() - start_clock + elapsed_max = torch.tensor(elapsed, device=device) + peak_memory = torch.tensor(torch.cuda.max_memory_allocated(device) / 1024**3, device=device) + if world > 1: + dist.all_reduce(elapsed_max, op=dist.ReduceOp.MAX) + dist.all_reduce(peak_memory, op=dist.ReduceOp.MAX) + if rank == 0: + log.close() + print(json.dumps({"stage": stage, "elapsed_seconds_max": float(elapsed_max), + "clips_per_second": (args.updates - start) * 6 / float(elapsed_max), + "peak_allocated_gib_per_rank_max": float(peak_memory)}), flush=True) + if args.save: + path = args.output / f"{stage.lower()}_update_{args.updates:07d}.pt" + checkpoint(path, stage, args.updates, model, optimizer, counts, + supervision_counts, + device, rank, world, code_hashes, data_hashes, + args.smoke, args.grad_clip) + finally: + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/compare_checkpoints.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/compare_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7c8dbf5e02277d9cf98379adc69bf013f7f9ed --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/compare_checkpoints.py @@ -0,0 +1,62 @@ +"""Compare continuous and resumed training checkpoints tensor by tensor.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + + +def compare(left: Path, right: Path) -> dict: + a = torch.load(left, map_location="cpu", weights_only=False) + b = torch.load(right, map_location="cpu", weights_only=False) + if (a["stage"], a["update"], a["next_global_sample_position"], a["exposures"], + a.get("supervision_exposures"), a.get("grad_clip")) != ( + b["stage"], b["update"], b["next_global_sample_position"], b["exposures"], + b.get("supervision_exposures"), b.get("grad_clip") + ): + raise AssertionError("stage/update/sampler cursor/exposures/optimizer contract differ") + model_differences = [] + if set(a["model"]) != set(b["model"]): + raise AssertionError("model tensor key sets differ") + for key in a["model"]: + if not torch.equal(a["model"][key], b["model"][key]): + model_differences.append(key) + if a["optimizer"]["param_groups"] != b["optimizer"]["param_groups"]: + raise AssertionError("optimizer parameter groups differ") + optimizer_differences = [] + left_states, right_states = a["optimizer"]["state"], b["optimizer"]["state"] + if set(left_states) != set(right_states): + raise AssertionError("optimizer state parameter IDs differ") + for parameter in left_states: + if set(left_states[parameter]) != set(right_states[parameter]): + raise AssertionError(f"optimizer state fields differ for parameter {parameter}") + for key, value in left_states[parameter].items(): + other = right_states[parameter][key] + equal = torch.equal(value, other) if torch.is_tensor(value) else value == other + if not equal: + optimizer_differences.append(f"{parameter}:{key}") + result = {"status": "pass" if not model_differences and not optimizer_differences else "fail", + "model_tensors": len(a["model"]), "model_differences": model_differences[:10], + "optimizer_states": len(left_states), + "optimizer_differences": optimizer_differences[:10], + "stage": a["stage"], "update": a["update"], + "next_global_sample_position": a["next_global_sample_position"]} + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("left", type=Path) + parser.add_argument("right", type=Path) + args = parser.parse_args() + result = compare(args.left, args.right) + print(json.dumps(result, indent=2)) + if result["status"] != "pass": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/coverage_sampler.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/coverage_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..2c00edc8e430b4c5421cb1491b0db472633be9fd --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/coverage_sampler.py @@ -0,0 +1,116 @@ +"""Stateless source quotas and source-local no-replacement GT tile coverage.""" + +from __future__ import annotations + +from collections import defaultdict +import hashlib +import random +import sqlite3 +from pathlib import Path + + +SOURCES = ("H2O", "ARCTIC", "HOT3D") +QUOTAS = {"S1_S3": (8, 7, 5), "S4": (7, 5, 8)} +RECORDING_BLOCK_TILES = 64 + + +def _seed(*values: object) -> int: + encoded = "|".join(map(str, values)).encode("utf-8") + return int.from_bytes(hashlib.blake2b(encoded, digest_size=8).digest(), "little") + + +class CoverageSampler: + """A global sample position determines one immutable tile and input mode. + + S2 and S3 share S1_S3 positions 0..799999. S4 uses a new independent + position space, seed, and coverage ledger. DDP rank r reads positions + start+r, start+r+world_size, etc.; resume needs only the next global + position and the frozen index/code hashes. + """ + + def __init__(self, index: str | Path, stage: str, seed: int = 20260925): + if stage not in QUOTAS: + raise ValueError(f"unknown coverage stage {stage}") + self.stage = stage + self.seed = int(seed) + self.quota = QUOTAS[stage] + self.by_recording: dict[str, dict[str, list[str]]] = { + name: defaultdict(list) for name in SOURCES + } + with sqlite3.connect(index) as connection: + rows = connection.execute( + "SELECT source, recording_id, tile_id FROM tiles " + "ORDER BY source, recording_id, tile_id" + ) + for source, recording, tile_id in rows: + self.by_recording[source][recording].append(tile_id) + self.sizes = { + source: sum(map(len, self.by_recording[source].values())) + for source in SOURCES + } + if min(self.sizes.values()) <= 0: + raise ValueError("each source must contain at least one tile") + self._permutation_cache: dict[tuple[str, int], list[str]] = {} + self._cycle_cache: tuple[int, list[str]] | None = None + + def source_and_ordinal(self, position: int) -> tuple[str, int]: + if position < 0: + raise ValueError("negative sample position") + cycle, within = divmod(position, sum(self.quota)) + if self._cycle_cache is None or self._cycle_cache[0] != cycle: + order = [source for source, count in zip(SOURCES, self.quota) for _ in range(count)] + random.Random(_seed(self.seed, self.stage, "source", cycle)).shuffle(order) + self._cycle_cache = (cycle, order) + else: + order = self._cycle_cache[1] + source = order[within] + source_index = SOURCES.index(source) + ordinal = cycle * self.quota[source_index] + order[:within].count(source) + return source, ordinal + + def _epoch_order(self, source: str, epoch: int) -> list[str]: + key = (source, epoch) + if key in self._permutation_cache: + return self._permutation_cache[key] + randomizer = random.Random(_seed(self.seed, self.stage, source, epoch)) + recordings = list(self.by_recording[source]) + randomizer.shuffle(recordings) + groups = [] + for recording in recordings: + group = self.by_recording[source][recording].copy() + randomizer.shuffle(group) + groups.append(group) + result: list[str] = [] + depth = 0 + while len(result) < self.sizes[source]: + for group in groups: + result.extend(group[depth:depth + RECORDING_BLOCK_TILES]) + depth += RECORDING_BLOCK_TILES + if len(result) != len(set(result)): + raise AssertionError(f"duplicate tile in {source} epoch {epoch}") + for old_key in list(self._permutation_cache): + if old_key[0] == source and old_key[1] < epoch - 1: + del self._permutation_cache[old_key] + self._permutation_cache[key] = result + return result + + def sample(self, position: int) -> dict[str, object]: + source, ordinal = self.source_and_ordinal(position) + epoch, offset = divmod(ordinal, self.sizes[source]) + tile_id = self._epoch_order(source, epoch)[offset] + mode_rng = random.Random(_seed(self.seed, self.stage, "mode", position)) + K_drop = {"H2O": .20, "ARCTIC": .50, "HOT3D": .30}[source] + K_available = mode_rng.random() >= K_drop + depth_available = source == "H2O" and K_available and mode_rng.random() >= .125 + mode = "rgb_depth_k" if depth_available else "rgb_k" if K_available else "rgb" + return { + "position": position, "source": source, "source_ordinal": ordinal, + "epoch": epoch, "tile_id": tile_id, "mode": mode, + } + + def shard(self, start: int, stop: int, rank: int, world_size: int): + if not 0 <= start <= stop or not 0 <= rank < world_size: + raise ValueError("invalid range or rank") + first = start + (rank - start) % world_size + for position in range(first, stop, world_size): + yield self.sample(position) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_formal_loss_spikes.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_formal_loss_spikes.py new file mode 100644 index 0000000000000000000000000000000000000000..f2f7417d5a9744b021aee827ed7f0b8e0e7bc4c2 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_formal_loss_spikes.py @@ -0,0 +1,85 @@ +"""Replay selected S1 sample positions with a fixed checkpoint for loss diagnosis.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for +from coverage_sampler import CoverageSampler +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def run(checkpoint: Path, updates: list[int]) -> dict: + state = torch.load(checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S1" or state.get("smoke"): + raise ValueError("diagnostic requires a formal S1 checkpoint") + torch.set_num_threads(2) + device = torch.device("cuda", 0) + model = model_for("S1") + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + criterion = BimanualLoss(LOSS) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + sampler = CoverageSampler(INDEX, "S1_S3") + results = [] + with torch.inference_mode(): + for update in updates: + for position in range((update - 1) * 6, update * 6): + spec = sampler.sample(position) + cpu = collate_h2o_clips([dataset[spec]]) + batch = move_to_device(cpu, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + joint_valid = batch["joint3d_valid"].bool() + reproj_valid = batch["reprojection_valid"].bool() + gt_z = batch["joint3d_camera"][..., 2][joint_valid] + pred_z = prediction["joints_camera"][..., 2][joint_valid] + gt_2d = batch["joint2d"][reproj_valid] + item = { + "update": update, + "position": position, + "source": spec["source"], + "mode": spec["mode"], + "tile_id": spec["tile_id"], + "loss": float(losses["total"]), + "terms": {name: float(value) for name, value in losses.items() + if name != "total" and float(value) != 0}, + "valid_joint_elements": int(joint_valid.sum()), + "valid_reprojection_elements": int(reproj_valid.sum()), + "gt_z_min_max_m": [float(gt_z.min()), float(gt_z.max())] if gt_z.numel() else None, + "pred_z_min_max_m": [float(pred_z.min()), float(pred_z.max())] if pred_z.numel() else None, + "gt_2d_min_max_px": [float(gt_2d.min()), float(gt_2d.max())] + if gt_2d.numel() else None, + "focal_px": [float(batch["K"][0, 0, 0, 0]), float(batch["K"][0, 0, 1, 1])], + } + results.append(item) + return {"checkpoint": str(checkpoint), "checkpoint_update": state["update"], + "sample_count": len(results), "samples": results} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--updates", type=int, nargs="+", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + report = run(args.checkpoint, args.updates) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({"output": str(args.output), "sample_count": report["sample_count"], + "top_losses": sorted(((row["loss"], row["position"], row["source"]) + for row in report["samples"]), reverse=True)[:10]})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_gradient_outliers.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_gradient_outliers.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3f55b373393f1666b75068fe2a9f00adb5a5d0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_gradient_outliers.py @@ -0,0 +1,83 @@ +"""Read-only per-tile gradient probe for registered S2 sample positions.""" + +from __future__ import annotations + +import argparse +import json +import math + +import torch + +from clean_train import ( + INDEX, LOSS, MixedDataset, attach_gt_vertices, collate_h2o_clips, + gradient_group_norms, model_for, move_to_device, +) +from coverage_sampler import CoverageSampler +from foundation_hand.training.losses import BimanualLoss + + +def minimum(values: torch.Tensor, mask: torch.Tensor) -> float | None: + selected = values.detach()[mask] + return float(selected.min()) if selected.numel() else None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--steps", type=int, nargs="+", required=True) + args = parser.parse_args() + + torch.set_num_threads(2) + device = torch.device("cuda:0") + model = model_for("S2").to(device) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S2" or not state["complete_backbone"]: + raise ValueError("expected a full S2 checkpoint") + model.load_state_dict(state["model"], strict=True) + del state + model.train() + criterion = BimanualLoss(LOSS).to(device) + sampler = CoverageSampler(INDEX, "S1_S3") + dataset = MixedDataset(8, (368, 640)) + + for step in args.steps: + if step < 1: + raise ValueError("steps are 1-based") + for rank in range(6): + spec = sampler.sample((step - 1) * 6 + rank) + cpu = collate_h2o_clips([dataset[spec]]) + batch = move_to_device(cpu, device) + attach_gt_vertices(batch, model) + model.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + losses["total"].backward() + groups = gradient_group_norms(model) + + z = prediction["joints_camera"][..., 2].detach() + valid = batch["reprojection_valid"].bool() & (z > 0) + rotation = prediction["mano_rotations_6d"].detach().float() + first = torch.nn.functional.normalize(rotation[..., :3], dim=-1) + second = rotation[..., 3:] + residual = second - (first * second).sum(dim=-1, keepdim=True) * first + report = { + "step": step, + "rank": rank, + "source": spec["source"], + "tile_id": spec["tile_id"], + "mode": spec["mode"], + "loss": float(losses["total"].detach()), + "reprojection_loss": float(losses["reprojection"].detach()), + "grad_norm": math.sqrt(sum(value * value for value in groups.values())), + "grad_groups_top": sorted(groups.items(), key=lambda item: -item[1])[:5], + "min_positive_valid_joint_z_m": minimum(z, valid), + "positive_valid_joint_z_below_1cm": int((valid & (z < .01)).sum()), + "min_rotation_first_norm": float(rotation[..., :3].norm(dim=-1).min()), + "min_rotation_orthogonal_residual_norm": float(residual.norm(dim=-1).min()), + } + print(json.dumps(report), flush=True) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_initial_gradients.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_initial_gradients.py new file mode 100644 index 0000000000000000000000000000000000000000..4e08e92d1aae8e056f4bd01f0229a09efa660043 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_initial_gradients.py @@ -0,0 +1,90 @@ +"""Measure each weighted loss contribution to the clean-start gradient.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for, sha +from coverage_sampler import CoverageSampler, SOURCES +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def grad_norms(model) -> dict[str, float]: + sums: dict[str, torch.Tensor] = {} + for name, parameter in model.named_parameters(): + if parameter.grad is None: + continue + parts = name.split(".") + group = ".".join(parts[:2]) if parts[0] in ("rgb_encoder", "decoder") else parts[0] + sums[group] = sums.get(group, parameter.grad.new_zeros(())) + parameter.grad.float().square().sum() + return {name: float(value.sqrt()) for name, value in sums.items()} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if state["stage"] != "S1" or state["index_sha256"] != sha(INDEX): + raise ValueError("expected complete S1 checkpoint on trainable index") + torch.cuda.set_device(0) + model = model_for("S1").cuda().train() + model.load_state_dict(state["model"], strict=True) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + sampler = CoverageSampler(INDEX, "S1_S3") + specs = {} + for position in range(200): + spec = sampler.sample(position) + specs.setdefault(spec["source"], spec) + if len(specs) == len(SOURCES): + break + criterion = BimanualLoss(LOSS) + report = {"checkpoint_sha256": sha(args.checkpoint), "samples": {}} + for source, spec in specs.items(): + sample = dataset[spec] + batch = move_to_device(collate_h2o_clips([sample]), torch.device("cuda", 0)) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + losses = criterion(model(batch), batch) + components = {} + for name, value in losses.items(): + if name == "total" or float(value.detach()) == 0.0: + continue + model.zero_grad(set_to_none=True) + value.backward(retain_graph=True) + groups = grad_norms(model) + components[name] = {"weighted_loss": float(value.detach()), + "global_grad_norm": sum(x * x for x in groups.values()) ** .5, + "groups": groups} + model.zero_grad(set_to_none=True) + losses["total"].backward() + groups = grad_norms(model) + report["samples"][source] = { + "tile_id": spec["tile_id"], "mode": spec["mode"], + "total_loss": float(losses["total"].detach()), + "total_grad_norm": sum(x * x for x in groups.values()) ** .5, + "total_groups": groups, "components": components, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps({source: { + "total_grad_norm": row["total_grad_norm"], + "largest_components": sorted( + ((name, entry["global_grad_norm"]) for name, entry in row["components"].items()), + key=lambda pair: pair[1], reverse=True, + )[:6], + "total_groups": row["total_groups"], + } for source, row in report["samples"].items()}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_s1_s2_temporal_transition.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_s1_s2_temporal_transition.py new file mode 100644 index 0000000000000000000000000000000000000000..50fa8bf7a8f13085a4801d5b3286bc098be2ac1a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/diagnose_s1_s2_temporal_transition.py @@ -0,0 +1,85 @@ +"""Measure the temporal block's effect on a frozen staged model.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from clean_train import ROOT, model_for, sha +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--limit", type=int, default=32) + args = parser.parse_args() + if args.limit <= 0 or (args.source != "H2O" and args.mode == "rgb_depth_k"): + raise ValueError("invalid evaluation condition or limit") + + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + manifest = panels / f"{args.source.lower()}_development_t8.jsonl" + if sha(manifest) != panel_report["sources"][args.source]["development"]["manifest_sha256"]: + raise RuntimeError("frozen development panel changed") + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + if (state["stage"] not in ("S1", "S2") or state["update"] < 2000 + or state.get("smoke") or not state.get("complete_backbone")): + raise RuntimeError("requires a complete formal S1/S2 checkpoint") + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + model.to(device).eval() + dataset = dataset_for(args.source, manifest) + limit = min(args.limit, len(dataset)) + rows = {False: [], True: []} + with torch.inference_mode(): + for index in range(limit): + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + for temporal_enabled in (False, True): + model.decoder.temporal_enabled = temporal_enabled + with torch.autocast(device.type, dtype=torch.bfloat16, + enabled=device.type == "cuda"): + prediction = model(batch) + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows[temporal_enabled].append( + make_row(prediction, batch, 0, frame, side) + ) + + summaries = {condition: aggregate(values) for condition, values in rows.items()} + counts_match = all( + summaries[False][metric]["count"] == summaries[True][metric]["count"] + for metric in FOUR_METRICS + ) + if not counts_match: + raise RuntimeError("temporal toggle changed metric denominators") + report = { + "checkpoint_sha256": sha(args.checkpoint), + "checkpoint_stage": state["stage"], "checkpoint_update": state["update"], + "source": args.source, "mode": args.mode, "clips": limit, + "temporal_off": {metric: summaries[False][metric] for metric in FOUR_METRICS}, + "temporal_on": {metric: summaries[True][metric] for metric in FOUR_METRICS}, + "temporal_on_minus_off": { + metric: summaries[True][metric]["mean"] - summaries[False][metric]["mean"] + for metric in FOUR_METRICS + }, + } + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/eval_stratified_probe.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/eval_stratified_probe.py new file mode 100644 index 0000000000000000000000000000000000000000..12e100450b2927f5f87f73686250de0a6ef0a932 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/eval_stratified_probe.py @@ -0,0 +1,195 @@ +"""Evaluate fixed, recording-spread development clips without checkpoint selection.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +import math +from pathlib import Path + +import torch + +from clean_eval import FOUR_METRICS, apply_mode, dataset_for +from clean_train import INDEX, ROOT, model_for, sha, training_code_hashes +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from scripts.evaluate_phase7_external import aggregate, make_row +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +def choose_indices(manifest: Path, limit: int) -> tuple[list[int], int]: + groups: dict[str, list[int]] = defaultdict(list) + with manifest.open() as stream: + for index, line in enumerate(stream): + row = json.loads(line) + group = row.get("take", row.get("group_key")) + if not group: + raise ValueError(f"manifest row {index} has no recording group") + groups[str(group)].append(index) + if limit < len(groups): + raise ValueError("limit must include at least one clip per recording group") + + ordered: dict[str, list[int]] = {} + for group, indices in groups.items(): + size = len(indices) + priorities = [size // 2, size // 4, 3 * size // 4, 0, size - 1] + offsets = list(dict.fromkeys(priorities + list(range(size)))) + ordered[group] = [indices[offset] for offset in offsets] + + selected: list[int] = [] + for depth in range(max(map(len, ordered.values()))): + for group in sorted(ordered): + if depth < len(ordered[group]): + selected.append(ordered[group][depth]) + if len(selected) == limit: + return selected, len(groups) + raise ValueError("limit exceeds manifest length") + + +def paired_group_deltas(reference: list[dict], candidate: list[dict], field: str) -> dict: + if len(reference) != len(candidate): + raise RuntimeError("paired evaluations have different row counts") + groups: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for first, second in zip(reference, candidate): + if first[field] != second[field]: + raise RuntimeError(f"paired {field} identities differ") + for name in FOUR_METRICS: + first_value, second_value = float(first[name]), float(second[name]) + if math.isfinite(first_value) != math.isfinite(second_value): + raise RuntimeError(f"paired {name} validity differs for {field}={first[field]}") + if math.isfinite(first_value): + groups[str(first[field])][name].append(second_value - first_value) + return { + group: { + name: {"count": len(values), "mean_delta": sum(values) / len(values)} + for name, values in metrics.items() + } + for group, metrics in sorted(groups.items()) + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--compare-checkpoint", type=Path) + parser.add_argument("--reference-temporal-off", action="store_true") + parser.add_argument("--compare-temporal-off", action="store_true") + parser.add_argument("--paired-groups", action="store_true") + parser.add_argument("--hybrid-parent-root", action="store_true") + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--mode", choices=("rgb", "rgb_k", "rgb_depth_k"), required=True) + parser.add_argument("--limit", type=int, default=32) + args = parser.parse_args() + if args.source != "H2O" and args.mode == "rgb_depth_k": + raise ValueError("only H2O has real metric depth") + if args.compare_temporal_off and not args.compare_checkpoint: + raise ValueError("--compare-temporal-off requires --compare-checkpoint") + if args.paired_groups and not args.compare_checkpoint: + raise ValueError("--paired-groups requires --compare-checkpoint") + if args.hybrid_parent_root and not args.compare_checkpoint: + raise ValueError("--hybrid-parent-root requires --compare-checkpoint") + + panels = ROOT / "eval/frozen_panels_sync_v2" + panel_report = json.loads((panels / "panels.json").read_text()) + manifest = panels / f"{args.source.lower()}_development_t8.jsonl" + expected = panel_report["sources"][args.source]["development"]["manifest_sha256"] + if sha(manifest) != expected: + raise RuntimeError("frozen development panel changed") + dataset = dataset_for(args.source, manifest) + indices, groups = choose_indices(manifest, args.limit) + if len(dataset) != sum(1 for _ in manifest.open()): + raise RuntimeError("dataset indices differ from frozen manifest rows") + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + checkpoints = [args.checkpoint] + if args.compare_checkpoint: + checkpoints.append(args.compare_checkpoint) + models = [] + identities = [] + for model_index, path in enumerate(checkpoints): + state = torch.load(path, map_location="cpu", weights_only=False) + if (state.get("smoke") or not state.get("complete_backbone") + or state["index_sha256"] != sha(INDEX) + or state["code_sha256"] != training_code_hashes()): + raise RuntimeError(f"checkpoint is not a complete matching formal state: {path}") + model = model_for(state["stage"]) + model.load_state_dict(state["model"], strict=True) + if ((model_index == 0 and args.reference_temporal_off) + or (model_index == 1 and args.compare_temporal_off)): + model.decoder.temporal_enabled = False + models.append(model.to(device).eval()) + identities.append({ + "checkpoint_sha256": sha(path), "stage": state["stage"], + "update": state["update"], + "temporal_enabled": bool(model.decoder.temporal_enabled), + }) + if args.hybrid_parent_root: + identities.append({ + **identities[1], "variant": "compare_local_reference_root", + "root_checkpoint_sha256": identities[0]["checkpoint_sha256"], + }) + rows = [[] for _ in identities] + with torch.inference_mode(): + for index in indices: + batch = collate_h2o_clips([dataset[index]]) + apply_mode(batch, args.mode) + batch = move_to_device(batch, device) + attach_gt_vertices(batch, models[0]) + predictions = [] + for model in models: + with torch.autocast(device.type, dtype=torch.bfloat16, + enabled=device.type == "cuda"): + predictions.append(model(batch)) + if args.hybrid_parent_root: + parent, candidate = predictions + delta = parent["wrist_root_translation"] - candidate["wrist_root_translation"] + hybrid = dict(candidate) + hybrid["wrist_root_translation"] = parent["wrist_root_translation"] + hybrid["joints_camera"] = candidate["joints_camera"] + delta.unsqueeze(-2) + hybrid["vertices_camera"] = candidate["vertices_camera"] + delta.unsqueeze(-2) + predictions.append(hybrid) + for model_index, prediction in enumerate(predictions): + for frame in range(batch["frame_valid"].shape[1]): + if bool(batch["frame_valid"][0, frame]): + for side in range(2): + rows[model_index].append( + make_row(prediction, batch, 0, frame, side) + ) + summaries = [aggregate(values) for values in rows] + if any(summary[name]["count"] == 0 for summary in summaries for name in FOUR_METRICS): + raise RuntimeError("stratified probe has an empty metric denominator") + if len(summaries) >= 2 and any( + summaries[0][name]["count"] != summary[name]["count"] + for summary in summaries[1:] for name in FOUR_METRICS + ): + raise RuntimeError("paired checkpoints have different metric denominators") + if args.hybrid_parent_root: + paired_group_deltas(rows[0], rows[2], "physical_recording_id") + print(json.dumps({ + "source": args.source, "mode": args.mode, + "panel_sha256": expected, "selection": "recording_round_robin_center", + "selected_indices": indices, "recording_groups": groups, + "results": [ + {**identity, "four_metrics": {name: summary[name] for name in FOUR_METRICS}} + for identity, summary in zip(identities, summaries) + ], + "compare_minus_reference": { + name: summaries[1][name]["mean"] - summaries[0][name]["mean"] + for name in FOUR_METRICS + } if len(summaries) >= 2 else None, + "hybrid_minus_reference": { + name: summaries[2][name]["mean"] - summaries[0][name]["mean"] + for name in FOUR_METRICS + } if args.hybrid_parent_root else None, + "hybrid_minus_compare": { + name: summaries[2][name]["mean"] - summaries[1][name]["mean"] + for name in FOUR_METRICS + } if args.hybrid_parent_root else None, + "paired_groups": { + "headset": paired_group_deltas(rows[0], rows[1], "headset_id"), + "recording": paired_group_deltas(rows[0], rows[1], "physical_recording_id"), + } if args.paired_groups else None, + }, separators=(",", ":"))) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/export_adapter_manifests.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/export_adapter_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..7120aeaf9b953c4f5a4a3ad64ee3c5deaaa3d5d9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/export_adapter_manifests.py @@ -0,0 +1,94 @@ +"""Translate frozen filtered tiles to the three existing native source adapters.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sqlite3 + + +def adapter_row(window: dict, tile_id: str, start: int, frames: list[int], time: int) -> dict: + dataset = window["dataset"] + source = window["source"] + selected = frames if time == 8 else [frames[0]] + shared = { + "filtered_tile_id": tile_id, + "filtered_window_id": window["id"], + "filtered_gt_path": window["filtered_gt_path"], + "filtered_start_offset": start, + "expected_frame_ids": selected, + } + if dataset == "ARCTIC": + offset = int(source["offset"]) + subject = window["recording_id"].split("/")[0] + return { + **shared, "dataset_id": "ARCTIC", "protocol": "P2", + "split_role": "arctic_p2_train", "subject_id": subject, + "physical_recording_id": window["recording_id"], + "group_key": f"ARCTIC/{subject}/{window['recording_id']}", + "camera_id": "ego_view_0_rectified", + "frame_ids_1based": selected, + "array_indices_0based": [frame - offset for frame in selected], + "image_paths": [source["rgb_template"].format(frame=frame) for frame in selected], + "mano_path": source["mano_path"], "camera_path": source["camera_path"], + "depth_input_available": False, "official_test_used": False, + } + if dataset == "H2O": + return {**shared, "take": window["recording_id"], "frame_ids": selected} + if dataset == "HOT3D": + path = Path(window["recording_id"]) + return { + **shared, "dataset": "HOT3D", "have_hand_object_pose_gt": True, + "recording_id": window["recording_id"], "participant_id": path.name.split("_")[0], + "stream_id": window["stream_id"], "headset": source["device"], + "timestamps_ns": window["_timestamps_ns"][start:start + len(selected)], + } + raise ValueError(f"foreign source {dataset}") + + +def export(index: Path, output: Path, time: int) -> dict[str, int]: + if time not in (1, 8): + raise ValueError("only T=1 and T=8 are registered") + output.mkdir(parents=True, exist_ok=False) + counts = {name: 0 for name in ("ARCTIC", "H2O", "HOT3D")} + files = {name: (output / f"{name.lower()}_t{time}.jsonl").open("w") for name in counts} + last_window = None + window = None + try: + with sqlite3.connect(index) as connection: + cursor = connection.execute( + "SELECT t.tile_id,t.window_id,t.source,t.start_offset,t.frame_ids_json," + "w.manifest_json FROM tiles t JOIN windows w ON t.window_id=w.window_id " + "ORDER BY t.source,t.window_id,t.start_offset" + ) + for tile_id, window_id, source_name, start, frames_json, manifest_json in cursor: + if window_id != last_window: + window = json.loads(manifest_json) + if source_name == "HOT3D": + timeline = json.loads(Path(window["source"]["timestamps_path"]).read_text()) + window["_timestamps_ns"] = timeline[str(window["stream_id"])][ + int(window["start"]):int(window["end"]) + ] + last_window = window_id + assert window is not None + row = adapter_row(window, tile_id, start, json.loads(frames_json), time) + files[source_name].write(json.dumps(row, separators=(",", ":")) + "\n") + counts[source_name] += 1 + finally: + for handle in files.values(): + handle.close() + return counts + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--index", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--time", type=int, choices=(1, 8), required=True) + args = parser.parse_args() + print(json.dumps(export(args.index, args.output, args.time), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/filtered_dataset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/filtered_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..ab36aee3e3c74559a40f03ce185464476858cd67 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/filtered_dataset.py @@ -0,0 +1,138 @@ +"""Use native source decoders while enforcing the frozen filtered-GT allowlist.""" + +from __future__ import annotations + +from functools import lru_cache +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS, corrupt_metric_depth +from foundation_hand.data.h2o_dataset import H2OCam4Dataset +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + +from coverage_sampler import _seed + + +@lru_cache(maxsize=256) +def filtered_valid(gt_path: str) -> tuple[np.ndarray, np.ndarray]: + with np.load(gt_path, allow_pickle=False) as payload: + return payload["frame_ids"].copy(), payload["valid"].astype(bool).copy() + + +MASKS = ( + "joint_element_valid", "joint_annotation_valid", "mano_annotation_valid", + "joint2d_valid", "joint3d_valid", "joint3d_root_relative_valid", + "translation_valid", "mano_pose_valid", "shape_valid", "vertices_valid", + "reprojection_valid", +) + + +def intersect_filtered_valid(sample: dict[str, Any], row: dict[str, Any]) -> None: + frame_ids, valid = filtered_valid(str(row["filtered_gt_path"])) + start = int(row["filtered_start_offset"]) + time = len(row["expected_frame_ids"]) + expected = np.asarray(row["expected_frame_ids"], dtype=np.int64) + if not np.array_equal(frame_ids[start:start + time], expected): + raise ValueError(f"filtered/native frame disagreement: {row['filtered_tile_id']}") + if sample["dataset_id"] == "HOT3D": + if not torch.equal(sample["timestamp_ns"], torch.as_tensor(row["timestamps_ns"])): + raise ValueError("HOT3D image and GT timeline disagree") + elif not torch.equal(sample["frame_id"], torch.from_numpy(expected)): + raise ValueError("image and filtered GT frame IDs disagree") + hand = torch.from_numpy(valid[start:start + time]).bool() + if hand.shape != (time, 2): + raise ValueError("filtered hand validity has wrong shape") + for key in MASKS: + if key not in sample: + continue + mask = sample[key] + if mask.shape[:2] != (time, 2) or mask.dtype != torch.bool: + raise ValueError(f"invalid native loss mask {key}: {mask.shape}") + expanded = hand + while expanded.ndim < mask.ndim: + expanded = expanded.unsqueeze(-1) + sample[key] = mask & expanded + + +class FilteredClipDataset(Dataset[dict[str, Any]]): + def __init__( + self, source: str, manifest: str | Path, time: int, target_hw: tuple[int, int], + mano_root: str | Path, hot3d_toolkit: str | Path, + photometric_augmentation: dict | None = None, + ) -> None: + self.source = source + self.rows = [json.loads(line) for line in Path(manifest).open() if line.strip()] + self.by_tile = {str(row["filtered_tile_id"]): index for index, row in enumerate(self.rows)} + if len(self.by_tile) != len(self.rows): + raise ValueError("duplicate filtered tile ID") + if source == "ARCTIC": + self.native = ARCTICClipDataset( + manifest, mano_root, target_hw, photometric_augmentation, 20260925, + hand_valid_policy="visible_mesh", + ) + elif source == "H2O": + self.native = H2OCam4Dataset( + "/SSD3/jiasen/foundation_hand/H2O/extracted", manifest, target_hw, + clip_lengths=(time,), strides=(1,), window_step=time, + allow_partial=False, photometric_augmentation=photometric_augmentation, + augmentation_seed=20260925, + ) + elif source == "HOT3D": + self.native = HOT3DClipDataset( + "/SSD3/jiasen/foundation_hand/HOT3D/dataset", manifest, + hot3d_toolkit, mano_root, target_hw, K_input_dropout=0.0, + ) + else: + raise ValueError(f"foreign source {source}") + if len(self.native) != len(self.rows): + raise ValueError("native adapter clip count differs from filtered index") + + def __len__(self) -> int: + return len(self.rows) + + def __getitem__(self, spec: dict[str, Any]) -> dict[str, Any]: + if spec["source"] != self.source: + raise ValueError("sample source differs from native adapter") + index = self.by_tile[str(spec["tile_id"])] + row = self.rows[index] + sample = self.native[(index, int(spec["epoch"]))] + intersect_filtered_valid(sample, row) + frame = sample["frame_valid"].bool() + mode = str(spec["mode"]) + if mode not in ("rgb", "rgb_k", "rgb_depth_k"): + raise ValueError(f"foreign input mode {mode}") + if mode == "rgb_depth_k" and self.source != "H2O": + raise ValueError("only H2O supplies real metric depth") + sample["K_input_available"] = frame & (mode != "rgb") + sample["depth_input_available"] = frame & (mode == "rgb_depth_k") + sample["K_available"] = sample["K_input_available"].clone() + sample["depth_available"] = sample["depth_input_available"].clone() + condition_code = 2 if mode == "rgb_depth_k" else 1 if self.source == "H2O" else 0 + if self.source == "H2O" and mode == "rgb_depth_k": + import random + position = int(spec["position"]) + rng = random.Random(_seed(20260925, "depth", position)) + if rng.random() < .30: + corruption = DEPTH_CORRUPTIONS[rng.randrange(len(DEPTH_CORRUPTIONS))] + depth, pixel_valid = corrupt_metric_depth( + sample["depth_m"].numpy(), sample["depth_pixel_valid"].numpy(), + corruption, seed=_seed(20260925, "corruption", position), + ) + sample["depth_m"] = torch.from_numpy(depth) + sample["depth_pixel_valid"] = torch.from_numpy(pixel_valid) + condition_code = 3 + DEPTH_CORRUPTIONS.index(corruption) + sample["depth_input_condition_code"] = torch.full( + frame.shape, condition_code, dtype=torch.long, + ) + sample["sampling_source_id"] = self.source + sample["filtered_tile_id"] = row["filtered_tile_id"] + sample["input_mode"] = mode + sample["source_ordinal"] = torch.full(frame.shape, int(spec["source_ordinal"]), dtype=torch.long) + sample["coverage_epoch"] = torch.full(frame.shape, int(spec["epoch"]), dtype=torch.long) + return sample diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/freeze_eval_panels.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/freeze_eval_panels.py new file mode 100644 index 0000000000000000000000000000000000000000..d84948d25345cda0de302ae204eaacf2a742d860 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/freeze_eval_panels.py @@ -0,0 +1,139 @@ +"""Freeze recording-disjoint development and confirmation GT panels.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path + +import numpy as np + +from audit_headset_sync import MAX_DELTA_NS, deltas, trajectory +from preflight_index import digest, tile_starts, EXPECTED_MANIFEST_SHA256 + + +SOURCES = { + "ARCTIC": Path("/SSD3/jiasen/foundation_hand/phase7_artifacts/manifests/arctic_p2_v2/arctic_p2_val_t8.jsonl"), + "H2O": Path("/SSD3/jiasen/foundation_hand/H2O/extracted/label_split/pose_val.txt"), + "HOT3D": Path("/SSD3/jiasen/foundation_hand/phase7_artifacts/manifests/hot3d_gt_v1_retry2/hot3d_heldout_t8.jsonl"), +} + + +def h2o_rows(path: Path) -> list[dict]: + by_take: dict[str, set[int]] = defaultdict(set) + for line in path.open(): + item = Path(line.strip()) + if not line.strip(): + continue + take = str(item.parents[1]) + if not take.endswith("cam4"): + raise ValueError(f"foreign H2O validation view {take}") + by_take[take].add(int(item.stem)) + rows = [] + for take, values in by_take.items(): + ids = sorted(values) + start = 0 + for position in range(1, len(ids) + 1): + if position < len(ids) and ids[position] == ids[position - 1] + 1: + continue + run = ids[start:position] + if len(run) >= 8: + for offset in tile_starts(len(run)): + rows.append({"take": take, "frame_ids": run[offset:offset + 8]}) + start = position + return rows + + +def load_jsonl(path: Path) -> list[dict]: + return [json.loads(line) for line in path.open() if line.strip()] + + +def recording(source: str, row: dict) -> str: + return row["take"] if source == "H2O" else row[ + "physical_recording_id" if source == "ARCTIC" else "recording_id" + ] + + +def clip_time(source: str, row: dict) -> int: + key = "frame_ids" if source == "H2O" else "frame_ids_1based" if source == "ARCTIC" else "timestamps_ns" + return int(row[key][0]) + + +def hot3d_headset_valid(row: dict) -> bool: + path = Path("/SSD3/jiasen/foundation_hand/HOT3D/dataset") / row["recording_id"] + stamps = np.asarray(row["timestamps_ns"], dtype=np.int64) + return bool(np.all(deltas(stamps, trajectory(str(path))) <= MAX_DELTA_NS)) + + +def freeze(train_manifest: Path, output: Path, per_recording: int = 8) -> dict: + if digest(train_manifest) != EXPECTED_MANIFEST_SHA256: + raise ValueError("training manifest differs from frozen allowlist") + if output.exists(): + raise FileExistsError(output) + train_recordings: dict[str, set[str]] = defaultdict(set) + for row in load_jsonl(train_manifest): + train_recordings[row["dataset"]].add(row["recording_id"]) + rows = { + "H2O": h2o_rows(SOURCES["H2O"]), + "ARCTIC": load_jsonl(SOURCES["ARCTIC"]), + "HOT3D": load_jsonl(SOURCES["HOT3D"]), + } + hot3d_total = len(rows["HOT3D"]) + rows["HOT3D"] = [row for row in rows["HOT3D"] if hot3d_headset_valid(row)] + plan: dict[str, dict] = {} + selected: dict[tuple[str, str], list[dict]] = {} + for source, values in rows.items(): + groups: dict[str, list[dict]] = defaultdict(list) + for row in values: + groups[recording(source, row)].append(row) + if train_recordings[source] & set(groups): + raise ValueError(f"{source} validation overlaps filtered train recordings") + ranked = sorted(groups, key=lambda name: hashlib.sha256( + f"clean-gt-eval-20260925|{source}|{name}".encode(), + ).digest()) + if len(ranked) < 2: + raise ValueError(f"{source} lacks disjoint validation recordings") + boundary = len(ranked) // 2 + plan[source] = {"train_recordings": len(train_recordings[source]), + "validation_recordings": len(ranked), "train_overlap": 0, + "source_sha256": digest(SOURCES[source])} + if source == "HOT3D": + plan[source]["candidate_clips"] = hot3d_total + plan[source]["clips_rejected_headset_sync"] = hot3d_total - len(values) + plan[source]["headset_sync_threshold_ms"] = MAX_DELTA_NS / 1e6 + for role, names in (("development", ranked[:boundary]), ("confirmation", ranked[boundary:])): + chosen = [] + for name in names: + candidates = sorted(groups[name], key=lambda row: clip_time(source, row)) + indices = np.linspace(0, len(candidates) - 1, + min(per_recording, len(candidates)), dtype=int) + chosen.extend(candidates[int(index)] for index in indices) + selected[source, role] = chosen + plan[source][role] = {"recordings": len(names), "clips": len(chosen), + "recording_ids": names} + output.mkdir(parents=True) + for (source, role), values in selected.items(): + path = output / f"{source.lower()}_{role}_t8.jsonl" + with path.open("w") as stream: + for row in values: + stream.write(json.dumps(row, separators=(",", ":")) + "\n") + plan[source][role]["manifest_sha256"] = digest(path) + report = {"status": "frozen", "train_manifest_sha256": EXPECTED_MANIFEST_SHA256, + "rule": "recording-disjoint, 8 spread T8 clips per recording; confirmation unopened for selection", + "sources": plan} + (output / "panels.json").write_text(json.dumps(report, indent=2) + "\n") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--train-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(freeze(args.train_manifest, args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/preflight_index.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/preflight_index.py new file mode 100644 index 0000000000000000000000000000000000000000..f5153a5cd84d39d0fd4e5779d33ab123eb1f11de --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/preflight_index.py @@ -0,0 +1,195 @@ +"""Audit the filtered GT allowlist and build a complete, immutable T=8 index. + +The index contains references only. It never copies or decodes source images. +""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +import os +from pathlib import Path +import sqlite3 + +import numpy as np + + +EXPECTED_MANIFEST_SHA256 = "b4b0ac4bc4a771c9bc7626a9eec7f5f541ef96908a9a64d219192efd7b8f7f89" +EXPECTED_WINDOWS = {"ARCTIC": 2939, "H2O": 928, "HOT3D": 18962} +EXPECTED_TILES = {"ARCTIC": 22750, "H2O": 6406, "HOT3D": 143930} + + +def digest(path: Path) -> str: + value = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(4 * 1024 * 1024), b""): + value.update(block) + return value.hexdigest() + + +def tile_starts(length: int, tile_size: int = 8) -> list[int]: + if length < tile_size: + raise ValueError(f"window has only {length} frames") + starts = list(range(0, length - tile_size + 1, tile_size)) + if starts[-1] + tile_size < length: + starts.append(length - tile_size) + covered = set().union(*(range(start, start + tile_size) for start in starts)) + if covered != set(range(length)): + raise AssertionError(f"tile coverage incomplete for length={length}") + return starts + + +def source_frame_paths(row: dict, frame_ids: np.ndarray) -> list[Path]: + source = row["source"] + if row["dataset"] == "HOT3D": + return [Path(source["root"]), Path(source["timestamps_path"])] + template = str(source["rgb_template"]) + paths = [Path(template.format(frame=int(frame_id))) for frame_id in frame_ids] + if row["dataset"] == "H2O": + root = Path(source["root"]) + paths += [root / "depth" / f"{int(frame_id):06d}.png" for frame_id in frame_ids] + paths += [root / "hand_pose" / f"{int(frame_id):06d}.txt" for frame_id in frame_ids] + paths += [root / "hand_pose_mano" / f"{int(frame_id):06d}.txt" for frame_id in frame_ids] + paths.append(root / "cam_intrinsics.txt") + elif row["dataset"] == "ARCTIC": + paths += [Path(source["mano_path"]), Path(source["camera_path"])] + return paths + + +def audit_window(row: dict, check_paths: bool) -> tuple[np.ndarray, np.ndarray, list[int]]: + if row.get("retained") is not True or row.get("filter_reason") != "retained": + raise ValueError("window is not retained") + name = row["dataset"] + if name not in EXPECTED_WINDOWS: + raise ValueError(f"foreign dataset {name}") + gt = Path(row["filtered_gt_path"]) + if not gt.is_file() or digest(gt) != row["gt_sha256"]: + raise ValueError(f"GT missing or hash mismatch: {gt}") + with np.load(gt, allow_pickle=False) as payload: + if "frame_ids" not in payload or "valid" not in payload: + raise ValueError("GT lacks frame_ids or valid") + frame_ids = payload["frame_ids"].astype(np.int64) + valid = payload["valid"].astype(bool) + if valid.shape != (len(frame_ids), 2): + raise ValueError(f"invalid hand mask shape {valid.shape}") + if name == "H2O" and "joints_native_m" not in payload: + raise ValueError("H2O lacks native joints") + length = int(row["frame_count"]) + if length != len(frame_ids) or length != int(row["end"]) - int(row["start"]): + raise ValueError("manifest/GT length disagreement") + if np.any(np.diff(frame_ids) <= 0): + raise ValueError("native frame IDs are not strictly increasing") + if name == "ARCTIC": + offset = int(row["source"]["offset"]) + if offset < 1 or not np.array_equal( + frame_ids, np.arange(int(row["start"]) + offset, int(row["end"]) + offset) + ): + raise ValueError("ARCTIC frame IDs disagree with registered sequence offset") + if name == "HOT3D": + timeline_path = Path(row["source"]["timestamps_path"]) + if not timeline_path.is_file(): + raise ValueError("HOT3D timeline is missing") + timeline = json.loads(timeline_path.read_text(encoding="utf-8")) + timestamps = timeline[str(row["stream_id"])][int(row["start"]):int(row["end"])] + if len(timestamps) != length: + raise ValueError("HOT3D timeline slice length mismatch") + if check_paths: + missing = next((str(path) for path in source_frame_paths(row, frame_ids) if not path.is_file() and not path.is_dir()), None) + if missing: + raise FileNotFoundError(missing) + return frame_ids, valid, tile_starts(length) + + +def build(manifest: Path, output: Path, check_paths: bool = True) -> dict: + if digest(manifest) != EXPECTED_MANIFEST_SHA256: + raise ValueError("filtered manifest SHA256 differs from frozen recipe") + if output.exists(): + raise FileExistsError(f"refusing to overwrite index: {output}") + output.parent.mkdir(parents=True, exist_ok=True) + temporary = output.with_suffix(output.suffix + ".tmp") + if temporary.exists(): + raise FileExistsError(f"unfinished index already exists: {temporary}") + connection = sqlite3.connect(temporary) + try: + connection.executescript(""" + CREATE TABLE windows ( + window_id TEXT PRIMARY KEY, source TEXT NOT NULL, + recording_id TEXT NOT NULL, stream_id TEXT, + manifest_json TEXT NOT NULL, frame_ids_json TEXT NOT NULL, + valid_left INTEGER NOT NULL, valid_right INTEGER NOT NULL + ); + CREATE TABLE tiles ( + tile_id TEXT PRIMARY KEY, window_id TEXT NOT NULL, + source TEXT NOT NULL, recording_id TEXT NOT NULL, + start_offset INTEGER NOT NULL, frame_ids_json TEXT NOT NULL, + FOREIGN KEY(window_id) REFERENCES windows(window_id) + ); + CREATE INDEX tiles_source_recording ON tiles(source, recording_id); + """) + windows: Counter[str] = Counter() + tiles: Counter[str] = Counter() + frame_entries: Counter[str] = Counter() + valid_hands: Counter[str] = Counter() + recordings: dict[str, set[str]] = {name: set() for name in EXPECTED_WINDOWS} + for line_number, line in enumerate(manifest.open(encoding="utf-8"), 1): + if not line.strip(): + continue + row = json.loads(line) + try: + frame_ids, valid, starts = audit_window(row, check_paths) + name = row["dataset"] + window_id = str(row["id"]) + recording_id = str(row["recording_id"]) + connection.execute( + "INSERT INTO windows VALUES (?,?,?,?,?,?,?,?)", + (window_id, name, recording_id, row.get("stream_id"), + json.dumps(row, separators=(",", ":")), + json.dumps(frame_ids.tolist()), int(valid[:, 0].sum()), int(valid[:, 1].sum())), + ) + for start in starts: + selected = frame_ids[start:start + 8].tolist() + connection.execute( + "INSERT INTO tiles VALUES (?,?,?,?,?,?)", + (f"{window_id}:{start}", window_id, name, recording_id, + start, json.dumps(selected)), + ) + windows[name] += 1 + tiles[name] += len(starts) + frame_entries[name] += len(frame_ids) + valid_hands[f"{name}:left"] += int(valid[:, 0].sum()) + valid_hands[f"{name}:right"] += int(valid[:, 1].sum()) + recordings[name].add(recording_id) + except Exception as error: + raise ValueError(f"manifest line {line_number}, id={row.get('id')}: {error}") from error + if dict(windows) != EXPECTED_WINDOWS or dict(tiles) != EXPECTED_TILES: + raise ValueError(f"coverage counts differ: windows={windows}, tiles={tiles}") + connection.commit() + except BaseException: + connection.close() + temporary.unlink(missing_ok=True) + raise + connection.close() + os.replace(temporary, output) + return { + "status": "pass", "manifest_sha256": EXPECTED_MANIFEST_SHA256, + "index_sha256": digest(output), "windows": dict(windows), + "tiles": dict(tiles), "frame_entries": dict(frame_entries), + "valid_hands": dict(valid_hands), + "recordings": {name: len(values) for name, values in recordings.items()}, + "source_paths_checked": check_paths, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--skip-source-paths", action="store_true") + args = parser.parse_args() + print(json.dumps(build(args.manifest, args.output, not args.skip_source_paths), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/probe_cold_start.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/probe_cold_start.py new file mode 100644 index 0000000000000000000000000000000000000000..6344fe0a91a9615173f3021e4df3437da404629e --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/probe_cold_start.py @@ -0,0 +1,95 @@ +"""Compare cold-start gradient flow without changing data, loss, or LR.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch +from torch import nn + +from clean_train import INDEX, LOSS, MixedDataset, STAGES, model_for +from coverage_sampler import CoverageSampler, SOURCES +from diagnose_initial_gradients import grad_norms +from foundation_hand.data.h2o_dataset import collate_h2o_clips +from foundation_hand.training.losses import BimanualLoss +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +VARIANTS = ( + ("zero_heads_zero_depth", 0.0, 0.0), + ("head_1e-2_zero_depth", 1e-2, 0.0), + ("head_1e-2_depth_1e-4", 1e-2, 1e-4), + ("head_5e-3_depth_1e-3", 5e-3, 1e-3), + ("head_1e-3_depth_1e-3", 1e-3, 1e-3), +) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + dataset = MixedDataset(1, STAGES["S1"]["hw"]) + coverage = CoverageSampler(INDEX, "S1_S3") + specs = {} + for position in range(200): + spec = coverage.sample(position) + specs.setdefault(spec["source"], spec) + if len(specs) == len(SOURCES): + break + device = torch.device("cuda", 0) + batches = { + source: move_to_device(collate_h2o_clips([dataset[spec]]), device) + for source, spec in specs.items() + } + criterion = BimanualLoss(LOSS) + results = [] + for name, head_std, depth_std in VARIANTS: + torch.manual_seed(20260925) + model = model_for("S1") + with torch.no_grad(): + for head in ( + model.joint2d_head, model.rotation_head, + model.translation_head, model.shape_head, + ): + if head_std: + nn.init.normal_(head.weight, std=head_std) + else: + nn.init.zeros_(head.weight) + final_depth = model.depth_encoder.encoder[-1] + if depth_std: + nn.init.normal_(final_depth.weight, std=depth_std) + else: + nn.init.zeros_(final_depth.weight) + model.to(device).train() + item = {"variant": name, "head_std": head_std, "depth_std": depth_std, + "samples": {}} + for source, batch in batches.items(): + model.zero_grad(set_to_none=True) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=torch.bfloat16): + losses = criterion(model(batch), batch) + losses["total"].backward() + groups = grad_norms(model) + item["samples"][source] = { + "mode": specs[source]["mode"], + "loss": float(losses["total"].detach()), + "grad_norm": sum(x * x for x in groups.values()) ** .5, + "decoder_grad": groups.get("decoder.spatial", 0.0), + "projection_grad": groups.get("rgb_encoder.projection", 0.0), + "depth_grad": groups.get("depth_encoder", 0.0), + "translation_head_grad": groups.get("translation_head", 0.0), + } + results.append(item) + del model + torch.cuda.empty_cache() + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(results, indent=2) + "\n") + print(json.dumps(results, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/run_formal_stages.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/run_formal_stages.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd55afacfa5d7d36a86318e62b0f4edd6bf4a47 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/run_formal_stages.py @@ -0,0 +1,186 @@ +"""Continue the registered six-GPU clean-GT stages after the S1 health gate.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +import subprocess +import time + + +ROOT = Path("/home/wuyifan/foundation_hand_clean_gt_dino_20260925") +CODE = ROOT / "code" +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +CHECKPOINTS = ROOT / "checkpoints" +LOGS = ROOT / "logs" +EVAL = ROOT / "eval" +RUN_TAG = "formal_v3" +S1_HEALTH_PIDFILE = LOGS / f"{RUN_TAG}_s1_health2k.pid" +S1_PIDFILE = LOGS / f"{RUN_TAG}_s1_full.pid" +ENDPOINTS = {"S1": 16667, "S2": 50000, "S3": 83334, "S4": 66667} +MODES = { + "H2O": ("rgb", "rgb_k", "rgb_depth_k"), + "ARCTIC": ("rgb", "rgb_k"), + "HOT3D": ("rgb", "rgb_k"), +} + + +def checksum(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def state(event: str, **details: object) -> None: + payload = {"event": event, "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S%z"), **details} + path = LOGS / f"{RUN_TAG}_controller_state.json" + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n") + temporary.replace(path) + print(json.dumps(payload), flush=True) + + +def endpoint(stage: str, update: int) -> Path: + return CHECKPOINTS / f"{RUN_TAG}_{stage.lower()}" / f"{stage.lower()}_update_{update:07d}.pt" + + +def process_running(pidfile: Path) -> bool: + if not pidfile.exists(): + return False + return subprocess.run( + ["start-stop-daemon", "--status", "--pidfile", str(pidfile)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, + ).returncode == 0 + + +def wait_for_s1_health() -> None: + target = endpoint("S1", 2000) + deadline = time.monotonic() + 3 * 3600 + if not process_running(S1_HEALTH_PIDFILE) and not target.is_file(): + raise RuntimeError("S1 health process is absent without a complete endpoint") + while process_running(S1_HEALTH_PIDFILE): + if time.monotonic() > deadline: + raise TimeoutError("S1 health exceeded its three-hour watchdog") + time.sleep(30) + if not target.is_file(): + raise RuntimeError("S1 health stopped without its complete formal endpoint") + + +def run_logged(command: list[str], log: Path) -> None: + if log.exists(): + raise FileExistsError(f"refusing to overwrite an existing run log: {log}") + print(json.dumps({"run": command, "log": str(log)}), flush=True) + with log.open("xb") as stream: + result = subprocess.run(command, cwd=CODE, stdout=stream, stderr=subprocess.STDOUT, + check=False) + if result.returncode != 0: + raise RuntimeError(f"command exited {result.returncode}; inspect {log}") + + +def audit(stage: str, update: int) -> dict: + target = endpoint(stage, update) + report_path = LOGS / f"{RUN_TAG}_{stage.lower()}_{update:07d}_audit.json" + if report_path.exists(): + report = json.loads(report_path.read_text()) + if report["status"] != "pass" or report["checkpoint_sha256"] != checksum(target): + raise RuntimeError(f"stale or failed endpoint audit: {report_path}") + else: + run_logged([ + PYTHON, str(CODE / "audit_formal_stage.py"), + "--checkpoint", str(target), + "--metrics", str(target.parent / "metrics.jsonl"), + "--stage", stage, "--update", str(update), + "--output", str(report_path), + ], LOGS / f"{RUN_TAG}_{stage.lower()}_{update:07d}_audit.console.log") + report = json.loads(report_path.read_text()) + if report["status"] != "pass": + raise RuntimeError(f"endpoint audit failed: {report_path}") + if update == 2000 and report["last_window_loss_mean"] > 2 * report["first_window_loss_mean"]: + raise RuntimeError(f"early-stage loss grew more than twofold: {report_path}") + state("audited", stage=stage, update=update, checkpoint_sha256=report["checkpoint_sha256"]) + return report + + +def train(stage: str, update: int, previous: Path) -> Path: + target = endpoint(stage, update) + if target.is_file(): + audit(stage, update) + return target + output = target.parent + command = [ + PYTHON, "-m", "torch.distributed.run", "--standalone", "--nproc_per_node=6", + "clean_train.py", "--stage", stage, "--output", str(output), + "--updates", str(update), "--workers", "2", "--save", + ] + if update == 2000: + if output.exists(): + raise FileExistsError(f"uncompleted formal stage requires diagnosis: {output}") + command += ["--parent", str(previous)] + else: + command += ["--resume", str(previous)] + label = "health2k" if update == 2000 else "full" + state("training", stage=stage, update=update, parent=str(previous)) + run_logged(command, LOGS / f"{RUN_TAG}_{stage.lower()}_{label}.console.log") + if not target.is_file(): + raise RuntimeError(f"training returned without endpoint: {target}") + audit(stage, update) + return target + + +def evaluate(stage: str, update: int, *, full: bool, confirmation: bool = False) -> None: + target = endpoint(stage, update) + role = "confirmation" if confirmation else "development" + conditions = [(source, mode) for source, modes in MODES.items() for mode in modes] + if not full: + conditions = [("H2O", "rgb_depth_k"), ("ARCTIC", "rgb_k"), ("HOT3D", "rgb_k")] + for source, mode in conditions: + tag = f"{RUN_TAG}_{stage.lower()}_{update:07d}_{role}_{source.lower()}_{mode}" + report_path = EVAL / "formal_stages" / f"{tag}.json" + if report_path.exists(): + report = json.loads(report_path.read_text()) + if (report["checkpoint_sha256"] != checksum(target) or report["source"] != source + or report["input_mode"] != mode or report["role"] != role): + raise RuntimeError(f"stale evaluation report: {report_path}") + continue + command = [ + PYTHON, str(CODE / "clean_eval.py"), "--checkpoint", str(target), + "--source", source, "--role", role, "--mode", mode, + "--output", str(report_path), + ] + if confirmation: + command.append("--final-checkpoint") + elif not full: + command += ["--allow-smoke", "--limit", "32"] + run_logged(command, LOGS / f"{tag}.console.log") + report = json.loads(report_path.read_text()) + if any(value["count"] == 0 for value in report["four_metrics"].values()): + raise RuntimeError(f"evaluation has an empty metric denominator: {report_path}") + state("evaluated", stage=stage, update=update, source=source, mode=mode, + role=role, report=str(report_path)) + + +def main() -> None: + try: + state("waiting_for_s1_health") + wait_for_s1_health() + audit("S1", 2000) + evaluate("S1", 2000, full=False) + parent = train("S1", ENDPOINTS["S1"], endpoint("S1", 2000)) + evaluate("S1", ENDPOINTS["S1"], full=False) + for stage in ("S2", "S3", "S4"): + short = train(stage, 2000, parent) + evaluate(stage, 2000, full=False) + parent = train(stage, ENDPOINTS[stage], short) + evaluate(stage, ENDPOINTS[stage], full=stage in ("S3", "S4")) + evaluate("S4", ENDPOINTS["S4"], full=True, confirmation=True) + state("complete", checkpoint=str(parent), checkpoint_sha256=checksum(parent)) + except Exception as error: + state("failed", error=f"{type(error).__name__}: {error}") + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/adapt_phase3_validation_subset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/adapt_phase3_validation_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..3597f9540602b5d9249706b44f33431b996d1b6b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/adapt_phase3_validation_subset.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Clone a fixed validation selection under a new preprocessing contract.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--resolution-hw", type=int, nargs=2, required=True) + args = parser.parse_args() + + source = json.loads(args.source.read_text(encoding="utf-8")) + record = dict(source) + record["version"] = f"{source['version']}_resolution_contract_v1" + record["parent_selection_manifest"] = str(args.source.resolve()) + record["parent_selection_manifest_sha256"] = sha256(args.source) + record["dataset_contract"] = dict(source["dataset_contract"]) + record["dataset_contract"]["resolution_hw"] = list(args.resolution_hw) + record["adaptation"] = ( + "Clip indices and all selection metadata are copied exactly; only the " + "resize/padding resolution contract changes." + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "created", + "output": str(args.output), + "count": len(record["clip_indices"]), + "resolution_hw": record["dataset_contract"]["resolution_hw"], + "sha256": sha256(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/analyze_phase8_checkpoint_drift.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/analyze_phase8_checkpoint_drift.py new file mode 100644 index 0000000000000000000000000000000000000000..75eb62e3785a60f5e05394066d2518db310df246 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/analyze_phase8_checkpoint_drift.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Measure layerwise model-parameter drift between two hash-bound checkpoints.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import torch + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _model_state(path: Path, expected_sha256: str) -> tuple[dict[str, torch.Tensor], dict[str, Any]]: + actual = sha256(path) + if actual != expected_sha256: + raise ValueError(f"checkpoint SHA256 differs: {path}") + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + state = checkpoint.get("model") + if not isinstance(state, dict) or not state: + raise ValueError(f"checkpoint has no model state: {path}") + return state, { + "path": str(path.resolve()), "sha256": actual, + "step": int(checkpoint.get("step", -1)), + "h2o_training_data_used": checkpoint.get("extra", {}).get( + "h2o_training_data_used" + ), + "official_test_used": checkpoint.get("extra", {}).get("official_test_used"), + } + + +def _group(name: str, depth: int) -> str: + components = name.split(".") + return ".".join(components[:depth]) + + +def analyze( + reference_path: Path, + reference_sha256: str, + candidate_path: Path, + candidate_sha256: str, + *, + group_depth: int = 2, +) -> dict[str, Any]: + if group_depth <= 0: + raise ValueError("group_depth must be positive") + reference, reference_meta = _model_state(reference_path, reference_sha256) + candidate, candidate_meta = _model_state(candidate_path, candidate_sha256) + if set(reference) != set(candidate): + missing = sorted(set(reference) - set(candidate)) + extra = sorted(set(candidate) - set(reference)) + raise ValueError(f"model state keys differ; missing={missing[:5]} extra={extra[:5]}") + accumulators: dict[str, dict[str, float]] = {} + for name in sorted(reference): + before = reference[name] + after = candidate[name] + if before.shape != after.shape: + raise ValueError(f"parameter shape differs: {name}") + if not before.is_floating_point(): + continue + before64 = before.detach().to(dtype=torch.float64) + delta = after.detach().to(dtype=torch.float64) - before64 + groups = ("__overall__", _group(name, 1), _group(name, group_depth)) + for group in dict.fromkeys(groups): + values = accumulators.setdefault(group, { + "parameter_count": 0.0, "reference_sq_sum": 0.0, + "delta_sq_sum": 0.0, "delta_abs_sum": 0.0, + "delta_abs_max": 0.0, "tensor_count": 0.0, + }) + values["parameter_count"] += float(delta.numel()) + values["reference_sq_sum"] += float(before64.square().sum()) + values["delta_sq_sum"] += float(delta.square().sum()) + values["delta_abs_sum"] += float(delta.abs().sum()) + values["delta_abs_max"] = max( + values["delta_abs_max"], float(delta.abs().max()) if delta.numel() else 0.0, + ) + values["tensor_count"] += 1.0 + groups: dict[str, Any] = {} + for group, values in sorted(accumulators.items()): + count = int(values["parameter_count"]) + delta_l2 = math.sqrt(values["delta_sq_sum"]) + reference_l2 = math.sqrt(values["reference_sq_sum"]) + groups[group] = { + "parameter_count": count, + "tensor_count": int(values["tensor_count"]), + "reference_l2": reference_l2, + "delta_l2": delta_l2, + "relative_l2": delta_l2 / max(reference_l2, 1e-12), + "delta_mean_abs": values["delta_abs_sum"] / max(count, 1), + "delta_max_abs": values["delta_abs_max"], + } + return { + "schema_version": "phase8_checkpoint_drift_v1", + "status": "complete", + "reference": reference_meta, + "candidate": candidate_meta, + "group_depth": group_depth, + "groups": groups, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference", type=Path, required=True) + parser.add_argument("--reference-sha256", required=True) + parser.add_argument("--candidate", type=Path, required=True) + parser.add_argument("--candidate-sha256", required=True) + parser.add_argument("--group-depth", type=int, default=2) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = analyze( + args.reference, args.reference_sha256, + args.candidate, args.candidate_sha256, + group_depth=args.group_depth, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/analyze_phase8_paired_input_modes.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/analyze_phase8_paired_input_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..615c329bb99ebb1df93134ba095c09b527aa8fd7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/analyze_phase8_paired_input_modes.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Paired depth-contribution diagnostic for two frozen evaluation bundles.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_summary(values: np.ndarray) -> dict[str, float | int] | None: + values = np.asarray(values, dtype=np.float64) + values = values[np.isfinite(values)] + if not len(values): + return None + return { + "count": int(len(values)), "mean": float(values.mean()), + "median": float(np.median(values)), "p90": float(np.quantile(values, .9)), + "p95": float(np.quantile(values, .95)), "p99": float(np.quantile(values, .99)), + "min": float(values.min()), "max": float(values.max()), + } + + +def correlation(left: np.ndarray, right: np.ndarray) -> float | None: + finite = np.isfinite(left) & np.isfinite(right) + if finite.sum() < 2 or np.std(left[finite]) == 0 or np.std(right[finite]) == 0: + return None + return float(np.corrcoef(left[finite], right[finite])[0, 1]) + + +def optimal_slope(delta: np.ndarray, desired: np.ndarray) -> float | None: + finite = np.isfinite(delta) & np.isfinite(desired) + denominator = float(np.dot(delta[finite], delta[finite])) + if denominator <= 1e-12: + return None + return float(np.dot(delta[finite], desired[finite]) / denominator) + + +def grouped_bootstrap( + groups: np.ndarray, gains: np.ndarray, *, seed: int, resamples: int, +) -> dict[str, float | int]: + unique = np.unique(groups) + by_group = {group: gains[groups == group] for group in unique} + generator = np.random.default_rng(seed) + estimates = np.empty(resamples, dtype=np.float64) + for index in range(resamples): + sampled = generator.choice(unique, size=len(unique), replace=True) + values = np.concatenate([by_group[group] for group in sampled]) + estimates[index] = np.nanmean(values) + return { + "groups": int(len(unique)), "resamples": int(resamples), + "estimate": float(np.nanmean(gains)), + "ci95_low": float(np.quantile(estimates, .025)), + "ci95_high": float(np.quantile(estimates, .975)), + } + + +def load_bundle(directory: Path) -> tuple[dict[str, Any], dict[str, np.ndarray], list[dict[str, str]]]: + report_path = directory / "evaluation.json" + raw_path = directory / "raw_predictions.npz" + rows_path = directory / "per_hand_frame_metrics.csv" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("official_test_used") is not False + or report.get("h2o_official_validation_used_for_external_selection") is True + ): + raise ValueError("paired diagnostic refuses a bundle without official_test_used=false") + with np.load(raw_path) as archive: + raw = {key: archive[key] for key in archive.files} + with rows_path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + return report, raw, rows + + +def observation_manifest(report: dict[str, Any]) -> dict[str, Any]: + for name in ("cache_manifest", "manifest"): + value = report.get(name) + if isinstance(value, dict) and value.get("sha256"): + return value + raise ValueError("evaluation lacks a hash-bound observation manifest") + + +def validate_pair( + base_report: dict[str, Any], depth_report: dict[str, Any], + base: dict[str, np.ndarray], depth: dict[str, np.ndarray], + base_rows: list[dict[str, str]], depth_rows: list[dict[str, str]], +) -> None: + if base_report["checkpoint"]["sha256"] != depth_report["checkpoint"]["sha256"]: + raise ValueError("paired modes must use the same checkpoint") + if observation_manifest(base_report)["sha256"] != observation_manifest(depth_report)["sha256"]: + raise ValueError("paired modes must use the same cache manifest") + if base_report["input_mode"] != "rgb_k" or depth_report["input_mode"] != "rgb_d_k": + raise ValueError("expected base=rgb_k and depth=rgb_d_k") + for key in ( + "target_wrist_root_translation", "target_joints_camera", + "translation_valid", "joint3d_valid", "frame_id", + ): + if key not in base or key not in depth or not np.array_equal(base[key], depth[key], equal_nan=True): + raise ValueError(f"paired raw target alignment differs: {key}") + if len(base_rows) != len(depth_rows): + raise ValueError("paired per-hand row counts differ") + identity = ("dataset", "subject_id", "physical_recording_id", "camera_id", "frame_id", "side") + if any(any(left[key] != right[key] for key in identity) for left, right in zip(base_rows, depth_rows)): + raise ValueError("paired per-hand row identities differ") + + +def analyze( + base_dir: Path, depth_dir: Path, output_dir: Path, *, seed: int, resamples: int, +) -> dict[str, Any]: + base_report, base, base_rows = load_bundle(base_dir) + depth_report, depth, depth_rows = load_bundle(depth_dir) + validate_pair(base_report, depth_report, base, depth, base_rows, depth_rows) + if output_dir.exists() and any(output_dir.iterdir()): + raise ValueError("output directory must be new or empty") + output_dir.mkdir(parents=True, exist_ok=True) + + predicted_base = base["predicted_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + predicted_depth = depth["predicted_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + target = base["target_wrist_root_translation"].reshape(-1, 3).astype(np.float64) + translation_valid = base["translation_valid"].reshape(-1).astype(bool) + delta = (predicted_depth - predicted_base) * 1000.0 + desired = (target - predicted_base) * 1000.0 + base_residual = (predicted_base - target) * 1000.0 + depth_residual = (predicted_depth - target) * 1000.0 + + base_joints = base["predicted_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + depth_joints = depth["predicted_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + target_joints = base["target_joints_camera"].reshape(-1, 21, 3).astype(np.float64) + joint_valid = base["joint3d_valid"].reshape(-1, 21).astype(bool) + base_point_error = np.linalg.norm(base_joints - target_joints, axis=-1) * 1000.0 + depth_point_error = np.linalg.norm(depth_joints - target_joints, axis=-1) * 1000.0 + base_mpjpe = np.full(len(joint_valid), np.nan) + depth_mpjpe = np.full(len(joint_valid), np.nan) + for index, valid in enumerate(joint_valid): + if valid.any(): + base_mpjpe[index] = base_point_error[index, valid].mean() + depth_mpjpe[index] = depth_point_error[index, valid].mean() + + groups = np.asarray([row["physical_recording_id"] for row in base_rows], dtype=object) + if len(groups) != len(predicted_base): + raise ValueError("raw hand axis does not match per-hand metric rows") + valid = translation_valid & np.isfinite(base_residual).all(1) & np.isfinite(depth_residual).all(1) + joint_rows = np.isfinite(base_mpjpe) & np.isfinite(depth_mpjpe) + translation_gain = np.linalg.norm(base_residual, axis=1) - np.linalg.norm(depth_residual, axis=1) + mpjpe_gain = base_mpjpe - depth_mpjpe + + paired_rows: list[dict[str, Any]] = [] + for index, metadata in enumerate(base_rows): + if not (valid[index] or joint_rows[index]): + continue + record: dict[str, Any] = { + key: metadata[key] for key in + ("dataset", "subject_id", "physical_recording_id", "camera_id", "frame_id", "side") + } + for axis_index, axis in enumerate("xyz"): + record[f"depth_contribution_{axis}_mm"] = float(delta[index, axis_index]) + record[f"desired_correction_{axis}_mm"] = float(desired[index, axis_index]) + record[f"base_{axis}_error_mm"] = float(base_residual[index, axis_index]) + record[f"depth_{axis}_error_mm"] = float(depth_residual[index, axis_index]) + record["base_mpjpe_mm"] = float(base_mpjpe[index]) + record["depth_mpjpe_mm"] = float(depth_mpjpe[index]) + record["mpjpe_gain_mm"] = float(mpjpe_gain[index]) + record["translation_norm_gain_mm"] = float(translation_gain[index]) + paired_rows.append(record) + row_path = output_dir / "paired_hand_rows.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(paired_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(paired_rows) + harm_path = output_dir / "largest_harm_cases.csv" + harm_rows = sorted(paired_rows, key=lambda row: row["mpjpe_gain_mm"])[:100] + with harm_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(harm_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(harm_rows) + + axis_diagnostics = {} + for axis_index, axis in enumerate("xyz"): + selected = valid & np.isfinite(delta[:, axis_index]) & np.isfinite(desired[:, axis_index]) + axis_diagnostics[axis] = { + "base_signed_error_mm": finite_summary(base_residual[selected, axis_index]), + "depth_signed_error_mm": finite_summary(depth_residual[selected, axis_index]), + "depth_contribution_mm": finite_summary(delta[selected, axis_index]), + "desired_correction_mm": finite_summary(desired[selected, axis_index]), + "contribution_desired_correlation": correlation( + delta[selected, axis_index], desired[selected, axis_index], + ), + "optimal_depth_contribution_scale": optimal_slope( + delta[selected, axis_index], desired[selected, axis_index], + ), + "direction_agreement_fraction": float(np.mean( + np.sign(delta[selected, axis_index]) == np.sign(desired[selected, axis_index]) + )), + "absolute_error_gain_mm": finite_summary( + np.abs(base_residual[selected, axis_index]) - np.abs(depth_residual[selected, axis_index]) + ), + } + report = { + "status": "complete", + "class": "paired_input_oracle_diagnostic_only", + "deployable_claim": False, + "checkpoint": base_report["checkpoint"], + "observation_manifest": observation_manifest(base_report), + "base_input_mode": "rgb_k", "depth_input_mode": "rgb_d_k", + "hands_with_translation": int(valid.sum()), + "hands_with_joint3d": int(joint_rows.sum()), + "base_absolute_mpjpe_mm": float(np.nanmean(base_mpjpe[joint_rows])), + "depth_absolute_mpjpe_mm": float(np.nanmean(depth_mpjpe[joint_rows])), + "depth_mpjpe_gain_mm": finite_summary(mpjpe_gain[joint_rows]), + "depth_harm_fraction_mpjpe": float(np.mean(mpjpe_gain[joint_rows] < 0)), + "translation_norm_gain_mm": finite_summary(translation_gain[valid]), + "depth_harm_fraction_translation_norm": float(np.mean(translation_gain[valid] < 0)), + "axis_diagnostics": axis_diagnostics, + "grouped_bootstrap_ci": { + "mpjpe_gain_mm": grouped_bootstrap( + groups[joint_rows], mpjpe_gain[joint_rows], seed=seed, resamples=resamples, + ), + "translation_norm_gain_mm": grouped_bootstrap( + groups[valid], translation_gain[valid], seed=seed, resamples=resamples, + ), + }, + "paired_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "largest_harm_cases": {"path": str(harm_path.resolve()), "sha256": sha256(harm_path)}, + "official_test_used": False, + } + report_path = output_dir / "analysis.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-rgb-k-dir", type=Path, required=True) + parser.add_argument("--depth-rgb-d-k-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + report = analyze( + args.base_rgb_k_dir, args.depth_rgb_d_k_dir, args.output_dir, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/arm_phase9_last2_distributed_completion.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/arm_phase9_last2_distributed_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..d4159e763e607821df8bedef7283073b6dc8064b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/arm_phase9_last2_distributed_completion.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Carry one admitted last-2 candidate through both distributed handoffs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def write_state(path: Path, status: str, candidate: str, **extra: Any) -> None: + atomic_json(path, { + "schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": status, "candidate": candidate, "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "official_test_used": False, **extra, + }) + + +def wait_json(path: Path, predicate: Any, state_path: Path, candidate: str, label: str) -> dict[str, Any]: + while True: + if path.is_file(): + value = read_json(path) + if predicate(value): return value + if str(value.get("status", "")).startswith("failed"): + raise ValueError(f"last-2 dependency failed: {path}") + write_state(state_path, label, candidate, dependency=str(path.resolve())) + time.sleep(30) + + +def remote_conditions(plan: dict[str, Any], registry: dict[str, Any]) -> list[str]: + owners = condition_owners(registry, load_assignment(plan)) + result = [item["condition"] for item in registry["conditions"] + if owners[item["condition"]] == "server_new"] + if len(result) != 3: raise ValueError("last-2 remote condition count differs") + return result + + +def start_process(command: list[str], log: Path) -> int: + log.parent.mkdir(parents=True, exist_ok=True) + handle = log.open("a", encoding="utf-8") + process = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=handle, + stderr=subprocess.STDOUT, text=True, start_new_session=True) + handle.close(); return process.pid + + +def start_remote(command: str) -> None: + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: raise RuntimeError("remote last-2 watcher launch failed") + + +def training_completion_plan(plan_path: Path, plan: dict[str, Any], registry_path: Path) -> dict[str, Any]: + registry = read_json(registry_path); conditions = remote_conditions(plan, registry) + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_last2_training_completion.py") + return { + "schema_version": "phase9_last2_training_completion_plan_v1", "status": "frozen", + "candidate": plan["candidate"], "source_owner": "server_new", + "destination_owner": "taku3", "conditions": conditions, "target_step": 405000, + "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/last2_v3/{plan['candidate']}/recovery/training_completion_staging", + "training_state_root": plan["training_state_root"], + "source_controller_state": plan["controller_states"]["server_new"], + "training_completion_state": plan["training_completion_state"], + "release_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_training_completion_release.json", + "receive_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_training_completion_receive.json", + "training_registry": {"path": str(registry_path.resolve()), "sha256": sha256(registry_path)}, + "controller_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "distributed_assignment": plan["distributed_assignment"], + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "results_before_terminal_states": True, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + {"path": str(registry_path.resolve()), "sha256": sha256(registry_path)}, + plan["distributed_assignment"], + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def evaluation_completion_plan(plan_path: Path, plan: dict[str, Any], dynamic: Path) -> dict[str, Any]: + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + return { + "schema_version": "phase9_resolution_evaluation_completion_release_plan_v1", + "status": "frozen", "source_owner": "server_new", "destination_owner": "taku3", + "source_host": "server_new", "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/last2_v3/{plan['candidate']}/recovery/evaluation_completion_staging", + "source_controller_state": plan["controller_states"]["server_new"], + "release_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_evaluation_completion_release.json", + "receive_state": f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{plan['candidate']}/server_evaluation_completion_receive.json", + "ssh_timeout_seconds": 30, + "evaluation_plan": {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "single_writer_per_output": True, "results_before_terminal_states": True, + "read_only_after_publish": True, + "scientific_contract": { + "amendment_scope": "terminal_evaluation_state_and_result_handoff_only", + "model_changed": False, "data_changed": False, "seed_changed": False, + "metric_changed": False, "selection_gate_changed": False, + }, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + plan["distributed_assignment"], + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def sync_plan_and_bridge(output: Path, value: dict[str, Any], bridge: Path) -> None: + if output.exists() and read_json(output) != value: raise ValueError(f"existing plan differs: {output}") + if not output.exists(): output.parent.mkdir(parents=True, exist_ok=True); atomic_json(output, value) + for path in (bridge, output): + installed = install_file("server_new", path) + if installed["sha256"] != sha256(path): raise ValueError(f"remote sync differs: {path}") + + +def sync_evaluation_admission(plan: dict[str, Any], dynamic: Path) -> None: + payload = read_json(dynamic) + remote_ids = {identifier for worker in payload["workers"] if worker["owner"] == "server_new" + for identifier in worker["evaluation_ids"]} + evaluations = {item["id"]: item for item in payload["evaluations"]} + for identifier in remote_ids: + item = evaluations[identifier] + for path_key, hash_key in (("config", "config_sha256"), + ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256")): + if remote_sha256("server_new", Path(item[path_key])) != item[hash_key]: + raise ValueError(f"remote last-2 evaluation input differs: {identifier}") + for path in (Path(plan["training_completion_state"]), + Path(plan["evaluation_plan_state"]), dynamic): + install_file("server_new", path) + + +def run(plan_path: Path, state_path: Path) -> dict[str, Any]: + plan = read_json(plan_path); candidate = plan["candidate"] + sync_state = Path(f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{candidate}/admission_sync_state.json") + admitted = wait_json(sync_state, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_admission_sync") + if admitted.get("admission") == "rejected": + return {"schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": "complete_formal_rejection", "candidate": candidate, + "completed_utc": utc_now(), "official_test_used": False} + registry_path = Path(plan["training_registry"]) + wait_json(registry_path, lambda value: value.get("status") == "frozen_ready", + state_path, candidate, "waiting_for_training_registry") + training_plan_path = plan_path.parent / f"last2_{candidate}_training_completion_plan_v1.json" + training_value = training_completion_plan(plan_path, plan, registry_path) + training_bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_last2_training_completion.py") + sync_plan_and_bridge(training_plan_path, training_value, training_bridge) + log_root = Path(f"/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/last2_v3/{candidate}/completion_logs") + receive_pid = start_process([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_last2_training_completion", "--plan", str(training_plan_path), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], log_root / "training_receive.log") + start_remote( + "cd /home/jiasen/foundation_hand && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + f"scripts.sync_phase9_last2_training_completion --plan {training_plan_path} --role publish " + f"--wait-timeout-seconds 1209600 >> {log_root / 'training_publish.log'} 2>&1 < /dev/null" + ) + receive_state = Path(training_value["receive_state"]) + wait_json(receive_state, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_training_completion_return") + dynamic = Path(plan["evaluation_plan"]) + wait_json(dynamic, lambda value: value.get("status") == "frozen_ready", + state_path, candidate, "waiting_for_evaluation_plan") + sync_evaluation_admission(plan, dynamic) + evaluation_plan_path = plan_path.parent / f"last2_{candidate}_evaluation_completion_plan_v1.json" + evaluation_value = evaluation_completion_plan(plan_path, plan, dynamic) + evaluation_bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + sync_plan_and_bridge(evaluation_plan_path, evaluation_value, evaluation_bridge) + evaluation_receive_pid = start_process([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_resolution_evaluation_completion", "--plan", str(evaluation_plan_path), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], log_root / "evaluation_receive.log") + start_remote( + "cd /home/jiasen/foundation_hand && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + f"scripts.sync_phase9_resolution_evaluation_completion --plan {evaluation_plan_path} --role publish " + f"--wait-timeout-seconds 1209600 >> {log_root / 'evaluation_publish.log'} 2>&1 < /dev/null" + ) + central = Path(plan["controller_states"]["taku3"]) + final = wait_json(central, lambda value: value.get("status") == "complete", + state_path, candidate, "waiting_for_central_candidate_decision") + return { + "schema_version": "phase9_last2_distributed_completion_arm_v1", + "status": "complete", "candidate": candidate, "completed_utc": utc_now(), + "training_receive_pid": receive_pid, "evaluation_receive_pid": evaluation_receive_pid, + "decision_report": final["decision_report"], "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser(); parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True); args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + result = run(args.plan, args.state); atomic_json(args.state, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/arm_phase9_shared_augmentation_evaluation_completion.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/arm_phase9_shared_augmentation_evaluation_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..2213de6d5ae74ec16fc626ba2609582464fcd890 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/arm_phase9_shared_augmentation_evaluation_completion.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Arm completion-only Stage 8 evaluation return after its plan freezes.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def completion_plan(static_plan_path: Path, static: dict[str, Any]) -> dict[str, Any]: + dynamic = Path(static["evaluation_plan"]) + admission = Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/" + "evaluation_admission_sync_state.json" + ) + if not dynamic.is_file() or not admission.is_file(): + raise RuntimeError("Stage 8 evaluation admission is not complete") + admitted = read_json(admission) + if admitted.get("status") != "complete" or admitted.get("evaluation_plan_sha256") != sha256(dynamic): + raise RuntimeError("Stage 8 evaluation admission is not complete") + bridge = Path("/home/jiasen/foundation_hand/scripts/sync_phase9_resolution_evaluation_completion.py") + assignment = Path(static["distributed_assignment"]["path"]) + return { + "schema_version": "phase9_resolution_evaluation_completion_release_plan_v1", + "status": "frozen", "source_owner": "server_new", "destination_owner": "taku3", + "source_host": "server_new", + "release_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts", + "staging_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts/shared_augmentation/896x512/recovery/server_evaluation_completion_staging_v1", + "source_controller_state": static["controller_states"]["server_new"], + "release_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/server_evaluation_completion_release_state_v1.json", + "receive_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/server_evaluation_completion_receive_state_v1.json", + "ssh_timeout_seconds": 30, + "evaluation_plan": {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + "completion_only_reverse_release": True, "live_reverse_sync_forbidden": True, + "single_writer_per_output": True, "results_before_terminal_states": True, + "read_only_after_publish": True, + "scientific_contract": { + "amendment_scope": "terminal_evaluation_state_and_result_handoff_only", + "model_changed": False, "data_changed": False, "seed_changed": False, + "metric_changed": False, "selection_gate_changed": False, + }, + "bindings": [ + {"path": str(bridge), "sha256": sha256(bridge)}, + {"path": str(static_plan_path.resolve()), "sha256": sha256(static_plan_path)}, + {"path": str(dynamic.resolve()), "sha256": sha256(dynamic)}, + {"path": str(assignment.resolve()), "sha256": sha256(assignment)}, + ], + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def arm(static_plan_path: Path, output_plan: Path) -> dict[str, Any]: + static = read_json(static_plan_path) + plan = completion_plan(static_plan_path, static) + if output_plan.exists() and read_json(output_plan) != plan: + raise ValueError("existing Stage 8 evaluation completion plan differs") + if not output_plan.exists(): + output_plan.parent.mkdir(parents=True, exist_ok=True); atomic_json(output_plan, plan) + copied = subprocess.run(["rsync", "-a", str(output_plan), f"server_new:{output_plan}.incoming"], check=False) + if copied.returncode: + raise RuntimeError("Stage 8 evaluation completion plan sync failed") + installed = subprocess.run(["ssh", "server_new", "mv", f"{output_plan}.incoming", str(output_plan)], check=False) + if installed.returncode: + raise RuntimeError("Stage 8 evaluation completion plan install failed") + log_root = Path("/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/completion_logs") + log_root.mkdir(parents=True, exist_ok=True) + receive = subprocess.Popen([ + "/SSD2/jiasen/envs/foundation_hand/bin/python", "-u", "-m", + "scripts.sync_phase9_resolution_evaluation_completion", "--plan", str(output_plan), + "--role", "receive", "--wait-timeout-seconds", "1209600", + ], stdin=subprocess.DEVNULL, stdout=(log_root / "evaluation_receive.log").open("a"), + stderr=subprocess.STDOUT, text=True, start_new_session=True) + remote = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.sync_phase9_resolution_evaluation_completion --plan " + str(output_plan) + + " --role publish --wait-timeout-seconds 1209600 >> " + + str(log_root / "evaluation_publish.log") + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", remote], check=False) + if result.returncode: + raise RuntimeError("Stage 8 evaluation completion publisher launch failed") + return { + "schema_version": "phase9_shared_augmentation_evaluation_completion_arm_v1", + "status": "complete", "completed_utc": utc_now(), + "completion_plan": str(output_plan.resolve()), + "completion_plan_sha256": sha256(output_plan), "receiver_pid": receive.pid, + "official_test_used": False, "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--static-plan", type=Path, required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = arm(args.static_plan, args.output_plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except RuntimeError as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_evaluation_completion_arm_v1", + "status": "waiting_for_evaluation_admission", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_coordinates.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_coordinates.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca4d235ec4f8a6ed42e9e7528951c26225cab2b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_coordinates.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Create reproducible camera/depth/joint audit artifacts for H2O cam4.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record +from foundation_hand.geometry.camera import ( + depth_mm_to_m, + intrinsics_from_h2o, + project_points, + unproject_depth, +) + +HAND_COLORS = ((50, 220, 50), (50, 80, 255)) # BGR: left green, right red +HAND_EDGES = ( + (0, 1), (1, 2), (2, 3), (3, 4), + (0, 5), (5, 6), (6, 7), (7, 8), + (0, 9), (9, 10), (10, 11), (11, 12), + (0, 13), (13, 14), (14, 15), (15, 16), + (0, 17), (17, 18), (18, 19), (19, 20), +) + + +def choose_samples(frame_csv: Path, count: int) -> list[dict[str, str]]: + with frame_csv.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + buckets: dict[str, list[dict[str, str]]] = {} + for row in rows: + key = f"{row['subject']}:{row['joint_left_valid']}{row['joint_right_valid']}" + buckets.setdefault(key, []).append(row) + selected: list[dict[str, str]] = [] + keys = sorted(buckets) + cursor = {key: 0 for key in keys} + while len(selected) < count and keys: + next_keys = [] + for key in keys: + candidates = buckets[key] + index = cursor[key] + if index < len(candidates): + # Walk each bucket across time rather than taking adjacent frames. + pos = min(len(candidates) - 1, round(index * max(1, len(candidates) - 1) / max(1, count // len(keys)))) + selected.append(candidates[pos]) + cursor[key] += 1 + next_keys.append(key) + if len(selected) == count: + break + keys = next_keys + return selected + + +def draw_joints(image: np.ndarray, uv: np.ndarray, valid_z: np.ndarray, color: tuple[int, int, int]) -> None: + inside = valid_z & (uv[:, 0] >= 0) & (uv[:, 0] < image.shape[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < image.shape[0]) + for start, end in HAND_EDGES: + if inside[start] and inside[end]: + cv2.line(image, tuple(np.rint(uv[start]).astype(int)), tuple(np.rint(uv[end]).astype(int)), color, 2) + for index, point in enumerate(uv): + if inside[index]: + radius = 5 if index == 0 else 3 + cv2.circle(image, tuple(np.rint(point).astype(int)), radius, color, -1) + + +def write_colored_ply(path: Path, xyz: np.ndarray, rgb: np.ndarray, valid: np.ndarray, stride: int = 8) -> int: + points = xyz[::stride, ::stride][valid[::stride, ::stride]] + colors = rgb[::stride, ::stride][valid[::stride, ::stride]] + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="ascii") as handle: + handle.write("ply\nformat ascii 1.0\n") + handle.write(f"element vertex {len(points)}\n") + handle.write("property float x\nproperty float y\nproperty float z\n") + handle.write("property uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n") + for point, color in zip(points, colors, strict=True): + handle.write(f"{point[0]:.6f} {point[1]:.6f} {point[2]:.6f} {int(color[0])} {int(color[1])} {int(color[2])}\n") + return len(points) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=24) + args = parser.parse_args() + + root = args.root.resolve() + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + selected = choose_samples(args.frame_csv, args.samples) + result_rows = [] + roundtrip_errors = [] + + for sample_index, row in enumerate(selected): + take = root / row["subject"] / row["scene"] / row["take"] / "cam4" + frame = f"{int(row['frame_id']):06d}" + rgb_bgr = cv2.imread(str(take / "rgb" / f"{frame}.png"), cv2.IMREAD_COLOR) + depth_raw = cv2.imread(str(take / "depth" / f"{frame}.png"), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_raw is None: + raise RuntimeError(f"Could not decode sample {take}/{frame}") + K, expected_hw = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + if rgb_bgr.shape[:2] != expected_hw or depth_raw.shape != expected_hw: + raise ValueError(f"RGB/depth/K size mismatch at {take}/{frame}") + depth_m, depth_valid = depth_mm_to_m(depth_raw) + xyz, xyz_valid = unproject_depth(depth_m, K) + + # Pixel -> camera -> pixel should recover exact pixel centers for every valid depth. + sparse_xyz = xyz[::16, ::16].reshape(-1, 3) + sparse_valid = xyz_valid[::16, ::16].reshape(-1) + uv_back, positive = project_points(sparse_xyz[sparse_valid], K) + vv, uu = np.meshgrid(np.arange(0, expected_hw[0], 16), np.arange(0, expected_hw[1], 16), indexing="ij") + uv_reference = np.stack((uu, vv), axis=-1).reshape(-1, 2)[sparse_valid] + pixel_error = np.linalg.norm(uv_back[positive] - uv_reference[positive], axis=-1) + roundtrip_errors.extend(pixel_error.tolist()) + + overlay = rgb_bgr.copy() + joints = load_joint_record(take / "hand_pose" / f"{frame}.txt") + hand_stats = [] + for hand_index, color in enumerate(HAND_COLORS): + if joints.annotation_valid[hand_index]: + uv, positive_z = project_points(joints.joints_camera_m[hand_index], K) + draw_joints(overlay, uv, positive_z, color) + hand_stats.append({"side": ("left", "right")[hand_index], "annotation_valid": True, "projected_in_frame": int(((uv[:, 0] >= 0) & (uv[:, 0] < expected_hw[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < expected_hw[0]) & positive_z).sum())}) + else: + hand_stats.append({"side": ("left", "right")[hand_index], "annotation_valid": False, "projected_in_frame": None}) + + valid_depth = depth_m[depth_valid] + clipped = np.clip(depth_m, 0, np.quantile(valid_depth, 0.99) if valid_depth.size else 1.0) + depth_u8 = np.rint(255 * clipped / max(float(clipped.max()), 1e-6)).astype(np.uint8) + depth_color = cv2.applyColorMap(depth_u8, cv2.COLORMAP_TURBO) + depth_color[~depth_valid] = 0 + edges = cv2.Canny(depth_u8, 30, 90) + alignment = rgb_bgr.copy() + alignment[edges > 0] = (0, 255, 255) + + label = f"{row['subject']}/{row['scene']}/{row['take']}/{frame} L={row['joint_left_valid']} R={row['joint_right_valid']}" + for image in (overlay, depth_color, alignment): + cv2.rectangle(image, (0, 0), (image.shape[1], 34), (0, 0, 0), -1) + cv2.putText(image, label, (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) + prefix = f"{sample_index:02d}_{row['subject']}_{row['scene']}_{row['take']}_{frame}" + cv2.imwrite(str(output / f"{prefix}_joint_overlay.jpg"), overlay) + cv2.imwrite(str(output / f"{prefix}_depth.jpg"), depth_color) + cv2.imwrite(str(output / f"{prefix}_depth_edges_rgb.jpg"), alignment) + ply_count = write_colored_ply(output / f"{prefix}_pointcloud.ply", xyz, cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB), xyz_valid) + result_rows.append({ + "sample": prefix, + "subject": row["subject"], "scene": row["scene"], "take": row["take"], "frame_id": int(row["frame_id"]), + "K": K.tolist(), "depth_dtype": str(depth_raw.dtype), "depth_valid_fraction": float(depth_valid.mean()), + "depth_min_m": float(valid_depth.min()), "depth_p50_m": float(np.quantile(valid_depth, 0.5)), "depth_p95_m": float(np.quantile(valid_depth, 0.95)), "depth_max_m": float(valid_depth.max()), + "pixel_roundtrip_max": float(pixel_error.max()) if pixel_error.size else None, + "pointcloud_vertices": ply_count, "hands": hand_stats, + }) + + errors = np.asarray(roundtrip_errors) + report = { + "root": str(root), "sample_count": len(result_rows), "selection": "round-robin across subject and annotation-valid combinations, spread over time", + "camera_convention_supported_by_projection": "x-right, y-down, z-forward; u=fx*x/z+cx, v=fy*y/z+cy", + "depth_unit": "released uint16 millimeters converted by /1000 to meters", + "pixel_unprojection_projection_roundtrip": {"count": int(errors.size), "mean_px": float(errors.mean()), "p95_px": float(np.quantile(errors, 0.95)), "max_px": float(errors.max())}, + "mano_numeric_reconstruction": "BLOCKED_MISSING_LICENSED_MANO_ASSETS", + "samples": result_rows, + } + (output / "coordinate_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: report[key] for key in ("sample_count", "camera_convention_supported_by_projection", "depth_unit", "pixel_unprojection_projection_roundtrip", "mano_numeric_reconstruction")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_mano.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_mano.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ae1a83d4f165c9542c997f6cd3bd7ceeff5b46 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_mano.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Numerically reproduce H2O MANO fits before formal training is allowed.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record, load_mano_record +from foundation_hand.geometry.camera import intrinsics_from_h2o, project_points +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.mano_translation import mano_raw_to_wrist, wrist_to_mano_raw + + +def stats(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values) + return {"count": int(array.size), "mean_mm": float(array.mean()), "p50_mm": float(np.quantile(array, .5)), "p95_mm": float(np.quantile(array, .95)), "max_mm": float(array.max())} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=50) + args = parser.parse_args(); args.output_dir.mkdir(parents=True, exist_ok=True) + required = [args.mano_root / "MANO_LEFT.pkl", args.mano_root / "MANO_RIGHT.pkl"] + if not all(path.is_file() for path in required): + report = {"status": "blocked", "reason": "licensed MANO assets missing", "required": [str(path) for path in required]} + (args.output_dir / "mano_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)); raise SystemExit(2) + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + layers = [ManoLayer(mano_root=str(args.mano_root), side=side, use_pca=False, ncomps=45, flat_hand_mean=True) for side in ("left", "right")] + with args.frame_csv.open(newline="", encoding="utf-8") as handle: rows = [row for row in csv.DictReader(handle) if row["joint_left_valid"] == "1" and row["joint_right_valid"] == "1"] + rows = [rows[round(index * (len(rows)-1) / max(args.samples-1, 1))] for index in range(args.samples)] + errors = {"left": [], "right": []}; roundtrip = {"left": [], "right": []}; root_offsets = {"left": [], "right": []} + for sample_index, row in enumerate(rows): + take = args.root / row["subject"] / row["scene"] / row["take"] / "cam4"; stem = f"{int(row['frame_id']):06d}" + joints_gt = load_joint_record(take / "hand_pose" / f"{stem}.txt"); mano = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + image = cv2.imread(str(take / "rgb" / f"{stem}.png")); K, _ = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + for hand, side in enumerate(("left", "right")): + with torch.no_grad(): vertices_mm, joints_mm = layers[hand](torch.from_numpy(mano.pose_axis_angle[hand:hand+1]), torch.from_numpy(mano.shape[hand:hand+1])) + native_joints_m = joints_mm[0].numpy() / 1000.0; reconstructed = native_joints_m + mano.translation_raw_m[hand] + per_joint = np.linalg.norm(reconstructed - joints_gt.joints_camera_m[hand], axis=-1) * 1000 + errors[side].extend(per_joint.tolist()); root_offsets[side].append(native_joints_m[0].tolist()) + wrist = mano_raw_to_wrist(mano.translation_raw_m[hand], native_joints_m[0]); raw_back = wrist_to_mano_raw(wrist, native_joints_m[0]) + roundtrip[side].append(float(np.linalg.norm(raw_back - mano.translation_raw_m[hand]) * 1000)) + if sample_index < 10: + uv, positive = project_points(reconstructed, K) + for point, valid in zip(uv, positive, strict=True): + if valid: cv2.circle(image, tuple(np.rint(point).astype(int)), 3, ((50,220,50),(50,80,255))[hand], -1) + if sample_index < 10: cv2.imwrite(str(args.output_dir / f"{sample_index:02d}_{row['subject']}_{row['scene']}_{row['take']}_{stem}_mano_overlay.jpg"), image) + report = { + "status": "passed" if max(stats(errors[side])["p95_mm"] for side in errors) < 5 else "failed", + "configuration": {"use_pca": False, "ncomps": 45, "flat_hand_mean": True, "native_output_unit": "mm", "placed_output_unit": "m"}, + "joint_reconstruction": {side: stats(values) for side, values in errors.items()}, + "translation_semantics": "raw translation places the MANO model origin; wrist = raw + native MANO joint0 / 1000", + "raw_to_wrist_root_offsets_m": root_offsets, + "translation_roundtrip": {side: stats(values) for side, values in roundtrip.items()}, + } + (args.output_dir / "mano_audit.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({key: report[key] for key in ("status", "joint_reconstruction", "translation_semantics", "translation_roundtrip")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase2_cam4.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase2_cam4.py new file mode 100644 index 0000000000000000000000000000000000000000..147fa879e7466f0015130321ffba9dec3915f615 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase2_cam4.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +"""Reproducible full-record audit of the extracted H2O cam4 dataset.""" + +from __future__ import annotations + +import argparse +import csv +import json +import random +from collections import Counter +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import ( + load_float_record, + parse_joint_record, + parse_mano_record, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + +CORE_FRAME_MODALITIES = ( + "rgb", + "depth", + "cam_pose", + "hand_pose", + "hand_pose_mano", + "obj_pose", + "obj_pose_rt", +) +SIDES = ("left", "right") + + +def quantiles(values: list[float] | np.ndarray) -> dict[str, float | int | None]: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if array.size == 0: + return {"count": 0, "mean": None, "p50": None, "p95": None, "max": None} + return { + "count": int(array.size), + "mean": float(array.mean()), + "p50": float(np.quantile(array, 0.50)), + "p95": float(np.quantile(array, 0.95)), + "max": float(array.max()), + } + + +def ids_in(directory: Path) -> set[int]: + return {int(path.stem) for path in directory.iterdir() if path.is_file() and path.stem.isdigit()} + + +def sample_evenly(items: list[Path], count: int) -> list[Path]: + if count <= 0 or not items: + return [] + if len(items) <= count: + return items + indices = np.linspace(0, len(items) - 1, count, dtype=int) + return [items[index] for index in indices] + + +def make_contact_sheet(rows: list[dict[str, object]], output: Path, title: str) -> None: + if not rows: + return + tile_w, tile_h = 320, 205 + columns = 4 + result_rows = (len(rows) + columns - 1) // columns + canvas = np.zeros((result_rows * tile_h + 36, columns * tile_w, 3), dtype=np.uint8) + cv2.putText(canvas, title, (8, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) + for index, row in enumerate(rows): + image = cv2.imread(str(row["rgb_path"]), cv2.IMREAD_COLOR) + if image is None: + continue + image = cv2.resize(image, (tile_w, 180), interpolation=cv2.INTER_AREA) + label = str(row["label"]) + cv2.rectangle(image, (0, 0), (tile_w, 24), (0, 0, 0), -1) + cv2.putText(image, label[:52], (4, 17), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (255, 255, 255), 1) + y = 36 + (index // columns) * tile_h + x = (index % columns) * tile_w + canvas[y : y + 180, x : x + tile_w] = image + output.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(output), canvas) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--depth-samples-per-take", type=int, default=2) + parser.add_argument("--invalid-visual-samples", type=int, default=40) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + root = args.root.resolve() + output = args.output_dir.resolve() + output.mkdir(parents=True, exist_ok=True) + rng = random.Random(args.seed) + + take_dirs = sorted(root.glob("subject*/*/*/cam4")) + if not take_dirs: + raise RuntimeError(f"No cam4 takes found below {root}") + + take_rows: list[dict[str, object]] = [] + depth_candidates: list[Path] = [] + invalid_visuals: dict[str, list[dict[str, object]]] = {"left": [], "right": []} + record_lengths = {"hand_pose": Counter(), "hand_pose_mano": Counter(), "cam_pose": Counter()} + valid_combinations = Counter() + valid_agreement = Counter() + projection_counts = {side: Counter() for side in SIDES} + raw_to_wrist_offsets = {side: [] for side in SIDES} + raw_wrist_distance_mm = {side: [] for side in SIDES} + rotation_det_errors: list[float] = [] + rotation_orth_errors: list[float] = [] + pose_last_row_errors: list[float] = [] + intrinsics_rows: list[list[float]] = [] + image_shapes = Counter() + missing_by_modality = Counter() + extra_by_modality = Counter() + frame_count = 0 + nonfinite_records = Counter() + + frame_csv = output / "frame_audit.csv" + frame_fields = [ + "subject", + "scene", + "take", + "frame_id", + "joint_left_valid", + "joint_right_valid", + "mano_left_valid", + "mano_right_valid", + "left_joints_in_frame", + "right_joints_in_frame", + "left_wrist_in_frame", + "right_wrist_in_frame", + "left_raw_to_wrist_mm", + "right_raw_to_wrist_mm", + "rgb_path", + ] + + with frame_csv.open("w", newline="", encoding="utf-8") as frame_handle: + writer = csv.DictWriter(frame_handle, fieldnames=frame_fields) + writer.writeheader() + + for cam4 in take_dirs: + subject, scene, take = cam4.parts[-4:-1] + K_values = load_float_record(cam4 / "cam_intrinsics.txt") + K, expected_hw = intrinsics_from_h2o(K_values) + intrinsics_rows.append(K_values.tolist()) + + frame_sets = {name: ids_in(cam4 / name) for name in CORE_FRAME_MODALITIES} + rgb_ids = frame_sets["rgb"] + for name, ids in frame_sets.items(): + missing_by_modality[name] += len(rgb_ids - ids) + extra_by_modality[name] += len(ids - rgb_ids) + + rgb_paths = sorted((cam4 / "rgb").glob("*.png")) + depth_paths = sorted((cam4 / "depth").glob("*.png")) + depth_candidates.extend(sample_evenly(depth_paths, args.depth_samples_per_take)) + if rgb_paths: + sample_rgb = cv2.imread(str(rgb_paths[0]), cv2.IMREAD_COLOR) + if sample_rgb is None: + raise RuntimeError(f"Could not decode {rgb_paths[0]}") + image_shapes[str(tuple(sample_rgb.shape))] += 1 + if sample_rgb.shape[:2] != expected_hw: + raise ValueError( + f"K image size {expected_hw} does not match RGB {sample_rgb.shape[:2]} at {cam4}" + ) + + take_rows.append( + { + "subject": subject, + "scene": scene, + "take": take, + "frames": len(rgb_ids), + **{f"missing_{name}": len(rgb_ids - ids) for name, ids in frame_sets.items()}, + **{f"extra_{name}": len(ids - rgb_ids) for name, ids in frame_sets.items()}, + } + ) + + for frame_id in sorted(rgb_ids): + stem = f"{frame_id:06d}" + joint_values = load_float_record(cam4 / "hand_pose" / f"{stem}.txt") + mano_values = load_float_record(cam4 / "hand_pose_mano" / f"{stem}.txt") + pose_values = load_float_record(cam4 / "cam_pose" / f"{stem}.txt") + record_lengths["hand_pose"][str(joint_values.size)] += 1 + record_lengths["hand_pose_mano"][str(mano_values.size)] += 1 + record_lengths["cam_pose"][str(pose_values.size)] += 1 + if not np.isfinite(joint_values).all(): + nonfinite_records["hand_pose"] += 1 + if not np.isfinite(mano_values).all(): + nonfinite_records["hand_pose_mano"] += 1 + if not np.isfinite(pose_values).all(): + nonfinite_records["cam_pose"] += 1 + + joints = parse_joint_record(joint_values) + mano = parse_mano_record(mano_values) + joint_key = tuple(bool(value) for value in joints.annotation_valid) + mano_key = tuple(bool(value) for value in mano.annotation_valid) + valid_combinations[f"joint_{int(joint_key[0])}{int(joint_key[1])}"] += 1 + valid_combinations[f"mano_{int(mano_key[0])}{int(mano_key[1])}"] += 1 + valid_agreement[str(joint_key == mano_key)] += 1 + + camera_pose = pose_values.reshape(4, 4) + rotation = camera_pose[:3, :3] + rotation_det_errors.append(abs(float(np.linalg.det(rotation)) - 1.0)) + rotation_orth_errors.append(float(np.linalg.norm(rotation.T @ rotation - np.eye(3)))) + pose_last_row_errors.append(float(np.linalg.norm(camera_pose[3] - np.array([0, 0, 0, 1])))) + + frame_row: dict[str, object] = { + "subject": subject, + "scene": scene, + "take": take, + "frame_id": frame_id, + "joint_left_valid": int(joints.annotation_valid[0]), + "joint_right_valid": int(joints.annotation_valid[1]), + "mano_left_valid": int(mano.annotation_valid[0]), + "mano_right_valid": int(mano.annotation_valid[1]), + "rgb_path": str(cam4 / "rgb" / f"{stem}.png"), + } + + for side_index, side in enumerate(SIDES): + in_frame_count = -1 + wrist_in_frame = -1 + distance_mm = float("nan") + if joints.annotation_valid[side_index]: + uv, positive = project_points(joints.joints_camera_m[side_index], K) + inside = ( + positive + & (uv[:, 0] >= 0) + & (uv[:, 0] < expected_hw[1]) + & (uv[:, 1] >= 0) + & (uv[:, 1] < expected_hw[0]) + ) + in_frame_count = int(inside.sum()) + wrist_in_frame = int(inside[0]) + projection_counts[side]["valid"] += 1 + projection_counts[side]["any_joint_in_frame"] += int(inside.any()) + projection_counts[side]["all_joints_in_frame"] += int(inside.all()) + projection_counts[side]["wrist_in_frame"] += int(inside[0]) + projection_counts[side]["all_positive_z"] += int(positive.all()) + + if joints.annotation_valid[side_index] and mano.annotation_valid[side_index]: + offset = ( + joints.joints_camera_m[side_index, 0] + - mano.translation_raw_m[side_index] + ) + raw_to_wrist_offsets[side].append(offset.astype(np.float64)) + distance_mm = float(np.linalg.norm(offset) * 1000.0) + raw_wrist_distance_mm[side].append(distance_mm) + + frame_row[f"{side}_joints_in_frame"] = in_frame_count + frame_row[f"{side}_wrist_in_frame"] = wrist_in_frame + frame_row[f"{side}_raw_to_wrist_mm"] = distance_mm + + if not joints.annotation_valid[side_index]: + invalid_visuals[side].append( + { + "rgb_path": cam4 / "rgb" / f"{stem}.png", + "label": f"{subject}/{scene}/{take}/{stem} {side} ann=0", + } + ) + + writer.writerow(frame_row) + frame_count += 1 + + take_csv = output / "take_audit.csv" + with take_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(take_rows[0])) + writer.writeheader() + writer.writerows(take_rows) + + depth_rows: list[dict[str, object]] = [] + pooled_depth: list[np.ndarray] = [] + for path in depth_candidates: + depth_mm = cv2.imread(str(path), cv2.IMREAD_UNCHANGED) + if depth_mm is None: + raise RuntimeError(f"Could not decode depth {path}") + depth_m, valid = depth_mm_to_m(depth_mm) + positive = depth_m[valid] + sampled = positive[::64] if positive.size else positive + pooled_depth.append(sampled) + depth_rows.append( + { + "path": str(path), + "dtype": str(depth_mm.dtype), + "height": depth_mm.shape[0], + "width": depth_mm.shape[1], + "zero_fraction": float((depth_mm == 0).mean()), + "positive_min_m": float(positive.min()) if positive.size else None, + "positive_p50_m": float(np.quantile(positive, 0.50)) if positive.size else None, + "positive_p95_m": float(np.quantile(positive, 0.95)) if positive.size else None, + "positive_p99_m": float(np.quantile(positive, 0.99)) if positive.size else None, + "positive_max_m": float(positive.max()) if positive.size else None, + "fraction_gt_3_86m": float((depth_m > 3.86).mean()), + "fraction_gt_5_46m": float((depth_m > 5.46).mean()), + } + ) + + depth_csv = output / "depth_sample_stats.csv" + with depth_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(depth_rows[0])) + writer.writeheader() + writer.writerows(depth_rows) + + selected_invalid = {} + for side in SIDES: + candidates = invalid_visuals[side] + rng.shuffle(candidates) + selected_invalid[side] = candidates[: args.invalid_visual_samples] + make_contact_sheet( + selected_invalid[side], + output / f"annotation_invalid_{side}_contact_sheet.jpg", + f"H2O cam4 {side}: annotation_valid=0 (not a presence label)", + ) + + intrinsics = np.asarray(intrinsics_rows, dtype=np.float64) + combined_depth = np.concatenate(pooled_depth) if pooled_depth else np.empty(0) + summary = { + "root": str(root), + "seed": args.seed, + "take_count": len(take_dirs), + "frame_count": frame_count, + "camera": "cam4_only", + "record_length_distributions": { + name: dict(counter) for name, counter in record_lengths.items() + }, + "valid_combinations": dict(valid_combinations), + "joint_mano_valid_agreement": dict(valid_agreement), + "annotation_valid_is_presence": False, + "presence_fields_found": False, + "presence_training_recommendation": "disabled_until_reliable_labels_exist", + "projection_from_annotation_valid_joints": { + side: dict(counter) for side, counter in projection_counts.items() + }, + "raw_mano_translation_is_wrist": False, + "raw_to_wrist_offset_m": { + side: { + "x": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 0]), + "y": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 1]), + "z": quantiles(np.asarray(raw_to_wrist_offsets[side])[:, 2]), + "norm_mm": quantiles(raw_wrist_distance_mm[side]), + } + for side in SIDES + }, + "frame_alignment": { + "missing_by_modality": dict(missing_by_modality), + "extra_by_modality": dict(extra_by_modality), + }, + "nonfinite_records": dict(nonfinite_records), + "camera_pose": { + "det_rotation_abs_error": quantiles(rotation_det_errors), + "orthogonality_frobenius_error": quantiles(rotation_orth_errors), + "last_row_error": quantiles(pose_last_row_errors), + }, + "intrinsics": { + "count": int(intrinsics.shape[0]), + "fx": quantiles(intrinsics[:, 0]), + "fy": quantiles(intrinsics[:, 1]), + "cx": quantiles(intrinsics[:, 2]), + "cy": quantiles(intrinsics[:, 3]), + "width_values": sorted(set(intrinsics[:, 4].tolist())), + "height_values": sorted(set(intrinsics[:, 5].tolist())), + }, + "rgb_shapes_by_take": dict(image_shapes), + "depth_audit": { + "sampling": "uniform frames within every take; all sampled pixels decoded", + "sample_count": len(depth_rows), + "samples_per_take": args.depth_samples_per_take, + "positive_depth_m": quantiles(combined_depth), + "zero_fraction_across_sample_means": quantiles( + [float(row["zero_fraction"]) for row in depth_rows] + ), + }, + "visibility_or_occlusion_fields": [], + "outputs": { + "frame_csv": str(frame_csv), + "take_csv": str(take_csv), + "depth_csv": str(depth_csv), + "invalid_contact_sheets": { + side: str(output / f"annotation_invalid_{side}_contact_sheet.jpg") + for side in SIDES + }, + }, + } + (output / "cam4_audit_summary.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(summary, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() + diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase3_evaluations.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase3_evaluations.py new file mode 100644 index 0000000000000000000000000000000000000000..49def655a023b3142313873e6958a56e53230566 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase3_evaluations.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Audit complete Phase 3 official-validation outputs.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path + + +def json_finite(value) -> bool: + if isinstance(value, float): + return math.isfinite(value) + if isinstance(value, dict): + return all(json_finite(item) for item in value.values()) + if isinstance(value, (list, tuple)): + return all(json_finite(item) for item in value) + return True + + +def audit_csv(path: Path, expected_rows: int) -> tuple[int, bool]: + rows = 0 + finite = True + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + rows += 1 + for value in row.values(): + if value in (None, ""): + continue + try: + numeric = float(value) + except ValueError: + continue + finite = finite and math.isfinite(numeric) + return rows, finite and rows == expected_rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("evaluation_root", type=Path) + parser.add_argument("--expected-evaluations", type=int, required=True) + parser.add_argument("--expected-clips", type=int, default=1495) + parser.add_argument("--expected-frames", type=int, default=11638) + parser.add_argument("--expected-frame-rows", type=int, default=23276) + parser.add_argument("--expected-transition-rows", type=int, default=30293) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + + reports = sorted(args.evaluation_root.glob("*/*/evaluation.json")) + records = [] + for path in reports: + report = json.loads(path.read_text(encoding="utf-8")) + frame_rows, frame_csv_valid = audit_csv( + path.parent / "per_hand_frame_metrics.csv", args.expected_frame_rows, + ) + transition_rows, transition_csv_valid = audit_csv( + path.parent / "per_temporal_transition_metrics.csv", + args.expected_transition_rows, + ) + passed = ( + report.get("status") == "evaluated" + and report.get("official_test_used") is False + and report.get("split_role") == "official_validation" + and report.get("clips") == args.expected_clips + and report.get("frames") == args.expected_frames + and json_finite(report) + and frame_csv_valid + and transition_csv_valid + ) + records.append({ + "run": path.parents[1].name, + "role": path.parent.name, + "report": str(path), + "checkpoint_sha256": report.get("checkpoint", {}).get("sha256"), + "frame_rows": frame_rows, + "transition_rows": transition_rows, + "passed": passed, + }) + + passed = len(records) == args.expected_evaluations and all( + record["passed"] for record in records + ) + payload = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "evaluations": len(records), + "expected_evaluations": args.expected_evaluations, + "total_frame_rows": sum(record["frame_rows"] for record in records), + "total_transition_rows": sum(record["transition_rows"] for record in records), + "records": records, + } + output = args.output or args.evaluation_root / "evaluation_audit.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": payload["status"], "evaluations": len(records), + "output": str(output), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase3_periodic_checkpoints.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase3_periodic_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..800daf71cffb5e2c37ca0ecb20384214bdd44b88 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase3_periodic_checkpoints.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Audit periodic Phase 3 checkpoints with one isolated loader per run.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +from pathlib import Path + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def worker(checkpoint_path: Path) -> None: + import torch + + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + model_finite = all( + not torch.is_tensor(value) or torch.isfinite(value).all().item() + for value in checkpoint.get("model", {}).values() + ) + print(json.dumps({ + "step": int(checkpoint["step"]), + "model_finite": model_finite, + "bytes": checkpoint_path.stat().st_size, + "sha256": sha256(checkpoint_path), + })) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_root", type=Path, nargs="?") + parser.add_argument("--step", type=int) + parser.add_argument("--expected-runs", type=int) + parser.add_argument("--run-prefix") + parser.add_argument("--output", type=Path) + parser.add_argument("--worker", type=Path) + args = parser.parse_args() + + if args.worker is not None: + worker(args.worker) + return + if args.run_root is None or args.step is None: + parser.error("run_root and --step are required") + + checkpoint_name = f"step_{args.step:07d}.pt" + run_dirs = sorted( + path.parent for path in args.run_root.glob(f"*/{checkpoint_name}") + if path.parent.is_dir() + and (args.run_prefix is None or path.parent.name.startswith(args.run_prefix)) + ) + if args.expected_runs is not None and len(run_dirs) != args.expected_runs: + raise ValueError( + f"expected {args.expected_runs} {checkpoint_name} files, found {len(run_dirs)}" + ) + + records = [] + for run_dir in run_dirs: + checkpoint_path = run_dir / checkpoint_name + process = subprocess.run( + [sys.executable, str(Path(__file__).resolve()), "--worker", str(checkpoint_path)], + check=True, capture_output=True, text=True, + ) + checkpoint_record = json.loads(process.stdout) + validation_rows = [ + json.loads(line) for line in (run_dir / "validation.jsonl").read_text( + encoding="utf-8" + ).splitlines() if line.strip() + ] + matching_validation = [ + row for row in validation_rows if int(row["step"]) == args.step + ] + provenance_path = run_dir / "run_provenance.json" + if not provenance_path.is_file(): + candidates = sorted(run_dir.glob("resume_provenance_*.json")) + if len(candidates) != 1: + raise FileNotFoundError( + f"expected one run/resume provenance file in {run_dir}" + ) + provenance_path = candidates[0] + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + records.append({ + "run": run_dir.name, + **checkpoint_record, + "run_commit": provenance.get("git_commit"), + "validation_records": len(matching_validation), + "validation_total_loss": ( + matching_validation[0]["losses"]["total"] + if len(matching_validation) == 1 else None + ), + }) + + passed = bool(records) and all( + record["step"] == args.step + and record["model_finite"] + and record["validation_records"] == 1 + for record in records + ) + result = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "expected_step": args.step, + "run_prefix": args.run_prefix, + "runs": records, + } + suffix = f"{args.step // 1000}k" if args.step % 1000 == 0 else str(args.step) + prefix = f"{args.run_prefix.rstrip('_-')}_" if args.run_prefix else "" + output_path = ( + args.output + if args.output is not None + else args.run_root / f"checkpoint_audit_{prefix}{suffix}.json" + ) + if output_path.exists(): + raise FileExistsError(f"refusing to overwrite checkpoint audit: {output_path}") + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": result["status"], "runs": len(records), "output": str(output_path) + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase3_run_checkpoints.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase3_run_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..e64c457dd74c0cd479f2c2f786f5f4e3c7ad56b5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase3_run_checkpoints.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Audit one completed Phase 3 run in an isolated process.""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +from pathlib import Path + +import torch + + +FINAL_ROLES = { + "step_100k": "step_0100000.pt", + "best_absolute": "best.pt", + "best_z": "best_z.pt", + "final": "step_0100000_final.pt", +} + + +def load_roles(path: Path | None) -> dict[str, str]: + if path is None: + return dict(FINAL_ROLES) + values = json.loads(path.read_text(encoding="utf-8")) + if ( + not isinstance(values, dict) + or not values + or any(not isinstance(role, str) or not role for role in values) + or any( + not isinstance(filename, str) or Path(filename).name != filename + for filename in values.values() + ) + ): + raise ValueError("checkpoint spec must be a non-empty role-to-filename JSON object") + return values + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_dir", type=Path) + parser.add_argument("--completed-step", type=int, default=100_000) + parser.add_argument("--checkpoint-spec", type=Path) + args = parser.parse_args() + roles = load_roles(args.checkpoint_spec) + summary = json.loads((args.run_dir / "summary.json").read_text(encoding="utf-8")) + result = { + "run": args.run_dir.name, + "summary_status": summary.get("status"), + "completed_step": summary.get("completed_step"), + "official_test_used": False, + "roles": {}, + } + for role, filename in roles.items(): + path = args.run_dir / filename + checkpoint = torch.load(path, map_location="cpu", weights_only=False) + finite = all( + not torch.is_tensor(value) or torch.isfinite(value).all().item() + for value in checkpoint.get("model", {}).values() + ) + result["roles"][role] = { + "path": str(path), + "bytes": path.stat().st_size, + "sha256": sha256(path), + "step": int(checkpoint["step"]), + "model_finite": finite, + } + del checkpoint + gc.collect() + result["status"] = "passed" if ( + result["summary_status"] == "completed" + and result["completed_step"] == args.completed_step + and all(item["model_finite"] for item in result["roles"].values()) + ) else "failed" + output = args.run_dir / "final_checkpoint_audit.json" + output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"run": args.run_dir.name, "status": result["status"]})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase4_visualizations.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase4_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..afb6efba5a62c71bf21add06f75168566c1a33f0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase4_visualizations.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Audit raw/filtered Phase 4 videos and deterministic rerender pixels.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def fraction(value: str) -> float: + numerator, denominator = value.split("/", 1) + return float(numerator) / float(denominator) + + +def probe_video(path: Path) -> dict[str, object]: + process = subprocess.run([ + "ffprobe", "-v", "error", "-select_streams", "v:0", + "-show_entries", "stream=codec_name,pix_fmt,width,height,avg_frame_rate,nb_frames,duration", + "-of", "json", str(path), + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) + streams = json.loads(process.stdout).get("streams", []) + if len(streams) != 1: + raise ValueError(f"expected one video stream: {path}") + stream = streams[0] + return { + "codec": stream.get("codec_name"), + "pixel_format": stream.get("pix_fmt"), + "width": int(stream["width"]), "height": int(stream["height"]), + "fps": fraction(stream["avg_frame_rate"]), + "frames": int(stream["nb_frames"]), + "duration_seconds": float(stream["duration"]), + } + + +def decoded_frame_audit(path: Path, expected_frames: int) -> list[dict[str, object]]: + capture = cv2.VideoCapture(str(path)) + if not capture.isOpened(): + raise RuntimeError(f"cannot decode video: {path}") + records = [] + try: + for index in sorted({0, expected_frames // 2, expected_frames - 1}): + capture.set(cv2.CAP_PROP_POS_FRAMES, index) + ok, frame = capture.read() + if not ok or frame is None: + raise RuntimeError(f"cannot decode frame {index}: {path}") + std = float(frame.std()) + nonzero_fraction = float(np.count_nonzero(frame) / frame.size) + if std < 1.0 or nonzero_fraction < 0.05: + raise ValueError(f"blank/degenerate frame {index}: {path}") + records.append({ + "frame_index": index, "std": std, + "nonzero_fraction": nonzero_fraction, + "pixel_sha256": hashlib.sha256(frame.tobytes()).hexdigest(), + }) + finally: + capture.release() + return records + + +def audit_video( + path: Path, + *, + expected_frames: int, + expected_fps: float, + expected_sha256: str | None = None, + require_h264: bool = False, +) -> dict[str, object]: + if not path.is_file(): + raise FileNotFoundError(path) + digest = sha256(path) + if expected_sha256 is not None and digest != expected_sha256: + raise ValueError(f"video SHA256 mismatch: {path}") + probe = probe_video(path) + if probe["frames"] != expected_frames: + raise ValueError(f"video frame count mismatch: {path}") + if abs(float(probe["fps"]) - expected_fps) > 1e-3: + raise ValueError(f"video fps mismatch: {path}") + if require_h264 and ( + probe["codec"] != "h264" or probe["pixel_format"] != "yuv420p" + ): + raise ValueError(f"filtered video codec contract mismatch: {path}") + return { + "path": str(path.resolve()), "sha256": digest, **probe, + "decoded_frames": decoded_frame_audit(path, expected_frames), + "passed": True, + } + + +def deterministic_frame_hash_audit( + primary: dict[str, Any], rerun: dict[str, Any], +) -> int: + def index(manifest: dict[str, Any]) -> dict[tuple[str, str, str], list[str]]: + return { + (record["take"], record["condition"], video_name): video["frame_pixel_sha256"] + for record in manifest["cases"] + for video_name, video in record["videos"].items() + } + left, right = index(primary), index(rerun) + if left.keys() != right.keys(): + raise ValueError("deterministic video case grid mismatch") + for key in left: + if left[key] != right[key]: + raise ValueError(f"deterministic frame pixel mismatch: {key}") + return sum(len(values) for values in left.values()) + + +def audit_raw_manifest(manifest: dict[str, Any]) -> list[dict[str, object]]: + if manifest.get("status") != "complete" or manifest.get("official_test_used") is not False: + raise ValueError("invalid raw video manifest") + fps = float(manifest["visualization_fps"]) + records = [] + for case in manifest["cases"]: + frame_count = len(case["frame_ids"]) + for role, path in case["videos"].items(): + records.append({ + "set": "raw_model_primary_results", "take": case["take"], + "condition": "raw", "role": role, + **audit_video( + Path(path), expected_frames=frame_count, expected_fps=fps, + ), + }) + return records + + +def audit_filtered_manifest(manifest: dict[str, Any]) -> list[dict[str, object]]: + if ( + manifest.get("status") != "complete" + or manifest.get("official_test_used") is not False + or manifest.get("result_role") != "filtered_inference_secondary_results" + ): + raise ValueError("invalid filtered video manifest") + records = [] + expected_roles = { + "raw_vs_filtered_30fps", "raw_vs_filtered_4fps", + "failure_diagnostic_30fps", + } + for case in manifest["cases"]: + if set(case["videos"]) != expected_roles: + raise ValueError("filtered video role grid mismatch") + for role, video in case["videos"].items(): + records.append({ + "set": "filtered_inference_secondary_results", + "take": case["take"], "condition": case["condition"], + "role": role, + **audit_video( + Path(video["path"]), expected_frames=int(video["frames"]), + expected_fps=float(video["fps"]), + expected_sha256=video["sha256"], require_h264=True, + ), + }) + return records + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--raw-manifest", type=Path, required=True) + parser.add_argument("--filtered-manifest", type=Path, required=True) + parser.add_argument("--filtered-rerun-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite visualization audit: {args.output}") + raw = json.loads(args.raw_manifest.read_text(encoding="utf-8")) + filtered = json.loads(args.filtered_manifest.read_text(encoding="utf-8")) + rerun = json.loads(args.filtered_rerun_manifest.read_text(encoding="utf-8")) + records = audit_raw_manifest(raw) + records.extend(audit_filtered_manifest(filtered)) + records.extend(audit_filtered_manifest(rerun)) + compared_frames = deterministic_frame_hash_audit(filtered, rerun) + report = { + "status": "passed", + "official_test_used": False, + "videos": len(records), + "deterministic_frame_hashes_compared": compared_frames, + "raw_model_primary_results_kept_separate": True, + "filtered_inference_secondary_results_kept_separate": True, + "records": records, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "passed", "videos": len(records), + "deterministic_frame_hashes_compared": compared_frames, + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_alignment_visualizations.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_alignment_visualizations.py new file mode 100644 index 0000000000000000000000000000000000000000..3ebd0b9fb31f916e3a2c0aaa08e79f95d53b848a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_alignment_visualizations.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Audit deterministic Phase 5 alignment diagnostic images.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def case_without_path(case: dict[str, Any]) -> dict[str, Any]: + return {key: value for key, value in case.items() if key not in ("image", "image_sha256")} + + +def image_audit(case: dict[str, Any]) -> dict[str, Any]: + path = Path(case["image"]) + digest = sha256(path) + if digest != case["image_sha256"]: + raise ValueError(f"manifest image hash mismatch: {path}") + image = cv2.imread(str(path), cv2.IMREAD_COLOR) + if image is None: + raise ValueError(f"cannot decode diagnostic image: {path}") + std = float(image.std()) + nonzero_fraction = float(np.count_nonzero(image) / image.size) + if min(image.shape[:2]) < 480 or std < 5.0 or nonzero_fraction < 0.2: + raise ValueError(f"blank or degenerate diagnostic image: {path}") + return { + "role": case["role"], "path": str(path.resolve()), "sha256": digest, + "width": int(image.shape[1]), "height": int(image.shape[0]), + "pixel_std": std, "nonzero_fraction": nonzero_fraction, + } + + +def audit_manifests( + primary: dict[str, Any], rerun: dict[str, Any], +) -> dict[str, Any]: + for manifest in (primary, rerun): + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_validation_secondary_failure_diagnostic" + or manifest.get("official_test_used") is not False + or manifest.get("used_for_model_or_threshold_selection") is not False + ): + raise ValueError("invalid alignment visualization manifest contract") + left = {case["role"]: case for case in primary["cases"]} + right = {case["role"]: case for case in rerun["cases"]} + if left.keys() != right.keys() or len(left) != len(primary["cases"]): + raise ValueError("visualization role grid mismatch or duplicate role") + primary_records, rerun_records = [], [] + for role in left: + if case_without_path(left[role]) != case_without_path(right[role]): + raise ValueError(f"visualization case metadata mismatch: {role}") + primary_record = image_audit(left[role]) + rerun_record = image_audit(right[role]) + if primary_record["sha256"] != rerun_record["sha256"]: + raise ValueError(f"deterministic image hash mismatch: {role}") + primary_records.append(primary_record) + rerun_records.append(rerun_record) + return { + "status": "passed", + "result_role": "deterministic_official_validation_visualization_audit", + "cases": len(left), + "deterministic_image_hashes_compared": len(left), + "primary": primary_records, + "rerun": rerun_records, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--primary-manifest", type=Path, required=True) + parser.add_argument("--rerun-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError("visualization audit refuses to overwrite output") + primary = json.loads(args.primary_manifest.read_text(encoding="utf-8")) + rerun = json.loads(args.rerun_manifest.read_text(encoding="utf-8")) + report = audit_manifests(primary, rerun) + report.update({ + "primary_manifest": str(args.primary_manifest.resolve()), + "rerun_manifest": str(args.rerun_manifest.resolve()), + }) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "cases": report["cases"], + "output": str(args.output), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_oof_bank.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..3d6814f9f1d8ebb1112e0086b5e5f95a44cd9f77 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_oof_bank.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python3 +"""Audit Phase 5 group-heldout coarse banks before refiner fitting.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + + +TAIL_ADMISSION_P95_MM = 40.0 +SEEDS = (20260716, 20260717, 20260718) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def distribution(values_m: np.ndarray) -> dict[str, float | int]: + values_mm = np.asarray(values_m, dtype=np.float64).reshape(-1) * 1000.0 + values_mm = values_mm[np.isfinite(values_mm)] + if not values_mm.size: + raise ValueError("cannot summarize an empty residual distribution") + absolute = np.abs(values_mm) + p95 = float(np.percentile(absolute, 95)) + return { + "count": int(len(values_mm)), + "signed_mean_mm": float(values_mm.mean()), + "signed_std_mm": float(values_mm.std()), + "mae_mm": float(absolute.mean()), + "p50_mm": float(np.percentile(absolute, 50)), + "p90_mm": float(np.percentile(absolute, 90)), + "p95_mm": p95, + "p99_mm": float(np.percentile(absolute, 99)), + "cvar95_mm": float(absolute[absolute >= p95].mean()), + "maximum_mm": float(absolute.max()), + } + + +def size_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 64.0, "small", np.where(values < 128.0, "medium", "large")) + + +def depth_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 0.5, "near", np.where(values < 0.8, "middle", "far")) + + +def validity_bucket(values: np.ndarray) -> np.ndarray: + return np.where(values < 0.25, "low", np.where(values < 0.60, "partial", "strong")) + + +def validate_bank_manifest(path: Path) -> dict[str, Any]: + manifest = json.loads(path.read_text(encoding="utf-8")) + required = ( + manifest.get("status") == "complete", + manifest.get("bank_version") == 2, + manifest.get("scope") == "full_fold", + manifest.get("result_role") == "official_train_group_heldout_oof_predictions", + manifest.get("leakage_audit", {}).get("passed") is True, + manifest.get("official_validation_used_for_assignment") is False, + manifest.get("official_test_used") is False, + manifest.get("oracle_information_at_inference") is False, + ) + if not all(required): + raise ValueError(f"OOF audit requires a complete leakage-free full-fold bank: {path}") + return manifest + + +def load_oof_banks(bank_dirs: list[Path]) -> tuple[dict[str, np.ndarray], list[dict[str, Any]]]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + manifests = [] + observed_pairs: set[tuple[int, str]] = set() + keys_by_checkpoint: dict[str, set[str]] = defaultdict(set) + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = validate_bank_manifest(manifest_path) + manifests.append(manifest) + fold = int(manifest["fold"]) + checkpoint = str(manifest["checkpoint"]["sha256"]) + pair = (fold, checkpoint) + if pair in observed_pairs: + raise ValueError(f"duplicate fold/checkpoint bank: {pair}") + observed_pairs.add(pair) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take bank hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in ( + "frame_id", "frame_valid", "mano_annotation_valid", + "translation_residual_m", "target_wrist_translation", + "coarse_hand_scale_px", "alignment_valid_fraction", + )} + valid = arrays["frame_valid"].astype(bool)[:, None] & arrays[ + "mano_annotation_valid" + ].astype(bool) + time = len(arrays["frame_id"]) + side = np.broadcast_to(np.asarray(("left", "right"))[None], (time, 2)) + frame = np.broadcast_to(arrays["frame_id"][:, None], (time, 2)) + take = str(take_record["take"]) + subject, action_family = take.split("/")[:2] + sample_keys = np.asarray([ + f"{take}|{int(frame_id)}|{hand}" + for frame_id, hand in zip(frame[valid], side[valid], strict=True) + ]) + duplicate_keys = keys_by_checkpoint[checkpoint].intersection(sample_keys.tolist()) + if duplicate_keys: + raise ValueError(f"duplicate samples within checkpoint bank: {take}") + keys_by_checkpoint[checkpoint].update(sample_keys.tolist()) + count = int(valid.sum()) + chunks["residual_z_m"].append(arrays["translation_residual_m"][..., 2][valid]) + chunks["side"].append(side[valid]) + chunks["frame_id"].append(frame[valid]) + chunks["sample_key"].append(sample_keys) + chunks["subject"].append(np.full(count, subject)) + chunks["action_family"].append(np.full(count, action_family)) + chunks["take"].append(np.full(count, take)) + chunks["fold"].append(np.full(count, fold, dtype=np.int16)) + chunks["coarse_seed"].append(np.full(count, int(manifest.get("seed", -1)), dtype=np.int64)) + chunks["checkpoint"].append(np.full(count, checkpoint)) + chunks["hand_scale_px"].append(arrays["coarse_hand_scale_px"][valid]) + chunks["wrist_depth_m"].append(arrays["target_wrist_translation"][..., 2][valid]) + chunks["local_depth_valid_fraction"].append(arrays["alignment_valid_fraction"][valid]) + if {int(manifest["fold"]) for manifest in manifests} != {0, 1, 2}: + raise ValueError("OOF audit requires coverage of folds 0/1/2") + return {key: np.concatenate(values) for key, values in chunks.items()}, manifests + + +def validation_reference(a1_root: Path) -> tuple[list[dict[str, Any]], np.ndarray]: + rows = [] + values = [] + for seed in SEEDS: + with np.load(a1_root / f"seed_{seed}" / "validation" / "features.npz", allow_pickle=False) as archive: + residual = archive["target_residual_z_m"].astype(np.float64) + rows.append({"seed": seed, **distribution(residual)}) + values.append(residual) + return rows, np.concatenate(values) + + +def cross_checkpoint_correlations(samples: dict[str, np.ndarray]) -> dict[str, Any]: + maps: dict[str, dict[str, float]] = defaultdict(dict) + metadata: dict[str, dict[str, int]] = {} + for checkpoint, key, residual, fold, seed in zip( + samples["checkpoint"], samples["sample_key"], samples["residual_z_m"], + samples["fold"], samples["coarse_seed"], strict=True, + ): + checkpoint = str(checkpoint) + maps[checkpoint][str(key)] = float(residual) + metadata[checkpoint] = {"fold": int(fold), "seed": int(seed)} + results = {} + checkpoints = sorted(maps) + for left_index, left in enumerate(checkpoints): + for right in checkpoints[left_index + 1:]: + overlap = sorted(set(maps[left]).intersection(maps[right])) + name = f"{left[:12]}_{right[:12]}" + if len(overlap) < 2: + results[name] = { + "status": "unavailable_no_overlapping_group_heldout_samples", + "overlap": len(overlap), + "pearson": None, + "left": {"checkpoint": left, **metadata[left]}, + "right": {"checkpoint": right, **metadata[right]}, + } + else: + x = np.asarray([maps[left][key] for key in overlap]) + y = np.asarray([maps[right][key] for key in overlap]) + results[name] = { + "status": "available", + "overlap": len(overlap), + "pearson": float(np.corrcoef(x, y)[0, 1]), + "left": {"checkpoint": left, **metadata[left]}, + "right": {"checkpoint": right, **metadata[right]}, + } + return results + + +def grouped_rows(samples: dict[str, np.ndarray]) -> list[dict[str, Any]]: + residual = samples["residual_z_m"] + groups: dict[str, np.ndarray] = { + "fold": samples["fold"].astype(str), + "checkpoint": samples["checkpoint"], + "side": samples["side"], + "subject": samples["subject"], + "action_family": samples["action_family"], + "take": samples["take"], + "hand_size": size_bucket(samples["hand_scale_px"]), + "wrist_depth": depth_bucket(samples["wrist_depth_m"]), + "local_depth_validity": validity_bucket(samples["local_depth_valid_fraction"]), + } + if np.all(samples["coarse_seed"] >= 0): + groups["coarse_seed"] = samples["coarse_seed"].astype(str) + rows = [{"source": "oof", "group": "all", "value": "all", **distribution(residual)}] + for field, values in groups.items(): + for value in sorted(set(values.tolist())): + rows.append({ + "source": "oof", "group": field, "value": value, + **distribution(residual[values == value]), + }) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--validation-a1-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("OOF audit refuses to overwrite outputs") + samples, manifests = load_oof_banks(args.bank_dir) + oof = distribution(samples["residual_z_m"]) + validation_rows, validation_values = validation_reference(args.validation_a1_root) + validation = distribution(validation_values) + quantiles = np.linspace(0.0, 1.0, 101) + quantile_l1_mm = float(np.mean(np.abs( + np.quantile(np.abs(samples["residual_z_m"]), quantiles) + - np.quantile(np.abs(validation_values), quantiles) + )) * 1000.0) + rows = grouped_rows(samples) + rows.extend({ + "source": "validation", "group": "seed", "value": row["seed"], + **{key: value for key, value in row.items() if key != "seed"}, + } for row in validation_rows) + rows.append({"source": "validation", "group": "all", "value": "all", **validation}) + tail_passed = bool(oof["p95_mm"] >= TAIL_ADMISSION_P95_MM) + report = { + "status": "passed" if tail_passed else "insufficient_oof_tail", + "experiment_class": "preregistered_data_admission_audit", + "residual_definition": "GT wrist z minus group-heldout coarse predicted wrist z", + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "folds": sorted({int(manifest["fold"]) for manifest in manifests}), + "checkpoints": sorted({str(manifest["checkpoint"]["sha256"]) for manifest in manifests}), + "coarse_seeds": sorted({ + int(manifest["seed"]) for manifest in manifests if manifest.get("seed") is not None + }), + "samples": len(samples["residual_z_m"]), + "takes": len(set(samples["take"].tolist())), + "oof": oof, + "validation_reference_by_seed": validation_rows, + "validation_reference_all": validation, + "absolute_residual_quantile_l1_distance_mm": quantile_l1_mm, + "tail_admission": { + "threshold_p95_mm": TAIL_ADMISSION_P95_MM, + "passed": tail_passed, + "rule": "do not fit a formal refiner if group-heldout OOF z P95 remains below 40 mm", + }, + "cross_checkpoint_pearson": cross_checkpoint_correlations(samples), + "leakage_audit_passed": all(manifest["leakage_audit"]["passed"] for manifest in manifests), + "official_validation_used_for_training_or_thresholds": False, + "official_test_used": False, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(json.dumps({ + "status": report["status"], "samples": report["samples"], "takes": report["takes"], + "oof": oof, "validation": validation, "official_test_used": False, + }, indent=2)) + if not tail_passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_periodic_checkpoints.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_periodic_checkpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..d039ac0e31f689bff49638990e6f519f51a0a996 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_periodic_checkpoints.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Audit Phase 5 periodic checkpoints, logs, provenance, and validation contract.""" + +from __future__ import annotations + +import argparse +import gc +import hashlib +import json +from pathlib import Path + +import torch + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_tree(value: object) -> bool: + if torch.is_tensor(value): + return bool(torch.isfinite(value).all()) if value.is_floating_point() else True + if isinstance(value, dict): + return all(finite_tree(item) for item in value.values()) + if isinstance(value, (list, tuple)): + return all(finite_tree(item) for item in value) + return True + + +def audit_run(run_dir: Path, step: int, expected_validation_records: int) -> dict[str, object]: + checkpoint_path = run_dir / f"step_{step:07d}.pt" + checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False) + checkpoint_record = { + "path": str(checkpoint_path.resolve()), + "bytes": checkpoint_path.stat().st_size, + "sha256": sha256(checkpoint_path), + "step": int(checkpoint["step"]), + "model_finite": finite_tree(checkpoint.get("model", {})), + "optimizer_finite": finite_tree(checkpoint.get("optimizer", {})), + } + del checkpoint + gc.collect() + + provenance = json.loads((run_dir / "run_provenance.json").read_text(encoding="utf-8")) + train_lines = [ + line for line in (run_dir / "train_metrics.jsonl").read_text(encoding="utf-8").splitlines() + if line.strip() + ] + last_train = json.loads(train_lines[-1]) if train_lines else {} + validation_path = run_dir / "validation.jsonl" + validation_rows = ( + [json.loads(line) for line in validation_path.read_text(encoding="utf-8").splitlines() if line.strip()] + if validation_path.is_file() else [] + ) + matching_validation = [row for row in validation_rows if int(row["step"]) == step] + finite_validation = finite_tree(matching_validation) + passed = ( + checkpoint_record["step"] == step + and checkpoint_record["model_finite"] + and checkpoint_record["optimizer_finite"] + and provenance.get("git_status") in ("", None) + and int(last_train.get("step", -1)) >= step + and len(matching_validation) == expected_validation_records + and finite_validation + ) + return { + "run": run_dir.name, + "status": "passed" if passed else "failed", + "checkpoint": checkpoint_record, + "git_commit": provenance.get("git_commit"), + "git_status_clean": provenance.get("git_status") in ("", None), + "train_manifest": provenance.get("hashes", {}).get("train_manifest"), + "config": provenance.get("hashes", {}).get("config"), + "last_train_step": last_train.get("step"), + "last_gradient_norm": last_train.get("gradient_norm"), + "last_frames_per_s": last_train.get("frames_per_s"), + "validation_records_at_step": len(matching_validation), + "expected_validation_records_at_step": expected_validation_records, + "validation_finite": finite_validation, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("run_root", type=Path) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--expected-runs", type=int, required=True) + parser.add_argument("--expected-validation-records", type=int, choices=(0, 1), required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite audit: {args.output}") + checkpoint_name = f"step_{args.step:07d}.pt" + run_dirs = sorted(path.parent for path in args.run_root.glob(f"*/{checkpoint_name}")) + if len(run_dirs) != args.expected_runs: + raise ValueError( + f"expected {args.expected_runs} {checkpoint_name} files, found {len(run_dirs)}" + ) + records = [ + audit_run(run_dir, args.step, args.expected_validation_records) + for run_dir in run_dirs + ] + passed = bool(records) and all(record["status"] == "passed" for record in records) + report = { + "status": "passed" if passed else "failed", + "expected_step": args.step, + "expected_runs": args.expected_runs, + "expected_validation_records_at_step": args.expected_validation_records, + "runs": records, + "official_test_used": False, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "runs": len(records), "output": str(args.output), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_residual_shift.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_residual_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..62c3bfe1f2b6ba39dc8a5cfb4b4c19d0c926de49 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase5_residual_shift.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Audit in-fold train versus held-out validation coarse z residual shift.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import numpy as np + + +SEEDS = (20260716, 20260717, 20260718) + + +def distribution(values_m: np.ndarray) -> dict[str, float | int]: + values_mm = np.asarray(values_m, dtype=np.float64) * 1000.0 + absolute = np.abs(values_mm) + p95 = float(np.percentile(absolute, 95)) + return { + "count": int(len(values_mm)), + "signed_mean_mm": float(values_mm.mean()), + "mae_mm": float(absolute.mean()), + "p50_mm": float(np.percentile(absolute, 50)), + "p90_mm": float(np.percentile(absolute, 90)), + "p95_mm": p95, + "p99_mm": float(np.percentile(absolute, 99)), + "cvar95_mm": float(absolute[absolute >= p95].mean()), + } + + +def load_rows(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def size_bucket(value: str) -> str: + size = float(value) + return "small" if size < 64.0 else "medium" if size < 128.0 else "large" + + +def depth_bucket(value: str) -> str: + depth = float(value) + return "near" if depth < 0.5 else "middle" if depth < 0.8 else "far" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--a1-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("residual-shift audit refuses to overwrite outputs") + + split_values: dict[str, dict[int, np.ndarray]] = {"train": {}, "validation": {}} + split_rows: dict[str, list[dict[str, str]]] = {} + summary_rows = [] + group_rows = [] + for split in split_values: + metadata_reference: list[tuple[str, str, str]] | None = None + for seed in SEEDS: + root = args.a1_root / f"seed_{seed}" / split + with np.load(root / "features.npz", allow_pickle=False) as archive: + values = archive["target_residual_z_m"].astype(np.float64) + rows = load_rows(root / "samples.csv") + if len(rows) != len(values): + raise ValueError(f"feature/metadata length mismatch for {split}/{seed}") + metadata = [(row["take"], row["frame_id"], row["side"]) for row in rows] + if metadata_reference is None: + metadata_reference = metadata + split_rows[split] = rows + elif metadata != metadata_reference: + raise ValueError(f"sample alignment differs across seeds for {split}") + split_values[split][seed] = values + result = distribution(values) + summary_rows.append({"split": split, "seed": seed, "group": "all", "value": "all", **result}) + + groups: dict[tuple[str, str], list[int]] = {} + for index, row in enumerate(rows): + values_by_group = { + "side": row["side"], + "action_family": row["action_family"], + "hand_size": size_bucket(row["hand_size_px"]), + "wrist_depth": depth_bucket(row["wrist_depth_m"]), + "take": row["take"], + } + for field, value in values_by_group.items(): + groups.setdefault((field, value), []).append(index) + for (field, value), indices in sorted(groups.items()): + group_rows.append({ + "split": split, "seed": seed, "group": field, "value": value, + **distribution(values[np.asarray(indices, dtype=np.int64)]), + }) + + correlations = {} + for split, by_seed in split_values.items(): + matrix = np.corrcoef([by_seed[seed] for seed in SEEDS]) + correlations[split] = { + f"{left}_{right}": float(matrix[left_index, right_index]) + for left_index, left in enumerate(SEEDS) + for right_index, right in enumerate(SEEDS) + if left_index < right_index + } + gaps = {} + for seed in SEEDS: + train = distribution(split_values["train"][seed]) + validation = distribution(split_values["validation"][seed]) + gaps[str(seed)] = { + "mae_ratio_validation_over_train": validation["mae_mm"] / train["mae_mm"], + "p95_ratio_validation_over_train": validation["p95_mm"] / train["p95_mm"], + "mae_gap_mm": validation["mae_mm"] - train["mae_mm"], + "p95_gap_mm": validation["p95_mm"] - train["p95_mm"], + } + report = { + "status": "audited", + "experiment_class": "diagnostic_existing_predictions", + "source": "Phase 4 A1 frozen coarse feature banks", + "residual_definition": "GT wrist z minus coarse predicted wrist z", + "seeds": list(SEEDS), + "summary": summary_rows, + "cross_seed_pearson": correlations, + "validation_over_train_gap": gaps, + "sample_alignment_across_seeds": True, + "official_test_used": False, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + rows_to_write = summary_rows + group_rows + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows_to_write[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows_to_write) + print(json.dumps({ + "status": report["status"], + "train": [row for row in summary_rows if row["split"] == "train"], + "validation": [row for row in summary_rows if row["split"] == "validation"], + "correlations": correlations, + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase6_sequence_inference.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase6_sequence_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e78513782072066d17259a1a4014e154227187ec --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase6_sequence_inference.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Audit a frozen checkpoint through the bounded arbitrary-length API.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import time +from collections import defaultdict +from pathlib import Path + +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def clone_batch(batch: dict[str, object]) -> dict[str, object]: + return { + key: value.clone() if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, required=True) + parser.add_argument("--frames", type=int, default=257) + parser.add_argument("--take") + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output must not already exist") + if args.manifest.name != "official_val.jsonl": + parser.error("sequence audit is hard-gated to official validation") + if args.frames < 1 or args.window < 1: + parser.error("frames and window must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + configured_mode = config["model"].get( + "temporal_attention_mode", "bidirectional", + ) + expected_mode = "causal" if args.mode == "causal" else "bidirectional" + if configured_mode != expected_mode: + parser.error("config temporal mode differs from requested audit mode") + + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (1,), (1,), + ) + by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + by_take[clip.take].append(index) + take = args.take + if take is None: + take = next((name for name, indices in by_take.items() if len(indices) >= args.frames), None) + if take is None or len(by_take.get(take, ())) < args.frames: + raise ValueError("no requested take contains the audit frame count") + indices = by_take[take][: args.frames] + + loader = DataLoader( + Subset(dataset, indices), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.mode, window_size=args.window, + offline_stride=(args.window // 2 if args.mode == "offline" else None), + ), + device=device, autocast_dtype=dtype, + ) + frame_ids: list[int] = [] + + def frames(): + for batch in loader: + frame_ids.append(int(batch["frame_id"][0, 0])) + yield batch + + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + output = runner.infer(frames()) + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + output_time = int(output["wrist_root_translation"].shape[1]) + finite = all(torch.isfinite(value).all() for value in output.values()) + + invariance = None + if args.mode == "causal": + invariant_loader = DataLoader( + Subset(dataset, indices[:8]), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ) + first = list(invariant_loader) + full = runner._stack_frames(first) + perturbed = clone_batch(full) + perturbed["rgb"][:, 4:] = -perturbed["rgb"][:, 4:] + perturbed["depth_m"][:, 4:] = 0 + perturbed["depth_pixel_valid"][:, 4:] = False + perturbed["depth_available"][:, 4:] = False + prefix = { + key: value[:, :4] if torch.is_tensor(value) and value.ndim >= 2 + and value.shape[1] == 8 else value + for key, value in full.items() + } + full = runner._to_device(full) + perturbed = runner._to_device(perturbed) + prefix = runner._to_device(prefix) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + full_output = model(full) + perturbed_output = model(perturbed) + prefix_output = model(prefix) + future_delta = float(( + full_output["wrist_root_translation"][:, :4] + - perturbed_output["wrist_root_translation"][:, :4] + ).abs().max()) + monolithic_prefix_delta = float(( + full_output["wrist_root_translation"][:, :4] + - prefix_output["wrist_root_translation"] + ).abs().max()) + stream_full = runner.infer_causal(first)["wrist_root_translation"][:, :4] + stream_prefix = runner.infer_causal(first[:4])["wrist_root_translation"] + prefix_delta = float((stream_full - stream_prefix).abs().max()) + invariance = { + "future_perturbation_max_abs_m": future_delta, + "future_perturbation_bitwise_zero": future_delta == 0.0, + "streaming_prefix_max_abs_m": prefix_delta, + "prefix_tolerance_m": 1e-6, + "prefix_passed": prefix_delta <= 1e-6, + "monolithic_full_vs_short_batch_max_abs_m": monolithic_prefix_delta, + "monolithic_batch_size_numerical_invariance": monolithic_prefix_delta <= 1e-6, + } + + invariance_passed = invariance is None or ( + invariance["future_perturbation_bitwise_zero"] and invariance["prefix_passed"] + ) + order_passed = len(frame_ids) == args.frames and all( + right > left for left, right in zip(frame_ids, frame_ids[1:]) + ) + memory_passed = ( + runner.maximum_resident_frames <= args.window + and runner.maximum_input_buffer_frames <= ( + args.window if args.mode == "causal" else args.window + args.window // 2 + ) + ) + report = { + "status": "passed" if ( + finite and output_time == args.frames and order_passed + and memory_passed and invariance_passed + ) else "failed", + "experiment": "P6_S5_length_generalized_inference", + "experiment_class": "frozen_checkpoint_engineering_audit", + "official_test_used": False, + "official_validation_used_for_selection": False, + "mode": args.mode, + "causal": args.mode == "causal", + "window": args.window, + "offline_stride": args.window // 2 if args.mode == "offline" else None, + "stitching": "center" if args.mode == "offline" else None, + "take": take, + "requested_frames": args.frames, + "output_frames": output_time, + "frame_ids_strictly_increasing": order_passed, + "finite": finite, + "elapsed_s": elapsed, + "throughput_fps": args.frames / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "maximum_gpu_window_frames": runner.maximum_resident_frames, + "maximum_cpu_input_buffer_frames": runner.maximum_input_buffer_frames, + "invariance": invariance, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": int(checkpoint["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if report["status"] != "passed": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase6_variable_length.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase6_variable_length.py new file mode 100644 index 0000000000000000000000000000000000000000..85097343ce2bb9177f32360d1e752196baa31a45 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase6_variable_length.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +"""Audit the frozen Phase 5 model's variable-length and causality contract.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import statistics +import subprocess +import time +from collections import defaultdict +from pathlib import Path +from typing import Any + +import torch +import yaml + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +LENGTHS = (1, 2, 4, 8, 16, 32, 64) +OUTPUT_KEYS = ( + "hand_tokens", "joint2d_norm", "mano_rotation_matrices", "mano_shape", + "wrist_root_translation", "joints_camera", "vertices_camera", +) +MODEL_INPUT_KEYS = ( + "rgb", "depth_m", "depth_pixel_valid", "K", "K_available", + "depth_available", "frame_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_model( + config: dict[str, Any], checkpoint: Path, device: torch.device, +) -> tuple[BimanualReconstructionModel, int]: + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(checkpoint, model, optimizer=None, map_location=device) + return model, int(state["step"]) + + +def contiguous_real_sequence( + root: Path, manifest: Path, resolution_hw: tuple[int, int], length: int, +) -> tuple[dict[str, torch.Tensor], str, list[int]]: + dataset = H2OCam4Dataset( + root, manifest, resolution_hw, clip_lengths=(1,), strides=(1,), + window_step=1, allow_partial=False, + ) + by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + by_take[clip.take].append(index) + selected: list[int] | None = None + selected_take = "" + for take, indices in by_take.items(): + frame_ids = [dataset.clips[index].frame_ids[0] for index in indices] + for start in range(0, len(indices) - length + 1): + candidate = frame_ids[start : start + length] + if all(right == left + 1 for left, right in zip(candidate[:-1], candidate[1:])): + selected = indices[start : start + length] + selected_take = take + break + if selected is not None: + break + if selected is None: + raise RuntimeError(f"no contiguous {length}-frame validation prefix") + samples = [dataset[index] for index in selected] + batch_frames = collate_h2o_clips(samples) + sequence = {} + for key in MODEL_INPUT_KEYS: + value = batch_frames[key] + if value.shape[0] != length or value.shape[1] != 1: + raise ValueError(f"unexpected T=1 collate shape for {key}: {value.shape}") + sequence[key] = value[:, 0].unsqueeze(0) + frame_ids = batch_frames["frame_id"][:, 0].tolist() + return sequence, selected_take, [int(value) for value in frame_ids] + + +def prefix(batch: dict[str, torch.Tensor], length: int, device: torch.device) -> dict[str, torch.Tensor]: + return {key: value[:, :length].to(device, non_blocking=True) for key, value in batch.items()} + + +def run_once( + model: BimanualReconstructionModel, + batch: dict[str, torch.Tensor], + dtype: torch.dtype, +) -> dict[str, Any]: + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + return model(batch) + + +def output_snapshot(output: dict[str, Any]) -> dict[str, torch.Tensor]: + return {key: output[key].detach().float().cpu() for key in OUTPUT_KEYS} + + +def max_prefix_differences( + left: dict[str, torch.Tensor], right: dict[str, torch.Tensor], length: int, +) -> dict[str, float]: + return { + key: float((left[key][:, :length] - right[key][:, :length]).abs().max()) + for key in OUTPUT_KEYS + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--repeats", type=int, default=2) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("variable-length audit is hard-gated to official validation") + if args.output.exists(): + parser.error("output must not exist") + if args.repeats < 1: + parser.error("repeats must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + real, take, frame_ids = contiguous_real_sequence( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), max(LENGTHS), + ) + model, step = build_model(config, args.checkpoint, device) + results = [] + snapshots: dict[int, dict[str, torch.Tensor]] = {} + for length in LENGTHS: + current = prefix(real, length, device) + run_once(model, current, dtype) + torch.cuda.synchronize(device) + torch.cuda.reset_peak_memory_stats(device) + latencies = [] + output: dict[str, Any] | None = None + repeats = args.repeats if length <= 16 else 1 + for _ in range(repeats): + start = time.perf_counter() + output = run_once(model, current, dtype) + torch.cuda.synchronize(device) + latencies.append(1000.0 * (time.perf_counter() - start)) + assert output is not None + snapshots[length] = output_snapshot(output) + temporal_attention = output["attention"]["temporal_attention"] + finite = { + key: bool(torch.isfinite(output[key]).all().item()) for key in OUTPUT_KEYS + } + results.append({ + "T": length, + "finite": finite, + "all_finite": all(finite.values()), + "hand_token_shape": list(output["hand_tokens"].shape), + "temporal_attention_shape": list(temporal_attention.shape), + "temporal_attention_elements": temporal_attention.numel(), + "temporal_attention_bytes": temporal_attention.numel() * temporal_attention.element_size(), + "latency_ms_p50": float(statistics.median(latencies)), + "latency_ms_samples": latencies, + "peak_allocated_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + }) + del output, current + torch.cuda.empty_cache() + print(f"T={length} complete", flush=True) + + base8 = prefix(real, 8, device) + changed8 = {key: value.clone() for key, value in base8.items()} + changed8["rgb"][:, 4:] = 1.0 - changed8["rgb"][:, 4:] + changed8["depth_m"][:, 4:] = 0.0 + changed8["depth_pixel_valid"][:, 4:] = False + changed8["depth_available"][:, 4:] = False + original8 = output_snapshot(run_once(model, base8, dtype)) + perturbed8 = output_snapshot(run_once(model, changed8, dtype)) + future_differences = max_prefix_differences(original8, perturbed8, 4) + prefix_differences = max_prefix_differences(snapshots[8], snapshots[4], 4) + window_comparisons = [] + reference = snapshots[64] + for length in LENGTHS: + first_joint_delta_mm = float( + torch.linalg.vector_norm( + snapshots[length]["joints_camera"][:, 0] + - reference["joints_camera"][:, 0], dim=-1, + ).mean() * 1000.0 + ) + window_comparisons.append({ + "T": length, + "first_frame_joint_delta_vs_T64_mm": first_joint_delta_mm, + "first_frame_wrist_max_delta_vs_T64_m": float( + (snapshots[length]["wrist_root_translation"][:, 0] + - reference["wrist_root_translation"][:, 0]).abs().max() + ), + }) + report = { + "status": "completed", + "experiment": "P6_S0_variable_length_contract", + "official_validation_used": True, + "official_validation_used_for_selection": False, + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + "device": args.gpu, + "take": take, + "frame_ids": frame_ids, + "forward_results": results, + "window_comparisons": window_comparisons, + "future_perturbation": { + "changed_frames": [4, 5, 6, 7], + "compared_frames": [0, 1, 2, 3], + "maximum_absolute_differences": future_differences, + "strict_zero_passed": all(value == 0.0 for value in future_differences.values()), + }, + "prefix_invariance": { + "prefix_T": 4, "full_T": 8, + "maximum_absolute_differences": prefix_differences, + "strict_zero_passed": all(value == 0.0 for value in prefix_differences.values()), + }, + "contract": { + "tensor_shape_variable_length": all(item["all_finite"] for item in results), + "offline_bidirectional_variable_length": True, + "bounded_memory_causal_streaming": False, + "historical_causal_description": "causal z-state postprocessor over noncausal T=8 coarse predictions", + }, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], + "future_strict_zero": report["future_perturbation"]["strict_zero_passed"], + "prefix_strict_zero": report["prefix_invariance"]["strict_zero_passed"], + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_arctic.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_arctic.py new file mode 100644 index 0000000000000000000000000000000000000000..782a56fcee3691d848037cb01ef48c6c9763b4c5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_arctic.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Deterministic numeric and visual audit for ARCTIC P2 train view 0.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + "max": float(array.max()), + } + + +def select_indices(rows: list[dict], count: int) -> list[int]: + recordings: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + recordings[(row["subject_id"], row["physical_recording_id"])].append(index) + strata: dict[str, list[int]] = defaultdict(list) + for (subject, _), indices in sorted(recordings.items()): + strata[subject].append(indices[len(indices) // 2]) + selected, cursor = [], 0 + while len(selected) < count: + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected.append(strata[subject][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) != count: + raise RuntimeError(f"only {len(selected)} subject/recording strata available") + return selected + + +def denormalize(image: torch.Tensor) -> np.ndarray: + value = image.permute(1, 2, 0).numpy() + return np.rint(np.clip((value * RGB_STD + RGB_MEAN) * 255.0, 0, 255)).astype(np.uint8) + + +def render(case: dict, output: Path) -> None: + image = case["image"].copy() + for side, color in enumerate(((40, 190, 250), (250, 100, 60))): + for point in case["joint2d"][side][case["joint_valid"][side]]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, color, -1) + cv2.putText( + image, f"{case['category']} {case['recording']}", (10, 24), + cv2.FONT_HERSHEY_SIMPLEX, .55, (255, 255, 255), 2, cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=16) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + dataset = ARCTICClipDataset(args.manifest, args.mano_root) + indices = select_indices(dataset.rows, args.clips) + enabled_regen, excluded_left, enabled_reprojection = [], [], [] + wrist_depth, hand_size, cases, hand_counts = [], [], [], [] + side_frames = {"left": 0, "right": 0} + root_relative_side_frames = {"left": 0, "right": 0} + root_relative_root_norm_mm: list[float] = [] + for index in indices: + sample = dataset[index] + enabled_regen.extend(sample["source_vertex_regen_error_mm"][sample["vertices_valid"]].tolist()) + left = sample["translation_valid"][:, 0] + excluded_left.extend(sample["source_vertex_regen_error_mm"][:, 0][left].tolist()) + for side_index, side in enumerate(("left", "right")): + valid = sample["joint3d_root_relative_valid"][:, side_index] + root_relative_side_frames[side] += int(valid.any(dim=-1).sum()) + root_relative_root_norm_mm.extend( + (torch.linalg.vector_norm( + sample["joint3d_root_relative"][:, side_index, 0], dim=-1, + )[valid[:, 0]] * 1000.0).tolist() + ) + enabled_reprojection.extend( + sample["projection_roundtrip_error_px"][sample["reprojection_valid"]].tolist() + ) + for frame in range(len(sample["frame_valid"])): + valid_hands = sample["translation_valid"][frame] + hand_counts.append(int(valid_hands.sum())) + sizes = [] + for side_index, side in enumerate(("left", "right")): + if not valid_hands[side_index]: + continue + side_frames[side] += 1 + wrist_depth.append(float(sample["wrist_root_translation"][frame, side_index, 2])) + points = sample["joint2d"][frame, side_index][sample["joint2d_valid"][frame, side_index]] + if len(points): + sizes.append(float((points.max(0).values - points.min(0).values).max())) + hand_size.extend(sizes) + points = sample["joint2d"][frame][sample["joint2d_valid"][frame]] + height, width = sample["rgb"].shape[-2:] + border = ( + float(torch.stack((points[:, 0], points[:, 1], width - points[:, 0], height - points[:, 1])).amin()) + if len(points) else float("inf") + ) + z = sample["wrist_root_translation"][frame, valid_hands, 2] + cases.append({ + "recording": sample["physical_recording_id"], + "image": denormalize(sample["rgb"][frame]), + "joint2d": sample["joint2d"][frame].numpy(), + "joint_valid": sample["joint2d_valid"][frame].numpy(), + "count": int(valid_hands.sum()), + "z": float(z.mean()) if len(z) else float("nan"), + "size": max(sizes, default=0.0), "border": border, + }) + valid_cases = [row for row in cases if row["count"] > 0] + selectors = { + "near": min(valid_cases, key=lambda row: row["z"]), + "far": max(valid_cases, key=lambda row: row["z"]), + "small": min(valid_cases, key=lambda row: row["size"]), + "border": min(valid_cases, key=lambda row: row["border"]), + "bimanual": next(row for row in valid_cases if row["count"] == 2), + } + single = next((row for row in valid_cases if row["count"] == 1), None) + if single is not None: + selectors["single"] = single + visuals = {} + for category, value in selectors.items(): + path = args.output_dir / f"{category}.png" + render(dict(value, category=category), path) + visuals[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + report = { + "status": "pending", "official_test_used": False, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clips": len(indices), "frames": len(cases), "clip_indices": indices, + "side_frames": side_frames, + "no_visible_hand_frames": hand_counts.count(0), + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "source_regeneration_mm": quantiles(enabled_regen), + "enabled_reprojection_roundtrip_px": quantiles(enabled_reprojection), + "excluded_left_geometry_regeneration_mm": quantiles(excluded_left), + "wrist_depth_m": quantiles(wrist_depth), + "projected_hand_size_px": quantiles(hand_size), + "image_contract": "full 840x600 ego view (0.3x 2800x2000), cv2 undistort with scaled K/dist8, then full-frame resize/pad", + "partial_supervision_contract": { + "right": "2D/3D/translation/pose/shape/vertices/reprojection", + "left": "direct-2D/translation/pose only", + }, + "source_compatible_root_relative_joint3d": { + "side_frames": root_relative_side_frames, + "root_norm_mm": quantiles(root_relative_root_norm_mm), + "shape_vertices_enabled": False, + "claim": "source-compatible legacy MANO joint target only; not corrected-MANO regeneration", + }, + "visualizations": visuals, + } + passed = ( + len(cases) >= 100 and report["source_regeneration_mm"]["max"] < 1.0 + and report["enabled_reprojection_roundtrip_px"]["p95"] < 1.0 + and all(value > 0 for value in side_frames.values()) + and all(value > 0 for value in root_relative_side_frames.values()) + and report["source_compatible_root_relative_joint3d"]["root_norm_mm"]["max"] < 1e-4 + and report["bimanual_frames"] > 0 + ) + report["status"] = "passed" if passed else "failed" + (args.output_dir / "audit.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_egodexter.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_egodexter.py new file mode 100644 index 0000000000000000000000000000000000000000..acd74ce8142f1d6b95335fba94e4dbd155454225 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_egodexter.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Deterministic no-model EgoDexter source audit for Phase 7.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path + +import numpy as np + +from foundation_hand.data.egodexter_dataset import EgoDexterSequenceDataset, SEQUENCES + + +def finite_summary(values: np.ndarray) -> dict[str, float | int]: + values = values[np.isfinite(values)] + return { + "count": int(len(values)), + "median": float(np.median(values)), + "p95": float(np.quantile(values, .95)), + "max": float(values.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--decode-frames-per-sequence", type=int, default=25) + args = parser.parse_args() + if args.decode_frames_per_sequence < 1: + parser.error("--decode-frames-per-sequence must be positive") + report: dict[str, object] = { + "status": "numeric_adapter_passed_handedness_freeze_pending", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "dataset": "EgoDexter", + "training_or_selection_use": False, + "official_test_used": False, + "camera_frame": "depth_camera", + "depth_units_input": "millimeters", + "model_units": "meters", + "rgb_stream": "color_on_depth full frame", + "input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "sequence_handedness": "must be frozen before first model inference", + "sequences": {}, + } + total_frames = 0 + total_visible = 0 + total_annotated = 0 + for sequence in SEQUENCES: + dataset = EgoDexterSequenceDataset(args.root, sequence, hand_side="left") + xyz = dataset.fingertips_3d_m + valid = np.linalg.norm(xyz, axis=-1) > 0.0 + uv = np.full_like(xyz[..., :2], np.nan) + uv[..., 0] = ( + dataset.K_source[0, 0] * xyz[..., 0] + / np.where(valid, xyz[..., 2], np.nan) + dataset.K_source[0, 2] + ) + uv[..., 1] = ( + dataset.K_source[1, 1] * xyz[..., 1] + / np.where(valid, xyz[..., 2], np.nan) + dataset.K_source[1, 2] + ) + error = np.linalg.norm(uv - dataset.fingertips_2d, axis=-1)[valid] + sample_indices = np.linspace( + 0, len(dataset) - 1, + min(args.decode_frames_per_sequence, len(dataset)), dtype=np.int64, + ) + depth_valid_fraction = [] + for index in sample_indices: + _, depth_mm, _ = dataset._load(int(index)) + depth_valid_fraction.append(float((depth_mm > 0).mean())) + lines = (dataset.sequence_root / "annotation.txt_3D.txt").read_text( + encoding="utf-8", + ).splitlines() + sequence_report = { + "frames": len(dataset), + "visible_fingertips": int(valid.sum()), + "annotated_frames": int(np.any(valid, axis=1).sum()), + "partial_annotation_rows": sum( + len([group for group in line.split(";") if group.strip()]) < 5 + for line in lines + ), + "projection_roundtrip_px": finite_summary(error), + "decoded_frames": len(sample_indices), + "depth_valid_fraction_mean": float(np.mean(depth_valid_fraction)), + } + report["sequences"][sequence] = sequence_report + total_frames += len(dataset) + total_visible += int(valid.sum()) + total_annotated += int(np.any(valid, axis=1).sum()) + report["totals"] = { + "frames": total_frames, + "visible_fingertips": total_visible, + "annotated_frames": total_annotated, + "decoded_numeric_audit_frames": args.decode_frames_per_sequence * len(SEQUENCES), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_hoi4d.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_hoi4d.py new file mode 100644 index 0000000000000000000000000000000000000000..db2cfc39662dcb4bb7473cb83d81701c37149f39 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_hoi4d.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Deterministic numeric and visual audit of the Phase 7 HOI4D adapter.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + "max": float(array.max()), + } + + +def select_indices(rows: list[dict], count: int) -> list[int]: + strata: dict[tuple[str, str], list[int]] = {} + seen: set[str] = set() + for index, row in enumerate(rows): + side_sets = [set(value) for value in row["hand_sides"]] + hand_class = ( + "bimanual" if any(len(value) == 2 for value in side_sets) else + "left" if any("left" in value for value in side_sets) else "right" + ) + key = (row["subject_id"], hand_class) + if row["physical_recording_id"] in seen: + continue + seen.add(row["physical_recording_id"]) + strata.setdefault(key, []).append(index) + selected: list[int] = [] + keys = sorted(strata) + cursor = 0 + while len(selected) < count: + progress = False + for key in keys: + if cursor < len(strata[key]): + selected.append(strata[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) != count: + raise RuntimeError(f"only {len(selected)} stratified clips found") + return selected + + +def denormalize(image: torch.Tensor) -> np.ndarray: + value = image.permute(1, 2, 0).numpy() + return np.rint(np.clip((value * RGB_STD + RGB_MEAN) * 255.0, 0, 255)).astype(np.uint8) + + +def render(case: dict, output: Path) -> None: + image = case["image"].copy() + colors = ((40, 190, 250), (250, 100, 60)) + for side in range(2): + for point in case["joint2d"][side][case["joint_valid"][side]]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, colors[side], -1) + depth = case["depth"] + valid = depth > 0 + depth_color = np.zeros((*depth.shape, 3), dtype=np.uint8) + if valid.any(): + scale = np.quantile(depth[valid], .95) + normalized = np.clip(depth / max(scale, 1e-6), 0, 1) + depth_color = cv2.applyColorMap( + np.rint(normalized * 255).astype(np.uint8), cv2.COLORMAP_TURBO, + )[..., ::-1] + depth_color[~valid] = 0 + combined = np.concatenate((image, depth_color), axis=1) + cv2.putText( + combined, f"{case['category']} {case['recording']}", (10, 24), + cv2.FONT_HERSHEY_SIMPLEX, .55, (255, 255, 255), 2, cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(combined, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=16) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + dataset = HOI4DClipDataset(args.root, args.manifest, args.mano_root) + indices = select_indices(dataset.rows, args.clips) + projection, regeneration, incompatible_left, depth_fraction, wrist_depth, hand_size = [], [], [], [], [], [] + cases: list[dict] = [] + side_frames = {"left": 0, "right": 0} + root_relative_side_frames = {"left": 0, "right": 0} + root_relative_root_norm_mm: list[float] = [] + hand_counts: list[int] = [] + for index in indices: + sample = dataset[index] + projection.extend(sample["projection_roundtrip_error_px"][sample["joint2d_valid"]].tolist()) + regeneration.extend(sample["source_vertex_regen_error_mm"][sample["vertices_valid"]].tolist()) + left_present = sample["translation_valid"][:, 0] + incompatible_left.extend(sample["source_vertex_regen_error_mm"][:, 0][left_present].tolist()) + for side_index, side in enumerate(("left", "right")): + valid = sample["joint3d_root_relative_valid"][:, side_index] + root_relative_side_frames[side] += int(valid.any(dim=-1).sum()) + root_relative_root_norm_mm.extend( + (torch.linalg.vector_norm( + sample["joint3d_root_relative"][:, side_index, 0], dim=-1, + )[valid[:, 0]] * 1000.0).tolist() + ) + for frame in range(len(sample["frame_valid"])): + valid_hands = sample["translation_valid"][frame] + hand_counts.append(int(valid_hands.sum())) + for side_index, side in enumerate(("left", "right")): + if valid_hands[side_index]: + side_frames[side] += 1 + wrist_depth.append(float(sample["wrist_root_translation"][frame, side_index, 2])) + points = sample["joint2d"][frame, side_index][sample["joint2d_valid"][frame, side_index]] + extent = points.max(0).values - points.min(0).values + hand_size.append(float(extent.max())) + depth_fraction.append(float(sample["depth_pixel_valid"][frame].float().mean())) + points = sample["joint2d"][frame][sample["joint2d_valid"][frame]] + height, width = sample["rgb"].shape[-2:] + border = min( + torch.stack((points[:, 0], points[:, 1], width - points[:, 0], height - points[:, 1])).amin().item() + if len(points) else float("inf"), + 1e9, + ) + cases.append({ + "recording": sample["physical_recording_id"], + "image": denormalize(sample["rgb"][frame]), + "depth": sample["depth_m"][frame, 0].numpy(), + "joint2d": sample["joint2d"][frame].numpy(), + "joint_valid": sample["joint2d_valid"][frame].numpy(), + "count": int(valid_hands.sum()), + "z": float(sample["wrist_root_translation"][frame, valid_hands, 2].mean()), + "size": max([ + float((sample["joint2d"][frame, side][sample["joint2d_valid"][frame, side]].max(0).values - sample["joint2d"][frame, side][sample["joint2d_valid"][frame, side]].min(0).values).max()) + for side in range(2) if sample["joint2d_valid"][frame, side].any() + ], default=0.0), + "border": border, + }) + selectors = { + "near": min(cases, key=lambda row: row["z"]), + "far": max(cases, key=lambda row: row["z"]), + "small": min(cases, key=lambda row: row["size"]), + "border": min(cases, key=lambda row: row["border"]), + "single": next(row for row in cases if row["count"] == 1), + "bimanual": next(row for row in cases if row["count"] == 2), + } + visuals = {} + for category, value in selectors.items(): + case = dict(value, category=category) + path = args.output_dir / f"{category}.png" + render(case, path) + visuals[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + report = { + "status": "pending", + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clip_indices": indices, + "clips": len(indices), "frames": len(cases), + "side_frames": side_frames, + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "projection_roundtrip_px": quantiles(projection), + "source_regeneration_mm": quantiles(regeneration), + "excluded_left_geometry_regeneration_mm": quantiles(incompatible_left), + "partial_supervision_contract": { + "right": "2D/3D/translation/pose/shape/vertices/reprojection", + "left": "direct-2D/translation/pose only", + "reason": "historical HOI4D MANO-left shapedirs cannot regenerate under corrected HOT3D/SMPL-X convention within 1 mm", + }, + "source_compatible_root_relative_joint3d": { + "side_frames": root_relative_side_frames, + "root_norm_mm": quantiles(root_relative_root_norm_mm), + "shape_vertices_enabled": False, + "claim": "source-compatible legacy MANO joint target only; not corrected-MANO regeneration", + }, + "depth_valid_fraction": quantiles(depth_fraction), + "wrist_depth_m": quantiles(wrist_depth), + "projected_hand_size_px": quantiles(hand_size), + "rgb_depth_sync": "same released aligned frame index decoded from both streams", + "depth_decode": "FFmpeg gray16le retained; millimeters converted to meters", + "visualizations": visuals, + "official_test_used": False, + } + passed = ( + len(cases) >= 100 and report["projection_roundtrip_px"]["median"] < .5 + and report["projection_roundtrip_px"]["p95"] < 1.0 + and report["source_regeneration_mm"]["max"] < 1.0 + and all(value > 0 for value in side_frames.values()) + and all(value > 0 for value in root_relative_side_frames.values()) + and report["source_compatible_root_relative_joint3d"]["root_norm_mm"]["max"] < 1e-4 + and report["single_hand_frames"] > 0 and report["bimanual_frames"] > 0 + ) + report["status"] = "passed" if passed else "failed" + (args.output_dir / "audit.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_hot3d.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_hot3d.py new file mode 100644 index 0000000000000000000000000000000000000000..bfb6e7fdb573f9f019252e1e8a5aab2b5086a635 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase7_hot3d.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Deterministic HOT3D numeric and full-frame visualization audit.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def select_clip_indices(rows: list[dict], count: int) -> list[int]: + strata: dict[tuple[str, str], list[int]] = {} + seen_recordings: set[tuple[str, str, str]] = set() + for index, row in enumerate(rows): + hand_class = "single" if min(row.get("hand_count", [2])) == 1 else "bimanual" + key = (row["headset"], hand_class) + recording_key = (row["headset"], hand_class, row["recording_id"]) + if recording_key in seen_recordings: + continue + seen_recordings.add(recording_key) + strata.setdefault(key, []).append(index) + ordered_keys = sorted(strata) + selected: list[int] = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in ordered_keys: + values = strata[key] + if cursor < len(values): + selected.append(values[cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + if len(selected) < count: + raise RuntimeError(f"only {len(selected)} stratified clips available") + return selected + + +def quantiles(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": int(array.size), + "mean": float(array.mean()), + "median": float(np.median(array)), + "p95": float(np.quantile(array, 0.95)), + "max": float(array.max()), + } + + +def denormalize(rgb: torch.Tensor) -> np.ndarray: + image = rgb.permute(1, 2, 0).cpu().numpy() + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def render_case(case: dict, output: Path) -> None: + image = case["image"].copy() + colors = ((40, 190, 250), (250, 100, 60)) + for side in range(2): + valid = case["joint_valid"][side] + for point in case["joint2d"][side][valid]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, colors[side], -1) + cv2.putText( + image, + f"{case['category']} {case['recording']} {case['stream']}", + (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 2, + cv2.LINE_AA, + ) + cv2.imwrite(str(output), cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, default=13) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + dataset = HOT3DClipDataset( + args.root, args.manifest, args.toolkit_root, args.mano_root, + K_input_dropout=0.3, dropout_seed=20260717, + ) + indices = select_clip_indices(dataset.rows, args.clips) + projection_errors: list[float] = [] + regeneration_errors: list[float] = [] + wrist_depths: list[float] = [] + hand_sizes: list[float] = [] + hand_counts: list[int] = [] + hand_sync_ms: list[float] = [] + headset_sync_ms: list[float] = [] + frame_cases: list[dict] = [] + headset_counts: dict[str, int] = {} + K_keep: list[bool] = [] + for index in indices: + sample = dataset[(index, 0)] + headset_counts[sample["headset_id"]] = headset_counts.get(sample["headset_id"], 0) + int(sample["frame_valid"].sum()) + projection_errors.extend(sample["projection_roundtrip_error_px"][torch.isfinite(sample["projection_roundtrip_error_px"])].tolist()) + regeneration_errors.extend(sample["source_vertex_regen_error_mm"][sample["translation_valid"]].tolist()) + hand_sync_ms.extend((sample["hand_pose_time_delta_ns"].abs() / 1e6).tolist()) + headset_sync_ms.extend((sample["headset_time_delta_ns"].abs() / 1e6).tolist()) + K_keep.append(bool(sample["K_input_available"][0])) + for frame_index in range(int(sample["frame_valid"].sum())): + valid_hands = sample["translation_valid"][frame_index] + hand_counts.append(int(valid_hands.sum())) + joint_valid = sample["joint2d_valid"][frame_index] + for side in range(2): + if not valid_hands[side]: + continue + wrist_depths.append(float(sample["wrist_root_translation"][frame_index, side, 2])) + points = sample["joint2d"][frame_index, side][joint_valid[side]] + if len(points): + extent = points.max(0).values - points.min(0).values + hand_sizes.append(float(extent.max())) + points_all = sample["joint2d"][frame_index][joint_valid] + if len(points_all): + h, w = sample["rgb"].shape[-2:] + border = torch.stack((points_all[:, 0], points_all[:, 1], w - points_all[:, 0], h - points_all[:, 1])).amin().item() + else: + border = float("inf") + valid_depth = sample["wrist_root_translation"][frame_index, :, 2][valid_hands] + frame_cases.append({ + "recording": sample["physical_recording_id"], + "stream": sample["stream_id"], + "image": denormalize(sample["rgb"][frame_index]), + "joint2d": sample["joint2d"][frame_index].cpu().numpy(), + "joint_valid": joint_valid.cpu().numpy(), + "hand_count": int(valid_hands.sum()), + "depth": float(valid_depth.mean()) if len(valid_depth) else float("nan"), + "border": float(border), + "size": float(max( + [ + (sample["joint2d"][frame_index, side][joint_valid[side]].max(0).values - sample["joint2d"][frame_index, side][joint_valid[side]].min(0).values).max().item() + for side in range(2) if joint_valid[side].any() + ], default=0.0, + )), + }) + + selectors = { + "near": lambda rows: min(rows, key=lambda row: row["depth"]), + "far": lambda rows: max(rows, key=lambda row: row["depth"]), + "border": lambda rows: min(rows, key=lambda row: row["border"]), + "small": lambda rows: min(rows, key=lambda row: row["size"]), + "single": lambda rows: next(row for row in rows if row["hand_count"] == 1), + "bimanual": lambda rows: next(row for row in rows if row["hand_count"] == 2), + } + visualizations = {} + for category, selector in selectors.items(): + case = dict(selector(frame_cases)) + case["category"] = category + path = args.output_dir / f"{category}.png" + render_case(case, path) + visualizations[category] = {"path": str(path.resolve()), "sha256": sha256(path)} + audit = { + "status": "passed", + "official_test_used": False, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "clip_indices": indices, + "clips": len(indices), + "frames": len(frame_cases), + "headset_frame_counts": headset_counts, + "single_hand_frames": hand_counts.count(1), + "bimanual_frames": hand_counts.count(2), + "projection_roundtrip_px": quantiles(projection_errors), + "source_regeneration_mm": quantiles(regeneration_errors), + "hand_pose_sync_ms": quantiles(hand_sync_ms), + "headset_sync_ms": quantiles(headset_sync_ms), + "wrist_depth_m": quantiles(wrist_depths), + "projected_hand_size_px": quantiles(hand_sizes), + "K_input_kept_clips": int(sum(K_keep)), + "K_input_dropped_clips": int(len(K_keep) - sum(K_keep)), + "visualizations": visualizations, + } + passed = ( + audit["frames"] >= 100 + and audit["projection_roundtrip_px"]["median"] < 0.5 + and audit["projection_roundtrip_px"]["p95"] < 1.0 + and audit["source_regeneration_mm"]["max"] < 1.0 + and audit["single_hand_frames"] > 0 + and audit["bimanual_frames"] > 0 + ) + audit["status"] = "passed" if passed else "failed" + output = args.output_dir / "audit.json" + output.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") + print(json.dumps(audit, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase9_resolution_cache.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase9_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..440147147d411ed3f266dfde7363c9c87e5f944f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase9_resolution_cache.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Audit true-source Phase 9 resolution caches and train-only folds.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +EXPECTED_HW = (512, 896) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def source_index_digest(rows: list[dict[str, Any]]) -> str: + values = [int(row["source_clip_index"]) for row in rows] + payload = json.dumps(values, separators=(",", ":")).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def projection_error_px(archive: np.lib.npyio.NpzFile) -> float: + xyz = archive["joint3d_camera"] + target = archive["joint2d"] + intrinsics = archive["K"] + z = xyz[..., 2] + projected = np.empty_like(target) + projected[..., 0] = ( + intrinsics[:, None, None, 0, 0] * xyz[..., 0] / z + + intrinsics[:, None, None, 0, 2] + ) + projected[..., 1] = ( + intrinsics[:, None, None, 1, 1] * xyz[..., 1] / z + + intrinsics[:, None, None, 1, 2] + ) + valid = ( + archive["reprojection_valid"].astype(bool) + & archive["joint3d_valid"].astype(bool) + & np.isfinite(projected).all(axis=-1) + & (z > 1e-6) + ) + if not valid.any(): + return 0.0 + return float(np.linalg.norm(projected[valid] - target[valid], axis=-1).max()) + + +def audit_payload(path: Path) -> dict[str, Any]: + with np.load(path, allow_pickle=False) as archive: + if tuple(int(value) for value in archive["image_hw"].reshape(-1)) != EXPECTED_HW: + raise ValueError(f"payload resolution differs: {path}") + if archive["rgb_u8"].shape != (8, *EXPECTED_HW, 3): + raise ValueError(f"RGB shape differs: {path}") + if archive["depth_m"].shape != (8, 1, *EXPECTED_HW): + raise ValueError(f"depth shape differs: {path}") + if archive["depth_pixel_valid"].shape != (8, 1, *EXPECTED_HW): + raise ValueError(f"depth validity shape differs: {path}") + valid_depth = archive["depth_pixel_valid"].astype(bool) + depth = archive["depth_m"] + if valid_depth.any() and ( + not np.isfinite(depth[valid_depth]).all() + or not (depth[valid_depth] > 0).all() + ): + raise ValueError(f"valid depth contains nonpositive/nonfinite values: {path}") + intrinsics = archive["K"] + if ( + intrinsics.shape != (8, 3, 3) + or not np.isfinite(intrinsics).all() + or not (intrinsics[:, 0, 0] > 0).all() + or not (intrinsics[:, 1, 1] > 0).all() + or not np.allclose(intrinsics[:, 2], (0.0, 0.0, 1.0), atol=1e-6) + ): + raise ValueError(f"intrinsics contract differs: {path}") + error = projection_error_px(archive) + if error > 1.0: + raise ValueError(f"projection error exceeds 1 px ({error}): {path}") + return { + "path": str(path.resolve()), + "projection_error_max_px": error, + "depth_valid_fraction": float(valid_depth.mean()), + } + + +def audit_cache(item: dict[str, Any]) -> dict[str, Any]: + report_path = Path(item["report"]) + manifest_path = Path(item["manifest"]) + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or tuple(report.get("resolution_hw", ())) != EXPECTED_HW + or report.get("source_manifest", {}).get("sha256") + != item["source_manifest_sha256"] + or report.get("cache_manifest", {}).get("sha256") != sha256(manifest_path) + or report.get("resume_invocation") is not True + ): + raise ValueError(f"cache report contract differs: {item['id']}") + rows = read_jsonl(manifest_path) + if ( + len(rows) != int(item["clips"]) + or len({int(row["source_clip_index"]) for row in rows}) != len(rows) + or {row.get("dataset_id") for row in rows} != {item["dataset"]} + or any(tuple(row.get("resolution_hw", ())) != EXPECTED_HW for row in rows) + ): + raise ValueError(f"cache manifest contract differs: {item['id']}") + if item.get("recordings") is not None and len({ + row["physical_recording_id"] for row in rows + }) != int(item["recordings"]): + raise ValueError(f"recording count differs: {item['id']}") + control_rows = read_jsonl(Path(item["control_manifest"])) + if [row["source_clip_index"] for row in rows] != [ + row["source_clip_index"] for row in control_rows + ]: + raise ValueError(f"source clip selection differs from 640 control: {item['id']}") + payload_bytes = 0 + for row in rows: + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"payload hash differs: {path}") + payload_bytes += path.stat().st_size + samples = [audit_payload(Path(rows[index]["cache_path"])) for index in { + 0, len(rows) // 2, len(rows) - 1, + }] + return { + "id": item["id"], + "dataset": item["dataset"], + "clips": len(rows), + "recordings": len({row["physical_recording_id"] for row in rows}), + "manifest": str(manifest_path.resolve()), + "manifest_sha256": sha256(manifest_path), + "source_index_sha256": source_index_digest(rows), + "control_source_index_sha256": source_index_digest(control_rows), + "payload_bytes": payload_bytes, + "all_payload_sha256_verified": True, + "samples": samples, + } + + +def audit_sidecar(item: dict[str, Any]) -> dict[str, Any]: + report = json.loads(Path(item["report"]).read_text(encoding="utf-8")) + base_rows = read_jsonl(Path(item["base_manifest"])) + rows = read_jsonl(Path(item["manifest"])) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("base_cache_manifest", {}).get("sha256") + != sha256(item["base_manifest"]) + or report.get("augmented_cache_manifest", {}).get("sha256") + != sha256(item["manifest"]) + or report.get("right_valid_joint_count") != 0 + or float(report.get("root_norm_max_mm", math.inf)) >= 1e-4 + or report.get("shape_supervision_restored") is not False + or report.get("vertices_supervision_restored") is not False + or report.get("camera_joint3d_supervision_restored") is not False + or len(rows) != len(base_rows) + ): + raise ValueError(f"sidecar report contract differs: {item['id']}") + for base, row in zip(base_rows, rows, strict=True): + if ( + row["source_clip_index"] != base["source_clip_index"] + or row["cache_path"] != base["cache_path"] + or row["cache_sha256"] != base["cache_sha256"] + or row.get("joint3d_root_relative_scope") != "historical_left_only" + or sha256(row["joint3d_root_relative_sidecar_path"]) + != row["joint3d_root_relative_sidecar_sha256"] + ): + raise ValueError(f"sidecar row binding differs: {item['id']}") + return { + "id": item["id"], + "clips": len(rows), + "manifest_sha256": sha256(item["manifest"]), + "left_hand_frames": report["left_hand_frames"], + "all_sidecar_sha256_verified": True, + } + + +def audit_multifold(item: dict[str, Any], h2o_rows: list[dict[str, Any]]) -> dict[str, Any]: + index = json.loads(Path(item["index"]).read_text(encoding="utf-8")) + rebuild = json.loads(Path(item["rebuild_index"]).read_text(encoding="utf-8")) + if ( + index.get("status") != "complete" + or index.get("official_test_used") is not False + or index.get("h2o_official_validation_used") is not False + or index.get("source_cache_manifest", {}).get("sha256") + != sha256(item["source_manifest"]) + or len(index.get("folds", [])) != 6 + ): + raise ValueError("resolution multifold index contract differs") + if ( + rebuild.get("status") != "complete" + or rebuild.get("official_test_used") is not False + or rebuild.get("h2o_official_validation_used") is not False + or rebuild.get("source_cache_manifest", {}).get("sha256") + != index["source_cache_manifest"]["sha256"] + or [fold["id"] for fold in rebuild.get("folds", [])] + != [fold["id"] for fold in index["folds"]] + or [ + (fold["train"]["sha256"], fold["heldout"]["sha256"]) + for fold in rebuild["folds"] + ] != [ + (fold["train"]["sha256"], fold["heldout"]["sha256"]) + for fold in index["folds"] + ] + ): + raise ValueError("resolution multifold deterministic rebuild differs") + base_groups = {row["physical_recording_id"] for row in h2o_rows} + fold_audits = [] + for fold in index["folds"]: + train = read_jsonl(Path(fold["train"]["path"])) + heldout = read_jsonl(Path(fold["heldout"]["path"])) + train_groups = {row["physical_recording_id"] for row in train} + heldout_groups = {row["physical_recording_id"] for row in heldout} + if ( + train_groups & heldout_groups + or train_groups | heldout_groups != base_groups + or len(train) + len(heldout) != len(h2o_rows) + or sha256(fold["train"]["path"]) != fold["train"]["sha256"] + or sha256(fold["heldout"]["path"]) != fold["heldout"]["sha256"] + ): + raise ValueError(f"resolution multifold leakage/binding differs: {fold['id']}") + fold_audits.append({ + "id": fold["id"], "train_clips": len(train), + "heldout_clips": len(heldout), "group_overlap": 0, + }) + return { + "folds": fold_audits, + "physical_recording_isolation": True, + "deterministic_rebuild_hashes_match": True, + } + + +def audit(plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution execution plan lacks official-data isolation") + caches = [audit_cache(item) for item in plan["caches"]] + cache_by_id = {item["id"]: item for item in plan["caches"]} + h2o_rows = read_jsonl(Path(cache_by_id["h2o_train"]["manifest"])) + sidecars = [audit_sidecar(item) for item in plan["sidecars"]] + multifold = audit_multifold(plan["multifold"], h2o_rows) + return { + "schema_version": "phase9_resolution_cache_audit_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "resolution_hw": list(EXPECTED_HW), + "caches": caches, + "sidecars": sidecars, + "multifold": multifold, + "official_test_used": False, + "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("audit output must be new") + result = audit(json.loads(args.plan.read_text(encoding="utf-8"))) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase9_selection_bindings.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase9_selection_bindings.py new file mode 100644 index 0000000000000000000000000000000000000000..7a41a0a543656c690e7a0853f340aaabd6a65cac --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase9_selection_bindings.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Audit every fold report consumed by the frozen Phase 9 selection.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.summarize_phase9_unified_selection import ( + CANDIDATES, + evaluation, + validate_multifold_index, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def json_sha256(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def candidate_records() -> list[tuple[str, str, str]]: + records = [] + for mixture, candidates in CANDIDATES.items(): + for _, fold_checkpoint_id in candidates: + for fold in ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + ): + records.append((mixture, fold_checkpoint_id, fold)) + return records + + +def evaluation_path( + *, fold_final_root: Path, fold_milestone_root: Path, + condition: str, checkpoint_id: str, +) -> Path: + if checkpoint_id == "final": + return fold_final_root / condition / "rgb_d_k" / "evaluation.json" + return ( + fold_milestone_root / condition / checkpoint_id + / "rgb_d_k" / "evaluation.json" + ) + + +def file_binding(record: dict[str, Any], key: str) -> dict[str, Any]: + binding = record.get(key, {}) + path = Path(str(binding.get("path", ""))) + declared = str(binding.get("sha256", "")) + exists = path.is_file() + actual = sha256(path) if exists else None + return { + "path": str(path), + "declared_sha256": declared, + "actual_sha256": actual, + "exists": exists, + "sha256_matches": exists and declared == actual, + } + + +def artifact_binding(report: dict[str, Any], key: str) -> dict[str, Any]: + binding = report.get(key, {}) + path = Path(str(binding.get("path", ""))) + declared = str(binding.get("sha256", "")) + exists = path.is_file() + actual = sha256(path) if exists else None + return { + "path": str(path), + "declared_sha256": declared, + "actual_sha256": actual, + "exists": exists, + "sha256_matches": exists and declared == actual, + } + + +def audit_report( + *, report_path: Path, condition: str, checkpoint_id: str, + expected_manifest_path: str, expected_manifest_sha256: str, +) -> dict[str, Any]: + report = evaluation(report_path, "phase9_h2o_fold_heldout") + cache = file_binding(report, "cache_manifest") + expected_path = Path(expected_manifest_path) + expected_exists = expected_path.is_file() + expected_actual_sha = sha256(expected_path) if expected_exists else None + cache.update({ + "expected_path": expected_manifest_path, + "expected_sha256": expected_manifest_sha256, + "expected_path_exists": expected_exists, + "expected_path_actual_sha256": expected_actual_sha, + "path_matches": cache["path"] == expected_manifest_path, + "content_matches_expected": ( + cache["declared_sha256"] == expected_manifest_sha256 + and cache["actual_sha256"] == expected_manifest_sha256 + and expected_actual_sha == expected_manifest_sha256 + ), + }) + if not cache["content_matches_expected"]: + binding_status = "content_mismatch" + elif not cache["path_matches"]: + binding_status = "path_mismatch_content_identical" + else: + binding_status = "canonical" + result = { + "id": f"{condition}_{checkpoint_id}_rgb_d_k", + "condition": condition, + "checkpoint_id": checkpoint_id, + "input_mode": "rgb_d_k", + "report": { + "path": str(report_path.resolve()), + "sha256": sha256(report_path), + }, + "binding_status": binding_status, + "cache_manifest": cache, + "config": file_binding(report, "config"), + "checkpoint": file_binding(report, "checkpoint"), + "sample_counts": { + "clips": report.get("clips"), + "frames": report.get("frames"), + "hands_rows": report.get("hands_rows"), + }, + "determinism": { + "metrics_sha256": json_sha256(report.get("metrics")), + "grouped_bootstrap_ci_sha256": json_sha256( + report.get("grouped_bootstrap_ci") + ), + "raw_predictions": artifact_binding(report, "raw_predictions"), + "per_hand_rows": artifact_binding(report, "per_hand_rows"), + "take_metrics": artifact_binding(report, "take_metrics"), + }, + "evaluation_role": report.get("evaluation_role"), + "official_test_used": report.get("official_test_used"), + "h2o_official_validation_used": report.get( + "h2o_official_validation_used" + ), + } + required_bindings = [result["config"], result["checkpoint"]] + required_artifacts = [ + result["determinism"]["raw_predictions"], + result["determinism"]["per_hand_rows"], + result["determinism"]["take_metrics"], + ] + if not all(item["sha256_matches"] for item in required_bindings + required_artifacts): + result["binding_status"] = "referenced_artifact_mismatch" + return result + + +def build_audit( + *, selection_plan_path: Path, assignment_path: Path, +) -> dict[str, Any]: + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + if ( + selection_plan.get("official_test_used") is not False + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + ): + raise ValueError("selection audit must explicitly exclude official test") + index_path = Path(selection_plan["multifold_index"]) + index = json.loads(index_path.read_text(encoding="utf-8")) + folds = { + fold["id"]: fold for fold in validate_multifold_index(index) + } + records = [] + for mixture, checkpoint_id, fold in candidate_records(): + condition = f"{mixture}_{fold}" + path = evaluation_path( + fold_final_root=Path(selection_plan["fold_final_root"]), + fold_milestone_root=Path(selection_plan["fold_milestone_root"]), + condition=condition, checkpoint_id=checkpoint_id, + ) + records.append(audit_report( + report_path=path, condition=condition, + checkpoint_id=checkpoint_id, + expected_manifest_path=folds[fold]["heldout"]["path"], + expected_manifest_sha256=folds[fold]["heldout"]["sha256"], + )) + mismatches = [ + record for record in records + if record["binding_status"] != "canonical" + ] + assigned = { + item["id"] + for item in assignment["phase9_selection_recovery"]["evaluations"] + } + mismatch_ids = {item["id"] for item in mismatches} + status_counts = { + status: sum(item["binding_status"] == status for item in records) + for status in sorted({item["binding_status"] for item in records}) + } + if len(records) != 72 or len({item["id"] for item in records}) != 72: + raise ValueError("selection-critical report set is not exactly 72 unique IDs") + if mismatch_ids != assigned: + raise ValueError( + "selection mismatch IDs differ from frozen distributed assignment: " + f"missing={sorted(assigned - mismatch_ids)} " + f"unexpected={sorted(mismatch_ids - assigned)}" + ) + if any( + item["binding_status"] != "path_mismatch_content_identical" + for item in mismatches + ): + raise ValueError("selection mismatch includes a non-path-only failure") + return { + "schema_version": "phase9_selection_binding_mismatch_manifest_v1", + "status": "complete_path_only_recovery_required", + "created_utc": datetime.now(timezone.utc).isoformat(), + "selection_plan": { + "path": str(selection_plan_path.resolve()), + "sha256": sha256(selection_plan_path), + }, + "distributed_assignment": { + "path": str(assignment_path.resolve()), + "sha256": sha256(assignment_path), + }, + "multifold_index": { + "path": str(index_path.resolve()), "sha256": sha256(index_path), + }, + "selection_critical_report_count": len(records), + "canonical_report_count": len(records) - len(mismatches), + "mismatch_count": len(mismatches), + "binding_status_counts": status_counts, + "mismatch_ids": sorted(mismatch_ids), + "records": records, + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("audit output must be new") + result = build_audit( + selection_plan_path=args.selection_plan, + assignment_path=args.assignment, + ) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase9_source_coverage.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase9_source_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..db9555573bedef023846df78f2f866856869bee5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/audit_phase9_source_coverage.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Audit unique source coverage and cached geometric distributions.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def recording_id(row: dict[str, Any]) -> str: + return str(row.get("physical_recording_id", row.get("recording_id", "unknown"))) + + +def subject_id(row: dict[str, Any]) -> str: + return str(row.get("subject_id", row.get("participant_id", "unknown"))) + + +def frame_tokens(row: dict[str, Any]) -> list[str]: + values = ( + row.get("timestamps_ns") or row.get("timestamps_seconds") + or row.get("frame_ids") or row.get("frame_ids_1based") + or row.get("image_paths") or [] + ) + group = recording_id(row) + return [f"{group}:{value}" for value in values] + + +def action_family(dataset: str, recording: str) -> str: + parts = recording.split("/") + if dataset == "H2O" and len(parts) > 1: + return parts[1][:1] + if dataset == "HOI4D": + fields = [part for part in parts if part.startswith(("C", "N", "S"))] + return "/".join(fields[:3]) if fields else "unknown" + if dataset == "ARCTIC" and len(parts) > 1: + return parts[-1].rsplit("_", 1)[0] + return "unknown" + + +def quantiles(values: list[float]) -> dict[str, float | int | None]: + finite = np.asarray(values, dtype=np.float64) + finite = finite[np.isfinite(finite)] + if not len(finite): + return {"count": 0, "mean": None, "p05": None, "median": None, "p95": None} + return { + "count": int(len(finite)), "mean": float(finite.mean()), + "p05": float(np.percentile(finite, 5)), + "median": float(np.percentile(finite, 50)), + "p95": float(np.percentile(finite, 95)), + } + + +def source_summary(dataset: str, rows: list[dict[str, Any]]) -> dict[str, Any]: + tokens = [token for row in rows for token in frame_tokens(row)] + recordings = {recording_id(row) for row in rows} + return { + "clips": len(rows), + "subjects_or_participants": sorted({subject_id(row) for row in rows}), + "physical_recordings": len(recordings), + "headsets": sorted({str(row.get("headset", row.get("serial_id", "unknown"))) for row in rows}), + "cameras_or_streams": sorted({str(row.get("camera_id", row.get("stream_id", "unknown"))) for row in rows}), + "frame_references": len(tokens), + "unique_image_observations": len(set(tokens)) if tokens else None, + "clip_overlap_fraction": (1.0 - len(set(tokens)) / len(tokens)) if tokens else None, + "action_or_object_families": dict(sorted(Counter( + action_family(dataset, recording) for recording in recordings + ).items())), + } + + +def cache_numeric_summary(rows: list[dict[str, Any]]) -> dict[str, Any]: + unique_frames: set[str] = set() + side_frames = [0, 0] + single_frames = bimanual_frames = valid_frames = 0 + joint_visible = joint_total = 0 + border_hands = projected_outlier_hands = 0 + hand_sizes: list[float] = [] + wrist_depths: list[float] = [] + fx_values: list[float] = [] + fy_values: list[float] = [] + fov_x_values: list[float] = [] + depth_valid_fractions: list[float] = [] + supervision = Counter() + for row in rows: + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"cache payload is missing or differs: {path}") + with np.load(path, allow_pickle=False) as archive: + frame_valid = archive["frame_valid"].astype(bool) + translation_valid = archive["translation_valid"].astype(bool) + joint2d_valid = archive["joint2d_valid"].astype(bool) + joint2d = archive["joint2d"] + translation = archive["wrist_root_translation"] + K = archive["K"] + image_hw = archive["image_hw"] + frame_ids = archive["frame_id"] + depth_available = archive["depth_input_available"].astype(bool) + depth_pixel_valid = archive["depth_pixel_valid"].astype(bool) + for key in ( + "joint2d_valid", "joint3d_valid", "translation_valid", + "mano_pose_valid", "shape_valid", "vertices_valid", + ): + supervision[key] += int(np.count_nonzero(archive[key])) + group = row["physical_recording_id"] + for time_index in np.flatnonzero(frame_valid): + unique_frames.add(f"{group}:{int(frame_ids[time_index])}") + valid_frames += 1 + present = translation_valid[time_index] + side_frames[0] += int(present[0]) + side_frames[1] += int(present[1]) + single_frames += int(present.sum() == 1) + bimanual_frames += int(present.sum() == 2) + matrix = K[time_index] + fx_values.append(float(matrix[0, 0])) + fy_values.append(float(matrix[1, 1])) + fov_x_values.append(float(2 * np.arctan(float(image_hw[1]) / (2 * matrix[0, 0])))) + if depth_available[time_index]: + depth_valid_fractions.append(float(depth_pixel_valid[time_index].mean())) + for side in range(2): + if not present[side]: + continue + valid = joint2d_valid[time_index, side] + points_all = joint2d[time_index, side] + height, width = int(image_hw[0]), int(image_hw[1]) + finite = np.isfinite(points_all).all(axis=-1) + in_frame = ( + finite & (points_all[:, 0] >= 0) & (points_all[:, 0] < width) + & (points_all[:, 1] >= 0) & (points_all[:, 1] < height) + ) + visible = valid & in_frame + joint_visible += int(visible.sum()) + joint_total += int(len(valid)) + valid_finite = valid & finite + if valid_finite.any(): + raw_points = points_all[valid_finite] + raw_extent = raw_points.max(axis=0) - raw_points.min(axis=0) + projected_outlier_hands += int(raw_extent.max() > 4 * max(height, width)) + if visible.any(): + points = points_all[visible] + extent = points.max(axis=0) - points.min(axis=0) + hand_sizes.append(float(extent.max())) + border_hands += int( + points[:, 0].min() < 8 or points[:, 0].max() >= width - 8 + or points[:, 1].min() < 8 or points[:, 1].max() >= height - 8 + ) + wrist_depths.append(float(translation[time_index, side, 2])) + return { + "unique_cached_frames": len(unique_frames), + "valid_frame_references": valid_frames, + "left_hand_frames": side_frames[0], + "right_hand_frames": side_frames[1], + "single_hand_frames": single_frames, + "bimanual_frames": bimanual_frames, + "joint_visibility_fraction": joint_visible / joint_total if joint_total else None, + "occlusion_proxy_fraction": 1.0 - joint_visible / joint_total if joint_total else None, + "border_hand_frames": border_hands, + "projected_geometry_outlier_hand_frames": projected_outlier_hands, + "projected_hand_size_px": quantiles(hand_sizes), + "wrist_depth_m": quantiles(wrist_depths), + "fx_px": quantiles(fx_values), + "fy_px": quantiles(fy_values), + "horizontal_fov_radians": quantiles(fov_x_values), + "depth_valid_fraction": quantiles(depth_valid_fractions), + "supervision_valid_elements": dict(supervision), + } + + +def build_report( + dataset: str, source_manifest: Path, cache_manifest: Path, +) -> dict[str, Any]: + source_rows, cache_rows = read_jsonl(source_manifest), read_jsonl(cache_manifest) + cached_indices = {int(row["source_clip_index"]) for row in cache_rows} + if len(cached_indices) != len(cache_rows): + raise ValueError("cache manifest contains duplicate source clip indices") + if {row.get("dataset_id") for row in cache_rows} != {dataset}: + raise ValueError("cache manifest dataset differs from request") + return { + "schema_version": "phase9_source_coverage_v1", + "status": "complete", + "dataset": dataset, + "source_manifest": {"path": str(source_manifest.resolve()), "sha256": sha256(source_manifest)}, + "cache_manifest": {"path": str(cache_manifest.resolve()), "sha256": sha256(cache_manifest)}, + "source": source_summary(dataset, source_rows), + "cache": { + "clips": len(cache_rows), + "source_clip_coverage_fraction": len(cache_rows) / len(source_rows), + "subjects_or_participants": sorted({subject_id(row) for row in cache_rows}), + "physical_recordings": len({recording_id(row) for row in cache_rows}), + **cache_numeric_summary(cache_rows), + }, + "optimizer_exposure_is_unique_coverage": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("H2O", "HOT3D", "HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = build_report(args.dataset, args.source_manifest, args.cache_manifest) + except (OSError, ValueError, KeyError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_manifests.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..51063b592a532d6c453c612b141931ae3ac86d48 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_manifests.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Build reproducible cam4-only H2O run manifests from official pose lists.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path + + +def contiguous_runs(frame_ids: list[int]) -> list[list[int]]: + if not frame_ids: + return [] + runs = [[frame_ids[0]]] + for frame_id in frame_ids[1:]: + if frame_id == runs[-1][-1] + 1: + runs[-1].append(frame_id) + else: + runs.append([frame_id]) + return runs + + +def official_records(path: Path) -> list[dict[str, object]]: + grouped: dict[str, list[int]] = defaultdict(list) + for line in path.read_text(encoding="utf-8").splitlines(): + relative = Path(line.strip()) + if not line.strip(): + continue + if relative.parts[-3] != "cam4" or relative.parts[-2] != "rgb": + raise ValueError(f"Not a cam4 RGB record: {line}") + take = Path(*relative.parts[:-2]) + grouped[str(take)].append(int(relative.stem)) + records = [] + for take, ids in sorted(grouped.items()): + for run_index, run in enumerate(contiguous_runs(sorted(set(ids)))): + records.append({"take": take, "run_index": run_index, "frame_ids": run}) + return records + + +def write_jsonl(path: Path, records: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as handle: + for record in records: + handle.write(json.dumps(record, separators=(",", ":")) + "\n") + + +def build_debug_records(frame_csv: Path, window: int = 16, per_category: int = 4) -> list[dict[str, object]]: + categories: dict[str, list[dict[str, str]]] = defaultdict(list) + with frame_csv.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + key = row["joint_left_valid"] + row["joint_right_valid"] + categories[key].append(row) + selected = [] + for category, rows in sorted(categories.items()): + if category not in {"01", "10", "11"}: + continue + indices = [round(i * (len(rows) - 1) / max(per_category - 1, 1)) for i in range(per_category)] + for row_index in indices: + row = rows[row_index] + center = int(row["frame_id"]) + start = max(0, center - window // 2) + take_path = Path(row["rgb_path"]).parents[1] + available = sorted(int(path.stem) for path in (take_path / "rgb").glob("*.png")) + valid_ids = set(available) + frames = [frame_id for frame_id in range(start, start + window) if frame_id in valid_ids] + selected.append({ + "take": "/".join(take_path.parts[-4:]), + "run_index": len(selected), + "frame_ids": frames, + "debug_center_valid": category, + "debug_center_frame": center, + }) + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--pose-list-dir", type=Path, required=True) + parser.add_argument("--frame-csv", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + summary = {} + for split in ("train", "val", "test"): + records = official_records(args.pose_list_dir / f"pose_{split}.txt") + output = args.output_dir / f"official_{split}.jsonl" + write_jsonl(output, records) + summary[split] = { + "path": str(output.resolve()), + "runs": len(records), + "frames": sum(len(record["frame_ids"]) for record in records), + "subjects": sorted({str(record["take"]).split("/")[0] for record in records}), + } + debug = build_debug_records(args.frame_csv) + debug_path = args.output_dir / "debug_cam4.jsonl" + write_jsonl(debug_path, debug) + summary["debug"] = {"path": str(debug_path.resolve()), "runs": len(debug), "frames": sum(len(record["frame_ids"]) for record in debug)} + tiny = [] + for category in ("01", "10", "11"): + tiny.extend([record for record in debug if record["debug_center_valid"] == category][:2]) + tiny_path = args.output_dir / "tiny_overfit_cam4.jsonl" + write_jsonl(tiny_path, tiny) + summary["tiny_overfit"] = { + "path": str(tiny_path.resolve()), + "runs": len(tiny), + "frames": sum(len(record["frame_ids"]) for record in tiny), + "center_valid_combinations": {category: 2 for category in ("01", "10", "11")}, + } + summary["policy"] = "Official pose split; clips are generated inside each contiguous take/run and never cross camera, sequence, or subject." + (args.output_dir / "manifest_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase3_val_subset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase3_val_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5c9941a59e168b9e49e961c4a41f3556b97aa9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase3_val_subset.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Build the fixed 256-clip Phase 3 validation subset from input-only strata.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.subset import balanced_stratified_indices + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def size_bucket(value: float) -> str: + if value < 64: + return "small" + if value < 128: + return "medium" + return "large" + + +def depth_bucket(value: float) -> str: + if value < 0.5: + return "near" + if value < 0.8: + return "middle" + return "far" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--per-hand-frames", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--count", type=int, default=256) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + with args.per_hand_frames.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + grouped: dict[int, list[dict[str, str]]] = defaultdict(list) + for row in rows: + grouped[int(row["clip_index"])].append(row) + + clip_records: list[dict[str, object]] = [] + for clip_index, clip_rows in sorted(grouped.items()): + sizes = [float(row["hand_size_px"]) for row in clip_rows if row["hand_size_px"]] + depths = [float(row["wrist_depth_m"]) for row in clip_rows if row["wrist_depth_m"]] + states = [row["annotation_state"] for row in clip_rows] + state_counts = Counter(states) + # Preserve rare one-hand-valid clips as a stratum instead of letting the + # dominant both-valid frames erase them. + annotation_state = "01" if state_counts["01"] else "10" if state_counts["10"] else state_counts.most_common(1)[0][0] + median_size = float(np.median(sizes)) if sizes else float("nan") + median_depth = float(np.median(depths)) if depths else float("nan") + first = clip_rows[0] + clip_records.append({ + "clip_index": clip_index, + "take": first["take"], + "subject": first["subject"], + "sequence": first["sequence"], + "first_frame_id": min(int(row["frame_id"]) for row in clip_rows), + "last_frame_id": max(int(row["frame_id"]) for row in clip_rows), + "hand_size_px_median": median_size, + "hand_size_bucket": size_bucket(median_size) if np.isfinite(median_size) else "unavailable", + "wrist_depth_m_median": median_depth, + "depth_bucket": depth_bucket(median_depth) if np.isfinite(median_depth) else "unavailable", + "annotation_state": annotation_state, + }) + + selected_indices = balanced_stratified_indices(clip_records, args.count, seed=args.seed) + selected_set = set(selected_indices) + selected_records = [record for record in clip_records if int(record["clip_index"]) in selected_set] + take_counts = Counter(str(record["take"]) for record in selected_records) + stratum_counts = Counter( + (str(record["hand_size_bucket"]), str(record["depth_bucket"]), str(record["annotation_state"])) + for record in selected_records + ) + manifest = { + "version": "phase3_stratified_256_v1", + "seed": args.seed, + "count": len(selected_indices), + "source_manifest": str(args.source_manifest.resolve()), + "source_manifest_sha256": sha256(args.source_manifest), + "source_clip_count": len(clip_records), + "dataset_contract": {"resolution_hw": [288, 512], "T": 8, "stride": 1, "allow_partial": True}, + "selection_inputs": "take, GT-projected hand extent, wrist depth, annotation validity; model errors are excluded", + "selection_policy": "balanced take quotas plus deterministic round-robin within-take size/depth/valid strata", + "clip_indices": selected_indices, + "take_counts": dict(sorted(take_counts.items())), + "stratum_counts": {"/".join(key): value for key, value in sorted(stratum_counts.items())}, + "official_test_used": False, + } + manifest_path = args.output_dir / "validation_subset_256.json" + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + + csv_path = args.output_dir / "validation_subset_256.csv" + with csv_path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(selected_records[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(selected_records) + (args.output_dir / "validation_subset_256.sha256").write_text( + f"{sha256(manifest_path)} {manifest_path.name}\n{sha256(csv_path)} {csv_path.name}\n", + encoding="utf-8", + ) + print(json.dumps({ + "status": "created", "count": len(selected_indices), "takes": len(take_counts), + "take_count_min": min(take_counts.values()), "take_count_max": max(take_counts.values()), + "manifest": str(manifest_path), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase4_balanced_sampler.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase4_balanced_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..da8852e7b9d01cedc7c28961a16d8b599e3a06a0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase4_balanced_sampler.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""Build a deterministic train-only geometry-balanced sampling manifest.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from collections import Counter +from pathlib import Path + +import numpy as np + +from foundation_hand.data import H2OCam4Dataset +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record +from foundation_hand.evaluation.phase4 import bimanual_asymmetry +from foundation_hand.geometry.camera import ( + intrinsics_from_h2o, + project_points, + resize_and_pad_intrinsics, +) + + +AXES = ( + "left_size_bucket", + "right_size_bucket", + "left_depth_bucket", + "right_depth_bucket", + "asymmetry_bucket", + "action_family", + "annotation_valid_state", +) +WEIGHT_MIN = 0.5 +WEIGHT_MAX = 3.0 +TAKE_FACTOR_MIN = 2.0 / 3.0 +TAKE_FACTOR_MAX = 1.5 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def fit_resize( + source_hw: tuple[int, int], target_hw: tuple[int, int], +) -> tuple[tuple[int, int], tuple[int, int]]: + source_h, source_w = source_hw + target_h, target_w = target_hw + scale = min(target_w / source_w, target_h / source_h) + resized = (max(1, round(source_h * scale)), max(1, round(source_w * scale))) + return resized, ((target_w - resized[1]) // 2, (target_h - resized[0]) // 2) + + +def size_bucket(value: float | None) -> str: + if value is None: + return "unavailable" + if value < 64.0: + return "small" + if value < 128.0: + return "medium" + return "large" + + +def depth_bucket(value: float | None) -> str: + if value is None: + return "unavailable" + if value < 0.5: + return "near" + if value < 0.8: + return "middle" + return "far" + + +def median_or_none(values: list[float]) -> float | None: + return float(np.median(values)) if values else None + + +def validity_state(valid_counts: list[int], frame_count: int) -> str: + frequent = [count / frame_count >= 0.5 for count in valid_counts] + if frequent == [True, True]: + return "both" + if frequent == [True, False]: + return "left_only" + if frequent == [False, True]: + return "right_only" + return "sparse" + + +def clip_geometry_record( + root: Path, + clip_index: int, + clip, + target_hw: tuple[int, int], + intrinsics_cache: dict[str, np.ndarray], +) -> dict[str, object]: + take_dir = root / clip.take + if clip.take not in intrinsics_cache: + K_raw, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + resized_hw, pad_left_top = fit_resize(source_hw, target_hw) + intrinsics_cache[clip.take] = resize_and_pad_intrinsics( + K_raw, source_hw, resized_hw, pad_left_top, + ) + K = intrinsics_cache[clip.take] + sizes: list[list[float]] = [[], []] + depths: list[list[float]] = [[], []] + valid_counts = [0, 0] + ratios: list[float] = [] + gaps: list[float] = [] + for frame_id in clip.frame_ids: + joints = load_joint_record(take_dir / "hand_pose" / f"{frame_id:06d}.txt") + joints_2d, positive = project_points(joints.joints_camera_m, K) + frame_sizes: list[float | None] = [None, None] + frame_depths: list[float | None] = [None, None] + for hand in range(2): + if not bool(joints.annotation_valid[hand]) or not bool(positive[hand].all()): + continue + extent = joints_2d[hand].max(axis=0) - joints_2d[hand].min(axis=0) + size = float(extent.max()) + depth = float(joints.joints_camera_m[hand, 0, 2]) + sizes[hand].append(size) + depths[hand].append(depth) + valid_counts[hand] += 1 + frame_sizes[hand] = size + frame_depths[hand] = depth + asymmetry = bimanual_asymmetry(frame_sizes, frame_depths) + if asymmetry["bimanual_size_ratio"] is not None: + ratios.append(float(asymmetry["bimanual_size_ratio"])) + gaps.append(float(asymmetry["bimanual_depth_gap_m"])) + median_sizes = [median_or_none(values) for values in sizes] + median_depths = [median_or_none(values) for values in depths] + aggregate_asymmetry = bimanual_asymmetry(median_sizes, median_depths) + parts = Path(clip.take).parts + return { + "clip_index": clip_index, + "take": clip.take, + "frame_count": len(clip.frame_ids), + "action_family": parts[1], + "annotation_valid_state": validity_state(valid_counts, len(clip.frame_ids)), + "left_valid_fraction": valid_counts[0] / len(clip.frame_ids), + "right_valid_fraction": valid_counts[1] / len(clip.frame_ids), + "left_hand_size_px": median_sizes[0], + "right_hand_size_px": median_sizes[1], + "left_wrist_depth_m": median_depths[0], + "right_wrist_depth_m": median_depths[1], + "median_size_ratio": median_or_none(ratios), + "median_depth_gap_m": median_or_none(gaps), + "left_size_bucket": size_bucket(median_sizes[0]), + "right_size_bucket": size_bucket(median_sizes[1]), + "left_depth_bucket": depth_bucket(median_depths[0]), + "right_depth_bucket": depth_bucket(median_depths[1]), + "asymmetry_bucket": aggregate_asymmetry["bimanual_asymmetry_bucket"] or "unavailable", + } + + +def assign_weights(records: list[dict[str, object]]) -> dict[str, object]: + if not records: + raise ValueError("cannot balance an empty clip set") + frequencies = { + axis: Counter(str(record[axis]) for record in records) for axis in AXES + } + take_counts = Counter(str(record["take"]) for record in records) + median_take_count = float(np.median(list(take_counts.values()))) + raw_weights = [] + for record in records: + marginal = [] + for axis in AXES: + counts = frequencies[axis] + count = counts[str(record[axis])] + marginal.append(math.sqrt(len(records) / (len(counts) * count))) + geometry_factor = float(np.mean(marginal)) + take_factor = math.sqrt(median_take_count / take_counts[str(record["take"])]) + take_factor = float(np.clip(take_factor, TAKE_FACTOR_MIN, TAKE_FACTOR_MAX)) + raw_weights.append(geometry_factor * take_factor) + record["geometry_rarity_factor"] = geometry_factor + record["take_frequency_factor"] = take_factor + scale = float(np.mean(raw_weights)) + weights = np.clip(np.asarray(raw_weights) / scale, WEIGHT_MIN, WEIGHT_MAX) + for record, weight in zip(records, weights, strict=True): + record["weight"] = float(weight) + return { + "axis_frequencies": { + axis: dict(sorted(counts.items())) for axis, counts in frequencies.items() + }, + "take_clip_count_min": min(take_counts.values()), + "take_clip_count_median": median_take_count, + "take_clip_count_max": max(take_counts.values()), + "weight_min": float(weights.min()), + "weight_mean": float(weights.mean()), + "weight_max": float(weights.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--expected-manifest-sha256", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--resolution-hw", type=int, nargs=2, default=(368, 640)) + parser.add_argument("--T", type=int, default=8) + parser.add_argument("--stride", type=int, default=1) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args() + if "test" in args.manifest.name.lower() or "val" in args.manifest.name.lower(): + raise ValueError("balanced sampler builder accepts official train only") + manifest_hash = sha256(args.manifest) + if manifest_hash != args.expected_manifest_sha256: + raise ValueError("official-train manifest hash mismatch") + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite {args.output}") + target_hw = tuple(args.resolution_hw) + dataset = H2OCam4Dataset( + args.root, args.manifest, target_hw, (args.T,), (args.stride,), + max_clips=args.max_clips, + ) + cache: dict[str, np.ndarray] = {} + records = [] + for clip_index, clip in enumerate(dataset.clips): + records.append(clip_geometry_record( + args.root, clip_index, clip, target_hw, cache, + )) + if (clip_index + 1) % 500 == 0: + print(f"clips={clip_index + 1}/{len(dataset)}", flush=True) + summary = assign_weights(records) + output = { + "version": "phase4_train_geometry_balanced_v1", + "phase": 4, + "wave": "B2", + "split_role": "official_train", + "official_test_used": False, + "source_manifest": str(args.manifest.resolve()), + "source_manifest_sha256": manifest_hash, + "dataset_contract": { + "resolution_hw": list(target_hw), "T": args.T, "stride": args.stride, + "allow_partial": True, + }, + "clip_count": len(records), + "policy": { + "axes": list(AXES), + "marginal_weight": "inverse square root of train-only clip frequency", + "combination": "mean marginal rarity multiplied by capped take-frequency correction", + "weight_cap": [WEIGHT_MIN, WEIGHT_MAX], + "take_factor_cap": [TAKE_FACTOR_MIN, TAKE_FACTOR_MAX], + "draws": "dataset_size draws with replacement per seed+epoch", + "validation_identity_used": False, + }, + "summary": summary, + "clips": records, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": "complete", "clips": len(records), **summary}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase4_checkpoint_index.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase4_checkpoint_index.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c866726979ff9b6154bd9fcd36293264747a33 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase4_checkpoint_index.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Build a deterministic index of Phase 4 official-validation checkpoints.""" + +from __future__ import annotations + +import argparse +import json +import os +import re +from pathlib import Path +from typing import Any + + +SHA256 = re.compile(r"[0-9a-f]{64}") +OFFICIAL_VALIDATION_CLIPS = 1495 +OFFICIAL_VALIDATION_FRAMES = 11638 + + +def evaluation_reports(root: Path) -> list[Path]: + """Find reports through SSD-backed artifact symlinks without following cycles.""" + reports = [] + visited_directories: set[Path] = set() + for directory, names, files in os.walk(root, followlinks=True): + directory_path = Path(directory) + resolved_directory = directory_path.resolve() + if resolved_directory in visited_directories: + names.clear() + continue + visited_directories.add(resolved_directory) + names[:] = sorted( + name for name in names + if (directory_path / name).resolve() not in visited_directories + ) + if "evaluation.json" in files: + reports.append(directory_path / "evaluation.json") + return sorted(reports) + + +def logical_location(root: Path, report_path: Path) -> tuple[str, str, str]: + parts = report_path.relative_to(root).parts + if "full_validation" in parts: + index = parts.index("full_validation") + if len(parts) <= index + 3: + raise ValueError(f"invalid full-validation path: {report_path}") + condition = "/".join(parts[:index]) + return condition, parts[index + 1], parts[index + 2] + if len(parts) < 2: + raise ValueError(f"invalid evaluation path: {report_path}") + return parts[0], report_path.parent.name, "reference" + + +def build_index(root: Path) -> dict[str, Any]: + root = root.resolve() + records = [] + for report_path in evaluation_reports(root): + report = json.loads(report_path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("split_role") != "official_validation": + continue + if report.get("official_test_used") is not False: + raise ValueError(f"official-validation report lacks test isolation: {report_path}") + # Real-checkpoint smokes use the validation split but are not complete + # evaluations and must not enter the formal checkpoint index. + if ( + report.get("clips") != OFFICIAL_VALIDATION_CLIPS + or report.get("frames") != OFFICIAL_VALIDATION_FRAMES + ): + continue + checkpoint = report.get("checkpoint") + if not isinstance(checkpoint, dict): + raise ValueError(f"missing checkpoint record: {report_path}") + sha256 = checkpoint.get("sha256") + if not isinstance(sha256, str) or SHA256.fullmatch(sha256) is None: + raise ValueError(f"invalid checkpoint SHA256: {report_path}") + checkpoint_path = Path(str(checkpoint.get("path", ""))) + if not checkpoint_path.is_file(): + raise FileNotFoundError(f"indexed checkpoint is missing: {checkpoint_path}") + step = checkpoint.get("step") + if not isinstance(step, int) or step < 0: + raise ValueError(f"invalid checkpoint step: {report_path}") + condition, run, role = logical_location(root, report_path) + config = report.get("config", {}) + records.append({ + "condition": condition, + "run": run, + "role": role, + "config": config.get("name"), + "seed": config.get("seed"), + "checkpoint_path": str(checkpoint_path.resolve()), + "checkpoint_sha256": sha256, + "checkpoint_step": step, + "evaluation_path": str(report_path.resolve()), + "clips": report.get("clips"), + "frames": report.get("frames"), + }) + if not records: + raise ValueError(f"no official-validation evaluations found under {root}") + unique_checkpoints = { + (record["checkpoint_path"], record["checkpoint_sha256"]) + for record in records + } + return { + "status": "indexed", + "official_test_used": False, + "evaluations": len(records), + "unique_checkpoints": len(unique_checkpoints), + "records": records, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--phase4-root", type=Path, default=Path("artifacts/phase4"), + ) + parser.add_argument( + "--output", type=Path, + default=Path("artifacts/phase4/reports/checkpoints.json"), + ) + args = parser.parse_args() + payload = build_index(args.phase4_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": payload["status"], + "evaluations": payload["evaluations"], + "unique_checkpoints": payload["unique_checkpoints"], + "output": str(args.output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase5_group_folds.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase5_group_folds.py new file mode 100644 index 0000000000000000000000000000000000000000..996077ed4feed509db4ffefe17c0a09ae4f40367 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase5_group_folds.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Build deterministic subject-held-out OOF manifests from official train only.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None: + with path.open("w", encoding="utf-8") as handle: + for record in records: + handle.write(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n") + + +def record_id(record: dict[str, Any]) -> tuple[str, int]: + return str(record["take"]), int(record["run_index"]) + + +def subject(record: dict[str, Any]) -> str: + return str(record["take"]).split("/", 1)[0] + + +def fold_summary(records: list[dict[str, Any]]) -> dict[str, Any]: + return { + "records": len(records), + "frames": sum(len(record["frame_ids"]) for record in records), + "takes": len({str(record["take"]) for record in records}), + "subjects": sorted({subject(record) for record in records}), + "action_families": sorted({str(record["take"]).split("/")[1] for record in records}), + } + + +def build_subject_folds(source_manifest: Path, output_root: Path) -> dict[str, Any]: + records = [ + json.loads(line) + for line in source_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not records: + raise ValueError("source manifest is empty") + ids = [record_id(record) for record in records] + if len(ids) != len(set(ids)): + raise ValueError("source manifest contains duplicate take/run records") + for record in records: + if not record.get("frame_ids"): + raise ValueError(f"record has no frames: {record_id(record)}") + + by_subject: dict[str, list[dict[str, Any]]] = defaultdict(list) + for record in records: + by_subject[subject(record)].append(record) + subjects = sorted(by_subject) + if len(subjects) < 2: + raise ValueError("subject-held-out OOF requires at least two subjects") + + output_root.mkdir(parents=True, exist_ok=True) + folds = [] + heldout_ids: set[tuple[str, int]] = set() + for fold_index, heldout_subject in enumerate(subjects): + fold_dir = output_root / f"fold_{fold_index}_{heldout_subject}" + fold_dir.mkdir(parents=True, exist_ok=True) + heldout = sorted(by_subject[heldout_subject], key=record_id) + train = sorted( + (record for record in records if subject(record) != heldout_subject), + key=record_id, + ) + train_path = fold_dir / "train.jsonl" + heldout_path = fold_dir / "heldout.jsonl" + write_jsonl(train_path, train) + write_jsonl(heldout_path, heldout) + + train_takes = {str(record["take"]) for record in train} + heldout_takes = {str(record["take"]) for record in heldout} + train_subjects = {subject(record) for record in train} + heldout_subjects = {subject(record) for record in heldout} + leakage_free = not (train_takes & heldout_takes) and not ( + train_subjects & heldout_subjects + ) + if not leakage_free: + raise RuntimeError(f"group leakage detected in fold {fold_index}") + current_ids = {record_id(record) for record in heldout} + if heldout_ids & current_ids: + raise RuntimeError("a source record appears in more than one heldout fold") + heldout_ids.update(current_ids) + folds.append({ + "fold": fold_index, + "heldout_subject": heldout_subject, + "train_manifest": str(train_path.relative_to(output_root)), + "train_manifest_sha256": sha256(train_path), + "heldout_manifest": str(heldout_path.relative_to(output_root)), + "heldout_manifest_sha256": sha256(heldout_path), + "train": fold_summary(train), + "heldout": fold_summary(heldout), + "leakage_audit": { + "take_overlap": [], + "subject_overlap": [], + "passed": True, + }, + }) + + if heldout_ids != set(ids): + raise RuntimeError("heldout folds do not form an exact partition of official train") + report = { + "version": "phase5_subject_oof_v1", + "status": "frozen", + "source_role": "official_train", + "source_manifest": str(source_manifest.resolve()), + "source_manifest_sha256": sha256(source_manifest), + "assignment": "one complete official-train subject per heldout fold", + "group_unit": "subject; take/recording is indivisible", + "folds": folds, + "source": fold_summary(records), + "coverage_audit": { + "heldout_records": len(heldout_ids), + "source_records": len(records), + "exact_partition": True, + }, + "official_validation_used_for_assignment": False, + "official_test_used": False, + } + (output_root / "folds.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + args = parser.parse_args() + report = build_subject_folds(args.source_manifest, args.output_root) + print(json.dumps({ + "status": report["status"], + "version": report["version"], + "folds": len(report["folds"]), + "source": report["source"], + "official_test_used": report["official_test_used"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase5_missing_alignment_package.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase5_missing_alignment_package.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9247dc5bb746e3387abd07ad37a634e36ece53 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase5_missing_alignment_package.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Build an exact zero-alignment package for true missing-input causal audits.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def validate_cache( + manifest: dict[str, Any], expected_condition: str, expected_scope: str, +) -> None: + if ( + manifest.get("status") != "complete" + or manifest.get("scope") != expected_scope + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + or manifest.get("input_condition") != expected_condition + ): + raise ValueError("invalid true missing-input cache contract") + if expected_scope == "full" and ( + manifest.get("clips") != 1495 or manifest.get("frames") != 11638 + ): + raise ValueError("invalid full-cache coverage") + + +def fallback_prediction(arrays: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + frame_id = arrays["frame_id"] + translation = arrays["pred_wrist_translation"] + if frame_id.ndim != 1 or translation.shape[:2] != (len(frame_id), 2): + raise ValueError("invalid cache take dimensions") + shape = (len(frame_id), 2) + zeros = np.zeros(shape, dtype=np.float32) + return { + "frame_id": frame_id.astype(np.int64, copy=False), + "calibrated_delta_z_m": zeros, + "alignment_applied": np.zeros(shape, dtype=bool), + "confidence": zeros.copy(), + "inlier_ratio": zeros.copy(), + "residual_scale_m": zeros.copy(), + "valid_fraction": zeros.copy(), + "quality": zeros.copy(), + } + + +def build_package( + cache_dir: Path, + output_dir: Path, + expected_condition: str, + expected_scope: str, +) -> dict[str, Any]: + if output_dir.exists() and any(output_dir.iterdir()): + raise FileExistsError("fallback alignment output must be new or empty") + manifest_path = cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + validate_cache(manifest, expected_condition, expected_scope) + output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = output_dir / "predictions" + prediction_root.mkdir() + records = [] + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"cache take hash mismatch: {take_path}") + arrays = load_npz(take_path) + stem = "__".join(Path(str(arrays["take"])).parts) + prediction_path = prediction_root / f"{stem}.npz" + np.savez_compressed(prediction_path, **fallback_prediction(arrays)) + records.append({ + "take": str(arrays["take"]), + "path": str(prediction_path.resolve()), + "sha256": sha256(prediction_path), + }) + report = { + "status": "evaluated", + "experiment_class": "preregistered_missing_input_causal_diagnostic", + "result_role": "exact_zero_alignment_max_uncertainty_input_package", + "input_condition": expected_condition, + "scope": expected_scope, + "cache_manifest": { + "path": str(manifest_path.resolve()), + "sha256": sha256(manifest_path), + }, + "coarse_checkpoint": manifest["checkpoint"], + "alignment_contract": ( + "alignment_applied=false and delta-z=0 for every hand/frame; " + "causal uncertainty evaluator maps unavailable alignment to maximum noise" + ), + "takes": records, + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + } + (output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument( + "--expected-condition", choices=("missing_depth", "missing_k"), required=True, + ) + parser.add_argument("--scope", choices=("full", "smoke"), default="full") + args = parser.parse_args() + report = build_package( + args.cache_dir, args.output_dir, args.expected_condition, args.scope, + ) + print(json.dumps({ + "status": report["status"], + "condition": report["input_condition"], + "takes": len(report["takes"]), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase5_oof_bank.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase5_oof_bank.py new file mode 100644 index 0000000000000000000000000000000000000000..3199c0ded583d5c1ea631b3681edadbb755d4337 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase5_oof_bank.py @@ -0,0 +1,525 @@ +#!/usr/bin/env python3 +"""Build a resume-safe group-held-out coarse prediction bank for Phase 5.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.alignment_calibration import projected_hand_scale_px +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +BANK_VERSION = 2 +SIDES = ("left", "right") +FRAME_ARRAYS = ( + "clip_index", + "frame_id", + "frame_valid", + "K_resized", + "K_raw", + "rgb_available", + "depth_available", + "K_available", + "pred_rotation_matrices", + "pred_shape", + "pred_wrist_translation", + "pred_joints_camera", + "pred_vertices_camera", + "pred_direct_2d_px", + "pred_joints_raw_px", + "pred_vertices_raw_px", + "pred_surface_depth_m", + "observed_surface_depth_m", + "observed_surface_xyz_m", + "surface_visible", + "surface_sample_valid", + "surface_local_discontinuity_m", + "silhouette_packed", + "silhouette_overlap_fraction", + "predicted_depth_order", + "alignment_delta_z_m", + "alignment_applied", + "alignment_valid_support_count", + "alignment_projected_support_count", + "alignment_inlier_ratio", + "alignment_residual_scale_m", + "alignment_valid_fraction", + "alignment_foreground_fraction", + "alignment_background_fraction", + "alignment_depth_discontinuity_m", + "alignment_conditioning_quality", + "coarse_direct_mano_consistency_px", + "coarse_hand_scale_px", + "coarse_wrist_velocity_m_per_frame", + "target_rotation_matrices", + "target_pose_axis_angle", + "target_shape", + "target_wrist_translation", + "target_joints_camera", + "target_vertices_camera", + "target_2d_px", + "translation_residual_m", + "joint_annotation_valid", + "joint_element_valid", + "mano_annotation_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def take_slug(take: str) -> str: + parts = Path(take).parts + if len(parts) != 4 or parts[-1] != "cam4": + raise ValueError(f"unexpected H2O take: {take}") + return "__".join(parts) + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def resolve_fold_contract( + folds_manifest: Path, + fold_index: int, + heldout_manifest: Path, + run_provenance: Path, +) -> dict[str, Any]: + folds = json.loads(folds_manifest.read_text(encoding="utf-8")) + if ( + folds.get("version") != "phase5_subject_oof_v1" + or folds.get("status") != "frozen" + or folds.get("source_role") != "official_train" + or folds.get("official_test_used") is not False + ): + raise ValueError("invalid or unfrozen Phase 5 OOF manifest") + matches = [record for record in folds["folds"] if int(record["fold"]) == fold_index] + if len(matches) != 1: + raise ValueError(f"fold {fold_index} is not uniquely registered") + fold = matches[0] + registered_heldout = folds_manifest.parent / fold["heldout_manifest"] + if heldout_manifest.resolve() != registered_heldout.resolve(): + raise ValueError("heldout manifest path differs from registered fold") + if sha256(heldout_manifest) != fold["heldout_manifest_sha256"]: + raise ValueError("heldout manifest hash differs from registered fold") + provenance = json.loads(run_provenance.read_text(encoding="utf-8")) + train_hash = provenance.get("hashes", {}).get("train_manifest", {}).get("sha256") + if train_hash != fold["train_manifest_sha256"]: + raise ValueError("checkpoint training manifest is not the registered fold train split") + if provenance.get("git_status") not in ("", None): + raise ValueError("OOF bank requires a checkpoint trained from a clean worktree") + return {"folds": folds, "fold": fold, "provenance": provenance} + + +def validate_checkpoint_provenance( + checkpoint: dict[str, Any], + *, + config: dict[str, Any], + config_path: Path, + run_provenance_path: Path, + provenance: dict[str, Any], +) -> None: + """Bind the extraction checkpoint to its clean training run and config.""" + + extra = checkpoint.get("extra", {}) + provenance_config_hash = provenance.get("hashes", {}).get("config", {}).get("sha256") + if provenance_config_hash != sha256(config_path): + raise ValueError("extraction config hash differs from checkpoint run provenance") + if provenance.get("config") != config or extra.get("config") != config: + raise ValueError("extraction config differs from checkpoint embedded config") + if extra.get("git_commit") != provenance.get("git_commit"): + raise ValueError("checkpoint git commit differs from run provenance") + if extra.get("run_provenance_sha256") != sha256(run_provenance_path): + raise ValueError("checkpoint run provenance hash mismatch") + protocol = config.get("protocol", {}) + if extra.get("checkpoint_role") != "final" or int(checkpoint.get("step", -1)) != int( + protocol.get("max_steps", -2) + ): + raise ValueError("OOF bank requires the preregistered fixed-final checkpoint") + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def target_geometry( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + pose_axis_angle = batch["mano_pose"].reshape(*batch["mano_pose"].shape[:-1], 16, 3) + rotations = axis_angle_to_matrix(torch.nan_to_num(pose_axis_angle)) + with torch.no_grad(): + vertices, joints = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = batch["mano_annotation_valid"].bool()[..., None, None] + vertices = torch.where(valid, vertices, torch.full_like(vertices, torch.nan)) + joints = torch.where(valid, joints, torch.full_like(joints, torch.nan)) + return pose_axis_angle, rotations, vertices, joints + + +def _observed_xyz( + pixels: np.ndarray, observed_depth_m: np.ndarray, K: np.ndarray, +) -> np.ndarray: + z = observed_depth_m.astype(np.float32) + xyz = np.full((*z.shape, 3), np.nan, dtype=np.float32) + valid = np.isfinite(z) & (z > 0.0) & np.isfinite(pixels).all(axis=-1) + xyz[..., 2][valid] = z[valid] + xyz[..., 0][valid] = (pixels[..., 0][valid] - K[0, 2]) * z[valid] / K[0, 0] + xyz[..., 1][valid] = (pixels[..., 1][valid] - K[1, 2]) * z[valid] / K[1, 1] + return xyz + + +def _velocity(translation: np.ndarray, frame_ids: np.ndarray) -> np.ndarray: + output = np.zeros_like(translation, dtype=np.float32) + contiguous = frame_ids[1:] == frame_ids[:-1] + 1 + output[1:][contiguous] = translation[1:][contiguous] - translation[:-1][contiguous] + return output + + +def infer_take( + *, + root: Path, + take: str, + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + loader = DataLoader( + Subset(dataset, clip_indices), batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + take_dir = root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + silhouette_hw: tuple[int, int] | None = None + for global_clip_index, batch_cpu in zip(clip_indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + target_pose, target_rotations, target_vertices, target_joints = target_geometry(batch, model) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + valid_times = int(batch["frame_valid"][0].sum()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor( + (width, height), device=device, + ) + pred_vertices = prediction["vertices_camera"][0, :valid_times].float().cpu().numpy() + pred_joints = prediction["joints_camera"][0, :valid_times].float().cpu().numpy() + frame_ids = batch["frame_id"][0, :valid_times].cpu().numpy().astype(np.int64) + surface_fields: dict[str, list[np.ndarray]] = defaultdict(list) + for time_index, frame_id in enumerate(frame_ids): + stem = f"{int(frame_id):06d}" + raw_depth_mm = cv2.imread(str(take_dir / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED) + if raw_depth_mm is None or raw_depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{stem}") + raw_depth_m, raw_depth_valid = depth_mm_to_m(raw_depth_mm) + packed_masks = [] + medians = [] + for hand in range(2): + diagnostics, samples = align_wrist_z( + pred_vertices[time_index, hand], K_raw, raw_depth_m, raw_depth_valid, + ) + if samples is None: + raise AssertionError("full-modality OOF extraction unexpectedly lacks surface samples") + if silhouette_hw is None: + silhouette_hw = samples.silhouette_hw + elif silhouette_hw != samples.silhouette_hw: + raise AssertionError("silhouette shape changed within OOF bank") + observed_xyz = _observed_xyz( + samples.projected_vertices_px, samples.observed_depth_m, K_raw, + ) + surface_fields["pred_vertices_raw_px"].append(samples.projected_vertices_px) + surface_fields["pred_surface_depth_m"].append(samples.predicted_depth_m) + surface_fields["observed_surface_depth_m"].append(samples.observed_depth_m) + surface_fields["observed_surface_xyz_m"].append(observed_xyz) + surface_fields["surface_visible"].append(samples.visible_vertex) + surface_fields["surface_sample_valid"].append(samples.sample_valid) + surface_fields["surface_local_discontinuity_m"].append(samples.local_discontinuity_m) + surface_fields["silhouette_packed"].append(samples.silhouette_packed) + for field, value in diagnostics.as_dict().items(): + surface_fields[f"alignment_{field}"].append(np.asarray(value)) + packed_masks.append(np.unpackbits( + samples.silhouette_packed, bitorder="little", + count=samples.silhouette_hw[0] * samples.silhouette_hw[1], + ).astype(bool)) + medians.append(float(np.median(samples.predicted_depth_m[samples.visible_vertex]))) + intersection = np.logical_and(packed_masks[0], packed_masks[1]).sum() + union = np.logical_or(packed_masks[0], packed_masks[1]).sum() + surface_fields["silhouette_overlap_fraction"].append( + np.asarray(intersection / max(union, 1), dtype=np.float32) + ) + surface_fields["predicted_depth_order"].append( + np.asarray(np.sign(medians[1] - medians[0]), dtype=np.int8) + ) + + mano_2d_raw, _ = project_points(pred_joints, K_raw) + direct_np = direct_2d[0, :valid_times].cpu().numpy() + raw_to_resized = np.asarray( + (width / raw_hw[1], height / raw_hw[0]), dtype=np.float32, + ) + consistency = np.linalg.norm( + direct_np - mano_2d_raw * raw_to_resized, axis=-1, + ).mean(axis=-1) + hand_scale = projected_hand_scale_px( + mano_2d_raw, source_hw=raw_hw, target_hw=(height, width), + ) + values: dict[str, np.ndarray] = { + "clip_index": np.full(valid_times, global_clip_index, dtype=np.int64), + "frame_id": frame_ids, + "frame_valid": batch["frame_valid"][0, :valid_times].cpu().numpy(), + "K_resized": batch["K"][0, :valid_times].float().cpu().numpy(), + "K_raw": np.broadcast_to(K_raw, (valid_times, 3, 3)).copy(), + "rgb_available": batch["frame_valid"][0, :valid_times].cpu().numpy(), + "depth_available": batch["depth_available"][0, :valid_times].cpu().numpy(), + "K_available": batch["K_available"][0, :valid_times].cpu().numpy(), + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0, :valid_times].float().cpu().numpy(), + "pred_shape": prediction["mano_shape"][0, :valid_times].float().cpu().numpy(), + "pred_wrist_translation": prediction["wrist_root_translation"][0, :valid_times].float().cpu().numpy(), + "pred_joints_camera": pred_joints, + "pred_vertices_camera": pred_vertices, + "pred_direct_2d_px": direct_np, + "pred_joints_raw_px": mano_2d_raw.astype(np.float32), + "coarse_direct_mano_consistency_px": consistency.astype(np.float32), + "coarse_hand_scale_px": hand_scale.astype(np.float32), + "target_rotation_matrices": target_rotations[0, :valid_times].float().cpu().numpy(), + "target_pose_axis_angle": target_pose[0, :valid_times].float().cpu().numpy(), + "target_shape": batch["mano_shape"][0, :valid_times].float().cpu().numpy(), + "target_wrist_translation": batch["wrist_root_translation"][0, :valid_times].float().cpu().numpy(), + "target_joints_camera": target_joints[0, :valid_times].float().cpu().numpy(), + "target_vertices_camera": target_vertices[0, :valid_times].float().cpu().numpy(), + "target_2d_px": batch["joint2d"][0, :valid_times].float().cpu().numpy(), + "joint_annotation_valid": batch["joint_annotation_valid"][0, :valid_times].cpu().numpy(), + "joint_element_valid": batch["joint_element_valid"][0, :valid_times].cpu().numpy(), + "mano_annotation_valid": batch["mano_annotation_valid"][0, :valid_times].cpu().numpy(), + } + values["translation_residual_m"] = ( + values["target_wrist_translation"] - values["pred_wrist_translation"] + ) + for key, hand_values in surface_fields.items(): + stacked = np.stack(hand_values) + if key not in ("silhouette_overlap_fraction", "predicted_depth_order"): + stacked = stacked.reshape(valid_times, 2, *stacked.shape[1:]) + values[key] = stacked + for key, value in values.items(): + chunks[key].append(value) + + arrays = {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + arrays["coarse_wrist_velocity_m_per_frame"] = _velocity( + arrays["pred_wrist_translation"], arrays["frame_id"], + ) + arrays["silhouette_hw"] = np.asarray(silhouette_hw, dtype=np.int32) + return arrays + + +def validate_bank_arrays( + arrays: dict[str, np.ndarray], + *, + take: str, + expected_frame_ids: list[int], + checkpoint_sha256: str, + config_sha256: str, + heldout_manifest_sha256: str, + fold_index: int, +) -> None: + missing = sorted(set(FRAME_ARRAYS) - arrays.keys()) + if missing: + raise ValueError(f"OOF bank is missing arrays: {missing}") + scalars = { + "bank_version": BANK_VERSION, + "take": take, + "checkpoint_sha256": checkpoint_sha256, + "config_sha256": config_sha256, + "heldout_manifest_sha256": heldout_manifest_sha256, + "fold_index": fold_index, + } + for key, expected in scalars.items(): + if str(arrays[key]) != str(expected): + raise ValueError(f"OOF bank scalar mismatch: {key}") + frame_ids = arrays["frame_id"].astype(np.int64).tolist() + if frame_ids != expected_frame_ids or len(frame_ids) != len(set(frame_ids)): + raise ValueError(f"OOF bank frame sequence mismatch for {take}") + for key in FRAME_ARRAYS: + if arrays[key].shape[0] != len(frame_ids): + raise ValueError(f"OOF bank time dimension mismatch: {key}") + if np.issubdtype(arrays[key].dtype, np.floating) and key.startswith("pred_"): + if not np.isfinite(arrays[key]).all(): + raise ValueError(f"non-finite coarse prediction array: {key}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--run-provenance", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--folds-manifest", type=Path, required=True) + parser.add_argument("--fold", type=int, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args() + if "test" in str(args.manifest).lower() or "val" in args.manifest.name.lower(): + parser.error("OOF bank accepts only registered official-train heldout manifests") + contract = resolve_fold_contract( + args.folds_manifest, args.fold, args.manifest, args.run_provenance, + ) + checkpoint_hash = sha256(args.checkpoint) + if checkpoint_hash != args.expected_checkpoint_sha256: + parser.error("checkpoint hash differs from the registered extraction command") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + config_hash = sha256(args.config) + heldout_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (int(config["data"]["T"]),), (int(config["data"]["stride"]),), + max_clips=args.max_clips, + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + expected_frames = { + take: [frame for index in indices for frame in dataset.clips[index].frame_ids] + for take, indices in indices_by_take.items() + } + if any(len(frames) != len(set(frames)) for frames in expected_frames.values()): + raise ValueError("OOF bank requires non-overlapping heldout inference clips") + + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + validate_checkpoint_provenance( + checkpoint, + config=config, + config_path=args.config, + run_provenance_path=args.run_provenance, + provenance=contract["provenance"], + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + records = [] + for take_index, (take, clip_indices) in enumerate(indices_by_take.items(), start=1): + output = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "heldout_manifest_sha256": heldout_hash, + "fold_index": args.fold, + } + if output.exists(): + with np.load(output, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + validate_bank_arrays(arrays, **expected) + status = "reused" + else: + arrays = infer_take( + root=args.root, take=take, dataset=dataset, clip_indices=clip_indices, + model=model, device=device, dtype=dtype, + ) + arrays.update({ + "bank_version": np.asarray(BANK_VERSION, dtype=np.int32), + "take": np.asarray(take), + "subject": np.asarray(take.split("/")[0]), + "action_family": np.asarray(take.split("/")[1]), + "side_names": np.asarray(SIDES), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "heldout_manifest_sha256": np.asarray(heldout_hash), + "fold_index": np.asarray(args.fold, dtype=np.int32), + }) + validate_bank_arrays(arrays, **expected) + save_npz_atomic(output, arrays) + status = "written" + records.append({ + "take": take, "clips": len(clip_indices), "frames": len(expected_frames[take]), + "path": str(output.resolve()), "sha256": sha256(output), "status": status, + }) + print(f"[{take_index}/{len(indices_by_take)}] {take}: {status}", flush=True) + + total_frames = sum(record["frames"] for record in records) + full_fold = args.max_clips is None + if full_fold and total_frames != int(contract["fold"]["heldout"]["frames"]): + raise ValueError("OOF bank heldout frame coverage differs from frozen fold") + report = { + "status": "complete", + "bank_version": BANK_VERSION, + "result_role": "official_train_group_heldout_oof_predictions", + "experiment_class": "preregistered_data_construction", + "official_validation_used_for_assignment": False, + "official_test_used": False, + "oracle_information_at_inference": False, + "gt_usage": "bank targets and post-hoc residual audit only", + "fold": args.fold, + "seed": int(config["seed"]), + "heldout_subject": contract["fold"]["heldout_subject"], + "folds_manifest": {"path": str(args.folds_manifest.resolve()), "sha256": sha256(args.folds_manifest)}, + "train_manifest_sha256": contract["fold"]["train_manifest_sha256"], + "heldout_manifest": {"path": str(args.manifest.resolve()), "sha256": heldout_hash}, + "leakage_audit": contract["fold"]["leakage_audit"], + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, "step": int(checkpoint["step"])}, + "run_provenance": {"path": str(args.run_provenance.resolve()), "sha256": sha256(args.run_provenance)}, + "training_git_commit": contract["provenance"]["git_commit"], + "extractor_git_commit": subprocess.run(["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, check=False).stdout.strip(), + "scope": "full_fold" if full_fold else "smoke", + "clips": len(dataset), "frames": total_frames, "takes": records, + "surface_contract": { + "location": "coarse MANO projection only", + "depth_source": "original aligned H2O metric depth", + "surface": "frontmost projected MANO vertex per 4-pixel cell", + "silhouette": "packed quarter-resolution conservative projected vertex hull", + "solver": "bounded MAD-scaled Huber IRLS; translation-z only", + "hand_scale": "projected coarse MANO joint extent in model-resized pixels", + }, + "arrays": list(FRAME_ARRAYS), + } + (args.output_dir / "bank_manifest.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "fold": args.fold, "clips": report["clips"], + "frames": report["frames"], "takes": len(records), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_adaptation_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_adaptation_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9e5cbc986e127ee1269792135884adc311eaa1 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_adaptation_configs.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Build matched A1/A2 configs after strict external zero-shot is complete.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +from pathlib import Path +from typing import Any + +import yaml + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_adaptation_inputs( + selection: dict[str, Any], zero_shot_state: dict[str, Any], split: dict[str, Any], +) -> None: + if ( + selection.get("status") != "selected_external_generalist_no_h2o" + or selection.get("h2o_training_data_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("external selection is not adaptation-eligible") + if ( + zero_shot_state.get("status") != "complete" + or set(zero_shot_state.get("completed_ids", [])) != { + "h2o_strict_zero_shot_rgb_d_k", "h2o_strict_zero_shot_rgb_k", + "h2o_strict_zero_shot_rgb_only", + } + or zero_shot_state.get("official_test_used") is not False + or zero_shot_state.get("h2o_training_data_used") is not False + ): + raise ValueError("strict three-mode H2O zero-shot must complete before adaptation") + if ( + split.get("status") != "frozen_h2o_train_group_split" + or split.get("h2o_official_validation_used") is not False + or split.get("official_test_used") is not False + or split.get("recording_overlap") != [] + ): + raise ValueError("H2O train-only group split is invalid") + + +def adaptation_config( + base: dict[str, Any], selection: dict[str, Any], split: dict[str, Any], branch: str, +) -> dict[str, Any]: + config = copy.deepcopy(base) + config["name"] = f"phase7_{branch.lower()}_scale100k_s20260717" + config["experiment"] = { + "phase": 7, "branch": "h2o_adaptation", "stage": "adaptation_scale_100k", + "condition": branch, "uses_h2o_training_data": True, + "initialization_checkpoint_sha256": selection["checkpoint"]["sha256"], + "initialization_checkpoint_step": selection["checkpoint"]["step"], + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + h2o_source = { + "dataset": "H2O", "split_role": "official_train", "weight": 1.0, + "cache_manifest": split["fit"]["path"], "K_input_dropout": 0.0, + } + if branch == "A1": + sources = [h2o_source] + elif branch == "A2": + source_lookup = { + str(source["dataset"]).upper(): copy.deepcopy(source) + for source in base["data"]["sources"] + } + if set(source_lookup) != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("winning external config is not the E40 three-source mixture") + h2o_source["weight"] = 0.5 + replay_weights = {"HOT3D": 0.2, "HOI4D": 0.2, "ARCTIC": 0.1} + sources = [h2o_source] + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + source = source_lookup[dataset] + source["weight"] = replay_weights[dataset] + source["split_role"] = "external_train" + sources.append(source) + else: + raise ValueError(f"unknown adaptation condition: {branch}") + config["data"]["sources"] = sources + config["data"]["validation_sources"] = [{ + "dataset": "H2O", "split_role": "train_group_heldout", + "cache_manifest": split["heldout"]["path"], "K_input_dropout": 0.0, + }] + config["model"]["modality_dropout_prob"] = 0.0 + config["model"]["dinov3_trainable_last_blocks"] = 0 + return config + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-selection", type=Path, required=True) + parser.add_argument("--zero-shot-state", type=Path, required=True) + parser.add_argument("--h2o-train-split", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + selection = json.loads(args.external_selection.read_text(encoding="utf-8")) + zero_shot = json.loads(args.zero_shot_state.read_text(encoding="utf-8")) + split = json.loads(args.h2o_train_split.read_text(encoding="utf-8")) + validate_adaptation_inputs(selection, zero_shot, split) + base_path = Path(selection["config"]["path"]) + if sha256(base_path) != selection["config"]["sha256"]: + parser.error("selected external config hash mismatch") + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + args.output_dir.mkdir(parents=True) + outputs = {} + for branch in ("A1", "A2"): + config = adaptation_config(base, selection, split, branch) + output = args.output_dir / f"phase7_{branch.lower()}_scale100k_s20260717.yaml" + output.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + outputs[branch] = {"path": str(output.resolve()), "sha256": sha256(output)} + record = { + "status": "adaptation_configs_frozen", "configs": outputs, + "external_selection": { + "path": str(args.external_selection.resolve()), "sha256": sha256(args.external_selection), + }, + "strict_zero_shot_state": { + "path": str(args.zero_shot_state.resolve()), "sha256": sha256(args.zero_shot_state), + }, + "h2o_train_split": { + "path": str(args.h2o_train_split.resolve()), "sha256": sha256(args.h2o_train_split), + }, + "h2o_official_validation_used_for_selection": False, "official_test_used": False, + } + (args.output_dir / "freeze.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_arctic_manifests.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_arctic_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..0dee727076139bcc1bfab8100719f0369d8ff69d --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_arctic_manifests.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Build ARCTIC P2 train/val manifests without reading the P2 test list.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_p2_train_val_without_test(path: Path) -> dict[str, list[str]]: + lines: list[str] = [] + saw_test_key = False + with path.open("r", encoding="utf-8") as handle: + for line in handle: + if line.lstrip().startswith('"test"'): + saw_test_key = True + break + lines.append(line) + if not saw_test_key: + raise ValueError("protocol does not contain a test boundary") + prefix = "".join(lines).rstrip() + if prefix.endswith(","): + prefix = prefix[:-1] + record = json.loads(prefix + "\n}\n") + if set(record) != {"train", "val"}: + raise ValueError(f"expected only train/val before test boundary, got {set(record)}") + return record + + +def sequence_rows( + data_root: Path, sequence: str, split: str, clip_length: int, window_step: int, +) -> tuple[list[dict[str, Any]], list[str]]: + subject, take = sequence.split("/", 1) + mano_path = data_root / "raw_seqs" / subject / f"{take}.mano.npy" + camera_path = data_root / "raw_seqs" / subject / f"{take}.egocam.dist.npy" + image_dir = data_root / "cropped_images" / subject / take / "0" + missing = [str(path) for path in (mano_path, camera_path, image_dir) if not path.exists()] + if missing: + return [], missing + mano = np.load(mano_path, allow_pickle=True).item() + frame_count = int(len(mano["right"]["rot"])) + if frame_count != int(len(mano["left"]["rot"])): + raise ValueError(f"left/right frame count differs for {sequence}") + images = sorted(image_dir.glob("*.jpg")) + if len(images) != frame_count: + return [], [f"{sequence}: image count {len(images)} != MANO frames {frame_count}"] + rows = [] + for first in range(1, frame_count - clip_length + 2, window_step): + frame_ids = list(range(first, first + clip_length)) + rows.append({ + "dataset_id": "ARCTIC", + "protocol": "P2", + "split_role": f"arctic_p2_{split}", + "subject_id": subject, + "physical_recording_id": sequence, + "group_key": f"ARCTIC/{subject}/{sequence}", + "camera_id": "ego_view_0_rectified", + "frame_ids_1based": frame_ids, + "array_indices_0based": [value - 1 for value in frame_ids], + "image_paths": [str((image_dir / f"{value:05d}.jpg").resolve()) for value in frame_ids], + "mano_path": str(mano_path.resolve()), + "camera_path": str(camera_path.resolve()), + "depth_input_available": False, + "official_test_used": False, + }) + return rows, [] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--protocol", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--window-step", type=int, default=8) + parser.add_argument("--allow-documented-missing-sequence-exclusions", action="store_true") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=False) + split = read_p2_train_val_without_test(args.protocol) + manifests = {} + missing: dict[str, list[str]] = {} + split_subjects: dict[str, set[str]] = {} + for role in ("train", "val"): + rows = [] + for sequence in split[role]: + sequence_values, absent = sequence_rows( + args.data_root, sequence, role, args.clip_length, args.window_step, + ) + rows.extend(sequence_values) + if absent: + missing[sequence] = absent + path = args.output_dir / f"arctic_p2_{role}_t{args.clip_length}.jsonl" + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + subjects = {row["subject_id"] for row in rows} + split_subjects[role] = subjects + manifests[role] = { + "path": str(path.resolve()), "sha256": sha256(path), + "clips": len(rows), "sequences": len({row["physical_recording_id"] for row in rows}), + "subjects": sorted(subjects), + } + overlap = sorted(split_subjects["train"] & split_subjects["val"]) + usable = not overlap and all(value["clips"] for value in manifests.values()) + status = ( + "passed" if usable and not missing else + "passed_with_documented_exclusions" + if usable and args.allow_documented_missing_sequence_exclusions else + "failed" + ) + report = { + "version": "phase7_arctic_p2_manifest_v1", + "status": status, + "protocol_path": str(args.protocol.resolve()), + "protocol_sha256": sha256(args.protocol), + "test_boundary_contract": "reader stops on the P2 test key before reading any test identity", + "clip_length": args.clip_length, "window_step": args.window_step, + "manifests": manifests, + "train_val_subject_overlap": overlap, + "missing_assets": missing, + "missing_sequence_policy": ( + "exclude entire physical recording from P2 train" + if args.allow_documented_missing_sequence_exclusions else "strict failure" + ), + "official_test_used": False, + } + (args.output_dir / "manifest_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not status.startswith("passed"): + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_continuation_manifest.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_continuation_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5feb4a5390224c6a49a11bd3846c9c91d88ea8 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_continuation_manifest.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Bind frozen 50k/100k external evaluations for final checkpoint selection.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from scripts.build_phase7_scale_eval_queue import input_mode + + +DATASETS = ("HOT3D", "HOI4D", "ARCTIC") + + +def build_manifest(evaluation_root: Path, condition: str, steps: tuple[int, ...]) -> dict: + evaluations = [] + for step in steps: + for dataset in DATASETS: + mode = input_mode(condition, dataset) + path = ( + evaluation_root + / f"{condition.lower()}_scale_step{step}_{dataset.lower()}_heldout2048_{mode}" + / "evaluation.json" + ).resolve() + if not path.is_file(): + raise ValueError(f"continuation evaluation missing: {path}") + report = json.loads(path.read_text(encoding="utf-8")) + if int(report.get("checkpoint_step", -1)) != step: + raise ValueError(f"continuation evaluation step mismatch: {path}") + evaluations.append({ + "candidate": f"{condition}_step{step}", "dataset": dataset, + "path": str(path), + }) + return { + "schema_version": "phase7_external_continuation_selection_v1", + "selection_split": "external_heldout_only", "datasets": list(DATASETS), + "condition": condition, "candidate_steps": list(steps), + "h2o_training_data_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--condition", default="E40", choices=("E40", "E70", "E100")) + parser.add_argument("--steps", type=int, nargs="+", default=(50000, 100000)) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + manifest = build_manifest(args.evaluation_root, args.condition, tuple(args.steps)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + print(json.dumps(manifest, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_h2o_zero_shot_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_h2o_zero_shot_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..75fc0a82c687ff6af3ff04114659af6756484fe7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_h2o_zero_shot_queue.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Build the hash-bound three-mode strict H2O zero-shot queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_h2o_zero_shot_queue import validate_queue + + +def build_queue(freeze_path: Path, root: Path, output_root: Path) -> dict: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + status = freeze.get("status") + if status not in { + "external_generalist_frozen", "external_architecture_candidate_frozen", + }: + raise ValueError("external freeze record is incomplete") + if status == "external_architecture_candidate_frozen" and ( + freeze.get("selected_within_family") is not True + or freeze.get("overall_external_generalist_winner") is not False + ): + raise ValueError("external architecture candidate role is ambiguous") + checkpoint = freeze["checkpoint_path"] + checkpoint_sha256 = freeze["checkpoint_sha256"] + manifest = freeze["h2o_validation_manifest"]["path"] + evaluations = [{ + "id": f"h2o_strict_zero_shot_{mode}", "input_mode": mode, + "config": freeze["config_path"], "checkpoint": checkpoint, + "checkpoint_sha256": checkpoint_sha256, + "freeze_record": str(freeze_path.resolve()), "root": str(root.resolve()), + "manifest": manifest, + "output_dir": str((output_root / mode).resolve()), + "bootstrap_resamples": 2000, + } for mode in INPUT_MODES] + queue = { + "schema_version": "phase7_h2o_strict_zero_shot_queue_v1", + "purpose": "One frozen external checkpoint evaluated once in three H2O input modes", + "external_freeze_status": status, + "allowed_physical_gpus": [0, 1, 2, 3], + "official_test_used": False, "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "evaluations": evaluations, + } + validate_queue(queue) + return queue + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + queue = build_queue(args.freeze_record, args.root, args.output_root) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_hoi4d_manifests.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_hoi4d_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebe2622b2f7c2957b904af4295816fe440fd0c9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_hoi4d_manifests.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Build deterministic group-isolated HOI4D train/held-out clip manifests.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +SERIALS = tuple(f"ZY2021080000{index}" for index in range(1, 5)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def discover_hand_frames(root: Path) -> dict[str, dict[int, set[str]]]: + recordings: dict[str, dict[int, set[str]]] = defaultdict(lambda: defaultdict(set)) + hand_root = root / "Hand_pose" + for side in ("left", "right"): + base = hand_root / f"handpose_{side}_hand" + for directory, _, filenames in os.walk(base): + frame_names = [name for name in filenames if name.endswith(".pickle")] + if not frame_names: + continue + relative = Path(directory).relative_to(base).as_posix() + for name in frame_names: + recordings[relative][int(Path(name).stem)].add(side) + return recordings + + +def split_for_serial(serial: str, heldout_serial: str) -> str: + if serial not in SERIALS: + raise ValueError(f"unknown HOI4D serial: {serial}") + return "heldout" if serial == heldout_serial else "train" + + +def recording_assets(root: Path, recording: str) -> tuple[Path, Path, Path]: + rgb = root / "HOI4D_release" / recording / "align_rgb" / "image.mp4" + depth = ( + root / "HOI4D_release" / "HOI4D_depth_video" / recording + / "align_depth" / "depth_video.avi" + ) + serial = recording.split("/", 1)[0] + K = root / "camera" / serial / "intrin.npy" + return rgb, depth, K + + +def make_rows( + root: Path, + recordings: dict[str, dict[int, set[str]]], + heldout_serial: str, + clip_length: int, + window_step: int, +) -> tuple[dict[str, list[dict[str, Any]]], list[dict[str, str]]]: + rows: dict[str, list[dict[str, Any]]] = {"train": [], "heldout": []} + missing: list[dict[str, str]] = [] + for recording in sorted(recordings): + rgb, depth, K = recording_assets(root, recording) + absent = [str(path) for path in (rgb, depth, K) if not path.is_file()] + if absent: + missing.append({"recording": recording, "missing": ";".join(absent)}) + continue + frames = recordings[recording] + available = sorted(frames) + if not available: + continue + serial, subject = recording.split("/")[:2] + split = split_for_serial(serial, heldout_serial) + frame_set = set(available) + for start in range(available[0], available[-1] + 1, window_step): + ids = list(range(start, start + clip_length)) + if not all(frame in frame_set for frame in ids): + continue + rows[split].append({ + "dataset_id": "HOI4D", + "split_role": f"external_{split}_group_split", + "serial_id": serial, + "subject_id": subject, + "physical_recording_id": recording, + "group_key": f"HOI4D/{subject}/{recording}", + "camera_id": serial, + "fps": 15.0, + "frame_ids": ids, + "timestamps_seconds": [frame / 15.0 for frame in ids], + "hand_sides": [sorted(frames[frame]) for frame in ids], + "rgb_video": str(rgb.resolve()), + "depth_video": str(depth.resolve()), + "K_path": str(K.resolve()), + "official_test_used": False, + }) + return rows, missing + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--heldout-serial", choices=SERIALS, default=SERIALS[-1]) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--window-step", type=int, default=8) + parser.add_argument("--allow-documented-missing-asset-exclusions", action="store_true") + args = parser.parse_args() + if args.clip_length <= 0 or args.window_step <= 0: + parser.error("clip length and window step must be positive") + args.output_dir.mkdir(parents=True, exist_ok=False) + recordings = discover_hand_frames(args.root) + rows, missing = make_rows( + args.root, recordings, args.heldout_serial, + args.clip_length, args.window_step, + ) + manifests = {} + for split, values in rows.items(): + path = args.output_dir / f"hoi4d_{split}_t{args.clip_length}.jsonl" + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in values), + encoding="utf-8", + ) + manifests[split] = { + "path": str(path.resolve()), "sha256": sha256(path), + "clips": len(values), + "subjects": sorted({row["subject_id"] for row in values}), + "recordings": len({row["physical_recording_id"] for row in values}), + "hand_frames": { + side: sum(side in sides for row in values for sides in row["hand_sides"]) + for side in ("left", "right") + }, + } + usable = all(rows.values()) + exclusions_allowed = bool(args.allow_documented_missing_asset_exclusions) + report = { + "version": "phase7_hoi4d_group_split_v1", + "status": ( + "passed" if usable and not missing else + "passed_with_documented_exclusions" if usable and exclusions_allowed else + "failed" + ), + "heldout_policy": "entire device/subject serial held out", + "heldout_serial": args.heldout_serial, + "grouping": "dataset, subject, complete physical recording", + "clip_length": args.clip_length, + "window_step": args.window_step, + "manifests": manifests, + "missing_assets": missing, + "missing_asset_recordings": len(missing), + "missing_asset_policy": ( + "excluded from both training and held-out evaluation; retained in audit" + if exclusions_allowed else "strict failure" + ), + "official_test_used": False, + } + (args.output_dir / "manifest_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if not report["status"].startswith("passed"): + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_hot3d_manifests.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_hot3d_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6baac33d76e1336f6bdc82c4a417627d8c123c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_hot3d_manifests.py @@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Build GT-only HOT3D recording-group manifests through official mask APIs.""" + +from __future__ import annotations + +import argparse +import bisect +from collections import Counter +import hashlib +import json +from pathlib import Path +import subprocess +import sys +from typing import Iterable + +from foundation_hand.data.hot3d_dataset import load_hot3d_api + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def participant_split(participants: Iterable[str]) -> tuple[set[str], set[str]]: + ordered = sorted(set(participants)) + if len(ordered) < 4: + raise ValueError("HOT3D participant split requires at least four GT participants") + heldout = {participant for index, participant in enumerate(ordered) if index % 4 == 3} + return set(ordered) - heldout, heldout + + +def contiguous_clips( + timestamps_ns: Iterable[int], + length: int, + max_gap_ns: int = 100_000_000, +) -> list[list[int]]: + timestamps = sorted(set(int(value) for value in timestamps_ns)) + runs: list[list[int]] = [] + current: list[int] = [] + for timestamp in timestamps: + if current and timestamp - current[-1] > max_gap_ns: + runs.append(current) + current = [] + current.append(timestamp) + if current: + runs.append(current) + clips: list[list[int]] = [] + for run in runs: + clips.extend(run[start : start + length] for start in range(0, len(run), length) if len(run[start : start + length]) == length) + return clips + + +def nearest_timestamp( + timestamp_ns: int, + reference_ns: list[int], + maximum_delta_ns: int, +) -> int | None: + position = bisect.bisect_left(reference_ns, int(timestamp_ns)) + candidates = reference_ns[max(0, position - 1) : position + 1] + if not candidates: + return None + nearest = min(candidates, key=lambda value: abs(value - timestamp_ns)) + return nearest if abs(nearest - timestamp_ns) <= maximum_delta_ns else None + + +def write_jsonl(path: Path, rows: list[dict]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--max-recordings", type=int) + parser.add_argument("--max-clips-per-recording-stream", type=int) + args = parser.parse_args() + if args.clip_length < 1: + parser.error("--clip-length must be positive") + + api = load_hot3d_api(args.toolkit_root) + source = args.toolkit_root.resolve() / "hot3d" + if str(source) not in sys.path: + sys.path.insert(0, str(source)) + from data_loaders.loader_hand_poses import load_hand_poses + from data_loaders.loader_masks import combine_mask_data, load_mask_data + + metadata_paths = sorted(args.root.glob("P*/metadata.json")) + metadata: list[tuple[Path, dict]] = [] + no_gt_count = 0 + for path in metadata_paths: + record = json.loads(path.read_text(encoding="utf-8")) + if record.get("have_hand_object_pose_gt") is not True: + no_gt_count += 1 + continue + metadata.append((path.parent, record)) + if args.max_recordings is not None: + metadata = metadata[: args.max_recordings] + participants = [record["participant_id"] for _, record in metadata] + train_participants, heldout_participants = participant_split(participants) + rows: dict[str, list[dict]] = {"train": [], "heldout": []} + skipped: Counter[str] = Counter() + counts: Counter[str] = Counter() + required_masks = ( + "mask_hand_visible.csv", + "mask_headset_pose_available.csv", + "mask_good_exposure.csv", + "mask_qa_pass.csv", + ) + for recording_dir, record in metadata: + missing = [ + name for name in required_masks + if not (recording_dir / "masks" / name).is_file() + ] + if missing: + skipped["missing_masks"] += 1 + continue + masks = [ + load_mask_data(str(recording_dir / "masks" / name)) + for name in required_masks + ] + combined = combine_mask_data(masks, "and") + hand_poses = load_hand_poses( + str(recording_dir / "mano_hand_pose_trajectory.jsonl") + ) + hand_timestamps = sorted(hand_poses) + streams = ["214-1"] if record["headset"] == "Aria" else ["1201-1", "1201-2"] + split = "train" if record["participant_id"] in train_participants else "heldout" + for stream_id in streams: + stream_mask = combined.data.get(stream_id) + if stream_mask is None: + skipped[f"missing_stream_{stream_id}"] += 1 + continue + timestamp_to_pose = { + timestamp: nearest_timestamp(timestamp, hand_timestamps, 20_000_000) + for timestamp, valid in stream_mask.items() if valid + } + timestamp_to_pose = { + timestamp: pose_timestamp + for timestamp, pose_timestamp in timestamp_to_pose.items() + if pose_timestamp is not None + } + clips = contiguous_clips(timestamp_to_pose, args.clip_length) + if args.max_clips_per_recording_stream is not None: + clips = clips[: args.max_clips_per_recording_stream] + for clip_index, timestamps in enumerate(clips): + rows[split].append({ + "dataset": "HOT3D", + "split": split, + "participant_id": record["participant_id"], + "recording_id": record["recording_name"], + "physical_recording_id": record["recording_name"], + "headset": record["headset"], + "stream_id": stream_id, + "clip_index_in_stream": clip_index, + "timestamps_ns": timestamps, + "hand_pose_timestamp_ns": [timestamp_to_pose[value] for value in timestamps], + "hand_count": [ + len(hand_poses[timestamp_to_pose[value]].poses) + for value in timestamps + ], + "have_hand_object_pose_gt": True, + "depth_input_available": False, + "K_input_dropout": 0.3, + "group_key": f"HOT3D/{record['participant_id']}/{record['recording_name']}", + }) + counts[f"{split}/{record['headset']}/{stream_id}"] += len(clips) + + args.output_dir.mkdir(parents=True, exist_ok=True) + paths = {} + for split, split_rows in rows.items(): + path = args.output_dir / f"hot3d_{split}_t{args.clip_length}.jsonl" + write_jsonl(path, split_rows) + paths[split] = {"path": str(path.resolve()), "sha256": sha256(path), "clips": len(split_rows)} + toolkit_commit = subprocess.run( + ["git", "-C", str(args.toolkit_root), "rev-parse", "HEAD"], + text=True, stdout=subprocess.PIPE, check=True, + ).stdout.strip() + audit = { + "status": "built", + "official_test_used": False, + "gt_metadata_records": len(metadata), + "excluded_no_gt_metadata_records": no_gt_count, + "train_participants": sorted(train_participants), + "heldout_participants": sorted(heldout_participants), + "participant_overlap": sorted(train_participants & heldout_participants), + "counts": dict(sorted(counts.items())), + "skipped": dict(sorted(skipped.items())), + "clip_length": args.clip_length, + "required_masks": list(required_masks), + "pose_contract": "nearest official MANO timestamp within 20ms; one or two hands allowed", + "toolkit": {"path": str(args.toolkit_root.resolve()), "git_commit": toolkit_commit}, + "manifests": paths, + } + output = args.output_dir / "hot3d_manifest_audit.json" + output.write_text(json.dumps(audit, indent=2) + "\n", encoding="utf-8") + print(json.dumps(audit, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_scale_eval_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_scale_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..104816c1155e66759d9276dae8052af0f372be82 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase7_scale_eval_queue.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Build a hash-bound formal evaluation queue for a matched scale step.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.run_phase7_heldout_cache_queue import output_complete + + +CONDITIONS = ("E40", "E70", "E100") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def stage_suffix(step: int) -> str: + suffixes = {2000: "2k", 10000: "10k", 50000: "50k", 100000: "100k"} + try: + return suffixes[step] + except KeyError as error: + raise ValueError(f"unsupported formal matched step: {step}") from error + + +def read_marker(run_root: Path, condition: str, step: int) -> dict[str, Any]: + marker_path = run_root / ".phase7_queue" / f"{condition}_scale_{stage_suffix(step)}.json" + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker["checkpoint"]) + config = Path(marker["config"]) + if ( + marker.get("status") != "complete" + or int(marker.get("completed_step", -1)) != step + or marker.get("official_test_used") is not False + or marker.get("h2o_training_data_used") is not False + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or not config.is_file() + or marker.get("config_sha256") != sha256(config) + ): + raise ValueError(f"scale marker failed frozen contract: {marker_path}") + return marker + + +def input_mode(condition: str, dataset: str) -> str: + if dataset == "HOI4D" and condition != "E100": + return "rgb_d_k" + return "rgb_k" + + +def build_queue( + plan: dict[str, Any], run_roots: dict[str, Path], step: int, + evaluation_root: Path, conditions: tuple[str, ...] = CONDITIONS, +) -> dict[str, Any]: + if plan.get("official_test_used") is not False or plan.get("h2o_used") is not False: + raise ValueError("formal cache plan is not external-only") + sources = {item["dataset"]: item for item in plan["sources"]} + if set(sources) != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("formal cache plan lacks the complete dataset grid") + for item in sources.values(): + if not output_complete(item): + raise ValueError(f"formal held-out cache is incomplete: {item['dataset']}") + markers = { + condition: read_marker(run_roots[condition], condition, step) + for condition in conditions + } + evaluations = [] + for condition in conditions: + marker = markers[condition] + for dataset in ("HOT3D", "HOI4D", "ARCTIC"): + source = sources[dataset] + mode = input_mode(condition, dataset) + evaluations.append({ + "id": f"{condition}_{dataset}_scale_step{step}_{mode}", + "config": marker["config"], + "checkpoint": marker["checkpoint"], + "checkpoint_sha256": marker["checkpoint_sha256"], + "cache_manifest": str( + (Path(source["output_dir"]) / "cache_manifest.jsonl").resolve() + ), + "input_mode": mode, + "output_dir": str(( + evaluation_root + / f"{condition.lower()}_scale_step{step}_{dataset.lower()}_heldout2048_{mode}" + ).resolve()), + "bootstrap_resamples": 2000, + }) + return { + "schema_version": "phase7_external_eval_queue_v1", + "purpose": f"Formal matched external scale evaluation at step {step}", + "matched_step": step, "selection_split": "external_heldout_only", + "official_test_used": False, "h2o_training_data_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--formal-cache-plan", type=Path, required=True) + parser.add_argument( + "--step", type=int, choices=(2000, 10000, 50000, 100000), required=True, + ) + parser.add_argument( + "--conditions", nargs="+", choices=CONDITIONS, default=list(CONDITIONS), + ) + parser.add_argument("--e40-run", type=Path, required=True) + parser.add_argument("--e70-run", type=Path, required=True) + parser.add_argument("--e100-run", type=Path, required=True) + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output queue already exists") + plan = json.loads(args.formal_cache_plan.read_text(encoding="utf-8")) + queue = build_queue( + plan, {"E40": args.e40_run, "E70": args.e70_run, "E100": args.e100_run}, + args.step, args.evaluation_root, tuple(args.conditions), + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_adaptation_eval_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_adaptation_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..73840a2414c7276121f0302064f82599ffb40c11 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_adaptation_eval_queue.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-mode H2O train-heldout adaptation evaluation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +HELDOUT = Path( + "/home/jiasen/foundation_hand/artifacts/phase7/manifests/" + "h2o_train_group_cv_v1/train_group_heldout.jsonl" +) +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, + condition: str, + step: int, + config: Path, + config_sha256: str, + checkpoint: Path, + checkpoint_sha256: str, + output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not condition or any(character.isspace() for character in condition): + raise ValueError("condition must be a nonempty whitespace-free identifier") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap_resamples must be positive") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + if not HELDOUT.is_file(): + raise ValueError("frozen H2O train-group-heldout manifest is missing") + evaluations = [ + { + "id": f"{condition}_step{step}_{input_mode}", + "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(HELDOUT.resolve()), + "cache_manifest_sha256": sha256(HELDOUT), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str( + (output_root / f"{condition}_step{step}_{input_mode}").resolve() + ), + } + for input_mode in INPUT_MODES + ] + return { + "schema_version": "phase8_adaptation_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "Three-mode H2O train-group-heldout selection evaluation.", + "selection_split": "h2o_train_group_heldout_only", + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, + step=args.step, + config=args.config, + config_sha256=args.config_sha256, + checkpoint=args.checkpoint, + checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_adaptation_forgetting_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_adaptation_forgetting_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8f458e2c336aefbba9a75f8127f54f089f1f6f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_adaptation_forgetting_queue.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Build hash-bound external forgetting diagnostics for an H2O-adapted model.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +DOMAINS = { + "HOT3D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), + "HOI4D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_d_k", + ), + "ARCTIC": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "arctic_val2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, + condition: str, + step: int, + config: Path, + config_sha256: str, + checkpoint: Path, + checkpoint_sha256: str, + output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not condition or any(character.isspace() for character in condition): + raise ValueError("condition must be a nonempty whitespace-free identifier") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap_resamples must be positive") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + evaluations = [] + for dataset, (manifest_string, input_mode) in DOMAINS.items(): + manifest = Path(manifest_string) + if not manifest.is_file() or "h2o" in str(manifest).lower(): + raise ValueError(f"external forgetting manifest is invalid: {manifest}") + evaluations.append({ + "id": f"{condition}_step{step}_{dataset}_{input_mode}", + "dataset": dataset, + "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str( + (output_root / f"{condition}_step{step}" / f"{dataset}_{input_mode}").resolve() + ), + }) + return { + "schema_version": "phase8_adaptation_forgetting_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "External held-out forgetting diagnostic only; never used for H2O selection.", + "evaluation_split": "external_heldout_forgetting_diagnostic_only", + "selection_use": False, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, + config=args.config, config_sha256=args.config_sha256, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_egodexter_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_egodexter_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..e2873ce3d5a27694cfbb51342326605472cc5f09 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_egodexter_queue.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Build one frozen model's six-condition EgoDexter zero-shot queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_egodexter_zero_shot import sha256, validate_freeze_record + + +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") +INFERENCE_MODES = ("offline", "causal") + + +def build_queue( + freeze_path: Path, model_id: str, root: Path, output_root: Path, +) -> dict[str, Any]: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + models = {item["id"]: item for item in freeze.get("models", [])} + if model_id not in models: + raise ValueError("model is absent from the final freeze") + model = models[model_id] + checkpoint = Path(model["checkpoint"]) + if not checkpoint.is_file() or sha256(checkpoint) != model["checkpoint_sha256"]: + raise ValueError("frozen checkpoint is missing or SHA256 differs") + if not root.is_dir() or not (root / "data").is_dir(): + raise ValueError("EgoDexter root is invalid") + evaluations = [] + for inference_mode in INFERENCE_MODES: + config = Path(model["inference_configs"][inference_mode]["path"]) + validate_freeze_record( + freeze, model_id, model["checkpoint_sha256"], config, inference_mode, + ) + for input_mode in INPUT_MODES: + evaluations.append({ + "id": f"{model_id}_{inference_mode}_{input_mode}", + "model_id": model_id, + "freeze_record": str(freeze_path.resolve()), + "config": str(config.resolve()), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": model["checkpoint_sha256"], + "root": str(root.resolve()), + "input_mode": input_mode, + "inference_mode": inference_mode, + "window": 8, + "output_dir": str((output_root / inference_mode / input_mode).resolve()), + }) + return { + "schema_version": "phase8_egodexter_zero_shot_queue_v1", + "model_id": model_id, + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--model-id", required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + queue = build_queue(args.freeze_record, args.model_id, args.root, args.output_root) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_external_tail_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_external_tail_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..57d07512de8608b779e00ee27b66ee001473fca7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_external_tail_queue.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Build a hash-bound 100k-to200k minimum-LR external continuation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + +import yaml + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, condition: str, config_path: Path, config_sha256: str, + output_dir: Path, checkpoint: Path, checkpoint_sha256: str, + resume_step: int = 100000, end_step: int = 200000, +) -> dict[str, Any]: + if not config_path.is_file() or sha256(config_path) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("resume checkpoint is missing or SHA256 differs") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + if config.get("experiment", {}).get("branch") != "external_only": + raise ValueError("schedule tail is restricted to external-only configs") + max_steps = int(config["protocol"]["max_steps"]) + if max_steps != resume_step or not end_step > resume_step: + raise ValueError("tail requires resume_step=config max_steps < end_step") + expected_checkpoint = output_dir / f"step_{resume_step:07d}_final.pt" + if checkpoint.resolve() != expected_checkpoint.resolve(): + raise ValueError("checkpoint path is not the final artifact in output_dir") + required_caches = [] + for source in config["data"]["sources"]: + manifest = Path(source["cache_manifest"]) + report_path = manifest.parent / "cache_report.json" + if not manifest.is_file() or not report_path.is_file(): + raise ValueError(f"source cache is incomplete: {manifest}") + report = json.loads(report_path.read_text(encoding="utf-8")) + clips = report.get("clips", report.get("cached_clips")) + recorded = report.get("cache_manifest", {}) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or int(clips or -1) <= 0 + or recorded.get("sha256") != sha256(manifest) + ): + raise ValueError(f"source cache report is not hash-valid: {report_path}") + required_caches.append({ + "id": f"{source['dataset']}_{clips}", + "report": str(report_path.resolve()), + "manifest": str(manifest.resolve()), + "expected_clips": int(clips), + }) + return { + "schema_version": "phase8_external_schedule_tail_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": f"Exact-resume {condition} from {resume_step} to {end_step} at the registered minimum LR.", + "official_test_used": False, "h2o_training_data_used": False, + "allowed_physical_gpus": [0, 1, 2, 3], + "required_caches": required_caches, + "stages": [{ + "id": f"{condition}_{end_step}_min_lr_tail", + "config": str(config_path.resolve()), + "config_sha256": config_sha256, + "output_dir": str(output_dir.resolve()), + "resume_from_step": resume_step, + "resume_checkpoint_sha256": checkpoint_sha256, + "stop_after_step": end_step, + "allow_schedule_tail": True, + }], + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--resume-step", type=int, default=100000) + parser.add_argument("--end-step", type=int, default=200000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, config_path=args.config, + config_sha256=args.config_sha256, output_dir=args.output_dir, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + resume_step=args.resume_step, end_step=args.end_step, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_h2o_adapted_validation_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_h2o_adapted_validation_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c9eec9bc1340e152be7824e02131c5ed03efc0b7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_h2o_adapted_validation_queue.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-mode formal H2O adaptation validation queue.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_external import sha256 +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_h2o_adapted_validation_queue import validate_queue + + +def build_queue(freeze_path: Path, root: Path, output_root: Path) -> dict[str, Any]: + freeze = json.loads(freeze_path.read_text(encoding="utf-8")) + if ( + freeze.get("status") != "h2o_adaptation_candidate_frozen" + or freeze.get("selection_split") != "h2o_train_group_heldout_only" + or freeze.get("h2o_official_validation_used_for_selection") is not False + or freeze.get("h2o_training_data_used") is not True + or freeze.get("official_test_used") is not False + ): + raise ValueError("adaptation freeze record is incomplete") + checkpoint = freeze.get("checkpoint", {}) + config = freeze.get("config", {}) + manifest = freeze.get("h2o_validation_manifest", {}) + for record, label in ( + (checkpoint, "checkpoint"), (config, "config"), (manifest, "manifest"), + ): + path = Path(record.get("path", "")) + if not path.is_file() or sha256(path) != record.get("sha256"): + raise ValueError(f"frozen {label} is missing or SHA256 differs") + if Path(manifest["path"]).name != "official_val.jsonl": + raise ValueError("only canonical H2O official validation is allowed") + if set(freeze.get("frozen_h2o_input_modes", [])) != set(INPUT_MODES): + raise ValueError("adaptation freeze record does not bind all input modes") + if not root.is_dir() or not (root / "subject3").is_dir(): + raise ValueError("H2O root does not contain the canonical validation subject") + evaluations = [{ + "id": f"{freeze['winner']}_formal_{mode}", + "input_mode": mode, + "config": str(Path(config["path"]).resolve()), + "checkpoint": str(Path(checkpoint["path"]).resolve()), + "checkpoint_sha256": checkpoint["sha256"], + "freeze_record": str(freeze_path.resolve()), + "root": str(root.resolve()), + "manifest": str(Path(manifest["path"]).resolve()), + "output_dir": str((output_root / mode).resolve()), + "bootstrap_resamples": 2000, + } for mode in INPUT_MODES] + queue = { + "schema_version": "phase8_h2o_adapted_validation_queue_v1", + "purpose": "Formal validation of one train-heldout-frozen H2O adaptation candidate.", + "selection_split": "h2o_train_group_heldout_only", + "allowed_physical_gpus": [0, 1, 2, 3], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "evaluations": evaluations, + } + validate_queue(queue) + return queue + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + queue = build_queue(args.freeze_record, args.root, args.output_root) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_left_root_relative_sidecars.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_left_root_relative_sidecars.py new file mode 100644 index 0000000000000000000000000000000000000000..1613c74abf4e6474d9947f19ff38ba45a442d1aa --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_left_root_relative_sidecars.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Attach target-only historical-left joint supervision to existing caches.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def left_only_target( + target: torch.Tensor, + source_valid: torch.Tensor, + translation_valid: torch.Tensor, + frame_valid: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + if target.shape[-2:] != (21, 3): + raise ValueError("target must end in [21,3]") + if source_valid.shape != target.shape[:-1]: + raise ValueError("source-valid shape differs from target") + if translation_valid.shape != target.shape[:-2]: + raise ValueError("translation-valid shape differs from target") + if frame_valid.shape != target.shape[:-3]: + raise ValueError("frame-valid shape differs from target") + valid = ( + source_valid.bool() + & translation_valid.bool()[..., None] + & frame_valid.bool()[..., None, None] + ) + valid[..., 1, :] = False + target = target.clone().masked_fill(~valid[..., None], float("nan")) + return target, valid + + +def read_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--expected-source-manifest-sha256", required=True) + parser.add_argument("--expected-cache-manifest-sha256", required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--resume", action="store_true") + parser.add_argument("--torch-threads", type=int, default=0) + args = parser.parse_args() + if sha256(args.source_manifest) != args.expected_source_manifest_sha256: + parser.error("source manifest SHA256 differs") + if sha256(args.cache_manifest) != args.expected_cache_manifest_sha256: + parser.error("cache manifest SHA256 differs") + if args.torch_threads < 0: + parser.error("--torch-threads cannot be negative") + if args.torch_threads: + torch.set_num_threads(args.torch_threads) + torch.set_num_interop_threads(1) + if args.resume: + if not (args.output_dir / "sidecars").is_dir(): + parser.error("--resume requires an existing sidecars directory") + elif args.output_dir.exists(): + parser.error("output directory already exists") + if args.dataset == "HOI4D": + if args.root is None: + parser.error("HOI4D requires --root") + dataset = HOI4DClipDataset( + args.root, args.source_manifest, args.mano_root, + ) + else: + dataset = ARCTICClipDataset(args.source_manifest, args.mano_root) + rows = read_jsonl(args.cache_manifest) + args.output_dir.mkdir(parents=True, exist_ok=args.resume) + sidecars = args.output_dir / "sidecars" + sidecars.mkdir(exist_ok=args.resume) + augmented: list[dict[str, Any] | None] = [None] * len(rows) + left_hand_frames = 0 + right_joint_count = 0 + root_norm_max_mm = 0.0 + started = time.monotonic() + order = sorted( + range(len(rows)), + key=lambda position: ( + str(rows[position]["physical_recording_id"]), + int(rows[position]["source_clip_index"]), + ), + ) + for processed, position in enumerate(order, start=1): + row = rows[position] + source_index = int(row["source_clip_index"]) + path = sidecars / f"clip_{source_index:07d}.npz" + if path.is_file() and args.resume: + try: + with np.load(path, allow_pickle=False) as sidecar: + if set(sidecar.files) != { + "joint3d_root_relative", "joint3d_root_relative_valid", + }: + raise ValueError("unexpected sidecar keys") + target = torch.from_numpy(sidecar["joint3d_root_relative"]) + valid = torch.from_numpy( + sidecar["joint3d_root_relative_valid"] + ).bool() + except (OSError, ValueError, EOFError): + preserved = path.with_name( + f"{path.name}.invalid_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}" + ) + path.rename(preserved) + if not path.is_file(): + target, source_valid = dataset.source_root_relative_joint3d(source_index) + with np.load(row["cache_path"], allow_pickle=False) as cache: + translation_valid = torch.from_numpy(cache["translation_valid"]).bool() + frame_valid = torch.from_numpy(cache["frame_valid"]).bool() + target, valid = left_only_target( + target, source_valid, translation_valid, frame_valid, + ) + temporary = path.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed( + handle, + joint3d_root_relative=target.numpy(), + joint3d_root_relative_valid=valid.numpy(), + ) + temporary.replace(path) + output_row = dict(row) + output_row.update({ + "joint3d_root_relative_sidecar_path": str(path.resolve()), + "joint3d_root_relative_sidecar_sha256": sha256(path), + "joint3d_root_relative_scope": "historical_left_only", + }) + augmented[position] = output_row + left_hand_frames += int(valid[..., 0, :].any(-1).sum()) + right_joint_count += int(valid[..., 1, :].sum()) + finite_roots = valid[..., 0, 0] + if finite_roots.any(): + root_norm_max_mm = max( + root_norm_max_mm, + float(torch.linalg.vector_norm(target[..., 0, 0, :][finite_roots], dim=-1).max() * 1000.0), + ) + if processed % 500 == 0 or processed == len(order): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": processed, + "clips": len(order), + "clips_per_second": processed / max(elapsed, 1e-9), + "eta_seconds": (len(order) - processed) / max(processed / elapsed, 1e-9), + }), flush=True) + if any(row is None for row in augmented): + raise RuntimeError("augmented manifest contains missing rows") + manifest = args.output_dir / "cache_manifest.jsonl" + manifest.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in augmented), + encoding="utf-8", + ) + elapsed = time.monotonic() - started + report = { + "schema_version": "phase8_left_root_relative_sidecars_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "dataset": args.dataset, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "base_cache_manifest": {"path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest)}, + "augmented_cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "clips": len(rows), + "left_hand_frames": left_hand_frames, + "right_valid_joint_count": right_joint_count, + "root_norm_max_mm": root_norm_max_mm, + "shape_supervision_restored": False, + "vertices_supervision_restored": False, + "camera_joint3d_supervision_restored": False, + "wall_seconds": elapsed, + "clips_per_second": len(rows) / max(elapsed, 1e-9), + "bytes": sum(path.stat().st_size for path in sidecars.iterdir()), + "resume_invocation": bool(args.resume), + "torch_threads": args.torch_threads or torch.get_num_threads(), + "official_test_used": False, + } + report_path = args.output_dir / "sidecar_report.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if not left_hand_frames or right_joint_count or root_norm_max_mm >= 1e-4: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_specialist_eval_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_specialist_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa0f9aa72435130c16fcd98a84a0963d098f45f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_specialist_eval_queue.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Build a hash-bound three-domain evaluation queue for one external checkpoint.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +DOMAINS = { + "HOT3D": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_only"), + }, + "HOI4D": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_d_k", "rgb_only"), + }, + "ARCTIC": { + "cache_manifest": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/arctic_val2048_fullgroups_v2/cache_manifest.jsonl", + "input_modes": ("rgb_k", "rgb_only"), + }, +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def build_queue( + *, condition: str, step: int, config: Path, config_sha256: str, + checkpoint: Path, checkpoint_sha256: str, output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + if step <= 0 or bootstrap_resamples <= 0: + raise ValueError("step and bootstrap resamples must be positive") + evaluations = [] + for dataset, domain in DOMAINS.items(): + manifest = Path(domain["cache_manifest"]) + if not manifest.is_file(): + raise ValueError(f"held-out manifest is missing: {manifest}") + slug = dataset.lower() + for input_mode in domain["input_modes"]: + evaluations.append({ + "id": f"{condition}_step{step}_{dataset}_{input_mode}", + "dataset": dataset, + "matrix_role": "primary_matched_rgb_k" if input_mode == "rgb_k" else "input_diagnostic", + "config": str(config.resolve()), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, + "bootstrap_resamples": bootstrap_resamples, + "output_dir": str((output_root / f"{condition}_step{step}" / f"{slug}_{input_mode}").resolve()), + }) + return { + "schema_version": "phase8_specialist_cross_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "purpose": "Frozen matched RGB-K cross-domain matrix plus RGB-only and HOI4D RGB-D-K diagnostics.", + "condition": condition, "checkpoint_step": step, + "h2o_training_data_used": False, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, + config=args.config, config_sha256=args.config_sha256, + checkpoint=args.checkpoint, checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_stage7_eval_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_stage7_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5db2287015b04a005106f0656ae4231c42687dcb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase8_stage7_eval_queue.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Build a hash-bound Stage 7 external held-out evaluation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase8_specialist_eval_queue import sha256 + + +STAGE7_DOMAINS = { + "HOT3D": ( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "rgb_k", + ), + "HOI4D": ( + "/SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/" + "hoi4d_heldout_left_root_relative_sidecars_v1/cache_manifest.jsonl", + "rgb_d_k", + ), + "ARCTIC": ( + "/SSD3/jiasen/foundation_hand/phase8_artifacts/source_audits/" + "arctic_p2_val_left_root_relative_sidecars_v1/cache_manifest.jsonl", + "rgb_k", + ), +} + + +def build_queue( + *, condition: str, step: int, config: Path, config_sha256: str, + checkpoint: Path, checkpoint_sha256: str, output_root: Path, + bootstrap_resamples: int, +) -> dict[str, Any]: + if condition not in {"L0_sampler_only", "L1_left_root_relative"}: + raise ValueError("condition is not a frozen Stage 7 condition") + if step != 10000 or bootstrap_resamples <= 0: + raise ValueError("Stage 7 evaluation requires step10k and positive resamples") + if not config.is_file() or sha256(config) != config_sha256: + raise ValueError("config is missing or SHA256 differs") + if not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha256: + raise ValueError("checkpoint is missing or SHA256 differs") + evaluations = [] + for dataset, (manifest_string, input_mode) in STAGE7_DOMAINS.items(): + manifest = Path(manifest_string) + if not manifest.is_file() or "h2o" in str(manifest).lower(): + raise ValueError(f"invalid Stage 7 held-out manifest: {manifest}") + evaluations.append({ + "id": f"{condition}_step10000_{dataset}_{input_mode}", + "dataset": dataset, "config": str(config.resolve()), + "config_sha256": config_sha256, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha256, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": input_mode, "bootstrap_resamples": bootstrap_resamples, + "output_dir": str((output_root / condition / f"{dataset}_{input_mode}").resolve()), + }) + return { + "schema_version": "phase8_stage7_eval_queue_v1", + "created_utc": datetime.now(timezone.utc).isoformat(), + "condition": condition, "checkpoint_step": step, + "evaluation_split": "external_heldout_only", + "h2o_training_data_used": False, + "h2o_official_validation_used": False, + "official_test_used": False, + "evaluations": evaluations, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--condition", required=True) + parser.add_argument("--step", type=int, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--config-sha256", required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256", required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--queue-path", type=Path, required=True) + args = parser.parse_args() + if args.queue_path.exists(): + parser.error("queue path already exists") + try: + queue = build_queue( + condition=args.condition, step=args.step, config=args.config, + config_sha256=args.config_sha256, checkpoint=args.checkpoint, + checkpoint_sha256=args.checkpoint_sha256, + output_root=args.output_root, + bootstrap_resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.queue_path.parent.mkdir(parents=True, exist_ok=True) + args.queue_path.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8") + print(json.dumps(queue, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_final_deployment_plan.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_final_deployment_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..bd59e8112af6f89be4d8c8387647095fdb424bf8 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_final_deployment_plan.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""Build the post-selection formal-validation and deployment-audit job plan.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +LENGTHS = [1, 2, 4, 8, 16, 32, 64] +ORDERING_LENGTHS = [31, 64, 257] + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def derive_causal_config(config: dict[str, Any]) -> dict[str, Any]: + result = deepcopy(config) + if result.get("model", {}).get("temporal_attention_mode") != "bidirectional": + raise ValueError("final checkpoint config is not the frozen bidirectional control") + result["model"]["temporal_attention_mode"] = "causal" + return result + + +def write_causal_config(source: Path, output: Path) -> str: + original = yaml.safe_load(source.read_text(encoding="utf-8")) + causal = derive_causal_config(original) + output.parent.mkdir(parents=True, exist_ok=True) + rendered = yaml.safe_dump(causal, sort_keys=False) + if output.exists(): + if yaml.safe_load(output.read_text(encoding="utf-8")) != causal: + raise ValueError("existing final causal config differs") + else: + temporary = output.with_suffix(".tmp") + temporary.write_text(rendered, encoding="utf-8") + temporary.replace(output) + return sha256(output) + + +def build_plan( + *, freeze_path: Path, freeze_state_path: Path, output_root: Path, + worker_state_root: Path, causal_config_path: Path, h2o_root: Path, +) -> dict[str, Any]: + state = read_json(freeze_state_path) + freeze = read_json(freeze_path) + if ( + state.get("status") != "complete" + or state.get("freeze_sha256") != sha256(freeze_path) + or freeze.get("status") != "phase9_final_unified_checkpoint_frozen" + or freeze.get("h2o_official_validation_used") is not False + or freeze.get("h2o_official_validation_used_for_selection") is not False + or freeze.get("official_test_used") is not False + ): + raise ValueError("final deployment freeze is incomplete or unbound") + checkpoint = freeze["checkpoint"] + config = freeze["config"] + validation = freeze["h2o_validation_manifest"] + training = freeze["h2o_training_manifest"] + for record, label in ( + (checkpoint, "checkpoint"), (config, "config"), + (validation, "validation manifest"), (training, "training manifest"), + ): + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"frozen final {label} differs") + causal_sha = write_causal_config(Path(config["path"]), causal_config_path) + if not h2o_root.is_dir(): + raise ValueError("canonical H2O root is missing") + common = { + "checkpoint": checkpoint["path"], + "checkpoint_sha256": checkpoint["sha256"], + "checkpoint_step": checkpoint["step"], + "config": config["path"], "config_sha256": config["sha256"], + "freeze_record": str(freeze_path.resolve()), + "freeze_record_sha256": sha256(freeze_path), + "root": str(h2o_root.resolve()), + } + jobs = [] + for gpu, mode in enumerate(INPUT_MODES): + jobs.append({ + **common, "id": f"formal_{mode}", "kind": "formal_validation", + "physical_gpu_id": gpu, "input_mode": mode, + "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output_dir": str((output_root / "formal_h2o" / mode).resolve()), + }) + jobs.append({ + **common, "id": "variable_length", "kind": "variable_length", + "physical_gpu_id": 0, "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output": str((output_root / "audits" / "variable_length.json").resolve()), + "lengths": LENGTHS, + }) + for index, frames in enumerate(ORDERING_LENGTHS, start=1): + for mode in ("offline", "causal"): + job_config = config if mode == "offline" else { + "path": str(causal_config_path.resolve()), "sha256": causal_sha, + } + jobs.append({ + **common, "id": f"{mode}_w8_{frames}", "kind": "sequence", + "physical_gpu_id": index, "mode": mode, "window": 8, + "frames": frames, "config": job_config["path"], + "config_sha256": job_config["sha256"], + "manifest": validation["path"], + "manifest_sha256": validation["sha256"], + "output": str(( + output_root / "audits" / f"{mode}_w8_{frames}.json" + ).resolve()), + }) + jobs.append({ + **common, "id": "latency_vram", "kind": "profile", + "physical_gpu_id": 3, "manifest": training["path"], + "manifest_sha256": training["sha256"], + "resolution_hw": freeze["resolution_hw"], + "output": str((output_root / "audits" / "latency_vram.json").resolve()), + }) + ids = [job["id"] for job in jobs] + outputs = [job.get("output", job.get("output_dir")) for job in jobs] + if len(jobs) != 11 or len(set(ids)) != 11 or len(set(outputs)) != 11: + raise ValueError("final deployment jobs are not unique and complete") + workers = [] + for gpu in range(4): + workers.append({ + "id": f"gpu{gpu}", "physical_gpu_id": gpu, + "state": str((worker_state_root / f"gpu{gpu}_state.json").resolve()), + "job_ids": [job["id"] for job in jobs if job["physical_gpu_id"] == gpu], + }) + assigned = [identifier for worker in workers for identifier in worker["job_ids"]] + if sorted(assigned) != sorted(ids) or len(set(assigned)) != 11: + raise ValueError("final deployment worker assignment overlaps or omits jobs") + return { + "schema_version": "phase9_final_deployment_plan_v1", + "status": "frozen_ready_post_selection", + "created_utc": freeze["created_utc"], + "freeze": {"path": str(freeze_path.resolve()), "sha256": sha256(freeze_path)}, + "winner": freeze["winner"], + "selected_mechanism": freeze["selected_mechanism"], + "resolution_hw": freeze["resolution_hw"], + "shared_augmentation": freeze["shared_augmentation"], + "checkpoint": checkpoint, "config": config, + "causal_config": { + "path": str(causal_config_path.resolve()), "sha256": causal_sha, + "only_change": "model.temporal_attention_mode=causal", + }, + "jobs": jobs, "workers": workers, + "official_validation_checkpoint_count": 1, + "formal_validation_modes": list(INPUT_MODES), + "variable_lengths": LENGTHS, + "sequence_contract": { + "offline_window": 8, "causal_window": 8, + "ordering_lengths": ORDERING_LENGTHS, + }, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--freeze", type=Path, required=True) + parser.add_argument("--freeze-state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--causal-config", type=Path, required=True) + parser.add_argument("--h2o-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + freeze_path=args.freeze, freeze_state_path=args.freeze_state, + output_root=args.output_root, worker_state_root=args.worker_state_root, + causal_config_path=args.causal_config, h2o_root=args.h2o_root, + ) + if args.output.exists(): + if read_json(args.output) != plan: + raise ValueError("existing final deployment plan differs") + else: + atomic_json(args.output, plan) + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_plan_state_v1", + "status": "complete", "plan": str(args.output.resolve()), + "plan_sha256": sha256(args.output), "job_count": len(plan["jobs"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_plan_state_v1", + "status": "failed_resumable", + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + }) + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_fold_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_fold_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..e98a67efcafc5b55c0d5ea9199882374ee8b7a3c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_fold_configs.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Generate hash-bound six-fold Phase 9 unified training configurations.""" + +from __future__ import annotations + +import argparse +import copy +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path + +import yaml + +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--multifold-index", type=Path, required=True) + parser.add_argument("--base-config", type=Path, action="append", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--run-root", type=Path, required=True) + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--data-readiness-state", type=Path, required=True) + parser.add_argument("--data-finalize-plan-sha256", required=True) + parser.add_argument("--initialization-checkpoint", type=Path, required=True) + parser.add_argument("--initialization-checkpoint-sha256", required=True) + parser.add_argument( + "--refresh", action="store_true", + help="Replace preregistered configs only when no training checkpoint exists.", + ) + args = parser.parse_args() + if (args.output_dir.exists() or args.registry.exists()) and not args.refresh: + parser.error("fold config output and registry must be new") + if args.refresh and args.run_root.exists() and any(args.run_root.rglob("*.pt")): + parser.error("cannot refresh fold configs after a training checkpoint exists") + if sha256(args.initialization_checkpoint) != args.initialization_checkpoint_sha256: + parser.error("initialization checkpoint SHA256 differs") + index = json.loads(args.multifold_index.read_text(encoding="utf-8")) + if index.get("status") != "complete" or index.get("official_test_used") is not False: + parser.error("multifold index is incomplete or lacks test isolation") + folds = [str(fold["id"]) for fold in index["folds"]] + args.output_dir.mkdir(parents=True, exist_ok=args.refresh) + conditions = [] + for base_path in args.base_config: + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + mixture = str(base["experiment"]["condition"]) + for fold in folds: + config = copy.deepcopy(base) + condition = f"{mixture}_{fold}" + config["name"] = f"phase9_{condition.lower()}_s20260717" + config["experiment"]["condition"] = condition + config["experiment"]["h2o_selection_fold"] = fold + h2o = next( + source for source in config["data"]["sources"] + if str(source["dataset"]).upper() == "H2O" + ) + h2o["cache_manifest"] = str( + (args.multifold_index.parent / f"{fold}_train.jsonl").resolve() + ) + config["data"]["validation_sources"] = [{ + "dataset": "H2O", "source_id": f"H2O_{fold}_heldout", + "split_role": "train_fold_heldout", + "cache_manifest": str( + (args.multifold_index.parent / f"{fold}_heldout.jsonl").resolve() + ), + "K_input_dropout": 0.0, + }] + path = args.output_dir / f"{condition.lower()}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + errors = validate_phase9_unified_contract(config, path) + if errors: + raise ValueError(f"invalid generated fold config {path}: {'; '.join(errors)}") + max_steps = int(config["protocol"]["max_steps"]) + conditions.append({ + "condition": condition, + "mixture": mixture, + "h2o_selection_fold": fold, + "config": str(path.resolve()), "config_sha256": sha256(path), + "initialization_checkpoint": str(args.initialization_checkpoint.resolve()), + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "output_dir": str((args.run_root / condition.lower()).resolve()), + "log_dir": str((args.run_root.parent / "queues" / "folds" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"scale{max_steps}", "stop_after_step": max_steps}, + ], + }) + registry = { + "schema_version": "phase9_h2o_multifold_training_queue_v1", + "status": "frozen_before_fold_training", + "created_utc": datetime.now(timezone.utc).isoformat(), + "multifold_index": { + "path": str(args.multifold_index.resolve()), + "sha256": sha256(args.multifold_index), + }, + "data_readiness_state": str(args.data_readiness_state.resolve()), + "data_finalize_plan_sha256": args.data_finalize_plan_sha256, + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "allowed_physical_gpus": [0, 1, 2, 3], + "prohibited_physical_gpus": [4, 5], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "conditions": conditions, + "shards": { + str(shard): [ + condition["condition"] for index, condition in enumerate(conditions) + if index % 3 == shard + ] + for shard in range(3) + }, + } + args.registry.parent.mkdir(parents=True, exist_ok=True) + args.registry.write_text(json.dumps(registry, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "registry": str(args.registry.resolve()), "sha256": sha256(args.registry), + "conditions": len(conditions), "shards": registry["shards"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_h2o_multifold.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_h2o_multifold.py new file mode 100644 index 0000000000000000000000000000000000000000..89dc683c2a03af0cb1fa1de79ebed7e7d3cf24bb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_h2o_multifold.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Build deterministic H2O official-train-only subject and family folds.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.audit_phase9_source_coverage import quantiles + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def family(row: dict[str, Any]) -> str: + parts = str(row["physical_recording_id"]).split("/") + if len(parts) < 2 or parts[1][:1] not in {"h", "k", "o"}: + raise ValueError("H2O recording lacks h/k/o family") + return parts[1][:1] + + +def fold_definitions(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + subjects = sorted({str(row["subject_id"]) for row in rows}) + families = sorted({family(row) for row in rows}) + if subjects != ["subject1", "subject2", "subject3"] or families != ["h", "k", "o"]: + raise ValueError("unexpected H2O official-train subjects or families") + definitions = [ + {"id": f"loso_{subject}", "axis": "subject", "heldout_value": subject} + for subject in subjects + ] + definitions.extend( + {"id": f"lofamily_{value}", "axis": "family", "heldout_value": value} + for value in families + ) + return definitions + + +def split_rows( + rows: list[dict[str, Any]], definition: dict[str, Any], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + if definition["axis"] == "subject": + heldout = [row for row in rows if row["subject_id"] == definition["heldout_value"]] + else: + heldout = [row for row in rows if family(row) == definition["heldout_value"]] + heldout_groups = {row["physical_recording_id"] for row in heldout} + train = [row for row in rows if row["physical_recording_id"] not in heldout_groups] + train_groups = {row["physical_recording_id"] for row in train} + if not train or not heldout or train_groups & heldout_groups: + raise ValueError("H2O fold is empty or leaks a physical recording") + if len(train) + len(heldout) != len(rows): + raise ValueError("H2O fold does not partition the cache") + return train, heldout + + +def numeric_stats(rows: list[dict[str, Any]]) -> dict[str, Any]: + side_frames = [0, 0] + hand_sizes: list[float] = [] + depths: list[float] = [] + for row in rows: + with np.load(row["cache_path"], allow_pickle=False) as archive: + valid_frame = archive["frame_valid"].astype(bool) + translation_valid = archive["translation_valid"].astype(bool) + translation = archive["wrist_root_translation"] + joint_valid = archive["joint2d_valid"].astype(bool) + joints = archive["joint2d"] + image_hw = archive["image_hw"] + height, width = int(image_hw[0]), int(image_hw[1]) + for time_index in np.flatnonzero(valid_frame): + for side in range(2): + if not translation_valid[time_index, side]: + continue + side_frames[side] += 1 + depths.append(float(translation[time_index, side, 2])) + points = joints[time_index, side] + valid = joint_valid[time_index, side] & np.isfinite(points).all(axis=-1) + valid &= ( + (points[:, 0] >= 0) & (points[:, 0] < width) + & (points[:, 1] >= 0) & (points[:, 1] < height) + ) + if valid.any(): + extent = points[valid].max(axis=0) - points[valid].min(axis=0) + hand_sizes.append(float(extent.max())) + return { + "left_hand_frames": side_frames[0], "right_hand_frames": side_frames[1], + "wrist_depth_m": quantiles(depths), + "projected_hand_size_px": quantiles(hand_sizes), + "family_clips": dict(sorted(Counter(family(row) for row in rows).items())), + } + + +def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + temporary.replace(path) + + +def build( + cache_manifest: Path, cache_report: Path, output_dir: Path, +) -> dict[str, Any]: + report = json.loads(cache_report.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" or report.get("dataset") != "H2O" + or report.get("split_role") != "official_train" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest) + ): + raise ValueError("H2O cache report is not an isolated official-train cache") + rows = [ + json.loads(line) for line in cache_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if len(rows) != 7000 or {row.get("dataset_id") for row in rows} != {"H2O"}: + raise ValueError("H2O multifold requires the canonical 7,000-clip cache") + output_dir.mkdir(parents=True, exist_ok=False) + folds = [] + for definition in fold_definitions(rows): + train, heldout = split_rows(rows, definition) + train_path = output_dir / f"{definition['id']}_train.jsonl" + heldout_path = output_dir / f"{definition['id']}_heldout.jsonl" + write_jsonl(train_path, train) + write_jsonl(heldout_path, heldout) + folds.append({ + **definition, + "train": {"path": str(train_path.resolve()), "sha256": sha256(train_path), + "clips": len(train), "recordings": len({row['physical_recording_id'] for row in train}), + **numeric_stats(train)}, + "heldout": {"path": str(heldout_path.resolve()), "sha256": sha256(heldout_path), + "clips": len(heldout), "recordings": len({row['physical_recording_id'] for row in heldout}), + **numeric_stats(heldout)}, + }) + return { + "schema_version": "phase9_h2o_train_multifold_v1", + "status": "complete", + "source_cache_manifest": {"path": str(cache_manifest.resolve()), "sha256": sha256(cache_manifest)}, + "selection_metrics": ["fold_macro_absolute_mpjpe", "worst_fold_absolute_mpjpe"], + "folds": folds, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--cache-report", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists() or args.output_dir.exists(): + parser.error("multifold output already exists") + try: + result = build(args.cache_manifest, args.cache_report, args.output_dir) + except (OSError, ValueError, KeyError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_hot_scale_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_hot_scale_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..02461a594c28ac7532731ee53ffecf3708076071 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_hot_scale_configs.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Generate matched J40 HOT10K/HOT50K data-volume configurations.""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +from pathlib import Path + +import yaml + +from scripts.train_phase7_external import validate_phase9_unified_contract + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--run-root", type=Path, required=True) + parser.add_argument("--data-readiness-state", type=Path, required=True) + parser.add_argument("--data-finalize-plan-sha256", required=True) + parser.add_argument("--initialization-checkpoint", type=Path, required=True) + parser.add_argument("--initialization-checkpoint-sha256", required=True) + parser.add_argument( + "--refresh", action="store_true", + help="Replace preregistered configs only when no training checkpoint exists.", + ) + args = parser.parse_args() + if (args.output_dir.exists() or args.registry.exists()) and not args.refresh: + parser.error("outputs must be new") + if args.refresh and args.run_root.exists() and any(args.run_root.rglob("*.pt")): + parser.error("cannot refresh HOT scale configs after a training checkpoint exists") + if sha256(args.initialization_checkpoint) != args.initialization_checkpoint_sha256: + parser.error("initialization checkpoint SHA256 differs") + base = yaml.safe_load(args.base_config.read_text(encoding="utf-8")) + if base["experiment"]["condition"] != "J40": + parser.error("base config must be J40") + args.output_dir.mkdir(parents=True, exist_ok=args.refresh) + hot_manifests = { + "J40_HOT10K": "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/hot3d_scale10000_v2/cache_manifest.jsonl", + "J40_HOT50K": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_50000_v1/cache_manifest.jsonl", + } + conditions = [] + for condition, hot_manifest in hot_manifests.items(): + config = copy.deepcopy(base) + config["name"] = f"phase9_{condition.lower()}_s20260717" + config["experiment"]["condition"] = condition + hot = next(source for source in config["data"]["sources"] if source["dataset"] == "HOT3D") + hot["cache_manifest"] = hot_manifest + path = args.output_dir / f"{condition.lower()}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + errors = validate_phase9_unified_contract(config, path) + if errors: + raise ValueError(f"invalid generated HOT scale config: {'; '.join(errors)}") + conditions.append({ + "condition": condition, "config": str(path.resolve()), + "config_sha256": sha256(path), + "initialization_checkpoint": str(args.initialization_checkpoint.resolve()), + "initialization_checkpoint_sha256": args.initialization_checkpoint_sha256, + "output_dir": str((args.run_root / condition.lower()).resolve()), + "log_dir": str((args.run_root.parent / "queues" / "hot_scale" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": "scale505k", "stop_after_step": 505000}, + ], + }) + registry = { + "schema_version": "phase9_hot_unique_scale_training_queue_v1", + "status": "frozen_before_hot_scale_training", + "data_readiness_state": str(args.data_readiness_state.resolve()), + "data_finalize_plan_sha256": args.data_finalize_plan_sha256, + "prerequisite_states": [ + {"condition": condition, "path": str( + (args.data_readiness_state.parent / f"{condition.lower()}_state.json").resolve() + )} for condition in ("J25", "J40", "J55") + ], + "allowed_physical_gpus": [0, 1, 2, 3], + "prohibited_physical_gpus": [4, 5], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + "conditions": conditions, + } + args.registry.write_text(json.dumps(registry, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "registry": str(args.registry.resolve()), "sha256": sha256(args.registry), + "conditions": [condition["condition"] for condition in conditions], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_last2_evaluation_plan.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_last2_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe26e4c5fc7553a82ce13c2dda94c111b6b189b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_last2_evaluation_plan.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Freeze one ordered last-2 candidate's 25 matched evaluations.""" + +from __future__ import annotations + +import argparse +import fcntl +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_evaluation_plan import ( + completed_training_jobs, + evaluation_record, +) +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_control_plan(path: Path, expected_sha256: str) -> dict[str, Any]: + if not path.is_file() or sha256(path) != expected_sha256: + raise ValueError("last-2 control evaluation plan differs") + plan = read_json(path) + if ( + plan.get("status") != "frozen_ready" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or len(plan.get("evaluations", [])) != 25 + ): + raise ValueError("last-2 control evaluation contract differs") + return plan + + +def build_plan( + *, candidate: str, training_controller_plan_path: Path, + training_controller_state_path: Path, output_root: Path, + worker_state_root: Path, distributed_assignment_path: Path, + distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or controller_state.get("h2o_official_validation_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("last-2 training controller is not complete and bound") + registry = read_json(registry_path) + if registry.get("candidate") != candidate: + raise ValueError("last-2 training registry candidate differs") + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + if candidate == "5e7": + control_path = Path(registry["base_evaluation_plan"]["path"]) + control_sha256 = registry["base_evaluation_plan"]["sha256"] + elif candidate == "1e6": + five_decision_path = Path(registry["five_e7_decision"]["path"]) + if ( + not five_decision_path.is_file() + or registry["five_e7_decision"]["sha256"] != sha256(five_decision_path) + ): + raise ValueError("conditional 1e-6 decision binding differs") + five_decision = read_json(five_decision_path) + control_path = Path(five_decision["evaluation_plan"]["path"]) + control_sha256 = five_decision["evaluation_plan"]["sha256"] + else: + raise ValueError("unknown last-2 evaluation candidate") + control = validate_control_plan(control_path, control_sha256) + control_items = {item["id"]: item for item in control["evaluations"]} + evaluations = [] + for identifier, control_item in control_items.items(): + role = control_item["training_role"] + job = jobs[role] + evaluations.append(evaluation_record( + evaluation_id=identifier, + job=job, + manifest=Path(control_item["cache_manifest"]), + mode=control_item["input_mode"], + role=control_item["evaluation_role"], + output=output_root / Path(control_item["output_dir"]).relative_to( + control["output_root"] + ), + )) + ids = [item["id"] for item in evaluations] + if len(ids) != 25 or len(set(ids)) != 25 or set(ids) != set(control_items): + raise ValueError("last-2 evaluation IDs differ from control") + control_reports = { + identifier: { + "path": str((Path(item["output_dir"]) / "evaluation.json").resolve()), + "sha256": sha256(Path(item["output_dir"]) / "evaluation.json"), + "evaluation_role": item["evaluation_role"], + "input_mode": item["input_mode"], + } + for identifier, item in control_items.items() + } + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_last2_evaluation_plan_v1", + "status": "frozen_ready", "candidate": candidate, + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "control_evaluation_plan": { + "path": str(control_path.resolve()), "sha256": control_sha256, + }, + "control_reports": control_reports, + "winner": registry["winner"], + "resolution_hw": registry["resolution_hw"], + "shared_augmentation": registry["shared_augmentation"], + "backbone_learning_rate": registry["backbone_learning_rate"], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "gate": "macro_and_worst_domain_must_both_strictly_improve", + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--candidate", choices=("5e7", "1e6"), required=True) + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + candidate=args.candidate, + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing last-2 evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_last2_evaluation_plan_state_v1", + "status": "failed_resumable", "candidate": args.candidate, + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_last2_evaluation_plan_state_v1", + "status": "complete", "candidate": args.candidate, + "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_last2_training_registry.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_last2_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..2a04b4420ca861e79c5a34cb4af9de021c0a7306 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_last2_training_registry.py @@ -0,0 +1,369 @@ +#!/usr/bin/env python3 +"""Freeze ordered DINO Base last-2 training registries after Stage 8.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.build_phase9_resolution_training_registry import ( + FOLDS, + atomic_json, + sha256, + write_config, +) +from scripts.train_phase7_external import validate_phase9_unified_contract + + +CANDIDATES = { + "5e7": {"phase9_stage": "last2_5e7", "backbone_learning_rate": 5e-7}, + "1e6": {"phase9_stage": "last2_1e6", "backbone_learning_rate": 1e-6}, +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_stage8( + controller_plan_path: Path, controller_state_path: Path, +) -> tuple[dict[str, Any], dict[str, Any], Path]: + state = read_json(controller_state_path) + decision_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(controller_plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not decision_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(decision_path) + ): + raise ValueError("Stage 8 decision controller is not complete and bound") + decision = read_json(decision_path) + evaluation_plan_path = Path(state.get("evaluation_plan", "")) + if ( + decision.get("status") != "complete" + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + or not evaluation_plan_path.is_file() + or state.get("evaluation_plan_sha256") != sha256(evaluation_plan_path) + or decision.get("evaluation_plan", {}).get("sha256") + != sha256(evaluation_plan_path) + ): + raise ValueError("Stage 8 decision/evaluation binding differs") + return decision, read_json(evaluation_plan_path), evaluation_plan_path + + +def selected_base( + stage8_decision: dict[str, Any], stage8_plan: dict[str, Any], + stage8_plan_path: Path, +) -> tuple[dict[str, Any], Path, str, bool]: + if stage8_decision["shared_augmentation_accepted"]: + base_plan = stage8_plan + base_plan_path = stage8_plan_path + mechanism = "shared_augmentation" + shared_augmentation = True + else: + preceding = stage8_decision["stage9_preceding_mechanism_gate"] + if ( + preceding.get("source_mechanism") != "resolution" + or preceding.get("stage9_last2_admitted") is not True + or stage8_plan.get("control", {}).get("kind") + != "resolution_896x512_candidate" + ): + raise ValueError("no selected preceding mechanism admits Stage 9") + base_plan_path = Path(stage8_plan["control"]["evaluation_plan"]["path"]) + if ( + not base_plan_path.is_file() + or stage8_plan["control"]["evaluation_plan"]["sha256"] + != sha256(base_plan_path) + ): + raise ValueError("selected resolution control plan differs") + base_plan = read_json(base_plan_path) + mechanism = "resolution" + shared_augmentation = False + if set(base_plan["training_jobs"]) != {"full", *FOLDS}: + raise ValueError("selected last-2 base training roles differ") + return base_plan, base_plan_path, mechanism, shared_augmentation + + +def derive_last2_config( + base: dict[str, Any], *, condition: str, candidate: str, + resolution_hw: list[int], shared_augmentation: bool, + stage8_decision_sha256: str, +) -> dict[str, Any]: + spec = CANDIDATES[candidate] + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = spec["phase9_stage"] + experiment["last2_resolution_hw"] = list(resolution_hw) + experiment["last2_shared_augmentation"] = bool(shared_augmentation) + experiment["stage8_decision_sha256"] = stage8_decision_sha256 + model = config["model"] + if model.get("encoder") != "dinov3": + raise ValueError("last-2 base does not use DINOv3") + if model.get("dinov3_model", "dinov3_vitb16") != "dinov3_vitb16": + raise ValueError("last-2 base is not DINO Base") + model["dinov3_trainable_last_blocks"] = 2 + config["protocol"]["backbone_learning_rate"] = spec[ + "backbone_learning_rate" + ] + return config + + +def validate_matched_last2( + base: dict[str, Any], derived: dict[str, Any], candidate: str, +) -> None: + for key in ("seed", "loss", "assets", "precision"): + if derived[key] != base[key]: + raise ValueError(f"last-2 config changes matched {key}") + base_model = deepcopy(base["model"]) + derived_model = deepcopy(derived["model"]) + base_model.pop("dinov3_trainable_last_blocks", None) + if derived_model.pop("dinov3_trainable_last_blocks", None) != 2: + raise ValueError("last-2 config does not train exactly two blocks") + if base_model != derived_model: + raise ValueError("last-2 config changes non-admitted model parameters") + base_protocol = deepcopy(base["protocol"]) + derived_protocol = deepcopy(derived["protocol"]) + base_protocol.pop("backbone_learning_rate", None) + actual_lr = derived_protocol.pop("backbone_learning_rate", None) + if actual_lr != CANDIDATES[candidate]["backbone_learning_rate"]: + raise ValueError("last-2 backbone learning rate differs") + if base_protocol != derived_protocol: + raise ValueError("last-2 config changes optimizer/scheduler horizon") + if derived["data"] != base["data"]: + raise ValueError("last-2 config changes data, mixture or augmentation") + + +def validate_conditional_1e6(path: Path | None) -> dict[str, Any]: + if path is None or not path.is_file(): + raise ValueError("1e-6 requires a frozen 5e-7 decision report") + report = read_json(path) + if ( + report.get("status") != "complete" + or report.get("candidate") != "5e7" + or report.get("gate", {}).get("macro_strictly_improved") is not True + or report.get("gate", {}).get("worst_domain_strictly_improved") is not True + or report.get("gate", {}).get("accepted") is not True + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError("5e-7 did not pass strict macro and worst-domain gates") + evaluation_plan = Path(report.get("evaluation_plan", {}).get("path", "")) + if ( + not evaluation_plan.is_file() + or report["evaluation_plan"].get("sha256") != sha256(evaluation_plan) + ): + raise ValueError("5e-7 decision evaluation plan differs") + return report + + +def build_registry( + *, candidate: str, stage8_controller_plan_path: Path, + stage8_controller_state_path: Path, last2_plan_path: Path, + output_root: Path, five_e7_decision_path: Path | None, +) -> dict[str, Any]: + if candidate not in CANDIDATES: + raise ValueError("unknown last-2 candidate") + stage8_decision, stage8_plan, stage8_plan_path = validate_stage8( + stage8_controller_plan_path, stage8_controller_state_path, + ) + decision_path = stage8_decision_path(stage8_controller_state_path) + preceding = stage8_decision["stage9_preceding_mechanism_gate"] + if preceding.get("stage9_last2_admitted") is not True: + raise ValueError("Stage 9 is not admitted by the preceding mechanism") + five_e7 = ( + validate_conditional_1e6(five_e7_decision_path) + if candidate == "1e6" else None + ) + base_plan, base_plan_path, mechanism, shared_augmentation = selected_base( + stage8_decision, stage8_plan, stage8_plan_path, + ) + resolution_hw = list(stage8_decision["resolution_hw"]) + if base_plan["resolution_hw"] != resolution_hw: + raise ValueError("last-2 base resolution differs from Stage 8 decision") + base_registry_path = Path(base_plan["training_registry"]["path"]) + if ( + not base_registry_path.is_file() + or base_plan["training_registry"]["sha256"] != sha256(base_registry_path) + ): + raise ValueError("last-2 base registry differs") + base_registry = read_json(base_registry_path) + last2_plan = read_json(last2_plan_path) + expected = last2_plan[ + "candidate_5e7" if candidate == "5e7" else "conditional_candidate_1e6" + ] + if ( + last2_plan.get("official_test_used") is not False + or expected.get("dinov3_trainable_last_blocks") != 2 + or float(expected.get("backbone_learning_rate")) + != CANDIDATES[candidate]["backbone_learning_rate"] + or last2_plan.get("dino_large") != "not_admitted" + ): + raise ValueError("frozen last-2 plan differs") + + target_step = int(base_registry["target_step"]) + label = candidate + config_root = output_root / label / "phase9" / "configs" + conditions = [] + for role in ("full", *FOLDS): + job = base_plan["training_jobs"][role] + config_path = Path(job["config"]) + if not config_path.is_file() or job["config_sha256"] != sha256(config_path): + raise ValueError(f"last-2 base config differs: {role}") + base = yaml.safe_load(config_path.read_text(encoding="utf-8")) + prefix = "S9L5" if candidate == "5e7" else "S9L10" + condition = f"{prefix}_{stage8_decision['winner'].split(':', 1)[0]}_{role}" + derived = derive_last2_config( + base, condition=condition, candidate=candidate, + resolution_hw=resolution_hw, + shared_augmentation=shared_augmentation, + stage8_decision_sha256=sha256(decision_path), + ) + validate_matched_last2(base, derived, candidate) + derived_path = config_root / f"{condition.lower()}.yaml" + errors = validate_phase9_unified_contract(derived, derived_path) + if errors: + raise ValueError("; ".join(errors)) + write_config(derived_path, derived) + run_dir = output_root / label / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"last-2 run exists before freeze: {run_dir}") + conditions.append({ + "condition": condition, "role": role, + "config": str(derived_path.resolve()), + "config_sha256": sha256(derived_path), + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / label / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": base_registry[ + "matched_source_exposure_batches" + ], + "expected_source_exposure_frames": base_registry[ + "matched_source_exposure_frames" + ], + }) + return { + "schema_version": "phase9_last2_training_registry_v1", + "status": "frozen_ready", "created_utc": stage8_decision["created_utc"], + "candidate": candidate, + "backbone_learning_rate": CANDIDATES[candidate]["backbone_learning_rate"], + "winner": stage8_decision["winner"], + "resolution_hw": resolution_hw, + "shared_augmentation": shared_augmentation, + "selected_preceding_mechanism": mechanism, + "stage8_decision": { + "path": str(decision_path.resolve()), + "sha256": sha256(decision_path), + }, + "base_evaluation_plan": { + "path": str(base_plan_path.resolve()), "sha256": sha256(base_plan_path), + }, + "base_training_registry": { + "path": str(base_registry_path.resolve()), "sha256": sha256(base_registry_path), + }, + "five_e7_decision": ( + {"path": str(five_e7_decision_path.resolve()), + "sha256": sha256(five_e7_decision_path)} + if five_e7 is not None else None + ), + "last2_plan": { + "path": str(last2_plan_path.resolve()), "sha256": sha256(last2_plan_path), + }, + "target_step": target_step, + "matched_source_exposure_batches": base_registry[ + "matched_source_exposure_batches" + ], + "matched_source_exposure_frames": base_registry[ + "matched_source_exposure_frames" + ], + "data_readiness_state": base_registry["data_readiness_state"], + "data_readiness_state_sha256": base_registry["data_readiness_state_sha256"], + "data_finalize_plan_sha256": base_registry["data_finalize_plan_sha256"], + "data_artifacts": base_registry["data_artifacts"], + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def stage8_decision_path(controller_state_path: Path) -> Path: + state = read_json(controller_state_path) + return Path(state["decision_report"]["path"]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--candidate", choices=tuple(CANDIDATES), required=True) + parser.add_argument("--stage8-controller-plan", type=Path, required=True) + parser.add_argument("--stage8-controller-state", type=Path, required=True) + parser.add_argument("--last2-plan", type=Path, required=True) + parser.add_argument("--five-e7-decision", type=Path) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + registry = build_registry( + candidate=args.candidate, + stage8_controller_plan_path=args.stage8_controller_plan, + stage8_controller_state_path=args.stage8_controller_state, + last2_plan_path=args.last2_plan, + output_root=args.output_root, + five_e7_decision_path=args.five_e7_decision, + ) + if args.output_registry.exists(): + if read_json(args.output_registry) != registry: + raise ValueError("existing last-2 training registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_last2_registry_state_v1", + "status": "failed_resumable", "candidate": args.candidate, + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_last2_registry_state_v1", + "status": "complete", "candidate": args.candidate, + "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_resolution_evaluation_plan.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_resolution_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..6817a02586ce001cae349a38ad3b8510e49cff7f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_resolution_evaluation_plan.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Freeze Stage 7 evaluations from completed matched-resolution training.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +EXTERNAL_MODES = { + "HOT3D": ("rgb_k", "rgb_only"), + "HOI4D": ("rgb_d_k", "rgb_k", "rgb_only"), + "ARCTIC": ("rgb_k", "rgb_only"), +} +EXTERNAL_CACHE_IDS = { + "HOT3D": "hot3d_heldout", + "HOI4D": "hoi4d_heldout", + "ARCTIC": "arctic_heldout", +} +H2O_MODES = ("rgb_d_k", "rgb_k", "rgb_only") + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def completed_training_jobs( + registry_path: Path, registry: dict[str, Any], state_root: Path, +) -> dict[str, dict[str, Any]]: + registry_hash = sha256(registry_path) + result = {} + for job in registry["conditions"]: + condition = job["condition"] + state_path = state_root / f"{condition.lower()}.json" + if not state_path.is_file(): + raise ValueError(f"resolution training state is missing: {condition}") + state = read_json(state_path) + marker = state.get("last_completed", {}) + checkpoint = Path(marker.get("checkpoint", "")) + if ( + state.get("status") != "complete" + or state.get("queue_sha256") != registry_hash + or state.get("official_test_used") is not False + or marker.get("completed_step") != registry["target_step"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + ): + raise ValueError(f"resolution training endpoint differs: {condition}") + result[job["role"]] = { + **job, + "state": str(state_path.resolve()), + "state_sha256": sha256(state_path), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": marker["checkpoint_sha256"], + "gpu_hours": state["gpu_hours_consumed"], + } + if set(result) != { + "full", "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + }: + raise ValueError("resolution training roles differ") + return result + + +def evaluation_record( + *, evaluation_id: str, job: dict[str, Any], manifest: Path, + mode: str, role: str, output: Path, +) -> dict[str, Any]: + config = Path(job["config"]) + if not config.is_file() or sha256(config) != job["config_sha256"]: + raise ValueError(f"resolution evaluation config differs: {evaluation_id}") + if not manifest.is_file(): + raise ValueError(f"resolution evaluation manifest missing: {evaluation_id}") + return { + "id": evaluation_id, + "training_role": job["role"], + "config": str(config.resolve()), + "config_sha256": job["config_sha256"], + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": sha256(manifest), + "input_mode": mode, + "evaluation_role": role, + "output_dir": str(output.resolve()), + } + + +def build_plan( + *, training_controller_plan_path: Path, training_controller_state_path: Path, + cache_plan_path: Path, output_root: Path, worker_state_root: Path, + distributed_assignment_path: Path, distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("resolution training controller is not complete and bound") + registry = read_json(registry_path) + if ( + registry.get("status") != "frozen_ready" + or registry.get("official_test_used") is not False + or registry.get("h2o_official_validation_used_for_selection") is not False + or registry.get("gate", {}).get("worst_domain_relative_regression_limit") + != controller_plan["worst_domain_relative_regression_limit"] + ): + raise ValueError("resolution training registry contract differs") + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + + cache_plan = read_json(cache_plan_path) + caches = {item["id"]: item for item in cache_plan["caches"]} + evaluations = [] + full = jobs["full"] + for dataset, modes in EXTERNAL_MODES.items(): + cache = caches[EXTERNAL_CACHE_IDS[dataset]] + manifest = Path(cache["manifest"]) + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=full, manifest=manifest, + mode=mode, role="phase9_external_heldout", + output=output_root / "full" / dataset.lower() / mode, + )) + for fold, job in jobs.items(): + if fold == "full": + continue + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + validation = config["data"].get("validation_sources", []) + if len(validation) != 1 or validation[0].get("dataset") != "H2O": + raise ValueError(f"resolution fold heldout differs: {fold}") + manifest = Path(validation[0]["cache_manifest"]) + for mode in H2O_MODES: + identifier = f"{fold}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=job, manifest=manifest, + mode=mode, role="phase9_h2o_fold_heldout", + output=output_root / "h2o" / fold / mode, + )) + ids = [item["id"] for item in evaluations] + outputs = [item["output_dir"] for item in evaluations] + if len(evaluations) != 25 or len(set(ids)) != 25 or len(set(outputs)) != 25: + raise ValueError("resolution evaluation IDs/outputs are not unique and complete") + + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_resolution_evaluation_plan_v1", + "status": "frozen_ready", + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "cache_execution_plan": { + "path": str(cache_plan_path.resolve()), "sha256": sha256(cache_plan_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "winner": registry["winner"], + "winner_checkpoint": registry["winner_checkpoint"], + "winner_config": registry["winner_config"], + "control_evidence": registry["control_evidence"], + "gate": registry["gate"], + "resolution_hw": [512, 896], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--cache-plan", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + cache_plan_path=args.cache_plan, output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing resolution evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_resolution_evaluation_plan_state_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_resolution_evaluation_plan_state_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_resolution_training_registry.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_resolution_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..3d10ab153ad63a19c9638d018c484bcd86b3254b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_resolution_training_registry.py @@ -0,0 +1,453 @@ +#!/usr/bin/env python3 +"""Freeze matched 896 training jobs from the selected 640 checkpoint.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +import re +from typing import Any + +import torch +import yaml + + +FOLDS = ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", +) +RESOLUTION_HW = [512, 896] +WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT = 0.01 +SOURCE_MANIFESTS = { + "H2O": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/h2o_train7000/cache_manifest.jsonl" + ), + "HOT3D": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/hot3d_train100000/cache_manifest.jsonl" + ), + "HOI4D": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/hoi4d_train37304_left_root/cache_manifest.jsonl" + ), + "ARCTIC": ( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/arctic_train21339_left_root/cache_manifest.jsonl" + ), +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_text(path: Path, value: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(value, encoding="utf-8") + temporary.replace(path) + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + atomic_text(path, json.dumps(value, indent=2) + "\n") + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def checkpoint_metadata( + path: Path, expected_sha256: str, expected_config_sha256: str, +) -> dict[str, Any]: + if not path.is_file() or sha256(path) != expected_sha256: + raise ValueError("selected 640 checkpoint hash differs") + payload = torch.load(path, map_location="cpu", weights_only=False) + extra = payload.get("extra", {}) + step = int(payload.get("step", -1)) + filename = re.search(r"step_(\d+)", path.name) + if ( + step <= 2000 + or filename is None + or int(filename.group(1)) != step + or extra.get("config_sha256") != expected_config_sha256 + or extra.get("official_test_used") is not False + or not extra.get("source_exposure_batches") + or not extra.get("external_initialization_checkpoint") + ): + raise ValueError("selected 640 checkpoint metadata differs") + return { + "step": step, + "source_exposure_batches": extra["source_exposure_batches"], + "source_exposure_frames": extra.get("source_exposure_frames", {}), + "completed_source_exposure_milestones": extra.get( + "completed_source_exposure_milestones", [] + ), + "initialization_checkpoint": extra["external_initialization_checkpoint"], + } + + +def derive_config( + base: dict[str, Any], *, condition: str, target_step: int, + h2o_train_manifest: str, h2o_heldout_manifest: str | None, + winner: str, winner_checkpoint_sha256: str, +) -> dict[str, Any]: + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = "resolution_896x512" + experiment["resolution_control_winner"] = winner + experiment["resolution_control_checkpoint_sha256"] = winner_checkpoint_sha256 + data = config["data"] + data["resolution_hw"] = list(RESOLUTION_HW) + for source in data["sources"]: + dataset = str(source["dataset"]).upper() + source["cache_manifest"] = ( + h2o_train_manifest if dataset == "H2O" else SOURCE_MANIFESTS[dataset] + ) + if h2o_heldout_manifest is None: + data.pop("validation_sources", None) + else: + validation = data.get("validation_sources", []) + if len(validation) != 1 or str(validation[0].get("dataset", "")).upper() != "H2O": + raise ValueError("fold base config lacks exactly one H2O heldout") + validation[0]["cache_manifest"] = h2o_heldout_manifest + return config + + +def validate_matched_config( + base: dict[str, Any], derived: dict[str, Any], target_step: int, +) -> None: + if ( + derived["seed"] != base["seed"] + or derived["model"] != base["model"] + or derived["loss"] != base["loss"] + or derived["assets"] != base["assets"] + or derived["precision"] != base["precision"] + or derived["data"]["T"] != base["data"]["T"] + or derived["data"]["batch_size"] != base["data"]["batch_size"] + or derived["data"].get("photometric_augmentation") + != base["data"].get("photometric_augmentation") + ): + raise ValueError("resolution config changes a matched model/data invariant") + base_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() if key != "cache_manifest" + } + for item in base["data"]["sources"] + } + derived_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() if key != "cache_manifest" + } + for item in derived["data"]["sources"] + } + if base_sources != derived_sources: + raise ValueError("resolution config changes source mixture or source settings") + if base["protocol"] != derived["protocol"]: + raise ValueError("resolution config changes optimizer/scheduler protocol") + + +def verify_readiness( + selection: dict[str, Any], readiness_path: Path, expected_plan_sha256: str, +) -> dict[str, Any]: + readiness = read_json(readiness_path) + audit_path = Path(readiness.get("audit", {}).get("path", "")) + if ( + readiness.get("status") != "complete" + or readiness.get("plan_sha256") != expected_plan_sha256 + or readiness.get("official_test_used") is not False + or readiness.get("h2o_official_validation_used") is not False + or readiness.get("winner") != selection.get("winner") + or readiness.get("winner_checkpoint") != selection.get("winner_checkpoint") + or readiness.get("winner_config") != selection.get("winner_config") + or not audit_path.is_file() + or readiness.get("audit", {}).get("sha256") != sha256(audit_path) + ): + raise ValueError("resolution cache readiness differs from selected winner") + audit = read_json(audit_path) + if ( + audit.get("status") != "complete" + or audit.get("plan_sha256") != expected_plan_sha256 + or audit.get("resolution_hw") != RESOLUTION_HW + or audit.get("official_test_used") is not False + or audit.get("h2o_official_validation_used") is not False + or not audit.get("multifold", {}).get("physical_recording_isolation") + or not audit.get("multifold", {}).get("deterministic_rebuild_hashes_match") + ): + raise ValueError("resolution cache audit differs") + return readiness + + +def write_config(path: Path, config: dict[str, Any]) -> None: + text = yaml.safe_dump(config, sort_keys=False, width=1000) + if path.exists(): + if path.read_text(encoding="utf-8") != text: + raise ValueError(f"existing resolution config differs: {path}") + return + atomic_text(path, text) + + +def build_registry( + *, selection_path: Path, readiness_path: Path, cache_plan_path: Path, + unified_queue_path: Path, fold_queue_path: Path, output_root: Path, +) -> dict[str, Any]: + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("unified selection is not complete and isolated") + cache_plan_sha256 = sha256(cache_plan_path) + readiness = verify_readiness(selection, readiness_path, cache_plan_sha256) + + winner = str(selection["winner"]) + mixture = winner.split(":", 1)[0] + if mixture not in {"J25", "J40", "J55"}: + raise ValueError("selected winner mixture is unknown") + winner_row = next( + (row for row in selection["candidates"] if row["id"] == winner), None + ) + if ( + winner_row is None + or winner_row.get("checkpoint") != selection["winner_checkpoint"] + or winner_row.get("config") != selection["winner_config"] + ): + raise ValueError("selected winner row is missing") + + unified_queue = read_json(unified_queue_path) + fold_queue = read_json(fold_queue_path) + full_job = next( + (item for item in unified_queue["conditions"] if item["condition"] == mixture), + None, + ) + if full_job is None: + raise ValueError("selected mixture is missing from the full-data queue") + selected_config = selection["winner_config"] + if ( + Path(selected_config["path"]).resolve() != Path(full_job["config"]).resolve() + or selected_config["sha256"] != full_job["config_sha256"] + or sha256(full_job["config"]) != full_job["config_sha256"] + ): + raise ValueError("selected config differs from the frozen full-data queue") + metadata = checkpoint_metadata( + Path(selection["winner_checkpoint"]["path"]), + selection["winner_checkpoint"]["sha256"], + selected_config["sha256"], + ) + initialization = metadata["initialization_checkpoint"] + initialization_path = Path(full_job["initialization_checkpoint"]) + if ( + Path(initialization.get("path", "")).resolve() + != initialization_path.resolve() + or initialization.get("sha256") != full_job["initialization_checkpoint_sha256"] + or not initialization_path.is_file() + or sha256(initialization_path) != full_job["initialization_checkpoint_sha256"] + ): + raise ValueError("selected checkpoint initialization differs") + + multifold = read_json( + output_root / "manifests" / "h2o_multifold_index.json" + ) + if ( + multifold.get("status") != "complete" + or multifold.get("official_test_used") is not False + or multifold.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution multifold index is not complete and isolated") + folds = {item["id"]: item for item in multifold["folds"]} + if set(folds) != set(FOLDS): + raise ValueError("resolution multifold IDs differ") + + config_root = output_root / "phase9" / "configs" + conditions = [] + base_full = yaml.safe_load(Path(full_job["config"]).read_text(encoding="utf-8")) + job_specs: list[tuple[str, dict[str, Any], str, str | None]] = [ + ("full", base_full, SOURCE_MANIFESTS["H2O"], None) + ] + fold_jobs = {item["condition"]: item for item in fold_queue["conditions"]} + for fold in FOLDS: + condition_id = f"{mixture}_{fold}" + if condition_id not in fold_jobs: + raise ValueError(f"selected mixture fold config is missing: {fold}") + base = yaml.safe_load( + Path(fold_jobs[condition_id]["config"]).read_text(encoding="utf-8") + ) + job_specs.append(( + fold, base, folds[fold]["train"]["path"], folds[fold]["heldout"]["path"] + )) + + target_step = int(metadata["step"]) + for role, base, h2o_train, h2o_heldout in job_specs: + condition = f"S7R_{mixture}_{role}" + config = derive_config( + base, condition=condition, target_step=target_step, + h2o_train_manifest=h2o_train, h2o_heldout_manifest=h2o_heldout, + winner=winner, + winner_checkpoint_sha256=selection["winner_checkpoint"]["sha256"], + ) + validate_matched_config(base, config, target_step) + config_path = config_root / f"{condition.lower()}.yaml" + write_config(config_path, config) + run_dir = output_root / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"resolution run output exists before registry freeze: {run_dir}") + conditions.append({ + "condition": condition, + "role": role, + "config": str(config_path.resolve()), + "config_sha256": sha256(config_path), + "initialization_checkpoint": full_job["initialization_checkpoint"], + "initialization_checkpoint_sha256": full_job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": metadata["source_exposure_batches"], + "expected_source_exposure_frames": metadata["source_exposure_frames"], + }) + + manifests = {} + for dataset, path in SOURCE_MANIFESTS.items(): + manifests[dataset] = {"path": path, "sha256": sha256(path)} + cache_plan = read_json(cache_plan_path) + artifact_paths = { + Path(item["manifest"]).resolve() for item in cache_plan["caches"] + } | { + Path(item["manifest"]).resolve() for item in cache_plan["sidecars"] + } | { + Path(cache_plan["multifold"]["index"]).resolve(), + } + for fold in folds.values(): + artifact_paths.add(Path(fold["train"]["path"]).resolve()) + artifact_paths.add(Path(fold["heldout"]["path"]).resolve()) + data_artifacts = [ + {"path": str(path), "sha256": sha256(path)} + for path in sorted(artifact_paths) + ] + registry = { + "schema_version": "phase9_resolution_training_registry_v1", + "status": "frozen_ready", + "created_utc": readiness["completed_utc"], + "winner": winner, + "winner_checkpoint": selection["winner_checkpoint"], + "winner_config": selection["winner_config"], + "control_evidence": winner_row, + "target_step": target_step, + "matched_source_exposure_batches": metadata["source_exposure_batches"], + "matched_source_exposure_frames": metadata["source_exposure_frames"], + "completed_source_exposure_milestones": metadata[ + "completed_source_exposure_milestones" + ], + "resolution_hw": RESOLUTION_HW, + "data_readiness_state": str(readiness_path.resolve()), + "data_readiness_state_sha256": sha256(readiness_path), + "data_finalize_plan_sha256": cache_plan_sha256, + "data_artifacts": data_artifacts, + "source_manifests": manifests, + "selection_report": { + "path": str(selection_path.resolve()), "sha256": sha256(selection_path), + }, + "cache_execution_plan": { + "path": str(cache_plan_path.resolve()), "sha256": cache_plan_sha256, + }, + "gate": { + "macro_absolute_mm_must_strictly_improve": True, + "worst_domain_relative_regression_limit": ( + WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT + ), + }, + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + return registry + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-report", type=Path, required=True) + parser.add_argument("--readiness-state", type=Path, required=True) + parser.add_argument("--cache-plan", type=Path, required=True) + parser.add_argument("--unified-queue", type=Path, required=True) + parser.add_argument("--fold-queue", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.state.is_file(): + state = read_json(args.state) + if state.get("status") == "complete": + if ( + args.output_registry.is_file() + and state.get("registry_sha256") == sha256(args.output_registry) + ): + print(json.dumps(state, indent=2)) + return + parser.error("completed resolution registry state differs") + try: + registry = build_registry( + selection_path=args.selection_report, + readiness_path=args.readiness_state, + cache_plan_path=args.cache_plan, + unified_queue_path=args.unified_queue, + fold_queue_path=args.fold_queue, + output_root=args.output_root, + ) + if args.output_registry.exists(): + existing = read_json(args.output_registry) + if existing != registry: + raise ValueError("existing resolution training registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_resolution_training_registry_state_v1", + "status": "failed_resumable", + "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_resolution_training_registry_state_v1", + "status": "complete", + "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "winner": registry["winner"], + "winner_checkpoint": registry["winner_checkpoint"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_selection_binding_recovery_plan.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_selection_binding_recovery_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..429d2680d06f834a198213ceaf1c0bf978888527 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_selection_binding_recovery_plan.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Freeze canonical re-evaluations for Phase 9 selection path mismatches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def canonical_config(condition: str) -> Path: + return Path( + "/home/jiasen/foundation_hand/artifacts/phase9/registry/fold_configs" + ) / f"{condition.lower()}.yaml" + + +def build_plan( + *, assignment_path: Path, audit_path: Path, selection_plan_path: Path, + failure_backup_root: Path, +) -> dict[str, Any]: + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + audit = json.loads(audit_path.read_text(encoding="utf-8")) + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + assignment_hash = sha256(assignment_path) + if ( + assignment.get("status") + != "frozen_before_distributed_recovery_or_stage7_work" + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + or audit.get("status") != "complete_path_only_recovery_required" + or audit.get("distributed_assignment", {}).get("sha256") + != assignment_hash + or audit.get("selection_plan", {}).get("sha256") + != sha256(selection_plan_path) + or selection_plan.get("official_test_used") is not False + ): + raise ValueError("selection recovery source contract differs") + assigned = { + item["id"]: item + for item in assignment["phase9_selection_recovery"]["evaluations"] + } + if len(assigned) != 11 or set(assigned) != set(audit["mismatch_ids"]): + raise ValueError("selection recovery assignment IDs differ") + records_by_id = {item["id"]: item for item in audit["records"]} + evaluations = [] + for identifier in sorted(assigned): + source = records_by_id[identifier] + owner_record = assigned[identifier] + if source.get("binding_status") != "path_mismatch_content_identical": + raise ValueError(f"recovery is not path-only: {identifier}") + config = canonical_config(source["condition"]) + if ( + not config.is_file() + or sha256(config) != source["config"]["declared_sha256"] + ): + raise ValueError(f"canonical config differs: {identifier}") + checkpoint = Path(source["checkpoint"]["path"]) + checkpoint_hash = source["checkpoint"]["declared_sha256"] + manifest = Path(source["cache_manifest"]["expected_path"]) + manifest_hash = source["cache_manifest"]["expected_sha256"] + if ( + not checkpoint.is_file() or sha256(checkpoint) != checkpoint_hash + or not manifest.is_file() or sha256(manifest) != manifest_hash + ): + raise ValueError(f"canonical recovery input differs: {identifier}") + owner = owner_record["owner"] + root = Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + determinism = source["determinism"] + evaluations.append({ + "id": identifier, + "owner": owner, + "physical_gpu_id": owner_record["physical_gpu_id"], + "condition": source["condition"], + "checkpoint_id": source["checkpoint_id"], + "input_mode": "rgb_d_k", + "evaluation_role": "phase9_h2o_fold_heldout", + "config": str(config.resolve()), + "config_sha256": sha256(config), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_hash, + "cache_manifest": str(manifest.resolve()), + "cache_manifest_sha256": manifest_hash, + "output_dir": str(( + root / "evaluations" / source["condition"] + / source["checkpoint_id"] / "rgb_d_k" + ).resolve()), + "prior_report": source["report"], + "expected_sample_counts": source["sample_counts"], + "expected_determinism": { + "metrics_sha256": determinism["metrics_sha256"], + "grouped_bootstrap_ci_sha256": determinism[ + "grouped_bootstrap_ci_sha256" + ], + "raw_predictions_sha256": determinism[ + "raw_predictions" + ]["declared_sha256"], + "per_hand_rows_sha256": determinism[ + "per_hand_rows" + ]["declared_sha256"], + "take_metrics_sha256": determinism[ + "take_metrics" + ]["declared_sha256"], + }, + }) + workers = [] + for owner in ("taku3", "server_new"): + allowlist = assignment["machines"][owner]["physical_gpu_allowlist"] + for gpu in allowlist: + ids = [ + item["id"] for item in evaluations + if item["owner"] == owner and item["physical_gpu_id"] == gpu + ] + if not ids: + continue + root = Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + workers.append({ + "id": f"{owner}_gpu{gpu}", "owner": owner, + "physical_gpu_id": gpu, + "state": str((root / "states" / f"gpu{gpu}.json").resolve()), + "log": str((root / "logs" / f"gpu{gpu}.log").resolve()), + "evaluation_ids": ids, + }) + assigned_ids = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(evaluations) != 11 + or len(assigned_ids) != 11 + or len(set(assigned_ids)) != 11 + or set(assigned_ids) != set(assigned) + ): + raise ValueError("selection recovery workers are not disjoint and complete") + backup_files = {} + for name in ( + "unified_selection_state.json", "unified_selection.log", + "unified_selection_watcher.log", + ): + path = failure_backup_root / name + if not path.is_file(): + raise ValueError(f"selection failure backup missing: {path}") + backup_files[name] = sha256(path) + repository = assignment_path.resolve().parents[3] + code_paths = [ + repository / "scripts/evaluate_phase7_external.py", + repository / "scripts/summarize_phase9_unified_selection.py", + repository / "scripts/run_phase9_selection_binding_recovery.py", + repository / "scripts/finalize_phase9_selection_binding_recovery.py", + repository / "scripts/merge_phase9_selection_binding_recovery.py", + ] + code_bindings = [] + for path in code_paths: + if not path.is_file(): + raise ValueError(f"selection recovery code missing: {path}") + code_bindings.append({"path": str(path), "sha256": sha256(path)}) + return { + "schema_version": "phase9_selection_binding_recovery_plan_v2", + "status": "frozen_before_recovery_evaluation", + "reason": "migration_path_binding_differs_with_identical_manifest_sha256", + "scientific_failure": False, + "resource_scheduling_amendment_only": True, + "distributed_assignment": { + "path": str(assignment_path.resolve()), "sha256": assignment_hash, + }, + "mismatch_manifest": { + "path": str(audit_path.resolve()), "sha256": sha256(audit_path), + }, + "selection_plan": { + "path": str(selection_plan_path.resolve()), + "sha256": sha256(selection_plan_path), + }, + "failure_backup": { + "root": str(failure_backup_root.resolve()), + "files": backup_files, + }, + "code_bindings": code_bindings, + "release_manifests": { + owner: str((Path( + assignment["phase9_selection_recovery"][ + f"{owner}_recovery_root" + ] + ) / "release_manifest.json").resolve()) + for owner in ("taku3", "server_new") + }, + "canonical_fold_milestone_root": selection_plan["fold_milestone_root"], + "dry_run_root": "/SSD2/jiasen/foundation_hand/phase9_artifacts/selection_binding_recovery_v2/dry_run", + "canonical_merge_state": "/SSD2/jiasen/foundation_hand/phase9_artifacts/selection_binding_recovery_v2/merge_state.json", + "canonical_merge_backup_root": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/recovery_backups/selection_binding_v2_20260731", + "selection_state": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/unified_selection_state.json", + "selection_log": "/SSD3/jiasen/foundation_hand/phase9_artifacts/queues/unified_selection.log", + "evaluations": evaluations, + "workers": workers, + "bootstrap_resamples": 2000, + "requirements": [ + "evaluate only assigned mismatches in new recovery roots", + "bind canonical config manifest checkpoint and expected SHA256", + "validate sample counts role isolation metrics and artifact determinism", + "run temporary JSON and CSV summarizer before canonical merge", + "atomically replace each mismatched canonical output under one merge lock", + "preserve failed selection and replaced output evidence" + ], + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--audit", type=Path, required=True) + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--failure-backup-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("recovery plan output must be new") + result = build_plan( + assignment_path=args.assignment, audit_path=args.audit, + selection_plan_path=args.selection_plan, + failure_backup_root=args.failure_backup_root, + ) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_shared_augmentation_evaluation_plan.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_shared_augmentation_evaluation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..e381262202ce3e6f36fd1a7cbc71286aa7b745ca --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_shared_augmentation_evaluation_plan.py @@ -0,0 +1,282 @@ +#!/usr/bin/env python3 +"""Freeze Stage 8 evaluations after shared-augmentation training completes.""" + +from __future__ import annotations + +import argparse +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.build_phase9_resolution_evaluation_plan import ( + EXTERNAL_MODES, + H2O_MODES, + completed_training_jobs, + evaluation_record, +) +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.phase9_distributed_assignment import ( + distribute_evaluations, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +HELDOUT_640 = { + "HOT3D": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hot3d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "HOI4D": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/hoi4d_heldout2048_fullgroups_v2/cache_manifest.jsonl", + "ARCTIC": "/SSD3/jiasen/foundation_hand/phase9_artifacts/cache/arctic_val2048_fullgroups_v2/cache_manifest.jsonl", +} +HELDOUT_896_IDS = { + "HOT3D": "hot3d_heldout", "HOI4D": "hoi4d_heldout", + "ARCTIC": "arctic_heldout", +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def control_reports_896(registry: dict[str, Any]) -> dict[str, dict[str, str]]: + path = Path(registry["control"]["evaluation_plan"]["path"]) + if ( + not path.is_file() + or registry["control"]["evaluation_plan"]["sha256"] != sha256(path) + ): + raise ValueError("Stage 8 896 control evaluation plan differs") + plan = read_json(path) + reports = {} + for item in plan["evaluations"]: + reports[item["id"]] = { + "path": str((Path(item["output_dir"]) / "evaluation.json").resolve()), + "evaluation_role": item["evaluation_role"], + "input_mode": item["input_mode"], + } + return reports + + +def control_reports_640(registry: dict[str, Any]) -> dict[str, dict[str, str]]: + control = registry["control"]["control_evidence"] + mixture = control["mixture"] + external_id = control["external_checkpoint_id"] + fold_id = control["fold_checkpoint_id"] + external_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/external_milestones" + ) + final_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold" + ) + milestone_root = Path( + "/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold_milestones" + ) + reports = {} + for dataset, modes in EXTERNAL_MODES.items(): + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + reports[identifier] = { + "path": str(( + external_root / mixture / external_id + / f"{dataset.lower()}_{mode}" / "evaluation.json" + ).resolve()), + "evaluation_role": "phase9_external_heldout", + "input_mode": mode, + } + for fold in FOLDS: + condition = f"{mixture}_{fold}" + for mode in H2O_MODES: + path = ( + final_root / condition / mode / "evaluation.json" + if fold_id == "final" + else milestone_root / condition / fold_id / mode / "evaluation.json" + ) + reports[f"{fold}_{mode}"] = { + "path": str(path.resolve()), + "evaluation_role": "phase9_h2o_fold_heldout", + "input_mode": mode, + } + return reports + + +def validate_control_reports(reports: dict[str, dict[str, str]]) -> None: + if len(reports) != 25: + raise ValueError("Stage 8 control report count differs") + for identifier, item in reports.items(): + path = Path(item["path"]) + if not path.is_file(): + raise ValueError(f"Stage 8 control report missing: {identifier}") + report = read_json(path) + if ( + report.get("status") != f"evaluated_{item['evaluation_role']}" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"Stage 8 control report differs: {identifier}") + item["sha256"] = sha256(path) + + +def build_plan( + *, training_controller_plan_path: Path, training_controller_state_path: Path, + resolution_cache_plan_path: Path, output_root: Path, worker_state_root: Path, + distributed_assignment_path: Path, distributed_assignment_sha256: str, +) -> dict[str, Any]: + assignment = load_assignment({"distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }}) + controller_plan = read_json(training_controller_plan_path) + controller_state = read_json(training_controller_state_path) + registry_path = Path(controller_state.get("training_registry", "")) + if ( + controller_state.get("status") != "complete" + or controller_state.get("plan_sha256") != sha256(training_controller_plan_path) + or controller_state.get("official_test_used") is not False + or controller_state.get("h2o_official_validation_used") is not False + or not registry_path.is_file() + or controller_state.get("training_registry_sha256") != sha256(registry_path) + ): + raise ValueError("shared augmentation training is not complete and bound") + registry = read_json(registry_path) + jobs = completed_training_jobs( + registry_path, registry, Path(controller_plan["training_state_root"]), + ) + resolution_hw = registry["resolution_hw"] + if resolution_hw == [512, 896]: + cache_plan = read_json(resolution_cache_plan_path) + cache_by_id = {item["id"]: item for item in cache_plan["caches"]} + heldouts = { + dataset: Path(cache_by_id[identifier]["manifest"]) + for dataset, identifier in HELDOUT_896_IDS.items() + } + control_reports = control_reports_896(registry) + elif resolution_hw == [368, 640]: + heldouts = {dataset: Path(path) for dataset, path in HELDOUT_640.items()} + control_reports = control_reports_640(registry) + else: + raise ValueError("shared augmentation resolution differs") + validate_control_reports(control_reports) + + evaluations = [] + full = jobs["full"] + for dataset, modes in EXTERNAL_MODES.items(): + for mode in modes: + identifier = f"full_{dataset.lower()}_{mode}" + evaluations.append(evaluation_record( + evaluation_id=identifier, job=full, manifest=heldouts[dataset], + mode=mode, role="phase9_external_heldout", + output=output_root / "full" / dataset.lower() / mode, + )) + for fold in FOLDS: + job = jobs[fold] + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + validation = config["data"].get("validation_sources", []) + if len(validation) != 1 or validation[0].get("dataset") != "H2O": + raise ValueError(f"augmentation fold heldout differs: {fold}") + manifest = Path(validation[0]["cache_manifest"]) + for mode in H2O_MODES: + evaluations.append(evaluation_record( + evaluation_id=f"{fold}_{mode}", job=job, manifest=manifest, + mode=mode, role="phase9_h2o_fold_heldout", + output=output_root / "h2o" / fold / mode, + )) + ids = [item["id"] for item in evaluations] + if len(ids) != 25 or len(set(ids)) != 25: + raise ValueError("shared augmentation evaluation IDs differ") + workers = distribute_evaluations( + evaluations=evaluations, assignment=assignment, + worker_state_root=worker_state_root, + ) + return { + "schema_version": "phase9_shared_augmentation_evaluation_plan_v1", + "status": "frozen_ready", + "created_utc": controller_state["completed_utc"], + "training_controller_plan": { + "path": str(training_controller_plan_path.resolve()), + "sha256": sha256(training_controller_plan_path), + }, + "training_controller_state": { + "path": str(training_controller_state_path.resolve()), + "sha256": sha256(training_controller_state_path), + }, + "training_registry": { + "path": str(registry_path.resolve()), "sha256": sha256(registry_path), + }, + "distributed_assignment": { + "path": str(distributed_assignment_path.resolve()), + "sha256": distributed_assignment_sha256, + }, + "winner": registry["winner"], + "resolution_hw": resolution_hw, + "resolution_decision": registry["resolution_decision"], + "control": registry["control"], + "control_reports": control_reports, + "gate": registry["gate"], + "training_jobs": jobs, + "evaluations": evaluations, + "workers": workers, + "output_root": str(output_root.resolve()), + "worker_heartbeat_seconds": 30, + "evaluator_progress_heartbeat_seconds": 30, + "stall_timeout_seconds": 900, + "max_attempts_per_evaluation": 2, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--training-controller-plan", type=Path, required=True) + parser.add_argument("--training-controller-state", type=Path, required=True) + parser.add_argument("--resolution-cache-plan", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--worker-state-root", type=Path, required=True) + parser.add_argument("--distributed-assignment", type=Path, required=True) + parser.add_argument("--distributed-assignment-sha256", required=True) + parser.add_argument("--output-plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + plan = build_plan( + training_controller_plan_path=args.training_controller_plan, + training_controller_state_path=args.training_controller_state, + resolution_cache_plan_path=args.resolution_cache_plan, + output_root=args.output_root, + worker_state_root=args.worker_state_root, + distributed_assignment_path=args.distributed_assignment, + distributed_assignment_sha256=args.distributed_assignment_sha256, + ) + if args.output_plan.exists(): + if read_json(args.output_plan) != plan: + raise ValueError("existing augmentation evaluation plan differs") + else: + atomic_json(args.output_plan, plan) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_eval_plan_state_v1", + "status": "failed_resumable", "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_shared_augmentation_eval_plan_state_v1", + "status": "complete", "plan": str(args.output_plan.resolve()), + "plan_sha256": sha256(args.output_plan), + "evaluation_count": len(plan["evaluations"]), + "worker_count": len(plan["workers"]), + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_shared_augmentation_training_registry.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_shared_augmentation_training_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..5867d7bdf6a01d537e221a7d5d1c01f6c0b2d69f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_phase9_shared_augmentation_training_registry.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Freeze Stage 8 shared-augmentation jobs after the resolution decision.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +from typing import Any + +import yaml + +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS +from scripts.build_phase9_resolution_training_registry import ( + FOLDS, + atomic_json, + checkpoint_metadata, + sha256, + write_config, +) +from scripts.train_phase7_external import validate_phase9_unified_contract + + +GEOMETRY_AUGMENTATION = { + "enabled": True, + "probability": 0.8, + "scale_min": 0.9, + "scale_max": 1.1, + "translation_fraction": 0.05, +} +DEPTH_CORRUPTION_DATASETS = {"H2O", "HOI4D"} +WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT = 0.01 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def derive_augmentation_config( + base: dict[str, Any], *, condition: str, resolution_hw: list[int], + resolution_decision_sha256: str, +) -> dict[str, Any]: + config = deepcopy(base) + config["name"] = condition.lower() + experiment = config["experiment"] + experiment["condition"] = condition + experiment["phase9_stage"] = ( + "shared_augmentation_896x512" + if resolution_hw == [512, 896] + else "shared_augmentation_640" + ) + experiment["resolution_decision_sha256"] = resolution_decision_sha256 + data = config["data"] + if data["resolution_hw"] != resolution_hw: + raise ValueError("augmentation base config resolution differs") + data["geometry_augmentation"] = deepcopy(GEOMETRY_AUGMENTATION) + for source in data["sources"]: + dataset = str(source["dataset"]).upper() + source["depth_corruption_probability"] = ( + 0.3 if dataset in DEPTH_CORRUPTION_DATASETS else 0.0 + ) + return config + + +def validate_matched_augmentation( + base: dict[str, Any], derived: dict[str, Any], resolution_hw: list[int], +) -> None: + if ( + derived["seed"] != base["seed"] + or derived["model"] != base["model"] + or derived["loss"] != base["loss"] + or derived["assets"] != base["assets"] + or derived["precision"] != base["precision"] + or derived["protocol"] != base["protocol"] + or derived["data"]["resolution_hw"] != resolution_hw + or derived["data"]["T"] != base["data"]["T"] + or derived["data"]["batch_size"] != base["data"]["batch_size"] + or derived["data"].get("photometric_augmentation") + != base["data"].get("photometric_augmentation") + or derived["data"].get("validation_sources") + != base["data"].get("validation_sources") + ): + raise ValueError("augmentation config changes a matched invariant") + base_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() + if key != "depth_corruption_probability" + } + for item in base["data"]["sources"] + } + derived_sources = { + str(item["dataset"]).upper(): { + key: value for key, value in item.items() + if key != "depth_corruption_probability" + } + for item in derived["data"]["sources"] + } + if base_sources != derived_sources: + raise ValueError("augmentation config changes source mixture/manifests") + if derived["data"]["geometry_augmentation"] != GEOMETRY_AUGMENTATION: + raise ValueError("augmentation affine parameters differ") + + +def data_artifacts_from_configs(configs: list[dict[str, Any]]) -> list[dict[str, str]]: + paths = set() + for config in configs: + for source in config["data"]["sources"]: + paths.add(Path(source["cache_manifest"]).resolve()) + for source in config["data"].get("validation_sources", []): + paths.add(Path(source["cache_manifest"]).resolve()) + return [ + {"path": str(path), "sha256": sha256(path)} for path in sorted(paths) + ] + + +def base_jobs_896( + resolution_state: dict[str, Any], decision: dict[str, Any], +) -> tuple[dict[str, dict[str, Any]], dict[str, Any]]: + evaluation_plan_path = Path(resolution_state["evaluation_plan"]) + if ( + not evaluation_plan_path.is_file() + or resolution_state.get("evaluation_plan_sha256") + != sha256(evaluation_plan_path) + ): + raise ValueError("accepted 896 evaluation plan differs") + evaluation_plan = read_json(evaluation_plan_path) + registry_path = Path(evaluation_plan["training_registry"]["path"]) + if evaluation_plan["training_registry"]["sha256"] != sha256(registry_path): + raise ValueError("accepted 896 training registry differs") + registry = read_json(registry_path) + jobs = { + role: { + "role": role, + "config": job["config"], + "config_sha256": job["config_sha256"], + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + } + for role, job in registry_job_map(registry).items() + } + context = { + "target_step": registry["target_step"], + "source_exposure_batches": registry["matched_source_exposure_batches"], + "source_exposure_frames": registry["matched_source_exposure_frames"], + "data_readiness_state": registry["data_readiness_state"], + "data_readiness_state_sha256": registry["data_readiness_state_sha256"], + "data_finalize_plan_sha256": registry["data_finalize_plan_sha256"], + "data_artifacts": registry["data_artifacts"], + "control": { + "kind": "resolution_896x512_candidate", + "evaluation_plan": { + "path": str(evaluation_plan_path.resolve()), + "sha256": sha256(evaluation_plan_path), + }, + "decision_report": decision, + }, + } + return jobs, context + + +def registry_job_map(registry: dict[str, Any]) -> dict[str, dict[str, Any]]: + result = {item["role"]: item for item in registry["conditions"]} + if set(result) != {"full", *FOLDS}: + raise ValueError("seven matched control roles differ") + return result + + +def base_jobs_640( + decision: dict[str, Any], unified_queue_path: Path, fold_queue_path: Path, + selection_path: Path, +) -> tuple[dict[str, dict[str, Any]], dict[str, Any]]: + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("winner") != decision.get("winner") + or selection.get("winner_checkpoint") != decision.get("control_checkpoint") + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("retained 640 selection evidence differs") + mixture = selection["winner"].split(":", 1)[0] + unified = read_json(unified_queue_path) + folds = read_json(fold_queue_path) + full = next(item for item in unified["conditions"] if item["condition"] == mixture) + if ( + Path(selection["winner_config"]["path"]).resolve() + != Path(full["config"]).resolve() + or selection["winner_config"]["sha256"] != full["config_sha256"] + ): + raise ValueError("retained 640 winner config differs from its mixture") + metadata = checkpoint_metadata( + Path(selection["winner_checkpoint"]["path"]), + selection["winner_checkpoint"]["sha256"], + selection["winner_config"]["sha256"], + ) + initialization = metadata["initialization_checkpoint"] + if ( + Path(initialization.get("path", "")).resolve() + != Path(full["initialization_checkpoint"]).resolve() + or initialization.get("sha256") != full["initialization_checkpoint_sha256"] + ): + raise ValueError("retained 640 initialization differs") + jobs = { + "full": { + "role": "full", "config": full["config"], + "config_sha256": full["config_sha256"], + "initialization_checkpoint": full["initialization_checkpoint"], + "initialization_checkpoint_sha256": full[ + "initialization_checkpoint_sha256" + ], + } + } + fold_jobs = {item["condition"]: item for item in folds["conditions"]} + for fold in FOLDS: + item = fold_jobs[f"{mixture}_{fold}"] + jobs[fold] = { + "role": fold, "config": item["config"], + "config_sha256": item["config_sha256"], + "initialization_checkpoint": full["initialization_checkpoint"], + "initialization_checkpoint_sha256": full[ + "initialization_checkpoint_sha256" + ], + } + readiness = Path(unified["data_readiness_state"]) + if not readiness.is_file(): + raise ValueError("retained 640 data readiness is missing") + configs = [ + yaml.safe_load(Path(item["config"]).read_text(encoding="utf-8")) + for item in jobs.values() + ] + context = { + "target_step": metadata["step"], + "source_exposure_batches": metadata["source_exposure_batches"], + "source_exposure_frames": metadata["source_exposure_frames"], + "data_readiness_state": str(readiness.resolve()), + "data_readiness_state_sha256": sha256(readiness), + "data_finalize_plan_sha256": unified["data_finalize_plan_sha256"], + "data_artifacts": data_artifacts_from_configs(configs), + "control": { + "kind": "frozen_640_winner", + "selection_report": { + "path": str(selection_path.resolve()), "sha256": sha256(selection_path), + }, + "control_evidence": next( + item for item in selection["candidates"] + if item["id"] == selection["winner"] + ), + "decision_report": decision, + }, + } + return jobs, context + + +def build_registry( + *, resolution_controller_plan_path: Path, + resolution_controller_state_path: Path, augmentation_plan_path: Path, + unified_queue_path: Path, fold_queue_path: Path, selection_path: Path, + output_root: Path, +) -> dict[str, Any]: + resolution_plan = read_json(resolution_controller_plan_path) + resolution_state = read_json(resolution_controller_state_path) + decision_path = Path(resolution_state.get("decision_report", {}).get("path", "")) + if ( + resolution_state.get("status") != "complete" + or resolution_state.get("plan_sha256") != sha256(resolution_controller_plan_path) + or resolution_state.get("official_test_used") is not False + or resolution_state.get("h2o_official_validation_used") is not False + or Path(resolution_plan["decision_report"]).resolve() != decision_path.resolve() + or not decision_path.is_file() + or resolution_state.get("decision_report", {}).get("sha256") + != sha256(decision_path) + ): + raise ValueError("resolution decision controller is not complete and bound") + decision = read_json(decision_path) + if ( + decision.get("status") != "complete" + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution decision report is not complete and isolated") + resolution_hw = decision["accepted_resolution_hw"] + if resolution_hw not in ([368, 640], [512, 896]): + raise ValueError("resolution decision value differs") + augmentation_plan = read_json(augmentation_plan_path) + if ( + augmentation_plan.get("official_test_used") is not False + or { + key: value for key, value in augmentation_plan.get("candidate", {}).get( + "geometry_augmentation", {} + ).items() if key in GEOMETRY_AUGMENTATION + } != GEOMETRY_AUGMENTATION + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "applicable_sources" + ) != ["H2O", "HOI4D"] + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "probability" + ) != 0.3 + or augmentation_plan.get("candidate", {}).get("depth_corruption", {}).get( + "conditions" + ) != list(DEPTH_CORRUPTIONS) + ): + raise ValueError("shared augmentation frozen plan differs") + + if resolution_hw == [512, 896]: + base_jobs, context = base_jobs_896(resolution_state, decision) + else: + base_jobs, context = base_jobs_640( + decision, unified_queue_path, fold_queue_path, selection_path, + ) + mixture = decision["winner"].split(":", 1)[0] + resolution_label = "896x512" if resolution_hw == [512, 896] else "640x368" + config_root = output_root / resolution_label / "phase9" / "configs" + conditions = [] + base_configs = [] + for role in ("full", *FOLDS): + job = base_jobs[role] + path = Path(job["config"]) + if not path.is_file() or sha256(path) != job["config_sha256"]: + raise ValueError(f"augmentation base config differs: {role}") + base = yaml.safe_load(path.read_text(encoding="utf-8")) + condition = f"S8A_{mixture}_{role}" + derived = derive_augmentation_config( + base, condition=condition, resolution_hw=resolution_hw, + resolution_decision_sha256=sha256(decision_path), + ) + validate_matched_augmentation(base, derived, resolution_hw) + config_path = config_root / f"{condition.lower()}.yaml" + errors = validate_phase9_unified_contract(derived, config_path) + if errors: + raise ValueError("; ".join(errors)) + write_config(config_path, derived) + run_dir = output_root / resolution_label / "runs" / condition.lower() + if run_dir.exists(): + raise ValueError(f"augmentation run exists before freeze: {run_dir}") + target_step = int(context["target_step"]) + conditions.append({ + "condition": condition, "role": role, + "config": str(config_path.resolve()), "config_sha256": sha256(config_path), + "initialization_checkpoint": job["initialization_checkpoint"], + "initialization_checkpoint_sha256": job[ + "initialization_checkpoint_sha256" + ], + "output_dir": str(run_dir.resolve()), + "log_dir": str((output_root / resolution_label / "queues" / condition.lower()).resolve()), + "stages": [ + {"id": "smoke2", "stop_after_step": 2}, + {"id": "health2k", "stop_after_step": 2000}, + {"id": f"matched_{target_step}", "stop_after_step": target_step}, + ], + "expected_source_exposure_batches": context[ + "source_exposure_batches" + ], + "expected_source_exposure_frames": context["source_exposure_frames"], + }) + base_configs.append(base) + data_artifacts = data_artifacts_from_configs(base_configs) + context_artifacts = { + item["path"]: item["sha256"] for item in context["data_artifacts"] + } + if any( + context_artifacts.get(item["path"]) != item["sha256"] + for item in data_artifacts + ): + raise ValueError("augmentation data artifacts differ from control") + # Preserve the stronger control set, including heldout and fold-index hashes. + data_artifacts = context["data_artifacts"] + return { + "schema_version": "phase9_shared_augmentation_training_registry_v1", + "status": "frozen_ready", + "created_utc": decision["created_utc"], + "winner": decision["winner"], + "resolution_hw": resolution_hw, + "resolution_decision": { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + }, + "shared_augmentation_plan": { + "path": str(augmentation_plan_path.resolve()), + "sha256": sha256(augmentation_plan_path), + }, + "control": context["control"], + "target_step": context["target_step"], + "matched_source_exposure_batches": context["source_exposure_batches"], + "matched_source_exposure_frames": context["source_exposure_frames"], + "data_readiness_state": context["data_readiness_state"], + "data_readiness_state_sha256": context["data_readiness_state_sha256"], + "data_finalize_plan_sha256": context["data_finalize_plan_sha256"], + "data_artifacts": data_artifacts, + "gate": { + "macro_absolute_mm_must_strictly_improve": True, + "worst_domain_relative_regression_limit": ( + WORST_DOMAIN_RELATIVE_REGRESSION_LIMIT + ), + "stage9_preceding_mechanism_requires_worst_strict_improvement": True, + }, + "allowed_physical_gpus": [0, 1, 2, 3, 4, 5], + "conditions": conditions, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--resolution-controller-plan", type=Path, required=True) + parser.add_argument("--resolution-controller-state", type=Path, required=True) + parser.add_argument("--augmentation-plan", type=Path, required=True) + parser.add_argument("--unified-queue", type=Path, required=True) + parser.add_argument("--fold-queue", type=Path, required=True) + parser.add_argument("--selection-report", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--output-registry", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + registry = build_registry( + resolution_controller_plan_path=args.resolution_controller_plan, + resolution_controller_state_path=args.resolution_controller_state, + augmentation_plan_path=args.augmentation_plan, + unified_queue_path=args.unified_queue, + fold_queue_path=args.fold_queue, + selection_path=args.selection_report, + output_root=args.output_root, + ) + if args.output_registry.exists(): + if read_json(args.output_registry) != registry: + raise ValueError("existing augmentation registry differs") + else: + atomic_json(args.output_registry, registry) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_registry_state_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "failure": f"{type(error).__name__}: {error}", + "official_test_used": False, + }) + raise + state = { + "schema_version": "phase9_shared_augmentation_registry_state_v1", + "status": "complete", "completed_utc": utc_now(), + "registry": str(args.output_registry.resolve()), + "registry_sha256": sha256(args.output_registry), + "conditions": [item["condition"] for item in registry["conditions"]], + "resolution_hw": registry["resolution_hw"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_sota_ground_truth.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_sota_ground_truth.py new file mode 100644 index 0000000000000000000000000000000000000000..d859aa4924bd3147b0a16d71a3f7164a13e2f25e --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/build_sota_ground_truth.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Build the immutable H2O GT bundle shared by all SOTA baseline evaluations.""" + +from __future__ import annotations + +import argparse +import hashlib +from pathlib import Path + +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import ( + load_float_record, + load_joint_record, + load_mano_record, +) +from foundation_hand.evaluation.sota import GroundTruthBundle, load_frame_index +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models.mano import ManoCameraLayer + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=256) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + keys, takes, frame_ids = load_frame_index(args.manifest) + count = len(keys) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + pose = np.zeros((count, 2, 48), dtype=np.float32) + shape = np.zeros((count, 2, 10), dtype=np.float32) + valid = np.zeros((count, 2), dtype=bool) + intrinsics = np.zeros((count, 3, 3), dtype=np.float32) + intrinsics_cache: dict[str, np.ndarray] = {} + + for index, (take_name, frame_id) in enumerate(zip(takes, frame_ids, strict=True)): + take = args.root / str(take_name) + stem = f"{int(frame_id):06d}" + joint_record = load_joint_record(take / "hand_pose" / f"{stem}.txt") + mano_record = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + if not np.array_equal(joint_record.annotation_valid, mano_record.annotation_valid): + raise ValueError(f"Joint/MANO validity mismatch: {keys[index]}") + valid[index] = joint_record.annotation_valid + joints[index] = joint_record.joints_camera_m + pose[index] = mano_record.pose_axis_angle + shape[index] = mano_record.shape + if str(take_name) not in intrinsics_cache: + values = load_float_record(take / "cam_intrinsics.txt") + intrinsics_cache[str(take_name)] = intrinsics_from_h2o(values)[0] + intrinsics[index] = intrinsics_cache[str(take_name)] + + joints[~valid] = np.nan + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + device = torch.device(args.device) + mano = ManoCameraLayer(args.mano_root).to(device).eval() + for start in range(0, count, args.batch_size): + end = min(start + args.batch_size, count) + pose_tensor = torch.from_numpy(pose[start:end]).to(device) + shape_tensor = torch.from_numpy(shape[start:end]).to(device) + wrist_tensor = torch.from_numpy(np.nan_to_num(joints[start:end, :, 0])).to(device) + with torch.no_grad(): + batch_vertices, _ = mano( + axis_angle_to_matrix(pose_tensor.reshape(end - start, 2, 16, 3)), + shape_tensor, + wrist_tensor, + ) + vertices[start:end] = batch_vertices.cpu().numpy() + vertices[~valid] = np.nan + + bundle = GroundTruthBundle( + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + annotation_valid=valid, + intrinsics=intrinsics, + metadata={ + "source": "H2O official validation cam4", + "official_test_used": False, + "manifest": str(args.manifest.resolve()), + "manifest_sha256": sha256(args.manifest), + "frames": count, + "runs": len(args.manifest.read_text(encoding="utf-8").splitlines()), + "takes": len(set(map(str, takes.tolist()))), + "joint_order": "H2O/OpenPose wrist-thumb-index-middle-ring-pinky", + "units": "meters", + }, + ) + bundle.save(args.output) + print(f"saved {count} frames to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase4_jitter_predictions.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase4_jitter_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..c638edc649e36a24ec91b04ad2594e22ffe09fcd --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase4_jitter_predictions.py @@ -0,0 +1,399 @@ +#!/usr/bin/env python3 +"""Cache hash-bound raw official-validation predictions for jitter evaluation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +CACHE_VERSION = 1 +FPS = 30.0 +FRAME_ARRAYS = ( + "clip_index", + "frame_id", + "frame_valid", + "K", + "pred_rotation_matrices", + "pred_shape", + "pred_wrist_translation", + "pred_joints_camera", + "pred_vertices_camera", + "pred_direct_2d_px", + "target_rotation_matrices", + "target_shape", + "target_wrist_translation", + "target_joints_camera", + "target_vertices_camera", + "target_2d_px", + "joint_annotation_valid", + "joint_element_valid", + "mano_annotation_valid", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def take_slug(take: str) -> str: + parts = Path(take).parts + if len(parts) != 4 or parts[-1] != "cam4": + raise ValueError(f"unexpected H2O take: {take}") + return "__".join(parts) + + +def manifest_frame_count(path: Path) -> int: + identities: set[tuple[str, int]] = set() + rows = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + record = json.loads(line) + take = str(record["take"]) + for frame_id in record["frame_ids"]: + identity = (take, int(frame_id)) + if identity in identities: + raise ValueError(f"duplicate manifest frame: {take}/{int(frame_id)}") + identities.add(identity) + rows += 1 + if rows == 0: + raise ValueError("prediction cache manifest is empty") + return rows + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def apply_input_condition( + batch: dict[str, Any], condition: str, +) -> dict[str, Any]: + if condition == "complete": + return batch + model_batch = dict(batch) + if condition == "missing_depth": + model_batch["depth_available"] = torch.zeros_like(batch["depth_available"]) + model_batch["depth_m"] = torch.zeros_like(batch["depth_m"]) + model_batch["depth_pixel_valid"] = torch.zeros_like(batch["depth_pixel_valid"]) + return model_batch + if condition == "missing_k": + model_batch["K_available"] = torch.zeros_like(batch["K_available"]) + identity = torch.eye(3, dtype=batch["K"].dtype, device=batch["K"].device) + model_batch["K"] = identity.expand_as(batch["K"]).clone() + return model_batch + raise ValueError(f"unsupported input condition: {condition}") + + +def target_geometry( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for jitter cache targets") + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, joints = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + return rotations, vertices, joints + + +def validate_cache_arrays( + arrays: dict[str, np.ndarray], + *, + take: str, + expected_frame_ids: list[int], + checkpoint_sha256: str, + config_sha256: str, + manifest_sha256: str, + input_condition: str = "complete", +) -> None: + missing = sorted(set(FRAME_ARRAYS) - arrays.keys()) + if missing: + raise ValueError(f"raw jitter cache is missing arrays: {missing}") + if int(arrays["cache_version"]) != CACHE_VERSION: + raise ValueError("raw jitter cache version mismatch") + scalar_expectations = { + "take": take, + "checkpoint_sha256": checkpoint_sha256, + "config_sha256": config_sha256, + "manifest_sha256": manifest_sha256, + } + for key, expected in scalar_expectations.items(): + if str(arrays[key]) != expected: + raise ValueError(f"raw jitter cache {key} mismatch") + if input_condition != "complete" and str(arrays.get("input_condition", "")) != input_condition: + raise ValueError("raw jitter cache input condition mismatch") + frame_ids = arrays["frame_id"].astype(np.int64).tolist() + if frame_ids != expected_frame_ids or len(frame_ids) != len(set(frame_ids)): + raise ValueError(f"raw jitter cache frame sequence mismatch for {take}") + for key in FRAME_ARRAYS: + if arrays[key].shape[0] != len(frame_ids): + raise ValueError(f"raw jitter cache time dimension mismatch: {key}") + if np.issubdtype(arrays[key].dtype, np.floating): + finite = np.isfinite(arrays[key]) + if key.startswith("target_"): + # Invalid annotations are intentionally retained as NaN. + continue + if not finite.all(): + raise ValueError(f"raw jitter cache prediction is non-finite: {key}") + + +def load_valid_cache( + path: Path, + **expected: object, +) -> dict[str, np.ndarray] | None: + if not path.is_file(): + return None + try: + with np.load(path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + validate_cache_arrays(arrays, **expected) + except (OSError, KeyError, ValueError): + return None + return arrays + + +def build_model( + config: dict[str, Any], checkpoint: Path, device: torch.device, +) -> tuple[BimanualReconstructionModel, int]: + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(checkpoint, model, optimizer=None, map_location=device) + return model, int(state["step"]) + + +def infer_take( + *, + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + input_condition: str, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = defaultdict(list) + subset = Subset(dataset, clip_indices) + loader = DataLoader( + subset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + for global_clip_index, batch_cpu in zip(clip_indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + target_rotations, target_vertices, _ = target_geometry(batch, model) + model_batch = apply_input_condition(batch, input_condition) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(model_batch) + valid_times = int(batch["frame_valid"][0].sum()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor( + (width, height), device=device, + ) + values: dict[str, torch.Tensor] = { + "clip_index": torch.full( + (valid_times,), global_clip_index, device=device, dtype=torch.int64, + ), + "frame_id": batch["frame_id"][0, :valid_times], + "frame_valid": batch["frame_valid"][0, :valid_times], + "K": batch["K"][0, :valid_times], + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0, :valid_times], + "pred_shape": prediction["mano_shape"][0, :valid_times], + "pred_wrist_translation": prediction["wrist_root_translation"][0, :valid_times], + "pred_joints_camera": prediction["joints_camera"][0, :valid_times], + "pred_vertices_camera": prediction["vertices_camera"][0, :valid_times], + "pred_direct_2d_px": direct_2d[0, :valid_times], + "target_rotation_matrices": target_rotations[0, :valid_times], + "target_shape": batch["mano_shape"][0, :valid_times], + "target_wrist_translation": batch["wrist_root_translation"][0, :valid_times], + "target_joints_camera": batch["joint3d_camera"][0, :valid_times], + "target_vertices_camera": target_vertices[0, :valid_times], + "target_2d_px": batch["joint2d"][0, :valid_times], + "joint_annotation_valid": batch["joint_annotation_valid"][0, :valid_times], + "joint_element_valid": batch["joint_element_valid"][0, :valid_times], + "mano_annotation_valid": batch["mano_annotation_valid"][0, :valid_times], + } + for key, value in values.items(): + array = value.detach().float().cpu().numpy() if value.is_floating_point() else value.cpu().numpy() + chunks[key].append(array) + return {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), default=0) + parser.add_argument("--max-clips", type=int) + parser.add_argument( + "--input-condition", choices=("complete", "missing_depth", "missing_k"), + default="complete", + ) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("jitter cache is hard-gated to official validation") + if args.max_clips is not None and args.max_clips < 1: + parser.error("--max-clips must be positive") + if not torch.cuda.is_available(): + parser.error("CUDA is required") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + config_hash = sha256(args.config) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (int(config["data"]["T"]),), (int(config["data"]["stride"]),), + max_clips=args.max_clips, + oracle_crop_enabled=config["model"].get("oracle_crop_mode", "none") != "none", + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + expected_frames = { + take: [ + frame_id + for index in indices + for frame_id in dataset.clips[index].frame_ids + ] + for take, indices in indices_by_take.items() + } + if any(len(values) != len(set(values)) for values in expected_frames.values()): + raise ValueError("jitter cache requires non-overlapping inference clips") + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model: BimanualReconstructionModel | None = None + checkpoint_step: int | None = None + records = [] + for take_index, (take, clip_indices) in enumerate(indices_by_take.items(), start=1): + output = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "manifest_sha256": manifest_hash, + "input_condition": args.input_condition, + } + arrays = load_valid_cache(output, **expected) + status = "reused" + if arrays is None: + if output.exists(): + raise ValueError(f"existing jitter cache failed validation: {output}") + if model is None: + model, checkpoint_step = build_model(config, args.checkpoint, device) + arrays = infer_take( + dataset=dataset, clip_indices=clip_indices, model=model, + device=device, dtype=dtype, input_condition=args.input_condition, + ) + arrays.update({ + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + "take": np.asarray(take), + "fps": np.asarray(FPS, dtype=np.float32), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "manifest_sha256": np.asarray(manifest_hash), + "input_condition": np.asarray(args.input_condition), + }) + validate_cache_arrays(arrays, **expected) + save_npz_atomic(output, arrays) + status = "written" + records.append({ + "take": take, "clips": len(clip_indices), + "frames": len(expected_frames[take]), "path": str(output), + "sha256": sha256(output), "status": status, + }) + print( + f"[{take_index}/{len(indices_by_take)}] {take}: " + f"{records[-1]['frames']} frames ({status})", + flush=True, + ) + if checkpoint_step is None: + # Read the step only when every cache was reused. + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + checkpoint_step = int(state["step"]) + total_frames = sum(record["frames"] for record in records) + full_validation = args.max_clips is None + expected_full_frames = manifest_frame_count(args.manifest) + if full_validation and total_frames != expected_full_frames: + raise ValueError( + "official-validation cache does not cover every manifest frame exactly once" + ) + report = { + "status": "complete", + "official_test_used": False, + "split_role": "official_validation", + "scope": "full" if full_validation else "smoke", + "fps": FPS, + "temporal_length": int(config["data"]["T"]), + "clip_boundary_filter_reset_required": True, + "input_condition": args.input_condition, + "missing_rgb_status": "unsupported_no_rgb_availability_or_training_dropout", + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": checkpoint_step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, + stdout=subprocess.PIPE, check=False, + ).stdout.strip(), + "clips": len(dataset), "frames": total_frames, + "expected_manifest_frames": expected_full_frames, "takes": records, + } + (args.output_dir / "cache_manifest.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "clips": report["clips"], + "frames": report["frames"], "takes": len(records), + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase6_sequence_predictions.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase6_sequence_predictions.py new file mode 100644 index 0000000000000000000000000000000000000000..5914ff7c6988c0f4da8b47b226fbbf1b7c0337e7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase6_sequence_predictions.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Cache bounded-window Phase 6 sequence predictions in the frozen raw schema.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +from collections import defaultdict +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from scripts.cache_phase4_jitter_predictions import ( + CACHE_VERSION, + FPS, + build_model, + load_valid_cache, + manifest_frame_count, + move_to_device, + save_npz_atomic, + sha256, + take_slug, + target_geometry, + validate_cache_arrays, +) + + +def validate_sequence_config(config: dict, mode: str) -> None: + """Validate model causality; frame iteration itself always supplies T=1.""" + + attention_mode = config["model"].get("temporal_attention_mode", "bidirectional") + expected_attention = "causal" if mode == "causal" else "bidirectional" + if attention_mode != expected_attention: + raise ValueError("sequence mode differs from config temporal attention mode") + + +def offline_stride(window: int, mode: str) -> int | None: + return max(window // 2, 1) if mode == "offline" else None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--max-takes", type=int) + args = parser.parse_args() + if args.manifest.name != "official_val.jsonl": + parser.error("sequence cache is hard-gated to official validation") + if args.window < 1: + parser.error("window must be positive") + if args.max_takes is not None and args.max_takes < 1: + parser.error("max-takes must be positive") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + try: + validate_sequence_config(config, args.mode) + except ValueError as error: + parser.error(str(error)) + + config_hash = sha256(args.config) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(config["data"]["resolution_hw"]), + (1,), (1,), + ) + indices_by_take: dict[str, list[int]] = defaultdict(list) + for index, clip in enumerate(dataset.clips): + indices_by_take[clip.take].append(index) + if args.max_takes is not None: + indices_by_take = dict(list(indices_by_take.items())[: args.max_takes]) + expected_frames = { + take: [dataset.clips[index].frame_ids[0] for index in indices] + for take, indices in indices_by_take.items() + } + if any(len(ids) != len(set(ids)) for ids in expected_frames.values()): + raise ValueError("sequence cache input contains duplicate take/frame identities") + + args.output_dir.mkdir(parents=True, exist_ok=True) + device = torch.device(f"cuda:{args.gpu}") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model = None + checkpoint_step = None + records = [] + maximum_gpu_window = 0 + maximum_cpu_buffer = 0 + for take_index, (take, indices) in enumerate(indices_by_take.items(), start=1): + output_path = args.output_dir / "takes" / f"{take_slug(take)}.npz" + expected = { + "take": take, + "expected_frame_ids": expected_frames[take], + "checkpoint_sha256": checkpoint_hash, + "config_sha256": config_hash, + "manifest_sha256": manifest_hash, + "input_condition": "complete", + } + arrays = load_valid_cache(output_path, **expected) + status = "reused" + if arrays is None: + if output_path.exists(): + raise ValueError(f"existing sequence cache failed validation: {output_path}") + if model is None: + model, checkpoint_step = build_model(config, args.checkpoint, device) + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.mode, window_size=args.window, + offline_stride=offline_stride(args.window, args.mode), + ), + device=device, autocast_dtype=dtype, + ) + target_chunks: dict[str, list[np.ndarray]] = defaultdict(list) + loader = DataLoader( + Subset(dataset, indices), batch_size=1, shuffle=False, + num_workers=0, collate_fn=collate_h2o_clips, pin_memory=True, + ) + + def frames(): + for global_index, batch_cpu in zip(indices, loader, strict=True): + batch = move_to_device(batch_cpu, device) + rotations, vertices, _ = target_geometry(batch, model) + values = { + # One output file is one continuous take. Frame gaps and + # frame_valid, not the source dataset index, delimit segments. + "clip_index": np.asarray([0], dtype=np.int64), + "frame_id": batch_cpu["frame_id"][0].numpy(), + "frame_valid": batch_cpu["frame_valid"][0].numpy(), + "K": batch_cpu["K"][0].numpy(), + "target_rotation_matrices": rotations[0].float().cpu().numpy(), + "target_shape": batch_cpu["mano_shape"][0].numpy(), + "target_wrist_translation": batch_cpu["wrist_root_translation"][0].numpy(), + "target_joints_camera": batch_cpu["joint3d_camera"][0].numpy(), + "target_vertices_camera": vertices[0].float().cpu().numpy(), + "target_2d_px": batch_cpu["joint2d"][0].numpy(), + "joint_annotation_valid": batch_cpu["joint_annotation_valid"][0].numpy(), + "joint_element_valid": batch_cpu["joint_element_valid"][0].numpy(), + "mano_annotation_valid": batch_cpu["mano_annotation_valid"][0].numpy(), + } + for key, value in values.items(): + target_chunks[key].append(value) + yield batch_cpu + + prediction = runner.infer(frames()) + height, width = config["data"]["resolution_hw"] + predicted = { + "pred_rotation_matrices": prediction["mano_rotation_matrices"][0].float().numpy(), + "pred_shape": prediction["mano_shape"][0].float().numpy(), + "pred_wrist_translation": prediction["wrist_root_translation"][0].float().numpy(), + "pred_joints_camera": prediction["joints_camera"][0].float().numpy(), + "pred_vertices_camera": prediction["vertices_camera"][0].float().numpy(), + "pred_direct_2d_px": ( + prediction["joint2d_norm"][0].float() + * torch.tensor((width, height)) + ).numpy(), + } + arrays = { + **{key: np.concatenate(values, axis=0) for key, values in target_chunks.items()}, + **predicted, + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + "take": np.asarray(take), + "fps": np.asarray(FPS, dtype=np.float32), + "checkpoint_sha256": np.asarray(checkpoint_hash), + "config_sha256": np.asarray(config_hash), + "manifest_sha256": np.asarray(manifest_hash), + "input_condition": np.asarray("complete"), + "sequence_mode": np.asarray(args.mode), + "sequence_window": np.asarray(args.window, dtype=np.int32), + } + validate_cache_arrays(arrays, **expected) + save_npz_atomic(output_path, arrays) + maximum_gpu_window = max(maximum_gpu_window, runner.maximum_resident_frames) + maximum_cpu_buffer = max(maximum_cpu_buffer, runner.maximum_input_buffer_frames) + status = "written" + records.append({ + "take": take, "clips": len(indices), "frames": len(expected_frames[take]), + "path": str(output_path), "sha256": sha256(output_path), "status": status, + }) + print(f"[{take_index}/{len(indices_by_take)}] {take} ({status})", flush=True) + + if checkpoint_step is None: + state = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + checkpoint_step = int(state["step"]) + total_frames = sum(record["frames"] for record in records) + expected_total = ( + manifest_frame_count(args.manifest) if args.max_takes is None + else sum(len(frame_ids) for frame_ids in expected_frames.values()) + ) + if total_frames != expected_total: + raise ValueError("sequence cache does not cover the frozen manifest exactly") + report = { + "status": "complete", + "experiment": "P6_S5_length_generalized_inference", + "official_test_used": False, + "official_validation_used_for_selection": False, + "split_role": "official_validation", + "scope": "full" if args.max_takes is None else "smoke", + "fps": FPS, + "temporal_length": 1, + "sequence_mode": args.mode, + "sequence_window": args.window, + "offline_stride": offline_stride(args.window, args.mode), + "stitching": "center" if args.mode == "offline" else None, + "maximum_gpu_window_frames": maximum_gpu_window, + "maximum_cpu_input_buffer_frames": maximum_cpu_buffer, + "input_condition": "complete", + "config": {"path": str(args.config.resolve()), "sha256": config_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": checkpoint_step, + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + check=False, + ).stdout.strip(), + "clips": len(dataset), "frames": total_frames, + "expected_manifest_frames": expected_total, "takes": records, + } + (args.output_dir / "cache_manifest.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "mode": args.mode, "window": args.window, + "frames": total_frames, "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase7_h2o_train.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase7_h2o_train.py new file mode 100644 index 0000000000000000000000000000000000000000..14a83bba28b96456e9238ece26d398545cc921eb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase7_h2o_train.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Build a bounded canonical cache from H2O official train only.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import math +from pathlib import Path +import time + +import numpy as np + +from foundation_hand.data import H2OCam4Dataset +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from scripts.cache_phase7_hot3d import ( + validate_cached_resolution, + validated_target_hw, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_train_manifest_path(path: Path) -> None: + if path.name != "official_train.jsonl": + raise ValueError("H2O adaptation cache requires canonical official_train.jsonl") + + +def center_out(values: list[int]) -> list[int]: + values = sorted(values) + center = (len(values) - 1) // 2 + order = [center] + distance = 1 + while len(order) < len(values): + if center + distance < len(values): + order.append(center + distance) + if center - distance >= 0: + order.append(center - distance) + distance += 1 + return [values[index] for index in order] + + +def balanced_clip_indices( + clips: list, count: int, max_recordings: int, +) -> list[int]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, clip in enumerate(clips): + parts = Path(clip.take).parts + groups[(parts[0], "/".join(parts[:-1]))].append(index) + strata: dict[str, list[tuple[str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[0]].append(key) + selected_groups: list[tuple[str, str]] = [] + cursor = 0 + while len(selected_groups) < min(max_recordings, len(groups)): + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected_groups.append(strata[subject][cursor]) + progress = True + if len(selected_groups) == max_recordings: + break + if not progress: + break + cursor += 1 + ordered = {key: center_out(groups[key]) for key in selected_groups} + selected = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in selected_groups: + if cursor < len(ordered[key]): + selected.append(ordered[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def rgb_uint8(rgb: np.ndarray) -> np.ndarray: + image = np.transpose(rgb, (0, 2, 3, 1)) + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int, required=True) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument("--resume", action="store_true") + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + validate_train_manifest_path(args.source_manifest) + if min(args.clips, args.max_recordings) <= 0: + parser.error("clip and recording counts must be positive") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + dataset = H2OCam4Dataset( + args.root, args.source_manifest, target_hw=target_hw, + clip_lengths=(8,), strides=(1,), + ) + candidate_count = min( + len(dataset), args.clips + max(32, math.ceil(args.clips * 0.1)), + ) + selected = balanced_clip_indices(dataset.clips, candidate_count, args.max_recordings) + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced H2O train clips are available") + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", "vertices_camera", + } + cached: dict[int, dict] = {} + skipped: list[int] = [] + started = time.monotonic() + for position, source_index in enumerate(selected, 1): + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise RuntimeError(f"invalid existing cache: {output}") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + else: + sample = dataset[(source_index, 0)] + has_supervision = bool(sample["translation_valid"].any()) + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + clip = dataset.clips[source_index] + parts = Path(clip.take).parts + if has_supervision: + cached[source_index] = { + "dataset_id": "H2O", + "subject_id": parts[0], + "sequence_id": "/".join(parts[1:-1]), + "physical_recording_id": "/".join(parts[:-1]), + "camera_id": "cam4", "stream_id": "cam4-rgb", + "headset_id": "H2O-ego", "source_clip_index": source_index, + "source_group_key": f"H2O/{'/'.join(parts[:-1])}", + "resolution_hw": list(target_hw), + "cache_path": str(output.resolve()), "cache_sha256": sha256(output), + } + else: + skipped.append(source_index) + if position % 10 == 0 or position == len(selected): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": position, "requested": len(selected), + "cached": len(cached), "skipped_no_supervision": len(skipped), + "clips_per_second": position / elapsed, + }), flush=True) + ordered_valid = [index for index in selected if index in cached][:args.clips] + if len(ordered_valid) == args.clips: + break + manifest = args.output_dir / "cache_manifest.jsonl" + temporary_manifest = manifest.with_suffix(".tmp") + temporary_manifest.write_text( + "".join(json.dumps(cached[index], sort_keys=True) + "\n" for index in ordered_valid), + encoding="utf-8", + ) + temporary_manifest.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": "complete" if len(ordered_valid) == args.clips else "insufficient_valid_clips", + "dataset": "H2O", "split_role": "official_train", + "source_manifest": { + "path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest), + }, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "requested_clips": args.clips, "candidate_clips_processed": position, + "resolution_hw": list(target_hw), + "cached_clips": len(ordered_valid), "valid_candidate_files": len(cached), + "recordings": len({cached[index]["physical_recording_id"] for index in ordered_valid}), + "skipped_no_supervision": skipped, + "wall_seconds": elapsed, "clips_per_second": position / elapsed, + "bytes": sum(Path(cached[index]["cache_path"]).stat().st_size for index in ordered_valid), + "resume_invocation": bool(args.resume), + "h2o_official_validation_used": False, "official_test_used": False, + } + (args.output_dir / "cache_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase7_hot3d.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase7_hot3d.py new file mode 100644 index 0000000000000000000000000000000000000000..7f6273de04231e6edb06c4fbfdacf1fe2547e592 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase7_hot3d.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Build a bounded, source-hash-bound HOT3D clip cache.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +import time + +import numpy as np + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset + + +def validated_target_hw(values: tuple[int, int] | list[int]) -> tuple[int, int]: + """Validate the full-frame cache resolution used by every source writer.""" + + if len(values) != 2: + raise ValueError("target resolution must contain height and width") + height, width = (int(value) for value in values) + if min(height, width) <= 0: + raise ValueError("target resolution dimensions must be positive") + return height, width + + +def validate_cached_resolution( + archive: np.lib.npyio.NpzFile, target_hw: tuple[int, int], +) -> None: + if "image_hw" not in archive.files: + raise ValueError("cached payload lacks image_hw") + image_hw = tuple(int(value) for value in np.asarray(archive["image_hw"]).reshape(-1)) + if image_hw != target_hw: + raise ValueError( + f"cached payload resolution {image_hw} does not match requested {target_hw}" + ) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def sha256_json(value: object) -> str: + payload = json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + return hashlib.sha256(payload).hexdigest() + + +def decode_position_slice( + decode_order: list[int], position_range: tuple[int, int] | None, +) -> tuple[list[int], tuple[int, int] | None]: + if position_range is None: + return decode_order, None + start, stop = position_range + if start < 0 or stop <= start or stop > len(decode_order): + raise ValueError( + f"invalid prefill position range [{start}, {stop}) for {len(decode_order)} candidates" + ) + return decode_order[start:stop], (start, stop) + + +def balanced_recording_keys( + groups: dict[tuple[str, str, str], list[int]], max_recordings: int, +) -> list[tuple[str, str, str]]: + strata: dict[tuple[str, str], list[tuple[str, str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[:2]].append(key) + selected: list[tuple[str, str, str]] = [] + cursor = 0 + while len(selected) < min(max_recordings, len(groups)): + progress = False + for stratum in sorted(strata): + if cursor < len(strata[stratum]): + selected.append(strata[stratum][cursor]) + progress = True + if len(selected) == max_recordings: + break + if not progress: + break + cursor += 1 + return selected + + +def balanced_indices( + rows: list[dict], count: int, max_recordings: int | None = None, +) -> list[int]: + groups: dict[tuple[str, str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + groups[(row["headset"], row["participant_id"], row["recording_id"])].append(index) + keys = sorted(groups) + if max_recordings is not None: + if max_recordings <= 0: + raise ValueError("max_recordings must be positive") + keys = balanced_recording_keys(groups, max_recordings) + selected: list[int] = [] + cursor = 0 + while len(selected) < min(count, len(rows)): + progress = False + for key in keys: + values = groups[key] + if cursor < len(values): + selected.append(values[cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def cache_candidate_count(requested: int, available: int) -> int: + return min(available, requested + max(64, int(np.ceil(requested * 0.1)))) + + +def first_valid_indices( + selected: list[int], cached: dict[int, dict], requested: int, +) -> list[int]: + return [index for index in selected if index in cached][:requested] + + +def should_stop_decoding( + selected: list[int], cached: dict[int, dict], requested: int, + decode_all_candidates: bool, +) -> bool: + """Stop early only when full candidate decoding was not requested.""" + + return ( + not decode_all_candidates + and len(first_valid_indices(selected, cached, requested)) == requested + ) + + +def rgb_uint8(rgb: np.ndarray) -> np.ndarray: + image = np.transpose(rgb, (0, 2, 3, 1)) + image = (image * RGB_STD + RGB_MEAN) * 255.0 + return np.rint(np.clip(image, 0, 255)).astype(np.uint8) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--toolkit-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument( + "--decode-all-candidates", action="store_true", + help="Decode the complete balanced overdraw pool before freezing the valid prefix.", + ) + parser.add_argument( + "--prefill-position-range", type=int, nargs=2, metavar=("START", "STOP"), + help=( + "Decode a zero-based half-open slice of the frozen candidate order into " + "a staging cache; no deployable cache manifest is produced." + ), + ) + parser.add_argument("--resume", action="store_true") + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + if args.clips < 1: + parser.error("--clips must be positive") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing output clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + dataset = HOT3DClipDataset( + args.root, args.source_manifest, args.toolkit_root, args.mano_root, + K_input_dropout=0.0, provider_cache_size=2, target_hw=target_hw, + ) + candidate_count = cache_candidate_count(args.clips, len(dataset.rows)) + selected = balanced_indices(dataset.rows, candidate_count, args.max_recordings) + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced candidates are available") + # Decode in recording order to avoid reopening VRS files for every clip. + full_decode_order = sorted( + selected, + key=lambda index: ( + dataset.rows[index]["recording_id"], + dataset.rows[index]["stream_id"], + dataset.rows[index]["timestamps_ns"][0], + ), + ) + prefill_range = ( + tuple(args.prefill_position_range) + if args.prefill_position_range is not None else None + ) + try: + decode_order, prefill_range = decode_position_slice( + full_decode_order, prefill_range, + ) + except ValueError as error: + parser.error(str(error)) + if prefill_range is not None and not args.decode_all_candidates: + parser.error("--prefill-position-range requires --decode-all-candidates") + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", + } + cache_rows: dict[int, dict] = {} + skipped_no_supervision: list[int] = [] + started = time.monotonic() + for position, source_index in enumerate(decode_order, 1): + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + try: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise ValueError("required cache arrays missing") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + if { + "source_hand_annotation_present", "geometry_convention_compatible", + }.issubset(archive.files): + masked_geometry = int(np.count_nonzero( + archive["source_hand_annotation_present"] + & ~archive["geometry_convention_compatible"] + )) + else: + # The previous strict writer raised before saving any + # clip containing a regeneration mismatch. + masked_geometry = 0 + except Exception as error: + raise RuntimeError(f"existing resume cache is invalid: {output}: {error}") from error + else: + sample = dataset[(source_index, 0)] + has_supervision = bool(sample["translation_valid"].any()) + masked_geometry = int(( + sample["source_hand_annotation_present"] + & ~sample["geometry_convention_compatible"] + ).sum()) + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + if has_supervision: + row = dataset.rows[source_index] + cache_rows[source_index] = { + "dataset_id": "HOT3D", + "subject_id": row["participant_id"], + "sequence_id": row["recording_id"], + "physical_recording_id": row["recording_id"], + "camera_id": row["stream_id"], + "stream_id": row["stream_id"], + "headset_id": row["headset"], + "source_clip_index": source_index, + "source_group_key": row["group_key"], + "resolution_hw": list(target_hw), + "geometry_masked_hand_frames": masked_geometry, + "cache_path": str(output.resolve()), + "cache_sha256": sha256(output), + } + else: + skipped_no_supervision.append(source_index) + if position % 10 == 0 or position == len(decode_order): + elapsed = time.monotonic() - started + print(json.dumps({ + "decoded": position, "total": len(decode_order), + "cached": len(cache_rows), + "skipped_no_supervision": len(skipped_no_supervision), + "clips_per_second": position / elapsed, + "eta_seconds": (len(decode_order) - position) / (position / elapsed), + }), flush=True) + if prefill_range is None and should_stop_decoding( + selected, cache_rows, args.clips, args.decode_all_candidates, + ): + break + if prefill_range is None: + ordered_cached = first_valid_indices(selected, cache_rows, args.clips) + manifest = args.output_dir / "cache_manifest.jsonl" + status = "complete" if len(ordered_cached) == args.clips else "insufficient_valid_clips" + mode = "deployable_cache" + else: + ordered_cached = [index for index in decode_order if index in cache_rows] + manifest = args.output_dir / "prefill_manifest.jsonl" + status = ( + "complete" + if len(ordered_cached) + len(skipped_no_supervision) == len(decode_order) + else "incomplete_prefill" + ) + mode = "staged_prefill" + temporary_manifest = manifest.with_suffix(".tmp") + temporary_manifest.write_text( + "".join(json.dumps(cache_rows[index], sort_keys=True) + "\n" for index in ordered_cached), + encoding="utf-8", + ) + temporary_manifest.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": status, + "mode": mode, + "official_test_used": False, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "clips": len(ordered_cached), + "candidate_clips_processed": position, + "full_candidate_clips": len(full_decode_order), + "requested_target_clips": args.clips, + "resolution_hw": list(target_hw), + "max_recordings": args.max_recordings, + "candidate_position_range": list(prefill_range) if prefill_range else None, + "candidate_source_indices_sha256": sha256_json(full_decode_order), + "recordings": len({cache_rows[index]["source_group_key"] for index in ordered_cached}), + "skipped_no_supervision": skipped_no_supervision, + "geometry_masked_hand_frames": sum( + cache_rows[index]["geometry_masked_hand_frames"] for index in ordered_cached + ), + "geometry_masked_source_indices": [ + index for index in ordered_cached + if cache_rows[index]["geometry_masked_hand_frames"] + ], + "decode_all_candidates": bool(args.decode_all_candidates), + "resume_invocation": bool(args.resume), + "wall_seconds": elapsed, + "clips_per_second": position / elapsed, + "bytes": sum(Path(cache_rows[index]["cache_path"]).stat().st_size for index in ordered_cached), + } + report_path = args.output_dir / "cache_report.json" + report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase7_unified_source.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase7_unified_source.py new file mode 100644 index 0000000000000000000000000000000000000000..72c1f102f49f8b1c31bd065469ea43d9f629b1cf --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/cache_phase7_unified_source.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Build resumable controlled caches for HOI4D or ARCTIC unified clips.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +import math +from pathlib import Path +import time + +import numpy as np +import torch + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset +from foundation_hand.data.schema import InvalidSourceSampleError +from scripts.cache_phase7_hot3d import ( + rgb_uint8, + validate_cached_resolution, + validated_target_hw, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def center_out(values: list[int]) -> list[int]: + values = sorted(values) + center = (len(values) - 1) // 2 + order = [center] + distance = 1 + while len(order) < len(values): + if center + distance < len(values): + order.append(center + distance) + if center - distance >= 0: + order.append(center - distance) + distance += 1 + return [values[index] for index in order] + + +def balanced_source_indices( + rows: list[dict], count: int, max_recordings: int, +) -> list[int]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(rows): + groups[(str(row["subject_id"]), str(row["physical_recording_id"]))].append(index) + strata: dict[str, list[tuple[str, str]]] = defaultdict(list) + for key in sorted(groups): + strata[key[0]].append(key) + selected_groups: list[tuple[str, str]] = [] + cursor = 0 + while len(selected_groups) < min(max_recordings, len(groups)): + progress = False + for subject in sorted(strata): + if cursor < len(strata[subject]): + selected_groups.append(strata[subject][cursor]) + progress = True + if len(selected_groups) == max_recordings: + break + if not progress: + break + cursor += 1 + ordered = {key: center_out(groups[key]) for key in selected_groups} + selected: list[int] = [] + cursor = 0 + while len(selected) < count: + progress = False + for key in selected_groups: + if cursor < len(ordered[key]): + selected.append(ordered[key][cursor]) + progress = True + if len(selected) == count: + break + if not progress: + break + cursor += 1 + return selected + + +def hand_side_source_indices(rows: list[dict], required_side: str) -> list[int]: + if required_side == "any": + return list(range(len(rows))) + if required_side not in {"left", "right"}: + raise ValueError("required hand side must be any, left or right") + return [ + index for index, row in enumerate(rows) + if any(required_side in sides for sides in row.get("hand_sides", [])) + ] + + +def cache_candidate_count(requested: int, available: int) -> int: + """Overdraw a deterministic candidate pool so invalid clips can be replaced.""" + return min(available, requested + max(32, math.ceil(requested * 0.1))) + + +def first_valid_indices( + selected: list[int], cached: dict[int, dict], requested: int, +) -> list[int]: + return [index for index in selected if index in cached][:requested] + + +def should_stop_decoding( + selected: list[int], cached: dict[int, dict], requested: int, + decode_all_candidates: bool, +) -> bool: + """Stop early only when full candidate decoding was not requested.""" + + return ( + not decode_all_candidates + and len(first_valid_indices(selected, cached, requested)) == requested + ) + + +def cache_completion_status( + requested: int, selected: list[int], cached: dict[int, dict], processed: int, + accept_all_valid: bool, +) -> str: + if accept_all_valid: + return "complete" if processed == len(selected) else "incomplete_source_scan" + return "complete" if len(first_valid_indices(selected, cached, requested)) == requested else "insufficient_valid_clips" + + +def recording_local_batches( + decode_order: list[int], rows: list[dict], batch_size: int = 2, +) -> list[list[int]]: + if batch_size < 1: + raise ValueError("prefetch batch size must be positive") + batches: list[list[int]] = [] + start = 0 + while start < len(decode_order): + recording = rows[decode_order[start]]["physical_recording_id"] + end = start + while ( + end < len(decode_order) + and rows[decode_order[end]]["physical_recording_id"] == recording + ): + end += 1 + group = decode_order[start:end] + batches.extend( + group[offset:offset + batch_size] + for offset in range(0, len(group), batch_size) + ) + start = end + return batches + + +def cache_row( + source_row: dict, source_index: int, output: Path, dataset: str, + target_hw: tuple[int, int], + right_geometry_masked_frames: int = 0, +) -> dict: + return { + "dataset_id": dataset, + "subject_id": str(source_row["subject_id"]), + "sequence_id": str(source_row["physical_recording_id"]), + "physical_recording_id": str(source_row["physical_recording_id"]), + "camera_id": str(source_row["camera_id"]), + "stream_id": str(source_row["camera_id"]), + "headset_id": str(source_row.get("serial_id", source_row["subject_id"])), + "source_clip_index": source_index, + "source_group_key": str(source_row["group_key"]), + "resolution_hw": list(target_hw), + "cache_path": str(output.resolve()), + "cache_sha256": sha256(output), + "right_geometry_masked_frames": int(right_geometry_masked_frames), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dataset", choices=("HOI4D", "ARCTIC"), required=True) + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--root", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--max-recordings", type=int, required=True) + parser.add_argument( + "--target-hw", type=int, nargs=2, default=(368, 640), + metavar=("HEIGHT", "WIDTH"), + help="Full-frame cache resolution; defaults to the historical 640x368 contract.", + ) + parser.add_argument( + "--required-hand-side", choices=("any", "left", "right"), default="any", + help="Optional source-manifest hand-presence filter before balancing.", + ) + parser.add_argument( + "--prefetch-batch-size", type=int, default=0, + help="Optional exact recording-local prefetch batch; 0 keeps the original decoder.", + ) + parser.add_argument( + "--decode-all-candidates", action="store_true", + help="Decode the complete balanced overdraw pool before freezing the valid prefix.", + ) + parser.add_argument( + "--accept-all-valid", action="store_true", + help="For a full source manifest, cache every valid clip and report invalid clips explicitly.", + ) + parser.add_argument("--resume", action="store_true") + parser.add_argument("--torch-threads", type=int, default=0) + args = parser.parse_args() + try: + target_hw = validated_target_hw(args.target_hw) + except ValueError as error: + parser.error(str(error)) + if min(args.clips, args.max_recordings) <= 0: + parser.error("clip and recording counts must be positive") + if args.torch_threads < 0: + parser.error("--torch-threads cannot be negative") + if args.torch_threads: + torch.set_num_threads(args.torch_threads) + torch.set_num_interop_threads(1) + if args.dataset == "HOI4D": + if args.root is None: + parser.error("HOI4D requires --root") + dataset = HOI4DClipDataset( + args.root, args.source_manifest, args.mano_root, target_hw=target_hw, + ) + else: + dataset = ARCTICClipDataset( + args.source_manifest, args.mano_root, target_hw=target_hw, + ) + eligible = hand_side_source_indices(dataset.rows, args.required_hand_side) + if args.accept_all_valid and args.clips != len(eligible): + parser.error("--accept-all-valid requires --clips to equal all eligible source clips") + eligible_rows = [dataset.rows[index] for index in eligible] + candidate_count = cache_candidate_count(args.clips, len(eligible_rows)) + selected = [ + eligible[index] + for index in balanced_source_indices( + eligible_rows, candidate_count, args.max_recordings, + ) + ] + if len(selected) < args.clips: + raise RuntimeError(f"only {len(selected)} balanced candidates are available") + if args.resume: + if not (args.output_dir / "clips").is_dir(): + parser.error("--resume requires an existing clips directory") + else: + args.output_dir.mkdir(parents=True, exist_ok=False) + clips_dir = args.output_dir / "clips" + clips_dir.mkdir(exist_ok=args.resume) + # Group source reads to retain decoded sequence/provider state. + decode_order = sorted( + selected, + key=lambda index: ( + dataset.rows[index]["physical_recording_id"], + dataset.rows[index].get("frame_ids", dataset.rows[index].get("frame_ids_1based"))[0], + ), + ) + excluded = { + "photometric_aug_params", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", "geometry_convention_compatible", + } + cached: dict[int, dict] = {} + skipped_no_supervision: list[int] = [] + skipped_invalid_source: list[dict[str, str | int]] = [] + started = time.monotonic() + if args.prefetch_batch_size < 0: + parser.error("--prefetch-batch-size cannot be negative") + batches = ( + recording_local_batches(decode_order, dataset.rows, args.prefetch_batch_size) + if args.dataset == "HOI4D" and args.prefetch_batch_size + else [[index] for index in decode_order] + ) + position = 0 + for batch_indices in batches: + missing = [ + index for index in batch_indices + if not (clips_dir / f"clip_{index:07d}.npz").is_file() + ] + if args.dataset == "HOI4D" and args.prefetch_batch_size and missing: + dataset.prefetch_clip_indices(missing) + for source_index in batch_indices: + position += 1 + output = clips_dir / f"clip_{source_index:07d}.npz" + if output.is_file() and args.resume: + with np.load(output, allow_pickle=False) as archive: + if "rgb_u8" not in archive.files or "translation_valid" not in archive.files: + raise RuntimeError(f"invalid existing cache: {output}") + validate_cached_resolution(archive, target_hw) + has_supervision = bool(archive["translation_valid"].any()) + right_geometry_masked_frames = int(np.count_nonzero( + archive["translation_valid"][..., 1] + & ~archive["mano_annotation_valid"][..., 1] + )) if args.dataset == "HOI4D" else 0 + else: + try: + sample = dataset[(source_index, 0)] + except InvalidSourceSampleError as error: + if not args.accept_all_valid: + raise + skipped_invalid_source.append({ + "source_clip_index": source_index, + "reason": str(error), + }) + has_supervision = False + else: + has_supervision = bool(sample["translation_valid"].any()) + right_geometry_masked_frames = int(( + sample["translation_valid"][..., 1] + & ~sample["mano_annotation_valid"][..., 1] + ).sum()) if args.dataset == "HOI4D" else 0 + if has_supervision: + arrays = { + key: value.cpu().numpy() + for key, value in sample.items() + if hasattr(value, "cpu") and key not in excluded and key != "rgb" + } + arrays["rgb_u8"] = rgb_uint8(sample["rgb"].cpu().numpy()) + temporary = output.with_suffix(".tmp") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + temporary.replace(output) + if not has_supervision: + if not skipped_invalid_source or skipped_invalid_source[-1]["source_clip_index"] != source_index: + skipped_no_supervision.append(source_index) + else: + cached[source_index] = cache_row( + dataset.rows[source_index], source_index, output, args.dataset, + target_hw, + right_geometry_masked_frames, + ) + if position % 10 == 0 or position == len(decode_order): + elapsed = time.monotonic() - started + print(json.dumps({ + "processed": position, "requested": len(decode_order), + "cached": len(cached), "skipped_no_supervision": len(skipped_no_supervision), + "skipped_invalid_source": len(skipped_invalid_source), + "clips_per_second": position / elapsed, + "eta_seconds": (len(decode_order) - position) / (position / elapsed), + }), flush=True) + if args.dataset == "HOI4D" and args.prefetch_batch_size: + dataset.clear_prefetch() + if should_stop_decoding( + selected, cached, args.clips, + args.decode_all_candidates or args.accept_all_valid, + ): + break + ordered_cached = first_valid_indices(selected, cached, args.clips) + manifest = args.output_dir / "cache_manifest.jsonl" + manifest_temporary = manifest.with_suffix(".tmp") + manifest_temporary.write_text( + "".join(json.dumps(cached[index], sort_keys=True) + "\n" for index in ordered_cached), + encoding="utf-8", + ) + manifest_temporary.replace(manifest) + elapsed = time.monotonic() - started + report = { + "status": cache_completion_status( + args.clips, selected, cached, position, args.accept_all_valid, + ), + "dataset": args.dataset, + "source_manifest": {"path": str(args.source_manifest.resolve()), "sha256": sha256(args.source_manifest)}, + "cache_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "requested_clips": args.clips, "candidate_clips_processed": position, + "resolution_hw": list(target_hw), + "cached_clips": len(ordered_cached), "valid_candidate_files": len(cached), + "recordings": len({cached[index]["source_group_key"] for index in ordered_cached}), + "required_hand_side": args.required_hand_side, + "eligible_source_clips": len(eligible), + "accept_all_valid": bool(args.accept_all_valid), + "all_eligible_processed": position == len(selected), + "cached_valid_clips": len(ordered_cached), + "decode_all_candidates": bool(args.decode_all_candidates), + "skipped_no_supervision": skipped_no_supervision, + "skipped_invalid_source": skipped_invalid_source, + "right_geometry_masked_frames": sum( + cached[index]["right_geometry_masked_frames"] for index in ordered_cached + ), + "right_geometry_masked_source_indices": [ + index for index in ordered_cached + if cached[index]["right_geometry_masked_frames"] + ], + "wall_seconds": elapsed, "clips_per_second": position / elapsed, + "bytes": sum(Path(cached[index]["cache_path"]).stat().st_size for index in ordered_cached), + "resume_invocation": bool(args.resume), "official_test_used": False, + "torch_threads": args.torch_threads or torch.get_num_threads(), + } + (args.output_dir / "cache_report.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + if report["status"] != "complete": + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/capture_environment.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/capture_environment.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3d38bbd2ddfca1e23fdbc2eb2518240f885a2f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/capture_environment.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Capture phase-2 environment without exposing unrelated environment variables.""" + +from __future__ import annotations + +import json +import platform +import subprocess +from pathlib import Path + +import cv2 +import numpy as np +import torch + + +def command(args: list[str]) -> str: + return subprocess.run(args, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.strip() + + +def main() -> None: + output = Path("artifacts/phase2/environment") + output.mkdir(parents=True, exist_ok=True) + report = { + "captured_at": command(["date", "--iso-8601=seconds"]), + "platform": platform.platform(), "python": platform.python_version(), + "torch": torch.__version__, "torch_cuda": torch.version.cuda, "cuda_available": torch.cuda.is_available(), + "cuda_devices": [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())], + "bf16_supported": [torch.cuda.is_bf16_supported(index) for index in range(torch.cuda.device_count())], + "numpy": np.__version__, "opencv": cv2.__version__, + "nvidia_smi": command(["nvidia-smi", "--query-gpu=index,name,memory.total,memory.free,driver_version", "--format=csv,noheader"]), + "git_status": command(["git", "status", "--short"]), + "git_head": command(["git", "rev-parse", "HEAD"]), + "dinov3_commit": command(["git", "-C", "third_party/dinov3", "rev-parse", "HEAD"]), + "manopth_commit": command(["git", "-C", "third_party/manopth", "rev-parse", "HEAD"]), + "h2oplayer_commit": command(["git", "-C", "third_party/h2oplayer", "rev-parse", "HEAD"]), + } + (output / "environment.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/capture_phase4_provenance.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/capture_phase4_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..805db38ce73a5086e3677718bcaf2d864e418d7f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/capture_phase4_provenance.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Capture the Phase 4 entry state without reading the official test split.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import subprocess +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import cv2 +import numpy as np +import torch + + +def command(args: list[str], cwd: Path) -> str: + result = subprocess.run( + args, + cwd=cwd, + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + return result.stdout.strip() + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/freeze/entry")) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + output = (root / args.output_dir).resolve() if not args.output_dir.is_absolute() else args.output_dir + output.mkdir(parents=True, exist_ok=True) + + checkpoint_index = json.loads( + (root / "artifacts/phase3/reports/long_tail_checkpoints.json").read_text(encoding="utf-8") + ) + checkpoints = [] + for run in checkpoint_index["runs"].values(): + role = run["roles"]["tail_best_absolute"] + path = Path(role["path"]) + checkpoints.append({ + "seed": int(run["seed"]), + "step": int(role["step"]), + "path": str(path), + "registered_sha256": role["sha256"], + "observed_sha256": sha256(path), + "bytes": path.stat().st_size, + "evaluation": role["evaluation"], + }) + + protected_inputs = { + "official_train_manifest": root / "artifacts/phase2/data_audit/manifests/official_train.jsonl", + "official_val_manifest": root / "artifacts/phase2/data_audit/manifests/official_val.jsonl", + "fixed_validation_subset": root / "artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json", + } + report = { + "captured_at": datetime.now(ZoneInfo("Asia/Hong_Kong")).isoformat(), + "project_root": str(root), + "git_head": command(["git", "rev-parse", "HEAD"], root), + "git_status": command(["git", "status", "--short", "--branch"], root), + "git_diff_stat": command(["git", "diff", "--stat"], root), + "git_diff_sha256": hashlib.sha256(command(["git", "diff", "--binary"], root).encode()).hexdigest(), + "platform": platform.platform(), + "python": platform.python_version(), + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "cuda_devices": [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())], + "numpy": np.__version__, + "opencv": cv2.__version__, + "nvidia_smi": command([ + "nvidia-smi", + "--query-gpu=index,name,uuid,memory.total,memory.used,memory.free,utilization.gpu", + "--format=csv,noheader", + ], root), + "submodules": command(["git", "submodule", "status"], root), + "checkpoints": checkpoints, + "protected_inputs": { + name: {"path": str(path.resolve()), "sha256": sha256(path), "bytes": path.stat().st_size} + for name, path in protected_inputs.items() + }, + "official_test_used": False, + "official_test_note": "The official test manifest and files are intentionally not read or hashed.", + } + (output / "entry_provenance.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + (output / "git_status.txt").write_text(report["git_status"] + "\n", encoding="utf-8") + (output / "git_diff.patch").write_text(command(["git", "diff", "--binary"], root) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "captured", + "output": str(output), + "git_head": report["git_head"], + "checkpoint_hashes_match": all( + item["registered_sha256"] == item["observed_sha256"] for item in checkpoints + ), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/capture_phase5_provenance.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/capture_phase5_provenance.py new file mode 100644 index 0000000000000000000000000000000000000000..bb59cafe4facd03ad4fb3b51fc4bb96eea8d77da --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/capture_phase5_provenance.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Capture Phase 5 entry provenance without touching the official test split.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import subprocess +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import torch + + +def command(args: list[str], cwd: Path) -> str: + return subprocess.run( + args, cwd=cwd, check=False, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + ).stdout.strip() + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase5/freeze/entry")) + args = parser.parse_args() + root = Path(__file__).resolve().parents[1] + output = args.output_dir if args.output_dir.is_absolute() else root / args.output_dir + output.mkdir(parents=True, exist_ok=True) + + baselines = [ + { + "name": f"p0_512_seed{seed}", + "checkpoint": root / f"artifacts/phase3/depth_dropout_runs_commit7583772/depth_dropout00_geometry_m3_l1_t1_s{seed}/best.pt", + "evaluation": root / f"artifacts/phase3/depth_dropout_full_validation/depth_dropout00_geometry_m3_l1_t1_s{seed}/best_absolute/evaluation.json", + } + for seed in (20260716, 20260717, 20260718) + ] + [{ + "name": "unified_640_tail_seed20260718", + "checkpoint": Path("/SSD3/jiasen/foundation_hand/phase3_artifacts/long_tail_runs_commitd401922/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/best.pt"), + "evaluation": root / "artifacts/phase3/long_tail_full_validation/longtail_photometric_on_geometry_m3_l1_t1_r640x368_s20260718/tail_best_absolute/evaluation.json", + }] + baseline_records = [] + for baseline in baselines: + evaluation = json.loads(baseline["evaluation"].read_text(encoding="utf-8")) + checkpoint = baseline["checkpoint"] + observed_hash = sha256(checkpoint) + baseline_records.append({ + "name": baseline["name"], + "checkpoint": str(checkpoint.resolve()), + "registered_sha256": evaluation["checkpoint"]["sha256"], + "observed_sha256": observed_hash, + "hash_matches": observed_hash == evaluation["checkpoint"]["sha256"], + "step": evaluation["checkpoint"]["step"], + "evaluation": str(baseline["evaluation"].resolve()), + "absolute_mpjpe_mm": evaluation["metrics"]["absolute_mpjpe_mm"]["mean"], + "official_test_used": evaluation["official_test_used"], + }) + + protected = { + "official_train": root / "artifacts/phase2/data_audit/manifests/official_train.jsonl", + "official_validation": root / "artifacts/phase2/data_audit/manifests/official_val.jsonl", + "fixed_validation_subset_640": root / "artifacts/phase3/validation_subset/resolution_640x368/validation_subset_256.json", + "phase5_oof_folds": root / "artifacts/phase5/splits/subject_oof_v1/folds.json", + } + report = { + "captured_at": datetime.now(ZoneInfo("Asia/Hong_Kong")).isoformat(), + "status": "captured", + "project_root": str(root), + "git_head": command(["git", "rev-parse", "HEAD"], root), + "git_status": command(["git", "status", "--short", "--branch"], root), + "git_diff_sha256": hashlib.sha256( + command(["git", "diff", "--binary"], root).encode() + ).hexdigest(), + "platform": platform.platform(), + "python": platform.python_version(), + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "nvidia_smi": command([ + "nvidia-smi", "--query-gpu=index,name,uuid,memory.total,memory.used,memory.free,utilization.gpu", + "--format=csv,noheader", + ], root), + "disk": command(["df", "-h", str(root), "/SSD2", "/SSD3"], root), + "active_compute_processes": command([ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid,process_name,used_memory", + "--format=csv,noheader", + ], root), + "baselines": baseline_records, + "protected_inputs": { + name: {"path": str(path.resolve()), "sha256": sha256(path), "bytes": path.stat().st_size} + for name, path in protected.items() + }, + "official_test_used": False, + "official_test_note": "Official test manifests, files, predictions, and hashes were intentionally not accessed.", + } + (output / "entry_provenance.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + (output / "git_status.txt").write_text(report["git_status"] + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], + "output": str(output), + "baseline_hashes_match": all(row["hash_matches"] for row in baseline_records), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase3_resume.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase3_resume.py new file mode 100644 index 0000000000000000000000000000000000000000..82924e82bed187f735fe17acf6647623b4b1e206 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase3_resume.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Compare uninterrupted and resumed Phase 3 final states exactly.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +from pathlib import Path + + +def worker(reference_path: Path, resumed_path: Path) -> None: + import numpy as np + import torch + + reference = torch.load(reference_path, map_location="cpu", weights_only=False) + resumed = torch.load(resumed_path, map_location="cpu", weights_only=False) + + def equal(left, right) -> bool: + if torch.is_tensor(left) and torch.is_tensor(right): + return left.dtype == right.dtype and left.shape == right.shape and torch.equal(left, right) + if isinstance(left, np.ndarray) and isinstance(right, np.ndarray): + return left.dtype == right.dtype and left.shape == right.shape and np.array_equal(left, right) + if isinstance(left, dict) and isinstance(right, dict): + return left.keys() == right.keys() and all(equal(left[key], right[key]) for key in left) + if isinstance(left, (tuple, list)) and isinstance(right, type(left)): + return len(left) == len(right) and all(equal(a, b) for a, b in zip(left, right)) + return left == right + + result = { + "reference_step": int(reference["step"]), + "resumed_step": int(resumed["step"]), + "model_exact": equal(reference["model"], resumed["model"]), + "optimizer_exact": equal(reference["optimizer"], resumed["optimizer"]), + "python_rng_exact": equal(reference["python_rng"], resumed["python_rng"]), + "numpy_rng_exact": equal(reference["numpy_rng"], resumed["numpy_rng"]), + "torch_rng_exact": equal(reference["torch_rng"], resumed["torch_rng"]), + "cuda_rng_exact": equal(reference["cuda_rng"], resumed["cuda_rng"]), + } + print(json.dumps(result)) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("reference_root", type=Path, nargs="?") + parser.add_argument("resumed_root", type=Path, nargs="?") + parser.add_argument("--expected-runs", type=int) + parser.add_argument("--checkpoint-name", default="step_0100000_final.pt") + parser.add_argument("--expected-step", type=int, default=100_000) + parser.add_argument("--worker", nargs=2, type=Path) + args = parser.parse_args() + if args.worker: + worker(*args.worker) + return + if args.reference_root is None or args.resumed_root is None: + parser.error("reference_root and resumed_root are required") + + # The resumed root defines the audited subset while a larger reference matrix + # may still be running. + run_names = sorted( + path.name for path in args.resumed_root.iterdir() + if path.is_dir() and not path.name.startswith("_") + ) + if args.expected_runs is not None and len(run_names) != args.expected_runs: + raise ValueError(f"expected {args.expected_runs} runs, found {len(run_names)}") + records = [] + for run_name in run_names: + reference_path = args.reference_root / run_name / args.checkpoint_name + resumed_path = args.resumed_root / run_name / args.checkpoint_name + if not reference_path.is_file() or not resumed_path.is_file(): + raise FileNotFoundError(f"missing final checkpoint for {run_name}") + process = subprocess.run( + [ + sys.executable, str(Path(__file__).resolve()), "--worker", + str(reference_path), str(resumed_path), + ], + check=True, capture_output=True, text=True, + ) + records.append({"run": run_name, **json.loads(process.stdout)}) + + passed = bool(records) and all( + row["reference_step"] == row["resumed_step"] == args.expected_step + and row["model_exact"] and row["optimizer_exact"] + and row["python_rng_exact"] and row["numpy_rng_exact"] + and row["torch_rng_exact"] and row["cuda_rng_exact"] + for row in records + ) + payload = { + "status": "passed" if passed else "failed", + "official_test_used": False, + "reference_root": str(args.reference_root), + "resumed_root": str(args.resumed_root), + "runs": records, + } + output = args.resumed_root / "exact_resume_audit.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": payload["status"], "runs": len(records), "output": str(output)}, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase5_alignment_calibrators.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase5_alignment_calibrators.py new file mode 100644 index 0000000000000000000000000000000000000000..5921cddec59bf99669817ea5ddbe8fee1c4c6335 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase5_alignment_calibrators.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Compare shared multi-checkpoint and per-seed OOF calibrators.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + + +CONDITIONS = ( + "coarse", + "robust_alignment_unscaled", + "calibrated_always", + "calibrated_confidence", +) +METRICS = ("absolute_mpjpe_mm", "z_mae_mm", "z_p95_mm", "z_cvar95_mm") + + +def load_report(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "fitted" + or report.get("result_role") != "train_oof_cross_validated_threshold_selection" + or report.get("official_validation_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"comparison requires a train-OOF-only calibration report: {path}") + return report + + +def compare_reports( + shared: dict[str, Any], per_seed: list[dict[str, Any]], +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + if int(shared.get("expected_banks_per_fold", -1)) <= 1: + raise ValueError("shared report is not a multi-checkpoint calibration") + expected_seeds = {int(seed) for seed in shared.get("coarse_seeds", [])} + specific = {} + for report in per_seed: + seeds = [int(seed) for seed in report.get("coarse_seeds", [])] + if int(report.get("expected_banks_per_fold", -1)) != 1 or len(seeds) != 1: + raise ValueError("each per-seed report must contain one seed and one bank per fold") + if seeds[0] in specific: + raise ValueError(f"duplicate per-seed report: {seeds[0]}") + specific[seeds[0]] = report + if set(specific) != expected_seeds: + raise ValueError( + f"per-seed reports do not match shared seeds: {sorted(specific)} vs {sorted(expected_seeds)}" + ) + + rows = [] + for seed in sorted(expected_seeds): + shared_metrics = shared["metrics_by_seed"][str(seed)] + specific_metrics = specific[seed]["metrics"] + for metric in METRICS: + shared_coarse = float(shared_metrics["coarse"][metric]) + specific_coarse = float(specific_metrics["coarse"][metric]) + if abs(shared_coarse - specific_coarse) > 1e-9: + raise ValueError(f"seed {seed} coarse {metric} mismatch") + for condition in CONDITIONS: + row: dict[str, Any] = {"seed": seed, "condition": condition} + for metric in METRICS: + shared_value = float(shared_metrics[condition][metric]) + specific_value = float(specific_metrics[condition][metric]) + row[f"shared_{metric}"] = shared_value + row[f"per_seed_{metric}"] = specific_value + row[f"shared_minus_per_seed_{metric}"] = shared_value - specific_value + rows.append(row) + + calibrated = [row for row in rows if row["condition"] == "calibrated_always"] + summary = { + "status": "compared", + "experiment_class": "train_oof_shared_vs_per_seed_calibrator_ablation", + "seeds": sorted(expected_seeds), + "primary_condition": "calibrated_always", + "shared_absolute_better_seed_count": sum( + row["shared_minus_per_seed_absolute_mpjpe_mm"] < 0 for row in calibrated + ), + "mean_shared_minus_per_seed_absolute_mpjpe_mm": sum( + row["shared_minus_per_seed_absolute_mpjpe_mm"] for row in calibrated + ) / len(calibrated), + "mean_shared_minus_per_seed_z_p95_mm": sum( + row["shared_minus_per_seed_z_p95_mm"] for row in calibrated + ) / len(calibrated), + "official_validation_used": False, + "official_test_used": False, + } + return rows, summary + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--shared", type=Path, required=True) + parser.add_argument("--per-seed", type=Path, action="append", required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + raise FileExistsError("comparison refuses to overwrite outputs") + shared = load_report(args.shared) + per_seed = [load_report(path) for path in args.per_seed] + rows, summary = compare_reports(shared, per_seed) + report = { + **summary, + "shared_report": str(args.shared.resolve()), + "per_seed_reports": [str(path.resolve()) for path in args.per_seed], + "rows": rows, + } + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase6_paired_evaluations.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase6_paired_evaluations.py new file mode 100644 index 0000000000000000000000000000000000000000..6720f4f081aba86cf6a2f3152e427076a0f95dad --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase6_paired_evaluations.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Pair two frozen Phase 6 evaluation outputs by take/frame/side.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + + +METRIC_ALIASES = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm",), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm",), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm",), + "root_relative_mpvpe_mm": ("root_relative_mpvpe_mm",), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm",), + "translation_x_mae_mm": ("translation_x_mae_mm",), + "translation_y_mae_mm": ("translation_y_mae_mm",), + "translation_z_mae_mm": ("translation_z_mae_mm",), + "direct_2d_error_px": ("direct_2d_error_px",), + "projected_mano_2d_px": ("projected_mano_2d_px", "mano_projected_2d_error_px"), + "direct_mano_consistency_px": ( + "direct_mano_consistency_px", "direct_mano_2d_consistency_px", + ), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_rows(path: Path, condition: str | None) -> dict[tuple[str, int, str], dict[str, float]]: + output = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + if condition is not None and row.get("condition") != condition: + continue + if row.get("annotation_valid") not in (None, "1", "True", "true"): + continue + identity = (row["take"], int(row["frame_id"]), row["side"]) + if identity in output: + raise ValueError(f"duplicate paired identity: {identity}") + metrics = {} + for canonical, aliases in METRIC_ALIASES.items(): + source = next((alias for alias in aliases if row.get(alias, "") != ""), None) + if source is not None: + metrics[canonical] = float(row[source]) + output[identity] = metrics + if not output: + raise ValueError(f"no rows selected from {path}") + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--baseline-dir", type=Path, required=True) + parser.add_argument("--candidate-dir", type=Path, required=True) + parser.add_argument("--baseline-condition") + parser.add_argument("--candidate-condition") + parser.add_argument("--baseline-label", required=True) + parser.add_argument("--candidate-label", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + baseline_path = args.baseline_dir / "per_hand_frame_metrics.csv" + candidate_path = args.candidate_dir / "per_hand_frame_metrics.csv" + baseline = load_rows(baseline_path, args.baseline_condition) + candidate = load_rows(candidate_path, args.candidate_condition) + if set(baseline) != set(candidate): + raise ValueError("paired evaluations have different take/frame/side identities") + common_metrics = sorted( + set().union(*(set(row) for row in baseline.values())) + & set().union(*(set(row) for row in candidate.values())) + ) + if not common_metrics: + raise ValueError("paired evaluations have no common metrics") + frame_rows = [] + for identity in sorted(baseline): + take, frame_id, side = identity + row: dict[str, object] = {"take": take, "frame_id": frame_id, "side": side} + for metric in common_metrics: + if metric not in baseline[identity] or metric not in candidate[identity]: + continue + delta = candidate[identity][metric] - baseline[identity][metric] + row[f"baseline_{metric}"] = baseline[identity][metric] + row[f"candidate_{metric}"] = candidate[identity][metric] + row[f"delta_{metric}"] = delta + frame_rows.append(row) + rng = np.random.default_rng(20260717) + paired_rows = [] + for metric in common_metrics: + selected = [row for row in frame_rows if f"delta_{metric}" in row] + frame_delta = np.asarray([float(row[f"delta_{metric}"]) for row in selected]) + by_take: dict[str, list[float]] = defaultdict(list) + for row in selected: + by_take[str(row["take"])].append(float(row[f"delta_{metric}"])) + takes = sorted(by_take) + take_delta = np.asarray([ + np.mean(by_take[take]) for take in takes + ]) + indices = rng.integers(0, len(take_delta), size=(10_000, len(take_delta))) + bootstrap = take_delta[indices].mean(axis=1) + paired_rows.append({ + "candidate": args.candidate_label, "baseline": args.baseline_label, + "metric": metric, "hands": len(frame_delta), "takes": len(takes), + "frame_weighted_delta": float(frame_delta.mean()), + "take_equal_delta": float(take_delta.mean()), + "ci95_low": float(np.percentile(bootstrap, 2.5)), + "ci95_high": float(np.percentile(bootstrap, 97.5)), + "largest_sample_gain": float(frame_delta.min()), + "largest_sample_harm": float(frame_delta.max()), + "largest_take_gain": float(take_delta.min()), + "largest_take_harm": float(take_delta.max()), + }) + args.output_dir.mkdir(parents=True, exist_ok=True) + for filename, rows in ( + ("per_hand_frame_deltas.csv", frame_rows), + ("paired_take_bootstrap_ci.csv", paired_rows), + ): + with (args.output_dir / filename).open("x", newline="", encoding="utf-8") as handle: + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "paired", + "official_test_used": False, + "baseline": { + "label": args.baseline_label, "directory": str(args.baseline_dir.resolve()), + "condition": args.baseline_condition, "rows_sha256": sha256(baseline_path), + }, + "candidate": { + "label": args.candidate_label, "directory": str(args.candidate_dir.resolve()), + "condition": args.candidate_condition, "rows_sha256": sha256(candidate_path), + }, + "paired_identities": len(frame_rows), + "physical_takes": len({str(row["take"]) for row in frame_rows}), + "metrics": paired_rows, + } + (args.output_dir / "comparison.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_adaptation_forgetting.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_adaptation_forgetting.py new file mode 100644 index 0000000000000000000000000000000000000000..e1cb408e3922668217c70a3eddaf0c68cfd7748b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_adaptation_forgetting.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Paired external forgetting comparison for an H2O-adapted checkpoint.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +from scripts.compare_phase8_specialist_curve import ( + MEAN_METRICS, + _load_rows, + _paired_bootstrap, +) + + +def _load_reference(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError("reference is not a strict external-heldout result") + return report + + +def _load_candidate(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_adaptation_external_heldout" + or report.get("evaluation_role") != "adaptation_external_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError("candidate is not an adaptation forgetting result") + return report + + +def compare( + reference_path: Path, + candidate_path: Path, + *, + seed: int = 20260717, + resamples: int = 2000, +) -> dict[str, Any]: + reference = _load_reference(reference_path) + candidate = _load_candidate(candidate_path) + for field in ("input_mode", "clips", "frames"): + if reference.get(field) != candidate.get(field): + raise ValueError(f"evaluation {field} differs") + if reference["cache_manifest"] != candidate["cache_manifest"]: + raise ValueError("evaluation cache manifest differs") + reference_rows = _load_rows(reference_path, reference) + candidate_rows = _load_rows(candidate_path, candidate) + if set(reference_rows) != set(candidate_rows): + raise ValueError("per-hand frame identities differ") + metrics: dict[str, Any] = {} + for metric in MEAN_METRICS: + metrics[metric] = { + "reference_global_mean": reference["metrics"][metric]["mean"], + "candidate_global_mean": candidate["metrics"][metric]["mean"], + **_paired_bootstrap( + reference_rows, candidate_rows, metric, "mean", seed, resamples, + ), + } + metrics["translation_z_recording_p95_mm"] = { + "reference_global_p95": reference["metrics"]["translation_z_mae_mm"]["p95"], + "candidate_global_p95": candidate["metrics"]["translation_z_mae_mm"]["p95"], + **_paired_bootstrap( + reference_rows, candidate_rows, "translation_z_mae_mm", "p95", + seed, resamples, + ), + } + return { + "schema_version": "phase8_adaptation_forgetting_comparison_v1", + "status": "complete", + "delta_definition": "adapted_candidate_minus_external_reference; positive is forgetting", + "reference": { + "evaluation": str(reference_path.resolve()), + "checkpoint": reference["checkpoint"], + }, + "candidate": { + "evaluation": str(candidate_path.resolve()), + "checkpoint": candidate["checkpoint"], + }, + "input_mode": reference["input_mode"], + "cache_manifest": reference["cache_manifest"], + "per_hand_identity_count": len(reference_rows), + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "metrics": metrics, + "selection_use": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-evaluation", type=Path, required=True) + parser.add_argument("--candidate-evaluation", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + report = compare( + args.reference_evaluation, args.candidate_evaluation, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_h2o_trainheldout.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_h2o_trainheldout.py new file mode 100644 index 0000000000000000000000000000000000000000..f823fbc57892f9bf3c1192807b564b7ad628c97a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_h2o_trainheldout.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Compare H2O train-heldout baselines separately by deployable input mode.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.select_phase7_h2o_adaptation import ( + METRIC_SPECS, + paired_recording_bootstrap, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def checked_artifact(report: dict[str, Any], name: str) -> Path: + record = report[name] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"{name} is missing or SHA256 differs: {path}") + return path + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("selection_split") != "h2o_train_group_heldout_only" + or manifest.get("h2o_official_validation_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("comparison manifest violates the train-heldout boundary") + by_mode: dict[str, list[dict[str, Any]]] = {} + cache_hashes: set[str] = set() + seen: set[tuple[str, str]] = set() + valid_status_roles = { + ("evaluated_h2o_train_group_heldout", "h2o_train_group_heldout"), + ("evaluated_h2o_train_group_heldout_control", "h2o_train_group_heldout_control"), + } + for item in manifest.get("candidates", []): + condition = str(item["condition"]) + report_path = Path(item["evaluation"]) + report = json.loads(report_path.read_text(encoding="utf-8")) + status_role = (report.get("status"), report.get("evaluation_role")) + mode = str(report.get("input_mode")) + if ( + status_role not in valid_status_roles + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or Path(report["cache_manifest"]["path"]).name != "train_group_heldout.jsonl" + ): + raise ValueError(f"invalid H2O train-heldout result: {report_path}") + if (condition, mode) in seen: + raise ValueError(f"duplicate condition/mode: {condition}/{mode}") + seen.add((condition, mode)) + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + cache = checked_artifact(report, "cache_manifest") + rows = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + cache_hashes.add(report["cache_manifest"]["sha256"]) + metrics = { + name: float(report["metrics"][row_metric][statistic]) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + by_mode.setdefault(mode, []).append({ + "condition": condition, "evaluation": str(report_path.resolve()), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config.resolve()), "cache_manifest": str(cache.resolve()), + "per_hand_rows": str(rows.resolve()), "metrics": metrics, + }) + if len(cache_hashes) != 1: + raise ValueError("candidates use different train-heldout manifests") + if not by_mode: + raise ValueError("comparison manifest has no candidates") + modes: dict[str, Any] = {} + for mode, candidates in sorted(by_mode.items()): + if len(candidates) < 2: + raise ValueError(f"input mode requires at least two candidates: {mode}") + order = sorted(candidates, key=lambda row: ( + row["metrics"]["absolute_mpjpe_mm"], + row["metrics"]["root_relative_mpjpe_mm"], + row["condition"], + )) + winner = order[0] + paired = {} + for candidate in order[1:]: + paired[candidate["condition"]] = { + name: paired_recording_bootstrap( + Path(winner["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + modes[mode] = { + "winner": winner["condition"], + "order": [candidate["condition"] for candidate in order], + "candidates": order, + "paired_recording_bootstrap_vs_winner": paired, + } + return { + "status": "compared_h2o_train_group_heldout_by_input_mode", + "selection_split": "h2o_train_group_heldout_only", + "selection_rule": "lowest Absolute MPJPE separately within each input mode", + "modes": modes, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_h2o_zero_shot.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c3efcc36b714f01f46834472c98a2b59014f8f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_h2o_zero_shot.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Compare already-frozen external checkpoints on H2O validation diagnostically.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import Any + +from scripts.compare_phase8_h2o_trainheldout import checked_artifact +from scripts.select_phase7_h2o_adaptation import METRIC_SPECS, paired_recording_bootstrap + + +BOUNDARY = "frozen_external_checkpoints_h2o_official_validation_diagnostic_only" + + +def _metrics(report: dict[str, Any]) -> dict[str, float]: + values = { + name: float(report["metrics"][row_metric][statistic]) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + if not all(math.isfinite(value) for value in values.values()): + raise ValueError("zero-shot report contains non-finite metrics") + return values + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("comparison_boundary") != BOUNDARY + or manifest.get("checkpoint_selection_frozen_before_h2o") is not True + or manifest.get("h2o_official_validation_used_for_external_selection") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("comparison manifest violates the frozen zero-shot boundary") + reference_condition = str(manifest.get("reference_condition", "")) + by_mode: dict[str, list[dict[str, Any]]] = {} + validation_hashes: set[str] = set() + seen: set[tuple[str, str]] = set() + for item in manifest.get("candidates", []): + condition = str(item["condition"]) + path = Path(item["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + mode = str(report.get("input_mode")) + if ( + report.get("status") != "evaluated_strict_h2o_zero_shot" + or report.get("evaluation_role") != "strict_external_zero_shot" + or report.get("h2o_training_data_used") is not False + or report.get("h2o_official_validation_used") is not True + or report.get("h2o_official_validation_used_for_external_selection") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid frozen H2O zero-shot result: {path}") + if (condition, mode) in seen: + raise ValueError(f"duplicate condition/mode: {condition}/{mode}") + seen.add((condition, mode)) + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + rows = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + validation = checked_artifact(report, "manifest") + validation_hashes.add(report["manifest"]["sha256"]) + by_mode.setdefault(mode, []).append({ + "condition": condition, + "evaluation": str(path.resolve()), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config), + "validation_manifest": str(validation), + "per_hand_rows": str(rows), + "metrics": _metrics(report), + }) + if len(validation_hashes) != 1 or not by_mode: + raise ValueError("zero-shot candidates must use one frozen validation manifest") + modes: dict[str, Any] = {} + for mode, candidates in sorted(by_mode.items()): + references = [row for row in candidates if row["condition"] == reference_condition] + if len(references) != 1 or len(candidates) < 2: + raise ValueError(f"mode lacks one reference and at least one candidate: {mode}") + reference = references[0] + comparisons = {} + for candidate in candidates: + if candidate is reference: + continue + comparisons[candidate["condition"]] = { + name: paired_recording_bootstrap( + Path(reference["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for name, (row_metric, statistic) in METRIC_SPECS.items() + } + modes[mode] = { + "reference": reference, + "candidates": [row for row in candidates if row is not reference], + "paired_candidate_minus_reference": comparisons, + } + return { + "status": "compared_frozen_h2o_zero_shot_diagnostic_only", + "comparison_boundary": BOUNDARY, + "selection_performed": False, + "reference_condition": reference_condition, + "modes": modes, + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_specialist_curve.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_specialist_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..92a78c396b10552bb60b3407b9e9686f7859ad84 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_specialist_curve.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Compare two frozen specialist checkpoints on identical external rows.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +MEAN_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", +) +IDENTITY_FIELDS = ( + "dataset", "physical_recording_id", "camera_id", "frame_id", "side", +) + + +def _load_report(path: Path) -> dict[str, Any]: + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or report.get("oracle_information_used") is not False + ): + raise ValueError(f"evaluation violates external curve contract: {path}") + return report + + +def _load_rows(report_path: Path, report: dict[str, Any]) -> dict[tuple[str, ...], dict[str, str]]: + specification = report["per_hand_rows"] + row_path = Path( + specification["path"] if isinstance(specification, dict) else specification, + ) + if not row_path.is_absolute(): + row_path = report_path.parent / row_path + if isinstance(specification, dict): + digest = hashlib.sha256(row_path.read_bytes()).hexdigest() + if digest != specification.get("sha256"): + raise ValueError(f"per-hand row SHA256 differs: {row_path}") + with row_path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + indexed: dict[tuple[str, ...], dict[str, str]] = {} + for row in rows: + identity = tuple(str(row[field]) for field in IDENTITY_FIELDS) + if identity in indexed: + raise ValueError(f"duplicate per-hand identity: {identity}") + indexed[identity] = row + if not indexed: + raise ValueError(f"evaluation has no per-hand rows: {row_path}") + return indexed + + +def _recording_statistic( + rows: dict[tuple[str, ...], dict[str, str]], metric: str, statistic: str, +) -> dict[tuple[str, str], float]: + grouped: dict[tuple[str, str], list[float]] = {} + for identity, row in rows.items(): + value = float(row[metric]) + if math.isfinite(value): + grouped.setdefault((identity[0], identity[1]), []).append(value) + if statistic == "mean": + reduce = np.mean + elif statistic == "p95": + reduce = lambda values: np.quantile(values, 0.95) + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + return {key: float(reduce(values)) for key, values in grouped.items()} + + +def _paired_bootstrap( + reference: dict[tuple[str, str], dict[str, str]], + candidate: dict[tuple[str, str], dict[str, str]], + metric: str, + statistic: str, + seed: int, + resamples: int, +) -> dict[str, Any]: + reference_values = _recording_statistic(reference, metric, statistic) + candidate_values = _recording_statistic(candidate, metric, statistic) + if set(reference_values) != set(candidate_values): + raise ValueError(f"finite recording coverage differs for {metric}/{statistic}") + keys = sorted(reference_values) + delta = np.asarray( + [candidate_values[key] - reference_values[key] for key in keys], + dtype=np.float64, + ) + rng = np.random.default_rng(seed) + sampled = delta[ + rng.integers(0, len(delta), size=(resamples, len(delta))) + ].mean(axis=1) + return { + "recording_statistic": statistic, + "recording_count": len(keys), + "mean_delta": float(delta.mean()), + "ci95_low": float(np.percentile(sampled, 2.5)), + "ci95_high": float(np.percentile(sampled, 97.5)), + } + + +def compare( + reference_path: Path, + candidate_path: Path, + *, + seed: int = 20260717, + resamples: int = 2000, +) -> dict[str, Any]: + reference_report = _load_report(reference_path) + candidate_report = _load_report(candidate_path) + for field in ("input_mode", "clips", "frames"): + if reference_report.get(field) != candidate_report.get(field): + raise ValueError(f"evaluation {field} differs") + if reference_report["cache_manifest"] != candidate_report["cache_manifest"]: + raise ValueError("evaluation cache manifest differs") + reference_rows = _load_rows(reference_path, reference_report) + candidate_rows = _load_rows(candidate_path, candidate_report) + if set(reference_rows) != set(candidate_rows): + raise ValueError("per-hand frame identities differ") + metrics: dict[str, Any] = {} + for metric in MEAN_METRICS: + reference_summary = reference_report["metrics"].get(metric) or {} + candidate_summary = candidate_report["metrics"].get(metric) or {} + metrics[metric] = { + "reference_global_mean": reference_summary.get("mean"), + "candidate_global_mean": candidate_summary.get("mean"), + **_paired_bootstrap( + reference_rows, candidate_rows, metric, "mean", seed, resamples, + ), + } + z_reference = reference_report["metrics"]["translation_z_mae_mm"] + z_candidate = candidate_report["metrics"]["translation_z_mae_mm"] + metrics["translation_z_recording_p95_mm"] = { + "reference_global_p95": z_reference.get("p95"), + "candidate_global_p95": z_candidate.get("p95"), + **_paired_bootstrap( + reference_rows, candidate_rows, "translation_z_mae_mm", "p95", + seed, resamples, + ), + } + absolute = metrics["absolute_mpjpe_mm"] + return { + "schema_version": "phase8_specialist_curve_comparison_v1", + "status": "complete", + "delta_definition": "candidate_minus_reference; negative favors candidate", + "reference": { + "evaluation": str(reference_path.resolve()), + "checkpoint_step": reference_report["checkpoint_step"], + "checkpoint": reference_report["checkpoint"], + }, + "candidate": { + "evaluation": str(candidate_path.resolve()), + "checkpoint_step": candidate_report["checkpoint_step"], + "checkpoint": candidate_report["checkpoint"], + }, + "input_mode": reference_report["input_mode"], + "cache_manifest": reference_report["cache_manifest"], + "per_hand_identity_count": len(reference_rows), + "bootstrap_seed": seed, + "bootstrap_resamples": resamples, + "metrics": metrics, + "candidate_absolute_lower": ( + float(absolute["candidate_global_mean"]) + < float(absolute["reference_global_mean"]) + ), + "candidate_absolute_ci_excludes_zero": absolute["ci95_high"] < 0.0, + "h2o_training_data_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-evaluation", type=Path, required=True) + parser.add_argument("--candidate-evaluation", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + args.reference_evaluation, args.candidate_evaluation, + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_stage7_left.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_stage7_left.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e522e3d109275545d58a7f4c7402d090b00fce --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/compare_phase8_stage7_left.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Compare matched Stage 7 left-supervision screens on external held-out data.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.select_phase7_h2o_adaptation import paired_recording_bootstrap + + +CONDITIONS = ("L0_sampler_only", "L1_left_root_relative") +DATASETS = ("HOT3D", "HOI4D", "ARCTIC") +METRICS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "source_root_relative_mpjpe_mm": ("source_root_relative_mpjpe_mm", "mean"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def checked(report: dict[str, Any], name: str) -> Path: + record = report[name] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"{name} is missing or SHA256 differs: {path}") + return path + + +def compare( + manifest: dict[str, Any], *, seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + if ( + manifest.get("evaluation_split") != "external_heldout_only" + or manifest.get("h2o_training_data_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("Stage 7 comparison boundary flags are invalid") + reports: dict[str, dict[str, dict[str, Any]]] = {condition: {} for condition in CONDITIONS} + for item in manifest.get("evaluations", []): + condition, dataset = str(item["condition"]), str(item["dataset"]) + if condition not in reports or dataset not in DATASETS: + raise ValueError(f"unexpected condition/dataset: {condition}/{dataset}") + if dataset in reports[condition]: + raise ValueError(f"duplicate condition/dataset: {condition}/{dataset}") + path = Path(item["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid external evaluation: {path}") + rows = checked(report, "per_hand_rows") + cache = checked(report, "cache_manifest") + checked(report, "checkpoint") + checked(report, "config") + reports[condition][dataset] = { + "path": str(path.resolve()), "report": report, + "rows": rows, "cache": cache, + } + for condition in CONDITIONS: + if set(reports[condition]) != set(DATASETS): + raise ValueError(f"{condition} does not contain all external domains") + datasets: dict[str, Any] = {} + for dataset in DATASETS: + reference = reports[CONDITIONS[0]][dataset] + candidate = reports[CONDITIONS[1]][dataset] + for key in ("sha256",): + if reference["report"]["cache_manifest"][key] != candidate["report"]["cache_manifest"][key]: + raise ValueError(f"{dataset} cache differs between L0 and L1") + if reference["report"]["input_mode"] != candidate["report"]["input_mode"]: + raise ValueError(f"{dataset} input mode differs between L0 and L1") + condition_metrics: dict[str, Any] = {} + for condition, record in ((CONDITIONS[0], reference), (CONDITIONS[1], candidate)): + report_metrics = record["report"]["metrics"] + condition_metrics[condition] = { + metric: ( + None if report_metrics.get(row_metric) is None + else float(report_metrics[row_metric][statistic]) + ) + for metric, (row_metric, statistic) in METRICS.items() + } + paired = { + metric: paired_recording_bootstrap( + reference["rows"], candidate["rows"], row_metric, statistic, + seed, resamples, + ) + for metric, (row_metric, statistic) in METRICS.items() + if condition_metrics[CONDITIONS[0]][metric] is not None + and condition_metrics[CONDITIONS[1]][metric] is not None + } + datasets[dataset] = { + "cache_manifest_sha256": reference["report"]["cache_manifest"]["sha256"], + "input_mode": reference["report"]["input_mode"], + "conditions": condition_metrics, + "paired_L1_minus_L0": paired, + } + macro: dict[str, Any] = {} + for metric in ("absolute_mpjpe_mm", "root_relative_mpjpe_mm"): + values = { + condition: [datasets[dataset]["conditions"][condition][metric] for dataset in DATASETS] + for condition in CONDITIONS + } + macro[metric] = { + **{condition: sum(rows) / len(rows) for condition, rows in values.items()}, + } + macro[metric]["L1_minus_L0"] = ( + macro[metric][CONDITIONS[1]] - macro[metric][CONDITIONS[0]] + ) + left_datasets = ("HOI4D", "ARCTIC") + source_values = { + condition: [ + datasets[dataset]["conditions"][condition]["source_root_relative_mpjpe_mm"] + for dataset in left_datasets + ] + for condition in CONDITIONS + } + if any(value is None for values in source_values.values() for value in values): + raise ValueError("left held-out source-root supervision is missing") + macro["source_root_relative_mpjpe_mm"] = { + condition: sum(values) / len(values) for condition, values in source_values.items() + } + macro["source_root_relative_mpjpe_mm"]["L1_minus_L0"] = ( + macro["source_root_relative_mpjpe_mm"][CONDITIONS[1]] + - macro["source_root_relative_mpjpe_mm"][CONDITIONS[0]] + ) + source_gain = -macro["source_root_relative_mpjpe_mm"]["L1_minus_L0"] + accepted = ( + source_gain >= 0.5 + and macro["absolute_mpjpe_mm"]["L1_minus_L0"] <= 1.0 + and macro["root_relative_mpjpe_mm"]["L1_minus_L0"] <= 1.0 + ) + return { + "schema_version": "phase8_stage7_left_comparison_v1", + "status": "complete", "datasets": datasets, "dataset_macro": macro, + "gate": { + "minimum_source_root_gain_mm": 0.5, + "maximum_absolute_regression_mm": 1.0, + "maximum_root_relative_regression_mm": 1.0, + "accepted": accepted, + }, + "h2o_training_data_used": False, "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = compare( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, resamples=args.bootstrap_resamples, + ) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/derive_phase9_hot_subset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/derive_phase9_hot_subset.py new file mode 100644 index 0000000000000000000000000000000000000000..abbd427229e098170eb3c8a45d4aef55ad057922 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/derive_phase9_hot_subset.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Derive a deterministic headset/recording-balanced HOT3D cache subset.""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict, deque +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def balanced_subset(rows: list[dict[str, Any]], clips: int) -> list[dict[str, Any]]: + if clips <= 0 or clips > len(rows): + raise ValueError("subset size must be in [1, source rows]") + unique_indices = {int(row["source_clip_index"]) for row in rows} + if len(unique_indices) != len(rows): + raise ValueError("source cache contains duplicate source_clip_index values") + grouped: dict[str, dict[str, deque[dict[str, Any]]]] = defaultdict(dict) + by_recording: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for row in rows: + headset = str(row.get("headset_id", "unknown")) + recording = str(row["physical_recording_id"]) + by_recording[(headset, recording)].append(row) + for (headset, recording), recording_rows in by_recording.items(): + grouped[headset][recording] = deque(sorted( + recording_rows, key=lambda row: int(row["source_clip_index"]), + )) + + headsets = sorted(grouped) + recording_cursor = {headset: 0 for headset in headsets} + recording_ids = { + headset: sorted(grouped[headset]) for headset in headsets + } + selected: list[dict[str, Any]] = [] + while len(selected) < clips: + progress = False + for headset in headsets: + ids = recording_ids[headset] + for _ in range(len(ids)): + cursor = recording_cursor[headset] % len(ids) + recording_cursor[headset] += 1 + queue = grouped[headset][ids[cursor]] + if queue: + selected.append(queue.popleft()) + progress = True + break + if len(selected) == clips: + break + if not progress: + raise RuntimeError("balanced subset exhausted before requested size") + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-manifest", type=Path, required=True) + parser.add_argument("--source-report", type=Path, required=True) + parser.add_argument("--clips", type=int, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + report = json.loads(args.source_report.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(args.source_manifest) + ): + parser.error("source cache report does not bind a complete manifest") + rows = load_jsonl(args.source_manifest) + selected = balanced_subset(rows, args.clips) + missing = [row["cache_path"] for row in selected if not Path(row["cache_path"]).is_file()] + if missing: + parser.error(f"selected cache payload is missing: {missing[0]}") + args.output_dir.mkdir(parents=True) + manifest = args.output_dir / "cache_manifest.jsonl" + temporary = manifest.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in selected), + encoding="utf-8", + ) + temporary.replace(manifest) + headset_counts = Counter(str(row.get("headset_id", "unknown")) for row in selected) + stream_counts = Counter(str(row.get("stream_id", "unknown")) for row in selected) + recording_counts = Counter(str(row["physical_recording_id"]) for row in selected) + output = { + "schema_version": "phase9_hot_balanced_subset_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "source_cache_manifest": { + "path": str(args.source_manifest.resolve()), + "sha256": sha256(args.source_manifest), + "rows": len(rows), + }, + "source_cache_report": { + "path": str(args.source_report.resolve()), + "sha256": sha256(args.source_report), + }, + "cache_manifest": { + "path": str(manifest.resolve()), + "sha256": sha256(manifest), + }, + "clips": len(selected), + "unique_source_clip_indices": len({int(row["source_clip_index"]) for row in selected}), + "recordings": len(recording_counts), + "headset_clip_counts": dict(sorted(headset_counts.items())), + "stream_clip_counts": dict(sorted(stream_counts.items())), + "recording_clip_count_min": min(recording_counts.values()), + "recording_clip_count_max": max(recording_counts.values()), + "payload_copy_bytes": 0, + "payloads_referenced_from_parent": True, + "official_test_used": False, + } + report_path = args.output_dir / "cache_report.json" + report_path.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8") + print(json.dumps(output, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase3.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase3.py new file mode 100644 index 0000000000000000000000000000000000000000..4acdc8f9c12791353d8d2fd3653421539f757245 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase3.py @@ -0,0 +1,1155 @@ +#!/usr/bin/env python3 +"""Audited Phase 3 validation with MANO meshes, tail metrics, and take CIs.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.phase4 import ( + action_name, + bimanual_asymmetry, + depth_validity_bucket, + find_failure_intervals, + load_action_label, + local_depth_statistics, + summarize_group_metrics, +) +from foundation_hand.evaluation.selection import select_visualization_frames +from foundation_hand.evaluation.visualization import ( + MeshLayer, + draw_skeleton, + project_mesh_layers, + render_mesh_layers, + save_attention_figure, + save_camera_views, +) +from foundation_hand.geometry.camera import project_points, unproject_depth +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +SIDES = ("left", "right") +PREDICTED_COLORS = ((32, 190, 105), (235, 112, 45)) +TARGET_COLORS = ((40, 160, 245), (215, 55, 190)) +FINGERTIP_INDICES = (4, 8, 12, 16, 20) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_clip_indices_manifest( + path: Path, + *, + source_manifest: Path, + data_config: dict[str, object], + dataset_length: int, +) -> tuple[list[int], dict[str, object]]: + record = json.loads(path.read_text(encoding="utf-8")) + contract = record.get("dataset_contract", {}) + resolution = [int(value) for value in data_config["resolution_hw"]] + if record.get("source_manifest_sha256") != sha256(source_manifest): + raise ValueError("clip subset source-manifest hash mismatch") + if int(record.get("source_clip_count", -1)) != dataset_length: + raise ValueError("clip subset source length mismatch") + if contract.get("resolution_hw") != resolution: + raise ValueError("clip subset resolution mismatch") + if int(contract.get("T", -1)) != int(data_config["T"]): + raise ValueError("clip subset temporal length mismatch") + if int(contract.get("stride", -1)) != int(data_config["stride"]): + raise ValueError("clip subset stride mismatch") + indices = [int(index) for index in record.get("clip_indices", [])] + if len(indices) != int(record.get("count", -1)) or len(indices) != len(set(indices)): + raise ValueError("clip subset count/uniqueness mismatch") + if not indices or min(indices) < 0 or max(indices) >= dataset_length: + raise ValueError("clip subset index out of bounds") + return indices, record + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def rgb_from_batch(batch: dict[str, Any], time_index: int) -> np.ndarray: + rgb = batch["rgb"][0, time_index].float().cpu().permute(1, 2, 0).numpy() + return np.clip((rgb * RGB_STD + RGB_MEAN) * 255.0, 0, 255).astype(np.uint8) + + +def hand_size_bucket(size: float | None) -> str | None: + if size is None: + return None + if size < 64: + return "small" + if size < 128: + return "medium" + return "large" + + +def wrist_depth_bucket(depth: float | None) -> str | None: + if depth is None: + return None + if depth < 0.5: + return "near" + if depth < 0.8: + return "middle" + return "far" + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + return + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def temporal_position_bias_report(model: BimanualReconstructionModel) -> dict[str, object]: + layers = [] + for layer_index, layer in enumerate(model.decoder.temporal): + bias = getattr(layer, "relative_position_bias", None) + if bias is None: + continue + values = bias.detach().float().cpu().numpy() + max_distance = int(layer.relative_bias_max_distance) + layers.append({ + "layer": layer_index, + "offsets_key_minus_query": list(range(-max_distance, max_distance + 1)), + "shape": list(values.shape), + "mean": float(values.mean()), + "std": float(values.std()), + "max_abs": float(np.abs(values).max()), + "per_head_bias": values.tolist(), + }) + return { + "mode": model.config.temporal_position_mode, + "sign_convention": "key_time_minus_query_time", + "layers": layers, + } + + +def add_label(image: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image.copy() + box_height = 8 + 18 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], box_height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (6, 17 + 18 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.38, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def attach_gt_geometry( + batch: dict[str, Any], model: BimanualReconstructionModel, +) -> tuple[torch.Tensor, torch.Tensor]: + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + vertices, joints = model.mano_layer( + axis_angle_to_matrix(pose), + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + return vertices, joints + + +def run_model( + model: BimanualReconstructionModel, + batch: dict[str, Any], + dtype: torch.dtype, +) -> dict[str, Any]: + with torch.autocast("cuda", dtype=dtype): + return model(batch) + + +def save_depth_geometry( + output: Path, batch: dict[str, Any], time_index: int, title: str, +) -> None: + depth = batch["depth_m"][0, time_index, 0].float().cpu().numpy() + valid = batch["depth_pixel_valid"][0, time_index, 0].bool().cpu().numpy() + K = batch["K"][0, time_index].float().cpu().numpy() + xyz, xyz_valid = unproject_depth(depth, K) + fig, axes = plt.subplots(2, 3, figsize=(13, 7), constrained_layout=True) + values = ( + (depth, "depth (m)", "viridis"), + (valid, "depth validity", "gray"), + (xyz[..., 2], "Z (m)", "viridis"), + (np.where(xyz_valid, xyz[..., 0], np.nan), "X (m)", "coolwarm"), + (np.where(xyz_valid, xyz[..., 1], np.nan), "Y (m)", "coolwarm"), + (np.linalg.norm(xyz, axis=-1), "XYZ norm (m)", "viridis"), + ) + for axis, (value, name, cmap) in zip(axes.flat, values, strict=True): + artist = axis.imshow(value, cmap=cmap) + axis.set_title(name) + axis.axis("off") + fig.colorbar(artist, ax=axis, shrink=0.75) + fig.suptitle(title) + fig.savefig(output, dpi=150) + plt.close(fig) + + +def render_frame_bundle( + output_dir: Path, + image: np.ndarray, + K: np.ndarray, + predicted_vertices: np.ndarray, + target_vertices: np.ndarray, + predicted_joints: np.ndarray, + target_joints_2d: np.ndarray, + direct_joints_2d: np.ndarray, + mano_joints_2d: np.ndarray, + valid_hands: np.ndarray, + faces: tuple[np.ndarray, np.ndarray], + title_lines: tuple[str, ...], +) -> np.ndarray: + predicted_layers = [ + MeshLayer(predicted_vertices[hand], faces[hand], PREDICTED_COLORS[hand], 0.58) + for hand in range(2) + ] + target_layers = [ + MeshLayer(target_vertices[hand], faces[hand], TARGET_COLORS[hand], 0.50) + for hand in range(2) if valid_hands[hand] + ] + predicted_render = render_mesh_layers(image, project_mesh_layers(predicted_layers, K)) + target_render = render_mesh_layers(image, project_mesh_layers(target_layers, K)) + joint_render = render_mesh_layers( + image, project_mesh_layers(target_layers + predicted_layers, K), + ) + panels = [image, target_render, predicted_render, joint_render] + names = ("RGB", "GT MANO", "predicted MANO", "joint z-buffer overlay") + labeled_panels = [] + for panel, name in zip(panels, names, strict=True): + labeled_panels.append(add_label(panel, (name,))) + mosaic = np.concatenate(( + np.concatenate(labeled_panels[:2], axis=1), + np.concatenate(labeled_panels[2:], axis=1), + ), axis=0) + cv2.imwrite(str(output_dir / "mesh_rgb_overlay.png"), cv2.cvtColor(add_label(mosaic, title_lines), cv2.COLOR_RGB2BGR)) + + for hand, side in enumerate(SIDES): + layers = [predicted_layers[hand]] + if valid_hands[hand]: + layers.insert(0, MeshLayer(target_vertices[hand], faces[hand], TARGET_COLORS[hand], 0.50)) + rendered = render_mesh_layers(image, project_mesh_layers(layers, K)) + cv2.imwrite(str(output_dir / f"{side}_mesh_overlay.png"), cv2.cvtColor(add_label(rendered, title_lines), cv2.COLOR_RGB2BGR)) + + skeleton = image.copy() + for hand in range(2): + if valid_hands[hand]: + skeleton = draw_skeleton(skeleton, target_joints_2d[hand], (255, 255, 255), marker="cross") + skeleton = draw_skeleton(skeleton, direct_joints_2d[hand], PREDICTED_COLORS[hand], marker="circle", draw_edges=False) + skeleton = draw_skeleton(skeleton, mano_joints_2d[hand], TARGET_COLORS[hand], marker="ring") + skeleton = add_label(skeleton, title_lines + ("GT=white cross; direct-2D=dot; projected predicted MANO=ring",)) + cv2.imwrite(str(output_dir / "skeleton_consistency_overlay.png"), cv2.cvtColor(skeleton, cv2.COLOR_RGB2BGR)) + return add_label(joint_render, title_lines) + + +def visualize_selections( + selections: list[dict[str, object]], + dataset: H2OCam4Dataset, + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + config: dict[str, Any], + output_root: Path, +) -> None: + faces = tuple(layer.th_faces.cpu().numpy() for layer in model.mano_layer.layers) + modalities = "RGB" + ("+Depth" if config["model"].get("use_depth") else "") + ("+K" if config["model"].get("use_rays") else "") + for selection_index, selection in enumerate(selections): + clip_index = int(selection["clip_index"]) + requested_time = int(selection["time_index"]) + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(): + target_vertices, _ = attach_gt_geometry(batch, model) + prediction = run_model(model, batch, dtype) + valid_times = int(batch["frame_valid"][0].sum()) + time_index = min(requested_time, valid_times - 1) + sample_dir = output_root / f"{selection_index:02d}_{selection['subject']}_{str(selection['sequence']).replace('/', '_')}_{int(selection['frame_id']):06d}" + sample_dir.mkdir(parents=True, exist_ok=True) + valid_hands = batch["mano_annotation_valid"][0, time_index].bool().cpu().numpy() + K = batch["K"][0, time_index].float().cpu().numpy() + image = rgb_from_batch(batch, time_index) + predicted_vertices = prediction["vertices_camera"][0, time_index].float().cpu().numpy() + target_vertices_np = target_vertices[0, time_index].float().cpu().numpy() + predicted_joints = prediction["joints_camera"][0, time_index].float() + mano_2d, _ = project_points(predicted_joints, batch["K"][0, time_index].float()) + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"][0, time_index].float().cpu().numpy() * np.asarray((width, height)) + title_lines = ( + f"{selection['subject']}/{selection['sequence']}/{int(selection['frame_id'])} | L/R valid={int(valid_hands[0])}/{int(valid_hands[1])}", + f"config={config['name']} input={modalities} presence=unsupervised", + f"selection={','.join(str(reason) for reason in selection['reasons'])}", + ) + render_frame_bundle( + sample_dir, image, K, predicted_vertices, target_vertices_np, + predicted_joints.cpu().numpy(), batch["joint2d"][0, time_index].float().cpu().numpy(), + direct_2d, mano_2d.cpu().numpy(), valid_hands, faces, title_lines, + ) + save_camera_views( + sample_dir / "camera_3d_front_side.png", predicted_vertices, target_vertices_np, + valid_hands, " | ".join(title_lines[:2]), + ) + save_depth_geometry(sample_dir / "depth_xyz.png", batch, time_index, " | ".join(title_lines[:2])) + + attention = prediction["attention"] + grid_hw = (height // int(config["model"].get("patch_size", 16)), width // int(config["model"].get("patch_size", 16))) + rgb_attention = attention["rgb_cross_attention"][0, -1, time_index].float().cpu().numpy() + save_attention_figure( + sample_dir / "rgb_attention_raw_shared_scale.png", image, + rgb_attention[0], rgb_attention[1], grid_hw, "RGB | " + " | ".join(title_lines[:2]), + ) + if "depth_cross_attention" in attention: + depth_attention = attention["depth_cross_attention"][0, -1, time_index].float().cpu().numpy() + save_attention_figure( + sample_dir / "depth_attention_raw_shared_scale.png", image, + depth_attention[0], depth_attention[1], grid_hw, "Depth | " + " | ".join(title_lines[:2]), + ) + if "temporal_attention" in attention: + temporal = attention["temporal_attention"][0, -1].float().cpu().numpy() + shared_max = max(float(temporal.max()), 1e-8) + fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True) + artist = None + for hand, side in enumerate(SIDES): + artist = axes[hand].imshow(temporal[hand], vmin=0, vmax=shared_max, cmap="viridis") + axes[hand].set_title(side) + axes[hand].set_xlabel("key frame") + axes[hand].set_ylabel("query frame") + fig.colorbar(artist, ax=axes, label="raw head-averaged attention weight") + fig.suptitle("last-layer, head-averaged temporal attention; not calibrated probability") + fig.savefig(sample_dir / "temporal_attention_raw_shared_scale.png", dpi=160) + plt.close(fig) + + video_path = sample_dir / "clip_mesh_overlay.mp4" + writer = cv2.VideoWriter(str(video_path), cv2.VideoWriter_fourcc(*"mp4v"), 4.0, (width, height)) + for clip_time in range(valid_times): + clip_image = rgb_from_batch(batch, clip_time) + clip_K = batch["K"][0, clip_time].float().cpu().numpy() + clip_valid = batch["mano_annotation_valid"][0, clip_time].bool().cpu().numpy() + pred_layers = [ + MeshLayer(prediction["vertices_camera"][0, clip_time, hand].float().cpu().numpy(), faces[hand], PREDICTED_COLORS[hand], 0.58) + for hand in range(2) + ] + gt_layers = [ + MeshLayer(target_vertices[0, clip_time, hand].float().cpu().numpy(), faces[hand], TARGET_COLORS[hand], 0.50) + for hand in range(2) if clip_valid[hand] + ] + rendered = render_mesh_layers(clip_image, project_mesh_layers(gt_layers + pred_layers, clip_K)) + rendered = add_label(rendered, ( + f"{selection['subject']}/{selection['sequence']} frame={int(batch['frame_id'][0, clip_time])}", + f"L/R valid={int(clip_valid[0])}/{int(clip_valid[1])} config={config['name']} input={modalities}", + )) + writer.write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + writer.release() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + parser.add_argument("--clip-indices-manifest", type=Path) + parser.add_argument("--num-workers", type=int, default=0) + parser.add_argument("--seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--skip-visualizations", action="store_true") + parser.add_argument( + "--phase4-diagnostics", + action="store_true", + help=( + "Add signed translation, action, asymmetry, local-depth, group, " + "CVaR, and long-failure diagnostics without changing model inference." + ), + ) + parser.add_argument( + "--drop-depth", action="store_true", + help="Mark metric depth unavailable at inference while retaining the RGB-D-K checkpoint.", + ) + parser.add_argument( + "--drop-k", action="store_true", + help="Mark intrinsics/ray conditioning unavailable at inference while retaining the RGB-D-K checkpoint.", + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + max_clips=args.max_clips, + oracle_crop_enabled=( + config["model"].get("oracle_crop_mode", "none") != "none" + ), + ) + subset_record = None + evaluation_dataset = dataset + if args.clip_indices_manifest is not None: + if args.max_clips is not None: + parser.error("--max-clips and --clip-indices-manifest are mutually exclusive") + if not args.skip_visualizations: + parser.error("clip-index subset evaluation requires --skip-visualizations") + indices, subset_record = load_clip_indices_manifest( + args.clip_indices_manifest, + source_manifest=args.manifest, + data_config=data_config, + dataset_length=len(dataset), + ) + evaluation_dataset = Subset(dataset, indices) + loader = DataLoader( + evaluation_dataset, batch_size=1, shuffle=False, num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + values: dict[str, list[float]] = defaultdict(list) + per_joint: dict[str, list[float]] = defaultdict(list) + attention_values: dict[str, list[float]] = defaultdict(list) + temporal_by_distance: dict[int, list[float]] = defaultdict(list) + temporal_by_signed_distance: dict[int, list[float]] = defaultdict(list) + frame_rows: list[dict[str, object]] = [] + temporal_rows: list[dict[str, object]] = [] + oracle_refinement_values: dict[str, list[float]] = defaultdict(list) + selection_records: list[dict[str, object]] = [] + frame_count = 0 + + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = move_to_device(batch_cpu, device) + target_vertices, _ = attach_gt_geometry(batch, model) + if args.drop_depth: + batch["depth_input_available"] = torch.zeros_like(batch["frame_valid"], dtype=torch.bool) + batch["depth_available"] = batch["depth_input_available"] + if args.drop_k: + batch["K_input_available"] = torch.zeros_like(batch["frame_valid"], dtype=torch.bool) + batch["K_available"] = batch["K_input_available"] + prediction = run_model(model, batch, dtype) + frame_valid = batch["frame_valid"].bool() + if "mixed_projection_success" in prediction: + mixed_valid = frame_valid[..., None].expand_as( + prediction["mixed_projection_success"], + ) + mixed_diagnostics = { + "mixed_projection_success_fraction": prediction[ + "mixed_projection_success" + ].float(), + "mixed_projection_support_count": prediction[ + "mixed_projection_support_count" + ].float(), + "mixed_projection_conditioning": prediction[ + "mixed_projection_conditioning" + ].float(), + "mixed_projection_inlier_ratio": prediction[ + "mixed_projection_inlier_ratio" + ].float(), + "mixed_projection_residual_scale_px": prediction[ + "mixed_projection_residual_scale_px" + ].float(), + } + for key, diagnostic in mixed_diagnostics.items(): + values[key].extend(diagnostic[mixed_valid].cpu().tolist()) + joint_annotation = batch["joint_annotation_valid"].bool() & frame_valid[..., None] + mano_annotation = batch["mano_annotation_valid"].bool() & frame_valid[..., None] + joint_valid = batch["joint_element_valid"].bool() & joint_annotation[..., None] + frame_count += int(frame_valid.sum()) + + target_joints = torch.nan_to_num(batch["joint3d_camera"]) + predicted_joints = prediction["joints_camera"].float() + absolute_joint_error = torch.linalg.vector_norm(predicted_joints - target_joints, dim=-1) * 1000.0 + predicted_relative = predicted_joints - predicted_joints[..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + relative_joint_error = torch.linalg.vector_norm(predicted_relative - target_relative, dim=-1) * 1000.0 + translation_signed_error = ( + prediction["wrist_root_translation"].float() + - torch.nan_to_num(batch["wrist_root_translation"]) + ) * 1000.0 + translation_error = translation_signed_error.abs() + + oracle_refinement = "coarse_joints_camera" in prediction + if oracle_refinement: + coarse_joints = prediction["coarse_joints_camera"].float() + coarse_absolute_joint_error = torch.linalg.vector_norm( + coarse_joints - target_joints, dim=-1, + ) * 1000.0 + coarse_relative = coarse_joints - coarse_joints[..., :1, :] + coarse_relative_joint_error = torch.linalg.vector_norm( + coarse_relative - target_relative, dim=-1, + ) * 1000.0 + coarse_translation_error = ( + prediction["coarse_wrist_root_translation"].float() + - torch.nan_to_num(batch["wrist_root_translation"]) + ).abs() * 1000.0 + rotation_delta_degrees = torch.linalg.vector_norm( + prediction["oracle_crop_rotation_delta_axis_angle"].float(), + dim=-1, + ).mean(dim=-1) * (180.0 / np.pi) + shape_delta_l2 = torch.linalg.vector_norm( + prediction["oracle_crop_shape_delta"].float(), dim=-1, + ) + delta_z_mm = prediction["oracle_crop_delta_z"].float().squeeze(-1) * 1000.0 + + vertex_error = torch.linalg.vector_norm(prediction["vertices_camera"].float() - target_vertices, dim=-1) * 1000.0 + predicted_vertex_relative = prediction["vertices_camera"].float() - prediction["wrist_root_translation"].float()[..., None, :] + target_vertex_relative = target_vertices - torch.nan_to_num(batch["wrist_root_translation"])[..., None, :] + relative_vertex_error = torch.linalg.vector_norm(predicted_vertex_relative - target_vertex_relative, dim=-1) * 1000.0 + if oracle_refinement: + coarse_vertices = prediction["coarse_vertices_camera"].float() + coarse_vertex_error = torch.linalg.vector_norm( + coarse_vertices - target_vertices, dim=-1, + ) * 1000.0 + coarse_vertex_relative = ( + coarse_vertices + - prediction["coarse_wrist_root_translation"].float()[..., None, :] + ) + coarse_relative_vertex_error = torch.linalg.vector_norm( + coarse_vertex_relative - target_vertex_relative, dim=-1, + ) * 1000.0 + + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"].float() * torch.tensor((width, height), device=device) + legacy_direct_2d = prediction["joint2d_norm"] * torch.tensor((width, height), device=device) + mano_2d, mano_positive = project_points(predicted_joints, batch["K"].float()) + target_2d = torch.nan_to_num(batch["joint2d"]) + direct_2d_error = torch.linalg.vector_norm(direct_2d - target_2d, dim=-1) + legacy_direct_2d_error = torch.linalg.vector_norm(legacy_direct_2d - target_2d, dim=-1) + mano_2d_error = torch.linalg.vector_norm(mano_2d - target_2d, dim=-1) + direct_mano_consistency = torch.linalg.vector_norm(direct_2d - mano_2d, dim=-1) + + for hand, side in enumerate(SIDES): + mask = joint_valid[..., hand, :] + hand_mask = mano_annotation[..., hand] + values[f"{side}_absolute_mpjpe_mm"].extend( + absolute_joint_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_root_relative_mpjpe_mm"].extend( + relative_joint_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_direct_2d_error_px"].extend( + direct_2d_error[..., hand, :][mask].cpu().tolist() + ) + values[f"{side}_legacy_bf16_direct_2d_error_px"].extend( + legacy_direct_2d_error[..., hand, :][mask].float().cpu().tolist() + ) + projected_mask = mask & mano_positive[..., hand, :] + values[f"{side}_mano_projected_2d_error_px"].extend( + mano_2d_error[..., hand, :][projected_mask].cpu().tolist() + ) + values[f"{side}_direct_mano_2d_consistency_px"].extend( + direct_mano_consistency[..., hand, :][projected_mask].cpu().tolist() + ) + values[f"{side}_absolute_mpvpe_mm"].extend(vertex_error[..., hand, :].mean(-1)[hand_mask].cpu().tolist()) + values[f"{side}_root_relative_mpvpe_mm"].extend(relative_vertex_error[..., hand, :].mean(-1)[hand_mask].cpu().tolist()) + for axis_index, axis in enumerate("xyz"): + values[f"{side}_translation_{axis}_mae_mm"].extend(translation_error[..., hand, axis_index][joint_annotation[..., hand]].cpu().tolist()) + if args.phase4_diagnostics: + values[f"{side}_translation_{axis}_signed_error_mm"].extend( + translation_signed_error[..., hand, axis_index][ + joint_annotation[..., hand] + ].cpu().tolist() + ) + for joint_index in range(21): + joint_mask = mask[..., joint_index] + per_joint[f"{side}_{joint_index:02d}_absolute_mpjpe_mm"].extend( + absolute_joint_error[..., hand, joint_index][joint_mask].cpu().tolist() + ) + fingertip_mask = mask[..., list(FINGERTIP_INDICES)] + fingertip_count = fingertip_mask.sum(-1) + values[f"{side}_fingertip_mpjpe_mm"].extend( + ( + (absolute_joint_error[..., hand, list(FINGERTIP_INDICES)] * fingertip_mask).sum(-1) + / fingertip_count.clamp_min(1) + )[fingertip_count > 0].cpu().tolist() + ) + + if predicted_joints.shape[1] > 1: + pair_valid = joint_annotation[:, 1:] & joint_annotation[:, :-1] + predicted_wrist_velocity = prediction["wrist_root_translation"][:, 1:] - prediction["wrist_root_translation"][:, :-1] + target_wrist_velocity = torch.nan_to_num(batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1]) + wrist_velocity_error = torch.linalg.vector_norm(predicted_wrist_velocity - target_wrist_velocity, dim=-1) * 1000.0 + values["wrist_velocity_error_mm_per_frame"].extend(wrist_velocity_error[pair_valid].float().cpu().tolist()) + predicted_joint_velocity = predicted_joints[:, 1:] - predicted_joints[:, :-1] + target_joint_velocity = target_joints[:, 1:] - target_joints[:, :-1] + pair_joint_valid = joint_valid[:, 1:] & joint_valid[:, :-1] + joint_velocity_error = torch.linalg.vector_norm(predicted_joint_velocity - target_joint_velocity, dim=-1) * 1000.0 + values["joint_velocity_error_mm_per_frame"].extend(joint_velocity_error[pair_joint_valid].cpu().tolist()) + acceleration_valid = None + acceleration_error = None + if predicted_wrist_velocity.shape[1] > 1: + acceleration_valid = pair_valid[:, 1:] & pair_valid[:, :-1] + predicted_acceleration = predicted_wrist_velocity[:, 1:] - predicted_wrist_velocity[:, :-1] + target_acceleration = target_wrist_velocity[:, 1:] - target_wrist_velocity[:, :-1] + acceleration_error = torch.linalg.vector_norm(predicted_acceleration - target_acceleration, dim=-1) * 1000.0 + values["wrist_acceleration_error_mm_per_frame2"].extend(acceleration_error[acceleration_valid].float().cpu().tolist()) + + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + for transition_index in range(pair_valid.shape[1]): + for hand, side in enumerate(SIDES): + if not bool(pair_valid[0, transition_index, hand]): + continue + valid_joint_mask = pair_joint_valid[0, transition_index, hand] + joint_value = ( + float(joint_velocity_error[0, transition_index, hand][valid_joint_mask].mean()) + if bool(valid_joint_mask.any()) else None + ) + acceleration_value = None + if ( + transition_index > 0 + and acceleration_valid is not None + and bool(acceleration_valid[0, transition_index - 1, hand]) + ): + acceleration_value = float(acceleration_error[0, transition_index - 1, hand]) + temporal_rows.append({ + "clip_index": clip_index, + "transition_index": transition_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id_from": int(batch["frame_id"][0, transition_index]), + "frame_id_to": int(batch["frame_id"][0, transition_index + 1]), + "side": side, + "wrist_velocity_error_mm_per_frame": float(wrist_velocity_error[0, transition_index, hand]), + "joint_velocity_error_mm_per_frame": joint_value, + "wrist_acceleration_error_mm_per_frame2": acceleration_value, + "identity_switch_fraction": None, + }) + + wrong_sequence: list[bool | None] = [] + valid_length = int(frame_valid[0].sum()) + for time_index in range(valid_length): + annotation_state = "".join(str(int(value)) for value in joint_annotation[0, time_index].int().cpu().tolist()) + both_valid = bool(joint_annotation[0, time_index].all()) + wrong_side = None + if both_valid: + correct = 0.5 * ( + absolute_joint_error[0, time_index, 0].mean() + + absolute_joint_error[0, time_index, 1].mean() + ) + swapped = 0.5 * ( + torch.linalg.vector_norm(predicted_joints[0, time_index, 0] - target_joints[0, time_index, 1], dim=-1).mean() + + torch.linalg.vector_norm(predicted_joints[0, time_index, 1] - target_joints[0, time_index, 0], dim=-1).mean() + ) * 1000.0 + wrong_side = bool(swapped < correct) + values["wrong_side_preference"].append(float(wrong_side)) + wrong_sequence.append(wrong_side) + valid_hand_errors = [ + float(absolute_joint_error[0, time_index, hand].mean()) + for hand in range(2) if joint_annotation[0, time_index, hand] + ] + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + frame_id = int(batch["frame_id"][0, time_index]) + sizes: list[float | None] = [None, None] + depths: list[float | None] = [None, None] + for hand in range(2): + is_valid = bool(joint_annotation[0, time_index, hand]) + if is_valid: + extent = batch["joint2d"][0, time_index, hand].max(0).values - batch["joint2d"][0, time_index, hand].min(0).values + sizes[hand] = float(extent.max()) + depths[hand] = float(batch["wrist_root_translation"][0, time_index, hand, 2]) + valid_sizes = [value for value in sizes if value is not None] + valid_depths = [value for value in depths if value is not None] + asymmetry = bimanual_asymmetry(sizes, depths) + if args.phase4_diagnostics: + action_label = load_action_label(args.root, take, frame_id) + action = action_name(action_label) + action_family = str(batch["sequence_id"][0]).split("/", 1)[0] + depth_np = batch["depth_m"][0, time_index, 0].float().cpu().numpy() + depth_valid_np = ( + batch["depth_pixel_valid"][0, time_index, 0].bool().cpu().numpy() + ) + else: + action_label = None + action = None + action_family = None + depth_np = None + depth_valid_np = None + for hand in range(2): + is_valid = bool(joint_annotation[0, time_index, hand]) + size = sizes[hand] + depth = depths[hand] + local_depth: dict[str, float | int | None] = {} + if args.phase4_diagnostics and is_valid: + local_depth = local_depth_statistics( + depth_np, + depth_valid_np, + batch["joint2d"][0, time_index, hand].float().cpu().numpy(), + ) + local_median = local_depth.get("depth_median_m") + local_surface_minus_wrist = ( + float(local_median) - float(depth) + if local_median is not None and depth is not None + else None + ) + row = { + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "side": SIDES[hand], + "annotation_valid": int(is_valid), + "annotation_state": annotation_state, + "hand_size_px": size, + "hand_size_bucket": hand_size_bucket(size), + "wrist_depth_m": depth, + "depth_bucket": wrist_depth_bucket(depth), + "absolute_mpjpe_mm": float(absolute_joint_error[0, time_index, hand].mean()) if is_valid else None, + "root_relative_mpjpe_mm": float(relative_joint_error[0, time_index, hand].mean()) if is_valid else None, + "absolute_mpvpe_mm": float(vertex_error[0, time_index, hand].mean()) if bool(mano_annotation[0, time_index, hand]) else None, + "root_relative_mpvpe_mm": float(relative_vertex_error[0, time_index, hand].mean()) if bool(mano_annotation[0, time_index, hand]) else None, + "direct_2d_error_px": float(direct_2d_error[0, time_index, hand].mean()) if is_valid else None, + "legacy_bf16_direct_2d_error_px": float(legacy_direct_2d_error[0, time_index, hand].mean()) if is_valid else None, + "mano_projected_2d_error_px": float(mano_2d_error[0, time_index, hand].mean()) if is_valid else None, + "direct_mano_2d_consistency_px": float(direct_mano_consistency[0, time_index, hand].mean()) if is_valid else None, + "fingertip_mpjpe_mm": float(absolute_joint_error[0, time_index, hand, list(FINGERTIP_INDICES)].mean()) if is_valid else None, + "translation_x_mae_mm": float(translation_error[0, time_index, hand, 0]) if is_valid else None, + "translation_y_mae_mm": float(translation_error[0, time_index, hand, 1]) if is_valid else None, + "translation_z_mae_mm": float(translation_error[0, time_index, hand, 2]) if is_valid else None, + "wrong_side_preference": int(wrong_side) if wrong_side is not None else None, + } + if args.phase4_diagnostics: + predicted_translation = prediction["wrist_root_translation"][ + 0, time_index, hand + ].float() + target_translation = batch["wrist_root_translation"][ + 0, time_index, hand + ].float() + row.update({ + "action_family": action_family, + "action_label": action_label, + "action_name": action, + **asymmetry, + "local_depth_valid_fraction": local_depth.get("valid_fraction"), + "local_depth_validity_bucket": depth_validity_bucket( + local_depth.get("valid_fraction") + ), + "local_depth_median_m": local_median, + "local_depth_q10_m": local_depth.get("depth_q10_m"), + "local_depth_q90_m": local_depth.get("depth_q90_m"), + "local_depth_iqr_m": local_depth.get("depth_iqr_m"), + "local_depth_discontinuity_m": local_depth.get( + "depth_discontinuity_m" + ), + "local_surface_minus_wrist_z_m": local_surface_minus_wrist, + "predicted_wrist_x_m": ( + float(predicted_translation[0]) if is_valid else None + ), + "predicted_wrist_y_m": ( + float(predicted_translation[1]) if is_valid else None + ), + "predicted_wrist_z_m": ( + float(predicted_translation[2]) if is_valid else None + ), + "target_wrist_x_m": float(target_translation[0]) if is_valid else None, + "target_wrist_y_m": float(target_translation[1]) if is_valid else None, + "target_wrist_z_m": float(target_translation[2]) if is_valid else None, + "translation_x_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 0]) + if is_valid else None + ), + "translation_y_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 1]) + if is_valid else None + ), + "translation_z_signed_error_mm": ( + float(translation_signed_error[0, time_index, hand, 2]) + if is_valid else None + ), + }) + if oracle_refinement: + mano_is_valid = bool(mano_annotation[0, time_index, hand]) + oracle_fields = { + "coarse_absolute_mpjpe_mm": ( + float(coarse_absolute_joint_error[0, time_index, hand].mean()) + if is_valid else None + ), + "coarse_root_relative_mpjpe_mm": ( + float(coarse_relative_joint_error[0, time_index, hand].mean()) + if is_valid else None + ), + "coarse_absolute_mpvpe_mm": ( + float(coarse_vertex_error[0, time_index, hand].mean()) + if mano_is_valid else None + ), + "coarse_root_relative_mpvpe_mm": ( + float(coarse_relative_vertex_error[0, time_index, hand].mean()) + if mano_is_valid else None + ), + "coarse_fingertip_mpjpe_mm": ( + float(coarse_absolute_joint_error[ + 0, time_index, hand, list(FINGERTIP_INDICES) + ].mean()) + if is_valid else None + ), + "coarse_translation_z_mae_mm": ( + float(coarse_translation_error[0, time_index, hand, 2]) + if is_valid else None + ), + "oracle_crop_delta_z_mm": ( + float(delta_z_mm[0, time_index, hand]) + if is_valid else None + ), + "oracle_crop_rotation_delta_geodesic_deg": ( + float(rotation_delta_degrees[0, time_index, hand]) + if is_valid else None + ), + "oracle_crop_shape_delta_l2": ( + float(shape_delta_l2[0, hand]) if is_valid else None + ), + "oracle_crop_rgb_available": int( + prediction["oracle_crop_rgb_available"][0, time_index, hand] + ), + "oracle_crop_depth_available": int( + prediction["oracle_crop_depth_available_effective"][ + 0, time_index, hand + ] + ), + } + row.update(oracle_fields) + if is_valid: + for key, value in oracle_fields.items(): + if key.startswith("oracle_crop_") and value is not None: + oracle_refinement_values[key].append(float(value)) + frame_rows.append(row) + selection_records.append({ + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "annotation_state": annotation_state, + "hand_size_bucket": hand_size_bucket(float(np.mean(valid_sizes))) if valid_sizes else None, + "depth_bucket": wrist_depth_bucket(float(np.mean(valid_depths))) if valid_depths else None, + "absolute_mpjpe_mm": float(np.mean(valid_hand_errors)) if valid_hand_errors else None, + }) + for transition_index, (previous, current) in enumerate( + zip(wrong_sequence[:-1], wrong_sequence[1:], strict=True) + ): + if previous is not None and current is not None: + identity_switch = float(previous != current) + values["identity_switch_fraction"].append(identity_switch) + temporal_rows.append({ + "clip_index": clip_index, + "transition_index": transition_index, + "take": f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4", + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id_from": int(batch["frame_id"][0, transition_index]), + "frame_id_to": int(batch["frame_id"][0, transition_index + 1]), + "side": "bimanual", + "wrist_velocity_error_mm_per_frame": None, + "joint_velocity_error_mm_per_frame": None, + "wrist_acceleration_error_mm_per_frame2": None, + "identity_switch_fraction": identity_switch, + }) + + attention = prediction["attention"] + rgb = attention["rgb_cross_attention"][:, -1] + left, right = rgb[..., 0, :], rgb[..., 1, :] + attention_values["rgb_same_peak"].extend((left.argmax(-1) == right.argmax(-1))[frame_valid].float().cpu().tolist()) + attention_values["rgb_left_right_cosine"].extend(torch.nn.functional.cosine_similarity(left, right, dim=-1)[frame_valid].float().cpu().tolist()) + attention_values["rgb_update_norm"].extend(attention["rgb_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + for key in ("depth_fusion_gate", "depth_fusion_gate_raw", "depth_update_norm", "gated_depth_update_norm"): + if key in attention: + attention_values[key].extend(attention[key][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + if "temporal_update_norm" in attention: + attention_values["temporal_update_norm"].extend( + attention["temporal_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist() + ) + if "temporal_attention" in attention: + temporal = attention["temporal_attention"][:, -1] + for hand in range(2): + valid_indices = torch.where(frame_valid[0])[0] + for query_index in valid_indices: + weights = temporal[0, hand, query_index, valid_indices].float() + normalized = weights / weights.sum().clamp_min(1e-8) + if normalized.numel() > 1: + entropy = -(normalized * normalized.clamp_min(1e-8).log()).sum() / np.log(normalized.numel()) + attention_values["temporal_normalized_entropy"].append(float(entropy)) + attention_values["temporal_diagonal"].append(float(temporal[0, hand, query_index, query_index])) + for key_index, key_frame in enumerate(valid_indices): + signed_distance = int(key_frame) - int(query_index) + temporal_by_distance[abs(signed_distance)].append(float(weights[key_index])) + temporal_by_signed_distance[signed_distance].append(float(weights[key_index])) + + selections = select_visualization_frames(selection_records, seed=args.seed) + strata_counts = { + field: { + str(value): sum(record.get(field) == value for record in selection_records) + for value in values_to_count + } + for field, values_to_count in ( + ("hand_size_bucket", ("small", "medium", "large")), + ("depth_bucket", ("near", "middle", "far")), + ("annotation_state", ("00", "01", "10", "11")), + ) + } + selection_manifest = { + "seed": args.seed, + "source_manifest": str(args.manifest.resolve()), + "clip_indices_manifest": ( + { + "path": str(args.clip_indices_manifest.resolve()), + "sha256": sha256(args.clip_indices_manifest), + "version": subset_record.get("version"), + "count": subset_record.get("count"), + } + if args.clip_indices_manifest is not None else None + ), + "checkpoint": str(args.checkpoint.resolve()), + "selection_policy": "random4 + error P50/P90/P95/worst + size/depth/valid-state medians", + "strata_counts": strata_counts, + "unavailable_requested_strata": [ + f"{field}={value}" + for field, counts in strata_counts.items() + for value, count in counts.items() if count == 0 + ], + "samples": selections, + } + (args.output_dir / "selection_manifest.json").write_text(json.dumps(selection_manifest, indent=2) + "\n", encoding="utf-8") + write_csv(args.output_dir / "per_hand_frame_metrics.csv", frame_rows) + write_csv(args.output_dir / "per_temporal_transition_metrics.csv", temporal_rows) + phase4_group_rows: list[dict[str, object]] = [] + phase4_failure_rows: list[dict[str, object]] = [] + if args.phase4_diagnostics: + phase4_metrics = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + ) + if oracle_refinement_values: + phase4_metrics += ( + "coarse_absolute_mpjpe_mm", + "coarse_root_relative_mpjpe_mm", + "coarse_absolute_mpvpe_mm", + "coarse_root_relative_mpvpe_mm", + "coarse_fingertip_mpjpe_mm", + "coarse_translation_z_mae_mm", + "oracle_crop_delta_z_mm", + "oracle_crop_rotation_delta_geodesic_deg", + "oracle_crop_shape_delta_l2", + ) + phase4_group_rows = summarize_group_metrics( + frame_rows, + phase4_metrics, + ( + "take", + "action_family", + "action_label", + "action_name", + "hand_size_bucket", + "depth_bucket", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", + ), + ) + phase4_failure_rows = find_failure_intervals( + frame_rows, + metric="translation_z_mae_mm", + threshold=40.0, + minimum_frames=3, + ) + find_failure_intervals( + frame_rows, + metric="absolute_mpjpe_mm", + threshold=50.0, + minimum_frames=3, + ) + write_csv(args.output_dir / "phase4_group_metrics.csv", phase4_group_rows) + write_csv(args.output_dir / "phase4_failure_intervals.csv", phase4_failure_rows) + + joint_rows = [] + for name, metric_values in sorted(per_joint.items()): + side, joint_index, _ = name.split("_", 2) + joint_rows.append({"side": side, "joint_index": int(joint_index), **distribution_summary(metric_values)}) + write_csv(args.output_dir / "per_joint_metrics.csv", joint_rows) + + bootstrap_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", "direct_2d_error_px", "mano_projected_2d_error_px", + "translation_z_mae_mm", "fingertip_mpjpe_mm", "wrong_side_preference", + ) + bootstrap_rows = bootstrap_take_means( + frame_rows, bootstrap_metrics, seed=args.seed, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "bootstrap_ci.csv", bootstrap_rows) + temporal_bootstrap_metrics = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", + ) + temporal_bootstrap_rows = bootstrap_take_means( + temporal_rows, temporal_bootstrap_metrics, + seed=args.seed, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "temporal_bootstrap_ci.csv", temporal_bootstrap_rows) + + distribution_metrics = {key: distribution_summary(metric_values) for key, metric_values in sorted(values.items())} + combined_keys = { + "absolute_mpjpe_mm": ("left_absolute_mpjpe_mm", "right_absolute_mpjpe_mm"), + "root_relative_mpjpe_mm": ("left_root_relative_mpjpe_mm", "right_root_relative_mpjpe_mm"), + "absolute_mpvpe_mm": ("left_absolute_mpvpe_mm", "right_absolute_mpvpe_mm"), + "root_relative_mpvpe_mm": ("left_root_relative_mpvpe_mm", "right_root_relative_mpvpe_mm"), + "direct_2d_error_px": ("left_direct_2d_error_px", "right_direct_2d_error_px"), + "legacy_bf16_direct_2d_error_px": ("left_legacy_bf16_direct_2d_error_px", "right_legacy_bf16_direct_2d_error_px"), + "mano_projected_2d_error_px": ("left_mano_projected_2d_error_px", "right_mano_projected_2d_error_px"), + "direct_mano_2d_consistency_px": ("left_direct_mano_2d_consistency_px", "right_direct_mano_2d_consistency_px"), + "fingertip_mpjpe_mm": ("left_fingertip_mpjpe_mm", "right_fingertip_mpjpe_mm"), + "translation_z_mae_mm": ("left_translation_z_mae_mm", "right_translation_z_mae_mm"), + } + for combined, components in combined_keys.items(): + distribution_metrics[combined] = distribution_summary(values[components[0]] + values[components[1]]) + + attention_report = { + key: distribution_summary(metric_values) for key, metric_values in sorted(attention_values.items()) + } + attention_report["temporal_attention_by_absolute_frame_distance"] = { + str(distance): distribution_summary(metric_values) + for distance, metric_values in sorted(temporal_by_distance.items()) + } + attention_report["temporal_attention_by_signed_frame_distance"] = { + str(distance): distribution_summary(metric_values) + for distance, metric_values in sorted(temporal_by_signed_distance.items()) + } + (args.output_dir / "attention_diagnostics.json").write_text(json.dumps(attention_report, indent=2) + "\n", encoding="utf-8") + position_bias_report = temporal_position_bias_report(model) + (args.output_dir / "temporal_position_bias.json").write_text( + json.dumps(position_bias_report, indent=2) + "\n", encoding="utf-8", + ) + + report = { + "status": "evaluated", + "split_role": "official_validation" if "val" in args.manifest.name else "non_test_evaluation", + "official_test_used": False, + "config": config, + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": sha256(args.checkpoint), + "step": int(checkpoint_state["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "inference_modality_override": { + "drop_depth": bool(args.drop_depth), + "drop_k": bool(args.drop_k), + "availability_contract": "input_and_legacy_flags_v2", + }, + "clips": len(evaluation_dataset), + "clip_indices_manifest": ( + { + "path": str(args.clip_indices_manifest.resolve()), + "sha256": sha256(args.clip_indices_manifest), + "version": subset_record.get("version"), + "count": subset_record.get("count"), + } + if args.clip_indices_manifest is not None else None + ), + "frames": frame_count, + "data_loader_workers": args.num_workers, + "metrics": distribution_metrics, + "attention": attention_report, + "temporal_position_bias": position_bias_report, + "bootstrap": bootstrap_rows, + "temporal_bootstrap": temporal_bootstrap_rows, + "phase4_diagnostics": { + "enabled": bool(args.phase4_diagnostics), + "group_rows": len(phase4_group_rows), + "failure_intervals": len(phase4_failure_rows), + "local_depth_contract": ( + "GT-joint region on aligned resized metric depth; surface statistics are " + "diagnostic and are not wrist-depth targets" + if args.phase4_diagnostics else None + ), + "failure_thresholds": ( + {"translation_z_mae_mm": 40.0, "absolute_mpjpe_mm": 50.0} + if args.phase4_diagnostics else None + ), + }, + "oracle_crop_refinement": { + "enabled": bool(oracle_refinement_values), + "gt_location_at_inference": bool(oracle_refinement_values), + "coarse_checkpoint_sha256": config.get("experiment", {}).get( + "coarse_checkpoint_sha256" + ), + "metrics": { + key: distribution_summary(metric_values) + for key, metric_values in sorted(oracle_refinement_values.items()) + }, + }, + "metric_definitions": { + "absolute_mpjpe_mm": "valid-joint-weighted Euclidean camera-space joint error", + "direct_2d_error_px": "valid-joint-weighted direct-head pixel error; frame means are used for take bootstrap", + "legacy_bf16_direct_2d_error_px": "Phase 2 compatibility metric that scales bf16 normalized coordinates before float conversion", + "absolute_mpvpe_mm": "mean Euclidean camera-space vertex error; MVE/MPVPE", + "root_relative_mpvpe_mm": "vertex error after subtracting each wrist/root", + "wrong_side_preference": "swapped L/R joint assignment has lower combined cost than semantic assignment", + "identity_switch_fraction": "adjacent both-valid frames change wrong-side assignment preference", + "translation_axis_signed_error_mm": "predicted camera-space wrist axis minus GT wrist axis", + "cvar95": "mean of observations at or above the empirical 95th percentile", + "attention": "last-layer, PyTorch head-averaged attention weights; not calibrated probability", + }, + "presence_note": "H2O annotation validity is not presence; no presence metric is reported.", + "device": torch.cuda.get_device_name(device), + "trainable_parameters": sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad), + "frozen_parameters": sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad), + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + + if not args.skip_visualizations: + visualize_selections( + selections, dataset, model, device, dtype, config, + args.output_dir / "visualization_audit", + ) + print(json.dumps({ + "status": report["status"], "clips": report["clips"], "frames": report["frames"], + "absolute_mpjpe_mm": distribution_metrics["absolute_mpjpe_mm"]["mean"], + "absolute_mpvpe_mm": distribution_metrics["absolute_mpvpe_mm"]["mean"], + "output_dir": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase4_jitter.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase4_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..01ef42bd758f0d15f63365ddcabec5115ffd2f99 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase4_jitter.py @@ -0,0 +1,767 @@ +#!/usr/bin/env python3 +"""Evaluate preregistered inference-only temporal filters from raw caches.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +import numpy as np +import torch + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.temporal_filter import ( + apply_by_segment, + butterworth_zero_phase, + derivative_norms, + ema, + ema_low_frequency_delay_frames, + filter_rotation_matrices, + high_frequency_energy_ratio, + rotation_geodesic_degrees, + valid_segments, +) +from foundation_hand.models.mano import ManoCameraLayer + + +FPS = 30.0 +FINGERTIPS = (4, 8, 12, 16, 20) + + +@dataclass(frozen=True) +class FilterCondition: + name: str + family: str + value: float | None + causal_status: str + latency_frames: float | None + + +def condition_grid() -> dict[str, FilterCondition]: + conditions = { + "F0_raw": FilterCondition("F0_raw", "F0", None, "raw", 0.0), + } + for alpha in (0.2, 0.4, 0.6): + name = f"F1_ema_alpha{alpha:g}" + conditions[name] = FilterCondition( + name, "F1", alpha, "causal", ema_low_frequency_delay_frames(alpha), + ) + for cutoff in (2.0, 4.0, 6.0): + name = f"F2_butterworth_{cutoff:g}hz" + conditions[name] = FilterCondition( + name, "F2", cutoff, "offline_zero_phase", None, + ) + return conditions + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty jitter report: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_take(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + if float(arrays["fps"]) != FPS: + raise ValueError(f"jitter cache fps mismatch: {path}") + return arrays + + +def filtered_parameters( + arrays: dict[str, np.ndarray], condition: FilterCondition, +) -> tuple[np.ndarray, np.ndarray, int]: + translation = arrays["pred_wrist_translation"].astype(np.float32) + rotations = arrays["pred_rotation_matrices"].astype(np.float32) + if condition.family == "F0": + return translation.copy(), rotations.copy(), 0 + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + if condition.family == "F1": + assert condition.value is not None + translation, fallback_translation = apply_by_segment( + translation, segments, + lambda values: ema(values, condition.value), minimum_frames=1, + ) + rotations, fallback_rotation = apply_by_segment( + rotations, segments, + lambda values: filter_rotation_matrices( + values, lambda quaternion: ema(quaternion, condition.value), + ), + minimum_frames=1, + ) + elif condition.family == "F2": + assert condition.value is not None + operation = lambda values: butterworth_zero_phase( + values, condition.value, FPS, order=2, + ) + translation, fallback_translation = apply_by_segment( + translation, segments, operation, minimum_frames=4, + ) + rotations, fallback_rotation = apply_by_segment( + rotations, segments, + lambda values: filter_rotation_matrices(values, operation), + minimum_frames=4, + ) + else: + raise ValueError(f"unsupported filter family: {condition.family}") + if fallback_translation != fallback_rotation: + raise AssertionError("translation/rotation filter fallback counts differ") + return translation, rotations, fallback_translation + + +def rebuild_geometry( + rotations: np.ndarray, + shape: np.ndarray, + translation: np.ndarray, + mano: ManoCameraLayer, + device: torch.device, + chunk_size: int = 256, +) -> tuple[np.ndarray, np.ndarray]: + vertices = [] + joints = [] + for start in range(0, len(rotations), chunk_size): + stop = min(start + chunk_size, len(rotations)) + with torch.inference_mode(): + chunk_vertices, chunk_joints = mano( + torch.from_numpy(rotations[start:stop]).to(device), + torch.from_numpy(shape[start:stop]).to(device), + torch.from_numpy(translation[start:stop]).to(device), + ) + vertices.append(chunk_vertices.cpu().numpy()) + joints.append(chunk_joints.cpu().numpy()) + return np.concatenate(vertices), np.concatenate(joints) + + +def project_points(points: np.ndarray, intrinsics: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + z = points[..., 2] + positive = np.isfinite(points).all(axis=-1) & (z > 1e-8) + safe_z = np.where(positive, z, 1.0) + x = intrinsics[:, None, None, 0, 0] * points[..., 0] / safe_z + x += intrinsics[:, None, None, 0, 2] + y = intrinsics[:, None, None, 1, 1] * points[..., 1] / safe_z + y += intrinsics[:, None, None, 1, 2] + projected = np.stack((x, y), axis=-1) + projected[~positive] = np.nan + return projected, positive + + +def append_finite(output: dict[str, list[float]], key: str, values: Iterable[float]) -> None: + output[key].extend(float(value) for value in values if np.isfinite(value)) + + +def per_frame_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + vertices: np.ndarray, + rotations: np.ndarray, + translation: np.ndarray, + frame_selected: np.ndarray, +) -> tuple[dict[str, list[float]], np.ndarray, np.ndarray]: + output: dict[str, list[float]] = defaultdict(list) + target_joints = arrays["target_joints_camera"] + target_vertices = arrays["target_vertices_camera"] + target_translation = arrays["target_wrist_translation"] + joint_valid = arrays["joint_element_valid"].astype(bool) + joint_valid &= frame_selected[:, None, None] + mano_valid = arrays["mano_annotation_valid"].astype(bool) + mano_valid &= frame_selected[:, None] + + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + joint_relative = joints - joints[..., :1, :] + target_joint_relative = target_joints - target_joints[..., :1, :] + root_joint_error = np.linalg.norm( + joint_relative - target_joint_relative, axis=-1, + ) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + vertex_relative = vertices - translation[..., None, :] + target_vertex_relative = target_vertices - target_translation[..., None, :] + root_vertex_error = np.linalg.norm( + vertex_relative - target_vertex_relative, axis=-1, + ) * 1000.0 + translation_signed = (translation - target_translation) * 1000.0 + + projected, projected_positive = project_points(joints, arrays["K"]) + projected_valid = joint_valid & projected_positive + target_2d = arrays["target_2d_px"] + projected_error = np.linalg.norm(projected - target_2d, axis=-1) + consistency = np.linalg.norm(projected - arrays["pred_direct_2d_px"], axis=-1) + direct_error = np.linalg.norm(arrays["pred_direct_2d_px"] - target_2d, axis=-1) + rotation_error = rotation_geodesic_degrees( + rotations, arrays["target_rotation_matrices"], + ).mean(axis=-1) + + for time_index in range(len(joints)): + for hand in range(2): + valid_joints = joint_valid[time_index, hand] + if valid_joints.any(): + append_finite(output, "absolute_mpjpe_mm", [ + joint_error[time_index, hand, valid_joints].mean() + ]) + append_finite(output, "root_relative_mpjpe_mm", [ + root_joint_error[time_index, hand, valid_joints].mean() + ]) + fingertip_valid = valid_joints[list(FINGERTIPS)] + if fingertip_valid.any(): + fingertip_values = joint_error[ + time_index, hand, list(FINGERTIPS) + ][fingertip_valid] + append_finite(output, "fingertip_mpjpe_mm", [fingertip_values.mean()]) + append_finite(output, "direct_2d_error_px", [ + direct_error[time_index, hand, valid_joints].mean() + ]) + valid_projected = projected_valid[time_index, hand] + if valid_projected.any(): + append_finite(output, "projected_mano_2d_error_px", [ + projected_error[time_index, hand, valid_projected].mean() + ]) + append_finite(output, "direct_mano_consistency_px", [ + consistency[time_index, hand, valid_projected].mean() + ]) + for axis, name in enumerate("xyz"): + append_finite(output, f"translation_{name}_signed_error_mm", [ + translation_signed[time_index, hand, axis] + ]) + append_finite(output, f"translation_{name}_mae_mm", [ + abs(translation_signed[time_index, hand, axis]) + ]) + if mano_valid[time_index, hand]: + append_finite(output, "absolute_mpvpe_mm", [ + vertex_error[time_index, hand].mean() + ]) + append_finite(output, "root_relative_mpvpe_mm", [ + root_vertex_error[time_index, hand].mean() + ]) + append_finite(output, "rotation_geodesic_error_deg", [ + rotation_error[time_index, hand] + ]) + return output, projected, joint_valid + + +def selected_segments( + arrays: dict[str, np.ndarray], frame_selected: np.ndarray, +) -> list[np.ndarray]: + return valid_segments( + arrays["clip_index"], arrays["frame_id"], + arrays["frame_valid"].astype(bool) & frame_selected, + ) + + +def temporal_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + projected: np.ndarray, + frame_selected: np.ndarray, +) -> dict[str, list[float]]: + output: dict[str, list[float]] = defaultdict(list) + segments = selected_segments(arrays, frame_selected) + target = arrays["target_joints_camera"] + annotation = arrays["joint_element_valid"].astype(bool) + for indices in segments: + for hand in range(2): + predicted_hand = joints[indices, hand] + target_hand = target[indices, hand] + valid_hand = annotation[indices, hand] + for order, error_name in ( + (1, "joint_velocity_error_mm_per_s"), + (2, "joint_acceleration_error_mm_per_s2"), + ): + if len(indices) <= order: + continue + predicted_derivative = np.diff(predicted_hand, n=order, axis=0) * FPS**order + target_derivative = np.diff(target_hand, n=order, axis=0) * FPS**order + derivative_valid = np.stack([ + valid_hand[start : len(valid_hand) - order + start] + for start in range(order + 1) + ]).all(axis=0) + errors = np.linalg.norm( + predicted_derivative - target_derivative, axis=-1, + ) * 1000.0 + for row, valid in zip(errors, derivative_valid, strict=True): + if valid.any(): + append_finite(output, error_name, [row[valid].mean()]) + translation_hand = joints[indices, hand, 0] + target_translation_hand = arrays["target_wrist_translation"][indices, hand] + translation_valid = arrays["joint_annotation_valid"][indices, hand].astype(bool) + for order, error_name in ( + (1, "wrist_velocity_error_mm_per_s"), + (2, "wrist_acceleration_error_mm_per_s2"), + ): + if len(indices) <= order: + continue + predicted_derivative = np.diff( + translation_hand, n=order, axis=0, + ) * FPS**order + target_derivative = np.diff( + target_translation_hand, n=order, axis=0, + ) * FPS**order + derivative_valid = np.stack([ + translation_valid[start : len(translation_valid) - order + start] + for start in range(order + 1) + ]).all(axis=0) + errors = np.linalg.norm( + predicted_derivative - target_derivative, axis=-1, + ) * 1000.0 + append_finite(output, error_name, errors[derivative_valid]) + if len(indices) >= 3: + acceleration = derivative_norms(predicted_hand, FPS, 2) * 1000.0 + append_finite( + output, "predicted_3d_joint_acceleration_mm_per_s2", + acceleration.mean(axis=-1), + ) + projected_acceleration = derivative_norms( + projected[indices, hand], FPS, 2, + ) + append_finite( + output, "predicted_2d_joint_acceleration_px_per_s2", + np.nanmean(projected_acceleration, axis=-1), + ) + if len(indices) >= 4: + jerk = derivative_norms(predicted_hand, FPS, 3) * 1000.0 + append_finite( + output, "predicted_3d_joint_jerk_mm_per_s3", + jerk.mean(axis=-1), + ) + projected_jerk = derivative_norms(projected[indices, hand], FPS, 3) + append_finite( + output, "predicted_2d_joint_jerk_px_per_s3", + np.nanmean(projected_jerk, axis=-1), + ) + append_finite(output, "high_frequency_energy_ratio", [ + high_frequency_energy_ratio(predicted_hand, FPS, 6.0) + ]) + if len(indices) >= 3: + velocity = derivative_norms(predicted_hand, FPS, 1).mean(axis=-1) + append_finite(output, "velocity_variation_m_per_s", [ + np.std(velocity) + ]) + + # Report jumps at clip boundaries without allowing the filter to cross them. + for index in range(1, len(joints)): + if ( + frame_selected[index - 1] + and frame_selected[index] + and arrays["frame_valid"][index - 1] + and arrays["frame_valid"][index] + and arrays["frame_id"][index] == arrays["frame_id"][index - 1] + 1 + and arrays["clip_index"][index] != arrays["clip_index"][index - 1] + ): + jump = np.linalg.norm(joints[index] - joints[index - 1], axis=-1) * 1000.0 + append_finite( + output, "clip_boundary_discontinuity_mm", jump.mean(axis=-1), + ) + return output + + +def identity_switch_metrics( + arrays: dict[str, np.ndarray], + joints: np.ndarray, + frame_selected: np.ndarray, +) -> dict[str, list[float]]: + wrong: list[bool | None] = [] + target = arrays["target_joints_camera"] + annotation = arrays["joint_annotation_valid"].astype(bool) + for index in range(len(joints)): + if not frame_selected[index] or not annotation[index].all(): + wrong.append(None) + continue + semantic = ( + np.linalg.norm(joints[index, 0] - target[index, 0], axis=-1).mean() + + np.linalg.norm(joints[index, 1] - target[index, 1], axis=-1).mean() + ) + swapped = ( + np.linalg.norm(joints[index, 0] - target[index, 1], axis=-1).mean() + + np.linalg.norm(joints[index, 1] - target[index, 0], axis=-1).mean() + ) + wrong.append(bool(swapped < semantic)) + switches = [] + for indices in selected_segments(arrays, frame_selected): + for previous, current in zip(indices[:-1], indices[1:], strict=True): + if wrong[previous] is not None and wrong[current] is not None: + switches.append(float(wrong[previous] != wrong[current])) + return {"identity_switch_fraction": switches} + + +def summarize_condition( + values: dict[str, list[float]], + condition: FilterCondition, + scope: str, +) -> list[dict[str, object]]: + return [ + { + "scope": scope, "condition": condition.name, + "family": condition.family, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + "metric": metric, **distribution_summary(observations), + } + for metric, observations in sorted(values.items()) + ] + + +def metric_lookup(rows: list[dict[str, object]], condition: str, metric: str) -> dict[str, object]: + matches = [ + row for row in rows + if row["condition"] == condition and row["metric"] == metric + ] + if len(matches) != 1: + raise ValueError(f"expected one jitter metric row for {condition}/{metric}") + return matches[0] + + +def build_overview( + metric_rows: list[dict[str, object]], conditions: list[FilterCondition], + scope: str, +) -> list[dict[str, object]]: + raw_name = "F0_raw" + keys = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "z_p95_mm": ("translation_z_mae_mm", "p95"), + "velocity_error_mm_per_s": ("joint_velocity_error_mm_per_s", "mean"), + "acceleration_error_mm_per_s2": ("joint_acceleration_error_mm_per_s2", "mean"), + "jitter_3d_acceleration_mm_per_s2": ( + "predicted_3d_joint_acceleration_mm_per_s2", "mean", + ), + "jitter_3d_jerk_mm_per_s3": ("predicted_3d_joint_jerk_mm_per_s3", "mean"), + "jitter_2d_acceleration_px_per_s2": ( + "predicted_2d_joint_acceleration_px_per_s2", "mean", + ), + "jitter_2d_jerk_px_per_s3": ("predicted_2d_joint_jerk_px_per_s3", "mean"), + "high_frequency_energy_ratio": ("high_frequency_energy_ratio", "mean"), + } + raw = { + name: float(metric_lookup(metric_rows, raw_name, metric)[statistic]) + for name, (metric, statistic) in keys.items() + } + output = [] + for condition in conditions: + values = { + name: float(metric_lookup(metric_rows, condition.name, metric)[statistic]) + for name, (metric, statistic) in keys.items() + } + row: dict[str, object] = { + "scope": scope, "condition": condition.name, + "family": condition.family, "filter_value": condition.value, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + } + for name, value in values.items(): + row[name] = value + row[f"{name}_delta"] = value - raw[name] + guardrails = [ + 100.0 * (values[name] - raw[name]) / raw[name] + for name in ( + "absolute_mpjpe_mm", "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", "z_p95_mm", + ) + ] + reductions = [ + (raw[name] - values[name]) / raw[name] + for name in ( + "jitter_3d_acceleration_mm_per_s2", + "jitter_3d_jerk_mm_per_s3", + "jitter_2d_acceleration_px_per_s2", + "jitter_2d_jerk_px_per_s3", + ) + ] + row["maximum_accuracy_degradation_percent"] = max(guardrails) + row["accuracy_guardrail_passed"] = bool(max(guardrails) <= 1.0) + row["jitter_reduction_score"] = float(np.mean(reductions)) + row["accuracy_delta"] = row["absolute_mpjpe_mm_delta"] + row["jitter_delta"] = row["jitter_3d_acceleration_mm_per_s2_delta"] + row["velocity_error_delta"] = row["velocity_error_mm_per_s_delta"] + row["acceleration_error_delta"] = row[ + "acceleration_error_mm_per_s2_delta" + ] + row["selected_for_full_validation"] = False + output.append(row) + return output + + +def paired_take_bootstrap_rows( + take_rows: list[dict[str, object]], + conditions: list[FilterCondition], + *, + samples: int, + seed: int = 20260716, +) -> list[dict[str, object]]: + if samples < 1: + raise ValueError("bootstrap samples must be positive") + index = { + (str(row["take"]), str(row["condition"]), str(row["metric"])): row + for row in take_rows + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(conditions): + if condition.family == "F0": + continue + for metric_index, metric in enumerate(metrics): + for statistic_name in ("mean", "p95"): + paired = [] + raw_values = [] + filtered_values = [] + for take in takes: + raw = index.get((take, "F0_raw", metric)) + filtered = index.get((take, condition.name, metric)) + if raw is None or filtered is None: + continue + raw_value = raw.get(statistic_name) + filtered_value = filtered.get(statistic_name) + if raw_value is None or filtered_value is None: + continue + raw_float = float(raw_value) + filtered_float = float(filtered_value) + if not np.isfinite(raw_float) or not np.isfinite(filtered_float): + continue + raw_values.append(raw_float) + filtered_values.append(filtered_float) + paired.append(filtered_float - raw_float) + deltas = np.asarray(paired, dtype=np.float64) + if not len(deltas): + continue + rng = np.random.default_rng(np.random.SeedSequence([ + seed, condition_index, metric_index, + 0 if statistic_name == "mean" else 1, + ])) + indices = rng.integers(0, len(deltas), size=(samples, len(deltas))) + bootstrap = deltas[indices].mean(axis=1) + output.append({ + "scope": take_rows[0]["scope"], + "condition": condition.name, + "family": condition.family, + "metric": metric, + "take_statistic": statistic_name, + "takes": len(deltas), + "raw": float(np.mean(raw_values)), + "filtered": float(np.mean(filtered_values)), + "filtered_minus_raw": float(deltas.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def choose_filter_conditions(overview: list[dict[str, object]]) -> dict[str, str | None]: + selected: dict[str, str | None] = {"F1": None, "F2": None} + for family in selected: + candidates = [ + row for row in overview + if row["family"] == family and row["accuracy_guardrail_passed"] + ] + if not candidates: + continue + candidates.sort(key=lambda row: ( + -float(row["jitter_reduction_score"]), + float(row["acceleration_error_mm_per_s2"]), + float(row["absolute_mpjpe_mm"]), + -float(row["filter_value"]), + )) + selected[family] = str(candidates[0]["condition"]) + candidates[0]["selected_for_full_validation"] = True + return selected + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument( + "--scope", choices=("smoke", "subset", "full"), required=True, + ) + parser.add_argument("--subset-manifest", type=Path) + parser.add_argument("--selection-json", type=Path) + parser.add_argument("--conditions") + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise ValueError("jitter output directory must be new or empty") + cache_manifest = json.loads( + (args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8") + ) + expected_cache_scope = "smoke" if args.scope == "smoke" else "full" + if ( + cache_manifest.get("status") != "complete" + or cache_manifest.get("official_test_used") is not False + or float(cache_manifest.get("fps")) != FPS + or cache_manifest.get("scope") != expected_cache_scope + or ( + expected_cache_scope == "full" + and (cache_manifest.get("clips") != 1495 or cache_manifest.get("frames") != 11638) + ) + ): + raise ValueError("invalid raw jitter cache manifest") + grid = condition_grid() + if args.conditions: + requested = [value.strip() for value in args.conditions.split(",") if value.strip()] + else: + requested = list(grid) + if not requested or set(requested) - set(grid) or "F0_raw" not in requested: + raise ValueError("jitter conditions must be registered and include F0_raw") + if args.scope == "subset": + if args.subset_manifest is None or args.selection_json is not None: + raise ValueError("subset scope requires only --subset-manifest") + subset = json.loads(args.subset_manifest.read_text(encoding="utf-8")) + selected_clip_indices = {int(value) for value in subset["clip_indices"]} + if ( + len(selected_clip_indices) != 256 + or subset.get("source_manifest_sha256") + != cache_manifest["manifest"]["sha256"] + or subset.get("official_test_used", False) is not False + ): + raise ValueError("jitter tuning subset must be the frozen 256 clips") + elif args.scope == "full": + if args.selection_json is None or args.subset_manifest is not None: + raise ValueError("full scope requires only --selection-json") + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + selected_names = { + value for value in selection["selected_conditions"].values() + if value is not None + } + if set(requested) != {"F0_raw", *selected_names}: + raise ValueError("full evaluation conditions differ from frozen subset selection") + selected_clip_indices = None + else: + if args.selection_json is not None or args.subset_manifest is not None: + raise ValueError("smoke scope does not accept selection/subset inputs") + selected_clip_indices = None + + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + conditions = [grid[name] for name in requested] + global_values: dict[str, dict[str, list[float]]] = { + condition.name: defaultdict(list) for condition in conditions + } + take_rows = [] + fallback_rows = [] + for take_record in cache_manifest["takes"]: + arrays = load_take(Path(take_record["path"])) + frame_selected = ( + np.ones(len(arrays["frame_id"]), dtype=bool) + if selected_clip_indices is None else + np.isin(arrays["clip_index"], list(selected_clip_indices)) + ) + if not frame_selected.any(): + continue + take = str(arrays["take"]) + for condition in conditions: + translation, rotations, fallbacks = filtered_parameters(arrays, condition) + vertices, joints = rebuild_geometry( + rotations, arrays["pred_shape"].astype(np.float32), + translation, mano, device, + ) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, rotations, translation, frame_selected, + ) + for metric, values in temporal_metrics( + arrays, joints, projected, frame_selected, + ).items(): + metrics[metric].extend(values) + for metric, values in identity_switch_metrics( + arrays, joints, frame_selected, + ).items(): + metrics[metric].extend(values) + for metric, observations in metrics.items(): + global_values[condition.name][metric].extend(observations) + summary = distribution_summary(observations) + take_rows.append({ + "scope": args.scope, "take": take, + "condition": condition.name, "family": condition.family, + "metric": metric, **summary, + }) + fallback_rows.append({ + "scope": args.scope, "take": take, + "condition": condition.name, + "fallback_segments": fallbacks, + }) + metric_rows = [] + for condition in conditions: + metric_rows.extend(summarize_condition( + global_values[condition.name], condition, args.scope, + )) + overview = build_overview(metric_rows, conditions, args.scope) + if args.scope == "full": + for row in overview: + row["selected_for_full_validation"] = row["family"] != "F0" + paired_rows = paired_take_bootstrap_rows( + take_rows, conditions, samples=args.bootstrap_samples, + ) + selection_payload = None + if args.scope == "subset": + selected = choose_filter_conditions(overview) + selection_payload = { + "status": "selected", + "official_test_used": False, + "selection_scope": "frozen_official_validation_subset_256", + "subset_manifest": str(args.subset_manifest.resolve()), + "checkpoint": cache_manifest["checkpoint"], + "selected_conditions": selected, + "rule": ( + "<=1% maximum accuracy degradation; maximize mean relative " + "3D/2D acceleration/jerk reduction; then acceleration error, " + "absolute MPJPE, weaker smoothing" + ), + } + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "jitter_selection.json").write_text( + json.dumps(selection_payload, indent=2) + "\n", encoding="utf-8", + ) + write_csv(args.output_dir / "jitter_condition_metrics.csv", metric_rows) + write_csv(args.output_dir / "jitter_take_metrics.csv", take_rows) + write_csv(args.output_dir / "jitter_filter_fallbacks.csv", fallback_rows) + write_csv(args.output_dir / "jitter_raw_vs_filtered.csv", overview) + if paired_rows: + write_csv( + args.output_dir / "jitter_paired_take_bootstrap_ci.csv", paired_rows, + ) + report = { + "status": "evaluated", + "official_test_used": False, + "result_role": ( + "engineering_smoke" if args.scope == "smoke" + else "filtered_inference_secondary_results" + ), + "raw_model_results_remain_primary": True, + "scope": args.scope, + "fps": FPS, + "cache_manifest": str((args.cache_dir / "cache_manifest.json").resolve()), + "conditions": requested, + "selection": selection_payload, + "outputs": { + "overview": "jitter_raw_vs_filtered.csv", + "metrics": "jitter_condition_metrics.csv", + "take_metrics": "jitter_take_metrics.csv", + "fallbacks": "jitter_filter_fallbacks.csv", + "paired_take_bootstrap_ci": ( + "jitter_paired_take_bootstrap_ci.csv" if paired_rows else None + ), + }, + } + (args.output_dir / "jitter_evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "scope": args.scope, + "conditions": requested, "selection": selection_payload, + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase5_causal_state.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1f9b2876ea7a730a657e4ef9d6b15250842bed --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase5_causal_state.py @@ -0,0 +1,554 @@ +#!/usr/bin/env python3 +"""Evaluate OOF-frozen causal wrist-z state estimators on official validation.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + +import numpy as np + +from foundation_hand.evaluation.causal_state import ( + causal_constant_velocity_kalman, + measurement_uncertainty_multiplier, +) +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.temporal_filter import ( + apply_by_segment, + butterworth_zero_phase, + ema, + valid_segments, +) +try: + from scripts.evaluate_phase4_jitter import ( + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, + ) +except ModuleNotFoundError: # Direct `python scripts/...` execution. + from evaluate_phase4_jitter import ( # type: ignore[no-redef] + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, + ) + + +FPS = 30.0 + + +@dataclass(frozen=True) +class Condition: + name: str + family: str + causal_status: str + latency_frames: float | None + + +CONDITIONS = ( + Condition("coarse", "coarse", "causal", 0.0), + Condition("calibrated_per_frame", "calibrated", "causal", 0.0), + Condition("ema_alpha0.6", "ema", "causal_fixed_lag", (1.0 - 0.6) / 0.6), + Condition("butterworth_2hz", "butterworth", "offline_zero_phase", None), + Condition("fixed_kalman", "fixed_kalman", "causal_state", 0.0), + Condition("uncertainty_kalman", "uncertainty_kalman", "causal_state", 0.0), +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def uncertainty_base(prediction: dict[str, np.ndarray]) -> np.ndarray: + available = prediction["alignment_applied"].astype(bool) + base = measurement_uncertainty_multiplier( + prediction["confidence"], + prediction["inlier_ratio"], + prediction["residual_scale_m"], + prediction["valid_fraction"], + prediction["quality"], + 1.0, + ) + return np.where(available, base, 5.0) + + +def condition_z( + arrays: dict[str, np.ndarray], + prediction: dict[str, np.ndarray], + condition: Condition, + selection: dict[str, object], +) -> tuple[np.ndarray, np.ndarray, int]: + coarse = arrays["pred_wrist_translation"][..., 2].astype(np.float64) + available = prediction["alignment_applied"].astype(bool) + correction = np.where(available, prediction["calibrated_delta_z_m"], 0.0) + measurement = coarse + correction + variance = np.full_like(measurement, np.nan) + if condition.family == "coarse": + return coarse.copy(), variance, 0 + if condition.family == "calibrated": + return measurement, variance, 0 + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + if condition.family == "ema": + filtered, fallback = apply_by_segment( + measurement, segments, lambda values: ema(values, 0.6), minimum_frames=1, + ) + return filtered, variance, fallback + if condition.family == "butterworth": + filtered, fallback = apply_by_segment( + measurement, + segments, + lambda values: butterworth_zero_phase(values, 2.0, FPS, order=2), + minimum_frames=4, + ) + return filtered, variance, fallback + parameters = selection["selected"][condition.family] + multiplier = np.ones_like(measurement) + if condition.family == "uncertainty_kalman": + strength = float(parameters["uncertainty_strength"]) + base = uncertainty_base(prediction) + multiplier = 1.0 + strength * (base - 1.0) + measurement_available = np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), measurement.shape, + ) + filtered, variance = causal_constant_velocity_kalman( + measurement, + frame_id=arrays["frame_id"], + segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], + measurement_available=measurement_available, + process_sigma_m_per_frame2=float(parameters["process_sigma_m_per_frame2"]), + measurement_sigma_m=float(parameters["measurement_sigma_m"]), + uncertainty_multiplier=multiplier, + ) + return filtered, variance, 0 + + +def translated_geometry( + arrays: dict[str, np.ndarray], z_m: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + coarse_z = arrays["pred_wrist_translation"][..., 2] + delta = z_m - coarse_z + translation = arrays["pred_wrist_translation"].astype(np.float64).copy() + joints = arrays["pred_joints_camera"].astype(np.float64).copy() + vertices = arrays["pred_vertices_camera"].astype(np.float64).copy() + translation[..., 2] = z_m + joints[..., 2] += delta[..., None] + vertices[..., 2] += delta[..., None] + return translation, joints, vertices + + +def append_metrics( + destination: dict[str, list[float]], source: dict[str, Iterable[float]], +) -> None: + for metric, values in source.items(): + destination[metric].extend(float(value) for value in values if np.isfinite(value)) + + +def response_diagnostics( + arrays: dict[str, np.ndarray], z_m: np.ndarray, +) -> dict[str, list[float]]: + output: dict[str, list[float]] = defaultdict(list) + target = arrays["target_wrist_translation"][..., 2] + hand_valid = arrays["joint_annotation_valid"].astype(bool) + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + for indices in segments: + for hand in range(2): + selected = indices[hand_valid[indices, hand]] + if len(selected) < 3 or np.any(np.diff(selected) != 1): + continue + pred_velocity = np.diff(z_m[selected, hand]) + target_velocity = np.diff(target[selected, hand]) + step = np.abs(target_velocity) >= 0.005 + if step.any(): + output["step_same_frame_absolute_error_mm"].extend( + (np.abs(pred_velocity[step] - target_velocity[step]) * 1000.0).tolist() + ) + output["step_same_frame_gain"].extend( + (pred_velocity[step] / target_velocity[step]).tolist() + ) + correlations = [] + for lag in range(4): + pred = pred_velocity[lag:] + truth = target_velocity[: len(target_velocity) - lag or None] + if len(pred) < 3 or np.std(pred) < 1e-10 or np.std(truth) < 1e-10: + correlations.append(float("-inf")) + else: + correlations.append(float(np.corrcoef(pred, truth)[0, 1])) + if np.isfinite(correlations).any(): + output["estimated_causal_lag_frames"].append(float(np.argmax(correlations))) + if len(selected) >= 8: + error = np.abs(z_m[selected, hand] - target[selected, hand]) * 1000.0 + output["segment_endpoint_drift_delta_mm"].append(float(error[-1] - error[0])) + output["segment_length_frames"].append(float(len(selected))) + starts = np.concatenate([indices[:1] for indices in segments]) if segments else np.empty(0, dtype=int) + if len(starts): + calibrated = arrays["_calibrated_measurement_z_m"] + output["boundary_reset_difference_mm"].extend( + (np.abs(z_m[starts] - calibrated[starts]) * 1000.0).reshape(-1).tolist() + ) + return output + + +def missing_transition_diagnostics( + arrays: dict[str, np.ndarray], + prediction: dict[str, np.ndarray], + selection: dict[str, object], + family: str, +) -> dict[str, list[float]]: + parameters = selection["selected"][family] + coarse = arrays["pred_wrist_translation"][..., 2].astype(np.float64) + available = prediction["alignment_applied"].astype(bool) + full_measurement = coarse + np.where( + available, prediction["calibrated_delta_z_m"], 0.0, + ) + missing_measurement = full_measurement.copy() + multiplier = np.ones_like(full_measurement) + missing_mask = np.zeros_like(available) + segments = valid_segments( + arrays["clip_index"], arrays["frame_id"], arrays["frame_valid"], + ) + for indices in segments: + if len(indices) >= 6: + missing_mask[indices[3:5]] = True + missing_measurement[missing_mask] = coarse[missing_mask] + if family == "uncertainty_kalman": + strength = float(parameters["uncertainty_strength"]) + base = uncertainty_base(prediction) + base[missing_mask] = 5.0 + multiplier = 1.0 + strength * (base - 1.0) + measurement_available = np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), full_measurement.shape, + ) + filtered, _ = causal_constant_velocity_kalman( + missing_measurement, + frame_id=arrays["frame_id"], segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], measurement_available=measurement_available, + process_sigma_m_per_frame2=float(parameters["process_sigma_m_per_frame2"]), + measurement_sigma_m=float(parameters["measurement_sigma_m"]), + uncertainty_multiplier=multiplier, + ) + target = arrays["target_wrist_translation"][..., 2] + hand_valid = arrays["joint_annotation_valid"].astype(bool) + output: dict[str, list[float]] = defaultdict(list) + selected = missing_mask & hand_valid + output["simulated_missing_span_z_mae_mm"].extend( + (np.abs(filtered - target)[selected] * 1000.0).tolist() + ) + for indices in segments: + if len(indices) < 6: + continue + recovery = indices[5] + valid = hand_valid[recovery] + output["first_recovery_frame_z_mae_mm"].extend( + (np.abs(filtered[recovery] - target[recovery])[valid] * 1000.0).tolist() + ) + return output + + +def paired_bootstrap( + take_rows: list[dict[str, object]], *, samples: int, seed: int = 20260716, +) -> list[dict[str, object]]: + index = { + (str(row["take"]), str(row["condition"]), str(row["metric"]), statistic): + float(row[statistic]) + for row in take_rows + for statistic in ("mean", "p95") + if row.get(statistic) is not None and np.isfinite(float(row[statistic])) + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(CONDITIONS): + if condition.name == "calibrated_per_frame": + continue + for metric_index, metric in enumerate(metrics): + for statistic_index, statistic in enumerate(("mean", "p95")): + pairs = [ + ( + index[(take, condition.name, metric, statistic)], + index[(take, "calibrated_per_frame", metric, statistic)], + ) + for take in takes + if (take, condition.name, metric, statistic) in index + and (take, "calibrated_per_frame", metric, statistic) in index + ] + if not pairs: + continue + delta = np.asarray([filtered - raw for filtered, raw in pairs]) + rng = np.random.default_rng(np.random.SeedSequence( + (seed, condition_index, metric_index, statistic_index), + )) + bootstrap = delta[ + rng.integers(0, len(delta), size=(samples, len(delta))) + ].mean(axis=1) + output.append({ + "reference": "calibrated_per_frame", "condition": condition.name, + "metric": metric, "take_statistic": statistic, "takes": len(delta), + "condition_minus_reference": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def build_overview(metric_rows: list[dict[str, object]]) -> list[dict[str, object]]: + index = { + (str(row["condition"]), str(row["metric"])): row for row in metric_rows + } + fields = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "absolute_mpvpe_mm": ("absolute_mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "z_mae_mm": ("translation_z_mae_mm", "mean"), + "z_p95_mm": ("translation_z_mae_mm", "p95"), + "velocity_error_mm_per_s": ("joint_velocity_error_mm_per_s", "mean"), + "acceleration_error_mm_per_s2": ("joint_acceleration_error_mm_per_s2", "mean"), + "predicted_acceleration_mm_per_s2": ( + "predicted_3d_joint_acceleration_mm_per_s2", "mean", + ), + "predicted_jerk_mm_per_s3": ("predicted_3d_joint_jerk_mm_per_s3", "mean"), + "high_frequency_energy_ratio": ("high_frequency_energy_ratio", "mean"), + "estimated_causal_lag_frames": ("estimated_causal_lag_frames", "mean"), + } + reference = { + name: float(index[("calibrated_per_frame", metric)][statistic]) + for name, (metric, statistic) in fields.items() + } + output = [] + for condition in CONDITIONS: + values = { + name: float(index[(condition.name, metric)][statistic]) + for name, (metric, statistic) in fields.items() + } + row: dict[str, object] = { + "reference": "calibrated_per_frame", "condition": condition.name, + "family": condition.family, "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, + } + for name, value in values.items(): + row[name] = value + row[f"{name}_delta"] = value - reference[name] + row["accuracy_delta"] = row["absolute_mpjpe_mm_delta"] + row["jitter_delta"] = row["predicted_acceleration_mm_per_s2_delta"] + row["velocity_error_delta"] = row["velocity_error_mm_per_s_delta"] + row["acceleration_error_delta"] = row["acceleration_error_mm_per_s2_delta"] + row["static_guardrail_passed"] = bool( + float(row["absolute_mpjpe_mm_delta"]) <= 0.2 + and float(row["z_mae_mm_delta"]) <= 0.2 + and float(row["z_p95_mm_delta"]) <= 0.2 + ) + row["retained_causal_candidate"] = bool( + condition.name == "uncertainty_kalman" + and row["static_guardrail_passed"] + and float(row["jitter_delta"]) < 0.0 + and float(row["velocity_error_delta"]) < 0.0 + and float(row["acceleration_error_delta"]) < 0.0 + ) + output.append(row) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-evaluation-dir", type=Path, required=True) + parser.add_argument("--selection-json", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument( + "--continuous-take-state", + action="store_true", + help="Keep state across model inference windows until a take/frame discontinuity.", + ) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("causal-state output directory must be new or empty") + cache_manifest_path = args.cache_dir / "cache_manifest.json" + alignment_report_path = args.alignment_evaluation_dir / "evaluation.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + alignment_report = json.loads(alignment_report_path.read_text(encoding="utf-8")) + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + or cache.get("frames") != 11638 + or float(cache.get("fps")) != FPS + ): + raise ValueError("invalid complete official-validation cache contract") + if ( + alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + or alignment_report.get("coarse_checkpoint", {}).get("sha256") + != cache.get("checkpoint", {}).get("sha256") + ): + raise ValueError("alignment evaluation does not match the raw cache") + if ( + selection.get("status") != "selected" + or selection.get("official_validation_used") is not False + or selection.get("official_test_used") is not False + or "coarse z is always" not in selection.get("measurement_contract", "") + ): + raise ValueError("causal-state parameters are not valid train-OOF selections") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + global_values = {condition.name: defaultdict(list) for condition in CONDITIONS} + take_rows = [] + response_rows = [] + missing_values = { + family: defaultdict(list) for family in ("fixed_kalman", "uncertainty_kalman") + } + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw-cache take hash mismatch: {take_path}") + arrays = load_npz(take_path) + if args.continuous_take_state: + arrays["clip_index"] = np.zeros_like(arrays["clip_index"]) + stem = "__".join(Path(str(arrays["take"])).parts) + prediction_path = args.alignment_evaluation_dir / "predictions" / f"{stem}.npz" + prediction = load_npz(prediction_path) + if not np.array_equal(arrays["frame_id"], prediction["frame_id"]): + raise ValueError(f"alignment frame mismatch: {arrays['take']}") + calibrated_measurement = arrays["pred_wrist_translation"][..., 2] + np.where( + prediction["alignment_applied"], prediction["calibrated_delta_z_m"], 0.0, + ) + arrays["_calibrated_measurement_z_m"] = calibrated_measurement + saved: dict[str, np.ndarray] = {"frame_id": arrays["frame_id"]} + for condition in CONDITIONS: + z_m, variance, fallbacks = condition_z(arrays, prediction, condition, selection) + translation, joints, vertices = translated_geometry(arrays, z_m) + selected = arrays["frame_valid"].astype(bool) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, arrays["pred_rotation_matrices"], translation, selected, + ) + append_metrics(metrics, temporal_metrics(arrays, joints, projected, selected)) + append_metrics(metrics, identity_switch_metrics(arrays, joints, selected)) + response = response_diagnostics(arrays, z_m) + append_metrics(metrics, response) + for metric, observations in metrics.items(): + global_values[condition.name][metric].extend(observations) + take_rows.append({ + "take": str(arrays["take"]), "condition": condition.name, + "family": condition.family, "metric": metric, + **distribution_summary(observations), + }) + for metric, observations in response.items(): + response_rows.append({ + "take": str(arrays["take"]), "condition": condition.name, + "metric": metric, **distribution_summary(observations), + }) + saved[f"{condition.name}_z_m"] = z_m + saved[f"{condition.name}_variance_m2"] = variance + saved[f"{condition.name}_fallback_segments"] = np.asarray(fallbacks) + for family in missing_values: + append_metrics( + missing_values[family], + missing_transition_diagnostics(arrays, prediction, selection, family), + ) + np.savez_compressed(prediction_root / f"{stem}.npz", **saved) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + metric_rows = [] + for condition in CONDITIONS: + for metric, observations in sorted(global_values[condition.name].items()): + metric_rows.append({ + "condition": condition.name, "family": condition.family, + "causal_status": condition.causal_status, + "latency_frames": condition.latency_frames, "metric": metric, + **distribution_summary(observations), + }) + missing_rows = [ + {"condition": family, "metric": metric, **distribution_summary(observations)} + for family, values in missing_values.items() + for metric, observations in sorted(values.items()) + ] + bootstrap_rows = paired_bootstrap( + take_rows, samples=args.bootstrap_samples, + ) + overview_rows = build_overview(metric_rows) + write_csv(args.output_dir / "metrics.csv", metric_rows) + write_csv(args.output_dir / "overview.csv", overview_rows) + write_csv(args.output_dir / "take_metrics.csv", take_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap_rows) + write_csv(args.output_dir / "response_diagnostics.csv", response_rows) + write_csv(args.output_dir / "missing_modality_transition.csv", missing_rows) + report = { + "status": "evaluated", + "experiment_class": "preregistered_confirmatory_causal_state", + "result_role": "deployable_causal_translation_z_state_ablation", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "alignment_evaluation": {"path": str(alignment_report_path.resolve()), "sha256": sha256(alignment_report_path)}, + "selection": {"path": str(args.selection_json.resolve()), "sha256": sha256(args.selection_json)}, + "checkpoint": cache["checkpoint"], + "conditions": [condition.__dict__ for condition in CONDITIONS], + "state_scope": "translation z only; pose/shape and translation x/y unchanged", + "measurement_contract": selection["measurement_contract"], + "boundary_contract": ( + "reset at invalid frame, frame discontinuity, and take boundary" + if args.continuous_take_state else + "reset at invalid frame, frame discontinuity, and frozen model clip boundary; never cross take" + ), + "continuous_take_state": args.continuous_take_state, + "long_sequence_limitation": ( + None if args.continuous_take_state else + "the inherited no-cross-clip rule limits a continuous state segment to the cache clip length" + ), + "missing_modality_diagnostic": "simulated local-alignment loss uses exact coarse-z fallback with high uncertainty; the unified coarse model's missing Depth/K static fallback was audited in Stage 3", + "outputs": { + "metrics": "metrics.csv", "take_metrics": "take_metrics.csv", + "overview": "overview.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "response": "response_diagnostics.csv", + "missing_transition": "missing_modality_transition.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "evaluated", "frames": cache["frames"], + "conditions": [condition.name for condition in CONDITIONS], + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase5_metric_alignment.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase5_metric_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..a1f686d340bef0e1a05bb1555d8d89dcd10f1938 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase5_metric_alignment.py @@ -0,0 +1,564 @@ +#!/usr/bin/env python3 +"""Evaluate deployable predicted-location wrist-z alignment on frozen raw caches.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import cv2 +import joblib +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.alignment_calibration import ( + FEATURE_NAMES, + features_from_take, + projected_hand_scale_px, +) +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + + +FINGERTIPS = (4, 8, 12, 16, 20) +CALIBRATED_CONDITIONS = ( + "coarse", + "robust_alignment_unscaled", + "calibrated_always", + "calibrated_confidence", + "missing_depth_fallback", + "missing_k_fallback", +) +RAW_CONDITIONS = ("coarse", "robust_alignment_unscaled") +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report: {path}") + path.parent.mkdir(parents=True, exist_ok=True) + first_fields = list(rows[0]) + extra_fields = sorted({key for row in rows for key in row} - set(first_fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=first_fields + extra_fields, lineterminator="\n", + ) + writer.writeheader() + writer.writerows(rows) + + +def _velocity(translation: np.ndarray, frame_ids: np.ndarray) -> np.ndarray: + output = np.zeros_like(translation, dtype=np.float32) + contiguous = frame_ids[1:] == frame_ids[:-1] + 1 + output[1:][contiguous] = translation[1:][contiguous] - translation[:-1][contiguous] + return output + + +def alignment_arrays( + arrays: dict[str, np.ndarray], data_root: Path, +) -> dict[str, np.ndarray]: + take = str(arrays["take"]) + take_dir = data_root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + time = len(arrays["frame_id"]) + diagnostics: dict[str, list[np.ndarray]] = defaultdict(list) + overlap = [] + predicted_depth_order = [] + for time_index, frame_id in enumerate(arrays["frame_id"]): + depth_mm = cv2.imread( + str(take_dir / "depth" / f"{int(frame_id):06d}.png"), cv2.IMREAD_UNCHANGED, + ) + if depth_mm is None or depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{int(frame_id):06d}") + depth_m, depth_valid = depth_mm_to_m(depth_mm) + masks = [] + predicted_surface_medians = [] + for hand in range(2): + result, samples = align_wrist_z( + arrays["pred_vertices_camera"][time_index, hand], + K_raw, depth_m, depth_valid, + ) + if samples is None: + raise AssertionError("complete-modality evaluation has no depth samples") + for field, value in result.as_dict().items(): + diagnostics[f"alignment_{field}"].append(np.asarray(value)) + masks.append(np.unpackbits( + samples.silhouette_packed, bitorder="little", + count=samples.silhouette_hw[0] * samples.silhouette_hw[1], + ).astype(bool)) + predicted_surface_medians.append(float(np.median( + samples.predicted_depth_m[samples.visible_vertex], + ))) + intersection = np.logical_and(masks[0], masks[1]).sum() + union = np.logical_or(masks[0], masks[1]).sum() + overlap.append(intersection / max(union, 1)) + predicted_depth_order.append(np.sign( + predicted_surface_medians[1] - predicted_surface_medians[0] + )) + values = { + key: np.stack(items).reshape(time, 2) + for key, items in diagnostics.items() + } + pred_joints_raw, _ = project_points(arrays["pred_joints_camera"], K_raw) + resized_hw = arrays["K"].shape # Cache K is already aligned to model image. + del resized_hw + # Recover resized dimensions from principal-point scaling used by the 640x368 cache. + width, height = 640.0, 368.0 + raw_to_resized = np.asarray((width / raw_hw[1], height / raw_hw[0]), dtype=np.float32) + mano_resized = pred_joints_raw * raw_to_resized + values.update({ + "frame_id": arrays["frame_id"], + "pred_wrist_translation": arrays["pred_wrist_translation"], + "coarse_hand_scale_px": projected_hand_scale_px( + pred_joints_raw, source_hw=raw_hw, target_hw=(int(height), int(width)), + ), + "coarse_direct_mano_consistency_px": np.linalg.norm( + arrays["pred_direct_2d_px"] - mano_resized, axis=-1, + ).mean(axis=-1), + "silhouette_overlap_fraction": np.asarray(overlap, dtype=np.float32), + "predicted_depth_order": np.asarray(predicted_depth_order, dtype=np.int8), + "coarse_wrist_velocity_m_per_frame": _velocity( + arrays["pred_wrist_translation"], arrays["frame_id"], + ), + }) + return values + + +def correction_grid( + geometry: dict[str, np.ndarray], package: dict[str, object], +) -> tuple[dict[str, np.ndarray], np.ndarray, np.ndarray]: + features = features_from_take(geometry) + flat = features.reshape(-1, features.shape[-1]) + calibrated = np.clip(package["regressor"].predict(flat), -0.12, 0.12).reshape(features.shape[:2]) + confidence = package["confidence"].predict_proba(flat)[:, 1].reshape(features.shape[:2]) + available = geometry["alignment_applied"].astype(bool) + threshold = float(package["confidence_threshold"]) + raw = np.where(available, geometry["alignment_delta_z_m"], 0.0) + calibrated_available = np.where(available, calibrated, 0.0) + gated = np.where(available & (confidence >= threshold), calibrated, 0.0) + zero = np.zeros_like(raw) + return { + "coarse": zero, + "robust_alignment_unscaled": raw, + "calibrated_always": calibrated_available, + "calibrated_confidence": gated, + "missing_depth_fallback": zero, + "missing_k_fallback": zero, + }, calibrated, confidence + + +def hand_size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def take_rows( + arrays: dict[str, np.ndarray], + geometry: dict[str, np.ndarray], + corrections: dict[str, np.ndarray], + calibrated: np.ndarray, + confidence: np.ndarray, +) -> tuple[list[dict[str, object]], list[dict[str, object]]]: + frame_rows = [] + temporal_rows = [] + take = str(arrays["take"]) + for condition, correction in corrections.items(): + joints = arrays["pred_joints_camera"].astype(np.float64).copy() + vertices = arrays["pred_vertices_camera"].astype(np.float64).copy() + translation = arrays["pred_wrist_translation"].astype(np.float64).copy() + joints[..., 2] += correction[..., None] + vertices[..., 2] += correction[..., None] + translation[..., 2] += correction + projected, _ = project_points(joints, arrays["K"]) + frame_valid = arrays["frame_valid"].astype(bool) + valid = arrays["mano_annotation_valid"].astype(bool) & frame_valid[:, None] + for time_index, hand in zip(*np.where(valid), strict=True): + target_joints = arrays["target_joints_camera"][time_index, hand] + target_vertices = arrays["target_vertices_camera"][time_index, hand] + pred_joints = joints[time_index, hand] + pred_vertices = vertices[time_index, hand] + joint_error = np.linalg.norm(pred_joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(pred_vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (pred_joints - pred_joints[:1]) - (target_joints - target_joints[:1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (pred_vertices - pred_joints[:1]) - (target_vertices - target_joints[:1]), axis=-1, + ) * 1000.0 + z_signed = 1000.0 * ( + translation[time_index, hand, 2] + - arrays["target_wrist_translation"][time_index, hand, 2] + ) + translation_signed = 1000.0 * ( + translation[time_index, hand] + - arrays["target_wrist_translation"][time_index, hand] + ) + target_2d = arrays["target_2d_px"][time_index, hand] + direct_2d = arrays["pred_direct_2d_px"][time_index, hand] + scale = float(geometry["coarse_hand_scale_px"][time_index, hand]) + target_depth = float(arrays["target_wrist_translation"][time_index, hand, 2]) + frame_rows.append({ + "condition": condition, + "take": take, + "subject": take.split("/")[0], + "action_family": take.split("/")[1], + "frame_id": int(arrays["frame_id"][time_index]), + "side": "right" if hand else "left", + "hand_size_bucket": hand_size_bucket(scale), + "depth_bucket": depth_bucket(target_depth), + "absolute_mpjpe_mm": float(joint_error.mean()), + "root_relative_mpjpe_mm": float(root_joint_error.mean()), + "absolute_mpvpe_mm": float(vertex_error.mean()), + "root_relative_mpvpe_mm": float(root_vertex_error.mean()), + "fingertip_mpjpe_mm": float(joint_error[list(FINGERTIPS)].mean()), + "translation_x_mae_mm": abs(float(translation_signed[0])), + "translation_y_mae_mm": abs(float(translation_signed[1])), + "translation_z_mae_mm": abs(float(z_signed)), + "translation_x_signed_error_mm": float(translation_signed[0]), + "translation_y_signed_error_mm": float(translation_signed[1]), + "translation_z_signed_error_mm": float(z_signed), + "direct_2d_error_px": float(np.linalg.norm(direct_2d - target_2d, axis=-1).mean()), + "mano_projected_2d_error_px": float(np.linalg.norm(projected[time_index, hand] - target_2d, axis=-1).mean()), + "direct_mano_2d_consistency_px": float( + np.linalg.norm(direct_2d - projected[time_index, hand], axis=-1).mean() + ), + "raw_alignment_delta_z_mm": 1000.0 * float(geometry["alignment_delta_z_m"][time_index, hand]), + "calibrated_delta_z_mm": 1000.0 * float(calibrated[time_index, hand]), + "applied_delta_z_mm": 1000.0 * float(correction[time_index, hand]), + "alignment_confidence": float(confidence[time_index, hand]), + "alignment_support": int(geometry["alignment_valid_support_count"][time_index, hand]), + "alignment_quality": float(geometry["alignment_conditioning_quality"][time_index, hand]), + }) + + contiguous = arrays["frame_id"][1:] == arrays["frame_id"][:-1] + 1 + for hand in range(2): + transition_valid = contiguous & valid[1:, hand] & valid[:-1, hand] + indices = np.where(transition_valid)[0] + pred_velocity = joints[1:, hand] - joints[:-1, hand] + target_velocity = arrays["target_joints_camera"][1:, hand] - arrays["target_joints_camera"][:-1, hand] + for index in indices: + temporal_rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][index + 1]), + "side": "right" if hand else "left", + "joint_velocity_error_mm_per_frame": float( + np.linalg.norm(pred_velocity[index] - target_velocity[index], axis=-1).mean() * 1000.0 + ), + }) + acceleration_valid = transition_valid[1:] & transition_valid[:-1] + acceleration_indices = np.where(acceleration_valid)[0] + pred_acceleration = pred_velocity[1:] - pred_velocity[:-1] + target_acceleration = target_velocity[1:] - target_velocity[:-1] + for index in acceleration_indices: + temporal_rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][index + 2]), + "side": "right" if hand else "left", + "joint_acceleration_error_mm_per_frame2": float( + np.linalg.norm(pred_acceleration[index] - target_acceleration[index], axis=-1).mean() * 1000.0 + ), + "predicted_joint_acceleration_mm_per_frame2": float( + np.linalg.norm(pred_acceleration[index], axis=-1).mean() * 1000.0 + ), + }) + both_valid = valid.all(axis=1) + wrong_side: list[bool | None] = [] + for time_index in range(len(valid)): + if not both_valid[time_index]: + wrong_side.append(None) + continue + correct = 0.5 * ( + np.linalg.norm( + joints[time_index, 0] - arrays["target_joints_camera"][time_index, 0], + axis=-1, + ).mean() + + np.linalg.norm( + joints[time_index, 1] - arrays["target_joints_camera"][time_index, 1], + axis=-1, + ).mean() + ) + swapped = 0.5 * ( + np.linalg.norm( + joints[time_index, 0] - arrays["target_joints_camera"][time_index, 1], + axis=-1, + ).mean() + + np.linalg.norm( + joints[time_index, 1] - arrays["target_joints_camera"][time_index, 0], + axis=-1, + ).mean() + ) + wrong_side.append(bool(swapped < correct)) + for index, (previous, current) in enumerate( + zip(wrong_side[:-1], wrong_side[1:], strict=True) + ): + if contiguous[index] and previous is not None and current is not None: + temporal_rows.append({ + "condition": condition, + "take": take, + "frame_id": int(arrays["frame_id"][index + 1]), + "side": "bimanual", + "identity_switch_fraction": float(previous != current), + }) + return frame_rows, temporal_rows + + +def aggregate_rows( + frame_rows: list[dict[str, object]], + temporal_rows: list[dict[str, object]], + conditions: tuple[str, ...] = CALIBRATED_CONDITIONS, +) -> list[dict[str, object]]: + output = [] + for condition in conditions: + selected = [row for row in frame_rows if row["condition"] == condition] + for metric in METRICS: + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row[metric] for row in selected), + }) + temporal_selected = [row for row in temporal_rows if row["condition"] == condition] + for metric in ( + "joint_velocity_error_mm_per_frame", + "joint_acceleration_error_mm_per_frame2", + "predicted_joint_acceleration_mm_per_frame2", + "identity_switch_fraction", + ): + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row.get(metric) for row in temporal_selected), + }) + for group in ("side", "hand_size_bucket", "depth_bucket", "take", "action_family"): + values = sorted({str(row[group]) for row in selected}) + for value in values: + grouped = [row for row in selected if str(row[group]) == value] + for metric in METRICS: + output.append({ + "condition": condition, "group": group, "value": value, "metric": metric, + **distribution_summary(row[metric] for row in grouped), + }) + return output + + +def paired_take_bootstrap( + frame_rows: list[dict[str, object]], + *, + conditions: tuple[str, ...] = CALIBRATED_CONDITIONS, + samples: int = 10_000, + seed: int = 20260716, +) -> list[dict[str, object]]: + take_means: dict[tuple[str, str, str], float] = {} + takes = sorted({str(row["take"]) for row in frame_rows}) + for condition in conditions: + for take in takes: + rows = [row for row in frame_rows if row["condition"] == condition and row["take"] == take] + for metric in METRICS: + take_means[(condition, take, metric)] = float(np.mean([float(row[metric]) for row in rows])) + output = [] + rng = np.random.default_rng(seed) + for condition in conditions[1:]: + for metric in METRICS: + delta = np.asarray([ + take_means[(condition, take, metric)] - take_means[("coarse", take, metric)] + for take in takes + ]) + indices = rng.integers(0, len(delta), size=(samples, len(delta))) + boot = delta[indices].mean(axis=1) + output.append({ + "condition": condition, "metric": metric, "takes": len(takes), + "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--calibrator", type=Path) + parser.add_argument("--calibration-json", type=Path) + parser.add_argument("--raw-only", action="store_true") + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("metric-alignment output directory must be new or empty") + cache = json.loads((args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + ): + raise ValueError("official-validation cache contract is invalid") + if args.raw_only: + if args.calibrator is not None or args.calibration_json is not None: + parser.error("--raw-only cannot accept calibrator inputs") + calibration = None + package = None + conditions = RAW_CONDITIONS + else: + if args.calibrator is None or args.calibration_json is None: + parser.error("calibrated evaluation requires --calibrator and --calibration-json") + calibration = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration.get("status") != "fitted" + or calibration.get("official_validation_used") is not False + or calibration.get("official_test_used") is not False + or calibration.get("model", {}).get("sha256") != sha256(args.calibrator) + ): + raise ValueError("OOF calibration contract is invalid") + package = joblib.load(args.calibrator) + if tuple(package["feature_names"]) != FEATURE_NAMES: + raise ValueError("calibrator feature schema mismatch") + conditions = CALIBRATED_CONDITIONS + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + all_frame_rows = [] + all_temporal_rows = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw-cache take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + geometry = alignment_arrays(arrays, args.data_root) + if args.raw_only: + zero = np.zeros_like(geometry["alignment_delta_z_m"]) + available = geometry["alignment_applied"].astype(bool) + corrections = { + "coarse": zero, + "robust_alignment_unscaled": np.where( + available, geometry["alignment_delta_z_m"], 0.0, + ), + } + calibrated, confidence = zero, zero + else: + corrections, calibrated, confidence = correction_grid(geometry, package) + frame_rows, temporal_rows = take_rows( + arrays, geometry, corrections, calibrated, confidence, + ) + all_frame_rows.extend(frame_rows) + all_temporal_rows.extend(temporal_rows) + np.savez_compressed( + prediction_root / f"{'__'.join(Path(str(arrays['take'])).parts)}.npz", + frame_id=arrays["frame_id"], + raw_alignment_delta_z_m=geometry["alignment_delta_z_m"], + calibrated_delta_z_m=calibrated, + confidence=confidence, + gated_delta_z_m=( + zero if args.raw_only else corrections["calibrated_confidence"] + ), + support=geometry["alignment_valid_support_count"], + projected_support=geometry["alignment_projected_support_count"], + quality=geometry["alignment_conditioning_quality"], + alignment_applied=geometry["alignment_applied"], + inlier_ratio=geometry["alignment_inlier_ratio"], + residual_scale_m=geometry["alignment_residual_scale_m"], + valid_fraction=geometry["alignment_valid_fraction"], + foreground_fraction=geometry["alignment_foreground_fraction"], + background_fraction=geometry["alignment_background_fraction"], + depth_discontinuity_m=geometry["alignment_depth_discontinuity_m"], + silhouette_overlap_fraction=geometry["silhouette_overlap_fraction"], + coarse_hand_scale_px=geometry["coarse_hand_scale_px"], + coarse_direct_mano_consistency_px=geometry[ + "coarse_direct_mano_consistency_px" + ], + coarse_wrist_velocity_m_per_frame=geometry[ + "coarse_wrist_velocity_m_per_frame" + ], + predicted_depth_order=geometry["predicted_depth_order"], + ) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + aggregate = aggregate_rows(all_frame_rows, all_temporal_rows, conditions) + paired = paired_take_bootstrap(all_frame_rows, conditions=conditions) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_frame_rows) + write_csv(args.output_dir / "per_temporal_metrics.csv", all_temporal_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + missing_fallback_exact = None if args.raw_only else all( + next(row for row in aggregate if row["condition"] == condition and row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm")["mean"] + == next(row for row in aggregate if row["condition"] == "coarse" and row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm")["mean"] + for condition in ("missing_depth_fallback", "missing_k_fallback") + ) + report = { + "status": "evaluated", + "experiment_class": "ablation" if args.raw_only else "deployable_ablation", + "result_role": ( + "fixed_raw_predicted_location_alignment_without_learned_confidence" + if args.raw_only else "deployable_predicted_location_metric_alignment" + ), + "official_validation_used": True, + "official_validation_used_for_model_or_threshold_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str((args.cache_dir / "cache_manifest.json").resolve()), "sha256": sha256(args.cache_dir / "cache_manifest.json")}, + "coarse_checkpoint": cache["checkpoint"], + "calibration": ( + None if args.raw_only else + {"path": str(args.calibration_json.resolve()), "sha256": sha256(args.calibration_json)} + ), + "calibrator": ( + None if args.raw_only else + {"path": str(args.calibrator.resolve()), "sha256": sha256(args.calibrator)} + ), + "conditions": list(conditions), + "confidence_threshold": None if args.raw_only else float(package["confidence_threshold"]), + "location": "coarse predicted MANO projection; no GT location/bbox/crop", + "correction": "translation z only; pose/shape and coarse outputs retained", + "solver": { + "loss": "MAD-scaled Huber IRLS", + "minimum_support": 20, + "maximum_raw_residual_m": 0.15, + "maximum_delta_m": 0.12, + "surface_location": "frontmost predicted MANO vertices at coarse projection", + }, + "missing_depth_k_fallback_exact": missing_fallback_exact, + "missing_rgb_status": "not_supported_by_frozen_coarse_cache; no claim", + "added_temporal_latency_frames": 0, + "outputs": { + "per_hand": "per_hand_frame_metrics.csv", + "per_temporal": "per_temporal_metrics.csv", + "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "frames": cache["frames"], + "missing_fallback_exact": missing_fallback_exact, "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase5_missing_modality.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase5_missing_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..4b0ac6c2f8b9d554603ecc696a9392e1f97bb9bf --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase5_missing_modality.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Evaluate true missing-Depth/K coarse-model caches against complete input.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import project_points +try: + from scripts.evaluate_phase4_jitter import identity_switch_metrics, temporal_metrics +except ModuleNotFoundError: # Direct `python scripts/...` execution. + from evaluate_phase4_jitter import identity_switch_metrics, temporal_metrics # type: ignore[no-redef] + + +CONDITIONS = ("complete", "missing_depth", "missing_k") +FINGERTIPS = (4, 8, 12, 16, 20) +STATIC_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "translation_x_signed_error_mm", "translation_y_signed_error_mm", + "translation_z_signed_error_mm", "direct_2d_error_px", + "mano_projected_2d_error_px", "direct_mano_2d_consistency_px", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def frame_rows(arrays: dict[str, np.ndarray], condition: str) -> list[dict[str, Any]]: + rows = [] + take = str(arrays["take"]) + projected, _ = project_points(arrays["pred_joints_camera"], arrays["K"][:, None]) + valid = arrays["frame_valid"].astype(bool)[:, None] & arrays["mano_annotation_valid"].astype(bool) + for time_index, hand in zip(*np.where(valid), strict=True): + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + vertices = arrays["pred_vertices_camera"][time_index, hand].astype(np.float64) + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_vertices = arrays["target_vertices_camera"][time_index, hand].astype(np.float64) + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (joints - joints[:1]) - (target_joints - target_joints[:1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (vertices - joints[:1]) - (target_vertices - target_joints[:1]), axis=-1, + ) * 1000.0 + translation_signed = 1000.0 * ( + arrays["pred_wrist_translation"][time_index, hand] + - arrays["target_wrist_translation"][time_index, hand] + ) + direct = arrays["pred_direct_2d_px"][time_index, hand] + target_2d = arrays["target_2d_px"][time_index, hand] + target_scale = float(np.max(np.ptp(target_2d, axis=0))) + rows.append({ + "condition": condition, "take": take, + "frame_id": int(arrays["frame_id"][time_index]), + "side": "right" if hand else "left", + "hand_size_bucket": size_bucket(target_scale), + "wrist_depth_bucket": depth_bucket(float(arrays["target_wrist_translation"][time_index, hand, 2])), + "absolute_mpjpe_mm": float(joint_error.mean()), + "root_relative_mpjpe_mm": float(root_joint_error.mean()), + "absolute_mpvpe_mm": float(vertex_error.mean()), + "root_relative_mpvpe_mm": float(root_vertex_error.mean()), + "fingertip_mpjpe_mm": float(joint_error[list(FINGERTIPS)].mean()), + "translation_x_mae_mm": abs(float(translation_signed[0])), + "translation_y_mae_mm": abs(float(translation_signed[1])), + "translation_z_mae_mm": abs(float(translation_signed[2])), + "translation_x_signed_error_mm": float(translation_signed[0]), + "translation_y_signed_error_mm": float(translation_signed[1]), + "translation_z_signed_error_mm": float(translation_signed[2]), + "direct_2d_error_px": float(np.linalg.norm(direct - target_2d, axis=-1).mean()), + "mano_projected_2d_error_px": float( + np.linalg.norm(projected[time_index, hand] - target_2d, axis=-1).mean() + ), + "direct_mano_2d_consistency_px": float( + np.linalg.norm(direct - projected[time_index, hand], axis=-1).mean() + ), + }) + return rows + + +def matched_cache_arrays( + reference: dict[str, np.ndarray], candidate: dict[str, np.ndarray], +) -> bool: + keys = ( + "frame_id", "frame_valid", "K", "target_rotation_matrices", "target_shape", + "target_wrist_translation", "target_joints_camera", "target_vertices_camera", + "target_2d_px", "joint_annotation_valid", "joint_element_valid", + "mano_annotation_valid", + ) + return all(np.array_equal(reference[key], candidate[key], equal_nan=True) for key in keys) + + +def aggregate_static(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + output = [] + group_fields: dict[str, str | None] = { + "all": None, "side": "side", "hand_size": "hand_size_bucket", + "wrist_depth": "wrist_depth_bucket", + } + for condition in CONDITIONS: + condition_rows = [row for row in rows if row["condition"] == condition] + for group, field in group_fields.items(): + values = ["all"] if field is None else sorted({str(row[field]) for row in condition_rows}) + for value in values: + selected = condition_rows if field is None else [ + row for row in condition_rows if str(row[field]) == value + ] + for metric in STATIC_METRICS: + output.append({ + "condition": condition, "group": group, "value": value, + "metric": metric, + **distribution_summary([float(row[metric]) for row in selected]), + }) + return output + + +def take_metric_rows( + static_rows: list[dict[str, Any]], dynamic: dict[tuple[str, str], dict[str, list[float]]], +) -> list[dict[str, Any]]: + output = [] + takes = sorted({str(row["take"]) for row in static_rows}) + for condition in CONDITIONS: + for take in takes: + selected = [ + row for row in static_rows + if row["condition"] == condition and row["take"] == take + ] + for metric in STATIC_METRICS: + output.append({ + "condition": condition, "take": take, "metric": metric, + **distribution_summary([float(row[metric]) for row in selected]), + }) + for metric, observations in sorted(dynamic[(condition, take)].items()): + output.append({ + "condition": condition, "take": take, "metric": metric, + **distribution_summary(observations), + }) + return output + + +def paired_take_bootstrap( + take_rows: list[dict[str, Any]], samples: int = 10_000, seed: int = 20260716, +) -> list[dict[str, Any]]: + index = { + (row["condition"], row["take"], row["metric"]): float(row["mean"]) + for row in take_rows + } + takes = sorted({str(row["take"]) for row in take_rows}) + metrics = sorted({str(row["metric"]) for row in take_rows}) + output = [] + for condition_index, condition in enumerate(CONDITIONS[1:]): + for metric_index, metric in enumerate(metrics): + pairs = [ + (index[(condition, take, metric)], index[("complete", take, metric)]) + for take in takes + if (condition, take, metric) in index and ("complete", take, metric) in index + ] + if not pairs: + continue + delta = np.asarray([missing - complete for missing, complete in pairs]) + rng = np.random.default_rng(np.random.SeedSequence((seed, condition_index, metric_index))) + bootstrap = delta[rng.integers(0, len(delta), size=(samples, len(delta)))].mean(axis=1) + output.append({ + "reference": "complete", "condition": condition, "metric": metric, + "takes": len(delta), "condition_minus_reference": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + }) + return output + + +def load_manifest( + path: Path, expected_condition: str, expected_scope: str = "full", +) -> dict[str, Any]: + manifest = json.loads(path.read_text(encoding="utf-8")) + condition = manifest.get("input_condition", "complete") + if ( + manifest.get("status") != "complete" or manifest.get("scope") != expected_scope + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + or condition != expected_condition + ): + raise ValueError(f"invalid {expected_condition} cache manifest") + if expected_scope == "full" and ( + manifest.get("frames") != 11638 or manifest.get("clips") != 1495 + ): + raise ValueError(f"invalid {expected_condition} full-cache coverage") + return manifest + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--complete-cache", type=Path, required=True) + parser.add_argument("--missing-depth-cache", type=Path, required=True) + parser.add_argument("--missing-k-cache", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--scope", choices=("full", "smoke"), default="full") + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("missing-modality evaluation output must be new or empty") + cache_dirs = { + "complete": args.complete_cache, + "missing_depth": args.missing_depth_cache, + "missing_k": args.missing_k_cache, + } + manifests = { + condition: load_manifest(path / "cache_manifest.json", condition, args.scope) + for condition, path in cache_dirs.items() + } + coverage = {(manifest["clips"], manifest["frames"]) for manifest in manifests.values()} + if len(coverage) != 1: + raise ValueError("missing-modality cache coverage differs") + checkpoint_hashes = {manifest["checkpoint"]["sha256"] for manifest in manifests.values()} + manifest_hashes = {manifest["manifest"]["sha256"] for manifest in manifests.values()} + if len(checkpoint_hashes) != 1 or len(manifest_hashes) != 1: + raise ValueError("missing-modality caches do not share checkpoint/split") + takes_by_condition = { + condition: {record["take"]: record for record in manifest["takes"]} + for condition, manifest in manifests.items() + } + if any(set(records) != set(takes_by_condition["complete"]) for records in takes_by_condition.values()): + raise ValueError("missing-modality cache take grids differ") + static_rows: list[dict[str, Any]] = [] + dynamic: dict[tuple[str, str], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for take in sorted(takes_by_condition["complete"]): + arrays_by_condition = {} + for condition in CONDITIONS: + record = takes_by_condition[condition][take] + path = Path(record["path"]) + if sha256(path) != record["sha256"]: + raise ValueError(f"cache take hash mismatch: {path}") + arrays_by_condition[condition] = load_npz(path) + reference = arrays_by_condition["complete"] + for condition, arrays in arrays_by_condition.items(): + if condition != "complete" and not matched_cache_arrays(reference, arrays): + raise ValueError(f"cache frame/GT mismatch: {take}/{condition}") + static_rows.extend(frame_rows(arrays, condition)) + selected = arrays["frame_valid"].astype(bool) + temporal = temporal_metrics( + arrays, arrays["pred_joints_camera"], arrays["pred_direct_2d_px"], selected, + ) + identity = identity_switch_metrics(arrays, arrays["pred_joints_camera"], selected) + for metric, observations in {**temporal, **identity}.items(): + dynamic[(condition, take)][metric].extend( + float(value) for value in observations if np.isfinite(value) + ) + + group_rows = aggregate_static(static_rows) + take_rows = take_metric_rows(static_rows, dynamic) + bootstrap = paired_take_bootstrap(take_rows, samples=args.bootstrap_samples) + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", static_rows) + write_csv(args.output_dir / "group_metrics.csv", group_rows) + write_csv(args.output_dir / "take_metrics.csv", take_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap) + overview_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", "direct_2d_error_px", + "mano_projected_2d_error_px", + ) + overview = { + condition: { + metric: next( + row for row in group_rows + if row["condition"] == condition and row["group"] == "all" and row["metric"] == metric + ) + for metric in overview_metrics + } + for condition in CONDITIONS + } + report = { + "status": "evaluated", + "experiment_class": "preregistered_missing_modality_fallback_diagnostic", + "result_role": "true_coarse_model_input_ablation", + "reference": "complete", + "conditions": list(CONDITIONS), + "scope": args.scope, + "checkpoint_sha256": next(iter(checkpoint_hashes)), + "cache_manifests": { + condition: {"path": str((path / "cache_manifest.json").resolve()), "sha256": sha256(path / "cache_manifest.json")} + for condition, path in cache_dirs.items() + }, + "overview": overview, + "missing_rgb_status": "unsupported_no_rgb_availability_or_training_dropout", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "conditions": report["conditions"], + "frames": manifests["complete"]["frames"], "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_harm_risk.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..42c2af30c8069268484c386d654a282509505b07 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_harm_risk.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +"""Run the single frozen validation comparison for the OOF harm-risk gate.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path + +import joblib +import numpy as np + +from foundation_hand.evaluation.harm_risk import ( + HARM_RISK_FEATURE_NAMES, + harm_risk_features, +) +from scripts.evaluate_phase6_mixed_projection import ( + METRICS, + aggregate_rows, + sha256, + take_rows, + write_csv, +) + + +ALWAYS = "coarse_wrist_ray__z_calibrated_always" +RISK = "coarse_wrist_ray__z_harm_risk" +SPECS = [ + {"id": "direct_xyz_coarse__z_coarse", "assembly": "direct_xyz_coarse", "z_mode": "coarse"}, + {"id": "direct_xyz_z_only__z_calibrated_always", "assembly": "direct_xyz_z_only", "z_mode": "calibrated_always"}, + {"id": ALWAYS, "assembly": "coarse_wrist_ray", "z_mode": "calibrated_always"}, + {"id": RISK, "assembly": "coarse_wrist_ray", "z_mode": "calibrated_confidence_0p6"}, +] + + +def paired_take_bootstrap( + rows: list[dict[str, object]], *, samples: int = 10_000, seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + output = [] + rng = np.random.default_rng(seed) + for metric in METRICS: + delta = [] + for take in takes: + candidate = [ + float(row[metric]) for row in rows + if row["condition"] == RISK and row["take"] == take + ] + reference = [ + float(row[metric]) for row in rows + if row["condition"] == ALWAYS and row["take"] == take + ] + delta.append(float(np.mean(candidate) - np.mean(reference))) + values = np.asarray(delta) + indices = rng.integers(0, len(values), size=(samples, len(values))) + boot = values[indices].mean(axis=1) + output.append({ + "condition": RISK, "reference": ALWAYS, "metric": metric, + "takes": len(takes), "delta_mean": float(values.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-dir", type=Path, required=True) + parser.add_argument("--risk-selection", type=Path, required=True) + parser.add_argument("--risk-package", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + cache_path = args.cache_dir / "cache_manifest.json" + alignment_path = args.alignment_dir / "evaluation.json" + cache = json.loads(cache_path.read_text(encoding="utf-8")) + alignment_report = json.loads(alignment_path.read_text(encoding="utf-8")) + risk_report = json.loads(args.risk_selection.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("scope") != "full" + or cache.get("official_test_used") is not False + or alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_path) + or risk_report.get("status") != "admitted_for_one_frozen_validation" + or risk_report.get("official_validation_used") is not False + or risk_report.get("official_test_used") is not False + or risk_report.get("package", {}).get("sha256") != sha256(args.risk_package) + ): + raise ValueError("cache/alignment/OOF-risk isolation contract failed") + package = joblib.load(args.risk_package) + if tuple(package["feature_names"]) != HARM_RISK_FEATURE_NAMES: + raise ValueError("risk package feature schema mismatch") + thresholds = package["selected_thresholds"] + if thresholds is None or thresholds != { + "expected_gain_threshold_mm": risk_report["selected"]["expected_gain_threshold_mm"], + "harm_probability_threshold": risk_report["selected"]["harm_probability_threshold"], + }: + raise ValueError("risk thresholds differ from frozen OOF selection") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_root = args.output_dir / "predictions" + prediction_root.mkdir() + all_rows = [] + coverage_rows = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + raw_path = Path(take_record["path"]) + if sha256(raw_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {raw_path}") + with np.load(raw_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + diagnostic_path = args.alignment_dir / "predictions" / raw_path.name + with np.load(diagnostic_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + if not np.array_equal(arrays["frame_id"], alignment["frame_id"]): + raise ValueError(f"alignment frame mismatch: {raw_path}") + available = alignment["alignment_applied"].astype(bool) + calibrated = np.where(available, alignment["calibrated_delta_z_m"], 0.0) + raw = np.where(available, alignment["raw_alignment_delta_z_m"], 0.0) + features = harm_risk_features( + calibrated_delta_z_m=calibrated, + raw_delta_z_m=raw, + confidence=alignment["confidence"], + alignment_available=available, + raw_alignment_available=available, + valid_support_count=alignment["support"], + projected_support_count=alignment["projected_support"], + inlier_ratio=alignment["inlier_ratio"], + residual_scale_m=alignment["residual_scale_m"], + valid_fraction=alignment["valid_fraction"], + foreground_fraction=alignment["foreground_fraction"], + background_fraction=alignment["background_fraction"], + depth_discontinuity_m=alignment["depth_discontinuity_m"], + conditioning_quality=alignment["quality"], + silhouette_overlap_fraction=alignment["silhouette_overlap_fraction"], + coarse_hand_scale_px=alignment["coarse_hand_scale_px"], + coarse_direct_mano_consistency_px=alignment[ + "coarse_direct_mano_consistency_px" + ], + coarse_wrist_translation=arrays["pred_wrist_translation"], + coarse_wrist_velocity_m_per_frame=alignment[ + "coarse_wrist_velocity_m_per_frame" + ], + predicted_depth_order=alignment["predicted_depth_order"], + ) + flat = features.reshape(-1, features.shape[-1]) + expected_gain = package["regressor"].predict(flat).reshape(features.shape[:2]) + harm_probability = package["classifier"].predict_proba(flat)[:, 1].reshape( + features.shape[:2] + ) + gate = ( + available + & (expected_gain >= thresholds["expected_gain_threshold_mm"]) + & (harm_probability <= thresholds["harm_probability_threshold"]) + ) + risk_alignment = dict(alignment) + risk_alignment["gated_delta_z_m"] = np.where(gate, calibrated, 0.0) + rows, saved = take_rows(arrays, risk_alignment, SPECS) + all_rows.extend(rows) + coverage_rows.append({ + "take": str(arrays["take"]), "samples": int(gate.size), + "available": int(available.sum()), "applied": int(gate.sum()), + "coverage": float(gate.mean()), + "mean_expected_gain_mm": float(expected_gain.mean()), + "mean_harm_probability": float(harm_probability.mean()), + }) + output = prediction_root / raw_path.name + np.savez_compressed( + output, **saved, expected_gain_mm=expected_gain.astype(np.float32), + harm_probability=harm_probability.astype(np.float32), risk_gate=gate, + risk_delta_z_m=np.where(gate, calibrated, 0.0), + ) + take_records.append({ + "take": str(arrays["take"]), "frames": len(arrays["frame_id"]), + "path": str(output), "sha256": sha256(output), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + aggregate = aggregate_rows(all_rows, SPECS) + paired = paired_take_bootstrap(all_rows) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "coverage_by_take.csv", coverage_rows) + primary = { + row["condition"]: row for row in aggregate + if row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm" + } + report = { + "status": "evaluated_single_frozen_oof_risk_policy", + "experiment": "P6_S3_harm_aware_risk_gate", + "experiment_class": "exploratory_deployable_frozen_oof_policy", + "official_validation_used": True, + "official_validation_used_for_threshold_selection": False, + "official_test_used": False, + "oracle_information": False, + "conditions": SPECS, + "risk_thresholds": thresholds, + "coverage": float(sum(row["applied"] for row in coverage_rows) / sum( + row["samples"] for row in coverage_rows + )), + "always_absolute_mpjpe_mm": float(primary[ALWAYS]["mean"]), + "risk_absolute_mpjpe_mm": float(primary[RISK]["mean"]), + "absolute_delta_mm": float(primary[RISK]["mean"] - primary[ALWAYS]["mean"]), + "new_rank_one": float(primary[RISK]["mean"]) < 19.174950061401493, + "cache_manifest": {"path": str(cache_path.resolve()), "sha256": sha256(cache_path)}, + "alignment_evaluation": { + "path": str(alignment_path.resolve()), "sha256": sha256(alignment_path), + }, + "risk_selection": { + "path": str(args.risk_selection.resolve()), "sha256": sha256(args.risk_selection), + }, + "risk_package": {"path": str(args.risk_package.resolve()), "sha256": sha256(args.risk_package)}, + "checkpoint": cache["checkpoint"], "calibrator": alignment_report["calibrator"], + "takes": take_records, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_mixed_projection.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..cf5426ac585026170b1b28ff18476ce0d6656dcb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_mixed_projection.py @@ -0,0 +1,471 @@ +#!/usr/bin/env python3 +"""Evaluate frozen Phase 6 mixed-projection assemblies on validation caches.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.mixed_projection import ( + coarse_wrist_ray_translation, + direct_wrist_ray_translation, + solve_mixed_projection_batch, +) + + +FINGERTIPS = (4, 8, 12, 16, 20) +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", + "direct_2d_error_px", + "projected_mano_2d_px", + "direct_mano_consistency_px", +) +REFERENCE = "direct_xyz_z_only__z_calibrated_always" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def condition_specs(selection: dict[str, Any]) -> list[dict[str, object]]: + winner = selection["winner"] + support = int(winner["minimum_support"]) + delta = float(winner["huber_delta_px"]) + output: list[dict[str, object]] = [ + {"id": "direct_xyz_coarse__z_coarse", "assembly": "direct_xyz_coarse", "z_mode": "coarse"}, + {"id": REFERENCE, "assembly": "direct_xyz_z_only", "z_mode": "calibrated_always"}, + {"id": "direct_xyz_z_only__z_raw_alignment", "assembly": "direct_xyz_z_only", "z_mode": "raw_alignment"}, + {"id": "direct_xyz_z_only__z_calibrated_confidence_0p6", "assembly": "direct_xyz_z_only", "z_mode": "calibrated_confidence_0p6"}, + ] + for z_mode in ( + "coarse", "raw_alignment", "calibrated_always", "calibrated_confidence_0p6", + ): + output.extend(( + {"id": f"coarse_wrist_ray__z_{z_mode}", "assembly": "coarse_wrist_ray", "z_mode": z_mode}, + {"id": f"direct_2d_wrist_ray__z_{z_mode}", "assembly": "direct_2d_wrist_ray", "z_mode": z_mode}, + { + "id": f"mixed_wls_s{support}__z_{z_mode}", + "assembly": "mixed_projection_21j_wls", "z_mode": z_mode, + "minimum_support": support, "huber_delta_px": None, + }, + { + "id": f"mixed_huber_d{delta:g}_s{support}__z_{z_mode}", + "assembly": "robust_mixed_projection", "z_mode": z_mode, + "minimum_support": support, "huber_delta_px": delta, + }, + )) + return output + + +def correction_grid(alignment: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + available = alignment["alignment_applied"].astype(bool) + raw = np.where(available, alignment["raw_alignment_delta_z_m"], 0.0) + calibrated = np.where(available, alignment["calibrated_delta_z_m"], 0.0) + confidence = np.where(available, alignment["gated_delta_z_m"], 0.0) + return { + "coarse": np.zeros_like(raw), + "raw_alignment": raw, + "calibrated_always": calibrated, + "calibrated_confidence_0p6": confidence, + } + + +def project(points: np.ndarray, K: np.ndarray) -> np.ndarray: + z = np.maximum(points[..., 2], 1e-8) + return np.stack(( + K[:, None, 0, 0] * points[..., 0] / z + K[:, None, 0, 2], + K[:, None, 1, 1] * points[..., 1] / z + K[:, None, 1, 2], + ), axis=-1) + + +def assemble( + spec: dict[str, object], + *, + coarse: np.ndarray, + root_relative_joints: np.ndarray, + anchors: np.ndarray, + K: np.ndarray, + z: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + direct = coarse.copy() + direct[:, 2] = z + ray = coarse_wrist_ray_translation(coarse, z) + assembly = spec["assembly"] + diagnostics: dict[str, np.ndarray] = {} + if assembly in {"direct_xyz_coarse", "direct_xyz_z_only"}: + return direct, diagnostics + if assembly == "coarse_wrist_ray": + return ray, diagnostics + if assembly == "direct_2d_wrist_ray": + translation, valid = direct_wrist_ray_translation(anchors, K, z, ray) + diagnostics.update({"success": valid, "failure_reason": np.where(valid, "ok", "invalid_k_or_anchor")}) + return translation, diagnostics + result = solve_mixed_projection_batch( + root_relative_joints, anchors, K, z, ray, + image_hw=(368, 640), minimum_support=int(spec["minimum_support"]), + robust_huber_delta_px=( + None if spec["huber_delta_px"] is None else float(spec["huber_delta_px"]) + ), + ) + diagnostics.update({ + "support_count": result.support_count, + "residual_scale_px": result.residual_scale_px, + "conditioning": result.conditioning, + "inlier_ratio": result.inlier_ratio, + "uncertainty_x_m": result.uncertainty_xy_m[:, 0], + "uncertainty_y_m": result.uncertainty_xy_m[:, 1], + "success": result.failure_reason == "ok", + "failure_reason": result.failure_reason, + }) + return result.translation_m, diagnostics + + +def hand_size_bucket(value: float) -> str: + return "small" if value < 64.0 else "medium" if value < 128.0 else "large" + + +def depth_bucket(value: float) -> str: + return "near" if value < 0.5 else "middle" if value < 0.8 else "far" + + +def take_rows( + arrays: dict[str, np.ndarray], + alignment: dict[str, np.ndarray], + specs: list[dict[str, object]], +) -> tuple[list[dict[str, object]], dict[str, np.ndarray]]: + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + time_index, hand = np.where(valid) + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + coarse_joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + coarse_vertices = arrays["pred_vertices_camera"][time_index, hand].astype(np.float64) + root_relative = coarse_joints - coarse_joints[:, :1] + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + K = arrays["K"][time_index].astype(np.float64) + corrections = correction_grid(alignment) + coarse_projected = project(coarse_joints, K) + scale = np.ptp(coarse_projected, axis=1).max(axis=-1) + frame_rows = [] + saved: dict[str, list[np.ndarray]] = defaultdict(list) + for spec in specs: + condition = str(spec["id"]) + z_mode = str(spec["z_mode"]) + z = coarse[:, 2] + corrections[z_mode][time_index, hand] + translation, diagnostics = assemble( + spec, coarse=coarse, root_relative_joints=root_relative, + anchors=anchors, K=K, z=z, + ) + shift = translation - coarse + joints = coarse_joints + shift[:, None] + vertices = coarse_vertices + shift[:, None] + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_vertices = arrays["target_vertices_camera"][time_index, hand].astype(np.float64) + target_translation = arrays["target_wrist_translation"][time_index, hand].astype(np.float64) + target_2d = arrays["target_2d_px"][time_index, hand].astype(np.float64) + projected = project(joints, K) + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + vertex_error = np.linalg.norm(vertices - target_vertices, axis=-1) * 1000.0 + root_joint_error = np.linalg.norm( + (joints - joints[:, :1]) - (target_joints - target_joints[:, :1]), axis=-1, + ) * 1000.0 + root_vertex_error = np.linalg.norm( + (vertices - joints[:, :1]) - (target_vertices - target_joints[:, :1]), axis=-1, + ) * 1000.0 + signed_translation = (translation - target_translation) * 1000.0 + success = diagnostics.get("success", np.ones(len(translation), dtype=bool)) + failure = diagnostics.get("failure_reason", np.full(len(translation), "ok")) + support = diagnostics.get("support_count", np.full(len(translation), 21)) + residual_scale = diagnostics.get("residual_scale_px", np.zeros(len(translation))) + conditioning = diagnostics.get("conditioning", np.ones(len(translation))) + inlier_ratio = diagnostics.get("inlier_ratio", np.ones(len(translation))) + uncertainty_x = diagnostics.get("uncertainty_x_m", np.zeros(len(translation))) + uncertainty_y = diagnostics.get("uncertainty_y_m", np.zeros(len(translation))) + for index in range(len(translation)): + current_time, current_hand = int(time_index[index]), int(hand[index]) + direct_error = np.linalg.norm(anchors[index] - target_2d[index], axis=-1).mean() + projected_error = np.linalg.norm(projected[index] - target_2d[index], axis=-1).mean() + consistency = np.linalg.norm(projected[index] - anchors[index], axis=-1).mean() + frame_rows.append({ + "condition": condition, + "assembly": spec["assembly"], + "z_mode": z_mode, + "take": take, + "subject": take.split("/")[0], + "action_family": take.split("/")[1], + "frame_id": int(arrays["frame_id"][current_time]), + "side": "right" if current_hand else "left", + "hand_size_bucket": hand_size_bucket(float(scale[index])), + "depth_bucket": depth_bucket(float(target_translation[index, 2])), + "absolute_mpjpe_mm": float(joint_error[index].mean()), + "root_relative_mpjpe_mm": float(root_joint_error[index].mean()), + "absolute_mpvpe_mm": float(vertex_error[index].mean()), + "root_relative_mpvpe_mm": float(root_vertex_error[index].mean()), + "fingertip_mpjpe_mm": float(joint_error[index, FINGERTIPS].mean()), + "translation_x_mae_mm": abs(float(signed_translation[index, 0])), + "translation_y_mae_mm": abs(float(signed_translation[index, 1])), + "translation_z_mae_mm": abs(float(signed_translation[index, 2])), + "translation_x_signed_error_mm": float(signed_translation[index, 0]), + "translation_y_signed_error_mm": float(signed_translation[index, 1]), + "translation_z_signed_error_mm": float(signed_translation[index, 2]), + "direct_2d_error_px": float(direct_error), + "projected_mano_2d_px": float(projected_error), + "direct_mano_consistency_px": float(consistency), + "applied_delta_z_mm": float(1000.0 * corrections[z_mode][current_time, current_hand]), + "support_count": int(support[index]), + "residual_scale_px": float(residual_scale[index]), + "conditioning": float(conditioning[index]), + "inlier_ratio": float(inlier_ratio[index]), + "uncertainty_x_mm": float(1000.0 * uncertainty_x[index]), + "uncertainty_y_mm": float(1000.0 * uncertainty_y[index]), + "solve_success": bool(success[index]), + "failure_reason": str(failure[index]), + }) + saved[f"translation__{condition}"].append(translation.astype(np.float32)) + saved[f"success__{condition}"].append(success.astype(bool)) + saved_arrays: dict[str, np.ndarray] = { + "frame_id": arrays["frame_id"], + "valid_time_index": time_index.astype(np.int64), + "valid_hand_index": hand.astype(np.int64), + } + saved_arrays.update({key: value[0] for key, value in saved.items()}) + return frame_rows, saved_arrays + + +def aggregate_rows( + rows: list[dict[str, object]], specs: list[dict[str, object]], +) -> list[dict[str, object]]: + output = [] + for spec in specs: + condition = str(spec["id"]) + selected = [row for row in rows if row["condition"] == condition] + for metric in METRICS: + output.append({ + "condition": condition, "group": "all", "value": "all", "metric": metric, + **distribution_summary(row[metric] for row in selected), + }) + for group in ("side", "hand_size_bucket", "depth_bucket", "take", "action_family"): + for value in sorted({str(row[group]) for row in selected}): + grouped = [row for row in selected if str(row[group]) == value] + for metric in METRICS: + output.append({ + "condition": condition, "group": group, "value": value, + "metric": metric, + **distribution_summary(row[metric] for row in grouped), + }) + output.append({ + "condition": condition, "group": "all", "value": "all", + "metric": "solve_success_fraction", + **distribution_summary(float(row["solve_success"]) for row in selected), + }) + return output + + +def paired_take_bootstrap( + rows: list[dict[str, object]], specs: list[dict[str, object]], + *, samples: int = 10_000, seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + take_mean: dict[tuple[str, str, str], float] = {} + for spec in specs: + condition = str(spec["id"]) + for take in takes: + selected = [row for row in rows if row["condition"] == condition and row["take"] == take] + for metric in METRICS: + take_mean[(condition, take, metric)] = float(np.mean([row[metric] for row in selected])) + output = [] + rng = np.random.default_rng(seed) + for spec in specs: + condition = str(spec["id"]) + if condition == REFERENCE: + continue + for metric in METRICS: + delta = np.asarray([ + take_mean[(condition, take, metric)] - take_mean[(REFERENCE, take, metric)] + for take in takes + ]) + indices = rng.integers(0, len(delta), size=(samples, len(delta))) + boot = delta[indices].mean(axis=1) + output.append({ + "condition": condition, "reference": REFERENCE, "metric": metric, + "takes": len(takes), "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(boot, 2.5)), + "ci_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--alignment-dir", type=Path, required=True) + parser.add_argument("--oof-selection", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + cache_manifest_path = args.cache_dir / "cache_manifest.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + alignment_report_path = args.alignment_dir / "evaluation.json" + alignment_report = json.loads(alignment_report_path.read_text(encoding="utf-8")) + selection = json.loads(args.oof_selection.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("split_role") != "official_validation" + or cache.get("scope") != "full" + or cache.get("official_test_used") is not False + or alignment_report.get("status") != "evaluated" + or alignment_report.get("official_test_used") is not False + or alignment_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + or selection.get("status") != "selected_oof_only" + or selection.get("official_validation_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("cache/alignment/OOF isolation contract failed") + specs = condition_specs(selection) + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_dir = args.output_dir / "predictions" + prediction_dir.mkdir() + all_rows = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + alignment_path = args.alignment_dir / "predictions" / take_path.name + with np.load(alignment_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + if not np.array_equal(arrays["frame_id"], alignment["frame_id"]): + raise ValueError(f"alignment frame mismatch: {take_path}") + rows, saved = take_rows(arrays, alignment, specs) + all_rows.extend(rows) + output_path = prediction_dir / take_path.name + np.savez_compressed(output_path, **saved) + take_records.append({ + "take": str(arrays["take"]), "frames": len(arrays["frame_id"]), + "path": str(output_path), "sha256": sha256(output_path), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + aggregate = aggregate_rows(all_rows, specs) + paired = paired_take_bootstrap(all_rows, specs) + reference_rows = { + (row["take"], row["frame_id"], row["side"]): row + for row in all_rows if row["condition"] == REFERENCE + } + case_rows = [] + for spec in specs: + condition = str(spec["id"]) + if condition == REFERENCE: + continue + selected = [row for row in all_rows if row["condition"] == condition] + deltas = np.asarray([ + float(row["absolute_mpjpe_mm"]) + - float(reference_rows[(row["take"], row["frame_id"], row["side"])]["absolute_mpjpe_mm"]) + for row in selected + ]) + for role, indices in ( + ("largest_gain", np.argsort(deltas)[:10]), + ("largest_harm", np.argsort(deltas)[-10:][::-1]), + ): + for rank, index in enumerate(indices, start=1): + row = selected[int(index)] + case_rows.append({ + "condition": condition, "role": role, "rank": rank, + "take": row["take"], "frame_id": row["frame_id"], "side": row["side"], + "absolute_delta_mm": float(deltas[index]), + "candidate_absolute_mpjpe_mm": row["absolute_mpjpe_mm"], + "reference_absolute_mpjpe_mm": reference_rows[ + (row["take"], row["frame_id"], row["side"]) + ]["absolute_mpjpe_mm"], + "support_count": row["support_count"], + "residual_scale_px": row["residual_scale_px"], + "conditioning": row["conditioning"], + "inlier_ratio": row["inlier_ratio"], + "failure_reason": row["failure_reason"], + }) + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "largest_gain_harm.csv", case_rows) + primary_rows = [ + row for row in aggregate + if row["group"] == "all" and row["metric"] == "absolute_mpjpe_mm" + ] + best = min(primary_rows, key=lambda row: float(row["mean"])) + reference = next(row for row in primary_rows if row["condition"] == REFERENCE) + guardrail = min(0.2, 0.01 * float(reference["mean"])) + report = { + "status": "evaluated_frozen_oof_selection", + "experiment": "P6_S1_cache_mixed_projection", + "experiment_class": "preregistered_cache_only_deployable_ablation", + "official_validation_used": True, + "official_validation_used_for_solver_constant_selection": False, + "official_test_used": False, + "oracle_information": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "alignment_evaluation": {"path": str(alignment_report_path.resolve()), "sha256": sha256(alignment_report_path)}, + "oof_selection": {"path": str(args.oof_selection.resolve()), "sha256": sha256(args.oof_selection)}, + "checkpoint": cache["checkpoint"], + "calibrator": alignment_report["calibrator"], + "conditions": specs, + "reference_condition": REFERENCE, + "reference_absolute_mpjpe_mm": float(reference["mean"]), + "best_condition": best["condition"], + "best_absolute_mpjpe_mm": float(best["mean"]), + "best_delta_mm": float(best["mean"] - reference["mean"]), + "new_rank_one": float(best["mean"]) < 19.45484110440441, + "geometry_secondary_guardrail_passed": float(best["mean"]) <= float(reference["mean"]) + guardrail, + "takes": take_records, + "outputs": { + "per_hand": "per_hand_frame_metrics.csv", "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "largest_gain_harm": "largest_gain_harm.csv", "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "reference": report["reference_absolute_mpjpe_mm"], + "best_condition": report["best_condition"], "best": report["best_absolute_mpjpe_mm"], + "new_rank_one": report["new_rank_one"], "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_pa_mpjpe.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_pa_mpjpe.py new file mode 100644 index 0000000000000000000000000000000000000000..59e3ad31371664ffe62f535f94ff288f2eaece36 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_pa_mpjpe.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Evaluate seed17 rigid and standard Procrustes-aligned MPJPE.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def summary(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + return { + "count": len(array), "mean": float(array.mean()), + "p50": float(np.percentile(array, 50)), + "p95": float(np.percentile(array, 95)), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + ): + raise ValueError("raw cache isolation contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + values: dict[str, list[float]] = defaultdict(list) + rows = [] + for take_record in manifest["takes"]: + path = Path(take_record["path"]) + if sha256(path) != take_record["sha256"]: + raise ValueError(f"cache take hash mismatch: {path}") + with np.load(path, allow_pickle=False) as archive: + predicted = archive["pred_joints_camera"] + target = archive["target_joints_camera"] + valid = archive["joint_annotation_valid"].astype(bool) & archive[ + "frame_valid" + ][:, None].astype(bool) + frame_ids = archive["frame_id"] + take = str(archive["take"]) + for hand, side in enumerate(("left", "right")): + indices = np.where(valid[:, hand])[0] + rigid = aligned_mpjpe_mm( + predicted[indices, hand], target[indices, hand], estimate_scale=False, + ) + similarity = aligned_mpjpe_mm( + predicted[indices, hand], target[indices, hand], estimate_scale=True, + ) + values["rigid_aligned_mpjpe_mm"].extend(rigid.tolist()) + values["pa_mpjpe_mm"].extend(similarity.tolist()) + values[f"{side}_rigid_aligned_mpjpe_mm"].extend(rigid.tolist()) + values[f"{side}_pa_mpjpe_mm"].extend(similarity.tolist()) + rows.extend({ + "take": take, "frame_id": int(frame_ids[index]), "side": side, + "rigid_aligned_mpjpe_mm": float(rigid[position]), + "pa_mpjpe_mm": float(similarity[position]), + } for position, index in enumerate(indices)) + with (args.output_dir / "per_hand_frame_metrics.csv").open( + "x", newline="", encoding="utf-8", + ) as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "evaluated", + "experiment": "P6_pose_alignment_metric_addendum", + "official_test_used": False, + "metric_definitions": { + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation, and scale", + "rigid_aligned_mpjpe_mm": "per-hand SE(3) Kabsch; removes translation and rotation only", + }, + "translation_only_system_invariance": True, + "metrics": {key: summary(items) for key, items in values.items()}, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_state_ray.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_state_ray.py new file mode 100644 index 0000000000000000000000000000000000000000..a44aac603af5f949a790d4f714314f029344abdf --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase6_state_ray.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Compose frozen causal-state z estimates with the coarse wrist camera ray.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.evaluation.mixed_projection import coarse_wrist_ray_translation +from scripts.evaluate_phase4_jitter import ( + identity_switch_metrics, + per_frame_metrics, + temporal_metrics, +) +from scripts.evaluate_phase5_causal_state import response_diagnostics +from scripts.evaluate_phase6_mixed_projection import METRICS, aggregate_rows, take_rows + + +STATE_CONDITIONS = ( + "coarse", + "calibrated_per_frame", + "ema_alpha0.6", + "butterworth_2hz", + "fixed_kalman", + "uncertainty_kalman", +) +REFERENCE = "calibrated_per_frame__coarse_wrist_ray" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + fields.extend(sorted({key for row in rows for key in row} - set(fields))) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_npz(path: Path) -> dict[str, np.ndarray]: + with np.load(path, allow_pickle=False) as archive: + return {key: archive[key] for key in archive.files} + + +def assemble_state_ray_geometry( + coarse_translation_m: np.ndarray, + coarse_joints_m: np.ndarray, + coarse_vertices_m: np.ndarray, + state_z_m: np.ndarray, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Preserve each coarse wrist ray and rigidly translate its hand geometry.""" + + coarse_translation = np.asarray(coarse_translation_m, dtype=np.float64) + state_z = np.asarray(state_z_m, dtype=np.float64) + safe_z = np.where( + np.isfinite(state_z) & (state_z > 0.05), + state_z, + coarse_translation[..., 2], + ) + translation = coarse_wrist_ray_translation(coarse_translation, safe_z) + shift = translation - coarse_translation + joints = np.asarray(coarse_joints_m, dtype=np.float64) + shift[..., None, :] + vertices = np.asarray(coarse_vertices_m, dtype=np.float64) + shift[..., None, :] + return translation, joints, vertices + + +def paired_bootstrap( + rows: list[dict[str, object]], + conditions: list[str], + *, + samples: int, + seed: int = 20260717, +) -> list[dict[str, object]]: + takes = sorted({str(row["take"]) for row in rows}) + means: dict[tuple[str, str, str], float] = {} + for condition in conditions: + for take in takes: + selected = [ + row for row in rows + if row["condition"] == condition and row["take"] == take + ] + for metric in METRICS: + means[(condition, take, metric)] = float( + np.mean([float(row[metric]) for row in selected]) + ) + output = [] + for condition_index, condition in enumerate(conditions): + if condition == REFERENCE: + continue + for metric_index, metric in enumerate(METRICS): + delta = np.asarray([ + means[(condition, take, metric)] - means[(REFERENCE, take, metric)] + for take in takes + ]) + rng = np.random.default_rng( + np.random.SeedSequence((seed, condition_index, metric_index)) + ) + bootstrap = delta[ + rng.integers(0, len(delta), size=(samples, len(delta))) + ].mean(axis=1) + output.append({ + "condition": condition, + "reference": REFERENCE, + "metric": metric, + "takes": len(takes), + "delta_mean": float(delta.mean()), + "ci_low": float(np.percentile(bootstrap, 2.5)), + "ci_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--state-evaluation-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + + cache_manifest_path = args.cache_dir / "cache_manifest.json" + state_report_path = args.state_evaluation_dir / "evaluation.json" + cache = json.loads(cache_manifest_path.read_text(encoding="utf-8")) + state_report = json.loads(state_report_path.read_text(encoding="utf-8")) + if ( + cache.get("status") != "complete" + or cache.get("sequence_mode") != "causal" + or cache.get("split_role") != "official_validation" + or cache.get("official_test_used") is not False + or state_report.get("status") != "evaluated" + or state_report.get("official_test_used") is not False + or state_report.get("official_validation_used_for_parameter_selection") is not False + or state_report.get("continuous_take_state") is not True + or state_report.get("cache_manifest", {}).get("sha256") != sha256(cache_manifest_path) + ): + raise ValueError("causal cache/state isolation contract failed") + + args.output_dir.mkdir(parents=True, exist_ok=True) + prediction_dir = args.output_dir / "predictions" + prediction_dir.mkdir() + specs = [ + { + "id": f"{condition}__coarse_wrist_ray", + "assembly": "coarse_wrist_ray", + "z_mode": "calibrated_always", + } + for condition in STATE_CONDITIONS + ] + all_rows: list[dict[str, object]] = [] + temporal_values = { + str(spec["id"]): defaultdict(list) for spec in specs + } + temporal_take_rows: list[dict[str, object]] = [] + take_records = [] + for take_index, take_record in enumerate(cache["takes"], start=1): + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"raw cache hash mismatch: {take_path}") + arrays = load_npz(take_path) + arrays["clip_index"] = np.zeros_like(arrays["clip_index"]) + state_path = args.state_evaluation_dir / "predictions" / take_path.name + state = load_npz(state_path) + if not np.array_equal(arrays["frame_id"], state["frame_id"]): + raise ValueError(f"state frame mismatch: {take_path}") + arrays["_calibrated_measurement_z_m"] = state["calibrated_per_frame_z_m"] + saved: dict[str, np.ndarray] = {"frame_id": arrays["frame_id"]} + for spec, state_condition in zip(specs, STATE_CONDITIONS, strict=True): + condition = str(spec["id"]) + z_m = state[f"{state_condition}_z_m"].astype(np.float64) + correction = z_m - arrays["pred_wrist_translation"][..., 2] + alignment = { + "alignment_applied": np.isfinite(correction), + "raw_alignment_delta_z_m": correction, + "calibrated_delta_z_m": correction, + "gated_delta_z_m": correction, + } + rows, _ = take_rows(arrays, alignment, [spec]) + all_rows.extend(rows) + translation, joints, vertices = assemble_state_ray_geometry( + arrays["pred_wrist_translation"], + arrays["pred_joints_camera"], + arrays["pred_vertices_camera"], + z_m, + ) + selected = arrays["frame_valid"].astype(bool) + _, projected, _ = per_frame_metrics( + arrays, + joints, + vertices, + arrays["pred_rotation_matrices"], + translation, + selected, + ) + values = temporal_metrics(arrays, joints, projected, selected) + identity = identity_switch_metrics(arrays, joints, selected) + values.update(identity) + values.update(response_diagnostics(arrays, z_m)) + for metric, observations in values.items(): + finite = [float(value) for value in observations if np.isfinite(value)] + temporal_values[condition][metric].extend(finite) + temporal_take_rows.append({ + "take": str(arrays["take"]), + "condition": condition, + "metric": metric, + **distribution_summary(finite), + }) + saved[f"translation__{condition}"] = translation.astype(np.float32) + saved[f"z_variance_m2__{condition}"] = state[ + f"{state_condition}_variance_m2" + ].astype(np.float32) + output_path = prediction_dir / take_path.name + np.savez_compressed(output_path, **saved) + take_records.append({ + "take": str(arrays["take"]), + "frames": len(arrays["frame_id"]), + "path": str(output_path), + "sha256": sha256(output_path), + }) + print(f"[{take_index}/{len(cache['takes'])}] {arrays['take']}", flush=True) + + aggregate = aggregate_rows(all_rows, specs) + conditions = [str(spec["id"]) for spec in specs] + paired = paired_bootstrap( + all_rows, conditions, samples=args.bootstrap_samples, + ) + temporal_rows = [ + {"condition": condition, "metric": metric, **distribution_summary(values)} + for condition in conditions + for metric, values in sorted(temporal_values[condition].items()) + ] + write_csv(args.output_dir / "per_hand_frame_metrics.csv", all_rows) + write_csv(args.output_dir / "group_metrics.csv", aggregate) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", paired) + write_csv(args.output_dir / "temporal_metrics.csv", temporal_rows) + write_csv(args.output_dir / "temporal_take_metrics.csv", temporal_take_rows) + + static_index = { + (str(row["condition"]), str(row["metric"])): row + for row in aggregate if row["group"] == "all" and row["value"] == "all" + } + temporal_index = { + (str(row["condition"]), str(row["metric"])): row for row in temporal_rows + } + overview = [] + for condition in conditions: + row: dict[str, object] = { + "condition": condition, + "absolute_mpjpe_mm": static_index[(condition, "absolute_mpjpe_mm")]["mean"], + "absolute_mpvpe_mm": static_index[(condition, "absolute_mpvpe_mm")]["mean"], + "fingertip_mpjpe_mm": static_index[(condition, "fingertip_mpjpe_mm")]["mean"], + "translation_x_mae_mm": static_index[(condition, "translation_x_mae_mm")]["mean"], + "translation_y_mae_mm": static_index[(condition, "translation_y_mae_mm")]["mean"], + "translation_z_mae_mm": static_index[(condition, "translation_z_mae_mm")]["mean"], + "translation_z_p95_mm": static_index[(condition, "translation_z_mae_mm")]["p95"], + "projected_mano_2d_px": static_index[(condition, "projected_mano_2d_px")]["mean"], + } + for metric in ( + "joint_velocity_error_mm_per_s", + "joint_acceleration_error_mm_per_s2", + "predicted_3d_joint_acceleration_mm_per_s2", + "predicted_3d_joint_jerk_mm_per_s3", + "high_frequency_energy_ratio", + "estimated_causal_lag_frames", + ): + if (condition, metric) in temporal_index: + row[metric] = temporal_index[(condition, metric)]["mean"] + overview.append(row) + reference = next(row for row in overview if row["condition"] == REFERENCE) + for row in overview: + row["absolute_delta_mm"] = float(row["absolute_mpjpe_mm"]) - float( + reference["absolute_mpjpe_mm"] + ) + row["static_guardrail_passed"] = bool( + float(row["absolute_delta_mm"]) <= 0.2 + and float(row["translation_z_mae_mm"]) + <= float(reference["translation_z_mae_mm"]) + 0.2 + and float(row["translation_z_p95_mm"]) + <= float(reference["translation_z_p95_mm"]) + 0.2 + ) + write_csv(args.output_dir / "overview.csv", overview) + report = { + "status": "evaluated_frozen_causal_state_coarse_ray", + "experiment_class": "preregistered_frozen_parameter_causal_state_composition", + "official_validation_used": True, + "official_validation_used_for_parameter_selection": False, + "official_test_used": False, + "oracle_information": False, + "cache_manifest": {"path": str(cache_manifest_path.resolve()), "sha256": sha256(cache_manifest_path)}, + "state_evaluation": {"path": str(state_report_path.resolve()), "sha256": sha256(state_report_path)}, + "selection": state_report["selection"], + "assembly": "coarse wrist camera ray recomputed at each frozen state z", + "reference": REFERENCE, + "conditions": conditions, + "takes": take_records, + "outputs": { + "overview": "overview.csv", + "per_hand": "per_hand_frame_metrics.csv", + "groups": "group_metrics.csv", + "paired_take_bootstrap": "paired_take_bootstrap_ci.csv", + "temporal": "temporal_metrics.csv", + "temporal_takes": "temporal_take_metrics.csv", + "predictions": "predictions/", + }, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": report["status"], "overview": overview}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase7_egodexter_zero_shot.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase7_egodexter_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..d9afe80a0f18d42d100ec440bdaeeb35b14f9e7f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase7_egodexter_zero_shot.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Evaluate a fully frozen Phase 7 model on EgoDexter exactly once.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import time +from typing import Any, Iterator + +import numpy as np +import torch +import yaml + +from foundation_hand.data.egodexter_dataset import ( + EgoDexterSequenceDataset, FINGERTIP_JOINT_INDICES, SEQUENCES, +) +from foundation_hand.inference import LengthGeneralizedInference, SequenceInferenceConfig +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.train_phase7_external import assert_physical_gpu_idle + + +FINGER_NAMES = ("thumb", "index", "middle", "ring", "little") +MODEL_INPUT_FIELDS = { + "rgb", "depth_m", "depth_pixel_valid", "K", "K_available", + "K_input_available", "depth_available", "depth_input_available", "frame_valid", +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def finite_summary(values: list[float]) -> dict[str, float | int] | None: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if not len(array): + return None + return { + "count": int(len(array)), "mean": float(array.mean()), + "median": float(np.median(array)), "p95": float(np.quantile(array, .95)), + } + + +def validate_freeze_record( + record: dict[str, Any], model_id: str, checkpoint_sha: str, + config_path: Path, inference_mode: str, +) -> dict[str, Any]: + if ( + record.get("status") != "phase7_final_models_frozen" + or record.get("egodexter_used_for_training_or_selection") is not False + or record.get("official_test_used") is not False + ): + raise ValueError("Phase 7 final model set is not EgoDexter-eligible") + models = {item["id"]: item for item in record.get("models", [])} + if model_id not in models: + raise ValueError(f"model is absent from the final freeze: {model_id}") + model = models[model_id] + if model.get("checkpoint_sha256") != checkpoint_sha: + raise ValueError("checkpoint differs from final model freeze") + config_record = model.get("inference_configs", {}).get(inference_mode, {}) + if ( + Path(config_record.get("path", "")).resolve() != config_path.resolve() + or config_record.get("sha256") != sha256(config_path) + ): + raise ValueError("inference config differs from final model freeze") + mapping = record.get("egodexter_sequence_handedness", {}) + if set(mapping) != set(SEQUENCES) or any(side not in {"left", "right"} for side in mapping.values()): + raise ValueError("EgoDexter sequence handedness is not fully frozen") + return model + + +def model_frame(frame: dict[str, object]) -> dict[str, object]: + return {key: frame[key] for key in MODEL_INPUT_FIELDS} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--model-id", required=True) + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--input-mode", choices=("rgb_d_k", "rgb_k", "rgb_only"), required=True) + parser.add_argument("--inference-mode", choices=("offline", "causal"), required=True) + parser.add_argument("--window", type=int, default=8) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + checkpoint_sha = sha256(args.checkpoint) + freeze = json.loads(args.freeze_record.read_text(encoding="utf-8")) + validate_freeze_record( + freeze, args.model_id, checkpoint_sha, args.config, args.inference_mode, + ) + assert_physical_gpu_idle(args.physical_gpu_id) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + attention_mode = config["model"].get("temporal_attention_mode", "bidirectional") + required_attention = "causal" if args.inference_mode == "causal" else "bidirectional" + if attention_mode != required_attention: + parser.error("inference mode and temporal attention mode differ") + assets = config["assets"] + device = torch.device("cuda") + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).to(device).eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + sequence_handedness = freeze["egodexter_sequence_handedness"] + rows: list[dict[str, Any]] = [] + raw_prediction, raw_target, raw_valid = [], [], [] + raw_sequence, raw_frame, raw_side = [], [], [] + maximum_gpu_window = 0 + maximum_cpu_buffer = 0 + total_frames = 0 + started = time.perf_counter() + torch.cuda.reset_peak_memory_stats() + for sequence_index, sequence in enumerate(SEQUENCES): + dataset = EgoDexterSequenceDataset( + args.root, sequence, hand_side=sequence_handedness[sequence], + target_hw=tuple(config["data"]["resolution_hw"]), + ) + targets: list[np.ndarray] = [] + target_valid: list[np.ndarray] = [] + frame_ids: list[int] = [] + + def frames() -> Iterator[dict[str, object]]: + for index in range(len(dataset)): + frame = dataset.frame(index, args.input_mode) + targets.append(frame["target_fingertips_camera_m"].numpy()) + target_valid.append(frame["target_fingertip_valid"].numpy()) + frame_ids.append(int(frame["frame_id"])) + yield model_frame(frame) + + runner = LengthGeneralizedInference( + model, + SequenceInferenceConfig( + mode=args.inference_mode, window_size=args.window, + offline_stride=(args.window // 2 if args.inference_mode == "offline" else None), + ), + device=device, autocast_dtype=dtype, + ) + output = runner.infer(frames()) + predicted = output["joints_camera"][0, :, dataset.side_index][ + :, FINGERTIP_JOINT_INDICES + ].numpy() + target = np.stack(targets) + valid = np.stack(target_valid) & np.isfinite(predicted).all(axis=-1) + error = np.linalg.norm(predicted - target, axis=-1) * 1000.0 + for frame_index, frame_id in enumerate(frame_ids): + for finger, name in enumerate(FINGER_NAMES): + rows.append({ + "model_id": args.model_id, "sequence": sequence, + "frame_id": frame_id, "hand_side": dataset.hand_side, + "finger": name, "target_visible": bool(valid[frame_index, finger]), + "fingertip_error_mm": ( + float(error[frame_index, finger]) if valid[frame_index, finger] else math.nan + ), + }) + raw_prediction.append(predicted) + raw_target.append(target) + raw_valid.append(valid) + raw_sequence.append(np.full(len(dataset), sequence_index, dtype=np.int16)) + raw_frame.append(np.asarray(frame_ids, dtype=np.int32)) + raw_side.append(np.full(len(dataset), dataset.side_index, dtype=np.int8)) + total_frames += len(dataset) + maximum_gpu_window = max(maximum_gpu_window, runner.maximum_resident_frames) + maximum_cpu_buffer = max(maximum_cpu_buffer, runner.maximum_input_buffer_frames) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + args.output_dir.mkdir(parents=True) + row_path = args.output_dir / "per_fingertip_metrics.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed( + raw_path, predicted_fingertips_camera_m=np.concatenate(raw_prediction), + target_fingertips_camera_m=np.concatenate(raw_target), + target_visible=np.concatenate(raw_valid), sequence_index=np.concatenate(raw_sequence), + frame_id=np.concatenate(raw_frame), side_index=np.concatenate(raw_side), + ) + visible = [row["fingertip_error_mm"] for row in rows if row["target_visible"]] + report = { + "status": "evaluated_frozen_egodexter_zero_shot", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "model_id": args.model_id, "checkpoint_step": int(state["step"]), + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": checkpoint_sha}, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "freeze_record": {"path": str(args.freeze_record.resolve()), "sha256": sha256(args.freeze_record)}, + "input_mode": args.input_mode, "inference_mode": args.inference_mode, + "causal": args.inference_mode == "causal", "window": args.window, + "frames": total_frames, "visible_fingertips": len(visible), + "coverage_fraction": len(visible) / (total_frames * len(FINGER_NAMES)), + "fingertip_error_mm": finite_summary(visible), + "per_finger": { + finger: finite_summary([ + row["fingertip_error_mm"] for row in rows + if row["finger"] == finger and row["target_visible"] + ]) for finger in FINGER_NAMES + }, + "per_sequence": { + sequence: finite_summary([ + row["fingertip_error_mm"] for row in rows + if row["sequence"] == sequence and row["target_visible"] + ]) for sequence in SEQUENCES + }, + "sequence_handedness": sequence_handedness, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": total_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + "maximum_gpu_window_frames": maximum_gpu_window, + "maximum_cpu_input_buffer_frames": maximum_cpu_buffer, + }, + "per_fingertip_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "gt_passed_to_model": False, "per_frame_gt_slot_selection_used": False, + "egodexter_used_for_training_or_selection": False, "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase7_external.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..b067ba132f65bcdbd91712c730da0ff052e1e2f6 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase7_external.py @@ -0,0 +1,749 @@ +#!/usr/bin/env python3 +"""Unified held-out evaluation for Phase 7 external-only checkpoints.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import CachedUnifiedClipDataset, collate_h2o_clips +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from foundation_hand.geometry.camera import project_points +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.train_experiment import attach_gt_vertices, move_to_device +from scripts.train_phase7_external import assert_physical_gpu_idle + + +TIP_INDICES = (4, 8, 12, 16, 20) + + +def checkpoint_h2o_training_data_used(checkpoint_extra: dict[str, Any]) -> bool: + """Read H2O exposure without relabelling historical H2O checkpoints.""" + + explicit = checkpoint_extra.get("h2o_training_data_used") + if isinstance(explicit, bool): + return explicit + experiment = checkpoint_extra.get("config", {}).get("experiment", {}) + phase = experiment.get("phase") + # Phase 3-6 checkpoints predate the explicit provenance flag and were + # trained on the canonical H2O train split. + if isinstance(phase, int) and 3 <= phase <= 6: + return True + raise ValueError("checkpoint lacks auditable H2O-training provenance") + + +def validate_evaluation_role( + role: str, config: dict[str, Any], dataset_ids: set[str], + checkpoint_extra: dict[str, Any], cache_manifest: Path, +) -> None: + branch = config.get("experiment", {}).get("branch") + if role == "external_heldout": + if branch != "external_only": + raise ValueError("external evaluation config is not external-only") + if "H2O" in dataset_ids or checkpoint_extra.get("h2o_training_data_used") is not False: + raise ValueError("external evaluator refuses H2O data or training exposure") + elif role == "h2o_train_group_heldout": + if branch != "h2o_adaptation": + raise ValueError("H2O train-heldout evaluation requires an adaptation config") + if dataset_ids != {"H2O"}: + raise ValueError("H2O train-heldout evaluation requires a pure H2O cache") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("adaptation checkpoint lacks H2O-training provenance") + if cache_manifest.name != "train_group_heldout.jsonl": + raise ValueError("adaptation selection requires the frozen train-group-heldout manifest") + elif role == "h2o_train_group_heldout_control": + if dataset_ids != {"H2O"}: + raise ValueError("H2O train-heldout control requires a pure H2O cache") + checkpoint_h2o_training_data_used(checkpoint_extra) + if cache_manifest.name != "train_group_heldout.jsonl": + raise ValueError("H2O control requires the frozen train-group-heldout manifest") + elif role == "adaptation_external_heldout": + if branch != "h2o_adaptation": + raise ValueError("adaptation forgetting evaluation requires an adaptation config") + if not dataset_ids or not dataset_ids.issubset({"HOT3D", "HOI4D", "ARCTIC"}): + raise ValueError("adaptation forgetting evaluation requires pure external held-out data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("adaptation forgetting checkpoint lacks H2O-training provenance") + if "h2o" in str(cache_manifest).lower(): + raise ValueError("adaptation forgetting evaluation refuses H2O cache paths") + elif role == "phase9_external_heldout": + if branch != "phase9_unified": + raise ValueError("Phase 9 external evaluation requires a unified config") + if not dataset_ids or not dataset_ids.issubset({"HOT3D", "HOI4D", "ARCTIC"}): + raise ValueError("Phase 9 external evaluation requires pure external held-out data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("Phase 9 unified checkpoint lacks H2O-training provenance") + if "h2o" in str(cache_manifest).lower(): + raise ValueError("Phase 9 external evaluation refuses H2O cache paths") + elif role == "phase9_h2o_fold_heldout": + fold = str(config.get("experiment", {}).get("h2o_selection_fold", "")) + if branch != "phase9_unified" or not fold: + raise ValueError("Phase 9 fold evaluation requires a fold-specific unified config") + if dataset_ids != {"H2O"}: + raise ValueError("Phase 9 fold evaluation requires pure H2O train-heldout data") + if checkpoint_extra.get("h2o_training_data_used") is not True: + raise ValueError("Phase 9 fold checkpoint lacks H2O-training provenance") + expected = f"{fold}_heldout.jsonl" + if cache_manifest.name != expected: + raise ValueError(f"Phase 9 fold cache must be {expected}") + else: + raise ValueError(f"unsupported evaluation role: {role}") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_progress_heartbeat(path: Path | None, value: dict[str, Any]) -> None: + if path is None: + return + payload = { + "schema_version": "phase9_evaluation_progress_heartbeat_v1", + "updated_utc": datetime.now(timezone.utc).isoformat(), + "evaluator_pid": os.getpid(), + "h2o_official_validation_used": False, + "official_test_used": False, + **value, + } + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def direct_child_pids(pid: int) -> list[int]: + path = Path(f"/proc/{pid}/task/{pid}/children") + try: + return sorted(int(value) for value in path.read_text().split()) + except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError): + return [] + + +def finite_summary(values: list[float]) -> dict[str, float | int] | None: + array = np.asarray(values, dtype=np.float64) + array = array[np.isfinite(array)] + if not len(array): + return None + p95 = float(np.quantile(array, .95)) + tail = array[array >= p95] + return { + "count": int(len(array)), "mean": float(array.mean()), + "median": float(np.median(array)), "p90": float(np.quantile(array, .90)), + "p95": p95, "p99": float(np.quantile(array, .99)), + "cvar95": float(tail.mean()), "max": float(array.max()), + } + + +def tensor_to_numpy(value: torch.Tensor) -> np.ndarray: + """Move persisted floating predictions to a NumPy-supported dtype.""" + value = value.detach().cpu() + if value.is_floating_point() and value.dtype == torch.bfloat16: + value = value.float() + return value.numpy() + + +def append_valid_frame_arrays( + raw: dict[str, list[np.ndarray]], values: dict[str, torch.Tensor], + frame_valid: torch.Tensor, +) -> None: + """Persist variable-length clips on one contiguous valid-frame axis.""" + + valid = tensor_to_numpy(frame_valid.bool()).reshape(-1) + batch, time = frame_valid.shape + for key, value in values.items(): + array = tensor_to_numpy(value) + if array.shape[:2] != (batch, time): + raise ValueError(f"raw temporal field shape differs from frame_valid: {key}") + flattened = array.reshape(batch * time, *array.shape[2:]) + raw.setdefault(key, []).append(flattened[valid]) + + +def hand_size_bucket(size_px: float) -> str: + if size_px < 64.0: + return "small_lt64" + if size_px < 128.0: + return "medium_64_128" + return "large_ge128" + + +def depth_bucket(depth_m: float) -> str: + return "far_gt0.8m" if depth_m > .8 else "near_le0.8m" + + +def apply_input_mode(batch: dict[str, Any], mode: str) -> None: + frame = batch["frame_valid"].bool() + if mode == "rgb_d_k": + batch["K_input_available"] = frame.clone() + elif mode == "rgb_k": + batch["K_input_available"] = frame.clone() + batch["depth_input_available"] = torch.zeros_like(frame) + elif mode == "rgb_only": + batch["K_input_available"] = torch.zeros_like(frame) + batch["depth_input_available"] = torch.zeros_like(frame) + else: + raise ValueError(f"unsupported input mode: {mode}") + batch["K_available"] = batch["K_input_available"] + batch["depth_available"] = batch["depth_input_available"] + + +def grouped_bootstrap( + rows: list[dict[str, Any]], metric: str, seed: int, resamples: int, +) -> dict[str, float | int] | None: + groups: dict[str, list[float]] = {} + for row in rows: + value = row.get(metric) + if value is not None and math.isfinite(float(value)): + groups.setdefault(str(row["physical_recording_id"]), []).append(float(value)) + if not groups: + return None + keys = sorted(groups) + generator = np.random.default_rng(seed) + estimates = [] + for _ in range(resamples): + sampled = generator.choice(keys, size=len(keys), replace=True) + values = [value for key in sampled for value in groups[str(key)]] + estimates.append(float(np.mean(values))) + return { + "groups": len(keys), "resamples": resamples, + "estimate": float(np.mean([value for values in groups.values() for value in values])), + "ci95_low": float(np.quantile(estimates, .025)), + "ci95_high": float(np.quantile(estimates, .975)), + } + + +def metric_fields() -> tuple[str, ...]: + return ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "source_root_relative_mpjpe_mm", + "rigid_se3_mpjpe_mm", "pa_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "direct_2d_error_px", + "projected_mano_2d_error_px", "direct_mano_consistency_px", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "translation_x_signed_mm", "translation_y_signed_mm", "translation_z_signed_mm", + ) + + +def ray_depth_diagnostic_row( + prediction: dict[str, torch.Tensor], batch: dict[str, Any], + batch_index: int, frame: int, side: int, translation_valid: bool, +) -> dict[str, float | bool]: + fields: dict[str, float | bool] = { + "ray_depth_confidence": math.nan, + "ray_depth_raw_delta_z_mm": math.nan, + "ray_depth_applied_delta_z_mm": math.nan, + "ray_depth_support_count": math.nan, + "ray_depth_local_valid_fraction": math.nan, + "ray_depth_correction_valid": False, + "ray_depth_base_z_error_mm": math.nan, + "ray_depth_final_z_error_mm": math.nan, + "ray_depth_harm_mm": math.nan, + } + if "ray_depth_confidence" not in prediction: + return fields + selector = (batch_index, frame, side) + support_count = int(prediction["ray_depth_support_count"][selector]) + fields.update({ + "ray_depth_confidence": float(prediction["ray_depth_confidence"][selector]), + "ray_depth_raw_delta_z_mm": float( + prediction["ray_depth_raw_delta_z_m"][selector] * 1000.0 + ), + "ray_depth_applied_delta_z_mm": float( + prediction["ray_depth_applied_delta_z_m"][selector] * 1000.0 + ), + "ray_depth_support_count": float(support_count), + "ray_depth_local_valid_fraction": support_count / 9.0, + "ray_depth_correction_valid": bool( + prediction["ray_depth_correction_valid"][selector] + ), + }) + if translation_valid: + target_z = batch["wrist_root_translation"][selector][2] + base_error = (prediction["ray_depth_base_z_m"][selector] - target_z).abs() * 1000.0 + final_error = ( + prediction["wrist_root_translation"][selector][2] - target_z + ).abs() * 1000.0 + fields.update({ + "ray_depth_base_z_error_mm": float(base_error), + "ray_depth_final_z_error_mm": float(final_error), + "ray_depth_harm_mm": float(final_error - base_error), + }) + return fields + + +def supervision_coverage(rows: list[dict[str, Any]]) -> dict[str, float | int]: + total = len(rows) + result: dict[str, float | int] = {"hand_rows": total} + for name, field in ( + ("joint3d", "joint3d_supervision"), + ("source_root_relative", "source_root_relative_supervision"), + ("translation", "translation_supervision"), + ("vertices", "vertices_supervision"), + ): + count = sum(bool(row.get(field, False)) for row in rows) + result[f"{name}_valid_hands"] = count + result[f"{name}_valid_fraction"] = count / total if total else 0.0 + return result + + +def make_row( + prediction: dict[str, torch.Tensor], batch: dict[str, Any], + batch_index: int, frame: int, side: int, +) -> dict[str, Any]: + side_name = ("left", "right")[side] + frame_valid = bool(batch["frame_valid"][batch_index, frame]) + translation_valid = frame_valid and bool(batch["translation_valid"][batch_index, frame, side]) + joint_mask = batch["joint3d_valid"][batch_index, frame, side].bool() & frame_valid + joint2d_mask = batch["joint2d_valid"][batch_index, frame, side].bool() & frame_valid + vertices_valid = frame_valid and bool(batch["vertices_valid"][batch_index, frame, side]) + source_relative_mask = torch.zeros_like(joint_mask) + if "joint3d_root_relative_valid" in batch: + source_relative_mask = ( + batch["joint3d_root_relative_valid"][batch_index, frame, side].bool() + & frame_valid + ) + row: dict[str, Any] = { + "dataset": str(batch["dataset_id"][batch_index]), + "subject_id": str(batch["subject_id"][batch_index]), + "physical_recording_id": str(batch["physical_recording_id"][batch_index]), + "camera_id": str(batch["camera_id"][batch_index]), + "headset_id": str(batch["headset_id"][batch_index]), + "frame_id": int(batch["frame_id"][batch_index, frame]), + "side": side_name, + "joint3d_supervision": bool(joint_mask.any()), + "source_root_relative_supervision": bool(source_relative_mask.any()), + "vertices_supervision": vertices_valid, + "translation_supervision": translation_valid, + } + row.update(ray_depth_diagnostic_row( + prediction, batch, batch_index, frame, side, translation_valid, + )) + for field in metric_fields(): + row[field] = math.nan + if translation_valid: + residual_mm = ( + prediction["wrist_root_translation"][batch_index, frame, side] + - batch["wrist_root_translation"][batch_index, frame, side] + ).float().cpu().numpy() * 1000.0 + for axis_index, axis in enumerate("xyz"): + row[f"translation_{axis}_signed_mm"] = float(residual_mm[axis_index]) + row[f"translation_{axis}_mae_mm"] = float(abs(residual_mm[axis_index])) + depth = float(batch["wrist_root_translation"][batch_index, frame, side, 2]) + row["wrist_depth_m"] = depth + row["depth_bucket"] = depth_bucket(depth) + else: + row["wrist_depth_m"] = math.nan + row["depth_bucket"] = "N/A" + if joint2d_mask.any(): + visible_joint_count = int(joint2d_mask.sum()) + row["visible_joint_count"] = visible_joint_count + row["occlusion_bucket"] = ( + "severe_le7" if visible_joint_count <= 7 + else ("partial_8_15" if visible_joint_count <= 15 else "visible_ge16") + ) + target_2d = batch["joint2d"][batch_index, frame, side].float() + height, width = batch["rgb"].shape[-2:] + direct = prediction["joint2d_norm"][batch_index, frame, side].float() * target_2d.new_tensor((width, height)) + predicted_3d = prediction["joints_camera"][batch_index, frame, side].float() + projected, positive = project_points( + predicted_3d, batch["K"][batch_index, frame].float(), + ) + valid_2d = joint2d_mask & torch.isfinite(target_2d).all(-1) + projected_valid = valid_2d & positive + row["direct_2d_error_px"] = float( + torch.linalg.vector_norm(direct - target_2d, dim=-1)[valid_2d].mean() + ) + if projected_valid.any(): + row["projected_mano_2d_error_px"] = float( + torch.linalg.vector_norm(projected - target_2d, dim=-1)[projected_valid].mean() + ) + row["direct_mano_consistency_px"] = float( + torch.linalg.vector_norm(direct - projected, dim=-1)[projected_valid].mean() + ) + valid_points = target_2d[valid_2d] + extent = valid_points.max(0).values - valid_points.min(0).values + size = float(extent.max()) + row["projected_hand_size_px"] = size + row["size_bucket"] = hand_size_bucket(size) + else: + row["visible_joint_count"] = 0 + row["occlusion_bucket"] = "unlabelled" + row["projected_hand_size_px"] = math.nan + row["size_bucket"] = "N/A" + if joint_mask.any(): + predicted_joints = prediction["joints_camera"][batch_index, frame, side].float() + target_joints = batch["joint3d_camera"][batch_index, frame, side].float() + errors = torch.linalg.vector_norm(predicted_joints - target_joints, dim=-1) * 1000.0 + row["absolute_mpjpe_mm"] = float(errors[joint_mask].mean()) + relative_prediction = predicted_joints - predicted_joints[:1] + relative_target = target_joints - target_joints[:1] + relative_error = torch.linalg.vector_norm(relative_prediction - relative_target, dim=-1) * 1000.0 + row["root_relative_mpjpe_mm"] = float(relative_error[joint_mask].mean()) + tips = torch.as_tensor(TIP_INDICES, device=joint_mask.device) + tip_mask = joint_mask[tips] + if tip_mask.any(): + row["fingertip_mpjpe_mm"] = float(errors[tips][tip_mask].mean()) + if bool(joint_mask.all()): + pred_np = predicted_joints.detach().cpu().numpy()[None] + target_np = target_joints.detach().cpu().numpy()[None] + row["rigid_se3_mpjpe_mm"] = float(aligned_mpjpe_mm( + pred_np, target_np, estimate_scale=False, + )[0]) + row["pa_mpjpe_mm"] = float(aligned_mpjpe_mm( + pred_np, target_np, estimate_scale=True, + )[0]) + if source_relative_mask.any(): + predicted_joints = prediction["joints_camera"][batch_index, frame, side].float() + predicted_relative = predicted_joints - predicted_joints[:1] + target_relative = batch["joint3d_root_relative"][batch_index, frame, side].float() + source_error = torch.linalg.vector_norm( + predicted_relative - target_relative, dim=-1, + ) * 1000.0 + row["source_root_relative_mpjpe_mm"] = float( + source_error[source_relative_mask].mean() + ) + if vertices_valid: + vertex_error = torch.linalg.vector_norm( + prediction["vertices_camera"][batch_index, frame, side].float() + - batch["vertices_camera"][batch_index, frame, side].float(), dim=-1, + ) * 1000.0 + row["mpvpe_mm"] = float(vertex_error.mean()) + return row + + +def aggregate(rows: list[dict[str, Any]]) -> dict[str, Any]: + result = {field: finite_summary([row[field] for row in rows]) for field in metric_fields()} + result["supervision_coverage"] = { + "overall": supervision_coverage(rows), + "left": supervision_coverage([row for row in rows if row["side"] == "left"]), + "right": supervision_coverage([row for row in rows if row["side"] == "right"]), + } + for split_name, selector in { + "left": lambda row: row["side"] == "left", + "right": lambda row: row["side"] == "right", + "near": lambda row: row["depth_bucket"] == "near_le0.8m", + "far": lambda row: row["depth_bucket"] == "far_gt0.8m", + "small": lambda row: row["size_bucket"] == "small_lt64", + "medium": lambda row: row["size_bucket"] == "medium_64_128", + "large": lambda row: row["size_bucket"] == "large_ge128", + }.items(): + selected = [row for row in rows if selector(row)] + result[f"bucket_{split_name}"] = { + "hands": len(selected), + "supervision_coverage": supervision_coverage(selected), + "absolute_mpjpe_mm": finite_summary([row["absolute_mpjpe_mm"] for row in selected]), + "translation_z_mae_mm": finite_summary([row["translation_z_mae_mm"] for row in selected]), + "fingertip_mpjpe_mm": finite_summary([row["fingertip_mpjpe_mm"] for row in selected]), + } + for field, prefix in (("headset_id", "headset"), ("occlusion_bucket", "occlusion")): + for value in sorted({str(row[field]) for row in rows}): + selected = [row for row in rows if str(row[field]) == value] + normalized = "".join(character.lower() if character.isalnum() else "_" for character in value) + result[f"bucket_{prefix}_{normalized}"] = { + "hands": len(selected), + "supervision_coverage": supervision_coverage(selected), + "absolute_mpjpe_mm": finite_summary([ + row["absolute_mpjpe_mm"] for row in selected + ]), + "root_relative_mpjpe_mm": finite_summary([ + row["root_relative_mpjpe_mm"] for row in selected + ]), + "translation_z_mae_mm": finite_summary([ + row["translation_z_mae_mm"] for row in selected + ]), + "fingertip_mpjpe_mm": finite_summary([ + row["fingertip_mpjpe_mm"] for row in selected + ]), + } + ray_rows = [row for row in rows if math.isfinite(float(row["ray_depth_confidence"]))] + result["ray_depth_diagnostics"] = None + if ray_rows: + correction_rows = [row for row in ray_rows if row["ray_depth_correction_valid"]] + result["ray_depth_diagnostics"] = { + "hands": len(ray_rows), + "correction_valid_hands": len(correction_rows), + "correction_valid_fraction": len(correction_rows) / len(ray_rows), + "confidence": finite_summary([row["ray_depth_confidence"] for row in ray_rows]), + "raw_delta_z_mm": finite_summary([row["ray_depth_raw_delta_z_mm"] for row in ray_rows]), + "applied_delta_z_mm": finite_summary([row["ray_depth_applied_delta_z_mm"] for row in ray_rows]), + "support_count": finite_summary([row["ray_depth_support_count"] for row in ray_rows]), + "local_valid_fraction": finite_summary([ + row["ray_depth_local_valid_fraction"] for row in ray_rows + ]), + "base_z_error_mm": finite_summary([row["ray_depth_base_z_error_mm"] for row in ray_rows]), + "final_z_error_mm": finite_summary([row["ray_depth_final_z_error_mm"] for row in ray_rows]), + "harm_mm": finite_summary([row["ray_depth_harm_mm"] for row in correction_rows]), + "harm_fraction": ( + float(np.mean([row["ray_depth_harm_mm"] > 0 for row in correction_rows])) + if correction_rows else None + ), + } + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--expected-cache-manifest-sha256") + parser.add_argument("--input-mode", choices=("rgb_d_k", "rgb_k", "rgb_only"), required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument( + "--allow-physical-gpus-4-5", action="store_true", + help="Explicit resource override; default preserves the historical GPU0-3 contract.", + ) + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--evaluation-id") + parser.add_argument("--heartbeat-path", type=Path) + parser.add_argument("--heartbeat-seconds", type=float, default=30.0) + parser.add_argument( + "--evaluation-role", + choices=( + "external_heldout", "h2o_train_group_heldout", + "h2o_train_group_heldout_control", "adaptation_external_heldout", + "phase9_external_heldout", "phase9_h2o_fold_heldout", + ), + default="external_heldout", + ) + args = parser.parse_args() + if args.heartbeat_seconds < 1: + parser.error("heartbeat interval must be at least one second") + if (args.heartbeat_path is None) != (args.evaluation_id is None): + parser.error("evaluation ID and heartbeat path must be provided together") + if sha256(args.checkpoint) != args.expected_checkpoint_sha256: + parser.error("checkpoint SHA256 differs from frozen expected value") + if ( + args.expected_cache_manifest_sha256 is not None + and sha256(args.cache_manifest) != args.expected_cache_manifest_sha256 + ): + parser.error("cache manifest SHA256 differs from frozen expected value") + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + allowed_physical_gpus = {0, 1, 2, 3} + if args.allow_physical_gpus_4_5: + allowed_physical_gpus.update((4, 5)) + if args.physical_gpu_id not in allowed_physical_gpus: + parser.error("physical GPU must be one of 0-3; GPU4-5 are reserved") + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + heartbeat_path = args.heartbeat_path + if heartbeat_path is not None: + if heartbeat_path.resolve().parent != args.output_dir.resolve(): + parser.error("evaluation heartbeat must be inside the output directory") + write_progress_heartbeat(heartbeat_path, { + "status": "initializing", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "processed_clips": 0, "processed_frames": 0, + "dataloader_worker_pids": [], + }) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + dataset = CachedUnifiedClipDataset(args.cache_manifest, K_input_dropout=0.0) + write_progress_heartbeat(heartbeat_path, { + "status": "data_ready", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": 0, + "processed_frames": 0, "dataloader_worker_pids": [], + }) + loader = DataLoader( + dataset, batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).cuda().eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location="cuda") + validate_evaluation_role( + args.evaluation_role, config, + {str(row["dataset_id"]).upper() for row in dataset.rows}, + state["extra"], args.cache_manifest, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + rows: list[dict[str, Any]] = [] + raw: dict[str, list[np.ndarray]] = {} + started = time.perf_counter() + last_heartbeat = started + processed_clips = 0 + processed_frames = 0 + torch.cuda.reset_peak_memory_stats() + with torch.inference_mode(): + for batch in loader: + processed_clips += len(batch["dataset_id"]) + apply_input_mode(batch, args.input_mode) + batch = move_to_device(batch, torch.device("cuda")) + if args.evaluation_role in { + "h2o_train_group_heldout", "h2o_train_group_heldout_control", + "phase9_h2o_fold_heldout", + }: + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + processed_frames += int(batch["frame_valid"].sum()) + now = time.perf_counter() + if now - last_heartbeat >= args.heartbeat_seconds: + write_progress_heartbeat(heartbeat_path, { + "status": "running", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), + "processed_clips": processed_clips, + "processed_frames": processed_frames, + "dataloader_worker_pids": direct_child_pids(os.getpid()), + }) + last_heartbeat = now + persisted = { + "predicted_joints_camera": prediction["joints_camera"], + "predicted_vertices_camera": prediction["vertices_camera"], + "predicted_wrist_root_translation": prediction["wrist_root_translation"], + "predicted_joint2d_norm": prediction["joint2d_norm"], + "predicted_mano_rotation_matrices": prediction["mano_rotation_matrices"], + "predicted_mano_shape": prediction["mano_shape"], + "target_mano_pose": batch["mano_pose"], + "mano_pose_valid": batch["mano_pose_valid"], + "target_joints_camera": batch["joint3d_camera"], + "target_vertices_camera": batch["vertices_camera"], + "target_wrist_root_translation": batch["wrist_root_translation"], + "target_joint2d": batch["joint2d"], + "joint3d_valid": batch["joint3d_valid"], + "vertices_valid": batch["vertices_valid"], + "translation_valid": batch["translation_valid"], + "joint2d_valid": batch["joint2d_valid"], + "frame_valid": batch["frame_valid"], + "K": batch["K"], + "frame_id": batch["frame_id"], + } + if "joint3d_root_relative" in batch: + persisted.update({ + "target_joint3d_root_relative": batch["joint3d_root_relative"], + "joint3d_root_relative_valid": batch["joint3d_root_relative_valid"], + }) + for key in ( + "ray_depth_wrist2d_norm", "ray_depth_log_base_z", + "ray_depth_base_z_m", "ray_depth_raw_delta_z_m", + "ray_depth_applied_delta_z_m", "ray_depth_confidence_logit", + "ray_depth_confidence", "ray_depth_local_statistics", + "ray_depth_support_count", "ray_depth_correction_valid", + "ray_depth_K_input_available", + ): + if key in prediction: + persisted[key] = prediction[key] + append_valid_frame_arrays(raw, persisted, batch["frame_valid"]) + batch_size, time_count = batch["frame_valid"].shape + for batch_index in range(batch_size): + for frame in range(time_count): + if not bool(batch["frame_valid"][batch_index, frame]): + continue + for side in range(2): + rows.append(make_row(prediction, batch, batch_index, frame, side)) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + write_progress_heartbeat(heartbeat_path, { + "status": "finalizing", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": processed_clips, + "processed_frames": processed_frames, + "dataloader_worker_pids": direct_child_pids(os.getpid()), + }) + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed(raw_path, **{ + key: np.concatenate(values, axis=0) for key, values in raw.items() + }) + row_path = args.output_dir / "per_hand_frame_metrics.csv" + with row_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + take_rows = [] + for take in sorted({str(row["physical_recording_id"]) for row in rows}): + selected = [row for row in rows if row["physical_recording_id"] == take] + record: dict[str, Any] = {"physical_recording_id": take, "hands": len(selected)} + for field in metric_fields(): + summary = finite_summary([row[field] for row in selected]) + record[field] = summary["mean"] if summary is not None else math.nan + take_rows.append(record) + take_path = args.output_dir / "take_metrics.csv" + with take_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(take_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(take_rows) + bootstrap = { + field: grouped_bootstrap(rows, field, int(config["seed"]), args.bootstrap_resamples) + for field in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "source_root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + report = { + "status": { + "external_heldout": "evaluated", + "h2o_train_group_heldout": "evaluated_h2o_train_group_heldout", + "h2o_train_group_heldout_control": "evaluated_h2o_train_group_heldout_control", + "adaptation_external_heldout": "evaluated_adaptation_external_heldout", + "phase9_external_heldout": "evaluated_phase9_external_heldout", + "phase9_h2o_fold_heldout": "evaluated_phase9_h2o_fold_heldout", + }[args.evaluation_role], + "evaluation_role": args.evaluation_role, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "experiment": config["name"], "checkpoint_step": int(state["step"]), + "checkpoint": {"path": str(args.checkpoint.resolve()), "sha256": args.expected_checkpoint_sha256}, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "cache_manifest": {"path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest)}, + "input_mode": args.input_mode, "clips": len(dataset), "frames": processed_frames, + "hands_rows": len(rows), "metrics": aggregate(rows), "grouped_bootstrap_ci": bootstrap, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": processed_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + }, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "raw_prediction_layout": "axis0 is the ordered sequence of frame_valid=true frames", + "per_hand_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "take_metrics": {"path": str(take_path.resolve()), "sha256": sha256(take_path)}, + "official_test_used": False, + "h2o_training_data_used": checkpoint_h2o_training_data_used(state["extra"]), + "h2o_official_validation_used": False, + "oracle_information_used": False, + "metric_definitions": { + "rigid_se3_mpjpe_mm": "per-hand Kabsch; removes translation and rotation", + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation and scale", + }, + } + output = args.output_dir / "evaluation.json" + output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + write_progress_heartbeat(heartbeat_path, { + "status": "complete", "evaluation_id": args.evaluation_id, + "output_dir": str(args.output_dir.resolve()), + "total_clips": len(dataset), "processed_clips": processed_clips, + "processed_frames": processed_frames, + "evaluation_report": str(output.resolve()), + "evaluation_report_sha256": sha256(output), + "dataloader_worker_pids": [], + }) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase7_h2o_zero_shot.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase7_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..dde27a07128671619a11c73262c329644068bc26 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase7_h2o_zero_shot.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Strict one-shot H2O validation evaluation of a frozen external generalist.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint +from scripts.evaluate_phase7_external import ( + aggregate, + apply_input_mode, + finite_summary, + grouped_bootstrap, + make_row, + metric_fields, + sha256, + tensor_to_numpy, +) +from scripts.train_experiment import attach_gt_vertices, move_to_device +from scripts.train_phase7_external import assert_physical_gpu_idle + + +INPUT_MODES = ("rgb_d_k", "rgb_k", "rgb_only") +EVALUATION_ROLES = ( + "strict_external_zero_shot", "h2o_adapted_formal", + "phase9_unified_formal", +) + + +def validate_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + status = record.get("status") + if status not in { + "external_generalist_frozen", "external_architecture_candidate_frozen", + }: + raise ValueError("external checkpoint is not frozen") + if status == "external_architecture_candidate_frozen" and ( + record.get("selected_within_family") is not True + or record.get("overall_external_generalist_winner") is not False + ): + raise ValueError("external architecture candidate role is ambiguous") + if record.get("checkpoint_sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen external generalist") + if record.get("official_test_used") is not False: + raise ValueError("freeze record must explicitly exclude official test") + if record.get("h2o_official_validation_used_for_external_selection") is not False: + raise ValueError("external selection must precede H2O validation access") + if not record.get("external_selection_sha256"): + raise ValueError("freeze record lacks external selection SHA256") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from freeze record") + + +def validate_adaptation_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + if record.get("status") != "h2o_adaptation_candidate_frozen": + raise ValueError("H2O adaptation candidate is not frozen") + checkpoint = record.get("checkpoint", {}) + if checkpoint.get("sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen adaptation candidate") + if record.get("h2o_official_validation_used_for_selection") is not False: + raise ValueError("adaptation selection must use H2O train-heldout only") + if record.get("official_test_used") is not False: + raise ValueError("adaptation freeze record must explicitly exclude official test") + if not record.get("adaptation_selection_sha256"): + raise ValueError("adaptation freeze record lacks selection SHA256") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from adaptation freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from adaptation freeze record") + + +def validate_phase9_freeze_record( + record: dict[str, Any], checkpoint_sha256: str, + validation_manifest: Path, input_mode: str, +) -> None: + if record.get("status") != "phase9_final_unified_checkpoint_frozen": + raise ValueError("Phase 9 final unified checkpoint is not frozen") + if record.get("checkpoint", {}).get("sha256") != checkpoint_sha256: + raise ValueError("checkpoint differs from frozen Phase 9 final checkpoint") + if ( + record.get("selection_complete") is not True + or record.get("stage9_final_decision_complete") is not True + or record.get("h2o_official_validation_used_for_selection") is not False + or record.get("official_test_used") is not False + or not record.get("selection_chain_sha256") + ): + raise ValueError("Phase 9 final selection provenance is incomplete") + if input_mode not in record.get("frozen_h2o_input_modes", []): + raise ValueError(f"input mode was not frozen: {input_mode}") + manifest_record = record.get("h2o_validation_manifest", {}) + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only the canonical H2O official validation manifest is allowed") + if Path(manifest_record.get("path", "")).resolve() != validation_manifest.resolve(): + raise ValueError("H2O validation manifest path differs from Phase 9 freeze record") + if manifest_record.get("sha256") != sha256(validation_manifest): + raise ValueError("H2O validation manifest SHA256 differs from Phase 9 freeze record") + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"cannot write empty metric rows: {path}") + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(rows) + + +def append_valid_frame_arrays( + raw: dict[str, list[np.ndarray]], values: dict[str, torch.Tensor], + frame_valid: torch.Tensor, +) -> None: + """Persist variable-length clips as one contiguous valid-frame axis.""" + + valid = tensor_to_numpy(frame_valid.bool()).reshape(-1) + batch, time = frame_valid.shape + for key, value in values.items(): + array = tensor_to_numpy(value) + if array.shape[:2] != (batch, time): + raise ValueError(f"raw temporal field shape differs from frame_valid: {key}") + flattened = array.reshape(batch * time, *array.shape[2:]) + raw.setdefault(key, []).append(flattened[valid]) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--freeze-record", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--input-mode", choices=INPUT_MODES, required=True) + parser.add_argument( + "--evaluation-role", choices=EVALUATION_ROLES, + default="strict_external_zero_shot", + ) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument("--clip-length", type=int, default=8) + parser.add_argument("--frame-stride", type=int, default=1) + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.physical_gpu_id not in {0, 1, 2, 3}: + parser.error("physical GPU must be one of 0-3; GPU4-5 are reserved") + import os + if os.environ.get("CUDA_VISIBLE_DEVICES") != str(args.physical_gpu_id): + parser.error("CUDA_VISIBLE_DEVICES must equal --physical-gpu-id") + if sha256(args.checkpoint) != args.expected_checkpoint_sha256: + parser.error("checkpoint SHA256 differs from frozen expected value") + freeze_record = json.loads(args.freeze_record.read_text(encoding="utf-8")) + if args.evaluation_role == "strict_external_zero_shot": + validate_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + elif args.evaluation_role == "h2o_adapted_formal": + validate_adaptation_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + else: + validate_phase9_freeze_record( + freeze_record, args.expected_checkpoint_sha256, args.manifest, args.input_mode, + ) + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + expected_branch = { + "strict_external_zero_shot": "external_only", + "h2o_adapted_formal": "h2o_adaptation", + "phase9_unified_formal": "phase9_unified", + }[args.evaluation_role] + if config.get("experiment", {}).get("branch") != expected_branch: + raise ValueError(f"checkpoint config branch is not {expected_branch}") + dataset = H2OCam4Dataset( + args.root, args.manifest, + target_hw=tuple(config["data"]["resolution_hw"]), + clip_lengths=(args.clip_length,), strides=(args.frame_stride,), + ) + loader = DataLoader( + dataset, batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + )).cuda().eval() + state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location="cuda") + expected_h2o_training = args.evaluation_role != "strict_external_zero_shot" + if state["extra"].get("h2o_training_data_used") is not expected_h2o_training: + raise ValueError("checkpoint H2O-training provenance differs from evaluation role") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + rows: list[dict[str, Any]] = [] + raw: dict[str, list[np.ndarray]] = {} + processed_frames = 0 + started = time.perf_counter() + torch.cuda.reset_peak_memory_stats() + with torch.inference_mode(): + for batch in loader: + apply_input_mode(batch, args.input_mode) + batch = move_to_device(batch, torch.device("cuda")) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + processed_frames += int(batch["frame_valid"].sum()) + persisted = { + "predicted_joints_camera": prediction["joints_camera"], + "predicted_vertices_camera": prediction["vertices_camera"], + "predicted_wrist_root_translation": prediction["wrist_root_translation"], + "predicted_joint2d_norm": prediction["joint2d_norm"], + "predicted_mano_rotation_matrices": prediction["mano_rotation_matrices"], + "predicted_mano_shape": prediction["mano_shape"], + "target_joints_camera": batch["joint3d_camera"], + "target_vertices_camera": batch["vertices_camera"], + "target_wrist_root_translation": batch["wrist_root_translation"], + "target_joint2d": batch["joint2d"], + "joint3d_valid": batch["joint3d_valid"], + "vertices_valid": batch["vertices_valid"], + "translation_valid": batch["translation_valid"], + "joint2d_valid": batch["joint2d_valid"], + "frame_valid": batch["frame_valid"], + "K": batch["K"], + "frame_id": batch["frame_id"], + } + append_valid_frame_arrays(raw, persisted, batch["frame_valid"]) + batch_size, time_count = batch["frame_valid"].shape + for batch_index in range(batch_size): + for frame in range(time_count): + if not bool(batch["frame_valid"][batch_index, frame]): + continue + for side in range(2): + rows.append(make_row(prediction, batch, batch_index, frame, side)) + torch.cuda.synchronize() + elapsed = time.perf_counter() - started + + raw_path = args.output_dir / "raw_predictions.npz" + np.savez_compressed(raw_path, **{ + key: np.concatenate(values, axis=0) for key, values in raw.items() + }) + row_path = args.output_dir / "per_hand_frame_metrics.csv" + write_csv(row_path, rows) + take_rows = [] + for take in sorted({str(row["physical_recording_id"]) for row in rows}): + selected = [row for row in rows if row["physical_recording_id"] == take] + record: dict[str, Any] = {"physical_recording_id": take, "hands": len(selected)} + for field in metric_fields(): + summary = finite_summary([row[field] for row in selected]) + record[field] = summary["mean"] if summary is not None else math.nan + take_rows.append(record) + take_path = args.output_dir / "take_metrics.csv" + write_csv(take_path, take_rows) + bootstrap = { + field: grouped_bootstrap( + rows, field, int(config["seed"]), args.bootstrap_resamples, + ) + for field in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "mpvpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + report = { + "status": { + "strict_external_zero_shot": "evaluated_strict_h2o_zero_shot", + "h2o_adapted_formal": "evaluated_h2o_adapted_formal", + "phase9_unified_formal": "evaluated_phase9_unified_formal", + }[args.evaluation_role], + "evaluation_role": args.evaluation_role, + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "experiment": config["name"], "checkpoint_step": int(state["step"]), + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": args.expected_checkpoint_sha256, + }, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "freeze_record": { + "path": str(args.freeze_record.resolve()), "sha256": sha256(args.freeze_record), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "input_mode": args.input_mode, "clips": len(dataset), "frames": processed_frames, + "hands_rows": len(rows), "metrics": aggregate(rows), + "grouped_bootstrap_ci": bootstrap, + "runtime": { + "wall_seconds": elapsed, "frames_per_second": processed_frames / elapsed, + "peak_vram_gib": torch.cuda.max_memory_allocated() / 2**30, + "physical_gpu_id": args.physical_gpu_id, + }, + "raw_predictions": {"path": str(raw_path.resolve()), "sha256": sha256(raw_path)}, + "raw_prediction_layout": "axis0 is the ordered sequence of frame_valid=true frames", + "per_hand_rows": {"path": str(row_path.resolve()), "sha256": sha256(row_path)}, + "take_metrics": {"path": str(take_path.resolve()), "sha256": sha256(take_path)}, + "h2o_training_data_used": expected_h2o_training, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + "oracle_information_used": False, + "metric_definitions": { + "rigid_se3_mpjpe_mm": "per-hand Kabsch; removes translation and rotation", + "pa_mpjpe_mm": "per-hand Sim(3) Umeyama; removes translation, rotation and scale", + }, + } + output = args.output_dir / "evaluation.json" + output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase8_translation_oracles.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase8_translation_oracles.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3f03e6d4363d51d6d533cf00426e064d9d61b4 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_phase8_translation_oracles.py @@ -0,0 +1,355 @@ +#!/usr/bin/env python3 +"""Evaluation-only ray/z/root-relative decomposition from persisted predictions.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + + +CONDITIONS = ( + "raw", + "predicted_pose_shape_gt_translation", + "predicted_ray_gt_z", + "gt_ray_predicted_z", + "predicted_root_relative_gt_translation", + "predicted_translation_gt_root_relative", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def flatten_leading(array: np.ndarray, trailing_dimensions: int) -> np.ndarray: + trailing = array.shape[-trailing_dimensions:] + return array.reshape(-1, *trailing) + + +def axis_angle_to_matrix(axis_angle: np.ndarray) -> np.ndarray: + angle = np.linalg.norm(axis_angle, axis=-1) + safe = np.maximum(angle, 1e-12) + axis = axis_angle / safe[..., None] + x, y, z = np.moveaxis(axis, -1, 0) + zero = np.zeros_like(x) + skew = np.stack(( + zero, -z, y, z, zero, -x, -y, x, zero, + ), axis=-1).reshape(*axis.shape[:-1], 3, 3) + identity = np.broadcast_to(np.eye(3), skew.shape) + matrix = ( + identity + np.sin(angle)[..., None, None] * skew + + (1.0 - np.cos(angle))[..., None, None] * (skew @ skew) + ) + return np.where((angle < 1e-12)[..., None, None], identity, matrix) + + +def decompose(arrays: dict[str, np.ndarray]) -> dict[str, Any]: + pred_joints = flatten_leading(arrays["predicted_joints_camera"], 3) + target_joints = flatten_leading(arrays["target_joints_camera"], 3) + pred_translation = flatten_leading( + arrays["predicted_wrist_root_translation"], 2, + ) + target_translation = flatten_leading( + arrays["target_wrist_root_translation"], 2, + ) + joint_valid = flatten_leading(arrays["joint3d_valid"], 2).astype(bool) + translation_valid = flatten_leading( + arrays["translation_valid"], 1, + ).astype(bool) + if not ( + pred_joints.shape[:2] == target_joints.shape[:2] + == pred_translation.shape[:2] == target_translation.shape[:2] + == joint_valid.shape[:2] + ): + raise ValueError("raw prediction arrays do not share frame/hand axes") + pred_relative = pred_joints - pred_joints[..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + pred_z = pred_translation[..., 2] + target_z = target_translation[..., 2] + safe_pred_z = np.where(np.abs(pred_z) > 1e-6, pred_z, np.nan) + safe_target_z = np.where(np.abs(target_z) > 1e-6, target_z, np.nan) + pred_ray = pred_translation[..., :2] / safe_pred_z[..., None] + target_ray = target_translation[..., :2] / safe_target_z[..., None] + pred_ray_gt_z_translation = np.concatenate( + (pred_ray * target_z[..., None], target_z[..., None]), axis=-1, + ) + gt_ray_pred_z_translation = np.concatenate( + (target_ray * pred_z[..., None], pred_z[..., None]), axis=-1, + ) + condition_joints = { + "raw": pred_joints, + "predicted_pose_shape_gt_translation": ( + pred_relative + target_translation[..., None, :] + ), + "predicted_ray_gt_z": ( + pred_relative + pred_ray_gt_z_translation[..., None, :] + ), + "gt_ray_predicted_z": ( + pred_relative + gt_ray_pred_z_translation[..., None, :] + ), + "predicted_root_relative_gt_translation": ( + pred_relative + target_translation[..., None, :] + ), + "predicted_translation_gt_root_relative": ( + target_relative + pred_translation[..., None, :] + ), + } + condition_errors: dict[str, np.ndarray] = {} + annotation_valid = joint_valid.any(axis=-1) & translation_valid + positive_depth = ( + np.isfinite(pred_z) & np.isfinite(target_z) + & (pred_z > 0.05) & (target_z > 0.05) + ) + hand_valid = annotation_valid & positive_depth + for name, joints in condition_joints.items(): + joint_error = np.linalg.norm(joints - target_joints, axis=-1) * 1000.0 + numerator = np.where(joint_valid, joint_error, 0.0).sum(axis=-1) + denominator = joint_valid.sum(axis=-1) + error = numerator / np.maximum(denominator, 1) + condition_errors[name] = np.where(hand_valid, error, np.nan) + translation_residual = (pred_translation - target_translation) * 1000.0 + ray_residual = pred_ray - target_ray + result = { + "condition_errors_mm": condition_errors, + "translation_residual_mm": translation_residual, + "ray_residual": ray_residual, + "predicted_z_m": pred_z, + "target_z_m": target_z, + "valid": hand_valid, + "annotation_valid": annotation_valid, + "positive_depth": positive_depth, + } + if "K" in arrays: + K = flatten_leading(arrays["K"], 2) + if K.shape[0] != hand_valid.shape[0]: + raise ValueError("K frame axis differs from prediction frame axis") + result["K"] = np.broadcast_to(K[:, None], (*hand_valid.shape, 3, 3)) + if {"predicted_mano_rotation_matrices", "target_mano_pose", "mano_pose_valid"}.issubset(arrays): + predicted_rotation = flatten_leading( + arrays["predicted_mano_rotation_matrices"], 4, + )[..., 0, :, :] + target_pose = flatten_leading(arrays["target_mano_pose"], 2) + pose_valid = flatten_leading(arrays["mano_pose_valid"], 1).astype(bool) + target_rotation = axis_angle_to_matrix(target_pose[..., :3]) + relative = predicted_rotation @ np.swapaxes(target_rotation, -1, -2) + cosine = np.clip( + (np.trace(relative, axis1=-2, axis2=-1) - 1.0) / 2.0, + -1.0, 1.0, + ) + result["global_orientation_geodesic_deg"] = np.degrees(np.arccos(cosine)) + result["global_orientation_valid"] = pose_valid + return result + + +def finite_summary(values: np.ndarray) -> dict[str, float | int] | None: + values = np.asarray(values, dtype=np.float64) + values = values[np.isfinite(values)] + if not values.size: + return None + return { + "count": int(values.size), "mean": float(values.mean()), + "median": float(np.median(values)), + "p95": float(np.quantile(values, 0.95)), + } + + +def correlation(x: np.ndarray, y: np.ndarray, valid: np.ndarray) -> float | None: + mask = valid & np.isfinite(x) & np.isfinite(y) + if mask.sum() < 2 or np.std(x[mask]) == 0 or np.std(y[mask]) == 0: + return None + return float(np.corrcoef(x[mask], y[mask])[0, 1]) + + +def build_report(result: dict[str, Any]) -> dict[str, Any]: + errors = result["condition_errors_mm"] + raw_mean = float(np.nanmean(errors["raw"])) + conditions = {} + for name in CONDITIONS: + summary = finite_summary(errors[name]) + if summary is None: + conditions[name] = None + continue + gain = raw_mean - float(summary["mean"]) + conditions[name] = { + **summary, "gain_vs_raw_mm": gain, + "gain_vs_raw_percent": 100.0 * gain / raw_mean, + } + fix_z_gain = raw_mean - float(np.nanmean(errors["predicted_ray_gt_z"])) + fix_ray_gain = raw_mean - float(np.nanmean(errors["gt_ray_predicted_z"])) + fix_translation_gain = raw_mean - float(np.nanmean( + errors["predicted_root_relative_gt_translation"], + )) + interaction = fix_translation_gain - fix_z_gain - fix_ray_gain + residual = result["translation_residual_mm"] + valid = result["valid"] + axis = { + name: { + "signed_mm": finite_summary(residual[..., index][valid]), + "absolute_mm": finite_summary(np.abs(residual[..., index][valid])), + } + for index, name in enumerate("xyz") + } + axis["correlation"] = { + "x_y": correlation(residual[..., 0], residual[..., 1], valid), + "x_z": correlation(residual[..., 0], residual[..., 2], valid), + "y_z": correlation(residual[..., 1], residual[..., 2], valid), + } + orientation = result.get("global_orientation_geodesic_deg") + orientation_valid = result.get("global_orientation_valid") + return { + "status": "evaluated_oracle_diagnostic_only", + "deployable_claim": False, + "selection_use": False, + "official_test_used": False, + "validity_audit": { + "annotation_valid_hands": int(result["annotation_valid"].sum()), + "positive_depth_hands": int(result["valid"].sum()), + "excluded_nonpositive_or_near_depth": int( + (result["annotation_valid"] & ~result["positive_depth"]).sum() + ), + "minimum_ray_depth_m": 0.05, + }, + "conditions": conditions, + "translation_attribution": { + "fix_z_gain_mm": fix_z_gain, + "fix_ray_gain_mm": fix_ray_gain, + "fix_all_translation_gain_mm": fix_translation_gain, + "nonadditive_interaction_mm": interaction, + "note": "Counterfactual gains are not assumed additive; interaction is reported explicitly.", + }, + "translation_axis_error": axis, + "ray_residual_norm": finite_summary( + np.linalg.norm(result["ray_residual"], axis=-1)[valid], + ), + "global_orientation_geodesic_deg": ( + finite_summary(orientation[orientation_valid]) + if orientation is not None and orientation_valid is not None else None + ), + } + + +def bucket_report(result: dict[str, Any], rows: list[dict[str, Any]]) -> dict[str, Any]: + shape = result["valid"].shape + flat_rows = np.asarray(rows, dtype=object).reshape(shape) + target_z = result["target_z_m"] + selectors: dict[str, np.ndarray] = { + "side_left": np.vectorize(lambda row: row.get("side") == "left")(flat_rows), + "side_right": np.vectorize(lambda row: row.get("side") == "right")(flat_rows), + "depth_near_le0.5m": target_z <= 0.5, + "depth_mid_0.5_0.8m": (target_z > 0.5) & (target_z <= 0.8), + "depth_far_gt0.8m": target_z > 0.8, + } + for size in ("small_lt64", "medium_64_128", "large_ge128"): + selectors[f"size_{size}"] = np.vectorize( + lambda row, expected=size: row.get("size_bucket") == expected, + )(flat_rows) + K = result.get("K") + if K is not None: + focal = np.sqrt(K[..., 0, 0] * K[..., 1, 1]) + finite = focal[result["valid"] & np.isfinite(focal)] + if finite.size: + low, high = np.quantile(finite, (1.0 / 3.0, 2.0 / 3.0)) + selectors["focal_low"] = focal <= low + selectors["focal_mid"] = (focal > low) & (focal <= high) + selectors["focal_high"] = focal > high + errors = result["condition_errors_mm"] + output: dict[str, Any] = {} + for name, selector in selectors.items(): + mask = result["valid"] & selector + raw = finite_summary(errors["raw"][mask]) + if raw is None: + output[name] = None + continue + raw_mean = float(raw["mean"]) + output[name] = { + "raw_absolute_mpjpe_mm": raw, + "fix_z_gain_mm": raw_mean - float(np.nanmean(errors["predicted_ray_gt_z"][mask])), + "fix_ray_gain_mm": raw_mean - float(np.nanmean(errors["gt_ray_predicted_z"][mask])), + "fix_translation_gain_mm": raw_mean - float(np.nanmean( + errors["predicted_root_relative_gt_translation"][mask], + )), + } + output["occlusion"] = { + "status": "N/A" if not any("occlusion_bucket" in row for row in rows) else "available", + "reason": "Phase 7 per-hand rows do not persist a common occlusion bucket", + } + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--raw-predictions", type=Path, required=True) + parser.add_argument("--per-hand-rows", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + args.output_dir.mkdir(parents=True, exist_ok=True) + with np.load(args.raw_predictions) as loaded: + result = decompose({key: loaded[key] for key in loaded.files}) + rows = list(csv.DictReader(args.per_hand_rows.open(encoding="utf-8"))) + flat_count = result["valid"].size + if len(rows) != flat_count: + raise ValueError( + f"per-hand rows ({len(rows)}) differ from raw frame-hand count ({flat_count})" + ) + errors = result["condition_errors_mm"] + output_rows = [] + for index, row in enumerate(rows): + record = { + key: row.get(key, "") for key in ( + "dataset", "subject_id", "physical_recording_id", "camera_id", + "frame_id", "side", "depth_bucket", "size_bucket", + ) + } + flat_index = np.unravel_index(index, result["valid"].shape) + for condition in CONDITIONS: + record[f"{condition}_absolute_mpjpe_mm"] = float( + errors[condition][flat_index] + ) + for axis_index, axis in enumerate("xyz"): + record[f"translation_{axis}_signed_mm"] = float( + result["translation_residual_mm"][flat_index][axis_index] + ) + record["target_wrist_depth_m"] = float(result["target_z_m"][flat_index]) + record["predicted_wrist_depth_m"] = float(result["predicted_z_m"][flat_index]) + record["ray_residual_norm"] = float(np.linalg.norm(result["ray_residual"][flat_index])) + if "K" in result: + record["fx_px"] = float(result["K"][flat_index][0, 0]) + record["fy_px"] = float(result["K"][flat_index][1, 1]) + output_rows.append(record) + csv_path = args.output_dir / "per_hand_oracle_decomposition.csv" + with csv_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(output_rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(output_rows) + report = build_report(result) + report["buckets"] = bucket_report(result, rows) + report.update({ + "raw_predictions": { + "path": str(args.raw_predictions.resolve()), + "sha256": sha256(args.raw_predictions), + }, + "per_hand_input": { + "path": str(args.per_hand_rows.resolve()), + "sha256": sha256(args.per_hand_rows), + }, + "per_hand_output": {"path": str(csv_path.resolve()), "sha256": sha256(csv_path)}, + }) + path = args.output_dir / "oracle_decomposition.json" + path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_sota_bundle.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_sota_bundle.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a226aebdf5591829184aa3e54525238a05d83a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_sota_bundle.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Evaluate one standardized external-model prediction bundle on H2O.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + evaluate_prediction_bundle, + write_csv_rows, +) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--prediction", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument( + "--pixel-scale", + type=float, + default=0.5, + help="Map raw H2O pixels to the Phase 3 640x368 evaluation scale.", + ) + parser.add_argument("--temporal-clip-length", type=int, default=8) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + prediction = PredictionBundle.load(args.prediction) + ground_truth = GroundTruthBundle.load(args.ground_truth) + report, frame_rows, temporal_rows = evaluate_prediction_bundle( + prediction, + ground_truth, + bootstrap_seed=args.bootstrap_seed, + bootstrap_samples=args.bootstrap_samples, + pixel_scale=args.pixel_scale, + temporal_clip_length=args.temporal_clip_length, + ) + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + write_csv_rows(args.output_dir / "per_hand_frame_metrics.csv", frame_rows) + write_csv_rows(args.output_dir / "per_temporal_transition_metrics.csv", temporal_rows) + print(json.dumps({ + "model": report["model_name"], + "coverage": report["coverage"]["hand_frame_fraction"], + "absolute_mpjpe_mm": report["metrics_success_conditioned"][ + "absolute_mpjpe_mm" + ]["mean"], + "root_relative_mpjpe_mm": report["metrics_success_conditioned"][ + "root_relative_mpjpe_mm" + ]["mean"], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_tiny.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_tiny.py new file mode 100644 index 0000000000000000000000000000000000000000..d1416cb0dd5df06fc941ee11a654e30062cf3517 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/evaluate_tiny.py @@ -0,0 +1,426 @@ +#!/usr/bin/env python3 +"""Deterministic full tiny-set evaluation and visualization.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path + +import cv2 +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def draw_points(image: np.ndarray, points: np.ndarray, color: tuple[int, int, int], marker: bool) -> None: + for point in points: + if not np.isfinite(point).all(): + continue + xy = tuple(np.rint(point).astype(int)) + if marker: + cv2.drawMarker(image, xy, color, cv2.MARKER_CROSS, 8, 1) + else: + cv2.circle(image, xy, 3, color, -1) + + +def mean(values: list[float]) -> float | None: + return float(np.mean(values)) if values else None + + +def image_size_bucket(max_side_px: float) -> str: + if max_side_px < 64: + return "small_lt64px" + if max_side_px < 128: + return "medium_64_128px" + return "large_ge128px" + + +def depth_bucket(depth_m: float) -> str: + if depth_m < 0.5: + return "near_lt0.5m" + if depth_m < 0.8: + return "middle_0.5_0.8m" + return "far_ge0.8m" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--train-log", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--max-clips", type=int) + args = parser.parse_args(); args.output_dir.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=args.max_clips, + oracle_crop_enabled=( + config["model"].get("oracle_crop_mode", "none") != "none" + ), + ) + loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_h2o_clips) + model_config = ModelConfig(**config["model"], dinov3_source=assets["dinov3_source"], dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"]) + device = torch.device(f"cuda:{args.gpu}") + model = BimanualReconstructionModel(model_config).to(device).eval() + load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + + values: dict[str, list[float]] = defaultdict(list) + loss_values: dict[str, list[float]] = defaultdict(list) + frame_rows: list[dict[str, object]] = [] + saved_overlays: list[Path] = [] + attention_same_peak = [] + attention_cosine = [] + depth_attention_same_peak = [] + temporal_attention_diagonal = [] + temporal_attention_entropy = [] + bimanual_cross_attention = [] + depth_gates = [] + raw_depth_gates = [] + rgb_update_norms = [] + depth_update_norms = [] + gated_depth_update_norms = [] + structured_diagnostics: dict[str, list[float]] = defaultdict(list) + visualization_index = 0 + saved_sequence_diagnostics = False + frame_count = 0 + bucket_values: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + + with torch.inference_mode(): + for batch in loader: + batch = {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + gt_vertices, _ = model.mano_layer( + axis_angle_to_matrix(pose), torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + mano_valid = (batch["mano_annotation_valid"].bool() & batch["frame_valid"].bool()[..., None])[..., None, None] + batch["vertices_camera"] = torch.where(mano_valid, gt_vertices, torch.full_like(gt_vertices, torch.nan)) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + for key, value in losses.items(): + loss_values[key].append(float(value)) + + frame_valid = batch["frame_valid"].bool() + frame_count += int(frame_valid.sum()) + ann = batch["joint_annotation_valid"].bool() & frame_valid[..., None] + joint_valid = batch["joint_element_valid"].bool() & ann[..., None] + target_joints = torch.nan_to_num(batch["joint3d_camera"]) + joint_error = torch.linalg.vector_norm(prediction["joints_camera"] - target_joints, dim=-1) * 1000 + pred_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + target_relative = target_joints - target_joints[..., :1, :] + relative_error = torch.linalg.vector_norm(pred_relative - target_relative, dim=-1) * 1000 + translation_error = (prediction["wrist_root_translation"] - torch.nan_to_num(batch["wrist_root_translation"])).abs() * 1000 + height, width = map(int, batch["image_hw"][0].tolist()) + predicted_2d = prediction["joint2d_norm"] * torch.tensor((width, height), device=device) + target_2d = torch.nan_to_num(batch["joint2d"]) + error_2d = torch.linalg.vector_norm(predicted_2d - target_2d, dim=-1) + if "structured_translation_delta" in prediction: + valid_hands = frame_valid[..., None].expand(-1, -1, 2) + structured_diagnostics["translation_delta_norm_mm"].extend( + ( + torch.linalg.vector_norm( + prediction["structured_translation_delta"], dim=-1, + )[valid_hands] * 1000.0 + ).float().cpu().tolist() + ) + structured_diagnostics["rotation_delta_norm_deg"].extend( + ( + torch.linalg.vector_norm( + prediction["structured_rotation_delta_axis_angle"], dim=-1, + )[valid_hands[..., None].expand(-1, -1, -1, 16)] + * (180.0 / np.pi) + ).float().cpu().tolist() + ) + structured_diagnostics["shape_delta_abs"].extend( + prediction["structured_shape_delta"].abs().reshape(-1).float().cpu().tolist() + ) + pixel_scale = torch.tensor((width, height), device=device) + structured_diagnostics["joint2d_delta_px"].extend( + torch.linalg.vector_norm( + prediction["structured_joint2d_delta"] * pixel_scale, + dim=-1, + )[valid_hands[..., None].expand(-1, -1, -1, 21)].float().cpu().tolist() + ) + structured_diagnostics["sample_offset_norm_px"].extend( + torch.linalg.vector_norm( + prediction["structured_sample_offsets"] * pixel_scale, + dim=-1, + )[frame_valid[..., None, None, None].expand( + -1, -1, 2, 7, prediction["structured_sample_offsets"].shape[-2], + )].float().cpu().tolist() + ) + + if not saved_sequence_diagnostics: + subject = batch["subject_id"][0] + sequence = batch["sequence_id"][0] + title_prefix = f"{config['name']} | {subject}/{sequence}" + if "temporal_attention" in prediction["attention"]: + temporal_plot = prediction["attention"]["temporal_attention"][0, -1].float().cpu().numpy() + fig, axes = plt.subplots(1, 2, figsize=(9, 4)) + for hand, side in enumerate(("left", "right")): + axes[hand].imshow(temporal_plot[hand], vmin=0, vmax=max(float(temporal_plot.max()), 1e-8), cmap="viridis") + axes[hand].set_title(f"{side} temporal attention") + axes[hand].set_xlabel("key frame") + axes[hand].set_ylabel("query frame") + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_temporal_attention.png", dpi=160) + plt.close(fig) + valid_times = frame_valid[0].cpu().numpy() + time_axis = np.arange(int(valid_times.sum())) + fig, axes = plt.subplots(1, 2, figsize=(11, 4)) + for hand, side in enumerate(("left", "right")): + hand_valid = ann[0, :, hand].cpu().numpy() & valid_times + pred_z = prediction["wrist_root_translation"][0, :, hand, 2].float().cpu().numpy()[valid_times] + gt_z = batch["wrist_root_translation"][0, :, hand, 2].float().cpu().numpy()[valid_times] + axes[0].plot(time_axis, pred_z, label=f"{side} pred") + axes[0].plot(time_axis[hand_valid[valid_times]], gt_z[hand_valid[valid_times]], "--", label=f"{side} GT") + per_frame = joint_error[0, :, hand].mean(-1).float().cpu().numpy()[valid_times] + axes[1].plot(time_axis[hand_valid[valid_times]], per_frame[hand_valid[valid_times]], label=side) + axes[0].set_title("Camera-space wrist z") + axes[0].set_ylabel("meters") + axes[1].set_title("Per-frame absolute MPJPE") + axes[1].set_ylabel("mm") + for axis in axes: + axis.set_xlabel("frame in clip") + axis.grid(alpha=0.25) + axis.legend() + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_translation_and_mpjpe.png", dpi=160) + plt.close(fig) + if "depth_fusion_gate" in prediction["attention"]: + gates = prediction["attention"]["depth_fusion_gate"][0, :, :, :, 0].float().cpu().numpy() + fig, axes = plt.subplots(1, 2, figsize=(10, 4)) + for hand, side in enumerate(("left", "right")): + for layer in range(gates.shape[0]): + axes[hand].plot(gates[layer, valid_times, hand], label=f"layer {layer}") + axes[hand].set_title(f"{side} depth gate") + axes[hand].set_xlabel("frame in clip") + axes[hand].set_ylim(0, 1) + axes[hand].grid(alpha=0.25) + axes[hand].legend() + fig.suptitle(title_prefix) + fig.tight_layout() + fig.savefig(args.output_dir / "sequence_depth_gate.png", dpi=160) + plt.close(fig) + saved_sequence_diagnostics = True + + for hand, side in enumerate(("left", "right")): + mask = joint_valid[..., hand, :] + values[f"{side}_absolute_mpjpe_mm"].extend(joint_error[..., hand, :][mask].float().cpu().tolist()) + values[f"{side}_root_relative_mpjpe_mm"].extend(relative_error[..., hand, :][mask].float().cpu().tolist()) + values[f"{side}_joint2d_error_px"].extend(error_2d[..., hand, :][mask].float().cpu().tolist()) + hand_mask = ann[..., hand] + for axis_index, axis in enumerate("xyz"): + values[f"{side}_translation_{axis}_mae_mm"].extend(translation_error[..., hand, axis_index][hand_mask].float().cpu().tolist()) + + rgb_attention = prediction["attention"]["rgb_cross_attention"][:, -1] + left_attention, right_attention = rgb_attention[..., 0, :], rgb_attention[..., 1, :] + valid_flat = frame_valid + attention_same_peak.extend((left_attention.argmax(-1) == right_attention.argmax(-1))[valid_flat].cpu().tolist()) + cosine = torch.nn.functional.cosine_similarity(left_attention, right_attention, dim=-1) + attention_cosine.extend(cosine[valid_flat].float().cpu().tolist()) + if "depth_fusion_gate" in prediction["attention"]: + depth_gates.extend(prediction["attention"]["depth_fusion_gate"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + raw_depth_gates.extend(prediction["attention"]["depth_fusion_gate_raw"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + depth_update_norms.extend(prediction["attention"]["depth_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + gated_depth_update_norms.extend(prediction["attention"]["gated_depth_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + depth_attention = prediction["attention"]["depth_cross_attention"][:, -1] + depth_attention_same_peak.extend( + (depth_attention[..., 0, :].argmax(-1) == depth_attention[..., 1, :].argmax(-1))[frame_valid].cpu().tolist() + ) + rgb_update_norms.extend(prediction["attention"]["rgb_update_norm"][:, -1][frame_valid].float().cpu().reshape(-1).tolist()) + + if "temporal_attention" in prediction["attention"]: + temporal = prediction["attention"]["temporal_attention"][:, -1] + for batch_index in range(temporal.shape[0]): + valid_indices = torch.where(frame_valid[batch_index])[0] + for hand_index in range(2): + for query_index in valid_indices: + weights = temporal[batch_index, hand_index, query_index, valid_indices].float() + weights = weights / weights.sum().clamp_min(1e-8) + temporal_attention_diagonal.append(float(temporal[batch_index, hand_index, query_index, query_index])) + if weights.numel() > 1: + entropy = -(weights * weights.clamp_min(1e-8).log()).sum() / np.log(weights.numel()) + temporal_attention_entropy.append(float(entropy)) + if "bimanual_attention" in prediction["attention"]: + bimanual = prediction["attention"]["bimanual_attention"][:, -1] + cross = 0.5 * (bimanual[..., 0, 1] + bimanual[..., 1, 0]) + bimanual_cross_attention.extend(cross[frame_valid].float().cpu().tolist()) + + if prediction["wrist_root_translation"].shape[1] > 1: + velocity_valid = ann[:, 1:] & ann[:, :-1] + predicted_velocity = prediction["wrist_root_translation"][:, 1:] - prediction["wrist_root_translation"][:, :-1] + target_velocity = torch.nan_to_num(batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1]) + velocity_error = torch.linalg.vector_norm(predicted_velocity - target_velocity, dim=-1) * 1000 + values["temporal_velocity_error_mm_per_frame"].extend(velocity_error[velocity_valid].float().cpu().tolist()) + if predicted_velocity.shape[1] > 1: + acceleration_valid = velocity_valid[:, 1:] & velocity_valid[:, :-1] + predicted_acceleration = predicted_velocity[:, 1:] - predicted_velocity[:, :-1] + target_acceleration = target_velocity[:, 1:] - target_velocity[:, :-1] + acceleration_error = torch.linalg.vector_norm(predicted_acceleration - target_acceleration, dim=-1) * 1000 + values["temporal_acceleration_error_mm_per_frame2"].extend( + acceleration_error[acceleration_valid].float().cpu().tolist() + ) + + for time_index in range(batch["rgb"].shape[1]): + if not frame_valid[0, time_index]: + continue + for hand, side in enumerate(("left", "right")): + is_valid = bool(ann[0, time_index, hand]) + annotation_state = "".join( + str(int(value)) for value in ann[0, time_index].int().cpu().tolist() + ) + max_side_px = None + wrist_depth_m = None + if is_valid: + points = batch["joint2d"][0, time_index, hand] + extent = points.max(dim=0).values - points.min(dim=0).values + max_side_px = float(extent.max()) + wrist_depth_m = float(batch["wrist_root_translation"][0, time_index, hand, 2]) + absolute_error = float(joint_error[0, time_index, hand].mean()) + root_error = float(relative_error[0, time_index, hand].mean()) + z_error = float(translation_error[0, time_index, hand, 2]) + for bucket in ( + f"image_size/{image_size_bucket(max_side_px)}", + f"wrist_depth/{depth_bucket(wrist_depth_m)}", + f"annotation_state/{annotation_state}", + ): + bucket_values[bucket]["absolute_mpjpe_mm"].append(absolute_error) + bucket_values[bucket]["root_relative_mpjpe_mm"].append(root_error) + bucket_values[bucket]["translation_z_mae_mm"].append(z_error) + frame_rows.append({ + "subject": batch["subject_id"][0], "sequence": batch["sequence_id"][0], + "frame_id": int(batch["frame_id"][0, time_index]), "side": side, + "annotation_valid": int(is_valid), + "annotation_state": annotation_state, + "hand_max_side_px": max_side_px, + "wrist_depth_m": wrist_depth_m, + "absolute_mpjpe_mm": float(joint_error[0, time_index, hand].mean()) if is_valid else None, + "root_relative_mpjpe_mm": float(relative_error[0, time_index, hand].mean()) if is_valid else None, + "joint2d_error_px": float(error_2d[0, time_index, hand].mean()) if is_valid else None, + **{f"pred_t_{axis}_m": float(prediction["wrist_root_translation"][0, time_index, hand, index]) for index, axis in enumerate("xyz")}, + **{f"gt_t_{axis}_m": float(batch["wrist_root_translation"][0, time_index, hand, index]) if is_valid else None for index, axis in enumerate("xyz")}, + }) + + if visualization_index < 16: + rgb = batch["rgb"][0, time_index].float().cpu().permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + for hand, color in enumerate(((50, 220, 50), (50, 80, 255))): + if ann[0, time_index, hand]: + draw_points(image, batch["joint2d"][0, time_index, hand].float().cpu().numpy(), (255, 255, 255), True) + draw_points(image, predicted_2d[0, time_index, hand].float().cpu().numpy(), color, False) + modalities = "RGB" + ("+Depth" if config["model"].get("use_depth") else "") + ("+K" if config["model"].get("use_rays") else "") + lines = ( + f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/{int(batch['frame_id'][0,time_index])} GT=x pred=dot", + f"config={config['name']} input={modalities}", + f"GT valid L={int(ann[0,time_index,0])} R={int(ann[0,time_index,1])} presence=unsupervised", + ) + cv2.rectangle(image, (0, 0), (width, 62), (0, 0, 0), -1) + for line_index, label in enumerate(lines): + cv2.putText(image, label, (6, 17 + 19 * line_index), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (255, 255, 255), 1) + overlay_path = args.output_dir / f"{visualization_index:02d}_prediction_overlay.jpg" + cv2.imwrite(str(overlay_path), image); saved_overlays.append(overlay_path) + grid_h, grid_w = height // 16, width // 16 + for hand, side in enumerate(("left", "right")): + heat = rgb_attention[0, time_index, hand].float().cpu().numpy().reshape(grid_h, grid_w) + heat = (heat - heat.min()) / max(float(heat.max() - heat.min()), 1e-8) + heat = cv2.resize(np.uint8(heat * 255), (width, height), interpolation=cv2.INTER_CUBIC) + heat = cv2.applyColorMap(heat, cv2.COLORMAP_TURBO) + cv2.imwrite(str(args.output_dir / f"{visualization_index:02d}_{side}_attention.jpg"), cv2.addWeighted(image, .55, heat, .45, 0)) + if "depth_cross_attention" in prediction["attention"]: + depth_attention = prediction["attention"]["depth_cross_attention"][:, -1] + depth_heat = depth_attention[0, time_index, hand].float().cpu().numpy().reshape(grid_h, grid_w) + depth_heat = (depth_heat - depth_heat.min()) / max(float(depth_heat.max() - depth_heat.min()), 1e-8) + depth_heat = cv2.resize(np.uint8(depth_heat * 255), (width, height), interpolation=cv2.INTER_CUBIC) + depth_heat = cv2.applyColorMap(depth_heat, cv2.COLORMAP_TURBO) + cv2.imwrite( + str(args.output_dir / f"{visualization_index:02d}_{side}_depth_attention.jpg"), + cv2.addWeighted(image, .55, depth_heat, .45, 0), + ) + visualization_index += 1 + + with (args.output_dir / "per_frame_metrics.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(frame_rows[0])); writer.writeheader(); writer.writerows(frame_rows) + + train_rows = [json.loads(line) for line in args.train_log.read_text(encoding="utf-8").splitlines() if line] + fig, axes = plt.subplots(1, 3, figsize=(15, 4)) + axes[0].plot([row["step"] for row in train_rows], [row["losses"]["total"] for row in train_rows]); axes[0].set_title("Total loss") + axes[1].plot([row["step"] for row in train_rows], [row["metrics"]["absolute_camera_mpjpe_mm"] for row in train_rows]); axes[1].set_title("Batch absolute MPJPE (mm)") + axes[2].plot([row["step"] for row in train_rows], [row["metrics"]["translation_z_mae_mm"] for row in train_rows]); axes[2].set_title("Batch z MAE (mm)") + for axis in axes: axis.set_xlabel("step"); axis.grid(alpha=.25) + fig.tight_layout(); fig.savefig(args.output_dir / "training_curves.png", dpi=160); plt.close(fig) + + metrics = {key: mean(item) for key, item in values.items()} + metrics.update({ + "all_absolute_mpjpe_mm": mean(values["left_absolute_mpjpe_mm"] + values["right_absolute_mpjpe_mm"]), + "all_root_relative_mpjpe_mm": mean(values["left_root_relative_mpjpe_mm"] + values["right_root_relative_mpjpe_mm"]), + "all_joint2d_error_px": mean(values["left_joint2d_error_px"] + values["right_joint2d_error_px"]), + "rgb_attention_same_peak_fraction": mean([float(value) for value in attention_same_peak]), + "rgb_attention_left_right_cosine": mean(attention_cosine), + "depth_attention_same_peak_fraction": mean([float(value) for value in depth_attention_same_peak]), + "temporal_attention_diagonal_mean": mean(temporal_attention_diagonal), + "temporal_attention_normalized_entropy": mean(temporal_attention_entropy), + "bimanual_cross_attention_mean": mean(bimanual_cross_attention), + "depth_gate_mean": mean(depth_gates), + "depth_gate_min": float(min(depth_gates)) if depth_gates else None, + "depth_gate_max": float(max(depth_gates)) if depth_gates else None, + "depth_gate_raw_mean": mean(raw_depth_gates), + "depth_gate_raw_min": float(min(raw_depth_gates)) if raw_depth_gates else None, + "depth_gate_raw_max": float(max(raw_depth_gates)) if raw_depth_gates else None, + "rgb_update_norm_mean": mean(rgb_update_norms), + "depth_update_norm_mean": mean(depth_update_norms), + "gated_depth_update_norm_mean": mean(gated_depth_update_norms), + }) + report = { + "status": "evaluated", "checkpoint": str(args.checkpoint.resolve()), + "split_role": "official_train_tiny_overfit" if "tiny" in args.manifest.name else "non_test_evaluation", + "official_test_used": False, + "clips": len(dataset), "frames": frame_count, + "metrics": metrics, "mean_weighted_losses": {key: mean(item) for key, item in loss_values.items()}, + "structured_residual_diagnostics": { + key: { + "mean": mean(items), + "p95": float(np.percentile(items, 95)) if items else None, + "maximum": float(max(items)) if items else None, + } + for key, items in sorted(structured_diagnostics.items()) + }, + "buckets": { + bucket: {"valid_hands": len(items["absolute_mpjpe_mm"]), **{key: mean(values) for key, values in items.items()}} + for bucket, items in sorted(bucket_values.items()) + }, + "occlusion_bucket": "UNAVAILABLE: H2O annotation_valid is not an occlusion or presence label.", + } + if "tiny" in args.manifest.name: + report["success_thresholds"] = {"absolute_mpjpe_mm": 15.0, "root_relative_mpjpe_mm": 8.0, "joint2d_error_px": 8.0} + report["tiny_overfit_passed"] = bool( + metrics["all_absolute_mpjpe_mm"] < 15 and metrics["all_root_relative_mpjpe_mm"] < 8 and metrics["all_joint2d_error_px"] < 8 + ) + (args.output_dir / "evaluation.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/extract_phase4_oracle_local_depth.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/extract_phase4_oracle_local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd7ff0e89f1308c39a663fd8afde461e7acc2f5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/extract_phase4_oracle_local_depth.py @@ -0,0 +1,324 @@ +#!/usr/bin/env python3 +"""Extract frozen-model A1 oracle local-depth features without test access.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import tempfile +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.local_depth import oracle_local_depth_features +from foundation_hand.evaluation.phase4 import ( + action_name, + bimanual_asymmetry, + load_action_label, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +SIDES = ("left", "right") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_save_npz(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{path.name}.", suffix=".npz", dir=path.parent, + ) + os.close(descriptor) + temporary = Path(temporary_name) + try: + np.savez_compressed(temporary, **arrays) + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError("A1 extraction produced no valid hand rows") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--split-role", choices=("official_train", "official_validation"), required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--expected-manifest-sha256", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--max-clips", type=int) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if "test" in args.manifest.name.lower() or "test" in args.split_role: + raise ValueError("Phase 4 A1 explicitly prohibits official-test access") + output_npz = args.output_dir / "features.npz" + output_csv = args.output_dir / "samples.csv" + output_json = args.output_dir / "extraction.json" + if any(path.exists() for path in (output_npz, output_csv, output_json)): + raise FileExistsError(f"refusing to overwrite existing A1 extraction in {args.output_dir}") + + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + if checkpoint_hash != args.expected_checkpoint_sha256: + raise ValueError("checkpoint hash differs from the registered Phase 3 reference") + if manifest_hash != args.expected_manifest_sha256: + raise ValueError("manifest hash differs from the registered Phase 4 protected input") + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), + (int(data_config["stride"]),), + max_clips=args.max_clips, + ) + loader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint_state = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + chunks: dict[str, list[np.ndarray]] = { + "control": [], + "local": [], + "coarse_translation_m": [], + "target_translation_m": [], + "coarse_joints_m": [], + "target_joints_m": [], + "direct_joints_2d_px": [], + "target_joints_2d_px": [], + "K_resized": [], + } + rows: list[dict[str, object]] = [] + raw_intrinsics: dict[str, np.ndarray] = {} + control_names: tuple[str, ...] | None = None + local_names: tuple[str, ...] | None = None + + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = move_to_device(batch_cpu, device) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + frame_valid = batch["frame_valid"][0].bool() + annotation_valid = batch["joint_annotation_valid"][0].bool() & frame_valid[:, None] + height, width = map(int, batch["image_hw"][0].tolist()) + direct_2d = prediction["joint2d_norm"][0].float().cpu().numpy() + direct_2d *= np.asarray((width, height), dtype=np.float32) + coarse_translation = prediction["wrist_root_translation"][0].float().cpu().numpy() + coarse_joints = prediction["joints_camera"][0].float().cpu().numpy() + target_translation = batch["wrist_root_translation"][0].float().cpu().numpy() + target_joints = batch["joint3d_camera"][0].float().cpu().numpy() + target_2d_resized = batch["joint2d"][0].float().cpu().numpy() + + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + take_dir = args.root / take + if take not in raw_intrinsics: + K_raw, raw_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + raw_intrinsics[take] = K_raw + else: + K_raw = raw_intrinsics[take] + raw_hw = None + + for time_index in torch.where(frame_valid)[0].cpu().tolist(): + frame_id = int(batch["frame_id"][0, time_index]) + stem = f"{frame_id:06d}" + raw_depth_mm = cv2.imread( + str(take_dir / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED, + ) + if raw_depth_mm is None: + raise RuntimeError(f"cannot read raw depth {take_dir}/depth/{stem}.png") + if raw_hw is not None and raw_depth_mm.shape != raw_hw: + raise ValueError(f"raw depth/K size mismatch at {take}/{stem}") + raw_depth_m, raw_depth_valid = depth_mm_to_m(raw_depth_mm) + target_2d_raw, positive = project_points(target_joints[time_index], K_raw) + + frame_sizes: list[float | None] = [None, None] + frame_depths: list[float | None] = [None, None] + for hand in range(2): + if bool(annotation_valid[time_index, hand]): + extent = ( + target_2d_resized[time_index, hand].max(axis=0) + - target_2d_resized[time_index, hand].min(axis=0) + ) + frame_sizes[hand] = float(extent.max()) + frame_depths[hand] = float(target_translation[time_index, hand, 2]) + asymmetry = bimanual_asymmetry(frame_sizes, frame_depths) + label = load_action_label(args.root, take, frame_id) + + clip_features: dict[str, list[np.ndarray]] = {key: [] for key in chunks} + clip_rows: list[dict[str, object]] = [] + for hand, side in enumerate(SIDES): + if not bool(annotation_valid[time_index, hand]): + continue + if not bool(positive[hand].all()): + raise ValueError(f"valid GT hand projects behind camera at {take}/{stem}/{side}") + features = oracle_local_depth_features( + raw_depth_m, + raw_depth_valid, + target_2d_raw[hand], + K_raw, + coarse_translation[time_index, hand], + hand, + ) + if control_names is None: + control_names, local_names = features.control_names, features.local_names + elif features.control_names != control_names or features.local_names != local_names: + raise AssertionError("A1 feature schema changed within one extraction") + clip_features["control"].append(features.control) + clip_features["local"].append(features.local) + clip_features["coarse_translation_m"].append(coarse_translation[time_index, hand]) + clip_features["target_translation_m"].append(target_translation[time_index, hand]) + clip_features["coarse_joints_m"].append(coarse_joints[time_index, hand]) + clip_features["target_joints_m"].append(target_joints[time_index, hand]) + clip_features["direct_joints_2d_px"].append(direct_2d[time_index, hand]) + clip_features["target_joints_2d_px"].append(target_2d_resized[time_index, hand]) + clip_features["K_resized"].append( + batch["K"][0, time_index].float().cpu().numpy() + ) + clip_rows.append({ + "sample_index": len(rows) + len(clip_rows), + "clip_index": clip_index, + "time_index": time_index, + "take": take, + "subject": batch["subject_id"][0], + "sequence": batch["sequence_id"][0], + "frame_id": frame_id, + "side": side, + "side_index": hand, + "action_family": str(batch["sequence_id"][0]).split("/", 1)[0], + "action_label": label, + "action_name": action_name(label), + "hand_size_px": frame_sizes[hand], + "wrist_depth_m": frame_depths[hand], + "bimanual_size_ratio": asymmetry["bimanual_size_ratio"], + "bimanual_depth_gap_m": asymmetry["bimanual_depth_gap_m"], + "bimanual_asymmetry_bucket": asymmetry["bimanual_asymmetry_bucket"], + "local_depth_valid_fraction": features.local_valid_fraction, + "local_depth_discontinuity_m": features.local_depth_discontinuity_m, + }) + if clip_rows: + for key, values in clip_features.items(): + chunks[key].append(np.stack(values).astype(np.float32)) + rows.extend(clip_rows) + + if (clip_index + 1) % 250 == 0: + print( + f"clips={clip_index + 1}/{len(dataset)} valid_hands={len(rows)}", + flush=True, + ) + + if control_names is None or local_names is None: + raise ValueError("A1 extraction found no annotation-valid hands") + arrays = {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + sample_count = len(rows) + if any(value.shape[0] != sample_count for value in arrays.values()): + raise AssertionError("A1 array and metadata row counts differ") + arrays["target_residual_z_m"] = ( + arrays["target_translation_m"][:, 2] - arrays["coarse_translation_m"][:, 2] + ).astype(np.float32) + if not all(np.isfinite(value).all() for value in arrays.values()): + raise ValueError("A1 extraction contains non-finite values") + + args.output_dir.mkdir(parents=True, exist_ok=True) + atomic_save_npz(output_npz, arrays) + write_csv(output_csv, rows) + report = { + "status": "extracted", + "phase": 4, + "wave": "A1_oracle_local_depth", + "split_role": args.split_role, + "official_test_used": False, + "oracle_contract": ( + "GT 2D joints locate multiscale regions in original aligned metric depth only; " + "GT wrist depth is a target and is never an input feature." + ), + "control_contract": ( + "The control receives the same oracle location, K, side and coarse translation " + "but no local depth or XYZ statistics." + ), + "config": str(args.config.resolve()), + "data_root": str(args.root.resolve()), + "manifest": {"path": str(args.manifest.resolve()), "sha256": manifest_hash}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": checkpoint_hash, + "step": int(checkpoint_state["step"]), + }, + "dataset_clips": len(dataset), + "valid_hand_samples": sample_count, + "control_dim": len(control_names), + "local_dim": len(local_names), + "control_feature_names": list(control_names), + "local_feature_names": list(local_names), + "precision": config["precision"], + "device": torch.cuda.get_device_name(device), + "outputs": { + "features": str(output_npz.resolve()), + "samples": str(output_csv.resolve()), + }, + } + output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": "complete", "samples": sample_count, "output": str(args.output_dir)})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_fold_milestone_recovery.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_fold_milestone_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..146372c43331db29514bf7bbef1d96c7be0c0103 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_fold_milestone_recovery.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Validate recovered fold milestones and atomically complete canonical states.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +import yaml + +from scripts.run_phase9_fold_milestone_eval import ( + atomic_json, + h2o_milestones, + milestone_checkpoint, + sha256, +) +from scripts.run_phase9_fold_shard import fold_evaluation_complete +from scripts.run_phase9_external_milestone_eval import stable_checkpoint_sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def expected_shard_evaluations( + registry: dict[str, Any], shard: int, output_root: Path, +) -> list[str]: + conditions = {item["condition"]: item for item in registry["conditions"]} + expected: list[str] = [] + for condition_id in registry["shards"][str(shard)]: + condition = conditions[condition_id] + config_path = Path(condition["config"]) + if sha256(config_path) != condition["config_sha256"]: + raise RuntimeError(f"fold config hash differs: {condition_id}") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + heldout = Path(config["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + run_dir = Path(condition["output_dir"]) + for milestone_id in h2o_milestones(config): + checkpoint = milestone_checkpoint(run_dir, milestone_id) + if checkpoint is None: + raise RuntimeError(f"missing checkpoint: {condition_id}:{milestone_id}") + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + evaluation_id = f"{condition_id}_{milestone_id}_{mode}" + output = output_root / condition_id / milestone_id / mode + if not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + raise RuntimeError(f"invalid recovered output: {evaluation_id}") + expected.append(evaluation_id) + return expected + + +def finalize(plan_path: Path) -> dict[str, Any]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + plan_hash = sha256(plan_path) + if plan.get("official_test_used") is not False: + raise RuntimeError("recovery plan must explicitly exclude official test") + registry_path = Path(plan["registry"]) + if sha256(registry_path) != plan["registry_sha256"]: + raise RuntimeError("registry SHA256 differs") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + worker_states: dict[str, str] = {} + recovered_ids: set[str] = set() + for worker in plan["workers"]: + state_path = Path(worker["state"]) + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or state.get("recovery_plan_sha256") != plan_hash + or state.get("recovery_worker_id") != worker["id"] + or set(state.get("assigned_evaluation_ids", [])) + != set(worker["evaluation_ids"]) + or not set(worker["evaluation_ids"]).issubset(state.get("completed_ids", [])) + ): + raise RuntimeError(f"incomplete recovery worker: {worker['id']}") + overlap = recovered_ids.intersection(worker["evaluation_ids"]) + if overlap: + raise RuntimeError(f"overlapping recovery IDs: {sorted(overlap)}") + recovered_ids.update(worker["evaluation_ids"]) + worker_states[worker["id"]] = sha256(state_path) + + completed_states: dict[str, Any] = {} + for shard_record in plan["canonical_states"]: + shard = int(shard_record["shard"]) + state_path = Path(shard_record["path"]) + if sha256(state_path) != shard_record["failed_state_sha256"]: + raise RuntimeError(f"canonical shard{shard} state changed during recovery") + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("registry_sha256") != plan["registry_sha256"] + or state.get("official_test_used") is not False + ): + raise RuntimeError(f"canonical shard{shard} binding differs") + expected = expected_shard_evaluations( + registry, shard, Path(plan["output_root"]), + ) + if len(expected) != 54 or len(set(expected)) != 54: + raise RuntimeError(f"shard{shard} expected evaluation count differs") + if not set(state.get("completed_ids", [])).union(recovered_ids).issuperset(expected): + raise RuntimeError(f"shard{shard} recovery coverage is incomplete") + state["recovered_failure"] = state.pop("failure", None) + state["status"] = "complete" + state["completed_ids"] = expected + state["allowed_physical_gpus"] = [0, 1, 2, 3, 4, 5] + state["resource_amendment"] = "gpu_4_5_evaluator_authorization_only_20260730" + state["recovery_plan"] = str(plan_path.resolve()) + state["recovery_plan_sha256"] = plan_hash + state["recovery_worker_state_sha256"] = worker_states + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state.pop("waiting_for", None) + atomic_json(state_path, state) + completed_states[str(shard)] = { + "path": str(state_path.resolve()), + "sha256": sha256(state_path), + "completed_ids": len(expected), + } + return { + "schema_version": "phase9_fold_milestone_recovery_merge_v1", + "status": "complete", + "recovery_plan": str(plan_path.resolve()), + "recovery_plan_sha256": plan_hash, + "canonical_states": completed_states, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + result = finalize(args.plan) + args.report.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.report, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_last2.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_last2.py new file mode 100644 index 0000000000000000000000000000000000000000..a32e407fc52390193f3f562b6d9ab92d00625032 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_last2.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +"""Freeze the ordered Stage 9 decision after both candidate controllers finish.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +import time +from typing import Any + +from scripts.phase9_distributed_assignment import detect_machine, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if detect_machine(assignment, None) != "taku3": + raise ValueError("last-2 finalizer is owned only by Taku3") + if ( + plan.get("schema_version") != "phase9_last2_finalizer_plan_v1" + or plan.get("candidate_order") != ["5e7", "1e6"] + or plan.get("selection_rule") + != "retain_preceding_then_5e7_then_1e6_only_on_each_strict_gate" + or plan.get("dino_large_admitted") is not False + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("last-2 finalizer contract differs") + for candidate in plan["candidate_order"]: + spec = plan["candidates"][candidate] + plan_path = Path(spec["plan"]) + if not plan_path.is_file() or sha256(plan_path) != spec["plan_sha256"]: + raise ValueError(f"last-2 {candidate} plan binding differs") + controller_plan = read_json(plan_path) + if ( + controller_plan.get("candidate") != candidate + or Path(controller_plan["controller_state"]).resolve() + != Path(spec["state"]).resolve() + or Path(controller_plan["decision_report"]).resolve() + != Path(spec["report"]).resolve() + ): + raise ValueError(f"last-2 {candidate} paths differ") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"last-2 finalizer binding differs: {path}") + + +def candidate_result( + candidate: str, spec: dict[str, Any], +) -> tuple[str, dict[str, Any] | None, dict[str, Any] | None]: + state_path = Path(spec["state"]) + if not state_path.is_file(): + return "waiting", None, None + state = read_json(state_path) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed"): + return "failed", state, None + return "waiting", state, None + if ( + state.get("candidate") != candidate + or state.get("plan_sha256") != spec["plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + return "failed", state, None + report_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + not report_path.is_file() + or report_path.resolve() != Path(spec["report"]).resolve() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + ): + return "failed", state, None + report = read_json(report_path) + accepted = report.get("gate", {}).get("accepted") + if ( + report.get("schema_version") != "phase9_last2_candidate_decision_v1" + or report.get("status") != "complete" + or report.get("candidate") != candidate + or accepted not in {True, False} + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + return "failed", state, report + if accepted and ( + report.get("gate", {}).get("macro_strictly_improved") is not True + or report.get("gate", {}).get("worst_domain_strictly_improved") is not True + or state.get("admitted") is not True + ): + return "failed", state, report + return "complete", state, report + + +def build_final_report( + plan: dict[str, Any], results: dict[str, tuple[dict[str, Any], dict[str, Any]]], + *, created_utc: str | None = None, +) -> dict[str, Any]: + five_state, five = results["5e7"] + one_state, one = results["1e6"] + if one["gate"]["accepted"] and not five["gate"]["accepted"]: + raise ValueError("1e-6 cannot be accepted after a rejected 5e-7 candidate") + if one["gate"]["accepted"]: + selected = "last2_1e6" + selected_report = one + elif five["gate"]["accepted"]: + selected = "last2_5e7" + selected_report = five + else: + selected = "preceding_mechanism" + selected_report = None + reports = {} + for candidate, (state, report) in results.items(): + path = Path(plan["candidates"][candidate]["report"]) + reports[candidate] = { + "path": str(path.resolve()), + "sha256": sha256(path), + "admitted": state.get("admitted") is True, + "accepted": report["gate"]["accepted"], + "decision": report["decision"], + "candidate_training_gpu_hours": float( + report.get("candidate_training_gpu_hours", 0.0) + ), + } + total_gpu_hours = sum( + item["candidate_training_gpu_hours"] for item in reports.values() + ) + return { + "schema_version": "phase9_last2_final_decision_v1", + "status": "complete", + "created_utc": created_utc or utc_now(), + "candidate_order": list(plan["candidate_order"]), + "selection_rule": plan["selection_rule"], + "selected": selected, + "last2_accepted": selected_report is not None, + "selected_candidate_report": ( + reports["1e6"] if selected == "last2_1e6" + else reports["5e7"] if selected == "last2_5e7" + else None + ), + "selected_candidate_training_jobs": ( + selected_report.get("candidate_training_jobs") + if selected_report is not None else None + ), + "candidate_reports": reports, + "total_candidate_training_gpu_hours": total_gpu_hours, + "rejection_disclosure": { + candidate: report.get("not_admitted_reason") + or report.get("gate", {}).get("rejection_reason") + for candidate, (_, report) in results.items() + if report["gate"]["accepted"] is False + }, + "dino_large_admitted": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("last-2 finalizer state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_last2_finalizer_state_v1", + "status": "waiting_for_candidate_controllers", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing last-2 finalizer state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + statuses = {} + ready = {} + failed = None + for candidate in plan["candidate_order"]: + status, candidate_state, report = candidate_result( + candidate, plan["candidates"][candidate], + ) + statuses[candidate] = status + if status == "failed": + failed = candidate + elif status == "complete": + assert candidate_state is not None and report is not None + ready[candidate] = (candidate_state, report) + state["candidate_statuses"] = statuses + state["updated_utc"] = utc_now() + if failed is not None: + state["status"] = "failed_candidate_binding" + state["failure_candidate"] = failed + atomic_json(args.state, state) + raise SystemExit(1) + if len(ready) == len(plan["candidate_order"]): + break + state["status"] = "waiting_for_candidate_controllers" + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + report_path = Path(plan["report"]) + report_path.parent.mkdir(parents=True, exist_ok=True) + state.setdefault("decision_created_utc", utc_now()) + state["status"] = "publishing_decision" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + report = build_final_report( + plan, ready, created_utc=state["decision_created_utc"], + ) + if report_path.exists(): + if read_json(report_path) != report: + state["status"] = "failed_existing_report_differs" + atomic_json(args.state, state) + raise SystemExit(1) + else: + atomic_json(report_path, report) + state["status"] = "complete" + state["decision"] = report["selected"] + state["decision_report"] = { + "path": str(report_path.resolve()), "sha256": sha256(report_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_resolution_cache.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e6d32a6109f73a7c0dc2b0fdefe9cb8fa15bc6 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_resolution_cache.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Finalize Phase 9 resolution caches after every source worker completes.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +import time +from typing import Any + +from scripts.audit_phase9_resolution_cache import audit +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + sha256, + validate_plan_bindings, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_admission(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + path = Path(plan["admission_state"]) + if not path.is_file(): + raise ValueError("resolution admission state is missing") + state = json.loads(path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution admission state differs") + return state + + +def inspect_workers( + plan_path: Path, plan: dict[str, Any], admission: dict[str, Any] +) -> tuple[str, list[dict[str, Any]]]: + records = [] + overall = "complete" + for worker in plan["workers"]: + path = Path(worker["state"]) + if not path.is_file(): + overall = "waiting_for_workers" + records.append({"worker": worker["id"], "status": "missing"}) + continue + state = json.loads(path.read_text(encoding="utf-8")) + status = state.get("status") + if str(status).startswith("failed"): + overall = "failed_dependency" + elif status != "complete" and overall != "failed_dependency": + overall = "waiting_for_workers" + if ( + state.get("worker") != worker["id"] + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution worker state differs: {worker['id']}") + if status == "complete" and ( + state.get("winner") != admission.get("winner") + or state.get("winner_checkpoint") != admission.get("winner_checkpoint") + or state.get("winner_config") != admission.get("winner_config") + or state.get("admission_state_sha256") != sha256(plan["admission_state"]) + ): + raise ValueError(f"resolution worker winner binding differs: {worker['id']}") + records.append({ + "worker": worker["id"], + "status": status, + "state": str(path.resolve()), + "state_sha256": sha256(path), + }) + return overall, records + + +def validate_existing_completion( + plan_path: Path, plan: dict[str, Any], state: dict[str, Any] +) -> bool: + audit_path = Path(plan["audit_output"]) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == sha256(plan_path) + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and audit_path.is_file() + and state.get("audit", {}).get("sha256") == sha256(audit_path) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan_bindings(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["readiness_state"]).resolve(): + parser.error("readiness state path differs from plan") + + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.state.is_file(): + existing = json.loads(args.state.read_text(encoding="utf-8")) + if validate_existing_completion(args.plan, plan, existing): + print(json.dumps(existing, indent=2)) + return + if existing.get("plan_sha256") not in (None, sha256(args.plan)): + parser.error("existing readiness state belongs to another plan") + + state: dict[str, Any] = { + "schema_version": "phase9_resolution_cache_readiness_v1", + "status": "waiting_for_admission", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, + "official_test_used": False, + } + while True: + try: + admission = validate_admission(args.plan, plan) + worker_status, workers = inspect_workers(args.plan, plan, admission) + except ValueError as error: + if "admission state is missing" in str(error): + state["status"] = "waiting_for_admission" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_validation" + state["failure"] = str(error) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + state["workers"] = workers + state["status"] = worker_status + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if worker_status == "failed_dependency": + raise SystemExit(1) + if worker_status != "complete": + time.sleep(args.poll_seconds) + continue + break + + audit_path = Path(plan["audit_output"]) + if audit_path.exists(): + existing_audit = json.loads(audit_path.read_text(encoding="utf-8")) + if ( + existing_audit.get("status") != "complete" + or existing_audit.get("plan_sha256") != sha256(args.plan) + or existing_audit.get("official_test_used") is not False + or existing_audit.get("h2o_official_validation_used") is not False + ): + state["status"] = "failed_existing_audit" + atomic_json(args.state, state) + raise SystemExit(1) + else: + state["status"] = "auditing" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + try: + result = audit(plan) + except Exception as error: + state["status"] = "failed_audit" + state["failure"] = f"{type(error).__name__}: {error}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise + result.update({ + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "admission_state": str(Path(plan["admission_state"]).resolve()), + "admission_state_sha256": sha256(plan["admission_state"]), + "winner": admission["winner"], + "winner_checkpoint": admission["winner_checkpoint"], + "winner_config": admission["winner_config"], + "worker_states": workers, + }) + audit_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(audit_path, result) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["admission_state_sha256"] = sha256(plan["admission_state"]) + state["winner"] = admission["winner"] + state["winner_checkpoint"] = admission["winner_checkpoint"] + state["winner_config"] = admission["winner_config"] + state["audit"] = { + "path": str(audit_path.resolve()), + "sha256": sha256(audit_path), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_selection_binding_recovery.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d8d4a11430f20985ff8c87f96eb749783db882 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/finalize_phase9_selection_binding_recovery.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Publish one host's complete selection recovery as an immutable release.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +from typing import Any + +from scripts.run_phase9_selection_binding_recovery import ( + atomic_json, + validate_recovered_output, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def release_root(plan: dict[str, Any], owner: str) -> Path: + assignment = json.loads( + Path(plan["distributed_assignment"]["path"]).read_text(encoding="utf-8") + ) + return Path( + assignment["phase9_selection_recovery"][f"{owner}_recovery_root"] + ) + + +def build_release( + *, plan_path: Path, owner: str, output: Path, +) -> dict[str, Any]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + plan_hash = sha256(plan_path) + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"selection recovery code binding differs: {path}") + root = release_root(plan, owner).resolve() + if output.parent.resolve() != root: + raise ValueError("selection recovery release must live at its frozen root") + owner_workers = [item for item in plan["workers"] if item["owner"] == owner] + owner_evaluations = [ + item for item in plan["evaluations"] if item["owner"] == owner + ] + expected_ids = {item["id"] for item in owner_evaluations} + completed_ids: set[str] = set() + worker_states = [] + for worker in owner_workers: + state_path = Path(worker["state"]) + if not state_path.is_file(): + raise ValueError(f"selection recovery worker state missing: {worker['id']}") + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("owner") != owner + or state.get("plan_sha256") != plan_hash + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or set(state.get("completed_ids", [])) + != set(worker["evaluation_ids"]) + ): + raise ValueError( + f"selection recovery worker state differs: {worker['id']}" + ) + completed_ids.update(state["completed_ids"]) + worker_states.append({ + "id": worker["id"], "path": str(state_path.resolve()), + "sha256": sha256(state_path), + }) + if completed_ids != expected_ids: + raise ValueError("selection recovery completed IDs differ") + evaluation_evidence = [] + files = [] + seen_relative_paths: set[str] = set() + for item in owner_evaluations: + evidence = validate_recovered_output(item) + directory = Path(item["output_dir"]).resolve() + try: + relative_output = directory.relative_to(root) + except ValueError as error: + raise ValueError("recovery output is outside owner root") from error + for path in sorted(directory.rglob("*")): + if path.is_symlink() or not path.is_file(): + if path.is_symlink(): + raise ValueError(f"recovery release refuses symlink: {path}") + continue + relative = str(path.resolve().relative_to(root)) + if relative in seen_relative_paths: + raise ValueError(f"duplicate recovery release path: {relative}") + seen_relative_paths.add(relative) + files.append({ + "path": relative, "sha256": sha256(path), + "bytes": path.stat().st_size, + }) + evaluation_evidence.append({ + "id": item["id"], "output_dir": str(relative_output), **evidence, + }) + return { + "schema_version": "phase9_selection_binding_recovery_release_v1", + "status": "complete_immutable_release", + "created_utc": datetime.now(timezone.utc).isoformat(), + "owner": owner, + "plan": {"path": str(plan_path.resolve()), "sha256": plan_hash}, + "distributed_assignment": plan["distributed_assignment"], + "root": str(root), + "worker_states": worker_states, + "evaluation_ids": sorted(expected_ids), + "evaluations": evaluation_evidence, + "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "read_only_after_publish": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--owner", choices=("taku3", "server_new"), required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = build_release(plan_path=args.plan, owner=args.owner, output=args.output) + if args.output.exists(): + existing = json.loads(args.output.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("owner") == args.owner + and existing.get("plan", {}).get("sha256") + == result["plan"]["sha256"] + and existing.get("files") == result["files"] + and existing.get("evaluations") == result["evaluations"] + ): + print(json.dumps(existing, indent=2)) + return + parser.error("existing recovery release differs") + atomic_json(args.output, result) + for item in result["files"]: + os.chmod(Path(result["root"]) / item["path"], 0o444) + os.chmod(args.output, 0o444) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase4_oracle_local_depth.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase4_oracle_local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..61cdc0efdd02dd690411a6cae7f8faf78c60a242 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase4_oracle_local_depth.py @@ -0,0 +1,605 @@ +#!/usr/bin/env python3 +"""Fit and evaluate the Phase 4 A1 bounded oracle wrist-z diagnostic.""" + +from __future__ import annotations + +import argparse +import copy +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import torch.nn.functional as F + +from foundation_hand.evaluation.local_depth import BoundedZResidualRegressor +from foundation_hand.evaluation.metrics import distribution_summary +from foundation_hand.geometry.camera import project_points + + +FINGERTIPS = (4, 8, 12, 16, 20) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV {path}") + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def stable_take_holdout(takes: list[str], modulus: int = 5) -> np.ndarray: + """Select a deterministic official-train-only holdout by complete take.""" + + if modulus < 2: + raise ValueError("holdout modulus must be at least two") + output = [] + for take in takes: + digest = hashlib.sha256(take.encode("utf-8")).digest() + output.append(int.from_bytes(digest[:8], "little") % modulus == 0) + return np.asarray(output, dtype=bool) + + +def padded_control(control: np.ndarray, local_dim: int) -> np.ndarray: + if control.ndim != 2 or control.shape[1] > local_dim: + raise ValueError("invalid control/local feature dimensions") + output = np.zeros((control.shape[0], local_dim), dtype=np.float32) + output[:, : control.shape[1]] = control + return output + + +def standardizer(features: np.ndarray, fit_mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + values = features[fit_mask].astype(np.float64) + mean = values.mean(axis=0).astype(np.float32) + std = values.std(axis=0).astype(np.float32) + std[std < 1e-6] = 1.0 + return mean, std + + +def fit_regressor( + features: np.ndarray, + target_m: np.ndarray, + train_mask: np.ndarray, + holdout_mask: np.ndarray, + *, + device: torch.device, + seed: int, + hidden_dim: int, + max_residual_m: float, + learning_rate: float, + weight_decay: float, + batch_size: int, + epochs: int, + patience: int, +) -> tuple[BoundedZResidualRegressor, np.ndarray, np.ndarray, list[dict[str, float | int]]]: + mean, std = standardizer(features, train_mask) + normalized = (features.astype(np.float32) - mean) / std + x = torch.from_numpy(normalized).to(device) + target = torch.from_numpy(target_m.astype(np.float32)).to(device) + train_indices = torch.from_numpy(np.where(train_mask)[0]).to(device) + holdout_indices = torch.from_numpy(np.where(holdout_mask)[0]).to(device) + if not train_indices.numel() or not holdout_indices.numel(): + raise ValueError("official-train fit/holdout split is empty") + + torch.manual_seed(seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(seed) + model = BoundedZResidualRegressor( + features.shape[1], hidden_dim=hidden_dim, max_residual_m=max_residual_m, + ).to(device) + optimizer = torch.optim.AdamW( + model.parameters(), lr=learning_rate, weight_decay=weight_decay, + ) + generator = torch.Generator(device=device).manual_seed(seed) + best_state = copy.deepcopy(model.state_dict()) + best_holdout = float("inf") + stale = 0 + history: list[dict[str, float | int]] = [] + for epoch in range(1, epochs + 1): + model.train() + shuffled = train_indices[torch.randperm(train_indices.numel(), generator=generator, device=device)] + losses = [] + for start in range(0, shuffled.numel(), batch_size): + indices = shuffled[start : start + batch_size] + optimizer.zero_grad(set_to_none=True) + prediction = model(x[indices]) + loss = F.smooth_l1_loss(prediction, target[indices], beta=0.01) + if not torch.isfinite(loss): + raise FloatingPointError("non-finite A1 training loss") + loss.backward() + optimizer.step() + losses.append(float(loss.detach())) + model.eval() + with torch.inference_mode(): + holdout_prediction = model(x[holdout_indices]) + holdout_mae = float((holdout_prediction - target[holdout_indices]).abs().mean()) + history.append({ + "epoch": epoch, + "train_smooth_l1": float(np.mean(losses)), + "holdout_residual_mae_m": holdout_mae, + }) + if holdout_mae < best_holdout - 1e-6: + best_holdout = holdout_mae + best_state = copy.deepcopy(model.state_dict()) + stale = 0 + else: + stale += 1 + if stale >= patience: + break + model.load_state_dict(best_state) + return model, mean, std, history + + +def infer_residual( + model: BoundedZResidualRegressor, + features: np.ndarray, + mean: np.ndarray, + std: np.ndarray, + device: torch.device, + batch_size: int = 8192, +) -> np.ndarray: + model.eval() + output = [] + with torch.inference_mode(): + for start in range(0, features.shape[0], batch_size): + values = (features[start : start + batch_size].astype(np.float32) - mean) / std + output.append(model(torch.from_numpy(values).to(device)).cpu().numpy()) + result = np.concatenate(output).astype(np.float32) + if not np.isfinite(result).all(): + raise FloatingPointError("A1 residual inference produced non-finite values") + return result + + +def variant_metrics( + arrays: dict[str, np.ndarray], residual_m: np.ndarray, +) -> dict[str, np.ndarray]: + coarse_translation = arrays["coarse_translation_m"] + target_translation = arrays["target_translation_m"] + coarse_joints = arrays["coarse_joints_m"] + target_joints = arrays["target_joints_m"] + refined_translation = coarse_translation.copy() + refined_translation[:, 2] += residual_m + refined_joints = coarse_joints.copy() + refined_joints[:, :, 2] += residual_m[:, None] + joint_error = np.linalg.norm(refined_joints - target_joints, axis=-1) * 1000.0 + relative_prediction = refined_joints - refined_joints[:, :1] + relative_target = target_joints - target_joints[:, :1] + relative_error = np.linalg.norm(relative_prediction - relative_target, axis=-1) * 1000.0 + translation_error = (refined_translation - target_translation) * 1000.0 + projected, positive = project_points(refined_joints, arrays["K_resized"]) + if not bool(positive.all()): + raise ValueError("A1 refined MANO joints project behind the camera") + target_2d = arrays["target_joints_2d_px"] + direct_2d = arrays["direct_joints_2d_px"] + return { + "absolute_mpjpe_mm": joint_error.mean(axis=1), + "root_relative_mpjpe_mm": relative_error.mean(axis=1), + "fingertip_mpjpe_mm": joint_error[:, FINGERTIPS].mean(axis=1), + "translation_z_signed_error_mm": translation_error[:, 2], + "translation_z_mae_mm": np.abs(translation_error[:, 2]), + "direct_2d_error_px": np.linalg.norm(direct_2d - target_2d, axis=-1).mean(axis=1), + "mano_projected_2d_error_px": np.linalg.norm(projected - target_2d, axis=-1).mean(axis=1), + "direct_mano_consistency_px": np.linalg.norm(direct_2d - projected, axis=-1).mean(axis=1), + "residual_magnitude_mm": np.abs(residual_m) * 1000.0, + "predicted_wrist_xyz_m": refined_translation, + "predicted_joints_m": refined_joints, + } + + +def temporal_metrics( + metadata: list[dict[str, str]], + target_translation: np.ndarray, + predictions: dict[str, dict[str, np.ndarray]], +) -> dict[str, dict[str, np.ndarray]]: + groups: dict[tuple[str, str], list[int]] = defaultdict(list) + for index, row in enumerate(metadata): + groups[(row["take"], row["side"])].append(index) + output = { + variant: { + "wrist_velocity_error_mm_per_frame": [], + "wrist_acceleration_error_mm_per_frame2": [], + } + for variant in predictions + } + for indices in groups.values(): + ordered = sorted(indices, key=lambda index: int(metadata[index]["frame_id"])) + for position in range(1, len(ordered)): + previous, current = ordered[position - 1], ordered[position] + if int(metadata[current]["frame_id"]) != int(metadata[previous]["frame_id"]) + 1: + continue + target_velocity = target_translation[current] - target_translation[previous] + for variant, metrics in predictions.items(): + wrist = metrics["predicted_wrist_xyz_m"] + error = np.linalg.norm((wrist[current] - wrist[previous]) - target_velocity) * 1000.0 + output[variant]["wrist_velocity_error_mm_per_frame"].append(float(error)) + for position in range(2, len(ordered)): + first, second, third = ordered[position - 2 : position + 1] + frame_ids = [int(metadata[index]["frame_id"]) for index in (first, second, third)] + if frame_ids[1] != frame_ids[0] + 1 or frame_ids[2] != frame_ids[1] + 1: + continue + target_acceleration = target_translation[third] - 2 * target_translation[second] + target_translation[first] + for variant, metrics in predictions.items(): + wrist = metrics["predicted_wrist_xyz_m"] + acceleration = wrist[third] - 2 * wrist[second] + wrist[first] + error = np.linalg.norm(acceleration - target_acceleration) * 1000.0 + output[variant]["wrist_acceleration_error_mm_per_frame2"].append(float(error)) + return { + variant: {metric: np.asarray(values, dtype=np.float32) for metric, values in metrics.items()} + for variant, metrics in output.items() + } + + +def summarize_groups( + metadata: list[dict[str, str]], + variants: dict[str, dict[str, np.ndarray]], + temporal: dict[str, dict[str, np.ndarray]], + challenge: dict[str, Any], +) -> list[dict[str, object]]: + farthest = float(challenge["thresholds"]["farthest_observed_wrist_depth_p80_m"]) + challenge_clips = set(int(value) for value in challenge["clip_indices"]) + masks = { + "all": np.ones(len(metadata), dtype=bool), + "left": np.asarray([row["side"] == "left" for row in metadata]), + "right": np.asarray([row["side"] == "right" for row in metadata]), + "small": np.asarray([float(row["hand_size_px"]) < 64.0 for row in metadata]), + "farthest_observed": np.asarray([ + float(row["wrist_depth_m"]) >= farthest for row in metadata + ]), + "strong_asymmetry": np.asarray([ + row["bimanual_asymmetry_bucket"] == "strong" for row in metadata + ]), + "challenge": np.asarray([int(row["clip_index"]) in challenge_clips for row in metadata]), + } + rows: list[dict[str, object]] = [] + scalar_metrics = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", + ) + for group, mask in masks.items(): + for variant, metrics in variants.items(): + for metric in scalar_metrics: + rows.append({ + "group": group, + "variant": variant, + "metric": metric, + **distribution_summary(metrics[metric][mask]), + }) + for variant, metrics in temporal.items(): + for metric, values in metrics.items(): + rows.append({ + "group": "all_contiguous_transitions", + "variant": variant, + "metric": metric, + **distribution_summary(values), + }) + return rows + + +def paired_take_bootstrap( + metadata: list[dict[str, str]], + variants: dict[str, dict[str, np.ndarray]], + *, + seed: int, + samples: int, +) -> list[dict[str, object]]: + take_indices: dict[str, list[int]] = defaultdict(list) + for index, row in enumerate(metadata): + take_indices[row["take"]].append(index) + rng = np.random.default_rng(seed) + rows: list[dict[str, object]] = [] + comparisons = (("local", "coarse"), ("local", "control"), ("control", "coarse")) + metric_stats = ( + ("absolute_mpjpe_mm", "mean"), + ("translation_z_mae_mm", "mean"), + ("translation_z_mae_mm", "p95"), + ("fingertip_mpjpe_mm", "mean"), + ("mano_projected_2d_error_px", "mean"), + ) + take_names = sorted(take_indices) + for candidate, reference in comparisons: + for metric, statistic in metric_stats: + deltas = [] + for take in take_names: + indices = take_indices[take] + candidate_values = variants[candidate][metric][indices] + reference_values = variants[reference][metric][indices] + if statistic == "mean": + delta = float(candidate_values.mean() - reference_values.mean()) + else: + delta = float(np.percentile(candidate_values, 95) - np.percentile(reference_values, 95)) + deltas.append(delta) + deltas_array = np.asarray(deltas, dtype=np.float64) + bootstrap_indices = rng.integers(0, len(deltas_array), size=(samples, len(deltas_array))) + distribution = deltas_array[bootstrap_indices].mean(axis=1) + rows.append({ + "candidate": candidate, + "reference": reference, + "metric": metric, + "per_take_statistic": statistic, + "take_count": len(deltas_array), + "paired_delta_candidate_minus_reference": float(deltas_array.mean()), + "ci95_low": float(np.percentile(distribution, 2.5)), + "ci95_high": float(np.percentile(distribution, 97.5)), + "bootstrap_samples": samples, + "bootstrap_seed": seed, + }) + return rows + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--train-extraction", type=Path, required=True) + parser.add_argument("--validation-extraction", type=Path, required=True) + parser.add_argument("--challenge-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--fit-seed", type=int, default=4401) + parser.add_argument("--holdout-modulus", type=int, default=5) + parser.add_argument("--hidden-dim", type=int, default=128) + parser.add_argument("--max-residual-m", type=float, default=0.15) + parser.add_argument("--learning-rate", type=float, default=3e-3) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--batch-size", type=int, default=4096) + parser.add_argument("--epochs", type=int, default=80) + parser.add_argument("--patience", type=int, default=12) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + return parser.parse_args() + + +def load_extraction(path: Path) -> tuple[dict[str, np.ndarray], list[dict[str, str]], dict[str, Any]]: + report = json.loads((path / "extraction.json").read_text(encoding="utf-8")) + if report.get("official_test_used") is not False: + raise ValueError("A1 extraction does not explicitly preserve official-test isolation") + arrays = dict(np.load(path / "features.npz")) + rows = read_csv(path / "samples.csv") + if any(value.shape[0] != len(rows) for value in arrays.values()): + raise ValueError(f"array/CSV length mismatch in {path}") + return arrays, rows, report + + +def main() -> None: + args = parse_args() + output_files = ( + args.output_dir / "results.json", + args.output_dir / "group_metrics.csv", + args.output_dir / "validation_predictions.csv", + args.output_dir / "paired_take_bootstrap_ci.csv", + args.output_dir / "regressors.pt", + ) + if any(path.exists() for path in output_files): + raise FileExistsError(f"refusing to overwrite existing A1 result in {args.output_dir}") + train, train_rows, train_report = load_extraction(args.train_extraction) + validation, validation_rows, validation_report = load_extraction(args.validation_extraction) + if train_report["split_role"] != "official_train": + raise ValueError("A1 fitting requires official_train extraction") + if validation_report["split_role"] != "official_validation": + raise ValueError("A1 reporting requires official_validation extraction") + if train_report["checkpoint"]["sha256"] != validation_report["checkpoint"]["sha256"]: + raise ValueError("train/validation A1 extractions use different frozen checkpoints") + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + if challenge.get("checkpoint_selection_allowed") is not False: + raise ValueError("challenge subset is not registered as secondary-only") + + holdout_mask = stable_take_holdout( + [row["take"] for row in train_rows], modulus=args.holdout_modulus, + ) + train_mask = ~holdout_mask + local_dim = train["local"].shape[1] + train_features = { + "control": padded_control(train["control"], local_dim), + "local": train["local"], + } + validation_features = { + "control": padded_control(validation["control"], local_dim), + "local": validation["local"], + } + device = torch.device(f"cuda:{args.gpu}") + regressors: dict[str, BoundedZResidualRegressor] = {} + scalers: dict[str, tuple[np.ndarray, np.ndarray]] = {} + histories: dict[str, list[dict[str, float | int]]] = {} + for index, variant in enumerate(("control", "local")): + model, mean, std, history = fit_regressor( + train_features[variant], + train["target_residual_z_m"], + train_mask, + holdout_mask, + device=device, + seed=args.fit_seed + index, + hidden_dim=args.hidden_dim, + max_residual_m=args.max_residual_m, + learning_rate=args.learning_rate, + weight_decay=args.weight_decay, + batch_size=args.batch_size, + epochs=args.epochs, + patience=args.patience, + ) + regressors[variant] = model + scalers[variant] = (mean, std) + histories[variant] = history + + residuals = {"coarse": np.zeros(len(validation_rows), dtype=np.float32)} + for variant in ("control", "local"): + mean, std = scalers[variant] + residuals[variant] = infer_residual( + regressors[variant], validation_features[variant], mean, std, device, + ) + variants = { + variant: variant_metrics(validation, residual) + for variant, residual in residuals.items() + } + coarse_root = variants["coarse"]["root_relative_mpjpe_mm"] + coarse_direct = variants["coarse"]["direct_2d_error_px"] + for variant in ("control", "local"): + if not np.allclose(variants[variant]["root_relative_mpjpe_mm"], coarse_root, atol=1e-4): + raise AssertionError("uniform A1 z residual changed root-relative geometry") + if not np.array_equal(variants[variant]["direct_2d_error_px"], coarse_direct): + raise AssertionError("A1 residual changed the frozen direct-2D head") + + temporal = temporal_metrics( + validation_rows, validation["target_translation_m"], variants, + ) + group_rows = summarize_groups(validation_rows, variants, temporal, challenge) + bootstrap_rows = paired_take_bootstrap( + validation_rows, + variants, + seed=args.fit_seed, + samples=args.bootstrap_samples, + ) + prediction_rows: list[dict[str, object]] = [] + for index, metadata in enumerate(validation_rows): + row: dict[str, object] = dict(metadata) + for variant, metrics in variants.items(): + for metric in ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", + ): + row[f"{variant}_{metric}"] = float(metrics[metric][index]) + prediction_rows.append(row) + + def summary_value(group: str, variant: str, metric: str, statistic: str) -> float: + match = next( + row for row in group_rows + if row["group"] == group and row["variant"] == variant and row["metric"] == metric + ) + return float(match[statistic]) + + coarse_z_p95 = summary_value("all", "coarse", "translation_z_mae_mm", "p95") + local_z_p95 = summary_value("all", "local", "translation_z_mae_mm", "p95") + reductions = { + "full_validation_z_p95_percent": 100.0 * (coarse_z_p95 - local_z_p95) / coarse_z_p95, + } + for group in ("small", "farthest_observed", "right"): + coarse_value = summary_value(group, "coarse", "absolute_mpjpe_mm", "mean") + local_value = summary_value(group, "local", "absolute_mpjpe_mm", "mean") + reductions[f"{group}_absolute_mpjpe_percent"] = 100.0 * (coarse_value - local_value) / coarse_value + gate_metric = ( + reductions["full_validation_z_p95_percent"] >= 20.0 + or reductions["small_absolute_mpjpe_percent"] >= 15.0 + or reductions["farthest_observed_absolute_mpjpe_percent"] >= 15.0 + ) + gate_no_regression = True # Exact by construction and asserted above. + gate = { + "registered_condition": ( + "z P95 reduction >=20% OR small/farthest-observed absolute MPJPE reduction >=15%; " + "root-relative and direct-2D degradation <=2%" + ), + "metric_gate_pass": bool(gate_metric), + "no_regression_gate_pass": gate_no_regression, + "formal_A1_gate_pass": bool(gate_metric and gate_no_regression), + "depth_increment_condition": ( + "A2 additionally requires local-depth to retain meaningful improvement beyond the " + "same-capacity oracle-location control; reported but not silently assumed." + ), + "reductions_percent": reductions, + } + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "group_metrics.csv", group_rows) + write_csv(args.output_dir / "validation_predictions.csv", prediction_rows) + write_csv(args.output_dir / "paired_take_bootstrap_ci.csv", bootstrap_rows) + torch.save({ + "wave": "A1_oracle_local_depth", + "fit_seed": args.fit_seed, + "input_dim": local_dim, + "hidden_dim": args.hidden_dim, + "max_residual_m": args.max_residual_m, + "models": { + variant: {key: value.detach().cpu() for key, value in model.state_dict().items()} + for variant, model in regressors.items() + }, + "scalers": { + variant: {"mean": mean, "std": std} + for variant, (mean, std) in scalers.items() + }, + }, args.output_dir / "regressors.pt") + report = { + "status": "evaluated", + "phase": 4, + "wave": "A1_oracle_local_depth", + "official_test_used": False, + "frozen_checkpoint": validation_report["checkpoint"], + "train_manifest": train_report["manifest"], + "validation_manifest": validation_report["manifest"], + "challenge_manifest": { + "path": str(args.challenge_manifest.resolve()), + "sha256": sha256(args.challenge_manifest), + "role": "secondary diagnostic only; never checkpoint selection", + }, + "protocol": { + "fit_data": "official_train only", + "fit_holdout": ( + f"whole-take SHA256 modulus-{args.holdout_modulus} holdout within official_train" + ), + "validation": "complete official validation, one independent report", + "control": "same input dimension and MLP parameter count; local-depth fields zeroed", + "hidden_dim": args.hidden_dim, + "max_residual_m": args.max_residual_m, + "learning_rate": args.learning_rate, + "weight_decay": args.weight_decay, + "batch_size": args.batch_size, + "maximum_epochs": args.epochs, + "early_stopping_patience": args.patience, + "fit_seed": args.fit_seed, + }, + "sample_counts": { + "official_train_fit": int(train_mask.sum()), + "official_train_holdout": int(holdout_mask.sum()), + "official_validation": len(validation_rows), + }, + "parameter_counts": { + variant: sum(parameter.numel() for parameter in model.parameters()) + for variant, model in regressors.items() + }, + "histories": histories, + "gate": gate, + "outputs": { + "group_metrics": str((args.output_dir / "group_metrics.csv").resolve()), + "validation_predictions": str((args.output_dir / "validation_predictions.csv").resolve()), + "paired_take_bootstrap_ci": str((args.output_dir / "paired_take_bootstrap_ci.csv").resolve()), + "regressors": str((args.output_dir / "regressors.pt").resolve()), + }, + } + (args.output_dir / "results.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": "complete", "gate": gate, "output": str(args.output_dir)})) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase5_alignment_calibrator.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase5_alignment_calibrator.py new file mode 100644 index 0000000000000000000000000000000000000000..68eb72f652ec43cc343bed31e01e11a7f82287e7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase5_alignment_calibrator.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +"""Fit shared metric-alignment correction/confidence using OOF banks only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +import joblib +import numpy as np +from sklearn.linear_model import HuberRegressor, LogisticRegression +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler + +from foundation_hand.evaluation.alignment_calibration import FEATURE_NAMES, features_from_take + +THRESHOLD_GRID = (0.50, 0.60, 0.70, 0.80, 0.90, 0.95, 1.01) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_bank_layout( + manifests: list[dict[str, Any]], expected_banks_per_fold: int, +) -> dict[str, Any]: + if expected_banks_per_fold < 1: + raise ValueError("expected banks per fold must be positive") + observed_pairs: set[tuple[int, str]] = set() + observed_fold_seeds: set[tuple[int, int]] = set() + fold_counts: Counter[int] = Counter() + seed_folds: dict[int, set[int]] = defaultdict(set) + for manifest in manifests: + fold = int(manifest["fold"]) + checkpoint = str(manifest["checkpoint"]["sha256"]) + pair = (fold, checkpoint) + if pair in observed_pairs: + raise ValueError(f"duplicate OOF fold/checkpoint bank: {pair}") + observed_pairs.add(pair) + fold_counts[fold] += 1 + seed = manifest.get("seed") + if seed is None: + if expected_banks_per_fold > 1: + raise ValueError("expanded OOF banks require an explicit coarse seed") + continue + seed = int(seed) + fold_seed = (fold, seed) + if fold_seed in observed_fold_seeds: + raise ValueError(f"duplicate OOF fold/seed bank: {fold_seed}") + observed_fold_seeds.add(fold_seed) + seed_folds[seed].add(fold) + if set(fold_counts) != {0, 1, 2}: + raise ValueError(f"shared calibrator requires folds 0/1/2, got {set(fold_counts)}") + if any(fold_counts[fold] != expected_banks_per_fold for fold in range(3)): + raise ValueError( + "OOF bank count per fold differs from --expected-banks-per-fold: " + f"{dict(sorted(fold_counts.items()))}" + ) + if expected_banks_per_fold > 1: + if len(seed_folds) != expected_banks_per_fold: + raise ValueError( + f"expected {expected_banks_per_fold} coarse seeds, got {sorted(seed_folds)}" + ) + incomplete = {seed: sorted(folds) for seed, folds in seed_folds.items() if folds != {0, 1, 2}} + if incomplete: + raise ValueError(f"each coarse seed must cover folds 0/1/2: {incomplete}") + return { + "banks_per_fold": {str(fold): fold_counts[fold] for fold in range(3)}, + "coarse_seeds": sorted(seed_folds), + } + + +def load_bank( + bank_dirs: list[Path], expected_banks_per_fold: int = 1, +) -> dict[str, np.ndarray]: + chunks: dict[str, list[np.ndarray]] = { + key: [] for key in ( + "features", "target_residual_z_m", "raw_delta_z_m", "alignment_applied", + "pred_joints_m", "target_joints_m", "side", "hand_scale_px", + "frame_id", "subject", "take", "coarse_seed", "checkpoint", + ) + } + manifests = [] + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("bank_version") != 2 + or manifest.get("scope") != "full_fold" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("leakage_audit", {}).get("passed") is not True + or manifest.get("official_test_used") is not False + or manifest.get("official_validation_used_for_assignment") is not False + ): + raise ValueError(f"calibrator requires a complete leakage-free OOF bank: {bank_dir}") + manifests.append(manifest) + validate_bank_layout(manifests, expected_banks_per_fold) + for bank_dir, manifest in zip(bank_dirs, manifests, strict=True): + seed = int(manifest.get("seed", -1)) + checkpoint = str(manifest["checkpoint"]["sha256"]) + for take_record in manifest["takes"]: + with np.load(take_record["path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + time = len(arrays["frame_id"]) + features = features_from_take(arrays) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays[ + "frame_valid" + ][:, None].astype(bool) + hand_indices = np.broadcast_to(np.arange(2)[None], (time, 2)) + frame_ids = np.broadcast_to(arrays["frame_id"][:, None], (time, 2)) + chunks["features"].append(features[valid]) + chunks["target_residual_z_m"].append(arrays["translation_residual_m"][..., 2][valid]) + chunks["raw_delta_z_m"].append(arrays["alignment_delta_z_m"][valid]) + chunks["alignment_applied"].append(arrays["alignment_applied"][valid]) + chunks["pred_joints_m"].append(arrays["pred_joints_camera"][valid]) + chunks["target_joints_m"].append(arrays["target_joints_camera"][valid]) + chunks["side"].append(hand_indices[valid]) + chunks["hand_scale_px"].append(arrays["coarse_hand_scale_px"][valid]) + chunks["frame_id"].append(frame_ids[valid]) + chunks["subject"].append(np.full(valid.sum(), str(arrays["subject"]))) + chunks["take"].append(np.full(valid.sum(), str(arrays["take"]))) + chunks["coarse_seed"].append(np.full(valid.sum(), seed, dtype=np.int64)) + chunks["checkpoint"].append(np.full(valid.sum(), checkpoint)) + return {key: np.concatenate(values, axis=0) for key, values in chunks.items()} + + +def correction_metrics(samples: dict[str, np.ndarray], correction_m: np.ndarray) -> dict[str, float]: + correction = np.asarray(correction_m, dtype=np.float64) + pred_joints = samples["pred_joints_m"].astype(np.float64).copy() + pred_joints[..., 2] += correction[:, None] + target_joints = samples["target_joints_m"].astype(np.float64) + joint_error_mm = np.linalg.norm(pred_joints - target_joints, axis=-1) * 1000.0 + z_error_mm = np.abs(samples["target_residual_z_m"] - correction) * 1000.0 + p95 = float(np.percentile(z_error_mm, 95)) + return { + "absolute_mpjpe_mm": float(joint_error_mm.mean()), + "z_mae_mm": float(z_error_mm.mean()), + "z_p95_mm": p95, + "z_cvar95_mm": float(z_error_mm[z_error_mm >= p95].mean()), + } + + +def fit_regressor(features: np.ndarray, target: np.ndarray): + return make_pipeline( + StandardScaler(), + HuberRegressor(epsilon=1.35, alpha=1e-4, max_iter=400, tol=1e-5), + ).fit(features, target) + + +def fit_confidence(features: np.ndarray, helpful: np.ndarray): + if np.unique(helpful).size < 2: + raise ValueError("alignment helpfulness target has only one class") + return make_pipeline( + StandardScaler(), + LogisticRegression(max_iter=1000, class_weight="balanced", C=1.0), + ).fit(features, helpful) + + +def select_confidence_threshold( + samples: dict[str, np.ndarray], + calibrated_correction_m: np.ndarray, + confidence: np.ndarray, +) -> tuple[float, list[dict[str, float | bool]]]: + coarse = correction_metrics(samples, np.zeros(len(confidence))) + guardrail_mm = min(0.2, 0.01 * coarse["absolute_mpjpe_mm"]) + available = samples["alignment_applied"].astype(bool) + rows = [] + for threshold in THRESHOLD_GRID: + applied = available & (confidence >= threshold) + correction = np.where(applied, calibrated_correction_m, 0.0) + metrics = correction_metrics(samples, correction) + rows.append({ + "threshold": threshold, + "available_fraction": float(available.mean()), + "applied_fraction": float(applied.mean()), + **metrics, + "absolute_guardrail_passed": bool( + metrics["absolute_mpjpe_mm"] <= coarse["absolute_mpjpe_mm"] + guardrail_mm + ), + }) + eligible = [row for row in rows if row["absolute_guardrail_passed"]] + if not eligible: + return 1.01, rows + eligible.sort(key=lambda row: ( + float(row["absolute_mpjpe_mm"]), + float(row["z_p95_mm"]), + float(row["applied_fraction"]), + )) + return float(eligible[0]["threshold"]), rows + + +def write_predictions( + path: Path, + samples: dict[str, np.ndarray], + calibrated: np.ndarray, + confidence: np.ndarray, + threshold: float, +) -> None: + with path.open("x", newline="", encoding="utf-8") as handle: + fields = ( + "sample_index", "coarse_seed", "checkpoint_sha256", "subject", "take", "frame_id", "side", + "target_residual_z_mm", "raw_alignment_delta_z_mm", + "calibrated_delta_z_mm", "confidence", "alignment_available", "applied", + ) + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for index in range(len(calibrated)): + writer.writerow({ + "sample_index": index, + "coarse_seed": int(samples.get("coarse_seed", np.full(len(calibrated), -1))[index]), + "checkpoint_sha256": str(samples.get("checkpoint", np.full(len(calibrated), ""))[index]), + "subject": samples["subject"][index], + "take": samples["take"][index], + "frame_id": int(samples["frame_id"][index]), + "side": "right" if int(samples["side"][index]) else "left", + "target_residual_z_mm": 1000.0 * samples["target_residual_z_m"][index], + "raw_alignment_delta_z_mm": 1000.0 * samples["raw_delta_z_m"][index], + "calibrated_delta_z_mm": 1000.0 * calibrated[index], + "confidence": confidence[index], + "alignment_available": bool(samples["alignment_applied"][index]), + "applied": bool( + samples["alignment_applied"][index] + and confidence[index] >= threshold + ), + }) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--expected-banks-per-fold", type=int, default=1) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("calibrator output directory must be new or empty") + samples = load_bank(args.bank_dir, args.expected_banks_per_fold) + features = samples["features"] + target = samples["target_residual_z_m"].astype(np.float64) + raw_delta = samples["raw_delta_z_m"].astype(np.float64) + available = samples["alignment_applied"].astype(bool) + subjects = samples["subject"] + cv_correction = np.zeros_like(target) + cv_confidence = np.zeros_like(target) + fold_records = [] + for heldout_subject in sorted(set(subjects.tolist())): + heldout = subjects == heldout_subject + train = ~heldout + regressor = fit_regressor(features[train], target[train]) + helpful = available[train] & ( + np.abs(target[train] - raw_delta[train]) < np.abs(target[train]) + ) + confidence_model = fit_confidence(features[train], helpful) + cv_correction[heldout] = np.clip(regressor.predict(features[heldout]), -0.12, 0.12) + cv_confidence[heldout] = confidence_model.predict_proba(features[heldout])[:, 1] + fold_records.append({ + "heldout_subject": heldout_subject, + "train_samples": int(train.sum()), + "heldout_samples": int(heldout.sum()), + "raw_helpful_fraction_train": float(helpful.mean()), + }) + threshold, threshold_rows = select_confidence_threshold( + samples, cv_correction, cv_confidence, + ) + raw_available = np.where(available, raw_delta, 0.0) + calibrated_available = np.where(available, cv_correction, 0.0) + selected_correction = np.where( + available & (cv_confidence >= threshold), cv_correction, 0.0, + ) + metrics = { + "coarse": correction_metrics(samples, np.zeros_like(target)), + "robust_alignment_unscaled": correction_metrics(samples, raw_available), + "calibrated_always": correction_metrics(samples, calibrated_available), + "calibrated_confidence": correction_metrics(samples, selected_correction), + } + corrections = { + "coarse": np.zeros_like(target), + "robust_alignment_unscaled": raw_available, + "calibrated_always": calibrated_available, + "calibrated_confidence": selected_correction, + } + metrics_by_seed = {} + for seed in sorted(set(samples["coarse_seed"].tolist())): + if int(seed) < 0: + continue + mask = samples["coarse_seed"] == seed + subset = { + key: value[mask] + for key, value in samples.items() + if key in ("target_residual_z_m", "pred_joints_m", "target_joints_m") + } + metrics_by_seed[str(int(seed))] = { + condition: correction_metrics(subset, correction[mask]) + for condition, correction in corrections.items() + } + + final_regressor = fit_regressor(features, target) + final_helpful = available & (np.abs(target - raw_delta) < np.abs(target)) + final_confidence = fit_confidence(features, final_helpful) + args.output_dir.mkdir(parents=True, exist_ok=True) + model_path = args.output_dir / "alignment_calibrator.joblib" + joblib.dump({ + "version": "phase5_oof_alignment_calibrator_v1", + "feature_names": FEATURE_NAMES, + "regressor": final_regressor, + "confidence": final_confidence, + "confidence_threshold": threshold, + "correction_bound_m": 0.12, + }, model_path) + predictions_path = args.output_dir / "oof_calibration_predictions.csv" + write_predictions( + predictions_path, samples, cv_correction, cv_confidence, threshold, + ) + report = { + "status": "fitted", + "experiment_class": "preregistered_oof_calibration", + "result_role": "train_oof_cross_validated_threshold_selection", + "official_validation_used": False, + "official_test_used": False, + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "expected_banks_per_fold": args.expected_banks_per_fold, + "coarse_seeds": sorted({int(seed) for seed in samples["coarse_seed"] if int(seed) >= 0}), + "samples": len(target), + "subjects": sorted(set(subjects.tolist())), + "features": list(FEATURE_NAMES), + "leave_one_subject_out": fold_records, + "confidence_target": "available raw robust delta reduces absolute wrist-z error", + "threshold_grid": list(THRESHOLD_GRID), + "selected_threshold": threshold, + "threshold_selection_rule": "minimize OOF absolute MPJPE among <=min(0.2mm,1%) guardrail candidates; tie-break z P95 then lower apply fraction", + "threshold_rows": threshold_rows, + "metrics": metrics, + "metrics_by_seed": metrics_by_seed, + "model": {"path": str(model_path.resolve()), "sha256": sha256(model_path)}, + "predictions": {"path": str(predictions_path.resolve()), "sha256": sha256(predictions_path)}, + } + (args.output_dir / "calibration.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "samples": report["samples"], + "selected_threshold": threshold, "metrics": metrics, + "official_validation_used": False, "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase5_causal_state.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase5_causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..bf8459c36303256261ef7ad38e7a1f322f501a9f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase5_causal_state.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Select causal translation-z state parameters using train OOF sequences only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.causal_state import ( + causal_constant_velocity_kalman, + measurement_uncertainty_multiplier, +) + + +PROCESS_SIGMAS = (0.002, 0.005, 0.01, 0.02, 0.05) +MEASUREMENT_SIGMAS = (0.0025, 0.005, 0.01, 0.02) +UNCERTAINTY_STRENGTHS = (0.5, 1.0, 2.0) +GUARDRAIL_MM = 0.2 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_calibration_predictions(path: Path) -> dict[tuple[str, int, str], dict[str, float | bool]]: + output = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + key = (row["take"], int(row["frame_id"]), row["side"]) + if key in output: + raise ValueError(f"duplicate OOF calibration prediction: {key}") + output[key] = { + "calibrated_delta_z_m": float(row["calibrated_delta_z_mm"]) / 1000.0, + "confidence": float(row["confidence"]), + "available": row["alignment_available"] == "True", + } + return output + + +def load_sequences( + bank_dirs: list[Path], prediction_csv: Path, +) -> tuple[list[dict[str, np.ndarray]], list[dict[str, Any]]]: + predictions = read_calibration_predictions(prediction_csv) + sequences = [] + manifests = [] + consumed: set[tuple[str, int, str]] = set() + for bank_dir in bank_dirs: + manifest_path = bank_dir / "bank_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("bank_version") != 2 + or manifest.get("scope") != "full_fold" + or manifest.get("official_test_used") is not False + ): + raise ValueError(f"invalid OOF bank: {bank_dir}") + manifests.append(manifest) + for record in manifest["takes"]: + with np.load(record["path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + time = len(arrays["frame_id"]) + calibrated = np.zeros((time, 2), dtype=np.float32) + confidence = np.zeros((time, 2), dtype=np.float32) + available = np.zeros((time, 2), dtype=bool) + prediction_present = np.zeros((time, 2), dtype=bool) + for index, frame_id in enumerate(arrays["frame_id"]): + for hand, side in enumerate(("left", "right")): + key = (str(arrays["take"]), int(frame_id), side) + if key not in predictions: + continue + row = predictions[key] + calibrated[index, hand] = float(row["calibrated_delta_z_m"]) + confidence[index, hand] = float(row["confidence"]) + available[index, hand] = bool(row["available"]) + prediction_present[index, hand] = True + consumed.add(key) + expected = arrays["mano_annotation_valid"].astype(bool) & arrays[ + "frame_valid" + ][:, None].astype(bool) + if np.any(expected & ~prediction_present): + raise ValueError(f"missing OOF calibration rows for {arrays['take']}") + uncertainty_base = measurement_uncertainty_multiplier( + confidence, + arrays["alignment_inlier_ratio"], + arrays["alignment_residual_scale_m"], + arrays["alignment_valid_fraction"], + arrays["alignment_conditioning_quality"], + 1.0, + ) + uncertainty_base = np.where(available, uncertainty_base, 5.0) + sequences.append({ + "take": np.asarray(arrays["take"]), + "clip_index": arrays["clip_index"], + "frame_id": arrays["frame_id"], + "frame_valid": arrays["frame_valid"].astype(bool), + "hand_valid": expected, + "coarse_z_m": arrays["pred_wrist_translation"][..., 2], + "measurement_z_m": arrays["pred_wrist_translation"][..., 2] + np.where( + available, calibrated, 0.0, + ), + "target_z_m": arrays["target_wrist_translation"][..., 2], + "pred_joints_m": arrays["pred_joints_camera"], + "target_joints_m": arrays["target_joints_camera"], + # The deployable coarse model remains a measurement even when + # local Depth/K alignment is unavailable. In that case the + # correction falls back to zero and uncertainty is maximal. + "measurement_available": np.broadcast_to( + arrays["frame_valid"][:, None].astype(bool), (time, 2), + ).copy(), + "alignment_available": available, + "uncertainty_multiplier_base": uncertainty_base, + }) + if consumed != set(predictions): + raise ValueError("OOF calibration predictions do not exactly match bank samples") + return sequences, manifests + + +def summarize_filter( + sequences: list[dict[str, np.ndarray]], + *, + process_sigma: float | None, + measurement_sigma: float | None, + uncertainty_strength: float, +) -> dict[str, float]: + absolute = [] + z_error = [] + velocity_error = [] + acceleration_error = [] + predicted_acceleration = [] + predicted_jerk = [] + for arrays in sequences: + measurement = arrays["measurement_z_m"] + if process_sigma is None or measurement_sigma is None: + filtered = measurement + else: + base = arrays["uncertainty_multiplier_base"] + multiplier = 1.0 + uncertainty_strength * (base - 1.0) + filtered, _ = causal_constant_velocity_kalman( + measurement, + frame_id=arrays["frame_id"], + segment_id=arrays["clip_index"], + valid=arrays["frame_valid"], + measurement_available=arrays["measurement_available"], + process_sigma_m_per_frame2=process_sigma, + measurement_sigma_m=measurement_sigma, + uncertainty_multiplier=multiplier, + ) + correction = filtered - arrays["coarse_z_m"] + joints = arrays["pred_joints_m"].astype(np.float64).copy() + joints[..., 2] += correction[..., None] + valid = arrays["hand_valid"] + joint_error = np.linalg.norm(joints - arrays["target_joints_m"], axis=-1).mean(axis=-1) + absolute.extend((joint_error[valid] * 1000.0).tolist()) + z_error.extend((np.abs(filtered - arrays["target_z_m"])[valid] * 1000.0).tolist()) + contiguous = ( + (arrays["frame_id"][1:] == arrays["frame_id"][:-1] + 1) + & (arrays["clip_index"][1:] == arrays["clip_index"][:-1]) + ) + for hand in range(2): + pair_valid = contiguous & valid[1:, hand] & valid[:-1, hand] + pred_velocity = np.diff(filtered[:, hand]) + target_velocity = np.diff(arrays["target_z_m"][:, hand]) + velocity_error.extend((np.abs(pred_velocity - target_velocity)[pair_valid] * 1000.0).tolist()) + if len(filtered) < 3: + continue + triple_valid = pair_valid[1:] & pair_valid[:-1] + pred_acceleration = np.diff(filtered[:, hand], n=2) + target_acceleration = np.diff(arrays["target_z_m"][:, hand], n=2) + acceleration_error.extend((np.abs(pred_acceleration - target_acceleration)[triple_valid] * 1000.0).tolist()) + predicted_acceleration.extend((np.abs(pred_acceleration)[triple_valid] * 1000.0).tolist()) + if len(filtered) >= 4: + quad_valid = triple_valid[1:] & triple_valid[:-1] + jerk = np.diff(filtered[:, hand], n=3) + predicted_jerk.extend((np.abs(jerk)[quad_valid] * 1000.0).tolist()) + absolute_array = np.asarray(absolute) + z_array = np.asarray(z_error) + return { + "absolute_mpjpe_mm": float(absolute_array.mean()), + "z_mae_mm": float(z_array.mean()), + "z_p95_mm": float(np.percentile(z_array, 95)), + "velocity_error_mm_per_frame": float(np.mean(velocity_error)), + "acceleration_error_mm_per_frame2": float(np.mean(acceleration_error)), + "predicted_acceleration_mm_per_frame2": float(np.mean(predicted_acceleration)), + "predicted_jerk_mm_per_frame3": float(np.mean(predicted_jerk)), + } + + +def select_candidate(rows: list[dict[str, Any]], baseline: dict[str, float]) -> dict[str, Any]: + eligible = [ + row for row in rows + if float(row["absolute_mpjpe_mm"]) <= baseline["absolute_mpjpe_mm"] + GUARDRAIL_MM + and float(row["z_mae_mm"]) <= baseline["z_mae_mm"] + GUARDRAIL_MM + and float(row["z_p95_mm"]) <= baseline["z_p95_mm"] + GUARDRAIL_MM + ] + if not eligible: + raise ValueError("no causal-state candidate passes the OOF static guardrails") + return min(eligible, key=lambda row: ( + float(row["predicted_acceleration_mm_per_frame2"]), + float(row["acceleration_error_mm_per_frame2"]), + float(row["velocity_error_mm_per_frame"]), + float(row["absolute_mpjpe_mm"]), + )) + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--bank-dir", type=Path, action="append", required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("causal-state output directory must be new or empty") + sequences, manifests = load_sequences(args.bank_dir, args.calibration_predictions) + baseline = summarize_filter( + sequences, process_sigma=None, measurement_sigma=None, uncertainty_strength=0.0, + ) + rows = [] + for process_sigma in PROCESS_SIGMAS: + for measurement_sigma in MEASUREMENT_SIGMAS: + for family, strengths in ( + ("fixed_kalman", (0.0,)), + ("uncertainty_kalman", UNCERTAINTY_STRENGTHS), + ): + for strength in strengths: + rows.append({ + "family": family, + "process_sigma_m_per_frame2": process_sigma, + "measurement_sigma_m": measurement_sigma, + "uncertainty_strength": strength, + **summarize_filter( + sequences, + process_sigma=process_sigma, + measurement_sigma=measurement_sigma, + uncertainty_strength=strength, + ), + }) + selected = { + family: select_candidate( + [row for row in rows if row["family"] == family], baseline, + ) + for family in ("fixed_kalman", "uncertainty_kalman") + } + args.output_dir.mkdir(parents=True, exist_ok=True) + grid_path = args.output_dir / "causal_state_oof_grid.csv" + write_csv(grid_path, rows) + report = { + "status": "selected", + "experiment_class": "train_oof_causal_state_selection", + "official_validation_used": False, + "official_test_used": False, + "bank_manifests": [ + {"path": str((path / "bank_manifest.json").resolve()), "sha256": sha256(path / "bank_manifest.json")} + for path in args.bank_dir + ], + "calibration_predictions": { + "path": str(args.calibration_predictions.resolve()), + "sha256": sha256(args.calibration_predictions), + }, + "sequences": len(sequences), + "baseline_calibrated_per_frame": baseline, + "guardrail_mm": GUARDRAIL_MM, + "selection_rule": "within +0.2 mm OOF Absolute/z-MAE/z-P95 guardrails, minimize predicted acceleration then acceleration error, velocity error, and Absolute MPJPE", + "measurement_contract": "coarse z is always the causal measurement on valid frames; unavailable local alignment applies zero correction with maximum uncertainty", + "selected": selected, + "grid": {"path": str(grid_path.resolve()), "sha256": sha256(grid_path), "rows": len(rows)}, + } + (args.output_dir / "causal_state_selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({"status": report["status"], "selected": selected}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase6_harm_risk.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase6_harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..ebfa2bd15ba7b93b4781f9835dd9f649c8e8904c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/fit_phase6_harm_risk.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python3 +"""Fit the preregistered OOF-only Phase 6 harmful-correction risk model.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +import joblib +import numpy as np +from sklearn.ensemble import HistGradientBoostingClassifier, HistGradientBoostingRegressor +from sklearn.metrics import brier_score_loss, roc_auc_score +from sklearn.model_selection import GroupKFold + +from foundation_hand.evaluation.mixed_projection import coarse_wrist_ray_translation + + +FEATURE_NAMES = ( + "calibrated_delta_z_m", "abs_calibrated_delta_z_m", + "raw_delta_z_m", "abs_raw_delta_z_m", "raw_calibrated_disagreement_m", + "existing_confidence", "alignment_available", "raw_alignment_available", + "valid_support_count", "projected_support_count", "inlier_ratio", + "residual_scale_m", "valid_fraction", "foreground_fraction", + "background_fraction", "depth_discontinuity_m", "conditioning_quality", + "silhouette_overlap_fraction", "coarse_hand_scale_px", + "coarse_direct_mano_consistency_px", "coarse_z_m", "coarse_ray_x", + "coarse_ray_y", "coarse_wrist_velocity_norm_m_per_frame", + "predicted_depth_order", "side_right", +) +GAIN_THRESHOLDS_MM = (-0.5, 0.0, 0.25, 0.5, 1.0, 2.0) +HARM_THRESHOLDS = (0.2, 0.3, 0.4, 0.5, 0.6) +SEED = 20260717 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_calibration_predictions( + path: Path, +) -> dict[tuple[int, str, int, int], tuple[float, float, bool]]: + lookup = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + hand = 1 if row["side"] == "right" else 0 + key = (int(row["coarse_seed"]), row["take"], int(row["frame_id"]), hand) + if key in lookup: + raise ValueError(f"duplicate calibration prediction: {key}") + lookup[key] = ( + float(row["calibrated_delta_z_mm"]) / 1000.0, + float(row["confidence"]), row["alignment_available"] == "True", + ) + if len(lookup) != 333_936: + raise ValueError(f"calibration prediction coverage changed: {len(lookup)}") + return lookup + + +def harm_cvar95( + coarse_absolute_mm: np.ndarray, + corrected_absolute_mm: np.ndarray, + applied: np.ndarray, +) -> float: + harm = np.where( + applied, np.maximum(corrected_absolute_mm - coarse_absolute_mm, 0.0), 0.0, + ) + threshold = np.percentile(harm, 95) + return float(harm[harm >= threshold].mean()) + + +def evaluate_policy( + *, + coarse_absolute_mm: np.ndarray, + corrected_absolute_mm: np.ndarray, + applied: np.ndarray, + seed_take_groups: np.ndarray, +) -> dict[str, float]: + final = np.where(applied, corrected_absolute_mm, coarse_absolute_mm) + by_group: dict[str, list[float]] = defaultdict(list) + coarse_by_group: dict[str, list[float]] = defaultdict(list) + for group, value, coarse in zip( + seed_take_groups, final, coarse_absolute_mm, strict=True, + ): + by_group[str(group)].append(float(value)) + coarse_by_group[str(group)].append(float(coarse)) + group_values = {key: float(np.mean(values)) for key, values in by_group.items()} + take_deltas = np.asarray([ + group_values[key] - float(np.mean(coarse_by_group[key])) for key in group_values + ]) + return { + "coverage": float(applied.mean()), + "absolute_frame_mean_mm": float(final.mean()), + "absolute_take_mean_mm": float(np.mean(list(group_values.values()))), + "harm_fraction_gt_0p5mm": float( + (applied & ((corrected_absolute_mm - coarse_absolute_mm) > 0.5)).mean() + ), + "harm_cvar95_mm": harm_cvar95( + coarse_absolute_mm, corrected_absolute_mm, applied, + ), + "worst_seed_take_harm_mm": float(take_deltas.max()), + } + + +def models() -> tuple[HistGradientBoostingRegressor, HistGradientBoostingClassifier]: + common = dict( + max_iter=150, learning_rate=0.05, max_depth=3, + min_samples_leaf=40, l2_regularization=1.0, + early_stopping=False, random_state=SEED, + ) + return HistGradientBoostingRegressor(**common), HistGradientBoostingClassifier(**common) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--calibration-json", type=Path, required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + calibration_report = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration_report.get("status") != "fitted" + or calibration_report.get("official_validation_used") is not False + or calibration_report.get("official_test_used") is not False + or calibration_report.get("samples") != 333_936 + or calibration_report.get("predictions", {}).get("sha256") + != sha256(args.calibration_predictions) + ): + raise ValueError("expanded OOF calibration contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + calibration = load_calibration_predictions(args.calibration_predictions) + + feature_chunks = [] + gain_chunks = [] + coarse_chunks = [] + corrected_chunks = [] + available_chunks = [] + physical_groups = [] + seed_take_groups = [] + sample_rows = [] + bank_records = [] + for bank_index, registered in enumerate(calibration_report["bank_manifests"], start=1): + manifest_path = Path(registered["path"]) + if sha256(manifest_path) != registered["sha256"]: + raise ValueError(f"bank manifest hash mismatch: {manifest_path}") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("official_test_used") is not False + or manifest.get("leakage_audit", {}).get("passed") is not True + ): + raise ValueError(f"bank isolation contract failed: {manifest_path}") + seed = int(manifest["seed"]) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + needed = ( + "frame_id", "frame_valid", "pred_wrist_translation", + "pred_joints_camera", "target_joints_camera", + "mano_annotation_valid", "alignment_delta_z_m", "alignment_applied", + "alignment_valid_support_count", "alignment_projected_support_count", + "alignment_inlier_ratio", "alignment_residual_scale_m", + "alignment_valid_fraction", "alignment_foreground_fraction", + "alignment_background_fraction", "alignment_depth_discontinuity_m", + "alignment_conditioning_quality", "silhouette_overlap_fraction", + "coarse_hand_scale_px", "coarse_direct_mano_consistency_px", + "coarse_wrist_velocity_m_per_frame", "predicted_depth_order", + ) + arrays = {key: archive[key] for key in needed} + take = str(archive["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + time_index, hand = np.where(valid) + count = len(time_index) + calibrated = np.zeros(count, dtype=np.float64) + confidence = np.zeros(count, dtype=np.float64) + available = np.zeros(count, dtype=bool) + for index, (time_value, hand_value) in enumerate( + zip(time_index, hand, strict=True), + ): + key = (seed, take, int(arrays["frame_id"][time_value]), int(hand_value)) + calibrated[index], confidence[index], available[index] = calibration[key] + raw = arrays["alignment_delta_z_m"][time_index, hand].astype(np.float64) + raw_available = arrays["alignment_applied"][time_index, hand].astype(bool) + calibrated = np.where(available, calibrated, 0.0) + raw = np.where(raw_available, raw, 0.0) + coarse_translation = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + coarse_joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + target_joints = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + corrected_translation = coarse_wrist_ray_translation( + coarse_translation, coarse_translation[:, 2] + calibrated, + ) + corrected_joints = coarse_joints + ( + corrected_translation - coarse_translation + )[:, None] + coarse_absolute = np.linalg.norm(coarse_joints - target_joints, axis=-1).mean(axis=1) * 1000.0 + corrected_absolute = np.linalg.norm( + corrected_joints - target_joints, axis=-1, + ).mean(axis=1) * 1000.0 + gain = coarse_absolute - corrected_absolute + z = np.maximum(coarse_translation[:, 2], 1e-6) + overlap = arrays["silhouette_overlap_fraction"][time_index] + depth_order = arrays["predicted_depth_order"][time_index] + velocity = arrays["coarse_wrist_velocity_m_per_frame"][time_index, hand] + features = np.column_stack(( + calibrated, np.abs(calibrated), raw, np.abs(raw), np.abs(raw - calibrated), + confidence, available, raw_available, + arrays["alignment_valid_support_count"][time_index, hand], + arrays["alignment_projected_support_count"][time_index, hand], + arrays["alignment_inlier_ratio"][time_index, hand], + arrays["alignment_residual_scale_m"][time_index, hand], + arrays["alignment_valid_fraction"][time_index, hand], + arrays["alignment_foreground_fraction"][time_index, hand], + arrays["alignment_background_fraction"][time_index, hand], + arrays["alignment_depth_discontinuity_m"][time_index, hand], + arrays["alignment_conditioning_quality"][time_index, hand], overlap, + arrays["coarse_hand_scale_px"][time_index, hand], + arrays["coarse_direct_mano_consistency_px"][time_index, hand], + coarse_translation[:, 2], coarse_translation[:, 0] / z, + coarse_translation[:, 1] / z, np.linalg.norm(velocity, axis=1), + depth_order, hand.astype(np.float64), + )).astype(np.float32) + features = np.nan_to_num(features, nan=0.0, posinf=1e6, neginf=-1e6) + feature_chunks.append(features) + gain_chunks.append(gain.astype(np.float32)) + coarse_chunks.append(coarse_absolute.astype(np.float32)) + corrected_chunks.append(corrected_absolute.astype(np.float32)) + available_chunks.append(available) + physical_groups.extend([take] * count) + seed_take_groups.extend([f"{seed}:{take}"] * count) + sample_rows.extend({ + "coarse_seed": seed, "take": take, + "frame_id": int(arrays["frame_id"][time_value]), + "side": "right" if hand_value else "left", + } for time_value, hand_value in zip(time_index, hand, strict=True)) + bank_records.append({ + "path": str(manifest_path), "sha256": registered["sha256"], + "seed": seed, "fold": int(manifest["fold"]), + }) + print(f"[{bank_index}/9] fold{manifest['fold']} seed{seed} loaded", flush=True) + + X = np.concatenate(feature_chunks) + gain = np.concatenate(gain_chunks) + coarse_absolute = np.concatenate(coarse_chunks) + corrected_absolute = np.concatenate(corrected_chunks) + available = np.concatenate(available_chunks) + groups = np.asarray(physical_groups) + seed_take = np.asarray(seed_take_groups) + if X.shape != (333_936, len(FEATURE_NAMES)) or len(set(zip( + (row["coarse_seed"] for row in sample_rows), + (row["take"] for row in sample_rows), + (row["frame_id"] for row in sample_rows), + (row["side"] for row in sample_rows), + ))) != len(sample_rows): + raise ValueError("OOF feature coverage or uniqueness changed") + + harmful = gain < -0.5 + harm_magnitude = np.maximum(-gain, 0.0) + regression_weight = 1.0 + 4.0 * np.minimum(harm_magnitude / 10.0, 5.0) + classifier_weight = 1.0 + 8.0 * np.minimum(harm_magnitude / 10.0, 5.0) + predicted_gain = np.zeros_like(gain) + predicted_harm = np.zeros_like(gain) + fold_id = np.full(len(gain), -1, dtype=np.int8) + splitter = GroupKFold(n_splits=5) + for fold, (train, heldout) in enumerate(splitter.split(X, gain, groups), start=0): + regressor, classifier = models() + regressor.fit(X[train], gain[train], sample_weight=regression_weight[train]) + classifier.fit(X[train], harmful[train], sample_weight=classifier_weight[train]) + predicted_gain[heldout] = regressor.predict(X[heldout]) + predicted_harm[heldout] = classifier.predict_proba(X[heldout])[:, 1] + fold_id[heldout] = fold + print(f"cross-fit {fold + 1}/5: {len(heldout)} held-out samples", flush=True) + if np.any(fold_id < 0): + raise AssertionError("cross-fitting omitted samples") + + coarse_policy = evaluate_policy( + coarse_absolute_mm=coarse_absolute, corrected_absolute_mm=corrected_absolute, + applied=np.zeros_like(available), seed_take_groups=seed_take, + ) + always_policy = evaluate_policy( + coarse_absolute_mm=coarse_absolute, corrected_absolute_mm=corrected_absolute, + applied=available, seed_take_groups=seed_take, + ) + grid_rows = [] + for gain_threshold in GAIN_THRESHOLDS_MM: + for harm_threshold in HARM_THRESHOLDS: + applied = available & (predicted_gain >= gain_threshold) & ( + predicted_harm <= harm_threshold + ) + row = { + "expected_gain_threshold_mm": gain_threshold, + "harm_probability_threshold": harm_threshold, + **evaluate_policy( + coarse_absolute_mm=coarse_absolute, + corrected_absolute_mm=corrected_absolute, + applied=applied, seed_take_groups=seed_take, + ), + } + row["absolute_delta_vs_always_mm"] = ( + row["absolute_take_mean_mm"] - always_policy["absolute_take_mean_mm"] + ) + row["harm_cvar_reduction_fraction"] = 1.0 - ( + row["harm_cvar95_mm"] / max(always_policy["harm_cvar95_mm"], 1e-12) + ) + row["admission_passed"] = bool( + row["absolute_delta_vs_always_mm"] <= 0.1 + and row["coverage"] >= 0.2 + and row["harm_cvar_reduction_fraction"] >= 0.2 + ) + grid_rows.append(row) + eligible = [row for row in grid_rows if row["admission_passed"]] + eligible.sort(key=lambda row: ( + row["absolute_take_mean_mm"], row["harm_cvar95_mm"], + row["worst_seed_take_harm_mm"], row["coverage"], + )) + selected = eligible[0] if eligible else None + + final_regressor, final_classifier = models() + final_regressor.fit(X, gain, sample_weight=regression_weight) + final_classifier.fit(X, harmful, sample_weight=classifier_weight) + package_path = args.output_dir / "harm_risk_package.joblib" + joblib.dump({ + "version": "phase6_harm_risk_v1", + "feature_names": FEATURE_NAMES, + "regressor": final_regressor, + "classifier": final_classifier, + "selected_thresholds": None if selected is None else { + "expected_gain_threshold_mm": selected["expected_gain_threshold_mm"], + "harm_probability_threshold": selected["harm_probability_threshold"], + }, + "harm_definition_mm": 0.5, + "seed": SEED, + }, package_path) + + prediction_rows = [] + for index, identity in enumerate(sample_rows): + prediction_rows.append({ + "sample_index": index, **identity, "cv_fold": int(fold_id[index]), + "coarse_absolute_mpjpe_mm": float(coarse_absolute[index]), + "corrected_absolute_mpjpe_mm": float(corrected_absolute[index]), + "realized_gain_mm": float(gain[index]), + "predicted_gain_mm": float(predicted_gain[index]), + "harmful_gt_0p5mm": bool(harmful[index]), + "predicted_harm_probability": float(predicted_harm[index]), + "alignment_available": bool(available[index]), + }) + write_csv(args.output_dir / "cross_fitted_predictions.csv", prediction_rows) + write_csv(args.output_dir / "threshold_grid.csv", grid_rows) + report = { + "status": "admitted_for_one_frozen_validation" if selected is not None else "rejected_oof_gate", + "experiment": "P6_S3_harm_aware_risk_gate", + "experiment_class": "exploratory_oof_only_cross_fitted_risk_model", + "official_validation_used": False, + "official_test_used": False, + "oracle_information_at_inference": False, + "samples": len(X), "physical_takes": len(set(groups)), + "seed_take_groups": len(set(seed_take)), "features": list(FEATURE_NAMES), + "cross_validation": "5-fold GroupKFold by physical take across coarse seeds", + "cross_fitted_gain_mae_mm": float(np.mean(np.abs(predicted_gain - gain))), + "cross_fitted_harm_brier": float(brier_score_loss(harmful, predicted_harm)), + "cross_fitted_harm_roc_auc": float(roc_auc_score(harmful, predicted_harm)), + "coarse_policy": coarse_policy, "always_policy": always_policy, + "selected": selected, "eligible_conditions": len(eligible), + "package": {"path": str(package_path), "sha256": sha256(package_path)}, + "calibration": { + "json": str(args.calibration_json.resolve()), + "json_sha256": sha256(args.calibration_json), + "predictions": str(args.calibration_predictions.resolve()), + "predictions_sha256": sha256(args.calibration_predictions), + }, + "banks": bank_records, + "outputs": { + "threshold_grid": "threshold_grid.csv", + "cross_fitted_predictions": "cross_fitted_predictions.csv", + }, + } + (args.output_dir / "risk_selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "selected": selected, + "gain_mae_mm": report["cross_fitted_gain_mae_mm"], + "harm_auc": report["cross_fitted_harm_roc_auc"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/freeze_phase7_h2o_adaptation_validation.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/freeze_phase7_h2o_adaptation_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..2298467e46db7bcb7e74db4bb2211252cb82a353 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/freeze_phase7_h2o_adaptation_validation.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Freeze a train-heldout-selected adaptation candidate before H2O validation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_external import sha256 +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES + + +def build_freeze_record(selection_path: Path, validation_manifest: Path) -> dict[str, Any]: + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if ( + selection.get("status") != "selected_h2o_adaptation_train_group_heldout" + or selection.get("selection_split") != "h2o_train_group_heldout_only" + or selection.get("h2o_official_validation_used") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("adaptation selection is not eligible for validation freeze") + winner = selection.get("winner") + candidates = [item for item in selection.get("candidates", []) if item["candidate"] == winner] + if len(candidates) != 1: + raise ValueError("adaptation winner is missing or duplicated") + candidate = candidates[0] + checkpoint, config = Path(candidate["checkpoint"]), Path(candidate["config"]) + if sha256(checkpoint) != candidate["checkpoint_sha256"]: + raise ValueError("adaptation checkpoint SHA256 mismatch") + if sha256(config) != candidate["config_sha256"]: + raise ValueError("adaptation config SHA256 mismatch") + if validation_manifest.name != "official_val.jsonl": + raise ValueError("only canonical H2O official validation may be frozen") + return { + "status": "h2o_adaptation_candidate_frozen", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "winner": winner, + "checkpoint": { + "path": str(checkpoint.resolve()), + "sha256": candidate["checkpoint_sha256"], + "step": candidate["checkpoint_step"], + }, + "config": { + "path": str(config.resolve()), + "sha256": candidate["config_sha256"], + }, + "adaptation_selection_path": str(selection_path.resolve()), + "adaptation_selection_sha256": sha256(selection_path), + "selection_split": "h2o_train_group_heldout_only", + "h2o_official_validation_used_for_selection": False, + "h2o_validation_manifest": { + "path": str(validation_manifest.resolve()), + "sha256": sha256(validation_manifest), + }, + "frozen_h2o_input_modes": list(INPUT_MODES), + "h2o_training_data_used": True, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection", type=Path, required=True) + parser.add_argument("--validation-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + try: + result = build_freeze_record(args.selection, args.validation_manifest) + except ValueError as error: + parser.error(str(error)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/freeze_phase7_h2o_zero_shot.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/freeze_phase7_h2o_zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..002866bbe6508fa9e5db8985698182f6eaab4657 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/freeze_phase7_h2o_zero_shot.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Freeze H2O zero-shot exposure only after external selection is immutable.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path + +from scripts.build_phase7_scale_eval_queue import sha256 + + +def build_freeze_record(selection_path: Path, manifest: Path) -> dict: + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if ( + selection.get("status") != "selected_external_generalist_no_h2o" + or selection.get("h2o_training_data_used") is not False + or selection.get("h2o_official_validation_used_for_external_selection") is not False + or selection.get("official_test_used") is not False + ): + raise ValueError("external generalist selection is not freeze-eligible") + checkpoint = Path(selection["checkpoint"]["path"]) + config = Path(selection["config"]["path"]) + if sha256(checkpoint) != selection["checkpoint"]["sha256"]: + raise ValueError("selected checkpoint hash mismatch") + if sha256(config) != selection["config"]["sha256"]: + raise ValueError("selected config hash mismatch") + if manifest.name != "official_val.jsonl": + raise ValueError("only canonical H2O official_val.jsonl can be frozen") + return { + "status": "external_generalist_frozen", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "checkpoint_path": str(checkpoint.resolve()), + "checkpoint_sha256": selection["checkpoint"]["sha256"], + "checkpoint_step": selection["checkpoint"]["step"], + "config_path": str(config.resolve()), "config_sha256": selection["config"]["sha256"], + "external_selection_path": str(selection_path.resolve()), + "external_selection_sha256": sha256(selection_path), + "frozen_h2o_input_modes": ["rgb_d_k", "rgb_k", "rgb_only"], + "h2o_validation_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-selection", type=Path, required=True) + parser.add_argument("--h2o-validation-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + record = build_freeze_record(args.external_selection, args.h2o_validation_manifest) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/freeze_phase9_final_deployment.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/freeze_phase9_final_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..fab8e06ab8f566b0f721a6d89481379322349a41 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/freeze_phase9_final_deployment.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python3 +"""Freeze the unique final Phase 9 checkpoint for post-selection deployment audits.""" + +from __future__ import annotations + +import argparse +import hashlib +import fcntl +import json +from pathlib import Path +from typing import Any + +import torch +import yaml + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def complete_controller( + plan_path: Path, state_path: Path, *, decision_path: Path | None = None, +) -> tuple[dict[str, Any], Path]: + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not report_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or (decision_path is not None and report_path.resolve() != decision_path.resolve()) + ): + raise ValueError(f"controller decision is incomplete or unbound: {state_path}") + report = read_json(report_path) + if report.get("status") != "complete" or report.get("official_test_used") is not False: + raise ValueError(f"controller decision is not isolated: {report_path}") + return report, report_path + + +def normalized_job(job: dict[str, Any], source: str) -> dict[str, Any]: + checkpoint = Path(job.get("checkpoint", job.get("path", ""))) + checkpoint_sha = job.get("checkpoint_sha256", job.get("sha256")) + config = Path(job.get("config", "")) + config_sha = job.get("config_sha256") + if ( + not checkpoint.is_file() or sha256(checkpoint) != checkpoint_sha + or not config.is_file() or sha256(config) != config_sha + ): + raise ValueError(f"selected full job differs: {source}") + return { + "source": source, + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": checkpoint_sha, + "config": str(config.resolve()), + "config_sha256": config_sha, + } + + +def preceding_full_job( + stage8: dict[str, Any], selection: dict[str, Any], +) -> tuple[dict[str, Any], str, bool, list[int]]: + resolution_hw = list(stage8["resolution_hw"]) + if stage8.get("shared_augmentation_accepted") is True: + job = normalized_job( + stage8["candidate_training_jobs"]["full"], + "stage8_shared_augmentation_full", + ) + return job, "shared_augmentation", True, resolution_hw + control = stage8["control"] + if control.get("kind") == "resolution_896x512_candidate": + path = Path(control["evaluation_plan"]["path"]) + if not path.is_file() or sha256(path) != control["evaluation_plan"]["sha256"]: + raise ValueError("selected resolution evaluation plan differs") + plan = read_json(path) + job = normalized_job(plan["training_jobs"]["full"], "stage7_resolution_full") + return job, "resolution", False, resolution_hw + if control.get("kind") == "frozen_640_winner": + record = control["selection_report"] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError("selected 640 selection report differs") + selected = read_json(path) + if selected.get("winner") != selection.get("winner"): + raise ValueError("selected 640 winner differs") + job = normalized_job({ + "checkpoint": selected["winner_checkpoint"]["path"], + "checkpoint_sha256": selected["winner_checkpoint"]["sha256"], + "config": selected["winner_config"]["path"], + "config_sha256": selected["winner_config"]["sha256"], + }, "phase9_frozen_640_winner") + return job, "frozen_640_winner", False, resolution_hw + raise ValueError("Stage 8 selected control kind differs") + + +def checkpoint_contract(job: dict[str, Any], resolution_hw: list[int]) -> int: + config = yaml.safe_load(Path(job["config"]).read_text(encoding="utf-8")) + if ( + config.get("experiment", {}).get("branch") != "phase9_unified" + or config.get("experiment", {}).get("official_test_used") is not False + or list(config.get("data", {}).get("resolution_hw", [])) != resolution_hw + ): + raise ValueError("final deployment config contract differs") + state = torch.load(job["checkpoint"], map_location="cpu", weights_only=False) + extra = state.get("extra", {}) + if ( + extra.get("config") != config + or extra.get("h2o_training_data_used") is not True + or extra.get("official_test_used") is not False + or not isinstance(state.get("model"), dict) + ): + raise ValueError("final deployment checkpoint provenance differs") + return int(state["step"]) + + +def build_freeze( + *, selection_plan_path: Path, selection_state_path: Path, + stage8_plan_path: Path, stage8_state_path: Path, + last2_plan_path: Path, last2_state_path: Path, + validation_manifest: Path, validation_manifest_sha256: str, + training_manifest: Path, training_manifest_sha256: str, +) -> dict[str, Any]: + selection_plan = read_json(selection_plan_path) + selection_state = read_json(selection_state_path) + selection_path = Path(selection_plan["output_json"]) + if ( + selection_state.get("status") != "complete" + or selection_state.get("plan_sha256") != sha256(selection_plan_path) + or selection_state.get("official_test_used") is not False + or selection_state.get("h2o_official_validation_used") is not False + or not selection_path.is_file() + ): + raise ValueError("unified selection is incomplete or unbound") + selection = read_json(selection_path) + if ( + selection.get("status") != "complete" + or selection.get("winner") != selection_state.get("winner") + or selection.get("winner_checkpoint") != selection_state.get("winner_checkpoint") + or selection.get("winner_config") != selection_state.get("winner_config") + or selection.get("official_test_used") is not False + or selection.get("h2o_official_validation_used") is not False + ): + raise ValueError("unified selection report differs") + required_plan = {item["id"]: item for item in selection_plan["required_states"]} + required_state = { + item["id"]: item for item in selection_state.get("required_states", []) + } + if len(required_plan) != 9 or set(required_state) != set(required_plan): + raise ValueError("unified selection required-state chain differs") + for identifier, item in required_state.items(): + path = Path(item["path"]) + expected_path = Path(required_plan[identifier]["path"]) + if ( + path.resolve() != expected_path.resolve() + or not path.is_file() or sha256(path) != item["sha256"] + ): + raise ValueError(f"unified selection required state differs: {identifier}") + payload = read_json(path) + if payload.get("status") != "complete" or payload.get("official_test_used") is not False: + raise ValueError(f"unified selection required state is incomplete: {identifier}") + + stage8_plan = read_json(stage8_plan_path) + stage8, stage8_path = complete_controller( + stage8_plan_path, stage8_state_path, + decision_path=Path(stage8_plan["decision_report"]), + ) + last2_plan = read_json(last2_plan_path) + last2, last2_path = complete_controller( + last2_plan_path, last2_state_path, + decision_path=Path(last2_plan["report"]), + ) + if stage8.get("winner") != selection.get("winner"): + raise ValueError("Stage 8 winner differs from unified selection") + + preceding, mechanism, shared_augmentation, resolution_hw = preceding_full_job( + stage8, selection, + ) + selected = str(last2["selected"]) + if selected in {"last2_5e7", "last2_1e6"}: + candidate = "5e7" if selected == "last2_5e7" else "1e6" + report_record = last2["selected_candidate_report"] + candidate_path = Path(report_record["path"]) + if not candidate_path.is_file() or sha256(candidate_path) != report_record["sha256"]: + raise ValueError("selected last-2 candidate report differs") + candidate_report = read_json(candidate_path) + if ( + candidate_report.get("candidate") != candidate + or candidate_report.get("gate", {}).get("accepted") is not True + ): + raise ValueError("selected last-2 gate differs") + job = normalized_job( + candidate_report["candidate_training_jobs"]["full"], selected, + ) + mechanism = selected + shared_augmentation = bool(candidate_report["shared_augmentation"]) + resolution_hw = list(candidate_report["resolution_hw"]) + elif selected == "preceding_mechanism": + job = preceding + else: + raise ValueError("last-2 final selection differs") + + step = checkpoint_contract(job, resolution_hw) + for path, expected, label in ( + (validation_manifest, validation_manifest_sha256, "official validation"), + (training_manifest, training_manifest_sha256, "official train"), + ): + if not path.is_file() or sha256(path) != expected: + raise ValueError(f"{label} manifest differs") + chain = { + "unified_selection_plan": sha256(selection_plan_path), + "unified_selection_state": sha256(selection_state_path), + "unified_selection": sha256(selection_path), + "stage8_controller_plan": sha256(stage8_plan_path), + "stage8_controller_state": sha256(stage8_state_path), + "stage8_decision": sha256(stage8_path), + "last2_finalizer_plan": sha256(last2_plan_path), + "last2_finalizer_state": sha256(last2_state_path), + "last2_final_decision": sha256(last2_path), + } + chain_hash = hashlib.sha256( + json.dumps(chain, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + return { + "schema_version": "phase9_final_deployment_freeze_v1", + "status": "phase9_final_unified_checkpoint_frozen", + "created_utc": last2["created_utc"], + "winner": selection["winner"], + "selected_mechanism": mechanism, + "resolution_hw": resolution_hw, + "shared_augmentation": shared_augmentation, + "checkpoint": { + "path": job["checkpoint"], "sha256": job["checkpoint_sha256"], + "step": step, + }, + "config": {"path": job["config"], "sha256": job["config_sha256"]}, + "selection_chain": chain, + "selection_chain_sha256": chain_hash, + "selection_complete": True, + "stage9_final_decision_complete": True, + "frozen_h2o_input_modes": list(INPUT_MODES), + "h2o_validation_manifest": { + "path": str(validation_manifest.resolve()), + "sha256": validation_manifest_sha256, + }, + "h2o_training_manifest": { + "path": str(training_manifest.resolve()), + "sha256": training_manifest_sha256, + }, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--selection-plan", type=Path, required=True) + parser.add_argument("--selection-state", type=Path, required=True) + parser.add_argument("--stage8-plan", type=Path, required=True) + parser.add_argument("--stage8-state", type=Path, required=True) + parser.add_argument("--last2-plan", type=Path, required=True) + parser.add_argument("--last2-state", type=Path, required=True) + parser.add_argument("--validation-manifest", type=Path, required=True) + parser.add_argument("--validation-manifest-sha256", required=True) + parser.add_argument("--training-manifest", type=Path, required=True) + parser.add_argument("--training-manifest-sha256", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = build_freeze( + selection_plan_path=args.selection_plan, + selection_state_path=args.selection_state, + stage8_plan_path=args.stage8_plan, stage8_state_path=args.stage8_state, + last2_plan_path=args.last2_plan, last2_state_path=args.last2_state, + validation_manifest=args.validation_manifest, + validation_manifest_sha256=args.validation_manifest_sha256, + training_manifest=args.training_manifest, + training_manifest_sha256=args.training_manifest_sha256, + ) + if args.output.exists(): + if read_json(args.output) != result: + raise ValueError("existing final deployment freeze differs") + else: + atomic_json(args.output, result) + state = { + "schema_version": "phase9_final_deployment_freeze_state_v1", + "status": "complete", "freeze": str(args.output.resolve()), + "freeze_sha256": sha256(args.output), + "checkpoint_sha256": result["checkpoint"]["sha256"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + except Exception as error: + atomic_json(args.state, { + "schema_version": "phase9_final_deployment_freeze_state_v1", + "status": "failed_resumable", + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used": False, + "official_test_used": False, + }) + raise + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c27472cd14392687856490a5d6fd1c44ee7bc4d7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_configs.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Generate the pre-registered Phase 3 decoder/temporal core configs.""" + +from __future__ import annotations + +import argparse +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +LAYOUTS = { + "l0": "sequential", + "l1": "alternating", + "l2": "hybrid_reread", +} +MATRIX_ROWS = ( + ("l0", "t0"), + ("l0", "t1"), + ("l1", "t0"), + ("l1", "t1"), + ("l2", "t1"), +) +MODALITIES = { + "m0": {"use_depth": False, "use_rays": False}, + "m3": {"use_depth": True, "use_rays": True}, +} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + + rows = [] + for modality, modality_values in MODALITIES.items(): + for layout, temporal in MATRIX_ROWS: + for seed in SEEDS: + name = f"core_{modality}_{layout}_{temporal}_s{seed}" + config = { + "name": name, + "seed": seed, + "experiment": { + "phase": 3, + "matrix": "decoder_temporal_core", + "modality": modality.upper(), + "layout": layout.upper(), + "temporal": temporal.upper(), + "registered_axes": ["layout", "temporal_attention", "modality"], + }, + "data": { + "resolution_hw": [288, 512], + "T": 8, + "stride": 1, + "batch_size": 1, + }, + "model": { + "encoder": "dinov3", + "decoder_dim": 512, + "decoder_layers": 3, + "attention_heads": 8, + "decoder_mode": LAYOUTS[layout], + "use_temporal": temporal == "t1", + "use_depth": modality_values["use_depth"], + "depth_mode": "log_depth", + "depth_gate_mode": "fixed", + "depth_gate_fixed_value": 0.5, + "use_rays": modality_values["use_rays"], + "use_bimanual_interaction": True, + "predict_presence": True, + "require_mano": True, + }, + "loss": { + "joint2d": 1.0, + "joint3d_camera": 10.0, + "vertices_camera": 1.0, + "local_pose": 1.0, + "global_orientation": 1.0, + "shape": 0.1, + "translation": 10.0, + "reprojection": 1.0, + "temporal_velocity": 0.1, + "temporal_acceleration": 0.05, + "bimanual_relative_wrist": 1.0, + "presence": 0.0, + }, + "assets": { + "dinov3_source": "third_party/dinov3", + "dinov3_weights": "/SSD3/jiasen/foundation_hand/pretrained/dinov3", + "mano_root": "/SSD3/jiasen/foundation_hand/pretrained/mano", + }, + "precision": "bf16", + "protocol": { + "max_steps": 100000, + "num_workers": 4, + "checkpoint_interval": 25000, + "validation_interval": 5000, + "validation_batches": 256, + "learning_rate": 5e-5, + "min_learning_rate": 5e-6, + "warmup_steps": 500, + "early_stopping_patience": 0, + "validation_subset_manifest": "artifacts/phase3/validation_subset/validation_subset_256.json", + }, + } + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": modality.upper(), "layout": layout.upper(), + "decoder_mode": LAYOUTS[layout], "temporal": temporal.upper(), + "use_depth": int(modality_values["use_depth"]), + "use_rays": int(modality_values["use_rays"]), + "depth_gate": 0.5 if modality_values["use_depth"] else "not_used", + }) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} configs under {args.output_dir}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_depth_fusion_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_depth_fusion_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..a1436a0b91cc980e884999390c44c9a0fda0795f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_depth_fusion_configs.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""Generate the first independent Phase 3 Depth fusion/representation controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = { + "gate025": { + "depth_mode": "log_depth", "depth_gate_mode": "fixed", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.25, + }, + "learned_gate": { + "depth_mode": "log_depth", "depth_gate_mode": "learned", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.5, + }, + "geometry": { + "depth_mode": "geometry", "depth_gate_mode": "fixed", + "depth_gate_floor": 0.0, "depth_gate_fixed_value": 0.5, + }, +} + + +def matrix_row(path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(path), "name": config["name"], "seed": config["seed"], + "modality": "M3", "layout": "L1", "temporal": "T1", + "variant": config["experiment"]["variant"], + "depth_mode": model["depth_mode"], + "depth_gate_mode": model["depth_gate_mode"], + "depth_gate_floor": model["depth_gate_floor"], + "depth_gate_fixed_value": model["depth_gate_fixed_value"], + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_fusion_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_fusion_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, changes in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / f"core_m3_l1_t1_s{seed}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, "matrix": "depth_fusion", "modality": "M3", + "layout": "L1", "temporal": "T1", "variant": variant, + "registered_axes": ["depth_fusion_or_representation"], + "reference": "P0_M3_L1_T1_fixed_gate_0.5", + } + config["model"].update(changes) + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append(matrix_row(path, config, "new_formal_run")) + rows.sort(key=lambda row: (str(row["variant"]), int(row["seed"]))) + write_matrix(args.runs_csv, rows) + write_matrix(args.matrix_csv, rows) + print(f"generated {len(rows)} Depth fusion configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_dropout_dose_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_dropout_dose_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..ff442de59dcd384b1d69070f92c29d57f47b2214 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_dropout_dose_configs.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Generate lower-dose Geometry modality-dropout Phase 3 controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = {"dropout005_geometry": 0.05, "dropout010_geometry": 0.10} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/dropout_dose_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/dropout_dose_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, probability in VARIANTS.items(): + for seed in SEEDS: + base_path = ( + args.base_config_dir + / f"depth_dropout00_geometry_m3_l1_t1_s{seed}.yaml" + ) + config = copy.deepcopy( + yaml.safe_load(base_path.read_text(encoding="utf-8")) + ) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "depth_modality_dropout_dose", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": variant, + "registered_axes": ["modality_dropout_dose"], + "reference": "D2_dropout00_and_dropout02_endpoints", + } + config["model"]["modality_dropout_prob"] = probability + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), + "name": name, + "seed": seed, + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "depth_mode": "geometry", + "variant": variant, + "modality_dropout_prob": probability, + "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(rows[0]), lineterminator="\n" + ) + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} dropout-dose configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_long_tail_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_long_tail_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..45500ef2d771d2f985343c04d4f262ebc1d0645a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_long_tail_configs.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Generate the preregistered E.3 low-learning-rate tail configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/photometric"), + ) + parser.add_argument( + "--checkpoint-root", type=Path, + default=Path("artifacts/phase3/photometric_runs_commit239b0bf"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/long_tail_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + source_name = f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + base_path = args.base_config_dir / f"{source_name}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "low_lr_tail", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": "photometric_on_r640x368_tail150k", + "registered_axes": ["training_duration"], + "reference": source_name, + } + config["protocol"]["max_steps"] = 150_000 + config["protocol"]["lr_schedule_steps"] = 100_000 + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + checkpoint = args.checkpoint_root / source_name / "step_0100000_final.pt" + rows.append({ + "config": str(path.resolve()), "name": name, "seed": seed, + "resume_checkpoint": str(checkpoint.resolve()), + "start_step": 100_000, "max_steps": 150_000, + "lr_schedule_steps": 100_000, "min_learning_rate": 5e-6, + "changed_variable": "training_duration_only", + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} E.3 low-LR-tail configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_modality_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_modality_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c89255f39b11007505204124621076e0d01704eb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_modality_configs.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Generate the new M1/M2 runs for the Phase 3 modality matrix.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +NEW_MODALITIES = { + "M1": {"use_depth": False, "use_rays": True}, + "M2": {"use_depth": True, "use_rays": False}, +} + + +def matrix_row(config_path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(config_path), + "name": config["name"], + "seed": config["seed"], + "modality": config["experiment"]["modality"], + "layout": config["experiment"]["layout"], + "temporal": config["experiment"]["temporal"], + "use_depth": int(model["use_depth"]), + "use_rays": int(model["use_rays"]), + "depth_gate": 0.5 if model["use_depth"] else "not_used", + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/modality")) + parser.add_argument("--new-runs-csv", type=Path, default=Path("artifacts/phase3/reports/modality_new_runs.csv")) + parser.add_argument("--full-matrix-csv", type=Path, default=Path("artifacts/phase3/reports/modality_config_matrix.csv")) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + new_rows = [] + full_rows = [] + for seed in SEEDS: + references = {} + for modality in ("M0", "M3"): + path = args.core_config_dir / f"core_{modality.lower()}_l1_t1_s{seed}.yaml" + config = yaml.safe_load(path.read_text(encoding="utf-8")) + references[modality] = config + full_rows.append(matrix_row(path, config, "reused_core_matrix")) + + for modality, flags in NEW_MODALITIES.items(): + config = copy.deepcopy(references["M3"]) + name = f"modality_{modality.lower()}_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "modality_causal", + "modality": modality, + "layout": "L1", + "temporal": "T1", + "registered_axes": ["modality"], + "decoder_promotion_source": "decoder_temporal_core_best_absolute_full_val", + } + config["model"]["use_depth"] = flags["use_depth"] + config["model"]["use_rays"] = flags["use_rays"] + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + row = matrix_row(path, config, "new_formal_run") + new_rows.append(row) + full_rows.append(row) + + new_rows.sort(key=lambda row: (str(row["modality"]), int(row["seed"]))) + full_rows.sort(key=lambda row: (str(row["modality"]), int(row["seed"]))) + write_matrix(args.new_runs_csv, new_rows) + write_matrix(args.full_matrix_csv, full_rows) + print(f"generated {len(new_rows)} new configs and {len(full_rows)} full-matrix rows") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_modality_dropout_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_modality_dropout_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..c2841dce151e58be976b8e49d194d5faab3c2e69 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_modality_dropout_configs.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Generate same-commit geometry controls for M3 modality-dropout training.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +DROP_PROB = 0.2 +VARIANTS = {"dropout00_geometry": 0.0, "dropout02_geometry": DROP_PROB} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/depth_fusion")) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_dropout_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/depth_dropout_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, probability in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / f"depth_geometry_m3_l1_t1_s{seed}.yaml" + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_{variant}_m3_l1_t1_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, "matrix": "depth_modality_dropout", "modality": "M3", + "layout": "L1", "temporal": "T1", "variant": variant, + "registered_axes": ["modality_dropout"], + "reference": "dropout00_geometry_same_commit", + } + config["model"]["modality_dropout_prob"] = probability + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "depth_mode": "geometry", "variant": variant, + "modality_dropout_prob": probability, "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} same-commit geometry modality-dropout configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_photometric_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_photometric_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..138bc89f81a2c18daf910344d7768488270af82f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_photometric_configs.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Generate same-code Phase 3 photometric augmentation off/on controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = {"off": False, "on": True} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/resolution"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/photometric"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/photometric_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/photometric_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for variant, enabled in VARIANTS.items(): + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"photometric_{variant}_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "photometric_augmentation", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": f"photometric_{variant}_r640x368", + "registered_axes": ["photometric_augmentation"], + "reference": "E1_promoted_r640x368", + } + config["data"]["photometric_augmentation"] = { + "enabled": enabled, + "probability": 0.8, + "brightness": 0.2, + "contrast": 0.2, + "saturation": 0.2, + "hue": 0.05, + } + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "variant": f"photometric_{variant}", + "photometric_enabled": enabled, + "resolution_h": 368, "resolution_w": 640, + "source": "new_same_commit_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} photometric off/on configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_resolution_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_resolution_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..4bc5c0e1550283a14452e8ffc4a36f9ed606302c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_resolution_configs.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Generate the 640x368 Phase 3 resolution controls.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +VALIDATION_SUBSET = ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" +) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/depth_fusion"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase3/resolution"), + ) + parser.add_argument( + "--runs-csv", type=Path, + default=Path("artifacts/phase3/reports/resolution_640_new_runs.csv"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/resolution_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + base_path = ( + args.base_config_dir + / f"depth_dropout005_geometry_m3_l1_t1_s{seed}.yaml" + ) + config = copy.deepcopy(yaml.safe_load(base_path.read_text(encoding="utf-8"))) + name = f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + config["name"] = name + config["experiment"] = { + "phase": 3, + "matrix": "resolution", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "variant": "dropout005_geometry_r640x368", + "registered_axes": ["input_resolution"], + "reference": "dropout005_geometry_r512x288_D3", + } + config["data"]["resolution_hw"] = [368, 640] + config["protocol"]["validation_subset_manifest"] = VALIDATION_SUBSET + path = args.output_dir / f"{name}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path), "name": name, "seed": seed, + "modality": "M3", "layout": "L1", "temporal": "T1", + "depth_mode": "geometry", "variant": "r640x368", + "resolution_h": 368, "resolution_w": 640, + "modality_dropout_prob": 0.05, "source": "new_formal_run", + }) + for path in (args.runs_csv, args.matrix_csv): + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + print(f"generated {len(rows)} 640x368 resolution configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_temporal_position_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_temporal_position_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..12031161423294f686ba8f955d905e9de947f069 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase3_temporal_position_configs.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Generate the P0/P1 relative temporal-position experiment configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) + + +def matrix_row(config_path: Path, config: dict, source: str) -> dict[str, object]: + model = config["model"] + return { + "config": str(config_path), + "name": config["name"], + "seed": config["seed"], + "modality": config["experiment"]["modality"], + "layout": config["experiment"]["layout"], + "temporal": config["experiment"]["temporal"], + "position": config["experiment"].get("position", "P0"), + "temporal_position_mode": model.get("temporal_position_mode", "none"), + "relative_bias_max_distance": model.get("temporal_relative_bias_max_distance", "not_used"), + "source": source, + } + + +def write_matrix(path: Path, rows: list[dict[str, object]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-config-dir", type=Path, default=Path("configs/phase3/core")) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase3/temporal_position")) + parser.add_argument( + "--new-runs-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_new_runs.csv"), + ) + parser.add_argument( + "--p0-runs-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_p0_reused_runs.csv"), + ) + parser.add_argument( + "--full-matrix-csv", type=Path, + default=Path("artifacts/phase3/reports/temporal_position_config_matrix.csv"), + ) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + new_rows = [] + p0_rows = [] + full_rows = [] + for seed in SEEDS: + p0_path = args.core_config_dir / f"core_m3_l1_t1_s{seed}.yaml" + p0 = yaml.safe_load(p0_path.read_text(encoding="utf-8")) + p0_row_config = copy.deepcopy(p0) + p0_row_config["experiment"]["position"] = "P0" + p0_row = matrix_row(p0_path, p0_row_config, "reused_core_matrix") + p0_rows.append(p0_row) + full_rows.append(p0_row) + + p1 = copy.deepcopy(p0) + name = f"temporal_p1_m3_l1_t1_s{seed}" + p1["name"] = name + p1["experiment"] = { + "phase": 3, + "matrix": "temporal_position", + "modality": "M3", + "layout": "L1", + "temporal": "T1", + "position": "P1", + "registered_axes": ["temporal_position"], + "reference": "P0_no_temporal_position_reused_core_m3_l1_t1", + } + p1["model"]["temporal_position_mode"] = "relative_bias" + p1["model"]["temporal_relative_bias_max_distance"] = 15 + p1_path = args.output_dir / f"{name}.yaml" + p1_path.write_text(yaml.safe_dump(p1, sort_keys=False), encoding="utf-8") + row = matrix_row(p1_path, p1, "new_formal_run") + new_rows.append(row) + full_rows.append(row) + + write_matrix(args.new_runs_csv, new_rows) + write_matrix(args.p0_runs_csv, p0_rows) + write_matrix(args.full_matrix_csv, full_rows) + print(f"generated {len(new_rows)} new configs and {len(full_rows)} P0/P1 rows") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase4_a3_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase4_a3_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..11d025bc0e7dd6e7f56fcad7fc54c12e8e9b509d --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase4_a3_configs.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Generate hash-bound A3 oracle-crop tiny/health/formal configs.""" + +from __future__ import annotations + +import argparse +import copy +import csv +import json +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +MODES = { + "rgb": "oracle_rgb", + "depth_k": "oracle_depth_k", + "rgb_depth_k": "oracle_rgb_depth_k", +} +STAGES = { + "tiny2k": { + "stage": "tiny", "max_steps": 2_000, "checkpoint_interval": 500, + "validation_interval": 500, "warmup_steps": 100, + "validation_subset_manifest": None, + }, + "health25k": { + "stage": "health", "max_steps": 25_000, + "checkpoint_interval": 5_000, "validation_interval": 5_000, + "warmup_steps": 500, + "validation_subset_manifest": ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" + ), + }, + "formal100k": { + "stage": "formal", "max_steps": 100_000, + "checkpoint_interval": 25_000, "validation_interval": 5_000, + "warmup_steps": 500, + "validation_subset_manifest": ( + "/home/jiasen/foundation_hand/artifacts/phase3/validation_subset/" + "resolution_640x368/validation_subset_256.json" + ), + }, +} + + +def protocol(stage: dict[str, object]) -> dict[str, object]: + output = { + "max_steps": stage["max_steps"], + "num_workers": 4, + "checkpoint_interval": stage["checkpoint_interval"], + "validation_interval": stage["validation_interval"], + "validation_batches": 256, + "learning_rate": 5e-5, + "min_learning_rate": 5e-6, + "warmup_steps": stage["warmup_steps"], + "early_stopping_patience": 0, + "lr_schedule_steps": stage["max_steps"], + } + if stage["validation_subset_manifest"] is not None: + output["validation_subset_manifest"] = stage["validation_subset_manifest"] + return output + + +def build_config( + base: dict, + mode_slug: str, + stage_slug: str, + checkpoint: dict, +) -> dict: + result = copy.deepcopy(base) + mode = MODES[mode_slug] + stage = STAGES[stage_slug] + seed = int(base["seed"]) + name = f"phase4_a3_{mode_slug}_r640x368_s{seed}_{stage_slug}" + result["name"] = name + result["experiment"] = { + "phase": 4, + "wave": "A", + "cell": "A3", + "stage": stage["stage"], + "oracle_crop_mode": mode, + "reference": base["name"], + "changed_variable": "oracle_raw_high_resolution_crop_residual_only", + "coarse_checkpoint_path": checkpoint["path"], + "coarse_checkpoint_sha256": checkpoint["sha256"], + "coarse_checkpoint_step": checkpoint["step"], + "gt_location_at_train_and_validation": True, + "deployable_inference": False, + "official_test_used": False, + } + result["model"].update({ + "oracle_crop_mode": mode, + "freeze_coarse_for_oracle_crop": True, + }) + result["sampling"] = {"mode": "uniform"} + result["protocol"] = protocol(stage) + return result + + +def write_config_matrices( + rows: list[dict[str, object]], + matrix_csv: Path, + formal_matrix_csv: Path, +) -> list[dict[str, object]]: + if not rows: + raise ValueError("at least one A3 configuration row is required") + matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + if not formal_rows: + raise ValueError("A3 configuration matrix has no formal rows") + formal_matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + return formal_rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, + default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--checkpoint-index", type=Path, + default=Path("artifacts/phase3/reports/long_tail_checkpoints.json"), + ) + parser.add_argument( + "--output-dir", type=Path, + default=Path("configs/phase4/a3_oracle_crop"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/a3_oracle_crop_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/a3_oracle_crop_formal_config_matrix.csv"), + ) + args = parser.parse_args() + checkpoint_index = json.loads(args.checkpoint_index.read_text(encoding="utf-8")) + args.output_dir.mkdir(parents=True, exist_ok=True) + rows = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + "longtail_photometric_on_geometry_m3_l1_t1_" + f"r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + run = checkpoint_index["runs"][base["name"]] + checkpoint = run["roles"]["tail_best_absolute"] + if int(run["seed"]) != seed or int(checkpoint["step"]) not in range(100_000, 150_001): + raise ValueError(f"invalid frozen checkpoint record for seed {seed}") + for mode_slug, mode in MODES.items(): + for stage_slug in STAGES: + if stage_slug != "formal100k" and seed != SEEDS[0]: + continue + generated = build_config(base, mode_slug, stage_slug, checkpoint) + output_path = args.output_dir / f"{generated['name']}.yaml" + output_path.write_text( + yaml.safe_dump(generated, sort_keys=False), encoding="utf-8", + ) + rows.append({ + "config": str(output_path.resolve()), + "name": generated["name"], + "seed": seed, + "mode": mode, + "stage": STAGES[stage_slug]["stage"], + "max_steps": STAGES[stage_slug]["max_steps"], + "initialization_checkpoint": checkpoint["path"], + "initialization_checkpoint_sha256": checkpoint["sha256"], + "initialization_checkpoint_step": checkpoint["step"], + "gt_location": True, + "official_test_used": False, + }) + formal_rows = write_config_matrices( + rows, args.matrix_csv, args.formal_matrix_csv, + ) + print(json.dumps({ + "status": "generated", "configs": len(rows), + "output_dir": str(args.output_dir), "matrix_csv": str(args.matrix_csv), + "formal_configs": len(formal_rows), + "formal_matrix_csv": str(args.formal_matrix_csv), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase4_b0_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase4_b0_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..374500c074dfdc0d588ae23fef22449cd82d1893 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase4_b0_configs.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Generate preregistered Phase 4 B0 axis-aware loss configurations.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +AXIS_WEIGHTS = (0.5, 0.5, 2.0) +HUBER_BETA_M = 0.01 + + +def b0_config(base: dict, seed: int, stage: str) -> dict: + config = copy.deepcopy(base) + config["seed"] = seed + suffix = { + "smoke": "smoke1", + "tiny": "tiny2k", + "health": "health25k", + "formal": "formal100k", + }[stage] + config["name"] = f"phase4_b0_axis_huber_r640x368_s{seed}_{suffix}" + config["experiment"] = { + "phase": 4, + "wave": "B", + "cell": "B0", + "stage": stage, + "reference": f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}", + "changed_variable": "translation_loss_only", + "frozen_model_recipe": True, + "official_test_used": False, + } + config["loss"]["translation_mode"] = "axis_huber" + config["loss"]["translation_axis_weights"] = list(AXIS_WEIGHTS) + config["loss"]["translation_huber_beta_m"] = HUBER_BETA_M + protocol = config["protocol"] + if stage == "smoke": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 1, + "lr_schedule_steps": 1, + "warmup_steps": 0, + "checkpoint_interval": 1, + "validation_interval": 1, + }) + elif stage == "tiny": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 2_000, + "lr_schedule_steps": 2_000, + "warmup_steps": 100, + "checkpoint_interval": 500, + "validation_interval": 500, + }) + elif stage == "health": + protocol.update({ + "max_steps": 25_000, + "lr_schedule_steps": 25_000, + "warmup_steps": 500, + "checkpoint_interval": 5_000, + "validation_interval": 5_000, + }) + elif stage == "formal": + protocol.update({ + "max_steps": 100_000, + "lr_schedule_steps": 100_000, + "warmup_steps": 500, + "checkpoint_interval": 25_000, + "validation_interval": 5_000, + }) + return config + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, default=Path("configs/phase3/long_tail"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("configs/phase4/b0_axis_loss")) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b0_axis_loss_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b0_axis_loss_formal_config_matrix.csv"), + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + stages = ("smoke", "tiny", "health", "formal") if seed == SEEDS[0] else ("formal",) + for stage in stages: + config = b0_config(base, seed, stage) + path = args.output_dir / f"{config['name']}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), + "name": config["name"], + "seed": seed, + "stage": stage, + "run_name": f"{stage}_seed{seed}", + "max_steps": config["protocol"]["max_steps"], + "changed_variable": "translation loss L1 -> axis Huber", + "translation_axis_weights": "0.5,0.5,2.0", + "translation_huber_beta_m": HUBER_BETA_M, + "official_test_used": False, + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + with args.formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + print(f"generated {len(rows)} Phase 4 B0 configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase4_b2_configs.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase4_b2_configs.py new file mode 100644 index 0000000000000000000000000000000000000000..fa886d4b37a143c5c5e844620f87afaea3cec7f1 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/generate_phase4_b2_configs.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Generate preregistered Phase 4 B2 balanced-sampling configurations.""" + +from __future__ import annotations + +import argparse +import copy +import csv +from pathlib import Path + +import yaml + + +SEEDS = (20260716, 20260717, 20260718) +FULL_SAMPLER_MANIFEST = Path( + "/home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/" + "train_geometry_balanced_v1.json" +) +TINY_SAMPLER_MANIFEST = Path( + "/home/jiasen/foundation_hand/artifacts/phase4/balanced_sampling/" + "tiny_train_geometry_balanced_v1.json" +) + + +def b2_config(base: dict, seed: int, stage: str) -> dict: + config = copy.deepcopy(base) + config["seed"] = seed + suffix = { + "smoke": "smoke1", + "tiny": "tiny2k", + "health": "health25k", + "formal": "formal100k", + }[stage] + config["name"] = f"phase4_b2_balanced_sampler_r640x368_s{seed}_{suffix}" + config["experiment"] = { + "phase": 4, + "wave": "B", + "cell": "B2", + "stage": stage, + "reference": f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}", + "changed_variable": "training_sampler_only", + "frozen_model_recipe": True, + "official_test_used": False, + } + config["sampling"] = { + "mode": "balanced", + "manifest": str( + TINY_SAMPLER_MANIFEST if stage == "tiny" else FULL_SAMPLER_MANIFEST + ), + } + protocol = config["protocol"] + if stage == "smoke": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 1, + "lr_schedule_steps": 1, + "warmup_steps": 0, + "checkpoint_interval": 1, + "validation_interval": 1, + }) + elif stage == "tiny": + protocol.pop("validation_subset_manifest", None) + protocol.update({ + "max_steps": 2_000, + "lr_schedule_steps": 2_000, + "warmup_steps": 100, + "checkpoint_interval": 500, + "validation_interval": 500, + }) + elif stage == "health": + protocol.update({ + "max_steps": 25_000, + "lr_schedule_steps": 25_000, + "warmup_steps": 500, + "checkpoint_interval": 5_000, + "validation_interval": 5_000, + }) + elif stage == "formal": + protocol.update({ + "max_steps": 100_000, + "lr_schedule_steps": 100_000, + "warmup_steps": 500, + "checkpoint_interval": 25_000, + "validation_interval": 5_000, + }) + return config + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument( + "--base-config-dir", type=Path, default=Path("configs/phase3/long_tail"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("configs/phase4/b2_balanced_sampling"), + ) + parser.add_argument( + "--matrix-csv", type=Path, + default=Path("artifacts/phase4/reports/b2_balanced_sampling_config_matrix.csv"), + ) + parser.add_argument( + "--formal-matrix-csv", type=Path, + default=Path( + "artifacts/phase4/reports/b2_balanced_sampling_formal_config_matrix.csv" + ), + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, object]] = [] + for seed in SEEDS: + base_path = args.base_config_dir / ( + f"longtail_photometric_on_geometry_m3_l1_t1_r640x368_s{seed}.yaml" + ) + base = yaml.safe_load(base_path.read_text(encoding="utf-8")) + stages = ("smoke", "tiny", "health", "formal") if seed == SEEDS[0] else ("formal",) + for stage in stages: + config = b2_config(base, seed, stage) + path = args.output_dir / f"{config['name']}.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") + rows.append({ + "config": str(path.resolve()), + "name": config["name"], + "seed": seed, + "stage": stage, + "run_name": f"{stage}_seed{seed}", + "max_steps": config["protocol"]["max_steps"], + "changed_variable": "uniform -> train-only balanced sampling", + "sampling_manifest": config["sampling"]["manifest"], + "official_test_used": False, + }) + args.matrix_csv.parent.mkdir(parents=True, exist_ok=True) + with args.matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + formal_rows = [row for row in rows if row["stage"] == "formal"] + with args.formal_matrix_csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, fieldnames=list(formal_rows[0]), lineterminator="\n", + ) + writer.writeheader() + writer.writerows(formal_rows) + print(f"generated {len(rows)} Phase 4 B2 configs") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/import_phase9_distributed_cache_worker_state.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/import_phase9_distributed_cache_worker_state.py new file mode 100644 index 0000000000000000000000000000000000000000..c41dc656030e78d58876c0bd9ad515c24f18ffac --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/import_phase9_distributed_cache_worker_state.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Normalize one external Stage 7 cache worker onto the central admission.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +from typing import Any + +from scripts.phase9_distributed_assignment import load_assignment +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +HOST_LOCAL_ADMISSION_FIELDS = frozenset({"admitted_utc", "available_gib"}) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: Any) -> str: + payload = json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, + ).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def scientific_admission(value: dict[str, Any]) -> dict[str, Any]: + return { + key: item for key, item in value.items() + if key not in HOST_LOCAL_ADMISSION_FIELDS + } + + +def validate_admission_pair( + source: dict[str, Any], central: dict[str, Any], expected_plan_sha256: str, +) -> dict[str, Any]: + for label, value in (("source", source), ("central", central)): + if ( + value.get("schema_version") != "phase9_resolution_admission_v1" + or value.get("status") != "complete" + or value.get("scientific_stage_admitted") is not True + or value.get("plan_sha256") != expected_plan_sha256 + or value.get("official_test_used") is not False + or value.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"{label} admission contract differs") + source_scientific = scientific_admission(source) + central_scientific = scientific_admission(central) + if source_scientific != central_scientific: + differing = sorted( + key for key in set(source_scientific) | set(central_scientific) + if source_scientific.get(key) != central_scientific.get(key) + ) + raise ValueError(f"distributed admission scientific binding differs: {differing}") + return { + "host_local_operational_fields": sorted(HOST_LOCAL_ADMISSION_FIELDS), + "source_operational_values": { + key: source[key] for key in sorted(HOST_LOCAL_ADMISSION_FIELDS) + }, + "central_operational_values": { + key: central[key] for key in sorted(HOST_LOCAL_ADMISSION_FIELDS) + }, + "normalized_scientific_binding_sha256": json_sha256(source_scientific), + } + + +def external_cache_worker_owner( + assignment: dict[str, Any], worker_id: str, +) -> str: + state_id = f"{worker_id}_cache_worker" + owners = { + item["id"]: item["owner"] + for item in assignment["stage7_cache_ownership"]["states"] + } + owner = owners.get(state_id) + if owner is None: + raise ValueError(f"distributed cache worker is undeclared: {worker_id}") + if owner == assignment["central_owner"]: + raise ValueError(f"cache worker is not external-owned: {worker_id}") + return owner + + +def validate_release_metadata( + release: dict[str, Any], receive: dict[str, Any], *, + source_owner: str, source_worker_sha256: str, bridge_plan_sha256: str, +) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != source_owner + or release.get("plan_sha256") != bridge_plan_sha256 + or release.get("producer_worker_state", {}).get("sha256") + != source_worker_sha256 + or release.get("live_reverse_sync_forbidden") is not True + or release.get("read_only_after_receive") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache release binding differs") + if ( + receive.get("status") != "complete" + or receive.get("plan_sha256") != bridge_plan_sha256 + or receive.get("release_file_count") != release.get("file_count") + or receive.get("release_total_bytes") != release.get("total_bytes") + or receive.get("live_reverse_sync_performed") is not False + or receive.get("official_test_used") is not False + or receive.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache receive binding differs") + released = { + item["id"]: (item["path"], item["file_count"], item["total_bytes"]) + for item in release.get("artifacts", []) + } + installed = { + item["id"]: (item["path"], item["file_count"], item["total_bytes"]) + for item in receive.get("installed", []) + } + if released != installed: + raise ValueError("external cache installed artifacts differ from release") + + +def validate_released_cache_files( + release: dict[str, Any], expected_files: list[dict[str, Any]], + resolution_hw: list[int], +) -> list[dict[str, Any]]: + root = Path(release["release_root"]) + inventory = {item["path"]: item for item in release["files"]} + results = [] + for expected in expected_files: + path = Path(expected["path"]) + relative = str(path.relative_to(root)) + record = inventory.get(relative) + if ( + record is None or record.get("sha256") != expected["sha256"] + or record.get("bytes") != path.stat().st_size + or not path.is_file() or sha256(path) != expected["sha256"] + ): + raise ValueError(f"external cache release file hash differs: {path}") + if path.name == "cache_report.json": + report = read_json(path) + if ( + report.get("status") != "complete" + or report.get("resolution_hw") != resolution_hw + or report.get("resume_invocation") is not True + or report.get("official_test_used") is not False + ): + raise ValueError(f"external cache report contract differs: {path}") + results.append({ + "path": str(path.resolve()), "sha256": expected["sha256"], + "release_relative_path": relative, "bytes": record["bytes"], + }) + return results + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("status") != "frozen" + or plan.get("central_owner") != "taku3" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("distributed admission import plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"distributed admission import binding differs: {path}") + assignment = load_assignment(plan) + if sha256(plan_path) == plan.get("superseded_plan_sha256"): + raise ValueError("distributed admission import plan identity differs") + return assignment + + +def build_imported_state(plan_path: Path, plan: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + assignment = validate_plan(plan_path, plan) + worker_id = plan["worker_id"] + source_owner = external_cache_worker_owner(assignment, worker_id) + if source_owner != plan["source_owner"]: + raise ValueError("distributed admission source owner differs") + source_admission_path = Path(plan["source_admission"]["evidence_path"]) + central_admission_path = Path(plan["central_admission"]["path"]) + source_worker_path = Path(plan["source_worker_state"]["evidence_path"]) + release_path = Path(plan["cache_release"]["evidence_path"]) + receive_path = Path(plan["cache_receive"]["path"]) + for path, expected in ( + (source_admission_path, plan["source_admission"]["sha256"]), + (central_admission_path, plan["central_admission"]["sha256"]), + (source_worker_path, plan["source_worker_state"]["sha256"]), + (release_path, plan["cache_release"]["sha256"]), + (receive_path, plan["cache_receive"]["sha256"]), + ): + if not path.is_file() or sha256(path) != expected: + raise ValueError(f"distributed admission evidence differs: {path}") + source_admission = read_json(source_admission_path) + central_admission = read_json(central_admission_path) + source_worker = read_json(source_worker_path) + release = read_json(release_path) + receive = read_json(receive_path) + admission = validate_admission_pair( + source_admission, central_admission, plan["cache_execution_plan_sha256"], + ) + if ( + source_worker.get("status") != "complete" + or source_worker.get("worker") != worker_id + or source_worker.get("plan_sha256") != plan["cache_execution_plan_sha256"] + or source_worker.get("admission_state_sha256") != plan["source_admission"]["sha256"] + or source_worker.get("winner") != central_admission["winner"] + or source_worker.get("winner_checkpoint") != central_admission["winner_checkpoint"] + or source_worker.get("winner_config") != central_admission["winner_config"] + or source_worker.get("official_test_used") is not False + or source_worker.get("h2o_official_validation_used") is not False + ): + raise ValueError("external cache worker scientific binding differs") + checkpoint = Path(source_worker["winner_checkpoint"]["path"]) + config = Path(source_worker["winner_config"]["path"]) + if ( + not checkpoint.is_file() + or sha256(checkpoint) != source_worker["winner_checkpoint"]["sha256"] + or not config.is_file() + or sha256(config) != source_worker["winner_config"]["sha256"] + ): + raise ValueError("external cache worker winner artifact differs") + validate_release_metadata( + release, receive, source_owner=source_owner, + source_worker_sha256=plan["source_worker_state"]["sha256"], + bridge_plan_sha256=plan["cache_release"]["plan_sha256"], + ) + if ( + release.get("file_count") != plan["cache_release"]["file_count"] + or release.get("total_bytes") != plan["cache_release"]["total_bytes"] + ): + raise ValueError("external cache release inventory totals differ") + if release["producer_worker_state"].get("value") != source_worker: + raise ValueError("external cache release worker value differs") + released_files = validate_released_cache_files( + release, plan["expected_cache_files"], plan["resolution_hw"], + ) + imported = deepcopy(source_worker) + imported["admission_state"] = str(central_admission_path.resolve()) + imported["admission_state_sha256"] = plan["central_admission"]["sha256"] + imported["distributed_admission_import"] = { + "schema_version": "phase9_distributed_admission_import_v1", + "status": "complete", "imported_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "worker": worker_id, "source_owner": source_owner, + "central_owner": assignment["central_owner"], + **admission, + "source_admission": { + "original_path": plan["source_admission"]["original_path"], + "evidence_path": str(source_admission_path.resolve()), + "sha256": plan["source_admission"]["sha256"], + }, + "central_admission": { + "path": str(central_admission_path.resolve()), + "sha256": plan["central_admission"]["sha256"], + }, + "source_worker_state": { + "original_path": plan["source_worker_state"]["original_path"], + "evidence_path": str(source_worker_path.resolve()), + "sha256": plan["source_worker_state"]["sha256"], + }, + "cache_release": { + "evidence_path": str(release_path.resolve()), + "sha256": plan["cache_release"]["sha256"], + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + }, + "cache_receive": { + "path": str(receive_path.resolve()), + "sha256": plan["cache_receive"]["sha256"], + }, + "released_cache_files": released_files, + "source_worker_state_preserved_unmodified": True, + "ordinary_single_host_binding_gate_changed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + audit = { + "schema_version": "phase9_distributed_admission_import_audit_v1", + "status": "complete", "created_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "worker": worker_id, "source_owner": source_owner, + "central_owner": assignment["central_owner"], + "source_admission_sha256": plan["source_admission"]["sha256"], + "central_admission_sha256": plan["central_admission"]["sha256"], + "host_local_operational_fields": admission["host_local_operational_fields"], + "normalized_scientific_binding_sha256": admission[ + "normalized_scientific_binding_sha256" + ], + "cache_release_sha256": plan["cache_release"]["sha256"], + "cache_receive_sha256": plan["cache_receive"]["sha256"], + "cache_release_file_count": release["file_count"], + "cache_release_total_bytes": release["total_bytes"], + "ordinary_single_host_binding_gate_changed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + return imported, audit + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output-state", type=Path, required=True) + parser.add_argument("--audit-output", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + if args.output_state.resolve() != Path(plan["output_state"]).resolve(): + parser.error("distributed admission output state differs") + if args.audit_output.resolve() != Path(plan["audit_output"]).resolve(): + parser.error("distributed admission audit output differs") + with Path(f"{args.output_state}.import.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + imported, audit = build_imported_state(args.plan, plan) + existing = read_json(args.output_state) if args.output_state.is_file() else None + if existing and existing.get("distributed_admission_import", {}).get( + "plan_sha256" + ) == sha256(args.plan): + if not args.audit_output.is_file(): + parser.error("imported worker exists without its audit") + print(json.dumps(existing, indent=2)) + return + atomic_json(args.output_state, imported) + audit["imported_worker_state"] = { + "path": str(args.output_state.resolve()), "sha256": sha256(args.output_state), + } + atomic_json(args.audit_output, audit) + print(json.dumps(imported, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/inspect_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/inspect_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..dad107db9c8f8406ee3a87089dcc0316a72f4fbb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/inspect_h2o.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +"""Inventory an extracted H2O egocentric dataset using only the standard library.""" + +from __future__ import annotations + +import argparse +import json +import struct +from collections import Counter, defaultdict +from pathlib import Path + + +CORE_FRAME_MODALITIES = { + "rgb", + "rgb256", + "depth", + "cam_pose", + "hand_pose", + "hand_pose_mano", + "obj_pose", + "obj_pose_rt", +} +TRAIN_LABEL_MODALITIES = {"action_label", "verb_label"} + + +def image_info(path: Path) -> dict[str, object]: + with path.open("rb") as handle: + header = handle.read(32) + if header.startswith(b"\x89PNG\r\n\x1a\n"): + width, height, bit_depth, color_type = struct.unpack(">IIBB", header[16:26]) + channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(color_type) + return { + "format": "PNG", + "width": width, + "height": height, + "bit_depth_per_channel": bit_depth, + "channels": channels, + "png_color_type": color_type, + } + + if header.startswith(b"\xff\xd8"): + handle.seek(2) + while True: + marker_start = handle.read(1) + if not marker_start: + break + if marker_start != b"\xff": + continue + marker = handle.read(1) + while marker == b"\xff": + marker = handle.read(1) + if marker in {b"\xd8", b"\xd9"}: + continue + size_raw = handle.read(2) + if len(size_raw) != 2: + break + size = struct.unpack(">H", size_raw)[0] + if marker and marker[0] in { + 0xC0, + 0xC1, + 0xC2, + 0xC3, + 0xC5, + 0xC6, + 0xC7, + 0xC9, + 0xCA, + 0xCB, + 0xCD, + 0xCE, + 0xCF, + }: + payload = handle.read(6) + bits, height, width, channels = struct.unpack(">BHHB", payload) + return { + "format": "JPEG", + "width": width, + "height": height, + "bit_depth_per_channel": bits, + "channels": channels, + } + handle.seek(size - 2, 1) + return {"format": "unknown"} + + +def numeric_frame_ids(files: list[Path]) -> set[int]: + return {int(path.stem) for path in files if path.stem.isdigit()} + + +def inspect_text(path: Path) -> dict[str, object]: + values = path.read_text(encoding="utf-8").split() + numeric = [] + for value in values[:8]: + try: + numeric.append(float(value)) + except ValueError: + numeric.append(value) + return {"value_count": len(values), "first_values": numeric} + + +def inspect_splits(root: Path) -> dict[str, object]: + result: dict[str, object] = {} + split_root = root / "label_split" + for split_path in sorted(split_root.glob("*.txt")): + lines = [line.strip() for line in split_path.read_text().splitlines() if line.strip()] + if split_path.name.startswith("pose_"): + missing = sum(not (root / line).is_file() for line in lines) + result[split_path.name] = { + "rows": len(lines), + "missing_paths": missing, + "first": lines[0] if lines else None, + "last": lines[-1] if lines else None, + } + else: + header = lines[0].split() if lines else [] + rows = [line.split() for line in lines[1:]] + path_index = header.index("path") if "path" in header else 1 + missing = sum(not (root / row[path_index]).is_dir() for row in rows) + class_counts: Counter[str] = Counter() + if "action_label" in header: + label_index = header.index("action_label") + class_counts.update(row[label_index] for row in rows) + result[split_path.name] = { + "rows": len(rows), + "columns": header, + "missing_paths": missing, + "class_counts": dict(sorted(class_counts.items(), key=lambda item: int(item[0]))), + } + return result + + +def inspect_dataset(root: Path) -> dict[str, object]: + modalities: dict[str, dict[str, object]] = defaultdict( + lambda: {"files": 0, "bytes": 0, "suffixes": set(), "sample": None} + ) + subject_take_counts: Counter[str] = Counter() + subject_rgb_frames: Counter[str] = Counter() + scene_take_counts: Counter[str] = Counter() + cameras: Counter[str] = Counter() + alignment_issue_counts: Counter[str] = Counter() + unexpected_alignment_issue_counts: Counter[str] = Counter() + alignment_examples: list[dict[str, object]] = [] + missing_modality_directory_takes: Counter[str] = Counter() + unexpected_modality_directory_takes: Counter[str] = Counter() + scalar_label_counts: dict[str, Counter[str]] = { + "action_label": Counter(), + "verb_label": Counter(), + "obj_pose": Counter(), + "obj_pose_rt": Counter(), + } + hand_presence: dict[str, Counter[str]] = { + "hand_pose": Counter(), + "hand_pose_mano": Counter(), + } + + take_dirs = sorted(root.glob("subject*/*/*/cam4")) + for cam4 in take_dirs: + subject, scene, take = cam4.parts[-4:-1] + subject_take_counts[subject] += 1 + scene_take_counts[f"{subject}/{scene}"] += 1 + for camera_dir in cam4.parent.glob("cam*"): + if camera_dir.is_dir(): + cameras[camera_dir.name] += 1 + + files_by_modality: dict[str, list[Path]] = {} + for child in sorted(cam4.iterdir()): + if child.is_dir(): + files = [entry for entry in child.iterdir() if entry.is_file()] + files_by_modality[child.name] = files + stats = modalities[child.name] + stats["files"] = int(stats["files"]) + len(files) + stats["bytes"] = int(stats["bytes"]) + sum(entry.stat().st_size for entry in files) + suffixes = stats["suffixes"] + assert isinstance(suffixes, set) + suffixes.update(entry.suffix.lower() for entry in files) + if stats["sample"] is None and files: + sample_path = sorted(files)[0] + sample: dict[str, object] = {"path": str(sample_path.relative_to(root))} + if sample_path.suffix.lower() in {".png", ".jpg", ".jpeg"}: + sample.update(image_info(sample_path)) + elif sample_path.suffix.lower() == ".txt": + sample.update(inspect_text(sample_path)) + stats["sample"] = sample + if child.name in scalar_label_counts: + for entry in files: + values = entry.read_text(encoding="utf-8").split() + if values: + scalar_label_counts[child.name][str(int(float(values[0])))] += 1 + if child.name in hand_presence: + right_flag_index = 64 if child.name == "hand_pose" else 62 + for entry in files: + values = entry.read_text(encoding="utf-8").split() + if len(values) <= right_flag_index: + hand_presence[child.name]["malformed"] += 1 + continue + left = int(float(values[0])) != 0 + right = int(float(values[right_flag_index])) != 0 + state = { + (True, True): "both", + (True, False): "left_only", + (False, True): "right_only", + (False, False): "neither", + }[(left, right)] + hand_presence[child.name][state] += 1 + elif child.is_file(): + stats = modalities[child.name] + stats["files"] = int(stats["files"]) + 1 + stats["bytes"] = int(stats["bytes"]) + child.stat().st_size + suffixes = stats["suffixes"] + assert isinstance(suffixes, set) + suffixes.add(child.suffix.lower()) + if stats["sample"] is None: + stats["sample"] = { + "path": str(child.relative_to(root)), + **inspect_text(child), + } + + expected_modalities = set(CORE_FRAME_MODALITIES) + if subject != "subject4": + expected_modalities.update(TRAIN_LABEL_MODALITIES) + actual_modalities = set(files_by_modality) + for modality in expected_modalities - actual_modalities: + missing_modality_directory_takes[modality] += 1 + for modality in actual_modalities - expected_modalities: + unexpected_modality_directory_takes[modality] += 1 + + rgb_ids = numeric_frame_ids(files_by_modality.get("rgb", [])) + subject_rgb_frames[subject] += len(rgb_ids) + for modality, files in files_by_modality.items(): + ids = numeric_frame_ids(files) + if ids and ids != rgb_ids: + missing = len(rgb_ids - ids) + extra = len(ids - rgb_ids) + if modality in expected_modalities: + alignment_issue_counts[modality] += 1 + alignment_scope = "expected" + else: + unexpected_alignment_issue_counts[modality] += 1 + alignment_scope = "unexpected" + if len(alignment_examples) < 20: + alignment_examples.append( + { + "take": f"{subject}/{scene}/{take}", + "modality": modality, + "scope": alignment_scope, + "missing_vs_rgb": missing, + "extra_vs_rgb": extra, + } + ) + + serializable_modalities = {} + for name, stats in sorted(modalities.items()): + serializable_modalities[name] = { + **stats, + "suffixes": sorted(stats["suffixes"]), + } + + object_stats = {} + for object_dir in sorted((root / "object").glob("*")): + if object_dir.is_dir(): + object_stats[object_dir.name] = sorted(path.name for path in object_dir.iterdir() if path.is_file()) + + return { + "root": str(root.resolve()), + "subjects": sorted(subject_take_counts), + "take_count": sum(subject_take_counts.values()), + "take_counts_by_subject": dict(sorted(subject_take_counts.items())), + "rgb_frames_by_subject": dict(sorted(subject_rgb_frames.items())), + "rgb_frames_total": sum(subject_rgb_frames.values()), + "take_counts_by_subject_scene": dict(sorted(scene_take_counts.items())), + "camera_directories": dict(sorted(cameras.items())), + "modalities": serializable_modalities, + "frame_alignment_issue_takes": dict(sorted(alignment_issue_counts.items())), + "unexpected_frame_alignment_issue_takes": dict(sorted(unexpected_alignment_issue_counts.items())), + "frame_alignment_examples": alignment_examples, + "missing_modality_directory_takes": dict(sorted(missing_modality_directory_takes.items())), + "unexpected_modality_directory_takes": dict(sorted(unexpected_modality_directory_takes.items())), + "per_frame_label_counts": { + name: dict(sorted(counts.items(), key=lambda item: int(item[0]))) + for name, counts in scalar_label_counts.items() + }, + "hand_presence_counts": { + name: dict(sorted(counts.items())) for name, counts in hand_presence.items() + }, + "objects": object_stats, + "splits": inspect_splits(root), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("root", type=Path, help="Extracted H2O root") + parser.add_argument("--output", type=Path, help="Write JSON to this path") + args = parser.parse_args() + report = inspect_dataset(args.root) + payload = json.dumps(report, indent=2, ensure_ascii=False) + "\n" + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(payload, encoding="utf-8") + print(payload, end="") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/merge_phase9_hot_prefill.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/merge_phase9_hot_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..a7db862b539b070f3f4174295d1c83bcbc7a2dfa --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/merge_phase9_hot_prefill.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Atomically hardlink completed HOT3D prefill shards into a live cache.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path + +from scripts.cache_phase7_hot3d import sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_prefill_reports(reports: list[dict]) -> None: + if not reports: + raise ValueError("at least one prefill report is required") + for report in reports: + if ( + report.get("status") != "complete" + or report.get("mode") != "staged_prefill" + or report.get("official_test_used") is not False + ): + raise ValueError("prefill report is incomplete or lacks test isolation") + stable_keys = ( + "full_candidate_clips", "requested_target_clips", "max_recordings", + "candidate_source_indices_sha256", + ) + for key in stable_keys: + if len({json.dumps(report.get(key), sort_keys=True) for report in reports}) != 1: + raise ValueError(f"prefill reports disagree on {key}") + source_hashes = {report["source_manifest"]["sha256"] for report in reports} + if len(source_hashes) != 1: + raise ValueError("prefill reports disagree on source manifest SHA256") + ranges = sorted(tuple(report["candidate_position_range"]) for report in reports) + if any(first[1] > second[0] for first, second in zip(ranges, ranges[1:])): + raise ValueError("prefill position ranges overlap") + + +def merge_prefills( + target_output_dir: Path, prefill_output_dirs: list[Path], report_path: Path, +) -> dict: + reports = [ + json.loads((path / "cache_report.json").read_text(encoding="utf-8")) + for path in prefill_output_dirs + ] + validate_prefill_reports(reports) + target_clips = target_output_dir / "clips" + if not target_clips.is_dir(): + raise ValueError("target cache clips directory does not exist") + if (target_output_dir / "cache_manifest.jsonl").exists(): + raise ValueError("target deployable manifest is already frozen") + linked = existing_identical = 0 + shard_records = [] + for output_dir, report in zip(prefill_output_dirs, reports, strict=True): + manifest = output_dir / "prefill_manifest.jsonl" + if sha256(manifest) != report["cache_manifest"]["sha256"]: + raise ValueError(f"prefill manifest SHA256 differs: {manifest}") + rows = [ + json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if len(rows) != int(report["clips"]): + raise ValueError(f"prefill manifest row count differs: {manifest}") + for row in rows: + source = Path(row["cache_path"]) + expected_name = f"clip_{int(row['source_clip_index']):07d}.npz" + if source.name != expected_name or not source.is_file(): + raise ValueError(f"invalid staged cache path: {source}") + if sha256(source) != row["cache_sha256"]: + raise ValueError(f"staged cache SHA256 differs: {source}") + target = target_clips / expected_name + try: + os.link(source, target) + linked += 1 + except FileExistsError: + if sha256(target) != row["cache_sha256"]: + raise ValueError(f"target cache collision differs: {target}") + existing_identical += 1 + shard_records.append({ + "output_dir": str(output_dir.resolve()), + "report_sha256": sha256(output_dir / "cache_report.json"), + "manifest_sha256": sha256(manifest), + "candidate_position_range": report["candidate_position_range"], + "clips": len(rows), + }) + result = { + "schema_version": "phase9_hot_prefill_merge_v1", + "status": "complete", "created_utc": utc_now(), + "target_output_dir": str(target_output_dir.resolve()), + "linked": linked, "existing_identical": existing_identical, + "shards": shard_records, "official_test_used": False, + } + report_path.parent.mkdir(parents=True, exist_ok=True) + temporary = report_path.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(report_path) + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--target-output-dir", type=Path, required=True) + parser.add_argument("--prefill-output-dir", type=Path, action="append", required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + result = merge_prefills( + args.target_output_dir, args.prefill_output_dir, args.report, + ) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/merge_phase9_selection_binding_recovery.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/merge_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..b71938506149e999f92a5aa6039455009504e185 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/merge_phase9_selection_binding_recovery.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""Dry-run, validate, and atomically merge Phase 9 selection recovery.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any, Callable + +from scripts.run_phase9_selection_binding_recovery import ( + atomic_json, + validate_recovered_output, +) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_release( + *, release_path: Path, plan_path: Path, plan: dict[str, Any], owner: str, +) -> dict[str, Any]: + if not release_path.is_file(): + raise ValueError(f"selection recovery release missing: {owner}") + release = json.loads(release_path.read_text(encoding="utf-8")) + root = release_path.parent.resolve() + expected_ids = { + item["id"] for item in plan["evaluations"] if item["owner"] == owner + } + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != owner + or release.get("plan", {}).get("sha256") != sha256(plan_path) + or Path(str(release.get("root", ""))).resolve() != root + or set(release.get("evaluation_ids", [])) != expected_ids + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or release.get("read_only_after_publish") is not True + ): + raise ValueError(f"selection recovery release contract differs: {owner}") + seen = set() + total_bytes = 0 + for item in release.get("files", []): + relative = Path(item["path"]) + if relative.is_absolute() or ".." in relative.parts or str(relative) in seen: + raise ValueError(f"invalid recovery release path: {relative}") + seen.add(str(relative)) + path = root / relative + if ( + not path.is_file() + or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"selection recovery release file differs: {path}") + total_bytes += item["bytes"] + if ( + len(seen) != release.get("file_count") + or total_bytes != release.get("total_bytes") + ): + raise ValueError(f"selection recovery release inventory differs: {owner}") + evidence = {item["id"]: item for item in release["evaluations"]} + if set(evidence) != expected_ids: + raise ValueError(f"selection recovery release evidence differs: {owner}") + for item in plan["evaluations"]: + if item["owner"] != owner: + continue + relative_output = Path(evidence[item["id"]]["output_dir"]) + if (root / relative_output).resolve() != Path(item["output_dir"]).resolve(): + raise ValueError(f"selection recovery output path differs: {item['id']}") + validate_recovered_output(item) + return release + + +def symlink_copy(source: str, destination: str) -> str: + os.symlink(str(Path(source).resolve()), destination) + return destination + + +def recovered_output_map( + plan: dict[str, Any], releases: dict[str, dict[str, Any]], + release_paths: dict[str, Path], +) -> dict[str, Path]: + result = {} + for owner, release in releases.items(): + root = release_paths[owner].parent.resolve() + by_id = {item["id"]: item for item in release["evaluations"]} + for item in plan["evaluations"]: + if item["owner"] == owner: + result[item["id"]] = root / by_id[item["id"]]["output_dir"] + return result + + +def run_dry_selection( + *, plan: dict[str, Any], recovered: dict[str, Path], +) -> dict[str, Any]: + selection_plan_path = Path(plan["selection_plan"]["path"]) + selection_plan = json.loads(selection_plan_path.read_text(encoding="utf-8")) + dry_root = Path(plan["dry_run_root"]) / sha256(selection_plan_path) + milestone_root = dry_root / "h2o_multifold_milestones" + output_json = dry_root / "unified_selection.json" + output_csv = dry_root / "unified_selection.csv" + if output_json.is_file() and output_csv.is_file(): + report = json.loads(output_json.read_text(encoding="utf-8")) + if ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + ): + return { + "root": str(dry_root.resolve()), + "json": {"path": str(output_json.resolve()), "sha256": sha256(output_json)}, + "csv": {"path": str(output_csv.resolve()), "sha256": sha256(output_csv)}, + "winner": report["winner"], + } + raise ValueError("existing selection dry-run output differs") + if dry_root.exists(): + shutil.rmtree(dry_root) + dry_root.mkdir(parents=True) + shutil.copytree( + Path(selection_plan["fold_milestone_root"]), milestone_root, + copy_function=symlink_copy, + ) + for item in plan["evaluations"]: + target = ( + milestone_root / item["condition"] / item["checkpoint_id"] + / item["input_mode"] + ) + if target.is_symlink() or target.is_file(): + target.unlink() + elif target.is_dir(): + shutil.rmtree(target) + os.symlink(str(recovered[item["id"]].resolve()), target, target_is_directory=True) + command = [ + sys.executable, "-m", "scripts.summarize_phase9_unified_selection", + "--external-root", selection_plan["external_root"], + "--fold-final-root", selection_plan["fold_final_root"], + "--fold-milestone-root", str(milestone_root.resolve()), + "--multifold-index", selection_plan["multifold_index"], + "--output-json", str(output_json.resolve()), + "--output-csv", str(output_csv.resolve()), + ] + log_path = dry_root / "summarizer.log" + with log_path.open("x", encoding="utf-8") as log: + result = subprocess.run( + command, cwd=Path.cwd(), stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + if result.returncode or not output_json.is_file() or not output_csv.is_file(): + raise ValueError(f"selection dry-run summarizer failed: {result.returncode}") + report = json.loads(output_json.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError("selection dry-run report isolation differs") + return { + "root": str(dry_root.resolve()), + "json": {"path": str(output_json.resolve()), "sha256": sha256(output_json)}, + "csv": {"path": str(output_csv.resolve()), "sha256": sha256(output_csv)}, + "log": {"path": str(log_path.resolve()), "sha256": sha256(log_path)}, + "winner": report["winner"], + } + + +def canonical_output(plan: dict[str, Any], item: dict[str, Any]) -> Path: + return ( + Path(plan["canonical_fold_milestone_root"]) + / item["condition"] / item["checkpoint_id"] / item["input_mode"] + ) + + +def prepare_outputs( + *, plan: dict[str, Any], recovered: dict[str, Path], +) -> dict[str, Path]: + prepared = {} + for item in plan["evaluations"]: + canonical = canonical_output(plan, item) + destination = canonical.parent / f".{canonical.name}.selection_recovery_v2_ready" + if destination.exists(): + shutil.rmtree(destination) + shutil.copytree(recovered[item["id"]], destination, copy_function=shutil.copy2) + candidate = {**item, "output_dir": str(destination.resolve())} + validate_recovered_output(candidate) + prepared[item["id"]] = destination + return prepared + + +def merge_outputs( + *, plan_path: Path, plan: dict[str, Any], prepared: dict[str, Path], + dry_run: dict[str, Any], releases: dict[str, dict[str, Any]], + release_paths: dict[str, Path], state_path: Path, +) -> dict[str, Any]: + backup_root = Path(plan["canonical_merge_backup_root"]) + backup_root.mkdir(parents=True, exist_ok=True) + lock_path = backup_root.parent / ".selection_binding_v2_merge.lock" + plan_hash = sha256(plan_path) + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if state_path.is_file(): + existing = json.loads(state_path.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == plan_hash + ): + return existing + if existing.get("plan_sha256") not in {None, plan_hash}: + raise ValueError("existing selection merge state differs") + replacements = [] + try: + for item in plan["evaluations"]: + canonical = canonical_output(plan, item) + backup = ( + backup_root / item["condition"] / item["checkpoint_id"] + / item["input_mode"] + ) + if backup.exists(): + raise ValueError(f"selection merge backup already exists: {backup}") + if not canonical.is_dir(): + raise ValueError(f"selection canonical output missing: {canonical}") + backup.parent.mkdir(parents=True, exist_ok=True) + os.replace(canonical, backup) + try: + os.replace(prepared[item["id"]], canonical) + except Exception: + os.replace(backup, canonical) + raise + replacements.append((item, canonical, backup)) + except Exception: + for item, canonical, backup in reversed(replacements): + staging = canonical.parent / f".{canonical.name}.rollback_recovered" + if staging.exists(): + shutil.rmtree(staging) + os.replace(canonical, staging) + os.replace(backup, canonical) + raise + merged = [] + for item, canonical, backup in replacements: + candidate = {**item, "output_dir": str(canonical.resolve())} + evidence = validate_recovered_output(candidate) + merged.append({ + "id": item["id"], "canonical_output": str(canonical.resolve()), + "backup_output": str(backup.resolve()), **evidence, + }) + state = { + "schema_version": "phase9_selection_binding_recovery_merge_state_v1", + "status": "complete", "completed_utc": datetime.now(timezone.utc).isoformat(), + "plan": str(plan_path.resolve()), "plan_sha256": plan_hash, + "dry_run": dry_run, + "releases": { + owner: { + "path": str(release_paths[owner].resolve()), + "sha256": sha256(release_paths[owner]), + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + } + for owner, release in releases.items() + }, + "merged": merged, + "failure_backup": plan["failure_backup"], + "summarizer_binding_gate_changed": False, + "evaluation_reports_modified": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(state_path, state) + return state + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--taku3-release", type=Path, required=True) + parser.add_argument("--server-new-release", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if ( + plan.get("official_test_used") is not False + or args.state.resolve() != Path(plan["canonical_merge_state"]).resolve() + ): + parser.error("selection merge plan/state contract differs") + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + parser.error(f"selection recovery code binding differs: {path}") + release_paths = { + "taku3": args.taku3_release, "server_new": args.server_new_release, + } + releases = { + owner: validate_release( + release_path=path, plan_path=args.plan, plan=plan, owner=owner, + ) + for owner, path in release_paths.items() + } + recovered = recovered_output_map(plan, releases, release_paths) + dry_run = run_dry_selection(plan=plan, recovered=recovered) + prepared = prepare_outputs(plan=plan, recovered=recovered) + state = merge_outputs( + plan_path=args.plan, plan=plan, prepared=prepared, dry_run=dry_run, + releases=releases, release_paths=release_paths, state_path=args.state, + ) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/merge_sota_bundles.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/merge_sota_bundles.py new file mode 100644 index 0000000000000000000000000000000000000000..584ee70fdf4d271fce83b8faeacf785e8d0e4324 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/merge_sota_bundles.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Merge disjoint inference shards and restore official-manifest frame order.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import numpy as np + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("inputs", nargs="+", type=Path) + args = parser.parse_args() + bundles = [PredictionBundle.load(path) for path in args.inputs] + names = {bundle.model_name for bundle in bundles} + if len(names) != 1: + raise ValueError(f"Shard model names differ: {names}") + has_vertices = {bundle.vertices_camera_m is not None for bundle in bundles} + if len(has_vertices) != 1: + raise ValueError("Shard vertex availability differs") + keys, _, _ = load_frame_index(args.manifest) + order_lookup = {str(key): index for index, key in enumerate(keys)} + concatenated_keys = np.concatenate([bundle.frame_keys for bundle in bundles]) + if set(map(str, concatenated_keys.tolist())) != set(map(str, keys.tolist())): + raise ValueError("Merged shards do not exactly cover the manifest") + order = np.argsort([order_lookup[str(key)] for key in concatenated_keys]) + metadata = dict(bundles[0].metadata) + metadata.pop("num_shards", None) + metadata.pop("shard_index", None) + for name in ( + "refined_windows", + "missing_detection_windows", + "tail_hand_frames_falling_back_to_wilor", + "root_iterations_total", + "smooth_iterations_total", + "run_count", + "new_initializations", + "new_optimizations", + ): + if all(name in bundle.metadata for bundle in bundles): + metadata[name] = sum(int(bundle.metadata[name]) for bundle in bundles) + delta_name = "initializer_mesh_reconstruction_delta_mm" + if all(delta_name in bundle.metadata for bundle in bundles): + weights = np.asarray( + [int(bundle.metadata.get("refined_windows", 0)) for bundle in bundles], + dtype=np.float64, + ) + values = np.asarray( + [float(bundle.metadata[delta_name]) for bundle in bundles], + dtype=np.float64, + ) + if weights.sum() > 0: + metadata[delta_name] = float(np.average(values, weights=weights)) + metadata.update({ + "merged_shards": len(bundles), + "shard_inputs": [str(path.resolve()) for path in args.inputs], + }) + PredictionBundle( + model_name=bundles[0].model_name, + frame_keys=concatenated_keys[order], + takes=np.concatenate([bundle.takes for bundle in bundles])[order], + frame_ids=np.concatenate([bundle.frame_ids for bundle in bundles])[order], + joints_camera_m=np.concatenate([ + bundle.joints_camera_m for bundle in bundles + ])[order], + detected=np.concatenate([bundle.detected for bundle in bundles])[order], + confidence=np.concatenate([bundle.confidence for bundle in bundles])[order], + vertices_camera_m=( + np.concatenate([bundle.vertices_camera_m for bundle in bundles])[order] + if True in has_vertices + else None + ), + metadata=metadata, + ).save(args.output) + print(f"merged {len(bundles)} shards into {args.output}") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/phase9_distributed_assignment.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/phase9_distributed_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..a244226e86486c4dc547fe55431fa31f45e015c4 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/phase9_distributed_assignment.py @@ -0,0 +1,156 @@ +"""Shared ownership checks for distributed Phase 9 controllers.""" + +from __future__ import annotations + +import json +from pathlib import Path +import socket +from typing import Any + +from scripts.run_phase9_unified_train_queue import sha256 + + +MACHINES = ("taku3", "server_new") + + +def load_assignment(plan: dict[str, Any]) -> dict[str, Any]: + binding = plan.get("distributed_assignment", {}) + path = Path(str(binding.get("path", ""))) + if not path.is_file() or sha256(path) != binding.get("sha256"): + raise ValueError("distributed assignment binding differs") + assignment = json.loads(path.read_text(encoding="utf-8")) + if ( + assignment.get("schema_version") + != "foundation_phase9_distributed_assignment_v2" + or assignment.get("central_owner") != "taku3" + or assignment.get("selection_owner") != "taku3" + or assignment.get("report_owner") != "taku3" + or assignment.get("scientific_contract", {}).get("official_test_used") + is not False + or assignment.get("writer_contract", {}).get( + "single_writer_per_output" + ) is not True + or assignment.get("writer_contract", {}).get( + "live_reverse_sync_forbidden" + ) is not True + ): + raise ValueError("distributed assignment contract differs") + return assignment + + +def detect_machine(assignment: dict[str, Any], requested: str | None) -> str: + host = socket.gethostname() + matches = [ + machine for machine in MACHINES + if assignment["machines"][machine]["hostname"] == host + ] + if requested is not None: + if requested not in MACHINES or assignment["machines"][requested]["hostname"] != host: + raise ValueError("requested distributed machine differs from hostname") + return requested + if len(matches) != 1: + raise ValueError(f"hostname is not uniquely assigned: {host}") + return matches[0] + + +def gpu_allowlist(assignment: dict[str, Any], machine: str) -> list[int]: + allowed = assignment["machines"][machine]["physical_gpu_allowlist"] + if ( + not isinstance(allowed, list) + or not allowed + or len(allowed) != len(set(allowed)) + or any(not isinstance(gpu, int) for gpu in allowed) + ): + raise ValueError(f"distributed GPU allowlist differs: {machine}") + if machine == "server_new" and allowed != [0, 1, 2, 5]: + raise ValueError("server_new GPU allowlist must be exactly 0/1/2/5") + return allowed + + +def role_owners(assignment: dict[str, Any]) -> dict[str, str]: + records = assignment["stage_condition_ownership"]["roles"] + result = {item["role"]: item["owner"] for item in records} + expected = { + "full", "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + } + if set(result) != expected or len(records) != len(result): + raise ValueError("distributed role ownership differs") + if any(owner not in MACHINES for owner in result.values()): + raise ValueError("distributed role owner is unknown") + return result + + +def condition_owners( + registry: dict[str, Any], assignment: dict[str, Any], +) -> dict[str, str]: + owners = role_owners(assignment) + result = {} + for item in registry["conditions"]: + condition = item["condition"] + role = item.get("role") + if role not in owners or condition in result: + raise ValueError(f"distributed training role differs: {condition}") + result[condition] = owners[role] + if len(result) != 7: + raise ValueError("distributed training registry must contain seven jobs") + return result + + +def controller_state_path(plan: dict[str, Any], machine: str) -> Path: + states = plan.get("controller_states", {}) + if set(states) != set(MACHINES): + raise ValueError("distributed controller states differ") + paths = [str(Path(value).resolve()) for value in states.values()] + if len(paths) != len(set(paths)): + raise ValueError("distributed controller states are not unique") + return Path(states[machine]) + + +def distribute_evaluations( + *, evaluations: list[dict[str, Any]], assignment: dict[str, Any], + worker_state_root: Path, +) -> list[dict[str, Any]]: + owners = role_owners(assignment) + grouped: dict[str, list[dict[str, Any]]] = {machine: [] for machine in MACHINES} + for item in evaluations: + role = item.get("training_role") + if role not in owners: + raise ValueError(f"distributed evaluation role differs: {item.get('id')}") + owner = owners[role] + item["owner"] = owner + grouped[owner].append(item) + workers = [] + for owner in MACHINES: + gpus = gpu_allowlist(assignment, owner) + buckets: dict[int, list[str]] = {gpu: [] for gpu in gpus} + for index, item in enumerate(grouped[owner]): + buckets[gpus[index % len(gpus)]].append(item["id"]) + for gpu, identifiers in buckets.items(): + if not identifiers: + continue + workers.append({ + "id": f"{owner}_gpu{gpu}", "owner": owner, + "physical_gpu_id": gpu, + "state": str(( + worker_state_root / owner / f"gpu{gpu}_state.json" + ).resolve()), + "evaluation_ids": identifiers, + }) + ids = [item["id"] for item in evaluations] + assigned = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(ids) != len(set(ids)) + or len(assigned) != len(ids) + or len(set(assigned)) != len(ids) + or set(assigned) != set(ids) + ): + raise ValueError("distributed evaluation workers overlap or omit IDs") + return workers + + +def local_workers(workers: list[dict[str, Any]], machine: str) -> list[dict[str, Any]]: + result = [item for item in workers if item.get("owner") == machine] + if any(item.get("owner") not in MACHINES for item in workers): + raise ValueError("distributed evaluation worker owner differs") + return result diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/postprocess_video_jitter.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/postprocess_video_jitter.py new file mode 100644 index 0000000000000000000000000000000000000000..0b737af92d0fc6c2aa7713b0b03d209f6147eb86 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/postprocess_video_jitter.py @@ -0,0 +1,927 @@ +#!/usr/bin/env python3 +"""Cache raw long-sequence predictions and render jitter-smoothed MANO demos. + +This is an offline visualization postprocessor. It does not change the model, +checkpoint, evaluator, or reported metrics. Missing raw caches are reconstructed +with the exact checkpoint and non-overlapping temporal chunks recorded in the +source selection manifest. Later filter changes reuse those caches. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml +from scipy.signal import butter, sosfiltfilt +from scipy.spatial.transform import Rotation + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + MeshLayer, + project_mesh_layers, + render_mesh_layers, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.training.checkpoint import load_checkpoint + + +LEFT_COLOR_RGB = (40, 100, 235) +RIGHT_COLOR_RGB = (235, 55, 55) +MESH_ALPHA = 0.55 +CACHE_VERSION = 1 +RAW_CACHE_KEYS = ( + "mano_rotations_6d", + "mano_rotation_matrices", + "mano_shape", + "wrist_root_translation", + "vertices_camera", + "joints_camera", + "joint2d_norm", + "presence_logit", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_json_atomic(path: Path, value: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + os.replace(temporary, path) + + +def save_npz_atomic(path: Path, arrays: dict[str, np.ndarray]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") + with temporary.open("wb") as handle: + np.savez_compressed(handle, **arrays) + os.replace(temporary, path) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def add_header(image_rgb: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image_rgb.copy() + height = 8 + 22 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, + line, + (8, 20 + 22 * index), + cv2.FONT_HERSHEY_SIMPLEX, + 0.55, + (255, 255, 255), + 1, + cv2.LINE_AA, + ) + return output + + +class FFmpegVideoWriter: + """Stream BGR frames to an atomic, Mac-compatible H.264 MP4.""" + + def __init__( + self, + path: Path, + fps: float, + frame_hw: tuple[int, int], + *, + crf: int, + preset: str, + ) -> None: + self.path = path + self.frame_hw = frame_hw + self.frames_written = 0 + path.parent.mkdir(parents=True, exist_ok=True) + self.temporary = path.with_name(f".{path.stem}.tmp-{os.getpid()}.mp4") + height, width = frame_hw + command = [ + "ffmpeg", + "-nostdin", + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "rawvideo", + "-pix_fmt", + "bgr24", + "-s:v", + f"{width}x{height}", + "-r", + f"{fps:.8g}", + "-i", + "pipe:0", + "-an", + "-c:v", + "libx264", + "-preset", + preset, + "-crf", + str(crf), + "-pix_fmt", + "yuv420p", + "-movflags", + "+faststart", + str(self.temporary), + ] + self.process = subprocess.Popen( + command, + stdin=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + def write(self, frame_bgr: np.ndarray) -> None: + height, width = self.frame_hw + if frame_bgr.shape != (height, width, 3) or frame_bgr.dtype != np.uint8: + raise ValueError( + f"invalid video frame {frame_bgr.shape}/{frame_bgr.dtype}; " + f"expected {(height, width, 3)}/uint8" + ) + if self.process.stdin is None: + raise RuntimeError("ffmpeg stdin is unavailable") + try: + self.process.stdin.write(np.ascontiguousarray(frame_bgr).tobytes()) + except BrokenPipeError as error: + stderr = self._read_stderr() + raise RuntimeError(f"ffmpeg stopped while writing {self.path}: {stderr}") from error + self.frames_written += 1 + + def _read_stderr(self) -> str: + if self.process.stderr is None: + return "" + return self.process.stderr.read().decode("utf-8", errors="replace").strip() + + def close(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + stderr = self._read_stderr() + return_code = self.process.wait() + if return_code != 0: + self.temporary.unlink(missing_ok=True) + raise RuntimeError(f"ffmpeg failed for {self.path}: {stderr}") + os.replace(self.temporary, self.path) + + def abort(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + if self.process.poll() is None: + self.process.terminate() + try: + self.process.wait(timeout=5) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + self.temporary.unlink(missing_ok=True) + + +def lowpass(values: np.ndarray, cutoff_hz: float, fps: float, order: int) -> np.ndarray: + if not 0.0 < cutoff_hz < fps / 2.0: + raise ValueError(f"cutoff must be in (0, {fps / 2.0}), got {cutoff_hz}") + if values.shape[0] < max(12, order * 6): + raise ValueError(f"sequence too short for zero-phase filtering: {values.shape[0]}") + sections = butter(order, cutoff_hz, btype="lowpass", fs=fps, output="sos") + return np.asarray(sosfiltfilt(sections, values, axis=0), dtype=np.float32) + + +def smooth_rotations( + matrices: np.ndarray, + cutoff_hz: float, + fps: float, + order: int, +) -> np.ndarray: + """Low-pass SO(3) trajectories through sign-continuous unit quaternions.""" + + if matrices.ndim != 5 or matrices.shape[1:] != (2, 16, 3, 3): + raise ValueError(f"unexpected rotation shape: {matrices.shape}") + frame_count = matrices.shape[0] + quaternions = Rotation.from_matrix(matrices.reshape(-1, 3, 3)).as_quat() + quaternions = quaternions.reshape(frame_count, 2, 16, 4) + for frame_index in range(1, frame_count): + dots = np.sum( + quaternions[frame_index - 1] * quaternions[frame_index], + axis=-1, + ) + quaternions[frame_index][dots < 0.0] *= -1.0 + filtered = lowpass(quaternions, cutoff_hz, fps, order) + norms = np.linalg.norm(filtered, axis=-1, keepdims=True) + if np.any(norms < 1e-6): + raise RuntimeError("quaternion low-pass produced a near-zero norm") + filtered /= norms + smoothed = Rotation.from_quat(filtered.reshape(-1, 4)).as_matrix() + return smoothed.reshape(matrices.shape).astype(np.float32) + + +def smooth_prediction( + raw: dict[str, np.ndarray], + *, + translation_cutoff_hz: float, + rotation_cutoff_hz: float, + fps: float, + order: int, +) -> dict[str, np.ndarray]: + shape = raw["mano_shape"] + stable_shape = np.median(shape, axis=0, keepdims=True).astype(np.float32) + return { + "frame_ids": raw["frame_ids"].copy(), + "mano_rotation_matrices": smooth_rotations( + raw["mano_rotation_matrices"], rotation_cutoff_hz, fps, order + ), + "mano_shape": np.repeat(stable_shape, shape.shape[0], axis=0), + "wrist_root_translation": lowpass( + raw["wrist_root_translation"], translation_cutoff_hz, fps, order + ), + } + + +def build_model( + config: dict[str, Any], + checkpoint_path: Path, + checkpoint_step: int, + device: torch.device, +) -> BimanualReconstructionModel: + assets = config["assets"] + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + state = load_checkpoint(checkpoint_path, model, optimizer=None, map_location=device) + if int(state["step"]) != checkpoint_step: + raise ValueError( + f"checkpoint step mismatch: expected {checkpoint_step}, got {state['step']}" + ) + return model + + +def infer_case( + *, + case: dict[str, Any], + dataset: H2OCam4Dataset, + clip_indices: list[int], + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + checkpoint_sha256: str, +) -> dict[str, np.ndarray]: + values: dict[str, list[np.ndarray]] = defaultdict(list) + observed_frame_ids: list[int] = [] + for clip_number, clip_index in enumerate(clip_indices, start=1): + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + clip_frame_ids = sample["frame_id"].cpu().numpy().astype(np.int32) + observed_frame_ids.extend(int(value) for value in clip_frame_ids) + for key in RAW_CACHE_KEYS: + if key in prediction: + values[key].append(prediction[key][0].float().cpu().numpy()) + del prediction, batch + if clip_number % 25 == 0 or clip_number == len(clip_indices): + print( + f" inference {clip_number}/{len(clip_indices)} chunks " + f"({len(observed_frame_ids)}/{len(case['frame_ids'])} frames)", + flush=True, + ) + + expected_frame_ids = [int(value) for value in case["frame_ids"]] + if observed_frame_ids != expected_frame_ids: + raise RuntimeError( + f"inference frame mismatch for {case['take']}: " + f"{len(observed_frame_ids)} != {len(expected_frame_ids)}" + ) + arrays = { + key: np.concatenate(chunks, axis=0).astype(np.float32) + for key, chunks in values.items() + } + arrays.update({ + "frame_ids": np.asarray(observed_frame_ids, dtype=np.int32), + "take": np.asarray(str(case["take"])), + "checkpoint_sha256": np.asarray(checkpoint_sha256), + "cache_version": np.asarray(CACHE_VERSION, dtype=np.int32), + }) + required = { + "mano_rotation_matrices", + "mano_shape", + "wrist_root_translation", + "vertices_camera", + "joints_camera", + } + missing = sorted(required - arrays.keys()) + if missing: + raise RuntimeError(f"model output is missing cache fields: {missing}") + for key, value in arrays.items(): + if np.issubdtype(value.dtype, np.floating) and not np.isfinite(value).all(): + raise RuntimeError(f"non-finite values in raw output {key} for {case['take']}") + return arrays + + +def load_raw_cache( + path: Path, + *, + case: dict[str, Any], + checkpoint_sha256: str, +) -> dict[str, np.ndarray] | None: + if not path.is_file(): + return None + try: + with np.load(path, allow_pickle=False) as archive: + raw = {key: archive[key] for key in archive.files} + if int(raw["cache_version"]) != CACHE_VERSION: + return None + if str(raw["take"]) != str(case["take"]): + return None + if str(raw["checkpoint_sha256"]) != checkpoint_sha256: + return None + expected = np.asarray(case["frame_ids"], dtype=np.int32) + if not np.array_equal(raw["frame_ids"], expected): + return None + return raw + except (KeyError, OSError, ValueError): + return None + + +def rebuild_mano_geometry( + prediction: dict[str, np.ndarray], + mano_layer: ManoCameraLayer, + device: torch.device, + *, + batch_size: int = 128, +) -> None: + vertices: list[np.ndarray] = [] + joints: list[np.ndarray] = [] + frame_count = prediction["frame_ids"].shape[0] + for start in range(0, frame_count, batch_size): + stop = min(start + batch_size, frame_count) + rotations = torch.from_numpy( + prediction["mano_rotation_matrices"][start:stop] + ).to(device) + shape = torch.from_numpy(prediction["mano_shape"][start:stop]).to(device) + translation = torch.from_numpy( + prediction["wrist_root_translation"][start:stop] + ).to(device) + with torch.inference_mode(): + vertex_batch, joint_batch = mano_layer(rotations, shape, translation) + vertices.append(vertex_batch.float().cpu().numpy()) + joints.append(joint_batch.float().cpu().numpy()) + prediction["vertices_camera"] = np.concatenate(vertices, axis=0).astype(np.float32) + prediction["joints_camera"] = np.concatenate(joints, axis=0).astype(np.float32) + + +def acceleration_stats(points_m: np.ndarray) -> dict[str, float]: + acceleration_mm = np.linalg.norm(np.diff(points_m, n=2, axis=0), axis=-1) * 1000.0 + return { + "mean_mm_per_frame2": float(acceleration_mm.mean()), + "p50_mm_per_frame2": float(np.percentile(acceleration_mm, 50)), + "p95_mm_per_frame2": float(np.percentile(acceleration_mm, 95)), + } + + +def displacement_stats(raw_m: np.ndarray, smoothed_m: np.ndarray) -> dict[str, float]: + displacement_mm = np.linalg.norm(smoothed_m - raw_m, axis=-1) * 1000.0 + return { + "mean_mm": float(displacement_mm.mean()), + "p50_mm": float(np.percentile(displacement_mm, 50)), + "p95_mm": float(np.percentile(displacement_mm, 95)), + "max_mm": float(displacement_mm.max()), + } + + +def rotation_displacement_stats( + raw_matrices: np.ndarray, + smoothed_matrices: np.ndarray, +) -> dict[str, float]: + relative = np.swapaxes(raw_matrices, -1, -2) @ smoothed_matrices + radians = Rotation.from_matrix(relative.reshape(-1, 3, 3)).magnitude() + degrees = np.degrees(radians) + return { + "mean_degrees": float(degrees.mean()), + "p50_degrees": float(np.percentile(degrees, 50)), + "p95_degrees": float(np.percentile(degrees, 95)), + "max_degrees": float(degrees.max()), + } + + +def jitter_metrics( + raw: dict[str, np.ndarray], + smoothed: dict[str, np.ndarray], +) -> dict[str, Any]: + raw_wrist = acceleration_stats(raw["wrist_root_translation"]) + smooth_wrist = acceleration_stats(smoothed["wrist_root_translation"]) + raw_vertices = acceleration_stats(raw["vertices_camera"]) + smooth_vertices = acceleration_stats(smoothed["vertices_camera"]) + + def reduction(raw_value: float, smooth_value: float) -> float: + return float((1.0 - smooth_value / max(raw_value, 1e-12)) * 100.0) + + return { + "wrist_acceleration_raw": raw_wrist, + "wrist_acceleration_smoothed": smooth_wrist, + "wrist_acceleration_mean_reduction_percent": reduction( + raw_wrist["mean_mm_per_frame2"], smooth_wrist["mean_mm_per_frame2"] + ), + "vertex_acceleration_raw": raw_vertices, + "vertex_acceleration_smoothed": smooth_vertices, + "vertex_acceleration_mean_reduction_percent": reduction( + raw_vertices["mean_mm_per_frame2"], + smooth_vertices["mean_mm_per_frame2"], + ), + "wrist_filter_displacement": displacement_stats( + raw["wrist_root_translation"], smoothed["wrist_root_translation"] + ), + "vertex_filter_displacement": displacement_stats( + raw["vertices_camera"], smoothed["vertices_camera"] + ), + "rotation_filter_displacement": rotation_displacement_stats( + raw["mano_rotation_matrices"], smoothed["mano_rotation_matrices"] + ), + "raw_shape_temporal_std_mean": float(raw["mano_shape"].std(axis=0).mean()), + } + + +def probe_video(path: Path, expected_frames: int, frame_hw: tuple[int, int]) -> None: + command = [ + "ffprobe", + "-v", + "error", + "-select_streams", + "v:0", + "-count_frames", + "-show_entries", + "stream=codec_name,pix_fmt,width,height,nb_read_frames", + "-of", + "json", + str(path), + ] + report = json.loads(subprocess.check_output(command, text=True)) + streams = report.get("streams", []) + if len(streams) != 1: + raise RuntimeError(f"expected one video stream in {path}") + stream = streams[0] + height, width = frame_hw + observed = ( + stream.get("codec_name"), + stream.get("pix_fmt"), + int(stream.get("width", -1)), + int(stream.get("height", -1)), + int(stream.get("nb_read_frames", -1)), + ) + expected = ("h264", "yuv420p", width, height, expected_frames) + if observed != expected: + raise RuntimeError(f"video validation failed for {path}: {observed} != {expected}") + + +def render_case( + *, + case: dict[str, Any], + raw: dict[str, np.ndarray], + smoothed: dict[str, np.ndarray], + source_case_dir: Path, + output_case_dir: Path, + data_root: Path, + faces: tuple[np.ndarray, np.ndarray], + fps: float, + translation_cutoff_hz: float, + rotation_cutoff_hz: float, + filter_order: int, + crf: int, + preset: str, +) -> dict[str, Any]: + output_case_dir.mkdir(parents=True, exist_ok=True) + take_dir = data_root / str(case["take"]) + raw_K, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + height, width = source_hw + output_paths = { + "smoothed_overlay": output_case_dir / "predicted_mano_overlay_smoothed.mp4", + "smoothed_side_by_side": output_case_dir / "side_by_side_smoothed.mp4", + "raw_vs_smoothed": output_case_dir / "raw_vs_smoothed.mp4", + } + writers = [ + FFmpegVideoWriter(output_paths["smoothed_overlay"], fps, source_hw, crf=crf, preset=preset), + FFmpegVideoWriter( + output_paths["smoothed_side_by_side"], + fps, + (height, width * 2), + crf=crf, + preset=preset, + ), + FFmpegVideoWriter( + output_paths["raw_vs_smoothed"], + fps, + (height, width * 2), + crf=crf, + preset=preset, + ), + ] + raw_overlay_path = source_case_dir / "predicted_mano_overlay.mp4" + raw_capture = cv2.VideoCapture(str(raw_overlay_path)) + if not raw_capture.isOpened(): + for writer in writers: + writer.abort() + raise RuntimeError(f"failed to open source overlay: {raw_overlay_path}") + + frame_ids = [int(value) for value in case["frame_ids"]] + preview = None + comparison_preview = None + try: + for frame_index, frame_id in enumerate(frame_ids): + raw_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), + cv2.IMREAD_COLOR, + ) + if raw_bgr is None or raw_bgr.shape[:2] != source_hw: + raise RuntimeError(f"raw RGB decode/shape failure: {take_dir}/{frame_id}") + ok, source_overlay_bgr = raw_capture.read() + if not ok or source_overlay_bgr.shape[:2] != source_hw: + raise RuntimeError( + f"source overlay ended at frame {frame_index}: {raw_overlay_path}" + ) + raw_rgb = cv2.cvtColor(raw_bgr, cv2.COLOR_BGR2RGB) + layers = [ + MeshLayer( + smoothed["vertices_camera"][frame_index, hand], + faces[hand], + LEFT_COLOR_RGB if hand == 0 else RIGHT_COLOR_RGB, + MESH_ALPHA, + ) + for hand in range(2) + ] + rendered = render_mesh_layers(raw_rgb, project_mesh_layers(layers, raw_K)) + rendered = add_header(rendered, ( + f"Post-processed MANO | zero-phase low-pass | left=BLUE right=RED alpha={MESH_ALPHA:.2f}", + f"{case['subject']}/{case['sequence']} | frame={frame_id} " + f"({frame_index + 1}/{len(frame_ids)}) | translation={translation_cutoff_hz:g} Hz " + f"rotation={rotation_cutoff_hz:g} Hz order={filter_order}", + )) + original_panel = add_header(raw_rgb, ("Original cam4 RGB",)) + side_by_side = np.concatenate((original_panel, rendered), axis=1) + source_overlay_rgb = cv2.cvtColor(source_overlay_bgr, cv2.COLOR_BGR2RGB) + raw_vs_smoothed = np.concatenate((source_overlay_rgb, rendered), axis=1) + + writers[0].write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + writers[1].write(cv2.cvtColor(side_by_side, cv2.COLOR_RGB2BGR)) + writers[2].write(cv2.cvtColor(raw_vs_smoothed, cv2.COLOR_RGB2BGR)) + if frame_index == len(frame_ids) // 2: + preview = rendered.copy() + comparison_preview = raw_vs_smoothed.copy() + if (frame_index + 1) % 100 == 0 or frame_index + 1 == len(frame_ids): + print(f" render {frame_index + 1}/{len(frame_ids)} frames", flush=True) + + extra, _ = raw_capture.read() + if extra: + raise RuntimeError(f"source overlay has extra frames: {raw_overlay_path}") + for writer in writers: + writer.close() + except BaseException: + for writer in writers: + if writer.process.poll() is None or writer.temporary.exists(): + writer.abort() + raise + finally: + raw_capture.release() + + if preview is None or comparison_preview is None: + raise RuntimeError(f"no preview generated for {case['take']}") + preview_path = output_case_dir / "preview_smoothed.png" + comparison_preview_path = output_case_dir / "preview_raw_vs_smoothed.png" + cv2.imwrite(str(preview_path), cv2.cvtColor(preview, cv2.COLOR_RGB2BGR)) + cv2.imwrite( + str(comparison_preview_path), + cv2.cvtColor(comparison_preview, cv2.COLOR_RGB2BGR), + ) + probe_video(output_paths["smoothed_overlay"], len(frame_ids), source_hw) + probe_video( + output_paths["smoothed_side_by_side"], + len(frame_ids), + (height, width * 2), + ) + probe_video( + output_paths["raw_vs_smoothed"], + len(frame_ids), + (height, width * 2), + ) + metrics = jitter_metrics(raw, smoothed) + record = { + "take": case["take"], + "subject": case["subject"], + "sequence": case["sequence"], + "category": case["category"], + "rank": case["rank"], + "frame_count": len(frame_ids), + "source_case": str(source_case_dir.resolve()), + "raw_prediction_cache": str((output_case_dir / "raw_prediction.npz").resolve()), + "smoothed_prediction_cache": str( + (output_case_dir / "smoothed_prediction.npz").resolve() + ), + "videos": {key: str(path.resolve()) for key, path in output_paths.items()}, + "preview": str(preview_path.resolve()), + "raw_vs_smoothed_preview": str(comparison_preview_path.resolve()), + "jitter_metrics": metrics, + } + write_json_atomic(output_case_dir / "case_postprocess.json", record) + record["preview_rgb"] = preview + return record + + +def save_contact_sheet(path: Path, records: list[dict[str, Any]]) -> None: + if not records: + return + panels = [] + for record in records: + panel = cv2.resize(record["preview_rgb"], (384, 216), interpolation=cv2.INTER_AREA) + panel = add_header(panel, ( + f"{record['category']} #{record['rank']} | " + f"jitter -{record['jitter_metrics']['vertex_acceleration_mean_reduction_percent']:.1f}%", + )) + panels.append(panel) + while len(panels) % 5: + panels.append(np.zeros_like(panels[0])) + rows = [np.concatenate(panels[index : index + 5], axis=1) for index in range(0, len(panels), 5)] + sheet = np.concatenate(rows, axis=0) + cv2.imwrite(str(path), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR)) + + +def source_case_directory(source_dir: Path, case: dict[str, Any]) -> Path: + category_dir = "best_cases" if case["category"] == "best" else "failure_cases" + recorded = Path(case["videos"]["original"]).parent.name + path = source_dir / category_dir / recorded + if not path.is_dir(): + raise FileNotFoundError(f"source case directory missing: {path}") + return path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Re-infer missing raw MANO caches and render zero-phase jitter-smoothed demos." + ) + parser.add_argument( + "--source-dir", + type=Path, + default=Path("artifacts/phase3/video_cases_best_model_long_sequences"), + ) + parser.add_argument("--output-dir", type=Path) + parser.add_argument("--data-root", type=Path, default=Path("data/H2O/extracted")) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--category", choices=("all", "best", "failure"), default="all") + parser.add_argument("--max-cases", type=int) + parser.add_argument("--translation-cutoff-hz", type=float, default=3.0) + parser.add_argument("--rotation-cutoff-hz", type=float, default=4.0) + parser.add_argument("--filter-order", type=int, default=2) + parser.add_argument("--crf", type=int, default=18) + parser.add_argument( + "--ffmpeg-preset", + choices=("ultrafast", "superfast", "veryfast", "faster", "fast", "medium"), + default="fast", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + source_dir = args.source_dir.resolve() + if args.output_dir is None: + output_dir = source_dir.with_name(f"{source_dir.name}_smoothed") + else: + output_dir = args.output_dir.resolve() + data_root = args.data_root.resolve() + if source_dir == output_dir: + raise ValueError("source and output directories must differ") + if args.filter_order < 1: + raise ValueError("filter order must be positive") + if not 0 <= args.crf <= 51: + raise ValueError("CRF must be in [0, 51]") + if not torch.cuda.is_available(): + raise RuntimeError("CUDA is required to reconstruct missing raw prediction caches") + device = torch.device(f"cuda:{args.gpu}") + + selection_path = source_dir / "selection_manifest.json" + selection = json.loads(selection_path.read_text(encoding="utf-8")) + if selection.get("status") != "complete" or selection.get("official_test_used") is not False: + raise ValueError("source selection manifest is incomplete or uses official test data") + config_path = Path(selection["config"]) + checkpoint = selection["checkpoint"] + checkpoint_path = Path(checkpoint["path"]) + expected_checkpoint_hash = str(checkpoint["sha256"]) + observed_checkpoint_hash = sha256(checkpoint_path) + if observed_checkpoint_hash != expected_checkpoint_hash: + raise ValueError("checkpoint hash differs from the source selection manifest") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + fps = float(selection["visualization_fps"]) + lowpass(np.zeros((32, 1), dtype=np.float32), args.translation_cutoff_hz, fps, args.filter_order) + lowpass(np.zeros((32, 1), dtype=np.float32), args.rotation_cutoff_hz, fps, args.filter_order) + + cases = [ + case + for case in selection["cases"] + if args.category == "all" or case["category"] == args.category + ] + if args.max_cases is not None: + if args.max_cases < 1: + raise ValueError("max cases must be positive") + cases = cases[: args.max_cases] + if not cases: + raise ValueError(f"no cases selected for category={args.category}") + output_dir.mkdir(parents=True, exist_ok=True) + + data_config = config["data"] + render_manifest_path = source_dir / "render_input_manifest.jsonl" + model_t = int(data_config["T"]) + dataset = H2OCam4Dataset( + data_root, + render_manifest_path, + tuple(data_config["resolution_hw"]), + (model_t,), + (int(data_config["stride"]),), + ) + clip_indices_by_take: dict[str, list[int]] = defaultdict(list) + for clip_index, clip in enumerate(dataset.clips): + clip_indices_by_take[clip.take].append(clip_index) + + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + model: BimanualReconstructionModel | None = None + mano_layer: ManoCameraLayer | None = None + faces: tuple[np.ndarray, np.ndarray] | None = None + records: list[dict[str, Any]] = [] + for case_index, case in enumerate(cases, start=1): + source_case_dir = source_case_directory(source_dir, case) + category_dir = "best_cases" if case["category"] == "best" else "failure_cases" + output_case_dir = output_dir / category_dir / source_case_dir.name + output_case_dir.mkdir(parents=True, exist_ok=True) + raw_cache_path = output_case_dir / "raw_prediction.npz" + print( + f"[{case_index}/{len(cases)}] {case['category']} #{case['rank']} " + f"{case['take']} ({len(case['frame_ids'])} frames)", + flush=True, + ) + raw = load_raw_cache( + raw_cache_path, + case=case, + checkpoint_sha256=expected_checkpoint_hash, + ) + if raw is None: + if model is None: + print("loading frozen model checkpoint", flush=True) + model = build_model( + config, + checkpoint_path, + int(checkpoint["step"]), + device, + ) + mano_layer = model.mano_layer + if mano_layer is None: + raise RuntimeError("loaded model has no MANO layer") + faces = tuple(layer.th_faces.cpu().numpy() for layer in mano_layer.layers) + raw = infer_case( + case=case, + dataset=dataset, + clip_indices=clip_indices_by_take[str(case["take"])], + model=model, + device=device, + dtype=dtype, + checkpoint_sha256=expected_checkpoint_hash, + ) + save_npz_atomic(raw_cache_path, raw) + print(f" saved raw cache: {raw_cache_path}", flush=True) + else: + print(f" reusing raw cache: {raw_cache_path}", flush=True) + + if mano_layer is None: + mano_layer = ManoCameraLayer(config["assets"]["mano_root"]).to(device).eval() + if faces is None: + faces = tuple(layer.th_faces.cpu().numpy() for layer in mano_layer.layers) + smoothed = smooth_prediction( + raw, + translation_cutoff_hz=args.translation_cutoff_hz, + rotation_cutoff_hz=args.rotation_cutoff_hz, + fps=fps, + order=args.filter_order, + ) + rebuild_mano_geometry(smoothed, mano_layer, device) + save_npz_atomic(output_case_dir / "smoothed_prediction.npz", smoothed) + record = render_case( + case=case, + raw=raw, + smoothed=smoothed, + source_case_dir=source_case_dir, + output_case_dir=output_case_dir, + data_root=data_root, + faces=faces, + fps=fps, + translation_cutoff_hz=args.translation_cutoff_hz, + rotation_cutoff_hz=args.rotation_cutoff_hz, + filter_order=args.filter_order, + crf=args.crf, + preset=args.ffmpeg_preset, + ) + records.append(record) + print( + " mean vertex acceleration reduction: " + f"{record['jitter_metrics']['vertex_acceleration_mean_reduction_percent']:.1f}%", + flush=True, + ) + + save_contact_sheet(output_dir / "contact_sheet_smoothed.png", records) + serializable_records = [ + {key: value for key, value in record.items() if key != "preview_rgb"} + for record in records + ] + summary = { + "status": "complete", + "purpose": "offline visualization-only jitter postprocessing", + "source_dir": str(source_dir), + "source_selection_manifest": str(selection_path), + "checkpoint": checkpoint, + "model_inference_policy": ( + f"same frozen checkpoint and non-overlapping T={model_t} chunks as source render" + ), + "raw_cache_policy": ( + "render-relevant raw outputs are cached before filtering and reused on later runs" + ), + "postprocessing": { + "translation": "zero-phase Butterworth low-pass in camera XYZ", + "translation_cutoff_hz": args.translation_cutoff_hz, + "rotation": "zero-phase Butterworth low-pass on sign-continuous unit quaternions", + "rotation_cutoff_hz": args.rotation_cutoff_hz, + "filter_order": args.filter_order, + "shape": "per-take temporal median, held constant", + "fps": fps, + "phase_lag_frames": 0, + }, + "video_encoding": { + "codec": "H.264", + "pixel_format": "yuv420p", + "crf": args.crf, + "preset": args.ffmpeg_preset, + }, + "metrics_are_official_evaluation": False, + "cases": serializable_records, + } + write_json_atomic(output_dir / "postprocess_manifest.json", summary) + mean_reductions = [ + record["jitter_metrics"]["vertex_acceleration_mean_reduction_percent"] + for record in records + ] + readme = f"""# Jitter-Smoothed Long-Sequence Video Cases + +This directory is a visualization-only postprocessing of `{source_dir}`. The +model, checkpoint, official evaluation, and source artifacts are unchanged. + +Missing predictions were reconstructed with the same frozen checkpoint and +non-overlapping T={model_t} inference policy as the source demo. Each case keeps +`raw_prediction.npz` before filtering, so filter parameters can be adjusted and +videos regenerated without running the reconstruction model again. + +The offline filter is a zero-phase order-{args.filter_order} Butterworth low-pass: + +- wrist translation cutoff: {args.translation_cutoff_hz:g} Hz; +- MANO rotation cutoff: {args.rotation_cutoff_hz:g} Hz; +- MANO shape: temporal median held fixed within each take. + +Zero-phase filtering introduces no visual time shift but uses future frames, so +these videos do not represent a causal real-time system. H.264/yuv420p output is +used for macOS playback. `raw_vs_smoothed.mp4` is the clearest A/B view. + +Across the {len(records)} rendered cases, mean per-case vertex-acceleration +reduction is {float(np.mean(mean_reductions)):.1f}%. See +`postprocess_manifest.json` and each `case_postprocess.json` for details. +""" + (output_dir / "README.md").write_text(readme, encoding="utf-8") + print(json.dumps({ + "status": "complete", + "output_dir": str(output_dir), + "case_count": len(records), + "mean_vertex_acceleration_reduction_percent": float(np.mean(mean_reductions)), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/prepare_phase9_storage_overflow.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/prepare_phase9_storage_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..8e5f5a81b71ffeca38c3c4a0820da0a212058a66 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/prepare_phase9_storage_overflow.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Bind unopened Phase 9 fold outputs to a larger physical volume.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def bind_directory(logical: Path, physical: Path) -> str: + if logical.is_symlink(): + if logical.resolve() != physical.resolve(): + raise RuntimeError(f"existing symlink has wrong target: {logical}") + return "existing_identical" + if logical.exists(): + raise RuntimeError(f"logical output already exists: {logical}") + physical.mkdir(parents=True, exist_ok=True) + logical.parent.mkdir(parents=True, exist_ok=True) + os.symlink(physical, logical, target_is_directory=True) + if not logical.is_symlink() or logical.resolve() != physical.resolve(): + raise RuntimeError(f"failed to bind output: {logical}") + return "created" + + +def prepare(plan: dict[str, Any], plan_path: Path) -> dict[str, Any]: + if plan.get("official_test_used") is not False: + raise ValueError("plan must explicitly exclude official test") + registry_path = Path(plan["fold_training_registry"]) + if sha256(registry_path) != plan["fold_training_registry_sha256"]: + raise ValueError("fold registry hash mismatch") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + raise ValueError("fold registry must explicitly exclude official test") + conditions = {row["condition"]: row for row in registry["conditions"]} + logical_roots = { + key: Path(value) for key, value in plan["logical_evaluation_roots"].items() + } + physical_root = Path(plan["physical_root"]) + rows = [] + for condition_id in plan["conditions"]: + if condition_id not in conditions: + raise ValueError(f"condition is absent from registry: {condition_id}") + condition = conditions[condition_id] + bindings = { + "run": ( + Path(condition["output_dir"]), + physical_root / "runs" / "h2o_multifold" / condition_id.lower(), + ), + "final_evaluation": ( + logical_roots["final"] / condition_id, + physical_root / "evaluations" / "h2o_multifold" / condition_id, + ), + "milestone_evaluation": ( + logical_roots["milestone"] / condition_id, + physical_root / "evaluations" / "h2o_multifold_milestones" / condition_id, + ), + } + for kind, (logical, physical) in bindings.items(): + status = bind_directory(logical, physical) + rows.append({ + "condition": condition_id, "kind": kind, "status": status, + "logical": str(logical), "physical": str(physical), + }) + return { + "schema_version": "phase9_storage_overflow_report_v1", + "status": "complete", + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "bindings": rows, + "scientific_protocol_changed": False, + "official_test_used": False, + "completed_utc": utc_now(), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("output report already exists") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + report = prepare(plan, args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_suffix(".tmp") + temporary.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.output) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/probe_memory.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/probe_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..c37fb1447ab5553ded97429d5473f5c2582a7123 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/probe_memory.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""4090 memory matrix using official random DINOv3 architecture (never training).""" + +from __future__ import annotations + +import argparse +import csv +import json +import platform +import time +from pathlib import Path + +import torch +from torch import nn + +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.models.encoders import PatchFeatures + + +class ProbeDinoEncoder(nn.Module): + def __init__(self, backbone: nn.Module, output_dim: int = 512) -> None: + super().__init__() + self.backbone = backbone.requires_grad_(False).eval() + self.projection = nn.Linear(768, output_dim) + self.patch_size = 16 + + def train(self, mode: bool = True): + super().train(mode) + self.backbone.eval() + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + with torch.no_grad(): + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + return PatchFeatures(self.projection(raw), (images.shape[-2] // 16, images.shape[-1] // 16), 16) + + +def make_batch(batch_size: int, time_steps: int, height: int, width: int, device: torch.device) -> dict[str, torch.Tensor]: + K = torch.tensor([[width * 0.5, 0, width * 0.5], [0, width * 0.5, height * 0.5], [0, 0, 1]], device=device, dtype=torch.float32) + return { + "rgb": torch.randn(batch_size, time_steps, 3, height, width, device=device), + "depth_m": torch.rand(batch_size, time_steps, 1, height, width, device=device) + 0.3, + "depth_pixel_valid": torch.ones(batch_size, time_steps, 1, height, width, device=device, dtype=torch.bool), + "K": K[None, None].expand(batch_size, time_steps, -1, -1).clone(), + "K_available": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + "depth_available": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + "frame_valid": torch.ones(batch_size, time_steps, device=device, dtype=torch.bool), + } + + +def run_case(backbone: nn.Module, case: dict[str, object], device: torch.device) -> dict[str, object]: + height, width = case["height"], case["width"] + dtype = torch.bfloat16 if case["precision"] == "bf16" else torch.float16 + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats(device) + config = ModelConfig( + encoder="tiny_debug", decoder_dim=512, decoder_layers=int(case["decoder_layers"]), attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, depth_mode="log_depth", use_rays=True, + use_bimanual_interaction=True, gradient_checkpointing=bool(case["gradient_checkpointing"]), + ) + model = BimanualReconstructionModel(config) + model.rgb_encoder = ProbeDinoEncoder(backbone, 512) + model.to(device).train() + batch = make_batch(int(case["batch_size"]), int(case["T"]), int(height), int(width), device) + start = time.perf_counter() + try: + with torch.autocast("cuda", dtype=dtype): + output = model(batch) + loss = ( + output["joint2d_norm"].square().mean() + + output["mano_rotations_6d"].square().mean() + + output["wrist_root_translation"].square().mean() + + output["mano_shape_sequence"].square().mean() + ) + forward_end = time.perf_counter() + loss.backward() + torch.cuda.synchronize(device) + end = time.perf_counter() + case.update({ + "status": "ok", "forward_s": forward_end - start, "forward_backward_s": end - start, + "frames_per_s": int(case["batch_size"]) * int(case["T"]) / (end - start), + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30, + "loss_finite": bool(torch.isfinite(loss)), + }) + except torch.cuda.OutOfMemoryError as error: + case.update({"status": "oom", "error": str(error).splitlines()[0], "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30}) + finally: + del model, batch + torch.cuda.empty_cache() + return case + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--quick", action="store_true", help="Probe the core matrix; omit extra checkpoint/layer variants") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + torch.cuda.set_device(args.gpu) + device = torch.device("cuda") + from dinov3.hub.backbones import dinov3_vitb16 + torch.manual_seed(20260716) + backbone = dinov3_vitb16(pretrained=False).to(device) + cases = [] + for width, height in ((384, 224), (512, 288), (640, 368)): + for T in (1, 4, 8, 16): + for batch_size in (1, 2): + for precision in ("bf16", "fp16"): + cases.append({"width": width, "height": height, "T": T, "batch_size": batch_size, "precision": precision, "decoder_layers": 3, "gradient_checkpointing": False}) + if not args.quick: + for layers in (2, 3): + for checkpointing in (False, True): + for batch_size in (1, 2): + cases.append({"width": 512, "height": 288, "T": 8, "batch_size": batch_size, "precision": "bf16", "decoder_layers": layers, "gradient_checkpointing": checkpointing}) + + results = [] + for index, case in enumerate(cases): + case.update({"case": index, "gpu": torch.cuda.get_device_name(device), "random_architecture_only": True, "dinov3": "official dinov3_vitb16 pretrained=False", "seed": 20260716}) + result = run_case(backbone, case, device) + results.append(result) + print(json.dumps(result), flush=True) + fields = sorted({key for result in results for key in result}) + with (args.output_dir / "memory_probe.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields) + writer.writeheader(); writer.writerows(results) + summary = { + "warning": "Architecture-only memory probe with official randomly initialized DINOv3 ViT-B/16. Not a training/quality result.", + "torch": torch.__version__, "python": platform.python_version(), "gpu": torch.cuda.get_device_name(device), + "case_count": len(results), "ok": sum(row["status"] == "ok" for row in results), "oom": sum(row["status"] == "oom" for row in results), + "results_csv": str((args.output_dir / "memory_probe.csv").resolve()), + } + (args.output_dir / "memory_probe_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/profile_phase5_alignment_solver.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/profile_phase5_alignment_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..842eb2831c09853c1731c7bd7a4e3d1276cad639 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/profile_phase5_alignment_solver.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Profile the deployable per-frame predicted-MANO/depth alignment solver.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import resource +import time +from pathlib import Path + +import cv2 +import numpy as np + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def latency_summary(values_ms: list[float]) -> dict[str, float | int]: + values = np.asarray(values_ms, dtype=np.float64) + if not values.size or not np.isfinite(values).all(): + raise ValueError("latency samples must be non-empty and finite") + return { + "frames": int(len(values)), + "mean_ms": float(values.mean()), + "std_ms": float(values.std()), + "p50_ms": float(np.percentile(values, 50)), + "p90_ms": float(np.percentile(values, 90)), + "p95_ms": float(np.percentile(values, 95)), + "minimum_ms": float(values.min()), + "maximum_ms": float(values.max()), + "throughput_frames_per_second": float(1000.0 / values.mean()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--frames", type=int, default=128) + parser.add_argument("--warmup", type=int, default=8) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite profile: {args.output}") + if args.frames < 1 or args.warmup < 0: + parser.error("frames must be positive and warmup non-negative") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("scope") != "full" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_test_used") is not False + ): + raise ValueError("profile requires a complete official-validation raw cache") + take_record = manifest["takes"][0] + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError("profile take cache hash mismatch") + with np.load(take_path, allow_pickle=False) as archive: + frame_ids = archive["frame_id"][:args.frames].astype(np.int64) + vertices = archive["pred_vertices_camera"][:args.frames].astype(np.float32) + take = str(archive["take"]) + take_dir = args.data_root / take + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + + depths = [] + for frame_id in frame_ids: + depth_mm = cv2.imread( + str(take_dir / "depth" / f"{int(frame_id):06d}.png"), cv2.IMREAD_UNCHANGED, + ) + if depth_mm is None or depth_mm.shape != raw_hw: + raise RuntimeError(f"missing or misaligned raw depth: {take}/{int(frame_id):06d}") + depths.append(depth_mm_to_m(depth_mm)) + cv2.setNumThreads(1) + for index in range(min(args.warmup, len(frame_ids))): + for hand in range(2): + align_wrist_z(vertices[index, hand], K_raw, *depths[index]) + + elapsed_ms = [] + applied = [] + support = [] + for index in range(len(frame_ids)): + started = time.perf_counter_ns() + for hand in range(2): + diagnostics, _ = align_wrist_z( + vertices[index, hand], K_raw, *depths[index], + ) + applied.append(diagnostics.applied) + support.append(diagnostics.valid_support_count) + elapsed_ms.append((time.perf_counter_ns() - started) / 1_000_000.0) + + report = { + "status": "profiled", + "experiment_class": "engineering_profile_not_model_selection", + "official_validation_used": True, + "official_validation_used_for_model_or_threshold_selection": False, + "official_test_used": False, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], + "take": take, + "frame_range": [int(frame_ids[0]), int(frame_ids[-1])], + "latency": { + **latency_summary(elapsed_ms), + "scope": "CPU per-frame two-hand projection/depth sampling/IRLS; raw depth predecoded; excludes coarse model and file I/O", + }, + "applied_hand_fraction": float(np.mean(applied)), + "support_count_mean": float(np.mean(support)), + "peak_process_rss_mib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0, + "cpu": platform.processor(), + "opencv_threads": cv2.getNumThreads(), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/profile_phase5_model.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/profile_phase5_model.py new file mode 100644 index 0000000000000000000000000000000000000000..08e09f54b448c025820f47f08d473f2dfbf8948b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/profile_phase5_model.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Profile a frozen candidate on one official-train clip without model selection.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader +from torch.utils.flop_counter import FlopCounterMode + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def move_to_device(batch: dict[str, object], device: torch.device) -> dict[str, object]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def parameter_counts(model: torch.nn.Module) -> dict[str, int]: + trainable = sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad) + frozen = sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad) + return {"trainable": trainable, "frozen": frozen, "total": trainable + frozen} + + +def percentile_summary(values: list[float]) -> dict[str, float | int]: + array = np.asarray(values, dtype=np.float64) + if not array.size or not np.isfinite(array).all(): + raise ValueError("latency measurements must be non-empty and finite") + return { + "iterations": int(len(array)), + "mean_ms": float(array.mean()), + "std_ms": float(array.std()), + "p50_ms": float(np.percentile(array, 50)), + "p90_ms": float(np.percentile(array, 90)), + "p95_ms": float(np.percentile(array, 95)), + "minimum_ms": float(array.min()), + "maximum_ms": float(array.max()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--warmup", type=int, default=20) + parser.add_argument("--iterations", type=int, default=100) + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(f"refusing to overwrite profile: {args.output}") + if args.warmup < 1 or args.iterations < 1: + parser.error("warmup and iterations must be positive") + if "test" in args.manifest.name.lower() or "val" in args.manifest.name.lower(): + parser.error("profiling is restricted to official-train data") + checkpoint_hash = sha256(args.checkpoint) + if checkpoint_hash != args.expected_checkpoint_sha256: + parser.error("checkpoint hash mismatch") + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data = config["data"] + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data["resolution_hw"]), + (int(data["T"]),), + (int(data["stride"]),), + max_clips=1, + ) + loader = DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + device = torch.device(f"cuda:{args.gpu}") + batch = move_to_device(next(iter(loader)), device) + assets = config["assets"] + model = BimanualReconstructionModel(ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + )).to(device).eval() + checkpoint = load_checkpoint(args.checkpoint, model, optimizer=None, map_location=device) + if checkpoint.get("extra", {}).get("config") != config: + raise ValueError("profiling config differs from checkpoint embedded config") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + for _ in range(args.warmup): + model(batch) + torch.cuda.synchronize(device) + torch.cuda.reset_peak_memory_stats(device) + starts = [torch.cuda.Event(enable_timing=True) for _ in range(args.iterations)] + ends = [torch.cuda.Event(enable_timing=True) for _ in range(args.iterations)] + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + for start, end in zip(starts, ends, strict=True): + start.record() + model(batch) + end.record() + torch.cuda.synchronize(device) + latency = percentile_summary([start.elapsed_time(end) for start, end in zip(starts, ends, strict=True)]) + peak_vram_gib = torch.cuda.max_memory_allocated(device) / 2**30 + + flop_counter = FlopCounterMode(display=False) + # FlopCounterMode's module tracker requires an autograd graph in PyTorch 2.6. + # This single pass is excluded from the inference latency measurements above. + with torch.autocast("cuda", dtype=dtype), flop_counter: + model(batch) + supported_flops = int(flop_counter.get_total_flops()) + report = { + "status": "profiled", + "experiment_class": "engineering_profile_not_model_selection", + "official_validation_used": False, + "official_test_used": False, + "git_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], check=True, text=True, stdout=subprocess.PIPE, + ).stdout.strip(), + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": checkpoint_hash, + "step": int(checkpoint["step"]), + }, + "manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "input": { + "batch_size": 1, + "clip_length": int(data["T"]), + "resolution_hw": list(data["resolution_hw"]), + "modalities": ["RGB", "Depth", "K"], + "precision": config["precision"], + }, + "parameters": parameter_counts(model), + "supported_operator_flops_per_clip": supported_flops, + "flops_scope": "PyTorch FlopCounterMode supported operators; forward only; unsupported custom operators are not estimated", + "latency": {**latency, "scope": "GPU model forward only; excludes data loading and host preprocessing"}, + "peak_allocated_vram_gib": peak_vram_gib, + "gpu": torch.cuda.get_device_name(device), + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/rank_phase7_external.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/rank_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..0a13c2df62d7118453c90ff38151bfa4acf049f4 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/rank_phase7_external.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Rank Phase 7 external checkpoints without frame-count weighting or H2O.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_p95_mm", +) + + +def dense_ranks(values: dict[str, float]) -> dict[str, int]: + ordered = sorted(set(values.values())) + return {name: ordered.index(value) + 1 for name, value in values.items()} + + +def evaluation_metrics(report: dict[str, Any]) -> dict[str, float]: + metrics = report["metrics"] + values = { + "absolute_mpjpe_mm": metrics["absolute_mpjpe_mm"]["mean"], + "root_relative_mpjpe_mm": metrics["root_relative_mpjpe_mm"]["mean"], + "fingertip_mpjpe_mm": metrics["fingertip_mpjpe_mm"]["mean"], + "translation_z_p95_mm": metrics["translation_z_mae_mm"]["p95"], + } + if any(value is None or not math.isfinite(float(value)) for value in values.values()): + raise ValueError("selection metrics must all be finite") + return {key: float(value) for key, value in values.items()} + + +def load_entries(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if manifest.get("selection_split") != "external_heldout_only": + raise ValueError("selection manifest must be external_heldout_only") + expected = set(manifest["datasets"]) + if expected != {"HOT3D", "HOI4D", "ARCTIC"}: + raise ValueError("selection requires exactly HOT3D, HOI4D and ARCTIC") + entries: list[dict[str, Any]] = [] + pairs: set[tuple[str, str]] = set() + steps: set[int] = set() + for item in manifest["evaluations"]: + condition = str(item["condition"]) + dataset = str(item["dataset"]) + pair = (condition, dataset) + if pair in pairs: + raise ValueError(f"duplicate condition/dataset pair: {pair}") + pairs.add(pair) + if dataset not in expected: + raise ValueError(f"unexpected dataset: {dataset}") + path = Path(item["path"]).resolve() + report = json.loads(path.read_text(encoding="utf-8")) + cache_path = str(report["cache_manifest"]["path"]).lower() + if "h2o" in cache_path or report.get("h2o_training_data_used") is not False: + raise ValueError("external ranking refuses H2O data or training exposure") + if report.get("official_test_used") is not False: + raise ValueError("external ranking refuses official-test evaluation") + step = int(report["checkpoint_step"]) + steps.add(step) + entries.append({ + "condition": condition, + "dataset": dataset, + "input_mode": report["input_mode"], + "checkpoint_step": step, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "evaluation_path": str(path), + **evaluation_metrics(report), + }) + conditions = {entry["condition"] for entry in entries} + missing = {(condition, dataset) for condition in conditions for dataset in expected} - pairs + if missing: + raise ValueError(f"incomplete condition/dataset grid: {sorted(missing)}") + if len(steps) != 1: + raise ValueError(f"checkpoint steps are not matched: {sorted(steps)}") + return entries + + +def pareto_frontier(vectors: dict[str, list[float]]) -> list[str]: + frontier = [] + for condition, vector in vectors.items(): + dominated = any( + other != condition + and all(left <= right for left, right in zip(other_vector, vector)) + and any(left < right for left, right in zip(other_vector, vector)) + for other, other_vector in vectors.items() + ) + if not dominated: + frontier.append(condition) + return sorted(frontier) + + +def rank_entries(entries: list[dict[str, Any]]) -> dict[str, Any]: + steps = {int(entry["checkpoint_step"]) for entry in entries} + if len(steps) != 1: + raise ValueError(f"checkpoint steps are not matched: {sorted(steps)}") + datasets = sorted({entry["dataset"] for entry in entries}) + conditions = sorted({entry["condition"] for entry in entries}) + lookup = {(entry["condition"], entry["dataset"]): entry for entry in entries} + dataset_ranks: dict[str, dict[str, float]] = {} + vectors = {condition: [] for condition in conditions} + for dataset in datasets: + metric_ranks = { + metric: dense_ranks({ + condition: lookup[(condition, dataset)][metric] + for condition in conditions + }) + for metric in METRICS + } + dataset_ranks[dataset] = {} + for condition in conditions: + score = sum(metric_ranks[metric][condition] for metric in METRICS) / len(METRICS) + dataset_ranks[dataset][condition] = score + vectors[condition].extend( + lookup[(condition, dataset)][metric] for metric in METRICS + ) + macro = { + condition: sum(dataset_ranks[dataset][condition] for dataset in datasets) / len(datasets) + for condition in conditions + } + order = sorted(conditions, key=lambda condition: ( + macro[condition], + sum(lookup[(condition, dataset)]["absolute_mpjpe_mm"] for dataset in datasets), + sum(lookup[(condition, dataset)]["root_relative_mpjpe_mm"] for dataset in datasets), + condition, + )) + return { + "matched_checkpoint_step": entries[0]["checkpoint_step"], + "dataset_ranks": dataset_ranks, + "macro_mean_rank": macro, + "pareto_frontier": pareto_frontier(vectors), + "order": order, + "winner": order[0], + "entries": entries, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + result = { + "status": "ranked_external_only", + "selection_rule": "dataset metric ranks -> macro mean rank -> Absolute/root-relative tie-break", + "frame_count_weighted": False, + "h2o_used": False, + "official_test_used": False, + **rank_entries(load_entries(manifest)), + } + args.output_dir.mkdir(parents=True, exist_ok=False) + (args.output_dir / "ranking.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + with (args.output_dir / "ranking.csv").open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter( + handle, + fieldnames=( + "condition", "macro_mean_rank", "on_pareto_frontier", + ), + lineterminator="\n", + ) + writer.writeheader() + for condition in result["order"]: + writer.writerow({ + "condition": condition, + "macro_mean_rank": result["macro_mean_rank"][condition], + "on_pareto_frontier": condition in result["pareto_frontier"], + }) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/recover_phase9_arctic_resolution_cache.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/recover_phase9_arctic_resolution_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..d4f62598bfecb94ccf2457dade735b0bca9d13fc --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/recover_phase9_arctic_resolution_cache.py @@ -0,0 +1,561 @@ +#!/usr/bin/env python3 +"""Restore the Stage 7 ARCTIC cache to the frozen 640 source-index set.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +from typing import Any + +import cv2 +import numpy as np + +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + cache_step_complete, + sha256, + validate_plan_bindings, +) + + +IDENTITY_FIELDS = ( + "dataset_id", + "subject_id", + "physical_recording_id", + "source_group_key", + "camera_id", + "stream_id", + "headset_id", +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def load_jsonl(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def indexed_rows( + rows: list[dict[str, Any]], label: str, +) -> tuple[list[int], dict[int, dict[str, Any]]]: + order = [int(row["source_clip_index"]) for row in rows] + if len(order) != len(set(order)): + duplicates = sorted({value for value in order if order.count(value) > 1}) + raise ValueError(f"{label} has duplicate source clip indices: {duplicates}") + return order, dict(zip(order, rows, strict=True)) + + +def compare_source_sets( + control_rows: list[dict[str, Any]], candidate_rows: list[dict[str, Any]], +) -> dict[str, Any]: + control_order, control = indexed_rows(control_rows, "control manifest") + candidate_order, candidate = indexed_rows(candidate_rows, "candidate manifest") + control_set, candidate_set = set(control), set(candidate) + missing = sorted(control_set - candidate_set) + extra = sorted(candidate_set - control_set) + drift = [] + for source_index in control_order: + if source_index not in candidate: + continue + differing = { + field: { + "control": control[source_index].get(field), + "candidate": candidate[source_index].get(field), + } + for field in IDENTITY_FIELDS + if control[source_index].get(field) != candidate[source_index].get(field) + } + if differing: + drift.append({"source_clip_index": source_index, "fields": differing}) + control_groups = {row["source_group_key"] for row in control_rows} + candidate_groups = { + candidate[index]["source_group_key"] + for index in control_order if index in candidate + } + return { + "control_count": len(control_order), + "candidate_count": len(candidate_order), + "control_unique_count": len(control_set), + "candidate_unique_count": len(candidate_set), + "missing_source_clip_indices": missing, + "extra_source_clip_indices": extra, + "identity_drift": drift, + "control_group_count": len(control_groups), + "candidate_accepted_group_count": len(candidate_groups), + "missing_groups": sorted(control_groups - candidate_groups), + "extra_groups": sorted(candidate_groups - control_groups), + } + + +def canonical_rows( + control_rows: list[dict[str, Any]], candidate_rows: list[dict[str, Any]], +) -> list[dict[str, Any]]: + comparison = compare_source_sets(control_rows, candidate_rows) + if ( + comparison["missing_source_clip_indices"] + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC source-index or group contract differs") + control_order, _ = indexed_rows(control_rows, "control manifest") + _, candidate = indexed_rows(candidate_rows, "candidate manifest") + return [candidate[index] for index in control_order] + + +def write_jsonl_atomic(path: Path, rows: list[dict[str, Any]]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), + encoding="utf-8", + ) + temporary.replace(path) + + +def preserve_file(source: Path, destination: Path) -> dict[str, Any]: + destination.parent.mkdir(parents=True, exist_ok=True) + source_hash = sha256(source) + if destination.exists(): + if not destination.is_file() or sha256(destination) != source_hash: + raise ValueError(f"preserved recovery evidence differs: {destination}") + else: + shutil.copy2(source, destination) + os.chmod(destination, 0o444) + return { + "path": str(destination.resolve()), + "sha256": source_hash, + "bytes": source.stat().st_size, + } + + +def quarantine_payload( + row: dict[str, Any], quarantine_root: Path, pass_id: str, +) -> dict[str, Any]: + source = Path(row["cache_path"]) + expected_hash = row["cache_sha256"] + if not source.is_file() or sha256(source) != expected_hash: + raise ValueError(f"extra ARCTIC payload differs: {source}") + destination = quarantine_root / pass_id / source.name + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + if not destination.is_file() or sha256(destination) != expected_hash: + raise ValueError(f"ARCTIC quarantine collision differs: {destination}") + source.unlink() + else: + source.replace(destination) + os.chmod(destination, 0o444) + return { + "source_clip_index": int(row["source_clip_index"]), + "path": str(destination.resolve()), + "sha256": expected_hash, + "bytes": destination.stat().st_size, + } + + +def payload_audit(rows: list[dict[str, Any]]) -> dict[str, Any]: + totals = { + "bytes": 0, + "clips_with_translation_supervision": 0, + "translation_valid_elements": 0, + "joint3d_valid_elements": 0, + "mano_annotation_valid_elements": 0, + } + probes: dict[int, dict[str, Any]] = {} + probe_positions = {0, len(rows) // 2, len(rows) - 1} + for position, row in enumerate(rows): + path = Path(row["cache_path"]) + if not path.is_file() or sha256(path) != row["cache_sha256"]: + raise ValueError(f"canonical ARCTIC payload differs: {path}") + with np.load(path, allow_pickle=False) as archive: + image_hw = [int(value) for value in archive["image_hw"].reshape(-1)] + if image_hw != [512, 896]: + raise ValueError(f"canonical ARCTIC resolution differs: {path}") + translation = np.asarray(archive["translation_valid"], dtype=bool) + joint3d = np.asarray(archive["joint3d_valid"], dtype=bool) + mano = np.asarray(archive["mano_annotation_valid"], dtype=bool) + if not translation.any(): + raise ValueError(f"canonical ARCTIC clip lacks supervision: {path}") + totals["bytes"] += path.stat().st_size + totals["clips_with_translation_supervision"] += 1 + totals["translation_valid_elements"] += int(translation.sum()) + totals["joint3d_valid_elements"] += int(joint3d.sum()) + totals["mano_annotation_valid_elements"] += int(mano.sum()) + if position in probe_positions: + probes[position] = { + "position": position, + "source_clip_index": int(row["source_clip_index"]), + "path": str(path.resolve()), + "sha256": row["cache_sha256"], + "image_hw": image_hw, + "frame_ids": archive["frame_id"].astype(int).tolist(), + "translation_valid_elements": int(translation.sum()), + "joint3d_valid_elements": int(joint3d.sum()), + } + return {**totals, "probes": [probes[key] for key in sorted(probes)]} + + +def source_extra_audit( + *, source_manifest: Path, control_report: dict[str, Any], + candidate_report: dict[str, Any], candidate_by_index: dict[int, dict[str, Any]], + extra_indices: list[int], mano_root: Path, +) -> list[dict[str, Any]]: + source_rows = [ + json.loads(line) + for line in source_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + control_skipped = {int(value) for value in control_report["skipped_no_supervision"]} + candidate_skipped = { + int(value) for value in candidate_report["skipped_no_supervision"] + } + low_dataset = ARCTICClipDataset( + source_manifest, mano_root, target_hw=(368, 640), + ) + high_dataset = ARCTICClipDataset( + source_manifest, mano_root, target_hw=(512, 896), + ) + results = [] + for source_index in extra_indices: + source = source_rows[source_index] + candidate = candidate_by_index[source_index] + images = [] + for value in source["image_paths"]: + path = Path(value) + image = cv2.imread(str(path), cv2.IMREAD_COLOR) + images.append({ + "path": str(path.resolve()), + "exists": path.is_file(), + "bytes": path.stat().st_size if path.is_file() else None, + "decoded_hw": list(image.shape[:2]) if image is not None else None, + }) + if any(not item["exists"] or item["decoded_hw"] != [600, 840] for item in images): + raise ValueError(f"ARCTIC extra source image differs: {source_index}") + mano_path, camera_path = Path(source["mano_path"]), Path(source["camera_path"]) + if not mano_path.is_file() or not camera_path.is_file(): + raise ValueError(f"ARCTIC extra annotation is missing: {source_index}") + mano_value = np.load(mano_path, allow_pickle=True).item() + camera_value = np.load(camera_path, allow_pickle=True).item() + if not {"left", "right"}.issubset(mano_value) or not { + "R_k_cam_np", "T_k_cam_np", "intrinsics", "dist8", + }.issubset(camera_value): + raise ValueError(f"ARCTIC extra annotation contract differs: {source_index}") + low = low_dataset[(source_index, 0)] + high = high_dataset[(source_index, 0)] + low_count = int(low["translation_valid"].sum()) + high_count = int(high["translation_valid"].sum()) + if ( + source_index not in control_skipped + or source_index in candidate_skipped + or low_count != 0 + or high_count <= 0 + or source["group_key"] != candidate["source_group_key"] + or source["physical_recording_id"] != candidate["physical_recording_id"] + ): + raise ValueError(f"ARCTIC extra acceptance reason differs: {source_index}") + results.append({ + "source_clip_index": source_index, + "classification": "resolution_dependent_supervision_boundary", + "control_640_reason": "skipped_no_supervision", + "control_640_translation_valid_elements": low_count, + "candidate_896_translation_valid_elements": high_count, + "subject_id": source["subject_id"], + "physical_recording_id": source["physical_recording_id"], + "source_group_key": source["group_key"], + "frame_ids_1based": source["frame_ids_1based"], + "images": images, + "mano_annotation": { + "path": str(mano_path.resolve()), "bytes": mano_path.stat().st_size, + "sides": sorted(mano_value), + }, + "camera_annotation": { + "path": str(camera_path.resolve()), "bytes": camera_path.stat().st_size, + "required_fields_present": True, + }, + }) + return results + + +def validate_recovery_plan(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + if ( + plan.get("status") != "frozen" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("ARCTIC recovery plan isolation differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"ARCTIC recovery binding differs: {path}") + execution_path = Path(plan["execution_plan"]["path"]) + execution = json.loads(execution_path.read_text(encoding="utf-8")) + if sha256(execution_path) != plan["execution_plan"]["sha256"]: + raise ValueError("ARCTIC execution plan binding differs") + validate_plan_bindings(execution) + return execution + + +def canonicalize_pass( + *, plan_path: Path, plan: dict[str, Any], pass_id: str, +) -> dict[str, Any]: + manifest_path = Path(plan["candidate_manifest"]) + report_path = Path(plan["candidate_report"]) + control_manifest_path = Path(plan["control_manifest"]["path"]) + control_report_path = Path(plan["control_report"]["path"]) + evidence_root = Path(plan["evidence_root"]) / pass_id + raw_manifest = preserve_file(manifest_path, evidence_root / "raw_cache_manifest.jsonl") + raw_report = preserve_file(report_path, evidence_root / "raw_cache_report.json") + control_rows = load_jsonl(control_manifest_path) + candidate_rows = load_jsonl(manifest_path) + control_report = json.loads(control_report_path.read_text(encoding="utf-8")) + candidate_report = json.loads(report_path.read_text(encoding="utf-8")) + comparison = compare_source_sets(control_rows, candidate_rows) + expected_extra = plan["expected_extra_source_clip_indices"] + if ( + comparison["control_count"] != plan["expected_clips"] + or comparison["candidate_count"] != plan["raw_candidate_clips"] + or comparison["missing_source_clip_indices"] + or comparison["extra_source_clip_indices"] != expected_extra + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC cache mismatch is outside the frozen recovery scope") + _, candidate_by_index = indexed_rows(candidate_rows, "candidate manifest") + extras = source_extra_audit( + source_manifest=Path(plan["source_manifest"]["path"]), + control_report=control_report, + candidate_report=candidate_report, + candidate_by_index=candidate_by_index, + extra_indices=expected_extra, + mano_root=Path(plan["mano_root"]), + ) + quarantined = [ + quarantine_payload(candidate_by_index[index], Path(plan["quarantine_root"]), pass_id) + for index in expected_extra + ] + accepted = canonical_rows(control_rows, candidate_rows) + coverage = payload_audit(accepted) + if coverage["clips_with_translation_supervision"] != plan["expected_clips"]: + raise ValueError("ARCTIC canonical supervision coverage differs") + write_jsonl_atomic(manifest_path, accepted) + manifest_hash = sha256(manifest_path) + canonical_report = dict(candidate_report) + canonical_report.update({ + "status": "complete", + "cached_clips": plan["expected_clips"], + "cached_valid_clips": plan["expected_clips"], + "valid_candidate_files": plan["expected_clips"], + "recordings": comparison["control_group_count"], + "bytes": coverage["bytes"], + "cache_manifest": { + "path": str(manifest_path.resolve()), "sha256": manifest_hash, + }, + "canonical_filter": { + "schema_version": "phase9_arctic_resolution_canonical_filter_v1", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "control_manifest": plan["control_manifest"], + "raw_manifest": raw_manifest, + "raw_report": raw_report, + "excluded_resolution_dependent_source_indices": expected_extra, + "quarantined_payloads": quarantined, + "ordering": "frozen_640_control_source_index_order", + "logical_clip_set_changed_from_control": False, + }, + "supervision_coverage": coverage, + "h2o_official_validation_used": False, + "official_test_used": False, + }) + atomic_json(report_path, canonical_report) + return { + "pass_id": pass_id, + "raw_manifest": raw_manifest, + "raw_report": raw_report, + "comparison": comparison, + "extra_source_audit": extras, + "quarantined_payloads": quarantined, + "canonical_manifest": { + "path": str(manifest_path.resolve()), "sha256": manifest_hash, + "rows": len(accepted), + }, + "canonical_report": { + "path": str(report_path.resolve()), "sha256": sha256(report_path), + }, + "supervision_coverage": coverage, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--audit-only", action="store_true") + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + execution = validate_recovery_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + workers = {item["id"]: item for item in execution["workers"]} + worker = workers["arctic"] + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("ARCTIC recovery state path differs from execution plan") + initial_step, resume_step = worker["steps"][:2] + if args.audit_only: + control_rows = load_jsonl(Path(plan["control_manifest"]["path"])) + candidate_rows = load_jsonl(Path(plan["candidate_manifest"])) + comparison = compare_source_sets(control_rows, candidate_rows) + _, candidate_by_index = indexed_rows(candidate_rows, "candidate manifest") + control_report = json.loads( + Path(plan["control_report"]["path"]).read_text(encoding="utf-8") + ) + candidate_report = json.loads( + Path(plan["candidate_report"]).read_text(encoding="utf-8") + ) + expected_extra = plan["expected_extra_source_clip_indices"] + if ( + comparison["control_count"] != plan["expected_clips"] + or comparison["candidate_count"] != plan["raw_candidate_clips"] + or comparison["missing_source_clip_indices"] + or comparison["extra_source_clip_indices"] != expected_extra + or comparison["identity_drift"] + or comparison["missing_groups"] + or comparison["extra_groups"] + ): + raise ValueError("ARCTIC preflight mismatch is outside recovery scope") + result = { + "schema_version": "phase9_arctic_resolution_mismatch_audit_v1", + "status": "complete", + "created_utc": utc_now(), + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "control_manifest": plan["control_manifest"], + "candidate_manifest": { + "path": str(Path(plan["candidate_manifest"]).resolve()), + "sha256": sha256(plan["candidate_manifest"]), + }, + "candidate_report": { + "path": str(Path(plan["candidate_report"]).resolve()), + "sha256": sha256(plan["candidate_report"]), + }, + "comparison": comparison, + "extra_source_audit": source_extra_audit( + source_manifest=Path(plan["source_manifest"]["path"]), + control_report=control_report, + candidate_report=candidate_report, + candidate_by_index=candidate_by_index, + extra_indices=expected_extra, + mano_root=Path(plan["mano_root"]), + ), + "mutation_performed": False, + "expected_clips_changed": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(Path(plan["preflight_audit_output"]), result) + print(json.dumps(result, indent=2)) + return + lock_path = Path(f"{args.state}.lock") + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state = json.loads(args.state.read_text(encoding="utf-8")) + if ( + state.get("worker") != "arctic" + or state.get("plan_sha256") != plan["execution_plan"]["sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + parser.error("ARCTIC failed state binding differs") + existing = state.get("canonical_set_recovery") + if existing and existing.get("status") == "complete": + if not cache_step_complete(initial_step, False) or not cache_step_complete( + resume_step, True + ): + parser.error("completed ARCTIC recovery outputs differ") + print(json.dumps(state, indent=2)) + return + if state.get("status") != "failed_resumable": + parser.error("ARCTIC recovery requires failed_resumable input state") + result: dict[str, Any] = { + "schema_version": "phase9_arctic_resolution_canonical_recovery_v1", + "status": "running", "started_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "failure_state_sha256": sha256(args.state), + "passes": [], "official_test_used": False, + "h2o_official_validation_used": False, + } + state["canonical_set_recovery"] = result + atomic_json(args.state, state) + initial = canonicalize_pass(plan_path=args.plan, plan=plan, pass_id="initial") + if not cache_step_complete(initial_step, False): + raise ValueError("initial ARCTIC canonical cache validation failed") + result["passes"].append(initial) + if initial_step["id"] not in state["completed_steps"]: + state["completed_steps"].append(initial_step["id"]) + command = list(resume_step["resume_command"]) + log_path = Path(plan["resume_log"]) + attempt = { + "step": resume_step["id"], "kind": "cache", + "recovery": "canonical_set_exact_resume_verify", + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_step"] = resume_step["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + completed = subprocess.run( + command, cwd=Path.cwd(), env=dict(os.environ, PYTHONPATH=str(Path.cwd())), + stdout=log, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = completed.returncode + if completed.returncode: + state["status"] = "failed_resumable" + result["status"] = "failed_resume_command" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(completed.returncode) + resumed = canonicalize_pass( + plan_path=args.plan, plan=plan, pass_id="resume_verify", + ) + result["passes"].append(resumed) + if not cache_step_complete(initial_step, False) or not cache_step_complete( + resume_step, True + ): + raise ValueError("resumed ARCTIC canonical cache validation failed") + if resume_step["id"] not in state["completed_steps"]: + state["completed_steps"].append(resume_step["id"]) + result["status"] = "complete" + result["completed_utc"] = utc_now() + result["canonical_manifest_sha256"] = sha256(plan["candidate_manifest"]) + result["canonical_report_sha256"] = sha256(plan["candidate_report"]) + atomic_json(Path(plan["audit_output"]), result) + result["audit_output"] = { + "path": str(Path(plan["audit_output"]).resolve()), + "sha256": sha256(plan["audit_output"]), + } + state["status"] = "waiting_for_remaining_steps" + state["updated_utc"] = utc_now() + state["failure_evidence_preserved"] = state.get("failure") + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_best_worst_video_cases.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_best_worst_video_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..04f5d1c2379da5af6f1d151193c5df89ce67d78b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_best_worst_video_cases.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +"""Render ranked full-take videos for the frozen Phase 3 candidate.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +import yaml + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + MeshLayer, + project_mesh_layers, + render_mesh_layers, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +LEFT_COLOR_RGB = (40, 100, 235) +RIGHT_COLOR_RGB = (235, 55, 55) +MESH_ALPHA = 0.55 + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def _mean(rows: list[dict[str, str]], field: str) -> float: + values = np.asarray([float(row[field]) for row in rows], dtype=np.float64) + if not np.isfinite(values).all(): + raise ValueError(f"non-finite {field} in sequence ranking rows") + return float(values.mean()) + + +def rank_video_sequences( + rows: list[dict[str, str]], *, count: int, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Rank validation takes by all annotation-valid hand-frame errors.""" + + grouped: dict[str, list[dict[str, str]]] = defaultdict(list) + for row in rows: + grouped[row["take"]].append(row) + + candidates = [] + for take, take_rows in grouped.items(): + valid_rows = [row for row in take_rows if int(row["annotation_valid"]) == 1] + if not valid_rows: + continue + observed = { + (int(row["frame_id"]), row["side"]) + for row in take_rows + } + if len(observed) != len(take_rows): + raise ValueError(f"duplicate evaluated hand-frame rows in {take}") + errors = np.asarray( + [float(row["absolute_mpjpe_mm"]) for row in valid_rows], + dtype=np.float64, + ) + if not np.isfinite(errors).all(): + raise ValueError(f"non-finite ranking errors in {take}") + first = valid_rows[0] + evaluated_frame_ids = sorted({int(row["frame_id"]) for row in take_rows}) + annotated_frame_ids = sorted({int(row["frame_id"]) for row in valid_rows}) + candidates.append({ + "take": take, + "subject": first["subject"], + "sequence": first["sequence"], + "evaluation_frame_ids": evaluated_frame_ids, + "evaluated_frame_count": len(evaluated_frame_ids), + "annotated_frame_count": len(annotated_frame_ids), + "annotated_hand_frames": len(valid_rows), + "absolute_mpjpe_mm_mean": float(errors.mean()), + "absolute_mpjpe_mm_p50": float(np.median(errors)), + "absolute_mpjpe_mm_max": float(errors.max()), + "root_relative_mpjpe_mm_mean": _mean(valid_rows, "root_relative_mpjpe_mm"), + "direct_2d_error_px_mean": _mean(valid_rows, "direct_2d_error_px"), + "translation_x_mae_mm_mean": _mean(valid_rows, "translation_x_mae_mm"), + "translation_y_mae_mm_mean": _mean(valid_rows, "translation_y_mae_mm"), + "translation_z_mae_mm_mean": _mean(valid_rows, "translation_z_mae_mm"), + }) + if len(candidates) < count * 2: + raise ValueError( + f"need at least {count * 2} validation takes, found {len(candidates)}" + ) + best = sorted( + candidates, + key=lambda row: (row["absolute_mpjpe_mm_mean"], row["take"]), + )[:count] + failure = sorted( + candidates, + key=lambda row: (-row["absolute_mpjpe_mm_mean"], row["take"]), + )[:count] + if {row["take"] for row in best} & {row["take"] for row in failure}: + raise AssertionError("best and failure sequence selections overlap") + return best, failure + + +def source_frame_ids(data_root: Path, take: str) -> list[int]: + frame_ids = sorted( + int(path.stem) for path in (data_root / take / "rgb").glob("*.png") + ) + if not frame_ids: + raise ValueError(f"no raw RGB frames in {data_root / take}") + expected = list(range(frame_ids[0], frame_ids[-1] + 1)) + if frame_ids != expected: + raise ValueError(f"raw RGB frames are not contiguous in {data_root / take}") + return frame_ids + + +def case_directory_name(rank: int, case: dict[str, Any]) -> str: + sequence = str(case["sequence"]).replace("/", "_") + first_frame, last_frame = case["frame_ids"][0], case["frame_ids"][-1] + return ( + f"{rank:02d}_{case['subject']}_{sequence}_" + f"frames_{first_frame:06d}_{last_frame:06d}" + ) + + +def move_to_device(batch: dict[str, Any], device: torch.device) -> dict[str, Any]: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def add_header(image_rgb: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image_rgb.copy() + height = 8 + 22 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (8, 20 + 22 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.55, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def open_writer(path: Path, fps: float, frame_hw: tuple[int, int]) -> cv2.VideoWriter: + height, width = frame_hw + writer = cv2.VideoWriter( + str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height), + ) + if not writer.isOpened(): + raise RuntimeError(f"failed to open video writer: {path}") + return writer + + +def frame_error_lookup( + rows: list[dict[str, str]], take: str, +) -> dict[int, float]: + values: dict[int, list[float]] = defaultdict(list) + for row in rows: + if row["take"] != take or int(row["annotation_valid"]) != 1: + continue + values[int(row["frame_id"])].append(float(row["absolute_mpjpe_mm"])) + return {frame_id: float(np.mean(errors)) for frame_id, errors in values.items()} + + +def render_case( + *, + case: dict[str, Any], + rank: int, + category: str, + output_dir: Path, + dataset: H2OCam4Dataset, + clip_indices: list[int], + metric_rows: list[dict[str, str]], + data_root: Path, + model: BimanualReconstructionModel, + device: torch.device, + dtype: torch.dtype, + faces: tuple[np.ndarray, np.ndarray], + fps: float, + model_t: int, +) -> dict[str, Any]: + output_dir.mkdir(parents=True, exist_ok=False) + take_dir = data_root / str(case["take"]) + raw_K, source_hw = intrinsics_from_h2o( + load_float_record(take_dir / "cam_intrinsics.txt") + ) + original_path = output_dir / "original_rgb.mp4" + overlay_path = output_dir / "predicted_mano_overlay.mp4" + comparison_path = output_dir / "side_by_side.mp4" + original_writer = open_writer(original_path, fps, source_hw) + overlay_writer = open_writer(overlay_path, fps, source_hw) + comparison_writer = open_writer( + comparison_path, fps, (source_hw[0], source_hw[1] * 2), + ) + errors = frame_error_lookup(metric_rows, str(case["take"])) + expected_frame_ids = list(case["frame_ids"]) + preview = None + rendered_frame_ids: list[int] = [] + try: + for clip_index in clip_indices: + sample = dataset[clip_index] + batch = move_to_device(collate_h2o_clips([sample]), device) + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + clip_frame_ids = [int(value) for value in sample["frame_id"].tolist()] + for time_index, frame_id in enumerate(clip_frame_ids): + raw_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), + cv2.IMREAD_COLOR, + ) + if raw_bgr is None or raw_bgr.shape[:2] != source_hw: + raise RuntimeError( + f"raw RGB decode/shape failure: {take_dir}/{frame_id}" + ) + raw_rgb = cv2.cvtColor(raw_bgr, cv2.COLOR_BGR2RGB) + layers = [ + MeshLayer( + prediction["vertices_camera"][0, time_index, hand] + .float().cpu().numpy(), + faces[hand], + LEFT_COLOR_RGB if hand == 0 else RIGHT_COLOR_RGB, + MESH_ALPHA, + ) + for hand in range(2) + ] + rendered = render_mesh_layers( + raw_rgb, project_mesh_layers(layers, raw_K), + ) + frame_error = errors.get(frame_id) + error_label = ( + f"{frame_error:.2f} mm" + if frame_error is not None else "n/a (not evaluated)" + ) + global_index = len(rendered_frame_ids) + rendered = add_header(rendered, ( + f"{category} #{rank} | predicted MANO | left=BLUE right=RED alpha={MESH_ALPHA:.2f}", + f"{case['subject']}/{case['sequence']} | frame={frame_id} ({global_index + 1}/{len(expected_frame_ids)}) | take MPJPE={case['absolute_mpjpe_mm_mean']:.2f} mm | frame={error_label}", + )) + original_panel = add_header(raw_rgb, ("Original cam4 RGB",)) + comparison = np.concatenate((original_panel, rendered), axis=1) + + original_writer.write(raw_bgr) + overlay_writer.write(cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) + comparison_writer.write(cv2.cvtColor(comparison, cv2.COLOR_RGB2BGR)) + rendered_frame_ids.append(frame_id) + if global_index == len(expected_frame_ids) // 2: + preview = comparison + del prediction, batch + finally: + original_writer.release() + overlay_writer.release() + comparison_writer.release() + + if rendered_frame_ids != expected_frame_ids: + raise RuntimeError( + f"rendered frame sequence mismatch for {case['take']}: " + f"{len(rendered_frame_ids)} != {len(expected_frame_ids)}" + ) + if preview is None: + raise RuntimeError(f"no preview generated for {case['take']}") + preview_path = output_dir / "preview.png" + cv2.imwrite(str(preview_path), cv2.cvtColor(preview, cv2.COLOR_RGB2BGR)) + record = { + **case, + "rank": rank, + "category": category, + "selection_requirement": "official-validation take with finite annotation-valid metrics", + "ranking_metric": "mean absolute MPJPE over all annotation-valid hand-frames in the take", + "inference_policy": f"contiguous full raw take, non-overlapping T={model_t} chunks with final partial chunk", + "colors_rgb": { + "left": list(LEFT_COLOR_RGB), "right": list(RIGHT_COLOR_RGB), + }, + "mesh_alpha": MESH_ALPHA, + "visualization_fps": fps, + "duration_seconds": len(expected_frame_ids) / fps, + "videos": { + "original": str(original_path.resolve()), + "predicted_mano_overlay": str(overlay_path.resolve()), + "side_by_side": str(comparison_path.resolve()), + }, + "preview": str(preview_path.resolve()), + } + (output_dir / "case.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + record["preview_rgb"] = preview + return record + + +def save_contact_sheet(output: Path, records: list[dict[str, Any]]) -> None: + panels = [] + for record in records: + preview = record["preview_rgb"] + panel = cv2.resize(preview, (384, 216), interpolation=cv2.INTER_AREA) + panel = add_header(panel, ( + f"{record['category']} #{record['rank']} | {record['absolute_mpjpe_mm_mean']:.2f} mm | {len(record['frame_ids'])} frames", + )) + panels.append(panel) + rows = [np.concatenate(panels[:5], axis=1), np.concatenate(panels[5:], axis=1)] + sheet = np.concatenate(rows, axis=0) + cv2.imwrite(str(output), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR)) + + +def save_case_summary(output: Path, records: list[dict[str, Any]]) -> None: + lines = [ + "# Ranked Long-Sequence Video Summary", + "", + "Takes are ranked by mean camera-space absolute MPJPE over every", + "annotation-valid official-validation hand-frame. Videos render each full raw", + "take continuously; frames outside the evaluated annotation runs do not affect", + "the ranking. All metric values below use only valid evaluation rows.", + "", + ] + for category, title in (("best", "Best Sequences"), ("failure", "Worst Sequences")): + lines.extend([ + f"## {title}", + "", + "| Rank | Take | Raw frames | Seconds | Evaluated frames | Abs MPJPE | Root-relative | Direct 2D | z MAE |", + "|---:|---|---:|---:|---:|---:|---:|---:|---:|", + ]) + for record in records: + if record["category"] != category: + continue + lines.append( + f"| {record['rank']} | `{record['take']}` | {len(record['frame_ids'])} | " + f"{record['duration_seconds']:.2f} | {record['evaluated_frame_count']} | " + f"{record['absolute_mpjpe_mm_mean']:.2f} mm | " + f"{record['root_relative_mpjpe_mm_mean']:.2f} mm | " + f"{record['direct_2d_error_px_mean']:.2f} px | " + f"{record['translation_z_mae_mm_mean']:.2f} mm |" + ) + lines.append("") + lines.extend([ + "Left MANO is blue, right MANO is red, and mesh alpha is 0.55. The", + "prediction-only overlay uses raw 1280x720 cam4 RGB and the original camera", + "intrinsics. GT meshes are not rendered. Official test was not used.", + "", + ]) + output.write_text("\n".join(lines), encoding="utf-8") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--evaluation-dir", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--count", type=int, default=5) + parser.add_argument("--fps", type=float, default=30.0) + args = parser.parse_args() + if args.count != 5: + raise ValueError("the showcase requires exactly five best and five failure cases") + if args.fps <= 0: + raise ValueError("fps must be positive") + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError(f"refusing to overwrite non-empty output: {args.output_dir}") + args.output_dir.mkdir(parents=True, exist_ok=True) + + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + metric_path = args.evaluation_dir / "per_hand_frame_metrics.csv" + report_path = args.evaluation_dir / "evaluation.json" + metric_rows = read_csv(metric_path) + report = json.loads(report_path.read_text(encoding="utf-8")) + checkpoint_hash = sha256(args.checkpoint) + manifest_hash = sha256(args.manifest) + if ( + report.get("split_role") != "official_validation" + or report.get("official_test_used") is not False + or report.get("checkpoint", {}).get("sha256") != checkpoint_hash + or report.get("manifest", {}).get("sha256") != manifest_hash + ): + raise ValueError("evaluation/checkpoint/manifest provenance mismatch") + + best, failure = rank_video_sequences(metric_rows, count=args.count) + selected = best + failure + for case in selected: + case["frame_ids"] = source_frame_ids(args.data_root, str(case["take"])) + case["raw_frame_count"] = len(case["frame_ids"]) + + render_manifest_path = args.output_dir / "render_input_manifest.jsonl" + render_manifest_path.write_text( + "".join( + json.dumps({"take": case["take"], "frame_ids": case["frame_ids"]}) + "\n" + for case in selected + ), + encoding="utf-8", + ) + model_t = int(data_config["T"]) + dataset = H2OCam4Dataset( + args.data_root, render_manifest_path, tuple(data_config["resolution_hw"]), + (model_t,), (int(data_config["stride"]),), + ) + clip_indices_by_take: dict[str, list[int]] = defaultdict(list) + for clip_index, clip in enumerate(dataset.clips): + clip_indices_by_take[clip.take].append(clip_index) + + device = torch.device(f"cuda:{args.gpu}") + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint( + args.checkpoint, model, optimizer=None, map_location=device, + ) + if int(checkpoint_state["step"]) != int(report["checkpoint"]["step"]): + raise ValueError("checkpoint step differs from source evaluation") + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + faces = tuple(layer.th_faces.cpu().numpy() for layer in model.mano_layer.layers) + + rendered_records = [] + for category, cases, parent_name in ( + ("best", best, "best_cases"), + ("failure", failure, "failure_cases"), + ): + parent = args.output_dir / parent_name + parent.mkdir(exist_ok=False) + for rank, case in enumerate(cases, start=1): + print( + f"rendering {category} #{rank}: {case['take']} " + f"({len(case['frame_ids'])} frames)", + flush=True, + ) + record = render_case( + case=case, rank=rank, category=category, + output_dir=parent / case_directory_name(rank, case), + dataset=dataset, + clip_indices=clip_indices_by_take[str(case["take"])], + metric_rows=metric_rows, data_root=args.data_root.resolve(), + model=model, device=device, dtype=dtype, faces=faces, + fps=args.fps, model_t=model_t, + ) + rendered_records.append(record) + + save_contact_sheet(args.output_dir / "contact_sheet.png", rendered_records) + save_case_summary(args.output_dir / "CASE_SUMMARY.md", rendered_records) + serializable_records = [ + {key: value for key, value in record.items() if key != "preview_rgb"} + for record in rendered_records + ] + manifest = { + "status": "complete", + "official_test_used": False, + "source_split": "official_validation", + "selection_policy": ( + "lowest/highest take mean absolute MPJPE over all annotation-valid " + "official-validation hand-frames" + ), + "render_policy": ( + "all contiguous raw frames in each selected take, including frames " + "outside evaluated annotation runs" + ), + "config": str(args.config.resolve()), + "checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": checkpoint_hash, + "step": int(checkpoint_state["step"]), + }, + "source_manifest": { + "path": str(args.manifest.resolve()), + "sha256": manifest_hash, + }, + "source_evaluation": str(args.evaluation_dir.resolve()), + "render_input_manifest": str(render_manifest_path.resolve()), + "model_input_resolution_hw": list(data_config["resolution_hw"]), + "model_temporal_window": model_t, + "render_space": "raw cam4 RGB resolution with original camera intrinsics", + "videos_are_prediction_only": True, + "visualization_fps": args.fps, + "cases": serializable_records, + } + (args.output_dir / "selection_manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8", + ) + readme = f"""# Best Model Long-Sequence Video Cases + +This directory uses the Phase 3 seed-20260718 step-140k tail-best checkpoint. +The five best and five worst cases are distinct official-validation takes, +ranked by mean camera-space absolute MPJPE across all annotation-valid +hand-frames in each take. + +Each case contains: + +- `original_rgb.mp4`: untouched full raw cam4 RGB sequence; +- `predicted_mano_overlay.mp4`: prediction-only MANO, left blue and right red; +- `side_by_side.mp4`: original and overlay comparison; +- `preview.png` and `case.json`. + +All raw frames from the selected take are rendered continuously, including +frames outside the evaluated annotation runs. Those frames display `n/a` for +the frame metric and do not affect ranking. Inference uses non-overlapping +T={model_t} chunks, matching the formal evaluator, with a final partial chunk. + +Playback is {args.fps:g} fps, matching the H2O capture rate. Mesh alpha is +0.55. Camera-space vertices are projected onto raw 1280x720 RGB with original +cam4 intrinsics. GT meshes are not rendered. Official test was not used. + +See `CASE_SUMMARY.md` for the ranking and metric breakdown, `contact_sheet.png` +for the visual index, and `selection_manifest.json` for full provenance. +""" + (args.output_dir / "README.md").write_text(readme, encoding="utf-8") + print(json.dumps({ + "status": "complete", + "output_dir": str(args.output_dir.resolve()), + "fps": args.fps, + "best_take_mpjpe_mm": [row["absolute_mpjpe_mm_mean"] for row in best], + "failure_take_mpjpe_mm": [ + row["absolute_mpjpe_mm_mean"] for row in failure + ], + "frame_counts": [len(row["frame_ids"]) for row in selected], + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_phase4_filtered_cases.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_phase4_filtered_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea9f5f1022a50e8c55ff0fe3b30b1d019fb4375 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_phase4_filtered_cases.py @@ -0,0 +1,517 @@ +#!/usr/bin/env python3 +"""Render deterministic raw/filtered failure videos from audited jitter caches.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.visualization import ( + OPENPOSE_HAND_EDGES, + draw_skeleton, + project_camera_points, +) +from foundation_hand.geometry.camera import intrinsics_from_h2o +from foundation_hand.models.mano import ManoCameraLayer +try: + from scripts.evaluate_phase4_jitter import ( + condition_grid, + filtered_parameters, + load_take, + rebuild_geometry, + ) +except ModuleNotFoundError: + from evaluate_phase4_jitter import ( # type: ignore[no-redef] + condition_grid, + filtered_parameters, + load_take, + rebuild_geometry, + ) + + +RAW_COLOR = (245, 145, 45) +FILTERED_COLOR = (35, 210, 235) +GT_COLOR = (70, 220, 105) +AXIS_COLORS = ((235, 80, 80), (70, 190, 90), (80, 130, 240)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +class FFmpegWriter: + def __init__(self, path: Path, fps: float, frame_hw: tuple[int, int]) -> None: + self.path = path + self.frame_hw = frame_hw + self.frames = 0 + path.parent.mkdir(parents=True, exist_ok=True) + self.temporary = path.with_name(f".{path.stem}.tmp-{os.getpid()}.mp4") + height, width = frame_hw + self.process = subprocess.Popen([ + "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-y", + "-f", "rawvideo", "-pix_fmt", "bgr24", "-s:v", f"{width}x{height}", + "-r", f"{fps:g}", "-i", "pipe:0", "-an", "-c:v", "libx264", + "-preset", "fast", "-crf", "18", "-pix_fmt", "yuv420p", + "-movflags", "+faststart", str(self.temporary), + ], stdin=subprocess.PIPE, stderr=subprocess.PIPE) + + def write(self, frame_bgr: np.ndarray) -> None: + if frame_bgr.shape != (*self.frame_hw, 3) or frame_bgr.dtype != np.uint8: + raise ValueError("video frame shape/dtype mismatch") + if self.process.stdin is None: + raise RuntimeError("ffmpeg stdin unavailable") + self.process.stdin.write(np.ascontiguousarray(frame_bgr).tobytes()) + self.frames += 1 + + def close(self) -> None: + assert self.process.stdin is not None + self.process.stdin.close() + stderr = self.process.stderr.read().decode("utf-8", errors="replace") if self.process.stderr else "" + return_code = self.process.wait() + if return_code: + self.temporary.unlink(missing_ok=True) + raise RuntimeError(f"ffmpeg failed: {stderr.strip()}") + os.replace(self.temporary, self.path) + + def abort(self) -> None: + if self.process.stdin is not None and not self.process.stdin.closed: + self.process.stdin.close() + if self.process.poll() is None: + self.process.terminate() + self.process.wait(timeout=10) + self.temporary.unlink(missing_ok=True) + + +def add_header(image: np.ndarray, lines: tuple[str, ...]) -> np.ndarray: + output = image.copy() + height = 8 + 24 * len(lines) + cv2.rectangle(output, (0, 0), (output.shape[1], height), (0, 0, 0), -1) + for index, line in enumerate(lines): + cv2.putText( + output, line, (9, 21 + 24 * index), cv2.FONT_HERSHEY_SIMPLEX, + 0.58, (255, 255, 255), 1, cv2.LINE_AA, + ) + return output + + +def ranked_failure_takes( + cache_manifest: dict[str, Any], count: int, +) -> list[dict[str, object]]: + records = [] + for record in cache_manifest["takes"]: + arrays = load_take(Path(record["path"])) + error = np.linalg.norm( + arrays["pred_joints_camera"] - arrays["target_joints_camera"], axis=-1, + ) * 1000.0 + valid = arrays["joint_element_valid"].astype(bool) + values = error[valid] + if not len(values) or not np.isfinite(values).all(): + continue + records.append({ + "take": str(arrays["take"]), "path": record["path"], + "frames": len(arrays["frame_id"]), + "raw_absolute_mpjpe_mm": float(values.mean()), + }) + if len(records) < count: + raise ValueError("not enough annotated takes for filtered video cases") + return sorted( + records, key=lambda row: (-float(row["raw_absolute_mpjpe_mm"]), str(row["take"])), + )[:count] + + +def project_joints(joints: np.ndarray, K: np.ndarray) -> np.ndarray: + pixels, z = project_camera_points(joints, K) + pixels[z <= 1e-8] = np.nan + return pixels + + +def overlay_joints( + image_rgb: np.ndarray, + joints: np.ndarray, + K: np.ndarray, + color: tuple[int, int, int], + valid_hands: np.ndarray | None = None, +) -> np.ndarray: + output = image_rgb + for hand in range(2): + if valid_hands is not None and not bool(valid_hands[hand]): + continue + output = draw_skeleton( + output, project_joints(joints[hand], K), color, + marker="ring" if color == GT_COLOR else "circle", + ) + return output + + +def side_limits(*joint_sequences: np.ndarray) -> tuple[float, float, float, float]: + points = np.concatenate([values.reshape(-1, 3) for values in joint_sequences]) + finite = points[np.isfinite(points).all(axis=-1)] + if not len(finite): + return -0.4, 0.4, 0.2, 0.9 + x0, x1 = np.percentile(finite[:, 0], (1, 99)) + z0, z1 = np.percentile(finite[:, 2], (1, 99)) + x_margin = max(0.03, 0.1 * (x1 - x0)) + z_margin = max(0.03, 0.1 * (z1 - z0)) + return x0 - x_margin, x1 + x_margin, z0 - z_margin, z1 + z_margin + + +def camera_side_panel( + raw_joints: np.ndarray, + filtered_joints: np.ndarray, + target_joints: np.ndarray, + valid_hands: np.ndarray, + limits: tuple[float, float, float, float], + frame_id: int, + size: tuple[int, int] = (540, 960), +) -> np.ndarray: + height, width = size + panel = np.full((height, width, 3), 248, dtype=np.uint8) + x0, x1, z0, z1 = limits + + def point(value: np.ndarray) -> tuple[int, int]: + x = int(round(50 + (value[0] - x0) / max(x1 - x0, 1e-6) * (width - 100))) + y = int(round(height - 45 - (value[2] - z0) / max(z1 - z0, 1e-6) * (height - 100))) + return x, y + + cv2.rectangle(panel, (50, 45), (width - 50, height - 45), (50, 50, 50), 1) + for joints, color, valid_only in ( + (target_joints, GT_COLOR, True), + (raw_joints, RAW_COLOR, False), + (filtered_joints, FILTERED_COLOR, False), + ): + for hand in range(2): + if valid_only and not valid_hands[hand]: + continue + finite = np.isfinite(joints[hand]).all(axis=-1) + for start, end in OPENPOSE_HAND_EDGES: + if finite[start] and finite[end]: + cv2.line(panel, point(joints[hand, start]), point(joints[hand, end]), color, 2, cv2.LINE_AA) + for joint_index in np.flatnonzero(finite): + cv2.circle(panel, point(joints[hand, joint_index]), 2, color, -1, cv2.LINE_AA) + panel = add_header(panel, ( + f"Camera side view x/z | frame={frame_id}", + "GT=green raw=orange filtered=cyan", + )) + return panel + + +def trace_panel( + raw_error: np.ndarray, + filtered_error: np.ndarray, + valid: np.ndarray, + current: int, + side: str, + size: tuple[int, int] = (540, 1920), +) -> np.ndarray: + height, width = size + panel = np.full((height, width, 3), 250, dtype=np.uint8) + finite_values = np.concatenate((raw_error[valid], filtered_error[valid])) + limit = max(10.0, float(np.percentile(np.abs(finite_values), 99))) if finite_values.size else 10.0 + left, right = 70, width - 35 + band_height = (height - 70) // 3 + for axis, axis_name in enumerate("xyz"): + top = 48 + axis * band_height + bottom = top + band_height - 12 + middle = (top + bottom) // 2 + cv2.line(panel, (left, middle), (right, middle), (150, 150, 150), 1) + cv2.putText(panel, f"{axis_name} +/-{limit:.0f}mm", (8, top + 18), cv2.FONT_HERSHEY_SIMPLEX, 0.48, AXIS_COLORS[axis], 1, cv2.LINE_AA) + + def points(values: np.ndarray) -> list[np.ndarray]: + output = [] + segment = [] + for index, value in enumerate(values[:, axis]): + if valid[index] and np.isfinite(value): + x = int(round(left + index / max(len(values) - 1, 1) * (right - left))) + y = int(round(middle - np.clip(value / limit, -1, 1) * (bottom - top) / 2)) + segment.append((x, y)) + elif segment: + output.append(np.asarray(segment, dtype=np.int32)) + segment = [] + if segment: + output.append(np.asarray(segment, dtype=np.int32)) + return output + + for segment in points(raw_error): + if len(segment) >= 2: + cv2.polylines(panel, [segment], False, (115, 115, 115), 1, cv2.LINE_AA) + for segment in points(filtered_error): + if len(segment) >= 2: + cv2.polylines(panel, [segment], False, AXIS_COLORS[axis], 2, cv2.LINE_AA) + current_x = int(round(left + current / max(len(raw_error) - 1, 1) * (right - left))) + cv2.line(panel, (current_x, 42), (current_x, height - 20), (20, 20, 20), 1) + return add_header(panel, ( + f"Signed wrist xyz error | {side} hand | raw=gray filtered=color", + )) + + +def worst_side(arrays: dict[str, np.ndarray]) -> int: + valid = arrays["joint_annotation_valid"].astype(bool) + signed_z = ( + arrays["pred_wrist_translation"] - arrays["target_wrist_translation"] + )[..., 2] * 1000.0 + means = [ + float(np.mean(np.abs(signed_z[:, hand][valid[:, hand]]))) + if valid[:, hand].any() else -1.0 + for hand in range(2) + ] + return int(np.argmax(means)) + + +def render_case( + *, + arrays: dict[str, np.ndarray], + condition_name: str, + filtered_translation: np.ndarray, + filtered_joints: np.ndarray, + data_root: Path, + output_dir: Path, +) -> dict[str, object]: + take = str(arrays["take"]) + take_dir = data_root / take + raw_K, source_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + output_dir.mkdir(parents=True, exist_ok=False) + paths = { + "raw_vs_filtered_30fps": output_dir / "raw_vs_filtered_30fps.mp4", + "raw_vs_filtered_4fps": output_dir / "raw_vs_filtered_4fps.mp4", + "failure_diagnostic_30fps": output_dir / "failure_diagnostic_30fps.mp4", + } + writers = { + "raw_vs_filtered_30fps": FFmpegWriter( + paths["raw_vs_filtered_30fps"], 30.0, (source_hw[0], source_hw[1] * 2), + ), + "raw_vs_filtered_4fps": FFmpegWriter( + paths["raw_vs_filtered_4fps"], 4.0, (source_hw[0], source_hw[1] * 2), + ), + "failure_diagnostic_30fps": FFmpegWriter( + paths["failure_diagnostic_30fps"], 30.0, (1080, 1920), + ), + } + side = worst_side(arrays) + side_name = "left" if side == 0 else "right" + valid_side = arrays["joint_annotation_valid"][:, side].astype(bool) + raw_error = ( + arrays["pred_wrist_translation"][:, side] + - arrays["target_wrist_translation"][:, side] + ) * 1000.0 + filtered_error = ( + filtered_translation[:, side] - arrays["target_wrist_translation"][:, side] + ) * 1000.0 + limits = side_limits( + arrays["pred_joints_camera"], filtered_joints, + arrays["target_joints_camera"], + ) + frame_hashes: dict[str, list[str]] = {key: [] for key in writers} + try: + for index, frame_id in enumerate(arrays["frame_id"].astype(int)): + image_bgr = cv2.imread( + str(take_dir / "rgb" / f"{frame_id:06d}.png"), cv2.IMREAD_COLOR, + ) + if image_bgr is None or image_bgr.shape[:2] != source_hw: + raise RuntimeError(f"raw RGB failure for {take}/{frame_id}") + image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) + raw_panel = overlay_joints( + image_rgb, arrays["pred_joints_camera"][index], raw_K, RAW_COLOR, + ) + raw_panel = add_header(raw_panel, ( + f"RAW model | {take} | frame={frame_id}", + "MANO joints=orange | 30 fps physical time", + )) + filtered_panel = overlay_joints( + image_rgb, filtered_joints[index], raw_K, FILTERED_COLOR, + ) + filtered_panel = add_header(filtered_panel, ( + f"FILTERED {condition_name} | {take} | frame={frame_id}", + "MANO joints=cyan | inference-only secondary", + )) + comparison_rgb = np.concatenate((raw_panel, filtered_panel), axis=1) + comparison_bgr = cv2.cvtColor(comparison_rgb, cv2.COLOR_RGB2BGR) + for key in ("raw_vs_filtered_30fps", "raw_vs_filtered_4fps"): + writers[key].write(comparison_bgr) + frame_hashes[key].append(hashlib.sha256(comparison_bgr.tobytes()).hexdigest()) + + diagnostic_overlay = overlay_joints( + image_rgb, arrays["target_joints_camera"][index], raw_K, + GT_COLOR, arrays["joint_annotation_valid"][index], + ) + diagnostic_overlay = overlay_joints( + diagnostic_overlay, arrays["pred_joints_camera"][index], raw_K, + RAW_COLOR, + ) + diagnostic_overlay = overlay_joints( + diagnostic_overlay, filtered_joints[index], raw_K, FILTERED_COLOR, + ) + diagnostic_overlay = add_header(diagnostic_overlay, ( + f"GT/raw/filtered overlay | {take} | frame={frame_id}", + "GT=green raw=orange filtered=cyan", + )) + top_left = cv2.resize(diagnostic_overlay, (960, 540), interpolation=cv2.INTER_AREA) + top_right = camera_side_panel( + arrays["pred_joints_camera"][index], filtered_joints[index], + arrays["target_joints_camera"][index], + arrays["joint_annotation_valid"][index], limits, frame_id, + ) + trace = trace_panel( + raw_error, filtered_error, valid_side, index, side_name, + ) + diagnostic_rgb = np.concatenate(( + np.concatenate((top_left, top_right), axis=1), trace, + ), axis=0) + diagnostic_bgr = cv2.cvtColor(diagnostic_rgb, cv2.COLOR_RGB2BGR) + writers["failure_diagnostic_30fps"].write(diagnostic_bgr) + frame_hashes["failure_diagnostic_30fps"].append( + hashlib.sha256(diagnostic_bgr.tobytes()).hexdigest() + ) + except Exception: + for writer in writers.values(): + writer.abort() + raise + for writer in writers.values(): + writer.close() + videos = { + key: { + "path": str(path.resolve()), "sha256": sha256(path), + "frames": writers[key].frames, + "fps": 4.0 if key.endswith("4fps") else 30.0, + "frame_pixel_sha256": frame_hashes[key], + } + for key, path in paths.items() + } + record = { + "take": take, "condition": condition_name, + "frames": len(arrays["frame_id"]), "trace_side": side_name, + "official_test_used": False, "videos": videos, + } + (output_dir / "case.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + return record + + +def assert_deterministic( + records: list[dict[str, object]], reference_manifest: Path, +) -> None: + reference = json.loads(reference_manifest.read_text(encoding="utf-8")) + reference_index = { + (record["take"], record["condition"]): record for record in reference["cases"] + } + observed_keys = {(record["take"], record["condition"]) for record in records} + if observed_keys != set(reference_index): + raise ValueError("visualization audit case grid mismatch") + for record in records: + other = reference_index.get((record["take"], record["condition"])) + if other is None: + raise ValueError("visualization audit case grid mismatch") + for video_name, video in record["videos"].items(): + if video["frame_pixel_sha256"] != other["videos"][video_name]["frame_pixel_sha256"]: + raise ValueError(f"visualization pixels are non-deterministic: {video_name}") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--selection-json", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + parser.add_argument("--case-count", type=int, default=3) + parser.add_argument("--audit-against", type=Path) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("filtered video output must be new or empty") + cache_manifest = json.loads( + (args.cache_dir / "cache_manifest.json").read_text(encoding="utf-8") + ) + selection = json.loads(args.selection_json.read_text(encoding="utf-8")) + if ( + cache_manifest.get("status") != "complete" + or cache_manifest.get("official_test_used") is not False + or cache_manifest.get("scope") != "full" + or cache_manifest.get("clips") != 1495 + or cache_manifest.get("frames") != 11638 + or selection.get("status") != "selected" + or selection.get("official_test_used") is not False + or selection.get("selection_scope") + != "frozen_official_validation_subset_256" + or selection.get("checkpoint", {}).get("sha256") + != cache_manifest.get("checkpoint", {}).get("sha256") + ): + raise ValueError("filtered video cache/selection provenance mismatch") + selected_conditions = [ + value for family, value in sorted(selection["selected_conditions"].items()) + if value is not None + ] + if not selected_conditions: + raise ValueError("no eligible filter condition was selected") + grid = condition_grid() + cases = ranked_failure_takes(cache_manifest, args.case_count) + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + records = [] + for condition_name in selected_conditions: + condition = grid[condition_name] + for rank, case in enumerate(cases, start=1): + arrays = load_take(Path(case["path"])) + filtered_translation, filtered_rotations, _ = filtered_parameters( + arrays, condition, + ) + _, filtered_joints = rebuild_geometry( + filtered_rotations, arrays["pred_shape"].astype(np.float32), + filtered_translation, mano, device, + ) + record = render_case( + arrays=arrays, condition_name=condition_name, + filtered_translation=filtered_translation, + filtered_joints=filtered_joints, + data_root=args.data_root, + output_dir=( + args.output_dir / condition_name + / f"{rank:02d}_{str(case['take']).replace('/', '__')}" + ), + ) + record["rank"] = rank + record["raw_absolute_mpjpe_mm"] = case["raw_absolute_mpjpe_mm"] + records.append(record) + if args.audit_against is not None: + assert_deterministic(records, args.audit_against) + manifest = { + "status": "complete", + "official_test_used": False, + "result_role": "filtered_inference_secondary_results", + "cache_checkpoint": cache_manifest["checkpoint"], + "selection_json": str(args.selection_json.resolve()), + "conditions": selected_conditions, + "case_selection": "highest raw take-level absolute MPJPE", + "deterministic_against": ( + str(args.audit_against.resolve()) if args.audit_against else None + ), + "deterministic_pixel_audit_passed": args.audit_against is not None, + "cases": records, + } + args.output_dir.mkdir(parents=True, exist_ok=True) + (args.output_dir / "video_manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "conditions": selected_conditions, + "cases": len(records), "deterministic_audit": args.audit_against is not None, + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_phase5_alignment_failure_cases.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_phase5_alignment_failure_cases.py new file mode 100644 index 0000000000000000000000000000000000000000..051fe5d245d148f74274f9d9d3dc2463f44468db --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_phase5_alignment_failure_cases.py @@ -0,0 +1,362 @@ +#!/usr/bin/env python3 +"""Render deterministic predicted-MANO/depth alignment failure diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import matplotlib +import numpy as np + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +from foundation_hand.data.h2o_fields import load_float_record +from foundation_hand.evaluation.metric_alignment import align_wrist_z +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def select_cases( + rows: list[dict[str, str]], refined_condition: str, +) -> list[dict[str, Any]]: + keyed: dict[tuple[str, int, str], dict[str, dict[str, str]]] = {} + for row in rows: + if row["condition"] not in ("coarse", refined_condition): + continue + key = (row["take"], int(row["frame_id"]), row["side"]) + keyed.setdefault(key, {})[row["condition"]] = row + pairs = [ + (key, values["coarse"], values[refined_condition]) + for key, values in keyed.items() + if set(values) == {"coarse", refined_condition} + ] + if not pairs: + raise ValueError("no matched coarse/refined frame rows") + + def z(row: dict[str, str]) -> float: + return float(row["translation_z_mae_mm"]) + + role_candidates = { + "right_far_small_tail": sorted( + ( + item for item in pairs + if item[0][2] == "right" and ( + item[1]["depth_bucket"] == "far" + or item[1]["hand_size_bucket"] == "small" + ) + ), + key=lambda item: (-z(item[1]), item[0]), + ), + "largest_z_gain": sorted( + pairs, key=lambda item: (-(z(item[1]) - z(item[2])), item[0]), + ), + "largest_z_harm": sorted( + pairs, key=lambda item: (-(z(item[2]) - z(item[1])), item[0]), + ), + } + selected = [] + used: set[tuple[str, int, str]] = set() + for role, candidates in role_candidates.items(): + choice = next((item for item in candidates if item[0] not in used), None) + if choice is None: + raise ValueError(f"cannot select a unique case for {role}") + key, coarse, refined = choice + used.add(key) + selected.append({ + "role": role, + "take": key[0], + "frame_id": key[1], + "side": key[2], + "coarse_z_mae_mm": z(coarse), + "refined_z_mae_mm": z(refined), + "z_mae_delta_mm": z(refined) - z(coarse), + "coarse_absolute_mpjpe_mm": float(coarse["absolute_mpjpe_mm"]), + "refined_absolute_mpjpe_mm": float(refined["absolute_mpjpe_mm"]), + "applied_delta_z_mm": float(refined["applied_delta_z_mm"]), + "alignment_confidence": float(refined["alignment_confidence"]), + "alignment_support": int(refined["alignment_support"]), + "alignment_quality": float(refined["alignment_quality"]), + "depth_bucket": coarse["depth_bucket"], + "hand_size_bucket": coarse["hand_size_bucket"], + }) + return selected + + +def inlier_masks( + observed_depth_m: np.ndarray, + predicted_depth_m: np.ndarray, + sample_valid: np.ndarray, + delta_z_m: float, + residual_scale_m: float, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + residual = observed_depth_m - predicted_depth_m + eligible = sample_valid & np.isfinite(residual) & (np.abs(residual) <= 0.15) + scale = max(float(residual_scale_m), 0.003) + inlier = eligible & (np.abs(residual - float(delta_z_m)) <= 1.345 * scale) + return eligible, inlier, eligible & ~inlier + + +def crop_bounds( + points_px: np.ndarray, image_hw: tuple[int, int], minimum_size: int = 240, +) -> tuple[int, int, int, int]: + height, width = image_hw + points = np.asarray(points_px, dtype=np.float64).reshape(-1, 2) + points = points[np.isfinite(points).all(axis=1)] + if not len(points): + return 0, 0, width, height + low, high = points.min(axis=0), points.max(axis=0) + center = (low + high) / 2.0 + size = max(float(np.max(high - low) + 120.0), float(minimum_size)) + size = min(size, float(width), float(height)) + x0 = int(np.clip(round(center[0] - size / 2), 0, width - size)) + y0 = int(np.clip(round(center[1] - size / 2), 0, height - size)) + return x0, y0, int(x0 + size), int(y0 + size) + + +def draw_points( + axis: plt.Axes, points: np.ndarray, color: str, label: str, + *, marker: str = "o", size: float = 10.0, alpha: float = 0.9, +) -> None: + values = np.asarray(points) + finite = np.isfinite(values).all(axis=-1) + axis.scatter( + values[finite, 0], values[finite, 1], s=size, c=color, + marker=marker, alpha=alpha, label=label, linewidths=0.4, + ) + + +def render_case( + case: dict[str, Any], + *, + cache_arrays: dict[str, np.ndarray], + alignment_arrays: dict[str, np.ndarray], + data_root: Path, + output: Path, +) -> dict[str, Any]: + frame_ids = cache_arrays["frame_id"].astype(np.int64) + matches = np.where(frame_ids == int(case["frame_id"]))[0] + if len(matches) != 1: + raise ValueError(f"frame is not unique in raw cache: {case}") + index = int(matches[0]) + hand = 1 if case["side"] == "right" else 0 + take_dir = data_root / case["take"] + frame_name = f"{int(case['frame_id']):06d}.png" + rgb_bgr = cv2.imread(str(take_dir / "rgb" / frame_name), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(take_dir / "depth" / frame_name), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise FileNotFoundError(f"missing RGB/depth for {case['take']}/{frame_name}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + K_raw, raw_hw = intrinsics_from_h2o(load_float_record(take_dir / "cam_intrinsics.txt")) + if tuple(rgb.shape[:2]) != raw_hw or tuple(depth_mm.shape) != raw_hw: + raise ValueError("raw RGB/depth/intrinsics dimensions disagree") + depth_m, depth_valid = depth_mm_to_m(depth_mm) + coarse_vertices = cache_arrays["pred_vertices_camera"][index, hand] + diagnostics, surface = align_wrist_z(coarse_vertices, K_raw, depth_m, depth_valid) + if surface is None: + raise AssertionError("complete-modality case has no surface samples") + stored_delta = float(alignment_arrays["raw_alignment_delta_z_m"][index, hand]) + if abs(diagnostics.delta_z_m - stored_delta) > 1e-8: + raise ValueError("rerender alignment delta differs from evaluated prediction") + correction = float(alignment_arrays["calibrated_delta_z_m"][index, hand]) + eligible, inlier, outlier = inlier_masks( + surface.observed_depth_m, surface.predicted_depth_m, + surface.sample_valid, diagnostics.delta_z_m, diagnostics.residual_scale_m, + ) + + coarse_joints = cache_arrays["pred_joints_camera"][index, hand].astype(np.float64) + target_joints = cache_arrays["target_joints_camera"][index, hand].astype(np.float64) + refined_joints = coarse_joints.copy() + refined_joints[:, 2] += correction + coarse_px, _ = project_points(coarse_joints, K_raw) + refined_px, _ = project_points(refined_joints, K_raw) + target_px, _ = project_points(target_joints, K_raw) + bounds = crop_bounds( + np.concatenate((coarse_px, target_px, surface.projected_vertices_px[surface.visible_vertex])), + raw_hw, + ) + x0, y0, x1, y1 = bounds + offset = np.asarray((x0, y0)) + + figure, axes = plt.subplots(2, 3, figsize=(16, 9), dpi=120) + rgb_axis = axes[0, 0] + rgb_axis.imshow(rgb[y0:y1, x0:x1]) + draw_points(rgb_axis, target_px - offset, "#2ca02c", "GT", marker="x", size=24) + draw_points(rgb_axis, coarse_px - offset, "#d6278b", "coarse", size=16) + draw_points(rgb_axis, refined_px - offset, "#00a6d6", "refined", marker="+", size=24) + rgb_axis.set_title(f"RGB projection | {case['side']}") + rgb_axis.legend(loc="upper right", fontsize=8) + rgb_axis.axis("off") + + depth_axis = axes[0, 1] + depth_display = np.where(depth_valid, depth_m, np.nan) + depth_axis.imshow(depth_display[y0:y1, x0:x1], cmap="turbo", vmin=0.25, vmax=1.25) + projected = surface.projected_vertices_px - offset + draw_points(depth_axis, projected[inlier], "#39d353", "IRLS inlier", size=13) + draw_points(depth_axis, projected[outlier], "#ff4d4f", "eligible outlier", marker="x", size=17) + invalid_visible = surface.visible_vertex & ~eligible + draw_points(depth_axis, projected[invalid_visible], "#dddddd", "invalid", size=5, alpha=0.45) + depth_axis.set_title("Observed metric depth + surface samples") + depth_axis.legend(loc="upper right", fontsize=7) + depth_axis.axis("off") + + scatter_axis = axes[0, 2] + predicted = surface.predicted_depth_m[eligible] + observed = surface.observed_depth_m[eligible] + scatter_axis.scatter(predicted[inlier[eligible]], observed[inlier[eligible]], s=9, c="#39d353", label="inlier") + scatter_axis.scatter(predicted[outlier[eligible]], observed[outlier[eligible]], s=12, c="#ff4d4f", marker="x", label="outlier") + if len(predicted): + low = float(min(predicted.min(), observed.min())) + high = float(max(predicted.max(), observed.max())) + grid = np.linspace(low, high, 100) + scatter_axis.plot(grid, grid, color="#666666", linewidth=1, label="surface identity") + scatter_axis.plot(grid, grid + diagnostics.delta_z_m, color="#d6278b", linewidth=1.3, label="raw IRLS shift") + scatter_axis.plot(grid, grid + correction, color="#00a6d6", linewidth=1.3, label="calibrated shift") + scatter_axis.set_xlabel("predicted MANO surface z (m)") + scatter_axis.set_ylabel("observed depth z (m)") + scatter_axis.set_title("Metric correspondence") + scatter_axis.grid(alpha=0.2) + scatter_axis.legend(fontsize=7) + + side_axis = axes[1, 0] + target_vertices = cache_arrays["target_vertices_camera"][index, hand] + refined_vertices = coarse_vertices.astype(np.float64).copy() + refined_vertices[:, 2] += correction + sample = np.arange(0, len(coarse_vertices), 6) + side_axis.scatter(coarse_vertices[sample, 2], coarse_vertices[sample, 0], s=3, c="#d6278b", alpha=0.35, label="coarse") + side_axis.scatter(refined_vertices[sample, 2], refined_vertices[sample, 0], s=3, c="#00a6d6", alpha=0.35, label="refined") + side_axis.scatter(target_vertices[sample, 2], target_vertices[sample, 0], s=3, c="#2ca02c", alpha=0.35, label="GT") + side_axis.set_xlabel("camera z (m)") + side_axis.set_ylabel("camera x (m)") + side_axis.set_title("Camera side view") + side_axis.grid(alpha=0.2) + side_axis.legend(fontsize=7) + side_axis.set_aspect("equal", adjustable="datalim") + + trace_axis = axes[1, 1] + start, stop = max(0, index - 20), min(len(frame_ids), index + 21) + trace_frames = frame_ids[start:stop] + coarse_signed = 1000.0 * ( + cache_arrays["pred_wrist_translation"][start:stop, hand, 2] + - cache_arrays["target_wrist_translation"][start:stop, hand, 2] + ) + refined_signed = coarse_signed + 1000.0 * alignment_arrays["calibrated_delta_z_m"][start:stop, hand] + trace_axis.plot(trace_frames, coarse_signed, color="#d6278b", label="coarse signed z") + trace_axis.plot(trace_frames, refined_signed, color="#00a6d6", label="refined signed z") + trace_axis.axhline(0.0, color="#555555", linewidth=0.8) + trace_axis.axvline(case["frame_id"], color="#111111", linestyle="--", linewidth=0.8) + trace_axis.set_xlabel("frame") + trace_axis.set_ylabel("pred - GT wrist z (mm)") + trace_axis.set_title("Local signed-z trace") + trace_axis.grid(alpha=0.2) + trace_axis.legend(fontsize=7) + + text_axis = axes[1, 2] + text_axis.axis("off") + text_axis.text(0.0, 1.0, "\n".join(( + f"role: {case['role']}", + f"take/frame: {case['take']} / {case['frame_id']}", + f"side, size, depth: {case['side']}, {case['hand_size_bucket']}, {case['depth_bucket']}", + f"coarse -> refined z MAE: {case['coarse_z_mae_mm']:.2f} -> {case['refined_z_mae_mm']:.2f} mm", + f"coarse -> refined MPJPE: {case['coarse_absolute_mpjpe_mm']:.2f} -> {case['refined_absolute_mpjpe_mm']:.2f} mm", + f"raw IRLS / calibrated delta-z: {1000.0 * diagnostics.delta_z_m:.2f} / {1000.0 * correction:.2f} mm", + f"support / inlier ratio: {diagnostics.valid_support_count} / {diagnostics.inlier_ratio:.3f}", + f"residual scale: {1000.0 * diagnostics.residual_scale_m:.2f} mm", + f"valid / foreground / background: {diagnostics.valid_fraction:.3f} / {diagnostics.foreground_fraction:.3f} / {diagnostics.background_fraction:.3f}", + f"depth discontinuity: {1000.0 * diagnostics.depth_discontinuity_m:.2f} mm", + f"conditioning / learned confidence: {diagnostics.conditioning_quality:.3f} / {case['alignment_confidence']:.3f}", + "selection: official-validation secondary diagnostic only", + )), va="top", family="monospace", fontsize=10) + figure.suptitle("Phase 5 predicted-location MANO-depth alignment diagnostic", fontsize=14) + figure.tight_layout() + output.parent.mkdir(parents=True, exist_ok=True) + figure.savefig(output) + plt.close(figure) + return { + **case, + "image": str(output.resolve()), + "image_sha256": sha256(output), + "eligible_surface_samples": int(eligible.sum()), + "inlier_surface_samples": int(inlier.sum()), + "outlier_surface_samples": int(outlier.sum()), + "rerender_raw_delta_z_mm": 1000.0 * diagnostics.delta_z_m, + "rerender_residual_scale_mm": 1000.0 * diagnostics.residual_scale_m, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-dir", type=Path, required=True) + parser.add_argument("--raw-cache-manifest", type=Path, required=True) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--condition", default="calibrated_always") + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("visualization output directory must be new or empty") + evaluation = json.loads((args.evaluation_dir / "evaluation.json").read_text(encoding="utf-8")) + cache = json.loads(args.raw_cache_manifest.read_text(encoding="utf-8")) + if evaluation.get("official_test_used") is not False or cache.get("official_test_used") is not False: + raise ValueError("failure visualization requires test-free inputs") + if args.condition not in evaluation.get("conditions", []): + raise ValueError(f"condition is absent from evaluation: {args.condition}") + cases = select_cases( + load_csv(args.evaluation_dir / "per_hand_frame_metrics.csv"), args.condition, + ) + cache_by_take = {record["take"]: record for record in cache["takes"]} + records = [] + for case in cases: + cache_record = cache_by_take[case["take"]] + cache_path = Path(cache_record["path"]) + if sha256(cache_path) != cache_record["sha256"]: + raise ValueError(f"raw-cache hash mismatch: {cache_path}") + with np.load(cache_path, allow_pickle=False) as archive: + cache_arrays = {key: archive[key] for key in archive.files} + prediction_path = args.evaluation_dir / "predictions" / f"{'__'.join(Path(case['take']).parts)}.npz" + with np.load(prediction_path, allow_pickle=False) as archive: + alignment = {key: archive[key] for key in archive.files} + filename = f"{case['role']}__{'__'.join(Path(case['take']).parts)}__f{case['frame_id']:06d}__{case['side']}.png" + records.append(render_case( + case, cache_arrays=cache_arrays, alignment_arrays=alignment, + data_root=args.data_root, output=args.output_dir / filename, + )) + report = { + "status": "complete", + "result_role": "official_validation_secondary_failure_diagnostic", + "selection_rule": ["right far/small maximum coarse z error", "largest refined z gain", "largest refined z harm"], + "condition": args.condition, + "evaluation": str(args.evaluation_dir.resolve()), + "raw_cache_manifest": str(args.raw_cache_manifest.resolve()), + "cases": records, + "used_for_model_or_threshold_selection": False, + "oracle_information_at_inference": False, + "official_test_used": False, + } + manifest_path = args.output_dir / "manifest.json" + manifest_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": report["status"], "cases": len(records), + "manifest": str(manifest_path), "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_sota_projection_audit.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_sota_projection_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..212336420b5c6d1a025fd254f26dc10df78e55fa --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/render_sota_projection_audit.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Render deterministic GT/prediction projection checks for SOTA bundles.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + align_prediction, +) + + +EDGES = tuple( + edge + for finger_start in (1, 5, 9, 13, 17) + for edge in ( + (0, finger_start), + (finger_start, finger_start + 1), + (finger_start + 1, finger_start + 2), + (finger_start + 2, finger_start + 3), + ) +) +SIDE_COLORS = ((255, 200, 0), (0, 80, 255)) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def project(points: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + normalized = points[..., :2] / points[..., 2:3] + return normalized @ intrinsics[:2, :2].T + intrinsics[:2, 2] + + +def draw_hand( + image: np.ndarray, + points: np.ndarray, + color: tuple[int, int, int], + *, + thickness: int, + radius: int, +) -> None: + rounded = np.rint(points).astype(np.int32) + for start, end in EDGES: + cv2.line( + image, + tuple(rounded[start]), + tuple(rounded[end]), + color, + thickness, + cv2.LINE_AA, + ) + for point in rounded: + cv2.circle(image, tuple(point), radius, color, -1, cv2.LINE_AA) + + +def make_panel( + image: np.ndarray, + label: str, + predicted: np.ndarray, + target: np.ndarray, + intrinsics: np.ndarray, + detected: np.ndarray, +) -> tuple[np.ndarray, float | None]: + panel = image.copy() + for hand in (0, 1): + draw_hand( + panel, + project(target[hand], intrinsics), + (245, 245, 245), + thickness=4, + radius=4, + ) + if detected[hand]: + draw_hand( + panel, + project(predicted[hand], intrinsics), + SIDE_COLORS[hand], + thickness=2, + radius=3, + ) + valid_hands = np.flatnonzero(detected) + error = None + if valid_hands.size: + error = float( + np.linalg.norm( + predicted[valid_hands] - target[valid_hands], axis=-1 + ).mean() + * 1000.0 + ) + cv2.rectangle(panel, (0, 0), (panel.shape[1], 46), (10, 10, 10), -1) + text = f"{label} Abs={error:.1f} mm" if error is not None else f"{label} missed" + cv2.putText( + panel, + text, + (12, 31), + cv2.FONT_HERSHEY_SIMPLEX, + 0.8, + (255, 255, 255), + 2, + cv2.LINE_AA, + ) + return panel, error + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--prediction", action="append", required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--samples", type=int, default=6) + parser.add_argument("--panel-width", type=int, default=480) + args = parser.parse_args() + if args.samples <= 0 or args.panel_width <= 0: + raise ValueError("samples and panel width must be positive") + + ground_truth = GroundTruthBundle.load(args.ground_truth) + bundles: list[tuple[str, PredictionBundle, Path]] = [] + labels = set() + for spec in args.prediction: + label, separator, raw_path = spec.partition("=") + if not separator or not label or not raw_path or label in labels: + raise ValueError(f"Invalid or duplicate prediction spec: {spec}") + labels.add(label) + path = Path(raw_path).resolve() + bundles.append((label, align_prediction(PredictionBundle.load(path), ground_truth), path)) + + eligible = ground_truth.annotation_valid.all(axis=1) + for _, bundle, _ in bundles: + eligible &= bundle.detected.all(axis=1) + candidate_indices = np.flatnonzero(eligible) + if candidate_indices.size < args.samples: + raise ValueError("Not enough jointly valid/detected frames for projection audit") + positions = np.rint( + np.linspace(0, candidate_indices.size - 1, args.samples) + ).astype(np.int64) + selected = candidate_indices[positions] + + output_rows = [] + record_rows: list[dict[str, Any]] = [] + for frame_index in selected: + take = str(ground_truth.takes[frame_index]) + frame_id = int(ground_truth.frame_ids[frame_index]) + path = args.root / take / "rgb" / f"{frame_id:06d}.png" + image = cv2.imread(str(path)) + if image is None: + raise RuntimeError(f"Image decode failure: {path}") + panels = [] + for label, bundle, _ in bundles: + panel, error = make_panel( + image, + label, + bundle.joints_camera_m[frame_index], + ground_truth.joints_camera_m[frame_index], + ground_truth.intrinsics[frame_index], + bundle.detected[frame_index], + ) + height = round(panel.shape[0] * args.panel_width / panel.shape[1]) + panels.append(cv2.resize(panel, (args.panel_width, height))) + record_rows.append({ + "frame_key": str(ground_truth.frame_keys[frame_index]), + "model": label, + "absolute_mpjpe_mm": error, + }) + output_rows.append(np.concatenate(panels, axis=1)) + + audit_models = [] + height, width = image.shape[:2] + for label, bundle, path in bundles: + detected_points = bundle.joints_camera_m[bundle.detected] + K = np.repeat(ground_truth.intrinsics[:, None], 2, axis=1)[bundle.detected] + uv = np.einsum( + "nij,nkj->nki", + K[:, :2, :2], + detected_points[..., :2] / detected_points[..., 2:3], + ) + K[:, None, :2, 2] + in_frame = ( + (uv[..., 0] >= 0) + & (uv[..., 0] < width) + & (uv[..., 1] >= 0) + & (uv[..., 1] < height) + ) + audit_models.append({ + "label": label, + "prediction": str(path), + "prediction_sha256": sha256(path), + "detected_hand_frames": int(bundle.detected.sum()), + "finite_detected_fraction": float(np.isfinite(detected_points).all(axis=-1).mean()), + "positive_depth_fraction": float((detected_points[..., 2] > 0).mean()), + "projected_joint_in_frame_fraction": float(in_frame.mean()), + "wrist_z_m_percentiles": np.percentile( + detected_points[:, 0, 2], (1, 50, 99) + ).tolist(), + }) + + args.output_dir.mkdir(parents=True, exist_ok=True) + contact_sheet = np.concatenate(output_rows, axis=0) + contact_path = args.output_dir / "projection_contact_sheet.jpg" + if not cv2.imwrite(str(contact_path), contact_sheet, [cv2.IMWRITE_JPEG_QUALITY, 92]): + raise RuntimeError(f"Failed to write {contact_path}") + payload = { + "status": "pass", + "official_test_used": False, + "selection": "evenly spaced among frames valid and detected for every model", + "legend": "GT white; prediction left cyan and right red", + "selected_frame_keys": [ + str(ground_truth.frame_keys[index]) for index in selected + ], + "per_selected_frame": record_rows, + "models": audit_models, + "contact_sheet": str(contact_path.resolve()), + "contact_sheet_sha256": sha256(contact_path), + } + (args.output_dir / "visual_audit.json").write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(payload, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_dynhamr_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_dynhamr_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..84bdce419fb36846d43852afe76b93928b2290ea --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_dynhamr_h2o.py @@ -0,0 +1,627 @@ +#!/usr/bin/env python3 +"""Run the released Dyn-HaMR TTO pipeline zero-shot on H2O validation runs.""" + +from __future__ import annotations + +import argparse +import contextlib +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import matplotlib.pyplot as plt +import numpy as np +import torch +import yaml +from scipy.interpolate import interp1d +from scipy.spatial.transform import Rotation, Slerp + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, frame_key +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--rescale-factor", type=float, default=1.3) + parser.add_argument("--max-runs", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + parser.add_argument( + "--run-indices", + nargs="*", + type=int, + help="Explicit global manifest-run order; overrides modulo sharding.", + ) + return parser.parse_args() + + +def _load_manifest_runs(path: Path) -> list[dict[str, Any]]: + runs = [json.loads(line) for line in path.read_text().splitlines() if line.strip()] + for run_index, run in enumerate(runs): + take = str(run["take"]) + if not take.endswith("/cam4"): + raise ValueError(f"Dyn-HaMR evaluation is cam4-only: {take}") + run["global_run_index"] = run_index + run["frame_ids"] = [int(value) for value in run["frame_ids"]] + return runs + + +def _import_hamer_runner(repo: Path) -> Any: + path = repo / "third-party" / "hamer" / "run.py" + spec = importlib.util.spec_from_file_location("dynhamr_released_hamer_runner", path) + if spec is None or spec.loader is None: + raise ImportError(f"Cannot import released HaMeR runner: {path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _to_numpy(value: Any) -> np.ndarray: + if torch.is_tensor(value): + return value.detach().float().cpu().numpy() + return np.asarray(value) + + +def _interpolate_rotvec(values: np.ndarray, visible: np.ndarray) -> np.ndarray: + output = values.copy() + indices = np.flatnonzero(visible) + if len(indices) < 2: + return output + times = np.arange(indices[0], indices[-1] + 1) + rotations = Rotation.from_rotvec(values[indices].reshape(len(indices), -1, 3)) + joint_count = rotations.as_rotvec().shape[1] + for joint in range(joint_count): + slerp = Slerp(indices, Rotation.from_rotvec(values[indices, joint])) + output[times, joint] = slerp(times).as_rotvec() + return output + + +def _interpolate_linear(values: np.ndarray, visible: np.ndarray) -> np.ndarray: + output = values.copy() + indices = np.flatnonzero(visible) + if len(indices) < 2: + return output + times = np.arange(indices[0], indices[-1] + 1) + function = interp1d(indices, values[indices], axis=0, kind="linear") + output[times] = function(times) + return output + + +def _extract_initialization( + frame_paths: list[Path], + raw_data: list[dict[str, Any]], + results: dict[str, Any], +) -> dict[str, np.ndarray]: + count = len(frame_paths) + pose = np.full((2, count, 15, 3), np.nan, dtype=np.float32) + orient = np.full((2, count, 1, 3), np.nan, dtype=np.float32) + shape = np.full((2, count, 10), np.nan, dtype=np.float32) + translation = np.full((2, count, 3), np.nan, dtype=np.float32) + keypoints = np.full((2, count, 21, 3), np.nan, dtype=np.float32) + confidence = np.full((2, count), np.nan, dtype=np.float32) + + for frame_index, (path, cleaned) in enumerate(zip(frame_paths, raw_data, strict=True)): + result = results[str(path)] + sides = np.asarray(result["tid"], dtype=np.int64) + for local, side in enumerate(sides): + mano = result["mano"][local] + hand_matrix = _to_numpy(mano["hand_pose"]).reshape(15, 3, 3) + root_matrix = _to_numpy(mano["global_orient"]).reshape(3, 3) + pose[side, frame_index] = Rotation.from_matrix(hand_matrix).as_rotvec() + orient[side, frame_index, 0] = Rotation.from_matrix(root_matrix).as_rotvec() + shape[side, frame_index] = _to_numpy(mano["betas"]).reshape(10) + translation[side, frame_index] = np.asarray( + result["cam_trans"][local], dtype=np.float32 + ) + keypoints[side, frame_index] = np.asarray( + result["extra_data"][local], dtype=np.float32 + ) + confidence[side, frame_index] = float( + cleaned["left_conf" if side == 0 else "right_conf"] + ) + + active = np.isfinite(pose).all(axis=(-1, -2)) + recovered = np.zeros_like(active) + vis_mask = np.full((2, count), -1.0, dtype=np.float32) + for side in (0, 1): + indices = np.flatnonzero(active[side]) + if len(indices) < 2: + continue + interval = slice(indices[0], indices[-1] + 1) + recovered[side, interval] = True + vis_mask[side, interval] = 0.0 + vis_mask[side, active[side]] = 1.0 + pose[side] = _interpolate_rotvec(pose[side], active[side]) + orient[side] = _interpolate_rotvec(orient[side], active[side]) + shape[side] = _interpolate_linear(shape[side], active[side]) + translation[side] = _interpolate_linear(translation[side], active[side]) + keypoints[side] = _interpolate_linear(keypoints[side], active[side]) + confidence[side] = _interpolate_linear(confidence[side], active[side]) + # The released file loader represents frames outside each recovered track + # with zeros and excludes them through the ternary visibility mask. + for values in (pose, orient, shape, translation, keypoints): + np.nan_to_num(values, copy=False) + return { + "pose": pose, + "orient": orient[:, :, 0], + "shape": shape, + "translation": translation, + "keypoints": keypoints, + "confidence": confidence, + "active": active, + "recovered": recovered, + "vis_mask": vis_mask, + } + + +def _run_official_initialization( + repo: Path, + frame_paths: list[Path], + detector: Any, + hamer_model: torch.nn.Module, + hamer_config: Any, + runner: Any, + rescale_factor: float, +) -> dict[str, np.ndarray]: + raw_data = runner.extract_raw_bboxes(frame_paths, detector, vis_dir=None) + cleaned_data = runner.clean_bbox_sequences(raw_data, vis_dir=None) + results = runner.run_hamer_on_cleaned_bboxes( + cleaned_data, + hamer_model, + hamer_config, + None, + SimpleNamespace( + rescale_factor=rescale_factor, + render=False, + res_folder=str(repo / "outputs" / "unused.pkl"), + ), + ) + return _extract_initialization(frame_paths, cleaned_data, results) + + +class _InactiveBMCLoss: + """Avoid loading unavailable BMC assets when all official bio weights are zero.""" + + def __init__(self, *_: Any, **__: Any) -> None: + pass + + def compute_loss(self, *_: Any, **__: Any) -> Any: + raise RuntimeError("BMC loss called although the released bio weight is zero") + + +def _run_optimizer_exact( + optimizer: Any, + observed: dict[str, Any], + iterations: int, +) -> int: + """Run the released outer-loop and early-stop logic without file checkpoints.""" + + optimizer.cur_step = 0 + optimizer.loss.cur_step = 0 + completed = 0 + for iteration in range(iterations): + optimizer.cur_step = iteration + optimizer.loss.cur_step = iteration + optimizer.optim_step(observed, iteration, writer=None) + completed = iteration + 1 + if np.isnan(optimizer.cur_loss): + raise FloatingPointError(f"{optimizer.name} produced NaN") + if optimizer.reached_max and optimizer.reached_max_iter < 0: + optimizer.reached_max_iter = iteration - 1 + if ( + optimizer.reached_max + and iteration - optimizer.reached_max_iter >= optimizer.max_chunk_steps + ): + break + loss_change = optimizer.prev_loss - optimizer.cur_loss + if optimizer.last_updated == iteration - 1 and loss_change == 0: + break + if ( + (optimizer.cur_loss < 0 and loss_change < 100) + or (iteration - optimizer.last_updated >= optimizer.max_chunk_steps) + or (loss_change < 20 and iteration - optimizer.last_updated > 5) + ): + optimizer.add_chunk += 1 + optimizer.last_updated = iteration + optimizer.prev_loss = optimizer.cur_loss + return completed + + +def _optimize_run( + repo: Path, + initialization: dict[str, np.ndarray], + intrinsics: np.ndarray, + device: torch.device, + log_path: Path, +) -> tuple[np.ndarray, np.ndarray, dict[str, int]]: + sys.path.insert(0, str(repo / "dyn-hamr")) + from body_model import MANO + from optim import losses as loss_module + from optim.base_scene import BaseSceneModel + from optim.optimizers import RootOptimizer, SmoothOptimizer + from util.logger import Logger + + active_sides = np.flatnonzero(initialization["recovered"].any(axis=1)) + count = initialization["pose"].shape[1] + output_joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + output_vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + if len(active_sides) == 0: + return output_joints, output_vertices, {"root_iterations": 0, "smooth_iterations": 0} + + loss_module.BMCLoss = _InactiveBMCLoss + config = yaml.safe_load((repo / "dyn-hamr" / "confs" / "optim.yaml").read_text())[ + "optim" + ] + all_weights = config["loss_weights"] + stage_weights = [ + {name: values[stage] for name, values in all_weights.items()} + for stage in range(3) + ] + options = dict(config["options"]) + options["vis_every"] = -1 + options["save_meshes"] = False + + batch = len(active_sides) + mano = MANO( + batch_size=batch * count, + pose2rot=True, + model_path=str(repo / "_DATA" / "data" / "mano"), + gender="neutral", + num_hand_joints=15, + mean_params=str(repo / "_DATA" / "data" / "mano_mean_params.npz"), + create_body_pose=False, + ).to(device) + scene = BaseSceneModel( + batch, + count, + mano, + None, + use_init=True, + opt_cams=False, + opt_scale=False, + async_tracks=True, + ) + observed: dict[str, Any] = { + "joints2d": torch.from_numpy(initialization["keypoints"][active_sides]).to(device), + "init_body_pose": torch.from_numpy(initialization["pose"][active_sides]).to(device), + "init_body_shape": torch.from_numpy(initialization["shape"][active_sides]).to(device), + "init_root_orient": torch.from_numpy(initialization["orient"][active_sides]).to(device), + "init_trans": torch.from_numpy(initialization["translation"][active_sides]).to(device), + "is_right": torch.from_numpy( + np.broadcast_to(active_sides[:, None], (batch, count)).astype(np.float32).copy() + ).to(device), + "vis_mask": torch.from_numpy(initialization["vis_mask"][active_sides]).to(device), + } + cam_data = { + "cam_R": torch.eye(3, device=device)[None].repeat(count, 1, 1), + "cam_t": torch.zeros(count, 3, device=device), + "intrins": torch.from_numpy( + np.stack( + [ + intrinsics[:, 0, 0], + intrinsics[:, 1, 1], + intrinsics[:, 0, 2], + intrinsics[:, 1, 2], + ], + axis=-1, + ).astype(np.float32) + ).to(device), + "static": True, + } + scene.initialize(observed, cam_data) + scene = scene.to(device) + Logger.init(str(log_path)) + + root_optimizer = RootOptimizer(scene, stage_weights, **options) + root_iterations = _run_optimizer_exact( + root_optimizer, observed, int(config["root"]["num_iters"]) + ) + smooth_options = dict(options) + smooth_options["opt_scale"] = bool(config["smooth"]["opt_scale"]) + smooth_optimizer = SmoothOptimizer(scene, stage_weights, **smooth_options) + smooth_iterations = _run_optimizer_exact( + smooth_optimizer, observed, int(config["smooth"]["num_iters"]) + ) + + with torch.inference_mode(): + prediction = scene.pred_params_mano(observed["is_right"]) + predicted_joints = prediction["joints3d"].float().cpu().numpy() + predicted_vertices = prediction["verts3d"].float().cpu().numpy() + for local, side in enumerate(active_sides): + valid = initialization["recovered"][side] + output_joints[valid, side] = predicted_joints[local, valid] + output_vertices[valid, side] = predicted_vertices[local, valid] + del root_optimizer, smooth_optimizer, scene, mano + torch.cuda.empty_cache() + plt.close("all") + return output_joints, output_vertices, { + "root_iterations": root_iterations, + "smooth_iterations": smooth_iterations, + } + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "detector", + "root", + "manifest", + "ground_truth", + "cache_dir", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + args.cache_dir.mkdir(parents=True, exist_ok=True) + args.output.parent.mkdir(parents=True, exist_ok=True) + + enable_legacy_mano_loading() + hamer_root = args.repo / "third-party" / "hamer" + sys.path.insert(0, str(hamer_root)) + sys.path.insert(0, str(args.repo / "dyn-hamr")) + os.chdir(args.repo) + from hamer.models import load_hamer + from ultralytics import YOLO + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + hamer_model, hamer_config = load_hamer(str(args.repo)) + hamer_model = hamer_model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + hamer_runner = _import_hamer_runner(args.repo) + + all_runs = _load_manifest_runs(args.manifest) + if args.run_indices is not None: + if len(set(args.run_indices)) != len(args.run_indices): + raise ValueError("Explicit run indices contain duplicates") + if any(index < 0 or index >= len(all_runs) for index in args.run_indices): + raise ValueError("Explicit run index is outside the manifest") + selected = [all_runs[index] for index in args.run_indices] + else: + selected = [ + run + for run in all_runs + if int(run["global_run_index"]) % args.num_shards == args.shard_index + ] + if args.max_runs is not None: + selected = selected[: args.max_runs] + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + + frame_keys: list[str] = [] + takes: list[str] = [] + frame_ids: list[int] = [] + run_outputs: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]] = [] + total_root_iterations = 0 + total_smooth_iterations = 0 + initialized_runs = 0 + optimized_runs = 0 + initialization_seconds = 0.0 + optimization_seconds = 0.0 + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for selected_index, run in enumerate(selected): + run_index = int(run["global_run_index"]) + take = str(run["take"]) + ids = np.asarray(run["frame_ids"], dtype=np.int64) + keys = np.asarray([frame_key(take, int(value)) for value in ids], dtype=np.str_) + frame_paths = [ + args.root / take / "rgb" / f"{int(value):06d}.png" for value in ids + ] + if not all(path.is_file() for path in frame_paths): + raise FileNotFoundError(f"Missing H2O RGB frame in run {run_index}") + run_dir = args.cache_dir / f"run_{run_index:03d}" + run_dir.mkdir(parents=True, exist_ok=True) + init_path = run_dir / "initialization.npz" + pred_path = run_dir / "prediction.npz" + log_path = run_dir / "optimizer.log" + if init_path.is_file(): + with np.load(init_path, allow_pickle=False) as data: + initialization = {name: data[name].copy() for name in data.files} + else: + if device.type == "cuda": + torch.cuda.synchronize(device) + stage_started = time.perf_counter() + with log_path.open("a", encoding="utf-8") as log, contextlib.redirect_stdout( + log + ), contextlib.redirect_stderr(log): + initialization = _run_official_initialization( + args.repo, + frame_paths, + detector, + hamer_model, + hamer_config, + hamer_runner, + args.rescale_factor, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + initialization_seconds += time.perf_counter() - stage_started + np.savez_compressed(init_path, **initialization) + initialized_runs += 1 + confidence = initialization["confidence"] + recovered = initialization["recovered"] + if pred_path.is_file(): + with np.load(pred_path, allow_pickle=False) as data: + run_joints = data["joints"].copy() + run_vertices = data["vertices"].copy() + iteration_counts = json.loads(str(data["iteration_counts_json"].item())) + else: + indices = np.asarray([gt_index[str(key)] for key in keys], dtype=np.int64) + # The released optimizer prints full pose tensors for every LBFGS + # closure. Logger still records scalar losses in optimizer.log. + if device.type == "cuda": + torch.cuda.synchronize(device) + stage_started = time.perf_counter() + with Path(os.devnull).open("w") as sink, contextlib.redirect_stdout( + sink + ), contextlib.redirect_stderr(sink): + run_joints, run_vertices, iteration_counts = _optimize_run( + args.repo, + initialization, + ground_truth.intrinsics[indices], + device, + log_path, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + optimization_seconds += time.perf_counter() - stage_started + np.savez_compressed( + pred_path, + joints=run_joints, + vertices=run_vertices, + iteration_counts_json=np.asarray(json.dumps(iteration_counts)), + ) + optimized_runs += 1 + total_root_iterations += int(iteration_counts["root_iterations"]) + total_smooth_iterations += int(iteration_counts["smooth_iterations"]) + frame_keys.extend(keys.tolist()) + takes.extend([take] * len(ids)) + frame_ids.extend(ids.tolist()) + run_outputs.append((run_joints, run_vertices, recovered.T, confidence.T)) + print( + f"Dyn-HaMR run {selected_index + 1}/{len(selected)} " + f"global={run_index} frames={len(ids)} " + f"iters={iteration_counts['root_iterations']}/{iteration_counts['smooth_iterations']}", + flush=True, + ) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "Dyn-HaMR", + "scope": "RGB detector/HaMeR initialization + per-run Root/Smooth test-time optimization", + "frames": int(sum(len(run["frame_ids"]) for run in selected)), + "runs": len(selected), + "processing_seconds": processing_seconds, + "frames_per_second": int(sum(len(run["frame_ids"]) for run in selected)) / processing_seconds, + "initialization_seconds": initialization_seconds, + "optimization_seconds": optimization_seconds, + "cache_and_host_overhead_seconds": processing_seconds - initialization_seconds - optimization_seconds, + "root_iterations": total_root_iterations, + "smooth_iterations": total_smooth_iterations, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + joints = np.concatenate([value[0] for value in run_outputs], axis=0) + vertices = np.concatenate([value[1] for value in run_outputs], axis=0) + detected = np.concatenate([value[2] for value in run_outputs], axis=0) + confidence = np.concatenate([value[3] for value in run_outputs], axis=0) + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + hamer_commit = subprocess.check_output( + ["git", "-C", str(hamer_root), "rev-parse", "HEAD"], text=True + ).strip() + hamer_checkpoint = args.repo / "_DATA" / "hamer_ckpts" / "checkpoints" / "hamer.ckpt" + reconstruction_parameters = sum( + parameter.numel() for parameter in hamer_model.parameters() + ) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/ZhengdiYu/Dyn-HaMR", + "repository_commit": commit, + "hamer_repository_commit": hamer_commit, + "hamer_checkpoint": str(hamer_checkpoint), + "hamer_checkpoint_sha256": sha256(hamer_checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": ( + "full RGB video, released enhanced YOLO/HaMeR tracker, known static H2O cam4 K, " + "per-contiguous-run Root and Smooth test-time optimization" + ), + "training_exposure": ( + "Dyn-HaMR is test-time optimization; released HaMeR initializer training includes " + "H2O3D but not H2O; no H2O fine-tuning" + ), + "fine_tuning": "not applicable: adaptation is per-video test-time optimization", + "camera_policy": "known static H2O cam4 extrinsics/intrinsics; no SLAM or GT pose", + "optimizer_config": str(args.repo / "dyn-hamr" / "confs" / "optim.yaml"), + "optimizer_config_sha256": sha256(args.repo / "dyn-hamr" / "confs" / "optim.yaml"), + "root_iterations_total": total_root_iterations, + "smooth_iterations_total": total_smooth_iterations, + "run_count": len(selected), + "new_initializations": initialized_runs, + "new_optimizations": optimized_runs, + "rescale_factor": args.rescale_factor, + "detector_confidence_threshold": 0.5, + "temporal": True, + "temporal_protocol": "each official validation manifest run optimized independently", + "optional_hmp_prior_used": False, + "inactive_bmc_asset_policy": ( + "BMC object initialization skipped because released bio weights are zero in all stages" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + "explicit_run_indices": args.run_indices, + } + bundle = PredictionBundle( + model_name="Dyn-HaMR-zero-shot-TTO", + frame_keys=np.asarray(frame_keys, dtype=np.str_), + takes=np.asarray(takes, dtype=np.str_), + frame_ids=np.asarray(frame_ids, dtype=np.int64), + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_foundation_hand_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_foundation_hand_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..52771dd5f05a9772cec1488dad3789b731bb9065 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_foundation_hand_h2o.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Export the promoted Phase 3 model into the common SOTA prediction schema.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.evaluation.sota import PredictionBundle, frame_key, load_frame_index +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training.checkpoint import load_checkpoint + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--max-clips", type=int) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + data_config, assets = config["data"], config["assets"] + keys, takes, frame_ids = load_frame_index(args.manifest) + key_to_index = {str(key): index for index, key in enumerate(keys)} + count = len(keys) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + + dataset = H2OCam4Dataset( + args.root, + args.manifest, + tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), + (int(data_config["stride"]),), + max_clips=args.max_clips, + ) + loader = DataLoader( + dataset, + batch_size=1, + shuffle=False, + num_workers=args.num_workers, + persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, + pin_memory=True, + ) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).eval() + checkpoint_state = load_checkpoint( + args.checkpoint, model, optimizer=None, map_location=device + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + + exported = 0 + processed_clips = 0 + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + with torch.inference_mode(): + for clip_index, batch_cpu in enumerate(loader): + batch = { + name: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for name, value in batch_cpu.items() + } + with torch.autocast("cuda", dtype=dtype): + output = model(batch) + valid_length = int(batch["frame_valid"][0].sum()) + output_joints = output["joints_camera"][0, :valid_length].float().cpu().numpy() + output_vertices = output["vertices_camera"][0, :valid_length].float().cpu().numpy() + for time_index in range(valid_length): + take = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/cam4" + frame_id_value = int(batch["frame_id"][0, time_index]) + index = key_to_index[frame_key(take, frame_id_value)] + joints[index] = output_joints[time_index] + vertices[index] = output_vertices[time_index] + detected[index] = True + exported += 1 + processed_clips = clip_index + 1 + if (clip_index + 1) % 100 == 0 or clip_index + 1 == len(loader): + print(f"FoundationHand clips {clip_index + 1}/{len(loader)}", flush=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + processed_frames = int(detected.all(axis=1).sum()) + if args.timing_output is not None: + timing_output = args.timing_output.resolve() + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "FoundationHand-Phase3", + "scope": "RGB+Depth+K decode/preprocessing + BF16 T=8 model forward + host result transfer", + "frames": processed_frames, + "clips": processed_clips, + "processing_seconds": processing_seconds, + "frames_per_second": processed_frames / processing_seconds, + "clips_per_second": processed_clips / processing_seconds, + "amortized_ms_per_frame": 1000.0 * processing_seconds / processed_frames, + "clip_length": int(data_config["T"]), + "resolution_hw": data_config["resolution_hw"], + "batch_size_clips": 1, + "num_workers": args.num_workers, + "precision": config["precision"], + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + if args.max_clips is not None: + processed = detected.all(axis=1) + keys, takes, frame_ids = keys[processed], takes[processed], frame_ids[processed] + joints, vertices = joints[processed], vertices[processed] + detected, confidence = detected[processed], confidence[processed] + elif exported != count: + raise RuntimeError(f"Expected {count} exported frames, observed {exported}") + + repository_commit = subprocess.check_output( + ["git", "rev-parse", "HEAD"], text=True + ).strip() + parameter_count = sum(parameter.numel() for parameter in model.parameters()) + trainable_parameter_count = sum( + parameter.numel() for parameter in model.parameters() if parameter.requires_grad + ) + bundle = PredictionBundle( + model_name="FoundationHand-Phase3", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata={ + "repository_commit_at_export": repository_commit, + "training_commit": "d4019222835132fcbcc850ba49e6e0b53ab352b3", + "checkpoint": str(args.checkpoint.resolve()), + "checkpoint_sha256": sha256(args.checkpoint), + "checkpoint_step": int(checkpoint_state["step"]), + "parameter_count": parameter_count, + "trainable_parameter_count_at_export": trainable_parameter_count, + "input": "full RGB + aligned metric Depth + H2O K, T=8", + "temporal": True, + "temporal_window": int(data_config["T"]), + "detector": False, + "fixed_semantic_slots": True, + "official_test_used": False, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_hamba_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_hamba_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..80aca96be62d8cdd4d3d9c34afa69fc86f906300 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_hamba_h2o.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Run the released Hamba checkpoint on H2O with a common hand detector.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, load_frame_index +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--preprocess-repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--checkpoint-sha256") + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=8) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "preprocess_repo", + "checkpoint", + "config", + "detector", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + if args.checkpoint_sha256 is not None and ( + len(args.checkpoint_sha256) != 64 + or any(character not in "0123456789abcdef" for character in args.checkpoint_sha256) + ): + raise ValueError("--checkpoint-sha256 must be 64 lowercase hexadecimal characters") + + sys.path.insert(0, str(args.preprocess_repo)) + sys.path.insert(0, str(args.repo)) + enable_legacy_mano_loading() + os.chdir(args.repo) + + from hamba.configs import get_config + from hamba.models import HAMBA + from ultralytics import YOLO + from wilor.datasets.vitdet_dataset import ViTDetDataset + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + config = get_config(str(args.config), update_cachedir=True) + config.defrost() + config.MODEL.BBOX_SHAPE = [192, 256] + config.MODEL.BACKBONE.pop("PRETRAINED_WEIGHTS", None) + config.MODEL.pop("PRETRAINED_WEIGHTS_INIT_REGRESSION", None) + config.freeze() + if not config.MODEL.USE_INIT_REGRESSION: + raise ValueError("This adapter requires the released initial-regressor configuration") + model = HAMBA(config, init_renderer=False) + checkpoint = torch.load( + args.checkpoint, + map_location="cpu", + weights_only=False, + mmap=True, + ) + model.load_state_dict(checkpoint["state_dict"], strict=True) + del checkpoint + model = model.to(device).eval() + + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch["keypoints_2d"] = torch.zeros((batch_size, 21, 3), dtype=torch.float32) + batch["is_valid"] = torch.ones(batch_size, dtype=torch.int64) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + record_indices = np.asarray([record[0] for record in records]) + intrinsic = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (intrinsic[:, 0, 0] + intrinsic[:, 1, 1]) + principal = intrinsic[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + camera = torch.stack(( + pred_cam[:, 1] + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), dim=-1).float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + batch_joints += camera[:, None] + batch_vertices += camera[:, None] + for local, (frame_index, side, score, _) in enumerate(records): + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + dataset = ViTDetDataset( + config, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"Hamba detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + kernel_path = Path(sys.modules["selective_scan_cuda_oflex"].__file__).resolve() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/humansensinglab/Hamba", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": args.checkpoint_sha256 or sha256(args.checkpoint), + "config": str(args.config), + "config_sha256": sha256(args.config), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector hand boxes, per-hand crops", + "training_exposure": "zero-shot H2O; release config includes H2O3D but not H2O", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "camera_policy": "cam_crop_to_full algebra with known H2O focal/principal point", + "preprocessing": "official HaMeR-compatible crop geometry shared with WiLoR", + "joint_source": "released Hamba initial regressor; no GT or external 2D joints", + "test_time_augmentation": False, + "selective_scan_kernel": str(kernel_path), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="Hamba-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_handdgp_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_handdgp_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..6a22aa27e858db7aa398de80e9399957e95d783b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_handdgp_h2o.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Run the released FreiHAND HandDGP checkpoint zero-shot on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any + +import cv2 +import kornia +import numpy as np +import torch + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + load_frame_index, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=32) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--crop-scale", type=float, default=1.3) + parser.add_argument("--input-size", type=int, default=224) + parser.add_argument("--canonical-focal", type=float, default=1000.0) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def _prepare_crop( + image_rgb: np.ndarray, + box_xyxy: np.ndarray, + intrinsic: np.ndarray, + *, + is_left: bool, + input_size: int, + crop_scale: float, + canonical_focal: float, + generate_patch_image: Any, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Apply the released square crop and canonical-intrinsics rectification.""" + + image = image_rgb + box = np.asarray(box_xyxy, dtype=np.float32).copy() + K = np.asarray(intrinsic, dtype=np.float32).copy() + if is_left: + width = image.shape[1] + image = np.ascontiguousarray(image[:, ::-1]) + box[[0, 2]] = (width - 1) - box[[2, 0]] + K[0, 2] = (width - 1) - K[0, 2] + + width = float(box[2] - box[0]) + height = float(box[3] - box[1]) + side = max(width, height) + center = np.asarray( + [(box[0] + box[2]) * 0.5, (box[1] + box[3]) * 0.5], + dtype=np.float32, + ) + square_box = ( + float(center[0] - 0.5 * side), + float(center[1] - 0.5 * side), + side, + side, + ) + crop, _, _, _, _ = generate_patch_image( + cvimg=image, + bbox=square_box, + scale=crop_scale, + rot=0.0, + shift=(0.0, 0.0), + do_flip=False, + out_shape=(input_size, input_size), + shift_wh=None, + mask=None, + ) + crop_tensor = torch.from_numpy(np.ascontiguousarray(crop)).float() + crop_tensor = crop_tensor.permute(2, 0, 1) / 255.0 + + # FreiHAND hands are centered close to the optical axis. For arbitrary + # detector crops, use the equivalent box-centered virtual camera and map + # its ray back to the raw H2O camera after inference. + focal_scaled = K[[0, 1], [0, 1]] * input_size / (side * crop_scale) + crop_intrinsic = np.asarray( + [ + [focal_scaled[0], 0.0, input_size * 0.5], + [0.0, focal_scaled[1], input_size * 0.5], + [0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + canonical_intrinsic = np.asarray( + [ + [canonical_focal, 0.0, input_size * 0.5], + [0.0, canonical_focal, input_size * 0.5], + [0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + rectification = torch.from_numpy( + canonical_intrinsic @ np.linalg.inv(crop_intrinsic) + ) + crop_tensor = kornia.geometry.transform.warp_affine( + crop_tensor.unsqueeze(0), + rectification[:2, :3].unsqueeze(0), + dsize=(input_size, input_size), + mode="bilinear", + padding_mode="zeros", + align_corners=True, + ).squeeze(0) + ray_offset = (center - K[:2, 2]) / K[[0, 1], [0, 1]] + return ( + crop_tensor, + torch.from_numpy(canonical_intrinsic), + torch.from_numpy(ray_offset.astype(np.float32)), + ) + + +def main() -> None: + args = parse_args() + for name in ( + "repo", + "checkpoint", + "detector", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from src.models.handdgp import HandDGP + from third_party.HandMesh.utils.preprocessing import generate_patch_image + from ultralytics import YOLO + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], + takes[: args.max_frames], + frame_ids[: args.max_frames], + ) + count = len(keys) + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack( + [ground_truth.intrinsics[gt_index[str(key)]] for key in keys] + ) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + model = HandDGP( + batch_size=args.reconstruction_batch_size, + imagenet_pretrain=False, + input_size=args.input_size, + ) + checkpoint = torch.load( + args.checkpoint, + map_location="cpu", + weights_only=False, + mmap=True, + ) + state_dict = { + name.removeprefix("model."): value + for name, value in checkpoint["state_dict"].items() + } + model.load_state_dict(state_dict, strict=True) + del checkpoint, state_dict + model = model.to(device).eval() + + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + queue: list[ + tuple[int, int, float, torch.Tensor, torch.Tensor, torch.Tensor] + ] = [] + + def flush_queue(force: bool = False) -> None: + while len(queue) >= args.reconstruction_batch_size or (force and queue): + batch_size = min(args.reconstruction_batch_size, len(queue)) + records = queue[:batch_size] + del queue[:batch_size] + images = torch.stack([record[3] for record in records]).to(device) + camera = torch.stack([record[4] for record in records]).to(device) + with torch.inference_mode(): + output = model(images, camera, hand_scale=0.2) + batch_joints = output["keypoints3D_cs"].float().cpu().numpy() + batch_vertices = output["mesh_vertices3D_cs"].float().cpu().numpy() + ray_offsets = torch.stack([record[5] for record in records]).numpy() + batch_joints[..., :2] += ( + ray_offsets[:, None] * batch_joints[..., 2:3] + ) + batch_vertices[..., :2] += ( + ray_offsets[:, None] * batch_vertices[..., 2:3] + ) + for local, (frame_index, side, score, _, _, _) in enumerate(records): + if side == 0: + batch_joints[local, :, 0] *= -1.0 + batch_vertices[local, :, 0] *= -1.0 + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images_bgr = [ + cv2.imread( + str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png") + ) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images_bgr): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images_bgr, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + image_rgb = cv2.cvtColor(images_bgr[local], cv2.COLOR_BGR2RGB) + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop, crop_intrinsic, ray_offset = _prepare_crop( + image_rgb, + boxes[choice], + intrinsics[frame_index], + is_left=side == 0, + input_size=args.input_size, + crop_scale=args.crop_scale, + canonical_focal=args.canonical_focal, + generate_patch_image=generate_patch_image, + ) + queue.append( + ( + frame_index, + side, + float(scores[choice]), + crop, + crop_intrinsic, + ray_offset, + ) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"HandDGP detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + handmesh_commit = subprocess.check_output( + [ + "git", + "-C", + str((args.repo / "third_party" / "HandMesh").resolve()), + "rev-parse", + "HEAD", + ], + text=True, + ).strip() + # Decoder upsampling matrices are fixed and repeated along the configured + # batch dimension. Count one copy so the reported model size is invariant + # to inference batch size. + reconstruction_parameters = sum( + parameter[0].numel() + if name.startswith("decoder3d.up_transform.") + else parameter.numel() + for name, parameter in model.named_parameters() + ) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/nianticlabs/HandDGP", + "repository_commit": commit, + "handmesh_repository_commit": handmesh_commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector boxes, per-hand crops", + "training_exposure": "released checkpoint trained only on FreiHAND; no H2O or H2O3D", + "fine_tuning": "not available: official repository contains inference/evaluation only", + "confidence_threshold": args.confidence_threshold, + "crop_scale": args.crop_scale, + "input_size": args.input_size, + "canonical_focal": args.canonical_focal, + "preprocessing": ( + "official square crop and canonical-intrinsics rectification; " + "left hands reflected before the right-hand model and mapped back in camera x" + ), + "camera_policy": ( + "official DGP in a box-centered virtual crop camera; known H2O K " + "maps the crop ray back to raw cam4" + ), + "joint_conversion": "official MPII output already matches H2O/OpenPose convention", + "hand_scale_m": 0.2, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="HandDGP-FreiHAND-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_hawor_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_hawor_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..d65afad091f550bdebc7783b6a1acebccb125a46 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_hawor_h2o.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Run HaWoR's official tracked camera-space hand stage on H2O validation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-left", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--confidence-threshold", type=float, default=0.2) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def contiguous_runs(takes: np.ndarray, frame_ids: np.ndarray) -> list[np.ndarray]: + starts = [0] + for index in range(1, len(frame_ids)): + if takes[index] != takes[index - 1] or frame_ids[index] != frame_ids[index - 1] + 1: + starts.append(index) + starts.append(len(frame_ids)) + return [np.arange(starts[i], starts[i + 1]) for i in range(len(starts) - 1)] + + +def main() -> None: + args = parse_args() + for name in ( + "repo", "checkpoint", "detector", "mano_left", "mano_right", "root", + "manifest", "ground_truth", "output", + ): + setattr(args, name, Path(getattr(args, name)).resolve()) + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + targets = ( + (args.repo / "_DATA" / "data" / "mano" / "MANO_RIGHT.pkl", args.mano_right), + (args.repo / "_DATA" / "data_left" / "mano_left" / "MANO_LEFT.pkl", args.mano_left), + ) + for target, source in targets: + if not target.exists(): + target.symlink_to(source) + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from ultralytics import YOLO + from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + from hawor.utils.process import run_mano, run_mano_left + from hawor.configs import get_config + from hawor.utils.rotation import rotation_matrix_to_angle_axis + from lib.models.hawor import HAWOR + + from foundation_hand.evaluation.sota import GroundTruthBundle + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + all_runs = contiguous_runs(takes, frame_ids) + selected_runs = [ + run for index, run in enumerate(all_runs) + if index % args.num_shards == args.shard_index + ] + selected_mask = np.zeros(count, dtype=bool) + for run in selected_runs: + selected_mask[run] = True + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + enable_legacy_mano_loading() + model_config = args.checkpoint.parent.parent / "model_config.yaml" + config = get_config(str(model_config), update_cachedir=True) + if config.MODEL.BACKBONE.TYPE == "vit" and "BBOX_SHAPE" not in config.MODEL: + config.defrost() + config.MODEL.BBOX_SHAPE = [192, 256] + config.freeze() + model = HAWOR.load_from_checkpoint( + str(args.checkpoint), + strict=False, + cfg=config, + map_location=device, + weights_only=False, + ) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + boxes = np.full((count, 2, 4), np.nan, dtype=np.float32) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for run_number, run_indices in enumerate(selected_runs, start=1): + if getattr(detector, "predictor", None) is not None: + for tracker in getattr(detector.predictor, "trackers", []): + if hasattr(tracker, "reset"): + tracker.reset() + image_paths = [ + args.root / str(takes[index]) / "rgb" / f"{int(frame_ids[index]):06d}.png" + for index in run_indices + ] + for local, image_path in enumerate(image_paths): + image = cv2.imread(str(image_path)) + if image is None: + raise RuntimeError(f"Image decode failure: {image_path}") + with torch.no_grad(): + result = detector.track( + image, + conf=args.confidence_threshold, + persist=True, + verbose=False, + )[0] + result_boxes = result.boxes.xyxy.float().cpu().numpy() + result_classes = result.boxes.cls.long().cpu().numpy() + result_scores = result.boxes.conf.float().cpu().numpy() + frame_index = int(run_indices[local]) + for side in (0, 1): + choices = np.flatnonzero(result_classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(result_scores[choices])]) + boxes[frame_index, side] = result_boxes[choice] + confidence[frame_index, side] = result_scores[choice] + + for side in (0, 1): + available = run_indices[np.isfinite(boxes[run_indices, side]).all(axis=1)] + # The released video pipeline requires two detections, then linearly + # interpolates missing boxes between the first and last detection. + if available.size < 2: + continue + segment = np.arange(int(available[0]), int(available[-1]) + 1) + for coordinate in range(4): + boxes[segment, side, coordinate] = np.interp( + frame_ids[segment], + frame_ids[available], + boxes[available, side, coordinate], + ) + segment_paths = np.asarray([ + str(args.root / str(takes[index]) / "rgb" / f"{int(frame_ids[index]):06d}.png") + for index in segment + ]) + K = intrinsics[int(segment[0])] + focal = float(0.5 * (K[0, 0] + K[1, 1])) + center = np.asarray([K[0, 2], K[1, 2]], dtype=np.float32) + results = model.inference( + segment_paths, + boxes[segment, side], + img_focal=focal, + img_center=center, + device=str(device), + do_flip=(side == 0), + ) + root_rotation = rotation_matrix_to_angle_axis( + results["pred_rotmat"][None, :, 0] + ) + hand_pose = rotation_matrix_to_angle_axis( + results["pred_rotmat"][None, :, 1:] + ) + if side == 0: + root_rotation[..., 1:] *= -1 + hand_pose[..., 1:] *= -1 + # Keep the exact official left/right MANO conversion after canonical + # left-hand input flipping. + if side == 0: + mano_output = run_mano_left( + results["pred_trans"][None, :, 0], + root_rotation, + hand_pose, + betas=results["pred_shape"][None], + ) + else: + mano_output = run_mano( + results["pred_trans"][None, :, 0], + root_rotation, + hand_pose, + betas=results["pred_shape"][None], + ) + joints[segment, side] = mano_output["joints"][0].float().cpu().numpy() + vertices[segment, side] = mano_output["vertices"][0].float().cpu().numpy() + detected[segment, side] = True + print( + f"HaWoR run {run_number}: frames through {int(run_indices[-1]) + 1}/{count}", + flush=True, + ) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + selected_frames = int(selected_mask.sum()) + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "HaWoR", + "scope": "RGB decode + tracked detector + bbox interpolation + temporal reconstruction + MANO conversion", + "frames": selected_frames, + "detected_hand_frames": int(detected[selected_mask].sum()), + "processing_seconds": processing_seconds, + "frames_per_second": selected_frames / processing_seconds, + "temporal_window": 16, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + keys = keys[selected_mask] + takes = takes[selected_mask] + frame_ids = frame_ids[selected_mask] + joints = joints[selected_mask] + vertices = vertices[selected_mask] + detected = detected[selected_mask] + confidence = confidence[selected_mask] + bundle = PredictionBundle( + model_name="HaWoR-camera", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata={ + "official_repository": "https://github.com/ThunderVVV/HaWoR", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "tracked per-hand RGB crops in contiguous 16-frame windows", + "confidence_threshold": args.confidence_threshold, + "temporal": True, + "temporal_window": 16, + "side_assignment": "official tracked detector handedness; highest confidence per side/frame", + "bbox_gap_policy": "official linear interpolation between first/last per-run detections", + "camera_conversion": "official get_trans with H2O fx/fy mean and principal point", + "excluded_for_camera_metrics": ["DROID-SLAM", "Metric3D", "world-space infiller"], + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_pad_hand_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_pad_hand_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..5fb890442b99e6018c5aa3ca6ca6c2cc4d695ed5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_pad_hand_h2o.py @@ -0,0 +1,501 @@ +#!/usr/bin/env python3 +"""Run the released PAD-Hand WiLoR refinement pipeline on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import types +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import ( + GroundTruthBundle, + PredictionBundle, + load_frame_index, +) +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + + +MANO_TO_OPENPOSE = np.asarray( + [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20], + dtype=np.int64, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def install_torch_scatter_compat() -> None: + """Provide the single torch-scatter operation used by the released model.""" + + if "torch_scatter" in sys.modules: + return + + def scatter_add( + source: torch.Tensor, + index: torch.Tensor, + dim: int = -1, + out: torch.Tensor | None = None, + dim_size: int | None = None, + ) -> torch.Tensor: + if out is None: + output_shape = list(source.shape) + output_shape[dim] = ( + dim_size if dim_size is not None else int(index.max().item()) + 1 + ) + out = source.new_zeros(output_shape) + index_shape = [1] * source.ndim + index_shape[dim] = index.numel() + expanded_index = index.reshape(index_shape).expand_as(source) + return out.scatter_add_(dim, expanded_index, source) + + module = types.ModuleType("torch_scatter") + module.scatter_add = scatter_add + sys.modules["torch_scatter"] = module + + +def enable_legacy_checkpoint_loading() -> None: + """Restore the pre-PyTorch-2.6 default for trusted official checkpoints.""" + + original_load = torch.load + + def load(*args: Any, **kwargs: Any) -> Any: + kwargs.setdefault("weights_only", False) + return original_load(*args, **kwargs) + + torch.load = load + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--pad-repo", type=Path, required=True) + parser.add_argument("--wilor-repo", type=Path, required=True) + parser.add_argument("--pad-checkpoint", type=Path, required=True) + parser.add_argument("--wilor-checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument("--diffusion-steps", type=int, default=4) + parser.add_argument("--kappa-degrees", type=float, default=15.0) + parser.add_argument("--seed", type=int, default=20260720) + parser.add_argument("--max-takes", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def stable_window_seed(base_seed: int, take: str, side: int, frame_id: int) -> int: + payload = f"{base_seed}|{take}|{side}|{frame_id}".encode("utf-8") + return int.from_bytes(hashlib.sha256(payload).digest()[:8], "little") % (2**31) + + +def contiguous_runs(frame_ids: np.ndarray) -> list[np.ndarray]: + if frame_ids.size == 0: + return [] + boundaries = np.flatnonzero(np.diff(frame_ids) != 1) + 1 + return [part for part in np.split(np.arange(frame_ids.size), boundaries) if part.size] + + +def main() -> None: + args = parse_args() + for name in ( + "pad_repo", + "wilor_repo", + "pad_checkpoint", + "wilor_checkpoint", + "detector", + "mano_right", + "root", + "manifest", + "ground_truth", + "output", + ): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + if args.diffusion_steps <= 0: + raise ValueError("--diffusion-steps must be positive") + + required_pad_assets = ( + "processed_MANO_RIGHT.pkl", + "MeshConv_template.ply", + "MeshConv_transform.pkl", + ) + for filename in required_pad_assets: + asset = args.pad_repo / "assets" / filename + if not asset.is_file(): + raise FileNotFoundError(f"Missing released PAD-Hand asset: {asset}") + wilor_mano = args.wilor_repo / "mano_data" / "MANO_RIGHT.pkl" + if not wilor_mano.exists(): + wilor_mano.symlink_to(args.mano_right) + + keys, takes, frame_ids = load_frame_index(args.manifest) + unique_takes = list(dict.fromkeys(map(str, takes.tolist()))) + if args.max_takes is not None: + unique_takes = unique_takes[: args.max_takes] + selected_takes = { + take + for index, take in enumerate(unique_takes) + if index % args.num_shards == args.shard_index + } + selected = np.asarray([str(take) in selected_takes for take in takes], dtype=bool) + keys, takes, frame_ids = keys[selected], takes[selected], frame_ids[selected] + if not len(keys): + raise ValueError("Shard contains no frames") + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + enable_legacy_mano_loading() + enable_legacy_checkpoint_loading() + sys.path.insert(0, str(args.wilor_repo)) + os.chdir(args.wilor_repo) + from ultralytics import YOLO + from wilor.datasets.vitdet_dataset import ViTDetDataset + from wilor.models import load_wilor + + wilor_model, wilor_cfg = load_wilor( + checkpoint_path=str(args.wilor_checkpoint), + cfg_path=str(args.wilor_repo / "pretrained_models" / "model_config.yaml"), + ) + wilor_model = wilor_model.to(device).eval() + detector = YOLO(str(args.detector)).to(device) + + count = len(keys) + relative_joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + relative_vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + cameras = np.full((count, 2, 3), np.nan, dtype=np.float32) + global_orient = np.full((count, 2, 1, 3, 3), np.nan, dtype=np.float32) + hand_pose = np.full((count, 2, 15, 3, 3), np.nan, dtype=np.float32) + betas = np.full((count, 2, 10), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = wilor_model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + record_indices = np.asarray([record[0] for record in records]) + K = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (K[:, 0, 0] + K[:, 1, 1]) + principal = K[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + camera = torch.stack( + ( + pred_cam[:, 1] + + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), + dim=-1, + ).float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + batch_global = ( + output["pred_mano_params"]["global_orient"].float().cpu().numpy() + ) + batch_pose = output["pred_mano_params"]["hand_pose"].float().cpu().numpy() + batch_betas = output["pred_mano_params"]["betas"].float().cpu().numpy() + for local, (frame_index, side, score, _) in enumerate(records): + relative_joints[frame_index, side] = batch_joints[local] + relative_vertices[frame_index, side] = batch_vertices[local] + cameras[frame_index, side] = camera[local] + global_orient[frame_index, side] = batch_global[local] + hand_pose[frame_index, side] = batch_pose[local] + betas[frame_index, side] = batch_betas[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop_dataset = ViTDetDataset( + wilor_cfg, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), crop_dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"PAD-Hand WiLoR initialization {end}/{count}", flush=True) + flush_queue(force=True) + + install_torch_scatter_compat() + sys.path.insert(0, str(args.pad_repo)) + os.chdir(args.pad_repo) + from models.MANO import MANO + from models.difussionsampler import DiffusionSampler + from models.pad_hand import PAD_Hand + from models.utils import batch_euler2matzxy, rotmat2eulerzxy + + pad_model = PAD_Hand( + device=device, + seqlen=16, + decoder=True, + d_model=512, + nhead=8, + d_hid=512, + nlayers=4, + dropout=0.1, + ).to(device) + checkpoint = torch.load(args.pad_checkpoint, map_location=device, weights_only=False) + pad_model.load_state_dict(checkpoint["model"]) + pad_model.eval() + pad_model.mode = "test" + mano = MANO("RIGHT", device) + sampler = DiffusionSampler( + args.diffusion_steps, np.deg2rad(args.kappa_degrees), device + ) + + refined_joints = relative_joints.copy() + refined_vertices = relative_vertices.copy() + refined_windows = 0 + missing_detection_windows = 0 + tail_frames = 0 + initializer_mesh_delta_sum = 0.0 + initializer_mesh_delta_count = 0 + + for take in dict.fromkeys(map(str, takes.tolist())): + take_indices = np.flatnonzero(takes == take) + order = np.argsort(frame_ids[take_indices]) + take_indices = take_indices[order] + take_frame_ids = frame_ids[take_indices] + for run_positions in contiguous_runs(take_frame_ids): + run_indices = take_indices[run_positions] + tail_frames += len(run_indices) % 16 * 2 + for side in (0, 1): + for window_start in range(0, len(run_indices) - 15, 16): + window = run_indices[window_start : window_start + 16] + if not detected[window, side].all(): + missing_detection_windows += 1 + continue + rotmats = np.concatenate( + (global_orient[window, side], hand_pose[window, side]), axis=1 + ) + rotmats_t = torch.from_numpy(rotmats).to(device) + betas_t = torch.from_numpy(betas[window, side]).to(device) + y0_pose = rotmat2eulerzxy(rotmats_t.reshape(-1, 3, 3)).reshape( + 1, 16, 48 + ) + y0_shape = betas_t.unsqueeze(0) + y0_shape_t = y0_shape.reshape(-1, 10) + y0_rotmat = batch_euler2matzxy(y0_pose.reshape(-1, 3))[0].reshape( + -1, 16, 3, 3 + ) + y0_mano = mano.forward(betas=y0_shape_t, thetas_rotmat=y0_rotmat) + y0_vertices = y0_mano.vertices + comparison_vertices = y0_vertices.detach().cpu().numpy().copy() + if side == 0: + comparison_vertices[..., 0] *= -1 + initializer_mesh_delta_sum += float( + np.linalg.norm( + comparison_vertices - relative_vertices[window, side], axis=-1 + ).sum() + ) + initializer_mesh_delta_count += comparison_vertices.shape[0] * 778 + + src_mask = torch.ones((1, 16), dtype=torch.bool, device=device) + x0_pose_pred = y0_pose.clone() + window_seed = stable_window_seed( + args.seed, take, side, int(frame_ids[window[0]]) + ) + torch.manual_seed(window_seed) + if device.type == "cuda": + torch.cuda.manual_seed_all(window_seed) + with torch.no_grad(): + for step in range(args.diffusion_steps, 0, -1): + if step == args.diffusion_steps: + step_batch = torch.full( + (1,), float(args.diffusion_steps), device=device + ) + noisy_pose = y0_pose + np.deg2rad( + args.kappa_degrees + ) * torch.randn_like(y0_pose) + else: + step_batch = torch.full( + (1,), step, device=device, dtype=torch.long + ) + noisy_pose = sampler.q_sample( + x0_pose_pred, y0_pose - x0_pose_pred, step_batch + ) + noisy_rotmat = batch_euler2matzxy( + noisy_pose.reshape(-1, 3) + )[0].reshape(-1, 16, 3, 3) + noisy_mano = mano.forward( + betas=y0_shape_t, thetas_rotmat=noisy_rotmat + ) + _, decoder_prediction = pad_model.forward( + y0_vertices.reshape(1, 16, 778, 3), + noisy_mano.vertices.reshape(1, 16, 778, 3), + step_batch.float(), + src_mask, + mano, + y0_shape_t, + ) + refined_rotmat = decoder_prediction[-2] + refined_mano = decoder_prediction[-1] + x0_pose_pred = rotmat2eulerzxy( + refined_rotmat.reshape(-1, 3, 3) + ).reshape(1, 16, 48) + vertices_out = refined_mano.vertices.detach().cpu().numpy() + joints_out = refined_mano.joints.detach().cpu().numpy()[ + :, MANO_TO_OPENPOSE + ] + if side == 0: + vertices_out[..., 0] *= -1 + joints_out[..., 0] *= -1 + refined_vertices[window, side] = vertices_out + refined_joints[window, side] = joints_out + refined_windows += 1 + + joints_camera = refined_joints + cameras[:, :, None] + vertices_camera = refined_vertices + cameras[:, :, None] + pad_commit = subprocess.check_output( + ["git", "-C", str(args.pad_repo), "rev-parse", "HEAD"], text=True + ).strip() + wilor_commit = subprocess.check_output( + ["git", "-C", str(args.wilor_repo), "rev-parse", "HEAD"], text=True + ).strip() + wilor_parameters = sum(parameter.numel() for parameter in wilor_model.parameters()) + detector_parameters = sum( + parameter.numel() for parameter in detector.model.parameters() + ) + pad_parameters = sum(parameter.numel() for parameter in pad_model.parameters()) + metadata = { + "official_repository": "https://github.com/DominoAI-Lab/PAD-Hand-CVPR-2026", + "repository_commit": pad_commit, + "base_wilor_repository_commit": wilor_commit, + "checkpoint": str(args.pad_checkpoint), + "checkpoint_sha256": sha256(args.pad_checkpoint), + "base_wilor_checkpoint": str(args.wilor_checkpoint), + "base_wilor_checkpoint_sha256": sha256(args.wilor_checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "pad_parameter_count": pad_parameters, + "reconstruction_parameter_count": wilor_parameters + pad_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": ( + wilor_parameters + pad_parameters + detector_parameters + ), + "input": ( + "full RGB detector, per-detection RGB crop WiLoR initialization, " + "per-side non-overlapping 16-frame PAD-Hand diffusion refinement" + ), + "temporal": True, + "temporal_window": 16, + "diffusion_steps": args.diffusion_steps, + "kappa_degrees": args.kappa_degrees, + "sampling_seed": args.seed, + "sampling_seed_policy": "SHA256(base seed, take, side, first frame)", + "refined_windows": refined_windows, + "missing_detection_windows": missing_detection_windows, + "tail_hand_frames_falling_back_to_wilor": tail_frames, + "initializer_mesh_reconstruction_delta_mm": ( + 1000.0 * initializer_mesh_delta_sum / initializer_mesh_delta_count + if initializer_mesh_delta_count + else None + ), + "camera_policy": "h2o_intrinsics", + "camera_conversion": ( + "WiLoR cam_crop_to_full algebra with known H2O focal/principal point; " + "PAD-Hand does not update camera translation" + ), + "side_assignment": "official WiLoR detector handedness; independent PAD-Hand refinement", + "training_exposure": ( + "paper trains on DexYCB/HO3D; released checkpoint does not label its " + "training split; no H2O fine-tuning" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="PAD-Hand-WiLoR-H2O-K", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints_camera, + vertices_camera_m=vertices_camera, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase3_full_validation.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase3_full_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..fd398945a306fb8176703ee7bb83eb8f92f6d408 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase3_full_validation.py @@ -0,0 +1,373 @@ +#!/usr/bin/env python3 +"""Evaluate every registered Phase 3 core checkpoint on official validation.""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import queue +import shlex +import subprocess +import threading +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +VAL_MANIFEST = Path("artifacts/phase2/data_audit/manifests/official_val.jsonl") + + +@dataclass(frozen=True) +class EvaluationJob: + name: str + run_name: str + role: str + config: Path + checkpoint: Path + output: Path + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + output = {} + for line in result.stdout.splitlines(): + index, uuid = (part.strip() for part in line.split(",", 1)) + output[int(index)] = uuid + return output + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if not line.strip(): + continue + uuid, pid = (part.strip() for part in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +DEFAULT_CHECKPOINT_FILES = { + "step_025k": "step_0025000.pt", + "step_050k": "step_0050000.pt", + "step_075k": "step_0075000.pt", + "step_100k": "step_0100000.pt", + "best_absolute": "best.pt", + "best_z": "best_z.pt", + "final": "step_0100000_final.pt", +} + + +def checkpoint_roles( + run_dir: Path, checkpoint_files: dict[str, str] | None = None, +) -> tuple[tuple[str, Path], ...]: + definitions = DEFAULT_CHECKPOINT_FILES if checkpoint_files is None else checkpoint_files + return tuple((role, run_dir / filename) for role, filename in definitions.items()) + + +def load_checkpoint_files(path: Path | None) -> dict[str, str]: + if path is None: + return dict(DEFAULT_CHECKPOINT_FILES) + values = json.loads(path.read_text(encoding="utf-8")) + if ( + not isinstance(values, dict) + or not values + or any(not isinstance(role, str) or not role for role in values) + or any( + not isinstance(filename, str) or Path(filename).name != filename + for filename in values.values() + ) + ): + raise ValueError("checkpoint spec must be a non-empty role-to-filename JSON object") + return values + + +def validation_state_path(output_root: Path, filename: str) -> Path: + if Path(filename).name != filename or not filename.endswith(".json"): + raise ValueError("state filename must be a JSON basename") + return output_root / filename + + +def build_jobs( + matrix_csv: Path, + run_root: Path, + output_root: Path, + roles: tuple[str, ...] | None = None, + checkpoint_files: dict[str, str] | None = None, +) -> list[EvaluationJob]: + available_roles = checkpoint_roles(Path("unused"), checkpoint_files) + selected_roles = set(roles or (role for role, _ in available_roles)) + with matrix_csv.open(newline="", encoding="utf-8") as handle: + matrix_rows = list(csv.DictReader(handle)) + jobs = [] + for row in matrix_rows: + config = Path(row["config"]) + run_name = row.get("run_name") or config.stem + for role, checkpoint in checkpoint_roles(run_root / run_name, checkpoint_files): + if role not in selected_roles: + continue + jobs.append(EvaluationJob( + name=f"{run_name}__{role}", run_name=run_name, role=role, + config=config, checkpoint=checkpoint, + output=output_root / run_name / role, + )) + return jobs + + +def validate_job_grid(jobs: list[EvaluationJob], roles: tuple[str, ...]) -> int: + """Validate one evaluation per run and selected checkpoint role.""" + if not jobs: + raise ValueError("evaluation matrix produced no jobs") + selected_roles = set(roles) + run_names = {job.run_name for job in jobs} + job_keys = {(job.run_name, job.role) for job in jobs} + expected_jobs = len(run_names) * len(selected_roles) + if len(job_keys) != len(jobs): + raise ValueError("evaluation matrix contains duplicate run/checkpoint-role jobs") + if len(jobs) != expected_jobs: + raise ValueError( + f"expected {len(run_names)} runs x {len(selected_roles)} checkpoint roles " + f"= {expected_jobs} jobs, got {len(jobs)}" + ) + return len(run_names) + + +def command_for( + job: EvaluationJob, gpu: int, num_workers: int, + drop_depth: bool = False, drop_k: bool = False, + phase4_diagnostics: bool = False, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/evaluate_phase3.py", + "--config", str(job.config), + "--root", DATA_ROOT, + "--manifest", str(VAL_MANIFEST), + "--checkpoint", str(job.checkpoint), + "--output-dir", str(job.output), + "--gpu", "0", + "--num-workers", str(num_workers), + "--bootstrap-samples", "10000", + "--skip-visualizations", + ] + if drop_depth: + command.append("--drop-depth") + if drop_k: + command.append("--drop-k") + if phase4_diagnostics: + command.append("--phase4-diagnostics") + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def completed_evaluation(path: Path, job: EvaluationJob) -> bool: + report_path = path / "evaluation.json" + if not report_path.is_file(): + return False + try: + report = json.loads(report_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return False + return ( + report.get("status") == "evaluated" + and report.get("official_test_used") is False + and Path(report.get("checkpoint", {}).get("path", "")).resolve() == job.checkpoint.resolve() + and report.get("clips") == 1495 + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + parser.add_argument("--run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--output-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--gpus", default="0,1,2,3,5") + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument("--roles") + parser.add_argument("--checkpoint-spec", type=Path) + parser.add_argument("--drop-depth", action="store_true") + parser.add_argument("--drop-k", action="store_true") + parser.add_argument("--phase4-diagnostics", action="store_true") + parser.add_argument("--state-filename", default="validation_state.json") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + if VAL_MANIFEST.name != "official_val.jsonl": + parser.error("full validation launcher is hard-gated to official_val.jsonl") + if args.num_workers < 0: + parser.error("--num-workers must be non-negative") + try: + state_path = validation_state_path(args.output_root, args.state_filename) + except ValueError as error: + parser.error(str(error)) + + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + known_gpus = gpu_uuid_map() + unknown = sorted(set(gpus) - set(known_gpus)) + if unknown: + parser.error(f"unknown GPU indices: {unknown}") + + try: + checkpoint_files = load_checkpoint_files(args.checkpoint_spec) + except (OSError, json.JSONDecodeError, ValueError) as error: + parser.error(str(error)) + known_roles = tuple(checkpoint_files) + roles = ( + known_roles if args.roles is None + else tuple(value.strip() for value in args.roles.split(",") if value.strip()) + ) + unknown_roles = sorted(set(roles) - set(known_roles)) + if not roles or unknown_roles: + parser.error(f"invalid --roles; selected={roles}, unknown={unknown_roles}") + jobs = build_jobs( + args.matrix_csv, args.run_root, args.output_root, roles, checkpoint_files, + ) + try: + run_count = validate_job_grid(jobs, roles) + except ValueError as error: + parser.error(str(error)) + missing_configs = sorted({str(job.config) for job in jobs if not job.config.is_file()}) + missing_checkpoints = sorted({str(job.checkpoint) for job in jobs if not job.checkpoint.is_file()}) + if missing_configs or missing_checkpoints: + parser.error(json.dumps({ + "missing_configs": missing_configs, + "missing_checkpoints": missing_checkpoints, + }, indent=2)) + if args.dry_run: + print(json.dumps({ + "runs": run_count, "jobs": len(jobs), "gpus": gpus, "roles": roles, + "official_test_used": False, + "first_command": shlex.join(command_for( + jobs[0], gpus[0], args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + )[0]), + "last_command": shlex.join(command_for( + jobs[-1], gpus[-1], args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + )[0]), + "drop_depth": args.drop_depth, "drop_k": args.drop_k, + "phase4_diagnostics": args.phase4_diagnostics, + "state_file": str(state_path), + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + work: queue.Queue[EvaluationJob] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "manifest": str(VAL_MANIFEST), + "roles": roles, "official_test_used": False, "jobs": {}, + "checkpoint_spec": str(args.checkpoint_spec) if args.checkpoint_spec else None, + "drop_depth": args.drop_depth, "drop_k": args.drop_k, + "phase4_diagnostics": args.phase4_diagnostics, + "state_file": str(state_path), + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for job in jobs: + if completed_evaluation(job.output, job): + state["jobs"][job.name] = { + "status": "skipped_completed", "output": str(job.output), + "checkpoint": str(job.checkpoint), "role": job.role, + } + continue + if job.output.exists() and any(job.output.iterdir()): + state["jobs"][job.name] = { + "status": "blocked_existing_incomplete", "output": str(job.output), + "checkpoint": str(job.checkpoint), "role": job.role, + } + stop_launching.set() + continue + work.put(job) + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + job = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for( + job, gpu, args.num_workers, args.drop_depth, args.drop_k, + args.phase4_diagnostics, + ) + log_path = log_root / f"{job.name}.log" + with state_lock: + state["jobs"][job.name] = { + "status": "running", "run": job.run_name, "role": job.role, + "config": str(job.config), "checkpoint": str(job.checkpoint), + "gpu": gpu, "gpu_uuid": gpu_uuid, "started_utc": utc_now(), + "output": str(job.output), "log": str(log_path), + "command": shlex.join(command), + } + persist() + job.output.mkdir(parents=True, exist_ok=False) + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][job.name]["pid"] = process.pid + persist() + return_code = process.wait() + valid_output = completed_evaluation(job.output, job) + with state_lock: + state["jobs"][job.name].update({ + "status": "completed" if return_code == 0 and valid_output else "failed", + "return_code": return_code, "output_validated": valid_output, + "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0 or not valid_output: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,), name=f"gpu-{gpu}") for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [ + name for name, record in state["jobs"].items() + if record["status"] in {"failed", "blocked_existing_incomplete"} + ] + state["status"] = "failed" if failed else "completed" + state["finished_utc"] = utc_now() + state["failed_jobs"] = failed + state["remaining_queue"] = work.qsize() + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase3_matrix.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase3_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..9e84d3da6831ce5604a00315099bb13709db6c57 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase3_matrix.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Run a pre-registered Phase 3 config queue on explicitly allowed idle GPUs.""" + +from __future__ import annotations + +import argparse +import csv +import json +import os +import queue +import shlex +import subprocess +import threading +import time +from datetime import datetime, timezone +from pathlib import Path + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +TRAIN_MANIFEST = "artifacts/phase2/data_audit/manifests/official_train.jsonl" +VAL_MANIFEST = "artifacts/phase2/data_audit/manifests/official_val.jsonl" +VAL_SUBSET = "artifacts/phase3/validation_subset/validation_subset_256.json" + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + output = {} + for line in result.stdout.splitlines(): + index, uuid = (part.strip() for part in line.split(",", 1)) + output[int(index)] = uuid + return output + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + ["nvidia-smi", "--query-compute-apps=gpu_uuid,pid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if not line.strip(): + continue + uuid, pid = (part.strip() for part in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +def command_for( + config: Path, + output_dir: Path, + gpu: int, + resume: Path | None = None, + validation_subset: Path | str = VAL_SUBSET, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/train_experiment.py", + "--config", str(config), + "--root", DATA_ROOT, + "--manifest", TRAIN_MANIFEST, + "--val-manifest", VAL_MANIFEST, + "--validation-subset-manifest", str(validation_subset), + "--output-dir", str(output_dir), + "--max-steps", "100000", + "--num-workers", "4", + "--checkpoint-interval", "25000", + "--validation-interval", "5000", + "--validation-batches", "256", + "--learning-rate", "5e-5", + "--min-learning-rate", "5e-6", + "--warmup-steps", "500", + "--early-stopping-patience", "0", + ] + if resume is not None: + command.extend(("--resume", str(resume))) + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, default=Path("artifacts/phase3/reports/core_config_matrix.csv")) + parser.add_argument("--output-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--gpus", default="0,1,2,3,5") + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--resume-root", type=Path) + parser.add_argument("--resume-step", type=int, default=75_000) + parser.add_argument( + "--validation-subset-manifest", type=Path, default=Path(VAL_SUBSET), + ) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + known_gpus = gpu_uuid_map() + unknown = sorted(set(gpus) - set(known_gpus)) + if unknown: + parser.error(f"unknown GPU indices: {unknown}") + + with args.matrix_csv.open(newline="", encoding="utf-8") as handle: + configs = [Path(row["config"]) for row in csv.DictReader(handle)] + missing = [str(path) for path in configs if not path.is_file()] + if missing: + parser.error(f"missing configs: {missing}") + jobs = [ + ( + config, + args.output_root / config.stem, + ( + args.resume_root / config.stem / f"step_{args.resume_step:07d}.pt" + if args.resume_root is not None else None + ), + ) + for config in configs + ] + missing_resume = [str(resume) for _, _, resume in jobs if resume and not resume.is_file()] + if missing_resume: + parser.error(f"missing resume checkpoints: {missing_resume}") + if args.dry_run: + print(json.dumps({ + "jobs": len(jobs), "gpus": gpus, + "commands": [ + shlex.join(command_for( + config, output, gpus[index % len(gpus)], resume, + args.validation_subset_manifest, + )[0]) + for index, (config, output, resume) in enumerate(jobs) + ], + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + state_path = args.output_root / "matrix_state.json" + work: queue.Queue[tuple[Path, Path, Path | None]] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "jobs": {}, + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for config, output, resume in jobs: + summary = output / "summary.json" + if summary.is_file() and json.loads(summary.read_text(encoding="utf-8")).get("status") == "completed": + state["jobs"][config.stem] = {"status": "skipped_completed", "output": str(output)} + continue + if output.exists() and any(output.iterdir()): + state["jobs"][config.stem] = { + "status": "blocked_existing_incomplete", "output": str(output), + } + stop_launching.set() + continue + work.put((config, output, resume)) + + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + config, output, resume = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for( + config, output, gpu, resume, args.validation_subset_manifest, + ) + log_path = log_root / f"{config.stem}.log" + with state_lock: + state["jobs"][config.stem] = { + "status": "running", "gpu": gpu, "gpu_uuid": gpu_uuid, + "started_utc": utc_now(), "output": str(output), + "log": str(log_path), "command": shlex.join(command), + "resume_checkpoint": str(resume) if resume is not None else None, + } + persist() + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][config.stem]["pid"] = process.pid + persist() + return_code = process.wait() + with state_lock: + state["jobs"][config.stem].update({ + "status": "completed" if return_code == 0 else "failed", + "return_code": return_code, "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,), name=f"gpu-{gpu}") for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [name for name, record in state["jobs"].items() if record["status"] in {"failed", "blocked_existing_incomplete"}] + state["status"] = "failed" if failed else "completed" + state["finished_utc"] = utc_now() + state["failed_jobs"] = failed + state["remaining_queue"] = work.qsize() + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase4_a3_matrix.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase4_a3_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..277b30257fd62aa997b6837b566ef7af2b34fe65 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase4_a3_matrix.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +"""Run the preregistered Phase 4 A3 formal matrix on explicitly allowed GPUs.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import os +import queue +import shlex +import subprocess +import threading +from datetime import datetime, timezone +from pathlib import Path + +import yaml + + +PYTHON = "/SSD2/jiasen/envs/foundation_hand/bin/python" +DATA_ROOT = "/SSD3/jiasen/foundation_hand/H2O/extracted" +TRAIN_MANIFEST = "artifacts/phase2/data_audit/manifests/official_train.jsonl" +VAL_MANIFEST = "artifacts/phase2/data_audit/manifests/official_val.jsonl" +VAL_SUBSET = ( + "artifacts/phase3/validation_subset/resolution_640x368/" + "validation_subset_256.json" +) +EXPECTED_SEEDS = {20260716, 20260717, 20260718} +MODE_SLUGS = { + "oracle_rgb": "rgb", + "oracle_depth_k": "depth_k", + "oracle_rgb_depth_k": "rgb_depth_k", +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def gpu_uuid_map() -> dict[int, str]: + result = subprocess.run( + ["nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits"], + text=True, stdout=subprocess.PIPE, check=True, + ) + return { + int(index.strip()): uuid.strip() + for line in result.stdout.splitlines() + for index, uuid in [line.split(",", 1)] + } + + +def gpu_compute_pids() -> dict[str, list[int]]: + result = subprocess.run( + [ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid", + "--format=csv,noheader,nounits", + ], + text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + output: dict[str, list[int]] = {} + for line in result.stdout.splitlines(): + if line.strip(): + uuid, pid = (value.strip() for value in line.split(",", 1)) + output.setdefault(uuid, []).append(int(pid)) + return output + + +def load_jobs( + matrix_csv: Path, + config_root: Path, + output_root: Path, +) -> list[dict[str, object]]: + with matrix_csv.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + observed = {(int(row["seed"]), row["mode"]) for row in rows} + expected = {(seed, mode) for seed in EXPECTED_SEEDS for mode in MODE_SLUGS} + if len(rows) != 9 or observed != expected: + raise ValueError("A3 formal matrix must contain exactly three modes x three seeds") + + jobs = [] + for row in rows: + seed = int(row["seed"]) + mode = row["mode"] + if row["stage"] != "formal" or int(row["max_steps"]) != 100_000: + raise ValueError("A3 matrix contains a non-formal or non-100k row") + if row["gt_location"] != "True" or row["official_test_used"] != "False": + raise ValueError("A3 formal matrix violates oracle/test-isolation contract") + config = config_root / Path(row["config"]).name + checkpoint = Path(row["initialization_checkpoint"]) + if not config.is_file() or not checkpoint.is_file(): + raise FileNotFoundError(f"missing A3 config/checkpoint: {config}, {checkpoint}") + if file_sha256(checkpoint) != row["initialization_checkpoint_sha256"]: + raise ValueError(f"initialization checkpoint hash mismatch for seed {seed}") + config_record = yaml.safe_load(config.read_text(encoding="utf-8")) + experiment = config_record.get("experiment", {}) + if ( + int(config_record["seed"]) != seed + or config_record["name"] != row["name"] + or experiment.get("oracle_crop_mode") != mode + or experiment.get("coarse_checkpoint_sha256") + != row["initialization_checkpoint_sha256"] + ): + raise ValueError(f"matrix/config mismatch for {config}") + jobs.append({ + "name": row["name"], + "seed": seed, + "mode": mode, + "config": config, + "checkpoint": checkpoint, + "output": output_root / row["name"], + }) + return jobs + + +def command_for( + job: dict[str, object], gpu: int, validation_subset: Path, +) -> tuple[list[str], dict[str, str]]: + command = [ + PYTHON, "scripts/train_experiment.py", + "--config", str(job["config"]), + "--root", DATA_ROOT, + "--manifest", TRAIN_MANIFEST, + "--val-manifest", VAL_MANIFEST, + "--validation-subset-manifest", str(validation_subset), + "--output-dir", str(job["output"]), + "--max-steps", "100000", + "--num-workers", "4", + "--checkpoint-interval", "25000", + "--validation-interval", "5000", + "--validation-batches", "256", + "--learning-rate", "5e-5", + "--min-learning-rate", "5e-6", + "--lr-schedule-steps", "100000", + "--warmup-steps", "500", + "--early-stopping-patience", "0", + "--init-checkpoint", str(job["checkpoint"]), + ] + environment = os.environ.copy() + environment["CUDA_VISIBLE_DEVICES"] = str(gpu) + environment["PYTHONPATH"] = "src" + return command, environment + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--matrix-csv", type=Path, required=True) + parser.add_argument( + "--config-root", type=Path, default=Path("configs/phase4/a3_oracle_crop"), + ) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--gpus", default="0,1,2,3,4,5") + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--validation-subset-manifest", type=Path, default=Path(VAL_SUBSET), + ) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + gpus = [int(value) for value in args.gpus.split(",") if value.strip()] + if not gpus or len(gpus) != len(set(gpus)): + parser.error("--gpus must contain unique GPU indices") + known_gpus = gpu_uuid_map() + if set(gpus) - set(known_gpus): + parser.error("--gpus contains an unknown GPU index") + if not args.validation_subset_manifest.is_file(): + parser.error("fixed validation subset is missing") + jobs = load_jobs(args.matrix_csv, args.config_root, args.output_root) + if args.dry_run: + print(json.dumps({ + "status": "dry_run", "jobs": len(jobs), "gpus": gpus, + "commands": [ + shlex.join(command_for(job, gpus[index % len(gpus)], args.validation_subset_manifest)[0]) + for index, job in enumerate(jobs) + ], + "official_test_used": False, + }, indent=2)) + return + + args.output_root.mkdir(parents=True, exist_ok=True) + log_root = args.output_root / "_logs" + log_root.mkdir(exist_ok=True) + state_path = args.output_root / "matrix_state.json" + work: queue.Queue[dict[str, object]] = queue.Queue() + state_lock = threading.Lock() + stop_launching = threading.Event() + state: dict[str, object] = { + "status": "running", "started_utc": utc_now(), "gpus": gpus, + "matrix_csv": str(args.matrix_csv), "official_test_used": False, "jobs": {}, + } + + def persist() -> None: + temporary = state_path.with_suffix(".tmp") + temporary.write_text(json.dumps(state, indent=2) + "\n", encoding="utf-8") + temporary.replace(state_path) + + for job in jobs: + output = job["output"] + summary = output / "summary.json" + if summary.is_file() and json.loads(summary.read_text(encoding="utf-8")).get("status") == "completed": + state["jobs"][job["name"]] = { + "status": "skipped_completed", "output": str(output), + } + elif output.exists() and any(output.iterdir()): + state["jobs"][job["name"]] = { + "status": "blocked_existing_incomplete", "output": str(output), + } + stop_launching.set() + else: + work.put(job) + persist() + + def worker(gpu: int) -> None: + gpu_uuid = known_gpus[gpu] + while not stop_launching.is_set(): + try: + job = work.get_nowait() + except queue.Empty: + return + while gpu_compute_pids().get(gpu_uuid): + if stop_launching.wait(args.poll_seconds): + work.task_done() + return + command, environment = command_for(job, gpu, args.validation_subset_manifest) + log_path = log_root / f"{job['name']}.log" + with state_lock: + state["jobs"][job["name"]] = { + "status": "running", "gpu": gpu, "gpu_uuid": gpu_uuid, + "started_utc": utc_now(), "output": str(job["output"]), + "log": str(log_path), "command": shlex.join(command), + } + persist() + with log_path.open("w", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, + ) + with state_lock: + state["jobs"][job["name"]]["pid"] = process.pid + persist() + return_code = process.wait() + with state_lock: + state["jobs"][job["name"]].update({ + "status": "completed" if return_code == 0 else "failed", + "return_code": return_code, "finished_utc": utc_now(), + }) + persist() + work.task_done() + if return_code != 0: + stop_launching.set() + return + + threads = [threading.Thread(target=worker, args=(gpu,)) for gpu in gpus] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + with state_lock: + failed = [ + name for name, record in state["jobs"].items() + if record["status"] in {"failed", "blocked_existing_incomplete"} + ] + state.update({ + "status": "failed" if failed else "completed", + "finished_utc": utc_now(), "failed_jobs": failed, + "remaining_queue": work.qsize(), + }) + persist() + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_adaptation_eval_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_adaptation_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c94ba7f43f0ea64e794d451c852510a306db20e6 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_adaptation_eval_queue.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Evaluate H2O adaptation checkpoints on frozen train-heldout groups.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_split") != "h2o_train_group_heldout_only" + ): + raise ValueError("adaptation evaluation queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("adaptation evaluation queue is empty") + for item in queue["evaluations"]: + if Path(item["cache_manifest"]).name != "train_group_heldout.jsonl": + raise ValueError("adaptation evaluation must use train_group_heldout.jsonl") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_train_group_heldout" + and report.get("evaluation_role") == "h2o_train_group_heldout" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("h2o_training_data_used") is True + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item.get("input_mode", "rgb_d_k"), + "--evaluation-role", "h2o_train_group_heldout", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty adaptation evaluation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_adaptation_forgetting_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_adaptation_forgetting_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa5b7a46bc6f95f83b75eb328abef01a86875a1 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_adaptation_forgetting_queue.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Evaluate H2O-adapted checkpoints on frozen external held-out caches.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_use") is not False + or queue.get("evaluation_split") != "external_heldout_forgetting_diagnostic_only" + ): + raise ValueError("adaptation forgetting queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("adaptation forgetting queue is empty") + for item in queue["evaluations"]: + if "h2o" in str(item["cache_manifest"]).lower(): + raise ValueError("adaptation forgetting queue refuses H2O cache paths") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_adaptation_external_heldout" + and report.get("evaluation_role") == "adaptation_external_heldout" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("h2o_training_data_used") is True + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--evaluation-role", "adaptation_external_heldout", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "selection_use": False, "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty forgetting evaluation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_adaptation_train_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_adaptation_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff2769a01a27e87301e9a37028692b23f43a562 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_adaptation_train_queue.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 7 H2O adaptation stages on idle GPUs 0-3.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_train_queue import ( + atomic_json, + cache_report_ready, + idle_gpu, + sha256, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def stage_marker(item: dict[str, Any]) -> Path: + return Path(item["output_dir"]) / ".phase7_queue" / f"{item['id']}.json" + + +def completed_matches(item: dict[str, Any]) -> bool: + marker_path = stage_marker(item) + if not marker_path.is_file(): + return False + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and int(marker.get("completed_step", -1)) == int(item["stop_after_step"]) + and marker.get("config_sha256") == item["config_sha256"] + and marker.get("h2o_training_data_used") is True + and marker.get("h2o_official_validation_used") is False + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", item["config"], "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(item["stop_after_step"]), + ] + if item.get("resume_checkpoint") is not None: + command.extend(("--resume", item["resume_checkpoint"])) + elif item.get("resume_from_step") is not None: + resume = Path(item["output_dir"]) / f"step_{int(item['resume_from_step']):07d}_final.pt" + command.extend(("--resume", str(resume))) + elif not item.get("neutral_start", False): + command.extend(("--init-checkpoint", item["init_checkpoint"])) + return command + + +def validate_stage_inputs(item: dict[str, Any]) -> None: + config = Path(item["config"]) + if not config.is_file() or sha256(config) != item["config_sha256"]: + raise RuntimeError(f"frozen config missing or SHA mismatch: {config}") + output = Path(item["output_dir"]) + resume_checkpoint = item.get("resume_checkpoint") + resume_step = item.get("resume_from_step") + if resume_checkpoint is not None: + resume = Path(resume_checkpoint) + if ( + not resume.is_file() + or sha256(resume) != item.get("resume_checkpoint_sha256") + ): + raise RuntimeError(f"explicit resume checkpoint is missing or has a SHA mismatch: {resume}") + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"explicit-resume adaptation output is not empty: {output}") + elif resume_step is None and item.get("neutral_start", False): + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new neutral-control output is not empty: {output}") + elif resume_step is None: + initialization = Path(item["init_checkpoint"]) + if ( + not initialization.is_file() + or sha256(initialization) != item["init_checkpoint_sha256"] + ): + raise RuntimeError(f"frozen initialization missing or SHA mismatch: {initialization}") + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new adaptation output is not empty: {output}") + else: + resume = output / f"step_{int(resume_step):07d}_final.pt" + if not resume.is_file(): + raise RuntimeError(f"resume checkpoint is missing: {resume}") + + +def write_stage_marker(item: dict[str, Any], gpu: int) -> dict[str, Any]: + output = Path(item["output_dir"]) + summary = json.loads((output / "summary.json").read_text(encoding="utf-8")) + step = int(item["stop_after_step"]) + checkpoint = output / f"step_{step:07d}_final.pt" + if ( + int(summary.get("completed_step", -1)) != step + or summary.get("h2o_training_data_used") is not True + or summary.get("official_test_used") is not False + or not checkpoint.is_file() + ): + raise RuntimeError(f"adaptation summary failed stage contract: {item['id']}") + marker = { + "status": "complete", "id": item["id"], "completed_utc": utc_now(), + "completed_step": step, "physical_gpu_id": gpu, + "config": str(Path(item["config"]).resolve()), + "config_sha256": item["config_sha256"], + "checkpoint": str(checkpoint.resolve()), "checkpoint_sha256": sha256(checkpoint), + "wall_seconds": summary.get("wall_seconds"), + "gpu_hours": summary.get("gpu_hours"), + "frames_per_second": summary.get("frames_per_second"), + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + marker_path = stage_marker(item) + marker_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(marker_path, marker) + return marker + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("h2o_training_data_used") is not True + ): + parser.error("adaptation queue exposure flags are not explicit and valid") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_caches", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": [0, 1, 2, 3], + "h2o_training_data_used": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + while not all(cache_report_ready(item) for item in queue["required_caches"]): + state["status"] = "waiting_for_caches" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + for index, item in enumerate(queue["stages"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + validate_stage_inputs(item) + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + command = training_command(item, gpu) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0: + marker = write_stage_marker(item, gpu) + state["completed_ids"].append(item["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + break + state["status"] = "failed_non_resource" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["stages"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_external_eval_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_external_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..a41353ff9900a376e42d6fd5e72a03b55d48a27c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_external_eval_queue.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +"""Wait for idle GPU0-3 slots and run a frozen Phase 7 evaluation queue.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def completed_matches(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("official_test_used") is False + and report.get("h2o_training_data_used") is False + and ( + item.get("cache_manifest_sha256") is None + or report.get("cache_manifest", {}).get("sha256") == item["cache_manifest_sha256"] + ) + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], + "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 1000)), + ] + if item.get("cache_manifest_sha256") is not None: + command.extend(( + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + )) + return command + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + # A second observation narrows the race with non-FoundationHand users. + time.sleep(1.0) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if queue.get("official_test_used") is not False: + parser.error("queue must explicitly set official_test_used=false") + items = queue["evaluations"] + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + state["status"] = "running" + for index, item in enumerate(items): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["updated_utc"] = utc_now() + state["waiting_for_idle_gpu"] = True + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + state["waiting_for_idle_gpu"] = False + output_dir = Path(item["output_dir"]) + if output_dir.exists() and any(output_dir.iterdir()): + state["status"] = "failed_existing_output" + state["failure"] = { + "id": item["id"], "reason": f"nonempty output: {output_dir}", + } + atomic_json(args.state, state) + raise SystemExit(1) + command = evaluator_command(item, gpu) + attempt = { + "id": item["id"], "gpu": gpu, "start_utc": utc_now(), + "command": command, + } + state["attempts"].append(attempt) + atomic_json(args.state, state) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + attempt["log"] = str(log_path.resolve()) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + break + tail = log_path.read_text(encoding="utf-8", errors="replace")[-4096:] + if ( + "is not idle" in tail + and (not output_dir.exists() or not any(output_dir.iterdir())) + ): + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_non_resource" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(items) + state["updated_utc"] = utc_now() + state["waiting_for_idle_gpu"] = False + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_external_train_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_external_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..7d97cea3b8039b51ace8f9e31f76e944c5001e83 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_external_train_queue.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 7 external scale stages when caches and GPUs are ready.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def cache_report_ready(item: dict[str, Any]) -> bool: + report_path = Path(item["report"]) + manifest_path = Path(item["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + clip_count = report.get("clips", report.get("cached_clips")) + recorded_manifest = report.get("cache_manifest", {}) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(clip_count or -1) == int(item["expected_clips"]) + and Path(recorded_manifest.get("path", "")).resolve() == manifest_path.resolve() + and recorded_manifest.get("sha256") == sha256(manifest_path) + ) + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1.0) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def stage_marker(item: dict[str, Any]) -> Path: + return Path(item["output_dir"]) / ".phase7_queue" / f"{item['id']}.json" + + +def completed_matches(item: dict[str, Any]) -> bool: + marker_path = stage_marker(item) + if not marker_path.is_file(): + return False + marker = json.loads(marker_path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and int(marker.get("completed_step", -1)) == int(item["stop_after_step"]) + and marker.get("config_sha256") == item["config_sha256"] + and marker.get("h2o_training_data_used") is False + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command(item: dict[str, Any], gpu: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", item["config"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(item["stop_after_step"]), + ] + resume_step = item.get("resume_from_step") + if resume_step is not None: + resume = Path(item["output_dir"]) / f"step_{int(resume_step):07d}_final.pt" + command.extend(("--resume", str(resume))) + if item.get("allow_schedule_tail") is True: + command.append("--allow-schedule-tail") + return command + + +def validate_stage_inputs(item: dict[str, Any]) -> None: + config = Path(item["config"]) + if not config.is_file() or sha256(config) != item["config_sha256"]: + raise RuntimeError(f"frozen config missing or SHA mismatch: {config}") + resume_step = item.get("resume_from_step") + output = Path(item["output_dir"]) + if resume_step is None: + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"new-stage output is not empty: {output}") + else: + resume = output / f"step_{int(resume_step):07d}_final.pt" + if not resume.is_file(): + raise RuntimeError(f"resume checkpoint is missing: {resume}") + expected_resume_sha = item.get("resume_checkpoint_sha256") + if expected_resume_sha is not None and sha256(resume) != expected_resume_sha: + raise RuntimeError(f"resume checkpoint SHA256 mismatch: {resume}") + + +def write_stage_marker(item: dict[str, Any], gpu: int) -> dict[str, Any]: + output = Path(item["output_dir"]) + summary = json.loads((output / "summary.json").read_text(encoding="utf-8")) + step = int(item["stop_after_step"]) + checkpoint = output / f"step_{step:07d}_final.pt" + if ( + int(summary.get("completed_step", -1)) != step + or summary.get("h2o_training_data_used") is not False + or summary.get("official_test_used") is not False + or not checkpoint.is_file() + ): + raise RuntimeError(f"training summary did not satisfy stage contract: {item['id']}") + marker = { + "status": "complete", "id": item["id"], "completed_utc": utc_now(), + "completed_step": step, "physical_gpu_id": gpu, + "config": str(Path(item["config"]).resolve()), + "config_sha256": item["config_sha256"], + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": sha256(checkpoint), + "wall_seconds": summary.get("wall_seconds"), + "gpu_hours": summary.get("gpu_hours"), + "frames_per_second": summary.get("frames_per_second"), + "schedule_tail_enabled": summary.get("schedule_tail_enabled", False), + "schedule_tail_learning_rate": summary.get("schedule_tail_learning_rate"), + "h2o_training_data_used": False, "official_test_used": False, + } + marker_path = stage_marker(item) + marker_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(marker_path, marker) + return marker + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + queue = json.loads(args.queue.read_text(encoding="utf-8")) + if queue.get("official_test_used") is not False: + parser.error("queue must explicitly set official_test_used=false") + if queue.get("h2o_training_data_used") is not False: + parser.error("queue must explicitly set h2o_training_data_used=false") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_caches", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), + "h2o_training_data_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + + while not all(cache_report_ready(item) for item in queue["required_caches"]): + state["status"] = "waiting_for_caches" + state["updated_utc"] = utc_now() + state["ready_caches"] = [ + item["id"] for item in queue["required_caches"] if cache_report_ready(item) + ] + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + for index, item in enumerate(queue["stages"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + try: + validate_stage_inputs(item) + except RuntimeError as error: + state["status"] = "failed_input_contract" + state["failure"] = {"id": item["id"], "reason": str(error)} + atomic_json(args.state, state) + raise SystemExit(str(error)) + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + command = training_command(item, gpu) + log_path = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0: + marker = write_stage_marker(item, gpu) + state["completed_ids"].append(item["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + break + tail = log_path.read_text(encoding="utf-8", errors="replace")[-4096:] + output = Path(item["output_dir"]) + if "is not idle" in tail and (not output.exists() or not any(output.iterdir())): + time.sleep(args.poll_seconds) + continue + state["status"] = "failed_non_resource_or_partial_output" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + + state["status"] = "complete" + state["current_index"] = len(queue["stages"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_h2o_adapted_validation_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_h2o_adapted_validation_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a3d4e4f667ade06aec102d29481ffdde764ac9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_h2o_adapted_validation_queue.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Run a frozen three-mode H2O validation package for an adapted checkpoint.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_training_data_used") is not True + or queue.get("selection_split") != "h2o_train_group_heldout_only" + or queue.get("h2o_official_validation_used_for_selection") is not False + ): + raise ValueError("adapted validation exposure flags are invalid") + items = queue.get("evaluations", []) + if {item.get("input_mode") for item in items} != set(INPUT_MODES) or len(items) != 3: + raise ValueError("adapted validation queue requires exactly three unique input modes") + if len({item.get("checkpoint_sha256") for item in items}) != 1: + raise ValueError("adapted validation modes must use one frozen checkpoint") + if len({item.get("freeze_record") for item in items}) != 1: + raise ValueError("adapted validation modes must use one freeze record") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_adapted_formal" + and report.get("evaluation_role") == "h2o_adapted_formal" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is True + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--freeze-record", item["freeze_record"], "--root", item["root"], + "--manifest", item["manifest"], "--input-mode", item["input_mode"], + "--evaluation-role", "h2o_adapted_formal", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_training_data_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty adapted validation output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_h2o_zero_shot_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_h2o_zero_shot_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9916057aef5704cf28f9a5084d7b3e2bc821cdc0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_h2o_zero_shot_queue.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Run the frozen three-mode strict H2O zero-shot evaluation package.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.evaluate_phase7_h2o_zero_shot import INPUT_MODES +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_training_data_used") is not False + or queue.get("h2o_official_validation_used_for_external_selection") is not False + ): + raise ValueError("strict zero-shot exposure flags are invalid") + items = queue.get("evaluations", []) + if {item.get("input_mode") for item in items} != set(INPUT_MODES) or len(items) != 3: + raise ValueError("strict zero-shot queue requires exactly three unique input modes") + if len({item.get("checkpoint_sha256") for item in items}) != 1: + raise ValueError("strict zero-shot modes must use one frozen checkpoint") + if len({item.get("manifest") for item in items}) != 1: + raise ValueError("strict zero-shot modes must use one frozen validation manifest") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_strict_h2o_zero_shot" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is False + and report.get("h2o_official_validation_used_for_external_selection") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--freeze-record", item["freeze_record"], "--root", item["root"], + "--manifest", item["manifest"], "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "official_test_used": False, "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty zero-shot output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_heldout_cache_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_heldout_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..2163297840a13304a2b53d0503dc025a689c1d1e --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase7_heldout_cache_queue.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Launch formal external held-out caches as their train caches complete.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import shlex +import subprocess +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def dependency_ready(item: dict[str, Any]) -> bool: + report_path = Path(item["dependency"]) + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + count = report.get("clips", report.get("cached_clips", 0)) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(count) >= 10000 + ) + + +def output_complete(item: dict[str, Any]) -> bool: + output = Path(item["output_dir"]) + report_path = output / "cache_report.json" + manifest_path = output / "cache_manifest.jsonl" + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + cache_manifest = report.get("cache_manifest", {}) + expected_recordings = item.get("physical_recordings") + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and int(report.get("clips", report.get("cached_clips", 0))) == 2048 + and report.get("source_manifest", {}).get("sha256") == item["source_manifest_sha256"] + and Path(cache_manifest.get("path", "")).resolve() == manifest_path.resolve() + and cache_manifest.get("sha256") == sha256(manifest_path) + and ( + expected_recordings is None + or int(report.get("recordings", -1)) == int(expected_recordings) + ) + ) + + +def command_tokens(command: str) -> tuple[list[str], dict[str, str]]: + tokens = shlex.split(command) + environment = dict(os.environ) + while tokens and "=" in tokens[0] and not tokens[0].startswith("-"): + key, value = tokens.pop(0).split("=", 1) + if key != "PYTHONPATH": + raise ValueError(f"unexpected command environment assignment: {key}") + environment[key] = str((Path.cwd() / value).resolve()) + if not tokens: + raise ValueError("cache command is empty") + return tokens, environment + + +def process_alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except (ProcessLookupError, PermissionError): + return False + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1.0: + parser.error("--poll-seconds must be at least 1") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False or plan.get("h2o_used") is not False: + parser.error("held-out cache plan must be external-only and non-test") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "waiting_for_train_caches", "plan": str(args.plan.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), "completed_ids": [], + "active": {}, "attempts": [], "official_test_used": False, "h2o_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan") != str(args.plan.resolve()): + parser.error("existing state belongs to a different plan") + state = previous + pending = {item["dataset"]: item for item in plan["sources"]} + processes: dict[str, subprocess.Popen[str]] = {} + while len(state["completed_ids"]) < len(pending): + for dataset, item in pending.items(): + if dataset in state["completed_ids"]: + continue + if output_complete(item): + state["completed_ids"].append(dataset) + state["active"].pop(dataset, None) + atomic_json(args.state, state) + continue + active = state["active"].get(dataset) + if active and process_alive(int(active["pid"])): + continue + if not dependency_ready(item): + continue + output = Path(item["output_dir"]) + command_key = "resume_command" if output.exists() else "start_command" + command, environment = command_tokens(item[command_key]) + log_path = args.state.parent / f"heldout_cache_{dataset.lower()}.log" + attempt = { + "dataset": dataset, "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), "mode": command_key, + } + state["attempts"].append(attempt) + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, + ) + processes[dataset] = process + state["active"][dataset] = {"pid": process.pid, "log": str(log_path.resolve())} + state["status"] = "running" + atomic_json(args.state, state) + finished = [] + for dataset, active in list(state["active"].items()): + process = processes.get(dataset) + if process is not None: + returncode = process.poll() + if returncode is None: + continue + state["active"][dataset]["returncode"] = returncode + processes.pop(dataset) + elif process_alive(int(active["pid"])): + continue + # A completed report is validated on the next loop. A dead process + # without one is retained as a failure rather than silently retried. + item = pending[dataset] + if output_complete(item): + finished.append(dataset) + else: + state["status"] = "failed_incomplete_output" + state["failure"] = {"dataset": dataset, "log": active["log"]} + atomic_json(args.state, state) + raise SystemExit(1) + for dataset in finished: + if dataset not in state["completed_ids"]: + state["completed_ids"].append(dataset) + state["active"].pop(dataset, None) + state["updated_utc"] = utc_now() + state["ready_dependencies"] = [ + dataset for dataset, item in pending.items() if dependency_ready(item) + ] + atomic_json(args.state, state) + if len(state["completed_ids"]) < len(pending): + time.sleep(args.poll_seconds) + state["status"] = "complete" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase8_egodexter_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase8_egodexter_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9d96eeb623ad017721160ed288970aa05e10ae3a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase8_egodexter_queue.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Run a frozen EgoDexter queue on atomically claimed physical GPU0-3.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("egodexter_used_for_training_or_selection") is not False + or not queue.get("evaluations") + ): + raise ValueError("EgoDexter queue boundary flags are invalid") + expected = { + (mode, input_mode) + for mode in ("offline", "causal") + for input_mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + actual = { + (item.get("inference_mode"), item.get("input_mode")) + for item in queue["evaluations"] + } + if actual != expected or len(queue["evaluations"]) != len(expected): + raise ValueError("EgoDexter queue must contain the exact six-condition grid") + if {item.get("model_id") for item in queue["evaluations"]} != {queue.get("model_id")}: + raise ValueError("EgoDexter queue mixes model IDs") + + +def completed_matches(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_frozen_egodexter_zero_shot" + and report.get("model_id") == item["model_id"] + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("inference_mode") == item["inference_mode"] + and report.get("egodexter_used_for_training_or_selection") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_egodexter_zero_shot", + "--model-id", item["model_id"], + "--freeze-record", item["freeze_record"], + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--root", item["root"], "--input-mode", item["input_mode"], + "--inference-mode", item["inference_mode"], + "--window", str(item.get("window", 8)), + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + output = Path(item["output_dir"]) + if output.exists(): + raise RuntimeError(f"EgoDexter output already exists: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode == 0 and completed_matches(item): + state["completed_ids"].append(item["id"]) + break + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase8_h2o_control_eval_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase8_h2o_control_eval_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..6106550a604d35b15aecabb34d29f911e7f8d1c9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase8_h2o_control_eval_queue.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Run hash-bound H2O train-heldout controls without changing their provenance.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase7_external_eval_queue import atomic_json, idle_gpu + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_queue(queue: dict[str, Any]) -> None: + if ( + queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + or queue.get("selection_split") != "h2o_train_group_heldout_only" + ): + raise ValueError("H2O control queue boundary flags are invalid") + if not queue.get("evaluations"): + raise ValueError("H2O control queue is empty") + for item in queue["evaluations"]: + if Path(item["cache_manifest"]).name != "train_group_heldout.jsonl": + raise ValueError("H2O control must use train_group_heldout.jsonl") + if not isinstance(item.get("expected_h2o_training_data_used"), bool): + raise ValueError("control item must freeze expected H2O provenance") + + +def completed_matches(item: dict[str, Any]) -> bool: + path = Path(item["output_dir"]) / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_h2o_train_group_heldout_control" + and report.get("evaluation_role") == "h2o_train_group_heldout_control" + and report.get("checkpoint", {}).get("sha256") == item["checkpoint_sha256"] + and report.get("input_mode") == item["input_mode"] + and report.get("h2o_training_data_used") is item["expected_h2o_training_data_used"] + and report.get("h2o_official_validation_used") is False + and report.get("official_test_used") is False + ) + + +def evaluator_command(item: dict[str, Any], gpu: int) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--input-mode", item["input_mode"], + "--evaluation-role", "h2o_train_group_heldout_control", + "--output-dir", item["output_dir"], "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(item.get("bootstrap_resamples", 2000)), + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=15.0) + args = parser.parse_args() + queue = json.loads(args.queue.read_text(encoding="utf-8")) + try: + validate_queue(queue) + except ValueError as error: + parser.error(str(error)) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "status": "running", "queue": str(args.queue.resolve()), + "started_utc": utc_now(), "updated_utc": utc_now(), + "current_index": 0, "completed_ids": [], "attempts": [], + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue") != str(args.queue.resolve()): + parser.error("existing state belongs to a different queue") + state = previous + for index, item in enumerate(queue["evaluations"]): + state["current_index"] = index + if completed_matches(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + while True: + gpu = idle_gpu() + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + output = Path(item["output_dir"]) + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty H2O control output: {output}") + command = evaluator_command(item, gpu) + log = args.state.parent / f"{args.queue.stem}_{item['id']}.log" + attempt = { + "id": item["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, "log": str(log.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log.open("a", encoding="utf-8") as handle: + result = subprocess.run( + command, env=dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)), + stdout=handle, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode != 0 or not completed_matches(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(item["id"]) + state["status"] = "complete" + state["current_index"] = len(queue["evaluations"]) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_data_finalize_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_data_finalize_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..8d1a4cd4bc05e33467e6e5aa5cf12294d155a053 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_data_finalize_queue.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Wait for Phase 9 base caches, then freeze subsets and left sidecars.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def base_cache_ready(item: dict[str, Any]) -> bool: + manifest = Path(item["manifest"]) + report_path = Path(item["report"]) + if not manifest.is_file() or not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("cache_manifest", {}).get("sha256") != sha256(manifest) + ): + return False + if item["dataset"] == "HOT3D": + return int(report.get("clips", -1)) == int(item["expected_clips"]) + return ( + report.get("accept_all_valid") is True + and report.get("all_eligible_processed") is True + and int(report.get("cached_valid_clips", 0)) > 0 + ) + + +def artifact_complete(item: dict[str, Any]) -> bool: + report_path = Path(item["report"]) + manifest = Path(item["manifest"]) + if not report_path.is_file() or not manifest.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + key = "augmented_cache_manifest" if item["kind"] == "left_sidecar" else "cache_manifest" + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get(key, {}).get("sha256") == sha256(manifest) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("finalize plan must explicitly exclude official test") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_data_finalize_state_v1", + "status": "waiting_for_base_caches", + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "started_utc": utc_now(), + "updated_utc": utc_now(), + "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != sha256(args.plan): + parser.error("existing state is bound to a different plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + base_caches = {item["dataset"]: item for item in plan["base_caches"]} + for item in plan["artifacts"]: + if artifact_complete(item): + continue + prerequisite = base_caches[item["requires_base_cache"]] + while not base_cache_ready(prerequisite): + state["status"] = "waiting_for_base_cache" + state["current_artifact"] = item["id"] + state["waiting_for_dataset"] = item["requires_base_cache"] + state["ready_base_caches"] = [ + dataset for dataset, base in base_caches.items() + if base_cache_ready(base) + ] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = [str(value) for value in item["command"]] + if item["kind"] == "left_sidecar": + base_manifest = Path(item["base_cache_manifest"]) + command = [ + value.replace("{BASE_CACHE_SHA256}", sha256(base_manifest)) + for value in command + ] + if (Path(item["output_dir"]) / "sidecars").is_dir(): + command.append("--resume") + log_path = Path(item["log"]) + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "id": item["id"], "start_utc": utc_now(), + "command": command, "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_artifact"] = item["id"] + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if result.returncode or not artifact_complete(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "returncode": result.returncode} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["artifacts"] = [{ + "id": item["id"], "manifest": item["manifest"], + "manifest_sha256": sha256(item["manifest"]), + "report": item["report"], "report_sha256": sha256(item["report"]), + } for item in plan["artifacts"]] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_distributed_resolution_cache_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_distributed_resolution_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9e349530aae1d53571708b4637ace42ed029b9e5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_distributed_resolution_cache_queue.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Enforce distributed cache ownership before entering the existing queue.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import sys + +from scripts.phase9_distributed_assignment import detect_machine, load_assignment + + +CACHE_OWNERS = { + "h2o": "taku3", + "hot3d": "server_new", + "hoi4d": "taku3", + "arctic": "taku3", +} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--assignment", type=Path, required=True) + parser.add_argument("--assignment-sha256", required=True) + parser.add_argument("--worker", choices=tuple(CACHE_OWNERS), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + assignment = load_assignment({"distributed_assignment": { + "path": str(args.assignment.resolve()), + "sha256": args.assignment_sha256, + }}) + machine = detect_machine(assignment, None) + if CACHE_OWNERS[args.worker] != machine: + parser.error(f"cache worker {args.worker} is owned by {CACHE_OWNERS[args.worker]}") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + matches = [item for item in plan["workers"] if item["id"] == args.worker] + if ( + len(matches) != 1 + or Path(matches[0]["state"]).resolve() != args.state.resolve() + or plan.get("official_test_used") is not False + ): + parser.error("distributed cache worker plan/state differs") + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_cache_queue", + "--plan", str(args.plan.resolve()), "--worker", args.worker, + "--state", str(args.state.resolve()), + "--poll-seconds", str(args.poll_seconds), + ] + os.execv(sys.executable, command) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_expanded_coverage_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_expanded_coverage_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c69ac4d00155e8221d06fc56dc05c3fd3890b3 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_expanded_coverage_queue.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Run frozen source-coverage audits after Phase 9 data finalization.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import readiness_complete + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def audit_complete(item: dict[str, Any]) -> bool: + output = Path(item["output"]) + if not output.is_file(): + return False + report = json.loads(output.read_text(encoding="utf-8")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("cache_manifest", {}).get("sha256") == sha256(item["cache_manifest"]) + and report.get("source_manifest", {}).get("sha256") == sha256(item["source_manifest"]) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("coverage plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_expanded_coverage_state_v1", + "status": "waiting_for_data", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "updated_utc": utc_now(), "completed_ids": [], "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing coverage state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not readiness_complete(plan): + state["status"] = "waiting_for_data" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + for item in plan["audits"]: + if audit_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + continue + output = Path(item["output"]) + if output.exists(): + raise RuntimeError(f"incomplete coverage output already exists: {output}") + command = [ + sys.executable, "-m", "scripts.audit_phase9_source_coverage", + "--dataset", item["dataset"], + "--source-manifest", item["source_manifest"], + "--cache-manifest", item["cache_manifest"], + "--output", item["output"], + ] + log_path = args.state.parent / f"expanded_coverage_{item['dataset'].lower()}.log" + attempt = { + "id": item["id"], "start_utc": utc_now(), + "command": command, "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not audit_complete(item): + state["status"] = "failed" + state["failure"] = {"id": item["id"], "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_external_milestone_eval.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_external_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..6b01ab8a3b01110cdfecc246e0022914527b06f1 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_external_milestone_eval.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Evaluate Phase 9 unified milestone checkpoints on native external held-outs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3, 4, 5) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def stable_checkpoint_sha256( + path: str | Path, + *, + stable_seconds: float = 2.0, + poll_seconds: float = 0.25, + timeout_seconds: float = 300.0, +) -> str: + """Hash a checkpoint only after a non-atomic torch.save has quiesced.""" + checkpoint = Path(path) + started = time.monotonic() + previous = (checkpoint.stat().st_size, checkpoint.stat().st_mtime_ns) + stable_since = time.monotonic() + while True: + if time.monotonic() - started > timeout_seconds: + raise TimeoutError(f"checkpoint did not stabilize: {checkpoint}") + time.sleep(poll_seconds) + before = checkpoint.stat() + signature = (before.st_size, before.st_mtime_ns) + if signature != previous: + previous = signature + stable_since = time.monotonic() + continue + if time.monotonic() - stable_since < stable_seconds: + continue + digest = sha256(checkpoint) + after = checkpoint.stat() + if (after.st_size, after.st_mtime_ns) == signature: + return digest + previous = (after.st_size, after.st_mtime_ns) + stable_since = time.monotonic() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def checkpoint_path(condition: dict[str, Any], checkpoint: dict[str, Any]) -> Path | None: + run = Path(condition["run_dir"]) + if checkpoint["kind"] == "final": + path = run / f"step_{int(checkpoint['step']):07d}_final.pt" + return path if path.is_file() else None + matches = sorted(run.glob(f"milestone_{checkpoint['milestone_id']}_step_*.pt")) + if len(matches) > 1: + raise RuntimeError(f"multiple checkpoint files for milestone {checkpoint['milestone_id']}") + return matches[0] if matches else None + + +def evaluation_complete( + output_dir: Path, checkpoint_hash: str, manifest_hash: str, input_mode: str, +) -> bool: + path = output_dir / "evaluation.json" + if not path.is_file(): + return False + report = json.loads(path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_phase9_external_heldout" + and report.get("evaluation_role") == "phase9_external_heldout" + and report.get("checkpoint", {}).get("sha256") == checkpoint_hash + and report.get("cache_manifest", {}).get("sha256") == manifest_hash + and report.get("input_mode") == input_mode + and report.get("h2o_training_data_used") is True + and report.get("official_test_used") is False + ) + + +def idle_gpu() -> int | None: + for gpu in ALLOWED_GPUS: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def evaluator_command( + condition: dict[str, Any], checkpoint: Path, checkpoint_hash: str, + source: dict[str, Any], gpu: int, output: Path, +) -> list[str]: + return [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", condition["config"], + "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", source["cache_manifest"], + "--expected-cache-manifest-sha256", source["cache_manifest_sha256"], + "--input-mode", source["input_mode"], + "--output-dir", str(output), + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(source.get("bootstrap_resamples", 2000)), + "--evaluation-role", "phase9_external_heldout", + ] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--condition", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + registry = json.loads(args.registry.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + parser.error("registry must explicitly exclude official test") + conditions = {item["condition"]: item for item in registry["conditions"]} + if args.condition not in conditions: + parser.error("unknown condition") + condition = conditions[args.condition] + config = Path(condition["config"]) + if not config.is_file() or sha256(config) != condition["config_sha256"]: + parser.error("frozen config is missing or changed") + for source in registry["sources"]: + manifest = Path(source["cache_manifest"]) + if not manifest.is_file() or sha256(manifest) != source["cache_manifest_sha256"]: + parser.error(f"held-out manifest is missing or changed: {source['id']}") + registry_hash = sha256(args.registry) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_external_milestone_eval_state_v1", + "status": "waiting_for_checkpoint", "condition": args.condition, + "registry": str(args.registry.resolve()), "registry_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(ALLOWED_GPUS), "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("registry_sha256") != registry_hash: + parser.error("existing state is bound to another registry version") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for checkpoint_spec in condition["checkpoints"]: + while True: + checkpoint = checkpoint_path(condition, checkpoint_spec) + if checkpoint is not None: + break + state["status"] = "waiting_for_checkpoint" + state["waiting_for"] = checkpoint_spec["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for source in registry["sources"]: + evaluation_id = f"{args.condition}_{checkpoint_spec['id']}_{source['id']}" + output = Path(registry["evaluation_root"]) / args.condition / checkpoint_spec["id"] / source["id"] + if evaluation_complete( + output, checkpoint_hash, source["cache_manifest_sha256"], source["input_mode"], + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + continue + while True: + gpu = idle_gpu() + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + if output.exists() and any(output.iterdir()): + release_physical_gpu_claim(gpu) + state["status"] = "failed_existing_output" + state["failure"] = {"id": evaluation_id, "output": str(output)} + atomic_json(args.state, state) + raise SystemExit(1) + command = evaluator_command( + condition, checkpoint, checkpoint_hash, source, gpu, output, + ) + log_path = args.state.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not evaluation_complete( + output, checkpoint_hash, source["cache_manifest_sha256"], source["input_mode"], + ): + state["status"] = "failed" + state["failure"] = {"id": evaluation_id, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_final_deployment_controller.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_final_deployment_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..a64e86ece28d0bcd9b90218507b54ae5ab7ae529 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_final_deployment_controller.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +"""Wait for final selection, then supervise formal validation and deployment audits.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + if ( + plan.get("schema_version") != "phase9_final_deployment_controller_plan_v1" + or plan.get("job_count") != 11 or plan.get("worker_count") != 4 + or plan.get("allowed_physical_gpus") != [0, 1, 2, 3] + or plan.get("official_validation_checkpoint_count") != 1 + or plan.get("h2o_official_validation_used_for_selection") is not False + or plan.get("official_test_used") is not False + ): + raise ValueError("final deployment controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"final deployment binding differs: {path}") + + +def final_decision_ready(plan: dict[str, Any]) -> bool: + state_path = Path(plan["last2_finalizer_state"]) + if not state_path.is_file(): + return False + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["last2_finalizer_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and report_path.is_file() + and state.get("decision_report", {}).get("sha256") == sha256(report_path) + and report_path.resolve() == Path(plan["last2_final_decision"]).resolve() + ) + + +def worker_status(path: Path, plan_hash: str) -> str: + if not path.is_file(): + return "missing" + state = read_json(path) + if state.get("plan_sha256") != plan_hash: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def pid_matches(pid: int, worker: str, dynamic_plan: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_final_deployment_worker" in command + and f"--worker {worker}" in command + and str(dynamic_plan.resolve()) in command + ) + + +def launch_worker(dynamic_plan: Path, worker: dict[str, Any], log_path: Path) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_final_deployment_worker", + "--plan", str(dynamic_plan.resolve()), "--worker", worker["id"], + "--state", worker["state"], + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def run_command(command: list[str], state: dict[str, Any], state_path: Path, label: str) -> None: + state["status"] = label + state[f"{label}_command"] = command + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = f"failed_{label}" + state[f"{label}_returncode"] = result.returncode + atomic_json(state_path, state) + raise SystemExit(result.returncode) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["controller_state"]).resolve(): + parser.error("final deployment controller state differs") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_final_deployment_controller_state_v1", + "status": "waiting_for_final_selection", "started_utc": utc_now(), + "updated_utc": utc_now(), "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "workers": {}, + "h2o_official_validation_used": False, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing final deployment controller state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not final_decision_ready(plan): + state["status"] = "waiting_for_final_selection" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + freeze = Path(plan["freeze"]) + freeze_command = [ + sys.executable, "-m", "scripts.freeze_phase9_final_deployment", + "--selection-plan", plan["selection_plan"], + "--selection-state", plan["selection_state"], + "--stage8-plan", plan["stage8_plan"], + "--stage8-state", plan["stage8_state"], + "--last2-plan", plan["last2_finalizer_plan"], + "--last2-state", plan["last2_finalizer_state"], + "--validation-manifest", plan["validation_manifest"], + "--validation-manifest-sha256", plan["validation_manifest_sha256"], + "--training-manifest", plan["training_manifest"], + "--training-manifest-sha256", plan["training_manifest_sha256"], + "--output", str(freeze), "--state", plan["freeze_state"], + ] + run_command(freeze_command, state, args.state, "freezing_final_checkpoint") + freeze_state = read_json(plan["freeze_state"]) + if ( + freeze_state.get("status") != "complete" or not freeze.is_file() + or freeze_state.get("freeze_sha256") != sha256(freeze) + ): + state["status"] = "failed_freeze_binding" + atomic_json(args.state, state) + raise SystemExit(1) + + dynamic_plan = Path(plan["dynamic_plan"]) + dynamic_command = [ + sys.executable, "-m", "scripts.build_phase9_final_deployment_plan", + "--freeze", str(freeze), "--freeze-state", plan["freeze_state"], + "--output-root", plan["output_root"], + "--worker-state-root", plan["worker_state_root"], + "--causal-config", plan["causal_config"], + "--h2o-root", plan["h2o_root"], + "--output", str(dynamic_plan), "--state", plan["dynamic_plan_state"], + ] + run_command(dynamic_command, state, args.state, "building_deployment_plan") + dynamic_state = read_json(plan["dynamic_plan_state"]) + if ( + dynamic_state.get("status") != "complete" or not dynamic_plan.is_file() + or dynamic_state.get("plan_sha256") != sha256(dynamic_plan) + ): + state["status"] = "failed_dynamic_plan_binding" + atomic_json(args.state, state) + raise SystemExit(1) + dynamic_hash = sha256(dynamic_plan) + dynamic = read_json(dynamic_plan) + state["dynamic_plan_sha256"] = dynamic_hash + state.setdefault("workers", {}) + while True: + statuses = {} + for worker in dynamic["workers"]: + path = Path(worker["state"]) + status = worker_status(path, dynamic_hash) + statuses[worker["id"]] = status + if status == "complete" or status.startswith("failed"): + continue + previous_pid = int(state["workers"].get(worker["id"], {}).get("pid", -1)) + if not pid_matches(previous_pid, worker["id"], dynamic_plan): + pid = launch_worker( + dynamic_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(status.startswith("failed") for status in statuses.values()): + state["status"] = "failed_deployment_worker" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = "running_post_selection_audits" + state["h2o_official_validation_used"] = True + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + report = Path(plan["summary_report"]) + if not report.is_file(): + run_command([ + sys.executable, "-m", "scripts.summarize_phase9_final_deployment", + "--plan", str(dynamic_plan), "--output", str(report), + ], state, args.state, "summarizing_deployment") + summary = read_json(report) + if ( + summary.get("status") != "complete" + or summary.get("deployment_contract", {}).get("passed") is not True + or summary.get("h2o_official_validation_used_for_selection") is not False + or summary.get("official_test_used") is not False + ): + state["status"] = "failed_deployment_summary" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["summary_report"] = {"path": str(report.resolve()), "sha256": sha256(report)} + state["checkpoint"] = summary["checkpoint"] + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["h2o_official_validation_used"] = True + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_final_deployment_worker.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_final_deployment_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ad40a896ea1c75803d879094f935440c2aae9c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_final_deployment_worker.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Run one disjoint final deployment worker with resumable output validation.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_artifact(record: dict[str, Any]) -> bool: + path = Path(record.get("path", "")) + return path.is_file() and record.get("sha256") == sha256(path) + + +def completed_matches(job: dict[str, Any]) -> bool: + kind = job["kind"] + path = ( + Path(job["output_dir"]) / "evaluation.json" + if kind == "formal_validation" else Path(job["output"]) + ) + if not path.is_file(): + return False + try: + report = read_json(path) + except (OSError, json.JSONDecodeError): + return False + common = ( + report.get("checkpoint", {}).get("sha256") == job["checkpoint_sha256"] + and report.get("config", {}).get("sha256") == job["config_sha256"] + and report.get("manifest", {}).get("sha256") == job["manifest_sha256"] + and report.get("official_test_used") is False + ) + if not common: + return False + report_step = report.get("checkpoint", {}).get( + "step", report.get("checkpoint_step") + ) + if int(report_step if report_step is not None else -1) != job["checkpoint_step"]: + return False + if kind == "formal_validation": + return ( + report.get("status") == "evaluated_phase9_unified_formal" + and report.get("evaluation_role") == "phase9_unified_formal" + and report.get("input_mode") == job["input_mode"] + and report.get("freeze_record", {}).get("sha256") + == job["freeze_record_sha256"] + and report.get("h2o_official_validation_used") is True + and report.get("h2o_official_validation_used_for_selection") is False + and report.get("h2o_training_data_used") is True + and all(validate_artifact(report[key]) for key in ( + "raw_predictions", "per_hand_rows", "take_metrics", + )) + ) + if kind == "variable_length": + results = report.get("forward_results", []) + return ( + report.get("status") == "completed" + and report.get("official_validation_used") is True + and [item.get("T") for item in results] == job["lengths"] + and all(item.get("all_finite") is True for item in results) + ) + if kind == "sequence": + bounded = ( + int(report.get("maximum_gpu_window_frames", 10**9)) <= job["window"] + and int(report.get("maximum_cpu_input_buffer_frames", 10**9)) + <= (job["window"] if job["mode"] == "causal" else 12) + ) + causal = report.get("invariance") + causal_ok = job["mode"] != "causal" or ( + isinstance(causal, dict) + and causal.get("future_perturbation_bitwise_zero") is True + and causal.get("prefix_passed") is True + ) + mode_ok = ( + report.get("causal") is (job["mode"] == "causal") + and report.get("offline_stride") + == (None if job["mode"] == "causal" else 4) + and report.get("stitching") + == (None if job["mode"] == "causal" else "center") + ) + return ( + report.get("status") == "passed" + and report.get("mode") == job["mode"] + and report.get("window") == job["window"] + and report.get("requested_frames") == job["frames"] + and report.get("output_frames") == job["frames"] + and report.get("frame_ids_strictly_increasing") is True + and report.get("finite") is True + and report.get("official_validation_used_for_selection") is False + and bounded and causal_ok and mode_ok + ) + if kind == "profile": + latency = report.get("latency", {}) + return ( + report.get("status") == "profiled" + and report.get("official_validation_used") is False + and report.get("input", {}).get("resolution_hw") == job["resolution_hw"] + and float(latency.get("p50_ms", 0)) > 0 + and float(latency.get("p95_ms", 0)) > 0 + and float(report.get("peak_allocated_vram_gib", 0)) > 0 + ) + return False + + +def command(job: dict[str, Any]) -> list[str]: + common = ["--config", job["config"], "--checkpoint", job["checkpoint"]] + if job["kind"] == "formal_validation": + return [ + sys.executable, "-m", "scripts.evaluate_phase7_h2o_zero_shot", + *common, "--expected-checkpoint-sha256", job["checkpoint_sha256"], + "--freeze-record", job["freeze_record"], "--root", job["root"], + "--manifest", job["manifest"], "--input-mode", job["input_mode"], + "--evaluation-role", "phase9_unified_formal", + "--output-dir", job["output_dir"], "--physical-gpu-id", + str(job["physical_gpu_id"]), "--bootstrap-resamples", "2000", + ] + if job["kind"] == "variable_length": + return [ + sys.executable, "-m", "scripts.audit_phase6_variable_length", + *common, "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--gpu", str(job["physical_gpu_id"]), + "--repeats", "2", + ] + if job["kind"] == "sequence": + return [ + sys.executable, "-m", "scripts.audit_phase6_sequence_inference", + *common, "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--mode", job["mode"], + "--window", str(job["window"]), "--frames", str(job["frames"]), + "--gpu", str(job["physical_gpu_id"]), + ] + if job["kind"] == "profile": + return [ + sys.executable, "-m", "scripts.profile_phase5_model", + *common, "--expected-checkpoint-sha256", job["checkpoint_sha256"], + "--root", job["root"], "--manifest", job["manifest"], + "--output", job["output"], "--gpu", str(job["physical_gpu_id"]), + "--warmup", "20", "--iterations", "100", + ] + raise ValueError(f"unknown final deployment job kind: {job['kind']}") + + +def output_target(job: dict[str, Any]) -> Path: + return Path(job.get("output", job.get("output_dir", ""))) + + +def archive_incomplete(job: dict[str, Any]) -> str | None: + target = output_target(job) + if not target.exists(): + return None + recovery = target.parent / "recovery" + recovery.mkdir(parents=True, exist_ok=True) + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + destination = recovery / f"{target.name}.{stamp}.incomplete" + suffix = 0 + while destination.exists(): + suffix += 1 + destination = recovery / f"{target.name}.{stamp}.{suffix}.incomplete" + shutil.move(str(target), str(destination)) + return str(destination.resolve()) + + +def validate_plan(plan: dict[str, Any], worker: dict[str, Any]) -> dict[str, dict[str, Any]]: + if ( + plan.get("status") != "frozen_ready_post_selection" + or plan.get("official_validation_checkpoint_count") != 1 + or plan.get("h2o_official_validation_used_for_selection") is not False + or plan.get("official_test_used") is not False + or worker.get("physical_gpu_id") not in {0, 1, 2, 3} + ): + raise ValueError("final deployment worker contract differs") + jobs = {job["id"]: job for job in plan["jobs"]} + if len(jobs) != 11 or any(identifier not in jobs for identifier in worker["job_ids"]): + raise ValueError("final deployment worker jobs differ") + if any(jobs[identifier]["physical_gpu_id"] != worker["physical_gpu_id"] for identifier in worker["job_ids"]): + raise ValueError("final deployment worker GPU assignment differs") + return jobs + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + worker = next((item for item in plan["workers"] if item["id"] == args.worker), None) + if worker is None: + parser.error("unknown final deployment worker") + try: + jobs = validate_plan(plan, worker) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("final deployment worker state differs") + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_final_deployment_worker_state_v1", + "status": "running", "worker": args.worker, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != plan_hash: + parser.error("existing final deployment worker state differs") + if state.get("status") == "complete": + invalid = [ + identifier for identifier in worker["job_ids"] + if not completed_matches(jobs[identifier]) + ] + if invalid: + state["status"] = "failed_completed_output_binding" + state["failure"] = {"invalid_completed_ids": invalid} + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + print(json.dumps(state, indent=2)) + return + for identifier in worker["job_ids"]: + job = jobs[identifier] + target = output_target(job) + lock_path = Path(f"{target}.lock") + lock_path.parent.mkdir(parents=True, exist_ok=True) + with lock_path.open("a+", encoding="utf-8") as output_lock: + fcntl.flock(output_lock.fileno(), fcntl.LOCK_EX) + if completed_matches(job): + if identifier not in state["completed_ids"]: + state["completed_ids"].append(identifier) + atomic_json(args.state, state) + continue + archived = archive_incomplete(job) + attempt = { + "id": identifier, "kind": job["kind"], + "physical_gpu_id": job["physical_gpu_id"], + "start_utc": utc_now(), "command": command(job), + } + log_path = args.state.parent / f"{identifier}.log" + attempt["log"] = str(log_path.resolve()) + if archived: + attempt["archived_incomplete_output"] = archived + state["current_id"] = identifier + state["status"] = "running" + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ) + if job["kind"] == "formal_validation": + environment["CUDA_VISIBLE_DEVICES"] = str(job["physical_gpu_id"]) + else: + environment.pop("CUDA_VISIBLE_DEVICES", None) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + attempt["command"], cwd=Path.cwd(), env=environment, + stdout=log, stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not completed_matches(job): + state["status"] = "failed_job" + state["failure"] = {"id": identifier, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(identifier) + atomic_json(args.state, state) + state["status"] = "complete" + state["current_id"] = None + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_fold_milestone_eval.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_fold_milestone_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..bae92c4c4151e059eb56207d37420d72fa6d3dbe --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_fold_milestone_eval.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +"""Evaluate H2O-bearing milestones for Phase 9 group-CV replicas.""" + +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any, Iterator + +import yaml + +from scripts.run_phase9_fold_shard import fold_evaluation_complete +from scripts.run_phase9_external_milestone_eval import stable_checkpoint_sha256 +from scripts.run_phase9_unified_train_queue import parse_physical_gpu_ids +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3, 4, 5) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def h2o_milestones(config: dict[str, Any]) -> list[str]: + return [ + str(milestone["id"]) + for milestone in config["protocol"].get("source_exposure_milestones", []) + if "H2O" in milestone.get("minimum_batches", {}) + ] + + +def milestone_checkpoint(run_dir: Path, milestone_id: str) -> Path | None: + matches = sorted(run_dir.glob(f"milestone_{milestone_id}_step_*.pt")) + if len(matches) > 1: + raise RuntimeError(f"multiple checkpoints found for milestone {milestone_id}") + return matches[0] if matches else None + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +@contextmanager +def exclusive_evaluation_output(output: Path) -> Iterator[None]: + output.parent.mkdir(parents=True, exist_ok=True) + lock_path = output.parent / f".{output.name}.phase9-evaluation.lock" + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(lock.fileno(), fcntl.LOCK_UN) + + +def recovery_assignment( + plan_path: Path, worker_id: str, registry_hash: str, +) -> tuple[dict[str, Any], str]: + plan = json.loads(plan_path.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + raise ValueError("recovery plan must explicitly exclude official test") + if plan.get("registry_sha256") != registry_hash: + raise ValueError("recovery plan registry SHA256 differs") + matches = [item for item in plan["workers"] if item["id"] == worker_id] + if len(matches) != 1: + raise ValueError(f"recovery worker must be unique: {worker_id}") + return matches[0], sha256(plan_path) + + +def evaluation_command( + config_path: Path, checkpoint: Path, checkpoint_hash: str, + heldout: Path, heldout_hash: str, mode: str, output: Path, gpu: int, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", str(config_path), "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", str(heldout), + "--expected-cache-manifest-sha256", heldout_hash, + "--input-mode", mode, "--output-dir", str(output), + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", "phase9_h2o_fold_heldout", + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--shard", type=int, choices=(0, 1, 2), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--recovery-plan", type=Path) + parser.add_argument("--worker-id") + args = parser.parse_args() + registry = json.loads(args.registry.read_text(encoding="utf-8")) + if registry.get("official_test_used") is not False: + parser.error("fold registry must explicitly exclude official test") + conditions = {item["condition"]: item for item in registry["conditions"]} + assigned = registry["shards"][str(args.shard)] + registry_hash = sha256(args.registry) + selected_ids: set[str] | None = None + recovery_plan_hash: str | None = None + if (args.recovery_plan is None) != (args.worker_id is None): + parser.error("--recovery-plan and --worker-id must be provided together") + if args.recovery_plan is not None: + try: + worker, recovery_plan_hash = recovery_assignment( + args.recovery_plan, args.worker_id, registry_hash, + ) + except (KeyError, TypeError, ValueError) as error: + parser.error(str(error)) + if int(worker["shard"]) != args.shard: + parser.error("recovery worker shard differs") + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("recovery worker state path differs") + if tuple(worker["allowed_physical_gpus"]) != args.allowed_physical_gpus: + parser.error("recovery worker GPU assignment differs") + selected_ids = set(worker["evaluation_ids"]) + if len(selected_ids) != len(worker["evaluation_ids"]): + parser.error("recovery worker contains duplicate evaluation IDs") + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_fold_milestone_eval_state_v1", + "status": "waiting_for_checkpoint", "shard": args.shard, + "registry": str(args.registry.resolve()), "registry_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_ids": [], "attempts": [], + "allowed_physical_gpus": list(args.allowed_physical_gpus), + "official_test_used": False, + } + if recovery_plan_hash is not None: + state.update({ + "recovery_plan": str(args.recovery_plan.resolve()), + "recovery_plan_sha256": recovery_plan_hash, + "recovery_worker_id": args.worker_id, + "assigned_evaluation_ids": sorted(selected_ids), + "resource_amendment": "gpu_4_5_evaluator_authorization_only_20260730", + }) + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("registry_sha256") != registry_hash: + parser.error("existing state belongs to another registry") + if recovery_plan_hash is not None and ( + previous.get("recovery_plan_sha256") != recovery_plan_hash + or previous.get("recovery_worker_id") != args.worker_id + or set(previous.get("assigned_evaluation_ids", [])) != selected_ids + or tuple(previous.get("allowed_physical_gpus", ())) + != args.allowed_physical_gpus + ): + parser.error("existing recovery state belongs to another assignment") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for condition_id in assigned: + condition = conditions[condition_id] + config_path = Path(condition["config"]) + if sha256(config_path) != condition["config_sha256"]: + parser.error(f"fold config hash differs: {condition_id}") + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) + heldout = Path(config["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + run_dir = Path(condition["output_dir"]) + for milestone_id in h2o_milestones(config): + milestone_ids = { + f"{condition_id}_{milestone_id}_{mode}" + for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + if selected_ids is not None and not (milestone_ids & selected_ids): + continue + while True: + checkpoint = milestone_checkpoint(run_dir, milestone_id) + if checkpoint is not None: + break + state["status"] = "waiting_for_checkpoint" + state["waiting_for"] = f"{condition_id}:{milestone_id}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + checkpoint_hash = stable_checkpoint_sha256(checkpoint) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + evaluation_id = f"{condition_id}_{milestone_id}_{mode}" + if selected_ids is not None and evaluation_id not in selected_ids: + continue + output = args.output_root / condition_id / milestone_id / mode + if fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + continue + with exclusive_evaluation_output(output): + if fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + if evaluation_id not in state["completed_ids"]: + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + continue + if output.exists() and any(output.iterdir()): + raise RuntimeError(f"nonempty incomplete output: {output}") + while True: + gpu = idle_gpu(args.allowed_physical_gpus) + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = evaluation_command( + config_path, checkpoint, checkpoint_hash, + heldout, heldout_hash, mode, output, gpu, + ) + log_path = args.state.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + state["status"] = "failed" + state["failure"] = { + "id": evaluation_id, "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + state["completed_ids"].append(evaluation_id) + atomic_json(args.state, state) + if selected_ids is not None and not selected_ids.issubset(state["completed_ids"]): + missing = sorted(selected_ids - set(state["completed_ids"])) + parser.error(f"recovery assignment contains unknown IDs: {missing}") + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_fold_overflow.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_fold_overflow.py new file mode 100644 index 0000000000000000000000000000000000000000..348d8b3162e8c54d6a313eb7961b75b243c63ab6 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_fold_overflow.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Run frozen Phase 9 fold conditions early on otherwise idle capacity.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def prerequisite_states_complete(plan: dict[str, Any]) -> bool: + for item in plan["prerequisite_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("overflow plan must explicitly exclude official test") + registry = Path(plan["fold_training_registry"]) + if sha256(registry) != plan["fold_training_registry_sha256"]: + parser.error("fold training registry SHA256 differs") + registry_payload = json.loads(registry.read_text(encoding="utf-8")) + registered = {item["condition"] for item in registry_payload["conditions"]} + if not plan["conditions"] or any(item not in registered for item in plan["conditions"]): + parser.error("overflow condition is not in the frozen fold registry") + + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + state: dict[str, Any] = { + "schema_version": "phase9_fold_overflow_state_v1", + "status": "waiting_for_prerequisites", + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "started_utc": utc_now(), + "updated_utc": utc_now(), + "completed_conditions": [], + "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing overflow state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + + while not prerequisite_states_complete(plan): + state["status"] = "waiting_for_prerequisites" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + child_root = Path(plan["child_state_root"]) + child_root.mkdir(parents=True, exist_ok=True) + for condition in plan["conditions"]: + if condition in state["completed_conditions"]: + continue + child_state = child_root / f"{condition.lower()}.json" + command = [ + sys.executable, + "-m", + "scripts.run_phase9_unified_train_queue", + "--queue", + str(registry), + "--condition", + condition, + "--state", + str(child_state), + "--poll-seconds", + str(args.poll_seconds), + "--allowed-physical-gpus", + str(plan["physical_gpu_id"]), + ] + log_path = args.state.parent / f"overflow_{condition.lower()}.log" + attempt = { + "condition": condition, + "start_utc": utc_now(), + "command": command, + "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "running_condition" + state["current_condition"] = condition + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, + stdout=log, + stderr=subprocess.STDOUT, + text=True, + check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode: + state["status"] = "failed_resumable" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_conditions"].append(condition) + atomic_json(args.state, state) + + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_fold_shard.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_fold_shard.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6b518537959a2149496efd6fae0f33badb5dc7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_fold_shard.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Run a shard of Phase 9 H2O group-CV replicas and formal fold evaluations.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) +from scripts.run_phase9_unified_train_queue import parse_physical_gpu_ids + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def main_training_complete(plan: dict[str, Any]) -> bool: + for item in plan["main_training_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def main_training_gate_satisfied( + plan: dict[str, Any], start_before_main_complete: bool, +) -> bool: + return start_before_main_complete or main_training_complete(plan) + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def fold_evaluation_complete( + output: Path, checkpoint_hash: str, manifest_hash: str, mode: str, +) -> bool: + report_path = output / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "evaluated_phase9_h2o_fold_heldout" + and report.get("evaluation_role") == "phase9_h2o_fold_heldout" + and report.get("checkpoint", {}).get("sha256") == checkpoint_hash + and report.get("cache_manifest", {}).get("sha256") == manifest_hash + and report.get("input_mode") == mode + and report.get("official_test_used") is False + ) + + +def run_fold_evaluations( + condition: dict[str, Any], state: dict[str, Any], state_path: Path, + evaluation_root: Path, poll_seconds: float, + allowed_gpus: tuple[int, ...] = ALLOWED_GPUS, +) -> None: + step = int(condition["stages"][-1]["stop_after_step"]) + checkpoint = Path(condition["output_dir"]) / f"step_{step:07d}_final.pt" + checkpoint_hash = sha256(checkpoint) + config = Path(condition["config"]) + config_payload = __import__("yaml").safe_load(config.read_text(encoding="utf-8")) + heldout = Path(config_payload["data"]["validation_sources"][0]["cache_manifest"]) + heldout_hash = sha256(heldout) + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + output = evaluation_root / condition["condition"] / mode + evaluation_id = f"{condition['condition']}_{mode}" + if fold_evaluation_complete(output, checkpoint_hash, heldout_hash, mode): + if evaluation_id not in state["completed_evaluations"]: + state["completed_evaluations"].append(evaluation_id) + continue + while True: + gpu = idle_gpu(allowed_gpus) + if gpu is not None: + break + state["status"] = "waiting_for_idle_gpu_evaluation" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + time.sleep(poll_seconds) + if output.exists() and any(output.iterdir()): + release_physical_gpu_claim(gpu) + raise RuntimeError(f"nonempty incomplete fold evaluation output: {output}") + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", str(config), "--checkpoint", str(checkpoint), + "--expected-checkpoint-sha256", checkpoint_hash, + "--cache-manifest", str(heldout), + "--expected-cache-manifest-sha256", heldout_hash, + "--input-mode", mode, "--output-dir", str(output), + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", "phase9_h2o_fold_heldout", + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + log_path = state_path.parent / f"{evaluation_id}.log" + attempt = { + "id": evaluation_id, "type": "fold_evaluation", + "start_utc": utc_now(), "physical_gpu_id": gpu, + "command": command, "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "evaluating_fold" + atomic_json(state_path, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode or not fold_evaluation_complete( + output, checkpoint_hash, heldout_hash, mode, + ): + raise RuntimeError(f"fold evaluation failed: {evaluation_id}") + state["completed_evaluations"].append(evaluation_id) + atomic_json(state_path, state) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--shard", type=int, choices=(0, 1, 2), required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--start-before-main-complete", action="store_true") + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("fold shard plan must explicitly exclude official test") + registry_path = Path(plan["fold_training_registry"]) + if sha256(registry_path) != plan["fold_training_registry_sha256"]: + parser.error("fold training registry SHA256 differs") + registry = json.loads(registry_path.read_text(encoding="utf-8")) + conditions = {item["condition"]: item for item in registry["conditions"]} + assigned = registry["shards"][str(args.shard)] + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state = { + "schema_version": "phase9_fold_shard_state_v1", + "status": "waiting_for_main_training", "shard": args.shard, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "completed_conditions": [], "completed_evaluations": [], "attempts": [], + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing shard state belongs to another plan") + state = previous + previous_gpus = tuple(state.get("allowed_physical_gpus", ALLOWED_GPUS)) + if state.get("attempts") and previous_gpus != args.allowed_physical_gpus: + parser.error("cannot change allowed GPUs after this shard has attempted work") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + state["allowed_physical_gpus"] = list(args.allowed_physical_gpus) + state["start_before_main_complete"] = bool(args.start_before_main_complete) + if args.start_before_main_complete: + state["resource_amendment"] = "user_authorized_all_idle_gpus_20260727" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + while not main_training_gate_satisfied(plan, args.start_before_main_complete): + state["status"] = "waiting_for_main_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_root = Path(plan["fold_evaluation_root"]) + for condition_id in assigned: + condition = conditions[condition_id] + if condition_id not in state["completed_conditions"]: + child_state = args.state.parent / "fold_jobs" / f"{condition_id.lower()}.json" + child_state.parent.mkdir(parents=True, exist_ok=True) + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry_path), "--condition", condition_id, + "--state", str(child_state), "--poll-seconds", str(args.poll_seconds), + "--allowed-physical-gpus", + ",".join(str(gpu) for gpu in args.allowed_physical_gpus), + ] + log_path = args.state.parent / f"{condition_id.lower()}_training.log" + attempt = { + "id": condition_id, "type": "fold_training", + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["attempts"].append(attempt) + state["status"] = "training_fold" + state["current_condition"] = condition_id + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + if result.returncode: + state["status"] = "failed_fold_training" + state["failure"] = {"condition": condition_id, "log": str(log_path.resolve())} + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_conditions"].append(condition_id) + atomic_json(args.state, state) + try: + run_fold_evaluations( + condition, state, args.state, evaluation_root, args.poll_seconds, + args.allowed_physical_gpus, + ) + except RuntimeError as error: + state["status"] = "failed_fold_evaluation" + state["failure"] = {"condition": condition_id, "reason": str(error)} + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_hot_cache_release_bridge.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_hot_cache_release_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f786874c313bcb438d540641b84f917de27431 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_hot_cache_release_bridge.py @@ -0,0 +1,352 @@ +#!/usr/bin/env python3 +"""Publish and receive the immutable server_new Stage 7 HOT3D cache release.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import ( + atomic_json, + cache_step_complete, + sha256, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any] | None: + candidate = Path(path) + if not candidate.is_file(): + return None + return json.loads(candidate.read_text(encoding="utf-8")) + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("publisher_owner") != "server_new" + or plan.get("receiver_owner") != "taku3" + ): + raise ValueError("HOT cache release bridge plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"HOT cache bridge binding differs: {path}") + root = Path(plan["release_root"]) + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("HOT cache release root is not /SSD2") + for item in plan["artifacts"]: + path = Path(item["path"]) + if root not in path.parents or path == root: + raise ValueError("HOT cache release artifact is outside release root") + if Path(plan["staging_root"]).parts[:2] != ("/", "SSD2"): + raise ValueError("HOT cache staging root is not /SSD2") + + +def inventory_tree(root: Path, directory: Path) -> list[dict[str, Any]]: + if not directory.is_dir() or directory.is_symlink(): + raise ValueError(f"HOT release artifact directory differs: {directory}") + records = [] + for path in sorted(directory.rglob("*")): + if path.is_symlink(): + raise ValueError(f"HOT release refuses symlink: {path}") + if not path.is_file(): + continue + records.append({ + "path": str(path.relative_to(root)), "bytes": path.stat().st_size, + "sha256": sha256(path), + }) + return records + + +def validate_primary(plan: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]] | None: + queue_path = Path(plan["producer_queue_state"]["path"]) + primary_path = Path(plan["producer_worker_state"]) + queue = read_json(queue_path) + primary = read_json(primary_path) + if queue is None or primary is None: + return None + if queue.get("status") != "complete": + return None + if ( + queue.get("plan_sha256") != plan["producer_queue_state"]["plan_sha256"] + or queue.get("official_test_used") is not False + or queue.get("h2o_official_validation_used") is not False + ): + raise ValueError("HOT producer queue completion binding differs") + execution_path = Path(plan["cache_execution_plan"]["path"]) + execution = json.loads(execution_path.read_text(encoding="utf-8")) + worker = next(item for item in execution["workers"] if item["id"] == "hot3d") + expected_steps = [item["id"] for item in worker["steps"]] + if ( + primary.get("status") != "complete" + or primary.get("worker") != "hot3d" + or primary.get("plan_sha256") != plan["cache_execution_plan"]["sha256"] + or primary.get("completed_steps") != expected_steps + or primary.get("official_test_used") is not False + or primary.get("h2o_official_validation_used") is not False + ): + raise ValueError("HOT primary worker completion differs") + for step in worker["steps"]: + if step["id"].endswith("resume_verify") and not cache_step_complete(step, True): + raise ValueError(f"HOT deployable resume output differs: {step['id']}") + return queue, primary + + +def publish(plan_path: Path, plan: dict[str, Any]) -> bool: + completion = validate_primary(plan) + if completion is None: + return False + queue, primary = completion + release_path = Path(plan["release_state"]) + if release_path.is_file(): + existing = json.loads(release_path.read_text(encoding="utf-8")) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return True + raise ValueError("existing HOT cache release differs") + root = Path(plan["release_root"]) + files: list[dict[str, Any]] = [] + artifact_records = [] + for item in plan["artifacts"]: + records = inventory_tree(root, Path(item["path"])) + files.extend(records) + artifact_records.append({ + "id": item["id"], "path": item["path"], + "relative_path": str(Path(item["path"]).relative_to(root)), + "file_count": len(records), + "total_bytes": sum(record["bytes"] for record in records), + }) + relative_paths = [item["path"] for item in files] + if len(relative_paths) != len(set(relative_paths)): + raise ValueError("HOT release inventory contains duplicate paths") + release = { + "schema_version": "phase9_hot_cache_immutable_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), "release_root": str(root.resolve()), + "producer_queue_state": { + "path": str(Path(plan["producer_queue_state"]["path"]).resolve()), + "sha256": sha256(plan["producer_queue_state"]["path"]), + "completed_utc": queue.get("completed_utc"), + }, + "producer_worker_state": { + "path": str(Path(plan["producer_worker_state"]).resolve()), + "sha256": sha256(plan["producer_worker_state"]), + "value": primary, + }, + "artifacts": artifact_records, "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "single_deployable_manifest_writer": "original_resolution_cache_runner", + "live_reverse_sync_forbidden": True, + "read_only_after_receive": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(release_path, release) + os.chmod(release_path, 0o444) + return True + + +def fetch_remote_json(host: str, path: str, timeout: float) -> dict[str, Any] | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if completed.returncode: + return None + try: + value = json.loads(completed.stdout) + except json.JSONDecodeError: + return None + return value if isinstance(value, dict) else None + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or release.get("live_reverse_sync_forbidden") is not True + or release.get("read_only_after_receive") is not True + ): + raise ValueError("HOT immutable release contract differs") + paths = [item["path"] for item in release.get("files", [])] + if ( + len(paths) != len(set(paths)) + or len(paths) != release.get("file_count") + or sum(item["bytes"] for item in release["files"]) != release.get("total_bytes") + ): + raise ValueError("HOT immutable release inventory differs") + for value in paths: + relative = Path(value) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError(f"HOT immutable release path is unsafe: {relative}") + + +def write_external_proxy(plan: dict[str, Any], queue: dict[str, Any] | None) -> None: + state_path = Path(plan["local_worker_state"]) + state = read_json(state_path) + if state is None or state.get("status") == "complete": + return + backup = Path(plan["local_state_backup"]) + if not backup.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(state_path, backup) + os.chmod(backup, 0o444) + if state.get("plan_sha256") != plan["cache_execution_plan"]["sha256"]: + raise ValueError("local HOT proxy state binding differs") + state.update({ + "status": "waiting_for_server_new_immutable_release", + "updated_utc": utc_now(), "external_owner": "server_new", + "external_queue_status": (queue or {}).get("status", "unavailable"), + "external_queue_updated_utc": (queue or {}).get("updated_utc"), + "live_reverse_sync_forbidden": True, + "h2o_official_validation_used": False, "official_test_used": False, + }) + atomic_json(state_path, state) + + +def verify_staging(staging: Path, release: dict[str, Any]) -> None: + for item in release["files"]: + path = staging / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] or sha256(path) != item["sha256"] + ): + raise ValueError(f"received HOT cache file differs: {path}") + + +def install_artifacts(plan: dict[str, Any], release: dict[str, Any], staging: Path) -> list[dict[str, Any]]: + installed = [] + backup_root = Path(plan["receive_backup_root"]) + for item in release["artifacts"]: + destination = Path(item["path"]) + source = staging / item["relative_path"] + backup = backup_root / item["relative_path"] + if destination.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + if backup.exists(): + raise ValueError(f"HOT receive backup already exists: {backup}") + os.replace(destination, backup) + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination) + for path in destination.rglob("*"): + os.chmod(path, 0o555 if path.is_dir() else 0o444) + os.chmod(destination, 0o555) + installed.append({ + "id": item["id"], "path": str(destination.resolve()), + "backup": str(backup.resolve()) if backup.exists() else None, + "file_count": item["file_count"], "total_bytes": item["total_bytes"], + }) + return installed + + +def receive(plan_path: Path, plan: dict[str, Any], state_path: Path) -> bool: + timeout = float(plan["ssh_timeout_seconds"]) + queue = fetch_remote_json( + plan["remote_host"], plan["producer_queue_state"]["path"], timeout, + ) + release = fetch_remote_json(plan["remote_host"], plan["release_state"], timeout) + if release is None: + write_external_proxy(plan, queue) + atomic_json(state_path, { + "schema_version": "phase9_hot_cache_receive_state_v1", + "status": "waiting_for_server_new_immutable_release", + "updated_utc": utc_now(), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "remote_queue_status": (queue or {}).get("status", "unavailable"), + "h2o_official_validation_used": False, "official_test_used": False, + }) + return False + validate_release(plan_path, plan, release) + if (read_json(state_path) or {}).get("status") == "complete": + return True + staging = Path(plan["staging_root"]) + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".release_files.txt" + file_list.write_text("".join(item["path"] + "\n" for item in release["files"]), encoding="utf-8") + command = [ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['remote_host']}:{Path(plan['release_root']).resolve()}/", + f"{staging.resolve()}/", + ] + completed = subprocess.run(command, check=False) + if completed.returncode: + raise RuntimeError(f"HOT immutable rsync failed: {completed.returncode}") + verify_staging(staging, release) + installed = install_artifacts(plan, release, staging) + remote_state = release["producer_worker_state"]["value"] + state_temporary = Path(plan["local_worker_state"]).with_suffix(".remote.tmp") + state_temporary.write_text(json.dumps(remote_state, indent=2) + "\n", encoding="utf-8") + if sha256(state_temporary) != release["producer_worker_state"]["sha256"]: + state_temporary.unlink() + raise ValueError("HOT received worker state differs") + os.replace(state_temporary, plan["local_worker_state"]) + result = { + "schema_version": "phase9_hot_cache_receive_state_v1", + "status": "complete", "completed_utc": utc_now(), + "updated_utc": utc_now(), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), "release_state": plan["release_state"], + "release_file_count": release["file_count"], + "release_total_bytes": release["total_bytes"], "installed": installed, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, result) + return True + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--state", type=Path) + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1 and not args.once: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + state_path = Path(plan["release_state"] if args.role == "publish" else plan["receive_state"]) + if args.state and args.state.resolve() != state_path.resolve(): + parser.error("HOT cache bridge state path differs") + state_path.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{state_path}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + complete = publish(args.plan, plan) if args.role == "publish" else receive( + args.plan, plan, state_path, + ) + if complete or args.once: + print(json.dumps(read_json(state_path) or {"status": "waiting"}, indent=2)) + return + time.sleep(args.poll_seconds) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_hot_prefill_merge_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_hot_prefill_merge_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..0044df9b517929b1658514cfee1e03e7f397a52a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_hot_prefill_merge_queue.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Wait for frozen HOT prefill shards and merge them into the primary cache.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +import time + +from scripts.cache_phase7_hot3d import sha256 +from scripts.merge_phase9_hot_prefill import merge_prefills + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def prefill_complete(path: Path) -> bool: + report = path / "cache_report.json" + if not report.is_file(): + return False + value = json.loads(report.read_text(encoding="utf-8")) + return value.get("status") == "complete" and value.get("mode") == "staged_prefill" + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("prefill plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + prefill_dirs = [Path(item["output_dir"]) for item in plan["shards"]] + state = { + "schema_version": "phase9_hot_prefill_merge_queue_v1", + "status": "waiting_for_prefill", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing state belongs to another prefill plan") + if previous.get("status") == "complete": + print(json.dumps(previous, indent=2)) + return + state = previous + while not all(prefill_complete(path) for path in prefill_dirs): + state["status"] = "waiting_for_prefill" + state["ready_shards"] = [str(path) for path in prefill_dirs if prefill_complete(path)] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "merging" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + result = merge_prefills( + Path(plan["target_output_dir"]), prefill_dirs, Path(plan["merge_report"]), + ) + state.update({ + "status": "complete", "updated_utc": utc_now(), + "merge_report": str(Path(plan["merge_report"]).resolve()), + "merge_report_sha256": sha256(Path(plan["merge_report"])), + "linked": result["linked"], + "existing_identical": result["existing_identical"], + }) + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_hot_prefill_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_hot_prefill_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..404aa2ad2ed1207d4650a0580a92722f4073d778 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_hot_prefill_queue.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +"""Run disjoint HOT3D cache prefills, merge them, and resume the canonical writer.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.cache_phase7_hot3d import sha256 +from scripts.merge_phase9_hot_prefill import merge_prefills + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def command_value(command: list[str], option: str) -> str: + try: + return command[command.index(option) + 1] + except (ValueError, IndexError) as error: + raise ValueError(f"prefill command lacks {option}") from error + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("resolution_hw") != [512, 896] + ): + raise ValueError("HOT prefill plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"HOT prefill binding differs: {path}") + source = Path(plan["source_manifest"]["path"]) + if not source.is_file() or sha256(source) != plan["source_manifest"]["sha256"]: + raise ValueError("HOT prefill source manifest differs") + target = Path(plan["target_output_dir"]) + if target.parts[:2] != ("/", "SSD2"): + raise ValueError("HOT prefill target is not on /SSD2") + shards = plan["shards"] + ranges = [tuple(item["candidate_position_range"]) for item in shards] + expected_start = 0 + outputs: set[Path] = set() + for shard, (start, stop) in zip(shards, ranges, strict=True): + if start != expected_start or stop <= start: + raise ValueError("HOT prefill ranges are not a contiguous partition") + expected_start = stop + output = Path(shard["output_dir"]) + if output.parts[:2] != ("/", "SSD2") or output == target or output in outputs: + raise ValueError("HOT prefill output ownership differs") + outputs.add(output) + command = shard["command"] + if ( + command_value(command, "--output-dir") != str(output) + or command_value(command, "--source-manifest") != str(source) + or command_value(command, "--prefill-position-range") != str(start) + or command[command.index("--prefill-position-range") + 2] != str(stop) + or command[command.index("--target-hw") + 1:command.index("--target-hw") + 3] + != ["512", "896"] + or "--decode-all-candidates" not in command + ): + raise ValueError(f"HOT prefill command differs: {shard['id']}") + if expected_start != int(plan["full_candidate_clips"]): + raise ValueError("HOT prefill ranges do not cover the candidate order") + if len({item["id"] for item in shards}) != len(shards): + raise ValueError("HOT prefill shard IDs are not unique") + if Path(plan["state"]).resolve() == plan_path.resolve(): + raise ValueError("HOT prefill state collides with its plan") + + +def prefill_complete(shard: dict[str, Any], plan: dict[str, Any]) -> bool: + output = Path(shard["output_dir"]) + report_path = output / "cache_report.json" + manifest_path = output / "prefill_manifest.jsonl" + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + start, stop = shard["candidate_position_range"] + processed = int(report.get("clips", -1)) + len( + report.get("skipped_no_supervision", []) + ) + return ( + report.get("status") == "complete" + and report.get("mode") == "staged_prefill" + and report.get("official_test_used") is False + and report.get("resolution_hw") == plan["resolution_hw"] + and report.get("candidate_position_range") == [start, stop] + and report.get("full_candidate_clips") == plan["full_candidate_clips"] + and report.get("requested_target_clips") == plan["requested_target_clips"] + and report.get("candidate_source_indices_sha256") + == plan["candidate_source_indices_sha256"] + and report.get("source_manifest", {}).get("sha256") + == plan["source_manifest"]["sha256"] + and report.get("cache_manifest", {}).get("sha256") == sha256(manifest_path) + and processed == stop - start + ) + + +def shard_pid_matches(pid: int, shard: dict[str, Any]) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + start, stop = shard["candidate_position_range"] + return ( + "scripts.cache_phase7_hot3d" in command + and f"--prefill-position-range {start} {stop}" in command + and f"--output-dir {Path(shard['output_dir']).resolve()}" in command + ) + + +def primary_pid_matches(pid: int, plan: dict[str, Any]) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_resolution_cache_queue" in command + and "--worker hot3d" in command + and f"--state {Path(plan['primary_state']).resolve()}" in command + ) + + +def launch(command: list[str], log_path: Path) -> int: + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def runtime_command(shard: dict[str, Any]) -> list[str]: + command = list(shard["command"]) + if Path(shard["output_dir"]).exists() and "--resume" not in command: + command.append("--resume") + return command + + +def primary_status(plan: dict[str, Any]) -> str: + path = Path(plan["primary_state"]) + if not path.is_file(): + return "missing" + state = json.loads(path.read_text(encoding="utf-8")) + if ( + state.get("plan_sha256") != plan["cache_execution_plan"]["sha256"] + or state.get("worker") != "hot3d" + or state.get("official_test_used") is not False + ): + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("HOT prefill state path differs from plan") + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_hot_prefill_queue_v1", + "status": "prefilling", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "shards": {}, "primary": {}, + "h2o_official_validation_used": False, "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing HOT prefill state belongs to another plan") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + statuses: dict[str, str] = {} + for shard in plan["shards"]: + identifier = shard["id"] + complete = prefill_complete(shard, plan) + statuses[identifier] = "complete" if complete else "running" + if complete: + continue + previous = state.setdefault("shards", {}).get(identifier, {}) + pid = int(previous.get("pid", -1)) + if not shard_pid_matches(pid, shard): + attempts = int(previous.get("attempts", 0)) + 1 + command = runtime_command(shard) + pid = launch(command, Path(shard["log"])) + state["shards"][identifier] = { + "pid": pid, "attempts": attempts, + "launched_utc": utc_now(), "command": command, + } + state["shard_statuses"] = statuses + state["updated_utc"] = utc_now() + if all(status == "complete" for status in statuses.values()): + break + state["status"] = "prefilling" + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + merge_path = Path(plan["merge_report"]) + if merge_path.is_file(): + merge = json.loads(merge_path.read_text(encoding="utf-8")) + if merge.get("status") != "complete": + parser.error("existing HOT prefill merge report differs") + else: + state["status"] = "merging" + atomic_json(args.state, state) + merge = merge_prefills( + Path(plan["target_output_dir"]), + [Path(item["output_dir"]) for item in plan["shards"]], + merge_path, + ) + state["merge_report"] = { + "path": str(merge_path.resolve()), "sha256": sha256(merge_path), + "linked": merge["linked"], + "existing_identical": merge["existing_identical"], + } + while True: + status = primary_status(plan) + state["primary_status"] = status + if status == "complete": + break + if status.startswith("failed") and status != "failed_resumable": + state["status"] = "failed_primary_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + pid = int(state.setdefault("primary", {}).get("pid", -1)) + if not primary_pid_matches(pid, plan): + command = list(plan["primary_resume_command"]) + pid = launch(command, Path(plan["primary_log"])) + state["primary"] = { + "pid": pid, "launched_utc": utc_now(), "command": command, + } + state["status"] = "merged_waiting_for_canonical_writer" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_last2_candidate_controller.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_last2_candidate_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8a1689c26bf3c9735e969e1bf77208b7844390 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_last2_candidate_controller.py @@ -0,0 +1,510 @@ +#!/usr/bin/env python3 +"""Run or formally reject one ordered DINO Base last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_resolution_evaluation_controller import ( + hard_failure as evaluation_hard_failure, + launch_worker as launch_evaluation_worker, + pid_matches as evaluation_pid_matches, + should_launch as should_launch_evaluation, + worker_status, +) +from scripts.run_phase9_resolution_training_controller import ( + condition_status, + hard_failure as training_hard_failure, + pid_matches as training_pid_matches, +) +from scripts.run_phase9_shared_augmentation_training_controller import ( + launch_worker as launch_training_worker, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("candidate") not in {"5e7", "1e6"} + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("training_job_count") != 7 + or plan.get("evaluation_count") != 25 + or plan.get("evaluation_worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + ): + raise ValueError("last-2 candidate controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"last-2 candidate binding differs: {path}") + + +def admission(plan: dict[str, Any]) -> tuple[str, str, dict[str, Any] | None]: + state_path = Path(plan["admission_controller_state"]) + if not state_path.is_file(): + return "waiting", "upstream_state_missing", None + state = read_json(state_path) + report_path = Path(state.get("decision_report", {}).get("path", "")) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed"): + return "failed", "upstream_controller_failed", None + return "waiting", "upstream_controller_incomplete", None + if ( + state.get("plan_sha256") != plan["admission_controller_plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not report_path.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or report_path.resolve() + != Path(plan["admission_decision_report"]).resolve() + ): + return "failed", "upstream_decision_binding_differs", None + report = read_json(report_path) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + return "failed", "upstream_decision_isolation_differs", None + if plan["candidate"] == "5e7": + admitted = report.get("stage9_preceding_mechanism_gate", {}).get( + "stage9_last2_admitted" + ) is True + reason = ( + "preceding_mechanism_macro_and_worst_improved" + if admitted else "preceding_mechanism_gate_failed" + ) + else: + admitted = ( + report.get("candidate") == "5e7" + and report.get("gate", {}).get("macro_strictly_improved") is True + and report.get("gate", {}).get("worst_domain_strictly_improved") is True + and report.get("gate", {}).get("accepted") is True + ) + reason = "five_e7_strict_gate_passed" if admitted else "five_e7_gate_failed" + return ("admitted" if admitted else "rejected"), reason, report + + +def formal_rejection( + plan: dict[str, Any], reason: str, upstream: dict[str, Any], output: Path, +) -> dict[str, Any]: + return { + "schema_version": "phase9_last2_candidate_decision_v1", + "status": "complete", "candidate": plan["candidate"], + "created_utc": utc_now(), + "decision": f"not_admitted_last2_{plan['candidate']}", + "not_admitted_reason": reason, + "gate": { + "macro_strictly_improved": False, + "worst_domain_strictly_improved": False, + "accepted": False, + }, + "upstream_decision": { + "path": str(Path(plan["admission_decision_report"]).resolve()), + "sha256": sha256(plan["admission_decision_report"]), + }, + "training_started": False, + "evaluation_started": False, + "dino_large_admitted": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = read_json(args.plan) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("last-2 controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + static_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_last2_candidate_controller_state_v1", + "status": "waiting_for_admission", "candidate": plan["candidate"], + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "machine": machine, + "controller_pid": os.getpid(), + "training_workers": {}, "evaluation_workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = read_json(args.state) + if state.get("plan_sha256") != static_hash: + parser.error("existing last-2 controller state differs") + if state.get("machine") != machine: + parser.error("existing last-2 state belongs to another machine") + if state.get("status") in {"complete", "complete_local"}: + print(json.dumps(state, indent=2)) + return + while True: + admission_status, reason, upstream = admission(plan) + if admission_status == "waiting": + state["status"] = "waiting_for_admission" + state["waiting_reason"] = reason + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + if admission_status == "failed": + state["status"] = "failed_admission_binding" + state["failure"] = reason + atomic_json(args.state, state) + raise SystemExit(1) + break + + decision_path = Path(plan["decision_report"]) + if admission_status == "rejected": + assert upstream is not None + if machine != "taku3": + while not decision_path.is_file(): + state["status"] = "waiting_for_central_rejection_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["status"] = "complete_local" + state["admitted"] = False + state["decision_report"] = { + "path": str(decision_path.resolve()), + "sha256": sha256(decision_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + if not decision_path.exists(): + decision_path.parent.mkdir(parents=True, exist_ok=True) + atomic_json( + decision_path, + formal_rejection(plan, reason, upstream, decision_path), + ) + report = read_json(decision_path) + if ( + report.get("status") != "complete" + or report.get("candidate") != plan["candidate"] + or report.get("decision") + != f"not_admitted_last2_{plan['candidate']}" + or report.get("not_admitted_reason") != reason + or report.get("training_started") is not False + or report.get("evaluation_started") is not False + or report.get("upstream_decision", {}).get("sha256") + != sha256(plan["admission_decision_report"]) + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + state["status"] = "failed_rejection_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["admitted"] = False + state["decision"] = report["decision"] + state["decision_report"] = { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + } + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + registry = Path(plan["training_registry"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_last2_training_registry", + "--candidate", plan["candidate"], + "--stage8-controller-plan", plan["stage8_controller_plan"], + "--stage8-controller-state", plan["stage8_controller_state"], + "--last2-plan", plan["last2_plan"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), + "--state", plan["training_registry_state"], + ] + if plan["candidate"] == "1e6": + builder_command.extend(("--five-e7-decision", plan["admission_decision_report"])) + if machine == "taku3": + state["status"] = "building_training_registry" + state["training_builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_training_registry_builder" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + registry_hash = sha256(registry) + registry_payload = read_json(registry) + conditions = [item["condition"] for item in registry_payload["conditions"]] + owners = condition_owners(registry_payload, assignment) + if ( + registry_payload.get("candidate") != plan["candidate"] + or len(conditions) != plan["training_job_count"] + or len(set(conditions)) != len(conditions) + or registry_payload.get("official_test_used") is not False + ): + state["status"] = "failed_training_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_hash + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("training_workers", {}) + training_state_root = Path(plan["training_state_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = training_state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_hash) + statuses[condition] = status + if training_hard_failure(status) or status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["training_workers"].get(condition, {}).get("pid", -1) + ) + if not training_pid_matches(previous_pid, condition, registry): + pid = launch_training_worker( + condition, registry, condition_state, + Path(plan["training_log_root"]) / f"{condition.lower()}.log", + allowed_gpus, + ) + state["training_workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["training_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(training_hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + training_completion = { + "schema_version": "phase9_last2_training_completion_state_v1", + "status": "complete", "candidate": plan["candidate"], + "completed_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "training_registry": str(registry.resolve()), + "training_registry_sha256": registry_hash, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if machine == "taku3": + atomic_json(Path(plan["training_completion_state"]), training_completion) + else: + while not Path(plan["training_completion_state"]).is_file(): + state["status"] = "waiting_for_central_training_aggregate_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + eval_builder = [ + sys.executable, "-m", "scripts.build_phase9_last2_evaluation_plan", + "--candidate", plan["candidate"], + "--training-controller-plan", str(args.plan), + "--training-controller-state", plan["training_completion_state"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["evaluation_worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["evaluation_builder_command"] = eval_builder + atomic_json(args.state, state) + result = subprocess.run(eval_builder, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_hash = sha256(evaluation_plan) + dynamic = read_json(evaluation_plan) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["evaluation_worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = evaluation_hash + state["owned_evaluation_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("evaluation_workers", {}) + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + worker_state = Path(worker["state"]) + status = worker_status(worker_state, evaluation_hash) + statuses[worker["id"]] = status + if not should_launch_evaluation(worker, machine, status): + continue + previous_pid = int( + state["evaluation_workers"].get(worker["id"], {}).get("pid", -1) + ) + if not evaluation_pid_matches( + previous_pid, worker["id"], evaluation_plan, + ): + pid = launch_evaluation_worker( + evaluation_plan, worker, + Path(plan["evaluation_worker_log_root"]) / f"{worker['id']}.log", + ) + state["evaluation_workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["evaluation_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "training_workers": state["training_workers"], + "evaluation_workers": state["evaluation_workers"], + } + if any(evaluation_hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["admitted"] = True + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + if not decision_path.exists(): + command = [ + sys.executable, "-m", "scripts.summarize_phase9_last2_decision", + "--plan", str(evaluation_plan), "--output", str(decision_path), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = read_json(decision_path) + if ( + report.get("status") != "complete" + or report.get("candidate") != plan["candidate"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != evaluation_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["admitted"] = True + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["decision_report"] = { + "path": str(decision_path.resolve()), "sha256": sha256(decision_path), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_last2_resume_training.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_last2_resume_training.py new file mode 100644 index 0000000000000000000000000000000000000000..b169e799e229b526fefbaa79729dba29e9466d86 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_last2_resume_training.py @@ -0,0 +1,859 @@ +#!/usr/bin/env python3 +"""Freeze and supervise the resource-only Stage 9 1e-6 training resume.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import getpass +import hashlib +import json +import os +from pathlib import Path +import signal +import socket +import subprocess +import time +from typing import Any + + +SCHEMA = "phase9_last2_1e6_resume_training_amendment_v1" +STATE_SCHEMA = "phase9_last2_1e6_resume_training_supervisor_v1" +CONTROL_SCHEMA = "phase9_last2_1e6_resume_control_v1" +EXTERNAL_ROLES = {"loso_subject2", "loso_subject3", "lofamily_k"} +EXPECTED_ROLES = { + "full", + "loso_subject1", + "loso_subject2", + "loso_subject3", + "lofamily_h", + "lofamily_k", + "lofamily_o", +} +RESUMABLE_STATUSES = { + "missing", + "waiting_for_data", + "waiting_for_prerequisites", + "waiting_for_idle_gpu", + "running", + "failed_resumable", +} + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: str | Path, value: dict[str, Any]) -> None: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name( + f".{destination.name}.tmp.{os.getpid()}.{time.time_ns()}" + ) + with temporary.open("w", encoding="utf-8") as handle: + json.dump(value, handle, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, destination) + + +def binding(path: str | Path) -> dict[str, str]: + resolved = Path(path).resolve() + if not resolved.is_file(): + raise ValueError(f"binding is missing: {resolved}") + return {"path": str(resolved), "sha256": sha256(resolved)} + + +def validate_binding(value: dict[str, Any], label: str) -> Path: + path = Path(str(value.get("path", ""))) + digest = value.get("sha256") + if not path.is_file() or not isinstance(digest, str) or sha256(path) != digest: + raise ValueError(f"{label} binding differs: {path}") + return path + + +def process_command(pid: int) -> str | None: + try: + return Path(f"/proc/{pid}/cmdline").read_bytes().replace( + b"\0", b" " + ).decode("utf-8", errors="replace") + except (FileNotFoundError, PermissionError, ProcessLookupError): + return None + + +def matching_pids(*needles: str) -> list[int]: + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + command = process_command(int(entry.name)) + if command and all(needle in command for needle in needles): + matches.append(int(entry.name)) + return sorted(matches) + + +def world_adapter_active_pids(formal_root: str) -> list[int]: + runners = ( + "scripts.run_world_adapter_formal_training_v1", + "scripts.control_world_adapter_formal_evaluation_v1", + "scripts.train_phase7_external", + "scripts.evaluate_phase7_external", + ) + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + command = process_command(int(entry.name)) + if command and formal_root in command and any(item in command for item in runners): + matches.append(int(entry.name)) + return sorted(matches) + + +def validate_world_adapter_terminal( + amendment: dict[str, Any], *, require_inactive: bool = True +) -> None: + evidence = amendment["world_adapter_isolation"] + training_path = validate_binding(evidence["training_controller"], "WA training") + evaluation_path = validate_binding( + evidence["evaluation_controller"], "WA evaluation" + ) + report_path = validate_binding(evidence["comparison_report"], "WA comparison") + training = read_json(training_path) + evaluation = read_json(evaluation_path) + report = read_json(report_path) + if ( + training.get("status") != "training_complete_evaluation_locked" + or training.get("training_job_count") != 42 + or training.get("current_stage_complete") != 42 + or training.get("workers") != {} + or training.get("official_test_used") is not False + or evaluation.get("status") != "complete_report_only_no_promotion" + or evaluation.get("evaluation_job_count") != 150 + or evaluation.get("completed_evaluation_jobs") != 150 + or evaluation.get("workers") != {} + or evaluation.get("official_test_used") is not False + or report.get("status") != "complete_report_only_no_promotion" + ): + raise ValueError("World Adapter formal run is not terminal and isolated") + active = world_adapter_active_pids(evidence["formal_root"]) + if require_inactive and active: + raise RuntimeError(f"World Adapter workers are active: {active}") + + +def validate_original_plan_bindings(plan: dict[str, Any]) -> None: + for item in plan.get("bindings", []): + validate_binding(item, "original plan") + + +def role_owners(assignment: dict[str, Any]) -> dict[str, str]: + records = assignment["stage_condition_ownership"]["roles"] + owners = {item["role"]: item["owner"] for item in records} + if set(owners) != EXPECTED_ROLES or len(records) != len(owners): + raise ValueError("original distributed role ownership differs") + return owners + + +def freeze(args: argparse.Namespace) -> None: + output = args.output.resolve() + if output.exists(): + raise ValueError(f"amendment output already exists: {output}") + original_plan_path = args.original_plan.resolve() + original_state_path = args.original_state.resolve() + registry_path = args.training_registry.resolve() + assignment_path = args.distributed_assignment.resolve() + original_plan = read_json(original_plan_path) + original_state = read_json(original_state_path) + registry = read_json(registry_path) + assignment = read_json(assignment_path) + validate_original_plan_bindings(original_plan) + owners = role_owners(assignment) + plan_hash = sha256(original_plan_path) + registry_hash = sha256(registry_path) + if ( + original_plan.get("candidate") != "1e6" + or original_plan.get("training_registry") != str(registry_path) + or original_plan.get("distributed_assignment", {}).get("path") + != str(assignment_path) + or original_plan.get("distributed_assignment", {}).get("sha256") + != sha256(assignment_path) + or original_state.get("plan_sha256") != plan_hash + or original_state.get("training_registry_sha256") != registry_hash + or original_state.get("official_test_used") is not False + or registry.get("status") != "frozen_ready" + or registry.get("candidate") != "1e6" + or registry.get("backbone_learning_rate") != 1e-6 + or registry.get("target_step") != 405000 + or registry.get("official_test_used") is not False + or len(registry.get("conditions", [])) != 7 + ): + raise ValueError("original 1e-6 plan, state, or registry differs") + state_root = Path(original_plan["training_state_root"]).resolve() + mappings = [] + observed_roles = set() + for item in registry["conditions"]: + condition = item["condition"] + role = item["role"] + observed_roles.add(role) + logical_owner = owners[role] + if (role in EXTERNAL_ROLES) != (logical_owner == "server_new"): + raise ValueError(f"unexpected original owner for {role}") + config_path = validate_binding( + {"path": item["config"], "sha256": item["config_sha256"]}, + f"config {condition}", + ) + initialization = validate_binding( + { + "path": item["initialization_checkpoint"], + "sha256": item["initialization_checkpoint_sha256"], + }, + f"initialization {condition}", + ) + mappings.append( + { + "condition": condition, + "role": role, + "logical_owner": logical_owner, + "execution_owner": "taku3", + "priority": 0 if logical_owner == "taku3" else 1, + "config": str(config_path), + "config_sha256": item["config_sha256"], + "initialization_checkpoint": str(initialization), + "initialization_checkpoint_sha256": item[ + "initialization_checkpoint_sha256" + ], + "output_dir": item["output_dir"], + "state": str(state_root / f"{condition.lower()}.json"), + } + ) + if observed_roles != EXPECTED_ROLES: + raise ValueError("1e-6 registry roles differ") + created = utc_now() + value = { + "schema_version": SCHEMA, + "status": "frozen_training_approved", + "created_utc": created, + "candidate": "1e6", + "authorization": { + "status": "approved", + "authorized_by": args.authorized_by, + "authorized_utc": created, + "request": args.authorization_note, + }, + "repository": str(args.repository.resolve()), + "python": str(args.python.resolve()), + "orchestrator": binding(Path(__file__).resolve()), + "original_controller_plan": binding(original_plan_path), + "original_controller_state_after_fail_closed_restart": binding( + original_state_path + ), + "training_registry": binding(registry_path), + "distributed_assignment": binding(assignment_path), + "training_runner": binding(args.training_runner.resolve()), + "model_training_runner": binding(args.model_training_runner.resolve()), + "training_mappings": mappings, + "supervisor_state": str(args.supervisor_state.resolve()), + "training_completion_report": str(args.completion_report.resolve()), + "control_file": str(args.control_file.resolve()), + "scheduling": { + "physical_gpu_allowlist": [0, 1, 2, 3, 4, 5], + "max_concurrent_training_workers": 4, + "minimum_gpu_slots_reserved_for_world_adapter": 2, + "cpu_nice": 10, + "io_class": "best-effort", + "io_priority": 7, + "existing_taku3_conditions_first": True, + }, + "world_adapter_isolation": { + "formal_root": args.world_adapter_formal_root, + "training_controller": binding(args.world_adapter_training_state), + "evaluation_controller": binding(args.world_adapter_evaluation_state), + "comparison_report": binding(args.world_adapter_comparison_report), + "training_jobs_complete": 42, + "evaluation_jobs_complete": 150, + "automatic_model_promotion": False, + }, + "external_owner_preflight": { + "host": "taku-g2", + "checked_utc": args.external_owner_checked_utc, + "matching_1e6_process_count": args.external_owner_process_count, + "canonical_training_states_present": sum( + Path(item["state"]).is_file() + for item in mappings + if item["logical_owner"] == "server_new" + ), + }, + "original_controller_restart_result": { + "status": original_state.get("status"), + "gpu_training_started": False, + "reason": "registry builder rejected existing runs before worker launch", + }, + "resource_schedule_amendment_only": True, + "external_process_preemption_forbidden": True, + "external_processes_preempted": False, + "scientific_fields_changed": [], + "model_changed": False, + "data_changed": False, + "seed_changed": False, + "optimizer_changed": False, + "learning_rate_changed": False, + "horizon_changed": False, + "metric_changed": False, + "selection_gate_changed": False, + "evaluation_started": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + validate_world_adapter_terminal(value) + atomic_json(output, value) + os.chmod(output, 0o444) + print(json.dumps({"path": str(output), "sha256": sha256(output)}, indent=2)) + + +def validate_amendment(path: Path) -> tuple[dict[str, Any], dict[str, Any]]: + amendment = read_json(path) + false_fields = ( + "external_processes_preempted", + "model_changed", + "data_changed", + "seed_changed", + "optimizer_changed", + "learning_rate_changed", + "horizon_changed", + "metric_changed", + "selection_gate_changed", + "evaluation_started", + "h2o_official_validation_used", + "official_test_used", + ) + if ( + amendment.get("schema_version") != SCHEMA + or amendment.get("status") != "frozen_training_approved" + or amendment.get("candidate") != "1e6" + or amendment.get("authorization", {}).get("status") != "approved" + or amendment.get("resource_schedule_amendment_only") is not True + or amendment.get("external_process_preemption_forbidden") is not True + or amendment.get("scientific_fields_changed") != [] + or any(amendment.get(key) is not False for key in false_fields) + ): + raise ValueError("1e-6 resume amendment contract differs") + orchestrator = validate_binding(amendment["orchestrator"], "orchestrator") + if orchestrator.resolve() != Path(__file__).resolve(): + raise ValueError("running orchestrator path differs from amendment") + original_plan_path = validate_binding( + amendment["original_controller_plan"], "original controller plan" + ) + original_state_path = validate_binding( + amendment["original_controller_state_after_fail_closed_restart"], + "original controller state", + ) + registry_path = validate_binding(amendment["training_registry"], "registry") + assignment_path = validate_binding( + amendment["distributed_assignment"], "distributed assignment" + ) + validate_binding(amendment["training_runner"], "training runner") + validate_binding(amendment["model_training_runner"], "model training runner") + original_plan = read_json(original_plan_path) + original_state = read_json(original_state_path) + registry = read_json(registry_path) + assignment = read_json(assignment_path) + validate_original_plan_bindings(original_plan) + owners = role_owners(assignment) + if ( + original_plan.get("candidate") != "1e6" + or original_plan.get("training_registry") != str(registry_path) + or original_state.get("plan_sha256") != sha256(original_plan_path) + or original_state.get("training_registry_sha256") != sha256(registry_path) + or registry.get("status") != "frozen_ready" + or registry.get("candidate") != "1e6" + or registry.get("backbone_learning_rate") != 1e-6 + or registry.get("target_step") != 405000 + or len(registry.get("conditions", [])) != 7 + ): + raise ValueError("bound original 1e-6 artifacts differ") + schedule = amendment.get("scheduling", {}) + if ( + schedule.get("physical_gpu_allowlist") != [0, 1, 2, 3, 4, 5] + or schedule.get("max_concurrent_training_workers") != 4 + or schedule.get("minimum_gpu_slots_reserved_for_world_adapter") != 2 + or schedule.get("cpu_nice") != 10 + or schedule.get("io_priority") != 7 + ): + raise ValueError("1e-6/World Adapter scheduling isolation differs") + preflight = amendment.get("external_owner_preflight", {}) + if ( + preflight.get("host") != "taku-g2" + or preflight.get("matching_1e6_process_count") != 0 + or preflight.get("canonical_training_states_present") != 0 + ): + raise ValueError("external owner preflight does not permit G3 execution") + jobs = {item["condition"]: item for item in registry["conditions"]} + mappings = amendment.get("training_mappings", []) + if len(mappings) != 7 or len({item.get("condition") for item in mappings}) != 7: + raise ValueError("resume mappings must contain seven unique conditions") + state_root = Path(original_plan["training_state_root"]).resolve() + for mapping in mappings: + condition = mapping.get("condition") + job = jobs.get(condition) + role = mapping.get("role") + if ( + job is None + or role != job.get("role") + or mapping.get("logical_owner") != owners.get(role) + or mapping.get("execution_owner") != "taku3" + or mapping.get("config") != job.get("config") + or mapping.get("config_sha256") != job.get("config_sha256") + or mapping.get("initialization_checkpoint") + != job.get("initialization_checkpoint") + or mapping.get("output_dir") != job.get("output_dir") + or Path(mapping.get("state", "")).resolve() + != state_root / f"{condition.lower()}.json" + ): + raise ValueError(f"resume mapping differs: {condition}") + validate_binding( + {"path": mapping["config"], "sha256": mapping["config_sha256"]}, + f"mapped config {condition}", + ) + validate_world_adapter_terminal(amendment, require_inactive=False) + return amendment, registry + + +def queue_pids(mapping: dict[str, Any], registry: Path) -> list[int]: + return matching_pids( + "scripts.run_phase9_unified_train_queue", + f"--condition {mapping['condition']}", + str(registry.resolve()), + str(Path(mapping["state"]).resolve()), + ) + + +def training_child_pids(mapping: dict[str, Any]) -> list[int]: + return matching_pids( + "scripts.train_phase7_external", + f"--output-dir {mapping['output_dir']}", + f"--config {mapping['config']}", + ) + + +def state_status(mapping: dict[str, Any], registry_hash: str) -> str: + path = Path(mapping["state"]) + if not path.is_file(): + return "missing" + try: + value = read_json(path) + except (OSError, json.JSONDecodeError): + return "unreadable" + if ( + value.get("queue_sha256") != registry_hash + or value.get("condition") != mapping["condition"] + or value.get("official_test_used") is not False + ): + return "failed_state_binding" + return str(value.get("status", "missing")) + + +def control_requested(amendment_path: Path, amendment: dict[str, Any]) -> bool: + path = Path(amendment["control_file"]) + if not path.is_file(): + return False + value = read_json(path) + return ( + value.get("schema_version") == CONTROL_SCHEMA + and value.get("amendment_sha256") == sha256(amendment_path) + and value.get("status") == "pause_requested" + ) + + +def terminate_queues( + amendment: dict[str, Any], registry: Path, grace_seconds: float = 30.0 +) -> dict[str, Any]: + matched = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + signals = [] + for condition, pids in matched.items(): + for pid in pids: + try: + os.killpg(pid, signal.SIGTERM) + signals.append({"condition": condition, "pid": pid, "signal": "SIGTERM"}) + except ProcessLookupError: + pass + deadline = time.monotonic() + grace_seconds + while time.monotonic() < deadline: + remaining = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + if not any(remaining.values()): + return {"matched": matched, "signals": signals, "remaining": remaining} + time.sleep(0.5) + remaining = { + mapping["condition"]: queue_pids(mapping, registry) + for mapping in amendment["training_mappings"] + } + return {"matched": matched, "signals": signals, "remaining": remaining} + + +def launch_worker(amendment: dict[str, Any], mapping: dict[str, Any]) -> tuple[int, list[str]]: + schedule = amendment["scheduling"] + command = [ + "ionice", + "-c", + "2", + "-n", + str(schedule["io_priority"]), + "nice", + "-n", + str(schedule["cpu_nice"]), + amendment["python"], + "-m", + "scripts.run_phase9_unified_train_queue", + "--queue", + amendment["training_registry"]["path"], + "--condition", + mapping["condition"], + "--state", + mapping["state"], + "--poll-seconds", + "30", + "--allowed-physical-gpus", + ",".join(str(item) for item in schedule["physical_gpu_allowlist"]), + ] + log_path = Path(amendment["supervisor_state"]).parent / "training_logs" / ( + f"{mapping['condition'].lower()}.log" + ) + log_path.parent.mkdir(parents=True, exist_ok=True) + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, + cwd=amendment["repository"], + stdin=subprocess.DEVNULL, + stdout=log, + stderr=subprocess.STDOUT, + text=True, + start_new_session=True, + ) + return process.pid, command + + +def ensure_workers( + amendment: dict[str, Any], registry: dict[str, Any], state: dict[str, Any] +) -> dict[str, str]: + registry_path = Path(amendment["training_registry"]["path"]) + registry_hash = amendment["training_registry"]["sha256"] + mappings = sorted( + amendment["training_mappings"], key=lambda item: (item["priority"], item["condition"]) + ) + statuses = { + mapping["condition"]: state_status(mapping, registry_hash) + for mapping in mappings + } + terminal = { + condition: status + for condition, status in statuses.items() + if status not in RESUMABLE_STATUSES and status != "complete" + } + if terminal: + raise RuntimeError(f"terminal training state: {terminal}") + active = [] + for mapping in mappings: + pids = queue_pids(mapping, registry_path) + if len(pids) > 1: + raise RuntimeError(f"multiple queue writers: {mapping['condition']}={pids}") + if pids: + active.append(mapping["condition"]) + record = state.setdefault("workers", {}).setdefault(mapping["condition"], {}) + record["pid"] = pids[0] + record["adopted_utc"] = utc_now() + maximum = amendment["scheduling"]["max_concurrent_training_workers"] + slots = maximum - len(active) + if slots < 0: + raise RuntimeError(f"1e-6 worker cap exceeded: {len(active)} > {maximum}") + jobs = {item["condition"]: item for item in registry["conditions"]} + for mapping in mappings: + if slots <= 0 or statuses[mapping["condition"]] == "complete": + continue + if mapping["condition"] in active: + continue + children = training_child_pids(mapping) + if children: + raise RuntimeError( + f"orphan training child blocks relaunch: {mapping['condition']}={children}" + ) + job = jobs[mapping["condition"]] + if mapping["config_sha256"] != job["config_sha256"]: + raise ValueError(f"config changed before launch: {mapping['condition']}") + record = state.setdefault("workers", {}).setdefault( + mapping["condition"], {"launches": 0} + ) + launches = int(record.get("launches", 0)) + if launches >= 3: + raise RuntimeError(f"relaunch limit reached: {mapping['condition']}") + pid, command = launch_worker(amendment, mapping) + record.update( + { + "pid": pid, + "launches": launches + 1, + "launched_utc": utc_now(), + "command": command, + } + ) + active.append(mapping["condition"]) + slots -= 1 + print(f"launched {mapping['condition']} pid={pid}", flush=True) + state["active_conditions"] = active + state["reserved_gpu_slots"] = 6 - len(active) + if state["reserved_gpu_slots"] < amendment["scheduling"][ + "minimum_gpu_slots_reserved_for_world_adapter" + ]: + raise RuntimeError("World Adapter GPU reservation was violated") + return statuses + + +def validate_completion( + amendment_path: Path, amendment: dict[str, Any], registry: dict[str, Any] +) -> dict[str, Any]: + registry_hash = amendment["training_registry"]["sha256"] + jobs = {item["condition"]: item for item in registry["conditions"]} + completed = [] + for mapping in amendment["training_mappings"]: + state_path = Path(mapping["state"]) + value = read_json(state_path) + job = jobs[mapping["condition"]] + marker = value.get("last_completed", {}) + checkpoint = Path(str(marker.get("checkpoint", ""))) + if ( + value.get("status") != "complete" + or value.get("queue_sha256") != registry_hash + or value.get("condition") != mapping["condition"] + or value.get("official_test_used") is not False + or marker.get("completed_step") != 405000 + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or not checkpoint.is_file() + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or queue_pids(mapping, Path(amendment["training_registry"]["path"])) + or training_child_pids(mapping) + ): + raise ValueError(f"terminal training output differs: {mapping['condition']}") + completed.append( + { + "condition": mapping["condition"], + "role": mapping["role"], + "logical_owner": mapping["logical_owner"], + "execution_owner": "taku3", + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": marker["checkpoint_sha256"], + "state": str(state_path.resolve()), + "state_sha256": sha256(state_path), + } + ) + return { + "schema_version": "phase9_last2_1e6_resume_training_completion_v1", + "status": "training_complete_evaluation_not_started", + "completed_utc": utc_now(), + "amendment": {"path": str(amendment_path), "sha256": sha256(amendment_path)}, + "training_registry": amendment["training_registry"], + "conditions": completed, + "condition_count": 7, + "evaluation_started": False, + "scientific_fields_changed": [], + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def run(args: argparse.Namespace) -> None: + amendment_path = args.amendment.resolve() + amendment, registry = validate_amendment(amendment_path) + state_path = args.state.resolve() + if state_path != Path(amendment["supervisor_state"]).resolve(): + raise ValueError("supervisor state path differs from amendment") + state_path.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{state_path}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state = { + "schema_version": STATE_SCHEMA, + "status": "starting", + "started_utc": utc_now(), + "updated_utc": utc_now(), + "amendment": str(amendment_path), + "amendment_sha256": sha256(amendment_path), + "supervisor_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if state_path.is_file(): + previous = read_json(state_path) + if previous.get("amendment_sha256") != sha256(amendment_path): + raise ValueError("existing supervisor state belongs to another amendment") + if previous.get("status") == "complete": + print(json.dumps(previous, indent=2)) + return + state = previous + state["supervisor_pid"] = os.getpid() + state["resumed_utc"] = utc_now() + while True: + validate_world_adapter_terminal(amendment, require_inactive=False) + world_adapter_pids = world_adapter_active_pids( + amendment["world_adapter_isolation"]["formal_root"] + ) + if world_adapter_pids: + termination = terminate_queues( + amendment, Path(amendment["training_registry"]["path"]) + ) + state["status"] = "paused_for_world_adapter" + state["world_adapter_active_pids"] = world_adapter_pids + state["world_adapter_pause"] = termination + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if any(termination["remaining"].values()): + raise RuntimeError( + "some queue workers survived the World Adapter priority pause" + ) + return + if control_requested(amendment_path, amendment): + termination = terminate_queues( + amendment, Path(amendment["training_registry"]["path"]) + ) + state["status"] = "paused_by_manual_request" + state["pause"] = termination + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if any(termination["remaining"].values()): + raise RuntimeError("some queue workers survived the pause request") + return + statuses = ensure_workers(amendment, registry, state) + state["training_statuses"] = statuses + state["status"] = "training" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + if all(status == "complete" for status in statuses.values()): + report = validate_completion(amendment_path, amendment, registry) + report_path = Path(amendment["training_completion_report"]) + if report_path.is_file(): + raise ValueError(f"completion report already exists: {report_path}") + atomic_json(report_path, report) + os.chmod(report_path, 0o444) + state["status"] = "complete" + state["training_completion_report"] = binding(report_path) + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + print(json.dumps(state, indent=2)) + return + time.sleep(args.poll_seconds) + + +def control(args: argparse.Namespace) -> None: + amendment_path = args.amendment.resolve() + amendment, _ = validate_amendment(amendment_path) + path = Path(amendment["control_file"]) + value = { + "schema_version": CONTROL_SCHEMA, + "status": "pause_requested" if args.action == "pause" else "cleared", + "created_utc": utc_now(), + "requested_by": f"{getpass.getuser()}@{socket.gethostname()}", + "amendment": str(amendment_path), + "amendment_sha256": sha256(amendment_path), + "note": args.note, + } + atomic_json(path, value) + print(json.dumps({"path": str(path), "sha256": sha256(path)}, indent=2)) + + +def status(args: argparse.Namespace) -> None: + amendment, registry = validate_amendment(args.amendment.resolve()) + registry_hash = amendment["training_registry"]["sha256"] + statuses = { + item["condition"]: state_status(item, registry_hash) + for item in amendment["training_mappings"] + } + active = { + item["condition"]: queue_pids( + item, Path(amendment["training_registry"]["path"]) + ) + for item in amendment["training_mappings"] + } + print( + json.dumps( + { + "amendment_sha256": sha256(args.amendment), + "training_statuses": statuses, + "active_queue_pids": active, + "world_adapter_active_pids": world_adapter_active_pids( + amendment["world_adapter_isolation"]["formal_root"] + ), + "target_step": registry["target_step"], + }, + indent=2, + ) + ) + + +def parser() -> argparse.ArgumentParser: + result = argparse.ArgumentParser() + subparsers = result.add_subparsers(dest="command", required=True) + freeze_parser = subparsers.add_parser("freeze") + freeze_parser.add_argument("--original-plan", type=Path, required=True) + freeze_parser.add_argument("--original-state", type=Path, required=True) + freeze_parser.add_argument("--training-registry", type=Path, required=True) + freeze_parser.add_argument("--distributed-assignment", type=Path, required=True) + freeze_parser.add_argument("--repository", type=Path, required=True) + freeze_parser.add_argument("--python", type=Path, required=True) + freeze_parser.add_argument("--training-runner", type=Path, required=True) + freeze_parser.add_argument("--model-training-runner", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-formal-root", required=True) + freeze_parser.add_argument("--world-adapter-training-state", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-evaluation-state", type=Path, required=True) + freeze_parser.add_argument("--world-adapter-comparison-report", type=Path, required=True) + freeze_parser.add_argument("--external-owner-checked-utc", required=True) + freeze_parser.add_argument("--external-owner-process-count", type=int, required=True) + freeze_parser.add_argument("--authorized-by", required=True) + freeze_parser.add_argument("--authorization-note", required=True) + freeze_parser.add_argument("--supervisor-state", type=Path, required=True) + freeze_parser.add_argument("--completion-report", type=Path, required=True) + freeze_parser.add_argument("--control-file", type=Path, required=True) + freeze_parser.add_argument("--output", type=Path, required=True) + freeze_parser.set_defaults(function=freeze) + run_parser = subparsers.add_parser("run") + run_parser.add_argument("--amendment", type=Path, required=True) + run_parser.add_argument("--state", type=Path, required=True) + run_parser.add_argument("--poll-seconds", type=float, default=30.0) + run_parser.set_defaults(function=run) + status_parser = subparsers.add_parser("status") + status_parser.add_argument("--amendment", type=Path, required=True) + status_parser.set_defaults(function=status) + control_parser = subparsers.add_parser("control") + control_parser.add_argument("action", choices=("pause", "resume")) + control_parser.add_argument("--amendment", type=Path, required=True) + control_parser.add_argument("--note") + control_parser.set_defaults(function=control) + return result + + +def main() -> None: + args = parser().parse_args() + if getattr(args, "poll_seconds", 30.0) < 1: + raise ValueError("poll interval must be at least one second") + args.function(args) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_cache_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_cache_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..880a58c8892f00aa6bfa02fb81d2bf8683a0808c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_cache_queue.py @@ -0,0 +1,372 @@ +#!/usr/bin/env python3 +"""Run one winner-gated, resumable Phase 9 resolution cache worker.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def validate_plan_bindings(plan: dict[str, Any]) -> None: + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution execution plan lacks official-data isolation") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution plan binding differs: {path}") + validate_execution_contract(plan) + + +def validate_execution_contract(plan: dict[str, Any]) -> None: + root = Path(plan["physical_root"]) + output_directories = [Path(path) for path in plan["output_directories"]] + if len(output_directories) != len(set(output_directories)): + raise ValueError("resolution output directories are not unique") + if any(path != root and root not in path.parents for path in output_directories): + raise ValueError("resolution output directory is outside the physical root") + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("resolution physical root is not on /SSD2") + + worker_ids: set[str] = set() + owned_outputs: dict[Path, str] = {} + cache_steps: list[dict[str, Any]] = [] + for worker in plan["workers"]: + worker_id = worker["id"] + if worker_id in worker_ids: + raise ValueError(f"duplicate resolution worker: {worker_id}") + worker_ids.add(worker_id) + if Path(worker["state"]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution worker state is not on /SSD2: {worker_id}") + step_ids: set[str] = set() + for step in worker["steps"]: + if step["id"] in step_ids: + raise ValueError(f"duplicate step in resolution worker: {worker_id}") + step_ids.add(step["id"]) + if step["kind"] in {"cache", "sidecar"}: + output = Path(step["output_dir"]) + owner = owned_outputs.setdefault(output, worker_id) + if owner != worker_id: + raise ValueError(f"resolution output has multiple writers: {output}") + if step["kind"] == "cache": + cache_steps.append(step) + for command_name in ("start_command", "resume_command"): + command = step[command_name] + if command and not any( + command[index:index + 3] == ["--target-hw", "512", "896"] + for index in range(len(command) - 2) + ): + raise ValueError( + f"resolution cache command lacks 512x896 target: " + f"{worker_id}/{step['id']}/{command_name}" + ) + + cache_contracts = { + (item["manifest"], item["report"], int(item["clips"])) + for item in plan["caches"] + } + step_contracts = { + (step["manifest"], step["report"], int(step["expected_clips"])) + for step in cache_steps + } + if not cache_contracts <= step_contracts: + raise ValueError("resolution audit cache lacks a matching writer step") + + +def selection_winner(plan: dict[str, Any]) -> dict[str, Any] | None: + state_path = Path(plan["selection_state"]) + report_path = Path(plan["selection_report"]) + if not state_path.is_file() or not report_path.is_file(): + return None + state = json.loads(state_path.read_text(encoding="utf-8")) + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or state.get("winner") != report.get("winner") + or state.get("winner_checkpoint") != report.get("winner_checkpoint") + ): + return None + checkpoint = Path(report["winner_checkpoint"]["path"]) + config = Path(report["winner_config"]["path"]) + if ( + not checkpoint.is_file() + or sha256(checkpoint) != report["winner_checkpoint"]["sha256"] + or not config.is_file() + or sha256(config) != report["winner_config"]["sha256"] + ): + return None + return { + "winner": report["winner"], + "winner_checkpoint": report["winner_checkpoint"], + "winner_config": report["winner_config"], + } + + +def ensure_admission(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any] | None: + admission_path = Path(plan["admission_state"]) + admission_path.parent.mkdir(parents=True, exist_ok=True) + lock_path = Path(f"{admission_path}.lock") + with lock_path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if admission_path.is_file(): + admission = json.loads(admission_path.read_text(encoding="utf-8")) + if ( + admission.get("status") != "complete" + or admission.get("plan_sha256") != sha256(plan_path) + or admission.get("official_test_used") is not False + ): + raise ValueError("resolution admission state differs") + return admission + winner = selection_winner(plan) + if winner is None: + return None + root = Path(plan["physical_root"]) + if root.exists() or any(Path(path).exists() for path in plan["output_directories"]): + raise ValueError("resolution output exists before admission") + available_gib = shutil.disk_usage(root.parent).free / (1024 ** 3) + if available_gib < float(plan["minimum_available_gib"]): + raise ValueError("SSD2 free space is below the frozen admission minimum") + admission = { + "schema_version": "phase9_resolution_admission_v1", + "status": "complete", + "admitted_utc": utc_now(), + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "scientific_stage_admitted": True, + "trigger": "frozen_full_data_640_winner_complete", + "available_gib": available_gib, + **winner, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(admission_path, admission) + return admission + + +def cache_step_complete(step: dict[str, Any], require_resume: bool) -> bool: + report_path = Path(step["report"]) + manifest_path = Path(step["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + count = report.get("cached_clips", report.get("clips")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and tuple(report.get("resolution_hw", ())) == (512, 896) + and report.get("source_manifest", {}).get("sha256") + == step["source_manifest_sha256"] + and report.get("cache_manifest", {}).get("sha256") == sha256(manifest_path) + and int(count) == int(step["expected_clips"]) + and (not require_resume or report.get("resume_invocation") is True) + ) + + +def sidecar_step_complete(step: dict[str, Any]) -> bool: + report_path = Path(step["report"]) + manifest_path = Path(step["manifest"]) + if not report_path.is_file() or not manifest_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("base_cache_manifest", {}).get("sha256") + == sha256(step["base_manifest"]) + and report.get("augmented_cache_manifest", {}).get("sha256") + == sha256(manifest_path) + and int(report.get("clips", -1)) == int(step["expected_clips"]) + and report.get("right_valid_joint_count") == 0 + and float(report.get("root_norm_max_mm", 1.0)) < 1e-4 + and ( + not step.get("require_resume") + or report.get("resume_invocation") is True + ) + ) + + +def multifold_step_complete(step: dict[str, Any]) -> bool: + path = Path(step["index"]) + if not path.is_file(): + return False + index = json.loads(path.read_text(encoding="utf-8")) + return ( + index.get("status") == "complete" + and index.get("official_test_used") is False + and index.get("h2o_official_validation_used") is False + and index.get("source_cache_manifest", {}).get("sha256") + == sha256(step["source_manifest"]) + and len(index.get("folds", [])) == 6 + ) + + +def step_complete(step: dict[str, Any]) -> bool: + if step["kind"] == "cache": + return cache_step_complete(step, bool(step.get("require_resume"))) + if step["kind"] == "sidecar": + return sidecar_step_complete(step) + if step["kind"] == "multifold": + return multifold_step_complete(step) + raise ValueError(f"unsupported resolution step kind: {step['kind']}") + + +def runtime_command(step: dict[str, Any]) -> list[str]: + if step["kind"] == "cache": + output = Path(step["output_dir"]) + command = step["resume_command"] if output.exists() else step["start_command"] + elif step["kind"] == "sidecar": + output = Path(step["output_dir"]) + command = step["resume_command"] if output.exists() else step["start_command"] + else: + command = step["command"] + base_hash = sha256(step["base_manifest"]) if step.get("base_manifest") else None + return [base_hash if token == "{BASE_CACHE_SHA256}" else token for token in command] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan_bindings(plan) + except ValueError as error: + parser.error(str(error)) + workers = {worker["id"]: worker for worker in plan["workers"]} + if args.worker not in workers: + parser.error(f"unknown resolution worker: {args.worker}") + worker = workers[args.worker] + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("worker state path differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + state_lock = Path(f"{args.state}.lock").open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + plan_hash = sha256(args.plan) + state = { + "schema_version": "phase9_resolution_cache_worker_state_v1", + "status": "waiting_for_640_winner", + "worker": args.worker, + "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, + "started_utc": utc_now(), + "updated_utc": utc_now(), + "completed_steps": [], + "attempts": [], + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash or previous.get("worker") != args.worker: + parser.error("existing resolution state belongs to another plan/worker") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while True: + try: + admission = ensure_admission(args.plan, plan) + except ValueError as error: + state["status"] = "failed_admission" + state["failure"] = str(error) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + if admission is not None: + break + state["status"] = "waiting_for_640_winner" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + state["admission_state"] = plan["admission_state"] + state["admission_state_sha256"] = sha256(plan["admission_state"]) + state["winner"] = admission["winner"] + state["winner_checkpoint"] = admission["winner_checkpoint"] + state["winner_config"] = admission["winner_config"] + atomic_json(args.state, state) + for step in worker["steps"]: + if step["id"] in state["completed_steps"] and step_complete(step): + continue + if step.get("always_run") is not True and step_complete(step): + state["completed_steps"].append(step["id"]) + atomic_json(args.state, state) + continue + command = runtime_command(step) + log_path = args.state.parent / f"{args.worker}_{step['id']}.log" + attempt = { + "step": step["id"], "kind": step["kind"], + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_step"] = step["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ, PYTHONPATH=str(Path.cwd())) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode or not step_complete(step): + state["status"] = "failed_resumable" + state["failure"] = { + "step": step["id"], "returncode": result.returncode, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + if step["id"] not in state["completed_steps"]: + state["completed_steps"].append(step["id"]) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_cache_supervisor.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_cache_supervisor.py new file mode 100644 index 0000000000000000000000000000000000000000..8eddded62d805d7d1f45f69aa0d13b3d7ad675e9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_cache_supervisor.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Supervise owner-bound Stage 7 cache workers and the readiness finalizer.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def process_matches(tokens: list[str]) -> list[int]: + matches = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (OSError, UnicodeDecodeError): + continue + if all(token in command for token in tokens): + matches.append(int(entry.name)) + return sorted(matches) + + +def read_json(path: str | Path) -> dict[str, Any] | None: + candidate = Path(path) + if not candidate.is_file(): + return None + return json.loads(candidate.read_text(encoding="utf-8")) + + +def latest_progress(path: Path) -> dict[str, Any] | None: + if not path.is_file(): + return None + with path.open("rb") as handle: + handle.seek(0, os.SEEK_END) + size = handle.tell() + handle.seek(max(0, size - 256 * 1024)) + lines = handle.read().decode("utf-8", errors="replace").splitlines() + for line in reversed(lines): + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and any( + key in value for key in ("processed", "decoded", "cached", "clips") + ): + return value + return None + + +def classify_failure(state: dict[str, Any], transient_returncodes: set[int]) -> str: + status = str(state.get("status", "missing")) + if not status.startswith("failed"): + return "not_failed" + if status != "failed_resumable": + return "terminal_failure" + returncode = state.get("failure", {}).get("returncode") + if returncode == 0: + return "terminal_contract_mismatch" + if returncode in transient_returncodes: + return "known_transient_resumable" + return "terminal_unregistered_resumable" + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("owner") != "taku3" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution supervisor plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution supervisor binding differs: {path}") + execution = plan["cache_execution_plan"] + path = Path(execution["path"]) + if not path.is_file() or sha256(path) != execution["sha256"]: + raise ValueError("resolution supervisor cache execution plan differs") + ids = [worker["id"] for worker in plan["local_workers"]] + if len(ids) != len(set(ids)) or "hot3d" in ids: + raise ValueError("resolution supervisor local ownership differs") + if Path(plan["disk"]["path"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution supervisor disk is not /SSD2") + if Path(plan["state"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution supervisor state is not /SSD2") + + +def launch(command: list[str], log_path: Path) -> int: + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ, PYTHONPATH=str(Path.cwd())), + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def local_worker_snapshot( + worker: dict[str, Any], *, plan_hash: str, now: float, + transient_returncodes: set[int], +) -> dict[str, Any]: + state_path = Path(worker["state"]) + state = read_json(state_path) + controllers = process_matches(worker["process_tokens"]) + result: dict[str, Any] = { + "id": worker["id"], "owner": "taku3", + "state": str(state_path.resolve()), "controller_pids": controllers, + } + if state is None: + result.update(status="missing", classification="missing_state") + return result + if ( + state.get("worker") != worker["id"] + or state.get("plan_sha256") != plan_hash + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + result.update(status=state.get("status"), classification="terminal_binding_mismatch") + return result + attempt = state.get("attempts", [])[-1] if state.get("attempts") else {} + log_path = Path(attempt["log"]) if attempt.get("log") else None + state_mtime = state_path.stat().st_mtime + result.update({ + "status": state.get("status"), "current_step": state.get("current_step"), + "completed_steps": state.get("completed_steps", []), + "state_sha256": sha256(state_path), + "state_heartbeat_age_seconds": round(max(0.0, now - state_mtime), 3), + "classification": classify_failure(state, transient_returncodes), + "log": str(log_path.resolve()) if log_path else None, + "log_mtime_age_seconds": ( + round(max(0.0, now - log_path.stat().st_mtime), 3) + if log_path and log_path.is_file() else None + ), + "progress": latest_progress(log_path) if log_path else None, + }) + return result + + +def remote_json(host: str, path: str, timeout: float) -> dict[str, Any] | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if completed.returncode: + return None + try: + value = json.loads(completed.stdout) + except json.JSONDecodeError: + return None + return value if isinstance(value, dict) else None + + +def external_snapshot(external: dict[str, Any]) -> dict[str, Any]: + queue = remote_json( + external["host"], external["queue_state"], external["ssh_timeout_seconds"], + ) + release = remote_json( + external["host"], external["release_state"], external["ssh_timeout_seconds"], + ) + if queue is None: + return { + "id": external["id"], "owner": external["owner"], + "status": "remote_unreachable_or_state_missing", + "classification": "external_monitor_alert", + } + status = str(queue.get("status", "missing")) + if release and release.get("status") == "complete_immutable_release": + display_status = "immutable_release_ready" + elif status == "complete": + display_status = "waiting_for_immutable_release" + else: + display_status = "waiting_for_server_new_immutable_release" + return { + "id": external["id"], "owner": external["owner"], + "status": display_status, "queue_status": status, + "queue_updated_utc": queue.get("updated_utc"), + "shard_statuses": queue.get("shard_statuses", {}), + "release_status": release.get("status") if release else "missing", + "classification": "external_owned_monitor_only", + } + + +def alarms_for( + workers: list[dict[str, Any]], *, log_stale_seconds: float, +) -> list[dict[str, Any]]: + alarms = [] + for worker in workers: + classification = worker.get("classification") + if classification and classification.startswith("terminal"): + alarms.append({"worker": worker["id"], "reason": classification}) + if ( + worker.get("status") == "running" + and not worker.get("controller_pids") + ): + alarms.append({"worker": worker["id"], "reason": "running_state_without_controller"}) + age = worker.get("log_mtime_age_seconds") + if ( + worker.get("status") == "running" and age is not None + and age > log_stale_seconds + ): + alarms.append({"worker": worker["id"], "reason": "stale_progress_log", "age_seconds": age}) + return alarms + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=60.0) + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1 and not args.once: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("resolution supervisor state path differs") + execution_hash = plan["cache_execution_plan"]["sha256"] + transient = {int(value) for value in plan["known_transient_returncodes"]} + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + existing = read_json(args.state) or {} + recovery_attempts = dict(existing.get("recovery_attempts", {})) + while True: + now = time.time() + local = [ + local_worker_snapshot( + worker, plan_hash=execution_hash, now=now, + transient_returncodes=transient, + ) + for worker in plan["local_workers"] + ] + recoveries = [] + for worker, snapshot in zip(plan["local_workers"], local, strict=True): + restartable = ( + snapshot["classification"] == "known_transient_resumable" + or snapshot["status"] in worker.get("restartable_statuses", []) + ) + attempts = int(recovery_attempts.get(worker["id"], 0)) + if ( + restartable and not snapshot["controller_pids"] + and attempts < int(plan["max_exact_resume_attempts"]) + ): + pid = launch(worker["resume_command"], Path(worker["supervisor_log"])) + attempts += 1 + recovery_attempts[worker["id"]] = attempts + recoveries.append({ + "worker": worker["id"], "pid": pid, "attempt": attempts, + "kind": "exact_frozen_queue_resume", "launched_utc": utc_now(), + }) + external = [external_snapshot(item) for item in plan["external_workers"]] + finalizer = plan["finalizer"] + finalizer_pids = process_matches(finalizer["process_tokens"]) + readiness = read_json(finalizer["state"]) + blocking_failure = any( + str(worker.get("status", "")).startswith("failed") for worker in local + ) + finalizer_recovery = None + if ( + not finalizer_pids + and (readiness or {}).get("status") != "complete" + and not blocking_failure + ): + pid = launch(finalizer["command"], Path(finalizer["log"])) + finalizer_pids = [pid] + finalizer_recovery = { + "pid": pid, "kind": "readiness_finalizer_restart", + "launched_utc": utc_now(), + } + disk = shutil.disk_usage(plan["disk"]["path"]) + disk_record = { + "path": plan["disk"]["path"], + "free_gib": round(disk.free / (1024 ** 3), 3), + "total_gib": round(disk.total / (1024 ** 3), 3), + } + alarms = alarms_for( + local, log_stale_seconds=float(plan["log_stale_seconds"]), + ) + if disk_record["free_gib"] < float(plan["disk"]["minimum_free_gib"]): + alarms.append({"worker": "disk", "reason": "minimum_free_space_breached"}) + state = { + "schema_version": "phase9_resolution_cache_supervisor_state_v1", + "status": "alert" if alarms else "monitoring", + "updated_utc": utc_now(), "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), "local_workers": local, + "external_workers": external, + "readiness": { + "status": (readiness or {}).get("status", "missing"), + "updated_utc": (readiness or {}).get("updated_utc"), + "finalizer_pids": finalizer_pids, + "recovery": finalizer_recovery, + }, + "disk": disk_record, "alarms": alarms, + "recoveries_this_poll": recoveries, + "recovery_attempts": recovery_attempts, + "max_exact_resume_attempts": plan["max_exact_resume_attempts"], + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(args.state, state) + if args.once: + print(json.dumps(state, indent=2)) + return + time.sleep(args.poll_seconds) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_evaluation_controller.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..64ea48925512f43aa2084947f82545ea83ac8f44 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_evaluation_controller.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""Supervise Stage 7 evaluation workers and freeze the resolution decision.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or plan.get("evaluation_count") != 25 + or plan.get("worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + ): + raise ValueError("resolution evaluation controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution evaluation binding differs: {path}") + + +def training_complete(plan: dict[str, Any]) -> bool: + path = Path( + plan.get("training_controller_states", {}).get( + "taku3", plan["training_controller_state"] + ) + ) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + registry = Path(state.get("training_registry", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["training_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and registry.is_file() + and state.get("training_registry_sha256") == sha256(registry) + ) + + +def pid_matches(pid: int, worker: str, evaluation_plan: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_resolution_evaluation_worker" in command + and f"--worker {worker}" in command + and str(evaluation_plan.resolve()) in command + ) + + +def worker_status(path: Path, plan_sha256: str) -> str: + if not path.is_file(): + return "missing" + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_sha256: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def hard_failure(status: str) -> bool: + return status.startswith("failed") and status != "failed_resumable" + + +def should_launch(worker: dict[str, Any], machine: str, status: str) -> bool: + return ( + worker.get("owner") == machine + and status != "complete" + and not hard_failure(status) + ) + + +def launch_worker( + evaluation_plan: Path, worker: dict[str, Any], log_path: Path, +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_evaluation_worker", + "--plan", str(evaluation_plan.resolve()), "--worker", worker["id"], + "--state", worker["state"], "--poll-seconds", "30", + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("resolution evaluation controller state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + static_plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_evaluation_controller_state_v1", + "status": "waiting_for_resolution_training", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_plan_hash, + "machine": machine, + "controller_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != static_plan_hash: + parser.error("existing evaluation controller state differs") + if state.get("machine") != machine: + parser.error("existing evaluation state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not training_complete(plan): + state["status"] = "waiting_for_resolution_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_resolution_evaluation_plan", + "--training-controller-plan", plan["training_controller_plan"], + "--training-controller-state", plan["training_controller_state"], + "--cache-plan", plan["cache_execution_plan"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + evaluation_plan_hash = sha256(evaluation_plan) + dynamic = json.loads(evaluation_plan.read_text(encoding="utf-8")) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = evaluation_plan_hash + state["owned_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("workers", {}) + + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + worker_state = Path(worker["state"]) + status = worker_status(worker_state, evaluation_plan_hash) + statuses[worker["id"]] = status + if not should_launch(worker, machine, status): + continue + previous_pid = int( + state["workers"].get(worker["id"], {}).get("pid", -1) + ) + if not pid_matches(previous_pid, worker["id"], evaluation_plan): + pid = launch_worker( + evaluation_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "worker_processes": state["workers"], + } + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + decision = Path(plan["decision_report"]) + if not decision.exists(): + command = [ + sys.executable, "-m", "scripts.summarize_phase9_resolution_decision", + "--plan", str(evaluation_plan), + "--control-external-root", plan["control_external_root"], + "--control-fold-final-root", plan["control_fold_final_root"], + "--control-fold-milestone-root", plan["control_fold_milestone_root"], + "--output", str(decision), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = json.loads(decision.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != evaluation_plan_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["accepted_resolution_hw"] = report["accepted_resolution_hw"] + state["decision_report"] = { + "path": str(decision.resolve()), "sha256": sha256(decision), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_evaluation_resource_recovery.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_evaluation_resource_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..2edf205a25ace56f727b1148bf1478dc02fbc5fa --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_evaluation_resource_recovery.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Rebind one unstarted logical evaluation worker to an idle allowed GPU.""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.train_phase7_external import assert_physical_gpu_idle + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_amendment(path: Path, value: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + plan_path = Path(value.get("evaluation_plan", {}).get("path", "")) + controller_plan = Path(value.get("controller_plan", "")) + if ( + value.get("schema_version") != "phase9_resolution_evaluation_resource_amendment_v1" + or value.get("status") != "frozen" + or value.get("worker") != "server_new_gpu5" + or value.get("owner") != "server_new" + or value.get("planned_physical_gpu_id") != 5 + or value.get("replacement_physical_gpu_id") not in {0, 1, 2} + or value.get("evaluation_ids") + != ["loso_subject3_rgb_d_k", "lofamily_k_rgb_k"] + or value.get("requires_dynamic_idle_check") is not True + or value.get("external_process_preemption_forbidden") is not True + or value.get("scientific_fields_changed") != [] + or any(value.get(key) is not False for key in ( + "model_changed", "data_changed", "seed_changed", "metric_changed", + "selection_gate_changed", "official_test_used", + "h2o_official_validation_used", + )) + or not plan_path.is_file() + or sha256(plan_path) != value.get("evaluation_plan", {}).get("sha256") + or not controller_plan.is_file() + or sha256(controller_plan) != value.get("controller_plan_sha256") + ): + raise ValueError("resolution evaluation resource amendment differs") + plan = read_json(plan_path) + worker = next(item for item in plan["workers"] if item["id"] == value["worker"]) + if ( + worker.get("owner") != value["owner"] + or worker.get("physical_gpu_id") != value["planned_physical_gpu_id"] + or worker.get("evaluation_ids") != value["evaluation_ids"] + or worker.get("state") != value["original_state"] + or value["replacement_physical_gpu_id"] not in {0, 1, 2, 5} + or plan.get("official_test_used") is not False + ): + raise ValueError("resolution evaluation recovery worker binding differs") + if not path.is_file(): + raise ValueError("resolution evaluation resource amendment is unreadable") + return plan, worker + + +def imported_state( + recovery: dict[str, Any], amendment_path: Path, amendment: dict[str, Any], + original_plan_path: Path, +) -> dict[str, Any]: + if ( + recovery.get("status") != "complete" + or recovery.get("worker") != amendment["worker"] + or recovery.get("owner") != amendment["owner"] + or recovery.get("assigned_evaluation_ids") != amendment["evaluation_ids"] + or recovery.get("completed_ids") != amendment["evaluation_ids"] + or recovery.get("official_test_used") is not False + or recovery.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution evaluation recovery state differs") + return { + **recovery, + "schema_version": "phase9_resolution_evaluation_worker_state_v1", + "plan": str(original_plan_path.resolve()), + "plan_sha256": amendment["evaluation_plan"]["sha256"], + "physical_gpu_id": amendment["replacement_physical_gpu_id"], + "planned_physical_gpu_id": amendment["planned_physical_gpu_id"], + "resource_amendment": { + "path": str(amendment_path.resolve()), "sha256": sha256(amendment_path), + "reason": amendment["reason"], + }, + "source_recovery_state": { + "path": str(Path(amendment["recovery_state"]).resolve()), + "sha256": sha256(amendment["recovery_state"]), + }, + "imported_utc": utc_now(), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--amendment", type=Path, required=True) + args = parser.parse_args() + amendment = read_json(args.amendment) + try: + plan, worker = validate_amendment(args.amendment, amendment) + assert_physical_gpu_idle(amendment["replacement_physical_gpu_id"]) + except (ValueError, RuntimeError) as error: + parser.error(str(error)) + + original_state = Path(amendment["original_state"]) + backup = Path(amendment["original_state_backup"]) + if original_state.is_file(): + old = read_json(original_state) + if old.get("status") != "waiting_for_idle_gpu" or old.get("attempts") != []: + parser.error("logical GPU5 worker is not an unstarted waiter") + backup.parent.mkdir(parents=True, exist_ok=True) + if backup.exists() and sha256(backup) != sha256(original_state): + parser.error("logical GPU5 waiter backup differs") + if not backup.exists(): + shutil.copy2(original_state, backup) + os.chmod(backup, 0o444) + original_state.unlink() + + amended = deepcopy(plan) + amended_worker = next(item for item in amended["workers"] if item["id"] == amendment["worker"]) + amended_worker["physical_gpu_id"] = amendment["replacement_physical_gpu_id"] + amended_worker["state"] = amendment["recovery_state"] + amended["resource_schedule_amendment"] = { + "path": str(args.amendment.resolve()), "sha256": sha256(args.amendment), + } + recovery_plan = Path(amendment["recovery_plan"]) + if recovery_plan.exists() and read_json(recovery_plan) != amended: + parser.error("existing resolution evaluation recovery plan differs") + if not recovery_plan.exists(): + atomic_json(recovery_plan, amended) + os.chmod(recovery_plan, 0o444) + command = [ + sys.executable, "-m", "scripts.run_phase9_resolution_evaluation_worker", + "--plan", str(recovery_plan.resolve()), "--worker", amendment["worker"], + "--state", amendment["recovery_state"], "--poll-seconds", "30", + ] + result = subprocess.run(command, check=False) + if result.returncode: + raise SystemExit(result.returncode) + recovery = read_json(amendment["recovery_state"]) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if any(not evaluation_complete(evaluations[identifier]) for identifier in amendment["evaluation_ids"]): + raise ValueError("resolution evaluation recovery output differs") + imported = imported_state( + recovery, args.amendment, amendment, + Path(amendment["evaluation_plan"]["path"]), + ) + temporary = original_state.with_suffix(".importing") + atomic_json(temporary, imported) + os.replace(temporary, original_state) + controller_command = [ + sys.executable, "-u", "-m", "scripts.run_phase9_resolution_evaluation_controller", + "--plan", amendment["controller_plan"], "--state", amendment["controller_state"], + "--machine", "server_new", "--poll-seconds", "30", + ] + with Path(amendment["controller_log"]).open("a", encoding="utf-8") as log: + process = subprocess.Popen( + controller_command, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + print(json.dumps({ + "status": "complete", "imported_state": str(original_state.resolve()), + "imported_state_sha256": sha256(original_state), + "controller_pid": process.pid, "completed_utc": utc_now(), + "official_test_used": False, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_evaluation_worker.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_evaluation_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..71abe7979fd0b9d390223e80008f859de2a7200b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_evaluation_worker.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +"""Run one fixed-GPU shard of Stage 7 resolution evaluations.""" + +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import time +from typing import Any, Iterator + +from scripts.phase9_distributed_assignment import ( + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +@contextmanager +def output_lock(output: Path) -> Iterator[None]: + output.parent.mkdir(parents=True, exist_ok=True) + path = output.parent / f".{output.name}.resolution-evaluation.lock" + with path.open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + yield + + +def evaluation_complete(item: dict[str, Any]) -> bool: + report_path = Path(item["output_dir"]) / "evaluation.json" + if not report_path.is_file(): + return False + report = json.loads(report_path.read_text(encoding="utf-8")) + bindings_match = ( + report.get("status") == f"evaluated_{item['evaluation_role']}" + and report.get("evaluation_role") == item["evaluation_role"] + and report.get("input_mode") == item["input_mode"] + and report.get("checkpoint", {}).get("path") == item["checkpoint"] + and report.get("checkpoint", {}).get("sha256") + == item["checkpoint_sha256"] + and report.get("config", {}).get("path") == item["config"] + and report.get("config", {}).get("sha256") == item["config_sha256"] + and report.get("cache_manifest", {}).get("path") + == item["cache_manifest"] + and report.get("cache_manifest", {}).get("sha256") + == item["cache_manifest_sha256"] + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + ) + if not bindings_match: + return False + for key in ("raw_predictions", "per_hand_rows", "take_metrics"): + artifact = report.get(key, {}) + path = Path(str(artifact.get("path", ""))) + if not path.is_file() or artifact.get("sha256") != sha256(path): + return False + return ( + isinstance(report.get("clips"), int) and report["clips"] > 0 + and isinstance(report.get("frames"), int) and report["frames"] > 0 + ) + + +def validate_inputs(items: list[dict[str, Any]]) -> None: + expected: dict[Path, str] = {} + for item in items: + for path_key, hash_key in ( + ("config", "config_sha256"), + ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256"), + ): + path = Path(item[path_key]) + digest = item[hash_key] + if path in expected and expected[path] != digest: + raise ValueError(f"evaluation input has conflicting hashes: {path}") + expected[path] = digest + for path, digest in expected.items(): + if not path.is_file() or sha256(path) != digest: + raise ValueError(f"resolution evaluation input differs: {path}") + + +def evaluation_command( + item: dict[str, Any], gpu: int, heartbeat_path: Path | None = None, + heartbeat_seconds: float = 30.0, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), "--bootstrap-resamples", "2000", + "--evaluation-role", item["evaluation_role"], + ] + if heartbeat_path is not None: + command.extend(( + "--evaluation-id", item["id"], + "--heartbeat-path", str(heartbeat_path.resolve()), + "--heartbeat-seconds", str(heartbeat_seconds), + )) + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def process_command(pid: int) -> str | None: + path = Path(f"/proc/{pid}/cmdline") + try: + return path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (FileNotFoundError, PermissionError, ProcessLookupError, UnicodeDecodeError): + return None + + +def evaluator_pid_matches(pid: int, item: dict[str, Any]) -> bool: + command = process_command(pid) + return bool( + command + and "scripts.evaluate_phase7_external" in command + and f"--evaluation-id {item['id']}" in command + and f"--output-dir {item['output_dir']}" in command + and f"--checkpoint {item['checkpoint']}" in command + ) + + +def process_descendants(pid: int) -> list[int]: + observed: set[int] = set() + pending = [pid] + while pending: + parent = pending.pop() + path = Path(f"/proc/{parent}/task/{parent}/children") + try: + children = [int(value) for value in path.read_text().split()] + except (FileNotFoundError, PermissionError, ProcessLookupError, ValueError): + children = [] + for child in children: + if child not in observed: + observed.add(child) + pending.append(child) + return sorted(observed) + + +def validate_progress_heartbeat( + path: Path, item: dict[str, Any], evaluator_pid: int, +) -> dict[str, Any]: + value = json.loads(path.read_text(encoding="utf-8")) + if ( + value.get("schema_version") != "phase9_evaluation_progress_heartbeat_v1" + or value.get("evaluation_id") != item["id"] + or value.get("evaluator_pid") != evaluator_pid + or value.get("output_dir") != str(Path(item["output_dir"]).resolve()) + or value.get("official_test_used") is not False + or value.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution evaluator heartbeat differs: {item['id']}") + return value + + +def terminate_owned_process(process: subprocess.Popen[str]) -> None: + if process.poll() is not None: + return + try: + os.killpg(process.pid, 15) + except ProcessLookupError: + return + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, 9) + except ProcessLookupError: + pass + process.wait(timeout=15) + + +def run_evaluation_child( + *, command: list[str], environment: dict[str, str], log_path: Path, + heartbeat_path: Path, item: dict[str, Any], state: dict[str, Any], + state_path: Path, worker_heartbeat_seconds: float, + stall_timeout_seconds: float, +) -> tuple[int, str | None]: + started = time.monotonic() + last_progress = started + last_heartbeat_write = 0.0 + with log_path.open("a", encoding="utf-8") as log: + process = subprocess.Popen( + command, env=environment, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + state["child"] = { + "pid": process.pid, "evaluation_id": item["id"], + "command": command, "started_utc": utc_now(), + } + atomic_json(state_path, state) + failure: str | None = None + try: + while process.poll() is None: + now = time.monotonic() + if not evaluator_pid_matches(process.pid, item): + failure = "evaluator_pid_or_cmdline_differs" + terminate_owned_process(process) + break + progress = None + if heartbeat_path.is_file(): + progress = validate_progress_heartbeat( + heartbeat_path, item, process.pid, + ) + age = time.time() - heartbeat_path.stat().st_mtime + last_progress = now - max(0.0, age) + if now - last_progress > stall_timeout_seconds: + failure = "evaluator_progress_stalled" + terminate_owned_process(process) + break + if now - last_heartbeat_write >= worker_heartbeat_seconds: + state["heartbeat"] = { + "updated_utc": utc_now(), "worker_pid": os.getpid(), + "evaluator_pid": process.pid, + "evaluator_cmdline_verified": True, + "descendant_pids": process_descendants(process.pid), + "log_mtime": log_path.stat().st_mtime, + "progress": progress, + "stall_timeout_seconds": stall_timeout_seconds, + } + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + last_heartbeat_write = now + time.sleep(min(5.0, worker_heartbeat_seconds)) + except Exception: + terminate_owned_process(process) + raise + returncode = process.wait() + return returncode, failure + + +def claim_when_idle(gpu: int, state: dict[str, Any], state_path: Path, poll: float) -> None: + while True: + try: + idle = assert_physical_gpu_idle(gpu) is None + except RuntimeError: + idle = False + if idle and claim_physical_gpu(gpu): + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + else: + return + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(state_path, state) + time.sleep(poll) + + +def archive_incomplete_output( + item: dict[str, Any], state: dict[str, Any], state_path: Path, +) -> None: + output = Path(item["output_dir"]) + if not output.exists() or not any(output.iterdir()): + return + root = state_path.parent / "failed_outputs" / item["id"] + root.mkdir(parents=True, exist_ok=True) + destination = root / f"attempt_{len(state['attempts']):03d}" + if destination.exists(): + raise ValueError(f"incomplete evaluation archive already exists: {destination}") + shutil.move(str(output), str(destination)) + state.setdefault("archived_incomplete_outputs", []).append({ + "id": item["id"], "source": str(output.resolve()), + "archive": str(destination.resolve()), "archived_utc": utc_now(), + }) + atomic_json(state_path, state) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if ( + plan.get("status") != "frozen_ready" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + ): + parser.error("resolution evaluation plan is not frozen and isolated") + workers = {item["id"]: item for item in plan["workers"]} + if args.worker not in workers: + parser.error("unknown resolution evaluation worker") + worker = workers[args.worker] + try: + assignment = load_assignment(plan) + machine = detect_machine(assignment, None) + except ValueError as error: + parser.error(str(error)) + if worker.get("owner") != machine: + parser.error("evaluation worker is externally owned on this host") + if worker.get("physical_gpu_id") not in gpu_allowlist(assignment, machine): + parser.error("evaluation worker GPU is not allowed on this host") + if Path(worker["state"]).resolve() != args.state.resolve(): + parser.error("resolution evaluation worker state differs from plan") + evaluations = {item["id"]: item for item in plan["evaluations"]} + items = [evaluations[identifier] for identifier in worker["evaluation_ids"]] + try: + validate_inputs(items) + except ValueError as error: + parser.error(str(error)) + + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_evaluation_worker_state_v1", + "status": "running", "worker": args.worker, + "physical_gpu_id": worker["physical_gpu_id"], + "owner": machine, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "assigned_evaluation_ids": worker["evaluation_ids"], + "completed_ids": [], "attempts": [], + "worker_pid": os.getpid(), + "started_utc": utc_now(), "updated_utc": utc_now(), + "resource_amendment": "user_authorized_idle_gpus_0_5_20260730", + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if ( + state.get("plan_sha256") != plan_hash + or state.get("worker") != args.worker + or state.get("owner") != machine + or state.get("assigned_evaluation_ids") != worker["evaluation_ids"] + ): + parser.error("existing evaluation worker state differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + gpu = int(worker["physical_gpu_id"]) + for item in items: + if evaluation_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + with output_lock(Path(item["output_dir"])): + if evaluation_complete(item): + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + atomic_json(args.state, state) + continue + prior_attempts = sum( + attempt.get("id") == item["id"] + for attempt in state["attempts"] + ) + if prior_attempts >= plan["max_attempts_per_evaluation"]: + state["status"] = "failed_terminal_attempt_limit" + state["failure"] = { + "id": item["id"], "attempts": prior_attempts, + "reason": "maximum exact-resume attempts exhausted", + } + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(1) + archive_incomplete_output(item, state, args.state) + claim_when_idle(gpu, state, args.state, args.poll_seconds) + heartbeat_path = Path(item["output_dir"]) / "evaluation_heartbeat.json" + command = evaluation_command( + item, gpu, heartbeat_path, + plan["evaluator_progress_heartbeat_seconds"], + ) + log_path = args.state.parent / "logs" / f"{item['id']}.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "id": item["id"], "start_utc": utc_now(), + "physical_gpu_id": gpu, "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_evaluation"] = item["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + returncode, failure = run_evaluation_child( + command=command, environment=environment, + log_path=log_path, heartbeat_path=heartbeat_path, + item=item, state=state, state_path=args.state, + worker_heartbeat_seconds=plan["worker_heartbeat_seconds"], + stall_timeout_seconds=plan["stall_timeout_seconds"], + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = returncode + attempt["supervisor_failure"] = failure + state["updated_utc"] = utc_now() + if returncode or failure or not evaluation_complete(item): + attempt_count = sum( + value.get("id") == item["id"] + for value in state["attempts"] + ) + state["status"] = ( + "failed_terminal_attempt_limit" + if attempt_count >= plan["max_attempts_per_evaluation"] + else "failed_resumable" + ) + state["failure"] = { + "id": item["id"], "returncode": returncode, + "supervisor_failure": failure, + "attempts": attempt_count, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(returncode or 1) + state["completed_ids"].append(item["id"]) + state.pop("child", None) + state.pop("failure", None) + atomic_json(args.state, state) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_training_controller.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..d6998ea02b27bfb0fc1d9a1c08cff8d426138ced --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_resolution_training_controller.py @@ -0,0 +1,268 @@ +#!/usr/bin/env python3 +"""Admit and supervise matched Phase 9 resolution training jobs.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or float(plan.get("worst_domain_relative_regression_limit", -1)) != 0.01 + ): + raise ValueError("resolution training controller contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution training binding differs: {path}") + + +def readiness_complete(plan: dict[str, Any]) -> bool: + path = Path(plan["readiness_state"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + audit = Path(state.get("audit", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["cache_execution_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and audit.is_file() + and state.get("audit", {}).get("sha256") == sha256(audit) + ) + + +def pid_matches(pid: int, condition: str, registry: Path) -> bool: + path = Path(f"/proc/{pid}/cmdline") + if not path.is_file(): + return False + try: + command = path.read_bytes().replace(b"\0", b" ").decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + return ( + "scripts.run_phase9_unified_train_queue" in command + and f"--condition {condition}" in command + and str(registry.resolve()) in command + ) + + +def condition_status(state_path: Path, registry_sha256: str) -> str: + if not state_path.is_file(): + return "missing" + state = json.loads(state_path.read_text(encoding="utf-8")) + if state.get("queue_sha256") != registry_sha256: + return "failed_state_binding" + return str(state.get("status", "missing")) + + +def hard_failure(status: str) -> bool: + return status.startswith("failed") and status != "failed_resumable" + + +def launch_worker( + condition: str, registry: Path, state_path: Path, log_path: Path, + allowed_gpus: list[int], +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry.resolve()), "--condition", condition, + "--state", str(state_path.resolve()), "--poll-seconds", "30", + "--allowed-physical-gpus", ",".join(str(gpu) for gpu in allowed_gpus), + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), + stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("resolution training controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_resolution_training_controller_state_v1", + "status": "waiting_for_cache_readiness", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "machine": machine, + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing controller state belongs to another plan") + if state.get("machine") != machine: + parser.error("existing controller state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not readiness_complete(plan): + state["status"] = "waiting_for_cache_readiness" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry = Path(plan["training_registry"]) + builder_state = Path(plan["registry_builder_state"]) + builder_command = [ + sys.executable, "-m", "scripts.build_phase9_resolution_training_registry", + "--selection-report", plan["selection_report"], + "--readiness-state", plan["readiness_state"], + "--cache-plan", plan["cache_execution_plan"], + "--unified-queue", plan["unified_training_queue"], + "--fold-queue", plan["fold_training_queue"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), "--state", str(builder_state), + ] + if machine == "taku3": + state["status"] = "building_registry" + state["builder_command"] = builder_command + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_registry_builder" + state["builder_returncode"] = result.returncode + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry_sha256 = sha256(registry) + registry_payload = json.loads(registry.read_text(encoding="utf-8")) + conditions = [item["condition"] for item in registry_payload["conditions"]] + owners = condition_owners(registry_payload, assignment) + if ( + len(conditions) != 7 + or len(set(conditions)) != 7 + or registry_payload.get("gate", {}).get( + "worst_domain_relative_regression_limit" + ) != plan["worst_domain_relative_regression_limit"] + or registry_payload.get("official_test_used") is not False + ): + state["status"] = "failed_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_sha256 + state["conditions"] = conditions + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("workers", {}) + + state_root = Path(plan["training_state_root"]) + log_root = Path(plan["training_log_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_sha256) + statuses[condition] = status + if hard_failure(status): + continue + if status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["workers"].get(condition, {}).get("pid", -1) + ) + if not pid_matches(previous_pid, condition, registry): + pid = launch_worker( + condition, registry, condition_state, + log_root / f"{condition.lower()}.log", + allowed_gpus, + ) + state["workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["condition_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + state["status"] = "complete" if machine == "taku3" else "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_selection_binding_recovery.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_selection_binding_recovery.py new file mode 100644 index 0000000000000000000000000000000000000000..1de788859399ebc11c495022e81815866e615f7d --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_selection_binding_recovery.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python3 +"""Run one disjoint Phase 9 selection-binding recovery worker.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import shutil +import socket +import subprocess +import sys +import time +from typing import Any + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def json_sha256(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def validate_input(path: str, expected_sha256: str, label: str) -> None: + candidate = Path(path) + if not candidate.is_file() or sha256(candidate) != expected_sha256: + raise ValueError(f"selection recovery {label} differs: {candidate}") + + +def validate_recovered_output(item: dict[str, Any]) -> dict[str, Any]: + output = Path(item["output_dir"]) + report_path = output / "evaluation.json" + if not report_path.is_file(): + raise ValueError(f"selection recovery report missing: {item['id']}") + report = json.loads(report_path.read_text(encoding="utf-8")) + expected_bindings = { + "config": (item["config"], item["config_sha256"]), + "checkpoint": (item["checkpoint"], item["checkpoint_sha256"]), + "cache_manifest": ( + item["cache_manifest"], item["cache_manifest_sha256"], + ), + } + for key, (path, digest) in expected_bindings.items(): + binding = report.get(key, {}) + if ( + Path(str(binding.get("path", ""))).resolve() != Path(path).resolve() + or binding.get("sha256") != digest + ): + raise ValueError( + f"selection recovery {key} binding differs: {item['id']}" + ) + if ( + report.get("status") != "evaluated_phase9_h2o_fold_heldout" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or { + key: report.get(key) + for key in ("clips", "frames", "hands_rows") + } != item["expected_sample_counts"] + ): + raise ValueError(f"selection recovery role/sample contract differs: {item['id']}") + expected = item["expected_determinism"] + artifacts = { + "raw_predictions": expected["raw_predictions_sha256"], + "per_hand_rows": expected["per_hand_rows_sha256"], + "take_metrics": expected["take_metrics_sha256"], + } + for key, expected_hash in artifacts.items(): + binding = report.get(key, {}) + path = Path(str(binding.get("path", ""))) + if ( + binding.get("sha256") != expected_hash + or not path.is_file() + or sha256(path) != expected_hash + ): + raise ValueError( + f"selection recovery deterministic artifact differs: " + f"{item['id']}:{key}" + ) + if ( + json_sha256(report.get("metrics")) != expected["metrics_sha256"] + or json_sha256(report.get("grouped_bootstrap_ci")) + != expected["grouped_bootstrap_ci_sha256"] + ): + raise ValueError(f"selection recovery deterministic metrics differ: {item['id']}") + return { + "report": str(report_path.resolve()), + "report_sha256": sha256(report_path), + "sample_counts": item["expected_sample_counts"], + "metrics_sha256": expected["metrics_sha256"], + "raw_predictions_sha256": expected["raw_predictions_sha256"], + } + + +def archive_incomplete_output(item: dict[str, Any]) -> str | None: + output = Path(item["output_dir"]) + if not output.exists() or not any(output.iterdir()): + return None + root = output.parents[3] / "incomplete_outputs" + root.mkdir(parents=True, exist_ok=True) + suffix = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") + destination = root / f"{item['id']}.{suffix}" + shutil.move(str(output), str(destination)) + return str(destination.resolve()) + + +def evaluation_command(item: dict[str, Any], gpu: int, bootstrap: int) -> list[str]: + command = [ + sys.executable, "-m", "scripts.evaluate_phase7_external", + "--config", item["config"], + "--checkpoint", item["checkpoint"], + "--expected-checkpoint-sha256", item["checkpoint_sha256"], + "--cache-manifest", item["cache_manifest"], + "--expected-cache-manifest-sha256", item["cache_manifest_sha256"], + "--input-mode", item["input_mode"], + "--output-dir", item["output_dir"], + "--physical-gpu-id", str(gpu), + "--bootstrap-resamples", str(bootstrap), + "--evaluation-role", item["evaluation_role"], + ] + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--owner", choices=("taku3", "server_new"), required=True) + parser.add_argument("--worker", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + assignment_path = Path(plan["distributed_assignment"]["path"]) + if ( + plan.get("official_test_used") is not False + or not assignment_path.is_file() + or sha256(assignment_path) != plan["distributed_assignment"]["sha256"] + ): + parser.error("selection recovery plan/assignment binding differs") + for binding in plan.get("code_bindings", []): + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + parser.error(f"selection recovery code binding differs: {path}") + assignment = json.loads(assignment_path.read_text(encoding="utf-8")) + if socket.gethostname() != assignment["machines"][args.owner]["hostname"]: + parser.error("selection recovery owner does not match this host") + matches = [item for item in plan["workers"] if item["id"] == args.worker] + if len(matches) != 1 or matches[0]["owner"] != args.owner: + parser.error("selection recovery worker owner differs") + worker = matches[0] + if args.state.resolve() != Path(worker["state"]).resolve(): + parser.error("selection recovery worker state differs") + gpu = int(worker["physical_gpu_id"]) + if gpu not in assignment["machines"][args.owner]["physical_gpu_allowlist"]: + parser.error("selection recovery GPU is not allowed on this host") + evaluations = {item["id"]: item for item in plan["evaluations"]} + assigned = [evaluations[identifier] for identifier in worker["evaluation_ids"]] + if any( + item["owner"] != args.owner or item["physical_gpu_id"] != gpu + for item in assigned + ): + parser.error("selection recovery evaluation assignment differs") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as state_lock: + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_selection_binding_recovery_worker_state_v1", + "status": "waiting_for_gpu", "owner": args.owner, + "worker": args.worker, "physical_gpu_id": gpu, + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "assigned_evaluation_ids": worker["evaluation_ids"], + "completed_ids": [], "attempts": [], + "started_utc": utc_now(), "updated_utc": utc_now(), + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if ( + previous.get("plan_sha256") != plan_hash + or previous.get("owner") != args.owner + or previous.get("worker") != args.worker + or previous.get("assigned_evaluation_ids") + != worker["evaluation_ids"] + ): + parser.error("existing selection recovery state differs") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for item in assigned: + for key in ("config", "checkpoint", "cache_manifest"): + validate_input(item[key], item[f"{key}_sha256"], key) + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError): + evidence = None + if evidence is not None: + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + continue + output = Path(item["output_dir"]) + lock_path = output.parent / f".{output.name}.selection-recovery.lock" + output.parent.mkdir(parents=True, exist_ok=True) + with lock_path.open("a+", encoding="utf-8") as output_lock: + fcntl.flock(output_lock.fileno(), fcntl.LOCK_EX) + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError): + evidence = None + if evidence is not None: + if item["id"] not in state["completed_ids"]: + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + atomic_json(args.state, state) + continue + archived = archive_incomplete_output(item) + while True: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + state["status"] = "waiting_for_gpu" + state["waiting_for"] = item["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + if claim_physical_gpu(gpu): + break + state["status"] = "waiting_for_gpu_claim" + state["waiting_for"] = item["id"] + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + command = evaluation_command( + item, gpu, int(plan["bootstrap_resamples"]) + ) + attempt = { + "evaluation_id": item["id"], "start_utc": utc_now(), + "command": command, + } + if archived is not None: + attempt["archived_incomplete_output"] = archived + state["status"] = "running" + state["current_evaluation"] = item["id"] + state["attempts"].append(attempt) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + env = dict(os.environ) + env["CUDA_VISIBLE_DEVICES"] = str(gpu) + env["PYTHONUNBUFFERED"] = "1" + try: + result = subprocess.run( + command, cwd=Path.cwd(), env=env, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + try: + evidence = validate_recovered_output(item) + except (FileNotFoundError, KeyError, TypeError, ValueError) as error: + state["status"] = "failed_resumable" + state["failure"] = f"{type(error).__name__}: {error}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + if result.returncode: + state["status"] = "failed_resumable" + state["failure"] = f"evaluator exited {result.returncode}" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + raise SystemExit(result.returncode) + state["completed_ids"].append(item["id"]) + state.setdefault("evidence", {})[item["id"]] = evidence + state.pop("failure", None) + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + if set(state["completed_ids"]) != set(worker["evaluation_ids"]): + state["status"] = "failed_state_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state.pop("waiting_for", None) + state.pop("current_evaluation", None) + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_selection_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_selection_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..9d6bcd0a5ebe87d4b4d325dff8080e1954ad4aaa --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_selection_queue.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Wait for complete Phase 9 evidence and freeze unified candidate selection.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +import sys +import time +from typing import Any + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def evidence_complete(plan: dict[str, Any]) -> bool: + for item in plan["required_states"]: + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def selection_complete(plan: dict[str, Any]) -> bool: + output = Path(plan["output_json"]) + if not output.is_file(): + return False + report = json.loads(output.read_text(encoding="utf-8")) + checkpoint = Path(report.get("winner_checkpoint", {}).get("path", "")) + config = Path(report.get("winner_config", {}).get("path", "")) + return ( + report.get("status") == "complete" + and report.get("official_test_used") is False + and report.get("h2o_official_validation_used") is False + and checkpoint.is_file() + and report.get("winner_checkpoint", {}).get("sha256") == sha256(checkpoint) + and config.is_file() + and report.get("winner_config", {}).get("sha256") == sha256(config) + and Path(plan["output_csv"]).is_file() + ) + + +def archive_incomplete_outputs(plan: dict[str, Any], state_path: Path) -> list[str]: + outputs = [Path(plan["output_json"]), Path(plan["output_csv"])] + temporary_outputs = [ + path.with_suffix(path.suffix + ".tmp") for path in outputs + ] + existing = [path for path in outputs + temporary_outputs if path.exists()] + if not existing: + return [] + root = state_path.parent / "selection_incomplete_outputs" + root.mkdir(parents=True, exist_ok=True) + archived = [] + for path in existing: + destination = root / f"{path.name}.{len(list(root.iterdir())):03d}" + shutil.move(str(path), str(destination)) + archived.append(str(destination.resolve())) + return archived + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + args = parser.parse_args() + plan = json.loads(args.plan.read_text(encoding="utf-8")) + if plan.get("official_test_used") is not False: + parser.error("selection plan must explicitly exclude official test") + plan_hash = sha256(args.plan) + args.state.parent.mkdir(parents=True, exist_ok=True) + state_lock = Path(f"{args.state}.lock").open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + state = { + "schema_version": "phase9_selection_state_v1", + "status": "waiting_for_evidence", "plan": str(args.plan.resolve()), + "plan_sha256": plan_hash, "started_utc": utc_now(), + "updated_utc": utc_now(), "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("plan_sha256") != plan_hash: + parser.error("existing selection state belongs to another plan") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not evidence_complete(plan): + state["status"] = "waiting_for_evidence" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + if not selection_complete(plan): + archived = archive_incomplete_outputs(plan, args.state) + if archived: + state.setdefault("archived_incomplete_outputs", []).extend(archived) + atomic_json(args.state, state) + command = [ + sys.executable, "-m", "scripts.summarize_phase9_unified_selection", + "--external-root", plan["external_root"], + "--fold-final-root", plan["fold_final_root"], + "--fold-milestone-root", plan["fold_milestone_root"], + "--multifold-index", plan["multifold_index"], + "--output-json", plan["output_json"], + "--output-csv", plan["output_csv"], + ] + log_path = args.state.parent / "unified_selection.log" + state["status"] = "running" + state["attempt"] = { + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, + text=True, check=False, + ) + state["attempt"]["end_utc"] = utc_now() + state["attempt"]["returncode"] = result.returncode + if result.returncode or not selection_complete(plan): + state["status"] = "failed" + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + report = json.loads(Path(plan["output_json"]).read_text(encoding="utf-8")) + state["status"] = "complete" + state["winner"] = report["winner"] + state["winner_checkpoint"] = report["winner_checkpoint"] + state["winner_config"] = report["winner_config"] + state["required_states"] = [ + { + "id": item["id"], "path": str(Path(item["path"]).resolve()), + "sha256": sha256(item["path"]), + } + for item in plan["required_states"] + ] + state["h2o_official_validation_used"] = False + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_shared_augmentation_evaluation_controller.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_shared_augmentation_evaluation_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..1f0c887433e7319788e98fec0e732a102fc70c38 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_shared_augmentation_evaluation_controller.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""Supervise Stage 8 evaluations and freeze augmentation/Stage 9 gates.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, + local_workers, +) +from scripts.run_phase9_resolution_evaluation_controller import ( + hard_failure, + launch_worker, + pid_matches, + should_launch, + worker_status, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("evaluation_count") != 25 + or plan.get("worker_count") != 10 + or plan.get("worker_heartbeat_seconds") != 30 + or plan.get("evaluator_progress_heartbeat_seconds") != 30 + or plan.get("stall_timeout_seconds") != 900 + or plan.get("max_attempts_per_evaluation") != 2 + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + ): + raise ValueError("shared augmentation evaluation plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"shared augmentation evaluation binding differs: {path}") + + +def training_complete(plan: dict[str, Any]) -> bool: + path = Path( + plan.get("training_controller_states", {}).get( + "taku3", plan["training_controller_state"] + ) + ) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + registry = Path(state.get("training_registry", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["training_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and registry.is_file() + and state.get("training_registry_sha256") == sha256(registry) + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("shared augmentation evaluation state differs from plan") + args.state.parent.mkdir(parents=True, exist_ok=True) + static_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_shared_augmentation_evaluation_controller_state_v1", + "status": "waiting_for_augmentation_training", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": static_hash, + "machine": machine, + "controller_pid": os.getpid(), + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != static_hash: + parser.error("existing augmentation evaluation state differs") + if state.get("machine") != machine: + parser.error("existing augmentation evaluation machine differs") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not training_complete(plan): + state["status"] = "waiting_for_augmentation_training" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + evaluation_plan = Path(plan["evaluation_plan"]) + builder_command = [ + sys.executable, "-m", + "scripts.build_phase9_shared_augmentation_evaluation_plan", + "--training-controller-plan", plan["training_controller_plan"], + "--training-controller-state", plan["training_controller_state"], + "--resolution-cache-plan", plan["resolution_cache_plan"], + "--output-root", plan["evaluation_output_root"], + "--worker-state-root", plan["worker_state_root"], + "--distributed-assignment", plan["distributed_assignment"]["path"], + "--distributed-assignment-sha256", plan["distributed_assignment"]["sha256"], + "--output-plan", str(evaluation_plan), + "--state", plan["evaluation_plan_state"], + ] + if machine == "taku3": + state["status"] = "building_evaluation_plan" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not evaluation_plan.is_file(): + state["status"] = "failed_evaluation_plan_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not evaluation_plan.is_file(): + state["status"] = "waiting_for_immutable_evaluation_plan_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + dynamic_hash = sha256(evaluation_plan) + dynamic = json.loads(evaluation_plan.read_text(encoding="utf-8")) + ids = [item["id"] for item in dynamic["evaluations"]] + assigned = [identifier for worker in dynamic["workers"] for identifier in worker["evaluation_ids"]] + if ( + len(ids) != plan["evaluation_count"] + or len(set(ids)) != len(ids) + or len(dynamic["workers"]) != plan["worker_count"] + or sorted(ids) != sorted(assigned) + or len(set(assigned)) != len(assigned) + ): + state["status"] = "failed_evaluation_plan_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["evaluation_plan"] = str(evaluation_plan.resolve()) + state["evaluation_plan_sha256"] = dynamic_hash + state["owned_workers"] = [ + item["id"] for item in local_workers(dynamic["workers"], machine) + ] + state.setdefault("workers", {}) + while True: + statuses = {} + observed_workers = ( + dynamic["workers"] if machine == "taku3" + else local_workers(dynamic["workers"], machine) + ) + for worker in observed_workers: + path = Path(worker["state"]) + status = worker_status(path, dynamic_hash) + statuses[worker["id"]] = status + if not should_launch(worker, machine, status): + continue + previous_pid = int( + state["workers"].get(worker["id"], {}).get("pid", -1) + ) + if not pid_matches(previous_pid, worker["id"], evaluation_plan): + pid = launch_worker( + evaluation_plan, worker, + Path(plan["worker_log_root"]) / f"{worker['id']}.log", + ) + state["workers"][worker["id"]] = { + "pid": pid, "launched_utc": utc_now(), + "state": worker["state"], + } + state["worker_statuses"] = statuses + state["updated_utc"] = utc_now() + state["heartbeat"] = { + "updated_utc": state["updated_utc"], + "controller_pid": os.getpid(), + "worker_processes": state["workers"], + } + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_evaluation_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "evaluating_and_waiting_for_external_states" + if machine == "taku3" else "evaluating_local_owned_jobs" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + if machine != "taku3": + state["status"] = "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + return + + decision = Path(plan["decision_report"]) + if not decision.exists(): + command = [ + sys.executable, "-m", + "scripts.summarize_phase9_shared_augmentation_decision", + "--plan", str(evaluation_plan), "--output", str(decision), + ] + state["status"] = "summarizing_decision" + state["decision_command"] = command + atomic_json(args.state, state) + result = subprocess.run(command, cwd=Path.cwd(), check=False) + if result.returncode: + state["status"] = "failed_decision_summary" + atomic_json(args.state, state) + raise SystemExit(result.returncode) + report = json.loads(decision.read_text(encoding="utf-8")) + if ( + report.get("status") != "complete" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + or report.get("evaluation_plan", {}).get("sha256") != dynamic_hash + ): + state["status"] = "failed_decision_binding" + atomic_json(args.state, state) + raise SystemExit(1) + state["status"] = "complete" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + state["decision"] = report["decision"] + state["stage9_last2_admitted"] = report[ + "stage9_preceding_mechanism_gate" + ]["stage9_last2_admitted"] + state["decision_report"] = { + "path": str(decision.resolve()), "sha256": sha256(decision), + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_shared_augmentation_training_controller.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_shared_augmentation_training_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..191670dce11e49ef1c417651529cdb49bca1cec2 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_shared_augmentation_training_controller.py @@ -0,0 +1,244 @@ +#!/usr/bin/env python3 +"""Supervise Stage 8 shared-augmentation training after resolution freeze.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any + +from scripts.phase9_distributed_assignment import ( + condition_owners, + controller_state_path, + detect_machine, + gpu_allowlist, + load_assignment, +) +from scripts.run_phase9_resolution_training_controller import ( + condition_status, + hard_failure, + pid_matches, +) +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def validate_plan(plan: dict[str, Any]) -> None: + assignment = load_assignment(plan) + if ( + plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("machine_gpu_allowlists") != { + machine: gpu_allowlist(assignment, machine) + for machine in ("taku3", "server_new") + } + or plan.get("job_count") != 7 + or float(plan.get("worst_domain_relative_regression_limit", -1)) != 0.01 + ): + raise ValueError("shared augmentation training plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"shared augmentation binding differs: {path}") + + +def resolution_decision_complete(plan: dict[str, Any]) -> bool: + state_path = Path(plan["resolution_controller_state"]) + if not state_path.is_file(): + return False + state = json.loads(state_path.read_text(encoding="utf-8")) + report = Path(state.get("decision_report", {}).get("path", "")) + return ( + state.get("status") == "complete" + and state.get("plan_sha256") == plan["resolution_controller_plan_sha256"] + and state.get("official_test_used") is False + and state.get("h2o_official_validation_used") is False + and report.is_file() + and state.get("decision_report", {}).get("sha256") == sha256(report) + ) + + +def launch_worker( + condition: str, registry: Path, state_path: Path, log_path: Path, + allowed_gpus: list[int], +) -> int: + command = [ + sys.executable, "-m", "scripts.run_phase9_unified_train_queue", + "--queue", str(registry.resolve()), "--condition", condition, + "--state", str(state_path.resolve()), "--poll-seconds", "30", + "--allowed-physical-gpus", ",".join(str(gpu) for gpu in allowed_gpus), + ] + log_path.parent.mkdir(parents=True, exist_ok=True) + log = log_path.open("a", encoding="utf-8") + process = subprocess.Popen( + command, cwd=Path.cwd(), env=dict(os.environ), stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + log.close() + return process.pid + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--machine", choices=("taku3", "server_new")) + parser.add_argument("--poll-seconds", type=float, default=60.0) + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + plan = json.loads(args.plan.read_text(encoding="utf-8")) + try: + validate_plan(plan) + assignment = load_assignment(plan) + machine = detect_machine(assignment, args.machine) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != controller_state_path(plan, machine).resolve(): + parser.error("shared augmentation controller state differs from plan") + allowed_gpus = gpu_allowlist(assignment, machine) + args.state.parent.mkdir(parents=True, exist_ok=True) + plan_hash = sha256(args.plan) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + state: dict[str, Any] = { + "schema_version": "phase9_shared_augmentation_training_controller_state_v1", + "status": "waiting_for_resolution_decision", + "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": plan_hash, + "machine": machine, + "workers": {}, + "h2o_official_validation_used": False, + "official_test_used": False, + } + if args.state.is_file(): + state = json.loads(args.state.read_text(encoding="utf-8")) + if state.get("plan_sha256") != plan_hash: + parser.error("existing shared augmentation controller state differs") + if state.get("machine") != machine: + parser.error("existing shared augmentation state belongs to another machine") + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + while not resolution_decision_complete(plan): + state["status"] = "waiting_for_resolution_decision" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + registry = Path(plan["training_registry"]) + builder_command = [ + sys.executable, "-m", + "scripts.build_phase9_shared_augmentation_training_registry", + "--resolution-controller-plan", plan["resolution_controller_plan"], + "--resolution-controller-state", plan["resolution_controller_state"], + "--augmentation-plan", plan["shared_augmentation_plan"], + "--unified-queue", plan["unified_training_queue"], + "--fold-queue", plan["fold_training_queue"], + "--selection-report", plan["selection_report"], + "--output-root", plan["output_root"], + "--output-registry", str(registry), + "--state", plan["registry_builder_state"], + ] + if machine == "taku3": + state["status"] = "building_registry" + state["builder_command"] = builder_command + atomic_json(args.state, state) + result = subprocess.run(builder_command, cwd=Path.cwd(), check=False) + if result.returncode or not registry.is_file(): + state["status"] = "failed_registry_builder" + state["builder_returncode"] = result.returncode + atomic_json(args.state, state) + raise SystemExit(result.returncode or 1) + else: + while not registry.is_file(): + state["status"] = "waiting_for_immutable_registry_sync" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + registry_hash = sha256(registry) + payload = json.loads(registry.read_text(encoding="utf-8")) + conditions = [item["condition"] for item in payload["conditions"]] + owners = condition_owners(payload, assignment) + if ( + len(conditions) != plan["job_count"] + or len(set(conditions)) != plan["job_count"] + or payload.get("shared_augmentation_plan", {}).get("sha256") + != plan["shared_augmentation_plan_sha256"] + or payload.get("gate", {}).get("worst_domain_relative_regression_limit") + != plan["worst_domain_relative_regression_limit"] + or payload.get("official_test_used") is not False + ): + state["status"] = "failed_registry_contract" + atomic_json(args.state, state) + raise SystemExit(1) + state["training_registry"] = str(registry.resolve()) + state["training_registry_sha256"] = registry_hash + state["resolution_hw"] = payload["resolution_hw"] + state["conditions"] = conditions + state["condition_owners"] = owners + state["owned_conditions"] = [ + condition for condition in conditions if owners[condition] == machine + ] + state.setdefault("workers", {}) + + state_root = Path(plan["training_state_root"]) + log_root = Path(plan["training_log_root"]) + while True: + statuses = {} + observed = conditions if machine == "taku3" else state["owned_conditions"] + for condition in observed: + condition_state = state_root / f"{condition.lower()}.json" + status = condition_status(condition_state, registry_hash) + statuses[condition] = status + if hard_failure(status) or status == "complete": + continue + if owners[condition] != machine: + continue + previous_pid = int( + state["workers"].get(condition, {}).get("pid", -1) + ) + if not pid_matches(previous_pid, condition, registry): + pid = launch_worker( + condition, registry, condition_state, + log_root / f"{condition.lower()}.log", + allowed_gpus, + ) + state["workers"][condition] = { + "pid": pid, "launched_utc": utc_now(), + "state": str(condition_state.resolve()), + } + state["condition_statuses"] = statuses + state["updated_utc"] = utc_now() + if any(hard_failure(status) for status in statuses.values()): + state["status"] = "failed_training_dependency" + atomic_json(args.state, state) + raise SystemExit(1) + if statuses and all(status == "complete" for status in statuses.values()): + break + state["status"] = ( + "training_and_waiting_for_external_states" + if machine == "taku3" else "training_local_owned_conditions" + ) + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + state["status"] = "complete" if machine == "taku3" else "complete_local" + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_unified_train_queue.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_unified_train_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f904f748a1ecc505a0efe794951a67ddb4acb67b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_phase9_unified_train_queue.py @@ -0,0 +1,364 @@ +#!/usr/bin/env python3 +"""Run one hash-bound Phase 9 unified mixture through smoke, health, and scale.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any +import re + +from scripts.train_phase7_external import ( + assert_physical_gpu_idle, + claim_physical_gpu, + release_physical_gpu_claim, +) + + +ALLOWED_GPUS = (0, 1, 2, 3) + + +def parse_physical_gpu_ids(value: str) -> tuple[int, ...]: + try: + gpu_ids = tuple(int(item.strip()) for item in value.split(",") if item.strip()) + except ValueError as error: + raise argparse.ArgumentTypeError("GPU IDs must be comma-separated integers") from error + if not gpu_ids or len(set(gpu_ids)) != len(gpu_ids): + raise argparse.ArgumentTypeError("GPU IDs must be nonempty and unique") + if any(gpu < 0 or gpu > 5 for gpu in gpu_ids): + raise argparse.ArgumentTypeError("physical GPU IDs must be between 0 and 5") + return gpu_ids + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def atomic_json(path: Path, value: dict[str, Any]) -> None: + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") + temporary.replace(path) + + +def attempt_gpu_hours(attempts: list[dict[str, Any]]) -> float: + seconds = 0.0 + for attempt in attempts: + if not attempt.get("start_utc") or not attempt.get("end_utc"): + continue + start = datetime.fromisoformat(attempt["start_utc"]) + end = datetime.fromisoformat(attempt["end_utc"]) + seconds += max(0.0, (end - start).total_seconds()) + return seconds / 3600.0 + + +def state_lock_path(state_path: Path) -> Path: + return Path(f"{state_path}.lock") + + +def readiness_complete(queue: dict[str, Any]) -> bool: + state_path = Path(queue["data_readiness_state"]) + if not state_path.is_file(): + return False + state = json.loads(state_path.read_text(encoding="utf-8")) + if ( + state.get("status") != "complete" + or state.get("official_test_used") is not False + or state.get("plan_sha256") != queue["data_finalize_plan_sha256"] + or ( + queue.get("data_readiness_state_sha256") is not None + and queue["data_readiness_state_sha256"] != sha256(state_path) + ) + ): + return False + for artifact in state.get("artifacts", []): + manifest = Path(artifact["manifest"]) + if not manifest.is_file() or sha256(manifest) != artifact["manifest_sha256"]: + return False + for artifact in queue.get("data_artifacts", []): + path = Path(artifact["path"]) + if not path.is_file() or sha256(path) != artifact["sha256"]: + return False + return True + + +def prerequisite_states_complete(registry: dict[str, Any]) -> bool: + for item in registry.get("prerequisite_states", []): + path = Path(item["path"]) + if not path.is_file(): + return False + state = json.loads(path.read_text(encoding="utf-8")) + if state.get("status") != "complete" or state.get("official_test_used") is not False: + return False + return True + + +def prerequisite_gate_satisfied( + registry: dict[str, Any], start_before_prerequisites: bool, +) -> bool: + return start_before_prerequisites or prerequisite_states_complete(registry) + + +def idle_gpu(allowed_gpus: tuple[int, ...] = ALLOWED_GPUS) -> int | None: + for gpu in allowed_gpus: + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + continue + if not claim_physical_gpu(gpu): + continue + time.sleep(1) + try: + assert_physical_gpu_idle(gpu) + except RuntimeError: + release_physical_gpu_claim(gpu) + continue + return gpu + return None + + +def marker_path(queue: dict[str, Any], stage: dict[str, Any]) -> Path: + return Path(queue["output_dir"]) / ".phase9_queue" / f"{stage['id']}.json" + + +def stage_complete(queue: dict[str, Any], stage: dict[str, Any]) -> bool: + path = marker_path(queue, stage) + if not path.is_file(): + return False + marker = json.loads(path.read_text(encoding="utf-8")) + checkpoint = Path(marker.get("checkpoint", "")) + return ( + marker.get("status") == "complete" + and marker.get("config_sha256") == queue["config_sha256"] + and int(marker.get("completed_step", -1)) == int(stage["stop_after_step"]) + and marker.get("official_test_used") is False + and checkpoint.is_file() + and marker.get("checkpoint_sha256") == sha256(checkpoint) + ) + + +def training_command( + queue: dict[str, Any], stage: dict[str, Any], gpu: int, + previous_checkpoint: Path | None, +) -> list[str]: + command = [ + sys.executable, "-m", "scripts.train_phase7_external", + "--config", queue["config"], + "--output-dir", queue["output_dir"], + "--physical-gpu-id", str(gpu), + "--stop-after-step", str(stage["stop_after_step"]), + ] + if previous_checkpoint is None: + command.extend(("--init-checkpoint", queue["initialization_checkpoint"])) + else: + command.extend(("--resume", str(previous_checkpoint))) + if gpu in {4, 5}: + command.append("--allow-physical-gpus-4-5") + return command + + +def latest_resumable_checkpoint( + queue: dict[str, Any], stage: dict[str, Any], previous_checkpoint: Path | None, +) -> Path | None: + target = int(stage["stop_after_step"]) + previous_step = -1 + if previous_checkpoint is not None: + match = re.search(r"step_(\d+)", previous_checkpoint.name) + previous_step = int(match.group(1)) if match else -1 + candidates = [] + for path in Path(queue["output_dir"]).glob("step_*.pt"): + match = re.fullmatch(r"step_(\d+)(?:_final)?\.pt", path.name) + if match is None: + continue + step = int(match.group(1)) + if previous_step < step < target and path.is_file(): + candidates.append((step, path)) + return max(candidates, default=(previous_step, previous_checkpoint))[1] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", type=Path, required=True) + parser.add_argument("--condition", required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--poll-seconds", type=float, default=30.0) + parser.add_argument( + "--allowed-physical-gpus", type=parse_physical_gpu_ids, + default=ALLOWED_GPUS, + ) + parser.add_argument("--start-before-prerequisites", action="store_true") + args = parser.parse_args() + if args.poll_seconds < 1: + parser.error("poll interval must be at least one second") + registry = json.loads(args.queue.read_text(encoding="utf-8")) + conditions = {item["condition"]: item for item in registry["conditions"]} + if args.condition not in conditions: + parser.error(f"condition not registered: {args.condition}") + queue = conditions[args.condition] + if registry.get("official_test_used") is not False: + parser.error("queue must explicitly exclude official test") + config = Path(queue["config"]) + initialization = Path(queue["initialization_checkpoint"]) + if not config.is_file() or sha256(config) != queue["config_sha256"]: + parser.error("frozen config is missing or has changed") + if not initialization.is_file() or sha256(initialization) != queue["initialization_checkpoint_sha256"]: + parser.error("frozen initialization checkpoint is missing or has changed") + args.state.parent.mkdir(parents=True, exist_ok=True) + lock_path = state_lock_path(args.state) + state_lock = lock_path.open("a+", encoding="utf-8") + fcntl.flock(state_lock.fileno(), fcntl.LOCK_EX) + registry_hash = sha256(args.queue) + state = { + "schema_version": "phase9_unified_train_state_v1", + "status": "waiting_for_data", + "condition": args.condition, + "queue": str(args.queue.resolve()), "queue_sha256": registry_hash, + "started_utc": utc_now(), "updated_utc": utc_now(), + "attempts": [], "completed_stages": [], + "allowed_physical_gpus": list(args.allowed_physical_gpus), + "official_test_used": False, + } + if args.state.is_file(): + previous = json.loads(args.state.read_text(encoding="utf-8")) + if previous.get("queue_sha256") != registry_hash: + parser.error("existing state is bound to another queue version") + state = previous + if state.get("status") == "complete": + print(json.dumps(state, indent=2)) + return + for attempt in state.get("attempts", []): + if attempt.get("start_utc") and not attempt.get("end_utc"): + attempt["end_utc"] = utc_now() + attempt["returncode"] = None + attempt["interrupted_before_queue_restart"] = True + previous_gpus = tuple(state.get("allowed_physical_gpus", ALLOWED_GPUS)) + if state.get("attempts") and previous_gpus != args.allowed_physical_gpus: + parser.error("cannot change allowed GPUs after this queue has attempted work") + previous_early_start = bool(state.get("start_before_prerequisites", False)) + if state.get("attempts") and previous_early_start != args.start_before_prerequisites: + parser.error("cannot change prerequisite scheduling after attempted work") + state["allowed_physical_gpus"] = list(args.allowed_physical_gpus) + state["start_before_prerequisites"] = bool(args.start_before_prerequisites) + if args.start_before_prerequisites: + state["resource_amendment"] = "user_authorized_all_idle_gpus_20260727" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + while not readiness_complete({**registry, **queue}): + state["status"] = "waiting_for_data" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + while not prerequisite_gate_satisfied(registry, args.start_before_prerequisites): + state["status"] = "waiting_for_prerequisites" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + + previous_checkpoint: Path | None = None + for stage in queue["stages"]: + if stage_complete(queue, stage): + previous_checkpoint = Path( + json.loads(marker_path(queue, stage).read_text(encoding="utf-8"))["checkpoint"] + ) + if stage["id"] not in state["completed_stages"]: + state["completed_stages"].append(stage["id"]) + continue + previous_checkpoint = latest_resumable_checkpoint( + queue, stage, previous_checkpoint, + ) + while True: + gpu = idle_gpu(args.allowed_physical_gpus) + if gpu is None: + state["status"] = "waiting_for_idle_gpu" + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + time.sleep(args.poll_seconds) + continue + break + command = training_command(queue, stage, gpu, previous_checkpoint) + log_path = Path(queue["log_dir"]) / f"{stage['id']}.log" + log_path.parent.mkdir(parents=True, exist_ok=True) + attempt = { + "stage": stage["id"], "physical_gpu_id": gpu, + "start_utc": utc_now(), "command": command, + "log": str(log_path.resolve()), + } + state["status"] = "running" + state["current_stage"] = stage["id"] + state["attempts"].append(attempt) + atomic_json(args.state, state) + environment = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) + try: + with log_path.open("a", encoding="utf-8") as log: + result = subprocess.run( + command, env=environment, stdout=log, + stderr=subprocess.STDOUT, text=True, check=False, + ) + finally: + release_physical_gpu_claim(gpu) + attempt["end_utc"] = utc_now() + attempt["returncode"] = result.returncode + state["updated_utc"] = utc_now() + if result.returncode: + periodic = sorted(Path(queue["output_dir"]).glob("step_*.pt")) + latest = periodic[-1] if periodic else None + state["status"] = "failed_resumable" if periodic else "failed" + state["failure"] = { + "stage": stage["id"], "returncode": result.returncode, + "latest_checkpoint": str(latest.resolve()) if latest else None, + "latest_checkpoint_sha256": sha256(latest) if latest else None, + "log": str(log_path.resolve()), + } + atomic_json(args.state, state) + raise SystemExit(result.returncode) + checkpoint = Path(queue["output_dir"]) / f"step_{int(stage['stop_after_step']):07d}_final.pt" + summary = json.loads((Path(queue["output_dir"]) / "summary.json").read_text(encoding="utf-8")) + marker = { + "status": "complete", "condition": args.condition, + "stage": stage["id"], "completed_utc": utc_now(), + "completed_step": int(stage["stop_after_step"]), + "physical_gpu_id": gpu, "config": str(config.resolve()), + "config_sha256": queue["config_sha256"], + "checkpoint": str(checkpoint.resolve()), + "checkpoint_sha256": sha256(checkpoint), + "source_manifest_sha256": summary["source_manifest_sha256"], + "source_exposure_batches": summary["source_exposure_batches"], + "wall_seconds": summary["wall_seconds"], + "gpu_hours": summary["gpu_hours"], + "frames_per_second": summary["frames_per_second"], + "peak_vram_gib": summary["peak_vram_gib"], + "official_test_used": False, + } + path = marker_path(queue, stage) + path.parent.mkdir(parents=True, exist_ok=True) + atomic_json(path, marker) + previous_checkpoint = checkpoint + state["completed_stages"].append(stage["id"]) + state["last_completed"] = marker + atomic_json(args.state, state) + + state["status"] = "complete" + state["gpu_hours_consumed"] = attempt_gpu_hours(state["attempts"]) + state["completed_utc"] = utc_now() + state["updated_utc"] = utc_now() + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_qort_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_qort_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..9c50b6afa211f8c32cd790f2fc21f36ea2055aa0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_qort_h2o.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Run the official QORT-Former H2O checkpoint on the common cam4 validation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +import torch +import torchvision.transforms as transforms +from PIL import Image + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=1) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + repo = args.repo.resolve() + sys.path.insert(0, str(repo)) + from lib.qort_former import QORT_Former + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys = keys[: args.max_frames] + takes = takes[: args.max_frames] + frame_ids = frame_ids[: args.max_frames] + count = len(keys) + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=True) + model = QORT_Former(num_classes=11).to(device).eval() + model.load_state_dict(checkpoint, strict=True) + transform = transforms.Compose([ + transforms.Resize((540, 960)), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), + ]) + + # QORT's released inference denormalizes u/v by the raw image size and z by + # 1000 mm. H2O K then deterministically maps released (u,v,z) to camera XYZ. + from foundation_hand.evaluation.sota import GroundTruthBundle + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + detected = np.ones((count, 2), dtype=bool) + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for start in range(0, count, args.batch_size): + end = min(start + args.batch_size, count) + images = [] + image_sizes = [] + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True): + path = args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png" + with Image.open(path) as image: + rgb = image.convert("RGB") + image_sizes.append(rgb.size) + images.append(transform(rgb)) + batch = torch.stack(images).to(device) + with torch.no_grad(): + outputs = model(batch) + logits = outputs["pred_logits"] + predictions = outputs["pred_keypoints"] + batch_indices = torch.arange(end - start, device=device) + left_index = logits[:, :, 9].argmax(dim=1) + right_index = logits[:, :, 10].argmax(dim=1) + left = predictions[0, batch_indices, left_index].reshape(-1, 21, 3) + right = predictions[1, batch_indices, right_index].reshape(-1, 21, 3) + uvz = torch.stack((left, right), dim=1).float().cpu().numpy() + scores = torch.stack(( + logits[batch_indices, left_index, 9].sigmoid(), + logits[batch_indices, right_index, 10].sigmoid(), + ), dim=1).float().cpu().numpy() + confidence[start:end] = scores + for local_index, (width, height) in enumerate(image_sizes): + uvz[local_index, ..., 0] *= width + uvz[local_index, ..., 1] *= height + z = uvz[local_index, ..., 2] + K = intrinsics[start + local_index] + joints[start + local_index, ..., 0] = (uvz[local_index, ..., 0] - K[0, 2]) / K[0, 0] * z + joints[start + local_index, ..., 1] = (uvz[local_index, ..., 1] - K[1, 2]) / K[1, 1] * z + joints[start + local_index, ..., 2] = z + if end % 100 == 0 or end == count: + print(f"QORT-Former {end}/{count}", flush=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output.resolve() + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "QORT-Former", + "scope": "RGB decode + resize/normalize + model forward + camera conversion", + "frames": count, + "processing_seconds": processing_seconds, + "frames_per_second": count / processing_seconds, + "batch_size": args.batch_size, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(repo), "rev-parse", "HEAD"], text=True + ).strip() + parameter_count = sum(parameter.numel() for parameter in model.parameters()) + bundle = PredictionBundle( + model_name="QORT-Former", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + detected=detected, + confidence=confidence, + vertices_camera_m=None, + metadata={ + "official_repository": "https://github.com/kcsayem/QORT-Former", + "repository_commit": commit, + "checkpoint": str(args.checkpoint.resolve()), + "checkpoint_sha256": sha256(args.checkpoint), + "parameter_count": parameter_count, + "input": "full RGB, resized to 960x540", + "temporal": False, + "detector": False, + "output_conversion": "official normalized u,v,z; raw H2O K unprojection", + "original_paper_metric": "mean endpoint error over 21 joints", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + }, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_wildhands_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_wildhands_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e77900e883aa37cc0b9aee3c5e030263be10f9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_wildhands_h2o.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Run the released WildHands checkpoint on H2O with a common hand detector.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import types +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import GroundTruthBundle, PredictionBundle, load_frame_index +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix + + +MANO_TO_OPENPOSE = np.asarray( + [0, 13, 14, 15, 16, 1, 2, 3, 17, 4, 5, 6, 18, 10, 11, 12, 19, 7, 8, 9, 20], + dtype=np.int64, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-dir", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=1.75) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def install_pytorch3d_rotation_compatibility() -> None: + """Provide the three pure-PyTorch transforms used by the official model.""" + + rotation_conversions = types.ModuleType("pytorch3d.transforms.rotation_conversions") + rotation_conversions.axis_angle_to_matrix = axis_angle_to_matrix + rotation_conversions.rotation_6d_to_matrix = rotation_6d_to_matrix + rotation_conversions.matrix_to_rotation_6d = ( + lambda matrix: matrix[..., :2, :].clone().reshape(matrix.shape[:-2] + (6,)) + ) + transforms = types.ModuleType("pytorch3d.transforms") + transforms.rotation_conversions = rotation_conversions + pytorch3d = types.ModuleType("pytorch3d") + pytorch3d.transforms = transforms + sys.modules.update({ + "pytorch3d": pytorch3d, + "pytorch3d.transforms": transforms, + "pytorch3d.transforms.rotation_conversions": rotation_conversions, + }) + + +def recursive_to(value: Any, device: torch.device) -> Any: + if torch.is_tensor(value): + return value.to(device) + if isinstance(value, dict): + return {name: recursive_to(item, device) for name, item in value.items()} + if isinstance(value, tuple): + return tuple(recursive_to(item, device) for item in value) + if isinstance(value, list): + return [recursive_to(item, device) for item in value] + return value + + +def main() -> None: + args = parse_args() + for name in ("repo", "checkpoint", "detector", "mano_dir", "root", "manifest", "ground_truth", "output"): + setattr(args, name, getattr(args, name).resolve()) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + + os.environ["WILDHANDS_MANO_DIR"] = str(args.mano_dir) + sys.path.insert(0, str(args.repo)) + enable_legacy_mano_loading() + install_pytorch3d_rotation_compatibility() + os.chdir(args.repo) + + from ultralytics import YOLO + from wildhands.configs.parser import construct_args + from wildhands.datasets.dataset import WildHandsDataset + from wildhands.models.wrapper import WildHandsWrapper + + keys, takes, frame_ids = load_frame_index(args.manifest) + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ground_truth.intrinsics[gt_index[str(key)]] for key in keys]) + + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + config = construct_args() + model = WildHandsWrapper(config) + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + ignored = ("head_o", "arti_head", "grasp_classifier") + state = { + name: value + for name, value in checkpoint["state_dict"].items() + if not any(token in name for token in ignored) + } + model.load_state_dict(state) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + reconstruction_queue: list[tuple[int, int, float, Any]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = recursive_to(default_collate([record[3] for record in records]), device) + with torch.no_grad(): + output = model(batch) + right_joints = output["pred.j3d.cam.r"].float().cpu().numpy() + left_joints = output["pred.j3d.cam.l"].float().cpu().numpy() + right_vertices = output["pred.v3d.cam.r"].float().cpu().numpy() + left_vertices = output["pred.v3d.cam.l"].float().cpu().numpy() + for local, (frame_index, side, score, _) in enumerate(records): + batch_joints = right_joints[local] if side else left_joints[local] + batch_vertices = right_vertices[local] if side else left_vertices[local] + joints[frame_index, side] = batch_joints[MANO_TO_OPENPOSE] + vertices[frame_index, side] = batch_vertices + detected[frame_index, side] = True + confidence[frame_index, side] = score + + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images_bgr = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images_bgr): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images_bgr, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + rgb = cv2.cvtColor(images_bgr[local], cv2.COLOR_BGR2RGB) + intrinsic = intrinsics[frame_index] + focal = float(0.5 * (intrinsic[0, 0] + intrinsic[1, 1])) + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + dataset = WildHandsDataset( + config, + rgb, + boxes[[choice]], + np.asarray([side], dtype=np.float32), + focal_length=focal, + rescale_factor=args.rescale_factor, + intrx=intrinsic, + ) + reconstruction_queue.append( + (frame_index, side, float(scores[choice]), dataset[0]) + ) + flush_queue() + if end % 100 == 0 or end == count: + print(f"WildHands detector {end}/{count}", flush=True) + flush_queue(force=True) + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + metadata = { + "official_repository": "https://github.com/ap229997/hands", + "repository_branch": "demo", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB, known H2O intrinsics, common detector hand boxes, per-hand crops", + "training_exposure": "zero-shot H2O; released model trained on ARCTIC, AssemblyHands, and EPIC", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "common WiLoR detector handedness; highest-confidence detection per side", + "camera_policy": "official WildHands weak-perspective conversion with known H2O intrinsics", + "joint_conversion": "official MANO output reordered to H2O/OpenPose convention", + "pytorch3d_compatibility": "three official pure-torch rotation formulas supplied without renderer", + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name="WildHands-zero-shot", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_wilor_h2o.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_wilor_h2o.py new file mode 100644 index 0000000000000000000000000000000000000000..cabd7ffbda3772dd8a1d4c3d23a13f7eba864eb0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/run_wilor_h2o.py @@ -0,0 +1,346 @@ +#!/usr/bin/env python3 +"""Run the complete official WiLoR detector + reconstruction pipeline on H2O.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import cv2 +import numpy as np +import torch +from torch.utils.data import default_collate + +from foundation_hand.evaluation.sota import PredictionBundle, load_frame_index + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--detector", type=Path, required=True) + parser.add_argument("--mano-right", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--timing-output", type=Path) + parser.add_argument("--official-output", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--detector-batch-size", type=int, default=16) + parser.add_argument("--reconstruction-batch-size", type=int, default=16) + parser.add_argument("--confidence-threshold", type=float, default=0.3) + parser.add_argument("--rescale-factor", type=float, default=2.0) + parser.add_argument( + "--camera-policy", + choices=("official", "h2o_intrinsics", "both"), + default="official", + ) + parser.add_argument("--max-frames", type=int) + parser.add_argument("--num-shards", type=int, default=1) + parser.add_argument("--shard-index", type=int, default=0) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + args.repo = args.repo.resolve() + args.checkpoint = args.checkpoint.resolve() + args.detector = args.detector.resolve() + args.mano_right = args.mano_right.resolve() + args.root = args.root.resolve() + args.manifest = args.manifest.resolve() + if args.ground_truth is not None: + args.ground_truth = args.ground_truth.resolve() + args.output = args.output.resolve() + if args.timing_output is not None: + args.timing_output = args.timing_output.resolve() + if args.official_output is not None: + args.official_output = args.official_output.resolve() + mano_target = args.repo / "mano_data" / "MANO_RIGHT.pkl" + if not mano_target.exists(): + mano_target.symlink_to(args.mano_right) + + sys.path.insert(0, str(args.repo)) + os.chdir(args.repo) + from ultralytics import YOLO + from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading + from wilor.datasets.vitdet_dataset import ViTDetDataset + from wilor.models import load_wilor + from wilor.utils.renderer import cam_crop_to_full + + keys, takes, frame_ids = load_frame_index(args.manifest) + if args.num_shards <= 0 or not 0 <= args.shard_index < args.num_shards: + raise ValueError("Invalid shard index/count") + shard = np.arange(len(keys)) % args.num_shards == args.shard_index + keys, takes, frame_ids = keys[shard], takes[shard], frame_ids[shard] + if args.max_frames is not None: + keys, takes, frame_ids = ( + keys[: args.max_frames], takes[: args.max_frames], frame_ids[: args.max_frames] + ) + count = len(keys) + intrinsics = None + if args.camera_policy in ("h2o_intrinsics", "both"): + if args.ground_truth is None: + raise ValueError("--camera-policy h2o_intrinsics requires --ground-truth") + from foundation_hand.evaluation.sota import GroundTruthBundle + + ground_truth = GroundTruthBundle.load(args.ground_truth) + gt_index = {str(key): index for index, key in enumerate(ground_truth.frame_keys)} + intrinsics = np.stack([ + ground_truth.intrinsics[gt_index[str(key)]] for key in keys + ]) + if args.camera_policy == "both" and args.official_output is None: + raise ValueError("--camera-policy both requires --official-output") + device = torch.device(args.device) + if device.type == "cuda": + torch.cuda.set_device(device) + + enable_legacy_mano_loading() + model, model_cfg = load_wilor( + checkpoint_path=str(args.checkpoint), + cfg_path=str(args.repo / "pretrained_models" / "model_config.yaml"), + ) + model = model.to(device).eval() + original_torch_load = torch.load + + def legacy_torch_load(*load_args: Any, **load_kwargs: Any) -> Any: + load_kwargs.setdefault("weights_only", False) + return original_torch_load(*load_args, **load_kwargs) + + torch.load = legacy_torch_load + try: + detector = YOLO(str(args.detector)).to(device) + finally: + torch.load = original_torch_load + joints = np.full((count, 2, 21, 3), np.nan, dtype=np.float32) + vertices = np.full((count, 2, 778, 3), np.nan, dtype=np.float32) + detected = np.zeros((count, 2), dtype=bool) + confidence = np.full((count, 2), np.nan, dtype=np.float32) + official_joints = ( + np.full_like(joints, np.nan) if args.camera_policy == "both" else None + ) + official_vertices = ( + np.full_like(vertices, np.nan) if args.camera_policy == "both" else None + ) + reconstruction_queue: list[tuple[int, int, float, dict[str, Any]]] = [] + + def flush_queue(force: bool = False) -> None: + while len(reconstruction_queue) >= args.reconstruction_batch_size or ( + force and reconstruction_queue + ): + batch_size = min(args.reconstruction_batch_size, len(reconstruction_queue)) + records = reconstruction_queue[:batch_size] + del reconstruction_queue[:batch_size] + batch = default_collate([record[3] for record in records]) + batch = { + name: value.to(device) if torch.is_tensor(value) else value + for name, value in batch.items() + } + with torch.no_grad(): + output = model(batch) + multiplier = 2 * batch["right"] - 1 + pred_cam = output["pred_cam"].clone() + pred_cam[:, 1] *= multiplier + box_center = batch["box_center"].float() + box_size = batch["box_size"].float() + img_size = batch["img_size"].float() + official_focal = ( + model_cfg.EXTRA.FOCAL_LENGTH + / model_cfg.MODEL.IMAGE_SIZE + * img_size.max() + ) + official_camera_tensor = cam_crop_to_full( + pred_cam, box_center, box_size, img_size, official_focal + ) + calibrated_camera_tensor = None + if args.camera_policy in ("h2o_intrinsics", "both"): + record_indices = np.asarray([record[0] for record in records]) + K = torch.from_numpy(intrinsics[record_indices]).to(device) + focal = 0.5 * (K[:, 0, 0] + K[:, 1, 1]) + principal = K[:, :2, 2] + denominator = box_size * pred_cam[:, 0] + 1e-9 + calibrated_camera_tensor = torch.stack(( + pred_cam[:, 1] + 2 * (box_center[:, 0] - principal[:, 0]) / denominator, + pred_cam[:, 2] + 2 * (box_center[:, 1] - principal[:, 1]) / denominator, + 2 * focal / denominator, + ), dim=-1) + camera_tensor = ( + calibrated_camera_tensor + if calibrated_camera_tensor is not None + else official_camera_tensor + ) + camera = camera_tensor.float().cpu().numpy() + batch_joints = output["pred_keypoints_3d"].float().cpu().numpy() + batch_vertices = output["pred_vertices"].float().cpu().numpy() + handedness = batch["right"].float().cpu().numpy() + batch_joints[..., 0] *= (2 * handedness - 1)[:, None] + batch_vertices[..., 0] *= (2 * handedness - 1)[:, None] + relative_joints = batch_joints.copy() + relative_vertices = batch_vertices.copy() + batch_joints += camera[:, None] + batch_vertices += camera[:, None] + if args.camera_policy == "both": + official_camera = official_camera_tensor.float().cpu().numpy() + batch_official_joints = relative_joints + official_camera[:, None] + batch_official_vertices = relative_vertices + official_camera[:, None] + for local, (frame_index, side, score, _) in enumerate(records): + joints[frame_index, side] = batch_joints[local] + vertices[frame_index, side] = batch_vertices[local] + detected[frame_index, side] = True + confidence[frame_index, side] = score + if args.camera_policy == "both": + official_joints[frame_index, side] = batch_official_joints[local] + official_vertices[frame_index, side] = batch_official_vertices[local] + + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_started = time.perf_counter() + for start in range(0, count, args.detector_batch_size): + end = min(start + args.detector_batch_size, count) + images = [ + cv2.imread(str(args.root / str(take) / "rgb" / f"{int(frame_id):06d}.png")) + for take, frame_id in zip(takes[start:end], frame_ids[start:end], strict=True) + ] + if any(image is None for image in images): + raise RuntimeError(f"Image decode failure in frame range {start}:{end}") + results = detector( + images, + conf=args.confidence_threshold, + verbose=False, + batch=args.detector_batch_size, + ) + for local, result in enumerate(results): + frame_index = start + local + boxes = result.boxes.xyxy.float().cpu().numpy() + classes = result.boxes.cls.long().cpu().numpy() + scores = result.boxes.conf.float().cpu().numpy() + for side in (0, 1): + choices = np.flatnonzero(classes == side) + if choices.size == 0: + continue + choice = int(choices[np.argmax(scores[choices])]) + crop_dataset = ViTDetDataset( + model_cfg, + images[local], + boxes[[choice]], + np.asarray([side], dtype=np.float32), + rescale_factor=args.rescale_factor, + fp16=False, + ) + reconstruction_queue.append(( + frame_index, side, float(scores[choice]), crop_dataset[0] + )) + flush_queue() + if end % 100 == 0 or end == count: + print(f"WiLoR detector {end}/{count}", flush=True) + flush_queue(force=True) + if device.type == "cuda": + torch.cuda.synchronize(device) + processing_seconds = time.perf_counter() - processing_started + if args.timing_output is not None: + timing_output = args.timing_output + timing_output.parent.mkdir(parents=True, exist_ok=True) + timing_output.write_text(json.dumps({ + "schema_version": "foundation_hand_external_speed_v1", + "model": "WiLoR", + "scope": "RGB decode + detector + crop preprocessing + reconstruction + camera conversion", + "frames": count, + "detected_hand_frames": int(detected.sum()), + "processing_seconds": processing_seconds, + "frames_per_second": count / processing_seconds, + "detector_batch_size": args.detector_batch_size, + "reconstruction_batch_size": args.reconstruction_batch_size, + "model_loading_excluded": True, + "output_serialization_excluded": True, + "cuda_synchronized": device.type == "cuda", + "device": str(device), + "gpu_name": torch.cuda.get_device_name(device) if device.type == "cuda" else None, + }, indent=2) + "\n", encoding="utf-8") + + commit = subprocess.check_output( + ["git", "-C", str(args.repo), "rev-parse", "HEAD"], text=True + ).strip() + reconstruction_parameters = sum(parameter.numel() for parameter in model.parameters()) + detector_parameters = sum(parameter.numel() for parameter in detector.model.parameters()) + effective_policy = ( + "h2o_intrinsics" if args.camera_policy == "both" else args.camera_policy + ) + metadata = { + "official_repository": "https://github.com/rolpotamias/WiLoR", + "repository_commit": commit, + "checkpoint": str(args.checkpoint), + "checkpoint_sha256": sha256(args.checkpoint), + "detector_checkpoint": str(args.detector), + "detector_checkpoint_sha256": sha256(args.detector), + "reconstruction_parameter_count": reconstruction_parameters, + "detector_parameter_count": detector_parameters, + "end_to_end_parameter_count": reconstruction_parameters + detector_parameters, + "input": "full RGB detector, per-detection RGB crop reconstruction", + "confidence_threshold": args.confidence_threshold, + "rescale_factor": args.rescale_factor, + "temporal": False, + "side_assignment": "official detector handedness; highest-confidence detection per side", + "camera_policy": effective_policy, + "camera_conversion": ( + "official cam_crop_to_full with released assumed focal" + if effective_policy == "official" + else "cam_crop_to_full algebra with known H2O focal/principal point" + ), + "official_test_used": False, + "num_shards": args.num_shards, + "shard_index": args.shard_index, + } + bundle = PredictionBundle( + model_name=( + "WiLoR-official-camera" + if effective_policy == "official" + else "WiLoR-H2O-K-calibrated" + ), + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=joints, + vertices_camera_m=vertices, + detected=detected, + confidence=confidence, + metadata=metadata, + ) + bundle.save(args.output) + if args.camera_policy == "both": + official_metadata = dict(metadata) + official_metadata.update({ + "camera_policy": "official", + "camera_conversion": "official cam_crop_to_full with released assumed focal", + }) + PredictionBundle( + model_name="WiLoR-official-camera", + frame_keys=keys, + takes=takes, + frame_ids=frame_ids, + joints_camera_m=official_joints, + vertices_camera_m=official_vertices, + detected=detected, + confidence=confidence, + metadata=official_metadata, + ).save(args.official_output) + print(json.dumps(bundle.metadata, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/screen_phase6_mixed_projection_oof.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/screen_phase6_mixed_projection_oof.py new file mode 100644 index 0000000000000000000000000000000000000000..71c0f7f48655721114a3fab67f4c9847cfdf1a0e --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/screen_phase6_mixed_projection_oof.py @@ -0,0 +1,484 @@ +#!/usr/bin/env python3 +"""Select Phase 6 mixed-projection constants on train OOF predictions only.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.mixed_projection import ( + coarse_wrist_ray_translation, + direct_wrist_ray_translation, + solve_mixed_projection_batch, +) + + +FINGERTIPS = (4, 8, 12, 16, 20) +Z_MODES = ( + "coarse", + "raw_alignment", + "calibrated_always", + "calibrated_confidence_0p6", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fields = list(rows[0]) + extras = sorted({key for row in rows for key in row} - set(fields)) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields + extras, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_cross_validated_calibration( + path: Path, +) -> dict[tuple[int, str, int, int], tuple[float, float, bool]]: + lookup: dict[tuple[int, str, int, int], tuple[float, float, bool]] = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + hand = 1 if row["side"] == "right" else 0 + key = ( + int(row["coarse_seed"]), row["take"], int(row["frame_id"]), hand, + ) + if key in lookup: + raise ValueError(f"duplicate calibration row: {key}") + lookup[key] = ( + float(row["calibrated_delta_z_mm"]) / 1000.0, + float(row["confidence"]), + row["alignment_available"] == "True", + ) + if len(lookup) != 333_936: + raise ValueError(f"expanded calibration row count changed: {len(lookup)}") + return lookup + + +def candidate_specs() -> list[dict[str, object]]: + output: list[dict[str, object]] = [] + for z_mode in Z_MODES: + output.extend(( + {"id": f"direct_xyz__z_{z_mode}", "assembly": "direct_xyz", "z_mode": z_mode}, + {"id": f"coarse_wrist_ray__z_{z_mode}", "assembly": "coarse_wrist_ray", "z_mode": z_mode}, + {"id": f"direct_2d_wrist_ray__z_{z_mode}", "assembly": "direct_2d_wrist_ray", "z_mode": z_mode}, + )) + for support in (4, 8, 12): + output.append({ + "id": f"mixed_wls_s{support}__z_{z_mode}", + "assembly": "mixed_projection_21j_wls", + "z_mode": z_mode, + "minimum_support": support, + "huber_delta_px": None, + }) + for delta in (2.0, 4.0, 8.0, 16.0): + output.append({ + "id": f"mixed_huber_d{delta:g}_s{support}__z_{z_mode}", + "assembly": "robust_mixed_projection", + "z_mode": z_mode, + "minimum_support": support, + "huber_delta_px": delta, + }) + return output + + +def corrections_for_take( + arrays: dict[str, np.ndarray], + *, + seed: int, + calibration: dict[tuple[int, str, int, int], tuple[float, float, bool]], +) -> tuple[dict[str, np.ndarray], np.ndarray, np.ndarray]: + time = len(arrays["frame_id"]) + calibrated = np.zeros((time, 2), dtype=np.float64) + confidence = np.zeros((time, 2), dtype=np.float64) + available = np.zeros((time, 2), dtype=bool) + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + for time_index, hand in zip(*np.where(valid), strict=True): + key = (seed, take, int(arrays["frame_id"][time_index]), int(hand)) + try: + calibrated[time_index, hand], confidence[time_index, hand], available[time_index, hand] = calibration[key] + except KeyError as error: + raise ValueError(f"missing cross-validated calibration row: {key}") from error + raw_available = arrays["alignment_applied"].astype(bool) + raw = np.where(raw_available, arrays["alignment_delta_z_m"], 0.0) + always = np.where(available, calibrated, 0.0) + gated = np.where(available & (confidence >= 0.6), calibrated, 0.0) + return { + "coarse": np.zeros((time, 2), dtype=np.float64), + "raw_alignment": raw, + "calibrated_always": always, + "calibrated_confidence_0p6": gated, + }, calibrated, confidence + + +def assemble( + spec: dict[str, object], + *, + coarse: np.ndarray, + root_relative_joints: np.ndarray, + anchors: np.ndarray, + K: np.ndarray, + z: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + direct = coarse.copy() + direct[:, 2] = z + ray = coarse_wrist_ray_translation(coarse, z) + assembly = spec["assembly"] + diagnostics: dict[str, np.ndarray] = {} + if assembly == "direct_xyz": + return direct, diagnostics + if assembly == "coarse_wrist_ray": + return ray, diagnostics + if assembly == "direct_2d_wrist_ray": + translation, valid = direct_wrist_ray_translation(anchors, K, z, ray) + diagnostics["success"] = valid + return translation, diagnostics + result = solve_mixed_projection_batch( + root_relative_joints, anchors, K, z, ray, + image_hw=(368, 640), + minimum_support=int(spec["minimum_support"]), + robust_huber_delta_px=( + None if spec["huber_delta_px"] is None else float(spec["huber_delta_px"]) + ), + ) + diagnostics.update({ + "support_count": result.support_count, + "residual_scale_px": result.residual_scale_px, + "conditioning": result.conditioning, + "inlier_ratio": result.inlier_ratio, + "uncertainty_x_m": result.uncertainty_xy_m[:, 0], + "uncertainty_y_m": result.uncertainty_xy_m[:, 1], + "success": result.failure_reason == "ok", + "failure_reason": result.failure_reason, + }) + return result.translation_m, diagnostics + + +def project(points: np.ndarray, K: np.ndarray) -> np.ndarray: + z = np.maximum(points[..., 2], 1e-8) + return np.stack(( + K[:, None, 0, 0] * points[..., 0] / z + K[:, None, 0, 2], + K[:, None, 1, 1] * points[..., 1] / z + K[:, None, 1, 2], + ), axis=-1) + + +def evaluate_translation( + arrays: dict[str, np.ndarray], + indices: tuple[np.ndarray, np.ndarray], + translation: np.ndarray, +) -> dict[str, np.ndarray]: + time_index, hand = indices + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + shift = translation - coarse + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + shift[:, None] + target = arrays["target_joints_camera"][time_index, hand].astype(np.float64) + target_translation = arrays["target_wrist_translation"][time_index, hand].astype(np.float64) + joint_error = np.linalg.norm(joints - target, axis=-1) * 1000.0 + signed_translation = (translation - target_translation) * 1000.0 + K = arrays["K_resized"][time_index].astype(np.float64) + projected = project(joints, K) + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + target_2d = arrays["target_2d_px"][time_index, hand].astype(np.float64) + return { + "absolute_mpjpe_mm": joint_error.mean(axis=1), + "fingertip_mpjpe_mm": joint_error[:, FINGERTIPS].mean(axis=1), + "translation_x_mae_mm": np.abs(signed_translation[:, 0]), + "translation_y_mae_mm": np.abs(signed_translation[:, 1]), + "translation_z_mae_mm": np.abs(signed_translation[:, 2]), + "projected_mano_2d_px": np.linalg.norm(projected - target_2d, axis=-1).mean(axis=1), + "direct_mano_consistency_px": np.linalg.norm(projected - anchors, axis=-1).mean(axis=1), + } + + +def distribution(values: np.ndarray) -> dict[str, float]: + values = np.asarray(values, dtype=np.float64) + threshold = float(np.percentile(values, 95)) + return { + "mean": float(values.mean()), + "p95": threshold, + "cvar95": float(values[values >= threshold].mean()), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--calibration-json", type=Path, required=True) + parser.add_argument("--calibration-predictions", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + calibration_report = json.loads(args.calibration_json.read_text(encoding="utf-8")) + if ( + calibration_report.get("status") != "fitted" + or calibration_report.get("official_validation_used") is not False + or calibration_report.get("official_test_used") is not False + or calibration_report.get("samples") != 333_936 + or calibration_report.get("predictions", {}).get("sha256") + != sha256(args.calibration_predictions) + ): + raise ValueError("expanded OOF calibration contract failed") + args.output_dir.mkdir(parents=True, exist_ok=True) + calibration = load_cross_validated_calibration(args.calibration_predictions) + specs = candidate_specs() + spec_by_id = {str(spec["id"]): spec for spec in specs} + per_take: dict[tuple[str, int, str], dict[str, float]] = {} + values: dict[str, dict[str, list[np.ndarray]]] = { + str(spec["id"]): defaultdict(list) for spec in specs + } + bank_records = [] + sample_order: list[tuple[int, str, int, int]] = [] + + for bank_index, registered in enumerate(calibration_report["bank_manifests"], start=1): + manifest_path = Path(registered["path"]) + if sha256(manifest_path) != registered["sha256"]: + raise ValueError(f"bank manifest hash mismatch: {manifest_path}") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("status") != "complete" + or manifest.get("result_role") != "official_train_group_heldout_oof_predictions" + or manifest.get("official_test_used") is not False + or manifest.get("leakage_audit", {}).get("passed") is not True + ): + raise ValueError(f"bank isolation contract failed: {manifest_path}") + seed = int(manifest["seed"]) + for take_record in manifest["takes"]: + take_path = Path(take_record["path"]) + if sha256(take_path) != take_record["sha256"]: + raise ValueError(f"take hash mismatch: {take_path}") + with np.load(take_path, allow_pickle=False) as archive: + needed = ( + "frame_id", "frame_valid", "K_resized", "pred_wrist_translation", + "pred_joints_camera", "pred_direct_2d_px", "target_wrist_translation", + "target_joints_camera", "target_2d_px", "mano_annotation_valid", + "alignment_delta_z_m", "alignment_applied", + ) + arrays = {key: archive[key] for key in needed} + arrays["take"] = archive["take"] + take = str(arrays["take"]) + valid = arrays["mano_annotation_valid"].astype(bool) & arrays["frame_valid"][:, None] + indices = np.where(valid) + time_index, hand = indices + corrections, _, _ = corrections_for_take( + arrays, seed=seed, calibration=calibration, + ) + coarse = arrays["pred_wrist_translation"][time_index, hand].astype(np.float64) + joints = arrays["pred_joints_camera"][time_index, hand].astype(np.float64) + root_relative = joints - joints[:, :1] + anchors = arrays["pred_direct_2d_px"][time_index, hand].astype(np.float64) + K = arrays["K_resized"][time_index].astype(np.float64) + take_sample_keys = [ + (seed, take, int(arrays["frame_id"][t]), int(h)) + for t, h in zip(time_index, hand, strict=True) + ] + sample_order.extend(take_sample_keys) + for spec in specs: + candidate_id = str(spec["id"]) + z_mode = str(spec["z_mode"]) + refined_z = coarse[:, 2] + corrections[z_mode][time_index, hand] + translation, diagnostics = assemble( + spec, coarse=coarse, root_relative_joints=root_relative, + anchors=anchors, K=K, z=refined_z, + ) + metrics = evaluate_translation(arrays, indices, translation) + for metric, metric_values in metrics.items(): + values[candidate_id][metric].append(metric_values.astype(np.float32)) + success = diagnostics.get("success", np.ones(len(translation), dtype=bool)) + per_take[(candidate_id, seed, take)] = { + "absolute_mpjpe_mm": float(metrics["absolute_mpjpe_mm"].mean()), + "fingertip_mpjpe_mm": float(metrics["fingertip_mpjpe_mm"].mean()), + "translation_x_mae_mm": float(metrics["translation_x_mae_mm"].mean()), + "translation_y_mae_mm": float(metrics["translation_y_mae_mm"].mean()), + "translation_z_mae_mm": float(metrics["translation_z_mae_mm"].mean()), + "projected_mano_2d_px": float(metrics["projected_mano_2d_px"].mean()), + "success_fraction": float(success.mean()), + } + bank_records.append({ + "manifest": str(manifest_path), "sha256": registered["sha256"], + "seed": seed, "fold": int(manifest["fold"]), + "heldout_subject": manifest["heldout_subject"], + "takes": len(manifest["takes"]), "frames": int(manifest["frames"]), + }) + print(f"[{bank_index}/9] fold{manifest['fold']} seed{seed} complete", flush=True) + + if len(sample_order) != 333_936 or len(set(sample_order)) != len(sample_order): + raise ValueError("OOF sample coverage or uniqueness changed") + summary_rows = [] + concatenated: dict[str, dict[str, np.ndarray]] = {} + for spec in specs: + candidate_id = str(spec["id"]) + candidate_values = { + metric: np.concatenate(chunks) + for metric, chunks in values[candidate_id].items() + } + concatenated[candidate_id] = candidate_values + take_rows = [value for (name, _, _), value in per_take.items() if name == candidate_id] + z_mode = str(spec["z_mode"]) + baseline_id = f"direct_xyz__z_{z_mode}" + row: dict[str, object] = { + **spec, + "samples": len(candidate_values["absolute_mpjpe_mm"]), + "seed_take_groups": len(take_rows), + "absolute_frame_mean_mm": float(candidate_values["absolute_mpjpe_mm"].mean()), + "absolute_take_mean_mm": float(np.mean([item["absolute_mpjpe_mm"] for item in take_rows])), + "fingertip_frame_mean_mm": float(candidate_values["fingertip_mpjpe_mm"].mean()), + "translation_x_mae_mm": float(candidate_values["translation_x_mae_mm"].mean()), + "translation_x_p95_mm": float(np.percentile(candidate_values["translation_x_mae_mm"], 95)), + "translation_y_mae_mm": float(candidate_values["translation_y_mae_mm"].mean()), + "translation_y_p95_mm": float(np.percentile(candidate_values["translation_y_mae_mm"], 95)), + "translation_z_mae_mm": float(candidate_values["translation_z_mae_mm"].mean()), + "projected_mano_2d_px": float(candidate_values["projected_mano_2d_px"].mean()), + "direct_mano_consistency_px": float(candidate_values["direct_mano_consistency_px"].mean()), + "success_fraction": float(np.mean([item["success_fraction"] for item in take_rows])), + } + if candidate_id == baseline_id: + row.update({ + "absolute_frame_delta_vs_same_z_direct_mm": 0.0, + "absolute_take_delta_vs_same_z_direct_mm": 0.0, + "largest_take_harm_mm": 0.0, + "largest_sample_harm_mm": 0.0, + "absolute_guardrail_passed": True, + }) + summary_rows.append(row) + + row_by_id = {str(row["id"]): row for row in summary_rows} + for row in summary_rows: + candidate_id = str(row["id"]) + baseline_id = f"direct_xyz__z_{row['z_mode']}" + if candidate_id == baseline_id: + continue + baseline = row_by_id[baseline_id] + take_deltas = [] + for (name, seed, take), item in per_take.items(): + if name != candidate_id: + continue + take_deltas.append( + item["absolute_mpjpe_mm"] + - per_take[(baseline_id, seed, take)]["absolute_mpjpe_mm"] + ) + sample_delta = ( + concatenated[candidate_id]["absolute_mpjpe_mm"] + - concatenated[baseline_id]["absolute_mpjpe_mm"] + ) + frame_delta = float(row["absolute_frame_mean_mm"] - baseline["absolute_frame_mean_mm"]) + take_delta = float(row["absolute_take_mean_mm"] - baseline["absolute_take_mean_mm"]) + guardrail = min(0.2, 0.01 * float(baseline["absolute_frame_mean_mm"])) + row.update({ + "absolute_frame_delta_vs_same_z_direct_mm": frame_delta, + "absolute_take_delta_vs_same_z_direct_mm": take_delta, + "largest_take_harm_mm": float(np.max(take_deltas)), + "largest_sample_harm_mm": float(np.max(sample_delta)), + "absolute_guardrail_passed": frame_delta <= guardrail, + }) + + eligible = [ + row for row in summary_rows + if row["assembly"] != "direct_xyz" and row["absolute_guardrail_passed"] + ] + eligible.sort(key=lambda row: ( + float(row["absolute_take_mean_mm"]), + float(row["largest_take_harm_mm"]), + max(float(row["translation_x_p95_mm"]), float(row["translation_y_p95_mm"])), + float(row["projected_mano_2d_px"]), + distribution(concatenated[str(row["id"])]["absolute_mpjpe_mm"])["cvar95"], + 0 if row["assembly"] == "mixed_projection_21j_wls" else 1, + )) + if not eligible: + raise RuntimeError("no mixed-projection setting passes the preregistered guardrail") + best_take = float(eligible[0]["absolute_take_mean_mm"]) + tied = [row for row in eligible if float(row["absolute_take_mean_mm"]) <= best_take + 0.02] + tied.sort(key=lambda row: ( + float(row["largest_take_harm_mm"]), + max(float(row["translation_x_p95_mm"]), float(row["translation_y_p95_mm"])), + float(row["projected_mano_2d_px"]), + distribution(concatenated[str(row["id"])]["absolute_mpjpe_mm"])["cvar95"], + 0 if row["assembly"] == "mixed_projection_21j_wls" else 1, + )) + winner = tied[0] + winner_id = str(winner["id"]) + baseline_id = f"direct_xyz__z_{winner['z_mode']}" + winner_delta = ( + concatenated[winner_id]["absolute_mpjpe_mm"] + - concatenated[baseline_id]["absolute_mpjpe_mm"] + ) + order_gain = np.argsort(winner_delta)[:20] + order_harm = np.argsort(winner_delta)[-20:][::-1] + case_rows = [] + for role, order in (("largest_gain", order_gain), ("largest_harm", order_harm)): + for rank, index in enumerate(order, start=1): + seed, take, frame_id, hand = sample_order[int(index)] + case_rows.append({ + "role": role, "rank": rank, "sample_index": int(index), + "seed": seed, "take": take, "frame_id": frame_id, + "side": "right" if hand else "left", + "winner": winner_id, "baseline": baseline_id, + "absolute_delta_mm": float(winner_delta[index]), + "winner_absolute_mpjpe_mm": float(concatenated[winner_id]["absolute_mpjpe_mm"][index]), + "baseline_absolute_mpjpe_mm": float(concatenated[baseline_id]["absolute_mpjpe_mm"][index]), + }) + + write_csv(args.output_dir / "oof_grid.csv", summary_rows) + write_csv(args.output_dir / "largest_gain_harm.csv", case_rows) + report = { + "status": "selected_oof_only", + "experiment": "P6_S1_cache_mixed_projection", + "official_validation_used": False, + "official_test_used": False, + "oracle_information": False, + "samples": len(sample_order), + "seed_take_groups": len({(seed, take) for seed, take, _, _ in sample_order}), + "physical_takes": len({take for _, take, _, _ in sample_order}), + "seeds": sorted({seed for seed, _, _, _ in sample_order}), + "banks": bank_records, + "calibration": { + "json": str(args.calibration_json.resolve()), + "json_sha256": sha256(args.calibration_json), + "cross_validated_predictions": str(args.calibration_predictions.resolve()), + "predictions_sha256": sha256(args.calibration_predictions), + "confidence_threshold": 0.6, + }, + "grid": { + "conditions": len(specs), "minimum_support": [4, 8, 12], + "huber_delta_px": [2.0, 4.0, 8.0, 16.0], + "irls_iterations": 5, + "mask": "predicted finite + positive z>0.05m + in-frame anchor", + "fallback": "coarse wrist ray at same selected z; direct xyz if K invalid", + }, + "selection_rule": ( + "minimize seed-take-equal Absolute within same-z direct guardrail; " + "0.02mm tie band then largest-take harm, xy P95, projected 2D, CVaR95, WLS simplicity" + ), + "winner": winner, + "same_z_direct_baseline": row_by_id[baseline_id], + "outputs": {"grid": "oof_grid.csv", "largest_gain_harm": "largest_gain_harm.csv"}, + } + (args.output_dir / "selection.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "winner": winner_id, + "absolute_take_mean_mm": winner["absolute_take_mean_mm"], + "absolute_delta_mm": winner["absolute_take_delta_vs_same_z_direct_mm"], + "projected_mano_2d_px": winner["projected_mano_2d_px"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/seed_phase9_cache_hardlinks.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/seed_phase9_cache_hardlinks.py new file mode 100644 index 0000000000000000000000000000000000000000..24c63f0ecef2de0911cd4cb725ab7bafc274d7f5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/seed_phase9_cache_hardlinks.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Seed an expanded cache with hash-verified hardlinks from an older cache.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def seed_hardlinks( + manifest: Path, output_dir: Path, expected_dataset: str, +) -> dict[str, Any]: + rows = [ + json.loads(line) for line in manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not rows or {row.get("dataset_id") for row in rows} != {expected_dataset}: + raise ValueError("source cache manifest dataset differs from expectation") + clips_dir = output_dir / "clips" + clips_dir.mkdir(parents=True, exist_ok=True) + logical_bytes = 0 + reused = 0 + for row in rows: + source = Path(row["cache_path"]) + if not source.is_file() or sha256(source) != row["cache_sha256"]: + raise ValueError(f"source payload is missing or differs: {source}") + target = clips_dir / source.name + if target.exists(): + if not target.is_file() or sha256(target) != row["cache_sha256"]: + raise ValueError(f"existing target payload differs: {target}") + else: + os.link(source, target) + logical_bytes += source.stat().st_size + reused += 1 + return { + "schema_version": "phase9_cache_hardlink_seed_v1", + "status": "complete", + "dataset": expected_dataset, + "source_manifest": {"path": str(manifest.resolve()), "sha256": sha256(manifest)}, + "output_dir": str(output_dir.resolve()), + "hardlinked_clips": reused, + "logical_bytes": logical_bytes, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--source-cache-manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--dataset", choices=("HOT3D", "HOI4D", "ARCTIC"), required=True) + parser.add_argument("--report", type=Path, required=True) + args = parser.parse_args() + if args.report.exists(): + parser.error("report already exists") + try: + result = seed_hardlinks(args.source_cache_manifest, args.output_dir, args.dataset) + except (OSError, ValueError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.report.parent.mkdir(parents=True, exist_ok=True) + temporary = args.report.with_suffix(".tmp") + temporary.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + temporary.replace(args.report) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/select_phase7_external_continuation.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/select_phase7_external_continuation.py new file mode 100644 index 0000000000000000000000000000000000000000..b9332b63326456953ca11d008b1a0f69c2b42c24 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/select_phase7_external_continuation.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Select the final external checkpoint across frozen continuation steps.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.rank_phase7_external import METRICS, dense_ranks, evaluation_metrics, pareto_frontier +from scripts.build_phase7_scale_eval_queue import sha256 + + +DATASETS = ("ARCTIC", "HOI4D", "HOT3D") + + +def load_candidates(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if manifest.get("selection_split") != "external_heldout_only": + raise ValueError("continuation selection must be external-heldout only") + if set(manifest.get("datasets", [])) != set(DATASETS): + raise ValueError("continuation selection requires all three external datasets") + entries: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + for item in manifest.get("evaluations", []): + candidate, dataset = str(item["candidate"]), str(item["dataset"]) + if dataset not in DATASETS or (candidate, dataset) in seen: + raise ValueError(f"invalid or duplicate candidate/dataset pair: {(candidate, dataset)}") + seen.add((candidate, dataset)) + path = Path(item["path"]).resolve() + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + or "h2o" in str(report["cache_manifest"]["path"]).lower() + ): + raise ValueError(f"non-external evaluation in continuation selection: {path}") + checkpoint = Path(report["checkpoint"]["path"]) + config = Path(report["config"]["path"]) + if sha256(checkpoint) != report["checkpoint"]["sha256"]: + raise ValueError(f"checkpoint hash mismatch: {checkpoint}") + if sha256(config) != report["config"]["sha256"]: + raise ValueError(f"config hash mismatch: {config}") + take_path = Path(report["take_metrics"]["path"]) + if sha256(take_path) != report["take_metrics"]["sha256"]: + raise ValueError(f"take metrics hash mismatch: {take_path}") + per_hand_path = Path(report["per_hand_rows"]["path"]) + if sha256(per_hand_path) != report["per_hand_rows"]["sha256"]: + raise ValueError(f"per-hand metrics hash mismatch: {per_hand_path}") + entries.append({ + "candidate": candidate, "dataset": dataset, + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint_path": str(checkpoint.resolve()), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config_path": str(config.resolve()), + "config_sha256": report["config"]["sha256"], + "evaluation_path": str(path), "take_metrics_path": str(take_path.resolve()), + "per_hand_metrics_path": str(per_hand_path.resolve()), + **evaluation_metrics(report), + }) + candidates = {entry["candidate"] for entry in entries} + missing = {(candidate, dataset) for candidate in candidates for dataset in DATASETS} - seen + if missing or len(candidates) < 2: + raise ValueError(f"incomplete continuation candidate grid: {sorted(missing)}") + for candidate in candidates: + selected = [entry for entry in entries if entry["candidate"] == candidate] + for field in ("checkpoint_step", "checkpoint_path", "checkpoint_sha256", "config_path", "config_sha256"): + if len({entry[field] for entry in selected}) != 1: + raise ValueError(f"candidate {candidate} has inconsistent {field}") + return entries + + +def rank_candidates(entries: list[dict[str, Any]]) -> dict[str, Any]: + candidates = sorted({entry["candidate"] for entry in entries}) + lookup = {(entry["candidate"], entry["dataset"]): entry for entry in entries} + dataset_ranks: dict[str, dict[str, float]] = {} + vectors = {candidate: [] for candidate in candidates} + for dataset in DATASETS: + ranks = { + metric: dense_ranks({candidate: lookup[(candidate, dataset)][metric] for candidate in candidates}) + for metric in METRICS + } + dataset_ranks[dataset] = {} + for candidate in candidates: + dataset_ranks[dataset][candidate] = sum(ranks[metric][candidate] for metric in METRICS) / len(METRICS) + vectors[candidate].extend(lookup[(candidate, dataset)][metric] for metric in METRICS) + macro = { + candidate: sum(dataset_ranks[dataset][candidate] for dataset in DATASETS) / len(DATASETS) + for candidate in candidates + } + order = sorted(candidates, key=lambda candidate: ( + macro[candidate], + sum(lookup[(candidate, dataset)]["absolute_mpjpe_mm"] for dataset in DATASETS), + sum(lookup[(candidate, dataset)]["root_relative_mpjpe_mm"] for dataset in DATASETS), + candidate, + )) + return { + "dataset_ranks": dataset_ranks, "macro_mean_rank": macro, + "pareto_frontier": pareto_frontier(vectors), "order": order, "winner": order[0], + } + + +def read_take_values( + path: Path, metric: str, statistic: str = "mean", +) -> dict[str, float]: + with path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + grouped: dict[str, list[float]] = {} + for row in rows: + value = float(row[metric]) + if math.isfinite(value): + grouped.setdefault(row["physical_recording_id"], []).append(value) + if statistic == "mean": + values = {key: float(np.mean(group)) for key, group in grouped.items()} + elif statistic == "p95": + values = {key: float(np.quantile(group, .95)) for key, group in grouped.items()} + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + if not values: + raise ValueError(f"no finite {metric} take values: {path}") + return values + + +def paired_take_bootstrap( + reference_path: Path, candidate_path: Path, metric: str, seed: int, resamples: int, + statistic: str = "mean", +) -> dict[str, Any]: + reference = read_take_values(reference_path, metric, statistic) + candidate = read_take_values(candidate_path, metric, statistic) + if set(reference) != set(candidate): + raise ValueError(f"paired take IDs differ for {metric}") + keys = sorted(reference) + delta = np.asarray([candidate[key] - reference[key] for key in keys], dtype=np.float64) + rng = np.random.default_rng(seed) + samples = delta[rng.integers(0, len(delta), size=(resamples, len(delta)))].mean(axis=1) + return { + "unit": "physical_recording", "recording_statistic": statistic, + "take_count": len(delta), + "delta_definition": "candidate_minus_reference; negative favors candidate", + "mean_delta": float(delta.mean()), + "ci95_low": float(np.percentile(samples, 2.5)), + "ci95_high": float(np.percentile(samples, 97.5)), + "resamples": resamples, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--funnel-selection", type=Path, required=True) + parser.add_argument("--expected-funnel-winner", required=True) + parser.add_argument("--reference-candidate", required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + parser.add_argument("--seed", type=int, default=20260717) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + funnel = json.loads(args.funnel_selection.read_text(encoding="utf-8")) + if ( + funnel.get("status") != "ranked_external_only" + or funnel.get("winner") != args.expected_funnel_winner + or funnel.get("h2o_used") is not False + or funnel.get("official_test_used") is not False + ): + parser.error("funnel selection does not match the frozen external-only decision") + manifest = json.loads(args.manifest.read_text(encoding="utf-8")) + entries = load_candidates(manifest) + ranking = rank_candidates(entries) + if args.reference_candidate not in ranking["order"]: + parser.error("reference candidate is absent") + lookup = {(entry["candidate"], entry["dataset"]): entry for entry in entries} + paired: dict[str, Any] = {} + paired_specs = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), + } + for candidate in ranking["order"]: + if candidate == args.reference_candidate: + continue + paired[candidate] = { + dataset: { + metric_name: paired_take_bootstrap( + Path(lookup[(args.reference_candidate, dataset)]["per_hand_metrics_path"]), + Path(lookup[(candidate, dataset)]["per_hand_metrics_path"]), + row_metric, args.seed, args.bootstrap_resamples, statistic, + ) + for metric_name, (row_metric, statistic) in paired_specs.items() + } + for dataset in DATASETS + } + winner = ranking["winner"] + winner_entries = [entry for entry in entries if entry["candidate"] == winner] + first = winner_entries[0] + result = { + "status": "selected_external_generalist_no_h2o", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "selection_rule": "dataset metric ranks -> macro mean rank -> Absolute/root-relative tie-break", + "selection_split": "external_heldout_only", "frame_count_weighted": False, + "funnel_selection": { + "path": str(args.funnel_selection.resolve()), "sha256": sha256(args.funnel_selection), + "winner": args.expected_funnel_winner, + }, + "candidate_manifest": {"path": str(args.manifest.resolve()), "sha256": sha256(args.manifest)}, + "reference_candidate": args.reference_candidate, + **ranking, "entries": entries, "paired_take_bootstrap": paired, + "checkpoint": { + "path": first["checkpoint_path"], "sha256": first["checkpoint_sha256"], + "step": first["checkpoint_step"], + }, + "config": {"path": first["config_path"], "sha256": first["config_sha256"]}, + "h2o_training_data_used": False, + "h2o_official_validation_used_for_external_selection": False, + "official_test_used": False, + } + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/select_phase7_h2o_adaptation.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/select_phase7_h2o_adaptation.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8d06a6082f25489ca5816a83149e0eba2424aa --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/select_phase7_h2o_adaptation.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Select a Phase 7 adaptation branch using H2O train-group-heldout only.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +import numpy as np + +from scripts.build_phase7_scale_eval_queue import sha256 + + +PRIMARY_METRIC = "absolute_mpjpe_mm" +METRIC_SPECS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} +IDENTITY_FIELDS = ("physical_recording_id", "camera_id", "frame_id", "side") + + +def checked_artifact(record: dict[str, Any], name: str) -> Path: + artifact = record[name] + path = Path(artifact["path"]).resolve() + if not path.is_file() or sha256(path) != artifact["sha256"]: + raise ValueError(f"{name} is missing or has a SHA256 mismatch: {path}") + return path + + +def load_candidates(manifest: dict[str, Any]) -> list[dict[str, Any]]: + if ( + manifest.get("selection_split") != "h2o_train_group_heldout_only" + or manifest.get("h2o_official_validation_used") is not False + or manifest.get("official_test_used") is not False + ): + raise ValueError("selection manifest violates the H2O train-heldout boundary") + candidates: list[dict[str, Any]] = [] + names: set[str] = set() + cache_sha256: set[str] = set() + for item in manifest.get("candidates", []): + name = str(item["candidate"]) + if name in names: + raise ValueError(f"duplicate candidate: {name}") + names.add(name) + report_path = Path(item["evaluation"]).resolve() + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_h2o_train_group_heldout" + or report.get("evaluation_role") != "h2o_train_group_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("h2o_official_validation_used") is not False + or report.get("official_test_used") is not False + or Path(report["cache_manifest"]["path"]).name != "train_group_heldout.jsonl" + ): + raise ValueError(f"candidate is not a valid train-heldout evaluation: {report_path}") + checkpoint = checked_artifact(report, "checkpoint") + config = checked_artifact(report, "config") + per_hand = checked_artifact(report, "per_hand_rows") + checked_artifact(report, "take_metrics") + cache = checked_artifact(report, "cache_manifest") + cache_sha256.add(report["cache_manifest"]["sha256"]) + metrics = { + metric: float(report["metrics"][row_metric]["mean"]) + for metric, (row_metric, statistic) in METRIC_SPECS.items() + if statistic == "mean" + } + metrics["translation_z_p95_mm"] = float( + report["metrics"]["translation_z_mae_mm"]["p95"] + ) + if not all(math.isfinite(value) for value in metrics.values()): + raise ValueError(f"candidate contains non-finite metrics: {name}") + candidates.append({ + "candidate": name, + "evaluation": str(report_path), + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint": str(checkpoint), + "checkpoint_sha256": report["checkpoint"]["sha256"], + "config": str(config), + "config_sha256": report["config"]["sha256"], + "cache_manifest": str(cache), + "cache_manifest_sha256": report["cache_manifest"]["sha256"], + "per_hand_rows": str(per_hand), + "metrics": metrics, + }) + if len(candidates) < 2: + raise ValueError("adaptation selection requires at least two candidates") + if len(cache_sha256) != 1: + raise ValueError("adaptation candidates use different train-heldout manifests") + return candidates + + +def read_paired_rows(path: Path, metric: str) -> dict[tuple[str, ...], float]: + result: dict[tuple[str, ...], float] = {} + with path.open(newline="", encoding="utf-8") as handle: + for row in csv.DictReader(handle): + identity = tuple(str(row[field]) for field in IDENTITY_FIELDS) + if identity in result: + raise ValueError(f"duplicate per-hand identity: {identity}") + result[identity] = float(row[metric]) + return result + + +def paired_recording_bootstrap( + reference: Path, + candidate: Path, + metric: str, + statistic: str, + seed: int, + resamples: int, +) -> dict[str, Any]: + reference_rows = read_paired_rows(reference, metric) + candidate_rows = read_paired_rows(candidate, metric) + if set(reference_rows) != set(candidate_rows): + raise ValueError(f"paired per-hand identities differ for {metric}") + grouped: dict[str, list[tuple[float, float]]] = {} + for identity in sorted(reference_rows): + reference_value, candidate_value = reference_rows[identity], candidate_rows[identity] + if math.isfinite(reference_value) and math.isfinite(candidate_value): + grouped.setdefault(identity[0], []).append((reference_value, candidate_value)) + if not grouped: + raise ValueError(f"no finite paired values for {metric}") + deltas = [] + for recording in sorted(grouped): + values = np.asarray(grouped[recording], dtype=np.float64) + if statistic == "mean": + delta = values[:, 1].mean() - values[:, 0].mean() + elif statistic == "p95": + delta = np.quantile(values[:, 1], .95) - np.quantile(values[:, 0], .95) + else: + raise ValueError(f"unsupported recording statistic: {statistic}") + deltas.append(float(delta)) + array = np.asarray(deltas, dtype=np.float64) + rng = np.random.default_rng(seed) + samples = array[rng.integers(0, len(array), size=(resamples, len(array)))].mean(1) + return { + "unit": "physical_recording", + "recording_statistic": statistic, + "recordings": len(array), + "delta_definition": "candidate_minus_reference; negative favors candidate", + "mean_delta": float(array.mean()), + "ci95_low": float(np.quantile(samples, .025)), + "ci95_high": float(np.quantile(samples, .975)), + "resamples": resamples, + } + + +def select( + manifest: dict[str, Any], seed: int = 20260717, resamples: int = 2000, +) -> dict[str, Any]: + candidates = load_candidates(manifest) + order = sorted(candidates, key=lambda item: ( + item["metrics"][PRIMARY_METRIC], + item["metrics"]["root_relative_mpjpe_mm"], + item["metrics"]["fingertip_mpjpe_mm"], + item["candidate"], + )) + reference = order[0] + paired = {} + for candidate in order[1:]: + paired[candidate["candidate"]] = { + metric_name: paired_recording_bootstrap( + Path(reference["per_hand_rows"]), Path(candidate["per_hand_rows"]), + row_metric, statistic, seed, resamples, + ) + for metric_name, (row_metric, statistic) in METRIC_SPECS.items() + } + return { + "status": "selected_h2o_adaptation_train_group_heldout", + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "selection_rule": "lowest train-group-heldout Absolute MPJPE; root-relative then fingertip tie-break; no multi-seed or one-percent gate", + "selection_split": "h2o_train_group_heldout_only", + "primary_metric": PRIMARY_METRIC, + "winner": reference["candidate"], + "order": [item["candidate"] for item in order], + "candidates": candidates, + "paired_recording_bootstrap_vs_winner": paired, + "h2o_training_data_used": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--seed", type=int, default=20260717) + parser.add_argument("--bootstrap-resamples", type=int, default=2000) + args = parser.parse_args() + if args.output.exists(): + parser.error("output already exists") + result = select( + json.loads(args.manifest.read_text(encoding="utf-8")), + seed=args.seed, + resamples=args.bootstrap_resamples, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase4_a3.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase4_a3.py new file mode 100644 index 0000000000000000000000000000000000000000..d8de0510886c2ea270a8dc11eb799add21226b64 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase4_a3.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +"""Real-batch equality/backward smoke for the A3 oracle crop refiner.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def attach_gt_vertices( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> None: + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + with torch.no_grad(): + vertices, _ = model.mano_layer( + axis_angle_to_matrix(pose), + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = ( + batch["mano_annotation_valid"].bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where( + valid, vertices, torch.full_like(vertices, torch.nan), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--base-config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--expected-checkpoint-sha256", required=True) + parser.add_argument("--mode", choices=( + "oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k", + ), required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + actual_hash = file_sha256(args.checkpoint) + if actual_hash != args.expected_checkpoint_sha256: + parser.error( + f"checkpoint hash mismatch: {actual_hash} != {args.expected_checkpoint_sha256}" + ) + args.output_dir.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load(args.base_config.read_text(encoding="utf-8")) + seed = int(config["seed"]) + torch.manual_seed(seed) + data, assets = config["data"], config["assets"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + photometric_augmentation=data.get("photometric_augmentation"), + augmentation_seed=seed, oracle_crop_enabled=True, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + device = torch.device(f"cuda:{args.gpu}") + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + common_model = { + **config["model"], + "dinov3_source": assets["dinov3_source"], + "dinov3_weights": assets["dinov3_weights"], + "mano_root": assets["mano_root"], + } + base = BimanualReconstructionModel(ModelConfig(**common_model)).to(device).eval() + load_checkpoint(args.checkpoint, base, optimizer=None, map_location=device) + refined_config = ModelConfig( + **common_model, oracle_crop_mode=args.mode, + freeze_coarse_for_oracle_crop=True, + ) + refined = BimanualReconstructionModel(refined_config).to(device).eval() + initialization = load_model_initialization( + args.checkpoint, refined, + allowed_missing_prefixes=("oracle_crop_",), map_location=device, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + with torch.inference_mode(), torch.autocast("cuda", dtype=dtype): + base_output = base(batch) + refined_output = refined(batch) + comparisons = { + "joint2d": torch.equal( + base_output["joint2d_norm"], refined_output["joint2d_norm"], + ), + "rotations": torch.equal( + base_output["mano_rotation_matrices"], + refined_output["coarse_mano_rotation_matrices"], + ) and torch.equal( + refined_output["mano_rotation_matrices"], + refined_output["coarse_mano_rotation_matrices"], + ), + "shape": torch.equal( + base_output["mano_shape"], refined_output["coarse_mano_shape"], + ) and torch.equal( + refined_output["mano_shape"], refined_output["coarse_mano_shape"], + ), + "translation": torch.equal( + base_output["wrist_root_translation"], + refined_output["coarse_wrist_root_translation"], + ) and torch.equal( + refined_output["wrist_root_translation"], + refined_output["coarse_wrist_root_translation"], + ), + "joints": torch.equal( + base_output["joints_camera"], refined_output["coarse_joints_camera"], + ) and torch.equal( + refined_output["joints_camera"], refined_output["coarse_joints_camera"], + ), + "vertices": torch.equal( + base_output["vertices_camera"], refined_output["coarse_vertices_camera"], + ) and torch.equal( + refined_output["vertices_camera"], refined_output["coarse_vertices_camera"], + ), + } + if not all(comparisons.values()): + raise RuntimeError(f"zero-init coarse/refined equality failed: {comparisons}") + del base, base_output, refined_output + torch.cuda.empty_cache() + + refined.train() + attach_gt_vertices(batch, refined) + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + trainable = { + name: value for name, value in refined.named_parameters() + if value.requires_grad + } + if not trainable or any(not name.startswith("oracle_crop_") for name in trainable): + raise RuntimeError("A3 smoke found trainable non-oracle parameters") + optimizer = torch.optim.AdamW(trainable.values(), lr=5e-5, weight_decay=0.05) + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=dtype): + prediction = refined(batch) + losses = criterion(prediction, batch) + losses["total"].backward() + gradients_finite = all( + parameter.grad is None or bool(torch.isfinite(parameter.grad).all()) + for parameter in trainable.values() + ) + heads_with_gradient = sorted( + name for name, parameter in trainable.items() + if parameter.grad is not None and bool(torch.count_nonzero(parameter.grad)) + ) + if not gradients_finite or not heads_with_gradient: + raise RuntimeError("A3 smoke backward did not produce finite head gradients") + optimizer.step() + smoke_checkpoint = args.output_dir / "smoke_checkpoint.pt" + save_checkpoint( + smoke_checkpoint, refined, optimizer, 1, + extra={ + "phase": 4, "wave": "A3", "mode": args.mode, + "coarse_checkpoint_sha256": actual_hash, + "official_test_used": False, + }, + exclude_prefixes=("rgb_encoder.backbone.",), + ) + reloaded = BimanualReconstructionModel(refined_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + [value for value in reloaded.parameters() if value.requires_grad], + lr=5e-5, weight_decay=0.05, + ) + resume = load_checkpoint( + smoke_checkpoint, reloaded, reloaded_optimizer, map_location=device, + ) + reload_exact = all( + key.startswith("rgb_encoder.backbone.") + or torch.equal(value, reloaded.state_dict()[key]) + for key, value in refined.state_dict().items() + ) + payload = { + "status": "passed", + "official_test_used": False, + "mode": args.mode, + "seed": seed, + "coarse_checkpoint": { + "path": str(args.checkpoint.resolve()), + "sha256": actual_hash, + "step": initialization["step"], + }, + "initialization_residual_missing_keys": initialization["residual_missing_keys"], + "checkpoint_excluded_prefixes": initialization[ + "checkpoint_excluded_prefixes" + ], + "zero_init_exact": comparisons, + "trainable_parameters": sum(value.numel() for value in trainable.values()), + "trainable_names_oracle_only": True, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "gradients_finite": gradients_finite, + "heads_with_gradient": heads_with_gradient, + "checkpoint_reload_exact": bool(reload_exact and resume["step"] == 1), + "oracle_crop_available_fraction": float( + batch["oracle_crop_available"].float().mean() + ), + "oracle_crop_depth_available_fraction": float( + batch["oracle_crop_depth_available"].float().mean() + ), + } + if not payload["checkpoint_reload_exact"]: + raise RuntimeError("A3 smoke checkpoint reload was not exact") + (args.output_dir / "smoke.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(payload, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase5_structured.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase5_structured.py new file mode 100644 index 0000000000000000000000000000000000000000..32656058c47b6e540b61932cf600b3a86860e640 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase5_structured.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Real-checkpoint forward/backward smoke for Phase 5 structured refinement.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + raise FileExistsError("structured smoke output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if not config.get("model", {}).get("structured_hand_refinement", False): + raise ValueError("smoke requires a structured-hand config") + expected_hash = config.get("experiment", {}).get("coarse_checkpoint_sha256") + if sha256(args.checkpoint) != expected_hash: + raise ValueError("coarse checkpoint hash does not match the registered config") + seed = int(config["seed"]) + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("structured_",), + map_location=device, + ) + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=5e-6, weight_decay=0.05) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + exact_zero_init = { + "joint2d": torch.equal(prediction["joint2d_norm"], prediction["coarse_joint2d_norm"]), + "rotation": torch.equal( + prediction["mano_rotation_matrices"], + prediction["coarse_mano_rotation_matrices"], + ), + "shape_sequence": torch.equal( + prediction["mano_shape_sequence"], + prediction["coarse_mano_shape_sequence"], + ), + "shape": torch.equal(prediction["mano_shape"], prediction["coarse_mano_shape"]), + "translation": torch.equal( + prediction["wrist_root_translation"], + prediction["coarse_wrist_root_translation"], + ), + } + losses["total"].backward() + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + residual_head_gradients = { + name: bool( + parameter.grad is not None and torch.isfinite(parameter.grad).all() + ) + for name, parameter in model.named_parameters() + if name.startswith("structured_") and name.endswith("weight") + } + required_head_gradients = { + name: finite for name, finite in residual_head_gradients.items() + if model_config.structured_refine_translation + or not name.startswith("structured_translation_head.") + } + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + args.output_dir.mkdir(parents=True, exist_ok=True) + checkpoint = args.output_dir / "structured_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, step=1, + extra={"kind": "phase5_structured_real_checkpoint_smoke"}, + exclude_prefixes=("rgb_encoder.backbone.",), + ) + expected_state = { + key: value.detach().cpu().clone() + for key, value in model.state_dict().items() + if not key.startswith("rgb_encoder.backbone.") + } + del prediction, losses, model, optimizer, criterion + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW(reloaded.parameters(), lr=5e-6, weight_decay=0.05) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected_state.items() + ) + shared_initialization_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("structured_", "rgb_encoder.backbone.")) + ] + passed = bool( + all(exact_zero_init.values()) + and all(required_head_gradients.values()) + and all(np.isfinite(value) for value in loss_values.values()) + and not shared_initialization_missing + and resume_exact + and resumed["step"] == 1 + ) + result = { + "status": "passed" if passed else "failed", + "experiment_class": "engineering_real_checkpoint_smoke", + "formal_training": False, + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "seed": seed, + "resolution_hw": data["resolution_hw"], + "T": data["T"], + "precision": config["precision"], + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_initialization_missing, + "exact_zero_initialization": exact_zero_init, + "losses": loss_values, + "losses_finite": all(np.isfinite(value) for value in loss_values.values()), + "gradient_norm": gradient_norm, + "residual_head_gradients_finite": residual_head_gradients, + "required_residual_head_gradients_finite": required_head_gradients, + "elapsed_s": elapsed, + "frames_per_s": int(data["T"]) / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "smoke_checkpoint": { + "path": str(checkpoint.resolve()), "sha256": sha256(checkpoint), + }, + "trainable_parameters": sum( + parameter.numel() for parameter in reloaded.parameters() + if parameter.requires_grad + ), + "frozen_parameters": sum( + parameter.numel() for parameter in reloaded.parameters() + if not parameter.requires_grad + ), + } + (args.output_dir / "smoke.json").write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": result["status"], "exact_zero_initialization": exact_zero_init, + "resume_exact": resume_exact, "checkpoint": result["smoke_checkpoint"], + }, indent=2)) + if result["status"] != "passed": + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase6_mixed_projection.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase6_mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..e77188fd1466a88d3953ae576c22e44590e495bc --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase6_mixed_projection.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Real-checkpoint smoke for differentiable Phase 6 mixed projection.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def prefix(batch: dict[str, object], length: int) -> dict[str, object]: + output = {} + for key, value in batch.items(): + output[key] = ( + value[:, :length] if torch.is_tensor(value) and value.ndim >= 2 + and value.shape[1] == batch["frame_valid"].shape[1] + else value + ) + return output + + +def attach_gt_vertices( + batch: dict[str, torch.Tensor], model: BimanualReconstructionModel, +) -> None: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for the real-batch smoke") + pose = torch.nan_to_num(batch["mano_pose"]).reshape( + *batch["mano_pose"].shape[:-1], 16, 3, + ) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, _ = model.mano_layer( + rotations, + torch.nan_to_num(batch["mano_shape"]), + torch.nan_to_num(batch["wrist_root_translation"]), + ) + valid = ( + batch["mano_annotation_valid"].bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where( + valid, vertices, torch.full_like(vertices, torch.nan), + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if config["model"].get("translation_parameterization") != "mixed_projection": + parser.error("smoke requires mixed_projection") + if sha256(args.checkpoint) != config["experiment"]["coarse_checkpoint_sha256"]: + parser.error("checkpoint hash differs from preregistration") + seed = int(config["seed"]) + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("mixed_log_tz_head",), + map_location=device, + ) + model.initialize_mixed_log_tz_from_direct_head() + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + learning_rate = float(config["protocol"]["learning_rate"]) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + attach_gt_vertices(batch, model) + args.output_dir.mkdir(parents=True, exist_ok=True) + excluded = checkpoint_excluded_prefixes(model) + initialized_checkpoint = args.output_dir / "mixed_projection_initialized_step0.pt" + save_checkpoint( + initialized_checkpoint, model, optimizer, 0, + extra={"kind": "phase6_mixed_projection_initialized_step0"}, + exclude_prefixes=excluded, + ) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + success_fraction = float(prediction["mixed_projection_success"].float().mean()) + teacher_z_difference_mm = float( + 1000.0 * ( + prediction["wrist_root_translation"][..., 2] + - prediction["mixed_projection_direct_teacher_translation"][..., 2] + ).abs().mean() + ) + losses["total"].backward() + gradient_groups = { + "log_tz": ["mixed_log_tz_head."], + "joint2d": ["joint2d_head."], + "pose": ["rotation_head."], + "shape": ["shape_head."], + "decoder": ["decoder."], + } + gradients = {} + for group, prefixes in gradient_groups.items(): + selected = [ + parameter.grad for name, parameter in model.named_parameters() + if parameter.requires_grad and name.startswith(tuple(prefixes)) + ] + gradients[group] = bool( + selected + and all(value is None or torch.isfinite(value).all() for value in selected) + and any(value.abs().sum() > 0 for value in selected if value is not None) + ) + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + model.eval() + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + t1 = model(prefix(batch, 1)) + t1_finite = bool( + torch.isfinite(t1["wrist_root_translation"]).all() + and torch.isfinite(t1["joints_camera"]).all() + ) + checkpoint = args.output_dir / "mixed_projection_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, 1, + extra={"kind": "phase6_mixed_projection_real_checkpoint_smoke"}, + exclude_prefixes=excluded, + ) + expected = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + if not key.startswith(excluded) + } + del model, optimizer, criterion, prediction, losses, t1 + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + reloaded, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected.items() + ) + shared_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("mixed_log_tz_head", "rgb_encoder.backbone.")) + ] + passed = bool( + all(np.isfinite(value) for value in loss_values.values()) + and success_fraction >= 0.99 + and all(gradients.values()) + and t1_finite + and resume_exact + and resumed["step"] == 1 + and not shared_missing + ) + report = { + "status": "passed" if passed else "failed", + "experiment": "P6_S2_differentiable_mixed_projection", + "experiment_class": "engineering_real_checkpoint_smoke", + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_missing, + "mixed_log_tz_initialization": "first-order log-softplus linearization", + "losses": loss_values, + "success_fraction": success_fraction, + "teacher_z_difference_mm": teacher_z_difference_mm, + "gradient_groups_finite_nonzero": gradients, + "gradient_norm": gradient_norm, + "T1_finite": t1_finite, + "T8_finite": all(np.isfinite(value) for value in loss_values.values()), + "elapsed_s": elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "initialized_checkpoint": { + "path": str(initialized_checkpoint.resolve()), + "sha256": sha256(initialized_checkpoint), + "step": 0, + }, + "checkpoint": {"path": str(checkpoint.resolve()), "sha256": sha256(checkpoint)}, + "trainable_parameters": sum(p.numel() for p in reloaded.parameters() if p.requires_grad), + "frozen_parameters": sum(p.numel() for p in reloaded.parameters() if not p.requires_grad), + } + (args.output_dir / "smoke.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "success_fraction": success_fraction, + "gradients": gradients, "resume_exact": resume_exact, + "output": str(args.output_dir), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase6_spatial_joint2d.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase6_spatial_joint2d.py new file mode 100644 index 0000000000000000000000000000000000000000..9c44a3f4073745881c46c5bdcea4843985a927ff --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_phase6_spatial_joint2d.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Real-checkpoint smoke for the Phase 6 spatial joint localizer.""" + +from __future__ import annotations + +import argparse +import json +import random +import time +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, +) +from scripts.smoke_phase6_mixed_projection import attach_gt_vertices, prefix, sha256 + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + args = parser.parse_args() + if args.output_dir.exists() and any(args.output_dir.iterdir()): + parser.error("output directory must be new or empty") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + if config["model"].get("joint2d_parameterization") != "spatial_heatmap": + parser.error("spatial smoke requires joint2d_parameterization=spatial_heatmap") + if sha256(args.checkpoint) != config["experiment"]["coarse_checkpoint_sha256"]: + parser.error("checkpoint hash differs from preregistration") + seed = int(config["seed"]) + random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + device = torch.device(f"cuda:{args.gpu}") + data = config["data"] + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data["resolution_hw"]), + (int(data["T"]),), (int(data["stride"]),), max_clips=1, + ) + batch = next(iter(DataLoader( + dataset, batch_size=1, shuffle=False, num_workers=0, + collate_fn=collate_h2o_clips, + ))) + batch = { + key: value.to(device) if torch.is_tensor(value) else value + for key, value in batch.items() + } + assets = config["assets"] + model_config = ModelConfig( + **config["model"], dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"], + ) + model = BimanualReconstructionModel(model_config).to(device).train() + initialization = load_model_initialization( + args.checkpoint, model, allowed_missing_prefixes=("joint_localization_",), + map_location=device, + ) + criterion = BimanualLoss(LossConfig(**config["loss"])).to(device) + learning_rate = float(config["protocol"]["learning_rate"]) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, learning_rate=learning_rate, backbone_learning_rate=None, + ), + lr=learning_rate, weight_decay=0.05, + ) + attach_gt_vertices(batch, model) + args.output_dir.mkdir(parents=True, exist_ok=True) + excluded = checkpoint_excluded_prefixes(model) + initialized_checkpoint = args.output_dir / "spatial_joint2d_initialized_step0.pt" + save_checkpoint( + initialized_checkpoint, model, optimizer, 0, + extra={"kind": "phase6_spatial_joint2d_initialized_step0"}, + exclude_prefixes=excluded, + ) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_values = {name: float(value.detach()) for name, value in losses.items()} + height, width = map(int, batch["image_hw"][0].tolist()) + teacher_difference_px = float(( + (prediction["joint2d_norm"] - prediction["joint2d_linear_teacher_norm"]) + * prediction["joint2d_norm"].new_tensor((width, height)) + ).abs().mean()) + entropy = prediction["joint2d_heatmap_entropy"] + entropy_finite_bounded = bool( + torch.isfinite(entropy).all() and (entropy >= 0).all() and (entropy <= 1.0 + 1e-6).all() + ) + losses["total"].backward() + groups = { + "embedding": ("joint_localization_embedding",), + "query": ("joint_localization_query.",), + "feature": ("joint_localization_feature.",), + "offset": ("joint_localization_offset.",), + "decoder": ("decoder.",), + } + gradients = {} + for group, prefixes in groups.items(): + selected = [ + parameter.grad for name, parameter in model.named_parameters() + if parameter.requires_grad and name.startswith(prefixes) + ] + gradients[group] = bool( + selected + and all(value is None or torch.isfinite(value).all() for value in selected) + and any(value is not None and value.abs().sum() > 0 for value in selected) + ) + teacher_frozen = all(not parameter.requires_grad for parameter in model.joint2d_head.parameters()) + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000.0)) + optimizer.step() + torch.cuda.synchronize(device) + elapsed = time.perf_counter() - started + model.eval() + with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16): + t1 = model(prefix(batch, 1)) + t1_finite = bool( + torch.isfinite(t1["joint2d_norm"]).all() + and torch.isfinite(t1["wrist_root_translation"]).all() + ) + checkpoint = args.output_dir / "spatial_joint2d_real_batch_smoke.pt" + save_checkpoint( + checkpoint, model, optimizer, 1, + extra={"kind": "phase6_spatial_joint2d_real_checkpoint_smoke"}, + exclude_prefixes=excluded, + ) + expected = { + key: value.detach().cpu().clone() for key, value in model.state_dict().items() + if not key.startswith(excluded) + } + del model, optimizer, criterion, prediction, losses, t1 + torch.cuda.empty_cache() + reloaded = BimanualReconstructionModel(model_config).to(device) + reloaded_optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + reloaded, learning_rate=learning_rate, backbone_learning_rate=None, + ), lr=learning_rate, weight_decay=0.05, + ) + resumed = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all( + torch.equal(reloaded.state_dict()[key].detach().cpu(), value) + for key, value in expected.items() + ) + shared_missing = [ + key for key in initialization["missing_keys"] + if not key.startswith(("joint_localization_", "rgb_encoder.backbone.")) + ] + passed = bool( + all(np.isfinite(value) for value in loss_values.values()) + and all(gradients.values()) and teacher_frozen and entropy_finite_bounded + and t1_finite and resume_exact and resumed["step"] == 1 and not shared_missing + ) + report = { + "status": "passed" if passed else "failed", + "experiment": "P6_S3B_spatial_2d_anchors", + "experiment_class": "engineering_real_checkpoint_smoke", + "official_test_used": False, + "config": {"path": str(args.config.resolve()), "sha256": sha256(args.config)}, + "source_checkpoint": { + "path": str(args.checkpoint.resolve()), "sha256": sha256(args.checkpoint), + "step": initialization["step"], + }, + "residual_missing_keys": initialization["residual_missing_keys"], + "shared_initialization_missing_keys": shared_missing, + "losses": loss_values, + "teacher_difference_px": teacher_difference_px, + "teacher_frozen": teacher_frozen, + "entropy_finite_bounded": entropy_finite_bounded, + "gradient_groups_finite_nonzero": gradients, + "gradient_norm": gradient_norm, + "T1_finite": t1_finite, + "T8_finite": all(np.isfinite(value) for value in loss_values.values()), + "elapsed_s": elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "resume_exact": resume_exact, + "resume_step": resumed["step"], + "initialized_checkpoint": { + "path": str(initialized_checkpoint.resolve()), + "sha256": sha256(initialized_checkpoint), "step": 0, + }, + "checkpoint": {"path": str(checkpoint.resolve()), "sha256": sha256(checkpoint)}, + } + (args.output_dir / "smoke.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "gradients": gradients, + "resume_exact": resume_exact, "output": str(args.output_dir), + }, indent=2)) + if not passed: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_real_batch.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_real_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..7581b85b5a1e7d58affbf1c719ca10b12c981c1f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/smoke_real_batch.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Real H2O batch structural smoke test; uses debug RGB encoder when weights are absent.""" + +from __future__ import annotations + +import argparse +import json +import time +from pathlib import Path + +import cv2 +import numpy as np +import torch +from torch.utils.data import DataLoader + +from foundation_hand.data import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint, save_checkpoint + + +def parameter_counts(model: torch.nn.Module) -> tuple[int, int]: + trainable = sum(value.numel() for value in model.parameters() if value.requires_grad) + frozen = sum(value.numel() for value in model.parameters() if not value.requires_grad) + return trainable, frozen + + +def draw_overlay(batch: dict[str, torch.Tensor], output: dict[str, torch.Tensor], path: Path) -> None: + rgb = batch["rgb"][0, 0].detach().cpu().permute(1, 2, 0).numpy() + rgb = np.clip((rgb * RGB_STD + RGB_MEAN) * 255, 0, 255).astype(np.uint8) + image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) + height, width = image.shape[:2] + predicted = output["joint2d_norm"][0, 0].detach().float().cpu().numpy() * np.array((width, height)) + target = batch["joint2d"][0, 0].detach().float().cpu().numpy() + annotation_valid = batch["joint_annotation_valid"][0, 0].cpu().numpy() + for hand, color in enumerate(((50, 220, 50), (50, 80, 255))): + for point in predicted[hand]: + cv2.circle(image, tuple(np.rint(point).astype(int)), 3, color, -1) + if annotation_valid[hand]: + for point in target[hand]: + cv2.drawMarker(image, tuple(np.rint(point).astype(int)), (255, 255, 255), cv2.MARKER_CROSS, 7, 1) + label = f"{batch['subject_id'][0]}/{batch['sequence_id'][0]}/{int(batch['frame_id'][0,0])} debug_encoder RGB-D-K" + cv2.rectangle(image, (0, 0), (width, 32), (0, 0, 0), -1) + cv2.putText(image, label, (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (255, 255, 255), 1) + cv2.imwrite(str(path), image) + + attention = output["attention"]["rgb_cross_attention"][0, -1, 0].detach().float().cpu().numpy() + grid_h, grid_w = height // 16, width // 16 + for hand, side in enumerate(("left", "right")): + heat = attention[hand].reshape(grid_h, grid_w) + heat = (heat - heat.min()) / max(float(heat.max() - heat.min()), 1e-8) + heat = cv2.resize(np.rint(heat * 255).astype(np.uint8), (width, height), interpolation=cv2.INTER_CUBIC) + heat = cv2.applyColorMap(heat, cv2.COLORMAP_TURBO) + mixed = cv2.addWeighted(image, 0.55, heat, 0.45, 0) + cv2.imwrite(str(path.with_name(path.stem + f"_{side}_rgb_attention.jpg")), mixed) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, default=0) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + torch.manual_seed(20260716); np.random.seed(20260716) + device = torch.device(f"cuda:{args.gpu}") + dataset = H2OCam4Dataset(args.root, args.manifest, (288, 512), (8,), (1,), max_clips=2) + loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_h2o_clips) + batch = next(iter(loader)) + batch = {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} + config = ModelConfig( + encoder="tiny_debug", decoder_dim=256, decoder_layers=3, attention_heads=8, + decoder_mode="alternating", use_temporal=True, use_depth=True, depth_mode="log_depth", + use_rays=True, use_bimanual_interaction=True, require_mano=False, + ) + model = BimanualReconstructionModel(config).to(device).train() + loss_function = BimanualLoss(LossConfig()).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) + torch.cuda.reset_peak_memory_stats(device) + start = time.perf_counter() + optimizer.zero_grad(set_to_none=True) + with torch.autocast("cuda", dtype=torch.bfloat16): + prediction = model(batch) + losses = loss_function(prediction, batch) + losses["total"].backward() + gradient_norm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1000)) + optimizer.step(); torch.cuda.synchronize(device) + elapsed = time.perf_counter() - start + checkpoint = args.output_dir / "real_batch_smoke.pt" + save_checkpoint(checkpoint, model, optimizer, 1, {"kind": "structural_smoke_debug_encoder"}) + reloaded = BimanualReconstructionModel(config).to(device) + reloaded_optimizer = torch.optim.AdamW(reloaded.parameters(), lr=1e-4) + resume = load_checkpoint(checkpoint, reloaded, reloaded_optimizer, device) + resume_exact = all(torch.equal(model.state_dict()[key], value) for key, value in reloaded.state_dict().items()) + trainable, frozen = parameter_counts(model) + result = { + "status": "passed_structural_smoke_only", "formal_training": False, + "limitation": "tiny_debug RGB encoder and no MANO assets; joint/vertex/reprojection losses are zero", + "seed": 20260716, "resolution_hw": [288, 512], "T": 8, "stride": 1, "batch_size": 1, "precision": "bf16", + "decoder": "alternating", "depth": "log_depth", "rays": True, + "trainable_parameters": trainable, "frozen_parameters": frozen, + "elapsed_s": elapsed, "frames_per_s": 8 / elapsed, + "peak_allocated_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "peak_reserved_gib": torch.cuda.max_memory_reserved(device) / 2**30, + "gradient_norm": gradient_norm, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "losses_finite": all(bool(torch.isfinite(value)) for value in losses.values()), + "resume_success": bool(resume_exact and resume["step"] == 1), "checkpoint": str(checkpoint.resolve()), + "input_shapes": {key: list(value.shape) for key, value in batch.items() if torch.is_tensor(value)}, + "output_shapes": {key: list(value.shape) for key, value in prediction.items() if torch.is_tensor(value)}, + "attention_shapes": {key: list(value.shape) for key, value in prediction["attention"].items()}, + } + (args.output_dir / "real_batch_smoke.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + draw_overlay(batch, prediction, args.output_dir / "real_batch_prediction_overlay.jpg") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/split_phase7_h2o_train_cache.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/split_phase7_h2o_train_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..add4ccef194d122b76ef5d116d75a15fe37c347a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/split_phase7_h2o_train_cache.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Create deterministic recording-group H2O train-fit/heldout cache manifests.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +from typing import Any + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def assign_group_folds(rows: list[dict[str, Any]], folds: int, seed: int) -> dict[str, int]: + if folds < 2: + raise ValueError("at least two folds are required") + subjects: dict[str, set[str]] = defaultdict(set) + group_subject: dict[str, str] = {} + for row in rows: + if str(row.get("dataset_id", "")).upper() != "H2O": + raise ValueError("H2O train cache split refuses non-H2O rows") + group = str(row["physical_recording_id"]) + subject = str(row["subject_id"]) + if group in group_subject and group_subject[group] != subject: + raise ValueError(f"physical recording spans subjects: {group}") + group_subject[group] = subject + subjects[subject].add(group) + assignments: dict[str, int] = {} + for subject, groups in sorted(subjects.items()): + ordered = sorted(groups, key=lambda group: hashlib.sha256( + f"{seed}|{subject}|{group}".encode("utf-8") + ).hexdigest()) + for index, group in enumerate(ordered): + assignments[group] = index % folds + return assignments + + +def split_rows( + rows: list[dict[str, Any]], assignments: dict[str, int], heldout_fold: int, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + fit, heldout = [], [] + for row in rows: + target = heldout if assignments[str(row["physical_recording_id"])] == heldout_fold else fit + target.append(row) + if not fit or not heldout: + raise ValueError("fit and heldout manifests must both be nonempty") + fit_groups = {row["physical_recording_id"] for row in fit} + heldout_groups = {row["physical_recording_id"] for row in heldout} + if fit_groups & heldout_groups: + raise AssertionError("physical recording leakage across H2O train split") + return fit, heldout + + +def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + path.write_text( + "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows), encoding="utf-8", + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-manifest", type=Path, required=True) + parser.add_argument("--cache-report", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--folds", type=int, default=5) + parser.add_argument("--heldout-fold", type=int, default=0) + parser.add_argument("--seed", type=int, default=20260717) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + if not 0 <= args.heldout_fold < args.folds: + parser.error("heldout fold is outside the fold range") + cache_report = json.loads(args.cache_report.read_text(encoding="utf-8")) + if ( + cache_report.get("status") != "complete" + or cache_report.get("dataset") != "H2O" + or cache_report.get("split_role") != "official_train" + or cache_report.get("h2o_official_validation_used") is not False + or cache_report.get("official_test_used") is not False + or cache_report["cache_manifest"]["sha256"] != sha256(args.cache_manifest) + ): + parser.error("cache report does not prove a complete official-train-only cache") + rows = [ + json.loads(line) for line in args.cache_manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + assignments = assign_group_folds(rows, args.folds, args.seed) + fit, heldout = split_rows(rows, assignments, args.heldout_fold) + args.output_dir.mkdir(parents=True) + fit_path = args.output_dir / "train_fit.jsonl" + heldout_path = args.output_dir / "train_group_heldout.jsonl" + write_jsonl(fit_path, fit) + write_jsonl(heldout_path, heldout) + record = { + "status": "frozen_h2o_train_group_split", "schema_version": "phase7_h2o_train_group_cv_v1", + "source_cache_manifest": { + "path": str(args.cache_manifest.resolve()), "sha256": sha256(args.cache_manifest), + }, + "folds": args.folds, "heldout_fold": args.heldout_fold, "seed": args.seed, + "group_key": "(dataset_id, subject_id, physical_recording_id)", + "fit": { + "path": str(fit_path.resolve()), "sha256": sha256(fit_path), "clips": len(fit), + "recordings": len({row["physical_recording_id"] for row in fit}), + }, + "heldout": { + "path": str(heldout_path.resolve()), "sha256": sha256(heldout_path), + "clips": len(heldout), + "recordings": len({row["physical_recording_id"] for row in heldout}), + }, + "assignments": assignments, "recording_overlap": [], + "h2o_official_validation_used": False, "official_test_used": False, + } + (args.output_dir / "split.json").write_text( + json.dumps(record, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(record, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_core.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_core.py new file mode 100644 index 0000000000000000000000000000000000000000..5e82cefcfac1b2f5833989ea3e5058a087bbd01f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_core.py @@ -0,0 +1,405 @@ +#!/usr/bin/env python3 +"""Summarize the pre-registered Phase 3 decoder/temporal core matrix.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import Iterable + +import numpy as np + + +CHECKPOINT_ROLES = ( + "step_025k", "step_050k", "step_075k", "step_100k", + "best_absolute", "best_z", "final", +) +FRAME_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "wrong_side_preference", +) +REPORT_METRICS = FRAME_METRICS + ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "identity_switch_fraction", +) +PAIR_DEFINITIONS = ( + ("l0_temporal", "L0", "T1", "L0", "T0"), + ("l1_temporal", "L1", "T1", "L1", "T0"), + ("alternating_without_temporal", "L1", "T0", "L0", "T0"), + ("alternating_with_temporal", "L1", "T1", "L0", "T1"), + ("hybrid_reread_vs_sequential", "L2", "T1", "L0", "T1"), + ("hybrid_reread_vs_alternating", "L2", "T1", "L1", "T1"), +) +OBSERVATION_KEY = ( + "clip_index", "time_index", "take", "subject", "sequence", + "frame_id", "side", "annotation_valid", "annotation_state", +) +TEMPORAL_OBSERVATION_KEY = ( + "clip_index", "transition_index", "take", "subject", "sequence", + "frame_id_from", "frame_id_to", "side", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: Iterable[dict[str, object]]) -> None: + rows = list(rows) + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fieldnames = list(rows[0]) + if any(list(row) != fieldnames for row in rows): + raise ValueError(f"inconsistent CSV fields for {path}") + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: str | None) -> float | None: + if value is None or value == "": + return None + result = float(value) + return result if math.isfinite(result) else None + + +def paired_take_differences( + candidate_rows: list[dict[str, str]], + reference_rows: list[dict[str, str]], + metric: str, + observation_key: tuple[str, ...] = OBSERVATION_KEY, +) -> dict[str, float]: + if len(candidate_rows) != len(reference_rows): + raise ValueError("paired evaluations have different observation counts") + take_values: dict[str, list[float]] = defaultdict(list) + frame_values = [] + for candidate, reference in zip(candidate_rows, reference_rows, strict=True): + if any(candidate[key] != reference[key] for key in observation_key): + raise ValueError("paired evaluations do not have identical observation order") + candidate_value = optional_float(candidate.get(metric)) + reference_value = optional_float(reference.get(metric)) + if candidate_value is None or reference_value is None: + continue + difference = candidate_value - reference_value + take_values[candidate["take"]].append(difference) + frame_values.append(difference) + if not take_values: + raise ValueError(f"no paired values for {metric}") + take_means = np.asarray([ + np.mean(values, dtype=np.float64) for _, values in sorted(take_values.items()) + ], dtype=np.float64) + return { + "take_equal_mean_delta": float(take_means.mean()), + "frame_weighted_mean_delta": float(np.mean(frame_values, dtype=np.float64)), + "take_count": int(take_means.size), + "observation_count": int(len(frame_values)), + "take_means": take_means, + } + + +def bootstrap_take_values( + take_values: np.ndarray, + seed: int = 20260716, + samples: int = 10_000, +) -> tuple[float, float]: + if take_values.ndim != 1 or take_values.size == 0: + raise ValueError("take_values must be a non-empty vector") + rng = np.random.default_rng(seed) + indices = rng.integers(0, take_values.size, size=(samples, take_values.size)) + means = take_values[indices].mean(axis=1) + return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5)) + + +def metric_mean(report: dict, name: str) -> float | None: + entry = report["metrics"].get(name) + if entry is not None: + return entry.get("mean") + if name in {"translation_x_mae_mm", "translation_y_mae_mm"}: + components = [ + report["metrics"][f"{side}_{name}"] for side in ("left", "right") + ] + count = sum(int(component["count"]) for component in components) + if count: + return sum( + float(component["mean"]) * int(component["count"]) + for component in components + ) / count + return None + + +def attention_mean(report: dict, name: str) -> float | None: + entry = report["attention"].get(name) + return None if entry is None else entry.get("mean") + + +def load_report(path: Path) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("official_test_used") is not False: + raise ValueError(f"invalid formal evaluation: {path}") + if report.get("split_role") != "official_validation" or report.get("clips") != 1495: + raise ValueError(f"incomplete or non-validation evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--temporal-evaluation-root", type=Path) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + report_paths = sorted(args.evaluation_root.glob("core_*/*/evaluation.json")) + if len(report_paths) != 210: + raise ValueError(f"expected 210 checkpoint evaluations, found {len(report_paths)}") + + all_rows = [] + best_rows = [] + reports_by_key: dict[tuple[str, str, str, int, str], tuple[Path, dict]] = {} + checkpoints: dict[str, dict[str, object]] = {} + collected_bootstrap = [] + for path in report_paths: + report = load_report(path) + config = report["config"] + experiment = config["experiment"] + run_name = path.parent.parent.name + role = path.parent.name + if role not in CHECKPOINT_ROLES: + raise ValueError(f"unregistered checkpoint role: {role}") + seed = int(config["seed"]) + training_summary = json.loads((args.run_root / run_name / "summary.json").read_text(encoding="utf-8")) + row: dict[str, object] = { + "run": run_name, + "modality": experiment["modality"], + "layout": experiment["layout"], + "temporal": experiment["temporal"], + "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "rgb_same_peak": attention_mean(report, "rgb_same_peak"), + "rgb_left_right_cosine": attention_mean(report, "rgb_left_right_cosine"), + "temporal_normalized_entropy": attention_mean(report, "temporal_normalized_entropy"), + "temporal_diagonal": attention_mean(report, "temporal_diagonal"), + "depth_fusion_gate": attention_mean(report, "depth_fusion_gate"), + "depth_fusion_gate_raw": attention_mean(report, "depth_fusion_gate_raw"), + "rgb_update_norm": attention_mean(report, "rgb_update_norm"), + "depth_update_norm": attention_mean(report, "depth_update_norm"), + "gated_depth_update_norm": attention_mean(report, "gated_depth_update_norm"), + "trainable_parameters": training_summary["trainable_parameters"], + "frozen_parameters": training_summary["frozen_parameters"], + "peak_vram_gib": training_summary["peak_vram_gib"], + "training_frames_per_s": training_summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + reports_by_key[(experiment["modality"], experiment["layout"], experiment["temporal"], seed, role)] = (path, report) + for bootstrap in report["bootstrap"]: + collected_bootstrap.append({ + "run": run_name, "modality": experiment["modality"], + "layout": experiment["layout"], "temporal": experiment["temporal"], + "seed": seed, "checkpoint_role": role, **bootstrap, + }) + checkpoint_record = checkpoints.setdefault(run_name, { + "config": config["name"], "modality": experiment["modality"], + "layout": experiment["layout"], "temporal": experiment["temporal"], + "seed": seed, "roles": {}, + }) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + write_csv(args.output_dir / "checkpoint_comparison.csv", all_rows) + write_csv(args.output_dir / "comparison.csv", best_rows) + write_csv(args.output_dir / "bootstrap_ci.csv", collected_bootstrap) + (args.output_dir / "checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for group_key in sorted({ + (row["modality"], row["layout"], row["temporal"]) for row in best_rows + }): + group = [row for row in best_rows if (row["modality"], row["layout"], row["temporal"]) == group_key] + if len(group) != 3: + raise ValueError(f"expected three seeds for {group_key}, got {len(group)}") + record: dict[str, object] = { + "modality": group_key[0], "layout": group_key[1], "temporal": group_key[2], + "seeds": [row["seed"] for row in group], + } + for metric in REPORT_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), + "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = {"mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1))} + aggregate.append(record) + + paired_rows = [] + for modality in ("M0", "M3"): + for comparison, candidate_layout, candidate_temporal, reference_layout, reference_temporal in PAIR_DEFINITIONS: + per_metric_by_seed: dict[str, list[dict[str, float]]] = defaultdict(list) + for seed in (20260716, 20260717, 20260718): + candidate_path, _ = reports_by_key[(modality, candidate_layout, candidate_temporal, seed, "best_absolute")] + reference_path, _ = reports_by_key[(modality, reference_layout, reference_temporal, seed, "best_absolute")] + candidate_rows = read_csv(candidate_path.parent / "per_hand_frame_metrics.csv") + reference_rows = read_csv(reference_path.parent / "per_hand_frame_metrics.csv") + for metric in FRAME_METRICS: + result = paired_take_differences(candidate_rows, reference_rows, metric) + per_metric_by_seed[metric].append({"seed": seed, **result}) + for metric in FRAME_METRICS: + results = per_metric_by_seed[metric] + stacked = np.stack([result["take_means"] for result in results], axis=0) + take_values = stacked.mean(axis=0) + ci_low, ci_high = bootstrap_take_values(take_values, args.seed, args.bootstrap_samples) + seed_deltas = [float(result["take_equal_mean_delta"]) for result in results] + paired_rows.append({ + "modality": modality, + "comparison": comparison, + "candidate": f"{candidate_layout}-{candidate_temporal}", + "reference": f"{reference_layout}-{reference_temporal}", + "metric": metric, + "delta_definition": "candidate_minus_reference_lower_is_better", + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "take_count": int(results[0]["take_count"]), + "observations_per_seed": int(results[0]["observation_count"]), + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + write_csv(args.output_dir / "paired_bootstrap_ci.csv", paired_rows) + + paired_temporal_rows = [] + if args.temporal_evaluation_root is not None: + temporal_metrics = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", + ) + for modality in ("M0", "M3"): + for comparison, candidate_layout, candidate_temporal, reference_layout, reference_temporal in PAIR_DEFINITIONS: + per_metric_by_seed: dict[str, list[dict[str, float]]] = defaultdict(list) + for seed in (20260716, 20260717, 20260718): + candidate_source, _ = reports_by_key[(modality, candidate_layout, candidate_temporal, seed, "best_absolute")] + reference_source, _ = reports_by_key[(modality, reference_layout, reference_temporal, seed, "best_absolute")] + candidate_path = ( + args.temporal_evaluation_root / candidate_source.parent.parent.name + / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + reference_path = ( + args.temporal_evaluation_root / reference_source.parent.parent.name + / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + candidate_rows = read_csv(candidate_path) + reference_rows = read_csv(reference_path) + for metric in temporal_metrics: + result = paired_take_differences( + candidate_rows, reference_rows, metric, + observation_key=TEMPORAL_OBSERVATION_KEY, + ) + per_metric_by_seed[metric].append({"seed": seed, **result}) + for metric in temporal_metrics: + results = per_metric_by_seed[metric] + stacked = np.stack([result["take_means"] for result in results], axis=0) + take_values = stacked.mean(axis=0) + ci_low, ci_high = bootstrap_take_values(take_values, args.seed, args.bootstrap_samples) + seed_deltas = [float(result["take_equal_mean_delta"]) for result in results] + paired_temporal_rows.append({ + "modality": modality, + "comparison": comparison, + "candidate": f"{candidate_layout}-{candidate_temporal}", + "reference": f"{reference_layout}-{reference_temporal}", + "metric": metric, + "delta_definition": "candidate_minus_reference_lower_is_better", + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "take_count": int(results[0]["take_count"]), + "observations_per_seed": int(results[0]["observation_count"]), + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + write_csv(args.output_dir / "paired_temporal_bootstrap_ci.csv", paired_temporal_rows) + + payload = { + "status": "complete", + "official_test_used": False, + "checkpoint_selection": "best_absolute selected only by the registered fixed 256-clip validation subset", + "evaluations": len(report_paths), + "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_bootstrap": { + "path": str((args.output_dir / "paired_bootstrap_ci.csv").resolve()), + "definition": "For each seed and take, compute paired per-observation candidate-reference deltas; average seeds within take; bootstrap the 24 take means.", + "temporal_path": ( + str((args.output_dir / "paired_temporal_bootstrap_ci.csv").resolve()) + if paired_temporal_rows else None + ), + "temporal_metric_limitation": ( + None if paired_temporal_rows + else "Provide --temporal-evaluation-root with transition exports to compute paired temporal take CIs." + ), + }, + "source_hashes": { + "full_validation_launcher_provenance": sha256(args.evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(report_paths), + "best_absolute_runs": len(best_rows), "paired_rows": len(paired_rows), + "paired_temporal_rows": len(paired_temporal_rows), + "output_dir": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_depth_fusion.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_depth_fusion.py new file mode 100644 index 0000000000000000000000000000000000000000..ab2a737a31f0909731dfc210277fff9c0a27cda9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_depth_fusion.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +"""Summarize the registered Phase 3 Depth fusion/representation controls.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + write_csv, + ) + + +VARIANTS = ("P0_fixed05", "gate025", "learned_gate", "geometry") +NEW_VARIANTS = ("gate025", "learned_gate", "geometry") + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def run_name(variant: str, seed: int) -> str: + if variant == "P0_fixed05": + return f"core_m3_l1_t1_s{seed}" + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_variant = None if variant == "P0_fixed05" else variant + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or (expected_variant is not None and experiment.get("variant") != expected_variant) + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal depth-fusion evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--new-run-root", type=Path, default=Path("artifacts/phase3/depth_fusion_runs")) + parser.add_argument("--core-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--new-evaluation-root", type=Path, default=Path("artifacts/phase3/depth_fusion_full_validation")) + parser.add_argument("--core-temporal-root", type=Path, default=Path("artifacts/phase3/temporal_position_p0_diagnostics")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + rows = [] + best_rows = [] + checkpoints: dict[str, dict] = {} + bootstrap_rows = [] + for variant in VARIANTS: + evaluation_root = args.core_evaluation_root if variant == "P0_fixed05" else args.new_evaluation_root + run_root = args.core_run_root if variant == "P0_fixed05" else args.new_run_root + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal run: {name}") + checkpoint_record = {"variant": variant, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + report_path = evaluation_root / name / role / "evaluation.json" + report = load_report(report_path, variant, seed) + reports[(variant, seed, role)] = (report_path, report) + row = { + "run": name, "variant": variant, "modality": "M3", + "layout": "L1", "temporal": "T1", "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in ( + "temporal_normalized_entropy", "temporal_diagonal", + "temporal_update_norm", "depth_fusion_gate", + "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ): + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, **item, + } for item in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(report_path.resolve()), + } + + expected_rows = len(VARIANTS) * len(SEEDS) * len(CHECKPOINT_ROLES) + if len(rows) != expected_rows or len(best_rows) != len(VARIANTS) * len(SEEDS): + raise ValueError(f"expected {expected_rows} rows, got {len(rows)}") + write_csv(args.output_dir / "depth_fusion_checkpoint_comparison.csv", rows) + write_csv(args.output_dir / "depth_fusion_comparison.csv", best_rows) + write_csv(args.output_dir / "depth_fusion_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "depth_fusion_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant, "modality": "M3", "layout": "L1", "temporal": "T1"} + for metric in FRAME_METRICS + TEMPORAL_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), + "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", "peak_vram_gib", + "training_frames_per_s", + ): + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + report_path, _ = reports[(variant, seed, "best_absolute")] + frame_cache[(variant, seed)] = read_csv(report_path.parent / "per_hand_frame_metrics.csv") + temporal_root = args.core_temporal_root if variant == "P0_fixed05" else args.new_evaluation_root + temporal_cache[(variant, seed)] = read_csv( + temporal_root / run_name(variant, seed) / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for variant in NEW_VARIANTS: + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {"candidate": frame_cache[(variant, seed)], "P0": frame_cache[("P0_fixed05", seed)]}, + metric, {"candidate": 1.0, "P0": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": f"{variant}-P0_fixed05", + "contrast": "+1*candidate -1*P0", + "metric": metric, + "delta_definition": "candidate minus fixed-gate-0.5 P0; lower is better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_fusion_bootstrap_ci.csv", paired_rows) + + temporal_rows = [] + for variant in NEW_VARIANTS: + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {"candidate": temporal_cache[(variant, seed)], "P0": temporal_cache[("P0_fixed05", seed)]}, + metric, {"candidate": 1.0, "P0": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": f"{variant}-P0_fixed05", + "contrast": "+1*candidate -1*P0", + "metric": metric, + "delta_definition": "candidate minus fixed-gate-0.5 P0; lower is better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_fusion_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", + "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "formal_validation_clips_per_run": 1495, + "evaluations": len(rows), + "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_depth_fusion_bootstrap_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_depth_fusion_temporal_ci.csv").resolve()), + "source_hashes": { + "new_validation_launcher": sha256(args.new_evaluation_root / "launcher_provenance.json"), + "core_validation_launcher": sha256(args.core_evaluation_root / "launcher_provenance.json"), + "matrix": sha256(Path("artifacts/phase3/reports/depth_fusion_new_runs.csv")), + }, + } + (args.output_dir / "depth_fusion_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "best_absolute_runs": len(best_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_dropout.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_dropout.py new file mode 100644 index 0000000000000000000000000000000000000000..f35a51389b1ce94b0b81b50bdffe572d73543924 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_dropout.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Summarize the same-commit Phase 3 geometry modality-dropout matrix.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) + + +VARIANTS = ("dropout00_geometry", "dropout02_geometry") + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown dropout variant: {variant}") + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "depth_modality_dropout" + or experiment.get("variant") != variant + or experiment.get("modality") != "M3" + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid complete-modality dropout evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row[metric] is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--run-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_runs_commit7583772"), + ) + parser.add_argument( + "--evaluation-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports = {} + checkpoint_rows = [] + best_rows = [] + checkpoints = {} + bootstrap_rows = [] + diagnostics = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((args.run_root / name / "summary.json").read_text(encoding="utf-8")) + provenance = json.loads( + (args.run_root / name / "run_provenance.json").read_text(encoding="utf-8") + ) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != "75837726f7eb8232b747932cbf536a834821e24d" + ): + raise ValueError(f"invalid formal dropout training run: {name}") + checkpoint_record = {"variant": variant, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = args.evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("dropout matrix is incomplete") + write_csv(args.output_dir / "depth_dropout_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "depth_dropout_comparison.csv", best_rows) + write_csv(args.output_dir / "depth_dropout_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "depth_dropout_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + diagnostics + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "dropout02": frame_cache[("dropout02_geometry", seed)], + "dropout00": frame_cache[("dropout00_geometry", seed)], + }, + metric, {"dropout02": 1.0, "dropout00": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": "dropout02_geometry-dropout00_geometry", + "metric": metric, "delta_definition": "dropout02 minus dropout00; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_bootstrap_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "dropout02": temporal_cache[("dropout02_geometry", seed)], + "dropout00": temporal_cache[("dropout00_geometry", seed)], + }, + metric, {"dropout02": 1.0, "dropout00": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": "dropout02_geometry-dropout00_geometry", + "metric": metric, "delta_definition": "dropout02 minus dropout00; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": "75837726f7eb8232b747932cbf536a834821e24d", + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str( + (args.output_dir / "paired_depth_dropout_bootstrap_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_depth_dropout_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "depth_dropout_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_dropout_dose.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_dropout_dose.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cbe8b0c7d099c4541ed67e9338ec4ffe15eac6 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_dropout_dose.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +"""Summarize D.2 endpoints together with the D.3 dropout-dose sweep.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, write_csv, + ) + + +TRAINING_COMMIT = "75837726f7eb8232b747932cbf536a834821e24d" +VARIANTS = ( + "dropout00_geometry", "dropout005_geometry", + "dropout010_geometry", "dropout02_geometry", +) +ENDPOINT_VARIANTS = {"dropout00_geometry", "dropout02_geometry"} +COMPARISONS = ( + ("dropout005_geometry", "dropout00_geometry"), + ("dropout010_geometry", "dropout00_geometry"), + ("dropout02_geometry", "dropout00_geometry"), + ("dropout010_geometry", "dropout005_geometry"), + ("dropout02_geometry", "dropout010_geometry"), + ("dropout02_geometry", "dropout005_geometry"), +) + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown dropout-dose variant: {variant}") + return f"depth_{variant}_m3_l1_t1_s{seed}" + + +def matrix_for(variant: str) -> str: + return ( + "depth_modality_dropout" + if variant in ENDPOINT_VARIANTS else "depth_modality_dropout_dose" + ) + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row[metric] is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != matrix_for(variant) + or experiment.get("variant") != variant + or experiment.get("modality") != "M3" + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid complete dropout-dose evaluation: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--endpoint-run-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_runs_commit7583772"), + ) + parser.add_argument( + "--dose-run-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_runs_commit7583772"), + ) + parser.add_argument( + "--endpoint-evaluation-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--dose-evaluation-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + diagnostics = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + reports = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + for variant in VARIANTS: + run_root = ( + args.endpoint_run_root if variant in ENDPOINT_VARIANTS else args.dose_run_root + ) + evaluation_root = ( + args.endpoint_evaluation_root + if variant in ENDPOINT_VARIANTS else args.dose_evaluation_root + ) + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text()) + provenance = json.loads((run_root / name / "run_provenance.json").read_text()) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid dropout-dose training run: {name}") + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 84 or len(best_rows) != 12: + raise ValueError("dropout-dose matrix is incomplete") + write_csv(args.output_dir / "dropout_dose_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "dropout_dose_comparison.csv", best_rows) + write_csv(args.output_dir / "dropout_dose_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "dropout_dose_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n" + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + diagnostics + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + temporal_rows = [] + for candidate, reference in COMPARISONS: + comparison = f"{candidate}-{reference}" + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(candidate, seed)], + "reference": frame_cache[(reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(candidate, seed)], + "reference": temporal_cache[(reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_dropout_dose_ci.csv", paired_rows) + write_csv(args.output_dir / "paired_dropout_dose_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_dropout_dose_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_dropout_dose_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "dropout_dose_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_dropout_dose_fallback.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_dropout_dose_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..2daef68597394f8412587333dcbf489ce2f188f0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_dropout_dose_fallback.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""Summarize complete and missing-modality behavior across four dropout doses.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_dropout_dose import ( + COMPARISONS as DOSE_COMPARISONS, ENDPOINT_VARIANTS, VARIANTS, + matrix_for, run_name, + ) + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) +else: + from summarize_phase3_dropout_dose import ( + COMPARISONS as DOSE_COMPARISONS, ENDPOINT_VARIANTS, VARIANTS, + matrix_for, run_name, + ) + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_depth, expected_k = CONDITIONS[condition] + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != matrix_for(variant) + or experiment.get("variant") != variant + or int(report["config"]["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid dropout-dose fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--endpoint-complete-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--dose-complete-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument( + "--endpoint-fallback-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_fallback"), + ) + parser.add_argument( + "--dose-fallback-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_fallback"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + diagnostics = ( + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + for variant in VARIANTS: + if variant in ENDPOINT_VARIANTS: + root = ( + args.endpoint_complete_root if condition == "complete" + else args.endpoint_fallback_root / condition + ) + else: + root = ( + args.dose_complete_root if condition == "complete" + else args.dose_fallback_root / condition + ) + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 48: + raise ValueError(f"expected 48 dropout-dose fallback rows, got {len(rows)}") + write_csv(args.output_dir / "dropout_dose_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + diagnostics: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": ( + float(np.std(values, ddof=1)) if len(values) > 1 else None + ), + } + aggregate.append(record) + + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + for candidate, reference in DOSE_COMPARISONS: + contrasts.append(( + f"{condition}:{candidate}-{reference}", + (condition, candidate), (condition, reference), + )) + + paired_rows = [] + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_dropout_dose_fallback_ci.csv", paired_rows) + write_csv( + args.output_dir / "paired_dropout_dose_fallback_temporal_ci.csv", temporal_rows + ) + + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + equality.append({ + "variant": variant, + "seed": seed, + "frame_metrics_identical": ( + frame_cache[("drop_k", variant, seed)] + == frame_cache[("drop_both", variant, seed)] + ), + }) + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "paired_frame": str( + (args.output_dir / "paired_dropout_dose_fallback_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_dropout_dose_fallback_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "dropout_dose_fallback_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + all_equal = all(row["frame_metrics_identical"] for row in equality) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all_equal, + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + }, indent=2)) + if not all_equal: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_fallback.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..5e26939c7294190d782e80c1a8713655ecf32cb7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_fallback.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""Summarize missing Depth/K inference behavior for the geometry dropout matrix.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from scripts.summarize_phase3_dropout import VARIANTS, run_name +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from summarize_phase3_dropout import VARIANTS, run_name + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + expected_depth, expected_k = CONDITIONS[condition] + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("variant") != variant + or int(report["config"]["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--complete-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_full_validation"), + ) + parser.add_argument( + "--fallback-root", type=Path, + default=Path("artifacts/phase3/depth_dropout_fallback"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + diagnostics = ( + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", + ) + reports = {} + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + root = args.complete_root if condition == "complete" else args.fallback_root / condition + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + reports[(condition, variant, seed)] = path + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in diagnostics: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 24: + raise ValueError(f"expected 24 fallback rows, got {len(rows)}") + write_csv(args.output_dir / "depth_dropout_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + diagnostics: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + } + aggregate.append(record) + + paired_rows = [] + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + contrasts.append(( + f"{condition}:dropout02-dropout00", + (condition, "dropout02_geometry"), + (condition, "dropout00_geometry"), + )) + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_fallback_ci.csv", paired_rows) + + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_depth_dropout_fallback_temporal_ci.csv", temporal_rows) + + # Geometry needs K for XYZ construction, so drop-K and drop-both should be identical. + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + k_rows = frame_cache[("drop_k", variant, seed)] + both_rows = frame_cache[("drop_both", variant, seed)] + equality.append({ + "variant": variant, "seed": seed, + "frame_metrics_identical": k_rows == both_rows, + }) + payload = { + "status": "complete", "official_test_used": False, + "geometry_k_dependency": ( + "When K is unavailable, XYZ/logZ geometry tokens and ray conditioning are both " + "disabled. Therefore drop_k and drop_both are expected to be identical." + ), + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "paired_frame": str( + (args.output_dir / "paired_depth_dropout_fallback_ci.csv").resolve() + ), + "paired_temporal": str( + (args.output_dir / "paired_depth_dropout_fallback_temporal_ci.csv").resolve() + ), + } + (args.output_dir / "depth_dropout_fallback_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all( + row["frame_metrics_identical"] for row in equality + ), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_long_tail.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_long_tail.py new file mode 100644 index 0000000000000000000000000000000000000000..d113631c873a7e249781efb84b821f65e074cebd --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_long_tail.py @@ -0,0 +1,337 @@ +#!/usr/bin/env python3 +"""Summarize the preregistered Phase 3 100k-to-150k low-LR tail.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, sha256, write_csv, + ) + from scripts.summarize_phase3_photometric import DIAGNOSTICS +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, TEMPORAL_KEY, + TEMPORAL_METRICS, aggregate_seed_contrasts, attention_mean, + contrast_take_differences, metric_mean, read_csv, sha256, write_csv, + ) + from summarize_phase3_photometric import DIAGNOSTICS + + +TRAINING_COMMIT = "d4019222835132fcbcc850ba49e6e0b53ab352b3" +REFERENCE_ROLE = "reference_best_absolute" +TAIL_ROLES = ( + "tail_step_125k", "tail_step_150k", "tail_best_absolute", + "tail_best_z", "tail_final", +) +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", "translation_z_mae_mm", +) + + +def reference_name(seed: int) -> str: + return f"photometric_on_geometry_m3_l1_t1_r640x368_s{seed}" + + +def tail_name(seed: int) -> str: + return f"longtail_{reference_name(seed)}" + + +def load_report(path: Path, seed: int, tail: bool) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + override = report.get("inference_modality_override", {}) + expected_matrix = "low_lr_tail" if tail else "photometric_augmentation" + expected_variant = ( + "photometric_on_r640x368_tail150k" if tail + else "photometric_on_r640x368" + ) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != expected_matrix + or experiment.get("variant") != expected_variant + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or int(config["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid long-tail evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def load_resume_audit(path: Path) -> dict: + audit = json.loads(path.read_text(encoding="utf-8")) + expected = {tail_name(seed) for seed in SEEDS} + rows = audit.get("runs", []) + if ( + audit.get("status") != "passed" + or audit.get("official_test_used") is not False + or {row.get("run") for row in rows} != expected + or any( + row.get("reference_step") != 150_000 + or row.get("resumed_step") != 150_000 + or not all(row.get(key) is True for key in ( + "model_exact", "optimizer_exact", "python_rng_exact", + "numpy_rng_exact", "torch_rng_exact", "cuda_rng_exact", + )) + for row in rows + ) + ): + raise ValueError(f"invalid long-tail exact-resume audit: {path}") + return {"status": "passed", "runs": len(rows), "path": str(path.resolve()), "sha256": sha256(path)} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--reference-evaluation-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--tail-run-root", type=Path, + default=Path("artifacts/phase3/long_tail_runs_commitd401922"), + ) + parser.add_argument( + "--tail-evaluation-root", type=Path, + default=Path("artifacts/phase3/long_tail_full_validation"), + ) + parser.add_argument( + "--resume-root", type=Path, + default=Path("artifacts/phase3/long_tail_resume_from125k"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports = {} + checkpoint_rows = [] + checkpoints = {} + training_audit = {} + for seed in SEEDS: + name = tail_name(seed) + run_dir = args.tail_run_root / name + summary = json.loads((run_dir / "summary.json").read_text(encoding="utf-8")) + provenance_path = Path(summary["run_provenance"]) + provenance = json.loads(provenance_path.read_text(encoding="utf-8")) + expected_resume = ( + Path("/SSD3/jiasen/foundation_hand/phase3_artifacts/photometric_runs_commit239b0bf") + / reference_name(seed) / "step_0100000_final.pt" + ) + schedule = summary.get("learning_rate_schedule", {}) + if ( + summary.get("status") != "completed" + or summary.get("start_step") != 100_000 + or summary.get("completed_step") != 150_000 + or schedule.get("total_steps") != 100_000 + or schedule.get("training_max_steps") != 150_000 + or schedule.get("min_lr") != 5e-6 + or provenance.get("git_commit") != TRAINING_COMMIT + or provenance.get("git_status") != "" + or Path(provenance.get("resume_checkpoint", "")).resolve() != expected_resume.resolve() + ): + raise ValueError(f"invalid long-tail training run: {name}") + training_audit[name] = { + "seed": seed, "start_step": 100_000, "completed_step": 150_000, + "lr_schedule_steps": 100_000, "min_lr": 5e-6, + "provenance": str(provenance_path), "provenance_sha256": sha256(provenance_path), + } + checkpoints[name] = {"seed": seed, "roles": {}} + paths = { + REFERENCE_ROLE: ( + args.reference_evaluation_root / reference_name(seed) + / "best_absolute" / "evaluation.json" + ), + **{ + role: args.tail_evaluation_root / name / role / "evaluation.json" + for role in TAIL_ROLES + }, + } + for role, path in paths.items(): + tail = role != REFERENCE_ROLE + report = load_report(path, seed, tail) + reports[(role, seed)] = path + row = { + "run": name, "seed": seed, "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "tail_training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + if len(checkpoint_rows) != 18: + raise ValueError(f"expected 18 reference/tail rows, got {len(checkpoint_rows)}") + write_csv(args.output_dir / "long_tail_checkpoint_comparison.csv", checkpoint_rows) + (args.output_dir / "long_tail_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + primary_roles = (REFERENCE_ROLE, "tail_best_absolute") + aggregate = [] + for role in primary_roles: + group = [row for row in checkpoint_rows if row["checkpoint_role"] == role] + record = {"role": role} + for metric in FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS: + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + joint_cache = {} + for role in primary_roles: + for seed in SEEDS: + parent = reports[(role, seed)].parent + frame_cache[(role, seed)] = read_csv(parent / "per_hand_frame_metrics.csv") + temporal_cache[(role, seed)] = read_csv(parent / "per_temporal_transition_metrics.csv") + joint_cache[(role, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in read_csv(parent / "per_joint_metrics.csv") + } + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + return contrast_take_differences( + { + "reference": cache[(REFERENCE_ROLE, seed)], + "tail": cache[("tail_best_absolute", seed)], + }, + metric, {"reference": -1.0, "tail": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in FRAME_METRICS: + paired_rows.append({ + "comparison": "tail_best-reference_best", "metric": metric, + "delta_definition": "tail minus reference; lower is better", + **aggregate_seed_contrasts( + [paired(metric, seed) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ), + }) + write_csv(args.output_dir / "paired_long_tail_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + temporal_rows.append({ + "comparison": "tail_best-reference_best", "metric": metric, + "delta_definition": "tail minus reference; lower is better", + **aggregate_seed_contrasts( + [paired(metric, seed, temporal=True) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ), + }) + write_csv(args.output_dir / "paired_long_tail_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": "tail_best-reference_best", + "subgroup_axis": subgroup[0], "subgroup_value": subgroup[1], + "metric": metric, + "delta_definition": "tail minus reference; lower is better", + } + try: + result = aggregate_seed_contrasts( + [paired(metric, seed, subgroup=subgroup) for seed in SEEDS], + args.seed, args.bootstrap_samples, + ) + except ValueError as error: + if "no paired values" not in str(error): + raise + result = { + "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, + "seed_20260717_delta": None, + "seed_20260718_delta": None, + "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + } + available = False + else: + available = True + subgroup_rows.append({**prefix, "available": available, **result}) + write_csv(args.output_dir / "paired_long_tail_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + for side in ("left", "right"): + for joint_index in range(21): + reference = np.asarray([ + joint_cache[(REFERENCE_ROLE, seed)][(side, joint_index)] for seed in SEEDS + ]) + tail = np.asarray([ + joint_cache[("tail_best_absolute", seed)][(side, joint_index)] for seed in SEEDS + ]) + joint_rows.append({ + "side": side, "joint_index": joint_index, + "reference_seed_mean_mm": float(reference.mean()), + "tail_seed_mean_mm": float(tail.mean()), + "tail_minus_reference_seed_mean_mm": float((tail - reference).mean()), + "tail_minus_reference_seed_sample_std_mm": float((tail - reference).std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "long_tail_per_joint_comparison.csv", joint_rows) + + resume_audit = load_resume_audit(args.resume_root / "exact_resume_audit.json") + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(checkpoint_rows), "aggregate": aggregate, + "training_audit": training_audit, "exact_resume": resume_audit, + } + output = args.output_dir / "long_tail_comparison.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "output": str(output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_modality.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..086229a9170bafceb69ba11354aba9b9c2f33897 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_modality.py @@ -0,0 +1,445 @@ +#!/usr/bin/env python3 +"""Summarize the Phase 3 four-modality causal matrix.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import Iterable + +import numpy as np + + +SEEDS = (20260716, 20260717, 20260718) +MODALITIES = ("M0", "M1", "M2", "M3") +CHECKPOINT_ROLES = ( + "step_025k", "step_050k", "step_075k", "step_100k", + "best_absolute", "best_z", "final", +) +FRAME_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", "root_relative_mpvpe_mm", + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", + "wrong_side_preference", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", "identity_switch_fraction", +) +REPORT_METRICS = FRAME_METRICS + TEMPORAL_METRICS +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", + "translation_x_mae_mm", "translation_y_mae_mm", "translation_z_mae_mm", +) +FRAME_KEY = ( + "clip_index", "time_index", "take", "subject", "sequence", + "frame_id", "side", "annotation_valid", "annotation_state", +) +TEMPORAL_KEY = ( + "clip_index", "transition_index", "take", "subject", "sequence", + "frame_id_from", "frame_id_to", "side", +) +CONTRASTS = ( + ("K_without_depth", {"M1": 1.0, "M0": -1.0}), + ("K_with_depth", {"M3": 1.0, "M2": -1.0}), + ("Depth_without_K", {"M2": 1.0, "M0": -1.0}), + ("Depth_with_K", {"M3": 1.0, "M1": -1.0}), + ("Depth_K_interaction", {"M3": 1.0, "M2": -1.0, "M1": -1.0, "M0": 1.0}), +) +SUBGROUPS = ( + ("side", "left"), ("side", "right"), + ("hand_size_bucket", "small"), ("hand_size_bucket", "medium"), + ("hand_size_bucket", "large"), + ("depth_bucket", "near"), ("depth_bucket", "middle"), + ("depth_bucket", "far"), +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: Iterable[dict[str, object]]) -> None: + rows = list(rows) + if not rows: + raise ValueError(f"refusing to write empty CSV: {path}") + fieldnames = list(rows[0]) + if any(list(row) != fieldnames for row in rows): + raise ValueError(f"inconsistent CSV fields for {path}") + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: str | None) -> float | None: + if value is None or value == "": + return None + result = float(value) + return result if math.isfinite(result) else None + + +def run_name(modality: str, seed: int) -> str: + prefix = "core" if modality in {"M0", "M3"} else "modality" + return f"{prefix}_{modality.lower()}_l1_t1_s{seed}" + + +def load_report(path: Path, modality: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != modality + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal modality evaluation: {path}") + return report + + +def metric_mean(report: dict, name: str) -> float | None: + entry = report["metrics"].get(name) + if entry is not None: + return entry.get("mean") + if name in {"translation_x_mae_mm", "translation_y_mae_mm"}: + components = [report["metrics"][f"{side}_{name}"] for side in ("left", "right")] + count = sum(int(component["count"]) for component in components) + if count: + return sum( + float(component["mean"]) * int(component["count"]) + for component in components + ) / count + return None + + +def attention_mean(report: dict, name: str) -> float | None: + entry = report["attention"].get(name) + return None if entry is None else entry.get("mean") + + +def bootstrap(values: np.ndarray, seed: int, samples: int) -> tuple[float, float]: + if values.ndim != 1 or values.size == 0: + raise ValueError("bootstrap values must be a non-empty vector") + rng = np.random.default_rng(seed) + indices = rng.integers(0, values.size, size=(samples, values.size)) + means = values[indices].mean(axis=1) + return float(np.percentile(means, 2.5)), float(np.percentile(means, 97.5)) + + +def contrast_take_differences( + rows_by_modality: dict[str, list[dict[str, str]]], + metric: str, + coefficients: dict[str, float], + observation_key: tuple[str, ...], + subgroup: tuple[str, str] | None = None, +) -> dict[str, object]: + modalities = tuple(coefficients) + reference_rows = rows_by_modality[modalities[0]] + if any(len(rows_by_modality[modality]) != len(reference_rows) for modality in modalities[1:]): + raise ValueError("contrast evaluations have different observation counts") + take_values: dict[str, list[float]] = defaultdict(list) + observation_values = [] + for index, reference in enumerate(reference_rows): + aligned = [rows_by_modality[modality][index] for modality in modalities] + if any( + any(row[key] != reference[key] for key in observation_key) + for row in aligned[1:] + ): + raise ValueError("contrast evaluations do not have identical observation order") + if subgroup is not None and reference.get(subgroup[0]) != subgroup[1]: + continue + values = [optional_float(row.get(metric)) for row in aligned] + if any(value is None for value in values): + continue + difference = sum( + coefficients[modality] * float(value) + for modality, value in zip(modalities, values, strict=True) + ) + take_values[reference["take"]].append(difference) + observation_values.append(difference) + if not take_values: + raise ValueError(f"no paired values for metric={metric}, subgroup={subgroup}") + return { + "take_means": { + take: float(np.mean(values, dtype=np.float64)) + for take, values in sorted(take_values.items()) + }, + "observation_mean": float(np.mean(observation_values, dtype=np.float64)), + "observation_count": len(observation_values), + } + + +def aggregate_seed_contrasts( + seed_results: list[dict[str, object]], seed: int, samples: int, +) -> dict[str, object]: + common_takes = set(seed_results[0]["take_means"]) + for result in seed_results[1:]: + common_takes &= set(result["take_means"]) + if not common_takes: + raise ValueError("seed contrasts have no common takes") + take_values = np.asarray([ + np.mean([result["take_means"][take] for result in seed_results]) + for take in sorted(common_takes) + ], dtype=np.float64) + ci_low, ci_high = bootstrap(take_values, seed, samples) + seed_deltas = [float(np.mean(list(result["take_means"].values()))) for result in seed_results] + return { + "take_equal_mean_delta": float(take_values.mean()), + "ci95_low": ci_low, + "ci95_high": ci_high, + "seed_delta_mean": float(np.mean(seed_deltas)), + "seed_delta_sample_std": float(np.std(seed_deltas, ddof=1)), + "seed_20260716_delta": seed_deltas[0], + "seed_20260717_delta": seed_deltas[1], + "seed_20260718_delta": seed_deltas[2], + "frame_weighted_delta_mean": float(np.mean([ + result["observation_mean"] for result in seed_results + ])), + "take_count": len(common_takes), + "observations_per_seed": int(seed_results[0]["observation_count"]), + "bootstrap_samples": samples, + "bootstrap_seed": seed, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--core-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--modality-run-root", type=Path, default=Path("artifacts/phase3/modality_runs")) + parser.add_argument("--core-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--modality-evaluation-root", type=Path, default=Path("artifacts/phase3/modality_full_validation")) + parser.add_argument("--core-temporal-root", type=Path, default=Path("artifacts/phase3/core_temporal_validation_v2")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + all_rows = [] + best_rows = [] + checkpoints: dict[str, dict[str, object]] = {} + collected_bootstrap = [] + for modality in MODALITIES: + evaluation_root = args.core_evaluation_root if modality in {"M0", "M3"} else args.modality_evaluation_root + run_root = args.core_run_root if modality in {"M0", "M3"} else args.modality_run_root + for seed in SEEDS: + name = run_name(modality, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal training run: {name}") + checkpoint_record = { + "modality": modality, "layout": "L1", "temporal": "T1", + "seed": seed, "roles": {}, + } + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, modality, seed) + reports[(modality, seed, role)] = (path, report) + row: dict[str, object] = { + "run": name, "modality": modality, "layout": "L1", "temporal": "T1", + "seed": seed, "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "temporal_normalized_entropy": attention_mean(report, "temporal_normalized_entropy"), + "temporal_diagonal": attention_mean(report, "temporal_diagonal"), + "depth_fusion_gate": attention_mean(report, "depth_fusion_gate"), + "depth_fusion_gate_raw": attention_mean(report, "depth_fusion_gate_raw"), + "rgb_update_norm": attention_mean(report, "rgb_update_norm"), + "depth_update_norm": attention_mean(report, "depth_update_norm"), + "gated_depth_update_norm": attention_mean(report, "gated_depth_update_norm"), + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + collected_bootstrap.extend({ + "run": name, "modality": modality, "seed": seed, + "checkpoint_role": role, **bootstrap_row, + } for bootstrap_row in report["bootstrap"]) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(all_rows) != 84 or len(best_rows) != 12: + raise ValueError(f"expected 84 checkpoint rows and 12 best rows, got {len(all_rows)}, {len(best_rows)}") + write_csv(args.output_dir / "modality_checkpoint_comparison.csv", all_rows) + write_csv(args.output_dir / "modality_comparison.csv", best_rows) + write_csv(args.output_dir / "modality_bootstrap_ci.csv", collected_bootstrap) + (args.output_dir / "modality_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for modality in MODALITIES: + group = [row for row in best_rows if row["modality"] == modality] + if len(group) != 3: + raise ValueError(f"expected three seeds for {modality}, got {len(group)}") + record: dict[str, object] = {"modality": modality, "layout": "L1", "temporal": "T1"} + for metric in REPORT_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + } + aggregate.append(record) + + frame_cache: dict[tuple[str, int], list[dict[str, str]]] = {} + temporal_cache: dict[tuple[str, int], list[dict[str, str]]] = {} + for modality in MODALITIES: + for seed in SEEDS: + report_path, _ = reports[(modality, seed, "best_absolute")] + frame_cache[(modality, seed)] = read_csv(report_path.parent / "per_hand_frame_metrics.csv") + temporal_root = args.core_temporal_root if modality in {"M0", "M3"} else args.modality_evaluation_root + temporal_cache[(modality, seed)] = read_csv( + temporal_root / run_name(modality, seed) / "best_absolute" / "per_temporal_transition_metrics.csv" + ) + + paired_rows = [] + for contrast, coefficients in CONTRASTS: + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {modality: frame_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "metric": metric, + "delta_definition": "contrast_delta_lower_is_better_except_interaction_is_additivity_residual", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_bootstrap_ci.csv", paired_rows) + + subgroup_rows = [] + unavailable_subgroups: set[tuple[str, str]] = set() + for contrast, coefficients in CONTRASTS[:4]: + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "subgroup_axis": subgroup[0], "subgroup": subgroup[1], "metric": metric, + "delta_definition": "contrast_delta_lower_is_better", + } + try: + seed_results = [ + contrast_take_differences( + {modality: frame_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, FRAME_KEY, subgroup, + ) + for seed in SEEDS + ] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable_subgroups.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, + "take_equal_mean_delta": None, "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, "seed_20260717_delta": None, + "seed_20260718_delta": None, "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_subgroup_ci.csv", subgroup_rows) + + temporal_rows = [] + for contrast, coefficients in CONTRASTS: + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {modality: temporal_cache[(modality, seed)] for modality in coefficients}, + metric, coefficients, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": contrast, + "contrast": " + ".join(f"{coefficient:+g}*{modality}" for modality, coefficient in coefficients.items()), + "metric": metric, + "delta_definition": "contrast_delta_lower_is_better_except_interaction_is_additivity_residual", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_modality_temporal_ci.csv", temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "formal_validation_clips_per_run": 1495, + "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "causal_contrasts": { + "paired_frame": str((args.output_dir / "paired_modality_bootstrap_ci.csv").resolve()), + "paired_subgroups": str((args.output_dir / "paired_modality_subgroup_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_modality_temporal_ci.csv").resolve()), + "definition": "Within each seed and observation, apply the registered modality contrast; average within take, average seeds within take, then bootstrap equal-weight take means.", + "unavailable_subgroups": [ + {"axis": axis, "value": value} + for axis, value in sorted(unavailable_subgroups) + ], + }, + "source_hashes": { + "core_validation_launcher": sha256(args.core_evaluation_root / "launcher_provenance.json"), + "modality_validation_launcher": sha256(args.modality_evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "modality_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(all_rows), + "best_absolute_runs": len(best_rows), "paired_rows": len(paired_rows), + "subgroup_rows": len(subgroup_rows), "temporal_rows": len(temporal_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_photometric.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_photometric.py new file mode 100644 index 0000000000000000000000000000000000000000..a6cef761d482c983cc6ad19adc664c7f0754d534 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_photometric.py @@ -0,0 +1,467 @@ +#!/usr/bin/env python3 +"""Summarize the paired Phase 3 photometric augmentation experiment.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) + + +TRAINING_COMMIT = "239b0bf8850dd5533d3b3f4236cf856b4e826af6" +VARIANTS = ("off", "on") +DIAGNOSTICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", +) +SUBGROUP_METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px", "fingertip_mpjpe_mm", "translation_z_mae_mm", +) +SCIENTIFIC_LOG_EXCLUSIONS = { + "timestamp", "frames_per_s", "peak_vram_gib", "photometric_augmentation", +} + + +def run_name(variant: str, seed: int) -> str: + if variant not in VARIANTS: + raise ValueError(f"unknown photometric variant: {variant}") + return f"photometric_{variant}_geometry_m3_l1_t1_r640x368_s{seed}" + + +def reference_run_name(seed: int) -> str: + return f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + augmentation = config.get("data", {}).get("photometric_augmentation", {}) + override = report.get("inference_modality_override", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "photometric_augmentation" + or experiment.get("variant") != f"photometric_{variant}_r640x368" + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or bool(augmentation.get("enabled")) != (variant == "on") + or int(config["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid formal photometric evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def canonical_scientific_record(record: dict) -> bytes: + filtered = { + key: value for key, value in record.items() + if key not in SCIENTIFIC_LOG_EXCLUSIONS + } + return json.dumps( + filtered, sort_keys=True, separators=(",", ":"), allow_nan=False, + ).encode("utf-8") + + +def audit_off_reference(off_path: Path, reference_path: Path) -> dict: + digest = hashlib.sha256() + compared = 0 + with off_path.open(encoding="utf-8") as off_handle, reference_path.open( + encoding="utf-8" + ) as reference_handle: + for compared, (off_line, reference_line) in enumerate( + zip(off_handle, reference_handle, strict=True), start=1, + ): + off_record = canonical_scientific_record(json.loads(off_line)) + reference_record = canonical_scientific_record(json.loads(reference_line)) + if off_record != reference_record: + raise ValueError( + f"off/reference scientific trajectory differs at record {compared}" + ) + digest.update(off_record) + digest.update(b"\n") + if compared != 100_000: + raise ValueError(f"expected 100000 compared records, got {compared}") + return { + "records": compared, "scientific_fields_exact": True, + "canonical_sha256": digest.hexdigest(), + } + + +def augmentation_statistics(path: Path, variant: str) -> dict: + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + if len(rows) != 100_000: + raise ValueError(f"expected 100000 augmentation records: {path}") + diagnostics = [row.get("photometric_augmentation") for row in rows] + if any(item is None for item in diagnostics): + raise ValueError(f"missing photometric diagnostics: {path}") + applied = np.asarray([float(item["applied_fraction"]) for item in diagnostics]) + if np.any((applied < 0.0) | (applied > 1.0)): + raise ValueError(f"invalid applied fraction: {path}") + expected_identity = variant == "off" + factor_limits = { + "brightness_mean": (0.8, 1.2), + "contrast_mean": (0.8, 1.2), + "saturation_mean": (0.8, 1.2), + "hue_mean": (-0.05, 0.05), + } + factor_stats = {} + for key, (low, high) in factor_limits.items(): + values = np.asarray([float(item[key]) for item in diagnostics]) + if expected_identity: + identity = 0.0 if key == "hue_mean" else 1.0 + if not np.all(values == identity): + raise ValueError(f"off run has non-identity {key}: {path}") + if np.any((values < low - 1e-7) | (values > high + 1e-7)): + raise ValueError(f"{key} outside registered range: {path}") + factor_stats[key] = { + "mean": float(values.mean()), "min": float(values.min()), + "max": float(values.max()), + } + if expected_identity and np.any(applied != 0.0): + raise ValueError(f"off run reports applied augmentation: {path}") + return { + "records": len(rows), "applied_fraction_mean": float(applied.mean()), + "factors": factor_stats, + } + + +def load_resume_audit(path: Path, variant: str) -> dict: + audit = json.loads(path.read_text(encoding="utf-8")) + expected_names = {run_name(variant, seed) for seed in SEEDS} + records = audit.get("runs", []) + if ( + audit.get("status") != "passed" + or audit.get("official_test_used") is not False + or {record.get("run") for record in records} != expected_names + or any( + record.get("reference_step") != 100_000 + or record.get("resumed_step") != 100_000 + or not all( + record.get(key) is True for key in ( + "model_exact", "optimizer_exact", "python_rng_exact", + "numpy_rng_exact", "torch_rng_exact", "cuda_rng_exact", + ) + ) + for record in records + ) + ): + raise ValueError(f"invalid {variant} exact-resume audit: {path}") + return { + "status": "passed", "variant": variant, "runs": len(records), + "path": str(path.resolve()), "sha256": sha256(path), + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--run-root", type=Path, + default=Path("artifacts/phase3/photometric_runs_commit239b0bf"), + ) + parser.add_argument( + "--evaluation-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--off-reference-root", type=Path, + default=Path("artifacts/phase3/resolution_640_runs_attempt2_commit7583772"), + ) + parser.add_argument( + "--off-resume-root", type=Path, + default=Path("artifacts/phase3/photometric_resume_from75k"), + ) + parser.add_argument( + "--on-resume-root", type=Path, + default=Path("artifacts/phase3/photometric_on_resume_from75k"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("artifacts/phase3/reports"), + ) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + resume_audits = { + variant: load_resume_audit( + ( + args.off_resume_root if variant == "off" + else args.on_resume_root + ) / "exact_resume_audit.json", + variant, + ) + for variant in VARIANTS + } + + reports: dict[tuple[str, int, str], Path] = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + training_audit = {} + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + run_dir = args.run_root / name + summary = json.loads((run_dir / "summary.json").read_text(encoding="utf-8")) + provenance = json.loads( + (run_dir / "run_provenance.json").read_text(encoding="utf-8") + ) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid photometric training run: {name}") + training_audit[name] = { + "variant": variant, "seed": seed, + "augmentation": augmentation_statistics( + run_dir / "train_metrics.jsonl", variant, + ), + } + if variant == "off": + training_audit[name]["e1_reference"] = audit_off_reference( + run_dir / "train_metrics.jsonl", + args.off_reference_root / reference_run_name(seed) / "train_metrics.jsonl", + ) + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = args.evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("photometric matrix is incomplete") + write_csv(args.output_dir / "photometric_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "photometric_comparison.csv", best_rows) + write_csv(args.output_dir / "photometric_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "photometric_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + (args.output_dir / "photometric_training_audit.json").write_text( + json.dumps({"status": "passed", "runs": training_audit}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + joint_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = read_csv( + parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + joint_cache[(variant, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in read_csv(parent / "per_joint_metrics.csv") + } + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + return contrast_take_differences( + {"off": cache[("off", seed)], "on": cache[("on", seed)]}, + metric, {"off": -1.0, "on": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in FRAME_METRICS: + results = [paired(metric, seed) for seed in SEEDS] + paired_rows.append({ + "comparison": "on-off", "metric": metric, + "delta_definition": "augmentation on minus off; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [paired(metric, seed, temporal=True) for seed in SEEDS] + temporal_rows.append({ + "comparison": "on-off", "metric": metric, + "delta_definition": "augmentation on minus off; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + unavailable = set() + for subgroup in SUBGROUPS: + for metric in SUBGROUP_METRICS: + prefix = { + "comparison": "on-off", "subgroup_axis": subgroup[0], + "subgroup_value": subgroup[1], "metric": metric, + "bucket_source": "aligned augmentation-off reference rows", + "delta_definition": "augmentation on minus off; lower is better", + } + try: + results = [paired(metric, seed, subgroup=subgroup) for seed in SEEDS] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, "seed_delta_mean": None, + "seed_delta_sample_std": None, "seed_20260716_delta": None, + "seed_20260717_delta": None, "seed_20260718_delta": None, + "frame_weighted_delta_mean": None, "take_count": 0, + "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + for side in ("left", "right"): + for joint_index in range(21): + off = np.asarray([ + joint_cache[("off", seed)][(side, joint_index)] for seed in SEEDS + ]) + on = np.asarray([ + joint_cache[("on", seed)][(side, joint_index)] for seed in SEEDS + ]) + delta = on - off + joint_rows.append({ + "side": side, "joint_index": joint_index, + "off_seed_mean_mm": float(off.mean()), + "off_seed_sample_std_mm": float(off.std(ddof=1)), + "on_seed_mean_mm": float(on.mean()), + "on_seed_sample_std_mm": float(on.std(ddof=1)), + "on_minus_off_seed_mean_mm": float(delta.mean()), + "on_minus_off_seed_sample_std_mm": float(delta.std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "photometric_per_joint_comparison.csv", joint_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_photometric_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_photometric_temporal_ci.csv").resolve() + ), + "paired_subgroups": str( + (args.output_dir / "paired_photometric_subgroup_ci.csv").resolve() + ), + "per_joint": str( + (args.output_dir / "photometric_per_joint_comparison.csv").resolve() + ), + "training_audit": str( + (args.output_dir / "photometric_training_audit.json").resolve() + ), + "exact_resume": { + "status": "passed", "runs": sum( + audit["runs"] for audit in resume_audits.values() + ), + "variants": resume_audits, + }, + "unavailable_subgroups": [ + {"axis": axis, "value": value} for axis, value in sorted(unavailable) + ], + "source_hashes": { + "training_launcher": sha256(args.run_root / "launcher_provenance.json"), + "validation_launcher": sha256( + args.evaluation_root / "launcher_provenance.json" + ), + }, + } + (args.output_dir / "photometric_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "per_joint_rows": len(joint_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_photometric_fallback.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_photometric_fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..e865911f92e2e957592fba42b7916a5421d6348b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_photometric_fallback.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Summarize missing-modality behavior for the final photometric candidate.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from scripts.summarize_phase3_photometric import DIAGNOSTICS, VARIANTS, run_name +else: + from summarize_phase3_modality import ( + FRAME_KEY, FRAME_METRICS, SEEDS, TEMPORAL_KEY, TEMPORAL_METRICS, + aggregate_seed_contrasts, attention_mean, contrast_take_differences, + metric_mean, read_csv, write_csv, + ) + from summarize_phase3_photometric import DIAGNOSTICS, VARIANTS, run_name + + +CONDITIONS = { + "complete": (False, False), + "drop_depth": (True, False), + "drop_k": (False, True), + "drop_both": (True, True), +} + + +def load_report(path: Path, variant: str, seed: int, condition: str) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + config = report.get("config", {}) + experiment = config.get("experiment", {}) + augmentation = config.get("data", {}).get("photometric_augmentation", {}) + override = report.get("inference_modality_override", {}) + expected_depth, expected_k = CONDITIONS[condition] + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != "photometric_augmentation" + or experiment.get("variant") != f"photometric_{variant}_r640x368" + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(config["data"]["resolution_hw"]) != (368, 640) + or bool(augmentation.get("enabled")) != (variant == "on") + or int(config["seed"]) != seed + or bool(override.get("drop_depth", False)) != expected_depth + or bool(override.get("drop_k", False)) != expected_k + ): + raise ValueError(f"invalid photometric fallback report: {path}") + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--complete-root", type=Path, + default=Path("artifacts/phase3/photometric_full_validation"), + ) + parser.add_argument( + "--fallback-root", type=Path, + default=Path("artifacts/phase3/photometric_fallback_validation"), + ) + parser.add_argument( + "--output-dir", type=Path, default=Path("artifacts/phase3/reports"), + ) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + rows = [] + frame_cache = {} + temporal_cache = {} + for condition in CONDITIONS: + root = args.complete_root if condition == "complete" else args.fallback_root / condition + for variant in VARIANTS: + for seed in SEEDS: + name = run_name(variant, seed) + path = root / name / "best_absolute" / "evaluation.json" + report = load_report(path, variant, seed, condition) + row = { + "condition": condition, "variant": variant, "seed": seed, + "checkpoint_sha256": report["checkpoint"]["sha256"], + "drop_depth": CONDITIONS[condition][0], + "drop_k": CONDITIONS[condition][1], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + rows.append(row) + frame_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_hand_frame_metrics.csv" + ) + temporal_cache[(condition, variant, seed)] = read_csv( + path.parent / "per_temporal_transition_metrics.csv" + ) + if len(rows) != 24: + raise ValueError(f"expected 24 complete/fallback rows, got {len(rows)}") + write_csv(args.output_dir / "photometric_fallback_comparison.csv", rows) + + aggregate = [] + for condition in CONDITIONS: + for variant in VARIANTS: + group = [ + row for row in rows + if row["condition"] == condition and row["variant"] == variant + ] + record = {"condition": condition, "variant": variant} + for metric in FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + } + aggregate.append(record) + + contrasts = [] + for variant in VARIANTS: + for condition in ("drop_depth", "drop_k", "drop_both"): + contrasts.append(( + f"{variant}:{condition}-complete", + (condition, variant), ("complete", variant), + )) + for condition in CONDITIONS: + contrasts.append(( + f"{condition}:on-off", (condition, "on"), (condition, "off"), + )) + + paired_rows = [] + temporal_rows = [] + for comparison, candidate, reference in contrasts: + for metric in FRAME_METRICS: + results = [ + contrast_take_differences( + { + "candidate": frame_cache[(*candidate, seed)], + "reference": frame_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + for metric in TEMPORAL_METRICS: + results = [ + contrast_take_differences( + { + "candidate": temporal_cache[(*candidate, seed)], + "reference": temporal_cache[(*reference, seed)], + }, + metric, {"candidate": 1.0, "reference": -1.0}, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + temporal_rows.append({ + "comparison": comparison, "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_photometric_fallback_ci.csv", paired_rows) + write_csv( + args.output_dir / "paired_photometric_fallback_temporal_ci.csv", temporal_rows, + ) + + equality = [] + for variant in VARIANTS: + for seed in SEEDS: + equality.append({ + "variant": variant, "seed": seed, + "frame_rows_identical": ( + frame_cache[("drop_k", variant, seed)] + == frame_cache[("drop_both", variant, seed)] + ), + "temporal_rows_identical": ( + temporal_cache[("drop_k", variant, seed)] + == temporal_cache[("drop_both", variant, seed)] + ), + }) + payload = { + "status": "complete", "official_test_used": False, + "evaluations": len(rows), "aggregate": aggregate, + "drop_k_drop_both_equality": equality, + "geometry_k_dependency": ( + "When K is unavailable, ray conditioning and XYZ/logZ geometry are disabled; " + "drop_k and drop_both are therefore expected to be identical." + ), + } + output = args.output_dir / "photometric_fallback_comparison.json" + output.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + print(json.dumps({ + "status": "complete", "evaluations": len(rows), + "drop_k_equals_drop_both": all( + row["frame_rows_identical"] and row["temporal_rows_identical"] + for row in equality + ), + "output": str(output), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_resolution.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..669c9bad9451479da904b1d35b1873d764686a56 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_resolution.py @@ -0,0 +1,377 @@ +#!/usr/bin/env python3 +"""Summarize the paired Phase 3 512x288 versus 640x368 resolution study.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, FRAME_KEY, FRAME_METRICS, SEEDS, SUBGROUPS, + TEMPORAL_KEY, TEMPORAL_METRICS, aggregate_seed_contrasts, + attention_mean, contrast_take_differences, metric_mean, read_csv, + sha256, write_csv, + ) + + +TRAINING_COMMIT = "75837726f7eb8232b747932cbf536a834821e24d" +VARIANTS = ("r512x288", "r640x368") +RESOLUTIONS = {"r512x288": (288, 512), "r640x368": (368, 640)} +NORMALIZED_2D_METRICS = ( + "direct_2d_error_px", "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", +) +PAIRED_FRAME_METRICS = FRAME_METRICS + tuple( + f"{metric}_at_512_width" for metric in NORMALIZED_2D_METRICS +) +DIAGNOSTICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", + "depth_fusion_gate", "depth_fusion_gate_raw", "rgb_update_norm", + "depth_update_norm", "gated_depth_update_norm", +) + + +def run_name(variant: str, seed: int) -> str: + if variant == "r512x288": + return f"depth_dropout005_geometry_m3_l1_t1_s{seed}" + if variant == "r640x368": + return f"depth_dropout005_geometry_m3_l1_t1_r640x368_s{seed}" + raise ValueError(f"unknown resolution variant: {variant}") + + +def load_report(path: Path, variant: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + override = report.get("inference_modality_override", {}) + expected_matrix = ( + "depth_modality_dropout_dose" if variant == "r512x288" else "resolution" + ) + expected_variant = ( + "dropout005_geometry" + if variant == "r512x288" else "dropout005_geometry_r640x368" + ) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("matrix") != expected_matrix + or experiment.get("variant") != expected_variant + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or tuple(report["config"]["data"]["resolution_hw"]) != RESOLUTIONS[variant] + or int(report["config"]["seed"]) != seed + or override.get("drop_depth", False) + or override.get("drop_k", False) + ): + raise ValueError(f"invalid formal resolution evaluation: {path}") + return report + + +def optional_aggregate(group: list[dict], metric: str) -> dict: + values = [float(row[metric]) for row in group if row.get(metric) is not None] + return { + "mean": float(np.mean(values)) if values else None, + "sample_std": float(np.std(values, ddof=1)) if len(values) > 1 else None, + "per_seed": {str(row["seed"]): row.get(metric) for row in group}, + } + + +def add_normalized_2d_columns( + rows: list[dict[str, str]], variant: str, +) -> list[dict[str, str]]: + scale = 512.0 / RESOLUTIONS[variant][1] + output = [] + for row in rows: + adapted = dict(row) + for metric in NORMALIZED_2D_METRICS: + value = adapted.get(metric) + adapted[f"{metric}_at_512_width"] = ( + "" if value in {None, ""} else str(float(value) * scale) + ) + output.append(adapted) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--reference-run-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_runs_commit7583772"), + ) + parser.add_argument( + "--candidate-run-root", type=Path, + default=Path("artifacts/phase3/resolution_640_runs_attempt2_commit7583772"), + ) + parser.add_argument( + "--reference-evaluation-root", type=Path, + default=Path("artifacts/phase3/dropout_dose_full_validation"), + ) + parser.add_argument( + "--candidate-evaluation-root", type=Path, + default=Path("artifacts/phase3/resolution_640_full_validation"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], Path] = {} + checkpoint_rows = [] + best_rows = [] + bootstrap_rows = [] + checkpoints = {} + for variant in VARIANTS: + run_root = ( + args.reference_run_root if variant == "r512x288" + else args.candidate_run_root + ) + evaluation_root = ( + args.reference_evaluation_root if variant == "r512x288" + else args.candidate_evaluation_root + ) + for seed in SEEDS: + name = run_name(variant, seed) + summary = json.loads((run_root / name / "summary.json").read_text()) + provenance = json.loads((run_root / name / "run_provenance.json").read_text()) + if ( + summary.get("status") != "completed" + or summary.get("completed_step") != 100_000 + or provenance.get("git_commit") != TRAINING_COMMIT + ): + raise ValueError(f"invalid resolution training run: {name}") + checkpoints[name] = {"variant": variant, "seed": seed, "roles": {}} + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, variant, seed) + reports[(variant, seed, role)] = path + row = { + "run": name, "variant": variant, "seed": seed, + "resolution_h": RESOLUTIONS[variant][0], + "resolution_w": RESOLUTIONS[variant][1], + "checkpoint_role": role, + "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in FRAME_METRICS + TEMPORAL_METRICS: + row[metric] = metric_mean(report, metric) + for metric in NORMALIZED_2D_METRICS: + value = row[metric] + row[f"{metric}_at_512_width"] = ( + None if value is None else value * 512.0 / RESOLUTIONS[variant][1] + ) + for metric in DIAGNOSTICS: + row[metric] = attention_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + checkpoint_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + bootstrap_rows.extend({ + "run": name, "variant": variant, "seed": seed, **item, + } for item in report["bootstrap"]) + checkpoints[name]["roles"][role] = { + "path": report["checkpoint"]["path"], + "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), + "evaluation": str(path.resolve()), + } + + if len(checkpoint_rows) != 42 or len(best_rows) != 6: + raise ValueError("resolution matrix is incomplete") + write_csv(args.output_dir / "resolution_checkpoint_comparison.csv", checkpoint_rows) + write_csv(args.output_dir / "resolution_comparison.csv", best_rows) + write_csv(args.output_dir / "resolution_bootstrap_ci.csv", bootstrap_rows) + (args.output_dir / "resolution_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n" + ) + + aggregate = [] + for variant in VARIANTS: + group = [row for row in best_rows if row["variant"] == variant] + record = {"variant": variant} + for metric in ( + PAIRED_FRAME_METRICS + TEMPORAL_METRICS + DIAGNOSTICS + + ("peak_vram_gib", "training_frames_per_s") + ): + record[metric] = optional_aggregate(group, metric) + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + frame_cache[(variant, seed)] = add_normalized_2d_columns( + read_csv(parent / "per_hand_frame_metrics.csv"), variant, + ) + temporal_cache[(variant, seed)] = read_csv( + parent / "per_temporal_transition_metrics.csv" + ) + + def paired(metric: str, seed: int, subgroup=None, temporal=False) -> dict: + cache = temporal_cache if temporal else frame_cache + key = TEMPORAL_KEY if temporal else FRAME_KEY + # Reference is inserted first so subgroup membership always comes from + # the fixed 512x288 evaluation rather than changing with resolution. + return contrast_take_differences( + { + "reference": cache[("r512x288", seed)], + "candidate": cache[("r640x368", seed)], + }, + metric, {"reference": -1.0, "candidate": 1.0}, key, subgroup, + ) + + paired_rows = [] + for metric in PAIRED_FRAME_METRICS: + results = [paired(metric, seed) for seed in SEEDS] + paired_rows.append({ + "comparison": "r640x368-r512x288", "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_ci.csv", paired_rows) + + temporal_rows = [] + for metric in TEMPORAL_METRICS: + results = [paired(metric, seed, temporal=True) for seed in SEEDS] + temporal_rows.append({ + "comparison": "r640x368-r512x288", "metric": metric, + "delta_definition": "candidate minus reference; lower is better", + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_temporal_ci.csv", temporal_rows) + + subgroup_rows = [] + unavailable = set() + subgroup_metrics = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "absolute_mpvpe_mm", + "direct_2d_error_px_at_512_width", "fingertip_mpjpe_mm", + "translation_z_mae_mm", + ) + for subgroup in SUBGROUPS: + for metric in subgroup_metrics: + prefix = { + "comparison": "r640x368-r512x288", + "subgroup_axis": subgroup[0], "subgroup_value": subgroup[1], + "metric": metric, + "bucket_source": "r512x288 reference rows", + "delta_definition": "candidate minus reference; lower is better", + } + try: + results = [paired(metric, seed, subgroup=subgroup) for seed in SEEDS] + except ValueError as error: + if "no paired values" not in str(error): + raise + unavailable.add(subgroup) + subgroup_rows.append({ + **prefix, "available": False, "take_equal_mean_delta": None, + "ci95_low": None, "ci95_high": None, + "seed_delta_mean": None, "seed_delta_sample_std": None, + "seed_20260716_delta": None, "seed_20260717_delta": None, + "seed_20260718_delta": None, "frame_weighted_delta_mean": None, + "take_count": 0, "observations_per_seed": 0, + "bootstrap_samples": args.bootstrap_samples, + "bootstrap_seed": args.seed, + }) + else: + subgroup_rows.append({ + **prefix, "available": True, + **aggregate_seed_contrasts(results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_resolution_subgroup_ci.csv", subgroup_rows) + + joint_rows = [] + joint_cache = {} + for variant in VARIANTS: + for seed in SEEDS: + parent = reports[(variant, seed, "best_absolute")].parent + rows = read_csv(parent / "per_joint_metrics.csv") + joint_cache[(variant, seed)] = { + (row["side"], int(row["joint_index"])): float(row["mean"]) + for row in rows + } + for side in ("left", "right"): + for joint_index in range(21): + reference = np.array([ + joint_cache[("r512x288", seed)][(side, joint_index)] for seed in SEEDS + ]) + candidate = np.array([ + joint_cache[("r640x368", seed)][(side, joint_index)] for seed in SEEDS + ]) + delta = candidate - reference + joint_rows.append({ + "side": side, "joint_index": joint_index, + "r512x288_seed_mean_mm": float(reference.mean()), + "r512x288_seed_sample_std_mm": float(reference.std(ddof=1)), + "r640x368_seed_mean_mm": float(candidate.mean()), + "r640x368_seed_sample_std_mm": float(candidate.std(ddof=1)), + "candidate_minus_reference_seed_mean_mm": float(delta.mean()), + "candidate_minus_reference_seed_sample_std_mm": float(delta.std(ddof=1)), + "statistical_unit": "seed; descriptive only, no take-level CI", + }) + write_csv(args.output_dir / "resolution_per_joint_comparison.csv", joint_rows) + + payload = { + "status": "complete", "official_test_used": False, + "training_commit": TRAINING_COMMIT, + "evaluations": len(checkpoint_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "evaluation_contract": { + "raw_2d": "processed-input pixels, retained for audit", + "normalized_2d": "640 metrics multiplied by 512/640; 512 unchanged", + "subgroup_membership": "always inherited from aligned r512x288 reference rows", + }, + "paired_frame": str((args.output_dir / "paired_resolution_ci.csv").resolve()), + "paired_temporal": str( + (args.output_dir / "paired_resolution_temporal_ci.csv").resolve() + ), + "paired_subgroups": str( + (args.output_dir / "paired_resolution_subgroup_ci.csv").resolve() + ), + "per_joint": str( + (args.output_dir / "resolution_per_joint_comparison.csv").resolve() + ), + "unavailable_subgroups": [ + {"axis": axis, "value": value} for axis, value in sorted(unavailable) + ], + "source_hashes": { + "reference_validation_launcher": sha256( + args.reference_evaluation_root / "launcher_provenance_sixth.json" + ), + "candidate_training_launcher": sha256( + args.candidate_run_root / "launcher_provenance.json" + ), + }, + } + (args.output_dir / "resolution_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n" + ) + print(json.dumps({ + "status": "complete", "evaluations": len(checkpoint_rows), + "paired_frame_rows": len(paired_rows), + "paired_temporal_rows": len(temporal_rows), + "subgroup_rows": len(subgroup_rows), "per_joint_rows": len(joint_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_temporal_position.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_temporal_position.py new file mode 100644 index 0000000000000000000000000000000000000000..a85351446385b326384584b1928ed219e889d36c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase3_temporal_position.py @@ -0,0 +1,286 @@ +#!/usr/bin/env python3 +"""Summarize the Phase 3 P0/P1 temporal-position experiment.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np + +if __package__: + from scripts.summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + REPORT_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + sha256, + write_csv, + ) +else: + from summarize_phase3_modality import ( + CHECKPOINT_ROLES, + FRAME_KEY, + FRAME_METRICS, + REPORT_METRICS, + SEEDS, + TEMPORAL_KEY, + TEMPORAL_METRICS, + aggregate_seed_contrasts, + attention_mean, + contrast_take_differences, + metric_mean, + read_csv, + sha256, + write_csv, + ) + + +POSITIONS = ("P0", "P1") +ATTENTION_METRICS = ( + "temporal_normalized_entropy", "temporal_diagonal", "temporal_update_norm", +) + + +def position_run_name(position: str, seed: int) -> str: + if position == "P0": + return f"core_m3_l1_t1_s{seed}" + if position == "P1": + return f"temporal_p1_m3_l1_t1_s{seed}" + raise ValueError(f"unknown temporal position: {position}") + + +def load_report(path: Path, position: str, seed: int) -> dict: + report = json.loads(path.read_text(encoding="utf-8")) + experiment = report.get("config", {}).get("experiment", {}) + observed_position = experiment.get("position", "P0") + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("split_role") != "official_validation" + or report.get("clips") != 1495 + or experiment.get("modality") != "M3" + or experiment.get("layout") != "L1" + or experiment.get("temporal") != "T1" + or observed_position != position + or int(report["config"]["seed"]) != seed + ): + raise ValueError(f"invalid formal temporal-position evaluation: {path}") + return report + + +def flatten_bias_report(position: str, seed: int, report: dict) -> list[dict[str, object]]: + rows = [] + bias_report = report["temporal_position_bias"] + for layer in bias_report["layers"]: + offsets = layer["offsets_key_minus_query"] + for head, values in enumerate(layer["per_head_bias"]): + for offset, value in zip(offsets, values, strict=True): + rows.append({ + "position": position, "seed": seed, "layer": int(layer["layer"]), + "head": head, "offset_key_minus_query": int(offset), "bias": float(value), + }) + return rows + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--p0-run-root", type=Path, default=Path("artifacts/phase3/core_runs")) + parser.add_argument("--p1-run-root", type=Path, default=Path("artifacts/phase3/temporal_position_runs")) + parser.add_argument("--p0-evaluation-root", type=Path, default=Path("artifacts/phase3/full_validation")) + parser.add_argument("--p1-evaluation-root", type=Path, default=Path("artifacts/phase3/temporal_position_full_validation")) + parser.add_argument("--p0-diagnostic-root", type=Path, default=Path("artifacts/phase3/temporal_position_p0_diagnostics")) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase3/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + reports: dict[tuple[str, int, str], tuple[Path, dict]] = {} + diagnostics: dict[tuple[str, int], tuple[Path, dict]] = {} + all_rows = [] + best_rows = [] + checkpoints = {} + for position in POSITIONS: + run_root = args.p0_run_root if position == "P0" else args.p1_run_root + evaluation_root = args.p0_evaluation_root if position == "P0" else args.p1_evaluation_root + for seed in SEEDS: + name = position_run_name(position, seed) + summary = json.loads((run_root / name / "summary.json").read_text(encoding="utf-8")) + if summary.get("status") != "completed" or summary.get("completed_step") != 100_000: + raise ValueError(f"incomplete formal training run: {name}") + checkpoint_record = {"position": position, "seed": seed, "roles": {}} + checkpoints[name] = checkpoint_record + for role in CHECKPOINT_ROLES: + path = evaluation_root / name / role / "evaluation.json" + report = load_report(path, position, seed) + reports[(position, seed, role)] = (path, report) + row: dict[str, object] = { + "run": name, "position": position, "seed": seed, + "checkpoint_role": role, "checkpoint_step": int(report["checkpoint"]["step"]), + "checkpoint_sha256": report["checkpoint"]["sha256"], + } + for metric in REPORT_METRICS: + row[metric] = metric_mean(report, metric) + row.update({ + "trainable_parameters": summary["trainable_parameters"], + "frozen_parameters": summary["frozen_parameters"], + "peak_vram_gib": summary["peak_vram_gib"], + "training_frames_per_s": summary["frames_per_s"], + }) + all_rows.append(row) + if role == "best_absolute": + best_rows.append(row) + checkpoint_record["roles"][role] = { + "path": report["checkpoint"]["path"], "sha256": report["checkpoint"]["sha256"], + "step": int(report["checkpoint"]["step"]), "evaluation": str(path.resolve()), + } + + diagnostic_path = ( + args.p0_diagnostic_root / name / "best_absolute" / "evaluation.json" + if position == "P0" + else args.p1_evaluation_root / name / "best_absolute" / "evaluation.json" + ) + diagnostic = load_report(diagnostic_path, position, seed) + formal_best = reports[(position, seed, "best_absolute")][1] + for metric in REPORT_METRICS: + if metric_mean(diagnostic, metric) != metric_mean(formal_best, metric): + raise ValueError(f"diagnostic metric drift for {name}: {metric}") + diagnostics[(position, seed)] = (diagnostic_path, diagnostic) + + if len(all_rows) != 42 or len(best_rows) != 6: + raise ValueError(f"expected 42 checkpoint rows and 6 best rows, got {len(all_rows)}, {len(best_rows)}") + write_csv(args.output_dir / "temporal_position_checkpoint_comparison.csv", all_rows) + + for row in best_rows: + diagnostic = diagnostics[(str(row["position"]), int(row["seed"]))][1] + for metric in ATTENTION_METRICS: + row[metric] = attention_mean(diagnostic, metric) + write_csv(args.output_dir / "temporal_position_comparison.csv", best_rows) + (args.output_dir / "temporal_position_checkpoints.json").write_text( + json.dumps({"official_test_used": False, "runs": checkpoints}, indent=2) + "\n", + encoding="utf-8", + ) + + aggregate = [] + for position in POSITIONS: + group = [row for row in best_rows if row["position"] == position] + record: dict[str, object] = {"position": position, "seeds": list(SEEDS)} + for metric in REPORT_METRICS + ATTENTION_METRICS: + values = [float(row[metric]) for row in group if row[metric] is not None] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + "per_seed": {str(row["seed"]): row[metric] for row in group}, + } + for metric in ("trainable_parameters", "peak_vram_gib", "training_frames_per_s"): + values = [float(row[metric]) for row in group] + record[metric] = { + "mean": float(np.mean(values)), "sample_std": float(np.std(values, ddof=1)), + } + aggregate.append(record) + + frame_cache = {} + temporal_cache = {} + attention_distance_rows = [] + bias_rows = [] + for position in POSITIONS: + for seed in SEEDS: + path, report = diagnostics[(position, seed)] + frame_cache[(position, seed)] = read_csv(path.parent / "per_hand_frame_metrics.csv") + temporal_cache[(position, seed)] = read_csv(path.parent / "per_temporal_transition_metrics.csv") + for distance_mode, report_key in ( + ("absolute", "temporal_attention_by_absolute_frame_distance"), + ("signed_key_minus_query", "temporal_attention_by_signed_frame_distance"), + ): + for distance, distribution in report["attention"][report_key].items(): + attention_distance_rows.append({ + "position": position, "seed": seed, "distance_mode": distance_mode, + "distance": int(distance), **distribution, + }) + bias_rows.extend(flatten_bias_report(position, seed, report)) + write_csv(args.output_dir / "temporal_position_attention_by_distance.csv", attention_distance_rows) + if not bias_rows: + raise ValueError("P1 diagnostic evaluations did not export relative-position bias") + write_csv(args.output_dir / "temporal_position_bias.csv", bias_rows) + + grouped_bias: dict[tuple[int, int, int], list[float]] = {} + for row in bias_rows: + key = (int(row["layer"]), int(row["head"]), int(row["offset_key_minus_query"])) + grouped_bias.setdefault(key, []).append(float(row["bias"])) + bias_aggregate_rows = [{ + "position": "P1", "layer": layer, "head": head, "offset_key_minus_query": offset, + "seed_mean_bias": float(np.mean(values)), + "seed_sample_std_bias": float(np.std(values, ddof=1)), + "seed_20260716_bias": values[0], "seed_20260717_bias": values[1], + "seed_20260718_bias": values[2], + } for (layer, head, offset), values in sorted(grouped_bias.items())] + write_csv(args.output_dir / "temporal_position_bias_aggregate.csv", bias_aggregate_rows) + + paired_rows = [] + coefficients = {"P1": 1.0, "P0": -1.0} + for metric in FRAME_METRICS: + seed_results = [ + contrast_take_differences( + {position: frame_cache[(position, seed)] for position in POSITIONS}, + metric, coefficients, FRAME_KEY, + ) + for seed in SEEDS + ] + paired_rows.append({ + "comparison": "P1_minus_P0", "metric": metric, + "delta_definition": "P1_minus_P0_lower_is_better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_temporal_position_bootstrap_ci.csv", paired_rows) + + paired_temporal_rows = [] + for metric in TEMPORAL_METRICS: + seed_results = [ + contrast_take_differences( + {position: temporal_cache[(position, seed)] for position in POSITIONS}, + metric, coefficients, TEMPORAL_KEY, + ) + for seed in SEEDS + ] + paired_temporal_rows.append({ + "comparison": "P1_minus_P0", "metric": metric, + "delta_definition": "P1_minus_P0_lower_is_better", + **aggregate_seed_contrasts(seed_results, args.seed, args.bootstrap_samples), + }) + write_csv(args.output_dir / "paired_temporal_position_temporal_ci.csv", paired_temporal_rows) + + payload = { + "status": "complete", "official_test_used": False, + "checkpoint_selection": "best_absolute selected only on the registered fixed 256-clip subset", + "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "aggregate": aggregate, + "paired_frame": str((args.output_dir / "paired_temporal_position_bootstrap_ci.csv").resolve()), + "paired_temporal": str((args.output_dir / "paired_temporal_position_temporal_ci.csv").resolve()), + "attention_distance": str((args.output_dir / "temporal_position_attention_by_distance.csv").resolve()), + "bias_aggregate": str((args.output_dir / "temporal_position_bias_aggregate.csv").resolve()), + "source_hashes": { + "p0_diagnostic_launcher": sha256(args.p0_diagnostic_root / "launcher_provenance.json"), + "p1_validation_launcher": sha256(args.p1_evaluation_root / "launcher_provenance.json"), + }, + } + (args.output_dir / "temporal_position_comparison.json").write_text( + json.dumps(payload, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": "complete", "evaluations": len(all_rows), "best_absolute_runs": len(best_rows), + "paired_rows": len(paired_rows), "paired_temporal_rows": len(paired_temporal_rows), + "bias_rows": len(bias_rows), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_a1.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_a1.py new file mode 100644 index 0000000000000000000000000000000000000000..72611727f8c8853380b2b3d4d31e8389d70b79e3 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_a1.py @@ -0,0 +1,359 @@ +#!/usr/bin/env python3 +"""Aggregate the three frozen-checkpoint Phase 4 A1 oracle diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary + +if __package__: + from scripts.fit_phase4_oracle_local_depth import paired_take_bootstrap +else: + from fit_phase4_oracle_local_depth import paired_take_bootstrap + + +SEEDS = (20260716, 20260717, 20260718) +VARIANTS = ("coarse", "control", "local") +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", + "translation_z_signed_error_mm", + "translation_z_mae_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_consistency_px", + "residual_magnitude_mm", +) +STABLE_FIELDS = ( + "sample_index", + "clip_index", + "time_index", + "take", + "subject", + "sequence", + "frame_id", + "side", + "side_index", + "action_family", + "action_label", + "action_name", + "hand_size_px", + "wrist_depth_m", + "bimanual_size_ratio", + "bimanual_depth_gap_m", + "bimanual_asymmetry_bucket", + "local_depth_valid_fraction", + "local_depth_discontinuity_m", +) + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty CSV {path}") + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def load_seed_results(root: Path) -> tuple[ + dict[int, list[dict[str, str]]], dict[int, dict[str, Any]], list[dict[str, str]] +]: + rows_by_seed: dict[int, list[dict[str, str]]] = {} + reports: dict[int, dict[str, Any]] = {} + reference: list[dict[str, str]] | None = None + for seed in SEEDS: + fit = root / f"seed_{seed}" / "fit" + rows = read_csv(fit / "validation_predictions.csv") + report = json.loads((fit / "results.json").read_text(encoding="utf-8")) + if report.get("official_test_used") is not False: + raise ValueError(f"seed {seed} did not preserve official-test isolation") + if reference is None: + reference = rows + else: + if len(rows) != len(reference): + raise ValueError("A1 seed validation row counts differ") + for index, (candidate, expected) in enumerate(zip(rows, reference, strict=True)): + for field in STABLE_FIELDS: + if candidate[field] != expected[field]: + raise ValueError( + f"A1 seed metadata mismatch at row {index}, field {field}" + ) + rows_by_seed[seed] = rows + reports[seed] = report + if reference is None: + raise ValueError("no A1 seed results found") + return rows_by_seed, reports, reference + + +def aggregate_predictions( + rows_by_seed: dict[int, list[dict[str, str]]], +) -> dict[str, dict[str, np.ndarray]]: + output: dict[str, dict[str, np.ndarray]] = {} + for variant in VARIANTS: + output[variant] = {} + for metric in METRICS: + per_seed = np.asarray([ + [float(row[f"{variant}_{metric}"]) for row in rows_by_seed[seed]] + for seed in SEEDS + ], dtype=np.float64) + output[variant][metric] = per_seed.mean(axis=0) + return output + + +def group_masks( + rows: list[dict[str, str]], challenge: dict[str, Any], +) -> dict[str, np.ndarray]: + farthest = float(challenge["thresholds"]["farthest_observed_wrist_depth_p80_m"]) + challenge_clips = {int(value) for value in challenge["clip_indices"]} + return { + "all": np.ones(len(rows), dtype=bool), + "left": np.asarray([row["side"] == "left" for row in rows]), + "right": np.asarray([row["side"] == "right" for row in rows]), + "small": np.asarray([float(row["hand_size_px"]) < 64.0 for row in rows]), + "farthest_observed": np.asarray([ + float(row["wrist_depth_m"]) >= farthest for row in rows + ]), + "strong_asymmetry": np.asarray([ + row["bimanual_asymmetry_bucket"] == "strong" for row in rows + ]), + "challenge": np.asarray([ + int(row["clip_index"]) in challenge_clips for row in rows + ]), + } + + +def aggregate_group_rows( + predictions: dict[str, dict[str, np.ndarray]], masks: dict[str, np.ndarray], +) -> list[dict[str, object]]: + rows: list[dict[str, object]] = [] + for group, mask in masks.items(): + for variant in VARIANTS: + for metric in METRICS: + rows.append({ + "group": group, + "variant": variant, + "metric": metric, + "seed_scope": "per-frame mean over seeds 20260716/17/18", + **distribution_summary(predictions[variant][metric][mask]), + }) + return rows + + +def find_value( + rows: list[dict[str, object]], group: str, variant: str, metric: str, statistic: str, +) -> float: + record = next( + row for row in rows + if row["group"] == group and row["variant"] == variant and row["metric"] == metric + ) + return float(record[statistic]) + + +def seed_summary_rows(reports: dict[int, dict[str, Any]]) -> list[dict[str, object]]: + rows = [] + for seed in SEEDS: + report = reports[seed] + reductions = report["gate"]["reductions_percent"] + rows.append({ + "seed": seed, + "checkpoint_step": report["frozen_checkpoint"]["step"], + "checkpoint_sha256": report["frozen_checkpoint"]["sha256"], + "formal_A1_gate_pass": report["gate"]["formal_A1_gate_pass"], + **reductions, + "control_best_epoch": min( + report["histories"]["control"], + key=lambda row: row["holdout_residual_mae_m"], + )["epoch"], + "local_best_epoch": min( + report["histories"]["local"], + key=lambda row: row["holdout_residual_mae_m"], + )["epoch"], + }) + return rows + + +def markdown_report( + report: dict[str, Any], group_rows: list[dict[str, object]], seed_rows: list[dict[str, object]], +) -> str: + gate = report["gate"] + lines = [ + "# Phase 4 A1 Oracle Local-Depth Diagnostic", + "", + "## Decision", + "", + f"- Formal gate: **{'PASS' if gate['formal_A1_gate_pass'] else 'FAIL'}**.", + f"- Action: **{gate['decision']}**.", + "- Official test used: no.", + "- A2 predicted-location diagnostic is not admitted when A1 fails the preregistered gate.", + "", + "## Three-Seed Aggregate", + "", + "| Metric / group | Coarse | Oracle-location control | Oracle local depth | Reduction vs coarse |", + "|---|---:|---:|---:|---:|", + ] + table_specs = ( + ("z P95 / all", "all", "translation_z_mae_mm", "p95"), + ("absolute MPJPE / all", "all", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / small", "small", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / farthest-observed", "farthest_observed", "absolute_mpjpe_mm", "mean"), + ("absolute MPJPE / right", "right", "absolute_mpjpe_mm", "mean"), + ("projected MANO 2D / all", "all", "mano_projected_2d_error_px", "mean"), + ) + for label, group, metric, statistic in table_specs: + values = { + variant: find_value(group_rows, group, variant, metric, statistic) + for variant in VARIANTS + } + reduction = 100.0 * (values["coarse"] - values["local"]) / values["coarse"] + lines.append( + f"| {label} | {values['coarse']:.2f} | {values['control']:.2f} | " + f"{values['local']:.2f} | {reduction:.2f}% |" + ) + lines.extend(( + "", + "The aggregate uses the per-frame mean error over the three frozen Phase 3 checkpoints, matching the Phase 4 Wave 0 aggregation convention. The local-depth regressor improves the tail beyond the same-capacity oracle-location control, but the registered full-validation/far-small thresholds are not reached.", + "", + "## Seed Stability", + "", + "| Seed | z P95 reduction | Small absolute reduction | Farthest-observed absolute reduction | Gate | Local best epoch |", + "|---:|---:|---:|---:|---|---:|", + )) + for row in seed_rows: + lines.append( + f"| {row['seed']} | {row['full_validation_z_p95_percent']:.2f}% | " + f"{row['small_absolute_mpjpe_percent']:.2f}% | " + f"{row['farthest_observed_absolute_mpjpe_percent']:.2f}% | " + f"{'pass' if row['formal_A1_gate_pass'] else 'fail'} | {row['local_best_epoch']} |" + ) + lines.extend(( + "", + "Seed 20260718 is the limiting case: its train-only holdout selected epoch 1 and its local-depth gain over the frozen coarse output is small. This prevents a robust three-seed claim even though seeds 20260716 and 20260717 individually pass.", + "", + "## Interpretation", + "", + "- Engineering correctness is established: data/hash isolation, raw depth/K alignment, feature schema, bounded residual, and exact root-relative/direct-2D invariance all passed.", + "- Local depth contains useful information beyond oracle location alone, but the gain is checkpoint-dependent and narrowly misses the preregistered aggregate threshold.", + "- Per the Phase 4 stop rule, do not implement the deployable local-depth branch or A2 at this point. Shift the next metric-z effort to matched axis-aware loss and train-only balanced-sampling controls; A3 remains an independent appearance upper-bound diagnostic.", + "", + "## Sources", + "", + f"- Input root: `{report['input_root']}`", + f"- Aggregate table: `{report['outputs']['comparison_csv']}`", + f"- Take bootstrap: `{report['outputs']['paired_take_bootstrap_ci']}`", + )) + return "\n".join(lines) + "\n" + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--input-root", type=Path, default=Path("artifacts/phase4/a1/formal")) + parser.add_argument( + "--challenge-manifest", type=Path, + default=Path("artifacts/phase4/challenge_subset/official_val_challenge_128.json"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/reports")) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + rows_by_seed, reports, metadata = load_seed_results(args.input_root) + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + predictions = aggregate_predictions(rows_by_seed) + group_rows = aggregate_group_rows(predictions, group_masks(metadata, challenge)) + bootstrap_rows = paired_take_bootstrap( + metadata, + predictions, + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + seed_rows = seed_summary_rows(reports) + + coarse_z_p95 = find_value(group_rows, "all", "coarse", "translation_z_mae_mm", "p95") + local_z_p95 = find_value(group_rows, "all", "local", "translation_z_mae_mm", "p95") + reductions = { + "full_validation_z_p95_percent": 100.0 * (coarse_z_p95 - local_z_p95) / coarse_z_p95, + } + for group in ("small", "farthest_observed", "right"): + coarse = find_value(group_rows, group, "coarse", "absolute_mpjpe_mm", "mean") + local = find_value(group_rows, group, "local", "absolute_mpjpe_mm", "mean") + reductions[f"{group}_absolute_mpjpe_percent"] = 100.0 * (coarse - local) / coarse + metric_pass = ( + reductions["full_validation_z_p95_percent"] >= 20.0 + or reductions["small_absolute_mpjpe_percent"] >= 15.0 + or reductions["farthest_observed_absolute_mpjpe_percent"] >= 15.0 + ) + invariance_pass = all( + abs(find_value(group_rows, "all", "local", metric, "mean") + - find_value(group_rows, "all", "coarse", metric, "mean")) <= 1e-4 + for metric in ("root_relative_mpjpe_mm", "direct_2d_error_px") + ) + formal_pass = bool(metric_pass and invariance_pass) + output_csv = args.output_dir / "a1_oracle_local_depth_comparison.csv" + output_bootstrap = args.output_dir / "paired_take_bootstrap_ci.csv" + output_seed = args.output_dir / "a1_oracle_local_depth_seed_stability.csv" + output_json = args.output_dir / "A1_ORACLE_LOCAL_DEPTH.json" + output_md = args.output_dir / "A1_ORACLE_LOCAL_DEPTH.md" + report = { + "status": "complete", + "phase": 4, + "wave": "A1_oracle_local_depth", + "official_test_used": False, + "input_root": str(args.input_root.resolve()), + "seed_scope": list(SEEDS), + "aggregation": "per-frame mean error over three seeds, then distribution summary", + "checkpoint_rule": "Phase 3 fixed-subset tail-best-absolute per seed", + "gate": { + "formal_A1_gate_pass": formal_pass, + "metric_gate_pass": bool(metric_pass), + "invariance_gate_pass": bool(invariance_pass), + "decision": ( + "ADMIT_A2" if formal_pass + else "STOP_LOCAL_DEPTH_BRANCH_AND_SHIFT_TO_LOSS_SAMPLING_OR_BACKBONE_CONTROLS" + ), + "thresholds": { + "full_validation_z_p95_reduction_percent": 20.0, + "small_or_farthest_absolute_mpjpe_reduction_percent": 15.0, + "root_relative_and_direct_2d_max_degradation_percent": 2.0, + }, + "observed_reductions_percent": reductions, + }, + "seed_results": seed_rows, + "outputs": { + "comparison_csv": str(output_csv.resolve()), + "paired_take_bootstrap_ci": str(output_bootstrap.resolve()), + "seed_stability_csv": str(output_seed.resolve()), + "markdown": str(output_md.resolve()), + }, + } + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(output_csv, group_rows) + write_csv(output_bootstrap, bootstrap_rows) + write_csv(output_seed, seed_rows) + output_json.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + output_md.write_text(markdown_report(report, group_rows, seed_rows), encoding="utf-8") + print(json.dumps({"status": "complete", "gate": report["gate"]}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_a3.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_a3.py new file mode 100644 index 0000000000000000000000000000000000000000..d41d5683a4d4ffc98d31e2e3e2bd85c042d499e2 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_a3.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +"""Summarize A3 refined predictions against their exact frozen coarse outputs.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Mapping + +try: + from scripts.summarize_phase4_control import ( + RECONSTRUCTION_KEY, + RECONSTRUCTION_METADATA, + SEEDS, + aggregate_seed_rows, + assert_pair_alignment, + distribution_rows, + groups, + paired_take_bootstrap, + read_csv, + statistic, + write_csv, + ) +except ModuleNotFoundError: + from summarize_phase4_control import ( # type: ignore[no-redef] + RECONSTRUCTION_KEY, + RECONSTRUCTION_METADATA, + SEEDS, + aggregate_seed_rows, + assert_pair_alignment, + distribution_rows, + groups, + paired_take_bootstrap, + read_csv, + statistic, + write_csv, + ) + + +MODES = ("oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k") +METRIC_PAIRS = { + "absolute_mpjpe_mm": "coarse_absolute_mpjpe_mm", + "root_relative_mpjpe_mm": "coarse_root_relative_mpjpe_mm", + "absolute_mpvpe_mm": "coarse_absolute_mpvpe_mm", + "root_relative_mpvpe_mm": "coarse_root_relative_mpvpe_mm", + "fingertip_mpjpe_mm": "coarse_fingertip_mpjpe_mm", + "translation_z_mae_mm": "coarse_translation_z_mae_mm", +} +METRICS = tuple(METRIC_PAIRS) + + +def discover_evaluations(root: Path, role: str) -> dict[str, dict[int, Path]]: + output: dict[str, dict[int, Path]] = {mode: {} for mode in MODES} + for report_path in sorted(root.glob(f"*/{role}/evaluation.json")): + report = json.loads(report_path.read_text(encoding="utf-8")) + oracle = report.get("oracle_crop_refinement", {}) + if ( + report.get("status") != "evaluated" + or report.get("official_test_used") is not False + or report.get("clips") != 1495 + or report.get("phase4_diagnostics", {}).get("enabled") is not True + or oracle.get("enabled") is not True + or oracle.get("gt_location_at_inference") is not True + ): + raise ValueError(f"invalid complete A3 evaluation: {report_path}") + config = report["config"] + mode = config["experiment"]["oracle_crop_mode"] + seed = int(config["seed"]) + if mode not in output or seed in output[mode]: + raise ValueError(f"unexpected or duplicate A3 mode/seed: {mode}/{seed}") + if ( + oracle.get("coarse_checkpoint_sha256") + != config["experiment"]["coarse_checkpoint_sha256"] + ): + raise ValueError(f"coarse checkpoint identity missing: {report_path}") + output[mode][seed] = report_path.parent + for mode, records in output.items(): + if tuple(sorted(records)) != SEEDS: + raise ValueError( + f"expected seeds {SEEDS} for {mode}, found {tuple(sorted(records))}" + ) + return output + + +def coarse_rows(rows: list[dict[str, str]]) -> list[dict[str, object]]: + output = [] + for source in rows: + row: dict[str, object] = dict(source) + for metric, coarse_metric in METRIC_PAIRS.items(): + if coarse_metric not in source: + raise ValueError(f"missing A3 coarse metric {coarse_metric}") + row[metric] = source[coarse_metric] + output.append(row) + return output + + +def compute_gate( + coarse_absolute: float, + refined_absolute: float, + coarse_fingertip: float, + refined_fingertip: float, + coarse_root_mpvpe: float, + refined_root_mpvpe: float, +) -> dict[str, float | bool]: + fingertip_gain = 100.0 * (coarse_fingertip - refined_fingertip) / coarse_fingertip + root_mpvpe_gain = 100.0 * ( + coarse_root_mpvpe - refined_root_mpvpe + ) / coarse_root_mpvpe + absolute_degradation = 100.0 * ( + refined_absolute - coarse_absolute + ) / coarse_absolute + return { + "fingertip_improvement_percent": fingertip_gain, + "root_relative_mpvpe_improvement_percent": root_mpvpe_gain, + "absolute_mpjpe_degradation_percent": absolute_degradation, + "accuracy_gain_passed": bool( + fingertip_gain >= 10.0 or root_mpvpe_gain >= 10.0 + ), + "absolute_guardrail_passed": bool(absolute_degradation <= 2.0), + "promotion_gate_passed": bool( + (fingertip_gain >= 10.0 or root_mpvpe_gain >= 10.0) + and absolute_degradation <= 2.0 + ), + } + + +def rename_distribution_conditions( + rows: list[dict[str, object]], mode: str, scope: str, +) -> None: + for row in rows: + row["mode"] = mode + row["scope"] = scope + row["condition"] = { + "reference": "coarse", + "candidate": "refined", + "candidate_minus_reference": "refined_minus_coarse", + }[row["condition"]] + + +def gate_from_distributions( + rows: list[dict[str, object]], mode: str, +) -> dict[str, float | bool]: + def overall(metric: str, condition: str) -> float: + matches = [ + row for row in rows + if row["group_field"] == "all" and row["group_value"] == "all" + and row["metric"] == metric and row["condition"] == condition + ] + if len(matches) != 1: + raise ValueError(f"missing overall {mode}/{metric}/{condition}") + return float(matches[0]["mean"]) + + return compute_gate( + overall("absolute_mpjpe_mm", "coarse"), + overall("absolute_mpjpe_mm", "refined"), + overall("fingertip_mpjpe_mm", "coarse"), + overall("fingertip_mpjpe_mm", "refined"), + overall("root_relative_mpvpe_mm", "coarse"), + overall("root_relative_mpvpe_mm", "refined"), + ) + + +def assert_coarse_identical_across_modes( + raw_by_mode: Mapping[str, Mapping[int, list[dict[str, str]]]], +) -> None: + reference_mode = MODES[0] + for seed in SEEDS: + reference = { + tuple(row[field] for field in RECONSTRUCTION_KEY): tuple( + row[coarse_metric] for coarse_metric in METRIC_PAIRS.values() + ) + for row in raw_by_mode[reference_mode][seed] + } + for mode in MODES[1:]: + candidate = { + tuple(row[field] for field in RECONSTRUCTION_KEY): tuple( + row[coarse_metric] for coarse_metric in METRIC_PAIRS.values() + ) + for row in raw_by_mode[mode][seed] + } + if candidate != reference: + raise ValueError( + f"frozen coarse outputs differ across A3 modes for seed {seed}" + ) + + +def seed_deltas( + raw_by_seed: Mapping[int, list[dict[str, str]]], mode: str, +) -> list[dict[str, object]]: + output = [] + for seed in SEEDS: + rows = [ + row for row in raw_by_seed[seed] + if int(row["annotation_valid"]) == 1 + ] + for metric, coarse_metric in METRIC_PAIRS.items(): + coarse = statistic((row.get(coarse_metric) for row in rows), "mean") + refined = statistic((row.get(metric) for row in rows), "mean") + if coarse is None or refined is None: + continue + output.append({ + "mode": mode, "seed": seed, "metric": metric, + "coarse": coarse, "refined": refined, + "refined_minus_coarse": refined - coarse, + }) + return output + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--role", default="best_absolute") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--challenge-manifest", type=Path, required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + evaluations = discover_evaluations(args.evaluation_root, args.role) + challenge = json.loads(args.challenge_manifest.read_text(encoding="utf-8")) + challenge_indices = {int(value) for value in challenge["clip_indices"]} + if ( + len(challenge_indices) != int(challenge["count"]) + or challenge.get("source_clip_count") != 1495 + or challenge.get("checkpoint_selection_allowed") is not False + or challenge.get("training_sampler_use_allowed") is not False + or challenge.get("official_test_used") is not False + ): + raise ValueError("invalid frozen official-validation challenge subset") + raw_by_mode = { + mode: { + seed: read_csv(evaluations[mode][seed] / "per_hand_frame_metrics.csv") + for seed in SEEDS + } + for mode in MODES + } + assert_coarse_identical_across_modes(raw_by_mode) + + comparison_output = [] + paired_output = [] + seed_output = [] + gates = {} + challenge_diagnostics = {} + for mode_index, mode in enumerate(MODES): + refined = aggregate_seed_rows( + raw_by_mode[mode], RECONSTRUCTION_KEY, METRICS, + ) + coarse = aggregate_seed_rows( + {seed: coarse_rows(raw_by_mode[mode][seed]) for seed in SEEDS}, + RECONSTRUCTION_KEY, METRICS, + ) + assert_pair_alignment( + coarse, refined, RECONSTRUCTION_KEY, RECONSTRUCTION_METADATA, + ) + distributions = distribution_rows( + coarse, refined, METRICS, require_annotation_valid=True, + ) + rename_distribution_conditions(distributions, mode, "full_validation") + comparison_output.extend(distributions) + + valid_coarse = [row for row in coarse if int(row["annotation_valid"]) == 1] + valid_refined = [row for row in refined if int(row["annotation_valid"]) == 1] + paired = paired_take_bootstrap( + valid_coarse, valid_refined, METRICS, groups(valid_coarse), + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + mode_index, + ) + paired.extend(paired_take_bootstrap( + valid_coarse, valid_refined, ("translation_z_mae_mm",), + groups(valid_coarse), statistics=("p95", "cvar95"), + bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 100 + mode_index, + )) + for row in paired: + row["mode"] = mode + row["scope"] = "full_validation" + row["coarse"] = row.pop("reference") + row["refined"] = row.pop("candidate") + row["refined_minus_coarse"] = row.pop("candidate_minus_reference") + paired_output.extend(paired) + seed_output.extend(seed_deltas(raw_by_mode[mode], mode)) + + gates[mode] = gate_from_distributions(distributions, mode) + + challenge_coarse = [ + row for row in coarse if int(row["clip_index"]) in challenge_indices + ] + challenge_refined = [ + row for row in refined if int(row["clip_index"]) in challenge_indices + ] + challenge_distributions = distribution_rows( + challenge_coarse, challenge_refined, METRICS, + require_annotation_valid=True, + ) + rename_distribution_conditions( + challenge_distributions, mode, "challenge_secondary", + ) + comparison_output.extend(challenge_distributions) + challenge_diagnostics[mode] = gate_from_distributions( + challenge_distributions, mode, + ) + challenge_paired = paired_take_bootstrap( + [row for row in challenge_coarse if int(row["annotation_valid"]) == 1], + [row for row in challenge_refined if int(row["annotation_valid"]) == 1], + METRICS, [("all", "all"), ("side", "left"), ("side", "right")], + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 200 + mode_index, + ) + for row in challenge_paired: + row["mode"] = mode + row["scope"] = "challenge_secondary" + row["coarse"] = row.pop("reference") + row["refined"] = row.pop("candidate") + row["refined_minus_coarse"] = row.pop("candidate_minus_reference") + paired_output.extend(challenge_paired) + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "a3_oracle_crop_comparison.csv", comparison_output) + write_csv( + args.output_dir / "a3_oracle_crop_paired_take_bootstrap_ci.csv", + paired_output, + ) + write_csv(args.output_dir / "a3_oracle_crop_seed_stability.csv", seed_output) + report = { + "status": "summarized", + "official_test_used": False, + "role": args.role, + "seeds": list(SEEDS), + "modes": list(MODES), + "aggregation": "aligned per-frame error averaged over three seeds", + "confidence_interval_unit": "paired official-validation take", + "coarse_consistency_across_modes": True, + "challenge_subset": { + "manifest": str(args.challenge_manifest.resolve()), + "clips": len(challenge_indices), + "role": "secondary_diagnostic_only", + "checkpoint_selection_allowed": False, + "diagnostics": challenge_diagnostics, + }, + "promotion_rule": ( + "fingertip MPJPE or root-relative MPVPE improves >=10%, and " + "absolute MPJPE degrades <=2%" + ), + "gates": gates, + } + (args.output_dir / "A3_ORACLE_CROP.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_control.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_control.py new file mode 100644 index 0000000000000000000000000000000000000000..786bf74861d7bf81eeee203f188c84966ad92b02 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_control.py @@ -0,0 +1,452 @@ +#!/usr/bin/env python3 +"""Compare a three-seed Phase 4 control with the matched 100k B-ref.""" + +from __future__ import annotations + +import argparse +import csv +import json +from collections import defaultdict +from pathlib import Path +from typing import Iterable, Mapping + +import numpy as np + +from foundation_hand.evaluation.metrics import distribution_summary + + +SEEDS = (20260716, 20260717, 20260718) +RECONSTRUCTION_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "fingertip_mpjpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "identity_switch_fraction", +) +RECONSTRUCTION_KEY = ("clip_index", "time_index", "side") +TEMPORAL_KEY = ("clip_index", "transition_index", "side") +RECONSTRUCTION_METADATA = ( + "take", + "frame_id", + "side", + "annotation_valid", + "hand_size_bucket", + "depth_bucket", + "action_family", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", +) +GROUP_FIELDS = ( + "side", + "hand_size_bucket", + "depth_bucket", + "action_family", + "bimanual_asymmetry_bucket", + "local_depth_validity_bucket", +) + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, object]]) -> None: + if not rows: + raise ValueError(f"refusing to write empty report {path}") + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: object) -> float | None: + if value in (None, ""): + return None + result = float(value) + return result if np.isfinite(result) else None + + +def discover_evaluations(root: Path, role: str) -> dict[int, Path]: + output = {} + for report_path in sorted(root.glob(f"*/{role}/evaluation.json")): + report = json.loads(report_path.read_text(encoding="utf-8")) + if report.get("status") != "evaluated" or report.get("official_test_used") is not False: + raise ValueError(f"invalid evaluation report: {report_path}") + if report.get("phase4_diagnostics", {}).get("enabled") is not True: + raise ValueError(f"Phase 4 diagnostics missing: {report_path}") + seed = int(report["config"]["seed"]) + if seed in output: + raise ValueError(f"duplicate seed {seed} under {root}") + output[seed] = report_path.parent + if tuple(sorted(output)) != SEEDS: + raise ValueError(f"expected seeds {SEEDS}, found {tuple(sorted(output))} under {root}") + return output + + +def row_key(row: Mapping[str, object], fields: tuple[str, ...]) -> tuple[str, ...]: + return tuple(str(row[field]) for field in fields) + + +def aggregate_seed_rows( + rows_by_seed: Mapping[int, list[dict[str, str]]], + key_fields: tuple[str, ...], + metric_fields: tuple[str, ...], +) -> list[dict[str, object]]: + maps = { + seed: {row_key(row, key_fields): row for row in rows} + for seed, rows in rows_by_seed.items() + } + keys = set(maps[SEEDS[0]]) + if any(set(maps[seed]) != keys for seed in SEEDS[1:]): + raise ValueError("three-seed exported row keys do not align") + output = [] + for key in sorted(keys): + first = maps[SEEDS[0]][key] + row: dict[str, object] = dict(first) + for metric in metric_fields: + values = [ + optional_float(maps[seed][key].get(metric)) for seed in SEEDS + ] + finite = [value for value in values if value is not None] + row[metric] = float(np.mean(finite)) if finite else None + output.append(row) + return output + + +def assert_pair_alignment( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + key_fields: tuple[str, ...], + metadata_fields: tuple[str, ...], +) -> None: + reference_map = {row_key(row, key_fields): row for row in reference} + candidate_map = {row_key(row, key_fields): row for row in candidate} + if reference_map.keys() != candidate_map.keys(): + raise ValueError("candidate/reference exported row keys do not align") + for key, reference_row in reference_map.items(): + candidate_row = candidate_map[key] + for field in metadata_fields: + if str(reference_row.get(field, "")) != str(candidate_row.get(field, "")): + raise ValueError(f"candidate/reference metadata mismatch at {key}/{field}") + + +def groups(rows: list[dict[str, object]]) -> list[tuple[str, str]]: + output = [("all", "all")] + for field in GROUP_FIELDS: + values = sorted({str(row.get(field)) for row in rows if row.get(field) not in (None, "")}) + output.extend((field, value) for value in values) + return output + + +def selected_rows( + rows: list[dict[str, object]], group_field: str, group_value: str, +) -> list[dict[str, object]]: + if group_field == "all": + return rows + return [row for row in rows if str(row.get(group_field)) == group_value] + + +def distribution_rows( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + metrics: tuple[str, ...], + *, + require_annotation_valid: bool, +) -> list[dict[str, object]]: + if require_annotation_valid: + reference = [row for row in reference if int(row["annotation_valid"]) == 1] + candidate = [row for row in candidate if int(row["annotation_valid"]) == 1] + output = [] + for group_field, group_value in groups(reference): + reference_group = selected_rows(reference, group_field, group_value) + candidate_group = selected_rows(candidate, group_field, group_value) + for metric in metrics: + summaries = { + "reference": distribution_summary(row.get(metric) for row in reference_group), + "candidate": distribution_summary(row.get(metric) for row in candidate_group), + } + for condition, summary in summaries.items(): + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "condition": condition, + **summary, + "mean_relative_percent": None, + }) + delta = { + statistic: ( + summaries["candidate"][statistic] - summaries["reference"][statistic] + if summaries["candidate"][statistic] is not None + and summaries["reference"][statistic] is not None else None + ) + for statistic in ("mean", "p50", "p90", "p95", "p99", "cvar95") + } + reference_mean = summaries["reference"]["mean"] + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "condition": "candidate_minus_reference", + "count": summaries["candidate"]["count"], + "std": None, + **delta, + "mean_relative_percent": ( + 100.0 * delta["mean"] / reference_mean + if delta["mean"] is not None and reference_mean not in (None, 0) else None + ), + }) + return output + + +def statistic(values: Iterable[object], name: str) -> float | None: + array = np.asarray( + [value for item in values if (value := optional_float(item)) is not None], + dtype=np.float64, + ) + if not array.size: + return None + if name == "mean": + return float(array.mean()) + threshold = float(np.percentile(array, 95)) + if name == "p95": + return threshold + if name == "cvar95": + return float(array[array >= threshold].mean()) + raise ValueError(f"unknown statistic {name}") + + +def paired_take_bootstrap( + reference: list[dict[str, object]], + candidate: list[dict[str, object]], + metrics: tuple[str, ...], + group_specs: list[tuple[str, str]], + *, + statistics: tuple[str, ...], + bootstrap_samples: int, + seed: int, +) -> list[dict[str, object]]: + output = [] + for group_index, (group_field, group_value) in enumerate(group_specs): + reference_group = selected_rows(reference, group_field, group_value) + candidate_group = selected_rows(candidate, group_field, group_value) + reference_by_take: dict[str, list[dict[str, object]]] = defaultdict(list) + candidate_by_take: dict[str, list[dict[str, object]]] = defaultdict(list) + for row in reference_group: + reference_by_take[str(row["take"])].append(row) + for row in candidate_group: + candidate_by_take[str(row["take"])].append(row) + takes = sorted(set(reference_by_take) & set(candidate_by_take)) + for metric_index, metric in enumerate(metrics): + for statistic_index, statistic_name in enumerate(statistics): + paired = [] + reference_values = [] + candidate_values = [] + for take in takes: + reference_value = statistic( + (row.get(metric) for row in reference_by_take[take]), statistic_name, + ) + candidate_value = statistic( + (row.get(metric) for row in candidate_by_take[take]), statistic_name, + ) + if reference_value is None or candidate_value is None: + continue + reference_values.append(reference_value) + candidate_values.append(candidate_value) + paired.append(candidate_value - reference_value) + deltas = np.asarray(paired, dtype=np.float64) + if not deltas.size: + continue + rng = np.random.default_rng( + np.random.SeedSequence([seed, group_index, metric_index, statistic_index]) + ) + indices = rng.integers( + 0, deltas.size, size=(bootstrap_samples, deltas.size), + ) + distribution = deltas[indices].mean(axis=1) + output.append({ + "group_field": group_field, + "group_value": group_value, + "metric": metric, + "statistic": f"take_{statistic_name}", + "takes": int(deltas.size), + "reference": float(np.mean(reference_values)), + "candidate": float(np.mean(candidate_values)), + "candidate_minus_reference": float(deltas.mean()), + "ci_low": float(np.percentile(distribution, 2.5)), + "ci_high": float(np.percentile(distribution, 97.5)), + "bootstrap_samples": bootstrap_samples, + }) + return output + + +def per_seed_deltas( + reference_dirs: Mapping[int, Path], + candidate_dirs: Mapping[int, Path], +) -> list[dict[str, object]]: + output = [] + for seed in SEEDS: + reference = [ + row for row in read_csv(reference_dirs[seed] / "per_hand_frame_metrics.csv") + if int(row["annotation_valid"]) == 1 + ] + candidate = [ + row for row in read_csv(candidate_dirs[seed] / "per_hand_frame_metrics.csv") + if int(row["annotation_valid"]) == 1 + ] + for metric in RECONSTRUCTION_METRICS: + reference_mean = statistic((row.get(metric) for row in reference), "mean") + candidate_mean = statistic((row.get(metric) for row in candidate), "mean") + if reference_mean is None or candidate_mean is None: + continue + output.append({ + "seed": seed, + "metric": metric, + "reference": reference_mean, + "candidate": candidate_mean, + "candidate_minus_reference": candidate_mean - reference_mean, + }) + return output + + +def lookup_distribution( + rows: list[dict[str, object]], group_field: str, group_value: str, + metric: str, condition: str, +) -> dict[str, object]: + matches = [ + row for row in rows + if row["group_field"] == group_field and row["group_value"] == group_value + and row["metric"] == metric and row["condition"] == condition + ] + if len(matches) != 1: + raise ValueError(f"expected one distribution row, found {len(matches)}") + return matches[0] + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--reference-root", type=Path, required=True) + parser.add_argument("--candidate-root", type=Path, required=True) + parser.add_argument("--role", default="best_absolute") + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--prefix", required=True) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + + reference_dirs = discover_evaluations(args.reference_root, args.role) + candidate_dirs = discover_evaluations(args.candidate_root, args.role) + reconstruction = {} + temporal = {} + for name, directories in (("reference", reference_dirs), ("candidate", candidate_dirs)): + reconstruction[name] = aggregate_seed_rows({ + seed: read_csv(directory / "per_hand_frame_metrics.csv") + for seed, directory in directories.items() + }, RECONSTRUCTION_KEY, RECONSTRUCTION_METRICS) + temporal[name] = aggregate_seed_rows({ + seed: read_csv(directory / "per_temporal_transition_metrics.csv") + for seed, directory in directories.items() + }, TEMPORAL_KEY, TEMPORAL_METRICS) + assert_pair_alignment( + reconstruction["reference"], reconstruction["candidate"], + RECONSTRUCTION_KEY, RECONSTRUCTION_METADATA, + ) + assert_pair_alignment( + temporal["reference"], temporal["candidate"], + TEMPORAL_KEY, ("take", "frame_id_from", "frame_id_to", "side"), + ) + reconstruction_rows = distribution_rows( + reconstruction["reference"], reconstruction["candidate"], + RECONSTRUCTION_METRICS, require_annotation_valid=True, + ) + temporal_rows = distribution_rows( + temporal["reference"], temporal["candidate"], + TEMPORAL_METRICS, require_annotation_valid=False, + ) + valid_reference = [ + row for row in reconstruction["reference"] if int(row["annotation_valid"]) == 1 + ] + valid_candidate = [ + row for row in reconstruction["candidate"] if int(row["annotation_valid"]) == 1 + ] + group_specs = groups(valid_reference) + paired_rows = paired_take_bootstrap( + valid_reference, valid_candidate, RECONSTRUCTION_METRICS, + group_specs, statistics=("mean",), + bootstrap_samples=args.bootstrap_samples, seed=args.seed, + ) + paired_rows.extend(paired_take_bootstrap( + valid_reference, valid_candidate, ("translation_z_mae_mm",), + group_specs, statistics=("p95", "cvar95"), + bootstrap_samples=args.bootstrap_samples, seed=args.seed + 1, + )) + paired_rows.extend(paired_take_bootstrap( + temporal["reference"], temporal["candidate"], TEMPORAL_METRICS, + [("all", "all"), ("side", "left"), ("side", "right")], + statistics=("mean",), bootstrap_samples=args.bootstrap_samples, + seed=args.seed + 2, + )) + seed_rows = per_seed_deltas(reference_dirs, candidate_dirs) + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / f"{args.prefix}_comparison.csv", reconstruction_rows + temporal_rows) + write_csv(args.output_dir / f"{args.prefix}_paired_take_bootstrap_ci.csv", paired_rows) + write_csv(args.output_dir / f"{args.prefix}_seed_stability.csv", seed_rows) + + def reduction(group_field: str, group_value: str, metric: str, statistic_name: str) -> float: + reference = lookup_distribution( + reconstruction_rows, group_field, group_value, metric, "reference", + )[statistic_name] + candidate = lookup_distribution( + reconstruction_rows, group_field, group_value, metric, "candidate", + )[statistic_name] + return 100.0 * (float(reference) - float(candidate)) / float(reference) + + gate = { + "z_p95_reduction_percent": reduction( + "all", "all", "translation_z_mae_mm", "p95", + ), + "small_absolute_reduction_percent": reduction( + "hand_size_bucket", "small", "absolute_mpjpe_mm", "mean", + ), + } + report = { + "status": "summarized", + "official_test_used": False, + "reference_root": str(args.reference_root.resolve()), + "candidate_root": str(args.candidate_root.resolve()), + "role": args.role, + "seeds": list(SEEDS), + "aggregation": "mean each aligned per-frame error over three seeds before distributions", + "confidence_interval_unit": "paired official-validation take", + "gate_diagnostics": gate, + "outputs": { + "comparison": f"{args.prefix}_comparison.csv", + "paired_take_bootstrap_ci": f"{args.prefix}_paired_take_bootstrap_ci.csv", + "seed_stability": f"{args.prefix}_seed_stability.csv", + }, + } + (args.output_dir / f"{args.prefix}.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_wave0.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_wave0.py new file mode 100644 index 0000000000000000000000000000000000000000..ed3340a99b19f9ae02a56d0a239a6f936d60ab8a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase4_wave0.py @@ -0,0 +1,536 @@ +#!/usr/bin/env python3 +"""Aggregate three frozen Phase 3 references into Phase 4 Wave 0 diagnostics.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +import numpy as np + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.phase4 import find_failure_intervals + + +SEEDS = (20260716, 20260717, 20260718) +MEAN_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "direct_2d_error_px", + "mano_projected_2d_error_px", + "direct_mano_2d_consistency_px", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", + "translation_x_signed_error_mm", + "translation_y_signed_error_mm", + "translation_z_signed_error_mm", +) +STABLE_FIELDS = ( + "clip_index", + "time_index", + "take", + "subject", + "sequence", + "frame_id", + "side", + "annotation_valid", + "annotation_state", + "hand_size_px", + "hand_size_bucket", + "wrist_depth_m", + "depth_bucket", + "action_family", + "action_label", + "action_name", + "bimanual_size_ratio", + "bimanual_depth_gap_m", + "right_minus_left_depth_m", + "bimanual_asymmetry_bucket", + "local_depth_valid_fraction", + "local_depth_validity_bucket", + "local_depth_median_m", + "local_depth_q10_m", + "local_depth_q90_m", + "local_depth_iqr_m", + "local_depth_discontinuity_m", + "local_surface_minus_wrist_z_m", + "target_wrist_x_m", + "target_wrist_y_m", + "target_wrist_z_m", +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_csv(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + return + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(rows[0]) + known = set(fieldnames) + fieldnames.extend(sorted({key for row in rows for key in row} - known)) + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def optional_float(value: object) -> float | None: + if value in (None, ""): + return None + number = float(value) + return number if np.isfinite(number) else None + + +def classify_failure(row: dict[str, Any]) -> str: + if not int(row["annotation_valid"]): + return "annotation_invalid" + wrong_side = optional_float(row.get("wrong_side_preference_mean")) + z_error = float(row["translation_z_mae_mm_mean"]) + root_error = float(row["root_relative_mpjpe_mm_mean"]) + direct_2d = float(row["direct_2d_error_px_mean"]) + conditions = { + "identity": wrong_side is not None and wrong_side >= 0.5, + "z": z_error >= 40.0, + "articulation": root_error >= 30.0, + "localization_2d": direct_2d >= 20.0, + } + active = [name for name, enabled in conditions.items() if enabled] + if not active: + return "nominal" + if active == ["z"]: + return "z_translation_dominant" + if active == ["articulation"]: + return "articulation_dominant" + if active == ["localization_2d"]: + return "localization_2d_dominant" + if active == ["identity"]: + return "identity_assignment" + return "mixed_failure" + + +def aggregate_seed_rows(rows_by_seed: dict[int, list[dict[str, str]]]) -> list[dict[str, Any]]: + reference = rows_by_seed[SEEDS[0]] + for seed in SEEDS[1:]: + rows = rows_by_seed[seed] + if len(rows) != len(reference): + raise ValueError(f"seed {seed} row count differs: {len(rows)} != {len(reference)}") + output: list[dict[str, Any]] = [] + for index, reference_row in enumerate(reference): + row: dict[str, Any] = {field: reference_row.get(field, "") for field in STABLE_FIELDS} + for seed in SEEDS[1:]: + candidate = rows_by_seed[seed][index] + for field in STABLE_FIELDS: + if candidate.get(field, "") != reference_row.get(field, ""): + raise ValueError(f"target field mismatch at row {index}, seed {seed}, {field}") + row["annotation_valid"] = int(reference_row["annotation_valid"]) + row["clip_index"] = int(reference_row["clip_index"]) + row["time_index"] = int(reference_row["time_index"]) + row["frame_id"] = int(reference_row["frame_id"]) + for metric in MEAN_METRICS + ("wrong_side_preference",): + values = [optional_float(rows_by_seed[seed][index].get(metric)) for seed in SEEDS] + finite = np.asarray([value for value in values if value is not None], dtype=np.float64) + row[f"{metric}_mean"] = float(finite.mean()) if finite.size else None + row[f"{metric}_std"] = float(finite.std(ddof=1)) if finite.size > 1 else 0.0 if finite.size else None + row["failure_type"] = classify_failure(row) + output.append(row) + return output + + +def take_side_metrics(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) + for row in rows: + if int(row["annotation_valid"]): + grouped[(str(row["take"]), str(row["side"]))].append(row) + output = [] + for (take, side), items in sorted(grouped.items()): + record: dict[str, Any] = { + "take": take, + "side": side, + "valid_hand_frames": len(items), + "action_family": items[0]["action_family"], + "hand_size_px_mean": np.mean([float(row["hand_size_px"]) for row in items]), + "wrist_depth_m_mean": np.mean([float(row["wrist_depth_m"]) for row in items]), + "local_depth_valid_fraction_mean": np.mean([ + float(row["local_depth_valid_fraction"]) for row in items + if row["local_depth_valid_fraction"] not in (None, "") + ]), + "strong_asymmetry_fraction": np.mean([ + row["bimanual_asymmetry_bucket"] == "strong" for row in items + if row["bimanual_asymmetry_bucket"] not in (None, "") + ]), + } + for metric in ( + "absolute_mpjpe_mm_mean", + "root_relative_mpjpe_mm_mean", + "absolute_mpvpe_mm_mean", + "fingertip_mpjpe_mm_mean", + "direct_2d_error_px_mean", + "mano_projected_2d_error_px_mean", + "translation_x_mae_mm_mean", + "translation_y_mae_mm_mean", + "translation_z_mae_mm_mean", + "translation_z_signed_error_mm_mean", + ): + summary = distribution_summary(row[metric] for row in items) + base = metric.removesuffix("_mean") + record[f"{base}_mean"] = summary["mean"] + record[f"{base}_p95"] = summary["p95"] + record[f"{base}_cvar95"] = summary["cvar95"] + output.append(record) + return output + + +def select_challenge_subset( + rows: list[dict[str, Any]], + *, + seed: int, + target_clips: int = 128, +) -> tuple[list[int], list[dict[str, Any]], dict[str, float]]: + if target_clips < 112: + raise ValueError("challenge subset needs at least 112 clips for failure/control coverage") + valid = [row for row in rows if int(row["annotation_valid"])] + depths = np.asarray([float(row["wrist_depth_m"]) for row in valid], dtype=np.float64) + farthest_observed_threshold = float(np.percentile(depths, 80)) + z_median = float(np.median([row["translation_z_mae_mm_mean"] for row in valid])) + selected: dict[int, dict[str, Any]] = {} + failure_clips: set[int] = set() + + def sample_record(row: dict[str, Any], reason: str) -> dict[str, Any]: + return { + "clip_index": int(row["clip_index"]), + "time_index": int(row["time_index"]), + "take": row["take"], + "frame_id": int(row["frame_id"]), + "side": row["side"], + "action_label": int(row["action_label"]), + "action_name": row["action_name"], + "hand_size_px": float(row["hand_size_px"]), + "wrist_depth_m": float(row["wrist_depth_m"]), + "absolute_mpjpe_mm_mean": float(row["absolute_mpjpe_mm_mean"]), + "translation_z_mae_mm_mean": float(row["translation_z_mae_mm_mean"]), + "reasons": [reason], + } + + def add_failure( + candidates: list[dict[str, Any]], + count: int, + reason: str, + metric: str, + ) -> None: + if count <= 0: + return + ordered = sorted( + candidates, + key=lambda row: (-float(row[metric]), str(row["take"]), int(row["frame_id"]), str(row["side"])), + ) + added = 0 + for row in ordered: + clip_index = int(row["clip_index"]) + if clip_index in selected: + if reason not in selected[clip_index]["reasons"]: + selected[clip_index]["reasons"].append(reason) + continue + selected[clip_index] = sample_record(row, reason) + failure_clips.add(clip_index) + added += 1 + if added >= count: + break + + for side, right_count, left_count in (("right", 12, 0), ("left", 0, 8)): + add_failure( + [row for row in valid if row["side"] == side], + right_count + left_count, + "high_z_error", + "translation_z_mae_mm_mean", + ) + for side in ("left", "right"): + add_failure( + [row for row in valid if row["side"] == side], + 8, + "high_absolute_error", + "absolute_mpjpe_mm_mean", + ) + add_failure([ + row for row in valid + if row["side"] == side + and row["hand_size_bucket"] == "small" + and float(row["wrist_depth_m"]) >= farthest_observed_threshold + ], 6, "farthest_observed_small_hand", "translation_z_mae_mm_mean") + add_failure([ + row for row in valid + if row["side"] == side and row["bimanual_asymmetry_bucket"] == "strong" + ], 6, "strong_bimanual_asymmetry", "translation_z_mae_mm_mean") + add_failure([ + row for row in valid + if row["side"] == side and int(row["action_label"]) != 0 + ], 2, "object_interaction", "absolute_mpjpe_mm_mean") + + for side in ("left", "right"): + side_count = sum(selected[index]["side"] == side for index in failure_clips) + add_failure( + [row for row in valid if row["side"] == side], + max(0, 32 - side_count), + "failure_balance_fill", + "translation_z_mae_mm_mean", + ) + + # Add one ordinary low-z control for every take and side. These 48 clips + # prevent the diagnostic from collapsing onto a few known failure takes. + controls = [row for row in valid if float(row["translation_z_mae_mm_mean"]) <= z_median] + for take in sorted({str(row["take"]) for row in valid}): + for side in ("left", "right"): + candidates = [ + row for row in controls + if row["take"] == take + and row["side"] == side + and int(row["clip_index"]) not in selected + ] + candidates.sort(key=lambda row: ( + abs(float(row["translation_z_mae_mm_mean"]) - z_median), + int(row["frame_id"]), + )) + if candidates: + record = sample_record(candidates[0], "take_side_low_z_control") + selected[int(record["clip_index"])] = record + + challenge_samples = [selected[index] for index in sorted(failure_clips)] + rng = np.random.default_rng(seed) + challenge_order = rng.permutation(len(challenge_samples)) + for challenge_index in challenge_order: + if len(selected) >= target_clips: + break + challenge = challenge_samples[int(challenge_index)] + matches = [ + row for row in controls + if int(row["action_label"]) == int(challenge["action_label"]) + and row["side"] == challenge["side"] + and int(row["clip_index"]) not in selected + ] + if not matches: + continue + matches.sort(key=lambda row: ( + abs(float(row["hand_size_px"]) - float(challenge["hand_size_px"])) + / max(float(challenge["hand_size_px"]), 1.0) + + abs(float(row["wrist_depth_m"]) - float(challenge["wrist_depth_m"])) / 0.1, + str(row["take"]), + int(row["frame_id"]), + )) + match = matches[0] + record = sample_record(match, "same_action_low_z_matched_control") + record["matched_to_clip_index"] = int(challenge["clip_index"]) + selected[int(record["clip_index"])] = record + + if len(selected) < target_clips: + ordinary = sorted( + controls, + key=lambda row: ( + abs(float(row["translation_z_mae_mm_mean"]) - z_median), + int(row["action_label"]), + str(row["side"]), + int(row["clip_index"]), + ), + ) + for row in ordinary: + if len(selected) >= target_clips: + break + clip_index = int(row["clip_index"]) + if clip_index in selected: + continue + selected[clip_index] = sample_record(row, "ordinary_action_matched_fill") + samples = sorted(selected.values(), key=lambda row: int(row["clip_index"])) + return [int(row["clip_index"]) for row in samples], samples, { + "farthest_observed_wrist_depth_p80_m": farthest_observed_threshold, + "reference_z_error_median_mm": z_median, + } + + +def compare_legacy_outputs( + evaluation_root: Path, + checkpoint_index: dict[str, Any], +) -> list[dict[str, Any]]: + records = [] + for run in checkpoint_index["runs"].values(): + seed = int(run["seed"]) + original = Path(run["roles"]["tail_best_absolute"]["evaluation"]).parent + current = evaluation_root / f"seed_{seed}" + original_report = json.loads((original / "evaluation.json").read_text(encoding="utf-8")) + current_report = json.loads((current / "evaluation.json").read_text(encoding="utf-8")) + exact = True + for metric, summary in original_report["metrics"].items(): + for statistic, value in summary.items(): + exact &= current_report["metrics"][metric][statistic] == value + for filename in ("per_hand_frame_metrics.csv", "per_temporal_transition_metrics.csv"): + old_rows = read_csv(original / filename) + new_rows = read_csv(current / filename) + exact &= len(old_rows) == len(new_rows) + if exact: + for old_row, new_row in zip(old_rows, new_rows, strict=True): + exact &= all(new_row[key] == value for key, value in old_row.items()) + records.append({ + "seed": seed, + "checkpoint_sha256": current_report["checkpoint"]["sha256"], + "manifest_sha256": current_report["manifest"]["sha256"], + "clips": current_report["clips"], + "frames": current_report["frames"], + "legacy_outputs_exact": bool(exact), + "source_phase3_evaluation": str(original), + "phase4_evaluation": str(current.resolve()), + }) + if not all(record["legacy_outputs_exact"] for record in records): + raise ValueError("Phase 4 evaluator does not reproduce Phase 3 outputs exactly") + return sorted(records, key=lambda row: int(row["seed"])) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--evaluation-root", + type=Path, + default=Path("artifacts/phase4/wave0/reference_evaluations"), + ) + parser.add_argument( + "--checkpoint-index", + type=Path, + default=Path("artifacts/phase3/reports/long_tail_checkpoints.json"), + ) + parser.add_argument("--output-dir", type=Path, default=Path("artifacts/phase4/reports")) + parser.add_argument( + "--challenge-output", + type=Path, + default=Path("artifacts/phase4/challenge_subset/official_val_challenge_128.json"), + ) + parser.add_argument("--seed", type=int, default=20260716) + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + args.challenge_output.parent.mkdir(parents=True, exist_ok=True) + + checkpoint_index = json.loads(args.checkpoint_index.read_text(encoding="utf-8")) + consistency = compare_legacy_outputs(args.evaluation_root, checkpoint_index) + rows_by_seed = { + seed: read_csv(args.evaluation_root / f"seed_{seed}" / "per_hand_frame_metrics.csv") + for seed in SEEDS + } + aggregated = aggregate_seed_rows(rows_by_seed) + valid = [row for row in aggregated if int(row["annotation_valid"])] + take_rows = take_side_metrics(aggregated) + write_csv(args.output_dir / "take_side_metrics.csv", take_rows) + write_csv(args.output_dir / "failure_taxonomy.csv", aggregated) + + failure_intervals = find_failure_intervals( + [ + {**row, "translation_z_mae_mm": row["translation_z_mae_mm_mean"]} + for row in aggregated + ], + metric="translation_z_mae_mm", + threshold=40.0, + minimum_frames=3, + ) + find_failure_intervals( + [ + {**row, "absolute_mpjpe_mm": row["absolute_mpjpe_mm_mean"]} + for row in aggregated + ], + metric="absolute_mpjpe_mm", + threshold=50.0, + minimum_frames=3, + ) + write_csv(args.output_dir / "wave0_failure_intervals.csv", failure_intervals) + + bootstrap_metrics = tuple(f"{metric}_mean" for metric in MEAN_METRICS[:10]) + bootstrap_rows = bootstrap_take_means( + valid, + bootstrap_metrics, + seed=args.seed, + samples=10_000, + ) + write_csv(args.output_dir / "wave0_reference_take_bootstrap_ci.csv", bootstrap_rows) + + clip_indices, challenge_samples, thresholds = select_challenge_subset( + aggregated, + seed=args.seed, + target_clips=128, + ) + validation_manifest = Path( + json.loads( + (args.evaluation_root / f"seed_{SEEDS[0]}" / "evaluation.json").read_text( + encoding="utf-8" + ) + )["manifest"]["path"] + ) + challenge_manifest = { + "version": "phase4_official_val_challenge_v1", + "seed": args.seed, + "count": len(clip_indices), + "source_manifest": str(validation_manifest), + "source_manifest_sha256": sha256(validation_manifest), + "source_clip_count": 1495, + "dataset_contract": {"resolution_hw": [368, 640], "T": 8, "stride": 1}, + "source_checkpoints": [ + {"seed": record["seed"], "sha256": record["checkpoint_sha256"]} + for record in consistency + ], + "selection_policy": ( + "secondary diagnostic only: high z/absolute error, farthest-observed small hands, " + "strong bimanual asymmetry, object interaction, same-action low-z controls, and " + "ordinary matched fill" + ), + "thresholds": thresholds, + "far_note": ( + "Official validation has no valid wrist z >= 0.8 m. The challenge therefore uses " + "the observed validation wrist-depth P80 and labels it farthest-observed, not far." + ), + "checkpoint_selection_allowed": False, + "training_sampler_use_allowed": False, + "official_test_used": False, + "clip_indices": sorted(clip_indices), + "reason_counts": dict(Counter( + reason for sample in challenge_samples for reason in sample["reasons"] + )), + "samples": challenge_samples, + } + args.challenge_output.write_text( + json.dumps(challenge_manifest, indent=2) + "\n", encoding="utf-8" + ) + write_csv(args.challenge_output.with_suffix(".csv"), challenge_samples) + + taxonomy_counts = Counter(str(row["failure_type"]) for row in aggregated) + report = { + "status": "passed", + "official_test_used": False, + "evaluator_commit": "222b247cbf574faa9c9051832d0d51077df4573c", + "consistency": consistency, + "valid_hand_frames": len(valid), + "failure_taxonomy_counts": dict(taxonomy_counts), + "long_failure_intervals": len(failure_intervals), + "challenge_manifest": str(args.challenge_output.resolve()), + "challenge_manifest_sha256": sha256(args.challenge_output), + "challenge_clips": len(clip_indices), + } + (args.output_dir / "WAVE0_AUDIT.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8" + ) + print(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase7_sequence_cache.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase7_sequence_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee2c43bea6622923c9cf4735cfd8610f5aeae19 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase7_sequence_cache.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Summarize frozen offline/causal sequence caches with static and dynamic metrics.""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.procrustes import aligned_mpjpe_mm +from foundation_hand.models.mano import ManoCameraLayer +from scripts.evaluate_phase4_jitter import ( + condition_grid, filtered_parameters, identity_switch_metrics, load_take, + per_frame_metrics, rebuild_geometry, temporal_metrics, +) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(8 * 1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def validate_manifest(manifest: dict[str, Any], path: Path) -> None: + if ( + manifest.get("status") != "complete" + or manifest.get("split_role") != "official_validation" + or manifest.get("official_validation_used_for_selection") is not False + or manifest.get("official_test_used") is not False + or manifest.get("sequence_mode") not in {"offline", "causal"} + or int(manifest.get("sequence_window", -1)) < 1 + ): + raise ValueError(f"invalid frozen sequence cache manifest: {path}") + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + if not rows: + raise ValueError(f"cannot write empty sequence summary: {path}") + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + + +def aligned_metrics(arrays: dict[str, np.ndarray], joints: np.ndarray) -> dict[str, list[float]]: + values: dict[str, list[float]] = defaultdict(list) + valid = arrays["joint_annotation_valid"].astype(bool) + valid &= arrays["frame_valid"][:, None].astype(bool) + for side in range(2): + indices = np.where(valid[:, side])[0] + if not len(indices): + continue + target = arrays["target_joints_camera"][indices, side] + predicted = joints[indices, side] + values["rigid_se3_mpjpe_mm"].extend(aligned_mpjpe_mm( + predicted, target, estimate_scale=False, + ).tolist()) + values["pa_mpjpe_mm"].extend(aligned_mpjpe_mm( + predicted, target, estimate_scale=True, + ).tolist()) + return values + + +def continuous_take_arrays(arrays: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + """Normalize legacy frame-iterator indices to one continuous take stream.""" + + if str(arrays.get("sequence_mode", "")) not in {"offline", "causal"}: + raise ValueError("take cache is not a bounded sequence-inference cache") + normalized = dict(arrays) + normalized["clip_index"] = np.zeros_like(arrays["frame_id"], dtype=np.int64) + return normalized + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, required=True) + parser.add_argument("--mano-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--gpu", type=int, choices=(0, 1, 2, 3), required=True) + parser.add_argument("--bootstrap-samples", type=int, default=2000) + args = parser.parse_args() + if args.output_dir.exists(): + parser.error("output directory already exists") + manifest_path = args.cache_dir / "cache_manifest.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + validate_manifest(manifest, manifest_path) + args.output_dir.mkdir(parents=True) + device = torch.device(f"cuda:{args.gpu}") + mano = ManoCameraLayer(args.mano_root).to(device).eval() + condition = condition_grid()["F0_raw"] + global_values: dict[str, list[float]] = defaultdict(list) + take_rows: list[dict[str, Any]] = [] + for take_record in manifest["takes"]: + path = Path(take_record["path"]) + if sha256(path) != take_record["sha256"]: + raise ValueError(f"take cache hash mismatch: {path}") + arrays = continuous_take_arrays(load_take(path)) + translation, rotations, _ = filtered_parameters(arrays, condition) + vertices, joints = rebuild_geometry( + rotations, arrays["pred_shape"].astype(np.float32), translation, + mano, device, + ) + selected = arrays["frame_valid"].astype(bool) + metrics, projected, _ = per_frame_metrics( + arrays, joints, vertices, rotations, translation, selected, + ) + for metric, observations in temporal_metrics( + arrays, joints, projected, selected, + ).items(): + metrics[metric].extend(observations) + for metric, observations in identity_switch_metrics( + arrays, joints, selected, + ).items(): + metrics[metric].extend(observations) + for metric, observations in aligned_metrics(arrays, joints).items(): + metrics[metric].extend(observations) + row: dict[str, Any] = {"take": str(arrays["take"]), "frames": len(joints)} + for metric, observations in metrics.items(): + global_values[metric].extend(observations) + summary = distribution_summary(observations) + row[metric] = summary["mean"] + row[f"{metric}_p95"] = summary["p95"] + take_rows.append(row) + all_fields = sorted({key for row in take_rows for key in row}) + normalized_rows = [{key: row.get(key) for key in all_fields} for row in take_rows] + write_csv(args.output_dir / "take_metrics.csv", normalized_rows) + metric_rows = [ + {"metric": metric, **distribution_summary(observations)} + for metric, observations in sorted(global_values.items()) + ] + write_csv(args.output_dir / "metrics.csv", metric_rows) + metric_names = sorted(global_values) + bootstrap = bootstrap_take_means( + take_rows, metric_names, seed=20260717, samples=args.bootstrap_samples, + ) + write_csv(args.output_dir / "take_bootstrap_ci.csv", bootstrap) + report = { + "status": "evaluated_frozen_sequence_cache", + "sequence_mode": manifest["sequence_mode"], + "causal": manifest["sequence_mode"] == "causal", + "window": manifest["sequence_window"], + "offline_stride": manifest.get("offline_stride"), + "frames": manifest["frames"], "takes": len(manifest["takes"]), + "metrics": {row["metric"]: { + key: value for key, value in row.items() if key != "metric" + } for row in metric_rows}, + "cache_manifest": {"path": str(manifest_path.resolve()), "sha256": sha256(manifest_path)}, + "checkpoint": manifest["checkpoint"], "config": manifest["config"], + "bounded_memory": { + "maximum_gpu_window_frames": manifest["maximum_gpu_window_frames"], + "maximum_cpu_input_buffer_frames": manifest["maximum_cpu_input_buffer_frames"], + }, + "take_metrics": "take_metrics.csv", "take_bootstrap_ci": "take_bootstrap_ci.csv", + "official_validation_used_for_selection": False, "official_test_used": False, + } + (args.output_dir / "evaluation.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "status": report["status"], "mode": report["sequence_mode"], + "absolute_mpjpe_mm": report["metrics"]["absolute_mpjpe_mm"]["mean"], + "output": str(args.output_dir), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase8_cross_domain_matrix.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase8_cross_domain_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec718b00fb86cb246600b0fafc8acaeb0e86941 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase8_cross_domain_matrix.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Summarize a frozen external cross-domain matrix without frame weighting.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +METRICS = ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", "rigid_se3_mpjpe_mm", + "pa_mpjpe_mm", "mpvpe_mm", "fingertip_mpjpe_mm", + "projected_mano_2d_error_px", "translation_x_mae_mm", + "translation_y_mae_mm", "translation_z_mae_mm", +) + + +def metric_mean(report: dict[str, Any], metric: str) -> float: + value = report.get("metrics", {}).get(metric) + if not isinstance(value, dict) or value.get("mean") is None: + return math.nan + return float(value["mean"]) + + +def summarize(manifest: Path, output_dir: Path) -> dict[str, Any]: + specification = json.loads(manifest.read_text(encoding="utf-8")) + if specification.get("official_test_used") is not False: + raise ValueError("matrix manifest must set official_test_used=false") + entries = specification.get("entries", []) + if not entries: + raise ValueError("matrix manifest is empty") + if output_dir.exists() and any(output_dir.iterdir()): + raise ValueError("output directory must be new or empty") + output_dir.mkdir(parents=True, exist_ok=True) + rows: list[dict[str, Any]] = [] + checkpoint_by_condition: dict[str, str] = {} + seen: set[tuple[str, str]] = set() + for entry in entries: + condition, dataset = str(entry["condition"]), str(entry["dataset"]) + key = (condition, dataset) + if key in seen: + raise ValueError(f"duplicate matrix cell: {condition}/{dataset}") + seen.add(key) + path = Path(entry["evaluation"]) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("evaluation_role") != "external_heldout" + or report.get("h2o_training_data_used") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"non-external or non-frozen matrix result: {path}") + checkpoint_sha = str(report["checkpoint"]["sha256"]) + prior = checkpoint_by_condition.setdefault(condition, checkpoint_sha) + if prior != checkpoint_sha: + raise ValueError(f"condition uses multiple checkpoints: {condition}") + row: dict[str, Any] = { + "condition": condition, "dataset": dataset, + "checkpoint_step": int(report["checkpoint_step"]), + "checkpoint_sha256": checkpoint_sha, + "input_mode": report["input_mode"], + "clips": int(report["clips"]), "frames": int(report["frames"]), + "evaluation": str(path.resolve()), + } + coverage = report.get("metrics", {}).get("supervision_coverage") + if not isinstance(coverage, dict): + raise ValueError(f"matrix result lacks supervision coverage: {path}") + for scope in ("overall", "left", "right"): + scoped = coverage.get(scope) + if not isinstance(scoped, dict): + raise ValueError(f"matrix result lacks {scope} supervision coverage: {path}") + for supervision in ("joint3d", "translation", "vertices"): + key = f"{supervision}_valid_fraction" + if scoped.get(key) is None: + raise ValueError(f"matrix result lacks {scope}/{key}: {path}") + row[f"{scope}_{key}"] = float(scoped[key]) + row.update({metric: metric_mean(report, metric) for metric in METRICS}) + z_summary = report.get("metrics", {}).get("translation_z_mae_mm") or {} + row["translation_z_p95_mm"] = float(z_summary.get("p95", math.nan)) + rows.append(row) + conditions = sorted({row["condition"] for row in rows}) + datasets = sorted({row["dataset"] for row in rows}) + expected = {(condition, dataset) for condition in conditions for dataset in datasets} + if seen != expected: + missing = sorted(expected - seen) + raise ValueError(f"cross-domain matrix is incomplete: {missing}") + + ranks: dict[str, dict[str, float]] = {condition: {} for condition in conditions} + for dataset in datasets: + selected = sorted( + (row for row in rows if row["dataset"] == dataset), + key=lambda row: row["absolute_mpjpe_mm"], + ) + for rank, row in enumerate(selected, 1): + ranks[row["condition"]][dataset] = float(rank) + mean_rank = { + condition: sum(ranks[condition].values()) / len(datasets) + for condition in conditions + } + absolute = { + condition: { + row["dataset"]: row["absolute_mpjpe_mm"] + for row in rows if row["condition"] == condition + } + for condition in conditions + } + pareto = [] + for condition in conditions: + dominated = any( + other != condition + and all(absolute[other][dataset] <= absolute[condition][dataset] for dataset in datasets) + and any(absolute[other][dataset] < absolute[condition][dataset] for dataset in datasets) + for other in conditions + ) + if not dominated: + pareto.append(condition) + + csv_path = output_dir / "cross_domain_matrix.csv" + with csv_path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader(); writer.writerows(rows) + report = { + "status": "complete", "selection": "dataset_macro_mean_rank", + "conditions": conditions, "datasets": datasets, + "dataset_ranks": ranks, "mean_rank": mean_rank, + "pareto_frontier": pareto, "rows": rows, + "official_test_used": False, + } + (output_dir / "summary.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8", + ) + return report + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + try: + result = summarize(args.manifest, args.output_dir) + except ValueError as error: + parser.error(str(error)) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase8_egodexter.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase8_egodexter.py new file mode 100644 index 0000000000000000000000000000000000000000..20bc81db0816cfd08d32c419fc3c157447dbb500 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase8_egodexter.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Summarize the complete frozen Phase 8 EgoDexter zero-shot grid.""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +from typing import Any + +from scripts.evaluate_phase7_egodexter_zero_shot import sha256 + + +def summarize(queue_paths: list[Path]) -> dict[str, Any]: + rows = [] + model_ids: set[str] = set() + for queue_path in queue_paths: + queue = json.loads(queue_path.read_text(encoding="utf-8")) + if ( + queue.get("egodexter_used_for_training_or_selection") is not False + or queue.get("official_test_used") is not False + ): + raise ValueError("EgoDexter queue boundary flags are invalid") + model_ids.add(queue["model_id"]) + for item in queue["evaluations"]: + report_path = Path(item["output_dir"]) / "evaluation.json" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_frozen_egodexter_zero_shot" + or report.get("model_id") != item["model_id"] + or report.get("input_mode") != item["input_mode"] + or report.get("inference_mode") != item["inference_mode"] + or report.get("checkpoint", {}).get("sha256") != item["checkpoint_sha256"] + or report.get("egodexter_used_for_training_or_selection") is not False + or report.get("official_test_used") is not False + ): + raise ValueError(f"invalid EgoDexter report: {report_path}") + for artifact in ("per_fingertip_rows", "raw_predictions"): + record = report[artifact] + path = Path(record["path"]) + if not path.is_file() or sha256(path) != record["sha256"]: + raise ValueError(f"EgoDexter {artifact} is missing or differs") + metric = report["fingertip_error_mm"] + rows.append({ + "model_id": item["model_id"], + "inference_mode": item["inference_mode"], + "input_mode": item["input_mode"], + "mean_fingertip_mm": metric["mean"], + "median_fingertip_mm": metric["median"], + "p95_fingertip_mm": metric["p95"], + "visible_fingertips": report["visible_fingertips"], + "coverage_fraction": report["coverage_fraction"], + "frames": report["frames"], + "fps": report["runtime"]["frames_per_second"], + "peak_vram_gib": report["runtime"]["peak_vram_gib"], + "maximum_gpu_window_frames": report["runtime"]["maximum_gpu_window_frames"], + "maximum_cpu_input_buffer_frames": report["runtime"]["maximum_cpu_input_buffer_frames"], + "per_finger": report["per_finger"], + "per_sequence": report["per_sequence"], + "evaluation": str(report_path.resolve()), + "evaluation_sha256": sha256(report_path), + }) + expected = len(model_ids) * 6 + identities = { + (row["model_id"], row["inference_mode"], row["input_mode"]) + for row in rows + } + if len(rows) != expected or len(identities) != expected: + raise ValueError("EgoDexter summary is not a complete unique grid") + return { + "schema_version": "phase8_egodexter_summary_v1", + "status": "complete_frozen_zero_shot", + "models": sorted(model_ids), + "conditions": rows, + "selection_use": False, + "egodexter_used_for_training_or_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--queue", action="append", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("summary outputs must not exist") + try: + result = summarize(args.queue) + except (KeyError, OSError, ValueError, json.JSONDecodeError) as error: + parser.error(str(error)) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + csv_fields = [ + "model_id", "inference_mode", "input_mode", "mean_fingertip_mm", + "median_fingertip_mm", "p95_fingertip_mm", "visible_fingertips", + "coverage_fraction", "frames", "fps", "peak_vram_gib", + "maximum_gpu_window_frames", "maximum_cpu_input_buffer_frames", + "evaluation", "evaluation_sha256", + ] + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=csv_fields, lineterminator="\n") + writer.writeheader() + writer.writerows({key: row[key] for key in csv_fields} for row in result["conditions"]) + print(json.dumps({"status": result["status"], "conditions": len(result["conditions"])}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_final_deployment.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_final_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..8a16fb5023edce3600880e38c45f2309e30f30c8 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_final_deployment.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Summarize formal H2O disclosure and the final deployment contract.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.run_phase9_final_deployment_worker import completed_matches +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def mean_metric(report: dict[str, Any], name: str) -> float: + value = report["metrics"][name] + return float(value["mean"] if isinstance(value, dict) else value) + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + jobs = {job["id"]: job for job in plan["jobs"]} + if len(jobs) != 11 or any(not completed_matches(job) for job in jobs.values()): + raise ValueError("final deployment jobs are not complete and bound") + formal = {} + formal_gpu_hours = 0.0 + for mode in plan["formal_validation_modes"]: + job = jobs[f"formal_{mode}"] + path = Path(job["output_dir"]) / "evaluation.json" + report = read_json(path) + formal_gpu_hours += float(report["runtime"]["wall_seconds"]) / 3600.0 + formal[mode] = { + "report": {"path": str(path.resolve()), "sha256": sha256(path)}, + "absolute_mpjpe_mm": mean_metric(report, "absolute_mpjpe_mm"), + "root_relative_mpjpe_mm": mean_metric(report, "root_relative_mpjpe_mm"), + "fingertip_mpjpe_mm": mean_metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": float( + report["metrics"]["translation_z_mae_mm"]["p95"] + ), + "frames": int(report["frames"]), + "peak_vram_gib": float(report["runtime"]["peak_vram_gib"]), + } + variable_job = jobs["variable_length"] + variable_path = Path(variable_job["output"]) + variable = read_json(variable_path) + sequence = {} + for mode in ("offline", "causal"): + sequence[mode] = {} + for frames in plan["sequence_contract"]["ordering_lengths"]: + job = jobs[f"{mode}_w8_{frames}"] + path = Path(job["output"]) + report = read_json(path) + sequence[mode][str(frames)] = { + "report": {"path": str(path.resolve()), "sha256": sha256(path)}, + "throughput_fps": float(report["throughput_fps"]), + "peak_allocated_gib": float(report["peak_allocated_gib"]), + "maximum_gpu_window_frames": int(report["maximum_gpu_window_frames"]), + "maximum_cpu_input_buffer_frames": int( + report["maximum_cpu_input_buffer_frames"] + ), + "invariance": report.get("invariance"), + } + profile_path = Path(jobs["latency_vram"]["output"]) + profile = read_json(profile_path) + attempts = [] + total_gpu_seconds = 0.0 + for worker in plan["workers"]: + state_path = Path(worker["state"]) + state = read_json(state_path) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != sha256(plan_path) + or state.get("official_test_used") is not False + ): + raise ValueError(f"final deployment worker state differs: {worker['id']}") + for attempt in state.get("attempts", []): + start = datetime.fromisoformat(attempt["start_utc"]) + end = datetime.fromisoformat(attempt["end_utc"]) + seconds = (end - start).total_seconds() + if seconds < 0: + raise ValueError("final deployment attempt duration is negative") + total_gpu_seconds += seconds + attempts.append({ + "worker": worker["id"], "id": attempt["id"], + "kind": attempt["kind"], "physical_gpu_id": attempt["physical_gpu_id"], + "start_utc": attempt["start_utc"], "end_utc": attempt["end_utc"], + "returncode": attempt["returncode"], + "gpu_hours": seconds / 3600.0, + "archived_incomplete_output": attempt.get("archived_incomplete_output"), + }) + return { + "schema_version": "phase9_final_deployment_summary_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "final_checkpoint_deployment_contract_passed", + "winner": plan["winner"], + "selected_mechanism": plan["selected_mechanism"], + "resolution_hw": plan["resolution_hw"], + "shared_augmentation": plan["shared_augmentation"], + "checkpoint": plan["checkpoint"], "config": plan["config"], + "formal_h2o_validation": formal, + "formal_h2o_validation_checkpoint_count": 1, + "formal_h2o_validation_gpu_hours": formal_gpu_hours, + "formal_h2o_validation_used_for_selection": False, + "variable_length": { + "report": {"path": str(variable_path.resolve()), "sha256": sha256(variable_path)}, + "lengths": [item["T"] for item in variable["forward_results"]], + "all_finite": all(item["all_finite"] for item in variable["forward_results"]), + }, + "sequence_inference": sequence, + "latency_vram": { + "report": {"path": str(profile_path.resolve()), "sha256": sha256(profile_path)}, + "latency": profile["latency"], + "peak_allocated_vram_gib": profile["peak_allocated_vram_gib"], + "supported_operator_flops_per_clip": profile[ + "supported_operator_flops_per_clip" + ], + }, + "deployment_attempts": attempts, + "deployment_total_gpu_hours": total_gpu_seconds / 3600.0, + "recovery_disclosure": [ + attempt for attempt in attempts + if attempt["returncode"] != 0 + or attempt["archived_incomplete_output"] is not None + ], + "deployment_contract": { + "t_1_2_4_8_16_32_64": True, + "offline_overlap_w8_31_64_257": True, + "causal_rolling_w8_31_64_257": True, + "future_prefix_invariance": True, + "bounded_memory": True, + "fresh_resolution_latency_vram": True, + "passed": True, + }, + "selection_mutated_after_formal_validation": False, + "h2o_official_validation_used": True, + "h2o_official_validation_used_for_selection": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + result = summarize(args.plan) + if args.output.exists(): + existing = read_json(args.output) + for key in ("created_utc",): + existing.pop(key, None) + result.pop(key, None) + if existing != result: + raise ValueError("existing final deployment summary differs") + else: + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(read_json(args.output), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_hot_scale.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_hot_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..ed40258b5b96d9a269aa993872a60e029faed81f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_hot_scale.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Summarize the matched Phase 9 HOT unique-coverage experiment.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + +from scripts.select_phase7_external_continuation import paired_take_bootstrap + + +METRICS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "pa_mpjpe_mm": ("pa_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_x_mae_mm": ("translation_x_mae_mm", "mean"), + "translation_y_mae_mm": ("translation_y_mae_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} + + +def load_evaluation(path: Path) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(path) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated_phase9_external_heldout" + or report.get("evaluation_role") != "phase9_external_heldout" + or report.get("h2o_training_data_used") is not True + or report.get("official_test_used") is not False + ): + raise ValueError(f"evaluation role/isolation mismatch: {path}") + return report + + +def scalar(report: dict[str, Any], metric: str, statistic: str) -> float: + value = float(report["metrics"][metric][statistic]) + if not math.isfinite(value): + raise ValueError(f"non-finite {metric}.{statistic}") + return value + + +def result_row( + condition: str, unique_clips: int, source_id: str, report: dict[str, Any], +) -> dict[str, Any]: + metrics = { + output: scalar(report, metric, statistic) + for output, (metric, statistic) in METRICS.items() + } + for name in ("aria", "quest3"): + bucket = report["metrics"].get(f"bucket_headset_{name}") + metrics[f"{name}_absolute_mpjpe_mm"] = ( + None if not bucket else float(bucket["absolute_mpjpe_mm"]["mean"]) + ) + return { + "condition": condition, + "hot_unique_clips": unique_clips, + "source_id": source_id, + "checkpoint": report["checkpoint"], + "metrics": metrics, + } + + +def summarize( + registry: dict[str, Any], evaluation_root: Path, control_root: Path, +) -> dict[str, Any]: + if registry.get("official_test_used") is not False: + raise ValueError("registry must explicitly exclude official test") + clip_counts = {"J40_HOT10K": 10_000, "J40_HOT50K": 50_000} + rows: list[dict[str, Any]] = [] + checkpoint_hashes: dict[str, str] = {} + for condition in registry["conditions"]: + condition_id = str(condition["condition"]) + if condition_id not in clip_counts: + continue + hashes = set() + for source in registry["sources"]: + source_id = str(source["id"]) + report = load_evaluation( + evaluation_root / condition_id / "final505k" / source_id + / "evaluation.json" + ) + if report["cache_manifest"]["sha256"] != source["cache_manifest_sha256"]: + raise ValueError(f"manifest hash mismatch: {condition_id}/{source_id}") + hashes.add(str(report["checkpoint"]["sha256"])) + rows.append(result_row( + condition_id, clip_counts[condition_id], source_id, report, + )) + if len(hashes) != 1: + raise ValueError(f"condition uses multiple checkpoints: {condition_id}") + checkpoint_hashes[condition_id] = hashes.pop() + + control_id = "J40_HOT100K" + hashes = set() + for source in registry["sources"]: + source_id = str(source["id"]) + report = load_evaluation(control_root / source_id / "evaluation.json") + if report["cache_manifest"]["sha256"] != source["cache_manifest_sha256"]: + raise ValueError(f"control manifest hash mismatch: {source_id}") + hashes.add(str(report["checkpoint"]["sha256"])) + rows.append(result_row(control_id, 100_000, source_id, report)) + if len(hashes) != 1: + raise ValueError("HOT100K control uses multiple checkpoints") + checkpoint_hashes[control_id] = hashes.pop() + + controls = { + row["source_id"]: row for row in rows if row["condition"] == control_id + } + for row in rows: + control = controls[row["source_id"]] + row["delta_vs_hot100k"] = { + metric: ( + None if value is None or control["metrics"][metric] is None + else value - control["metrics"][metric] + ) + for metric, value in row["metrics"].items() + } + paired: dict[str, dict[str, dict[str, Any]]] = {} + for condition_id in clip_counts: + paired[condition_id] = {} + for source in registry["sources"]: + source_id = str(source["id"]) + candidate_dir = evaluation_root / condition_id / "final505k" / source_id + reference_dir = control_root / source_id + paired[condition_id][source_id] = { + metric: paired_take_bootstrap( + reference_dir / "take_metrics.csv", + candidate_dir / "take_metrics.csv", + metric, seed=20260717, resamples=2000, + ) + for metric in ( + "absolute_mpjpe_mm", "root_relative_mpjpe_mm", + "fingertip_mpjpe_mm", "translation_z_mae_mm", + ) + } + paired[condition_id][source_id]["translation_z_p95_mm"] = ( + paired_take_bootstrap( + reference_dir / "per_hand_frame_metrics.csv", + candidate_dir / "per_hand_frame_metrics.csv", + "translation_z_mae_mm", seed=20260717, resamples=2000, + statistic="p95", + ) + ) + return { + "schema_version": "phase9_hot_unique_scale_summary_v1", + "status": "complete", + "comparison": "matched_J40_final505k_source_exposure", + "checkpoint_sha256": checkpoint_hashes, + "rows": rows, + "paired_recording_bootstrap_vs_hot100k": paired, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--evaluation-root", type=Path, required=True) + parser.add_argument("--control-root", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("summary outputs must be new") + result = summarize( + json.loads(args.registry.read_text(encoding="utf-8")), + args.evaluation_root, args.control_root, + ) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + args.output_json.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + fields = [ + "condition", "hot_unique_clips", "source_id", "checkpoint_sha256", + *METRICS, "aria_absolute_mpjpe_mm", "quest3_absolute_mpjpe_mm", + *[f"delta_{metric}" for metric in METRICS], + ] + with args.output_csv.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for row in result["rows"]: + writer.writerow({ + "condition": row["condition"], + "hot_unique_clips": row["hot_unique_clips"], + "source_id": row["source_id"], + "checkpoint_sha256": row["checkpoint"]["sha256"], + **row["metrics"], + **{ + f"delta_{metric}": row["delta_vs_hot100k"][metric] + for metric in METRICS + }, + }) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_last2_decision.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_last2_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..0c773ab0e98bd5e250e22c0e2fbd1ae392be8b95 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_last2_decision.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Apply the strict macro-and-worst gate to one last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.summarize_phase9_resolution_decision import ( + NATIVE_EXTERNAL, + checked_report, + h2o_guardrails, + metric, +) + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def strict_gate( + control_domains: dict[str, float], candidate_domains: dict[str, float], +) -> dict[str, Any]: + if set(control_domains) != {"h2o", "hot3d", "hoi4d", "arctic"}: + raise ValueError("last-2 control domains differ") + if set(candidate_domains) != set(control_domains): + raise ValueError("last-2 candidate domains differ") + control_macro = sum(control_domains.values()) / 4 + candidate_macro = sum(candidate_domains.values()) / 4 + control_worst = max(control_domains.values()) + candidate_worst = max(candidate_domains.values()) + macro = candidate_macro < control_macro + worst = candidate_worst < control_worst + return { + "control_macro_absolute_mm": control_macro, + "candidate_macro_absolute_mm": candidate_macro, + "macro_delta_mm": candidate_macro - control_macro, + "macro_strictly_improved": macro, + "control_worst_domain_absolute_mm": control_worst, + "candidate_worst_domain_absolute_mm": candidate_worst, + "worst_domain_delta_mm": candidate_worst - control_worst, + "worst_domain_strictly_improved": worst, + "accepted": macro and worst, + } + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if len(evaluations) != 25: + raise ValueError("last-2 evaluation count differs") + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"last-2 evaluation incomplete: {item['id']}") + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + control_reports = {} + for identifier, item in plan["control_reports"].items(): + path = Path(item["path"]) + if not path.is_file() or item["sha256"] != sha256(path): + raise ValueError(f"last-2 control report hash differs: {identifier}") + control_reports[identifier] = checked_report( + path, item["evaluation_role"], item["input_mode"], + ) + control_external = { + dataset: control_reports[f"full_{dataset}_{mode}"] + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = { + (fold, mode): control_reports[f"{fold}_{mode}"] + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + gate = strict_gate(control_domains, candidate_domains) + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + candidate = plan["candidate"] + return { + "schema_version": "phase9_last2_candidate_decision_v1", + "status": "complete", "candidate": candidate, + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": ( + f"accept_last2_{candidate}" if gate["accepted"] + else f"reject_last2_{candidate}" + ), + "backbone_learning_rate": plan["backbone_learning_rate"], + "resolution_hw": plan["resolution_hw"], + "shared_augmentation": plan["shared_augmentation"], + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "control_evaluation_plan": plan["control_evaluation_plan"], + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "dino_large_admitted": False, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("last-2 candidate decision output must be new") + result = summarize(args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_resolution_decision.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_resolution_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..0341ee8e004ae8b5d4fc699ded58fb19dfec1eab --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_resolution_decision.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Apply the frozen Stage 7 resolution gate and report all guardrails.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +FOLDS = ( + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", +) +NATIVE_EXTERNAL = { + "hot3d": "rgb_k", "hoi4d": "rgb_d_k", "arctic": "rgb_k", +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def checked_report(path: Path, role: str, mode: str) -> dict[str, Any]: + report = read_json(path) + if ( + report.get("status") != f"evaluated_{role}" + or report.get("evaluation_role") != role + or report.get("input_mode") != mode + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution decision input differs: {path}") + return report + + +def metric(report: dict[str, Any], name: str, statistic: str = "mean") -> float: + value = report.get("metrics", {}).get(name, {}).get(statistic) + if value is None or not math.isfinite(float(value)): + raise ValueError(f"missing finite metric {name}.{statistic}") + return float(value) + + +def h2o_guardrails(reports: dict[tuple[str, str], dict[str, Any]]) -> dict[str, Any]: + result = {} + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + selected = [reports[(fold, mode)] for fold in FOLDS] + absolute = [metric(report, "absolute_mpjpe_mm") for report in selected] + root = [metric(report, "root_relative_mpjpe_mm") for report in selected] + fingertip = [metric(report, "fingertip_mpjpe_mm") for report in selected] + z_tail = [ + metric(report, "translation_z_mae_mm", "p95") for report in selected + ] + result[mode] = { + "absolute_macro_mm": sum(absolute) / len(absolute), + "absolute_worst_fold_mm": max(absolute), + "root_relative_macro_mm": sum(root) / len(root), + "fingertip_macro_mm": sum(fingertip) / len(fingertip), + "translation_z_p95_macro_mm": sum(z_tail) / len(z_tail), + "translation_z_p95_worst_fold_mm": max(z_tail), + "fold_absolute_mm": dict(zip(FOLDS, absolute, strict=True)), + } + return result + + +def gate_decision( + control_domains: dict[str, float], candidate_domains: dict[str, float], + relative_limit: float, +) -> dict[str, Any]: + if set(control_domains) != {"h2o", "hot3d", "hoi4d", "arctic"}: + raise ValueError("resolution control domains differ") + if set(candidate_domains) != set(control_domains): + raise ValueError("resolution candidate domains differ") + control_macro = sum(control_domains.values()) / 4 + candidate_macro = sum(candidate_domains.values()) / 4 + control_worst = max(control_domains.values()) + candidate_worst = max(candidate_domains.values()) + worst_relative_regression = (candidate_worst - control_worst) / control_worst + macro_improved = candidate_macro < control_macro + worst_passed = worst_relative_regression <= relative_limit + return { + "control_macro_absolute_mm": control_macro, + "candidate_macro_absolute_mm": candidate_macro, + "macro_delta_mm": candidate_macro - control_macro, + "macro_strictly_improved": macro_improved, + "control_worst_domain_absolute_mm": control_worst, + "candidate_worst_domain_absolute_mm": candidate_worst, + "worst_domain_relative_regression": worst_relative_regression, + "worst_domain_relative_regression_limit": relative_limit, + "worst_domain_gate_passed": worst_passed, + "accepted": macro_improved and worst_passed, + } + + +def summarize( + plan_path: Path, control_external_root: Path, + control_fold_final_root: Path, control_fold_milestone_root: Path, +) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"resolution evaluation is incomplete: {item['id']}") + + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + + control = plan["control_evidence"] + mixture = control["mixture"] + external_id = control["external_checkpoint_id"] + fold_id = control["fold_checkpoint_id"] + control_external = { + dataset: checked_report( + control_external_root / mixture / external_id + / f"{dataset}_{mode}" / "evaluation.json", + "phase9_external_heldout", mode, + ) + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = {} + for fold in FOLDS: + condition = f"{mixture}_{fold}" + for mode in ("rgb_d_k", "rgb_k", "rgb_only"): + path = ( + control_fold_final_root / condition / mode / "evaluation.json" + if fold_id == "final" + else control_fold_milestone_root / condition / fold_id + / mode / "evaluation.json" + ) + control_h2o_reports[(fold, mode)] = checked_report( + path, "phase9_h2o_fold_heldout", mode, + ) + + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + for dataset, expected in control["absolute_mm"].items(): + if not math.isclose(control_domains[dataset], float(expected), abs_tol=1e-8): + raise ValueError(f"resolution control evidence differs: {dataset}") + gate = gate_decision( + control_domains, candidate_domains, + float(plan["gate"]["worst_domain_relative_regression_limit"]), + ) + + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + return { + "schema_version": "phase9_resolution_decision_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "accept_896x512" if gate["accepted"] else "retain_640x368", + "accepted_resolution_hw": [512, 896] if gate["accepted"] else [368, 640], + "control_resolution_hw": [368, 640], + "candidate_resolution_hw": [512, 896], + "winner": plan["winner"], + "control_checkpoint": plan["winner_checkpoint"], + "candidate_full_checkpoint": { + "path": plan["training_jobs"]["full"]["checkpoint"], + "sha256": plan["training_jobs"]["full"]["checkpoint_sha256"], + }, + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--control-external-root", type=Path, required=True) + parser.add_argument("--control-fold-final-root", type=Path, required=True) + parser.add_argument("--control-fold-milestone-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("resolution decision output must be new") + result = summarize( + args.plan, args.control_external_root, args.control_fold_final_root, + args.control_fold_milestone_root, + ) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_resolution_evaluation_metrics.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_resolution_evaluation_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc33c1d7f19286e4dc4a9a36f79f012afae244c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_resolution_evaluation_metrics.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +"""Write the complete paired 640/896 Stage 7 metric inventory.""" + +from __future__ import annotations + +import argparse +import csv +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +FIELDS = { + "absolute_mpjpe_mm": ("absolute_mpjpe_mm", "mean"), + "root_relative_mpjpe_mm": ("root_relative_mpjpe_mm", "mean"), + "pa_mpjpe_mm": ("pa_mpjpe_mm", "mean"), + "mpvpe_mm": ("mpvpe_mm", "mean"), + "fingertip_mpjpe_mm": ("fingertip_mpjpe_mm", "mean"), + "translation_x_mae_mm": ("translation_x_mae_mm", "mean"), + "translation_y_mae_mm": ("translation_y_mae_mm", "mean"), + "translation_z_mae_mm": ("translation_z_mae_mm", "mean"), + "translation_z_p95_mm": ("translation_z_mae_mm", "p95"), +} + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def metric_values(report: dict[str, Any]) -> dict[str, float]: + result = {} + for label, (metric, statistic) in FIELDS.items(): + value = report.get("metrics", {}).get(metric, {}).get(statistic) + if not isinstance(value, (int, float)) or not math.isfinite(float(value)): + raise ValueError(f"resolution metric is missing or nonfinite: {label}") + result[label] = float(value) + return result + + +def control_path(plan: dict[str, Any], item: dict[str, Any], identifier: str) -> Path: + control = plan["control_evidence"] + mixture = control["mixture"] + if identifier.startswith("full_"): + name = identifier.removeprefix("full_") + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/external_milestones") + / mixture / control["external_checkpoint_id"] / name / "evaluation.json" + ) + fold = item["training_role"] + mode = item["input_mode"] + condition = f"{mixture}_{fold}" + if control["fold_checkpoint_id"] == "final": + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold") + / condition / mode / "evaluation.json" + ) + return ( + Path("/SSD3/jiasen/foundation_hand/phase9_artifacts/evaluations/h2o_multifold_milestones") + / condition / control["fold_checkpoint_id"] / mode / "evaluation.json" + ) + + +def checked_report(path: Path, item: dict[str, Any]) -> dict[str, Any]: + report = read_json(path) + if ( + report.get("status") != f"evaluated_{item['evaluation_role']}" + or report.get("evaluation_role") != item["evaluation_role"] + or report.get("input_mode") != item["input_mode"] + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"resolution paired report binding differs: {path}") + return report + + +def hot_headsets(report: dict[str, Any]) -> dict[str, Any]: + result = {} + for headset in ("aria", "quest3"): + metrics = report.get("metrics", {}).get(f"bucket_headset_{headset}", {}) + result[headset] = { + key: float(metrics[source][statistic]) + for key, (source, statistic) in FIELDS.items() + if source in metrics and statistic in metrics[source] + } + return result + + +def summarize(plan_path: Path, decision_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + decision = read_json(decision_path) + if ( + decision.get("status") != "complete" + or decision.get("evaluation_plan", {}).get("sha256") != sha256(plan_path) + or decision.get("official_test_used") is not False + or decision.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution decision binding differs") + owners = { + identifier: worker["owner"] + for worker in plan["workers"] for identifier in worker["evaluation_ids"] + } + rows = [] + for item in plan["evaluations"]: + if not evaluation_complete(item): + raise ValueError(f"resolution evaluation is incomplete: {item['id']}") + candidate_path = Path(item["output_dir"]) / "evaluation.json" + candidate = checked_report(candidate_path, item) + baseline_path = control_path(plan, item, item["id"]) + baseline = checked_report(baseline_path, item) + candidate_metrics = metric_values(candidate) + baseline_metrics = metric_values(baseline) + row = { + "evaluation_id": item["id"], "owner": owners[item["id"]], + "training_role": item["training_role"], "input_mode": item["input_mode"], + "evaluation_role": item["evaluation_role"], + "checkpoint_sha256": item["checkpoint_sha256"], + "config_sha256": item["config_sha256"], + "cache_manifest_sha256": item["cache_manifest_sha256"], + "clips": candidate["clips"], "frames": candidate["frames"], + "wall_seconds": candidate["runtime"]["wall_seconds"], + "gpu_hours": candidate["runtime"]["wall_seconds"] / 3600.0, + "candidate_report_sha256": sha256(candidate_path), + "control_report_sha256": sha256(baseline_path), + "candidate": candidate_metrics, "control": baseline_metrics, + "delta": { + key: candidate_metrics[key] - baseline_metrics[key] + for key in FIELDS + }, + "candidate_grouped_recording_ci": candidate["grouped_bootstrap_ci"], + "control_grouped_recording_ci": baseline["grouped_bootstrap_ci"], + } + if item["id"].startswith("full_hot3d_"): + row["hot3d_headset"] = { + "candidate": hot_headsets(candidate), "control": hot_headsets(baseline), + } + rows.append(row) + return { + "schema_version": "phase9_resolution_evaluation_metrics_v1", + "status": "complete", "created_utc": datetime.now(timezone.utc).isoformat(), + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "decision_report": {"path": str(decision_path.resolve()), "sha256": sha256(decision_path)}, + "evaluation_count": len(rows), "paired_control_count": len(rows), + "paired_by_evaluation_id_and_identical_heldout_contract": True, + "candidate_evaluation_gpu_hours": sum(row["gpu_hours"] for row in rows), + "candidate_training_gpu_hours": decision["candidate_training_gpu_hours"], + "control_domain_absolute_mm": decision["control_domain_absolute_mm"], + "candidate_domain_absolute_mm": decision["candidate_domain_absolute_mm"], + "gate": decision["gate"], "h2o_guardrails": decision["h2o_guardrails"], + "rows": rows, + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def write_csv(path: Path, report: dict[str, Any]) -> None: + fieldnames = [ + "evaluation_id", "owner", "training_role", "input_mode", "clips", "frames", + "wall_seconds", "gpu_hours", "checkpoint_sha256", "config_sha256", + "cache_manifest_sha256", "candidate_report_sha256", "control_report_sha256", + ] + [f"{prefix}_{field}" for prefix in ("candidate", "control", "delta") for field in FIELDS] + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("x", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=fieldnames, lineterminator="\n") + writer.writeheader() + for source in report["rows"]: + row = {key: source[key] for key in fieldnames if key in source} + for prefix in ("candidate", "control", "delta"): + for field in FIELDS: + row[f"{prefix}_{field}"] = source[prefix][field] + writer.writerow(row) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--decision", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("resolution metric outputs must be new") + result = summarize(args.plan, args.decision) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output_json, result) + write_csv(args.output_csv, result) + print(json.dumps({ + "status": "complete", "json_sha256": sha256(args.output_json), + "csv_sha256": sha256(args.output_csv), "evaluation_count": 25, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_shared_augmentation_decision.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_shared_augmentation_decision.py new file mode 100644 index 0000000000000000000000000000000000000000..161b1cb515462f41add17769350833b0a3a9cc3c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_shared_augmentation_decision.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +"""Apply Stage 8 gate and freeze whether Stage 9 has a valid predecessor.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +import math +from pathlib import Path +from typing import Any + +from scripts.build_phase9_resolution_training_registry import FOLDS +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.summarize_phase9_resolution_decision import ( + NATIVE_EXTERNAL, + checked_report, + gate_decision, + h2o_guardrails, + metric, +) + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def stage9_preceding_gate( + augmentation_accepted: bool, augmentation_gate: dict[str, Any], + resolution_decision: dict[str, Any], +) -> dict[str, Any]: + augmentation_worst_improved = ( + augmentation_gate["candidate_worst_domain_absolute_mm"] + < augmentation_gate["control_worst_domain_absolute_mm"] + ) + if augmentation_accepted: + source = "shared_augmentation" + passed = ( + augmentation_gate["macro_strictly_improved"] + and augmentation_worst_improved + ) + else: + source = "resolution" + resolution_gate = resolution_decision["gate"] + passed = ( + resolution_decision["decision"] == "accept_896x512" + and resolution_gate["macro_strictly_improved"] + and resolution_gate["candidate_worst_domain_absolute_mm"] + < resolution_gate["control_worst_domain_absolute_mm"] + ) + return { + "source_mechanism": source, + "macro_and_worst_domain_strictly_improved": passed, + "stage9_last2_admitted": passed, + } + + +def summarize(plan_path: Path) -> dict[str, Any]: + plan = read_json(plan_path) + evaluations = {item["id"]: item for item in plan["evaluations"]} + if len(evaluations) != 25: + raise ValueError("shared augmentation evaluation count differs") + for item in evaluations.values(): + if not evaluation_complete(item): + raise ValueError(f"augmentation evaluation incomplete: {item['id']}") + + candidate_external = {} + for dataset, mode in NATIVE_EXTERNAL.items(): + identifier = f"full_{dataset}_{mode}" + candidate_external[dataset] = checked_report( + Path(evaluations[identifier]["output_dir"]) / "evaluation.json", + "phase9_external_heldout", mode, + ) + candidate_h2o_reports = { + (fold, mode): checked_report( + Path(evaluations[f"{fold}_{mode}"]["output_dir"]) / "evaluation.json", + "phase9_h2o_fold_heldout", mode, + ) + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + control_reports = {} + for identifier, item in plan["control_reports"].items(): + path = Path(item["path"]) + if not path.is_file() or item["sha256"] != sha256(path): + raise ValueError(f"augmentation control report hash differs: {identifier}") + control_reports[identifier] = checked_report( + path, item["evaluation_role"], item["input_mode"], + ) + control_external = { + dataset: control_reports[f"full_{dataset}_{mode}"] + for dataset, mode in NATIVE_EXTERNAL.items() + } + control_h2o_reports = { + (fold, mode): control_reports[f"{fold}_{mode}"] + for fold in FOLDS for mode in ("rgb_d_k", "rgb_k", "rgb_only") + } + candidate_h2o = h2o_guardrails(candidate_h2o_reports) + control_h2o = h2o_guardrails(control_h2o_reports) + control_domains = { + "h2o": control_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in control_external.items() + }, + } + candidate_domains = { + "h2o": candidate_h2o["rgb_d_k"]["absolute_macro_mm"], + **{ + dataset: metric(report, "absolute_mpjpe_mm") + for dataset, report in candidate_external.items() + }, + } + resolution_path = Path(plan["resolution_decision"]["path"]) + if ( + not resolution_path.is_file() + or plan["resolution_decision"]["sha256"] != sha256(resolution_path) + ): + raise ValueError("augmentation resolution decision binding differs") + resolution = read_json(resolution_path) + expected_control_domains = ( + resolution["candidate_domain_absolute_mm"] + if resolution["decision"] == "accept_896x512" + else resolution["control_domain_absolute_mm"] + ) + for dataset, expected in expected_control_domains.items(): + if not math.isclose(control_domains[dataset], float(expected), abs_tol=1e-8): + raise ValueError(f"augmentation selected control differs: {dataset}") + gate = gate_decision( + control_domains, candidate_domains, + float(plan["gate"]["worst_domain_relative_regression_limit"]), + ) + preceding = stage9_preceding_gate(gate["accepted"], gate, resolution) + + external_guardrails = {} + for dataset in NATIVE_EXTERNAL: + external_guardrails[dataset] = {} + for label, reports in ( + ("control", control_external), ("candidate", candidate_external), + ): + report = reports[dataset] + external_guardrails[dataset][label] = { + "absolute_mm": metric(report, "absolute_mpjpe_mm"), + "root_relative_mm": metric(report, "root_relative_mpjpe_mm"), + "fingertip_mm": metric(report, "fingertip_mpjpe_mm"), + "translation_z_p95_mm": metric( + report, "translation_z_mae_mm", "p95" + ), + } + training_gpu_hours = sum( + float(job["gpu_hours"]) for job in plan["training_jobs"].values() + ) + accepted = bool(gate["accepted"]) + return { + "schema_version": "phase9_shared_augmentation_decision_v1", + "status": "complete", + "created_utc": datetime.now(timezone.utc).isoformat(), + "decision": "accept_shared_augmentation" if accepted else "reject_shared_augmentation", + "shared_augmentation_accepted": accepted, + "selected_mechanism": "shared_augmentation" if accepted else "control", + "resolution_hw": plan["resolution_hw"], + "winner": plan["winner"], + "control_domain_absolute_mm": control_domains, + "candidate_domain_absolute_mm": candidate_domains, + "gate": gate, + "stage9_preceding_mechanism_gate": preceding, + "h2o_guardrails": {"control": control_h2o, "candidate": candidate_h2o}, + "external_guardrails": external_guardrails, + "candidate_training_gpu_hours": training_gpu_hours, + "candidate_training_jobs": { + role: { + "checkpoint": job["checkpoint"], + "checkpoint_sha256": job["checkpoint_sha256"], + "config": job["config"], "config_sha256": job["config_sha256"], + "gpu_hours": job["gpu_hours"], + } + for role, job in plan["training_jobs"].items() + }, + "control": plan["control"], + "resolution_decision": plan["resolution_decision"], + "evaluation_plan": {"path": str(plan_path.resolve()), "sha256": sha256(plan_path)}, + "selection_uses_four_domain_heldout_and_h2o_train_only_multifold": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error("shared augmentation decision output must be new") + result = summarize(args.plan) + args.output.parent.mkdir(parents=True, exist_ok=True) + atomic_json(args.output, result) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_unified_selection.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_unified_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..829747f7fdc5bbde018e1e0026d893dd7ea8fc8c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_phase9_unified_selection.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Select a Phase 9 unified candidate with dataset-equal group-CV evidence.""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +from typing import Any + + +CANDIDATES = { + "J25": [ + ("all20", "all_sources_20k"), + ("all50", "all_sources_50k"), + ("all100", "all_sources_100k"), + ("final405k", "final"), + ], + "J40": [ + ("nonhot20", "nonhot_20k"), + ("nonhot50_hot100", "nonhot_50k_hot_100k"), + ("nonhot100_hot200", "nonhot_100k_hot_200k"), + ("final505k", "final"), + ], + "J55": [ + ("nonhot20", "nonhot_20k"), + ("nonhot50", "nonhot_50k"), + ("nonhot100_hot367", "nonhot_100k_hot_367k"), + ("final675k", "final"), + ], +} +NATIVE_EXTERNAL = { + "hot3d": "hot3d_rgb_k", + "hoi4d": "hoi4d_rgb_d_k", + "arctic": "arctic_rgb_k", +} +METRICS = { + "absolute": "absolute_mpjpe_mm", + "root_relative": "root_relative_mpjpe_mm", + "fingertip": "fingertip_mpjpe_mm", +} + + +def evaluation(path: Path, expected_role: str) -> dict[str, Any]: + if not path.is_file(): + raise FileNotFoundError(path) + report = json.loads(path.read_text(encoding="utf-8")) + if ( + report.get("evaluation_role") != expected_role + or report.get("status") != f"evaluated_{expected_role}" + or report.get("official_test_used") is not False + or report.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"evaluation role/isolation mismatch: {path}") + return report + + +def validate_multifold_index(index: dict[str, Any]) -> list[dict[str, Any]]: + expected_folds = { + "loso_subject1", "loso_subject2", "loso_subject3", + "lofamily_h", "lofamily_k", "lofamily_o", + } + folds = index.get("folds", []) + ids = [fold.get("id") for fold in folds] + if ( + index.get("status") != "complete" + or index.get("h2o_official_validation_used") is not False + or index.get("official_test_used") is not False + or index.get("selection_metrics") + != ["fold_macro_absolute_mpjpe", "worst_fold_absolute_mpjpe"] + or len(ids) != 6 + or set(ids) != expected_folds + or any( + not fold.get("heldout", {}).get("sha256") + or not fold.get("heldout", {}).get("path") + for fold in folds + ) + ): + raise ValueError("multifold index selection/isolation contract differs") + return folds + + +def mean_metric(report: dict[str, Any], metric: str) -> float: + value = report["metrics"][metric] + if value is None or not math.isfinite(float(value["mean"])): + raise ValueError(f"missing finite metric: {metric}") + return float(value["mean"]) + + +def rank_values(values: dict[str, float]) -> dict[str, float]: + ordered = sorted(values.items(), key=lambda item: (item[1], item[0])) + ranks: dict[str, float] = {} + position = 0 + while position < len(ordered): + end = position + 1 + while end < len(ordered) and ordered[end][1] == ordered[position][1]: + end += 1 + rank = (position + 1 + end) / 2.0 + for key, _ in ordered[position:end]: + ranks[key] = rank + position = end + return ranks + + +def pareto_frontier(rows: list[dict[str, Any]], datasets: tuple[str, ...]) -> set[str]: + frontier = set() + for row in rows: + dominated = any( + other["id"] != row["id"] + and all(other["absolute_mm"][dataset] <= row["absolute_mm"][dataset] for dataset in datasets) + and any(other["absolute_mm"][dataset] < row["absolute_mm"][dataset] for dataset in datasets) + for other in rows + ) + if not dominated: + frontier.add(row["id"]) + return frontier + + +def summarize( + external_root: Path, fold_final_root: Path, fold_milestone_root: Path, + folds: list[dict[str, Any]], +) -> dict[str, Any]: + rows: list[dict[str, Any]] = [] + for mixture, candidates in CANDIDATES.items(): + for external_id, fold_id in candidates: + candidate_id = f"{mixture}:{external_id}" + external_reports = { + dataset: evaluation( + external_root / mixture / external_id / source_id / "evaluation.json", + "phase9_external_heldout", + ) + for dataset, source_id in NATIVE_EXTERNAL.items() + } + if ( + len({json.dumps(report["checkpoint"], sort_keys=True) for report in external_reports.values()}) != 1 + or len({json.dumps(report["config"], sort_keys=True) for report in external_reports.values()}) != 1 + ): + raise ValueError(f"external checkpoint/config binding differs: {candidate_id}") + fold_reports = [] + for fold_record in folds: + fold = fold_record["id"] + condition = f"{mixture}_{fold}" + root = fold_final_root if fold_id == "final" else fold_milestone_root / condition / fold_id + path = ( + root / condition / "rgb_d_k" / "evaluation.json" + if fold_id == "final" + else root / "rgb_d_k" / "evaluation.json" + ) + report = evaluation(path, "phase9_h2o_fold_heldout") + if ( + report.get("input_mode") != "rgb_d_k" + or report.get("cache_manifest", {}).get("path") + != fold_record["heldout"]["path"] + or report.get("cache_manifest", {}).get("sha256") + != fold_record["heldout"]["sha256"] + ): + raise ValueError(f"fold heldout binding differs: {condition}") + fold_reports.append(report) + h2o_absolute = [mean_metric(report, METRICS["absolute"]) for report in fold_reports] + row = { + "id": candidate_id, "mixture": mixture, + "external_checkpoint_id": external_id, + "fold_checkpoint_id": fold_id, + "checkpoint": external_reports["hot3d"]["checkpoint"], + "config": external_reports["hot3d"]["config"], + "absolute_mm": { + "h2o": sum(h2o_absolute) / len(h2o_absolute), + **{ + dataset: mean_metric(report, METRICS["absolute"]) + for dataset, report in external_reports.items() + }, + }, + "h2o_worst_fold_absolute_mm": max(h2o_absolute), + "h2o_fold_absolute_mm": dict(zip( + [fold["id"] for fold in folds], h2o_absolute, strict=True, + )), + "h2o_fold_macro_root_relative_mm": sum( + mean_metric(report, METRICS["root_relative"]) for report in fold_reports + ) / len(fold_reports), + "h2o_fold_macro_fingertip_mm": sum( + mean_metric(report, METRICS["fingertip"]) for report in fold_reports + ) / len(fold_reports), + } + rows.append(row) + datasets = ("h2o", "hot3d", "hoi4d", "arctic") + for dataset in datasets: + ranks = rank_values({row["id"]: row["absolute_mm"][dataset] for row in rows}) + best = min(row["absolute_mm"][dataset] for row in rows) + for row in rows: + row.setdefault("dataset_rank", {})[dataset] = ranks[row["id"]] + row.setdefault("normalized_regression_from_best", {})[dataset] = ( + row["absolute_mm"][dataset] - best + ) / best + frontier = pareto_frontier(rows, datasets) + for row in rows: + row["dataset_equal_mean_rank"] = sum(row["dataset_rank"].values()) / len(datasets) + row["worst_dataset_normalized_regression"] = max( + row["normalized_regression_from_best"].values() + ) + row["pareto_frontier"] = row["id"] in frontier + ordered = sorted(rows, key=lambda row: ( + row["dataset_equal_mean_rank"], + row["worst_dataset_normalized_regression"], + sum(row["absolute_mm"].values()), + row["id"], + )) + return { + "schema_version": "phase9_unified_selection_v1", + "status": "complete", + "selection_rule": "dataset_equal_mean_rank_then_worst_normalized_regression_then_sum", + "normalization": "candidate_minus_per_dataset_best divided by per_dataset_best", + "winner": ordered[0]["id"], + "winner_checkpoint": ordered[0]["checkpoint"], + "winner_config": ordered[0]["config"], + "pareto_frontier": sorted(frontier), + "candidates": ordered, + "h2o_official_validation_used": False, + "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--external-root", type=Path, required=True) + parser.add_argument("--fold-final-root", type=Path, required=True) + parser.add_argument("--fold-milestone-root", type=Path, required=True) + parser.add_argument("--multifold-index", type=Path, required=True) + parser.add_argument("--output-json", type=Path, required=True) + parser.add_argument("--output-csv", type=Path, required=True) + args = parser.parse_args() + if args.output_json.exists() or args.output_csv.exists(): + parser.error("selection outputs must be new") + index = json.loads(args.multifold_index.read_text(encoding="utf-8")) + result = summarize( + args.external_root, args.fold_final_root, args.fold_milestone_root, + validate_multifold_index(index), + ) + args.output_json.parent.mkdir(parents=True, exist_ok=True) + csv_temporary = args.output_csv.with_suffix(args.output_csv.suffix + ".tmp") + json_temporary = args.output_json.with_suffix(args.output_json.suffix + ".tmp") + with csv_temporary.open("x", newline="", encoding="utf-8") as handle: + fields = [ + "id", "mixture", "external_checkpoint_id", "fold_checkpoint_id", + "h2o_absolute_mm", "hot3d_absolute_mm", "hoi4d_absolute_mm", + "arctic_absolute_mm", "h2o_worst_fold_absolute_mm", + "dataset_equal_mean_rank", "worst_dataset_normalized_regression", + "pareto_frontier", + ] + writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") + writer.writeheader() + for row in result["candidates"]: + writer.writerow({ + **{key: row[key] for key in fields if key in row}, + **{f"{dataset}_absolute_mm": row["absolute_mm"][dataset] for dataset in ("h2o", "hot3d", "hoi4d", "arctic")}, + }) + json_temporary.write_text( + json.dumps(result, indent=2) + "\n", encoding="utf-8", + ) + csv_temporary.replace(args.output_csv) + json_temporary.replace(args.output_json) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_pilots.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_pilots.py new file mode 100644 index 0000000000000000000000000000000000000000..2d3328105d986f49810eb62ccfe40cd8a9d5dd0e --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_pilots.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""Create reproducible comparison tables and curves from completed pilots.""" + +from __future__ import annotations + +import argparse +import csv +import json +from datetime import datetime +from pathlib import Path + +import matplotlib.pyplot as plt + + +EXPERIMENTS_30MIN = { + "B Sequential RGB": "b_sequential_v1", + "C Alternating RGB": "c_alternating_v1", + "D Alternating RGB+K": "d_rgb_k_v1", + "E Alternating RGB+Depth": "e_rgb_depth_fixed_v1", + "F Alternating RGB+Depth+K": "f_rgb_depth_k_fixed_v1", +} + +EXPERIMENTS_2H = { + "C Alternating RGB": { + "result": "c_alternating_v3_resume_step50", + "segments": ["c_alternating_v1", "c_alternating_v2_resume_step25", "c_alternating_v3_resume_step50"], + }, + "D Alternating RGB+K": {"result": "d_rgb_k_v1", "segments": ["d_rgb_k_v1"]}, + "F Alternating RGB+Depth+K": {"result": "f_rgb_depth_k_fixed_v1", "segments": ["f_rgb_depth_k_fixed_v1"]}, +} + + +def load_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--pilot-root", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--suite", choices=("30min", "2h"), default="30min") + args = parser.parse_args() + args.output_dir.mkdir(parents=True, exist_ok=True) + + rows = [] + bucket_rows = [] + curves = {} + if args.suite == "30min": + experiments = { + label: {"result": directory, "segments": [directory]} + for label, directory in EXPERIMENTS_30MIN.items() + } + else: + experiments = EXPERIMENTS_2H + for label, experiment in experiments.items(): + directory = experiment["result"] + root = args.pilot_root / directory + summary = load_json(root / "summary.json") + evaluation = load_json(root / "full_validation_best" / "evaluation.json") + validation = [] + training_records = [] + for segment in experiment["segments"]: + segment_root = args.pilot_root / segment + if (segment_root / "validation.jsonl").is_file(): + validation.extend(json.loads(line) for line in (segment_root / "validation.jsonl").read_text().splitlines()) + if (segment_root / "metrics.jsonl").is_file(): + training_records.extend(json.loads(line) for line in (segment_root / "metrics.jsonl").read_text().splitlines()) + validation.sort(key=lambda item: item["step"]) + training_records.sort(key=lambda item: item["step"]) + best_record = min(validation, key=lambda item: item["metrics"]["absolute_camera_mpjpe_mm"]) + metrics = evaluation["metrics"] + first_timestamp = datetime.fromisoformat(training_records[0]["timestamp"]) + last_timestamp = datetime.fromisoformat(training_records[-1]["timestamp"]) + wall_minutes = (last_timestamp - first_timestamp).total_seconds() / 60 + rows.append({ + "experiment": label, + "best_step": best_record["step"], + "trained_steps": summary["completed_step"], + "elapsed_minutes": wall_minutes, + "peak_vram_gib": summary["peak_vram_gib"], + "frames_per_s": summary["frames_per_s"], + "subset_best_absolute_mpjpe_mm": best_record["metrics"]["absolute_camera_mpjpe_mm"], + "full_absolute_mpjpe_mm": metrics["all_absolute_mpjpe_mm"], + "full_root_relative_mpjpe_mm": metrics["all_root_relative_mpjpe_mm"], + "full_joint2d_error_px": metrics["all_joint2d_error_px"], + "z_mae_mm": (metrics["left_translation_z_mae_mm"] + metrics["right_translation_z_mae_mm"]) / 2, + "velocity_error_mm_per_frame": metrics["temporal_velocity_error_mm_per_frame"], + "acceleration_error_mm_per_frame2": metrics["temporal_acceleration_error_mm_per_frame2"], + "rgb_attention_same_peak_fraction": metrics["rgb_attention_same_peak_fraction"], + "temporal_attention_entropy": metrics["temporal_attention_normalized_entropy"], + "depth_gate_mean": metrics["depth_gate_mean"], + "best_checkpoint": summary["best_checkpoint"], + }) + for bucket, values in evaluation["buckets"].items(): + bucket_rows.append({"experiment": label, "bucket": bucket, **values}) + curves[label] = validation + + with (args.output_dir / "comparison.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + with (args.output_dir / "bucket_comparison.csv").open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(bucket_rows[0])) + writer.writeheader() + writer.writerows(bucket_rows) + (args.output_dir / "comparison.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8") + + fig, axes = plt.subplots(1, 3, figsize=(16, 4.5)) + metric_names = ( + ("absolute_camera_mpjpe_mm", "Absolute MPJPE (mm)"), + ("root_relative_mpjpe_mm", "Root-relative MPJPE (mm)"), + ("translation_z_mae_mm", "Translation z MAE (mm)"), + ) + for label, records in curves.items(): + steps = [record["step"] for record in records] + for axis, (metric, title) in zip(axes, metric_names, strict=True): + axis.plot(steps, [record["metrics"][metric] for record in records], label=label) + axis.set_title(title) + axis.set_xlabel("step") + axis.grid(alpha=0.25) + axes[0].legend(fontsize=7) + fig.tight_layout() + fig.savefig(args.output_dir / "validation_curves.png", dpi=180) + plt.close(fig) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_sota_evaluation.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_sota_evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..b46e9cca845bda5ca51a6087e12136c3f45da2b0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_sota_evaluation.py @@ -0,0 +1,813 @@ +#!/usr/bin/env python3 +"""Build the reproducible FoundationHand external-baseline comparison report.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +from foundation_hand.evaluation.sota import paired_take_bootstrap, write_csv_rows + + +METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", +) +TEMPORAL_METRICS = ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "joint_acceleration_error_mm_per_frame2", +) + +PROTOCOLS = { + "FoundationHand-Phase3": ( + "h2o_trained", + "H2O train;validation 子集选模", + ), + "QORT-Former": ("h2o_trained", "H2O train"), + "WiLoR-H2O-K": ("zero_shot", "无 H2O 微调;训练含 H2O3D"), + "HaWoR-camera": ("zero_shot", "发布权重无 H2O 微调"), + "WildHands-zero-shot": ( + "zero_shot", + "无 H2O;训练用 ARCTIC/AssemblyHands/EPIC", + ), + "Hamba-zero-shot": ( + "zero_shot", + "无 H2O;训练含 H2O3D", + ), + "PAD-Hand-WiLoR": ( + "zero_shot", + "无 H2O;论文训练用 DexYCB/HO3D,release checkpoint 未标具体版本", + ), + "HandDGP-zero-shot": ( + "zero_shot", + "无 H2O/H2O3D;发布权重仅用 FreiHAND 训练", + ), + "Dyn-HaMR-TTO": ( + "test_time_optimization", + "无 H2O;HaMeR initializer 含 H2O3D;每段视频独立 TTO", + ), + "WiLoR-native-camera": ("diagnostic", "同一 WiLoR 权重;原生 demo camera"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def read_rows(path: Path) -> list[dict[str, Any]]: + with path.open(newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle)) + for row in rows: + for key, value in tuple(row.items()): + if value == "": + row[key] = None + return rows + + +def parameters(metadata: dict[str, Any]) -> tuple[int, int]: + if "end_to_end_parameter_count" in metadata: + return ( + int(metadata["reconstruction_parameter_count"]), + int(metadata["end_to_end_parameter_count"]), + ) + count = int(metadata["parameter_count"]) + return count, count + + +def metric_mean(report: dict[str, Any], metric: str) -> float | None: + summary = report["metrics_success_conditioned"].get(metric) + return None if summary is None else summary["mean"] + + +def temporal_mean(report: dict[str, Any], metric: str) -> float | None: + summary = report["temporal_metrics_success_conditioned"].get(metric) + return None if summary is None else summary["mean"] + + +def fmt(value: float | int | None, digits: int = 3) -> str: + if value is None: + return "N/A" + return f"{float(value):.{digits}f}" + + +def fmt_params(value: int) -> str: + return f"{value / 1_000_000:.1f}M" + + +def load_evaluation(label: str, directory: Path) -> dict[str, Any]: + report_path = directory / "evaluation.json" + frame_path = directory / "per_hand_frame_metrics.csv" + temporal_path = directory / "per_temporal_transition_metrics.csv" + report = json.loads(report_path.read_text(encoding="utf-8")) + if ( + report.get("status") != "evaluated" + or report.get("split_role") != "official_validation" + or report.get("official_test_used") is not False + ): + raise ValueError(f"Not a complete official-validation evaluation: {directory}") + model_parameters, end_to_end_parameters = parameters(report["prediction_metadata"]) + track, h2o_exposure = PROTOCOLS.get( + label, + ("uncategorized", report["prediction_metadata"].get("training_exposure", "Unknown")), + ) + row: dict[str, Any] = { + "label": label, + "model_name": report["model_name"], + "evaluation_track": track, + "h2o_exposure": h2o_exposure, + "input": report["prediction_metadata"].get("input"), + "temporal": report["prediction_metadata"].get("temporal"), + "model_parameter_count": model_parameters, + "end_to_end_parameter_count": end_to_end_parameters, + "frames": report["frames"], + "takes": report["takes"], + "annotation_valid_hand_frames": report["coverage"]["annotation_valid_hand_frames"], + "successful_hand_frames": report["coverage"]["successful_hand_frames"], + "coverage": report["coverage"]["hand_frame_fraction"], + "temporal_pair_coverage": report["coverage"]["temporal_pair_fraction"], + **{metric: metric_mean(report, metric) for metric in METRICS}, + **{metric: temporal_mean(report, metric) for metric in TEMPORAL_METRICS}, + **report["failure_aware"], + "evaluation_json": str(report_path.resolve()), + "evaluation_json_sha256": sha256(report_path), + "frame_metrics_csv": str(frame_path.resolve()), + "frame_metrics_csv_sha256": sha256(frame_path), + "temporal_metrics_csv": str(temporal_path.resolve()), + "temporal_metrics_csv_sha256": sha256(temporal_path), + } + for side in ("left", "right"): + row[f"{side}_coverage"] = report["per_side"][side]["coverage"] + row[f"{side}_absolute_mpjpe_mm"] = report["per_side"][side][ + "absolute_mpjpe_mm" + ]["mean"] + row[f"{side}_root_relative_mpjpe_mm"] = report["per_side"][side][ + "root_relative_mpjpe_mm" + ]["mean"] + return { + "label": label, + "directory": directory, + "report": report, + "frame_rows": read_rows(frame_path), + "summary": row, + } + + +def markdown_report( + evaluations: list[dict[str, Any]], + paired_rows: list[dict[str, Any]], + refinement_rows: list[dict[str, Any]], + dynhamr_hawor_rows: list[dict[str, Any]], + speed_report: dict[str, Any] | None, + *, + manifest: Path, + manifest_hash: str, + ground_truth: Path, + ground_truth_hash: str, + bootstrap_seed: int, + bootstrap_samples: int, +) -> str: + rows = [evaluation["summary"] for evaluation in evaluations] + foundation_evaluation = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "FoundationHand-Phase3" + ) + foundation_trainable = foundation_evaluation["report"]["prediction_metadata"].get( + "trainable_parameter_count_at_export" + ) + foundation_row = foundation_evaluation["summary"] + rows_by_label = {row["label"]: row for row in rows} + + comparative_note = "" + if "HaWoR-camera" in rows_by_label: + hawor_row = rows_by_label["HaWoR-camera"] + hawor_root = next( + row for row in paired_rows + if row["candidate"] == "HaWoR-camera" + and row["metric"] == "root_relative_mpjpe_mm" + ) + comparative_note = ( + "作为跨赛道描述性配对,FoundationHand 在 absolute joints/mesh、fingertip、z 和时间误差上更低;" + f"HaWoR 的逐帧 root-relative 均值虽低 " + f"{foundation_row['root_relative_mpjpe_mm'] - hawor_row['root_relative_mpjpe_mm']:.3f} mm," + f"但 take-equal paired delta 为 {hawor_root['candidate_minus_baseline']:+.3f} mm、" + f"95% CI [{hawor_root['ci95_low']:.3f}, {hawor_root['ci95_high']:.3f}]," + "只能判为等价,不能声称 HaWoR 显著更好。HaWoR 的 2D 优势有 paired CI 支持。" + ) + + qort_note = "" + if "QORT-Former" in rows_by_label: + qort_row = rows_by_label["QORT-Former"] + qort_note = ( + "具体到 QORT-Former:公开 checkpoint 在本 validation 上为 left/right " + f"{qort_row['left_absolute_mpjpe_mm']:.3f}/" + f"{qort_row['right_absolute_mpjpe_mm']:.3f} mm,没有达到论文 test 的 " + "20.1/19.9 mm 水平。它说明“公开权重在当前开发集未重现论文量级”," + "但 split 不同,所以不是论文数字错误的充分证据。" + ) + wildhands_note = "" + if "WildHands-zero-shot" in rows_by_label: + wildhands_row = rows_by_label["WildHands-zero-shot"] + wildhands_note = ( + "WildHands 发布权重在本协议的 root-relative MPJPE 为 " + f"{wildhands_row['root_relative_mpjpe_mm']:.3f} mm,与论文 H2O validation " + f"GT-box 结果 31.08 mm 相差 " + f"{wildhands_row['root_relative_mpjpe_mm'] - 31.08:.3f} mm," + "支持当前模型与关节适配的正确性。" + f"但 absolute MPJPE/z MAE 达 {wildhands_row['absolute_mpjpe_mm']:.3f}/" + f"{wildhands_row['translation_z_mae_mm']:.3f} mm,说明相对姿态接近论文量级不代表" + "绝对 camera-space 深度准确。" + ) + pad_note = "" + if "PAD-Hand-WiLoR" in rows_by_label and "WiLoR-H2O-K" in rows_by_label: + pad_row = rows_by_label["PAD-Hand-WiLoR"] + wilor_row = rows_by_label["WiLoR-H2O-K"] + pad_root = next( + row for row in refinement_rows + if row["metric"] == "root_relative_mpjpe_mm" + ) + pad_note = ( + "PAD-Hand 与 WiLoR 使用相同检测、初始化和 camera translation;其 16 帧扩散 refinement " + f"使 root-relative MPJPE 增加 " + f"{pad_row['root_relative_mpjpe_mm'] - wilor_row['root_relative_mpjpe_mm']:.3f} mm " + f"(take-equal paired delta {pad_root['candidate_minus_baseline']:+.3f} mm," + f"95% CI [{pad_root['ci95_low']:.3f}, {pad_root['ci95_high']:.3f}])," + f"但 joint velocity/acceleration error 从 " + f"{wilor_row['joint_velocity_error_mm_per_frame']:.3f}/" + f"{wilor_row['joint_acceleration_error_mm_per_frame2']:.3f} 降至 " + f"{pad_row['joint_velocity_error_mm_per_frame']:.3f}/" + f"{pad_row['joint_acceleration_error_mm_per_frame2']:.3f}。" + "因此它在 H2O 上是平滑性收益而非空间精度 SOTA。" + ) + dynhamr_note = "" + if "Dyn-HaMR-TTO" in rows_by_label: + dynhamr_row = rows_by_label["Dyn-HaMR-TTO"] + dynhamr_evaluation = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "Dyn-HaMR-TTO" + ) + dynhamr_metadata = dynhamr_evaluation["report"]["prediction_metadata"] + dynhamr_note = ( + "Dyn-HaMR 不是一次前向的重建网络:本表按每个 official-validation 连续 run " + "独立执行发布的 Root/Smooth test-time optimization,并使用已知静态 cam4 K。" + f"其 Coverage/absolute/root-relative MPJPE 为 {100 * dynhamr_row['coverage']:.2f}%/" + f"{dynhamr_row['absolute_mpjpe_mm']:.3f}/{dynhamr_row['root_relative_mpjpe_mm']:.3f} mm。" + f"94 个 run 共执行 {int(dynhamr_metadata['root_iterations_total']):,}/" + f"{int(dynhamr_metadata['smooth_iterations_total']):,} 次 Root/Smooth 外循环。" + "因此它属于高计算量 TTO 系统赛道,不能当作与 HaWoR/WiLoR 同成本的 feed-forward 模型。" + ) + if dynhamr_hawor_rows: + root_contrast = next( + row for row in dynhamr_hawor_rows + if row["metric"] == "root_relative_mpjpe_mm" + ) + dynhamr_note += ( + " 与 HaWoR 直接配对时,Dyn-HaMR 的 root-relative take-equal delta 为 " + f"{root_contrast['candidate_minus_baseline']:+.3f} mm,95% CI " + f"[{root_contrast['ci95_low']:.3f}, {root_contrast['ci95_high']:.3f}]," + "不能宣称任一方法显著更好。" + ) + h2o_trained = [row for row in rows if row["evaluation_track"] == "h2o_trained"] + zero_shot = [row for row in rows if row["evaluation_track"] == "zero_shot"] + test_time_optimization = [ + row for row in rows if row["evaluation_track"] == "test_time_optimization" + ] + diagnostics = [row for row in rows if row["evaluation_track"] == "diagnostic"] + uncategorized = [row for row in rows if row["evaluation_track"] == "uncategorized"] + h2o_absolute_winner = min( + (row for row in h2o_trained if row["absolute_mpjpe_mm"] is not None), + key=lambda row: row["absolute_mpjpe_mm"], + ) + h2o_root_winner = min( + (row for row in h2o_trained if row["root_relative_mpjpe_mm"] is not None), + key=lambda row: row["root_relative_mpjpe_mm"], + ) + zero_absolute_winner = min( + (row for row in zero_shot if row["absolute_mpjpe_mm"] is not None), + key=lambda row: row["absolute_mpjpe_mm"], + ) + zero_root_winner = min( + (row for row in zero_shot if row["root_relative_mpjpe_mm"] is not None), + key=lambda row: row["root_relative_mpjpe_mm"], + ) + zero_mesh_winner = min( + (row for row in zero_shot if row["absolute_mpvpe_mm"] is not None), + key=lambda row: row["absolute_mpvpe_mm"], + ) + zero_projected_winner = min( + (row for row in zero_shot if row["projected_2d_error_px"] is not None), + key=lambda row: row["projected_2d_error_px"], + ) + table_header = ( + "| 模型 | H2O 暴露 | 输入 | Params (模型/E2E) | Coverage | Abs MPJPE | " + "Root MPJPE | MPVPE | Root MPVPE | 2D | Fingertip | z MAE | PCK20 | AUC0-50 |" + ) + table_divider = ( + "|---|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|" + ) + speed_section: list[str] = [] + if speed_report is not None: + speed_by_label = { + row["setting_id"]: row for row in speed_report["rows"] + } + speed_section = [ + "", + "## 推理速度", + "", + ( + "同一 94 帧 H2O 连续片段、RTX 4090、包含 RGB 解码/预处理/所需 detector/" + "重建与 camera conversion 的本机实测中,批处理/时序摊销吞吐为:" + f"FoundationHand T8 {speed_by_label['FoundationHand-T8']['median_fps']:.2f} FPS," + f"QORT batch16 {speed_by_label['QORT-b16']['median_fps']:.2f} FPS," + f"WiLoR batch16 {speed_by_label['WiLoR-b16']['median_fps']:.2f} FPS," + f"HaWoR T16 {speed_by_label['HaWoR-T16']['median_fps']:.2f} FPS," + f"Dyn-HaMR TTO {speed_by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS。" + ), + "", + ( + "QORT/WiLoR 的 batch1 在线吞吐分别为 " + f"{speed_by_label['QORT-b1']['median_fps']:.2f}/" + f"{speed_by_label['WiLoR-b1']['median_fps']:.2f} FPS。" + "FoundationHand 的独立纯模型 profile 为 " + f"{speed_report['foundation_model_only_profile']['p50_ms_per_t8_clip']:.2f} ms/T8 clip," + f"即 {speed_report['foundation_model_only_profile']['amortized_frames_per_second']:.1f} frame/s;" + "完整数据路径为 T=8 RGB+Depth+K,因此二者不是同一计时口径。" + "HaWoR 与 Dyn-HaMR 是离线时序/TTO 方法,摊销 ms/frame 不是因果单帧延迟。" + "完整口径、重复范围与 Dyn-HaMR 开销拆分见 `INFERENCE_SPEED_REPORT.md`。" + ), + ] + + def result_line(row: dict[str, Any]) -> str: + return ( + f"| {row['label']} | {row['h2o_exposure']} | {row['input']} | " + f"{fmt_params(row['model_parameter_count'])}/{fmt_params(row['end_to_end_parameter_count'])} | " + f"{100 * row['coverage']:.2f}% | {fmt(row['absolute_mpjpe_mm'])} | " + f"{fmt(row['root_relative_mpjpe_mm'])} | {fmt(row['absolute_mpvpe_mm'])} | " + f"{fmt(row['root_relative_mpvpe_mm'])} | {fmt(row['projected_2d_error_px'])} | " + f"{fmt(row['fingertip_mpjpe_mm'])} | {fmt(row['translation_z_mae_mm'])} | " + f"{100 * row['absolute_pck_20mm']:.2f}% | {row['absolute_auc_0_50mm']:.4f} |" + ) + + lines = [ + "# FoundationHand 外部 SOTA 统一复评报告", + "", + "## 公平性结论", + "", + ( + "把 FoundationHand/QORT 与外部发布权重排成一个训练条件等价的 SOTA 总榜是不公平的。" + "前两者使用 H2O 训练,其余方法没有在 H2O 上微调;因此本报告改为域内训练与" + "零样本泛化两条前向赛道,并把逐视频优化方法单列为 TTO 赛道。" + "所有模型仍共享同一 validation、GT、坐标系和 evaluator。" + ), + "", + ( + f"H2O 域内训练赛道中,absolute/root-relative MPJPE 最低的分别是 " + f"**{h2o_absolute_winner['label']} ({fmt(h2o_absolute_winner['absolute_mpjpe_mm'])} mm)** " + f"和 **{h2o_root_winner['label']} ({fmt(h2o_root_winner['root_relative_mpjpe_mm'])} mm)**。" + "这仍是系统级比较:FoundationHand 使用 RGB+metric Depth+K、T=8,QORT 使用单帧 RGB。" + ), + "", + ( + f"H2O 零样本 RGB 赛道中,absolute/root-relative MPJPE 最低的分别是 " + f"**{zero_absolute_winner['label']} ({fmt(zero_absolute_winner['absolute_mpjpe_mm'])} mm)** " + f"和 **{zero_root_winner['label']} ({fmt(zero_root_winner['root_relative_mpjpe_mm'])} mm)**;" + f"absolute MPVPE 最低的是 **{zero_mesh_winner['label']} " + f"({fmt(zero_mesh_winner['absolute_mpvpe_mm'])} mm)**,投影 2D 最低的是 " + f"**{zero_projected_winner['label']} ({fmt(zero_projected_winner['projected_2d_error_px'])} px)**。" + ), + "", + comparative_note, + "", + ( + "这是一份同数据、同 GT、同坐标系、同评估器的开发集复评,不是可直接发表的官方-test " + "SOTA 声明。FoundationHand 的模型选择使用过该 validation split 的固定子集;各方法的输入模态和训练数据也不同。" + ), + "", + "## H2O 域内训练赛道", + "", + ( + "误差均为越低越好;Coverage、PCK、AUC 越高越好。MPJPE/MPVPE 是检测成功样本上的均值;" + "失败不会被静默删除,而是通过 Coverage 和 failure-aware PCK/AUC 计入。2D 误差按 Phase3 " + "约定缩放到 640x368 评估像素。" + ), + "", + table_header, + table_divider, + ] + lines.extend(result_line(row) for row in h2o_trained) + lines.extend([ + "", + "## H2O 零样本 RGB 赛道", + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in zero_shot) + if test_time_optimization: + lines.extend([ + "", + "## H2O 零样本 Test-Time Optimization 赛道", + "", + ( + "该表使用同一 H2O validation 和 evaluator,但方法在每段测试视频上优化模型变量," + "计算预算显著高于一次前向方法,因此不参与上方 zero-shot feed-forward winner 判定。" + ), + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in test_time_optimization) + if diagnostics or uncategorized: + lines.extend([ + "", + "## 诊断与未分类结果", + "", + table_header, + table_divider, + ]) + lines.extend(result_line(row) for row in diagnostics + uncategorized) + lines.extend([ + "", + "### 左右手拆分", + "", + "| 模型 | Left coverage | Left Abs | Left Root | Right coverage | Right Abs | Right Root |", + "|---|---:|---:|---:|---:|---:|---:|", + ]) + for row in rows: + lines.append( + f"| {row['label']} | {100 * row['left_coverage']:.2f}% | " + f"{fmt(row['left_absolute_mpjpe_mm'])} | " + f"{fmt(row['left_root_relative_mpjpe_mm'])} | " + f"{100 * row['right_coverage']:.2f}% | " + f"{fmt(row['right_absolute_mpjpe_mm'])} | " + f"{fmt(row['right_root_relative_mpjpe_mm'])} |" + ) + lines.extend([ + "", + "WiLoR-H2O-K 使用已知 H2O 内参代入官方 `cam_crop_to_full` 代数,没有使用 GT pose 或拟合参数。" + "`WiLoR-native-camera` 保留发布 demo 的假设焦距,仅用于展示原样 camera translation 在 H2O 上的行为,不参与主结论。", + "", + ( + f"参数量由实际加载模块逐参数计数。FoundationHand 总参数 126.8M 中,export 时可训练参数为 " + f"{fmt_params(int(foundation_trainable)) if foundation_trainable is not None else 'N/A'}(DINO 冻结);" + "外部 RGB 方法的 E2E 数量包含实际使用的公开 detector。HaWoR 的 camera-space 表不加载与该任务无关的 " + "DROID-SLAM、Metric3D 和 world-space infiller。Dyn-HaMR 的参数数目是实际使用的 HaMeR initializer " + "与 detector;逐 run 优化变量随帧数变化,不计作网络参数。" + ), + "", + "QORT-Former 不输出 MANO mesh,因此 MPVPE 为 N/A。其 normalized `(u,v,z)` 反归一化和 K 反投影逐式复现了它所基于的官方 [H2OTR `pixel2cam`](https://github.com/chohoseong/H2OTR/blob/master/util/ops.py),不是用 GT pose 拟合得到的坐标。", + *speed_section, + "", + "## 时间指标", + "", + "| 模型 | Pair coverage | Wrist velocity | Joint velocity | Wrist acceleration | Joint acceleration |", + "|---|---:|---:|---:|---:|---:|", + ]) + for row in rows: + lines.append( + f"| {row['label']} | {100 * row['temporal_pair_coverage']:.2f}% | " + f"{fmt(row['wrist_velocity_error_mm_per_frame'])} | " + f"{fmt(row['joint_velocity_error_mm_per_frame'])} | " + f"{fmt(row['wrist_acceleration_error_mm_per_frame2'])} | " + f"{fmt(row['joint_acceleration_error_mm_per_frame2'])} |" + ) + lines.extend([ + "", + "时间差分只在同一连续 run、同一 Phase3 T=8 clip 内计算;检测失败的 pair 由 pair coverage 单独报告。", + "", + "### PAD-Hand refinement 诊断", + "", + pad_note, + "", + "### Dyn-HaMR TTO 诊断", + "", + dynhamr_note, + "", + "## 配对统计", + "", + ( + f"下表为候选模型减 FoundationHand 的 take-equal paired bootstrap;负值表示候选误差更低。" + f"每项只使用两模型都成功的精确交集,{bootstrap_samples:,} 次重采样,seed={bootstrap_seed}。" + ), + "", + "| 候选 | Metric | Paired hands | Takes | Delta | 95% CI |", + "|---|---|---:|---:|---:|---:|", + ]) + for row in paired_rows: + if row["metric"] not in ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_z_mae_mm", + ): + continue + lines.append( + f"| {row['candidate']} | {row['metric']} | {row['paired_hand_frames']} | " + f"{row['take_count']} | {fmt(row['candidate_minus_baseline'])} | " + f"[{fmt(row['ci95_low'])}, {fmt(row['ci95_high'])}] |" + ) + lines.extend([ + "", + "## 与论文原表的关系", + "", + "| 工作 | 论文报告 | 为什么不能与本表直接混排 |", + "|---|---|---|", + "| QORT-Former | H2O official test mean end-point error: left 20.1 mm, right 19.9 mm | 本报告是 official validation;论文未报告本 split 数字。指标形式接近,但 split 不同。 |", + "| WiLoR | FreiHAND PA-MPJPE/PA-MPVPE 5.5/5.1 mm;HO3D 7.5/7.7 mm | 数据集不同,且经过 Procrustes alignment;本表是 H2O 绝对 camera-space。 |", + "| HaWoR | DexYCB PA-MPJPE 4.76 mm、AUC 90.5 | 数据集不同,且 PA 对齐;本表只评 camera-space hand stage,不含 SLAM、Metric3D、world-space infiller。 |", + "| WildHands | H2O validation zero-shot root-relative MPJPE 31.08 mm、MRRPE 49.49 mm | 论文主要 ablation 使用 GT hand boxes;本表使用公开 detector,并额外报告 absolute camera-space、mesh、coverage。 |", + "| Hamba | FreiHAND PA-MPJPE/PA-MPVPE 5.8/5.5 mm(无 TTA) | 论文不报告 H2O;数据集不同且经 Procrustes alignment。本表发布配置含 H2O3D,但未含 H2O。 |", + "| PAD-Hand | DexYCB WiLoR→PAD-Hand: PA-MPJPE 4.88→4.63 mm、MPJPE 12.75→10.56 mm、ACCEL 6.70→3.34 | 本表是 H2O zero-shot,且保留 WiLoR camera translation;release checkpoint 未在 README 标明对应 DexYCB/HO3D 版本。 |", + "| HandDGP | FreiHAND camera-space MJE/MVE 46.3/46.3 mm | 发布权重仅用 FreiHAND;本表使用 H2O detector crop、已知 K 和同一 camera-space evaluator。 |", + "| Dyn-HaMR | 论文在动态相机视频上报告 global 4D hand-motion 指标 | 论文目标含相机运动与 world-space trajectory;本表因 H2O cam4 静止且 K 已知,只评每段 TTO 后的 camera-space hand 输出。 |", + "", + "因此,本复评能够检查公开 checkpoint 在同一 H2O validation 上的实际行为,但不能单独证实或否定论文 official-test 数字。", + "", + qort_note, + "", + wildhands_note, + "", + "原始来源:QORT-Former [paper](https://arxiv.org/abs/2502.19769) / [official repo](https://github.com/kcsayem/QORT-Former);WiLoR [paper](https://arxiv.org/abs/2409.12259) / [official repo](https://github.com/rolpotamias/WiLoR);HaWoR [paper](https://arxiv.org/abs/2501.02973) / [official repo](https://github.com/ThunderVVV/HaWoR);WildHands [ECCV page](https://eccv.ecva.net/virtual/2024/poster/2450) / [official repo](https://github.com/ap229997/hands);Hamba [NeurIPS paper](https://proceedings.neurips.cc/paper_files/paper/2024/hash/03e9a69e5b686c316a07d73f0cf5e225-Abstract-Conference.html) / [official repo](https://github.com/humansensinglab/Hamba);PAD-Hand [CVPR paper](https://openaccess.thecvf.com/content/CVPR2026/html/Ismayilzada_PAD-Hand_Physics-Aware_Diffusion_for_Hand_Motion_Recovery_CVPR_2026_paper.html) / [official repo](https://github.com/DominoAI-Lab/PAD-Hand-CVPR-2026);HandDGP [project](https://nianticlabs.github.io/handdgp/) / [official repo](https://github.com/nianticlabs/HandDGP);Dyn-HaMR [CVPR paper](https://openaccess.thecvf.com/content/CVPR2025/html/Yu_Dyn-HaMR_Recovering_4D_Interacting_Hand_Motion_from_a_Dynamic_Camera_CVPR_2025_paper.html) / [official repo](https://github.com/ZhengdiYu/Dyn-HaMR)。", + "", + "## 协议与公平性边界", + "", + f"- Manifest: `{manifest}`,SHA256 `{manifest_hash}`。", + f"- Ground truth bundle: `{ground_truth}`,SHA256 `{ground_truth_hash}`。", + f"- 样本:{rows[0]['frames']:,} 帧、{rows[0]['takes']} takes、{rows[0]['annotation_valid_hand_frames']:,} 个 annotation-valid hand-frames。", + "- Split:H2O official validation(subject3 held-out runs);official test(subject4)未使用。", + "- Camera:全部输出统一成 raw cam4 的 x-right/y-down/z-forward metric XYZ,再由同一 K 投影。", + "- 关节:H2O 左/右各 21 joints;mesh 统一为对应 MANO 778 vertices。", + "- FoundationHand 输入 RGB+metric Depth+K、T=8;QORT 输入单帧 RGB;WiLoR/WildHands/Hamba/HandDGP 输入 RGB detector/crop;HaWoR 与 PAD-Hand 输入 T=16 RGB track;Dyn-HaMR 对每个完整连续 run 做 TTO。协议一致不等于输入模态或计算预算一致。", + "- FoundationHand checkpoint 在 validation 固定子集上被选择;因此本报告用于开发期横向复评,最终无偏结论必须在冻结后一次性跑 official test。", + "- 直接运行 WiLoR/HaWoR/WildHands/Hamba/PAD-Hand/HandDGP 是有效的 H2O out-of-box 泛化测试,但不能解释为这些模型在 H2O 充分微调后的上限。Dyn-HaMR 已通过官方定义的 per-video TTO 适配测试序列。", + "- HandDGP 官方仓库只有 inference/evaluation;WiLoR/Hamba 只保留训练模块而缺少完整 runner/config;HaWoR 官方 README 仍写明训练代码将后续发布;PAD-Hand 仅发布 demo。自行编写微调器会形成新的派生训练配方,不能标成官方 fine-tuned baseline。", + "- 真正的 H2O fine-tuning 对照需要统一 H2O train、冻结 validation/test、同 detector/K、相同输入预算和选模规则,并同时报告 pretrained 与 fine-tuned;当前公开资产不足以严格完成这一实验。", + "- WiLoR/HaWoR 声明 CC BY-NC-ND 4.0,Hamba 声明 CC BY-NC 4.0;WildHands、QORT 与 PAD-Hand 在审计 commit 未见明确 LICENSE。MANO/Ultralytics 等依赖另有许可。当前下载与运行仅用于本地研究复评,不代表可重分发模型资产。", + "", + "## 已录用开源候选审计", + "", + "| 工作 | 状态 | 本报告处理 |", + "|---|---|---|", + "| PAD-Hand | CVPR 2026 Highlight;官方 demo 与 checkpoint | 纳入 zero-shot temporal 表;与相同 WiLoR initializer 成对报告。 |", + "| WildHands | ECCV 2024;官方代码与 checkpoint;论文明确 H2O zero-shot | 纳入零样本量化表。 |", + "| Hamba | NeurIPS 2024;官方推理代码与 checkpoint | 纳入零样本量化表;使用共同 detector 与官方 crop/initial-regressor。 |", + "| ViDiHand | 2026-06 arXiv;1.3B video diffusion + 37M decoder;metric two-hand camera-space 输出 | 方法与 H2O 高度匹配,但官方仓库仅 README,明确写明 code will be released soon;当前无 checkpoint/推理/训练代码。 |", + "| Dyn-HaMR | CVPR 2025 Highlight;官方代码、HaMeR 权重与 TTO 配置 | 已按每个连续 run、静态已知 H2O K 完整运行,单列 TTO 赛道;不是可微调 feed-forward baseline。 |", + "| HandDGP | ECCV 2024;官方 FreiHAND checkpoint 与 camera-space 推理 | 已用发布权重、官方 rectification/DGP 和共同 detector 纳入 zero-shot 表;仓库无训练入口。 |", + "| EgoHandICL | ICLR 2026;官方仓库 commit `16e5690` 含名义训练/推理文件 | 推理脚本引用未发布的 `handicl` 核心 package;Hugging Face 仅有数据/标注压缩包而无 checkpoint,README 还含 `` 与空权重路径,不能形成可审计推理或微调。 |", + "| MaskHand | ICCV 2025 | 项目页只有论文与演示;截至 2026-07-20,论文所指官方 GitHub 返回 404,无 checkpoint,无法同权重复评。 |", + "| Pose-Guided Temporal Enhancement | CVPR 2025 | 未找到作者公开的推理仓库或 checkpoint。 |", + "| OmniHands | ACM TOG 2026;官方代码与 image/video/multiview checkpoints | 任务核心是双手交互及 temporal/multiview,发布 demo 的相机输出/评估协议与本表单手 camera-space 协议不同,暂不混排。 |", + "| Enhancing Monocular 3D Hand Reconstruction with Learned Texture Priors | WACV 2026;公开 texture-supervised HaMeR 权重 | 仓库仍将完整 code release 标为未完成;待稳定发布后可按 HaMeR camera adapter 加入。 |", + "| HandOS | CVPR 2025 | 官方项目当前未提供可下载 checkpoint,无法做同权重复评。 |", + "| PS-HPME / Pseudo-Stereo-Hand | Knowledge-Based Systems 2026;目标为单目 camera-space mesh | 论文给出的官方 GitHub 地址在本次审计返回 404,无法下载代码或 checkpoint。 |", + "| SesaHand | ICLR 2026;生成数据增强重建 | 不是独立重建推理模型,官方仓库的 pretrained model 与 samples 仍标为 TBD。 |", + "| POEM-v2 | TPAMI 2025;代码/权重公开 | 多视图方法;当前冻结 H2O 产物只有 cam4,不能伪装成公平单目基线。 |", + "", + "## 公开实现与资产溯源", + "", + ]) + for evaluation in evaluations: + metadata = evaluation["report"]["prediction_metadata"] + lines.append(f"### {evaluation['label']}") + lines.append("") + if metadata.get("official_repository"): + lines.append(f"- Official repository: {metadata['official_repository']}") + lines.append(f"- Repository commit: `{metadata['repository_commit']}`") + elif metadata.get("training_commit"): + lines.append(f"- Training commit: `{metadata['training_commit']}`") + lines.append( + f"- Repository commit at export: `{metadata['repository_commit_at_export']}`" + ) + checkpoint = metadata.get("checkpoint", metadata.get("hamer_checkpoint")) + checkpoint_hash = metadata.get( + "checkpoint_sha256", metadata.get("hamer_checkpoint_sha256") + ) + lines.append(f"- Checkpoint: `{checkpoint}`") + lines.append(f"- Checkpoint SHA256: `{checkpoint_hash}`") + if metadata.get("detector_checkpoint"): + lines.append(f"- Detector: `{metadata['detector_checkpoint']}`") + lines.append( + f"- Detector SHA256: `{metadata['detector_checkpoint_sha256']}`" + ) + if metadata.get("base_wilor_checkpoint"): + lines.append( + f"- Base WiLoR commit: `{metadata['base_wilor_repository_commit']}`" + ) + lines.append(f"- Base WiLoR: `{metadata['base_wilor_checkpoint']}`") + lines.append( + f"- Base WiLoR SHA256: `{metadata['base_wilor_checkpoint_sha256']}`" + ) + lines.append(f"- Evaluation JSON SHA256: `{evaluation['summary']['evaluation_json_sha256']}`") + lines.append("") + lines.extend([ + "## 可复现产物", + "", + "- `comparison.csv`: 完整主表机器可读版本。", + "- `paired_take_bootstrap.csv`: 全指标配对差值与 CI。", + "- `pad_hand_vs_wilor_paired_take_bootstrap.csv`: PAD-Hand refinement 相对同一 WiLoR initializer 的配对差值。", + "- `dynhamr_vs_hawor_paired_take_bootstrap.csv`: Dyn-HaMR TTO 相对最强 zero-shot 前向 HaWoR 的直接配对差值。", + "- `INFERENCE_SPEED_REPORT.md`、`speed_comparison.csv` 与 `speed_report.json`: 同机统一推理速度、原始 timing 哈希和 Dyn-HaMR TTO 开销拆分。", + "- `report.json`: 汇总、论文协议旁注和所有输入文件 hash。", + "- `visual_audit/projection_contact_sheet.jpg` 与 `visual_audit/visual_audit.json`: 固定样本投影和全量正深度/画内统计。", + "- 各 evaluation 目录保留逐 hand-frame 与逐 temporal-transition CSV,可重算全部统计。", + "", + ]) + return "\n".join(lines) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument( + "--evaluation", + action="append", + required=True, + help="LABEL=directory containing evaluation.json and metric CSV files", + ) + parser.add_argument("--foundation-label", default="FoundationHand-Phase3") + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--ground-truth", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--bootstrap-seed", type=int, default=20260716) + parser.add_argument("--bootstrap-samples", type=int, default=10_000) + args = parser.parse_args() + + evaluations = [] + labels = set() + for spec in args.evaluation: + label, separator, raw_directory = spec.partition("=") + if not separator or not label or not raw_directory: + raise ValueError(f"Invalid --evaluation value: {spec}") + if label in labels: + raise ValueError(f"Duplicate evaluation label: {label}") + labels.add(label) + evaluations.append(load_evaluation(label, Path(raw_directory).resolve())) + if args.foundation_label not in labels: + raise ValueError(f"Missing foundation label: {args.foundation_label}") + baseline = next( + evaluation for evaluation in evaluations + if evaluation["label"] == args.foundation_label + ) + paired_rows: list[dict[str, Any]] = [] + for evaluation in evaluations: + if evaluation is baseline or evaluation["label"] == "WiLoR-native-camera": + continue + contrasts = paired_take_bootstrap( + baseline["frame_rows"], + evaluation["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + paired_rows.extend({ + "baseline": args.foundation_label, + "candidate": evaluation["label"], + **contrast, + } for contrast in contrasts) + + refinement_rows: list[dict[str, Any]] = [] + if "WiLoR-H2O-K" in labels and "PAD-Hand-WiLoR" in labels: + wilor = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "WiLoR-H2O-K" + ) + pad_hand = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "PAD-Hand-WiLoR" + ) + refinement_rows = [ + { + "baseline": "WiLoR-H2O-K", + "candidate": "PAD-Hand-WiLoR", + **contrast, + } + for contrast in paired_take_bootstrap( + wilor["frame_rows"], + pad_hand["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + ] + + dynhamr_hawor_rows: list[dict[str, Any]] = [] + if "HaWoR-camera" in labels and "Dyn-HaMR-TTO" in labels: + hawor = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "HaWoR-camera" + ) + dynhamr = next( + evaluation for evaluation in evaluations + if evaluation["label"] == "Dyn-HaMR-TTO" + ) + dynhamr_hawor_rows = [ + { + "baseline": "HaWoR-camera", + "candidate": "Dyn-HaMR-TTO", + **contrast, + } + for contrast in paired_take_bootstrap( + hawor["frame_rows"], + dynhamr["frame_rows"], + seed=args.bootstrap_seed, + samples=args.bootstrap_samples, + ) + ] + + args.output_dir.mkdir(parents=True, exist_ok=True) + comparison_rows = [evaluation["summary"] for evaluation in evaluations] + write_csv_rows(args.output_dir / "comparison.csv", comparison_rows) + write_csv_rows(args.output_dir / "paired_take_bootstrap.csv", paired_rows) + if refinement_rows: + write_csv_rows( + args.output_dir / "pad_hand_vs_wilor_paired_take_bootstrap.csv", + refinement_rows, + ) + if dynhamr_hawor_rows: + write_csv_rows( + args.output_dir / "dynhamr_vs_hawor_paired_take_bootstrap.csv", + dynhamr_hawor_rows, + ) + manifest = args.manifest.resolve() + ground_truth = args.ground_truth.resolve() + speed_report_path = args.output_dir / "speed_report.json" + speed_report = ( + json.loads(speed_report_path.read_text(encoding="utf-8")) + if speed_report_path.is_file() + else None + ) + payload = { + "status": "complete", + "official_test_used": False, + "split_role": "official_validation", + "manifest": str(manifest), + "manifest_sha256": sha256(manifest), + "ground_truth": str(ground_truth), + "ground_truth_sha256": sha256(ground_truth), + "bootstrap_seed": args.bootstrap_seed, + "bootstrap_samples": args.bootstrap_samples, + "comparison": comparison_rows, + "paired_take_bootstrap": paired_rows, + "pad_hand_vs_wilor_paired_take_bootstrap": refinement_rows, + "dynhamr_vs_hawor_paired_take_bootstrap": dynhamr_hawor_rows, + "paper_reported_context": { + "QORT-Former": "H2O test MEE left/right 20.1/19.9 mm", + "WiLoR": "FreiHAND PA-MPJPE/PA-MPVPE 5.5/5.1 mm; HO3D 7.5/7.7 mm", + "HaWoR": "DexYCB PA-MPJPE 4.76 mm, AUC 90.5", + "WildHands": "H2O validation zero-shot MPJPE/MRRPE 31.08/49.49 mm", + "Hamba": "FreiHAND no-TTA PA-MPJPE/PA-MPVPE 5.8/5.5 mm", + "PAD-Hand": ( + "DexYCB WiLoR->PAD-Hand PA-MPJPE 4.88->4.63 mm, " + "MPJPE 12.75->10.56 mm, ACCEL 6.70->3.34" + ), + "HandDGP": "FreiHAND camera-space MJE/MVE 46.3/46.3 mm", + "Dyn-HaMR": "global 4D hand-motion reconstruction on dynamic-camera videos", + }, + } + if speed_report is not None: + payload["speed_benchmark"] = { + "path": str(speed_report_path.resolve()), + "sha256": sha256(speed_report_path), + "status": speed_report.get("status"), + } + (args.output_dir / "report.json").write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + report_text = markdown_report( + evaluations, + paired_rows, + refinement_rows, + dynhamr_hawor_rows, + speed_report, + manifest=manifest, + manifest_hash=payload["manifest_sha256"], + ground_truth=ground_truth, + ground_truth_hash=payload["ground_truth_sha256"], + bootstrap_seed=args.bootstrap_seed, + bootstrap_samples=args.bootstrap_samples, + ) + (args.output_dir / "SOTA_EVALUATION_REPORT.md").write_text( + report_text, encoding="utf-8" + ) + print(json.dumps({ + "models": [evaluation["label"] for evaluation in evaluations], + "output_dir": str(args.output_dir.resolve()), + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_sota_speed.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_sota_speed.py new file mode 100644 index 0000000000000000000000000000000000000000..11ebd0914d721320b8787f1e806411a282dab0cc --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/summarize_sota_speed.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Summarize synchronized external-baseline speed measurements.""" + +from __future__ import annotations + +import argparse +import csv +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np + + +SETTINGS = { + "FoundationHand-T8": ("FoundationHand", "temporal_clip", "RGB+Depth+K, T=8, clip batch=1"), + "QORT-b1": ("QORT-Former", "framewise", "batch=1"), + "QORT-b16": ("QORT-Former", "batched", "batch=16"), + "WiLoR-b1": ("WiLoR", "framewise", "detector/reconstruction batch=1"), + "WiLoR-b16": ("WiLoR", "batched", "detector/reconstruction batch=16"), + "HaWoR-T16": ("HaWoR", "offline_temporal", "tracked temporal window=16"), + "Dyn-HaMR-TTO": ("Dyn-HaMR", "test_time_optimization", "one 94-frame run"), +} + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def write_csv(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--timing", action="append", required=True, help="SETTING=timing.json") + parser.add_argument("--foundation-profile", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + + grouped: dict[str, list[tuple[Path, dict[str, Any]]]] = {} + for spec in args.timing: + label, separator, raw_path = spec.partition("=") + if not separator or label not in SETTINGS or not raw_path: + raise ValueError(f"Invalid timing specification: {spec}") + path = Path(raw_path).resolve() + payload = json.loads(path.read_text(encoding="utf-8")) + if payload.get("schema_version") != "foundation_hand_external_speed_v1": + raise ValueError(f"Unexpected timing schema: {path}") + if int(payload.get("frames", 0)) != 94: + raise ValueError(f"Benchmark must contain exactly 94 frames: {path}") + grouped.setdefault(label, []).append((path, payload)) + + missing = set(SETTINGS) - set(grouped) + if missing: + raise ValueError(f"Missing benchmark settings: {sorted(missing)}") + + rows: list[dict[str, Any]] = [] + raw_measurements: dict[str, list[dict[str, Any]]] = {} + for label, (model, mode, setting) in SETTINGS.items(): + measurements = grouped[label] + fps = np.asarray([item[1]["frames_per_second"] for item in measurements]) + seconds = np.asarray([item[1]["processing_seconds"] for item in measurements]) + row = { + "setting_id": label, + "model": model, + "mode": mode, + "setting": setting, + "repeats": len(measurements), + "frames_per_repeat": 94, + "median_processing_seconds": float(np.median(seconds)), + "median_fps": float(np.median(fps)), + "min_fps": float(fps.min()), + "max_fps": float(fps.max()), + "amortized_ms_per_frame": float(1000.0 / np.median(fps)), + } + rows.append(row) + raw_measurements[label] = [ + { + "path": str(path), + "sha256": sha256(path), + **payload, + } + for path, payload in measurements + ] + + by_label = {row["setting_id"]: row for row in rows} + dyn = raw_measurements["Dyn-HaMR-TTO"][0] + foundation_profile_path = args.foundation_profile.resolve() + foundation_profile = json.loads( + foundation_profile_path.read_text(encoding="utf-8") + ) + foundation_forward_ms = float(foundation_profile["latency"]["p50_ms"]) + foundation_model_fps = 8_000.0 / foundation_forward_ms + dyn_initializer_fps = dyn["frames"] / dyn["initialization_seconds"] + dyn_optimizer_fraction = dyn["optimization_seconds"] / dyn["processing_seconds"] + throughput_order = [ + "FoundationHand-T8", "QORT-b16", "WiLoR-b16", "HaWoR-T16", "Dyn-HaMR-TTO" + ] + + args.output_dir.mkdir(parents=True, exist_ok=True) + write_csv(args.output_dir / "speed_comparison.csv", rows) + report_payload = { + "status": "complete", + "schema_version": "foundation_hand_external_speed_report_v1", + "date": "2026-07-21", + "hardware": "NVIDIA GeForce RTX 4090", + "physical_gpu_policy": ( + "QORT/WiLoR/HaWoR repeats used idle physical GPU0; " + "Dyn-HaMR used idle physical GPU1; all GPUs are identical RTX 4090 cards" + ), + "workload": "first official H2O validation contiguous run (94 RGB frames)", + "timed_scope": ( + "RGB decode/preprocessing through final camera-space conversion; " + "model loading and prediction serialization excluded" + ), + "cuda_synchronized": True, + "rows": rows, + "raw_measurements": raw_measurements, + "foundation_model_only_profile": { + "path": str(foundation_profile_path), + "sha256": sha256(foundation_profile_path), + "p50_ms_per_t8_clip": foundation_forward_ms, + "amortized_frames_per_second": foundation_model_fps, + "scope": foundation_profile["latency"]["scope"], + }, + "dynhamr_diagnostics": { + "initializer_fps": dyn_initializer_fps, + "initializer_seconds": dyn["initialization_seconds"], + "optimization_seconds": dyn["optimization_seconds"], + "optimizer_fraction": dyn_optimizer_fraction, + "root_iterations": dyn["root_iterations"], + "smooth_iterations": dyn["smooth_iterations"], + }, + } + (args.output_dir / "speed_report.json").write_text( + json.dumps(report_payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + lines = [ + "# FoundationHand 外部方法推理速度复评", + "", + "## 结论", + "", + ( + f"在相同 94 帧 H2O RGB 连续片段和 RTX 4090 上,批处理吞吐排序为 " + f"**FoundationHand ({by_label['FoundationHand-T8']['median_fps']:.2f} FPS) > " + f"QORT-Former ({by_label['QORT-b16']['median_fps']:.2f} FPS) > " + f"WiLoR ({by_label['WiLoR-b16']['median_fps']:.2f} FPS) > " + f"HaWoR ({by_label['HaWoR-T16']['median_fps']:.2f} FPS) > " + f"Dyn-HaMR ({by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS)**。" + ), + "", + ( + "QORT/WiLoR 是逐帧前向方法;FoundationHand 使用 T=8 RGB+Depth+K clip;" + "HaWoR 必须看到时序窗口/连续 track;" + "Dyn-HaMR 对整段测试视频优化。因此 FPS 可比较系统计算成本,但 HaWoR/Dyn-HaMR 的" + "摊销 ms/frame 不是因果单帧响应延迟。" + ), + "", + "## 端到端摊销吞吐", + "", + "计时包含 RGB 解码、官方预处理、需要的 detector、重建和 camera-space 转换;不包含权重加载与 NPZ 写盘。", + "", + "| 方法 | 模式 | 设置 | 重复 | Median FPS | 范围 | 摊销 ms/frame |", + "|---|---|---|---:|---:|---:|---:|", + ] + for label in throughput_order: + row = by_label[label] + lines.append( + f"| {row['model']} | {row['mode']} | {row['setting']} | {row['repeats']} | " + f"{row['median_fps']:.3f} | {row['min_fps']:.3f}-{row['max_fps']:.3f} | " + f"{row['amortized_ms_per_frame']:.2f} |" + ) + lines.extend([ + "", + "## Batch-1 在线前向", + "", + "| 方法 | Median FPS | 范围 | ms/frame |", + "|---|---:|---:|---:|", + ]) + for label in ("QORT-b1", "WiLoR-b1"): + row = by_label[label] + lines.append( + f"| {row['model']} | {row['median_fps']:.3f} | " + f"{row['min_fps']:.3f}-{row['max_fps']:.3f} | " + f"{row['amortized_ms_per_frame']:.2f} |" + ) + lines.extend([ + "", + "HaWoR 和 Dyn-HaMR 不列入 batch-1 在线表:前者是非因果 tracked temporal inference,后者是整段 TTO。", + "", + "## FoundationHand 开销拆分", + "", + ( + f"FoundationHand 完整 RGB+Depth+K 数据路径的中位吞吐为 " + f"{by_label['FoundationHand-T8']['median_fps']:.2f} FPS(" + f"{by_label['FoundationHand-T8']['amortized_ms_per_frame']:.2f} ms/frame 摊销)。" + f"独立的 100 次 GPU forward 计时 P50 为 {foundation_forward_ms:.2f} ms/T=8 clip," + f"等价于 {foundation_model_fps:.1f} frame/s 的纯模型吞吐;两者差额主要来自 RGB/Depth 解码、" + "640x368 预处理、worker 启动和 host-device/host result transfer。" + ), + "", + ( + "FoundationHand 的 T=8 需要先获得一个 8 帧窗口,因此上述 14.2 ms/frame 是系统吞吐," + "不是零缓冲的单帧响应延迟。" + ), + "", + "## Dyn-HaMR 开销拆分", + "", + ( + f"Dyn-HaMR 的 detector+HaMeR 初始化耗时 {dyn['initialization_seconds']:.2f} s," + f"相当于 {dyn_initializer_fps:.2f} FPS;32 次 Root + 300 次 Smooth TTO 耗时 " + f"{dyn['optimization_seconds']:.2f} s,占完整推理时间 {100 * dyn_optimizer_fraction:.2f}%。" + f"完整 94 帧用时 {dyn['processing_seconds']:.2f} s,即 " + f"{by_label['Dyn-HaMR-TTO']['median_fps']:.3f} FPS。" + ), + "", + "## 公平性边界", + "", + "- FoundationHand/QORT/WiLoR/HaWoR 各重复 3 次并报告中位数和范围;Dyn-HaMR 因完整 TTO 昂贵,报告一次无缓存的完整官方优化。", + "- QORT/WiLoR 的 batch=16 数字是吞吐,不是单请求延迟。", + "- HaWoR 速度只覆盖本 SOTA 报告使用的 camera-space hand stage,不包含 DROID-SLAM、Metric3D 或 world-space infiller。", + "- FoundationHand 使用 RGB+metric Depth+K 且不需要 detector;外部方法为 RGB,因此这是已部署系统吞吐比较,不是输入模态等价的 backbone benchmark。", + "- Dyn-HaMR 使用已知静态 H2O K,因此不包含 VIPE/DROID-SLAM;包含与量化结果完全相同的 Root/Smooth TTO。", + "- FoundationHand/QORT/WiLoR/HaWoR 重复测量使用空闲物理 GPU0;Dyn-HaMR 使用空闲物理 GPU1。六张卡均为 RTX 4090。", + "- 这些是本机 release-code 系统测速,不应与论文在其他 GPU、分辨率或只计 model-forward 的 FPS 直接混排。", + "", + "## 可复现产物", + "", + "- `speed_comparison.csv`: 汇总速度表。", + "- `speed_report.json`: 原始 timing 路径、SHA256、计时范围与 Dyn-HaMR 分段耗时。", + "- 原始同步 timing JSON 位于 `artifacts/sota/speed_benchmark_20260721/`。", + "", + ]) + (args.output_dir / "INFERENCE_SPEED_REPORT.md").write_text( + "\n".join(lines), encoding="utf-8" + ) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_last2_candidate_admission.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_last2_candidate_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..ab89a845500fc88174c957806b8b2318ca3e8e0a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_last2_candidate_admission.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Forward-sync one frozen last-2 admission to its remote owner controller.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def upstream_files(plan: dict[str, Any]) -> list[Path]: + state_path = Path(plan["admission_controller_state"]) + report_path = Path(plan["admission_decision_report"]) + if not state_path.is_file() or not report_path.is_file(): + raise NotReady("last-2 upstream decision is not complete") + state = read_json(state_path) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != plan["admission_controller_plan_sha256"] + or state.get("decision_report", {}).get("path") != str(report_path.resolve()) + or state.get("decision_report", {}).get("sha256") != sha256(report_path) + or state.get("official_test_used") is not False + ): + raise NotReady("last-2 upstream decision is not complete") + files = [report_path, state_path] + stage8_state = Path(plan["stage8_controller_state"]) + if stage8_state not in files: + stage8 = read_json(stage8_state) + stage8_report = Path(stage8["decision_report"]["path"]) + files.extend((stage8_report, stage8_state)) + return files + + +def admission_payload(plan: dict[str, Any]) -> tuple[str, list[Path], list[dict[str, str]]]: + files = upstream_files(plan) + central_path = Path(plan["controller_states"]["taku3"]) + if not central_path.is_file(): + raise NotReady("central last-2 candidate has not consumed admission") + central = read_json(central_path) + decision_path = Path(plan["decision_report"]) + if central.get("status") == "complete" and central.get("admitted") is False: + if not decision_path.is_file() or central.get("decision_report", {}).get("sha256") != sha256(decision_path): + raise ValueError("central last-2 rejection binding differs") + return "rejected", files + [decision_path, central_path], [] + registry_path = Path(plan["training_registry"]) + if not registry_path.is_file() or not central.get("training_registry_sha256"): + raise NotReady("central last-2 training registry is not frozen") + if ( + central.get("plan_sha256") != sha256(Path(central["plan"])) + or central.get("training_registry") != str(registry_path.resolve()) + or central.get("training_registry_sha256") != sha256(registry_path) + or central.get("official_test_used") is not False + ): + raise ValueError("central last-2 controller binding differs") + registry = read_json(registry_path) + owners = condition_owners(registry, load_assignment(plan)) + conditions = registry.get("conditions", []) + if ( + registry.get("status") != "frozen_ready" + or registry.get("candidate") != plan["candidate"] + or len(conditions) != 7 + or sum(owner == "server_new" for owner in owners.values()) != 3 + or registry.get("official_test_used") is not False + ): + raise ValueError("last-2 registry contract differs") + files.extend((Path(plan["training_registry_state"]), + *[Path(item["config"]) for item in conditions], registry_path)) + prerequisites, seen = [], set() + for item in conditions: + pair = (item["initialization_checkpoint"], item["initialization_checkpoint_sha256"]) + if pair not in seen: prerequisites.append({"path": pair[0], "sha256": pair[1]}); seen.add(pair) + for item in registry["data_artifacts"]: + pair = (item["path"], item["sha256"]) + if pair not in seen: prerequisites.append({"path": pair[0], "sha256": pair[1]}); seen.add(pair) + return "admitted", files, prerequisites + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = Path(state).parent.parent / "server_new.log" + command = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_last2_candidate_controller --plan " + str(plan_path.resolve()) + + " --state " + state + " --machine server_new --poll-seconds 30 >> " + + str(log) + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: raise RuntimeError("remote last-2 controller launch failed") + time.sleep(2) + probe = subprocess.run([ + "ssh", "server_new", "pgrep", "-fo", + f"scripts.run_phase9_last2_candidate_controller.*last2_v3/{plan['candidate']}.*server_new.json", + ], stdout=subprocess.PIPE, text=True, check=False) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote last-2 controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + admission, files, prerequisites = admission_payload(plan) + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"central last-2 prerequisite differs: {path}") + if remote_sha256("server_new", path) != item["sha256"]: + raise ValueError(f"remote last-2 prerequisite differs: {path}") + registry = Path(plan["training_registry"]) + ordered = [path for path in files if path != registry] + ([registry] if registry in files else []) + installed = [install_file("server_new", path) for path in ordered] + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_last2_candidate_admission_sync_v1", + "status": "complete", "candidate": plan["candidate"], "admission": admission, + "completed_utc": utc_now(), "plan_sha256": sha256(plan_path), + "installed": installed, "immutable_prerequisites": prerequisites, + "registry_installed_last": registry in files, "remote_controller_pid": pid, + "official_test_used": False, "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_last2_candidate_admission_sync_v1", + "status": "waiting_for_candidate_admission", "candidate": plan["candidate"], + "watcher_pid": os.getpid(), "updated_utc": utc_now(), "detail": str(error), + "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_last2_training_completion.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_last2_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..6c9fa4facf8e3fbbde000e22bcab8de5e9a983fc --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_last2_training_completion.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Completion-only remote training handoff for an admitted last-2 candidate.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_resolution_training_completion import active_writer_pids +from scripts.sync_phase9_shared_augmentation_training_completion import ( + file_record, install, json_sha256, validate_terminal, +) + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(path: Path, plan: dict[str, Any]) -> None: + conditions = plan.get("conditions", []) + if ( + plan.get("schema_version") != "phase9_last2_training_completion_plan_v1" + or plan.get("status") != "frozen" + or plan.get("candidate") not in {"5e7", "1e6"} + or len(conditions) != 3 or len(set(conditions)) != 3 + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("target_step") != 405000 + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + ): + raise ValueError("last-2 training completion plan differs") + for binding in plan["bindings"]: + candidate = Path(binding["path"]) + if not candidate.is_file() or sha256(candidate) != binding["sha256"]: + raise ValueError(f"last-2 completion binding differs: {candidate}") + if not path.is_file(): raise ValueError("last-2 completion plan is unreadable") + + +def registry_jobs(plan: dict[str, Any]) -> tuple[Path, dict[str, Any], dict[str, Any]]: + path = Path(plan["training_registry"]["path"]) + if not path.is_file() or sha256(path) != plan["training_registry"]["sha256"]: + raise ValueError("last-2 training registry hash differs") + registry = read_json(path); jobs = {item["condition"]: item for item in registry["conditions"]} + owners = condition_owners(registry, load_assignment(plan)) + remote = [condition for condition in jobs if owners[condition] == "server_new"] + if ( + registry.get("status") != "frozen_ready" + or registry.get("candidate") != plan["candidate"] + or remote != plan["conditions"] + or registry.get("target_step") != 405000 + or registry.get("official_test_used") is not False + ): + raise ValueError("last-2 training registry contract differs") + return path, registry, jobs + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + registry_path, _, jobs = registry_jobs(plan) + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): raise NotReady("remote last-2 controller is missing") + controller = read_json(controller_path) + statuses = controller.get("training_statuses", {}) + if any(statuses.get(condition) != "complete" for condition in plan["conditions"]): + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("remote last-2 controller failed") + raise NotReady("remote last-2 training is still running") + if ( + controller.get("plan_sha256") != plan["controller_plan"]["sha256"] + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("official_test_used") is not False + ): + raise ValueError("remote last-2 controller binding differs") + root, state_root = Path(plan["release_root"]), Path(plan["training_state_root"]) + records, files = [], [] + for condition in plan["conditions"]: + job = jobs[condition]; state_path = state_root / f"{condition.lower()}.json" + state = read_json(state_path) + if state.get("queue_sha256") != sha256(registry_path): + raise ValueError(f"last-2 state registry binding differs: {condition}") + if active_writer_pids(job["output_dir"]): raise NotReady(f"last-2 writer exists: {condition}") + checkpoint, evidence = validate_terminal(job, state) + pair = [file_record(root, "checkpoint", checkpoint), + file_record(root, "training_state", state_path)] + files.extend(pair); records.append({ + "condition": condition, "role": job["role"], + "checkpoint_sha256": sha256(checkpoint), + "final_total_loss": float(evidence["metric"]["losses"]["total"]), + "metrics_sha256": evidence["metrics_sha256"], + "summary_sha256": evidence["summary_sha256"], "files": pair, + }) + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): return read_json(output) + records, files = source_records(plan) + value = { + "schema_version": "phase9_last2_training_completion_release_v1", + "status": "complete_immutable_release", "candidate": plan["candidate"], + "created_utc": utc_now(), "plan_sha256": sha256(plan_path), + "training_registry": plan["training_registry"], "release_root": plan["release_root"], + "conditions": records, "files": files, "file_count": 6, + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, "live_reverse_sync_performed": False, + "results_before_terminal_states": True, "official_test_used": False, + } + atomic_json(output, value); os.chmod(output, 0o444) + for item in files: os.chmod(item["absolute_path"], 0o444) + return value + + +def fetch(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run(["ssh", "server_new", "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, check=False) + if result.returncode: raise NotReady("remote last-2 release is unavailable") + return json.loads(result.stdout) + + +def validate_release(plan_path: Path, plan: dict[str, Any], value: dict[str, Any]) -> None: + files = value.get("files", []) + if ( + value.get("schema_version") != "phase9_last2_training_completion_release_v1" + or value.get("status") != "complete_immutable_release" + or value.get("candidate") != plan["candidate"] + or value.get("plan_sha256") != sha256(plan_path) + or value.get("training_registry") != plan["training_registry"] + or [item.get("condition") for item in value.get("conditions", [])] != plan["conditions"] + or len(files) != 6 or len({item.get("path") for item in files}) != 6 + or value.get("results_before_terminal_states") is not True + or value.get("official_test_used") is not False + ): + raise ValueError("last-2 immutable release differs") + + +def central_ready(plan: dict[str, Any]) -> bool: + path = Path(plan["training_completion_state"]) + if not path.is_file(): return False + value = read_json(path) + return (value.get("status") == "complete" and value.get("candidate") == plan["candidate"] + and value.get("training_registry_sha256") == plan["training_registry"]["sha256"] + and value.get("official_test_used") is False) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): return read_json(output) + release = fetch(plan); validate_release(plan_path, plan, release) + installed = install(plan, release) + deadline = time.monotonic() + 120 + while time.monotonic() < deadline and not central_ready(plan): time.sleep(2) + if not central_ready(plan): raise TimeoutError("central last-2 training did not converge") + value = { + "schema_version": "phase9_last2_training_completion_receive_v1", + "status": "complete", "candidate": plan["candidate"], "completed_utc": utc_now(), + "plan_sha256": sha256(plan_path), "release_sha256": json_sha256(release), + "installed": installed, "file_count": 6, "total_bytes": release["total_bytes"], + "results_before_terminal_states": True, "official_test_used": False, + } + atomic_json(output, value); return value + + +def main() -> None: + parser = argparse.ArgumentParser(); parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + try: validate_plan(args.plan, plan) + except ValueError as error: parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True); deadline = time.monotonic() + args.wait_timeout_seconds + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + value = publish(args.plan, plan) if args.role == "publish" else receive(args.plan, plan) + print(json.dumps(value, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(Path(f"{target}.watcher.json"), { + "schema_version": "phase9_last2_training_completion_watcher_v1", + "status": "waiting_for_terminal_source", "candidate": plan["candidate"], + "role": args.role, "watcher_pid": os.getpid(), "updated_utc": utc_now(), + "detail": str(error), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_resolution_evaluation_completion.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_resolution_evaluation_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..7213c888087d9e7daec2af464ac979afd0e504fa --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_resolution_evaluation_completion.py @@ -0,0 +1,450 @@ +#!/usr/bin/env python3 +"""Publish and import terminal server_new Stage 7 evaluation evidence.""" + +from __future__ import annotations + +import argparse +from collections import Counter +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_resolution_evaluation_worker import evaluation_complete +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +class NotReady(RuntimeError): + """A healthy source dependency has not reached its terminal state.""" + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: dict[str, Any]) -> str: + payload = (json.dumps(value, indent=2) + "\n").encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + if ( + plan.get("schema_version") + != "phase9_resolution_evaluation_completion_release_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or scientific.get("amendment_scope") + != "terminal_evaluation_state_and_result_handoff_only" + or any( + scientific.get(key) is not False + for key in ( + "model_changed", "data_changed", "seed_changed", + "metric_changed", "selection_gate_changed", + ) + ) + ): + raise ValueError("resolution evaluation completion plan contract differs") + for key in ( + "release_root", "staging_root", "release_state", "receive_state", + ): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution evaluation completion {key} is not /SSD2") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution evaluation completion binding differs: {path}") + if not plan_path.is_file(): + raise ValueError("resolution evaluation completion plan is unreadable") + + +def remote_inventory(plan: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]: + path = Path(plan["evaluation_plan"]["path"]) + if not path.is_file() or sha256(path) != plan["evaluation_plan"]["sha256"]: + raise ValueError("resolution evaluation plan hash differs") + dynamic = read_json(path) + workers = [item for item in dynamic["workers"] if item["owner"] == "server_new"] + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + assigned = [identifier for worker in workers for identifier in worker["evaluation_ids"]] + if ( + len(dynamic["evaluations"]) != 25 + or len(dynamic["workers"]) != 10 + or len(workers) != 4 + or len(assigned) != 9 + or len(set(assigned)) != 9 + or any(evaluations[identifier]["training_role"] not in { + "loso_subject2", "loso_subject3", "lofamily_k", + } for identifier in assigned) + or dynamic.get("official_test_used") is not False + or dynamic.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new resolution evaluation ownership differs") + return dynamic, workers + + +def active_evaluator_pids(evaluation_id: str, proc_root: Path = Path("/proc")) -> list[int]: + result = [] + token = f"--evaluation-id {evaluation_id}" + for entry in proc_root.iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (FileNotFoundError, PermissionError, ProcessLookupError, UnicodeDecodeError): + continue + if "scripts.evaluate_phase7_external" in command and token in command: + result.append(int(entry.name)) + return sorted(result) + + +def release_file(root: Path, kind: str, path: Path) -> dict[str, Any]: + if not path.is_file() or path.is_symlink() or root not in path.resolve().parents: + raise ValueError(f"resolution evaluation release artifact differs: {path}") + return { + "kind": kind, + "path": str(path.resolve().relative_to(root.resolve())), + "absolute_path": str(path.resolve()), + "bytes": path.stat().st_size, + "sha256": sha256(path), + } + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + dynamic, workers = remote_inventory(plan) + dynamic_hash = plan["evaluation_plan"]["sha256"] + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): + raise NotReady("server_new evaluation controller state is missing") + controller = read_json(controller_path) + if controller.get("status") not in {"complete_local", "complete"}: + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("server_new evaluation controller failed") + raise NotReady("server_new evaluation controller is still running") + if ( + controller.get("machine") != "server_new" + or controller.get("evaluation_plan_sha256") != dynamic_hash + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new evaluation controller binding differs") + + root = Path(plan["release_root"]) + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + records = [] + files = [] + for worker in workers: + state_path = Path(worker["state"]) + if not state_path.is_file(): + raise NotReady(f"server_new evaluation worker is missing: {worker['id']}") + state = read_json(state_path) + if state.get("status") != "complete": + if str(state.get("status", "")).startswith("failed_terminal"): + raise ValueError(f"server_new evaluation worker failed: {worker['id']}") + raise NotReady(f"server_new evaluation worker is still running: {worker['id']}") + if ( + state.get("worker") != worker["id"] + or state.get("owner") != "server_new" + or state.get("plan_sha256") != dynamic_hash + or state.get("assigned_evaluation_ids") != worker["evaluation_ids"] + or state.get("completed_ids") != worker["evaluation_ids"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError(f"server_new evaluation worker binding differs: {worker['id']}") + files.append(release_file(root, "worker_state", state_path)) + for identifier in worker["evaluation_ids"]: + if active_evaluator_pids(identifier): + raise NotReady(f"server_new evaluator still exists: {identifier}") + item = evaluations[identifier] + if not evaluation_complete(item): + raise ValueError(f"server_new evaluation result differs: {identifier}") + report_path = Path(item["output_dir"]) / "evaluation.json" + report = read_json(report_path) + result_files = [release_file(root, "evaluation_report", report_path)] + for key in ("raw_predictions", "per_hand_rows", "take_metrics"): + artifact = report[key] + path = Path(artifact["path"]) + record = release_file(root, key, path) + if record["sha256"] != artifact["sha256"]: + raise ValueError(f"server_new result artifact hash differs: {identifier}") + result_files.append(record) + files.extend(result_files) + records.append({ + "evaluation_id": identifier, + "worker": worker["id"], + "checkpoint_sha256": item["checkpoint_sha256"], + "config_sha256": item["config_sha256"], + "cache_manifest_sha256": item["cache_manifest_sha256"], + "clips": report["clips"], "frames": report["frames"], + "wall_seconds": report["runtime"]["wall_seconds"], + "gpu_hours": report["runtime"]["wall_seconds"] / 3600.0, + "evaluation_report_sha256": sha256(report_path), + "files": result_files, + }) + files.append(release_file(root, "controller_state", controller_path)) + paths = [item["path"] for item in files] + if len(records) != 9 or len(files) != 41 or len(paths) != len(set(paths)): + raise ValueError("server_new evaluation release inventory differs") + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + existing = read_json(output) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution evaluation release differs") + records, files = source_records(plan) + result = { + "schema_version": "phase9_resolution_evaluation_completion_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "destination_owner": "taku3", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_root": str(Path(plan["release_root"]).resolve()), + "evaluation_plan": plan["evaluation_plan"], + "evaluations": records, "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "results_before_terminal_states": True, + "single_writer_per_output": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, result) + os.chmod(output, 0o444) + for item in files: + os.chmod(item["absolute_path"], 0o444) + return result + + +def fetch_release(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", plan["source_host"], + "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + timeout=float(plan["ssh_timeout_seconds"]), + ) + if result.returncode: + raise NotReady("server_new evaluation completion release is unavailable") + try: + value = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise ValueError("server_new evaluation completion release is unreadable") from error + return value + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + files = release.get("files", []) + paths = [item.get("path") for item in files] + _, workers = remote_inventory(plan) + expected_ids = { + identifier for worker in workers for identifier in worker["evaluation_ids"] + } + records = release.get("evaluations", []) + record_ids = [item.get("evaluation_id") for item in records] + kind_counts = Counter(item.get("kind") for item in files) + if ( + release.get("schema_version") + != "phase9_resolution_evaluation_completion_release_v1" + or release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("destination_owner") != "taku3" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("evaluation_plan") != plan["evaluation_plan"] + or len(records) != 9 + or len(record_ids) != len(set(record_ids)) + or set(record_ids) != expected_ids + or len(files) != 41 or len(paths) != len(set(paths)) + or kind_counts != { + "evaluation_report": 9, "raw_predictions": 9, + "per_hand_rows": 9, "take_metrics": 9, + "worker_state": 4, "controller_state": 1, + } + or release.get("file_count") != 41 + or sum(item.get("bytes", -1) for item in files) != release.get("total_bytes") + or release.get("completion_only_reverse_release") is not True + or release.get("live_reverse_sync_performed") is not False + or release.get("results_before_terminal_states") is not True + or release.get("single_writer_per_output") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + ): + raise ValueError("resolution evaluation immutable release differs") + for value in paths: + path = Path(str(value)) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"unsafe resolution evaluation release path: {path}") + file_hashes = {(item["path"], item["sha256"]) for item in files} + for record in records: + result_files = record.get("files", []) + if ( + len(result_files) != 4 + or record.get("evaluation_report_sha256") + != next( + (item["sha256"] for item in result_files + if item.get("kind") == "evaluation_report"), None, + ) + or any((item.get("path"), item.get("sha256")) not in file_hashes + for item in result_files) + ): + raise ValueError("resolution evaluation release result binding differs") + + +def verify_file(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"resolution evaluation completion file differs: {path}") + return path + + +def install_release(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root = Path(plan["release_root"]) + staging = Path(plan["staging_root"]) + pending = [] + installed = [] + for item in release["files"]: + destination = root / item["path"] + if destination.exists(): + verify_file(root, item) + installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".pending_evaluation_release_files.txt" + file_list.write_text( + "".join(item["path"] + "\n" for item in pending), encoding="utf-8", + ) + result = subprocess.run([ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['source_host']}:{root.resolve()}/", f"{staging.resolve()}/", + ], check=False) + if result.returncode: + raise RuntimeError(f"resolution evaluation rsync failed: {result.returncode}") + for item in pending: + verify_file(staging, item) + order = {"evaluation_report": 0, "raw_predictions": 0, "per_hand_rows": 0, + "take_metrics": 0, "controller_state": 1, "worker_state": 2} + for item in sorted(pending, key=lambda value: (order[value["kind"]], value["path"])): + source = staging / item["path"] + destination = root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + raise ValueError(f"resolution evaluation destination appeared: {destination}") + os.replace(source, destination) + os.chmod(destination, 0o444) + verify_file(root, item) + installed.append({**item, "resumed_existing": False}) + return sorted(installed, key=lambda item: item["path"]) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): + existing = read_json(output) + if existing.get("status") == "complete" and existing.get("plan_sha256") == sha256(plan_path): + return existing + raise ValueError("existing resolution evaluation receive state differs") + release = fetch_release(plan) + validate_release(plan_path, plan, release) + installed = install_release(plan, release) + result = { + "schema_version": "phase9_resolution_evaluation_completion_receive_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state": plan["release_state"], + "release_sha256": json_sha256(release), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "installed": installed, + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "results_before_terminal_states": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, result) + return result + + +def wait_for_result( + role: str, plan_path: Path, plan: dict[str, Any], timeout_seconds: float, +) -> dict[str, Any]: + deadline = time.monotonic() + timeout_seconds + watcher_path = Path( + f"{plan['release_state' if role == 'publish' else 'receive_state']}.watcher.json" + ) + while True: + try: + return publish(plan_path, plan) if role == "publish" else receive(plan_path, plan) + except NotReady as error: + if timeout_seconds <= 0 or time.monotonic() >= deadline: + raise + atomic_json(watcher_path, { + "schema_version": "phase9_resolution_evaluation_completion_watcher_v1", + "status": "waiting_for_terminal_source", "role": role, + "watcher_pid": os.getpid(), "updated_utc": utc_now(), + "detail": str(error), "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "h2o_official_validation_used": False, "official_test_used": False, + }) + time.sleep(min(30.0, max(1.0, deadline - time.monotonic()))) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = wait_for_result( + args.role, args.plan, plan, args.wait_timeout_seconds, + ) + except Exception as error: + atomic_json(Path(f"{target}.failure.json"), { + "schema_version": "phase9_resolution_evaluation_completion_failure_v1", + "status": "failed_resumable", "updated_utc": utc_now(), + "role": args.role, "failure": f"{type(error).__name__}: {error}", + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, "official_test_used": False, + }) + raise + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_resolution_training_completion.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_resolution_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..34c74406bf5162cc0d980d780e5ef77133e4776c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_resolution_training_completion.py @@ -0,0 +1,569 @@ +#!/usr/bin/env python3 +"""Publish and import terminal server_new Stage 7 training evidence.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any +import zipfile + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +EXPECTED_CONDITIONS = ( + "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", + "S7R_J25_lofamily_k", +) +EXPECTED_STAGES = ("smoke2", "health2k", "matched_405000") + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan_path: Path, plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + if ( + plan.get("schema_version") + != "phase9_resolution_training_completion_release_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("read_only_after_publish") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or scientific.get("amendment_scope") + != "terminal_state_and_final_checkpoint_handoff_only" + or any( + scientific.get(key) is not False + for key in ( + "model_changed", "data_changed", "seed_changed", + "optimizer_changed", "horizon_changed", + "selection_gate_changed", + ) + ) + ): + raise ValueError("resolution training completion plan contract differs") + if tuple(item["condition"] for item in plan.get("conditions", [])) != EXPECTED_CONDITIONS: + raise ValueError("resolution training completion conditions differ") + for key in ("release_root", "staging_root"): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"resolution training completion {key} is not /SSD2") + if Path(plan["release_state"]).parts[:2] != ("/", "SSD2"): + raise ValueError("resolution training completion release state is not /SSD2") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution completion binding differs: {path}") + if sha256(plan_path) == "": + raise ValueError("resolution completion plan is unreadable") + + +def last_json_record(path: Path, tail_bytes: int = 1 << 20) -> dict[str, Any]: + with path.open("rb") as handle: + handle.seek(0, os.SEEK_END) + size = handle.tell() + handle.seek(max(0, size - tail_bytes)) + lines = handle.read().splitlines() + for line in reversed(lines): + if line.strip(): + value = json.loads(line) + if not isinstance(value, dict): + break + return value + raise ValueError(f"terminal metric record is unavailable: {path}") + + +def validate_condition_payload( + expected: dict[str, Any], job: dict[str, Any], state: dict[str, Any], + metric: dict[str, Any], summary: dict[str, Any], +) -> None: + marker = state.get("last_completed", {}) + attempts = state.get("attempts", []) + losses = metric.get("losses", {}) + if ( + state.get("status") != "complete" + or state.get("condition") != expected["condition"] + or state.get("queue_sha256") != expected["training_registry_sha256"] + or state.get("official_test_used") is not False + or tuple(state.get("completed_stages", [])) != EXPECTED_STAGES + or tuple(item.get("stage") for item in attempts) != EXPECTED_STAGES + or any(item.get("returncode") != 0 for item in attempts) + or marker.get("status") != "complete" + or marker.get("stage") != "matched_405000" + or marker.get("completed_step") != 405000 + or marker.get("checkpoint") != expected["checkpoint"] + or marker.get("checkpoint_sha256") != expected["checkpoint_sha256"] + or marker.get("config") != job["config"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or metric.get("step") != 405000 + or not isinstance(losses, dict) + or not losses + or any( + not isinstance(value, (int, float)) or not math.isfinite(float(value)) + for value in losses.values() + ) + or summary.get("status") != "completed" + or summary.get("completed_step") != 405000 + or summary.get("protocol_max_steps") != 405000 + or summary.get("registered_run_end_step") != 405000 + or summary.get("final_checkpoint") != expected["checkpoint"] + or summary.get("final_checkpoint_sha256") != expected["checkpoint_sha256"] + or summary.get("source_exposure_batches") + != job["expected_source_exposure_batches"] + or summary.get("official_test_used") is not False + ): + raise ValueError( + f"resolution terminal training evidence differs: {expected['condition']}" + ) + + +def writer_matches(command: str, output_dir: str) -> bool: + return ( + "scripts.train_phase7_external" in command + and f"--output-dir {output_dir}" in command + ) + + +def active_writer_pids(output_dir: str, proc_root: Path = Path("/proc")) -> list[int]: + result = [] + for entry in proc_root.iterdir(): + if not entry.name.isdigit(): + continue + try: + command = (entry / "cmdline").read_bytes().replace(b"\0", b" ").decode() + except (FileNotFoundError, PermissionError, UnicodeDecodeError, ProcessLookupError): + continue + if writer_matches(command, output_dir): + result.append(int(entry.name)) + return sorted(result) + + +def verify_checkpoint_archive(path: Path) -> None: + if not zipfile.is_zipfile(path): + raise ValueError(f"resolution final checkpoint archive differs: {path}") + with zipfile.ZipFile(path) as archive: + if not archive.namelist() or archive.testzip() is not None: + raise ValueError(f"resolution final checkpoint is truncated: {path}") + + +def validate_source_completion(plan: dict[str, Any]) -> list[dict[str, Any]]: + assignment = load_assignment(plan) + registry_path = Path(plan["training_registry"]["path"]) + registry = read_json(registry_path) + if sha256(registry_path) != plan["training_registry"]["sha256"]: + raise ValueError("resolution completion registry hash differs") + jobs = {item["condition"]: item for item in registry["conditions"]} + owners = condition_owners(registry, assignment) + controller_path = Path(plan["source_controller_state"]["path"]) + controller = read_json(controller_path) + if ( + sha256(controller_path) != plan["source_controller_state"]["sha256"] + or controller.get("status") != "complete_local" + or controller.get("machine") != "server_new" + or controller.get("plan_sha256") + != plan["training_controller_plan"]["sha256"] + or controller.get("training_registry_sha256") + != plan["training_registry"]["sha256"] + or controller.get("condition_statuses") + != {condition: "complete" for condition in EXPECTED_CONDITIONS} + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new resolution controller completion differs") + + records = [] + root = Path(plan["release_root"]) + for expected in plan["conditions"]: + condition = expected["condition"] + if condition not in jobs or owners.get(condition) != "server_new": + raise ValueError(f"resolution completion ownership differs: {condition}") + job = jobs[condition] + config = Path(job["config"]) + state_path = Path(expected["state"]) + checkpoint = Path(expected["checkpoint"]) + metrics = Path(expected["metrics"]) + summary_path = Path(expected["summary"]) + for path in (state_path, checkpoint, metrics, summary_path, config): + if not path.is_file() or path.is_symlink(): + raise ValueError(f"resolution terminal artifact differs: {path}") + if ( + sha256(config) != job["config_sha256"] + or sha256(state_path) != expected["state_sha256"] + or checkpoint.stat().st_size != expected["checkpoint_bytes"] + or sha256(checkpoint) != expected["checkpoint_sha256"] + or sha256(metrics) != expected["metrics_sha256"] + or sha256(summary_path) != expected["summary_sha256"] + ): + raise ValueError(f"resolution terminal artifact hash differs: {condition}") + if active_writer_pids(job["output_dir"]): + raise ValueError(f"resolution output still has a writer: {condition}") + state = read_json(state_path) + metric = last_json_record(metrics) + summary = read_json(summary_path) + validate_condition_payload(expected, job, state, metric, summary) + verify_checkpoint_archive(checkpoint) + condition_files = [] + for kind, path in (("checkpoint", checkpoint), ("training_state", state_path)): + if root not in path.parents: + raise ValueError(f"resolution release file is outside root: {path}") + condition_files.append({ + "kind": kind, + "path": str(path.relative_to(root)), + "absolute_path": str(path.resolve()), + "bytes": path.stat().st_size, + "sha256": sha256(path), + }) + records.append({ + "condition": condition, + "role": job["role"], + "completed_utc": state["completed_utc"], + "gpu_hours": state["gpu_hours_consumed"], + "wall_seconds": marker_wall_seconds(state), + "final_total_loss": float(metric["losses"]["total"]), + "metrics_sha256": expected["metrics_sha256"], + "summary_sha256": expected["summary_sha256"], + "checkpoint_archive_crc_verified": True, + "active_writer_pids": [], + "files": condition_files, + }) + return records + + +def marker_wall_seconds(state: dict[str, Any]) -> float: + marker = state.get("last_completed", {}) + value = marker.get("wall_seconds") + if not isinstance(value, (int, float)) or not math.isfinite(float(value)): + raise ValueError("resolution terminal wall time differs") + return float(value) + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + existing = read_json(output) + if ( + existing.get("status") == "complete_immutable_release" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution completion release differs") + conditions = validate_source_completion(plan) + files = [item for condition in conditions for item in condition["files"]] + paths = [item["path"] for item in files] + if len(paths) != 6 or len(set(paths)) != 6: + raise ValueError("resolution completion release inventory differs") + release = { + "schema_version": "phase9_resolution_training_completion_release_v1", + "status": "complete_immutable_release", + "created_utc": utc_now(), + "owner": "server_new", + "destination_owner": "taku3", + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "release_root": str(Path(plan["release_root"]).resolve()), + "source_controller_state": plan["source_controller_state"], + "conditions": conditions, + "files": files, + "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "read_only_after_publish": True, + "single_writer_per_output": True, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(output, release) + os.chmod(output, 0o444) + for item in files: + os.chmod(Path(item["absolute_path"]), 0o444) + return release + + +def fetch_remote_json(host: str, path: str, timeout: float) -> dict[str, Any]: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={int(timeout)}", + host, "cat", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + timeout=timeout + 2, check=False, + ) + if result.returncode: + raise ValueError("resolution completion release is unavailable") + try: + value = json.loads(result.stdout) + except json.JSONDecodeError as error: + raise ValueError("resolution completion release is unreadable") from error + if not isinstance(value, dict): + raise ValueError("resolution completion release is not an object") + return value + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + files = release.get("files", []) + paths = [item.get("path") for item in files] + if ( + release.get("schema_version") + != "phase9_resolution_training_completion_release_v1" + or release.get("status") != "complete_immutable_release" + or release.get("owner") != "server_new" + or release.get("destination_owner") != "taku3" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("completion_only_reverse_release") is not True + or release.get("live_reverse_sync_performed") is not False + or release.get("read_only_after_publish") is not True + or release.get("single_writer_per_output") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or len(files) != 6 + or len(paths) != len(set(paths)) + or release.get("file_count") != 6 + or sum(item.get("bytes", -1) for item in files) != release.get("total_bytes") + ): + raise ValueError("resolution completion immutable release differs") + expected = { + (item["state_sha256"], item["checkpoint_sha256"]) + for item in plan["conditions"] + } + observed = { + ( + next(file["sha256"] for file in item["files"] if file["kind"] == "training_state"), + next(file["sha256"] for file in item["files"] if file["kind"] == "checkpoint"), + ) + for item in release.get("conditions", []) + } + if expected != observed: + raise ValueError("resolution completion condition hashes differ") + for value in paths: + path = Path(str(value)) + if path.is_absolute() or ".." in path.parts: + raise ValueError(f"unsafe resolution completion release path: {path}") + + +def verify_record(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"] + ): + raise ValueError(f"resolution completion file differs: {path}") + return path + + +def validate_global_completion_payload( + controller: dict[str, Any], registry_sha256: str, + conditions: dict[str, dict[str, Any]], +) -> None: + expected = { + "S7R_J25_full", "S7R_J25_loso_subject1", "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", "S7R_J25_lofamily_h", + "S7R_J25_lofamily_k", "S7R_J25_lofamily_o", + } + if ( + controller.get("status") != "complete" + or controller.get("machine") != "taku3" + or controller.get("training_registry_sha256") != registry_sha256 + or controller.get("condition_statuses") + != {condition: "complete" for condition in sorted(expected)} + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + or set(conditions) != expected + or any( + state.get("status") != "complete" + or state.get("queue_sha256") != registry_sha256 + or state.get("last_completed", {}).get("completed_step") != 405000 + or state.get("official_test_used") is not False + for state in conditions.values() + ) + ): + raise ValueError("global resolution training completion differs") + + +def install_release(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root = Path(plan["release_root"]) + staging = Path(plan["staging_root"]) + pending = [] + installed = [] + for item in release["files"]: + destination = root / item["path"] + if destination.exists(): + verify_record(root, item) + installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + file_list = staging / ".pending_release_files.txt" + file_list.write_text( + "".join(item["path"] + "\n" for item in pending), encoding="utf-8", + ) + result = subprocess.run([ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{plan['source_host']}:{root.resolve()}/", f"{staging.resolve()}/", + ], check=False) + if result.returncode: + raise RuntimeError(f"resolution completion rsync failed: {result.returncode}") + for item in pending: + verify_record(staging, item) + for kind in ("checkpoint", "training_state"): + for item in pending: + if item["kind"] != kind: + continue + source = staging / item["path"] + destination = root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + if destination.exists(): + raise ValueError(f"resolution completion destination appeared: {destination}") + os.replace(source, destination) + os.chmod(destination, 0o444) + verify_record(root, item) + installed.append({**item, "resumed_existing": False}) + return sorted(installed, key=lambda item: item["path"]) + + +def backup_central_controller(plan: dict[str, Any]) -> dict[str, str]: + source = Path(plan["central_controller_state"]) + destination = Path(plan["central_controller_backup"]) + if destination.exists(): + return {"path": str(destination.resolve()), "sha256": sha256(destination)} + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + os.chmod(destination, 0o444) + return {"path": str(destination.resolve()), "sha256": sha256(destination)} + + +def wait_for_global_completion(plan: dict[str, Any]) -> dict[str, Any]: + deadline = time.monotonic() + float(plan["central_completion_timeout_seconds"]) + registry_hash = plan["training_registry"]["sha256"] + state_root = Path(plan["training_state_root"]) + while time.monotonic() < deadline: + controller = read_json(plan["central_controller_state"]) + registry = read_json(plan["training_registry"]["path"]) + states = { + item["condition"]: read_json( + state_root / f"{item['condition'].lower()}.json" + ) + for item in registry["conditions"] + } + try: + validate_global_completion_payload(controller, registry_hash, states) + except ValueError: + time.sleep(2) + continue + return controller + raise TimeoutError("central resolution training controller did not converge") + + +def receive(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + if state_path.is_file(): + existing = read_json(state_path) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == sha256(plan_path) + ): + return existing + raise ValueError("existing resolution completion receive state differs") + release = fetch_remote_json( + plan["source_host"], plan["release_state"], + float(plan["ssh_timeout_seconds"]), + ) + validate_release(plan_path, plan, release) + backup = backup_central_controller(plan) + installed = install_release(plan, release) + controller = wait_for_global_completion(plan) + result = { + "schema_version": "phase9_resolution_training_completion_receive_v1", + "status": "complete", + "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), + "plan_sha256": sha256(plan_path), + "release_state": plan["release_state"], + "release_sha256": sha256_bytes(release), + "file_count": release["file_count"], + "total_bytes": release["total_bytes"], + "installed": installed, + "central_controller_backup": backup, + "central_controller_state": { + "path": str(Path(plan["central_controller_state"]).resolve()), + "sha256": sha256(plan["central_controller_state"]), + "status": controller["status"], + }, + "completion_only_reverse_release": True, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, + "official_test_used": False, + } + atomic_json(state_path, result) + return result + + +def sha256_bytes(value: dict[str, Any]) -> str: + import hashlib + payload = (json.dumps(value, indent=2) + "\n").encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--state", type=Path) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(args.plan, plan) + except ValueError as error: + parser.error(str(error)) + expected = Path( + plan["release_state"] if args.role == "publish" else plan["receive_state"] + ) + if args.state and args.state.resolve() != expected.resolve(): + parser.error("resolution completion state path differs") + expected.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{expected}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + try: + result = publish(args.plan, plan) if args.role == "publish" else receive( + args.plan, plan, expected, + ) + except Exception as error: + failure = Path(f"{expected}.failure.json") + atomic_json(failure, { + "schema_version": "phase9_resolution_training_completion_failure_v1", + "status": "failed_resumable", + "updated_utc": utc_now(), + "role": args.role, + "plan": str(args.plan.resolve()), + "plan_sha256": sha256(args.plan), + "failure": f"{type(error).__name__}: {error}", + "h2o_official_validation_used": False, + "official_test_used": False, + }) + raise + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_resolution_training_handoff.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_resolution_training_handoff.py new file mode 100644 index 0000000000000000000000000000000000000000..e55e92fce4239842ceb0765c72f32f3d506032e7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_resolution_training_handoff.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Publish central Stage 7 readiness and registry to server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import json +from pathlib import Path +import subprocess +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + scientific = plan.get("scientific_contract", {}) + unchanged_fields = ( + "model_changed", + "data_changed", + "seed_changed", + "optimizer_changed", + "horizon_changed", + "selection_gate_changed", + ) + if ( + plan.get("schema_version") + != "phase9_resolution_distributed_training_handoff_amendment_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "taku3" + or plan.get("destination_owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("readiness_published_last") is not True + or plan.get("immutable_sync") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("server_new_physical_gpu_allowlist") != [0, 1, 2, 5] + or plan.get("external_owned_conditions") != [ + "S7R_J25_loso_subject2", + "S7R_J25_loso_subject3", + "S7R_J25_lofamily_k", + ] + or scientific.get("amendment_scope") + != "resource_scheduling_and_immutable_handoff_only" + or any(scientific.get(field) is not False for field in unchanged_fields) + ): + raise ValueError("resolution training handoff plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"resolution training handoff binding differs: {path}") + + +def ordered_handoff_files(plan: dict[str, Any]) -> list[dict[str, Any]]: + records = list(plan["files"]) + if ( + not records or records[-1].get("role") != "readiness" + or any(item.get("role") == "readiness" for item in records[:-1]) + or len({item["path"] for item in records}) != len(records) + ): + raise ValueError("resolution readiness must be published uniquely and last") + return records + + +def remote_sha256(host: str, path: str) -> str | None: + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "sha256sum", path], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode or not completed.stdout.strip(): + return None + return completed.stdout.split()[0] + + +def prepare_remote_parent(host: str, path: str) -> None: + parent = str(Path(path).parent) + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "mkdir", "-p", parent], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode: + detail = completed.stderr.strip() or f"returncode={completed.returncode}" + raise ValueError(f"cannot prepare resolution handoff parent {parent}: {detail}") + + +def validate_remote_cache_receive(plan: dict[str, Any]) -> None: + item = plan["remote_cache_receive_state"] + if remote_sha256(plan["destination_host"], item["path"]) != item["sha256"]: + raise ValueError("server_new cache receive state hash differs") + completed = subprocess.run( + ["ssh", "-o", "BatchMode=yes", plan["destination_host"], "cat", item["path"]], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False, + ) + if completed.returncode: + raise ValueError("server_new cache receive state is unreadable") + try: + state = json.loads(completed.stdout) + except json.JSONDecodeError as error: + raise ValueError("server_new cache receive state is unreadable") from error + if ( + state.get("status") != "complete" + or state.get("file_count") != item["file_count"] + or state.get("total_bytes") != item["total_bytes"] + or state.get("read_only") is not True + or state.get("live_reverse_sync_performed") is not False + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + ): + raise ValueError("server_new cache receive state contract differs") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(plan) + records = ordered_handoff_files(plan) + validate_remote_cache_receive(plan) + except ValueError as error: + parser.error(str(error)) + if args.state.resolve() != Path(plan["state"]).resolve(): + parser.error("resolution training handoff state differs") + if args.state.is_file(): + existing = read_json(args.state) + if ( + existing.get("status") == "complete" + and existing.get("plan_sha256") == sha256(args.plan) + ): + print(json.dumps(existing, indent=2)) + return + parser.error("existing resolution training handoff state differs") + published = [] + for item in records: + source = Path(item["path"]) + if not source.is_file() or sha256(source) != item["sha256"]: + parser.error(f"resolution handoff source differs: {source}") + try: + prepare_remote_parent(plan["destination_host"], str(source.resolve())) + except ValueError as error: + parser.error(str(error)) + completed = subprocess.run([ + "rsync", "-a", "--chmod=F444", str(source.resolve()), + f"{plan['destination_host']}:{source.resolve()}", + ], check=False) + if completed.returncode: + raise SystemExit(completed.returncode) + if remote_sha256(plan["destination_host"], str(source.resolve())) != item["sha256"]: + parser.error(f"resolution handoff remote hash differs: {source}") + published.append(item) + state = { + "schema_version": "phase9_resolution_training_handoff_state_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "destination": plan["destination_host"], "published": published, + "readiness_published_last": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(args.state, state) + print(json.dumps(state, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_shared_augmentation_admission.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_shared_augmentation_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..e4c3d14120047c2df37a4932378ce275eb8da7e8 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_shared_augmentation_admission.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Forward-sync frozen Stage 8 admission and start the remote owner controller.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def admission_files(plan: dict[str, Any]) -> tuple[list[Path], list[dict[str, str]]]: + controller_path = Path(plan["controller_states"]["taku3"]) + if not controller_path.is_file(): + raise NotReady("central Stage 8 controller state is missing") + controller = read_json(controller_path) + registry_path = Path(plan["training_registry"]) + if not registry_path.is_file() or not controller.get("training_registry_sha256"): + raise NotReady("central Stage 8 registry is not frozen yet") + if ( + controller.get("plan_sha256") != sha256(plan_path_from_state(controller)) + or controller.get("training_registry") != str(registry_path.resolve()) + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("official_test_used") is not False + or controller.get("h2o_official_validation_used") is not False + ): + raise ValueError("central Stage 8 controller binding differs") + registry = read_json(registry_path) + assignment = load_assignment(plan) + owners = condition_owners(registry, assignment) + conditions = registry.get("conditions", []) + if ( + registry.get("status") != "frozen_ready" + or len(conditions) != 7 + or len({item["condition"] for item in conditions}) != 7 + or sum(owner == "server_new" for owner in owners.values()) != 3 + or registry.get("official_test_used") is not False + or registry.get("h2o_official_validation_used_for_selection") is not False + ): + raise ValueError("Stage 8 training registry contract differs") + resolution_state = Path(plan["resolution_controller_state"]) + state = read_json(resolution_state) + decision = Path(state.get("decision_report", {}).get("path", "")) + if ( + state.get("status") != "complete" + or state.get("plan_sha256") != plan["resolution_controller_plan_sha256"] + or not decision.is_file() + or state.get("decision_report", {}).get("sha256") != sha256(decision) + or state.get("official_test_used") is not False + ): + raise ValueError("Stage 8 resolution admission binding differs") + files = [ + decision, resolution_state, Path(plan["registry_builder_state"]), + *[Path(item["config"]) for item in conditions], registry_path, + ] + for path in files: + if not path.is_file(): + raise ValueError(f"Stage 8 admission file is missing: {path}") + prerequisites = [] + seen = set() + for item in conditions: + pair = (item["initialization_checkpoint"], item["initialization_checkpoint_sha256"]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + for item in registry["data_artifacts"]: + pair = (item["path"], item["sha256"]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + return files, prerequisites + + +def plan_path_from_state(state: dict[str, Any]) -> Path: + path = Path(state.get("plan", "")) + if not path.is_file(): + raise ValueError("Stage 8 controller plan is missing") + return path + + +def remote_sha256(host: str, path: Path) -> str | None: + result = subprocess.run( + ["ssh", "-o", "BatchMode=yes", host, "sha256sum", str(path)], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, check=False, + ) + return result.stdout.split()[0] if result.returncode == 0 else None + + +def install_file(host: str, path: Path) -> dict[str, Any]: + digest = sha256(path) + observed = remote_sha256(host, path) + if observed is not None: + if observed != digest: + raise ValueError(f"remote Stage 8 admission destination differs: {path}") + return {"path": str(path.resolve()), "sha256": digest, "resumed_existing": True} + temporary = Path(f"{path}.incoming-stage8-v3") + mkdir = subprocess.run( + ["ssh", host, "mkdir", "-p", str(path.parent)], check=False, + ) + if mkdir.returncode: + raise RuntimeError(f"remote Stage 8 admission mkdir failed: {path.parent}") + copied = subprocess.run( + ["rsync", "-a", str(path), f"{host}:{temporary}"], check=False, + ) + if copied.returncode or remote_sha256(host, temporary) != digest: + raise RuntimeError(f"remote Stage 8 admission staging differs: {path}") + installed = subprocess.run( + ["ssh", host, "mv", str(temporary), str(path)], check=False, + ) + if installed.returncode or remote_sha256(host, path) != digest: + raise RuntimeError(f"remote Stage 8 admission install differs: {path}") + return {"path": str(path.resolve()), "sha256": digest, "resumed_existing": False} + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/controller_logs/server_new_training.log" + command = ( + "cd /home/jiasen/foundation_hand && mkdir -p " + str(Path(log).parent) + + " && setsid -f /SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_shared_augmentation_training_controller --plan " + + str(plan_path.resolve()) + " --state " + state + + " --machine server_new --poll-seconds 30 >> " + log + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", plan["source_host"], command], check=False) + if result.returncode: + raise RuntimeError("remote Stage 8 controller launch failed") + time.sleep(2) + probe = subprocess.run( + ["ssh", plan["source_host"], "pgrep", "-fo", + "scripts.run_phase9_shared_augmentation_training_controller.*shared_augmentation_v3.*server_new.json"], + stdout=subprocess.PIPE, text=True, check=False, + ) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote Stage 8 controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + files, prerequisites = admission_files(plan) + host = plan["source_host"] + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"local Stage 8 prerequisite differs: {path}") + if remote_sha256(host, path) != item["sha256"]: + raise ValueError(f"remote Stage 8 immutable prerequisite differs: {path}") + registry = Path(plan["training_registry"]) + installed = [] + for path in [item for item in files if item != registry] + [registry]: + installed.append(install_file(host, path)) + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_shared_augmentation_admission_sync_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "installed": installed, "immutable_prerequisites": prerequisites, + "remote_controller_pid": pid, + "registry_installed_last": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args() + plan = read_json(args.plan) + plan["source_host"] = "server_new" + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan) + atomic_json(args.state, result) + print(json.dumps(result, indent=2)) + return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: + raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_admission_sync_v1", + "status": "waiting_for_frozen_registry", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "plan": str(args.plan.resolve()), "plan_sha256": sha256(args.plan), + "h2o_official_validation_used": False, "official_test_used": False, + }) + time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_shared_augmentation_evaluation_admission.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_shared_augmentation_evaluation_admission.py new file mode 100644 index 0000000000000000000000000000000000000000..77f49003f8c121544b93407abc20a771830f37e0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_shared_augmentation_evaluation_admission.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Forward-sync the frozen Stage 8 evaluation plan to server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import time +from typing import Any + +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_shared_augmentation_admission import install_file, remote_sha256 + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def frozen_payload(plan: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, str]]]: + dynamic_path = Path(plan["evaluation_plan"]) + central_state = Path(plan["controller_states"]["taku3"]) + if not dynamic_path.is_file() or not central_state.is_file(): + raise NotReady("central Stage 8 evaluation plan is not frozen yet") + state = read_json(central_state) + dynamic = read_json(dynamic_path) + if not state.get("evaluation_plan_sha256"): + raise NotReady("central Stage 8 evaluation controller has not admitted the plan") + if ( + state.get("plan_sha256") != sha256(Path(state["plan"])) + or state.get("evaluation_plan") != str(dynamic_path.resolve()) + or state.get("evaluation_plan_sha256") != sha256(dynamic_path) + or len(dynamic.get("evaluations", [])) != 25 + or len(dynamic.get("workers", [])) != 10 + or dynamic.get("worker_heartbeat_seconds") != 30 + or dynamic.get("stall_timeout_seconds") != 900 + or dynamic.get("official_test_used") is not False + ): + raise ValueError("Stage 8 evaluation admission binding differs") + remote_ids = { + identifier for worker in dynamic["workers"] if worker["owner"] == "server_new" + for identifier in worker["evaluation_ids"] + } + evaluations = {item["id"]: item for item in dynamic["evaluations"]} + if len(remote_ids) != 9: + raise ValueError("Stage 8 remote evaluation ownership differs") + prerequisites = [] + seen = set() + for identifier in sorted(remote_ids): + item = evaluations[identifier] + for path_key, hash_key in ( + ("config", "config_sha256"), ("checkpoint", "checkpoint_sha256"), + ("cache_manifest", "cache_manifest_sha256"), + ): + pair = (item[path_key], item[hash_key]) + if pair not in seen: + prerequisites.append({"path": pair[0], "sha256": pair[1]}) + seen.add(pair) + return dynamic, prerequisites + + +def launch_remote(plan_path: Path, plan: dict[str, Any]) -> int: + state = plan["controller_states"]["server_new"] + log = "/SSD2/jiasen/foundation_hand/phase9_artifacts/queues/shared_augmentation_v3/controller_logs/server_new_evaluation.log" + command = ( + "cd /home/jiasen/foundation_hand && setsid -f " + "/SSD2/jiasen/envs/foundation_hand/bin/python -u -m " + "scripts.run_phase9_shared_augmentation_evaluation_controller --plan " + + str(plan_path.resolve()) + " --state " + state + + " --machine server_new --poll-seconds 30 >> " + log + " 2>&1 < /dev/null" + ) + result = subprocess.run(["ssh", "server_new", command], check=False) + if result.returncode: + raise RuntimeError("remote Stage 8 evaluation controller launch failed") + time.sleep(2) + probe = subprocess.run([ + "ssh", "server_new", "pgrep", "-fo", + "scripts.run_phase9_shared_augmentation_evaluation_controller.*shared_augmentation_v3.*server_new.json", + ], stdout=subprocess.PIPE, text=True, check=False) + if probe.returncode or not probe.stdout.strip().isdigit(): + raise RuntimeError("remote Stage 8 evaluation controller PID is unavailable") + return int(probe.stdout.strip()) + + +def synchronize(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + _, prerequisites = frozen_payload(plan) + for item in prerequisites: + path = Path(item["path"]) + if not path.is_file() or sha256(path) != item["sha256"]: + raise ValueError(f"central Stage 8 evaluation prerequisite differs: {path}") + if remote_sha256("server_new", path) != item["sha256"]: + raise ValueError(f"remote Stage 8 evaluation prerequisite differs: {path}") + dynamic = Path(plan["evaluation_plan"]) + files = [ + Path(plan["training_controller_state"]), Path(plan["evaluation_plan_state"]), + dynamic, + ] + installed = [install_file("server_new", path) for path in files[:-1]] + installed.append(install_file("server_new", dynamic)) + pid = launch_remote(plan_path, plan) + return { + "schema_version": "phase9_shared_augmentation_evaluation_admission_sync_v1", + "status": "complete", "completed_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "evaluation_plan_sha256": sha256(dynamic), "installed": installed, + "immutable_prerequisites": prerequisites, "evaluation_plan_installed_last": True, + "remote_controller_pid": pid, "official_test_used": False, + "h2o_official_validation_used": False, + } + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--state", type=Path, required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + deadline = time.monotonic() + args.wait_timeout_seconds + args.state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{args.state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + result = synchronize(args.plan, plan); atomic_json(args.state, result) + print(json.dumps(result, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(args.state, { + "schema_version": "phase9_shared_augmentation_evaluation_admission_sync_v1", + "status": "waiting_for_frozen_evaluation_plan", "watcher_pid": os.getpid(), + "updated_utc": utc_now(), "detail": str(error), + "plan_sha256": sha256(args.plan), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_shared_augmentation_training_completion.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_shared_augmentation_training_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..8c94bcfcd6549c3e5607171cb2a612bd1d6b3b3e --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_shared_augmentation_training_completion.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Completion-only server_new to taku3 handoff for Stage 8 training.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import math +import os +from pathlib import Path +import shutil +import subprocess +import time +from typing import Any + +from scripts.phase9_distributed_assignment import condition_owners, load_assignment +from scripts.run_phase9_unified_train_queue import atomic_json, sha256 +from scripts.sync_phase9_resolution_training_completion import ( + active_writer_pids, + last_json_record, + verify_checkpoint_archive, +) + + +EXPECTED = ( + "S8A_J25_loso_subject2", "S8A_J25_loso_subject3", "S8A_J25_lofamily_k", +) + + +class NotReady(RuntimeError): + pass + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def json_sha256(value: dict[str, Any]) -> str: + return hashlib.sha256((json.dumps(value, indent=2) + "\n").encode()).hexdigest() + + +def validate_plan(path: Path, plan: dict[str, Any]) -> None: + if ( + plan.get("schema_version") + != "phase9_shared_augmentation_training_completion_plan_v1" + or plan.get("status") != "frozen" + or plan.get("source_owner") != "server_new" + or plan.get("destination_owner") != "taku3" + or tuple(plan.get("conditions", [])) != EXPECTED + or plan.get("target_step") != 405000 + or plan.get("completion_only_reverse_release") is not True + or plan.get("live_reverse_sync_forbidden") is not True + or plan.get("single_writer_per_output") is not True + or plan.get("results_before_terminal_states") is not True + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + ): + raise ValueError("Stage 8 training completion plan contract differs") + for key in ("release_root", "staging_root", "release_state", "receive_state"): + if Path(plan[key]).parts[:2] != ("/", "SSD2"): + raise ValueError(f"Stage 8 completion {key} is not /SSD2") + for binding in plan["bindings"]: + candidate = Path(binding["path"]) + if not candidate.is_file() or sha256(candidate) != binding["sha256"]: + raise ValueError(f"Stage 8 completion binding differs: {candidate}") + if not path.is_file(): + raise ValueError("Stage 8 completion plan is unreadable") + + +def registry_payload(plan: dict[str, Any]) -> tuple[Path, dict[str, Any], dict[str, Any]]: + path = Path(plan["training_registry"]["path"]) + if not path.is_file() or sha256(path) != plan["training_registry"]["sha256"]: + raise ValueError("Stage 8 training registry hash differs") + registry = read_json(path) + owners = condition_owners(registry, load_assignment(plan)) + jobs = {item["condition"]: item for item in registry["conditions"]} + if ( + registry.get("status") != "frozen_ready" + or registry.get("target_step") != 405000 + or tuple(condition for condition in jobs if owners[condition] == "server_new") + != EXPECTED + or registry.get("official_test_used") is not False + ): + raise ValueError("Stage 8 training registry contract differs") + return path, registry, jobs + + +def validate_terminal(job: dict[str, Any], state: dict[str, Any]) -> tuple[Path, dict[str, Any]]: + marker = state.get("last_completed", {}) + checkpoint = Path(marker.get("checkpoint", "")) + metrics = Path(job["output_dir"]) / "metrics.jsonl" + summary_path = Path(job["output_dir"]) / "summary.json" + if not checkpoint.is_file() or not metrics.is_file() or not summary_path.is_file(): + raise ValueError(f"Stage 8 terminal artifact is missing: {job['condition']}") + metric = last_json_record(metrics) + summary = read_json(summary_path) + losses = metric.get("losses", {}) + if ( + state.get("status") != "complete" + or state.get("condition") != job["condition"] + or marker.get("completed_step") != 405000 + or marker.get("config") != job["config"] + or marker.get("config_sha256") != job["config_sha256"] + or marker.get("source_exposure_batches") != job["expected_source_exposure_batches"] + or marker.get("checkpoint_sha256") != sha256(checkpoint) + or metric.get("step") != 405000 + or not losses + or any(not isinstance(value, (int, float)) or not math.isfinite(float(value)) + for value in losses.values()) + or summary.get("status") != "completed" + or summary.get("completed_step") != 405000 + or summary.get("final_checkpoint_sha256") != marker["checkpoint_sha256"] + or summary.get("official_test_used") is not False + or state.get("official_test_used") is not False + ): + raise ValueError(f"Stage 8 terminal evidence differs: {job['condition']}") + verify_checkpoint_archive(checkpoint) + return checkpoint, {"metric": metric, "summary": summary, + "metrics_sha256": sha256(metrics), + "summary_sha256": sha256(summary_path)} + + +def file_record(root: Path, kind: str, path: Path) -> dict[str, Any]: + if not path.is_file() or path.is_symlink() or root not in path.resolve().parents: + raise ValueError(f"Stage 8 release file differs: {path}") + return {"kind": kind, "path": str(path.resolve().relative_to(root.resolve())), + "absolute_path": str(path.resolve()), "bytes": path.stat().st_size, + "sha256": sha256(path)} + + +def source_records(plan: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + registry_path, _, jobs = registry_payload(plan) + controller_path = Path(plan["source_controller_state"]) + if not controller_path.is_file(): + raise NotReady("server_new Stage 8 controller state is missing") + controller = read_json(controller_path) + if controller.get("status") != "complete_local": + if str(controller.get("status", "")).startswith("failed"): + raise ValueError("server_new Stage 8 controller failed") + raise NotReady("server_new Stage 8 training is still running") + if ( + controller.get("plan_sha256") != plan["training_controller_plan"]["sha256"] + or controller.get("training_registry_sha256") != sha256(registry_path) + or controller.get("condition_statuses") != {condition: "complete" for condition in EXPECTED} + or controller.get("official_test_used") is not False + ): + raise ValueError("server_new Stage 8 controller binding differs") + root = Path(plan["release_root"]) + state_root = Path(plan["training_state_root"]) + records, files = [], [] + for condition in EXPECTED: + job = jobs[condition] + state_path = state_root / f"{condition.lower()}.json" + state = read_json(state_path) + if state.get("queue_sha256") != sha256(registry_path): + raise ValueError(f"Stage 8 state registry binding differs: {condition}") + if active_writer_pids(job["output_dir"]): + raise NotReady(f"Stage 8 writer still exists: {condition}") + checkpoint, evidence = validate_terminal(job, state) + condition_files = [file_record(root, "checkpoint", checkpoint), + file_record(root, "training_state", state_path)] + files.extend(condition_files) + records.append({ + "condition": condition, "role": job["role"], + "checkpoint_sha256": sha256(checkpoint), + "final_total_loss": float(evidence["metric"]["losses"]["total"]), + "metrics_sha256": evidence["metrics_sha256"], + "summary_sha256": evidence["summary_sha256"], + "gpu_hours": state["gpu_hours_consumed"], "files": condition_files, + }) + return records, files + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["release_state"]) + if output.is_file(): + value = read_json(output) + if value.get("status") == "complete_immutable_release" and value.get("plan_sha256") == sha256(plan_path): + return value + raise ValueError("existing Stage 8 release differs") + records, files = source_records(plan) + value = { + "schema_version": "phase9_shared_augmentation_training_completion_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "server_new", "destination_owner": "taku3", + "plan_sha256": sha256(plan_path), "release_root": plan["release_root"], + "training_registry": plan["training_registry"], + "conditions": records, "files": files, "file_count": 6, + "total_bytes": sum(item["bytes"] for item in files), + "completion_only_reverse_release": True, "live_reverse_sync_performed": False, + "results_before_terminal_states": True, "single_writer_per_output": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, value) + os.chmod(output, 0o444) + for item in files: + os.chmod(item["absolute_path"], 0o444) + return value + + +def fetch(plan: dict[str, Any]) -> dict[str, Any]: + result = subprocess.run(["ssh", plan["source_host"], "cat", plan["release_state"]], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + text=True, check=False) + if result.returncode: + raise NotReady("server_new Stage 8 release is unavailable") + return json.loads(result.stdout) + + +def validate_release(plan_path: Path, plan: dict[str, Any], value: dict[str, Any]) -> None: + files = value.get("files", []) + if ( + value.get("schema_version") != "phase9_shared_augmentation_training_completion_release_v1" + or value.get("status") != "complete_immutable_release" + or value.get("plan_sha256") != sha256(plan_path) + or value.get("training_registry") != plan["training_registry"] + or tuple(item.get("condition") for item in value.get("conditions", [])) != EXPECTED + or len(files) != 6 or len({item.get("path") for item in files}) != 6 + or sum(item.get("bytes", -1) for item in files) != value.get("total_bytes") + or value.get("results_before_terminal_states") is not True + or value.get("official_test_used") is not False + ): + raise ValueError("Stage 8 immutable release differs") + + +def verify(root: Path, item: dict[str, Any]) -> Path: + path = root / item["path"] + if (not path.is_file() or path.is_symlink() or path.stat().st_size != item["bytes"] + or sha256(path) != item["sha256"]): + raise ValueError(f"Stage 8 completion file differs: {path}") + return path + + +def install(plan: dict[str, Any], release: dict[str, Any]) -> list[dict[str, Any]]: + root, staging = Path(plan["release_root"]), Path(plan["staging_root"]) + pending, installed = [], [] + for item in release["files"]: + if (root / item["path"]).exists(): + verify(root, item); installed.append({**item, "resumed_existing": True}) + else: + pending.append(item) + if pending: + staging.mkdir(parents=True, exist_ok=True) + listing = staging / ".pending_stage8_files.txt" + listing.write_text("".join(item["path"] + "\n" for item in pending), encoding="utf-8") + result = subprocess.run(["rsync", "-a", "--partial", f"--files-from={listing}", + f"{plan['source_host']}:{root}/", f"{staging}/"], check=False) + if result.returncode: + raise RuntimeError("Stage 8 completion rsync failed") + for item in pending: verify(staging, item) + for kind in ("checkpoint", "training_state"): + for item in pending: + if item["kind"] != kind: continue + source, destination = staging / item["path"], root / item["path"] + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination); os.chmod(destination, 0o444) + verify(root, item); installed.append({**item, "resumed_existing": False}) + return installed + + +def central_complete(plan: dict[str, Any]) -> bool: + path = Path(plan["central_controller_state"]) + if not path.is_file(): return False + value = read_json(path) + return (value.get("status") == "complete" + and value.get("training_registry_sha256") == plan["training_registry"]["sha256"] + and value.get("official_test_used") is False) + + +def receive(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + output = Path(plan["receive_state"]) + if output.is_file(): return read_json(output) + release = fetch(plan); validate_release(plan_path, plan, release) + backup = Path(plan["central_controller_backup"]) + if not backup.exists(): + backup.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(plan["central_controller_state"], backup); os.chmod(backup, 0o444) + installed = install(plan, release) + deadline = time.monotonic() + plan["central_completion_timeout_seconds"] + while time.monotonic() < deadline and not central_complete(plan): time.sleep(2) + if not central_complete(plan): raise TimeoutError("central Stage 8 controller did not converge") + value = { + "schema_version": "phase9_shared_augmentation_training_completion_receive_v1", + "status": "complete", "completed_utc": utc_now(), + "plan_sha256": sha256(plan_path), "release_sha256": json_sha256(release), + "file_count": 6, "total_bytes": release["total_bytes"], "installed": installed, + "results_before_terminal_states": True, "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, value); return value + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "receive"), required=True) + parser.add_argument("--wait-timeout-seconds", type=float, default=0) + args = parser.parse_args(); plan = read_json(args.plan) + try: validate_plan(args.plan, plan) + except ValueError as error: parser.error(str(error)) + target = Path(plan["release_state" if args.role == "publish" else "receive_state"]) + target.parent.mkdir(parents=True, exist_ok=True) + deadline = time.monotonic() + args.wait_timeout_seconds + with Path(f"{target}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + while True: + try: + value = publish(args.plan, plan) if args.role == "publish" else receive(args.plan, plan) + print(json.dumps(value, indent=2)); return + except NotReady as error: + if args.wait_timeout_seconds <= 0 or time.monotonic() >= deadline: raise + atomic_json(Path(f"{target}.watcher.json"), { + "schema_version": "phase9_shared_augmentation_training_completion_watcher_v1", + "status": "waiting_for_terminal_source", "role": args.role, + "watcher_pid": os.getpid(), "updated_utc": utc_now(), "detail": str(error), + "plan_sha256": sha256(args.plan), "official_test_used": False, + }); time.sleep(30) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_taku_resolution_caches.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_taku_resolution_caches.py new file mode 100644 index 0000000000000000000000000000000000000000..84cb358bfea905f09ef6978f46deff950973aab4 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/sync_phase9_taku_resolution_caches.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python3 +"""Publish and install Taku3-owned Stage 7 caches on server_new.""" + +from __future__ import annotations + +import argparse +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +from typing import Any + +from scripts.run_phase9_resolution_cache_queue import atomic_json, sha256 + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def read_json(path: str | Path) -> dict[str, Any]: + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def validate_plan(plan: dict[str, Any]) -> None: + if ( + plan.get("status") != "frozen" + or plan.get("source_owner") != "taku3" + or plan.get("destination_owner") != "server_new" + or plan.get("official_test_used") is not False + or plan.get("h2o_official_validation_used") is not False + or plan.get("live_reverse_sync_forbidden") is not True + ): + raise ValueError("Taku3 cache sync plan contract differs") + for binding in plan["bindings"]: + path = Path(binding["path"]) + if not path.is_file() or sha256(path) != binding["sha256"]: + raise ValueError(f"Taku3 cache sync binding differs: {path}") + root = Path(plan["release_root"]) + if root.parts[:2] != ("/", "SSD2"): + raise ValueError("Taku3 cache sync root is not /SSD2") + for item in plan["artifacts"]: + path = Path(item["path"]) + if root not in path.parents: + raise ValueError(f"Taku3 cache artifact is outside release root: {path}") + + +def known_payload_hashes(manifests: list[str]) -> dict[Path, str]: + known: dict[Path, str] = {} + hash_fields = ( + ("cache_path", "cache_sha256"), + ("joint3d_root_relative_sidecar_path", "joint3d_root_relative_sidecar_sha256"), + ) + for value in manifests: + for line in Path(value).read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + row = json.loads(line) + for path_field, hash_field in hash_fields: + if row.get(path_field) and row.get(hash_field): + path = Path(row[path_field]).resolve() + digest = row[hash_field] + previous = known.setdefault(path, digest) + if previous != digest: + raise ValueError(f"conflicting manifest payload hash: {path}") + return known + + +def inventory_artifacts( + root: Path, artifacts: list[dict[str, Any]], known: dict[Path, str], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + files: list[dict[str, Any]] = [] + artifact_records = [] + seen: set[str] = set() + for item in artifacts: + artifact = Path(item["path"]) + if not artifact.exists() or artifact.is_symlink(): + raise ValueError(f"Taku3 cache artifact differs: {artifact}") + candidates = [artifact] if artifact.is_file() else sorted(artifact.rglob("*")) + start = len(files) + for path in candidates: + if path.is_symlink(): + raise ValueError(f"Taku3 cache release refuses symlink: {path}") + if not path.is_file(): + continue + relative = str(path.relative_to(root)) + if relative in seen: + raise ValueError(f"duplicate Taku3 cache release path: {relative}") + seen.add(relative) + digest = known.get(path.resolve()) + if digest is None: + digest = sha256(path) + files.append({ + "path": relative, "sha256": digest, "bytes": path.stat().st_size, + }) + selected = files[start:] + artifact_records.append({ + "id": item["id"], "path": str(artifact.resolve()), + "relative_path": str(artifact.relative_to(root)), + "kind": "file" if artifact.is_file() else "directory", + "file_count": len(selected), + "total_bytes": sum(record["bytes"] for record in selected), + }) + return files, artifact_records + + +def validate_readiness(plan: dict[str, Any]) -> dict[str, Any]: + path = Path(plan["readiness_state"]["path"]) + state = read_json(path) + audit = Path(state.get("audit", {}).get("path", "")) + if ( + state.get("status") != "complete" + or sha256(path) != plan["readiness_state"]["sha256"] + or state.get("plan_sha256") != plan["cache_execution_plan_sha256"] + or state.get("official_test_used") is not False + or state.get("h2o_official_validation_used") is not False + or not audit.is_file() + or state.get("audit", {}).get("sha256") != sha256(audit) + ): + raise ValueError("Taku3 cache release readiness differs") + return state + + +def publish(plan_path: Path, plan: dict[str, Any]) -> dict[str, Any]: + readiness = validate_readiness(plan) + output = Path(plan["release_state"]) + if output.is_file(): + release = read_json(output) + if ( + release.get("status") == "complete_immutable_release" + and release.get("plan_sha256") == sha256(plan_path) + ): + return release + raise ValueError("existing Taku3 cache release differs") + root = Path(plan["release_root"]) + known = known_payload_hashes(plan["payload_manifests"]) + files, artifacts = inventory_artifacts(root, plan["artifacts"], known) + release = { + "schema_version": "phase9_taku_cache_immutable_release_v1", + "status": "complete_immutable_release", "created_utc": utc_now(), + "owner": "taku3", "destination_owner": "server_new", + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_root": str(root.resolve()), + "readiness_state": { + "path": str(Path(plan["readiness_state"]["path"]).resolve()), + "sha256": plan["readiness_state"]["sha256"], + "audit": readiness["audit"], + }, + "artifacts": artifacts, "files": files, "file_count": len(files), + "total_bytes": sum(item["bytes"] for item in files), + "payload_hash_source": "globally_audited_cache_and_sidecar_manifests", + "read_only_after_publish": True, "live_reverse_sync_forbidden": True, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(output, release) + os.chmod(output, 0o444) + for item in plan["artifacts"]: + path = Path(item["path"]) + if path.is_file(): + os.chmod(path, 0o444) + continue + for candidate in path.rglob("*"): + os.chmod(candidate, 0o555 if candidate.is_dir() else 0o444) + os.chmod(path, 0o555) + return release + + +def validate_release(plan_path: Path, plan: dict[str, Any], release: dict[str, Any]) -> None: + if ( + release.get("status") != "complete_immutable_release" + or release.get("owner") != "taku3" + or release.get("destination_owner") != "server_new" + or release.get("plan_sha256") != sha256(plan_path) + or release.get("release_root") != str(Path(plan["release_root"]).resolve()) + or release.get("read_only_after_publish") is not True + or release.get("live_reverse_sync_forbidden") is not True + or release.get("official_test_used") is not False + or release.get("h2o_official_validation_used") is not False + or len(release.get("files", [])) != release.get("file_count") + or sum(item["bytes"] for item in release["files"]) != release.get("total_bytes") + ): + raise ValueError("Taku3 cache immutable release differs") + paths = [item["path"] for item in release["files"]] + if len(paths) != len(set(paths)) or any( + Path(path).is_absolute() or ".." in Path(path).parts for path in paths + ): + raise ValueError("Taku3 cache release paths differ") + + +def push(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + release = read_json(plan["release_state"]) + validate_release(plan_path, plan, release) + file_list = Path(plan["push_file_list"]) + file_list.parent.mkdir(parents=True, exist_ok=True) + file_list.write_text( + "".join(item["path"] + "\n" for item in release["files"]), + encoding="utf-8", + ) + state = { + "schema_version": "phase9_taku_cache_push_state_v1", + "status": "syncing", "started_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state_sha256": sha256(plan["release_state"]), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "destination": plan["destination_host"], + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, state) + staging = Path(plan["destination_staging_root"]) + command = [ + "rsync", "-a", "--partial", f"--files-from={file_list}", + f"{Path(plan['release_root']).resolve()}/", + f"{plan['destination_host']}:{staging.resolve()}/", + ] + completed = subprocess.run(command, check=False) + state["returncode"] = completed.returncode + state["updated_utc"] = utc_now() + state["status"] = "synced_waiting_for_remote_install" if not completed.returncode else "failed_resumable" + atomic_json(state_path, state) + if completed.returncode: + raise SystemExit(completed.returncode) + return state + + +def verify_files(root: Path, release: dict[str, Any]) -> None: + for item in release["files"]: + path = root / item["path"] + if ( + not path.is_file() or path.is_symlink() + or path.stat().st_size != item["bytes"] or sha256(path) != item["sha256"] + ): + raise ValueError(f"received Taku3 cache file differs: {path}") + + +def install(plan_path: Path, plan: dict[str, Any], state_path: Path) -> dict[str, Any]: + release = read_json(plan["release_state"]) + validate_release(plan_path, plan, release) + staging = Path(plan["destination_staging_root"]) + verify_files(staging, release) + root = Path(plan["release_root"]) + installed = [] + for item in release["artifacts"]: + source = staging / item["relative_path"] + destination = root / item["relative_path"] + if destination.exists(): + raise ValueError(f"Taku3 cache destination already exists: {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + os.replace(source, destination) + if destination.is_file(): + os.chmod(destination, 0o444) + else: + for path in destination.rglob("*"): + os.chmod(path, 0o555 if path.is_dir() else 0o444) + os.chmod(destination, 0o555) + installed.append(item) + state = { + "schema_version": "phase9_taku_cache_receive_state_v1", + "status": "complete", "completed_utc": utc_now(), "updated_utc": utc_now(), + "plan": str(plan_path.resolve()), "plan_sha256": sha256(plan_path), + "release_state_sha256": sha256(plan["release_state"]), + "file_count": release["file_count"], "total_bytes": release["total_bytes"], + "installed": installed, "read_only": True, + "live_reverse_sync_performed": False, + "h2o_official_validation_used": False, "official_test_used": False, + } + atomic_json(state_path, state) + return state + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--plan", type=Path, required=True) + parser.add_argument("--role", choices=("publish", "push", "install"), required=True) + parser.add_argument("--state", type=Path) + args = parser.parse_args() + plan = read_json(args.plan) + try: + validate_plan(plan) + except ValueError as error: + parser.error(str(error)) + expected_state = { + "publish": Path(plan["release_state"]), + "push": Path(plan["push_state"]), + "install": Path(plan["destination_receive_state"]), + }[args.role] + if args.state and args.state.resolve() != expected_state.resolve(): + parser.error("Taku3 cache sync state differs") + expected_state.parent.mkdir(parents=True, exist_ok=True) + with Path(f"{expected_state}.lock").open("a+", encoding="utf-8") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + if args.role == "publish": + result = publish(args.plan, plan) + elif args.role == "push": + result = push(args.plan, plan, expected_state) + else: + result = install(args.plan, plan, expected_state) + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/train_experiment.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/train_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..0773e54df5b6b201d2dd25e039341ea338b675c6 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/train_experiment.py @@ -0,0 +1,776 @@ +#!/usr/bin/env python3 +"""Formal H2O camera-space training entry point with hard asset/geometry gates.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import random +import shlex +import socket +import subprocess +import sys +import time +from dataclasses import asdict +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader, Subset + +from foundation_hand.data import ( + H2OCam4Dataset, + ResumableRandomBatchSampler, + ResumableWeightedBatchSampler, + collate_h2o_clips, + load_balanced_sampling_weights, +) +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import ( + load_checkpoint, + load_model_initialization, + save_checkpoint, +) +from foundation_hand.training.metrics import camera_metrics +from foundation_hand.training.optimizer import ( + checkpoint_excluded_prefixes, + optimizer_parameter_groups, + set_scheduled_learning_rate, +) +from foundation_hand.training.schedule import warmup_cosine_learning_rate + + +def git_state() -> str: + return subprocess.run(["git", "status", "--short"], text=True, stdout=subprocess.PIPE, check=False).stdout + + +def git_commit() -> str | None: + result = subprocess.run( + ["git", "rev-parse", "HEAD"], text=True, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=False, + ) + return result.stdout.strip() or None + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def resolved_weight_path(value: str) -> Path: + path = Path(value) + return path / "model.safetensors" if path.is_dir() else path + + +def capture_run_provenance( + args: argparse.Namespace, + config: dict, + output_path: Path, +) -> Path: + assets = config["assets"] + tracked_files = { + "config": args.config, + "train_manifest": args.manifest, + "validation_manifest": args.val_manifest, + "validation_subset": args.validation_subset_manifest, + "sampling_manifest": Path(config.get("sampling", {}).get("manifest", "")), + "initialization_checkpoint": args.init_checkpoint, + "dinov3_weights": resolved_weight_path(assets["dinov3_weights"]), + "mano_left": Path(assets["mano_root"]) / "MANO_LEFT.pkl", + "mano_right": Path(assets["mano_root"]) / "MANO_RIGHT.pkl", + } + hashes = { + name: {"path": str(path.resolve()), "sha256": file_sha256(path)} + for name, path in tracked_files.items() if path is not None and path.is_file() + } + gpu_inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid,name,memory.total", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, + ).stdout.strip().splitlines() + provenance = { + "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "hostname": socket.gethostname(), + "git_commit": git_commit(), + "git_status": git_state(), + "command_argv": [sys.executable, *sys.argv], + "command_shell": shlex.join([sys.executable, *sys.argv]), + "working_directory": str(Path.cwd()), + "config": config, + "seed": int(config["seed"]), + "cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "gpu_inventory": gpu_inventory, + "python": sys.version, + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "hashes": hashes, + "resume_checkpoint": str(args.resume.resolve()) if args.resume else None, + "initialization_checkpoint": ( + str(args.init_checkpoint.resolve()) if args.init_checkpoint else None + ), + } + output_path.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8") + return output_path + + +def load_validation_subset( + path: Path, + validation_manifest: Path, + data_config: dict, + dataset_size: int, +) -> tuple[list[int], dict]: + record = json.loads(path.read_text(encoding="utf-8")) + if record.get("source_manifest_sha256") != file_sha256(validation_manifest): + raise ValueError("validation subset source-manifest hash does not match --val-manifest") + contract = record.get("dataset_contract", {}) + expected = { + "resolution_hw": list(data_config["resolution_hw"]), + "T": int(data_config["T"]), + "stride": int(data_config["stride"]), + } + for key, value in expected.items(): + if contract.get(key) != value: + raise ValueError(f"validation subset contract mismatch for {key}: {contract.get(key)} != {value}") + indices = [int(index) for index in record["clip_indices"]] + if len(indices) != len(set(indices)) or not indices: + raise ValueError("validation subset indices must be non-empty and unique") + if min(indices) < 0 or max(indices) >= dataset_size: + raise ValueError("validation subset index is outside the validation dataset") + return indices, record + + +def preflight(config: dict, root: Path, manifest: Path) -> list[str]: + blockers = [] + if not root.is_dir(): blockers.append(f"dataset root missing: {root}") + if not manifest.is_file(): blockers.append(f"manifest missing: {manifest}") + assets = config.get("assets", {}) + source = Path(assets.get("dinov3_source") or "") + weights = Path(assets.get("dinov3_weights") or "") + mano_root = Path(assets.get("mano_root") or "") + if not (source / "hubconf.py").is_file(): blockers.append(f"official DINOv3 source missing: {source}") + valid_weight = weights.is_file() or (weights.is_dir() and (weights / "model.safetensors").is_file()) + if not valid_weight: blockers.append("DINOv3 pretrained weight missing; formal training forbids random DINO") + for side in ("LEFT", "RIGHT"): + if not (mano_root / f"MANO_{side}.pkl").is_file(): blockers.append(f"licensed MANO_{side}.pkl missing") + coordinate_report = Path("artifacts/phase2/coordinate_audit/mano_audit.json") + if not coordinate_report.is_file(): blockers.append("numerical MANO reconstruction/translation audit has not passed") + else: + audit = json.loads(coordinate_report.read_text(encoding="utf-8")) + if audit.get("status") != "passed": blockers.append("MANO coordinate audit exists but did not pass") + return blockers + + +def protocol_mismatches(config: dict, args: argparse.Namespace) -> list[str]: + """Reject formal runs whose CLI silently diverges from the registered config.""" + + protocol = config.get("protocol") + if protocol is None: + return [] + actual = { + "max_steps": args.max_steps, + "num_workers": args.num_workers, + "checkpoint_interval": args.checkpoint_interval, + "validation_interval": args.validation_interval, + "validation_batches": args.validation_batches, + "learning_rate": args.learning_rate, + "min_learning_rate": args.min_learning_rate, + "warmup_steps": args.warmup_steps, + "early_stopping_patience": args.early_stopping_patience, + } + mismatches = [ + f"protocol {key}={protocol.get(key)} but CLI resolved {value}" + for key, value in actual.items() if protocol.get(key) != value + ] + if "lr_schedule_steps" in protocol: + resolved_schedule_steps = ( + args.max_steps if args.lr_schedule_steps is None else args.lr_schedule_steps + ) + if protocol["lr_schedule_steps"] != resolved_schedule_steps: + mismatches.append( + "protocol lr_schedule_steps=" + f"{protocol['lr_schedule_steps']} but CLI resolved {resolved_schedule_steps}" + ) + registered_subset = protocol.get("validation_subset_manifest") + actual_subset = str(args.validation_subset_manifest) if args.validation_subset_manifest else None + if registered_subset != actual_subset: + mismatches.append( + f"protocol validation_subset_manifest={registered_subset} but CLI resolved {actual_subset}" + ) + return mismatches + + +def attach_gt_vertices(batch: dict[str, torch.Tensor], model: BimanualReconstructionModel) -> None: + if model.mano_layer is None: + raise RuntimeError("MANO layer is required for formal geometry supervision") + pose = torch.nan_to_num(batch["mano_pose"]).reshape(*batch["mano_pose"].shape[:-1], 16, 3) + rotations = axis_angle_to_matrix(pose) + with torch.no_grad(): + vertices, _ = model.mano_layer(rotations, torch.nan_to_num(batch["mano_shape"]), torch.nan_to_num(batch["wrist_root_translation"])) + valid = ( + batch.get("vertices_valid", batch["mano_annotation_valid"]).bool() + & batch["frame_valid"].bool()[..., None] + )[..., None, None] + batch["vertices_camera"] = torch.where(valid, vertices, torch.full_like(vertices, torch.nan)) + + +def move_to_device(batch: dict, device: torch.device) -> dict: + return { + key: value.to(device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + +def photometric_diagnostics(batch: dict[str, torch.Tensor]) -> dict[str, float]: + parameters = batch.get("photometric_aug_params") + if parameters is None: + return {} + values = parameters[batch["frame_valid"].bool()] + if values.numel() == 0: + return {} + return { + "applied_fraction": float(values[:, 0].mean()), + "brightness_mean": float(values[:, 1].mean()), + "contrast_mean": float(values[:, 2].mean()), + "saturation_mean": float(values[:, 3].mean()), + "hue_mean": float(values[:, 4].mean()), + } + + +def run_validation( + model: BimanualReconstructionModel, + criterion: BimanualLoss, + loader: DataLoader, + device: torch.device, + dtype: torch.dtype, + max_batches: int, +) -> dict[str, dict[str, float]]: + """Run a bounded deterministic validation pass without changing train RNG.""" + + was_training = model.training + model.eval() + loss_values: dict[str, list[float]] = {} + metric_values: dict[str, list[float]] = {} + with torch.inference_mode(): + for batch_index, batch in enumerate(loader): + if batch_index >= max_batches: + break + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + for key, value in losses.items(): + scalar = float(value) + if math.isfinite(scalar): + loss_values.setdefault(key, []).append(scalar) + for key, value in camera_metrics(prediction, batch).items(): + if math.isfinite(value): + metric_values.setdefault(key, []).append(value) + model.train(was_training) + return { + "losses": {key: sum(values) / len(values) for key, values in loss_values.items()}, + "metrics": {key: sum(values) / len(values) for key, values in metric_values.items()}, + } + + +def validation_state_from_log(path: Path, metric: str) -> tuple[float, int]: + if not path.is_file(): + return float("inf"), 0 + best = float("inf") + no_improvement = 0 + for line in path.read_text(encoding="utf-8").splitlines(): + record = json.loads(line) + value = record.get("metrics", {}).get(metric) + if value is not None and math.isfinite(value): + if float(value) < best: + best = float(value) + no_improvement = 0 + else: + no_improvement += 1 + return best, no_improvement + + +def attention_diagnostics(prediction: dict, batch: dict) -> dict[str, float | None]: + attention = prediction.get("attention", {}) + frame_valid = batch["frame_valid"].bool() + result: dict[str, float | None] = {} + if "rgb_cross_attention" in attention: + weights = attention["rgb_cross_attention"][:, -1] + left, right = weights[..., 0, :], weights[..., 1, :] + result["rgb_attention_same_peak_fraction"] = float( + (left.argmax(-1) == right.argmax(-1))[frame_valid].float().mean() + ) + result["rgb_attention_left_right_cosine"] = float( + torch.nn.functional.cosine_similarity(left, right, dim=-1)[frame_valid].mean() + ) + if "depth_fusion_gate" in attention: + result["depth_gate_mean"] = float(attention["depth_fusion_gate"][:, -1][frame_valid].float().mean()) + result["depth_gate_raw_mean"] = float(attention["depth_fusion_gate_raw"][:, -1][frame_valid].float().mean()) + result["gated_depth_update_norm_mean"] = float( + attention["gated_depth_update_norm"][:, -1][frame_valid].float().mean() + ) + if "temporal_attention" in attention: + weights = attention["temporal_attention"][:, -1] + entropy_values = [] + for batch_index in range(weights.shape[0]): + valid_indices = torch.where(frame_valid[batch_index])[0] + if valid_indices.numel() <= 1: + continue + selected = weights[batch_index, :, valid_indices][:, :, valid_indices].float() + selected = selected / selected.sum(dim=-1, keepdim=True).clamp_min(1e-8) + entropy = -(selected * selected.clamp_min(1e-8).log()).sum(dim=-1) / math.log(valid_indices.numel()) + entropy_values.append(entropy.mean()) + result["temporal_attention_normalized_entropy"] = ( + float(torch.stack(entropy_values).mean()) if entropy_values else None + ) + return result + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--val-manifest", type=Path) + parser.add_argument("--validation-subset-manifest", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--max-steps", type=int, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--checkpoint-interval", type=int, default=100) + parser.add_argument("--learning-rate", type=float, default=1e-4) + parser.add_argument("--min-learning-rate", type=float) + parser.add_argument("--lr-schedule-steps", type=int) + parser.add_argument("--warmup-steps", type=int, default=0) + parser.add_argument("--depth-gate-warmup-steps", type=int, default=0) + parser.add_argument("--validation-interval", type=int, default=500) + parser.add_argument("--validation-batches", type=int, default=32) + parser.add_argument("--max-minutes", type=float) + parser.add_argument("--early-stopping-patience", type=int, default=0) + args = parser.parse_args() + if args.checkpoint_interval <= 0: + parser.error("--checkpoint-interval must be positive") + if args.validation_interval <= 0: + parser.error("--validation-interval must be positive") + if args.validation_batches <= 0: + parser.error("--validation-batches must be positive") + if args.max_minutes is not None and args.max_minutes <= 0: + parser.error("--max-minutes must be positive") + if args.early_stopping_patience < 0: + parser.error("--early-stopping-patience must be non-negative") + if args.resume is not None and args.init_checkpoint is not None: + parser.error("--resume and --init-checkpoint are mutually exclusive") + lr_schedule_steps = ( + args.max_steps if args.lr_schedule_steps is None else args.lr_schedule_steps + ) + if not 0 < lr_schedule_steps <= args.max_steps: + parser.error("--lr-schedule-steps must be in (0, max-steps]") + if not 0 <= args.warmup_steps < lr_schedule_steps: + parser.error("--warmup-steps must be in [0, lr-schedule-steps)") + min_learning_rate = args.learning_rate if args.min_learning_rate is None else args.min_learning_rate + if not 0 <= min_learning_rate <= args.learning_rate: + parser.error("--min-learning-rate must be in [0, learning-rate]") + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + deterministic_training = bool( + config.get("protocol", {}).get("deterministic_training", False) + ) + if deterministic_training: + os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") + torch.use_deterministic_algorithms(True) + torch.backends.cudnn.benchmark = False + oracle_crop_mode = config.get("model", {}).get("oracle_crop_mode", "none") + structured_refinement = bool( + config.get("model", {}).get("structured_hand_refinement", False) + ) + mixed_projection = ( + config.get("model", {}).get( + "translation_parameterization", "direct_xyz", + ) == "mixed_projection" + ) + spatial_joint2d = ( + config.get("model", {}).get( + "joint2d_parameterization", "hand_token_linear", + ) == "spatial_heatmap" + ) + matched_control_initialization = bool( + config.get("experiment", {}).get("matched_control_initialization", False) + ) + residual_initialization = ( + oracle_crop_mode != "none" or structured_refinement + or mixed_projection or spatial_joint2d + ) + if residual_initialization and args.resume is None and args.init_checkpoint is None: + parser.error("registered residual training requires --init-checkpoint on a new run") + if ( + not residual_initialization + and not matched_control_initialization + and args.init_checkpoint is not None + ): + parser.error( + "--init-checkpoint is restricted to registered residual or matched-control runs" + ) + if args.init_checkpoint is not None: + if not args.init_checkpoint.is_file(): + parser.error(f"initialization checkpoint missing: {args.init_checkpoint}") + expected_init_hash = config.get("experiment", {}).get("coarse_checkpoint_sha256") + actual_init_hash = file_sha256(args.init_checkpoint) + if expected_init_hash != actual_init_hash: + parser.error( + "initialization checkpoint hash mismatch: " + f"{actual_init_hash} != {expected_init_hash}" + ) + protocol_errors = protocol_mismatches(config, args) + if protocol_errors: + parser.error("; ".join(protocol_errors)) + if args.validation_subset_manifest is not None and args.val_manifest is None: + parser.error("--validation-subset-manifest requires --val-manifest") + if args.output_dir.exists() and any(args.output_dir.iterdir()) and args.resume is None: + parser.error("--output-dir must be new or empty unless --resume is provided") + args.output_dir.mkdir(parents=True, exist_ok=True) + blockers = preflight(config, args.root, args.manifest) + if args.val_manifest is not None and not args.val_manifest.is_file(): + blockers.append(f"validation manifest missing: {args.val_manifest}") + if args.validation_subset_manifest is not None and not args.validation_subset_manifest.is_file(): + blockers.append(f"validation subset manifest missing: {args.validation_subset_manifest}") + if blockers: + result = {"status": "blocked_preflight", "config": str(args.config), "blockers": blockers, "timestamp": datetime.now(timezone.utc).isoformat()} + (args.output_dir / "BLOCKED.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(result, indent=2)) + raise SystemExit(2) + + provenance_name = "run_provenance.json" if args.resume is None else f"resume_provenance_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json" + provenance_path = capture_run_provenance(args, config, args.output_dir / provenance_name) + sampling_config = config.get("sampling", {"mode": "uniform"}) + sampling_mode = str(sampling_config.get("mode", "uniform")) + if sampling_mode not in {"uniform", "balanced"}: + parser.error(f"unsupported sampling mode: {sampling_mode}") + checkpoint_context = { + "config": config, + "external_frozen_backbone": config["assets"]["dinov3_weights"], + "sampler": ( + "global_step_weighted_v1" if sampling_mode == "balanced" + else "global_step_seeded_v1" + ), + "git_commit": git_commit(), + "run_provenance": str(provenance_path), + "run_provenance_sha256": file_sha256(provenance_path), + "initialization_checkpoint": ( + { + "path": str(args.init_checkpoint.resolve()), + "sha256": file_sha256(args.init_checkpoint), + } + if args.init_checkpoint is not None else None + ), + } + + seed = int(config["seed"]); random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed) + data_config, model_values, assets = config["data"], config["model"], config["assets"] + photometric_config = data_config.get("photometric_augmentation") + dataset = H2OCam4Dataset( + args.root, args.manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + photometric_augmentation=photometric_config, + augmentation_seed=seed, + oracle_crop_enabled=oracle_crop_mode != "none", + ) + model_config = ModelConfig(**model_values, dinov3_source=assets["dinov3_source"], dinov3_weights=assets["dinov3_weights"], mano_root=assets["mano_root"]) + device = torch.device("cuda") + model = BimanualReconstructionModel(model_config).to(device) + initialization_record = None + if args.init_checkpoint is not None: + allowed_missing_prefixes = ( + (("oracle_crop_",) if oracle_crop_mode != "none" else ()) + + (("structured_",) if structured_refinement else ()) + + (("mixed_log_tz_head",) if mixed_projection else ()) + + (("joint_localization_",) if spatial_joint2d else ()) + ) + initialization_record = load_model_initialization( + args.init_checkpoint, model, + allowed_missing_prefixes=allowed_missing_prefixes, map_location=device, + require_residual=residual_initialization, + ) + checkpoint_context["initialization_checkpoint"].update({ + "source_step": initialization_record["step"], + "residual_missing_keys": initialization_record["residual_missing_keys"], + "checkpoint_excluded_prefixes": initialization_record[ + "checkpoint_excluded_prefixes" + ], + }) + if mixed_projection: + model.initialize_mixed_log_tz_from_direct_head() + checkpoint_context["initialization_checkpoint"].update({ + "mixed_log_tz_initialization": ( + "first-order log-softplus linearization of frozen direct-z head" + ), + "direct_xyz_teacher_frozen": True, + }) + loss_config = LossConfig(**config.get("loss", {})) + criterion = BimanualLoss(loss_config).to(device) + optimizer = torch.optim.AdamW( + optimizer_parameter_groups( + model, + learning_rate=args.learning_rate, + backbone_learning_rate=config.get("protocol", {}).get( + "backbone_learning_rate" + ), + ), + lr=args.learning_rate, + weight_decay=0.05, + ) + excluded_checkpoint_prefixes = checkpoint_excluded_prefixes(model) + start_step = 0 + if args.resume: + start_step = int(load_checkpoint(args.resume, model, optimizer, device)["step"]) + set_scheduled_learning_rate(optimizer, args.learning_rate) + sampling_manifest_record = None + if sampling_mode == "balanced": + sampling_manifest = sampling_config.get("manifest") + if not sampling_manifest: + raise ValueError("balanced sampling requires sampling.manifest") + weights, sampling_manifest_record = load_balanced_sampling_weights( + sampling_manifest, args.manifest, data_config, len(dataset), + ) + batch_sampler = ResumableWeightedBatchSampler( + weights, int(data_config["batch_size"]), seed, start_step, args.max_steps, + include_epoch=photometric_config is not None, + ) + else: + batch_sampler = ResumableRandomBatchSampler( + len(dataset), int(data_config["batch_size"]), seed, start_step, args.max_steps, + include_epoch=photometric_config is not None, + ) + loader_generator = torch.Generator().manual_seed(seed + 10_000_000) + loader = DataLoader( + dataset, batch_sampler=batch_sampler, generator=loader_generator, + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + val_loader = None + val_dataset_size = 0 + val_evaluated_samples = 0 + validation_subset_record = None + if args.val_manifest is not None: + val_dataset = H2OCam4Dataset( + args.root, args.val_manifest, tuple(data_config["resolution_hw"]), + (int(data_config["T"]),), (int(data_config["stride"]),), + oracle_crop_enabled=oracle_crop_mode != "none", + ) + val_dataset_size = len(val_dataset) + if args.validation_subset_manifest is not None: + validation_indices, validation_subset_record = load_validation_subset( + args.validation_subset_manifest, args.val_manifest, data_config, len(val_dataset), + ) + expected_batches = math.ceil(len(validation_indices) / int(data_config["batch_size"])) + if args.validation_batches != expected_batches: + raise ValueError( + f"--validation-batches must be {expected_batches} to evaluate the complete fixed subset" + ) + val_evaluated_samples = len(validation_indices) + else: + val_evaluated_samples = min( + len(val_dataset), args.validation_batches * int(data_config["batch_size"]), + ) + validation_generator = torch.Generator().manual_seed(seed + 20_000_000) + validation_indices = torch.randperm( + len(val_dataset), generator=validation_generator, + )[:val_evaluated_samples].tolist() + validation_subset = Subset(val_dataset, validation_indices) + val_loader = DataLoader( + validation_subset, batch_size=int(data_config["batch_size"]), shuffle=False, + generator=torch.Generator().manual_seed(seed + 30_000_000), + num_workers=args.num_workers, persistent_workers=args.num_workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + log_path = args.output_dir / "train_metrics.jsonl" + validation_log_path = args.output_dir / "validation.jsonl" + best_metric_name = "absolute_camera_mpjpe_mm" + best_metric, no_improvement_validations = validation_state_from_log(validation_log_path, best_metric_name) + best_z_metric_name = "translation_z_mae_mm" + best_z_metric, _ = validation_state_from_log(validation_log_path, best_z_metric_name) + torch.cuda.reset_peak_memory_stats(device) + started = time.perf_counter() + completed_step = start_step + processed_frames = 0 + last_validation_step = -1 + stopped_for_time = False + stopped_for_early_stopping = False + for step, batch in zip(range(start_step, args.max_steps), loader, strict=True): + if args.max_minutes is not None and time.perf_counter() - started >= args.max_minutes * 60: + stopped_for_time = True + break + batch = move_to_device(batch, device) + processed_frames += int(batch["frame_valid"].sum()) + learning_rate = warmup_cosine_learning_rate( + step, lr_schedule_steps, args.learning_rate, min_learning_rate, + args.warmup_steps, + ) + set_scheduled_learning_rate(optimizer, learning_rate) + optimizer.zero_grad(set_to_none=True) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + loss_diagnostics = criterion.translation_diagnostics(prediction, batch) + if not torch.isfinite(losses["total"]): + raise FloatingPointError(f"NaN/Inf loss at step {step}") + losses["total"].backward() + depth_gate_warmup_active = step < args.depth_gate_warmup_steps + if depth_gate_warmup_active: + for name, parameter in model.named_parameters(): + if ".depth_gate." in name: + parameter.grad = None + grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) + if not torch.isfinite(grad_norm): + raise FloatingPointError(f"NaN/Inf gradient at step {step}") + optimizer.step() + completed_step = step + 1 + record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": step + 1, "seed": seed, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "loss_diagnostics": { + key: float(value.detach()) for key, value in loss_diagnostics.items() + }, + "metrics": camera_metrics(prediction, batch), "gradient_norm": float(grad_norm), + "diagnostics": attention_diagnostics(prediction, batch), + "photometric_augmentation": photometric_diagnostics(batch), + "learning_rate": learning_rate, + "depth_gate_warmup_active": depth_gate_warmup_active, + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "frames_per_s": processed_frames / (time.perf_counter() - started), + } + with log_path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(record) + "\n") + if completed_step % args.checkpoint_interval == 0: + save_checkpoint( + args.output_dir / f"step_{completed_step:07d}.pt", model, optimizer, completed_step, + checkpoint_context, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if val_loader is not None and completed_step % args.validation_interval == 0: + validation = run_validation(model, criterion, val_loader, device, dtype, args.validation_batches) + validation_record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": completed_step, + "batches": args.validation_batches, **validation, + } + with validation_log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(validation_record) + "\n") + last_validation_step = completed_step + current_metric = validation["metrics"].get(best_metric_name, float("inf")) + current_z_metric = validation["metrics"].get(best_z_metric_name, float("inf")) + if current_metric < best_metric: + best_metric = current_metric + no_improvement_validations = 0 + save_checkpoint( + args.output_dir / "best.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_metric_name: best_metric}, "checkpoint_role": "best_absolute"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + else: + no_improvement_validations += 1 + if current_z_metric < best_z_metric: + best_z_metric = current_z_metric + save_checkpoint( + args.output_dir / "best_z.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_z_metric_name: best_z_metric}, "checkpoint_role": "best_z"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if args.early_stopping_patience and no_improvement_validations >= args.early_stopping_patience: + stopped_for_early_stopping = True + break + if val_loader is not None and completed_step > 0 and last_validation_step != completed_step: + validation = run_validation(model, criterion, val_loader, device, dtype, args.validation_batches) + validation_record = { + "timestamp": datetime.now(timezone.utc).isoformat(), "step": completed_step, + "batches": args.validation_batches, **validation, + } + with validation_log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(validation_record) + "\n") + current_metric = validation["metrics"].get(best_metric_name, float("inf")) + current_z_metric = validation["metrics"].get(best_z_metric_name, float("inf")) + if current_metric < best_metric: + best_metric = current_metric + save_checkpoint( + args.output_dir / "best.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_metric_name: best_metric}, "checkpoint_role": "best_absolute"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + if current_z_metric < best_z_metric: + best_z_metric = current_z_metric + save_checkpoint( + args.output_dir / "best_z.pt", model, optimizer, completed_step, + {**checkpoint_context, "best_metric": {best_z_metric_name: best_z_metric}, "checkpoint_role": "best_z"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + final_checkpoint = args.output_dir / f"step_{completed_step:07d}_final.pt" + save_checkpoint( + final_checkpoint, model, optimizer, completed_step, + {**checkpoint_context, "checkpoint_role": "final"}, + exclude_prefixes=excluded_checkpoint_prefixes, + ) + summary = { + "status": ( + "stopped_early_validation" if stopped_for_early_stopping else + "stopped_time_budget" if stopped_for_time else "completed" + ), + "config": config, "model_config": asdict(model_config), "loss_config": asdict(loss_config), + "seed": seed, "dataset_clips": len(dataset), "validation_manifest": str(args.val_manifest) if args.val_manifest else None, + "validation_dataset_clips": val_dataset_size, "validation_evaluated_samples": val_evaluated_samples, + "validation_sampling": ( + validation_subset_record.get("version") if validation_subset_record is not None else + "fixed_seed_uniform_random_subset_v1" if val_loader is not None else None + ), + "validation_subset_manifest": str(args.validation_subset_manifest.resolve()) if args.validation_subset_manifest else None, + "run_provenance": str(provenance_path), + "initialization": checkpoint_context["initialization_checkpoint"], + "start_step": start_step, "completed_step": completed_step, "requested_max_steps": args.max_steps, + "elapsed_minutes": (time.perf_counter() - started) / 60, + "sampler": checkpoint_context["sampler"], + "sampling_manifest": ( + str(Path(sampling_config["manifest"]).resolve()) + if sampling_manifest_record is not None else None + ), + "learning_rate_schedule": { + "name": "warmup_cosine_clamped", "base_lr": args.learning_rate, + "min_lr": min_learning_rate, "warmup_steps": args.warmup_steps, + "total_steps": lr_schedule_steps, + "training_max_steps": args.max_steps, + "backbone_lr_scale": next( + ( + float(group["lr_scale"]) + for group in optimizer.param_groups + if group.get("group_name") == "dinov3_backbone" + ), + None, + ), + "deterministic_training": deterministic_training, + }, + "best_validation": {best_metric_name: best_metric if math.isfinite(best_metric) else None}, + "best_z_validation": {best_z_metric_name: best_z_metric if math.isfinite(best_z_metric) else None}, + "best_z_checkpoint": str(args.output_dir / "best_z.pt") if (args.output_dir / "best_z.pt").is_file() else None, + "early_stopping_patience": args.early_stopping_patience, + "validation_checks_without_improvement": no_improvement_validations, + "best_checkpoint": str(args.output_dir / "best.pt") if (args.output_dir / "best.pt").is_file() else None, + "final_checkpoint": str(final_checkpoint), "git_status": git_state(), + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "frames_per_s": processed_frames / max(time.perf_counter() - started, 1e-6), + "precision": config["precision"], "gpu": torch.cuda.get_device_name(device), + "trainable_parameters": sum(parameter.numel() for parameter in model.parameters() if parameter.requires_grad), + "frozen_parameters": sum(parameter.numel() for parameter in model.parameters() if not parameter.requires_grad), + } + (args.output_dir / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/train_phase7_external.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/train_phase7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..fba61b4edae8c4636a2bb46343fa410e3885120a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/scripts/train_phase7_external.py @@ -0,0 +1,1316 @@ +#!/usr/bin/env python3 +"""External-only Phase 7 training over hash-bound unified clip caches.""" + +from __future__ import annotations + +import argparse +from collections import Counter +import copy +from dataclasses import asdict +from datetime import datetime, timezone +import hashlib +import json +import math +import os +from pathlib import Path +import random +import shlex +import socket +import subprocess +import sys +import time +from typing import Any + +import numpy as np +import torch +import yaml +from torch.utils.data import DataLoader + +from foundation_hand.data import ( + CachedUnifiedClipDataset, + ResumableMixtureBatchSampler, + UnifiedConcatDataset, + collate_h2o_clips, +) +from foundation_hand.models import BimanualReconstructionModel, ModelConfig +from foundation_hand.training import BimanualLoss, LossConfig +from foundation_hand.training.checkpoint import load_checkpoint, save_checkpoint +from foundation_hand.training.metrics import camera_metrics +from foundation_hand.training.optimizer import ( + clear_staged_later_gradients, + checkpoint_excluded_prefixes, + optimizer_parameter_groups, + set_scheduled_learning_rate, + set_staged_parameter_group_phase, + staged_optimizer_parameter_groups, +) +from foundation_hand.training.schedule import warmup_cosine_learning_rate +from foundation_hand.data.cached_unified_dataset import DEPTH_CORRUPTIONS +from scripts.train_experiment import attach_gt_vertices, move_to_device + + +PHASE9_H2O_TRAIN_MANIFESTS = { + "full_data_640": Path( + "/SSD3/jiasen/foundation_hand/phase7_artifacts/cache/" + "h2o_official_train7000_v1/cache_manifest.jsonl" + ), + "resolution_896x512": Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "cache/h2o_train7000/cache_manifest.jsonl" + ), +} +PHASE9_H2O_TRAIN_MANIFESTS.update({ + "shared_augmentation_640": PHASE9_H2O_TRAIN_MANIFESTS["full_data_640"], + "shared_augmentation_896x512": PHASE9_H2O_TRAIN_MANIFESTS[ + "resolution_896x512" + ], +}) +PHASE9_H2O_FOLD_ROOTS = { + "full_data_640": Path("artifacts/phase9/manifests/h2o_multifold_v1"), + "resolution_896x512": Path( + "/SSD2/jiasen/foundation_hand/phase9_artifacts/resolution_896x512/" + "manifests/h2o_multifold_v1" + ), +} +PHASE9_H2O_FOLD_ROOTS.update({ + "shared_augmentation_640": PHASE9_H2O_FOLD_ROOTS["full_data_640"], + "shared_augmentation_896x512": PHASE9_H2O_FOLD_ROOTS[ + "resolution_896x512" + ], +}) +PHASE9_DATASETS = ("H2O", "HOT3D", "HOI4D", "ARCTIC") + + +def sha256(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def git_output(*arguments: str) -> str: + return subprocess.run( + ["git", *arguments], text=True, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, check=False, + ).stdout.strip() + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def assert_physical_gpu_idle(physical_gpu_id: int) -> None: + """Fail before CUDA allocation if another compute process owns the GPU.""" + + inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid", "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ).stdout.splitlines() + mapping = { + int(line.split(",", 1)[0].strip()): line.split(",", 1)[1].strip() + for line in inventory if line.strip() + } + if physical_gpu_id not in mapping: + raise RuntimeError(f"physical GPU {physical_gpu_id} is not present") + compute = subprocess.run( + [ + "nvidia-smi", "--query-compute-apps=gpu_uuid,pid,process_name", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, + ).stdout.splitlines() + owners = [line for line in compute if line.split(",", 1)[0].strip() == mapping[physical_gpu_id]] + if owners: + raise RuntimeError( + f"physical GPU {physical_gpu_id} is not idle: " + "; ".join(owners) + ) + + +def claim_physical_gpu(physical_gpu_id: int) -> bool: + """Atomically reserve an idle GPU across FoundationHand queue processes.""" + + path = Path(f"/tmp/foundation_hand_{os.getuid()}_gpu{physical_gpu_id}.claim") + owner = os.getpid() + while True: + try: + descriptor = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + try: + recorded = int(path.read_text(encoding="ascii").strip()) + except (OSError, ValueError): + recorded = -1 + if recorded == owner: + return True + try: + os.kill(recorded, 0) + except (OSError, ValueError): + try: + path.unlink() + except FileNotFoundError: + pass + continue + return False + else: + with os.fdopen(descriptor, "w", encoding="ascii") as handle: + handle.write(f"{owner}\n") + return True + + +def release_physical_gpu_claim(physical_gpu_id: int) -> None: + """Release a claim owned by this process after a failed stability check.""" + + path = Path(f"/tmp/foundation_hand_{os.getuid()}_gpu{physical_gpu_id}.claim") + try: + if int(path.read_text(encoding="ascii").strip()) == os.getpid(): + path.unlink() + except (FileNotFoundError, OSError, ValueError): + return + + +def contains_h2o(value: str) -> bool: + return any(part.lower() == "h2o" for part in Path(value).parts) + + +def load_cache_rows(path: Path) -> list[dict[str, Any]]: + return [ + json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + + +def validate_external_contract(config: dict[str, Any], config_path: Path) -> list[str]: + errors: list[str] = [] + experiment = config.get("experiment", {}) + if int(experiment.get("phase", -1)) not in {7, 8}: + errors.append("external-only experiment.phase must be 7 or 8") + if experiment.get("branch") != "external_only": + errors.append("experiment.branch must be external_only") + if experiment.get("uses_h2o_training_data") is not False: + errors.append("uses_h2o_training_data must be explicitly false") + if config.get("model", {}).get("dinov3_trainable_last_blocks", 0) != 0: + errors.append("Phase 7 external screen requires frozen DINO") + if float(config.get("model", {}).get("modality_dropout_prob", 0.0)) != 0.0: + errors.append("model modality dropout is frame-wise; use source clip dropout instead") + sources = config.get("data", {}).get("sources", []) + if not sources: + errors.append("at least one external source is required") + source_ids: set[str] = set() + for source in sources: + name = str(source.get("dataset", "")) + source_id = str(source.get("source_id", name)) + if source_id in source_ids: + errors.append(f"duplicate external source_id: {source_id}") + source_ids.add(source_id) + manifest = str(source.get("cache_manifest", "")) + if name.upper() not in {"HOT3D", "HOI4D", "ARCTIC"}: + errors.append(f"unsupported external source: {name}") + if contains_h2o(manifest) or name.upper() == "H2O": + errors.append(f"H2O source forbidden in external-only training: {manifest}") + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"source weight must be positive: {name}") + if name.upper() == "HOT3D" and float(source.get("K_input_dropout", -1)) != 0.3: + errors.append("HOT3D K_input_dropout must equal frozen clip-level 0.3") + if contains_h2o(str(config_path)): + errors.append("external-only config path must not be under an H2O directory") + if "initialization_checkpoint" in experiment: + errors.append("external-only configs may not define initialization_checkpoint") + return errors + + +def validate_adaptation_contract(config: dict[str, Any]) -> list[str]: + errors: list[str] = [] + experiment = config.get("experiment", {}) + if int(experiment.get("phase", -1)) not in {7, 8}: + errors.append("adaptation experiment.phase must be 7 or 8") + if experiment.get("branch") != "h2o_adaptation": + errors.append("experiment.branch must be h2o_adaptation") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("H2O adaptation must explicitly use H2O training data") + expected_init = str(experiment.get("initialization_checkpoint_sha256", "")) + if len(expected_init) != 64: + errors.append("adaptation requires a frozen initialization checkpoint SHA256") + if config.get("model", {}).get("dinov3_trainable_last_blocks", 0) != 0: + errors.append("adaptation requires frozen DINO") + if float(config.get("model", {}).get("modality_dropout_prob", 0.0)) != 0.0: + errors.append("use source clip dropout instead of frame-wise model dropout") + sources = config.get("data", {}).get("sources", []) + if not sources or not any(str(source.get("dataset", "")).upper() == "H2O" for source in sources): + errors.append("adaptation requires an H2O official-train source") + allowed = {"H2O", "HOT3D", "HOI4D", "ARCTIC"} + source_ids: set[str] = set() + for source in sources: + name = str(source.get("dataset", "")).upper() + source_id = str(source.get("source_id", name)) + if source_id in source_ids: + errors.append(f"duplicate adaptation source_id: {source_id}") + source_ids.add(source_id) + role = str(source.get("split_role", "")) + if name not in allowed: + errors.append(f"unsupported adaptation source: {name}") + if name == "H2O" and role != "official_train": + errors.append("H2O adaptation source must be official_train") + if name == "H2O" and Path(str(source.get("cache_manifest", ""))).name != "train_fit.jsonl": + errors.append("H2O adaptation training requires frozen train_fit.jsonl") + if name != "H2O" and role != "external_train": + errors.append(f"external replay source must be external_train: {name}") + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"source weight must be positive: {name}") + if name == "HOT3D" and float(source.get("K_input_dropout", -1)) != 0.3: + errors.append("HOT3D replay K_input_dropout must equal 0.3") + if sources and not math.isclose( + sum(float(source.get("weight", 0.0)) for source in sources), 1.0, + rel_tol=0.0, abs_tol=1e-8, + ): + errors.append("adaptation source weights must sum to one") + validation_sources = config.get("data", {}).get("validation_sources", []) + if len(validation_sources) != 1: + errors.append("adaptation requires exactly one H2O train-group-heldout source") + else: + validation = validation_sources[0] + if ( + str(validation.get("dataset", "")).upper() != "H2O" + or validation.get("split_role") != "train_group_heldout" + or Path(str(validation.get("cache_manifest", ""))).name + != "train_group_heldout.jsonl" + ): + errors.append("adaptation validation must be frozen H2O train_group_heldout.jsonl") + staged = config.get("protocol", {}).get("staged_adaptation") + if staged is not None: + prefixes = staged.get("initial_trainable_prefixes", []) + unfreeze_step = int(staged.get("unfreeze_step", -1)) + scale = float(staged.get("unfrozen_learning_rate_scale", -1.0)) + if not isinstance(prefixes, list) or not prefixes or not all( + isinstance(prefix, str) and prefix for prefix in prefixes + ): + errors.append("staged adaptation requires nonempty trainable prefixes") + if not 0 < unfreeze_step < int(config.get("protocol", {}).get("max_steps", 0)): + errors.append("staged adaptation unfreeze_step must be within training horizon") + if not 0.0 < scale <= 1.0: + errors.append("staged adaptation LR scale must be in (0, 1]") + return errors + + +def validate_h2o_neutral_control_contract(config: dict[str, Any]) -> list[str]: + """Validate the random-task-head H2O control without faking an init checkpoint.""" + + experiment = config.get("experiment", {}) + errors: list[str] = [] + if int(experiment.get("phase", -1)) != 8: + errors.append("neutral H2O control must be registered in Phase 8") + if experiment.get("branch") != "h2o_neutral_control": + errors.append("neutral H2O control branch is invalid") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("neutral H2O control must explicitly use H2O training data") + if experiment.get("neutral_task_heads") is not True: + errors.append("neutral H2O control must explicitly declare neutral_task_heads=true") + if any(key.startswith("initialization_checkpoint") for key in experiment): + errors.append("neutral H2O control forbids initialization checkpoint fields") + adaptation_view = copy.deepcopy(config) + adaptation_view["experiment"].update({ + "phase": 7, + "branch": "h2o_adaptation", + "initialization_checkpoint_sha256": "0" * 64, + }) + errors.extend(validate_adaptation_contract(adaptation_view)) + sources = config.get("data", {}).get("sources", []) + if len(sources) != 1 or str(sources[0].get("dataset", "")).upper() != "H2O": + errors.append("neutral H2O control must use only H2O official train") + return errors + + +def validate_phase9_unified_contract( + config: dict[str, Any], config_path: Path, +) -> list[str]: + """Validate the shared four-source Phase 9 direct-XYZ training contract.""" + + errors: list[str] = [] + experiment = config.get("experiment", {}) + specialization = experiment.get("data_only_amendment") == "arctic_h2o_s9_v2_20260917" + data = config.get("data", {}) + model = config.get("model", {}) + loss = config.get("loss", {}) + if int(experiment.get("phase", -1)) != 9: + errors.append("Phase 9 unified training requires experiment.phase=9") + if experiment.get("branch") != "phase9_unified": + errors.append("Phase 9 unified training requires branch=phase9_unified") + if experiment.get("uses_h2o_training_data") is not True: + errors.append("Phase 9 unified training must declare H2O training use") + if experiment.get("h2o_official_validation_used_for_selection") is not False: + errors.append("H2O official validation must be excluded from selection") + if experiment.get("official_test_used") is not False: + errors.append("official test must be explicitly unused") + if len(str(experiment.get("initialization_checkpoint_sha256", ""))) != 64: + errors.append("Phase 9 requires a hash-bound external initialization") + if "phase9" not in {part.lower() for part in config_path.parts}: + errors.append("Phase 9 unified config must live under configs/phase9") + + phase9_stage = str(experiment.get("phase9_stage", "full_data_640")) + last2_stage = phase9_stage in {"last2_5e7", "last2_1e6"} + expected_model = { + "decoder_mode": "alternating", + "use_temporal": True, + "translation_parameterization": "direct_xyz", + "dinov3_trainable_last_blocks": 2 if last2_stage else 0, + "temporal_attention_mode": "bidirectional", + } + for key, expected in expected_model.items(): + if model.get(key) != expected: + errors.append(f"Phase 9 frozen model contract requires {key}={expected}") + if not math.isclose( + float(loss.get("joint3d_root_relative", 0.0)), + 10.0, + rel_tol=0.0, + abs_tol=1e-8, + ): + errors.append( + "Phase 9 frozen loss contract requires joint3d_root_relative=10.0" + ) + resolution = list(data.get("resolution_hw", [])) + if last2_stage: + expected_resolution = list(experiment.get("last2_resolution_hw", [])) + if expected_resolution not in ([368, 640], [512, 896]): + errors.append("Phase 9 last-2 requires a frozen 640 or 896 resolution") + h2o_contract_stage = ( + "resolution_896x512" + if expected_resolution == [512, 896] + else "full_data_640" + ) + else: + expected_resolution = { + "full_data_640": [368, 640], + "resolution_896x512": [512, 896], + "shared_augmentation_640": [368, 640], + "shared_augmentation_896x512": [512, 896], + }.get(phase9_stage) + h2o_contract_stage = phase9_stage + if expected_resolution is None: + errors.append(f"unsupported Phase 9 stage contract: {phase9_stage}") + elif resolution != expected_resolution or int(data.get("T", -1)) != 8: + errors.append( + f"Phase 9 {phase9_stage} contract requires " + f"{expected_resolution[1]}x{expected_resolution[0]} and T=8" + ) + shared_augmentation_stage = phase9_stage in { + "shared_augmentation_640", "shared_augmentation_896x512", + } or (last2_stage and experiment.get("last2_shared_augmentation") is True) + geometry = data.get("geometry_augmentation", {}) + expected_geometry = { + "enabled": True, "probability": 0.8, + "scale_min": 0.9, "scale_max": 1.1, + "translation_fraction": 0.05, + } + if shared_augmentation_stage: + if geometry != expected_geometry: + errors.append("Phase 9 shared geometry augmentation parameters differ") + elif bool(geometry.get("enabled", False)): + errors.append("Phase 9 shared geometry augmentation is not yet admitted") + if last2_stage: + if model.get("encoder") != "dinov3": + errors.append("Phase 9 last-2 requires the shared DINOv3 encoder") + if model.get("dinov3_model", "dinov3_vitb16") != "dinov3_vitb16": + errors.append("Phase 9 last-2 admits DINO Base only") + expected_backbone_lr = 5e-7 if phase9_stage == "last2_5e7" else 1e-6 + actual_backbone_lr = config.get("protocol", {}).get( + "backbone_learning_rate" + ) + if actual_backbone_lr is None or not math.isclose( + float(actual_backbone_lr), expected_backbone_lr, + rel_tol=0.0, abs_tol=1e-15, + ): + errors.append( + f"Phase 9 {phase9_stage} requires backbone learning rate " + f"{expected_backbone_lr}" + ) + elif config.get("protocol", {}).get("backbone_learning_rate") is not None: + errors.append("Phase 9 frozen-DINO stages forbid backbone learning rate") + if int(config.get("seed", -1)) != 20260717: + errors.append("Phase 9 primary seed must be 20260717") + + sources = data.get("sources", []) + names = [str(source.get("dataset", "")).upper() for source in sources] + if specialization: + if len(sources) != 2 or set(names) != {"H2O", "ARCTIC"}: + errors.append("Specialization requires exactly H2O and ARCTIC") + weights = {source["dataset"]: float(source["weight"]) for source in sources} + if not any(all(math.isclose(weights.get(k, -1), v, abs_tol=1e-10) + for k, v in pair.items()) + for pair in ({"H2O": 0.5, "ARCTIC": 0.5}, + {"H2O": 1 / 3, "ARCTIC": 2 / 3})): + errors.append("Unregistered specialization ratio") + if phase9_stage != "last2_1e6": + errors.append("Specialization must retain last2_1e6") + parent_config = Path(experiment["parent_config"]) + if sha256(parent_config) != experiment["parent_config_sha256"]: + errors.append("Parent configuration hash differs") + parent = yaml.safe_load(parent_config.read_text()) + for section in ("model", "loss", "precision"): + if config[section] != parent[section]: + errors.append(f"Specialization changed parent {section}") + expected_protocol = copy.deepcopy(parent["protocol"]) + for milestone in expected_protocol.get("source_exposure_milestones", []): + milestone["minimum_batches"] = { + k: v for k, v in milestone["minimum_batches"].items() + if k in {"H2O", "ARCTIC"} + } + if config["protocol"] != expected_protocol: + errors.append("Data-only experiment must preserve the complete Stage 9 protocol") + if {k: v for k, v in data.items() if k != "sources"} != { + k: v for k, v in parent["data"].items() if k != "sources" + }: + errors.append("Data-only experiment changed augmentation, batch size, or sequence settings") + if experiment["initialization_checkpoint_sha256"] != parent["experiment"]["initialization_checkpoint_sha256"]: + errors.append("Data-only experiment must use the same E40 initialization as Stage 9") + if config["seed"] != parent["seed"]: + errors.append("Data-only experiment changed the Stage 9 seed") + for source in sources: + original = next((s for s in parent["data"]["sources"] + if s["dataset"] == source["dataset"]), None) + if original is None: + errors.append("Unknown source in data-only experiment") + continue + if {k: v for k, v in source.items() if k != "weight"} != { + k: v for k, v in original.items() if k != "weight" + }: + errors.append(f"Specialization changed source contract: {source['dataset']}") + elif len(sources) != 4 or set(names) != set(PHASE9_DATASETS): + errors.append("Phase 9 unified training requires exactly H2O/HOT3D/HOI4D/ARCTIC") + source_ids = [str(source.get("source_id", source.get("dataset", ""))) for source in sources] + if len(set(source_ids)) != len(source_ids): + errors.append("Phase 9 sampling source IDs must be unique") + if sources and not math.isclose( + sum(float(source.get("weight", 0.0)) for source in sources), + 1.0, rel_tol=0.0, abs_tol=1e-8, + ): + errors.append("Phase 9 source weights must sum to one") + for source, name in zip(sources, names): + if float(source.get("weight", 0.0)) <= 0.0: + errors.append(f"Phase 9 source weight must be positive: {name}") + expected_role = "official_train" if name == "H2O" else "external_train" + if source.get("split_role") != expected_role: + errors.append(f"Phase 9 {name} split role must be {expected_role}") + expected_k_dropout = 0.3 if name == "HOT3D" else 0.0 + if float(source.get("K_input_dropout", -1.0)) != expected_k_dropout: + errors.append(f"Phase 9 {name} K_input_dropout must equal {expected_k_dropout}") + corruption_probability = float( + source.get("depth_corruption_probability", 0.0) + ) + expected_corruption_probability = ( + 0.3 if shared_augmentation_stage and name in {"H2O", "HOI4D"} + else 0.0 + ) + if not math.isclose( + corruption_probability, expected_corruption_probability, + rel_tol=0.0, abs_tol=1e-12, + ): + errors.append( + f"Phase 9 {name} depth corruption probability must equal " + f"{expected_corruption_probability}" + ) + + selection_fold = experiment.get("h2o_selection_fold") + h2o_sources = [source for source, name in zip(sources, names) if name == "H2O"] + validation_sources = data.get("validation_sources", []) + if h2o_sources: + h2o_manifest = Path(str(h2o_sources[0].get("cache_manifest", ""))).resolve() + expected_h2o_manifest = PHASE9_H2O_TRAIN_MANIFESTS.get( + h2o_contract_stage + ) + fold_root = PHASE9_H2O_FOLD_ROOTS.get(h2o_contract_stage) + if selection_fold is None: + if ( + expected_h2o_manifest is None + or h2o_manifest != expected_h2o_manifest.resolve() + ): + errors.append( + "Phase 9 full run must use its stage-matched frozen H2O train cache" + ) + if validation_sources: + errors.append("Phase 9 full run cannot validate on leaked train subsets") + else: + if fold_root is None: + errors.append("Phase 9 fold stage has no admitted manifest root") + fold_root = Path("/__invalid_phase9_fold_root__") + expected_train = (fold_root.resolve() / f"{selection_fold}_train.jsonl") + expected_heldout = ( + fold_root.resolve() / f"{selection_fold}_heldout.jsonl" + ) + if h2o_manifest != expected_train: + errors.append("Phase 9 fold run H2O train manifest does not match its fold") + if len(validation_sources) != 1: + errors.append("Phase 9 fold run requires exactly its H2O heldout source") + elif ( + str(validation_sources[0].get("dataset", "")).upper() != "H2O" + or Path(str(validation_sources[0].get("cache_manifest", ""))).resolve() + != expected_heldout + ): + errors.append("Phase 9 fold validation manifest does not match its fold") + + valid_source_ids = set(source_ids) + milestone_ids: set[str] = set() + for milestone in config.get("protocol", {}).get("source_exposure_milestones", []): + milestone_id = str(milestone.get("id", "")) + minimum = milestone.get("minimum_batches", {}) + if not milestone_id or milestone_id in milestone_ids: + errors.append("Phase 9 exposure milestone IDs must be nonempty and unique") + milestone_ids.add(milestone_id) + if not minimum or not set(minimum).issubset(valid_source_ids): + errors.append(f"invalid source keys in exposure milestone: {milestone_id}") + if any(int(value) <= 0 for value in minimum.values()): + errors.append(f"exposure milestone counts must be positive: {milestone_id}") + return errors + + +def reached_source_exposure_milestones( + milestones: list[dict[str, Any]], + counts: Counter[str], + completed: set[str], +) -> list[str]: + reached = [] + for milestone in milestones: + milestone_id = str(milestone["id"]) + if milestone_id in completed: + continue + minimum = milestone["minimum_batches"] + if all(counts[source_id] >= int(target) for source_id, target in minimum.items()): + reached.append(milestone_id) + return reached + + +def checkpoint_context_with_exposure( + context: dict[str, Any], + source_batches: Counter[str], + source_frames: Counter[str], + depth_conditions: Counter[str], + completed_milestones: set[str], +) -> dict[str, Any]: + return { + **context, + "source_exposure_batches": dict(source_batches), + "source_exposure_frames": dict(source_frames), + "depth_input_condition_frames": dict(depth_conditions), + "completed_source_exposure_milestones": sorted(completed_milestones), + } + + +def validate_cache_manifest( + path: Path, expected_dataset: str, allow_h2o: bool = False, +) -> tuple[list[dict], list[str]]: + errors: list[str] = [] + if not path.is_file(): + return [], [f"cache manifest missing: {path}"] + rows = load_cache_rows(path) + if not rows: + errors.append(f"cache manifest is empty: {path}") + for index, row in enumerate(rows): + dataset = str(row.get("dataset_id", "")) + cache_path = Path(str(row.get("cache_path", ""))) + if dataset.upper() != expected_dataset.upper(): + errors.append(f"row {index} dataset mismatch: {dataset} != {expected_dataset}") + if not allow_h2o and ( + dataset.upper() == "H2O" or contains_h2o(str(cache_path)) + ): + errors.append(f"row {index} contains forbidden H2O data") + if not cache_path.is_file(): + errors.append(f"row {index} cache missing: {cache_path}") + if not row.get("cache_sha256"): + errors.append(f"row {index} lacks cache_sha256") + if len(errors) >= 20: + errors.append("additional cache errors omitted") + break + return rows, errors + + +def write_provenance( + output: Path, + config_path: Path, + config: dict[str, Any], + source_hashes: dict[str, str], + resume: Path | None, + initialization_checkpoint: Path | None = None, +) -> dict[str, Any]: + inventory = subprocess.run( + [ + "nvidia-smi", "--query-gpu=index,uuid,name,memory.total,memory.used", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, + ).stdout.strip().splitlines() + record = { + "timestamp_utc": utc_now(), + "hostname": socket.gethostname(), + "git_commit": git_output("rev-parse", "HEAD"), + "git_status": git_output("status", "--short"), + "command_argv": [sys.executable, *sys.argv], + "command_shell": shlex.join([sys.executable, *sys.argv]), + "working_directory": str(Path.cwd()), + "config_path": str(config_path.resolve()), + "config_sha256": sha256(config_path), + "config": config, + "source_manifest_sha256": source_hashes, + "resume_checkpoint": str(resume.resolve()) if resume else None, + "cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES"), + "gpu_inventory": inventory, + "python": sys.version, + "torch": torch.__version__, + "torch_cuda": torch.version.cuda, + "external_only_neutral_heads": ( + config.get("experiment", {}).get("branch") == "external_only" + ), + "neutral_task_heads": ( + config.get("experiment", {}).get("branch") + in {"external_only", "h2o_neutral_control"} + ), + "initialization_checkpoint": ( + { + "path": str(initialization_checkpoint.resolve()), + "sha256": sha256(initialization_checkpoint), + } + if initialization_checkpoint is not None else None + ), + "h2o_initialization_used": False, + "h2o_training_data_used": bool( + config.get("experiment", {}).get("uses_h2o_training_data", False) + ), + "official_test_used": False, + } + name = "run_provenance.json" if resume is None else f"resume_provenance_{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}.json" + (output / name).write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8") + return record + + +def source_batch_counts(batch: dict[str, Any]) -> dict[str, int]: + values = batch.get("sampling_source_id", batch.get("dataset_id", [])) + if isinstance(values, str): + values = [values] + return dict(Counter(str(value) for value in values)) + + +def source_frame_counts(batch: dict[str, Any]) -> dict[str, int]: + datasets = batch.get("sampling_source_id", batch.get("dataset_id", [])) + if isinstance(datasets, str): + datasets = [datasets] + valid = batch["frame_valid"].detach().cpu() + counts: Counter[str] = Counter() + for index, dataset in enumerate(datasets): + counts[str(dataset)] += int(valid[index].sum()) + return dict(counts) + + +def depth_input_condition_counts(batch: dict[str, Any]) -> dict[str, int]: + codes = batch.get("depth_input_condition_code") + if codes is None: + return {} + names = {0: "source_unavailable", 1: "rgb_k", 2: "clean_rgb_d_k"} + names.update({3 + index: f"corrupted_{name}" for index, name in enumerate(DEPTH_CORRUPTIONS)}) + values = codes.detach().cpu().reshape(-1).tolist() + return dict(Counter(names.get(int(value), f"unknown_{int(value)}") for value in values)) + + +def gpu_telemetry(physical_gpu_id: int) -> dict[str, float] | None: + result = subprocess.run( + [ + "nvidia-smi", f"--id={physical_gpu_id}", + "--query-gpu=utilization.gpu,memory.used", + "--format=csv,noheader,nounits", + ], text=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, + ) + if result.returncode != 0 or not result.stdout.strip(): + return None + utilization, memory = result.stdout.strip().split(",")[:2] + return { + "gpu_utilization_percent": float(utilization.strip()), + "gpu_memory_used_mib": float(memory.strip()), + } + + +def run_validation( + model: BimanualReconstructionModel, + criterion: BimanualLoss, + loaders: dict[str, DataLoader], + device: torch.device, + dtype: torch.dtype, + max_batches: int, +) -> dict[str, Any]: + was_training = model.training + model.eval() + sources: dict[str, Any] = {} + with torch.inference_mode(): + for name, loader in loaders.items(): + metric_rows: list[dict[str, float]] = [] + loss_rows: list[dict[str, float]] = [] + for batch_index, batch in enumerate(loader): + if batch_index >= max_batches: + break + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + metric_rows.append(camera_metrics(prediction, batch)) + loss_rows.append({key: float(value) for key, value in losses.items()}) + sources[name] = { + "batches": len(metric_rows), + "metrics": { + key: float(np.mean([row[key] for row in metric_rows if math.isfinite(row.get(key, math.nan))])) + for key in sorted({key for row in metric_rows for key in row}) + if any(math.isfinite(row.get(key, math.nan)) for row in metric_rows) + }, + "losses": { + key: float(np.mean([row[key] for row in loss_rows if math.isfinite(row.get(key, math.nan))])) + for key in sorted({key for row in loss_rows for key in row}) + if any(math.isfinite(row.get(key, math.nan)) for row in loss_rows) + }, + } + model.train(was_training) + absolute = [ + record["metrics"]["absolute_camera_mpjpe_mm"] + for record in sources.values() + if "absolute_camera_mpjpe_mm" in record["metrics"] + ] + return { + "sources": sources, + "macro_absolute_camera_mpjpe_mm": float(np.mean(absolute)) if absolute else None, + } + + +def build_datasets( + config: dict[str, Any], seed: int, allow_h2o: bool = False, +) -> tuple[UnifiedConcatDataset, list[int], list[float], dict[str, str]]: + data = config["data"] + expected_resolution_hw = tuple(int(value) for value in data["resolution_hw"]) + datasets = [] + sizes: list[int] = [] + weights: list[float] = [] + hashes: dict[str, str] = {} + for source in data["sources"]: + manifest = Path(source["cache_manifest"]).resolve() + _, errors = validate_cache_manifest( + manifest, str(source["dataset"]), allow_h2o=allow_h2o, + ) + if errors: + raise ValueError("; ".join(errors)) + source_id = str(source.get("source_id", source["dataset"])) + if source_id in hashes: + raise ValueError(f"duplicate training source_id: {source_id}") + dataset = CachedUnifiedClipDataset( + manifest, + K_input_dropout=float(source.get("K_input_dropout", 0.0)), + dropout_seed=seed, + photometric_augmentation=data.get("photometric_augmentation"), + depth_input_dropout=float(source.get("depth_input_dropout", 0.0)), + depth_corruption_probability=float( + source.get("depth_corruption_probability", 0.0) + ), + joint3d_root_relative_scope=str( + source.get("joint3d_root_relative_scope", "auto") + ), + source_id=source_id, + expected_resolution_hw=expected_resolution_hw, + geometry_augmentation=data.get("geometry_augmentation"), + ) + datasets.append(dataset) + sizes.append(len(dataset)) + weights.append(float(source["weight"])) + hashes[source_id] = sha256(manifest) + return UnifiedConcatDataset(datasets), sizes, weights, hashes + + +def build_validation_loaders( + config: dict[str, Any], seed: int, batch_size: int, workers: int, + allow_h2o: bool = False, +) -> dict[str, DataLoader]: + loaders: dict[str, DataLoader] = {} + expected_resolution_hw = tuple( + int(value) for value in config["data"]["resolution_hw"] + ) + for source in config.get("data", {}).get("validation_sources", []): + name = str(source.get("source_id", source["dataset"])) + manifest = Path(source["cache_manifest"]).resolve() + _, errors = validate_cache_manifest( + manifest, str(source["dataset"]), allow_h2o=allow_h2o, + ) + if errors: + raise ValueError("; ".join(errors)) + dataset = CachedUnifiedClipDataset( + manifest, + K_input_dropout=float(source.get("K_input_dropout", 0.0)), + dropout_seed=seed, + joint3d_root_relative_scope=str( + source.get("joint3d_root_relative_scope", "auto") + ), + source_id=str(source.get("source_id", source["dataset"])), + expected_resolution_hw=expected_resolution_hw, + ) + loaders[name] = DataLoader( + dataset, batch_size=batch_size, shuffle=False, num_workers=workers, + persistent_workers=workers > 0, collate_fn=collate_h2o_clips, + pin_memory=True, + ) + return loaders + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--physical-gpu-id", type=int, required=True) + parser.add_argument( + "--allow-physical-gpus-4-5", action="store_true", + help="Explicit resource override; default preserves the historical GPU0-3 contract.", + ) + parser.add_argument("--stop-after-step", type=int) + parser.add_argument( + "--allow-schedule-tail", action="store_true", + help="Allow external-only exact resume beyond max_steps at the clamped minimum LR.", + ) + args = parser.parse_args() + config = yaml.safe_load(args.config.read_text(encoding="utf-8")) + branch = str(config.get("experiment", {}).get("branch", "")) + if branch == "external_only": + errors = validate_external_contract(config, args.config) + if args.init_checkpoint is not None: + errors.append("external-only training forbids checkpoint initialization") + elif branch == "h2o_adaptation": + errors = validate_adaptation_contract(config) + if args.resume is None and args.init_checkpoint is None: + errors.append("new H2O adaptation requires --init-checkpoint") + if args.resume is not None and args.init_checkpoint is not None: + errors.append("--resume and --init-checkpoint are mutually exclusive") + elif branch == "h2o_neutral_control": + errors = validate_h2o_neutral_control_contract(config) + if args.init_checkpoint is not None: + errors.append("neutral H2O control forbids --init-checkpoint") + elif branch == "phase9_unified": + errors = validate_phase9_unified_contract(config, args.config) + if args.resume is None and args.init_checkpoint is None: + errors.append("new Phase 9 unified training requires --init-checkpoint") + if args.resume is not None and args.init_checkpoint is not None: + errors.append("--resume and --init-checkpoint are mutually exclusive") + else: + errors = [f"unsupported Phase 7 training branch: {branch}"] + if errors: + parser.error("; ".join(errors)) + if args.init_checkpoint is not None: + if not args.init_checkpoint.is_file(): + parser.error(f"initialization checkpoint missing: {args.init_checkpoint}") + expected = config["experiment"]["initialization_checkpoint_sha256"] + actual = sha256(args.init_checkpoint) + if actual != expected: + parser.error(f"initialization checkpoint SHA256 mismatch: {actual} != {expected}") + if args.output_dir.exists() and any(args.output_dir.iterdir()) and args.resume is None: + parser.error("--output-dir must be new or empty unless --resume is supplied") + visible = os.environ.get("CUDA_VISIBLE_DEVICES") + if visible != str(args.physical_gpu_id): + parser.error( + "CUDA_VISIBLE_DEVICES must name exactly --physical-gpu-id for auditable launch" + ) + allowed_physical_gpus = {0, 1, 2, 3} + if args.allow_physical_gpus_4_5: + allowed_physical_gpus.update((4, 5)) + if args.physical_gpu_id not in allowed_physical_gpus: + parser.error("Phase 7 may use only physical GPUs 0-3; GPU4-5 are reserved") + assert_physical_gpu_idle(args.physical_gpu_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + protocol = config["protocol"] + max_steps = int(protocol["max_steps"]) + run_end_step = max_steps if args.stop_after_step is None else int(args.stop_after_step) + checkpoint_interval = int(protocol["checkpoint_interval"]) + validation_interval = int(protocol["validation_interval"]) + validation_batches = int(protocol["validation_batches"]) + telemetry_interval = int(protocol.get("telemetry_interval", 100)) + workers = int(protocol["num_workers"]) + batch_size = int(config["data"]["batch_size"]) + seed = int(config["seed"]) + if min(max_steps, checkpoint_interval, validation_interval, validation_batches, telemetry_interval) <= 0: + parser.error("step, checkpoint, and validation values must be positive") + if run_end_step <= 0: + parser.error("--stop-after-step must be positive") + if run_end_step > max_steps and not args.allow_schedule_tail: + parser.error("--stop-after-step exceeds protocol.max_steps without --allow-schedule-tail") + if args.allow_schedule_tail and branch != "external_only": + parser.error("--allow-schedule-tail is restricted to external-only training") + + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + allow_h2o = branch in { + "h2o_adaptation", "h2o_neutral_control", "phase9_unified", + } + train_dataset, source_sizes, source_weights, source_hashes = build_datasets( + config, seed, allow_h2o=allow_h2o, + ) + validation_loaders = build_validation_loaders( + config, seed, batch_size, workers, allow_h2o=allow_h2o, + ) + assets = config["assets"] + model_config = ModelConfig( + **config["model"], + dinov3_source=assets["dinov3_source"], + dinov3_weights=assets["dinov3_weights"], + mano_root=assets["mano_root"], + ) + device = torch.device("cuda") + assert_physical_gpu_idle(args.physical_gpu_id) + provenance = write_provenance( + args.output_dir, args.config, config, source_hashes, args.resume, + args.init_checkpoint, + ) + model = BimanualReconstructionModel(model_config).to(device) + initialization_state = None + if args.init_checkpoint is not None: + specialization = config["experiment"].get("data_only_amendment") == "arctic_h2o_s9_v2_20260917" + if specialization: + payload = torch.load(args.init_checkpoint, map_location="cpu", weights_only=False) + if tuple(payload.get("excluded_model_prefixes", ())) != ("rgb_encoder.backbone.",): + raise RuntimeError("E40 exclusion contract differs from historical Stage 9") + missing = set(model.state_dict()) - set(payload["model"]) + if set(payload["model"]) - set(model.state_dict()): + raise RuntimeError("Unexpected E40 tensors") + if missing != {k for k in model.state_dict() if k.startswith("rgb_encoder.backbone.")}: + raise RuntimeError("E40 must supply every non-backbone tensor") + pretrained_backbone = {k: v.detach().cpu().clone() for k, v in model.state_dict().items() if k in missing} + initialization_state = load_checkpoint( + args.init_checkpoint, model, optimizer=None, map_location=device, + ) + if specialization: + if initialization_state["step"] != 200000: + raise RuntimeError("Data-only experiment must initialize from exact E40 200K") + if initialization_state["extra"].get("h2o_training_data_used") is not False: + raise RuntimeError("E40 initialization must retain no-H2O provenance") + if initialization_state["extra"].get("official_test_used") is not False: + raise RuntimeError("Parent official-test isolation is missing") + current = model.state_dict() + assert all(torch.equal(current[k].detach().cpu(), v) for k, v in payload["model"].items()) + assert all(torch.equal(current[k].detach().cpu(), v) for k, v in pretrained_backbone.items()) + composition = { + "initialization_checkpoint": str(args.init_checkpoint.resolve()), + "initialization_checkpoint_sha256": sha256(args.init_checkpoint), + "source_step": 200000, "new_stage_start_step": 0, + "loaded_non_backbone_tensors": len(payload["model"]), + "pretrained_backbone_tensors_preserved": len(pretrained_backbone), + "all_non_backbone_tensors_equal_E40": True, + "depth_and_K_reinitialized": False, + "matches_historical_stage9_initialization": True, + } + (args.output_dir / "initialization_composition.json").write_text(json.dumps(composition, indent=2) + "\n") + del payload, pretrained_backbone, current + elif initialization_state.get("extra", {}).get("h2o_training_data_used") is not False: + raise RuntimeError("adaptation initialization lacks strict no-H2O provenance") + criterion = BimanualLoss(LossConfig(**config.get("loss", {}))).to(device) + learning_rate = float(protocol["learning_rate"]) + minimum_lr = float(protocol["min_learning_rate"]) + warmup_steps = int(protocol["warmup_steps"]) + staged_adaptation = protocol.get("staged_adaptation") + staged_prefixes: tuple[str, ...] = () + if staged_adaptation is not None: + staged_prefixes = tuple(staged_adaptation["initial_trainable_prefixes"]) + parameter_groups = staged_optimizer_parameter_groups( + model, + learning_rate=learning_rate, + initial_trainable_prefixes=staged_prefixes, + unfrozen_learning_rate_scale=float( + staged_adaptation["unfrozen_learning_rate_scale"] + ), + ) + else: + backbone_learning_rate = protocol.get("backbone_learning_rate") + parameter_groups = optimizer_parameter_groups( + model, + learning_rate=learning_rate, + backbone_learning_rate=( + float(backbone_learning_rate) + if backbone_learning_rate is not None else None + ), + ) + optimizer = torch.optim.AdamW( + parameter_groups, + lr=learning_rate, weight_decay=float(protocol.get("weight_decay", 0.05)), + ) + start_step = 0 + resume_extra: dict[str, Any] | None = None + if args.resume is not None: + if not args.resume.is_file(): + parser.error(f"resume checkpoint missing: {args.resume}") + state = load_checkpoint(args.resume, model, optimizer, device) + start_step = int(state["step"]) + resume_extra = state.get("extra", {}) + if resume_extra.get("config_sha256") != provenance["config_sha256"]: + raise RuntimeError("resume config hash differs from checkpoint") + if resume_extra.get("source_manifest_sha256") != source_hashes: + raise RuntimeError("resume source manifests differ from checkpoint") + set_scheduled_learning_rate(optimizer, learning_rate) + if start_step >= max_steps and not args.allow_schedule_tail: + parser.error(f"checkpoint step {start_step} is not below max_steps {max_steps}") + if start_step >= run_end_step: + parser.error( + f"checkpoint step {start_step} is not below this invocation's end step {run_end_step}" + ) + + batch_sampler = ResumableMixtureBatchSampler( + source_sizes, source_weights, batch_size, seed, start_step, run_end_step, + include_epoch=bool(config["data"].get("photometric_augmentation")), + ) + loader = DataLoader( + train_dataset, batch_sampler=batch_sampler, + generator=torch.Generator().manual_seed(seed + 10_000_000), + num_workers=workers, persistent_workers=workers > 0, + collate_fn=collate_h2o_clips, pin_memory=True, + ) + dtype = torch.bfloat16 if config["precision"] == "bf16" else torch.float16 + context = { + "phase": int(config.get("experiment", {}).get("phase", 7)), + "branch": branch, + "config": config, + "config_sha256": provenance["config_sha256"], + "source_manifest_sha256": source_hashes, + "h2o_training_data_used": allow_h2o, + "h2o_checkpoint_initialization_used": False, + "external_initialization_checkpoint": ( + { + "path": str(args.init_checkpoint.resolve()), + "sha256": sha256(args.init_checkpoint), + "source_step": int(initialization_state["step"]), + } + if args.init_checkpoint is not None + else ( + resume_extra.get("external_initialization_checkpoint") + if resume_extra is not None else None + ) + ), + "official_test_used": False, + "checkpoint_role": "periodic", + "schedule_tail": { + "enabled": bool(args.allow_schedule_tail), + "registered_max_steps": max_steps, + "run_end_step": run_end_step, + "learning_rate_after_horizon": minimum_lr, + }, + } + excluded = () if config["experiment"].get("data_only_amendment") else checkpoint_excluded_prefixes(model) + log_path = args.output_dir / "train_metrics.jsonl" + val_path = args.output_dir / "validation.jsonl" + started = time.perf_counter() + processed_frames = 0 + completed_step = start_step + iterator = iter(loader) + telemetry_samples: list[dict[str, float]] = [] + cumulative_source_batches: Counter[str] = Counter( + (resume_extra or {}).get("source_exposure_batches", {}) + ) + cumulative_source_frames: Counter[str] = Counter( + (resume_extra or {}).get("source_exposure_frames", {}) + ) + cumulative_depth_conditions: Counter[str] = Counter( + (resume_extra or {}).get("depth_input_condition_frames", {}) + ) + exposure_milestones = list(protocol.get("source_exposure_milestones", [])) + completed_exposure_milestones = set( + (resume_extra or {}).get("completed_source_exposure_milestones", []) + ) + torch.cuda.reset_peak_memory_stats(device) + for step in range(start_step, run_end_step): + fetch_started = time.perf_counter() + batch = next(iterator) + data_seconds = time.perf_counter() - fetch_started + batch = move_to_device(batch, device) + attach_gt_vertices(batch, model) + step_source_batches = source_batch_counts(batch) + step_source_frames = source_frame_counts(batch) + step_depth_conditions = depth_input_condition_counts(batch) + cumulative_source_batches.update(step_source_batches) + cumulative_source_frames.update(step_source_frames) + cumulative_depth_conditions.update(step_depth_conditions) + processed_frames += int(batch["frame_valid"].sum()) + scheduled_lr = warmup_cosine_learning_rate( + step, max_steps, learning_rate, minimum_lr, warmup_steps, + ) + staged_later_active = bool( + staged_adaptation is not None + and step >= int(staged_adaptation["unfreeze_step"]) + ) + if staged_adaptation is not None: + set_staged_parameter_group_phase( + optimizer, active=staged_later_active, + ) + set_scheduled_learning_rate(optimizer, scheduled_lr) + optimizer.zero_grad(set_to_none=True) + forward_start = torch.cuda.Event(enable_timing=True) + forward_end = torch.cuda.Event(enable_timing=True) + backward_end = torch.cuda.Event(enable_timing=True) + forward_start.record() + with torch.autocast("cuda", dtype=dtype): + prediction = model(batch) + losses = criterion(prediction, batch) + forward_end.record() + if not torch.isfinite(losses["total"]): + raise FloatingPointError(f"non-finite loss at step {step + 1}") + losses["total"].backward() + if staged_adaptation is not None and not staged_later_active: + clear_staged_later_gradients(model, staged_prefixes) + group_norms = { + group["group_name"]: float(torch.linalg.vector_norm(torch.stack([ + p.grad.detach().float().norm() for p in group["params"] if p.grad is not None + ]))) for group in optimizer.param_groups + } + gradient_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10.0) + if not torch.isfinite(gradient_norm): + raise FloatingPointError(f"non-finite gradient at step {step + 1}") + optimizer.step() + backward_end.record() + torch.cuda.synchronize(device) + completed_step = step + 1 + elapsed = time.perf_counter() - started + record = { + "timestamp_utc": utc_now(), + "step": completed_step, + "seed": seed, + "source_counts": step_source_batches, + "source_frame_counts": step_source_frames, + "depth_input_condition_counts": step_depth_conditions, + "losses": {key: float(value.detach()) for key, value in losses.items()}, + "metrics": camera_metrics(prediction, batch), + "gradient_norm": float(gradient_norm), + "gradient_group_norms_preclip": group_norms, + "clip_scale": min(1.0, 10.0 / (float(gradient_norm) + 1e-6)), + "optimizer_group_lrs": {g["group_name"]: g["lr"] for g in optimizer.param_groups}, + "learning_rate": scheduled_lr, + "staged_adaptation": ( + { + "later_group_active": staged_later_active, + "unfreeze_step": int(staged_adaptation["unfreeze_step"]), + "unfrozen_learning_rate_scale": float( + staged_adaptation["unfrozen_learning_rate_scale"] + ), + } + if staged_adaptation is not None else None + ), + "timing": { + "data_loading_seconds": data_seconds, + "forward_seconds": forward_start.elapsed_time(forward_end) / 1000.0, + "backward_optimizer_seconds": forward_end.elapsed_time(backward_end) / 1000.0, + "steps_per_second": (completed_step - start_step) / elapsed, + "frames_per_second": processed_frames / elapsed, + }, + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + } + if completed_step == start_step + 1 or completed_step % telemetry_interval == 0: + telemetry = gpu_telemetry(args.physical_gpu_id) + if telemetry is not None: + telemetry_samples.append(telemetry) + record["gpu_telemetry"] = telemetry + with log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(record) + "\n") + if completed_step % checkpoint_interval == 0: + save_checkpoint( + args.output_dir / f"step_{completed_step:07d}.pt", + model, optimizer, completed_step, + checkpoint_context_with_exposure( + context, cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + newly_reached = reached_source_exposure_milestones( + exposure_milestones, cumulative_source_batches, + completed_exposure_milestones, + ) + for milestone_id in newly_reached: + completed_exposure_milestones.add(milestone_id) + save_checkpoint( + args.output_dir + / f"milestone_{milestone_id}_step_{completed_step:07d}.pt", + model, optimizer, completed_step, + checkpoint_context_with_exposure( + context, cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + if validation_loaders and completed_step % validation_interval == 0: + result = run_validation( + model, criterion, validation_loaders, device, dtype, validation_batches, + ) + with val_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps({"timestamp_utc": utc_now(), "step": completed_step, **result}) + "\n") + + final_path = args.output_dir / f"step_{completed_step:07d}_final.pt" + save_checkpoint( + final_path, model, optimizer, completed_step, + checkpoint_context_with_exposure( + {**context, "checkpoint_role": "final"}, + cumulative_source_batches, cumulative_source_frames, + cumulative_depth_conditions, completed_exposure_milestones, + ), + exclude_prefixes=excluded, + ) + elapsed = time.perf_counter() - started + schedule_tail_argument = " --allow-schedule-tail" if args.allow_schedule_tail else "" + resource_override_argument = ( + " --allow-physical-gpus-4-5" if args.allow_physical_gpus_4_5 else "" + ) + resume_command = ( + f"CUDA_VISIBLE_DEVICES= {shlex.quote(sys.executable)} " + f"-m scripts.train_phase7_external --config {shlex.quote(str(args.config.resolve()))} " + f"--output-dir {shlex.quote(str(args.output_dir.resolve()))} " + f"--resume {shlex.quote(str(final_path.resolve()))} " + f"--physical-gpu-id {args.physical_gpu_id}{schedule_tail_argument}" + f"{resource_override_argument}" + ) + (args.output_dir / "resume_command.txt").write_text(resume_command + "\n", encoding="utf-8") + summary = { + "status": ( + "completed_schedule_tail" + if args.allow_schedule_tail and completed_step == run_end_step and completed_step > max_steps + else ("completed" if completed_step == max_steps else "paused_requested") + ), + "start_timestamp_utc": datetime.fromtimestamp( + time.time() - elapsed, timezone.utc, + ).isoformat(), + "end_timestamp_utc": utc_now(), + "start_step": start_step, + "completed_step": completed_step, + "protocol_max_steps": max_steps, + "registered_run_end_step": run_end_step, + "schedule_tail_enabled": bool(args.allow_schedule_tail), + "schedule_tail_learning_rate": minimum_lr if args.allow_schedule_tail else None, + "wall_seconds": elapsed, + "gpu_ids_visible": os.environ.get("CUDA_VISIBLE_DEVICES"), + "physical_gpu_id": args.physical_gpu_id, + "gpu_hours": elapsed / 3600.0, + "train_samples_per_second": ( + (completed_step - start_step) * batch_size / max(elapsed, 1e-9) + ), + "optimizer_steps_per_second": (completed_step - start_step) / max(elapsed, 1e-9), + "frames_per_second": processed_frames / max(elapsed, 1e-9), + "peak_vram_gib": torch.cuda.max_memory_allocated(device) / 2**30, + "gpu_utilization_percent_mean": ( + float(np.mean([value["gpu_utilization_percent"] for value in telemetry_samples])) + if telemetry_samples else None + ), + "gpu_telemetry_samples": len(telemetry_samples), + "final_checkpoint": str(final_path.resolve()), + "final_checkpoint_sha256": sha256(final_path), + "resume_command": resume_command, + "source_manifest_sha256": source_hashes, + "official_test_used": False, + "h2o_training_data_used": allow_h2o, + "model_config": asdict(model_config), + "source_exposure_batches": dict(cumulative_source_batches), + "source_exposure_frames": dict(cumulative_source_frames), + "depth_input_condition_frames": dict(cumulative_depth_conditions), + "completed_source_exposure_milestones": sorted( + completed_exposure_milestones + ), + "staged_adaptation": staged_adaptation, + } + (args.output_dir / "summary.json").write_text( + json.dumps(summary, indent=2) + "\n", encoding="utf-8", + ) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/smoke_adapters.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/smoke_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..187e1e4a8016617c0eb87fb67f5d443d23898476 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/smoke_adapters.py @@ -0,0 +1,57 @@ +"""Decode one frozen filtered tile from each source without starting training.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).parent / "src")) + +import torch + +from filtered_dataset import FilteredClipDataset + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--manifests", type=Path, required=True) + parser.add_argument("--time", type=int, choices=(1, 8), required=True) + parser.add_argument("--source", choices=("H2O", "ARCTIC", "HOT3D"), required=True) + parser.add_argument("--tile-id", help="Inspect a specific frozen tile") + args = parser.parse_args() + source = args.source + with torch.no_grad(): + dataset = FilteredClipDataset( + source, args.manifests / f"{source.lower()}_t{args.time}.jsonl", + args.time, (368, 640), + "/SSD3/jiasen/foundation_hand/pretrained/mano", + Path(__file__).parent / "third_party", + photometric_augmentation={"enabled": False}, + ) + mode = "rgb_depth_k" if source == "H2O" else "rgb_k" + spec = {"source": source, "tile_id": args.tile_id or dataset.rows[0]["filtered_tile_id"], + "epoch": 0, "source_ordinal": 0, "position": 0, "mode": mode} + sample = dataset[spec] + out = { + "source": source, "tile_id": spec["tile_id"], "frames": sample["frame_id"].tolist(), + "rgb_shape": list(sample["rgb"].shape), + "K_shape": list(sample["K"].shape), + "K_input": sample["K_input_available"].tolist(), + "K_supervision": sample["K_supervision_valid"].tolist(), + "depth_input": sample["depth_input_available"].tolist(), + "valid": {key: int(sample[key].sum()) for key in ( + "joint2d_valid", "joint3d_valid", "translation_valid", + "mano_pose_valid", "shape_valid", "vertices_valid", "reprojection_valid", + )}, + "finite_K": bool(torch.isfinite(sample["K"]).all()), + "valid_depth_pixels": int(sample["depth_pixel_valid"].sum()), + } + if "joint3d_root_relative_valid" in sample: + out["valid"]["joint3d_root_relative_valid"] = int(sample["joint3d_root_relative_valid"].sum()) + print(json.dumps(out, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/PKG-INFO b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..620eae1cf16816e8b6f85bc64184fc9d6654ac92 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/PKG-INFO @@ -0,0 +1,18 @@ +Metadata-Version: 2.4 +Name: foundation-hand +Version: 0.1.0 +Summary: Full-frame token-based bimanual reconstruction research code +Requires-Python: <3.12,>=3.11 +Requires-Dist: einops>=0.8 +Requires-Dist: numpy>=2.0 +Requires-Dist: opencv-python-headless>=4.10 +Requires-Dist: Pillow>=10 +Requires-Dist: PyYAML>=6 +Requires-Dist: scipy>=1.13 +Requires-Dist: torch>=2.6 +Requires-Dist: torchvision>=0.21 +Requires-Dist: tqdm>=4.66 +Provides-Extra: dev +Requires-Dist: pytest>=8; extra == "dev" +Provides-Extra: mano +Requires-Dist: smplx>=0.1.28; extra == "mano" diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/SOURCES.txt b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..41e91bffda7c0b0e844c367e275687fe7b4f6dc7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/SOURCES.txt @@ -0,0 +1,16 @@ +README.md +pyproject.toml +src/foundation_hand/__init__.py +src/foundation_hand.egg-info/PKG-INFO +src/foundation_hand.egg-info/SOURCES.txt +src/foundation_hand.egg-info/dependency_links.txt +src/foundation_hand.egg-info/requires.txt +src/foundation_hand.egg-info/top_level.txt +src/foundation_hand/data/__init__.py +src/foundation_hand/data/h2o_fields.py +src/foundation_hand/geometry/__init__.py +src/foundation_hand/geometry/camera.py +src/foundation_hand/geometry/mano_translation.py +tests/test_camera_geometry.py +tests/test_h2o_fields.py +tests/test_mano_translation.py \ No newline at end of file diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/dependency_links.txt b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/requires.txt b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..11a43ceccd64d950bbf022a5b8750dd7f449011f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/requires.txt @@ -0,0 +1,15 @@ +einops>=0.8 +numpy>=2.0 +opencv-python-headless>=4.10 +Pillow>=10 +PyYAML>=6 +scipy>=1.13 +torch>=2.6 +torchvision>=0.21 +tqdm>=4.66 + +[dev] +pytest>=8 + +[mano] +smplx>=0.1.28 diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/top_level.txt b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..6079d899260f4660e036318093285d2af7c1c176 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand.egg-info/top_level.txt @@ -0,0 +1 @@ +foundation_hand diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/__init__.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e2e8cc628c3ac4153bb9f660cad3e0083b5cb2 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/__init__.py @@ -0,0 +1,4 @@ +"""Unified full-frame bimanual reconstruction research package.""" + +__version__ = "0.1.0" + diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/__init__.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92b384d9e870d1f786ec2172145012828e61a7bb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/__init__.py @@ -0,0 +1,49 @@ +"""Dataset parsing and batching.""" + +from .h2o_fields import H2OJointRecord, H2OManoRecord, parse_joint_record, parse_mano_record + +__all__ = [ + "H2OJointRecord", + "H2OManoRecord", + "parse_joint_record", + "parse_mano_record", +] +from foundation_hand.data.h2o_dataset import H2OCam4Dataset, collate_h2o_clips +from foundation_hand.data.cached_unified_dataset import CachedUnifiedClipDataset, UnifiedConcatDataset +from foundation_hand.data.egodexter_dataset import EgoDexterSequenceDataset +from foundation_hand.data.hot3d_dataset import HOT3DClipDataset +from foundation_hand.data.hoi4d_dataset import HOI4DClipDataset +from foundation_hand.data.arctic_dataset import ARCTICClipDataset +from foundation_hand.data.samplers import ( + ResumableMixtureBatchSampler, + ResumableRandomBatchSampler, + ResumableWeightedBatchSampler, + load_balanced_sampling_weights, +) +from foundation_hand.data.schema import ( + INPUT_AVAILABILITY_KEYS, + SUPERVISION_MASK_KEYS, + deterministic_clip_keep, + input_availability, + supervision_mask, +) + +__all__ = [ + "H2OCam4Dataset", + "HOT3DClipDataset", + "HOI4DClipDataset", + "ARCTICClipDataset", + "CachedUnifiedClipDataset", + "EgoDexterSequenceDataset", + "UnifiedConcatDataset", + "ResumableMixtureBatchSampler", + "ResumableRandomBatchSampler", + "ResumableWeightedBatchSampler", + "collate_h2o_clips", + "load_balanced_sampling_weights", + "INPUT_AVAILABILITY_KEYS", + "SUPERVISION_MASK_KEYS", + "deterministic_clip_keep", + "input_availability", + "supervision_mask", +] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/arctic_dataset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/arctic_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f22c15913e63b81fc8c79314d132d1f92d63d91a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/arctic_dataset.py @@ -0,0 +1,322 @@ +"""ARCTIC P2 rectified full-frame clips in the Phase 7 unified schema.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.h2o_dataset import ( + RGB_MEAN, + RGB_STD, + PhotometricAugmentation, + _resize_pad, + apply_photometric_augmentation, + sample_photometric_parameters, +) +from foundation_hand.geometry.camera import project_points, resize_and_pad_intrinsics +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import ( + axis_angle_to_matrix, + matrix_to_axis_angle, +) +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.data.schema import ( + InvalidSourceSampleError, + source_root_relative_joint_target, +) + + +def transform_points(points: torch.Tensor, world_to_camera: torch.Tensor) -> torch.Tensor: + if points.shape[-1] != 3 or world_to_camera.shape[-2:] != (4, 4): + raise ValueError("expected points [...,N,3] and transforms [...,4,4]") + return torch.einsum( + "...ij,...nj->...ni", world_to_camera[..., :3, :3], points, + ) + world_to_camera[..., None, :3, 3] + + +def geometry_compatibility_mask( + hand_valid: torch.Tensor, vertex_error_mm: torch.Tensor, +) -> torch.Tensor: + """Apply the frozen 1 mm MANO convention gate per frame and hand.""" + + return hand_valid & torch.isfinite(vertex_error_mm) & (vertex_error_mm < 1.0) + + +def compose_camera_global_orientation( + world_axis_angle: torch.Tensor, world_to_camera: torch.Tensor, +) -> torch.Tensor: + world_rotation = axis_angle_to_matrix(world_axis_angle) + camera_rotation = world_to_camera[..., :3, :3] @ world_rotation + return matrix_to_axis_angle(camera_rotation) + + +class ARCTICClipDataset(Dataset[dict[str, Any]]): + """Use P2 train or P2 val only; view 0 is rectified before model input.""" + + source_hw = (600, 840) + original_hw = (2000, 2800) + + def __init__( + self, + manifest: str | Path, + mano_root: str | Path, + target_hw: tuple[int, int] = (368, 640), + photometric_augmentation: Mapping[str, Any] | None = None, + augmentation_seed: int = 20260717, + hand_valid_policy: str = "legacy_wrist", + ) -> None: + self.manifest = Path(manifest).resolve() + self.target_hw = tuple(target_hw) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.augmentation_seed = int(augmentation_seed) + if hand_valid_policy not in {"legacy_wrist", "visible_mesh"}: + raise ValueError(f"unknown ARCTIC hand validity policy: {hand_valid_policy}") + self.hand_valid_policy = hand_valid_policy + self.rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not self.rows or any(row.get("dataset_id") != "ARCTIC" for row in self.rows): + raise ValueError("manifest must be non-empty and ARCTIC-only") + if any(row.get("protocol") != "P2" for row in self.rows): + raise ValueError("ARCTIC adapter accepts protocol P2 only") + if any(row.get("split_role") not in {"arctic_p2_train", "arctic_p2_val"} for row in self.rows): + raise ValueError("ARCTIC manifest may contain P2 train or val only") + if any(row.get("official_test_used") is not False for row in self.rows): + raise ValueError("ARCTIC manifest lacks test-isolation declaration") + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + self._source_mano = { + side: ManoLayer( + mano_root=str(mano_root), side=side, use_pca=False, + ncomps=45, flat_hand_mean=False, + ) + for side in ("left", "right") + } + self._target_mano = ManoCameraLayer(mano_root, fix_left_shapedirs=True) + self._cached_sequence: str | None = None + self._cached_mano: dict[str, Any] | None = None + self._cached_camera: dict[str, Any] | None = None + + def __len__(self) -> int: + return len(self.rows) + + def _sequence(self, row: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + sequence = str(row["physical_recording_id"]) + if self._cached_sequence != sequence: + self._cached_mano = np.load(row["mano_path"], allow_pickle=True).item() + self._cached_camera = np.load(row["camera_path"], allow_pickle=True).item() + self._cached_sequence = sequence + assert self._cached_mano is not None and self._cached_camera is not None + return self._cached_mano, self._cached_camera + + def source_root_relative_joint3d( + self, index: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Regenerate source-compatible camera-frame joints without images.""" + + row = self.rows[int(index)] + indices = [int(value) for value in row["array_indices_0based"]] + mano, camera = self._sequence(row) + rotation = torch.from_numpy(camera["R_k_cam_np"][indices].astype(np.float32)) + joints = torch.full((len(indices), 2, 21, 3), float("nan")) + hand_valid = torch.ones((len(indices), 2), dtype=torch.bool) + for side_index, side in enumerate(("left", "right")): + values = mano[side] + raw_pose = torch.from_numpy(np.concatenate(( + values["rot"][indices], values["pose"][indices], + ), axis=-1).astype(np.float32)) + beta = torch.from_numpy( + np.repeat( + np.asarray(values["shape"], dtype=np.float32)[None], + len(indices), axis=0, + ) + ) + with torch.no_grad(): + _, joints_mm = self._source_mano[side](raw_pose, beta) + relative_world = (joints_mm - joints_mm[:, :1]) / 1000.0 + joints[:, side_index] = torch.einsum( + "tij,tnj->tni", rotation, relative_world, + ) + return source_root_relative_joint_target(joints, hand_valid) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + indices = [int(value) for value in row["array_indices_0based"]] + frame_ids = [int(value) for value in row["frame_ids_1based"]] + mano, camera = self._sequence(row) + K_original = np.asarray(camera["intrinsics"], dtype=np.float32) + input_scale = self.source_hw[1] / self.original_hw[1] + if abs(input_scale - self.source_hw[0] / self.original_hw[0]) > 1e-9: + raise ValueError("ARCTIC ego speedup scale is anisotropic") + K_input = resize_and_pad_intrinsics( + K_original, self.original_hw, self.source_hw, + ) + distortion = np.asarray(camera["dist8"], dtype=np.float64) + parameters = sample_photometric_parameters( + self.photometric_augmentation, self.augmentation_seed, clip_index, epoch, + ) + rgb_rows = [] + resized_hw = pad_left_top = None + for path in row["image_paths"]: + bgr = cv2.imread(path, cv2.IMREAD_COLOR) + if bgr is None or bgr.shape[:2] != self.source_hw: + raise InvalidSourceSampleError(f"invalid ARCTIC ego image: {path}") + rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) + # Downloaded ego speedup images are scaled raw full frames. Rectify + # them to the undistorted camera frame used by ARCTIC P2 geometry. + rgb = cv2.undistort(rgb, K_input, distortion, None, K_input) + rgb = apply_photometric_augmentation(rgb, parameters) + rgb, resized_hw, pad_left_top = _resize_pad( + rgb, self.target_hw, cv2.INTER_LINEAR, + ) + rgb_rows.append( + np.transpose((rgb.astype(np.float32) / 255.0 - RGB_MEAN) / RGB_STD, (2, 0, 1)) + ) + assert resized_hw is not None and pad_left_top is not None + K = resize_and_pad_intrinsics( + K_input, self.source_hw, resized_hw, pad_left_top, + ) + time = len(indices) + source_vertices = torch.full((time, 2, 778, 3), float("nan")) + source_joints = torch.full((time, 2, 21, 3), float("nan")) + pose_camera = torch.full((time, 2, 48), float("nan")) + shape = torch.full((time, 2, 10), float("nan")) + wrist = torch.full((time, 2, 3), float("nan")) + world_to_camera = torch.eye(4)[None].repeat(time, 1, 1) + world_to_camera[:, :3, :3] = torch.from_numpy(camera["R_k_cam_np"][indices]) + world_to_camera[:, :3, 3] = torch.from_numpy(camera["T_k_cam_np"][indices, :, 0]) + for side_index, side in enumerate(("left", "right")): + values = mano[side] + raw_pose = torch.from_numpy(np.concatenate(( + values["rot"][indices], values["pose"][indices], + ), axis=-1).astype(np.float32)) + beta = torch.from_numpy( + np.repeat(np.asarray(values["shape"], dtype=np.float32)[None], time, axis=0) + ) + translation_world = torch.from_numpy(values["trans"][indices].astype(np.float32)) + with torch.no_grad(): + vertices_mm, joints_mm = self._source_mano[side](raw_pose, beta) + vertices_world = vertices_mm / 1000.0 + translation_world[:, None] + joints_world = joints_mm / 1000.0 + translation_world[:, None] + source_vertices[:, side_index] = transform_points(vertices_world, world_to_camera) + source_joints[:, side_index] = transform_points(joints_world, world_to_camera) + full_pose = raw_pose.clone() + full_pose[:, 3:] += self._source_mano[side].th_hands_mean + full_pose[:, :3] = compose_camera_global_orientation( + full_pose[:, :3], world_to_camera, + ) + pose_camera[:, side_index] = full_pose + shape[:, side_index] = beta + wrist[:, side_index] = source_joints[:, side_index, 0] + + K_tensor = torch.from_numpy(np.repeat(K[None], time, axis=0)) + source_joint2d, source_positive = project_points(source_joints, K_tensor) + height, width = self.target_hw + in_frame = ( + source_positive & torch.isfinite(source_joint2d).all(-1) + & (source_joint2d[..., 0] >= 0) & (source_joint2d[..., 0] < width) + & (source_joint2d[..., 1] >= 0) & (source_joint2d[..., 1] < height) + ) + if self.hand_valid_policy == "visible_mesh": + mesh_uv, mesh_positive = project_points(source_vertices, K_tensor) + mesh_in_frame = ( + mesh_positive & torch.isfinite(mesh_uv).all(-1) + & (mesh_uv[..., 0] >= 0) & (mesh_uv[..., 0] < width) + & (mesh_uv[..., 1] >= 0) & (mesh_uv[..., 1] < height) + ) + hand_valid = mesh_in_frame.any(-1) + else: + hand_valid = in_frame[..., 0] & (in_frame.sum(-1) >= 3) + rotations = axis_angle_to_matrix( + torch.nan_to_num(pose_camera).reshape(time, 2, 16, 3) + ) + with torch.no_grad(): + target_vertices, target_joints = self._target_mano( + rotations, torch.nan_to_num(shape), torch.nan_to_num(wrist), + ) + vertex_error_mm = torch.linalg.vector_norm( + target_vertices - source_vertices, dim=-1, + ).amax(dim=-1) * 1000.0 + geometry_valid = geometry_compatibility_mask(hand_valid, vertex_error_mm) + joint2d_valid = in_frame & hand_valid[..., None] + joint3d_valid = geometry_valid[..., None].expand(-1, -1, 21) + root_relative_joints, root_relative_valid = source_root_relative_joint_target( + source_joints, hand_valid, + ) + target_projected, _ = project_points(target_joints, K_tensor) + projection_error = torch.linalg.vector_norm( + target_projected - source_joint2d, dim=-1, + ) + for tensor, valid in ( + (target_vertices, geometry_valid), (target_joints, geometry_valid), + (source_joint2d, hand_valid), (pose_camera, hand_valid), + (shape, geometry_valid), (wrist, hand_valid), + ): + mask = valid + while mask.ndim < tensor.ndim: + mask = mask.unsqueeze(-1) + tensor.masked_fill_(~mask, float("nan")) + output: dict[str, Any] = { + "rgb": torch.from_numpy(np.stack(rgb_rows)), + "depth_m": torch.zeros((time, 1, *self.target_hw), dtype=torch.float32), + "depth_pixel_valid": torch.zeros((time, 1, *self.target_hw), dtype=torch.bool), + "K": K_tensor, + "camera_pose": world_to_camera, + "joint3d_camera": target_joints, + "joint3d_root_relative": root_relative_joints, + "joint2d": source_joint2d, + "joint_element_valid": joint3d_valid, + "mano_pose": pose_camera, + "mano_shape": shape, + "mano_translation_raw": torch.full_like(wrist, float("nan")), + "wrist_root_translation": wrist, + "joint_annotation_valid": geometry_valid, + "mano_annotation_valid": geometry_valid, + "joint2d_valid": joint2d_valid, + "joint3d_valid": joint3d_valid, + "joint3d_root_relative_valid": root_relative_valid, + "translation_valid": hand_valid, + "mano_pose_valid": hand_valid, + "shape_valid": geometry_valid, + "vertices_valid": geometry_valid, + "reprojection_valid": joint3d_valid, + "vertices_camera": target_vertices, + "presence_target": hand_valid.float(), + "presence_label_valid": torch.zeros((time, 2), dtype=torch.bool), + "presence_valid": torch.zeros((time, 2), dtype=torch.bool), + "depth_available": torch.zeros(time, dtype=torch.bool), + "K_available": torch.ones(time, dtype=torch.bool), + "depth_input_available": torch.zeros(time, dtype=torch.bool), + "K_input_available": torch.ones(time, dtype=torch.bool), + "K_supervision_valid": torch.ones(time, dtype=torch.bool), + "frame_valid": torch.ones(time, dtype=torch.bool), + "hand_side_id": torch.tensor((0, 1))[None].expand(time, -1).clone(), + "timestamp_ns": torch.tensor(indices, dtype=torch.long), + "frame_id": torch.tensor(frame_ids, dtype=torch.long), + "source_vertex_regen_error_mm": vertex_error_mm, + "geometry_convention_compatible": geometry_valid, + "projection_roundtrip_error_px": projection_error, + "photometric_aug_params": torch.from_numpy(np.repeat(parameters[None], time, axis=0)), + "image_hw": torch.tensor(self.target_hw, dtype=torch.long), + "dataset_id": "ARCTIC", + "subject_id": str(row["subject_id"]), + "sequence_id": str(row["physical_recording_id"]), + "physical_recording_id": str(row["physical_recording_id"]), + "camera_id": "ego_view_0_rectified", + "stream_id": "ego_rgb_rectified", + "headset_id": str(row["subject_id"]), + } + return output diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/cached_unified_dataset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/cached_unified_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..616b65592175b6ec7b745ca8e448fe1292b5c713 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/cached_unified_dataset.py @@ -0,0 +1,465 @@ +"""Hash-bound controlled cache for unified external clips.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import ConcatDataset, Dataset + +from foundation_hand.data.h2o_dataset import ( + RGB_MEAN, + RGB_STD, + PhotometricAugmentation, + apply_photometric_augmentation, + sample_photometric_parameters, +) +from foundation_hand.data.schema import deterministic_clip_keep + + +DEPTH_CORRUPTIONS = ( + "quantization", "random_holes", "edge_erosion", "edge_dilation", + "local_invalid", "additive_noise", "multiplicative_noise", + "registration_shift", "sparse_outliers", "global_bias", +) + + +@dataclass(frozen=True) +class FullFrameGeometryAugmentation: + enabled: bool = False + probability: float = 0.0 + scale_min: float = 1.0 + scale_max: float = 1.0 + translation_fraction: float = 0.0 + + @classmethod + def from_mapping( + cls, value: Mapping[str, Any] | None, + ) -> "FullFrameGeometryAugmentation": + config = cls() if value is None else cls(**dict(value)) + if not 0.0 <= config.probability <= 1.0: + raise ValueError("geometry augmentation probability must be in [0, 1]") + if not 0.5 <= config.scale_min <= config.scale_max <= 2.0: + raise ValueError("geometry augmentation scale range must be within [0.5, 2.0]") + if not 0.0 <= config.translation_fraction <= 0.25: + raise ValueError("geometry translation fraction must be in [0, 0.25]") + if config.enabled and config.probability <= 0.0: + raise ValueError("enabled geometry augmentation requires positive probability") + return config + + +def sample_full_frame_affine( + config: FullFrameGeometryAugmentation, + seed: int, + source_clip_index: int, + epoch: int, + image_hw: tuple[int, int], +) -> tuple[np.ndarray, bool]: + """Sample one GT-independent affine shared by every frame and modality.""" + + matrix = np.eye(3, dtype=np.float32) + if not config.enabled: + return matrix, False + generator = np.random.default_rng( + int(seed) * 1_000_003 + int(source_clip_index) * 97_409 + int(epoch) * 65_537 + ) + if float(generator.random()) >= config.probability: + return matrix, False + height, width = image_hw + scale = float(generator.uniform(config.scale_min, config.scale_max)) + dx = float(generator.uniform(-1.0, 1.0) * config.translation_fraction * width) + dy = float(generator.uniform(-1.0, 1.0) * config.translation_fraction * height) + center_x, center_y = (width - 1.0) / 2.0, (height - 1.0) / 2.0 + matrix[0, 0] = scale + matrix[1, 1] = scale + matrix[0, 2] = (1.0 - scale) * center_x + dx + matrix[1, 2] = (1.0 - scale) * center_y + dy + return matrix, True + + +def apply_full_frame_affine( + rgb_u8: np.ndarray, + arrays: dict[str, np.ndarray], + matrix: np.ndarray, +) -> tuple[np.ndarray, dict[str, np.ndarray]]: + """Warp full-frame inputs and update K/2D supervision with the same affine.""" + + rgb = np.asarray(rgb_u8) + if rgb.ndim != 4 or rgb.shape[-1] != 3: + raise ValueError(f"expected T,H,W,3 RGB cache, got {rgb.shape}") + time, height, width, _ = rgb.shape + if "image_hw" in arrays and tuple( + int(value) for value in np.asarray(arrays["image_hw"]).reshape(-1) + ) != (height, width): + raise ValueError("cached image_hw differs from RGB payload shape") + transform = np.asarray(matrix, dtype=np.float32) + if transform.shape != (3, 3) or not np.allclose(transform[2], (0.0, 0.0, 1.0)): + raise ValueError("full-frame geometry transform must be a 3x3 affine") + affine = transform[:2] + warped_rgb = np.stack([ + cv2.warpAffine( + frame, affine, (width, height), flags=cv2.INTER_LINEAR, + borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0), + ) + for frame in rgb + ]) + updated = dict(arrays) + if "depth_m" in updated and "depth_pixel_valid" in updated: + depth = np.asarray(updated["depth_m"], dtype=np.float32) + valid = np.asarray(updated["depth_pixel_valid"], dtype=bool) + if depth.shape != valid.shape or depth.shape != (time, 1, height, width): + raise ValueError("cached depth/valid geometry shape differs from RGB") + warped_depth = np.stack([ + cv2.warpAffine( + frame[0], affine, (width, height), flags=cv2.INTER_NEAREST, + borderMode=cv2.BORDER_CONSTANT, borderValue=0.0, + )[None] + for frame in depth + ]).astype(np.float32) + warped_valid = np.stack([ + cv2.warpAffine( + frame[0].astype(np.uint8), affine, (width, height), + flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, + borderValue=0, + )[None] + for frame in valid + ]).astype(bool) + updated["depth_m"] = np.where(warped_valid, warped_depth, 0.0).astype(np.float32) + updated["depth_pixel_valid"] = warped_valid + if "K" in updated: + intrinsics = np.asarray(updated["K"], dtype=np.float32) + if intrinsics.shape != (time, 3, 3): + raise ValueError("cached K shape differs from RGB time dimension") + updated["K"] = np.einsum("ij,tjk->tik", transform, intrinsics).astype(np.float32) + if "joint2d" in updated: + joints = np.asarray(updated["joint2d"], dtype=np.float32).copy() + joints_x = joints[..., 0].copy() + joints_y = joints[..., 1].copy() + joints[..., 0] = ( + transform[0, 0] * joints_x + + transform[0, 1] * joints_y + + transform[0, 2] + ) + joints[..., 1] = ( + transform[1, 0] * joints_x + + transform[1, 1] * joints_y + + transform[1, 2] + ) + updated["joint2d"] = joints + return warped_rgb, updated + + +def _shift(array: np.ndarray, dy: int, dx: int, fill: float | bool) -> np.ndarray: + result = np.full_like(array, fill) + source_y = slice(max(0, -dy), array.shape[-2] - max(0, dy)) + target_y = slice(max(0, dy), array.shape[-2] - max(0, -dy)) + source_x = slice(max(0, -dx), array.shape[-1] - max(0, dx)) + target_x = slice(max(0, dx), array.shape[-1] - max(0, -dx)) + result[..., target_y, target_x] = array[..., source_y, source_x] + return result + + +def corrupt_metric_depth( + depth_m: np.ndarray, + pixel_valid: np.ndarray, + corruption: str, + seed: int, +) -> tuple[np.ndarray, np.ndarray]: + """Apply one deterministic clip-level sensor corruption to model inputs.""" + + if corruption not in DEPTH_CORRUPTIONS: + raise ValueError(f"unsupported depth corruption: {corruption}") + depth = np.asarray(depth_m, dtype=np.float32).copy() + valid = np.asarray(pixel_valid, dtype=bool).copy() + generator = np.random.default_rng(seed) + if corruption == "quantization": + quantum = float(generator.choice((0.002, 0.005, 0.010))) + depth[valid] = np.round(depth[valid] / quantum) * quantum + elif corruption == "random_holes": + valid &= generator.random(valid.shape) >= 0.10 + elif corruption == "edge_erosion": + neighbors = [ + _shift(valid, dy, dx, False) + for dy in (-1, 0, 1) for dx in (-1, 0, 1) + ] + valid = np.logical_and.reduce(neighbors) + elif corruption == "edge_dilation": + offsets = [(dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)] + shifted_valid = [ + _shift(valid, dy, dx, False) + for dy, dx in offsets + ] + shifted_depth = [ + np.where(mask, _shift(depth, dy, dx, 0.0), np.inf) + for mask, (dy, dx) in zip(shifted_valid, offsets, strict=True) + ] + dilated = np.logical_or.reduce(shifted_valid) + nearest_foreground = np.minimum.reduce(shifted_depth) + depth = np.where(dilated, nearest_foreground, depth) + valid = dilated + elif corruption == "local_invalid": + height, width = valid.shape[-2:] + box_h, box_w = max(1, height // 5), max(1, width // 5) + top = int(generator.integers(0, max(1, height - box_h + 1))) + left = int(generator.integers(0, max(1, width - box_w + 1))) + valid[..., top : top + box_h, left : left + box_w] = False + elif corruption == "additive_noise": + noise = generator.normal(0.0, 0.0075, size=depth.shape).astype(np.float32) + depth[valid] += noise[valid] + elif corruption == "multiplicative_noise": + scale = generator.normal(1.0, 0.015, size=depth.shape).astype(np.float32) + depth[valid] *= scale[valid] + elif corruption == "registration_shift": + dy, dx = generator.integers(-3, 4, size=2) + depth = _shift(depth, int(dy), int(dx), 0.0) + valid = _shift(valid, int(dy), int(dx), False) + elif corruption == "sparse_outliers": + outliers = valid & (generator.random(valid.shape) < 0.02) + offsets = generator.uniform(-0.08, 0.08, size=depth.shape).astype(np.float32) + depth[outliers] += offsets[outliers] + elif corruption == "global_bias": + depth[valid] += float(generator.uniform(-0.04, 0.04)) + depth = np.where(valid, np.clip(depth, 0.02, 3.0), 0.0).astype(np.float32) + return depth, valid + + +class CachedUnifiedClipDataset(Dataset[dict[str, Any]]): + """Read bounded Phase 7 clip caches without source-format assumptions.""" + + def __init__( + self, + manifest: str | Path, + K_input_dropout: float = 0.0, + dropout_seed: int = 20260717, + photometric_augmentation: Mapping[str, Any] | None = None, + depth_input_dropout: float = 0.0, + depth_corruption_probability: float = 0.0, + joint3d_root_relative_scope: str = "auto", + source_id: str | None = None, + max_clips: int | None = None, + expected_resolution_hw: tuple[int, int] | None = None, + geometry_augmentation: Mapping[str, Any] | None = None, + ) -> None: + self.manifest = Path(manifest).resolve() + self.K_input_dropout = float(K_input_dropout) + self.dropout_seed = int(dropout_seed) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.geometry_augmentation = FullFrameGeometryAugmentation.from_mapping( + geometry_augmentation + ) + self.depth_input_dropout = float(depth_input_dropout) + self.depth_corruption_probability = float(depth_corruption_probability) + root_relative_scope = str(joint3d_root_relative_scope) + self.joint3d_root_relative_scope = { + "historical_left_only": "left_only", + }.get(root_relative_scope, root_relative_scope) + self.source_id = source_id + self.expected_resolution_hw = ( + tuple(int(value) for value in expected_resolution_hw) + if expected_resolution_hw is not None else None + ) + if not 0.0 <= self.K_input_dropout <= 1.0: + raise ValueError("K_input_dropout must be in [0, 1]") + if not 0.0 <= self.depth_input_dropout <= 1.0: + raise ValueError("depth_input_dropout must be in [0, 1]") + if not 0.0 <= self.depth_corruption_probability <= 1.0: + raise ValueError("depth_corruption_probability must be in [0, 1]") + if self.joint3d_root_relative_scope not in {"auto", "disabled", "left_only"}: + raise ValueError( + "joint3d_root_relative_scope must be auto, disabled, left_only " + "or historical_left_only" + ) + rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + self.rows = rows[:max_clips] + declared_resolutions = { + tuple(int(value) for value in row["resolution_hw"]) + for row in self.rows if "resolution_hw" in row + } + if len(declared_resolutions) > 1: + raise ValueError("cache manifest mixes multiple resolutions") + if self.expected_resolution_hw is not None: + if declared_resolutions and declared_resolutions != {self.expected_resolution_hw}: + raise ValueError( + f"cache resolution {sorted(declared_resolutions)} does not match " + f"configured {self.expected_resolution_hw}" + ) + if not declared_resolutions and self.expected_resolution_hw != (368, 640): + raise ValueError( + "legacy cache without resolution metadata is approved only for 640x368" + ) + for row in self.rows: + path = Path(row["cache_path"]) + if not path.is_file(): + raise FileNotFoundError(path) + if self.rows and self.expected_resolution_hw is not None and not declared_resolutions: + with np.load(self.rows[0]["cache_path"], allow_pickle=False) as archive: + if "image_hw" not in archive.files: + raise ValueError("legacy cache payload lacks image_hw") + actual = tuple(int(value) for value in archive["image_hw"].reshape(-1)) + if actual != self.expected_resolution_hw: + raise ValueError( + f"legacy cache resolution {actual} does not match configured " + f"{self.expected_resolution_hw}" + ) + + def __len__(self) -> int: + return len(self.rows) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + with np.load(row["cache_path"], allow_pickle=False) as archive: + arrays = {key: archive[key] for key in archive.files} + rgb = arrays.pop("rgb_u8") + if self.geometry_augmentation.enabled: + image_hw = tuple(int(value) for value in arrays["image_hw"].reshape(-1)) + geometry_matrix, geometry_applied = sample_full_frame_affine( + self.geometry_augmentation, + self.dropout_seed + 307, + int(row["source_clip_index"]), + epoch, + image_hw, + ) + if geometry_applied: + rgb, arrays = apply_full_frame_affine(rgb, arrays, geometry_matrix) + arrays["geometry_aug_matrix"] = np.repeat( + geometry_matrix[None], len(arrays["frame_valid"]), axis=0, + ) + arrays["geometry_aug_applied"] = np.full( + len(arrays["frame_valid"]), geometry_applied, dtype=bool, + ) + parameters = sample_photometric_parameters( + self.photometric_augmentation, + self.dropout_seed, + int(row["source_clip_index"]), + epoch, + ) + rgb = np.stack([ + apply_photometric_augmentation(frame, parameters) for frame in rgb + ]) + rgb = rgb.astype(np.float32) / 255.0 + rgb = (rgb - RGB_MEAN) / RGB_STD + arrays["rgb"] = np.transpose(rgb, (0, 3, 1, 2)) + output = {key: torch.from_numpy(np.asarray(value)) for key, value in arrays.items()} + sidecar_path = row.get("joint3d_root_relative_sidecar_path") + if self.joint3d_root_relative_scope == "disabled": + output["joint3d_root_relative"] = torch.full_like( + output["joint3d_camera"], float("nan"), + ) + output["joint3d_root_relative_valid"] = torch.zeros_like( + output["joint3d_valid"], dtype=torch.bool, + ) + elif sidecar_path is not None: + with np.load(sidecar_path, allow_pickle=False) as sidecar: + relative = torch.from_numpy(sidecar["joint3d_root_relative"]) + relative_valid = torch.from_numpy( + sidecar["joint3d_root_relative_valid"] + ).bool() + if ( + relative.shape != output["joint3d_camera"].shape + or relative_valid.shape != output["joint3d_valid"].shape + or relative_valid[..., 1, :].any() + ): + raise RuntimeError("invalid historical-left root-relative sidecar") + output["joint3d_root_relative"] = relative.masked_fill( + ~relative_valid[..., None], float("nan"), + ) + output["joint3d_root_relative_valid"] = relative_valid + if self.joint3d_root_relative_scope == "left_only": + if ( + "joint3d_root_relative" not in output + or "joint3d_root_relative_valid" not in output + ): + raise RuntimeError("left-only scope requires cached root-relative targets") + relative_valid = output["joint3d_root_relative_valid"].bool().clone() + relative_valid[..., 1, :] = False + output["joint3d_root_relative_valid"] = relative_valid + output["joint3d_root_relative"] = output[ + "joint3d_root_relative" + ].masked_fill(~relative_valid[..., None], float("nan")) + keep_K = deterministic_clip_keep( + 1.0 - self.K_input_dropout, + self.dropout_seed, + int(row["source_clip_index"]), + epoch, + ) + output["K_input_available"] = torch.full( + output["frame_valid"].shape, keep_K, dtype=torch.bool, + ) + output["K_available"] = output["K_input_available"].clone() + source_depth_available = output["depth_input_available"].bool() + keep_depth = deterministic_clip_keep( + 1.0 - self.depth_input_dropout, + self.dropout_seed + 101, + int(row["source_clip_index"]), epoch, + ) + corrupt_depth = keep_depth and deterministic_clip_keep( + self.depth_corruption_probability, + self.dropout_seed + 211, + int(row["source_clip_index"]), epoch, + ) + condition_code = 0 + if bool(source_depth_available.any()) and not keep_depth: + output["depth_input_available"] = torch.zeros_like(source_depth_available) + condition_code = 1 + elif bool(source_depth_available.any()) and corrupt_depth: + corruption_index = ( + self.dropout_seed * 31 + int(row["source_clip_index"]) * 17 + epoch + ) % len(DEPTH_CORRUPTIONS) + corruption = DEPTH_CORRUPTIONS[corruption_index] + depth, valid = corrupt_metric_depth( + output["depth_m"].numpy(), output["depth_pixel_valid"].numpy(), + corruption, + seed=(self.dropout_seed * 1_000_003 + int(row["source_clip_index"]) * 97 + epoch), + ) + output["depth_m"] = torch.from_numpy(depth) + output["depth_pixel_valid"] = torch.from_numpy(valid) + condition_code = 3 + corruption_index + elif bool(source_depth_available.any()): + condition_code = 2 + output["depth_available"] = output["depth_input_available"].clone() + output["depth_input_condition_code"] = torch.full( + output["frame_valid"].shape, condition_code, dtype=torch.long, + ) + output["photometric_aug_params"] = torch.from_numpy( + np.repeat(parameters[None], len(output["frame_valid"]), axis=0) + ) + for key in ( + "dataset_id", "subject_id", "sequence_id", "physical_recording_id", + "camera_id", "stream_id", "headset_id", + ): + output[key] = row[key] + output["sampling_source_id"] = self.source_id or row["dataset_id"] + return output + + +class UnifiedConcatDataset(ConcatDataset): + """Concat dataset that preserves the sampler-provided augmentation epoch.""" + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + global_index, epoch = int(index[0]), int(index[1]) + else: + global_index, epoch = int(index), 0 + if global_index < 0: + global_index += len(self) + if global_index < 0 or global_index >= len(self): + raise IndexError("dataset index out of range") + dataset_index = int(np.searchsorted( + self.cumulative_sizes, global_index, side="right", + )) + previous = 0 if dataset_index == 0 else self.cumulative_sizes[dataset_index - 1] + return self.datasets[dataset_index][(global_index - previous, epoch)] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/egodexter_dataset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/egodexter_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..096ba3b2ab29316e3a92ab05dede9abf8ddbd85c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/egodexter_dataset.py @@ -0,0 +1,151 @@ +"""EgoDexter full-frame RGB-D sequence adapter for frozen zero-shot evaluation.""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Iterator + +import cv2 +import numpy as np +import torch + +from foundation_hand.data.h2o_dataset import RGB_MEAN, RGB_STD, _resize_pad +from foundation_hand.geometry.camera import depth_mm_to_m, resize_and_pad_intrinsics + + +SEQUENCES = ("Desk", "Fruits", "Kitchen", "Rotunda") +FINGERTIP_JOINT_INDICES = (4, 8, 12, 16, 20) + + +def parse_fingertip_line( + line: str, dimensions: int, *, missing_value: float = 0.0, +) -> np.ndarray: + groups = [group.strip() for group in line.split(";") if group.strip()] + if not 1 <= len(groups) <= 5: + raise ValueError(f"expected one to five fingertips, got {len(groups)}") + values = [[float(value.strip()) for value in group.split(",")] for group in groups] + present = np.asarray(values, dtype=np.float32) + if present.shape != (len(groups), dimensions): + raise ValueError(f"expected fingertip width {dimensions}, got {present.shape}") + array = np.full((5, dimensions), missing_value, dtype=np.float32) + array[: len(groups)] = present + return array + + +def load_depth_intrinsics(calibration_path: str | Path) -> np.ndarray: + text = Path(calibration_path).read_text(encoding="utf-8") + section = text.split("Depth Intrisics Matrix:", 1) + if len(section) != 2: + raise ValueError("depth intrinsics section missing") + rows = [] + for line in section[1].strip().splitlines()[:3]: + values = re.findall(r"[-+]?\d+(?:\.\d+)?", line) + if len(values) != 3: + raise ValueError(f"invalid depth intrinsics row: {line}") + rows.append([float(value) for value in values]) + K = np.asarray(rows, dtype=np.float32) + if K.shape != (3, 3) or not np.allclose(K[2], (0.0, 0.0, 1.0)): + raise ValueError("invalid depth intrinsics matrix") + return K + + +class EgoDexterSequenceDataset: + """Expose one sequence in order without using its annotations as model input.""" + + def __init__( + self, + root: str | Path, + sequence: str, + *, + hand_side: str, + target_hw: tuple[int, int] = (368, 640), + ) -> None: + if sequence not in SEQUENCES: + raise ValueError(f"unknown EgoDexter sequence: {sequence}") + if hand_side not in {"left", "right"}: + raise ValueError("hand_side must be frozen per sequence as left or right") + self.root = Path(root).resolve() + self.sequence = sequence + self.hand_side = hand_side + self.side_index = 0 if hand_side == "left" else 1 + self.target_hw = tuple(target_hw) + self.sequence_root = self.root / "data" / sequence + self.K_source = load_depth_intrinsics(self.root / "CameraCalibration_640x480.txt") + self.rgb_paths = sorted( + (self.sequence_root / "color_on_depth").glob("image_*_color_on_depth.png") + ) + self.depth_paths = sorted((self.sequence_root / "depth").glob("image_*_depth.png")) + lines_2d = (self.sequence_root / "annotation.txt").read_text( + encoding="utf-8", + ).splitlines() + lines_3d = (self.sequence_root / "annotation.txt_3D.txt").read_text( + encoding="utf-8", + ).splitlines() + lengths = {len(self.rgb_paths), len(self.depth_paths), len(lines_2d), len(lines_3d)} + if len(lengths) != 1 or not self.rgb_paths: + raise ValueError(f"EgoDexter sequence streams/annotations differ: {lengths}") + self.fingertips_2d = np.stack([ + parse_fingertip_line(line, 2, missing_value=-1.0) for line in lines_2d + ]) + self.fingertips_3d_m = np.stack([ + parse_fingertip_line(line, 3) for line in lines_3d + ]) / 1000.0 + + def __len__(self) -> int: + return len(self.rgb_paths) + + def _load(self, index: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + rgb_bgr = cv2.imread(str(self.rgb_paths[index]), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(self.depth_paths[index]), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise RuntimeError(f"EgoDexter decode failed: {self.sequence}/{index}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + if rgb.shape[:2] != (480, 640) or depth_mm.shape != (480, 640): + raise ValueError(f"unexpected EgoDexter resolution: {rgb.shape}/{depth_mm.shape}") + rgb, resized_hw, pad_left_top = _resize_pad(rgb, self.target_hw, cv2.INTER_AREA) + depth_mm, depth_hw, depth_pad = _resize_pad( + depth_mm, self.target_hw, cv2.INTER_NEAREST, + ) + if depth_hw != resized_hw or depth_pad != pad_left_top: + raise AssertionError("EgoDexter RGB/depth preprocessing diverged") + K = resize_and_pad_intrinsics( + self.K_source, (480, 640), resized_hw, pad_left_top, + ) + return rgb, depth_mm, K + + def frame(self, index: int, input_mode: str) -> dict[str, object]: + if input_mode not in {"rgb_d_k", "rgb_k", "rgb_only"}: + raise ValueError(f"unsupported input mode: {input_mode}") + rgb, depth_mm, K = self._load(index) + depth_m, depth_valid = depth_mm_to_m(depth_mm) + rgb = rgb.astype(np.float32) / 255.0 + rgb = (rgb - RGB_MEAN) / RGB_STD + K_available = input_mode != "rgb_only" + depth_available = input_mode == "rgb_d_k" + fingertips = self.fingertips_3d_m[index].copy() + fingertip_valid = np.linalg.norm(fingertips, axis=-1) > 0.0 + fingertips[~fingertip_valid] = np.nan + return { + "rgb": torch.from_numpy(np.transpose(rgb, (2, 0, 1))).float()[None, None], + "depth_m": torch.from_numpy(depth_m[None]).float()[None, None], + "depth_pixel_valid": torch.from_numpy(depth_valid[None])[None, None], + "K": torch.from_numpy(K).float()[None, None], + "K_available": torch.tensor([[K_available]], dtype=torch.bool), + "K_input_available": torch.tensor([[K_available]], dtype=torch.bool), + "depth_available": torch.tensor([[depth_available]], dtype=torch.bool), + "depth_input_available": torch.tensor([[depth_available]], dtype=torch.bool), + "frame_valid": torch.ones((1, 1), dtype=torch.bool), + "sequence_id": self.sequence, + "frame_id": index, + "hand_side": self.hand_side, + "hand_side_index": self.side_index, + "target_fingertips_camera_m": torch.from_numpy(fingertips), + "target_fingertip_valid": torch.from_numpy(fingertip_valid), + "target_fingertips_2d_source": torch.from_numpy(self.fingertips_2d[index]), + "K_supervision": torch.from_numpy(K).float(), + } + + def iter_frames(self, input_mode: str) -> Iterator[dict[str, object]]: + for index in range(len(self)): + yield self.frame(index, input_mode) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/h2o_dataset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/h2o_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..f5f771d19779fc8abbe5e010465f753057a4dd31 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/h2o_dataset.py @@ -0,0 +1,407 @@ +"""Cam4-only H2O RGB-D-K clip dataset with explicit annotation masks.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Iterable, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.h2o_fields import load_float_record, load_joint_record, load_mano_record +from foundation_hand.data.oracle_crop import ( + crop_resize_intrinsics, + crop_resize_with_padding, + oracle_square_crop_spec, +) +from foundation_hand.geometry.camera import depth_mm_to_m, intrinsics_from_h2o, project_points, resize_and_pad_intrinsics + +RGB_MEAN = np.asarray([0.485, 0.456, 0.406], dtype=np.float32) +RGB_STD = np.asarray([0.229, 0.224, 0.225], dtype=np.float32) + + +@dataclass(frozen=True) +class ClipRef: + take: str + frame_ids: tuple[int, ...] + + +@dataclass(frozen=True) +class PhotometricAugmentation: + enabled: bool = False + probability: float = 0.8 + brightness: float = 0.2 + contrast: float = 0.2 + saturation: float = 0.2 + hue: float = 0.05 + + @classmethod + def from_mapping( + cls, values: Mapping[str, Any] | None, + ) -> "PhotometricAugmentation": + config = cls(**dict(values or {})) + if not 0.0 <= config.probability <= 1.0: + raise ValueError("photometric probability must be in [0, 1]") + for name in ("brightness", "contrast", "saturation"): + if not 0.0 <= getattr(config, name) < 1.0: + raise ValueError(f"photometric {name} must be in [0, 1)") + if not 0.0 <= config.hue <= 0.5: + raise ValueError("photometric hue must be in [0, 0.5]") + return config + + +def sample_photometric_parameters( + config: PhotometricAugmentation, + seed: int, + clip_index: int, + epoch: int, +) -> np.ndarray: + """Return applied, brightness, contrast, saturation, and hue.""" + + identity = np.asarray([0.0, 1.0, 1.0, 1.0, 0.0], dtype=np.float32) + if not config.enabled: + return identity + rng = np.random.default_rng(np.random.SeedSequence([seed, clip_index, epoch])) + if rng.random() >= config.probability: + return identity + return np.asarray([ + 1.0, + rng.uniform(1.0 - config.brightness, 1.0 + config.brightness), + rng.uniform(1.0 - config.contrast, 1.0 + config.contrast), + rng.uniform(1.0 - config.saturation, 1.0 + config.saturation), + rng.uniform(-config.hue, config.hue), + ], dtype=np.float32) + + +def apply_photometric_augmentation( + rgb: np.ndarray, parameters: np.ndarray, +) -> np.ndarray: + """Apply a fixed-order color transform without changing image geometry.""" + + if float(parameters[0]) == 0.0: + return rgb + _, brightness, contrast, saturation, hue = parameters.astype(np.float32) + image = rgb.astype(np.float32) / 255.0 + image *= brightness + channel_mean = image.mean(axis=(0, 1), keepdims=True) + image = (image - channel_mean) * contrast + channel_mean + luminance = ( + image[..., 0:1] * 0.299 + + image[..., 1:2] * 0.587 + + image[..., 2:3] * 0.114 + ) + image = (image - luminance) * saturation + luminance + image = np.clip(image, 0.0, 1.0) + if float(hue) != 0.0: + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + hsv[..., 0] = np.mod(hsv[..., 0] + float(hue) * 360.0, 360.0) + image = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) + return np.rint(np.clip(image, 0.0, 1.0) * 255.0).astype(np.uint8) + + +def _load_jsonl(path: Path) -> list[dict[str, Any]]: + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + + +def _fit_resize(source_hw: tuple[int, int], target_hw: tuple[int, int]) -> tuple[tuple[int, int], tuple[int, int]]: + source_h, source_w = source_hw + target_h, target_w = target_hw + scale = min(target_w / source_w, target_h / source_h) + resized_h = max(1, round(source_h * scale)) + resized_w = max(1, round(source_w * scale)) + pad_top = (target_h - resized_h) // 2 + pad_left = (target_w - resized_w) // 2 + return (resized_h, resized_w), (pad_left, pad_top) + + +def _resize_pad(array: np.ndarray, target_hw: tuple[int, int], interpolation: int, fill: int | float = 0) -> tuple[np.ndarray, tuple[int, int], tuple[int, int]]: + resized_hw, pad_left_top = _fit_resize(array.shape[:2], target_hw) + resized = cv2.resize(array, (resized_hw[1], resized_hw[0]), interpolation=interpolation) + target_h, target_w = target_hw + pad_left, pad_top = pad_left_top + if array.ndim == 3: + output = np.full((target_h, target_w, array.shape[2]), fill, dtype=array.dtype) + else: + output = np.full((target_h, target_w), fill, dtype=array.dtype) + output[pad_top : pad_top + resized_hw[0], pad_left : pad_left + resized_hw[1]] = resized + return output, resized_hw, pad_left_top + + +class H2OCam4Dataset(Dataset[dict[str, Any]]): + """Read only cam4 clips; annotation-invalid numerical targets become NaN.""" + + def __init__( + self, + root: str | Path, + manifest: str | Path, + target_hw: tuple[int, int] = (288, 512), + clip_lengths: Iterable[int] = (8,), + strides: Iterable[int] = (1,), + window_step: int | None = None, + allow_partial: bool = True, + max_clips: int | None = None, + photometric_augmentation: Mapping[str, Any] | None = None, + augmentation_seed: int = 0, + oracle_crop_enabled: bool = False, + ) -> None: + self.root = Path(root).resolve() + self.manifest = Path(manifest).resolve() + self.target_hw = tuple(target_hw) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.augmentation_seed = int(augmentation_seed) + self.oracle_crop_enabled = bool(oracle_crop_enabled) + lengths = tuple(sorted(set(int(value) for value in clip_lengths))) + strides = tuple(sorted(set(int(value) for value in strides))) + if not lengths or not set(lengths).issubset({1, 2, 4, 8, 16}): + raise ValueError(f"Unsupported clip lengths: {lengths}") + if not strides or not set(strides).issubset({1, 2, 4}): + raise ValueError(f"Unsupported strides: {strides}") + self.clips: list[ClipRef] = [] + for record in _load_jsonl(self.manifest): + take = str(record["take"]) + if not take.endswith("cam4"): + raise ValueError(f"Manifest is not cam4-only: {take}") + available = tuple(int(value) for value in record["frame_ids"]) + for length in lengths: + for stride in strides: + span = (length - 1) * stride + 1 + step = window_step or span + for start in range(0, len(available), step): + ids = available[start : start + span : stride] + if len(ids) == length or (allow_partial and ids): + self.clips.append(ClipRef(take=take, frame_ids=ids)) + if max_clips is not None and len(self.clips) >= max_clips: + return + + def __len__(self) -> int: + return len(self.clips) + + def _load_frame( + self, + take: Path, + frame_id: int, + photometric_parameters: np.ndarray, + ) -> dict[str, np.ndarray | bool | int]: + stem = f"{frame_id:06d}" + rgb_bgr = cv2.imread(str(take / "rgb" / f"{stem}.png"), cv2.IMREAD_COLOR) + depth_mm = cv2.imread(str(take / "depth" / f"{stem}.png"), cv2.IMREAD_UNCHANGED) + if rgb_bgr is None or depth_mm is None: + raise RuntimeError(f"Missing/decode failure at {take}/{stem}") + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + K, source_hw = intrinsics_from_h2o(load_float_record(take / "cam_intrinsics.txt")) + if rgb.shape[:2] != source_hw or depth_mm.shape != source_hw: + raise ValueError(f"RGB/depth/K mismatch at {take}/{stem}") + joints = load_joint_record(take / "hand_pose" / f"{stem}.txt") + mano = load_mano_record(take / "hand_pose_mano" / f"{stem}.txt") + if not np.array_equal(joints.annotation_valid, mano.annotation_valid): + raise ValueError(f"Joint/MANO valid disagreement at {take}/{stem}") + rgb = apply_photometric_augmentation(rgb, photometric_parameters) + oracle_crops = ( + self._extract_oracle_crops( + rgb, depth_mm, K, joints.joints_camera_m, + joints.annotation_valid, + ) + if self.oracle_crop_enabled else {} + ) + rgb, resized_hw, pad_left_top = _resize_pad(rgb, self.target_hw, cv2.INTER_AREA) + depth_mm, depth_resized_hw, depth_pad = _resize_pad(depth_mm, self.target_hw, cv2.INTER_NEAREST) + if depth_resized_hw != resized_hw or depth_pad != pad_left_top: + raise AssertionError("RGB/depth preprocessing diverged") + K_out = resize_and_pad_intrinsics(K, source_hw, resized_hw, pad_left_top) + depth_m, depth_valid = depth_mm_to_m(depth_mm) + + joint2d, positive_z = project_points(joints.joints_camera_m, K_out) + joint_valid = np.broadcast_to(joints.annotation_valid[:, None], (2, 21)).copy() & positive_z + + joint3d = joints.joints_camera_m.copy() + pose = mano.pose_axis_angle.copy() + shape = mano.shape.copy() + raw_translation = mano.translation_raw_m.copy() + wrist_translation = joints.joints_camera_m[:, 0].copy() + for hand in range(2): + if not joints.annotation_valid[hand]: + joint3d[hand] = np.nan + joint2d[hand] = np.nan + wrist_translation[hand] = np.nan + if not mano.annotation_valid[hand]: + pose[hand] = np.nan + shape[hand] = np.nan + raw_translation[hand] = np.nan + + rgb_float = rgb.astype(np.float32) / 255.0 + rgb_float = (rgb_float - RGB_MEAN) / RGB_STD + cam_pose = load_float_record(take / "cam_pose" / f"{stem}.txt").reshape(4, 4).astype(np.float32) + return { + "rgb": np.transpose(rgb_float, (2, 0, 1)), + "depth_m": depth_m[None], + "depth_pixel_valid": depth_valid[None], + "K": K_out, + "camera_pose": cam_pose, + "joint3d_camera": joint3d, + "joint2d": joint2d, + "joint_element_valid": joint_valid, + "mano_pose": pose, + "mano_shape": shape, + "mano_translation_raw": raw_translation, + "wrist_root_translation": wrist_translation, + "joint_annotation_valid": joints.annotation_valid, + "mano_annotation_valid": mano.annotation_valid, + "joint2d_valid": joint_valid, + "joint3d_valid": joint_valid, + "translation_valid": joints.annotation_valid.copy(), + "mano_pose_valid": mano.annotation_valid.copy(), + "shape_valid": mano.annotation_valid.copy(), + "vertices_valid": mano.annotation_valid.copy(), + "reprojection_valid": joint_valid.copy(), + # No reliable H2O field supplies on-screen presence. + "presence_target": np.full((2,), np.nan, dtype=np.float32), + "presence_label_valid": np.zeros((2,), dtype=bool), + "presence_valid": np.zeros((2,), dtype=bool), + "depth_available": True, + "K_available": True, + "depth_input_available": True, + "K_input_available": True, + "K_supervision_valid": True, + "hand_side_id": np.asarray((0, 1), dtype=np.int64), + "timestamp_ns": np.int64(round(frame_id * 1_000_000_000 / 30)), + "frame_id": frame_id, + **oracle_crops, + } + + @staticmethod + def _extract_oracle_crops( + rgb: np.ndarray, + depth_mm: np.ndarray, + K: np.ndarray, + joints_camera_m: np.ndarray, + annotation_valid: np.ndarray, + ) -> dict[str, np.ndarray]: + """Extract fixed A3 crops from raw aligned inputs and GT location.""" + + output_hw = (224, 224) + crops_rgb = np.zeros((2, 3, *output_hw), dtype=np.float32) + crops_depth = np.zeros((2, 1, *output_hw), dtype=np.float32) + crops_depth_valid = np.zeros((2, 1, *output_hw), dtype=bool) + crops_K = np.zeros((2, 3, 3), dtype=np.float32) + boxes = np.full((2, 4), -1, dtype=np.int32) + available = np.zeros(2, dtype=bool) + depth_available = np.zeros(2, dtype=bool) + joint2d_raw, positive_z = project_points(joints_camera_m, K) + for hand in range(2): + joint_valid = ( + np.full(21, bool(annotation_valid[hand]), dtype=bool) + & positive_z[hand] + & np.isfinite(joint2d_raw[hand]).all(axis=-1) + ) + spec = oracle_square_crop_spec( + joint2d_raw[hand], joint_valid, rgb.shape[:2], + ) + if spec is None: + continue + crop_rgb = crop_resize_with_padding( + rgb, spec, interpolation=cv2.INTER_LINEAR, + ) + crop_depth_mm = crop_resize_with_padding( + depth_mm, spec, interpolation=cv2.INTER_NEAREST, + ) + depth_m, valid = depth_mm_to_m(crop_depth_mm) + rgb_float = crop_rgb.astype(np.float32) / 255.0 + rgb_float = (rgb_float - RGB_MEAN) / RGB_STD + crops_rgb[hand] = np.transpose(rgb_float, (2, 0, 1)) + crops_depth[hand, 0] = depth_m + crops_depth_valid[hand, 0] = valid + crops_K[hand] = crop_resize_intrinsics(K, spec) + boxes[hand] = (spec.x0, spec.y0, spec.x1, spec.y1) + available[hand] = True + depth_available[hand] = bool(valid.any()) + return { + "oracle_crop_rgb": crops_rgb, + "oracle_crop_depth_m": crops_depth, + "oracle_crop_depth_pixel_valid": crops_depth_valid, + "oracle_crop_K": crops_K, + "oracle_crop_box_xyxy_raw": boxes, + "oracle_crop_available": available, + "oracle_crop_depth_available": depth_available, + } + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + clip = self.clips[clip_index] + take = self.root / clip.take + parts = Path(clip.take).parts + photometric_parameters = sample_photometric_parameters( + self.photometric_augmentation, + self.augmentation_seed, + clip_index, + epoch, + ) + frames = [ + self._load_frame(take, frame_id, photometric_parameters) + for frame_id in clip.frame_ids + ] + tensor_keys = set(frames[0]) - {"frame_id"} + output: dict[str, Any] = {} + for key in tensor_keys: + values = np.stack([np.asarray(frame[key]) for frame in frames]) + output[key] = torch.from_numpy(values) + output["frame_valid"] = torch.ones(len(frames), dtype=torch.bool) + output["dataset_id"] = "H2O" + output["subject_id"] = parts[0] + output["sequence_id"] = "/".join(parts[1:-1]) + output["physical_recording_id"] = "/".join(parts[:-1]) + output["camera_id"] = "cam4" + output["headset_id"] = "H2O-ego" + output["stream_id"] = "cam4-rgb" + output["frame_id"] = torch.tensor(clip.frame_ids, dtype=torch.long) + output["image_hw"] = torch.tensor(self.target_hw, dtype=torch.long) + output["photometric_aug_params"] = torch.from_numpy( + np.repeat(photometric_parameters[None], len(frames), axis=0) + ) + return output + + +def _pad_time(value: torch.Tensor, target_t: int, fill: float | int | bool) -> torch.Tensor: + if value.shape[0] == target_t: + return value + shape = (target_t - value.shape[0],) + value.shape[1:] + padding = torch.full(shape, fill, dtype=value.dtype) + return torch.cat((value, padding), dim=0) + + +def collate_h2o_clips(samples: list[dict[str, Any]]) -> dict[str, Any]: + """Pad variable length clips without repeating frames.""" + + max_t = max(int(sample["frame_valid"].shape[0]) for sample in samples) + metadata = { + "dataset_id", "subject_id", "sequence_id", "physical_recording_id", + "camera_id", "headset_id", "stream_id", "sampling_source_id", + "filtered_tile_id", "input_mode", + } + metadata &= set(samples[0]) + result: dict[str, Any] = {key: [sample[key] for sample in samples] for key in metadata} + nan_keys = { + "joint3d_camera", "joint3d_root_relative", "joint2d", "mano_pose", "mano_shape", + "mano_translation_raw", "wrist_root_translation", "presence_target", + "vertices_camera", "source_vertex_regen_error_mm", + "projection_roundtrip_error_px", + } + for key in samples[0]: + if key in metadata: + continue + values = [sample[key] for sample in samples] + if key == "image_hw": + result[key] = torch.stack(values) + continue + fill: float | int | bool = float("nan") if key in nan_keys else False if values[0].dtype == torch.bool else -1 if key == "frame_id" else 0 + result[key] = torch.stack([_pad_time(value, max_t, fill) for value in values]) + result["clip_length"] = torch.tensor([sample["frame_valid"].shape[0] for sample in samples], dtype=torch.long) + return result diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/h2o_fields.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/h2o_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..397172b7f7d4c4ac7f0040d4797d5b079e5264a3 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/h2o_fields.py @@ -0,0 +1,88 @@ +"""Strict parsers for the released H2O per-frame hand records.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +HAND_COUNT = 2 +JOINTS_PER_HAND = 21 +JOINT_RECORD_VALUES_PER_HAND = 64 +JOINT_RECORD_VALUES = 128 +MANO_RECORD_VALUES_PER_HAND = 62 +MANO_RECORD_VALUES = 124 +MANO_POSE_DIMS = 48 +MANO_SHAPE_DIMS = 10 + +LEFT = 0 +RIGHT = 1 + + +@dataclass(frozen=True) +class H2OJointRecord: + """Camera-space OpenPose-order hand joints and annotation validity.""" + + annotation_valid: np.ndarray # [2] bool + joints_camera_m: np.ndarray # [2, 21, 3] float32; invalid rows are not supervision + + +@dataclass(frozen=True) +class H2OManoRecord: + """Raw H2O MANO fit parameters and annotation validity.""" + + annotation_valid: np.ndarray # [2] bool + translation_raw_m: np.ndarray # [2, 3] + pose_axis_angle: np.ndarray # [2, 48], global first + shape: np.ndarray # [2, 10] + + +def load_float_record(path: str | Path) -> np.ndarray: + """Load one whitespace-separated H2O text record without accepting bad tokens.""" + + text = Path(path).read_text(encoding="utf-8") + values = np.fromstring(text, dtype=np.float64, sep=" ") + if values.size != len(text.split()): + raise ValueError(f"Non-numeric or malformed value in {path}") + return values + + +def parse_joint_record(values: np.ndarray) -> H2OJointRecord: + values = np.asarray(values, dtype=np.float64).reshape(-1) + if values.size != JOINT_RECORD_VALUES: + raise ValueError(f"Expected {JOINT_RECORD_VALUES} hand_pose values, got {values.size}") + + hands = values.reshape(HAND_COUNT, JOINT_RECORD_VALUES_PER_HAND) + valid = hands[:, 0] != 0 + joints = hands[:, 1:].reshape(HAND_COUNT, JOINTS_PER_HAND, 3).astype(np.float32) + return H2OJointRecord(annotation_valid=valid, joints_camera_m=joints) + + +def parse_mano_record(values: np.ndarray) -> H2OManoRecord: + values = np.asarray(values, dtype=np.float64).reshape(-1) + if values.size != MANO_RECORD_VALUES: + raise ValueError(f"Expected {MANO_RECORD_VALUES} hand_pose_mano values, got {values.size}") + + hands = values.reshape(HAND_COUNT, MANO_RECORD_VALUES_PER_HAND) + valid = hands[:, 0] != 0 + translation = hands[:, 1:4].astype(np.float32) + pose = hands[:, 4 : 4 + MANO_POSE_DIMS].astype(np.float32) + shape = hands[:, 4 + MANO_POSE_DIMS :].astype(np.float32) + if shape.shape != (HAND_COUNT, MANO_SHAPE_DIMS): + raise AssertionError(f"Unexpected MANO shape slice: {shape.shape}") + return H2OManoRecord( + annotation_valid=valid, + translation_raw_m=translation, + pose_axis_angle=pose, + shape=shape, + ) + + +def load_joint_record(path: str | Path) -> H2OJointRecord: + return parse_joint_record(load_float_record(path)) + + +def load_mano_record(path: str | Path) -> H2OManoRecord: + return parse_mano_record(load_float_record(path)) + diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/hoi4d_dataset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/hoi4d_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..af4abbb4603ca6f7cf9396f9905a8b83137ff377 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/hoi4d_dataset.py @@ -0,0 +1,443 @@ +"""HOI4D RGB-D-K clips with explicit wrist-root and supervision semantics.""" + +from __future__ import annotations + +import json +import pickle +from pathlib import Path +import subprocess +from typing import Any, Mapping + +import cv2 +import numpy as np +import torch +from torch.utils.data import Dataset + +from foundation_hand.data.h2o_dataset import ( + RGB_MEAN, + RGB_STD, + PhotometricAugmentation, + _resize_pad, + apply_photometric_augmentation, + sample_photometric_parameters, +) +from foundation_hand.geometry.camera import ( + depth_mm_to_m, + project_points, + resize_and_pad_intrinsics, +) +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.data.schema import ( + InvalidSourceSampleError, + source_root_relative_joint_target, +) + + +def load_hoi4d_mano_annotation(path: str | Path) -> dict[str, np.ndarray]: + """Load one source annotation while classifying payload corruption narrowly.""" + + source = Path(path) + try: + with source.open("rb") as handle: + annotation = pickle.load(handle) + values = { + "poseCoeff": np.asarray(annotation["poseCoeff"], dtype=np.float32), + "beta": np.asarray(annotation["beta"], dtype=np.float32), + "trans": np.asarray(annotation["trans"], dtype=np.float32), + "kps2D": np.asarray(annotation["kps2D"], dtype=np.float32), + } + except (OSError, EOFError, pickle.UnpicklingError, KeyError, TypeError, ValueError) as error: + raise InvalidSourceSampleError( + f"invalid HOI4D MANO annotation payload: {source}: {error}" + ) from error + expected = { + "poseCoeff": (48,), "beta": (10,), "trans": (3,), "kps2D": (21, 2), + } + mismatches = [ + f"{key}={values[key].shape} expected={shape}" + for key, shape in expected.items() if values[key].shape != shape + ] + if mismatches: + raise InvalidSourceSampleError( + f"invalid HOI4D MANO annotation shapes: {source}: {'; '.join(mismatches)}" + ) + return values + + +def hoi4d_geometry_compatibility_mask( + hand_valid: torch.Tensor, vertex_error_mm: torch.Tensor, +) -> torch.Tensor: + """Keep historical-left mesh masked and apply the frozen 1 mm right gate.""" + + geometry_valid = ( + hand_valid & torch.isfinite(vertex_error_mm) & (vertex_error_mm < 1.0) + ) + geometry_valid[..., 0] = False + return geometry_valid + + +def decode_video_frames( + path: str | Path, + frame_ids: list[int], + source_hw: tuple[int, int], + pixel_format: str, + dtype: str, + channels: int, + fps: float | None = None, +) -> np.ndarray: + """Decode exact sorted frame indices while preserving 16-bit depth.""" + + if not frame_ids or frame_ids != sorted(set(frame_ids)): + raise ValueError("HOI4D decoded frame IDs must be non-empty, sorted and unique") + contiguous = frame_ids == list(range(frame_ids[0], frame_ids[-1] + 1)) + if fps is not None and contiguous: + if fps <= 0: + raise ValueError("HOI4D fps must be positive") + command = [ + "ffmpeg", "-v", "error", "-ss", f"{frame_ids[0] / fps:.9f}", + "-i", str(path), "-frames:v", str(len(frame_ids)), + "-f", "rawvideo", "-pix_fmt", pixel_format, "-", + ] + else: + expression = frame_select_expression(frame_ids) + command = [ + "ffmpeg", "-v", "error", "-i", str(path), "-vf", f"select={expression}", + "-vsync", "0", "-frames:v", str(len(frame_ids)), + "-f", "rawvideo", "-pix_fmt", pixel_format, "-", + ] + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) + if result.returncode != 0: + raise RuntimeError(f"ffmpeg decode failed for {path}: {result.stderr.decode(errors='replace')}") + height, width = source_hw + expected = len(frame_ids) * height * width * channels * np.dtype(dtype).itemsize + if len(result.stdout) != expected: + raise RuntimeError( + f"decoded byte count mismatch for {path}: {len(result.stdout)} != {expected}" + ) + shape = (len(frame_ids), height, width) if channels == 1 else ( + len(frame_ids), height, width, channels, + ) + return np.frombuffer(result.stdout, dtype=dtype).reshape(shape).copy() + + +def frame_select_expression(frame_ids: list[int]) -> str: + contiguous = frame_ids == list(range(frame_ids[0], frame_ids[-1] + 1)) + if contiguous: + return f"between(n\\,{frame_ids[0]}\\,{frame_ids[-1]})" + return "+".join(f"eq(n\\,{frame})" for frame in frame_ids) + + +class HOI4DClipDataset(Dataset[dict[str, Any]]): + """Load group-split HOI4D clips into the Phase 7 unified schema.""" + + source_hw = (1080, 1920) + + def __init__( + self, + root: str | Path, + manifest: str | Path, + mano_root: str | Path, + target_hw: tuple[int, int] = (368, 640), + photometric_augmentation: Mapping[str, Any] | None = None, + augmentation_seed: int = 20260717, + ) -> None: + self.root = Path(root).resolve() + self.manifest = Path(manifest).resolve() + self.target_hw = tuple(target_hw) + self.photometric_augmentation = PhotometricAugmentation.from_mapping( + photometric_augmentation + ) + self.augmentation_seed = int(augmentation_seed) + self.rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + if not self.rows or any(row.get("dataset_id") != "HOI4D" for row in self.rows): + raise ValueError("manifest must be non-empty and HOI4D-only") + if any(row.get("official_test_used") is not False for row in self.rows): + raise ValueError("HOI4D manifest lacks official-test isolation declaration") + enable_legacy_mano_loading() + from manopth.manolayer import ManoLayer + self._source_mano = { + side: ManoLayer( + mano_root=str(mano_root), side=side, use_pca=False, + ncomps=45, flat_hand_mean=True, + ) + for side in ("left", "right") + } + self._target_mano = ManoCameraLayer(mano_root, fix_left_shapedirs=True) + self._prefetched_recording: str | None = None + self._prefetched_rgb: dict[int, np.ndarray] = {} + self._prefetched_depth: dict[int, np.ndarray] = {} + + def __len__(self) -> int: + return len(self.rows) + + def _annotation_path(self, row: dict[str, Any], frame: int, side: str) -> Path: + return ( + self.root / "Hand_pose" / f"handpose_{side}_hand" + / row["physical_recording_id"] / f"{frame}.pickle" + ) + + def prefetch_clip_indices(self, clip_indices: list[int]) -> None: + if not clip_indices: + self.clear_prefetch() + return + rows = [self.rows[index] for index in clip_indices] + recordings = {str(row["physical_recording_id"]) for row in rows} + rgb_paths = {str(row["rgb_video"]) for row in rows} + depth_paths = {str(row["depth_video"]) for row in rows} + frame_rates = {float(row["fps"]) for row in rows} + if ( + len(recordings) != 1 or len(rgb_paths) != 1 + or len(depth_paths) != 1 or len(frame_rates) != 1 + ): + raise ValueError("HOI4D prefetch batch must stay within one physical recording") + frame_ids = sorted({int(frame) for row in rows for frame in row["frame_ids"]}) + rgb = decode_video_frames( + next(iter(rgb_paths)), frame_ids, self.source_hw, "rgb24", "u1", 3, + fps=next(iter(frame_rates)), + ) + depth = decode_video_frames( + next(iter(depth_paths)), frame_ids, self.source_hw, "gray16le", " None: + self._prefetched_recording = None + self._prefetched_rgb = {} + self._prefetched_depth = {} + + def source_root_relative_joint3d( + self, index: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Regenerate source-compatible joints without decoding RGB-D video.""" + + row = self.rows[int(index)] + frame_ids = [int(value) for value in row["frame_ids"]] + joints = torch.full((len(frame_ids), 2, 21, 3), float("nan")) + hand_valid = torch.zeros((len(frame_ids), 2), dtype=torch.bool) + for side_index, side in enumerate(("left", "right")): + frame_indices = [] + poses = [] + shapes = [] + for frame_index, frame in enumerate(frame_ids): + path = self._annotation_path(row, frame, side) + if not path.is_file(): + continue + annotation = load_hoi4d_mano_annotation(path) + poses.append(annotation["poseCoeff"]) + shapes.append(annotation["beta"]) + frame_indices.append(frame_index) + if not frame_indices: + continue + with torch.no_grad(): + _, joints_mm = self._source_mano[side]( + torch.from_numpy(np.stack(poses)), + torch.from_numpy(np.stack(shapes)), + ) + relative = (joints_mm - joints_mm[:, :1]) / 1000.0 + joints[frame_indices, side_index] = relative + hand_valid[frame_indices, side_index] = True + return source_root_relative_joint_target(joints, hand_valid) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + frame_ids = [int(value) for value in row["frame_ids"]] + fps = float(row["fps"]) + use_prefetch = ( + self._prefetched_recording == str(row["physical_recording_id"]) + and all(frame in self._prefetched_rgb for frame in frame_ids) + and all(frame in self._prefetched_depth for frame in frame_ids) + ) + if use_prefetch: + rgb_raw = np.stack([self._prefetched_rgb[frame] for frame in frame_ids]) + depth_raw = np.stack([self._prefetched_depth[frame] for frame in frame_ids]) + else: + rgb_raw = decode_video_frames( + row["rgb_video"], frame_ids, self.source_hw, "rgb24", "u1", 3, + fps=fps, + ) + depth_raw = decode_video_frames( + row["depth_video"], frame_ids, self.source_hw, "gray16le", " None: + """Compatibility needed by the official SMPL-X loader on Python 3.11.""" + + if not hasattr(inspect, "getargspec"): + inspect.getargspec = inspect.getfullargspec # type: ignore[attr-defined] + aliases = { + "bool": np.bool_, "int": np.int64, "float": np.float64, + "complex": np.complex128, "object": np.object_, + "unicode": np.str_, "str": np.str_, + } + for name, value in aliases.items(): + if name not in np.__dict__: + setattr(np, name, value) + + +def load_hot3d_api(toolkit_root: str | Path) -> dict[str, Any]: + """Import the pinned official toolkit without copying or rewriting it.""" + + toolkit = Path(toolkit_root).resolve() + source = toolkit / "hot3d" + if not (source / "dataset_api.py").is_file(): + raise FileNotFoundError(f"official HOT3D toolkit missing: {source}") + source_text = str(source) + if source_text not in sys.path: + sys.path.insert(0, source_text) + enable_hot3d_runtime_compatibility() + from dataset_api import Hot3dDataProvider + from data_loaders.loader_hand_poses import Handedness, load_mano_shape_params + from data_loaders.loader_object_library import load_object_library + from data_loaders.mano_layer import MANOHandModel + from projectaria_tools.core.calibration import FISHEYE624, LINEAR + from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions + from projectaria_tools.core.stream_id import StreamId + return { + "Hot3dDataProvider": Hot3dDataProvider, + "Handedness": Handedness, + "load_mano_shape_params": load_mano_shape_params, + "load_object_library": load_object_library, + "MANOHandModel": MANOHandModel, + "LINEAR": LINEAR, + "FISHEYE624": FISHEYE624, + "TimeDomain": TimeDomain, + "TimeQueryOptions": TimeQueryOptions, + "StreamId": StreamId, + } + + +def transform_points(points: np.ndarray, transform: np.ndarray) -> np.ndarray: + points = np.asarray(points, dtype=np.float64) + transform = np.asarray(transform, dtype=np.float64) + if transform.shape != (4, 4): + raise ValueError("transform must be 4x4") + return (points @ transform[:3, :3].T + transform[:3, 3]).astype(np.float32) + + +def linear_camera_matrix(calibration: Any) -> np.ndarray: + focal = np.asarray(calibration.get_focal_lengths(), dtype=np.float64) + principal = np.asarray(calibration.get_principal_point(), dtype=np.float64) + if focal.size != 2 or principal.size != 2: + raise ValueError("HOT3D linear calibration is not pinhole fx/fy/cx/cy") + return np.asarray([ + [focal[0], 0.0, principal[0]], + [0.0, focal[1], principal[1]], + [0.0, 0.0, 1.0], + ], dtype=np.float32) + + +def pca_to_full_local_pose( + coefficients: np.ndarray, + source_layer: Any, +) -> torch.Tensor: + coefficients_t = torch.as_tensor(coefficients, dtype=torch.float32) + if coefficients_t.shape != (15,): + raise ValueError(f"HOT3D MANO PCA pose must have 15 values, got {coefficients_t.shape}") + return ( + coefficients_t @ source_layer.hand_components[:15].detach().cpu() + + source_layer.pose_mean[3:].detach().cpu() + ).reshape(15, 3) + + +def geometry_valid_mask( + annotation_present: torch.Tensor, + vertex_error_mm: torch.Tensor, + threshold_mm: float = 1.0, +) -> torch.Tensor: + """Enable geometry supervision only where MANO regeneration passes audit.""" + + return ( + annotation_present.bool() + & torch.isfinite(vertex_error_mm) + & (vertex_error_mm < threshold_mm) + ) + + +def hot3d_supervision_masks( + geometry_valid: torch.Tensor, + source_vertices: torch.Tensor, + joint2d: torch.Tensor, + positive_depth: torch.Tensor, + projection_error: torch.Tensor, + K: torch.Tensor, + image_hw: tuple[int, int], + max_projection_error_px: float = 2.0, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Keep full-hand 3D targets for visible hands, but only visible 2D joints.""" + + height, width = image_hw + mesh_uv, mesh_positive = project_points(source_vertices, K) + mesh_in_frame = ( + mesh_positive & torch.isfinite(mesh_uv).all(-1) + & (mesh_uv[..., 0] >= 0) & (mesh_uv[..., 0] < width) + & (mesh_uv[..., 1] >= 0) & (mesh_uv[..., 1] < height) + ) + hand_valid = geometry_valid & mesh_in_frame.any(-1) + joint_in_frame = ( + positive_depth & torch.isfinite(joint2d).all(-1) + & (joint2d[..., 0] >= 0) & (joint2d[..., 0] < width) + & (joint2d[..., 1] >= 0) & (joint2d[..., 1] < height) + ) + joint2d_valid = ( + hand_valid[..., None] & joint_in_frame + & torch.isfinite(projection_error) + & (projection_error <= max_projection_error_px) + ) + joint3d_valid = hand_valid[..., None].expand_as(joint2d_valid) + return hand_valid, joint2d_valid, joint3d_valid + + +def quest_linear_camera_calibration( + device: Any, stream_id: Any, linear_model: Any, native_model: Any, +) -> tuple[Any, Any]: + """Use Quest3's native device-to-camera transform with its rectified intrinsics.""" + + T_device_camera, _ = device.get_camera_calibration( + stream_id, camera_model=native_model, + ) + _, linear_calibration = device.get_camera_calibration( + stream_id, camera_model=linear_model, + ) + return T_device_camera, linear_calibration + + +class HOT3DClipDataset(Dataset[dict[str, Any]]): + """Decode rectilinear HOT3D clips through the official toolkit.""" + + def __init__( + self, + root: str | Path, + manifest: str | Path, + toolkit_root: str | Path, + mano_root: str | Path, + target_hw: tuple[int, int] = (368, 640), + K_input_dropout: float = 0.3, + dropout_seed: int = 20260717, + max_clips: int | None = None, + provider_cache_size: int = 2, + ) -> None: + self.root = Path(root).resolve() + self.manifest = Path(manifest).resolve() + self.toolkit_root = Path(toolkit_root).resolve() + self.mano_root = Path(mano_root).resolve() + self.target_hw = tuple(int(value) for value in target_hw) + self.K_input_dropout = float(K_input_dropout) + self.dropout_seed = int(dropout_seed) + self.provider_cache_size = int(provider_cache_size) + if not 0.0 <= self.K_input_dropout <= 1.0: + raise ValueError("K_input_dropout must be in [0, 1]") + if self.provider_cache_size < 1: + raise ValueError("provider_cache_size must be positive") + rows = [ + json.loads(line) for line in self.manifest.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + for row in rows: + if row.get("dataset") != "HOT3D" or row.get("have_hand_object_pose_gt") is not True: + raise ValueError("HOT3D manifest contains a non-GT or foreign row") + if len(row.get("timestamps_ns", [])) == 0: + raise ValueError("HOT3D manifest contains an empty clip") + self.rows = rows[:max_clips] + self._api: dict[str, Any] | None = None + self._object_library: Any | None = None + self._source_mano: Any | None = None + self._target_mano: ManoCameraLayer | None = None + self._providers: OrderedDict[str, Any] = OrderedDict() + + def __len__(self) -> int: + return len(self.rows) + + def _initialize_runtime(self) -> None: + if self._api is not None: + return + self._api = load_hot3d_api(self.toolkit_root) + self._object_library = self._api["load_object_library"]( + str(self.root / "assets") + ) + self._source_mano = self._api["MANOHandModel"]( + str(self.mano_root), joint_mapper=None, + ) + self._target_mano = ManoCameraLayer( + self.mano_root, fix_left_shapedirs=True, + ).eval() + + def _provider(self, recording: str) -> Any: + self._initialize_runtime() + if recording in self._providers: + provider = self._providers.pop(recording) + self._providers[recording] = provider + return provider + assert self._api is not None + provider = self._api["Hot3dDataProvider"]( + sequence_folder=str(self.root / recording), + object_library=self._object_library, + mano_hand_model=self._source_mano, + ) + self._providers[recording] = provider + while len(self._providers) > self.provider_cache_size: + self._providers.popitem(last=False) + return provider + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + if isinstance(index, tuple): + clip_index, epoch = int(index[0]), int(index[1]) + else: + clip_index, epoch = int(index), 0 + row = self.rows[clip_index] + provider = self._provider(str(row["recording_id"])) + assert self._api is not None and self._target_mano is not None + hand_provider = provider.mano_hand_data_provider + if hand_provider is None: + raise RuntimeError("GT HOT3D row has no official MANO provider") + device = provider.device_data_provider + pose_provider = provider.device_pose_data_provider + stream_id = self._api["StreamId"](str(row["stream_id"])) + is_aria = str(row["headset"]) == "Aria" + keep_K = deterministic_clip_keep( + 1.0 - self.K_input_dropout, + self.dropout_seed, + clip_index, + epoch, + ) + shape_params = torch.as_tensor( + self._api["load_mano_shape_params"]( + str(self.root / row["recording_id"] / "mano_hand_pose_trajectory.jsonl") + ), + dtype=torch.float32, + ) + + frames: list[dict[str, Any]] = [] + source_vertices: list[np.ndarray] = [] + pose_targets: list[np.ndarray] = [] + shape_targets: list[np.ndarray] = [] + wrist_targets: list[np.ndarray] = [] + hand_valid_rows: list[np.ndarray] = [] + raw_calibrations: list[Any] = [] + resize_contracts: list[tuple[tuple[int, int], tuple[int, int], tuple[int, int]]] = [] + for timestamp_ns in row["timestamps_ns"]: + timestamp_ns = int(timestamp_ns) + hand_with_dt = hand_provider.get_pose_at_timestamp( + timestamp_ns, + self._api["TimeQueryOptions"].CLOSEST, + self._api["TimeDomain"].TIME_CODE, + 20_000_000, + ) + headset_with_dt = pose_provider.get_pose_at_timestamp( + timestamp_ns, + self._api["TimeQueryOptions"].CLOSEST, + self._api["TimeDomain"].TIME_CODE, + 20_000_000, + ) + if hand_with_dt is None or headset_with_dt is None: + raise RuntimeError( + f"HOT3D 20ms synchronization failure recording={row['recording_id']} " + f"stream={row['stream_id']} timestamp_ns={timestamp_ns} " + f"hand_missing={hand_with_dt is None} " + f"headset_missing={headset_with_dt is None}" + ) + if is_aria: + T_device_camera, calibration = device.get_online_camera_calibration( + stream_id, timestamp_ns, camera_model=self._api["LINEAR"], + ) + else: + T_device_camera, calibration = quest_linear_camera_calibration( + device, stream_id, self._api["LINEAR"], self._api["FISHEYE624"], + ) + image = device.get_undistorted_image(timestamp_ns, stream_id) + if image is None: + raise RuntimeError("official HOT3D provider returned no image") + if image.ndim == 2: + image = np.repeat(image[..., None], 3, axis=-1) + if image.ndim != 3 or image.shape[-1] != 3: + raise ValueError(f"unexpected HOT3D image shape: {image.shape}") + K_raw = linear_camera_matrix(calibration) + image, resized_hw, pad_left_top = _resize_pad( + image, self.target_hw, cv2.INTER_AREA, + ) + K = resize_and_pad_intrinsics( + K_raw, tuple(int(v) for v in calibration.get_image_size()[::-1]), + resized_hw, pad_left_top, + ) + source_hw = tuple(int(v) for v in calibration.get_image_size()[::-1]) + T_world_camera = ( + headset_with_dt.pose3d.T_world_device @ T_device_camera + ) + T_camera_world = np.asarray(T_world_camera.inverse().to_matrix()) + + poses = np.full((2, 48), np.nan, dtype=np.float32) + shapes = np.full((2, 10), np.nan, dtype=np.float32) + wrists = np.full((2, 3), np.nan, dtype=np.float32) + vertices = np.full((2, 778, 3), np.nan, dtype=np.float32) + valid = np.zeros(2, dtype=bool) + collection = hand_with_dt.pose3d_collection + for handedness, side in ( + (self._api["Handedness"].Left, 0), + (self._api["Handedness"].Right, 1), + ): + if handedness not in collection.poses: + continue + hand = collection.poses[handedness] + source_layer = ( + self._source_mano.mano_layer_left + if side == 0 else self._source_mano.mano_layer_right + ) + local_pose = pca_to_full_local_pose(hand.joint_angles, source_layer) + R_camera_world = torch.as_tensor( + T_camera_world[:3, :3], dtype=torch.float32, + ) + R_world_wrist = torch.as_tensor( + hand.wrist_pose.to_matrix()[:3, :3], dtype=torch.float32, + ) + global_pose = matrix_to_axis_angle( + (R_camera_world @ R_world_wrist)[None], + )[0] + source_vertex = hand_provider.get_hand_mesh_vertices(hand) + if source_vertex is None: + continue + # The official provider's mesh is authoritative. Wrist position + # is obtained from its native MANO root by undoing the global + # raw-translation convention through the source layer below. + native_output = source_layer( + betas=shape_params[None], + global_orient=matrix_to_axis_angle(R_world_wrist[None]), + hand_pose=torch.as_tensor(hand.joint_angles)[None], + transl=torch.as_tensor(hand.wrist_pose.to_matrix()[:3, 3])[None], + return_verts=True, + ) + wrist_world = native_output.joints[0, 0].detach().cpu().numpy() + poses[side] = torch.cat((global_pose, local_pose.reshape(-1))).numpy() + shapes[side] = shape_params.numpy() + wrists[side] = transform_points(wrist_world[None], T_camera_world)[0] + vertices[side] = transform_points( + source_vertex.detach().cpu().numpy(), T_camera_world, + ) + valid[side] = True + rgb = image.astype(np.float32) / 255.0 + rgb = (rgb - RGB_MEAN) / RGB_STD + frames.append({ + "rgb": np.transpose(rgb, (2, 0, 1)), + "K": K.astype(np.float32), + "camera_pose": np.asarray(T_world_camera.to_matrix(), dtype=np.float32), + "timestamp_ns": np.int64(timestamp_ns), + "frame_id": np.int64(timestamp_ns), + "hand_pose_time_delta_ns": np.int64(hand_with_dt.time_delta_ns), + "headset_time_delta_ns": np.int64(headset_with_dt.time_delta_ns), + }) + source_vertices.append(vertices) + pose_targets.append(poses) + shape_targets.append(shapes) + wrist_targets.append(wrists) + hand_valid_rows.append(valid) + raw_calibrations.append(calibration) + resize_contracts.append((source_hw, resized_hw, pad_left_top)) + + pose_tensor = torch.from_numpy(np.stack(pose_targets)) + shape_tensor = torch.from_numpy(np.stack(shape_targets)) + wrist_tensor = torch.from_numpy(np.stack(wrist_targets)) + valid_tensor = torch.from_numpy(np.stack(hand_valid_rows)) + rotations = axis_angle_to_matrix( + torch.nan_to_num(pose_tensor).reshape(len(frames), 2, 16, 3) + ) + with torch.no_grad(): + target_vertices, target_joints = self._target_mano( + rotations, torch.nan_to_num(shape_tensor), + torch.nan_to_num(wrist_tensor), + ) + source_vertex_tensor = torch.from_numpy(np.stack(source_vertices)) + vertex_error_mm = torch.linalg.vector_norm( + target_vertices - source_vertex_tensor, dim=-1, + ).amax(dim=-1) * 1000.0 + geometry_valid = geometry_valid_mask(valid_tensor, vertex_error_mm) + + K_tensor = torch.from_numpy(np.stack([frame["K"] for frame in frames])) + joint2d, positive = project_points(target_joints, K_tensor) + time = len(frames) + projection_error = torch.full((time, 2, 21), float("nan")) + for frame_index, calibration in enumerate(raw_calibrations): + source_hw, resized_hw, (pad_left, pad_top) = resize_contracts[frame_index] + scale_x = resized_hw[1] / source_hw[1] + scale_y = resized_hw[0] / source_hw[0] + for side in range(2): + if not geometry_valid[frame_index, side]: + continue + for joint_index, point in enumerate(target_joints[frame_index, side]): + source_uv = calibration.project(point.detach().cpu().numpy()) + if source_uv is None: + continue + resized_uv = torch.tensor( + ( + float(source_uv[0]) * scale_x + pad_left, + float(source_uv[1]) * scale_y + pad_top, + ), + dtype=joint2d.dtype, + ) + projection_error[frame_index, side, joint_index] = ( + torch.linalg.vector_norm( + resized_uv - joint2d[frame_index, side, joint_index] + ) + ) + geometry_valid, joint2d_valid, joint3d_valid = hot3d_supervision_masks( + geometry_valid, source_vertex_tensor, joint2d, positive, + projection_error, K_tensor, self.target_hw, + ) + for tensor in (target_vertices, target_joints, joint2d, pose_tensor, shape_tensor, wrist_tensor): + mask = geometry_valid + while mask.ndim < tensor.ndim: + mask = mask.unsqueeze(-1) + tensor.masked_fill_(~mask, float("nan")) + output: dict[str, Any] = { + "rgb": torch.from_numpy(np.stack([frame["rgb"] for frame in frames])), + "depth_m": torch.zeros((time, 1, *self.target_hw), dtype=torch.float32), + "depth_pixel_valid": torch.zeros((time, 1, *self.target_hw), dtype=torch.bool), + "K": K_tensor, + "camera_pose": torch.from_numpy(np.stack([frame["camera_pose"] for frame in frames])), + "joint3d_camera": target_joints, + "joint2d": joint2d, + "joint_element_valid": joint3d_valid, + "mano_pose": pose_tensor, + "mano_shape": shape_tensor, + "mano_translation_raw": torch.full_like(wrist_tensor, float("nan")), + "wrist_root_translation": wrist_tensor, + "joint_annotation_valid": geometry_valid, + "mano_annotation_valid": geometry_valid, + "joint2d_valid": joint2d_valid, + "joint3d_valid": joint3d_valid, + "translation_valid": geometry_valid, + "mano_pose_valid": geometry_valid, + "shape_valid": geometry_valid, + "vertices_valid": geometry_valid, + "reprojection_valid": joint2d_valid, + "vertices_camera": target_vertices, + "presence_target": torch.full((time, 2), float("nan")), + "presence_label_valid": torch.zeros((time, 2), dtype=torch.bool), + "presence_valid": torch.zeros((time, 2), dtype=torch.bool), + "depth_available": torch.zeros(time, dtype=torch.bool), + "K_available": torch.full((time,), keep_K, dtype=torch.bool), + "depth_input_available": torch.zeros(time, dtype=torch.bool), + "K_input_available": torch.full((time,), keep_K, dtype=torch.bool), + "K_supervision_valid": torch.ones(time, dtype=torch.bool), + "frame_valid": torch.ones(time, dtype=torch.bool), + "hand_side_id": torch.tensor((0, 1))[None].expand(time, -1).clone(), + "timestamp_ns": torch.tensor([frame["timestamp_ns"] for frame in frames]), + "frame_id": torch.tensor([frame["frame_id"] for frame in frames]), + "hand_pose_time_delta_ns": torch.tensor([frame["hand_pose_time_delta_ns"] for frame in frames]), + "headset_time_delta_ns": torch.tensor([frame["headset_time_delta_ns"] for frame in frames]), + "source_vertex_regen_error_mm": vertex_error_mm, + "source_hand_annotation_present": valid_tensor, + "geometry_convention_compatible": geometry_valid, + "projection_roundtrip_error_px": projection_error, + "image_hw": torch.tensor(self.target_hw, dtype=torch.long), + "dataset_id": "HOT3D", + "subject_id": str(row["participant_id"]), + "sequence_id": str(row["recording_id"]), + "physical_recording_id": str(row["recording_id"]), + "camera_id": str(row["stream_id"]), + "stream_id": str(row["stream_id"]), + "headset_id": str(row["headset"]), + } + return output diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/oracle_crop.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/oracle_crop.py new file mode 100644 index 0000000000000000000000000000000000000000..b615a58c3762a9ab88ed870acf5b6bc532d8ba6e --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/oracle_crop.py @@ -0,0 +1,105 @@ +"""Pre-registered raw-image crop geometry for the A3 oracle diagnostic.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import cv2 +import numpy as np + +from foundation_hand.geometry.camera import resize_and_pad_intrinsics + + +@dataclass(frozen=True) +class OracleCropSpec: + x0: int + y0: int + side: int + source_hw: tuple[int, int] + output_hw: tuple[int, int] = (224, 224) + + @property + def x1(self) -> int: + return self.x0 + self.side + + @property + def y1(self) -> int: + return self.y0 + self.side + + +def oracle_square_crop_spec( + joints_2d: np.ndarray, + joint_valid: np.ndarray, + source_hw: tuple[int, int], + *, + margin: float = 1.5, + min_side: int = 96, + min_points: int = 4, + output_hw: tuple[int, int] = (224, 224), +) -> OracleCropSpec | None: + """Build the fixed A3 square ROI from valid GT joint locations.""" + + points = np.asarray(joints_2d, dtype=np.float64) + valid = np.asarray(joint_valid, dtype=bool) + if points.shape != (21, 2) or valid.shape != (21,): + raise ValueError("expected joints [21,2] and validity [21]") + source_h, source_w = (int(value) for value in source_hw) + output_h, output_w = (int(value) for value in output_hw) + if min(source_h, source_w, output_h, output_w, min_side, min_points) <= 0: + raise ValueError("image sizes, minimum side, and minimum points must be positive") + if margin < 1.0: + raise ValueError("crop margin must be at least 1") + valid &= np.isfinite(points).all(axis=-1) + if int(valid.sum()) < min_points: + return None + selected = points[valid] + lower = selected.min(axis=0) + upper = selected.max(axis=0) + center = 0.5 * (lower + upper) + side = int(np.ceil(max(float(np.max(upper - lower)) * margin, float(min_side)))) + x0 = int(np.floor(float(center[0]) - side / 2.0)) + y0 = int(np.floor(float(center[1]) - side / 2.0)) + if x0 >= source_w or y0 >= source_h or x0 + side <= 0 or y0 + side <= 0: + return None + return OracleCropSpec(x0, y0, side, (source_h, source_w), (output_h, output_w)) + + +def crop_resize_with_padding( + array: np.ndarray, + spec: OracleCropSpec, + *, + interpolation: int, + fill: int | float = 0, +) -> np.ndarray: + """Apply an integer square crop, explicit padding, then one resize.""" + + value = np.asarray(array) + if value.shape[:2] != spec.source_hw: + raise ValueError(f"source shape {value.shape[:2]} does not match {spec.source_hw}") + crop_shape = (spec.side, spec.side) + value.shape[2:] + crop = np.full(crop_shape, fill, dtype=value.dtype) + source_h, source_w = spec.source_hw + source_x0, source_y0 = max(0, spec.x0), max(0, spec.y0) + source_x1, source_y1 = min(source_w, spec.x1), min(source_h, spec.y1) + if source_x1 > source_x0 and source_y1 > source_y0: + target_x0, target_y0 = source_x0 - spec.x0, source_y0 - spec.y0 + crop[ + target_y0 : target_y0 + source_y1 - source_y0, + target_x0 : target_x0 + source_x1 - source_x0, + ] = value[source_y0:source_y1, source_x0:source_x1] + output_h, output_w = spec.output_hw + return cv2.resize(crop, (output_w, output_h), interpolation=interpolation) + + +def crop_resize_intrinsics(K: np.ndarray, spec: OracleCropSpec) -> np.ndarray: + """Update raw intrinsics for the exact integer-crop/resize transform.""" + + matrix = np.asarray(K, dtype=np.float32) + if matrix.shape != (3, 3): + raise ValueError(f"expected K [3,3], got {matrix.shape}") + crop_K = matrix.copy() + crop_K[0, 2] -= spec.x0 + crop_K[1, 2] -= spec.y0 + return resize_and_pad_intrinsics( + crop_K, (spec.side, spec.side), spec.output_hw, (0, 0), + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/samplers.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..bf66124e4179cb7965c062132f17b2124003d6c8 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/samplers.py @@ -0,0 +1,240 @@ +"""Deterministic batch sampling that can resume exactly from a global step.""" + +from __future__ import annotations + +import math +import hashlib +import json +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import torch +from torch.utils.data import Sampler + + +SampleIndex = int | tuple[int, int] + + +class ResumableRandomBatchSampler(Sampler[list[SampleIndex]]): + """Generate an epoch permutation from ``seed + epoch``. + + The batch at a given global step is a pure function of the dataset size, + batch size, seed, and step. Reconstructing the sampler with ``start_step`` + therefore produces the same remaining batches after a checkpoint resume. + """ + + def __init__( + self, + dataset_size: int, + batch_size: int, + seed: int, + start_step: int, + end_step: int, + include_epoch: bool = False, + ) -> None: + if dataset_size <= 0: + raise ValueError("dataset_size must be positive") + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0 <= start_step <= end_step: + raise ValueError(f"Invalid step range: [{start_step}, {end_step})") + self.dataset_size = dataset_size + self.batch_size = batch_size + self.seed = seed + self.start_step = start_step + self.end_step = end_step + self.include_epoch = include_epoch + self.steps_per_epoch = math.ceil(dataset_size / batch_size) + + def __len__(self) -> int: + return self.end_step - self.start_step + + def __iter__(self) -> Iterator[list[SampleIndex]]: + cached_epoch = -1 + permutation: list[int] = [] + for step in range(self.start_step, self.end_step): + epoch, batch_in_epoch = divmod(step, self.steps_per_epoch) + if epoch != cached_epoch: + generator = torch.Generator().manual_seed(self.seed + epoch) + permutation = torch.randperm(self.dataset_size, generator=generator).tolist() + cached_epoch = epoch + start = batch_in_epoch * self.batch_size + indices = permutation[start : min(start + self.batch_size, self.dataset_size)] + if self.include_epoch: + yield [(index, epoch) for index in indices] + else: + yield indices + + +class ResumableWeightedBatchSampler(Sampler[list[SampleIndex]]): + """Draw a deterministic weighted epoch with replacement. + + Each epoch contains ``dataset_size`` draws. The draw sequence is a pure + function of the weights, seed, and epoch, so resuming at a global step + reproduces the uninterrupted batches exactly. + """ + + def __init__( + self, + weights: torch.Tensor | list[float], + batch_size: int, + seed: int, + start_step: int, + end_step: int, + include_epoch: bool = False, + ) -> None: + values = torch.as_tensor(weights, dtype=torch.float64, device="cpu") + if values.ndim != 1 or values.numel() == 0: + raise ValueError("weights must be a non-empty one-dimensional sequence") + if not torch.isfinite(values).all() or bool((values <= 0).any()): + raise ValueError("weights must be finite and strictly positive") + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0 <= start_step <= end_step: + raise ValueError(f"Invalid step range: [{start_step}, {end_step})") + self.weights = values + self.dataset_size = int(values.numel()) + self.batch_size = batch_size + self.seed = seed + self.start_step = start_step + self.end_step = end_step + self.include_epoch = include_epoch + self.steps_per_epoch = math.ceil(self.dataset_size / batch_size) + + def __len__(self) -> int: + return self.end_step - self.start_step + + def __iter__(self) -> Iterator[list[SampleIndex]]: + cached_epoch = -1 + draws: list[int] = [] + for step in range(self.start_step, self.end_step): + epoch, batch_in_epoch = divmod(step, self.steps_per_epoch) + if epoch != cached_epoch: + generator = torch.Generator().manual_seed(self.seed + epoch) + draws = torch.multinomial( + self.weights, + num_samples=self.dataset_size, + replacement=True, + generator=generator, + ).tolist() + cached_epoch = epoch + start = batch_in_epoch * self.batch_size + indices = draws[start : min(start + self.batch_size, self.dataset_size)] + if self.include_epoch: + yield [(index, epoch) for index in indices] + else: + yield indices + + +class ResumableMixtureBatchSampler(Sampler[list[SampleIndex]]): + """Draw an exact-resume batch from a registered dataset mixture. + + Source selection is independent of source length, so a large frame-count + dataset cannot silently dominate a registered mixture. Sampling within a + source is uniform with replacement and is a pure function of global step. + """ + + def __init__( + self, + source_sizes: list[int] | tuple[int, ...], + source_weights: list[float] | tuple[float, ...], + batch_size: int, + seed: int, + start_step: int, + end_step: int, + include_epoch: bool = False, + ) -> None: + sizes = torch.as_tensor(source_sizes, dtype=torch.int64) + weights = torch.as_tensor(source_weights, dtype=torch.float64) + if sizes.ndim != 1 or sizes.numel() == 0 or bool((sizes <= 0).any()): + raise ValueError("source_sizes must be a non-empty positive sequence") + if weights.shape != sizes.shape: + raise ValueError("source_weights must match source_sizes") + if not torch.isfinite(weights).all() or bool((weights <= 0).any()): + raise ValueError("source_weights must be finite and positive") + if batch_size <= 0: + raise ValueError("batch_size must be positive") + if not 0 <= start_step <= end_step: + raise ValueError(f"Invalid step range: [{start_step}, {end_step})") + self.source_sizes = sizes + self.source_weights = weights / weights.sum() + self.source_offsets = torch.cat((sizes.new_zeros(1), sizes.cumsum(0)[:-1])) + self.batch_size = int(batch_size) + self.seed = int(seed) + self.start_step = int(start_step) + self.end_step = int(end_step) + self.include_epoch = bool(include_epoch) + self.steps_per_epoch = math.ceil(int(sizes.sum()) / self.batch_size) + + def __len__(self) -> int: + return self.end_step - self.start_step + + def __iter__(self) -> Iterator[list[SampleIndex]]: + for step in range(self.start_step, self.end_step): + generator = torch.Generator().manual_seed(self.seed + step) + source_ids = torch.multinomial( + self.source_weights, + num_samples=self.batch_size, + replacement=True, + generator=generator, + ) + indices: list[SampleIndex] = [] + epoch = step // self.steps_per_epoch + for source_id in source_ids.tolist(): + local_index = int(torch.randint( + int(self.source_sizes[source_id]), + (1,), generator=generator, + )) + global_index = int(self.source_offsets[source_id]) + local_index + indices.append((global_index, epoch) if self.include_epoch else global_index) + yield indices + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_balanced_sampling_weights( + path: str | Path, + train_manifest: str | Path, + data_config: dict[str, Any], + dataset_size: int, +) -> tuple[list[float], dict[str, Any]]: + """Validate and load a train-only Phase 4 balanced-sampling manifest.""" + + manifest_path = Path(path) + train_manifest_path = Path(train_manifest) + record = json.loads(manifest_path.read_text(encoding="utf-8")) + if record.get("version") != "phase4_train_geometry_balanced_v1": + raise ValueError("unsupported balanced-sampling manifest version") + if record.get("split_role") != "official_train" or record.get("official_test_used") is not False: + raise ValueError("balanced sampling must be built from official train only") + if record.get("source_manifest_sha256") != _sha256(train_manifest_path): + raise ValueError("balanced-sampling source hash does not match --manifest") + contract = record.get("dataset_contract", {}) + expected_contract = { + "resolution_hw": list(data_config["resolution_hw"]), + "T": int(data_config["T"]), + "stride": int(data_config["stride"]), + } + for key, expected in expected_contract.items(): + if contract.get(key) != expected: + raise ValueError( + f"balanced-sampling contract mismatch for {key}: " + f"{contract.get(key)} != {expected}" + ) + rows = record.get("clips", []) + if len(rows) != dataset_size or record.get("clip_count") != dataset_size: + raise ValueError("balanced-sampling clip count does not match the training dataset") + indices = [row.get("clip_index") for row in rows] + if indices != list(range(dataset_size)): + raise ValueError("balanced-sampling clip indices must be ordered and complete") + weights = torch.as_tensor([row.get("weight") for row in rows], dtype=torch.float64) + if not torch.isfinite(weights).all() or bool((weights <= 0).any()): + raise ValueError("balanced-sampling weights must be finite and strictly positive") + return weights.tolist(), record diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/schema.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..15e3e8a1bdb388388060e4f27b01fbea4fa22104 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/data/schema.py @@ -0,0 +1,89 @@ +"""Unified multi-source sample supervision and modality contracts.""" + +from __future__ import annotations + +from typing import Mapping + +import torch + + +class InvalidSourceSampleError(RuntimeError): + """A manifest row points to missing, unreadable, or malformed source data.""" + + +SUPERVISION_MASK_KEYS = ( + "joint2d_valid", + "joint3d_valid", + "joint3d_root_relative_valid", + "translation_valid", + "mano_pose_valid", + "shape_valid", + "vertices_valid", + "reprojection_valid", + "presence_valid", + "K_supervision_valid", +) + + +def source_root_relative_joint_target( + joints_camera: torch.Tensor, + hand_valid: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Keep credible source-layer joint geometry separate from MANO compatibility.""" + + if joints_camera.shape[-2:] != (21, 3): + raise ValueError("source joints must end in [21,3]") + if hand_valid.shape != joints_camera.shape[:-2]: + raise ValueError("hand-valid mask differs from source joint prefix") + relative = joints_camera - joints_camera[..., :1, :] + valid = hand_valid[..., None] & torch.isfinite(relative).all(dim=-1) + relative = relative.masked_fill(~valid[..., None], float("nan")) + return relative, valid + +INPUT_AVAILABILITY_KEYS = ( + "depth_input_available", + "K_input_available", +) + + +def supervision_mask( + batch: Mapping[str, torch.Tensor], + key: str, + fallback: torch.Tensor, +) -> torch.Tensor: + """Resolve a Phase 7 mask while preserving historical batch behavior.""" + + value = batch.get(key) + return fallback.bool() if value is None else value.bool() + + +def input_availability( + batch: Mapping[str, torch.Tensor], + key: str, + legacy_key: str, + fallback: torch.Tensor, +) -> torch.Tensor: + """Keep model-input availability separate from geometry supervision.""" + + value = batch.get(key) + if value is None: + value = batch.get(legacy_key, fallback) + return value.bool() + + +def deterministic_clip_keep( + probability: float, + seed: int, + clip_index: int, + epoch: int, +) -> bool: + """Deterministic clip-level Bernoulli used by external input dropout.""" + + if not 0.0 <= probability <= 1.0: + raise ValueError("probability must be in [0, 1]") + generator = torch.Generator(device="cpu") + generator.manual_seed( + (int(seed) * 1_000_003 + int(clip_index) * 9_176 + int(epoch)) + % (2**63 - 1) + ) + return bool(torch.rand((), generator=generator).item() < probability) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/__init__.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..981c62ba4cc30967189bc146bb40d8fe3e3635f8 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/__init__.py @@ -0,0 +1,6 @@ +"""Evaluation and visualization utilities for camera-space reconstruction.""" + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary +from foundation_hand.evaluation.selection import select_visualization_frames + +__all__ = ["bootstrap_take_means", "distribution_summary", "select_visualization_frames"] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/alignment_calibration.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/alignment_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..458feac1e2e30ca149ae69fd3fa91bdb346d0d02 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/alignment_calibration.py @@ -0,0 +1,70 @@ +"""Shared feature contract for OOF metric-alignment calibration and inference.""" + +from __future__ import annotations + +import numpy as np + + +FEATURE_NAMES = ( + "raw_alignment_delta_z_m", + "log_valid_support_count", + "inlier_ratio", + "residual_scale_m", + "valid_fraction", + "foreground_fraction", + "background_fraction", + "depth_discontinuity_m", + "conditioning_quality", + "coarse_wrist_z_m", + "log_hand_scale_px", + "direct_mano_consistency_px", + "silhouette_overlap_fraction", + "coarse_velocity_z_m_per_frame", + "side_right", +) + + +def projected_hand_scale_px( + projected_joints_px: np.ndarray, + *, + source_hw: tuple[int, int], + target_hw: tuple[int, int], +) -> np.ndarray: + """Measure projected hand extent after mapping source pixels to model pixels.""" + + source_height, source_width = source_hw + target_height, target_width = target_hw + if min(source_height, source_width, target_height, target_width) <= 0: + raise ValueError("source and target image dimensions must be positive") + scale = np.asarray( + (target_width / source_width, target_height / source_height), dtype=np.float32, + ) + resized = np.asarray(projected_joints_px, dtype=np.float32) * scale + return np.ptp(resized, axis=-2).max(axis=-1) + + +def features_from_take(arrays: dict[str, np.ndarray]) -> np.ndarray: + """Create `[time,left/right,feature]` geometry-only calibration inputs.""" + + time = len(arrays["frame_id"]) + side_right = np.broadcast_to(np.asarray((0.0, 1.0), dtype=np.float32), (time, 2)) + overlap = np.broadcast_to(arrays["silhouette_overlap_fraction"][:, None], (time, 2)) + values = ( + arrays["alignment_delta_z_m"], + np.log1p(arrays["alignment_valid_support_count"]), + arrays["alignment_inlier_ratio"], + arrays["alignment_residual_scale_m"], + arrays["alignment_valid_fraction"], + arrays["alignment_foreground_fraction"], + arrays["alignment_background_fraction"], + arrays["alignment_depth_discontinuity_m"], + arrays["alignment_conditioning_quality"], + arrays["pred_wrist_translation"][..., 2], + np.log1p(np.maximum(arrays["coarse_hand_scale_px"], 0.0)), + arrays["coarse_direct_mano_consistency_px"], + overlap, + arrays["coarse_wrist_velocity_m_per_frame"][..., 2], + side_right, + ) + features = np.stack(values, axis=-1).astype(np.float64) + return np.nan_to_num(features, nan=0.0, posinf=0.0, neginf=0.0) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/causal_state.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/causal_state.py new file mode 100644 index 0000000000000000000000000000000000000000..66dea1ca7230f736d8ffb5f32f645ed7b862f4b7 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/causal_state.py @@ -0,0 +1,121 @@ +"""Causal translation-z state estimators for Phase 5 deployment.""" + +from __future__ import annotations + +import numpy as np + + +def measurement_uncertainty_multiplier( + confidence: np.ndarray, + inlier_ratio: np.ndarray, + residual_scale_m: np.ndarray, + valid_fraction: np.ndarray, + conditioning_quality: np.ndarray, + strength: float, +) -> np.ndarray: + """Map bounded geometry diagnostics to a deterministic measurement-noise scale.""" + + if strength < 0.0: + raise ValueError("uncertainty strength must be non-negative") + components = np.stack(( + 1.0 - np.clip(confidence, 0.0, 1.0), + 1.0 - np.clip(inlier_ratio, 0.0, 1.0), + np.clip(residual_scale_m / 0.02, 0.0, 2.0) / 2.0, + 1.0 - np.clip(valid_fraction, 0.0, 1.0), + 1.0 - np.clip(conditioning_quality, 0.0, 1.0), + ), axis=-1) + return np.clip(1.0 + strength * components.mean(axis=-1), 1.0, 5.0) + + +def causal_constant_velocity_kalman( + measurement_m: np.ndarray, + *, + frame_id: np.ndarray, + segment_id: np.ndarray | None = None, + valid: np.ndarray, + measurement_available: np.ndarray, + process_sigma_m_per_frame2: float, + measurement_sigma_m: float, + uncertainty_multiplier: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray]: + """Filter `[time,hand]` z measurements without crossing invalid/discontinuous frames.""" + + measurement = np.asarray(measurement_m, dtype=np.float64) + frame_id = np.asarray(frame_id, dtype=np.int64) + segment = ( + np.zeros(len(measurement), dtype=np.int64) + if segment_id is None else np.asarray(segment_id) + ) + valid = np.asarray(valid, dtype=bool) + available = np.asarray(measurement_available, dtype=bool) + if measurement.ndim != 2 or measurement.shape[1] != 2: + raise ValueError("measurement_m must have shape [time,2]") + if ( + frame_id.shape != (len(measurement),) + or segment.shape != (len(measurement),) + or valid.shape != (len(measurement),) + ): + raise ValueError("frame_id, segment_id, and valid must have shape [time]") + if available.shape != measurement.shape: + raise ValueError("measurement_available must match measurement_m") + if process_sigma_m_per_frame2 <= 0.0 or measurement_sigma_m <= 0.0: + raise ValueError("Kalman noise scales must be positive") + if uncertainty_multiplier is None: + multiplier = np.ones_like(measurement) + else: + multiplier = np.asarray(uncertainty_multiplier, dtype=np.float64) + if multiplier.shape != measurement.shape or np.any(multiplier < 1.0): + raise ValueError("uncertainty_multiplier must match measurements and be >=1") + + output = measurement.copy() + variance = np.full_like(measurement, np.nan) + transition = np.asarray(((1.0, 1.0), (0.0, 1.0)), dtype=np.float64) + observation = np.asarray((1.0, 0.0), dtype=np.float64) + q = process_sigma_m_per_frame2**2 * np.asarray( + ((0.25, 0.5), (0.5, 1.0)), dtype=np.float64, + ) + + for hand in range(2): + initialized = False + state = np.zeros(2, dtype=np.float64) + covariance = np.eye(2, dtype=np.float64) + previous_frame = -1 + previous_segment: object = None + for index in range(len(measurement)): + contiguous = ( + initialized + and frame_id[index] == previous_frame + 1 + and segment[index] == previous_segment + ) + if not valid[index] or not contiguous: + initialized = False + if not valid[index]: + output[index, hand] = measurement[index, hand] + previous_frame = int(frame_id[index]) + previous_segment = segment[index] + continue + if not initialized: + if not available[index, hand] or not np.isfinite(measurement[index, hand]): + output[index, hand] = measurement[index, hand] + previous_frame = int(frame_id[index]) + previous_segment = segment[index] + continue + state[:] = (measurement[index, hand], 0.0) + initial_variance = (measurement_sigma_m * multiplier[index, hand]) ** 2 + covariance = np.diag((initial_variance, 4.0 * initial_variance)) + initialized = True + else: + state = transition @ state + covariance = transition @ covariance @ transition.T + q + if available[index, hand] and np.isfinite(measurement[index, hand]): + r = (measurement_sigma_m * multiplier[index, hand]) ** 2 + innovation = measurement[index, hand] - observation @ state + innovation_variance = float(observation @ covariance @ observation + r) + gain = covariance @ observation / innovation_variance + state = state + gain * innovation + covariance = (np.eye(2) - np.outer(gain, observation)) @ covariance + output[index, hand] = state[0] + variance[index, hand] = covariance[0, 0] + previous_frame = int(frame_id[index]) + previous_segment = segment[index] + return output.astype(np.float32), variance.astype(np.float32) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/harm_risk.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/harm_risk.py new file mode 100644 index 0000000000000000000000000000000000000000..9fc2a46bd4f7c4cdcee6de1fbb10dfb6b37add31 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/harm_risk.py @@ -0,0 +1,71 @@ +"""Predicted-only feature contract for Phase 6 harmful-correction risk.""" + +from __future__ import annotations + +import numpy as np + + +HARM_RISK_FEATURE_NAMES = ( + "calibrated_delta_z_m", "abs_calibrated_delta_z_m", + "raw_delta_z_m", "abs_raw_delta_z_m", "raw_calibrated_disagreement_m", + "existing_confidence", "alignment_available", "raw_alignment_available", + "valid_support_count", "projected_support_count", "inlier_ratio", + "residual_scale_m", "valid_fraction", "foreground_fraction", + "background_fraction", "depth_discontinuity_m", "conditioning_quality", + "silhouette_overlap_fraction", "coarse_hand_scale_px", + "coarse_direct_mano_consistency_px", "coarse_z_m", "coarse_ray_x", + "coarse_ray_y", "coarse_wrist_velocity_norm_m_per_frame", + "predicted_depth_order", "side_right", +) + + +def harm_risk_features( + *, + calibrated_delta_z_m: np.ndarray, + raw_delta_z_m: np.ndarray, + confidence: np.ndarray, + alignment_available: np.ndarray, + raw_alignment_available: np.ndarray, + valid_support_count: np.ndarray, + projected_support_count: np.ndarray, + inlier_ratio: np.ndarray, + residual_scale_m: np.ndarray, + valid_fraction: np.ndarray, + foreground_fraction: np.ndarray, + background_fraction: np.ndarray, + depth_discontinuity_m: np.ndarray, + conditioning_quality: np.ndarray, + silhouette_overlap_fraction: np.ndarray, + coarse_hand_scale_px: np.ndarray, + coarse_direct_mano_consistency_px: np.ndarray, + coarse_wrist_translation: np.ndarray, + coarse_wrist_velocity_m_per_frame: np.ndarray, + predicted_depth_order: np.ndarray, +) -> np.ndarray: + calibrated = np.asarray(calibrated_delta_z_m, dtype=np.float64) + raw = np.asarray(raw_delta_z_m, dtype=np.float64) + if calibrated.ndim != 2 or calibrated.shape[1] != 2 or raw.shape != calibrated.shape: + raise ValueError("risk delta-z arrays must have shape [time,2]") + time = len(calibrated) + overlap = np.broadcast_to( + np.asarray(silhouette_overlap_fraction)[:, None], (time, 2), + ) + depth_order = np.broadcast_to( + np.asarray(predicted_depth_order)[:, None], (time, 2), + ) + side = np.broadcast_to(np.asarray((0.0, 1.0)), (time, 2)) + translation = np.asarray(coarse_wrist_translation, dtype=np.float64) + z = np.maximum(translation[..., 2], 1e-6) + velocity_norm = np.linalg.norm(coarse_wrist_velocity_m_per_frame, axis=-1) + values = ( + calibrated, np.abs(calibrated), raw, np.abs(raw), np.abs(raw - calibrated), + confidence, alignment_available, raw_alignment_available, + valid_support_count, projected_support_count, inlier_ratio, + residual_scale_m, valid_fraction, foreground_fraction, + background_fraction, depth_discontinuity_m, conditioning_quality, + overlap, coarse_hand_scale_px, coarse_direct_mano_consistency_px, + translation[..., 2], translation[..., 0] / z, translation[..., 1] / z, + velocity_norm, depth_order, side, + ) + features = np.stack(values, axis=-1).astype(np.float32) + return np.nan_to_num(features, nan=0.0, posinf=1e6, neginf=-1e6) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/local_depth.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/local_depth.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7ba9904db72607171a18a6c7415efd2a09ffdf --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/local_depth.py @@ -0,0 +1,231 @@ +"""Oracle local-depth feature extraction and bounded wrist-z residual models.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +import torch +from torch import nn + + +ANCHOR_JOINTS = (0, 4, 5, 8, 9, 12, 13, 16, 17, 20) +WINDOW_RADII = (3, 7, 15) +BBOX_MARGINS = (0.10, 0.30, 0.60) +DEPTH_STAT_NAMES = ( + "valid_fraction", + "q10_m", + "q25_m", + "q50_m", + "q75_m", + "q90_m", + "iqr_m", + "discontinuity_m", +) + + +def _depth_statistics(depth_m: np.ndarray, valid: np.ndarray) -> np.ndarray: + mask = np.asarray(valid, dtype=bool) & np.isfinite(depth_m) & (depth_m > 0.0) + valid_fraction = float(mask.mean()) if mask.size else 0.0 + values = np.asarray(depth_m, dtype=np.float64)[mask] + if not values.size: + return np.asarray([valid_fraction, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], dtype=np.float32) + q10, q25, q50, q75, q90 = np.percentile(values, (10, 25, 50, 75, 90)) + return np.asarray([ + valid_fraction, + q10, + q25, + q50, + q75, + q90, + q75 - q25, + q90 - q10, + ], dtype=np.float32) + + +def _clipped_region( + center_xy: np.ndarray, + half_size_xy: np.ndarray, + image_hw: tuple[int, int], +) -> tuple[slice, slice]: + height, width = image_hw + x0 = max(0, int(np.floor(float(center_xy[0] - half_size_xy[0])))) + y0 = max(0, int(np.floor(float(center_xy[1] - half_size_xy[1])))) + x1 = min(width, int(np.ceil(float(center_xy[0] + half_size_xy[0]))) + 1) + y1 = min(height, int(np.ceil(float(center_xy[1] + half_size_xy[1]))) + 1) + return slice(y0, max(y0, y1)), slice(x0, max(x0, x1)) + + +def _geometry_from_median( + center_xy: np.ndarray, + median_depth_m: float, + K: np.ndarray, +) -> np.ndarray: + if median_depth_m <= 0.0 or not np.isfinite(median_depth_m): + return np.zeros(5, dtype=np.float32) + x_ray = (float(center_xy[0]) - float(K[0, 2])) / float(K[0, 0]) + y_ray = (float(center_xy[1]) - float(K[1, 2])) / float(K[1, 1]) + return np.asarray([ + x_ray * median_depth_m, + y_ray * median_depth_m, + median_depth_m, + np.log(max(median_depth_m, 1e-6)), + 1.0, + ], dtype=np.float32) + + +@dataclass(frozen=True) +class OracleLocalDepthFeatures: + control: np.ndarray + local: np.ndarray + control_names: tuple[str, ...] + local_names: tuple[str, ...] + local_valid_fraction: float + local_depth_discontinuity_m: float + + +def oracle_local_depth_features( + depth_m: np.ndarray, + depth_valid: np.ndarray, + joints_2d_raw: np.ndarray, + K_raw: np.ndarray, + coarse_translation_m: np.ndarray, + side_index: int, +) -> OracleLocalDepthFeatures: + """Extract oracle-location features without using GT wrist depth as input.""" + + depth_m = np.asarray(depth_m, dtype=np.float32) + depth_valid = np.asarray(depth_valid, dtype=bool) + joints = np.asarray(joints_2d_raw, dtype=np.float32) + K = np.asarray(K_raw, dtype=np.float32) + coarse = np.asarray(coarse_translation_m, dtype=np.float32) + if depth_m.ndim != 2 or depth_valid.shape != depth_m.shape: + raise ValueError("raw metric depth and validity must be aligned HxW arrays") + if joints.shape != (21, 2) or K.shape != (3, 3) or coarse.shape != (3,): + raise ValueError("unexpected joint/K/coarse feature shape") + if side_index not in (0, 1): + raise ValueError("side_index must be 0 for left or 1 for right") + + height, width = depth_m.shape + finite = np.isfinite(joints).all(axis=-1) + if finite.any(): + minimum = joints[finite].min(axis=0) + maximum = joints[finite].max(axis=0) + center = 0.5 * (minimum + maximum) + extent = np.maximum(maximum - minimum, 1.0) + else: + center = np.asarray([width / 2.0, height / 2.0], dtype=np.float32) + extent = np.ones(2, dtype=np.float32) + + control_names = ( + "coarse_x_m", + "coarse_y_m", + "coarse_z_m", + "log_coarse_z", + "bbox_center_u_norm", + "bbox_center_v_norm", + "bbox_width_norm", + "bbox_height_norm", + "fx_norm", + "fy_norm", + "cx_norm", + "cy_norm", + "side_left", + "side_right", + ) + control = np.asarray([ + coarse[0], + coarse[1], + coarse[2], + np.log(max(float(coarse[2]), 1e-6)), + center[0] / width, + center[1] / height, + extent[0] / width, + extent[1] / height, + K[0, 0] / width, + K[1, 1] / height, + K[0, 2] / width, + K[1, 2] / height, + float(side_index == 0), + float(side_index == 1), + ], dtype=np.float32) + + local_values: list[float] = [] + local_names: list[str] = [] + anchor_validities: list[float] = [] + anchor_discontinuities: list[float] = [] + for joint_index in ANCHOR_JOINTS: + joint_center = joints[joint_index] if finite[joint_index] else center + for radius in WINDOW_RADII: + y_slice, x_slice = _clipped_region( + joint_center, + np.asarray([radius, radius], dtype=np.float32), + (height, width), + ) + statistics = _depth_statistics( + depth_m[y_slice, x_slice], depth_valid[y_slice, x_slice] + ) + geometry = _geometry_from_median(joint_center, float(statistics[3]), K) + prefix = f"joint{joint_index:02d}_r{radius}" + local_values.extend(statistics.tolist()) + local_names.extend(f"{prefix}_{name}" for name in DEPTH_STAT_NAMES) + local_values.extend(geometry.tolist()) + local_names.extend( + f"{prefix}_{name}" for name in ("median_x_m", "median_y_m", "median_z_m", "log_median_z", "median_valid") + ) + local_values.append(float(statistics[3] - coarse[2]) if statistics[0] > 0 else 0.0) + local_names.append(f"{prefix}_median_minus_coarse_z_m") + anchor_validities.append(float(statistics[0])) + anchor_discontinuities.append(float(statistics[7])) + + for margin in BBOX_MARGINS: + half_size = np.maximum(extent * (0.5 + margin), 4.0) + y_slice, x_slice = _clipped_region(center, half_size, (height, width)) + statistics = _depth_statistics(depth_m[y_slice, x_slice], depth_valid[y_slice, x_slice]) + geometry = _geometry_from_median(center, float(statistics[3]), K) + prefix = f"bbox_m{int(round(margin * 100)):02d}" + local_values.extend(statistics.tolist()) + local_names.extend(f"{prefix}_{name}" for name in DEPTH_STAT_NAMES) + local_values.extend(geometry.tolist()) + local_names.extend( + f"{prefix}_{name}" for name in ("median_x_m", "median_y_m", "median_z_m", "log_median_z", "median_valid") + ) + local_values.append(float(statistics[3] - coarse[2]) if statistics[0] > 0 else 0.0) + local_names.append(f"{prefix}_median_minus_coarse_z_m") + + local_array = np.asarray(local_values, dtype=np.float32) + if not np.isfinite(control).all() or not np.isfinite(local_array).all(): + raise ValueError("oracle local-depth feature extraction produced non-finite values") + return OracleLocalDepthFeatures( + control=control, + local=np.concatenate((control, local_array)).astype(np.float32), + control_names=control_names, + local_names=control_names + tuple(local_names), + local_valid_fraction=float(np.mean(anchor_validities)), + local_depth_discontinuity_m=float(np.mean(anchor_discontinuities)), + ) + + +class BoundedZResidualRegressor(nn.Module): + """Small zero-initialized residual MLP for an oracle diagnostic.""" + + def __init__( + self, + input_dim: int, + hidden_dim: int = 128, + max_residual_m: float = 0.15, + ) -> None: + super().__init__() + self.max_residual_m = float(max_residual_m) + self.network = nn.Sequential( + nn.Linear(input_dim, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, 1), + ) + nn.init.zeros_(self.network[-1].weight) + nn.init.zeros_(self.network[-1].bias) + + def forward(self, features: torch.Tensor) -> torch.Tensor: + return self.max_residual_m * torch.tanh(self.network(features).squeeze(-1)) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/metric_alignment.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/metric_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..918bb5bbce077ed9b0fdd77cdc2c0911ee799004 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/metric_alignment.py @@ -0,0 +1,333 @@ +"""Predicted-MANO to observed-depth alignment for deployable wrist-z correction.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass + +import cv2 +import numpy as np + +from foundation_hand.geometry.camera import project_points + + +@dataclass(frozen=True) +class AlignmentDiagnostics: + delta_z_m: float + applied: bool + valid_support_count: int + projected_support_count: int + inlier_ratio: float + residual_scale_m: float + valid_fraction: float + foreground_fraction: float + background_fraction: float + depth_discontinuity_m: float + conditioning_quality: float + + def as_dict(self) -> dict[str, float | int | bool]: + return asdict(self) + + +@dataclass(frozen=True) +class SurfaceSamples: + projected_vertices_px: np.ndarray + predicted_depth_m: np.ndarray + observed_depth_m: np.ndarray + visible_vertex: np.ndarray + sample_valid: np.ndarray + local_discontinuity_m: np.ndarray + silhouette_packed: np.ndarray + silhouette_hw: tuple[int, int] + + +def _empty_diagnostics(projected: int = 0) -> AlignmentDiagnostics: + return AlignmentDiagnostics( + delta_z_m=0.0, + applied=False, + valid_support_count=0, + projected_support_count=int(projected), + inlier_ratio=0.0, + residual_scale_m=0.0, + valid_fraction=0.0, + foreground_fraction=0.0, + background_fraction=0.0, + depth_discontinuity_m=0.0, + conditioning_quality=0.0, + ) + + +def robust_location_irls( + residuals_m: np.ndarray, + *, + base_weights: np.ndarray | None = None, + huber_k: float = 1.345, + iterations: int = 8, + minimum_scale_m: float = 0.003, + maximum_delta_m: float = 0.12, +) -> tuple[float, float, float]: + """Estimate a bounded common translation with MAD-scaled Huber IRLS.""" + + residuals = np.asarray(residuals_m, dtype=np.float64).reshape(-1) + finite = np.isfinite(residuals) + residuals = residuals[finite] + if not residuals.size: + return 0.0, 0.0, 0.0 + if base_weights is None: + weights = np.ones_like(residuals) + else: + input_weights = np.asarray(base_weights, dtype=np.float64).reshape(-1)[finite] + weights = np.clip(input_weights, 0.0, None) + if not np.any(weights > 0.0): + return 0.0, 0.0, 0.0 + + location = float(np.median(residuals)) + scale = max( + minimum_scale_m, + 1.4826 * float(np.median(np.abs(residuals - location))), + ) + for _ in range(iterations): + standardized = np.abs(residuals - location) / scale + robust = np.ones_like(standardized) + outside = standardized > huber_k + robust[outside] = huber_k / standardized[outside] + combined = weights * robust + if combined.sum() <= 1e-12: + return 0.0, scale, 0.0 + updated = float(np.sum(combined * residuals) / np.sum(combined)) + if abs(updated - location) < 1e-7: + location = updated + break + location = updated + location = float(np.clip(location, -maximum_delta_m, maximum_delta_m)) + inlier_ratio = float(np.mean(np.abs(residuals - location) <= huber_k * scale)) + return location, scale, inlier_ratio + + +def _visible_vertex_mask( + pixels: np.ndarray, + depth_m: np.ndarray, + image_hw: tuple[int, int], + cell_size: int, +) -> np.ndarray: + height, width = image_hw + finite = np.isfinite(pixels).all(axis=-1) & np.isfinite(depth_m) & (depth_m > 0.0) + inside = finite & (pixels[:, 0] >= 0) & (pixels[:, 0] < width) & ( + pixels[:, 1] >= 0 + ) & (pixels[:, 1] < height) + visible = np.zeros(len(pixels), dtype=bool) + indices = np.where(inside)[0] + if not len(indices): + return visible + cells_x = np.floor(pixels[indices, 0] / cell_size).astype(np.int64) + cells_y = np.floor(pixels[indices, 1] / cell_size).astype(np.int64) + cell_width = (width + cell_size - 1) // cell_size + cell_ids = cells_y * cell_width + cells_x + order = np.lexsort((depth_m[indices], cell_ids)) + sorted_ids = cell_ids[order] + first = np.r_[True, sorted_ids[1:] != sorted_ids[:-1]] + visible[indices[order[first]]] = True + return visible + + +def _sample_depth_regions( + depth_m: np.ndarray, + depth_valid: np.ndarray, + pixels: np.ndarray, + radius: int, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + height, width = depth_m.shape + count = len(pixels) + observed = np.full(count, np.nan, dtype=np.float32) + valid = np.zeros(count, dtype=bool) + discontinuity = np.full(count, np.nan, dtype=np.float32) + finite_pixels = np.isfinite(pixels).all(axis=-1) + centers = np.rint(np.where(finite_pixels[:, None], pixels, 0.0)).astype(np.int64) + offsets = np.arange(-radius, radius + 1, dtype=np.int64) + offset_y, offset_x = np.meshgrid(offsets, offsets, indexing="ij") + sample_x = centers[:, 0, None] + offset_x.reshape(1, -1) + sample_y = centers[:, 1, None] + offset_y.reshape(1, -1) + inside = finite_pixels[:, None] & (sample_x >= 0) & (sample_x < width) & ( + sample_y >= 0 + ) & (sample_y < height) + clipped_x = np.clip(sample_x, 0, width - 1) + clipped_y = np.clip(sample_y, 0, height - 1) + values = depth_m[clipped_y, clipped_x] + sample_valid = inside & depth_valid[clipped_y, clipped_x] & np.isfinite(values) & ( + values > 0.0 + ) + eligible = sample_valid.any(axis=1) + if np.any(eligible): + eligible_valid = sample_valid[eligible] + sorted_values = np.sort( + np.where(eligible_valid, values[eligible], np.inf), axis=1, + ) + counts = eligible_valid.sum(axis=1) + + def row_percentile(quantile: float) -> np.ndarray: + position = (counts - 1) * quantile + lower = np.floor(position).astype(np.int64) + upper = np.ceil(position).astype(np.int64) + fraction = position - lower + lower_value = np.take_along_axis(sorted_values, lower[:, None], axis=1)[:, 0] + upper_value = np.take_along_axis(sorted_values, upper[:, None], axis=1)[:, 0] + difference = upper_value - lower_value + interpolated = lower_value + difference * fraction + upper_stable = fraction >= 0.5 + interpolated[upper_stable] = ( + upper_value[upper_stable] + - difference[upper_stable] * (1.0 - fraction[upper_stable]) + ) + return interpolated + + q10, q50, q90 = (row_percentile(quantile) for quantile in (0.1, 0.5, 0.9)) + observed[eligible] = q50.astype(np.float32) + discontinuity[eligible] = (q90 - q10).astype(np.float32) + valid[eligible] = True + return observed, valid, discontinuity + + +def conservative_silhouette( + projected_vertices_px: np.ndarray, + visible_vertex: np.ndarray, + image_hw: tuple[int, int], + *, + downsample: int = 4, +) -> tuple[np.ndarray, tuple[int, int]]: + """Return a packed conservative projected-hull mask for bank/audit storage.""" + + height, width = image_hw + output_hw = ( + (height + downsample - 1) // downsample, + (width + downsample - 1) // downsample, + ) + mask = np.zeros(output_hw, dtype=np.uint8) + points = np.asarray(projected_vertices_px, dtype=np.float32)[visible_vertex] + points = points[np.isfinite(points).all(axis=-1)] / float(downsample) + if len(points) >= 3: + hull = cv2.convexHull(np.rint(points).astype(np.int32)) + cv2.fillConvexPoly(mask, hull, 1) + packed = np.packbits(mask.reshape(-1), bitorder="little") + return packed, output_hw + + +def sample_predicted_surface( + vertices_camera_m: np.ndarray, + K: np.ndarray, + depth_m: np.ndarray, + depth_valid: np.ndarray, + *, + cell_size: int = 4, + sample_radius: int = 2, + silhouette_downsample: int = 4, +) -> SurfaceSamples: + vertices = np.asarray(vertices_camera_m, dtype=np.float32) + depth = np.asarray(depth_m, dtype=np.float32) + valid = np.asarray(depth_valid, dtype=bool) + matrix = np.asarray(K, dtype=np.float32) + if vertices.ndim != 2 or vertices.shape[1] != 3: + raise ValueError("vertices must have shape [V,3]") + if depth.ndim != 2 or valid.shape != depth.shape or matrix.shape != (3, 3): + raise ValueError("depth, validity, or K shape mismatch") + pixels, positive = project_points(vertices, matrix) + visible = _visible_vertex_mask(pixels, vertices[:, 2], depth.shape, cell_size) + visible &= positive + observed, sample_valid, discontinuity = _sample_depth_regions( + depth, valid, pixels, sample_radius, + ) + sample_valid &= visible + packed, silhouette_hw = conservative_silhouette( + pixels, visible, depth.shape, downsample=silhouette_downsample, + ) + return SurfaceSamples( + projected_vertices_px=pixels.astype(np.float32), + predicted_depth_m=vertices[:, 2].astype(np.float32), + observed_depth_m=observed, + visible_vertex=visible, + sample_valid=sample_valid, + local_discontinuity_m=discontinuity, + silhouette_packed=packed, + silhouette_hw=silhouette_hw, + ) + + +def solve_wrist_delta_z( + samples: SurfaceSamples, + *, + minimum_support: int = 20, + maximum_raw_residual_m: float = 0.15, + discontinuity_scale_m: float = 0.04, + maximum_delta_m: float = 0.12, +) -> AlignmentDiagnostics: + residuals = samples.observed_depth_m - samples.predicted_depth_m + projected_count = int(samples.visible_vertex.sum()) + candidate = samples.sample_valid & np.isfinite(residuals) & ( + np.abs(residuals) <= maximum_raw_residual_m + ) + count = int(candidate.sum()) + if count < minimum_support: + return _empty_diagnostics(projected_count) + values = residuals[candidate].astype(np.float64) + discontinuity = samples.local_discontinuity_m[candidate].astype(np.float64) + weights = 1.0 / (1.0 + np.square(discontinuity / discontinuity_scale_m)) + delta, scale, inlier_ratio = robust_location_irls( + values, base_weights=weights, maximum_delta_m=maximum_delta_m, + ) + foreground_fraction = float(np.mean(values < delta - max(0.02, 2.5 * scale))) + background_fraction = float(np.mean(values > delta + max(0.03, 2.5 * scale))) + valid_fraction = count / max(projected_count, 1) + support_score = min(1.0, count / 80.0) + scale_score = float(np.exp(-scale / 0.025)) + contamination_score = max(0.0, 1.0 - foreground_fraction - background_fraction) + quality = float(np.clip( + support_score * inlier_ratio * scale_score * contamination_score, + 0.0, 1.0, + )) + return AlignmentDiagnostics( + delta_z_m=delta, + applied=True, + valid_support_count=count, + projected_support_count=projected_count, + inlier_ratio=inlier_ratio, + residual_scale_m=scale, + valid_fraction=valid_fraction, + foreground_fraction=foreground_fraction, + background_fraction=background_fraction, + depth_discontinuity_m=float(np.nanmedian(discontinuity)), + conditioning_quality=quality, + ) + + +def align_wrist_z( + vertices_camera_m: np.ndarray, + K: np.ndarray | None, + depth_m: np.ndarray | None, + depth_valid: np.ndarray | None, + *, + minimum_support: int = 20, +) -> tuple[AlignmentDiagnostics, SurfaceSamples | None]: + if K is None or depth_m is None or depth_valid is None: + return _empty_diagnostics(), None + matrix = np.asarray(K) + if matrix.shape != (3, 3) or not np.isfinite(matrix).all() or min( + float(matrix[0, 0]), float(matrix[1, 1]) + ) <= 0.0: + return _empty_diagnostics(), None + samples = sample_predicted_surface( + vertices_camera_m, matrix, depth_m, depth_valid, + ) + return solve_wrist_delta_z(samples, minimum_support=minimum_support), samples + + +def apply_translation_delta_z( + translation_m: np.ndarray, + joints_m: np.ndarray, + vertices_m: np.ndarray, + delta_z_m: float, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + translation = np.asarray(translation_m, dtype=np.float32).copy() + joints = np.asarray(joints_m, dtype=np.float32).copy() + vertices = np.asarray(vertices_m, dtype=np.float32).copy() + translation[..., 2] += float(delta_z_m) + joints[..., 2] += float(delta_z_m) + vertices[..., 2] += float(delta_z_m) + return translation, joints, vertices diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/metrics.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..2f904f95c1ee76ed1b12b0debaa6126225acc9c9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/metrics.py @@ -0,0 +1,100 @@ +"""Distribution summaries and take-level uncertainty estimates.""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence + +import numpy as np + + +PERCENTILES = (50, 90, 95, 99) + + +def finite_array(values: Iterable[float | int | None]) -> np.ndarray: + array = np.asarray([value for value in values if value is not None], dtype=np.float64) + return array[np.isfinite(array)] + + +def distribution_summary(values: Iterable[float | int | None]) -> dict[str, float | int | None]: + """Return central statistics, fixed tail percentiles, and upper-tail CVaR.""" + + array = finite_array(values) + if array.size == 0: + return { + "count": 0, + "mean": None, + "std": None, + **{f"p{percentile}": None for percentile in PERCENTILES}, + "cvar95": None, + } + p95 = float(np.percentile(array, 95)) + return { + "count": int(array.size), + "mean": float(array.mean()), + "std": float(array.std(ddof=0)), + **{ + f"p{percentile}": float(np.percentile(array, percentile)) + for percentile in PERCENTILES + }, + "cvar95": float(array[array >= p95].mean()), + } + + +def bootstrap_take_means( + rows: Sequence[Mapping[str, object]], + metric_names: Sequence[str], + *, + take_key: str = "take", + seed: int = 20260716, + samples: int = 10_000, +) -> list[dict[str, float | int | str | None]]: + """Bootstrap equally weighted take means and return percentile 95% CIs. + + Frame/hand observations are first averaged within each take. Resampling then + operates on takes, which avoids treating adjacent video frames as independent. + """ + + if samples <= 0: + raise ValueError("samples must be positive") + grouped: dict[str, dict[str, list[float]]] = defaultdict(lambda: defaultdict(list)) + for row in rows: + take = str(row[take_key]) + for metric in metric_names: + value = row.get(metric) + if value is None: + continue + number = float(value) + if np.isfinite(number): + grouped[take][metric].append(number) + + rng = np.random.default_rng(seed) + output: list[dict[str, float | int | str | None]] = [] + for metric in metric_names: + take_values = np.asarray( + [np.mean(items[metric]) for items in grouped.values() if items.get(metric)], + dtype=np.float64, + ) + if take_values.size == 0: + output.append({ + "metric": metric, + "take_count": 0, + "take_mean": None, + "ci95_low": None, + "ci95_high": None, + "bootstrap_samples": samples, + "seed": seed, + }) + continue + indices = rng.integers(0, take_values.size, size=(samples, take_values.size)) + bootstrap = take_values[indices].mean(axis=1) + output.append({ + "metric": metric, + "take_count": int(take_values.size), + "take_mean": float(take_values.mean()), + "ci95_low": float(np.percentile(bootstrap, 2.5)), + "ci95_high": float(np.percentile(bootstrap, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/mixed_projection.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..ce3762b44d153f24c7d08a7639fb51bb788602e9 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/mixed_projection.py @@ -0,0 +1,248 @@ +"""Predicted-anchor mixed-projection translation assembly.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + + +@dataclass(frozen=True) +class MixedProjectionBatchResult: + translation_m: np.ndarray + support_count: np.ndarray + residual_scale_px: np.ndarray + conditioning: np.ndarray + inlier_ratio: np.ndarray + uncertainty_xy_m: np.ndarray + failure_reason: np.ndarray + + +def coarse_wrist_ray_translation( + coarse_translation_m: np.ndarray, + refined_z_m: np.ndarray, + *, + minimum_depth_m: float = 0.05, +) -> np.ndarray: + """Change z while preserving the coarse camera ray.""" + + coarse = np.asarray(coarse_translation_m, dtype=np.float64) + z = np.asarray(refined_z_m, dtype=np.float64) + if coarse.shape[:-1] != z.shape or coarse.shape[-1] != 3: + raise ValueError("coarse translation and refined z shapes differ") + output = coarse.copy() + valid = ( + np.isfinite(coarse).all(axis=-1) + & np.isfinite(z) + & (coarse[..., 2] > minimum_depth_m) + & (z > minimum_depth_m) + ) + ratio = np.ones_like(z) + ratio[valid] = z[valid] / coarse[..., 2][valid] + output[..., :2] *= ratio[..., None] + output[..., 2] = np.where(np.isfinite(z), z, coarse[..., 2]) + return output + + +def direct_wrist_ray_translation( + anchors_px: np.ndarray, + intrinsics: np.ndarray, + refined_z_m: np.ndarray, + fallback_translation_m: np.ndarray, + *, + minimum_depth_m: float = 0.05, +) -> tuple[np.ndarray, np.ndarray]: + """Back-project the predicted direct-2D wrist at the selected depth.""" + + anchors = np.asarray(anchors_px, dtype=np.float64) + K = np.asarray(intrinsics, dtype=np.float64) + z = np.asarray(refined_z_m, dtype=np.float64) + fallback = np.asarray(fallback_translation_m, dtype=np.float64) + if anchors.shape[-2:] != (21, 2) or K.shape[-2:] != (3, 3): + raise ValueError("unexpected anchor or K shape") + output = fallback.copy() + wrist = anchors[..., 0, :] + fx, fy = K[..., 0, 0], K[..., 1, 1] + cx, cy = K[..., 0, 2], K[..., 1, 2] + valid = ( + np.isfinite(wrist).all(axis=-1) + & np.isfinite(K).all(axis=(-2, -1)) + & np.isfinite(z) + & (fx > 1e-8) + & (fy > 1e-8) + & (z > minimum_depth_m) + ) + output[..., 0] = np.where(valid, (wrist[..., 0] - cx) * z / fx, output[..., 0]) + output[..., 1] = np.where(valid, (wrist[..., 1] - cy) * z / fy, output[..., 1]) + output[..., 2] = np.where(np.isfinite(z), z, output[..., 2]) + return output, valid + + +def solve_mixed_projection_batch( + root_relative_joints_m: np.ndarray, + anchors_px: np.ndarray, + intrinsics: np.ndarray, + refined_z_m: np.ndarray, + fallback_translation_m: np.ndarray, + *, + image_hw: tuple[int, int], + minimum_support: int = 8, + robust_huber_delta_px: float | None = None, + irls_iterations: int = 5, + minimum_joint_depth_m: float = 0.05, + denominator_epsilon: float = 1e-10, +) -> MixedProjectionBatchResult: + """Solve tx/ty from predicted 2D anchors and MANO root-relative joints. + + Every solve mask is derived from predicted quantities. Failed solves keep + the supplied fallback x/y and the selected finite z. + """ + + joints = np.asarray(root_relative_joints_m, dtype=np.float64) + anchors = np.asarray(anchors_px, dtype=np.float64) + K = np.asarray(intrinsics, dtype=np.float64) + z = np.asarray(refined_z_m, dtype=np.float64) + fallback = np.asarray(fallback_translation_m, dtype=np.float64) + if joints.ndim != 3 or joints.shape[1:] != (21, 3): + raise ValueError(f"expected joints [N,21,3], got {joints.shape}") + count = joints.shape[0] + expected = { + "anchors": (count, 21, 2), + "intrinsics": (count, 3, 3), + "refined z": (count,), + "fallback": (count, 3), + } + for name, shape in expected.items(): + value = {"anchors": anchors, "intrinsics": K, "refined z": z, "fallback": fallback}[name] + if value.shape != shape: + raise ValueError(f"expected {name} {shape}, got {value.shape}") + if not 1 <= minimum_support <= 21: + raise ValueError("minimum_support must be in [1,21]") + if robust_huber_delta_px is not None and robust_huber_delta_px <= 0.0: + raise ValueError("Huber delta must be positive") + if irls_iterations < 1: + raise ValueError("IRLS iterations must be positive") + height, width = image_hw + if height <= 0 or width <= 0: + raise ValueError("image dimensions must be positive") + + fx, fy = K[:, 0, 0], K[:, 1, 1] + cx, cy = K[:, 0, 2], K[:, 1, 2] + joint_z = joints[..., 2] + z[:, None] + finite_k = np.isfinite(K).all(axis=(1, 2)) & (fx > 1e-8) & (fy > 1e-8) + finite_joint = np.isfinite(joints).all(axis=-1) + finite_anchor = np.isfinite(anchors).all(axis=-1) + in_frame = ( + (anchors[..., 0] >= 0.0) + & (anchors[..., 0] <= width - 1.0) + & (anchors[..., 1] >= 0.0) + & (anchors[..., 1] <= height - 1.0) + ) + mask = ( + finite_k[:, None] + & np.isfinite(z)[:, None] + & (joint_z > minimum_joint_depth_m) + & finite_joint + & finite_anchor + & in_frame + ) + support = mask.sum(axis=1).astype(np.int64) + + safe_joint_z = np.where(mask, joint_z, 1.0) + ax = fx[:, None] / safe_joint_z + ay = fy[:, None] / safe_joint_z + bx = anchors[..., 0] - cx[:, None] - fx[:, None] * joints[..., 0] / safe_joint_z + by = anchors[..., 1] - cy[:, None] - fy[:, None] * joints[..., 1] / safe_joint_z + ax = np.where(mask, ax, 0.0) + ay = np.where(mask, ay, 0.0) + bx = np.where(mask, bx, 0.0) + by = np.where(mask, by, 0.0) + + weights = mask.astype(np.float64) + + def solve(current_weights: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + denom_x = np.sum(current_weights * np.square(ax), axis=1) + denom_y = np.sum(current_weights * np.square(ay), axis=1) + tx = np.divide( + np.sum(current_weights * ax * bx, axis=1), denom_x, + out=np.full(count, np.nan), where=denom_x > denominator_epsilon, + ) + ty = np.divide( + np.sum(current_weights * ay * by, axis=1), denom_y, + out=np.full(count, np.nan), where=denom_y > denominator_epsilon, + ) + return tx, ty, denom_x, denom_y + + tx, ty, denom_x, denom_y = solve(weights) + if robust_huber_delta_px is not None: + for _ in range(irls_iterations): + residual = np.sqrt( + np.square(ax * tx[:, None] - bx) + + np.square(ay * ty[:, None] - by) + ) + robust = np.minimum( + 1.0, + robust_huber_delta_px / np.maximum(residual, 1e-12), + ) + weights = np.where(mask, robust, 0.0) + tx, ty, denom_x, denom_y = solve(weights) + + residual = np.sqrt( + np.square(ax * tx[:, None] - bx) + + np.square(ay * ty[:, None] - by) + ) + residual_masked = np.where(mask, residual, np.nan) + residual_scale = np.full(count, np.inf, dtype=np.float64) + has_support = support > 0 + if has_support.any(): + supported_residual = residual_masked[has_support] + median = np.nanmedian(supported_residual, axis=1) + mad = np.nanmedian( + np.abs(supported_residual - median[:, None]), axis=1, + ) + residual_scale[has_support] = 1.4826 * mad + if robust_huber_delta_px is None: + inlier = np.where(mask, True, False) + else: + inlier = mask & (residual <= robust_huber_delta_px) + inlier_ratio = np.divide( + inlier.sum(axis=1), support, + out=np.zeros(count, dtype=np.float64), where=support > 0, + ) + conditioning = np.divide( + np.minimum(denom_x, denom_y), np.maximum(denom_x, denom_y), + out=np.zeros(count, dtype=np.float64), where=np.maximum(denom_x, denom_y) > 0.0, + ) + uncertainty = np.stack(( + np.divide( + residual_scale, np.sqrt(denom_x), out=np.full(count, np.inf), + where=denom_x > denominator_epsilon, + ), + np.divide( + residual_scale, np.sqrt(denom_y), out=np.full(count, np.inf), + where=denom_y > denominator_epsilon, + ), + ), axis=-1) + + sufficient = support >= minimum_support + conditioned = (denom_x > denominator_epsilon) & (denom_y > denominator_epsilon) + finite_solution = np.isfinite(tx) & np.isfinite(ty) + success = finite_k & sufficient & conditioned & finite_solution + output = fallback.copy() + output[:, 0] = np.where(success, tx, output[:, 0]) + output[:, 1] = np.where(success, ty, output[:, 1]) + output[:, 2] = np.where(np.isfinite(z), z, output[:, 2]) + reason = np.full(count, "ok", dtype=" str: + return ACTION_NAMES.get(int(label), f"unknown_{int(label)}") + + +def load_action_label(data_root: str | Path, take: str, frame_id: int) -> int: + path = Path(data_root) / take / "action_label" / f"{int(frame_id):06d}.txt" + values = path.read_text(encoding="utf-8").split() + if len(values) != 1: + raise ValueError(f"expected one H2O action label in {path}, found {len(values)}") + label = int(values[0]) + if label not in ACTION_NAMES: + raise ValueError(f"unknown H2O action label {label} in {path}") + return label + + +def local_depth_statistics( + depth_m: np.ndarray, + depth_valid: np.ndarray, + joints_2d: np.ndarray, + *, + margin_fraction: float = 0.25, + minimum_size_px: int = 24, +) -> dict[str, float | int | None]: + """Summarize aligned metric depth in a conservative GT-joint region. + + This diagnostic intentionally describes visible surface geometry. It does + not equate the local depth median with the camera-space wrist center. + """ + + if depth_m.ndim != 2 or depth_valid.shape != depth_m.shape: + raise ValueError("depth and validity must be aligned HxW arrays") + points = np.asarray(joints_2d, dtype=np.float64) + finite = np.isfinite(points).all(axis=-1) + if not finite.any(): + return { + "roi_x0": None, + "roi_y0": None, + "roi_x1": None, + "roi_y1": None, + "pixel_count": 0, + "valid_fraction": None, + "depth_median_m": None, + "depth_q10_m": None, + "depth_q90_m": None, + "depth_iqr_m": None, + "depth_discontinuity_m": None, + } + points = points[finite] + minimum = points.min(axis=0) + maximum = points.max(axis=0) + center = 0.5 * (minimum + maximum) + extent = np.maximum(maximum - minimum, float(minimum_size_px)) + extent *= 1.0 + 2.0 * float(margin_fraction) + height, width = depth_m.shape + x0 = max(0, int(np.floor(center[0] - extent[0] / 2.0))) + y0 = max(0, int(np.floor(center[1] - extent[1] / 2.0))) + x1 = min(width, int(np.ceil(center[0] + extent[0] / 2.0)) + 1) + y1 = min(height, int(np.ceil(center[1] + extent[1] / 2.0)) + 1) + if x1 <= x0 or y1 <= y0: + return { + "roi_x0": x0, + "roi_y0": y0, + "roi_x1": x1, + "roi_y1": y1, + "pixel_count": 0, + "valid_fraction": None, + "depth_median_m": None, + "depth_q10_m": None, + "depth_q90_m": None, + "depth_iqr_m": None, + "depth_discontinuity_m": None, + } + region_valid = np.asarray(depth_valid[y0:y1, x0:x1], dtype=bool) + region_depth = np.asarray(depth_m[y0:y1, x0:x1], dtype=np.float64) + region_valid &= np.isfinite(region_depth) & (region_depth > 0.0) + values = region_depth[region_valid] + report: dict[str, float | int | None] = { + "roi_x0": x0, + "roi_y0": y0, + "roi_x1": x1, + "roi_y1": y1, + "pixel_count": int(region_valid.size), + "valid_fraction": float(region_valid.mean()), + "depth_median_m": None, + "depth_q10_m": None, + "depth_q90_m": None, + "depth_iqr_m": None, + "depth_discontinuity_m": None, + } + if values.size: + q10, q25, q50, q75, q90 = np.percentile(values, (10, 25, 50, 75, 90)) + report.update({ + "depth_median_m": float(q50), + "depth_q10_m": float(q10), + "depth_q90_m": float(q90), + "depth_iqr_m": float(q75 - q25), + "depth_discontinuity_m": float(q90 - q10), + }) + return report + + +def depth_validity_bucket(value: float | None) -> str | None: + if value is None or not np.isfinite(value): + return None + if value < 0.5: + return "low" + if value < 0.9: + return "partial" + return "high" + + +def bimanual_asymmetry( + hand_sizes_px: Sequence[float | None], + wrist_depths_m: Sequence[float | None], +) -> dict[str, float | str | None]: + if len(hand_sizes_px) != 2 or len(wrist_depths_m) != 2: + raise ValueError("bimanual asymmetry requires left/right pairs") + if any(value is None or not np.isfinite(value) for value in hand_sizes_px): + size_ratio = None + else: + small = max(min(float(hand_sizes_px[0]), float(hand_sizes_px[1])), 1e-6) + size_ratio = max(float(hand_sizes_px[0]), float(hand_sizes_px[1])) / small + if any(value is None or not np.isfinite(value) for value in wrist_depths_m): + depth_gap = None + signed_depth_gap = None + else: + signed_depth_gap = float(wrist_depths_m[1]) - float(wrist_depths_m[0]) + depth_gap = abs(signed_depth_gap) + + if size_ratio is None or depth_gap is None: + bucket = None + elif size_ratio >= 2.0 or depth_gap >= 0.20: + bucket = "strong" + elif size_ratio >= 1.5 or depth_gap >= 0.10: + bucket = "moderate" + else: + bucket = "balanced" + return { + "bimanual_size_ratio": size_ratio, + "bimanual_depth_gap_m": depth_gap, + "right_minus_left_depth_m": signed_depth_gap, + "bimanual_asymmetry_bucket": bucket, + } + + +def summarize_group_metrics( + rows: Sequence[Mapping[str, object]], + metrics: Sequence[str], + group_fields: Sequence[str], +) -> list[dict[str, object]]: + output: list[dict[str, object]] = [] + for group_field in group_fields: + groups: dict[str, list[Mapping[str, object]]] = defaultdict(list) + for row in rows: + value = row.get(group_field) + if value not in (None, ""): + groups[str(value)].append(row) + for group_value, group_rows in sorted(groups.items()): + for side in ("all", "left", "right"): + side_rows = ( + group_rows if side == "all" + else [row for row in group_rows if row.get("side") == side] + ) + for metric in metrics: + summary = distribution_summary(row.get(metric) for row in side_rows) + output.append({ + "group_field": group_field, + "group_value": group_value, + "side": side, + "metric": metric, + **summary, + }) + return output + + +def find_failure_intervals( + rows: Sequence[Mapping[str, object]], + *, + metric: str, + threshold: float, + minimum_frames: int = 3, +) -> list[dict[str, object]]: + """Find contiguous valid-frame intervals above a registered error threshold.""" + + grouped: dict[tuple[str, str], list[Mapping[str, object]]] = defaultdict(list) + for row in rows: + value = row.get(metric) + if row.get("annotation_valid") and value not in (None, ""): + grouped[(str(row["take"]), str(row["side"]))].append(row) + + intervals: list[dict[str, object]] = [] + for (take, side), group in sorted(grouped.items()): + ordered = sorted(group, key=lambda row: int(row["frame_id"])) + current: list[Mapping[str, object]] = [] + + def flush() -> None: + if len(current) < minimum_frames: + current.clear() + return + values = np.asarray([float(row[metric]) for row in current], dtype=np.float64) + intervals.append({ + "take": take, + "side": side, + "metric": metric, + "threshold": float(threshold), + "start_frame": int(current[0]["frame_id"]), + "end_frame": int(current[-1]["frame_id"]), + "frame_count": len(current), + "mean": float(values.mean()), + "maximum": float(values.max()), + "p95": float(np.percentile(values, 95)), + }) + current.clear() + + previous_frame: int | None = None + for row in ordered: + frame = int(row["frame_id"]) + above = float(row[metric]) >= threshold + if not above or (previous_frame is not None and frame != previous_frame + 1): + flush() + if above: + current.append(row) + previous_frame = frame + flush() + return sorted( + intervals, + key=lambda row: (-int(row["frame_count"]), -float(row["mean"]), str(row["take"])), + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/procrustes.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f5b53bcabf1384c6af810216589e897a459250 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/procrustes.py @@ -0,0 +1,46 @@ +"""Rigid and similarity-aligned 3D joint errors.""" + +from __future__ import annotations + +import numpy as np + + +def aligned_mpjpe_mm( + predicted_m: np.ndarray, + target_m: np.ndarray, + *, + estimate_scale: bool, +) -> np.ndarray: + """Return per-sample Kabsch/Umeyama MPJPE for arrays ending in [J,3].""" + + predicted = np.asarray(predicted_m, dtype=np.float64) + target = np.asarray(target_m, dtype=np.float64) + if predicted.shape != target.shape or predicted.ndim < 3 or predicted.shape[-1] != 3: + raise ValueError("predicted and target joints must share shape [...,J,3]") + prefix = predicted.shape[:-2] + joints = predicted.shape[-2] + source = predicted.reshape(-1, joints, 3) + destination = target.reshape(-1, joints, 3) + if not np.isfinite(source).all() or not np.isfinite(destination).all(): + raise ValueError("aligned MPJPE expects finite valid-hand joints") + source_mean = source.mean(axis=1, keepdims=True) + destination_mean = destination.mean(axis=1, keepdims=True) + source_centered = source - source_mean + destination_centered = destination - destination_mean + covariance = np.swapaxes(source_centered, 1, 2) @ destination_centered + left, singular, right_transposed = np.linalg.svd(covariance) + correction = np.ones((len(source), 3), dtype=np.float64) + correction[:, -1] = np.where( + np.linalg.det(left @ right_transposed) < 0.0, -1.0, 1.0, + ) + rotation = (left * correction[:, None, :]) @ right_transposed + aligned = source_centered @ rotation + if estimate_scale: + numerator = (singular * correction).sum(axis=1) + denominator = np.square(source_centered).sum(axis=(1, 2)) + scale = np.divide( + numerator, denominator, out=np.ones_like(numerator), where=denominator > 1e-12, + ) + aligned = aligned * scale[:, None, None] + error = np.linalg.norm(aligned - destination_centered, axis=-1).mean(axis=1) * 1000.0 + return error.reshape(prefix) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/selection.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/selection.py new file mode 100644 index 0000000000000000000000000000000000000000..0e01a5da365d139c657d71efd738c8b38b555d0c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/selection.py @@ -0,0 +1,69 @@ +"""Deterministic, auditable selection of qualitative validation examples.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence + +import numpy as np + + +def _nearest_rank(records: list[Mapping[str, object]], metric: str, percentile: float) -> Mapping[str, object] | None: + candidates = [record for record in records if record.get(metric) is not None] + if not candidates: + return None + values = np.asarray([float(record[metric]) for record in candidates], dtype=np.float64) + target = float(np.percentile(values, percentile)) + return candidates[int(np.argmin(np.abs(values - target)))] + + +def select_visualization_frames( + records: Sequence[Mapping[str, object]], + *, + seed: int = 20260716, + random_count: int = 4, + metric: str = "absolute_mpjpe_mm", +) -> list[dict[str, object]]: + """Select random, error-tail, scale, depth, and validity-state frames.""" + + if not records: + return [] + rng = np.random.default_rng(seed) + selected: dict[tuple[int, int], dict[str, object]] = {} + + def add(record: Mapping[str, object] | None, reason: str) -> None: + if record is None: + return + key = (int(record["clip_index"]), int(record["time_index"])) + if key not in selected: + selected[key] = { + "clip_index": key[0], + "time_index": key[1], + "subject": record["subject"], + "sequence": record["sequence"], + "take": record["take"], + "frame_id": int(record["frame_id"]), + "annotation_state": record["annotation_state"], + "hand_size_bucket": record.get("hand_size_bucket"), + "depth_bucket": record.get("depth_bucket"), + metric: record.get(metric), + "reasons": [], + } + selected[key]["reasons"].append(reason) + + random_count = min(random_count, len(records)) + for index in rng.choice(len(records), size=random_count, replace=False): + add(records[int(index)], "random") + + for percentile in (50, 90, 95, 100): + add(_nearest_rank(list(records), metric, percentile), f"error_p{percentile}") + + for field, values in ( + ("hand_size_bucket", ("small", "medium", "large")), + ("depth_bucket", ("near", "middle", "far")), + ("annotation_state", ("00", "01", "10", "11")), + ): + for value in values: + bucket = [record for record in records if record.get(field) == value] + add(_nearest_rank(bucket, metric, 50) if bucket else None, f"{field}={value}") + + return sorted(selected.values(), key=lambda item: (int(item["clip_index"]), int(item["time_index"]))) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/sota.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/sota.py new file mode 100644 index 0000000000000000000000000000000000000000..3eecabedfeca76d5b64506fb7b9aa9840c38c28f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/sota.py @@ -0,0 +1,630 @@ +"""Shared prediction format and fair H2O evaluation for external baselines.""" + +from __future__ import annotations + +import csv +import json +from collections import defaultdict +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping, Sequence + +import numpy as np + +from foundation_hand.evaluation.metrics import bootstrap_take_means, distribution_summary + + +SCHEMA_VERSION = "foundation_hand_sota_prediction_v1" +SIDES = ("left", "right") +FINGERTIP_INDICES = (4, 8, 12, 16, 20) +PRIMARY_METRICS = ( + "absolute_mpjpe_mm", + "root_relative_mpjpe_mm", + "absolute_mpvpe_mm", + "root_relative_mpvpe_mm", + "projected_2d_error_px", + "fingertip_mpjpe_mm", + "translation_x_mae_mm", + "translation_y_mae_mm", + "translation_z_mae_mm", +) + + +def frame_key(take: str, frame_id: int) -> str: + return f"{take}/{frame_id:06d}" + + +def load_frame_index(manifest: str | Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Expand an official run manifest into its unique, deterministic frame order.""" + + takes: list[str] = [] + frame_ids: list[int] = [] + keys: list[str] = [] + seen: set[str] = set() + for line in Path(manifest).read_text(encoding="utf-8").splitlines(): + if not line.strip(): + continue + record = json.loads(line) + take = str(record["take"]) + if not take.endswith("/cam4"): + raise ValueError(f"SOTA evaluation is cam4-only: {take}") + for value in record["frame_ids"]: + frame_id = int(value) + key = frame_key(take, frame_id) + if key in seen: + raise ValueError(f"Duplicate frame in manifest: {key}") + seen.add(key) + takes.append(take) + frame_ids.append(frame_id) + keys.append(key) + if not keys: + raise ValueError("Manifest contains no frames") + return ( + np.asarray(keys, dtype=np.str_), + np.asarray(takes, dtype=np.str_), + np.asarray(frame_ids, dtype=np.int64), + ) + + +@dataclass(frozen=True) +class PredictionBundle: + """Camera-space predictions aligned one-to-one with an official frame manifest.""" + + model_name: str + frame_keys: np.ndarray + takes: np.ndarray + frame_ids: np.ndarray + joints_camera_m: np.ndarray + detected: np.ndarray + confidence: np.ndarray + metadata: Mapping[str, Any] + vertices_camera_m: np.ndarray | None = None + + def validate(self) -> None: + count = len(self.frame_keys) + expected = { + "takes": (count,), + "frame_ids": (count,), + "joints_camera_m": (count, 2, 21, 3), + "detected": (count, 2), + "confidence": (count, 2), + } + for name, shape in expected.items(): + if np.asarray(getattr(self, name)).shape != shape: + raise ValueError( + f"{name} shape {np.asarray(getattr(self, name)).shape} != {shape}" + ) + if self.vertices_camera_m is not None: + vertices = np.asarray(self.vertices_camera_m) + if vertices.ndim != 4 or vertices.shape[:2] != (count, 2) or vertices.shape[-1] != 3: + raise ValueError(f"Unexpected vertices_camera_m shape: {vertices.shape}") + if len(set(map(str, self.frame_keys.tolist()))) != count: + raise ValueError("Prediction frame keys must be unique") + finite_joints = np.isfinite(self.joints_camera_m).all(axis=(-1, -2)) + if np.any(self.detected & ~finite_joints): + raise ValueError("Detected hands must have 21 finite camera-space joints") + if self.vertices_camera_m is not None: + finite_vertices = np.isfinite(self.vertices_camera_m).all(axis=(-1, -2)) + if np.any(self.detected & ~finite_vertices): + raise ValueError("Detected hands must have finite camera-space vertices") + + def save(self, path: str | Path) -> None: + self.validate() + payload: dict[str, np.ndarray] = { + "schema_version": np.asarray(SCHEMA_VERSION), + "model_name": np.asarray(self.model_name), + "frame_keys": np.asarray(self.frame_keys, dtype=np.str_), + "takes": np.asarray(self.takes, dtype=np.str_), + "frame_ids": np.asarray(self.frame_ids, dtype=np.int64), + "joints_camera_m": np.asarray(self.joints_camera_m, dtype=np.float32), + "detected": np.asarray(self.detected, dtype=np.bool_), + "confidence": np.asarray(self.confidence, dtype=np.float32), + "metadata_json": np.asarray(json.dumps(dict(self.metadata), sort_keys=True)), + } + if self.vertices_camera_m is not None: + payload["vertices_camera_m"] = np.asarray( + self.vertices_camera_m, dtype=np.float32 + ) + output = Path(path) + output.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(output, **payload) + + @classmethod + def load(cls, path: str | Path) -> "PredictionBundle": + with np.load(path, allow_pickle=False) as data: + version = str(data["schema_version"].item()) + if version != SCHEMA_VERSION: + raise ValueError(f"Unsupported prediction schema: {version}") + bundle = cls( + model_name=str(data["model_name"].item()), + frame_keys=data["frame_keys"].copy(), + takes=data["takes"].copy(), + frame_ids=data["frame_ids"].copy(), + joints_camera_m=data["joints_camera_m"].copy(), + detected=data["detected"].copy(), + confidence=data["confidence"].copy(), + metadata=json.loads(str(data["metadata_json"].item())), + vertices_camera_m=( + data["vertices_camera_m"].copy() + if "vertices_camera_m" in data.files + else None + ), + ) + bundle.validate() + return bundle + + +@dataclass(frozen=True) +class GroundTruthBundle: + frame_keys: np.ndarray + takes: np.ndarray + frame_ids: np.ndarray + joints_camera_m: np.ndarray + vertices_camera_m: np.ndarray + annotation_valid: np.ndarray + intrinsics: np.ndarray + metadata: Mapping[str, Any] + + def save(self, path: str | Path) -> None: + count = len(self.frame_keys) + if self.joints_camera_m.shape != (count, 2, 21, 3): + raise ValueError(f"Unexpected GT joints shape: {self.joints_camera_m.shape}") + if self.vertices_camera_m.shape[:2] != (count, 2): + raise ValueError(f"Unexpected GT vertices shape: {self.vertices_camera_m.shape}") + output = Path(path) + output.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed( + output, + schema_version=np.asarray("foundation_hand_sota_ground_truth_v1"), + frame_keys=np.asarray(self.frame_keys, dtype=np.str_), + takes=np.asarray(self.takes, dtype=np.str_), + frame_ids=np.asarray(self.frame_ids, dtype=np.int64), + joints_camera_m=np.asarray(self.joints_camera_m, dtype=np.float32), + vertices_camera_m=np.asarray(self.vertices_camera_m, dtype=np.float32), + annotation_valid=np.asarray(self.annotation_valid, dtype=np.bool_), + intrinsics=np.asarray(self.intrinsics, dtype=np.float32), + metadata_json=np.asarray(json.dumps(dict(self.metadata), sort_keys=True)), + ) + + @classmethod + def load(cls, path: str | Path) -> "GroundTruthBundle": + with np.load(path, allow_pickle=False) as data: + version = str(data["schema_version"].item()) + if version != "foundation_hand_sota_ground_truth_v1": + raise ValueError(f"Unsupported GT schema: {version}") + return cls( + frame_keys=data["frame_keys"].copy(), + takes=data["takes"].copy(), + frame_ids=data["frame_ids"].copy(), + joints_camera_m=data["joints_camera_m"].copy(), + vertices_camera_m=data["vertices_camera_m"].copy(), + annotation_valid=data["annotation_valid"].copy(), + intrinsics=data["intrinsics"].copy(), + metadata=json.loads(str(data["metadata_json"].item())), + ) + + +def align_prediction( + prediction: PredictionBundle, ground_truth: GroundTruthBundle +) -> PredictionBundle: + """Return predictions in GT order, rejecting missing or extra frame keys.""" + + gt_keys = list(map(str, ground_truth.frame_keys.tolist())) + pred_index = {str(key): index for index, key in enumerate(prediction.frame_keys.tolist())} + if set(pred_index) != set(gt_keys): + missing = sorted(set(gt_keys) - set(pred_index)) + extra = sorted(set(pred_index) - set(gt_keys)) + raise ValueError( + f"Prediction/GT frame mismatch: missing={missing[:3]} extra={extra[:3]}" + ) + order = np.asarray([pred_index[key] for key in gt_keys], dtype=np.int64) + return PredictionBundle( + model_name=prediction.model_name, + frame_keys=prediction.frame_keys[order], + takes=prediction.takes[order], + frame_ids=prediction.frame_ids[order], + joints_camera_m=prediction.joints_camera_m[order], + detected=prediction.detected[order], + confidence=prediction.confidence[order], + metadata=prediction.metadata, + vertices_camera_m=( + prediction.vertices_camera_m[order] + if prediction.vertices_camera_m is not None + else None + ), + ) + + +def _project(points: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + z = points[..., 2:3] + normalized = points[..., :2] / z + return np.einsum("nij,nhkj->nhki", intrinsics[:, :2, :2], normalized) + intrinsics[ + :, None, None, :2, 2 + ] + + +def _mean_or_none(value: np.ndarray) -> float | None: + finite = value[np.isfinite(value)] + return float(finite.mean()) if finite.size else None + + +def _auc_pck(errors_mm: np.ndarray, success: np.ndarray, maximum_mm: float = 50.0) -> float: + thresholds = np.linspace(0.0, maximum_mm, 101) + hits = success[..., None] & (errors_mm[..., None] <= thresholds) + pck = hits.reshape(-1, len(thresholds)).mean(axis=0) + return float(np.trapezoid(pck, thresholds) / maximum_mm) + + +def evaluate_prediction_bundle( + prediction: PredictionBundle, + ground_truth: GroundTruthBundle, + *, + bootstrap_seed: int = 20260716, + bootstrap_samples: int = 10_000, + pixel_scale: float = 1.0, + temporal_clip_length: int | None = 8, +) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]: + """Evaluate one model without silently dropping detector failures.""" + + prediction = align_prediction(prediction, ground_truth) + valid = ground_truth.annotation_valid.astype(bool) + finite = np.isfinite(prediction.joints_camera_m).all(axis=(-1, -2)) + success = valid & prediction.detected & finite + + joint_error = np.linalg.norm( + prediction.joints_camera_m - ground_truth.joints_camera_m, axis=-1 + ) * 1000.0 + pred_relative = prediction.joints_camera_m - prediction.joints_camera_m[:, :, :1] + gt_relative = ground_truth.joints_camera_m - ground_truth.joints_camera_m[:, :, :1] + relative_error = np.linalg.norm(pred_relative - gt_relative, axis=-1) * 1000.0 + projected = _project(prediction.joints_camera_m, ground_truth.intrinsics) + target_projected = _project(ground_truth.joints_camera_m, ground_truth.intrinsics) + if pixel_scale <= 0: + raise ValueError("pixel_scale must be positive") + projected_error = np.linalg.norm(projected - target_projected, axis=-1) * pixel_scale + translation_error = np.abs( + prediction.joints_camera_m[:, :, 0] - ground_truth.joints_camera_m[:, :, 0] + ) * 1000.0 + + vertex_error: np.ndarray | None = None + relative_vertex_error: np.ndarray | None = None + if prediction.vertices_camera_m is not None: + vertex_error = np.linalg.norm( + prediction.vertices_camera_m - ground_truth.vertices_camera_m, axis=-1 + ) * 1000.0 + pred_vertex_relative = ( + prediction.vertices_camera_m - prediction.joints_camera_m[:, :, None, 0] + ) + gt_vertex_relative = ( + ground_truth.vertices_camera_m - ground_truth.joints_camera_m[:, :, None, 0] + ) + relative_vertex_error = np.linalg.norm( + pred_vertex_relative - gt_vertex_relative, axis=-1 + ) * 1000.0 + + wrong_side: list[bool | None] = [] + for frame_index in range(len(ground_truth.frame_keys)): + if bool(valid[frame_index].all() and success[frame_index].all()): + correct = 0.5 * ( + joint_error[frame_index, 0].mean() + joint_error[frame_index, 1].mean() + ) + swapped = 500.0 * ( + np.linalg.norm( + prediction.joints_camera_m[frame_index, 0] + - ground_truth.joints_camera_m[frame_index, 1], + axis=-1, + ).mean() + + np.linalg.norm( + prediction.joints_camera_m[frame_index, 1] + - ground_truth.joints_camera_m[frame_index, 0], + axis=-1, + ).mean() + ) + wrong_side.append(bool(swapped < correct)) + else: + wrong_side.append(None) + + rows: list[dict[str, Any]] = [] + for frame_index in range(len(ground_truth.frame_keys)): + for hand, side in enumerate(SIDES): + is_valid = bool(valid[frame_index, hand]) + is_success = bool(success[frame_index, hand]) + row: dict[str, Any] = { + "frame_key": str(ground_truth.frame_keys[frame_index]), + "take": str(ground_truth.takes[frame_index]), + "frame_id": int(ground_truth.frame_ids[frame_index]), + "side": side, + "annotation_valid": int(is_valid), + "detected": int(prediction.detected[frame_index, hand]), + "evaluation_success": int(is_success), + "coverage_success": int(is_success) if is_valid else None, + "confidence": ( + float(prediction.confidence[frame_index, hand]) + if np.isfinite(prediction.confidence[frame_index, hand]) + else None + ), + "wrong_side_preference": ( + int(wrong_side[frame_index]) + if wrong_side[frame_index] is not None + else None + ), + } + metric_values = { + "absolute_mpjpe_mm": joint_error[frame_index, hand].mean(), + "root_relative_mpjpe_mm": relative_error[frame_index, hand].mean(), + "projected_2d_error_px": projected_error[frame_index, hand].mean(), + "fingertip_mpjpe_mm": joint_error[ + frame_index, hand, list(FINGERTIP_INDICES) + ].mean(), + "translation_x_mae_mm": translation_error[frame_index, hand, 0], + "translation_y_mae_mm": translation_error[frame_index, hand, 1], + "translation_z_mae_mm": translation_error[frame_index, hand, 2], + } + if vertex_error is not None and relative_vertex_error is not None: + metric_values.update({ + "absolute_mpvpe_mm": vertex_error[frame_index, hand].mean(), + "root_relative_mpvpe_mm": relative_vertex_error[ + frame_index, hand + ].mean(), + }) + for name in PRIMARY_METRICS: + row[name] = ( + float(metric_values[name]) + if is_success and name in metric_values + else None + ) + rows.append(row) + + temporal_rows: list[dict[str, Any]] = [] + run_positions = np.zeros(len(ground_truth.frame_keys), dtype=np.int64) + for index in range(1, len(run_positions)): + if ( + ground_truth.takes[index] == ground_truth.takes[index - 1] + and ground_truth.frame_ids[index] == ground_truth.frame_ids[index - 1] + 1 + ): + run_positions[index] = run_positions[index - 1] + 1 + for current in range(1, len(ground_truth.frame_keys)): + previous = current - 1 + consecutive = ( + ground_truth.takes[current] == ground_truth.takes[previous] + and ground_truth.frame_ids[current] == ground_truth.frame_ids[previous] + 1 + ) + clip_consecutive = ( + consecutive + and ( + temporal_clip_length is None + or run_positions[current] % temporal_clip_length != 0 + ) + ) + if not clip_consecutive: + continue + for hand, side in enumerate(SIDES): + gt_pair_valid = bool(valid[previous, hand] and valid[current, hand]) + pred_pair_valid = bool(success[previous, hand] and success[current, hand]) + wrist_velocity = None + joint_velocity = None + wrist_acceleration = None + joint_acceleration = None + gt_triplet_valid = False + pred_triplet_valid = False + if gt_pair_valid and pred_pair_valid: + predicted_delta = ( + prediction.joints_camera_m[current, hand] + - prediction.joints_camera_m[previous, hand] + ) + target_delta = ( + ground_truth.joints_camera_m[current, hand] + - ground_truth.joints_camera_m[previous, hand] + ) + velocity_error = np.linalg.norm(predicted_delta - target_delta, axis=-1) * 1000.0 + wrist_velocity = float(velocity_error[0]) + joint_velocity = float(velocity_error.mean()) + if previous >= 1: + before_previous = previous - 1 + triplet_consecutive = ( + ground_truth.takes[before_previous] == ground_truth.takes[current] + and ground_truth.frame_ids[before_previous] + 1 + == ground_truth.frame_ids[previous] + and ( + temporal_clip_length is None + or run_positions[current] % temporal_clip_length >= 2 + ) + ) + gt_triplet_valid = bool( + triplet_consecutive + and valid[before_previous, hand] + and valid[previous, hand] + and valid[current, hand] + ) + pred_triplet_valid = bool( + gt_triplet_valid + and success[before_previous, hand] + and success[previous, hand] + and success[current, hand] + ) + if pred_triplet_valid: + predicted_acceleration = ( + prediction.joints_camera_m[current, hand] + - 2 * prediction.joints_camera_m[previous, hand] + + prediction.joints_camera_m[before_previous, hand] + ) + target_acceleration = ( + ground_truth.joints_camera_m[current, hand] + - 2 * ground_truth.joints_camera_m[previous, hand] + + ground_truth.joints_camera_m[before_previous, hand] + ) + acceleration_error = np.linalg.norm( + predicted_acceleration - target_acceleration, axis=-1 + ) * 1000.0 + wrist_acceleration = float(acceleration_error[0]) + joint_acceleration = float(acceleration_error.mean()) + identity_switch = None + if wrong_side[previous] is not None and wrong_side[current] is not None: + identity_switch = int(wrong_side[previous] != wrong_side[current]) + temporal_rows.append({ + "take": str(ground_truth.takes[current]), + "side": side, + "frame_id_from": int(ground_truth.frame_ids[previous]), + "frame_id_to": int(ground_truth.frame_ids[current]), + "annotation_pair_valid": int(gt_pair_valid), + "evaluation_pair_success": int(gt_pair_valid and pred_pair_valid), + "annotation_triplet_valid": int(gt_triplet_valid), + "evaluation_triplet_success": int(pred_triplet_valid), + "wrist_velocity_error_mm_per_frame": wrist_velocity, + "joint_velocity_error_mm_per_frame": joint_velocity, + "wrist_acceleration_error_mm_per_frame2": wrist_acceleration, + "joint_acceleration_error_mm_per_frame2": joint_acceleration, + "identity_switch_fraction": identity_switch, + }) + + metric_summary = { + metric: distribution_summary(row[metric] for row in rows) + for metric in PRIMARY_METRICS + } + valid_joint = np.broadcast_to(valid[..., None], joint_error.shape) + success_joint = np.broadcast_to(success[..., None], joint_error.shape) + report: dict[str, Any] = { + "status": "evaluated", + "schema_version": SCHEMA_VERSION, + "model_name": prediction.model_name, + "frames": int(len(ground_truth.frame_keys)), + "takes": int(len(set(map(str, ground_truth.takes.tolist())))), + "official_test_used": False, + "split_role": "official_validation", + "prediction_metadata": dict(prediction.metadata), + "projected_2d_pixel_scale": pixel_scale, + "temporal_evaluation_clip_length": temporal_clip_length, + "coverage": { + "annotation_valid_hand_frames": int(valid.sum()), + "successful_hand_frames": int(success.sum()), + "hand_frame_fraction": float(success.sum() / valid.sum()), + "annotation_invalid_prediction_rate": float( + prediction.detected[~valid].mean() if np.any(~valid) else 0.0 + ), + "valid_temporal_pairs": int(sum(row["annotation_pair_valid"] for row in temporal_rows)), + "successful_temporal_pairs": int( + sum(row["evaluation_pair_success"] for row in temporal_rows) + ), + }, + "metrics_success_conditioned": metric_summary, + "failure_aware": { + "absolute_pck_20mm": float( + (success_joint & (joint_error <= 20.0))[valid_joint].mean() + ), + "absolute_pck_50mm": float( + (success_joint & (joint_error <= 50.0))[valid_joint].mean() + ), + "absolute_auc_0_50mm": _auc_pck( + joint_error[valid_joint], success_joint[valid_joint] + ), + "root_relative_pck_20mm": float( + (success_joint & (relative_error <= 20.0))[valid_joint].mean() + ), + "root_relative_pck_50mm": float( + (success_joint & (relative_error <= 50.0))[valid_joint].mean() + ), + "root_relative_auc_0_50mm": _auc_pck( + relative_error[valid_joint], success_joint[valid_joint] + ), + }, + "per_side": { + side: { + "coverage": float(success[:, hand].sum() / valid[:, hand].sum()), + **{ + metric: distribution_summary( + row[metric] for row in rows if row["side"] == side + ) + for metric in PRIMARY_METRICS + }, + } + for hand, side in enumerate(SIDES) + }, + "temporal_metrics_success_conditioned": { + name: distribution_summary(row[name] for row in temporal_rows) + for name in ( + "wrist_velocity_error_mm_per_frame", + "joint_velocity_error_mm_per_frame", + "wrist_acceleration_error_mm_per_frame2", + "joint_acceleration_error_mm_per_frame2", + "identity_switch_fraction", + ) + }, + "equal_take_bootstrap_ci": bootstrap_take_means( + rows, + ("coverage_success",) + PRIMARY_METRICS, + seed=bootstrap_seed, + samples=bootstrap_samples, + ), + } + valid_pairs = report["coverage"]["valid_temporal_pairs"] + report["coverage"]["temporal_pair_fraction"] = ( + float(report["coverage"]["successful_temporal_pairs"] / valid_pairs) + if valid_pairs + else None + ) + return report, rows, temporal_rows + + +def write_csv_rows(path: str | Path, rows: Sequence[Mapping[str, Any]]) -> None: + if not rows: + raise ValueError("Cannot write an empty metric table") + output = Path(path) + output.parent.mkdir(parents=True, exist_ok=True) + with output.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0]), lineterminator="\n") + writer.writeheader() + writer.writerows(rows) + + +def paired_take_bootstrap( + baseline_rows: Sequence[Mapping[str, Any]], + candidate_rows: Sequence[Mapping[str, Any]], + metrics: Sequence[str] = PRIMARY_METRICS, + *, + seed: int = 20260716, + samples: int = 10_000, +) -> list[dict[str, Any]]: + """Bootstrap candidate-minus-baseline deltas on their exact success intersection.""" + + key_fields = ("frame_key", "side") + baseline = {tuple(row[field] for field in key_fields): row for row in baseline_rows} + candidate = {tuple(row[field] for field in key_fields): row for row in candidate_rows} + if set(baseline) != set(candidate): + raise ValueError("Paired metric tables do not contain identical hand-frame keys") + rng = np.random.default_rng(seed) + output: list[dict[str, Any]] = [] + for metric in metrics: + by_take: dict[str, list[float]] = defaultdict(list) + for key in baseline: + first = baseline[key].get(metric) + second = candidate[key].get(metric) + if first is None or second is None: + continue + if np.isfinite(float(first)) and np.isfinite(float(second)): + by_take[str(baseline[key]["take"])].append(float(second) - float(first)) + take_delta = np.asarray( + [np.mean(values) for values in by_take.values() if values], dtype=np.float64 + ) + if take_delta.size == 0: + output.append({ + "metric": metric, + "paired_hand_frames": 0, + "take_count": 0, + "candidate_minus_baseline": None, + "ci95_low": None, + "ci95_high": None, + }) + continue + indices = rng.integers(0, take_delta.size, size=(samples, take_delta.size)) + boot = take_delta[indices].mean(axis=1) + output.append({ + "metric": metric, + "paired_hand_frames": int(sum(len(values) for values in by_take.values())), + "take_count": int(take_delta.size), + "candidate_minus_baseline": float(take_delta.mean()), + "ci95_low": float(np.percentile(boot, 2.5)), + "ci95_high": float(np.percentile(boot, 97.5)), + "bootstrap_samples": samples, + "seed": seed, + }) + return output diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/subset.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/subset.py new file mode 100644 index 0000000000000000000000000000000000000000..250d37a0fa78a5caf231fa86d3948bce52f3f31d --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/subset.py @@ -0,0 +1,72 @@ +"""Deterministic take-balanced, within-take stratified subset construction.""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Mapping, Sequence + +import numpy as np + + +def balanced_stratified_indices( + records: Sequence[Mapping[str, object]], + count: int, + *, + seed: int, +) -> list[int]: + """Balance quotas over takes and round-robin available within-take strata.""" + + if count <= 0 or count > len(records): + raise ValueError("count must be positive and no larger than the record count") + by_take: dict[str, list[Mapping[str, object]]] = defaultdict(list) + for record in records: + by_take[str(record["take"])].append(record) + takes = sorted(by_take) + if not takes: + return [] + + rng = np.random.default_rng(seed) + shuffled_takes = list(np.asarray(takes)[rng.permutation(len(takes))]) + base, remainder = divmod(count, len(takes)) + quotas = {take: base + int(position < remainder) for position, take in enumerate(shuffled_takes)} + selected: list[int] = [] + + for take in takes: + groups: dict[tuple[str, str, str], list[Mapping[str, object]]] = defaultdict(list) + for record in by_take[take]: + stratum = ( + str(record["hand_size_bucket"]), + str(record["depth_bucket"]), + str(record["annotation_state"]), + ) + groups[stratum].append(record) + group_keys = sorted(groups) + group_keys = [group_keys[int(index)] for index in rng.permutation(len(group_keys))] + for key in group_keys: + order = rng.permutation(len(groups[key])) + groups[key] = [groups[key][int(index)] for index in order] + cursors = {key: 0 for key in group_keys} + take_selected = 0 + while take_selected < min(quotas[take], len(by_take[take])): + progressed = False + for key in group_keys: + cursor = cursors[key] + if cursor >= len(groups[key]): + continue + selected.append(int(groups[key][cursor]["clip_index"])) + cursors[key] += 1 + take_selected += 1 + progressed = True + if take_selected >= quotas[take]: + break + if not progressed: + break + + if len(selected) < count: + selected_set = set(selected) + remaining = [int(record["clip_index"]) for record in records if int(record["clip_index"]) not in selected_set] + order = rng.permutation(len(remaining)) + selected.extend(remaining[int(index)] for index in order[: count - len(selected)]) + if len(selected) != count or len(set(selected)) != count: + raise AssertionError("subset construction failed to return unique requested indices") + return sorted(selected) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/temporal_filter.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/temporal_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..44b73366b267f458273c51efb3583dc1b4778020 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/temporal_filter.py @@ -0,0 +1,183 @@ +"""Inference-only temporal filters and jitter metrics with hard segment resets.""" + +from __future__ import annotations + +from collections.abc import Callable + +import numpy as np +from scipy.signal import butter, sosfiltfilt +from scipy.spatial.transform import Rotation + + +def valid_segments( + clip_ids: np.ndarray, + frame_ids: np.ndarray, + frame_valid: np.ndarray, +) -> list[np.ndarray]: + """Return contiguous valid indices without crossing clip or frame gaps.""" + + clip_ids = np.asarray(clip_ids) + frame_ids = np.asarray(frame_ids) + frame_valid = np.asarray(frame_valid, dtype=bool) + if not (clip_ids.ndim == frame_ids.ndim == frame_valid.ndim == 1): + raise ValueError("segment metadata must be one-dimensional") + if not (len(clip_ids) == len(frame_ids) == len(frame_valid)): + raise ValueError("segment metadata lengths differ") + output: list[np.ndarray] = [] + start: int | None = None + for index in range(len(frame_ids)): + continues = ( + start is not None + and frame_valid[index] + and clip_ids[index] == clip_ids[index - 1] + and frame_ids[index] == frame_ids[index - 1] + 1 + ) + if not continues: + if start is not None: + output.append(np.arange(start, index, dtype=np.int64)) + start = index if frame_valid[index] else None + if start is not None: + output.append(np.arange(start, len(frame_ids), dtype=np.int64)) + return output + + +def ema(values: np.ndarray, alpha: float) -> np.ndarray: + if not 0.0 < alpha <= 1.0: + raise ValueError("EMA alpha must be in (0, 1]") + values = np.asarray(values) + if values.ndim < 1 or values.shape[0] == 0: + raise ValueError("EMA requires a non-empty time dimension") + output = values.astype(np.float64, copy=True) + for index in range(1, len(output)): + output[index] = alpha * values[index] + (1.0 - alpha) * output[index - 1] + return output.astype(values.dtype, copy=False) + + +def butterworth_zero_phase( + values: np.ndarray, + cutoff_hz: float, + fps: float, + order: int = 2, +) -> np.ndarray: + values = np.asarray(values) + if values.ndim < 1 or values.shape[0] < 4: + raise ValueError("zero-phase filtering requires at least four frames") + if fps <= 0.0 or not 0.0 < cutoff_hz < fps / 2.0: + raise ValueError("Butterworth cutoff must lie below Nyquist") + if order < 1: + raise ValueError("Butterworth order must be positive") + sections = butter(order, cutoff_hz, btype="lowpass", fs=fps, output="sos") + # H2O inference clips have T=8. Explicit n-1 padding preserves the hard + # clip boundary while allowing a verified zero-phase filter on full clips. + filtered = sosfiltfilt( + sections, values.astype(np.float64), axis=0, padlen=values.shape[0] - 1, + ) + if not np.isfinite(filtered).all(): + raise FloatingPointError("Butterworth filtering produced NaN/Inf") + return filtered.astype(values.dtype) + + +def apply_by_segment( + values: np.ndarray, + segments: list[np.ndarray], + operation: Callable[[np.ndarray], np.ndarray], + *, + minimum_frames: int, +) -> tuple[np.ndarray, int]: + values = np.asarray(values) + output = values.copy() + fallback_segments = 0 + for indices in segments: + if len(indices) < minimum_frames: + fallback_segments += 1 + continue + filtered = operation(values[indices]) + if filtered.shape != values[indices].shape: + raise ValueError("temporal operation changed the signal shape") + output[indices] = filtered + return output, fallback_segments + + +def unwrap_quaternion_signs(quaternions: np.ndarray) -> np.ndarray: + quaternions = np.asarray(quaternions) + if quaternions.ndim < 2 or quaternions.shape[-1] != 4: + raise ValueError("quaternions must have shape [time, ..., 4]") + output = quaternions.copy() + for index in range(1, len(output)): + dots = np.sum(output[index - 1] * output[index], axis=-1) + output[index][dots < 0.0] *= -1.0 + return output + + +def filter_rotation_matrices( + matrices: np.ndarray, + operation: Callable[[np.ndarray], np.ndarray], +) -> np.ndarray: + matrices = np.asarray(matrices) + if matrices.ndim < 3 or matrices.shape[-2:] != (3, 3): + raise ValueError("rotation matrices must have shape [time, ..., 3, 3]") + original_shape = matrices.shape + quaternions = Rotation.from_matrix(matrices.reshape(-1, 3, 3)).as_quat() + quaternions = quaternions.reshape(*original_shape[:-2], 4) + quaternions = unwrap_quaternion_signs(quaternions) + filtered = operation(quaternions) + norms = np.linalg.norm(filtered, axis=-1, keepdims=True) + if not np.isfinite(norms).all() or np.any(norms < 1e-8): + raise FloatingPointError("quaternion filter produced invalid norms") + filtered = filtered / norms + result = Rotation.from_quat(filtered.reshape(-1, 4)).as_matrix() + return result.reshape(original_shape).astype(matrices.dtype) + + +def finite_differences( + values: np.ndarray, fps: float, order: int, +) -> np.ndarray: + values = np.asarray(values) + if fps <= 0.0 or order < 1: + raise ValueError("finite difference fps/order is invalid") + output = values + for _ in range(order): + output = np.diff(output, axis=0) * fps + return output + + +def derivative_norms(values: np.ndarray, fps: float, order: int) -> np.ndarray: + differences = finite_differences(values, fps, order) + return np.linalg.vector_norm(differences, axis=-1) + + +def high_frequency_energy_ratio( + values: np.ndarray, fps: float, threshold_hz: float = 6.0, +) -> float: + values = np.asarray(values, dtype=np.float64) + if values.ndim < 1 or values.shape[0] < 4: + raise ValueError("spectral metric requires at least four frames") + if not 0.0 < threshold_hz < fps / 2.0: + raise ValueError("spectral threshold must lie below Nyquist") + centered = values - values.mean(axis=0, keepdims=True) + spectrum = np.fft.rfft(centered, axis=0) + power = np.abs(spectrum) ** 2 + frequencies = np.fft.rfftfreq(values.shape[0], d=1.0 / fps) + non_dc = frequencies > 0.0 + denominator = float(power[non_dc].sum()) + if denominator == 0.0: + return 0.0 + return float(power[frequencies >= threshold_hz].sum() / denominator) + + +def rotation_geodesic_degrees( + prediction: np.ndarray, target: np.ndarray, +) -> np.ndarray: + prediction = np.asarray(prediction) + target = np.asarray(target) + if prediction.shape != target.shape or prediction.shape[-2:] != (3, 3): + raise ValueError("rotation geodesic inputs must be aligned matrices") + relative = np.swapaxes(target, -1, -2) @ prediction + cosine = np.clip((np.trace(relative, axis1=-2, axis2=-1) - 1.0) / 2.0, -1.0, 1.0) + return np.rad2deg(np.arccos(cosine)) + + +def ema_low_frequency_delay_frames(alpha: float) -> float: + if not 0.0 < alpha <= 1.0: + raise ValueError("EMA alpha must be in (0, 1]") + return (1.0 - alpha) / alpha diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/visualization.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..fcec3681b699141bd51a7d3ad49cab5dcf905f6c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/evaluation/visualization.py @@ -0,0 +1,202 @@ +"""Camera-correct MANO, skeleton, attention, and 3D visualizations.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +import textwrap + +import cv2 +import matplotlib.pyplot as plt +import numpy as np + + +OPENPOSE_HAND_EDGES = tuple( + (start + offset, start + offset + 1) + for start in (1, 5, 9, 13, 17) + for offset in range(3) +) + ((0, 1), (0, 5), (0, 9), (0, 13), (0, 17)) + + +@dataclass(frozen=True) +class MeshLayer: + vertices_camera: np.ndarray + faces: np.ndarray + color_rgb: tuple[int, int, int] + alpha: float = 0.55 + + +def project_camera_points(points: np.ndarray, K: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + points = np.asarray(points, dtype=np.float32) + z = points[..., 2] + safe_z = np.where(z > 1e-8, z, 1.0) + u = K[0, 0] * points[..., 0] / safe_z + K[0, 2] + v = K[1, 1] * points[..., 1] / safe_z + K[1, 2] + return np.stack((u, v), axis=-1), z + + +def render_mesh_layers(image_rgb: np.ndarray, layers: Sequence[MeshLayer]) -> np.ndarray: + """Rasterize constant-color triangular meshes with perspective-correct z-order.""" + + image = np.asarray(image_rgb, dtype=np.uint8) + height, width = image.shape[:2] + depth_buffer = np.full((height, width), np.inf, dtype=np.float32) + color_buffer = np.zeros((height, width, 3), dtype=np.float32) + alpha_buffer = np.zeros((height, width), dtype=np.float32) + + for layer in layers: + vertices = np.asarray(layer.vertices_camera, dtype=np.float32) + faces = np.asarray(layer.faces, dtype=np.int64) + # The caller supplies already projected xy by temporarily storing pixel x/y + # in vertices_camera x/y when using this low-level rasterizer. + projected = vertices[:, :2] + z_values = vertices[:, 2] + for face in faces: + z = z_values[face] + if np.any(z <= 1e-6) or not np.isfinite(z).all(): + continue + triangle = projected[face] + if not np.isfinite(triangle).all(): + continue + x_min = max(int(np.floor(triangle[:, 0].min())), 0) + x_max = min(int(np.ceil(triangle[:, 0].max())), width - 1) + y_min = max(int(np.floor(triangle[:, 1].min())), 0) + y_max = min(int(np.ceil(triangle[:, 1].max())), height - 1) + if x_min > x_max or y_min > y_max: + continue + x0, y0 = triangle[0] + x1, y1 = triangle[1] + x2, y2 = triangle[2] + denominator = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2) + if abs(float(denominator)) < 1e-8: + continue + yy, xx = np.mgrid[y_min : y_max + 1, x_min : x_max + 1] + px = xx.astype(np.float32) + 0.5 + py = yy.astype(np.float32) + 0.5 + w0 = ((y1 - y2) * (px - x2) + (x2 - x1) * (py - y2)) / denominator + w1 = ((y2 - y0) * (px - x2) + (x0 - x2) * (py - y2)) / denominator + w2 = 1.0 - w0 - w1 + inside = (w0 >= -1e-5) & (w1 >= -1e-5) & (w2 >= -1e-5) + inverse_z = w0 / z[0] + w1 / z[1] + w2 / z[2] + pixel_z = np.where(inverse_z > 1e-8, 1.0 / inverse_z, np.inf) + local_depth = depth_buffer[y_min : y_max + 1, x_min : x_max + 1] + update = inside & (pixel_z < local_depth) + if not np.any(update): + continue + local_depth[update] = pixel_z[update] + local_color = color_buffer[y_min : y_max + 1, x_min : x_max + 1] + local_color[update] = np.asarray(layer.color_rgb, dtype=np.float32) + local_alpha = alpha_buffer[y_min : y_max + 1, x_min : x_max + 1] + local_alpha[update] = float(layer.alpha) + + alpha = alpha_buffer[..., None] + rendered = image.astype(np.float32) * (1.0 - alpha) + color_buffer * alpha + return np.clip(rendered, 0, 255).astype(np.uint8) + + +def project_mesh_layers(layers: Sequence[MeshLayer], K: np.ndarray) -> list[MeshLayer]: + """Convert camera-space vertices to pixel-x, pixel-y, camera-z vertices.""" + + projected_layers = [] + for layer in layers: + pixels, z = project_camera_points(layer.vertices_camera, K) + pixel_vertices = np.concatenate((pixels, z[:, None]), axis=-1) + projected_layers.append(MeshLayer(pixel_vertices, layer.faces, layer.color_rgb, layer.alpha)) + return projected_layers + + +def draw_skeleton( + image_rgb: np.ndarray, + points: np.ndarray, + color_rgb: tuple[int, int, int], + *, + marker: str = "circle", + draw_edges: bool = True, +) -> np.ndarray: + image = image_rgb.copy() + finite = np.isfinite(points).all(axis=-1) + integer = np.rint(np.where(finite[:, None], points, 0)).astype(np.int32) + if draw_edges: + for start, end in OPENPOSE_HAND_EDGES: + if finite[start] and finite[end]: + cv2.line(image, tuple(integer[start]), tuple(integer[end]), color_rgb, 1, cv2.LINE_AA) + for index, point in enumerate(integer): + if not finite[index]: + continue + if marker == "cross": + cv2.drawMarker(image, tuple(point), color_rgb, cv2.MARKER_CROSS, 8, 1) + elif marker == "ring": + cv2.circle(image, tuple(point), 4, color_rgb, 1, cv2.LINE_AA) + else: + cv2.circle(image, tuple(point), 2, color_rgb, -1, cv2.LINE_AA) + return image + + +def save_attention_figure( + output: Path, + image_rgb: np.ndarray, + left: np.ndarray, + right: np.ndarray, + grid_hw: tuple[int, int], + title: str, +) -> None: + """Save raw and image overlays using a shared left/right attention scale.""" + + height, width = image_rgb.shape[:2] + left_grid = np.asarray(left, dtype=np.float32).reshape(grid_hw) + right_grid = np.asarray(right, dtype=np.float32).reshape(grid_hw) + lower = float(min(left_grid.min(), right_grid.min())) + upper = float(max(left_grid.max(), right_grid.max())) + if upper <= lower: + upper = lower + 1e-8 + fig, axes = plt.subplots(2, 2, figsize=(11, 7), constrained_layout=True) + images = [] + for column, (side, grid) in enumerate((('left', left_grid), ('right', right_grid))): + raw = axes[0, column].imshow(grid, cmap="turbo", vmin=lower, vmax=upper) + images.append(raw) + axes[0, column].set_title(f"{side}: raw weights") + axes[0, column].set_xlabel("patch x") + axes[0, column].set_ylabel("patch y") + upsampled = cv2.resize(grid, (width, height), interpolation=cv2.INTER_CUBIC) + axes[1, column].imshow(image_rgb) + axes[1, column].imshow(upsampled, cmap="turbo", alpha=0.45, vmin=lower, vmax=upper) + axes[1, column].set_title(f"{side}: RGB overlay") + axes[1, column].axis("off") + fig.colorbar(images[0], ax=axes, shrink=0.82, label="raw head-averaged attention weight") + wrapped_title = textwrap.fill(title, width=95) + fig.suptitle(f"{wrapped_title}\nlast layer, head-averaged; visualization is not calibrated probability", fontsize=11) + fig.savefig(output, dpi=160) + plt.close(fig) + + +def save_camera_views( + output: Path, + predicted: np.ndarray, + target: np.ndarray, + valid_hands: np.ndarray, + title: str, +) -> None: + fig, axes = plt.subplots(1, 2, figsize=(12, 5), constrained_layout=True) + colors = ("#22a06b", "#e56b2f") + for axis, view_name, horizontal_index in zip(axes, ("front", "side"), (0, 2), strict=True): + for hand in range(2): + axis.scatter( + predicted[hand, :, horizontal_index], predicted[hand, :, 1], + s=4, alpha=0.35, c=colors[hand], label=f"{'LR'[hand]} pred", + ) + if valid_hands[hand]: + axis.scatter( + target[hand, :, horizontal_index], target[hand, :, 1], + s=4, alpha=0.22, c="black", label=f"{'LR'[hand]} GT", + ) + axis.set_xlabel("x (m)" if horizontal_index == 0 else "z (m)") + axis.set_ylabel("y (m)") + axis.set_title(f"{view_name}: {'x-y' if horizontal_index == 0 else 'z-y'}") + axis.legend(fontsize=7) + axis.set_aspect("equal", adjustable="datalim") + axis.invert_yaxis() + axis.grid(alpha=0.25) + fig.suptitle(textwrap.fill(title, width=105), fontsize=11) + fig.savefig(output, dpi=160) + plt.close(fig) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/__init__.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..202e66331920bb936a0aeacff8fc23a08071a85e --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/__init__.py @@ -0,0 +1,14 @@ +"""Camera and MANO geometry helpers.""" + +from .camera import depth_mm_to_m, intrinsics_from_h2o, project_points, unproject_depth +from .mano_translation import mano_raw_to_wrist, wrist_to_mano_raw + +__all__ = [ + "depth_mm_to_m", + "intrinsics_from_h2o", + "project_points", + "unproject_depth", + "mano_raw_to_wrist", + "wrist_to_mano_raw", +] + diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/camera.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..0f897cdebe7bd9cbd1a19c164a9b4909c72f6f4b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/camera.py @@ -0,0 +1,121 @@ +"""Camera-space geometry with explicit H2O units and image conventions.""" + +from __future__ import annotations + +from typing import overload + +import numpy as np +import torch + + +def intrinsics_from_h2o(values: np.ndarray) -> tuple[np.ndarray, tuple[int, int]]: + """Convert `fx fy cx cy width height` to K and `(height, width)`.""" + + values = np.asarray(values, dtype=np.float64).reshape(-1) + if values.size != 6: + raise ValueError(f"Expected 6 intrinsics values, got {values.size}") + fx, fy, cx, cy, width, height = values + if fx <= 0 or fy <= 0 or width <= 0 or height <= 0: + raise ValueError(f"Invalid intrinsics: {values.tolist()}") + K = np.array([[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]], dtype=np.float32) + return K, (int(round(height)), int(round(width))) + + +def depth_mm_to_m(depth_mm: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Convert released uint16 millimeter depth to metric depth plus validity.""" + + depth_m = np.asarray(depth_mm, dtype=np.float32) / 1000.0 + valid = np.isfinite(depth_m) & (depth_m > 0.0) + depth_m = np.where(valid, depth_m, 0.0).astype(np.float32) + return depth_m, valid + + +@overload +def project_points(points_camera: np.ndarray, K: np.ndarray) -> tuple[np.ndarray, np.ndarray]: ... + + +@overload +def project_points(points_camera: torch.Tensor, K: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: ... + + +def project_points(points_camera, K): + """Project x-right, y-down, z-forward camera points to image pixels.""" + + if isinstance(points_camera, torch.Tensor): + z = points_camera[..., 2] + safe_z = torch.where(z.abs() > 1e-8, z, torch.ones_like(z)) + fx, fy, cx, cy = K[..., 0, 0], K[..., 1, 1], K[..., 0, 2], K[..., 1, 2] + while fx.ndim < z.ndim: + fx, fy, cx, cy = (value.unsqueeze(-1) for value in (fx, fy, cx, cy)) + u = fx * points_camera[..., 0] / safe_z + cx + v = fy * points_camera[..., 1] / safe_z + cy + return torch.stack((u, v), dim=-1), z > 0 + + points = np.asarray(points_camera) + matrix = np.asarray(K) + z = points[..., 2] + safe_z = np.where(np.abs(z) > 1e-8, z, 1.0) + fx, fy, cx, cy = matrix[..., 0, 0], matrix[..., 1, 1], matrix[..., 0, 2], matrix[..., 1, 2] + while np.ndim(fx) < np.ndim(z): + fx, fy, cx, cy = (np.expand_dims(value, -1) for value in (fx, fy, cx, cy)) + u = fx * points[..., 0] / safe_z + cx + v = fy * points[..., 1] / safe_z + cy + return np.stack((u, v), axis=-1).astype(np.float32), z > 0 + + +def unproject_depth(depth_m: np.ndarray, K: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Unproject an HxW metric depth map to an HxWx3 camera-space point map.""" + + depth = np.asarray(depth_m, dtype=np.float32) + if depth.ndim != 2: + raise ValueError(f"Expected HxW depth, got {depth.shape}") + matrix = np.asarray(K, dtype=np.float32) + height, width = depth.shape + u, v = np.meshgrid(np.arange(width, dtype=np.float32), np.arange(height, dtype=np.float32)) + x = (u - matrix[0, 2]) * depth / matrix[0, 0] + y = (v - matrix[1, 2]) * depth / matrix[1, 1] + points = np.stack((x, y, depth), axis=-1) + valid = np.isfinite(depth) & (depth > 0.0) + points[~valid] = 0.0 + return points, valid + + +def resize_and_pad_intrinsics( + K: np.ndarray, + source_hw: tuple[int, int], + resized_hw: tuple[int, int], + pad_left_top: tuple[int, int] = (0, 0), +) -> np.ndarray: + """Update K for anisotropic resize followed by left/top pixel padding.""" + + source_h, source_w = source_hw + resized_h, resized_w = resized_hw + pad_left, pad_top = pad_left_top + if min(source_h, source_w, resized_h, resized_w) <= 0: + raise ValueError("Image sizes must be positive") + out = np.asarray(K, dtype=np.float32).copy() + sx = resized_w / source_w + sy = resized_h / source_h + out[0, 0] *= sx + out[0, 2] = out[0, 2] * sx + pad_left + out[1, 1] *= sy + out[1, 2] = out[1, 2] * sy + pad_top + return out + + +def patch_center_rays( + K: torch.Tensor, + grid_hw: tuple[int, int], + patch_size: int, +) -> torch.Tensor: + """Return unnormalized patch-center rays `[... , N, 3]`.""" + + grid_h, grid_w = grid_hw + dtype, device = K.dtype, K.device + u = (torch.arange(grid_w, dtype=dtype, device=device) + 0.5) * patch_size + v = (torch.arange(grid_h, dtype=dtype, device=device) + 0.5) * patch_size + vv, uu = torch.meshgrid(v, u, indexing="ij") + x = (uu.reshape(-1) - K[..., 0, 2].unsqueeze(-1)) / K[..., 0, 0].unsqueeze(-1) + y = (vv.reshape(-1) - K[..., 1, 2].unsqueeze(-1)) / K[..., 1, 1].unsqueeze(-1) + one = torch.ones_like(x) + return torch.stack((x, y, one), dim=-1) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/mano_compat.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/mano_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..92572790a447e15a1bed2ae8cfdec9473188276b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/mano_compat.py @@ -0,0 +1,26 @@ +"""Compatibility shim for the licensed MANO files and legacy chumpy loader.""" + +from __future__ import annotations + +import inspect + +import numpy as np + + +def enable_legacy_mano_loading() -> None: + """Restore names removed after the legacy MANO/chumpy release.""" + + if not hasattr(inspect, "getargspec"): + inspect.getargspec = inspect.getfullargspec # type: ignore[attr-defined] + aliases = { + "bool": bool, + "int": int, + "float": float, + "complex": complex, + "object": object, + "unicode": str, + "str": str, + } + for name, value in aliases.items(): + if name not in np.__dict__: + setattr(np, name, value) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/mano_translation.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/mano_translation.py new file mode 100644 index 0000000000000000000000000000000000000000..bd038e2956d172f29194b892244df021571b6ba5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/mano_translation.py @@ -0,0 +1,34 @@ +"""Conversion between H2O raw MANO translation and wrist/root translation.""" + +from __future__ import annotations + +import numpy as np +import torch + + +def mano_raw_to_wrist(raw_translation, mano_root_offset_m): + """Convert H2O raw MANO translation to camera-space MANO joint-0 position. + + H2OPlayer places native MANO joints using `joint_mm / 1000 + raw_translation`. + Therefore the wrist is the placed native joint 0, not the raw translation itself. + """ + + if isinstance(raw_translation, torch.Tensor): + return raw_translation + mano_root_offset_m + return np.asarray(raw_translation) + np.asarray(mano_root_offset_m) + + +def wrist_to_mano_raw(wrist_translation, mano_root_offset_m): + """Inverse of :func:`mano_raw_to_wrist`.""" + + if isinstance(wrist_translation, torch.Tensor): + return wrist_translation - mano_root_offset_m + return np.asarray(wrist_translation) - np.asarray(mano_root_offset_m) + + +def root_center_mano(vertices_m, joints_m): + """Root-center native MANO outputs while returning the removed root offset.""" + + root = joints_m[..., 0, :] + return vertices_m - root[..., None, :], joints_m - root[..., None, :], root + diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/mixed_projection.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/mixed_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..a80850e3c6eaa88fd7f1501e539f629638d881bb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/mixed_projection.py @@ -0,0 +1,167 @@ +"""Differentiable mixed-projection translation solve.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch + + +@dataclass(frozen=True) +class TorchMixedProjectionResult: + translation_m: torch.Tensor + support_count: torch.Tensor + residual_scale_px: torch.Tensor + conditioning: torch.Tensor + inlier_ratio: torch.Tensor + uncertainty_xy_m: torch.Tensor + success: torch.Tensor + + +def _masked_lower_median(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + """Return the deterministic lower median along the joint dimension.""" + + if values.ndim != 2 or mask.shape != values.shape: + raise ValueError("masked median expects equal [N,J] tensors") + counts = mask.sum(dim=1) + ordered = torch.sort( + torch.where(mask, values, torch.full_like(values, torch.inf)), dim=1, + ).values + indices = ((counts - 1).clamp_min(0) // 2)[:, None] + selected = ordered.gather(1, indices).squeeze(1) + return torch.where(counts > 0, selected, torch.full_like(selected, torch.inf)) + + +def solve_mixed_projection_translation( + root_relative_joints_m: torch.Tensor, + anchors_px: torch.Tensor, + K: torch.Tensor, + refined_z_m: torch.Tensor, + fallback_translation_m: torch.Tensor, + *, + image_hw: tuple[int, int], + K_available: torch.Tensor | None = None, + minimum_support: int = 4, + huber_delta_px: float = 16.0, + irls_iterations: int = 5, + minimum_joint_depth_m: float = 0.05, + denominator_epsilon: float = 1e-10, +) -> TorchMixedProjectionResult: + """Solve tx/ty while retaining gradients through geometry and robust weights.""" + + if root_relative_joints_m.shape[-2:] != (21, 3): + raise ValueError("root-relative joints must end in [21,3]") + if anchors_px.shape != (*root_relative_joints_m.shape[:-1], 2): + raise ValueError("anchor shape differs from joints") + if K.shape != (*root_relative_joints_m.shape[:-2], 3, 3): + raise ValueError("K shape differs from joints") + if refined_z_m.shape != root_relative_joints_m.shape[:-2]: + raise ValueError("z shape differs from joints") + if fallback_translation_m.shape != (*refined_z_m.shape, 3): + raise ValueError("fallback translation shape differs from z") + if not 1 <= minimum_support <= 21: + raise ValueError("minimum_support must be in [1,21]") + if huber_delta_px <= 0.0 or irls_iterations < 1: + raise ValueError("Huber delta and IRLS iterations must be positive") + height, width = image_hw + if height <= 0 or width <= 0: + raise ValueError("image dimensions must be positive") + + prefix = refined_z_m.shape + count = refined_z_m.numel() + joints = root_relative_joints_m.reshape(count, 21, 3) + anchors = anchors_px.reshape(count, 21, 2) + intrinsics = K.reshape(count, 3, 3) + z = refined_z_m.reshape(count) + fallback = fallback_translation_m.reshape(count, 3) + available = ( + torch.ones(count, dtype=torch.bool, device=z.device) + if K_available is None else K_available.reshape(count).bool() + ) + fx, fy = intrinsics[:, 0, 0], intrinsics[:, 1, 1] + cx, cy = intrinsics[:, 0, 2], intrinsics[:, 1, 2] + joint_z = joints[..., 2] + z[:, None] + finite_k = torch.isfinite(intrinsics).all(dim=-1).all(dim=-1) & (fx > 1e-8) & (fy > 1e-8) + mask = ( + available[:, None] + & finite_k[:, None] + & torch.isfinite(z)[:, None] + & torch.isfinite(joints).all(dim=-1) + & torch.isfinite(anchors).all(dim=-1) + & (joint_z > minimum_joint_depth_m) + & (anchors[..., 0] >= 0.0) + & (anchors[..., 0] <= width - 1.0) + & (anchors[..., 1] >= 0.0) + & (anchors[..., 1] <= height - 1.0) + ) + support = mask.sum(dim=1) + safe_depth = torch.where(mask, joint_z, torch.ones_like(joint_z)) + ax = torch.where(mask, fx[:, None] / safe_depth, torch.zeros_like(safe_depth)) + ay = torch.where(mask, fy[:, None] / safe_depth, torch.zeros_like(safe_depth)) + bx = anchors[..., 0] - cx[:, None] - fx[:, None] * joints[..., 0] / safe_depth + by = anchors[..., 1] - cy[:, None] - fy[:, None] * joints[..., 1] / safe_depth + bx = torch.where(mask, bx, torch.zeros_like(bx)) + by = torch.where(mask, by, torch.zeros_like(by)) + + def solve(weights: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + denom_x = (weights * ax.square()).sum(dim=1) + denom_y = (weights * ay.square()).sum(dim=1) + tx = (weights * ax * bx).sum(dim=1) / denom_x.clamp_min(denominator_epsilon) + ty = (weights * ay * by).sum(dim=1) / denom_y.clamp_min(denominator_epsilon) + return tx, ty, denom_x, denom_y + + weights = mask.to(joints.dtype) + tx, ty, denom_x, denom_y = solve(weights) + for _ in range(irls_iterations): + residual = torch.sqrt( + (ax * tx[:, None] - bx).square() + + (ay * ty[:, None] - by).square() + + 1e-12 + ) + robust = torch.clamp(huber_delta_px / residual, max=1.0) + weights = torch.where(mask, robust, torch.zeros_like(robust)) + tx, ty, denom_x, denom_y = solve(weights) + + residual = torch.sqrt( + (ax * tx[:, None] - bx).square() + + (ay * ty[:, None] - by).square() + + 1e-12 + ) + median = _masked_lower_median(residual, mask) + mad = _masked_lower_median(torch.abs(residual - median[:, None]), mask) + scale = torch.where(support > 0, 1.4826 * mad, torch.full_like(mad, torch.inf)) + inlier_ratio = torch.where( + support > 0, + (mask & (residual <= huber_delta_px)).sum(dim=1).to(joints.dtype) + / support.clamp_min(1).to(joints.dtype), + torch.zeros_like(z), + ) + conditioning = torch.minimum(denom_x, denom_y) / torch.maximum( + denom_x, denom_y, + ).clamp_min(denominator_epsilon) + uncertainty = torch.stack(( + scale / torch.sqrt(denom_x.clamp_min(denominator_epsilon)), + scale / torch.sqrt(denom_y.clamp_min(denominator_epsilon)), + ), dim=-1) + success = ( + available & finite_k & (support >= minimum_support) + & (denom_x > denominator_epsilon) & (denom_y > denominator_epsilon) + & torch.isfinite(tx) & torch.isfinite(ty) + ) + solved = torch.stack((tx, ty, z), dim=-1) + translation = torch.where(success[:, None], solved, fallback) + finite_z = torch.isfinite(z) + use_selected_z = available & finite_k & finite_z + translation = torch.cat(( + translation[:, :2], + torch.where(use_selected_z, z, fallback[:, 2])[:, None], + ), dim=-1) + return TorchMixedProjectionResult( + translation_m=translation.reshape(*prefix, 3), + support_count=support.reshape(prefix), + residual_scale_px=scale.reshape(prefix), + conditioning=conditioning.reshape(prefix), + inlier_ratio=inlier_ratio.reshape(prefix), + uncertainty_xy_m=uncertainty.reshape(*prefix, 2), + success=success.reshape(prefix), + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/rotations.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/rotations.py new file mode 100644 index 0000000000000000000000000000000000000000..560cfe1671fa464e9348d59b96dc44e392a32e71 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/geometry/rotations.py @@ -0,0 +1,55 @@ +"""Differentiable rotation representations used by prediction and losses.""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F + + +def rotation_6d_to_matrix(value: torch.Tensor) -> torch.Tensor: + if value.shape[-1] != 6: + raise ValueError(f"Expected rotation 6D, got {value.shape}") + first = F.normalize(value[..., :3], dim=-1) + second_raw = value[..., 3:] + second = F.normalize(second_raw - (first * second_raw).sum(dim=-1, keepdim=True) * first, dim=-1) + third = torch.cross(first, second, dim=-1) + return torch.stack((first, second, third), dim=-2) + + +def axis_angle_to_matrix(axis_angle: torch.Tensor) -> torch.Tensor: + """Rodrigues formula with a stable small-angle branch.""" + + if axis_angle.shape[-1] != 3: + raise ValueError(f"Expected axis-angle [...,3], got {axis_angle.shape}") + theta2 = (axis_angle * axis_angle).sum(dim=-1, keepdim=True) + theta = torch.sqrt(theta2.clamp_min(1e-16)) + a = torch.where(theta2 > 1e-8, torch.sin(theta) / theta, 1 - theta2 / 6 + theta2 * theta2 / 120) + # torch.where evaluates both branches, so the large-angle expression must + # also remain finite at exact zero for zero-initialized residual heads. + b = torch.where( + theta2 > 1e-8, + (1 - torch.cos(theta)) / theta2.clamp_min(1e-16), + 0.5 - theta2 / 24 + theta2 * theta2 / 720, + ) + x, y, z = axis_angle.unbind(dim=-1) + zero = torch.zeros_like(x) + skew = torch.stack((zero, -z, y, z, zero, -x, -y, x, zero), dim=-1).reshape(axis_angle.shape[:-1] + (3, 3)) + eye = torch.eye(3, dtype=axis_angle.dtype, device=axis_angle.device).expand(axis_angle.shape[:-1] + (3, 3)) + return eye + a.unsqueeze(-1) * skew + b.unsqueeze(-1) * (skew @ skew) + + +def matrix_to_axis_angle(matrix: torch.Tensor) -> torch.Tensor: + """Convert rotation matrices to axis-angle using a stable atan2 form.""" + + if matrix.shape[-2:] != (3, 3): + raise ValueError(f"Expected rotation matrices, got {matrix.shape}") + vector = torch.stack( + (matrix[..., 2, 1] - matrix[..., 1, 2], matrix[..., 0, 2] - matrix[..., 2, 0], matrix[..., 1, 0] - matrix[..., 0, 1]), + dim=-1, + ) + # The epsilon keeps the derivative of the norm finite at exact identity. + sin_angle = 0.5 * torch.sqrt((vector * vector).sum(dim=-1) + 1e-12) + cos_angle = 0.5 * (matrix.diagonal(dim1=-2, dim2=-1).sum(dim=-1) - 1) + angle = torch.atan2(sin_angle, cos_angle) + scale = angle / (2 * sin_angle) + return vector * scale[..., None] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/inference/__init__.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/inference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4e4eaa20d7002f3d29890cb7af9c24a735a8bf --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/inference/__init__.py @@ -0,0 +1,5 @@ +"""Length-generalized inference utilities.""" + +from .sequence import LengthGeneralizedInference, SequenceInferenceConfig + +__all__ = ["LengthGeneralizedInference", "SequenceInferenceConfig"] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/inference/sequence.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/inference/sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..288f7b6fd1e09d0af4e624ed4c62a1ac13fcc4cc --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/inference/sequence.py @@ -0,0 +1,212 @@ +"""Bounded-GPU-memory offline and causal sequence inference.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Iterable, Mapping + +import torch + + +@dataclass(frozen=True) +class SequenceInferenceConfig: + mode: str + window_size: int + offline_stride: int | None = None + stitching: str = "center" + + def __post_init__(self) -> None: + if self.mode not in {"offline", "causal"}: + raise ValueError(f"unknown sequence inference mode: {self.mode}") + if self.window_size < 1: + raise ValueError("window_size must be positive") + if self.offline_stride is not None and not 1 <= self.offline_stride <= self.window_size: + raise ValueError("offline_stride must be in [1, window_size]") + if self.stitching != "center": + raise ValueError("only fixed center stitching is registered") + + +class LengthGeneralizedInference: + """Run a model over a frame iterator without sequence-length GPU growth.""" + + _NON_TEMPORAL_OUTPUTS = { + "mano_shape_sequence", "coarse_mano_shape_sequence", "attention", + } + + def __init__( + self, + model: torch.nn.Module, + config: SequenceInferenceConfig, + *, + device: torch.device | str, + autocast_dtype: torch.dtype | None = None, + ) -> None: + self.model = model + self.config = config + self.device = torch.device(device) + self.autocast_dtype = autocast_dtype + model_config = getattr(model, "config", None) + attention_mode = getattr(model_config, "temporal_attention_mode", None) + if config.mode == "causal" and attention_mode != "causal": + raise ValueError( + "causal streaming requires temporal_attention_mode='causal'" + ) + self.maximum_resident_frames = 0 + self.maximum_input_buffer_frames = 0 + + @staticmethod + def _stack_frames(frames: list[Mapping[str, object]]) -> dict[str, object]: + if not frames: + raise ValueError("cannot stack an empty frame sequence") + output: dict[str, object] = {} + for key in frames[0]: + values = [frame[key] for frame in frames] + first = values[0] + if torch.is_tensor(first) and first.ndim >= 2 and first.shape[1] == 1: + if not all(torch.is_tensor(value) and value.shape[1] == 1 for value in values): + raise ValueError(f"inconsistent temporal field: {key}") + output[key] = torch.cat(values, dim=1) + else: + if torch.is_tensor(first) and not all( + torch.equal(first, value) for value in values[1:] + if torch.is_tensor(value) + ): + raise ValueError(f"non-temporal tensor changed within window: {key}") + output[key] = first + return output + + def _to_device(self, batch: Mapping[str, object]) -> dict[str, object]: + return { + key: value.to(self.device, non_blocking=True) if torch.is_tensor(value) else value + for key, value in batch.items() + } + + def _run_window(self, frames: list[Mapping[str, object]]) -> dict[str, object]: + self.maximum_resident_frames = max(self.maximum_resident_frames, len(frames)) + batch = self._to_device(self._stack_frames(frames)) + autocast_enabled = self.autocast_dtype is not None and self.device.type == "cuda" + with torch.inference_mode(), torch.autocast( + device_type=self.device.type, + dtype=self.autocast_dtype, + enabled=autocast_enabled, + ): + return self.model(batch) + + @classmethod + def _extract_frame( + cls, output: Mapping[str, object], index: int, time: int, + ) -> dict[str, torch.Tensor]: + frame: dict[str, torch.Tensor] = {} + for key, value in output.items(): + if ( + key not in cls._NON_TEMPORAL_OUTPUTS + and torch.is_tensor(value) + and value.ndim >= 2 + and value.shape[1] == time + ): + frame[key] = value[:, index : index + 1].detach().cpu() + if not frame: + raise ValueError("model output has no temporal tensors") + return frame + + @staticmethod + def _concatenate(frames: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]: + if not frames: + return {} + common = set.intersection(*(set(frame) for frame in frames)) + return { + key: torch.cat([frame[key] for frame in frames], dim=1) + for key in sorted(common) + } + + @staticmethod + def _window_starts(length: int, window: int, stride: int) -> list[int]: + if length <= window: + return [0] + starts = list(range(0, length - window + 1, stride)) + final = length - window + if starts[-1] != final: + starts.append(final) + return starts + + def infer_offline( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> dict[str, torch.Tensor]: + if self.config.mode != "offline": + raise ValueError("infer_offline requires mode='offline'") + window = self.config.window_size + stride = self.config.offline_stride or max(window // 2, 1) + buffer: list[Mapping[str, object]] = [] + buffer_start = 0 + total = 0 + next_start = 0 + last_start: int | None = None + selected: list[dict[str, torch.Tensor] | None] = [] + priority: list[int] = [] + + def run_window(start: int, local_frames: list[Mapping[str, object]]) -> None: + output = self._run_window(local_frames) + local_time = len(local_frames) + for local_index in range(local_time): + global_index = start + local_index + center_priority = min(local_index + 1, local_time - local_index) + if center_priority > priority[global_index]: + selected[global_index] = self._extract_frame( + output, local_index, local_time, + ) + priority[global_index] = center_priority + + for frame in frame_iterator: + buffer.append(frame) + selected.append(None) + priority.append(-1) + total += 1 + self.maximum_input_buffer_frames = max( + self.maximum_input_buffer_frames, len(buffer), + ) + while next_start + window <= total: + offset = next_start - buffer_start + run_window(next_start, buffer[offset : offset + window]) + last_start = next_start + next_start += stride + if last_start > buffer_start: + drop = last_start - buffer_start + del buffer[:drop] + buffer_start = last_start + if total == 0: + return {} + final_start = max(total - window, 0) + if last_start != final_start: + offset = final_start - buffer_start + run_window(final_start, buffer[offset:]) + if any(frame is None for frame in selected): + raise AssertionError("offline stitching omitted a frame") + return self._concatenate([frame for frame in selected if frame is not None]) + + def stream_causal( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> Iterable[dict[str, torch.Tensor]]: + if self.config.mode != "causal": + raise ValueError("stream_causal requires mode='causal'") + rolling: list[Mapping[str, object]] = [] + for frame in frame_iterator: + rolling.append(frame) + if len(rolling) > self.config.window_size: + rolling.pop(0) + self.maximum_input_buffer_frames = max( + self.maximum_input_buffer_frames, len(rolling), + ) + output = self._run_window(rolling) + yield self._extract_frame(output, len(rolling) - 1, len(rolling)) + + def infer_causal( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> dict[str, torch.Tensor]: + return self._concatenate(list(self.stream_causal(frame_iterator))) + + def infer( + self, frame_iterator: Iterable[Mapping[str, object]], + ) -> dict[str, torch.Tensor]: + if self.config.mode == "offline": + return self.infer_offline(frame_iterator) + return self.infer_causal(frame_iterator) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/__init__.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9cc5c23a03b9059a0eee77e5bb43735d2c70fcb3 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/__init__.py @@ -0,0 +1,3 @@ +from foundation_hand.models.bimanual import BimanualReconstructionModel, ModelConfig + +__all__ = ["BimanualReconstructionModel", "ModelConfig"] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/bimanual.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/bimanual.py new file mode 100644 index 0000000000000000000000000000000000000000..25095078c7f76f3c1f0987ca37b233e351645093 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/bimanual.py @@ -0,0 +1,1021 @@ +"""Unified RGB-D-K video bimanual reconstruction model.""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from pathlib import Path +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from foundation_hand.data.schema import input_availability +from foundation_hand.geometry.camera import patch_center_rays +from foundation_hand.geometry.mixed_projection import solve_mixed_projection_translation +from foundation_hand.geometry.rotations import axis_angle_to_matrix, rotation_6d_to_matrix +from foundation_hand.models.decoder import HandQueryDecoder +from foundation_hand.models.encoders import DepthGeometryEncoder, DinoV3Encoder, TinyPatchEncoder +from foundation_hand.models.mano import ManoCameraLayer +from foundation_hand.models.structured_hand import ( + FINGER_PARTS, + PALM_PART, + ROOT_PART, + StructuredHandRefinement, +) + + +@dataclass +class ModelConfig: + encoder: str = "dinov3" + dinov3_source: str | None = None + dinov3_weights: str | None = None + dinov3_model: str = "dinov3_vitb16" + dinov3_dim: int = 768 + dinov3_trainable_last_blocks: int = 0 + decoder_dim: int = 512 + decoder_layers: int = 3 + attention_heads: int = 8 + patch_size: int = 16 + decoder_mode: str = "alternating" + use_temporal: bool = True + use_depth: bool = True + depth_mode: str = "log_depth" + use_rays: bool = True + use_bimanual_interaction: bool = True + depth_gate_floor: float = 0.0 + depth_gate_mode: str = "learned" + depth_gate_fixed_value: float = 0.5 + modality_dropout_prob: float = 0.0 + temporal_position_mode: str = "none" + temporal_relative_bias_max_distance: int = 15 + temporal_attention_mode: str = "bidirectional" + predict_presence: bool = True + mano_root: str | None = None + require_mano: bool = False + mano_fix_left_shapedirs: bool = False + gradient_checkpointing: bool = False + oracle_crop_mode: str = "none" + freeze_coarse_for_oracle_crop: bool = False + structured_hand_refinement: bool = False + structured_refinement_detach_locations: bool = True + structured_refinement_deterministic_detached_sampling: bool = False + structured_deformable_samples: int = 4 + structured_refine_translation: bool = True + translation_parameterization: str = "direct_xyz" + mixed_projection_minimum_support: int = 4 + mixed_projection_huber_delta_px: float = 16.0 + mixed_projection_irls_iterations: int = 5 + ray_depth_residual_max_m: float = 0.20 + ray_depth_enable_residual: bool = True + ray_depth_confidence_initial_logit: float = -4.0 + ray_depth_sample_radius_px: float = 8.0 + ray_depth_minimum_support: int = 3 + joint2d_parameterization: str = "hand_token_linear" + heatmap_offset_enabled: bool = True + heatmap_use_depth: bool = True + + +class BimanualReconstructionModel(nn.Module): + def __init__(self, config: ModelConfig) -> None: + super().__init__() + self.config = config + if not 0.0 <= config.modality_dropout_prob < 1.0: + raise ValueError("modality_dropout_prob must be in [0, 1)") + if config.oracle_crop_mode not in { + "none", "oracle_rgb", "oracle_depth_k", "oracle_rgb_depth_k", + }: + raise ValueError(f"unknown oracle crop mode: {config.oracle_crop_mode}") + if config.freeze_coarse_for_oracle_crop and config.oracle_crop_mode == "none": + raise ValueError("coarse freezing requires an oracle crop mode") + if config.structured_hand_refinement and config.oracle_crop_mode != "none": + raise ValueError("structured and oracle crop refinement are mutually exclusive") + if config.translation_parameterization not in { + "direct_xyz", "mixed_projection", "ray_depth_residual", + }: + raise ValueError( + f"unknown translation parameterization: {config.translation_parameterization}" + ) + if config.joint2d_parameterization not in { + "hand_token_linear", "spatial_heatmap", + }: + raise ValueError( + f"unknown joint2d parameterization: {config.joint2d_parameterization}" + ) + if ( + config.translation_parameterization in { + "mixed_projection", "ray_depth_residual", + } + and (config.structured_hand_refinement or config.oracle_crop_mode != "none") + ): + raise ValueError( + "mixed projection cannot be combined with an existing refinement branch" + ) + if config.ray_depth_residual_max_m <= 0.0: + raise ValueError("ray-depth residual bound must be positive") + if config.ray_depth_sample_radius_px <= 0.0: + raise ValueError("ray-depth sample radius must be positive") + if config.ray_depth_minimum_support <= 0: + raise ValueError("ray-depth minimum support must be positive") + if config.encoder == "dinov3": + if config.dinov3_source is None or config.dinov3_weights is None: + raise ValueError("Formal DINOv3 encoder requires explicit official source and local pretrained weights") + self.rgb_encoder = DinoV3Encoder( + Path(config.dinov3_source), Path(config.dinov3_weights), config.dinov3_model, + config.decoder_dim, config.dinov3_dim, frozen=True, + trainable_last_blocks=config.dinov3_trainable_last_blocks, + ) + elif config.encoder == "tiny_debug": + self.rgb_encoder = TinyPatchEncoder(config.decoder_dim, config.patch_size) + else: + raise ValueError(f"Unknown encoder: {config.encoder}") + if config.use_depth: + self.depth_encoder = DepthGeometryEncoder(config.decoder_dim, config.patch_size, config.depth_mode) + if config.use_rays: + self.ray_encoder = nn.Sequential(nn.Linear(4, config.decoder_dim), nn.GELU(), nn.Linear(config.decoder_dim, config.decoder_dim)) + self.hand_queries = nn.Parameter(torch.randn(2, config.decoder_dim) * 0.02) + self.side_embedding = nn.Parameter(torch.randn(2, config.decoder_dim) * 0.02) + self.decoder = HandQueryDecoder( + config.decoder_dim, config.decoder_layers, config.attention_heads, + config.use_depth, config.use_temporal, config.use_bimanual_interaction, config.decoder_mode, + config.gradient_checkpointing, config.depth_gate_floor, + config.depth_gate_mode, config.depth_gate_fixed_value, + config.temporal_position_mode, config.temporal_relative_bias_max_distance, + config.temporal_attention_mode, + ) + self.joint2d_head = nn.Linear(config.decoder_dim, 42) + if config.joint2d_parameterization == "spatial_heatmap": + dim = config.decoder_dim + self.joint_localization_embedding = nn.Parameter( + torch.randn(2, 21, dim) * 0.02, + ) + self.joint_localization_query = nn.Linear(dim, dim) + self.joint_localization_feature = nn.Sequential( + nn.LayerNorm(dim), nn.Linear(dim, dim), + ) + self.joint_localization_offset = nn.Sequential( + nn.LayerNorm(dim * 2), nn.Linear(dim * 2, 2), + ) + nn.init.zeros_(self.joint_localization_offset[-1].weight) + nn.init.zeros_(self.joint_localization_offset[-1].bias) + self.rotation_head = nn.Linear(config.decoder_dim, 16 * 6) + self.translation_head = nn.Linear(config.decoder_dim, 3) + if config.translation_parameterization == "mixed_projection": + self.mixed_log_tz_head = nn.Linear(config.decoder_dim, 1) + if config.translation_parameterization == "ray_depth_residual": + self.ray_depth_log_z_head = nn.Linear(config.decoder_dim, 1) + ray_depth_feature_dim = config.decoder_dim * 2 + 8 + self.ray_depth_delta_head = nn.Sequential( + nn.LayerNorm(ray_depth_feature_dim), + nn.Linear(ray_depth_feature_dim, config.decoder_dim), nn.GELU(), + nn.Linear(config.decoder_dim, 1), + ) + self.ray_depth_confidence_head = nn.Sequential( + nn.LayerNorm(ray_depth_feature_dim), + nn.Linear(ray_depth_feature_dim, config.decoder_dim), nn.GELU(), + nn.Linear(config.decoder_dim, 1), + ) + nn.init.zeros_(self.ray_depth_delta_head[-1].weight) + nn.init.zeros_(self.ray_depth_delta_head[-1].bias) + nn.init.zeros_(self.ray_depth_confidence_head[-1].weight) + self.ray_depth_confidence_head[-1].bias.data.fill_( + config.ray_depth_confidence_initial_logit, + ) + self.presence_head = nn.Linear(config.decoder_dim, 1) if config.predict_presence else None + self.shape_score = nn.Linear(config.decoder_dim, 1) + self.shape_head = nn.Linear(config.decoder_dim, 10) + self.mano_layer = ( + ManoCameraLayer( + config.mano_root, + fix_left_shapedirs=config.mano_fix_left_shapedirs, + ) + if config.mano_root is not None else None + ) + if config.require_mano and self.mano_layer is None: + raise ValueError("Formal camera-space MANO training requires a licensed mano_root") + self._initialize_structured_refiner() + self._initialize_oracle_crop_refiner() + self._initialize_prediction_heads() + if config.translation_parameterization == "mixed_projection": + # Retained only as a frozen missing-K/invalid-solve teacher fallback. + for parameter in self.translation_head.parameters(): + parameter.requires_grad_(False) + if config.joint2d_parameterization == "spatial_heatmap": + for parameter in self.joint2d_head.parameters(): + parameter.requires_grad_(False) + if config.freeze_coarse_for_oracle_crop: + for name, parameter in self.named_parameters(): + if not name.startswith("oracle_crop_"): + parameter.requires_grad_(False) + + def _initialize_oracle_crop_refiner(self) -> None: + mode = self.config.oracle_crop_mode + if mode == "none": + return + use_rgb = mode in {"oracle_rgb", "oracle_rgb_depth_k"} + use_depth = mode in {"oracle_depth_k", "oracle_rgb_depth_k"} + if use_depth and not self.config.use_depth: + raise ValueError("oracle Depth+K refinement requires the coarse depth encoder") + feature_dim = self.config.decoder_dim * (1 + int(use_rgb) + int(use_depth)) + feature_dim += int(use_rgb) + int(use_depth) + if use_depth: + feature_dim += 4 + self.oracle_crop_fusion = nn.Sequential( + nn.LayerNorm(feature_dim), + nn.Linear(feature_dim, self.config.decoder_dim), + nn.GELU(), + nn.Linear(self.config.decoder_dim, self.config.decoder_dim), + nn.GELU(), + ) + if use_rgb: + self.oracle_crop_rotation_head = nn.Linear( + self.config.decoder_dim, 16 * 3, + ) + self.oracle_crop_shape_head = nn.Linear(self.config.decoder_dim, 10) + nn.init.zeros_(self.oracle_crop_rotation_head.weight) + nn.init.zeros_(self.oracle_crop_rotation_head.bias) + nn.init.zeros_(self.oracle_crop_shape_head.weight) + nn.init.zeros_(self.oracle_crop_shape_head.bias) + if use_depth: + self.oracle_crop_delta_z_head = nn.Linear(self.config.decoder_dim, 1) + nn.init.zeros_(self.oracle_crop_delta_z_head.weight) + nn.init.zeros_(self.oracle_crop_delta_z_head.bias) + + def _initialize_structured_refiner(self) -> None: + if not self.config.structured_hand_refinement: + return + dim = self.config.decoder_dim + self.structured_refiner = StructuredHandRefinement( + dim, self.config.attention_heads, use_depth=self.config.use_depth, + samples=self.config.structured_deformable_samples, + ) + self.structured_root_orientation_head = nn.Linear(dim, 3) + self.structured_finger_rotation_head = nn.Linear(dim, 3 * 3) + self.structured_translation_head = nn.Linear(dim, 3) + self.structured_shape_head = nn.Linear(dim, 10) + self.structured_root_2d_head = nn.Linear(dim, 2) + self.structured_finger_2d_head = nn.Linear(dim, 4 * 2) + for head in ( + self.structured_root_orientation_head, + self.structured_finger_rotation_head, + self.structured_translation_head, + self.structured_shape_head, + self.structured_root_2d_head, + self.structured_finger_2d_head, + ): + nn.init.zeros_(head.weight) + nn.init.zeros_(head.bias) + + def _initialize_prediction_heads(self) -> None: + """Start metric heads from finite, physically valid neutral predictions.""" + + identity_6d = torch.tensor((1.0, 0.0, 0.0, 0.0, 1.0, 0.0)) + with torch.no_grad(): + nn.init.zeros_(self.joint2d_head.weight) + nn.init.zeros_(self.joint2d_head.bias) + nn.init.zeros_(self.rotation_head.weight) + self.rotation_head.bias.copy_(identity_6d.repeat(16)) + nn.init.zeros_(self.translation_head.weight) + # softplus(inverse_softplus(0.6)) starts the wrist at z=0.6 m. + self.translation_head.bias.copy_(torch.tensor((0.0, 0.0, -0.19587037))) + if self.config.translation_parameterization == "mixed_projection": + nn.init.zeros_(self.mixed_log_tz_head.weight) + self.mixed_log_tz_head.bias.fill_(torch.log(torch.tensor(0.6))) + if self.config.translation_parameterization == "ray_depth_residual": + nn.init.zeros_(self.ray_depth_log_z_head.weight) + self.ray_depth_log_z_head.bias.fill_(torch.log(torch.tensor(0.6))) + nn.init.zeros_(self.shape_head.weight) + nn.init.zeros_(self.shape_head.bias) + if self.presence_head is not None: + nn.init.zeros_(self.presence_head.weight) + nn.init.zeros_(self.presence_head.bias) + + def forward(self, batch: dict[str, torch.Tensor]) -> dict[str, Any]: + rgb = batch["rgb"] + if rgb.ndim != 5: + raise ValueError(f"Expected RGB [B,T,3,H,W], got {rgb.shape}") + batch_size, time, _, height, width = rgb.shape + frame_valid = batch["frame_valid"].bool() + features = self.rgb_encoder(rgb.reshape(batch_size * time, 3, height, width)) + tokens = features.tokens + if "K" in batch: + K = batch["K"].reshape(batch_size * time, 3, 3).to(tokens.dtype) + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ).reshape(batch_size * time) + else: + K = torch.eye(3, dtype=tokens.dtype, device=tokens.device)[None].expand(batch_size * time, -1, -1) + K_available = torch.zeros(batch_size * time, dtype=torch.bool, device=tokens.device) + if self.training and self.config.modality_dropout_prob > 0.0 and self.config.use_rays: + keep_probability = 1.0 - self.config.modality_dropout_prob + K_available = K_available & ( + torch.rand(K_available.shape, device=K_available.device) < keep_probability + ) + if self.config.use_rays: + rays = patch_center_rays(K, features.grid_hw, features.patch_size) + availability = K_available.reshape(-1, 1, 1) + ray_inputs = torch.cat((rays, availability.expand(-1, rays.shape[1], 1).to(rays.dtype)), dim=-1) + tokens = tokens + self.ray_encoder(ray_inputs) * availability.to(tokens.dtype) + rgb_tokens = tokens.reshape(batch_size, time, tokens.shape[1], tokens.shape[2]) + + depth_tokens = None + depth_available = input_availability( + batch, + "depth_input_available", + "depth_available", + torch.zeros( + (batch_size, time), device=rgb.device, dtype=torch.bool, + ), + ) & frame_valid + # Training-only independent modality dropout tests fallback robustness without + # mutating the dataset availability contract or validation behavior. + if self.training and self.config.modality_dropout_prob > 0.0: + keep_probability = 1.0 - self.config.modality_dropout_prob + if self.config.use_depth: + depth_available = depth_available & ( + torch.rand(depth_available.shape, device=depth_available.device) < keep_probability + ) + if self.config.use_depth: + depth_m = batch.get("depth_m") + depth_pixel_valid = batch.get("depth_pixel_valid") + if depth_m is None or depth_pixel_valid is None: + depth_m = torch.zeros((batch_size, time, 1, height, width), dtype=rgb.dtype, device=rgb.device) + depth_pixel_valid = torch.zeros_like(depth_m, dtype=torch.bool) + depth_available = torch.zeros_like(frame_valid) + if self.config.depth_mode == "geometry": + depth_available = depth_available & K_available.reshape(batch_size, time) + depth_features = self.depth_encoder( + depth_m.reshape(batch_size * time, 1, height, width).to(tokens.dtype), + depth_pixel_valid.reshape(batch_size * time, 1, height, width), K, + ) + if depth_features.grid_hw != features.grid_hw: + raise ValueError(f"RGB/depth patch grids differ: {features.grid_hw} vs {depth_features.grid_hw}") + depth_tokens = depth_features.tokens.reshape(batch_size, time, depth_features.tokens.shape[1], depth_features.tokens.shape[2]) + + initial_query = ( + self.hand_queries + self.side_embedding + )[None, None].expand(batch_size, time, -1, -1) + rgb_only_query = None + rgb_only_attention = None + if self.config.translation_parameterization == "ray_depth_residual": + rgb_only_query, rgb_only_attention = self.decoder( + initial_query, rgb_tokens, None, frame_valid, + torch.zeros_like(depth_available), self.side_embedding[None], + ) + query, attention = self.decoder( + initial_query, rgb_tokens, depth_tokens, frame_valid, + depth_available, self.side_embedding[None], + ) + linear_joint2d_norm = torch.sigmoid( + self.joint2d_head(query).reshape(batch_size, time, 2, 21, 2) + ) + joint2d_output: dict[str, torch.Tensor] = {} + if self.config.joint2d_parameterization == "spatial_heatmap": + joint2d_norm, joint2d_output = self._spatial_joint2d( + query, rgb_tokens, depth_tokens, depth_available, + features.grid_hw, + ) + joint2d_output["joint2d_linear_teacher_norm"] = linear_joint2d_norm.detach() + else: + joint2d_norm = linear_joint2d_norm + rotations_6d = self.rotation_head(query).reshape(batch_size, time, 2, 16, 6) + translation_token = rgb_only_query if rgb_only_query is not None else query + translation_raw = self.translation_head(translation_token) + wrist_translation = torch.cat( + (translation_raw[..., :2], F.softplus(translation_raw[..., 2:3]) + 1e-4), dim=-1 + ) + + score = self.shape_score(query).squeeze(-1).masked_fill(~frame_valid[:, :, None], -torch.inf) + shape_weights = torch.softmax(score, dim=1) + pooled = (query * shape_weights[..., None]).sum(dim=1) + shape = self.shape_head(pooled) + rotation_matrices = rotation_6d_to_matrix(rotations_6d) + shape_sequence = shape + expanded_shape = shape[:, None].expand(-1, time, -1, -1) + refined_translation = wrist_translation + mixed_projection_output: dict[str, torch.Tensor] = {} + if self.config.translation_parameterization == "mixed_projection": + refined_translation, mixed_projection_output = self._apply_mixed_projection( + batch, query, joint2d_norm, rotation_matrices, expanded_shape, + wrist_translation, frame_valid, height=height, width=width, + ) + ray_depth_output: dict[str, torch.Tensor] = {} + if self.config.translation_parameterization == "ray_depth_residual": + if rgb_only_query is None: + raise RuntimeError("ray-depth translation requires an RGB-only query") + refined_translation, ray_depth_output = self._apply_ray_depth_translation( + batch, rgb_only_query, query, wrist_translation, frame_valid, + depth_available, height=height, width=width, + ) + ray_depth_output["rgb_only_translation_attention"] = rgb_only_attention + structured_output: dict[str, torch.Tensor] = {} + if self.config.structured_hand_refinement: + ( + joint2d_norm, rotation_matrices, shape_sequence, + expanded_shape, refined_translation, structured_output, + ) = self._apply_structured_refinement( + query, joint2d_norm, rgb_tokens, depth_tokens, features.grid_hw, + frame_valid, depth_available, rotation_matrices, shape, + expanded_shape, wrist_translation, shape_weights, + ) + oracle_output: dict[str, torch.Tensor] = {} + if self.config.oracle_crop_mode != "none": + rotation_matrices, shape_sequence, expanded_shape, refined_translation, oracle_output = ( + self._apply_oracle_crop_refinement( + batch, query, rotation_matrices, shape, expanded_shape, + wrist_translation, shape_weights, frame_valid, + depth_available, + ) + ) + output: dict[str, Any] = { + "hand_tokens": query, + "joint2d_norm": joint2d_norm, + "mano_rotations_6d": rotations_6d, + "mano_rotation_matrices": rotation_matrices, + "mano_shape_sequence": shape_sequence, + "mano_shape": expanded_shape, + "wrist_root_translation": refined_translation, + "shape_pool_weights": shape_weights, + "attention": attention, + "translation_parameterization": self.config.translation_parameterization, + "joint2d_parameterization": self.config.joint2d_parameterization, + **joint2d_output, + **mixed_projection_output, + **ray_depth_output, + **structured_output, + **oracle_output, + } + if self.presence_head is not None: + output["presence_logit"] = self.presence_head(query).squeeze(-1) + if self.mano_layer is not None: + if self.config.oracle_crop_mode != "none": + coarse_vertices, coarse_joints = self.mano_layer( + output["coarse_mano_rotation_matrices"], + output["coarse_mano_shape"], + output["coarse_wrist_root_translation"], + ) + output["coarse_vertices_camera"] = coarse_vertices + output["coarse_joints_camera"] = coarse_joints + vertices, joints = self.mano_layer( + output["mano_rotation_matrices"], output["mano_shape"], output["wrist_root_translation"] + ) + output["vertices_camera"] = vertices + output["joints_camera"] = joints + return output + + def _spatial_joint2d( + self, + hand_tokens: torch.Tensor, + rgb_tokens: torch.Tensor, + depth_tokens: torch.Tensor | None, + depth_available: torch.Tensor, + grid_hw: tuple[int, int], + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + spatial = rgb_tokens + if self.config.heatmap_use_depth and depth_tokens is not None: + spatial = spatial + 0.5 * depth_tokens * depth_available[ + :, :, None, None + ].to(depth_tokens.dtype) + spatial = self.joint_localization_feature(spatial) + joint_query = self.joint_localization_query(hand_tokens)[..., None, :] + joint_query = joint_query + self.joint_localization_embedding[None, None] + logits = torch.einsum( + "bthjd,btsd->bthjs", joint_query, spatial, + ) / (spatial.shape[-1] ** 0.5) + probability_float = torch.softmax(logits.float(), dim=-1) + probabilities = probability_float.to(spatial.dtype) + grid_height, grid_width = grid_hw + if grid_height * grid_width != spatial.shape[-2]: + raise ValueError("joint heatmap grid differs from encoded feature grid") + rows, columns = torch.meshgrid( + torch.arange(grid_height, device=spatial.device), + torch.arange(grid_width, device=spatial.device), indexing="ij", + ) + centers = torch.stack(( + (columns.reshape(-1) + 0.5) / grid_width, + (rows.reshape(-1) + 0.5) / grid_height, + ), dim=-1).to(dtype=probability_float.dtype) + coordinates = torch.einsum("bthjs,sd->bthjd", probability_float, centers) + pooled = torch.einsum("bthjs,btsd->bthjd", probabilities, spatial) + raw_offset = self.joint_localization_offset(torch.cat((joint_query, pooled), dim=-1)) + patch_scale = raw_offset.new_tensor((1.0 / grid_width, 1.0 / grid_height)) + offset = ( + torch.tanh(raw_offset) * patch_scale + if self.config.heatmap_offset_enabled else torch.zeros_like(raw_offset) + ) + coordinates = (coordinates + offset).clamp(0.0, 1.0) + probability_float = probability_float.clamp_min(1e-12) + entropy = -( + probability_float * probability_float.log() + ).sum(dim=-1) / math.log(float(spatial.shape[-2])) + return coordinates, { + "joint2d_heatmap_logits": logits, + "joint2d_heatmap_entropy": entropy, + "joint2d_heatmap_confidence": 1.0 - entropy, + "joint2d_heatmap_offset_norm": offset, + } + + def initialize_mixed_log_tz_from_direct_head( + self, reference_raw: float = -0.19587037, + ) -> None: + """Linearize log(softplus(x)) around the historical 0.6 m prior.""" + + if self.config.translation_parameterization != "mixed_projection": + raise RuntimeError("mixed log-tz initialization requires mixed projection") + reference = self.translation_head.bias.new_tensor(reference_raw) + reference_depth = F.softplus(reference) + 1e-4 + slope = torch.sigmoid(reference) / reference_depth + with torch.no_grad(): + self.mixed_log_tz_head.weight.copy_( + slope * self.translation_head.weight[2:3] + ) + self.mixed_log_tz_head.bias.copy_( + torch.log(reference_depth) + + slope * (self.translation_head.bias[2:3] - reference) + ) + + def initialize_ray_depth_from_direct_head( + self, reference_raw: float = -0.19587037, + ) -> None: + """Warm-start RGB base-z while retaining the direct no-K fallback.""" + + if self.config.translation_parameterization != "ray_depth_residual": + raise RuntimeError("ray-depth initialization requires ray_depth_residual") + reference = self.translation_head.bias.new_tensor(reference_raw) + reference_depth = F.softplus(reference) + 1e-4 + slope = torch.sigmoid(reference) / reference_depth + with torch.no_grad(): + self.ray_depth_log_z_head.weight.copy_( + slope * self.translation_head.weight[2:3] + ) + self.ray_depth_log_z_head.bias.copy_( + torch.log(reference_depth) + + slope * (self.translation_head.bias[2:3] - reference) + ) + + def _sample_local_depth_statistics( + self, + batch: dict[str, torch.Tensor], + wrist_norm: torch.Tensor, + base_z: torch.Tensor, + available: torch.Tensor, + *, + height: int, + width: int, + ) -> tuple[torch.Tensor, torch.Tensor]: + """Sample a deterministic 3x3 metric-depth stencil at predicted wrists.""" + + batch_size, time, hands = wrist_norm.shape[:3] + depth = batch.get("depth_m") + valid_image = batch.get("depth_pixel_valid") + if depth is None or valid_image is None: + statistics = base_z.new_zeros(batch_size, time, hands, 8) + support = torch.zeros_like(base_z, dtype=torch.long) + return statistics, support + radius = float(self.config.ray_depth_sample_radius_px) + offsets = wrist_norm.new_tensor([ + (-radius, -radius), (0.0, -radius), (radius, -radius), + (-radius, 0.0), (0.0, 0.0), (radius, 0.0), + (-radius, radius), (0.0, radius), (radius, radius), + ]) + offset_norm = offsets * offsets.new_tensor((2.0 / width, 2.0 / height)) + grid = wrist_norm[..., None, :] * 2.0 - 1.0 + offset_norm + in_frame = (grid.abs() <= 1.0).all(dim=-1) + grid = grid.reshape(batch_size * time, hands * 9, 1, 2).float() + sampled_depth = F.grid_sample( + depth.reshape(batch_size * time, 1, height, width).float(), + grid, mode="nearest", padding_mode="zeros", align_corners=False, + ).reshape(batch_size, time, hands, 9) + sampled_valid = F.grid_sample( + valid_image.reshape(batch_size * time, 1, height, width).float(), + grid, mode="nearest", padding_mode="zeros", align_corners=False, + ).reshape(batch_size, time, hands, 9) > 0.5 + valid = ( + sampled_valid & in_frame & available[..., None, None] + & torch.isfinite(sampled_depth) & (sampled_depth > 0.02) + & (sampled_depth < 3.0) + ) + support = valid.sum(dim=-1) + safe = torch.where(valid, sampled_depth, torch.zeros_like(sampled_depth)) + denominator = support.clamp_min(1).to(base_z.dtype) + mean = safe.sum(dim=-1) / denominator + variance = ( + torch.where(valid, (sampled_depth - mean[..., None]).square(), + torch.zeros_like(sampled_depth)).sum(dim=-1) + / denominator + ) + nan_values = torch.where( + valid, sampled_depth, + torch.full_like(sampled_depth, float("nan")), + ) + median = torch.nanmedian(nan_values, dim=-1).values + minimum = torch.where( + valid, sampled_depth, torch.full_like(sampled_depth, float("inf")), + ).min(dim=-1).values + maximum = torch.where( + valid, sampled_depth, torch.full_like(sampled_depth, float("-inf")), + ).max(dim=-1).values + any_valid = support > 0 + median = torch.where(any_valid, median, torch.zeros_like(median)) + minimum = torch.where(any_valid, minimum, torch.zeros_like(minimum)) + maximum = torch.where(any_valid, maximum, torch.zeros_like(maximum)) + statistics = torch.stack(( + support.to(base_z.dtype) / 9.0, + median, median - base_z, minimum, maximum, + maximum - minimum, mean, variance.clamp_min(0.0).sqrt(), + ), dim=-1).to(base_z.dtype) + return statistics, support + + def _apply_ray_depth_translation( + self, + batch: dict[str, torch.Tensor], + rgb_query: torch.Tensor, + fused_query: torch.Tensor, + direct_fallback: torch.Tensor, + frame_valid: torch.Tensor, + depth_available: torch.Tensor, + *, + height: int, + width: int, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + wrist_norm = torch.sigmoid( + self.joint2d_head(rgb_query).reshape(*rgb_query.shape[:3], 21, 2) + )[..., 0, :] + log_base_z = self.ray_depth_log_z_head(rgb_query).squeeze(-1).clamp(-3.0, 1.0) + base_z = torch.exp(log_base_z) + if "K" in batch: + K = batch["K"].to(rgb_query.dtype) + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ) & frame_valid + else: + K = torch.eye( + 3, dtype=rgb_query.dtype, device=rgb_query.device, + )[None, None].expand(*frame_valid.shape, -1, -1) + K_available = torch.zeros_like(frame_valid) + usable_depth = depth_available & K_available + statistics, support = self._sample_local_depth_statistics( + batch, wrist_norm, base_z, usable_depth, + height=height, width=width, + ) + features = torch.cat((rgb_query, fused_query - rgb_query, statistics), dim=-1) + raw_delta = float(self.config.ray_depth_residual_max_m) * torch.tanh( + self.ray_depth_delta_head(features).squeeze(-1) + ) + confidence_logit = self.ray_depth_confidence_head(features).squeeze(-1) + correction_valid = ( + usable_depth[:, :, None] + & (support >= int(self.config.ray_depth_minimum_support)) + ) + if not self.config.ray_depth_enable_residual: + correction_valid = torch.zeros_like(correction_valid) + confidence = torch.where( + correction_valid, torch.sigmoid(confidence_logit), + torch.zeros_like(confidence_logit), + ) + delta = torch.where(correction_valid, raw_delta, torch.zeros_like(raw_delta)) + refined_z = (base_z + confidence * delta).clamp(0.05, 3.0) + u = wrist_norm[..., 0] * float(width) + v = wrist_norm[..., 1] * float(height) + fx = K[..., 0, 0][:, :, None].clamp_min(1e-6) + fy = K[..., 1, 1][:, :, None].clamp_min(1e-6) + cx = K[..., 0, 2][:, :, None] + cy = K[..., 1, 2][:, :, None] + ray_x = (u - cx) / fx + ray_y = (v - cy) / fy + assembled = torch.stack((ray_x * refined_z, ray_y * refined_z, refined_z), dim=-1) + use_ray = K_available[:, :, None, None] & frame_valid[:, :, None, None] + translation = torch.where(use_ray, assembled, direct_fallback) + translation = torch.where( + frame_valid[:, :, None, None], translation, + torch.zeros_like(translation), + ) + return translation, { + "ray_depth_wrist2d_norm": wrist_norm, + "ray_depth_log_base_z": log_base_z, + "ray_depth_base_z_m": base_z, + "ray_depth_raw_delta_z_m": delta, + "ray_depth_applied_delta_z_m": confidence * delta, + "ray_depth_confidence_logit": confidence_logit, + "ray_depth_confidence": confidence, + "ray_depth_local_statistics": statistics, + "ray_depth_support_count": support, + "ray_depth_correction_valid": correction_valid, + "ray_depth_K_input_available": K_available, + "ray_depth_direct_fallback_translation": direct_fallback, + } + + def _apply_mixed_projection( + self, + batch: dict[str, torch.Tensor], + hand_tokens: torch.Tensor, + joint2d_norm: torch.Tensor, + rotation_matrices: torch.Tensor, + expanded_shape: torch.Tensor, + direct_translation: torch.Tensor, + frame_valid: torch.Tensor, + *, + height: int, + width: int, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + if self.mano_layer is None: + raise RuntimeError("mixed projection requires the MANO camera layer") + log_tz = self.mixed_log_tz_head(hand_tokens).squeeze(-1).clamp(-3.0, 1.0) + tz = torch.exp(log_tz) + zero_translation = torch.zeros_like(direct_translation) + _, canonical_joints = self.mano_layer( + rotation_matrices, expanded_shape, zero_translation, + ) + root_relative_joints = canonical_joints - canonical_joints[..., :1, :] + anchors_px = joint2d_norm * joint2d_norm.new_tensor((width, height)) + if "K" in batch: + K = batch["K"].to(joint2d_norm.dtype) + K_available = input_availability( + batch, "K_input_available", "K_available", frame_valid, + ) & frame_valid + else: + K = torch.eye( + 3, dtype=joint2d_norm.dtype, device=joint2d_norm.device, + )[None, None].expand(*frame_valid.shape, -1, -1) + K_available = torch.zeros_like(frame_valid) + K = K[:, :, None].expand(-1, -1, 2, -1, -1) + K_available = K_available[:, :, None].expand(-1, -1, 2) + result = solve_mixed_projection_translation( + root_relative_joints, anchors_px, K, tz, direct_translation, + image_hw=(height, width), K_available=K_available, + minimum_support=self.config.mixed_projection_minimum_support, + huber_delta_px=self.config.mixed_projection_huber_delta_px, + irls_iterations=self.config.mixed_projection_irls_iterations, + ) + translation = torch.where( + frame_valid[:, :, None, None], + result.translation_m, + torch.zeros_like(result.translation_m), + ) + return translation, { + "mixed_projection_log_tz": log_tz, + "mixed_projection_direct_teacher_translation": direct_translation.detach(), + "mixed_projection_support_count": result.support_count, + "mixed_projection_residual_scale_px": result.residual_scale_px, + "mixed_projection_conditioning": result.conditioning, + "mixed_projection_inlier_ratio": result.inlier_ratio, + "mixed_projection_uncertainty_xy_m": result.uncertainty_xy_m, + "mixed_projection_success": result.success, + } + + def _apply_structured_refinement( + self, + coarse_hand_tokens: torch.Tensor, + coarse_joint2d_norm: torch.Tensor, + rgb_tokens: torch.Tensor, + depth_tokens: torch.Tensor | None, + grid_hw: tuple[int, int], + frame_valid: torch.Tensor, + depth_available: torch.Tensor, + coarse_rotations: torch.Tensor, + coarse_shape_sequence: torch.Tensor, + coarse_shape: torch.Tensor, + coarse_translation: torch.Tensor, + shape_pool_weights: torch.Tensor, + ) -> tuple[ + torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, + dict[str, torch.Tensor], + ]: + part_tokens, diagnostics = self.structured_refiner( + coarse_hand_tokens, coarse_joint2d_norm, rgb_tokens, depth_tokens, + grid_hw, frame_valid, depth_available, + detach_locations=self.config.structured_refinement_detach_locations, + deterministic_detached_sampling=( + self.config.structured_refinement_deterministic_detached_sampling + ), + ) + root_token = part_tokens[..., ROOT_PART, :] + palm_token = part_tokens[..., PALM_PART, :] + finger_tokens = part_tokens[..., FINGER_PARTS, :] + + root_rotation_delta = self._bounded_axis_angle( + self.structured_root_orientation_head(root_token), + ) + finger_rotation_delta = self._bounded_axis_angle( + self.structured_finger_rotation_head(finger_tokens).reshape( + *finger_tokens.shape[:-1], 3, 3, + ) + ) + rotation_delta = torch.cat(( + root_rotation_delta[..., None, :], + finger_rotation_delta.reshape(*finger_rotation_delta.shape[:3], 15, 3), + ), dim=-2) + rotation_delta = rotation_delta * frame_valid[ + :, :, None, None, None + ].to(rotation_delta.dtype) + refined_rotations = self._compose_rotation_residual( + coarse_rotations, rotation_delta, + ) + + if self.config.structured_refine_translation: + translation_raw = self.structured_translation_head(root_token) + translation_scale = torch.tensor( + (0.05, 0.05, 0.12), dtype=translation_raw.dtype, + device=translation_raw.device, + ) + translation_delta = translation_scale * translation_raw / torch.sqrt( + 1.0 + translation_raw.square(), + ) + translation_delta = translation_delta * frame_valid[ + :, :, None, None + ].to(translation_delta.dtype) + else: + translation_delta = torch.zeros_like(coarse_translation) + refined_translation = coarse_translation + translation_delta + + raw_shape_delta = torch.tanh(self.structured_shape_head(palm_token)) + shape_delta = ( + raw_shape_delta * shape_pool_weights[..., None] + ).sum(dim=1) + refined_shape_sequence = coarse_shape_sequence + shape_delta + refined_shape = coarse_shape + shape_delta[:, None] + + joint2d_delta = torch.zeros_like(coarse_joint2d_norm) + joint2d_delta[..., 0, :] = self.structured_root_2d_head(root_token) + joint2d_delta[..., 1:, :] = self.structured_finger_2d_head( + finger_tokens, + ).reshape(*finger_tokens.shape[:3], 20, 2) + joint2d_delta = 0.1 * torch.tanh(joint2d_delta) + joint2d_delta = joint2d_delta * frame_valid[ + :, :, None, None, None + ].to(joint2d_delta.dtype) + refined_joint2d = (coarse_joint2d_norm + joint2d_delta).clamp(0.0, 1.0) + return ( + refined_joint2d, refined_rotations, refined_shape_sequence, + refined_shape, refined_translation, + { + "coarse_joint2d_norm": coarse_joint2d_norm, + "coarse_mano_rotation_matrices": coarse_rotations, + "coarse_mano_shape_sequence": coarse_shape_sequence, + "coarse_mano_shape": coarse_shape, + "coarse_wrist_root_translation": coarse_translation, + "structured_part_tokens": part_tokens, + "structured_rotation_delta_axis_angle": rotation_delta, + "structured_translation_delta": translation_delta, + "structured_shape_delta": shape_delta, + "structured_joint2d_delta": joint2d_delta, + **diagnostics, + }, + ) + + @staticmethod + def _bounded_axis_angle(raw: torch.Tensor, maximum_radians: float = 0.35) -> torch.Tensor: + denominator = torch.sqrt(1.0 + (raw * raw).sum(dim=-1, keepdim=True)) + return maximum_radians * raw / denominator + + @staticmethod + def _compose_rotation_residual( + coarse: torch.Tensor, delta_axis_angle: torch.Tensor, + ) -> torch.Tensor: + delta_matrix = axis_angle_to_matrix(delta_axis_angle) + identity = torch.eye( + 3, dtype=delta_matrix.dtype, device=delta_matrix.device, + ) + # This is algebraically coarse @ delta_matrix, but its zero-residual + # path is coarse + coarse @ 0. Direct BF16 coarse @ I can re-round the + # coarse matrix and violate the registered exact initialization gate. + return coarse + coarse @ (delta_matrix - identity) + + def _apply_oracle_crop_refinement( + self, + batch: dict[str, torch.Tensor], + coarse_hand_tokens: torch.Tensor, + coarse_rotations: torch.Tensor, + coarse_shape_sequence: torch.Tensor, + coarse_shape: torch.Tensor, + coarse_translation: torch.Tensor, + shape_pool_weights: torch.Tensor, + frame_valid: torch.Tensor, + coarse_depth_available: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]: + required = {"oracle_crop_available"} + mode = self.config.oracle_crop_mode + use_rgb = mode in {"oracle_rgb", "oracle_rgb_depth_k"} + use_depth = mode in {"oracle_depth_k", "oracle_rgb_depth_k"} + if use_rgb: + required.add("oracle_crop_rgb") + if use_depth: + required.update({ + "oracle_crop_depth_m", "oracle_crop_depth_pixel_valid", + "oracle_crop_depth_available", "oracle_crop_K", + }) + missing = sorted(required - batch.keys()) + if missing: + raise ValueError(f"oracle crop mode requires batch fields: {missing}") + + batch_size, time, hands, dim = coarse_hand_tokens.shape + if hands != 2: + raise ValueError("oracle crop refinement expects two hand tokens") + roi_available = batch["oracle_crop_available"].bool() & frame_valid[:, :, None] + parts = [coarse_hand_tokens] + availability_parts = [] + rgb_available = roi_available if use_rgb else torch.zeros_like(roi_available) + if use_rgb: + local_rgb = batch["oracle_crop_rgb"] + if local_rgb.shape[:3] != (batch_size, time, hands): + raise ValueError(f"unexpected oracle RGB crop shape: {local_rgb.shape}") + local_hw = local_rgb.shape[-2:] + rgb_features = self.rgb_encoder( + local_rgb.reshape(batch_size * time * hands, 3, *local_hw), + ) + rgb_token = rgb_features.tokens.mean(dim=1).reshape( + batch_size, time, hands, dim, + ) + parts.append(rgb_token * rgb_available[..., None].to(rgb_token.dtype)) + availability_parts.append(rgb_available[..., None].to(rgb_token.dtype)) + + depth_available = torch.zeros_like(roi_available) + if use_depth: + local_depth = batch["oracle_crop_depth_m"] + local_valid = batch["oracle_crop_depth_pixel_valid"].bool() + local_K = batch["oracle_crop_K"].to(coarse_hand_tokens.dtype) + local_hw = local_depth.shape[-2:] + expected_prefix = (batch_size, time, hands) + if local_depth.shape[:3] != expected_prefix or local_K.shape[:3] != expected_prefix: + raise ValueError("unexpected oracle depth/K crop shape") + depth_available = ( + batch["oracle_crop_depth_available"].bool() + & roi_available + & coarse_depth_available[:, :, None] + ) + identity_K = torch.eye( + 3, dtype=local_K.dtype, device=local_K.device, + ).expand_as(local_K) + safe_local_K = torch.where( + depth_available[..., None, None], local_K, identity_K, + ) + depth_features = self.depth_encoder( + local_depth.reshape(batch_size * time * hands, 1, *local_hw).to(coarse_hand_tokens.dtype), + local_valid.reshape(batch_size * time * hands, 1, *local_hw), + safe_local_K.reshape(batch_size * time * hands, 3, 3), + ) + depth_token = depth_features.tokens.mean(dim=1).reshape( + batch_size, time, hands, dim, + ) + parts.append(depth_token * depth_available[..., None].to(depth_token.dtype)) + normalized_K = torch.stack(( + safe_local_K[..., 0, 0] / local_hw[1], + safe_local_K[..., 1, 1] / local_hw[0], + safe_local_K[..., 0, 2] / local_hw[1], + safe_local_K[..., 1, 2] / local_hw[0], + ), dim=-1) + parts.append(normalized_K * depth_available[..., None].to(normalized_K.dtype)) + availability_parts.append(depth_available[..., None].to(depth_token.dtype)) + parts.extend(availability_parts) + fused = self.oracle_crop_fusion(torch.cat(parts, dim=-1)) + + refined_rotations = coarse_rotations + refined_shape_sequence = coarse_shape_sequence + refined_shape = coarse_shape + rotation_delta = torch.zeros( + (*coarse_rotations.shape[:-2], 3), + dtype=coarse_rotations.dtype, device=coarse_rotations.device, + ) + shape_delta = torch.zeros_like(coarse_shape_sequence) + if use_rgb: + raw_rotation = self.oracle_crop_rotation_head(fused).reshape( + batch_size, time, hands, 16, 3, + ) + rotation_delta = self._bounded_axis_angle(raw_rotation) + rotation_delta = rotation_delta * rgb_available[..., None, None].to(rotation_delta.dtype) + refined_rotations = self._compose_rotation_residual( + coarse_rotations, rotation_delta, + ) + raw_shape = torch.tanh(self.oracle_crop_shape_head(fused)) + weights = shape_pool_weights * rgb_available.to(shape_pool_weights.dtype) + weights = weights / weights.sum(dim=1, keepdim=True).clamp_min(1e-8) + shape_delta = (raw_shape * weights[..., None]).sum(dim=1) + shape_delta = shape_delta * rgb_available.any(dim=1)[..., None].to(shape_delta.dtype) + refined_shape_sequence = coarse_shape_sequence + shape_delta + refined_shape = refined_shape_sequence[:, None].expand(-1, time, -1, -1) + + delta_z = torch.zeros_like(coarse_translation[..., 2:3]) + if use_depth: + delta_z = 0.15 * torch.tanh(self.oracle_crop_delta_z_head(fused)) + delta_z = delta_z * depth_available[..., None].to(delta_z.dtype) + refined_translation = coarse_translation + torch.cat( + (torch.zeros_like(coarse_translation[..., :2]), delta_z), dim=-1, + ) + return ( + refined_rotations, + refined_shape_sequence, + refined_shape, + refined_translation, + { + "coarse_mano_rotation_matrices": coarse_rotations, + "coarse_mano_shape_sequence": coarse_shape_sequence, + "coarse_mano_shape": coarse_shape, + "coarse_wrist_root_translation": coarse_translation, + "oracle_crop_rotation_delta_axis_angle": rotation_delta, + "oracle_crop_shape_delta": shape_delta, + "oracle_crop_delta_z": delta_z, + "oracle_crop_rgb_available": rgb_available, + "oracle_crop_depth_available_effective": depth_available, + }, + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/decoder.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..2031cad4d2a5790f82da07dec1958f33f6153c71 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/decoder.py @@ -0,0 +1,267 @@ +"""Factorized spatial-temporal semantic hand-query decoder.""" + +from __future__ import annotations + +from typing import Any + +import torch +from torch import nn +from torch.utils.checkpoint import checkpoint + + +class SpatialUpdate(nn.Module): + def __init__( + self, + dim: int, + heads: int, + use_depth: bool, + use_bimanual: bool, + depth_gate_floor: float, + depth_gate_mode: str, + depth_gate_fixed_value: float, + ) -> None: + super().__init__() + self.query_norm = nn.LayerNorm(dim) + self.rgb_norm = nn.LayerNorm(dim) + self.rgb_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.use_bimanual = use_bimanual + if use_bimanual: + self.hand_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.use_depth = use_depth + if not 0.0 <= depth_gate_floor < 1.0: + raise ValueError(f"depth_gate_floor must be in [0,1), got {depth_gate_floor}") + if depth_gate_mode not in {"learned", "fixed"}: + raise ValueError(f"Unknown depth_gate_mode: {depth_gate_mode}") + if not 0.0 <= depth_gate_fixed_value <= 1.0: + raise ValueError(f"depth_gate_fixed_value must be in [0,1], got {depth_gate_fixed_value}") + self.depth_gate_floor = depth_gate_floor + self.depth_gate_mode = depth_gate_mode + self.depth_gate_fixed_value = depth_gate_fixed_value + if use_depth: + self.depth_norm = nn.LayerNorm(dim) + self.depth_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.depth_gate = nn.Sequential(nn.Linear(dim * 2, dim), nn.GELU(), nn.Linear(dim, 1)) + nn.init.zeros_(self.depth_gate[-1].weight) + nn.init.zeros_(self.depth_gate[-1].bias) + self.ffn = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim * 4), nn.GELU(), nn.Linear(dim * 4, dim)) + + def forward( + self, + queries: torch.Tensor, + rgb: torch.Tensor, + depth: torch.Tensor | None, + depth_available: torch.Tensor, + side_bias: torch.Tensor, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + q = self.query_norm(queries + side_bias) + if self.use_bimanual: + hand_delta, _ = self.hand_attention(q, q, q, need_weights=False) + queries = queries + hand_delta + q = self.query_norm(queries + side_bias) + rgb_delta, rgb_attention = self.rgb_attention(q, self.rgb_norm(rgb), self.rgb_norm(rgb), need_weights=True) + queries = queries + rgb_delta + aux: dict[str, torch.Tensor] = { + "rgb_cross_attention": rgb_attention, + "rgb_update_norm": torch.linalg.vector_norm(rgb_delta, dim=-1), + } + if self.use_depth and depth is not None: + q = self.query_norm(queries + side_bias) + depth_delta, depth_attention = self.depth_attention(q, self.depth_norm(depth), self.depth_norm(depth), need_weights=True) + if self.depth_gate_mode == "fixed": + raw_gate = torch.full_like(depth_delta[..., :1], self.depth_gate_fixed_value) + else: + raw_gate = torch.sigmoid(self.depth_gate(torch.cat((q, depth_delta), dim=-1))) + gate = self.depth_gate_floor + (1.0 - self.depth_gate_floor) * raw_gate + gate = gate * depth_available[:, None, None].to(gate.dtype) + queries = queries + gate * depth_delta + aux.update({ + "depth_cross_attention": depth_attention, + "depth_fusion_gate": gate, + "depth_fusion_gate_raw": raw_gate * depth_available[:, None, None].to(raw_gate.dtype), + "depth_update_norm": torch.linalg.vector_norm(depth_delta, dim=-1), + "gated_depth_update_norm": torch.linalg.vector_norm(gate * depth_delta, dim=-1), + }) + queries = queries + self.ffn(queries) + return queries, aux + + +class TemporalUpdate(nn.Module): + def __init__( + self, + dim: int, + heads: int, + use_temporal: bool, + use_bimanual: bool, + position_mode: str = "none", + relative_bias_max_distance: int = 15, + attention_mode: str = "bidirectional", + ) -> None: + super().__init__() + if position_mode not in {"none", "relative_bias"}: + raise ValueError(f"Unknown temporal position mode: {position_mode}") + if position_mode != "none" and not use_temporal: + raise ValueError("temporal position conditioning requires use_temporal=True") + if relative_bias_max_distance < 1: + raise ValueError("relative_bias_max_distance must be positive") + if attention_mode not in {"bidirectional", "causal"}: + raise ValueError(f"Unknown temporal attention mode: {attention_mode}") + self.use_temporal = use_temporal + self.use_bimanual = use_bimanual + self.position_mode = position_mode + self.heads = heads + self.relative_bias_max_distance = relative_bias_max_distance + self.attention_mode = attention_mode + if use_temporal: + self.temporal_norm = nn.LayerNorm(dim) + self.temporal_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + if position_mode == "relative_bias": + self.relative_position_bias = nn.Parameter( + torch.zeros(heads, 2 * relative_bias_max_distance + 1) + ) + if use_bimanual: + self.bimanual_norm = nn.LayerNorm(dim) + self.bimanual_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + + def _relative_attention_bias( + self, batch_hands: int, time: int, dtype: torch.dtype, device: torch.device, + ) -> torch.Tensor | None: + if self.position_mode == "none": + return None + positions = torch.arange(time, device=device) + # Signed key-query displacement preserves ordered offline-video direction. + relative = positions[None, :] - positions[:, None] + relative = relative.clamp( + -self.relative_bias_max_distance, self.relative_bias_max_distance, + ) + self.relative_bias_max_distance + per_head = self.relative_position_bias[:, relative].to(dtype=dtype) + return per_head[None].expand(batch_hands, -1, -1, -1).reshape( + batch_hands * self.heads, time, time, + ) + + def _attention_mask( + self, batch_hands: int, time: int, dtype: torch.dtype, + device: torch.device, + ) -> torch.Tensor | None: + attention_mask = self._relative_attention_bias( + batch_hands, time, dtype, device, + ) + if self.attention_mode == "bidirectional": + return attention_mask + future = torch.triu( + torch.ones(time, time, dtype=torch.bool, device=device), diagonal=1, + ) + if attention_mask is None: + return future + return attention_mask.masked_fill(future[None], float("-inf")) + + def forward(self, tokens: torch.Tensor, frame_valid: torch.Tensor) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + batch, time, hands, dim = tokens.shape + aux: dict[str, torch.Tensor] = {} + if self.use_temporal: + per_hand = tokens.permute(0, 2, 1, 3).reshape(batch * hands, time, dim) + normalized = self.temporal_norm(per_hand) + key_padding = (~frame_valid)[:, None].expand(batch, hands, time).reshape(batch * hands, time) + attention_mask = self._attention_mask( + batch * hands, time, normalized.dtype, normalized.device, + ) + if attention_mask is not None and attention_mask.dtype != torch.bool: + float_padding = torch.zeros_like(key_padding, dtype=normalized.dtype) + key_padding_mask: torch.Tensor = float_padding.masked_fill(key_padding, float("-inf")) + else: + key_padding_mask = key_padding + delta, weights = self.temporal_attention( + normalized, normalized, normalized, + key_padding_mask=key_padding_mask, attn_mask=attention_mask, + need_weights=True, + ) + per_hand = per_hand + delta + tokens = per_hand.reshape(batch, hands, time, dim).permute(0, 2, 1, 3) + aux["temporal_attention"] = weights.reshape(batch, hands, time, time) + aux["temporal_update_norm"] = torch.linalg.vector_norm(delta, dim=-1).reshape(batch, hands, time).permute(0, 2, 1) + if self.use_bimanual: + pairs = tokens.reshape(batch * time, hands, dim) + normalized = self.bimanual_norm(pairs) + delta, weights = self.bimanual_attention(normalized, normalized, normalized, need_weights=True) + tokens = (pairs + delta).reshape(batch, time, hands, dim) + aux["bimanual_attention"] = weights.reshape(batch, time, hands, hands) + return tokens * frame_valid[:, :, None, None].to(tokens.dtype), aux + + +class HandQueryDecoder(nn.Module): + def __init__( + self, + dim: int, + layers: int, + heads: int, + use_depth: bool, + use_temporal: bool, + use_bimanual: bool, + mode: str, + gradient_checkpointing: bool = False, + depth_gate_floor: float = 0.0, + depth_gate_mode: str = "learned", + depth_gate_fixed_value: float = 0.5, + temporal_position_mode: str = "none", + temporal_relative_bias_max_distance: int = 15, + temporal_attention_mode: str = "bidirectional", + ) -> None: + super().__init__() + if mode not in {"sequential", "alternating", "hybrid_reread"}: + raise ValueError(f"Unknown decoder mode: {mode}") + self.mode = mode + self.gradient_checkpointing = gradient_checkpointing + self.temporal_enabled = True + self.spatial = nn.ModuleList([ + SpatialUpdate( + dim, heads, use_depth, use_bimanual, depth_gate_floor, + depth_gate_mode, depth_gate_fixed_value, + ) + for _ in range(layers) + ]) + temporal_layers = layers if mode == "alternating" else 1 + self.temporal = nn.ModuleList([ + TemporalUpdate( + dim, heads, use_temporal, use_bimanual, + temporal_position_mode, temporal_relative_bias_max_distance, + temporal_attention_mode, + ) + for _ in range(temporal_layers) + ]) + # With three spatial blocks this is S-S-T-S. The single temporal block + # and all parameters exactly match the sequential S-S-S-T baseline. + self.hybrid_temporal_after = max(layers - 2, 0) + + def forward(self, queries: torch.Tensor, rgb: torch.Tensor, depth: torch.Tensor | None, frame_valid: torch.Tensor, depth_available: torch.Tensor, side_bias: torch.Tensor) -> tuple[torch.Tensor, dict[str, Any]]: + batch, time, hands, dim = queries.shape + rgb_flat = rgb.reshape(batch * time, rgb.shape[2], dim) + depth_flat = None if depth is None else depth.reshape(batch * time, depth.shape[2], dim) + available_flat = depth_available.reshape(batch * time) + aux: dict[str, list[torch.Tensor]] = {} + for layer_index, spatial in enumerate(self.spatial): + spatial_args = (queries.reshape(batch * time, hands, dim), rgb_flat, depth_flat, available_flat, side_bias) + if self.gradient_checkpointing and self.training: + flat, layer_aux = checkpoint(spatial, *spatial_args, use_reentrant=False) + else: + flat, layer_aux = spatial(*spatial_args) + queries = flat.reshape(batch, time, hands, dim) * frame_valid[:, :, None, None].to(flat.dtype) + for key, value in layer_aux.items(): + aux.setdefault(key, []).append(value.reshape(batch, time, *value.shape[1:])) + if self.mode == "alternating" and self.temporal_enabled: + if self.gradient_checkpointing and self.training: + queries, temporal_aux = checkpoint(self.temporal[layer_index], queries, frame_valid, use_reentrant=False) + else: + queries, temporal_aux = self.temporal[layer_index](queries, frame_valid) + for key, value in temporal_aux.items(): + aux.setdefault(key, []).append(value) + elif self.mode == "hybrid_reread" and self.temporal_enabled and layer_index == self.hybrid_temporal_after: + if self.gradient_checkpointing and self.training: + queries, temporal_aux = checkpoint(self.temporal[0], queries, frame_valid, use_reentrant=False) + else: + queries, temporal_aux = self.temporal[0](queries, frame_valid) + for key, value in temporal_aux.items(): + aux.setdefault(key, []).append(value) + if self.mode == "sequential" and self.temporal_enabled: + queries, temporal_aux = self.temporal[0](queries, frame_valid) + for key, value in temporal_aux.items(): + aux.setdefault(key, []).append(value) + return queries, {key: torch.stack(values, dim=1) for key, values in aux.items()} diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/encoders.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/encoders.py new file mode 100644 index 0000000000000000000000000000000000000000..1b7c243f1cc84457e794d5e045b543f93d344f93 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/encoders.py @@ -0,0 +1,180 @@ +"""RGB and metric depth/geometry patch encoders.""" + +from __future__ import annotations + +from pathlib import Path +from typing import NamedTuple + +import torch +from torch import nn + + +class PatchFeatures(NamedTuple): + tokens: torch.Tensor + grid_hw: tuple[int, int] + patch_size: int + + +class TinyPatchEncoder(nn.Module): + """Debug-only encoder; never a substitute for a pretrained DINOv3 result.""" + + def __init__(self, output_dim: int, patch_size: int = 16, width: int = 64) -> None: + super().__init__() + self.patch_size = patch_size + self.output_dim = output_dim + self.network = nn.Sequential( + nn.Conv2d(3, width, 7, stride=2, padding=3), nn.GELU(), + nn.Conv2d(width, output_dim, patch_size // 2, stride=patch_size // 2), + ) + + def forward(self, images: torch.Tensor) -> PatchFeatures: + features = self.network(images) + return PatchFeatures(features.flatten(2).transpose(1, 2), features.shape[-2:], self.patch_size) + + +class DinoV3Encoder(nn.Module): + """Frozen official DINOv3 dense patch-token wrapper.""" + + def __init__( + self, + source_repo: str | Path, + weights: str | Path, + model_name: str = "dinov3_vitb16", + output_dim: int = 512, + input_dim: int = 768, + frozen: bool = True, + trainable_last_blocks: int = 0, + ) -> None: + super().__init__() + source_repo, weights = Path(source_repo), Path(weights) + self.backend = "torch_hub" + self.num_prefix_tokens = 0 + if weights.is_dir() and (weights / "model.safetensors").is_file(): + try: + from transformers import AutoModel + except ImportError as error: + raise ImportError("Transformers >=4.56 is required for local DINOv3 safetensors") from error + self.backbone = AutoModel.from_pretrained(str(weights), local_files_only=True) + self.backend = "transformers" + self.patch_size = int(self.backbone.config.patch_size) + self.num_prefix_tokens = 1 + int(self.backbone.config.num_register_tokens) + input_dim = int(self.backbone.config.hidden_size) + else: + if not (source_repo / "hubconf.py").is_file(): + raise FileNotFoundError(f"Official DINOv3 source repo not found: {source_repo}") + if not weights.is_file(): + raise FileNotFoundError( + f"DINOv3 pretrained weight not found: {weights}. Random DINO is not accepted for formal experiments." + ) + self.backbone = torch.hub.load( + str(source_repo), model_name, source="local", pretrained=True, weights=str(weights) + ) + self.patch_size = int(self.backbone.patch_size) + self.output_dim = output_dim + self.projection = nn.Linear(input_dim, output_dim) + if trainable_last_blocks < 0: + raise ValueError("trainable_last_blocks must be non-negative") + blocks = self._backbone_blocks() + if trainable_last_blocks > len(blocks): + raise ValueError( + f"requested {trainable_last_blocks} trainable DINO blocks, " + f"but the backbone has {len(blocks)}" + ) + if not frozen and trainable_last_blocks: + raise ValueError("full-backbone training and last-block training are mutually exclusive") + self.trainable_last_blocks = trainable_last_blocks + self.frozen = frozen and trainable_last_blocks == 0 + if frozen: + self.backbone.requires_grad_(False) + if trainable_last_blocks: + for block in blocks[-trainable_last_blocks:]: + block.requires_grad_(True) + self._backbone_final_norm().requires_grad_(True) + self._set_backbone_mode(False) + + def _backbone_blocks(self) -> nn.ModuleList: + blocks = getattr(self.backbone, "layer", None) + if blocks is None: + blocks = getattr(self.backbone, "blocks", None) + if not isinstance(blocks, nn.ModuleList): + raise TypeError("unsupported DINOv3 backbone: transformer blocks are unavailable") + return blocks + + def _backbone_final_norm(self) -> nn.Module: + norm = getattr(self.backbone, "norm", None) + if not isinstance(norm, nn.Module): + raise TypeError("unsupported DINOv3 backbone: final norm is unavailable") + return norm + + def _set_backbone_mode(self, mode: bool) -> None: + self.backbone.eval() + if self.trainable_last_blocks: + for block in self._backbone_blocks()[-self.trainable_last_blocks:]: + block.train(mode) + self._backbone_final_norm().train(mode) + + def train(self, mode: bool = True): + super().train(mode) + if self.frozen or self.trainable_last_blocks: + self._set_backbone_mode(mode) + return self + + def forward(self, images: torch.Tensor) -> PatchFeatures: + height, width = images.shape[-2:] + if height % self.patch_size or width % self.patch_size: + raise ValueError(f"DINO input {height}x{width} must be divisible by patch size {self.patch_size}") + if self.frozen: + with torch.no_grad(): + if self.backend == "transformers": + raw = self.backbone(pixel_values=images).last_hidden_state[:, self.num_prefix_tokens :] + else: + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + else: + if self.backend == "transformers": + raw = self.backbone(pixel_values=images).last_hidden_state[:, self.num_prefix_tokens :] + else: + raw = self.backbone.forward_features(images)["x_norm_patchtokens"] + tokens = self.projection(raw) + return PatchFeatures(tokens, (height // self.patch_size, width // self.patch_size), self.patch_size) + + +class DepthGeometryEncoder(nn.Module): + """Aligned metric log-depth or XYZ/logZ patch encoder.""" + + def __init__(self, output_dim: int, patch_size: int = 16, mode: str = "log_depth") -> None: + super().__init__() + if mode not in {"log_depth", "geometry"}: + raise ValueError(f"Unknown depth mode: {mode}") + self.mode = mode + self.patch_size = patch_size + channels = 2 if mode == "log_depth" else 5 + hidden = max(32, output_dim // 4) + self.encoder = nn.Sequential( + nn.Conv2d(channels, hidden, 3, padding=1), nn.GELU(), + nn.Conv2d(hidden, output_dim, patch_size, stride=patch_size), + ) + # Start as a zero residual so the gate need not suppress random depth noise. + nn.init.zeros_(self.encoder[-1].weight) + nn.init.zeros_(self.encoder[-1].bias) + + def forward(self, depth_m: torch.Tensor, valid: torch.Tensor, K: torch.Tensor) -> PatchFeatures: + if depth_m.ndim != 4 or depth_m.shape[1] != 1: + raise ValueError(f"Expected [BT,1,H,W] depth, got {depth_m.shape}") + valid_float = valid.to(depth_m.dtype) + log_z = torch.where(valid, depth_m.clamp_min(1e-4).log(), torch.zeros_like(depth_m)) + if self.mode == "log_depth": + inputs = torch.cat((log_z, valid_float), dim=1) + else: + _, _, height, width = depth_m.shape + u = torch.arange(width, device=depth_m.device, dtype=depth_m.dtype).view(1, 1, 1, width) + v = torch.arange(height, device=depth_m.device, dtype=depth_m.dtype).view(1, 1, height, 1) + cx = K[:, 0, 2].view(-1, 1, 1, 1) + cy = K[:, 1, 2].view(-1, 1, 1, 1) + fx = K[:, 0, 0].view(-1, 1, 1, 1) + fy = K[:, 1, 1].view(-1, 1, 1, 1) + x = (u - cx) * depth_m / fx + y = (v - cy) * depth_m / fy + x, y = x * valid_float, y * valid_float + inputs = torch.cat((x, y, depth_m * valid_float, log_z, valid_float), dim=1) + features = self.encoder(inputs) + return PatchFeatures(features.flatten(2).transpose(1, 2), features.shape[-2:], self.patch_size) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/mano.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/mano.py new file mode 100644 index 0000000000000000000000000000000000000000..aa23fb1a21aee64238a7ae6ce20b24c346643482 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/mano.py @@ -0,0 +1,61 @@ +"""Independent left/right MANO layers with wrist-root camera translation.""" + +from __future__ import annotations + +from pathlib import Path + +import torch +from torch import nn + +from foundation_hand.geometry.mano_compat import enable_legacy_mano_loading +from foundation_hand.geometry.rotations import matrix_to_axis_angle + + +class ManoCameraLayer(nn.Module): + """Run official manopth in native mm, root-center, then place wrist in camera meters.""" + + def __init__( + self, + mano_root: str | Path, + fix_left_shapedirs: bool = False, + ) -> None: + super().__init__() + root = Path(mano_root) + required = [root / "MANO_LEFT.pkl", root / "MANO_RIGHT.pkl"] + missing = [str(path) for path in required if not path.is_file()] + if missing: + raise FileNotFoundError(f"Licensed MANO assets missing: {missing}") + enable_legacy_mano_loading() + try: + from manopth.manolayer import ManoLayer + except ImportError as error: + raise ImportError("Install the pinned official manopth source before enabling MANO") from error + self.layers = nn.ModuleList([ + ManoLayer(mano_root=str(root), side="left", use_pca=False, ncomps=45, flat_hand_mean=True), + ManoLayer(mano_root=str(root), side="right", use_pca=False, ncomps=45, flat_hand_mean=True), + ]) + if fix_left_shapedirs: + # Match the official HOT3D provider's corrected MANO-left + # convention. The historical default remains unchanged for old + # H2O checkpoints. + with torch.no_grad(): + self.layers[0].th_shapedirs[:, 0, :].mul_(-1) + + def forward(self, rotation_matrices: torch.Tensor, shape: torch.Tensor, wrist_translation_m: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + if rotation_matrices.shape[-3:] != (16, 3, 3): + raise ValueError(f"Expected [...,2,16,3,3], got {rotation_matrices.shape}") + leading = rotation_matrices.shape[:-4] + if rotation_matrices.shape[-4] != 2: + raise ValueError("MANO hand dimension must be fixed [left,right]") + vertices_out, joints_out = [], [] + for hand, layer in enumerate(self.layers): + pose = matrix_to_axis_angle(rotation_matrices[..., hand, :, :, :]).reshape(-1, 48) + betas = shape[..., hand, :].reshape(-1, 10) + vertices_mm, joints_mm = layer(pose, betas) + root_mm = joints_mm[:, :1] + wrist = wrist_translation_m[..., hand, :].reshape(-1, 1, 3) + vertices = (vertices_mm - root_mm) / 1000.0 + wrist + joints = (joints_mm - root_mm) / 1000.0 + wrist + vertices_out.append(vertices.reshape(*leading, vertices.shape[-2], 3)) + joints_out.append(joints.reshape(*leading, joints.shape[-2], 3)) + return torch.stack(vertices_out, dim=-3), torch.stack(joints_out, dim=-3) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/structured_hand.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/structured_hand.py new file mode 100644 index 0000000000000000000000000000000000000000..e5d3e8dd8fc760012d2622d61a13fef716ae1703 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/models/structured_hand.py @@ -0,0 +1,192 @@ +"""Predicted-location structured hand refinement for Phase 5.""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + + +PART_COUNT = 7 +ROOT_PART = 0 +PALM_PART = 1 +FINGER_PARTS = slice(2, 7) + + +def structured_part_locations(joints_2d_norm: torch.Tensor) -> torch.Tensor: + """Map 21 predicted joints to root, palm, and five finger centers.""" + + if joints_2d_norm.ndim != 5 or joints_2d_norm.shape[-2:] != (21, 2): + raise ValueError("joint locations must have shape [B,T,2,21,2]") + root = joints_2d_norm[..., :1, :] + palm = joints_2d_norm[..., (0, 1, 5, 9, 13, 17), :].mean( + dim=-2, keepdim=True, + ) + fingers = torch.stack([ + joints_2d_norm[..., start : start + 4, :].mean(dim=-2) + for start in (1, 5, 9, 13, 17) + ], dim=-2) + return torch.cat((root, palm, fingers), dim=-2) + + +def kinematic_attention_mask(device: torch.device) -> torch.Tensor: + """Return a symmetric root-palm-finger graph mask for self-attention.""" + + allowed = torch.eye(PART_COUNT, dtype=torch.bool, device=device) + allowed[ROOT_PART, PALM_PART] = True + allowed[PALM_PART, ROOT_PART] = True + allowed[PALM_PART, FINGER_PARTS] = True + allowed[FINGER_PARTS, PALM_PART] = True + return ~allowed + + +class StructuredHandRefinement(nn.Module): + """Fuse coarse hand tokens with deformably sampled full-frame features.""" + + def __init__( + self, dim: int, heads: int, *, use_depth: bool, samples: int = 4, + maximum_offset_norm: float = 0.08, + ) -> None: + super().__init__() + if samples < 1: + raise ValueError("deformable sample count must be positive") + if not 0.0 < maximum_offset_norm <= 0.25: + raise ValueError("maximum normalized offset must be in (0,0.25]") + self.samples = samples + self.maximum_offset_norm = maximum_offset_norm + self.use_depth = use_depth + self.part_embedding = nn.Parameter(torch.randn(PART_COUNT, dim) * 0.02) + self.offset_head = nn.Linear(dim, samples * 2) + nn.init.zeros_(self.offset_head.weight) + nn.init.zeros_(self.offset_head.bias) + self.rgb_projection = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim)) + if use_depth: + self.depth_projection = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, dim)) + self.fusion_norm = nn.LayerNorm(dim) + self.graph_attention = nn.MultiheadAttention(dim, heads, batch_first=True) + self.ffn = nn.Sequential( + nn.LayerNorm(dim), nn.Linear(dim, dim * 4), nn.GELU(), + nn.Linear(dim * 4, dim), + ) + + @staticmethod + def _sample( + tokens: torch.Tensor, + grid_hw: tuple[int, int], + locations: torch.Tensor, + *, + deterministic_detached: bool = False, + ) -> torch.Tensor: + batch, time, patches, dim = tokens.shape + grid_height, grid_width = grid_hw + if patches != grid_height * grid_width: + raise ValueError("feature token count does not match patch grid") + if locations.shape[:2] != (batch, time) or locations.shape[-1] != 2: + raise ValueError("sample locations must align with [B,T] tokens") + if deterministic_detached: + features = tokens.detach().reshape(batch * time, patches, dim) + coordinates = locations.reshape(batch * time, -1, 2) + x = coordinates[..., 0] * grid_width - 0.5 + y = coordinates[..., 1] * grid_height - 0.5 + x0, y0 = torch.floor(x), torch.floor(y) + x1, y1 = x0 + 1.0, y0 + 1.0 + + def corner(x_index: torch.Tensor, y_index: torch.Tensor) -> torch.Tensor: + valid = ( + (x_index >= 0.0) & (x_index < grid_width) + & (y_index >= 0.0) & (y_index < grid_height) + ) + flat_index = ( + y_index.clamp(0, grid_height - 1).long() * grid_width + + x_index.clamp(0, grid_width - 1).long() + ) + value = torch.gather( + features, + 1, + flat_index[..., None].expand(-1, -1, dim), + ) + return value * valid[..., None].to(value.dtype) + + sampled = ( + corner(x0, y0) * ((x1 - x) * (y1 - y))[..., None] + + corner(x1, y0) * ((x - x0) * (y1 - y))[..., None] + + corner(x0, y1) * ((x1 - x) * (y - y0))[..., None] + + corner(x1, y1) * ((x - x0) * (y - y0))[..., None] + ) + sampled = sampled.reshape(*locations.shape[:-1], dim).mean(dim=-2) + return sampled + feature_map = tokens.reshape( + batch * time, grid_height, grid_width, dim, + ).permute(0, 3, 1, 2) + flat_locations = locations.reshape(batch * time, -1, locations.shape[-2], 2) + grid = flat_locations.mul(2.0).sub(1.0) + sampled = F.grid_sample( + feature_map, grid, mode="bilinear", padding_mode="zeros", + align_corners=False, + ) + sampled = sampled.mean(dim=-1).transpose(1, 2) + return sampled.reshape(*locations.shape[:-2], dim) + + def forward( + self, + coarse_hand_tokens: torch.Tensor, + joint2d_norm: torch.Tensor, + rgb_tokens: torch.Tensor, + depth_tokens: torch.Tensor | None, + grid_hw: tuple[int, int], + frame_valid: torch.Tensor, + depth_available: torch.Tensor, + *, + detach_locations: bool, + deterministic_detached_sampling: bool = False, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + batch, time, hands, dim = coarse_hand_tokens.shape + if hands != 2: + raise ValueError("structured refinement expects two hands") + locations = structured_part_locations(joint2d_norm) + if detach_locations: + locations = locations.detach() + seeds = coarse_hand_tokens[..., None, :] + self.part_embedding + offsets = self.maximum_offset_norm * torch.tanh( + self.offset_head(seeds).reshape( + batch, time, hands, PART_COUNT, self.samples, 2, + ) + ) + sample_locations = locations[..., None, :] + offsets + sampled_rgb = self._sample( + rgb_tokens, + grid_hw, + sample_locations, + deterministic_detached=deterministic_detached_sampling, + ) + tokens = seeds + self.rgb_projection(sampled_rgb) + if self.use_depth and depth_tokens is not None: + sampled_depth = self._sample( + depth_tokens, + grid_hw, + sample_locations, + deterministic_detached=deterministic_detached_sampling, + ) + depth_mask = depth_available[:, :, None, None, None].to(sampled_depth.dtype) + tokens = tokens + self.depth_projection(sampled_depth) * depth_mask + graph_input = self.fusion_norm(tokens).reshape( + batch * time * hands, PART_COUNT, dim, + ) + graph_delta, graph_weights = self.graph_attention( + graph_input, graph_input, graph_input, + attn_mask=kinematic_attention_mask(graph_input.device), + need_weights=True, + ) + tokens = (graph_input + graph_delta).reshape( + batch, time, hands, PART_COUNT, dim, + ) + tokens = tokens + self.ffn(tokens) + tokens = tokens * frame_valid[:, :, None, None, None].to(tokens.dtype) + return tokens, { + "structured_part_locations": locations, + "structured_sample_offsets": offsets, + "structured_sample_locations": sample_locations, + "structured_graph_attention": graph_weights.reshape( + batch, time, hands, PART_COUNT, PART_COUNT, + ), + } diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/__init__.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d718428f981b8ec69c68dee3978a07ce6689678 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/__init__.py @@ -0,0 +1,3 @@ +from foundation_hand.training.losses import BimanualLoss, LossConfig + +__all__ = ["BimanualLoss", "LossConfig"] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/checkpoint.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..17d23ba069d588aaeee71af0d863dc35ca9002fb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/checkpoint.py @@ -0,0 +1,97 @@ +"""Exact model/optimizer/RNG checkpoint save and resume.""" + +from __future__ import annotations + +import random +from pathlib import Path +from typing import Any + +import numpy as np +import torch + + +def save_checkpoint( + path: str | Path, + model: torch.nn.Module, + optimizer: torch.optim.Optimizer, + step: int, + extra: dict[str, Any] | None = None, + exclude_prefixes: tuple[str, ...] = (), +) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + model_state = { + key: value for key, value in model.state_dict().items() + if not key.startswith(exclude_prefixes) + } + state = { + "model": model_state, "optimizer": optimizer.state_dict(), "step": step, + "excluded_model_prefixes": exclude_prefixes, + "python_rng": random.getstate(), "numpy_rng": np.random.get_state(), + "torch_rng": torch.get_rng_state(), "cuda_rng": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None, + "extra": extra or {}, + } + torch.save(state, path) + + +def load_checkpoint(path: str | Path, model: torch.nn.Module, optimizer: torch.optim.Optimizer | None = None, map_location: str | torch.device = "cpu") -> dict[str, Any]: + state = torch.load(path, map_location=map_location, weights_only=False) + excluded_prefixes = tuple(state.get("excluded_model_prefixes", ())) + incompatible = model.load_state_dict(state["model"], strict=not excluded_prefixes) + if incompatible.unexpected_keys: + raise RuntimeError(f"Unexpected checkpoint keys: {incompatible.unexpected_keys}") + disallowed_missing = [ + key for key in incompatible.missing_keys + if not key.startswith(excluded_prefixes) + ] + if disallowed_missing: + raise RuntimeError(f"Missing non-excluded checkpoint keys: {disallowed_missing}") + if optimizer is not None: + optimizer.load_state_dict(state["optimizer"]) + random.setstate(state["python_rng"]) + np.random.set_state(state["numpy_rng"]) + torch.set_rng_state(state["torch_rng"].cpu()) + if torch.cuda.is_available() and state["cuda_rng"] is not None: + torch.cuda.set_rng_state_all([value.cpu() for value in state["cuda_rng"]]) + return {"step": state["step"], "extra": state["extra"]} + + +def load_model_initialization( + path: str | Path, + model: torch.nn.Module, + *, + allowed_missing_prefixes: tuple[str, ...], + map_location: str | torch.device = "cpu", + require_residual: bool = True, +) -> dict[str, Any]: + """Load an old model into a registered residual extension only.""" + + if require_residual and not allowed_missing_prefixes: + raise ValueError("initialization requires explicit allowed missing prefixes") + state = torch.load(path, map_location=map_location, weights_only=False) + incompatible = model.load_state_dict(state["model"], strict=False) + if incompatible.unexpected_keys: + raise RuntimeError(f"Unexpected initialization keys: {incompatible.unexpected_keys}") + checkpoint_excluded_prefixes = tuple(state.get("excluded_model_prefixes", ())) + accepted_missing_prefixes = allowed_missing_prefixes + checkpoint_excluded_prefixes + disallowed_missing = [ + key for key in incompatible.missing_keys + if not key.startswith(accepted_missing_prefixes) + ] + if disallowed_missing: + raise RuntimeError( + f"Missing non-residual initialization keys: {disallowed_missing}" + ) + residual_missing = [ + key for key in incompatible.missing_keys + if key.startswith(allowed_missing_prefixes) + ] + if require_residual and not residual_missing: + raise RuntimeError("initialization did not add any registered residual parameters") + return { + "step": int(state["step"]), + "extra": state.get("extra", {}), + "missing_keys": sorted(incompatible.missing_keys), + "residual_missing_keys": sorted(residual_missing), + "checkpoint_excluded_prefixes": checkpoint_excluded_prefixes, + } diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/losses.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..6e409461719f8b6fac7cee4689ec7e5870df36fd --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/losses.py @@ -0,0 +1,341 @@ +"""Mask-safe camera-space bimanual training losses.""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch +import torch.nn.functional as F +from torch import nn + +from foundation_hand.data.schema import supervision_mask +from foundation_hand.geometry.rotations import axis_angle_to_matrix +from foundation_hand.geometry.camera import project_points + + +@dataclass +class LossConfig: + joint2d: float = 1.0 + joint2d_teacher: float = 0.0 + joint3d_camera: float = 10.0 + joint3d_root_relative: float = 0.0 + vertices_camera: float = 1.0 + local_pose: float = 1.0 + global_orientation: float = 1.0 + shape: float = 0.1 + translation: float = 10.0 + reprojection: float = 1.0 + temporal_velocity: float = 0.1 + temporal_acceleration: float = 0.05 + bimanual_relative_wrist: float = 1.0 + presence: float = 0.0 + translation_teacher: float = 0.0 + translation_mode: str = "l1" + translation_axis_weights: tuple[float, float, float] = (1.0, 1.0, 1.0) + translation_huber_beta_m: float = 0.01 + wrist_ray: float = 0.0 + robust_log_z: float = 0.0 + z_tail_cvar: float = 0.0 + depth_confidence_calibration: float = 0.0 + paired_modality_no_harm: float = 0.0 + + def __post_init__(self) -> None: + if self.translation_mode not in {"l1", "axis_huber"}: + raise ValueError(f"unsupported translation mode: {self.translation_mode}") + if len(self.translation_axis_weights) != 3: + raise ValueError("translation_axis_weights must contain x/y/z weights") + weights = tuple(float(value) for value in self.translation_axis_weights) + if any(value <= 0.0 for value in weights): + raise ValueError("translation axis weights must be positive") + if self.translation_huber_beta_m <= 0.0: + raise ValueError("translation_huber_beta_m must be positive") + self.translation_axis_weights = weights + + +def masked_mean(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + mask = torch.broadcast_to(mask, values.shape) + safe = torch.where(mask, values, torch.zeros_like(values)) + count = mask.sum() + return safe.sum() / count.clamp_min(1) + + +def masked_l1(prediction: torch.Tensor, target: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + safe_target = torch.where(torch.broadcast_to(mask, target.shape), target, torch.zeros_like(target)) + return masked_mean((prediction - safe_target).abs(), mask) + + +class BimanualLoss(nn.Module): + def __init__(self, config: LossConfig) -> None: + super().__init__() + self.config = config + + def _translation_loss( + self, + prediction: torch.Tensor, + target: torch.Tensor, + mask: torch.Tensor, + ) -> torch.Tensor: + if self.config.translation_mode == "l1": + return masked_l1(prediction, target, mask[..., None]) + safe_target = torch.where(mask[..., None], target, torch.zeros_like(target)) + elementwise = F.smooth_l1_loss( + prediction, + safe_target, + reduction="none", + beta=float(self.config.translation_huber_beta_m), + ) + weights = prediction.new_tensor(self.config.translation_axis_weights) + return masked_mean(elementwise * weights, mask[..., None]) + + def translation_diagnostics( + self, + prediction: dict[str, torch.Tensor], + batch: dict[str, torch.Tensor], + ) -> dict[str, torch.Tensor]: + """Return detached-loggable per-axis terms without changing total loss.""" + + frame = batch["frame_valid"].bool() + mask = supervision_mask( + batch, + "translation_valid", + batch["joint_annotation_valid"].bool(), + ) & frame[..., None] + target = torch.where( + mask[..., None], + batch["wrist_root_translation"], + torch.zeros_like(batch["wrist_root_translation"]), + ) + error = prediction["wrist_root_translation"] - target + if self.config.translation_mode == "axis_huber": + elementwise = F.smooth_l1_loss( + prediction["wrist_root_translation"], + target, + reduction="none", + beta=float(self.config.translation_huber_beta_m), + ) + weights = prediction["wrist_root_translation"].new_tensor( + self.config.translation_axis_weights + ) + else: + elementwise = error.abs() + weights = prediction["wrist_root_translation"].new_ones(3) + diagnostics: dict[str, torch.Tensor] = {} + for axis_index, axis in enumerate(("x", "y", "z")): + raw_mae = masked_mean(error[..., axis_index].abs(), mask) + axis_term = masked_mean(elementwise[..., axis_index], mask) + diagnostics[f"translation_{axis}_raw_mae_m"] = raw_mae + diagnostics[f"translation_{axis}_effective_loss_contribution"] = ( + axis_term * weights[axis_index] * float(self.config.translation) / 3.0 + ) + return diagnostics + + def forward(self, prediction: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: + frame = batch["frame_valid"].bool() + legacy_joint = batch["joint_annotation_valid"].bool() + legacy_mano = batch["mano_annotation_valid"].bool() + legacy_joint_elements = ( + batch["joint_element_valid"].bool() & legacy_joint[..., None] + ) + joint2d_valid = supervision_mask( + batch, "joint2d_valid", legacy_joint_elements, + ) & frame[..., None, None] + joint3d_valid = supervision_mask( + batch, "joint3d_valid", legacy_joint_elements, + ) & frame[..., None, None] + joint3d_root_relative_valid = supervision_mask( + batch, "joint3d_root_relative_valid", joint3d_valid, + ) & frame[..., None, None] + translation_valid = supervision_mask( + batch, "translation_valid", legacy_joint, + ) & frame[..., None] + pose_valid = supervision_mask( + batch, "mano_pose_valid", legacy_mano, + ) & frame[..., None] + shape_valid = supervision_mask( + batch, "shape_valid", legacy_mano, + ) & frame[..., None] + vertices_valid = supervision_mask( + batch, "vertices_valid", legacy_mano, + ) & frame[..., None] + image_hw = batch["image_hw"].to(prediction["joint2d_norm"].dtype) + wh = image_hw[:, None, None, None, [1, 0]] + target_2d_norm = batch["joint2d"].to(wh.dtype) / wh + joint_mask = joint2d_valid + + losses: dict[str, torch.Tensor] = {} + losses["joint2d"] = masked_l1(prediction["joint2d_norm"], target_2d_norm, joint_mask[..., None]) + if "joint2d_linear_teacher_norm" in prediction: + losses["joint2d_teacher"] = masked_l1( + prediction["joint2d_norm"], + prediction["joint2d_linear_teacher_norm"], + frame[..., None, None, None], + ) + else: + losses["joint2d_teacher"] = prediction["hand_tokens"].sum() * 0 + target_axis = batch["mano_pose"].reshape(*batch["mano_pose"].shape[:-1], 16, 3) + target_rot = axis_angle_to_matrix(torch.nan_to_num(target_axis)) + rotation_error = (prediction["mano_rotation_matrices"] - target_rot).abs() + losses["global_orientation"] = masked_mean( + rotation_error[..., :1, :, :], pose_valid[..., None, None, None], + ) + losses["local_pose"] = masked_mean( + rotation_error[..., 1:, :, :], pose_valid[..., None, None, None], + ) + losses["translation"] = self._translation_loss( + prediction["wrist_root_translation"], + batch["wrist_root_translation"], + translation_valid, + ) + if "mixed_projection_direct_teacher_translation" in prediction: + losses["translation_teacher"] = masked_l1( + prediction["wrist_root_translation"], + prediction["mixed_projection_direct_teacher_translation"], + translation_valid[..., None], + ) + else: + losses["translation_teacher"] = prediction["hand_tokens"].sum() * 0 + zero = prediction["hand_tokens"].sum() * 0 + if "ray_depth_wrist2d_norm" in prediction: + wrist_mask = joint2d_valid[..., 0] + losses["wrist_ray"] = masked_l1( + prediction["ray_depth_wrist2d_norm"], + target_2d_norm[..., 0, :], wrist_mask[..., None], + ) + target_z = batch["wrist_root_translation"][..., 2] + safe_target_z = torch.where( + translation_valid, target_z.clamp_min(1e-4), + torch.ones_like(target_z), + ) + losses["robust_log_z"] = masked_mean( + F.smooth_l1_loss( + prediction["ray_depth_log_base_z"], safe_target_z.log(), + reduction="none", beta=0.05, + ), + translation_valid, + ) + final_z_error = ( + prediction["wrist_root_translation"][..., 2] - target_z + ).abs() + valid_z_error = final_z_error[translation_valid] + if valid_z_error.numel(): + tail_count = max(1, int((valid_z_error.numel() + 19) // 20)) + losses["z_tail_cvar"] = torch.topk( + valid_z_error, k=tail_count, largest=True, + ).values.mean() + else: + losses["z_tail_cvar"] = zero + correction_valid = ( + prediction["ray_depth_correction_valid"].bool() + & translation_valid + ) + base_error = (prediction["ray_depth_base_z_m"] - target_z).abs() + corrected_error = final_z_error + helpful = (corrected_error < base_error).to( + prediction["ray_depth_confidence_logit"].dtype, + ) + confidence_bce = F.binary_cross_entropy_with_logits( + prediction["ray_depth_confidence_logit"], helpful, + reduction="none", + ) + losses["depth_confidence_calibration"] = masked_mean( + confidence_bce, correction_valid, + ) + losses["paired_modality_no_harm"] = masked_mean( + (corrected_error - base_error).clamp_min(0.0), + correction_valid, + ) + else: + losses["wrist_ray"] = zero + losses["robust_log_z"] = zero + losses["z_tail_cvar"] = zero + losses["depth_confidence_calibration"] = zero + losses["paired_modality_no_harm"] = zero + + shape_mask = shape_valid.any(dim=1) + safe_shape = torch.where( + shape_valid[..., None], batch["mano_shape"], + torch.zeros_like(batch["mano_shape"]), + ) + target_shape = ( + safe_shape.sum(dim=1) + / shape_valid.sum(dim=1).clamp_min(1)[..., None] + ) + losses["shape"] = masked_l1(prediction["mano_shape_sequence"], target_shape, shape_mask[..., None]) + + if "joints_camera" in prediction: + losses["joint3d_camera"] = masked_l1( + prediction["joints_camera"], batch["joint3d_camera"], + joint3d_valid[..., None], + ) + else: + losses["joint3d_camera"] = prediction["hand_tokens"].sum() * 0 + if "joints_camera" in prediction: + predicted_relative = ( + prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + ) + if "joint3d_root_relative" in batch: + target_relative = batch["joint3d_root_relative"] + else: + target_relative = ( + batch["joint3d_camera"] - batch["joint3d_camera"][..., :1, :] + ) + losses["joint3d_root_relative"] = masked_l1( + predicted_relative, target_relative, + joint3d_root_relative_valid[..., None], + ) + else: + losses["joint3d_root_relative"] = prediction["hand_tokens"].sum() * 0 + if "vertices_camera" in prediction and "vertices_camera" in batch: + losses["vertices_camera"] = masked_l1( + prediction["vertices_camera"], batch["vertices_camera"], + vertices_valid[..., None, None], + ) + else: + losses["vertices_camera"] = prediction["hand_tokens"].sum() * 0 + if "joints_camera" in prediction and "K" in batch: + projected, positive = project_points(prediction["joints_camera"], batch["K"]) + reprojection_norm = projected / wh + K_supervision_valid = supervision_mask( + batch, "K_supervision_valid", frame, + ) & frame + reprojection_valid = supervision_mask( + batch, "reprojection_valid", joint2d_valid, + ) + reprojection_mask = ( + reprojection_valid & positive & K_supervision_valid[..., None, None] + ) + losses["reprojection"] = masked_l1(reprojection_norm, target_2d_norm, reprojection_mask[..., None]) + else: + losses["reprojection"] = prediction["hand_tokens"].sum() * 0 + + wrists = prediction["wrist_root_translation"] + pair_valid = translation_valid.all(dim=-1) + target_relative = batch["wrist_root_translation"][:, :, 1] - batch["wrist_root_translation"][:, :, 0] + pred_relative = wrists[:, :, 1] - wrists[:, :, 0] + losses["bimanual_relative_wrist"] = masked_l1(pred_relative, target_relative, pair_valid[..., None]) + + velocity_valid = translation_valid[:, 1:] & translation_valid[:, :-1] + pred_velocity = wrists[:, 1:] - wrists[:, :-1] + target_velocity = batch["wrist_root_translation"][:, 1:] - batch["wrist_root_translation"][:, :-1] + losses["temporal_velocity"] = masked_l1(pred_velocity, target_velocity, velocity_valid[..., None]) + acceleration_valid = velocity_valid[:, 1:] & velocity_valid[:, :-1] + pred_acceleration = pred_velocity[:, 1:] - pred_velocity[:, :-1] + target_acceleration = target_velocity[:, 1:] - target_velocity[:, :-1] + losses["temporal_acceleration"] = masked_l1(pred_acceleration, target_acceleration, acceleration_valid[..., None]) + + if "presence_logit" in prediction and self.config.presence > 0: + valid = supervision_mask( + batch, "presence_valid", batch["presence_label_valid"].bool(), + ) & frame[..., None] + target = torch.where(valid, batch["presence_target"], torch.zeros_like(batch["presence_target"])) + bce = F.binary_cross_entropy_with_logits(prediction["presence_logit"], target, reduction="none") + losses["presence"] = masked_mean(bce, valid) + else: + losses["presence"] = prediction["hand_tokens"].sum() * 0 + + weighted = { + name: value * float(getattr(self.config, name)) + for name, value in losses.items() + } + weighted["total"] = sum(weighted.values()) + return weighted diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/metrics.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..c3409994ee6d28374fbf42f8ccb1b191fee54eb2 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/metrics.py @@ -0,0 +1,34 @@ +"""Camera-space metrics reported separately from root-relative accuracy.""" + +from __future__ import annotations + +import torch + +from foundation_hand.data.schema import supervision_mask + + +def camera_metrics(prediction: dict[str, torch.Tensor], batch: dict[str, torch.Tensor]) -> dict[str, float]: + frame = batch["frame_valid"].bool() + legacy_joint = batch["joint_annotation_valid"].bool() + joint_valid = supervision_mask( + batch, + "joint3d_valid", + batch["joint_element_valid"].bool() & legacy_joint[..., None], + ) & frame[..., None, None] + metrics: dict[str, float] = {} + translation_error = (prediction["wrist_root_translation"] - torch.nan_to_num(batch["wrist_root_translation"])).abs() + trans_mask = supervision_mask( + batch, "translation_valid", legacy_joint, + ) & frame[..., None] + for index, axis in enumerate("xyz"): + values = translation_error[..., index][trans_mask] + metrics[f"translation_{axis}_mae_mm"] = float(values.mean() * 1000) if values.numel() else float("nan") + if "joints_camera" in prediction: + target = torch.nan_to_num(batch["joint3d_camera"]) + error = torch.linalg.vector_norm(prediction["joints_camera"] - target, dim=-1) + metrics["absolute_camera_mpjpe_mm"] = float(error[joint_valid].mean() * 1000) if joint_valid.any() else float("nan") + pred_relative = prediction["joints_camera"] - prediction["joints_camera"][..., :1, :] + target_relative = target - target[..., :1, :] + relative_error = torch.linalg.vector_norm(pred_relative - target_relative, dim=-1) + metrics["root_relative_mpjpe_mm"] = float(relative_error[joint_valid].mean() * 1000) if joint_valid.any() else float("nan") + return metrics diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/optimizer.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa76830ba81297de3971dc7a8f3e956608f8890 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/optimizer.py @@ -0,0 +1,135 @@ +"""Optimizer grouping for low-learning-rate backbone adaptation.""" + +from __future__ import annotations + +import torch + + +BACKBONE_PREFIX = "rgb_encoder.backbone." + + +def optimizer_parameter_groups( + model: torch.nn.Module, + *, + learning_rate: float, + backbone_learning_rate: float | None, +) -> list[dict[str, object]]: + if learning_rate <= 0: + raise ValueError("learning_rate must be positive") + main_parameters = [] + backbone_parameters = [] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad: + continue + target = backbone_parameters if name.startswith(BACKBONE_PREFIX) else main_parameters + target.append(parameter) + if not main_parameters: + raise ValueError("optimizer has no non-backbone trainable parameters") + if backbone_parameters and backbone_learning_rate is None: + raise ValueError("trainable DINOv3 blocks require backbone_learning_rate") + if not backbone_parameters and backbone_learning_rate is not None: + raise ValueError("backbone_learning_rate was set but no backbone parameter is trainable") + groups: list[dict[str, object]] = [{ + "params": main_parameters, + "lr": learning_rate, + "lr_scale": 1.0, + "group_name": "main", + }] + if backbone_parameters: + assert backbone_learning_rate is not None + if not 0 < backbone_learning_rate <= learning_rate: + raise ValueError("backbone_learning_rate must be in (0, learning_rate]") + groups.append({ + "params": backbone_parameters, + "lr": backbone_learning_rate, + "lr_scale": backbone_learning_rate / learning_rate, + "group_name": "dinov3_backbone", + }) + return groups + + +def staged_optimizer_parameter_groups( + model: torch.nn.Module, + *, + learning_rate: float, + initial_trainable_prefixes: tuple[str, ...], + unfrozen_learning_rate_scale: float, +) -> list[dict[str, object]]: + """Build stable parameter groups for a freeze-then-unfreeze schedule.""" + + if learning_rate <= 0: + raise ValueError("learning_rate must be positive") + if not initial_trainable_prefixes: + raise ValueError("initial_trainable_prefixes must not be empty") + if not 0.0 < unfrozen_learning_rate_scale <= 1.0: + raise ValueError("unfrozen_learning_rate_scale must be in (0, 1]") + initial_parameters = [] + later_parameters = [] + for name, parameter in model.named_parameters(): + if not parameter.requires_grad or name.startswith(BACKBONE_PREFIX): + continue + target = ( + initial_parameters + if name.startswith(initial_trainable_prefixes) + else later_parameters + ) + target.append(parameter) + if not initial_parameters: + raise ValueError("staged optimizer has no initially trainable parameters") + if not later_parameters: + raise ValueError("staged optimizer has no later-unfrozen parameters") + return [ + { + "params": initial_parameters, + "lr": learning_rate, + "lr_scale": 1.0, + "group_name": "staged_initial", + }, + { + "params": later_parameters, + "lr": 0.0, + "lr_scale": 0.0, + "unfrozen_lr_scale": unfrozen_learning_rate_scale, + "group_name": "staged_later", + }, + ] + + +def set_staged_parameter_group_phase( + optimizer: torch.optim.Optimizer, *, active: bool, +) -> None: + """Switch the later group without changing optimizer parameter identity.""" + + for group in optimizer.param_groups: + if group.get("group_name") == "staged_later": + group["lr_scale"] = float(group["unfrozen_lr_scale"]) if active else 0.0 + + +def clear_staged_later_gradients( + model: torch.nn.Module, initial_trainable_prefixes: tuple[str, ...], +) -> None: + """Make the initial phase a true freeze while retaining stable groups.""" + + for name, parameter in model.named_parameters(): + if ( + parameter.requires_grad + and not name.startswith(BACKBONE_PREFIX) + and not name.startswith(initial_trainable_prefixes) + ): + parameter.grad = None + + +def set_scheduled_learning_rate( + optimizer: torch.optim.Optimizer, learning_rate: float, +) -> None: + for parameter_group in optimizer.param_groups: + parameter_group["lr"] = learning_rate * float(parameter_group.get("lr_scale", 1.0)) + + +def checkpoint_excluded_prefixes(model: torch.nn.Module) -> tuple[str, ...]: + backbone_is_trainable = any( + parameter.requires_grad + for name, parameter in model.named_parameters() + if name.startswith(BACKBONE_PREFIX) + ) + return () if backbone_is_trainable else (BACKBONE_PREFIX,) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/schedule.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..f230d5239a3acd995eb21f897e0a238b56883104 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/src/foundation_hand/training/schedule.py @@ -0,0 +1,26 @@ +"""Step-deterministic learning-rate schedules.""" + +from __future__ import annotations + +import math + + +def warmup_cosine_learning_rate( + step: int, + total_steps: int, + base_lr: float, + min_lr: float, + warmup_steps: int, +) -> float: + if total_steps <= 0: + raise ValueError("total_steps must be positive") + if not 0 <= warmup_steps < total_steps: + raise ValueError("warmup_steps must be in [0, total_steps)") + if not 0 <= min_lr <= base_lr: + raise ValueError("Expected 0 <= min_lr <= base_lr") + if warmup_steps and step < warmup_steps: + return base_lr * (step + 1) / warmup_steps + progress = (step - warmup_steps) / max(total_steps - warmup_steps - 1, 1) + progress = min(max(progress, 0.0), 1.0) + cosine = 0.5 * (1.0 + math.cos(math.pi * progress)) + return min_lr + (base_lr - min_lr) * cosine diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/test_contract.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/test_contract.py new file mode 100644 index 0000000000000000000000000000000000000000..68b938b2aa050e510e544ed06105a08bb428ef15 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/test_contract.py @@ -0,0 +1,61 @@ +from collections import Counter +from pathlib import Path +import sqlite3 +import tempfile +import unittest + +from coverage_sampler import CoverageSampler, SOURCES +from preflight_index import tile_starts + + +class IndexTests(unittest.TestCase): + def test_tail_covers_every_frame_without_duplicates_at_start(self): + for length in range(8, 100): + starts = tile_starts(length) + self.assertEqual(starts[0], 0) + self.assertEqual(len(starts), (length + 7) // 8) + self.assertEqual(set().union(*(set(range(s, s + 8)) for s in starts)), set(range(length))) + + +class SamplerTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.index = Path(self.temp.name) / "index.sqlite" + with sqlite3.connect(self.index) as connection: + connection.execute("CREATE TABLE tiles(source TEXT, recording_id TEXT, tile_id TEXT)") + for source in SOURCES: + for recording in range(2): + for tile in range(5): + connection.execute( + "INSERT INTO tiles VALUES (?,?,?)", + (source, f"{source}-{recording}", f"{source}-{recording}-{tile}"), + ) + + def test_quota_resume_ddp_and_no_replacement(self): + sampler = CoverageSampler(self.index, "S1_S3") + first = [sampler.sample(pos) for pos in range(200)] + self.assertEqual(Counter(row["source"] for row in first), + Counter({"H2O": 80, "ARCTIC": 70, "HOT3D": 50})) + for source in SOURCES: + source_rows = [row for row in first if row["source"] == source] + self.assertEqual(len({row["tile_id"] for row in source_rows[:10]}), 10) + resumed = CoverageSampler(self.index, "S1_S3") + self.assertEqual(first[43:], [resumed.sample(pos) for pos in range(43, 200)]) + shards = [CoverageSampler(self.index, "S1_S3") for _ in range(6)] + merged = sorted((row for rank, item in enumerate(shards) + for row in item.shard(0, 200, rank, 6)), + key=lambda row: row["position"]) + self.assertEqual(first, merged) + + def test_s4_has_separate_ledger_and_modes(self): + sampler = CoverageSampler(self.index, "S4") + first = [sampler.sample(pos) for pos in range(200)] + self.assertEqual(Counter(row["source"] for row in first), + Counter({"H2O": 70, "ARCTIC": 50, "HOT3D": 80})) + self.assertTrue(all(row["mode"] != "rgb_depth_k" for row in first + if row["source"] != "H2O")) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/test_hot3d_rotation.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/test_hot3d_rotation.py new file mode 100644 index 0000000000000000000000000000000000000000..70352220213018fe79a2540793fd9bfd46df2014 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/test_hot3d_rotation.py @@ -0,0 +1,24 @@ +import unittest + +import numpy as np +from scipy.spatial.transform import Rotation +import torch + +from third_party.hot3d.data_loaders.rotation_compat import matrix_to_axis_angle + + +class Hot3dRotationTests(unittest.TestCase): + def test_roundtrip_including_singular_angles(self): + values = np.array([ + [0.0, 0.0, 0.0], [1e-8, 0.0, 0.0], [0.4, -1.2, 2.1], + [np.pi - 1e-8, 0.0, 0.0], [0.0, np.pi, 0.0], + ]) + for value in values: + matrix = Rotation.from_rotvec(value).as_matrix() + recovered = matrix_to_axis_angle(torch.tensor(matrix, dtype=torch.float64)).numpy() + error = (Rotation.from_rotvec(recovered).inv() * Rotation.from_matrix(matrix)).magnitude() + self.assertLess(error, 1e-8) + + +if __name__ == "__main__": + unittest.main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/tests/test_hot3d_supervision_masks.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/tests/test_hot3d_supervision_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..78e1e20c79e447348dc12d5a5aea09852d83562f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/tests/test_hot3d_supervision_masks.py @@ -0,0 +1,89 @@ +import torch + +from foundation_hand.data.hot3d_dataset import ( + hot3d_supervision_masks, + quest_linear_camera_calibration, +) + + +def test_visible_mesh_keeps_full_3d_but_masks_offscreen_2d() -> None: + K = torch.tensor([[[100.0, 0.0, 50.0], [0.0, 100.0, 50.0], [0.0, 0.0, 1.0]]]) + source_vertices = torch.tensor([[ + [[0.0, 0.0, 1.0], [1.0, 0.0, 1.0]], + [[2.0, 0.0, 1.0], [3.0, 0.0, 1.0]], + ]]) + joint2d = torch.full((1, 2, 21, 2), 50.0) + joint2d[0, 0, 1] = torch.tensor([150.0, 50.0]) + joint2d[0, 0, 3] = torch.tensor([8_000_000.0, 50.0]) + errors = torch.zeros((1, 2, 21)) + errors[0, 0, 2] = 3.0 + errors[0, 0, 4] = float("nan") + + hand, joint2d_mask, joint3d_mask = hot3d_supervision_masks( + torch.ones((1, 2), dtype=torch.bool), source_vertices, joint2d, + torch.ones((1, 2, 21), dtype=torch.bool), errors, K, (100, 100), + ) + + assert hand.tolist() == [[True, False]] + assert joint2d_mask[0, 0, :5].tolist() == [True, False, False, False, False] + assert not joint2d_mask[0, 1].any() + assert joint3d_mask[0, 0].all() + assert not joint3d_mask[0, 1].any() + + +def test_missing_geometry_remains_invalid_even_when_mesh_projects_inside() -> None: + K = torch.eye(3).unsqueeze(0) + source_vertices = torch.tensor([[[[0.0, 0.0, 1.0]], [[0.0, 0.0, 1.0]]]]) + joint2d = torch.zeros((1, 2, 21, 2)) + errors = torch.zeros((1, 2, 21)) + + hand, joint2d_mask, joint3d_mask = hot3d_supervision_masks( + torch.tensor([[False, True]]), source_vertices, joint2d, + torch.ones((1, 2, 21), dtype=torch.bool), errors, K, (100, 100), + ) + + assert hand.tolist() == [[False, True]] + assert not joint2d_mask[0, 0].any() + assert not joint3d_mask[0, 0].any() + assert joint2d_mask[0, 1].all() + assert joint3d_mask[0, 1].all() + + +def test_temporal_masks_are_independent_per_frame_and_hand() -> None: + K = torch.eye(3).repeat(8, 1, 1) + source_vertices = torch.tensor([[[[0.0, 0.0, 1.0]], [[2.0, 0.0, 1.0]]]]).repeat(8, 1, 1, 1) + source_vertices[1, 0, 0, 0] = 2.0 + source_vertices[1, 1, 0, 0] = 0.0 + joint2d = torch.zeros((8, 2, 21, 2)) + errors = torch.zeros((8, 2, 21)) + + hand, joint2d_mask, joint3d_mask = hot3d_supervision_masks( + torch.ones((8, 2), dtype=torch.bool), source_vertices, joint2d, + torch.ones((8, 2, 21), dtype=torch.bool), errors, K, (1, 1), + ) + + assert hand[0].tolist() == [True, False] + assert hand[1].tolist() == [False, True] + assert hand[2:].tolist() == [[True, False]] * 6 + assert torch.equal(joint2d_mask, joint3d_mask) + + +def test_quest_rectification_preserves_native_camera_extrinsic() -> None: + linear_model, native_model = object(), object() + native_transform, identity_transform = object(), object() + linear_calibration, native_calibration = object(), object() + + class Device: + def get_camera_calibration(self, stream_id, camera_model): + assert stream_id == "camera" + if camera_model is native_model: + return native_transform, native_calibration + if camera_model is linear_model: + return identity_transform, linear_calibration + raise AssertionError("unexpected calibration model") + + transform, calibration = quest_linear_camera_calibration( + Device(), "camera", linear_model, native_model, + ) + assert transform is native_transform + assert calibration is linear_calibration diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/README.md b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/README.md new file mode 100644 index 0000000000000000000000000000000000000000..082f4c7ce9db928ac1089a0d8ea61ce5eef03a42 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/README.md @@ -0,0 +1,4 @@ +This run vendors the small HOT3D provider code from the read-only HaWoR checkout on G2. +Only its two `pytorch3d.transforms.matrix_to_axis_angle` calls are replaced with a +CPU-only SciPy rotvec conversion, which must pass near-identity and near-pi +round-trip tests. Source data and annotations are unchanged. diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/Hot3DVisualizer.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/Hot3DVisualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..0857105bdab063bf49095f980d0cfc32f6003d07 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/Hot3DVisualizer.py @@ -0,0 +1,656 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from typing import Dict, List, Optional + +import matplotlib.pyplot as plt + +import numpy as np +import rerun as rr # @manual + +from data_loaders.hand_common import LANDMARK_CONNECTIVITY +from data_loaders.headsets import Headset +from data_loaders.loader_object_library import ObjectLibrary +from projectaria_tools.core.stream_id import StreamId # @manual +from collections import defaultdict +import torch + +try: + from dataset_api import Hot3dDataProvider # @manual +except ImportError: + from hot3d.dataset_api import Hot3dDataProvider + +from data_loaders.HandDataProviderBase import ( # @manual + HandDataProviderBase, + HandPose3dCollectionWithDt, +) +from data_loaders.ObjectBox2dDataProvider import ( # @manual + ObjectBox2dCollectionWithDt, + ObjectBox2dProvider, +) + +from data_loaders.ObjectPose3dProvider import ( # @manual + ObjectPose3dCollectionWithDt, + ObjectPose3dProvider, +) + +from projectaria_tools.core.calibration import ( + CameraCalibration, + DeviceCalibration, + FISHEYE624, + LINEAR, +) +from projectaria_tools.core.mps import get_eyegaze_point_at_depth # @manual + +from projectaria_tools.core.mps.utils import ( # @manual + filter_points_from_confidence, + filter_points_from_count, +) + +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.sophus import SE3 # @manual +from projectaria_tools.utils.rerun_helpers import ( # @manual + AriaGlassesOutline, + ToTransform3D, +) + + +class Hot3DVisualizer: + + def __init__(self, hot3d_data_provider: Hot3dDataProvider) -> None: + + self._hot3d_data_provider = hot3d_data_provider + # Device calibration and Image stream data + self._device_data_provider = hot3d_data_provider.device_data_provider + # Data provider at time T (for device & objects & hand poses) + self._device_pose_provider = hot3d_data_provider.device_pose_data_provider + self._hand_data_provider = hot3d_data_provider.mano_hand_data_provider + self._object_pose_data_provider = hot3d_data_provider.object_pose_data_provider + self._object_box2d_data_provider = ( + hot3d_data_provider.object_box2d_data_provider + ) + # Object library + self._object_library = hot3d_data_provider.object_library + + # If required + # Retrieve a distinct color mapping for object bounding box to show consistent color across stream_ids + # - Use a Colormap for visualizing object bounding box + self._object_box2d_colors = None + if self._object_box2d_data_provider is not None: + color_map = plt.get_cmap("viridis") + self._object_box2d_colors = color_map( + np.linspace(0, 1, len(self._object_box2d_data_provider.object_uids)) + ) + + # Keep track of what 3D assets has been loaded/unloaded so we will load them only when needed + self._object_cache_status = {} + + # To be parametrized later + self._jpeg_quality = 75 + + def log_static_assets( + self, + image_stream_ids: List[StreamId], + disable_vis=False + ) -> None: + """ + Log all static assets (aka Timeless assets) + - assets that are immutable (but can still move if attached to a 3D Pose) + """ + + # Configure the world coordinate system to ease navigation + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + if not disable_vis: + rr.log("world", rr.ViewCoordinates.RIGHT_HAND_Z_UP, static=True) + else: + rr.log("world", rr.ViewCoordinates.RIGHT_HAND_Y_UP, static=True) + + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + ## for Aria devices, we use online calibration which is a dynamic asset + pass + elif self._hot3d_data_provider.get_device_type() is Headset.Quest3: + # For each of the stream ids we want to use, export the camera calibration (intrinsics and extrinsics) + for stream_id in image_stream_ids: + # + # Plot the camera configuration + [extrinsics, intrinsics] = ( + self._device_data_provider.get_camera_calibration(stream_id) + ) + Hot3DVisualizer.log_pose( + f"world/device/{stream_id}", extrinsics, static=True + ) + Hot3DVisualizer.log_calibration(f"world/device/{stream_id}", intrinsics) + + # Deal with Aria specifics + # - Glasses outline + # - Point cloud + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + if not disable_vis: + Hot3DVisualizer.log_aria_glasses( + "world/device/glasses_outline", + self._device_data_provider.get_device_calibration(), + ) + + # Point cloud (downsampled for visualization) + point_cloud = self._device_data_provider.get_point_cloud() + if point_cloud: + # Filter out low confidence points + threshold_invdep = 5e-4 + threshold_dep = 5e-4 + point_cloud = filter_points_from_confidence( + point_cloud, threshold_invdep, threshold_dep + ) + # Down sample points + points_data_down_sampled = filter_points_from_count( + point_cloud, 500_000 + ) + # Retrieve point position + point_positions = [it.position_world for it in points_data_down_sampled] + POINT_COLOR = [200, 200, 200] + if not disable_vis: + rr.log( + "world/points", + rr.Points3D(point_positions, colors=POINT_COLOR, radii=0.002), + static=True, + ) + + def log_dynamic_assets( + self, + stream_ids: List[StreamId], + timestamp_ns: int, + vertices_input = None, + disable_vis=False # to speed up exporting + ) -> None: + """ + Log dynamic assets: + I.e assets that are moving, such as: + - 3D assets + - Device pose + - Hands + - Object poses + - Image related specifics assets + - images (stream_ids) + - Object Bounding boxes + - Aria Eye Gaze + """ + dataset = defaultdict(list) + + # + ## Retrieve and log data that is not stream_id dependent (pure 3D data) + # + acceptable_time_delta = 0 + + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + # For each of the stream ids we want to use, export the camera calibration (intrinsics and extrinsics) + for stream_id in stream_ids: + # + # Plot the camera configuration + [extrinsics, intrinsics] = ( + self._device_data_provider.get_online_camera_calibration( + stream_id=stream_id, timestamp_ns=timestamp_ns + ) + ) + if str(stream_id) == '214-1': + ego_extrinsics = extrinsics.to_matrix() + # print(ego_extrinsics) + ego_focal = intrinsics.get_focal_lengths()[0] + if not disable_vis: + Hot3DVisualizer.log_pose(f"world/device/{stream_id}", extrinsics) + Hot3DVisualizer.log_calibration(f"world/device/{stream_id}", intrinsics) + + elif self._hot3d_data_provider.get_device_type() is Headset.Quest3: + ## for Quest devices we will use factory calibration which is a static asset + pass + + headset_pose3d_with_dt = None + if self._device_data_provider is not None: + headset_pose3d_with_dt = self._device_pose_provider.get_pose_at_timestamp( + timestamp_ns=timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + acceptable_time_delta=acceptable_time_delta, + ) + + hand_poses_with_dt = None + if self._hand_data_provider is not None: + hand_poses_with_dt = self._hand_data_provider.get_pose_at_timestamp( + timestamp_ns=timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + acceptable_time_delta=acceptable_time_delta, + ) + + if not disable_vis: + object_poses_with_dt = None + if self._object_pose_data_provider is not None: + object_poses_with_dt = ( + self._object_pose_data_provider.get_pose_at_timestamp( + timestamp_ns=timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + acceptable_time_delta=acceptable_time_delta, + ) + ) + + aria_eye_gaze_data = ( + self._device_data_provider.get_eye_gaze(timestamp_ns) + if self._hot3d_data_provider.get_device_type() is Headset.Aria + else None + ) + + # + ## Log Device pose + # + if headset_pose3d_with_dt is not None: + headset_pose3d = headset_pose3d_with_dt.pose3d + head_pose = headset_pose3d.T_world_device.to_matrix() + if not disable_vis: + Hot3DVisualizer.log_pose( + "world/device", headset_pose3d.T_world_device, static=False + ) + + # + ## Log Hand poses + # + rot_r, trans_r, pose_r, betas_r, rot_l, trans_l, pose_l, betas_l, vertices_r, vertices_l = Hot3DVisualizer.log_hands( + "world/hands", # /{handedness_label}/... will be added as necessary + self._hand_data_provider, + hand_poses_with_dt, + show_hand_mesh=True, + show_hand_vertices=False, + show_hand_landmarks=True, + vertices_inputs=vertices_input, + disable_vis=disable_vis + ) + + dataset['rot_r'].append(rot_r) + dataset['trans_r'].append(trans_r) # world-space translation + dataset['pose_r'].append(pose_r) + dataset['betas_r'].append(betas_r) + dataset['rot_l'].append(rot_l) + dataset['pose_l'].append(pose_l) + dataset['betas_l'].append(betas_l) + dataset['trans_l'].append(trans_l) # world-space translation + # dataset['vertices_r'].append(vertices_r) + # dataset['vertices_l'].append(vertices_l) + + + # + ## Log Object poses + # + if not disable_vis: + Hot3DVisualizer.log_object_poses( + "world/objects", + object_poses_with_dt, + self._object_pose_data_provider, + self._object_library, + self._object_cache_status, + ) + + # + ## Log stream dependent data + # + for stream_id in stream_ids: + # + ## Log Image data + # + + # Undistorted image (required if you want see reprojected 3D mesh on the images) + image_data = self._device_data_provider.get_undistorted_image( + timestamp_ns, stream_id + ) + if str(stream_id) == '214-1': + ego_image_cv2 = np.rot90(image_data[:, :, ::-1], -1) + # ego_image_cv2 = image_data[:, :, ::-1] + if not disable_vis: + if image_data is not None: + rr.log( + f"world/device/{stream_id}", + rr.Image(image_data).compress(jpeg_quality=self._jpeg_quality), + ) + + # Raw device images (required for object bounding box visualization) + image_data = self._device_data_provider.get_image(timestamp_ns, stream_id) + if image_data is not None: + rr.log( + f"world/device/{stream_id}_raw", + rr.Image(image_data).compress(jpeg_quality=self._jpeg_quality), + ) + + if ( + self._object_box2d_data_provider is not None + and stream_id in self._object_box2d_data_provider.stream_ids + ): + box2d_collection_with_dt = ( + self._object_box2d_data_provider.get_box2d_at_timestamp( + stream_id=stream_id, + timestamp_ns=timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + ) + ) + Hot3DVisualizer.log_object_bounding_boxes( + stream_id, + box2d_collection_with_dt, + self._object_box2d_data_provider, + self._object_library, + self._object_box2d_colors, + ) + + # + ## Eye Gaze image reprojection + # + if self._hot3d_data_provider.get_device_type() is Headset.Aria: + + # We are showing EyeGaze reprojection only on the RGB image stream + if stream_id != StreamId("214-1"): + continue + + # Reproject EyeGaze for raw and pinhole images + camera_configurations = [FISHEYE624, LINEAR] + for camera_model in camera_configurations: + + eye_gaze_reprojection_data = ( + self._device_data_provider.get_eye_gaze_in_camera( + stream_id, timestamp_ns, camera_model=camera_model + ) + ) + if ( + eye_gaze_reprojection_data is None + or not eye_gaze_reprojection_data.any() + ): + continue + + label = ( + f"world/device/{stream_id}/eye-gaze_projection" + if camera_model == LINEAR + else f"world/device/{stream_id}_raw/eye-gaze_projection_raw" + ) + rr.log( + label, + rr.Points2D(eye_gaze_reprojection_data, radii=20), + # TODO consistent color and size depending of camera resolution + ) + # + ## Log device dependent remaining 3D data + # + + # Log 3D eye gaze + if not disable_vis: + if aria_eye_gaze_data is not None: + T_device_CPF = ( + self._device_data_provider.get_device_calibration().get_transform_device_cpf() + ) + # Compute eye_gaze vector at depth_m (30cm for a proxy 3D vector to display) + gaze_vector_in_cpf = get_eyegaze_point_at_depth( + aria_eye_gaze_data.yaw, aria_eye_gaze_data.pitch, depth_m=0.3 + ) + # Draw EyeGaze vector + rr.log( + "world/device/eye-gaze", + rr.Arrows3D( + origins=[T_device_CPF @ [0, 0, 0]], + vectors=[T_device_CPF @ gaze_vector_in_cpf], + ), + ) + if headset_pose3d_with_dt is None: + head_pose = None + return ego_image_cv2, head_pose, ego_extrinsics, ego_focal, dataset + + @staticmethod + def log_aria_glasses( + label: str, + device_calibration: DeviceCalibration, + use_cad_calibration: bool = True, + ) -> None: + ## Plot Project Aria Glasses outline (as lines) + aria_glasses_point_outline = AriaGlassesOutline( + device_calibration, use_cad_calibration + ) + rr.log(label, rr.LineStrips3D([aria_glasses_point_outline]), static=True) + + @staticmethod + def log_calibration( + label: str, + camera_calibration: CameraCalibration, + ) -> None: + rr.log( + label, + rr.Pinhole( + resolution=[ + camera_calibration.get_image_size()[0], + camera_calibration.get_image_size()[1], + ], + focal_length=float(camera_calibration.get_focal_lengths()[0]), + ), + static=True, + ) + + @staticmethod + def log_pose(label: str, pose: SE3, static=False) -> None: + rr.log(label, ToTransform3D(pose, False), static=static) + + @staticmethod + def log_hands( + label: str, + hand_data_provider: HandDataProviderBase, + hand_poses_with_dt: HandPose3dCollectionWithDt, + show_hand_mesh=True, + show_hand_vertices=True, + show_hand_landmarks=True, + vertices_inputs=None, + disable_vis=False + ): + logged_right_hand_data = False + logged_left_hand_data = False + rot_r, trans_r, pose_r, betas_r, rot_l, trans_l, pose_l, betas_l, vertices_r, vertices_l = torch.zeros([3]), torch.zeros([3]), torch.zeros([45]), torch.zeros([10]), torch.zeros([3]), torch.zeros([3]), torch.zeros([45]), torch.zeros([10]), torch.zeros([778, 3]), torch.zeros([778, 3]) + + if hand_poses_with_dt is None: + return rot_r, trans_r, pose_r, betas_r, rot_l, trans_l, pose_l, betas_l, vertices_r, vertices_l + hand_pose_collection = hand_poses_with_dt.pose3d_collection + + for hand_pose_data in hand_pose_collection.poses.values(): + + if hand_pose_data.is_left_hand(): + logged_left_hand_data = True + elif hand_pose_data.is_right_hand(): + logged_right_hand_data = True + + handedness_label = hand_pose_data.handedness_label() + + # Skeleton/Joints landmark representation + if show_hand_landmarks: + hand_landmarks, out_rot, out_trans, out_pose, out_betas = hand_data_provider.get_hand_landmarks(hand_pose_data) + # convert landmarks to connected lines for display + # (i.e retrieve points along the HAND LANDMARK_CONNECTIVITY as a list) + points = [ + connections + for connectivity in LANDMARK_CONNECTIVITY + for connections in [ + [hand_landmarks[it].numpy().tolist() for it in connectivity] + ] + ] + if handedness_label == 'right': + rot_r, trans_r, pose_r, betas_r = out_rot, out_trans, out_pose, out_betas + elif handedness_label == 'left': + rot_l, trans_l, pose_l, betas_l = out_rot, out_trans, out_pose, out_betas + else: + raise NotImplementedError + # rr.log( + # f"{label}/{handedness_label}/joints", + # rr.LineStrips3D(points, radii=0.002), + # ) + + # Update mesh vertices if required + hand_mesh_vertices = ( + hand_data_provider.get_hand_mesh_vertices(hand_pose_data) + if show_hand_vertices or show_hand_mesh + else None + ) + if not vertices_inputs is None: + if handedness_label == 'right': + hand_mesh_vertices = vertices_inputs[1] + else: + hand_mesh_vertices = vertices_inputs[0] + + if handedness_label == 'right': + vertices_r = hand_mesh_vertices + else: + vertices_l = hand_mesh_vertices + + if not disable_vis: + + # Vertices representation + if show_hand_vertices: + rr.log( + f"{label}/{handedness_label}/mesh", + rr.Points3D(hand_mesh_vertices), + ) + + # Triangular Mesh representation + if show_hand_mesh: + [hand_triangles, hand_vertex_normals] = ( + hand_data_provider.get_hand_mesh_faces_and_normals(hand_pose_data) + ) + rr.log( + f"{label}/{handedness_label}/mesh_faces", + rr.Mesh3D( + vertex_positions=hand_mesh_vertices, + vertex_normals=hand_vertex_normals, + triangle_indices=hand_triangles, # TODO: we could avoid sending this list if we want to save memory + ), + ) + if not disable_vis: + # If some hand data has not been logged, do not show it in the visualizer + if logged_left_hand_data is False: + rr.log(f"{label}/left", rr.Clear.recursive()) + if logged_right_hand_data is False: + rr.log(f"{label}/right", rr.Clear.recursive()) + + return rot_r, trans_r, pose_r, betas_r, rot_l, trans_l, pose_l, betas_l, vertices_r, vertices_l + + @staticmethod + def log_object_poses( + label: str, # "world/objects", + object_poses_with_dt: ObjectPose3dCollectionWithDt, + object_pose_data_provider: ObjectPose3dProvider, + object_library: ObjectLibrary, + object_cache_status: Dict[int, bool], + ): + if object_poses_with_dt is None: + return + + objects_pose3d_collection = object_poses_with_dt.pose3d_collection + + # Keep a mapping to know what object has been seen, and which one has not + object_uids = object_pose_data_provider.object_uids_with_poses + logging_status = {x: False for x in object_uids} + + for ( + object_uid, + object_pose3d, + ) in objects_pose3d_collection.poses.items(): + + object_name = object_library.object_id_to_name_dict[object_uid] + object_name = object_name + "_" + str(object_uid) + object_cad_asset_filepath = ObjectLibrary.get_cad_asset_path( + object_library_folderpath=object_library.asset_folder_name, + object_id=object_uid, + ) + + Hot3DVisualizer.log_pose( + f"world/objects/{object_name}", + object_pose3d.T_world_object, + False, + ) + # Mark object has been seen + logging_status[object_uid] = True + + # Link the corresponding 3D object + if object_uid not in object_cache_status.keys(): + object_cache_status[object_uid] = True + rr.log( + f"world/objects/{object_name}", + rr.Asset3D( + path=object_cad_asset_filepath, + ), + ) + + # If some object are not visible, we clear the entity (last known mesh and pose will not be displayed) + for object_uid, displayed in logging_status.items(): + if not displayed: + object_name = object_library.object_id_to_name_dict[object_uid] + object_name = object_name + "_" + str(object_uid) + rr.log( + f"world/objects/{object_name}", + rr.Clear.recursive(), + ) + if object_uid in object_cache_status.keys(): + del object_cache_status[object_uid] # We will log the mesh again + + @staticmethod + def log_object_bounding_boxes( + stream_id: StreamId, + box2d_collection_with_dt: Optional[ObjectBox2dCollectionWithDt], + object_box2d_data_provider: ObjectBox2dProvider, + object_library: ObjectLibrary, + bbox_colors: np.ndarray, + ): + """ + Object bounding boxes (valid for native raw images). + - We assume that the image corresponding to the stream_id has been logged beforehand as 'world/device/{stream_id}_raw/' + """ + + # Keep a mapping to know what object has been seen, and which one has not + object_uids = list(object_box2d_data_provider.object_uids) + logging_status = {x: False for x in object_uids} + + if ( + box2d_collection_with_dt is None + or box2d_collection_with_dt.box2d_collection is None + ): + # No bounding box are retrieved, we clear all the bounding box visualization existing so far + rr.log(f"world/device/{stream_id}_raw/bbox", rr.Clear.recursive()) + return + + object_uids_at_query_timestamp = ( + box2d_collection_with_dt.box2d_collection.object_uid_list + ) + + for object_uid in object_uids_at_query_timestamp: + object_name = object_library.object_id_to_name_dict[object_uid] + axis_aligned_box2d = box2d_collection_with_dt.box2d_collection.box2ds[ + object_uid + ] + box = axis_aligned_box2d.box2d + if box is None: + continue + + logging_status[object_uid] = True + rr.log( + f"world/device/{stream_id}_raw/bbox/{object_name}", + rr.Boxes2D( + mins=[box.left, box.top], + sizes=[box.width, box.height], + colors=bbox_colors[object_uids.index(object_uid)], + ), + ) + # If some object are not visible, we clear the bounding box visualization + for key, value in logging_status.items(): + if not value: + object_name = object_library.object_id_to_name_dict[key] + rr.log( + f"world/device/{stream_id}_raw/bbox/{object_name}", + rr.Clear.flat(), + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/dataset_download_status_manager.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/dataset_download_status_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..03da5d69c43ee016dc847ef6ed1c45ca64536d2c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/dataset_download_status_manager.py @@ -0,0 +1,53 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import json +from typing import Final, List + +DOWNLOAD_STATUS_FILE: Final[str] = ".download_status.json" + + +class DatasetDownloadStatusManager: + def __init__(self, data_groups: List[str]): + self.status = {data_group: False for data_group in data_groups} + + # Read status file from json and assign to status + def from_json(self, json_path: str) -> None: + try: + with open(json_path, "r") as f: + data = json.load(f) + for expected_data_group in self.status: + if expected_data_group not in data: + error = f"{DOWNLOAD_STATUS_FILE} is missing data group {expected_data_group}.\n" + error += f"Your data may be out of date, try clearing {DOWNLOAD_STATUS_FILE} in your sequence path" + raise Exception(error) + self.status = data + except Exception as e: + print(f"[warning]: cannot read status json. {e}") + + def to_json(self, json_path: str): + try: + json_object = json.dumps(self.status, indent=4) + with open(json_path, "w") as outfile: + outfile.write(json_object) + except Exception as e: + print(f"[warning]: can not write status json. {e}") + + def set_download_status(self, data_type: str, value: bool): + if data_type not in self.status: + raise Exception(f"data type {data_type} is not supported") + self.status[data_type] = value + + def get_download_status(self, data_type: str) -> bool: + return self.status[data_type] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/dataset_downloader_base.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/dataset_downloader_base.py new file mode 100644 index 0000000000000000000000000000000000000000..e1a2eeea27aa6e1ee0cd55dd86d6c1e6dfd1417f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/dataset_downloader_base.py @@ -0,0 +1,283 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import hashlib +import json +import os +import shutil +import tempfile +from pathlib import Path +from typing import List, Optional, Tuple +from zipfile import is_zipfile, ZipFile + +import requests + +from dataset_download_status_manager import ( + DatasetDownloadStatusManager, + DOWNLOAD_STATUS_FILE, +) + +from requests.adapters import HTTPAdapter +from requests.packages.urllib3.util.retry import Retry +from tqdm import tqdm +from utils import load_data_groups_from_cdn + +CHUCK_SIZE_BYTE = 8192 +STATUS_CODE_DEFAULT = 404 + + +DATA_TYPE_TO_SAVE_PATH = { + "mps_eye_gaze": os.path.join("mps", "eye_gaze"), + "mps_slam_trajectories": os.path.join("mps", "slam"), + "mps_slam_points": os.path.join("mps", "slam"), + "mps_slam_calibration": os.path.join("mps", "slam"), + "mps_slam_summary": os.path.join("mps", "slam"), + "mps_hand_tracking": os.path.join("mps", "hand_tracking"), +} + + +def calculate_file_sha1(file_path: str) -> str: + sha1 = hashlib.sha1() + with open(file_path, "rb") as file: + chunk = file.read(4096) # Read the file in 4KB chunks + while chunk: + sha1.update(chunk) + chunk = file.read(4096) + + sha1_sum = sha1.hexdigest() + return sha1_sum + + +class DatasetDownloaderBase: + __KEY_URL: str = "download_url" + __KEY_FILENAME: str = "filename" + __KEY_CHECKSUM: str = "sha1sum" + + def __init__( + self, + cdn_file: str, + data_types: List[str], + sequences: Optional[List[str]] = None, + overwrite: bool = True, + ): + + # add slam summary if any slam data is requested + if "mps_slam_summary" not in data_types: + if ( + "mps_slam_trajectories" in data_types + or "mps_slam_calibration" in data_types + or "mps_slam_points" in data_types + ): + data_types.append("mps_slam_summary") + + self.data_types_selected = data_types + self.overwrite = overwrite + + # load cdn file + with open(cdn_file, "r") as f: + cdn_file_data = json.load(f) + if "sequences" not in cdn_file_data: + raise Exception("invalid cdn_file, missing key: sequences") + self.sequences_data = cdn_file_data["sequences"] + if "sequence_config" not in cdn_file_data: + raise Exception("invalid cdn_file, missing key: sequence_config") + self.sequence_config = cdn_file_data["sequence_config"] + + self.sequences = sequences + if sequences is None: + self.sequences = self.__get_all_sequences() + + self.data_types_all = load_data_groups_from_cdn(cdn_file) + + def download_data(self, output_folder: str): + if not os.path.exists(output_folder): + print(f"Creating local output folder {output_folder}") + os.makedirs(output_folder) + + # download sequences + responses = {} + for sequence in self.sequences: + responses[sequence] = self.__download_sequence( + sequence=sequence, + output_folder=output_folder, + ) + num_success_sequences = sum(1 for sequence in responses if responses[sequence]) + print( + f"{num_success_sequences} of {len(self.sequences)} sequences are successfully downloaded" + ) + + def __download_sequence( + self, + sequence: str, + output_folder: str, + ) -> bool: + output_folder_seq = os.path.join(output_folder, sequence) + print(f"downloading sequence {sequence} to {output_folder_seq}") + + if sequence not in self.sequences_data: + print(f"sequence {sequence} is not available in the selected data group") + return False + + if not os.path.exists(output_folder_seq): + os.makedirs(output_folder_seq) + + # check last download status + status_manager = DatasetDownloadStatusManager(self.data_types_all) + status_json = os.path.join(output_folder_seq, DOWNLOAD_STATUS_FILE) + if os.path.exists(status_json): + status_manager.from_json(status_json) + + final_success = True + for data_type in self.data_types_selected: + # skip the data which has already been downloaded if overwrite is not set + if not self.overwrite and status_manager.get_download_status(data_type): + if data_type == 'hand_data' and not os.path.exists('output_folder_seq/mano_hand_pose_trajectory.jsonl'): + pass + else: + print(f"skip downloading datatype {data_type} since already downloaded") + continue + data_type_download_is_success = True + is_success, status_code = self.__download_data_from_url( + sequence=sequence, + data_type=data_type, + output_folder=output_folder_seq, + ) + if not is_success: + data_type_download_is_success = False + final_success = False + print(f"{data_type} is NOT downloaded with error code {status_code}") + + # log download status for each data_type + status_manager.set_download_status(data_type, data_type_download_is_success) + + # write the download status to json + status_manager.to_json(status_json) + return final_success + + def __download_data_from_url( + self, + sequence: str, + data_type: str, + output_folder: str, + ) -> Tuple[bool, int]: + status_code = STATUS_CODE_DEFAULT + is_success = True + sequence_data = self.sequences_data[sequence] + + if data_type not in sequence_data: + print(f"Data type {data_type} is not available for sequence: {sequence}") + return is_success, status_code + + network_link = sequence_data[data_type][self.__KEY_URL] + if not network_link: + print( + f"Url for sequence '{sequence}', data type '{data_type}' is not available" + ) + return is_success, status_code + + try: + with tempfile.TemporaryDirectory() as local_tmp_path: + download_filename = sequence_data[data_type][self.__KEY_FILENAME] + download_file_path = os.path.join(local_tmp_path, download_filename) + sha1sum = sequence_data[data_type][self.__KEY_CHECKSUM] + session = requests.Session() + # allow retry on errors of too many requests (429), internal server error (500), + # bad gateway (502), service unavailable (503), or gateway timeout (504) + + retries = Retry( + total=5, + backoff_factor=2, # final try is 2*(2**5) = 64 seconds + status_forcelist=[429, 500, 502, 503, 504], + ) + + session.mount("https://", HTTPAdapter(max_retries=retries)) + + with session.get(network_link, stream=True, timeout=10) as r: + # r.raise_for_status() + total_size_in_bytes = int(r.headers.get("content-length", 0)) + + _, _, free_disk_in_bytes = shutil.disk_usage("/") + if free_disk_in_bytes < total_size_in_bytes: + raise Exception( + f"Insufficient disk space for sequence '{sequence}' data type '{data_type}'. Required \ + {total_size_in_bytes} bytes, available {free_disk_in_bytes} bytes" + ) + with open(download_file_path, "wb") as f: + print(f"Serializing to {download_file_path}") + progress_bar = tqdm( + total=total_size_in_bytes, unit="iB", unit_scale=True + ) + for chunk in r.iter_content(chunk_size=CHUCK_SIZE_BYTE): + # serialize chunk of 8KB + progress_bar.update(len(chunk)) + f.write(chunk) + progress_bar.close() + status_code = r.status_code + # raise exception if download fails and skip the unzip part below + r.raise_for_status() + + calculated_checksum = calculate_file_sha1(download_file_path) + if sha1sum != calculated_checksum: + error = f"different checksum value for sequence '{sequence}' and data type '{data_type}'\n" + error += f"Calculated checksum: {calculated_checksum}, expected checksum: {sha1sum}" + raise Exception(error) + + if is_zipfile(download_file_path): + # unzip and reorganize + with ZipFile(download_file_path) as zip_ref: + unzipped_top_dir_name = sequence + unzipped_dir = os.path.join( + local_tmp_path, unzipped_top_dir_name + ) + if not os.path.exists(unzipped_dir): + os.makedirs(unzipped_dir) + + # MOVE MPS FILES + if data_type in DATA_TYPE_TO_SAVE_PATH.keys(): + zip_ref.extractall(output_folder) + for local_path in zip_ref.namelist(): + abs_path = os.path.join(output_folder, local_path) + if os.path.isfile(abs_path): + move_filename = os.path.basename(abs_path) + move_path = os.path.join( + Path(abs_path).parent, + DATA_TYPE_TO_SAVE_PATH[data_type], + ) + os.makedirs(move_path, exist_ok=True) + shutil.move( + abs_path, os.path.join(move_path, move_filename) + ) + else: + zip_ref.extractall(output_folder) + else: + output_filename = os.path.join(output_folder, download_filename) + if data_type == "main_vrs": + basename_old = os.path.basename(output_filename) + basename_new = "recording.vrs" + output_filename = output_filename.replace( + basename_old, basename_new + ) + shutil.copyfile( + download_file_path, + output_filename, + ) + except Exception as e: + # Handle request exceptions (e.g., ConnectionError, TooManyRedirects, etc.) + print(f"An error occurred: {e}. Status code: {status_code}") + is_success = False + + return is_success, status_code + + def __get_all_sequences(self) -> List[str]: + return list(self.sequences_data.keys()) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/dataset_downloader_base_main.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/dataset_downloader_base_main.py new file mode 100644 index 0000000000000000000000000000000000000000..6d22dd308a74bf4aa7b4f62c9b2823b577c67cf0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/dataset_downloader_base_main.py @@ -0,0 +1,141 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import argparse + +from dataset_downloader_base import DatasetDownloaderBase + +from utils import load_data_groups_from_cdn, load_sequences_list_from_cdn + + +def parse_args(): + parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) + parser.add_argument( + "-c", + "--cdn_file", + dest="cdn_file", + type=str, + required=True, + default=None, + help="input file listing the CDN urls", + ) + + parser.add_argument( + "-o", + "--output_folder", + dest="output_folder", + type=str, + required=True, + help="output folder for storing the downloaded dataset locally", + ) + + parser.add_argument( + "-w", + "--overwrite", + dest="overwrite", + action="store_true", + required=False, + default=False, + help=""" + If set, re-download and overwrite sequences which have been downloaded before + """, + ) + + parser.add_argument( + "-d", + "--data_types", + dest="data_types", + nargs="+", + required=False, + default=[], + help=""" + List (space separated) of data types to download for each sequence. + To get a list of all data types available for this dataset, leave this blank and it will list all options. + If not set, and IFF single data type exists, it will will be downloaded automatically", + """, + ) + + parser.add_argument( + "-l", + "--sequence_names", + dest="sequence_names", + nargs="+", + required=False, + help="a list of sequence names (separated by space) to be downloaded. If not set, all sequences will be downloaded", + ) + + return parser.parse_args() + + +def main(): + args = parse_args() + + all_data_groups = load_data_groups_from_cdn(args.cdn_file) + all_data_groups_list = list(all_data_groups.keys()) + # remove slam summary since this gets downloaded automatically if any slam data is requested + if "mps_slam_summary" in all_data_groups_list: + all_data_groups_list.remove("mps_slam_summary") + + # If sequence_names is specified as "all", retrieve all sequences from the CDN file + if len(args.sequence_names) == 1 and "all" in args.sequence_names: + args.sequence_names = load_sequences_list_from_cdn(args.cdn_file) + + # If data_types are not specified, ask the user to specify one + # If only one data type is available, automatically download it + if len(args.data_types) == 0 and len(all_data_groups_list) > 1: + print("-d(, --data_types) must be specified") + print("Available data types include:") + for i in range(len(all_data_groups_list)): + print(f"{i}: {all_data_groups_list[i]}") + exit(1) + elif len(all_data_groups_list) == 1: + args.data_types = [0] # Download the only existing data type available + elif "all" in args.data_types: + args.data_types = [i for i in range(len(all_data_groups_list))] + + data_types = [] + for input_data_type in args.data_types: + data_types.append(all_data_groups_list[int(input_data_type)]) + + if args.sequence_names is None: + download_all = ( + input( + """ + -l(, --sequence_names) is not specified. + Do you want to download all sequences? [y/n] + """ + ).lower() + == "y" + ) + if not download_all: + print("Please rerun the command with -l(, --sequence_names) specified.") + print( + "Here is the list of available sequences:\n", + load_sequences_list_from_cdn(args.cdn_file), + ) + exit(1) + else: + print(f"Downloading the following sequences: {args.sequence_names}") + + downloader = DatasetDownloaderBase( + cdn_file=args.cdn_file, + data_types=data_types, + sequences=args.sequence_names, + overwrite=args.overwrite, + ) + downloader.download_data(output_folder=args.output_folder) + + +if __name__ == "__main__": + main() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/utils.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8497d012ac3d5f31dd8f1aa001e958f3f403c0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_downloader/utils.py @@ -0,0 +1,120 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import json +import os +from typing import Dict, Final, List + + +########################################################################### + +# We require AT LEAST ONE of these files for eye_gaze +MPS_EYE_GAZE_FILES_REQUIRED: Final[List[str]] = [ + "general_eye_gaze.csv", + "generalized_eye_gaze.csv", + "personalized_eye_gaze.csv", + "calibrated_eye_gaze.csv", +] + +MPS_EYE_GAZE_FILES: Final[List[str]] = MPS_EYE_GAZE_FILES_REQUIRED + ["summary.json"] + +# We requires ALL of these SLAM files +MPS_SLAM_FILES_REQUIRED: Final[List[str]] = [ + "closed_loop_trajectory.csv", + "open_loop_trajectory.csv", + "online_calibration.jsonl", + "semidense_observations.csv.gz", +] + +MPS_SLAM_FILES: Final[List[str]] = MPS_SLAM_FILES_REQUIRED + [ + "semidense_points.csv.gz", + "global_points.csv.gz", + "summary.json", +] + +MPS_FOLDER: Final[str] = "mps" +MPS_SLAM_FOLDER: Final[str] = "slam" +MPS_EYE_GAZE_FOLDER: Final[str] = "eye_gaze" + +MPS_SLAM_GROUP_FILES: Final[Dict[str, List[str]]] = { + "mps_slam_trajectories": [MPS_SLAM_FILES[0], MPS_SLAM_FILES[1]], + "mps_slam_calibration": [MPS_SLAM_FILES[2]], + "mps_slam_points": [ + MPS_SLAM_FILES[3], + MPS_SLAM_FILES[4], + MPS_SLAM_FILES[5], + ], + "mps_slam_summary": [MPS_SLAM_FILES[6]], +} +MPS_DATA_GROUP_FILES: Final[Dict[str, List[str]]] = { + **MPS_SLAM_GROUP_FILES, + **{ + "mps_eye_gaze": MPS_EYE_GAZE_FILES, + }, +} +########################################################################### + + +# Load the list of sequences listed from the cdn file +def load_sequences_list_from_cdn(cdn_file: str) -> List[str]: + if not os.path.exists(cdn_file): + raise Exception("CDN file does not exist") + + # load sequences from cdn file + sequences_list = [] + with open(cdn_file, "r") as f: + cdn_file_data = json.load(f) + if "sequences" not in cdn_file_data: + raise Exception("invalid cdn_file, missing key: sequences") + sequences_list = cdn_file_data["sequences"].keys() + return sequences_list + + +# Load a list of data group name to all files included in that data group +def load_data_groups_from_cdn(cdn_file: str) -> Dict[str, List[str]]: + if not os.path.exists(cdn_file): + raise Exception("CDN file does not exist") + + # load sequence_config from cdn file + sequence_config = {} + with open(cdn_file, "r") as f: + cdn_file_data = json.load(f) + if "sequence_config" not in cdn_file_data: + raise Exception("invalid cdn_file, missing key: sequence_config") + sequence_config = cdn_file_data["sequence_config"] + + data_groups = {} + + # load main vrs data group + if "main" not in sequence_config: + raise Exception("invalid cdn_file, missing key: sequence_config/main") + main_data = sequence_config["main"] + if "recording" not in main_data: + raise Exception("invalid cdn_file, missing key: sequence_config/main/recording") + + # Only add "recording" and "mps" data if they are defined as different than None + if main_data["recording"] != "None": + data_groups["main_vrs"] = main_data["recording"] + if main_data["mps"] != "None": + # next add mps data groups which are predefined + data_groups.update(MPS_DATA_GROUP_FILES) + + # load custom data groups for this dataset + if "data_groups" not in sequence_config: + raise Exception("invalid cdn_file, missing key: sequence_config/data_groups") + + for data_group, files in sequence_config["data_groups"].items(): + data_groups[data_group] = files + + return data_groups diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/AlignedBox2d.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/AlignedBox2d.py new file mode 100644 index 0000000000000000000000000000000000000000..617a9eb36f78a748bd806412e4fe9bc25ebb3b6a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/AlignedBox2d.py @@ -0,0 +1,156 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from __future__ import annotations + +import numpy as np + + +class AlignedBox2d: + """ + An 2D axis aligned box in floating point. + + Assumptions: + * The origin is at top-left corner + * `right` and `bottom` are not inclusive in the region, i.e. the width and + height can be simply calculated by `right - left` and `bottom - top`. + """ + + def __init__(self, left: float, top: float, right: float, bottom: float): + """Initializes the bounding box given (left, top, right, bottom)""" + self._left: float = left + self._top: float = top + self._right: float = right + self._bottom: float = bottom + + def __repr__(self): + return f"AlignedBox2d(left: {self._left}, top: {self._top}, right: {self._right}, bottom: {self._bottom})" + + @property + def left(self) -> float: + """Left of the aligned box on x-axis.""" + return self._left + + @property + def top(self) -> float: + """Top of the aligned box on y-axis.""" + return self._top + + @property + def right(self) -> float: + """Right of the aligned box on x-axis.""" + return self._right + + @property + def bottom(self) -> float: + """Bottom of the aligned box on y-axis.""" + return self._bottom + + @property + def width(self) -> float: + """Width of the aligned box. + + Returns: + Width computed by right - left + """ + return self.right - self.left + + @property + def height(self) -> float: + """Height of the aligned box. + + Returns: + Height computed by bottom - top + """ + return self.bottom - self.top + + def pad(self, width: float, height: float) -> AlignedBox2d: + """Pads the region by extending `width` and `height` on four sides. + + Args: + width (float): length to pad on left and right sides + height (float): length to pad on top and bottom sides + Returns: + a new AlignedBox2d object with padded region + """ + return AlignedBox2d( + self.left - width, + self.top - height, + self.right + width, + self.bottom + height, + ) + + def array_ltrb(self) -> np.ndarray: + """Converts the box into a float np.ndarray of shape (4,): (left, top, right, bottom). + + Returns: + a float np.ndarray of shape (4,) representing (left, top, right, bottom) + """ + return np.array([self.left, self.top, self.right, self.bottom]) + + def array_ltwh(self) -> np.ndarray: + """Converts the box into a float np.ndarray of shape (4,): (left, top, width, height). + + Returns: + a float np.ndarray of shape (4,) representing (left, top, width, height) + """ + return np.array([self.left, self.top, self.width, self.height]) + + def int_array_ltrb(self) -> np.ndarray: + """Converts the box into an int np.ndarray of shape (4,): (left, top, width, height). + + Returns: + an int np.ndarray of shape (4,) representing (left, top, right, bottom) + """ + return self.array_ltrb().astype(int) + + def int_array_ltwh(self) -> np.ndarray: + """Converts the box into an int np.ndarray of shape (4,): (left, top, width, height). + + Returns: + an int np.ndarray of shape (4,) representing (left, top, width, height) + """ + return self.array_ltwh().astype(int) + + def round(self) -> AlignedBox2d: + """Rounds the float values to int. + + Returns: + a new AlignedBox2d object with rounded values (still float) + """ + return AlignedBox2d( + np.round(self.left), + np.round(self.top), + np.round(self.right), + np.round(self.bottom), + ) + + def clip(self, boundary: AlignedBox2d) -> AlignedBox2d: + """Clips the region by the boundary + + Args: + boundary (AlignedBox2d): boundary of box to be clipped + (boundary.left: minimum left / right value, + boundary.top: minimum top / bottom value, + boundary.right: maximum left / right value, + boundary.bottom: maximum top / bottom value) + Returns: + a new clipped AlignedBox2d object + """ + return AlignedBox2d( + min(max(self.left, boundary.left), boundary.right), + min(max(self.top, boundary.top), boundary.bottom), + min(max(self.right, boundary.left), boundary.right), + min(max(self.bottom, boundary.top), boundary.bottom), + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/AriaDataProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/AriaDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe3bd30a62796ec01fd6b8230ec97adf6503758 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/AriaDataProvider.py @@ -0,0 +1,337 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +from typing import List, Optional + +import numpy as np + +from projectaria_tools.core import data_provider # @manual +from projectaria_tools.core.calibration import ( # @manual + CameraCalibration, + DeviceCalibration, + distort_by_calibration, + FISHEYE624, + get_linear_camera_calibration, + LINEAR, +) +from projectaria_tools.core.mps import ( # @manual + EyeGaze, + get_eyegaze_point_at_depth, + MpsDataPathsProvider, + MpsDataProvider, +) +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.sophus import SE3 # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + + +class AriaDataProvider: + + def __init__( + self, vrs_filepath: str, mps_folder_path: Optional[str] = None + ) -> None: + self._vrs_data_provider = data_provider.create_vrs_data_provider(vrs_filepath) + + # MPS data provider + if mps_folder_path is not None and os.path.exists(mps_folder_path): + mps_data_paths_provider = MpsDataPathsProvider(mps_folder_path) + mps_data_paths = mps_data_paths_provider.get_data_paths() + self._mps_data_provider = MpsDataProvider(mps_data_paths) + print(mps_data_paths) + else: + self._mps_data_provider = None + + def get_image_stream_ids(self) -> List[StreamId]: + # retrieve all streams ids and filter the one that are image based + stream_ids = self._vrs_data_provider.get_all_streams() + image_stream_ids = [ + p + for p in stream_ids + if self._vrs_data_provider.get_label_from_stream_id(p).startswith("camera-") + ] + return image_stream_ids + + def get_sequence_timestamps( + self, + stream_id: StreamId = StreamId("214-1"), + time_domain: TimeDomain = TimeDomain.TIME_CODE, + ) -> List[int]: + """ + Returns the list of "time code" timestamp for the sequence + """ + return self._vrs_data_provider.get_timestamps_ns(stream_id, time_domain) + + def get_image_stream_label(self, stream_id: StreamId) -> str: + return self._vrs_data_provider.get_label_from_stream_id(stream_id) + + def get_image(self, timestamp_ns: int, stream_id: StreamId) -> np.ndarray: + image = self._vrs_data_provider.get_image_data_by_time_ns( + stream_id, + timestamp_ns, + TimeDomain.TIME_CODE, + TimeQueryOptions.CLOSEST, + ) + return image[0].to_numpy_array() + + def get_undistorted_image( + self, timestamp_ns: int, stream_id: StreamId + ) -> np.ndarray: + image = self.get_image(timestamp_ns, stream_id) + + [T_device_camera, native_camera_online_calibration] = ( + self.get_online_camera_calibration( + stream_id, timestamp_ns=timestamp_ns, camera_model=FISHEYE624 + ) + ) + [T_device_camera, pinhole_camera_online_calibration] = ( + self.get_online_camera_calibration( + stream_id, timestamp_ns=timestamp_ns, camera_model=LINEAR + ) + ) + + # Compute the actual undistorted image + undistorted_image = distort_by_calibration( + image, pinhole_camera_online_calibration, native_camera_online_calibration + ) + + return undistorted_image + + def get_device_calibration(self) -> DeviceCalibration: + """ + Return the device calibration (factory calibration of all sensors) + """ + return self._vrs_data_provider.get_device_calibration() + + def get_camera_calibration( + self, + stream_id: StreamId, + camera_model=FISHEYE624, + ) -> tuple[SE3, CameraCalibration]: + """ + Return the camera calibration of the device of the sequence as [Extrinsics, Intrinsics] + Note: + - A corresponding pinhole camera can be requested by using camera_model = LINEAR. + - This is the camera model used to generate the 'get_undistorted_image'. + """ + if not (camera_model is FISHEYE624 or camera_model is LINEAR): + raise ValueError( + "Invalid camera_model type, only FISHEYE624 and LINEAR are supported" + ) + + device_calibration = self.get_device_calibration() + stream_label = self._vrs_data_provider.get_label_from_stream_id(stream_id) + camera_calibration = device_calibration.get_camera_calib(stream_label) + + # If a corresponding pinhole camera is requested, we build one on the fly + if camera_model == LINEAR: + focal_lengths = camera_calibration.get_focal_lengths() + image_size = camera_calibration.get_image_size() + camera_calibration = get_linear_camera_calibration( + image_size[0], image_size[1], focal_lengths[0] + ) + # else return the native FISHEYE624 camera model + + T_device_camera = camera_calibration.get_transform_device_camera() + return [T_device_camera, camera_calibration] + + def get_online_camera_calibration( + self, + stream_id: StreamId, + timestamp_ns: Optional[int], + time_domain: TimeDomain = TimeDomain.TIME_CODE, + camera_model=FISHEYE624, + ) -> tuple[SE3, CameraCalibration]: + """ + Return the camera calibration of the device of the sequence as [Extrinsics, Intrinsics] + Note: + - A corresponding pinhole camera can be requested by using camera_model = LINEAR. + - This is the camera model used to generate the 'get_undistorted_image'. + """ + if not (camera_model is FISHEYE624 or camera_model is LINEAR): + raise ValueError( + "Invalid camera_model type, only FISHEYE624 and LINEAR are supported" + ) + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError( + f"{time_domain} is not supported. Only TIME_CODE is supported" + ) + + device_timestamp_ns = ( + self._vrs_data_provider.convert_from_timecode_to_device_time_ns( + timestamp_ns + ) + ) + online_calibration = self._mps_data_provider.get_online_calibration( + device_timestamp_ns=device_timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + ) + camera_calibs = online_calibration.camera_calibs + + stream_label = self._vrs_data_provider.get_label_from_stream_id(stream_id) + camera_calib = [c for c in camera_calibs if c.get_label() == stream_label] + if len(camera_calib) == 0: + raise ValueError( + f"camera_calib not found for stream_label: {stream_label} stream_id: {stream_id} at timestamp_ns: {timestamp_ns}" + ) + camera_calibration = camera_calib[0] + + ## Fix the image size to correspond to the image saved in the vrs. + ## The calibration returned by mps_data_provider has hardcoded image sizes which are incorrect. + [_, native_camera_calibration] = self.get_camera_calibration( + stream_id, camera_model=camera_model + ) + camera_calibration = CameraCalibration( + camera_calibration.get_label(), + camera_model, + camera_calibration.projection_params(), + camera_calibration.get_transform_device_camera(), + native_camera_calibration.get_image_size()[0], ## correct the image size + native_camera_calibration.get_image_size()[1], + camera_calibration.get_valid_radius(), + camera_calibration.get_max_solid_angle(), + camera_calibration.get_serial_number(), + ) + # Store the relative transform from device to camera + T_device_camera = camera_calibration.get_transform_device_camera() + + # If a corresponding pinhole camera is requested, we build one on the fly + if camera_model == LINEAR: + focal_lengths = camera_calibration.get_focal_lengths() + image_size = camera_calibration.get_image_size() + camera_calibration = get_linear_camera_calibration( + image_size[0], image_size[1], focal_lengths[0] + ) + # Info: transform_device_camera is set to ID in this path in the camera_calibration + # else return the native FISHEYE624 camera model + + return [T_device_camera, camera_calibration] + + def _timestamp_convert( + self, timestamp: int, time_domain_in: TimeDomain, time_domain_out: TimeDomain + ) -> int: + """ + Returns the converted timestamp between two domains (TimeCode <-> Aria DeviceTime) + """ + if ( + self._vrs_data_provider + and time_domain_in == TimeDomain.TIME_CODE + and time_domain_out == TimeDomain.DEVICE_TIME + ): + # Map to corresponding timestamp + device_timestamp_ns = ( + self._vrs_data_provider.convert_from_timecode_to_device_time_ns( + timestamp + ) + ) + return device_timestamp_ns + return None + + ### + # Add MPS data specifics + ### + + def get_point_cloud(self) -> Optional[np.ndarray]: + """ + Return the point cloud of the scene + """ + if self._mps_data_provider is None: + return None + if self._mps_data_provider.has_semidense_point_cloud(): + point_cloud_data = self._mps_data_provider.get_semidense_point_cloud() + # Point cloud filtering is left to the user + return point_cloud_data + + return None + + def _get_gaze_vector_reprojection( + self, + eye_gaze: EyeGaze, + stream_id_label: str, + device_calibration: DeviceCalibration, + camera_calibration: CameraCalibration, + ) -> np.ndarray: + """ + Helper function to project a eye gaze output onto a given image and its calibration, assuming specified fixed depth + """ + gaze_center_in_cpf = get_eyegaze_point_at_depth( + eye_gaze.yaw, eye_gaze.pitch, depth_m=eye_gaze.depth or 1.0 + ) + transform_device_cpf = device_calibration.get_transform_device_cpf() + transform_device_camera = device_calibration.get_transform_device_sensor( + stream_id_label, True + ) + # We use CAD value (this is the coordinate system used by the Eye Gaze model prediction) + # Using factory calibration (i.e CAD = False) would lead to less accurate EyeGaze reprojection. + transform_camera_cpf = transform_device_camera.inverse() @ transform_device_cpf + gaze_center_in_camera = transform_camera_cpf @ gaze_center_in_cpf + gaze_center_in_pixels = camera_calibration.project(gaze_center_in_camera) + return gaze_center_in_pixels + + def get_eye_gaze_in_camera( + self, + stream_id: StreamId, + timestamp_ns: int, + time_domain: TimeDomain = TimeDomain.TIME_CODE, + camera_model=FISHEYE624, + ): + """ + Return the eye_gaze at the given timestamp projected in the given stream for the given time_domain + """ + if not (camera_model is FISHEYE624 or camera_model is LINEAR): + raise ValueError( + "Invalid camera_model type, only FISHEYE624 and LINEAR are supported" + ) + + eye_gaze = self.get_eye_gaze(timestamp_ns, time_domain) + if eye_gaze: + [T_device_camera, camera_calibration] = self.get_camera_calibration( + stream_id, camera_model + ) + # Compute eye_gaze vector at depth_m and project it in the image + gaze_projection = self._get_gaze_vector_reprojection( + eye_gaze, + self.get_image_stream_label(stream_id), + self.get_device_calibration(), + camera_calibration, + ) + return gaze_projection + return None + + def get_eye_gaze( + self, + timestamp_ns: int, + time_domain: TimeDomain = TimeDomain.TIME_CODE, + ) -> Optional[EyeGaze]: + """ + Return the eye_gaze data at the given timestamp + """ + # Map to corresponding timestamp + if time_domain == TimeDomain.TIME_CODE: + device_timestamp_ns = self._timestamp_convert( + timestamp_ns, TimeDomain.TIME_CODE, TimeDomain.DEVICE_TIME + ) + elif time_domain == TimeDomain.DEVICE_TIME: + device_timestamp_ns = timestamp_ns + else: + raise ValueError("Unsupported time domain") + + if device_timestamp_ns: + if self._mps_data_provider.has_personalized_eyegaze(): + return self._mps_data_provider.get_personalized_eyegaze( + device_timestamp_ns + ) + elif self._mps_data_provider.has_general_eyegaze(): + return self._mps_data_provider.get_general_eyegaze(device_timestamp_ns) + return None diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HamerManoHandDataProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HamerManoHandDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..3aacacc12c74b5fffcd8d8fb29b2bd1aff698468 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HamerManoHandDataProvider.py @@ -0,0 +1,141 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from typing import List, Optional + +import numpy as np +import torch + +from data_loaders.HandDataProviderBase import HandDataProviderBase + +from data_loaders.loader_hand_poses import ( + Handedness, + HandPose, + load_hand_poses, + load_mano_shape_params, + load_hamer_hand_poses +) + +from data_loaders.rotation_compat import matrix_to_axis_angle + +from .hamer_mano_layer import HamerMANOHandModel + + +class HamerMANOHandDataProvider(HandDataProviderBase): + + def __init__( + self, + hand_pose_trajectory_filepath: str, + mano_layer: HamerMANOHandModel, + ) -> None: + + super().__init__() + self._hand_poses = load_hamer_hand_poses(hand_pose_trajectory_filepath) + self._sorted_timestamp_ns_list: List[int] = sorted(self._hand_poses.keys()) + + # Hand profile + self._mano_shape_params = load_mano_shape_params(hand_pose_trajectory_filepath) + if self._mano_shape_params is not None: + self._mano_shape_params = torch.from_numpy( + np.array(self._mano_shape_params) + ) + + self.mano_layer = mano_layer + + @property + def timestamp_ns_list(self) -> List[int]: + return self._sorted_timestamp_ns_list + + def get_hand_mesh_vertices( + self, hand_wrist_data: HandPose + ) -> Optional[torch.Tensor]: + """ + Return the hand mesh corresponding to given HandPose + """ + if ( + hand_wrist_data.wrist_pose is not None + and self._mano_shape_params is not None + and self.mano_layer is not None + ): + hand_wrist_pose_matrix = hand_wrist_data.wrist_pose.to_matrix() + hand_wrist_pose_tensor = torch.from_numpy(hand_wrist_pose_matrix) + + hand_wrist_rotation_axis_angle = matrix_to_axis_angle( + hand_wrist_pose_tensor[:3, :3] + ) + hand_wrist_pose_tensor = torch.cat( + [hand_wrist_rotation_axis_angle, hand_wrist_pose_tensor[:3, 3]] + ) + + mesh_vertices, landmarks = self.mano_layer.forward_kinematics( + self._mano_shape_params, + torch.from_numpy(np.array(hand_wrist_data.joint_angles)), + hand_wrist_pose_tensor, + torch.tensor([hand_wrist_data.handedness == Handedness.Right]), + ) + + return mesh_vertices + return None + + def get_hand_mesh_faces_and_normals( + self, hand_wrist_data: HandPose + ) -> Optional[List[np.ndarray]]: + """ + Return the hand mesh faces and normals + """ + if self.mano_layer is not None: + if hand_wrist_data.handedness == Handedness.Right: + hand_triangles = self.mano_layer.mano_layer_right.faces + else: + hand_triangles = self.mano_layer.mano_layer_left.faces + + vertices = self.get_hand_mesh_vertices(hand_wrist_data) + assert vertices is not None + normals = HandDataProviderBase.get_triangular_mesh_normals( + vertices.float().numpy(), hand_triangles + ) + return [hand_triangles, normals] + else: + return None + + def get_hand_landmarks(self, hand_wrist_data: HandPose) -> Optional[torch.Tensor]: + """ + Return the hand joint landmarks corresponding to given HandPose + See how to map the vertices together to represent a Hand as linked lines using LANDMARK_CONNECTIVITY + """ + if ( + hand_wrist_data.wrist_pose is not None + and self._mano_shape_params is not None + and self.mano_layer is not None + ): + hand_wrist_pose_matrix = hand_wrist_data.wrist_pose.to_matrix() + hand_wrist_pose_tensor = torch.from_numpy(hand_wrist_pose_matrix) + + hand_wrist_rotation_axis_angle = matrix_to_axis_angle( + hand_wrist_pose_tensor[:3, :3] + ) + hand_wrist_pose_tensor = torch.cat( + [hand_wrist_rotation_axis_angle, hand_wrist_pose_tensor[:3, 3]] + ) + + mesh_vertices, hand_landmarks = self.mano_layer.forward_kinematics( + self._mano_shape_params, + torch.from_numpy(np.array(hand_wrist_data.joint_angles)), + hand_wrist_pose_tensor, + torch.tensor([hand_wrist_data.handedness == Handedness.Right]), + ) + + return hand_landmarks, None, None, None, None + + return None diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HandBox2dDataProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HandBox2dDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..2405abccbc98db7a54530d787aa4918d25e4c15a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HandBox2dDataProvider.py @@ -0,0 +1,192 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +import logging +import os +from dataclasses import dataclass +from typing import Any, Dict, List, Optional + +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +from .AlignedBox2d import AlignedBox2d +from .constants import HAND_BOX2D_DATA_CSV_COLUMNS + +from .io_utils import float_or_none, is_float +from .loader_poses_utils import check_csv_columns +from .pose_utils import lookup_timestamp + +logger = logging.getLogger(__name__) +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(filename)s - %(lineno)d - %(levelname)s - %(message)s", +) + + +@dataclass +class HandBox2d: + box2d: AlignedBox2d + visibility_ratio: float + + +@dataclass +class HandBox2dCollection: + timestamp_ns: int + box2ds: Dict[int, HandBox2d] + + +HandBox2dTrajectory = Dict[int, HandBox2dCollection] # trajectory for a single stream +HandBox2dTrajectoryCollection = Dict[ + str, HandBox2dTrajectory +] # trajectories for multiple streams + + +@dataclass +class HandBox2dCollectionWithDt: + box2d_collection: HandBox2dCollection + time_delta_ns: int + + +class HandBox2dProvider: + + def __init__( + self, box2d_trajectory_collection: HandBox2dTrajectoryCollection + ) -> None: + + self._box2d_trajectory_collection = box2d_trajectory_collection + + self._sorted_timestamp_ns_list: Dict[str, List[int]] = {} + for stream_id in self._box2d_trajectory_collection.keys(): + self._sorted_timestamp_ns_list[stream_id] = sorted( + self._box2d_trajectory_collection[stream_id].keys() + ) + + def get_timestamp_ns_list(self, stream_id: StreamId) -> Optional[List[int]]: + return self._sorted_timestamp_ns_list.get(str(stream_id), None) + + @property + def stream_ids(self) -> List[StreamId]: + return [StreamId(x) for x in self._box2d_trajectory_collection.keys()] + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the trajectory + """ + stats = {} + stats["num_frames"] = { + k: sum(v) for k, v in self._sorted_timestamp_ns_list.items() + } + stats["stream_ids"] = [str(x) for x in self.stream_ids] + return stats + + def get_bbox_at_timestamp( + self, + stream_id: StreamId, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + ) -> Optional[HandBox2dCollectionWithDt]: + """ + Return the list of poses at the given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + if stream_id not in self.stream_ids: + raise ValueError(f"Box2d trajectory not available for stream {stream_id}.") + + box2d_collection, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._box2d_trajectory_collection[str(stream_id)], + sorted_timestamp_list=self.get_timestamp_ns_list(stream_id=stream_id), + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if box2d_collection is None or time_delta_ns is None: + return None + else: + return HandBox2dCollectionWithDt( + box2d_collection=box2d_collection, time_delta_ns=time_delta_ns + ) + + +def parse_box2ds_from_csv_reader(csv_reader) -> HandBox2dTrajectoryCollection: + + box2d_trajectory_collection: HandBox2dTrajectoryCollection = {} + + # Read the header row + header = next(csv_reader) + + # Ensure we have the desired columns + check_csv_columns(header, HAND_BOX2D_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in csv_reader: + + stream_id = str(StreamId(row[header.index("stream_id")])) + timestamp_ns = int(row[header.index("timestamp[ns]")]) + hand_index = int(row[header.index("hand_index")]) + visibility_ratio = float_or_none(row[header.index("visibility_ratio[%]")]) + + if is_float(row[header.index("x_min[pixel]")]): + x_min_px = float(row[header.index("x_min[pixel]")]) + x_max_px = float(row[header.index("x_max[pixel]")]) + y_min_px = float(row[header.index("y_min[pixel]")]) + y_max_px = float(row[header.index("y_max[pixel]")]) + + box2d = AlignedBox2d( + left=x_min_px, top=y_min_px, right=x_max_px, bottom=y_max_px + ) + else: + box2d = None + + object_box2d = HandBox2d( + box2d=box2d, + visibility_ratio=visibility_ratio, + ) + + if stream_id not in box2d_trajectory_collection: + box2d_trajectory_collection[stream_id] = {} + + if timestamp_ns not in box2d_trajectory_collection[stream_id]: + box2d_trajectory_collection[stream_id][timestamp_ns] = HandBox2dCollection( + timestamp_ns=timestamp_ns, box2ds={} + ) + + box2d_trajectory_collection[stream_id][timestamp_ns].box2ds[ + hand_index + ] = object_box2d + return box2d_trajectory_collection + + +def load_box2d_trajectory_from_csv(filename: str) -> Optional[HandBox2dProvider]: + """Load Dynamic Objects meta data from a CSV file. + + Keyword arguments: + filename -- the csv file i.e. sequence_folder + "/dynamic_objects.csv" + """ + if not os.path.exists(filename): + logger.warn(f"filename: {filename} does not exist.") + return None + + # Open the CSV file for reading + with open(filename, "r") as f: + csv_reader = csv.reader(f) + box2d_trajectory_collection = parse_box2ds_from_csv_reader( + csv_reader=csv_reader + ) + return HandBox2dProvider( + box2d_trajectory_collection=box2d_trajectory_collection + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HandDataProviderBase.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HandDataProviderBase.py new file mode 100644 index 0000000000000000000000000000000000000000..e9698fe7d8622ae73d26cc7faeefdafd73c47f73 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HandDataProviderBase.py @@ -0,0 +1,162 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from abc import abstractmethod +from dataclasses import dataclass +from typing import Any, Dict, List, Optional + +import numpy as np +import torch + +from data_loaders.loader_hand_poses import Handedness, HandPose, HandPose3dCollection +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual + +from .pose_utils import lookup_timestamp + + +@dataclass +class HandPose3dCollectionWithDt: + pose3d_collection: HandPose3dCollection + time_delta_ns: int + + +class HandDataProviderBase: + + def __init__( + self, + ) -> None: + + self._hand_poses = None + self._sorted_timestamp_ns_list: Optional[List[int]] = None + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the Hand data + """ + assert self._sorted_timestamp_ns_list is not None + assert self._hand_poses is not None + + stats = {} + stats["num_frames"] = len(self._sorted_timestamp_ns_list) + stats["num_right_hands"] = sum( + [ + 1 + for it in self._hand_poses.values() + if Handedness.Right in it.poses.keys() + ] + ) + stats["num_left_hands"] = sum( + [ + 1 + for it in self._hand_poses.values() + if Handedness.Left in it.poses.keys() + ] + ) + return stats + + def get_pose_at_timestamp( + self, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + acceptable_time_delta: Optional[int] = None, + ) -> Optional[HandPose3dCollectionWithDt]: + """ + Return the list of hands available at a given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + hand_pose_collection, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._hand_poses, + sorted_timestamp_list=self._sorted_timestamp_ns_list, + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if ( + hand_pose_collection is None + or time_delta_ns is None + or ( + acceptable_time_delta is not None + and abs(time_delta_ns) > acceptable_time_delta + ) + ): + return None + else: + return HandPose3dCollectionWithDt( + pose3d_collection=hand_pose_collection, time_delta_ns=time_delta_ns + ) + + @abstractmethod + def get_hand_mesh_vertices( + self, hand_wrist_data: HandPose + ) -> Optional[torch.Tensor]: + """ + Return the hand mesh corresponding to given HandPose + """ + + @abstractmethod + def get_hand_mesh_faces_and_normals( + self, hand_wrist_data: HandPose + ) -> Optional[List[np.ndarray]]: + """ + Return the hand mesh faces and normals + """ + + @abstractmethod + def get_hand_landmarks(self, hand_wrist_data: HandPose) -> Optional[torch.Tensor]: + """ + Return the hand joint landmarks corresponding to given HandPose + See how to map the vertices together to represent a Hand as linked lines using LANDMARK_CONNECTIVITY + """ + + @staticmethod + def normalized( + vecs: np.ndarray, axis: int = -1, add_const_to_denom: bool = True + ) -> np.ndarray: + """ + Normalize a set of vectors. + Args: + vecs: np.ndarray of shape (..., V). + axis: axis along which to normalize. + add_const_to_denom: if True, add a small constant to the denominator to prevent numerical issues. + Returns: + np.ndarray of the same shape as vecs. + """ + denom = np.linalg.norm(vecs, axis=axis, keepdims=True) + if add_const_to_denom: + denom += 1e-5 + return vecs / denom + + @staticmethod + def get_triangular_mesh_normals( + vertices: np.ndarray, triangles: np.ndarray + ) -> np.ndarray: + """ + Compute the normals of a triangular mesh. + Args: + vertices: np.ndarray of shape (..., V, 3). + triangles: np.ndarray of shape (..., F, 3). + Returns: + normals: np.ndarray of shape (..., F, 3). + """ + norm = np.zeros_like(vertices) + tris = vertices[triangles] + n = np.cross(tris[::, 1] - tris[::, 0], tris[::, 2] - tris[::, 0]) + n = HandDataProviderBase.normalized(n) + norm[triangles[:, 0]] += n + norm[triangles[:, 1]] += n + norm[triangles[:, 2]] += n + return HandDataProviderBase.normalized(norm) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HeadsetPose3dProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HeadsetPose3dProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..5aef12a0ac3c423e62dad1f21d9709d7e103c285 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/HeadsetPose3dProvider.py @@ -0,0 +1,171 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.sophus import SE3 # @manual + +from .constants import POSE_DATA_CSV_COLUMNS +from .loader_poses_utils import check_csv_columns +from .pose_utils import lookup_timestamp + + +@dataclass +class HeadsetPose3d: + """ + Class to store pose of a headset + """ + + T_world_device: Optional[SE3] = None + + +HeadsetPose3dTrajectory = Dict[int, HeadsetPose3d] + + +@dataclass +class HeadsetPose3dWithDt: + pose3d: HeadsetPose3d + time_delta_ns: int + + +class HeadsetPose3dProvider(object): + def __init__( + self, headset_pose3d_trajectory: HeadsetPose3dTrajectory, headset_uid: str + ): + self._pose3d_trajectory: HeadsetPose3dTrajectory = headset_pose3d_trajectory + self._sorted_timestamp_ns_list: List[int] = sorted( + self._pose3d_trajectory.keys() + ) + self._headset_uid: str = str(headset_uid) + + @property + def timestamp_ns_list(self) -> List[int]: + return self._sorted_timestamp_ns_list + + @property + def headset_uid(self) -> str: + return self._headset_uid + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the trajectory + """ + stats = {} + stats["num_frames"] = len(self._sorted_timestamp_ns_list) + stats["headset_uid"] = str(self._headset_uid) + return stats + + def get_pose_at_timestamp( + self, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + acceptable_time_delta: Optional[int] = None, + ) -> Optional[HeadsetPose3dWithDt]: + """ + Return the list of poses at the given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + headset_pose3d, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._pose3d_trajectory, + sorted_timestamp_list=self._sorted_timestamp_ns_list, + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if ( + headset_pose3d is None + or time_delta_ns is None + or ( + acceptable_time_delta is not None + and abs(time_delta_ns) > acceptable_time_delta + ) + ): + return None + else: + return HeadsetPose3dWithDt( + pose3d=headset_pose3d, time_delta_ns=time_delta_ns + ) + + +def load_headset_pose_trajectory_from_csv(filename: str) -> Tuple[Dict[int, SE3], str]: + """Load Device Poses meta data from a CSV file. + + Keyword arguments: + filename -- the csv file i.e. sequence_folder + "/headset_trajectory.csv" + """ + + pose3d_trajectory: HeadsetPose3dTrajectory = {} + headset_uids = set() + + # Open the CSV file for reading + with open(filename, "r") as f: + reader = csv.reader(f) + + # Read the header row + header = next(reader) + + # Ensure we have the desired columns + check_csv_columns(header, POSE_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in reader: + translation = [ + row[header.index("t_wo_x[m]")], + row[header.index("t_wo_y[m]")], + row[header.index("t_wo_z[m]")], + ] + quaternion_xyz = [ + row[header.index("q_wo_x")], + row[header.index("q_wo_y")], + row[header.index("q_wo_z")], + ] + quaternion_w = row[header.index("q_wo_w")] + timestamp_ns = int(row[header.index("timestamp[ns]")]) + headset_uids.add(str(row[header.index("object_uid")])) + + object_pose = SE3.from_quat_and_translation( + float(quaternion_w), + np.array([float(o) for o in quaternion_xyz]), + np.array([float(o) for o in translation]), + )[0] + + pose3d_trajectory[timestamp_ns] = HeadsetPose3d(T_world_device=object_pose) + + if len(headset_uids) != 1: + raise ValueError( + f"Expected 1 headset pose per timestamp, got {len(headset_uids)}. headset_uids: {headset_uids}" + ) + + return pose3d_trajectory, headset_uids.pop() + + +def load_headset_pose_provider_from_csv(filename: str) -> HeadsetPose3dProvider: + """ + Load pose_provider from csv + """ + + headset_pose3d_trajectory, headset_uid = load_headset_pose_trajectory_from_csv( + filename + ) + return HeadsetPose3dProvider( + headset_pose3d_trajectory=headset_pose3d_trajectory, + headset_uid=headset_uid, + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/ManoHandDataProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/ManoHandDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..25427dba074f9d75468879a9747ae915221958e5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/ManoHandDataProvider.py @@ -0,0 +1,140 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from typing import List, Optional + +import numpy as np +import torch + +from data_loaders.HandDataProviderBase import HandDataProviderBase + +from data_loaders.loader_hand_poses import ( + Handedness, + HandPose, + load_hand_poses, + load_mano_shape_params, +) + +from data_loaders.rotation_compat import matrix_to_axis_angle + +from .mano_layer import MANOHandModel + + +class MANOHandDataProvider(HandDataProviderBase): + + def __init__( + self, + hand_pose_trajectory_filepath: str, + mano_layer: MANOHandModel, + ) -> None: + + super().__init__() + self._hand_poses = load_hand_poses(hand_pose_trajectory_filepath) + self._sorted_timestamp_ns_list: List[int] = sorted(self._hand_poses.keys()) + + # Hand profile + self._mano_shape_params = load_mano_shape_params(hand_pose_trajectory_filepath) + if self._mano_shape_params is not None: + self._mano_shape_params = torch.from_numpy( + np.array(self._mano_shape_params) + ) + + self.mano_layer = mano_layer + + @property + def timestamp_ns_list(self) -> List[int]: + return self._sorted_timestamp_ns_list + + def get_hand_mesh_vertices( + self, hand_wrist_data: HandPose + ) -> Optional[torch.Tensor]: + """ + Return the hand mesh corresponding to given HandPose + """ + if ( + hand_wrist_data.wrist_pose is not None + and self._mano_shape_params is not None + and self.mano_layer is not None + ): + hand_wrist_pose_matrix = hand_wrist_data.wrist_pose.to_matrix() + hand_wrist_pose_tensor = torch.from_numpy(hand_wrist_pose_matrix) + + hand_wrist_rotation_axis_angle = matrix_to_axis_angle( + hand_wrist_pose_tensor[:3, :3] + ) + hand_wrist_pose_tensor = torch.cat( + [hand_wrist_rotation_axis_angle, hand_wrist_pose_tensor[:3, 3]] + ) + + mesh_vertices, landmarks, _, _, _, _ = self.mano_layer.forward_kinematics( + self._mano_shape_params, + torch.from_numpy(np.array(hand_wrist_data.joint_angles)), + hand_wrist_pose_tensor, + torch.tensor([hand_wrist_data.handedness == Handedness.Right]), + ) + + return mesh_vertices + return None + + def get_hand_mesh_faces_and_normals( + self, hand_wrist_data: HandPose + ) -> Optional[List[np.ndarray]]: + """ + Return the hand mesh faces and normals + """ + if self.mano_layer is not None: + if hand_wrist_data.handedness == Handedness.Right: + hand_triangles = self.mano_layer.mano_layer_right.faces + else: + hand_triangles = self.mano_layer.mano_layer_left.faces + + vertices = self.get_hand_mesh_vertices(hand_wrist_data) + assert vertices is not None + normals = HandDataProviderBase.get_triangular_mesh_normals( + vertices.float().numpy(), hand_triangles + ) + return [hand_triangles, normals] + else: + return None + + def get_hand_landmarks(self, hand_wrist_data: HandPose) -> Optional[torch.Tensor]: + """ + Return the hand joint landmarks corresponding to given HandPose + See how to map the vertices together to represent a Hand as linked lines using LANDMARK_CONNECTIVITY + """ + if ( + hand_wrist_data.wrist_pose is not None + and self._mano_shape_params is not None + and self.mano_layer is not None + ): + hand_wrist_pose_matrix = hand_wrist_data.wrist_pose.to_matrix() + hand_wrist_pose_tensor = torch.from_numpy(hand_wrist_pose_matrix) + + hand_wrist_rotation_axis_angle = matrix_to_axis_angle( + hand_wrist_pose_tensor[:3, :3] + ) + hand_wrist_pose_tensor = torch.cat( + [hand_wrist_rotation_axis_angle, hand_wrist_pose_tensor[:3, 3]] + ) + + mesh_vertices, hand_landmarks, out_rot, out_trans, out_pose, out_betas = self.mano_layer.forward_kinematics( + self._mano_shape_params, + torch.from_numpy(np.array(hand_wrist_data.joint_angles)), + hand_wrist_pose_tensor, + torch.tensor([hand_wrist_data.handedness == Handedness.Right]), + ) + + return hand_landmarks, out_rot, out_trans, out_pose, out_betas + + return None diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/ObjectBox2dDataProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/ObjectBox2dDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..c6328dec62733715731533c6674dc89b1827a81c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/ObjectBox2dDataProvider.py @@ -0,0 +1,219 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +import logging +import os +from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Set + +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +from .AlignedBox2d import AlignedBox2d + +from .constants import BOX2D_DATA_CSV_COLUMNS +from .io_utils import float_or_none, is_float +from .loader_poses_utils import check_csv_columns +from .pose_utils import lookup_timestamp + +logger = logging.getLogger(__name__) +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(filename)s - %(lineno)d - %(levelname)s - %(message)s", +) + + +@dataclass +class ObjectBox2d: + box2d: Optional[AlignedBox2d] + visibility_ratio: float + + +@dataclass +class ObjectBox2dCollection: + timestamp_ns: int + box2ds: Dict[str, ObjectBox2d] + + @property + def object_uid_list(self) -> Set[str]: + return set(self.box2ds.keys()) + + +ObjectBox2dTrajectory = Dict[ + int, ObjectBox2dCollection +] # trajectory for a single stream +ObjectBox2dTrajectoryCollection = Dict[ + str, ObjectBox2dTrajectory +] # trajectories for multiple streams + + +@dataclass +class ObjectBox2dCollectionWithDt: + box2d_collection: ObjectBox2dCollection + time_delta_ns: int + + +class ObjectBox2dProvider: + + def __init__( + self, box2d_trajectory_collection: ObjectBox2dTrajectoryCollection + ) -> None: + + self._box2d_trajectory_collection = box2d_trajectory_collection + + self._sorted_timestamp_ns_list: Dict[str, List[int]] = {} + for stream_id in self._box2d_trajectory_collection.keys(): + self._sorted_timestamp_ns_list[stream_id] = sorted( + self._box2d_trajectory_collection[stream_id].keys() + ) + + self._object_uids_with_box2ds: Set = { + x + for box2d_trajectory in self._box2d_trajectory_collection.values() + for v in box2d_trajectory.values() + for x in v.object_uid_list + } + + def get_timestamp_ns_list(self, stream_id: StreamId) -> Optional[List[int]]: + return self._sorted_timestamp_ns_list.get(str(stream_id), None) + + @property + def stream_ids(self) -> List[StreamId]: + return [StreamId(x) for x in self._box2d_trajectory_collection.keys()] + + @property + def object_uids(self) -> Set[str]: + return set(self._object_uids_with_box2ds) + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the trajectory + """ + stats = {} + stats["num_frames"] = { + k: sum(v) for k, v in self._sorted_timestamp_ns_list.items() + } + stats["stream_ids"] = [str(x) for x in self.stream_ids] + stats["num_objects"] = len(self.object_uids) + stats["object_uids"] = [str(x) for x in self.object_uids] + return stats + + def get_box2d_at_timestamp( + self, + stream_id: StreamId, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + acceptable_time_delta: Optional[int] = None, + ) -> Optional[ObjectBox2dCollectionWithDt]: + """ + Return the list of boxes at the given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + if stream_id not in self.stream_ids: + raise ValueError(f"Box2d trajectory not available for stream {stream_id}.") + + box2d_collection, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._box2d_trajectory_collection[str(stream_id)], + sorted_timestamp_list=self.get_timestamp_ns_list(stream_id=stream_id), + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if ( + box2d_collection is None + or time_delta_ns is None + or ( + acceptable_time_delta is not None + and abs(time_delta_ns) > acceptable_time_delta + ) + ): + return None + else: + return ObjectBox2dCollectionWithDt( + box2d_collection=box2d_collection, time_delta_ns=time_delta_ns + ) + + +def parse_box2ds_from_csv_reader(csv_reader) -> ObjectBox2dTrajectoryCollection: + + box2d_trajectory_collection: ObjectBox2dTrajectoryCollection = {} + + # Read the header row + header = next(csv_reader) + + # Ensure we have the desired columns + check_csv_columns(header, BOX2D_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in csv_reader: + + stream_id = str(StreamId(row[header.index("stream_id")])) + timestamp_ns = int(row[header.index("timestamp[ns]")]) + object_uid = str(row[header.index("object_uid")]) + visibility_ratio = float_or_none(row[header.index("visibility_ratio[%]")]) + + if is_float(row[header.index("x_min[pixel]")]): + x_min_px = float(row[header.index("x_min[pixel]")]) + x_max_px = float(row[header.index("x_max[pixel]")]) + y_min_px = float(row[header.index("y_min[pixel]")]) + y_max_px = float(row[header.index("y_max[pixel]")]) + + box2d = AlignedBox2d( + left=x_min_px, top=y_min_px, right=x_max_px, bottom=y_max_px + ) + else: + box2d = None + + object_box2d = ObjectBox2d( + box2d=box2d, + visibility_ratio=visibility_ratio, + ) + + if stream_id not in box2d_trajectory_collection: + box2d_trajectory_collection[stream_id] = {} + + if timestamp_ns not in box2d_trajectory_collection[stream_id]: + box2d_trajectory_collection[stream_id][timestamp_ns] = ( + ObjectBox2dCollection(timestamp_ns=timestamp_ns, box2ds={}) + ) + + box2d_trajectory_collection[stream_id][timestamp_ns].box2ds[ + object_uid + ] = object_box2d + return box2d_trajectory_collection + + +def load_box2d_trajectory_from_csv(filename: str) -> Optional[ObjectBox2dProvider]: + """Load Dynamic Objects meta data from a CSV file. + + Keyword arguments: + filename -- the csv file i.e. sequence_folder + "/dynamic_objects.csv" + """ + if not os.path.exists(filename): + logger.warn(f"filename: {filename} does not exist.") + return None + + # Open the CSV file for reading + with open(filename, "r") as f: + csv_reader = csv.reader(f) + box2d_trajectory_collection = parse_box2ds_from_csv_reader( + csv_reader=csv_reader + ) + return ObjectBox2dProvider( + box2d_trajectory_collection=box2d_trajectory_collection + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/ObjectPose3dProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/ObjectPose3dProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..e0491636eabc661dba5d82456cbfcc1a7ac82279 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/ObjectPose3dProvider.py @@ -0,0 +1,182 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +from dataclasses import dataclass + +from typing import Any, Dict, List, Optional, Set + +import numpy as np +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.sophus import SE3 # @manual + +from .constants import POSE_DATA_CSV_COLUMNS +from .loader_poses_utils import check_csv_columns +from .pose_utils import lookup_timestamp + + +@dataclass +class ObjectPose3d: + """ + Class to store pose of a single entity (object/headset/hand) + """ + + T_world_object: Optional[SE3] = None + + +@dataclass +class ObjectPose3dCollection: + """ + Class to store the poses for a given timestamp + """ + + timestamp_ns: int + poses: Dict[str, ObjectPose3d] + + @property + def object_uid_list(self) -> Set[str]: + return set(self.poses.keys()) + + +ObjectPose3dTrajectory = Dict[int, ObjectPose3dCollection] + + +@dataclass +class ObjectPose3dCollectionWithDt: + pose3d_collection: ObjectPose3dCollection + time_delta_ns: int + + +class ObjectPose3dProvider(object): + def __init__(self, pose3d_trajectory: ObjectPose3dTrajectory): + self._pose3d_trajectory: ObjectPose3dTrajectory = pose3d_trajectory + self._sorted_timestamp_ns_list: List[int] = sorted( + self._pose3d_trajectory.keys() + ) + self._object_uids_with_poses: Set = { + x for v in self._pose3d_trajectory.values() for x in v.object_uid_list + } + + @property + def timestamp_ns_list(self) -> List[int]: + return self._sorted_timestamp_ns_list + + @property + def object_uids_with_poses(self) -> Set[str]: + return set(self._object_uids_with_poses) + + def get_data_statistics(self) -> Dict[str, Any]: + """ + Returns the stats of the trajectory + """ + stats = {} + stats["num_frames"] = len(self._sorted_timestamp_ns_list) + stats["num_objects"] = len(self._object_uids_with_poses) + stats["object_uids"] = [str(x) for x in self._object_uids_with_poses] + return stats + + def get_pose_at_timestamp( + self, + timestamp_ns: int, + time_query_options: TimeQueryOptions, + time_domain: TimeDomain, + acceptable_time_delta: Optional[int] = None, + ) -> Optional[ObjectPose3dCollectionWithDt]: + """ + Return the list of poses available at the given timestamp + """ + if time_domain is not TimeDomain.TIME_CODE: + raise ValueError("Value other than TimeDomain.TIME_CODE not yet supported.") + + pose3d_collection, time_delta_ns = lookup_timestamp( + time_indexed_dict=self._pose3d_trajectory, + sorted_timestamp_list=self._sorted_timestamp_ns_list, + query_timestamp=timestamp_ns, + time_query_options=time_query_options, + ) + + if ( + pose3d_collection is None + or time_delta_ns is None + or ( + acceptable_time_delta is not None + and abs(time_delta_ns) > acceptable_time_delta + ) + ): + return None + else: + return ObjectPose3dCollectionWithDt( + pose3d_collection=pose3d_collection, time_delta_ns=time_delta_ns + ) + + +def load_object_pose_trajectory_from_csv(filename: str) -> ObjectPose3dTrajectory: + """Load Dynamic Objects meta data from a CSV file. + + Keyword arguments: + filename -- the csv file i.e. sequence_folder + "/dynamic_objects.csv" + """ + + pose3d_trajectory: ObjectPose3dTrajectory = {} + # Open the CSV file for reading + with open(filename, "r") as f: + reader = csv.reader(f) + + # Read the header row + header = next(reader) + + # Ensure we have the desired columns + check_csv_columns(header, POSE_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in reader: + translation = [ + row[header.index("t_wo_x[m]")], + row[header.index("t_wo_y[m]")], + row[header.index("t_wo_z[m]")], + ] + quaternion_xyz = [ + row[header.index("q_wo_x")], + row[header.index("q_wo_y")], + row[header.index("q_wo_z")], + ] + quaternion_w = row[header.index("q_wo_w")] + timestamp_ns = int(row[header.index("timestamp[ns]")]) + object_uid = str(row[header.index("object_uid")]) + + T_world_object = SE3.from_quat_and_translation( + float(quaternion_w), + np.array([float(o) for o in quaternion_xyz]), + np.array([float(o) for o in translation]), + )[0] + + pose3d = ObjectPose3d(T_world_object=T_world_object) + + if timestamp_ns not in pose3d_trajectory: + pose3d_trajectory[timestamp_ns] = ObjectPose3dCollection( + timestamp_ns=timestamp_ns, poses={} + ) + + pose3d_trajectory[timestamp_ns].poses[object_uid] = pose3d + + return pose3d_trajectory + + +def load_pose_provider_from_csv(filename: str) -> ObjectPose3dProvider: + """ + Load the ObjectPose3dProvider from a csv file + """ + return ObjectPose3dProvider( + pose3d_trajectory=load_object_pose_trajectory_from_csv(filename) + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/PathProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/PathProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..62106f8b93b17ac9cd1848f6cedf3ef2c5b3d443 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/PathProvider.py @@ -0,0 +1,145 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os + +from .headsets import Headset +from .io_utils import load_json + + +class Hot3dDataPathProvider(object): + @staticmethod + def fromRecordingFolder(recording_instance_folderpath): + + metadata_filepath = os.path.join(recording_instance_folderpath, "metadata.json") + metadata_json = load_json(metadata_filepath) + headset = Headset[metadata_json["headset"]] + + if headset is Headset.Aria: + return AriaDatasetPaths( + recording_instance_folderpath=recording_instance_folderpath + ) + elif headset is Headset.Quest3: + return Quest3DatasetPaths( + recording_instance_folderpath=recording_instance_folderpath + ) + else: + raise NotImplementedError(f"{headset} not supported at the moment.") + + +class Quest3DatasetPaths(object): + def __init__(self, recording_instance_folderpath): + self._recording_instance_folderpath = recording_instance_folderpath + + @property + def recording_instance_folderpath(self): + return self._recording_instance_folderpath + + @property + def dynamic_objects_filepath(self): + return f"{self._recording_instance_folderpath}/dynamic_objects.csv" + + @property + def headset_trajectory_filepath(self): + return f"{self._recording_instance_folderpath}/headset_trajectory.csv" + + @property + def mano_hand_pose_trajectory_filepath(self): + return f"{self._recording_instance_folderpath}/mano_hand_pose_trajectory.jsonl" + + @property + def vrs_filepath(self): + return f"{self._recording_instance_folderpath}/recording.vrs" + + @property + def box2d_objects_filepath(self): + return f"{self._recording_instance_folderpath}/box2d_objects.csv" + + @property + def box2d_hands_filepath(self): + return f"{self._recording_instance_folderpath}/box2d_hands.csv" + + @property + def scene_metadata_filepath(self): + return f"{self._recording_instance_folderpath}/metadata.json" + + @property + def camera_models_filepath(self): + return f"{self._recording_instance_folderpath}/camera_models.json" + + @property + def required_filepaths(self): + return [ + self.vrs_filepath, + self.dynamic_objects_filepath, + self.headset_trajectory_filepath, + self.camera_models_filepath, + self.mano_hand_pose_trajectory_filepath, + ] + + def is_valid(self) -> bool: + return all(os.path.exists(filepath) for filepath in self.required_filepaths) + + +class AriaDatasetPaths(object): + def __init__(self, recording_instance_folderpath): + self._recording_instance_folderpath = recording_instance_folderpath + + @property + def recording_instance_folderpath(self): + return self._recording_instance_folderpath + + @property + def dynamic_objects_filepath(self): + return f"{self._recording_instance_folderpath}/dynamic_objects.csv" + + @property + def headset_trajectory_filepath(self): + return f"{self._recording_instance_folderpath}/headset_trajectory.csv" + + @property + def mano_hand_pose_trajectory_filepath(self): + return f"{self._recording_instance_folderpath}/mano_hand_pose_trajectory.jsonl" + + @property + def vrs_filepath(self): + return f"{self._recording_instance_folderpath}/recording.vrs" + + @property + def box2d_objects_filepath(self): + return f"{self._recording_instance_folderpath}/box2d_objects.csv" + + @property + def box2d_hands_filepath(self): + return f"{self._recording_instance_folderpath}/box2d_hands.csv" + + @property + def mps_folderpath(self): + return f"{self._recording_instance_folderpath}/mps" + + @property + def scene_metadata_filepath(self): + return f"{self._recording_instance_folderpath}/metadata.json" + + @property + def required_filepaths(self): + return [ + self.vrs_filepath, + self.dynamic_objects_filepath, + self.headset_trajectory_filepath, + self.mano_hand_pose_trajectory_filepath, + ] + + def is_valid(self) -> bool: + return all(os.path.exists(filepath) for filepath in self.required_filepaths) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/QuestDataProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/QuestDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..ce51c2b579dd7de478015f75836dec63c1d86b95 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/QuestDataProvider.py @@ -0,0 +1,207 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from typing import List, Optional + +import numpy as np +from data_loaders.io_utils import load_json +from PIL import Image + +from projectaria_tools.core.calibration import ( # @manual + CameraCalibration, + DeviceCadExtrinsics, + DeviceCalibration, + distort_by_calibration, + FISHEYE624, + get_linear_camera_calibration, + LINEAR, +) +from projectaria_tools.core.sophus import SE3 # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +try: + from pyvrs import ImageConversion, SyncVRSReader # @manual +except ImportError: + from pyvrs2 import SyncVRSReader # @manual + from vrsbindings import ImageConversion # @manual + + +class QuestDataProvider: + + def __init__(self, vrs_filepath: str, device_calibration_filepath: str) -> None: + self._vrs_reader = SyncVRSReader(vrs_filepath) + # Configure Image conversion + self._vrs_reader.set_image_conversion(ImageConversion.NORMALIZE) + self._vrs_reader.set_stream_type_image_conversion( + 8010, ImageConversion.NORMALIZE_GREY8 + ) + + # Keep the two last stream ids (the one with largest resolution) + image_stream_ids = [] + for stream_id in self._vrs_reader.stream_ids: + if self._vrs_reader.might_contain_images(stream_id): + image_stream_ids.append(stream_id) + image_stream_ids = sorted(image_stream_ids) + + # Filter the reader + filtered_reader = self._vrs_reader.filtered_by_fields( + stream_ids=image_stream_ids + ) + self._vrs_reader = filtered_reader + + # Loading camera calibration data + device_calibration_json = load_json(device_calibration_filepath) + camera_calibration = {} + for it in device_calibration_json: + quaternion = it["T_Device_Camera"]["quaternion_wxyz"] + translation = it["T_Device_Camera"]["translation_xyz"] + image_height = it["imageHeight"] + image_width = it["imageWidth"] + label = it["label"] + max_solid_angle = 1 # Limiting the fov to a constant value. + # projection_model_type = it["projectionModelType"] + projection_params = it["projectionParams"] + serial_number = it["serialNumber"] + + T_world_device = SE3.from_quat_and_translation( + quaternion[0], + quaternion[1:4], + translation, + ) + # Skip focal_y and rely on a single focal length for x,y + projection_params = projection_params[:1] + projection_params[2:] + + # Build the corresponding camera calibration object + camera_calibration[label] = CameraCalibration( + label, + FISHEYE624, + projection_params, + T_world_device, + image_width, + image_height, + None, + max_solid_angle, + serial_number, + ) + + self._device_calibration = DeviceCalibration( + camera_calibration, {}, {}, {}, {}, DeviceCadExtrinsics(), "", "" + ) + + def get_device_calibration(self) -> DeviceCalibration: + """ + Return the device calibration (factory calibration of all sensors) + """ + return self._device_calibration + + def get_camera_calibration( + self, + stream_id: StreamId, + camera_model=FISHEYE624, + ) -> tuple[SE3, CameraCalibration]: + """ + Return the camera calibration of the device of the sequence as [Extrinsics, Intrinsics] + Note: + - A corresponding pinhole camera can be requested by using camera_model = LINEAR. + - This is the camera model used to generate the 'get_undistorted_image'. + """ + if not (camera_model is FISHEYE624 or camera_model is LINEAR): + raise ValueError( + "Invalid camera_model type, only FISHEYE624 and LINEAR are supported" + ) + + device_calibration = self.get_device_calibration() + # Map the string to the right label + stream_label = self.get_image_stream_label(stream_id) + stream_labels_str = [ + self.get_image_stream_label(x) for x in self.get_image_stream_ids() + ] + idx_stream = stream_labels_str.index(stream_label) + corresponding_calibration_label = device_calibration.get_camera_labels()[ + idx_stream + ] + camera_calibration = device_calibration.get_camera_calib( + corresponding_calibration_label + ) + + # If a corresponding pinhole camera is requested, we build one on the fly + if camera_model == LINEAR: + focal_lengths = camera_calibration.get_focal_lengths() + image_size = camera_calibration.get_image_size() + camera_calibration = get_linear_camera_calibration( + image_size[0], image_size[1], focal_lengths[0] + ) + # else return the native FISHEYE624 camera model + + T_device_camera = camera_calibration.get_transform_device_camera() + return [T_device_camera, camera_calibration] + + def get_image_stream_ids(self) -> List[StreamId]: + # retrieve all streams ids and filter the one that are image based + image_stream_ids = [] + for stream_id in self._vrs_reader.stream_ids: + if self._vrs_reader.might_contain_images(stream_id): + image_stream_ids.append(stream_id) + image_stream_ids = sorted(image_stream_ids) + return [StreamId(x) for x in image_stream_ids] + + def get_sequence_timestamps(self) -> List[int]: + """ + Returns the list of "time code" timestamp for the sequence + """ + timestamps = self._vrs_reader.get_timestamp_list() + # convert timestamp from float to int in ns + return sorted({int(x * 1e9) for x in timestamps}) + + def get_image_stream_label(self, stream_id: StreamId) -> str: + return str(stream_id) + + def get_image(self, timestamp_ns: int, stream_id: StreamId) -> Optional[np.ndarray]: + try: + record = self._vrs_reader.read_record_by_time( + stream_id=self.get_image_stream_label(stream_id), + timestamp=timestamp_ns / 1e9, + ) + except ValueError as e: + print( + f"No record found for timestamp {timestamp_ns} and stream {stream_id}. Caught exception: {e}" + ) + record = None + + if record is not None and record.record_type == "data": + grey8 = Image.fromarray(record.image_blocks[0]) + return np.array(grey8) + else: + print(f"No image found for timestamp {timestamp_ns} and stream {stream_id}") + return None + + def get_undistorted_image( + self, timestamp_ns: int, stream_id: StreamId + ) -> Optional[np.ndarray]: + image = self.get_image(timestamp_ns, stream_id) + if image is None: + return None + + [T_device_camera, native_camera_calibration] = self.get_camera_calibration( + stream_id, camera_model=FISHEYE624 + ) + [T_device_camera, pinhole_camera_calibration] = self.get_camera_calibration( + stream_id, camera_model=LINEAR + ) + + # Compute the actual undistorted image + undistorted_image = distort_by_calibration( + image, pinhole_camera_calibration, native_camera_calibration + ) + return undistorted_image diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/constants.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd7aac8b7a70cd72eb3380b6d5c0c4fab5b8774 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/constants.py @@ -0,0 +1,53 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +POSE_DATA_CSV_COLUMNS = [ + "object_uid", + "timestamp[ns]", + "t_wo_x[m]", + "t_wo_y[m]", + "t_wo_z[m]", + "q_wo_w", + "q_wo_x", + "q_wo_y", + "q_wo_z", +] + +BOX2D_DATA_CSV_COLUMNS = [ + "stream_id", + "object_uid", + "timestamp[ns]", + "x_min[pixel]", + "x_max[pixel]", + "y_min[pixel]", + "y_max[pixel]", + "visibility_ratio[%]", +] + +HAND_BOX2D_DATA_CSV_COLUMNS = [ + "stream_id", + "hand_index", + "timestamp[ns]", + "x_min[pixel]", + "x_max[pixel]", + "y_min[pixel]", + "y_max[pixel]", + "visibility_ratio[%]", +] + +MASK_DATA_CSV_COLUMNS = [ + "timestamp[ns]", + "stream_id", + "mask", +] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/hamer_mano_layer.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/hamer_mano_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..7edddb76be01b280c0dc4b145498f79336f4e34f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/hamer_mano_layer.py @@ -0,0 +1,284 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +from typing import List, Optional + +SMPLX_IMPORT_SUCCEEDED = False # default suppose we can't import SMPLX + +try: + import smplx + + SMPLX_IMPORT_SUCCEEDED = True +except ImportError: + print( + "INFO: HOT3D hands requires smplx (See our GitHub repository for more information on its installation)." + ) + +import torch + +mano_joint_mapping = [ + 16, + 17, + 18, + 19, + 20, + 0, + 14, + 15, + 1, + 2, + 3, + 4, + 5, + 6, + 10, + 11, + 12, + 7, + 8, + 9, +] + + +class HamerMANOHandModel: + N_VERT = 778 + N_LANDMARKS = 21 + MANO_FINGERTIP_VERT_INDICES = { + "thumb": 744, + "index": 320, + "middle": 443, + "ring": 554, + "pinky": 671, + } + + def __init__( + self, + mano_model_files_dir: str, + joint_mapper: Optional[List] = mano_joint_mapping, + ): + mano_left_filename = os.path.join(mano_model_files_dir, "MANO_LEFT.pkl") + mano_right_filename = os.path.join(mano_model_files_dir, "MANO_RIGHT.pkl") + + self.use_pose_pca = False + self.num_shape_params = 10 + self.device = "cpu" + self.dtype = torch.float32 + self.joint_mapper = joint_mapper + + self.mano_layer_left = smplx.create( + mano_left_filename, + "mano", + use_pca=self.use_pose_pca, + is_rhand=False, + flat_hand_mean=True + ) + self.mano_layer_left.to(self.device) + + self.mano_layer_right = smplx.create( + mano_right_filename, + "mano", + use_pca=self.use_pose_pca, + is_rhand=True, + flat_hand_mean=True + ) + self.mano_layer_right.to(self.device) + + # fix MANO shapedirs of the left hand bug (https://github.com/vchoutas/smplx/issues/48) + if ( + torch.sum( + torch.abs( + self.mano_layer_left.shapedirs[:, 0, :] + - self.mano_layer_right.shapedirs[:, 0, :] + ) + ) + < 1 + ): + self.mano_layer_left.shapedirs[:, 0, :] *= -1 + + def forward_kinematics( + self, + shape_params: torch.Tensor, + joint_angles: torch.Tensor, + global_xfrom: torch.Tensor, + is_right_hand: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + assert shape_params.shape[0] == self.num_shape_params + is_batched = len(joint_angles.shape) == 2 + if len(global_xfrom.shape) == 1: + global_xfrom = torch.unsqueeze(global_xfrom, 0) + assert global_xfrom.shape[1] == 6 + if len(joint_angles.shape) == 1: + joint_angles = torch.unsqueeze(joint_angles, 0) + assert is_right_hand.shape[0] == joint_angles.shape[0] + + num_frames = joint_angles.shape[0] + + # Left hand FK + if torch.any(torch.logical_not(is_right_hand)): + left_global_xform = global_xfrom[torch.logical_not(is_right_hand)] + left_joint_angles = joint_angles[torch.logical_not(is_right_hand)] + left_mano_output = self.mano_layer_left( + betas=shape_params[None] + .repeat(left_global_xform.shape[0], 1) + .to(self.dtype), + global_orient=left_global_xform[:, :3].to(self.dtype), + hand_pose=left_joint_angles.to(self.dtype), + transl=left_global_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + ) + + # Right hand FK + if torch.any(is_right_hand): + right_global_xform = global_xfrom[is_right_hand] + right_joint_angles = joint_angles[is_right_hand] + right_mano_output = self.mano_layer_right( + betas=shape_params[None] + .repeat(right_global_xform.shape[0], 1) + .to(self.dtype), + global_orient=right_global_xform[:, :3].to(self.dtype), + hand_pose=right_joint_angles.to(self.dtype), + transl=right_global_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + ) + + # Merge the left and right hand outputs + out_vertices = torch.zeros( + ( + num_frames, + self.N_VERT, + 3, + ) + ).to(self.device) + if torch.any(torch.logical_not(is_right_hand)): + out_vertices[torch.logical_not(is_right_hand)] = left_mano_output.vertices + if torch.sum(is_right_hand) > 0: + out_vertices[is_right_hand] = right_mano_output.vertices + + out_landmarks = torch.zeros( + ( + num_frames, + self.N_LANDMARKS, + 3, + ) + ).to(self.device) + if torch.any(torch.logical_not(is_right_hand)): + if left_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + left_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([left_mano_output.joints, extra_joints], dim=1) + else: + joints = left_mano_output.joints + out_landmarks[torch.logical_not(is_right_hand)] = joints + if torch.sum(is_right_hand) > 0: + if right_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + right_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([right_mano_output.joints, extra_joints], dim=1) + else: + joints = right_mano_output.joints + out_landmarks[is_right_hand] = joints + + assert out_landmarks.shape[1] == self.N_LANDMARKS + + if self.joint_mapper is not None: + out_landmarks = out_landmarks[:, self.joint_mapper] + + if not is_batched: + out_vertices = torch.squeeze(out_vertices, 0) + out_landmarks = torch.squeeze(out_landmarks, 0) + + return out_vertices, out_landmarks + + def shape_only_forward_kinematics( + self, + shape_params: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Method to get the vertices and landmarks of the hand using only the shape + parameters and passing 0s for pose params and global xform. + + Args: + shape_params: N x 6 (N is the number of frames) or 6, + """ + is_batched = len(shape_params.shape) == 2 + if is_batched: + assert shape_params.shape[1] == self.num_shape_params + num_frames = shape_params.shape[0] + else: + assert shape_params.shape[0] == self.num_shape_params + shape_params = shape_params.unsqueeze(0) + num_frames = 1 + + # create zero pose params + pose_params = torch.zeros((num_frames, 15)) + pose_xform = torch.zeros((num_frames, 6)) + + # FK + left_mano_output = self.mano_layer_left( + betas=shape_params.to(self.dtype), + global_orient=pose_xform[:, :3].to(self.dtype), + hand_pose=pose_params.to(self.dtype), + transl=pose_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + ) + + # Merge the left and right hand outputs + out_vertices = left_mano_output.vertices + + if left_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + left_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([left_mano_output.joints, extra_joints], dim=1) + else: + joints = left_mano_output.joints + out_landmarks = joints + + assert out_landmarks.shape[1] == self.N_LANDMARKS + + if self.joint_mapper is not None: + out_landmarks = out_landmarks[:, self.joint_mapper] + + if not is_batched: + out_vertices = torch.squeeze(out_vertices, 0) + out_landmarks = torch.squeeze(out_landmarks, 0) + + return out_vertices, out_landmarks + + +def loadHamerManoHandModel( + mano_model_files_dir: Optional[str], +) -> HamerMANOHandModel: + if not SMPLX_IMPORT_SUCCEEDED or mano_model_files_dir is None: + return None + + return HamerMANOHandModel(mano_model_files_dir) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/hand_common.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/hand_common.py new file mode 100644 index 0000000000000000000000000000000000000000..0051c15cf542e71353fcbac020ccc635f624707c --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/hand_common.py @@ -0,0 +1,169 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from enum import Enum + +# Define a HAND with 21 landmarks + + +class LANDMARK(Enum): + THUMB_FINGERTIP = "Thumb fingertip" + INDEX_FINGER_FINGERTIP = "Index finger fingertip" + MIDDLE_FINGER_FINGERTIP = "Middle finger fingertip" + RING_FINGER_FINGERTIP = "Ring finger fingertip" + PINKY_FINGER_FINGERTIP = "Pinky finger fingertip" + WRIST_JOINT = "Wrist joint" + THUMB_INTERMEDIATE_FRAME = "Thumb intermediate frame" + THUMB_DISTAL_FRAME = "Thumb distal frame" + INDEX_PROXIMAL_FRAME = "Index proximal frame" + INDEX_INTERMEDIATE_FRAME = "Index intermediate frame" + INDEX_DISTAL_FRAME = "Index distal frame" + MIDDLE_PROXIMAL_FRAME = "Middle proximal frame" + MIDDLE_INTERMEDIATE_FRAME = "Middle intermediate frame" + MIDDLE_DISTAL_FRAME = "Middle distal frame" + RING_PROXIMAL_FRAME = "Ring proximal frame" + RING_INTERMEDIATE_FRAME = "Ring intermediate frame" + RING_DISTAL_FRAME = "Ring distal frame" + PINKY_PROXIMAL_FRAME = "Pinky proximal frame" + PINKY_INTERMEDIATE_FRAME = "Pinky intermediate frame" + PINKY_DISTAL_FRAME = "Pinky distal frame" + PALM_CENTER = "Palm center" + + +LANDMARK_INDEX_TO_NAMING = [ + LANDMARK.THUMB_FINGERTIP, + LANDMARK.INDEX_FINGER_FINGERTIP, + LANDMARK.MIDDLE_FINGER_FINGERTIP, + LANDMARK.RING_FINGER_FINGERTIP, + LANDMARK.PINKY_FINGER_FINGERTIP, + LANDMARK.WRIST_JOINT, + LANDMARK.THUMB_INTERMEDIATE_FRAME, + LANDMARK.THUMB_DISTAL_FRAME, + LANDMARK.INDEX_PROXIMAL_FRAME, + LANDMARK.INDEX_INTERMEDIATE_FRAME, + LANDMARK.INDEX_DISTAL_FRAME, + LANDMARK.MIDDLE_PROXIMAL_FRAME, + LANDMARK.MIDDLE_INTERMEDIATE_FRAME, + LANDMARK.MIDDLE_DISTAL_FRAME, + LANDMARK.RING_PROXIMAL_FRAME, + LANDMARK.RING_INTERMEDIATE_FRAME, + LANDMARK.RING_DISTAL_FRAME, + LANDMARK.PINKY_PROXIMAL_FRAME, + LANDMARK.PINKY_INTERMEDIATE_FRAME, + LANDMARK.PINKY_DISTAL_FRAME, + LANDMARK.PALM_CENTER, +] + +LANDMARK_NAMING_TO_INDEX = {k: i for i, k in enumerate(LANDMARK_INDEX_TO_NAMING)} + +LANDMARK_CONNECTIVITY = [ + # pinky + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_FINGER_FINGERTIP], + ], + # ring + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_FINGER_FINGERTIP], + ], + # middle + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_FINGER_FINGERTIP], + ], + # index + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_FINGER_FINGERTIP], + ], + # thumb + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.WRIST_JOINT], + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_INTERMEDIATE_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_DISTAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_DISTAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_FINGERTIP], + ], + # palm + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.THUMB_INTERMEDIATE_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.INDEX_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.MIDDLE_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_PROXIMAL_FRAME], + ], + [ + LANDMARK_NAMING_TO_INDEX[LANDMARK.RING_PROXIMAL_FRAME], + LANDMARK_NAMING_TO_INDEX[LANDMARK.PINKY_PROXIMAL_FRAME], + ], +] diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/headsets.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/headsets.py new file mode 100644 index 0000000000000000000000000000000000000000..abae4d86c59362b8b72eb9a63d23c6a678061dbb --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/headsets.py @@ -0,0 +1,20 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +from enum import auto, Enum + + +class Headset(Enum): + Aria = auto() + Quest3 = auto() diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/io_utils.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/io_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..049ec39b2470981786bbba9c3334923d1f6fb02a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/io_utils.py @@ -0,0 +1,48 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import json +from typing import Any, Optional + + +def load_json(json_filepath): + with open(json_filepath, "r") as fp: + return json.loads(fp.read()) + + +def write_json(payload, json_filepath): + with open(json_filepath, "w") as fp: + json.dump(payload, fp, indent=4, sort_keys=True) + + +def is_float(x: Any) -> bool: + """ + Function checks if the input is convertible to float + """ + if x is None: + return False + if len(x) == 0: + return False + try: + float(x) + return True + except ValueError: + return False + + +def float_or_none(x: Any) -> Optional[float]: + """ + Function returns a float if x is convertible to float, otherwise None + """ + return float(x) if is_float(x) else None diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_hand_poses.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_hand_poses.py new file mode 100644 index 0000000000000000000000000000000000000000..42d50df41166a8391165347c45be01c578af566a --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_hand_poses.py @@ -0,0 +1,201 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import json +from dataclasses import dataclass +from enum import Enum +from typing import Dict, List, Optional + +import numpy as np +from projectaria_tools.core.sophus import SE3 # @manual + +LEFT_HAND_INDEX = 0 +RIGHT_HAND_INDEX = 1 + + +class Handedness(Enum): + Left = int(LEFT_HAND_INDEX) + Right = int(RIGHT_HAND_INDEX) + + +@dataclass +class HandPose: + """Define a Hand pose as wrist_pose (SE3), and joint_angles.""" + + handedness: Handedness + wrist_pose: Optional[SE3] + joint_angles: List[float] + + def is_left_hand(self) -> bool: + return self.handedness == Handedness.Left + + def is_right_hand(self) -> bool: + return self.handedness == Handedness.Right + + def handedness_label(self) -> str: + return "left" if self.is_left_hand() else "right" + + +@dataclass +class HandPose3dCollection: + """ + Class to store the Hand poses for a given timestamp + """ + + timestamp_ns: int + poses: Dict[Handedness, HandPose] + + +TimestampHandPoses3d = Dict[int, HandPose3dCollection] + + +def _get_hand_pose(handedness: str, hand_poses_json: Dict) -> Optional[SE3]: + if handedness in hand_poses_json.keys(): + wrist = hand_poses_json[handedness]["wrist_xform"] + quaternion_w = wrist["q_wxyz"][0] + quaternion_xyz = wrist["q_wxyz"][1:4] + translation = wrist["t_xyz"] + hand_pose = SE3.from_quat_and_translation( + float(quaternion_w), + np.array([float(o) for o in quaternion_xyz]), + np.array([float(o) for o in translation]), + )[0] + return hand_pose + return None + + +def _get_mano_joint_angles( + handedness: str, hand_poses_json: Dict +) -> Optional[List[float]]: + if handedness in hand_poses_json.keys(): + pose_pca = hand_poses_json[handedness]["pose"] + return pose_pca + return None + + +def parse_hand_poses_from_fileobject(fileobject): + hand_poses_per_timestamp: TimestampHandPoses3d = {} + for line in fileobject: + # Parse the JSON file line + hand_pose_instance = json.loads(line) + timestamp_ns = hand_pose_instance["timestamp_ns"] + hand_poses_json = hand_pose_instance["hand_poses"] + + # Read hand pose data + left_hand_pose = _get_hand_pose(str(LEFT_HAND_INDEX), hand_poses_json) + right_hand_pose = _get_hand_pose(str(RIGHT_HAND_INDEX), hand_poses_json) + + left_joint_angles = _get_mano_joint_angles( + str(LEFT_HAND_INDEX), hand_poses_json + ) + right_joint_angles = _get_mano_joint_angles( + str(RIGHT_HAND_INDEX), hand_poses_json + ) + + # If hand pose data is available, add it to the dictionary + if ( + left_hand_pose is not None or right_hand_pose is not None + ) and timestamp_ns not in hand_poses_per_timestamp: + hand_poses_per_timestamp[timestamp_ns] = HandPose3dCollection( + timestamp_ns=timestamp_ns, poses={} + ) + + if left_hand_pose is not None: + hand_poses_per_timestamp[timestamp_ns].poses[Handedness.Left] = HandPose( + Handedness.Left, left_hand_pose, left_joint_angles + ) + + if right_hand_pose is not None: + hand_poses_per_timestamp[timestamp_ns].poses[Handedness.Right] = HandPose( + Handedness.Right, right_hand_pose, right_joint_angles + ) + return hand_poses_per_timestamp + +def parse_hamer_hand_poses_from_fileobject(fileobject): + hand_poses_per_timestamp: TimestampHandPoses3d = {} + for line in fileobject: + # Parse the JSON file line + hand_pose_instance = json.loads(line) + timestamp_ns = hand_pose_instance["timestamp_ns"] + hand_poses_json = hand_pose_instance["hand_poses"] + + # Read hand pose data + left_hand_pose = _get_hand_pose(str(LEFT_HAND_INDEX), hand_poses_json) + right_hand_pose = _get_hand_pose(str(RIGHT_HAND_INDEX), hand_poses_json) + + left_joint_angles = _get_mano_joint_angles( + str(LEFT_HAND_INDEX), hand_poses_json + ) + right_joint_angles = _get_mano_joint_angles( + str(RIGHT_HAND_INDEX), hand_poses_json + ) + + # If hand pose data is available, add it to the dictionary + if ( + left_hand_pose is not None or right_hand_pose is not None + ) and timestamp_ns not in hand_poses_per_timestamp: + hand_poses_per_timestamp[timestamp_ns] = HandPose3dCollection( + timestamp_ns=timestamp_ns, poses={} + ) + + if left_hand_pose is not None: + hand_poses_per_timestamp[timestamp_ns].poses[Handedness.Left] = HandPose( + Handedness.Left, left_hand_pose, left_joint_angles + ) + + if right_hand_pose is not None: + hand_poses_per_timestamp[timestamp_ns].poses[Handedness.Right] = HandPose( + Handedness.Right, right_hand_pose, right_joint_angles + ) + return hand_poses_per_timestamp + + +def load_hand_poses(filename: str) -> TimestampHandPoses3d: + """Load Hand Poses meta data from a JSONL file. + + Keyword arguments: + filename -- the jsonl file i.e. sequence_folder + "/hand_pose_trajectory.jsonl" + """ + with open(filename, "r") as fobj: + hand_poses_per_timestamp = parse_hand_poses_from_fileobject(fobj) + + return hand_poses_per_timestamp + +def load_hamer_hand_poses(filename: str) -> TimestampHandPoses3d: + """Load Hand Poses meta data from a JSONL file. + + Keyword arguments: + filename -- the jsonl file i.e. sequence_folder + "/hand_pose_trajectory.jsonl" + """ + with open(filename, "r") as fobj: + hand_poses_per_timestamp = parse_hamer_hand_poses_from_fileobject(fobj) + + return hand_poses_per_timestamp + + +def load_mano_shape_params(filename: str) -> Optional[List[float]]: + betas = None + with open(filename, "rb") as f: + for line in f: + hand_pose_instance = json.loads(line) + for handedness in ["0", "1"]: + if ( + handedness in hand_pose_instance["hand_poses"].keys() + and "betas" in hand_pose_instance["hand_poses"][handedness] + ): + betas = hand_pose_instance["hand_poses"][handedness]["betas"] + break + if betas is not None: + break + return betas diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_masks.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..356e016338fce9b4744bf281da153d139b8568ce --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_masks.py @@ -0,0 +1,157 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import csv +from collections import Counter +from typing import Dict, List, Optional + +import numpy as np +from projectaria_tools.core.stream_id import StreamId # @manual + +from .constants import MASK_DATA_CSV_COLUMNS +from .loader_poses_utils import check_csv_columns + +TimestampedMask = Dict[int, bool] +StreamMask = Dict[str, TimestampedMask] + + +class MaskData(object): + def __init__(self, mask_data: Optional[StreamMask] = None): + self._mask = mask_data if mask_data is not None else Dict[str, bool] + + @property + def data(self): + return self._mask + + @property + def stream_ids(self): + return [StreamId(x) for x in self._mask.keys()] + + def stream_mask(self, stream_id: StreamId) -> Optional[TimestampedMask]: + return self._mask.get(str(stream_id), None) + + def length(self, stream_id: StreamId) -> int: + if str(stream_id) not in self._mask: + return 0 + return len(self._mask[str(stream_id)]) + + def num_true(self, stream_id: StreamId) -> int: + """Return the number of True values""" + if str(stream_id) not in self._mask: + return 0 + + return Counter(self._mask[str(stream_id)].values()).get(True, 0) + + def num_false(self, stream_id: StreamId) -> int: + """Return the number of False values""" + if str(stream_id) not in self._mask: + return 0 + return Counter(self._mask[str(stream_id)].values()).get(False, 0) + + def stats(self): + return { + sid: { + "length": self.length(sid), + "num_true": self.num_true(sid), + "num_false": self.num_false(sid), + } + for sid in sorted(self._mask.keys()) + } + + +def load_mask_data(mask_filename: str) -> MaskData: + """Load mask data from a HOT3D mask CSV file. + Data saved as CSV with three columns: + # timestamp[ns],stream_id,mask + # 67842008213302,214-1,True + # ... + """ + mask = {} + with open(mask_filename, "r") as f: + reader = csv.reader(f) + + # Read the header row + header = next(reader) + + # Ensure we have the desired columns + check_csv_columns(header, MASK_DATA_CSV_COLUMNS) + + # Read the rest of the rows in the CSV file + for row in reader: + timestamp_int = row[header.index("timestamp[ns]")] + stream_id_str = row[header.index("stream_id")] + value = row[header.index("mask")] + + if stream_id_str not in mask: + mask[stream_id_str] = {} + + mask[stream_id_str][timestamp_int] = bool(value == "True") + + return MaskData(mask) + + +def combine_mask_data( + mask_list: List[MaskData], + operator: str = "and", # i.e 'and' or 'or' +) -> MaskData: + """ + Combine mask data from two or three sources given a logical operator. + """ + + stream_id_strs = {str(y) for x in mask_list for y in x.stream_ids} + stream_ids = [StreamId(x) for x in stream_id_strs] + + out_mask_dict = {} + for stream_id in stream_ids: + timestamped_mask_list = [x.stream_mask(stream_id=stream_id) for x in mask_list] + if any(x is None for x in timestamped_mask_list): + raise ValueError("mask data must be present for all streams") + out_mask_dict[str(stream_id)] = combine_timestamped_mask_data( + mask_list=timestamped_mask_list, operator=operator + ) + return MaskData(out_mask_dict) + + +def combine_timestamped_mask_data( + mask_list: List[TimestampedMask], + operator: str = "and", # i.e 'and' or 'or' +) -> TimestampedMask: + + if len(mask_list) > 0: + if not all(len(d) == len(mask_list[0]) for d in mask_list): + raise ValueError("Mask data must have the same length") + else: + raise ValueError("mask_list must not be empty") + + ## ensure the timestamps are identical across lists + reference_tsns_list = list(mask_list[0].keys()) + for it in mask_list[1:]: + if list(it.keys()) != reference_tsns_list: + raise ValueError("Mask data must have the same timestamps") + + resulting_array = np.array([mask_list[0][tsns] for tsns in reference_tsns_list]) + # resulting_array = np.array(list(mask_list[0].values())) + for it in mask_list[1:]: + if operator == "and": + resulting_array = resulting_array & np.array( + [it[tsns] for tsns in reference_tsns_list] + ) + elif operator == "or": + resulting_array = resulting_array | np.array( + [it[tsns] for tsns in reference_tsns_list] + ) + else: + raise ValueError("Invalid operator") + + return dict(zip(reference_tsns_list, resulting_array.tolist())) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_object_library.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_object_library.py new file mode 100644 index 0000000000000000000000000000000000000000..18c5b6935de8032bbc400277c479cf8420a2ff18 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_object_library.py @@ -0,0 +1,92 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + + +import os +from typing import Any, Dict, Set + +from .io_utils import load_json + + +class ObjectLibrary(object): + def __init__(self, object_library_json: Dict[str, Any], asset_folder: str): + self._object_library_json = object_library_json + ( + self._object_id_to_name_dict, + self._object_name_to_id_dict, + ) = self._get_object_id_name_mappings(object_library_json) + ( + self._headset_id_to_name_dict, + self._headset_name_to_id_dict, + ) = self._get_headset_id_name_mappings(object_library_json) + + self._asset_folder = asset_folder + + @property + def object_id_to_name_dict(self): + return self._object_id_to_name_dict + + @property + def object_name_to_id_dict(self): + return self._object_name_to_id_dict + + @property + def headset_id_to_name_dict(self): + return self._headset_id_to_name_dict + + @property + def headset_name_to_id_dict(self): + return self._headset_name_to_id_dict + + @property + def object_uids(self) -> Set[str]: + return set(self._object_name_to_id_dict.values()) + + @property + def headset_uids(self) -> Set[str]: + return set(self._headset_name_to_id_dict.values()) + + @property + def asset_folder_name(self) -> str: + return self._asset_folder + + def _get_object_id_name_mappings(self, object_info_json): + + object_id_to_name_dict = { + k: v["instance_name"] + for k, v in object_info_json.items() + if v["instance_type"] == "object" and v["motion_type"] == "dynamic" + } + object_name_to_id_dict = {v: k for k, v in object_id_to_name_dict.items()} + return object_id_to_name_dict, object_name_to_id_dict + + def _get_headset_id_name_mappings(self, object_info_json): + headset_id_to_name_dict = { + k: v["instance_name"] + for k, v in object_info_json.items() + if v["instance_type"] == "headset" + } + headset_name_to_id_dict = {v: k for k, v in headset_id_to_name_dict.items()} + return headset_id_to_name_dict, headset_name_to_id_dict + + @staticmethod + def get_cad_asset_path(object_library_folderpath: str, object_id: str) -> str: + return os.path.join(object_library_folderpath, f"{object_id}.glb") + + +def load_object_library(object_library_folderpath: str) -> ObjectLibrary: + instance_filepath = os.path.join(object_library_folderpath, "instance.json") + object_library_json = load_json(instance_filepath) + asset_folder = os.path.join(object_library_folderpath) + return ObjectLibrary(object_library_json, asset_folder) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_poses_utils.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_poses_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..58a266244547f4fd60541a802624b9c340c04356 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/loader_poses_utils.py @@ -0,0 +1,27 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + + +from typing import List + + +def check_csv_columns(csv_columns: List[str], expected_columns: List[str]) -> None: + """Ensure csv_columns is containing all value from expected_columns""" + for column in csv_columns: + if column not in expected_columns: + raise ValueError( + "Invalid Object CSV format. Expected columns are: {}".format( + ", ".join(expected_columns) + ) + ) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/mano_layer.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/mano_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..82e87e141668df5c1e0ea3153bd09840fb8734d5 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/mano_layer.py @@ -0,0 +1,301 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +from typing import List, Optional + +SMPLX_IMPORT_SUCCEEDED = False # default suppose we can't import SMPLX + +try: + import smplx + + SMPLX_IMPORT_SUCCEEDED = True +except ImportError: + print( + "INFO: HOT3D hands requires smplx (See our GitHub repository for more information on its installation)." + ) + +import torch + +mano_joint_mapping = [ + 16, + 17, + 18, + 19, + 20, + 0, + 14, + 15, + 1, + 2, + 3, + 4, + 5, + 6, + 10, + 11, + 12, + 7, + 8, + 9, +] + + +class MANOHandModel: + N_VERT = 778 + N_LANDMARKS = 21 + MANO_FINGERTIP_VERT_INDICES = { + "thumb": 744, + "index": 320, + "middle": 443, + "ring": 554, + "pinky": 671, + } + + def __init__( + self, + mano_model_files_dir: str, + joint_mapper: Optional[List] = mano_joint_mapping, + ): + mano_left_filename = os.path.join(mano_model_files_dir, "MANO_LEFT.pkl") + mano_right_filename = os.path.join(mano_model_files_dir, "MANO_RIGHT.pkl") + + self.use_pose_pca = True + self.num_pose_coeffs = 15 + self.num_shape_params = 10 + self.device = "cpu" + self.dtype = torch.float32 + self.joint_mapper = joint_mapper + + self.mano_layer_left = smplx.create( + mano_left_filename, + "mano", + use_pca=self.use_pose_pca, + is_rhand=False, + num_pca_comps=self.num_pose_coeffs, + ) + self.mano_layer_left.to(self.device) + + self.mano_layer_right = smplx.create( + mano_right_filename, + "mano", + use_pca=self.use_pose_pca, + is_rhand=True, + num_pca_comps=self.num_pose_coeffs, + ) + self.mano_layer_right.to(self.device) + + # fix MANO shapedirs of the left hand bug (https://github.com/vchoutas/smplx/issues/48) + if ( + torch.sum( + torch.abs( + self.mano_layer_left.shapedirs[:, 0, :] + - self.mano_layer_right.shapedirs[:, 0, :] + ) + ) + < 1 + ): + self.mano_layer_left.shapedirs[:, 0, :] *= -1 + + def forward_kinematics( + self, + shape_params: torch.Tensor, + joint_angles: torch.Tensor, + global_xfrom: torch.Tensor, + is_right_hand: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + assert shape_params.shape[0] == self.num_shape_params + is_batched = len(joint_angles.shape) == 2 + if len(global_xfrom.shape) == 1: + global_xfrom = torch.unsqueeze(global_xfrom, 0) + assert global_xfrom.shape[1] == 6 + if len(joint_angles.shape) == 1: + joint_angles = torch.unsqueeze(joint_angles, 0) + if self.use_pose_pca: + assert joint_angles.shape[1] == self.num_pose_coeffs + assert is_right_hand.shape[0] == joint_angles.shape[0] + + num_frames = joint_angles.shape[0] + + # Left hand FK + if torch.any(torch.logical_not(is_right_hand)): + left_global_xform = global_xfrom[torch.logical_not(is_right_hand)] + left_joint_angles = joint_angles[torch.logical_not(is_right_hand)] + left_mano_output = self.mano_layer_left( + betas=shape_params[None] + .repeat(left_global_xform.shape[0], 1) + .to(self.dtype), + global_orient=left_global_xform[:, :3].to(self.dtype), + hand_pose=left_joint_angles.to(self.dtype), + transl=left_global_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + return_full_pose=True, + ) + left_full_pose = left_mano_output.full_pose[0, 3:] + left_full_rot = left_mano_output.full_pose[0, :3] + + # Right hand FK + if torch.any(is_right_hand): + right_global_xform = global_xfrom[is_right_hand] + right_joint_angles = joint_angles[is_right_hand] + right_mano_output = self.mano_layer_right( + betas=shape_params[None] + .repeat(right_global_xform.shape[0], 1) + .to(self.dtype), + global_orient=right_global_xform[:, :3].to(self.dtype), + hand_pose=right_joint_angles.to(self.dtype), + transl=right_global_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + return_full_pose=True, + ) + right_full_pose = right_mano_output.full_pose[0, 3:] + right_full_rot = right_mano_output.full_pose[0, :3] + + # Merge the left and right hand outputs + out_vertices = torch.zeros( + ( + num_frames, + self.N_VERT, + 3, + ) + ).to(self.device) + if torch.any(torch.logical_not(is_right_hand)): + out_vertices[torch.logical_not(is_right_hand)] = left_mano_output.vertices + if torch.sum(is_right_hand) > 0: + out_vertices[is_right_hand] = right_mano_output.vertices + + out_landmarks = torch.zeros( + ( + num_frames, + self.N_LANDMARKS, + 3, + ) + ).to(self.device) + if torch.any(torch.logical_not(is_right_hand)): + out_pose = left_full_pose + out_rot = left_full_rot + out_trans = left_global_xform[:, 3:].to(self.dtype)[0] + out_betas = left_mano_output.betas[0] + if left_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + left_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([left_mano_output.joints, extra_joints], dim=1) + else: + joints = left_mano_output.joints + out_landmarks[torch.logical_not(is_right_hand)] = joints + if torch.sum(is_right_hand) > 0: + out_pose = right_full_pose + out_rot = right_full_rot + out_trans = right_global_xform[:, 3:].to(self.dtype)[0] + out_betas = right_mano_output.betas[0] + if right_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + right_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([right_mano_output.joints, extra_joints], dim=1) + else: + joints = right_mano_output.joints + out_landmarks[is_right_hand] = joints + + assert out_landmarks.shape[1] == self.N_LANDMARKS + + if self.joint_mapper is not None: + out_landmarks = out_landmarks[:, self.joint_mapper] + + if not is_batched: + out_vertices = torch.squeeze(out_vertices, 0) + out_landmarks = torch.squeeze(out_landmarks, 0) + + return out_vertices, out_landmarks, out_rot, out_trans, out_pose, out_betas + + def shape_only_forward_kinematics( + self, + shape_params: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Method to get the vertices and landmarks of the hand using only the shape + parameters and passing 0s for pose params and global xform. + + Args: + shape_params: N x 6 (N is the number of frames) or 6, + """ + is_batched = len(shape_params.shape) == 2 + if is_batched: + assert shape_params.shape[1] == self.num_shape_params + num_frames = shape_params.shape[0] + else: + assert shape_params.shape[0] == self.num_shape_params + shape_params = shape_params.unsqueeze(0) + num_frames = 1 + + # create zero pose params + pose_params = torch.zeros((num_frames, 15)) + pose_xform = torch.zeros((num_frames, 6)) + + # FK + left_mano_output = self.mano_layer_left( + betas=shape_params.to(self.dtype), + global_orient=pose_xform[:, :3].to(self.dtype), + hand_pose=pose_params.to(self.dtype), + transl=pose_xform[:, 3:].to(self.dtype), + return_verts=True, # MANO doesn't return landmarks as well if this is false + ) + + # Merge the left and right hand outputs + out_vertices = left_mano_output.vertices + + if left_mano_output.joints.shape[1] != self.N_LANDMARKS: + extra_joints = torch.index_select( + left_mano_output.vertices, + 1, + torch.tensor( + list(self.MANO_FINGERTIP_VERT_INDICES.values()), + dtype=torch.long, + ), + ) + joints = torch.cat([left_mano_output.joints, extra_joints], dim=1) + else: + joints = left_mano_output.joints + out_landmarks = joints + + assert out_landmarks.shape[1] == self.N_LANDMARKS + + if self.joint_mapper is not None: + out_landmarks = out_landmarks[:, self.joint_mapper] + + if not is_batched: + out_vertices = torch.squeeze(out_vertices, 0) + out_landmarks = torch.squeeze(out_landmarks, 0) + + return out_vertices, out_landmarks + + +def loadManoHandModel( + mano_model_files_dir: Optional[str], +) -> MANOHandModel: + if not SMPLX_IMPORT_SUCCEEDED or mano_model_files_dir is None: + return None + + return MANOHandModel(mano_model_files_dir) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/pose_utils.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/pose_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cb52f869a187e035857da89771a4b456c52639 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/pose_utils.py @@ -0,0 +1,101 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import bisect +from typing import Any, Dict, List, Optional, Tuple + +from projectaria_tools.core.sensor_data import TimeQueryOptions # @manual + + +def query_left_right(ordered_timestamps: List, query_timestamp: int): + """ + Return the left and right timestamp of the query timestamp by using bisection. + Assumption: timestamps are monotonically sorted in the ordered_timestamps List + """ + idx = bisect.bisect_left(ordered_timestamps, query_timestamp) + if idx == 0: + lower_timestamp = None + else: + lower_timestamp = ordered_timestamps[idx - 1] + + if idx == len(ordered_timestamps): + upper_timestamp = None + else: + upper_timestamp = ordered_timestamps[idx] + + if lower_timestamp is not None and upper_timestamp is not None: + alpha = (query_timestamp - lower_timestamp) / ( + upper_timestamp - lower_timestamp + ) + else: + alpha = None + return lower_timestamp, upper_timestamp, alpha + + +def lookup_timestamp( + time_indexed_dict: Dict[int, Any], + sorted_timestamp_list: Optional[List[int]], + query_timestamp: int, + time_query_options: TimeQueryOptions, +) -> Tuple[Any, int]: + """ + Lookup the object corresponding to query_timestamp based on the time_query_options. + time_indexed_dict: a dictionary of timestamp to object + sorted_timestamp_list: a precomputed list of sorted timestamps in time_indexed_dict. If None, it will be computed from time_indexed_dict. + query_timestamp: the timestamp to query + time_query_options: the time query options to use (CLOSEST, BEFORE, AFTER) + """ + + if sorted_timestamp_list is None: + sorted_timestamp_list = sorted(time_indexed_dict.keys()) + + obj = None + time_delta_ns = None + + if query_timestamp in time_indexed_dict: + obj = time_indexed_dict[query_timestamp] + time_delta_ns = 0 + else: + left_frame_tsns, right_frame_tsns, alpha = query_left_right( + ordered_timestamps=sorted_timestamp_list, + query_timestamp=query_timestamp, + ) + if time_query_options == TimeQueryOptions.BEFORE: + if left_frame_tsns is not None: + obj = time_indexed_dict[left_frame_tsns] + time_delta_ns = query_timestamp - left_frame_tsns + + elif time_query_options == TimeQueryOptions.AFTER: + if right_frame_tsns is not None: + obj = time_indexed_dict[right_frame_tsns] + time_delta_ns = query_timestamp - right_frame_tsns + + elif time_query_options == TimeQueryOptions.CLOSEST: + if left_frame_tsns is not None and right_frame_tsns is not None: + if abs(query_timestamp - left_frame_tsns) > abs( + query_timestamp - right_frame_tsns + ): + obj = time_indexed_dict[right_frame_tsns] + time_delta_ns = query_timestamp - right_frame_tsns + else: + obj = time_indexed_dict[left_frame_tsns] + time_delta_ns = query_timestamp - left_frame_tsns + elif left_frame_tsns is not None: + obj = time_indexed_dict[left_frame_tsns] + time_delta_ns = query_timestamp - left_frame_tsns + elif right_frame_tsns is not None: + obj = time_indexed_dict[right_frame_tsns] + time_delta_ns = query_timestamp - right_frame_tsns + + return obj, time_delta_ns diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/rotation_compat.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/rotation_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..80d0adc1690d7209d85971dc746b28952833767f --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/rotation_compat.py @@ -0,0 +1,12 @@ +"""CPU-only rotation conversion for the vendored HOT3D GT provider.""" + +import numpy as np +from scipy.spatial.transform import Rotation +import torch + + +def matrix_to_axis_angle(matrix: torch.Tensor) -> torch.Tensor: + if matrix.shape != (3, 3) or matrix.requires_grad or matrix.device.type != "cpu": + raise ValueError("HOT3D GT wrist rotation must be a detached CPU 3x3 matrix") + value = Rotation.from_matrix(matrix.detach().numpy().astype(np.float64)).as_rotvec() + return torch.as_tensor(np.array(value, copy=True), dtype=matrix.dtype) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_hands.csv b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_hands.csv new file mode 100644 index 0000000000000000000000000000000000000000..564ac4a9eeff0c85d762b3e2b4f7a41e8252ad78 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_hands.csv @@ -0,0 +1,19 @@ +stream_id,hand_index,timestamp[ns],x_min[pixel],x_max[pixel],y_min[pixel],y_max[pixel],visibility_ratio[%] +214-1,0,56773008264542,1135,1382,616,882,1.0 +214-1,1,56773008264542,1147,1383,444,606,1.0 +214-1,0,56823008196882,1047,1237,634,771,1.0 +214-1,1,56823008196882,1103,1271,312,499,1.0 +214-1,0,56873008205866,903,1180,705,868,1.0 +214-1,1,56873008205866,922,1183,389,620,1.0 +1201-1,0,56773008347142,510,578,82,188,1.0 +1201-1,1,56773008347142,525,604,34,81,1.0 +1201-1,0,56823008294232,478,541,82,140,1.0 +1201-1,1,56823008294232,514,564,0,42,1.0 +1201-1,0,56873008299754,421,513,88,164,1.0 +1201-1,1,56873008299754,439,539,0,56,1.0 +1201-2,0,56773008347130,509,586,398,466,1.0 +1201-2,1,56773008347130,508,585,311,392,1.0 +1201-2,0,56823008294220,479,542,396,440,1.0 +1201-2,1,56823008294220,487,533,279,342,1.0 +1201-2,0,56873008299742,422,525,453,479,1.0 +1201-2,1,56873008299742,426,517,329,419,1.0 diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_objects.csv b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_objects.csv new file mode 100644 index 0000000000000000000000000000000000000000..20f1997c2cd4bc791a5096114af147036724e9f0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/aria_sample_recording/box2d_objects.csv @@ -0,0 +1,31 @@ +stream_id,object_uid,timestamp[ns],x_min[pixel],x_max[pixel],y_min[pixel],y_max[pixel],visibility_ratio[%] +214-1,225397651484143,56773008264542,1298,1368,839,1088,0.9550728949717346 +214-1,194930206998778,56773008264542,838,1059,486,726,1.0 +214-1,225397651484143,56823008196882,834,1063,865,913,1.0 +214-1,194930206998778,56823008196882,840,1169,386,719,0.9773508641516446 +214-1,253405647833885,56823008196882,1182,1300,1039,1110,1.0 +214-1,194930206998778,56873008205866,1044,1331,952,1241,1.0 +214-1,96945373046044,56873008205866,896,932,760,791,0.15743519781718962 +214-1,253405647833885,56873008205866,852,984,552,764,0.9002003352549164 +1201-1,225397651484143,56773008347142,519,567,183,273,1.0 +1201-1,194930206998778,56773008347142,403,491,5,97,1.0 +1201-1,96945373046044,56773008347142,564,594,253,289,1.0 +1201-1,253405647833885,56773008347142,590,626,282,325,1.0 +1201-1,225397651484143,56823008294232,389,468,144,169,1.0 +1201-1,194930206998778,56823008294232,405,532,0,99,0.9799943909507338 +1201-1,253405647833885,56823008294232,486,525,230,259,1.0 +1201-1,225397651484143,56873008299754,585,626,297,368,1.0 +1201-1,194930206998778,56873008299754,443,537,197,297,1.0 +1201-1,96945373046044,56873008299754,418,432,104,122,0.20871143375680581 +1201-1,253405647833885,56873008299754,401,463,20,108,0.97145822522055 +1201-2,225397651484143,56773008347130,580,586,417,433,0.6715328467153284 +1201-2,194930206998778,56773008347130,393,477,338,430,1.0 +1201-2,228358276546933,56773008347130,535,577,10,56,1.0 +1201-2,261746112525368,56773008347130,511,540,17,58,1.0 +1201-2,225397651484143,56823008294220,458,486,474,479,1.0 +1201-2,194930206998778,56823008294220,392,514,313,437,0.981008459114281 +1201-2,261746112525368,56823008294220,594,606,57,76,1.0 +1201-2,96945373046044,56823008294220,410,436,309,330,0.2748735244519393 +1201-2,194930206998778,56873008299742,536,550,476,479,1.0 +1201-2,228358276546933,56873008299742,441,480,102,142,1.0 +1201-2,253405647833885,56873008299742,401,450,401,479,0.967680608365019 diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/test_AriaDataProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/test_AriaDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..895820b205a3f1a34207f0bde5d900b2a6d056a0 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/test_AriaDataProvider.py @@ -0,0 +1,85 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +import unittest + +from data_loaders.AriaDataProvider import AriaDataProvider +from projectaria_tools.core.calibration import FISHEYE624, LINEAR +from projectaria_tools.core.stream_id import StreamId + +aria_vrs_resource = "aria_sample_recording/sequence.vrs" + +try: + from libfb.py import parutil + + vrs_file_filepath = parutil.get_file_path( + "test_data/" + aria_vrs_resource, pkg=__package__ + ) +except ImportError: + from pathlib import Path + + THIS_DIR = Path(__file__) + vrs_file_filepath = str(THIS_DIR.parent / aria_vrs_resource) + + +class TestAriaDataProvider(unittest.TestCase): + def setUp(self) -> None: + super().setUp() + + def test_provider_aria_recording(self) -> None: + self.assertTrue(os.path.exists(vrs_file_filepath)) + provider = AriaDataProvider(vrs_file_filepath, "") + + self.assertIsNotNone(provider) + self.assertIsNotNone(provider.get_device_calibration()) + + # Aria VRS files contains 3 Image streams (1 RGB, 2 SLAM) + stream_ids = provider.get_image_stream_ids() + self.assertEqual(len(stream_ids), 3) + self.assertTrue(StreamId("214-1") in stream_ids) + self.assertTrue(StreamId("1201-1") in stream_ids) + self.assertTrue(StreamId("1201-2") in stream_ids) + + timestamps = provider.get_sequence_timestamps() + self.assertTrue(len(timestamps) > 0) + + for stream_id in stream_ids: + img_array = provider.get_image(timestamps[0], stream_id) + self.assertIsNotNone(img_array) + if "rgb" in provider.get_image_stream_label(stream_id): + self.assertEqual(img_array.shape, (1408, 1408, 3)) + elif "slam" in provider.get_image_stream_label(stream_id): + self.assertEqual(img_array.shape, (480, 640)) + + undistorted_img_array = provider.get_image(timestamps[0], stream_id) + self.assertIsNotNone(undistorted_img_array) + + # Retrieve camera calibration + self.assertIsNotNone(provider.get_camera_calibration(stream_id)) + self.assertIsNotNone(provider.get_camera_calibration(stream_id, FISHEYE624)) + self.assertIsNotNone(provider.get_camera_calibration(stream_id, LINEAR)) + + # Assert we have the right camera type + self.assertEqual( + provider.get_camera_calibration(stream_id)[1].model_name(), + FISHEYE624, + ) + self.assertEqual( + provider.get_camera_calibration(stream_id, LINEAR)[1].model_name(), + LINEAR, + ) + + # MPS resources are empty since not initialized + self.assertIsNone(provider.get_point_cloud()) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/test_HandBox2dDataProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/test_HandBox2dDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..67107335d5687870e6e7cd011dbeecd67d8d76ac --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/test_HandBox2dDataProvider.py @@ -0,0 +1,67 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +import unittest + +from data_loaders.HandBox2dDataProvider import load_box2d_trajectory_from_csv +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +box2d_hands_resource = "aria_sample_recording/box2d_hands.csv" + +try: + from libfb.py import parutil + + box2d_hands_filepath = parutil.get_file_path( + "test_data/" + box2d_hands_resource, pkg=__package__ + ) +except ImportError: + from pathlib import Path + + THIS_DIR = Path(__file__) + box2d_hands_filepath = str(THIS_DIR.parent / box2d_hands_resource) + + +class TestHandBox2dDataProvider(unittest.TestCase): + def setUp(self) -> None: + super().setUp() + + def test_provider_aria_recording(self) -> None: + self.assertTrue(os.path.exists(box2d_hands_filepath)) + provider = load_box2d_trajectory_from_csv(filename=box2d_hands_filepath) + + stream_ids = provider.stream_ids + self.assertEqual(len(stream_ids), 3) + + self.assertTrue(StreamId("214-1") in stream_ids) + self.assertTrue(StreamId("1201-1") in stream_ids) + self.assertTrue(StreamId("1201-2") in stream_ids) + + for stream_id in stream_ids: + timestamp_ns_list = provider.get_timestamp_ns_list(stream_id=stream_id) + self.assertIsNotNone(timestamp_ns_list) + self.assertGreater(len(timestamp_ns_list), 0) + + query_timestamp_ns = timestamp_ns_list[len(timestamp_ns_list) // 2] + + box2d_collection_with_dt = provider.get_bbox_at_timestamp( + stream_id=stream_id, + timestamp_ns=query_timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + ) + + self.assertIsNotNone(box2d_collection_with_dt) + self.assertIsNotNone(box2d_collection_with_dt.box2d_collection) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/test_ObjectBox2dDataProvider.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/test_ObjectBox2dDataProvider.py new file mode 100644 index 0000000000000000000000000000000000000000..1875ba371ad42bea016b4afe8865f34a33653a42 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/data_loaders/tests/test_ObjectBox2dDataProvider.py @@ -0,0 +1,73 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +import unittest + +from data_loaders.ObjectBox2dDataProvider import load_box2d_trajectory_from_csv +from projectaria_tools.core.sensor_data import TimeDomain, TimeQueryOptions # @manual +from projectaria_tools.core.stream_id import StreamId # @manual + +box2d_objects_resource = "aria_sample_recording/box2d_objects.csv" + +try: + from libfb.py import parutil + + box2d_objects_filepath = parutil.get_file_path( + "test_data/" + box2d_objects_resource, pkg=__package__ + ) +except ImportError: + from pathlib import Path + + THIS_DIR = Path(__file__) + box2d_objects_filepath = str(THIS_DIR.parent / box2d_objects_resource) + + +class TestObjectBox2dDataProvider(unittest.TestCase): + def setUp(self) -> None: + super().setUp() + + def test_provider_aria_recording(self) -> None: + self.assertTrue(os.path.exists(box2d_objects_filepath)) + provider = load_box2d_trajectory_from_csv(filename=box2d_objects_filepath) + object_uids = provider.object_uids + self.assertEqual(len(object_uids), 6) + + stream_ids = provider.stream_ids + self.assertEqual(len(stream_ids), 3) + + self.assertTrue(StreamId("214-1") in stream_ids) + self.assertTrue(StreamId("1201-1") in stream_ids) + self.assertTrue(StreamId("1201-2") in stream_ids) + + for stream_id in stream_ids: + timestamp_ns_list = provider.get_timestamp_ns_list(stream_id=stream_id) + self.assertIsNotNone(timestamp_ns_list) + self.assertGreater(len(timestamp_ns_list), 0) + + query_timestamp_ns = timestamp_ns_list[len(timestamp_ns_list) // 2] + + box2d_collection_with_dt = provider.get_box2d_at_timestamp( + stream_id=stream_id, + timestamp_ns=query_timestamp_ns, + time_query_options=TimeQueryOptions.CLOSEST, + time_domain=TimeDomain.TIME_CODE, + ) + + self.assertIsNotNone(box2d_collection_with_dt) + self.assertIsNotNone(box2d_collection_with_dt.box2d_collection) + object_uids_at_query_timestamp = ( + box2d_collection_with_dt.box2d_collection.object_uid_list + ) + self.assertGreater(len(object_uids_at_query_timestamp), 0) diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/dataset_api.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/dataset_api.py new file mode 100644 index 0000000000000000000000000000000000000000..09eb2b03bdf11d3a69d54eeaf4b409cf445b9232 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/dataset_api.py @@ -0,0 +1,236 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import os +from typing import Any, Dict, Optional + +import data_loaders.HandBox2dDataProvider as HandBox2dDataProvider + +import data_loaders.ObjectBox2dDataProvider as ObjectBox2dDataProvider + +from data_loaders.AriaDataProvider import AriaDataProvider + +from data_loaders.HeadsetPose3dProvider import ( + HeadsetPose3dProvider, + load_headset_pose_provider_from_csv, +) + +from data_loaders.headsets import Headset +from data_loaders.io_utils import load_json +from data_loaders.loader_object_library import ObjectLibrary +from data_loaders.mano_layer import MANOHandModel +from data_loaders.ManoHandDataProvider import MANOHandDataProvider +from data_loaders.HamerManoHandDataProvider import HamerMANOHandDataProvider + +from data_loaders.ObjectPose3dProvider import ( + load_pose_provider_from_csv, + ObjectPose3dProvider, +) +from data_loaders.PathProvider import Hot3dDataPathProvider + +from data_loaders.QuestDataProvider import QuestDataProvider + +# 3D assets +# - object_uid + +# 3D transform +# Aria Device to Optitrack + +# Generic idea around the DataProvider is that is allow to initialize the data reading +# and offer a generic interface to retrieve timestamp data by TYPE (Image, Object, Hand, etc.) + + +class Hot3dDataProvider: + """ + High Level interface to retrieve and use data from the hot3d dataset + """ + + def __init__( + self, + sequence_folder: str, + object_library: ObjectLibrary, + mano_hand_model: Optional[MANOHandModel] = None, + fail_on_missing_data: bool = True, + use_slam_hamer: bool = False, + ) -> None: + """ + INIT_DOC_STRING + """ + # Will read all required metadata + # Hands + # Objects + # Device type, ... + self.path_provider = Hot3dDataPathProvider.fromRecordingFolder( + recording_instance_folderpath=sequence_folder + ) + if use_slam_hamer: + self.hamer_mano_hand_pose_trajectory_filepath = self.path_provider.mano_hand_pose_trajectory_filepath.replace("mano_hand_pose_trajectory.jsonl", "slam_hamer.jsonl") + else: + self.hamer_mano_hand_pose_trajectory_filepath = None + + if not self.path_provider.is_valid(): + missing_filepaths = [ + filepath + for filepath in self.path_provider.required_filepaths + if not os.path.exists(filepath) + ] + + if fail_on_missing_data: + raise RuntimeError( + f"Invalid hot3d path. Not all expected data are present. missing_filepaths: {missing_filepaths}" + ) + else: + print( + f"Not all expected data are present. missing_filepaths: {missing_filepaths}" + ) + + self._dynamic_objects_provider = load_pose_provider_from_csv( + self.path_provider.dynamic_objects_filepath + ) + + self._device_pose_provider = load_headset_pose_provider_from_csv( + self.path_provider.headset_trajectory_filepath + ) + + self._object_box2d_provider = ( + ObjectBox2dDataProvider.load_box2d_trajectory_from_csv( + self.path_provider.box2d_objects_filepath + ) + ) + + self._hand_box2d_provider = ( + HandBox2dDataProvider.load_box2d_trajectory_from_csv( + self.path_provider.box2d_hands_filepath + ) + ) + + self._object_library: ObjectLibrary = object_library + + self._mano_hand_data_provider = None + if os.path.isfile(self.path_provider.mano_hand_pose_trajectory_filepath): + if mano_hand_model is not None: + if self.hamer_mano_hand_pose_trajectory_filepath: + self._mano_hand_data_provider = HamerMANOHandDataProvider( + self.hamer_mano_hand_pose_trajectory_filepath, + mano_hand_model, + ) + else: + self._mano_hand_data_provider = MANOHandDataProvider( + self.path_provider.mano_hand_pose_trajectory_filepath, + mano_hand_model, + ) + else: + print("No MANO hand model provided, skipping MANO hand data provider") + else: + print( + f"WARN: Cannot find {self.path_provider.mano_hand_pose_trajectory_filepath}" + ) + + if self.get_device_type() == Headset.Aria: + self._device_data_provider = AriaDataProvider( + self.path_provider.vrs_filepath, + self.path_provider.mps_folderpath, + ) + elif self.get_device_type() == Headset.Quest3: + self._device_data_provider = QuestDataProvider( + self.path_provider.vrs_filepath, + self.path_provider.camera_models_filepath, + ) + else: + raise RuntimeError(f"Unsupported device type {self.get_device_type()}") + + def get_data_statistics(self) -> Dict[str, Any]: + statistics_dict = {} + statistics_dict["dynamic_objects"] = ( + self._dynamic_objects_provider.get_data_statistics() + ) + + if self._mano_hand_data_provider is not None: + statistics_dict["mano_hand_poses"] = ( + self._mano_hand_data_provider.get_data_statistics() + ) + + if self._object_box2d_provider is not None: + statistics_dict["object_box2ds"] = ( + self.object_box2d_data_provider.get_data_statistics() + ) + + if self._hand_box2d_provider is not None: + statistics_dict["hand_box2ds"] = ( + self.hand_box2d_data_provider.get_data_statistics() + ) + return statistics_dict + + @property + def object_library(self) -> ObjectLibrary: + """ + Return the object library used for initializing the Hot3dDataProvider + """ + return self._object_library + + @property + def device_data_provider(self): + """ + Return the device data provider (calibration and image stream data) + """ + return self._device_data_provider + + @property + def mano_hand_data_provider(self) -> Optional[MANOHandDataProvider]: + """ + Return the Mano hand data provider + """ + return self._mano_hand_data_provider + + @property + def object_box2d_data_provider(self): + """ + Return the object box2d data provider + """ + return self._object_box2d_provider + + @property + def hand_box2d_data_provider(self): + """ + Return the hand box2d data provider + """ + return self._hand_box2d_provider + + @property + def object_pose_data_provider(self) -> Optional[ObjectPose3dProvider]: + """ + Return the object pose provider + """ + return self._dynamic_objects_provider + + @property + def device_pose_data_provider(self) -> Optional[HeadsetPose3dProvider]: + """ + Return the device pose provider + """ + return self._device_pose_provider + + def get_device_type(self) -> Headset: + """ + Return the type of device used for recording (e.g. Quest3, Aria, etc.) + """ + return Headset[self.get_sequence_metadata()["headset"]] + + def get_sequence_metadata(self) -> Dict: + """ + Return the metadata associated with the sequence + """ + metadata_json = load_json(self.path_provider.scene_metadata_filepath) + + return metadata_json diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/export_gt.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/export_gt.py new file mode 100644 index 0000000000000000000000000000000000000000..aec9abc30f1f1fc9a749aebd1c2f4bfd3ff2fc1b --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/export_gt.py @@ -0,0 +1,25 @@ +import pickle +from viewer_export_gt import export_gt +import json +# import concurrent.futures + + +def load_set(set_file='train_set.pkl'): + try: + with open(set_file, 'rb') as f: + set = pickle.load(f) + return set + except FileNotFoundError: + return f"Error: The file {set_file} does not exist." + +if __name__ == "__main__": + + set = ['P0001_a68492d5', 'P0001_9b6feab7', 'P0014_8254f925', 'P0011_76ea6d47', 'P0014_84ea2dcc', 'P0001_8d136980', 'P0012_476bae57', 'P0012_130a66e1', 'P0014_24cb3bf0', 'P0010_1c9fe708', 'P0002_2ea9af5b', 'P0011_11475e24', 'P0010_0ecbf39f', 'P0010_160e551c', 'P0015_42b8b389', 'P0012_915e71c6', 'P0002_65085bfc', 'P0011_47878e48', 'P0011_cee8fe4f', 'P0002_016222d1', 'P0012_d85e10f6', 'P0012_119de519', 'P0010_41c4c626', 'P0012_f7e3880b', 'P0009_02511c2f', 'P0011_72efb935', 'P0010_924e574e'] + print(set) + cnt = 0 + for video_name in set: + export_gt("dataset/" + video_name, start_frame=20) + cnt += 1 + print(f"finished {cnt}/{len(set)} test videos") + with open('hot3d_dataset_export/val.json', 'w') as f: + json.dump(set, f) \ No newline at end of file diff --git a/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/viewer_export_gt.py b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/viewer_export_gt.py new file mode 100644 index 0000000000000000000000000000000000000000..e0d8e02511953fefdbf90ff522c069ee51ee6e18 --- /dev/null +++ b/home/wuyifan/foundation_hand_clean_gt_dino_20260925/code/third_party/hot3d/viewer_export_gt.py @@ -0,0 +1,293 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# 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. + +import argparse +import os +import shutil +import subprocess +from typing import Optional, Type + +import rerun as rr # @manual +from data_loaders.loader_object_library import load_object_library +from data_loaders.mano_layer import loadManoHandModel +from data_loaders.hamer_mano_layer import loadHamerManoHandModel + +import sys +sys.path.append("..") +import pickle +import numpy as np +from collections import defaultdict +import torch +import joblib + +try: + from dataset_api import Hot3dDataProvider # @manual +except ImportError: + from hot3d.dataset_api import Hot3dDataProvider + +try: + from Hot3DVisualizer import Hot3DVisualizer +except ImportError: + from hot3d.Hot3DVisualizer import Hot3DVisualizer + +from tqdm import tqdm +import cv2 + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--sequence_folder", + type=str, + help="path to hot3d data sequence", + required=True, + ) + parser.add_argument( + "--object_library_folder", + type=str, + help="path to object library folder containing instance.json and *.glb cad files", + required=True, + ) + parser.add_argument( + "--mano_model_folder", + type=str, + default=None, + help="path to MANO models containing the MANO_RIGHT/LEFT.pkl files", + required=False, + ) + + parser.add_argument("--jpeg_quality", type=int, default=75, help=argparse.SUPPRESS) + + # If this path is set, we will save the rerun (.rrd) file to the given path + parser.add_argument( + "--rrd_output_path", type=str, default=None, help=argparse.SUPPRESS + ) + parser.add_argument( + "--use_slam_hamer", action="store_true" + ) + + return parser.parse_args() + + +def execute_rerun( + sequence_folder: str, + object_library_folder: str, + mano_model_folder: Optional[str], + rrd_output_path: Optional[str], + jpeg_quality: int, + timestamps_slice: Type[slice], + fail_on_missing_data: bool, + use_slam_hamer: bool, +): + export_gt_folder = sequence_folder.replace('dataset', 'hot3d_dataset_export') + if not os.path.exists(export_gt_folder): + os.makedirs(export_gt_folder) + # if os.path.exists(os.path.join(export_gt_folder, export_gt_folder.split('/')[-1] + '.mp4')): + # return + + if not os.path.exists(sequence_folder): + raise RuntimeError(f"Sequence folder {sequence_folder} does not exist") + if not os.path.exists(object_library_folder): + raise RuntimeError( + f"Object Library folder {object_library_folder} does not exist" + ) + + object_library = load_object_library( + object_library_folderpath=object_library_folder + ) + + if use_slam_hamer: + mano_hand_model = loadHamerManoHandModel(mano_model_folder) + else: + mano_hand_model = loadManoHandModel(mano_model_folder) + + # + # Initialize hot3d data provider + # + data_provider = Hot3dDataProvider( + sequence_folder=sequence_folder, + object_library=object_library, + mano_hand_model=mano_hand_model, + fail_on_missing_data=fail_on_missing_data, + use_slam_hamer=use_slam_hamer, + ) + print(f"data_provider statistics: {data_provider.get_data_statistics()}") + + # + # Prepare the rerun rerun log configuration + # + # rr.init("hot3d Data Viewer", spawn=(rrd_output_path is None)) + # if rrd_output_path is not None: + # print(f"Saving .rrd file to {rrd_output_path}") + # rr.save(rrd_output_path) + + # + # Initialize the rerun hot3d visualizer interface + # + rr_visualizer = Hot3DVisualizer(data_provider) + + # Define which image stream will be shown + image_stream_ids = data_provider.device_data_provider.get_image_stream_ids() + + # + # Log static assets (aka Timeless assets) + rr_visualizer.log_static_assets(image_stream_ids, disable_vis=True) + + timestamps = data_provider.device_data_provider.get_sequence_timestamps() + # + # Visualize the dataset sequence + # + # Loop over the timestamps of the sequence and visualize corresponding data + image_list = [] + tt_list = [] + ego_extrinsics_list = [] + head_pose_list = [] + data_video = defaultdict(list) + + for timestamp in tqdm(timestamps[timestamps_slice]): + + rr.set_time_nanos("synchronization_time", int(timestamp)) + rr.set_time_sequence("timestamp", timestamp) + + ego_image_cv2, head_pose, ego_extrinsics, ego_focal, data_img = rr_visualizer.log_dynamic_assets(image_stream_ids, timestamp, disable_vis=True) + if head_pose is None: + continue + for key in data_img.keys(): + data_video[key].extend(data_img[key]) + ego_extrinsics_list.append(ego_extrinsics) + head_pose_list.append(head_pose) + image_list.append(ego_image_cv2) + tt_list.append(timestamp) + data_video_all = {} + for key in data_video.keys(): + if torch.is_tensor(data_video[key][0]): + data_video_all[key] = torch.stack(data_video[key]) + save_pth = os.path.join(export_gt_folder, 'anno.pth') + joblib.dump(data_video_all, save_pth) + print("saved", save_pth) + head_pose_list = np.stack(head_pose_list) + ego_extrinsics_list = np.stack(ego_extrinsics_list) + with open(os.path.join(export_gt_folder, 'head_pose.pkl'), 'wb') as file: + pickle.dump(head_pose_list, file) + with open(os.path.join(export_gt_folder, 'ego_extrinsics.pkl'), 'wb') as file: + pickle.dump(ego_extrinsics_list, file) + with open(os.path.join(export_gt_folder, 'focal.txt'), 'w') as file: + file.write(str(ego_focal)) + + with open(os.path.join(export_gt_folder, 'tt_list.pkl'), 'wb') as file: + pickle.dump(tt_list, file) + create_video_from_list_fast(image_list, os.path.join(export_gt_folder, export_gt_folder.split('/')[-1] + '.mp4')) + + +def create_video_from_list_fast(image_list, output_path): + tmp_folder = os.path.join(os.path.dirname(output_path), 'extracted_images') + os.makedirs(tmp_folder, exist_ok=True) + for t, img in enumerate(tqdm(image_list)): + cv2.imwrite(os.path.join(tmp_folder, f"{t:04d}.jpg"), img) + create_video_from_images_ffmpeg(tmp_folder, output_path) + # shutil.rmtree(tmp_folder) + + +def create_video_from_images_ffmpeg(image_folder, output_video, frame_rate=30): + # 确保图片文件夹存在 + if not os.path.isdir(image_folder): + raise ValueError(f"Image folder {image_folder} does not exist.") + + # 构建 FFmpeg 命令 + ffmpeg_command = [ + 'ffmpeg', + '-framerate', str(frame_rate), + '-i', os.path.join(image_folder, '%04d.jpg'), # 假设图片文件名为 0001.png, 0002.png, 0003.png, ... + '-c:v', 'h264_nvenc', + '-preset', 'fast', + '-pix_fmt', 'yuv420p', + output_video + ] + + # 打印 FFmpeg 命令(可选) + print('Running FFmpeg command:', ' '.join(ffmpeg_command)) + + # 调用 FFmpeg 命令 + subprocess.run(ffmpeg_command, check=True) + +def create_video_from_list(image_list, output_path, fps=30): + # Check if the list is not empty + if not image_list: + print("The image list is empty.") + return + + # Get the width and height of the images + height, width, _ = image_list[0].shape + + # Define the codec and create VideoWriter object + fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Codec for mp4 + video_writer = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) + + # Write each frame to the video file + for image in tqdm(image_list): + video_writer.write(image) + + # Release the video writer + video_writer.release() + print(f"Video saved to {output_path}") + +def main(): + args = parse_args() + print(f"args provided: {args}") + + try: + execute_rerun( + sequence_folder=args.sequence_folder, + object_library_folder=args.object_library_folder, + mano_model_folder=args.mano_model_folder, + rrd_output_path=args.rrd_output_path, + jpeg_quality=args.jpeg_quality, + timestamps_slice=slice(None, 300, None), + fail_on_missing_data=False, + use_slam_hamer=args.use_slam_hamer, + ) + except Exception as error: + print(f"An exception occurred: {error}") + +def export_gt(sequence_folder, start_frame=20, debug=False): + print(sequence_folder) + # args = parse_args() + # print(f"args provided: {args}") + from easydict import EasyDict as edict + args = edict() + args.object_library_folder = "dataset/assets" + args.mano_model_folder = "mano_v1_2/models/" + args.rrd_output_path = None + args.jpeg_quality = 75 + args.use_slam_hamer = False + + if debug: + len = 300 + else: + len = None + + execute_rerun( + sequence_folder=sequence_folder, + object_library_folder=args.object_library_folder, + mano_model_folder=args.mano_model_folder, + rrd_output_path=args.rrd_output_path, + jpeg_quality=args.jpeg_quality, + timestamps_slice=slice(start_frame, len, None), + fail_on_missing_data=False, + use_slam_hamer=args.use_slam_hamer, + ) + + +if __name__ == "__main__": + main()